'.join(result)\n html = (f'
').replace('\\n', '')\n dh(html)\n if not warning:\n return True\n\n def _useImage(self, image, kind, key, node):\n asApi = self.asApi\n api = self.api\n F = api.F\n (imageDir, imageName) = os.path.split(image)\n (base, ext) = os.path.splitext(imageName)\n localBase = self.repoTempDir if asApi else self.cwd\n localDir = f'{localBase}/{self.localImageDir}'\n if not os.path.exists(localDir):\n os.makedirs(localDir, exist_ok=True)\n if type(node) is int:\n nType = F.otype.v(node)\n if nType == 'tablet':\n nodeRep = F.catalogId.v(node)\n elif nType in OUTER_QUAD_TYPES:\n nodeRep = self.atfFromOuterQuad(node)\n else:\n nodeRep = str(node)\n else:\n nodeRep = node\n nodeRep = (\n nodeRep.lower()\n .replace('|', 'q')\n .replace('~', '-')\n .replace('@', '(a)')\n .replace('&', '(e)')\n .replace('+', '(p)')\n .replace('.', '(d)')\n )\n keyRep = '' if key == '' else f'-{key}'\n localImageName = f'{kind}-{nodeRep}{keyRep}{ext}'\n localImagePath = f'{localDir}/{localImageName}'\n if (\n not os.path.exists(localImagePath)\n or os.path.getmtime(image) > os.path.getmtime(localImagePath)\n ):\n copyfile(image, localImagePath)\n base = '/local/' if asApi else ''\n return f'{base}{self.localImageDir}/{localImageName}'\n\n def _getImagery(self):\n for (dirFmt, ext, kind, objectType) in (\n (IDEO_TO, LINEART_EXT, 'lineart', 'ideograph'),\n (TABLET_TO, LINEART_EXT, 'lineart', 'tablet'),\n (PHOTO_TO, PHOTO_EXT, 'photo', 'tablet'),\n ):\n srcDir = dirFmt.format(self.imageDir)\n filePaths = glob(f'{srcDir}/*.{ext}')\n images = {}\n idPat = re.compile('P[0-9]+')\n for filePath in filePaths:\n (fileDir, fileName) = os.path.split(filePath)\n (base, thisExt) = os.path.splitext(fileName)\n if kind == 'lineart' and objectType == 'tablet':\n ids = idPat.findall(base)\n if not ids:\n print(f'skipped non-{objectType} \"{fileName}\"')\n continue\n identifier = ids[0]\n key = base.replace('_l', '').replace(identifier, '')\n else:\n identifier = base\n if identifier.startswith('['):\n identifier = '|' + identifier[1:]\n if identifier.endswith(']'):\n identifier = identifier[0:-1] + '|'\n key = ''\n images.setdefault(identifier, {})[key] = filePath\n self._imagery.setdefault(objectType, {})[kind] = images\n print(f'Found {len(images)} {objectType} {kind}s')\n\n\ndef _wrapLink(piece, objectType, kind, identifier, pos='bottom', caption=None):\n title = (\n 'to CDLI main page for this item'\n if kind == 'main' else f'to higher resolution {kind} on CDLI'\n )\n url = URL_FORMAT.get(objectType, {}).get(kind, '').format(identifier)\n\n result = outLink(piece, url, title=title) if url else piece\n if caption:\n result = (\n f'
'\n f'
{result}
'\n f'
{caption}
'\n '
'\n )\n return result\n","sub_path":"tf/extra/cunei.py","file_name":"cunei.py","file_ext":"py","file_size_in_byte":35852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"582066259","text":"def collatz(number):\n if number % 2 == 0:\n print(number // 2)\n return number // 2\n else:\n odd_number = 3 * number + 1\n print(odd_number)\n return odd_number\n\n\ntry:\n user_number = int(input(\"Enter a number: \"))\nexcept:\n print(\"You must a number :(\")\n raise SystemExit\n\ncount = 0\n\nwhile user_number != 1:\n user_number = collatz(user_number)\n count += 1\n\nprint(f\"Process was completed in {count} steps\")\n","sub_path":"Chapter 3/collatzNumber.py","file_name":"collatzNumber.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"631177192","text":"\"\"\"assistant\n\nThis is the Assistant Class file. Update this Assistant Class to meet use case needs.\n\nEach Assistant is responsible to complete the following:\n\n1. Initialize themselves, including checking ability to log into email (receive and send).\n2. Retrieving the oldest email in the Inbox and processing (as follows).\n3. Process SUPPORT requests via the support module (and return status from support module).\n4. Process MANAGE requests if device not locked or beyond in service to date (and return status from manage module).\n5. Process any other request via the Assistant if device not locked, suspended, or beyond in service to date and\n returning status as well.\n\nNote that the Assistant is also responsible for updating the StatusBoard to reflect current state.\n\nSee StatusBoard object to understand the different \"states\" (status) that the device or an Assistant may enter (and be\ndisplayed via the StatusBoard). Not all Assistants use all the \"states\" -- it may depend on what the Assistant does.\n\n\n 2019 09 28 -- MT -- Initial stub.\n\n\"\"\"\nimport logging\nimport time\nimport re\nimport assistant_email.assistant_email as ae\nimport manage.manage as mg\nimport support.support as sr\n\n\nclass Assistant:\n\n def __init__(self, status_board):\n \"\"\"Initialize the Assistant.\n\n :param status_board: (StatusBoard object)\n Enable the Assistant to display status updates if required.\n \"\"\"\n # Log what the Assistant is doing, does, or encounters using the Assistant's module name.\n self._logger_ = logging.getLogger(__name__)\n self._logger_.info(\"Being initialized.\")\n\n # Initialize status and exception information.\n self._assistant_status_ = \"READY\"\n self._assistant_exception_ = None\n\n # Show that Assistant (will soon be) ready.\n self._status_board_ = status_board\n self._status_board_.set_and_show_status(self._assistant_status_)\n\n # Initialize mailboxes.\n self._inbox_ = ae.AssistantEmailInboundImap(\"assistant_email_inbound.txt\")\n self._outbox_ = ae.AssistantEmailOutboundSmtp(\"assistant_email_outbound.txt\")\n\n self._logger_.info(\"Initialization completed.\")\n\n return\n\n @property\n def assistant_status(self):\n return self._assistant_status_\n\n @property\n def assistant_exception(self):\n return self._assistant_exception_\n\n def _set_and_show_email_status_and_pause_(self, new_status=None, pause=60):\n \"\"\"Show current email status and pause (maybe).\n\n :param new_status: (string)\n New status (state) to update to. If None use existing.\n\n :param pause: (integer)\n Number of seconds to pause (unless \"READY\" which has no pause).\n\n :return: (nothing)\n Object may be updated in place with new_status.\n\n \"\"\"\n if new_status and new_status != self._assistant_status_:\n self._assistant_status_ = new_status\n self._status_board_.set_and_show_status(self._assistant_status_)\n\n if new_status != \"READY\":\n time.sleep(pause)\n\n return\n\n def _assistant_work_(self, request):\n \"\"\"Process request for Assistant. This is the main method that should be replaced by actual Assistant child\n class object.\n\n :param request: (request object)\n Request to process.\n\n :return: (string)\n Return status.\n\n \"\"\"\n outbound_email_status = self._outbox_.send_email_reply(request, \"Assistant work -- CLASS STUB.\")\n self._set_and_show_email_status_and_pause_(outbound_email_status)\n\n return outbound_email_status\n\n def process_request(self):\n \"\"\"Main work loop for Assistant. Check email for requests and process based on request type.\n\n This routine reads emails and deletes them from inbox and sends response. This routine also updates the\n Assistant object status (and exception information if applicable). The routine also updates the StatusBoard\n based on the status arising from processing the request.\n\n :return: (nothing)\n Object updated in place with status and any exception information as necessary.\n\n \"\"\"\n # If we haf outbound errors previously, check that we can connect before getting work.\n if self._assistant_status_ == \"EMAIL_OUTBOUND_ERROR\":\n if not self._outbox_.login():\n self._logger_.error(f\"Still unable to connect with outbound mailbox.\")\n return\n else:\n self._outbox_.logout()\n self._set_and_show_email_status_and_pause_(\"READY\", pause=0)\n\n # Get oldest email request in inbox.\n email_ok, request = self._inbox_.get_oldest_inbox_email_request()\n\n # If problem encountered accessing inbox (after successful login) change state and return.\n if not email_ok:\n self._set_and_show_email_status_and_pause_(\"ERROR_EMAIL_INBOUND\")\n return\n\n # If everything ok but no email then log and return (keeping earlier ready state).\n if email_ok and request is None:\n self._logger_.info(\"No requests found in inbound mailbox.\")\n return\n\n # Have a request to process. Indicate we are working.\n self._logger_.info(f\"Request {request.header} received from {request.originator}.\")\n self._assistant_status_ = \"WORKING\"\n self._status_board_.set_and_show_status(self._assistant_status_)\n\n # Get the subject of the email request to determine if SUPPORT or MANAGE request. Remove leading Re: or Fwd:.\n subject = re.sub(\"^((Re:|Fwd:) ?)*\", \"\", request.header).strip()\n\n # Process SUPPORT request if one.\n if subject.startswith(\"SUPPORT:\"):\n support_result_status = sr.process_support_request(request, self._outbox_)\n self._set_and_show_email_status_and_pause_(support_result_status, pause=0)\n return\n\n # If device is locked then MANAGE or work requests not processed.\n if not sr.is_unlocked():\n self._outbox_.send_email_reply(request, \"Device is locked for maintenance. Please resend later.\")\n return\n\n # Process MANAGE request if one (and made it through above).\n if subject.startswith(\"MANAGE:\"):\n manage_result_status = mg.process_manage_request(request, self._outbox_)\n self._set_and_show_email_status_and_pause_(manage_result_status, pause=0)\n return\n\n # If device is no longer in service then work request not processed.\n if not sr.is_in_service():\n self._outbox_.send_email_reply(request, \"Device license expired. Please resend when license renewed.\")\n return\n\n # If Assistant is suspended then work request not processed.\n if mg.is_suspended():\n self._outbox_.send_email_reply(request, \"Assistant is suspended. Please resend later.\")\n return\n\n # If made it to here, have a potential work request. Process it accordingly.\n self._logger_.info(f\"Assistant working on {request.header} from {request.originator}.\")\n work_result_status = self._assistant_work_(request)\n self._logger_.info(f\"Assistant completed working on {request.header} from {request.originator} \"\n f\"with status {work_result_status}\")\n self._set_and_show_email_status_and_pause_(work_result_status)\n\n return\n","sub_path":"assistant/assistant.py","file_name":"assistant.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"290551213","text":"from __future__ import print_function\nimport sys\nimport os\n\nfrom ..launcher import BashLauncher, QsubLauncher\n\n\n_LAUNCHERS = {\n 'bash': BashLauncher,\n 'qsub': QsubLauncher,\n}\n\n\ndef main():\n import argparse\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument('uuid', type=str,\n help='Unique identifier for simulation')\n parser.add_argument('--extra-args', default='',\n help='Extra arguments for wmt-slave command')\n parser.add_argument('--launcher', choices=_LAUNCHERS.keys(),\n default='bash', help='Launch method')\n parser.add_argument('--run', action='store_true',\n help='Launch simulation')\n\n args = parser.parse_args()\n\n launcher = _LAUNCHERS[args.launcher](args.uuid)\n if args.run:\n launcher.run()\n else:\n print(launcher.script())\n\n","sub_path":"wmtexe/cmd/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"569103333","text":"#!/usr/bin/env python\n#-*- coding: UTF-8-*-\n\nimport xlrd\n\nclass ReadExcelFile:\n def __init__(self,filepath = u'D:\\\\sendemail\\\\amazon.xls'):\n try:\n self.filedata = xlrd.open_workbook(filepath)\n return None\n except Exception as e:\n print(str(e))\n return None\n def GetTablebySheetName(self,sheetname = 'sheet1'):\n # 获得表格\n self.table = []\n self.table.append(self.filedata.sheet_by_name(sheetname))\n def FindAllEmailAdress(self,keyword = 'Email'):\n self.list = []\n for signaltable in self.table:\n # 拿到总列数\n ncols = signaltable.ncols\n # 获取“Email” 所在列的值\n for colnum in range(0, ncols):\n colvals = signaltable.col_values(colnum)\n if colvals[0] == keyword:\n print(\"The key word \"+keyword+' Line :',colnum)\n colvals.remove(keyword)\n self.list = self.list + colvals\n break\n return self.list\n\nif __name__ ==\"__main__\":\n ref=ReadExcelFile()\n ref.GetTablebySheetName('amazon top 1000 reviewer-US')\n print(ref.FindAllEmailAdress())\n\n","sub_path":"ReadExcelFile.py","file_name":"ReadExcelFile.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"314462043","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom PIL import Image\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\n\nimages = ('city', 'sky', 'sea')\n\nfeatures = []\nlabels = []\n\nfor j, image in enumerate(images):\n for k in range(1, 21):\n im = Image.open(\"images/\" + image + \"/\" + image + str(k) + \".jpg\")\n arr = list(im.getdata())\n\n pca = PCA(n_components=2, whiten=True).fit(arr)\n rgb_pca = pca.transform(arr)\n\n features.append(rgb_pca.flatten())\n labels.append(image)\n\ntrainFeat = np.array(features)\ntrainLabels = np.array(labels)\n\nfeatures = []\nlabels = []\n\nfor j, image in enumerate(images):\n for k in range(21, 26):\n im = Image.open(\"images/\" + image + \"/\" + image + str(k) + \".jpg\")\n arr = list(im.getdata())\n\n pca = PCA(n_components=2, whiten=True).fit(arr)\n rgb_pca = pca.transform(arr)\n\n features.append(rgb_pca.flatten())\n labels.append(image)\n\ntestFeat = np.array(features)\ntestLabels = np.array(labels)\n\nprint(\"[INFO] evaluating accuracy...\")\nmodel = KNeighborsClassifier(n_neighbors=5)\nmodel.fit(trainFeat, trainLabels)\nacc = model.score(testFeat, testLabels)\npredict = model.predict(trainFeat)\npredict2 = model.predict(testFeat)\n\nprint(predict)\nprint(predict2)\nprint(\"[INFO] test accuracy: {:.3f}%\".format(acc * 100))\n","sub_path":"2018-fall/pattern-recognition/knn-pca.py","file_name":"knn-pca.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"201013030","text":"# Created by Jiayong Lin and Hanyu Wang.\n\nimport collections\nimport re\n\nimport nltk\nimport pandas as pd\nfrom nltk.metrics.distance import edit_distance\nfrom tqdm import tqdm\n\n\ndef train(text, model):\n\t\"\"\"generate or update a word model (dictionary of word:frequency)\"\"\"\n\twords = lambda text : re.findall('[a-z]+', text.lower())\n\tfor word in words(text):\n\t\tmodel[word] += 1\n\treturn model\n\n\nmodel = collections.defaultdict(lambda: 0)\nmodel = train(open('data/words.txt').read(), model)\nreal_words = set(model)\n\n# generate Test Dataset \ndata = pd.DataFrame(columns = [\"Correct\", \"Misspelling\"])\nf = open(\"data/misspelling.txt\", \"r\")\nj = 0\n\nalphabet = set('abcdefghijklmnopqrstuvwxyz')\nfor i in tqdm(f):\n\t# print(j)\n\t# if j > 50:\n\t# \tbreak\n\tj += 1\n\tif i[0] ==\"$\":\n\t\tcorrect = i[1:].lower().strip()\n\telse:\n\t\ti = i.lower().strip()\n\t\tif not (i in real_words) and not (set(i) - alphabet) and not (set(correct) - alphabet) and 0 < edit_distance(correct, i) <= 2:\n\t\t\tdata = data.append({'Correct': correct, 'Misspelling':i},ignore_index=True)\n\ndata.to_csv( path_or_buf = 'data/testdata.txt' ,sep=' ', index=False, header=False )\n","sub_path":"GenerateTestData.py","file_name":"GenerateTestData.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"90104573","text":"import can\nimport socket\nimport struct\nimport serial\nfrom queue import Queue\n\nclass SocketCANConnection:\n # See
for format\n CAN_FRAME_FMT = \"=IB3x8s\"\n CAN_FRAME_SIZE = struct.calcsize(CAN_FRAME_FMT)\n\n\n def __init__(self, interface):\n \"\"\"\n Initiates a CAN connection on the given interface (e.g. 'can0').\n \"\"\"\n # Creates a raw CAN connection and binds it to the given interface.\n self.socket = socket.socket(socket.AF_CAN,\n socket.SOCK_RAW,\n socket.CAN_RAW)\n\n self.socket.bind((interface, ))\n self.socket.settimeout(1.)\n self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)\n\n def send_frame(self, frame):\n data = frame.data.ljust(8, b'\\x00')\n data = struct.pack(self.CAN_FRAME_FMT,\n frame.id,\n len(frame.data),\n data)\n\n self.socket.send(data)\n\n def receive_frame(self):\n try:\n frame, _ = self.socket.recvfrom(self.CAN_FRAME_SIZE)\n except socket.timeout:\n return None\n can_id, can_dlc, data = struct.unpack(self.CAN_FRAME_FMT, frame)\n\n return can.Frame(id=can_id, data=data[:can_dlc])\n\nclass CVRACANDongleConnection:\n \"\"\"\n Implements the CAN API for the CVRA CAN dongle.\n \"\"\"\n def __init__(self, port, baudrate=115200, timeout=None):\n import cvra_can\n self.cvra_can = cvra_can\n from datagrammessages import SerialConnection\n\n self.conn = SerialConnection(port)\n self.conn.set_msg_handler('rx', lambda msg: self.rx_handler(msg))\n self.conn.set_msg_handler('drop', self.drop_handler)\n\n id_filter = [int(self.cvra_can.Frame.ID(0, extended=0)),\n self.cvra_can.Frame.ID.mask(0, extended=1)]\n if not self.conn.service_call('filter', id_filter):\n print('filter configuration error')\n sys.exit(1)\n self.conn.service_call('silent', False)\n self.conn.service_call('loop back', False)\n self.conn.service_call('bit rate', 1000000)\n self.rx_queue = Queue()\n\n def rx_handler(self, msg):\n rec = self.cvra_can.Frame.decode(msg[0])\n if rec.can_id.extended:\n return\n frame = can.Frame(id=rec.can_id.value,\n data=rec.data,\n extended=rec.can_id.extended,\n transmission_request=rec.can_id.remote,\n data_length=len(rec.data))\n self.rx_queue.put(frame)\n\n def drop_handler(self, msg):\n # non fatal error\n # print a warning?\n pass\n\n def send_frame(self, frame):\n ident = self.cvra_can.Frame.ID(value=frame.id,\n extended=frame.extended,\n remote=frame.transmission_request)\n if frame.transmission_request:\n data = frame.data_length * b'0'\n else:\n data = frame.data\n frame = self.cvra_can.Frame(can_id=ident, data=data).encode()\n self.conn.service_call('tx', [frame])\n\n def receive_frame(self):\n try:\n return self.rx_queue.get(True, 1) # block with timeout 1 sec\n except:\n return None\n","sub_path":"client/can/adapters.py","file_name":"adapters.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"567982572","text":"#! /usr/bin/env python3\n\nimport os\nimport os.path\nimport re\nimport shutil\nimport subprocess\n\nprojects = [\n 'FactoryFactory',\n 'FactoryFactory.AspNet.DependencyInjection'\n]\n\nversion = '0.4.0'\nsuffix = 'beta'\nis_release = False\n\n\ndef abspath(path):\n home = os.path.abspath(os.path.dirname(__file__))\n return os.path.normpath(os.path.join(home, path))\n\n\ndef dotnet(*args):\n process = [\"dotnet\"] + list(args)\n subprocess.run(process, check=True)\n\n\nbuild_number = os.environ.get('APPVEYOR_BUILD_NUMBER', '0')\npull_request_number = os.environ.get('APPVEYOR_PULL_REQUEST_NUMBER', False)\n\nif os.environ.get('APPVEYOR_REPO_TAG', False) == 'true':\n is_release = True\n\nversion_number = re.search(r'^\\d+\\.\\d+\\.\\d+', version)\nif version_number:\n version_number = version_number.group()\n file_version = version_number + '.' + build_number\nelse:\n file_version = False\n\nif pull_request_number:\n package_version = version + '-pr' + pull_request_number\nelse:\n package_version = version\n if suffix and suffix != '':\n package_version += '-' + suffix\n\npackage_path = abspath('build')\n\nos.makedirs(abspath('src/.version'), exist_ok=True)\nwith open(abspath('src/.version/version.cs'), 'w') as f:\n f.writelines([\n 'using System.Reflection;\\n'\n '\\n',\n '[assembly:AssemblyInformationalVersion(\"{0}\")]\\n'.format(package_version)\n ])\n if file_version:\n f.writelines([\n '[assembly:AssemblyVersion(\"{0}\")]\\n'.format(file_version),\n '[assembly:AssemblyFileVersion(\"{0}\")]\\n'.format(file_version)\n ])\n\nshutil.rmtree(abspath('build'), ignore_errors=True)\ndotnet('build', abspath('src/FactoryFactory.sln'))\ndotnet('test', abspath('src/FactoryFactory.Tests/FactoryFactory.Tests.csproj'))\n\nfor project in projects:\n dotnet(\n 'pack',\n '-o', package_path,\n '--no-build',\n abspath('src/{0}/{0}.csproj'.format(project))\n )\n\nif is_release:\n key = os.environ.get('NUGET_KEY', False)\n if key:\n for f in os.listdir(package_path):\n artifact = os.path.join(package_path, f)\n if artifact.endswith('.nupkg') and os.path.isfile(artifact):\n dotnet(\n 'nuget', 'push', artifact,\n '-k', key,\n '-s', 'https://api.nuget.org/v3/index.json'\n )\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"245873422","text":"def absolute(num):\n if num < 0:\n return -num\n else:\n return num\n\ndef maximum(listy):\n a = listy[0]\n for number in listy:\n if number > a:\n a = number\n else:\n continue\n return a\n\n","sub_path":"assignment_3_Functions_solved.py","file_name":"assignment_3_Functions_solved.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"617169500","text":"#\r\n# This module imports and creates a celery application. It should be called to create a celery worker\r\n#\r\nfrom ptapp import celery,create_app\r\nfrom ptapp.tasks import updateAllInformation_task\r\nfrom config import Config\r\nfrom celery.schedules import crontab\r\n\r\nconfig = Config()\r\n\r\nschedule = {\r\n 'updateAll': {\r\n 'task': 'ptapp.tasks.updateAllInformation_task',\r\n 'schedule': crontab(minute=\"*/15\")\r\n }\r\n}\r\nconfig.setConfig('beat_schedule', schedule)\r\n# We are creating a flask context as well so that the tasks have access to it?\r\napp = create_app(config)\r\n# https://flask.palletsprojects.com/en/1.0.x/appcontext/\r\napp.app_context().push()\r\n\r\n#Celery beat can't be configured to run a task on startup so we do it here.\r\nupdateAllInformation_task.apply_async(countdown=30)\r\n","sub_path":"oldstuff/celery_worker.py","file_name":"celery_worker.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"608460795","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.models import AbstractUser\n\n\nclass User(AbstractUser):\n profile_photo = models.ImageField()\n\n\nclass Post(models.Model):\n '''Model definition for Post.'''\n\n title = models.CharField(_('Post'), max_length=50)\n content = models.TextField(_('Content'))\n is_publishable = models.BooleanField(_('Is Publishable ?'), default=False)\n created_at = models.DateTimeField(_('Created at '), auto_now_add=True)\n updated_at = models.DateTimeField(_('Updated at '), auto_now=True)\n photo = models.ImageField()\n\n class Meta:\n '''Meta definition for Post.'''\n\n verbose_name = 'Post'\n verbose_name_plural = 'Posts'\n\n def __str__(self):\n '''Unicode representation of Post.'''\n return self.title\n\n\nclass Question(models.Model):\n text = models.CharField(max_length=200)\n active = models.BooleanField(default=True)\n draft = models.BooleanField(default=False)\n timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)\n\n def __str__(self):\n return self.text\n\n\nclass Answer(models.Model):\n question = models.ForeignKey(Question, on_delete=models.CASCADE)\n text = models.CharField(max_length=120)\n active = models.BooleanField(default=True)\n draft = models.BooleanField(default=False)\n timestamp = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return self.text\n\n\nclass Category(models.Model):\n private_name = models.CharField('Private name', max_length=164)\n\n class Meta:\n verbose_name = 'Category'\n verbose_name_plural = 'Categories'\n\n\nclass CategoryI18n(models.Model):\n name = models.CharField('Name i18n', max_length=164)\n language_key = models.CharField('Language', max_length=20)\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Category i18n'\n verbose_name_plural = 'Categories i18n'\n\n\nclass Item(models.Model):\n private_name = models.CharField('Private name', max_length=164)\n price = models.DecimalField('Price', decimal_places=2, max_digits=8)\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Item'\n verbose_name_plural = 'Items'\n\n\nclass ItemI18n(models.Model):\n name = models.CharField('Name i18n', max_length=164)\n language_key = models.CharField('Language', max_length=20)\n item = models.ForeignKey(Item, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name = 'Item i18n'\n verbose_name_plural = 'Items i18n'\n\n# #MenuNavbar\n# class HeadersMenuNavbar(models.Model):\n\n# menu_id = models.CharField(max_length=100)\n# menu = models.CharField(max_length=60)\n# url = models.CharField(max_length=100)\n# show_in_footer = models.BooleanField(default=True)\n\n# def __str__(self):\n# return self.menu_id\n\n# #Type\n# class HeadersSubMenuType(models.Model):\n# sub_menu_type_id = models.CharField(max_length=60)\n# sub_menu_type = models.CharField(max_length=60)\n# sub_menu_type_title = models.CharField(max_length=60, null=True)\n\n# def __str__(self):\n# return \"{}\".format(self.sub_menu_type)\n\n# #MenuDropdown\n# class HeadersSubMenu(models.Model):\n# sub_menu_id = models.CharField(max_length=60)\n# menu = models.ForeignKey(HeadersMenuNavbar, on_delete=models.CASCADE, related_name='sub_menu', null=True, blank=True)\n# item = models.CharField(max_length=60)\n# url = models.CharField(max_length=100)\n# types = models.ForeignKey(HeadersSubMenuType, on_delete=models.CASCADE, null=True)\n# show_in_footer = models.BooleanField(default=True)\n\n\n# def __str__(self):\n# return \"{}\".format(self.menu)\n\n\nclass HeadersMenuNavbar(models.Model):\n \"\"\"for headers menu navbar\"\"\"\n menu_id = models.CharField(max_length=100, unique=True)\n menu = models.CharField(max_length=60)\n url = models.CharField(max_length=100)\n show_in_footer = models.BooleanField(default=True)\n\n def __str__(self):\n return self.menu_id\n\n\nclass HeadersSubMenuType(models.Model):\n \"\"\"for headers sub menu types\"\"\"\n title = models.CharField(max_length=60, null=True)\n menu = models.ForeignKey(\n HeadersMenuNavbar, on_delete=models.CASCADE, related_name='sub_menu', null=True, blank=True)\n\n def __str__(self):\n return \"{}\".format(self.title)\n\n\nclass HeadersSubMenu(models.Model):\n \"\"\"for headers sub menu\"\"\"\n sub_menu_id = models.CharField(max_length=60, unique=True)\n item = models.CharField(max_length=60)\n url = models.CharField(max_length=100)\n types = models.ForeignKey(\n HeadersSubMenuType, on_delete=models.CASCADE, related_name='sub_menu_items', null=True)\n show_in_footer = models.BooleanField(default=True)\n\n def __str__(self):\n return \"{}\".format(self.item)\n\n\n# statistics =\n\n\nclass Statistic(models.Model):\n title = models.CharField(max_length=60, unique=True)\n description = models.TextField(max_length=2000)\n image = models.ImageField(upload_to = 'images/')\n \n# title\n# description\n# image upload\n\nclass AssociatedWith(models.Model):\n title = models.CharField(max_length=60, unique=True)\n status = models.BooleanField(default=True)\n image = models.ImageField(upload_to = 'associated/')\n \nclass TrustedWith(models.Model):\n title = models.CharField(max_length=60, unique=True)\n status = models.BooleanField(default=True)\n image = models.ImageField(upload_to = 'trusted_with/')\n \n \nclass Test1(models.Model):\n name = models.CharField(max_length=60)\nclass Test2(models.Model):\n test1 = models.ManyToManyField(Test1, related_name='names')\n sirname = models.CharField(max_length=60)\n \n \nclass Features(models.Model):\n title = models.CharField(max_length=60)\n \n\nclass Content(models.Model):\n content_id = models.CharField(max_length=60)\n contents = models.ForeignKey(Features, on_delete=models.CASCADE, related_name=\"features\")\n title = models.CharField(max_length=60)\n image = models.ImageField(upload_to = 'content/')\n summary = models.TextField(max_length=2000)\n \nclass TechnologyStackItemCategory(models.Model):\n \n technology_stack_item_category_id = models.CharField(max_length=60, unique=True)\n title = models.CharField(max_length=60)\n \n def __str__(self):\n return self.title\n \n \nclass TechnologyCategory(models.Model):\n technology_category_id = models.CharField(max_length=60, unique=True)\n # category_name = models.CharField(max_length=60)\n \n title = models.CharField(max_length=60)\n # category = models.ForeignKey(, on_delete=models.CASCADE, blank=True, null=True)\n # technology_stack_items = models.ForeignKey(TechnologyStackItems, on_delete=models.CASCADE) \n \n def __str__(self):\n return self.title\n\nclass TechnologyStackSubItem(models.Model):\n # technology_stack_item = models.ManyToManyField(TechnologyStackItem)\n technology_stack_subitem_id = models.CharField(max_length=60)\n title = models.CharField(max_length=60)\n image_icon = models.ImageField(upload_to = 'technology_stack_sub_item/')\n \n def __str__(self):\n return self.title\n\nclass TechnologyStackItem(models.Model):\n \n title = models.CharField(max_length=60)\n technology_category = models.ForeignKey(TechnologyCategory, on_delete=models.CASCADE)\n technology_stack_item = models.ForeignKey(TechnologyStackItemCategory, on_delete=models.CASCADE) \n technology_stack_sub_item = models.ManyToManyField(TechnologyStackSubItem)\n \n def __str__(self):\n return self.title\n\n\nclass WhatWeOfferCategory(models.Model):\n \"\"\"Category for what we offer\"\"\"\n title = models.CharField(max_length=60)\n status = models.BooleanField(default=True)\n\n def __str__(self):\n return \"{}\".format(self.title)\n\n class Meta:\n verbose_name = '4.1. What we offer Category'\n\n\nclass WhatWeOfferSubCategory(models.Model):\n \"\"\"Sub-Category for what we offer\"\"\"\n category = models.ForeignKey(\n WhatWeOfferCategory, on_delete=models.CASCADE, related_name=\"category\")\n title = models.CharField(max_length=100)\n image = models.FileField(upload_to='whatweoffer/')\n summary = models.TextField(max_length=2000)\n status = models.BooleanField(default=True)\n\n def __str__(self):\n return \"{}\".format(self.title)\n\n class Meta:\n verbose_name = '4.2. What we offer Sub-Category'\n\n \n\n \n# class TechnologyStackItems_has_TechnologyStackSubItems(models.model):\n# technology_stack_items_id = models.ForeignKey(TechnologyStackItems, on_delete=models.CASCADE)\n# technology_stack_sub_item_id = models.ForeignKey(TechnologyStackSubItems, on_delete=models.CASCADE)\n \n\nclass Author(models.Model):\n name = models.CharField(max_length=255)\n\nclass Book(models.Model):\n author = models.ForeignKey(Author, on_delete=models.CASCADE)\n title = models.CharField(max_length=255)\n\n\n","sub_path":"custom_admin/custom_ui/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"639295710","text":"# Autor: Gustavo Policarpo\n# Nome: Soma Simples\n# Nível: 1\n# Categoria: INICIANTE\n# URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1003\n\nA = None\nB = None\n\ndef read_integer():\n try:\n # read for Python 2.x\n return int(raw_input())\n except NameError:\n # read for Python 3.x\n return int(input())\n\n\nA = read_integer()\nB = read_integer()\nprint(str(\"SOMA = \") + str(A + B))\n\n","sub_path":"URI/INICIANTE/1003 - Soma Simples.py","file_name":"1003 - Soma Simples.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"199858744","text":"from django.urls import path\nfrom public_app import views\nfrom django.conf.urls import url\nfrom figures import views\n\nurlpatterns = [\n # A list of figures for a given problem\n # path('/', views.problem_display_html, name='problem_display_html'),\n\n # Upload figures for a given problem\n path('upload//', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'),\n\n # Delete all figures for a given problem\n path('delete_problem_figures//', views.delete_figures_for_problem, name='delete_figures_for_problem'),\n\n # Dissassociate a figure and delete the file.\n path('delete_figure//', views.delete_figure, name='delete_figure'),\n url(r'^clear/$', views.delete_all_figures, name='delete_all_figures'),\n\n path('categorize_media//', views.categorize_media, name='categorize_media'),\n\n # NOT USED. REMOVE AFTER TESTING AND BEFORE PRODUCTION\n # url(r'^upload/$', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'),\n # url(r'^upload/(?P[0-9]{1,9})/$', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'),\n # Upload figures without assigning them to a problem\n path('upload/', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'),\n # path('upload/', views.ProgressBarUploadView, name='progress_bar_upload'),\n # path('upload//', views.ProgressBarUploadView, name='progress_bar_upload'),\n # Not used\n url(r'^basic-upload/$', views.BasicUploadView.as_view(), name='basic_upload'),\n # path('basic-upload/', views.BasicUploadView, name='basic_upload'),\n # Not used\n path('basic-upload/', views.BasicUploadView.as_view(), name='basic_upload'),\n # url(r'^progress-bar-upload/$', views.ProgressBarUploadView, name='progress_bar_upload'),\n # Not used\n url(r'^progress-bar-upload/$', views.ProgressBarUploadView.as_view(), name='progress_bar_upload'),\n # url(r'^drag-and-drop-upload/$', views.DragAndDropUploadView, name='drag_and_drop_upload'),\n # Not used\n url(r'^drag-and-drop-upload/$', views.DragAndDropUploadView.as_view(), name='drag_and_drop_upload'),\n]\n","sub_path":"osu_www/figures/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"154406154","text":"from django_select2.forms import ModelSelect2TagWidget\n\nfrom .models import UserTags, Indastry\n\n\nclass BaseSelect2TagWidget(ModelSelect2TagWidget):\n search_fields = [\"name__icontains\"]\n def value_from_datadict(self, data, files, name):\n values = super().value_from_datadict(data, files, name)\n ids = []\n for value in values:\n try:\n pk = int(value)\n except ValueError:\n pk = UserTags.objects.create(name=value).pk\n ids.append(pk)\n return ids\n\n\nclass TagSelec2(BaseSelect2TagWidget):\n queryset = UserTags.objects.all()\n\n\nclass IndastrySelect2(BaseSelect2TagWidget):\n queryset = Indastry.objects.all()\n","sub_path":"coworker/users/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"511235277","text":"num = 0\nwhile num < 10:\n num = num + 1\n # print(num**2) # 输出1-10的平方\n if num >= 10:\n break\n\n\nfrom random import randint\nguesses_left = 3\nrandom_number = randint(1, 10)\nwhile guesses_left > 0 :\n guess = int(input(\"Your guess: \"))\n if guess == random_number:\n print(\"You win\")\n break\n guesses_left -= 1\nelse:\n print(\"You lose\")\n\nhobbies = []\nfor num in range(3): # 谁能告诉我这个num是啥作用\n hobby = input(\"input one of your favorite hobbies: \") # input( )功能向用户获取信息\n hobbies.append(hobby)\n# print(hobbies)\n\n\nphrase = \"A bird in the hand...\"\nfor char in phrase:\n if char == \"A\" or char == \"a\":\n print(\"X\",) # print ( \" , \") ','有什么作用\n else:\n print(char,)\n\n\nchoices = ['pizza', 'pasta', 'salad', 'nachos']\nprint('Your choices are: ')\nfor index, item in enumerate(choices): #enumrate() 枚举 通过为列表中的每个元素提供相应的索引\n print(index + 1, item) # index从 0 开始索引,index+1从 1 开始索引","sub_path":"pro/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"441064418","text":"\n@IN.hook\ndef ws_action_messenger_init_session(context, message):\n\t\n\tfrom_nabar_id = context.nabar.id\n\t\n\tif not from_nabar_id:\n\t\treturn\n\t\n\troom = None\n\tmessenger = IN.messenger\n\t\n\tif 'to_nabar_id' in message:\n\t\tto_nabar_id = message['to_nabar_id']\n\t\tif not to_nabar_id:\n\t\t\treturn\n\t\tif messenger.message_access(from_nabar_id, to_nabar_id):\n\t\t\n\t\t\troom = messenger.get_su_room_between(from_nabar_id, to_nabar_id)\n\t\t\tif not room:\n\t\t\t\troom = messenger.create_su_room(from_nabar_id, to_nabar_id)\n\t\t\t\n\telif 'room_id' in message:\n\t\troom_id = int(message['room_id'])\n\t\tif not room_id:\n\t\t\treturn\n\t\troom = IN.entitier.load_single('Room', room_id)\n\t\n\tif not room:\n\t\treturn\n\t\n\t\n\tif not room.access('send', from_nabar_id):\n\t\treturn\n\t\n\tmessage = {\n\t\t'ws_command' : 'init_session',\n\t\t'room' : {\n\t\t\t'id' : room.id,\n\t\t\t'name' : room.get_title(from_nabar_id),\n\t\t\t'type' : room.type\n\t\t}\n\t}\n\t\n\tif room.type == 'su':\n\t\t# set to_nabar_id\n\t\tif room.members[0] == from_nabar_id:\n\t\t\tmessage['to_nabar_id'] = room.members[1]\n\t\telse:\n\t\t\tmessage['to_nabar_id'] = room.members[0]\n\t\t\n\t# TODO: ACCESS CHECK\n\tcontext.send(message)\n\t\n\n@IN.hook\ndef ws_action_messenger_send(context, message):\n\t\n\tif not message['message']:\n\t\treturn\n\t\n\tif not message['room_id']:\n\t\treturn\n\t\n\troom_id = message['room_id']\n\t\n\t# TODO: access check\n\t\n\troom = IN.entitier.load_single('Room', room_id)\n\t\n\tif not room:\n\t\traise Exception('Room not found!')\n\t\n\tif not room.access('send', context.nabar.id):\n\t\treturn\n\t\n\tmessenger = IN.messenger\n\t\n\tmessage = messenger.send_text_message_to_room(message['message'], room, context.nabar)\n\t\n\tif not message:\n\t\treturn\n\t\t\n\t# send themed message\n\t\n\tsend_message = {\n\t\t'message' : {\n\t\t\t'id' : message.id,\n\t\t\t'message' : IN.themer.theme(message, args = {\n\t\t\t\t'context' : context\n\t\t\t}),\n\t\t\t'nabar_id' : message.nabar_id,\n\t\t\t'read_status' : 1,\n\t\t},\n\t\t'room' : {\n\t\t\t'id' : room.id,\n\t\t\t'name' : room.get_title(context.nabar.id),\n\t\t\t'type' : room.type\n\t\t}\n\t}\n\t\n\tws_message = {\n\t\t'ws_command' : 'messenger_new_message',\n\t\t'messages' : [send_message]\n\t}\n\t\n\t# TODO: send to all public room members\n\tif room.type == 'public':\n\t\t\n\t\tsubscriptions = IN.APP.context_subscriptions\n\t\tcontexts = IN.APP.contexts\n\t\t\n\t\tif room.id not in subscriptions:\n\t\t\treturn\n\t\t\n\t\tfor nabar_id in subscriptions[room.id]:\n\t\t\n\t\t\tfor nabar_context in contexts[nabar_id]:\n\t\t\t\ttry:\n\t\t\t\t\tnabar_context.send(ws_message)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tIN.logger.debug()\n\telse:\n\t\t\n\t\tcontexts = IN.APP.contexts\n\t\t\n\t\tfor nabar_id in room.members:\n\t\t\tif nabar_id in contexts:\n\t\t\t\tfor nabar_context in contexts[nabar_id]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tnabar_context.send(ws_message)\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tIN.logger.debug()\n\n@IN.hook\ndef ws_action_messenger_rooms_state(context, message):\n\t\n\tif 'rooms_state' not in message:\n\t\treturn\n\t\n\trooms_state = message['rooms_state']\n\t\n\tif not rooms_state:\n\t\treturn\n\t\n\t# TODO: ACCESS CHECK for each room\n\t\n\twhere = []\n\t\n\tfor room_id, last_message_id in rooms_state.items():\n\t\twhere.append(['and', [['room_id', room_id], ['id', '>', last_message_id], ['status', 1]]])\n\t\n\ttry:\n\t\t\n\t\tcursor = IN.db.select({\n\t\t\t'table' : 'message.message',\n\t\t\t'columns' : ['id'],\n\t\t\t'where' : ['OR', where],\n\t\t\t'order' : 'created'\n\t\t}).execute()\n\t\t\n\t\tmessages = []\n\t\t\n\t\tif cursor.rowcount != 0:\n\t\t\tids = [data['id'] for data in cursor]\n\t\t\t\n\t\t\tmessage_entities = IN.entitier.load_multiple('Message', ids)\n\t\t\tread_status = IN.messenger.get_message_read_status(ids, context.nabar.id)\n\t\t\t\n\t\t\tso = sorted(message_entities.values(), key = lambda o : o.id)\n\t\t\t\n\t\t\t__theme = IN.themer.theme\n\t\t\targs = {'context' : context}\n\t\t\t\n\t\t\tfor message_entity in so:\n\t\t\t\tid = message_entity.id\n\t\t\t\tmessages.append({\t\t\t\t\n\t\t\t\t\t'message' : {\n\t\t\t\t\t\t'id' : id,\n\t\t\t\t\t\t'message' : __theme(message_entity, args = args),\n\t\t\t\t\t\t'nabar_id' : message_entity.nabar_id,\n\t\t\t\t\t\t'read_status' : read_status.get(id, 2)\n\t\t\t\t\t},\n\t\t\t\t\t'room' : {\n\t\t\t\t\t\t'id' : message_entity.room_id,\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\n\t\ttry:\n\t\t\tcontext.send({\n\t\t\t\t'ws_command' : 'messenger_rooms_state',\n\t\t\t\t'messages' : messages\n\t\t\t})\n\t\texcept Exception as e1:\n\t\t\tIN.logger.debug()\n\t\t\t\n\texcept Exception as e:\n\t\tIN.logger.debug()\n\t\n@IN.hook\ndef ws_action_messenger_room_messages_load_more(context, message):\n\t\n\t# TODO: ROOM ACCESS\n\t\n\tif 'room_id' not in message:\n\t\treturn\n\t\n\troom_id = message['room_id']\n\t\n\tfirst_message_id = 0;\n\tif 'first_message_id' in message:\n\t\tfirst_message_id = message['first_message_id']\n\t\n\ttry:\n\t\twhere = [\n\t\t\t['room_id', room_id],\n\t\t\t['status', 1],\n\t\t]\n\t\t\n\t\tif first_message_id > 0:\n\t\t\twhere.append(['id', '<', first_message_id])\n\t\t\n\t\tcursor = IN.db.select({\n\t\t\t'table' : 'message.message',\n\t\t\t'columns' : ['id'],\n\t\t\t'where' : where,\n\t\t\t'order' : {'created' : 'desc'},\n\t\t\t'limit' : 15,\n\t\t}).execute()\n\t\t\n\t\tmessages = []\n\t\t\n\t\tif cursor.rowcount != 0:\n\t\t\tids = [data['id'] for data in cursor]\n\t\t\t\n\t\t\tmessage_entities = IN.entitier.load_multiple('Message', ids)\n\t\t\t\n\t\t\tread_status = IN.messenger.get_message_read_status(ids, context.nabar.id)\n\t\t\t\n\t\t\tso = sorted(message_entities.values(), key = lambda o : o.id, reverse=True)\n\t\t\t\n\t\t\t__theme = IN.themer.theme\n\t\t\targs = {'context' : context}\n\t\t\t\n\t\t\tfor message_entity in so:\n\t\t\t\tid = message_entity.id\n\t\t\t\tmessages.append({\n\t\t\t\t\t'message' : {\n\t\t\t\t\t\t'id' : id,\n\t\t\t\t\t\t'message' : __theme(message_entity, args = args),\n\t\t\t\t\t\t'nabar_id' : message_entity.nabar_id,\n\t\t\t\t\t\t'read_status' : read_status.get(id, 2)\n\t\t\t\t\t},\n\t\t\t\t\t'room' : {\n\t\t\t\t\t\t'id' : message_entity.room_id,\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\n\t\ttry:\n\t\t\tcontext.send({\n\t\t\t\t'ws_command' : 'messenger_room_messages_load_more',\n\t\t\t\t'messages' : messages\n\t\t\t})\n\t\texcept Exception as e1:\n\t\t\tIN.logger.debug()\n\t\t\t\n\texcept Exception as e:\n\t\tIN.logger.debug()\n\t\n\n@IN.hook\ndef ws_action_messenger_mark_read(context, message):\n\t\n\tif 'ids' not in message:\n\t\treturn\n\t\n\tids = message['ids']\n\t\n\tif not ids:\n\t\treturn\n\t\n\ttry:\n\t\t\n\t\tIN.db.update({\n\t\t\t'table' : 'message.message_nabar',\n\t\t\t'set' : [['status', 2]], # read\n\t\t\t'where' : [\n\t\t\t\t['nabar_id', context.nabar.id],\n\t\t\t\t['message_id', 'IN', ids]\n\t\t\t]\n\t\t}).execute()\n\t\t\n\t\tIN.db.connection.commit()\n\t\t\n\texcept Exception as e:\n\t\tIN.db.connection.rollback()\n\t\tIN.logger.debug()\n\n@IN.hook\ndef ws_action_messenger_notification_count(context, message):\n\ttry:\n\t\tnabar_id = context.nabar.id\n\t\t\n\t\tif not nabar_id:\n\t\t\treturn\n\t\t\t\n\t\t\n\t\tcursor = IN.db.select({\n\t\t\t'table' : ['message.message_nabar', 'mn'],\n\t\t\t'count_column' : 'distinct m.room_id',\n\t\t\t'join' : [\n\t\t\t\t['inner join', 'message.message', 'm', [\n\t\t\t\t\t['mn.message_id = m.id']\n\t\t\t\t]]\n\t\t\t],\n\t\t\t'where' : [\n\t\t\t\t['mn.nabar_id', nabar_id],\n\t\t\t\t['mn.status', 1],\n\t\t\t\t['m.status', '>=', 1],\n\t\t\t],\n\t\t}).execute_count()\n\t\t\n\t\tif cursor.rowcount == 0:\n\t\t\treturn\n\t\t\n\t\tcount = cursor.fetchone()[0]\n\t\t\n\t\tcontext.send({\n\t\t\t'ws_command' : 'messenger_notification_count',\n\t\t\t'count' : count\n\t\t})\n\t\t\n\texcept Exception as e:\n\t\tIN.logger.debug()\n\n\n@IN.hook\ndef ws_action_messenger_subscribe(context, message):\n\ttry:\n\t\t\n\t\tsubscriptions = IN.APP.context_subscriptions\n\t\tkey = message['key']\n\t\tif key not in subscriptions:\n\t\t\tsubscriptions[key] = set()\n\t\t\n\t\tsubscriptions[key].add(context.nabar.id)\n\t\t\n\texcept Exception as e:\n\t\tIN.logger.debug()\n\n\n@IN.hook\ndef ws_action_messenger_unsubscribe(context, message):\n\ttry:\n\t\t\n\t\tsubscriptions = IN.APP.context_subscriptions\n\t\tkey = message['key']\n\t\tif key not in subscriptions:\n\t\t\treturn\n\t\t\n\t\tsubscriptions[key].remove(context.nabar.id)\n\t\t\n\texcept Exception as e:\n\t\tIN.logger.debug()\n","sub_path":"messenger/ws_action.py","file_name":"ws_action.py","file_ext":"py","file_size_in_byte":7382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"535680735","text":"\nfrom RingerTrigEgammaAnalysis.Arcanus import Arcanus\nfrom RingerTrigEgammaAnalysis.TrigAnalysisTool import TrigAnalysisTool\n\nfrom RingerTrigEgammaAnalysis.mc14_ElectronDef import e24_medium_L1EM20VH,e24_lhmedium_L1EM20VH,\\\n e24_medium_L1EM20VH_L2CaloSP_ringer, e24_medium_L1EM20VH_L2CaloPd_ringer,\\\n e24_medium_L1EM20VH_L2CaloPf_ringer, e24_lhmedium_L1EM20VH_L2EFCaloSP_ringer,\\\n e24_lhmedium_L1EM20VH_L2EFCaloPd_ringer, e24_lhmedium_L1EM20VH_L2EFCaloPf_ringer\n\n\n\n#=======================================================================================\nbasepath = '/afs/cern.ch/work/j/jodafons/news'\nsgnName='/afs/cern.ch/work/j/jodafons/public/sample.user.jodafons.mc14_13TeV.147406.PowhegPythia8_AZNLO_Zee.recon.RDO.rel20.1.0.4.e3059_s1982_s2008_r5993_rr0003.ph0001_PhysVal.root'\nbkgName='/afs/cern.ch/work/j/jodafons/public/sample.user.jodafons.mc14_13TeV.129160.Pythia8_AU2CTEQ6L1_perf_JF17.recon.RDO.rel20.1.0.4.e3084_s2044_s2008_r5988.rr0003.ph0001_PhysVal.root'\nlabels = ['e24_medium_L1EM18VH','e24_lhmedium_L1EM18VH', 'e24_lhtight_L1EM20VH', 'e24_lhmedium_idperf_L1EM20VH']\nlevel = 2\n\n#Triggers =============================================================================\ntes = [ \n e24_medium_L1EM20VH, \n e24_medium_L1EM20VH_L2CaloSP_ringer,\n e24_medium_L1EM20VH_L2CaloPd_ringer,\n e24_medium_L1EM20VH_L2CaloPf_ringer,\n e24_lhmedium_L1EM20VH,\n e24_lhmedium_L1EM20VH_L2EFCaloSP_ringer,\n e24_lhmedium_L1EM20VH_L2EFCaloPd_ringer,\n e24_lhmedium_L1EM20VH_L2EFCaloPf_ringer,\n ]\n\n#Tools =================================================================================\nZeeTool = TrigAnalysisTool( tes, \n baseDir='signal/Trigger',\n bucketName='Zee',\n pidName='lhtight', \n level=level)\n\n#Main ==================================================================================\nmain = Arcanus( level=level, output='Zee_Physval.root', maxEvents=-1,\n tools=[ZeeTool])\n\nmain.setBucket('Zee', [sgnName],'Trigger/HLT/Egamma/Ntuple',labels)\n#Run ===================================================================================\nmain.initialize()\nmain.execute()\nmain.finalize()\n#=======================================================================================\n\n\n\n","sub_path":"scripts/validate/run_zee.py","file_name":"run_zee.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"414855221","text":"#encoding: utf-8\nfrom OpenOrange import *\n\nParentJobPosition = SuperClass(\"JobPosition\",\"Master\",__file__)\nclass JobPosition(ParentJobPosition):\n\n\n def defaults(self):\n ParentJobPosition.defaults(self)\n\n def getAvgCost(self):\n tot,cnt = 0,0\n emps = Query()\n emps.sql = \"SELECT {WeeklyWorkHrs}, {PayBase}, {Wages} \"\n emps.sql += \"FROM [Employee] POIr \"\n emps.sql += \"WHERE?AND ({Closed} = i|0| OR {Closed} IS NULL) \"\n emps.sql += \"WHERE?AND {JobPosition} = s|%s| \" % self.Code\n if (emps.open()):\n for emp in emps:\n tot += emp.Wages / (emp.WeeklyWorkHrs * 52 / 12)\n cnt += 1\n if (cnt):\n return (tot/cnt)\n else:\n return 0.0\n","sub_path":"extra/PayRoll/records/JobPosition.py","file_name":"JobPosition.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"218685518","text":"import gspread \nfrom google.oauth2.service_account import Credentials\nfrom pprint import pprint\n\nSCOPE = [\n \"https://www.googleapis.com/auth/spreadsheets\",\n \"https://www.googleapis.com/auth/drive.file\",\n \"https://www.googleapis.com/auth/drive\"\n ]\n\nCREDS = Credentials.from_service_account_file(\"creds.json\")\nSCOPED_CREDS = CREDS.with_scopes(SCOPE)\nGSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)\nSHEET = GSPREAD_CLIENT.open(\"love_sandwiches\")\n\ndef get_sales_data():\n \"\"\"\n Get sales figures input from the user.\n Run a while loop to ensure correct string data is provided, and\n the loop breaks when correct data type is provided and function returns sales data \"\"\"\n while True:\n print(\"Please enter sales data from the last market.\")\n print(\"Data should be six numbers, seperated by commas\")\n print(\"Example: 10,20,30,40,50,60\\n\")\n\n data_str = input(\"Please enter your data here in the format shown above: \")\n sales_data = data_str.split(\",\")\n if validate_data(sales_data):\n print(\"Data entered is valid\")\n break\n\n return sales_data\n\n\ndef validate_data(values):\n \"\"\" \n Inside the try, the function will convert string values into integers. \n Function will raise value errors if the input cannot be converted into an integer,\n or if the number of items in the values list is not equal to 6\n \"\"\"\n try:\n [int(value) for value in values]\n if len(values) != 6:\n raise ValueError(f\"Exactly 6 values are required. You provided {len(values)}\\n\")\n \n except ValueError as e:\n print(f\"Invalid data {e}, please try again\\n\")\n print(\"--------------------------------------\\n\")\n return False\n\n return True\n\ndef update_worksheet(sheet, data):\n print(f\"Updating {sheet} worksheet...\")\n intended_worksheet = SHEET.worksheet(sheet)\n intended_worksheet.append_row(data)\n print(f\"Updated {sheet} successfully\")\n\n\ndef calculate_surplus_data(sales_row):\n \"\"\"\n Compare sales with stock and calculate surplus for each item\n\n The surplus is defined as the sales figure subtracted from the stock.\n - Positive surplus indicates waste\n - Negative surplus indicates extra sandwiches made when the stock was sold out.\n \"\"\"\n print(\"Calculating surplus data...\\n\")\n stock = SHEET.worksheet(\"stock\").get_all_values()\n stock_row = stock[len(stock) - 1]\n \n surplus_data = []\n for stock, sales in zip(stock_row, sales_row):\n surplus = int(stock) - sales\n surplus_data.append(surplus)\n \n return surplus_data\n\n\ndef get_last_5_entries_sales():\n \"\"\"\n Collects columns of data from worksheet, collecting\n the last five entries of sandwiches and returns the data \n as a list of lists\n \"\"\"\n sales = SHEET.worksheet(\"sales\")\n \n columns = []\n for ind in range(1,7):\n column = sales.col_values(ind)\n columns.append(column[-5:])\n \n return columns\n\n\ndef calculate_stock_data(data):\n \"\"\"\n Calculate the average stock for each item type, adding 10%\n \"\"\"\n print(\"Calculating stock data...\")\n new_stock_data = []\n for column in data:\n int_column = [int(num) for num in column]\n average = sum(int_column) / len(int_column)\n stock_num = average * 1.1\n new_stock_data.append(round(stock_num))\n\n return new_stock_data\n\ndef get_stock_values(data):\n \"\"\"\n Creates a dictionary of sandwich type headings as keys and stock values as values\n \"\"\"\n headings = SHEET.worksheet(\"stock\").get_all_values()[0]\n \n stock_dictionary = dict(zip(headings, data))\n return stock_dictionary\n\n\ndef main():\n \"\"\"Run all program functions\"\"\"\n data = get_sales_data()\n print(data)\n sales_data = [int(num) for num in data]\n update_worksheet(\"sales\", sales_data)\n new_surplus_data = calculate_surplus_data(sales_data)\n update_worksheet(\"surplus\", new_surplus_data)\n sales_columns = get_last_5_entries_sales()\n stock_data = calculate_stock_data(sales_columns)\n print(stock_data)\n update_worksheet(\"stock\", stock_data)\n stock_values = get_stock_values(stock_data)\n print(stock_values)\n\nprint(\"Welcome to Love Sandwiches data automation\")\nstock_data = main()\n\nstock_values = get_stock_values(stock_data)\nprint(\"Make the following number of sandwiches for the next market:\")\nprint(stock_values)\n\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"460367384","text":"# Always prefer setuptools over distutils\nfrom setuptools import setup, find_packages\n# To use a consistent encoding\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n# Arguments marked as \"Required\" below must be included for upload to PyPI.\n# Fields marked as \"Optional\" may be commented out.\n\nsetup(\n name='randomuser_generator_gcse', # Required\n version='1.2.0', # Required\n description='A random user generator.',\n install_requires=['requests']\n)","sub_path":"pypi_install_script/randomuser_generator_gcse-1.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"641061468","text":"import click\nimport numpy as np\nfrom sklearn.neighbors import KDTree\nfrom matplotlib import pylab as plt\nfrom scipy.sparse import coo_matrix\nfrom refhic.util import fdr\nimport pandas as pd\n\ndef rhoDelta(data,resol,dc):\n pos = data[[1, 4]].to_numpy() // resol\n # remove singleton\n posTree = KDTree(pos, leaf_size=30, metric='chebyshev')\n NNindexes, NNdists = posTree.query_radius(pos, r=2, return_distance=True)\n _l = []\n for v in NNindexes:\n _l.append(len(v))\n _l=np.asarray(_l)\n data = data[_l>5].reset_index(drop=True)\n # end of remove singleton\n pos = data[[1, 4]].to_numpy() // resol\n val = data[6].to_numpy()\n\n posTree = KDTree(pos, leaf_size=30, metric='chebyshev')\n NNindexes, NNdists = posTree.query_radius(pos, r=dc, return_distance=True)\n\n # calculate local density rho\n rhos = []\n for i in range(len(NNindexes)):\n # rhos.append(np.sum(np.exp(-(NNdists[i] / dc) ** 2)))\n rhos.append(np.dot(np.exp(-(NNdists[i] / dc) ** 2), val[NNindexes[i]]))\n rhos = np.asarray(rhos)\n\n # calculate delta_i, i.e. distance to nearest point with larger rho\n _r = 100\n _indexes, _dists = posTree.query_radius(pos, r=_r, return_distance=True, sort_results=True)\n deltas = rhos * 0\n LargerNei = rhos * 0 - 1\n for i in range(len(_indexes)):\n idx = np.argwhere(rhos[_indexes[i]] > rhos[_indexes[i][0]])\n if idx.shape[0] == 0:\n deltas[i] = _dists[i][-1] + 1\n else:\n LargerNei[i] = _indexes[i][idx[0]]\n deltas[i] = _dists[i][idx[0]]\n failed = np.argwhere(LargerNei == -1).flatten()\n while len(failed) > 1 and _r < 100000:\n _r = _r * 10\n _indexes, _dists = posTree.query_radius(pos[failed], r=_r, return_distance=True, sort_results=True)\n for i in range(len(_indexes)):\n idx = np.argwhere(rhos[_indexes[i]] > rhos[_indexes[i][0]])\n if idx.shape[0] == 0:\n deltas[failed[i]] = _dists[i][-1] + 1\n else:\n LargerNei[failed[i]] = _indexes[i][idx[0]]\n deltas[failed[i]] = _dists[i][idx[0]]\n failed = np.argwhere(LargerNei == -1).flatten()\n\n data['rhos']=rhos\n data['deltas']=deltas\n\n return data\n\n\n@click.command()\n@click.option('--dc', type=int, default=25000, help='distance cutoff for local density calculation in terms of bp. [25000]')\n@click.option('--minscore', type=float,default=0.5, help='min RefHiC score [0.5]')\n@click.option('--resol', default=5000, help='resolution [5000]')\n@click.option('--alpha', type=float, default=0.05, help='FDR alpha [0.05]')\n@click.option('--mindelta', type=float, default=5, help='min distance allowed between two loops [5]')\n@click.option('--refine',type=bool,default = True,help ='refine loops. Should always set as True [True]')\n@click.option('--verbose',type=bool,default =False, help='show plot [False]')\n@click.argument('candidates', type=str,required=True)\n@click.argument('output', type=str,required=True)\ndef pool(dc,candidates,resol,mindelta,minscore,output,refine,alpha,verbose):\n '''call loop from loop candidates by clustering'''\n dc=dc/resol\n data = pd.read_csv(candidates, sep='\\t', header=None)\n data = data[data[6] > minscore].reset_index(drop=True)\n data = data[data[4] - data[1] > 11*resol].reset_index(drop=True)\n data[['rhos','deltas']]=0\n data=data.groupby([0,9]).apply(rhoDelta,resol=resol,dc=dc).reset_index(drop=True)\n\n\n minrho=fdr(data[(data[9]=='target') & (data['deltas']>mindelta)]['rhos'],data[(data[9]=='decoy') & (data['deltas']>mindelta)]['rhos'],alpha=alpha)\n\n\n\n if verbose:\n plt.figure()\n plt.plot(data[(data[9]=='decoy') & (data['deltas']>mindelta)]['rhos'],data[(data[9]=='decoy')& (data['deltas']>mindelta)]['deltas'],'.',label='decoy')\n plt.plot(data[(data[9] == 'target')& (data['deltas']>mindelta)]['rhos'], data[(data[9] == 'target')& (data['deltas']>mindelta)]['deltas'],'.' ,label='target')\n plt.plot([minrho,minrho],[0,np.max(data['deltas'])])\n plt.xlabel('rho')\n plt.ylabel('delta')\n plt.legend()\n plt.show()\n\n targetData=data[data[9]=='target'].reset_index(drop=True)\n\n loopPds=[]\n for chrom in set(targetData[0]):\n data = targetData[targetData[0]==chrom].reset_index(drop=True)\n\n pos = data[[1, 4]].to_numpy() // resol\n posTree = KDTree(pos, leaf_size=30, metric='chebyshev')\n\n rhos = data['rhos'].to_numpy()\n deltas = data['deltas'].to_numpy()\n centroid = np.argwhere((rhos > minrho) & (deltas > mindelta)).flatten()\n\n\n # calculate delta_i, i.e. distance to nearest point with larger rho\n _r = 100\n _indexes, _dists = posTree.query_radius(pos, r=_r, return_distance=True, sort_results=True)\n LargerNei = rhos * 0 - 1\n for i in range(len(_indexes)):\n idx = np.argwhere(rhos[_indexes[i]] > rhos[_indexes[i][0]])\n if idx.shape[0] == 0:\n pass\n else:\n LargerNei[i] = _indexes[i][idx[0]]\n\n failed = np.argwhere(LargerNei == -1).flatten()\n while len(failed) > 1 and _r < 100000:\n _r = _r * 10\n _indexes, _dists = posTree.query_radius(pos[failed], r=_r, return_distance=True, sort_results=True)\n for i in range(len(_indexes)):\n idx = np.argwhere(rhos[_indexes[i]] > rhos[_indexes[i][0]])\n if idx.shape[0] == 0:\n pass\n else:\n LargerNei[failed[i]] = _indexes[i][idx[0]]\n failed = np.argwhere(LargerNei == -1).flatten()\n\n\n # assign rest loci to loop clusters\n LargerNei = LargerNei.astype(int)\n label = LargerNei * 0 - 1\n for i in range(len(centroid)):\n label[centroid[i]] = i\n decreasingsortedIdxRhos = np.argsort(-rhos)\n for i in decreasingsortedIdxRhos:\n if label[i] == -1:\n label[i] = label[LargerNei[i]]\n\n\n\n # refine loop\n val = data[6].to_numpy()\n refinedLoop = []\n label = label.flatten()\n for l in set(label):\n idx = np.argwhere(label == l).flatten()\n if len(idx) > 0:\n refinedLoop.append(idx[np.argmax(val[idx])])\n\n\n if refine:\n loopPds.append(data.loc[refinedLoop])\n else:\n loopPds.append(data.loc[centroid])\n\n\n loopPd=pd.concat(loopPds).sort_values(6,ascending=False)\n loopPd[[0,1,2,3,4,5,6,7,8]].to_csv(output,sep='\\t',header=False, index=False)\n print(len(loopPd),'loops saved to ',output)\n\nif __name__ == '__main__':\n pool()\n","sub_path":"refhic/poolLoop.py","file_name":"poolLoop.py","file_ext":"py","file_size_in_byte":6630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"163274746","text":"\r\ndef balance_check(s):\r\n if len(s)% 2 != 0:\r\n return False\r\n\r\n opening = set ('([{')\r\n\r\n matches = set ([ ( '(' ,')' ), ( '{' ,'}' ), ( '[' ,']' ) ])\r\n print (matches)\r\n\r\n stack = []\r\n\r\n for bracket in s:\r\n\r\n if bracket in opening:\r\n stack.append(bracket)\r\n else:\r\n if len(stack) == 0:\r\n return False\r\n last_open = stack.pop()\r\n\r\n if (last_open, bracket) not in (matches):\r\n return False\r\n return len(stack) == 0\r\n\r\nret = balance_check('[[{{(}}]]')\r\nprint(ret)\r\n\r\n","sub_path":"python_programs/Interview_questions/balance_check.py","file_name":"balance_check.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"170881601","text":"from xcp2k.inputsection import InputSection\n\n\nclass _non_local7(InputSection):\n def __init__(self):\n InputSection.__init__(self)\n self.Type = None\n self.Verbose_output = None\n self.Kernel_file_name = None\n self.Cutoff = None\n self.Parameters = None\n self.Scale = None\n self._name = \"NON_LOCAL\"\n self._keywords = {'Type': 'TYPE', 'Verbose_output': 'VERBOSE_OUTPUT', 'Kernel_file_name': 'KERNEL_FILE_NAME', 'Cutoff': 'CUTOFF', 'Parameters': 'PARAMETERS', 'Scale': 'SCALE'}\n\n","sub_path":"xcp2k/classes/_non_local7.py","file_name":"_non_local7.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"508196746","text":"\n\nfrom xai.brain.wordbase.nouns._forsythia import _FORSYTHIA\n\n#calss header\nclass _FORSYTHIAS(_FORSYTHIA, ):\n\tdef __init__(self,): \n\t\t_FORSYTHIA.__init__(self)\n\t\tself.name = \"FORSYTHIAS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"forsythia\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_forsythias.py","file_name":"_forsythias.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"184224235","text":"import sys\nimport warnings\n\nimport numpy as np\n\nfrom ml.classifiers.nn.network import Network\nfrom ml.classifiers.nn.layer import InputLayer, HiddenLayer, OutputLayer\nfrom ml.utilities.function import LeakyReLU\nfrom ml.utilities.preprocessing import OneHotEncoder\nfrom ml.utilities.metrics import confusion_matrix\n\n\nfrom sklearn import preprocessing, model_selection, metrics\n\n\ndef main(argv):\n np.random.seed(1337)\n np.seterr(all = 'ignore')\n warnings.simplefilter(action = 'ignore', category = FutureWarning)\n\n\n print()\n print('Classification Experiment: Spambase')\n print()\n\n\n data = np.loadtxt('./data/csv/spambase.csv', delimiter = ',')\n X = preprocessing.scale(data[:, :57])\n Y = data[:, 57].astype(int)\n\n ohe = OneHotEncoder(Y)\n\n X, X_t, Y, Y_t = model_selection.train_test_split(X, ohe.encode(Y), train_size = 0.75)\n\n\n nn = Network()\n\n nn.add(InputLayer(57, learning = 0.25, regular = 0.001, momentum = 0.0125))\n nn.add(HiddenLayer(100, learning = 0.25, regular = 0.001, momentum = 0, function = LeakyReLU()))\n nn.add(HiddenLayer(100, learning = 0.25, regular = 0.001, momentum = 0, function = LeakyReLU()))\n nn.add(HiddenLayer(50, learning = 0.25, regular = 0.001, momentum = 0.0125))\n nn.add(HiddenLayer(10, learning = 0.25, regular = 0.001, momentum = 0.0125))\n nn.add(OutputLayer(2))\n\n nn.fit(X, Y, batch = 250, epochs = 1000)\n\n P = nn.predict(X_t)\n\n\n P = ohe.decode(P)\n Y_t = ohe.decode(Y_t)\n\n\n\n print()\n print()\n print()\n print(' Result: {:.2f}% Correct'.format(100 * (Y_t == P).sum() / float(len(Y_t))))\n print()\n print(' Classification Report:')\n print()\n print(metrics.classification_report(Y_t, P))\n print()\n print(' Confusion Matrix:')\n print()\n print(confusion_matrix(Y_t, P))\n print()\n\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n","sub_path":"examples/nn/nn_spambase.py","file_name":"nn_spambase.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"569074663","text":"\n\nfrom xai.brain.wordbase.nouns._croquette import _CROQUETTE\n\n#calss header\nclass _CROQUETTES(_CROQUETTE, ):\n\tdef __init__(self,): \n\t\t_CROQUETTE.__init__(self)\n\t\tself.name = \"CROQUETTES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"croquette\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_croquettes.py","file_name":"_croquettes.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"450448064","text":"from django.shortcuts import render,redirect\nfrom .forms import DocumentForm\nfrom .models import Document\n\ndef model_form_upload(request):\n form = DocumentForm()\n if request.method == 'POST':\n form = DocumentForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('Home')\n template_name = 'app2/model_form_upload.html'\n context = {'form': form}\n return render(request,template_name,context)\n\ndef fileview(request):\n file = Document.objects.all()\n template_name = 'app2/uploade_file.html'\n context = {'file': file}\n return render(request,template_name,context)\n\n ","sub_path":"MEDIA File/app2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"427833953","text":"from Qt import QtWidgets, QtCore, QtGui\n\n\nclass NumberSpinBox(QtWidgets.QDoubleSpinBox):\n def __init__(self, *args, **kwargs):\n min_value = kwargs.pop(\"minimum\", -99999)\n max_value = kwargs.pop(\"maximum\", 99999)\n decimals = kwargs.pop(\"decimal\", 0)\n super(NumberSpinBox, self).__init__(*args, **kwargs)\n self.setFocusPolicy(QtCore.Qt.StrongFocus)\n self.setDecimals(decimals)\n self.setMinimum(min_value)\n self.setMaximum(max_value)\n\n def wheelEvent(self, event):\n if self.hasFocus():\n super(NumberSpinBox, self).wheelEvent(event)\n else:\n event.ignore()\n\n def value(self):\n output = super(NumberSpinBox, self).value()\n if self.decimals() == 0:\n output = int(output)\n return output\n\n\nclass ComboBox(QtWidgets.QComboBox):\n value_changed = QtCore.Signal()\n\n def __init__(self, *args, **kwargs):\n super(ComboBox, self).__init__(*args, **kwargs)\n\n self.currentIndexChanged.connect(self._on_change)\n\n def _on_change(self, *args, **kwargs):\n self.value_changed.emit()\n\n def set_value(self, value):\n for idx in range(self.count()):\n _value = self.itemData(idx, role=QtCore.Qt.UserRole)\n if _value == value:\n self.setCurrentIndex(idx)\n break\n\n def value(self):\n return self.itemData(self.currentIndex(), role=QtCore.Qt.UserRole)\n\n\nclass PathInput(QtWidgets.QLineEdit):\n def clear_end_path(self):\n value = self.text().strip()\n if value.endswith(\"/\"):\n while value and value[-1] == \"/\":\n value = value[:-1]\n self.setText(value)\n\n def keyPressEvent(self, event):\n # Always change backslash `\\` for forwardslash `/`\n if event.key() == QtCore.Qt.Key_Backslash:\n event.accept()\n new_event = QtGui.QKeyEvent(\n event.type(),\n QtCore.Qt.Key_Slash,\n event.modifiers(),\n \"/\",\n event.isAutoRepeat(),\n event.count()\n )\n QtWidgets.QApplication.sendEvent(self, new_event)\n return\n super(PathInput, self).keyPressEvent(event)\n\n def focusOutEvent(self, event):\n super(PathInput, self).focusOutEvent(event)\n self.clear_end_path()\n\n\nclass ClickableWidget(QtWidgets.QWidget):\n clicked = QtCore.Signal()\n\n def mouseReleaseEvent(self, event):\n if event.button() == QtCore.Qt.LeftButton:\n self.clicked.emit()\n super(ClickableWidget, self).mouseReleaseEvent(event)\n\n\nclass ExpandingWidget(QtWidgets.QWidget):\n def __init__(self, label, parent):\n super(ExpandingWidget, self).__init__(parent)\n\n self.toolbox_hidden = False\n\n top_part = ClickableWidget(parent=self)\n\n side_line_widget = QtWidgets.QWidget(top_part)\n side_line_widget.setObjectName(\"SideLineWidget\")\n\n button_size = QtCore.QSize(5, 5)\n button_toggle = QtWidgets.QToolButton(parent=side_line_widget)\n button_toggle.setProperty(\"btn-type\", \"expand-toggle\")\n button_toggle.setIconSize(button_size)\n button_toggle.setArrowType(QtCore.Qt.RightArrow)\n button_toggle.setCheckable(True)\n button_toggle.setChecked(False)\n\n label_widget = QtWidgets.QLabel(label, parent=side_line_widget)\n label_widget.setObjectName(\"DictLabel\")\n\n before_label_widget = QtWidgets.QWidget(side_line_widget)\n before_label_layout = QtWidgets.QVBoxLayout(before_label_widget)\n before_label_layout.setContentsMargins(0, 0, 0, 0)\n\n after_label_widget = QtWidgets.QWidget(side_line_widget)\n after_label_layout = QtWidgets.QVBoxLayout(after_label_widget)\n after_label_layout.setContentsMargins(0, 0, 0, 0)\n\n spacer_widget = QtWidgets.QWidget(side_line_widget)\n\n side_line_layout = QtWidgets.QHBoxLayout(side_line_widget)\n side_line_layout.setContentsMargins(5, 10, 0, 10)\n side_line_layout.addWidget(button_toggle)\n side_line_layout.addWidget(before_label_widget)\n side_line_layout.addWidget(label_widget)\n side_line_layout.addWidget(after_label_widget)\n side_line_layout.addWidget(spacer_widget, 1)\n\n top_part_layout = QtWidgets.QHBoxLayout(top_part)\n top_part_layout.setContentsMargins(0, 0, 0, 0)\n top_part_layout.addWidget(side_line_widget)\n\n before_label_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n after_label_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n spacer_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n label_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\n self.top_part_ending = None\n self.after_label_layout = after_label_layout\n self.before_label_layout = before_label_layout\n\n self.side_line_widget = side_line_widget\n self.side_line_layout = side_line_layout\n self.button_toggle = button_toggle\n self.label_widget = label_widget\n\n top_part.clicked.connect(self._top_part_clicked)\n self.button_toggle.clicked.connect(self._btn_clicked)\n\n self.main_layout = QtWidgets.QVBoxLayout(self)\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n self.main_layout.setSpacing(0)\n self.main_layout.addWidget(top_part)\n\n def hide_toolbox(self, hide_content=False):\n self.button_toggle.setArrowType(QtCore.Qt.NoArrow)\n self.toolbox_hidden = True\n self.content_widget.setVisible(not hide_content)\n self.parent().updateGeometry()\n\n def set_content_widget(self, content_widget):\n content_widget.setVisible(False)\n self.main_layout.addWidget(content_widget)\n self.content_widget = content_widget\n\n def _btn_clicked(self):\n self.toggle_content(self.button_toggle.isChecked())\n\n def _top_part_clicked(self):\n self.toggle_content()\n\n def toggle_content(self, *args):\n if self.toolbox_hidden:\n return\n\n if len(args) > 0:\n checked = args[0]\n else:\n checked = not self.button_toggle.isChecked()\n arrow_type = QtCore.Qt.RightArrow\n if checked:\n arrow_type = QtCore.Qt.DownArrow\n self.button_toggle.setChecked(checked)\n self.button_toggle.setArrowType(arrow_type)\n self.content_widget.setVisible(checked)\n self.parent().updateGeometry()\n\n def add_widget_after_label(self, widget):\n self.after_label_layout.addWidget(widget)\n\n def add_widget_before_label(self, widget):\n self.before_label_layout.addWidget(widget)\n\n def resizeEvent(self, event):\n super(ExpandingWidget, self).resizeEvent(event)\n self.content_widget.updateGeometry()\n\n\nclass UnsavedChangesDialog(QtWidgets.QDialog):\n message = \"You have unsaved changes. What do you want to do with them?\"\n\n def __init__(self, parent=None):\n super().__init__(parent)\n message_label = QtWidgets.QLabel(self.message)\n\n btns_widget = QtWidgets.QWidget(self)\n btns_layout = QtWidgets.QHBoxLayout(btns_widget)\n\n btn_ok = QtWidgets.QPushButton(\"Save\")\n btn_ok.clicked.connect(self.on_ok_pressed)\n btn_discard = QtWidgets.QPushButton(\"Discard\")\n btn_discard.clicked.connect(self.on_discard_pressed)\n btn_cancel = QtWidgets.QPushButton(\"Cancel\")\n btn_cancel.clicked.connect(self.on_cancel_pressed)\n\n btns_layout.addWidget(btn_ok)\n btns_layout.addWidget(btn_discard)\n btns_layout.addWidget(btn_cancel)\n\n layout = QtWidgets.QVBoxLayout(self)\n layout.addWidget(message_label)\n layout.addWidget(btns_widget)\n\n self.state = None\n\n def on_cancel_pressed(self):\n self.done(0)\n\n def on_ok_pressed(self):\n self.done(1)\n\n def on_discard_pressed(self):\n self.done(2)\n\n\nclass SpacerWidget(QtWidgets.QWidget):\n def __init__(self, parent=None):\n super(SpacerWidget, self).__init__(parent)\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\n\nclass GridLabelWidget(QtWidgets.QWidget):\n def __init__(self, label, parent=None):\n super(GridLabelWidget, self).__init__(parent)\n\n self.input_field = None\n\n self.properties = {}\n\n layout = QtWidgets.QVBoxLayout(self)\n layout.setContentsMargins(0, 2, 0, 0)\n layout.setSpacing(0)\n\n label_proxy = QtWidgets.QWidget(self)\n\n label_proxy_layout = QtWidgets.QHBoxLayout(label_proxy)\n label_proxy_layout.setContentsMargins(0, 0, 0, 0)\n label_proxy_layout.setSpacing(0)\n\n label_widget = QtWidgets.QLabel(label, label_proxy)\n spacer_widget_h = SpacerWidget(label_proxy)\n label_proxy_layout.addWidget(\n spacer_widget_h, 0, alignment=QtCore.Qt.AlignRight\n )\n label_proxy_layout.addWidget(\n label_widget, 0, alignment=QtCore.Qt.AlignRight\n )\n\n spacer_widget_v = SpacerWidget(self)\n\n layout.addWidget(label_proxy, 0)\n layout.addWidget(spacer_widget_v, 1)\n\n label_proxy.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n label_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\n self.label_widget = label_widget\n\n def setProperty(self, name, value):\n cur_value = self.properties.get(name)\n if cur_value == value:\n return\n\n self.label_widget.setProperty(name, value)\n self.label_widget.style().polish(self.label_widget)\n\n def mouseReleaseEvent(self, event):\n if self.input_field:\n return self.input_field.show_actions_menu(event)\n return super(GridLabelWidget, self).mouseReleaseEvent(event)\n","sub_path":"pype/tools/settings/settings/widgets/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":9830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"131568035","text":"import os\r\n#results='/mnt/blobfuse/train-output/ByMZ/2.18/pred_out/ByMZ-Multi_6layer_99_1_withBN_yb99.5_yerode1_cyan.75_mustdv_2-2-0.1-1_1_1_1_1_1_1_1_1_1-0.0005-0.9995-stain5-mu1.0-sigma1.0-start_stain0-GPU0/'\r\ninput_folder='/mnt/blobfuse/train-output/ByMZ/data_dots_labels_for_multiplex/zipped/Inga/Inga_Completed/Inga_Completed_Annot/'\r\nimport glob\r\nimport shutil\r\nimport cv2\r\nimport copy\r\nimport matplotlib.pyplot as plt\r\nimport concurrent.futures\r\nimport numpy as np\r\nimport collections\r\nimport pickle\r\nimport sys\r\nimport json\r\nbinarize_thre=int(sys.argv[2])\r\nresults=sys.argv[1]\r\nprint('results',results)\r\nfiles=glob.glob(input_folder+'/*.zip')\r\n\r\n\r\nbase_folder='../../data_multiplex/data_dots_labels_for_multiplex/2nd_batch'\r\nunzipped_folder='unzipped'#Areeha/2938_cd20h_cd3h_cd4h_cd8h.png-points/'\r\nimage_folder='images'#Areeha/2938_cd20h_cd3h_cd4h_cd8h.png'\r\nsave_folder='dots_visualization_with_seg_16_deconve_dgx1_bionly'#Areeha/'\r\nannotator='Inga'\r\ndef visualize_one_patch(imname,save_folder):\r\n color_idx={'Yellow':2, 'Purple':4,'Black':0, 'Cyan':3, 'Red':1}\r\n if not os.path.exists(save_folder):\r\n os.makedirs(save_folder)\r\n\r\n #load dots\r\n print(imname)\r\n image_name=imname.split('/')[-1]\r\n cell_type={'Yellow':'CD3 Double Negative T cell','Black':'CD16 Myeloid Cell','Purple':'CD8 Cytotoxic cell','Red':'CD20 B cell','Cyan':'CD4 helper T cell'}\r\n for color in cell_type.keys():\r\n heat_pred=cv2.imread(os.path.join(results,os.path.basename(imname)[0:-4]+'_'+str(color_idx[color])+'.png'))\r\n if heat_pred.shape[0]>400:\r\n heat_pred=cv2.resize(heat_pred,(400,400))\r\n heatmap1,heat_binary= cv2.threshold(heat_pred,binarize_thre,255,cv2.THRESH_BINARY)\r\n cv2.imwrite(os.path.join(save_folder,os.path.basename(imname)[0:-4]+'_'+color+'.png'),heat_binary)\r\n return 0\r\n\r\n\r\nannotators=['Areeha','Christian','Emily','Inga']\r\ncolors_by_annotators={}\r\n#for annotator in annotators:\r\ndef process_one_patch_parall(imname):\r\n precision_dict={'Black':[],'Red':[],'Yellow':[],'Cyan':[],'Purple':[]}\r\n recall_dict={'Black':[],'Red':[],'Yellow':[],'Cyan':[],'Purple':[]}\r\n colors_by_one_annotator = []\r\n annotator = imname.split('/')[-2]\r\n dots_folder = os.path.join(base_folder,unzipped_folder,annotator,os.path.basename(imname)+'-points')\r\n save_folder_processed_dots = os.path.join(base_folder,'processed_dots',annotator)\r\n #print(dots_folder,os.path.exists(dots_folder))\r\n save_dir = os.path.join(results,save_folder,annotator)\r\n #print('save_dir',save_dir)\r\n if not os.path.exists(save_dir):\r\n os.makedirs(save_dir)\r\n \r\n precision_dict1={}\r\n recall_dict1={}\r\n visualize_one_patch(imname,save_dir)\r\n return 0\r\ndef main():\r\n with concurrent.futures.ProcessPoolExecutor( max_workers=40) as executor:\r\n for number, pr in zip(im_names, executor.map(process_one_patch_parall, im_names, chunksize=2)):\r\n print('%s is prime: %s' % (number, pr))\r\n\r\n return 0\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n im_names=[]\r\n for annotator in ['Christian','Emily']:#['Areeha','Christian','Emily', 'Inga']:# ['Christian','Emily']:# ['Areeha','Christian','Emily','Inga']:\r\n im_names+=glob.glob(os.path.join(base_folder,image_folder,annotator)+'/*.png')\r\n #im_names+=glob.glob(os.path.join(base_folder,image_folder,'Emily')+'/2271_cd16h_cd4h_cd8.png')\r\n main()\r\n\r\n","sub_path":"training_phase/eval_visual/visualize_wholeslide_from_v4.py","file_name":"visualize_wholeslide_from_v4.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"338834521","text":"#!/usr/bin/env python2\n\nimport sys\nimport struct\nfrom datetime import datetime\n\n# You can use this method to exit on failure conditions.\ndef bork(msg):\n sys.exit(msg)\n\n\n# Some constants. You shouldn't need to change these.\nMAGIC = 0x8BADF00D\nVERSION = 1\n\nif len(sys.argv) < 2:\n sys.exit(\"Usage: python stub.py input_file.fpff\")\n\n# Normally we'd parse a stream to save memory, but the FPFF files in this\n# assignment are relatively small.\nwith open(sys.argv[1], 'rb') as fpff:\n data = fpff.read()\n\n#index begins at 0, ends at 8\nindex = 0\noffset = 8\n\nSECTION_ASCII = 0x1\nSECTION_UTF8 = 0x2\nSECTION_WORDS = 0x3\nSECTION_DWORDS = 0x4\nSECTION_DOUBLES = 0x5\nSECTION_COORD = 0x6\nSECTION_REFERENCE = 0x7\nSECTION_PNG = 0x8\nSECTION_GIF87 = 0x9\nSECTION_GIF89 = 0xA\n\nPNG_Signature = \"\\x89\\x50\\x4e\\x47\\x0d\\x0a\\x1a\\x0a\"\nGIF87_Signature = \"\\x47\\x49\\x46\\x38\\x37\\x61\\x0d\\x0a\"\nGIF89_Signature = \"\\x47\\x49\\x46\\x38\\x39\\x61\\x0d\\x0a\"\n\n# Hint: struct.unpack will be VERY useful.\n# Hint: you might find it easier to use an index/offset variable than\n# hardcoding ranges like 0:8\n\n#data[0:0+8] = data[0:8] = data[index:index + offset]\n\nmagic, version = struct.unpack(\"= ced:\n total -= ced\n totalced += 1\n else:\n if totalced > 0:\n print(f'Total de {totalced} Cédulas de R$ {ced} ')\n if ced == 50:\n ced = 20\n if ced == 20:\n ced = 10\n if ced == 10:\n ced = 1\n totalced = 0\n if total == 0:\n break\nprint('-='*20)\nprint('Volte Sempre ao Banco do Traumer, Tenha um Bom Dia!')","sub_path":"CursoPython/Exercicios/Ex071.py","file_name":"Ex071.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"643076955","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 7 18:38:58 2019\n\n@author: DarkArmy\n\"\"\"\n\nimport cv2\nimport numpy as np\n \nimg = cv2.imread('IMG_20190106_170921.jpg')\n\n#converting image into its hsv form\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n#selecting the color range to be extracted\nlower_green = np.array([10, 0, 60]) #lowest range\nupper_green = np.array([92, 255, 255]) #highest range\n\n#creating mask for image segmentation \nmask = cv2.inRange(hsv, lower_green, upper_green)\n\n#extracting the foreground from the image\nfg = cv2.bitwise_and(img, img, mask=mask)\n\n#saving the extracted image\ncv2.imwrite('fg1.jpg',fg) #Foreground image","sub_path":"Code/background_remove.py","file_name":"background_remove.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"311652290","text":"\r\ndef gcd(a, b): \r\n if (a == 0): \r\n return b\r\n return gcd(b % a, a)\r\n \r\ndef lowest(den3, num3): \r\n common_factor = gcd(num3, den3)\r\n \r\n den3 = int(den3 / common_factor)\r\n num3 = int(num3 / common_factor)\r\n return f'{num3} / {den3}'\r\n \r\n\r\n# Function to add two fractions \r\ndef addFraction(num1, den1, num2, den2): \r\n den3 = gcd(den1, den2)\r\n\r\n den3 = (den1 * den2) / den3\r\n num3 = ((num1) * (den3 / den1) + (num2) * (den3 / den2))\r\n return lowest(den3, num3)\r\n\r\n\r\n# Driver Code \r\nnum1 = 1; den1 = 1500\r\nnum2 = 2; den2 = 500\r\n \r\nprint(f'{num1} / {den1} + {num2} / {den2} = {addFraction(num1, den1, num2, den2)}')","sub_path":"py_sandbox/add_fractions.py","file_name":"add_fractions.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"158648942","text":"from bs4 import BeautifulSoup\nimport urlparse\nclass Parser(object):\n def parsing(self, aUrl, content):\n if aUrl is None:\n return\n urlPool=set()\n soup=BeautifulSoup(content,'html.parser',from_encoding='utf-8')\n links=soup.find_all('a')\n for link in links:\n link=link.get('href','default')\n fulLink=urlparse.urljoin(aUrl,link)\n urlPool.add(fulLink)\n title=soup.find_all('title')\n return urlPool,title\n\n","sub_path":"innerSpider/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"628849465","text":"def get_magic_triangle(n):\n triangle = [[1], [1, 1]]\n for row in range(2, n):\n new_row = []\n for col in range(0, row + 1):\n if col - 1 < 0:\n new_row.append(1)\n elif col >= len(triangle[row-1]):\n new_row.append(1)\n else:\n upper_left = triangle[row - 1][col - 1]\n upper_right = triangle[row - 1][col]\n new_value = upper_left + upper_right\n new_row.append(new_value)\n triangle.append(new_row)\n\n return triangle\n\nprint(get_magic_triangle(3))\n\n","sub_path":"PYTHON-ADVANCED-SEPT-2020/PYTHON ADVANCED/10_EXAM_PREPARATION/03_magic_triangle.py","file_name":"03_magic_triangle.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"232342321","text":"# -*- coding: utf-8 -*-\n# Kurs: Python: Grundlagen der Programmierung für Nicht-Informatiker\n# Semester: Herbstsemester 2018\n# Homepage: http://accaputo.ch/kurs/python-uzh-hs-2018/\n# Author: Giuseppe Accaputo\n# Aufgabe: Warm-Up: Dictionaries besser kennenlernen\n\ndef preisliste_ausgeben(menu): \n print(\"Unsere Preisliste:\")\n \n for (gericht, preis) in menu.items():\n print(\" *\", gericht, \",\", preis, \"CHF\")\n\nmenu = {\n \"Burger\": 10.5,\n \"Pommes\": 4.0,\n \"Chicken Nuggets\": 8.25\n}\n\npreisliste_ausgeben(menu)","sub_path":"musterloesungen/6.0_warm_ups/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"528644215","text":"import gym\nfrom gym import wrappers\nimport numpy as np\n\nenv = gym.make('FrozenLake8x8-v0')\n# env = wrappers.Monitor(env, './experiments/frozenlake-v0', force=True)\n\nQ = np.random.rand(env.observation_space.n, env.action_space.n)\nQ = Q / 10 ** 5\n#0 left, 1 down, 2 right, 3 up\n\nalpha = 0.25\ngamma = .9\nnum_episodes = 9999\n\ndef train():\n epsilon = .7\n rewards = [0 for _ in range(100)] #moving average over 100 episodes\n for i in range(num_episodes):\n obs0 = env.reset()\n ep_reward = 0\n for t in range(500):\n # env.render()\n if np.random.random_sample() < epsilon:\n action = np.random.randint(0, env.action_space.n)\n else:\n action = np.argmax(Q[obs0,:])\n obs1, reward, done, info = env.step(action)\n Q[obs0, action] += alpha*(reward + gamma*np.max(Q[obs1,:]) - Q[obs0, action])\n #penalize if fall into hole\n if done and reward == 0:\n Q[obs0, action] -= 1 * 10 ** -3\n ep_reward += reward\n obs0 = obs1\n epsilon -= 3 * 10 ** -5\n if done:\n break\n rewards.append(ep_reward)\n rewards.pop(0)\n\n print(\"Average reward over 100 episodes: \" + str(sum(rewards) / len(rewards)))\n # print(\"Final Q-Table Values\")\n # print(Q)\n\ndef simulate():\n obs0 = env.reset()\n for t in range(200):\n env.render()\n action = np.argmax(Q[obs0,:])\n obs1, reward, done, info = env.step(action)\n obs0 = obs1\n if done:\n env.render()\n break\n print(obs0, reward)\n\nif __name__ == '__main__':\n train()\n # simulate()\n","sub_path":"frozenlake/frozenlake8x8-v0.py","file_name":"frozenlake8x8-v0.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"450497682","text":"from collections import defaultdict\nfrom typing import (\n FrozenSet, Iterable, List, Optional, Set, Text, Tuple, Union, Any, Dict, Callable\n)\n\nimport json\nimport os\nfrom src.data_model import StarSigns, CompatibilityScoreMark, Personality, Species, VillagerData, Compatibility\n\n_personality_comp_score_matrix = defaultdict(dict)\n\n\ndef get_star_sign_by_birthday(birth):\n # type: (Tuple[int, int]) -> StarSigns\n def birth_to_int(m, d):\n return (m << 8) | d\n\n star_sign_def = [\n (((1, 1), (1, 19)), StarSigns.Capricorn),\n (((1, 20), (2, 18)), StarSigns.Aquarius),\n (((2, 19), (3, 20)), StarSigns.Pisces),\n (((3, 21), (4, 19)), StarSigns.Aries),\n (((4, 20), (5, 20)), StarSigns.Taurus),\n (((5, 21), (6, 20)), StarSigns.Gemini),\n (((6, 21), (7, 22)), StarSigns.Cancer),\n (((7, 23), (8, 22)), StarSigns.Leo),\n (((8, 23), (9, 22)), StarSigns.Virgo),\n (((9, 23), (10, 22)), StarSigns.Libra),\n (((10, 23), (11, 21)), StarSigns.Scorpio),\n (((11, 22), (12, 21)), StarSigns.Sagittarius),\n (((12, 22), (12, 31)), StarSigns.Capricorn),\n ]\n\n convert_list = map(\n lambda ss_def: (range(birth_to_int(*ss_def[0][0]), birth_to_int(*ss_def[0][1]) + 1), ss_def[1]),\n star_sign_def\n )\n birth_int = birth_to_int(*birth)\n\n for tuple_range_ss in convert_list:\n if birth_int in tuple_range_ss[0]:\n return tuple_range_ss[1]\n raise ValueError(\"Invalid birthday\")\n\n\ndef get_compatibility_score_by_unicode_sign(sign):\n # type: (str) -> CompatibilityScoreMark\n if sign == \"♥\":\n return CompatibilityScoreMark.HEART\n elif sign == \"♦\":\n return CompatibilityScoreMark.DIAMOND\n elif sign == \"♣\":\n return CompatibilityScoreMark.CLOVER\n elif sign == \"×\":\n return CompatibilityScoreMark.CROSS\n else:\n raise ValueError(\"Sign must be either ♥, ♦, ♣, or ×\")\n\n\ndef calculate_compatibility_score_by_personality(p1, p2):\n # type: (Personality, Personality) -> CompatibilityScoreMark\n return _personality_comp_score_matrix[p1][p2]\n\n\ndef calculate_compatibility_score_by_species(s1, s2):\n # type: (Species, Species) -> CompatibilityScoreMark\n def check_species(chk1, chk2):\n return (s1 == chk1 and s2 == chk2) or (s2 == chk1 and s1 == chk2)\n\n if check_species(Species.Bear, Species.Cub) or \\\n check_species(Species.Bull, Species.Cow) or \\\n check_species(Species.Cat, Species.Tiger) or \\\n check_species(Species.Dog, Species.Wolf) or \\\n check_species(Species.Goat, Species.Sheep) or \\\n check_species(Species.Kangaroo, Species.Koala):\n return CompatibilityScoreMark.HEART\n elif s1 == s2 or \\\n check_species(Species.Deer, Species.Horse) or \\\n check_species(Species.Hamster, Species.Squirrel) or \\\n check_species(Species.Hamster, Species.Mouse) or \\\n check_species(Species.Mouse, Species.Squirrel):\n return CompatibilityScoreMark.DIAMOND\n elif check_species(Species.Cat, Species.Mouse) or \\\n check_species(Species.Cat, Species.Hamster) or \\\n check_species(Species.Dog, Species.Gorilla) or \\\n check_species(Species.Dog, Species.Monkey) or \\\n check_species(Species.Sheep, Species.Wolf):\n return CompatibilityScoreMark.CROSS\n else:\n return CompatibilityScoreMark.CLOVER\n\n\n_star_sign_group_idx = {\n StarSigns.Aries: 1,\n StarSigns.Leo: 1,\n StarSigns.Sagittarius: 1,\n\n StarSigns.Taurus: 2,\n StarSigns.Virgo: 2,\n StarSigns.Capricorn: 2,\n\n StarSigns.Gemini: 3,\n StarSigns.Libra: 3,\n StarSigns.Aquarius: 3,\n\n StarSigns.Cancer: 4,\n StarSigns.Scorpio: 4,\n StarSigns.Pisces: 4,\n}\n\n\ndef calculate_compatibility_score_by_star_signs(ss1, ss2):\n # type: (StarSigns, StarSigns) -> CompatibilityScoreMark\n ss1_gid = _star_sign_group_idx[ss1]\n ss2_gid = _star_sign_group_idx[ss2]\n if ss1_gid == ss2_gid:\n return CompatibilityScoreMark.HEART\n elif (ss1_gid == 1 and ss2_gid == 4) or \\\n (ss1_gid == 4 and ss2_gid == 1) or \\\n (ss1_gid == 2 and ss2_gid == 3) or \\\n (ss1_gid == 3 and ss2_gid == 2):\n return CompatibilityScoreMark.CROSS\n else:\n return CompatibilityScoreMark.DIAMOND\n\n\ndef calc_villager_compatibility(villager_a, villager_b):\n # type: (VillagerData, VillagerData) -> Optional[Dict[str, CompatibilityScoreMark]]\n if not villager_a.birthday or not villager_b.birthday or \\\n not villager_a.personality or not villager_b.personality or \\\n not villager_a.species or not villager_b.species:\n return None\n villager_a_star_sign = get_star_sign_by_birthday(villager_a.birthday)\n villager_b_star_sign = get_star_sign_by_birthday(villager_b.birthday)\n return {\n \"personality\": calculate_compatibility_score_by_personality(\n villager_a.personality, villager_b.personality\n ),\n \"species\": calculate_compatibility_score_by_species(\n villager_a.species, villager_b.species\n ),\n \"star_sign\": calculate_compatibility_score_by_star_signs(\n villager_a_star_sign, villager_b_star_sign\n )\n }\n\n\ndef calculate_compatibility_matrix(villagers_list, data_src):\n # type: (List[str], AcListerVillagerDataReader) -> List[List[Dict]]\n\n comp_matrix = []\n\n def query_nth_villager_data(idx):\n dat = data_src.get_data_by_villager_id(villagers_list[idx])\n if not dat:\n raise ValueError(\n \"Failed to query the information for the {}th villager: no villager with id {} in the database\".format(\n idx + 1, villagers_list[idx]\n )\n )\n\n return dat\n\n for i in range(len(villagers_list)):\n va = query_nth_villager_data(i)\n curr_row = []\n for j in range(len(villagers_list)):\n vb = query_nth_villager_data(j)\n curr_row.append(calc_villager_compatibility(va, vb))\n comp_matrix.append(curr_row)\n\n return comp_matrix\n\n\ndef evaluate_compatibility(comp_mark):\n # type: (List[CompatibilityScoreMark]) -> Compatibility\n from collections import Counter\n assert len(comp_mark) == 3\n counts = Counter(comp_mark)\n\n def test_good_compatibility():\n return (\n (\n counts[CompatibilityScoreMark.HEART] >= 2\n ) or (\n counts[CompatibilityScoreMark.HEART] == 1 and\n counts[CompatibilityScoreMark.DIAMOND] == 1 and\n counts[CompatibilityScoreMark.CLOVER] == 1\n ) or (\n counts[CompatibilityScoreMark.HEART] == 1 and\n counts[CompatibilityScoreMark.DIAMOND] == 2\n )\n )\n\n def test_bad_compatibility():\n return counts[CompatibilityScoreMark.CROSS] >= 2\n\n if test_good_compatibility():\n return Compatibility.GOOD\n elif test_bad_compatibility():\n return Compatibility.BAD\n else:\n return Compatibility.AVERAGE\n\n\ndef get_data_dir_path():\n return os.path.join(os.path.dirname(__file__), os.path.pardir, \"data\")\n\n\ndef load_personality_compatibility_data():\n data_dir_path = get_data_dir_path()\n with open(os.path.join(data_dir_path, \"personality_compatibility.json\"), \"r\") as _fp:\n data = json.load(_fp) # type: Dict[str,Dict[str,str]]\n for p1, p2_comp in data.items():\n p1_enum = getattr(Personality, p1)\n assert p1_enum\n for p2, comp in p2_comp.items():\n p2_enum = getattr(Personality, p2)\n assert p2_enum\n _personality_comp_score_matrix[p1_enum][p2_enum] = get_compatibility_score_by_unicode_sign(comp)\n\n\nload_personality_compatibility_data()\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"397476382","text":"#Import necessary tools\r\nimport numpy as np\nimport easygui\r\nimport tables\r\nimport os\r\n\r\n#Get name of directory where the data files and hdf5 file sits, and change to that directory for processing\r\ndir_name = easygui.diropenbox()\r\nos.chdir(dir_name)\r\n\r\n#Look for the hdf5 file in the directory\r\nfile_list = os.listdir('./')\r\nhdf5_name = ''\r\nfor files in file_list:\r\n\tif files[-2:] == 'h5':\r\n\t\thdf5_name = files\r\n\r\n#Open the hdf5 file\r\nhf5 = tables.open_file(hdf5_name, 'r+')\n\n# Grab the names of the arrays containing digital inputs, and pull the data into a numpy array\ndig_in_nodes = hf5.list_nodes('/digital_in')\ndig_in = []\ndig_in_pathname = []\nfor node in dig_in_nodes:\n\tdig_in_pathname.append(node._v_pathname)\n\texec(\"dig_in.append(hf5.root.digital_in.%s[:])\" % dig_in_pathname[-1].split('/')[-1])\ndig_in = np.array(dig_in)\n\n# Get the stimulus delivery times - take the end of the stimulus pulse as the time of delivery\ndig_on = []\nfor i in range(len(dig_in)):\n\tdig_on.append(np.where(dig_in[i,:] == 1)[0])\nchange_points = []\nfor on_times in dig_on:\n\tchanges = []\n\tfor j in range(len(on_times) - 1):\n\t\tif np.abs(on_times[j] - on_times[j+1]) > 30:\n\t\t\tchanges.append(on_times[j])\n\ttry:\n\t\tchanges.append(on_times[-1]) # append the last trial which will be missed by this method\n\texcept:\n\t\tpass # Continue without appending anything if this port wasn't on at all\n\tchange_points.append(changes)\n\n# Show the user the number of trials on each digital input channel, and ask them to confirm\ncheck = easygui.ynbox(msg = 'Digital input channels: ' + str(dig_in_pathname) + '\\n' + 'No. of trials: ' + str([len(changes) for changes in change_points]), title = 'Check and confirm the number of trials detected on digital input channels')\n\n# Go ahead only if the user approves by saying yes\nif check:\n\tpass\nelse:\n\tprint(\"Well, if you don't agree, blech_clust can't do much!\")\n\tsys.exit()\n\n# Ask the user which digital input channels should be used for slicing out LFP arrays, and convert the channel numbers into integers for pulling stuff out of change_points\ndig_in_channels = easygui.multchoicebox(msg = 'Which digital input channels should be used to slice out LFP data trial-wise?', choices = ([path for path in dig_in_pathname]))\ndig_in_channel_nums = []\nfor i in range(len(dig_in_pathname)):\n\tif dig_in_pathname[i] in dig_in_channels:\n\t\tdig_in_channel_nums.append(i)\n\n# Ask the user for the pre and post stimulus durations to be pulled out, and convert to integers\ndurations = easygui.multenterbox(msg = 'What are the signal durations pre and post stimulus that you want to pull out', fields = ['Pre stimulus (ms)', 'Post stimulus (ms)'])\nfor i in range(len(durations)):\n\tdurations[i] = int(durations[i])\n\n# Grab the names of the arrays containing LFP recordings\nlfp_nodes = hf5.list_nodes('/raw_LFP')\n\n# Make the Parsed_LFP node in the hdf5 file if it doesn't exist, else move on\ntry:\n\thf5.remove_node('/Parsed_LFP', recursive = True)\nexcept:\n\tpass\nhf5.create_group('/', 'Parsed_LFP')\n\n# Run through the tastes\nfor i in range(len(dig_in_channels)):\n\tnum_electrodes = len(lfp_nodes) \n\tnum_trials = len(change_points[dig_in_channel_nums[i]])\n\tthis_taste_LFPs = np.zeros((num_electrodes, num_trials, durations[0] + durations[1]))\n\tfor electrode in range(num_electrodes):\n\t\tfor j in range(len(change_points[dig_in_channel_nums[i]])):\n\t\t\tthis_taste_LFPs[electrode, j, :] = np.mean(lfp_nodes[electrode][change_points[dig_in_channel_nums[i]][j] - durations[0]*30:change_points[dig_in_channel_nums[i]][j] + durations[1]*30].reshape((-1, 30)), axis = 1)\n\t\n\t# Put the LFP data for this taste in hdf5 file under /Parsed_LFP\n\thf5.create_array('/Parsed_LFP', 'dig_in_%i_LFPs' % (dig_in_channel_nums[i]), this_taste_LFPs)\n\thf5.flush()\n\t\t\t\n\n# ASk people if they want to delete rawLFPs or not, that way we offer the option to run analyses in many different ways. (ie. First half V back half)\n\nmsg = \"Do you want to delete the Raw LFP data?\"\nrawLFPdelete = easygui.buttonbox(msg,choices = [\"Yes\",\"No\"])\n\nif rawLFPdelete == \"Yes\":\n\t#Delete data\n\thf5.remove_node('/raw_LFP', recursive = True)\nhf5.flush()\n\nhf5.close()\n\n","sub_path":"3. Generalized/Old/New_Trial_Parse.py","file_name":"New_Trial_Parse.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"452214432","text":"# by amounra 0216 : http://www.aumhaa.com\n# written against Live 9.6 release on 021516\n\nfrom __future__ import absolute_import, print_function\n\nfrom aumhaa.v2.base.debug import *\n\ndebug = initialize_debug()\n\n\nclass PRODUCTS:\n\tBRAIN = 1\n\tOHM64 = 2\n\tBLOCK = 3\n\tCODE = 4\n\tMCD = 5 \n\tMCP = 6 \n\tOHMRGB = 7\n\tCNTRLR = 8\n\tBRAIN2 = 9\n\tENLIGHTEN = 10\n\tALIAS8 = 11\n\tBASE = 12\n\tBRAINJR = 13\n\tDS1 = 16\n\tBASEII = 17\n\tMINIM = 21\n\nLIVID_RGB_COLORMAP = [2, 64, 4, 8, 16, 127, 32]\n\nQUERYSURFACE = (240, 126, 127, 6, 1, 247)\n\nNEWQUERYSURFACE = (240, 0, 1, 97, 0, 7, 8, 247)\n\nCALLS = {'set_local_control':8,\n\t\t'set_pad_pressure_output_type':10,\n\t\t'set_encoder_mapping':11,\n\t\t'reverse_crossfader':15,\n\t\t'set_encoder_encosion_mode':17,\n\t\t'set_encoder_speed':30,\n\t\t'set_fader_led_colors':61,\n\t\t'set_streaming_enabled':62,\n\t\t'set_pad_output_type':66,\n\t\t'set_function_button_leds_linked':68,\n\t\t'set_capacitive_fader_note_output_enabled':69,\n\t\t}\n\ndef fallback_send_midi(message = None, *a, **k):\n\tdebug('control surface not assigned to the sysex call:', message);\n\n\ndef get_call_type(call_type):\n\t#debug('call type is:', call_type)\n\tif call_type in CALLS:\n\t\treturn [CALLS[call_type]]\n\telse:\n\t\treturn False\n\n\n\nclass LividSettings(object):\n\n\n\tdef __init__(self, prefix = [240, 0, 1, 97], model = None, control_surface = None, *a, **k):\n\t\tsuper(LividSettings, self).__init__()\n\t\tself._prefix = prefix\n\t\tself._model = [model]\n\t\tself._send_midi = control_surface._send_midi if control_surface else fallback_send_midi\n\t\tfor keyword, value in k.iteritems():\n\t\t\tsetattr(self, keyword, value)\n\t\n\n\tdef query_surface(self):\n\t\tself._send_midi(QUERYSURFACE)\n\t\n\n\tdef new_query_surface(self):\n\t\tself._send_midi(NEWQUERYSURFACE)\n\t\n\n\tdef set_model(self, model):\n\t\tself._model = [model]\n\t\n\n\tdef send(self, call = None, message = [], *a, **k):\n\t\tcall = get_call_type(call)\n\t\tif call:\n\t\t\tmessage = self._prefix + self._model + call + message + [247]\n\t\t\tself._send_midi(tuple(message))\n\t\telse:\n\t\t\tdebug(call, 'is not a valid lividsettings call')\n\t\n\n\nclass DescriptorBank(object):\n\n\n\tdef __init__(self, name = None, *a, **k):\n\t\tsuper(DescriptorBank, self).__init__()\n\t\n\n\n\n\n\n\n\n\n\n","sub_path":"aumhaa/v2/livid/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"50967790","text":"# Copyright 2008 Jens Scheffler\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 datastore_base import DatastoreSqlStub\nfrom datastore_sqlite_stub import PRMHelper\nfrom google.appengine.api import apiproxy_stub_map\nfrom google.appengine.api import datastore_file_stub\nfrom pysqlite2 import dbapi2 as sqlite\n\n\ndef setup_refstore(app_id='test'):\n \"\"\"Sets up a clean \"reference\" store (file-based implementation.\"\"\"\n stub = datastore_file_stub.DatastoreFileStub(app_id, None, None)\n apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)\n\ndef setup_sqlite(name=None):\n \"\"\"Sets up an in-memory sqlite instance \n and connects the datastore to it.\n \n Args:\n name: the name of the instance to connect to, \n None or empty string for in-memory\n \n Returns:\n a sqlite connection object pointing to the database.\n \"\"\"\n if name:\n raise 'Not implemented yet'\n else:\n connection = sqlite.connect(':memory:')\n name = 'memory'\n get_connection = lambda: connection\n release_connection = lambda x: None \n prm_helper = PRMHelper(get_connection, release_connection)\n stub = DatastoreSqlStub(prm_helper)\n apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', stub)\n return connection\n\n\ndef teardown_sqlite():\n \"\"\"Used by unit-tests to disconnect and unregister \n the sqlite stub.\"\"\"\n proxy = apiproxy_stub_map.apiproxy\n proxy._APIProxyStubMap__stub_map.pop('datastore_v3')\n \n\ndef create_tabledef(connection, model_instance, prm_helper=None):\n \"\"\"Create a SQL statement to populate a table \n from a fully populated Model.\n \n Args:\n connection: a database connection that should be used\n model_instance: an instance of a model, \n each field filled with a non-None value\n prm_helper: an object that contains logic \n about how protocl-buffers\n should be mapped to a relational datastore\n \n Returns:\n a SQL statement that could be used to create a new table.\n \"\"\"\n \n # Make sure the helper exists\n if not prm_helper:\n prm_helper = PRMHelper(None, None)\n \n # Convert the model into a map of propert key/value pairs\n entity = model_instance._populate_internal_entity()\n pb = entity._ToPb()\n as_dict = prm_helper.entityToDict(pb)\n \n # Delegate to the prm-helper\n return prm_helper.suggestMutation(\n connection, model_instance.kind(), as_dict)[0]\n \n \ndef create_tables(list_of_models, connection):\n \"\"\"Creates one or more SQL tables \n from a list of prepopulated models.\n \n Args:\n list_of_models: a list of models, each of a different kind\n connection: the SQLite connection that should be used\n \"\"\"\n cursor = connection.cursor()\n ok = False\n try:\n for model in list_of_models:\n tabledef = create_tabledef(connection, model)\n cursor.execute(tabledef)\n ok = True\n finally:\n if ok:\n connection.commit()\n else:\n connection.rollback()\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"609047676","text":"#!/usr/bin/python3\n\nimport multiprocessing\nimport glob\nimport scipy as sp\nfrom scipy import stats\nimport nibabel as nib\nimport matplotlib.pyplot as plt\nfrom optparse import OptionParser\nfrom datetime import datetime\n\ndef add(img_data):\n\n\treturn sp.mean(img_data), sp.mean(img_data) * 2\t\n\ndef lin_fit(img_data):\n# actual fitting function\n# linear fitting after taking natural logarithm\n\tte = 8\n\tne = 8\n\tTE_data = []\n\tfor i in range(int(float(ne))):\n\t\tTE_data.append((i+1) * int(float(te)))\n\tln_data = sp.log(img_data[:])\n\tslope, intercept, r_value, p_value, std_err = stats.linregress(TE_data, ln_data)\t\n\treturn -1/slope, r_value\n\n\ndef fit(in_data, output, num):\n# basically numpy apply_along_axis for parts of data\n\taxis = 3\n\tout_part = sp.apply_along_axis(add, axis, in_data)\n\toutput.put((num, out_part))\n\n\ndef multifit(data):\n# cuts nifti to smaller chunks and distributes to CPUs\n\tworkers = 4\n\tjobs = []\n\toutput = multiprocessing.Queue()\n\tpart = int(128 / workers)\n\tfor i in range(workers):\n\t\tdata_chunk = data[i*part:(i+1)*part,:,:,:]\n\t\tp = multiprocessing.Process(target=fit, args=(data_chunk, output, i))\n\t\tjobs.append(p)\n\t\tp.start()\n\tprint(\"waiting for job\")\n\tout = [output.get() for i in jobs]\n\t\n\tfor job in jobs:\n\t\tjob.join()\n\tprint(\"all jobs done\")\n\tout.sort()\n\tout = [r[1] for r in out]\n\tout = sp.concatenate(out,0)\n\tt2 = out[:,:,:,0]\n\tr2_err = out[:,:,:,1]\n\treturn [t2, r2_err]\n\t\n\n\ndef main():\n\t\n\n\tstartTime = datetime.now()\n\n\tparser = OptionParser()\n\t[opts, args] = parser.parse_args()\n\tnifti = nib.load(\"mems_20180222_01__8NE_.nii\")\n\tdata = nifti.get_data()\n\tpars = {\"te \" : 8, \"ne \" : 8}\n\t#plt.imshow(data[:,:,15,1], cmap=\"gray\")\n\t[t2_fit_data, r2_err_data] = multifit(data)\n\tout_t2 = nib.Nifti1Image(t2_fit_data, nifti.affine, nifti.header)\n\tout_err = nib.Nifti1Image(r2_err_data, nifti.affine, nifti.header)\n\tnib.save(out_t2, \"t2_test.nii\")\n\tnib.save(out_err, \"t2_err_test.nii\")\n\tprint(\"time: \" + str(datetime.now() - startTime))\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"multitest.py","file_name":"multitest.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"532003145","text":"import pandas as pd\nimport numpy as np\nimport os\n\nclass GenericCBA(object):\n \"\"\"Main module class.\n Packages all core concepts and functionality of a cost-benefit analysis.\n\n Usage\n\n GenericCBA.read_parameters() # reads parameters in the form given in a\n # guidebook\n\n # (...)\n # potential manipulation of parameters - testing, sensitivity analysis\n # (...)\n\n GenericCBA.prepare_parameters() # manipulates parameters internally\n # to a form suitable for computation\n GenericCBA.read_project_inputs() # reads project inputs\n\n # (...)\n # potential manipulation of inputs, although setting up separate input\n # files is preferred\n # (...)\n\n GenericCBA.perform_economic_analysis()\n GenericCBA.print_economic_indicators()\n\n GenericCBA.perform_financial_analysis()\n GenericCBA.print_financial_indicators()\n \"\"\"\n\n def __init__(self,\n init_year,\n evaluation_period,\n price_level,\n fin_discount_rate,\n eco_discount_rate,\n currency,\n verbose=False\n ):\n \"\"\"\n Input\n ------\n init_year: int\n The first year of economic analysis\n\n evaluation_period: int\n Duration of evaluation period in years.\n\n price_level: int\n The year in relation to which prices are set.\n\n fin_discount_rate: float\n Discount rate for financial analysis.\n\n eco_discount_rate: float\n Discount rate for economic analysis.\n\n currency: str\n Currency code.\n\n verbose: bool, optional\n Flag to control verbosity.\n\n Returns\n ------\n object\n GenericCBA object.\n \"\"\"\n\n self.yr_i = init_year\n self.N_yr = evaluation_period\n self.yr_f = self.yr_i + self.N_yr - 1\n self.yrs = [i for i in range(self.yr_i, self.yr_i + self.N_yr)]\n\n self.yr_op = None\n self.N_yr_bld = None\n self.N_yr_op = None\n self.yrs_op = None\n\n self.yr_pl = price_level\n\n self.r_fin = fin_discount_rate\n self.r_eco = eco_discount_rate\n\n self.currency = currency\n\n self.verbose = verbose\n\n self.C_fin = None # CAPEX financial\n self.C_eco = None # CAPEX economic\n self.O0_fin = {} # OPEX financial in 0th variant\n self.O0_eco = {} # OPEX economic in 0th variant\n self.O1_fin = {} # OPEX financial in 1st variant\n self.O1_eco = {} # OPEX economic in 1st variant\n self.I0_fin = {} # income financial in 0th variant\n self.I1_fin = {} # income financial in 1st variant\n\n self.UC = {} # unit costs\n self.B0 = {} # benefits in 0th variant\n self.B1 = {} # benefits in 1st variant\n self.NB = {} # net benefits\n self.NC = {} # net costs\n self.NI = {} # net income\n\n # economic indicators\n self.ENPV = None\n self.ERR = None\n self.EBCR = None\n\n # pycba directory\n self.dirn = os.path.dirname(__file__)\n\n def read_parameters(self):\n raise NotImplementedError(\"Function read_parameters is supposed\"\n \"to be defined in the specific \"\n \"implementation\")\n\n def prepare_parameters(self):\n raise NotImplementedError(\"Function prepare_parameters is supposed\"\n \"to be defined in the specific \"\n \"implementation\")\n\n def read_project_inputs(self):\n raise NotImplementedError(\"Function read_project_inputs is supposed\"\n \"to be defined in the specific \"\n \"implementation\")\n\n def perform_economic_analysis(self):\n raise NotImplementedError(\"Function perform_economic_analysis is \"\n \"supposed to be defined in the specific \"\n \"implementation\")\n\n def print_economic_indicators(self):\n print(\"ENPV: %.2f M %s\" % (self.ENPV / 1e6, self.currency.upper()))\n print(\"ERR : %.2f %%\" % (self.ERR * 100))\n print(\"BCR : %.2f\" % self.EBCR)\n\n def perform_financial_analysis(self):\n raise NotImplementedError(\"To be added.\")\n\n def print_financial_indicators(self):\n raise NotImplementedError(\"To be added.\")\n","sub_path":"pycba/genericcba.py","file_name":"genericcba.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"108810409","text":"#!/usr/bin/env python\n\nimport logging\nimport logging.config\n\nlogging.config.fileConfig('logging.conf')\n# create logger\nlogger = logging.getLogger('VSCADA.logger')\n\nlogger.debug('logger program starts')\n\nimport vserver\nlogger.info('check TSV')\nlogger.info('send TSI signal')\nlogger.info('check motor')\nlogger.warn('the motor is not connected')\nlogger.info('start the server')\nvserver.run()\nlogger.debug('startup program ends')\n\n","sub_path":"vscada 2_22_17/vscada/example/daemon/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"149905773","text":"import sqlite3\r\nimport os\r\nimport time\r\nfrom os import path\r\nfrom RecordParser.MsgInfoAcquire import MsgProcess\r\nfrom RecordParser.CommonParse import BytesProcessOutsideException\r\nfrom RecordParser.MsgInfoAcquire import ErrorEscapeException\r\n\r\n'''\r\n 该脚本用于验证多个记录文件,按照时间顺序分别存储于不同的月份表中\r\n 注意:这里基本明确的数据库的创建基于 “ 车组号+端号 ”\r\n'''\r\n\r\n# Create the database and table\r\ndata_base2 = sqlite3.connect('CR400BF_5113_01_record_base')\r\ncursor2 = data_base2.cursor()\r\n\r\ndata_base = sqlite3.connect('CR400BF_5113_08_record_base')\r\ncursor = data_base.cursor()\r\n\r\n\r\n# 根据日志时间创���表\r\ndef create_table_in_month(cr, db, tbl_name):\r\n cr.execute('CREATE TABLE IF NOT EXISTS \"%s\" ('\r\n 'T_ATOUTC int,' # UTC日历时间\r\n 'N_CYCLE int,'\r\n 'NID_MODLE int,'\r\n 'Q_HOT_STANDBY int,'\r\n 'T_ATO int,'\r\n 'M_POS int,'\r\n 'V_SPEED int,'\r\n 'M_ATOMODE int,'\r\n 'L_MESSAGE int,'\r\n 'MSG_CONTENT text,'\r\n 'PRIMARY KEY (T_ATOUTC, N_CYCLE, Q_HOT_STANDBY)' # 考虑时间、周期、主备系作为主键\r\n ')' % tbl_name) # 占位符写在字符串中,最后再写变量\r\n\r\n db.commit()\r\n\r\n\r\n# 获取当前路径下所有记录的纪录路径\r\ndef get_all_log_files(file_list=list, root_path=str):\r\n files = os.listdir(root_path)\r\n for fileName in files:\r\n\r\n full_path = path.join(root_path, fileName)\r\n if path.isdir(full_path):\r\n get_all_log_files(file_list, full_path)\r\n else:\r\n if '.txt' in full_path:\r\n file_list.append(full_path)\r\n print(full_path)\r\n else:\r\n pass\r\n return file_list\r\n\r\n\r\n# 根据UTC时间获得表名,格式201905到月份\r\ndef get_tbl_name_by_utctime(utc_time=int):\r\n log_time = time.localtime(utc_time)\r\n if log_time.tm_mon < 10:\r\n return str(log_time.tm_year)+'0' + str(log_time.tm_mon)\r\n else:\r\n return str(log_time.tm_year) + str(log_time.tm_mon)\r\n\r\n\r\n# 将指定路径下信息按照日期分类写入数据库\r\ndef insert_record_in_date(log_path=str):\r\n with open(log_path, mode='r', errors='ignore') as f:\r\n for line in f:\r\n try:\r\n l_stream = line.split()[0]\r\n msg_info = MsgProcess(l_stream)\r\n msg_info.msg_head_process() # 解析出消息头(先反转义再解析)\r\n # 选择相应的数据表\r\n tbl_name = get_tbl_name_by_utctime(msg_info.t_atoutc)\r\n # 数据库插入变量按照 execute('INSERT INTO table_name('%d','%s')'%(var1,var2)) 字符串后结束语句再跟命令\r\n cursor.execute('INSERT OR IGNORE INTO \"%s\" VALUES (\"%d\", \"%d\", \"%d\", \"%d\", \"%d\", \"%d\", \"%d\",'\r\n ' \"%d\", \"%d\", \"%s\")' % (tbl_name, msg_info.t_atoutc, msg_info.n_cycle,\r\n msg_info.nid_modle,msg_info.q_standby, msg_info.t_ato,\r\n msg_info.m_pos, msg_info.v_speed, msg_info.m_atomode,\r\n msg_info.l_message, msg_info.msg_content))\r\n # 捕获转义异常\r\n except ErrorEscapeException as err:\r\n print(err)\r\n # 捕获字节流解析异常\r\n except BytesProcessOutsideException as err:\r\n print(err)\r\n # 捕获索引异常\r\n except IndexError as err:\r\n print(err)\r\n print('line: '+line)\r\n\r\n data_base.commit()\r\n\r\n\r\n# 创建存储表\r\nfor dt in ['201901', '201902', '201903', '201904', '201905', '201905',\r\n '201906', '201907', '201910', '201911', '201912']:\r\n create_table_in_month(cursor2, data_base2, dt)\r\n create_table_in_month(cursor, data_base, dt)\r\n\r\n\r\n# 初始化路径\r\nrootPath = os.getcwd()\r\nprint(rootPath)\r\nfileArray = []\r\n\r\n\r\n# 获取路径下所有记录并写入数据库\r\nfileArray = get_all_log_files(fileArray, rootPath)\r\nfor f in fileArray:\r\n insert_record_in_date(f)\r\n","sub_path":"Part4_MultiTableStore.py","file_name":"Part4_MultiTableStore.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"17209471","text":"import os\nimport numpy as np\nimport json\nfrom PIL import Image\n\n\n# set the path to the downloaded data:\ndata_path = './data/RedLights2011_Medium'\n\n# set a path for saving predictions:\npreds_path = './data/hw02_preds'\nanno_path = './data/hw02_annotations'\n\n# get sorted list of files:\nfile_names = sorted(os.listdir(data_path))\n\n# remove any non-JPEG files:\nfile_names = [f for f in file_names if '.jpg' in f]\n\n# save preds (overwrites any previous predictions!)\n\n\nwith open(os.path.join(anno_path,'annotations_train.json'),'r') as f_a:\n data_a = json.load(f_a)\n with open(os.path.join(preds_path,'preds_train_redlight1.json'),'r') as f_t:\n data_t = json.load(f_t)\n\n # Visualiza all the results\n count = 0\n for img_name in data_a:\n I = Image.open(os.path.join(data_path,img_name))\n I = np.array(I)\n h, w, _ = I.shape\n bounding_boxes = data_a[img_name]\n for b in bounding_boxes:\n [tl_row,tl_col,br_row,br_col] = b[:4]\n tl_row = int(tl_row)\n tl_col = int(tl_col)\n br_row = int(min(br_row,h))\n br_col = int(min(br_col,w))\n I[tl_row:br_row, tl_col, :] = [0,255,0]\n I[tl_row:br_row, br_col-1, :] = [0,255,0]\n I[tl_row, tl_col:br_col, :] = [0,255,0]\n I[br_row-1, tl_col:br_col, :] = [0,255,0]\n\n bounding_boxes = data_t[img_name]\n for b in bounding_boxes:\n [tl_row,tl_col,br_row,br_col] = b[:4]\n tl_row = int(tl_row)\n tl_col = int(tl_col)\n br_row = int(min(br_row,h))\n br_col = int(min(br_col,w))\n I[tl_row:br_row, tl_col, :] = [0,0,255]\n I[tl_row:br_row, br_col-1, :] = [0,0,255]\n I[tl_row, tl_col:br_col, :] = [0,0,255]\n I[br_row-1, tl_col:br_col, :] = [0,0,255]\n img = Image.fromarray(I, 'RGB')\n img.save(os.path.join(preds_path,img_name))\n\n count += 1\n if count > 10:\n break\n","sub_path":"visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"40383607","text":"# coding=utf-8\nimport os\nimport subprocess\nimport digits\nimport yaml\nimport time\nfrom kubernetes import client, config\n\n\nclass KubernetasCoord(object):\n\n def __init__(self, logger):\n self.logger = logger\n config.load_kube_config()\n self.v1 = client.CoreV1Api()\n\n @staticmethod\n def get_pod_name(job_id):\n return \"digits-%s\" % job_id\n\n def get_pods_status(self, pod_label):\n \"\"\"\n 根据job_id获取pod状态信息\n :param job_id:\n :return:\n \"\"\"\n\n resp = self.v1.list_namespaced_pod(namespace='default', label_selector='app=%s' % pod_label)\n status_list = []\n for i in resp.items:\n status_list.append(i.status.phase)\n return status_list\n\n @staticmethod\n def generate_yaml(job_dir, pod_label, node_count, gpu_count):\n \"\"\"\n 根据用户参数生成用于创建容器组的yaml配置文件\n :param job_dir: job路径\n :param pod_label:\n :param node_count: 节点数量\n :param gpu_count: 每个节点GPU数量\n :return: 生成的yaml文件的路径\n \"\"\"\n\n digits_path = os.path.dirname(digits.__file__)\n yaml_path = os.path.join(digits_path, 'tools/k8s/mpi_node_base.yaml')\n new_yaml_path = os.path.join(job_dir, 'mpi-nodes.yaml')\n name = pod_label\n\n # 读取mpi_node_base.yaml中的内容,并将可修改的参数进行替换,保存成新的yaml文件\n with open(yaml_path, mode='r+') as r_file:\n with open(new_yaml_path, 'w+') as w_file:\n for line in r_file.readlines():\n if line.find(\"$name$\") >= 0:\n new_line = line.replace(\"$name$\", name)\n w_file.write(new_line)\n elif line.find(\"$label$\") >= 0:\n new_line = line.replace(\"$label$\", name)\n w_file.write(new_line)\n elif line.find(\"$node_count$\") >= 0:\n new_line = line.replace(\"$node_count$\", '%d' % node_count)\n w_file.write(new_line)\n elif line.find(\"$gpu_count$\") >= 0:\n new_line = line.replace(\"$gpu_count$\", '%d' % gpu_count)\n w_file.write(new_line)\n else:\n w_file.write(line)\n return new_yaml_path\n\n def create_deployment(self, yaml_path, pod_label):\n \"\"\"\n 创建deployment类型的容器组\n :param yaml_path: yaml文件路径\n :param pod_label: 容器组label\n :return: 无\n \"\"\"\n\n # 读取yaml文件\n with open(yaml_path) as f:\n dep = yaml.load(f)\n resp = client.ExtensionsV1beta1Api().create_namespaced_deployment(body=dep, namespace=\"default\")\n self.logger.info(\"Deployment created. status='%s'\" % str(resp.status))\n running = False\n\n # 由于容器组启动需要一定时间,使用轮询判断deployment是否成功启动\n # 当所有容器都启动成功时,running设置为True,退出循环,结束轮询\n while not running:\n # 轮询时间间隔为1秒\n time.sleep(1)\n # 获取deployment创建状态\n status = self.get_pods_status(pod_label=pod_label)\n if len(status) > 0:\n self.logger.info(status)\n running = True\n for stat in status:\n # 如果有任何一个容器状态不为Running,表示未全部成功启动\n if not stat == 'Running':\n # 未全部成功启动,需要继续轮询\n running = False\n break\n self.logger.info(\"Deployment created successfully!\")\n\n @staticmethod\n def delete_deployment(name):\n \"\"\"\n 删除deployment\n :param name: 要删除的deployment的name\n :return: 无\n \"\"\"\n # Delete deployment\n api_response = client.ExtensionsV1beta1Api().delete_namespaced_deployment(\n name=name,\n namespace=\"default\",\n body=client.V1DeleteOptions(\n propagation_policy='Foreground',\n grace_period_seconds=5))\n print(\"Deployment deleted. status='%s'\" % str(api_response.status))\n\n def generate_hostfile(self, pod_label, slots, job_dir):\n resp = self.v1.list_namespaced_pod(namespace='default', label_selector='app=%s' % pod_label)\n lines = []\n for i in resp.items:\n lines.append('%s slots=%d'% (i.status.pod_ip, slots))\n hostfile_path = os.path.join(job_dir, 'hostfile')\n f = open(hostfile_path, 'w')\n lines = [line + '\\n' for line in lines]\n f.writelines(lines)\n f.close()\n\n def container_prepare(self, job_id, job_dir='/home/nfsdir/nfsdir/zyf', node_count=1, gpu_count=1, slots=1):\n pod_label = self.get_pod_name(job_id)\n yaml_path = self.generate_yaml(job_dir=job_dir, pod_label=pod_label, node_count=node_count, gpu_count=gpu_count)\n self.create_deployment(yaml_path, pod_label=pod_label)\n self.generate_hostfile(pod_label=pod_label, slots=slots, job_dir=job_dir)\n\n @staticmethod\n def delete_pods(job_id):\n KubernetasCoord.delete_deployment(name=KubernetasCoord.get_pod_name(job_id))\n\n","sub_path":"digits/tools/k8s/k8s_coordinate.py","file_name":"k8s_coordinate.py","file_ext":"py","file_size_in_byte":5397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"114076340","text":"\"\"\"Labels model.\"\"\"\nfrom django.db import models\nfrom django.urls import reverse_lazy\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass Label(models.Model):\n \"\"\"Label model.\"\"\"\n\n name = models.CharField(\n max_length=100,\n unique=True,\n db_index=True,\n verbose_name=_('LabelName'),\n help_text=_('HelpLabelFieldText'),\n error_messages={\n 'unique': _('LabelWithThisNameAlreadyExist'),\n 'blank': _('ThisFieldCannotBeBlank'),\n },\n )\n created_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self) -> str:\n \"\"\"\n String representation.\n\n Returns:\n str:\n \"\"\"\n return self.name\n\n def get_absolute_url(self): # noqa: D102\n return reverse_lazy('labels')\n\n class Meta(object):\n \"\"\"Meta information.\"\"\"\n\n verbose_name = _('Label')\n verbose_name_plural = _('Labels')\n ordering = ['name']\n","sub_path":"task_manager/labels/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"454256465","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n\nimport jieba\nfrom collections import Counter\nimport matplotlib.pyplot as plt\n\nTOKEN = []\n\nwords_count = {}\n\n\ndef cut(string):\n return list(jieba.cut(string))\n\n\nfor i, line in enumerate((open('article_9k.txt'))):\n if i > 100000: break\n TOKEN += cut(line)\n\nwords_count = Counter(TOKEN)\n\n\n# for word, f in words_count.most_common(100):\n# print(word, f)\n\n\n# frequiences = [f for w, f in words_count.most_common(10000)]\n#\n# x = [i for i in range(10000)]\n#\n# plt.plot(x, frequiences)\n#\n# plt.show()\n\n\ndef prob_1(word):\n return words_count.get(word, 0) / len(TOKEN)\n\n\nprint(prob_1('我们'))\n\nTOKEN = [str(t) for t in TOKEN]\n\n# TOKEN = ['此外', '自', '本周', '6', '月', '12', '日起', '除', '小米', '手机']\nTOKEN_2_GRAM = [''.join(TOKEN[i:i + 2]) for i in range(len(TOKEN[:-1]))]\nprint(len(TOKEN))\nprint(len(TOKEN_2_GRAM))\nwords_count_2 = Counter(TOKEN_2_GRAM)\n\n\ndef prob_2(word1, word2):\n if word1 + word2 in words_count_2:\n return words_count_2[word1 + word2] / len(TOKEN_2_GRAM)\n else:\n return (prob_1(word1) + prob_1(word2)) / 2\n\n\nprint(prob_2('我们', '的'))\n\n\ndef get_probablity(sentence):\n words = cut(sentence)\n sentence_pro = 1\n for i, word in enumerate(words[:-1]):\n next_ = words[i + 1]\n print(word, next_)\n probablity = prob_2(word, next_)\n sentence_pro *= probablity\n print('sentence_pro:', sentence_pro)\n return sentence_pro\n\n\nif __name__ == '__main__':\n sentence = \"小明抽到一台苹果手机\"\n get_probablity(sentence)\n sentence = \"小明抽到一台波音飞机\"\n get_probablity(sentence)\n sentence = \"洋葱奶昔来一杯\"\n get_probablity(sentence)\n sentence = \"养乐多绿茶来一杯\"\n get_probablity(sentence)\n\n need_compared = [\n \"今天晚上请你吃大餐,我们晚上一起吃日料 明天晚上请你吃大餐,我们一起吃苹果\",\n \"真事\"\n \"一只好看的小猫 真是一只好看的小猫\",\n \"今天我去吃火锅 今晚火锅去吃我\",\n \"洋葱奶昔来一杯 奶茶来一杯\"\n ]\n for s in need_compared:\n s1, s2 = s.split()\n p1, p2 = get_probablity(s1), get_probablity(s2)\n better = s1 if p1 > p2 else s2\n print('{} is more possible'.format(better))\n print('-' * 4 + ' {} with probility {}'.format(s1, p1))\n print('-' * 4 + ' {} with probility {}'.format(s2, p2))\n","sub_path":"ch01/language_model.py","file_name":"language_model.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206797984","text":"# Convert string of roman numerals to a base 10 integer in decimal notation\n# Runs in O(len(roman_numeral_str)) time and O(1) extra space complexity\n\n# NOTE: Unlike the EPI solution, mine validates the roman numeral string.\n\nVALUE_MAP = {\n 'I': 1,\n 'V': 5,\n 'X': 10,\n 'L': 50,\n 'C': 100,\n 'D': 500,\n 'M': 1000\n}\n\ndef roman_to_decimal(roman_numeral_str):\n result, prev_value = 0, 0\n for char in reversed(roman_numeral_str):\n value = VALUE_MAP[char]\n if prev_value and (value / prev_value == 0.2 or value / prev_value == 0.1):\n result -= value\n elif value < prev_value:\n raise ValueError('Invalid roman numeral string')\n else:\n result += value\n\n prev_value = value\n\n return result\n\nprint(roman_to_decimal('LIX') == 59)\nprint(roman_to_decimal('LVIIII') == 59)\nprint(roman_to_decimal('XXXXXIIIIIIIII') == 59)\nprint(roman_to_decimal('XVX')) # Should raise ValueError\n","sub_path":"py/roman_to_decimal.py","file_name":"roman_to_decimal.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"545386535","text":"\"\"\"\nAnimation of moviment of the vehicle.\n\nAuthor: Gustavo Muller Nunes\n\"\"\"\nimport math\nimport numpy as np\nfrom scipy.spatial.distance import pdist, squareform\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport scipy.integrate as integrate\nimport matplotlib.animation as animation\n\nclass VehicleMovePlot(object):\n '''\n Show animated move of a list of points or update plot with real time\n data.\n\n Arguments:\n points: list of points with 3 columns [x, y, orientation]\n '''\n def __init__(self, points=None, interval=100):\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111, xlim=(-10, 100), ylim=(-10, 100))\n self.ax.grid(True)\n\n if points is not None:\n self.points = np.array(points)\n self.ani = animation.FuncAnimation(self.fig, self.animate,\n frames=len(points),\n interval=interval, blit=True)\n\n def animate(self, i):\n x = self.points[0:i+1, 0]\n y = self.points[0:i+1, 1]\n orientation = self.points[0:i+1, 2]\n\n # Create previous points\n self.p1, = self.ax.plot(x, y, 'bo', ms=5, alpha=0.3, color='#4588b2')\n\n # Create actual point\n self.p2, = self.ax.plot(x[-1], y[-1], 'bo', ms=10, alpha=0.7, color='#4588b2')\n\n # Create orientation arrow\n ARROW_SIZE = 1.8\n ARROW_WIDTH = 0.6\n ax_xlim = self.ax.get_xlim()\n ax_ylim = self.ax.get_ylim()\n arrow_xsize = ARROW_SIZE * (ax_xlim[1] - ax_xlim[0]) / 50\n arrow_xsize *= math.cos(orientation[-1])\n arrow_ysize = ARROW_SIZE * (ax_ylim[1] - ax_ylim[0]) / 50\n arrow_ysize *= math.sin(orientation[-1])\n arrow_width = min(arrow_xsize, arrow_ysize) * ARROW_WIDTH / 2\n\n arrow = plt.Arrow(x[-1], y[-1], arrow_xsize, arrow_ysize, alpha=0.8,\n facecolor='#356989', edgecolor='#356989', width=arrow_width)\n self.p3 = self.ax.add_patch(arrow)\n\n return self.p1, self.p2, self.p3\n\n def show(self):\n plt.show()\n\n def reset(self):\n pass\n\n def update(self, points):\n self.points = np.array(points)\n x = self.points[0:, 0]\n y = self.points[0:, 1]\n orientation = self.points[0:, 2]\n\n # Create previous points\n p1, = self.ax.plot(x, y, 'bo', ms=5, alpha=0.3, color='#4588b2')\n\n # Create actual point\n p2, = self.ax.plot(x[-1], y[-1], 'bo', ms=10, alpha=0.7, color='#4588b2')\n\n # Create orientation arrow\n ax_xlim = self.ax.get_xlim()\n ax_ylim = self.ax.get_ylim()\n arrow_xsize = 2* (ax_xlim[1] - ax_xlim[0]) / 50\n arrow_xsize *= math.cos(math.pi/2 + orientation[-1])\n arrow_ysize = 2* (ax_ylim[1] - ax_ylim[0]) / 50\n arrow_ysize *= math.sin(math.pi/2 + orientation[-1])\n\n arrow = plt.Arrow(x[-1], y[-1], arrow_xsize, arrow_ysize, alpha=0.8,\n facecolor='#356989', edgecolor='#356989')\n p3 = self.ax.add_patch(arrow)\n\n plt.draw()\n return p1, p2, p3\n","sub_path":"AI for Robotics/Exercices/Lesson 3 - Particle Filters/VehicleMovePlot.py","file_name":"VehicleMovePlot.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"116932142","text":"import sys\r\nfrom time import sleep\r\nfrom check import checkFile, returnCheck, checkBook, checkStock\r\nfrom setFile import update_database, create_file\r\nfrom display import mainMenu, showMenu\r\nfrom errorHandle import askInput, askBookID, askExit\r\nfrom calculate import calTotal\r\nfrom login import adminLog\r\n\r\n\r\nadminLog()\r\nwhile True:\r\n\r\n while True:\r\n mainMenu()\r\n userChoice = askInput()\r\n if userChoice == 1:\r\n showMenu()\r\n\r\n elif userChoice == 2:\r\n transaction = \"b\"\r\n showMenu()\r\n break\r\n elif userChoice == 3:\r\n transaction = \"r\"\r\n showMenu()\r\n break\r\n elif userChoice == 4:\r\n print(\"Thank you for using the Library Management System\")\r\n sleep(2)\r\n sys.exit()\r\n break\r\n else:\r\n print(\"Please input valid option!\")\r\n\r\n userID = input(\"Please enter the ibrary id: \")\r\n userName = input(\"Please input your name: \")\r\n tray = []\r\n\r\n while True:\r\n\r\n userInput = askBookID()\r\n\r\n # checks if file already exists\r\n fileInDisk = checkFile(userID, transaction)\r\n\r\n if fileInDisk is False:\r\n if transaction == \"r\":\r\n # doesnt let user return file if it isnt borrowed yet\r\n print(\"This id hasnt borrowed any book yet!\")\r\n else:\r\n if checkStock(userInput) is False:\r\n break\r\n changeType = \"w\"\r\n create_file(\r\n userID, transaction, userInput, userName, changeType\r\n ) # creates borrow file if it doesnt exist\r\n # and updates the database\r\n update_database(transaction, userInput)\r\n tray.append(userInput)\r\n print(\"The book you requested has now been borrowed.\")\r\n\r\n else:\r\n if transaction == \"b\": # only executes if user wants to borrow\r\n if checkStock(userInput) is False:\r\n break\r\n # checks if book already exists in borrow file\r\n bookInFile = checkBook(userID, transaction, userInput)\r\n if bookInFile is True:\r\n print(\"Sorry! You have already borrowed this book.\")\r\n else:\r\n changeType = (\r\n \"a\"\r\n ) # adds book to borrow file if doesnt exists in borrow file\r\n create_file(\r\n userID, transaction, userInput, userName, changeType\r\n ) # appends borrowed book\r\n update_database(transaction, userInput)\r\n print(\"The book you requested has now been borrowed.\")\r\n tray.append(userInput)\r\n else: # only executes if user is returning the book\r\n # checks if this is first time returning the book\r\n returnedBook = returnCheck(userID)\r\n if returnedBook is False:\r\n # checks if the input book is borrowed or not\r\n bookInFile = checkBook(userID, \"b\", userInput)\r\n if bookInFile is False:\r\n print(\"Sorry! You have not borrowed this book yet!.\")\r\n else:\r\n changeType = (\r\n \"w\"\r\n ) # if this is first time and book is borowed then create return file\r\n create_file(\r\n userID, transaction, userInput, userName, changeType\r\n )\r\n # and updates the database\r\n update_database(transaction, userInput)\r\n print(\"Thanks for returning the book!\")\r\n else: # executes if it is not the first time returning the book\r\n bookInFile = checkBook(userID, \"b\", userInput)\r\n if bookInFile is False:\r\n print(\"Sorry! You have not borrowed this book yet!.\")\r\n else:\r\n # checks if the book is already returned or not\r\n bookInFile = checkBook(userID, transaction, userInput)\r\n if bookInFile is True:\r\n print(\"Sorry! You have already returned this book.\")\r\n else: # executes if this isnt first time returning the book nor the book is already returned\r\n changeType = \"a\"\r\n create_file(\r\n userID, transaction, userInput, userName, changeType\r\n ) # appends borrowed book\r\n update_database(transaction, userInput)\r\n print(\"Thanks for returning the book!\")\r\n if transaction == \"b\":\r\n checkExit = askExit()\r\n if checkExit == \"n\":\r\n calTotal(tray, userID)\r\n break\r\n else:\r\n checkExit = askExit()\r\n if checkExit == \"n\":\r\n break\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"300733768","text":"# Perform the necessary imports\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.cluster import KMeans\r\n\r\n# Create scaler: scaler\r\nscaler = StandardScaler()\r\n\r\n# Create KMeans instance: kmeans\r\nkmeans = KMeans(n_clusters = 4)\r\n\r\n# Create pipeline: pipeline\r\npipeline = make_pipeline(scaler, kmeans)\r\n\r\n\r\n\r\n\r\n\r\n\r\n##############################\r\n# Clustering the fish data\r\n###############################\r\n\r\n# Import pandas\r\nimport pandas as pd\r\n\r\n# Fit the pipeline to samples\r\npipeline.fit(samples)\r\n\r\n# Calculate the cluster labels: labels\r\nlabels = pipeline.predict(samples)\r\n\r\n# Create a DataFrame with labels and species as columns: df\r\ndf = pd.DataFrame({'labels': labels, 'species': species})\r\n\r\n# Create crosstab: ct\r\nct = pd.crosstab(df['labels'], df['species'])\r\n\r\n# Display ct\r\nprint(ct)\r\n\r\n\r\n\r\n###############################\r\n# Example Normalizer data\r\n###############################\r\n\r\n# Import Normalizer\r\nfrom sklearn.preprocessing import Normalizer\r\n\r\n# Create a normalizer: normalizer\r\nnormalizer = Normalizer()\r\n\r\n# Create a KMeans model with 10 clusters: kmeans\r\nkmeans = KMeans(n_clusters = 10)\r\n\r\n# Make a pipeline chaining normalizer and kmeans: pipeline\r\npipeline = make_pipeline(normalizer, kmeans)\r\n\r\n# Fit pipeline to the daily price movements\r\npipeline.fit(movements)\r\n\r\n\r\n\r\n# Import pandas\r\nimport pandas as pd\r\n\r\n# Predict the cluster labels: labels\r\nlabels = pipeline.predict(movements)\r\n\r\n# Create a DataFrame aligning labels and companies: df\r\ndf = pd.DataFrame({'labels': labels, 'companies': companies})\r\n\r\n# Display df sorted by cluster label\r\nprint(df.sort_values(['labels']))\r\n\r\n\r\n\r\n","sub_path":"python_career_machine_learning_scientist/02_unsupervised_learning_in_python/clustering_exploration/04_kmeans_with_pipeline.py","file_name":"04_kmeans_with_pipeline.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"92829583","text":"class Point:\r\n # Documentation string\r\n \"\"\"\r\n The class Point represents a #D point\r\n Instance attributes: x,y,z\r\n \"\"\"\r\n #Default object initialization\r\n def __init__(self):\r\n self.mX = 1.1\r\n self.mY = 1.1\r\n self.mZ = 1.1\r\n print( \"call FIRST\\n\")\r\n\r\n #Custom initialization\r\n def __init__(self, x=0.0, y=0.0, z=0.0):\r\n self.mX = x\r\n self.mY = y \r\n self.mZ = z\r\n print( \"call second\\n\")\r\n\t\t #Print out the String of this object's values\r\n def toString(self):\r\n return '({}, {}, {})'.format(str(self.mX),str(self.mY),str(self.mZ))\r\n\r\n #Set new locations for the point\r\n def SetPoint(self, x=None, y=None, z=None):\r\n if x is not None: #this is just a trick\r\n self.mX = x #to only update values\r\n if y is not None: #passed to function only\r\n self.mY = y\r\n if z is not None:\r\n self.mZ = z\r\n\r\n #Returns the distance\r\n def Distance(self, other):\r\n d = (( (other.mX - self.mX) ** 2) \r\n + ((other.mY - self.mY) ** 2) \r\n + ((other.mZ - self.mZ) ** 2)) ** 0.5\r\n return d\r\n\r\n\r\n#Remember this method gets executed sinces its our 'main'\r\ndef main():\r\n p1 = Point()\r\n p2 = Point(4.0, 5.0, -2.0)\r\n p3 = Point(z = 3.0)\r\n\r\n print( p1.toString() )\r\n print( p2.toString() )\r\n print( p3.toString() )\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\t\r\n(0.0, 0.0, 0.0)\r\n(4.0, 5.0, -2.0)\r\n(0.0, 0.0, 3.0)\r\n\r\n","sub_path":"C++_11/hara/java_script/str_funtion (1).py","file_name":"str_funtion (1).py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310934903","text":"# https://leetcode.com/problems/design-linked-list/\n# (707) Design Linked List (DLL implementation)\n\nclass Node(object):\n def __init__(self, val=None, next=None, prev=None):\n self.val = val\n self.next = next\n self.prev = prev\n\nclass MyLinkedList(object):\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def getNode(self, index):\n pointer = self.head\n for i in range(0, index):\n pointer = pointer.next\n return pointer\n\n def get(self, index):\n if index < 0 or index >= self.length:\n return -1\n return self.getNode(index).val\n\n def addAtHead(self, val):\n if self.length == 0:\n self.head = self.tail = Node(val)\n else:\n self.head.prev = Node(val, self.head)\n self.head = self.head.prev\n self.length += 1\n \n def addAtTail(self, val):\n if self.length == 0:\n self.head = self.tail = Node(val)\n else:\n self.tail.next = Node(val, None, self.tail)\n self.tail = self.tail.next\n self.length += 1\n\n def addAtIndex(self, index, val):\n if index <= 0:\n self.addAtHead(val)\n elif index == self.length:\n self.addAtTail(val)\n elif index < self.length:\n pointer = self.getNode(index)\n newNode = Node(val, pointer, pointer.prev)\n pointer.prev.next = newNode\n pointer.prev = newNode\n self.length += 1\n\n def deleteAtIndex(self, index):\n if index < 0 or index >= self.length:\n return\n if self.length == 1:\n self.head = None\n self.tail = None\n else:\n pointer = self.getNode(index)\n if pointer == self.head:\n self.head = self.head.next\n self.head.prev = None\n elif pointer == self.tail:\n self.tail = self.tail.prev\n self.tail.next = None\n else:\n pointer.prev.next, pointer.next.prev = pointer.next, pointer.prev\n self.length -= 1","sub_path":"leetcode/707-2.py","file_name":"707-2.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"467177260","text":"import graphMethods\n\ndef initGraph():\n graph = {}\n\n graphMethods.addVertexToDictionary(graph, 1)\n graphMethods.addVertexToDictionary(graph, 2)\n graphMethods.addVertexToDictionary(graph, 3)\n graphMethods.addVertexToDictionary(graph, 4)\n graphMethods.addVertexToDictionary(graph, 5)\n graphMethods.addVertexToDictionary(graph, 6)\n\n graphMethods.addEdge(graph, 1, 2, 6)\n graphMethods.addEdge(graph, 1, 3, 4)\n\n graphMethods.addEdge(graph, 2, 4, 7)\n graphMethods.addEdge(graph, 2, 5, 4)\n graphMethods.addEdge(graph, 2, 6, 2)\n\n graphMethods.addEdge(graph, 3, 4, 3)\n graphMethods.addEdge(graph, 3, 5, 8)\n\n graphMethods.addEdge(graph, 4, 6, 10)\n\n graphMethods.addEdge(graph, 5, 6, 1)\n\n return graph\n\ndef getItemWithSmallestValue(dictionaty):\n smallest = -1\n smallestKey = -1\n for v in dictionaty:\n current = dictionaty[v]\n if smallest < 0 or smallest > current:\n smallest = current\n smallestKey = v\n return [smallestKey, smallest]\n\n\ndef dijkstra(fromVertex, graph):\n shortestDistanceResult = {}\n resolvedVertexDict = {}\n\n basedVertex = fromVertex\n resolvedVertexDict[fromVertex] = 0\n\n while len(graph) > len(resolvedVertexDict):\n basedVertexRelations = graph[basedVertex]\n for edge in basedVertexRelations:\n vertex = edge[0]\n weight = edge[1]\n\n newDistance = resolvedVertexDict[basedVertex] + weight\n\n if vertex not in shortestDistanceResult or shortestDistanceResult[vertex] > newDistance:\n shortestDistanceResult[vertex] = newDistance\n\n smallestItem = getItemWithSmallestValue(shortestDistanceResult)\n smallestVertexName = smallestItem[0]\n smallestDistance = smallestItem[1]\n\n del shortestDistanceResult[smallestVertexName]\n resolvedVertexDict[smallestVertexName] = smallestDistance\n basedVertex = smallestVertexName\n\n return resolvedVertexDict\n\n\n\ngraph = initGraph()\ngraphMethods.printGraph(graph)\n\n#Task: Find shortest distance from vertex 1 to rest of vertexes\n\nshortestDistances = getShortestDistances(1, graph)\n\nprint(\"Shortest distances from vertex 1 to others are:\")\nprint(shortestDistances)\n\n \n\n \n \n \n\n","sub_path":"Graph/Dijkstra/python/dijkstra.py","file_name":"dijkstra.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"446226650","text":"from concurso import Concurso\nfrom disparo import Disparo\nfrom participante import Participante\n\n \n\ndef dibujar_menu():\n print(\n f\"\"\"\n ======================================\n ======================================\n == MENU ==\n == ==\n == 0 Agregar participante == \n == 1 Mostrar registros ==\n == 2 Mostrar podio ==\n == 3 Mostrar ultimo ==\n == 4 Cantidad participantes ==\n == 5 Ordenar por edad ==\n == 6 Promedio disparos ==\n == 7 Mejores disparos ==\n == 8 Guardar CSV ==\n == 9 Borrar CSV ==\n == 10 Guardar en DB ==\n == 11 Mostrar registros en DB ==\n == 12 Mostrar ganador [POST] ==\n == 13 Salir ==\n ======================================\n ======================================\n \"\"\"\n )\n opcion = input(\"Ingrese una opcion: \")\n return opcion\n\n\ndef seleccionar_opciones(Concurso, opcion):\n \"\"\"\n Recibe un objeto de concurso y una opcion\n Permite seleccionar distintas opciones con sus funcionalidades\n \"\"\"\n opciones = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\"]\n while opcion != \"13\":\n try:\n if opcion == \"0\":\n nombre = input(\"Ingrese nombre del participante: \")\n apellido = input(\"Ingrese apellido del participante: \")\n edad = input(\"Ingrese la edad del participante: \")\n sexo = input(\"Ingrese sexo del participante [F/M]: \").upper()\n participante = Disparo(nombre, apellido, edad, sexo)\n participante.hacer_disparos() \n Concurso.set_disparos(participante.armar_datos())\n elif opcion == \"1\":\n if len(Concurso.get_disparos()) == 0:\n print(\n f\"\"\"\n ==============================================\n == No se encontraron registros ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_registros()\n elif opcion == \"2\":\n if len(Concurso.get_disparos()) < 3:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 3 participantes ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_podio()\n elif opcion == \"3\":\n if len(Concurso.get_disparos()) < 3:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 2 participantes ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_ultimo()\n elif opcion == \"4\":\n Concurso.cantidad_participantes()\n elif opcion == \"5\":\n if len(Concurso.get_disparos()) < 2:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 2 participantes ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_ordenado_por_edad()\n elif opcion == \"6\":\n if len(Concurso.get_disparos()) < 1:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 1 participante ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_promedio_disparo()\n elif opcion == \"7\":\n if len(Concurso.get_disparos()) < 1:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 1 participante ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_mejores_disparos()\n elif opcion == \"8\":\n Concurso.guardar_CSV()\n elif opcion == \"9\":\n Concurso.borrar_CSV()\n elif opcion == \"10\":\n if len(Concurso.get_disparos()) < 1:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 1 participante ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.guardar_DB()\n elif opcion == \"11\":\n Concurso.consultar_todos_DB()\n elif opcion == \"12\":\n if len(Concurso.get_disparos()) < 3:\n print(\n f\"\"\"\n ==============================================\n == Se necesita al menos 3 participantes ==\n ==============================================\n \"\"\"\n )\n else:\n Concurso.mostrar_ganador_POST()\n elif opcion not in opciones:\n print(\n f\"\"\"\n ===================================================\n == Por favor seleccione una opcion correcta ==\n ===================================================\n \"\"\"\n )\n \n \n except FileNotFoundError:\n print(\n f\"\"\"\n ==============================================\n == ERROR: Archivo no encontrado ==\n ==============================================\n \"\"\"\n )\n \n finally:\n opcion = dibujar_menu()\n else:\n print(\n \"\"\"\n SALIENDO........\n \"\"\"\n ) \n \n\ndef iniciar():\n \"\"\"\n Inicia el programa\n Dibuja y contiene la lógica del menú\n \"\"\"\n concurso_disparos = Concurso()\n opcion = dibujar_menu()\n seleccionar_opciones(concurso_disparos, opcion)\n \n \n\niniciar()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"140258061","text":"from django.conf.urls.defaults import *\nfrom django.conf import settings #for MEDIA_ROOT\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Example:\n (r'^', include('base.urls')),\n (r'^', include('tracker.urls')),\n\n # Uncomment the admin/doc line below and add 'django.contrib.admindocs' \n # to INSTALLED_APPS to enable admin documentation:\n (r'^admineral/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n (r'^admineral/', include(admin.site.urls)),\n \n #URLs for django-rpx-plus: \n #url(r'^accounts/$', 'django.views.generic.simple.redirect_to', \n # {'url': '/accounts/profile/', 'permanent': False},\n # name='auth_home'),\n #url(r'^accounts/profile/$', 'tracker.views.edit_user_profile', name='edit_profile'),\n url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', \n {'template_name': 'django_rpx_plus/logged_out.html'}, \n name='auth_logout'),\n #url(r'^accounts/associate/delete/(\\d+)/$', tracker.views.delete_associated_login, name='delete-associated-login'),\n (r'^accounts/', include('django_rpx_plus.urls')),\n\n #Temporary fix for serving static files in dev environment.\n #See: http://docs.djangoproject.com/en/dev/howto/static-files/\n #In production setting, the webserver automatically overrides this, \n #so there is no need to take this out when in production:\n (r'^static/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n)\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"577602507","text":"import cv2\r\nimport numpy as np\r\n\r\n\r\ndef imageRead(openpath, flag=cv2.IMREAD_UNCHANGED):\r\n image = cv2.imread(openpath, flag)\r\n if image is not None:\r\n print(\"Image Opened\")\r\n return image\r\n else:\r\n print(\"Image Not Opened\")\r\n print(\"Program Abort\")\r\n exit()\r\n\r\n\r\ndef imageShow(imagename, image, flag=cv2.WINDOW_GUI_EXPANDED):\r\n cv2.namedWindow(imagename, flag)\r\n cv2.imshow(imagename, image)\r\n cv2.waitKey()\r\n return\r\n \r\n \r\ndef imageCopy(src):\r\n return np.copy(src)\r\n\r\n\r\ndef drawLine(image, point1, point2, color=(255, 0, 0), thickness=5, lineType=cv2.LINE_AA):\r\n result = imageCopy(image)\r\n return cv2.line(result, point1, point2, color, thickness, lineType)\r\n\r\n\r\ndef drawPolygon(image, pts, isClosed, color=(255, 0, 0), thickness=5, lineType=cv2.LINE_AA):\r\n result = imageCopy(image)\r\n pts = pts.reshape((-1, 1, 2))\r\n return cv2.polylines(result, [pts], isClosed, color, thickness, lineType)\r\n\r\n\r\npath = \"/home/nw/Desktop/OpenCV_in_Ubuntu/Data/Lane_Detection_Images/\"\r\nroadImage_01 = \"solidWhiteCurve.jpg\"\r\nroadImage_02 = \"solidWhiteRight.jpg\"\r\nroadImage_03 = \"solidYellowCurve.jpg\"\r\nroadImage_04 = \"solidYellowCurve2.jpg\"\r\nroadImage_05 = \"solidYellowLeft.jpg\"\r\nroadImage_06 = \"whiteCarLaneSwitch.jpg\"\r\n\r\nopenPath = path+roadImage_01\r\n\r\nroadColor = imageRead(openPath, cv2.IMREAD_COLOR)\r\nimageShow(\"roadColor\", roadColor)\r\n\r\nheight = roadColor.shape[0]\r\nwidth = roadColor.shape[1]\r\n\r\npt1 = (0, height)\r\npt2 = (int(width *0.5), int(height *0.5))\r\npt3 = (width, height)\r\n\r\npts = np.vstack((pt1, pt2, pt3)).astype(np.int32)\r\nroadColor_Poly_01 = drawPolygon(roadColor, pts, True, (255, 0, 0))\r\nimageShow(\"roadColor_Poly_01\", roadColor_Poly_01)\r\nroadColor_Line_01 = drawLine(roadColor, pt1, pt2, (255, 0, 0))\r\nroadColor_Line_01 = drawLine(roadColor_Line_01, pt2, pt3, (255, 0, 0))\r\nroadColor_Line_01 = drawLine(roadColor_Line_01, pt3, pt1, (255, 0, 0))\r\nimageShow(\"roadColor_Line_01\", roadColor_Line_01)\r\n\r\npt1 = (int(width*0.4), int(height*0.6))\r\npt2 = (int(width*0.6), int(height*0.6))\r\npt3 = (width, height)\r\npt4 = (0, height)\r\n\r\npts = np.vstack((pt1, pt2, pt3, pt4)).astype(np.int32)\r\nroadColor_Poly_02 = drawPolygon(roadColor, pts, False, (255, 0, 0))\r\nimageShow(\"roadColor_Poly_02\", roadColor_Poly_02)\r\nroadColor_Line_02 = drawLine(roadColor, pt1, pt2, (255, 0, 0))\r\nroadColor_Line_02 = drawLine(roadColor_Line_02, pt2, pt3, (255, 0, 0))\r\nroadColor_Line_02 = drawLine(roadColor_Line_02, pt3, pt4, (255, 0, 0))\r\nroadColor_Line_02 = drawLine(roadColor_Line_02, pt4, pt1, (255, 0, 0))\r\nimageShow(\"roadColor_Line_02\", roadColor_Line_02)\r\n\r\ncv2.destroyAllWindows()\r\n","sub_path":"courses/w10_opencv/source/OpenCV_in_Ubuntu/Python/1st_06H/21_Image_Draw_Polygon.py","file_name":"21_Image_Draw_Polygon.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"362010063","text":"# -*- coding:utf-8 -*-\n## author : cypro666\n## note : python3.4+\n\"\"\"\nsimple wrapper of mysql operations, based on pymysql\n\"\"\"\nimport sys\nfrom threading import Lock\nfrom pymysql import connections\nfrom pymysql import err as mysqlerr\n# from pymysql.cursors import SSCursor\nfrom getpass import getpass\n\nfrom .debug import time_meter, print_exception\nfrom .utilities import DummyLock\n\n__all__ = ['OpMysql']\n\n\nclass OpMysql(object):\n \"\"\" simple wrapper of mysql operations, based on pymysql \"\"\"\n \n def __init__(self, **kwargs):\n \"\"\" `kwargs` is a dict(always from json) like: \n {\n \"host\" : \"192.168.1.24\",\n \"port\" : 3306,\n \"username\" : \"root\",\n \"password\" : \"bingo321\",\n \"database\" : \"mytest\"\n }\n \"\"\"\n self.__con = None\n if 'lock' in kwargs and kwargs['lock']:\n self.__lock = Lock()\n else:\n self.__lock = DummyLock()\n try:\n user = kwargs['username']\n passwd = kwargs['password']\n host, port, dbname= kwargs['host'], kwargs['port'], kwargs['database']\n if 'show' in kwargs and kwargs['show']:\n sys.stdout.write('Try to connect '+user+'@'+host+':'+str(port)+'/'+dbname+'\\n')\n self.__con = connections.Connection(host = str(host), port = int(port), \n user = str(user), passwd = str(passwd), \n database = str(dbname), charset = 'utf8')\n except Exception:\n raise RuntimeError('OpMysql: connect failed!')\n self.__cur = self.__con.cursor()\n \n \n def __del__(self):\n \"\"\" close in release \"\"\"\n if self.__con:\n self.__con.commit()\n self.__cur.close()\n self.__con.close()\n # sys.stdout.write('OpMysql: connection closed!\\n')\n \n def select_database(self, dbname):\n \"\"\" change database \"\"\"\n with self.__lock:\n self.__con.select_db(dbname)\n \n \n def execute(self, sql, args = None):\n \"\"\" execute SQL on selected database with commit \"\"\"\n with self.__lock:\n try:\n cur = self.__con.cursor()\n cur.execute(sql, args = args)\n self.__con.commit() \n cur.close() \n except mysqlerr.Error:\n print_exception('OpMysql.query')\n except Exception as e:\n raise e\n \n def execute_nocommit(self, sql, args = None):\n \"\"\" execute SQL on selected database without commit \"\"\"\n with self.__lock:\n try:\n self.__cur.execute(sql, args = args)\n except mysqlerr.Error:\n print_exception('OpMysql.query')\n except Exception as e:\n raise e\n \n \n def commit(self):\n \"\"\" COMMIT \"\"\"\n with self.__lock:\n self.__con.commit()\n \n \n def fetch(self, sql, args = None, size = 0):\n \"\"\" fetch data using SQL, always for SELECT tasks \"\"\"\n with self.__lock:\n cur = self.__con.cursor()\n cur.execute(sql, args = args)\n try:\n if size <= 0 : \n items = cur.fetchall()\n else:\n items = cur.fetchmany(size)\n cur.close()\n return items\n except Exception:\n print_exception(sql)\n cur.close()\n return None\n\n \n def query(self, sql, buffered = True):\n \"\"\" only for simple query, return raw results \"\"\"\n with self.__lock:\n try:\n return self.__con.query(sql, unbuffered = not buffered)\n except Exception:\n print_exception('OpMysql.query')\n\n\n\n@time_meter(__name__)\ndef test():\n dbf = OpMysql(username='root', password=getpass(),\n host='localhost', port='3306', database='mysql')\n dbf.select_database('mysql')\n \n print(dbf.query(\"\"\"SELECT * FROM `user` LIMIT %d;\"\"\" % (10,), True))\n\n sql = \"\"\"SELECT * FROM `user` WHERE host=%s;\"\"\"\n cur = dbf.fetch(sql, (\"localhost\",))\n for i in cur:\n print(i)\n \n result = dbf.fetch(sql = \"\"\"SELECT COUNT(*) FROM `user`\"\"\", args = None, size = -1)\n print(result)\n\n\n\n\n\n\n\n","sub_path":"magic3/opmysql.py","file_name":"opmysql.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"118694573","text":"import os\nimport joblib\nimport logging\nimport uvicorn\nimport pandas as pd\nfrom typing import Optional, List, NoReturn\nfrom sklearn.pipeline import Pipeline\nfrom fastapi import FastAPI\n\nfrom .src.entities.app_params import RequestData, ResponseData\n\n\nPREDICTOR_HOST = os.environ.get(\"HOST\", default=\"0.0.0.0\")\nPREDICTOR_PORT = os.environ.get(\"PORT\", default=8080)\n\nlogger = logging.getLogger(__name__)\nmodel: Optional[Pipeline] = None\napp = FastAPI()\n\n\ndef load_model() -> NoReturn:\n global model\n\n classifier_path = os.getenv(\n \"CLASSIFIER_PATH\",\n default=\"models/logreg.pkl\")\n if classifier_path is None:\n err = f\"variable not set: CLASSIFIER_PATH\"\n logger.error(err)\n raise RuntimeError(err)\n\n transformer_path = os.getenv(\n \"TRANSFORMER_PATH\",\n default=\"models/transformer.pkl\")\n if transformer_path is None:\n err = f\"variable not set: PATH_TO_TRANSFORMER\"\n logger.error(err)\n raise RuntimeError(err)\n\n logger.info(f\"Classifier found: {classifier_path}\")\n\n classifier = joblib.load(classifier_path)\n\n logger.info(\"Classifier loaded\")\n\n logger.info(f\"Transformer found: {transformer_path}\")\n\n transformer = joblib.load(transformer_path)\n\n logger.info(\"Transformer loaded\")\n\n model = Pipeline([\n ('transformer', transformer),\n ('classifier', classifier)\n ])\n\n logger.info(\"Pipeline created\")\n\n\n\ndef make_preds(\n data: List[RequestData], pipeline: Pipeline) -> List[ResponseData]:\n df = pd.DataFrame(x.__dict__ for x in data)\n\n # correct features order\n columns = [\n 'age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg',\n 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal'\n ]\n\n df = df[columns]\n df['target'] = None\n\n ids = list(range(len(data)))\n predicts = model.predict(df)\n\n return [\n ResponseData(id=id_, target=int(target_))\n for id_, target_ in zip(ids, predicts)\n ]\n\n\n@app.get(\"/\")\ndef main():\n return \"This is the entry point of our predictor.\"\n\n\n@app.on_event(\"startup\")\ndef startup():\n logger.info(\"Starting service...\")\n load_model()\n\n\n@app.get(\"/status\")\ndef status() -> bool:\n if model is not None:\n return \"Predictor is ready\"\n return \"Predictor not ready\"\n\n\n@app.api_route(\"/predict\", response_model=List[ResponseData], methods=[\"GET\", \"POST\"])\ndef predict(request: List[RequestData]):\n global model\n return make_preds(request, model)\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"ml_app.app:app\", host=PREDICTOR_HOST, port=os.getenv(\"PORT\", PREDICTOR_PORT))","sub_path":"online_inference/ml_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"500099626","text":"# Funcion para la cantidad de estudiantes de 1 y 2 semestre\ndef estudiantes_semestre(lista, carrer):\n total = 0\n for li in range(len(lista)):\n if carrera[li] == carrer and (semestre[li] == str(1) or (semestre[li] == str(2))):\n total += 1\n\n print(f\"De la carrera {carrer} respondieron: {str(total-1)} estudiantes\")\n\n\n# Funcion para los datos de las encuentas de la pregunta # 5\ndef encuesta_pregunta5(lista1, lista2, dato, nu):\n pr5_resp = 0\n\n for se in range(len(lista1)):\n if (lista1[se] == dato) and (lista2[se] == str(nu)):\n pr5_resp += 1\n return pr5_resp\n\n\n# Funcion para sacar el porcentaje\ndef porcentaje(nh, nf, np, animo):\n rsf = round((nf * 100) / 255)\n rsh = round((nh * 100) / 255)\n resul = rsf + rsh\n print(f\"{str(resul)}% respondió {str(np)}. \"\n f\"{animo}, de las cuales {str(rsf)}% fueron mujeres y {str(rsh)}% fueron hombres\")\n\n\n# Funcion para sacar la edad promedio\ndef promedio_edades(genero, g):\n edades = 0\n totales = 0\n for sef in range(len(sexo)):\n if (sexo[sef] == genero) and (semestre[sef] == str(\"1\")):\n edades = edades + int(edad[sef])\n totales += 1\n\n promedio = edades / totales\n print(f\"La edad promedio de {g} es de {str(round(promedio))} años\")\n\n\n# Funcion para calcular la cantidad de estudiantes en las carreras\ndef carrera_estudiantes(word):\n estudiante_hombre = 0\n estudiante_mujer = 0\n for cr in range(len(carrera)):\n if (carrera[cr] == word) and (sexo[cr] == \"Masculino\"):\n estudiante_hombre = estudiante_hombre + 1\n\n elif (carrera[cr] == word) and (sexo[cr] == \"Femenino\"):\n estudiante_mujer = estudiante_mujer + 1\n\n return estudiante_hombre, estudiante_mujer\n\n\n# Lee el archivo y extrae los datos en la variable lectura\nfile = open(\"datos2.csv\", \"r\")\nlectura = file.read()\nfile.close()\n\n\n# Separa los datos\ndatos = []\nfor i in lectura.split(\"\\n\"):\n datos.append(i)\n\npalabra = \"\"\nnuevo = []\nfor i in range(len(datos)):\n palabra = datos[i].split(\";\")\n nuevo.append(palabra)\n\n\n# Listas para almacenar los datos\ncarrera = []\nedad = []\nsemestre = []\nsexo = []\nresp5 = []\n\n\n# Ciclo para almancer los datos del documento en las listas\nfor numero in range(len(nuevo)):\n carrera.append(nuevo[numero][1])\n edad.append(nuevo[numero][2])\n semestre.append(nuevo[numero][3])\n sexo.append(nuevo[numero][4])\n resp5.append(nuevo[numero][9])\n\n# Condicion para la calcular la cantidad de hombres y mujeres\nmasculino = 0\nfemenino = 0\n\nfor hm in sexo:\n if hm == \"Masculino\":\n masculino += 1\n else:\n femenino += 1\n\n# Punto #1 LISTO\n\nhombres = round((masculino * 100) / 252)\nmujeres = round((femenino * 100) / 252)\nprint(f\"El porcentaje de hombres que respondio la encuesta es de {str(hombres)} %\")\nprint(f\"El porcentaje de mujeres que respondio la encuesta es de {str(mujeres)} %\")\n\n\n# Punto #2 LISTO\n# Carreras\nestudiantes_semestre(carrera, \"IMTR\")\nestudiantes_semestre(carrera, \"ICIV\")\nestudiantes_semestre(carrera, \"INAV\")\nestudiantes_semestre(carrera, \"IMEC\")\nestudiantes_semestre(carrera, \"IELE\")\nestudiantes_semestre(carrera, \"IAMB\")\nestudiantes_semestre(carrera, \"IIND\")\nestudiantes_semestre(carrera, \"IQUI\")\nestudiantes_semestre(carrera, \"IBIO\")\nestudiantes_semestre(carrera, \"ISCO\")\nestudiantes_semestre(carrera, \"IETR\")\n\n# Punto #3 LISTO\n# Femenino\npre5_resp1_feme = encuesta_pregunta5(sexo, resp5, \"Femenino\", 1)\npre5_resp2_feme = encuesta_pregunta5(sexo, resp5, \"Femenino\", 2)\npre5_resp3_feme = encuesta_pregunta5(sexo, resp5, \"Femenino\", 3)\npre5_resp4_feme = encuesta_pregunta5(sexo, resp5, \"Femenino\", 4)\n\n# Masculino\npre5_resp1_masc = encuesta_pregunta5(sexo, resp5, \"Masculino\", 1)\npre5_resp2_masc = encuesta_pregunta5(sexo, resp5, \"Masculino\", 2)\npre5_resp3_masc = encuesta_pregunta5(sexo, resp5, \"Masculino\", 3)\npre5_resp4_masc = encuesta_pregunta5(sexo, resp5, \"Masculino\", 4)\npre5_resp5_masc = encuesta_pregunta5(sexo, resp5, \"Masculino\", 5)\n\nprint()\nporcentaje(pre5_resp1_masc, pre5_resp1_feme, 1, \" Totalmente desacuerdo\")\nporcentaje(pre5_resp2_masc, pre5_resp2_feme, 2, \"En desacuerdo\")\nporcentaje(pre5_resp3_masc, pre5_resp3_feme, 3, \"Ni en acuerdo ni en desacuerdo\")\nporcentaje(pre5_resp4_masc, pre5_resp4_feme, 4, \"De acuerdo\")\nporcentaje(pre5_resp4_masc, 0, 5, \"Totalmente de acuerdo\")\n\n\n# PUNTO #4 LISTO\n# Hombre\npromedio_edades(\"Masculino\", \"Hombres\")\n\n# Mujer\npromedio_edades(\"Femenino\", \"Mujeres\")\n\n# PUNTO #5 LISTO\nh_iciv, f_iciv = carrera_estudiantes(\"ICIV\")\nporchombre = round((h_iciv * 100) / 252)\nporcmujer = round((f_iciv * 100) / 252)\nprint(f\"La carrera con mayor estudantes es:ICIV tiene {str(porchombre)}% de hombres y {str(porcmujer)}% de mujeres\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180448172","text":"import MapReduce\nimport sys\n\nmr = MapReduce.MapReduce()\n\n\ndef mapper(record):\n mr.emit_intermediate(record[1], record)\n\n\ndef initReducer(list):\n for order_records in list:\n if order_records[0] == 'order':\n for lines in list:\n if lines[0] == 'line_item':\n mr.emit(order_records + lines)\n\n\ndef reducer(initList):\n initReducer(initList)\n\n\ninputdata = open(sys.argv[1])\nmr.execute(inputdata, mapper, reducer)\n","sub_path":"python-mapreduce/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319503176","text":"from django.urls import path\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path(\"/\", views.show, name=\"show\"),\r\n path(\"/details\", views.details, name=\"details\"),\r\n path(\"/create_user\", views.create_user, name=\"create_user\"),\r\n path(\"/profile//update_user\", views.update_user, name=\"update_user\"),\r\n path(\"details\", views.details_redirect, name=\"details_redirect\"),\r\n path(\"profile\", views.profile_redirect, name=\"profile_redirect\"),\r\n path(\"/profile/\", views.profile, name=\"profile\"),\r\n path(\"/fetch_frame//\", views.fetch_frame, name=\"fetch_frame\"),\r\n path(\"/create_camera\", views.create_camera, name=\"create_camera\")\r\n]","sub_path":"website/organizations/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"486681555","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 1 10:59:42 2020\n\n@author: Johan Odelius\nLuleå University of Technology\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy import stats\nimport os\n\n#%% Read sweden\nurl = 'https://www.arcgis.com/sharing/rest/content/items/b5e7488e117749c19881cce45db13f7e/data'\nxl = pd.ExcelFile(url)\n\nprint(xl.sheet_names[-1])\n\n# Save local\ni_would_like_to_save_data_to_local_file = 'yes' #(yes/no)\nfilepath = 'data/'\nif i_would_like_to_save_data_to_local_file.lower() == 'yes':\n filename = xl.sheet_names[-1]+'.xlsx'\n file_exist = os.path.isfile(filepath+filename)\n if file_exist:\n do_write=input('File \"%s\" exist, overwrite (yes/no)?' % filename)\n \n if not file_exist or 'y' in do_write:\n if not os.path.exists(filepath):\n os.mkdir(filepath)\n print('Writing '+filename)\n with pd.ExcelWriter(filepath+filename) as writer:\n for sheet in xl.sheet_names:\n df = xl.parse(sheet)\n df.to_excel(writer, sheet_name=sheet, index=False)\n \n\n# Confirmed cases\ndf_cases = xl.parse('Antal per dag region') #pd.read_excel(url,sheet_name=0)\ndf_cases.index = pd.to_datetime(df_cases['Statistikdatum'])\nlast_update = pd.to_datetime(df_cases['Statistikdatum'][-1])\ndf_cases.drop(['Statistikdatum'],axis=1,inplace=True)\n\n# Replace missing values with zero\ndf_cases.fillna(0,inplace=True) \n\n# Deaths\ndf_deaths = xl.parse('Antal avlidna per dag') #pd.read_excel(url,sheet_name=1)\ndf_deaths.iloc[[isinstance(d,str) and 'saknas' in d for d in df_deaths['Datum_avliden'].values],0]=''\ndf_deaths.index = pd.to_datetime(df_deaths['Datum_avliden'])\ndf_deaths.drop(['Datum_avliden'],axis=1,inplace=True)\n\n# Intesive care\ndf_iva = xl.parse('Antal intensivvårdade per dag') #pd.read_excel(url,sheet_name=2)\ndf_iva.index = pd.to_datetime(df_iva['Datum_vårdstart'])\ndf_iva.loc[:,'Antal_intensivvårdade'].fillna(0,inplace=True) \ndf_iva.drop(['Datum_vårdstart'],axis=1,inplace=True)\n\ndf_reg = xl.parse('Totalt antal per region') #pd.read_excel(url,sheet_name=1)\n\nxl.close()\n\n#%% Merge to one dataframe\n# Align index names\ndf_cases.index.name = 'Datum'\ndf_deaths.index.name = 'Datum'\ndf_iva.index.name = 'Datum'\n\n# Merge\ndf = df_cases.copy()\ndf[df_deaths.columns[0]] = df_deaths.iloc[:,0]\ndf[df_iva.columns[0]] = df_iva.iloc[:,0]\n\n# Fill missing to zero\ndf.fillna(0, inplace=True) \n\n# Renamce region column names\nnew_cols = {col : col+'_antal_fall' for col in df_cases if not 'fall' in col}\ndf.rename(columns=new_cols, inplace=True)\n\n# set x=0 when first case is reported and exclude last date\nfor col in df:\n if 'antal_fall' in col:\n valid_cases = np.logical_and(df[col].cumsum().values>0,df.indexlast_update:\n break\n t.append(d)\n print(d.strftime('%Y-%m-%d')) \n m_d = fit(df.loc['2020-02-01':d.strftime('%Y-%m-%d')], data_label='Antal', cols=cols, p0=[5, 70, 2000]) #[4,50,1000]\n for col in cols:\n if len(m_d[col]['mdl']['p'])>0:\n yhat.loc[d,col] = m_d[col]['mdl']['p'][2]\n else:\n yhat.loc[d,col] = np.nan\n\n#%%\nfig,axes = plt.subplots(nrows=2,ncols=1)\ncols2 = ['Antal_avlidna','Antal_intensivvårdade']\ncols1 = np.setdiff1d(cols,cols2)\nyhat[cols1].plot(ax=axes[0],logy=False)\nyhat[cols2].plot(ax=axes[1])\n\n#%% Fit logistic model with fix offset\ncols = ['Antal_intensivvårdade','Antal_avlidna']\ndb = [5,5+2]\n\nb = np.round(m_1['Totalt_antal_fall']['mdl']['p'][1]+db[0])\nm_b_1 = fit(df, data_label='Antal', cols=cols[0], mdl=logistic_b_mdl, p0=[5, 2500]) \n\nb = np.round(m_1['Totalt_antal_fall']['mdl']['p'][1]+db[1])\nm_b_2 = fit(df, data_label='Antal', cols=cols[1], mdl=logistic_b_mdl, p0=[5, 2500]) \n\nm_b = {**m_b_1,**m_b_2}\n\n\n#%% plot\ncols = ['Totalt_antal_fall']\n# Init plot\nfig,axes = plt.subplots(nrows=2,ncols=1)\ncolors = ['C0','C1','C2','C3','C4','C5','C6','C7','C8']\n# Plot data \nax11 = plt.subplot(211) \nfor col in cols: \n plt.plot(m[col]['data']['t'], m[col]['data']['y'], colors[0]+':.', label=col) \n plt.plot(m[col]['fit']['t'], m[col]['fit']['y'], colors[1]+'-',label=col+' logistic fit') \nplt.ylabel('Antal fall')\nplt.legend(loc=2)\n\nax12 = ax11.twinx()\nfor n,col in enumerate(['Antal_intensivvårdade','Antal_avlidna']): \n plt.plot(m[col]['data']['t'], m[col]['data']['y'], colors[3*n+3]+':.', label=col) \n plt.plot(m[col]['fit']['t'], m[col]['fit']['y'], colors[3*n+4]+'-',label=col+' logistic fit') \n #plt.plot(m_b[col]['fit']['t'], m_b[col]['fit']['y'], colors[3*n+4]+'--',label=col+(' logistic fit (b=+%.1f)' % db[n]))\nplt.ylabel('Antal iva/avlidna')\nplt.legend(loc=6)\n\n \nax21 = plt.subplot(212) \nfor col in cols: \n plt.plot(m[col]['data']['t'], m[col]['data']['dy'], colors[0]+':.', label=col) \n plt.plot(m[col]['data']['t'], pd.Series(m[col]['data']['dy']).rolling(7,center=True).mean().values, colors[1]+'-', label=col) \n plt.plot(m[col]['fit']['t'], m[col]['fit']['dy'], colors[2]+'--',label=col+' logistic fit') \nplt.ylabel('Antal fall per dag')\nplt.legend(loc=2)\n\nax22 = ax21.twinx()\nfor n,col in enumerate(['Antal_intensivvårdade','Antal_avlidna']): \n plt.plot(m[col]['data']['t'], m[col]['data']['dy'], colors[3*n+3]+'.:', label=col) \n plt.plot(m[col]['data']['t'], pd.Series(m[col]['data']['dy']).rolling(7,center=True).mean().values, colors[3*n+4]+'-', label=col) \n plt.plot(m[col]['fit']['t'], m[col]['fit']['dy'], colors[3*n+5]+'--',label=col+' logistic fit') \n #plt.plot(m_b[col]['fit']['t'], m_b[col]['fit']['dy'], colors[4*n+5]+'--',label=col+(' logistic fit (b=+%.1f)' % db[n])) \nplt.ylabel('Antal iva/avlidna per dag')\nplt.legend(loc=6)\n\n#%% Plot logistic model with fix offset\n#fig,axes = plt.subplots(nrows=1,ncols=1)\n#c = {'db':list(range(-7,15))}\n#cols = ['Antal_intensivvårdade','Antal_avlidna']\n#for n,col in enumerate(cols): \n# c[col]=[]\n# for o in c['db']: #offset from cases \n# b = np.round(m_1['Totalt_antal_fall']['mdl']['p'][1]+o)\n# m_o = fit(df, data_label='Antal', cols=cols, mdl=logistic_b_mdl, p0=[5, 2500]) \n# c[col].append(m_o[col]['mdl']['p'][1])\n# plt.plot(c['db'],c[col],colors[n],label=col)\n# plt.plot(c['db'],[m_2[col]['mdl']['p'][2]]*len(c['db']),colors[n]+'--',label=col)\n#plt.legend()\n#plt.xlabel('Offset b')\n#plt.ylabel('Antal')\n","sub_path":"logistic_analyse_swe.py","file_name":"logistic_analyse_swe.py","file_ext":"py","file_size_in_byte":11448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"320189553","text":"import cv2\nimport os\nimport numpy as np\nfrom time import sleep\nimport time\n\n\nsubjects = [\"\", \"Shoaib\",\"Arman\",\"Azam\"]\n\n\ndef detect_face(img):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml')\n\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);\n\n if (len(faces) == 0):\n return None, None\n\n (x, y, w, h) = faces[0]\n\n # cv2.destroyAllWindows()\n\n return gray[y:y+w, x:x+h], faces[0]\n\n\ndef prepare_training_data(data_folder_path):\n\n dirs = os.listdir(data_folder_path)\n\n faces = []\n labels = []\n\n for dir_name in dirs:\n if not dir_name.startswith(\"s\"):\n continue;\n\n label = int(dir_name.replace(\"s\", \"\"))\n\n subject_dir_path = data_folder_path + \"/\" + dir_name\n\n subject_images_names = os.listdir(subject_dir_path)\n\n\n for image_name in subject_images_names:\n\n if image_name.startswith(\".\"):\n continue;\n\n image_path = subject_dir_path + \"/\" + image_name\n\n image = cv2.imread(image_path)\n\n # cv2.imshow(\"Training on image...\", cv2.resize(image, (400, 500)))\n # cv2.waitKey(1)\n\n face, rect = detect_face(image)\n \n\n if face is not None:\n faces.append(face)\n labels.append(label)\n\n cv2.destroyAllWindows()\n cv2.waitKey(1)\n cv2.destroyAllWindows()\n\n return faces, labels\n\nprint(\"Preparing data...\")\nfaces, labels = prepare_training_data(\"training-data\")\nprint(\"Data prepared\")\n\nprint(\"Total faces: \", len(faces))\nprint(\"Total labels: \", len(labels))\n\n\n\nface_recognizer = cv2.face.LBPHFaceRecognizer_create()\n\n\nface_recognizer.train(faces, np.array(labels))\n\n\ndef draw_rectangle(img, rect):\n (x, y, w, h) = rect\n cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n\ndef draw_text(img, text, x, y):\n cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)\n\n\ndef takephoto():\n\ttry:\n\t face_cascade= cv2.CascadeClassifier('data\\\\haarcascade_frontalface_alt2.xml')\n\t cap = cv2.VideoCapture(0)\n\t ret,frame = cap.read()\n\t gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n\t faces= face_cascade.detectMultiScale(gray,scaleFactor=1.5,minNeighbors=5)\n\t for(x,y,w,h) in faces:\n\t # print(x,y,w,h)\n\t roi_gray = gray[y:y+h, x: x+w]\n\t # img_item = 'my_img.png'\n\t cv2.imwrite('my_img.png',roi_gray)\n\n\t cv2.imshow('frame',frame)\n\t # print(\"before sleep\")\n\t # print(\"Predicting images...\")\n\t test_img1 = cv2.imread(\"my_img.png\")\n\t predicted_img1 = predict(test_img1)\n\t # cv2.imshow(\"Test1\", cv2.resize(predicted_img1, (400, 500)))\n\t # time.sleep(5)\n\t # cv2.waitKey(0)\n\t # print(\"aftersleep\")\n\t # if cv2.waitKey(20) & 0xFF == ord('q'):\n\t # break\n\n\t cap.release()\n\t cv2.destroyAllWindows()\n\texcept:\n\t\tpass\n\n\ndef predict(test_img):\n try:\n img = test_img.copy()\n face, rect = detect_face(img)\n\n label, confidence = face_recognizer.predict(face)\n label_text = subjects[label]\n print('Hello ' + label_text)\n # draw_rectangle(img, rect)\n # draw_text(img, label_text, rect[0], rect[1]-5)\n print(confidence)\n if confidence < 40:\n \treturn img\n else:\n \tpass\n except:\n takephoto()\n\n\n\ntakephoto()\n","sub_path":"core/MainFaceRecognition.py","file_name":"MainFaceRecognition.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"135469656","text":"\"\"\"This module contains the Flask App.\"\"\"\n\nimport time\nimport json\nimport os\n\nfrom flask import request\nfrom flask import Flask\nfrom flask import redirect\nfrom flask import jsonify\nfrom flask import json\nimport requests\n\nimport secrets\nimport swagger_client\nfrom strava import activity_to_dict\nfrom strava import user_to_dict\nfrom strava import check_and_refresh\n\nRESPONSE_TYPE = \"code\"\nSCOPE = \"read_all,activity:read_all,activity:read,profile:read_all\"\n\napp = Flask(__name__)\n\ndef load_users():\n \"\"\"Load users from users directory.\"\"\"\n users = {}\n for file in os.listdir(\"users\"):\n with open(os.path.join(\"users\", file), \"r\") as user_config_file:\n user_config = json.load(user_config_file)\n user_id = user_config[\"athlete\"][\"id\"]\n users[user_id] = user_config\n app.config[\"USERS\"] = users\n\n\n@app.route(\"/users\")\ndef list_users():\n \"\"\"List all users.\"\"\"\n load_users()\n users = list(map(user_to_dict, app.config[\"USERS\"].values()))\n \n # user_names = [u[\"athlete\"][\"firstname\"] for u in app.config[\"USERS\"].values()]\n response = jsonify(users)\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response\n\n\n@app.route(\"//routes\")\ndef list_routes(user_id):\n \"\"\"List the last routes.\"\"\"\n user_id = int(user_id)\n check_and_refresh(app, user_id)\n api = swagger_client.ActivitiesApi()\n api.api_client.configuration.access_token = app.config[\"USERS\"][user_id][\n \"access_token\"\n ]\n r = api.get_logged_in_athlete_activities(per_page=100)\n response = jsonify(list(map(activity_to_dict, r)))\n response.headers.add(\"Access-Control-Allow-Origin\", \"*\")\n return response\n\n\n@app.route(\"/start\")\ndef authenticate():\n \"\"\"Starts the authentication process.\"\"\"\n url = f\"https://www.strava.com/oauth/authorize?client_id={secrets.STRAVA_CLIENT_ID}&response_type=code&redirect_uri={secrets.REDIRECT_URI}&scope={SCOPE}\"\n return redirect(url)\n\n\n@app.route(\"/user_token_exchange\")\ndef user_token_exchange():\n \"\"\"Receive the user code and query Strava to get the final access token.\"\"\"\n user_code = request.args.get(\"code\")\n scopes = request.args.get(\"scope\")\n\n r = requests.post(\n \"https://www.strava.com/api/v3/oauth/token\",\n data={\n \"client_id\": secrets.STRAVA_CLIENT_ID,\n \"client_secret\": secrets.STRAVA_CLIENT_SECRET,\n \"code\": user_code,\n \"grant_type\": \"authorization_code\",\n },\n )\n user_config = r.json()\n user_id = user_config[\"athlete\"][\"id\"]\n with open(os.path.join(\"users\", f\"{user_id}.json\"), \"w\") as user_file:\n json.dump(user_config, user_file)\n app.config[\"USERS\"][user_id].update(user_config)\n return f\"Welcome {user_config['athlete']['firstname']}\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n","sub_path":"python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225608997","text":"'''\nAuthor @ Subhamoy Karmakar\n\nThis is the Module where\n\nInput:\n\nOutput:\n'''\n# This file contains the names of all the table currently being used in the project from SQL.\npolicycaseframe = \"policycaseframe\" # this table contains the case frame details of policy-case-frame.\nallPolicies = \"allpolicies\" # contains details of all the polices and their statements and if they are log generating\nintermPolicy = \"intermpolicy\"\ndemocontext = \"democontext\" # Delete this later and replace with the original context table.\nTABLE_LOGS = 'logs' # this is the table Logs\nTABLE_POLICY_STMT_NODE_DEPENDENCY = 'policystmtnodedependency'\n","sub_path":"PHASE-1.1_IMPROVEMENT_PHASE/POLICOMP_TOOL/SQLTableNames.py","file_name":"SQLTableNames.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"595153881","text":"# a = 17\n# if a >=18:\n# print('你的年龄是:', a)\n# print('你已成年')\n# else:\n# print('你的年龄是:', a)\n# print('你未成年')\n#\n# b = 2\n# if b >= 18:\n# print('adult')\n# elif b >= 6:\n# print('teenager')\n# elif b >= 3:\n# print('kid')\n# else:\n# print('baby')\n#\n# s = input('birth:')\n# birth = int(s)\n# if birth < 2000:\n# print('00前')\n# else:\n# print('00后')\n\n# 作业\nw = input('weight:')\nh = input('height:')\nweight = float(w)\nheight = float(h)\nbmi = weight / (height * height)\nif bmi < 18.5:\n print('过轻')\nelif 18.5 <= bmi <= 25:\n print('正常')\nelif 25 <= bmi <= 28:\n print('过重')\nelif 28 <= bmi <= 32:\n print('肥胖')\nelse:\n print('严重肥胖')","sub_path":"python_basis/python_procedure/01_python_basis/07_condition.py","file_name":"07_condition.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"353717029","text":"from __future__ import print_function\n\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport math\nimport sys\nimport time\nfrom tensorflow.python.platform import tf_logging as logging\n\n#tf.enable_eager_execution()\n\nlogging._get_logger().setLevel(logging.INFO)\nstart = time.time()\n\nhidden_units = [128,64,32]\nlearning_rate = 0.001\nbatch_size = 26\n#batch_size = 1\n\nnum_epochs = 1\nl1_regularization_strength = 0.001\nNUM_PARALLEL_BATCHES = 1\nhash_bucket_size = 3000\n\nfilenames = \"/memverge/home/songjue/data/tmp/sparse.csv\"\n#filenames = \"./sparse.csv\"\nmodel_dir = 'model_linkedin'\n\ntarget = 'label'\ndelim = ','\nlabel_vocabulary = [\"0\", \"1\"]\n\n\n\nDEEP_FEATURE_DIMS = 3000\nWIDE_FEATURE_DIMS = 100\nNON_ZERO_NUM = 10\n\nBATCH_IDX = np.array([ i for i in range(batch_size)], dtype='int64')\n\nfeatures_deep = ['d0', 'd1', 'd2', 'd3', 'd4']\nfeatures_wide = ['w1']\ndefault_value = [[\"\"]] * 7\nfeature_cols = {'w1':0, 'd0':1, 'd1':2, 'd2':3, 'd3':4, 'd4':5}\nlabel_cols = {target: 6}\n\n# calculate emb_dim\nemb_dim = []\nfor c in features_deep:\n# emb_dim.append(int(math.log(len(df[c].unique()), 2)))\n emb_dim.append(8)\n#print(emb_dim)\n\ndeep_cols = []\ncount = 0\nfor col in features_deep:\n col = tf.feature_column.categorical_column_with_hash_bucket(col, hash_bucket_size=hash_bucket_size)\n deep_cols.append(tf.feature_column.embedding_column(col, emb_dim[count]))\n count += 1\n\nwide_cols = tf.feature_column.categorical_column_with_hash_bucket(features_wide[0], hash_bucket_size=hash_bucket_size)\n\ndef getBatches(filenames):\n \"\"\" 1. code snippet below uses constant batch_size to tranform tensors, so:\n - error like \"InvalidArgumentError: Input to reshape is a tensor with 32 values, but the requested shape has 52\" for the last batch.\n could be solved by using 'local variable of tf'? HOW?\n - d.batch() must be called and before map().\n - current code does not work with map_and_batch (since map_and_batch call map() first then batch() ??)\n\n 2. both dense/sparse tensor work fine\n \"\"\"\n def _mk_wide(idx):\n\n v = tf.reshape(tf.cast(tf.string_to_number(idx.values), tf.float32), [batch_size, 2]) #idx:value\n\n idx = tf.map_fn(lambda x: (x[0], tf.to_int64(x[1][0])), elems=(BATCH_IDX, v), dtype=(tf.int64, tf.int64))\n idx = tf.transpose(idx)\n val = tf.map_fn(lambda x: x[1], elems=tf.dtypes.as_string(v))\n #'''\n return tf.sparse.SparseTensor(indices=idx, values=val, dense_shape=[batch_size, WIDE_FEATURE_DIMS])\n '''\n return tf.sparse.to_dense(tf.sparse.SparseTensor(indices=idx, values=val, dense_shape=[batch_size, WIDE_FEATURE_DIMS]), default_value='0')\n '''\n\n def _mk_deep(indexes):\n def _make_idx(row, cols):\n return tf.map_fn(lambda x: (row, x), elems=cols, dtype=(tf.int64, tf.int64))\n\n idx = tf.reshape(tf.cast(tf.string_to_number(indexes.values), tf.int64), [batch_size, NON_ZERO_NUM])\n elems = (BATCH_IDX, idx)\n alternate = tf.map_fn(lambda x: _make_idx(x[0], x[1]), elems, dtype=(tf.int64, tf.int64))\n alternate = tf.transpose(alternate)\n indices = tf.reshape(alternate, [batch_size * NON_ZERO_NUM, 2])\n\n val = np.array(['1'] * (batch_size * NON_ZERO_NUM)) #, dtype='int64')\n #'''\n return tf.sparse_reorder(tf.sparse.SparseTensor(indices=indices,\n values=val,\n dense_shape=[batch_size, DEEP_FEATURE_DIMS]))\n '''\n return tf.sparse.to_dense(tf.sparse_reorder(tf.sparse.SparseTensor(indices=indices,\n values=val,\n dense_shape=[batch_size, DEEP_FEATURE_DIMS])), default_value='0')\n '''\n def _parse_one_feature(k, x):\n indices = tf.string_split(x, \":\")\n return tf.cond(pred=tf.equal(k, 'w1'),\n true_fn=lambda: _mk_wide(indices), # lambda is a must as true_fn/false_fn expects a callable\n false_fn=lambda: _mk_deep(indices))\n\n\n def _parse_one_batch(records):\n #print(records)\n columns = tf.decode_csv(records, default_value, field_delim=delim)\n\n features = dict([(k, _parse_one_feature(k, columns[v])) for k, v in feature_cols.items()])\n # features = dict([(k, columns[v]) for k, v in feature_cols.items()])\n\n labels = [columns[v] for _, v in label_cols.items()]\n labels = tf.stack(labels, axis=1)\n\n return features, labels\n\n #d = tf.data.Dataset.from_tensor_slices(filenames)\n # d = d.flat_map(lambda filename: tf.data.TextLineDataset(filename, buffer_size=10000).skip(1).shard(int(FLAGS.num_workers), int(FLAGS.worker_idx)))\n #d = d.flat_map(lambda filename: tf.data.TextLineDataset(filename, buffer_size=10000).skip(1))\n\n d = tf.data.TextLineDataset(filenames, buffer_size=10000).skip(1)\n d = d.batch(batch_size) \n d = d.repeat(num_epochs)\n #d = d.apply( tf.data.experimental.map_and_batch(_parse_one_batch, batch_size)) #, num_parallel_batches=NUM_PARALLEL_BATCHES))\n d = d.map(map_func=_parse_one_batch)\n d = d.prefetch(1000)\n\n return d\n\n'''\nd = getBatches(filenames)\n#d = tf.data.TextLineDataset(filenames, buffer_size=10000).skip(1)\niterator = d.make_one_shot_iterator()\nf, l = iterator.get_next()\n\nsess = tf.Session()\nwhile True:\n try:\n print(sess.run(f['w1'])) #convert Bytes to String\n print(\"------------------------\")\n # except tf.errors.OutOfRangeError:\n # break\n except:\n e = sys.exc_info()[0]\n print(\"Error: %s
\" % e )\n break\n'''\n\nconfig = tf.estimator.RunConfig()\n\nconfig = config.replace(keep_checkpoint_max=5, save_checkpoints_steps=500)\n#for Intel MKL tunning (effective only in cpu-training??)\nsession_config = tf.ConfigProto()\nsession_config.gpu_options.allow_growth = True\nsession_config.intra_op_parallelism_threads = 48\nsession_config.inter_op_parallelism_threads = 48\n#session_config.log_device_placement = True\nconfig = config.replace(session_config=session_config)\n\nestimator = tf.estimator.DNNLinearCombinedClassifier(\n model_dir=model_dir,\n config=config,\n linear_feature_columns=wide_cols,\n dnn_feature_columns=deep_cols,\n dnn_hidden_units=hidden_units,\n n_classes=len(label_vocabulary), label_vocabulary=label_vocabulary)\n\nestimator.train(input_fn=lambda:getBatches(filenames))\n\nend = time.time()\nprint(\"***** training finished, CPU time elapsed: \", end-start, \" ******\")\n","sub_path":"linkedin/bak-train_sparse.py","file_name":"bak-train_sparse.py","file_ext":"py","file_size_in_byte":6500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"131935891","text":"import urllib.request\n\nimport os\nimport re\nimport urllib.error\ndef download_page(pageUrl):\n try:\n page = urllib.request.urlopen(pageUrl)\n text = page.read().decode('utf-8')\n \n\n\n regPostTitle = re.compile('.*? ', flags= re.DOTALL)\n titles = regPostTitle.findall(text)\n regTag = re.compile('<.*?>', re.DOTALL)\n regSpace = re.compile('\\s{2,}', re.DOTALL)\n for t in titles:\n clean_t = regSpace.sub(\"\", t)\n clean_t = regTag.sub(\"\", clean_t)\n\n\n regAuthor = re.compile('.*?', flags= re.DOTALL)\n author = regAuthor.findall(text)\n regTag1 = re.compile('<.*?>', re.DOTALL)\n regSpace1 = re.compile('\\s{2,}', re.DOTALL)\n regDescr1 = re.compile('Автор: ', re.DOTALL)\n for a in author:\n clean_a = regSpace1.sub(\"\", a)\n clean_a = regTag1.sub(\"\", clean_a)\n clean_a = clean_a.replace(\"Автор: \", \"\")\n\n \n regDate = re.compile('.*?', flags= re.DOTALL)\n date = regDate.findall(text)\n regTag1 = re.compile('<.*?>', re.DOTALL)\n regSpace1 = re.compile('\\s{2,}', re.DOTALL)\n\n for d in date:\n clean_d = regSpace1.sub(\"\", d)\n clean_d = regTag1.sub(\"\", clean_d)\n clean_d = clean_d.replace(\"Обновлено \", \"\")\n\n \n \n regText = re.compile(\"\"\".*?
\"\"\", flags= re.DOTALL)\n plaintxt = regText.findall(text)\n newtxt = []\n regTag = re.compile('<.*?>', re.DOTALL)\n regSpace = re.compile('\\s{2,}', re.DOTALL)\n for p in plaintxt:\n clean_p = regSpace.sub(\"\", p)\n clean_p = regTag.sub(\"\", clean_p)\n newtxt.append(clean_p)\n for l in newtxt:\n l = l.replace(\" \", \" \")\n with open('newspaper/article.txt', 'a', encoding=\"utf-8\") as f:\n f.write('@au', clean_a)\n f.write('\\n')\n f.write('@ti', clean_t)\n f.write('\\n')\n f.write('@da', clean_d)\n f.write('\\n')\n f.write(l)\n\n \n \n\n \n \n \n\n data = 'path\\t%s\\t\\t%s\\t%s\\tпублицистика\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t нейтральный\\tn-возраст\\tn-уровень\\tгородская\\t%s\\tРославльская правда\\t%s\\tгазета\\tРоссия\\tРославль\\tru' % (clean_a, clean_t, clean_d, pageUrl, clean_d[6:])\n fieldnames = ['path', 'author', 'sex', 'birthday', 'header', 'created', 'sphere', 'genre_fi', 'type', 'topic', 'chronotop', 'style', 'audience_age', 'audience_level', 'audience_size', 'source', 'publication', 'publisher', 'publ_year', 'medium', 'country', 'region', 'language']\n\n \n with open('newspaper/metadata14.csv', 'a',encoding=\"utf-8\") as f:\n f.write('\\t'.join(fieldnames) + '\\n')\n f.write(data + '\\n')\n\n\n except:\n print('Error at', pageUrl)\n return\n\n\n\n \n\ncommonUrl = 'http://ropravda.ru/index.php/'\ncat = ['roslavl-i-roslavlchane','delovaya-zhizn', 'mestnoe-samoupravlenie', 'selo-rodnoe', 'obrazovanie', 'kultura', 'sport', 'kraevedenie', 'roslavl-pravoslavnyj', 'tvorchestvo-nashikh-zemlyakov', 'proisshestviya', 'sotsialnaya-sfera', 'raznoe']\nfor c in cat:\n for i in range(1000, 1600):\n pageUrl = commonUrl + c + '/'+ str(i) \n download_page(pageUrl)\n\n\n\n","sub_path":"hw5.2.py","file_name":"hw5.2.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"539860256","text":"from django.urls import path,include\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static \nfrom rest_framework.urlpatterns import format_suffix_patterns\nurlpatterns = [\n path('home/', views.home1 , name='home'),\n path('product/', views.product , name='product'),\n path('product//',views.product_detail,name='product_detail'),\n path('post/',views.post,name='product_post'),\n path('',views.api_root),\n path('snippets/', views.SnippetList.as_view()),\n path('snippets//', views.SnippetDetail.as_view()),\n path('users/', views.UserList.as_view()),\n path('users//', views.UserDetail.as_view()),\n \n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nurlpatterns = format_suffix_patterns(urlpatterns) ","sub_path":"client/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"544614470","text":"\n'''_____Standard imports_____'''\nimport numpy as np\nimport json\n\ndef load_data(dir):\n\n data = []\n file = open(dir,'r')\n for line in file:\n data.append(float(line))\n return data\n\n\ndef load_Bscan_spectra(file_dir, block_start=276, block_end = 632084, shape1=617, shape2=1024):\n\n data = np.fromfile(file_dir, dtype = np.uint16)\n\n block_end = block_start + 1024*1024\n\n block_data = data[block_start: block_end]\n Bscan_spectra = block_data.reshape([1024,1024])\n return Bscan_spectra\n\n\ndef load_calibration(dir=None):\n\n if dir is None:\n dir = \"calibration/calibration_parameters.json\"\n\n with open(dir) as json_file:\n calibration = json.load(json_file)\n\n return calibration\n","sub_path":"PyOCTCalibration/toolbox/loadings.py","file_name":"loadings.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"197994759","text":"import pytest\n\nimport numpy as np\n\nfrom numpy.testing import assert_array_equal, assert_allclose, assert_equal\n\nfrom pyuoi import UoI_L1Logistic\nfrom pyuoi.linear_model.logistic import fit_intercept_fixed_coef\nfrom pyuoi.utils import make_classification\n\n\ndef test_fit_intercept_fixed_coef():\n \"\"\"Test that the intercept in fit correctly for fixed coefficients.\"\"\"\n X = np.zeros((6, 5))\n coef = np.ones((1, 5))\n y = np.ones(6)\n y[:3] = 0.\n b = fit_intercept_fixed_coef(X, coef, y, 2)\n assert_allclose(b, 0.)\n\n\ndef test_l1logistic_intercept():\n \"\"\"Test that binary L1 Logistic fits an intercept when run.\"\"\"\n for fi in [True, False]:\n X, y, w, b = make_classification(n_samples=100,\n random_state=11,\n n_features=4,\n w_scale=4.,\n include_intercept=fi)\n l1log = UoI_L1Logistic(fit_intercept=fi).fit(X, y)\n if not fi:\n assert_array_equal(l1log.intercept_, 0.)\n else:\n l1log.intercept_\n\n\ndef test_l1logistic_binary():\n \"\"\"Test that binary L1 Logistic runs in the UoI framework.\"\"\"\n n_inf = 4\n methods = ('acc', 'log')\n X, y, w, b = make_classification(n_samples=2000,\n random_state=6,\n n_informative=n_inf,\n n_features=10,\n w_scale=4.,\n include_intercept=True)\n\n for method in methods:\n l1log = UoI_L1Logistic(random_state=10,\n estimation_score=method).fit(X, y)\n assert (np.sign(w) == np.sign(l1log.coef_)).mean() >= .8\n assert_allclose(w, l1log.coef_, rtol=.5, atol=.5)\n\n\n@pytest.mark.skip(reason=\"Logistic is not currently finished\")\ndef test_l1logistic_multiclass():\n \"\"\"Test that multiclass L1 Logistic runs in the UoI framework when all\n classes share a support.\"\"\"\n n_features = 4\n n_inf = 3\n X, y, w, b = make_classification(n_samples=1000,\n random_state=6,\n n_classes=3,\n n_informative=n_inf,\n n_features=n_features,\n shared_support=True)\n l1log = UoI_L1Logistic().fit(X, y)\n print()\n print(w)\n print(l1log.coef_)\n assert_array_equal(np.sign(w), np.sign(l1log.coef_))\n assert_allclose(w, l1log.coef_, atol=.5)\n\n\ndef test_estimation_score_usage():\n \"\"\"Test the ability to change the estimation score in UoI L1Logistic\"\"\"\n methods = ('acc', 'log')\n X, y, w, b = make_classification(n_samples=100,\n random_state=6,\n n_informative=2,\n n_features=6)\n scores = []\n for method in methods:\n l1log = UoI_L1Logistic(random_state=12, estimation_score=method)\n assert_equal(l1log.estimation_score, method)\n l1log.fit(X, y)\n score = np.max(l1log.scores_)\n scores.append(score)\n assert_equal(len(set(scores)), len(methods))\n\n\ndef test_set_random_state():\n \"\"\"Tests whether random states are handled correctly.\"\"\"\n X, y, w, b = make_classification(n_samples=100,\n random_state=60,\n n_informative=4,\n n_features=5,\n w_scale=4.)\n # same state\n l1log_0 = UoI_L1Logistic(random_state=13)\n l1log_1 = UoI_L1Logistic(random_state=13)\n l1log_0.fit(X, y)\n l1log_1.fit(X, y)\n assert_array_equal(l1log_0.coef_, l1log_1.coef_)\n\n # different state\n l1log_1 = UoI_L1Logistic(random_state=14)\n l1log_1.fit(X, y)\n assert not np.array_equal(l1log_0.coef_, l1log_1.coef_)\n\n # different state, not set\n l1log_0 = UoI_L1Logistic()\n l1log_1 = UoI_L1Logistic()\n l1log_0.fit(X, y)\n l1log_1.fit(X, y)\n assert not np.array_equal(l1log_0.coef_, l1log_1.coef_)\n","sub_path":"tests/test_uoi_l1logistic.py","file_name":"test_uoi_l1logistic.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"392454739","text":"import random\n\n'''You have a Dice class which has 6 dice\nYou can roll all of them with roll()\nCheck the current rolled numbers with get_current()\nYou can reroll with reroll()\nYour task is to get where all dice is a 6'''\n\n\nclass Dice(object):\n\n def __init__(self):\n self.dice = [0, 0, 0, 0, 0, 0]\n\n def roll(self):\n for i in range(len(self.dice)):\n self.dice[i] = random.randint(1,6)\n return self.dice\n\n def get_current(self, index=None):\n if index != None:\n return self.dice[index]\n else:\n return self.dice\n\n def reroll(self, index=None):\n if index != None:\n self.dice[index] = random.randint(1,6)\n else:\n self.roll()\n\n\n\ndice = Dice()\nsixsixsix = False\ndice.roll()\nroll = dice.get_current()\n\n\nfor x in range(6):\n while(dice.get_current(x)) != 6:\n dice.reroll(x)\n\nfor x in roll:\n print (x)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"week-04/day-1/dice.py","file_name":"dice.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"484180671","text":"from decimal import Decimal\n\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils.functional import cached_property\nfrom django.utils.text import format_lazy\nfrom django.utils.translation import ugettext_lazy as _\nfrom shapely.geometry import CAP_STYLE, JOIN_STYLE, mapping\n\nfrom c3nav.mapdata.fields import GeometryField\nfrom c3nav.mapdata.models.geometry.base import GeometryMixin\nfrom c3nav.mapdata.models.locations import SpecificLocation\nfrom c3nav.mapdata.utils.cache.changes import changed_geometries\nfrom c3nav.mapdata.utils.json import format_geojson\n\n\nclass SpaceGeometryMixin(GeometryMixin):\n space = models.ForeignKey('mapdata.Space', on_delete=models.CASCADE, verbose_name=_('space'))\n\n class Meta:\n abstract = True\n\n @cached_property\n def level_id(self):\n return self.space.level_id\n\n def get_geojson_properties(self, *args, **kwargs) -> dict:\n result = super().get_geojson_properties(*args, **kwargs)\n if hasattr(self, 'get_color'):\n color = self.get_color()\n if color:\n result['color'] = color\n if hasattr(self, 'opacity'):\n result['opacity'] = self.opacity\n return result\n\n @property\n def subtitle(self):\n base_subtitle = super().subtitle\n space = getattr(self, '_space_cache', None)\n if space is not None:\n level = getattr(space, '_level_cache', None)\n if level is not None:\n return format_lazy(_('{category}, {space}, {level}'),\n category=base_subtitle,\n space=space.title,\n level=level.title)\n return format_lazy(_('{category}, {space}'),\n category=base_subtitle,\n level=space.title)\n return base_subtitle\n\n def register_change(self, force=True):\n space = self.space\n force = force or self.all_geometry_changed\n if force or self.geometry_changed:\n changed_geometries.register(space.level_id, space.geometry.intersection(\n self.geometry if force else self.get_changed_geometry()\n ))\n\n def details_display(self):\n result = super().details_display()\n result['display'].insert(3, (\n _('Space'),\n {\n 'id': self.space_id,\n 'slug': self.space.get_slug(),\n 'title': self.space.title,\n 'can_search': self.space.can_search,\n },\n ))\n return result\n\n def register_delete(self):\n space = self.space\n changed_geometries.register(space.level_id, space.geometry.intersection(self.geometry))\n\n def save(self, *args, **kwargs):\n self.register_change()\n super().save(*args, **kwargs)\n\n\nclass Column(SpaceGeometryMixin, models.Model):\n \"\"\"\n An column in a space, also used to be able to create rooms within rooms.\n \"\"\"\n geometry = GeometryField('polygon')\n\n class Meta:\n verbose_name = _('Column')\n verbose_name_plural = _('Columns')\n default_related_name = 'columns'\n\n\nclass Area(SpaceGeometryMixin, SpecificLocation, models.Model):\n \"\"\"\n An area in a space.\n \"\"\"\n geometry = GeometryField('polygon')\n\n class Meta:\n verbose_name = _('Area')\n verbose_name_plural = _('Areas')\n default_related_name = 'areas'\n\n def _serialize(self, **kwargs):\n result = super()._serialize(**kwargs)\n return result\n\n def details_display(self):\n result = super().details_display()\n result['editor_url'] = reverse('editor.areas.edit', kwargs={'space': self.space_id, 'pk': self.pk})\n return result\n\n\nclass Stair(SpaceGeometryMixin, models.Model):\n \"\"\"\n A stair\n \"\"\"\n geometry = GeometryField('linestring')\n\n class Meta:\n verbose_name = _('Stair')\n verbose_name_plural = _('Stairs')\n default_related_name = 'stairs'\n\n\nclass Ramp(SpaceGeometryMixin, models.Model):\n \"\"\"\n A ramp\n \"\"\"\n geometry = GeometryField('polygon')\n\n class Meta:\n verbose_name = _('Ramp')\n verbose_name_plural = _('Ramps')\n default_related_name = 'ramps'\n\n\nclass Obstacle(SpaceGeometryMixin, models.Model):\n \"\"\"\n An obstacle\n \"\"\"\n geometry = GeometryField('polygon')\n height = models.DecimalField(_('height'), max_digits=6, decimal_places=2, default=0.8,\n validators=[MinValueValidator(Decimal('0'))])\n\n class Meta:\n verbose_name = _('Obstacle')\n verbose_name_plural = _('Obstacles')\n default_related_name = 'obstacles'\n\n def _serialize(self, geometry=True, **kwargs):\n result = super()._serialize(geometry=geometry, **kwargs)\n result['height'] = float(str(self.height))\n return result\n\n\nclass LineObstacle(SpaceGeometryMixin, models.Model):\n \"\"\"\n An obstacle that is a line with a specific width\n \"\"\"\n geometry = GeometryField('linestring')\n width = models.DecimalField(_('width'), max_digits=4, decimal_places=2, default=0.15)\n height = models.DecimalField(_('height'), max_digits=6, decimal_places=2, default=0.8,\n validators=[MinValueValidator(Decimal('0'))])\n\n class Meta:\n verbose_name = _('Line Obstacle')\n verbose_name_plural = _('Line Obstacles')\n default_related_name = 'lineobstacles'\n\n def serialize(self, geometry=True, **kwargs):\n result = super().serialize(geometry=geometry, **kwargs)\n if geometry:\n result.move_to_end('buffered_geometry')\n return result\n\n def _serialize(self, geometry=True, **kwargs):\n result = super()._serialize(geometry=geometry, **kwargs)\n result['width'] = float(str(self.width))\n result['height'] = float(str(self.height))\n if geometry:\n result['buffered_geometry'] = format_geojson(mapping(self.buffered_geometry))\n return result\n\n @property\n def buffered_geometry(self):\n return self.geometry.buffer(self.width / 2, join_style=JOIN_STYLE.mitre, cap_style=CAP_STYLE.flat)\n\n def to_geojson(self, *args, **kwargs):\n result = super().to_geojson(*args, **kwargs)\n result['original_geometry'] = result['geometry']\n result['geometry'] = format_geojson(mapping(self.buffered_geometry))\n return result\n\n\nclass POI(SpaceGeometryMixin, SpecificLocation, models.Model):\n \"\"\"\n An point of interest\n \"\"\"\n geometry = GeometryField('point')\n\n class Meta:\n verbose_name = _('Point of Interest')\n verbose_name_plural = _('Points of Interest')\n default_related_name = 'pois'\n\n def details_display(self):\n result = super().details_display()\n result['editor_url'] = reverse('editor.pois.edit', kwargs={'space': self.space_id, 'pk': self.pk})\n return result\n\n\nclass Hole(SpaceGeometryMixin, models.Model):\n \"\"\"\n A hole in the ground of a space, e.g. for stairs.\n \"\"\"\n geometry = GeometryField('polygon')\n\n class Meta:\n verbose_name = _('Hole')\n verbose_name_plural = _('Holes')\n default_related_name = 'holes'\n\n\nclass AltitudeMarker(SpaceGeometryMixin, models.Model):\n \"\"\"\n An altitude marker\n \"\"\"\n geometry = GeometryField('point')\n altitude = models.DecimalField(_('altitude'), null=False, max_digits=6, decimal_places=2)\n\n class Meta:\n verbose_name = _('Altitude Marker')\n verbose_name_plural = _('Altitude Markers')\n default_related_name = 'altitudemarkers'\n\n @property\n def title(self):\n return '%s (%sm)' % (super().title, self.altitude)\n","sub_path":"src/c3nav/mapdata/models/geometry/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":7790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"284248828","text":"import sys\nimport logging\nimport os.path\nimport numpy as np\nimport json\nimport lasfile\nimport tornado\nimport tornado.autoreload\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nimport tornado.websocket\n\n\nclass SocketConnection(tornado.websocket.WebSocketHandler):\n def open(self):\n pass\n\n def on_close(self):\n pass\n\n def on_message(self, msg):\n msg = json.loads(msg)\n msg_type = msg.get('type')\n msg_data = msg.get('data')\n if msg_type == 'load':\n self.init_stream('../static/{0}'.format(msg_data['filename']))\n self.send_header()\n self.send_chunk()\n if msg_type == 'next_chunk':\n self.send_chunk()\n\n def init_stream(self, filename):\n self.point_cloud = lasfile.LASFile(filename)\n\n def send_header(self):\n data = {\n 'num_points': self.point_cloud.num_points,\n 'chunk_size': self.point_cloud.chunk_size,\n 'scale_factor': self.point_cloud.scale_factor,\n 'center': self.point_cloud.center,\n 'extent': self.point_cloud.extents\n }\n self.send_msg('header', data)\n\n def send_msg(self, msg_type, data):\n self.write_message({'type': msg_type, 'data': data})\n\n def send_chunk(self):\n try:\n chunk = self.point_cloud.next()\n self.write_message(bytes(chunk), True)\n except StopIteration:\n return\n\n\n\nclass StaticFileHandler(tornado.web.StaticFileHandler):\n def get(self, path, include_body=True):\n if not path:\n path = 'index.html'\n return super(StaticFileHandler, self).get(path, include_body)\n\n def set_extra_headers(self, path):\n if self.settings.get('debug'):\n self.set_header('Cache-control', 'no-cache')\n\n\nroutes = [\n (r'/socket', SocketConnection),\n (r'/(.*)$', StaticFileHandler, {'path': './app'}),\n]\n\n\nif __name__ == '__main__':\n tornado.options.parse_command_line()\n tornado.autoreload.start()\n tornado.web.Application(routes, debug=True).listen(8080)\n tornado.ioloop.IOLoop.instance().start()\n\n\n","sub_path":"plasio/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"113795608","text":"from bioblend.galaxy import GalaxyInstance\nfrom typing import Tuple, List\nfrom workflow import BaseWorkflow, GalaxyWorkflow\nimport ansible_bridge\nimport planemo_bridge\nimport logging\nimport string\nimport random\nimport re\n\nlog = logging.getLogger(\"GalaxyBenchmarker\")\n\n\nclass Galaxy:\n def __init__(self, url, user_key, shed_install=False,\n ssh_user=None, ssh_key=None, galaxy_root_path=None,\n galaxy_config_dir=None, galaxy_user=None):\n self.url = url\n self.user_key = user_key\n self.shed_install = shed_install\n self.ssh_user = ssh_user\n self.ssh_key = ssh_key\n\n self.galaxy_root_path = galaxy_root_path\n self.galaxy_config_dir = galaxy_config_dir\n self.galaxy_user = galaxy_user\n\n self.instance = GalaxyInstance(url, key=user_key)\n\n def impersonate(self, user=None, user_key=None) -> GalaxyInstance:\n \"\"\"\n Returns a GalaxyInstance for the given user_key. If user is provided,\n user_key is fetched from Galaxy.\n \"\"\"\n if user is not None:\n user_id = self.instance.users.get_users(f_name=user)[0][\"id\"]\n user_key = self.instance.users.get_user_apikey(user_id)\n return GalaxyInstance(self.url, key=user_key)\n\n def create_user(self, username) -> Tuple:\n \"\"\"\n Creates a new user (if not already created) with username and a random password and returns\n its user_id and api_key as a tuple.\n \"\"\"\n if len(self.instance.users.get_users(f_name=username)) == 0:\n password = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(32)])\n self.instance.users.create_local_user(username,\n \"{username}@galaxy.uni.andreas-sk.de\".format(username=username),\n password)\n\n user_id = self.instance.users.get_users(f_name=username)[0][\"id\"]\n user_key = self.instance.users.get_user_apikey(user_id)\n\n if user_key == \"Not available.\":\n user_key = self.instance.users.create_user_apikey(user_id)\n\n return user_id, user_key\n\n def delete_all_histories_for_user(self, user, purge=True):\n \"\"\"\n Deletes and - if not set otherwise - purges for a given username all its histories.\n \"\"\"\n impersonated = self.impersonate(user)\n histories = impersonated.histories.get_histories()\n\n for history in histories:\n impersonated.histories.delete_history(history[\"id\"], purge)\n\n def install_tools_for_workflows(self, workflows: List[BaseWorkflow]):\n log.info(\"Installing all necessary workflow-tools on Galaxy.\")\n for workflow in workflows:\n if type(workflow) is GalaxyWorkflow:\n log.info(\"Installing tools for workflow '{workflow}'\".format(workflow=workflow.name))\n planemo_bridge.install_workflow([workflow.path], self.instance)\n\n def deploy_job_conf(self):\n \"\"\"\n Deploys the job_conf.xml-file to the Galaxy-Server.\n \"\"\"\n # Hostname parsed from the Galaxy-URL\n host = re.findall(\"^[a-z][a-z0-9+\\-.]*://([a-z0-9\\-._~%!$&'()*+,;=]+@)?([a-z0-9\\-._~%]+|\\[[a-z0-9\\-.\"\n + \"_~%!$&'()*+,;=:]+\\])\", self.url)[0][1]\n\n if None in (self.ssh_user, self.ssh_key, self.galaxy_root_path, self.galaxy_config_dir, self.galaxy_user):\n raise ValueError(\"ssh_user, ssh_key, galaxy_root_path, galaxy_config_dir, and galaxy_user need \"\n \"to be set in order to deploy the job_conf.xml-file!\")\n\n values = {\n \"galaxy_root_path\": self.galaxy_root_path,\n \"galaxy_config_dir\": self.galaxy_config_dir,\n \"galaxy_user\": self.galaxy_user\n }\n ansible_bridge.run_playbook(\"prepare_galaxy.yml\", host, self.ssh_user, self.ssh_key, values)\n","sub_path":"galaxy_benchmarker/galaxy_bridge.py","file_name":"galaxy_bridge.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"254576235","text":"from flask import Flask, request, abort\nfrom flask_cors import cross_origin\nfrom urllib.parse import parse_qs\nimport os, json, codecs, re, random\n\nfrom linebot import (LineBotApi, WebhookHandler)\nfrom linebot.exceptions import (InvalidSignatureError)\nfrom linebot.models import *\n\n#導入env, model\nfrom env import *\nfrom model import *\n#導入Others\nfrom Others.flexMessageJSON import *\n#導入Controllers\nfrom Controllers.messageController import *\nfrom Controllers.locationController import *\nfrom Controllers.postbackController import *\n#導入Managers\nfrom Managers.channelManager import *\nfrom Managers.messageManager import *\nfrom Managers.statementManager import *\n#導入Services\nfrom Services.geocodingService import *\n\napp = Flask(__name__)\n\nline_bot_api = LineBotApi(GET_SECRET(\"ACCESS_TOKEN\")) \nhandler = WebhookHandler(GET_SECRET(\"API_SECRET\"))\n\n####################檢查uWSGI->Flask是否正常運作####################\n@app.route(\"/\")\ndef index():\n return 'BotApp is Working!'\n\n####################一般callback####################\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # handle webhook body\n try:\n create_table()\n handler.handle(body, signature)\n except InvalidSignatureError:\n print(\"Invalid signature. Please check your channel access token/channel secret.\")\n abort(400)\n\n return 'OK'\n\n####################推播####################\n@app.route(\"/pushing\", methods=['POST'])\ndef pushing():\n data = json.loads(request.get_data())\n mtype = data.get('type', 'text')\n title = data.get('title', '')\n message = data.get('message', '')\n channel_id = data.get('channel_id', '')\n template = data.get('template', None)\n status = pushing_process(mtype, title, message, channel_id) if template == None else pushing_template(title, message, channel_id, template)\n return json.dumps({'msg': status})\n\n####################[匯入, 拉黑, JSON]: [詞條]####################\n#詞條拉黑\n@app.route(\"/operateStatement\", methods=['POST'])\ndef operateStatement():\n data = json.loads(request.get_data())\n action = data[\"action\"]\n adjust = data[\"adjust\"]\n statement_id = data[\"statement_id\"]\n operate_statement(action, adjust, statement_id)\n return json.dumps({'msg': 'ok'})\n\n#匯入詞條\n@app.route(\"/importStatement\", methods=['POST'])\ndef importStatement():\n data = json.loads(request.get_data())\n for item in data[\"data\"]:\n create_statement(item[\"keyword\"], item[\"response\"], 0, 0)\n return json.dumps({'msg': 'ok'})\n\n#詞條轉JSON\n@app.route(\"/getStatementJSON\", methods=['POST'])\ndef getStatementJSON():\n data = json.loads(request.get_data())\n channel_id = data[\"channel_id\"] if data[\"channel_id\"] and data[\"channel_id\"]!=\"ALL\" else \"ALL\"\n return json.dumps(get_line_statement_table(channel_id))\n\n#推播紀錄轉JSON\n@app.route(\"/getPushedJSON\", methods=['POST'])\ndef getPushedJSON():\n return json.dumps(get_line_pushed_table())\n\n####################小功能####################\n##隨機產生後綴字\ndef getPostfix():\n p = random.randint(1,10)\n postfix = get_postfix() if get_postfix() and p%5==0 else \"\"\n return postfix\n\n#貼圖unicode轉line編碼 [請傳入 sticon(u\"\\U數字\") ]\ndef sticon(unic):\n return codecs.decode(json.dumps(unic).strip('\"'), 'unicode_escape')\n\n#取得ChannelId [如果是群組或聊天室,一樣回傳channelId,不是userId]\ndef getChannelId(event):\n e_source = event.source\n return e_source.room_id if e_source.type == \"room\" else e_source.group_id if e_source.type == \"group\" else e_source.user_id\n\n#取得UserId\ndef getUserId(event):\n return event.source.user_id if hasattr(event.source, 'user_id') else None\n\n####################取得EVENT物件、發送訊息####################\ndef get_event_obj(event):\n ##取得頻道及使用者ID\n channelId = getChannelId(event)\n userId = getUserId(event)\n ##建頻道資料\n if userId: create_channel(userId)\n create_channel(channelId)\n ##取得頻道資料\n channelData = get_channel(channelId)\n userData = get_channel(userId) if userId else None\n \n profileName = \"\"\n try: profileName = line_bot_api.get_profile(userId).display_name if userId else \"\"\n except: profileName = \"\"\n\n return {\n \"reply_token\": event.reply_token,\n \"channelPK\": get_pk_by_channel_id(channelId),\n \"userPK\": get_pk_by_channel_id(userId),\n \"channelId\": channelId,\n \"userId\": userId,\n \"lineMessage\": \"\", #取得收到的訊息\n \"lineMessageType\": event.message.type if hasattr(event, 'message') else None,\n \"level\": int(int(userData['exp'])/10) if userData else int(int(channelData['exp'])/10), #等級\n \"exp\": int(userData['exp'])%10 if userData else int(channelData['exp'])%10, #經驗值每+10升一級\n \"nickname\": userData['nickname'] if userData and int(int(userData['exp'])/10)>=2 and userData['nickname'] else profileName,\n \"mute\": channelData['mute'],\n \"global_talk\": channelData['global_talk'],\n \"replyList\": [], #初始化傳送內容(可為List或單一Message Object)\n \"replyLog\": [\"\", 0, \"\"], #發出去的物件準備寫入紀錄用 [訊息, 有效度(0=功能型, 1=關鍵字, 2=一般型), 訊息類型]\n \"postfix\": getPostfix()\n }\n\ndef send_reply(GET_EVENT, STORE_LOG = False):\n ##儲存訊息\n if STORE_LOG:\n if GET_EVENT[\"replyLog\"][0]: store_replied(GET_EVENT[\"replyLog\"][0], GET_EVENT[\"replyLog\"][1], GET_EVENT[\"replyLog\"][2], GET_EVENT[\"channelPK\"]) #記錄機器人本次回的訊息\n store_received(GET_EVENT[\"lineMessage\"], GET_EVENT[\"lineMessageType\"], GET_EVENT[\"channelPK\"], GET_EVENT[\"userPK\"]) #儲存本次收到的語句\n ####回傳給LINE\n line_bot_api.reply_message(GET_EVENT[\"reply_token\"], GET_EVENT[\"replyList\"])\n\n####################[加入, 退出]: [好友, 聊天窗]####################\n@handler.add(FollowEvent)\ndef handle_follow(event):\n ##取得EVENT物件\n GET_EVENT = get_event_obj(event)\n flexObject = flexStatusMenu({\n \"global_talk_text\": \"所有人教的\" if GET_EVENT['global_talk'] else \"本頻道教的\", \n \"mute_text\": \"安靜\" if GET_EVENT['mute'] else \"可以說話\", \n \"global_talk\": GET_EVENT['global_talk'], \n \"mute\": GET_EVENT['mute']\n })\n GET_EVENT[\"replyList\"] = [\n TextSendMessage(text=GET_EVENT[\"nickname\"] + \",歡迎您成為本熊貓的好友!\" + sticon(u\"\\U00100097\")),\n FlexSendMessage(alt_text = \"主選單\", contents = flexMainMenu(GET_EVENT[\"channelId\"], GET_EVENT[\"level\"])),\n FlexSendMessage(alt_text = flexObject[0], contents = flexObject[1])\n ]\n ##發送回覆\n send_reply(GET_EVENT, False)\n@handler.add(JoinEvent)\ndef handle_join(event):\n ##取得EVENT物件\n GET_EVENT = get_event_obj(event)\n flexObject = flexStatusMenu({\n \"global_talk_text\": \"所有人教的\" if GET_EVENT['global_talk'] else \"本頻道教的\", \n \"mute_text\": \"安靜\" if GET_EVENT['mute'] else \"可以說話\", \n \"global_talk\": GET_EVENT['global_talk'], \n \"mute\": GET_EVENT['mute']\n })\n GET_EVENT[\"replyList\"] = [\n TextSendMessage(text=\"大家好我叫酷熊貓\" + sticon(u\"\\U00100097\")),\n FlexSendMessage(alt_text = \"主選單\", contents = flexMainMenu(GET_EVENT[\"channelId\"], GET_EVENT[\"level\"])),\n FlexSendMessage(alt_text = flexObject[0], contents = flexObject[1])\n ]\n ##發送回覆\n send_reply(GET_EVENT, False)\n@handler.add(UnfollowEvent)\ndef handle_unfollow(event):\n remove_channel(getChannelId(event))\n@handler.add(LeaveEvent)\ndef handle_leave(event):\n pass\n #remove_channel(getChannelId(event))\n\n####################PostbackEvent處理區#################### \n@handler.add(PostbackEvent)\ndef handle_postback(event):\n ##取得EVENT物件\n GET_EVENT = get_event_obj(event)\n data = parse_qs(event.postback.data)\n \n ##發送回覆\n GET_EVENT = postback_processer(GET_EVENT, data)\n send_reply(GET_EVENT, False)\n\n####################文字訊息處理區#################### \n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n ##取得EVENT物件\n GET_EVENT = get_event_obj(event)\n GET_EVENT[\"lineMessage\"] = event.message.text\n\n ##發送\n GET_EVENT = message_processer(GET_EVENT)\n send_reply(GET_EVENT, True)\n\n####################貼圖訊息處理區#################### \n@handler.add(MessageEvent, message=StickerMessage)\ndef handle_sticker_message(event):\n ##取得EVENT物件\n GET_EVENT = get_event_obj(event)\n GET_EVENT[\"lineMessage\"] = event.message.package_id + ',' + event.message.sticker_id\n GET_EVENT[\"replyList\"] = StickerSendMessage(package_id=event.message.package_id, sticker_id=event.message.sticker_id)\n GET_EVENT[\"replyLog\"] = [GET_EVENT[\"lineMessage\"], 2, 'sticker']\n GET_EVENT[\"replyList\"] = [GET_EVENT[\"replyList\"], TextSendMessage(text=GET_EVENT[\"postfix\"])] if GET_EVENT[\"postfix\"] else GET_EVENT[\"replyList\"]\n ##發送\n send_reply(GET_EVENT, True)\n\n####################位置訊息處理區#################### \n@handler.add(MessageEvent, message=LocationMessage)\ndef handle_location_message(event):\n ##取得EVENT物件\n LOCATION_INFO = {\n \"title\": str(event.message.title),\n \"addr\": addr_format(str(event.message.address)),\n \"lat\": float(event.message.latitude),\n \"lng\": float(event.message.longitude)\n }\n GET_EVENT = get_event_obj(event)\n GET_EVENT[\"lineMessage\"] = LOCATION_INFO[\"title\"] + ',' + LOCATION_INFO[\"addr\"] + ',' + str(LOCATION_INFO[\"lat\"]) + ',' + str(LOCATION_INFO[\"lng\"])\n \n ##發送\n GET_EVENT = location_processer(GET_EVENT, LOCATION_INFO)\n send_reply(GET_EVENT, True)\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"519424096","text":"# -*- coding: utf-8 -*-\n# ---\n# @Institution: Automation,T&E,Turing,HQ\n# @Time: 2021/6/7\n# @File: test_sharing _of_requested_bugreport_declined_while_being_taken_11.3.2\n# @Author: pengleiyang\n# @E-mail: pengleiyang@huaqin.com\n# @Desc: test_sharing _of_requested_bugreport_declined_while_being_taken_11.3.2自动化测试脚本\n# @update: Record important updates\n# ---\n\nimport os\nimport unittest\nimport time\nimport warnings\nimport uiautomator2 as u2\nfrom PIL import Image\nfrom utils.device_info_util.device_info import DeviceInfo\nfrom utils.pic_util.pic_util import PicUtil\n\n'''\n只写到11.3.1判断是否通过\n'''\n\n\nclass SharingOfRequestedBugreportDeclinedWhileBeingTaken(unittest.TestCase):\n def setUp(self):\n warnings.simplefilter('ignore', ResourceWarning) # 屏蔽警报信息\n print(\"测试开始\")\n print(\"获取手机设备信息!\")\n self.device = DeviceInfo()\n self.devices = self.device.check_device()[0]\n device = self.devices[0] # 暂时默认只连接一台手机\n print(device)\n self.d = u2.connect(device) # 连接待测设备\n self.d.unlock()\n print(\"解锁成功\")\n\n def test_11_3_2(self):\n print(\"启动cts测试应用!\")\n os.system(\"adb shell am start -n com.android.cts.verifier/com.android.cts.verifier.CtsVerifierActivity\")\n self.assertFalse(self.d.exists(text=\"Folded\") and self.d.exists(resourceId=\"com.android.cts.verifier:id/export\")\n , \"cts未在主界面,请检查\")\n for i in range(100):\n if self.d.exists(text=\"Device Owner Requesting Bugreport Tests\"):\n self.d(text=\"Device Owner Requesting Bugreport Tests\").click()\n if self.d.exists(text=\"Check device owner\"):\n # points = self.d(text=\"Profile owner installed\").info.get(\"bounds\")\n # print(points)\n im = self.d(text=\"Check device owner\").screenshot()\n pic_dir_path = os.path.abspath(os.path.join(os.getcwd(), \"..\")) + \"/report/pic/\" # 测试结果图片文件夹保存路径\n now_time = time.strftime(\"%Y-%m-%d-%H_%M_%S\", time.localtime(time.time()))\n pic_path = pic_dir_path + \"test_11_3_1_\" + now_time + \".jpg\" # 测试结果图片保存路径\n im.save(pic_path)\n image = Image.open(pic_path)\n image = image.convert('RGB')\n color = PicUtil().get_dominant_color(image)\n print(color)\n # 绿色RGB值范围: 75-100,95-120, 20-40\n # 红色RGB值范围: 120-130, 62-73, 55-65\n R, G, B = color\n if 75 < int(R) < 95 < int(G) < 120 and 20 < int(B) < 40:\n print(\"11.3.1测试pass!\")\n return True\n else:\n self.assertFalse(\"11.1.1测试fail!\")\n break\n else:\n self.d.swipe(0.5, 0.9, 0.5, 0.2)\n time.sleep(2)\n","sub_path":"testcases/managedprovisioning/deviceownerrequestingbugreporttests/test_sharing _of_requested_bugreport_declined_while_being_taken_11.3.2.py","file_name":"test_sharing _of_requested_bugreport_declined_while_being_taken_11.3.2.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"16973002","text":"import io\nimport time\nimport pymorphy2\nimport re\nimport os\n\nclass Normalizer:\n morph = pymorphy2.MorphAnalyzer()\n regex = re.compile('[^а-я]')\n\n def norm(self, x):\n return self.morph.parse(x)[0].normal_form\n\n def prepareText(self, text):\n return self.regex.sub(\" \", text.lower()).split()\n\n def normText(self, oldPath, newPath):\n oldFile = open(oldPath, \"r\").read()\n old = self.prepareText(str(oldFile))\n new = []\n for word in old:\n new.append(self.norm(word))\n newFile = open(newPath, \"w\")\n for word in new:\n newFile.write(\" \" + word)\n newFile.close()\n return\n\nif __name__ == \"__main__\":\n\n # Имя автора\n authorNames = [\"А. Беляев\", \"А. Чехов\", \"Д. Лондон\", \"Л. Толстой\", \"М. Зощенко\", \"Макс Фрай\", \"Марк Твен\", \"Н. Носов\", \"Стругацкие\"]\n\n n = Normalizer();\n start = time.time()\n for authorName in authorNames:\n i = 1\n path = 'Корпуса/' + authorName + \"/Исходники\"\n\n for file in os.listdir(path):\n n.normText(path + \"/\" + file, \"Корпуса/\" + authorName + \"/Обработано/\" + authorName + \" \" + str(i) + \".txt\")\n i += 1\n print(authorName + \" is DONE!\")\n\n end = time.time()\n print(\"TOTAL: \" + str(int(end - start)) + \" sec.\")\n","sub_path":"venv/fileLoad.py","file_name":"fileLoad.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"629308824","text":"from __future__ import print_function\nimport keras\n#from keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nfrom keras.applications import InceptionV3\nfrom keras.preprocessing.image import ImageDataGenerator\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nbatch_size = 32\nnum_classes = 2\nepochs = 200\n\n# input image dimensions\nimg_rows, img_cols = 256, 256\n\n# the data, split between train and test sets\nx_train = np.load('cropTrain_1800.npy')\nx_test = np.load('cropTest_200.npy')\n\n#(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\ny_train = np.zeros((x_train.shape[0],2))\ny_train[:900,0] = 1\ny_train[900:,1] = 1\ny_test = np.zeros((x_test.shape[0],2))\ny_test[:100,0] = 1\ny_test[100:,1] = 1\n\ndatagen = ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True)\n\ndatagen.fit(x_train)\n\n\n# convert class vectors to binary class matrices\n#y_train = keras.utils.to_categorical(y_train, num_classes)\n#y_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(lr=0.01),\n metrics=['accuracy'])\n\n#hist = model.fit(x_train, y_train,\n# batch_size=batch_size,\n# epochs=epochs,\n# verbose=1,\n# validation_data=(x_test, y_test))\n\nhist = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\n steps_per_epoch=len(x_train) / batch_size, epochs=epochs, validation_data=(x_test, y_test))\n\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n\nplt.plot(hist.history['loss'],'r')\nplt.plot(hist.history['val_loss'],'b')\nplt.show()","sub_path":"mn.py","file_name":"mn.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"456010625","text":"#\r\n#============================== GO ==============================#\r\nimport network_base_test as demo\r\nimport numpy, pickle_data as pickle\r\nimport cv2\r\n\r\ndef pic_2data(pic):\r\n pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY)\r\n pic = cv2.resize(pic, (28,28))\r\n data = numpy.asarray(pic)\r\n return numpy.reshape(data, [784])\r\n\r\nmodule_file = '../MODEL_DATA/decent_network.plk'\r\ntraining_data, validation_data, test_data = pickle.load_data_wrapper()\r\nmodel = pickle.load_network(module_file)\r\n# demo.evaluate(model, test_data, True)\r\nfor _ in range (9):\r\n index = int(numpy.random.randint(1,1000,1))\r\n demo.sample(model.results_list[-1], test_data, index)\r\n\r\n# Video demo\r\n# for i in range(1000):\r\n# v, frame = cv2.VideoCapture(0).read()\r\n# cv2.imshow('XIAOLI', frame)\r\n# demo.test(model.results_list[-1], pic_2data(frame))\r\n# cv2.waitKey(1)\r\n\r\n#============================== XIAOLI-20170608 ==============================#","sub_path":"bpn_foundation/MNIST_DEMO.py","file_name":"MNIST_DEMO.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"93094827","text":"\"\"\"\nTalk of Europe Creative Camp #2 :: Wordcloud project :: SQLAlchemy model\n\nCopyright 2015, Konstantin Tretyakov, Ilya Kuzovkin, Alexander Tkachenko.\nLicense: MIT\n\"\"\"\n\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\ndef _saobject_repr(self):\n s = [self.__class__.__name__, '\\n']\n for c in self.__class__.__table__.columns:\n s.extend(['\\t', c.name, ': ', unicode(getattr(self, c.name)).encode('utf-8'), '\\n'])\n return ''.join(s)\n\n\ndef _saobject_as_dict(self):\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\ndef _saobject_as_tuple(self):\n return tuple([getattr(self, n.name) for n in self.__table__.columns])\n\n\nBase.__repr__ = _saobject_repr\nBase._as_dict = _saobject_as_dict\nBase._as_tuple = _saobject_as_tuple\n\n\nclass Speech(Base):\n __tablename__ = 'speech'\n id = Column(Integer, primary_key=True)\n date = Column(Date, nullable=False, index=True)\n speaker_uri = Column(Unicode(200), nullable=False, index=True)\n first_name = Column(Unicode(100), nullable=False)\n last_name = Column(Unicode(100), nullable=False)\n country = Column(String(3), nullable=False, index=True)\n speech = Column(Unicode, nullable=False)\n lang = Column(String(2))\n\n\ndef open_db(db_url = None):\n \"Returns an initialized Session object. If db_url is not specified, uses get_config().db_url\"\n if db_url is None:\n from talkofeuropedb.config import get_config\n db_url = get_config().db_url\n e = create_engine(db_url)\n Session = sessionmaker(e)\n return Session()\n\n","sub_path":"src/talkofeuropedb/talkofeuropedb/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"399855027","text":"# -*- coding: utf-8 -*-\n# 2. Написать два алгоритма нахождения i-го по счёту простого числа.\n# Первый - использовать алгоритм решето Эратосфена.\n# Второй - без использования \"решета\".\n# Проанализировать скорость и сложность алгоритмов.\n\nimport cProfile\n\n\n# Вариант 1 - Решето\n\ndef gen_sieve(n):\n sieve = [i for i in range(n + 1)]\n sieve[0], sieve[1] = 0, 0\n return sieve\n\n\ndef fix_digs(sieve):\n n = len(sieve)\n for i in range(2, n):\n if sieve[i] != 0:\n k = i + i\n while k < n:\n sieve[k] = 0\n k += i\n\n\ndef add_digs(sieve, numbers):\n sieve.append(numbers)\n fix_digs(sieve)\n\n\ndef get_dig(n):\n sieve = gen_sieve(n)\n fix_digs(sieve)\n first_index = 2\n k = 0\n numbers = len(sieve)\n\n while k != n:\n for i in range(first_index, numbers):\n if sieve[i] != 0:\n k += 1\n add_digs(sieve, numbers)\n first_index = numbers\n numbers += 1\n\n return sieve[first_index - 1]\n\n\n# print(get_dig(15))\n\n# Результаты timeit n=100\n#\n# get_dig(10)\n# 100 loops, best of 3: 108 usec per loop\n# get_dig(100)\n# 100 loops, best of 3: 21.1 msec per loop\n# get_dig(200)\n# 100 loops, best of 3: 119 msec per loop\n\n# Результаты cProfile\n#\n# cProfile.run('get_dig(100)') - 1777 function calls in 0.029 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 443 0.028 0.000 0.028 0.000 lesson04_hw02.py:18(fix_digs)\n# 442 0.000 0.000 0.029 0.000 lesson04_hw02.py:28(add_digs)\n# 444 0.000 0.000 0.000 0.000 {built-in method builtins.len}\n# 442 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n\n# cProfile.run('get_dig(1000)') - 27689 function calls in 7.157 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 6921 7.137 0.001 7.138 0.001 lesson04_hw02.py:18(fix_digs)\n# 6920 0.006 0.000 7.146 0.001 lesson04_hw02.py:28(add_digs)\n# 6922 0.001 0.000 0.001 0.000 {built-in method builtins.len}\n# 6920 0.001 0.000 0.001 0.000 {method 'append' of 'list' objects}\n\n# cProfile.run('get_dig(2000)') - 61569 function calls in 35.066 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 15391 35.014 0.002 35.017 0.002 lesson04_hw02.py:18(fix_digs)\n# 15390 0.017 0.000 35.036 0.002 lesson04_hw02.py:28(add_digs)\n# 15392 0.003 0.000 0.003 0.000 {built-in method builtins.len}\n# 15390 0.003 0.000 0.003 0.000 {method 'append' of 'list' objects}\n\n\n# Вариант 2 - без решета\n\ndef get_dig2(n):\n lim_nums = 0x7fffffff\n list_digs = []\n result_num = 0\n for i in range(2, lim_nums):\n for k in list_digs:\n if i % k == 0:\n break\n else:\n if n > 0:\n list_digs.append(i)\n n -= 1\n else:\n result_num = k\n break\n return result_num\n\n\n# print(get_dig2(15))\n\n# Результаты timeit n=100\n#\n# dig2(10)\n# 100 loops, best of 3: 6.46 usec per loop\n# get_dig2(100)\"\n# 100 loops, best of 3: 284 usec per loop\n# get_dig2(200)\n# 100 loops, best of 3: 1.05 msec per loop\n# dig2(1000)\n# 100 loops, best of 3: 27.4 msec per loop\n\n# Результаты cProfile\n#\n# cProfile.run('get_dig2(100)') - 104 function calls in 0.000 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 1 0.000 0.000 0.000 0.000 lesson04_hw02.py:67(get_dig2)\n# 100 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n\n# cProfile.run('get_dig2(1000)') - 1004 function calls in 0.029 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 1 0.029 0.029 0.029 0.029 lesson04_hw02.py:75(get_dig2)\n# 1000 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n\n# cProfile.run('get_dig2(2000)') - 2004 function calls in 0.111 seconds\n# ncalls tottime percall cumtime percall filename:lineno(function)\n# 1 0.111 0.111 0.111 0.111 lesson04_hw02.py:80(get_dig2)\n# 2000 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n\n\n# cProfile.run('get_dig(2000)')\n# cProfile.run('get_dig2(2000)')\n\n\n# Вывод\n# 1. Алгоритм работы с решетом сложен и работает медленно с большими числами\n# в связи с тем, что чем больше число в поиске, тем глубже\n# нужно растягивать решето и его обрабатывать.\n# На каждый шаг перебора числа приходится по 4 разных вызова обработки решета.\n# Основные затраты времени приходятся на зачеркивание составных чисел.\n\n#\n# 2. Без решета, удалось собрать алгоритм с обработкой в один проход и количество\n# вызовов равно порядковому номеру числа в ряде.\n# Как результат, вариант 2 значительно быстрее варианта 1.\n","sub_path":"lesson_04/lesson04_hw02.py","file_name":"lesson04_hw02.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"574989629","text":"import babeltrace.writer as btw\nimport tempfile\n\n# temporary directory holding the CTF trace\ntrace_path = tempfile.mkdtemp()\n\nprint('trace path: {}'.format(trace_path))\n\n# our writer\nwriter = btw.Writer(trace_path)\nwriter.byte_order = 2 #setto modalità big endian, info trovata su babeltrace.h\n\n# create one default clock and register it to the writer\n# the default frequency is 1 Ghz, that increments clock each nanosecond\nclock = btw.Clock('my_clock')\nclock.description = 'this is my clock'\n#clock.offset_seconds = 18\n#clock.time = 18\nwriter.add_clock(clock)\n\n# create stream_profiler_1 stream class and assign our clock to it\nstream_class = btw.StreamClass('stream_profiler_1')\nstream_class.clock = clock\n\n\n# create response_time event class, that stores all the response times collected by profiler_1\nevent_class = btw.EventClass('response_time')\n\n# create one 8-bit unsigned integer field. This will be used for code ID.\nint8_field_decl = btw.IntegerFieldDeclaration(8)\nint8_field_decl.signed = False\n# add this field declaration to response_time event class\nevent_class.add_field(int8_field_decl, 'ID_field')\n\n# create one 32-bit signed integer field. This will be used for timestamp.\nint32_field_decl = btw.IntegerFieldDeclaration(32)\nint32_field_decl.signed = False\n# add this field declaration to response_time event class\nevent_class.add_field(int32_field_decl, 'timestamp_field')\n\n# create one 32-bit signed integer field. This will be used for timestamp\n# int32_field_decl = btw.IntegerFieldDeclaration(32)\n# int32_field_decl.signed = True\n# add this field declaration to our event class\n#event_class.add_field(int32_field_decl, 'timestamp_field')\n\n# register response_time event class to stream_profiler_1 stream class\nstream_class.add_event_class(event_class)\n\n# create a single event1, event2, event3, event4, event5, based on response_time event class\nevent1 = btw.Event(event_class)\nevent2 = btw.Event(event_class)\nevent3 = btw.Event(event_class)\nevent4 = btw.Event(event_class)\nevent5 = btw.Event(event_class)\n\n# assign an integer value to our single field of event1, event2, event3, event4, event5\nevent1.payload('ID_field').value = 1\nevent1.payload('timestamp_field').value = 780000\nevent2.payload('ID_field').value = 45\nevent2.payload('timestamp_field').value = 781000\nevent3.payload('ID_field').value = 48\nevent3.payload('timestamp_field').value = 782000\nevent4.payload('ID_field').value = 49\nevent4.payload('timestamp_field').value = 783000\nevent5.payload('ID_field').value = 50\nevent5.payload('timestamp_field').value = 784000\n\n# create stream_profiler_1 stream\nstream = writer.create_stream(stream_class)\n\n# append our single event1, event2, event3, event4, event5 to stream_profiler_1 stream\nstream.append_event(event1)\nstream.append_event(event2)\nstream.append_event(event3)\nstream.append_event(event4)\nstream.append_event(event5)\n\n# flush the stream\nstream.flush()\n","sub_path":"parsing/dev/standalone.py","file_name":"standalone.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"382632053","text":"# -*- coding: utf-8 -*-\nimport json\n\nfrom aiohttp.http_exceptions import HttpProcessingError\nfrom aioresponses import aioresponses\nfrom asynctest.case import TestCase\nfrom ddt import data, ddt, unpack\n\nfrom alamo_worker.plugins.druid import DruidPlugin, DruidResultParser\nfrom alamo_worker.plugins.tests import (\n RESPONSE_DRUID_TIMESERIES,\n RESPONSE_DRUID_TOPN,\n RESPONSE_DRUID_GROUP_BY,\n RESPONSE_DRUID_ERROR_MESSAGE,\n RESPONSE_DRUID_ONLY_ERROR\n)\n\nDRUID_CHECK = {\n \"id\": 514,\n \"integration_key\": \"35f63d5f4d5f45a48f4fd83aaf221a52\",\n \"service_name\": \"bunny\",\n \"service_id\": \"891\",\n \"sc_id\": \"166\",\n \"entity_name\": \"druid\",\n \"entity_id\": \"4622568\",\n \"environment\": \"prod\",\n \"sources\": [\n {\n \"name\": \"test_druid\",\n \"type\": \"druid\",\n \"source_type\": \"druid\",\n \"query_type\": \"timeseries\",\n \"granularity\": \"day\",\n \"data_source\": \"performance\",\n \"filter\": \"{\\\"fields\\\": [{\\\"dimension\\\": \\\"service_id\\\", \\\"value\\\": \\\"CM.991213.tz_pl\\\", \\\"type\\\": \\\"selector\\\"}\", # noqa\n \"aggregations\": \"[{\\\"name\\\": \\\"count\\\", \\\"type\\\": \\\"count\\\"}]\"\n }\n ],\n \"triggers\": [\n {\n \"id\": 542,\n \"uuid\": \"4ffb2ff8-26b2-44e5-9b23-528ac1427686\",\n \"name\": \"warning#1\",\n \"severity\": \"WARNING\",\n \"enabled\": True,\n \"url\": \"http://127.0.0.1:8090/#/891/entity/4622568/checks/514/\",\n \"debounce\": 5,\n \"repeat_every\": 0,\n \"is_kpi\": False,\n \"tags\": [],\n \"rule\": \"test_druid.first_contentful_paint_histogram_90 > 2000\"\n }\n ],\n \"tags\": [\n \"druid\"\n ],\n \"frequency\": 20,\n \"fields\": {},\n \"uuid\": \"b5d48d99-60d9-4445-b1cc-f717dd6ae89e\",\n \"name\": \"test_druid\",\n \"description\": None,\n \"created\": \"2018-01-24T14:10:53.927409+01:00\",\n \"modified\": \"2018-01-24T14:10:53.927489+01:00\",\n \"template_name\": \"druid_template\",\n \"template_version\": \"\",\n \"unknown_as_failure\": False\n}\n\n\n@ddt\nclass TestDruidPlugin(TestCase):\n\n async def setUp(self):\n self.druid = DruidPlugin()\n self.ignored_fields = [\n 'uuid', 'name', 'severity', 'enabled', 'url', 'tags']\n\n @aioresponses(param='aiomock')\n async def test_good_response(self, aiomock):\n aiomock.post(\n 'http://localhost:8092/druid/v2',\n body=json.dumps(RESPONSE_DRUID_TIMESERIES),\n content_type='application/json'\n )\n result = await self.druid.execute(\n DRUID_CHECK, DRUID_CHECK['sources'][0]\n )\n self.assertEqual(result.status, 0)\n\n @unpack\n @data(\n (RESPONSE_DRUID_ERROR_MESSAGE, 'Test message'),\n (RESPONSE_DRUID_ONLY_ERROR, 'Query timeout'),\n )\n @aioresponses()\n async def test_druid_error(self, response, message, aiomock):\n aiomock.post(\n 'http://localhost:8092/druid/v2',\n body=json.dumps(response),\n content_type='application/json'\n )\n result = await self.druid.execute(\n DRUID_CHECK,\n DRUID_CHECK['sources'][0]\n )\n self.assertEqual(result.message, message)\n self.assertEqual(result.status, 2)\n\n @aioresponses()\n async def test_invalid_response(self, aiomock):\n aiomock.post(\n 'http://localhost:8092/druid/v2',\n body='[]',\n content_type='application/json'\n )\n result = await self.druid.execute(\n DRUID_CHECK, DRUID_CHECK['sources'][0]\n )\n self.assertEqual(result.status, 2)\n self.assertEqual(result.message, 'Empty response from Druid.')\n\n async def test_with_exception(self):\n with aioresponses() as m:\n m.post(\n 'http://localhost:8092/druid/v2',\n status=500,\n exception=HttpProcessingError()\n )\n with self.assertLogs('alamo_worker.plugins.druid', 'ERROR'):\n result = await self.druid.execute(\n DRUID_CHECK, DRUID_CHECK['sources'][0]\n )\n self.assertEqual(result.status, 2)\n\n async def test_druid_result_parser_not_implemented(self):\n parser = DruidResultParser({}, 'notimplemented')\n\n with self.assertRaises(NotImplementedError) as context:\n parser.collect_result()\n\n self.assertTrue('notimplemented is not supported', context.exception)\n\n @unpack\n @data(\n (RESPONSE_DRUID_TIMESERIES, 'timeseries', 3),\n (RESPONSE_DRUID_TOPN, 'topN', 5),\n (RESPONSE_DRUID_GROUP_BY, 'groupBy', 7)\n )\n async def test_druid_result_parser(self, response, query_type, expected):\n parser = DruidResultParser(response, query_type)\n datapoints = parser.collect_result()\n self.assertEqual(len(datapoints[0].keys()), expected)\n\n @aioresponses()\n async def test_health_check__healthy(self, aiomock):\n aiomock.post(\n 'http://localhost:8092/druid/v2',\n status=200,\n body='[]',\n content_type='application/json'\n )\n plugin = DruidPlugin()\n result = await plugin.healthy()\n self.assertEqual(result, ('druid', True))\n\n @aioresponses()\n async def test_health_check__not_healthy(self, aiomock):\n aiomock.post(\n 'http://localhost:8092/druid/v2',\n status=500,\n body='{\"error\": \"Unknown exception\"}',\n content_type='application/json'\n )\n plugin = DruidPlugin()\n result = await plugin.healthy()\n self.assertEqual(result, ('druid', False))\n","sub_path":"alamo_worker/plugins/tests/test_druid_plugin.py","file_name":"test_druid_plugin.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"362745991","text":"'''\nDescription: 前程贷pytest的前置后置模块\nVersion: 2.0\nAutor: byh\nDate: 2020-12-11 16:42:07\nLastEditors: byh\nLastEditTime: 2020-12-30 13:41:06\n'''\nimport pytest\n\nfrom selenium import webdriver\nfrom middleware.logger_handler import logger\nfrom PageObject.login_page import LoginPage\nfrom TestData.login_data import LoginData\n\n\n@pytest.fixture()\ndef init_driver():\n logger.info(\"*********测试用例开始执行***********\")\n driver=webdriver.Chrome()\n driver.get('http://120.78.128.25:8765/Index/login.html')\n driver.maximize_window()\n yield driver\n driver.close()\n logger.info(\"*********测试用例执行结束***********\")\n\n\n@pytest.fixture()\ndef init_login(init_driver):\n try:\n LoginPage(init_driver).login(*LoginData.success_data)\n except Exception as e:\n logger.info(\"登录前程贷失败\")\n raise e\n yield init_driver\n \n \n","sub_path":"Testcase/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"219209663","text":"# Copyright 2018 D-Wave Systems Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# ================================================================================================\n\"\"\"\n\nThe binary quadratic model (BQM) class contains\nIsing and quadratic unconstrained binary optimization (QUBO) models\nused by samplers such as the D-Wave system.\n\nThe :term:`Ising` model is an objective function of :math:`N` variables\n:math:`s=[s_1,...,s_N]` corresponding to physical Ising spins, where :math:`h_i`\nare the biases and :math:`J_{i,j}` the couplings (interactions) between spins.\n\n.. math::\n\n \\\\text{Ising:} \\\\qquad E(\\\\bf{s}|\\\\bf{h},\\\\bf{J})\n = \\\\left\\\\{ \\\\sum_{i=1}^N h_i s_i + \\\\sum_{i>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n\n This example creates a binary quadratic model with non-numeric variables\n (variables can be any hashable object).\n\n >>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': -1.0, 'c': 0.5},\n ... {('a', 'b'): -1.0, ('b', 'c'): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> len(bqm)\n 3\n >>> 'b' in bqm\n True\n\n Attributes:\n linear (dict[variable, bias]):\n Linear biases as a dict, where keys are the variables of\n the binary quadratic model and values the linear biases associated\n with these variables.\n\n quadratic (dict[(variable, variable), bias]):\n Quadratic biases as a dict, where keys are 2-tuples of variables, which\n represent an interaction between the two variables, and values\n are the quadratic biases associated with the interactions.\n\n offset (number):\n The energy offset associated with the model. Same type as given\n on instantiation.\n\n vartype (:class:`.Vartype`):\n The model's type. One of :class:`.Vartype.SPIN` or :class:`.Vartype.BINARY`.\n\n variables (keysview):\n The variables in the binary quadratic model as a dictionary keys\n view object.\n\n adj (dict):\n The model's interactions as nested dicts.\n In graphic representation, where variables are nodes and interactions\n are edges or adjacencies, keys of the outer dict (`adj`) are all\n the model's nodes (e.g. `v`) and values are the inner dicts. For the\n inner dict associated with outer-key/node 'v', keys are all the nodes\n adjacent to `v` (e.g. `u`) and values are quadratic biases associated\n with the pair of inner and outer keys (`u, v`).\n\n info (dict):\n A place to store miscellaneous data about the binary quadratic model\n as a whole.\n\n SPIN (:class:`.Vartype`): An alias of :class:`.Vartype.SPIN` for easier access.\n\n BINARY (:class:`.Vartype`): An alias of :class:`.Vartype.BINARY` for easier access.\n\n Examples:\n This example creates an instance of the :class:`.BinaryQuadraticModel`\n class for the K4 complete graph, where the nodes have biases\n set equal to their sequential labels and interactions are the\n concatenations of the node pairs (e.g., 23 for u,v = 2,3).\n\n >>> import dimod\n ...\n >>> linear = {1: 1, 2: 2, 3: 3, 4: 4}\n >>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,\n ... (2, 3): 23, (2, 4): 24,\n ... (3, 4): 34}\n >>> offset = 0.0\n >>> vartype = dimod.BINARY\n >>> bqm_k4 = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype)\n >>> bqm_k4.info = {'Complete K4 binary quadratic model.'}\n >>> bqm_k4.info.issubset({'Complete K3 binary quadratic model.',\n ... 'Complete K4 binary quadratic model.',\n ... 'Complete K5 binary quadratic model.'})\n True\n >>> bqm_k4.adj.viewitems() # Show all adjacencies # doctest: +SKIP\n [(1, {2: 12, 3: 13, 4: 14}),\n (2, {1: 12, 3: 23, 4: 24}),\n (3, {1: 13, 2: 23, 4: 34}),\n (4, {1: 14, 2: 24, 3: 34})]\n >>> bqm_k4.adj[2] # Show adjacencies for node 2 # doctest: +SKIP\n {1: 12, 3: 23, 4: 24}\n >>> bqm_k4.adj[2][3] # Show the quadratic bias for nodes 2,3 # doctest: +SKIP\n 23\n\n \"\"\"\n\n SPIN = Vartype.SPIN\n BINARY = Vartype.BINARY\n\n @vartype_argument('vartype')\n def __init__(self, linear, quadratic, offset, vartype, **kwargs):\n\n self._adj = LockableDict()\n\n self.linear = LinearView(self)\n self.quadratic = QuadraticView(self)\n self.adj = AdjacencyView(self)\n\n self.offset = offset # we are agnostic to type, though generally should behave like a number\n self.vartype = vartype\n self.info = LockableDict(kwargs) # any additional kwargs are kept as info (metadata)\n\n # add linear, quadratic\n self.add_variables_from(linear)\n self.add_interactions_from(quadratic)\n\n @classmethod\n def empty(cls, vartype):\n \"\"\"Create an empty binary quadratic model.\n\n Equivalent to instantiating a :class:`.BinaryQuadraticModel` with no bias values\n and zero offset for the defined :class:`vartype`:\n\n .. code-block:: python\n\n BinaryQuadraticModel({}, {}, 0.0, vartype)\n\n Args:\n vartype (:class:`.Vartype`/str/set):\n Variable type for the binary quadratic model. Accepted input values:\n\n * :attr:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :attr:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n Examples:\n >>> bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY)\n\n \"\"\"\n return cls({}, {}, 0.0, vartype)\n\n def __repr__(self):\n return 'BinaryQuadraticModel({}, {}, {}, {})'.format(self.linear, self.quadratic, self.offset, self.vartype)\n\n def __eq__(self, other):\n \"\"\"Model is equal if and only if linear, adj, offset and vartype are all equal.\"\"\"\n\n try:\n if self.vartype is not other.vartype:\n return False\n\n if self.offset != other.offset:\n return False\n\n if self.linear != other.linear:\n return False\n\n return self.adj == other.adj\n except AttributeError:\n return False\n\n def __ne__(self, other):\n return not (self == other)\n\n def __len__(self):\n return len(self.adj)\n\n def __contains__(self, v):\n return v in self.adj\n\n def __iter__(self):\n return iter(self.adj)\n\n @property\n def is_writeable(self):\n return getattr(self, '_writeable', True)\n\n @is_writeable.setter\n def is_writeable(self, b):\n b = bool(b) # cast\n\n self._writeable = b\n\n # also set the flags on the relevant data object objects\n self._adj.is_writeable = self.info.is_writeable = b\n for neighbors in self._adj.values():\n neighbors.is_writeable = b\n\n @property\n def offset(self):\n return self._offset\n\n @offset.setter\n @lockable_method\n def offset(self, offset):\n self._offset = offset\n\n @property\n def variables(self):\n \"\"\"Return binary quadratic model's variables as a dictionary view object.\"\"\"\n return abc.KeysView(self.linear)\n\n##################################################################################################\n# vartype properties\n##################################################################################################\n\n @property\n def spin(self):\n \"\"\":class:`.BinaryQuadraticModel`: An instance of the Ising model subclass\n of the :class:`.BinaryQuadraticModel` superclass, corresponding to\n a binary quadratic model with spins as its variables.\n\n Enables access to biases for the spin-valued binary quadratic model\n regardless of the :class:`vartype` set when the model was created.\n If the model was created with the :attr:`.binary` vartype,\n the Ising model subclass is instantiated upon the first use of the\n :attr:`.spin` property and used in any subsequent reads.\n\n Examples:\n This example creates a QUBO model and uses the :attr:`.spin` property\n to instantiate the corresponding Ising model.\n\n >>> import dimod\n ...\n >>> bqm_qubo = dimod.BinaryQuadraticModel({0: -1, 1: -1}, {(0, 1): 2}, 0.0, dimod.BINARY)\n >>> bqm_spin = bqm_qubo.spin\n >>> bqm_spin # doctest: +SKIP\n BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, Vartype.SPIN)\n >>> bqm_spin.spin is bqm_spin\n True\n\n Note:\n Methods like :meth:`.add_variable`, :meth:`.add_variables_from`,\n :meth:`.add_interaction`, etc. should only be used on the base model.\n\n \"\"\"\n # NB: The existence of the _spin property implies that it is up to date, methods that\n # invalidate it will erase the property\n try:\n spin = self._spin\n if spin is not None:\n return spin\n except AttributeError:\n pass\n\n if self.vartype is Vartype.SPIN:\n self._spin = spin = self\n else:\n self._counterpart = self._spin = spin = self.change_vartype(Vartype.SPIN, inplace=False)\n\n # we also want to go ahead and set spin.binary to refer back to self\n spin._binary = self\n\n return spin\n\n @property\n def binary(self):\n \"\"\":class:`.BinaryQuadraticModel`: An instance of the QUBO model subclass of\n the :class:`.BinaryQuadraticModel` superclass, corresponding to a binary quadratic\n model with binary variables.\n\n Enables access to biases for the binary-valued binary quadratic model\n regardless of the :class:`vartype` set when the model was created. If the model\n was created with the :attr:`.spin` vartype, the QUBO model subclass is instantiated\n upon the first use of the :attr:`.binary` property and used in any subsequent reads.\n\n Examples:\n This example creates an Ising model and uses the :attr:`.binary` property\n to instantiate the corresponding QUBO model.\n\n >>> import dimod\n ...\n >>> bqm_spin = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)\n >>> bqm_qubo = bqm_spin.binary\n >>> bqm_qubo # doctest: +SKIP\n BinaryQuadraticModel({0: -1.0, 1: -1.0}, {(0, 1): 2.0}, 0.0, Vartype.BINARY)\n >>> bqm_qubo.binary is bqm_qubo\n True\n\n Note:\n Methods like :meth:`.add_variable`, :meth:`.add_variables_from`,\n :meth:`.add_interaction`, etc. should only be used on the base model.\n\n \"\"\"\n # NB: The existence of the _binary property implies that it is up to date, methods that\n # invalidate it will erase the property\n try:\n binary = self._binary\n if binary is not None:\n return binary\n except AttributeError:\n pass\n\n if self.vartype is Vartype.BINARY:\n self._binary = binary = self\n else:\n self._counterpart = self._binary = binary = self.change_vartype(Vartype.BINARY, inplace=False)\n\n # we also want to go ahead and set binary.spin to refer back to self\n binary._spin = self\n\n return binary\n\n###################################################################################################\n# update methods\n###################################################################################################\n\n def add_variable(self, v, bias, vartype=None):\n \"\"\"Add variable v and/or its bias to a binary quadratic model.\n\n Args:\n v (variable):\n The variable to add to the model. Can be any python object\n that is a valid dict key.\n\n bias (bias):\n Linear bias associated with v. If v is already in the model, this value is added\n to its current linear bias. Many methods and functions expect `bias` to be a number\n but this is not explicitly checked.\n\n vartype (:class:`.Vartype`, optional, default=None):\n Vartype of the given bias. If None, the vartype of the binary\n quadratic model is used. Valid values are :class:`.Vartype.SPIN` or\n :class:`.Vartype.BINARY`.\n\n Examples:\n This example creates an Ising model with two variables, adds a third,\n and adds to the linear biases of the initial two.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)\n >>> len(bqm.linear)\n 2\n >>> bqm.add_variable(2, 2.0, vartype=dimod.SPIN) # Add a new variable\n >>> bqm.add_variable(1, 0.33, vartype=dimod.SPIN)\n >>> bqm.add_variable(0, 0.33, vartype=dimod.BINARY) # Binary value is converted to spin value\n >>> len(bqm.linear)\n 3\n >>> bqm.linear[1]\n 1.33\n\n \"\"\"\n\n # handle the case that a different vartype is provided\n if vartype is not None and vartype is not self.vartype:\n if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:\n # convert from binary to spin\n bias /= 2\n self.offset += bias\n elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:\n # convert from spin to binary\n self.offset -= bias\n bias *= 2\n else:\n raise ValueError(\"unknown vartype\")\n\n # we used to do this using self.linear but working directly with _adj\n # is much faster\n _adj = self._adj\n if v in _adj:\n if v in _adj[v]:\n _adj[v][v] += bias\n else:\n _adj[v][v] = bias\n else:\n _adj[v] = LockableDict({v: bias})\n\n try:\n self._counterpart.add_variable(v, bias, vartype=self.vartype)\n except AttributeError:\n pass\n\n def add_variables_from(self, linear, vartype=None):\n \"\"\"Add variables and/or linear biases to a binary quadratic model.\n\n Args:\n linear (dict[variable, bias]/iterable[(variable, bias)]):\n A collection of variables and their linear biases to add to the model.\n If a dict, keys are variables in the binary quadratic model and\n values are biases. Alternatively, an iterable of (variable, bias) pairs.\n Variables can be any python object that is a valid dict key.\n Many methods and functions expect the biases\n to be numbers but this is not explicitly checked.\n If any variable already exists in the model, its bias is added to\n the variable's current linear bias.\n\n vartype (:class:`.Vartype`, optional, default=None):\n Vartype of the given bias. If None, the vartype of the binary\n quadratic model is used. Valid values are :class:`.Vartype.SPIN` or\n :class:`.Vartype.BINARY`.\n\n Examples:\n This example creates creates an empty Ising model, adds two variables,\n and subsequently adds to the bias of the one while adding a new, third,\n variable.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({}, {}, 0.0, dimod.SPIN)\n >>> len(bqm.linear)\n 0\n >>> bqm.add_variables_from({'a': .5, 'b': -1.})\n >>> 'b' in bqm\n True\n >>> bqm.add_variables_from({'b': -1., 'c': 2.0})\n >>> bqm.linear['b']\n -2.0\n\n \"\"\"\n if isinstance(linear, abc.Mapping):\n for v, bias in iteritems(linear):\n self.add_variable(v, bias, vartype=vartype)\n else:\n try:\n for v, bias in linear:\n self.add_variable(v, bias, vartype=vartype)\n except TypeError:\n raise TypeError(\"expected 'linear' to be a dict or an iterable of 2-tuples.\")\n\n def add_interaction(self, u, v, bias, vartype=None):\n \"\"\"Add an interaction and/or quadratic bias to a binary quadratic model.\n\n Args:\n v (variable):\n One of the pair of variables to add to the model. Can be any python object\n that is a valid dict key.\n\n u (variable):\n One of the pair of variables to add to the model. Can be any python object\n that is a valid dict key.\n\n bias (bias):\n Quadratic bias associated with u, v. If u, v is already in the model, this value\n is added to the current quadratic bias. Many methods and functions expect `bias` to\n be a number but this is not explicitly checked.\n\n vartype (:class:`.Vartype`, optional, default=None):\n Vartype of the given bias. If None, the vartype of the binary\n quadratic model is used. Valid values are :class:`.Vartype.SPIN` or\n :class:`.Vartype.BINARY`.\n\n Examples:\n This example creates an Ising model with two variables, adds a third,\n adds to the bias of the initial interaction, and creates\n a new interaction.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)\n >>> len(bqm.quadratic)\n 1\n >>> bqm.add_interaction(0, 2, 2) # Add new variable 2\n >>> bqm.add_interaction(0, 1, .25)\n >>> bqm.add_interaction(1, 2, .25, vartype=dimod.BINARY) # Binary value is converted to spin value\n >>> len(bqm.quadratic)\n 3\n >>> bqm.quadratic[(0, 1)]\n 0.75\n\n \"\"\"\n if u == v:\n raise ValueError(\"no self-loops allowed, therefore ({}, {}) is not an allowed interaction\".format(u, v))\n\n _adj = self._adj\n\n if vartype is not None and vartype is not self.vartype:\n if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:\n # convert from binary to spin\n bias /= 4\n\n self.add_offset(bias)\n self.add_variable(u, bias)\n self.add_variable(v, bias)\n\n elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:\n # convert from spin to binary\n\n self.add_offset(bias)\n self.add_variable(u, -2 * bias)\n self.add_variable(v, -2 * bias)\n\n bias *= 4\n else:\n raise ValueError(\"unknown vartype\")\n else:\n # so that they exist.\n if u not in self:\n _adj[u] = LockableDict()\n if v not in self:\n _adj[v] = LockableDict()\n\n if u in _adj[v]:\n _adj[u][v] = _adj[v][u] = _adj[u][v] + bias\n else:\n _adj[u][v] = _adj[v][u] = bias\n\n try:\n self._counterpart.add_interaction(u, v, bias, vartype=self.vartype)\n except AttributeError:\n pass\n\n def add_interactions_from(self, quadratic, vartype=None):\n \"\"\"Add interactions and/or quadratic biases to a binary quadratic model.\n\n Args:\n quadratic (dict[(variable, variable), bias]/iterable[(variable, variable, bias)]):\n A collection of variables that have an interaction and their quadratic\n bias to add to the model. If a dict, keys are 2-tuples of variables\n in the binary quadratic model and values are their corresponding\n bias. Alternatively, an iterable of 3-tuples. Each interaction in `quadratic` should be\n unique; that is, if `(u, v)` is a key, `(v, u)` should not be.\n Variables can be any python object that is a valid dict key.\n Many methods and functions expect the biases to be numbers but this is not\n explicitly checked.\n\n vartype (:class:`.Vartype`, optional, default=None):\n Vartype of the given bias. If None, the vartype of the binary\n quadratic model is used. Valid values are :class:`.Vartype.SPIN` or\n :class:`.Vartype.BINARY`.\n\n Examples:\n This example creates creates an empty Ising model, adds an interaction\n for two variables, adds to its bias while adding a new variable,\n then adds another interaction.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN)\n >>> bqm.add_interactions_from({('a', 'b'): -.5})\n >>> bqm.quadratic[('a', 'b')]\n -0.5\n >>> bqm.add_interactions_from({('a', 'b'): -.5, ('a', 'c'): 2})\n >>> bqm.add_interactions_from({('b', 'c'): 2}, vartype=dimod.BINARY) # Binary value is converted to spin value\n >>> len(bqm.quadratic)\n 3\n >>> bqm.quadratic[('a', 'b')]\n -1.0\n\n \"\"\"\n if isinstance(quadratic, abc.Mapping):\n for (u, v), bias in iteritems(quadratic):\n self.add_interaction(u, v, bias, vartype=vartype)\n else:\n try:\n for u, v, bias in quadratic:\n self.add_interaction(u, v, bias, vartype=vartype)\n except TypeError:\n raise TypeError(\"expected 'quadratic' to be a dict or an iterable of 3-tuples.\")\n\n def remove_variable(self, v):\n \"\"\"Remove variable v and all its interactions from a binary quadratic model.\n\n Args:\n v (variable):\n The variable to be removed from the binary quadratic model.\n\n Notes:\n If the specified variable is not in the binary quadratic model, this function does nothing.\n\n Examples:\n This example creates an Ising model and then removes one variable.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': 0.0, 'b': 1.0, 'c': 2.0},\n ... {('a', 'b'): 0.25, ('a','c'): 0.5, ('b','c'): 0.75},\n ... -0.5, dimod.SPIN)\n >>> bqm.remove_variable('a')\n >>> 'a' in bqm.linear\n False\n >>> ('b','c') in bqm.quadratic\n True\n\n \"\"\"\n if v not in self:\n return\n\n adj = self.adj\n\n # first remove all the interactions associated with v\n while adj[v]:\n self.remove_interaction(v, next(iter(adj[v])))\n\n # remove the variable\n del self.linear[v]\n\n try:\n # invalidates counterpart\n del self._counterpart\n if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):\n del self._binary\n elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):\n del self._spin\n except AttributeError:\n pass\n\n def remove_variables_from(self, variables):\n \"\"\"Remove specified variables and all of their interactions from a binary quadratic model.\n\n Args:\n variables(iterable):\n A collection of variables to be removed from the binary quadratic model.\n If any variable is not in the model, it is ignored.\n\n Examples:\n This example creates an Ising model with three variables and interactions\n among all of them, and then removes two variables.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 1.0, 2: 2.0},\n ... {(0, 1): 0.25, (0,2): 0.5, (1,2): 0.75},\n ... -0.5, dimod.SPIN)\n >>> bqm.remove_variables_from([0, 1])\n >>> len(bqm.linear)\n 1\n >>> len(bqm.quadratic)\n 0\n\n \"\"\"\n for v in variables:\n self.remove_variable(v)\n\n def remove_interaction(self, u, v):\n \"\"\"Remove interaction of variables u, v from a binary quadratic model.\n\n Args:\n u (variable):\n One of the pair of variables in the binary quadratic model that\n has an interaction.\n\n v (variable):\n One of the pair of variables in the binary quadratic model that\n has an interaction.\n\n Notes:\n Any interaction not in the binary quadratic model is ignored.\n\n Examples:\n This example creates an Ising model with three variables that has interactions\n between two, and then removes an interaction.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)\n >>> bqm.remove_interaction('b', 'c')\n >>> ('b', 'c') in bqm.quadratic\n False\n >>> bqm.remove_interaction('a', 'c') # not an interaction, so ignored\n >>> len(bqm.quadratic)\n 1\n\n \"\"\"\n\n try:\n del self.quadratic[(u, v)]\n except KeyError:\n return # no interaction with that name\n\n try:\n # invalidates counterpart\n del self._counterpart\n if self.vartype is not Vartype.BINARY and hasattr(self, '_binary'):\n del self._binary\n elif self.vartype is not Vartype.SPIN and hasattr(self, '_spin'):\n del self._spin\n except AttributeError:\n pass\n\n def remove_interactions_from(self, interactions):\n \"\"\"Remove all specified interactions from the binary quadratic model.\n\n Args:\n interactions (iterable[[variable, variable]]):\n A collection of interactions. Each interaction should be a 2-tuple of variables\n in the binary quadratic model.\n\n Notes:\n Any interaction not in the binary quadratic model is ignored.\n\n Examples:\n This example creates an Ising model with three variables that has interactions\n between two, and then removes an interaction.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({}, {('a', 'b'): -1.0, ('b', 'c'): 1.0}, 0.0, dimod.SPIN)\n >>> bqm.remove_interactions_from([('b', 'c'), ('a', 'c')]) # ('a', 'c') is not an interaction, so ignored\n >>> len(bqm.quadratic)\n 1\n\n \"\"\"\n for u, v in interactions:\n self.remove_interaction(u, v)\n\n def add_offset(self, offset):\n \"\"\"Add specified value to the offset of a binary quadratic model.\n\n Args:\n offset (number):\n Value to be added to the constant energy offset of the binary quadratic model.\n\n Examples:\n\n This example creates an Ising model with an offset of -0.5 and then\n adds to it.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({0: 0.0, 1: 0.0}, {(0, 1): 0.5}, -0.5, dimod.SPIN)\n >>> bqm.add_offset(1.0)\n >>> bqm.offset\n 0.5\n\n \"\"\"\n self.offset += offset\n\n try:\n self._counterpart.add_offset(offset)\n except AttributeError:\n pass\n\n def remove_offset(self):\n \"\"\"Set the binary quadratic model's offset to zero.\n\n Examples:\n This example creates an Ising model with a positive energy offset, and\n then removes it.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({}, {}, 1.3, dimod.SPIN)\n >>> bqm.remove_offset()\n >>> bqm.offset\n 0.0\n\n \"\"\"\n self.add_offset(-self.offset)\n\n def scale(self, scalar, ignored_variables=None, ignored_interactions=None,\n ignore_offset=False):\n \"\"\"Multiply by the specified scalar all the biases and offset of a binary quadratic model.\n\n Args:\n scalar (number):\n Value by which to scale the energy range of the binary quadratic model.\n\n ignored_variables (iterable, optional):\n Biases associated with these variables are not scaled.\n\n ignored_interactions (iterable[tuple], optional):\n As an iterable of 2-tuples. Biases associated with these interactions are not scaled.\n\n ignore_offset (bool, default=False):\n If True, the offset is not scaled.\n\n Examples:\n\n This example creates a binary quadratic model and then scales it to half\n the original energy range.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 2.0}, {('a', 'b'): -1.0}, 1.0, dimod.SPIN)\n >>> bqm.scale(0.5)\n >>> bqm.linear['a']\n -1.0\n >>> bqm.quadratic[('a', 'b')]\n -0.5\n >>> bqm.offset\n 0.5\n\n \"\"\"\n\n if ignored_variables is None:\n ignored_variables = set()\n elif not isinstance(ignored_variables, abc.Container):\n ignored_variables = set(ignored_variables)\n\n if ignored_interactions is None:\n ignored_interactions = set()\n elif not isinstance(ignored_interactions, abc.Container):\n ignored_interactions = set(ignored_interactions)\n\n linear = self.linear\n for v in linear:\n if v in ignored_variables:\n continue\n linear[v] *= scalar\n\n quadratic = self.quadratic\n for u, v in quadratic:\n if (u, v) in ignored_interactions or (v, u) in ignored_interactions:\n continue\n quadratic[(u, v)] *= scalar\n\n if not ignore_offset:\n self.offset *= scalar\n\n try:\n self._counterpart.scale(scalar, ignored_variables=ignored_variables,\n ignored_interactions=ignored_interactions)\n except AttributeError:\n pass\n\n def normalize(self, bias_range=1, quadratic_range=None,\n ignored_variables=None, ignored_interactions=None,\n ignore_offset=False):\n \"\"\"Normalizes the biases of the binary quadratic model such that they\n fall in the provided range(s), and adjusts the offset appropriately.\n\n If `quadratic_range` is provided, then `bias_range` will be treated as\n the range for the linear biases and `quadratic_range` will be used for\n the range of the quadratic biases.\n\n Args:\n bias_range (number/pair):\n Value/range by which to normalize the all the biases, or if\n `quadratic_range` is provided, just the linear biases.\n\n quadratic_range (number/pair):\n Value/range by which to normalize the quadratic biases.\n\n ignored_variables (iterable, optional):\n Biases associated with these variables are not scaled.\n\n ignored_interactions (iterable[tuple], optional):\n As an iterable of 2-tuples. Biases associated with these interactions are not scaled.\n\n ignore_offset (bool, default=False):\n If True, the offset is not scaled.\n\n Examples:\n\n >>> bqm = dimod.BinaryQuadraticModel({'a': -2.0, 'b': 1.5},\n ... {('a', 'b'): -1.0},\n ... 1.0, dimod.SPIN)\n >>> max(abs(bias) for bias in bqm.linear.values())\n 2.0\n >>> max(abs(bias) for bias in bqm.quadratic.values())\n 1.0\n >>> bqm.normalize([-1.0, 1.0])\n >>> max(abs(bias) for bias in bqm.linear.values())\n 1.0\n >>> max(abs(bias) for bias in bqm.quadratic.values())\n 0.5\n\n \"\"\"\n\n def parse_range(r):\n if isinstance(r, Number):\n return -abs(r), abs(r)\n return r\n\n def min_and_max(iterable):\n if not iterable:\n return 0, 0\n return min(iterable), max(iterable)\n\n if ignored_variables is None:\n ignored_variables = set()\n elif not isinstance(ignored_variables, abc.Container):\n ignored_variables = set(ignored_variables)\n\n if ignored_interactions is None:\n ignored_interactions = set()\n elif not isinstance(ignored_interactions, abc.Container):\n ignored_interactions = set(ignored_interactions)\n\n if quadratic_range is None:\n linear_range, quadratic_range = bias_range, bias_range\n else:\n linear_range = bias_range\n\n lin_range, quad_range = map(parse_range, (linear_range,\n quadratic_range))\n\n lin_min, lin_max = min_and_max([v for k, v in self.linear.items()\n if k not in ignored_variables])\n quad_min, quad_max = min_and_max([v for (a, b), v in self.quadratic.items()\n if ((a, b) not in ignored_interactions\n and (b, a) not in\n ignored_interactions)])\n\n inv_scalar = max(lin_min / lin_range[0], lin_max / lin_range[1],\n quad_min / quad_range[0], quad_max / quad_range[1])\n\n if inv_scalar != 0:\n self.scale(1 / inv_scalar, ignored_variables=ignored_variables,\n ignored_interactions=ignored_interactions,\n ignore_offset=ignore_offset)\n\n def fix_variable(self, v, value):\n \"\"\"Fix the value of a variable and remove it from a binary quadratic model.\n\n Args:\n v (variable):\n Variable in the binary quadratic model to be fixed.\n\n value (int):\n Value assigned to the variable. Values must match the :class:`.Vartype` of the binary\n quadratic model.\n\n Examples:\n\n This example creates a binary quadratic model with one variable and fixes\n its value.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0.}, {('a', 'b'): -1}, 0.0, dimod.SPIN)\n >>> bqm.fix_variable('a', -1)\n >>> bqm.offset\n 0.5\n >>> bqm.linear['b']\n 1.0\n >>> 'a' in bqm\n False\n\n \"\"\"\n adj = self.adj\n linear = self.linear\n\n if value not in self.vartype.value:\n raise ValueError(\"expected value to be in {}, received {} instead\".format(self.vartype.value, value))\n\n removed_interactions = []\n for u in adj[v]:\n self.add_variable(u, value * adj[v][u])\n removed_interactions.append((u, v))\n self.remove_interactions_from(removed_interactions)\n\n self.add_offset(value * linear[v])\n self.remove_variable(v)\n\n def fix_variables(self, fixed):\n \"\"\"Fix the value of the variables and remove it from a binary quadratic model.\n\n Args:\n fixed (dict):\n A dictionary of variable assignments.\n\n Examples:\n >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN)\n >>> bqm.fix_variables({'a': -1, 'b': +1})\n\n \"\"\"\n for v, val in fixed.items():\n self.fix_variable(v, val)\n\n\n def flip_variable(self, v):\n \"\"\"Flip variable v in a binary quadratic model.\n\n Args:\n v (variable):\n Variable in the binary quadratic model. If v is not in the binary\n quadratic model, it is ignored.\n\n Examples:\n This example creates a binary quadratic model with two variables and inverts\n the value of one.\n\n >>> import dimod\n ...\n >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)\n >>> bqm.flip_variable(1)\n >>> bqm.linear[1], bqm.linear[2], bqm.quadratic[(1, 2)]\n (-1.0, 2, -0.5)\n\n \"\"\"\n adj = self.adj\n linear = self.linear\n quadratic = self.quadratic\n\n if v not in adj:\n return\n\n if self.vartype is Vartype.SPIN:\n # in this case we just multiply by -1\n linear[v] *= -1.\n for u in adj[v]:\n adj[v][u] *= -1.\n adj[u][v] *= -1.\n\n if (u, v) in quadratic:\n quadratic[(u, v)] *= -1.\n elif (v, u) in quadratic:\n quadratic[(v, u)] *= -1.\n else:\n raise RuntimeError(\"quadratic is missing an interaction\")\n\n elif self.vartype is Vartype.BINARY:\n self.offset += linear[v]\n linear[v] *= -1\n\n for u in adj[v]:\n bias = adj[v][u]\n\n adj[v][u] *= -1.\n adj[u][v] *= -1.\n\n linear[u] += bias\n\n if (u, v) in quadratic:\n quadratic[(u, v)] *= -1.\n elif (v, u) in quadratic:\n quadratic[(v, u)] *= -1.\n else:\n raise RuntimeError(\"quadratic is missing an interaction\")\n\n else:\n raise RuntimeError(\"Unexpected vartype\")\n\n try:\n self._counterpart.flip_variable(v)\n except AttributeError:\n pass\n\n def update(self, bqm, ignore_info=True):\n \"\"\"Update one binary quadratic model from another.\n\n Args:\n bqm (:class:`.BinaryQuadraticModel`):\n The updating binary quadratic model. Any variables in the updating\n model are added to the updated model. Values of biases and the offset\n in the updating model are added to the corresponding values in\n the updated model.\n\n ignore_info (bool, optional, default=True):\n If True, info in the given binary quadratic model is ignored, otherwise\n :attr:`.BinaryQuadraticModel.info` is updated with the given binary quadratic\n model's info, potentially overwriting values.\n\n Examples:\n This example creates two binary quadratic models and updates the first\n from the second.\n\n >>> import dimod\n ...\n >>> linear1 = {1: 1, 2: 2}\n >>> quadratic1 = {(1, 2): 12}\n >>> bqm1 = dimod.BinaryQuadraticModel(linear1, quadratic1, 0.5, dimod.SPIN)\n >>> bqm1.info = {'BQM number 1'}\n >>> linear2 = {2: 0.25, 3: 0.35}\n >>> quadratic2 = {(2, 3): 23}\n >>> bqm2 = dimod.BinaryQuadraticModel(linear2, quadratic2, 0.75, dimod.SPIN)\n >>> bqm2.info = {'BQM number 2'}\n >>> bqm1.update(bqm2)\n >>> bqm1.offset\n 1.25\n >>> 'BQM number 2' in bqm1.info\n False\n >>> bqm1.update(bqm2, ignore_info=False)\n >>> 'BQM number 2' in bqm1.info\n True\n >>> bqm1.offset\n 2.0\n\n \"\"\"\n self.add_variables_from(bqm.linear, vartype=bqm.vartype)\n self.add_interactions_from(bqm.quadratic, vartype=bqm.vartype)\n self.add_offset(bqm.offset)\n\n if not ignore_info:\n self.info.update(bqm.info)\n\n def contract_variables(self, u, v):\n \"\"\"Enforce u, v being the same variable in a binary quadratic model.\n\n The resulting variable is labeled 'u'. Values of interactions between `v` and\n variables that `u` interacts with are added to the corresponding interactions\n of `u`.\n\n Args:\n u (variable):\n Variable in the binary quadratic model.\n\n v (variable):\n Variable in the binary quadratic model.\n\n Examples:\n This example creates a binary quadratic model representing the K4 complete graph\n and contracts node (variable) 3 into node 2. The interactions between\n 3 and its neighbors 1 and 4 are added to the corresponding interactions\n between 2 and those same neighbors.\n\n >>> import dimod\n ...\n >>> linear = {1: 1, 2: 2, 3: 3, 4: 4}\n >>> quadratic = {(1, 2): 12, (1, 3): 13, (1, 4): 14,\n ... (2, 3): 23, (2, 4): 24,\n ... (3, 4): 34}\n >>> bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.5, dimod.SPIN)\n >>> bqm.contract_variables(2, 3)\n >>> 3 in bqm.linear\n False\n >>> bqm.quadratic[(1, 2)]\n 25\n\n \"\"\"\n adj = self.adj\n\n if u not in adj:\n raise ValueError(\"{} is not a variable in the binary quadratic model\".format(u))\n if v not in adj:\n raise ValueError(\"{} is not a variable in the binary quadratic model\".format(v))\n\n # if there is an interaction between u, v it becomes linear for u\n if v in adj[u]:\n if self.vartype is Vartype.BINARY:\n self.add_variable(u, adj[u][v])\n elif self.vartype is Vartype.SPIN:\n self.add_offset(adj[u][v])\n else:\n raise RuntimeError(\"unexpected vartype\")\n self.remove_interaction(u, v)\n\n # all of the interactions that v has become interactions for u\n neighbors = list(adj[v])\n for w in neighbors:\n self.add_interaction(u, w, adj[v][w])\n self.remove_interaction(v, w)\n\n # finally remove v\n self.remove_variable(v)\n\n###################################################################################################\n# transformations\n###################################################################################################\n\n def relabel_variables(self, mapping, inplace=True):\n \"\"\"Relabel variables of a binary quadratic model as specified by mapping.\n\n Args:\n mapping (dict):\n Dict mapping current variable labels to new ones. If an incomplete mapping is\n provided, unmapped variables retain their current labels.\n\n inplace (bool, optional, default=True):\n If True, the binary quadratic model is updated in-place; otherwise, a new binary\n quadratic model is returned.\n\n Returns:\n :class:`.BinaryQuadraticModel`: A binary quadratic model\n with the variables relabeled. If `inplace` is set to True, returns\n itself.\n\n Examples:\n This example creates a binary quadratic model with two variables and relables one.\n\n >>> import dimod\n ...\n >>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)\n >>> model.relabel_variables({0: 'a'}) # doctest: +SKIP\n BinaryQuadraticModel({1: 1.0, 'a': 0.0}, {('a', 1): -1}, 0.0, Vartype.SPIN)\n\n This example creates a binary quadratic model with two variables and returns a new\n model with relabled variables.\n\n >>> import dimod\n ...\n >>> model = dimod.BinaryQuadraticModel({0: 0., 1: 1.}, {(0, 1): -1}, 0.0, vartype=dimod.SPIN)\n >>> new_model = model.relabel_variables({0: 'a', 1: 'b'}, inplace=False) # doctest: +SKIP\n >>> new_model.quadratic # doctest: +SKIP\n {('a', 'b'): -1}\n\n \"\"\"\n try:\n old_labels = set(mapping)\n new_labels = set(itervalues(mapping))\n except TypeError:\n raise ValueError(\"mapping targets must be hashable objects\")\n\n for v in new_labels:\n if v in self.linear and v not in old_labels:\n raise ValueError(('A variable cannot be relabeled \"{}\" without also relabeling '\n \"the existing variable of the same name\").format(v))\n\n if inplace:\n shared = old_labels & new_labels\n if shared:\n old_to_intermediate, intermediate_to_new = resolve_label_conflict(mapping, old_labels, new_labels)\n\n self.relabel_variables(old_to_intermediate, inplace=True)\n self.relabel_variables(intermediate_to_new, inplace=True)\n return self\n\n linear = self.linear\n quadratic = self.quadratic\n adj = self.adj\n\n # rebuild linear and adj with the new labels\n for old in list(linear):\n if old not in mapping:\n continue\n\n new = mapping[old]\n\n # get the new interactions that need to be added\n new_interactions = [(new, v, adj[old][v]) for v in adj[old]]\n\n self.add_variable(new, linear[old])\n self.add_interactions_from(new_interactions)\n self.remove_variable(old)\n\n return self\n else:\n return BinaryQuadraticModel({mapping.get(v, v): bias for v, bias in iteritems(self.linear)},\n {(mapping.get(u, u), mapping.get(v, v)): bias\n for (u, v), bias in iteritems(self.quadratic)},\n self.offset, self.vartype)\n\n @vartype_argument('vartype')\n def change_vartype(self, vartype, inplace=True):\n \"\"\"Create a binary quadratic model with the specified vartype.\n\n Args:\n vartype (:class:`.Vartype`/str/set, optional):\n Variable type for the changed model. Accepted input values:\n\n * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n inplace (bool, optional, default=True):\n If True, the binary quadratic model is updated in-place; otherwise, a new binary\n quadratic model is returned.\n\n Returns:\n :class:`.BinaryQuadraticModel`. A new binary quadratic model with\n vartype matching input 'vartype'.\n\n Examples:\n This example creates an Ising model and then creates a QUBO from it.\n\n >>> import dimod\n ...\n >>> bqm_spin = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)\n >>> bqm_qubo = bqm_spin.change_vartype('BINARY', inplace=False)\n >>> bqm_spin.offset, bqm_spin.vartype\n (0.5, )\n >>> bqm_qubo.offset, bqm_qubo.vartype\n (-2.0, )\n\n \"\"\"\n\n if not inplace:\n # create a new model of the appropriate type, then add self's biases to it\n new_model = BinaryQuadraticModel({}, {}, 0.0, vartype)\n\n new_model.add_variables_from(self.linear, vartype=self.vartype)\n new_model.add_interactions_from(self.quadratic, vartype=self.vartype)\n new_model.add_offset(self.offset)\n\n return new_model\n\n # in this case we are doing things in-place, if the desired vartype matches self.vartype,\n # then we don't need to do anything\n if vartype is self.vartype:\n return self\n\n if self.vartype is Vartype.SPIN and vartype is Vartype.BINARY:\n linear, quadratic, offset = self.spin_to_binary(self.linear, self.quadratic, self.offset)\n elif self.vartype is Vartype.BINARY and vartype is Vartype.SPIN:\n linear, quadratic, offset = self.binary_to_spin(self.linear, self.quadratic, self.offset)\n else:\n raise RuntimeError(\"something has gone wrong. unknown vartype conversion.\")\n\n # drop everything\n for v in linear:\n self.remove_variable(v)\n self.add_offset(-self.offset)\n\n self.vartype = vartype\n self.add_variables_from(linear)\n self.add_interactions_from(quadratic)\n self.add_offset(offset)\n\n return self\n\n##################################################################################################\n# static method\n##################################################################################################\n\n @staticmethod\n def spin_to_binary(linear, quadratic, offset):\n \"\"\"convert linear, quadratic, and offset from spin to binary.\n Does no checking of vartype. Copies all of the values into new objects.\n \"\"\"\n\n # the linear biases are the easiest\n new_linear = {v: 2. * bias for v, bias in iteritems(linear)}\n\n # next the quadratic biases\n new_quadratic = {}\n for (u, v), bias in iteritems(quadratic):\n new_quadratic[(u, v)] = 4. * bias\n new_linear[u] -= 2. * bias\n new_linear[v] -= 2. * bias\n\n # finally calculate the offset\n offset += sum(itervalues(quadratic)) - sum(itervalues(linear))\n\n return new_linear, new_quadratic, offset\n\n @staticmethod\n def binary_to_spin(linear, quadratic, offset):\n \"\"\"convert linear, quadratic and offset from binary to spin.\n Does no checking of vartype. Copies all of the values into new objects.\n \"\"\"\n h = {}\n J = {}\n linear_offset = 0.0\n quadratic_offset = 0.0\n\n for u, bias in iteritems(linear):\n h[u] = .5 * bias\n linear_offset += bias\n\n for (u, v), bias in iteritems(quadratic):\n\n J[(u, v)] = .25 * bias\n\n h[u] += .25 * bias\n h[v] += .25 * bias\n\n quadratic_offset += bias\n\n offset += .5 * linear_offset + .25 * quadratic_offset\n\n return h, J, offset\n\n###################################################################################################\n# Methods\n###################################################################################################\n\n def copy(self):\n \"\"\"Create a copy of a BinaryQuadraticModel.\n\n Returns:\n :class:`.BinaryQuadraticModel`\n\n Examples:\n\n >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 2}, {(1, 2): 0.5}, 0.5, dimod.SPIN)\n >>> bqm2 = bqm.copy()\n\n\n \"\"\"\n # new objects are constructed for each, so we just need to pass them in\n return BinaryQuadraticModel(self.linear, self.quadratic, self.offset, self.vartype, **self.info)\n\n def energy(self, sample):\n \"\"\"Determine the energy of the specified sample of a binary quadratic model.\n\n Energy of a sample for a binary quadratic model is defined as a sum, offset\n by the constant energy offset associated with the binary quadratic model, of\n the sample multipled by the linear bias of the variable and\n all its interactions; that is,\n\n .. math::\n\n E(\\mathbf{s}) = \\sum_v h_v s_v + \\sum_{u,v} J_{u,v} s_u s_v + c\n\n where :math:`s_v` is the sample, :math:`h_v` is the linear bias, :math:`J_{u,v}`\n the quadratic bias (interactions), and :math:`c` the energy offset.\n\n Code for the energy calculation might look like the following::\n\n energy = model.offset # doctest: +SKIP\n for v in model: # doctest: +SKIP\n energy += model.linear[v] * sample[v]\n for u, v in model.quadratic: # doctest: +SKIP\n energy += model.quadratic[(u, v)] * sample[u] * sample[v]\n\n Args:\n sample (dict):\n Sample for which to calculate the energy, formatted as a dict where keys\n are variables and values are the value associated with each variable.\n\n Returns:\n float: Energy for the sample.\n\n Examples:\n This example creates a binary quadratic model and returns the energies for\n a couple of samples.\n\n >>> import dimod\n >>> bqm = dimod.BinaryQuadraticModel({1: 1, 2: 1}, {(1, 2): 1}, 0.5, dimod.SPIN)\n >>> bqm.energy({1: -1, 2: -1})\n -0.5\n >>> bqm.energy({1: 1, 2: 1})\n 3.5\n\n \"\"\"\n linear = self.linear\n quadratic = self.quadratic\n\n if isinstance(sample, SampleView):\n # because the SampleView object simply reads from an underlying matrix, each read\n # is relatively expensive.\n # However, sample.items() is ~10x faster than {sample[v] for v in sample}, therefore\n # it is much more efficient to dump sample into a dictionary for repeated reads\n sample = dict(sample)\n en = 0\n en += self.offset\n en += sum(linear[v] * sample[v] for v in linear)\n en += sum(sample[u] * sample[v] * quadratic[(u, v)] for u, v in quadratic)\n return en\n\n def energies(self, samples_like, dtype=np.float):\n \"\"\"Determine the energies of the given samples.\n\n Args:\n samples_like (samples_like):\n A collection of raw samples. `samples_like` is an extension of NumPy's array_like\n structure. See :func:`.as_samples`.\n\n dtype (:class:`numpy.dtype`):\n The data type of the returned energies.\n\n Returns:\n :obj:`numpy.ndarray`: The energies.\n\n \"\"\"\n samples, labels = as_samples(samples_like)\n\n if all(v == idx for idx, v in enumerate(labels)):\n ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(dtype=dtype)\n else:\n ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(variable_order=labels, dtype=dtype)\n\n energies = samples.dot(ldata) + (samples[:, irow]*samples[:, icol]).dot(qdata) + offset\n return np.asarray(energies, dtype=dtype) # handle any type promotions\n\n##################################################################################################\n# conversions\n##################################################################################################\n\n def to_coo(self, fp=None, vartype_header=False):\n \"\"\"Serialize the binary quadratic model to a COOrdinate_ format encoding.\n\n .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)\n\n Args:\n fp (file, optional):\n `.write()`-supporting `file object`_ to save the linear and quadratic biases\n of a binary quadratic model to. The model is stored as a list of 3-tuples,\n (i, j, bias), where :math:`i=j` for linear biases. If not provided,\n returns a string.\n\n vartype_header (bool, optional, default=False):\n If true, the binary quadratic model's variable type as prepended to the\n string or file as a header.\n\n .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n .. note:: Variables must use index lables (numeric lables). Binary quadratic\n models saved to COOrdinate format encoding do not preserve offsets.\n\n Examples:\n This is an example of a binary quadratic model encoded in COOrdinate format.\n\n .. code-block:: none\n\n 0 0 0.50000\n 0 1 0.50000\n 1 1 -1.50000\n\n The Coordinate format with a header\n\n .. code-block:: none\n\n # vartype=SPIN\n 0 0 0.50000\n 0 1 0.50000\n 1 1 -1.50000\n\n This is an example of writing a binary quadratic model to a COOrdinate-format\n file.\n\n >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)\n >>> with open('tmp.ising', 'w') as file: # doctest: +SKIP\n ... bqm.to_coo(file)\n\n This is an example of writing a binary quadratic model to a COOrdinate-format string.\n\n >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.SPIN)\n >>> bqm.to_coo() # doctest: +SKIP\n 0 0 -1.000000\n 0 1 -1.000000\n 1 1 1.000000\n\n \"\"\"\n import dimod.serialization.coo as coo\n\n if fp is None:\n return coo.dumps(self, vartype_header)\n else:\n coo.dump(self, fp, vartype_header)\n\n @classmethod\n def from_coo(cls, obj, vartype=None):\n \"\"\"Deserialize a binary quadratic model from a COOrdinate_ format encoding.\n\n .. _COOrdinate: https://en.wikipedia.org/wiki/Sparse_matrix#Coordinate_list_(COO)\n\n Args:\n obj: (str/file):\n Either a string or a `.read()`-supporting `file object`_ that represents\n linear and quadratic biases for a binary quadratic model. This data\n is stored as a list of 3-tuples, (i, j, bias), where :math:`i=j`\n for linear biases.\n\n vartype (:class:`.Vartype`/str/set, optional):\n Variable type for the binary quadratic model. Accepted input values:\n\n * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n If not provided, the vartype must be specified with a header in the\n file.\n\n .. _file object: https://docs.python.org/3/glossary.html#term-file-object\n\n .. note:: Variables must use index lables (numeric lables). Binary quadratic\n models created from COOrdinate format encoding have offsets set to\n zero.\n\n Examples:\n An example of a binary quadratic model encoded in COOrdinate format.\n\n .. code-block:: none\n\n 0 0 0.50000\n 0 1 0.50000\n 1 1 -1.50000\n\n The Coordinate format with a header\n\n .. code-block:: none\n\n # vartype=SPIN\n 0 0 0.50000\n 0 1 0.50000\n 1 1 -1.50000\n\n This example saves a binary quadratic model to a COOrdinate-format file\n and creates a new model by reading the saved file.\n\n >>> import dimod\n >>> bqm = dimod.BinaryQuadraticModel({0: -1.0, 1: 1.0}, {(0, 1): -1.0}, 0.0, dimod.BINARY)\n >>> with open('tmp.qubo', 'w') as file: # doctest: +SKIP\n ... bqm.to_coo(file)\n >>> with open('tmp.qubo', 'r') as file: # doctest: +SKIP\n ... new_bqm = dimod.BinaryQuadraticModel.from_coo(file, dimod.BINARY)\n >>> any(new_bqm) # doctest: +SKIP\n True\n\n \"\"\"\n import dimod.serialization.coo as coo\n\n if isinstance(obj, str):\n return coo.loads(obj, cls=cls, vartype=vartype)\n\n return coo.load(obj, cls=cls, vartype=vartype)\n\n def to_serializable(self, use_bytes=False, bias_dtype=np.float32,\n bytes_type=bytes):\n \"\"\"Convert the binary quadratic model to a serializable object.\n\n Args:\n use_bytes (bool, optional, default=False):\n If True, a compact representation representing the biases as bytes is used.\n\n bias_dtype (numpy.dtype, optional, default=numpy.float32):\n If `use_bytes` is True, this numpy dtype will be used to\n represent the bias values in the serialized format.\n\n bytes_type (class, optional, default=bytes):\n This class will be used to wrap the bytes objects in the\n serialization if `use_bytes` is true. Useful for when using\n Python 2 and using BSON encoding, which will not accept the raw\n `bytes` type, so `bson.Binary` can be used instead.\n\n Returns:\n dict: An object that can be serialized.\n\n Examples:\n\n Encode using JSON\n\n >>> import dimod\n >>> import json\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN)\n >>> s = json.dumps(bqm.to_serializable())\n\n Encode using BSON_ in python 3.5+\n\n >>> import dimod\n >>> import bson\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN)\n >>> doc = bqm.to_serializable(use_bytes=True)\n >>> b = bson.BSON.encode(doc) # doctest: +SKIP\n\n Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`,\n we need to signal to the encoder that it should encode the biases and labels as binary\n data.\n\n >>> import dimod\n >>> import bson\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN)\n >>> doc = bqm.to_serializable(use_bytes=True, bytes_type=bson.Binary)\n >>> b = bson.BSON.encode(doc) # doctest: +SKIP\n\n See also:\n :meth:`~.BinaryQuadraticModel.from_serializable`\n\n :func:`json.dumps`, :func:`json.dump` JSON encoding functions\n\n :meth:`bson.BSON.encode` BSON encoding method\n\n .. _BSON: http://bsonspec.org/\n\n \"\"\"\n from dimod.package_info import __version__\n schema_version = \"2.0.0\"\n\n variables = list(iter_serialize_variables(self.variables))\n\n try:\n variables.sort()\n except TypeError:\n # cannot unlike types in py3\n pass\n\n num_variables = len(variables)\n\n # when doing byte encoding we can use less space depending on the\n # total number of variables\n index_dtype = np.uint16 if num_variables <= 2**16 else np.uint32\n\n ldata, (irow, icol, qdata), offset = self.to_numpy_vectors(\n dtype=bias_dtype,\n index_dtype=index_dtype,\n sort_indices=True,\n variable_order=variables)\n\n doc = {\"basetype\": \"BinaryQuadraticModel\",\n \"type\": type(self).__name__,\n \"version\": {\"dimod\": __version__,\n \"bqm_schema\": schema_version},\n \"variable_labels\": variables,\n \"variable_type\": self.vartype.name,\n \"info\": self.info,\n \"offset\": float(offset),\n \"use_bytes\": bool(use_bytes)\n }\n\n if use_bytes:\n doc.update({'linear_biases': array2bytes(ldata, bytes_type=bytes_type),\n 'quadratic_biases': array2bytes(qdata, bytes_type=bytes_type),\n 'quadratic_head': array2bytes(irow, bytes_type=bytes_type),\n 'quadratic_tail': array2bytes(icol, bytes_type=bytes_type)})\n else:\n doc.update({'linear_biases': ldata.tolist(),\n 'quadratic_biases': qdata.tolist(),\n 'quadratic_head': irow.tolist(),\n 'quadratic_tail': icol.tolist()})\n\n return doc\n\n def _asdict(self):\n # support simplejson encoding\n return self.to_serializable()\n\n @classmethod\n def _from_serializable_v1(cls, obj):\n # deprecated\n import warnings\n\n msg = (\"bqm is serialized with a deprecated format and will no longer \"\n \"work in dimod 0.9.0.\")\n warnings.warn(msg)\n\n from dimod.serialization.json import bqm_decode_hook\n\n # try decoding with json\n dct = bqm_decode_hook(obj, cls=cls)\n if isinstance(dct, cls):\n return dct\n\n # assume if not json then binary-type\n bias_dtype, index_dtype = obj[\"bias_dtype\"], obj[\"index_dtype\"]\n lin = np.frombuffer(obj[\"linear\"], dtype=bias_dtype)\n num_variables = len(lin)\n vals = np.frombuffer(obj[\"quadratic_vals\"], dtype=bias_dtype)\n if obj[\"as_complete\"]:\n i, j = zip(*itertools.combinations(range(num_variables), 2))\n else:\n i = np.frombuffer(obj[\"quadratic_head\"], dtype=index_dtype)\n j = np.frombuffer(obj[\"quadratic_tail\"], dtype=index_dtype)\n\n off = obj[\"offset\"]\n\n return cls.from_numpy_vectors(lin, (i, j, vals), off,\n str(obj[\"variable_type\"]),\n variable_order=obj[\"variable_order\"])\n\n @classmethod\n def from_serializable(cls, obj):\n \"\"\"Deserialize a binary quadratic model.\n\n Args:\n obj (dict):\n A binary quadratic model serialized by :meth:`~.BinaryQuadraticModel.to_serializable`.\n\n Returns:\n :obj:`.BinaryQuadraticModel`\n\n Examples:\n\n Encode and decode using JSON\n\n >>> import dimod\n >>> import json\n ...\n >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN)\n >>> s = json.dumps(bqm.to_serializable())\n >>> new_bqm = dimod.BinaryQuadraticModel.from_serializable(json.loads(s))\n\n See also:\n :meth:`~.BinaryQuadraticModel.to_serializable`\n\n :func:`json.loads`, :func:`json.load` JSON deserialization functions\n\n \"\"\"\n if obj.get(\"version\", {\"bqm_schema\": \"1.0.0\"})[\"bqm_schema\"] != \"2.0.0\":\n return cls._from_serializable_v1(obj)\n\n variables = [tuple(v) if isinstance(v, list) else v\n for v in obj[\"variable_labels\"]]\n\n if obj[\"use_bytes\"]:\n ldata = bytes2array(obj[\"linear_biases\"])\n qdata = bytes2array(obj[\"quadratic_biases\"])\n irow = bytes2array(obj[\"quadratic_head\"])\n icol = bytes2array(obj[\"quadratic_tail\"])\n else:\n ldata = obj[\"linear_biases\"]\n qdata = obj[\"quadratic_biases\"]\n irow = obj[\"quadratic_head\"]\n icol = obj[\"quadratic_tail\"]\n\n offset = obj[\"offset\"]\n vartype = obj[\"variable_type\"]\n\n bqm = cls.from_numpy_vectors(ldata,\n (irow, icol, qdata),\n offset,\n str(vartype), # handle unicode for py2\n variable_order=variables)\n\n bqm.info.update(obj[\"info\"])\n return bqm\n\n def to_networkx_graph(self, node_attribute_name='bias', edge_attribute_name='bias'):\n \"\"\"Convert a binary quadratic model to NetworkX graph format.\n\n Args:\n node_attribute_name (hashable, optional, default='bias'):\n Attribute name for linear biases.\n\n edge_attribute_name (hashable, optional, default='bias'):\n Attribute name for quadratic biases.\n\n Returns:\n :class:`networkx.Graph`: A NetworkX graph with biases stored as\n node/edge attributes.\n\n Examples:\n This example converts a binary quadratic model to a NetworkX graph, using first\n the default attribute name for quadratic biases then \"weight\".\n\n >>> import networkx as nx\n >>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> BQM = bqm.to_networkx_graph()\n >>> BQM[0][1]['bias']\n 0.5\n >>> BQM.node[0]['bias']\n 1\n >>> BQM_w = bqm.to_networkx_graph(edge_attribute_name='weight')\n >>> BQM_w[0][1]['weight']\n 0.5\n\n \"\"\"\n import networkx as nx\n\n BQM = nx.Graph()\n\n # add the linear biases\n BQM.add_nodes_from(((v, {node_attribute_name: bias, 'vartype': self.vartype})\n for v, bias in iteritems(self.linear)))\n\n # add the quadratic biases\n BQM.add_edges_from(((u, v, {edge_attribute_name: bias}) for (u, v), bias in iteritems(self.quadratic)))\n\n # set the offset and vartype properties for the graph\n BQM.offset = self.offset\n BQM.vartype = self.vartype\n\n return BQM\n\n @classmethod\n def from_networkx_graph(cls, G, vartype=None, node_attribute_name='bias',\n edge_attribute_name='bias'):\n \"\"\"Create a binary quadratic model from a NetworkX graph.\n\n Args:\n G (:obj:`networkx.Graph`):\n A NetworkX graph with biases stored as node/edge attributes.\n\n vartype (:class:`.Vartype`/str/set, optional):\n Variable type for the binary quadratic model. Accepted input\n values:\n\n * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n If not provided, the `G` should have a vartype attribute. If\n `vartype` is provided and `G.vartype` exists then the argument\n overrides the property.\n\n node_attribute_name (hashable, optional, default='bias'):\n Attribute name for linear biases. If the node does not have a\n matching attribute then the bias defaults to 0.\n\n edge_attribute_name (hashable, optional, default='bias'):\n Attribute name for quadratic biases. If the edge does not have a\n matching attribute then the bias defaults to 0.\n\n Returns:\n :obj:`.BinaryQuadraticModel`\n\n Examples:\n\n >>> import networkx as nx\n ...\n >>> G = nx.Graph()\n >>> G.add_node('a', bias=.5)\n >>> G.add_edge('a', 'b', bias=-1)\n >>> bqm = dimod.BinaryQuadraticModel.from_networkx_graph(G, 'SPIN')\n >>> bqm.adj['a']['b']\n -1\n\n \"\"\"\n if vartype is None:\n if not hasattr(G, 'vartype'):\n msg = (\"either 'vartype' argument must be provided or \"\n \"the given graph should have a vartype attribute.\")\n raise ValueError(msg)\n vartype = G.vartype\n\n linear = G.nodes(data=node_attribute_name, default=0)\n quadratic = G.edges(data=edge_attribute_name, default=0)\n offset = getattr(G, 'offset', 0)\n\n return cls(linear, quadratic, offset, vartype)\n\n def to_ising(self):\n \"\"\"Converts a binary quadratic model to Ising format.\n\n If the binary quadratic model's vartype is not :class:`.Vartype.SPIN`,\n values are converted.\n\n Returns:\n tuple: 3-tuple of form (`linear`, `quadratic`, `offset`), where `linear`\n is a dict of linear biases, `quadratic` is a dict of quadratic biases,\n and `offset` is a number that represents the constant offset of the\n binary quadratic model.\n\n Examples:\n This example converts a binary quadratic model to an Ising problem.\n\n >>> import dimod\n >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> model.to_ising() # doctest: +SKIP\n ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4)\n\n \"\"\"\n # cast to a dict\n return dict(self.spin.linear), dict(self.spin.quadratic), self.spin.offset\n\n @classmethod\n def from_ising(cls, h, J, offset=0.0):\n \"\"\"Create a binary quadratic model from an Ising problem.\n\n\n Args:\n h (dict/list):\n Linear biases of the Ising problem. If a dict, should be of the\n form `{v: bias, ...}` where v is a spin-valued variable and `bias`\n is its associated bias. If a list, it is treated as a list of\n biases where the indices are the variable labels.\n\n J (dict[(variable, variable), bias]):\n Quadratic biases of the Ising problem.\n\n offset (optional, default=0.0):\n Constant offset applied to the model.\n\n Returns:\n :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to\n :class:`.Vartype.SPIN`.\n\n Examples:\n This example creates a binary quadratic model from an Ising problem.\n\n >>> import dimod\n >>> h = {1: 1, 2: 2, 3: 3, 4: 4}\n >>> J = {(1, 2): 12, (1, 3): 13, (1, 4): 14,\n ... (2, 3): 23, (2, 4): 24,\n ... (3, 4): 34}\n >>> model = dimod.BinaryQuadraticModel.from_ising(h, J, offset = 0.0)\n >>> model # doctest: +SKIP\n BinaryQuadraticModel({1: 1, 2: 2, 3: 3, 4: 4}, {(1, 2): 12, (1, 3): 13, (1, 4): 14, (2, 3): 23, (3, 4): 34, (2, 4): 24}, 0.0, Vartype.SPIN)\n\n \"\"\"\n if isinstance(h, abc.Sequence):\n h = dict(enumerate(h))\n\n return cls(h, J, offset, Vartype.SPIN)\n\n def to_qubo(self):\n \"\"\"Convert a binary quadratic model to QUBO format.\n\n If the binary quadratic model's vartype is not :class:`.Vartype.BINARY`,\n values are converted.\n\n Returns:\n tuple: 2-tuple of form (`biases`, `offset`), where `biases` is a dict\n in which keys are pairs of variables and values are the associated linear or\n quadratic bias and `offset` is a number that represents the constant offset\n of the binary quadratic model.\n\n Examples:\n This example converts a binary quadratic model with spin variables to QUBO format\n with binary variables.\n\n >>> import dimod\n >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> model.to_qubo() # doctest: +SKIP\n ({(0, 0): 1.0, (0, 1): 2.0, (1, 1): -6.0, (1, 2): 6.0, (2, 2): -2.0}, 2.9)\n\n \"\"\"\n qubo = dict(self.binary.quadratic)\n qubo.update(((v, v), bias) for v, bias in iteritems(self.binary.linear))\n return qubo, self.binary.offset\n\n @classmethod\n def from_qubo(cls, Q, offset=0.0):\n \"\"\"Create a binary quadratic model from a QUBO model.\n\n Args:\n Q (dict):\n Coefficients of a quadratic unconstrained binary optimization\n (QUBO) problem. Should be a dict of the form `{(u, v): bias, ...}`\n where `u`, `v`, are binary-valued variables and `bias` is their\n associated coefficient.\n\n offset (optional, default=0.0):\n Constant offset applied to the model.\n\n Returns:\n :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to\n :class:`.Vartype.BINARY`.\n\n Examples:\n This example creates a binary quadratic model from a QUBO model.\n\n >>> import dimod\n >>> Q = {(0, 0): -1, (1, 1): -1, (0, 1): 2}\n >>> model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)\n >>> model.linear # doctest: +SKIP\n {0: -1, 1: -1}\n >>> model.vartype\n \n\n \"\"\"\n linear = {}\n quadratic = {}\n for (u, v), bias in iteritems(Q):\n if u == v:\n linear[u] = bias\n else:\n quadratic[(u, v)] = bias\n\n return cls(linear, quadratic, offset, Vartype.BINARY)\n\n def to_numpy_matrix(self, variable_order=None):\n \"\"\"Convert a binary quadratic model to NumPy 2D array.\n\n Args:\n variable_order (list, optional):\n If provided, indexes the rows/columns of the NumPy array. If `variable_order` includes\n any variables not in the binary quadratic model, these are added to the NumPy array.\n\n Returns:\n :class:`numpy.ndarray`: The binary quadratic model as a NumPy 2D array. Note that the\n binary quadratic model is converted to :class:`~.Vartype.BINARY` vartype.\n\n Notes:\n The matrix representation of a binary quadratic model only makes sense for binary models.\n For a binary sample x, the energy of the model is given by:\n\n .. math::\n\n E(x) = x^T Q x\n\n The offset is dropped when converting to a NumPy array.\n\n Examples:\n This example converts a binary quadratic model to NumPy array format while\n ordering variables and adding one ('d').\n\n >>> import dimod\n >>> import numpy as np\n ...\n >>> model = dimod.BinaryQuadraticModel({'a': 1, 'b': -1, 'c': .5},\n ... {('a', 'b'): .5, ('b', 'c'): 1.5},\n ... 1.4,\n ... dimod.BINARY)\n >>> model.to_numpy_matrix(variable_order=['d', 'c', 'b', 'a'])\n array([[ 0. , 0. , 0. , 0. ],\n [ 0. , 0.5, 1.5, 0. ],\n [ 0. , 0. , -1. , 0.5],\n [ 0. , 0. , 0. , 1. ]])\n\n \"\"\"\n import numpy as np\n\n if variable_order is None:\n # just use the existing variable labels, assuming that they are [0, N)\n num_variables = len(self)\n mat = np.zeros((num_variables, num_variables), dtype=float)\n\n try:\n for v, bias in iteritems(self.binary.linear):\n mat[v, v] = bias\n except IndexError:\n raise ValueError((\"if 'variable_order' is not provided, binary quadratic model must be \"\n \"index labeled [0, ..., N-1]\"))\n\n for (u, v), bias in iteritems(self.binary.quadratic):\n if u < v:\n mat[u, v] = bias\n else:\n mat[v, u] = bias\n\n else:\n num_variables = len(variable_order)\n idx = {v: i for i, v in enumerate(variable_order)}\n\n mat = np.zeros((num_variables, num_variables), dtype=float)\n\n try:\n for v, bias in iteritems(self.binary.linear):\n mat[idx[v], idx[v]] = bias\n except KeyError as e:\n raise ValueError((\"variable {} is missing from variable_order\".format(e)))\n\n for (u, v), bias in iteritems(self.binary.quadratic):\n iu, iv = idx[u], idx[v]\n if iu < iv:\n mat[iu, iv] = bias\n else:\n mat[iv, iu] = bias\n\n return mat\n\n @classmethod\n def from_numpy_matrix(cls, mat, variable_order=None, offset=0.0, interactions=None):\n \"\"\"Create a binary quadratic model from a NumPy array.\n\n Args:\n mat (:class:`numpy.ndarray`):\n Coefficients of a quadratic unconstrained binary optimization (QUBO)\n model formatted as a square NumPy 2D array.\n\n variable_order (list, optional):\n If provided, labels the QUBO variables; otherwise, row/column indices are used.\n If `variable_order` is longer than the array, extra values are ignored.\n\n offset (optional, default=0.0):\n Constant offset for the binary quadratic model.\n\n interactions (iterable, optional, default=[]):\n Any additional 0.0-bias interactions to be added to the binary quadratic model.\n\n Returns:\n :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to\n :class:`.Vartype.BINARY`.\n\n\n Examples:\n This example creates a binary quadratic model from a QUBO in NumPy format while\n adding an interaction with a new variable ('f'), ignoring an extra variable\n ('g'), and setting an offset.\n\n >>> import dimod\n >>> import numpy as np\n >>> Q = np.array([[1, 0, 0, 10, 11],\n ... [0, 2, 0, 12, 13],\n ... [0, 0, 3, 14, 15],\n ... [0, 0, 0, 4, 0],\n ... [0, 0, 0, 0, 5]]).astype(np.float32)\n >>> model = dimod.BinaryQuadraticModel.from_numpy_matrix(Q,\n ... variable_order = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],\n ... offset = 2.5,\n ... interactions = {('a', 'f')})\n >>> model.linear # doctest: +SKIP\n {'a': 1.0, 'b': 2.0, 'c': 3.0, 'd': 4.0, 'e': 5.0, 'f': 0.0}\n >>> model.quadratic[('a', 'd')]\n 10.0\n >>> model.quadratic[('a', 'f')]\n 0.0\n >>> model.offset\n 2.5\n\n \"\"\"\n import numpy as np\n\n if mat.ndim != 2:\n raise ValueError(\"expected input mat to be a square 2D numpy array\")\n\n num_row, num_col = mat.shape\n if num_col != num_row:\n raise ValueError(\"expected input mat to be a square 2D numpy array\")\n\n if variable_order is None:\n variable_order = list(range(num_row))\n\n if interactions is None:\n interactions = []\n\n bqm = cls({}, {}, offset, Vartype.BINARY)\n\n for (row, col), bias in np.ndenumerate(mat):\n if row == col:\n bqm.add_variable(variable_order[row], bias)\n elif bias:\n bqm.add_interaction(variable_order[row], variable_order[col], bias)\n\n for u, v in interactions:\n bqm.add_interaction(u, v, 0.0)\n\n return bqm\n\n def to_numpy_vectors(self, variable_order=None, dtype=np.float, index_dtype=np.int64, sort_indices=False):\n \"\"\"Convert a binary quadratic model to numpy arrays.\n\n Args:\n variable_order (iterable, optional):\n If provided, labels the variables; otherwise, row/column indices are used.\n\n dtype (:class:`numpy.dtype`, optional):\n Data-type of the biases. By default, the data-type is inferred from the biases.\n\n index_dtype (:class:`numpy.dtype`, optional):\n Data-type of the indices. By default, the data-type is inferred from the labels.\n\n sort_indices (bool, optional, default=False):\n If True, the indices are sorted, first by row then by column. Otherwise they\n match :attr:`~.BinaryQuadraticModel.quadratic`.\n\n Returns:\n :obj:`~numpy.ndarray`: A numpy array of the linear biases.\n\n tuple: The quadratic biases in COOrdinate format.\n\n :obj:`~numpy.ndarray`: A numpy array of the row indices of the quadratic matrix\n entries\n\n :obj:`~numpy.ndarray`: A numpy array of the column indices of the quadratic matrix\n entries\n\n :obj:`~numpy.ndarray`: A numpy array of the values of the quadratic matrix\n entries\n\n The offset\n\n Examples:\n >>> bqm = dimod.BinaryQuadraticModel({}, {(0, 1): .5, (3, 2): -1, (0, 3): 1.5}, 0.0, dimod.SPIN)\n >>> lin, (i, j, vals), off = bqm.to_numpy_vectors(sort_indices=True)\n >>> lin\n array([0., 0., 0., 0.])\n >>> i\n array([0, 0, 2])\n >>> j\n array([1, 3, 3])\n >>> vals\n array([ 0.5, 1.5, -1. ])\n\n \"\"\"\n linear = self.linear\n quadratic = self.quadratic\n\n num_variables = len(linear)\n num_interactions = len(quadratic)\n\n irow = np.empty(num_interactions, dtype=index_dtype)\n icol = np.empty(num_interactions, dtype=index_dtype)\n qdata = np.empty(num_interactions, dtype=dtype)\n\n if variable_order is None:\n try:\n ldata = np.fromiter((linear[v] for v in range(num_variables)), count=num_variables, dtype=dtype)\n except KeyError:\n raise ValueError((\"if 'variable_order' is not provided, binary quadratic model must be \"\n \"index labeled [0, ..., N-1]\"))\n\n # we could speed this up a lot with cython\n for idx, ((u, v), bias) in enumerate(quadratic.items()):\n irow[idx] = u\n icol[idx] = v\n qdata[idx] = bias\n\n else:\n try:\n ldata = np.fromiter((linear[v] for v in variable_order), count=num_variables, dtype=dtype)\n except KeyError:\n raise ValueError(\"provided 'variable_order' does not match binary quadratic model\")\n\n label_to_idx = {v: idx for idx, v in enumerate(variable_order)}\n\n # we could speed this up a lot with cython\n for idx, ((u, v), bias) in enumerate(quadratic.items()):\n irow[idx] = label_to_idx[u]\n icol[idx] = label_to_idx[v]\n qdata[idx] = bias\n\n if sort_indices:\n # row index should be less than col index, this handles upper-triangular vs lower-triangular\n swaps = irow > icol\n if swaps.any():\n # in-place\n irow[swaps], icol[swaps] = icol[swaps], irow[swaps]\n\n # sort lexigraphically\n order = np.lexsort((irow, icol))\n if not (order == range(len(order))).all():\n # copy\n irow = irow[order]\n icol = icol[order]\n qdata = qdata[order]\n\n return ldata, (irow, icol, qdata), ldata.dtype.type(self.offset)\n\n @classmethod\n def from_numpy_vectors(cls, linear, quadratic, offset, vartype, variable_order=None):\n \"\"\"Create a binary quadratic model from vectors.\n\n Args:\n linear (array_like):\n A 1D array-like iterable of linear biases.\n\n quadratic (tuple[array_like, array_like, array_like]):\n A 3-tuple of 1D array_like vectors of the form (row, col, bias).\n\n offset (numeric, optional):\n Constant offset for the binary quadratic model.\n\n vartype (:class:`.Vartype`/str/set):\n Variable type for the binary quadratic model. Accepted input values:\n\n * :class:`.Vartype.SPIN`, ``'SPIN'``, ``{-1, 1}``\n * :class:`.Vartype.BINARY`, ``'BINARY'``, ``{0, 1}``\n\n variable_order (iterable, optional):\n If provided, labels the variables; otherwise, indices are used.\n\n Returns:\n :obj:`.BinaryQuadraticModel`\n\n Examples:\n >>> import dimod\n >>> import numpy as np\n ...\n >>> linear_vector = np.asarray([-1, 1])\n >>> quadratic_vectors = (np.asarray([0]), np.asarray([1]), np.asarray([-1.0]))\n >>> bqm = dimod.BinaryQuadraticModel.from_numpy_vectors(linear_vector, quadratic_vectors, 0.0, dimod.SPIN)\n >>> print(bqm.quadratic)\n {(0, 1): -1.0}\n\n \"\"\"\n\n try:\n heads, tails, values = quadratic\n except ValueError:\n raise ValueError(\"quadratic should be a 3-tuple\")\n\n if not len(heads) == len(tails) == len(values):\n raise ValueError(\"row, col, and bias should be of equal length\")\n\n if variable_order is None:\n variable_order = list(range(len(linear)))\n\n linear = {v: float(bias) for v, bias in zip(variable_order, linear)}\n quadratic = {(variable_order[u], variable_order[v]): float(bias)\n for u, v, bias in zip(heads, tails, values)}\n\n return cls(linear, quadratic, offset, vartype)\n\n def to_pandas_dataframe(self):\n \"\"\"Convert a binary quadratic model to pandas DataFrame format.\n\n Returns:\n :class:`pandas.DataFrame`: The binary quadratic model as a DataFrame. The DataFrame has\n binary vartype. The rows and columns are labeled by the variables in the binary quadratic\n model.\n\n Notes:\n The DataFrame representation of a binary quadratic model only makes sense for binary models.\n For a binary sample x, the energy of the model is given by:\n\n .. math::\n\n E(x) = x^T Q x\n\n\n The offset is dropped when converting to a pandas DataFrame.\n\n Examples:\n This example converts a binary quadratic model to pandas DataFrame format.\n\n >>> import dimod\n >>> model = dimod.BinaryQuadraticModel({'a': 1.1, 'b': -1., 'c': .5},\n ... {('a', 'b'): .5, ('b', 'c'): 1.5},\n ... 1.4,\n ... dimod.BINARY)\n >>> model.to_pandas_dataframe() # doctest: +SKIP\n a b c\n a 1.1 0.5 0.0\n b 0.0 -1.0 1.5\n c 0.0 0.0 0.5\n\n \"\"\"\n import pandas as pd\n\n try:\n variable_order = sorted(self.linear)\n except TypeError:\n variable_order = list(self.linear)\n\n return pd.DataFrame(self.to_numpy_matrix(variable_order=variable_order),\n index=variable_order,\n columns=variable_order) # let it choose its own datatype\n\n @classmethod\n def from_pandas_dataframe(cls, bqm_df, offset=0.0, interactions=None):\n \"\"\"Create a binary quadratic model from a QUBO model formatted as a pandas DataFrame.\n\n Args:\n bqm_df (:class:`pandas.DataFrame`):\n Quadratic unconstrained binary optimization (QUBO) model formatted\n as a pandas DataFrame. Row and column indices label the QUBO variables;\n values are QUBO coefficients.\n\n offset (optional, default=0.0):\n Constant offset for the binary quadratic model.\n\n interactions (iterable, optional, default=[]):\n Any additional 0.0-bias interactions to be added to the binary quadratic model.\n\n Returns:\n :class:`.BinaryQuadraticModel`: Binary quadratic model with vartype set to\n :class:`vartype.BINARY`.\n\n Examples:\n This example creates a binary quadratic model from a QUBO in pandas DataFrame format\n while adding an interaction and setting a constant offset.\n\n >>> import dimod\n >>> import pandas as pd\n >>> pd_qubo = pd.DataFrame(data={0: [-1, 0], 1: [2, -1]})\n >>> pd_qubo\n 0 1\n 0 -1 2\n 1 0 -1\n >>> model = dimod.BinaryQuadraticModel.from_pandas_dataframe(pd_qubo,\n ... offset = 2.5,\n ... interactions = {(0,2), (1,2)})\n >>> model.linear # doctest: +SKIP\n {0: -1, 1: -1.0, 2: 0.0}\n >>> model.quadratic # doctest: +SKIP\n {(0, 1): 2, (0, 2): 0.0, (1, 2): 0.0}\n >>> model.offset\n 2.5\n >>> model.vartype\n \n\n \"\"\"\n if interactions is None:\n interactions = []\n\n bqm = cls({}, {}, offset, Vartype.BINARY)\n\n for u, row in bqm_df.iterrows():\n for v, bias in row.iteritems():\n if u == v:\n bqm.add_variable(u, bias)\n elif bias:\n bqm.add_interaction(u, v, bias)\n\n for u, v in interactions:\n bqm.add_interaction(u, v, 0.0)\n\n return bqm\n\n\nBQM = BinaryQuadraticModel\n\"\"\"Alias for :obj:`.BinaryQuadraticModel`\"\"\"\n","sub_path":"dimod/binary_quadratic_model.py","file_name":"binary_quadratic_model.py","file_ext":"py","file_size_in_byte":96483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"265182047","text":"# 输入一个胃口数组和一个饼干大小的数组,让更多的胃口得到满足\ndef findContentChildren(g, s):\n \"\"\"\n :type g: List[int]\n :type s: List[int]\n :rtype: int\n \"\"\"\n g.sort()\n s.sort()\n len1=len(g)\n len2=len(s)\n i=0\n j=0\n num=0\n while i PROFILE_AVATAR_MAX_SIZE:\n raise ValidationError('Maximum file size that can be uploaded is {max_size} KB.'.format(max_size=PROFILE_AVATAR_MAX_SIZE))\n\n\ndef profile_avatar_validate_dimension(avatar):\n width = avatar.width\n height = avatar.height\n if width > PROFILE_AVATAR_MAX_WIDTH or height > PROFILE_AVATAR_MAX_HEIGHT:\n raise ValidationError('Dimensions are larger than what is allowed: {max_width}x{max_height} pixels.'.format(max_width=PROFILE_AVATAR_MAX_WIDTH, max_height=PROFILE_AVATAR_MAX_HEIGHT))\n\n\nclass ProfileModel(Model):\n user = OneToOneField(\n to=UserModel,\n on_delete=CASCADE,\n related_name='profile',\n )\n user_folder_name = CharField(\n verbose_name='user_folder_name',\n max_length=150,\n null=True,\n blank=True,\n )\n avatar = ImageField(\n upload_to=profile_avatar_file_upload_to,\n null=True,\n blank=True,\n validators=[\n profile_avatar_validate_size,\n profile_avatar_validate_dimension,\n ],\n help_text='Maximum file size that can be uploaded is {max_size} KB. Maximum dimensions: {max_width}x{max_height} pixels.'.format(max_size=PROFILE_AVATAR_MAX_SIZE, max_width=PROFILE_AVATAR_MAX_WIDTH, max_height=PROFILE_AVATAR_MAX_HEIGHT),\n )\n\n class Meta:\n db_table = 'mobelux_security_profile'\n verbose_name_plural = 'profiles'\n verbose_name = 'profile'\n ordering = ['user__username', ]\n default_permissions = []\n\n def __str__(self):\n return self.user.__str__()\n\n def get_user_folder_upload_to(self):\n return '{profiles_folder_name}{user_folder_name}'.format(\n profiles_folder_name=PROFILES_FOLDER_NAME + '/',\n user_folder_name=self.user_folder_name + '/',\n )\n\n def get_new_user_folder_upload_to(self):\n return '{profiles_folder_name}{new_user_folder_name}'.format(\n profiles_folder_name=PROFILES_FOLDER_NAME + '/',\n new_user_folder_name=self.user.username + '/',\n )\n\n def get_avatar_file_upload_to(self):\n return '{user_folder_upload_to}{avatar_file_name}.{avatar_file_ext}'.format(\n user_folder_upload_to=self.get_user_folder_upload_to(),\n avatar_file_name=PROFILE_AVATAR_FILE_NAME,\n avatar_file_ext=PROFILE_AVATAR_FILE_EXT,\n )\n\n def get_new_avatar_file_upload_to(self):\n return '{new_user_folder_upload_to}{avatar_file_name}.{avatar_file_ext}'.format(\n new_user_folder_upload_to=self.get_new_user_folder_upload_to(),\n avatar_file_name=PROFILE_AVATAR_FILE_NAME,\n avatar_file_ext=PROFILE_AVATAR_FILE_EXT,\n )\n\n def get_user_folder_path(self):\n return MEDIA_FOLDER_PATH + self.get_user_folder_upload_to()\n\n def get_new_user_folder_path(self):\n return MEDIA_FOLDER_PATH + self.get_new_user_folder_upload_to()\n\n def get_avatar_file_path(self):\n return MEDIA_FOLDER_PATH + self.get_avatar_file_upload_to()\n\n def get_new_avatar_file_path(self):\n return MEDIA_FOLDER_PATH + self.get_new_avatar_file_upload_to()\n\n def signal_profilemodel_pre_save(self):\n user_folder_path = self.get_user_folder_path()\n new_user_folder_path = self.get_new_user_folder_path()\n avatar_file_path = self.get_avatar_file_path()\n new_avatar_file_path = self.get_new_avatar_file_path()\n if not exists_path(path=user_folder_path):\n create_folder_path(path=user_folder_path)\n if user_folder_path == new_user_folder_path:\n if exists_path(path=avatar_file_path):\n if self.avatar:\n self.avatar.name = self.get_avatar_file_upload_to()\n else:\n delete_file_path(path=avatar_file_path)\n else:\n if exists_path(path=new_user_folder_path):\n delete_folder_path(path=new_user_folder_path)\n create_folder_path(path=new_user_folder_path)\n if exists_path(path=avatar_file_path):\n if self.avatar:\n move_file_path(path=avatar_file_path, new_path=new_avatar_file_path)\n self.avatar.name = self.get_new_avatar_file_upload_to()\n else:\n delete_file_path(path=avatar_file_path)\n else:\n if self.avatar:\n self.avatar.name = None\n delete_folder_path(path=user_folder_path)\n self.user_folder_name = self.user.username\n\n\nclass UserGroupModel(Model):\n user = ForeignKey(\n to=UserModel,\n on_delete=CASCADE,\n )\n group = ForeignKey(\n to=AuthGroup,\n on_delete=CASCADE,\n )\n\n class Meta:\n db_table = 'mobelux_security_user_group'\n ordering = ['user', 'group', ]\n default_permissions = []\n\n def __str__(self):\n return '<{user}> <{group}>'.format(user=self.user, group=self.group)\n\n\nclass UserPermissionModel(Model):\n user = ForeignKey(\n to=UserModel,\n on_delete=CASCADE,\n )\n permission = ForeignKey(\n to=AuthPermission,\n on_delete=CASCADE,\n )\n\n class Meta:\n db_table = 'mobelux_security_user_permission'\n ordering = ['user', 'permission', ]\n default_permissions = []\n\n def __str__(self):\n return '<{user}> <{permission}>'.format(user=self.user, permission=self.permission)\n","sub_path":"backend/security/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":12460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39536745","text":"import langid\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n# We use the file saved from last step as example\ntweets_filename = 'twitter_ten_1000_tweets'\ntweets_file = open(tweets_filename, \"r\")\nd={}\nd_langid={}\ncount_geo_tagged = 0\nfor line in tweets_file:\n try:\n # Read in one line of the file, convert it into a json object \n tweet = json.loads(line.strip())\n if 'text' in tweet: # only messages contains 'text' field is a tweet\n #print tweet['lang'] # This is the tweet's id\n #print tweet['place']['country']\n if (tweet['place']['country'] =='United States'):\n if tweet['lang'] in d.keys():\n d[tweet['lang']]=d.get(tweet['lang'], 0)+1\n else:\n d[tweet['lang']]=1\n #print tweet['created_at'] # when the tweet posted\n #print tweet['text'] # content of the tweet\n classify=langid.classify(tweet['text'])\n classify=classify[0]\n if classify in d_langid.keys():\n d_langid[classify]=d_langid.get(classify, 0)+1\n else:\n d_langid[classify]=1\n #print tweet['user']['id'] # id of the user who posted the tweet\n #print tweet['user']['name'] # name of the user, e.g. \"Wei Xu\"\n\n if tweet['user']['geo_enabled'] == 1 :\n count_geo_tagged += 1\n\n except:\n # read in a line is not in JSON format (sometimes error occured)\n continue\n\n\nd_modified=STRING_DATA = dict([(str(k), v) for k, v in d.items()])\nprint (d)\n#print d_modified\nsum=0\n\nprint (d_langid)\nsum=0\nfor key,value in d_langid.items():\n sum+=value\nprint (sum)\n\nprint('Tweets in UnitedStates')\nfor key, value in d.items() :\n\tprint(key, round((value*100.0/count_geo_tagged),2) , '%')\n\n#plt.plot(map_twitter.keys(), map_twitter.values() , 'ro')\n\n#plt.show()\n\n","sub_path":"operate_q4.py","file_name":"operate_q4.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"455604710","text":"import tensorflow as tf\n# use here to create or models\nx1 = tf.constant(5)\nx2 = tf.constant(6)\n\nresult = tf.multiply(x1,x2)\n\n# Need to close sessions like writing opening docs\nwith tf.Session() as sess:\n output = sess.run(result)\n print(result)\n","sub_path":"tensorflow/tutorial1.py","file_name":"tutorial1.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39859940","text":"#!/usr/bin/env python\n\nfrom src.transcript import Transcript \nfrom src.gene import Gene\nfrom src.mrna import Mrna\n\ndef build_transcript_dictionary(seqs, genes):\n transcripts = {}\n\n for gene in genes:\n gene = Gene.from_gff_feature(gene)\n if gene == None:\n print(\"Could not convert GFFFeature to Gene, skipping\")\n continue\n\n new_mrnas = []\n for mrna in gene['mrna']:\n mrna = Mrna.from_gff_feature(mrna)\n if mrna == None:\n print(\"Could not convert GFFFeature to Mrna, skipping\")\n continue\n new_mrnas.append(mrna)\n gene.children['mrna'] = new_mrnas\n\n if gene.seqid in transcripts:\n transcripts[gene.seqid].genes.append(gene)\n else:\n if gene.seqid in seqs:\n transcripts[gene.seqid] = Transcript([gene], seqs[gene.seqid])\n else:\n print(\"Gene \"+gene.attributes[\"ID\"]+\" is on sequence \"+gene.seqid+\" which does not exist. Skipping...\")\n\n return transcripts\n","sub_path":"src/transcript_builder.py","file_name":"transcript_builder.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"638319069","text":"\"\"\"\n NTT Data @author Marcus Rockel\n\"\"\"\n\nimport pandas as pd\nimport datetime\nfrom openpyxl import load_workbook\nfrom openpyxl.worksheet.table import Table, TableStyleInfo\nfrom openpyxl.styles import Alignment\n#from openpyxl.worksheet.worksheet import max_row\nimport os\nimport inspect\nimport sys\nimport re\nfrom . import config\nfrom . import load\nfrom numpy import where, arange, nan\n\n\ndef write_messages_to_record(message, filepath_out, obj, to_column=\"A\"):\n \"\"\"\n Input:\n - message: a dataframe with the following columns\n - 'Row_No'\n - obj + '_Migration_Id'\n - 'Filename'\n - 'Message'\n - filepath_out: the filepath where to write to\n - obj: \"Account\" or \"Contact\"\n - to_column: which column to write to\n Output: Messages in excel file\n \"\"\"\n for file in message.Filename.unique():\n if obj in [\"Account\", \"Contact\"]:\n tableName = \"Table_\" + obj + \"s\"\n display_name = tableName\n else:\n tableName = \"Table_\" + obj\n display_name = tableName\n style = TableStyleInfo(name=\"TableStyleMedium2\", showRowStripes=True)\n\n message.columns = [\n 'Row_No', obj + '_Migration_Id', 'Filename', 'Message']\n message_out = message.loc[\n message.Filename == file, [\n 'Row_No', 'Message']].sort_values(by='Row_No')\n wb = load_workbook(filepath_out + file) \n if obj == \"Account\":\n ws = wb['AccountData']\n else:\n ws = wb[obj]\n ws[\"A6\"].value = 'Message'\n for row in ws.iter_rows(min_row=7):\n for cell in row:\n cell.alignment = Alignment(wrapText=True)\n for i in range(0, message_out.shape[0]):\n ws[to_column + str(i + 7)\n ].value = message_out.Message.iloc[i]\n for i, table in enumerate(ws._tables):\n if table.name == tableName:\n tableRef = i\n resTable = Table(\n displayName=display_name, ref=\"A\" + ws._tables[i].ref[1:])\n resTable.tableStyleInfo = style\n ws._tables[tableRef] = resTable\n # set a minimum width for column A\n if ws.column_dimensions[\"A\"].width < 50 and to_column == \"A\":\n ws.column_dimensions[\"A\"].width = 50\n wb.save(filepath_out + file)\n\n\ndef get_messages_to_record(\n filepath,\n obj,\n date=None,\n filename=None,\n data_path=None):\n m = re.search(r'(.*/)[^/]*/([^/]*)$', filepath.replace('\\\\','/'))\n if m:\n filepath_out = m.group(1)\n else:\n print(\"whoops\")\n message = pd.read_csv(\n filepath,\n skiprows=1,\n names=[\n 'Row_No',\n obj + '_Migration_Id',\n 'Filename',\n 'Message']).sort_values(by='Row_No').fillna('')\n write_messages_to_record(\n message, filepath_out, obj)\n\n\ndef mark_deduplicated_records(obj, country, filename_starts_with=\"\"):\n df = load.file_load(obj, country, filename_starts_with=filename_starts_with)\n df['Row_No'] = arange(len(df))+1\n dupl_path = config.FILEPATHS['data_path'] + country + \"\\\\\" + obj + \"\\\\Duplicate_Report\\\\Complete_\" + obj + \"_Duplicate_Report.xlsx\"\n dupl = pd.read_excel(\n dupl_path,\n dtype=str,\n usecols='A, C')\n dupl.columns = ['Id', 'Dupl_Filename']\n df = pd.merge(\n df, dupl[['Id', 'Dupl_Filename']], left_on=obj+'_Migration_Id', right_on='Id', how='left')\n df['Message'] = where(\n [df.Dupl_Filename.iloc[i] != 'Not Deduplicated' and isinstance(df.Dupl_Filename.iloc[i], str) for i in range(0,df.shape[0])],\n 'Duplicate',\n '')\n filepath_out = (config.FILEPATHS['data_path'] + country + \"\\\\\" + obj + \"\\\\\").replace('\\\\','/')\n \n write_messages_to_record(\n df[['Row_No', obj + '_Migration_Id', 'Filename', 'Message']],\n filepath_out,\n obj=obj)\n\n\ndef get_duplicate_column_values(df, column):\n counts = pd.DataFrame(df[column].value_counts().reset_index())\n counts.columns = [column, column + '_count']\n df = pd.merge(\n df,\n counts,\n on=column,\n how=\"left\")\n return df\n\n\ndef mark_duplicate_migration_ids(obj, country, filename_starts_with=\"\"):\n \"\"\" Mark migration Ids that occur more than once \"\"\"\n df = load.file_load(obj, country, filename_starts_with=filename_starts_with)\n df['Row_No'] = arange(len(df))+1\n df = get_duplicate_column_values(df, obj + \"_Migration_Id\")\n\n df['Message'] = where(\n df[obj + \"_Migration_Id_count\"] > 1,\n 'Duplicate Migration Id',\n '')\n filepath_out = (config.FILEPATHS['data_path'] + country + \"\\\\\" + obj + \"\\\\\").replace('\\\\','/')\n \n write_messages_to_record(\n df[['Row_No', obj + '_Migration_Id', 'Filename', 'Message']],\n filepath_out,\n obj=obj)\n\ndef make_column_values_unique(\n obj,\n country,\n filename_starts_with=\"\",\n column=\"\"):\n \"\"\" Mark migration Ids that occur more than once \"\"\"\n if column == \"\":\n column = obj + \"_Migration_Id\"\n df = load.file_load(obj, country, filename_starts_with)\n df['Row_No'] = arange(len(df)) + 1\n df = get_duplicate_column_values(df, column)\n df['Message'] = where(df[column + \"_count\"] > 1,\n df[column] + \"@\" + df.Row_No.apply(str),\n df[column])\n filepath_out = (config.FILEPATHS['data_path'] + country + \"\\\\\" + obj + \"\\\\\").replace('\\\\','/')\n \n write_messages_to_record(\n df[['Row_No', obj + '_Migration_Id', 'Filename', 'Message']],\n filepath_out,\n obj=obj,\n to_column=\"B\")\n\ndef insert_column_values_by_migr_id(\n message,\n filepath_out,\n obj,\n country,\n filename_starts_with=\"\",\n to_column=\"A\"):\n \"\"\"\n Input:\n - message: a dataframe with the following columns\n - obj + '_Migration_Id',\n - 'Filename',\n - 'New_Column_Value'\n - filepath_out: the filepath where to write to\n - obj: \"Account\" or \"Contact\"\n - to_column: which column to write to\n Output: Messages in excel file\n \"\"\"\n res = [k for k in message.Filename.unique() if filename_starts_with in k]\n for file in res:\n message_out = message.loc[\n message.Filename == file,\n [obj + '_Migration_Id', 'Filename', 'New_Column_Value']]\n df = load.file_load(obj, country, filename_starts_with=file)\n df = pd.merge(\n df,\n message_out[[obj + '_Migration_Id', 'New_Column_Value']],\n on = obj + \"_Migration_Id\",\n how=\"left\")\n df['Row_No'] = df.index + 1\n # df.Row_No = df.Row_No.astype(str)\n write_messages_to_record(\n df[['Row_No', obj + '_Migration_Id', 'Filename', 'New_Column_Value']],\n filepath_out,\n obj=obj,\n to_column=to_column)","sub_path":"migrationtools/messages_to_records.py","file_name":"messages_to_records.py","file_ext":"py","file_size_in_byte":6939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"290993982","text":"from __future__ import absolute_import\n\nimport cv2\nimport numpy as np\nfrom numpy.linalg import pinv\n\nfrom ball_3d_coordinates.baseline.camera_calibration.cam_cal import CameraCalibration\n\n_CLASSES = 3\n_INPUT_DIMENSION = 4\n_HIDDEN_SIZE = 3\n\n_INITIAL_LEARNING_RATE = 0.01\n_NUMBER_OF_EPOCHS = 500\n\nclass FFNNCameraCalibration(CameraCalibration):\n\t\"\"\" The camera calibration is done following the \n\t\tNeurocalibration paper in which they try to compute the \n\t\t12 parameters of the projection matrix using a\n\t\tneural network approach. Given a certain number of samples\n\t\tthey use this information to minimize the projection error. \"\"\"\n\tdef __init__(self):\n\t\tsuper(FFNNCameraCalibration, self).__init__()\n\n\tdef compute_camera_calibration(self):\n\t\t\"\"\" Having W and V which are respectevely the intrisic parameters\n\t\t\tand the extrinsic ones, we can now compute the \n\t\t\tentire projection matrix, de-normalizing the values \"\"\"\n\t\tW, V = self.train()\n\n\t\tW[0][0] = W[0][0] * (self.S1_x_max - self.S1_x_min) + self.S1_x_min\n\t\tW[1][1] = W[1][1] * (self.S1_y_max - self.S1_y_min) + self.S1_y_min\n\n\t\tV[0][0] = V[0][0] * (self.S2_x_max - self.S2_x_min) + self.S2_x_min\n\t\tV[1][1] = V[1][1] * (self.S2_y_max - self.S2_y_min) + self.S2_y_min\n\t\tV[2][2] = V[2][2] * (self.S2_z_max - self.S2_z_min) + self.S2_z_min\n\n\t\tP = np.dot(W, np.transpose(V))\n\n\t\treturn P\n\n\tdef loss(self, model, X, D):\n\t\t\"\"\" Computation of the loss in order\n\t\t\tto keep track of the learning \"\"\"\n\n\t\tV = model['V']\n\t\tW = model['W']\n\t\tL = model['L']\n\n\t\t\"\"\" Inference \"\"\"\n\t\tY = np.dot(X, V)\n\t\tZ = np.dot(Y, W)\n\t\tO = np.multiply(Z, L)\n\n\t\treturn 1/2 * np.sum(np.power((D - O), 2))\n\n\tdef normalize_2d(self, data):\n\t\t\"\"\" The method computes the 2D normalization \n\t\t\tsaving the parameters for computing the \n\t\t\tinverse normalization \"\"\"\n\t\tmin_value = np.min(data[:,0])\n\t\tmax_value = np.max(data[:,0])\n\n\t\tdata[:,0] = (data[:,0] - min_value) / (max_value - min_value)\n\n\t\tself.S1_x_min = min_value\n\t\tself.S1_x_max = max_value\n\n\t\tmin_value = np.min(data[:,1])\n\t\tmax_value = np.max(data[:,1])\n\n\t\tdata[:,1] = (data[:,1] - min_value) / (max_value - min_value)\n\n\t\tself.S1_y_min = min_value\n\t\tself.S1_y_max = max_value\n\n\t\treturn data\n\n\tdef normalize_3d(self, data):\n\t\t\"\"\" The method computes the 3D normalization \n\t\t\tsaving the parameters for computing the \n\t\t\tinverse normalization \"\"\"\n\t\tmin_value = np.min(data[:,0])\n\t\tmax_value = np.max(data[:,0])\n\n\t\tdata[:,0] = (data[:,0] - min_value) / (max_value - min_value)\n\n\t\tself.S2_x_min = min_value\n\t\tself.S2_x_max = max_value\n\n\t\tmin_value = np.min(data[:,1])\n\t\tmax_value = np.max(data[:,1])\n\n\t\tdata[:,1] = (data[:,1] - min_value) / (max_value - min_value)\n\n\t\tself.S2_y_min = min_value\n\t\tself.S2_y_max = max_value\n\n\t\tmin_value = np.min(data[:,2])\n\t\tmax_value = np.max(data[:,2])\n\n\t\tdata[:,2] = (data[:,2] - min_value) / (max_value - min_value)\n\n\t\tself.S2_z_min = min_value\n\t\tself.S2_z_max = max_value\n\n\t\treturn data\n\n\tdef train(self):\n\t\t\"\"\" The method computes the training, initializing\n\t\t\tthe weights, computing the gradient at each epoch\n\t\t\tand updating them accordingly to the learning step.\"\"\"\n\t\tmodel = {}\n\n\t\t\"\"\" Features: adding 1 column of ones to fit the specifications.\"\"\"\n\t\tX = self.get_unity_object_points()\n\n\t\t\"\"\" Normalization of the 3D points \"\"\"\n\t\tX = self.normalize_3d(X)\n\n\t\tones = np.ones((X.shape[0], 1))\n\t\tX = np.concatenate((X, ones), axis=1)\n\t\t\n\t\t\"\"\" Labels: adding 1 column of ones to fit the specifications. \"\"\"\n\t\tD = self.get_unity_img_points()\n\n\t\t\"\"\" Normalization of the 2D points \"\"\"\n\t\tD = self.normalize_2d(D)\n\n\t\tones = np.ones((D.shape[0], 1))\n\t\tD = np.concatenate((D, ones), axis=1)\n\t\t\n\t\tnp.random.seed(0)\n\n\t\t\"\"\" Initialization of the weigths with a random value\n\t\t\tbetween -1 and 1 \"\"\"\n\t\tV = np.random.uniform(low=-1, high=1, size=(4, 3))\n\t\tW = np.random.uniform(low=-1, high=1, size=(3, 3))\n\t\tL = np.ones((X.shape[0], 3)) \n\n\t\tlr = _INITIAL_LEARNING_RATE\n\n\t\tmodel = {'V': V, 'W': W, 'L': L}\n\n\t\tfor epoch in range(0, _NUMBER_OF_EPOCHS):\n\t\t\tfor i in range(0, X.shape[0]):\n\t\t\t\t\"\"\" Inference \"\"\"\n\t\t\t\tY = np.dot(X, V)\n\t\t\t\tZ = np.dot(Y, W)\n\t\t\t\tO = np.multiply(Z, L)\n\n\t\t\t\t\"\"\" W update \"\"\"\n\t\t\t\tfor k in range(0, W.shape[0]):\n\t\t\t\t\tfor j in range(0, W.shape[1]):\n\t\t\t\t\t\tW[j][k] += + lr * (D[i][k] - O[i][k]) * Y[i][j]\n\n\t\t\t\t\"\"\" B update \"\"\"\n\n\t\t\t\t\"\"\" V update \"\"\"\n\t\t\t\tfor l in range(0, V.shape[0]):\n\t\t\t\t\tfor j in range(0, V.shape[1]):\n\t\t\t\t\t\terr = 0\n\t\t\t\t\t\tfor k in range(0, 3):\n\t\t\t\t\t\t\terr += (D[i][k] - O[i][k]) * W[k][j] * X[i][l]\n\t\t\t\t\t\tV[l][j] += + lr * L[i][0] * err\n\n\t\t\t\t\"\"\" L update \"\"\"\n\t\t\t\tsum_err = 0\n\t\t\t\tfor k in range(0, 3):\n\t\t\t\t\terr = D[i][k] - O[i][k]\n\t\t\t\t\tfact = 0\n\t\t\t\t\tfor j in range(0, 3):\n\t\t\t\t\t\tfact += W[k][j] * Y[i][j]\n\t\t\t\t\tsum_err += err * fact\n\t\t\t\tL[i] += + lr * sum_err\n\n\t\t\tmodel = {'V': V, 'W': W, 'L': L}\n\n\t\t\tif epoch % 10 == 0:\n\t\t\t\tprint(\"Loss at epoch (%s): %s\" %(epoch, self.loss(model, X, D)))\n\n\n\t\treturn model['W'], model['V']\n\n\n\t\n\n\n\n\t","sub_path":"ball_3d_coordinates/baseline/camera_calibration/ffnn_cam_cal.py","file_name":"ffnn_cam_cal.py","file_ext":"py","file_size_in_byte":4856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"6764404","text":"\"\"\"\r\n268.缺失数字\r\n给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。\r\n示例 1:\r\n输入: [3,0,1]\r\n输出: 2\r\n示例 2:\r\n输入: [9,6,4,2,3,5,7,0,1]\r\n输出: 8\r\n说明:\r\n你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?\r\n来源:力扣(LeetCode)\r\n链接:https://leetcode-cn.com/problems/missing-number\r\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\r\n\"\"\"\r\nclass Solution:\r\n #5.02%,25.31%\r\n def missingNumber(self, nums) -> int:\r\n for i in range(len(nums)+1):\r\n if i not in nums:\r\n return i\r\n\r\n #95.33%, 22.94%\r\n #利用数学法,但有可能造成溢出,最好一边加一边减\r\n def missingNumber2(self, nums) -> int:\r\n sum = 0\r\n isHaveZero = False\r\n for num in nums:\r\n if num == 0:\r\n isHaveZero = True\r\n sum += num\r\n if not isHaveZero:\r\n return 0\r\n maxNum = max(nums)\r\n temp = (maxNum * (maxNum + 1) >> 1)\r\n if temp == sum:\r\n return maxNum + 1\r\n return temp - sum\r\n #改善上面的数学法\r\n #96.94%,25.31%\r\n def missingNumber3(self, nums) -> int:\r\n sum = 0\r\n for i, num in enumerate(nums):\r\n sum += i+1\r\n sum -= num\r\n return sum\r\n\r\n #位运算法\r\n def missingNumber4(self, nums) -> int:\r\n miss = len(nums)\r\n for i, num in enumerate(nums):\r\n miss ^= i ^ num\r\n return miss\r\n\r\ns = Solution()\r\nprint(s.missingNumber4([1,0]))\r\nprint(s.missingNumber4([1]))\r\nprint(s.missingNumber4([0]))\r\nprint(s.missingNumber4([3,0,1]))\r\nprint(s.missingNumber4([9,6,4,2,3,5,7,0,1]))","sub_path":"MissingNumber.py","file_name":"MissingNumber.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"197708586","text":"'''\nDescription: henggao_learning\nversion: v1.0.0\nAuthor: henggao\nDate: 2020-11-04 10:47:36\nLastEditors: henggao\nLastEditTime: 2020-11-05 17:09:29\n'''\nfrom pymongo import MongoClient\nimport csv\n# 创建连接MongoDB数据库函数\n\n\ndef connection():\n # 1:连接MongoDB数据库\n conn = MongoClient(\"192.168.55.110\", 20000)\n # 2:连接数据库(segyfile)。没有时会自动创建\n db = conn.segyfile\n # 3:创建集合\n set1 = db.data\n # 4:看情况是否选择清空(两种清空方式,第一种不行的情况下,选择第二种)\n # 第一种直接remove\n set1.remove(None)\n # 第二种remove不好用的时候\n # set1.delete_many({})\n return set1\n\n\ndef insertToMongoDB(set1):\n # 打开文件test.csv\n with open('./mongeostore_env/upload/test.csv', 'r', encoding='utf-8')as csvfile:\n # 调用csv中的DictReader函数直接获取数据为字典形式\n reader = csv.DictReader(csvfile)\n # 创建一个counts计数一下 看自己一共添加了了多少条数据\n counts = 0\n for each in reader:\n # 将数据中需要转换类型的数据转换类型。原本全是字符串(string)。\n each['?rank'] = int(each['?rank'])\n each['costMoney'] = float(each['costMoney'])\n each['combat'] = float(each['combat'])\n each['topHeroesCombat'] = int(each['topHeroesCombat'])\n # each['表显里程'] = float(each['表显里程'])\n # each['排量'] = float(each['排量'])\n # each['过户数量'] = int(each['过户数量'])\n set1.insert(each)\n # set1.insert_one(each)\n counts += 1\n print('成功添加了'+str(counts)+'条数据 ')\n# 创建主函数\n\n\ndef main():\n set1 = connection()\n insertToMongoDB(set1)\n\n\n# 判断是不是调用的main函数。这样以后调用的时候就可以防止不会多次调用 或者函数调用错误\nif __name__ == '__main__':\n main()\n","sub_path":"mytest/10csvtomongo.py","file_name":"10csvtomongo.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"293821516","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\"\"\"\nCopyright (C) 2019 Unisoc\nCreated on Jan 18, 2016\n2016.03.11 -- add ytag parser\n2019.01.05 -- add .ylog parser\n2019.11.19 -- add ylog 4.x cap file parser\n\"\"\"\n\nimport errno\nimport operator\nimport optparse\nimport os\nimport shutil\nimport sys\nimport traceback\nimport zlib\nfrom ctypes import *\n\nLOG_FILE_MAX_SIZE = 1024 * 1024 * 250\nKEY_LENGTH = 1\n\n\nclass FileHeader(Structure):\n _fields_ = [('m', c_int),\n ('r', c_char * 64),\n ('v', c_int),\n ('re', c_char * 24), ]\n\n\nclass BlockHeader(Structure):\n _fields_ = [('m', c_int),\n ('seq', c_uint),\n ('l', c_int),\n ('z', c_int),\n ('t', c_char)]\n\n\nclass FileTail(Structure):\n _fields_ = [('m', c_int),\n ('seq', c_uint),\n ('l', c_int),\n ('v', c_int),\n ('r', c_char * 64),\n ('re', c_char * 24), ]\n\n\nANDROID_LOG_FILE_DICT = {\n 'M': 'android_main.log',\n 'S': 'android_system.log',\n 'R': 'android_radio.log',\n 'E': 'android_events.log',\n 'C': 'android_crash.log',\n}\nYLOG_LOG_FILE_DICT = {}\nYLOG_CTL_CMD_DICT = {}\nYLOG_LOG_FILE_FD_DICT = {}\nYLOG_LOG_FILE_ID_DICT = {}\n\nIS_DEBUG_MODE = False\n\n# Python version check\nver = sys.version_info\nif ver[0] == 3:\n my_open = open\nelse:\n def my_open(file, mode='rb'):\n return open(file, mode)\n\n\ndef get_next_filename(old_file_name, index):\n return \"{id}-{name}\".format(id=index, name=old_file_name)\n\n\ndef split_andorid_log_file(root_dir, log_file_dir_path, android_log, android_log_file_dict):\n android_log_file_fd_dict = {}\n android_log_file_id_dict = {}\n keys = list(android_log_file_dict.keys())\n last_token = ''\n log_file_dir_full_path = root_dir + log_file_dir_path\n\n for key in keys:\n android_log_file_id_dict[key] = 0\n filename = get_next_filename(android_log_file_dict[key], android_log_file_id_dict[key])\n android_log_file_fd_dict[key] = my_open(os.path.join(log_file_dir_full_path, filename), 'wb')\n\n count = -1\n while True:\n count = count + 1\n filename = os.path.join(log_file_dir_full_path, get_next_filename(android_log, count))\n log_file = None\n if os.path.isfile(filename):\n log_file = my_open(filename, 'rb')\n if log_file is None:\n break\n for binary_data in log_file.readlines():\n log_line = binary_data.decode(errors='ignore')\n if log_line[0:KEY_LENGTH] in keys:\n token = log_line[0:KEY_LENGTH]\n android_log_file_fd_dict[token].write(binary_data)\n last_token = token\n if android_log_file_fd_dict[token].tell() > LOG_FILE_MAX_SIZE:\n android_log_file_id_dict[token] = android_log_file_id_dict[token] + 1\n filename = get_next_filename(android_log_file_dict[token], android_log_file_id_dict[token])\n android_log_file_fd_dict[token].close()\n android_log_file_fd_dict[token] = my_open(os.path.join(log_file_dir_full_path, filename), 'wb')\n else:\n if len(last_token) > 0:\n android_log_file_fd_dict[last_token].write(binary_data)\n log_file.close()\n\n for key in keys:\n android_log_file_fd_dict[key].close()\n\n\ndef unzip_ylog_file(ylog_file, log_file_dir):\n global IS_DEBUG_MODE\n ylog_dict_build = False\n debug_log_file = None\n try:\n tmp_ylog_file = ylog_file + \".tmp\"\n if not os.path.isfile(ylog_file):\n print(\"open ylog err\")\n return\n if IS_DEBUG_MODE:\n debug_log_file = open(tmp_ylog_file, \"wb\")\n\n with open(ylog_file, 'rb') as file:\n file_header = FileHeader()\n while file.readinto(file_header) == sizeof(file_header):\n if file_header.m != 0x2E2E:\n if IS_DEBUG_MODE:\n print('format error')\n pass\n break\n\n block_header = BlockHeader()\n block_count = 1\n\n block_size = sizeof(BlockHeader)\n read_block_size = file.readinto(block_header)\n\n while read_block_size == block_size:\n block_count = block_count + 1\n if block_header.m != 0x5A5A:\n if block_header.m == 0xB5B5:\n file.read(sizeof(FileTail) - sizeof(BlockHeader))\n else:\n if block_header.m == 0x2E2E:\n file.read(sizeof(FileHeader) - sizeof(BlockHeader))\n else:\n block_data = file.read(block_header.l)\n if block_header.z == 1:\n try:\n raw_data = zlib.decompress(block_data)\n except:\n pass\n else:\n raw_data = block_data\n\n if not ylog_dict_build:\n ylog_dict_build = True\n build_ylog_dict(raw_data, log_file_dir)\n\n if (block_header.t != '\\x00') and (ord(block_header.t) != 0):\n key_order = ord(block_header.t)\n\n if YLOG_CTL_CMD_DICT[key_order] == 0:\n decode_data = raw_data.decode(errors='ignore')\n if decode_data.find('YZIPC') != -1 and decode_data.find('CPIZY') != -1:\n YLOG_CTL_CMD_DICT[key_order] = 1\n\n YLOG_LOG_FILE_FD_DICT[key_order].write(raw_data)\n\n if (YLOG_LOG_FILE_FD_DICT[key_order].tell() > LOG_FILE_MAX_SIZE) and (\n YLOG_LOG_FILE_ID_DICT[key_order] != -1):\n YLOG_LOG_FILE_ID_DICT[key_order] = YLOG_LOG_FILE_ID_DICT[key_order] + 1\n filename = get_next_filename(YLOG_LOG_FILE_DICT[key_order],\n YLOG_LOG_FILE_ID_DICT[key_order])\n YLOG_LOG_FILE_FD_DICT[key_order].close()\n YLOG_LOG_FILE_FD_DICT[key_order] = my_open(\n os.path.join(log_file_dir, filename), 'wb')\n\n if IS_DEBUG_MODE:\n debug_log_file.write(raw_data)\n read_block_size = file.readinto(block_header)\n except:\n traceback.print_exc()\n pass\n if debug_log_file is not None:\n debug_log_file.close()\n\n keys = list(YLOG_LOG_FILE_FD_DICT.keys())\n for key in keys:\n if YLOG_LOG_FILE_FD_DICT[key] is not None:\n YLOG_LOG_FILE_FD_DICT[key].close()\n\n\ndef build_ylog_dict(meta_info, log_file_dir):\n YLOG_LOG_FILE_DICT.clear()\n YLOG_CTL_CMD_DICT.clear()\n if IS_DEBUG_MODE:\n print(YLOG_LOG_FILE_DICT)\n print('meta:', meta_info)\n meta = meta_info.decode(\"utf-8\")\n start = meta.find(\"TAGS:\")\n line = meta[start:]\n if line[0:5] == \"TAGS:\":\n if IS_DEBUG_MODE:\n print(line)\n line.strip()\n tags = [x for x in line[5:256].split(';') if x.strip()]\n for tag in tags:\n key = tag[0:tag.find(\":\")]\n value = tag[tag.find(\":\") + 1:]\n key_order = ord(key)\n YLOG_LOG_FILE_DICT.update({key_order: value})\n YLOG_CTL_CMD_DICT.update({key_order: 0})\n\n if IS_DEBUG_MODE:\n print('all log dict:', YLOG_LOG_FILE_DICT.keys())\n\n keys = list(YLOG_LOG_FILE_DICT.keys())\n for key in keys:\n YLOG_LOG_FILE_ID_DICT[key] = 0\n if YLOG_LOG_FILE_DICT[key].find('.log') == -1:\n YLOG_LOG_FILE_ID_DICT[key] = -1\n filename = YLOG_LOG_FILE_DICT[key]\n if YLOG_LOG_FILE_ID_DICT[key] != -1:\n filename = get_next_filename(filename, YLOG_LOG_FILE_ID_DICT[key])\n YLOG_LOG_FILE_FD_DICT[key] = my_open(os.path.join(log_file_dir, filename), 'wb')\n if IS_DEBUG_MODE:\n print(\"new fd dict:\", key, '=', YLOG_LOG_FILE_FD_DICT[key])\n\n\ndef repair_cap_file(filename, filemagic):\n if ver[0] == 3:\n magic = filemagic\n else:\n magic = str(filemagic)\n\n raw_cap_file = open(filename, \"rb\")\n\n while True:\n data = raw_cap_file.read(len(magic))\n if len(data) < len(magic):\n if IS_DEBUG_MODE:\n print(filename, \"repair failed....\")\n break\n if operator.eq(data, magic):\n if raw_cap_file.tell() == len(magic):\n if IS_DEBUG_MODE:\n print(filename, \"raw format ok....\")\n break\n if raw_cap_file.tell() > 0:\n tmp_file_name = filename + '.tmp'\n tmp_file_fd = open(tmp_file_name, 'wb')\n raw_cap_file.seek(-1 * len(magic), 1)\n tmp_file_fd.write(raw_cap_file.read())\n tmp_file_fd.close()\n raw_cap_file.close()\n if IS_DEBUG_MODE:\n print(filename, \"repair ok....\")\n print(tmp_file_name, filename)\n os.remove(filename)\n os.rename(tmp_file_name, filename)\n return True\n raw_cap_file.seek(-1 * (len(magic) - 1), 1)\n raw_cap_file.close()\n\n\ndef parser_ylog_files(root_path, ylog_files):\n for file in ylog_files:\n log_file_dir_path = file.replace('.ylog', '')\n log_file_dir = log_file_dir_path\n log_file_dir_path = '.' + os.sep + log_file_dir_path\n print('extracting ' + file + ' to ' + log_file_dir + os.sep)\n\n if os.path.exists(log_file_dir_path):\n shutil.rmtree(log_file_dir_path)\n try:\n os.mkdir(log_file_dir_path)\n except:\n if IS_DEBUG_MODE:\n traceback.print_exc()\n pass\n\n unzip_ylog_file(file, log_file_dir_path)\n\n try:\n split_andorid_log_file(root_path, log_file_dir_path, \"android.log\", ANDROID_LOG_FILE_DICT)\n parser_ctl_cmd(log_file_dir_path)\n except:\n if IS_DEBUG_MODE:\n traceback.print_exc()\n pass\n\n recheck_file(log_file_dir_path)\n continue\n\n\ndef recheck_file(log_file_dir_path):\n out_log_files = os.listdir(log_file_dir_path)\n for out_log_file in out_log_files:\n log_file = os.path.join(log_file_dir_path, out_log_file)\n if (not os.path.isdir(log_file)) and (0 == os.path.getsize(log_file)):\n os.remove(log_file)\n continue\n if not os.path.isdir(log_file):\n if 'tcpdump' in log_file:\n repair_cap_file(log_file, b'\\xd4\\xc3\\xb2\\xa1')\n if 'hcidump' in log_file:\n repair_cap_file(log_file, b'\\x62\\x74\\x73\\x6e\\x6f\\x6f\\x70')\n\n\ndef parser_ctl_cmd(log_file_dir):\n keys = list(YLOG_LOG_FILE_DICT.keys())\n for key in keys:\n if YLOG_CTL_CMD_DICT[key] != 1:\n continue\n filename = YLOG_LOG_FILE_DICT[key]\n log_file_name = os.path.join(log_file_dir, '0-' + filename)\n yzipctl_cmd_len = 40\n if ('lastlog' in log_file_name) and (os.path.getsize(log_file_name) < yzipctl_cmd_len):\n os.remove(log_file_name)\n continue\n log_file_fd = my_open(log_file_name, 'rb')\n out_file_fd = None\n for binary_data in log_file_fd.readlines():\n line_data = binary_data.decode(errors='ignore')\n start = line_data.find('YZIPC02')\n if start != -1:\n end = line_data.find('20CPIZY')\n out_file_name = log_file_dir + os.sep + binary_data[start + 7:end].decode(errors='ignore')\n if out_file_fd is not None:\n out_file_fd.write(binary_data[0:start])\n out_file_fd.close()\n if not os.path.exists(os.path.dirname(out_file_name)):\n try:\n os.makedirs(os.path.dirname(out_file_name))\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n out_file_fd = my_open(out_file_name, 'wb')\n out_file_fd.write(binary_data[end + 7:])\n else:\n if out_file_fd is not None:\n out_file_fd.write(binary_data)\n log_file_fd.close()\n out_file_fd.close()\n\n\ndef static_andorid_log(android_log_file):\n is_first_line = None\n last_line = \"\"\n line_count = 0\n liblog_count = 0\n lost_log_count = 0\n word_dict = {}\n is_ylog_log = None\n with my_open(android_log_file, 'rb') as f:\n for binary_line in f.readlines():\n if is_first_line is None:\n is_first_line = binary_line\n last_line = binary_line\n line_count = line_count + 1\n line = binary_line.decode(errors='ignore')\n if line.find('liblog :') > 0:\n liblog_count = liblog_count + 1\n liblog_value = line[line.find('liblog :') + 9:]\n if IS_DEBUG_MODE:\n print(int(liblog_value))\n lost_log_count = lost_log_count + int(liblog_value)\n else:\n keys = line.split()\n if len(keys) > 6:\n if '---' in keys[0]:\n continue\n if is_ylog_log is None:\n if ('M' in keys[0] or 'S' in keys[0] or 'E' in keys[0] or 'R' in keys[0] or 'C' in keys[0]):\n is_ylog_log = True\n else:\n is_ylog_log = False\n if is_ylog_log:\n tag_index = 6\n else:\n tag_index = 5\n key = keys[tag_index]\n else:\n key = \"unknown\"\n if key in word_dict:\n word_dict[key] += 1\n else:\n word_dict[key] = 1\n\n word_tups = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n\n if IS_DEBUG_MODE:\n print('0:', is_first_line)\n print(line_count, ':', last_line)\n print('liblog', liblog_count)\n print('liblogc', lost_log_count)\n\n print('Android log output statistics ')\n ljust_len = 18\n print('Lost rate : '.ljust(ljust_len) + '{:.2%}'.format(\n lost_log_count * 1.0001 / (line_count + lost_log_count) * 1.0001))\n print(\"Total line num:\".ljust(ljust_len) + str(line_count + lost_log_count))\n print(\"Lost line num:\".ljust(ljust_len) + str(lost_log_count))\n print('\\n')\n\n max_tags = 0\n print('Chattiest top 12 tags:')\n print('TAG'.ljust(32) + 'NUM'.ljust(8) + 'PERCENT')\n for word_tup in word_tups:\n max_tags += 1\n print(\n word_tup[0].ljust(32) + str(word_tup[1]).ljust(8) + '{:.2%}'.format(word_tup[1] * 1.0001 / line_count))\n if max_tags > 12:\n break\n\n print('\\n')\n\n\ndef sort_by_apk_path(elem):\n return elem[2]\n\n\ndef get_version_info(log_file):\n lst = []\n version_info_file = log_file + '.version.log'\n\n outfile = open(version_info_file, 'w')\n\n do_dump_package = None\n package_name = None\n apk_path = None\n\n with my_open(log_file, 'rb') as f:\n for binary_line in f.readlines():\n line = binary_line.decode(errors='ignore')\n if 'dumpsys package' in line:\n last_do_dump_package = do_dump_package\n do_dump_package = line\n if last_do_dump_package is not None:\n lst.sort(key=sort_by_apk_path)\n outfile.write('\\n\\n' + last_do_dump_package)\n for i in lst:\n outfile.write(i[0] + ' ' + i[1] + ' ' + i[2] + '\\n')\n lst = []\n package_name = None\n apk_path = None\n else:\n if package_name is None:\n if 'Package [' in line:\n package_name = line\n else:\n if apk_path is None:\n if 'codePath=' in line:\n apk_path = line\n else:\n if 'versionName=' in line:\n version_info = line\n lst.append((package_name.strip(), version_info.strip(), apk_path.strip()))\n package_name = None\n apk_path = None\n\n if do_dump_package is not None:\n lst.sort(key=sort_by_apk_path)\n outfile.write('\\n\\n' + do_dump_package)\n for i in lst:\n outfile.write(i[0] + ' ' + i[1] + ' ' + i[2] + '\\n')\n\n outfile.close()\n print('get version info to file ' + version_info_file)\n\n\ndef main():\n global IS_DEBUG_MODE\n\n os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))\n ylog_parser_relative_path = '.' + os.sep\n parser = optparse.OptionParser()\n parser.add_option('-d', dest='set_debug_mode', default=False, action='store_true', help='output some debug info')\n parser.add_option('-s', dest='do_statis', default=False, action='store_true', help='statistics log file')\n parser.add_option('-v', dest='do_versioninfo', default=False, action='store_true', help='get apk version file')\n options, args = parser.parse_args()\n\n if options.set_debug_mode:\n IS_DEBUG_MODE = True\n\n if options.do_statis:\n static_andorid_log(ylog_parser_relative_path + sys.argv[2])\n return\n\n if options.do_versioninfo:\n get_version_info(ylog_parser_relative_path + sys.argv[2])\n return\n\n if not args:\n all_files = os.listdir(os.path.join(ylog_parser_relative_path, ''))\n if IS_DEBUG_MODE:\n print(all_files)\n ylog_files = [f for f in all_files if f.find(\".ylog\", len(f) - 5) > 1]\n else:\n ylog_files = args\n\n if IS_DEBUG_MODE:\n print(ylog_files)\n\n parser_ylog_files(ylog_parser_relative_path, ylog_files)\n\n print(\"extract done\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/load/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":18284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"260636986","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/taurus/qt/qtgui/container/qcontainer.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"This module provides basic pure Qt container widgets\"\"\"\nfrom builtins import str\nimport json\nfrom taurus.external.qt import Qt\nfrom taurus.qt.qtgui.icon import getStandardIcon\n__all__ = [\n 'QGroupWidget']\n__docformat__ = 'restructuredtext'\n_TitleBarStyleExpanded = '.QFrame {{\\nborder-width: 0px;\\nborder-style: solid;\\nborder-color: {stop_color};\\nborder-top-left-radius: {border_radius};\\nborder-top-right-radius: {border_radius};\\nborder-bottom-left-radius: 0px;\\nborder-bottom-right-radius: 0px;\\nbackground-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\\n stop: 0 {start_color}, stop: 1 {stop_color});\\n}}'\n_TitleBarStyleCollapsed = '.QFrame {{\\nborder-width: 0px;\\nborder-style: solid;\\nborder-color: {stop_color};\\nborder-top-left-radius: {border_radius};\\nborder-top-right-radius: {border_radius};\\nborder-bottom-left-radius: {border_radius};\\nborder-bottom-right-radius: {border_radius};\\nbackground-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\\n stop: 0 {start_color}, stop: 1 {stop_color});\\n}}'\n_TitleLabelStyle = '.QLabel {{ color : {font_color}; }}'\n_ContentBarStyleWithTitle = 'ContentFrame {{\\nborder-top-width: 0px;\\nborder-left-width: 1px;\\nborder-right-width: 1px;\\nborder-bottom-width: 1px;\\nborder-style: solid;\\nborder-color: {border_color};\\nborder-top-left-radius: 0px;\\nborder-top-right-radius: 0px;\\nborder-bottom-left-radius: {border_radius};\\nborder-bottom-right-radius: {border_radius};\\nbackground-color: qlineargradient(x1: 0, y1: 0, x2: 1.0, y2: 1.0,\\n stop: 0 {start_color}, stop: 1 {stop_color});\\n/*\\n background-position: center center;\\n*/\\n}}'\n_ContentBarStyleWithoutTitle = 'ContentFrame {{\\nborder-width: 1px;\\nborder-style: solid;\\nborder-color: {border_color};\\nborder-top-left-radius: {border_radius};\\nborder-top-right-radius: {border_radius};\\nborder-bottom-left-radius: {border_radius};\\nborder-bottom-right-radius: {border_radius};\\nbackground-color: qlineargradient(x1: 0, y1: 0, x2: 1.0, y2: 1.0,\\n stop: 0 {start_color}, stop: 1 {stop_color});\\n/*\\n background-position: center center;\\n*/\\n}}'\n\nclass ContentFrame(Qt.QFrame):\n pass\n\n\nclass QGroupWidget(Qt.QWidget):\n \"\"\"An expandable/collapsible composite widget\"\"\"\n DefaultTitleBarVisible = True\n DefaultTitleBarHeight = 16\n DefaultTitleBarStyle = {'start_color': 'rgb(60, 150, 255)', \n 'stop_color': 'rgb(0, 65, 200)', \n 'font_color': 'white', \n 'border_radius': '5px'}\n DefaultContentVisible = True\n DefaultContentStyle = {'start_color': 'rgb(224, 224, 224)', \n 'stop_color': 'rgb(255, 255, 255)', \n 'border_color': 'rgb(0, 85, 227)', \n 'border_radius': '5px'}\n\n def __init__(self, parent=None, designMode=False):\n Qt.QWidget.__init__(self, parent)\n self._titleVisible = self.DefaultTitleBarVisible\n self._contentVisible = self.DefaultContentVisible\n self._titleBarStyle = self.DefaultTitleBarStyle\n self._contentStyle = self.DefaultContentStyle\n self.__init()\n self._updateStyle()\n self.resetContentVisible()\n self.resetTitleHeight()\n self.resetTitleVisible()\n\n def __init(self):\n panelLayout = Qt.QVBoxLayout()\n panelLayout.setSpacing(0)\n panelLayout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(panelLayout)\n self._titleBar = titleBar = Qt.QFrame()\n panelLayout.addWidget(titleBar, 0)\n l = Qt.QHBoxLayout()\n l.setContentsMargins(2, 2, 2, 2)\n l.setSpacing(2)\n self._titleBar.setLayout(l)\n self._titleButton = Qt.QToolButton()\n self._titleButton.setStyleSheet('border: 0px')\n styleOption = Qt.QStyleOption()\n styleOption.initFrom(self._titleButton)\n style = Qt.QApplication.style()\n icon = style.standardIcon(Qt.QStyle.SP_DesktopIcon, styleOption, self._titleButton)\n self._titleButton.setIcon(icon)\n self._titleLabel = Qt.QLabel()\n self._upDownButton = Qt.QToolButton()\n self._upDownButton.setStyleSheet('border: 0px')\n self._upDownButton.clicked.connect(self.switchContentVisible)\n l.addWidget(self._titleButton, 0)\n l.addWidget(self._titleLabel, 1)\n l.addWidget(self._upDownButton, 0)\n self._content = content = ContentFrame()\n l = Qt.QHBoxLayout()\n l.setContentsMargins(0, 0, 0, 0)\n content.setLayout(l)\n panelLayout.addWidget(content, 1)\n\n def _updateStyle(self):\n \"\"\"Internal method that updates the style \"\"\"\n if self.contentVisible:\n ts = _TitleBarStyleExpanded\n else:\n ts = _TitleBarStyleCollapsed\n fullTitleBarStyle = ts.format(**self._titleBarStyle)\n fullTitleLabelStyle = _TitleLabelStyle.format(**self._titleBarStyle)\n if self.titleVisible:\n contentStyleTemplate = _ContentBarStyleWithTitle\n else:\n contentStyleTemplate = _ContentBarStyleWithoutTitle\n contentStyle = self._contentStyle.copy()\n contentStyle['border_color'] = self._titleBarStyle['stop_color']\n fullContentStyle = contentStyleTemplate.format(**contentStyle)\n self._titleBar.setStyleSheet(fullTitleBarStyle)\n self._titleLabel.setStyleSheet(fullTitleLabelStyle)\n self._content.setStyleSheet(fullContentStyle)\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n return {'module': 'taurus.qt.qtgui.container', 'group': 'Taurus Containers', \n 'icon': 'designer:groupwidget.png', \n 'container': True}\n\n def content(self):\n \"\"\"Returns the contents widget\n\n :return: (Qt.QFrame) the content widget\"\"\"\n return self._content\n\n def titleBar(self):\n \"\"\"Returns the title bar widget\n\n :return: (Qt.QFrame) the title bar widget\"\"\"\n return self._titleBar\n\n def titleButton(self):\n \"\"\"Returns the title button widget\n\n :return: (Qt.QToolButton) the title button widget\"\"\"\n return self._titleButton\n\n def collapseButton(self):\n \"\"\"Returns the collapse button widget\n\n :return: (Qt.QToolButton) the collapse button widget\"\"\"\n return self._upDownButton\n\n def setTitle(self, title):\n \"\"\"Sets this widget's title\n\n :param title: (str) the new widget title\"\"\"\n self._titleLabel.setText(title)\n\n def getTitle(self):\n \"\"\"Returns this widget's title\n\n :return: (str) this widget's title\"\"\"\n return self._titleLabel.text()\n\n def setTitleIcon(self, icon):\n \"\"\"Sets this widget's title icon\n\n :param icon: (Qt.QIcon) the new widget title icon\"\"\"\n self._titleButton.setIcon(icon)\n\n def getTitleIcon(self):\n \"\"\"Returns this widget's title icon\n\n :return: (Qt.QIcon) this widget's title icon\"\"\"\n return self._titleButton.icon()\n\n def switchContentVisible(self):\n \"\"\"Switches this widget's contents visibility\"\"\"\n self.setContentVisible(not self.isContentVisible())\n\n def isContentVisible(self):\n \"\"\"Returns this widget's contents visibility\n\n :return: (bool) this widget's contents visibility\"\"\"\n return self._contentVisible\n\n def resetContentVisible(self):\n \"\"\"Resets this widget's contents visibility\"\"\"\n self.setContentVisible(self.DefaultContentVisible)\n\n def setContentVisible(self, show):\n \"\"\"Sets this widget's contents visibility\n\n :param show: (bool) the new widget contents visibility\"\"\"\n self._contentVisible = show\n self._updateStyle()\n if show:\n icon_name = Qt.QStyle.SP_TitleBarShadeButton\n else:\n icon_name = Qt.QStyle.SP_TitleBarUnshadeButton\n icon = getStandardIcon(icon_name, self._upDownButton)\n self._upDownButton.setIcon(icon)\n self._content.setVisible(show)\n self.adjustSize()\n\n def isTitleVisible(self):\n \"\"\"Returns this widget's title visibility\n\n :return: (bool) this widget's title visibility\"\"\"\n return self._titleVisible\n\n def resetTitleVisible(self):\n \"\"\"Resets this widget's title visibility\"\"\"\n self.setTitleVisible(self.DefaultTitleBarVisible)\n\n def setTitleVisible(self, show):\n \"\"\"Sets this widget's title visibility\n\n :param icon: (bool) the new widget title visibility\"\"\"\n self._titleVisible = show\n self._titleBar.setVisible(show)\n self._updateStyle()\n\n def getTitleHeight(self):\n \"\"\"Returns this widget's title height\n\n :return: (bool) this widget's title height\"\"\"\n return self.titleButton().iconSize().height()\n\n def setTitleHeight(self, h):\n \"\"\"Sets this widget's title height\n\n :param icon: (bool) the new widget title height\"\"\"\n s = Qt.QSize(h, h)\n self.titleButton().setIconSize(s)\n self.collapseButton().setIconSize(s)\n\n def resetTitleHeight(self):\n \"\"\"Resets this widget's title height\"\"\"\n self.setTitleHeight(self.DefaultTitleBarHeight)\n\n def getTitleStyle(self):\n \"\"\"Returns this widget's title style\n\n :return: (dict) this widget's title style\"\"\"\n return self._titleBarStyle\n\n def setTitleStyle(self, style_map):\n \"\"\"Sets this widget's title style\n Used key/values for style_map:\n - 'start_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'stop_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'font_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'border_radius': radius (Ex.: '5px', '5px,2px')\n\n :param style_map: (dict) the new widget title style\"\"\"\n style = self.DefaultTitleBarStyle.copy()\n style.update(style_map)\n self._titleBarStyle = style\n self._updateStyle()\n\n def resetTitleStyle(self):\n \"\"\"Resets this widget's title style\"\"\"\n self.setTitleStyle({})\n\n def getTitleStyleStr(self):\n \"\"\"Returns this widget's title style\n\n :return: (dict) this widget's title style\"\"\"\n return json.dumps(self._titleBarStyle)\n\n def setTitleStyleStr(self, style_map):\n \"\"\"Sets this widget's title style\n Used key/values for style_map:\n - 'start_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'stop_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'font_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'border_radius': radius (Ex.: '5px', '5px,2px')\n\n :param style_map: (dict) the new widget title style\"\"\"\n style_map = json.loads(str(style_map))\n self.setTitleStyle(style_map)\n\n def resetTitleStyleStr(self):\n \"\"\"Resets this widget's title style\"\"\"\n self.resetTitleStyle()\n\n def getContentStyle(self):\n \"\"\"Returns this widget's content style\n\n :return: (dict) this widget's content style\"\"\"\n return self._contentStyle\n\n def setContentStyle(self, style_map):\n \"\"\"Sets this widget's content style\n Used key/values for style_map:\n - 'start_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'stop_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n\n :param style_map: (dict) the new widget content style\"\"\"\n style = self.DefaultContentStyle.copy()\n style.update(style_map)\n self._contentStyle = style\n self._updateStyle()\n\n def resetContentStyle(self):\n \"\"\"Resets this widget's content style\"\"\"\n self.setContentStyle({})\n\n def getContentStyleStr(self):\n \"\"\"Returns this widget's content style\n\n :return: (dict) this widget's content style\"\"\"\n return json.dumps(self._contentStyle)\n\n def setContentStyleStr(self, style_map):\n \"\"\"Sets this widget's content style\n Used key/values for style_map:\n - 'start_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n - 'stop_color' : brush (Ex.: '#E0E0E0', 'rgb(0,0,0)', 'white')\n\n :param style_map: (dict) the new widget content style\"\"\"\n style_map = json.loads(str(style_map))\n self.setContentStyle(style_map)\n\n def resetContentStyleStr(self):\n \"\"\"Resets this widget's content style\"\"\"\n self.resetContentStyle()\n\n title = Qt.pyqtProperty('QString', getTitle, setTitle)\n titleIcon = Qt.pyqtProperty('QIcon', getTitleIcon, setTitleIcon)\n titleHeight = Qt.pyqtProperty('int', getTitleHeight, setTitleHeight, resetTitleHeight)\n titleVisible = Qt.pyqtProperty('bool', isTitleVisible, setTitleVisible)\n contentVisible = Qt.pyqtProperty('bool', isContentVisible, setContentVisible, resetContentVisible)\n contentStyle = Qt.pyqtProperty('QString', getContentStyleStr, setContentStyleStr, resetContentStyleStr, doc='The style must be a json dictionary')\n titleStyle = Qt.pyqtProperty('QString', getTitleStyleStr, setTitleStyleStr, resetTitleStyleStr, doc='The style must be a json dictionary')\n\n\ndef demo():\n \"\"\"QGroup Widget\"\"\"\n w = Qt.QWidget()\n l = Qt.QVBoxLayout()\n w.setLayout(l)\n panel = QGroupWidget()\n panel.title = 'Database'\n contentLayout = Qt.QFormLayout()\n panel.content().setLayout(contentLayout)\n contentLayout.addRow('&Host', Qt.QLineEdit())\n contentLayout.addRow('&Port', Qt.QLineEdit())\n l.addWidget(panel, 0)\n panel = QGroupWidget()\n panel.title = 'Hello world'\n panel.titleIcon = Qt.QIcon.fromTheme('video-x-generic')\n panel.setTitleStyle({'start_color': 'rgb(255, 60, 60)', \n 'stop_color': 'rgb(200, 0, 0)', \n 'font_color': 'rgb(140, 0, 0)', \n 'border_radius': '10px'})\n panel.setContentStyle({'border_radius': '0px'})\n contentLayout = Qt.QFormLayout()\n panel.content().setLayout(contentLayout)\n contentLayout.addRow('State', Qt.QPushButton('Press here'))\n contentLayout.addRow('Status', Qt.QLineEdit())\n contentLayout.addRow('Coment', Qt.QLineEdit())\n contentLayout.addRow('Build', Qt.QCheckBox())\n contentLayout.addRow('Upper limit', Qt.QSpinBox())\n contentLayout.addRow('Lower limit', Qt.QSpinBox())\n l.addWidget(panel, 0)\n panel = QGroupWidget()\n panel.title = 'Hello world 2'\n panel.titleIcon = Qt.QIcon.fromTheme('network-server')\n panel.titleVisible = False\n contentLayout = Qt.QFormLayout()\n panel.content().setLayout(contentLayout)\n contentLayout.addRow('Something', Qt.QLineEdit())\n contentLayout.addRow('More', Qt.QLineEdit())\n l.addWidget(panel, 0)\n panel = QGroupWidget()\n panel.title = '5'\n panel.titleIcon = Qt.QIcon.fromTheme('folder')\n contentLayout = Qt.QVBoxLayout()\n panel.content().setLayout(contentLayout)\n panel2 = QGroupWidget()\n panel2.title = '5.1'\n panel2.titleIcon = Qt.QIcon.fromTheme('folder')\n panel2.titleHeight = 48\n contentLayout2 = Qt.QFormLayout()\n panel2.content().setLayout(contentLayout2)\n contentLayout2.addRow('Something', Qt.QLineEdit())\n contentLayout2.addRow('More', Qt.QLineEdit())\n contentLayout.addWidget(panel2, 0)\n l.addWidget(panel, 0)\n l.addStretch(1)\n w.show()\n w.adjustSize()\n return w\n\n\ndef main():\n import sys, taurus.qt.qtgui.application\n Application = taurus.qt.qtgui.application.TaurusApplication\n app = Application.instance()\n owns_app = app is None\n if owns_app:\n app = Application(app_name='Group widget demo', app_version='1.0', org_domain='Taurus', org_name='Tango community')\n w = demo()\n w.show()\n if owns_app:\n sys.exit(app.exec_())\n else:\n return w\n return\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/taurus-4.6.1-py2.7/qcontainer.py","file_name":"qcontainer.py","file_ext":"py","file_size_in_byte":15890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"413080346","text":"from sys import argv\nfrom os.path import exists\n\nscript, from_file, to_file = argv\n\nprint (\"Copying from {0} to {1}\".format(from_file, to_file))\ntexto = open(from_file, \"r\")\nindata = (texto.read())\n\nprint (\"The input file is {0} bytes long\".format(len(indata)))\n\nprint (\"Does the output file exist? {0}\".format(exists(to_file)))\nprint (\"Ready, hit RETURN to continue, CTRL-C to abort\")\ninput()\n\noutput = open(to_file, \"w\")\noutput.write(indata)\n\nprint (\"Alright, all done\")\ninput(\"Finish? \")\n\noutput.close()\ntexto.close()\n","sub_path":"Programación/Código Python/TheHardWay/ex17.py","file_name":"ex17.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"554153062","text":"import os\nimport numpy as np\n\nclass Model:\n def __init__(self):\n pass\n\n @staticmethod\n def get_s_params(frequency, length, width, thickness, delta_length):\n '''\n Calculates waveguide s-parameters based on the SiEPIC compact model for waveguides\n Args:\n None\n frequency (frequency array) and self.wglen (waveguide length) are used to calculate the s-parameters\n Returns:\n None\n self.s becomes the s-matrix calculated by this function \n '''\n #using file that assumes width 500nm and height 220nm\n filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"WaveGuideTETMStrip,w=500,h=220.txt\")\n\n with open(filename, 'r') as f:#read info from waveguide s-param file\n coeffs = f.readline().split()\n \n mat = np.zeros((len(frequency),2,2), dtype=complex) #initialize array to hold s-params\n \n c0 = 299792458 #m/s\n\n #loss calculation\n TE_loss = 700 #dB/m for width 500nm\n alpha = TE_loss/(20*np.log10(np.exp(1))) \n\n w = np.asarray(frequency) * 2 * np.pi #get angular frequency from frequency\n lam0 = float(coeffs[0]) #center wavelength\n w0 = (2*np.pi*c0) / lam0 #center frequency (angular)\n \n ne = float(coeffs[1]) #effective index\n ng = float(coeffs[3]) #group index\n nd = float(coeffs[5]) #group dispersion\n \n #calculation of K\n K = 2*np.pi*ne/lam0 + (ng/c0)*(w - w0) - (nd*lam0**2/(4*np.pi*c0))*((w - w0)**2)\n \n for x in range(0, len(frequency)): #build s-matrix from K and waveguide length\n mat[x,0,1] = mat[x,1,0] = np.exp(-alpha*length + (K[x]*length*1j))\n \n s = mat\n return frequency, s\n\n @staticmethod\n def about():\n print(\"Lumerical model: uses a third order polynomial to approximate the phase through a waveguide.\")","sub_path":"klayout_dot_config/python/SiEPIC/ann/models/wg1550_lumerical/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"449113287","text":"import numpy as np\n\nimport pytest\nimport json\nimport jsonpickle\n\nfrom metrics import (\n Statistic,\n ttest,\n ttest_greater,\n ttest_less,\n ttest_equal,\n compute_raw_metrics,\n compute_metrics,\n)\n\n\ndef test_successfully_stores_statistics():\n \"\"\"\n Sample size = 3\n Mean = 2\n Standard deviation = 1\n \"\"\"\n s = Statistic(3, 2, 1)\n assert s.mean == 2\n assert s.std == 1\n assert s.sample_size == 3\n\n\ndef test_computes_mean_from_observations():\n \"\"\"\n μ = (1 + 2 + 3 + 4)/4 = 10/4 = 2.5\n \"\"\"\n s = Statistic.from_observations([1, 2, 3, 4])\n assert s.mean == 2.5\n\n\ndef test_computes_sampling_std_from_observations():\n \"\"\"\n μ = 2.5\n std^2 = ((1 - 2.5)^2 + (2 - 2.5)^2 + (3 - 2.5)^2 + (4 - 2.5)^2)/(4 - 1)\n std^2 = ((-1.5)^2 + (-0.5)^2 + (0.5)^2 + (1.5)^2)/3\n std^2 = (2.25 + 0.25 + 0.25 + 2.25)/3 = 5/3\n std = sqrt(5/3)\n \"\"\"\n s = Statistic.from_observations([1, 2, 3, 4])\n assert s.std == np.sqrt(5 / 3)\n\n\ndef test_computes_sample_size_from_observations():\n \"\"\"\n Sample size of [1, 2, 3, 4] is 4, since there are 4 observations\n \"\"\"\n s = Statistic.from_observations([1, 2, 3, 4])\n assert s.sample_size == 4\n\n\ndef test_confidence_interval_exact():\n \"\"\"\n The function shouldn't fail if all samples are the same. The confidence\n interval should then be equal to the only sample value sampled instead of\n failing.\n \"\"\"\n s = Statistic.from_observations([3, 3, 3, 3])\n assert s.confidence_interval() == (3, 3)\n\n\ndef test_confidence_interval():\n \"\"\"\n Example taken from http://www.stat.yale.edu/Courses/1997-98/101/confint.htm:\n\n The dataset \"Normal Body Temperature, Gender, and Heart Rate\" contains 130\n observations of body temperature, along with the gender of each individual\n and his or her heart rate.\n\n Variable N Mean StDev\n TEMP 130 98.249 0.733\n\n Let's assume that the sample was taken randomly, that the sampling distribution\n approximates a normal distribution and the samples are independent, so we\n can use the t statistic to estimate a confidence interval for the body\n temperature. Assume the significance level alpha of 95% (0.05).\n\n The number of degrees of freedom will be:\n dof = N - 1 = 129\n\n Since we want a confidence interval, the central area under the curve will\n have a p-value sum of 0.95, then there will be a 0.025 for each side\n remaining. Then, we want the critical t value for 129 degrees of freedom\n and the significance of 0.025. Using the cfd of the t distribution, we then\n have:\n t* = 1.978524\n\n Notice that at the link of the yale university, an approximate t-value was\n used by looking up a t-table and using 120 degrees of freedom.\n\n The sampling standard deviation then will be StDev/sqrt(N) = 0.733 / sqrt(130)\n\n Finally, our confidence interval will be:\n μ +- t* SEMean\n μ +- 1.978524 * 0.733 / sqrt(130)\n \"\"\"\n mu = 98.249\n std = 0.733\n n = 130\n\n t = 1.978524\n sem = std / np.sqrt(n)\n s = Statistic(n, mu, std)\n\n min_true, max_true = (mu - t * sem, mu + t * sem)\n min_comp, max_comp = s.confidence_interval()\n\n # Since our original values have 3 decimal places, we could approximate up\n # to 3 decimal places for comparison, but instead, let's use the maximum of\n # precision we have from the t value (5 significant digits)\n assert pytest.approx(min_comp, 1e-5) == pytest.approx(min_true, 1e-5)\n assert pytest.approx(max_comp, 1e-5) == pytest.approx(max_true, 1e-5)\n\n\ndef test_ttest_two_tailed():\n \"\"\"\n For this test, let's use an example as reference.\n https://en.wikipedia.org/wiki/Student%27s_t-test\n\n The sample values are:\n A1 = {30.02, 29.99, 30.11, 29.97, 30.01, 29.99}\n A2 = {29.89, 29.93, 29.72, 29.98, 30.02, 29.98}\n \"\"\"\n a1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99]\n a2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98]\n\n s1 = Statistic.from_observations(a1)\n s2 = Statistic.from_observations(a2)\n\n t_value, p_value = ttest(s1, s2, \"two-sided\")\n\n assert pytest.approx(s1.mean - s2.mean, 1e-3) == 0.095\n assert pytest.approx(t_value, 1e-3) == 1.959\n assert pytest.approx(p_value, 1e-3) == 0.07857\n\n\ndef test_ttests_one_tailed():\n \"\"\"\n For this test, let's use an example as reference.\n https://www.statstutor.ac.uk/resources/uploaded/unpaired-t-test.pdf\n \"\"\"\n poultry = [\n 129,\n 132,\n 102,\n 106,\n 94,\n 102,\n 87,\n 99,\n 170,\n 113,\n 135,\n 142,\n 86,\n 143,\n 152,\n 146,\n 144,\n ]\n beef = [\n 186,\n 181,\n 176,\n 149,\n 184,\n 190,\n 158,\n 139,\n 175,\n 148,\n 152,\n 111,\n 141,\n 153,\n 190,\n 157,\n 131,\n 149,\n 135,\n 132,\n ]\n\n s1 = Statistic.from_observations(poultry)\n s2 = Statistic.from_observations(beef)\n\n result = ttest(s1, s2, \"less\")\n assert result[1] < 0.001\n\n\ndef test_return_of_ttest_greater(snapshot):\n snapshot.snapshot_dir = \"snapshots\"\n # Snapshot testing of the return of this function\n s1 = Statistic(30, 10, 2)\n s2 = Statistic(30, 8, 1)\n result = jsonpickle.encode(ttest_greater(s1, s2))\n snapshot.assert_match(json.dumps(result), \"ttest_greater.txt\")\n\n\ndef test_return_of_ttest_less(snapshot):\n snapshot.snapshot_dir = \"snapshots\"\n # Snapshot testing of the return of this function\n s1 = Statistic(30, 10, 2)\n s2 = Statistic(30, 8, 1)\n result = jsonpickle.encode(ttest_less(s1, s2))\n snapshot.assert_match(json.dumps(result), \"ttest_less.txt\")\n\n\ndef test_return_of_ttest_equal(snapshot):\n snapshot.snapshot_dir = \"snapshots\"\n # Snapshot testing of the return of this function\n s1 = Statistic(30, 10, 2)\n s2 = Statistic(30, 8, 1)\n result = jsonpickle.encode(ttest_equal(s1, s2))\n snapshot.assert_match(json.dumps(result), \"ttest_equal.txt\")\n\n\ndef test_return_of_compute_raw_metrics(snapshot):\n snapshot.snapshot_dir = \"snapshots\"\n # Snapshot testing of the return of this function\n s1 = [1, 2, 3, 3]\n s2 = [[2, 3, 3, 2], [2, 2, 3, 3], [3, 3, 3, 3]]\n result = jsonpickle.encode(compute_raw_metrics(s1, s2))\n snapshot.assert_match(json.dumps(result), \"compute_raw_metrics.txt\")\n\n\ndef test_return_of_compute_metrics(snapshot):\n snapshot.snapshot_dir = \"snapshots\"\n # Snapshot testing of the return of this function\n s1 = [1, 2, 3, 3]\n s2 = [[2, 3, 3, 2], [2, 2, 3, 3], [3, 3, 3, 3]]\n result = jsonpickle.encode(compute_metrics(s1, s2))\n snapshot.assert_match(json.dumps(result), \"compute_metrics.txt\")\n","sub_path":"questao-2/src/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":6732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"289551158","text":"from __future__ import print_function\n\nimport argparse\nimport configparser\nimport csv\nimport logging\nimport multiprocessing\nimport os\nimport pickle\nimport sys\nfrom datetime import datetime\n\nimport gym\nimport gym.wrappers as wrappers\nimport neat\nimport numpy as np\nimport visualize\n\n\nclass Neat(object):\n def __init__(self, config):\n pop = neat.Population(config)\n self.stats = neat.StatisticsReporter()\n pop.add_reporter(self.stats)\n pop.add_reporter(neat.StdOutReporter(True))\n # Checkpoint every 10 generations or 900 seconds.\n pop.add_reporter(neat.Checkpointer(10, 900))\n self.config = config\n self.population = pop\n self.pool = multiprocessing.Pool()\n self.generation_count = 0\n self.best_agents = []\n\n def execute_algorithm(self, generations):\n self.population.run(self.fitness_function, generations)\n\n def fitness_function(self, genomes, config):\n t_start = datetime.now()\n\n nets = []\n for gid, g in genomes:\n nets.append((g, neat.nn.FeedForwardNetwork.create(g, config)))\n g.fitness = []\n\n for i, (genome, net) in enumerate(nets):\n # run episodes\n state = env.reset()\n terminal_reached = False\n step_size = props.getint('initialisation', 'step_size')\n step = 0\n total_rewards = 0\n while not terminal_reached:\n # take action based on observation\n nn_output = net.activate(state)\n action = np.argmax(nn_output)\n\n # perform next step\n observation, reward, done, info = env.step(action)\n total_rewards += reward\n for x in range(step_size - 1):\n if done:\n terminal_reached = True\n break\n observation, reward, done, info = env.step(action)\n total_rewards += reward\n\n step += 1\n if done:\n terminal_reached = True\n\n # assign fitness to be total rewards\n genome.fitness = total_rewards\n\n # sort the genomes by fitness\n nets_sorted = sorted(nets, key=lambda x: x[0].fitness, reverse=True)\n # save the best individual's genomes\n best_genome, best_net = nets_sorted[0]\n self.best_agents.append((self.generation_count, best_genome, best_net))\n logger.debug(\"Best genome fitness: %f\", best_genome.fitness)\n\n worst_genome, worst_net = nets_sorted[len(nets_sorted) - 1]\n logger.debug(\"Worst genome fitness: %f\", worst_genome.fitness)\n\n # save genome\n with open('best_genomes/gen-{0}-genome'.format(self.generation_count), 'wb') as f:\n pickle.dump(best_genome, f)\n\n logger.debug(\"Completed generation: %d. Time taken: %f\", self.generation_count,\n (datetime.now() - t_start).total_seconds())\n self.generation_count += 1\n\n\ndef test_best_agent(generation_count, genome, net):\n logger.debug(\"Generating best agent result: %d\", generation_count)\n t_start = datetime.now()\n\n test_episodes = props.getint('test', 'test_episodes')\n step_size = props.getint('initialisation', 'step_size')\n\n total_steps = 0.0\n total_rewards = 0.0\n\n for i in range(test_episodes):\n state = env.reset()\n terminal_reached = False\n steps = 0\n while not terminal_reached:\n env.render()\n output = net.activate(state)\n action = np.argmax(output)\n next_state, reward, done, info = env.step(action)\n\n for x in range(step_size - 1):\n if done:\n terminal_reached = True\n break\n next_state, reward2, done, info = env.step(action)\n reward += reward2\n\n total_rewards += reward\n state = next_state\n\n steps += 1\n if done:\n terminal_reached = True\n total_steps += steps\n\n average_steps_per_episode = total_steps / test_episodes\n average_rewards_per_episode = total_rewards / test_episodes\n\n # save this to file along with the generation number\n entry = [generation_count, average_steps_per_episode, average_rewards_per_episode]\n with open(r'agent_evaluation.csv', 'a') as f:\n writer = csv.writer(f)\n writer.writerow(entry)\n\n logger.debug(\"Finished: evaluating best agent. Time taken: %f\", (datetime.now() - t_start).total_seconds())\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=None)\n parser.add_argument('env_id', nargs='?', default='CartPole-v0', help='Select the environment to run')\n args = parser.parse_args()\n\n # Call `undo_logger_setup` if you want to undo Gym's logger setup\n # and configure things manually. (The default should be fine most\n # of the time.)\n gym.undo_logger_setup()\n\n logging.basicConfig(filename='log/debug-{0}.log'.format(datetime.now().strftime(\"%Y%m%d-%H:%M:%S-%f\")),\n level=logging.DEBUG)\n logger = logging.getLogger()\n formatter = logging.Formatter('[%(asctime)s] %(message)s')\n handler = logging.StreamHandler(sys.stderr)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n # You can set the level to logging.DEBUG or logging.WARN if you\n # want to change the amount of output.\n logger.setLevel(logging.DEBUG)\n\n env = gym.make(args.env_id)\n\n logger.debug(\"action space: %s\", env.action_space)\n logger.debug(\"observation space: %s\", env.observation_space)\n\n # Load the properties file\n local_dir = os.path.dirname(__file__)\n logger.debug(\"Loading Properties\")\n props = configparser.ConfigParser()\n prop_path = os.path.join(local_dir, 'properties/{0}/neatem_properties.ini'.format(env.spec.id))\n props.read(prop_path)\n logger.debug(\"Finished: Loading Properties\")\n\n # Load the config file, which is assumed to live in properties/[environment id] directory\n logger.debug(\"Loading NEAT Config file\")\n config_path = os.path.join(local_dir, 'properties/{0}/config'.format(env.spec.id))\n config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n config_path)\n\n agent = Neat(config)\n\n # Run until the winner from a generation is able to solve the environment\n # or the user interrupts the process.\n env_monitor_setup = False\n try:\n\n agent.execute_algorithm(props.getint('train', 'generation'))\n\n visualize.plot_stats(agent.stats, ylog=False, view=False, filename=\"fitness.svg\")\n\n # generate test results and record gameplay\n if not env_monitor_setup:\n outdir = 'videos/tmp/neat-data/{0}-{1}'.format(env.spec.id, str(datetime.now()))\n env = wrappers.Monitor(env, directory=outdir, force=True)\n env_monitor_setup = True\n\n for (generation_count, genome, net) in agent.best_agents:\n test_best_agent(generation_count, genome, net)\n\n mfs = sum(agent.stats.get_fitness_mean()[-20:]) / 20.0\n logger.debug(\"Average mean fitness over last 20 generations: %f\", mfs)\n\n mfs = sum(agent.stats.get_fitness_stat(min)[-20:]) / 20.0\n logger.debug(\"Average min fitness over last 20 generations: %f\", mfs)\n\n # Use the ten best genomes seen so far as an ensemble-ish control system.\n best_genomes = agent.stats.best_unique_genomes(10)\n\n # Save the winners\n for n, g in enumerate(best_genomes):\n name = 'winners/winner-{0}'.format(n)\n with open(name + '.pickle', 'wb') as f:\n pickle.dump(g, f)\n\n visualize.draw_net(config, g, view=False, filename=name + \"-net.gv\")\n visualize.draw_net(config, g, view=False, filename=name + \"-net-enabled.gv\",\n show_disabled=False)\n visualize.draw_net(config, g, view=False, filename=name + \"-net-enabled-pruned.gv\",\n show_disabled=False, prune_unused=True)\n\n break\n except KeyboardInterrupt:\n logger.debug(\"User break.\")\n\n env.close()\n\n # Upload to the scoreboard. We could also do this from another\n # logger.info(\"Successfully ran RandomAgent. Now trying to upload results to the scoreboard. If it breaks, you can always just try re-uploading the same results.\")\n # gym.upload(outdir)\n","sub_path":"NEAT.py","file_name":"NEAT.py","file_ext":"py","file_size_in_byte":8544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"153181358","text":"import os\nimport time\nimport logging\nfrom utils import get_tmp_file, rm_tmp_dir\nfrom senseye_cameras import create_input, Stream\n\nlog = logging.getLogger(__name__)\n\n\ndef test_read():\n '''\n Test reading from an ffmpeg camera.\n cam.open() will only run successfully if:\n 1. ffmpeg binaries on the system path\n 2. A camera ffmpeg can access.\n Thus, only run the test if camera.open() does not fail.\n '''\n cam = None\n try:\n cam = create_input(type='ffmpeg', id=0)\n cam.open()\n except Exception as e:\n log.warning(f'Test could not be run, camera open failed with error: {e}. This is most likely a hardware issue.')\n return\n\n frame, timestamp = cam.read()\n assert frame is not None\n\n cam.close()\n\n\ndef test_stream():\n '''\n Test an ffmeg stream: ffmpeg -> file\n '''\n try:\n s = Stream(\n input_type='ffmpeg', id=0,\n output_type='file', path=get_tmp_file(),\n reading=True, writing=True,\n )\n except Exception as e:\n log.warning(f'Test could not be run, stream initialization failed with error: {e}. This is most likely a hardware issue.')\n return\n\n time.sleep(2)\n\n s.stop()\n\n assert os.stat(get_tmp_file()).st_size > 0\n rm_tmp_dir()\n","sub_path":"tests/camera_ffmpeg_test.py","file_name":"camera_ffmpeg_test.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"103050866","text":"STOP_WORDS = [\n 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'has',\n 'he', 'i', 'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to',\n 'were', 'will', 'with'\n]\n\nclass FileReader:\n def __init__(self, filename):\n self.filename = filename.open()\n\n def read_contents(self):\n contents = self.filename.read()\n return contents\n\nclass WordList:\n def __init__(self, text):\n self.text = text\n self.words =[]\n\n def extract_words(self):\n import string\n self.words = self.text.lower().split()\n self.words = [word.strip(string.punctuation) for word in self.words]\n\n def remove_stop_words(self):\n self.words = [\n word \n for word in self.words\n if not word in STOP_WORDS]\n\n def get_freqs(self):\n freqs = {\n word: self.words.count(word)\n for word in self.words\n }\n alpha_freqs = dict(sorted(freqs.items()))\n return dict(sorted(alpha_freqs.items(), key=lambda seq: seq[1], reverse=True))\n\nclass FreqPrinter:\n def __init__(self, freqs):\n self.freqs = freqs\n\n def print_freqs(self):\n top_ten = []\n top_ten_words = []\n i = 0\n for item in self.freqs.items():\n if i < 10:\n top_ten.append(item)\n top_ten_words.append(item[0])\n i += 1\n longest_word = max(top_ten_words, key=len)\n for item in top_ten:\n print(f\"{item[0].rjust(len(longest_word) + 2)} | {str(item[1]).ljust(3)}{item[1] * '*'}\")\n\nif __name__ == \"__main__\":\n import argparse\n import sys\n from pathlib import Path\n\n parser = argparse.ArgumentParser(\n description='Get the word frequency in a text file.')\n parser.add_argument('file', help='file to read')\n args = parser.parse_args()\n\n file = Path(args.file)\n if file.is_file():\n reader = FileReader(file)\n word_list = WordList(reader.read_contents())\n word_list.extract_words()\n word_list.remove_stop_words()\n printer = FreqPrinter(word_list.get_freqs())\n printer.print_freqs()\n else:\n print(f\"{file} does not exist!\")\n sys.exit(1)\n","sub_path":"word_frequency.py","file_name":"word_frequency.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"540948233","text":"import discord\nfrom discord.ext import commands\n\n\n# Cog used for reloading updated cogs while bot is running\nclass DevCmd(commands.Cog):\n # Initializes the cog.\n def __init__(self, bot):\n self.bot = bot\n\n # Command used to trigger a reload. The argument list should include the\n # names of the extensions to reload.\n @commands.command()\n @commands.is_owner()\n async def reload(self, ctx, *args):\n # Generate a message to be sent after completion\n message = \"Reload called.\\n\"\n # Iterate through arguments and reload them if they exist\n for arg in args:\n # Set up a variable to store the extension name.\n ext = None\n # Search extension list for the argument\n for extension in self.bot._extension_list:\n if extension.endswith(arg):\n ext = extension\n break\n if ext is None:\n message += f\"{arg} does not exist in loaded extensions.\\n\"\n else:\n message += f\"Reloading {ext}.\\n\"\n # Try to reload the extension; add result to message\n if ext in self.bot._extension_list:\n try:\n self.bot.reload_extension(ext)\n except commands.errors.ExtensionNotLoaded:\n message += f\"{ext} not loaded.\\n\"\n except commands.errors.ExtensionNotFound:\n message += f\"{ext} not found.\\n\"\n except commands.errors.ExtensionFailed as e:\n print(e)\n message += f\"{ext} failed; execution error.\\n\"\n except commands.errors.NoEntryPointError:\n message += f\"{ext} has no setup function.\\n\"\n else:\n message += f\"{ext} reloaded.\\n\"\n else:\n message += f\"{ext} is not in the extension list.\\n\"\n # Remove trailing newline and notify the user\n message = message[:-1]\n print(message)\n await ctx.send(message)\n\n # Reloads all extensions in bot's extension list.\n @commands.command()\n @commands.is_owner()\n async def reload_all(self, ctx):\n # Generate a message to be sent after completion\n message = \"Reloading all extensions. . .\\n\"\n # Iterate through all extensions in bot's extension list and reload them\n for ext in self.bot._extension_list:\n try:\n self.bot.reload_extension(ext)\n except commands.errors.ExtensionNotLoaded:\n message += f\"{ext} not loaded.\\n\"\n except commands.errors.ExtensionNotFound:\n message += f\"{ext} not found.\\n\"\n except commands.errors.ExtensionFailed:\n message += f\"{ext} failed; execution error.\\n\"\n except commands.errors.NoEntryPointError:\n message += f\"{ext} has no setup function.\\n\"\n else:\n message += f\"{ext} reloaded.\\n\"\n message = message[:-1] # get rid of trailing newline\n # Notify the user\n await ctx.send(message)\n print(message)\n\n # Resets all extensions, rebuilding the extension list from scratch\n @commands.command()\n @commands.is_owner()\n async def reset_all(self, ctx):\n message = \"Begin reset of all extensions.\\nUnloading extensions. . .\\n\"\n for ext in self.bot._extension_list:\n try:\n self.bot.unload_extension(ext)\n except commands.errors.ExtensionNotLoaded:\n message += f\"{ext} was not loaded\\n\"\n else:\n message += f\"{ext} unloaded successfully\\n\"\n # Rebuild the extension list from scratch and load the extensions from\n # the generated extension list.\n\n message += \"Rebuilding extension list from scratch. . .\\n\"\n message += self.bot._build_extensions()\n\n # Notify the user\n print(message)\n await ctx.send(message)\n\n\n# setup command for the cog\ndef setup(bot):\n bot.add_cog(DevCmd(bot))\n","sub_path":"cogs/dev_cmd.py","file_name":"dev_cmd.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"385736627","text":"import audio\nimport video\nimport time\nimport os\nimport pygame\n\nMAINPATH = os.path.join(\"..\")\nVIDEOPATH = os.path.join(MAINPATH, \"resources\")\n\nVIDEO = video.Video(VIDEOPATH, \"Hello World\", (800, 600))\n\nsprite = video.Sprite(VIDEO, \"button\")\nsprite.set_position(100, 100)\nsprite.click_bind(lambda: print(\"Hello!\"))\nsprite.draw()\n\ntext = video.Text(VIDEO, \"regular-bold\", 34)\ntext.set_color((255, 255, 255))\ntext.set_text(\"Hello World! This is a test to see if my wrapping function works now that I got the text class back.\")\ntext.set_wrapping_to(True, 300)\ntext.set_position(200, 200)\ntext.draw()\n\ngame = True\n\nwhile game:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game = False\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n VIDEO.send_click_global_event(event.pos)\n if event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n VIDEO.send_unclick_global_event(event.pos)\n if event.type == pygame.MOUSEMOTION:\n VIDEO.send_mouse_motion_event(event.pos)\n VIDEO.update()\n\n VIDEO.clock.tick(30)\n\nVIDEO.quit()\n\n# AUDIOPATH = os.path.join(MAINPATH, \"resources\", \"sounds\")\n#\n# AUDIO = audio.Audio(AUDIOPATH)\n#\n# sound = audio.Sound(AUDIO, \"killers\")\n# sound.play()\n# print(sound.length)\n# time.sleep(3)\n# sound.setvolume(0.2)\n# print(sound.volume)\n# time.sleep(3)\n# sound.stop(2)\n# print('fading')\n#\n# time.sleep(5)\n#\n# AUDIO.quit()\n","sub_path":"core/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"305284996","text":"from datetime import timedelta, datetime\nfrom celery.schedules import crontab\nfrom django.contrib.auth.models import User\nfrom django.core.cache import cache\nfrom django.http import HttpResponse\nimport simplejson\nfrom celery.decorators import task, periodic_task\nimport tempfile\nimport zipfile\nimport csv\nfrom couchexport.export import export, Format\nfrom pactcarehq.forms.weekly_schedule_form import hack_pact_usernames\nfrom django.core.mail import send_mail\n\n@task\ndef schema_export(namespace, download_id):\n cache_container = {}\n tmp = tempfile.NamedTemporaryFile(suffix='.xls', delete=False)\n if export(namespace, tmp, format=Format.XLS):\n cache_container['mimetype'] = 'application/vnd.ms-excel'\n cache_container['Content-Disposition'] = 'attachment; filename=%s.xls' % namespace\n cache_container['location'] = tmp.name\n tmp.close()\n else:\n cache_container = {}\n cache_container['mimetype'] = 'text/plain'\n cache_container['location'] = None\n cache_container['message'] = \"No data due to an error generating the file\"\n cache.set(download_id, simplejson.dumps(cache_container), 86400)\n\n\n@task\ndef all_chw_submit_report(total_interval, download_id):\n from pactcarehq.views import _get_schedule_tally\n users = User.objects.all().filter(username__in=hack_pact_usernames)\n all_data = {}\n cache_container = {}\n cache_container['mimetype'] = 'application/zip'\n temp_csv = tempfile.TemporaryFile()\n csv_writer = csv.writer(temp_csv, dialect=csv.excel)\n\n csv_filename = \"chw_schedule_report-%s-%d_days.csv\" % (datetime.utcnow().strftime(\"%Y-%m-%d\"), total_interval)\n csv_keys = ['visit_date','assigned_chw','scheduled_pact_id','is_scheduled','visit_type','submitted_by','visit_id']\n csv_keys = ['visit_date','assigned_chw','pact_id','is_scheduled','contact_type', 'visit_type','visit_kept', 'submitted_by','visit_id']\n csv_writer.writerow(csv_keys)\n\n for user in users:\n username = user.username\n arr, patients, scheduled, visited = _get_schedule_tally(username, total_interval)\n for date, pt_visit in arr:\n if len(pt_visit) > 0:\n for cpt, v in pt_visit:\n rowdata = [date.strftime('%Y-%m-%d'), username, cpt.pact_id]\n if v != None:\n #is scheduled\n if v.form['scheduled'] == 'yes':\n rowdata.append('scheduled')\n else:\n rowdata.append('unscheduled')\n #contact_type\n rowdata.append(v.form['contact_type'])\n\n #visit type\n rowdata.append(v.form['visit_type'])\n\n #visit kept\n rowdata.append(v.form['visit_kept'])\n\n rowdata.append(v.form['Meta']['username'])\n if v.form['Meta']['username'] == username:\n rowdata.append('assigned')\n else:\n rowdata.append('covered')\n rowdata.append(v.get_id)\n else:\n rowdata.append('novisit')\n csv_writer.writerow(rowdata)\n else:\n #csvdata.append(','.join([date.strftime('%Y-%m-%d'),'nopatients']))\n csv_writer.writerow([date.strftime('%Y-%m-%d'), username,'nopatients'])\n temp_csv.seek(0)\n temp_zip = tempfile.NamedTemporaryFile(suffix='.zip', delete=False)\n\n cache_container['location'] = temp_zip.name\n cache_container['Content-Disposition'] = 'attachment; filename=%s.zip' % (csv_filename)\n\n zip_file = zipfile.ZipFile(temp_zip, 'w', zipfile.ZIP_DEFLATED)\n zip_file.writestr(csv_filename, temp_csv.read())\n temp_csv.close()\n\n zip_file.close()\n temp_zip.close()\n cache.set(download_id, simplejson.dumps(cache_container), 86400)\n\n\n\nhack_chw_username_phones = {\n 'ss524': '6178168512@vtext.com',\n 'lm723': '6175434561@vtext.com',\n 'an907': '6178941127@vtext.com',\n 'lnb9': '6178944627@vtext.com',\n 'ma651': '6176509230@vtext.com',\n 'ac381': '6179218161@vtext.com',\n 'cs783': '6178168506@vtext.com',\n 'ao970': '6178168507@vtext.com',\n 'nc903': '6173788671@vtext.com',\n 'isaac': '6174597765@vtext.com',\n 'clare': '6175298471@vtext.com',\n}\n\n@periodic_task(run_every=crontab(minute=30, hour=15))\n#@periodic_task(run_every=crontab(hour=\"*\", minute=\"*\", day_of_week=\"*\"))\ndef schedule_coverage_tally_report():\n \"\"\"scheduled tally for all CHWs sms'ed via email\"\"\"\n from pactcarehq.views import _get_schedule_tally\n #for each CHW\n #do a single date query for dateitme.today(), get the num actual vs. expected\n #ping chw with text message\n #then append to email message to clare\n\n users = sorted(filter(lambda x: x.username.count(\"_\") == 0, User.objects.all().filter(is_active=True)), key=lambda x: x.username)\n total_interval = 1\n scheduled = []\n unscheduled = []\n subject = \"CHW consolidated submission report for %s\" % (datetime.now().strftime(\"%A %B %d, %Y, %I:%M%p\"))\n for user in users:\n ret, patients, total_scheduled, total_visited= _get_schedule_tally(user.username, total_interval)\n if total_scheduled > 0:\n scheduled.append(\"%s: %d/%d\" % (user.username, total_visited, total_scheduled))\n else:\n unscheduled.append(user.username)\n\n\n body = '\\n'.join([subject, '', 'Scheduled Today:\\n', '\\n'.join(scheduled), '\\nNot Scheduled Today:\\n', '\\n'.join(unscheduled)])\n send_mail(subject, body, 'notifications@dimagi.com', ['dmyung@dimagi.com', 'CMCBEE@partners.org'], fail_silently=False)\n\n\n@periodic_task(run_every=crontab(minute=00, hour=15))\ndef schedule_coverage_tally_report_sms():\n \"\"\"scheduled tally for all CHWs sms'ed via SMS email\"\"\"\n from pactcarehq.views import _get_schedule_tally\n #for each CHW\n #do a single date query for dateitme.today(), get the num actual vs. expected\n #ping chw with text message\n #then append to email message to clare\n\n users = sorted(filter(lambda x: x.username.count(\"_\") == 0, User.objects.all().filter(is_active=True)), key=lambda x: x.username)\n total_interval = 1\n scheduled = []\n unscheduled = []\n for user in users:\n if user.username.lower() in hack_chw_username_phones:\n ret, patients, total_scheduled, total_visited= _get_schedule_tally(user.username, total_interval)\n if total_scheduled > 0:\n if total_visited == total_scheduled:\n message_text = \"You have submitted data for all %d of your patients today, great!\" % (total_scheduled)\n else:\n message_text = \"Today you have submitted %d of your %d scheduled patient visits.\" % (total_visited, total_scheduled)\n message_text += \" To see your full schedule visit https://pact.dimagi.com/schedules/chw/%s\" % (user.username.lower())\n send_mail('', message_text, 'notifications@dimagi.com', [hack_chw_username_phones[user.username.lower()]], fail_silently=False)\n\n","sub_path":"pact_apps/pactcarehq/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"517676544","text":"import os\nimport time\nimport tvm\nimport numpy as np\nimport math\nfrom collections import namedtuple\nfrom tvm.contrib import ndk\nfrom tvm import rpc\n\n\nclass Config(namedtuple(\"Config\", (\"op_config_lst\", \"graph_config\"))):\n pass\n\n\nclass RpcInfo(object):\n def __init__(self, host, port, target_host=None, device_key=\"\", use_rpc=None, fcompile=None, sess_timeout=0):\n self.host = host\n self.port = port\n self.target_host = target_host\n self.device_key = device_key\n self.use_rpc = use_rpc\n self.fcompile = ndk.create_shared if fcompile == \"ndk\" else None\n self.sess_timeout = sess_timeout\n\n def get_remote(self):\n remote = None\n if self.use_rpc == \"tracker\":\n tracker = rpc.connect_tracker(self.host, self.port)\n if (self.device_key.find(\"android\") == 0):\n cmds = [\n \"adb reverse tcp:9190 tcp:9190\",\n \"adb forward tcp:5001 tcp:5001\",\n \"adb shell am start -n org.apache.tvm.tvmrpc/org.apache.tvm.tvmrpc.MainActivity 1> /dev/null 2> /dev/null\",\n ]\n os.system(\"; \".join(cmds))\n remote = tracker.request(self.device_key, session_timeout=self.sess_timeout)\n elif self.use_rpc == \"server\":\n remote = rpc.connect(self.host, self.port, session_timeout=self.sess_timeout)\n return remote\n\n\ndef to_int(expr):\n try:\n res = int(expr)\n except Exception as e:\n raise RuntimeError(\"fail to convert to int: %s\" % str(e))\n return res\n\n\ndef to_tuple(expr_tuple):\n return tuple([to_int(x) for x in expr_tuple])\n\n\ndef int_to_lst(value, bit=32, base=10):\n assert isinstance(value, int)\n ret = [0] * bit\n cur = 0\n if value < 0:\n f = -1\n value = -value\n else:\n f = 1\n while value != 0:\n r = value % base\n value = value // base\n ret[cur] = r * f\n cur += 1\n return ret\n\n\ndef powerx_lst(x, left, right):\n ret = []\n beg = 1\n while beg < left:\n beg *= x\n while beg < right:\n ret.append(beg)\n beg = beg * x\n return ret\n\n\ndef get_factor_lst(value):\n assert isinstance(value, int)\n ret = []\n end = math.sqrt(value)\n for i in range(1, math.ceil(end)):\n if value % i == 0:\n ret.append(i)\n ret.append(value // i)\n if end - int(end) < 1e-10 and value % int(end) == 0:\n ret.append(int(end))\n\n return ret\n\n\ndef split_part_names(original, parts):\n assert isinstance(original, str) and isinstance(parts, int)\n return [original + \".\" + str(i) for i in range(parts)]\n\n\ndef str_to_tuple(s):\n assert isinstance(s, str)\n return tuple(int(x) for x in s.strip()[1:-1].split(\",\"))\n\n\ndef any_factor_split(value, number, allow_non_divisible='off'):\n assert allow_non_divisible in ['off', 'power2', 'continuous']\n ret = []\n assert_print(isinstance(number, int))\n recursive_factor_split(value, [], number, ret, allow_non_divisible)\n return ret\n\n\ndef recursive_factor_split(left, cur, number, ret, policy):\n if number == 1:\n ret.append(cur + [left])\n return\n if policy == 'power2':\n f_lst = get_factor_lst(left)\n f_lst.extend(powerx_lst(2, 1, left))\n f_lst = list(set(f_lst))\n elif policy == 'continuous':\n f_lst = list(range(1, left + 1))\n else:\n f_lst = get_factor_lst(left)\n f_lst = sorted(f_lst)\n for f in f_lst:\n recursive_factor_split(left // f, cur + [f], number - 1, ret, policy)\n\n\ndef three_factor_split(value):\n assert isinstance(value, int)\n ret = []\n for i in range(1, value + 1):\n if value % i == 0:\n res = value // i\n factor_lst = get_factor_lst(res)\n for factor in factor_lst:\n ret.append((i, factor, res // factor))\n return ret\n\n\ndef two_factor_split(value):\n assert isinstance(value, int)\n ret = []\n for i in range(1, value + 1):\n if value % i == 0:\n ret.append((i, value // i))\n return ret\n\n\ndef dev(input):\n import torch\n m = torch.mean(input, dim=-1)\n return torch.pow(torch.sum(torch.pow(input - m, 2)), 0.5)\n\n\ndef _dfs_interleave(cur, la, lb, pa, pb, enda, endb, res):\n tmp = []\n if pa == enda:\n while pb != endb:\n tmp.append(lb[pb])\n pb += 1\n res.append(cur + tmp)\n return\n if pb == endb:\n while pa != enda:\n tmp.append(la[pa])\n pa += 1\n res.append(cur + tmp)\n return\n _dfs_interleave(cur + [la[pa]], la, lb, pa + 1, pb, enda, endb, res)\n _dfs_interleave(cur + [lb[pb]], la, lb, pa, pb + 1, enda, endb, res)\n return\n\n\ndef interleave(la, lb):\n res = []\n _dfs_interleave([], la, lb, 0, 0, len(la), len(lb), res)\n return res\n\n\ndef permute(lst):\n from itertools import permutations\n return [list(x) for x in permutations(lst, len(lst))]\n\n\ndef gumbel_softmax(logits):\n import torch\n from torch.autograd import Variable\n epsilon = 1e-20\n G = torch.rand_like(logits)\n y = logits + -Variable(torch.log(-torch.log(G + epsilon) + epsilon))\n soft_y = torch.softmax(y, dim=-1)\n _, index = soft_y.max(dim=-1)\n hard_y = torch.zeros_like(soft_y).view(-1, soft_y.shape[-1])\n hard_y.scatter_(1, index.view(-1, 1), 1)\n hard_y = hard_y.view(*soft_y.shape)\n return soft_y + (hard_y - soft_y).detach()\n\n\ndef parted_linear(x, left, right):\n import torch\n if left > right:\n left, right = right, left\n return torch.relu(right - torch.relu(right - x) - left) + left\n\n\ndef _dfs_gen_enum(cur, cur_len, elements, length, res):\n if cur_len == length:\n res.append(cur)\n return\n for ele in elements:\n _dfs_gen_enum(cur + [ele], cur_len + 1, elements, length, res)\n return\n\n\ndef gen_enum(elements, length):\n res = []\n _dfs_gen_enum([], 0, elements, length, res)\n return res\n\n\ndef _dfs_gen_group(cur, elements, p, length, left_groups, res, padding):\n if left_groups == 1:\n res.append(cur + [length] * (1 + padding))\n elif left_groups > 1:\n # _dfs_gen_group(cur, elements, p, length, left_groups-1, res)\n for i in range(p + 1, length):\n _dfs_gen_group(cur + [i], elements, i, length, left_groups - 1, res, padding)\n else:\n raise RuntimeError(\"At least 1 group\")\n\n\ndef gen_group(elements, most_groups=3):\n res = []\n length = len(elements)\n lower = min(length, most_groups)\n upper = min(length, most_groups)\n for groups in range(lower, upper + 1):\n _dfs_gen_group([], elements, 0, length, groups, res, most_groups - groups)\n return res\n\n\ndef fact(n):\n acc = 1\n while n > 0:\n acc, n = acc * n, n - 1\n return acc\n\n\ndef comb(m, n):\n assert m >= n\n return fact(m) // (fact(n) * fact(m - n))\n\n\ndef is_power_of_x(x, val):\n assert isinstance(val, int) and val > 0\n return math.fabs(math.pow(x, int(math.log(val, x))) - val) < 1e-20\n\n\ndef nearest_power_of_two(val):\n assert isinstance(val, int) and val > 0\n return int(math.pow(2, int(math.log2(val))))\n\n\ndef test_allclose(value, target, rtol=1e-5, print_diff=False):\n passed = 1\n from tvm.testing import assert_allclose\n try:\n assert_allclose(value, target, rtol)\n except AssertionError:\n passed = 0\n if print_diff:\n print(target - value)\n print(\"Max diff:\", np.max(np.fabs(target - value)))\n return passed\n\n\ndef assert_print(bool_stmt, false_str=\"\"):\n if not bool_stmt:\n raise AssertionError(false_str)\n\n\ndef free_cuda():\n import torch\n ret = []\n if torch.cuda.is_available():\n filename = \"flextensor_check_cuda_free_memory_{}\".format(time.time())\n os.system(\"nvidia-smi -q -d Memory | grep -A4 GPU | grep Free > {}\".format(filename))\n memory_gpu = list(\n filter(lambda x: x[0] > 0,\n [(int(x.split()[2]), i) for i, x in enumerate(open(filename, 'r').readlines())]))\n memory_gpu = sorted(memory_gpu, key=lambda x: x[0], reverse=True)\n os.remove(filename)\n return [x[1] for x in memory_gpu]\n return ret\n\n\ndef test_three_factor_split():\n values = [16, 256, 512, 24, 3, 1024, 2048, 4096]\n for v in values:\n print(len(three_factor_split(v)))\n\n\ndef test_interleave():\n la = [\"none\", \"rx\", \"ry\", \"rc\"]\n lb = [\"bi\", \"hi\", \"wi\", \"ci\"]\n res = interleave(la, lb)\n print(\"length={}\".format(len(res)))\n for ele in res:\n print(ele)\n\n\ndef test_permute():\n lst = [\"b\", \"k\", \"x\", \"y\"]\n res = permute(lst)\n print(\"length={}\".format(len(res)))\n for ele in res:\n print(ele)\n\n\ndef test_gen_enum():\n elements = [True, False]\n length = 4\n res = gen_enum(elements, length)\n print(\"length={}\".format(len(res)))\n for ele in res:\n print(ele)\n\n\ndef test_gen_group():\n elements = ['x', 'y', 'z', 'w']\n res = gen_group(elements)\n print(\"length={}\".format(len(res)))\n for ele in res:\n print(ele)\n\n\ndef test_any_factor_split():\n ret = any_factor_split(448, 4, 'power2')\n print(ret)\n print(\"length=\", len(ret))\n\n\nif __name__ == \"__main__\":\n test_any_factor_split()\n","sub_path":"flextensor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"511661723","text":"from model import common\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nimport pdb\n\n\ndef make_model(args, parent=False):\n return KPRCN(args)\n\nclass KPRCN(nn.Module):\n def __init__(self, args, conv=common.default_conv):\n super(KPRCN, self).__init__()\n n_resgroups = args.n_resgroups\n n_resblocks = args.n_resblocks\n n_feats = args.nc_feats\n kernel_size = args.kernel_size\n reduction = args.reduction\n self.nalu = args.nalu \n act = nn.ReLU(True)\n \n # define head module\n modules_head = [conv(args.nc_input, args.nc_feats, args.kernel_size),\n\t\t\tnn.ReLU()\n ]\n\n # define body module\n modules_body = [\n common.ResBlock(\n conv, n_feats, kernel_size, act=act, res_scale=args.res_scale\n ) for _ in range(n_resblocks-2)\n ]\n modules_body.append(conv(n_feats, n_feats, kernel_size))\n\n self.nc_output = 3 if args.prediction == 'DP' else args.recon_kernel_size**2\n \n # define tail module\n modules_tail = [conv(args.nc_feats, self.nc_output, args.kernel_size)]\n\n self.head = nn.Sequential(*modules_head)\n self.body = nn.Sequential(*modules_body)\n self.tail = nn.Sequential(*modules_tail)\n\n\n def forward(self, x):\n # x = self.sub_mean(x)\n x = self.head(x)\n\n res = self.body(x)\n if self.nalu:\n conv_W = F.conv2d(res, self.W, padding=1)\n conv_M = F.conv2d(res, self.M, padding=1)\n res = self.sig(conv_M) * self.tan(conv_W)\n \n # res += x\n\n x = self.tail(res)\n \n # x = self.add_mean(x)\n\n return x \n \n def forward_debug(self, x):\n x = self.sub_mean(x)\n x = self.head(x)\n\n res = self.body(x)\n\n def load_state_dict(self, state_dict, strict=True):\n own_state = self.state_dict()\n for name, param in state_dict.items():\n if name in own_state:\n if isinstance(param, nn.Parameter):\n param = param.data\n try:\n own_state[name].copy_(param)\n except Exception:\n if name.find('tail') == -1:\n raise RuntimeError('While copying the parameter named {}, '\n 'whose dimensions in the model are {} and '\n 'whose dimensions in the checkpoint are {}.'\n .format(name, own_state[name].size(), param.size()))\n elif strict:\n if name.find('tail') == -1:\n raise KeyError('unexpected key \"{}\" in state_dict'\n .format(name))\n\n","sub_path":"navi/model/kprcn.py","file_name":"kprcn.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"640383291","text":"import numpy as np\nimport tensorflow as tf\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport os\n\ndef get_data_file(base_dir):\n data_path = os.path.join(base_dir, 'datasets', 'test_datasets.npy')\n data = np.load(data_path)\n img_paths = data[:50, :1]\n captions = data[:50, 2:]\n train_images = np.squeeze(img_paths, axis=1)\n train_images = [os.path.join(base_dir, 'datasets', 'images', img) for img in train_images]\n train_captions = np.squeeze(captions, axis=1)\n train_captions = ['' + cap + ' ' for cap in train_captions]\n train_images = list(set(train_images)) # 테스트를 위한 중복제거\n print(train_images[:3])\n print(train_captions[:3])\n return train_images, train_captions\n\n\ndef image_load(image_path):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_jpeg(img, channels=3)\n img = tf.image.resize(img, (255, 255))\n return img, image_path\n\n\n# numpy 사용, 찬우 코드\ndef img_normalization_1(image_path):\n img = Image.open(image_path)\n img = img.resize((255, 255))\n img2 = np.array(img)\n min_max_image = (img - np.min(img)) / (np.max(img) - np.min(img))\n mean_std_image = (img-img2.mean(axis=(0,1,2),keepdims=True))/np.std(img,axis=(0,1,2),keepdims=True)\n return [img, min_max_image, mean_std_image]\n\n\n# tensorflow 사용, 솔지 코드\ndef img_normalization_2(img):\n # tf_img = tf.constant(img, dtype=tf.float32)\n mean, var = tf.nn.moments(img, axes=[0, 1, 2])\n nn_moments_image = (img - mean) / var**0.5\n image_standardization_image = tf.image.per_image_standardization(img)\n return [nn_moments_image, image_standardization_image]\n\n\nbase_dir = os.path.abspath('.')\ntrain_images, train_captions = get_data_file(base_dir)\n\n\ntrain_images = train_images[:2]\nfor train_image in train_images:\n img, image_path = image_load(train_image)\n images1 = img_normalization_1(image_path)\n images2 = img_normalization_2(img)\n titles = ['origin_img', 'min_max_image', 'mean_std_image', 'nn_moments_image', 'image_standardization_image']\n images = images1 + images2\n f = plt.figure()\n for i, image in enumerate(images):\n f.add_subplot(2, 3, i+1)\n plt.title(titles[i])\n plt.imshow(image)\n plt.show()","sub_path":"doc/img_normalization_test.py","file_name":"img_normalization_test.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"93644131","text":"limit=12000\n# Algo here https://en.wikipedia.org/wiki/Farey_sequence#Next_term\n# a/b and c/d are adjacent if and only if bc-ad = 1, this is true for 1/3 and 4000/11999\na,b,c,d,=1,3,4000,11999\nresult = 0\n\nwhile not (c==1 and d==2):\n result +=1 \n k = (limit+b)//d\n e = k*c-a\n f = k*d-b\n a=c\n b=d\n c=e\n d=f\n\nprint(result)","sub_path":"countingFractionsInARangePE73.py","file_name":"countingFractionsInARangePE73.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87123568","text":"import sys\n__author__ = 'gambrinius'\n\n\ndef all_combinations(S, combinations):\n \"\"\"\n The function find all combinations(string patterns)\n for input string.\n :param S:\n :param combinations:\n :return: modified input list (add combinations)\n \"\"\"\n if len(S) < 1:\n return 0\n\n j = int()\n for j in range(len(S)):\n combinations.append(S[0: j + 1])\n\n all_combinations(S[1: j+1], combinations)\n\n\ndef count_overlapping_substrings(string, substring):\n \"\"\"\n The function counts the number of occurrences\n of a substring in a string.\n :param string:\n :param substring:\n :return: count\n \"\"\"\n count = 0\n i = -1\n while True:\n i = string.find(substring, i+1)\n if i == -1:\n return count\n count += 1\n\n\ndef sort_by_length(string):\n \"\"\"\n The function sorts the list by string length.\n :param string:\n :return: length of string\n \"\"\"\n return len(string)\n\n\ndef string_patterns(S):\n \"\"\"\n The main function, finding string patterns.\n :param S:\n :return: list of unique combinations\n \"\"\"\n array = list() # list for storing all combinations\n all_combinations(S, array) # find all combinations for string\n unique_combinations = list() # list for storing result combinations\n\n for element in set(array): # delete repeat combinations and single characters\n if len(element) != 1 and count_overlapping_substrings(S, element) >= 2: # check conditions\n unique_combinations.append(element)\n unique_combinations.sort(key=sort_by_length, reverse=True)\n\n if len(unique_combinations) != 0:\n return unique_combinations\n else:\n return None\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n try:\n input_file = open(sys.argv[1], 'r')\n test_cases = input_file.readlines()\n\n for test in test_cases:\n print(string_patterns(test))\n print(\"-----\")\n input_file.close()\n except IOError:\n print('Can\\'t open this file', sys.argv[1])\n else:\n print(\"Missed argument - name of text file\")\n","sub_path":"StringPatterns.py","file_name":"StringPatterns.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"320705602","text":"#!/usr/bin/env python3\n\"\"\"\nSimple template rendering a number of molecules originating from PDB files.\n\nIt also demonstrates the usage of different configuration files to influence\nthe rendering (use -h to see how).\n\nUses a number of pre-defined Povray objects to simplify scene building\n\"\"\"\n\n__author__ = \"Marcel Kempenaar\"\n__status__ = \"Template\"\n__version__ = \"2017.3\"\n\nimport sys\nimport math\nimport argparse\nfrom pypovray import pypovray, pdb, load_config, models, logger\nfrom vapory import Scene, LightSource\n\n# This program uses globals as the `scene` function requires them at each step\nETHANOL = VIAGRA = BENZENE = RAD_PER_SCENE = FRONT_LIGHT = None\n\n\ndef scene_objects():\n \"\"\" Creates molecule objects and any other pre-calculated data \"\"\"\n global ETHANOL, VIAGRA, BENZENE, RAD_PER_SCENE, FRONT_LIGHT\n\n FRONT_LIGHT = LightSource([0, 14, -28], 'color', [1, 0.8, 0.4],\n 'fade_distance', 6, 'fade_power', 2,\n 'area_light', 3, 3, 12, 12,\n 'circular orient adaptive', 0)\n\n # Calculate the radians per scene\n RAD_PER_SCENE = (math.pi / 180) * 3\n\n # Read in a PDB file and construct a molecule\n ETHANOL = pdb.PDBMolecule('pdb/ethanol.pdb', center=False, offset=[-10, 8, -5])\n VIAGRA = pdb.PDBMolecule('pdb/viagra.pdb', center=False, offset=[3, -3, -7])\n BENZENE = pdb.PDBMolecule('pdb/benzene.pdb', center=False, offset=[0, 8, -5])\n\n\ndef frame(step):\n \"\"\" Returns the scene at step number (1 step per frame) \"\"\"\n\n # Rotate the molecules updating its orientation (a persistent modification)\n ETHANOL.rotate([1, 1, 0], RAD_PER_SCENE)\n VIAGRA.rotate([1, 0, 1], RAD_PER_SCENE)\n BENZENE.rotate([0, 1, 1], RAD_PER_SCENE)\n\n # Combine molecule objects (an object.povray_molecule is a list of atoms, they need\n # to be concatenated to be added to the scene)\n molecules = ETHANOL.povray_molecule + VIAGRA.povray_molecule + BENZENE.povray_molecule\n\n logger.info(' @Step: %s', step)\n # Return a 'Scene' object containing -all- objects to render, i.e. the camera,\n # light(s) and in this case, molecules too.\n return Scene(models.default_camera,\n objects=[models.default_light, FRONT_LIGHT] + molecules,\n included=['colors.inc'])\n\n\ndef main(args):\n \"\"\" Runs the simulation \"\"\"\n\n # Load a user defined configuration file\n if args.config:\n pypovray.SETTINGS = load_config(args.config)\n if args.frame:\n # Create objects for the scene (i.e. parse PDB files)\n scene_objects()\n # User entered the specific frame to render\n pypovray.render_scene_to_png(frame, args.frame)\n else:\n # No output file type and no specific frame, exit\n if not args.gif and not args.mp4:\n parser.print_help()\n sys.exit('\\nPlease specify either a specific frame number or ' +\n 'output format for a movie file')\n else:\n # Create objects for the scene (i.e. parse PDB files)\n scene_objects()\n # Render a movie, depending on output type selected (both files is possible)\n if args.gif:\n pypovray.render_scene_to_gif(frame)\n if args.mp4:\n pypovray.render_scene_to_mp4(frame)\n return 0\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Render PDB files using Python and Povray')\n parser.add_argument('--config', help='Load a configuration file containing pypovray settings')\n parser.add_argument('--frame', type=int,\n help='A specific frame (number) to render ' +\n '(single image output file)')\n parser.add_argument('--gif', action=\"store_true\", default=False,\n help='Create a GIF movie file using moviepy. ' +\n 'Note; this reduces the output quality')\n parser.add_argument('--mp4', action=\"store_true\", default=False,\n help='Create a high-quality MP4 output file using ffmpeg')\n\n pargs = parser.parse_args()\n\n sys.exit(main(pargs))\n","sub_path":"template_pdb.py","file_name":"template_pdb.py","file_ext":"py","file_size_in_byte":4110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"430171579","text":"import json\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import HttpResponse, render_to_response\nfrom pandas import DataFrame\nimport numpy\n\nfrom finance.models import Transaction\n\n\n@login_required\ndef stats(request):\n stats_by = request.GET.get('by', 'category')\n\n trx = Transaction.objects.filter(amount__lt=0).exclude(category__name='Credit Card Payments')\n original_df = DataFrame(data=[{k: getattr(t, k) for k in ('date', 'category', 'amount')} for t in trx])\n\n df = original_df.set_index('date').groupby('category').resample('M', how='sum')\n\n chart_df = df.reset_index()\\\n .pivot_table(values='amount', index=['date'], columns=['category'], aggfunc=numpy.sum)\\\n .replace(numpy.NaN, 0)\n\n months = [x.strftime('%Y-%m-%d') for x in chart_df.index]\n chart_series = [\n {'name': category, 'type': 'column', 'data': [abs(float(a)) for a in amounts]}\n for category,amounts in chart_df.iteritems()]\n\n table_df = df.reset_index()\\\n .pivot_table(values='amount', index=['category'], columns=['date'], aggfunc=numpy.sum)\\\n .replace(numpy.NaN, 0)#.reset_index()\n table_data = [(category, list(amounts)) for category,amounts in chart_df.iteritems()]\n total_df = original_df.set_index('date').resample('M', how='sum').transpose()\n table_data.append(('Total', total_df.values[0]))\n\n return render_to_response('transactions/stats.html', {\n 'months_json': json.dumps(months),\n 'chart_series_json': json.dumps(chart_series),\n 'chart_df': chart_df,\n 'months': months,\n 'table_data': table_data,\n })\n","sub_path":"finance/views/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"486368295","text":"from contextlib import suppress\n\nfrom mongoengine.base.datastructures import BaseDict\nimport graphene\nfrom graphene.relay import Node\nfrom graphene_mongo import MongoengineObjectType\nfrom graphene.types.generic import GenericScalar\nfrom common.utils import find_users, count_users\nfrom levels.models import (\n LevelModel, BalanceModel, HostModel, PowerModel, \n)\nfrom market.models import (\n SpiralModel\n)\nfrom badges.models import (BadgeModel)\nfrom common.utils import prepare_json\nfrom common.types import GeometryObjectType\nfrom common.fields import CustomMongoengineConnectionField\nfrom pprint import pprint\n\n\nclass Power(MongoengineObjectType):\n # powers = graphene.List('levels.types.Power',\n # blockchain=graphene.String(required=True),\n # host = graphene.String(required=True),\n # first=graphene.Int(),\n # last=graphene.Int())\n \n # def resolve_powers(self, info, blockchain, host):\n \n # qs = PowerModel.objects(blockchain=blockchain, username = self.username, host=host)\n # return qs;\n badges = graphene.List('badges.types.Badge', first=graphene.Int(),\n last=graphene.Int(), \n )\n\n json_metadata = GenericScalar()\n\n avatar = graphene.String()\n\n\n\n def resolve_avatar(self, info):\n user = LevelModel.objects(username=self.author, blockchain = self.blockchain).first()\n if (user):\n meta = prepare_json(user.meta)\n else: \n meta = {}\n \n if 'img' in meta:\n return meta['img']\n else:\n return \"/ava.png\" \n\n\n def resolve_json_metadata(self, info):\n User = LevelModel.objects(username = self.username, blockchain = self.blockchain).first()\n \n return prepare_json(User.meta)\n\n # if isinstance(self.meta, BaseDict):\n # return prepare_json(self.meta)\n # else: \n # return {}\n \n\n def resolve_badges(self, info):\n \n qs = BadgeModel.objects(blockchain = self.blockchain, username = self.username)\n #TODO find badges and construct\n return qs;\n\n class Meta:\n model = PowerModel\n interfaces = (Node, )\n\n\n \n \n\nclass Balance(MongoengineObjectType):\n\n\n\n class Meta:\n model = BalanceModel\n interfaces = (Node, )\n\n\nclass Host(MongoengineObjectType):\n\n totalgrowth = graphene.Float()\n roundgrowth = graphene.Float()\n risk = graphene.Float()\n\n def resolve_roundgrowth(self, info):\n spiral = SpiralModel.objects(host=self.username, ahost=self.username).first()\n growth = spiral.overlap / 100 - 100 \n growth = round(growth, 2) \n return growth\n\n\n\n def resolve_totalgrowth(self, info):\n spiral = SpiralModel.objects(host=self.username, ahost=self.username).first()\n growth = spiral.overlap / 100 - 100 \n\n totalgrowth = spiral.pool_limit * growth / 2\n totalgrowth = round(totalgrowth, 2)\n return totalgrowth\n\n def resolve_risk(self, info):\n spiral = SpiralModel.objects(host = self.username, ahost=self.username).first()\n risk = spiral.loss_percent / 10000 * 100 \n risk = round(risk, 2)\n\n return risk\n\n\n class Meta:\n model= HostModel\n interfaces = (Node, )\n\nclass Level(MongoengineObjectType):\n\n levels = graphene.List('levels.types.Level',\n blockchain=graphene.String(required=True),\n first=graphene.Int(),\n last=graphene.Int())\n\n balances = graphene.List('levels.types.Balance',\n blockchain=graphene.String(required=True),\n host = graphene.String(required=True))\n\n powers = graphene.List('levels.types.Power',\n blockchain=graphene.String(required=True),\n host = graphene.String(required=True),\n first=graphene.Int(),\n last=graphene.Int())\n\n badges = graphene.List('badges.types.Badge', first=graphene.Int(),\n last=graphene.Int(), \n )\n\n\n exp_summ_black = graphene.Float(blockchain=graphene.String(required=True),host=graphene.String(required=True), level = graphene.Int(required=True))\n exp_summ_white = graphene.Float(blockchain=graphene.String(required=True),host=graphene.String(required=True), level = graphene.Int(required=True))\n\n total_recieved = graphene.Float(blockchain=graphene.String(required=True),host=graphene.String(required=True), level = graphene.Int(required=True))\n \n info = GenericScalar()\n avatar = graphene.String()\n count = graphene.Int()\n\n gdp = graphene.Float()\n \n nickname = graphene.String()\n\n def resolve_nickname(self, info):\n user = LevelModel.objects(username=self.username, blockchain = self.blockchain).first()\n if (user):\n meta = prepare_json(user.meta)\n else:\n meta = {}\n \n \n if 'nickname' in meta:\n return meta['nickname']\n else:\n return \"\" \n\n\n # rec_summ_black = graphene.Float(host=graphene.String(), level = graphene.Int())\n # rec_summ_white = graphene.Float(host=graphene.String(), level = graphene.Int())\n\n # def resolve_gdp(self, info, host):\n \n def resolve_badges(self, info):\n \n qs = BadgeModel.objects(blockchain = self.blockchain, username = self.username)\n #TODO find badges and construct\n return qs;\n\n\n def resolve_powers(self, info, blockchain, host):\n qs = PowerModel.objects(blockchain=blockchain, username = self.username, host=host)\n return qs;\n\n def resolve_count(self, info):\n return 1\n \n def resolve_info(self, info):\n # if isinstance(self.meta, BaseDict):\n return prepare_json(self.meta)\n # else: \n # return {}\n\n def resolve_avatar(self, info):\n info = prepare_json(self.meta)\n if 'img' in info:\n return info['img']\n else:\n return \"\"\n\n def resolve_exp_summ_black(self, info, blockchain, host, level):\n print(\"blockchain: \", self.blockchain)\n\n balance = BalanceModel.objects(username = self.username, blockchain=blockchain, host = host, pool_color = \"black\", withdrawed = False)\n summ = 0\n host = HostModel.objects(username = host)\n lev = host[0]['levels'][level - 1]\n \n for bal in balance:\n spl = bal.ref_amount.split(\" \")\n summ = summ + float(spl[0]) * lev / 1000000\n summ = round(summ,8);\n\n return summ\n\n def resolve_exp_summ_white(self, info, blockchain, host, level):\n print(\"blockchain:\", self.blockchain)\n balance = BalanceModel.objects(username = self.username, blockchain = blockchain, host = host, pool_color = \"white\", withdrawed = False)\n summ = 0\n host = HostModel.objects(username = host)\n lev = host[0]['levels'][level - 1]\n\n for bal in balance:\n spl = bal.ref_amount.split(\" \")\n summ = summ + float(spl[0]) * lev / 1000000\n summ = round(summ,8);\n print(summ)\n return summ\n \n\n def resolve_total_recieved(self, info, blockchain, host, level):\n print(\"username\", self.username)\n print(\"blockchain\", blockchain)\n print('host', host)\n\n balance = BalanceModel.objects(username = self.username, blockchain = blockchain, host = host, win = True, withdrawed = True)\n print(balance)\n summ = 0\n host = HostModel.objects(username = host)\n lev = host[0]['levels'][level - 1]\n\n for bal in balance:\n spl = bal.ref_amount.split(\" \")\n summ = summ + float(spl[0]) * lev / 1000000\n summ = round(summ,8);\n print(summ)\n return summ\n\n\n # def resolve_lev(self, info, first=None, last=None):\n # # print(self.username)\n # # print(parent)\n # # lev = get_level(self)\n # if hasattr(self, 'lev'):\n # return self.lev + 1\n # else:\n # return 1\n\n # level = CustomMongoengineConnectionField(Level)\n\n def resolve_levels(self, info, blockchain, first=None, last=None):\n # TODO Написать простой пагинатор для комментов\n username = find_users(self, blockchain)\n\n return username\n \n def resolve_balances(self, info, host):\n\n balance = BalanceModel.objects(username = self.username, host = host)\n # for i, bal in enumerate(balance):\n # print(i)\n # spl = bal.ref_amount.split(\" \")\n # balance[i] = float(spl[0])\n\n return balance\n \n \n\n class Meta:\n model = LevelModel\n interfaces = (Node, )\n\n ","sub_path":"levels/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":8995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579313570","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.8 (3413)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\yuuta\\YCU-Programing\\Code_Review\\ura_1\\django_press\\templatetags\\nav.py\n# Compiled at: 2020-01-08 02:37:40\n# Size of source mod 2**32: 380 bytes\nfrom django import template\nfrom django_press.models import Page\nregister = template.Library()\n\n@register.inclusion_tag('django_press/nav/main.html', takes_context=True)\ndef nav(context, core, **kwargs):\n nav_pages = Page.objects.filter(in_nav=True, publish=True).all()\n return {**{'nav_pages':nav_pages, \n 'core':core}, **kwargs}","sub_path":"pycfiles/django_press-0.1.13-py3-none-any/nav.cpython-38.py","file_name":"nav.cpython-38.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"549923088","text":"'''\ntrain and test ConGAE-fc, which uses fully connected layers for spacial info, thus use dataframe instead of graph format for input.\n'''\n\nimport os\nimport torch\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n \nimport argparse\nimport os\nimport sys\nimport random\nimport torch.nn as nn\nfrom torch.utils import data\nfrom torch.nn import functional as F\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D \nfrom random import shuffle\nimport pickle\nimport torchvision.transforms as transforms\nimport time\nfrom torch.utils.data import DataLoader, TensorDataset\nimport math\nfrom sklearn.metrics import roc_curve, auc\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch import Tensor\nfrom importlib import reload\n\n\nfrom model import ConGAE_fc\n\nparser = argparse.ArgumentParser()\n\n# model\nparser.add_argument('--model', default = 'ConGAE_fc', help = 'Model type:ConAE_fc')\n# training parameters\nparser.add_argument('--test', type=bool, default = True, help = 'Directly enter test mode. If False, train the model.')\nparser.add_argument('--randomseed', type=int, default = 1)\nparser.add_argument('--train_epoch', type =int, default = 150 , help = 'number of training epochs')\nparser.add_argument('--lr', default = 5e-5 , help = 'learning rate')\nparser.add_argument('--dropout_p', default = 0.2 , help = 'drop out rate')\nparser.add_argument('--verbal', default = False, type = bool , help = 'print loss during training')\n# 2-layer ConGAE parameters\nparser.add_argument('--hiddem_dim1', type=int, default = 300, help = 'hidden dimension of the first fc layer')\nparser.add_argument('--hiddem_dim2', type=int, default = 150, help = 'hidden dimension of the second fc layer')\nparser.add_argument('--hour_emb', type=int, default = 100, help = 'hour emnbedding dimension')\nparser.add_argument('--week_emb', type=int, default = 100, help = 'week emnbedding dimension')\n\n# files\nparser.add_argument('--log_dir', default = '../log/' , help = 'directory to save model')\n\nargs = parser.parse_args()\nprint(args)\n\n#Reproducability \nnp.random.seed(seed=args.randomseed)\nrandom.seed(args.randomseed)\ntorch.manual_seed(args.randomseed)\n\nresult_dir = args.log_dir + 'results/'\nif not os.path.exists(result_dir):\n os.makedirs(result_dir)\n\ntrain_data = '../data/Q2_transposed.pkl'\n\n\ndirName = '../data/selected_50_orig/' \ntt_min, tt_max =np.load(dirName + 'tt_minmax.npy' )\n\n\ndef fill_na(df):\n '''interpolate NA in dataset'''\n df.interpolate(inplace=True)\n df.bfill(inplace=True)\n df.fillna(df.mean().mean(), inplace=True)\n\ndef missing_rate(df):\n '''calculate missing rate'''\n return df.isnull().sum().sum() / df.shape[0] / df.shape[1]\n\n\ndef select_traing(df):\n # leave out NFL days\n Q1 = df.iloc[:350]\n Q2 = df.iloc[750: ] \n Q = pd.concat([Q1, Q2], axis=0)\n return Q\n\nx_train = pd.read_pickle(train_data )\nx_train = select_traing(x_train)\nfill_na(x_train)\n\n\n'''construct dataset'''\ndata_train = x_train.values\nslices = [data_train[i:i + 1] for i in range(data_train.shape[0])]\nlabels = [(s.weekday(), s.hour) for s in x_train.index.droplevel(0)]\nindices = np.random.permutation(len(slices))\nsplit_point = int(0.1* len(indices))\n\nfeature_dim = slices[0].shape[1]\n\ndataset_train = TensorDataset(Tensor(slices), Tensor(labels))\n\n'''dataloader'''\nbatch_size = 20\ntrain_loader = DataLoader(dataset=dataset_train, batch_size=batch_size, drop_last=True,\n sampler=SubsetRandomSampler(indices[:-split_point]), pin_memory=True)\nval_loader = DataLoader(dataset=dataset_train, batch_size=batch_size, drop_last=True,\n sampler=SubsetRandomSampler(indices[-split_point:]), pin_memory=True)\n\n'''Load model'''\n\nmodel = ConGAE_fc(feature_dim,args.hiddem_dim1,args.hiddem_dim2, args.dropout_p,hour_emb = args.hour_emb, week_emb = args.week_emb)\n\nmodel.float()\n# print(model)\n\n# specify optimizer\noptimizer = torch.optim.Adam(model.parameters(), lr=args.lr)\ncriterion = nn.MSELoss()\n\ndef calc_rmse(recon_adj, adj, tt_min, tt_max):\n adj = adj * (tt_max - tt_min) + tt_min\n recon_adj = recon_adj * (tt_max - tt_min) + tt_min\n rmse = criterion(recon_adj, adj)\n return torch.sqrt(rmse)\n\n\ndef train(epoch, train_loader ,test_loader, best_val, best_epoch, verbal = True):\n model.train()\n train_loss = 0\n loss_train = []\n loss_val = []\n for graph_data in train_loader:\n slice_data = graph_data[0]\n label_data = graph_data[1].long()\n slice_data = slice_data.to(device)\n label_data = label_data.to(device)\n optimizer.zero_grad()\n recon = model(slice_data, label_data[:,1].unsqueeze(1), label_data[:,0].unsqueeze(1))\n loss = criterion(recon, slice_data)\n loss.backward()\n optimizer.step()\n loss_train.append(loss.item())\n for graph_val in val_loader:\n # evaluation\n model.eval()\n slice_data = graph_val[0]\n label_data = graph_val[1].long()\n slice_data = slice_data.to(device)\n label_data = label_data.to(device)\n with torch.no_grad():\n recon_val = model(slice_data,\n label_data[:,1].unsqueeze(1), label_data[:,0].unsqueeze(1))\n mse_val = criterion(recon_val, slice_data)\n loss_val.append(mse_val.item())\n \n loss_train = sum(loss_train) / len(loss_train)\n loss_val = sum(loss_val) / len(loss_val)\n \n # print results\n if args.verbal and epoch % 10 == 0:\n print('Train Epoch: {} loss: {:e} val_loss: {:e}'.format(\n epoch, loss_train, loss_val ))\n rmse = math.sqrt(loss_val) * (tt_max - tt_min) # calc_rmse(recon, graph_data.edge_attr, tt_min, tt_max) \n print('validation travel time rmse mean: {:e}'.format(rmse))\n \n # early-stopping\n if loss_val < best_val:\n torch.save({\n 'epoch' : epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, model_path)\n best_val = loss_val\n best_epoch = epoch\n\n return loss_train, loss_val, best_val, best_epoch\n\n# ## Train\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nloss_track = []\nval_track = []\nmodel_path = args.log_dir + args.model + '.pt'\n\nif not args.test:\n model = model.to(device)\n n_epochs = args.train_epoch\n start = time.time()\n best_epoch = 0\n best_val = float('inf') # for early stopping\n lr_decay_step_size = 50\n\n for epoch in range(1, n_epochs+1):\n train_loss, val_loss, best_val,epoch = train(epoch, train_loader, val_loader, best_val, best_epoch)\n loss_track.append(train_loss)\n val_track.append(val_loss)\n if epoch % lr_decay_step_size == 0:\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.5 * param_group['lr']\n\n print(\"time for {} epochs: {:.3f} min\".format(n_epochs, (time.time() - start)/60))\n\n torch.cuda.empty_cache()\n\n\n # plot learning curve\n plt.plot(np.array(loss_track), label = 'traiing')\n plt.plot(np.array(val_track), label = 'validaiton')\n plt.title(\"loss\")\n plt.xlabel(\"# epoch\")\n plt.ylabel(\"MSE loss\")\n plt.legend()\n # plt.ylim(0.4, 1)\n # plt.show()\n plt.savefig(result_dir + args.model +\"_\"+ '_training_curve.png')\n\n# # ## examinne results\n\n\ncheckpoint = torch.load(model_path)\nmodel.load_state_dict(checkpoint['model_state_dict'])\nepoch = checkpoint['epoch']\n\nmodel = model.to('cpu')\nprint(\"best model is at epoch\", epoch)\n\n# ## test missing sensitivity\n\ndef constr_dataloader(df):\n '''construct dataset given test dataframe'''\n data_train = df.values\n slices = [data_train[i:i + 1] for i in range(data_train.shape[0])]\n labels = df.index\n indices = np.random.permutation(len(slices))\n\n feature_dim = slices[0].shape[1]\n\n dataset_train = TensorDataset(Tensor(slices), Tensor(labels))\n\n '''dataloader'''\n batch_size = 1\n loader = DataLoader(dataset=dataset_train, batch_size=batch_size, drop_last=True,\n pin_memory=True)\n return loader\n\ndef cal_rmse_array(test_loader, model):\n '''# calcualte rmse for every item in test set'''\n model = model.to('cpu')\n rmse = np.zeros(len(test_loader))\n i=0\n for graph_data in test_loader:\n model.eval()\n with torch.no_grad():\n slice_data = graph_data[0]\n label_data = graph_data[1].long()\n slice_data = slice_data\n label_data = label_data\n recon = model(slice_data, label_data[:,1].unsqueeze(1), \n label_data[:,0].unsqueeze(1))\n# loss = criterion(recon, slice_data)\n loss = calc_rmse(recon, slice_data, tt_min, tt_max) / 60\n rmse[i] = loss.item()\n i += 1\n return rmse\n\n\ndef cal_auc(labels, rmse):\n '''auc given rmse'''\n fpr, tpr, thresholds = roc_curve(labels, rmse)\n roc_auc= auc(fpr, tpr)\n return roc_auc\n\n\n'''s-t, ano frac'''\nauc_avg = np.zeros(6)\nano_list = ['sp', 'time']\nseed_list = [\"\", \"2\", '3', '4', '5']\n# seed_list = [\"\"]\nfor file_seed in seed_list:\n aucs = []\n data_dir = '../data/test_synthetic' + file_seed +'/'\n for ano in ano_list:\n for frac_ano in [0.05, 0.1, 0.2]:\n #read data\n x_test = pd.read_pickle(data_dir + '{}_ano_{}.pkl'.format(ano, frac_ano))\n y_test = pd.read_pickle(data_dir + '{}_labels_ano_{}.pkl'.format(ano, frac_ano))\n fill_na(x_test)\n # consttuct dataloader\n test_loader = constr_dataloader(x_test)\n #auc\n rmse = cal_rmse_array(test_loader, model)\n auc_score = cal_auc(y_test.values, rmse)\n aucs.append( auc_score) \n auc_avg = auc_avg + np.array(aucs)\nauc_avg = auc_avg / len(seed_list)\n\n\nprint(args.model)\nprint(auc_avg)\n\nwith open(result_dir + args.model+ '.pt', 'wb') as fp:\n pickle.dump(auc_avg, fp)\n\n","sub_path":"src/ConGAE-fc-train-test.py","file_name":"ConGAE-fc-train-test.py","file_ext":"py","file_size_in_byte":9941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"35548511","text":"from django.contrib.auth import get_user_model\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template import loader\n\n\nUserModel = get_user_model()\n\n\ndef email_address_exists(email):\n \"\"\"\n Checks if a specific email address already exists against a user account\n \"\"\"\n found = UserModel.objects.filter(email__iexact=email).exists()\n return found\n\n\ndef send_mail(subject_template_name, email_template_name,\n context, from_email, to_email, html_email_template_name=None):\n \"\"\"\n Send a django.core.mail.EmailMultiAlternatives to `to_email`.\n \"\"\"\n subject = loader.render_to_string(subject_template_name, context)\n # Email subject *must not* contain newlines\n subject = ''.join(subject.splitlines())\n body = loader.render_to_string(email_template_name, context)\n\n email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])\n if html_email_template_name is not None:\n html_email = loader.render_to_string(html_email_template_name, context)\n email_message.attach_alternative(html_email, 'text/html')\n\n email_message.send()\n\n\ndef get_users(email):\n \"\"\"\n Function to return users with an email\n \"\"\"\n return UserModel.objects.filter(email=email)\n\n\n","sub_path":"account/utils/email_util.py","file_name":"email_util.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"174593158","text":"\"\"\"The ABQ Data Entry application\n\nChapter 3 Version\n\"\"\"\n\n# Tkinter imports\nimport tkinter as tk\nfrom tkinter import ttk\n\n# For creating the filename\nfrom datetime import datetime\n\n# For file operations\nfrom pathlib import Path\n\n# For creating the CSV file\nimport csv\n\n# Create a dict to hold our variables\nvariables = dict()\n# Variable to store the number of records saved\nrecords_saved = 0\n\n# Configure the root window\nroot = tk.Tk()\nroot.title('ABQ Data Entry Application')\nroot.columnconfigure(0, weight=1)\n\n# Application heading\nttk.Label(\n root,\n text=\"ABQ Data Entry Application\",\n font=(\"TkDefaultFont\", 16)\n).grid()\n\n####################\n# Data Record Form #\n####################\n\n# Build the data record form in a Frame\n# to keep geometry management simpler\ndrf = ttk.Frame(root)\ndrf.grid(padx=10, sticky=(tk.E + tk.W))\ndrf.columnconfigure(0, weight=1)\n\n##############################\n# Record information Frame #\n##############################\nr_info = ttk.LabelFrame(drf, text='Record Information')\nr_info.grid(sticky=(tk.W + tk.E))\nfor i in range(3):\n r_info.columnconfigure(i, weight=1 )\n\n# Date\nvariables['Date'] = tk.StringVar()\nttk.Label(r_info, text='Date').grid(row=0, column=0)\ntk.Entry(\n r_info, textvariable=variables['Date']\n).grid(row=1, column=0, sticky=(tk.W + tk.E))\n\n# Time\ntime_values = ['8:00', '12:00', '16:00', '20:00']\nvariables['Time'] = tk.StringVar()\nttk.Label(r_info, text='Time').grid(row=0, column=1)\nttk.Combobox(\n r_info, textvariable=variables['Time'], values=time_values\n).grid(row=1, column=1, sticky=(tk.W + tk.E))\n\n# Technician\nvariables['Technician'] = tk.StringVar()\nttk.Label(r_info, text='Technician').grid(row=0, column=2)\nttk.Entry(\n r_info, textvariable=variables['Technician']\n).grid(row=1, column=2, sticky=(tk.W + tk.E))\n\n# Lab\nvariables['Lab'] = tk.StringVar()\nttk.Label(r_info, text='Lab').grid(row=2, column=0)\nlabframe = ttk.Frame(r_info)\nfor lab in ('A', 'B', 'C'):\n ttk.Radiobutton(\n labframe, value=lab, text=lab, variable=variables['Lab']\n).pack(side=tk.LEFT, expand=True)\nlabframe.grid(row=3, column=0, sticky=(tk.W + tk.E))\n\n# Plot\nvariables['Plot'] = tk.IntVar()\nttk.Label(r_info, text='Plot').grid(row=2, column=1)\nttk.Combobox(\n r_info,\n textvariable=variables['Plot'],\n values=list(range(1, 21))\n).grid(row=3, column=1, sticky=(tk.W + tk.E))\n\n# Seed Sample\nvariables['Seed Sample'] = tk.StringVar()\nttk.Label(r_info, text='Seed Sample').grid(row=2, column=2)\nttk.Entry(\n r_info,\n textvariable=variables['Seed Sample']\n).grid(row=3, column=2, sticky=(tk.W + tk.E))\n\n#################################\n# Environment information Frame #\n#################################\ne_info = ttk.LabelFrame(drf, text=\"Environment Data\")\ne_info.grid(sticky=(tk.W + tk.E))\nfor i in range(3):\n e_info.columnconfigure(i, weight=1)\n\n# Humidity\nvariables['Humidity'] = tk.DoubleVar()\nttk.Label(e_info, text=\"Humidity (g/m³)\").grid(row=0, column=0)\nttk.Spinbox(\n e_info, textvariable=variables['Humidity'],\n from_=0.5, to=52.0, increment=0.01,\n).grid(row=1, column=0, sticky=(tk.W + tk.E))\n\n# Light\nvariables['Light'] = tk.DoubleVar()\nttk.Label(e_info, text='Light (klx)').grid(row=0, column=1)\nttk.Spinbox(\n e_info, textvariable=variables['Light'],\n from_=0, to=100, increment=0.01\n).grid(row=1, column=1, sticky=(tk.W + tk.E))\n\n# Temperature\nvariables['Temperature'] = tk.DoubleVar()\nttk.Label(e_info, text='Temperature (°C)').grid(row=0, column=2)\nttk.Spinbox(\n e_info, textvariable=variables['Temperature'],\n from_=4, to=40, increment=.01\n).grid(row=1, column=2, sticky=(tk.W + tk.E))\n\n# Equipment Fault\nvariables['Equipment Fault'] = tk.BooleanVar(value=False)\nttk.Checkbutton(\n e_info, variable=variables['Equipment Fault'],\n text='Equipment Fault'\n).grid(row=2, column=0, sticky=tk.W, pady=5)\n\n\n###########################\n# Plant information Frame #\n###########################\np_info = ttk.LabelFrame(drf, text=\"Plant Data\")\np_info.grid(sticky=(tk.W + tk.E))\nfor i in range(3):\n p_info.columnconfigure(i, weight=1)\n\n# Plants\nvariables['Plants'] = tk.IntVar()\nttk.Label(p_info, text='Plants').grid(row=0, column=0)\nttk.Spinbox(\n p_info, textvariable=variables['Plants'],\n from_=0, to=20, increment=1\n).grid(row=1, column=0, sticky=(tk.W + tk.E))\n\n# Blossoms\nvariables['Blossoms'] = tk.IntVar()\nttk.Label(p_info, text='Blossoms').grid(row=0, column=1)\nttk.Spinbox(\n p_info, textvariable=variables['Blossoms'],\n from_=0, to=1000, increment=1\n).grid(row=1, column=1, sticky=(tk.W + tk.E))\n\n# Fruit\nvariables['Fruit'] = tk.IntVar()\nttk.Label(p_info, text='Fruit').grid(row=0, column=2)\nttk.Spinbox(\n p_info, textvariable=variables['Fruit'],\n from_=0, to=1000, increment=1\n).grid(row=1, column=2, sticky=(tk.W + tk.E))\n\n# Min Height\nvariables['Min Height'] = tk.DoubleVar()\nttk.Label(p_info, text='Min Height (cm)').grid(row=2, column=0)\nttk.Spinbox(\n p_info, textvariable=variables['Min Height'],\n from_=0, to=1000, increment=0.01\n).grid(row=3, column=0, sticky=(tk.W + tk.E))\n\n# Max Height\nvariables['Max Height'] = tk.DoubleVar()\nttk.Label(p_info, text='Max Height (cm)').grid(row=2, column=1)\nttk.Spinbox(\n p_info, textvariable=variables['Max Height'],\n from_=0, to=1000, increment=0.01\n).grid(row=3, column=1, sticky=(tk.W + tk.E))\n\n# Med Height\nvariables['Med Height'] = tk.DoubleVar()\nttk.Label(p_info, text='Median Height (cm)').grid(row=2, column=2)\nttk.Spinbox(\n p_info, textvariable=variables['Med Height'],\n from_=0, to=1000, increment=0.01\n).grid(row=3, column=2, sticky=(tk.W + tk.E))\n\n\n#################\n# Notes Section #\n#################\n\nttk.Label(drf, text=\"Notes\").grid()\n# we can't use a variable for a Text input\nnotes_inp = tk.Text(drf, width=75, height=10)\nnotes_inp.grid(sticky=(tk.W + tk.E))\n\n\n########################\n# Save & Reset Buttons #\n########################\nbuttons = ttk.Frame(drf)\nbuttons.grid(sticky=tk.E + tk.W)\nsave_button = ttk.Button(buttons, text='Save')\nsave_button.pack(side=tk.RIGHT)\n\nreset_button = ttk.Button(buttons, text='Reset')\nreset_button.pack(side=tk.RIGHT)\n\n##############\n# Status Bar #\n##############\n\n# This is attached to the root window, not the form!\nstatus_variable = tk.StringVar()\nttk.Label(\n root, textvariable=status_variable\n).grid(sticky=tk.W + tk.E, row=99, padx=10)\n\n#############\n# Functions #\n#############\n\n\ndef on_reset():\n \"\"\"Called when reset button is clicked, or after save\"\"\"\n\n for variable in variables.values():\n if isinstance(variable, tk.BooleanVar):\n variable.set(False)\n else:\n variable.set('')\n\n # reset notes_inp\n notes_inp.delete('1.0', tk.END)\n\n\nreset_button.configure(command=on_reset)\n\ndef on_save():\n \"\"\"Handle save button clicks\"\"\"\n\n global records_saved\n # For now, we save to a hardcoded filename with a datestring.\n # If it doesnt' exist, create it,\n # otherwise just append to the existing file\n datestring = datetime.today().strftime(\"%Y-%m-%d\")\n filename = f\"abq_data_record_{datestring}.csv\"\n newfile = not Path(filename).exists()\n\n # get the data from the variables\n data = dict()\n fault = variables['Equipment Fault'].get()\n for key, variable in variables.items():\n if fault and key in ('Light', 'Humidity', 'Temperature'):\n data[key] = ''\n else:\n try:\n data[key] = variable.get()\n except tk.TclError:\n status_variable.set(\n f'Error in field: {key}. Data was not saved!')\n return\n # get the Text widget contents separately\n data['Notes'] = notes_inp.get('1.0', tk.END)\n\n # Append the record to a CSV\n with open(filename, 'a', newline='') as fh:\n csvwriter = csv.DictWriter(fh, fieldnames=data.keys())\n if newfile:\n csvwriter.writeheader()\n csvwriter.writerow(data)\n\n records_saved += 1\n status_variable.set(\n f\"{records_saved} records saved this session\")\n on_reset()\n\nsave_button.configure(command=on_save)\n\n# Reset the form\non_reset()\n\n####################\n# Execute Mainloop #\n####################\nroot.mainloop()\n","sub_path":"Chapter03/data_entry_app.py","file_name":"data_entry_app.py","file_ext":"py","file_size_in_byte":7927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"563002012","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# you need a tokenizer script that is included in the Google's bert repository.\n# git clone https://github.com/google-research/bert.git\n\nimport os, sys, io\nimport argparse\n# import progressbar\n\nparser = argparse.ArgumentParser(description=\"WordPiece tokenizer: BERT's tokenization methodology.\")\nparser.add_argument(\"--bert_dir\", \"-b\", required=True, type = str, help = \"relative path to the BERT script directory.\")\nparser.add_argument(\"--vocab_file\", \"-v\", required=True, type = str, help = \"WordPiece vocabulary file. You can use the one distributed along with pre-trained bert model.\")\nparser.add_argument(\"--corpus\", \"-c\", required=True, type = str, help = \"relative path to the raw text corpus to be processed.\")\nparser.add_argument(\"--separator\", required=False, type=str, default=\" \", help=\"token separator. DEFAULT:whitespace\")\nparser.add_argument(\"--case_sensitive\", action=\"store_true\", help=\"case sensitive tokenizatoin. DEFAULT:False\")\nparser.add_argument(\"--eos\", required=False, type=str, default=\"\", help=\"end-of-sentence characters. DEFAULT:empty\")\nargs = parser.parse_args()\n\nsys.path.append(args.bert_dir)\n\nfrom tokenization import FullTokenizer\n\ntokenizer = FullTokenizer(vocab_file=args.vocab_file, do_lower_case=not args.case_sensitive)\n\nseparator = args.separator\neos = args.eos\nwith io.open(args.corpus, mode=\"r\") as ifs:\n for sentence in ifs:\n sentence = sentence.strip()\n if len(sentence) == 0:\n continue\n lst_token = tokenizer.tokenize(sentence)\n print(separator.join(lst_token)+eos)","sub_path":"wordpiece_tokenizer.py","file_name":"wordpiece_tokenizer.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"505798480","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pygame\nimport random\n\n# Inicializaçao do pygame\npygame.init()\n\n# Define o tamanho da tela e o nome da janela\ntela = pygame.display.set_mode([700, 497])\npygame.display.set_caption(\"FlapPyLadies\")\n\n# Frame por segundo\nclock = pygame.time.Clock()\n\n# Carrega imagens e efeitos sonoros\nimg_jogador = pygame.image.load('img/jogador.png')\nimg_perdeu = pygame.image.load('img/perdeu.png')\nimg_logo = pygame.image.load('img/logoPython.png')\nimg_obs1 = pygame.image.load('img/img_obs1.png')\nimg_obs2 = pygame.image.load('img/img_obs2.png')\nimg_inicial = pygame.image.load('img/inicial.png')\nimg_fundo1 = pygame.image.load('img/fundo.jpg')\nimg_fundo2 = pygame.image.load('img/fundo.jpg')\npula = pygame.mixer.Sound('sounds/jump.wav')\nbate = pygame.mixer.Sound('sounds/explode.wav')\npula.set_volume(0.1)\nbate.set_volume(0.1)\n\n\n# Funçao para exibir o jogador\ndef jogador(jog_area):\n # Teste. Parametros: interface, cor, posiçao\n # pygame.draw.rect(tela,[0,0,0],jog_area)\n\n # Desenha imagem do jogador\n tela.blit(img_jogador, jog_area)\n\n\n# Funçao para exibir os obstaculos\ndef obstaculo(obs_cima, obs_baixo):\n # Teste\n # pygame.draw.rect(tela, [0,255,0], obs_cima)\n # pygame.draw.rect(tela, [0,255,0], obs_baixo)\n\n # Desenha imagem obstaculo\n tela.blit(img_obs1, [x_loc, y_tam - 500])\n tela.blit(img_obs2, [x_loc, y_tam + espaco])\n\n\n# Funçao para exibir a pontuaçao\ndef pontuacao(pontos):\n # Define fonte e tamanho\n fonte = pygame.font.Font('fonts/geo.ttf', 75)\n # Define texto e cor. Transforma int em str.\n texto = fonte.render(str(pontos), True, [255, 255, 255])\n tela.blit(texto, [350, 20])\n\n\n# Funçao para exibir a introduçao\ndef introducao():\n tela.fill([255, 255, 255])\n tela.blit(img_logo, [40, 300])\n tela.blit(img_inicial, [170, 50])\n pygame.display.update()\n pygame.time.wait(2000)\n\n\n# Declara variaveis #\n# Posiçao inicial do jogador\nx = 350\ny = 250\n# Velocidade inicial do jogador\nx_vel = 0\ny_vel = 5\n# Define a posicao do solo\nsolo = 477\nteto = 0\n# Localizaçao do obstaculo\nx_loc = 700\ny_loc = 0\n# Tamanho do obstaculo\nx_tam = 70\ny_tam = random.randint(0, 350)\n# Define o espaço do obstaculo\nespaco = 150\n# Deifne a velocidade em que o obstaculo aparece\nobs_vel = 4\n# Pontuaçao\npontos = 0\n# Define se a janela esta aberta ou fechada\nfechar = False\n\ntamImg = 1320\nposImg = 0\n\nintroducao()\n\n# Loop do jogo #\n# Inicio while. Enquanto nao fechar a janela... #\nfim = False\nwhile not fechar:\n # Cria obstaculos (retangulo para colisao)\n obs_cima = pygame.Rect(x_loc, y_loc, x_tam, y_tam)\n obs_baixo = pygame.Rect(x_loc, int(y_loc + y_tam + espaco), x_tam, y_tam + 500)\n # Cria jogador (retangulo para colisao)\n jog_area = pygame.Rect(x, y, 45, 45)\n\n # Inicio for. Reconhece os eventos de entrada do jogador #\n for event in pygame.event.get():\n # Se o jogador clicar em fechar\n if event.type == pygame.QUIT:\n fechar = True\n # Se o jogador apertar a tecla \"espaço\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n pula.play()\n y_vel = -10\n # Se o jogador soltar a tecla \"espaço\"\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n y_vel = 5\n # Fim for\n\n # Chama as funçoes #\n # Desenha o fundo\n tela.blit(img_fundo1, (posImg, 0))\n tela.blit(img_fundo2, (posImg + tamImg, 0))\n posImg -= 2\n if posImg * -1 == tamImg:\n posImg = 0\n # Desenha obstaculo\n obstaculo(obs_cima, obs_baixo)\n # Desenha jogador\n jogador(jog_area)\n # Desenha pontuaçao\n pontuacao(pontos)\n\n # Incrementa velocidade na posiçao y do jogador\n y += y_vel\n # Decrementa velocidade na posicao x do obstaculo\n x_loc -= obs_vel\n\n # Detecta colisoes do jogador com solo e obstaculos #\n # Jogador e solo/teto\n if y > solo or y < teto:\n bate.play()\n fim = True\n y_vel = 0\n obs_vel = 0\n\n # Jogador e obstaculo de cima\n if jog_area.colliderect(obs_cima):\n bate.play()\n fim = True\n obs_vel = 0\n y_vel = 0\n\n # Jogador e obstaculo de baixo\n if jog_area.colliderect(obs_baixo):\n bate.play()\n fim = True\n obs_vel = 0\n y_vel = 0\n\n # Se a localizaçao do obstaculo for menor que -80 (fora da tela)\n if x_loc < -80:\n # Cria outro obstaculo. Obstaculo de cima possui tamanho randomico de 0 a 350\n x_loc = 700\n y_tam = random.randint(0, 350)\n\n # Detecta se o jogador passou pelo obstaculo\n if x > x_loc and x < x_loc + 3:\n pontos += 1\n # Atualiza o fundo\n pygame.display.flip()\n clock.tick(60)\n\n # Jogar novamente #\n while fim:\n pygame.time.wait(300)\n for event in pygame.event.get():\n # Se o jogador clicar em fechar\n if event.type == pygame.QUIT:\n fim = False\n fechar = True\n # Se o jogador apertar a tecla \"espaço\"\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n # Posiçao inicial do jogador\n x = 350\n y = 250\n # Velocidade inicial do jogador\n x_vel = 0\n y_vel = 5\n # Localizaçao do obstaculo\n x_loc = 700\n y_loc = 0\n # Tamanho do obstaculo\n x_tam = 70\n y_tam = random.randint(0, 350)\n # Define o espaço do obstaculo\n espaco = 150\n # Deifne a velocidade em que o obstaculo aparece\n obs_vel = 4\n # Pontuaçao\n pontos = 0\n fim = False\n\n # Imagem Game Over\n tela.fill([255, 255, 255])\n # Carrega imagem do game over\n tela.blit(img_perdeu, (175, 20))\n # Define fonte e tamanho\n fonte = pygame.font.Font('fonts/geo.ttf', 50)\n # Define texto e cor. Transforma int em str.\n texto = fonte.render(str(pontos), True, [238, 37, 79])\n tela.blit(texto, [410, 53])\n pygame.display.flip()\n\n # Fim for\n\npygame.quit()\n","sub_path":"flappyladies/flappy.py","file_name":"flappy.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"458673553","text":"\"\"\"Models for the multilingual_survey app\"\"\"\nfrom django.contrib.contenttypes import fields\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django_libs.models_mixins import TranslationModelMixin\nfrom hvad.models import TranslatableModel, TranslatedFields\n\n\nclass Survey(TranslationModelMixin, TranslatableModel):\n \"\"\"\n A Survey consists of several Questions.\n\n :title: The name of this survey. Authors may change the title.\n :description: Optional description to add extra information to the survey.\n :slug: The slug of this survey. The slug should never be changed, since it\n might be referenced in the code.\n\n \"\"\"\n translations = TranslatedFields(\n title=models.CharField(\n verbose_name=_('Title'),\n max_length=256,\n ),\n description=models.TextField(\n verbose_name=_('Description'),\n max_length=2048,\n blank=True,\n )\n )\n\n slug = models.SlugField(\n verbose_name=_('Slug'),\n max_length=256,\n unique=True,\n )\n\n\nclass SurveyQuestion(TranslationModelMixin, TranslatableModel):\n \"\"\"\n Belongs to a Survey and has several SurveyAnswers.\n\n :title: The title of this question.\n :slug: The slug of this question. This will be used to create the form's\n field name.\n :content: An optional longer description of this question.\n :survey: FK to Survey.\n :is_multi_select: If ``True``, we will render checkboxes instead of\n radiobuttons or a drop-down-list..\n :has_other_field: If ``True``, the SurveyForm will allow the user to input\n any value into a \"other\" field. If ``False``, no such field will be\n rendered.\n :required: Makes the field required, but accepts either a selected answer\n or the other field, if there is one.\n :position: Can be used to order questions in a survey.\n\n \"\"\"\n translations = TranslatedFields(\n title=models.CharField(\n verbose_name=_('Title'),\n max_length=256,\n ),\n content=models.TextField(\n verbose_name=_('Content'),\n blank=True,\n )\n )\n\n slug = models.SlugField(\n verbose_name=('Slug'),\n max_length=256,\n )\n\n survey = models.ForeignKey(\n Survey,\n verbose_name=_('Survey'),\n related_name='questions',\n )\n\n is_multi_select = models.BooleanField(\n verbose_name=_('Is multi-select'),\n default=False,\n )\n\n has_other_field = models.BooleanField(\n verbose_name=_('Has other-field'),\n default=False,\n )\n\n required = models.BooleanField(\n verbose_name=_('Required'),\n default=False,\n )\n\n generic_position = fields.GenericRelation(\n 'generic_positions.ObjectPosition'\n )\n\n class Meta:\n unique_together = ('slug', 'survey')\n\n\nclass SurveyAnswer(TranslationModelMixin, TranslatableModel):\n \"\"\"\n Belongs to a SurveyQuestion.\n\n :title: The title of this answer. Authors may change this title.\n :slug: The slug of this answer. Should never be changed since it might be\n referenced in the code.\n :position: Can be used to order answers.\n\n \"\"\"\n translations = TranslatedFields(\n title=models.CharField(verbose_name=_('Title'), max_length=256),\n )\n\n slug = models.SlugField(\n verbose_name=_('Slug'),\n max_length=256,\n )\n\n question = models.ForeignKey(\n SurveyQuestion,\n verbose_name=_('Question'),\n related_name='answers'\n )\n\n generic_position = fields.GenericRelation(\n 'generic_positions.ObjectPosition'\n )\n\n class Meta:\n unique_together = ('slug', 'question')\n\n\n@python_2_unicode_compatible\nclass SurveyResponse(models.Model):\n \"\"\"\n Ties a user response to an answer.\n\n :user: Optional FK to the User. If ``None``, we are dealing with an\n anonymous answer.\n :session_id: Optional session id storage to identify anonymous users.\n :question: Optional FK to a SurveyQuestion. Must be set, if ``answer`` is\n not set but ``other_answer`` is set, so that we know to which question\n this custom answer belongs.\n :answer: Optional FK to a SurveyAnswer. If ``None``, then ``other_answer``\n must be given.\n :other_answer: Optional free text entered by the user if no available\n answer matches him. If ``None``, then ``answer`` must be given.\n :date_created: Creation date of this answer.\n\n \"\"\"\n user = models.ForeignKey(\n 'auth.User',\n verbose_name=_('User'),\n related_name='responses',\n blank=True, null=True,\n )\n\n session_id = models.CharField(\n verbose_name=_('Session ID'),\n max_length=1024,\n blank=True,\n )\n\n question = models.ForeignKey(\n SurveyQuestion,\n verbose_name=_('Question'),\n related_name='responses',\n blank=True, null=True,\n )\n\n answer = models.ManyToManyField(\n SurveyAnswer,\n verbose_name=_('Answer'),\n related_name='responses',\n )\n\n other_answer = models.CharField(\n verbose_name=_('Other answer'),\n max_length=1024,\n blank=True,\n )\n\n date_created = models.DateTimeField(\n verbose_name=_('Date created'),\n auto_now_add=True,\n )\n\n def __str__(self):\n return u'Answer to {0} from {1}'.format(\n self.question, self.user.email if self.user else '(?)')\n\n class Meta:\n ordering = ('question', )\n","sub_path":"multilingual_survey/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"588379698","text":"def split(lst):\n return ([i for item in lst for i in item.split()])\n \ndef convert_n2int(x):\n try:\n return int(x)\n except ValueError:\n return x\n \ndef convert_w2n (textnum, numwords={}):\n \n replace = True\n \n units = [ \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\"nine\", \"ten\", \"eleven\",\"twelve\",\"thirteen\",\"fourteen\", \"fifteen\",\"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n \n tens = [\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"]\n\n scales = [\"hundred\", \"thousand\", \"million\", \"billion\", \"trillion\"]\n \n if not numwords:\n units = units\n\n tens = tens\n\n scales = scales\n\n numwords[\"and\"] = (1, 0)\n for idx, word in enumerate(units): numwords[word] = (1, idx)\n for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)\n for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)\n\n ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}\n ordinal_endings = [('ieth', 'y'), ('th', '')]\n \n textnum_split = split([textnum])\n idx = []\n for i in range(len(textnum_split)):\n check_text = textnum_split[i]\n if \"-\" in check_text:\n idx.append(i)\n \n for i in idx:\n to_find = textnum_split[i].split('-')\n if to_find[0] in tens:\n textnum_split[i] = \" \".join(to_find)\n else:\n textnum_split[i] = \"-\".join(to_find)\n textnum = ' '.join(textnum_split)\n\n current = result = 0\n curstring = \"\"\n onnumber = False\n for word in textnum.split():\n if word in ordinal_words:\n scale, increment = (1, ordinal_words[word])\n current = current * scale + increment\n if scale > 100:\n result += current\n current = 0\n onnumber = True\n else:\n for ending, replacement in ordinal_endings:\n if word.endswith(ending):\n word = \"%s%s\" % (word[:-len(ending)], replacement)\n\n if word not in numwords:\n if onnumber:\n curstring += repr(result + current) + \" \"\n curstring += word + \" \"\n result = current = 0\n onnumber = False\n else:\n scale, increment = numwords[word]\n\n current = current * scale + increment\n if scale > 100:\n result += current\n current = 0\n onnumber = True\n\n if onnumber:\n curstring += repr(result + current)\n\n return curstring\n\ndef check_var(sent):\n sent = convert_w2n(sent)\n sent = split([sent])\n a = [convert_n2int(sent[j]) for j in range(len(sent))]\n check_int = []\n for elem in a:\n if type(elem)== int:\n check_int.append(True)\n else:\n check_int.append(False)\n if True in check_int:\n return True, ' '.join(sent)\n else:\n return False, ' '.join(sent) \n","sub_path":"hey_ac/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"574555185","text":"#\n# Copyright (c) 2014 TrendMicro. Data Center Services Research and Development. (dcsrd@dl.trendmicro.com)\n#\n\nimport boto.dynamodb\nfrom boto.dynamodb.exceptions import DynamoDBKeyNotFoundError\n\n\nclass DynamoDB():\n\n def __init__(self):\n self.conn = None\n self.table = None\n\n def connect(self, region, aws_access_key_id, aws_secret_access_key, conn=None):\n self.conn = conn if conn else boto.dynamodb.connect_to_region(region,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_secret_access_key)\n\n def get_table(self, name):\n try:\n table = self.conn.get_table(name)\n except boto.exception.DynamoDBResponseError:\n raise ValueError(\"Fail to connect to DynamoDB with table name: %s\" % name)\n return table\n\n def add_item(self, table, hash_key, attrs, range_key=None):\n if not range_key:\n return table.new_item(hash_key=hash_key, attrs=attrs)\n else:\n return table.new_item(hash_key=hash_key, range_key=range_key, attrs=attrs)\n\n def update_item(self, table, hash_key, key, value):\n item = table.get_item(hash_key=hash_key)\n item[key] = value\n return item\n\n def get_item(self, table, hash_key, range_key=None):\n item = None\n try:\n if not range_key:\n item = table.get_item(hash_key=hash_key)\n else:\n item = table.get_item(hash_key=hash_key, range_key=range_key)\n except DynamoDBKeyNotFoundError:\n pass\n return item\n\n def get_item_count(self, table):\n count = 0\n for item in table.scan():\n count += 1\n return count\n\n def commit(self, item):\n item.put()\n\n","sub_path":"omelet/aws/dynamodb.py","file_name":"dynamodb.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"296456823","text":"import os\nimport torch\nimport numpy as np\nfrom PIL import Image\nfrom rsunet2d import RSUNet\nfrom collections import OrderedDict\n\nfrom sklearn.metrics import average_precision_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import matthews_corrcoef\n\n\n# load ims\nprefix = '../mitoem/mito_human_valid'\nims = np.load(prefix + '_ims.npy')\n\n# load segs\nsegs = np.load(prefix + '_segs.npy')\nsegs[segs>0] = 1\nsegs = segs.astype(np.uint8)\n\n# build model\nmodel = RSUNet([16,32,48,64,80]).cuda()\nmodel = model.eval()\n\n# restore weights\nweight = '../u2d-bc-r2h-train/models_mk95/model-009000-0.9175.pth'\n\nnew_state_dict = OrderedDict()\nstate_dict = torch.load(weight)\nfor k, v in state_dict.items():\n\tname = k[7:] # remove module.\n\tnew_state_dict[name] = v\nmodel.load_state_dict(new_state_dict)\n\nif torch.cuda.device_count() > 1:\n\tmodel = torch.nn.DataParallel(model)\n\n# pad for overlap\nbd = 32\nims = np.pad(ims, ((0,0),(bd,bd),(bd,bd)), mode='symmetric')\n\n# settings\nin_shape = [100, 576, 576]\nstride = out_shape = [100, 512, 512]\noutput_segs = np.zeros([ims.shape[0] - (in_shape[0] - out_shape[0]),\n ims.shape[1] - (in_shape[1] - out_shape[1]),\n ims.shape[2] - (in_shape[2] - out_shape[2])], np.float32)\n# inference loop\nwith torch.no_grad():\n\tfor z in list(np.arange(0, ims.shape[0] - in_shape[0], stride[0])) + [ims.shape[0] - in_shape[0]]:\n\t\tfor y in list(np.arange(0, ims.shape[1] - in_shape[1], stride[1])) + [ims.shape[1] - in_shape[1]]:\n\t\t\tfor x in list(np.arange(0, ims.shape[2] - in_shape[2], stride[2])) + [ims.shape[2] - in_shape[2]]:\n\t\t\t\tim = ims[z : z + in_shape[0], y : y + in_shape[1], x : x + in_shape[2]]\n\t\t\t\tim = im.astype(np.float32) / 255.0\n\t\t\t\tim = np.expand_dims(im, axis=1)\n\t\t\t\tim = torch.Tensor(im).cuda()\n\t\t\t\t\n\t\t\t\tpred = model(im)\n\t\t\t\tpred = torch.nn.functional.pad(pred, tuple([-32]*4))\n\t\t\t\t\n\t\t\t\tpred = torch.nn.functional.softmax(pred, dim=1)\n\t\t\t\tpred = pred[:,1]\n\t\t\t\tpred = np.squeeze(pred.data.cpu().numpy())\n\t\t\t\t\n\t\t\t\toutput_segs[z : z + out_shape[0], y : y + out_shape[1], x : x + out_shape[2]] = pred\ndel ims\n\n# measure prediction\nserial_segs = segs.reshape(-1)\nmAP = average_precision_score(serial_segs, output_segs.reshape(-1))\n\nbin_segs = output_segs\nbin_segs[bin_segs>=0.5] = 1\nbin_segs[bin_segs<0.5] = 0\nserial_bin_segs = bin_segs.reshape(-1)\n\nintersection = np.logical_and(serial_segs==1, serial_bin_segs==1)\nunion = np.logical_or(serial_segs==1, serial_bin_segs==1)\nIoU = np.sum(intersection) / np.sum(union)\n\nF1 = f1_score(serial_segs, serial_bin_segs)\nMCC = matthews_corrcoef(serial_segs, serial_bin_segs)\nprint('mAP=%.4f, F1=%.4f, MCC=%.4f, IoU=%.4f' % (mAP, F1, MCC, IoU))\n# mAP=0.9072, F1=0.8383, MCC=0.8318, IoU=0.7216\n","sub_path":"r2h-ours/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"516949074","text":"\"\"\"\nTest individual tool functionality\n\"\"\"\n\nimport os\nimport shlex\nimport sys\n\nimport matplotlib as mpl\n\nimport tempfile\nimport pandas as pd\nimport tables\n\nfrom ctapipe.utils import get_dataset_path\nfrom ctapipe.core import run_tool\nfrom ctapipe.io import DataLevel\nimport numpy as np\nfrom pathlib import Path\n\n\nGAMMA_TEST_LARGE = get_dataset_path(\"gamma_test_large.simtel.gz\")\nLST_MUONS = get_dataset_path(\"lst_muons.simtel.zst\")\n\n\ndef test_merge(tmpdir):\n from ctapipe.tools.dl1_merge import MergeTool\n from ctapipe.tools.stage1 import Stage1Tool\n\n config = Path(\"./examples/stage1_config.json\").absolute()\n\n with tempfile.NamedTemporaryFile(suffix=\".hdf5\") as f1, tempfile.NamedTemporaryFile(\n suffix=\".hdf5\"\n ) as f2, tempfile.NamedTemporaryFile(\n suffix=\".hdf5\"\n ) as out_all, tempfile.NamedTemporaryFile(\n suffix=\".hdf5\"\n ) as out_skip_images, tempfile.NamedTemporaryFile(\n suffix=\".hdf5\"\n ) as out_skip_parameters:\n assert (\n run_tool(\n Stage1Tool(),\n argv=[\n f\"--config={config}\",\n f\"--input={GAMMA_TEST_LARGE}\",\n f\"--output={f1.name}\",\n \"--write-parameters\",\n \"--write-images\",\n \"--overwrite\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n assert (\n run_tool(\n Stage1Tool(),\n argv=[\n f\"--config={config}\",\n f\"--input={GAMMA_TEST_LARGE}\",\n f\"--output={f2.name}\",\n \"--write-parameters\",\n \"--write-images\",\n \"--overwrite\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n\n assert (\n run_tool(\n MergeTool(),\n argv=[f\"{f1.name}\", f\"{f2.name}\", f\"--o={out_all.name}\", \"--overwrite\"],\n cwd=tmpdir,\n )\n == 0\n )\n\n assert (\n run_tool(\n MergeTool(),\n argv=[\n f\"{f1.name}\",\n f\"{f2.name}\",\n f\"--o={out_skip_images.name}\",\n \"--overwrite\",\n \"--skip-images\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n\n assert (\n run_tool(\n MergeTool(),\n argv=[\n f\"{f1.name}\",\n f\"{f2.name}\",\n f\"--o={out_skip_parameters.name}\",\n \"--overwrite\",\n \"--skip-parameters\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n\n out_files_list = [out_all.name, out_skip_images.name, out_skip_parameters.name]\n\n for out_file in out_files_list:\n with tables.open_file(out_file, mode=\"r\") as out_f, tables.open_file(\n f1.name, mode=\"r\"\n ) as in_f:\n\n # Check expanded tables\n assert len(out_f.root.simulation.service.shower_distribution) == 2\n assert len(out_f.root.simulation.event.subarray.shower) == 220\n assert len(out_f.root.configuration.simulation.run) == 2\n assert len(out_f.root.dl1.monitoring.subarray.pointing) == 2\n assert len(out_f.root.dl1.event.subarray.trigger) == 220\n assert len(out_f.root.dl1.event.telescope.trigger) == 918\n assert len(out_f.root.simulation.service.shower_distribution) == 2\n # Check subarray and service meta\n assert out_f.root.dl1.service[\"image_statistics.__table_column_meta__\"]\n assert out_f.root.configuration.instrument.subarray.layout\n assert out_f.root.configuration.instrument.telescope.optics\n assert (\n out_f.root.configuration.instrument.telescope.camera.geometry_LSTCam\n )\n assert (\n out_f.root.configuration.instrument.telescope.camera.readout_LSTCam\n )\n\n # Check image statistics\n table_in = in_f.root[\"/dl1/service/image_statistics\"]\n table_out = out_f.root[\"/dl1/service/image_statistics\"]\n for row in range(len(table_in)):\n assert table_out.cols.counts[row] == np.multiply(\n table_in.cols.counts[row], 2\n )\n assert table_out.cols.cumulative_counts[row] == np.multiply(\n table_in.cols.cumulative_counts[row], 2\n )\n\n # Check telescope tables\n for tel in in_f.root.dl1.monitoring.telescope.pointing:\n assert len(\n out_f.root.dl1.monitoring.telescope.pointing[tel.name]\n ) == np.multiply(\n len(in_f.root.dl1.monitoring.telescope.pointing[tel.name]), 2\n )\n\n if out_file != out_skip_images.name:\n for tel in in_f.root.dl1.event.telescope.images:\n assert len(\n out_f.root.dl1.event.telescope.images[tel.name]\n ) == np.multiply(\n len(in_f.root.dl1.event.telescope.images[tel.name]), 2\n )\n\n if out_file != out_skip_parameters.name:\n for tel in in_f.root.dl1.event.telescope.parameters:\n assert len(\n out_f.root.dl1.event.telescope.parameters[tel.name]\n ) == np.multiply(\n len(in_f.root.dl1.event.telescope.parameters[tel.name]), 2\n )\n\n\ndef test_stage_1(tmpdir):\n from ctapipe.tools.stage1 import Stage1Tool\n\n config = Path(\"./examples/stage1_config.json\").absolute()\n with tempfile.NamedTemporaryFile(suffix=\".hdf5\") as f:\n assert (\n run_tool(\n Stage1Tool(),\n argv=[\n f\"--config={config}\",\n f\"--input={GAMMA_TEST_LARGE}\",\n f\"--output={f.name}\",\n \"--write-parameters\",\n \"--overwrite\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n\n # check tables were written\n with tables.open_file(f.name, mode=\"r\") as tf:\n assert tf.root.dl1\n assert tf.root.dl1.event.telescope\n assert tf.root.dl1.event.subarray\n assert tf.root.configuration.instrument.subarray.layout\n assert tf.root.configuration.instrument.telescope.optics\n assert tf.root.configuration.instrument.telescope.camera.geometry_LSTCam\n assert tf.root.configuration.instrument.telescope.camera.readout_LSTCam\n\n assert tf.root.dl1.monitoring.subarray.pointing.dtype.names == (\n \"time\",\n \"array_azimuth\",\n \"array_altitude\",\n \"array_ra\",\n \"array_dec\",\n )\n\n # check we can read telescope parametrs\n dl1_features = pd.read_hdf(f.name, \"/dl1/event/telescope/parameters/tel_001\")\n features = (\n \"obs_id\",\n \"event_id\",\n \"tel_id\",\n \"hillas_intensity\",\n \"concentration_cog\",\n \"leakage_pixels_width_1\",\n )\n for feature in features:\n assert feature in dl1_features.columns\n\n with tempfile.NamedTemporaryFile(suffix=\".hdf5\") as f:\n assert (\n run_tool(\n Stage1Tool(),\n argv=[\n f\"--config={config}\",\n f\"--input={GAMMA_TEST_LARGE}\",\n f\"--output={f.name}\",\n \"--write-images\",\n \"--overwrite\",\n ],\n cwd=tmpdir,\n )\n == 0\n )\n\n with tables.open_file(f.name, mode=\"r\") as tf:\n assert tf.root.dl1\n assert tf.root.dl1.event.telescope\n assert tf.root.dl1.event.subarray\n assert tf.root.configuration.instrument.subarray.layout\n assert tf.root.configuration.instrument.telescope.optics\n assert tf.root.configuration.instrument.telescope.camera.geometry_LSTCam\n assert tf.root.configuration.instrument.telescope.camera.readout_LSTCam\n assert tf.root.dl1.event.telescope.images.tel_001\n dl1_image = tf.root.dl1.event.telescope.images.tel_001\n assert \"image_mask\" in dl1_image.dtype.names\n assert \"image\" in dl1_image.dtype.names\n assert \"peak_time\" in dl1_image.dtype.names\n\n\ndef test_stage1_datalevels(tmpdir):\n \"\"\"test the dl1 tool on a file not providing r1 or dl0\"\"\"\n from ctapipe.io import EventSource\n from ctapipe.tools.stage1 import Stage1Tool\n\n class DummyEventSource(EventSource):\n @classmethod\n def is_compatible(cls, path):\n with open(path, \"rb\") as f:\n dummy = f.read(5)\n return dummy == b\"dummy\"\n\n @property\n def datalevels(self):\n return (DataLevel.R0,)\n\n @property\n def is_simulation(self):\n return True\n\n @property\n def obs_ids(self):\n return [1]\n\n @property\n def subarray(self):\n return None\n\n def _generator(self):\n return None\n\n with tempfile.NamedTemporaryFile(mode=\"wb\", suffix=\".dummy\") as f:\n with tempfile.NamedTemporaryFile(mode=\"wb\", suffix=\".h5\") as out:\n f.write(b\"dummy\")\n f.flush()\n\n config = Path(\"./examples/stage1_config.json\").absolute()\n tool = Stage1Tool()\n\n assert (\n run_tool(\n tool,\n argv=[\n f\"--config={config}\",\n f\"--input={f.name}\",\n f\"--output={out.name}\",\n \"--write-images\",\n \"--overwrite\",\n ],\n cwd=tmpdir,\n )\n == 1\n )\n # make sure the dummy event source was really used\n assert isinstance(tool.event_source, DummyEventSource)\n\n # we need to \"touch\" the output file again, otherwise tempfile will\n # complain it no longer exists as the tool removed it\n open(out.name, mode=\"a\").close()\n\n\ndef test_muon_reconstruction(tmpdir):\n from ctapipe.tools.muon_reconstruction import MuonAnalysis\n\n with tempfile.NamedTemporaryFile(suffix=\".hdf5\") as f:\n assert (\n run_tool(\n MuonAnalysis(),\n argv=[f\"--input={LST_MUONS}\", f\"--output={f.name}\", \"--overwrite\"],\n cwd=tmpdir,\n )\n == 0\n )\n\n with tables.open_file(f.name) as t:\n table = t.root.dl1.event.telescope.parameters.muons[:]\n assert len(table) > 20\n assert np.count_nonzero(np.isnan(table[\"muonring_radius\"])) == 0\n\n assert run_tool(MuonAnalysis(), [\"--help-all\"]) == 0\n\n\ndef test_display_summed_images(tmpdir):\n from ctapipe.tools.display_summed_images import ImageSumDisplayerTool\n\n mpl.use(\"Agg\")\n assert (\n run_tool(\n ImageSumDisplayerTool(),\n argv=shlex.split(f\"--infile={GAMMA_TEST_LARGE} \" \"--max-events=2 \"),\n cwd=tmpdir,\n )\n == 0\n )\n\n assert run_tool(ImageSumDisplayerTool(), [\"--help-all\"]) == 0\n\n\ndef test_display_integrator(tmpdir):\n from ctapipe.tools.display_integrator import DisplayIntegrator\n\n mpl.use(\"Agg\")\n\n assert (\n run_tool(\n DisplayIntegrator(),\n argv=shlex.split(f\"--f={GAMMA_TEST_LARGE} \" \"--max_events=1 \"),\n cwd=tmpdir,\n )\n == 0\n )\n\n assert run_tool(DisplayIntegrator(), [\"--help-all\"]) == 0\n\n\ndef test_display_events_single_tel(tmpdir):\n from ctapipe.tools.display_events_single_tel import SingleTelEventDisplay\n\n mpl.use(\"Agg\")\n\n assert (\n run_tool(\n SingleTelEventDisplay(),\n argv=shlex.split(\n f\"--infile={GAMMA_TEST_LARGE} \"\n \"--tel=11 \"\n \"--max-events=2 \" # <--- inconsistent!!!\n ),\n cwd=tmpdir,\n )\n == 0\n )\n\n assert run_tool(SingleTelEventDisplay(), [\"--help-all\"]) == 0\n\n\ndef test_display_dl1(tmpdir):\n from ctapipe.tools.display_dl1 import DisplayDL1Calib\n\n mpl.use(\"Agg\")\n\n assert (\n run_tool(\n DisplayDL1Calib(),\n argv=shlex.split(\"--max_events=1 \" \"--telescope=11 \"),\n cwd=tmpdir,\n )\n == 0\n )\n\n assert run_tool(DisplayDL1Calib(), [\"--help-all\"]) == 0\n\n\ndef test_info():\n from ctapipe.tools.info import info\n\n info(show_all=True)\n\n\ndef test_dump_triggers(tmpdir):\n from ctapipe.tools.dump_triggers import DumpTriggersTool\n\n sys.argv = [\"dump_triggers\"]\n outfile = tmpdir.join(\"triggers.fits\")\n tool = DumpTriggersTool(infile=GAMMA_TEST_LARGE, outfile=str(outfile))\n\n assert run_tool(tool, cwd=tmpdir) == 0\n\n assert outfile.exists()\n assert run_tool(tool, [\"--help-all\"]) == 0\n\n\ndef test_dump_instrument(tmpdir):\n from ctapipe.tools.dump_instrument import DumpInstrumentTool\n\n sys.argv = [\"dump_instrument\"]\n tmpdir.chdir()\n\n tool = DumpInstrumentTool()\n\n assert run_tool(tool, [f\"--input={GAMMA_TEST_LARGE}\"], cwd=tmpdir) == 0\n assert tmpdir.join(\"FlashCam.camgeom.fits.gz\").exists()\n\n assert (\n run_tool(tool, [f\"--input={GAMMA_TEST_LARGE}\", \"--format=ecsv\"], cwd=tmpdir)\n == 0\n )\n assert tmpdir.join(\"MonteCarloArray.optics.ecsv.txt\").exists()\n\n assert (\n run_tool(tool, [f\"--input={GAMMA_TEST_LARGE}\", \"--format=hdf5\"], cwd=tmpdir)\n == 0\n )\n assert tmpdir.join(\"subarray.h5\").exists()\n\n assert run_tool(tool, [\"--help-all\"], cwd=tmpdir) == 0\n\n\ndef test_camdemo(tmpdir):\n from ctapipe.tools.camdemo import CameraDemo\n\n sys.argv = [\"camera_demo\"]\n tool = CameraDemo()\n tool.num_events = 10\n tool.cleanframes = 2\n tool.display = False\n\n assert run_tool(tool, cwd=tmpdir) == 0\n assert run_tool(tool, [\"--help-all\"]) == 0\n\n\ndef test_bokeh_file_viewer(tmpdir):\n from ctapipe.tools.bokeh.file_viewer import BokehFileViewer\n\n sys.argv = [\"bokeh_file_viewer\"]\n tool = BokehFileViewer(disable_server=True)\n assert run_tool(tool, cwd=tmpdir) == 0\n assert str(tool.reader.input_url) == get_dataset_path(\"gamma_test_large.simtel.gz\")\n assert run_tool(tool, [\"--help-all\"]) == 0\n\n\ndef test_extract_charge_resolution(tmpdir):\n from ctapipe.tools.extract_charge_resolution import ChargeResolutionGenerator\n\n output_path = os.path.join(str(tmpdir), \"cr.h5\")\n tool = ChargeResolutionGenerator()\n assert run_tool(tool, [\"-f\", GAMMA_TEST_LARGE, \"-O\", output_path], cwd=tmpdir) == 1\n # TODO: Test files do not contain true charge, cannot test tool fully\n # assert os.path.exists(output_path)\n assert run_tool(tool, [\"--help-all\"]) == 0\n\n\ndef test_plot_charge_resolution(tmpdir):\n from ctapipe.tools.plot_charge_resolution import ChargeResolutionViewer\n from ctapipe.plotting.tests.test_charge_resolution import create_temp_cr_file\n\n path = create_temp_cr_file(tmpdir)\n\n output_path = os.path.join(str(tmpdir), \"cr.pdf\")\n tool = ChargeResolutionViewer()\n\n argv = [\"-f\", str(path), \"-o\", output_path]\n assert run_tool(tool, argv) == 0\n assert os.path.exists(output_path)\n assert run_tool(tool, [\"--help-all\"]) == 0\n","sub_path":"ctapipe/tools/tests/test_tools.py","file_name":"test_tools.py","file_ext":"py","file_size_in_byte":15882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"367270887","text":"\"\"\"\nhttps://leetcode.com/problems/path-sum/\nLC112 Path Sum\nEasy\n\nGiven a binary tree and a sum,\ndetermine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.\n\nNote: A leaf is a node with no children.\n\"\"\"\n\nfrom A02_TreeNode import *\n\n\nclass Solution_A1:\n def hasPathSum(self, root: TreeNode, target: int) -> bool:\n \"\"\"\n Borrow the idea of allPath, but add boolean verification when hit a leaf\n \"\"\"\n return self.validPathCollecter(root, target, [])\n\n def validPathCollecter(self, root, target: int, path_so_far: List[int]) -> bool:\n if not root:\n return False\n\n elif not root.left and not root.right: # isLeaf\n path_so_far = path_so_far + [root.val]\n return sum(path_so_far) == target\n\n else:\n left_path, right_path = path_so_far[:], path_so_far[:]\n left_path.append(root.val)\n right_path.append(root.val)\n return self.validPathCollecter(root.left, target, left_path) or \\\n self.validPathCollecter(root.right, target, right_path)\n\n\nclass Solution_A2:\n def hasPathSum(self, root: TreeNode, target: int) -> bool:\n \"\"\"\n Use an internal fucntion to collect all path sums when hit a leaf\n Similar idea as A, but carry just the pathSum in recursion in stead of detailed path\n \"\"\"\n return self.pathSumChecker(root, 0, target)\n\n def pathSumChecker(self, root: TreeNode, carryover: int, target: int) -> bool:\n \"\"\"\n Internal helper to add all pathSum to a list\n \"\"\"\n if not root:\n return False\n else:\n new_carryover = carryover + root.val\n if not root.left and not root.right: # isLeaf\n return new_carryover == target # collect path sum\n else:\n # carry the path sum so far and recursive find left and right\n return self.pathSumChecker(root.left, new_carryover, target) or \\\n self.pathSumChecker(root.right, new_carryover, target)\n\n\nif __name__ == \"__main__\":\n testCase = Solution_A2()\n\n T0 = None\n assert not testCase.hasPathSum(T0, 0), \"Edge 0\"\n\n T1 = genTree([1])\n assert testCase.hasPathSum(T1, 1), \"Edge 1\"\n\n T2 = genTree([\n 5,\n 4, 8,\n 11, None, 13, 4,\n 7, 2, None, None, None, None, None, 1\n ])\n assert testCase.hasPathSum(T2, 22), \"Example 1, 5+4+11+2\"\n\n T3 = genTree([\n 1,\n 2, 3\n ])\n assert not testCase.hasPathSum(T3, 5), \"Example 2\"\n\n T4 = genTree([\n 1,\n 2, None\n ])\n assert not testCase.hasPathSum(T4, 0), \"Example 3\"\n\n print(\"All passed\")\n","sub_path":"LeetCode/LC112_path_sum.py","file_name":"LC112_path_sum.py","file_ext":"py","file_size_in_byte":2735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"229311073","text":"import socket\nimport threading\nimport pymongo\n\nclass Server():\n # Add MongoDB COLLECTION\n COLLECTION = pymongo.MongoClient(\n \"mongodb+srv://user:password0@cluster0.pa3o1.mongodb.net/project0?retryWrites=true&w=majority\")\\\n ['database0']\\\n ['collection0']\n HEADER = 64\n FORMAT = \"utf-8\"\n DISCONNECT_MESSAGE = \"!DISCONNECT\"\n ADDR = (\"192.168.0.2\",5050)\n\n @classmethod\n def send(cls, conn, msg):\n message = str(msg).encode(cls.FORMAT)\n msg_length = len(message)\n send_length = str(msg_length).encode(cls.FORMAT)\n send_length += b' ' * (cls.HEADER - len(send_length))\n conn.send(send_length)\n conn.send(message)\n\n @classmethod\n def receive_client(cls, conn, addr):\n cls.CONNECTION_COUNT+=1\n print(f\"[NEW CONNECTION] {addr} now connected. [ACTIVE CONNECTIONS] {cls.CONNECTION_COUNT}\")\n while True:\n # Receive Message Length Header\n msg_length = conn.recv(cls.HEADER).decode(cls.FORMAT)\n if msg_length:\n msg_length = int(msg_length)\n # Receive Message\n msg = conn.recv(msg_length).decode(cls.FORMAT)\n # Disconnect Line\n if msg == cls.DISCONNECT_MESSAGE:\n print(f\"[CONNECTION SEVERED] {addr}\")\n break\n else:\n # Query COLLECTION\n ans = cls.COLLECTION.find_one({\"key\": msg})[\"value\"]\n cls.send(conn, ans)\n cls.CONNECTION_COUNT-=1\n conn.close()\n\n @classmethod\n def start(cls):\n cls.CONNECTION_COUNT=0\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind(cls.ADDR)\n\n server.listen()\n print(f\"[STARTING] Server is listening on {cls.ADDR}\")\n while (True):\n conn, addr = server.accept()\n threading.Thread(target=cls.receive_client, args=(conn,addr)).start()\n\n# Operation\nServer.start()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"201546651","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nSIGMA = 1\nZ = 0.5\nTMAX = 1\nTMIN = 1e-2\nTAU = 1e5\n\nrandom.seed(1)\n\n\ndef f(x, y):\n return x ** 2 - np.cos(4 * np.pi * x) + (y - 1) ** 2\n\n\ndef r(z):\n return (-2 * SIGMA ** 2 * np.log(1 - z)) ** 0.5\n\n\ndef cartesian(r_, theta):\n return [r_ * np.cos(theta), r_ * np.sin(theta)]\n\n\ndef random_pair(z):\n return cartesian(r(z), random.random() * 2 * np.pi)\n\n\nt = 0\nT = TMAX\ncurrent_coord = [2, 2]\ncurrent_minimum = f(current_coord[0], current_coord[1])\nx_lst = [current_coord[0]]\ny_lst = [current_coord[1]]\nf_lst = [current_minimum]\nt_lst = [t]\nwhile T > TMIN:\n t += 1\n T = TMAX * np.exp(-t / TAU)\n\n delta = random_pair(Z)\n new_coord = [current_coord[0] + delta[0], current_coord[1] + delta[1]]\n new_minimum = f(new_coord[0], new_coord[1])\n\n if (new_minimum < current_minimum) or (\n random.random() < np.exp(-(new_minimum - current_minimum) / T)):\n current_coord = new_coord\n current_minimum = f(new_coord[0], new_coord[1])\n\n x_lst.append(current_coord[0])\n y_lst.append(current_coord[1])\n f_lst.append(current_minimum)\n t_lst.append(t)\n\n # print(current_coord)\n # print(current_minimum)\n\nprint(current_coord)\nprint(current_minimum)\n\nplt.figure()\nplt.plot(t_lst, x_lst)\nplt.xlabel(\"t\")\nplt.ylabel(\"x\")\nplt.title(\"Candidate x coordinate over time\")\nplt.savefig(\"Candidate x coordinate over time\")\n\n\nplt.figure()\nplt.plot(t_lst, y_lst)\nplt.xlabel(\"t\")\nplt.ylabel(\"y\")\nplt.title(\"Candidate y coordinate over time\")\nplt.savefig(\"Candidate y coordinate over time\")\n\n\nplt.figure()\nplt.plot(t_lst, f_lst)\nplt.xlabel(\"t\")\nplt.ylabel(\"f(x,y)\")\nplt.title(\"Candidate global minimum over time\")\nplt.savefig(\"Candidate global minimum over time\")\n\nplt.show()\n","sub_path":"salesman/annealing.py","file_name":"annealing.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"254733039","text":"# A simple example using the HTTP plugin that shows the retrieval of a\n# single file via HTTP.\n#\nfrom java.util import Random\n\nfrom net.grinder.script import Test\nfrom net.grinder.plugin.http import HTTPRequest\n\n\ntest1 = Test(1, \"Localhost\")\nrequest1 = test1.wrap(HTTPRequest())\nrandom = Random()\n\nclass TestRunner:\n def __call__(self):\n i = abs(random.nextInt()) % 999\n url = 'http://localhost?%d' % i\n request1.GET(url)\n\n","sub_path":"sample/grinder.py","file_name":"grinder.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"400777316","text":"from flask import (Flask, flash, request, redirect, render_template, session, url_for)\nfrom oauth import (OAuthConsumer, OAuthToken, OAuthRequest, OAuthSignatureMethod_HMAC_SHA1, OAuthClient)\nfrom khanv2 import khanv2, consumer \nimport os\nimport json\nimport sys\nimport cgi\nimport requests\nimport urlparse\n\n@khanv2.route('/')\ndef index():\n access_token = session.get('oauth_token')\n if access_token is None:\n return redirect(url_for('login'))\n full_url='http://www.khanacademy.org/api/v1/user'\n url=urlparse.urlparse(full_url)\n query_params = cgi.parse_qs(url.query)\n for key in query_params:\n query_params[key] = query_params[key][0]\n token=OAuthToken.from_string(access_token)\n oauth_request = OAuthRequest.from_consumer_and_token(\n consumer,\n token=token,\n http_url='http://www.khanacademy.org/api/v1/user',\n parameters=query_params,\n http_method='GET'\n )\n oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, token)\n r = requests.get(oauth_request.to_url()).content\n data=json.loads(r)\n return render_template(\"index.html\", email=str(data['student_summary']['email']))\n\n@khanv2.route('/login')\ndef login():\n oauth_request = OAuthRequest.from_consumer_and_token(\n consumer,\n callback='http://127.0.0.1:5000/oauth_callback',\n http_url='http://www.khanacademy.org/api/auth/request_token'\n )\n oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)\n return redirect(oauth_request.to_url())\n\n@khanv2.route('/oauth_callback')\ndef oauth_callback():\n oauth_token = request.args.get(\"oauth_token\", \"\")\n oauth_secret = request.args.get(\"oauth_token_secret\", \"\")\n oauth_verifier = request.args.get(\"oauth_verifier\", \"\")\n request_token = OAuthToken(oauth_token, oauth_secret)\n request_token.set_verifier(oauth_verifier)\n session[\"request_token\"] = request_token.to_string()\n oauth_request = OAuthRequest.from_consumer_and_token(\n consumer, \n token=request_token, \n http_url='http://www.khanacademy.org/api/auth/access_token',\n callback=None, \n parameters=None, \n verifier=request_token.verifier\n )\n oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, request_token)\n r = requests.get(oauth_request.to_url())\n access_token = OAuthToken.from_string(r.text)\n session['oauth_token'] = access_token.to_string()\n return redirect(url_for(\"index\"))\n\n@khanv2.route('/logout')\ndef logout():\n session.pop('oauth_token', None)\n session.pop('request_token', None)\n return redirect(url_for('index'))","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"178093854","text":"\"\"\" webserver's login subsystem\n\n\n This sub-package is based on aiohttp-login https://github.com/imbolc/aiohttp-login\n\"\"\"\nimport asyncio\nimport logging\nfrom typing import Dict\n\nimport asyncpg\nfrom aiohttp import web\n\nfrom servicelib.aiopg_utils import DSN\nfrom servicelib.application_keys import APP_CONFIG_KEY\nfrom servicelib.application_setup import ModuleCategory, app_module_setup\n\nfrom ..db_config import CONFIG_SECTION_NAME as DB_SECTION\nfrom ..email_config import CONFIG_SECTION_NAME as SMTP_SECTION\nfrom ..rest_config import APP_OPENAPI_SPECS_KEY\nfrom ..rest_config import CONFIG_SECTION_NAME as REST_SECTION\nfrom ..statics import INDEX_RESOURCE_NAME\nfrom .cfg import APP_LOGIN_CONFIG, cfg\nfrom .config import CONFIG_SECTION_NAME\nfrom .routes import create_routes\nfrom .storage import AsyncpgStorage\n\nlog = logging.getLogger(__name__)\n\n\nTIMEOUT_SECS = 5\n\n\ndef _create_login_config(app: web.Application, storage: AsyncpgStorage) -> Dict:\n \"\"\"\n Creates compatible config to update login.cfg.cfg object\n \"\"\"\n login_cfg = app[APP_CONFIG_KEY].get(CONFIG_SECTION_NAME, {}) # optional!\n smtp_cfg = app[APP_CONFIG_KEY][SMTP_SECTION]\n\n config = {\"APP\": app, \"STORAGE\": storage}\n\n def _fmt(val):\n if isinstance(val, str):\n if val.strip().lower() in [\"null\", \"none\", \"\"]:\n return None\n return val\n\n for key, value in login_cfg.items():\n config[key.upper()] = _fmt(value)\n\n for key, value in smtp_cfg.items():\n config[\"SMTP_{}\".format(key.upper())] = _fmt(value)\n\n return config\n\n\nasync def _setup_config_and_pgpool(app: web.Application):\n \"\"\"\n - gets input configs from different subsystems and initializes cfg (internal configuration)\n - creates a postgress pool and asyncpg storage object\n\n :param app: fully setup application on startup\n :type app: web.Application\n \"\"\"\n db_cfg = app[APP_CONFIG_KEY][DB_SECTION][\"postgres\"]\n\n # db\n pool = await asyncpg.create_pool(\n dsn=DSN.format(**db_cfg) + f\"?application_name={__name__}_{id(app)}\",\n min_size=db_cfg[\"minsize\"],\n max_size=db_cfg[\"maxsize\"],\n loop=asyncio.get_event_loop(),\n )\n\n storage = AsyncpgStorage(pool) # NOTE: this key belongs to cfg, not settings!\n\n # config\n config = _create_login_config(app, storage)\n cfg.configure(config)\n\n if INDEX_RESOURCE_NAME in app.router:\n cfg[\"LOGIN_REDIRECT\"] = app.router[INDEX_RESOURCE_NAME].url_for()\n else:\n log.warning(\n \"Unknown location for login page. Defaulting redirection to %s\",\n cfg[\"LOGIN_REDIRECT\"],\n )\n\n app[APP_LOGIN_CONFIG] = cfg\n\n yield # ----------------\n\n if config[\"STORAGE\"].pool is not pool:\n log.error(\"Somebody has changed the db pool\")\n try:\n await asyncio.wait_for(pool.close(), timeout=TIMEOUT_SECS)\n except asyncio.TimeoutError:\n log.exception(\"Failed to close login storage loop\")\n\n\n@app_module_setup(\n __name__,\n ModuleCategory.ADDON,\n depends=[f\"simcore_service_webserver.{mod}\" for mod in (\"rest\", \"db\")],\n logger=log,\n)\ndef setup_login(app: web.Application):\n \"\"\" Setting up login subsystem in application\n\n \"\"\"\n # routes\n specs = app[APP_OPENAPI_SPECS_KEY]\n routes = create_routes(specs)\n app.router.add_routes(routes)\n\n # signals\n app.cleanup_ctx.append(_setup_config_and_pgpool)\n return True\n\n\n__all__ = \"setup_login\"\n","sub_path":"services/web/server/src/simcore_service_webserver/login/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"161431751","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom io import StringIO\nfrom io import BytesIO\n\ntry:\n f = open('file.txt', 'r')\n print(f.read())\nfinally:\n if f:\n f.close()\n\nwith open('file.txt', 'r', encoding='gbk', errors='ignore') as f:\n for line in f.readlines(): # readlines() return a list\n print(line.strip()) # 把末尾的 '\\n' 删掉\n\nf = StringIO()\nf.write('hello')\nf.write(' ')\nf.write('world!')\nprint(f.getvalue())\n\nf = BytesIO()\nf.write('中文'.encode('utf-8'))\nprint(f.getvalue())","sub_path":"base_io.py","file_name":"base_io.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"125343431","text":"\"\"\"\n sp500 symbols\n\"\"\"\n\nimport logging\nimport urllib.request\nimport datetime\nfrom collections import OrderedDict\n\nfrom bs4 import BeautifulSoup\n\nfrom stock_common.lib import util\nfrom stock_common.conf.config import Config\nfrom stock_common.lib.database import Database\n\nCONFIGS = Config.get_configs()\ndb = Database(CONFIGS)\n\n\nclass SP500():\n \"\"\"\n SP500 class that scraping sp500 symbols from wikipeia\n \"\"\"\n def __init__(self):\n self.url = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'\n self.mongo_schema = 'stock_recommender'\n self.mongo_collection = 'ticker_symbols'\n\n def get_symbols_from_wikipedia(self):\n \"\"\"\n Request wikipedia url and parse the html to get sp500 symbols\n\n Returns:\n a list of dict\n \"\"\"\n header = {'User-Agent': 'Mozilla/5.0'}\n req = urllib.request.Request(self.url, headers=header)\n page = urllib.request.urlopen(req)\n soup = BeautifulSoup(page, 'lxml')\n\n table = soup.find('table', {'class': 'wikitable sortable'})\n rows = table.findAll('tr')\n\n now = datetime.datetime.now()\n\n header = [\n 'symbol', 'security', 'sec_filings', 'sector', 'sub_industry',\n 'address', 'first_added_date', 'cik'\n ]\n\n symbols = []\n for row in rows:\n col = row.findAll('td')\n if col:\n values = [\n None if value.string is None\n else value.string.strip() for value in col\n ]\n data = OrderedDict(zip(header, values))\n if data['first_added_date']:\n first_added_date = datetime.datetime.strptime(\n data['first_added_date'], '%Y-%m-%d')\n else:\n first_added_date = None\n\n symbol = {\n '_id': data['symbol'],\n 'symbol': data['symbol'],\n 'security': data['security'],\n 'sector': data['sector'],\n 'industry': data['sub_industry'],\n 'address': data['address'],\n 'first_added_date': first_added_date,\n 'central_index_key': data['cik'],\n 'last_updated': now,\n 'source': 'sp500',\n }\n\n symbols.append(symbol)\n\n return symbols\n\n @db.connect('MONGO')\n def upsert_symbols_into_mongo(self, client):\n \"\"\"\n Upserting sp500 symbols into mongo\n \"\"\"\n collection = client[self.mongo_schema][self.mongo_collection]\n symbols = self.get_symbols_from_wikipedia()\n\n for symbol in symbols:\n collection.replace_one({'_id': symbol['_id']}, symbol, upsert=True)\n\n @db.connect('MONGO')\n def get_symbols_from_mongo(self, client, details=False):\n \"\"\"\n Getting SP500 symbols from Mongo\n \"\"\"\n collection = client[self.mongo_schema][self.mongo_collection]\n\n if details:\n return list(collection.find())\n else:\n symbols = list(collection.find(\n {}, {'symbol': 1, '_id': 0}\n ))\n return [item['symbol'] for item in symbols]\n\n def refresh_historical_prices(self):\n \"\"\"\n Download historical prices of sp500 and store to mongodb\n \"\"\"\n\n symbols = self.get_symbols_from_mongo()\n if 'SPY' not in symbols:\n symbols.append('SPY')\n\n end_date = datetime.date.today()\n start_date = end_date - datetime.timedelta(days=50)\n\n pf = util.read_data(symbols, start_date, end_date)\n\n logging.info('Saving Prices to HDF5 file.')\n filename = CONFIGS.CURRENT_PATH + '/../tmp/' + CONFIGS.PRICES_H5\n pf.to_hdf(filename, key='prices', mode='w')\n\n df_history = pf.to_frame().reset_index()\n df_history.columns = [\n 'date', 'symbol', 'open', 'high', 'low', 'close', 'volume']\n df_history.date =\\\n df_history.date.astype(str).str.replace('-', '').astype(int)\n df_history['_id'] =\\\n df_history.date.astype(str) + ':' + df_history.symbol\n\n documents = df_history.to_dict('records')\n\n assert documents\n\n self.replace_historical_prices_in_mongo(documents)\n\n @db.connect('MONGO')\n def replace_historical_prices_in_mongo(self, client, documents):\n \"\"\"\n Replace Historical Prices in MongoDB\n \"\"\"\n\n db = client.stock_recommender\n db.prices.delete_many({})\n db.prices.insert_many(documents)\n","sub_path":"data/sp500.py","file_name":"sp500.py","file_ext":"py","file_size_in_byte":4623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"20039249","text":"from ..util import Resources\nimport os\n\n\nclass KEXPDestinationDirectoryRule:\n\n def __init__(self, dest_dir):\n self.picard_dir = os.path.join(dest_dir, Resources.picard_directory)\n self.mbid_dir = os.path.join(dest_dir, Resources.mbid_directory)\n \n def get_dest(self, audiofile):\n # get the name of the release directory\n directory = os.path.split(os.path.split(audiofile.file_name)[0])[1]\n \n if Resources.has_mbid(audiofile):\n dest = os.path.join(self.mbid_dir, directory)\n else:\n dest = os.path.join(self.picard_dir, directory)\n \n if not (os.path.exists(dest)):\n os.makedirs(dest)\n\n return dest","sub_path":"audio_pipeline/tb_ui/model/Rules.py","file_name":"Rules.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"594336427","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread(\"../../data/teppich.png\", cv2.IMREAD_GRAYSCALE)\n\n\n''' FFT '''\nIMG = np.fft.fft2(img)\nMAGNITUDE = np.abs(IMG)\nANGLE = np.angle(IMG)\n\n''' Filter out frequencies '''\nprint(\"Number of frequencies:\", MAGNITUDE.shape)\nfrequencies_to_delete = 25\nMAGNITUDE[:-frequencies_to_delete, :-frequencies_to_delete] = 0\n\n\n''' IFFT '''\nIMG = MAGNITUDE * np.exp(1j * ANGLE)\nfiltered_image = np.fft.ifft2(IMG).astype(np.float32)\n\n''' Bild anzeigen '''\ncv2.imshow(\"img\", img)\ncv2.imshow(\"filtered\", filtered_image / np.max(filtered_image))\n\ncv2.waitKey(0)\n","sub_path":"3_Signalorientierte_Bildverarbeitung/ü3/l_c.py","file_name":"l_c.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"73941281","text":"#!/usr/bin/env python3.5\n\n\nfrom datetime import datetime\nimport time\nimport os\nimport cnn_db_loader\n\nimport tf_utils\nimport cnn_tf_graphs\n\nimport tensorflow as tf\nfrom tensorflow.contrib import learn\n\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('experiment_folder', '45', #26\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"Directory where to write event logs \"\"\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t \"\"\"and checkpoint.\"\"\")\ntf.app.flags.DEFINE_integer('max_steps', 1000000,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"Number of batches to run.\"\"\")\ntf.app.flags.DEFINE_boolean('log_device_placement', False,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"Whether to log device placement.\"\"\")\ntf.app.flags.DEFINE_integer('batch_size', 100, #25, 100\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"\"\"Size of a batch.\"\"\")\n\ncnn_db_loader.NUMBER_ALPHAS = 0\ncnn_db_loader.NUMBER_IMAGES = 3\ncnn_db_loader.NUMBER_XYZ = 0\nos.environ['CUDA_VISIBLE_DEVICES']='0' #'0'\n\nMOMENTUM = 0.9\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.001 # Initial learning rate.\n\nRESTORE = False\n\n\nPaSC_still_BASE = '/user/HS204/m09113/my_project_folder/PaSC/still/multi_fit_CCR_iter75_reg30_256/'\n#PaSC_still_BASE = '/user/HS204/m09113/my_project_folder/PaSC/still/multi_fit_CCR_iter75_reg30/'\nPaSC_video_BASE = '/user/HS204/m09113/my_project_folder/PaSC/video/multi_fit_CCR_iter75_reg30_256/'\n#PaSC_video_BASE = '/user/HS204/m09113/my_project_folder/PaSC/video/multi_fit_CCR_iter75_reg30/'\nCASIA_BASE = '/user/HS204/m09113/my_project_folder/CASIA_webface/multi_fit_CCR_iter75_reg30_256/'\n#CASIA_BASE = '/user/HS204/m09113/my_project_folder/CASIA_webface/multi_fit_CCR_iter75_reg30/'\nExperint_BASE = '/user/HS204/m09113/my_project_folder/cnn_experiments/'\nexperiment_dir = Experint_BASE+FLAGS.experiment_folder\ndb_dir = experiment_dir+'/db_input/'\ntrain_dir = experiment_dir+'/train'\n\ntf.logging.set_verbosity(tf.logging.DEBUG)\n\ndef train():\n\t\"\"\"Train CIFAR-10 for a number of steps.\"\"\"\n\twith tf.Graph().as_default():\n\t\tglobal_step = tf.contrib.framework.get_or_create_global_step()\n\n\t\tpasc_still = cnn_db_loader.PaSC_still_loader(outputfolder=db_dir, db_base=PaSC_still_BASE)\n\t\tpasc_video = cnn_db_loader.PaSC_video_loader(outputfolder=db_dir, db_base=PaSC_video_BASE)\n\t\tcasia = cnn_db_loader.CASIA_webface_loader(outputfolder=db_dir, db_base=CASIA_BASE)\n\t\tpasc_still.set_all_as_train()\n\t\tcasia.set_all_as_train()\n\t\tpasc_video.split_train_eval(train_proportion=0.8)\n\t\tdb_loader = cnn_db_loader.Aggregator(pasc_video, pasc_still, casia)\n\t\t#db_loader = cnn_db_loader.Aggregator(pasc_still)\n\n\t\tnum_batches_per_epoch = len(db_loader.examples_train) / FLAGS.batch_size\n\n\t\timages_list, labels_list = db_loader.get_training_multi_image_and_label_lists()\n\n\t\t#images = [0]*cnn_db_loader.NUMBER_IMAGES\n\t\toutput = tf_utils.inputs_multi(images_list, labels_list, FLAGS.batch_size, db_loader.get_mean_image_path(), png_with_alpha=True, image_size=256)\n\t\t#output = tf_utils.inputs_multi(images_list, labels_list, FLAGS.batch_size, db_loader.get_mean_image_path(), png_with_alpha=False, image_size=512)\n\t\timages = output[:cnn_db_loader.NUMBER_IMAGES]\n\t\tlabels = output[-1]\n\t\t#print (output)\n\t\t#for i in range(cnn_db_loader.NUMBER_IMAGES):\n\t\t#\timages[i], labels = tf_utils.inputs([image[i] for image in images_list], labels_list, FLAGS.batch_size, db_loader.get_mean_image_path())\n\n\t\tconfs = [0]*cnn_db_loader.NUMBER_IMAGES\n\t\twith tf.variable_scope(\"confidence_estimation\") as scope:\n\t\t\tfor i in range(cnn_db_loader.NUMBER_IMAGES):\n\t\t\t\tconfs[i] = cnn_tf_graphs.confidence_cnn23(images[i], input_size=256)\n\t\t\t\t#confs[i] = cnn_tf_graphs.confidence_cnn4(images[i], input_size=512)\n\t\t\t\tscope.reuse_variables()\n\t\t\t\t#tf.get_variable_scope().reuse_variables()\n\n\t\tmerging_input_list = [[images[i], confs[i]] for i in range(cnn_db_loader.NUMBER_IMAGES)]\n\t\tmerged_image = cnn_tf_graphs.merge_isomaps_softmax(merging_input_list)\n\n\t\tmerged_image = tf.slice(merged_image,[0,0,0,0],[-1,-1,-1,3])\n\n\t\t# Build a Graph that computes the logits predictions from the inference model.\n\t\tlogits, _ = cnn_tf_graphs.inference(network=\"alex\", mode=learn.ModeKeys.TRAIN, batch_size=FLAGS.batch_size, num_classes=db_loader.number_ids, input_image_tensor=merged_image, image_size=256)\n\t\t#logits, _ = cnn_tf_graphs.inference(network=\"alex\", mode=learn.ModeKeys.TRAIN, batch_size=FLAGS.batch_size, num_classes=db_loader.number_ids, input_image_tensor=merged_image, image_size=512)\n\n\t\t# Calculate loss.\n\t\t#loss = cnn_tf_graphs.l2_loss(logits, labels)\n\t\tloss = cnn_tf_graphs.softmax_loss(logits, labels, db_loader.number_ids)\n\n\t\ttop_k_op = tf.nn.in_top_k(logits, labels, 1)\n\t\tsum_correct = tf.reduce_sum(tf.cast(top_k_op, tf.float32))\n\t\taccuracy = tf.divide(tf.multiply(sum_correct,tf.constant(100.0)),tf.constant(float(FLAGS.batch_size)))\n\t\t#accuracy, accuracy_update = tf.contrib.metrics.streaming_accuracy(tf.argmax(logits,1), tf.argmax(labels, 1))\n\n\t\tlr = tf.constant(INITIAL_LEARNING_RATE, tf.float32)\n\t\ttf.summary.scalar('learning_rate', lr)\n\t\ttf.summary.scalar('momentum', MOMENTUM)\n\t\ttf.summary.scalar('batch_size', FLAGS.batch_size)\n\t\ttf.summary.scalar('accuracy', accuracy)\n\n\t\toptimizer=tf.train.MomentumOptimizer(learning_rate=lr, momentum=MOMENTUM)\n\t\t#optimizer=tf.train.AdadeltaOptimizer(learning_rate=lr)\n\n\t\ttrain_op = tf.contrib.layers.optimize_loss(\n\t\t\t\t\tloss=loss,\n\t\t\t\t\tglobal_step=tf.contrib.framework.get_global_step(),\n\t\t\t\t\tlearning_rate=lr,\n\t\t\t\t\toptimizer=optimizer,\n\t\t\t\t\tvariables=None)\n\t\t\t\t\t#variables=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, \"confidence_estimation\"))\n\t\n\n\t\tlogging_hook = tf.train.LoggingTensorHook(\n\t\t\t\t\t\ttensors={'step': tf.contrib.framework.get_global_step(),\n\t\t\t\t\t\t\t\t 'loss': loss,\n\t\t\t\t\t\t\t\t 'lr': lr,\n\t\t\t\t\t\t\t\t 'acc': accuracy},\n\t\t\t\t\t\tevery_n_iter=100)\n\n\t\t#saver = tf.train.Saver(var_list=None, keep_checkpoint_every_n_hours=1)\n\t\tsaver = tf.train.Saver(var_list=None, max_to_keep=None)\n\t\tif RESTORE:\n\t\t\tclassification_network_variables = [var for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) if var not in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"confidence_estimation\")]\n\t\t\tall_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n\t\t\tprint ('all vars:',len(all_variables))\n\t\t\tconf_conv3_variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"confidence_estimation/deconv3/\")\n\t\t\tconf_conv3_optimize = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, \"OptimizeLoss/confidence_estimation/deconv3/\")\n\t\t\tprint ('conv3 vars', len(conf_conv3_variables+conf_conv3_optimize))\n\t\t\tgood_ones = [var for var in all_variables if (var not in conf_conv3_variables) and (var not in conf_conv3_optimize)]\n\t\t\t#print (type(all_variables))\n\t\t\t#restorer = tf.train.Saver(var_list=classification_network_variables, max_to_keep=None)\n\t\t\trestorer = tf.train.Saver(var_list=good_ones, max_to_keep=None)\n\n\t\tclass _LearningRateSetterHook(tf.train.SessionRunHook):\n\t\t\t\"\"\"Sets learning_rate based on global step.\"\"\"\n\n\t\t\tdef begin(self):\n\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**6\n\t\t\t\t#print(self.num_batches_per_epoch)\n\t\n\t\t\tdef before_run(self, run_context):\n\t\t\t\treturn tf.train.SessionRunArgs(\n\t\t\t\t\ttf.contrib.framework.get_global_step(), # Asks for global step value.\n\t\t\t\t\tfeed_dict={lr: self._lrn_rate}) # Sets learning rate\n\t\n\t\t\tdef after_run(self, run_context, run_values):\n\t\t\t\ttrain_step = run_values.results\n\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE\n\t\t\t\t#training_epoch = int(train_step/num_batches_per_epoch)\n\t\t\t\t#self._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**int(train_step/num_batches_per_epoch/2.7)\n\t\t\t\tif train_step < 1.5*num_batches_per_epoch:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE\n\t\t\t\telif train_step < 3.0*num_batches_per_epoch:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**1\n\t\t\t\telif train_step < 4.5*num_batches_per_epoch:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**2\n\t\t\t\telif train_step < 6.0*num_batches_per_epoch:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**3\n\t\t\t\telif train_step < 7.5*num_batches_per_epoch:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**4\n\t\t\t\telse:\n\t\t\t\t\tself._lrn_rate = INITIAL_LEARNING_RATE * LEARNING_RATE_DECAY_FACTOR**5\n\n\t\t\t\t\t\t\t\n\n\t\tconfig = tf.ConfigProto( allow_soft_placement=False, log_device_placement=FLAGS.log_device_placement)\n\t\tconfig.gpu_options.allow_growth = True\n\t\n\t\twith tf.train.MonitoredTrainingSession(\n\t\t\t\tis_chief=True,\n\t\t\t\tcheckpoint_dir=train_dir,\n\t\t\t\thooks=[ tf.train.StopAtStepHook(last_step=FLAGS.max_steps),\n\t\t\t\t\t\ttf.train.NanTensorHook(loss),\n\t\t\t\t\t\ttf.train.CheckpointSaverHook(checkpoint_dir=train_dir, save_steps=num_batches_per_epoch, saver=saver),\n\t\t\t\t\t\tlogging_hook,\n\t\t\t\t\t\t_LearningRateSetterHook()],\n\t\t\t\tconfig=config,\n\t\t\t\tsave_checkpoint_secs=3600)\tas mon_sess:\n\t\t\t#saver.restore(mon_sess,'/user/HS204/m09113/my_project_folder/cnn_experiments/28/train_first_part/model.ckpt-21575')\n\t\t\tif RESTORE:\n\t\t\t\trestorer.restore(mon_sess,tf.train.latest_checkpoint(train_dir+'_restore'))\n\t\t\twhile not mon_sess.should_stop():\n\t\t\t\tmon_sess.run(train_op)\n\t\t\t\t#mon_sess.run(train_op)\n\t\t#my_summary_op = tf.summary.merge_all()\n\t\t#sv = tf.train.Supervisor(logdir=\"/my/training/directory\", summary_op=None) # Do not run the summary service\n\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n\n\tif not os.path.exists(experiment_dir):\n\t\tos.mkdir(experiment_dir)\n\n\n\tif not os.path.exists(train_dir):\n\t\tos.mkdir(train_dir)\n\n\tif not os.path.exists(db_dir):\n\t\tos.mkdir(db_dir)\n\n\twith tf.device('/gpu:0'):\n\t\ttrain()\n\n\nif __name__ == '__main__':\n\ttf.app.run()\n","sub_path":"cnn_experiment_train_merging.py","file_name":"cnn_experiment_train_merging.py","file_ext":"py","file_size_in_byte":9512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"387239446","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Match',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('match_decimal', models.DecimalField(default=0.0, max_digits=16, decimal_places=8)),\n ('questions_answered', models.IntegerField(default=0)),\n ('timestamp', models.DateTimeField(auto_now_add=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('user_a', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='match_user_a')),\n ('user_b', models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='match_user_b')),\n ],\n ),\n ]\n","sub_path":"src/matches/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"343079362","text":"from mpl_toolkits.mplot3d import Axes3D\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nx1=0\r\nxr=1\r\n\r\nt0=0\r\nt1=0.5\r\n\r\nnx=10\r\nnt=100\r\n\r\ndx=(xr-x1)/(nx-1)\r\ndt=(t1-t0)/(nt-1)\r\n\r\nx= np.zeros((nt,nx))\r\nt= np.zeros((nt,nx))\r\nu=np.zeros((nt,nx))\r\n\r\nsig= dt/dx**2\r\n\r\nfor j in range(nx):\r\n for i in range(nt):\r\n x[i,j]= x1+j*dx\r\n t[i,j]= t0+i*dt\r\n \r\n \r\n#initial condition setting\r\nfor i in range(nx):\r\n u[0,i]= np.sin(np.pi*x[0,i])\r\n\r\nfor i in range(0,nt-1):\r\n #matrix assemble\r\n A= np.matrix(np.zeros((nx,nx)))\r\n B= np.matrix(np.zeros((nx,1)))\r\n \r\n A[0,0]=1\r\n A[nx-1,nx-1]=1\r\n \r\n B[0]=0\r\n B[nx-1]=0\r\n \r\n for j in range(1,nx-1):\r\n A[j,j-1]=-sig\r\n A[j,j]=1+2*sig\r\n A[j,j+1]=-sig\r\n \r\n B[j]=u[i,j]\r\n \r\n #u[i+1,:]=Gauss(A,B).A1\r\n u[i+1,:]=np.linalg.solve(A,B).A1\r\nfig = plt.figure()\r\nsurf=fig.add_subplot(111,projection='3d')\r\n\r\nsurf.plot_surface(t,x,u)\r\nsurf.set_xlabel('t')\r\nsurf.set_ylabel('x')\r\nsurf.set_zlabel('u')\r\n\r\n#plt.contourf(t,x,u)\r\n#plt.xlabel('t')\r\n#plt.ylabel('x')\r\n\r\nplt.show()\r\n","sub_path":"lab09_PDE_implicitMethod_HeatEquation.py","file_name":"lab09_PDE_implicitMethod_HeatEquation.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"428058765","text":"\"\"\"Domain logic for the csp.\"\"\"\nimport json\nimport logging\nimport os\nfrom time import sleep\nfrom typing import List\n\nfrom ska_ser_skallop.connectors import configuration as con_config\nfrom ska_ser_skallop.event_handling.builders import MessageBoardBuilder, get_message_board_builder\nfrom ska_ser_skallop.mvp_control.configuration import types\nfrom ska_ser_skallop.mvp_control.describing import mvp_names as names\nfrom ska_ser_skallop.mvp_control.entry_points import base\nfrom ska_ser_skallop.mvp_control.entry_points.composite import CompositeEntryPoint\nfrom ska_ser_skallop.utils.singleton import Memo\n\nfrom ..mvp_model.states import ObsState\nfrom ..obsconfig.config import Observation\n\nlogger = logging.getLogger(__name__)\n\n# scan duration needs to be a singleton in order to keep track of scan\n# settings between configure scan and run scan\nSCAN_DURATION = 4\n\n\nclass LogEnabled:\n \"\"\"class that allows for logging if set by env var\"\"\"\n\n def __init__(self) -> None:\n self._live_logging = bool(os.getenv(\"DEBUG_ENTRYPOINT\"))\n self._tel = names.TEL()\n\n def _log(self, mssage: str):\n if self._live_logging:\n logger.info(mssage)\n\n\nclass StartUpStep(base.StartUpStep, LogEnabled):\n \"\"\"Implementation of Startup step for CSP\"\"\"\n\n def __init__(self, nr_of_subarrays: int) -> None:\n super().__init__()\n self.nr_of_subarrays = nr_of_subarrays\n self.csp_controller = con_config.get_device_proxy(self._tel.csp.controller)\n\n def do_startup(self):\n \"\"\"Domain logic for starting up a telescope on the interface to csp.\n\n This implments the set_telescope_to_running method on the entry_point.\n \"\"\"\n self.csp_controller.command_inout(\"On\", [])\n\n def set_wait_for_do_startup(self) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited\n for before startup of csp is done.\n :return: brd\n \"\"\"\n brd = get_message_board_builder()\n brd.set_waiting_on(self._tel.csp.controller).for_attribute(\"state\").to_become_equal_to(\n \"ON\", ignore_first=False\n )\n # Note we do not wait for controller on skalow as\n # it seems it does not change state subarrays\n if self._tel.skamid:\n # we wait for cbf vccs to be in proper initialised state\n brd.set_waiting_on(self._tel.csp.cbf.controller).for_attribute(\n \"reportVccState\"\n ).to_become_equal_to([\"[0, 0, 0, 0]\", \"[0 0 0 0]\"], ignore_first=False)\n for index in range(1, self.nr_of_subarrays + 1):\n brd.set_waiting_on(self._tel.csp.subarray(index)).for_attribute(\n \"state\"\n ).to_become_equal_to(\"ON\", ignore_first=False)\n return brd\n\n def set_wait_for_doing_startup(self) -> MessageBoardBuilder:\n \"\"\"\n Not implemented.\n\n :raises NotImplementedError: Raises the error when\n implementation is not done.\n \"\"\"\n raise NotImplementedError()\n\n def set_wait_for_undo_startup(self) -> MessageBoardBuilder:\n \"\"\"\n Domain logic for what needs to be waited for switching the csp off.\n :return: brd\n \"\"\"\n brd = get_message_board_builder()\n # controller\n # the low telescope does not switch off so there is no wait\n if self._tel.skamid:\n brd.set_waiting_on(self._tel.csp.controller).for_attribute(\"state\").to_become_equal_to(\n \"OFF\", ignore_first=False\n )\n # subarrays\n for index in range(1, self.nr_of_subarrays + 1):\n brd.set_waiting_on(self._tel.csp.subarray(index)).for_attribute(\n \"state\"\n ).to_become_equal_to(\"OFF\", ignore_first=False)\n return brd\n\n def undo_startup(self):\n \"\"\"Domain logic for switching the csp off.\"\"\"\n self.csp_controller.command_inout(\"Off\", [])\n\n\nclass CspAssignResourcesStep(base.AssignResourcesStep, LogEnabled):\n \"\"\"Implementation of Assign Resources Step for CSP.\"\"\"\n\n def __init__(self, observation: Observation) -> None:\n \"\"\"\n Init object.\n\n :param observation: An instance of the Observation class or None.\n If None, a new instance of Observation will be created.\n\n \"\"\"\n super().__init__()\n self.observation = observation\n self._tel = names.TEL()\n\n def do_assign_resources(\n self,\n sub_array_id: int,\n dish_ids: List[int],\n composition: types.Composition, # pylint: disable=\n sb_id: str,\n ):\n \"\"\"Domain logic for assigning resources to a subarray in csp.\n\n This implments the compose_subarray method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n :param dish_ids: this dish indices (in case of mid) to control\n :param composition: The assign resources configuration paramaters\n :param sb_id: a generic ide to identify a sb to assign resources\n \"\"\"\n if self._tel.skalow:\n subarray_name = self._tel.skalow.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n csp_low_configuration = json.dumps(csp_low_assign_resources)\n self._log(\n f\"commanding {subarray_name} with AssignResources:\" f\" {csp_low_configuration} \"\n )\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"AssignResources\", csp_low_configuration)\n elif self._tel.skamid:\n subarray_name = self._tel.skamid.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n config = self.observation.generate_assign_resources_config().as_json\n self._log(f\"commanding {subarray_name} with AssignResources: {config} \")\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"AssignResources\", config)\n\n def undo_assign_resources(self, sub_array_id: int):\n \"\"\"Domain logic for releasing resources on a subarray in csp.\n\n This implments the tear_down_subarray method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with ReleaseAllResources\")\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"ReleaseAllResources\")\n\n def set_wait_for_do_assign_resources(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited\n for subarray assign resources is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n self._tel = names.TEL()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\"IDLE\")\n\n return builder\n\n def set_wait_for_doing_assign_resources(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Not implemented.\n\n :param sub_array_id: The index id of the subarray to control\n :return: brd\n \"\"\"\n brd = get_message_board_builder()\n brd.set_waiting_on(self._tel.csp.subarray(sub_array_id)).for_attribute(\n \"obsState\"\n ).to_become_equal_to(\"RESOURCING\")\n return brd\n\n def set_wait_for_undo_resources(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited for\n subarray releasing resources is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\"EMPTY\")\n\n return builder\n\n\nclass CspConfigureStep(base.ConfigureStep, LogEnabled):\n \"\"\"Implementation of Configure Scan Step for CSP.\"\"\"\n\n def __init__(self, observation: Observation) -> None:\n \"\"\"\n Init object.\n\n :param observation: An instance of the Observation class or None.\n If None, a new instance of Observation will be created.\n \"\"\"\n super().__init__()\n self.observation = observation\n self._tel = names.TEL()\n\n def do_configure(\n self,\n sub_array_id: int,\n configuration: types.ScanConfiguration,\n sb_id: str,\n duration: float,\n ):\n \"\"\"Domain logic for configuring a scan on subarray in csp.\n\n This implments the compose_subarray method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n :param configuration: The assign resources configuration paramaters\n :param sb_id: a generic ide to identify a sb to assign resources\n :param duration: duration of scan\n \"\"\"\n # scan duration needs to be a memorised for\n # future objects that mnay require it\n Memo(scan_duration=duration)\n if self._tel.skalow:\n subarray_name = self._tel.skalow.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n cbf_low_configuration = json.dumps(csp_low_configure_scan)\n self._log(f\"commanding {subarray_name} with Configure:\" f\" {cbf_low_configuration} \")\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"Configure\", cbf_low_configuration)\n elif self._tel.skamid:\n subarray_name = self._tel.skamid.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n csp_mid_configuration = self.observation.generate_csp_scan_config().as_json\n self._log(f\"commanding {subarray_name} with Configure:\" f\" {csp_mid_configuration} \")\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"Configure\", csp_mid_configuration)\n\n def undo_configure(self, sub_array_id: int):\n \"\"\"\n Domain logic for clearing configuration on a subarray in csp.\n\n This implments the clear_configuration method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n subarray_name = self._tel.csp.cbf.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with command GoToIdle\")\n subarray.command_inout(\"GoToIdle\")\n\n def set_wait_for_do_configure(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited\n for configuring a scan is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\"READY\")\n return builder\n\n def set_wait_for_doing_configure(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited\n for a subarray to be in a state of configuring.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\n \"CONFIGURING\"\n )\n return builder\n\n def set_wait_for_undo_configure(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited for\n subarray clear scan config is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\"IDLE\")\n return builder\n\n\nclass CspScanStep(base.ScanStep, LogEnabled):\n\n \"\"\"Implementation of Scan Step for CBF.\"\"\"\n\n def __init__(self, observation: Observation) -> None:\n \"\"\"\n Init object.\n\n :param observation: An instance of the Observation class or None.\n If None, a new instance of Observation will be created.\n \"\"\"\n super().__init__()\n self.observation = observation\n self._tel = names.TEL()\n\n def do_scan(self, sub_array_id: int):\n \"\"\"Domain logic for running a scan on subarray in csp.\n\n This implments the scan method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n\n :raises Exception: Raise exception in do method of scan command\n \"\"\"\n if self._tel.skalow:\n scan_config_arg = json.dumps(csp_low_scan)\n elif self._tel.skamid:\n scan_config_arg = self.observation.generate_run_scan_conf().as_json\n scan_duration = Memo().get(\"scan_duration\")\n self._tel = names.TEL()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"Commanding {subarray_name} to Scan with {scan_config_arg}\")\n try:\n subarray.command_inout(\"Scan\", scan_config_arg)\n sleep(scan_duration)\n current_state = subarray.read_attribute(\"obsState\")\n if current_state.value == ObsState.SCANNING:\n subarray.command_inout(\"EndScan\")\n except Exception as exception:\n logger.exception(exception)\n raise exception\n\n def set_wait_for_do_scan(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"This is a no-op as there is no scanning command\n\n :param sub_array_id: The index id of the subarray to control\n :return: message board builder\n \"\"\"\n return get_message_board_builder()\n\n def undo_scan(self, sub_array_id: int):\n \"\"\"This is a no-op as no undo for scan is needed\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n\n def set_wait_for_doing_scan(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifyig what needs to be done for\n waiting for subarray to be scanning.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\n \"SCANNING\", ignore_first=True\n )\n return builder\n\n def set_wait_for_undo_scan(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"This is a no-op as no undo for scan is needed\n\n :param sub_array_id: The index id of the subarray to control\n :return: message board builder\n \"\"\"\n return get_message_board_builder()\n\n\nclass CSPSetOnlineStep(base.SetOnlineStep, LogEnabled):\n \"\"\"Domain logic for setting csp to online\"\"\"\n\n def __init__(self, nr_of_subarrays: int) -> None:\n super().__init__()\n self.nr_of_subarrays = nr_of_subarrays\n\n def do_set_online(self):\n \"\"\"Domain logic for setting devices in csp to online.\"\"\"\n controller_name = self._tel.csp.controller\n controller = con_config.get_device_proxy(controller_name)\n self._log(f\"Setting adminMode for {controller_name} to '0' (ONLINE)\")\n controller.write_attribute(\"adminmode\", 0)\n for index in range(1, self.nr_of_subarrays + 1):\n subarray_name = self._tel.csp.subarray(index)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"Setting adminMode for {subarray_name} to '0' (ONLINE)\")\n subarray.write_attribute(\"adminmode\", 0)\n\n def set_wait_for_do_set_online(self) -> MessageBoardBuilder:\n \"\"\"\n Domain logic for waiting for setting to online to be complete.\n\n :return: builder\n \"\"\"\n controller_name = self._tel.csp.controller\n builder = get_message_board_builder()\n builder.set_waiting_on(controller_name).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(controller_name).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n for index in range(1, self.nr_of_subarrays + 1):\n subarray = self._tel.csp.subarray(index)\n builder.set_waiting_on(subarray).for_attribute(\"adminMode\").to_become_equal_to(\n \"ONLINE\", ignore_first=False\n )\n builder.set_waiting_on(subarray).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\"], ignore_first=False\n )\n return builder\n\n def undo_set_online(self):\n \"\"\"Domain logic for setting devices in csp to offline.\"\"\"\n controller_name = self._tel.csp.controller\n controller = con_config.get_device_proxy(controller_name)\n self._log(f\"Setting adminMode for {controller_name} to '1' (OFFLINE)\")\n controller.write_attribute(\"adminmode\", 1)\n for index in range(1, self.nr_of_subarrays + 1):\n subarray_name = self._tel.csp.subarray(index)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"Setting adminMode for {subarray_name} to '1' (OFFLINE)\")\n subarray.write_attribute(\"adminmode\", 1)\n\n def set_wait_for_undo_set_online(self) -> MessageBoardBuilder:\n \"\"\"\n Domain logic for waiting for setting to offline to be complete.\n\n :return: builder\n \"\"\"\n controller_name = self._tel.csp.controller\n builder = get_message_board_builder()\n builder.set_waiting_on(controller_name).for_attribute(\"adminMode\").to_become_equal_to(\n \"OFFLINE\", ignore_first=False\n )\n for index in range(1, self.nr_of_subarrays + 1):\n subarray = self._tel.csp.subarray(index)\n builder.set_waiting_on(subarray).for_attribute(\"adminMode\").to_become_equal_to(\n \"OFFLINE\", ignore_first=False\n )\n return builder\n\n def set_wait_for_doing_set_online(self) -> MessageBoardBuilder:\n \"\"\"\n Not implemented.\n\n :raises NotImplementedError: Raises the error when\n implementation is not done.\n \"\"\"\n raise NotImplementedError()\n\n\nclass CSPAbortStep(base.AbortStep, LogEnabled):\n\n \"\"\"Implementation of Abort Step for CSP.\"\"\"\n\n def do_abort(self, sub_array_id: int):\n \"\"\"Domain logic for running a abort on subarray in csp.\n\n This implments the scan method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with Abort command\")\n subarray.command_inout(\"Abort\")\n\n def set_wait_for_do_abort(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"Domain logic specifying what needs to be waited for abort is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\n \"ABORTED\", ignore_first=True\n )\n return builder\n\n\nclass CSPObsResetStep(base.ObsResetStep, LogEnabled):\n\n \"\"\"Implementation of ObsReset Step for CSP.\"\"\"\n\n def set_wait_for_do_obsreset(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic for running a obsreset on subarray in csp.\n\n This implments the scan method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\n \"IDLE\", ignore_first=True\n )\n return builder\n\n def do_obsreset(self, sub_array_id: int):\n \"\"\"\n Domain logic specifying what needs to be waited for obsreset is done.\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with ObsReset command\")\n subarray.command_inout(\"Obsreset\")\n\n def undo_obsreset(self, sub_array_id: int):\n \"\"\"\n Domain logic for releasing resources on a subarray in csp.\n\n This implments the tear_down_subarray method on the entry_point.\n\n :param sub_array_id: The index id of the subarray to control\n \"\"\"\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with ReleaseAllResources\")\n subarray.set_timeout_millis(6000)\n subarray.command_inout(\"ReleaseAllResources\")\n\n def set_wait_for_undo_obsreset(self, sub_array_id: int) -> MessageBoardBuilder:\n \"\"\"\n Domain logic specifying what needs to be waited for\n subarray releasing resources is done.\n\n :param sub_array_id: The index id of the subarray to control\n :return: builder\n \"\"\"\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\"EMPTY\")\n\n return builder\n\n\nclass CSPRestart(base.RestartStep, LogEnabled):\n def do_restart(self, sub_array_id: int):\n subarray_name = self._tel.csp.subarray(sub_array_id)\n subarray = con_config.get_device_proxy(subarray_name)\n self._log(f\"commanding {subarray_name} with Restart command\")\n subarray.command_inout(\"Restart\")\n\n def set_wait_for_do_restart(self, sub_array_id: int) -> MessageBoardBuilder:\n builder = get_message_board_builder()\n subarray_name = self._tel.csp.subarray(sub_array_id)\n builder.set_waiting_on(subarray_name).for_attribute(\"obsState\").to_become_equal_to(\n \"EMPTY\", ignore_first=True\n )\n return builder\n\n\nclass CSPWaitReadyStep(base.WaitReadyStep, LogEnabled):\n def __init__(self, nr_of_subarrays: int) -> None:\n super().__init__()\n self._nr_of_subarrays = nr_of_subarrays\n\n def set_wait_for_sut_ready_for_session(self) -> MessageBoardBuilder:\n builder = get_message_board_builder()\n for sub_id in range(1, self._nr_of_subarrays + 1):\n subarray = self._tel.csp.subarray(sub_id)\n builder.set_waiting_on(subarray).for_attribute(\"state\").to_become_equal_to(\n [\"OFF\", \"ON\", \"DISABLE\"], ignore_first=False\n )\n return builder\n\n\nclass CSPEntryPoint(CompositeEntryPoint):\n \"\"\"Derived Entrypoint scoped to CSP element.\"\"\"\n\n nr_of_subarrays = 2\n\n def __init__(self, observation: Observation | None = None) -> None:\n \"\"\"\n Init Object\n\n :param observation: An instance of the Observation class or None.\n If None, a new instance of Observation will be created.\n \"\"\"\n super().__init__()\n if observation is None:\n observation = Observation()\n self.observation = observation\n self.set_online_step = CSPSetOnlineStep(self.nr_of_subarrays)\n self.start_up_step = StartUpStep(self.nr_of_subarrays)\n self.assign_resources_step = CspAssignResourcesStep(observation)\n self.configure_scan_step = CspConfigureStep(observation)\n self.scan_step = CspScanStep(observation)\n self.abort_step = CSPAbortStep()\n self.obsreset_step = CSPObsResetStep()\n self.restart_step = CSPRestart()\n self.wait_ready = CSPWaitReadyStep(self.nr_of_subarrays)\n\n\ncsp_mid_assign_resources_template = {\n \"interface\": \"https://schema.skao.int/ska-csp-configure/2.0\",\n \"subarray_id\": 1,\n \"dish\": {\"receptor_ids\": [\"001\", \"002\"]},\n}\n\ncsp_mid_configure_scan_template = {\n \"interface\": \"https://schema.skao.int/ska-csp-configure/2.0\",\n \"subarray\": {\"subarray_name\": \"science period 23\"},\n \"common\": {\n \"config_id\": \"sbi-mvp01-20200325-00001-science_A\",\n \"frequency_band\": \"1\",\n \"subarray_id\": \"1\",\n },\n \"cbf\": {\n \"delay_model_subscription_point\": \"sys/tg_test/1/string_scalar\",\n \"fsp\": [\n {\n \"fsp_id\": 1,\n \"function_mode\": \"CORR\",\n \"frequency_slice_id\": 1,\n \"integration_factor\": 1,\n \"zoom_factor\": 0,\n \"channel_averaging_map\": [[0, 2], [744, 0]],\n \"channel_offset\": 0,\n \"output_link_map\": [[0, 0], [200, 1]],\n },\n {\n \"fsp_id\": 2,\n \"function_mode\": \"CORR\",\n \"frequency_slice_id\": 2,\n \"integration_factor\": 1,\n \"zoom_factor\": 1,\n \"zoom_window_tuning\": 650000,\n \"channel_averaging_map\": [[0, 2], [744, 0]],\n \"channel_offset\": 744,\n \"output_link_map\": [[0, 4], [200, 5]],\n \"output_host\": [[0, \"192.168.1.1\"]],\n \"output_port\": [[0, 9744, 1]],\n },\n ],\n \"vlbi\": {},\n },\n \"pss\": {},\n \"pst\": {},\n \"pointing\": {\n \"target\": {\n \"system\": \"ICRS\",\n \"target_name\": \"Polaris Australis\",\n \"ra\": \"21:08:47.92\",\n \"dec\": \"-88:57:22.9\",\n }\n },\n}\n\ncsp_low_assign_resources = {\n \"interface\": \"https://schema.skao.int/ska-low-csp-assignresources/2.0\",\n \"common\": {\"subarray_id\": 1},\n \"lowcbf\": {\n \"resources\": [\n {\n \"device\": \"fsp_01\",\n \"shared\": True,\n \"fw_image\": \"pst\",\n \"fw_mode\": \"unused\",\n },\n {\n \"device\": \"p4_01\",\n \"shared\": True,\n \"fw_image\": \"p4.bin\",\n \"fw_mode\": \"p4\",\n },\n ]\n },\n}\n\ncsp_low_configure_scan = {\n \"interface\": \"https://schema.skao.int/ska-csp-configure/2.0\",\n \"subarray\": {\"subarray_name\": \"science period 23\"},\n \"common\": {\n \"config_id\": \"sbi-mvp01-20200325-00001-science_A\",\n \"subarray_id\": 1,\n },\n \"lowcbf\": {\n \"stations\": {\n \"stns\": [[1, 0], [2, 0], [3, 0], [4, 0]],\n \"stn_beams\": [\n {\n \"beam_id\": 1,\n \"freq_ids\": [64, 65, 66, 67, 68, 68, 70, 71],\n \"boresight_dly_poly\": \"url\",\n }\n ],\n },\n \"timing_beams\": {\n \"beams\": [\n {\n \"pst_beam_id\": 13,\n \"stn_beam_id\": 1,\n \"offset_dly_poly\": \"url\",\n \"stn_weights\": [0.9, 1.0, 1.0, 0.9],\n \"jones\": \"url\",\n \"dest_ip\": [\"10.22.0.1:2345\", \"10.22.0.3:3456\"],\n \"dest_chans\": [128, 256],\n \"rfi_enable\": [\"true\", \"true\", \"true\"],\n \"rfi_static_chans\": [1, 206, 997],\n \"rfi_dynamic_chans\": [242, 1342],\n \"rfi_weighted\": 0.87,\n }\n ]\n },\n \"search_beams\": \"tbd\",\n \"zooms\": \"tbd\",\n },\n}\n\n\ncsp_low_scan = {\n \"common\": {\"subarray_id\": 1},\n \"lowcbf\": {\n \"scan_id\": 987654321,\n \"unix_epoch_seconds\": 1616971738,\n \"timestamp_ns\": 987654321,\n \"packet_offset\": 123456789,\n \"scan_seconds\": 30,\n },\n}\n","sub_path":"tests/resources/models/csp_model/entry_point.py","file_name":"entry_point.py","file_ext":"py","file_size_in_byte":28449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"619137278","text":"import hashlib\nimport string\nimport random\nimport socket\n\n# start listening for messages\ns = socket.socket()\nhost = '127.0.0.1'\nport = 1234 \ns.bind((host, port))\ns.listen(5)\n\nwhile True:\n # accept data from a client\n c, addr = s.accept()\n\n # receive and split message into the components of the block\n rec = c.recv(1024)\n split = rec.split('.')\n nonce = split[0]\n p_prev = split[1]\n p_root = split[2]\n time_stamp = split[3]\n target = split[4]\n\n # hash block\n hash_val = hashlib.sha256(p_prev + p_root + time_stamp + nonce)\n hash_as_int = int(hash_val.hexdigest(), 16)\n\n # verify the hash is smaller than the target\n if (hash_as_int < target):\n print('YES')\n else: \n print('NO')\n\n c.close()","sub_path":"puzzle_verifier.py","file_name":"puzzle_verifier.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"333115142","text":"#!/usr/bin/python3.4\n# -*-coding:Utf-8 \n\nclass\tEtudiant:\n\n\t\"\"\"Classe représentant un étudiant. On représente un étudiant par son prénom (attribut prenom), son âge (attribut age) et sa note moyenne (attribut moyenne, entre 0 et 20). Paramètres du constructeur : prenom -- le prénom de l'étudiant / age -- l'âge de l'étudiant / moyenne -- la moyenne de l'étudiant\"\"\"\n\n\tdef __init__(self, prenom, age, moyenne):\n\t\tself.prenom = prenom\n\t\tself.age = age\n\t\tself.moyenne = moyenne\n\n\tdef __repr__(self):\n\t\treturn \"\".format(self.prenom, self.age, self.moyenne)\n\t\n\netudiants = [\n Etudiant(\"Clément\", 14, 16),\n Etudiant(\"Charles\", 12, 15),\n Etudiant(\"Oriane\", 14, 18),\n Etudiant(\"Thomas\", 11, 12),\n Etudiant(\"Damien\", 12, 15),\n]\n\nfrom operator import attrgetter\nprint(sorted(etudiants, key = attrgetter(\"moyenne\")))\nprint(\"By age then by med \\n{}\".format(sorted(etudiants, key = attrgetter(\"age\",\"moyenne\"))))\n","sub_path":"Chap02/test_sort_obj.py","file_name":"test_sort_obj.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"94504708","text":"\nfrom ..files import *\n\n\n__all__ = ['MegaFileobject', 'MegaFile', 'MegaFolder']\n\n\nclass MegaFileobject(IDFileobject):\n def _init(self):\n self._old_versions = set()\n\n @classmethod\n def from_metadata(cls, parent, meta):\n name = meta['a']['n']\n host = parent.host\n path = parent.path.childpath(name, escape=False)\n\n # if multiple files have the same name, take the newest one\n oldobj = host._filesystem.get(path)\n if oldobj is not None:\n if oldobj.is_folder:\n oldobj = None # FIXME: handle duplicate folders\n else:\n oldobj = oldobj.__dict__.copy()\n\n obj = cls(parent.host, path)\n obj._update_metadata_local(meta)\n\n # if multiple files have the same name, take the newest one\n if oldobj is not None:\n if '_server_modification_time' in oldobj and oldobj['_server_modification_time'] > obj.server_modification_time:\n id = obj._id\n assert id is not None, obj\n obj.__dict__.update(oldobj)\n obj._old_versions.add(id)\n elif '_id' in oldobj:\n obj._old_versions.add(oldobj['_id'])\n\n return obj\n\n _mega_obj = None\n\n @property\n def _megaobj(self):\n if self._mega_obj is None:\n _ = self.id\n return self._mega_obj\n\n @_megaobj.setter\n def _megaobj(self, obj):\n self._mega_obj = obj\n\n def _load_metadata(self):\n _ = self.id\n\n def _update_metadata_local(self, meta):\n self._megaobj = meta\n\n assert meta.get('h') is not None, meta\n self.id = meta['h']\n\n self.server_modification_time = meta['ts']\n\n def _deleted(self):\n super()._deleted()\n self._mega_obj = None\n\n def _delete_old_versions(self):\n while self._old_versions:\n dupe = self._old_versions.pop()\n try:\n self.do_with_exponential_backoff(self.host._mega.destroy, dupe)\n except:\n self._old_versions.add(dupe)\n raise\n\n def _try_delete_old_versions(self):\n try:\n self._delete_old_versions()\n except Exception as e:\n #~ print('error deleting old versions of \"{}\": {}'.format(self, e))\n pass\n\n\nclass MegaFile(MegaFileobject, File):\n def _update_metadata_local(self, meta):\n assert 'iv' in meta, meta\n super()._update_metadata_local(meta)\n\n self.size = meta['s']\n\n def _get_server_modification_time(self):\n self._load_metadata()\n return self._server_modification_time\n\n def _get_size(self):\n self._load_metadata()\n return self._size\n\n\nclass MegaFolder(MegaFileobject, Folder):\n def _update_metadata_local(self, meta):\n super()._update_metadata_local(meta)\n\n def _get_children(self):\n children = self.host._mega.get_files_in_node(self.id)\n children = [file_or_folder_from_metadata(\n self, meta) for meta in children.values()]\n # ~ for child in children:\n #~ child._try_delete_old_versions()\n return children\n\n # def _get_size(self):\n # self._load_metadata()\n # return self._size\n\n\ndef file_or_folder_from_metadata(parent, meta):\n if meta['t'] == 1:\n cls = MegaFolder\n else:\n cls = MegaFile\n return cls.from_metadata(parent, meta)\n","sub_path":"webdrives/mega/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"447321328","text":"#!/usr/bin/env python3\n\nfrom models.model import db\nfrom models.account import Account\n\nfor email in ['toto@epsi.fr', 'titi@epsi.fr']:\n a = Account(email)\n a.IsAdmin = False\n a.FirstName = email\n db.session.add(a)\n db.session.commit()\n\nprint(Account.query.all())\n\n","sub_path":"populate_db.py","file_name":"populate_db.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"127536520","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('questions', '0010_answer_resolve'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Raiting',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('like', models.IntegerField(default=0)),\n ('resolve', models.IntegerField(default=0)),\n ],\n ),\n migrations.RemoveField(\n model_name='answer',\n name='likes',\n ),\n migrations.RemoveField(\n model_name='answer',\n name='resolve',\n ),\n migrations.AddField(\n model_name='raiting',\n name='answer',\n field=models.ForeignKey(to='questions.Answer'),\n ),\n migrations.AddField(\n model_name='raiting',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n ]\n","sub_path":"diabetes_project/apps/questions/migrations/0011_auto_20151016_0956.py","file_name":"0011_auto_20151016_0956.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319056435","text":"from discord.ext import commands\nfrom discord import embeds\nimport json\nimport requests\n\n\"\"\"\n wiki.py for BitBot4.0 By Cameron Whittaker (c) 2019\n\"\"\"\n\nclass Wiki:\n def __init__(self, bot):\n self.bot = bot\n\n\n\n @commands.command(pass_context=True)\n async def wiki(self, ctx, *args):\n search_query = \" \".join(args)\n\n # # Use wiki API to get a JSON search result from the search_query\n # result = requests.get(\"https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=\" + search_query).content\n #\n # json_result = json.loads(result)\n # entries = json_result['query']['search']\n #\n # if len(entries) > 1:\n # # Search term is ambigious, need user to select entry.\n # string = \"\"\n # for entry in entries:\n # string += str(entries.index(entry) + 1) + \")\\t\" + entry['title'] + \"\\n\"\n #\n # await self.bot.say(\"**Found multiple entries. Type `$wiki select ` to show a specific entry:-**\\n\"\n # \"```\\n{}```\".format(string))\n # return\n\n # Only one entry. Let's make a new request to get said entry\n\n raw_result = requests.get(\"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts\"\n \"&exlimit=max&explaintext&exintro&titles={}&redirects=\".format(search_query)).content\n\n\n json_result = json.loads(raw_result)\n page_data = list(json_result['query']['pages'].values())[0]\n\n if \"extract\" not in page_data.keys():\n # wiki results came back with no results\n await self.bot.say(\":x: **No Wikipedia entries matching `{}`**\".format(search_query))\n return\n\n elif page_data['extract'].startswith(page_data['title'] + \" may refer to:\"):\n # wiki result came back with a result, but it is a disambiguation page.\n await self.bot.say(\"*This feature is a WIP and currently is not capable of disambiguous searching. Use specific search terms.*\")\n return\n\n # Actual wiki entry\n\n string = \"*\" + page_data['extract'][:(2000 - 1500)]\n string += \"...*\\n\\n *To see the full entry, visit <{}>*\".format(\"https://en.wikipedia.org/wiki/\" + page_data['title'].replace(\" \", \"_\"))\n\n # Discord embed code.\n embed = embeds.Embed(color=16777215)\n embed.set_author(name=\"Wikipedia Entry\")\n embed.set_footer(text=\"BitBot 4.0 Wikipedia Search\")\n embed.add_field(name=page_data['title'], value=string, inline=True)\n\n await self.bot.say(embed=embed)\n return\n\n\n\ndef setup(bot):\n bot.add_cog(Wiki(bot))","sub_path":"modules/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":2695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"192326231","text":"import sys\n\n\ndef make_partition(size, number_partitions):\n blocks = []\n value = size // number_partitions\n\n if number_partitions <= 1:\n return [0]\n\n if value < 1:\n print(\"Could not make partitions for {} elements. Partitions TOO small\".format(number_partitions),\n file=sys.stderr)\n return blocks\n\n for k in range(number_partitions):\n blocks.append(k * value)\n\n return blocks\n\n\ndef get_partition_range(part_list, _part):\n start_end = []\n\n if _part == 0:\n print(\"First partition MUST be one (1) not {}\".format(_part), file=sys.stderr)\n return [0]\n\n if _part > len(part_list):\n print(\"The part ({}) CANNOT be greater to the number of fractions\".format(_part), file=sys.stderr)\n return [0]\n\n for k in range(_part - 1, _part + 1):\n start_end.append(part_list[k])\n\n if k + 1 >= len(part_list):\n return start_end\n\n return start_end\n","sub_path":"Utilities/FilePartition.py","file_name":"FilePartition.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"84803890","text":"import io\nimport random\nimport sys\nimport json\nimport time\nimport datetime\nfrom contextlib import contextmanager\nimport re\nimport os\nimport unittest\nimport argparse\nimport json\nimport ir_datasets\n\n\n@contextmanager\ndef tmp_environ(**kwargs):\n orig_values = {}\n for key, value in kwargs.items():\n orig_values[key] = os.environ.get(key)\n os.environ[key] = value\n try:\n yield\n finally:\n for key, value in kwargs.items():\n orig_value = orig_values[key]\n if orig_value is not None:\n os.environ[key] = orig_value\n else:\n del os.environ[key]\n\n\nclass TestDownloads(unittest.TestCase):\n dlc_filter = None\n output_path = None\n rand_delay = None # useful for being nice to servers when running tests by adding a random delay between tests\n output_data = []\n\n def test_downloads(self):\n with open('ir_datasets/etc/downloads.json') as f:\n data = json.load(f)\n try:\n self._test_download_iter(data)\n finally:\n if self.output_path is not None:\n with open(self.output_path, 'wt') as f:\n json.dump(self.output_data, f)\n\n def _test_download_iter(self, data, prefix=''):\n with tmp_environ(IR_DATASETS_DL_TRIES='10'): # give the test up to 10 attempts to download\n if 'url' in data and 'expected_md5' in data:\n if self.dlc_filter is None or re.search(self.dlc_filter, prefix) and not data.get('skip_test', False):\n with self.subTest(prefix):\n if self.rand_delay is not None:\n # sleep in range of [0.5, 1.5] * rand_delay seconds\n time.sleep(random.uniform(self.rand_delay * 0.5, self.rand_delay * 1.5))\n record = {\n 'name': prefix,\n 'url': data['url'],\n 'time': datetime.datetime.now().isoformat(),\n 'duration': None,\n 'result': 'IN_PROGRESS',\n 'fail_messagae': None,\n 'md5': data['expected_md5'],\n 'size': 0,\n }\n self.output_data.append(record)\n start = time.time()\n try:\n download = ir_datasets.util.Download([ir_datasets.util.RequestsDownload(data['url'])], expected_md5=data['expected_md5'], stream=True)\n with download.stream() as stream:\n inp = stream.read(io.DEFAULT_BUFFER_SIZE)\n while len(inp) > 0:\n record['size'] += len(inp)\n inp = stream.read(io.DEFAULT_BUFFER_SIZE)\n record['duration'] = time.time() - start\n record['result'] = 'PASS'\n except KeyboardInterrupt:\n record['duration'] = time.time() - start\n record['result'] = 'USER_SKIP'\n self.skipTest('Test skipped by user')\n self.output_data.append({})\n except Exception as ex:\n record['duration'] = time.time() - start\n record['result'] = 'FAIL'\n record['fail_messagae'] = str(ex)\n raise\n elif 'instructions' in data:\n pass\n else:\n for key in data.keys():\n self._test_download_iter(data[key], prefix=f'{prefix}/{key}' if prefix else key)\n\n\nif __name__ == '__main__':\n argv = sys.argv\n for i, arg in enumerate(argv):\n if arg == '--filter':\n TestDownloads.dlc_filter = argv[i+1]\n argv = argv[:i] + argv[i+2:]\n for i, arg in enumerate(argv):\n if arg == '--output':\n TestDownloads.output_path = argv[i+1]\n argv = argv[:i] + argv[i+2:]\n for i, arg in enumerate(argv):\n if arg == '--randdelay':\n TestDownloads.rand_delay = float(argv[i+1])\n argv = argv[:i] + argv[i+2:]\n unittest.main(argv=argv)\n","sub_path":"test/downloads.py","file_name":"downloads.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"53139558","text":"data = []\ncount = 0\nwith open('reviews.txt', 'r') as f:\n\tfor line in f:\n\t\tdata.append(line)\n\t\tcount += 1\n\t\tif count % 1000 == 0:\n\t\t\tprint(len(data))\nprint('檔案讀取完了,總共有', count, '筆資料')\n\nwc = {}\nfor d in data:\n\twords = d.split()\n\tfor word in words:\n\t\tif word in wc:\n\t\t\twc[word] += 1\n\n\t\telse:\n\t\t\twc[word] = 1\nfor word in wc:\n\tif wc[word] > 1000000:\n\t\tprint(word, wc[word])\nprint(len(wc))\nprint(wc['a'])\n\nwhile True:\n\tword = input('你想查什麼字: ')\n\tif word == 'q':\n\t\tbreak\n\tif word in wc:\n\t\tprint(word, '出現的次數為', wc[word])\n\telse:\n\t\tprint('這個字不存在')\nprint('感謝您使用本查詢')\n\n\n\n\n\n\n\n\n\n\n# print(len(data))\n# print(data[0])\n# print('-------------')\n# print(data[1])\n\n# sum_len = 0 \n# for d in data:\n# \tsum_len = sum_len + len(d)\n# print('平均資料的長度為: ', sum_len / len(data))\n\n# new = []\n# for d in data:\n# \tif len(d) < 100:\n# \t\tnew.append(d)\n# print('一共有', len(new), '筆資料長度小於100')\n\n\t\n","sub_path":"data_for.py","file_name":"data_for.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"238243533","text":"import tensorflow as tf\nimport input_data\n\nVERSION = \"simple.rnn.56.14.2\"\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\ntrain_x_data, train_y_data = mnist.train.images, mnist.train.labels\ntrain_data_len = len(train_x_data)\ntest_x_data, test_y_data = mnist.test.images, mnist.test.labels\ntest_data_len = len(test_x_data)\n\nRNN_SIZE = 56\nRNN_DEPTH = 2\nTIMESTEP_SIZE = 14\nBATCH_SIZE = 2048\n\nX = tf.placeholder(\"float\", [BATCH_SIZE, 784])\nY = tf.placeholder(\"float\", [BATCH_SIZE, 10])\n\n# RNN model\none_cell = tf.nn.rnn_cell.BasicRNNCell(RNN_SIZE)\nrnn_cell = tf.nn.rnn_cell.MultiRNNCell([one_cell] * RNN_DEPTH)\nstate = tf.zeros([BATCH_SIZE, rnn_cell.state_size])\nX_split = tf.split(1, TIMESTEP_SIZE, X)\noutputs, state = tf.nn.rnn(rnn_cell, X_split, state)\n\ninitializer = tf.contrib.layers.xavier_initializer()\n\nW = tf.get_variable(\"W\", shape=[RNN_SIZE, 10], initializer=initializer)\nb = tf.Variable(tf.random_uniform([10], -1.0, 1.0))\n\nmodel = tf.matmul(outputs[-1], W) + b\nmodel_with_softmax = tf.nn.softmax(model)\n\n# cross entropy\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model, Y))\n\nLEARNING_RATE = 0.001\nlearning_rate = tf.Variable(LEARNING_RATE)\noptimizer = tf.train.RMSPropOptimizer(LEARNING_RATE, 0.9)\ntrain = optimizer.minimize(cost)\n\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n\n \"\"\"\n Variables and functions about\n Loading and Saving Data.\n \"\"\"\n saver = tf.train.Saver()\n SAVE_DIR = 'save_files'\n import os\n if not os.path.isdir(SAVE_DIR):\n os.mkdir(SAVE_DIR)\n MODEL_SAVE_PATH = \"{0}/{1}.{2}.ckpt\".format(SAVE_DIR, os.path.basename(__file__), VERSION)\n INFO_FILE_PATH = \"{0}/{1}.{2}.info\".format(SAVE_DIR, os.path.basename(__file__), VERSION)\n\n def do_load():\n start_epoch = 1\n try:\n epochs = []\n avg_costs = []\n avg_accuracys = []\n learning_rates = []\n\n with open(INFO_FILE_PATH, \"r\") as f:\n while True:\n line = f.readline()\n if not line:\n break\n data = line.split()\n epochs.append(int(data[0]))\n avg_costs.append(float(data[1]))\n avg_accuracys.append(float(data[2]))\n learning_rates.append(float(data[3]))\n saver.restore(sess, MODEL_SAVE_PATH)\n print(\"[*] The save file exists!\")\n\n print(\"Do you wanna continue? (y/n) \", end=\"\", flush=True)\n if input() == 'n':\n print(\"not continue...\")\n print(\"[*] Start a training from the beginning.\")\n os.remove(INFO_FILE_PATH)\n os.remove(MODEL_SAVE_PATH)\n sess.run(init)\n else:\n print(\"continue...\")\n print(\"[*] Start a training from the save file.\")\n start_epoch = epochs[-1] + 1\n for epoch, avg_cost, avg_accuracy, learning_rate in zip(epochs, avg_costs, avg_accuracys,\n learning_rates):\n print(\"Epoch {0} with learning rate = {1} : avg_cost = {2}, avg_accuracy = {3}\".\n format(epoch, learning_rate, avg_cost, avg_accuracy))\n\n except FileNotFoundError:\n print(\"[*] There is no save files.\")\n print(\"[*] Start a training from the beginning.\")\n sess.run(init)\n\n return start_epoch\n\n def do_save():\n print(\"[progress] Saving result! \\\"Never\\\" exit!!\", end='', flush=True)\n saver.save(sess, MODEL_SAVE_PATH)\n with open(INFO_FILE_PATH, \"a\") as f:\n f.write(\"{0} {1} {2} {3}\".format(epoch, avg_cost, avg_accuracy, LEARNING_RATE) + os.linesep)\n print(\"\", end='\\r', flush=True)\n\n\n \"\"\"\n Variables and functions about\n Training and Testing Model\n \"\"\"\n DISPLAY_SAVE_STEP = 10\n TRAINING_EPOCHS = 500\n\n def do_train():\n print(\"[progress] Training model for optimizing cost!\", end='', flush=True)\n # Loop all batches for training\n avg_cost = 0\n for end in range(BATCH_SIZE, test_data_len + 1, BATCH_SIZE):\n start = end - BATCH_SIZE\n batch_x = train_x_data[start:end]\n batch_y = train_y_data[start:end]\n data = {X: batch_x, Y: batch_y}\n sess.run(train, feed_dict=data)\n avg_cost += sess.run(cost, feed_dict=data) * len(batch_x) / train_data_len\n\n print(\"\", end='\\r', flush=True)\n return avg_cost\n\n def do_test():\n print(\"[progress] Testing model for evaluating accuracy!\", end='', flush=True)\n correct_prediction = tf.equal(tf.argmax(model_with_softmax, 1), tf.argmax(Y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\n # Loop all batches for test\n avg_accuracy = 0\n for end in range(BATCH_SIZE, test_data_len+1, BATCH_SIZE):\n start = end - BATCH_SIZE\n batch_x = test_x_data[start:end]\n batch_y = test_y_data[start:end]\n data = {X: batch_x, Y: batch_y}\n avg_accuracy += accuracy.eval(data) * len(batch_x) / test_data_len\n\n print(\"\", end='\\r', flush=True)\n return avg_accuracy\n\n\n ##### Start of flow\n\n start_epoch = do_load()\n\n if start_epoch == 1:\n avg_accuracy = do_test()\n print(\"After initializing, accuracy = {0}\".format(avg_accuracy))\n\n # Training cycle\n for epoch in range(start_epoch, TRAINING_EPOCHS + 1):\n\n avg_cost = do_train()\n\n # Logging the result\n if epoch % DISPLAY_SAVE_STEP == start_epoch % DISPLAY_SAVE_STEP or epoch == TRAINING_EPOCHS:\n avg_accuracy = do_test()\n do_save()\n\n # Print Result\n print(\"Epoch {0} : avg_cost = {1}, accuracy = {2}\".format(epoch, avg_cost, avg_accuracy))","sub_path":"MNIST/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":5940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"512654556","text":"import concurrent.futures\nimport urllib.request\n\nURLS = ['http://www.foxnews.com/',\n 'http://www.cnn.com/',\n 'http://europe.wsj.com/',\n 'http://www.bbc.co.uk/',\n 'http://yaegar.me',\n 'http://laike9m.com',\n 'http://google.com',\n ]\n\n# Retrieve a single page and report the url and contents\ndef load_url(url, timeout):\n with urllib.request.urlopen(url, timeout=timeout) as conn:\n return conn.read()\n\n# We can use a with statement to ensure threads are cleaned up promptly\nwith concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n # Start the load operations and mark each future with its URL\n future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}\n for future in concurrent.futures.as_completed(future_to_url):\n url = future_to_url[future]\n try:\n data = future.result()\n except Exception as exc:\n print('%r generated an exception: %s' % (url, exc))\n else:\n print('%r page is %d bytes' % (url, len(data)))\n\n\nimport time\ndef wait_on_b():\n # time.sleep(6)\n print(b.result()) # b will never complete because it is waiting on a.\n return 5\n\ndef wait_on_a():\n time.sleep(5)\n print(a.result()) # a will never complete because it is waiting on b.\n return 6\n\n\nexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=2)\na = executor.submit(wait_on_b)\nb = executor.submit(wait_on_a)\n","sub_path":"concurrent-and-future.py","file_name":"concurrent-and-future.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"162542796","text":"#\n# abc074 c\n#\nimport sys\nfrom io import StringIO\nimport unittest\n\n\nclass TestClass(unittest.TestCase):\n def assertIO(self, input, output):\n stdout, stdin = sys.stdout, sys.stdin\n sys.stdout, sys.stdin = StringIO(), StringIO(input)\n resolve()\n sys.stdout.seek(0)\n out = sys.stdout.read()[:-1]\n sys.stdout, sys.stdin = stdout, stdin\n self.assertEqual(out, output)\n\n def test_入力例_1(self):\n input = \"\"\"1 2 10 20 15 200\"\"\"\n output = \"\"\"110 10\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_2(self):\n input = \"\"\"1 2 1 2 100 1000\"\"\"\n output = \"\"\"200 100\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_3(self):\n input = \"\"\"17 19 22 26 55 2802\"\"\"\n output = \"\"\"2634 934\"\"\"\n self.assertIO(input, output)\n\n\ndef resolve():\n A, B, C, D, E, F = map(int, input().split())\n N = 0\n W = 100*A\n S = 0\n for i in range(31):\n for j in range(31):\n for k in range(101):\n for l in range(101):\n w = A*i+B*j\n s = C*k+D*l\n if w == 0 or 100*w+s > F or s > w*E:\n break\n n = 100*s / (100*w+s)\n if n > N:\n N = n\n W = 100*w+s\n S = s\n print(f\"{W} {S}\")\n\n\nif __name__ == \"__main__\":\n # unittest.main()\n resolve()\n","sub_path":"abc074/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"408420557","text":"'''\nWrite a procedure char_freq_table() that, when run in a terminal, accepts a\nfile name from the user, builds a frequency listing of the characters contained\nin the file, and prints a sorted and nicely formatted character frequency table\nto the screen.\n'''\n\nimport os\nimport profile\n\n\nclass CharFreqTable(object):\n\n def __init__(self, filename):\n self.filename = os.path.abspath(filename)\n self.char_freq = {}\n self._count_chars(self._read_file(filename))\n\n def _read_file(self, filename):\n try:\n file = open(filename, \"rb\")\n data = file.read()\n file.close()\n data = [chr(i) for i in data if chr(i).isalpha()]\n return data\n except(FileNotFoundError):\n raise(Exception(\"nie ma takiego pliku: %s\" % self.filename))\n\n def _count_chars(self, data):\n for c in data:\n if c not in self.char_freq:\n self.char_freq[c] = 1\n self.char_freq[c] += 1\n\n def __str__(self):\n result = []\n result.append(filename)\n for k in sorted(self.char_freq.keys()):\n result.append(\"%s = %d\" % (k, self.char_freq[k]))\n return \"\\n\".join(result)\n\n\nif __name__ == '__main__':\n filename = input(\"podaj plik: \")\n cft = CharFreqTable(filename)\n print(cft)\n","sub_path":"simple46exercises/io/zadanie34.py","file_name":"zadanie34.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"567521185","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 11 05:51:33 2017\n\n@author: Camilo Cruz\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCount the number of times a substring is found on a larger string\nCreated on Wed Nov 02 23:39:59 2016\n@author: Camilo\nNote: Erase the '#' to visualize the execution\n\"\"\"\n\nword = 'cam'\nstring = 'pppppppaeiouppppppaeioupzaaaaaaeiosxyz' #modify for raw_input\ncount = 0\nfor_count = 0\nsubstr = string[0]\nmax_str = string[0]\n\n#range_max = len(string) - len(word) + 1\n\nfor i in range(1, len(string)):\n for_count += 1\n #print for_count, 'Substr:' + substr, 'Max:' + max_str\n \n \n if string[i] >= string[i-1]:\n substr += string[i]\n #max_str += string[i] \n if len(substr) > len(max_str):\n max_str = substr\n \n elif string[i] < string[i-1] :\n #substr += string[i]\n #max_str = substr\n substr = string[i]\n \n \n\nprint ('Longest substring in alphabetical order is: ') + max_str\n#print for_count \n","sub_path":"6.00.1x_Introduction_to_Computer_Science_and_Programming_Using_Python/Week_1/Problem Set 1/PS_1_3.py","file_name":"PS_1_3.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"354544745","text":"import abc\nfrom collections import namedtuple\nfrom enum import Enum\n\nimport six\n\nfrom dagster import check\nfrom dagster.core.definitions.repository import RepositoryDefinition\nfrom dagster.core.definitions.schedule import ScheduleDefinition, ScheduleDefinitionData\nfrom dagster.core.errors import DagsterError\nfrom dagster.core.instance import DagsterInstance\nfrom dagster.serdes import whitelist_for_serdes\nfrom dagster.utils.error import SerializableErrorInfo\n\n\nclass DagsterSchedulerError(DagsterError):\n '''Base class for all Dagster Scheduler errors'''\n\n\nclass DagsterScheduleReconciliationError(DagsterError):\n '''Error raised during schedule state reconcilation. During reconcilation, exceptions that are\n raised when trying to start or stop a schedule are collected and passed to this wrapper exception.\n The individual exceptions can be accessed by the `errors` property. '''\n\n def __init__(self, preamble, errors, *args, **kwargs):\n self.errors = errors\n\n error_msg = preamble\n error_messages = []\n for i_error, error in enumerate(self.errors):\n error_messages.append(str(error))\n error_msg += '\\n Error {i_error}: {error_message}'.format(\n i_error=i_error + 1, error_message=str(error)\n )\n\n self.message = error_msg\n self.error_messages = error_messages\n\n super(DagsterScheduleReconciliationError, self).__init__(error_msg, *args, **kwargs)\n\n\nclass DagsterScheduleDoesNotExist(DagsterSchedulerError):\n '''Errors raised when ending a job for a schedule.'''\n\n\n@whitelist_for_serdes\nclass ScheduleStatus(Enum):\n RUNNING = 'RUNNING'\n STOPPED = 'STOPPED'\n ENDED = 'ENDED'\n\n\ndef get_schedule_change_set(old_schedules, new_schedule_defs):\n check.list_param(old_schedules, 'old_schedules', Schedule)\n check.list_param(new_schedule_defs, 'new_schedule_defs', ScheduleDefinition)\n\n new_schedules_defs_dict = {s.name: s for s in new_schedule_defs}\n old_schedules_dict = {s.name: s for s in old_schedules}\n\n new_schedule_defs_names = set(new_schedules_defs_dict.keys())\n old_schedules_names = set(old_schedules_dict.keys())\n\n added_schedules = new_schedule_defs_names - old_schedules_names\n changed_schedules = new_schedule_defs_names & old_schedules_names\n removed_schedules = old_schedules_names - new_schedule_defs_names\n\n changeset = []\n\n for schedule_name in added_schedules:\n changeset.append((\"add\", schedule_name, []))\n\n for schedule_name in changed_schedules:\n changes = []\n\n old_schedule_def = old_schedules_dict[schedule_name].schedule_definition_data\n new_schedule_def = new_schedules_defs_dict[schedule_name]\n\n if old_schedule_def.cron_schedule != new_schedule_def.cron_schedule:\n changes.append(\n (\"cron_schedule\", (old_schedule_def.cron_schedule, new_schedule_def.cron_schedule))\n )\n\n if len(changes) > 0:\n changeset.append((\"change\", schedule_name, changes))\n\n for schedule_name in removed_schedules:\n changeset.append((\"remove\", schedule_name, []))\n\n return changeset\n\n\nclass SchedulerDebugInfo(\n namedtuple('SchedulerDebugInfo', 'errors scheduler_config_info scheduler_info schedule_storage')\n):\n def __new__(cls, errors, scheduler_config_info, scheduler_info, schedule_storage):\n return super(SchedulerDebugInfo, cls).__new__(\n cls,\n errors=check.list_param(errors, 'errors', of_type=str),\n scheduler_config_info=check.str_param(scheduler_config_info, 'scheduler_config_info'),\n scheduler_info=check.str_param(scheduler_info, 'scheduler_info'),\n schedule_storage=check.list_param(schedule_storage, 'schedule_storage', of_type=str),\n )\n\n\nclass SchedulerHandle(object):\n def __init__(\n self, schedule_defs,\n ):\n check.list_param(schedule_defs, 'schedule_defs', ScheduleDefinition)\n self.schedule_defs = schedule_defs\n\n\n@whitelist_for_serdes\nclass Schedule(\n namedtuple('Schedule', 'schedule_definition_data status python_path repository_path')\n):\n def __new__(cls, schedule_definition_data, status, python_path=None, repository_path=None):\n\n return super(Schedule, cls).__new__(\n cls,\n check.inst_param(\n schedule_definition_data, 'schedule_definition_data', ScheduleDefinitionData\n ),\n check.inst_param(status, 'status', ScheduleStatus),\n check.opt_str_param(python_path, 'python_path'),\n check.opt_str_param(repository_path, 'repository_path'),\n )\n\n @property\n def name(self):\n return self.schedule_definition_data.name\n\n @property\n def cron_schedule(self):\n return self.schedule_definition_data.cron_schedule\n\n @property\n def environment_vars(self):\n return self.schedule_definition_data.environment_vars\n\n def with_status(self, status):\n check.inst_param(status, 'status', ScheduleStatus)\n\n return Schedule(\n self.schedule_definition_data,\n status=status,\n python_path=self.python_path,\n repository_path=self.repository_path,\n )\n\n\nclass Scheduler(six.with_metaclass(abc.ABCMeta)):\n '''Abstract base class for a scheduler. This component is responsible for interfacing with\n an external system such as cron to ensure scheduled repeated execution according.\n '''\n\n def _get_schedule_by_name(self, instance, repository, schedule_name):\n schedule = instance.get_schedule_by_name(repository, schedule_name)\n if not schedule:\n raise DagsterScheduleDoesNotExist(\n 'You have attempted to start the job for schedule {name}, but it does not exist.'.format(\n name=schedule_name\n )\n )\n\n return schedule\n\n def reconcile_scheduler_state(self, instance, repository, python_path, repository_path):\n '''Reconcile the ScheduleDefinitions list from the repository and ScheduleStorage\n on the instance to ensure there is a 1-1 correlation between ScheduleDefinitions and\n\n Schedules, where the ScheduleDefinitions list is the source of truth.\n\n If a new ScheduleDefinition is introduced, a new Schedule is added to storage with status\n ScheduleStatus.STOPPED.\n\n For every previously existing ScheduleDefinition (where schedule_name is the primary key),\n any changes to the definition are persisted in the corresponding Schedule and the status is\n left unchanged. The schedule is also restarted to make sure the external artifacts (such\n as a cron job) are up to date.\n\n For every ScheduleDefinitions that is removed, the corresponding Schedule is removed from\n the storage and the corresponding Schedule is ended.\n '''\n\n schedules_to_restart = []\n for schedule_def in repository.schedule_defs:\n # If a schedule already exists for schedule_def, overwrite bash script and\n # metadata file\n existing_schedule = instance.get_schedule_by_name(repository, schedule_def.name)\n if existing_schedule:\n # Keep the status, but replace schedule_def, python_path, and repository_path\n schedule = Schedule(\n schedule_def.schedule_definition_data,\n existing_schedule.status,\n python_path,\n repository_path,\n )\n\n instance.update_schedule(repository, schedule)\n schedules_to_restart.append(schedule)\n else:\n schedule = Schedule(\n schedule_def.schedule_definition_data,\n ScheduleStatus.STOPPED,\n python_path,\n repository_path,\n )\n\n instance.add_schedule(repository, schedule)\n\n # Delete all existing schedules that are not in schedule_defs\n schedule_def_names = {s.name for s in repository.schedule_defs}\n existing_schedule_names = set([s.name for s in instance.all_schedules(repository)])\n schedule_names_to_delete = existing_schedule_names - schedule_def_names\n\n schedule_reconciliation_errors = []\n for schedule in schedules_to_restart:\n # Restart is only needed if the schedule was previously running\n if schedule.status == ScheduleStatus.RUNNING:\n try:\n self.stop_schedule(instance, repository, schedule.name)\n self.start_schedule(instance, repository, schedule.name)\n except DagsterSchedulerError as e:\n schedule_reconciliation_errors.append(e)\n\n if schedule.status == ScheduleStatus.STOPPED:\n try:\n self.stop_schedule(instance, repository, schedule.name)\n except DagsterSchedulerError as e:\n schedule_reconciliation_errors.append(e)\n\n for schedule_name in schedule_names_to_delete:\n try:\n instance.stop_schedule_and_delete_from_storage(repository, schedule_name)\n except DagsterSchedulerError as e:\n schedule_reconciliation_errors.append(e)\n\n if len(schedule_reconciliation_errors):\n raise DagsterScheduleReconciliationError(\n \"One or more errors were encountered by the Scheduler while starting or stopping schedules. \"\n \"Individual error messages follow:\",\n errors=schedule_reconciliation_errors,\n )\n\n def start_schedule_and_update_storage_state(self, instance, repository, schedule_name):\n '''\n Updates the status of the given schedule to `ScheduleStatus.RUNNING` in schedule storage,\n then calls `start_schedule`.\n\n This should not be overridden by subclasses.\n\n Args:\n instance (DagsterInstance): The current instance.\n repository (RepositoryDefinition): The repository containing the schedule definition.\n schedule_name (string): The name of the schedule to start running.\n '''\n\n check.inst_param(instance, 'instance', DagsterInstance)\n check.inst_param(repository, 'repository', RepositoryDefinition)\n check.str_param(schedule_name, 'schedule_name')\n\n schedule = self._get_schedule_by_name(instance, repository, schedule_name)\n\n if schedule.status == ScheduleStatus.RUNNING:\n raise DagsterSchedulerError(\n 'You have attempted to start schedule {name}, but it is already running'.format(\n name=schedule_name\n )\n )\n\n self.start_schedule(instance, repository, schedule.name)\n started_schedule = schedule.with_status(ScheduleStatus.RUNNING)\n instance.update_schedule(repository, started_schedule)\n return started_schedule\n\n def stop_schedule_and_update_storage_state(self, instance, repository, schedule_name):\n '''\n Updates the status of the given schedule to `ScheduleStatus.STOPPED` in schedule storage,\n then calls `stop_schedule`.\n\n This should not be overridden by subclasses.\n\n Args:\n instance (DagsterInstance): The current instance.\n repository (RepositoryDefinition): The repository containing the schedule definition.\n schedule_name (string): The name of the schedule to start running.\n '''\n\n check.inst_param(instance, 'instance', DagsterInstance)\n check.inst_param(repository, 'repository', RepositoryDefinition)\n check.str_param(schedule_name, 'schedule_name')\n\n schedule = self._get_schedule_by_name(instance, repository, schedule_name)\n\n self.stop_schedule(instance, repository, schedule.name)\n stopped_schedule = schedule.with_status(ScheduleStatus.STOPPED)\n instance.update_schedule(repository, stopped_schedule)\n return stopped_schedule\n\n def stop_schedule_and_delete_from_storage(self, instance, repository, schedule_name):\n '''\n Deletes a schedule from schedule storage, then calls `stop_schedule`.\n\n This should not be overridden by subclasses.\n\n Args:\n instance (DagsterInstance): The current instance.\n repository (RepositoryDefinition): The repository containing the schedule definition.\n schedule_name (string): The name of the schedule to start running.\n '''\n\n check.inst_param(instance, 'instance', DagsterInstance)\n check.inst_param(repository, 'repository', RepositoryDefinition)\n check.str_param(schedule_name, 'schedule_name')\n\n schedule = self._get_schedule_by_name(instance, repository, schedule_name)\n self.stop_schedule(instance, repository, schedule.name)\n instance.delete_schedule(repository, schedule)\n return schedule\n\n @abc.abstractmethod\n def debug_info(self):\n '''Returns debug information about the scheduler\n '''\n\n @abc.abstractmethod\n def start_schedule(self, instance, repository, schedule_name):\n '''Start running a schedule. This method is called by `start_schedule_and_update_storage_state`,\n which first updates the status of the schedule in schedule storage to `ScheduleStatus.RUNNING`,\n then calls this method.\n\n For example, in the cron scheduler, this method writes a cron job to the cron tab\n for the given schedule.\n\n Args:\n instance (DagsterInstance): The current instance.\n repository (RepositoryDefinition): The repository containing the schedule definition.\n schedule_name (string): The name of the schedule to start running.\n '''\n\n @abc.abstractmethod\n def stop_schedule(self, instance, repository, schedule_name):\n '''Stop running a schedule.\n\n This method is called by\n 1) `stop_schedule_and_update_storage_state`,\n which first updates the status of the schedule in schedule storage to `ScheduleStatus.STOPPED`,\n then calls this method.\n 2) `stop_schedule_and_delete_from_storage`, which deletes the schedule from schedule storage\n then calls this method.\n\n For example, in the cron scheduler, this method deletes the cron job for a given scheduler\n from the cron tab.\n\n Args:\n instance (DagsterInstance): The current instance.\n repository (RepositoryDefinition): The repository containing the schedule definition.\n schedule_name (string): The schedule to stop running.\n '''\n\n @abc.abstractmethod\n def running_schedule_count(self, repository_name, schedule_name):\n '''Returns the number of jobs currently running for the given schedule. This method is used\n for detecting when the scheduler is out of sync with schedule storage.\n\n For example, when:\n - There are duplicate jobs runnning for a single schedule\n - There are no jobs runnning for a schedule that is set to be running\n - There are still jobs running for a schedule that is set to be stopped\n\n When the scheduler and schedule storage are in sync, this method should return:\n - 1 when a schedule is set to be running\n - 0 wen a schedule is set to be stopped\n\n Args:\n repository_name (string): The name of the repository containing the schedule definition.\n schedule_name (string): The schedule to return the number of jobs for\n '''\n\n @abc.abstractmethod\n def get_logs_path(self, instance, repository, schedule_name):\n '''Get path to scheduler logs for schedule\n '''\n\n @abc.abstractmethod\n def get_logs_directory(self, instance, repository, schedule_name):\n '''Get directory that stores logs for schedule\n '''\n\n\nclass ScheduleTickStatsSnapshot(\n namedtuple(\n 'ScheduleTickStatsSnapshot', ('ticks_started ticks_succeeded ticks_skipped ticks_failed'),\n )\n):\n def __new__(\n cls, ticks_started, ticks_succeeded, ticks_skipped, ticks_failed,\n ):\n return super(ScheduleTickStatsSnapshot, cls).__new__(\n cls,\n ticks_started=check.int_param(ticks_started, 'ticks_started'),\n ticks_succeeded=check.int_param(ticks_succeeded, 'ticks_succeeded'),\n ticks_skipped=check.int_param(ticks_skipped, 'ticks_skipped'),\n ticks_failed=check.int_param(ticks_failed, 'ticks_failed'),\n )\n\n\n@whitelist_for_serdes\nclass ScheduleTickStatus(Enum):\n STARTED = 'STARTED'\n SKIPPED = 'SKIPPED'\n SUCCESS = 'SUCCESS'\n FAILURE = 'FAILURE'\n\n\ndef _validate_schedule_tick_args(status, run_id=None, error=None):\n check.inst_param(status, 'status', ScheduleTickStatus)\n\n if status == ScheduleTickStatus.SUCCESS:\n check.str_param(run_id, 'run_id')\n check.invariant(\n error is None, desc=\"Schedule tick status is SUCCESS, but error was provided\"\n )\n elif status == ScheduleTickStatus.FAILURE:\n check.invariant(run_id is None, \"Schedule tick status is FAILURE but run_id was provided\")\n check.inst_param(error, 'error', SerializableErrorInfo)\n else:\n check.invariant(\n run_id is None, \"Schedule tick status was not SUCCESS, but run_id was provided\"\n )\n check.invariant(\n error is None, \"Schedule tick status was not FAILURE but error was provided\"\n )\n\n\n@whitelist_for_serdes\nclass ScheduleTickData(\n namedtuple('Schedule', 'schedule_name cron_schedule timestamp status run_id error')\n):\n def __new__(cls, schedule_name, cron_schedule, timestamp, status, run_id=None, error=None):\n '''\n This class defines the data that is serialized and stored in ``ScheduleStorage``. We depend\n on the schedule storage implementation to provide schedule tick ids, and therefore\n separate all other data into this serializable class that can be stored independently of the\n id\n\n Arguments:\n schedule_name (str): The name of the schedule for this tick\n cron_schedule (str): The cron schedule of the ``ScheduleDefinition`` for tracking\n purposes. This is helpful when debugging changes in the cron schedule.\n timestamp (float): The timestamp at which this schedule execution started\n status (ScheduleTickStatus): The status of the tick, which can be updated\n\n Keyword Arguments:\n run_id (str): The run created by the tick. This is set only when the status is\n ``ScheduleTickStatus.SUCCESS``\n error (SerializableErrorInfo): The error caught during schedule execution. This is set\n only when the status is ``ScheduleTickStatus.Failure``\n '''\n\n _validate_schedule_tick_args(status, run_id, error)\n return super(ScheduleTickData, cls).__new__(\n cls,\n check.str_param(schedule_name, 'schedule_name'),\n check.str_param(cron_schedule, 'cron_schedule'),\n check.float_param(timestamp, 'timestamp'),\n status,\n run_id,\n error,\n )\n\n def with_status(self, status, run_id=None, error=None):\n check.inst_param(status, 'status', ScheduleTickStatus)\n return self._replace(status=status, run_id=run_id, error=error)\n\n\nclass ScheduleTick(namedtuple('Schedule', 'tick_id schedule_tick_data')):\n '''\n A scheduler is configured to run at an multiple intervals set by the `cron_schedule`\n properties on ``ScheduleDefinition``. We define a schedule tick as each time the scheduler\n runs for a specific schedule.\n\n When the schedule is being executed to create a pipeline run, we create a``ScheduleTick``\n object and store it in ``ScheduleStorage``. This is needed because not every tick results\n in creating a run, due to skips or errors.\n\n At the beginning of schedule execution, we create a ``ScheduleTick`` object in the\n ``ScheduleTickStatus.STARTED`` state.\n\n A schedule definition has a `should_execute` argument, where users can define a function\n which defines whether to create a run for the current tick. In the case where\n ``should_execute`` returns false, schedule execution is short-circuited, a run is not created,\n and the status of the schedule tick is updated to be ``ScheduleTickStatus.SKIPPED``.\n\n There are also several errors that can occur during schedule execution, which are important\n to track for observability and alerting. There are several user defined functions that\n are run during schedule execution, which are each wrapped with a ``user_error_boundary``.\n There is also the possibility of a framework error. These errors are caught,\n serialized, and stored on the ``ScheduleTick``.\n '''\n\n def __new__(cls, tick_id, schedule_tick_data):\n return super(ScheduleTick, cls).__new__(\n cls,\n check.int_param(tick_id, 'tick_id'),\n check.inst_param(schedule_tick_data, 'schedule_tick_data', ScheduleTickData),\n )\n\n def with_status(self, status, run_id=None, error=None):\n check.inst_param(status, 'status', ScheduleTickStatus)\n return self._replace(\n schedule_tick_data=self.schedule_tick_data.with_status(status, run_id, error)\n )\n\n @property\n def schedule_name(self):\n return self.schedule_tick_data.schedule_name\n\n @property\n def cron_schedule(self):\n return self.schedule_tick_data.cron_schedule\n\n @property\n def timestamp(self):\n return self.schedule_tick_data.timestamp\n\n @property\n def status(self):\n return self.schedule_tick_data.status\n\n @property\n def run_id(self):\n return self.schedule_tick_data.run_id\n\n @property\n def error(self):\n return self.schedule_tick_data.error\n","sub_path":"python_modules/dagster/dagster/core/scheduler/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":21966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"540571942","text":"'''\n序列中出现次数最多的元素\n'''\nfrom collections import Counter\n\nif __name__ == \"__main__\":\n words = [\n 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',\n 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',\n 'eyes', \"don't\", 'look', 'around', 'the', 'eyes', 'look', 'into',\n 'my', 'eyes', \"you're\", 'under'\n ]\n word_counts = Counter(words)\n print(word_counts)\n\n top_three = word_counts.most_common(3)\n print(top_three)\n\n morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']\n word_counts.update(morewords)\n top_three = word_counts.most_common(3)\n print(top_three)\n","sub_path":"python3_cookbook/chapter01/demo12.py","file_name":"demo12.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"278477379","text":"import os\nimport shutil\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport json\nfrom sys import path\npath.append(r'../dubi') \nimport dubi_n as dn\n\n\n\n'''\n只在下午收盘后 也就是17-21点之间发 也就是只发按日计算的\n将hour折算为day 生成一个新的csv文件 然后和以往一样合并\n'''\ndef td(fromfile,tofile):\n lines=dict()\n with open(fromfile) as f:\n for line in f.readlines():\n line=line.strip('\\n')\n date=line[0:6]\n lines[date]=line\n with open(tofile,\"w\") as f:\n for date,line in lines.items():\n date=str(20)+date\n f.write(date+line[8:]+\"\\n\")\n\ndef today(alloc,pairs):\n for pair in alloc:\n path=f\"../gubi/{pair}\"\n if not os.path.exists(path):\n os.mkdir(path)\n \n if alloc[pair]=='day':\n for file in [\"_net.png\",\"_ori.png\",\"_net.csv\",\".csv\"]: \n shutil.copy(f\"../dubi/{pair}/{pair}{file}\",f\"{path}\")\n for sym in pairs[pair]:\n shutil.copy(f\"../dubi/{pair}/{sym}_pos.csv\",f\"{path}\")\n \n \n elif alloc[pair]=='session':\n for file in [\"_net.png\",\"_ori.png\"]: \n shutil.copy(f\"../gubi_hour/{pair}/{pair}{file}\",f\"{path}\")\n for sym in pairs[pair]:\n shutil.copy(f\"../gubi_hour/{pair}/{sym}_pos.csv\",f\"{path}\")\n td(f\"../gubi_hour/{pair}/{pair}_net.csv\",f\"{path}/{pair}_net.csv\")\n td(f\"../gubi_hour/{pair}/{pair}.csv\",f\"{path}/{pair}.csv\")\n \n\ndef genfig(pairs):\n global dh\n global d\n dh=list()\n for i,pair in enumerate(pairs):\n print(\"genfig\",i,pair)\n file=\"../gubi/\"+pair+\"/\"+pair+\".csv\"\n dh.append(pd.read_csv(file,index_col=0,parse_dates=True)*pos[pair]['all'])\n d=pd.concat(dh,axis=1);d=d['20150323':'21000101'];d.fillna(value=0)\n d=d.sum(1);d=1+(d-d[0])/pd.DataFrame(list(casha.values()))[0].sum()\n pd.DataFrame(d,columns=[\"sum\"]).to_csv('sum.csv')\n d.plot()\n plt.savefig('sum.png', dpi=100);plt.close()\n print(dn.genresultpara(pd.DataFrame(d)))\n\n\ndef gensubfig(pairs):\n dh=list()\n for i,pair in enumerate(pairs):\n if \"_\" in pair:\n continue\n print(\"gensubfig\",i,pair)\n file=\"../gubi/\"+pair+\"/\"+pair+\".csv\"\n dh.append(pd.read_csv(file,index_col=0,parse_dates=True)*pos[pair]['all'])\n d=pd.concat(dh,axis=1);d=d['20150323':'21000101'];d.fillna(value=0)\n d=d.sum(1);d=1+(d-d[0])/pd.DataFrame(list(casha.values()))[0].sum()\n \n pd.DataFrame(d,columns=[\"sum\"]).to_csv('subsum.csv')\n d.plot()\n plt.savefig('../gubi/subsum.png', dpi=100);plt.close()\n\ndef genpartfig(pairs): \n for i,pair in enumerate(pairs):\n dsub=list()\n for i,pair in enumerate(pairs):\n file=\"../gubi/\"+pair+\"/\"+pair+\"_net.csv\"\n \n dsub.append(pd.read_csv(file,index_col=0,parse_dates=True)*pos[pair]['all'])\n dsub=pd.concat(dsub,axis=1);\n\n fig,axes = plt.subplots(nrows=3, ncols=4)\n count=0\n for pair in pairs:\n x,y=int(count/4),count-4*int(count/4)\n dsub[pair].dropna(how='any').plot(ax=axes[x,y])\n axes[x,y].set_title(pair,x=0.8,y=0.08,fontsize=10)\n axes[x,y].set_xticklabels([])\n axes[x,y].set_yticklabels([])\n axes[x,y].set_xticks([])\n axes[x,y].set_yticks([])\n count+=1\n file=\"../gubi/allpart.png\"\n fig.savefig(file, dpi=100);plt.close()\n\nwith open('./para.json') as f:\n para=json.load(f)\n\nwith open('./para_pos.json') as f:\n pos=json.load(f)\n \nwith open('./para_casha.json') as f:\n casha=json.load(f) \n\nwith open('./para_alloc.json') as f:\n alloc=json.load(f)\n\npairs=list(para.keys())\n\ntoday(alloc,para)\ngenfig(alloc)\ngensubfig(alloc)\ngenpartfig(pairs)\n\n","sub_path":"project/gubi_llp/gubi/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"112892334","text":"'''\nChild of DZIIO, with functions to\n1) Automatically mask regions with tissue (H&E only, not tested for other stains)\n1) Automatically extract tiles with tissue above some % area.\n2) Automatically crop dzi images\n'''\n\nimport numpy as np\nimport cv2\nimport warnings\nfrom pathlib import Path\nimport importlib\nfrom PIL import Image\nfrom scipy import interpolate, ndimage\nimport skimage.morphology as morp\n\nfrom dzi_io import dzi_io\n\n\nclass TileGenerator(dzi_io.DZIIO):\n '''\n inherits openslide class with custom functions\n '''\n\n def __init__(self, src, target=None, px_size=None, mask_px_size=10, no_mask=False, read_from_base=False, **kwargs):\n '''\n :param src: Path to the .dzi file\n :param target: Target .dzi file to write to.\n :param px_size: micron per pixel at the pyramid's base level. By default it would try to read the mpp from a json file stored under\n dzi_files/properties.json if it exists but this could be overwritten.\n :param mask_px_size: Pixel size of the thumbnail in um used for generating mask where there is tissue.\n :param no_mask: Don't generate mask to save time.\n '''\n super(TileGenerator, self).__init__(src, target=target, **kwargs)\n\n self.px_size = px_size if px_size is not None else 0.22\n self.mask_px_size = mask_px_size\n\n self.up_ratio = mask_px_size / self.px_size # >1\n self.down_ratio = 1 / self.up_ratio # <1\n\n self.mask_size = int( max(self.height, self.width) / mask_px_size * self.px_size )\n if not no_mask:\n self.generate_mask()\n\n if read_from_base:\n self.get_tile = self.get_tile_base\n else:\n self.get_tile = self.get_tile_closest\n\n # kht.plot.multiplot(self.thumb, self.mask)\n\n def get_tiles(self, area_thres_percent=0.5, shuffle=False, tilesize_base=(1024,1024), tilesize_out=(256,256), overlap=0, coord_only=False, loop=False, border=255):\n '''\n Function for generating tiles given there is enough tissue in the tile.\n :param area_thres_percent: How much tissue there should be in the tile.\n :param shuffle: whether to shuffle the\n :param tilesize_base: size of the tile at level 0.\n :param tilesize_out: size of tile to output. Always samples from level 0 for better image quality.\n :param overlap: how many pixels to overlap with adjacent slide on ONE side.\n eg For tilesize==(1024,1024) and overlap==512 would give you twice as many tiles.\n :param coord_only: returns only (x,y) coordinates but not the actual image.\n :param loop: generator is infinite loop\n :param border: if not None, allows reading regions outside the slide's width/height. Border regions will be greyscale (0-255) given by this parameter.\n :param read_from_base: only downsample from the highest resolution level of the pyramid\n :return: generator that returns a Tile object containing (PIL Image, x, y)\n '''\n\n assert tilesize_base[0]*tilesize_out[1] == tilesize_base[1]*tilesize_out[0] # Make sure in/out aspect ratio is the same\n\n notcompleted = True\n list_x = range(np.int(np.floor(self.width / (tilesize_base[0]-overlap))+1))\n list_y = range(np.int(np.floor(self.height / (tilesize_base[1]-overlap))+1))\n\n tile_mask_width, tile_mask_height = self.slide_to_mask((tilesize_base[0], tilesize_base[1]))\n tile_mask_width = np.maximum(np.int(tile_mask_width), 1)\n tile_mask_height = np.maximum(np.int(tile_mask_height), 1)\n\n while loop or notcompleted:\n if shuffle: # Whether to shuffle the slides. If false, yields slides sequentially from x=0,y=0\n list_x = np.random.permutation(list_x)\n list_y = np.random.permutation(list_y)\n\n for i in list_x:\n for j in list_y:\n x = i * (tilesize_base[0]-overlap)\n y = j * (tilesize_base[1]-overlap)\n mask_coord = self.slide_to_mask((x, y))\n x_mask = np.int(mask_coord[0])\n y_mask = np.int(mask_coord[1])\n\n # if (x_mask + tile_mask_width < self.mask.shape[1] and y_mask + tile_mask_height < self.mask.shape[0]):\n if (self.masked_percent(x_mask, y_mask, tile_mask_width, tile_mask_height) > area_thres_percent):\n if coord_only:\n yield (x,y)\n else:\n tile = self.get_tile((x, y), tilesize_base, tilesize_out, border)\n yield Tile(tile, x, y)\n notcompleted = False\n\n def get_tile_base(self, r, tilesize_base, tilesize_out, border):\n tile = Image.fromarray(self.read_region(r, 0, tilesize_base, border=border))\n return tile.resize(tilesize_out)\n\n def get_tile_closest(self, r, tilesize_base, tilesize_out, border):\n level = np.int(np.log2(np.float(tilesize_base[0]) / np.float(tilesize_out[0])))\n if np.isclose(level, np.log2(np.float(tilesize_base[0]) / np.float(tilesize_out[0]))):\n tile = Image.fromarray(self.read_region(r, level, tilesize_out, border=border))\n return tile\n else:\n closest_level_tilesize = (np.int(tilesize_base[0] / np.power(2, level)), np.int(tilesize_base[1] / np.power(2, level)))\n tile = Image.fromarray(self.read_region(r, level, closest_level_tilesize, border=border))\n return tile.resize(tilesize_out)\n\n def get_stack(self, r, tilesize, levels, border):\n \"\"\"\n Returns a list of images same pixel dimensions at different magnifications centred around the same location.\n :param r: Centre location at base coordinate\n :param tilesize:\n :param levels: A list of levels. eg [2, 3, 4]\n :param border:\n :return:\n \"\"\"\n\n img = []\n for level in levels:\n _img = self.read_region(r, level, tilesize, border=border, mode=1)\n img.append(_img)\n\n return img\n\n def generate_mask(self, method='hsv_otsu', kernelsize=20, bg_thresh=0.07):\n '''\n Using the a thumbnail of the slide, generates a mask with 1s where tissue is present.\n method can be a pytorch .pth.tar file. If so try to load it and use it to predict a mask\n :return: None\n '''\n\n self.thumb = np.array(self.get_thumbnail(self.mask_size))\n kernel = np.ones((kernelsize, kernelsize), np.uint8)\n\n if method==\"hsv_otsu\":\n self.mask = cv2.cvtColor(self.thumb, cv2.COLOR_RGB2HSV).astype(float)\n # self.mask = self.mask[:,:,0]*self.mask[:,:,1]*(255-self.mask[:,:,2])\n self.mask = self.mask[:,:,1]*np.minimum(np.maximum(255-self.mask[:,:,2], 128), 10)\n self.mask = np.cast[np.uint8](self.mask/np.max(self.mask)*255)\n\n ret, _ = cv2.threshold(self.mask, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n self.mask = cv2.morphologyEx(np.cast[np.uint8](self.mask>ret), cv2.MORPH_CLOSE, kernel)\n self.mask = morp.remove_small_objects(self.mask.astype(bool), min_size=int(10000/self.mask_px_size))\n elif Path(method).exists(): # Unet\n torch = importlib.import_module(\"torch\")\n\n with torch.no_grad():\n checkpoint = torch.load(Path(method), map_location=lambda storage, loc: storage)\n assert('arch' in checkpoint and 'state_dict' in checkpoint)\n\n try:\n self.model = checkpoint['arch'](2, blk_out=eval(checkpoint['config']['blk_out']))\n self.model.load_state_dict(checkpoint['state_dict'])\n except Exception as e:\n raise(e)\n\n # img_to_batch\n if isinstance(self.thumb, np.ndarray):\n img = Image.fromarray(self.thumb)\n\n img = np.array(img)[:, :, :3] if img.mode.startswith(\"RGB\") else np.array(img)[:, :, np.newaxis]\n # Converting single image to a batch. Need to verify that W and H hasn't been swapped\n img = torch.Tensor(np.moveaxis(img, (0, 1, 2), (1, 2, 0))[np.newaxis, :, :, :] / 255.)\n img = img.to(next(self.model.named_parameters())[1].device)\n mask = torch.nn.functional.softmax(self.model(img), dim=1)\n\n # batch_to_img\n mask = np.moveaxis(mask.data.cpu().numpy()[0], (0, 1, 2), (2, 0, 1))[:,:,1]\n\n # ret, _ = cv2.threshold((mask*255).astype(np.uint8), 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n #\n # self.mask = cv2.morphologyEx(np.cast[np.uint8](mask*255 > ret), cv2.MORPH_CLOSE, kernel)\n self.mask = mask > bg_thresh\n self.mask = cv2.morphologyEx(np.cast[np.uint8](self.mask), cv2.MORPH_CLOSE, kernel)\n self.mask = ndimage.morphology.binary_fill_holes(self.mask)\n self.mask = morp.remove_small_objects(self.mask.astype(bool), min_size=int(10000/self.mask_px_size))\n else:\n print(f\"Please code for other methods for thresholding tissue here. Current: {method}\")\n\n def get_mask(self, x, y, tile_width=None, tile_height=None, downsample=1):\n '''\n # Returns high resolution mask given the top left coordinates of the tile.\n # downsample is relative to original image\n :param x: coordinate at level 0\n :param y: coordinate at level 0\n :param tile_width: coordinate at level 0\n :param tile_height: coordinate at level 0\n :param downsample: relative to original image\n :return: mask where pixels with tissue are 1.\n '''\n\n mask = np.array(self.mask) # Due to the annoying way how row/col are swapped between PIL and numpy array\n height, width = mask.shape\n\n old_y, old_x = np.mgrid[0:height, 0:width]\n old_points = np.array([old_x.ravel(), old_y.ravel()]).T\n\n mask_linear = mask.ravel()\n\n # Now the query points\n mask_coord = self.slide_to_mask((x, y))\n if tile_width is None:\n tile_width = self.tilesize\n if height is None:\n tile_height = self.tilesize\n tile_mask_width, tile_mask_height = self.slide_to_mask((tile_width, tile_height))\n x_mask = np.int(mask_coord[0])\n y_mask = np.int(mask_coord[1])\n tile_mask_width = np.int(tile_mask_width)\n tile_mask_height = np.int(tile_mask_height)\n new_y, new_x = np.mgrid[0:tile_height:downsample, 0:tile_width:downsample]\n new_x = new_x * tile_mask_width / tile_width + x_mask\n new_y = new_y * tile_mask_height / tile_height + y_mask\n\n mask = interpolate.griddata(old_points, mask_linear, (new_x, new_y), method='nearest')\n return mask\n\n def masked_percent(self, x, y, tile_mask_width, tile_mask_height):\n '''\n Calculates the percent of a tile filled with tissue\n :param x: x coordinate in mask\n :param y: y coordinate in mask\n :param tile_mask_width: width of tile in mask\n :param tile_mask_height: height of tile in mask\n :return: % of tile that is masked as 1\n '''\n\n area = tile_mask_width * tile_mask_height\n filled = np.array(self.mask)[np.maximum(0, y):y + tile_mask_height, np.maximum(0, x):x + tile_mask_width]\n filled = np.sum(filled == 1)\n return filled / area\n\n def mask_to_slide(self, r, dtype='float', level=0):\n '''\n Functions for mapping coordinate of smaller image to a level in the image pyramid.\n :param r: tuple coordinates (x,y) of thumbnail\n :param dtype: data type\n :param level: level of the image pyramid. 0 for the full image. Supports float.\n :return: integer tuples (x,y) in full image\n '''\n x = np.floor(self.up_ratio * r[0] * np.power(0.5, level))\n y = np.floor(self.up_ratio * r[1] * np.power(0.5, level))\n\n if dtype=='float':\n return (x, y)\n else:\n return (np.int(x), np.int(y))\n\n def slide_to_mask(self, r, dtype='float'):\n '''\n Functions for mapping coordinate of full image to thumbnail\n :param r: tuple coordinates (x,y) of full image\n :param dtype: data type\n :return: integer tuples (x,y) in thumbnail\n '''\n x = np.floor(self.down_ratio * r[0])\n y = np.floor(self.down_ratio * r[1])\n\n if dtype=='float':\n return (x, y)\n else:\n return (np.int(x), np.int(y))\n\ndef find_autorotate_angle(dzi):\n \"\"\"\n # Todo\n Automatically finds the principle angle of the needle biopsy\n :param dzi:\n :return: angle in deg\n \"\"\"\n dzi.get_mask()\n\n return 0\n\n# Object to store the tile\nclass Tile(object):\n def __init__(self, image, x, y):\n self.image = image\n self.x = x\n self.y = y\n\n# -------------- Deprecated Names -------------\ndef Tile_generator(src, target=None, px_size=None, mask_px_size=10, **kwargs):\n warnings.warn(\"Tile_generator class has been renamed to TileGenerator\", DeprecationWarning)\n return TileGenerator(src, target=target, px_size=px_size, mask_px_size=mask_px_size, **kwargs)\n\n\n","sub_path":"dzi_io/tile_generator.py","file_name":"tile_generator.py","file_ext":"py","file_size_in_byte":13306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87440701","text":"from proj.models import Record\nfrom log.models import AddtionalDetails\nfrom django.contrib.auth.models import User,auth\nfrom datetime import datetime\n\ndef add_to_context(request):\n if request.user.is_authenticated:\n info = AddtionalDetails.objects.get(username=request.user.username)\n profile=info.profile\n info=info.notifications[::-1]\n list1=[]\n for i in info[:5]:\n j=i[2:-2]\n k=j.split(\"', '\")\n # print(k[1])\n\n a=datetime.strptime(k[1],'%Y-%m-%d %H:%M:%S.%f')\n diff=datetime.now()-a \n # k[1]=str((diff.seconds)//60)+\" minutes ago\"\n if(diff.days==0):\n hrs=(diff.seconds)//3600\n if hrs==0:\n mini=(diff.seconds)//60\n if mini==0:\n k[1]=str(diff.seconds)+\" Seconds ago\"\n else:\n k[1]=str(diff.seconds//60)+\" minutes ago\"\n else:\n k[1]=str(hrs)+\" hours ago\"\n\n else:\n k[1]=str(diff.days)+\" days ago\"\n\n list1.append(k)\n\n return {'info': list1,'profile':profile}\n \n return {'notifications': ''}","sub_path":"log/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"223711090","text":"import matplotlib.pyplot as plt\r\n\r\n\r\ndef get_data(name):\r\n with open(name, \"r\") as file:\r\n data = []\r\n while True:\r\n line = file.readline()\r\n if not line:\r\n break\r\n data += line.split()\r\n return data\r\n\r\n\r\ndef sort_data(name):\r\n data = get_data(name)\r\n chars = []\r\n for i in range(len(data)):\r\n for j in data[i].lower():\r\n chars += j\r\n return chars\r\n\r\n\r\ndef organize(name):\r\n data = sort_data(name)\r\n letters = []\r\n frequency = []\r\n for i in data:\r\n if i not in letters:\r\n letters.append(i)\r\n frequency.append(data.count(i))\r\n else:\r\n pass\r\n return letters, frequency\r\n\r\n\r\ndef graph_it(name):\r\n letters = organize(name)[0]\r\n frequency = organize(name)[1]\r\n plt.title(\"Frequencia de letras num documento de texto\")\r\n for i in letters:\r\n plt.plot([], [], label = i, )\r\n plt.pie(frequency, autopct = \"%1.1f%%\")\r\n plt.legend()\r\n plt.show()\r\n\r\n\r\ngraph_it(\"data.txt\")\r\n","sub_path":"Cap7/Cap7_7.10/Cap7_7.10.py","file_name":"Cap7_7.10.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"528710433","text":"# dictionaries are hash tables, key:value pairs\ndict = {'Adam': ['adam@email.com', 2445055],\n 'Bard': 'bard@email.com'}\n\ndict # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@email.com'}\ndict['Adam'] # ['adam@email.com', 2445055]\ndict['Adam'][1] # 2445055\n\n# update value\ndict['Bard'] = 'bard@anotheremail.com'\ndict # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}\n\n# add key:value pair\ndict['Cole'] = 'cole@email.com'\ndict # {'Cole': 'cole@email.com', 'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}\n\n# remove key:value pair\ndel dict['Cole'] # {'Adam': ['adam@email.com', 2445055], 'Bard': 'bard@anotheremail.com'}\n\n'Cole' in dict # False\n'Adam' in dict # True\n\n# create dictionary from a list of tuples\ndict_list_tuples = dict([(1, \"x\"), (2, \"y\"), (3, \"z\")])\ndict_list_tuples # {1: 'x', 2: 'y', 3: 'z'}\n\n'''\nMichael Sjoeberg\n2018-11-05\nhttps://github.com/michaelsjoeberg/python-playground/blob/master/basics/dictionaries.py\n'''","sub_path":"basics/dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"380285140","text":"# Created by Aashish Adhikari at 6:41 PM 4/11/2020\n#Taken from https://discuss.pytorch.org/t/is-there-a-way-to-mix-many-different-activation-functions-efficiently/648/5\n\n#PyTorch and NumPy allow setting certain elements of a tensor using boolean masks.\n# Mask are the same size as the tensor being masked and only those elements are updated where the mask value is true\n\n'''--------------------------NOT SURE IF THIS IS CORRECT---------------------------'''\n\nimport torch, torch.nn as nn\nimport torch.nn.functional as F\n\nclass Example_network (nn.Module):\n\n\n\n def __init__(self):\n super(Example_network, self).__init__()\n self.linear = nn.Linear(5,2)\n\n def forward(self,input):\n nonlinearities = [F.leaky_relu, F.tanh]\n masks = [[1,0],[0,1]] # a list of masks\n\n preactivation = self.linear(input)\n\n garbage_output = preactivation.new(preactivation.size())\n print(\"Garbage output to edit is: \",garbage_output)\n\n for nonlinearity, mask in zip(nonlinearities, masks):\n\n garbage_output[mask] = nonlinearity(preactivation[mask])\n print(\"Inside: \",garbage_output)\n\n return garbage_output\n\na = torch.FloatTensor([1,2,3,4,5])\nntwork = Example_network()\nprint(ntwork(a))","sub_path":"PyTorch_Ideas/Different_Activations_on_the_Same_Layer.py","file_name":"Different_Activations_on_the_Same_Layer.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"44728585","text":"\n\n#calss header\nclass _SYNDICATED():\n\tdef __init__(self,): \n\t\tself.name = \"SYNDICATED\"\n\t\tself.definitions = [u'(of articles and photographs) sold to several different newspapers and magazines for publishing', u'(of television or radio programmes) sold to several different broadcasting organizations']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_syndicated.py","file_name":"_syndicated.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"257617623","text":"\"\"\"\n.. todo::\n\n WRITEME\n\"\"\"\nfrom copy import deepcopy\nimport logging\nimport os.path\nimport socket\nimport numpy\nnp = numpy\nfrom pylearn2.train_extensions import TrainExtension\nimport theano\nimport theano.tensor as T\nfrom pylearn2.utils import serial\n\nlog = logging.getLogger(__name__)\n\nclass SaveWeights(TrainExtension):\n \"\"\"\n A callback that saves a copy of the weights of the model every with some given epoch frequency.\n \n Parameters\n ----------\n save_freq : int\n Frequency of saves, in epochs.\n save_path : str\n Output directory for the weights of model. \n \"\"\"\n def __init__(self, save_freq=None, save_path=None):\n assert((save_freq is not None) and (save_path is not None))\n self.save_path = save_path\n self.save_freq = save_freq\n self._tag_key = \"SaveWeights\"\n\n def setup(self, model, dataset, algorithm):\n \"\"\"\n Sets some model tag entries.\n\n Parameters\n ----------\n model : pylearn2.models.model.Model\n dataset : pylearn2.datasets.dataset.Dataset\n Not used\n algorithm : TrainingAlgorithm\n Not used\n \"\"\"\n if self._tag_key in model.tag:\n log.warning('Model tag key \"%s\" already found. This may indicate '\n 'multiple instances of %s trying to use the same tag '\n 'entry.',\n self._tag_key, self.__class__.__name__)\n log.warning('If this is the case, specify tag key manually in '\n '%s constructor.', self.__class__.__name__)\n # Useful information for locating the saved model.\n if self.save_path is not None:\n model.tag[self._tag_key]['save_path'] = os.path.abspath(\n self.save_path)\n model.tag[self._tag_key]['hostname'] = socket.gethostname()\n self._update_tag(model)\n\n def on_monitor(self, model, dataset, algorithm):\n \"\"\"\n Looks whether the model performs better than earlier. If it's the\n case, saves the model.\n\n Parameters\n ----------\n model : pylearn2.models.model.Model\n model.monitor must contain a channel with name given by\n self.channel_name\n dataset : pylearn2.datasets.dataset.Dataset\n Not used\n algorithm : TrainingAlgorithm\n Not used\n \"\"\"\n freq = self.save_freq\n epochs_seen = model.monitor.get_epochs_seen()\n\n if freq > 0 and epochs_seen % freq == 0:\n weights = model.get_weights()\n numpy.savez(os.path.join(self.save_path,\"weights.\"+str(epochs_seen)+\".npz\"), weights)\n\n \"\"\"\n val_record = channel.val_record\n new_cost = val_record[-1]\n\n if self.coeff * new_cost < self.coeff * self.best_cost:\n self.best_cost = new_cost\n # Update the tag of the model object before saving it.\n self._update_tag(model)\n if self.store_best_model:\n self.best_model = deepcopy(model)\n if self.save_path is not None:\n serial.save(self.save_path, model, on_overwrite='backup')\n \"\"\"\n\n def _update_tag(self, model):\n \"\"\"\n Update `model.tag` with information about the current best.\n\n Parameters\n ----------\n model : pylearn2.models.model.Model\n The model to update.\n \"\"\"\n # More stuff to be added later. For now, we care about the best cost.\n pass\n #model.tag[self._tag_key]['best_cost'] = self.best_cost\n\n","sub_path":"pylearn2/train_extensions/save_weights.py","file_name":"save_weights.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"522580581","text":"\n# coding: utf-8\n\n# In[63]:\n\nimport pandas as pd\nfrom pandas import *\nimport numpy as np\nimport datetime as dt\nfrom datetime import timedelta\nimport os\nfrom glob import glob\n\nos.chdir(r'C:\\Users\\ph052367\\OneDrive\\netSpend FTP\\\\')\nloc = r'C:\\Users\\ph052367\\OneDrive\\netSpend\\\\'\nsplitsname = r'netSpend_Splits.csv'\nfcrname = 'fcr_detail_global_disp_'\nnpsname = 'csat_survey_'\nahtname = 'ns_sgs_callbycall_'\nrostername = 'NS_SGS_Daily_Roster.csv'\nvasname = 'vas_report_'\next ='.csv'\n\nstartdate = dt.date.today() - Timedelta('60 day')\nenddate = dt.date.today() \ndaterange = Timestamp(enddate) - Timestamp(startdate)\ndaterange = (daterange / np.timedelta64(1, 'D')).astype(int)\nprint('Starting scrubbing file...')\n\n\n# In[64]:\n\ndata = []\nframes = []\ncalls = []\nbracket = []\ntry:\n for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):\n nps = pd.read_csv(npsname + date_range.strftime('%m_%d_%Y') + ext, parse_dates = ['call_date','date_completed'], dtype = {'cash_number': object}, usecols = ['login_name', 'cash_number', 'region','answer_8_q10', 'answer_9_q11', 'answer_7_q9', 'answer_6_q7', 'question_1_q1','comment_1_q8','comment_2_q12', 'answer_1_q2','customer_segment_name','channel_name','loyalty_tag','answer_2_q3', 'answer_3_q4','answer_4_q5', 'answer_5_q6','date_completed', 'gdv','direct_deposit','csat_score','dist_name', 'call_disp','od_active','call_date'])\n frames.append(nps)\nexcept IOError:\n print('File does not exist:', npsname + date_range.strftime('%m_%d_%Y') + ext)\nnps = pd.concat(frames)\nprint('NPS Done') \ntry:\n for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):\n aht = pd.read_csv(ahtname + date_range.strftime('%Y_%m_%d') + ext, dtype = {'PhoneNumber': object, 'Agent Login': object, 'Disposition': object, 'Split': object}, usecols = ['PhoneNumber', 'Split' , 'Agent Login', 'SegStart', 'Disposition' , 'TalkTime', 'AnsHoldTime', 'ACWTime', 'HoldCount', 'Droppedcalls', 'Wait Time'])\n calls.append(aht)\nexcept IOError:\n print('File does not exist:', ahtname + date_range.strftime('%Y_%m_%d') + ext)\naht = pd.concat(calls)\nprint('AHT Done') \ntry:\n for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):\n fcr = pd.read_csv(fcrname + date_range.strftime('%m_%d_%Y') + ext, parse_dates = ['call_time'], dtype = {'cash_number': object}, usecols = ['login_name', 'call_time', 'cash_number', 'future_hits', 'previous_hits'])\n data.append(fcr)\nexcept IOError:\n print('File does not exist:', fcrname + date_range.strftime('%m_%d_%Y') + ext)\nfcr = pd.concat(data)\nprint('FCR Done') \ntry:\n for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):\n vas = pd.read_csv(vasname + date_range.strftime('%m_%d_%Y') + ext, parse_dates = ['Call_date'], dtype = {'Cash_number': object}, error_bad_lines = False, usecols = ['login_name', 'Cash_number', 'Call_date', 'FAP_Eligible', 'FAP_Enrollment', 'DD_Eligible', 'DD_Enrollment', 'AA_Eligible', 'AA_Enrollment', 'PBR_Enrollment'] )\n bracket.append(vas)\nexcept IOError:\n print('File does not exist:', vasname + date_range.strftime('%m_%d_%Y') + ext)\nvas = pd.concat(bracket)\nprint('VAS Done') \nroster = pd.read_csv(loc + rostername, parse_dates = ['Report_Date','Live_Date', 'Inactive_Date'], dtype = {'Avaya_ID': object})\nprint('Roster Done')\nsplits = pd.read_csv(loc + splitsname, dtype = {'Split': object})\nprint('Splits Done') \n\n\n# In[65]:\n\n#capitalize the first letters of the columns, rename the columns for all files\nnps.columns = map(str.title, nps.columns)\nvas.columns = map(str.title, vas.columns)\nnps.rename(columns = {'Login_Name':'tCAM_ID','Answer_8_Q10':'Continue_netSpend','Answer_9_Q11':'Net_Promoter','Answer_7_Q9':'Satisfied_Product','Answer_6_Q7':'First_Call_Resolution','Question_1_Q1':'Call_Reason','Comment_1_Q8':'Improve_Service','Comment_2_Q12':'Improve_Product', 'Answer_1_Q2':'IVR_Satisfaction','Customer_Segment_Name':'Segment','Answer_2_Q3':'Understood_Question', 'Answer_3_Q4':'Resolved_Issue','Answer_4_Q5':'Satisfying_Resolution', 'Answer_5_Q6':'Timeliness_Resolution','Date_Completed':'Survey_Time', 'Gdv':'Gross_Debit_Volume','Csat_Score':'CSAT_Score','Dist_Name':'Distributor', 'Call_Disp':'Purp-Disp','Od_Active':'ODP','Call_Date':'Call_Time' }, inplace = True)\nfcr.rename(columns= {'cash_number':'Cash_Number','login_name':'tCAM_ID','call_time':'Call_Time', 'channel_name':'Channel_Name', 'previous_hits':'Previous_Hits', 'future_hits':'Future_Hits','purpose':'Purpose','disposition':'Disposition'}, inplace = True)\naht.rename(columns= {'PhoneNumber':'Cash_Number', 'Agent Login':'Avaya_ID', 'SegStart' : 'Call_Start', 'SegStop' : 'Call_End', 'TalkTime' : 'Talk_Time', 'AnsHoldTime': 'Hold_Time','HoldCount':'Hold_Count','Droppedcalls':'Released_Calls','ACWTime': 'ACW_Time', 'Wait Time': 'Queue_Time'}, inplace = True)\nvas.rename(columns= { 'Fap_Eligible' : 'FAP_Eligible' , 'Fap_Enrollment' :'FAP_Enrollment' , 'Aa_Eligible': 'AA_Eligible', 'Aa_Enrollment':'AA_Enrollment', 'Dd_Eligible': 'DD_Eligible','Dd_Enrollment':'DD_Enrollment', 'Pbr_Enrollment':'PBR_Enrollment', 'Call_Purpose':'Purpose', 'Call_Disposition':'Disposition', 'Login_Name':'tCAM_ID'}, inplace = True)\n#only keep the inbound calls on the switch report and SGS data from the surveys. Drop unnecessary columns and duplicates. Fix the cash numbers to make sure they do not have a decimal point\nkeep = ['2']\naht = aht.loc[aht['Disposition'].isin(keep)]\nsgs = ['SGS']\nnps = nps.loc[nps['Region'].isin(sgs)]\naht.drop_duplicates(subset = ['Avaya_ID', 'Call_Start','Cash_Number'], inplace = True)\naht.drop('Disposition', axis = 1, inplace = True)\nnps.drop('Region', axis = 1, inplace = True)\nfcr['Cash_Number'] = fcr['Cash_Number'].astype(str).map(lambda x: x.split('.')[0])\nnps['Cash_Number'] = nps['Cash_Number'].astype(str).map(lambda x: x.split('.')[0])\naht['Cash_Number'] = aht['Cash_Number'].astype(str).map(lambda x: x.split('.')[0])\naht['Call_Start'] = aht['Call_Start'].astype(str).map(lambda x: x.split(':000')[0])\n\n\n# In[66]:\n\n#sort the dataframes and create the date columns used for merging later\nnps.sort('Call_Time', ascending = True, inplace = True)\naht.sort('Call_Start', ascending = True, inplace = True)\nfcr.sort('Call_Time', ascending = True, inplace = True)\nvas.sort('Call_Date', inplace = True)\naht['Call_Start'] = pd.to_datetime(aht['Call_Start'], format = '%m/%d/%Y %H:%M:%S')\naht['Call_Date'] = aht['Call_Start'].dt.date\naht['Call_Date'] = pd.to_datetime(aht['Call_Date'], format = '%Y-%m-%d')\nfcr['Call_Date'] = fcr['Call_Time'].dt.date\nfcr['Call_Date'] = pd.to_datetime(fcr['Call_Date'], format = '%Y-%m-%d')\nvas['Call_Date'] = pd.to_datetime(vas['Call_Date'], format = '%Y-%m-%d')\nnps['Call_Date'] = nps['Call_Time'].dt.date\nnps['Call_Date'] = pd.to_datetime(nps['Call_Date'], format = '%Y-%m-%d')\nnps['Survey_Date'] = nps['Survey_Time'].dt.date\nnps['Survey_Date'] = pd.to_datetime(nps['Survey_Date'], format = '%Y-%m-%d')\nnps['Report_Date'] = nps['Survey_Date']\nnps.drop('Survey_Date', axis = 1, inplace = True)\n\n\n# In[67]:\n\n#check if the survey was eligible for VAS. If it was but wasn't enrolled, create a column to point this out.\nvas['VAS_Enrollment'] = np.where((vas['FAP_Enrollment'] + vas['AA_Enrollment'] + vas['DD_Enrollment'] + vas['PBR_Enrollment']) > 0, 'VAS Enrollment', 'No Enrollment' )\nvas['VAS_Eligible_Sum'] = np.where((vas['FAP_Eligible'] + vas['AA_Eligible'] + vas['DD_Eligible'] ) > 0, 1, 0)\nvas['VAS_Eligible'] = np.where((vas['VAS_Eligible_Sum'] + vas['PBR_Enrollment']) > 0, 1, 0)\nvas['VAS_Status'] = np.where((vas['VAS_Enrollment'] == 'No Enrollment') & (vas['VAS_Eligible'] == 1), 'Missing VAS', 'Not Applicable')\nvas['VAS_Record'] = 1\n#separate purpose-disposition, create a simple NPS column to average, fill blanks\nnps['Survey_Count'] = 1\nnps['Channel_Name'].fillna('Unknown', inplace = True)\nnps['Segment'].fillna('Unknown', inplace = True)\nnps['Gross_Debit_Volume'].fillna(0, inplace = True)\nnps['Loyalty_Tag'].fillna('Unknown', inplace = True)\nnps['Call_Reason'].fillna('Unknown', inplace = True)\nnps['Purp-Disp'].fillna('Unknown - Unknown', inplace = True)\nnps['Purpose'], nps['Disposition'] = zip(*nps['Purp-Disp'].apply(lambda x: x.split('-', 1)))\nnps['Disposition'] = nps['Disposition'].map(str.strip)\nnps.drop('Purp-Disp', axis = 1, inplace = True)\nnps['Net_Promoter'] = nps['Net_Promoter'].astype(str).map(lambda x: x.split('.')[0])\nnps['NPS_Score'] = nps['Net_Promoter'].astype(str).map({'10' : -1, '9' : -1, '8' : -1, '7' : -1, '6' : -1, '5' : -1, '4' : -1, '3' : 0, '2' : 0, '1' : 1, '0' : 1})\n\n\n# In[68]:\n\n#create a separate dataframe for blank call_time surveys which can't be merged and calculate the time between the call and survey response\nnps_time = nps[nps['Call_Time'] == np.datetime64('nat')]\nnps = nps[pd.notnull(nps['Call_Time'])]\nnps['Survey_Time_Delta'] = (nps['Survey_Time'] - nps['Call_Time']) / np.timedelta64(1, 'D')\nbins = np.array([0, 3, 7, 14, 21, 30, 1000])\nnps['Survey_Time_Bin'] = pd.cut(nps['Survey_Time_Delta'], bins)\nnps['Survey_Time_Bin'] = nps['Survey_Time_Bin'].map({'(0, 3]' : 'Within 3 Days', '(3, 7]' : '3 - 7 Days', \n '(7, 14]': '7 - 14 Days' , '(14, 21]' : '14 - 21 Days', '(21, 30]' : '21 - 30 Days',\n '(30, 1000]' : '30+ Days'})\n\n\n# In[69]:\n\n#add columns to the AHT data and then merge it to get the split names and tCAM IDs\naht['Total_Time'] = aht['Talk_Time'] + aht['Hold_Time'] + aht['ACW_Time']\naht['AHT_Beyond_15mins'] = np.where(aht['Total_Time'] > 900, 1, 0)\naht['Hold_Beyond_3mins'] = np.where(aht['Hold_Time'] > 180, 1, 0)\naht['Total_Calls'] = 1\naht = pd.merge(aht, splits, how = 'left', on = ['Split'])\nroster2 = roster.copy()\nroster = roster[['Avaya_ID', 'tCAM_ID', 'Report_Date']]\nroster.rename(columns = {'Report_Date' : 'Call_Date'}, inplace = True)\naht = pd.merge(aht, roster, how = 'left', on = ['Avaya_ID', 'Call_Date'])\naht['tCAM_ID'].fillna('Unknown', inplace = True)\naht.drop('Avaya_ID', axis = 1, inplace = True)\n\n\n# In[70]:\n\n#aggregate the AHT data to only have the columns we need, and then make sure that each value is completely unique by setting total_calls == 1\ngrouped_aht = aht.pivot_table(index=['Call_Date','tCAM_ID', 'Queue_Name', 'Program', 'Split_Name', 'Cash_Number'], \n values = ['Total_Calls','Total_Time', 'Talk_Time', 'Hold_Time', 'ACW_Time', 'Hold_Count', 'Released_Calls','AHT_Beyond_15mins','Hold_Beyond_3mins', 'Queue_Time'], \n aggfunc = np.sum, )\ngrouped_aht = grouped_aht.reset_index()\nmissing = ['Unknown']\nmissing_tcam = grouped_aht.loc[grouped_aht['tCAM_ID'].isin(missing)]\ngrouped_aht_unique = grouped_aht[grouped_aht['Total_Calls'] == 1]\n\n\n# In[71]:\n\n#aggregate the NPS data to join to the AHT data to help make sure there will be no duplicates, then merge to the AHT aggregate dataframe to create an AHT per survey dataframe\ngrouped_nps = nps.groupby(['Call_Date','tCAM_ID','Cash_Number'], as_index= False).agg({'Survey_Count': np.sum})\ngrouped_nps = pd.merge(grouped_nps, roster, how = 'left', on = ['tCAM_ID', 'Call_Date'])\ngrouped_nps = grouped_nps[grouped_nps['Survey_Count'] == 1]\naht_per_disp = pd.merge(grouped_nps, grouped_aht_unique, how = 'left', on = ['tCAM_ID', 'Cash_Number', 'Call_Date'])\naht_per_disp = aht_per_disp[pd.notnull(aht_per_disp['Total_Time'])]\naht_per_disp = aht_per_disp[['Call_Date','tCAM_ID', 'Queue_Name', 'Program', 'Split_Name', 'Cash_Number', 'Total_Calls','Total_Time', 'Talk_Time', 'Hold_Time', 'ACW_Time', 'Hold_Count', 'Released_Calls','AHT_Beyond_15mins','Hold_Beyond_3mins', 'Queue_Time']]\n\n\n# In[72]:\n\n# use the same logic to merge the VAS data and create a dataframe where the surveys have VAS or were eligible for VAS\ngrouped_vas = vas.groupby(['Call_Date','tCAM_ID','Cash_Number','VAS_Enrollment', 'VAS_Status'], as_index= False).agg(np.sum)\ngrouped_vas = grouped_vas[grouped_vas['VAS_Eligible']== 1]\nvas_survey = pd.merge(grouped_nps, grouped_vas, how = 'left', on = ['tCAM_ID', 'Cash_Number', 'Call_Date'])\nvas_survey = vas_survey[pd.notnull(vas_survey['VAS_Enrollment'])]\nvas_survey = vas_survey[['Call_Date','tCAM_ID','Cash_Number', 'FAP_Eligible','FAP_Enrollment', 'AA_Eligible', 'AA_Enrollment', 'DD_Eligible', 'DD_Enrollment', 'PBR_Enrollment','VAS_Enrollment', 'VAS_Status']]\n\n\n# In[73]:\n\n# fcr['Total_Hits'] = 1\n# g14 = fcr.groupby([pd.Grouper(freq='14D',key='Call_Time'),'Cash_Number']).sum()\n# g7 = fcr.groupby([pd.Grouper(freq='7D',key='Call_Time'),'Cash_Number']).sum()\n# g3 = fcr.groupby([pd.Grouper(freq='3D',key='Call_Time'),'Cash_Number']).sum()\n\n\n# In[74]:\n\n# g14.rename(columns = {'Total_Hits' :'Previous_Hits_14_Days'}, inplace = True)\n# g14.drop('Future_Hits', axis = 1, inplace = True)\n# g7.rename(columns = {'Total_Hits' :'Previous_Hits_7_Days'}, inplace = True)\n# g7.drop('Future_Hits', axis = 1, inplace = True)\n# g3.rename(columns = {'Total_Hits' :'Previous_Hits_3_Days'}, inplace = True)\n# g3.drop('Future_Hits', axis = 1, inplace = True)\n# g14 = g14.reset_index()\n# g7 = g7.reset_index()\n# g3 = g3.reset_index()\n\n\n# In[75]:\n\n# temp = pd.merge(g14, g7, how ='left', on = ['Call_Time', 'Cash_Number'])\n# previous_hits = pd.merge(temp, g3, how ='left', on = ['Call_Time', 'Cash_Number'])\n# previous_hits['Previous_Hits_14_Days'].fillna(0, inplace = True)\n# previous_hits['Previous_Hits_7_Days'].fillna(0, inplace = True)\n# previous_hits['Previous_Hits_3_Days'].fillna(0, inplace = True)\n\n\n# In[76]:\n\n# nps = pd.merge(nps, previous_hits, how ='left', on = ['Call_Time', 'Cash_Number'])\n\n\n# In[77]:\n\n#merge the VAS surveys back to the original NPS data and fill blanks\nnps = pd.merge(nps, vas_survey, how ='left', on = ['Call_Date', 'Cash_Number', 'tCAM_ID'])\nnps['FAP_Eligible'].fillna(0, inplace = True)\nnps['AA_Eligible'].fillna(0, inplace = True)\nnps['DD_Eligible'].fillna(0, inplace = True)\nnps['FAP_Enrollment'].fillna(0, inplace = True)\nnps['AA_Enrollment'].fillna(0, inplace = True)\nnps['DD_Enrollment'].fillna(0, inplace = True)\nnps['PBR_Enrollment'].fillna(0, inplace = True)\nnps['VAS_Enrollment'].fillna('No Enrollment', inplace = True)\nnps['VAS_Status'].fillna('Not Applicable', inplace = True)\n\n\n# In[78]:\n\n#merge the surveys+VAS back to the AHT details, then merge with the fcr data to get the previous and future hits\nnps = pd.merge(nps, aht_per_disp, how ='left', on = ['Call_Date', 'Cash_Number', 'tCAM_ID'])\nnps['Total_Calls'].fillna(0, inplace = True)\nnps['Total_Time'].fillna(0, inplace = True)\nnps['Talk_Time'].fillna(0, inplace = True)\nnps['Hold_Time'].fillna(0, inplace = True)\nnps['ACW_Time'].fillna(0, inplace = True)\nnps['Queue_Time'].fillna(0, inplace = True)\nnps['Hold_Count'].fillna(0, inplace = True)\nnps['Released_Calls'].fillna(0, inplace = True)\nnps['AHT_Beyond_15mins'].fillna(0, inplace = True)\nnps['Hold_Beyond_3mins'].fillna(0, inplace = True)\nnps['Split_Name'].fillna('No Record', inplace = True)\nnps['Queue_Name'].fillna('No Record', inplace = True)\nnps['Program'].fillna('No Record', inplace = True)\nnps = pd.merge(nps, fcr, how ='left', on = ['Call_Time', 'Call_Date', 'Cash_Number', 'tCAM_ID'])\nnps['Future_Hits'].fillna(0, inplace = True)\nnps['Previous_Hits'].fillna(0, inplace = True)\n\n\n# In[79]:\n\n#add the surveys with no call_time, just in case\ncombined = [nps, nps_time]\nnps = pd.concat(combined)\n\n\n# In[80]:\n\n#add blank QA scrubbing columns\nnps['Correct_Disposition'] = ''\nnps['Call_Recorded'] = ''\nnps['Main Issue'] = ''\nnps['Definition'] = ''\nnps['Rating_Cause'] = ''\nnps['Root_Cause'] = ''\nnps['Resolved'] = ''\nnps['VOC_Product'] = ''\nnps['Self_Help_Offered'] = ''\nnps['Appropriate_Self_Help'] = ''\nnps['Coaching_Commitment'] = ''\nnps['Coaching_Type'] = ''\nnps['Coaching_ID'] = ''\nnps['Recommendation'] = ''\n\n\n# In[81]:\n\n#create bins for various fields\nahtbins = np.array([-1, 0, 300, 600, 900, 1200, 10000])\nnps['AHT_Bin'] = pd.cut(nps['Total_Time'], ahtbins)\nnps['AHT_Bin'] = nps['AHT_Bin'].map({'(-1, 0]': 'No AHT Record', '(0, 300]': '0-5 min', '(300, 600]': '5-10 min', \n '(600, 900]': '10-15 min' , '(900, 1200]':'15-20 min' , '(1200, 10000]': '20+ min'})\n\nwaitbins = np.array([-1, 0, 55, 120, 300, 600, 10000])\nnps['Queue_Bin'] = pd.cut(nps['Queue_Time'], waitbins)\nnps['Queue_Bin'] = nps['Queue_Bin'].map({'(-1, 0]': 'No AHT Record', '(0, 55]': 'Within 55 sec','(55, 120]': '55 sec - 2 min', \n '(120, 300]': '2-5 min' , '(300, 600]':'5-10 min' , '(600, 10000]': '10+ min'})\n\nholdbins = np.array([-1, 0, 60, 120, 180, 300, 600, 10000])\nnps['Hold_Bin'] = pd.cut(nps['Hold_Time'], holdbins)\nnps['Hold_Bin'] = nps['Hold_Bin'].map({'(-1, 0]': 'No Hold Record', '(0, 60]': '0-1 min','(60, 120]': '1-2 min', '(120, 180]': '2-3 min', \n '(180, 300]': '3-5 min' , '(300, 600]':'5-10 min' , '(600, 10000]': '10+ min'})\n\n# callbins = np.array([-1, 0, 1, 3, 5, 10, 20, 30, 10000])\n# nps['Weekly_Calls_Bin'] = pd.cut(nps['Previous_Hits_7_Days'], callbins)\n# nps['Weekly_Calls_Bin'] = nps['Weekly_Calls_Bin'].map({'(-1, 0]': 'First Call','(0, 1]': '1 Prior Call', \n# '(1, 3]': '2-3 Prior Calls' , '(3, 5]':'3-5 Prior Calls' , '(5, 10]':'5-10 Calls' , '(10, 20]':'10-20 Prior Calls' , '(20, 30]':'20-30 Prior Calls' , '(30, 10000]': '30+ Prior Calls'})\n\n\n# In[82]:\n\n#add priority scrubbing column which checks for some cardholder information and the NPS rating\nnps['Red_Flag'] = (((nps['Gross_Debit_Volume'] >= 100000) & (nps['Loyalty_Tag']=='Loyal User') & (nps['NPS_Score'] == -1))).astype(int)\nnps['Scrubbing_Priority'] = nps['Net_Promoter'].astype(str).map({'10':'High','9':'High','8':'High','7':'High','6':'High','5':'High','4':'High','3':'Medium','2':'Medium','1':'Low','0':'Low'})\nnps['Scrubbing_Priority'] = np.where(nps['Red_Flag'] == 1, 'Critical', nps['Scrubbing_Priority'])\n\n\n# In[83]:\n\n#create a field to filter out the non-verbatim surveys\nnps['Service_Verbatim'] = np.where(nps['Improve_Service'].isnull(), 0, 1)\nnps['Product_Verbatim'] = np.where(nps['Improve_Product'].isnull(), 0, 1)\nnps['Verbatim_Exists'] = nps['Service_Verbatim'] + nps['Product_Verbatim']\n\n\n# In[84]:\n\n#add roster details, activity, and tenure\nnps = pd.merge(nps, roster2, how = 'left', on = ['tCAM_ID', 'Report_Date'])\nnps['Tenure_Days'] = (nps['Call_Date'] - nps['Live_Date']) / np.timedelta64(1, 'D')\nnps['Status'] = np.where(nps['Inactive_Date'] > '2010-01-01', 'Inactive', 'Active')\nnps['Employee_ID'].fillna('Unknown', inplace = True)\ntenurebins = np.array([-1000, 1, 30, 60, 90, 180, 365, 20000])\nnps['Tenure_Bin'] = pd.cut(nps['Tenure_Days'], tenurebins)\nnps['Tenure_Bin'] = nps['Tenure_Bin'].map({'(-1000, 1]': 'Nesting', '(1, 30]': '1-30 Days','(30, 60]': '31-60 Days', '(60, 90]': '61-90 Days', \n '(90, 180]': '91-180 Days' , '(180, 365]':'181-365 Days' , '(365, 20000]': '365+ Days'})\n\n\n# In[85]:\n\n#create the dataframe in the order you want it output as\nnps = nps[[ 'Report_Date', 'Call_Time', 'Survey_Time_Delta', 'Survey_Time_Bin', 'Employee_ID', 'tCAM_ID', 'Employee_Name','Team_Manager','Account_Manager','Location_ID', 'LOB', 'Role', 'Batch', 'Live_Date','Tenure_Days','Tenure_Bin', 'Status', 'Cash_Number', 'Channel_Name', 'Distributor', 'Segment', 'Gross_Debit_Volume','ODP','Direct_Deposit', 'Loyalty_Tag', \n 'Split_Name', 'Program', 'Queue_Name', 'Call_Reason', 'Purpose', 'Disposition', 'VAS_Enrollment', 'AA_Eligible', 'AA_Enrollment', 'DD_Eligible', 'DD_Enrollment', 'FAP_Eligible', 'FAP_Enrollment', 'PBR_Enrollment','VAS_Status',\n 'IVR_Satisfaction', 'Understood_Question', 'Resolved_Issue', 'Satisfying_Resolution', 'Timeliness_Resolution', 'First_Call_Resolution', 'Satisfied_Product', 'Continue_netSpend', 'Net_Promoter', 'Queue_Time', 'Talk_Time', 'Hold_Time', 'ACW_Time', 'Total_Time', 'Total_Calls',\n 'AHT_Beyond_15mins', 'Hold_Beyond_3mins', 'Hold_Count', 'Released_Calls', 'CSAT_Score', 'NPS_Score','Survey_Count','Previous_Hits','Future_Hits', 'AHT_Bin', 'Queue_Bin', 'Hold_Bin', 'Improve_Service', 'Improve_Product', 'Verbatim_Exists','Scrubbing_Priority',\n 'Correct_Disposition','Call_Recorded','Main Issue', 'Definition','Rating_Cause','Root_Cause','Resolved', 'VOC_Product','Self_Help_Offered', 'Appropriate_Self_Help', 'Coaching_Commitment','Coaching_Type', 'Coaching_ID', 'Recommendation']]\n\n\n# In[86]:\n\nlocation = r'\\\\mandavfnp01\\NetSpend\\NetSpend Quality Reports\\Tableau Dashboard\\Survey Scrubbing\\\\'\nnps['Report_Date'] = pd.to_datetime(nps['Report_Date'], format = '%Y-%m-%d')\n\nindex = nps.set_index(['Report_Date'], drop= False).sort_index()\n# may = nps.ix['2015-05-01': '2015-05-30']\n# may.to_csv(location+'2015-05_SGS_NPS_Analysis.csv', mode = 'w', header = True, index = False)\n# june = nps.ix['2015-06-01': '2015-06-30']\n# june.to_csv(location+'2015-06_SGS_NPS_Analysis.csv', mode = 'w', header = True, index = False)\n# july = nps.ix['2015-07-01': '2015-07-31']\n# july.to_csv(location+'2015-07_SGS_NPS_Analysis.csv', mode = 'w', header = True, index = False)\n# aug = nps.ix['2015-08-01': '2015-08-31']\n# aug.to_csv(location+'2015-08_SGS_NPS_Analysis.csv', mode = 'w', header = True, index = False)\n\n\n# In[87]:\n\nsep = index.ix['2015-09-01' : '2015-09-30']\nsep.to_csv(location + '2015-09_SGS_NPS_Analysis.csv', mode = 'a', header = False, index = False)\n\n\n# In[89]:\n\n#only look at data beyond a certain date based on the last file created\ndavloc =r'\\\\mandavfnp01\\NetSpend\\NetSpend Quality Reports\\Tableau Dashboard\\Survey Scrubbing\\Davao\\\\'\nfilelist = os.listdir(davloc)\nfor file in filelist:\n date_name = file[19:-4]\n read_date = pd.to_datetime(date_name) + Timedelta(1, unit='d')\nindex = index.ix[read_date:]\n\n\n# In[95]:\n\nindex['Report_Date'] = index['Report_Date'].apply(lambda x:x.date().strftime('%Y-%m-%d'))\n\n\n# In[96]:\n\ntarlac = index[index['Location_ID'] == 'SGS-Tarlac']\ndavao = index[index['Location_ID'] == 'SGS-Davao']\n\n\n# In[97]:\n\ndavloc =r'\\\\mandavfnp01\\NetSpend\\NetSpend Quality Reports\\Tableau Dashboard\\Survey Scrubbing\\Davao\\\\'\ndavaofile = 'NS_Davao_Scrubbing_'\ntarloc =r'\\\\mandavfnp01\\NetSpend\\NetSpend Quality Reports\\Tableau Dashboard\\Survey Scrubbing\\Tarlac\\\\'\ntarfile = 'NS_Tarlac_Scrubbing_'\nfor date in davao['Report_Date'].unique():\n x = davao.loc[date]\n x.to_csv(davloc + davaofile + date + ext, index = False)\nprint('Davao Complete')\nfor date in tarlac['Report_Date'].unique():\n y = tarlac.loc[date]\n y.to_csv(tarloc + tarfile + date + ext, index = False)\nprint('Tarlac Complete')\n\n\n# In[99]:\n\nlocation = r'\\\\mandavfnp01\\NetSpend\\NetSpend Quality Reports\\Tableau Dashboard\\Survey Scrubbing\\\\'\nsummary =sep.pivot_table(index = ['Report_Date'], columns = ['Location_ID', 'Scrubbing_Priority'], values = ['Survey_Count'], aggfunc = {'Survey_Count': np.sum}, fill_value = 0, margins = False)\nsummary.to_csv(location + 'NPS_Scrubbing_Summary.csv', mode = 'a', index = True, header = False)\n\n","sub_path":"Python/25004_Scrubbing.py","file_name":"25004_Scrubbing.py","file_ext":"py","file_size_in_byte":23094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"313496181","text":"'''\nCreated on Aug 18, 2015\n\n@author: olivier\n\nCode for some algorithms with transport\n'''\nimport node\nimport heapq\nimport sys\nimport graph_utilities\n\n''' Dijkstra finds the shortest path in a graph between a source and a sink vertex \n If euclidean then use Euclidean distances else use number of hops'''\ndef dijkstra(g,src,snk,euclidean=True,fromNode = True):\n ''' Compute adjacencies in the graph '''\n g.compute_adjacencies(fromNode)\n ''' set all node weights to be infinity '''\n for key in g.nodes.keys():\n g.nodes[key].weight = sys.maxint\n g.nodes[key].seen = False\n g.nodes[key].next = None\n snk.weight = 0\n heap = []\n heapq.heappush(heap,(0,snk))\n animation_lst = []\n while 1 == 1:\n try:\n (price,node) = heapq.heappop(heap)\n except:\n break\n if not node == snk:\n animation_lst.append([(node.next,price)])\n if node.seen == True:\n continue\n node.seen = True\n if node == src:\n break\n # print node+\" has \"+str(len(node_dic[node].links))+\" links\"\n for e in node.neighs:\n other = e.get_other_vertex(node)\n if euclidean:\n weight = node.weight+e.length\n else:\n weight = node.weight+1\n if weight < other.weight:\n other.weight = weight\n other.next = e\n heapq.heappush(heap,(weight,other))\n continue\n ''' Check that source was reached (source is connected to sink by at least one path'''\n if not src.seen:\n# print 'Could not find a path between source and sink'\n return None,None\n node = src\n shortest_path = []\n while not node == snk:\n e = node.next\n shortest_path.append((e,e.length))\n node = e.get_other_vertex(node)\n return shortest_path,animation_lst\n\n''' TSP from Convex Hull:\n This TSP heuristic works relatively well on graphs with Euclidean distances.\n 1. Find a convex hull of the nodes\n 2. Until all the nodes are in the TSP tour:\n 2.1. Find the node N and TSP link (A,B) that minimizes the difference \n (AN) + (NB) - (AB)\n 2.2 Replace (A,B) with (A,N) and (N,B)\n'''\ndef tsp_convex_hull(g):\n ''' Find the convex hull on the nodes on g '''\n convex_hull = graph_utilities.convexHull(g)\n if not convex_hull:\n return convex_hull\n write_edges = []\n for ix in range(len(convex_hull)):\n e = g.find_edge(convex_hull[ix],convex_hull[(ix+1) % len(convex_hull)])\n if e:\n write_edges.append(e)\n tsp_anim = []\n tsp_anim.append(([],write_edges))\n while len(convex_hull) < len(g.nodes):\n minDist = sys.maxint\n minNode = None\n hullNodeIdx = -1\n for key in g.nodes.keys():\n if g.nodes[key] in convex_hull:\n continue\n for ix in range(len(convex_hull)):\n dist = g.distance(g.nodes[key],convex_hull[ix]) \\\n + g.distance(g.nodes[key],convex_hull[(ix+1) % len(convex_hull)]) \\\n - g.distance(convex_hull[ix],convex_hull[(ix+1) % len(convex_hull)])\n if dist < minDist:\n minNode = g.nodes[key]\n minDist = dist\n hullNodeIdx = ix+1\n erase_edge = [g.find_edge(convex_hull[hullNodeIdx-1],\n convex_hull[hullNodeIdx % len(convex_hull)])]\n write_edges = [g.find_edge(minNode,convex_hull[hullNodeIdx-1]),\n g.find_edge(minNode,convex_hull[hullNodeIdx % len(convex_hull)])]\n tsp_anim.append((erase_edge,write_edges))\n convex_hull.insert(hullNodeIdx,minNode)\n return convex_hull,tsp_anim \n \n''' TSP from Closest neighbor:\n This TSP heuristic works starts from a random node and\n at each step moves to the closest unvisited neighbor.\n'''\ndef tsp_closest(g,ndIdx = None):\n ''' Select a random node in g '''\n nodes = g.get_nodes()\n for key in nodes.keys():\n nodes[key].seen = False\n if ndIdx == None:\n nd = g.get_random_node()\n else:\n nd = nodes[ndIdx]\n nd.seen = True\n visited = [nd]\n tsp_anim = []\n while True:\n nd1 = visited[len(visited)-1]\n minDist = sys.maxint\n nd2 = None\n for key in nodes.keys():\n nd = nodes[key]\n if nd.seen:\n continue\n if g.distance(nd1,nd) < minDist:\n minDist = g.distance(nd1,nd)\n nd2 = nd\n if not nd2:\n break\n visited.append(nd2)\n nd2.seen = True\n e = g.find_edge(nd1,nd2)\n tsp_anim.append(([],[e]))\n e = g.find_edge(visited[len(visited)-1],visited[0])\n tsp_anim.append(([],[e]))\n return visited,tsp_anim \n\n''' In this heuristic we start from a TSP tour and try to improve the tour with \n a series of 2-exchanges. Let (a,b) and (c,d) be two connections of the TSP tour.\n If (a,c)+(b,d) < (a,b)+(c,d), then reverse the sequence from b to c.\n'''\ndef tsp_2_exchange(g,tour):\n flag = True\n tsp_anim = []\n while flag:\n flag = False\n for ix1 in range(len(tour)-2):\n d1 = g.distance(tour[ix1],tour[ix1+1])\n for ix2 in range(ix1+2,len(tour)):\n d2 = g.distance(tour[ix2],tour[(ix2+1) % len(tour)])\n d3 = g.distance(tour[ix1],tour[ix2])\n d4 = g.distance(tour[ix1+1],tour[(ix2+1) % len(tour)])\n if d1+d2 > d3+d4:\n# tourtxt = str(ix1)+' '+str(ix2)+' start'\n# for nd in tour:\n# tourtxt += ' '+str(nd.idx)\n# print tourtxt\n e1 = g.find_edge(tour[ix1],tour[ix1+1])\n e2 = g.find_edge(tour[ix2],tour[(ix2+1) % len(tour)])\n e3 = g.find_edge(tour[ix1],tour[ix2])\n e4 = g.find_edge(tour[(ix2+1)%len(tour)],tour[ix1+1])\n tsp_anim.append(([e1,e2],[e3,e4]))\n for ix in range(ix2-ix1):\n v = tour.pop(ix2)\n tour.insert(ix1+1+ix,v)\n# tourtxt = ''\n# for nd in tour:\n# tourtxt += ' '+str(nd.idx)\n# print tourtxt\n flag = True\n break\n if flag:\n break\n return tour,tsp_anim\n","sub_path":"transport_algorithms.py","file_name":"transport_algorithms.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"383274629","text":"import pytest\n\nimport numpy as np\n\nimport simulacra as si\n\n\n@pytest.mark.parametrize(\n 'answer',\n [\n 'foobar',\n 'wizbang',\n 'floof',\n '1203',\n '15.194',\n ]\n)\ndef test_ask_for_input_str(mocker, answer):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = answer)\n\n assert si.cluster.ask_for_input('?') == answer\n\n\n@pytest.mark.parametrize(\n 'answer',\n [\n '5',\n '1233',\n '102319',\n ]\n)\ndef test_ask_for_input_int(mocker, answer):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = answer)\n\n assert si.cluster.ask_for_input('?', cast_to = int) == int(answer)\n\n\n@pytest.mark.parametrize(\n 'answer',\n [\n '5',\n '1233',\n '102319',\n '5091.59324',\n '10.24102',\n ]\n)\ndef test_ask_for_input_float(mocker, answer):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = answer)\n\n assert si.cluster.ask_for_input('?', cast_to = float) == float(answer)\n\n\n@pytest.mark.parametrize(\n 'answer',\n [\n 'true',\n 'TrUe',\n 't',\n 'T',\n 'yes',\n 'y',\n 'YeS',\n '1',\n 'on',\n ]\n)\ndef test_ask_for_bool_with_true(mocker, answer):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = answer)\n\n assert si.cluster.ask_for_bool('?')\n\n\n@pytest.mark.parametrize(\n 'answer',\n [\n 'false',\n 'faLSE',\n 'f',\n 'F',\n 'no',\n 'NO',\n 'n',\n '0',\n 'off',\n ]\n)\ndef test_ask_for_bool_with_false(mocker, answer):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = answer)\n\n assert not si.cluster.ask_for_bool('?')\n\n\ndef test_ask_for_eval_with_np_linspace(mocker):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = 'np.linspace(0, 1, 100)')\n\n assert np.all(si.cluster.ask_for_eval('?') == np.linspace(0, 1, 100))\n\n\ndef test_ask_for_eval_with_units(mocker):\n mocker.patch('simulacra.cluster.job_creation.input', return_value = '10 * u.THz')\n\n assert si.cluster.ask_for_eval('?') == 10 * si.units.THz\n","sub_path":"tests/cluster/test_ask.py","file_name":"test_ask.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"144193504","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport tempfile\nfrom urllib.parse import parse_qs\n\ndef getRequestCount(file):\n if not os.path.isfile(file):\n return 0\n\n with open(file, 'r') as file:\n return int(file.read())\n\ndef setRequestCount(file, count):\n with open(file, 'r') as file:\n file.write(count)\n\nquery = parse_qs(os.environ.get('QUERY_STRING', ''), keep_blank_values=True)\nfilename = query.get('filename', [''])[0]\nmode = query.get('mode', [''])[0]\n\ntmpFile = os.path.join(tempfile.gettempdir(), filename)\ncurrentCount = getRequestCount(tmpFile)\n\nif mode == 'getFont':\n setRequestCount(tmpFile, currentCount + 1)\n sys.stdout.write(\n 'Access-control-max-age: 0\\r\\n'\n 'Access-control-allow-origin: *\\r\\n'\n 'Access-control-allow-methods: *\\r\\n'\n 'Cache-Control: max-age=0\\r\\n'\n 'Content-Type: application/octet-stream\\r\\n\\r\\n'\n )\nelse:\n sys.stdout.write(\n 'Access-control-max-age: 0\\r\\n'\n 'Access-control-allow-origin: *\\r\\n'\n 'Access-control-allow-methods: *\\r\\n\\r\\n'\n '{}'.format(currentCount)\n )","sub_path":"LayoutTests/http/tests/css/resources/webfont-request.py","file_name":"webfont-request.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"542603235","text":"# -*- coding: utf-8 -*-\r\n\r\nimport random\r\nimport math\r\nimport statistics\r\nimport copy\r\n\r\n\r\nclass DE_params(object):\r\n\r\n default_value = {\r\n 'f': 0.5,\r\n 'cr': 0.5,\r\n 'crs': 'bin',\r\n 'base': 'rand1',\r\n 'p': None,\r\n 'f2': None\r\n }\r\n\r\n def __init__(self,\r\n n_gene,\r\n n_po,\r\n n_generation,\r\n g_min,\r\n g_max,\r\n eval_func):\r\n\r\n self.N_GENE = n_gene # 遺伝子長\r\n self.N_POP = n_po # 1世代の個体数\r\n self.N_GENERATION = n_generation # 最大計算世代数\r\n self.GENE_MIN = g_min # 遺伝子の最小値\r\n self.GENE_MAX = g_max # 遺伝子の最大値\r\n self.EVALUATE_FUNCTION = eval_func # 評価関数\r\n\r\n # set_paramで変更可能\r\n # スケーリングパラメータ\r\n self.SCALING_PARAMETER = DE_params.default_value['f']\r\n # 交叉率\r\n self.CROSSOVER_RATE = DE_params.default_value['cr']\r\n # 交叉方法\r\n self.CROSSOVER_TYPE = DE_params.default_value['crs']\r\n # ベースベクトル選択方法\r\n self.BASE = DE_params.default_value['base']\r\n # 上位層のパーセンテージ(current-to-p_best)\r\n self.TOP_PERCENT = DE_params.default_value['p']\r\n # スケーリングパラメータ\r\n self.SCALING_PARAMETER2 = DE_params.default_value['f2']\r\n\r\n try:\r\n super().__init__()\r\n except AttributeError:\r\n pass\r\n\r\n def set_param(\r\n self,\r\n f=None,\r\n cr=None,\r\n crs=None,\r\n base=None,\r\n p=None,\r\n f2=None,\r\n ):\r\n\r\n if f is not None:\r\n self.SCALING_PARAMETER = f\r\n if mu is not None:\r\n self.CROSSOVER_RATE = cr\r\n if el is not None:\r\n self.CROSSOVER_TYPE = crs\r\n if nt is not None:\r\n self.BASE = base\r\n if pe is not None:\r\n self.TOP_PERCENT = p\r\n if lg is not None:\r\n self.SCALING_PARAMETER2 = f2\r\n\r\n try:\r\n super().set_param(f, cr, crs, base, p, f2)\r\n except AttributeError:\r\n pass\r\n\r\n\r\nclass DE_evaluate(object):\r\n\r\n def get_score(self, population):\r\n\r\n score_list = [None] * len(population)\r\n for i, p in enumerate(population):\r\n score_list[i] = p['score']\r\n\r\n try:\r\n super().get_score(population)\r\n except AttributeError:\r\n pass\r\n\r\n return score_list\r\n\r\n def calc_score(self, x, eval_func):\r\n\r\n try:\r\n super().calc_score(x)\r\n except AttributeError:\r\n pass\r\n\r\n return eval_func(x)\r\n\r\n def evaluate(self, population, eval_val):\r\n\r\n for p in population:\r\n if p['score'] is None:\r\n p['score'] = self.calc_score(p['gene'], eval_func)\r\n\r\n try:\r\n super().evaluate(population)\r\n except AttributeError:\r\n pass\r\n\r\n return fitness\r\n\r\n\r\nclass DE_method(DE_evaluate):\r\n\r\n def __get_population(self, n_pop, n_gene, gene):\r\n\r\n g_min, g_max = gene\r\n for i in range(n_pop):\r\n population = [\r\n random.uniform(g_min, g_max)\r\n for _ in range(n_gene)]\r\n\r\n yield population\r\n\r\n def __select_method(self, population, base, trg, p):\r\n\r\n if base == 'rand1':\r\n selected = random.sample(population, 3)\r\n elif base == 'rand2':\r\n selected = random.sample(population, 5)\r\n elif base == 'best':\r\n population.sort(\r\n key=lambda x: (x['score'] is not None, x),\r\n reverse=True)\r\n selected = [None] * 3\r\n selected[0] = population[0]\r\n selected[1:] = random.sample(population[1:], 2)\r\n elif base == 'current-to':\r\n if trg is None:\r\n print('target is None')\r\n return\r\n selected = [None] * 3\r\n selected[0] = trg\r\n selected[1:] = random.sample(population, 2)\r\n elif any(base == b for b in (\r\n 'current-to-best', 'current-to-p_best')):\r\n if trg is None:\r\n print('target is None')\r\n return\r\n population.sort(\r\n key=lambda x: (x['score'] is not None, x),\r\n reverse=True)\r\n selected = [None] * 5\r\n selected[0:3:2] = trg\r\n if base == 'current-to-best':\r\n selected['gene'] = population[0]\r\n selected[3:] = random.sample(population[1:], 2)\r\n else:\r\n s = random.sample(\r\n population[\r\n :math.ceil(len(population) * p / 100)], 3)\r\n s.sort(\r\n key=lambda x: (x['score'] is not None, x),\r\n reverse=True)\r\n selected['gene'] = s[0]\r\n selected[3:] = s[1:]\r\n else:\r\n print('Unknown base')\r\n return\r\n\r\n return selected\r\n\r\n def __mutate(self, selected, f, base, f2):\r\n\r\n if any(base == b for b in (\r\n 'rand1', 'best', 'current-to')):\r\n parent1, parent2, parent3 = selected\r\n mutant = parent1['gene'] + \\\r\n f * (parent2['gene'] - parent3['gene'])\r\n elif base == 'rand2':\r\n parent1, parent2, parent3, parent4, parent5 = selected\r\n mutant = parent1['gene'] + \\\r\n f * (parent2['gene'] - parent3['gene']) + \\\r\n f * (parent4['gene'] - parent5['gene'])\r\n elif any(base == b for b in (\r\n 'current-to-best', 'current-to-p_best')):\r\n if f2 is None:\r\n print('Scaling Factor is None')\r\n return\r\n parent1, parent2, parent3, parent4, parent5 = selected\r\n mutant = parent1['gene'] + \\\r\n f2 * (parent2['gene'] - parent3['gene']) + \\\r\n f * (parent4['gene'] - parent5['gene'])\r\n else:\r\n print('Unknown base')\r\n return\r\n\r\n return mutant\r\n\r\n def __crossover(self, parent, mutant, cr, crs):\r\n\r\n l_parent = len(parent)\r\n rd = random.random\r\n j = random.randint(0, l_parent - 1)\r\n if crs == 'bin':\r\n child = [\r\n gm if rd() < cr or i == j else g1\r\n for i, (gp, gm) in enumerate(zip(parent, mutant))\r\n ]\r\n elif crs == 'exp':\r\n child = copy.deepcopy(parent)\r\n for k in range(j + 1, l_parent):\r\n if rd() >= cr:\r\n child[j:k - 1] = mutant[j:k - 1]\r\n break\r\n else:\r\n child[j:] = mutant[j:]\r\n else:\r\n print('Unknown mode')\r\n return\r\n\r\n return child\r\n\r\n def DE_main(\r\n self, n_generation, n_pop, n_gene, gene, eval_func, f,\r\n cr, crs, base, p, f2):\r\n\r\n population = [\r\n {'score': None, 'gene': p}\r\n for p in super().get_population(n_pop, n_gene, gene)\r\n ]\r\n super().evaluate(population, eval_func)\r\n\r\n for g in range(n_generation):\r\n print('Generation: ' + str(g + 1))\r\n for i in range(n_pop):\r\n parent = population[i]\r\n population.pop(i)\r\n\r\n selected = self.__select_method(\r\n population, base, parent, p)\r\n mutant = self.__mutate(selected, f, base, f2)\r\n child = self.__crossover(\r\n parent['gene'], mutant, cr, crs)\r\n score_child = super().calc_score(child, eval_func)\r\n if score_child > parent[0]:\r\n population.append((score_child, child))\r\n else:\r\n population.append(parent)\r\n\r\n score = super().get_score(population)\r\n\r\n print('min: ', min(score)) # 最も低い評価を表示\r\n print('max: ', max(score)) # 最も高い評価を表示\r\n print('ave: ', statistics.mean(score)) # 評価の平均値を表示\r\n\r\n population.sort(\r\n key=lambda x: (x['score'] is not None, x),\r\n reverse=True)\r\n\r\n return population\r\n\r\n\r\nclass DE(DE_params, DE_method):\r\n\r\n def __init__(\r\n self, n_gene, n_po, n_generation, g_min, g_max,\r\n eval_func, f, cr):\r\n\r\n super().__init__(\r\n n_gene, n_po, n_generation, g_min, g_max, eval_func,\r\n f, cr)\r\n\r\n def main(self):\r\n\r\n gene = (self.GENE_MIN, self.GENE_MAX)\r\n population = super().DE_main(\r\n self.N_GENERATION, self.N_POP, self.N_GENE, gene,\r\n self.EVALUATE_FUNCTION, self.SCALING_PARAMETER,\r\n self.CROSSOVER_RATE, self.CROSSOVER_TYPE, self.BASE,\r\n self.TOP_PERCENT, self.SCALING_PARAMETER2)\r\n\r\n print('best')\r\n print(population[0]) # 最も高い評価の個体を表示\r\n\r\n# http://www.ints.info.hiroshima-cu.ac.jp/~kushida/ML/ML11.pdf\r\n# https://qiita.com/LeftLetter/items/124461ff2f0841d9132b","sub_path":"python/de.py","file_name":"de.py","file_ext":"py","file_size_in_byte":9225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"238819275","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass DQN(nn.Module):\n def __init__(self, state_size, action_size, hidden_size):\n\n super(DQN, self).__init__()\n\n self.fc1 = nn.Linear(state_size, hidden_size)\n self.fc2 = nn.Linear(hidden_size, hidden_size)\n self.fc3 = nn.Linear(hidden_size, hidden_size)\n self.fc4 = nn.Linear(hidden_size, action_size)\n\n def forward(self, state):\n \"\"\"Build a network that maps state -> action Q values.\"\"\"\n x = self.fc1(state)\n x = F.relu(x)\n x = self.fc2(x)\n x = F.relu(x)\n x = self.fc3(x)\n x = F.relu(x)\n action_values = self.fc4(x)\n\n return action_values\n","sub_path":"src/dqn/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"162289637","text":"import numpy as np\nimport os\nimport sys\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nfrom data_loader import ASLDataset, PreprocessSample, PreprocessAlphaEmbd\nfrom network_parameters import *\nfrom model_classes import ConcatFusionLSTM, LogitFusionLSTM, AttConcatFusionLSTM\n\nfusion_type = args.fusion_type\ntest_model = args.test_model\nsave_loc = args.save_dir\nsave_model = args.save_model\nnum_epochs = args.num_epochs\nbatch_size = args.batch_size\nnum_layers = args.num_layers\nnum_layers_sk = args.num_layers_sk\nlearning_rate = args.learning_rate\nsample_rate = args.sample_rate\nsample_rate_sk = args.sample_rate_sk\n#input_len = args.input_len\ninput_loc = args.data_dir\nhidden_size = args.state_size\nhidden_size_sk = args.state_size_sk\ndrop_out = args.drop_out\n\n\ndef print_args():\n for arg in vars(args):\n print (arg, getattr(args, arg))\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint ('device', device)\n\ninput_path = os.path.join(input_loc)\ntrain_dataset = ASLDataset(input_path, train_subs, transform=PreprocessAlphaEmbd(sample_rate, sample_rate_sk))\ntrain_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=6)\ntest_dataset = ASLDataset(input_path, test_subs, transform=PreprocessAlphaEmbd(sample_rate, sample_rate_sk))\ntest_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True, num_workers=6)\n\ndata_sample = test_dataset[0]\nsk_input_len = data_sample['sk_frames'].shape[-1]\nembd_input_len = data_sample['rgb_dat'].shape[-1]\n\nlabel2temp, temp2label = test_dataset.get_label_dicts()\nnum_class = len(label2temp)\n\nif test_model=='': \n if fusion_type=='focus_concat':\n model = AttConcatFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out)\n if fusion_type=='concat':\n model = ConcatFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out)\n if fusion_type=='sum':\n model = LogitFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out, fusion_type=fusion_type)\n if fusion_type=='mean':\n model = LogitFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out, fusion_type=fusion_type)\n if fusion_type=='only_sk':\n model = LogitFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out, fusion_type=fusion_type)\n if fusion_type=='only_embd':\n model = LogitFusionLSTM((embd_input_len, sk_input_len), (hidden_size, hidden_size_sk), (num_layers, num_layers_sk), num_class, drop_out, fusion_type=fusion_type)\nelse:\n model = torch.load(os.path.join(save_loc, test_model))\n\n'''\nfor name, param in model.named_parameters():\n if param.requires_grad:\n print (name, param.size())\nsys.exit()\n'''\nmodel.to(device)\nloss_fn = torch.nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(list(model.parameters()), lr=learning_rate)\n\nmodel_name = '{}_{}_I{}_{}_H{}_{}_L{}_{}'.format(fusion_type, args.test_subj, embd_input_len,sk_input_len, hidden_size, hidden_size_sk, num_layers, num_layers_sk)\nrun_mode = [' ##TRAIN##', ' @@TEST@@ ']\nbest_test_acc = 0.\nbest_id = 0\nif test_model!='':\n num_epochs = 1\nfor ep in range(num_epochs):\n for r, dataloader in enumerate([train_dataloader, test_dataloader]):\n if r==0 and test_model!='':\n continue\n ep_loss, ep_acc = [], []\n model.train() # default train mode\n if r==1: # evaluation mode for dropout\n model.eval()\n for i_batch, batch in enumerate(dataloader):\n x_dat = batch['rgb_dat'].float()\n y_dat = batch['labels']\n x_dat_sk = batch['sk_frames'].float()\n \n x_dat = x_dat.to(device)\n x_dat_sk = x_dat_sk.to(device)\n y_dat = y_dat.to(device)\n \n effective_batch = x_dat.size()[0]\n if args.fusion_type=='focus_concat':\n y_logits, scores = model((x_dat, x_dat_sk))\n else:\n y_logits = model((x_dat, x_dat_sk))\n loss = loss_fn(y_logits, y_dat)\n ep_loss.append(loss.item()*effective_batch)\n preds = torch.max(y_logits, dim=-1)[1]\n acc = ((y_dat==preds).float().mean())\n if i_batch%10==0:\n print ('** {} ** batch loss '.format(run_mode[r]), i_batch, loss.item(), \"accuracy \", acc.item())\n #print (scores.mean(dim=0))\n ep_acc.append(acc.item()*effective_batch)\n data_len = len(test_dataset)\n if r==0:\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n data_len = len(train_dataset)\n print ('** {} ** EP: '.format(run_mode[r]), ep, sum(ep_loss)/data_len, sum(ep_acc)/data_len, flush=True)\n if test_model!='':\n break\n if r:\n if best_test_acc < sum(ep_acc)/data_len:\n best_test_acc = sum(ep_acc)/data_len\n best_id = ep\n if save_model:\n torch.save(model, os.path.join(save_loc, model_name))\n print ('==>> best so far', best_test_acc, best_id, '<==', flush=True)\n print_args()\nprint ('best test acc and ep id (during training)', best_test_acc, best_id) \n","sub_path":"unused/alpha_fusion_rnn.py","file_name":"alpha_fusion_rnn.py","file_ext":"py","file_size_in_byte":5207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"62285332","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\n #обращаю внимание, тест должен упасть с ошибкой NoSuchElementException\nbrowser = webdriver.Chrome()\nbrowser.get(\"http://suninjuly.github.io/registration1.html\")\n\ninput1 = browser.find_element_by_css_selector(\"div.first_block > div.form-group.first_class > input\")\ninput1.send_keys(\"Slava\")\ninput2 = browser.find_element_by_css_selector(\"div.first_block > div.form-group.second_class > input\")\ninput2.send_keys(\"Ego\")\ninput3 = browser.find_element_by_css_selector(\"div.first_block > div.form-group.third_class > input\")\ninput3.send_keys(\"slavkoego@gmail.com\")\n# Отправляем заполненную форму\nbutton = browser.find_element_by_css_selector(\"button.btn\").click()\n\n # Проверяем, что смогли зарегистрироваться\n # ждем загрузки страницы\ntime.sleep(1)\n\n # находим элемент, содержащий текст\nwelcome_text_elt = browser.find_element_by_tag_name(\"h1\")\n # записываем в переменную welcome_text текст из элемента welcome_text_elt\nwelcome_text = welcome_text_elt.text\n\n # с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта\nassert \"Congratulations! You have successfully registered!\" == welcome_text\n\n # ожидание чтобы визуально оценить результаты прохождения скрипта\ntime.sleep(3)\n # закрываем браузер после всех манипуляций\nbrowser.quit()\n\n","sub_path":"python_selenium/test1-6.py","file_name":"test1-6.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"137169648","text":"'''\nCS 119\nProgrammer: Ruben Antonio Mejia Corleto\nDate: 03/11/2021\nDescription: A program to determine the drink size and price multiplier based on the letter the user enters\n in the Coffee Vending Machine.\n The machine provides coffee in three sizes: small (9oz), medium (12oz), and large (15oz).\n The program prints a message to the user giving the various drink size options and then prompts the user\n for the drink size. \n The user can enter an ‘s’ or‘S’ for small, an ‘m’ or ‘M’ for medium, and an ‘l’ or ‘L’ for large. \n Depending on which size the user requests, it prints a message such as: \n “You have ordered a (small, medium, large) drink.” \n In addition to displaying the size ordered, it also record a price multiplier. \n The price multiplier for a small is 1, for a medium is 2, and for a large is 3. \n If the user does not enter a valid character, print an error message (such as “Error: Invalid drink size”)\n and exit the program. \n The program uses if-then-else statements for this problem.\n After the if-then-else statements, it prints the value of the price multiplier to ensure that the correct\n value was recorded. \n'''\n\n#Asks user for input for size of drink\ndrinkSizeLetter = input(\"Choose your coffee size (S)mall (9oz), (M)edium (12oz) or (L)arge (15oz): \")\n\n#Validates input, sets the size chosen, assigns a price multiplier and displays size and multiplier.\nif drinkSizeLetter == \"S\" or drinkSizeLetter == 's':\n drinkSize = \"small\"\n priceMultiplier = 1\nelif drinkSizeLetter == \"M\" or drinkSizeLetter == \"m\":\n drinkSize = \"medium\"\n priceMultiplier = 2\nelif drinkSizeLetter == \"L\" or drinkSizeLetter == \"l\":\n drinkSize = \"large\"\n priceMultiplier = 3\nelse:\n print (\"Error: Invalid drink size\")\n quit()\nprint (\"You have ordered a \" + drinkSize + \" drink.\")\nprint (\"The price multiplier is \" + str(priceMultiplier))\n","sub_path":"Project2/Program2.py","file_name":"Program2.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"270214287","text":"\"\"\"\ncassandra 3.7.0 (Ubuntu 14.04)\n\"\"\"\nimport common.config as config\nimport plugin_dir.plugin_installer_test as t_inst\nimport plugin_dir.collectd.cassandra as p_inst\n\n\nclass CassandraConfiguratorTest(\n t_inst.PluginInstallerTest, p_inst.CassandraConfigurator):\n\n def collect_data(self):\n \"\"\"\n data = {\n 'url': url\n }\n base serviceurl\n 'service:jmx:rmi:///jndi/rmi://localhost:7199/jmxrmi'\n \"\"\"\n data = {\n 'url': 'service:jmx:rmi:///jndi/rmi://localhost:7199/jmxrmi'\n }\n\n return data\n\n\nif __name__ == '__main__':\n cassandra = CassandraConfiguratorTest(\n 'DEBIAN', 'COLLECTD', 'java', 'test_wavefront_cassandra.conf')\n config.INSTALL_LOG = '/dev/stdout'\n cassandra.install()\n","sub_path":"app-config/WF-PCInstaller/plugin_dir/collectd/test/cassandra_test.py","file_name":"cassandra_test.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"50952942","text":"import numpy as np\nfrom os import urandom\n\ndef WORD_SIZE():\n return(16);\n\ndef ALPHA():\n return(5);\n\ndef BETA():\n return(1);\n\nMASK_VAL = 2 ** WORD_SIZE() - 1;\nRC=2** WORD_SIZE() - 4\n\ndef shuffle_together(l):\n state = np.random.get_state();\n for x in l:\n np.random.set_state(state);\n np.random.shuffle(x);\n\ndef rol(x,k):\n return(((x << k) & MASK_VAL) | (x >> (WORD_SIZE() - k)));\n\ndef ror(x,k):\n return((x >> k) | ((x << (WORD_SIZE() - k)) & MASK_VAL));\n\ndef enc_one_round(p, k):\n # L = p[1]\n # R= (p[0] & rot(p[0], alpha) ^ p[1] ^ rot(p[0], beta) ^k\n c1=p[0]\n c0=(p[0] & rol(p[0], ALPHA())) ^ p[1] ^ rol(p[0], BETA()) ^ k\n return(c0,c1);\n\ndef dec_one_round(c,k):\n return enc_one_round([c[1], c[0]], k)\n\ndef get_sequence(num_rounds):\n if num_rounds < 40:\n states = [1] * 5\n else:\n states = [1] * 6\n\n for i in range(num_rounds - 5):\n if num_rounds < 40:\n feedback = states[i + 2] ^ states[i]\n else:\n feedback = states[i + 1] ^ states[i]\n states.append(feedback)\n\n return tuple(states)\n\n\ndef expand_key_simeck(k, t):\n ks = [0 for i in range(t)];\n ks[0] = k[len(k)-1];\n l = list(reversed(k[:len(k)-1]));\n seq=get_sequence(t)\n for i in range(t-1):\n l[i%3], ks[i+1] = enc_one_round((l[i%3], ks[i]), RC^seq[i]);\n print(ks)\n return(ks);\n\ndef encrypt_simeck(p, ks):\n x, y = p[0], p[1];\n for k in ks:\n x,y = enc_one_round((x,y), k);\n return(x, y);\n\ndef decrypt(c, ks):\n x, y = c[0], c[1];\n for k in reversed(ks):\n x, y = dec_one_round((x,y), k);\n return(x,y);\n\ndef check_testvector():\n key = (0x1918,0x1110,0x0908,0x0100)\n pt = (0x6565, 0x6877)\n ks = expand_key_simeck(key, 32)\n ct = encrypt_simeck(pt, ks)\n if (ct == (0x770d, 0x2c76)):\n print(\"Testvector verified.\")\n return(True);\n else:\n print(\"Testvector not verified.\")\n return(False);\n\n","sub_path":"src/data_cipher/cipher_simeck.py","file_name":"cipher_simeck.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"365889118","text":"\"\"\"\nCSAPX Lab 3: Merchants of Venice\n\nGiven a list of merchants at integer locations on a road, find the optimal\nlocation to place a new merchant, such that the sum of the distances the\nnew merchant must travel to all other merchants is minimized.\n\n$ python3 merchants.py [slow|fast] input-file\n\nAuthor: Sean Strout @ RIT CS\nAuthor: Rhythm Patel\n\"\"\"\n\nimport collections # namedtuple\nimport sys # arg\nimport time # clock\nimport random # random\n\nfrom typing import List\nfrom typing import Tuple\n\n\n'''\nMerchant: \n String - name : Merchant's name\n Integer - location: Merchant's location\n'''\nMerchant = collections.namedtuple('Merchant', ('name', 'location')) #Created a merchant type through which the data sent to sorted\n\ndef read_merchants( filename: str ) -> List[ Merchant ]:\n \"\"\"\n :return: A list of merchants\n Read merchant from a file into a list of merchant namedtuples.\n :param filename: The name of the file\n \"\"\"\n merchants = list( )\n with open( filename ) as f:\n for line in f:\n fields = line.split( ' ' )\n merchants.append( Merchant(\n name=(fields[ 0 ]),\n location=int(fields[ 1 ])\n ) )\n return merchants\n\ndef _partition(data: List[Merchant], pivot: Merchant) \\\n -> Tuple[List[Merchant], List[Merchant], List[Merchant]]:\n \"\"\"\n Three way partition the data into smaller, equal and greater lists,\n in relationship to the pivot\n :param data: The data to be sorted (a list)\n :param pivot: The value to partition the data on\n :return: Three list: smaller, equal and greater\n \"\"\"\n less, equal, greater = [], [], []\n for element in data:\n if element.location < pivot.location:\n less.append(element)\n elif element.location > pivot.location:\n greater.append(element)\n else:\n equal.append(element)\n return less, equal, greater\n\n\ndef quick_sort(data: List[Merchant]) -> List[Merchant]:\n \"\"\"\n Performs a quick sort and returns a newly sorted list\n :param data: The data to be sorted (a list)\n :return: A sorted list\n \"\"\"\n if len(data) == 0:\n return []\n else:\n pivot = data[0]\n less, equal, greater = _partition(data, pivot)\n return quick_sort(less) + equal + quick_sort(greater)\n\ndef quick_select(data: List[Merchant],k: int)-> List[Merchant]: #Quick Select Method (faster way to sort)\n \"\"\"\n Performs a quick sort and returns a newly sorted list\n :param data: The data to be sorted (a list)\n :return: A sorted list\n \"\"\"\n if len(data) == 0:\n return []\n else:\n pivot = data[0]\n less, equal, greater = _partition(data, pivot)\n if len(less) <= k < (len(less)+len(equal)): #If k is between the size of the 'smaller'list and the 'equal' list, return the equal element\n return pivot\n elif len(less)>k: #if k is in the smaller list, return the quick select method again to search for the kth element in the smaller array\n return quick_select(less, k)\n else: #if k is in the greater list return\n return quick_select(greater, k - len(less) - len(equal))\n\ndef distance_sum(data: List[Merchant]) -> List[Merchant]: #Method that accesses the location of all the merchants from a data list and finds the sum of the location values\n x = 0\n lst = read_merchants(sys.argv[2])\n for i in range(len(lst)):\n x += lst[i].location\n return x\n\ndef main() -> None:\n \"\"\"\n The main function.\n :return: None\n \"\"\"\n\n merchants = read_merchants(sys.argv[2])\n k = len(merchants)//2\n\n if sys.argv[1] == 'slow':\n print('$ python3 merchant.py' + ' ' + str(sys.argv[1]) + ' ' + str(sys.argv[2]))\n print('Search Type: slow')\n print('Number of Merchants: ', len(merchants))\n start = time.time() #Starts the timer\n sortedMerchants = list(quick_sort(merchants))\n end = time.time() #Stops the timer\n t1 = end - start\n print('Elapsed Time: ', t1)\n print('Optimal store location: ', sortedMerchants[k])\n print('Sum of Distances:', str(distance_sum(merchants)))\n\n else: #sys.argv[1] == 'fast':\n print('$ python3 merchant.py' + ' ' + str(sys.argv[1]) + ' ' + str(sys.argv[2]))\n print('Search Type: fast')\n print('Number of Merchants: ', len(merchants))\n s = time.time()\n Value = quick_select(merchants, k)\n e = time.time()\n t0 = e-s\n print('Elapsed Time: ', t0)\n print('Optimal store location: ', Value)\n print('Sum of Distances:', str(distance_sum(merchants)))\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/merchants.py","file_name":"merchants.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"18758947","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('camo', '0038_pot_group_done_aso'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='operation',\n name='hours',\n ),\n migrations.AddField(\n model_name='operation',\n name='tth_end',\n field=models.DecimalField(max_digits=6, default=0, verbose_name='Licznik końcowy', decimal_places=1),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='operation',\n name='tth_start',\n field=models.DecimalField(max_digits=6, default=0, verbose_name='Licznik początkowy', decimal_places=1),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='operation',\n name='landings',\n field=models.IntegerField(verbose_name='Liczba lądowań'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='operation',\n name='operation_date',\n field=models.DateField(verbose_name='Data operacji'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='operation',\n name='pdt_ref',\n field=models.CharField(max_length=30, verbose_name='PDT Ref.'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='pot_group',\n name='done_aso',\n field=models.ForeignKey(verbose_name='Organizacja', to='camo.ASO'),\n preserve_default=True,\n ),\n ]\n","sub_path":"camo/migrations/0039_auto_20150409_1232.py","file_name":"0039_auto_20150409_1232.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277535850","text":"import pandas as pd\n\ndef importHighflowResults(files):\n classes = {}\n\n for i, file in enumerate(files):\n currentClass = 'class{}'.format(int(file[31]))\n currentFile = pd.read_csv(file, sep=',', dtype=str)\n currentFile.index = currentFile.iloc[:,0]\n currentFile.drop(['Year'], axis=1, inplace=True)\n if currentClass in classes:\n classes[currentClass].append(currentFile)\n continue\n classes[currentClass] = [currentFile]\n return classes\n\n","sub_path":"Utils/importHighflowResults.py","file_name":"importHighflowResults.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"149473418","text":"import random\nfrom time import sleep\n\n# 21 game. It takes 1 player and 1 dealer. they each get 3 cards. the sum of the 3 cards is checked to see =21\n# Player is able to hit (gain another card if the original card sum way less than 21) or stay (close to 21)\n# Dealer is unable to hit/stay. only able to take their own 3 cards.\n# Maybe try implementing a chip system. that could be cool\n\n# Deck. Numeric only, for now.\n# This branch will try out randint instead of actual cards\np_card1 = random.randint(2, 14)\np_card2 = random.randint(2, 14)\np_card3 = random.randint(2, 14)\n\n# Player hand. Contains the cards as well as unique actions for the player.\ndef player_hand():\n print('For this round, your cards are: {}, {}, {} .'.format(p_card1, p_card2, p_card3))\n sum1 = p_card1 + p_card2 + p_card3\n print(\"The sum of your cards is \" + str(sum1) + '.')\n return\n\n# Initial sum of cards\ndef initial_sum():\n return p_card1 + p_card2 + p_card3\n\n# Action is unique to players.\ndef p_hit():\n return p_card1 + p_card2 + p_card3\n\n\n\n# Dealer hand\nd_card1 = random.randint(2, 14)\nd_card2 = random.randint(2, 14)\nd_card3 = random.randint(2, 14)\n\ndef dealer_hand():\n print('For this round, the dealer had: {}, {}, {} '.format(d_card1, d_card2, d_card3))\n card_sum = d_card1 + d_card2 + d_card3\n print(\"The dealer had \" + str(card_sum) + \" in total.\")\n return\n\n\n# Game state. Contains the logic/flowchart of the game\n\ndef game():\n while True:\n print(\"Welcome. Try to get the sum of your cards to 21\")\n player_hand()\n if initial_sum() > 21:\n sleep(2.5)\n print('Its a bust! Game over.')\n dealer_hand()\n if input('Would you like to play again?') in ('Yes' , 'y' , 'yes'):\n return game()\n else:\n break\n\n\n elif initial_sum() == 21:\n sleep(2.5)\n print('You win!')\n dealer_hand()\n if input('Would you like to play again?') in ('Yes', 'y', 'yes'):\n return game()\n else:\n break\n\n\n\n else:\n a = input(\"Would you like to hit or fold?\")\n\n if a == 'hit':\n print('The new card is: ' + str(random.randint(2, 14)))\n print('The new sum is: ' + str(p_hit()))\n sleep(2.5)\n if p_hit() > 21:\n print('Its a bust! Game over.')\n dealer_hand()\n if input('Would you like to play again?') in ('Yes', 'y', 'yes'):\n return game()\n else:\n break\n elif p_hit() < 21:\n if input('Would you like to hit') == 'Yes':\n return p_hit()\n if input('Would you like to fold') == 'No':\n return game()\n\n elif p_hit() == 21:\n print('You win!')\n dealer_hand()\n if input('Would you like to play again?') in ('Yes', 'y', 'yes'):\n return game()\n else:\n break\n\n else:\n sleep(3)\n print('Game over.')\n return dealer_hand()\n if input('Would you like to play again?') in ('Yes', 'y', 'yes'):\n return game()\n else:\n break\ngame()","sub_path":"Cardgame.py","file_name":"Cardgame.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"325195584","text":"import requests\nimport lxml.etree\nfrom pprint import pprint\n\n\ngeocoder_api_server = \"http://geocode-maps.yandex.ru/1.x/\"\ngeocoder_params = {\n \"apikey\": \"40d1649f-0493-4b70-98ba-98533de7710b\",\n \"format\": \"xml\"}\n\n\ndef scale(site):\n geocoder_params['geocode'] = site\n response = requests.get(geocoder_api_server, params=geocoder_params)\n if not response:\n with open('err.xml', 'wb') as fo:\n fo.write(response.content)\n pprint(geocoder_params)\n return None\n root = lxml.etree.fromstring(response.content)\n lx, ly = list(map(float, root.findtext('.//{*}lowerCorner').split()))\n ux, uy = list(map(float, root.findtext('.//{*}upperCorner').split()))\n adress = root.findtext('.//{*}formatted')\n code = root.findtext('.//{*}postal_code')\n dx, dy = abs(lx - ux), abs(ly - uy)\n d = max((dx, dy)) / 2\n coords = tuple(map(float, root.findtext('.//{*}pos').split()))\n return list(coords), d, adress, code","sub_path":"scale.py","file_name":"scale.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"483249395","text":"import time\nimport os\nfrom shutil import copy2\n\ndef backup(dir_path, root_path):\n\n items = os.listdir(dir_path)\n\n dir_path = dir_path + \"\\\\\"\n\n project_files = []\n project_folders = []\n\n for item in items:\n\n file_path = dir_path + item\n\n if(os.path.isfile(dir_path+item)):\n project_files.append(item)\n else:\n project_folders.append(item)\n\n\n for folder in project_folders:\n if folder != \"BACKUP\":\n\n backup_dir = root_path + \"\\\\\" + \"BACKUP\" + dir_path[len(root_path):] + folder + \"\\\\\"\n\n if os.path.exists(backup_dir) == False:\n os.mkdir(backup_dir)\n\n backup(dir_path + folder,root_path)\n\n for file in project_files:\n if file != \"Backup.py\" and file != \"Backup.bat\":\n backup_path = root_path + \"\\\\\" + \"BACKUP\" + dir_path[len(root_path):]\n src = dir_path + file\n\n current_revision = 0\n revision_exists = True\n mtime = 0.0\n while revision_exists:\n dst = backup_path + str(current_revision) + \"_\" + file\n if os.path.exists(dst):\n current_revision = current_revision + 1\n mtime = os.path.getmtime(dst)\n else:\n revision_exists = False\n\n delta = abs(mtime - os.path.getmtime(src))\n\n if delta > 1.0 or current_revision == 0:\n\n copy2(src,dst)\n print(file + \" has been backed up!\")\n\n\n return\n\nif __name__ == '__main__':\n\n print(\"Performing backup on all modified project files.\")\n start_time = time.time()\n root_path = os.path.dirname(os.path.realpath(__file__))\n\n backup(root_path,root_path)\n\n print(\"---- Backup completed in %.3f seconds ---\" %(time.time() - start_time))\n","sub_path":"Backup.py","file_name":"Backup.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"111315138","text":"from pathlib import Path\nimport random as r\n\nMIN_X = 0\nMIN_Y = 0\n\nMAX_X = 1024\nMAX_Y = 1024\n\nSAMPLES = [\n ['sample1', \"542 552\"],\n]\n\nfor name, s in SAMPLES:\n Path(name + '.in').write_text(s+'\\n')\n Path(name + '.desc').write_text(name+'\\n')\n\nTESTCASES = [\n ['1-middle-right', \"1024 512\"],\n ['2-middle-left', \"0 512\"],\n ['3-top-middle', \"512 1024\"],\n ['4-bottom-middle', \"512 0\"],\n ['5-top-left', \"0 1024\"],\n ['6-top-right', \"1024 1024\"],\n ['7-bottom-left', \"0 0\"],\n ['8-bottom-right', \"1024 0\"],\n ['9-initial-spot', \"512 512\"],\n]\n\nfor desc, s in TESTCASES:\n Path(desc + '.in').write_text(s+'\\n')\n Path(desc + '.desc').write_text(desc+'\\n')\n\nfor i in range(1,21):\n Path('random' + str(i) + '.in').write_text(str(r.randint(MIN_X, MAX_X)) + ' ' + str(r.randint(MIN_Y, MAX_Y)) + '\\n')\n Path('random' + str(i) + '.desc').write_text('random testcase ' + str(i) + '\\n')","sub_path":"cp21/fun-contest/hotorcold/executables/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"82297802","text":"'''\ndescription: Python library to write WRFDA fm128_radar ascii files\nlicense: APACHE 2.0\nauthor: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)\n'''\n\nimport numpy\n\n\nclass write_fm128_radar:\n def __init__(self, radar_name, lat0, lon0, elv0, date, lat,\n lon, elv, rf, rf_qc, rf_err,\n rv, rv_qc, rv_err, outfile='fm128_radar.out', single=True):\n '''\n single: boolean indicating if each reflection angle has its own distinct\n lon/lat grid\n '''\n if (numpy.shape(radar_name) == True and numpy.shape(radar_name)>1):\n # multiple radars in output file\n nrad = numpy.shape(radar_name)\n # convert date to string\n dstring = [d.strftime('%Y-%m-%d %H:%M:%S') for d in date]\n self.init_file(nrad, outfile)\n for r_int in range(0, nrad):\n if single:\n max_levs = numpy.shape(elv[r_int])[0]\n else:\n max_levs = numpy.ones(nrad)\n np = self.get_number_of_points(rf[r_int])\n # number of points: degrees * distance\n self.write_header(radar_name[r_int], lon0[r_int], lat0[r_int],\n elv0[r_int], dstring[r_int], np[r_int],\n max_levs[r_int])\n if single:\n self.write_data_single(dstring[r_int], lat[r_int], lon[r_int],\n elv0[r_int], elv[r_int], rv[r_int],\n rv_qc[r_int], rv_err[r_int], rf[r_int],\n rf_qc[r_int], rf_err[r_int])\n else:\n self.write_data(dstring[r_int], lat[r_int], lon[r_int], elv0[r_int],\n elv[r_int], rv[r_int], rv_qc[r_int],\n rv_err[r_int], rf[r_int], rf_qc[r_int], rf_err[r_int])\n else:\n # one radar in output file\n self.init_file(1, outfile)\n if single:\n max_levs = numpy.shape(elv)[0]\n else:\n max_levs = 1\n np = self.get_number_of_points(rf)\n dstring = date.strftime('%Y-%m-%d %H:%M:%S')\n self.write_header(radar_name, lon0, lat0, elv0, dstring, np, max_levs)\n if single:\n self.write_data_single(dstring, lat, lon, elv0, elv, rv, rv_qc, rv_err,\n rf, rf_qc, rf_err)\n else:\n self.write_data(dstring, lat, lon, elv0, elv, rv, rv_qc, rv_err,\n rf, rf_qc, rf_err)\n self.close_file()\n\n def init_file(self, nrad, outfile):\n '''\n Initialize output file\n - input:\n * nrad: number of radars\n * outfile: name of output file\n '''\n self.f = open(outfile, 'w')\n fmt = \"%14s%3i\"\n self.f.write(fmt % (\"TOTAL RADAR = \", nrad))\n self.f.write(\"\\n\")\n self.f.write(\"%s\" % (\"#-----------------------------#\"))\n self.f.write(\"\\n\")\n self.f.write(\"\\n\")\n\n def close_file(self):\n '''\n Close output file\n '''\n self.f.close()\n\n def write_header(self, radar_name, lon0, lat0, elv0, date, np, max_levs):\n '''\n Write the radar specific header to the output file\n '''\n # define header format\n fmt = \"%5s%2s%12s%8.3f%2s%8.3f%2s%8.1f%2s%19s%6i%6i\"\n # add temporary test data\n name='RADAR'\n hor_spacing=''\n self.f.write(fmt % (name, hor_spacing, radar_name, lon0, hor_spacing,\n lat0, hor_spacing, elv0, hor_spacing, date,\n np, max_levs))\n self.f.write(\"\\n\")\n self.f.write(\"%s\" % (\n '#---------------------------------------------------------#'))\n self.f.write(\"\\n\")\n self.f.write(\"\\n\")\n\n def get_number_of_points(self, rf):\n '''\n Return the total number of points for a radar\n Input:\n - (Masked) array of reflectivity points\n \n Output:\n - For a masked array this all all points that are not masked\n - For a normal array this is all points\n '''\n try:\n # masked array\n return len(rf.count(axis=0).flatten().nonzero()[0])\n except AttributeError:\n # Fallback for a non-masked array\n return len(rf[0,:].flatten())\n\n\n def get_levs_point(self, rf_data_point):\n '''\n Return the number of levels for a data point.\n Input:\n - (Masked) array of reflectivity data points.\n Output:\n - For a masked array this all all points that are not masked\n - For a normal array this is all points\n '''\n try:\n return rf_data_point.count()\n except AttributeError:\n try:\n return len(rf_data_point)\n except TypeError:\n return 1\n\n def write_data(self, date, lat, lon, elv0, elv, rv_data, rv_qc, rv_err,\n rf_data, rf_qc, rf_err):\n '''\n Write radar measurements to the output file\n '''\n fmt = \"%12s%3s%19s%2s%12.3f%2s%12.3f%2s%8.1f%2s%6i\"\n fmt_2 = \"%3s%12.1f%12.3f%4i%12.3f%2s%12.3f%4i%12.3f%2s\"\n hor_spacing = ''\n # loop over horizontal data points\n for m in range(0, numpy.shape(lat)[0]): # vertical levels\n for i in range(0, numpy.shape(lat)[1]):\n for j in range(0, numpy.shape(lat)[2]):\n levs = self.get_levs_point(rf_data[m,i,j])\n if levs > 0:\n # Only write the output data if there is at least 1 vertical level\n # with reflectivity data\n self.f.write(fmt % ('FM-128 RADAR', hor_spacing, date, hor_spacing,\n lat[m,i,j], hor_spacing, lon[m,i,j], hor_spacing,\n elv0, hor_spacing, levs))\n self.f.write(\"\\n\")\n # loop over vertical elevations for each radar\n try:\n if not rf_data.mask[m,i,j]:\n self.f.write(fmt_2 % (hor_spacing, elv[m,i,j],\n rv_data[m,i,j], rv_qc[m,i,j],\n rv_err[m,i,j], hor_spacing,\n rf_data[m,i,j], rf_qc[m,i,j],\n rf_err[m,i,j], hor_spacing))\n self.f.write(\"\\n\")\n except AttributeError:\n self.f.write(fmt_2 % (hor_spacing, elv[m,i,j],\n rv_data[m,i,j], rv_qc[m,i,j],\n rv_err[m,i,j], hor_spacing,\n rf_data[m,i,j], rf_qc[m,i,j],\n rf_err[m,i,j], hor_spacing))\n self.f.write(\"\\n\")\n\n def write_data_single(self, date, lat, lon, elv0, elv, rv_data, rv_qc, rv_err,\n rf_data, rf_qc, rf_err):\n '''\n Write radar measurements to the output file\n '''\n fmt = \"%12s%3s%19s%2s%12.3f%2s%12.3f%2s%8.1f%2s%6i\"\n fmt_2 = \"%3s%12.1f%12.3f%4i%12.3f%2s%12.3f%4i%12.3f%2s\"\n hor_spacing = ''\n # loop over horizontal data points\n for i in range(0, numpy.shape(lat)[0]):\n for j in range(0, numpy.shape(lat)[1]):\n levs = self.get_levs_point(rf_data[:,i,j])\n if levs > 0:\n # Only write the output data if there is at least 1 vertical level\n # with reflectivity data\n self.f.write(fmt % ('FM-128 RADAR', hor_spacing, date, hor_spacing,\n lat[i,j], hor_spacing, lon[i,j], hor_spacing,\n elv0, hor_spacing, levs))\n self.f.write(\"\\n\")\n # loop over vertical elevations for each radar\n for m in range(0, numpy.shape(elv)[0]): # count_nz(i)):\n try:\n if not rf_data.mask[m,i,j]:\n self.f.write(fmt_2 % (hor_spacing, elv[m,i,j],\n rv_data[m,i,j], rv_qc[m,i,j],\n rv_err[m,i,j], hor_spacing,\n rf_data[m,i,j], rf_qc[m,i,j],\n rf_err[m,i,j], hor_spacing))\n self.f.write(\"\\n\")\n except AttributeError:\n self.f.write(fmt_2 % (hor_spacing, elv[m,i,j],\n rv_data[m,i,j], rv_qc[m,i,j],\n rv_err[m,i,j], hor_spacing,\n rf_data[m,i,j], rf_qc[m,i,j],\n rf_err[m,i,j], hor_spacing))\n self.f.write(\"\\n\")\n\n","sub_path":"fm128_radar/write_fm128_radar.py","file_name":"write_fm128_radar.py","file_ext":"py","file_size_in_byte":8103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"606220388","text":"from .base import FunctionalTest\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\nclass NewVisitorTest(FunctionalTest):\n\n # replaced with wait_for_row_in_list_table\n \"\"\"\n def check_for_row_in_list_table(self, row_text):\n\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(row_text, [row.text for row in rows])\n \"\"\"\n\n def test_can_start_a_list_and_retrieve_it_later(self):\n #user has heard about new online todo app.\n #user goes to homepage\n #self.browser.get('http://klee05.pythonanywhere.com')\n self.browser.get(self.live_server_url)\n\n #user notices the page title and header mention todo-lists\n self.assertIn('To-Do', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('To-Do', header_text)\n\n #user is invited to enter a todo item straight away\n inputbox = self.get_item_input_box()\n self.assertEqual(\n inputbox.get_attribute('placeholder'),\n 'Enter a to-do item'\n )\n # user types \"buy peacock feathres\" into a text box\n inputbox.send_keys('Buy peacock feathers')\n\n # when user hits enter, page updates and page lists the item in the todo list\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n #time.sleep(1)\n #self.check_for_row_in_list_table('1: Buy peacock feathers')\n #table = self.browser.find_element_by_id('id_list_table')\n\n # there is still a textbox inviting her to add another item. user enters\n # \"use peacock feathers to make a fly\"\n inputbox = self.get_item_input_box()\n inputbox.send_keys('Use peacock feathers to make a fly')\n inputbox.send_keys(Keys.ENTER)\n time.sleep(1)\n\n #page updates and shows the second item on the list\n #self.check_for_row_in_list_table('1: Buy peacock feathers')\n #self.check_for_row_in_list_table('2: Use peacock feathers to make a fly')\n self.wait_for_row_in_list_table('2: Use peacock feathers to make a fly')\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n\n # Edith wonders whether the site will remember her list. Then she sees\n # that the site has generated a unique URL for her -- there is some\n # explanatory text to that effect.\n\n # She visits that URL - her to-do list is still there.\n\n # Satisfied, she goes back to sleep\n\n def test_multiple_users_can_start_lists_at_different_urls(self):\n # Edith starts a new to-do list\n self.browser.get(self.live_server_url)\n inputbox = self.get_item_input_box()\n inputbox.send_keys('Buy peacock feathers')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n\n # She notices that her list has a unique URL\n edith_list_url = self.browser.current_url\n self.assertRegex(edith_list_url, '/lists/.+')\n\n # Now a new user, Francis, comes along to the site.\n\n ## We use a new browser session to make sure that no information\n ## of Edith's is coming through from cookies etc\n self.browser.quit()\n self.browser = webdriver.Firefox()\n\n # Francis visits the home page. There is no sign of Edith's\n # list\n self.browser.get(self.live_server_url)\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Buy peacock feathers', page_text)\n self.assertNotIn('make a fly', page_text)\n\n # Francis starts a new list by entering a new item. He\n # is less interesting than Edith...\n inputbox = self.get_item_input_box()\n inputbox.send_keys('Buy milk')\n inputbox.send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy milk')\n\n # Francis gets his own unique URL\n francis_list_url = self.browser.current_url\n self.assertRegex(francis_list_url, '/lists/.+')\n self.assertNotEqual(francis_list_url, edith_list_url)\n\n # Again, there is no trace of Edith's list\n page_text = self.browser.find_element_by_tag_name('body').text\n self.assertNotIn('Buy peacock feathers', page_text)\n self.assertIn('Buy milk', page_text)\n\n # Satisfied, they both go back to sleep\n\nif __name__ == '__main__':\n unittest.main(warnings='ignore')\n\n","sub_path":"functional_tests/test_simple_list_creation.py","file_name":"test_simple_list_creation.py","file_ext":"py","file_size_in_byte":4606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"520054905","text":"import sys, time, locale\nfrom Utiles.Factura import fecha as getFecha\nfrom Utiles.Conexion import getProductos, verificarCodigos, setCompra, setCodigos\nfrom UI.UI_compra import *\nfrom Utiles.EnviarCorreo import enviarCorreo\nfrom Constantes import CORREO\n\n\"\"\"\nClase Compra\nEn esta clase se realiza toda la actividad de realizar una compra, confirmar comprar\nconfirmar envio de correos y confirmar la genereacion de facturas.\n\"\"\"\nclass Compra():\n def __init__(self):\n self.UIc = UI_Compra(getProductos())\n self.fecha = getFecha()\n self.UIc.setLEfecha(self.fecha)\n self.UIc.sigAceptar.connect(self.aceptar)\n self.UIc.sigAceptar.connect(self.aceptar)\n self.UIc.sigEliminar.connect(self.eliminar)\n self.UIc.sigEliminarTodo.connect(self.eliminarTodo)\n self.UIc.sigIngresarCodigos.connect(self.ingresarCodigos)\n self.UIc.sigEditar.connect(self.editar)\n #-----------------FUNCIONES-----------------\n def show(self):\n self.UIc.show()\n \n def notificarCompra(self):\n enviarCorreo('NOTIF_COMPRA', CORREO, None, None)\n \n def ingresarCodigos(self):\n codigos = self.UIc.getLECodigos()\n self.UIc.clearLEcodigos()\n codigos = codigos.split(\" \")\n codigos = [item for item in codigos if item]\n self.UIc.addLW(codigos)\n \n def aceptar(self):\n repetido = False\n locale.setlocale(locale.LC_ALL, '')\n factura = self.UIc.getLEfactura()\n descripcion = self.UIc.getCBdescripcion()\n codigos = []\n for index in range(self.UIc.countLW()):\n codigos.append(self.UIc.getLWitem(index))\n socio = self.UIc.getLEsocio()\n moneda = self.UIc.getLEmoneda()\n tasa = self.UIc.getLEtasa()\n aux = []\n aux = self.verificarRepetido(codigos)\n if(len(aux)>= 3):\n self.UIc.throwMsgErrorRepetido()\n self.UIc.clearLW()\n self.UIc.addLW(aux)\n repetido = True\n else:\n repetido = False\n aux = []\n if (codigos != aux and repetido == False):\n verificacion = []\n verificacion = verificarCodigos(codigos)\n if (verificacion[0] == 'False'):\n try:\n valor = float(moneda) * float(tasa)\n valor = str(locale.currency(valor, grouping=True))\n setCompra(factura, descripcion, socio, moneda, tasa, self.fecha, valor, codigos)\n setCodigos(codigos, descripcion)\n \n self.UIc.clearLW()\n self.UIc.clearLEsocio()\n self.UIc.clearLEmoneda()\n self.UIc.clearLEtasa()\n self.UIc.clearLEfactura()\n self.notificarCompra()\n self.UIc.throwMsgProcesoTerminado()\n except Exception as e :\n print(e)\n self.UIc.throwMsgErrorProceso()\n \n else:\n self.UIc.clearLW()\n self.UIc.addLW(verificacion)\n self.UIc.throwMsgErrorRepetido()\n else:\n self.UIc.throwMsgErrorIngreso()\n \n def verificarRepetido(self, valores):\n repetido = ['Codigos repetidos','No se agregaron codigos']\n unico = []\n for x in valores:\n if x not in unico:\n unico.append(x)\n else:\n if x not in repetido:\n repetido.append(x)\n if(len(repetido)>= 3):\n return repetido\n else:\n return ['']\n \n def editar(self):\n self.row = self.UIc.getLWrow()\n self.UIc.takeLW(self.row)\n self.UIc.insertLW(self.row, self.UIc.getLECodigos())\n def eliminar(self):\n self.row = self.UIc.getLWrow()\n self.UIc.takeLW(self.row)\n def eliminarTodo(self):\n self.UIc.clearLW()\n def show(self):\n self.UIc.show()\n def hide(self):\n self.UIc.hie()\n ","sub_path":"Paneles/Compra.py","file_name":"Compra.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"487277392","text":"\ndef common_prefix_length(s1, s2):\n n, ans = min(len(s1), len(s2)), 0\n while ans < n and s1[ans] == s2[ans]:\n ans += 1\n return ans\n\n\nn = int(input())\ntelephone = []\nfor i in range(n):\n telephone.append(input())\n\ntelephone.sort()\ntel1 = telephone.pop(0)\nnumber = len(tel1)\nwhile len(telephone)>0:\n tel2 = telephone.pop(0)\n number += len(tel2) - common_prefix_length(tel1, tel2)\n tel1 = tel2\n\n# The number of elements (referencing a number) stored in the structure.\nprint(number)\n","sub_path":"practice/puzzles/medium/Telephone Numbers.py","file_name":"Telephone Numbers.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277290481","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nclass Solution(object):\n def solve(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: None Do not return anything, modify board in-place instead.\n \"\"\"\n if not board:\n return\n\n x_len = len(board[0])\n y_len = len(board)\n\n exclude_set = set()\n\n def foo(x, y):\n if x < 0 or y < 0:\n return\n\n if x >= x_len or y >= y_len:\n return\n\n if board[y][x] == 'X':\n return\n\n if (x, y) in exclude_set:\n return\n\n exclude_set.add((x, y))\n\n foo(x - 1, y)\n foo(x + 1, y)\n foo(x, y - 1)\n foo(x, y + 1)\n\n for x in range(x_len):\n foo(x, 0)\n foo(x, y_len - 1)\n\n for y in range(y_len):\n foo(0, y)\n foo(x_len - 1, y)\n\n for y in range(y_len):\n for x in range(x_len):\n if board[y][x] == 'O' and (x, y) not in exclude_set:\n board[y][x] = 'X'\n\n\nif __name__ == '__main__':\n solution = Solution()\n\n board = [[\"X\", \"X\", \"X\", \"X\"], [\"X\", \"O\", \"O\", \"X\"], [\"X\", \"X\", \"O\", \"X\"], [\"X\", \"O\", \"X\", \"X\"]]\n\n solution.solve(board)\n\n print(board)\n","sub_path":"leetcode/130.py","file_name":"130.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"103027632","text":"'''\nネズミ学習問題のQラーニングプログラム\nCopyright(c) 2020 Koji Makino and Hiromitsu Nishizaki All Rights Reserved.\n'''\nimport numpy as np\n#シミュレータクラスの設定\nclass MyEnvironmentSimulator():\n def __init__(self):\n self.reset()\n#初期化\n def reset(self):\n self._state = 0\n return self._state\n#行動による状態変化\n def step(self, action):\n reward = 0\n if self._state==0:#電源OFFの状態\n if action==0:#電源ボタンを押す\n self._state = 1#電源ON\n else:#行動ボタンを押す\n self._state = 0#電源OFF\n else:#電源ONの状態\n if action==0:\n self._state = 0\n else:\n self._state = 1\n reward = 1#報酬が得られる\n return self._state, reward\n#Q値クラスの設定\nclass MyQTable():\n def __init__(self):\n self._Qtable = np.zeros((2, 2))\n#行動の選択\n def get_action(self, state, epsilon):\n if epsilon > np.random.uniform(0, 1):#ランダム行動\n next_action = np.random.choice([0, 1])\n else:#Q値に従った行動\n a = np.where(self._Qtable[state]==self._Qtable[state].max())[0]\n next_action = np.random.choice(a)\n return next_action\n#Q値の更新\n def update_Qtable(self, state, action, reward, next_state):\n gamma = 0.9\n alpha = 0.5\n next_maxQ=max(self._Qtable[next_state])\n self._Qtable[state, action] = (1 - alpha) * self._Qtable[state, action] + alpha * (reward + gamma * next_maxQ)\n return self._Qtable\n\ndef main():\n num_episodes = 10 #総エピソード回数\n max_number_of_steps =5 #各エピソードの行動数\n epsilon = np.linspace(start=1.0, stop=0.0, num=num_episodes)#徐々に最適行動のみをとる、ε-greedy法\n env = MyEnvironmentSimulator()\n tab = MyQTable()\n\n for episode in range(num_episodes): #エピソード回数分繰り返す\n state = env.reset()\n episode_reward = 0\n for t in range(max_number_of_steps): #各エピソードで行う行動数分繰り返す\n action = tab.get_action(state, epsilon[episode]) #行動の決定\n next_state, reward = env.step(action) #行動による状態変化\n print(state, action, reward)#表示\n q_table = tab.update_Qtable(state, action, reward, next_state)#Q値の更新\n state = next_state\n episode_reward += reward #報酬を追加\n print(f'Episode:{episode+1:4.0f}, Reward:{episode_reward:3.0f}')\n print(q_table)\n np.savetxt('Qvalue.txt', tab._Qtable)\n \nif __name__ == '__main__':\n main()\n","sub_path":"tensor_flow/program/ch3/Skinner_QL/skinner_QL.py","file_name":"skinner_QL.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"448243511","text":"import pickle\n\nimport tests.base.utils as tutils\nfrom pytorch_lightning import Trainer\nfrom tests.base import LightningTestModel\n\n\ndef test_testtube_logger(tmpdir):\n \"\"\"Verify that basic functionality of test tube logger works.\"\"\"\n tutils.reset_seed()\n hparams = tutils.get_default_hparams()\n model = LightningTestModel(hparams)\n\n logger = tutils.get_default_testtube_logger(tmpdir, False)\n\n assert logger.name == 'lightning_logs'\n\n trainer_options = dict(\n default_save_path=tmpdir,\n max_epochs=1,\n train_percent_check=0.05,\n logger=logger\n )\n\n trainer = Trainer(**trainer_options)\n result = trainer.fit(model)\n\n assert result == 1, 'Training failed'\n\n\ndef test_testtube_pickle(tmpdir):\n \"\"\"Verify that pickling a trainer containing a test tube logger works.\"\"\"\n tutils.reset_seed()\n\n hparams = tutils.get_default_hparams()\n\n logger = tutils.get_default_testtube_logger(tmpdir, False)\n logger.log_hyperparams(hparams)\n logger.save()\n\n trainer_options = dict(\n default_save_path=tmpdir,\n max_epochs=1,\n train_percent_check=0.05,\n logger=logger\n )\n\n trainer = Trainer(**trainer_options)\n pkl_bytes = pickle.dumps(trainer)\n trainer2 = pickle.loads(pkl_bytes)\n trainer2.logger.log_metrics({'acc': 1.0})\n","sub_path":"tests/loggers/test_test_tube.py","file_name":"test_test_tube.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"41645345","text":"#from parents import Rectangle\nfrom assets.parents.Rectangle import Rectangle as Rectangle\nfrom assets.parents.Hit import*\nclass Wall(Rectangle):\n def draw(self):\n self.name = \"wall\"\n if self.colour ==(100, 250, 100):\n self.id = self.canvas.create_image(\"brick.jpg\", self.x, self.y, self.width, self.length)\n else:\n self.id = self.canvas.create_rectangle(self.colour, [self.x, self.y, self.width, self.length])\n self.pos = [self.x, self.y, self.x+self.width, self.x+self.length]\n def move(self, xVelocity, yVelocity):\n self.pos[0] += int(xVelocity)\n self.pos[2] += int(xVelocity)\n self.pos[1] += int(yVelocity)\n self.pos[3] += int(yVelocity)\n if self.colour ==(100, 250, 100):\n self.canvas.move_image(self.id, int(xVelocity), int(yVelocity))\n else:\n self.canvas.move_rectangle(self.id, int(xVelocity), int(yVelocity))\n self.x+=int(xVelocity)\n self.y+=int(yVelocity)\n self.pos = [self.x, self.y, self.x+self.width, self.y+self.length]\n def act(self, objectM, phase):\n stop(objectM, phase)","sub_path":"portableGame/assets/Wall.py","file_name":"Wall.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"561559913","text":"#\n# @lc app=leetcode id=83 lang=python3\n#\n# [83] Remove Duplicates from Sorted List\n#\n# https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/\n#\n# algorithms\n# Easy (43.00%)\n# Total Accepted: 347.8K\n# Total Submissions: 807.9K\n# Testcase Example: '[1,1,2]'\n#\n# Given a sorted linked list, delete all duplicates such that each element\n# appear only once.\n#\n# Example 1:\n#\n#\n# Input: 1->1->2\n# Output: 1->2\n#\n#\n# Example 2:\n#\n#\n# Input: 1->1->2->3->3\n# Output: 1->2->3\n#\n#\n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n if not head:\n return head\n base = head\n tmp = head\n while head:\n if base.val == head.val:\n base.next = head.next\n else:\n base = head\n head = head.next\n return tmp\n","sub_path":"leetcode/83.remove-duplicates-from-sorted-list.py","file_name":"83.remove-duplicates-from-sorted-list.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"586261035","text":"import csv\nimport sys\nfrom leaderboard import app, load_config, update_scores\nfrom pymongo import MongoClient\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print(\"Usage: python {} datasets.toml output.csv\".format(sys.argv[0]))\n sys.exit(1)\n\n load_config(sys.argv[1])\n app.client = MongoClient(app.mongodb_host)\n app.coll = app.client['competition']['results']\n\n docs = update_scores()\n\n print(\"Writing results to {}...\".format(sys.argv[2]))\n with open(sys.argv[2], 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(['username', 'rank', 'overall_score'])\n for doc in docs:\n writer.writerow([doc['username'], doc['rank'], doc['score']])\n","sub_path":"leaderboards/search/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"373664520","text":"import sys\ninput = sys.stdin.readline\n\nN, K = map(int, input().split())\nA = [int(input()) for _ in range(N)]\ncnt = 0\nfor i in range(N-1, -1, -1):\n if K//A[i] > 0:\n cnt += K//A[i]\n K = K%A[i]\nprint(cnt)","sub_path":"Python/BaekOJ/StepByStep/16. GREEDY/01. Coin 0.py","file_name":"01. Coin 0.py","file_ext":"py","file_size_in_byte":218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"220730437","text":"import math\n\ndef integrate_single_channel(vals,t):\n # vals is a list of floats\n # t is a float\n # this integrates vals over t\n # the value of the first 1/5 of vals is averaged to find a background level\n # the result of the integration is returned\n stop = int(math.ceil(len(vals)/5))\n # stop is the index of the end of the first 5th of vals\n ave = 0.0\n for i in range(stop):\n ave += vals[i]\n ave /= float(stop)\n # ave is now the average value of the first 5th of the data\n # now we integrate, by left side Riemann\n total = 0.0\n for i in range(stop,len(vals)):\n total += (vals[i]-ave)*t\n # by subtracting ave we remove any static vertical offset\n # leaving only the signal plus noise\n return total\n\ndef integrate_json_ord_clump(ev,t):\n # ev is a list of events as they are save in json ord clump format\n # t is the time between measurements, saved encoded as a float\n # this function returns a list of dicts\n # each of those dicts correstponts to an event\n # the keys to the dicts are integers representing channels\n # the values are the value of that channel integrated over time\n ou = []\n for event in ev:\n da = event[\"DATA\"]\n # da is now a dict mapping string channels to lists of floats\n q = dict()\n for ch in da:\n q[int(ch)] = integrate_single_channel(da[ch],t)\n # this adds an integer->float entry to q with the integration result for a channel\n ou.append(q)\n return ou\n","sub_path":"integrate_json_ord_clump.py","file_name":"integrate_json_ord_clump.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310854464","text":"from rbnf.std.compiler import *\nfrom Redy.Opt.ConstExpr import constexpr, const\n\ntry:\n from Redy.Opt.ConstExpr import feature\nexcept:\n from Redy.Opt.ConstExpr import optimize as feature\nfrom .user_interface import ResultDescription\n\n__all__ = ['compile', 'ResultDescription']\n\n\nclass ZeroExp:\n def __init__(self, bnf_syntax: str, use: str, custom_lexer_wrapper=None):\n state = State(bootstrap)\n tokens = tuple(rbnf_lexing(bnf_syntax))\n result = Statements.match(tokens, state)\n if result.status is Unmatched:\n max_fetched = state.max_fetched\n tk: Tokenizer = tokens[max_fetched]\n before = recover_codes(tokens[max_fetched - 10:max_fetched])\n later = recover_codes(tokens[max_fetched: max_fetched + 10])\n raise SyntaxError(\"Error at line {}, col {}, see details:\\n{}\", tk.lineno, tk.colno,\n Green(before) + Red(later))\n\n asdl = result.value\n ctx = create_ctx()\n visit(asdl, ctx)\n lexer = ctx['lex']\n lang = ctx['lang']\n if use is None:\n for end in asdl.value[::-1]:\n if isinstance(end, ParserASDL):\n top_parser = ctx[end.name]\n break\n else:\n raise ValueError(\"No top parser found!\")\n\n else:\n top_parser = ctx[use]\n\n @feature\n def match(text) -> ResultDescription:\n _state = State(constexpr[lang])\n _wrapper: const = custom_lexer_wrapper\n _lexer: const = lexer\n\n _tokens = tuple(_wrapper(_lexer(text)) if constexpr[custom_lexer_wrapper] else _lexer(text))\n _result: Result = constexpr[top_parser.match](_tokens, _state)\n return constexpr[ResultDescription](_state, _result.value, _tokens)\n\n self.match = match\n\n\ndef compile(bnf_syntax: str, use: str = None, custom_lexer_wrapper=None):\n bnf_syntax = bnf_syntax\n return ZeroExp(bnf_syntax, use, custom_lexer_wrapper=custom_lexer_wrapper)\n","sub_path":"rbnf/zero/impl.py","file_name":"impl.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"187825779","text":"import requests\n# 建立登录接口函数\ndef apiLogin():\n # 登录接口\n login_url = 'http://localhost/index.php?ctl=user&act=dologin&fhash=inIRwtRtTAHUvoFmjcpjXdHBNAIQXictVptkoWuXScmCmBxhnu'\n # 登录接口参数\n login_data = {\n 'email':'13587652131',\n 'user_pwd':'U1BIVWp0dXlqYUFkdVpvU2hpYWdBZlBJZHlQUEtMRE1KcHZ0VmlsQUhtYnNrZXdMREElMjV1NjVCOSUyNXU3RUY0amsxNDcyNTglMjV1OEY2RiUyNXU0RUY2',\n 'ajax':'1',\n }\n result = requests.post(url=login_url,data=login_data)\n return result.json(),result.status_code\n","sub_path":"api_frame/step2/login_test.py","file_name":"login_test.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"204738123","text":"import hashlib\nimport urllib\nimport datetime\nimport flask\nimport pymongo\nimport bson.binary\nimport bson.objectid\nimport bson.errors\nfrom cStringIO import StringIO\nfrom PIL import Image\nimport gridfs\nfrom flask import request\nimport json\nfrom bson.json_util import dumps\nfrom base64 import b64decode\n\napp = flask.Flask(__name__)\napp.debug = True\ndb = pymongo.MongoClient('localhost', 27017).test1\nallow_formats = set(['jpeg', 'png', 'gif'])\n# fs = gridfs.GridFS(db)\n\ntestbase64= 2;\n\n# grid_fs = gridfs.GridFS(db)\n\ndef save_file(f):\n content = StringIO(f.read())\n try:\n mime = Image.open(content).format.lower()\n if mime not in allow_formats:\n raise IOError()\n except IOError:\n flask.abort(400)\n\n sha1 = hashlib.sha1(content.getvalue()).hexdigest()\n testbase64 = bson.binary.Binary(content.getvalue())\n c = dict(\n content=bson.binary.Binary(content.getvalue()),\n mime=mime,\n time=datetime.datetime.utcnow(),\n sha1=sha1,\n imageurl= 'http://127.0.0.1:7777/f/' + sha1,\n is_deleted= 0,\n )\n try:\n db.files.save(c)\n except pymongo.errors.DuplicateKeyError:\n pass\n return sha1\n\n@app.route('/f/')\ndef serve_file(sha1):\n try:\n f = db.files.find_one({'sha1': sha1})\n\n if f is None:\n raise bson.errors.InvalidId()\n if flask.request.headers.get('If-Modified-Since') == f['time'].ctime():\n return flask.Response(status=304)\n resp = flask.Response(f['content'], mimetype='image/' + f['mime'])\n resp.headers['Last-Modified'] = f['time'].ctime()\n\n # return flask.jsonify({'images':testbase64}) #dumps(f['content']) #json.dumps(f) #flask.jsonify(dumps(f))\n return resp\n #return flask.jsonify({'images': str(f['content']), 'time': str(f['time'])})\n except bson.errors.InvalidId:\n flask.abort(404)\n\n@app.route('/f')\ndef getall():\n items = db.files.find({}, {\"sha1\": 1, \"description\": 1, 'imageurl': 1, \"_id\": 0, \"dataurl\": 1}) #, \"time\": 1, 'content': 1\n # a = fs.put(c)\n\n # it = json.dumps(items)\n return dumps(items)\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n # f = flask.request.files['uploaded_file']\n f = flask.request.files['image']\n # text = flask.request.files['text']\n # print text\n\n #test post request ####################\n # imagebase64 = request.body.image\n # sha1 = hashlib.sha1(imagebase64).hexdigest()\n # upload = request.get_json()\n # imagebase64 = upload['image']\n # print imagebase64\n # imagebindata =b64decode(imagebase64)\n # print imagebindata\n # # description = upload['description']\n # sha1 = hashlib.sha1(imagebindata).hexdigest()\n # c = dict(\n # content=bson.binary.Binary(imagebindata),\n # time=datetime.datetime.utcnow(),\n # dataurl= 'data:image/png;base64,{}'.format(urllib.quote(imagebase64.rstrip('\\n'))),\n # imageurl= 'http://127.0.0.1:7777/f/' + sha1,\n # sha1=sha1,\n # mime='png',\n # description=description,\n # is_deleted= 0,\n # )\n # try:\n # db.files.save(c)\n # except pymongo.errors.DuplicateKeyError:\n # pass\n # return \"get it\"\n\n #########test end####################\n # sha1 = save_file(imagebase64)\n sha1 = save_file(f)\n return flask.redirect('/f/' + str(sha1))\n\n# @app.route\n\n@app.route('/')\ndef index():\n return '''\n \n \n \n \n '''\n\nif __name__ == '__main__':\n app.run(host='192.168.0.100', port=7777)\n# import bson.binary\n# import datetime\n# import hashlib\n# import bson.errors\n# try:\n# \tfrom StringIO import StringIO\n# except ImportError:\n# \tfrom io import BytesIO as StringIO\n#\n#\n# import flask\n# import pymongo\n# from PIL import Image\n#\n# app = flask.Flask(__name__)\n# app.debug = True\n# db = pymongo.MongoClient('localhost',27017).test\n# allowed_format = ['jpeg','gif', 'png']\n#\n#\n# @app.route('/')\n# def index():\n# \treturn \"\"\"\n# \t\n# \t\n# \t\t\n# \t\t\t\n# \t\t\n# \t\n# \t\"\"\"\n#\n# @app.route('//update')\n# def test(sha1):\n# \treturn \"\"\"\n# \t\n# \t\n# \t\t\n# \t\t\t\n# \t\t\n# \t\n# \t\"\"\" %(sha1,)\n#\n# #remove image\n# @app.route('//remove')\n# def remove(sha1):\n# \ttry:\n# \t\timageitem = db.files.find_one({'sha1':sha1})\n# \t\tif imageitem is None:\n# \t\t\traise bson.errors.InvalidId()\n# \t\tresult = db.files.remove({'sha1':sha1})\n# \t\treturn flask.jsonify({'operation':result['ok']})\n# \texcept bson.errors.InvalidId:\n# \t\tflask.abort(404)\n#\n# #get image\n# @app.route('/')\n# def download(sha1):\n# \ttry:\n# \t\timageitem = db.files.find_one({'sha1':sha1})\n# \t\tif imageitem is None:\n# \t\t\traise bson.errors.InvalidId()\n# \t\tif flask.request.headers.get('If-Modified-Since') == imageitem['time'].ctime():\n# \t\t\treturn flask.Response(status=304)\n# \t\tresp = flask.Response(imageitem['content'], mimetype='image/' + imageitem['mime'])\n# \t\tresp.headers['Last-Modified'] = imageitem['time'].ctime()\n# \t\treturn resp\n# \texcept bson.errors.InvalidId:\n# \t\tflask.abort(404)\n#\n# #upload image\n# @app.route('/upload', methods=['POST'])\n# def upload():\n# \tuploadedfile = flask.request.files['uploadedfile']\n# \ttry:\n# \t\tsha1 = save_file(uploadedfile)\n# \t\treturn flask.jsonify({'imageid':sha1})\n# \texcept Exception as e:\n# \t\tflask.abort(400)\n#\n# #update image\n# @app.route('//update', methods=['POST'])\n# def update(sha1):\n# \tprint (sha1)\n# \tprint (dir(flask.request))\n# \tprint (flask.request.headers)\n# \tprint (flask.request.files)\n# \tupdatedfile = flask.request.files['updatedfile']\n#\n# \ttry:\n# \t\tupdate_file(sha1, updatedfile)\n# \t\treturn flask.jsonify({'imageid':sha1})\n# \texcept Exception as e:\n# \t\tflask.abort(404)\n#\n#\n#\n# #check image type\n# def formate_check(content):\n# \tglobal allowed_format\n# \ttry:\n# \t\tmime = Image.open(content).format.lower()\n# \t\tif mime not in allowed_format:\n# \t\t\traise IOError()\n# \t\treturn mime\n# \texcept IOError:\n# \t\traise IOError\n#\n# #from the request get the file content\n# def get_content(_file):\n# \treturn StringIO(_file.read())\n#\n# def save_file(uploadedfile):\n# \tcontent = get_content(uploadedfile)\n# \tmime = formate_check(content)\n# \tsha1 = hashlib.sha1(content.getvalue()).hexdigest()\n# \timageitem = dict(\n# \t\tcontent=bson.binary.Binary(content.getvalue()),\n# \t\tmime = mime,\n# \t\ttime = datetime.datetime.utcnow(),\n# \t\tsha1 = sha1\n# \t)\n# \ttry:\n# \t\tdb.files.save(imageitem)\n# \t\treturn imageitem['sha1']\n# \texcept pymongo.errors.WriteError:\n# \t\traise pymongo.errors.WriteError\n#\n# def update_file(sha1, updatedfile):\n# \timageitem = db.files.find_one({'sha1':sha1})\n# \tif imageitem is None:\n# \t\traise bson.errors.InvalidId()\n# \tcontent = get_content(updatedfile)\n# \tformate_check(content)\n# \ttry:\n# \t\tdb.files.update({'sha1':sha1}, {'$set':{'content':bson.binary.Binary(content.getvalue()),'time':datetime.datetime.utcnow()}})\n# \texcept Exception as e:\n# \t\traise e\n\nif __name__ == '__main__':\n\tapp.run(port=9001)\n","sub_path":"flask-api-v2/flask_gridfs_images.py","file_name":"flask_gridfs_images.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"401313426","text":"\"\"\"Wrapper for JavaCard applet data\"\"\"\n\nfrom io import BytesIO\nfrom collections import namedtuple\nfrom .util import AID, merge_dicts\n\n# Extended component tags used to store selected metadata - NON-STANDARD!\n_EXTENDED_TAGS = {\n 'dap.rsa.sha1': 0xe0,\n 'dap.rsa.sha256': 0xe1,\n 'dap.p256.sha1': 0xe2,\n 'dap.p256.sha256': 0xe3\n}\n\n# Tag names\n_TAG_NAMES = merge_dicts({\n 1: 'Header',\n 2: 'Directory',\n 3: 'Applet',\n 4: 'Import',\n 5: 'ConstantPool',\n 6: 'Class',\n 7: 'Method',\n 8: 'StaticField',\n 9: 'RefLocation',\n 10: 'Export',\n 11: 'Descriptor',\n 12: 'Deubg'},\n {v: k for k, v in _EXTENDED_TAGS.items()})\n\n\n# A set of items loaded in the JavaCard in the right order\n_LOAD_LIST = ['Header', 'Directory', 'Import', 'Applet', 'Class', 'Method',\n 'StaticField', 'Export', 'ConstantPool', 'RefLocation']\n\n# Size of tag-length prefix in bytes\n_TL_SIZE = 3\n# Magic word contained in header\n_HDR_MAGIC_BYTES = b'\\xde\\xca\\xff\\xed'\n\n# CAP item record, storing its size and offset inside unordered data block\n_CapItem = namedtuple('CapItem', ['size', 'offset'])\n\n\nclass Header:\n \"\"\"Header item\"\"\"\n @classmethod\n def read_from(cls, stream):\n \"\"\"Reads header from a stream\"\"\"\n obj = cls()\n try:\n magic = stream.read(len(_HDR_MAGIC_BYTES))\n if magic != _HDR_MAGIC_BYTES:\n raise RuntimeError(\"Wrong applet format\")\n obj.cap_minor_ver = (stream.read(1))[0]\n obj.cap_major_ver = (stream.read(1))[0]\n _ = stream.read(1) # flags\n obj.package_minor_ver = (stream.read(1))[0]\n obj.package_major_ver = (stream.read(1))[0]\n aid_len = (stream.read(1))[0]\n obj.package_aid = AID(stream.read(aid_len))\n if not len(obj.package_aid) or len(obj.package_aid) != aid_len:\n raise RuntimeError(\"Wrong applet format\")\n name_len_byte = stream.read(1)\n if len(name_len_byte):\n name_len = name_len_byte[0]\n obj.package_name = stream.read(name_len).decode()\n if len(obj.package_name) != name_len:\n raise RuntimeError(\"Wrong applet format\")\n else:\n obj.package_name = \"\"\n except:\n raise RuntimeError(\"Wrong applet format\")\n return obj\n\n def __str__(self):\n s = \"CAP v%d.%d, Package: '%s' %s v%d.%d\" % (\n self.cap_major_ver, self.cap_minor_ver,\n self.package_name, str(self.package_aid),\n self.package_major_ver, self.package_minor_ver)\n return s\n\n def __repr__(self):\n return \"%s(%s)\" % (type(self).__name__, str(self))\n\n\nclass Applet:\n \"\"\"Wrapper for JavaCard applet data\"\"\"\n @classmethod\n def read_from(cls, stream):\n \"\"\"Reads applet from a stream of CAP components (e.g. IJC file)\"\"\"\n obj = cls()\n obj._data = stream.read()\n obj._item_table = {}\n obj._tot_size = 0\n idx = 0\n while idx < len(obj._data):\n if len(obj._data) - idx < _TL_SIZE:\n raise RuntimeError(\"Wrong applet format\")\n tag = obj._data[idx]\n if tag == 0:\n raise RuntimeError(\"Wrong applet format\")\n size = obj._data[idx+1] << 8 | obj._data[idx+2]\n if idx + _TL_SIZE + size > len(obj._data):\n raise RuntimeError(\"Wrong applet format\")\n if tag in _TAG_NAMES:\n tag_name = _TAG_NAMES[tag]\n obj._item_table[tag_name] = _CapItem(size=size + _TL_SIZE,\n offset=idx)\n if tag_name in _LOAD_LIST:\n obj._tot_size += size + _TL_SIZE\n idx += _TL_SIZE + size\n obj._header = obj._parse_header_item()\n obj._applet_aid_list = obj._parse_applet_item()\n return obj\n\n def _parse_header_item(self):\n \"\"\"Parses 'Header' component returning decoded header\"\"\"\n item = self._item_table.get('Header')\n if item is None:\n RuntimeError(\"Wrong applet format\")\n stream = BytesIO(self._data[item.offset + _TL_SIZE:\n item.offset + item.size])\n return Header.read_from(stream)\n\n def _parse_applet_item(self):\n \"\"\"Parses 'Applet' component returning a list of applet AID\"\"\"\n item = self._item_table.get('Applet')\n if item is None:\n RuntimeError(\"Wrong applet format\")\n stream = BytesIO(self._data[item.offset + _TL_SIZE:\n item.offset + item.size])\n aid_list = []\n try:\n count = (stream.read(1))[0]\n for i in range(count):\n aid_len = (stream.read(1))[0]\n aid = stream.read(aid_len)\n if len(aid) != aid_len:\n RuntimeError(\"Wrong applet format\")\n _ = stream.read(2) # install_method_offset\n aid_list.append(AID(aid))\n except:\n RuntimeError(\"Wrong applet format\")\n return aid_list\n\n def __len__(self):\n return self._tot_size\n\n def get_data(self, offset: int = 0, size: int = -1):\n \"\"\"Returns piece of loadable data starting from a given offset\"\"\"\n if size < 0:\n size = len(self) - offset\n if offset < 0 or size < 0:\n raise ValueError(\"Trying to access outside of stored data\")\n if offset + size > len(self):\n size = len(self) - offset\n size = size if size >= 0 else 0\n data = bytearray()\n rm_size = size\n load_off = 0\n dst_off = offset\n for tag_name in _LOAD_LIST:\n if rm_size <= 0:\n break\n item = self._item_table.get(tag_name)\n if item is not None:\n if load_off <= dst_off <= load_off + item.size:\n chunk_off = item.offset + (dst_off - load_off)\n chunk_len = min(item.size - (dst_off - load_off), rm_size)\n data += self._data[chunk_off: chunk_off + chunk_len]\n dst_off += chunk_len\n rm_size -= chunk_len\n load_off += item.size\n return bytes(data)\n\n def get_metadata(self, item_name: str = ''):\n \"\"\"Returns metadata specified by item name or a full set if the name is\n not provided\n \"\"\"\n if item_name:\n item = self._item_table.get(item_name)\n if item is not None:\n return self._data[item.offset + _TL_SIZE:\n item.offset + item.size]\n return b''\n else:\n res = {}\n for k in _EXTENDED_TAGS.keys():\n item = self._item_table.get(k)\n if item is not None:\n res[k] = self._data[item.offset + _TL_SIZE:\n item.offset + item.size]\n return res\n\n def hash(self, hasher):\n \"\"\"Returns hash of loadable data using provided hasher, e.g.\n hashlib.sha256()\n \"\"\"\n for tag_name in _LOAD_LIST:\n item = self._item_table.get(tag_name)\n if item is not None:\n hasher.update(\n self._data[item.offset: item.offset + item.size])\n return hasher.digest()\n\n @property\n def package_aid(self):\n return self._header.package_aid\n\n @property\n def applet_aid_list(self):\n return self._applet_aid_list\n\n @property\n def header(self):\n return self._header\n\n def __str__(self):\n aid_strings = [str(aid) for aid in self._applet_aid_list]\n s = \"%s, Applets: [%s], Code: %dbytes\" % (\n str(self._header), \", \".join(aid_strings), len(self))\n return s\n\n def __repr__(self):\n return \"%s(%s)\" % (type(self).__name__, str(self))\n","sub_path":"src/omfgp/applet.py","file_name":"applet.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"645461746","text":"# -*- coding: utf-8 -*-\n#\n# Copyright © 2013 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public\n# License as published by the Free Software Foundation; either version\n# 2 of the License (GPLv2) or (at your option) any later version.\n# There is NO WARRANTY for this software, express or implied,\n# including the implied warranties of MERCHANTABILITY,\n# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should\n# have received a copy of GPLv2 along with this software; if not, see\n# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.\nimport os\nimport shutil\nimport tempfile\n\nfrom pulp_rpm.common.constants import STATE_COMPLETE\nfrom pulp_rpm.common.ids import TYPE_ID_ISO\nfrom pulp_rpm.plugins.importers.iso_importer.bumper import ISOBumper\nfrom pulp_rpm.plugins.importers.iso_importer.sync import ISOSyncRun\nfrom rpm_support_base import PulpRPMTests\nimport importer_mocks\n\nfrom mock import call, MagicMock, patch\nfrom pulp.plugins.model import Repository\n\nclass TestISOSyncRun(PulpRPMTests):\n \"\"\"\n Test the ISOSyncRun object.\n \"\"\"\n def setUp(self):\n self.iso_sync_run = ISOSyncRun()\n self.temp_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.temp_dir)\n\n def test_cancel_sync(self):\n \"\"\"\n Test what happens if cancel_sync is called when there is no Bumper.\n \"\"\"\n FakeBumper = MagicMock(spec_set=ISOBumper)\n\n self.iso_sync_run.bumper = FakeBumper()\n self.iso_sync_run.cancel_sync()\n self.iso_sync_run.bumper.cancel_download.assert_called_once_with()\n\n @patch('pulp_rpm.plugins.importers.iso_importer.bumper.pycurl.Curl',\n side_effect=importer_mocks.ISOCurl)\n @patch('pulp_rpm.plugins.importers.iso_importer.bumper.pycurl.CurlMulti',\n side_effect=importer_mocks.CurlMulti)\n @patch('pulp_rpm.plugins.importers.iso_importer.sync.SyncProgressReport', autospec=True)\n def test_perform_sync(self, progress_report, curl_multi, curl):\n \"\"\"\n Assert that we perform all of the correct calls to various things during perform_sync().\n \"\"\"\n repo = MagicMock(spec=Repository)\n working_dir = os.path.join(self.temp_dir, \"working\")\n os.mkdir(working_dir)\n pkg_dir = os.path.join(self.temp_dir, 'content')\n os.mkdir(pkg_dir)\n repo.working_dir = working_dir\n sync_conduit = importer_mocks.get_sync_conduit(type_id=TYPE_ID_ISO, pkg_dir=pkg_dir)\n config = importer_mocks.get_basic_config(\n feed_url='http://fake.com/iso_feed/', max_speed='500.0', num_threads='5',\n ssl_client_cert=\"Trust me, I'm who I say I am.\", ssl_client_key=\"Secret Key\",\n ssl_ca_cert=\"Uh, I guess that's the right server.\",\n proxy_url='http://proxy.com', proxy_port='1234', proxy_user=\"the_dude\",\n proxy_password='bowling')\n\n report = self.iso_sync_run.perform_sync(repo, sync_conduit, config)\n\n # There should now be three Units in the DB, one for each of the three ISOs that our mocks\n # got us.\n units = [tuple(call)[1][0] for call in sync_conduit.save_unit.mock_calls]\n self.assertEqual(len(units), 3)\n expected_units = {\n 'test.iso': {\n 'checksum': 'f02d5a72cd2d57fa802840a76b44c6c6920a8b8e6b90b20e26c03876275069e0',\n 'size': 16, 'contents': 'This is a file.\\n'},\n 'test2.iso': {\n 'checksum': 'c7fbc0e821c0871805a99584c6a384533909f68a6bbe9a2a687d28d9f3b10c16',\n 'size': 22, 'contents': 'This is another file.\\n'},\n 'test3.iso': {\n 'checksum': '94f7fe923212286855dea858edac1b4a292301045af0ddb275544e5251a50b3c',\n 'size': 34, 'contents': 'Are you starting to get the idea?\\n'}}\n for unit in units:\n expected_unit = expected_units[unit.unit_key['name']]\n self.assertEqual(unit.unit_key['checksum'], expected_unit['checksum'])\n self.assertEqual(unit.unit_key['size'], expected_unit['size'])\n expected_storage_path = os.path.join(\n pkg_dir, unit.unit_key['name'], unit.unit_key['checksum'],\n str(unit.unit_key['size']), unit.unit_key['name'])\n self.assertEqual(unit.storage_path, expected_storage_path)\n with open(unit.storage_path) as data:\n contents = data.read()\n self.assertEqual(contents, expected_unit['contents'])\n","sub_path":"pulp_rpm/test/unit/server/test_iso_importer_sync.py","file_name":"test_iso_importer_sync.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"494809311","text":"#!/usr/bin/env python3\n\nimport re\nimport time\n\nmsg = \" Unpacking nmap (7.60-1ubuntu5) ... \"\n\n\ndef main():\n\n installed_pkgs = list()\n log_file = \"/var/log/apt/term.log\"\n\n print(\" Get installed packages on Linux machine from\".format(log_file))\n\n # find pattern\n pattern = re.compile(r\"Unpacking (\\S+) (\\S+)\")\n\n with open(log_file, \"r\") as f:\n\n # read lines from log file\n print(\"[*] Reading {} ...\".format(log_file))\n data = f.read()\n lines = data.split(\"\\n\")\n\n time.sleep(1)\n\n # parse file\n print(\"[*] Parsing {} ...\".format(log_file))\n for line in lines:\n match = re.findall(pattern, line)\n\n if len(match):\n installed_pkgs.append(match[0])\n\n time.sleep(1)\n\n print(\"[+] Operation Finished.\")\n\n time.sleep(1)\n\n # display installed packages\n for pkg in installed_pkgs:\n package, version = pkg[0], pkg[1].strip(\"()\")\n print(\"[+] Package : {} ({})\".format(package, version))\n\n print(\"[+] total number of packages : {}\".format(len(installed_pkgs)).title())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/installed_pkgs.py","file_name":"installed_pkgs.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"457416696","text":"from mcrcon import MCRcon\ncodes = ['§1','§2','§3','§4','§5','§6','§7','§8','§9','§c','§a','§f','§r']\nfc = 0\nip = input('Server IP: ')\npas = input('Password: ')\nmcr = MCRcon(ip, pas)\nmcr.connect()\nconnected = True\nprint('Logged in')\nwhile connected:\n comm = input('> ')\n if comm != 'rconlog':\n resp = mcr.command(comm)\n while fc != 13:\n resp = resp.replace(codes[fc], '')\n fc = fc + 1\n print(resp)\n fc = 0\n else:\n mcr.disconnect()\n connected = False","sub_path":"darthcon.py","file_name":"darthcon.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"76569538","text":"#######################################################\n# 3次元グラフ\n####################################################### \nimport svgplot\nimport math\n\n# 座標の下限\nXmin = -1\nYmin = -1\nZmin = -1\n\n# 座標の上限\nXmax = 1\nYmax = 1\nZmax = 1\n\n# 描画する関数\ndef func(x, z):\n r2 = x * x + z * z\n return math.exp(-r2) * math.cos(10 * math.sqrt(r2))\n\nsvgplot.plot_start(480, 260)\nlowerhorizon = []\nupperhorizon = []\nfor i in range(241):\n lowerhorizon.append(2e300) # 正の最大値\n upperhorizon.append(-2e300) # 負の最大値\ni = 240\nfor iz in range(21):\n z = Zmin + (Zmax - Zmin) / 20 * iz\n ok1 = 0\n for ix in range(201):\n x = Xmin + (Xmax - Xmin) / 200 * ix\n i = ix + 2 * (20 - iz) # 0..240\n y = 30 * (func(x, z) - Ymin) / (Ymax - Ymin) + 5 * iz # 0..130\n ok = 0\n if y < lowerhorizon[i]:\n lowerhorizon[i] = y\n ok = 1\n if y > upperhorizon[i]:\n upperhorizon[i] = y\n ok = 1\n if ok == 1 and ok1 == 1:\n svgplot.draw(2*i, 2*y)\n else:\n svgplot.move(2*i, 2*y)\n ok1 = ok\nsvgplot.plot_end(0)\n","sub_path":"3dgraph.py","file_name":"3dgraph.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"237093589","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n# 正常情况下,定义一个class,创建该class的实例后,可以给这个实例绑定任何属性和方法\n\nclass Student(object):\n pass\n\n# 给实例绑定属性\ns1 = Student()\ns1.name = \"xioaming\"\nprint(s1.name)\n# 给实例绑定方法\ndef set_age(self,age):\n self.age = age\n\nfrom types import MethodType\ns1.set_age = MethodType(set_age, s1) # 给实例绑定方法\nprint(hasattr(s1, 'set_age'))\ns1.set_age(20) # 调用方法\nprint(s1.age)\n\n# 给一个实例绑定的方法对其他实例绑定不了\ns2 = Student()\n# s2.set_age(22) # 报错:AttributeError: 'Student' object has no attribute 'set_age'\n\n# 给class绑定方法\ndef set_name(self, name):\n self.name = name\nStudent.set_name = set_name\n\n# 绑定之后,所有实例都可以访问该方法\ns3 = Student()\ns3.set_name(\"xiaowang\")\nprint(s3.name)\ns1.set_name(\"xiaoming\")\nprint(s1.name)\n\n# 如果限制实例的属性,可以在类的定义中添加__slots__变量\n\nclass People(object):\n __slots__ = ('name', 'sex')\n\np1 = People()\n# 给实例p1绑定__slots__变量中包含属性\np1.name = \"harry\"\np1.sex = \"male\"\nprint(p1.name, p1.sex)\n# 绑定slots变量中没有包含的属性时会报错\n# p1.age = (20)\n# print(p1.age)\n\n# __slots__变量限制的属性只对当前类实例有效,对继承的子类无效\n# 如果在子类中定义__slots__变量,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__\nclass Man(People):\n __slots__ = ('height')\n\nm1 = Man()\nm1.name, m1.sex, m1.height = [\"xiaoming\", \"male\", 180]\nprint(m1.name, m1.sex, m1.height)","sub_path":"learn/slots.py","file_name":"slots.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"338877215","text":"import networkx as nx\nimport os\nimport matplotlib.pyplot as plt\nimport random\nimport sys\nimport itertools\nimport math\nimport metis\nfrom output_scorer import score_output\nimport dummy\n\ndef main(inputFolder, outputFolder, name, case):\n\tinputs = readInput(inputFolder)\n\tG = inputs[0]\n\tG.remove_edges_from(G.selfloop_edges())\n\tencode = {}\n\tdecode = {}\n\tlabelID = 0\n\tfor node in G.nodes:\n\t\tencode[node] = labelID\n\t\tdecode[labelID] = node\n\t\tlabelID += 1\n\tG = nx.relabel_nodes(G, encode)\n\tfor u,v,d in G.edges(data=True):\n\t\td['weight'] = 1\n\tnum_buses = inputs[1]\n\tif num_buses == 1:\n\t\tbus_arrangements = []\n\t\tstudents = []\n\t\tfor node in G.nodes:\n\t\t\tstudents.append(decode[node])\n\t\tbus_arrangements.append(students)\n\t\twriteOutput(bus_arrangements, outputFolder, name)\n\t\treturn\n\tsize_bus = inputs[2]\n\tconstraints = inputs[3]\n\tfor i in range(len(constraints)):\n\t\tfor j in range(len(constraints[i])):\n\t\t\tconstraints[i][j] = encode[constraints[i][j]]\n\n\tedges_dict = computeRowdyEdges(constraints, G)\n\tif case == 1:\n\t\tnewG = G\n\t\tcomponents = partition(newG, num_buses)\n\telif case == 2:\n\t\tnewG = G\n\t\tcomponents = new_partition(newG, num_buses, size_bus)\n\telif case == 3:\n\t\tnewG = addRowdyEdges(G, edges_dict)\n\t\tcomponents = partition(newG, num_buses)\n\telif case == 4:\n\t\tnewG = addRowdyEdges(G, edges_dict)\n\t\tcomponents = new_partition(newG, num_buses, size_bus)\n\tbus_arrangements = merge(components, num_buses, G, size_bus)\n\tif bus_arrangements is None:\n\t\treturn\n\tfor i in range(len(bus_arrangements)):\n\t\tfor j in range(len(bus_arrangements[i])):\n\t\t\tbus_arrangements[i][j] = decode[bus_arrangements[i][j]]\n\tif bus_arrangements is None:\n\t\treturn\n\twriteOutput(bus_arrangements, outputFolder, name)\n\n\ndef writeOutput(bus_arrangements, folder, name):\n\tif not os.path.exists(folder):\n\t\tos.makedirs(folder)\n\tfile = folder + name +'.out'\n\twith open(file, 'w') as f:\n\t\tfor bus in bus_arrangements:\n\t\t\tf.write(\"%s\\n\" % bus)\n\tf.close()\n\n\ndef computeRowdyEdges(constraints, G):\n edge_weights = {}\n for x in constraints:\n length = len(x)\n all_edges = list(itertools.combinations(x, 2))\n for edge in all_edges:\n \tif not G.has_edge(edge[0], edge[1]):\n \t\tedge_weights[edge] = -1\n \telse:\n\t if(edge in edge_weights):\n\t edge_weights[edge] = max(edge_weights.get(edge), -1/length)\n\t else:\n\t edge_weights[edge] = -1/(length)\n return edge_weights\n\t\ndef readInput(inputFolder):\n\tgraph = nx.read_gml(inputFolder + \"graph.gml\")\n\tparameters = open(inputFolder + \"parameters.txt\")\n\tnum_buses = int(parameters.readline())\n\tsize_bus = int(parameters.readline())\n\tconstraints = []\n\tfor line in parameters:\n\t\tline = line[1: -2]\n\t\tcurr_constraint = [node.replace(\"'\",\"\") for node in line.split(\", \")]\n\t\tconstraints.append(curr_constraint)\n\treturn (graph, num_buses, size_bus, constraints)\n\n\ndef addRowdyEdges(G, edges):\n\tl = []\n\tfor k, v in edges.items():\n\t\tl.append((k[0], k[1], v))\n\tG.add_weighted_edges_from(l)\n\treturn G\n\ndef new_partition(G, num_buses, size_bus):\n\tgraph_components = {}\n\tedgecuts = ()\n\tparts = ()\n\tnodes_subgraph = []\n\tcut_size = num_buses\n\twhile True:\n\t\t(edgecuts, parts) = metis.part_graph(G, cut_size)\n\t\tnodes_subgraph = [[] for _ in range(max(parts) + 1)]\n\t\tfor i, p in enumerate(parts):\n\t\t\tnodes_subgraph[p].append(i)\n\t\tnodes_subgraph = list(filter(lambda x: len(x) > 0, nodes_subgraph))\n\t\tif len(nodes_subgraph) == num_buses:\n\t\t\tbreak\n\t\telif len(nodes_subgraph) >= 0.5*num_buses:\n\t\t\tnodes_subgraph.sort(key=lambda x: len(x))\n\t\t\twhile len(nodes_subgraph) < num_buses:\n\t\t\t\tbigComp = nodes_subgraph.pop()\n\t\t\t\tsub_g = nx.Graph(G.subgraph(bigComp))\n\t\t\t\tif nx.number_connected_components(sub_g) > 1:\n\t\t\t\t\tcComps = list(nx.connected_components(sub_g))\n\t\t\t\t\tcComps = [list(a) for a in cComps]\n\t\t\t\t\tcComps.sort(key=lambda x: len(x))\n\t\t\t\t\tbigG = cComps.pop()\n\t\t\t\t\tsub_g = nx.Graph(sub_g.subgraph(bigG))\n\t\t\t\t\tfor m in cComps:\n\t\t\t\t\t\tnodes_subgraph.append(m)\n\t\t\t\tparts = partition(sub_g, size_bus)\n\t\t\t\tfor k, v in parts.items():\n\t\t\t\t\tnodes_subgraph.append(list(k.nodes()))\n\t\t\t\tnodes_subgraph.sort(key=lambda x: len(x))\n\t\t\tbreak\n\t\tcut_size -= 1\n\n\tfor i in nodes_subgraph:\n\t\tsub_graph = G.subgraph(i)\n\t\tif nx.number_of_nodes(sub_graph) > size_bus:\n\t\t\trecursive_part = new_partition_helper(sub_graph, 2, size_bus)\n\t\t\tif recursive_part is not None:\n\t\t\t\tfor k in recursive_part:\n\t\t\t\t\tgraph_components[k[0]] = k[1]\n\t\t\telse:\n\t\t\t\tsub_g = nx.Graph(sub_graph)\n\t\t\t\trecursive_part = partition(sub_g, size_bus)\n\t\t\t\tfor k, v in recursive_part.items():\n\t\t\t\t\tgraph_components[k] = v\n\t\telse:\n\t\t\tgraph_components[sub_graph] = nx.number_of_nodes(sub_graph)\n\treturn graph_components\n\ndef new_partition_helper(G, num_buses, size_bus):\n\tgraph_components = []\n\tnodes = list(G.nodes)\n\tcut_size = num_buses\n\tnodes_subgraph = []\n\tparts = None\n\tran = 0\n\twhile True:\n\t\t(edgecuts, parts) = metis.part_graph(G, cut_size)\n\t\tnodes_subgraph = [[] for _ in range(max(parts) + 1)]\n\t\tfor i in range(len(parts)):\n\t\t\tlnum = parts[i]\n\t\t\tvertex = nodes[i]\n\t\t\tnodes_subgraph[lnum].append(vertex)\n\t\tnodes_subgraph = [x for x in nodes_subgraph if len(x) > 0]\n\t\tif len(nodes_subgraph) > 1:\n\t\t\tbreak\n\t\tcut_size -=1\n\t\tran += 1\n\t\tif cut_size == 1 or ran > 4:\n\t\t\treturn None\n\n\tfor i in nodes_subgraph:\n\t\tsub_graph = G.subgraph(i)\n\t\tif nx.number_of_nodes(sub_graph) > size_bus:\n\t\t\tr_comps = new_partition_helper(sub_graph, 2, size_bus)\n\t\t\tfor s in r_comps:\n\t\t\t\tgraph_components.append(s)\n\t\telse:\n\t\t\tgraph_components.append([sub_graph, nx.number_of_nodes(sub_graph)])\n\treturn graph_components\n\n\n\ndef partition(G, capacity):\n graph_components = {}\n need_cut = []\n cut_set = nx.minimum_edge_cut(G)\n G = delete_edges(G, cut_set) \n sub_graphs = [graph for graph in nx.connected_component_subgraphs(G)]\n for i in sub_graphs:\n \tgraph_components[i] = nx.number_of_nodes(i)\n \tif(graph_components[i] > capacity):\n \t\tneed_cut.append(i)\n while(need_cut):\n graph_components.pop(need_cut[0])\n big_graph = need_cut.pop(0)\n cut_set = nx.minimum_edge_cut(big_graph)\n big_graph = delete_edges(big_graph, cut_set) \n sub_big_graph = [graph for graph in nx.connected_component_subgraphs(big_graph)]\n for i in sub_big_graph:\n graph_components[i] = nx.number_of_nodes(i)\n if(graph_components[i] > capacity):\n need_cut.append(i)\n return graph_components\n\ndef delete_edges(G, edges):\n for x, y in edges:\n G.remove_edge(x,y)\n return G\n\n\ndef merge(comp_dict, k, G, bus_size):\n\tsorted_comp = sorted(comp_dict.items(), key=lambda kv: kv[1])\n\tgidMap = {}\n\tgID = 0\n\t#Map Graph ID to list of tuples (gID, sumEdgesWeight)\n\t#sorted_comp = [['GID', (GraphObject, SizeofGraph)], ...]\n\tlength = len(sorted_comp)\n\tconnections = [[0 for i in range(length)] for j in range(length)]\n\tsd = []\n\tfor i in sorted_comp:\n\t\ti[0].graph['id'] = gID\n\t\tgidMap[str(gID)] = i[0]\n\t\tsd.append([str(gID), (i[0], i[1])])\n\t\tgID += 1\t\n\tsorted_comp = sd\n\tfor a in sorted_comp:\n\t\tfor b in sorted_comp:\n\t\t\tif a is not b and connections[a[1][0].graph['id']][b[1][0].graph['id']] is not None:\n\t\t\t\tw = 0\n\t\t\t\tfor i in list(a[1][0].nodes):\n\t\t\t\t\tfor j in list(b[1][0].nodes):\n\t\t\t\t\t\tif G.has_edge(i, j):\n\t\t\t\t\t\t\tw += G[i][j]['weight']\n\t\t\t\tconnections[a[1][0].graph['id']][b[1][0].graph['id']] = w\n\t\t\t\tconnections[b[1][0].graph['id']][a[1][0].graph['id']] = w\n\t\n\tbuses = []\n\twhile len(sorted_comp) != k:\n\t\tminComp = sorted_comp.pop(0)\n\t\tminID = minComp[0]\n\t\totherID = findBestMerge(minID, sorted_comp, minComp[1][1], bus_size, connections)\n\n\t\t\n\t\tif otherID == '':\n\t\t\tsorted_comp.insert(0, minComp)\n\t\t\ttoDistribute = []\n\t\t\twhile len(sorted_comp) > k:\n\t\t\t\tsplitter = sorted_comp.pop(0)\n\t\t\t\tminComps = splitter[0].split('+')\n\t\t\t\tfor j in minComps:\n\t\t\t\t\ttoDistribute += list(gidMap[j].nodes)\n\t\t\t\n\t\t\tbuses = [[] for i in range(k)]\n\t\t\tfor j in range(len(sorted_comp)):\n\t\t\t\tids = sorted_comp[j][0].split('+')\n\t\t\t\tnodes = []\n\t\t\t\tfor i in ids:\n\t\t\t\t\tnodes += list(gidMap[i].nodes)\n\t\t\t\tbuses[j] = nodes\n\n\t\t\tadded = [sorted_comp[i][1][1] for i in range(len(sorted_comp))]\n\t\t\twhile toDistribute:\n\t\t\t\tnode = toDistribute.pop()\n\t\t\t\tindex = random.randint(0, len(sorted_comp) - 1)\n\t\t\t\twhile added[index] + 1 > bus_size:\n\t\t\t\t\tindex = random.randint(0, len(sorted_comp) - 1)\n\t\t\t\tbuses[index].append(node)\n\t\t\t\tadded[index] += 1\t\n\t\t\treturn buses\n\t\t\n\t\tsorted_comp = list(filter(lambda x: x[0] != otherID, sorted_comp))\n\t\t\n\t\tminComps = minID.split('+')\n\t\totherComps = otherID.split('+')\n\t\tminNodes = sum([nx.number_of_nodes(gidMap[a]) for a in minComps])\n\t\totherNodes = sum([nx.number_of_nodes(gidMap[a]) for a in otherComps])\n\t\t\n\t\tsorted_comp.append([minID + \"+\" + otherID, (minComp[1][0], minNodes + otherNodes)])\n\t\tsorted_comp.sort(key=lambda x: x[1][1])\n\n\n\tfor bus in sorted_comp:\n\t\tids = bus[0].split('+')\n\t\tnodes = []\n\t\tfor i in ids:\n\t\t\tnodes += list(gidMap[i].nodes)\n\t\tbuses.append(nodes)\n\n\treturn buses\n\n\ndef findBestMerge(gID, sList, numGNodes, capacity, connections):\n\tids = gID.split('+')\n\tids = [int(a) for a in ids]\n\tbest = -math.inf\n\totherID = ''\n\tfor x in sList:\n\t\tif x[0] != str(gID):\n\t\t\toID = x[0]\n\t\t\tcomps = oID.split('+')\n\t\t\tcomps = [int(b) for b in comps]\n\t\t\tedgeSum = 0\n\t\t\tfor i in ids:\n\t\t\t\tfor j in comps:\n\t\t\t\t\tedgeSum += connections[i][j]\n\t\t\tif numGNodes + x[1][1] <= capacity and edgeSum > best:\n\t\t\t\tbest = edgeSum\n\t\t\t\totherID = oID\n\treturn otherID\n\ndef draw(G):\n\tpos = nx.spring_layout(G,k=1,iterations=20)\n\tnx.draw(G, pos)\n\tlabels = nx.get_edge_attributes(G,'weight')\n\t#nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)\n\tnx.draw_networkx_labels(G, pos=pos)\n\tplt.show()\n\n\n# if __name__ == '__main__':\n# \tiname = \"all_inputs/small/\"\n# \toname = \"all_outputs/small/\"\n\n# \ta = []\n# \tb = []\n# \tfor x in os.listdir(iname)[:40]:\n# \t\tx = x + \"/\"\n# \t\ttry:\n# \t\t\tmain(iname+x, oname+x)\n# \t\t\ta.append(iname+x)\n# \t\t\tb.append(oname+x+\".out\")\n# \t\texcept:\n# \t\t\tcontinue\n# \tscores = []\n# \tfor i in range(len(a)):\n# \t\ttry:\n# \t\t\tscore, msg = score_output(a[i], b[i])\n# \t\t\tscores.append(score)\n# \t\t\tprint(msg)\n# \t\texcept:\n# \t\t\tcontinue\n# \tprint(\"Average is: \", sum(scores)/len(scores))\n\ndef solver_main(input_type):\n\tiname = \"all_inputs/\" + input_type + \"/\"\n\toname = \"all_outputs/\" + input_type + \"/\"\n\n\tfiles = list(os.walk(iname))[0][1]\n\tscores = []\n\tfiles.sort(reverse=True)\n\tfor f in files:\n\t\tprint(f)\n\t\ttry:\n\t\t\tmain(iname + f + \"/\", oname, f + \"1\", 1)\n\t\t\tscore1, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + \"1.out\")\n\t\texcept:\n\t\t\tscore1 = 0\n\t\t\topen(oname + str(f) + \"1.out\", 'a').close()\n\t\ttry:\n\t\t\tmain(iname + f + \"/\", oname, f + \"2\", 2)\n\t\t\tscore2, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + \"2.out\")\n\t\texcept:\n\t\t\tscore2 == 0\n\t\t\topen(oname + str(f) + \"2.out\", 'a').close()\n\t\ttry:\n\t\t\tmain(iname + f + \"/\", oname, f + \"3\", 3)\n\t\t\tscore3, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + \"3.out\")\n\t\texcept:\n\t\t\tscore3 = 0\n\t\t\topen(oname + str(f) + \"3.out\", 'a').close()\n\t\ttry:\n\t\t\tmain(iname + f + \"/\", oname, f + \"4\", 4)\n\t\t\tscore4, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + \"4.out\")\n\t\texcept:\n\t\t\tscore4 = 0\n\t\t\topen(oname + str(f) + \"4.out\", 'a').close()\n\t\tdummyScores = []\n\t\tfor i in range(5):\n\t\t\tdummy.main(f, iType = input_type, counter = i)\n\t\t\tscoreDum, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + str(i) + \"5.out\")\n\t\t\tdummyScores.append(scoreDum)\n\t\tscore5 = max(dummyScores)\n\t\tindex_dum = dummyScores.index(score5)\n\t\tos.rename(oname + str(f) + str(dummyScores.index(score5)) + \"5.out\", oname + str(f) + \"5.out\")\n\t\tif index_dum == 0:\n\t\t\tos.remove(oname + str(f) + \"15.out\")\n\t\t\tos.remove(oname + str(f) + \"25.out\")\n\t\t\tos.remove(oname + str(f) + \"35.out\")\n\t\t\tos.remove(oname + str(f) + \"45.out\")\n\t\telif index_dum == 1:\n\t\t\tos.remove(oname + str(f) + \"05.out\")\n\t\t\tos.remove(oname + str(f) + \"25.out\")\n\t\t\tos.remove(oname + str(f) + \"35.out\")\n\t\t\tos.remove(oname + str(f) + \"45.out\")\n\t\telif index_dum == 2:\n\t\t\tos.remove(oname + str(f) + \"05.out\")\n\t\t\tos.remove(oname + str(f) + \"15.out\")\n\t\t\tos.remove(oname + str(f) + \"35.out\")\n\t\t\tos.remove(oname + str(f) + \"45.out\")\n\t\telif index_dum == 3:\n\t\t\tos.remove(oname + str(f) + \"05.out\")\n\t\t\tos.remove(oname + str(f) + \"15.out\")\n\t\t\tos.remove(oname + str(f) + \"25.out\")\n\t\t\tos.remove(oname + str(f) + \"45.out\")\n\t\telif index_dum == 4:\n\t\t\tos.remove(oname + str(f) + \"05.out\")\n\t\t\tos.remove(oname + str(f) + \"15.out\")\n\t\t\tos.remove(oname + str(f) + \"25.out\")\n\t\t\tos.remove(oname + str(f) + \"35.out\")\n\t\tscore = max(score1, score2, score3, score4, score5)\n\t\tif score == score1:\n\t\t\tos.rename(oname + str(f) + \"1.out\", oname + str(f) + \".out\")\n\t\t\tos.remove(oname + str(f) + \"2.out\")\n\t\t\tos.remove(oname + str(f) + \"3.out\")\n\t\t\tos.remove(oname + str(f) + \"4.out\")\n\t\t\tos.remove(oname + str(f) + \"5.out\")\n\t\telif score == score2:\n\t\t\tos.rename(oname + str(f) + \"2.out\", oname + str(f) + \".out\")\n\t\t\tos.remove(oname + str(f) + \"1.out\")\n\t\t\tos.remove(oname + str(f) + \"3.out\")\n\t\t\tos.remove(oname + str(f) + \"4.out\")\n\t\t\tos.remove(oname + str(f) + \"5.out\")\n\t\telif score == score3:\n\t\t\tos.rename(oname + str(f) + \"3.out\", oname + str(f) + \".out\")\n\t\t\tos.remove(oname + str(f) + \"1.out\")\n\t\t\tos.remove(oname + str(f) + \"2.out\")\n\t\t\tos.remove(oname + str(f) + \"4.out\")\n\t\t\tos.remove(oname + str(f) + \"5.out\")\n\t\telif score == score4:\n\t\t\tos.rename(oname + str(f) + \"4.out\", oname + str(f) + \".out\")\n\t\t\tos.remove(oname + str(f) + \"1.out\")\n\t\t\tos.remove(oname + str(f) + \"2.out\")\n\t\t\tos.remove(oname + str(f) + \"3.out\")\n\t\t\tos.remove(oname + str(f) + \"5.out\")\n\t\telif score == score5:\n\t\t\tos.rename(oname + str(f) + \"4.out\", oname + str(f) + \".out\")\n\t\t\tos.remove(oname + str(f) + \"1.out\")\n\t\t\tos.remove(oname + str(f) + \"2.out\")\n\t\t\tos.remove(oname + str(f) + \"3.out\")\n\t\t\tos.remove(oname + str(f) + \"5.out\")\n\t\tcount = 0\n\t\twhile score == 0:\n\t\t\tif count > 10:\n\t\t\t\tbreak\n\t\t\tos.remove(oname + str(f) + \".out\")\n\t\t\tdummy.main(f, iType=input_type)\n\t\t\tos.rename(oname + str(f) + \"05.out\", oname + str(f) + \".out\")\n\t\t\tscore, msg = score_output(iname + \"/\" + f + \"/\", oname + str(f) + \".out\")\n\t\t\tcount += 1\n\t\tprint(\"Score: \", score*100, \"%\")\n\t\ttry:\n\t\t\tif score >= 0:\n\t\t\t\tscores.append(score)\n\t\texcept:\n\t\t\tcontinue\n\tprint(\"Average: \", sum(scores)/len(scores))\n\tprint(len(files))\n\tprint(len(scores))\n","sub_path":"finalSolver/greedyCutSolver.py","file_name":"greedyCutSolver.py","file_ext":"py","file_size_in_byte":14115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"264138272","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 04 21:50:16 2017\r\n\r\n@author: raghavrastogi\r\n\"\"\"\r\nfrom mlxtend.plotting import plot_decision_regions\r\nfrom sklearn import datasets\r\nimport numpy as np\r\niris = datasets.load_iris()\r\nX = iris.data[:, [2, 3]]\r\ny = iris.target\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.cross_validation import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nsc = StandardScaler()\r\nsc.fit(X_train)\r\nX_train_std = sc.transform(X_train)\r\nX_test_std = sc.transform(X_test)\r\n \r\n#from sklearn.tree import DecisionTreeClassifier\r\n#tree = DecisionTreeClassifier(criterion='entropy',max_depth=3, random_state=0)\r\n#tree.fit(X_train, y_train)\r\n#X_combined = np.vstack((X_train, X_test))\r\n#y_combined = np.hstack((y_train, y_test))\r\n#plot_decision_regions(X_combined, y_combined,tree)\r\n#plt.xlabel('petal length [cm]')\r\n#plt.ylabel('petal width [cm]')\r\n#plt.legend(loc='upper left')\r\n#plt.show()\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nforest = RandomForestClassifier(criterion='entropy',n_estimators=10,random_state=1,n_jobs=2)\r\nforest.fit(X_train, y_train)\r\nX_combined = np.vstack((X_train, X_test))\r\ny_combined = np.hstack((y_train, y_test))\r\nplot_decision_regions(X_combined, y_combined,forest)\r\nplt.xlabel('petal length')\r\nplt.ylabel('petal width')\r\nplt.legend(loc='upper left')\r\nplt.show()\r\n\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nknn = KNeighborsClassifier(n_neighbors=5, p=2,metric='minkowski')\r\nX_combined_std = np.vstack((X_train_std, X_test_std))\r\ny_combined = np.hstack((y_train, y_test))\r\nknn.fit(X_train_std, y_train)\r\nplot_decision_regions(X_combined_std, y_combined,knn)\r\nplt.xlabel('petal length [standardized]')\r\nplt.ylabel('petal width [standardized]')\r\nplt.show()","sub_path":"raschka_3_decision_tree_classifier_randforest_KNN.py","file_name":"raschka_3_decision_tree_classifier_randforest_KNN.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"162693426","text":"import random\n\n\nprint('Whats your name ?')\nname = input()\nsecretnumber = random.randint(1,20)\nprint('I am thinking of a number between 1 and 20')\ntry:\n\n for guesses in range (1,7):\n print('take a guess')\n guess = int(input())\n\n if guess > 20:\n print('we asked to guess a number between 1 and 20 phunk! ')\n\n elif guess < secretnumber:\n print('your guess is too low')\n elif guess > secretnumber:\n print('your guess is too high')\n\n else:\n break\n\n if guess == secretnumber:\n print('good job' + name + ' guessed the number i was thinking in '+ str(guesses)+' guesses.')\n else:\n print(name +' could not guess my number, iwas thinking about '+str(secretnumber)+'.')\n\nexcept ValueError:\n print('please type a number')\n","sub_path":"Chapters_ABSWP/randomnumber.py","file_name":"randomnumber.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"15281156","text":"# coding: utf8\r\n\r\n# @Author: 郭 璞\r\n# @File: TestAll.py \r\n# @Time: 2017/5/12 \r\n# @Contact: 1064319632@qq.com\r\n# @blog: http://blog.csdn.net/marksinoberg\r\n# @Description: \r\nfrom whooshlearn.csdn import Login, BlogScanner, BlogDetails, Searcher\r\n\r\nlogin = Login()\r\nsession = login.login(username=\"marksinoberg\", password=\"PRCstylewarmup\")\r\nprint(session)\r\n\r\nscanner = BlogScanner(domain=\"Marksinoberg\")\r\nblogs = scanner.scan()\r\nprint(blogs[0:3])\r\n\r\nblogdetails = BlogDetails(session=session, blogurl=blogs[0])\r\nblog = blogdetails.getSource()\r\nprint(blog['url'])\r\nprint(blog['description'])\r\nprint(blog['tags'])\r\n\r\n# test whoosh for searcher\r\nsearcher = Searcher()\r\ncounter=1\r\nfor item in blogs[0:10]:\r\n print(\"开始处理第{}篇文章\".format(counter))\r\n counter+=1\r\n details = BlogDetails(session=session, blogurl=item).getSource()\r\n searcher.addblog(details)\r\n# searcher.addblog(blog)\r\n# searcher.search('DbHelper')\r\n# searcher.search('Python')\r\nsearcher.search(\"博客\")","sub_path":"whooshlearn/TestAll.py","file_name":"TestAll.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277439649","text":"\"\"\"First the Black-Scholes formula as a benchmark for Monte Carlo valuation of a european vanilla option.\nThe Black-Scholes formula\"\"\"\n\nfrom random import normalvariate\nfrom math import exp, sqrt, log\n\n\n\"\"\"Approximation of the Normal Distribution\"\"\"\ndef N(x):\n y = abs(x)\n if y > 37:\n nd = 0\n else:\n e = exp(-y * y / 2.0)\n if y < 7.07106781186547:\n sumA = 0.0352624965998911 * y + 0.700383064443688\n sumA = sumA * y + 6.37396220353165\n sumA = sumA * y + 33.912866078383\n sumA = sumA * y + 112.079291497871\n sumA = sumA * y + 221.213596169931\n sumA = sumA * y + 220.206867912376\n sumB = 0.0883883476483184 * y + 1.75566716318264\n sumB = sumB * y + 16.064177579207\n sumB = sumB * y + 86.7807322029461\n sumB = sumB * y + 296.564248779674\n sumB = sumB * y + 637.333633378831\n sumB = sumB * y + 793.826512519948\n sumB = sumB * y + 440.413735824752\n nd = e * sumA / sumB\n else:\n sumA = y + 0.65\n sumA = y + 4.0 / sumA\n sumA = y + 3.0 / sumA\n sumA = y + 2.0 / sumA\n sumA = y + 1.0 / sumA\n nd = e / (sumA * 2.506628274631)\n if x > 0:\n nd = 1.0 - nd\n return nd\n\n\n\"\"\"Black-Scholes formula\"\"\"\ndef BlackScholes(S0, K, T, r, d, sigma, isCall):\n # Parameter for switching between call and put: isCall = True => callPut = 1, isCall = False => callPut = -1\n callPut = 2 * isCall - 1\n # Forward value: Compounding\n forward = S0 * exp((r - d) * T)\n\n # Black-Scholes solution\n d1 = (log(forward / K) + 0.5 * sigma * sigma * T) / (sigma * sqrt(T))\n d2 = d1 - sigma * sqrt(T)\n result = callPut * exp(-r * T) * (forward * N(callPut * d1) - K * N(callPut * d2))\n\n return result\n\n\n\"\"\"Testa olika värden på parametrarna.\"\"\"\ndef TestBlackScholesFormula():\n \"\"\" The parameters here should return a value of 16.7341... \"\"\"\n S0 = 100.0\n K = 100.0\n isCall = True\n r = 0.1\n d = 0.0\n sigma = 0.3\n T = 1.0\n\n analytical = BlackScholes(S0, K, T, r, d, sigma, isCall)\n print(analytical)\n\nTestBlackScholesFormula()\n\n\n\"\"\"Python function for generating a random walk\"\"\"\ndef MonteCarloPath(S0, sigma, r, d, timePoints, nt):\n # Path starts at time timePoints[0] = 0, for each time step we append the simulated index level\n St = S0\n path = [St]\n det = r - d - 0.5 * sigma * sigma\n for i in range(nt - 1):\n # Get time step dt and a standard normal random variable\n dt = timePoints[i + 1] - timePoints[i]\n rand = normalvariate(0.0, 1.0)\n\n # Solution to Black-Scholes SDE\n St = St * exp(det * dt + sigma * sqrt(dt) * rand)\n path.append(St)\n\n return path\n\n\"\"\"A simple test\n#Let us test the above function: We do a few iterations,\n# that give different outcomes since we do not specify a seed for the random number generator at each iteration\"\"\"\ndef TestRandomWalk():\n S0 = 100.0\n sigma = 0.3\n r = 0.1\n d = 0.0\n timePoints = [0.0, 0.5, 1.0, 1.5, 2.0]\n nt = len(timePoints)\n\n path = MonteCarloPath(S0, sigma, r, d, timePoints, nt)\n\n print(path)\n\n\nfor i in range(5):\n TestRandomWalk()\n\n\n\"\"\"Example payoff for a european vanilla option: Only one cashflow at expiry\"\"\"\ndef VanillaPayoff(path, parameters):\n # Extraxt contract parameters\n strikePrice = parameters[0]\n isCall = parameters[1]\n cfIndex = parameters[2]\n\n # Find index level at expiry/maturity: In this case at the only cash flow time indicated by cfIndex\n ST = path[cfIndex]\n callPut = 2 * isCall - 1\n\n # Payoff of a vanilla option: Return an array of cashflows and cashflow times (in this case one at expiry)\n cashFlows = [[max(callPut * (ST - strikePrice), 0.0), cfIndex]]\n result = {\"CashFlows\": cashFlows, \"KO Index\": cfIndex, \"KO Pos\": 0}\n\n return result\n\n\ndef NikkeiLinkedNotePayoff(path, parameters):\n nominal = parameters[0] # The amount invested\n initial = parameters[1] # The initial index level\n knockOut = parameters[2] # knock out level: 105% = 1.05\n knockIn = parameters[3] # knock in level : 65% = 0.65\n highRate = parameters[4] # For example: 4% = 0.04\n lowRate = parameters[5] # For example: 0.1% = 0.001\n strike = parameters[6] # strike level: 85% = 0.85\n intervals = parameters[7] # The lengths of the cash flow periods in years\n cfIndices = parameters[8] # the indices of cashflow time points\n\n # Check if the contract has been knocked in: We simulate the path for all dates so we just take the minimum\n strike = strike * initial\n knockIn = knockIn * initial\n knockOut = knockOut * initial\n isKnockIn = (min(path) < knockIn)\n\n # Loop over the cash flow dates\n cashFlows = []\n isKnockOut = False\n index = 0\n koIndex = cfIndices[-1]\n koPos = len(cfIndices) - 1\n for cfIndex in cfIndices:\n St = path[cfIndex]\n if not isKnockOut:\n if St >= strike:\n cashFlows.append([nominal * intervals[index] * highRate, cfIndex])\n else:\n cashFlows.append([nominal * intervals[index] * lowRate, cfIndex])\n if St >= knockOut:\n \"\"\" We add the nominal cash flow to the position of 'index' \"\"\"\n cashFlows[index][0] += nominal\n isKnockOut = True\n koIndex = cfIndex\n koPos = index\n else:\n cashFlows.append([0.0, cfIndex])\n\n index += 1\n\n if not isKnockOut:\n # In this case the investment amount ha still not been repaid: cfIndex is the last of cfIndices (hence the -1)\n cfIndex = cfIndices[-1]\n ST = path[cfIndex]\n pos = len(cfIndices) - 1\n if isKnockIn:\n cashFlows[pos][0] += nominal * min(ST / initial, 1.0)\n else:\n cashFlows[pos][0] += nominal\n\n # print(S0, S0*1.05, S0*0.85, S0*0.65, min(path))\n # print([path[index] for index in cfIndices])\n # print(cashFlows)\n\n result = {\"CashFlows\": cashFlows, \"KO Index\": koIndex, \"KO Pos\": koPos}\n return result\n\n\"\"\"Testing the payoff functions\"\"\"\ndef TestVanillaPayoff():\n S0 = 100.0\n K = 100.0\n isCall = True\n sigma = 0.3\n r = 0.1\n d = 0.0\n timePoints = [0.0, 0.5, 1.0, 1.5, 2.0]\n nt = len(timePoints)\n cfIndex = nt - 1 # A vanilla option only has one cash flow, the one at expiry = last index of the timePoints array.\n parameters = [K, isCall, cfIndex]\n path = MonteCarloPath(S0, sigma, r, d, timePoints, nt)\n\n print(path)\n\n payOff = VanillaPayoff(path, parameters)\n\n print(payOff)\n\n\nfor i in range(5):\n TestVanillaPayoff()\n\n\ndef TestStructurePayoff():\n nominal = 1e9\n initial = 17900.0\n S0 = 18000.0\n knockOut = 1.05\n knockIn = 0.65\n highRate = 0.04\n lowRate = 0.001\n strike = 0.85\n r = 0.01\n d = 0.00\n sigma = 0.15\n dt = 1.0 / 365\n timePoints = [i * dt for i in range(3 * 365 + 1)]\n nt = len(timePoints)\n cfIndices = [182, 365, 365 + 182, 2 * 365, 2 * 365 + 182, 3 * 365]\n intervals = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]\n parameters = [nominal, initial, knockOut, knockIn, highRate, lowRate, strike, intervals, cfIndices]\n\n path = MonteCarloPath(S0, sigma, r, d, timePoints, nt)\n\n # We do not really want to print the path in this case\n # print(path)\n\n payOff = NikkeiLinkedNotePayoff(path, parameters)\n\n print(payOff)\n\n\nfor i in range(5):\n TestStructurePayoff()\n\n\"\"\"The monte Carlo function\"\"\"\n\n\ndef MonteCarlo(S0, sigma, r, d, timePoints, payOffFunction, parameters, nSim):\n theor = 0.0\n nt = len(timePoints)\n remainLife = 0.0\n for i in range(nSim):\n # Simulate path and calculate contract value: Payoff returns an array of cashflows\n path = MonteCarloPath(S0, sigma, r, d, timePoints, nt)\n result = payOffFunction(path, parameters)\n cashFlows = result[\"CashFlows\"]\n koIndex = result[\"KO Index\"]\n koPos = result[\"KO Pos\"]\n remainLife += timePoints[koIndex]\n\n # Initilize array for knockout probabilities\n if i == 0:\n koProb = [0.0 for cf in cashFlows]\n cfs = [0.0 for cf in cashFlows]\n cfPVs = [0.0 for cf in cashFlows]\n\n koProb[koPos] += 1.0\n pv = 0.0\n index = 0\n for cashFlow in cashFlows:\n # For each cash flow we have the cash flow value and the index of when it occurs in the timePoints array\n cfValue = cashFlow[0]\n cfIndex = cashFlow[1]\n cfTime = timePoints[cfIndex]\n\n # Discount the cash flow and add to payoff: Assuming a constant discount rate\n cfPV = cfValue * exp(-r * cfTime)\n pv += cfPV\n\n # Accumulate the total cashflows and their PVs\n cfs[index] += cfValue\n cfPVs[index] += cfPV\n\n index += 1\n\n # Add to the result of previous simulations (cfs and cfs have an extra nominal cash flow which must be moved)\n theor += pv\n\n # Take the average\n result = {}\n result[\"Theoretical Value\"] = theor / nSim\n result[\"Remaining Life\"] = remainLife / nSim\n result[\"KO Probability\"] = [prob / nSim for prob in koProb]\n result[\"Cash Flows\"] = [cf / nSim for cf in cfs]\n result[\"Cash Flow PVs\"] = [cfPV / nSim for cfPV in cfPVs]\n\n return result\n\n\"\"\"Here is an example of how to use the Monte Carlo Function together with a vanilla option payoff\"\"\"\n\n\ndef VanillaOptionTest():\n S0 = 100.0\n K = 100.0\n isCall = True\n r = 0.1\n d = 0.0\n sigma = 0.3\n T = 1.0\n timePoints = [0.0, T] # Only time now and at expiry\n cfIndex = len(timePoints) - 1 # This is the final point in the path\n parameters = [K, isCall, cfIndex]\n nSim = 1000000\n payOff = VanillaPayoff\n\n analytical = BlackScholes(S0, K, T, r, d, sigma, isCall)\n monteCarlo = MonteCarlo(S0, sigma, r, d, timePoints, payOff, parameters, nSim)\n\n print(\"Analytical : \", analytical)\n print(\"Monte Carlo : \", monteCarlo)\n\n\nVanillaOptionTest()\n\n\"\"\"Here is an example of how to use the Monte Carlo function with a Nikkei linked note payoff.\nNotice that the Cash Flows are the approximate expected cash flows and are close to weighting the\nTheoretical Value with knock-out probabilities at different knock-out dates.\nWe assume that there are cash flows every 0.5 years and that the 0.5 years is 182 or 183 days (not accounting for leap years)\"\"\"\n\n\ndef StructuredNoteTest():\n nominal = 1e9\n initial = 17900.0\n S0 = 18000.0\n knockOut = 1.05\n knockIn = 0.65\n highRate = 0.04\n lowRate = 0.001\n strike = 0.85\n r = 0.01\n d = 0.00\n sigma = 0.15\n dt = 1.0 / 365\n timePoints = [i * dt for i in range(3 * 365 + 1)]\n cfIndices = [182, 365, 365 + 182, 2 * 365, 2 * 365 + 182,\n 3 * 365] # Approximate indices of cash flows in the array timePoints\n intervals = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5] # Cash flows each 6 months\n parameters = [nominal, initial, knockOut, knockIn, highRate, lowRate, strike, intervals, cfIndices]\n\n payOff = NikkeiLinkedNotePayoff\n nSim = 10000\n\n monteCarlo = MonteCarlo(S0, sigma, r, d, timePoints, payOff, parameters, nSim)\n\n for key in monteCarlo.keys():\n print(key, monteCarlo[key])\n if key in [\"Cash Flows\", \"Cash Flow PVs\", \"KO Probability\"]:\n \"\"\" A simple check that the arrays sum up to the correct number \"\"\"\n print(\"SUM(\" + key + \") : \", sum(monteCarlo[key]))\n\n\nStructuredNoteTest()\n\n\"\"\"Interpolation Function\"\"\"\n\n\ndef FindPosition(point, points):\n \"\"\"Determines the position of point in the vector points\"\"\"\n if point < points[0]:\n return -1\n\n for i in range(len(points) - 1):\n if point < points[i + 1]:\n return i\n\n return len(points)\n\n\ndef LinearInterpolation(point, points, values):\n \"\"\"LinearInterpolation(point, points, values)\"\"\"\n n = len(points)\n i = FindPosition(point, points)\n if i == -1:\n return values[0]\n\n elif i == len(values):\n return values[len(values) - 1]\n\n coeff = (values[i + 1] - values[i]) / (points[i + 1] - points[i])\n value = values[i] + (point - points[i]) * coeff\n\n return value\n\n\"\"\"Discount Factor and Forward Rate Calculation\"\"\"\n\n\ndef ForwardRate(timePoints, rates, timeStart, timeEnd):\n \"\"\" Interpolate rates \"\"\"\n rateStart = LinearInterpolation(timeStart, timePoints, rates)\n rateEnd = LinearInterpolation(timeEnd, timePoints, rates)\n\n \"\"\" Calculate discount factors \"\"\"\n discStart = exp(-rateStart * timeStart)\n discEnd = exp(-rateEnd * timeEnd)\n\n \"\"\" Forward discount factor and forward rate\"\"\"\n dForw = discEnd / discStart\n dt = timeEnd - timeStart\n forw = (1.0 - dForw) / (dt * dForw)\n\n return forw\n\n\nclass FloatingRateNote:\n def __init__(self, nominal, maturityTime, cashFlowTimes, spread):\n \"\"\" Assuming that cash flow times and maturity are with respect to today and today is the start date.\n A real FRN valuation would include start date, maturity date, cash flow period, business date adjustments\n and a day count method.\n \"\"\"\n self.nominal = nominal\n self.maturityTime = maturityTime\n self.cashFlowTimes = cashFlowTimes\n self.spread = spread\n\n def PresentValue(self, timePoints, rates):\n pv = 0.0\n nCF = len(self.cashFlowTimes)\n\n for iCF in range(nCF):\n if iCF == 0:\n # Assuming today is time t = 0.0 and cashFlowTimes[0] is the time to the first cash flow\n t0 = 0.0\n t1 = self.cashFlowTimes[iCF]\n else:\n # A forward starting time period\n t0 = self.cashFlowTimes[iCF - 1]\n t1 = self.cashFlowTimes[iCF]\n\n dt = t1 - t0\n F = ForwardRate(timePoints, rates, t0, t1)\n\n rate = LinearInterpolation(t1, timePoints, rates)\n disc = exp(-rate * t1)\n\n \"\"\" Cash flow \"\"\"\n pv += self.nominal * (F + self.spread) * dt * disc\n\n \"\"\" Final repayment of nominal: Note that after the loop above the discount factor will be the one for maturity\n as this is the last cash flow time.\n \"\"\"\n pv += self.nominal * disc\n\n return pv\n\n\"\"\"Testing FRN Valuation\"\"\"\n\n\ndef TestValuationFRN():\n timePoints = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]\n rates = [0.01, 0.015, 0.018, 0.2, 0.21, 0.215, 0.218, 2.20]\n nominal = 1e9\n maturityTime = 3.0\n cashFlowTimes = [0.25 * i for i in range(1, 13)]\n spread = -0.0040\n frn = FloatingRateNote(nominal, maturityTime, cashFlowTimes, spread)\n\n theor = frn.PresentValue(timePoints, rates)\n\n print(theor)\n\n\nTestValuationFRN()\n\n\"\"\"Testing Structured Swap Valuation\"\"\"\n\n\ndef StructuredSwapTest():\n \"\"\" We assume an interest rate curve even if it is not used in the valuation of the structured swap \"\"\"\n rateTimes = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]\n ratesUSD = [0.01, 0.015, 0.018, 0.02, 0.021, 0.0215, 0.0218, 0.0220]\n ratesJPY = [0.00, 0.005, 0.008, 0.01, 0.015, 0.018, 0.02, 0.021]\n\n nominalJPY = 1e9\n nominalUSD = nominalJPY / 112.5\n fxRate = 112.5 # An approximate made up raate between JPY and USD\n initial = 18000.0\n S0 = 17200.0\n knockOut = 1.05\n knockIn = 0.65\n highRate = 0.04\n lowRate = 0.001\n strike = 0.85\n T = 3.0\n r = LinearInterpolation(T, rateTimes, ratesJPY)\n d = 0.00\n sigma = 0.15\n dt = 1.0 / 365\n timePoints = [i * dt for i in range(3 * 365 + 1)]\n cfIndices = [182, 365, 365 + 182, 2 * 365, 2 * 365 + 182,\n 3 * 365] # Approximate indices of cash flows in the array timePoints\n intervals = [0.5, 0.5, 0.5, 0.5, 0.5, 0.5] # Cash flows each 6 months\n parameters = [nominalJPY, initial, knockOut, knockIn, highRate, lowRate, strike, intervals, cfIndices]\n\n payOff = NikkeiLinkedNotePayoff\n nSim = 10000\n\n monteCarlo = MonteCarlo(S0, sigma, r, d, timePoints, payOff, parameters, nSim)\n structPV = monteCarlo[\"Theoretical Value\"]\n\n \"\"\" At this point we will create one FRN for each knock-out time \"\"\"\n floatPV = 0.0\n maturities = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0]\n for i in range(len(maturities)):\n maturity = maturities[i]\n cashFlowTimes = [0.25 * j for j in range(1, int(maturity / 0.25) + 1)]\n spread = -0.0040\n frn = FloatingRateNote(nominalUSD, maturity, cashFlowTimes, spread)\n floatPV += monteCarlo[\"KO Probability\"][i] * frn.PresentValue(rateTimes, ratesUSD)\n\n \"\"\" Print the leg PVs and the total PV \"\"\"\n print(\"-\" * 100)\n print(\"Struct Leg (JPY): \", structPV)\n print(\"Libor Leg (USD): \", floatPV)\n print(\"Swap Value (USD): \", structPV / fxRate - floatPV)\n\n \"\"\" Print additional info of struct leg \"\"\"\n print(\"-\" * 100)\n for key in monteCarlo.keys():\n print(key, monteCarlo[key])\n print(\"-\" * 100)\n\n\nStructuredSwapTest()\n\n\"\"\"Struct Leg (JPY): 980394145.5618186\nLibor Leg (USD): 8819712.721639313\nSwap Value (USD): -105098.09442314692\n----------------------------------------------------------------------------------------------------\nRemaining Life 1.9955400000000068\nTheoretical Value 980394145.5618186\nCash Flows [212424050.0, 156953200.0, 102133200.0, 69439500.0, 52483400.0, 421286653.8808537]\nCash Flow PVs [210526001.9605835, 154153316.9439502, 99414949.65016069, 66984139.65931969, 50175235.420371205, 399140501.92743486]\nKO Probability [0.195, 0.1448, 0.0935, 0.063, 0.0473, 0.4564]\"\"\"","sub_path":"RandomPathSimulator.py","file_name":"RandomPathSimulator.py","file_ext":"py","file_size_in_byte":17570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"352030312","text":"\r\n# 给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。\r\n\r\n# 如果剩余字符少于 k 个,则将剩余字符全部反转。\r\n# 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。\r\n\r\n\r\nclass Solution:\r\n def reverseStr(self, s: str, k: int) -> str:\r\n # ok:k相加,前面的反转,i+k超出也可以\r\n a =''\r\n i = 0\r\n while i < len(s):\r\n a+=s[i:i + k][::-1]\r\n a+=s[i + k:i + 2 * k]\r\n i += 2 * k\r\n\r\n return a\r\n\r\n#copy\r\n\r\n\r\nclass Solution:\r\n def reverseStr(self, s: str, k: int) -> str:\r\n j = 1\r\n str2 = ''\r\n for i in range(0,len(s),k):\r\n if j == 1:\r\n str2 += s[i:i+k][::-1] #轮流j=1,2,i+k超出也可以\r\n j = 2\r\n elif j==2:\r\n str2 += s[i:i+k]\r\n j = 1\r\n return str2\r\n\r\n#me\r\n\r\nclass Solution:\r\n def reverseStr(self, s: str, k: int) -> str:\r\n #0628 15min\r\n flag=-1\r\n res=''\r\n # if len(s)<=k:return s[::-1] #容易二十年估计\r\n for i in range(0,len(s),k): #可以超出\r\n if flag<0:\r\n res+=s[i:i+k][::-1]\r\n else:\r\n res+=s[i:i+k]\r\n flag*=(-1) #放在后面不然后面失效\r\n\r\n return res\r\n\r\n\r\n ","sub_path":"leetcode_solution/leetcode类别/10字符串/简单/541. 反转字符串 II.py","file_name":"541. 反转字符串 II.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"326241103","text":"import googlemaps\nimport constants\nfrom datetime import datetime\nimport pickle\n\ngmaps = googlemaps.Client(key=constants.GOOGLEROUTESKEY)\n\n# Geocoding an address\n\n\ndef geocode_address(addresstext):\n return gmaps.geocode(addresstext)\n\n# Look up an address with reverse geocoding\n\n\ndef reverse_geocode_result(lat, lon):\n return gmaps.reverse_geocode((lat, lon))\n\n\n# Request directions via public transit\n#now = datetime.now()\n\n\ndef directions_result(addfrom, addto, tmode):\n return gmaps.directions(addfrom,\n addto,\n mode=tmode,\n departure_time=datetime.now())\n\n\n#=========================================\n# Function for getting the nearby clusters\n# Similar to the one explained By Meraldo Antonio in: \n#https://github.com/meraldoantonio/AccidentPredictor/blob/master/CODE/Exploratory%20Data%20Analysis/UK_Accidents_Google_Route_Predict.ipynb\n#=========================================\nfrom math import sin, cos, sqrt, atan2, radians\nkms_per_radian = 6371.0088\n# Dataframe with cluster columns coords as latitude and longitude, and target dataframe \n# Return Cluster -1 as default if no result with weight 0.\ndef getClusters(df_cluster, y ,x,distance, df_eval):\n R=kms_per_radian\n df_eval['Cluster'] = -1\n df_eval['Weight'] = float(0.000000)\n lats = df_eval[y]\n longs = df_eval[x]\n for i in range(0,df_eval.shape[0]):\n for j in range(0,df_cluster.shape[0]):\n cluster_id = int (df_cluster.iloc[[j]]['Cluster'])\n lat1 = radians(float(df_cluster.iloc[[j]][y]))\n lon1 = radians(float(df_cluster.iloc[[j]][x]))\n lat2 = radians(lats[i])\n lon2 = radians(longs[i])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2\n c = 2 * atan2(sqrt(a), sqrt(1 - a))\n\n distance = R * c\n\n if(distance < 0.080):\n print(\"Result: [Cluster \" + str(cluster_id) + \"]: \" + str(distance*1000) + \" m\")\n df_eval.at[i,'Weight']= (df_cluster.iloc[[j]]['Weight'])\n df_eval.at[i,'Cluster']= int(df_cluster.iloc[[j]]['Cluster'])\n return df_eval\n\n\n\n#=========================================\n# Function for predicting severity of accidents \n#=========================================\nRFC_model11 = constants.MODEL\nmodel = pickle.load(open(RFC_model11, 'rb'))\n\ndef predict_severity(values):\n new_params_to_predict = values.reshape(1,9)\n proba_new_values = model.predict_proba(new_params_to_predict)\n return(round(proba_new_values[0][1]*100, 2))","sub_path":"apitransit.py","file_name":"apitransit.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"403917424","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*- \n# Author:aigo\n\nfrom django.apps import AppConfig\n\n\nclass InternshipConfig(AppConfig):\n label = \"internship\"\n name = \"allapps.internship\"\n verbose_name = ('实习')\n\n def ready(self):\n super(InternshipConfig, self).ready()\n from . import receivers\n\n\nSUITE_ID = 3\nSUITE_APP_ID = 12\n\nINTERNSHIP_DEFAULT_CONFIG = {\n \"corporation_type\": \"GaoJi\",\n\n \"student_form_fields\": [\n \"name\",\n \"ethnic_code\",\n \"admission_ticket\",\n \"last_mobile\",\n \"college\",\n \"major\",\n \"grade\",\n \"clazz\",\n \"comment\"\n ],\n\n \"extattr_fields\": {\n \"home_info_fields\": [\n # \"\\u5bb6\\u5ead\\u8054\\u7cfb\\u4eba\",\n # \"\\u5bb6\\u5ead\\u8054\\u7cfb\\u7535\\u8bdd\",\n # \"\\u7d27\\u6025\\u8054\\u7cfb\\u4eba\",\n # \"\\u7d27\\u6025\\u8054\\u7cfb\\u4eba\\u7535\\u8bdd\",\n # \"\\u5bb6\\u5ead\\u5730\\u5740\",\n # \"\\u8be6\\u7ec6\\u5730\\u5740\"\n ],\n \"student_extattr_fields\": [\n \"\\u5b66\\u53f7\",\n \"\\u6bd5\\u4e1a\\u5e74\\u4efd\",\n \"\\u5b66\\u5236\",\n \"\\u751f\\u6e90\\u5730\",\n \"\\u653f\\u6cbb\\u9762\\u8c8c\",\n \"\\u6c11\\u65cf\",\n \"qq\"\n ]\n },\n \"template_menus\": [\n # \"personal_info\",\n # \"ShiXiZhiDao\",\n # \"personal_job_push\",\n # \"my_favorite\"\n ],\n \"feedback_month_dates\": {\n \"default\": [\n [\n 1,\n 14\n ],\n [\n 15,\n 31\n ]\n ]\n },\n \"signin_config\": \"week\",\n\n \"institution_form_fields\": {\n \"institution_student_form_fields\": [\n # \"internship_type\",\n \"name\",\n # \"organizing_institution_bar_code\",\n \"city\",\n \"place\",\n \"starting_date\",\n \"position\",\n \"salary\",\n \"contacts\",\n # \"contact_number\",\n # \"contact_email\",\n \"is_school_recommend\",\n \"school_recommend\"\n ],\n \"institution_teacher_form_fields\": [\n # \"internship_type\",\n \"name\",\n # \"organizing_institution_bar_code\",\n \"city\",\n \"place\",\n \"starting_date\",\n \"position\",\n \"salary\",\n \"verify_status\",\n \"match_status\",\n \"status\",\n # \"graduate_goes\",\n # \"institution_type\",\n # \"institution_industry\",\n # \"behavior_intention\",\n # \"job_type\",\n # \"is_employed_hard\",\n # \"dispatch_nature\",\n # \"concreteness_employment_statistics_institution\",\n # \"concreteness_receive_institution\",\n # \"difficult_student_type\",\n \"contacts\",\n \"contact_number\",\n # \"contact_email\",\n \"is_school_recommend\",\n \"school_recommend\",\n \"comment\"\n ]\n },\n\n \"institution_table_columns\": [\n \"student\",\n \"xibie\",\n \"zhuanye\",\n \"institude\",\n # \"organizing_institution_bar_code\",\n \"position\",\n # \"is_school_recommend\",\n \"edit_institution\",\n \"zydk_status\"\n ],\n\n \"internship_grades\": [3],\n}\n","sub_path":"Documents/backupCode/allapps/internship/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"543891985","text":"# PYTHON 3\n# \n# Author: Kate Willett\n# Created: 1 February 2013, IDL, Converted to Python 3 December 2020\n# Last update: 20 August 2021\n# Location:/home/h04/hadkw/HadISDH_Code/HADISDH_BUILD/\t\n# GitHub: https://github.com/Kate-Willett/HadISDH_Build\t\t\t\t\t\n# -----------------------\n# CODE PURPOSE AND OUTPUT\n# -----------------------\n# For one variable at a time, IN A SET ORDER!!! [T, RH, DPD, q, e, Td, Tw]\n# Read in list of stations passing through PHA/IDPHA\n# MUST HAVE INPUT ADJUSTMENT UNCERTAINTY FOR EACH VARIABLE - find #***MISSEDADJUNC***\n# Loop through each station\n# read in homogenised station (ASCII VERSION OF ABS)\n# Find cases of subzeros (RH, q and e) or supersaturation (RH, DPD, Td and Tw indirectly q, e) and output to list (continue to process)\n# WORKING WITH HOMOGENISED ACTUALS:\n# create station anomalies and climatologies using desired climatology period\n# WORKING WITH HOMOGENISED ANOMALIES:\n# create station actuals from homogenised anomalies and non-homog climatologies (create these from ascii absolutes, could adjust by climatology of adjustments?)\n# List stations with < 15 years present for each month of climatology as BADS - output to list and do not continue to process.\n# Work out measurement uncertainty\n# Work out adjustment uncertainties an dmissed adjustment uncertainty\n# Output to netCDF (with 2 sigma uncertainties!!!)\n# Make stationstats plot of all uncertainties\n\n# This code now also works through all of the wet bulb extremes: Twmax, Twmax95p, Twmean95p, Tw25, Tw27, Tw29, Tw31, Tw33, Tw35\n# - it works with the already processed good list of Tw (PosthomogIDPHAtw_good... so sats and bads are removed.\n# - temporally matches to homogenised Tw as there are periods within a station that will have been removed because no suitable adjustment could be found.\n# - pulls through measurement uncertainty from Tw netCDFs\n# - pulls through adjustments and adjustment uncertainty from Tw netCDFs\n# - pulls through climatology uncertainty from Tw netCDFs\n# - pulls through total uncertainty from Tw netCDFs\n \n# \n# \n# -----------------------\n# LIST OF MODULES\n# -----------------------\n# import numpy as np # used\n# import numpy.ma as npm # used\n# from datetime import datetime # used\n# import matplotlib.pyplot as plt\n# import sys, os, getopt # used\n# import re\n# import struct\n# import glob # used\n# import pdb # used\n# import netCDF4 as nc4\n# from subprocess import call, check_output, run, PIPE # used\n\n# Kate's Functions\n# import CalcHums\n# from RandomsRanges import LetterRange\n# \n# -----------------------\n# DATA\n# -----------------------\n# Input station lists, adjustment log lists\n# /scratch/hadkw/UPDATE/LISTS_DOCS/'\n# goodforHadISDH.'+versiondots+'_'+typee+var+'.txt'\n# HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'.log'\n# PosthomogIDPHArh_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt' CREATED AFTER RH RUN)\n# PosthomogPHAdpd_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt' CREATED AFTER DPD RUN)\n# Input homogenised ascii data\n# /scratch/hadkw/UPDATE/MONTHLIES/HOMOG/ASCII/DIR/' # this will then be PHAASCII or IDPHAASCII\n# _'_'+typee+'adj.txt'\n# Input SLPclims from 20CR in raw station files\n# /scratch/hadkw/UPDATE/MONTHLIES/NETCDF/'\n# StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc'\n# \n# -----------------------\n# HOW TO RUN THE CODE\n# -----------------------\n# Ensure that you have updated the end year, version, clim period etc or switched HardWire = 0 and F1_HadISDHBuildConfig.txt is up to date\n#\n# The variables should be run in a specific order:\n# T IDPHA first because homogenised t_abs are used to:\n# -> estimate uncertainties in RH, q, e, Td and dpd\n# RH IDPHA second because homogenised rh_abs is used to:\n# -> find supersats in q, e\n# -> estimate uncertainties in q, e, Td, and DPD\n# DPD PHA third because PosthomogPHAdpd_anoms8110_sats are used for:\n# -> find supersats in Tw and Td\n# homog Td is made up from homog T - homog DPD anyway\n# q IDPHA fourth because all dependencies are now complete\n# e IDPHA fifth because all dependencies are now complete\n# td PHADPD sixth because all dependencies are now complete\n# tw IDPHA zeventh because all dependencies are now complete\n#\n# > module load scitools/default-current\n# > python F12_CreateHomogNCDFStUnc --var --typee --runtype \n#\n## Which variable?\n# var = 'dpd'\t#'dpd','td','t','tw','e','q','rh'\n#\n## Which homog type?\n# typee = 'PHA'\t#'PHA' (for DPD only),'IDPHA' (for t, e, q, rh and tw),'PHADPD' (for Td) \n#\n## What sort of run?\n# runtype = 'all' # runs all stations within the station list\n# runtype = '00000099999' # restarts from the given station ID then continues through all stations within the station list\n#\n#\n# Or ./F12_submit_spice.sh\n# \n# -----------------------\n# OUTPUT\n# -----------------------\n# Output lists of good, bad, supersaturated and subzero stations\n# /scratch/hadkw/UPDATE/LISTS_DOCS/\n# Posthomog_anoms'+CLMlab+'_HadISDH.'+versiondots+'.txt' \n# Output homogenised netCDF data\n# /scratch/hadkw/UPDATE/MONTHLIES/HOMOG/NETCDF/DIR/' # this will then be PHANETCDF or IDPHANETCDF\n# '_anoms_homog.nc'\n# Output uncertainty plots\n# /scratch/hadkw/UPDATE/MONTHLIES/HOMOG/STAT_PLOTS/UNCPLOTS/DIR/' \n# '_anoms_stationstats.png'\n# Output log info\n# /scratch/hadkw/OutputLogFile'+versiondots+'.txt'\n# \n# -----------------------\n# VERSION/RELEASE NOTES\n# -----------------------\n#\n# Version 6 (20 August 2021)\n# ---------\n# \n# Enhancements\n# Now also outputs all of the Tw extremes: Twmax, Twmax95p, Twmean95p, Tw25, Tw27, Tw29, Tw31, Tw33, Tw35\n# \n# Changes\n# \n# Bug fixes\n# \n#\n# Version 5 (12 January 2021)\n# ---------\n# \n# Enhancements\n# Now only outputs stations that are 'good' or do not have subzeros or supersaturated values. These stations are\n# listed in seperate files with all being in the 'BAD' station list then repeated in the SATS and SUBS files\n# THis doesn't change the final grids but means that we no longer need to faff around pulling out the sats and subs stations\n# \n# Changes\n# This is now python 3 rather than IDL\n# Climatology now calculated where >= 15 years represented for each month, not > 15 - so a few more stations get through.\n# Tw supersats set to when DPD has a supersat (station removed from further processing) so far fewer Tw supersats now found (was Tw > T)\n# Now pulls through monthly standard deviations too\n# Calculates the pseudo e, q, Td with correction to use ice bulb when Twet <= 0 .Twet calculated from T which is set to 5. in case of missing\n# so will result in wet bulb (too high e) in some cases where it should be ice\n# T values only differ due to missed adjustment error\n# RH values only differ due to missed adjustment error\n# DPD values differ due to missed adjustment error AND measurement error which is now lower when pseudoTwet is <= 0 and so the ice bulb calc for e is used\n# q values only differ due to the missed adjustment error\n# e as for q\n# Tw very similar - values only differ due to missed adjustment error. Supersats are now those found from DPD not Tw>T - so far fewer supersats.\n# Td now has own list of sats and bads assessed rather than copied from DPD and T and differs in adj error\n#\n# \n# Bug fixes\n#\n#\n# Version 4 (8 February 2018)\n# ---------\n# \n# Enhancements\n# Now reads in station counts and missed adjustment uncertainty automatically so no updating required.\n# Now runs variable/homogtype from the command line so no updating beyond year required\n### Which variable? T first, RH, DPD, q, e, td, tw\n#param = 'tw'\n## Which homog type?\n#homogtype = 'ID'\t\t#'ID','DPD' for Td, 'PHA' - req for DPD or PHA versions of all variables\n# \n# Changes\n# \n# Bug fixes\n#\n# Version 3 (31 January 2017)\n# ---------\n# \n# Enhancements\n# General tidy up of code and input variable format\n# \n# Changes\n# \n# Bug fixes\n# \n# Version 2 (12 August 2015)\n# ---------\n# \n# Enhancements\n# Improved header\n# Added capacity to output using different climatology period 1981-2010\n# Rearranged file input structure to account for choices of climatolgoy period\n# Tidied up code generally and tried to fix some oddities (changes)\n# \n# Changes\n# NOT SURE WHY BUT FOR UNCERTAINTY IN Td and DPD it tries to read in raw T and station_Pclim but\n# as it was would fail and set statP_arr to standard pressure of 1013. I have changed so that it reads in 20CRstation_Pclim \n# and no raw T (homog T already read in)\n# ALSO - not really sure why DPD has to come first so that it then needs to read in unhomogenised Td - need to go through code again really\n# \n# Bug fixes\n# RH subzeros not listed properly - were added to supersats and labelled as supersats\n# This has resulted in 1 fewer sat and 1 new sub for RH (anoms8110)\n# missed adjustment for e was 0.12 but should have been 0.2!!!\n#\n#\n# Version 1 (15 January 2015)\n# ---------\n# \n# Enhancements\n# \n# Changes\n# \n# Bug fixes\n# \n# -----------------------\n# OTHER INFORMATION\n# -----------------------\n##measurement uncertainty for obs_error:\n# For RH sensors this is approximatly 2% at 10% RH and 2.5% at 98% RH\n# For psychormeters we can assume 0.3 deg C wetbulb depession\n# This scales out as:\n# -50 deg C = 30% 0 deg C = 5.8% RH, 50 deg = 1.2% RH\t- \n# -50 = 30%\n# -40 = 30%\n# -30 = 30%\n# -20 = 20%\n# -10 = 10%\n# 0 = 6%\n# 10 = 4%\n# 20 = 2.5%\n# 30 = 1.8%\n# 40 = 1.4%\n# 50+ = 1.2% \n\n# give all 40-50 1.4%\n# give all 0-10 6% (apply upwards bin)\n# USED Michael de Podesta's spread sheet with eq. (ice and wet) from Buck 1981 (my thesis ch 2)\n# so - read in temperature netcdfs for climatology - scale errors with climatology or raw values?\n# scale with raw - may lead to change over time as temperatures change?\n# - may also lead to biases where adjustments have been made as T is not homog.\n# scale with clim - continuous over time but a little coarse? Although pos and neg should balance out?\n# penalise cold months - but that IS where we're least certain\n# AT GRIDBOX level this could scale with time too - introduce some change to RH sensor uncertainty beginning in 1990s to\n# be almost complete by 2011? Tricky and a bit arbitray - at least doing all using wetbulb uncertainty is a 'worst case'\n\n\n#******************************************************\n# Global variables and imports\n# Inbuilt: (may not all be required actually)\nimport numpy as np # used\nimport numpy.ma as npm # used\nfrom datetime import datetime # used\nimport matplotlib.pyplot as plt\nimport sys, os, getopt # used\nimport re\nimport struct\nimport glob # used\nimport pdb # used\nimport netCDF4 as nc4\n#from netCDF4 import Dataset # used\nfrom subprocess import call, check_output, run, PIPE # used\n\n# Kate's Functions\nimport CalcHums\nfrom RandomsRanges import LetterRange\n\n# Restarter station ID\nRestartValue = '-----------' # '00000099999'\n\n# Start and end years if HardWire = 1\nstyear = 1973\nedyear = 2019\n\n# Dataset version if HardWire = 1\nversiondots = '4.2.0.2019f'\nversion = 'v420_2019f'\nhadisdversiondots = '3.1.0.2019f'\nhadisdversion = 'v310_2019f'\n\n# HARDWIRED SET UP!!!\n# If HardWire = 1 then program reads from the above run choices\n# If HardWire = 0 then program reads in from F1_HadISDHBuildConfig.txt\nHardWire = 0\n\nif (HardWire == 0):\n \n #' Read in the config file to get all of the info\n with open('F1_HadISDHBuildConfig.txt') as f:\n \n ConfigDict = dict(x.rstrip().split('=', 1) for x in f)\n \n versiondots = ConfigDict['VersionDots']\n hadisdversiondots = ConfigDict['HadISDVersionDots']\n styear = ConfigDict['StartYear']\n edyear = ConfigDict['EndYear']\n\n# AttribDict held in memory to probide global attribute text later\n#' Read in the attribute file to get all of the info\nwith open('F1_HadISDHBuildAttributes.txt') as f:\n \n AttribDict = dict(x.rstrip().split('=', 1) for x in f)\n\n# NOT CODED THIS FUNCTIONALITY YET\n## Are we working with homogenised actuals (True) or anomalies (False)?\n#Actuals = True\n\n# Set up directories locations\nupdateyy = str(edyear)[2:4]\nupdateyyyy = str(edyear)\nworkingdir = '/scratch/hadkw/UPDATE'+updateyyyy\n#workingdir = '/data/users/hadkw/WORKING_HADISDH/UPDATE'+updateyyyy\n\n# Set up filenames\nINDIRLIST = workingdir+'/LISTS_DOCS/'\nINDIRHOM = workingdir+'/MONTHLIES/HOMOG/' # this will then be PHAASCII or IDPHAASCII\nINDIRP = workingdir+'/MONTHLIES/NETCDF/'\n\n#workingdir = '/scratch/hadkw/UPDATE'+updateyyyy\nOUTDIRLIST = workingdir+'/LISTS_DOCS/'\nOUTDIRHOM = workingdir+'/MONTHLIES/HOMOG/' # this will then be PHANETCDF or IDPHANETCDF\nOUTDIRPLOTS = workingdir+'/MONTHLIES/HOMOG/STAT_PLOTS/UNCPLOTS/' \n# File for output stats but also for reading in missed adjustment uncertainties\nOUTPUTLOG = workingdir+'/LISTS_DOCS/OutputLogFile'+versiondots+'.txt'\n\n# Set up variables\nMDI = -1e+30\n#*** at some point add all the header info from the new HadISD files***\n\n# Dictionaries for param, units, homogdirprefix, STATION FILE PREFIX, standard name, long name, raw data suffix(only for test run)\nParamDict = dict([('q',['q','g/kg','IDPHA','Q','specific_humidity','monthly mean 2m specific humidity']),\n\t ('rh',['RH','%rh','IDPHA','RH','relative_humidity','monthly mean 2m relative humidity']),\n\t ('t',['T','deg C','IDPHA','T','drybulb_temperature','monthly mean 2m dry bulb temperature']), # Note this needs to be changed to IDPHAMG later\n\t ('td',['Td','deg C','IDPHA','TD','dewpoint_temperature','monthly mean 2m dew point temperature']),\n\t ('tw',['Tw','deg C','IDPHA','TW','wetbulb_temperature','monthly mean 2m wetbulb temperature']),\n\t ('e',['e','hPa','IDPHA','E','vapour_pressure','monthly mean 2m vapour pressure']),\n\t ('dpd',['DPD','deg C','PHA','DPD','dewpoint depression','monthly mean 2m dew point depression']),\n\t ('tw_max',['TwX','deg C','IDPHA','TWMAX','wetbulb_temperature_maximum','monthly maximum 2m wetbulb temperature']), # 'twmx'\n\t ('tw_min',['TwN','deg C','IDPHA','TWMIN','wetbulb_temperature_minimum','monthly minimum 2m wetbulb temperature']), # 'twmx'\n\t ('tw_max_90p',['TwX90p','%','IDPHA','TWMAX90','wetbulb_temperature_max90p','percentage of days per month maximum > 90 percentile maximum 2m wetbulb temperature']), # 'twx90'\n\t ('tw_mean_90p',['TwM90p','%','IDPHA','TWMEAN90','wetbulb_temperature_mean90p','percentage of days per month mean > 90 percentile mean 2m wetbulb temperature']), # 'twm90'\n\t ('tw_mean_10p',['TwM10p','%','IDPHA','TWMEAN10','wetbulb_temperature_mean10p','percentage of days per month mean < 10 percentile mean 2m wetbulb temperature']), # 'twm90'\n\t ('tw_min_10p',['TwN10p','%','IDPHA','TWMIN10','wetbulb_temperature_min10p','percentage of days per month minimum < 10 percentile mean 2m wetbulb temperature']), # 'twm90'\n\t ('tw_max_ex25',['TwX25','%','IDPHA','TWX25','wetbulb_temperature_ex25','percentage of days per month >= 25 deg 2m wetbulb temperature']), # 'tw25'\n\t ('tw_max_ex27',['TwX27','%','IDPHA','TWX27','wetbulb_temperature_ex27','percentage of days per month >= 27 deg 2m wetbulb temperature']), # 'tw27'\n\t ('tw_max_ex29',['TwX29','%','IDPHA','TWX29','wetbulb_temperature_ex29','percentage of days per month >= 29 deg 2m wetbulb temperature']), # 'tw29'\n\t ('tw_max_ex31',['TwX31','%','IDPHA','TWX31','wetbulb_temperature_ex31','percentage of days per month >= 31 deg 2m wetbulb temperature']), # 'tw31'\n\t ('tw_max_ex33',['TwX33','%','IDPHA','TWX33','wetbulb_temperature_ex33','percentage of days per month >= 33 deg 2m wetbulb temperature']), # 'tw33'\n\t ('tw_max_ex35',['TwX35','%','IDPHA','TWX35','wetbulb_temperature_ex35','percentage of days per month >= 35 deg 2m wetbulb temperature']), # 'tw35'\n\t ('tw_max_sw25',['TwXD25','deg C','IDPHA','TWXDD25','wetbulb_temperature_sw25','degrees per month >= 25 deg 2m wetbulb temperature']), # 'tw25'\n\t ('tw_max_sw27',['TwXD27','deg C','IDPHA','TWXDD27','wetbulb_temperature_sw27','degrees per month >= 27 deg 2m wetbulb temperature']), # 'tw27'\n\t ('tw_max_sw29',['TwXD29','deg C','IDPHA','TWXDD29','wetbulb_temperature_sw29','degrees per month >= 29 deg 2m wetbulb temperature']), # 'tw29'\n\t ('tw_max_sw31',['TwXD31','deg C','IDPHA','TWXDD31','wetbulb_temperature_sw31','degrees per month >= 31 deg 2m wetbulb temperature']), # 'tw31'\n\t ('tw_max_sw33',['TwXD33','deg C','IDPHA','TWXDD33','wetbulb_temperature_sw33','degrees per month >= 33 deg 2m wetbulb temperature']), # 'tw33'\n\t ('tw_max_sw35',['TwXD35','deg C','IDPHA','TWXDD35','wetbulb_temperature_sw35','degrees per month >= 35 deg 2m wetbulb temperature']), # 'tw35'\n\t ('t_max',['TX','deg C','IDPHA','TMAX','drybulb_temperature_maximum','monthly maximum 2m drybulb temperature']), # 'twmx'\n\t ('t_min',['TN','deg C','IDPHA','TMIN','drybulb_temperature_minimum','monthly minimum 2m drybulb temperature']), # 'twmx'\n\t ('t_max_90p',['TX90p','%','IDPHA','TMAX90','drybulb_temperature_max90p','percentage of days per month maximum > 90 percentile maximum 2m drybulb temperature']), # 'twx90'\n\t ('t_mean_90p',['TM90p','%','IDPHA','TMEAN90','drybulb_temperature_mean90p','percentage of days per month mean > 90 percentile mean 2m drybulb temperature']), # 'twm90'\n\t ('t_mean_10p',['TM10p','%','IDPHA','TMEAN10','drybulb_temperature_mean10p','percentage of days per month mean < 10 percentile mean 2m drybulb temperature']), # 'twm90'\n\t ('t_min_10p',['TN10p','%','IDPHA','TMIN10','drybulb_temperature_min10p','percentage of days per month minimum < 10 percentile mean 2m drybulb temperature']), # 'twm90'\n\t ('t_max_ex25',['TX25','%','IDPHA','TX25','drybulb_temperature_ex25','percentage of days per month >= 25 deg 2m drybulb temperature']), # 'tw25'\n\t ('t_max_ex30',['TX30','%','IDPHA','TX30','drybulb_temperature_ex30','percentage of days per month >= 30 deg 2m drybulb temperature']), # 'tw27'\n\t ('t_max_ex35',['TX35','%','IDPHA','TX35','drybulb_temperature_ex35','percentage of days per month >= 35 deg 2m drybulb temperature']), # 'tw29'\n\t ('t_max_ex40',['TX40','%','IDPHA','TX40','drybulb_temperature_ex40','percentage of days per month >= 40 deg 2m drybulb temperature']), # 'tw31'\n\t ('t_max_ex45',['TX45','%','IDPHA','TX45','drybulb_temperature_ex45','percentage of days per month >= 45 deg 2m drybulb temperature']), # 'tw33'\n\t ('t_max_ex50',['TX50','%','IDPHA','TX50','drybulb_temperature_ex50','percentage of days per month >= 50 deg 2m drybulb temperature']), # 'tw35'\n\t ('t_all_ex18',['TN18','%','IDPHA','TN18','drybulb_temperature_ex35','percentage of days per month all >= 18 deg 2m drybulb temperature'])]) # 'tw35'\n\nExtremesList = ['tw_max','tw_min','tw_max_90p','tw_mean_90p','tw_mean_10p','tw_min_10p',\n 'tw_max_ex25','tw_max_ex27','tw_max_ex29','tw_max_ex31','tw_max_ex33','tw_max_ex35',\n\t\t'tw_max_sw25','tw_max_sw27','tw_max_sw29','tw_max_sw31','tw_max_sw33','tw_max_sw35',\n\t\t't_max','t_min','t_max_90p','t_mean_90p','t_mean_10p','t_min_10p',\n\t\t't_max_ex25','t_max_ex30','t_max_ex35','t_max_ex40','t_max_ex45','t_max_ex50','t_all_ex18'] # 0:18 for tw (including last value + 1 for referencing, 18: for t extremes\n\t\t\nWetEx = [i for i in ExtremesList if re.search(r'tw_', i)]\nDryEx = [i for i in ExtremesList if re.search(r't_', i)]\n\n#******************************************************\n# SUBROUTINES #\n#******************************************************\n# READDATA\ndef ReadData(FileName,typee,delimee):\n ''' Use numpy genfromtxt reading to read in all rows from a complex array '''\n ''' Need to specify format as it is complex '''\n ''' outputs an array of tuples that in turn need to be subscripted by their names defaults f0...f8 '''\n return np.genfromtxt(FileName, dtype=typee, delimiter=delimee, encoding='latin-1') # ReadData\n# return np.genfromtxt(FileName, dtype=typee, delimiter=delimee) # ReadData\n\n#****************************************************\n# MakeDaysSince\ndef MakeDaysSince(TheStYr,TheStMon,TheEdYr,TheEdMon):\n ''' Take counts of months since styr, stmn (assume 15th day of month) '''\n ''' Work out counts of days since styr,stmn, January - incl leap days '''\n ''' Also work out time boundaries 1st and last day of month '''\n ''' This can cope with incomplete years or individual months '''\n \n # set up arrays for month month bounds\n BoundsArray = np.empty((((TheEdYr-TheStYr)+1)*((TheEdMon-TheStMon)+1),2))\n \n # make a date object for each time point and subtract start date\n StartDate = datetime(TheStYr,TheStMon,1,0,0,0)\t# January\n \n DaysArray = list(np.array([[(datetime(j,i,1,0,0,0)-StartDate).days + 15 for i in np.arange(1,13)] for j in np.arange(TheStYr,TheEdYr+1)]).flat)\n BoundsArray[:,0] = list(np.array([[(datetime(j,i,1,0,0,0)-StartDate).days for i in np.arange(1,13)] for j in np.arange(TheStYr,TheEdYr+1)]).flat)\n BoundsArray[:,1] = np.append(BoundsArray[1:,0]-1,(datetime(TheEdYr,TheEdMon,31,23,59,59)-StartDate).days)\n \n return DaysArray,BoundsArray\n\n#**************************************************************************************\n# WriteNetCDF\ndef WriteNetCDF(FileName,TheStYr,TheEdYr,TheClims,TheDataList,DimObject,AttrObject,GlobAttrObject,TheMDI):\n ''' WRites NetCDF4 '''\n ''' Sort out the date/times to write out and time bounds '''\n ''' Write to file, set up given dimensions, looping through all potential variables and their attributes, and then the provided dictionary of global attributes '''\n\n# # Attributes and things common to all vars\n# add_offset = -100.0 # storedval=int((var-offset)/scale)\n# scale_factor = 0.01\n \n # Sort out date/times to write out\n TimPoints,TimBounds = MakeDaysSince(int(TheStYr),1,int(TheEdYr),12)\n nTims = len(TimPoints)\n MonthName = ['January ',\n 'February ',\n\t 'March ',\n\t 'April ',\n\t 'May ',\n\t 'June ',\n\t 'July ',\n\t 'August ',\n\t 'September ',\n\t 'October ',\n\t 'November ',\n\t 'December ']\n\t\n # Create a new netCDF file - have tried zlib=True,least_significant_digit=3 (and 1) - no difference\n ncfw = nc4.Dataset(FileName,'w',format='NETCDF4_CLASSIC') # need to try NETCDF4 and also play with compression but test this first\n \n # Write out the global attributes\n if ('description' in GlobAttrObject):\n ncfw.description = GlobAttrObject['description']\n\t#print(GlobAttrObject['description'])\n\t\n if ('File_created' in GlobAttrObject):\n ncfw.File_created = GlobAttrObject['File_created']\n\n if ('Title' in GlobAttrObject):\n ncfw.Title = GlobAttrObject['Title']\n\n if ('Institution' in GlobAttrObject):\n ncfw.Institution = GlobAttrObject['Institution']\n\n if ('History' in GlobAttrObject):\n ncfw.History = GlobAttrObject['History']\n\n if ('Licence' in GlobAttrObject):\n ncfw.Licence = GlobAttrObject['Licence']\n\n if ('Project' in GlobAttrObject):\n ncfw.Project = GlobAttrObject['Project']\n\n if ('Processing_level' in GlobAttrObject):\n ncfw.Processing_level = GlobAttrObject['Processing_level']\n\n if ('Acknowledgement' in GlobAttrObject):\n ncfw.Acknowledgement = GlobAttrObject['Acknowledgement']\n\n if ('Source' in GlobAttrObject):\n ncfw.Source = GlobAttrObject['Source']\n\n if ('Comment' in GlobAttrObject):\n ncfw.Comment = GlobAttrObject['Comment']\n\n if ('References' in GlobAttrObject):\n ncfw.References = GlobAttrObject['References']\n\n if ('Creator_name' in GlobAttrObject):\n ncfw.Creator_name = GlobAttrObject['Creator_name']\n\n if ('Creator_email' in GlobAttrObject):\n ncfw.Creator_email = GlobAttrObject['Creator_email']\n\n if ('Version' in GlobAttrObject):\n ncfw.Version = GlobAttrObject['Version']\n\n if ('doi' in GlobAttrObject):\n ncfw.doi = GlobAttrObject['doi']\n\n if ('Conventions' in GlobAttrObject):\n ncfw.Conventions = GlobAttrObject['Conventions']\n\n if ('netcdf_type' in GlobAttrObject):\n ncfw.netcdf_type = GlobAttrObject['netcdf_type']\n\t\n # Loop through and set up the dimension names and quantities\n for vv in range(len(DimObject[0])):\n ncfw.createDimension(DimObject[0][vv],DimObject[1][vv])\n\t\n # Go through each dimension and set up the variable and attributes for that dimension if needed\n for vv in range(len(DimObject)-2): # ignore first two elements of the list but count all other dictionaries\n# print(DimObject[vv+2]['var_name'])\n\t\n\t# NOt 100% sure this works in a loop with overwriting\n\t# initiate variable with name, type and dimensions\n MyVar = ncfw.createVariable(DimObject[vv+2]['var_name'],DimObject[vv+2]['var_type'],DimObject[vv+2]['var_dims'])\n \n\t# Apply any other attributes\n if ('standard_name' in DimObject[vv+2]):\n MyVar.standard_name = DimObject[vv+2]['standard_name']\n\t \n if ('long_name' in DimObject[vv+2]):\n MyVar.long_name = DimObject[vv+2]['long_name']\n\t \n if ('units' in DimObject[vv+2]):\n MyVar.units = DimObject[vv+2]['units']\n\t\t \t \n if ('axis' in DimObject[vv+2]):\n MyVar.axis = DimObject[vv+2]['axis']\n\n if ('calendar' in DimObject[vv+2]):\n MyVar.calendar = DimObject[vv+2]['calendar']\n\n if ('start_year' in DimObject[vv+2]):\n MyVar.start_year = DimObject[vv+2]['start_year']\n\n if ('end_year' in DimObject[vv+2]):\n MyVar.end_year = DimObject[vv+2]['end_year']\n\n if ('start_month' in DimObject[vv+2]):\n MyVar.start_month = DimObject[vv+2]['start_month']\n\n if ('end_month' in DimObject[vv+2]):\n MyVar.end_month = DimObject[vv+2]['end_month']\n\n if ('bounds' in DimObject[vv+2]):\n MyVar.bounds = DimObject[vv+2]['bounds']\n\t\n\t# Provide the data to the variable\n if (DimObject[vv+2]['var_name'] == 'time'):\n MyVar[:] = TimPoints\n\n if (DimObject[vv+2]['var_name'] == 'bounds_time'):\n MyVar[:,:] = TimBounds\n\n if (DimObject[vv+2]['var_name'] == 'month'):\n# pdb.set_trace()\n# MyVar[mm,:] = [nc4.stringtochar(np.array(MonthName[mm],dtype='S10')) for mm in np.arange(1,13)] \n MyVar[:,:] = [[MonthName[mm][cc] for cc in range(10)] for mm in range(12)] \n\n # Go through each variable and set up the variable attributes\n for vv in range(len(AttrObject)): # ignore first two elements of the list but count all other dictionaries\n\n# print(AttrObject[vv]['var_name'])\n\n # initiate variable with name, type and dimensions\n MyVar = ncfw.createVariable(AttrObject[vv]['var_name'],AttrObject[vv]['var_type'],AttrObject[vv]['var_dims'],fill_value = TheMDI)\n \n\t# Apply any other attributes\n if ('long_name' in AttrObject[vv]):\n MyVar.long_name = AttrObject[vv]['long_name']\n\t \n if ('units' in AttrObject[vv]):\n MyVar.units = AttrObject[vv]['units']\n\n# MyVar.add_offset = add_offset\n# MyVar.scale_factor = scale_factor\n\n MyVar.reference_period = str(TheClims[0])+', '+str(TheClims[1])\n\n\t# Provide the data to the variable - depending on howmany dimensions there are\n\t## First change masked array to normal array filled with MDI\n #TheDataList[vv][TheDataList[vv].mask] = TheMDI\n MyVar[:] = TheDataList[vv].filled()\n\t \n ncfw.close()\n \n return # WriteNCCF\n\n#*******************************************************\n# MAIN #\n#*******************************************************\ndef main(argv):\n\n # INPUT PARAMETERS AS STRINGS!!!!\n var = 'q'\t # 'q','rh','e','td','tw','t','dpd'\n typee = 'IDPHA' # 'PHA','IDPHA','PHADPD'\n runtype = 'all' # 'all','00000099999'\n\n try:\n opts, args = getopt.getopt(argv, \"hi:\",\n\t [\"var=\",\"typee=\",\"runtype=\"])\n except getopt.GetoptError:\n print('Usage (as strings) F12_CreateHomogNCDFStUnc.py --var --typee --runtype ')\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == \"--var\":\n try:\n var = arg\n except:\n sys.exit(\"Failed: var not a string\")\n elif opt == \"--typee\":\n try:\n typee = arg\n except:\n sys.exit(\"Failed: typee not a string\")\n elif opt == \"--runtype\":\n try:\n runtype = arg\n except:\n sys.exit(\"Failed: typee not a string\")\n \n# assert var != '' and typee != '', \"Input values not specified.\"\n\n print(var,typee,runtype)\n \n # Check to see if we're starting from the beginning?\n if (RestartValue == '-----------') & (runtype != 'all'):\n \n # Restarter set from run command line variables\n RestartID = runtype \n\n else:\n \n RestartID = RestartValue\n\t\n # Which climatology?\n MYclst = 1991\t# 1976, 1981\n MYcled = 2020\t# 2005, 2010\n CLMlab = str(MYclst)[2:4]+str(MYcled)[2:4]\n\n#*******************************************************\n # variable specific filepaths and directories\n # homogenised data file suffix\n DatSuffix = '_anoms'+CLMlab+'_homog.nc'\n\n # Needs to be IDPHAMG for T for the log of adjustments and MissedAdjErr\n homogtype = typee\n if (var == 't'):\n homogtype = 'IDPHAMG'\n\n # Set up files for read in and write out\n \n InList = INDIRLIST+'goodforHadISDH.'+versiondots+'_'+typee+var+'.txt'\n \n InHom = INDIRHOM+ParamDict[var][2]+'ASCII/'+ParamDict[var][3]+'DIR/'\t #***\n # Diretories to read in homog T and RH for finding measurement uncertainty\n InHomT = INDIRHOM+'IDPHAASCII/TDIR/'\t #***\n InHomRH = INDIRHOM+'IDPHAASCII/RHDIR/'\t #***\n # Note that homogtype is set to IDPHAMG for T (see above)\n# InLog = INDIRLIST+'HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'_JAN2020.log' #***\n InLog = INDIRLIST+'HadISDH.land'+ParamDict[var][0]+'.'+versiondots+'_'+homogtype+'.log' #***\n \n OutList = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_goodsHadISDH.'+versiondots+'.txt'\n OutFunniesT = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutFunniesZ = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_subzerosHadISDH.'+versiondots+'.txt'\n INRHSATS = OUTDIRLIST+'PosthomogIDPHArh_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n INDPDSATS = OUTDIRLIST+'PosthomogPHAdpd_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutBads = OUTDIRLIST+'Posthomog'+typee+var+'_anoms'+CLMlab+'_badsHadISDH.'+versiondots+'.txt'\n\n #OutDat = OUTDIRHOM+typee+'NETCDF/'+ParamDict[var][3]+'DIR/'\n # I think this works for Td and DPD so not need to Td special case loop below (Td read and write from to IDPHAASCII IDPHANETCDF...\n OutDat = OUTDIRHOM+ParamDict[var][2]+'NETCDF/'+ParamDict[var][3]+'DIR/'\n OutPlots = OUTDIRPLOTS+ParamDict[var][3]+'DIR/'\n\n homsuffix = '_'+typee+'adj.txt'\n # Special case for Td \n if (typee == 'PHADPD'):\n\n homsuffix = '_PHAadj.txt'\n# OutDat = OUTDIRHOM+'IDPHANETCDF/'+ParamDict[var][3]+'DIR/'\n# # I'm not copying over from DPD anymote\n\n # THis sets up the station lists to search from - in the end there should be identical stations going into the\n # Tw and T extremes datasets, so some T stations will have been removed unnecessarily because they fail for Tw\n # Tw sats/subs/bads are used as outputs even though they may not quite match up because this covers the main source\n # station removal.\n if (var in ExtremesList):\n InListTw = INDIRLIST+'PosthomogIDPHAtw_anoms'+CLMlab+'_goodsHadISDH.'+versiondots+'.txt'\n InListT = INDIRLIST+'PosthomogIDPHAt_anoms'+CLMlab+'_goodsHadISDH.'+versiondots+'.txt'\n InCheckExList = INDIRLIST+'goodforHadISDHEx.'+versiondots+'.txt'\n rawsuffix = '_hummonthQC.nc' \n # Note that these are only used for reporting how many subs/sats/bads there are but it doesn't completely\n # match up as some tw stations won't be included as tw extreme stations anyway. \n OutFunniesT = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_satsHadISDH.'+versiondots+'.txt'\n OutFunniesZ = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_subzerosHadISDH.'+versiondots+'.txt'\n OutBads = OUTDIRLIST+'Posthomog'+typee+'tw_anoms'+CLMlab+'_badsHadISDH.'+versiondots+'.txt'\n\n # A tweak if its a tw extreme:\n if (var in WetEx):\n InHom = INDIRHOM+'IDPHANETCDF/TWDIR/'\t #***\n InRaw = INDIRP\t #***\n # A tweak if its a t extreme:\n if (var in DryEx):\n InHom = INDIRHOM+'IDPHANETCDF/TDIR/'\t #***\n InRaw = INDIRP\t #***\n\n#--------------------------------------------------------\n # other variables and arrays \n clst = MYclst - int(styear)\n cled = MYcled - int(styear)\n nyrs = (int(edyear) + 1) - int(styear)\n nmons = nyrs * 12\n # Save netCDF file as days since 01-01-1973 DD-MM-YYYY\n\n # UNCERTAINTIES IN MEASUREMENT\n RHBins = [-100,-40,-30,-20,-10,0,10,20,30,40,50,100]\t# degrees C\n\n # 1 sigma (THIS IS LATER *2 TO PROVIDE 2 SIGMA UNCS)\n RHUnc = [15,15,15,10,5,2.75,1.8,1.35,1.1,0.95,0.8] \n t_unc = 0.2\n tw_unc = 0.15\n\n # Missed Adjustment Uncertainty if its NOT an extreme:\n if (var not in ExtremesList):\n\n # Find the missed adjustment uncertainty from the Adjs_Stats file for variable and homogtype\n moo = check_output(['grep','-a','^'+var+'_'+homogtype+'_STD_GAUSSDIFFS=',OUTPUTLOG])\n # Now sort out this string which is a byte array, remove newline and split\n moo = moo.decode(\"utf-8\").strip('\\n').split('=')\t\n # print('Check read in of missed adjustment')\n # pdb.set_trace()\n \n MissedAdjErr = float(moo[1]) # THIS IS 1 SIGMA AND LATER * 2 TO PROVIDE 2 SIGMA UNCS\n \n#*************************************************************\n# Work through station by station\n#*************************************************************\n \n # Open and read in station list \n # A tweak if its an extreme:\n if (var not in ExtremesList):\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\",\"|U13\")\n MyDelimiters = [11,8,10,7,1,2,1,29,13]\n RawData = ReadData(InList,MyTypes,MyDelimiters)\n StationListID = np.array(RawData['f0'])\n StationListLat = np.array(RawData['f1'])\n StationListLon = np.array(RawData['f2'])\n StationListElev = np.array(RawData['f3'])\n StationListCID = np.array(RawData['f5'])\n StationListName = np.array(RawData['f7'])\n\n else:\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\")\n MyDelimiters = [11,9,10,7,1,2,1,29]\n RawDataT = ReadData(InListT,MyTypes,MyDelimiters)\n RawDataTw = ReadData(InListTw,MyTypes,MyDelimiters)\n MyTypes = (\"|U11\",\"float\",\"float\",\"float\",\"|U1\",\"|U2\",\"|U1\",\"|U29\",\"|U13\")\n MyDelimiters = [11,8,10,7,1,2,1,29,13]\n CheckData = ReadData(InCheckExList,MyTypes,MyDelimiters)\n # Asuuming both station lists are unique and sorted (ok for numerical station IDs but check alphanumerics?) locate the stations that are common to \n\t# both the good extremes and t or tw passing PHA lists\n CommonStations, MapToRaw, MapToCheck = np.intersect1d(np.array(RawDataT['f0']),np.array(CheckData['f0']),assume_unique=True,return_indices=True)\n\n TempStationListID = np.array(RawDataT['f0'])[MapToRaw]\n\n CommonStations, MapToRaw, MapToCheck = np.intersect1d(np.array(RawDataTw['f0']),TempStationListID,assume_unique=True,return_indices=True)\n\n StationListID = np.array(RawDataTw['f0'])[MapToRaw]\n StationListLat = np.array(RawDataTw['f1'])[MapToRaw]\n StationListLon = np.array(RawDataTw['f2'])[MapToRaw]\n StationListElev = np.array(RawDataTw['f3'])[MapToRaw]\n StationListCID = np.array(RawDataTw['f5'])[MapToRaw]\n StationListName = np.array(RawDataTw['f7'])[MapToRaw]\n \n# print('Test to see if station read in has worked correctly')\n# # Yes this works as expected\n# pdb.set_trace()\n \n nstations = len(StationListID)\n\n # loop through station by station\n for st in range(nstations):\n\n # check if restart necessary\n if RestartID != '-----------' and RestartID != StationListID[st]:\n continue\n\n RestartID = '-----------'\n \n # find homog file for selected variable and read in to array \n # A tweak if its a Tw extreme:\n if (var not in ExtremesList):\n InFile = InHom+StationListID[st]+homsuffix\n MyTypes = np.append(\"|U12\",[\"int\"]*13)\n MyDelimiters = np.append([12,4,6],[7]*11)\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n \n stat_abs = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_abs = npm.append(stat_abs,np.copy(npm.array(moo[2:14])/100.)) \n\n # If its tw extremes then we're reading in from netCDF and MDI is already -1e30\n else:\n ncf = nc4.Dataset(InRaw+StationListID[st][0:6]+'-'+StationListID[st][6:11]+rawsuffix,'r')\n stat_abs = npm.array(ncf.variables[var][:]) # do we need to release the pointer?\n # Convert to float - important for days exceedance variables\n stat_abs = stat_abs.astype(float)\n ncf.close()\n\n #print('Check file read in: ',StationListID[st])\n #pdb.set_trace() \n \n # Initiate other masked arrays\n stat_anoms = npm.repeat(MDI,nmons)\n stat_sds = npm.repeat(MDI,nmons) # to be filled at end\n stat_clims = npm.repeat(MDI,12)\n stat_clim_sds = npm.repeat(MDI,12)\n stat_adjs = npm.repeat(0.,nmons)\n stat_adjs_err = npm.repeat(0.,nmons)\n stat_clims_err = npm.repeat(MDI,nmons)\n stat_obs_err = npm.repeat(MDI,nmons)\n station_err = npm.repeat(MDI,nmons)\n\n # Use masked arrays so set the old MDI which is now -99.99 to the new MDI which is -1e30 then convert to masked - a double check on floating point imprecision for netCDF files (tw extremes)\n stat_abs[stat_abs <= -99.99] = MDI\n stat_abs = npm.masked_equal(stat_abs, MDI) # should not fall over if there are no missing values\n #print('Check masking of stat_abs array and Tw extremes exceedance MDI float/ints')\n #pdb.set_trace()\n\t \n#*******************************************************************************\n# Find subzeros and supersats (if relevant to variable), output to releavnt lists and then move on to next station\n#*******************************************************************************\n \n\t# DO NOT PROCESS THE STATION ANY FURTHER AS ITS NOW CONSIDERED A BAD!!!\n # No relevance for T\n # subsats - RH, q, e should not be less than zero \n # supersats - RH should not be greater than 100\n # DPD should not be less than zero (derived Td then fine)\n # Td should not be greater than T - using same listing as for DPD\n # Tw should not be greater than T\n\t# COULD TRANSFER PROBLEMS IN RH or DPD TO ALL VARIABLES\n # FIND HOMOGENISED FILE IF IT EXISTS\n \n # No need to look for subs and sats if its T or its an extreme [already removed tw extremes ones as we're using PosthomogIDPHAtw_goodslist]\n if (var not in ExtremesList): \n\t \n GotSats = False\n GotSubs = False\n\t \n # for rh sats where RH > 100. and subs where RH < 0.\n if (var == 'rh'):\n\t \n if (len(np.where(stat_abs.compressed() > 100.)[0]) > 0):\n\t\t#if (len(stat_abs[(stat_abs > MDI) & (stat_abs > 100.)]) > 0):\n\n print('Found supersats!')\n #GotSats = len(stat_abs[(stat_abs > MDI) & (stat_abs > 100.)])\n GotSats = len(np.where(stat_abs.compressed() > 100.)[0])\n\t\t \t\t\n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found subzeros!')\n GotSubs = len(np.where(stat_abs.compressed() < 0.)[0])\n #GotSubs = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)])\n\t \t\n\t # For dpd sats where dpd < 0\n elif (var == 'dpd'):\t\n \n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found supersats!')\n GotSats = len(np.where(stat_abs.compressed() < 0.)[0])\n #GotSats = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)])\n\t \t\t\n\t # for q or e subs if q or e < 0 and if RH station listed as sat\n elif (var == 'q') or (var == 'e'):\n\n if (len(np.where(stat_abs.compressed() < 0.)[0]) > 0):\n #if (len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) > 0):\n\n print('Found subzeros!')\n GotSubs = len(np.where(stat_abs.compressed() < 0.)[0]) \t\n #GotSubs = len(stat_abs[(stat_abs > MDI) & (stat_abs < 0.)]) \t\n\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INRHSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'RH supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\n\t \t\n # for td sats if DPD station listed as sat\n elif (var == 'td'):\n\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INDPDSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'DPD supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\n\t \n\t # for tw sats if tw > t so need to read in t or just use dpd? Tw is very sensitive to this so it kicks out A LOT of stations\n elif (var == 'tw'):\t\n\t\n # Look for the station string in the RH list? - NOTE CHECK_OUTPUT WILL FAIL IF IT CAN@T FIND ANYTHING\n moo = run(['grep','-a','^'+StationListID[st],INDPDSATS],stdout=PIPE)\n if (moo.returncode == 0): # then we've found the station\n \n print('Found supersats!')\n GotSats = 'DPD supersats found '+moo.stdout.decode('utf-8').split()[1]\n# pdb.set_trace()\t \n\n # If we've got a supersat - write out station to list of supersats\n if (GotSats):\n filee = open(OutFunniesT,'a+')\n filee.write('%s %s\\n' % (StationListID[st],GotSats))\n filee.close()\n\t # Do we need to list as bads too?\n filee = open(OutBads,'a+')\n filee.write('%s %s\\n' % (StationListID[st], 'Supersaturation found'))\n filee.close()\n\n # If we've got a subzero - write out station to list of subzeros\n if (GotSubs):\n filee = open(OutFunniesZ,'a+')\n filee.write('%s %s\\n' % (StationListID[st],GotSubs))\n filee.close()\n\t # Do we need to list as bads too?\n filee = open(OutBads,'a+')\n filee.write('%s %s\\n' % (StationListID[st], 'Subzero found'))\n filee.close()\n\n # Now stop processing this station if we've found a sat or sub\n if (GotSats) or (GotSubs):\n print('Stopping processing station: ',StationListID[st])\n continue\t \n\t \n#******************************************************************\n# create station anomalies and climatologies from homogenised abs\n#******************************************************************\n\n # NOTE: we can do this for the Tw extremes but its not entirely logical or useful I think\n # ALSO: we don't want exceedance days failing because there aren't enough days to calculate a climatology\n # As we're working with masked arrays nothing should in theory break I think - does it fill with MDI if a value cannot be calculated? CHECK!!!\n \n\t# reshape the array to be a row for each year\n stat_abs = np.reshape(stat_abs,(nyrs,12)) \n # subset the values to just the climatology period\n subclm = stat_abs[clst:cled+1,:] \n \n\t# For non-extremes only, because extremes are already selected from t and tw passing this criteria\n\t# Are there enough years (>= 15) for each month? There must be a climatology value for each month to continue processing station\n if (var not in ExtremesList) & (npm.sum(npm.count(subclm,0) >= 15) < 12): # counts for each valid month over the 30 year period, sums these counts and enters loop if at least 1 count is less than 15\n\n # No there are not for at least one month so write out to bad station file and cease processeing\n print('At least one month has too few values to calculate a climatology')\n filee = open(OutBads,'a+')\n filee.write('%s %s %i\\n' % (StationListID[st], 'Too few months for a climatology', np.sum(npm.count(subclm,0) >= 15)))\n filee.close()\n #pdb.set_trace()\n continue\n\t \t\n\t# Calculate climatology, climatological standard deviation and anomalies\n stat_clims = npm.mean(subclm,0) # compute the mean over each 30 year slice for each month, ignoring missing data \n # Note that np.std assumes we're calculating st dev from whole population where as IDL assumes sample of population so deg_of_freedom = n-1\n\t# To match with previous IDL code, and because very often we have missing data, set ddof = 1 to use n-1\n stat_clim_sds = npm.std(subclm,0,ddof=1) # compute the stdeviation over each 30 year slice for each month, ignoring missing data \n stat_anoms = stat_abs - stat_clims # this substracts the right month clim from the right month actual, ignoring missing data\n\n #print('Check whether the masked arrays are working on sparse extremes data')\n #pdb.set_trace()\n\n#**# CALCULATE CLIMATOLOGY UNCERTAINTY - ***2-SIGMA*** \n # For extremes - import climatology uncertainty from Tw or T \n # At this point, for extremes, also mask in the missing data from the homogenised anomalies - removing periods of known \n # inhomogeneity that couldn't be adjusted for - and have no adjustment information with which to QC the data\n if (var not in ExtremesList): \n stat_clims_err = np.tile((stat_clim_sds / np.sqrt(npm.count(subclm,0))) * 2, [nyrs,1])\n # Mask the uncertainty array with the same missing values\n stat_clims_err[stat_abs.mask] = MDI\n stat_clims_err = npm.masked_equal(stat_clims_err, MDI) # should not fall over if there are no missing values\n stat_clims_err = np.reshape(stat_clims_err, 12 * nyrs)\n # Reshape the arrays ready to write to file\n stat_abs = np.reshape(stat_abs, 12 * nyrs)\n stat_anoms = np.reshape(stat_anoms, 12 * nyrs)\n\n else:\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n if (var in WetEx):\n stat_clims_err = npm.array(ncf.variables['tw_climerr'][:]) # do we need to release the pointer?\n AnomMask = npm.array(ncf.variables['tw_anoms'][:]) \n elif (var in DryEx):\n stat_clims_err = npm.array(ncf.variables['t_climerr'][:]) # do we need to release the pointer?\n AnomMask = npm.array(ncf.variables['t_anoms'][:]) \n ncf.close()\n\n stat_clims_err[stat_clims_err <= -99.99] = MDI\n stat_clims_err = npm.masked_equal(stat_clims_err, MDI) # should not fall over if there are no missing values\n # Reshape the arrays ready to write to file\n stat_abs = np.reshape(stat_abs, 12 * nyrs)\n stat_anoms = np.reshape(stat_anoms, 12 * nyrs)\n stat_abs[AnomMask <= -99.99] = MDI\n stat_anoms[AnomMask <= -99.99] = MDI\n #stat_sds set later to tw_sds or t_sds which is then masked\n\n #print('Completed anomalies and climatology error - check')\n #pdb.set_trace()\n\t\n#********************************************************************\t\n# Work out the relative measurement uncertainty - ***2 SIGMA***\n#********************************************************************\n \n\t# Find right variable to process\n if (var == 't'):\n\t\n # Easy for T - +/- 0.2 deg - this is 1 sigma so multiply by 2\n stat_obs_err[:] = (t_unc / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var == 'tw'):\n\t\n # Easy for Tw - +/- 0.15 deg - this is 1 sigma so multiply by 2 - WET BULB ERROR pre 1980 (mostly)\n # 15%rh at -50 deg C T, 0.8 %rh at 50 deg C T\n # scale all error based on %rh at T\n stat_obs_err[:] = (tw_unc / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var == 'rh'):\n\t\n # FOR RH - easy - bin from -50 to 50 deg C and apply table of %rh errors based on 0.15 deg C error in Tw - multiply by 2 to give 2 sigma unc\n\t # If T file exists then read in T_abs homogenise\n if (len(glob.glob(InHomT+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomT+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absT = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absT = npm.append(stat_absT,np.copy(npm.array(moo[2:14])/100.)) \n\n # Set all missing values to 5. degrees which will map to a 2.75% RH uncertainty (>= 0. and < 10. deg) - may be months where T was removed by PHA so still present in RH\n stat_absT[stat_absT == -99.99] = 5. \n\n # Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute uncertainty\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (RHUnc[b] / np.sqrt(60.)) * 2. # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the RH unc aligns with T bins')\n# pdb.set_trace()\n\t\t \n\t # No T file exists - # NO TEMPERATURE DATA SO ASSUME MODERATE UNCERTAINTY OF 3%\n else:\n\t \n stat_obs_err[:] = (2.75 / np.sqrt(60.)) * 2 \t# minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \n\n elif (var in ['q', 'e', 'td', 'dpd']): # var is q, e, td or dpd\n\t\n # FOR q or e or Td: (ASSUME RH=80% IF NO RH FILE/OB EXISTS, and 2.75%rh uncertainty IF NO TEMPERATURE FILE/OB EXIST - set T = 5. to get that [>=0.<10 deg]) - *2 to get 2sigma\n\t # If T file exists then read in T_abs homogenise\n if (len(glob.glob(InHomT+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomT+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absT = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absT = npm.append(stat_absT,np.copy(np.array(moo[2:14])/100.)) \n\n # Set all missing values to 0 degrees which will map to a 3% RH uncertainty - may be months where T was removed by PHA so still present in RH\n stat_absT[stat_absT == -99.99] = 5. \n\t\t \n # If no T file then set T values to 0. degrees\n else:\n\n stat_absT = npm.repeat(5.,nmons)\n\t\t \n\t # If RH file exists then read in RH_abs homogenise\n if (len(glob.glob(InHomRH+StationListID[st]+'_IDPHAadj.txt')) == 1):\n \n InFile = InHomRH+StationListID[st]+'_IDPHAadj.txt'\n RawData = ReadData(InFile,MyTypes,MyDelimiters)\n stat_absRH = npm.array(()) # initiate empty masked array to append to\n for yy in range(nyrs):\n \n moo = list(RawData[yy])\n stat_absRH = npm.append(stat_absRH,np.copy(npm.array(moo[2:14])/100.)) \n\n # Set all missing values to 80. %rh - may be months where RH was removed by PHA so still present in q\n stat_absRH[stat_absRH == -99.99] = 80. \n\t\t \n # If no RH file then set RH values to 80. %rh\n else:\n\n stat_absRH = npm.repeat(80.,nmons)\n\t\t \n # Get uncertainty for q or e\n # qsat=(q/RH)*100\n # q+err=((RH+err)/100)*qsat\n # qerr=(q+err)-q\n if ((var == 'q') or (var == 'e')):\n \t \n\t\t# Set up a pseudo qsat or esat masked array\n sat_array = (stat_abs / stat_absRH) * 100.\n\t # Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute uncertainty\n\t\t # straight RHUnc not /sqrt(60.) because we're pretending this is an individual ob\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (((((stat_absRH[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] + RHUnc[b]) / 100.) \\\n\t\t * sat_array[(stat_absT >= binn) & (stat_absT < RHBins[b+1])]) \\\n\t\t\t\t\t\t\t\t\t\t - stat_abs[(stat_absT >= binn) & (stat_absT < RHBins[b+1])]) / npm.sqrt(60.)) * 2.\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the q / e unc aligns with RH and T bins - masking of stat_abs???')\n# pdb.set_trace()\n\t\t\n\t # If its Td or DPD then\n # FOR Td: use error in e. (ASSUME RH=80% IF NO RH FILE/OB EXISTS, and 2.75%rh uncertainty IF NO TEMPERATURE FILE/OB EXIST)\n # e=e(Td)\n # esat=(e/RH)*100\n # e+err=((RH+err)/100)*esat\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n else:\n\n # Need to read in station P from 20CR - that's a pain! - its in the raw station netCDF files\n if (len(glob.glob(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc')) == 1):\n \n ncf = nc4.Dataset(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc','r')\n # Climatological station level P from 20CR - repeated for each year giving an nmons array\n P_arr = npm.array(ncf.variables['20CRstation_Pclim'][:]) # do we need to release the pointer?\n ncf.close()\n# print('Read in Station P - check')\n# pdb.set_trace()\n\n # If the station file doesn't exist then assume standard P of 1013\n else:\n\n P_arr = npm.repeat(1013.,nmons)\t\t\n\n # Now compute the uncertainty in Td\n\t\t# Set up a pseudo esat masked array - \n if (var == 'td'):\n\n\t\t # We're working with Td so calculating e fairly easy\t\t\n\t\t # we can use T so that the ice bulb equation can be used - if T is set to 5. when it should be < 0. then its going to be wrong\n\t\t # Using wet bulb instead of ice bulb will give slightly higher values of e \n # Calculate esat\n sat_array = (CalcHums.vap(stat_abs, stat_absT, P_arr,roundit=False) / stat_absRH) * 100.\n\n else: \n\t\n\t\t # we're working with DPD so must get Td from T-DPD\n\t\t # Problem when we have set T to 5. and DPD exists because Td could be very wrong - VERY LOW or possibly too high for cold stations/months - can't do much about this\n # For consistency (its all wrong anyway) we use T here too to choose ice or wet bulb calc\n # Calculate esat\n sat_array = (CalcHums.vap((stat_absT-stat_abs), stat_absT, P_arr,roundit=False) / stat_absRH) * 100.\n\t\t\n\t\t# Loop through RH bins start to penultimate bin\n for b,binn in enumerate(RHBins[:-1]):\n\t\t\n # Set T to the RH Uncertainty for the associated level of T in RHBins and compute e+err\n\t\t # straight RHUnc not /sqrt(60.) because we're pretending this is an individual ob\n # Calculate e+err=((RH+err)/100)*esat\n stat_obs_err[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] = (((stat_absRH[(stat_absT >= binn) & (stat_absT < RHBins[b+1])] + RHUnc[b]) / 100.) \\\n\t\t * sat_array[(stat_absT >= binn) & (stat_absT < RHBins[b+1])])\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\n# print('Check the e+err aligns with RH and T bins')\n# pdb.set_trace()\n\t\n\t\t# Compute Td+err from Td+err(e+err) and then substract Td to get Tderr adn then divide by 60 and * 2 to get 2sigma\n if (var == 'td'):\n \n\t\t # Working with Td so straightforward \n\t\t # Again using T to get pseudowetbulb to detect ice bulb - will be a little too high in erroneous wet bulb cases\t\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n stat_obs_err = (((CalcHums.td_from_vap(stat_obs_err,P_arr,stat_absT,roundit=False)) - stat_abs) / npm.sqrt(60.) ) * 2.\t\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n \n else:\n\t\t\n\t\t # Working with DPD so need to get pseudo Td\n # Td+err=Td+err(e+err)\n # Tderr=(Td+err)-Td\n stat_obs_err = ((CalcHums.td_from_vap(stat_obs_err,P_arr,stat_absT,roundit=False)) - (stat_absT - stat_abs)) # Again using Td instead of T to get pseudowetbulb to detect ice bulb - will be a little too low in erroneous ice cases\t\t\n\t\t # DPD = add 0.2 deg C unc from T on to DPD then *2 to get 2sigma\n stat_obs_err = ((stat_obs_err + 0.2) / npm.sqrt(60.)) * 2.\n\t\t # minimum number of obs per month is 15 days * 4 obs per day = 60 for single station within gridbox \t\t\n\t\t \n# print('Check the Tderr or DPDerr aligns with RH and T bins')\n# pdb.set_trace()\n\t\t# This give DPD obs error slightly smaller than the IDL version when T is < or very close to 0. because the ice bulb calculation is used here to convert to vapour pressure\n\n else: # Its an extreme so use T or Tw measurement error\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n if (var in WetEx):\n stat_obs_err = npm.array(ncf.variables['tw_obserr'][:]) # do we need to release the pointer?\n elif (var in DryEx):\n stat_obs_err = npm.array(ncf.variables['t_obserr'][:]) # do we need to release the pointer?\n ncf.close()\n stat_obs_err[stat_obs_err <= -99.99] = MDI\n stat_obs_err = npm.masked_equal(stat_obs_err, MDI) # should not fall over if there are no missing values\n\n #print('Check the obs error for Tw extreme')\n #pdb.set_trace()\n\n # Now mask in the missing data\n stat_obs_err[stat_abs.mask] = MDI\n stat_obs_err = npm.masked_equal(stat_obs_err, MDI) # should not fall over if there are no missing values\n#\tstat_obs_err.mask = stat_abs.mask\t \n\n#*******************************************************************\n# RH SENSOR ERROR (post 1980 - progressively) - NOT ADDED YET\n#*******************************************************************\n\n#*******************************************************************\n# Work on adjustment uncertainties\n#*******************************************************************\n # If its an extreme then read in adj and adjerr from Tw or T\n if (var not in ExtremesList):\n \n # read in log and find adjustment uncertainties - apply\n # # Gunzip PHA output file\n # call(['gunzip',InLog+'.gz'])\n\n # find homog adj for this station and append to array \n if (homogtype == 'PHA'):\n #PHA - 0=ID, 3=stmon,6=edmon, 8=ibreak, 9=cbreak, 10=adj, 11=eadj \n\t\n stmonget = 3\n edmonget = 6\n adjget = 10\n eadj = 11\n\t \n moo = check_output(['grep','-a','^Adj write:'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split('Adj write:')\t\n\n elif (homogtype == 'IDPHAMG') or (homogtype == 'PHADPD'):\n #IDPHAMG - 0=ID, 2=stmon, 3=edmon, 6=adj, 7=eadj, 8=adj source indicator \n\n stmonget = 2\n edmonget = 3\n adjget = 6\n eadj = 7\n\t \n moo = check_output(['grep','-a','^'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split('\\n') # no space\t\n\n else:\n #IDPHA - 0=ID, 2=stmon, 3=edmon, 6=adj, 7=eadj \n\n stmonget = 2\n edmonget = 3\n adjget = 6\n eadj = 7\n\t \n moo = check_output(['grep','-a','^'+StationListID[st],InLog])\n # Now sort out this string which is a byte array\n # This creates a list of strings for each adjustment with a blank string at the beginning\n moo = moo.decode(\"utf-8\").split(' \\n')\t\n\n # Remove the blank string\n moo.remove('')\n # Strip the \\n newline characters, random letters and split the strings to make a list of lists\n # b, i, p in IDPHAMG \n moo = [i.strip(' ABCDEFGHIJKLMNOPQRSTUVWXYZbip\\n').split() for i in moo] \n\n # Now loop through the adjustments to append to array\n # Ignore first line as this is most recent period so adjustment is 0\n for rec,adjstr in enumerate(moo[1:]):\n\n Adj = -(np.copy(float(adjstr[adjget])))\n #print(Adj)\n # these go from 1+, not 0+, first in loop is most recent period - no adjustment here \n stat_adjs[int(adjstr[stmonget])-1:int(adjstr[edmonget])] = Adj\n # THIS IS A 5th-95th so 1.65 sigma\n # divide by 1.65 then multiply by 2 to get 2sigma error - consistent with everything else then.\n stat_adjs_err[int(adjstr[stmonget])-1:int(adjstr[edmonget])] = float(adjstr[eadj]) / 1.65\n\n # print('Check read in and processing of adjustment and error')\n # pdb.set_trace()\n\n # # gzip PHA output file for tidiness\n # call(['gzip',InLog])\n\n # add in the flat adjustment error for missed adjustments derived from teh missing middle\n # combine in quadtrature and multiply by 2 to give a 2 sigma error\n stat_adjs_err = (npm.sqrt((stat_adjs_err**2) + (MissedAdjErr**2))) * 2.\n \n else:\n ncf = nc4.Dataset(InHom+StationListID[st]+DatSuffix,'r')\n if (var in WetEx):\n stat_adjs = npm.array(ncf.variables['tw_adjustments'][:]) \n stat_adjs_err = npm.array(ncf.variables['tw_adjerr'][:]) \n elif (var in DryEx):\n stat_adjs = npm.array(ncf.variables['t_adjustments'][:]) \n stat_adjs_err = npm.array(ncf.variables['t_adjerr'][:]) \n ncf.close()\n stat_adjs_err[stat_adjs_err <= -99.99] = MDI\n stat_adjs_err = npm.masked_equal(stat_adjs_err, MDI) # should not fall over if there are no missing values\n stat_adjs[stat_adjs <= -99.99] = MDI\n stat_adjs = npm.masked_equal(stat_adjs, MDI) # should not fall over if there are no missing values\n\n # Now mask in the missing data\n #stat_adjs_err.mask = stat_abs.mask\n #stat_adjs.mask = stat_abs.mask\t \n stat_adjs_err[stat_abs.mask] = MDI\n stat_adjs_err = npm.masked_equal(stat_adjs_err, MDI) # should not fall over if there are no missing values\n stat_adjs[stat_abs.mask] = MDI\n stat_adjs = npm.masked_equal(stat_adjs, MDI) # should not fall over if there are no missing values\n\n #print('Completed adjustment + MissedAdjErr - check')\n #pdb.set_trace()\n\n#***********************************************************************\n# Calc combined station error - ***2 SIGMA***\n#*********************************************************************** \n \n\t# Combine errors in quadrature - should have same mask as obs\n # Also ok for Tw extremes because we have read in 2 sigma uncertainties\n station_err = npm.sqrt(stat_obs_err**2 + stat_clims_err**2 + stat_adjs_err**2) # NOT * 2 as these are already * 2 !!!!! WORKS OUT SAME AS DOIGN 1 SIGMA COMBINED * 2\n\t\n#*******************************************************************************\n# Read in monthly standard deviations from unhomogenised NetCDF files and mask to homogenised\n#*********************************************************************************\n # File has to be present or we wouldn't be working on it\n ncf = nc4.Dataset(INDIRP+StationListID[st][0:6]+'-'+StationListID[st][6:11]+'_hummonthQC.nc','r')\n # Monthly standard deviation of all hourly values going into the monthly actual value\n\n # If its an extreme then use the standard deviation of the actual Tw or T across the month from the raw file \n if (var not in ExtremesList):\n # stat_sds = npm.array(ncf.variables[ParamDict[var][6]+'_std'][:]) # do we need to release the pointer?\n stat_sds = npm.array(ncf.variables[var+'_std'][:]) # do we need to release the pointer?\n else:\n# stat_sds = npm.array(ncf.variables['tw_std'][:]) # do we need to release the pointer?\n if (var in WetEx):\n stat_sds = npm.array(ncf.variables['tw_max_std'][:]) # do we need to release the pointer?\n if (var in DryEx):\n stat_sds = npm.array(ncf.variables['t_max_std'][:]) # do we need to release the pointer?\n ncf.close()\n\n # Use masked arrays with new MDI\n stat_sds[stat_abs.mask] = MDI\n stat_sds = npm.masked_equal(stat_sds, MDI) # should not fall over if there are no missing values\n # Actually because these are the raw (not homogenised!) standard deviations across all hourly data going into the monthly mean\n\t# the missing data may be less than the homogenised version where periods of ambiguous adjustment are removed\n\t# So need to mask using stat_abs too - having first ensured that stat_sds is a masked array which I think it was anyway from the netCDF file.\n\t\n\t# Check whether masked values that were previously -999 are in fact set to -1e30?\n\t# Yes - this is done in WriteNetCDF\n \n# print('Check read in of monthly Std values and masking')\n# pdb.set_trace()\n\n#**********************************************************************************\n# Write out to good list\n#**********************************************************************************\n\n filee = open(OutList,'a+')\n filee.write('%11s% 9.4f% 10.4f% 7.1f %2s %-29s\\n' % (StationListID[st],StationListLat[st], StationListLon[st], StationListElev[st],StationListCID[st],StationListName[st]))\n filee.close()\n \t\n#*********************************************************************************\n# Write out to netCDF file\n#************************************************************************************\n \n\t# NOTE THAT ITS JUST ONE VARIABLE!!!\n # List data together to pass to NetCDF writer\n DataList = [stat_anoms, stat_abs, stat_sds, stat_clims, stat_clim_sds, stat_adjs, stat_adjs_err, stat_clims_err, stat_obs_err, station_err]\n\n DimList = [['time','month','characters','bound_pairs'],\n\t [nmons,12,10,2],\n \t dict([('var_type','f4'),\n \t\t ('var_name','time'),\n \t\t ('var_dims',('time',)),\n \t\t ('standard_name','time'),\n \t\t ('long_name','time'),\n \t\t ('units','days since 1973-1-1 00:00:00'),\n \t\t ('axis','T'),\n \t\t ('calendar','gregorian'),\n \t\t ('start_year',int(styear)),\n \t\t ('end_year',int(edyear)),\n \t\t ('start_month',1),\n \t\t ('end_month',12),\n \t\t ('bounds','bounds_time')]),\n \t dict([('var_type','i4'),\n \t\t ('var_name','bounds_time'),\n \t\t ('var_dims',('time','bound_pairs',)), \n \t\t ('standard_name','time'),\n \t\t ('long_name','time period boundaries')]),\n \t dict([('var_type','S1'),\n \t\t ('var_name','month'),\n \t\t ('var_dims',('month','characters',)), \n \t\t ('long_name','month of year')])]\n\n # Attribute list for variables\n AttrList = [dict([('var_type','f4'),\n\t ('var_name',var+'_anoms'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' anomaly'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_abs'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_stds'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' standard deviations'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_clims'),\n\t\t ('var_dims',('month',)), \n\t ('long_name',ParamDict[var][5]+' climatology '+str(MYclst)+'-'+str(MYcled)),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_clim_stds'),\n\t\t ('var_dims',('month',)), \n\t ('long_name',ParamDict[var][5]+' climatological standard deviation '+str(MYclst)+'-'+str(MYcled)),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_adjustments'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' homogenisation adjustments from NCEIs PHA algorithm'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_adjerr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' adjustment uncertainty estimate including missed adjustment (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_climerr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' climatology uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_obserr'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' measurement uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])]),\n dict([('var_type','f4'),\n\t ('var_name',var+'_uncertainty'),\n\t\t ('var_dims',('time',)), \n\t ('long_name',ParamDict[var][5]+' combined station uncertainty estimate (2 sigma)'),\n\t ('units',ParamDict[var][1])])] \n\n GlobAttrObjectList = dict([['File_created',datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')], # Is there a call for time stamping?\n\t\t\t ['Description','HadISDH monthly land surface homogenised data'],\n\t\t\t ['Title','HadISDH monthly land surface climate monitoring product'], \n\t\t\t ['Institution', AttribDict['Institution']],\n\t\t\t ['History', AttribDict['History']], \n\t\t\t ['Licence', AttribDict['NCLicence']],\n\t\t\t ['Project', AttribDict['Project']],\n\t\t\t ['Processing_level', AttribDict['Processing_level']],\n\t\t\t ['Acknowledgement', AttribDict['Acknowledgement']],\n\t\t\t ['Source', 'HadISD '+hadisdversiondots+' '+AttribDict['Source']],\n\t\t\t ['Comment',''],\n\t\t\t ['References', AttribDict['References']],\n\t\t\t ['Creator_name', AttribDict['Creator_name']],\n\t\t\t ['Creator_email', AttribDict['Creator_email']],\n\t\t\t ['Version', versiondots],\n\t\t\t ['doi',''], # This needs to be filled in\n\t\t\t ['Conventions', AttribDict['Conventions']],\n\t\t\t ['netCDF_type', AttribDict['netCDF_type']]]) \n\n # Write out monthly data to netCDH\n WriteNetCDF(OutDat+StationListID[st]+DatSuffix,styear,edyear,[MYclst,MYcled],DataList,DimList,AttrList,GlobAttrObjectList,MDI)\n\n#**********************************************************************************\n# Plot homogenisation plots\n#**********************************************************************************\n# Plot the time series of the anomalies, adjustments and individual and combined uncertainty components\n#**********************************************************************************\n # If its an extreme then do not plot\n if (var not in ExtremesList):\n \n\t # Set up lists for looping through plot panels\n PlotTitles = [StationListID[st]+' Anomalies (Homogenised)', \n\t 'PHA Adjustments', \n\t\t 'Adjustment Uncertainty (2sigma)', \n\t\t 'Measurement Uncertainty (2sigma)', \n\t\t 'Climatology Uncertainty (2sigma)', \n\t\t 'Total Station Uncertainty (2sigma)']\n\t\t \n PlotVars = [stat_anoms, stat_adjs, stat_adjs_err, stat_obs_err, stat_clims_err, station_err]\n\t\n NPlots = len(PlotVars)\n\n\t # letters for plotting\n Letteree = LetterRange(0,NPlots)\n\n\t # Positioning\n xpos = []\n ypos = []\n xfat = []\n ytall = []\n totalyspace = 0.90\t# start 0.08 end 0.98\n totalxspace = 0.85\t# start 0.12 end 0.98\n \n for n in range(NPlots):\n xpos.append(0.12)\n ypos.append(0.98-((n+1)*(totalyspace/NPlots)))\n xfat.append(totalxspace)\n ytall.append(totalyspace/NPlots)\n \n # Xarray of months\n DateArr = np.array(list(np.array([[datetime(j,i,1,0,0,0) for i in np.arange(1,13)] for j in np.arange(int(styear),int(edyear)+1)]).flat))\n xtitlee = 'Years'\n \n\t # Make the plot \n plt.clf()\n f,axarr = plt.subplots(NPlots, figsize=(7,10), sharex=False)\t#6,18\n \n for pp in range(NPlots):\n \n axarr[pp].set_position([xpos[pp],ypos[pp],xfat[pp],ytall[pp]])\n axarr[pp].set_xlim([DateArr[0],DateArr[-1]])\n \n # If its not the last plot then suppress year tick labels on x axis\n if pp < NPlots-1:\n \n axarr[pp].set_xticklabels([]) \n\n # If its not the first or second plot then ensure y axis goes down to zero.\t\t\n if (pp > 1):\n \n if (np.max(PlotVars[pp]) > 0.):\n\n axarr[pp].set_ylim(0.,np.max(PlotVars[pp])*1.05)\t \t\t\n\n else:\n \n axarr[pp].set_ylim(0.,1.)\t\t \n \n #pdb.set_trace()\n# axarr[pp].plot(DateArr[PlotVars[pp] > MDI],PlotVars[pp][PlotVars[pp] > MDI],c='black',linewidth=0.5)\n axarr[pp].plot(DateArr,PlotVars[pp],c='black',linewidth=0.5)\n\n axarr[pp].annotate(Letteree[pp]+') '+PlotTitles[pp],xy=(0.03,0.03), xycoords='axes fraction',size=12)\n\n axarr[pp].set_ylabel(ParamDict[var][1],fontsize=12)\n #axarr[pp].hlines(0,DataArr[0],DataArr[-1],color='black',linewidth=0.5)\n \n axarr[NPlots-1].set_xlabel(xtitlee,fontsize=12)\n \n #plt.show()\n plt.savefig(OutPlots+StationListID[st]+'_anoms'+CLMlab+'_stationstats'+'.eps')\n plt.savefig(OutPlots+StationListID[st]+'_anoms'+CLMlab+'_stationstats'+'.png')\n plt.close()\n\n#***************************************************************************************\n# If this is the last station in the list then output counts to OUTPUTLOGFILE - shouldn't matter if we've had a restart as long as we haven't double written to the list files???\n#**************************************************************************************\n\n # Write out number of good, bad and (if they exist) supersat and subzero stations\n filee = open(OUTPUTLOG,'a+')\n moo = check_output(['wc','-l',OutList])\n filee.write('%s%s%i\\n' % (var, '_GOOD_STATIONS_AFTER_HOMOG_CONVERSION=', int(moo.decode('utf-8').split()[0])))\n moo = check_output(['wc','-l',OutBads])\n filee.write('%s%s%i\\n' % (var, '_BAD_STATIONS_AFTER_HOMOG_CONVERSION=', int(moo.decode('utf-8').split()[0])))\n if (len(glob.glob(OutFunniesT)) > 0):\n\n moo = check_output(['wc','-l',OutFunniesT])\n filee.write('%s%s%i\\n' % (var, '_SUPERSAT_STATIONS_AFTER_HOMOG_CONVERSION=',int(moo.decode('utf-8').split()[0])))\n\n if (len(glob.glob(OutFunniesZ)) > 0):\n\n moo = check_output(['wc','-l',OutFunniesZ])\n filee.write('%s%s%i\\n' % (var, '_SUBZERO_STATIONS_AFTER_HOMOG_CONVERSION=',int(moo.decode('utf-8').split()[0])))\n\n filee.close()\n \n print('All done!')\n \nif __name__ == '__main__':\n \n main(sys.argv[1:])\n\n#************************************************************************\n \n","sub_path":"F12_CreateHomogNCDFStUnc.py","file_name":"F12_CreateHomogNCDFStUnc.py","file_ext":"py","file_size_in_byte":79479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"260325442","text":"__author__ = 'shmakovs'\n\nAllPTYFileName = \"//panfs/pan1/prokdata/database_tmp/all1603.pty\"\nSpacerHitsFileName = \"//panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/SpacersSummary_9595.tsv_filtered\"\n\nBadCRISPRArraysFileName = \"//panfs/pan1/prokdata/CRISPRicity/SpacerAnalysis/AllIteration/Bad_CRISPRs.tsv\"\nBadCRISPRArrays = set()\nfor Line in open(BadCRISPRArraysFileName, \"r\"):\n BadCRISPRArrays.add(Line[:-1])\n\n# Bad Spacer Hits? -> in _filtered\n\nSpacersInfoDict = dict()\nwith open(SpacerHitsFileName, \"r\") as CRISPRArrayInfo:\n for Line in CRISPRArrayInfo:\n LineValues = Line[:-1].split(\"\\t\")\n\n if LineValues[1] != \"Intergenic\":\n continue\n if LineValues[3] == \"PhageNearby\":\n continue\n if LineValues[4] == \"VirusHit\":\n continue\n\n SpacersInfoDict[LineValues[0]] = LineValues[1:]\n\n","sub_path":"onetimers/SpacerAnalysis/Intergenic/IntergenicToFasta.py","file_name":"IntergenicToFasta.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"8158006","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 24 18:03:30 2017\n\n@author: mathieu\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom scipy.stats import skew\n\nclass Preprocess():\n \n def __init__(self):\n self.scaler = StandardScaler()\n self.summary_cat = pd.DataFrame()\n pass\n \n def fit_cat(self,X,y):\n \n self.mean = dict()\n self.var = dict()\n self.Neigh = ['Blmngtn','Blueste','BrDale','BrkSide','ClearCr','CollgCr',\\\n 'Crawfor','Edwards','Gilbert','IDOTRR','MeadowV','Mitchel',\\\n 'NAmes','NoRidge','NPkVill','NridgHt','NWAmes','OldTown',\\\n 'SWISU','Sawyer','SawyerW','Somerst','StoneBr','Timber','Veenker']\n for name in self.Neigh :\n self.mean[name] = np.nanmean(y.loc[X['Neighborhood'] == name,'SalePrice'])\n self.var[name] = np.nanvar(y.loc[X['Neighborhood'] == name,'SalePrice'])\n \n self.Zone = ['FV','RH','RL','RM']\n for name in self.Zone :\n self.mean[name] = np.nanmean(y.loc[X['MSZoning'] == name,'SalePrice'])\n\n \n self.Func = ['Typ','Min1','Min2','Mod','Maj1','Maj2','Sev']\n for name in self.Func:\n self.mean[name] = np.mean(y.loc[X['Functional'] == name,'SalePrice'])\n self.var[name] = np.var(y.loc[X['Functional'] == name,'SalePrice'])\n \n return self\n \n def fit_num(self,X,y):\n \n\n for i in np.arange(1,11) :\n self.mean[i] = np.nanmean(y.loc[X['OverallQual'] == i,'SalePrice'])\n \n return self\n \n \n def transform_num(self,train,test = False):\n X = train.copy()\n \n X['OverallQuallMean'] = 0\n for i in np.arange(1,11) :\n X.loc[X['OverallQual'] == i,'OverallQuallMean'] = self.mean[i]\n \"\"\"\n X['Neighmean'] = 0\n X['Neighvar'] = 0\n X['Zonemean'] = 0\n X['OverallQuallMean'] = 0\n X['Funcmean'] = 0\n X['Funcvar'] = 0 \n \n for name in self.Neigh :\n X.loc[X['Neighborhood'] == name,'Neighmean'] = self.mean[name] \n X.loc[X['Neighborhood'] == name,'Neighvar'] = self.var[name] \n \n self.Zone = ['FV','RH','RL','RM']\n for name in self.Zone :\n X.loc[X['MSZoning'] == name,'Zonemean'] = self.mean[name] \n for i in np.arange(1,11) :\n X.loc[X['OverallQual'] == i,'OverallQuallMean'] = self.mean[i]\n \n self.Func = ['Typ','Min1','Min2','Mod','Maj1','Maj2','Sev']\n for name in self.Func:\n X.loc[X['Functional'] == name,'Funcmean'] = self.mean[name] \n X.loc[X['Functional'] == name,'Funcvar'] = self.var[name] \n \n \n X.drop('MoSold',axis = 1,inplace = True)\n X.drop('MiscVal',axis = 1,inplace = True)\n X.drop('MiscFeature',axis = 1,inplace = True) \n X.drop('SaleType',axis = 1,inplace = True) \n X.drop('Fence',axis = 1,inplace = True) \n X.drop('PoolQC',axis = 1,inplace = True) \n X.drop('3SsnPorch',axis = 1,inplace = True) \n X.drop('PavedDrive',axis = 1,inplace = True) \n X.drop('GarageFinish',axis = 1,inplace = True)\n X.drop('GarageType',axis = 1,inplace = True)\n X.drop('FireplaceQu',axis = 1,inplace = True)\n X.drop('HalfBath',axis = 1,inplace = True)\n X.drop('Electrical',axis = 1,inplace = True)\n X.drop('BsmtFinType2',axis = 1,inplace = True)\n X.drop('BsmtFinType1',axis = 1,inplace = True)\n X.drop('MasVnrType',axis = 1,inplace = True)\n X.drop('Exterior2nd',axis = 1,inplace = True)\n X.drop('RoofStyle',axis = 1,inplace = True)\n X.drop('BldgType',axis = 1,inplace = True)\n X.drop('Condition2',axis = 1,inplace = True)\n X.drop('LandSlope',axis = 1,inplace = True)\n X.drop('LandContour',axis = 1,inplace = True)\n X.drop('LotShape',axis = 1,inplace = True)\n X.drop('Alley',axis = 1,inplace = True)\n X.drop('Street',axis = 1,inplace = True)\n X.drop('MSSubClass',axis = 1,inplace = True)\n X.drop('LotFrontage',axis = 1,inplace = True)\n \n X.loc[X['ExterQual'] == 'Ex','ExterQual'] = 5\n X.loc[X['ExterQual'] == 'Gd','ExterQual'] = 4\n X.loc[X['ExterQual'] == 'TA','ExterQual'] = 3\n X.loc[X['ExterQual'] == 'Fa','ExterQual'] = 2\n X.loc[X['ExterQual'] == 'Po','ExterQual'] = 1\n \n X.loc[X['ExterCond'] == 'Ex','ExterCond'] = 5\n X.loc[X['ExterCond'] == 'Gd','ExterCond'] = 4\n X.loc[X['ExterCond'] == 'TA','ExterCond'] = 3\n X.loc[X['ExterCond'] == 'Fa','ExterCond'] = 2\n X.loc[X['ExterCond'] == 'Po','ExterCond'] = 1\n \n \n X['ExterQual'] = pd.Series(X['ExterQual'],dtype = int)\n X['ExterCond'] = pd.Series(X['ExterCond'],dtype = int)\n \n X_numeric = X.select_dtypes(include= ['int','float'])\n \n X_numeric['Yr'] = (X_numeric['YearBuilt']*X_numeric['YearRemodAdd'])\n X_numeric['Overall'] = (X_numeric['OverallQual']*(X_numeric['OverallCond']))\n X_numeric['Tt_Area'] = (X_numeric['TotalBsmtSF']/(X_numeric['GrLivArea']))\n \n X_numeric[['GrLivArea']] = (np.log(X_numeric[['GrLivArea']] + 1))\n X_numeric[['LotArea']] = (np.log(X_numeric[['LotArea']] + 1))\n X_numeric[['BsmtFinSF1']] = (np.log(X_numeric[['BsmtFinSF1']] + 1))\n X_numeric[['TotalBsmtSF']] = (np.log(X_numeric[['TotalBsmtSF']] + 1))\n X_numeric[['1stFlrSF']] = (np.log(X_numeric[['1stFlrSF']] + 1))\n X_numeric[['2ndFlrSF']] = (np.log(X_numeric[['2ndFlrSF']] + 1))\n X_numeric[['GarageArea']] = (np.log(X_numeric[['GarageArea']] + 1))\n X_numeric[['OpenPorchSF']] = (np.log(X_numeric[['OpenPorchSF']] + 1))\n X_numeric[['LowQualFinSF']] = (np.log(X_numeric[['LowQualFinSF']] + 1))\n X_numeric.fillna(X_numeric.mean(),inplace = True)\n \"\"\"\n X.fillna(X.mean(),inplace = True)\n if not test :\n self.skewed_feats = X.apply(lambda x: skew(x.dropna())) #compute skewness\n self.skewed_feats = self.skewed_feats[self.skewed_feats > 0.75]\n self.skewed_feats = self.skewed_feats.index\n\n X[self.skewed_feats] = np.log1p(X[self.skewed_feats])\n if(not test):\n self.scaler.fit(X)\n \n X = pd.DataFrame(self.scaler.transform(X))\n #X.columns = train.columns.append('OverallQuallMean')\n \n \"\"\" \n X_cat.sort_index(axis=1,inplace = True)\n X1 = pd.concat([X_numeric,X_cat],axis=1)\n \"\"\"\n return X\n \n def transform_cat(self,train):\n X = train.copy()\n \n X['Neighmean'] = 0\n X['Neighvar'] = 0\n X['Zonemean'] = 0\n X['Funcmean'] = 0\n X['Funcvar'] = 0 \n for name in self.Neigh :\n X.loc[X['Neighborhood'] == name,'Neighmean'] = self.mean[name] \n X.loc[X['Neighborhood'] == name,'Neighvar'] = self.var[name] \n \n\n for name in self.Zone :\n X.loc[X['MSZoning'] == name,'Zonemean'] = self.mean[name] \n \n\n for name in self.Func:\n X.loc[X['Functional'] == name,'Funcmean'] = self.mean[name] \n X.loc[X['Functional'] == name,'Funcvar'] = self.var[name] \n \n X.fillna(X.mean(),inplace = True)\n \n return X\n \n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"243142021","text":"from os import getcwd\nfrom os.path import join\nfrom dotenv import load_dotenv\nimport argparse\nfrom instagram import auth_in_instagram\nfrom instagram import fetch_comments_last_three_months\nfrom instagram import fetch_instagram_post_ids\nfrom instagram import get_instagram_users_and_count_number_messages\nfrom vk import fetch_vk_posts\nfrom vk import fetch_all_vk_comments\nfrom vk import get_comments_last_two_weeks\nfrom vk import get_vk_commentator_ids\nfrom vk import fetch_vk_user_ids_who_liked_post\nfrom vk import get_vk_target_audience\nfrom facebook import fetch_all_facebook_posts\nfrom facebook import fetch_last_month_comments\nfrom facebook import fetch_post_reactions\nfrom facebook import get_facebook_target_audience\nfrom facebook import get_fb_commentator_ids\n\n\ndef get_social_media():\n parser = argparse.ArgumentParser(\n description='Скрипт ищет самых активных пользователей')\n parser.add_argument('social_media', help='Социальная сеть')\n args = parser.parse_args()\n return args.social_media\n\n\ndef main():\n load_dotenv(join(getcwd(), '.env'))\n social_media = get_social_media()\n\n if social_media == 'instagram':\n bot = auth_in_instagram()\n all_instagram_post_ids = fetch_instagram_post_ids(bot)\n instagram_comments_last_three_months = fetch_comments_last_three_months(\n bot,\n all_instagram_post_ids\n )\n users_and_count_number_messages = get_instagram_users_and_count_number_messages(\n instagram_comments_last_three_months\n )\n print(users_and_count_number_messages)\n\n elif social_media == 'vk':\n all_vk_posts = fetch_vk_posts()\n all_vk_comments = fetch_all_vk_comments(all_vk_posts)\n vk_comments_last_two_weeks = get_comments_last_two_weeks(all_vk_comments)\n vk_commentator_ids = get_vk_commentator_ids(vk_comments_last_two_weeks)\n vk_user_ids_who_liked_posts = fetch_vk_user_ids_who_liked_post(all_vk_posts)\n vk_target_audience = get_vk_target_audience(\n vk_commentator_ids,\n vk_user_ids_who_liked_posts\n )\n print(vk_target_audience)\n\n elif social_media == 'facebook':\n all_facebook_posts = fetch_all_facebook_posts()\n last_month_facebook_post_comments = fetch_last_month_comments(all_facebook_posts)\n all_facebook_post_reactions = fetch_post_reactions(all_facebook_posts)\n facebook_commentator_ids = get_fb_commentator_ids(\n last_month_facebook_post_comments\n )\n facebook_target_audience = get_facebook_target_audience(\n all_facebook_post_reactions,\n facebook_commentator_ids\n )\n print(facebook_target_audience)\n\n else:\n print('Неправильно ввели название социальной сети. Вы ввели: {}'.format(social_media))\n\n\nif __name__ == '__main__':\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"479783019","text":"from unittest.mock import patch, mock_open, call, Mock\nfrom copy import deepcopy\nfrom json import dumps as jdumps\nfrom stat import S_IRUSR, S_IWUSR\nfrom os.path import abspath\n\nimport pytest\nfrom hypothesis import given, example\nimport hypothesis.strategies as strat\n\nfrom vault_anyconfig.vault_anyconfig import VaultAnyConfig\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.chmod\")\n@patch(\"vault_anyconfig.vault_anyconfig.dump_base\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.read\")\n@given(\n file_path=strat.text(min_size=1, alphabet=strat.characters(blacklist_categories=(\"C\"))),\n secret_path=strat.text(\n min_size=1,\n alphabet=strat.characters(\n blacklist_categories=(\"C\"), # Since we separately specify the key, we cannot include \".\" in the secret path\n blacklist_characters=\".\",\n ),\n ),\n secret_key=strat.text(\n min_size=1,\n alphabet=strat.characters(\n blacklist_categories=(\"C\"), blacklist_characters=\".\" # Keys require actual values, not more dot separators\n ),\n ),\n)\n@example(file_path=\"/some/path/secret.cert\", secret_path=\"/secret/file\", secret_key=\"crt\")\n@example(file_path=\"/some/path/.hiddenfile\", secret_path=\"/secret/hidden/file\", secret_key=\"\")\n@example(file_path=\".hiddenfile\", secret_path=\"/secret/hidden/file\", secret_key=\"\")\n@example(file_path=\" .hiddenfile_with_space\", secret_path=\"/secret/hidden/file\", secret_key=\"\")\n@example(file_path=\".hiddenfile_with_space \", secret_path=\"/secret/hidden/file\", secret_key=\"\")\n@example(file_path=\"somefile\", secret_path=\"/secret/file\", secret_key=\"\")\n@example(file_path=\"somefile\", secret_path=\" /secret/with/space\", secret_key=\"\")\n@example(file_path=\"somefile\", secret_path=\"/secret/with/space \", secret_key=\"\")\ndef test_dump_different_file_paths_and_secrets(\n mock_hvac_client_read,\n mock_dump,\n mock_chmod,\n file_path,\n secret_path,\n secret_key,\n localhost_client,\n gen_input_config,\n gen_processed_config,\n gen_vault_response_kv1,\n file_contents,\n):\n \"\"\"\n Tests that secret keys, whitespace in paths, and hidden files are all handled correctly\n \"\"\"\n mock_hvac_client_read.return_value = gen_vault_response_kv1(file_contents=file_contents, secret_key=secret_key)\n\n if secret_key != \"\":\n secret_key = \".\" + secret_key\n\n input_config = gen_input_config(vault_files={file_path: secret_path + secret_key})\n\n with patch(\"builtins.open\", new_callable=mock_open) as mock_open_handle:\n localhost_client.dump(input_config, \"out.json\", process_secret_files=True)\n mock_open_handle.assert_called_once_with(abspath(file_path), \"w\")\n mock_open_handle().write.assert_called_once_with(file_contents)\n\n mock_hvac_client_read.assert_called_with(secret_path)\n\n mock_chmod.assert_called_with(abspath(file_path), S_IRUSR)\n\n\n@patch(\"vault_anyconfig.vault_anyconfig.chmod\")\n@patch(\"vault_anyconfig.vault_anyconfig.Client.read\")\n@given(\n file_path=strat.text(min_size=1, alphabet=strat.characters(blacklist_categories=(\"C\"))),\n secret_path=strat.text(min_size=1, alphabet=strat.characters(blacklist_categories=(\"C\"))),\n secret_key=strat.text(),\n)\ndef test_write_new_file(\n mock_hvac_client_read, mock_chmod, file_path, secret_path, secret_key, localhost_client, file_contents\n):\n \"\"\"\n Retrieves a string from a (mock) HVAC client and writes it to a (mock) file.\n \"\"\"\n mock_hvac_client_read.return_value = {\"data\": {\"file\": file_contents}}\n file_path_normalized = abspath(file_path)\n\n with patch(\"builtins.open\", new_callable=mock_open) as mock_open_handle:\n localhost_client.save_file_from_vault(file_path, secret_path, \"file\")\n mock_open_handle.assert_called_once_with(file_path_normalized, \"w\")\n mock_open_handle().write.assert_called_once_with(file_contents)\n\n mock_hvac_client_read.assert_called_with(secret_path)\n\n mock_chmod.assert_called_with(file_path_normalized, S_IRUSR)\n","sub_path":"tests/unit/file_handling_tests/test_fuzz_secret_file.py","file_name":"test_fuzz_secret_file.py","file_ext":"py","file_size_in_byte":3957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"77837216","text":"from dataset.DriveDatasetLoader import DriveDatasetLoader\nfrom methods.multi_line_opr import cached_multi_norm, cached_multi\nfrom methods.single_line_opr import cached_single, cached_single_norm\nfrom util.data_util import accuracy\nfrom util.print_color import *\nfrom util.timer import Timer\n\n\ndef line_with_training():\n train_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_train()\n test_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_test()\n\n # op = cached_single_norm\n op = cached_multi_norm\n\n size = 15\n timer = Timer()\n\n green('line_with_training')\n timer.start('Train')\n thresh, train_acc = find_best_acc(op, train_data, size)\n train_auc = calc_auc(train_data, op, size)\n timer.stop()\n\n timer.start('Test')\n test_acc = accuracy(op, test_data, thresh, size)\n test_auc = calc_auc(test_data, op, size)\n timer.stop()\n\n green(f'Threshold: {thresh}')\n green(f'Train average accuracy: {train_acc}')\n green(f'Train average AUC: {train_auc}')\n green(f'Test average accuracy: {test_acc}')\n green(f'Test average AUC: {test_auc}')\n\n # cv2.imshow('Image', linestr)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n\ndef line_no_training():\n data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_train()\n # data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_testing()\n\n op = cached_single_norm\n # op = cached_multi_norm\n\n size = 15\n timer = Timer()\n\n timer.start('line_no_training')\n acc = find_best_acc_each(op, data, size)\n timer.stop()\n\n green(f'Test average accuracy: {acc}')\n\n\ndef optic_with_training():\n train_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_train()\n test_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_test()\n\n # op = cached_single\n # thresh = 64\n\n op = cached_multi\n thresh = 119\n\n size = 15\n timer = Timer()\n\n green('optic_with_training')\n timer.start('Train')\n disk_thresh, train_acc = find_best_acc_optic(op, thresh, train_data, size)\n timer.stop()\n\n timer.start('Test')\n test_acc = get_accuracy_optic(op, test_data, thresh, disk_thresh)\n timer.stop()\n\n blue(f'Disk threshold: {disk_thresh}')\n blue(f'Train average accuracy: {train_acc}')\n blue(f'Test average accuracy: {test_acc}')\n\n\ndef optic_no_training():\n # data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_training()\n data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_test()\n\n # op = cached_single\n op = cached_multi\n\n size = 15\n timer = Timer()\n\n timer.start('optic_no_training')\n acc, auc = find_best_acc_optic_each(op, data, size)\n timer.stop()\n\n green(f'Test average accuracy: {acc}')\n green(f'Test average AUC: {auc}')\n\n\ndef proposed_with_training():\n train_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_train()\n test_data = DriveDatasetLoader('D:/Datasets/DRIVE', 10).load_test()\n\n op = cached_single\n # op = cached_multi\n\n thresh = 64\n optic_thresh = 42\n size = 15\n timer = Timer()\n\n green('proposed_with_training')\n timer.start('Train')\n proposed_thresh, train_acc = find_best_acc_proposed(op, thresh, optic_thresh, train_data, size)\n timer.stop()\n\n timer.start('Test')\n test_acc = get_accuracy_proposed(op, test_data, thresh, optic_thresh, proposed_thresh)\n timer.stop()\n\n blue(f'Proposed threshold: {proposed_thresh}')\n blue(f'Train accuracy: {train_acc}')\n blue(f'Test accuracy: {test_acc}')\n\n\ndef proposed_no_training():\n pass\n\n\nif __name__ == '__main__':\n proposed_with_training()\n","sub_path":"test/thresholding_test.py","file_name":"thresholding_test.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"83685167","text":"\"\"\"\nThis module will be available in templates as ``u``.\n\nThis module is also used to lookup custom template context providers, i.e. functions\nfollowing a special naming convention which are called to update the template context\nbefore rendering resource's detail or index views.\n\"\"\"\nfrom __future__ import division, unicode_literals\n\nfrom sqlalchemy import func, desc, text\n\nfrom clld import RESOURCES\nfrom clld.web.util.helpers import get_referents\nfrom clld.web.util.htmllib import HTML\nfrom clld.db.meta import DBSession\nfrom clld.db.models.common import Contributor, ValueSet, Contribution, ContributionContributor\n\n\ndef td_coverage(glottolog=0, grambank=0):\n if glottolog == 0:\n if grambank == 0:\n percentage = 0\n else:\n percentage = 1\n else:\n percentage = grambank / glottolog\n return HTML.td(\n '\\xa0%s%%\\xa0' % int(round(percentage * 100)),\n class_='center',\n style='background-color: hsl({0},100%,50%)'.format((percentage) * 120))\n\n\ndef source_detail_html(context=None, request=None, **kw):\n return dict(referents=get_referents(context, exclude=[\n 'language',\n 'sentence',\n 'contribution',\n #'valueset',\n ]))\n\n\ndef dataset_detail_html(context=None, request=None, **kw):\n contribs = DBSession.query(Contributor.name, func.count(ValueSet.id).label('c'))\\\n .join(\n Contributor.contribution_assocs,\n ContributionContributor.contribution,\n Contribution.valuesets)\\\n .group_by(Contributor.name)\\\n .order_by(desc(text('c')))\n return dict(\n contribs=contribs,\n stats=context.get_stats(\n [rsc for rsc in RESOURCES if rsc.name in ['language', 'parameter', 'value']]),\n )\n","sub_path":"grambank/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"46761004","text":"\"\"\"\nTests for LocalDAL\n\"\"\"\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport tempfile\nimport platform\nfrom datetime import datetime\n\nfrom datmo.core.storage.driver.blitzdb_dal_driver import BlitzDBDALDriver\nfrom datmo.core.storage.local.dal import LocalDAL\nfrom datmo.core.entity.model import Model\nfrom datmo.core.entity.session import Session\nfrom datmo.core.util.exceptions import EntityNotFound, InvalidArgumentType\n\n\nclass TestLocalDAL():\n def setup_method(self):\n # provide mountable tmp directory for docker\n tempfile.tempdir = \"/tmp\" if not platform.system(\n ) == \"Windows\" else None\n test_datmo_dir = os.environ.get('TEST_DATMO_DIR',\n tempfile.gettempdir())\n self.temp_dir = tempfile.mkdtemp(dir=test_datmo_dir)\n self.datadriver = BlitzDBDALDriver(\"file\", self.temp_dir)\n\n self.dal = LocalDAL(self.datadriver)\n model_name = \"model_1\"\n model = self.dal.model.create(Model({\"name\": model_name}))\n\n self.session_input_dict = {\n \"name\": \"session_1\",\n \"model_id\": model.id,\n \"current\": True\n }\n\n def teardown_method(self):\n pass\n\n def test_create_session_by_dictionary(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n assert session.id\n assert session.name == self.session_input_dict['name']\n assert session.created_at\n assert session.updated_at\n\n session_2 = self.dal.session.create(Session(self.session_input_dict))\n\n assert session_2.id != session.id\n\n test_session_input_dict = self.session_input_dict.copy()\n test_session_input_dict['id'] = \"session_id\"\n\n session_3 = self.dal.session.create(Session(test_session_input_dict))\n\n assert session_3.id == test_session_input_dict['id']\n\n def test_get_by_id_session(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n result = self.dal.session.get_by_id(session.id)\n assert session.id == result.id\n\n def test_get_by_shortened_id_session(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n result = self.dal.session.get_by_shortened_id(session.id[:10])\n assert session.id == result.id\n\n def test_get_by_id_session_new_driver_instance(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n # create new dal with new driver instance (fails)\n new_driver_instance = BlitzDBDALDriver(\"file\", self.temp_dir)\n new_dal_instance = LocalDAL(new_driver_instance)\n new_session_1 = new_dal_instance.session.get_by_id(session.id)\n assert new_session_1.id == session.id\n # create new dal instance with same driver (success)\n new_dal_instance = LocalDAL(self.datadriver)\n new_session_2 = new_dal_instance.session.get_by_id(session.id)\n assert new_session_2.id == session.id\n\n def test_update_session(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n # Update required and optional parameters\n updated_session_input_dict = self.session_input_dict.copy()\n updated_session_input_dict['id'] = session.id\n updated_session_input_dict['name'] = \"session_yo\"\n updated_session_input_dict['created_at'] = datetime.utcnow()\n updated_session = self.dal.session.update(updated_session_input_dict)\n\n assert session.id == updated_session.id\n assert session.updated_at < updated_session.updated_at\n assert updated_session.name == updated_session_input_dict['name']\n assert updated_session.created_at == updated_session_input_dict[\n 'created_at']\n\n def test_delete_session(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n self.dal.session.delete(session.id)\n deleted = False\n try:\n self.dal.session.get_by_id(session.id)\n except EntityNotFound:\n deleted = True\n assert deleted\n\n def test_query_sessions(self):\n session = self.dal.session.create(Session(self.session_input_dict))\n\n assert len(self.dal.session.query({\"id\": session.id})) == 1\n _ = self.dal.session.create(Session(self.session_input_dict))\n assert len(\n self.dal.session.query({\n \"name\": self.session_input_dict['name']\n })) == 2\n\n def test_query_sessions_current(self):\n session_1 = self.dal.session.create(Session(self.session_input_dict))\n session_2 = self.dal.session.create(\n Session({\n \"name\": \"test\",\n \"model_id\": \"test\",\n \"current\": False\n }))\n current_sessions = self.dal.session.query({\"current\": True})\n noncurrent_sessions = self.dal.session.query({\"current\": False})\n assert len(current_sessions) == 1\n assert current_sessions[0] == session_1\n assert len(noncurrent_sessions) == 1\n assert noncurrent_sessions[0] == session_2\n\n def test_create_update_key_to_same_value(self):\n session_1 = self.dal.session.create(Session(self.session_input_dict))\n session_2 = self.dal.session.create(\n Session({\n \"name\": \"test\",\n \"model_id\": \"test\",\n \"current\": False\n }))\n\n next_session = self.dal.session.query({\"model_id\": session_2.model_id})\n next_session = next_session[0]\n\n # get current session and update to false if present\n current_session = self.dal.session.query({\n \"model_id\": session_1.model_id\n })\n if len(current_session) == 1:\n current_session = current_session[0]\n current_session.model_id = session_2.model_id\n self.dal.session.update(current_session)\n\n # update the next session to the current one\n next_session.model_id = session_1.model_id\n self.dal.session.update(next_session)\n\n # ensure we still get the right result\n current_sessions = self.dal.session.query({\n \"model_id\": session_1.model_id\n })\n noncurrent_sessions = self.dal.session.query({\n \"model_id\": session_2.model_id\n })\n assert len(current_sessions) == 1\n assert current_sessions[0] == session_2\n assert len(noncurrent_sessions) == 1\n assert noncurrent_sessions[0] == session_1\n\n def test_sort_sessions(self):\n session_1 = self.dal.session.create(Session(self.session_input_dict))\n session_2 = self.dal.session.create(Session(self.session_input_dict))\n\n # Sorting of snapshot in descending\n items = self.dal.session.query(\n {\n \"name\": self.session_input_dict['name']\n },\n sort_key=\"created_at\",\n sort_order=\"descending\")\n assert items[0].created_at == session_2.created_at\n\n # Sorting of snapshot in ascending\n items = self.dal.session.query(\n {\n \"name\": self.session_input_dict[\"name\"]\n },\n sort_key=\"created_at\",\n sort_order=\"ascending\")\n assert items[0].created_at == session_1.created_at\n\n # Wrong order being passed in\n failed = False\n try:\n _ = self.dal.session.query(\n {\n \"name\": self.session_input_dict['name']\n },\n sort_key=\"created_at\",\n sort_order=\"wrong_order\")\n except InvalidArgumentType:\n failed = True\n assert failed\n\n # Wrong key and order being passed in\n failed = False\n try:\n _ = self.dal.session.query(\n {\n \"name\": self.session_input_dict[\"name\"]\n },\n sort_key=\"wrong_key\",\n sort_order=\"wrong_order\")\n except InvalidArgumentType:\n failed = True\n assert failed\n\n # wrong key and right order being passed in\n expected_items = self.dal.session.query(\n {\n \"name\": self.session_input_dict[\"name\"]\n },\n sort_key=\"created_at\",\n sort_order=\"ascending\")\n items = self.dal.session.query(\n {\n \"name\": self.session_input_dict[\"name\"]\n },\n sort_key=\"wrong_key\",\n sort_order=\"ascending\")\n expected_ids = [item.id for item in expected_items]\n ids = [item.id for item in items]\n assert set(expected_ids) == set(ids)\n\n def test_query_sessions_range_query(self):\n _ = self.dal.session.create(Session(self.session_input_dict))\n _ = self.dal.session.create(Session(self.session_input_dict))\n _ = self.dal.session.create(Session(self.session_input_dict))\n sessions = self.dal.session.query(\n {}, sort_key=\"created_at\", sort_order=\"descending\")\n result = self.dal.session.query({\n \"created_at\": {\n \"$lt\": sessions[1].created_at.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n }\n })\n assert len(sessions) == 3\n assert len(result) == 1\n","sub_path":"datmo/core/storage/local/tests/test_dal_session.py","file_name":"test_dal_session.py","file_ext":"py","file_size_in_byte":9333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"325772136","text":"\r\nimport sys,os\r\nimport tensorflow as tf\r\nimport pandas as pd\r\nimport yaml\r\nimport numpy as np\r\nimport copy\r\nfrom sklearn.model_selection import train_test_split\r\nimport traceback\r\nimport matplotlib as mpl\r\nif os.environ.get('DISPLAY','') == '':\r\n print('no display found. Using non-interactive Agg backend')\r\n mpl.use('Agg')\r\nfrom matplotlib import pyplot as plt\r\n\r\nif os.name == 'nt':\r\n TF_DATA_DIR = r'//dingo/scratch/pteng/dataset/fissure3d512_series'\r\n TARGET_DIR = r'//dingo/scratch/pteng/dataset/rawlung/'\r\n MEAN_CSV = r'//dingo/scratch/pteng/dataset/rawlung/mean.csv'\r\n YAML_PATH = r'//dingo/scratch/pteng/dataset/fissure3d512_series/tfrecords.yml'\r\nelse:\r\n TF_DATA_DIR = r'/scratch/pteng/dataset/fissure3d512_series'\r\n TARGET_DIR = r'/scratch/pteng/dataset/rawlung/'\r\n MEAN_CSV = r'/scratch/pteng/dataset/rawlung/mean.csv'\r\n YAML_PATH = r'/scratch/pteng/dataset/fissure3d512_series/tfrecords.yml'\r\n \r\nTARGET_DIR_MASK = os.path.join(TARGET_DIR,'mask')\r\nTARGET_DIR_IMG = os.path.join(TARGET_DIR,'image')\r\n\r\nimport copy\r\nimport pandas as pd\r\nfrom scipy import ndimage\r\nfrom scipy.ndimage import morphology\r\n\r\nimport SimpleITK as sitk\r\ndef read(fpath):\r\n reader= sitk.ImageFileReader()\r\n reader.SetFileName(fpath)\r\n img = reader.Execute()\r\n arr = sitk.GetArrayFromImage(img) \r\n spacing = img.GetSpacing()\r\n origin = img.GetOrigin()\r\n direction = img.GetDirection() \r\n return arr,spacing,origin,direction\r\n\r\ndef write(fpath,arr,spacing,origin,direction,use_compression=True):\r\n img = sitk.GetImageFromArray(arr)\r\n img.SetSpacing(spacing)\r\n img.SetOrigin(origin)\r\n img.SetDirection(direction)\r\n writer = sitk.ImageFileWriter() \r\n writer.SetFileName(fpath)\r\n writer.SetUseCompression(use_compression)\r\n writer.Execute(img)\r\n\r\n \r\n#https://respiratory-research.biomedcentral.com/articles/10.1186/1465-9921-15-23\r\nTISSUE_HU = -750.\r\ndef get_image_and_label(m_id_str):\r\n \r\n img_fpath = os.path.join(TARGET_DIR_IMG,m_id_str+'.nii.gz')\r\n mask_fpath = os.path.join(TARGET_DIR_MASK,m_id_str+'.nii.gz')\r\n img,spacing,origin,direction=read(img_fpath)\r\n msk,spacing,origin,direction=read(mask_fpath)\r\n \r\n fis = np.zeros(msk.shape)\r\n for r in [1,2,3,4,5]:\r\n tmp = msk == r\r\n tmp = morphology.binary_dilation(tmp,iterations=1)\r\n fis+=tmp.astype('int8')\r\n \r\n msk = msk > 0\r\n lung = morphology.binary_closing(msk,iterations=3)\r\n fis = np.logical_and(lung==1,fis>1)\r\n \r\n fis = fis.astype('int8')\r\n \r\n label = np.zeros(msk.shape)\r\n # 0:bkgd,1:airinlung,2:tissueinlung,3:fissure\r\n # (what about airway, heart, aorta, liver, esophagus...)\r\n label[np.logical_and(lung>0,img0,img>=TISSUE_HU)]=2\r\n label[fis==1]=3\r\n label[msk==0]=0\r\n print(np.unique(label))\r\n return copy.deepcopy(img), copy.deepcopy(label)\r\n\r\ndef normct(input):\r\n MINVAL = -1000.\r\n MAXVAL = 1000.\r\n RANGE = MAXVAL-MINVAL \r\n return np.clip((input-MINVAL)/RANGE,0.,1.)\r\n\r\nw = 512\r\nh = 512\r\nc = 11\r\nc_y = 1\r\none_hot_dim = 4\r\n\r\ndef _int64_feature(value):\r\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\r\n\r\ndef _bytes_feature(value):\r\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\r\n \r\ndef convert_to(m_id_str, file_path):\r\n \"\"\"Converts a dataset to tfrecords.\"\"\"\r\n \r\n print('processing...',m_id_str)\r\n img, label = get_image_and_label(m_id_str)\r\n \r\n img=np.swapaxes(img,0,2)\r\n label=np.swapaxes(label,0,2)\r\n\r\n ap_sz,lr_sz,si_sz = img.shape \r\n if ap_sz !=w or lr_sz != w or si_sz < 50:\r\n print('skip!',img.shape)\r\n return\r\n\r\n print(img.shape)\r\n ap_sz,lr_sz,si_sz = img.shape \r\n \r\n img = img.astype(np.int16)\r\n label = label.astype(np.uint8)\r\n print(img.shape,label.shape)\r\n \r\n image_raw = img.tostring()\r\n label_raw = label.tostring()\r\n #https://github.com/tensorflow/ecosystem/issues/61\r\n \r\n print('Writing', file_path)\r\n options = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.GZIP)\r\n writer = tf.python_io.TFRecordWriter(file_path,options=options)\r\n example = tf.train.Example(features=tf.train.Features(feature={\r\n 'height': _int64_feature(ap_sz),\r\n 'width': _int64_feature(lr_sz),\r\n 'depth': _int64_feature(si_sz),\r\n 'label_raw': _bytes_feature(label_raw),\r\n 'image_raw': _bytes_feature(image_raw),\r\n }))\r\n writer.write(example.SerializeToString())\r\n writer.close()\r\n\r\ndef serving_input_fn(params): # for deployment\r\n inputs = {INPUT_TENSOR_NAME: tf.placeholder(tf.float32, [None, w,h,c])}\r\n return tf.estimator.export.ServingInputReceiver(inputs, inputs)\r\n\r\ndef _parse_(serialized_example):\r\n features={\r\n #'image_raw': tf.FixedLenFeature([],tf.string),\r\n #'label_raw': tf.FixedLenFeature([],tf.string),\r\n 'image_raw': tf.FixedLenFeature([],tf.string),\r\n 'label_raw': tf.FixedLenFeature([],tf.string),\r\n 'height': tf.FixedLenFeature([], tf.int64),\r\n 'width': tf.FixedLenFeature([], tf.int64),\r\n 'depth': tf.FixedLenFeature([], tf.int64),\r\n }\r\n example = tf.parse_single_example(serialized_example,features)\r\n height = tf.cast(example['height'],tf.int64)\r\n width = tf.cast(example['width'],tf.int64)\r\n depth = tf.cast(example['depth'],tf.int64)\r\n image_shape = tf.stack([height, width, depth])\r\n\r\n image = tf.decode_raw(example['image_raw'], tf.int16)\r\n image = tf.reshape(image, image_shape)\r\n label = tf.decode_raw(example['label_raw'], tf.uint8)\r\n label = tf.reshape(label, image_shape)\r\n \r\n # slice it.\r\n min_ind = tf.constant(0,dtype=tf.int64)\r\n max_ind = depth-c-1\r\n ind = tf.random_uniform([1], minval=min_ind, maxval=max_ind, dtype=tf.int64)\r\n ind = ind[0]\r\n image = tf.transpose(image,[1,2,0])\r\n img_slice = tf.slice(image,[0,0,ind],[width,depth,c])\r\n label_slice = tf.expand_dims(label[ind+5,:,:],axis=-1)\r\n \r\n img_slice = tf.image.resize_image_with_crop_or_pad(img_slice,w,w)\r\n label_slice = tf.image.resize_image_with_crop_or_pad(label_slice,w,w)\r\n \r\n img_slice = (tf.clip_by_value(tf.cast(img_slice, tf.float32),-1000.,1000.)+1000.)/2000.\r\n \r\n augment = True\r\n if augment:\r\n # poor mans rotate and crop\r\n tf_radian = tf.random_uniform([1],minval=0,maxval=360*np.pi/180)\r\n img_slice = tf.contrib.image.rotate(img_slice,tf_radian)\r\n label_slice = tf.contrib.image.rotate(label_slice,tf_radian)\r\n\r\n print(img_slice.get_shape().as_list(),'!!')\r\n print(label_slice.get_shape().as_list(),'!!') \r\n \r\n return {INPUT_TENSOR_NAME:img_slice}, label_slice\r\n \r\n \r\nif not os.path.exists(YAML_PATH):\r\n NUM_EXAMPLES_TRAIN = 0\r\n train_ind_list = []\r\n valid_ind_list = []\r\n test_ind_list = []\r\nelse:\r\n is_print = False\r\n with open(YAML_PATH,'r') as f:\r\n content = yaml.load(f.read())\r\n \r\n x_data = [x['file_path'] for x in content]\r\n y_data = np.array([x['mean_hu'] for x in content])\r\n y_data_scaled = (y_data-np.min(y_data))/(np.max(y_data)-np.min(y_data))\r\n y_data_scaled = (10*y_data_scaled).astype(np.int8)\r\n y_data_scaled[y_data_scaled==10]=8 # 10 seems to be only 1or 2 series, thus train_test_split complains.\r\n if is_print:\r\n print(np.unique(y_data_scaled))\r\n print(len(np.unique(y_data_scaled)))\r\n y_data = y_data_scaled\r\n #y_data = np.ones(y_data_scaled.shape)\r\n random_seed = 42\r\n train_valid_ind_list, test_ind_list, y_train_valid, y_test = train_test_split(\r\n x_data, y_data, test_size=0.25, random_state=random_seed,stratify=y_data,\r\n )\r\n train_ind_list, valid_ind_list, y_train, y_valid = train_test_split(\r\n train_valid_ind_list, y_train_valid, test_size=0.33, random_state=random_seed,stratify=y_train_valid,\r\n )\r\n NUM_EXAMPLES_TRAIN = len(train_ind_list)\r\n if is_print:\r\n print(len(y_data))\r\n print(y_test)\r\n print(y_valid)\r\n print(y_train)\r\n print(len(train_ind_list),len(valid_ind_list),len(test_ind_list))\r\n \r\n \r\nINPUT_TENSOR_NAME = 'inputs'\r\nbatch_size = None\r\ndef train_input_fn(training_dir=TF_DATA_DIR, batch_size=batch_size, params=None):\r\n return _input_fn(training_dir, train_ind_list, batch_size=batch_size)\r\n \r\ndef eval_input_fn(training_dir=TF_DATA_DIR, batch_size=batch_size, params=None):\r\n return _input_fn(training_dir, valid_ind_list, batch_size=batch_size)\r\n\r\ndef _input_fn(training_dir, abs_path_file_list, batch_size=batch_size):\r\n tfrecord_dataset = tf.data.TFRecordDataset(filenames=abs_path_file_list, compression_type='GZIP')\r\n # buffer_size=batch_size*10)\r\n buffer_size=5\r\n random_seed=42\r\n tfrecord_dataset = tfrecord_dataset.map(lambda x:_parse_(x)).shuffle(\r\n buffer_size,seed=random_seed,reshuffle_each_iteration=True).batch(batch_size)\r\n tfrecord_iterator = tfrecord_dataset.make_one_shot_iterator()\r\n return tfrecord_iterator.get_next()\r\n \r\nif __name__ == '__main__':\r\n import argparse\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('generate',type=str,choices=['False','True'])\r\n args = parser.parse_args()\r\n if eval(args.generate) is False:\r\n \r\n sess = tf.InteractiveSession()\r\n tf.global_variables_initializer().run()\r\n \r\n batch_size = 2\r\n tf_images,tf_labels = train_input_fn(batch_size=batch_size)\r\n coord = tf.train.Coordinator()\r\n threads = tf.train.start_queue_runners(coord=coord,sess=sess)\r\n for _ in range(10):\r\n img, lbl = sess.run([tf_images, tf_labels])\r\n x = img[INPUT_TENSOR_NAME]\r\n print(x.shape,lbl.shape)\r\n coord.request_stop()\r\n coord.join(threads)\r\n\r\n sys.exit(0)\r\n \r\n if not os.path.exists(TF_DATA_DIR):\r\n os.makedirs(TF_DATA_DIR)\r\n \r\n ind_list = [x.strip('.nii.gz') for x in os.listdir(TARGET_DIR_IMG)]\r\n print(len(ind_list))\r\n df = pd.read_csv(MEAN_CSV)\r\n content = []\r\n for n,row in df.iterrows():\r\n print(n)\r\n marking_review_id_str = str(int(row['marking_review_id']))\r\n print(marking_review_id_str,marking_review_id_str in ind_list)\r\n if marking_review_id_str in ind_list:\r\n file_path = os.path.join(TF_DATA_DIR, marking_review_id_str + '.tfrecords')\r\n convert_to(marking_review_id_str, file_path)\r\n content.append(dict(\r\n marking_review_id=marking_review_id_str,\r\n mean_hu=row['mean_HU'],\r\n file_path=file_path,\r\n ))\r\n with open(YAML_PATH,'w') as f:\r\n f.write(yaml.dump(content))\r\n ","sub_path":"vae/bkup/datagen_series.py","file_name":"datagen_series.py","file_ext":"py","file_size_in_byte":10782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"338191897","text":"from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout\r\nfrom PyQt5.QtWidgets import QLineEdit, QPushButton, QHBoxLayout, QMessageBox\r\nfrom PyQt5.QtGui import QIcon\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nimport sys\r\nimport distanceSensor\r\nimport servomechanism\r\nimport membranePump\r\n\r\ndata0 = \"1\"\r\ndata1 = \"2\"\r\ndata2 = \"3\"\r\ndata3 = \"4\"\r\n\r\n\r\nclass Menu(QWidget):\r\n def __init__(self, parent=None):\r\n super().__init__(parent)\r\n\r\n self.interfejs()\r\n\r\n def interfejs(self):\r\n print(\"Main wind\")\r\n label1 = QLabel(\" Hello in Drink Master Servis!\", self)\r\n font = QtGui.QFont()\r\n font.setPointSize(16)\r\n label1.setFont(font)\r\n\r\n distanceSensor = QPushButton(\"&DISTANCE SENSOR\",self)\r\n servomechanism = QPushButton(\"&SERVOMECHANISM\", self)\r\n membranePumps = QPushButton(\"&MEMBRANE PUMPS\", self)\r\n\r\n distanceSensor.clicked.connect(self.showDistanceSensor)\r\n servomechanism.clicked.connect(self.showServomechanism)\r\n membranePumps.clicked.connect(self.showMembranePumps)\r\n\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n\r\n distanceSensor.setFont(font)\r\n servomechanism.setFont(font)\r\n membranePumps.setFont(font)\r\n\r\n ukladT = QGridLayout()\r\n ukladT.addWidget(label1,0, 0,1,3)\r\n ukladT.addWidget(distanceSensor)\r\n ukladT.addWidget(servomechanism)\r\n ukladT.addWidget(membranePumps)\r\n\r\n self.setLayout(ukladT)\r\n self.setGeometry(50, 50, 300, 100)\r\n # self.setWindowIcon(QIcon(\"photo.png\")) #ikonka trzeba dodać\r\n self.setWindowTitle(\"Drink Master Servis\")\r\n self.show()\r\n\r\n\r\n\r\n def showDistanceSensor(self):\r\n print(\"Open Window DistanceSensor\")\r\n self.ds = distanceSensor.DistanceSensor()\r\n self.ds.show()\r\n self.close()\r\n\r\n def showServomechanism(self):\r\n print(\"Open Window Servomechanism\")\r\n self.s = servomechanism.Servomechanism()\r\n self.s.show()\r\n self.close()\r\n\r\n def showMembranePumps(self):\r\n print(\"Open Window MembranePumps-XD\")\r\n self.mp = membranePump.MembranePump()\r\n self.mp.show()\r\n self.close()","sub_path":"app/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"407072260","text":"# Copyright 2018 The YARL-Project, All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport unittest\nfrom yarl.execution.ray import ApexExecutor\n\n\nclass TestRayExecutor(unittest.TestCase):\n \"\"\"\n Tests the ApexExecutor which provides an interface for distributing Apex-style workloads\n via Ray.\n \"\"\"\n\n env_spec = dict(\n type=\"openai\",\n gym_env=\"CartPole-v0\"\n )\n agent_config = dict(\n type=\"random\"\n )\n\n # Note that all of these args are allowed to be none,\n # Ray will just start a local redis and fetch number of cpus.\n cluster_spec = dict(\n redis_address=None,\n num_cpus=2,\n num_gpus=0,\n task_queue_depth=1,\n weight_sync_steps=100,\n env_interaction_task_depth=1,\n num_worker_samples=100,\n learn_queue_size=1,\n num_local_workers=1,\n num_remote_workers=1\n )\n\n def test_apex_workload(self):\n # Define executor, test assembly.\n executor = ApexExecutor(\n environment_spec=self.env_spec,\n agent_config=self.agent_config,\n cluster_spec=self.cluster_spec\n )\n print(\"Successfully created executor.\")\n\n # Kicks off remote tasks.\n executor.init_tasks()\n print(\"Initialized Apex executor Ray tasks, starting workload:\")\n\n # Executes actual workload.\n result = executor.execute_workload(workload=dict(num_timesteps=10000))\n print(\"Finished executing workload:\")\n print(result)\n","sub_path":"yarl/tests/test_execution/test_apex_executor.py","file_name":"test_apex_executor.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"601096384","text":"n = int(input())\n\nphoneBook = {}\n\n# str = 'artem 24101994'\n# print(str.split())\n# for i in range(n):\nphoneBook = dict(str(input()).split() for _ in range(n))\n\n\nwhile True:\n try:\n name = input()\n if name in phoneBook:\n print('{}={}'.format(name, phoneBook[name]))\n else:\n print('Not found')\n except:\n break\n\n# print(phoneBook)\n","sub_path":"hackerrank/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"74217130","text":"# -*- coding: utf-8 -*-\n\nclass Solution(object):\n def intToRoman(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n numDict = [[\"\",\"I\",\"II\",\"III\",\"IV\",\"V\",\"VI\",\"VII\",\"VIII\",\"IX\"],\n [\"\",\"X\",\"XX\",\"XXX\",\"XL\",\"L\",\"LX\",\"LXX\",\"LXXX\",\"XC\"],\n [\"\",\"C\",\"CC\",\"CCC\",\"CD\",\"D\",\"DC\",\"DCC\",\"DCCC\",\"CM\"],\n [\"\",\"M\",\"MM\",\"MMM\"]] \n return numDict[3][num / 1000 % 10]+numDict[2][num / 100 % 10]+numDict[1][num / 10 % 10]+numDict[0][num % 10]\n\n \nif __name__=='__main__':\n s= 500\n so=Solution()\n print(so.intToRoman(s))\n\n\n","sub_path":"12_integer_to_roman.py","file_name":"12_integer_to_roman.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"646348536","text":"# This is a demo task.\n\n# Write a function:\n\n# def solution(A)\n\n# that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.\n\n# For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.\n\n# Given A = [1, 2, 3], the function should return 4.\n\n# Given A = [−1, −3], the function should return 1.\n\n# Write an efficient algorithm for the following assumptions:\n\n# N is an integer within the range [1..100,000];\n# each element of array A is an integer within the range [−1,000,000..1,000,000].\nfrom bisect import bisect_left\nC = [-1, -2, 4, 5, 6, 12, 3, 4, 1, 0]\nB = []\nD = [-3, -4, -12312312, 2, 3, 1, 5, 5]\n\ndef solution(A):\n noNeg = list(filter(lambda x: x > 0, A))\n minVal = 1\n if len(noNeg) is 0:\n return minVal\n for N in sorted(noNeg):\n if N is minVal - 1:\n continue\n elif N is not minVal:\n return minVal\n else:\n minVal += 1\n return minVal\n\n\nsolution(C)\nsolution(B)\nsolution(D)\n","sub_path":"AofN.py","file_name":"AofN.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"91088186","text":"\ndef printArrayToFile(f, nparray):\n for elm in nparray:\n print(\"%.4f\" %(elm), end=' ', file=f)\n print(\"\\n\", end='', file=f)\n\n\nimport numpy as np\n\n\nreadfile = open(\"example-3-results.txt\", 'r')\nworkfile = open(\"workfile.txt\", \"w\")\n\ndims = (5, 40, 50)\n\npressureData = np.loadtxt(readfile)\n\npressureDist = pressureData[23].reshape(dims)\n\nnewPressureDist = np.zeros(dims, dtype=float)\n\nfor zIndx in range(dims[0]):\n newPressureDist[zIndx] = pressureDist[dims[0]-zIndx-1]\n\n\nprint(pressureDist)\n\n\nprintThis = \"[\"\n\nfor i in range(1000):\n printThis += \"3000\"\n if(i < 1000-1):\n printThis += \", \"\n\nprintThis += \"];\"\n\n#print(newPressureDist.reshape(dims[0]*dims[1]*dims[2]), file=workfile)\n\n#np.savetxt(workfile, newPressureDist.reshape(dims[0]*dims[1]*dims[2]))\n\nprintArrayToFile(workfile, newPressureDist.reshape(dims[0]*dims[1]*dims[2]))\n\n\nworkfile.close()\nreadfile.close()\n\n","sub_path":"Thesis/Simulation Examples/example-3-generatePressureDist.py","file_name":"example-3-generatePressureDist.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"128707171","text":"# ### Problem 2\n# Prompt the user with the message, ‘Is it better to be rude or kind to People?’ \n# Keeping prompting the user to enter an answer until they enter the word kind. \n# Each time they enter something other than kind, print the message, ‘That’s not the answer I had hoped to hear. Try again.’ and prompt the user again.\n# Once the user enters kind, print, ’Now that’s what I wanted to hear!’ and exit the program.\n\n# create a variable that holds userinput\nuserinput = input(\"IS it better to be rude or kind to People? \")\n\n# continue to ask user for input until kind is entered. print message based on userinput\nwhile userinput != \"kind\":\n if userinput != \"kind\":\n print(\"That's not the answer I had hoped to hear. Try again.\")\n userinput = input(\"Is it better to be rude of kind to people? \")\n if userinput == \"kind\":\n print(\"Now that's what I wanted to hear\")","sub_path":"q2.py","file_name":"q2.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"374645945","text":"from sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom Algorithms.plotDecisionRegions import plot_decision_regions\nimport matplotlib.pyplot as plt\nimport numpy as np\n\niris = datasets.load_iris()\nX = iris.data[:, [2, 3]]\ny = iris.target\n\n# Разбили набор данных на обучающий и испытательный\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1, stratify=y)\n\nX_combined = np.vstack((X_train, X_test))\ny_combined = np.hstack((y_train, y_test))\n\n# Tree classifier\n\nforest = RandomForestClassifier(criterion='gini',\n n_estimators=25,\n random_state=1,\n n_jobs=2)\nforest.fit(X_train, y_train)\nplot_decision_regions(X_combined,\n y_combined,\n classifier=forest,\n test_idx=range(105, 150))\nplt.xlabel('Длина лепестка [std]')\nplt.ylabel('Ширина лепестка [std]')\nplt.legend(loc='upper left')\nplt.show()\n","sub_path":"Scikit-learn/RandomForestClassifier/RandomForestClassifier.py","file_name":"RandomForestClassifier.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"544238482","text":"from algorithm import chromatic_balls, deep_cluster, greedy_expansion, pivot, rmm, vote\nfrom statistics import mean, median\nfrom log import log_real_world\nimport inspect\nfrom graph import Graph\nfrom dataset import read_dataset\nimport queue as Q\nfrom time import process_time\n\ndef clean_source_code_line(line):\n cleaned = line.split(':', maxsplit = 1)[1].split('#', maxsplit=1)[0].strip()\n if cleaned[-1] == ',':\n return cleaned[:-1].strip()\n return cleaned\n\ndef approx_errors(runs, graph, cluster_generator):\n result = {\n 'errors': [],\n 'cluster_counts': [],\n 'wall_clock_times': []\n }\n for _ in range(runs):\n start_time = process_time()\n clustering = cluster_generator(graph)\n end_time = process_time()\n result['errors'].append(graph.error_of(clustering))\n result['cluster_counts'].append(len(clustering))\n result['wall_clock_times'].append(end_time - start_time)\n print('#', end = '',flush=True)\n print(end='\\r')\n return result\n\ndef remove_nodes_with_low_degree(graph: Graph, min_degree):\n if min_degree == 0:\n return\n deleted = set()\n pq = Q.PriorityQueue()\n for node in graph.nodes():\n pq.put((graph.degree[node],node))\n while not pq.empty():\n degree, node = pq.get()\n if node in deleted: continue\n if degree >= min_degree:\n return\n for neig in graph.neighbors(node):\n pq.put((graph.degree[neig]-1, neig))\n graph.remove_node(node)\n deleted.add(node)\n\ndef run_real_world_experiment(dataset_name, algorithms, algorithm_names, runs, minimum_degree = 0):\n print(f\"Reading dataset: {dataset_name}\")\n dataset = read_dataset(dataset_name)\n if minimum_degree > 0:\n dataset_name = dataset_name + f\"_min_degree_{minimum_degree}\"\n summaries = []\n for i in range(len(algorithms)+1):\n summary = {}\n summary['runs'] = runs\n summary['number_of_nodes'] = 0\n summary['number_of_edges'] = 0\n summary['number_of_colors'] = 0\n summary['dataset'] = dataset_name\n summary['errors'] = [0]*summary['runs']\n summary['wall_clock_times'] = [0]*summary['runs']\n summary['number_of_clusters'] = [0]*summary['runs']\n summary['algorithm'] = algorithm_names[algorithms[i]].split('.', maxsplit=1)[1] if i < len(algorithms) else 'primary_edge_graph'\n summaries.append(summary)\n summaries[-1]['runs'] = 10\n summaries[-1]['wall_clock_times'] = [0]*summaries[-1]['runs']\n summaries[-1]['dataset'] = dataset_name\n\n for graph_number, graph in enumerate(dataset):\n print(f'part {graph_number}')\n if minimum_degree > 0:\n remove_nodes_with_low_degree(graph, minimum_degree)\n\n # measure time of to create primary_edge_graph(), we generally cache it to speed up the experiments\n for i in range(summaries[-1]['runs']):\n if hasattr(graph, 'primary_graph'):\n delattr(graph, 'primary_graph')\n start_time = process_time()\n graph.primary_edge_graph()\n end_time = process_time()\n summaries[-1]['wall_clock_times'][i] += end_time - start_time\n \n results_by_algorithm = {}\n for i in range(len(algorithms)):\n summary = summaries[i]\n alg = algorithms[i]\n summary['number_of_nodes'] += graph.number_of_nodes()\n summary['number_of_edges'] += graph.number_of_edges()\n summary['number_of_colors'] = max(summary['number_of_colors'], len(graph.colors()))\n measurements = approx_errors(summary['runs'], graph, alg)\n for i in range(summary['runs']):\n summary['errors'][i] += measurements['errors'][i]\n summary['number_of_clusters'][i] += measurements['cluster_counts'][i]\n summary['wall_clock_times'][i] += measurements['wall_clock_times'][i]\n results_by_algorithm[algorithm_names[alg]] = mean(measurements['errors'])\n print(\"{0:65} mean: {1:8} median: {2:8} wct all runs: {3:8} seconds\".format(summary['algorithm'], round(mean(measurements['errors'])), round(median(measurements['errors'])), round(sum(measurements['wall_clock_times']), 2)))\n print()\n\n for i in range(len(algorithms)+1):\n summary = summaries[i]\n log_real_world(summary)\n\ndef run_real_world_experiment_on_all_algorithms_and_datasets(): \n print(\"run_real_world_experiment\") \n algorithms = [ \n lambda graph: pivot.pivot(graph),\n lambda graph: pivot.reduce_and_cluster(graph),\n lambda graph: deep_cluster.deep_cluster(graph),\n lambda graph: vote.vote(graph),\n lambda graph: rmm.random_maximum_merging(graph),\n lambda graph: greedy_expansion.greedy_expansion(graph),\n lambda graph: greedy_expansion.greedy_expansion(graph.primary_edge_graph()),\n lambda graph: chromatic_balls.chromatic_balls(graph),\n ]\n algorithm_names = {alg:clean_source_code_line(inspect.getsourcelines(alg)[0][0]) for alg in algorithms}\n small_datasets = ['facebook', 'twitter', 'microsoft_academic', 'cooking', 'dawn']\n large_datasets = ['dblp', 'string']\n legacy_datasets = ['legacy_string', 'legacy_dblp']\n for dataset_name in small_datasets + large_datasets:\n run_real_world_experiment(dataset_name, algorithms, algorithm_names, runs = 50)\n run_real_world_experiment(dataset_name + '_multilabel', algorithms[:-1], algorithm_names, runs = 50)\n for dataset_name in legacy_datasets:\n run_real_world_experiment(dataset_name, algorithms, algorithm_names, runs = 50, minimum_degree=10)\n \nrun_real_world_experiment_on_all_algorithms_and_datasets()","sub_path":"src/experiment_real_world.py","file_name":"experiment_real_world.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"219644568","text":"#!/usr/bin/python\n#-*- coding:utf-8 -*-\n\n# 创建一个函数,用于接收用户输入的数字,并计算用户输入数字的和\n\n\ndef NumberSumup(x, y):\n sum = x + y\n return sum\n\n\ntry:\n n = input(\"Please input 2 numbers: \")\n (x, y) = (n[0], n[1])\nexcept Exception as e:\n print (e)\n\nprint(NumberSumup(int(x), int(y)))\n\n\n# 创建一个函数,传入n个整数,返回其中最大的数和最小的数\n\ndef comparetwonumber(x, y):\n try:\n if int(x) > int(y):\n return x\n else:\n return y\n except Exception as e:\n print(e)\n\n\nn = input(\"Please input numbers separated by ',': \")\nlength = len(n) - 1\ni = 0\nmax_num = 0\nwhile i <= length:\n max_num = comparetwonumber(n[i], max_num)\n i = i + 1\n\nprint(\"The Max number is: \" + str(max_num))\n\n\n#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\n# 创建一个函数,传入一个参数n,返回n的阶乘\ndef factorial(n):\n if n == 0 or n ==1:\n return 1\n else:\n return n*factorial(n-1)\n\n\nresult = factorial(6)\nprint(result)\n","sub_path":"exercise/9 函数/exercise9.py","file_name":"exercise9.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"509102890","text":"from import_clr import *\nclr.AddReference(\"ManagedIR16Filters\")\nfrom Lepton import CCI\nfrom IR16Filters import IR16Capture, NewIR16FrameEvent, NewBytesFrameEvent\nimport numpy as np\nimport time\nfrom collections import deque\n\n\nclass Lepton:\n def __init__(self):\n # Find device\n found_device = None\n for device in CCI.GetDevices():\n if device.Name.startswith(\"PureThermal\"):\n print(device.Name)\n found_device = device\n break\n if not found_device:\n print(\"Couldn't find lepton device\")\n else:\n self.lep = found_device.Open()\n\n # Get the current camera uptime\n # print(self.lep.oem.GetSoftwareVersion())\n # print(\"Camera Up Time: {}\".format(self.lep.sys.GetCameraUpTime()))\n\n # Run a FFC. If this command executes successfully, the shutter on the lepton should close and open.\n self.lep.sys.RunFFCNormalization()\n\n # Get the current palette (**Pseudo-color** L*ook *Up Table)\n # lep.vid.GetPcolorLut()\n # lep.sys.SetGainMode(CCI.Sys.GainMode.LOW)\n # lep.vid.SetPcolorLut(3)\n # print(self.lep.sys.GetFpaTemperatureKelvin())\n\n try:\n self.lep.rad.SetTLinearEnableStateChecked(True)\n print(\"This lepton supports tlinear\")\n self.tlinear = True\n except:\n print(\"This lepton does not support tlinear\")\n self.tlinear = False\n\n # Start streaming\n self.capture = None\n # change maxlen to control the number of frames of history we want to keep\n self.incoming_frames = deque(maxlen=10)\n if self.capture is not None:\n # don't recreate capture if we already made one\n self.capture.RunGraph()\n else:\n self.capture = IR16Capture()\n self.capture.SetupGraphWithBytesCallback(NewBytesFrameEvent(self.__got_a_frame))\n self.capture.RunGraph()\n while len(self.incoming_frames) == 0:\n time.sleep(.1)\n\n def update_frame(self, rotate=0, flip=0, coef=0.05, offset=0.0):\n height, width, net_array = self.incoming_frames[-1]\n raw = self.short_array_to_numpy(height, width, net_array)\n\n if rotate == 0 and flip:\n raw = np.flip(raw, 1)\n elif rotate == 1 and not flip:\n raw = np.flip(np.transpose(raw, (1, 0)), 1)\n elif rotate == 1 and flip:\n raw = np.flip(np.flip(np.transpose(raw, (1, 0)), 0), 1)\n elif rotate == 2 and not flip:\n raw = np.flip(np.flip(raw, 0), 1)\n elif rotate == 2 and flip:\n raw = np.flip(raw, 0)\n elif rotate == 3 and not flip:\n raw = np.flip(np.transpose(raw, (1, 0)), 0)\n elif rotate == 3 and flip:\n raw = np.transpose(raw, (1, 0))\n\n # print(\"debug\", coef, offset)\n if self.tlinear:\n # Lepton 3.5 (with radiometric accuracy)\n # raw is in centikelvin\n temp = (raw - 27315) / 100 + offset\n else:\n # Lepton 3.0 (without radiometric accuracy), need to calibrate the coefficient(COEF)\n # raw is in raw value\n # celsius = (raw_data - 8192) * coefficient / 100 + camera_temperature\n temp = (np.float64(raw) - 8192) * coef + offset + self.camera_temp()\n\n return raw, temp\n\n # return in celsius\n def camera_temp(self):\n # note self.lep.sys.GetFpaTemperatureKelvin() is in centi_kelvin\n # convert it in celsius by (value - 27315) / 100\n return (self.lep.sys.GetFpaTemperatureKelvin() - 27315) / 100\n\n def run_ffc(self):\n self.lep.sys.RunFFCNormalization()\n\n def stop_streaming(self):\n print(\"Stop streaming\")\n self.capture.StopGraph()\n self.capture.Dispose()\n\n def __got_a_frame(self, short_array, width, height):\n self.incoming_frames.append((height, width, short_array))\n\n @staticmethod\n def short_array_to_numpy(height, width, frame):\n return np.fromiter(frame, dtype=\"uint16\").reshape(height, width)\n","sub_path":"src/lepton_control.py","file_name":"lepton_control.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"130769181","text":"import numpy as np \r\nfrom numpy import random\r\nfrom numpy.random import seed\r\nfrom numpy.random import rand\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import colors\r\nimport statistics\r\n\r\ndef average(MArray, LocalSpace):\r\n \r\n for i in range(-MArray[0], MArray[1]): \r\n for j in range(-MArray[2], MArray[3]):\r\n if i != 0 and j != 0: \r\n A[1+i][1+j] = (LocalSpace[1][1] + LocalSpace[1+i][1+j])/2 #Average between z.cell and n.cell\r\n \r\n \r\n \r\n if LocalSpace[1][1] >= LocalSpace[1+i][1+j]: # Difference in Energy between z.cell and n.cell\r\n Diff[1+i][1+j] = abs(abs(LocalSpace[1][1]) - abs(LocalSpace[1+i][1+j]))\r\n else: \r\n Diff[1+i][1+j] = abs(abs(LocalSpace[1+i][1+j]) - abs(LocalSpace[1][1]))\r\n \r\n \r\n \r\n FluxCell = np.zeros((2,1))\r\n FluxCell[0][0] = (LocalSpace[1+i][1+j] / Diff[1+i][1+j]) * A[1+i][1+j] # Flux for z.cell\r\n FluxCell[1][0] = (LocalSpace[1][1] / Diff[1+i][1+j]) * A[1+i][1+j] # Flux for n.cell\r\n print(FluxCell)\r\n Flux[1+i][1+j] = FluxCell[1][0] # Put this flux vector into array\r\n Flux[1][1] += (1/8)*FluxCell[0][0] \r\n print(Flux)\r\n return Diff \r\n return Flux \r\n return A \r\n\r\ndef Localupdate(MArray, LocalSpace, Flux):\r\n LocalSpace = LocalSpace + Flux \r\n return LocalSpace \r\n \r\n \r\n # FluxCell = np.zeros(1,2)\r\n # Flux = Diff[1+i][1+j]\r\ndef GlobalUpdate(MArray, LocalSpace): #put into local space\r\n for i in range(-MArray[0], MArray[1]): \r\n for j in range(-MArray[2], MArray[3]):\r\n space[n+i][m+j] = LocalSpace[1+i][1+j]\r\n return space\r\n\r\ndef Rule(MArray, LocalSpace): #the rule for this update\r\n average(MArray, LocalSpace)\r\n Localupdate(MArray, LocalSpace, Flux)\r\n GlobalUpdate(MArray, LocalSpace)\r\n\r\ndef LocalSpacelimits(n,m,X,Y): #Limits local space for boundedness\r\n if (n >= 1 and m >= 1) and (n != X and m != Y):\r\n #Array of possible movement directions\r\n #[-i,+i,-j,+j] yes/no\r\n MArray = [1,1,1,1]\r\n Rule(MArray, LocalSpace)\r\n ## Edges w/o corners\r\n # left edge no -j\r\n if n == 0 and m >= 1 and m != Y:\r\n MArray = [1,1,0,1]\r\n Rule(MArray, LocalSpace)\r\n \r\n # top edge no -i\r\n elif n >= 1 and m == 0 and n != X:\r\n MArray = [0,1,1,1]\r\n Rule(MArray, LocalSpace)\r\n \r\n # right edge no +j\r\n elif n == X and m >= 1 and m != Y:\r\n MArray = [1,1,1,0]\r\n Rule(MArray, LocalSpace)\r\n\r\n # bottom edge no +i\r\n elif n >= X and m == Y and n != X:\r\n MArray = [1,0,1,1]\r\n Rule(MArray, LocalSpace)\r\n ## corners\r\n # Top left\r\n elif n == 0 and m == 0:\r\n MArray = [0,1,0,1]\r\n Rule(MArray, LocalSpace)\r\n \r\n # Top right\r\n elif n == X and m == 0:\r\n MArray = [0,1,1,0]\r\n Rule(MArray, LocalSpace)\r\n \r\n elif n == X and m == Y:\r\n MArray = [1,0,1,0]\r\n Rule(MArray, LocalSpace)\r\n \r\n # Bottom left\r\n else:\r\n MArray = [1,0,0,1]\r\n Rule(MArray, LocalSpace)\r\n\r\ndef LocalSpaceSetup(space, i, j):\r\n\r\n n = random.randint(X)\r\n \r\n m = random.randint(Y)\r\n \r\n \r\n # zeroth cell (z.vec), cell of interest \r\n O = space[33+i][33+j]\r\n \r\n #[0101;0100;1100]\r\n #[0001;0000;1001]\r\n #[0011;0001;] \r\n #\r\n #[0101;0100;1100]\r\n #[0001;0000;1001]\r\n #[0011;0001;1001]\r\n #\r\n # [1010]\r\n # [RIGHT/UP/LEFT/DOWN]\r\n #\r\n # Define neighbour cells (n.cells) \r\n OIIO = space[n-1][m-1] \r\n OIOO = space[n-1][m]\r\n IIOO = space[n-1][m+1]\r\n IOOI = space[n][m+1]\r\n IOOI = space[n+1][m+1]\r\n OOOI = space[n+1][m]\r\n OOII = space[n+1][m-1]\r\n OOIO = space[n][m-1] \r\n \r\n LocalSpace = np.array([[OIIO, OIOO, IIOO],[OOIO, O, IOOI],[OOII, OOOI, IOOI]])\r\n\r\n Diff = np.zeros_like(LocalSpace)\r\n A = np.zeros_like(LocalSpace)\r\n Flux = np.zeros_like(LocalSpace)\r\n\r\n#May be better to average this!\r\n# Void draws from surrounding\r\n# def Entropy(i, j, LocalSpace):\r\n# if i == j and i == 1:\r\n# LocalSpace[1][1] -= 0.01*(LocalSpace.shape[0]*LocalSpace.shape[1] - 1)\r\n# else:\r\n# LocalSpace[1+i][1+j] += 0.01\r\n# return LocalSpace\r\n# # # Thing gives to surrounding \r\n# def Gravity(i, j, LocalSpace):\r\n# if i == j and i == 1:\r\n# LocalSpace[1][1] += 0.01*(LocalSpace.shape[0]*LocalSpace.shape[1] - 1)\r\n# else:\r\n# LocalSpace[1+i][1+j] -= 0.01\r\n# return LocalSpace\r\n\r\n# # More gives to less\r\n# def GraEntQ(i, j, LocalSpace):\r\n# if LocalSpace[1][1] < LocalSpace[1+i][1+j]: # if z.cell is less than n.cell: 1 bit to z.cell from n.cell\r\n# LocalSpace[1][1] += 0.01\r\n# LocalSpace[1+i][1+j] -= 0.01\r\n# elif LocalSpace[1][1] > LocalSpace[1+i][1+j]: # if z.cell is more than n.cell: 1 bit from z.cell to n.cell. LocalSpace[1][1]\r\n# LocalSpace[1][1] -= 0.01\r\n# LocalSpace[1+i][1+j] += 0.01\r\n# return LocalSpace # if equal, ignore. hopefully this takes care of the \r\n\r\n# # True/False in terms of directions in bounds [negative_i, positive_i, negative_j, positive_j]\r\n# def LocalUpdate(MArray, LocalSpace):\r\n# if LocalSpace[1][1] >= float(1): #select surrounding cells\r\n# for i in range(-MArray[0], MArray[1]): \r\n# for j in range(-MArray[2], MArray[3]):\r\n# Entropy(i, j, LocalSpace)\r\n \r\n \r\n# # elif 0 is min, draw from all \r\n# elif LocalSpace[1][1] <= float(0): #select surrounding cells\r\n# for i in range(-MArray[0], MArray[1]): \r\n# for j in range(-MArray[2], MArray[3]):\r\n# Gravity(i, j, LocalSpace)\r\n# else: \r\n# for i in range(-MArray[0], MArray[0]): \r\n# for j in range(-MArray[2], MArray[0]):\r\n# GraEntQ(i, j, LocalSpace) \r\n# return LocalSpace \r\n\r\n\r\n\r\n\r\n#All zero array\r\n# X = input(\"X size (Global)\")\r\n# Y = input(\"Y size (Global)\") \r\nXsize = 65\r\nYsize = 65\r\nspace = np.random.uniform(-1, 1, (Xsize, Ysize))\r\n\r\n# x(1 skip 2,0 skip 2) 01010101\r\n\r\n\r\n# x(0 skip 2,1 skip 2) 10101010\r\n# space[:,:] = random.randint(-1000, 1000, 1)\r\nspace[33][33] = 1000 \r\nspace[31][31] = 1000\r\n\r\nX = space.shape[0] - 1\r\nY = space.shape[1] - 1\r\n\r\n\r\n\r\n# No. of time steps\r\ntime = 10\r\n\r\n# Loop over all possible time\r\nt = 0\r\nwhile t < time:\r\n t += 1\r\n if t <= X: \r\n for i in range(-t, t):\r\n for j in range(t, t): \r\n \r\n LocalSpaceSetup(space)\r\n LocalSpacelimits(n,m,X,Y)\r\n \r\n \r\n\r\nimage = space\r\nplt.imshow(image, cmap=plt.cm.hot_r)\r\nplt.colorbar()\r\nplt.show()\r\nprint(space)\r\n\r\n\r\n# print(space)","sub_path":"Universe1.py","file_name":"Universe1.py","file_ext":"py","file_size_in_byte":7011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"95345940","text":"import pyomo.environ as pyo\r\nimport pyomo\r\nimport numpy as np\r\nimport pandas\r\nimport random\r\nimport string\r\nfrom Stkw_Linear.plin_models import Indicator_Weak_Concrete, Indicator_Strong_Concrete, DCC_Concrete, CC_Concrete, Incremental_Concrete, DLog_Concrete, Indicator_Layered\r\n\r\n\r\nclass B_Solver(object):\r\n def __init__(self, solver_name):\r\n self.name = solver_name\r\n self.solver = pyomo.opt.SolverFactory(solver_name)\r\n \r\nclass Benchmark(object):\r\n def __init__(self, n_intervals, n_its, rng, time_limit):\r\n self.n_intervals = n_intervals\r\n self.n_its = n_its\r\n self.time_limit = time_limit\r\n self.step_function_models = [] \r\n self.b_solvers = []\r\n self.output_df = pandas.DataFrame(columns = [\r\n \"benchmark_iteration\",\r\n \"model\",\r\n \"solver\",\r\n \"lower_bound\",\r\n \"upper_bound\",\r\n \"time\",\r\n #\"wall_time\",\r\n \"status\",\r\n #\"return_code\",\r\n \"error_rc\"\r\n ])\r\n #Festsetzten des RNGs pro benchmark\r\n self.rng = rng\r\n \r\n def add_model(self,model):\r\n self.step_function_models.append(model)\r\n \r\n def add_solver(self, b_solver):\r\n #Add Time Limit\r\n if b_solver.name == 'cplex':\r\n b_solver.solver.options['timelimit'] = self.time_limit\r\n elif b_solver.name == 'glpk': \r\n b_solver.solver.options['tmlim'] = self.time_limit\r\n elif b_solver.name == 'gurobi': \r\n b_solver.solver.options['TimeLimit'] = self.time_limit\r\n self.b_solvers.append(b_solver)\r\n \r\n def set_benchmark_parameters(self, n_intervals, n_its, rng, time_limit):\r\n self.n_intervals = n_intervals\r\n self.n_its = n_its\r\n self.time_limit = time_limit\r\n self.rng = rng\r\n\r\n def reset_output(self):\r\n self.output_df = pandas.DataFrame(columns = [\r\n \"benchmark_iteration\",\r\n \"model\",\r\n \"solver\",\r\n \"lower_bound\",\r\n \"upper_bound\",\r\n \"time\",\r\n #\"wall_time\",\r\n \"status\",\r\n #\"return_code\",\r\n \"error_rc\"\r\n ])\r\n\r\n def run(self, benchmark_its):\r\n for i in range(benchmark_its):\r\n f_values, f_intercepts, f_slopes, grid_values = self.gen_data()\r\n for model in self.step_function_models:\r\n for b_solver in self.b_solvers:\r\n instance = model.instantiate(self.n_its, self.n_intervals, f_values, f_intercepts, f_slopes, grid_values)\r\n try:\r\n results = self.solve(b_solver, instance, model)\r\n output_dict = {\r\n \"benchmark_iteration\": i,\r\n \"model\": model.name,\r\n \"solver\": b_solver.name,\r\n \"lower_bound\": results.problem.lower_bound,\r\n \"upper_bound\": results.problem.upper_bound,\r\n \"time\": results.solver.time,\r\n #\"wall_time\": results.solver.wall_time,\r\n \"status\": results.solver.status,\r\n #\"return_code\": results.solver.return_code,\r\n \"error_rc\": results.solver.error_rc,\r\n }\r\n except Exception as e:\r\n print(e)\r\n output_dict = {\r\n \"benchmark_iteration\": i,\r\n \"model\": model.name,\r\n \"solver\": b_solver.name,\r\n \"lower_bound\": 0,\r\n \"upper_bound\": np.inf,\r\n \"time\": self.time_limit,\r\n #\"wall_time\": results.solver.wall_time,\r\n \"status\": \"aborted\",\r\n #\"return_code\": results.solver.return_code,\r\n \"error_rc\": -1,\r\n }\r\n self.output_df = self.output_df.append(output_dict, ignore_index = True)\r\n print(\"Ended Run \" + str(i))\r\n \r\n def solve(self,b_solver, instance, model):\r\n return b_solver.solver.solve(instance)\r\n \r\n def interpolation(self, f_values, grid_values):\r\n f_slopes = (f_values[:,1:]-f_values[:,:-1])/(grid_values[:,1:]-grid_values[:,:-1])\r\n f_intercepts = f_values[:,:-1] - f_slopes*grid_values[:,:-1]\r\n return (f_intercepts, f_slopes)\r\n\r\n def gen_data(self):\r\n f_values = np.around(self.rng.random((self.n_its,self.n_intervals+1)),4)\r\n grid_values = np.array([np.linspace(0,1,self.n_intervals+1).tolist() for i in range(self.n_its)])\r\n f_intercepts, f_slopes = self.interpolation(f_values, grid_values)\r\n return (f_values,f_intercepts, f_slopes, grid_values)\r\n\r\n def save_output(self, path):\r\n full_path = path + \"it\" + str(self.n_its) + \"_ints\" + str(self.n_intervals) + \".csv\"\r\n self.output_df.to_csv(full_path)\r\n print(\"Saved to \" + full_path)\r\n\r\n def n_vars(self):\r\n _, xi = self.gen_data()\r\n a = np.full((self.n_its, self.n_intervals), 0)\r\n for model in self.step_function_models:\r\n s = self.b_solvers[0]\r\n inst = model.instantiate(self.n_its, self.n_intervals, a, xi)\r\n result = s.solver.solve(inst)\r\n print(model.name, \"Constraints:\", result.problem.number_of_constraints, \"Variables:\", result.problem.number_of_variables, \"Binary:\", result.problem.number_of_binary_variables)\r\n\r\nclass MonotoneBenchmark(Benchmark):\r\n def gen_data(self):\r\n grid_values = np.array([np.linspace(0,1,self.n_intervals+1).tolist() for i in range(self.n_its)])\r\n f_delta = np.around(self.rng.random((self.n_its,self.n_intervals+1)),4)\r\n f_cum = np.cumsum(f_delta, axis = 1)\r\n f_values = 1- np.array([row/row[-1] for row in f_cum])\r\n f_intercepts, f_slopes = self.interpolation(f_values, grid_values)\r\n return (f_values, f_intercepts, f_slopes,grid_values)\r\n \r\n def save_output(self, path):\r\n super().save_output(path + \"Mon_\")\r\n\r\nclass ConcaveBenchmark(Benchmark):\r\n def gen_data(self):\r\n grid_values = np.array([np.linspace(0,1,self.n_intervals+1).tolist() for i in range(self.n_its)])\r\n f_delta = np.around(self.rng.random((self.n_its,self.n_intervals+1)),4)\r\n f_delta_sorted = np.sort(f_delta, axis = 1)\r\n f_cum = np.cumsum(f_delta_sorted, axis = 1)\r\n f_values = 1- np.array([row/row[-1] for row in f_cum])\r\n f_intercepts, f_slopes = self.interpolation(f_values, grid_values)\r\n return (f_values, f_intercepts, f_slopes,grid_values)\r\n\r\n def save_output(self, path):\r\n super().save_output(path + \"Con_\")\r\n\r\n\r\nif __name__ == \"__main__\": \r\n settings = [\r\n {\r\n \"n_its\": 5,\r\n \"n_intervals\": 8,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10\r\n },\r\n {\r\n \"n_its\": 10,\r\n \"n_intervals\": 64,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10\r\n },\r\n {\r\n \"n_its\": 20,\r\n \"n_intervals\": 128,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10\r\n },{\r\n \"n_its\": 25,\r\n \"n_intervals\": 512,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10}\r\n ]\r\n\r\n #Nonmonotone Benchmark\r\n B = Benchmark(**settings[0])\r\n #Monotone Benchmark\r\n B_m = MonotoneBenchmark(**settings[0])\r\n #Concave Benchmark\r\n B_c = ConcaveBenchmark(**settings[0])\r\n #add solvers\r\n gurobi = B_Solver(\"gurobi\")\r\n cplex = B_Solver(\"cplex\")\r\n #add models\r\n\r\n models = [\r\n Indicator_Weak_Concrete(),\r\n Indicator_Strong_Concrete(),\r\n DCC_Concrete(),\r\n CC_Concrete(),\r\n Incremental_Concrete(),\r\n DLog_Concrete(),\r\n Indicator_Layered()\r\n ]\r\n \r\n B.add_solver(gurobi)\r\n B.add_solver(cplex)\r\n for model in models:\r\n B.add_model(model)\r\n\r\n B_m.add_solver(gurobi)\r\n B_m.add_solver(cplex)\r\n\r\n m_models = [\r\n Indicator_Weak_Concrete(),\r\n Indicator_Strong_Concrete(),\r\n DCC_Concrete(),\r\n CC_Concrete(),\r\n Incremental_Concrete(),\r\n DLog_Concrete(),\r\n Indicator_Layered()\r\n ]\r\n \r\n for model in m_models:\r\n B_m.add_model(model)\r\n\r\n\r\n B_c.add_solver(gurobi)\r\n B_c.add_solver(cplex)\r\n \r\n for model in m_models: \r\n B_c.add_model(model)\r\n\r\n Benchmarks = [\r\n B, \r\n B_m,\r\n B_c\r\n ]\r\n\r\n for setting in settings:\r\n for Benchmark in Benchmarks:\r\n Benchmark.set_benchmark_parameters(**setting)\r\n Benchmark.run(5)\r\n Benchmark.save_output(\"data\\\\plin1705\\\\\")\r\n Benchmark.reset_output()\r\n","sub_path":"Stkw_Linear/plin_benchmarking.py","file_name":"plin_benchmarking.py","file_ext":"py","file_size_in_byte":8982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"116212632","text":"import numpy as np\nfrom scipy.optimize import minimize\n\ndef identity(x):\n \"\"\"The identity function\"\"\"\n return x\n\ndef d_identity(x):\n \"\"\"The derivative of the identity function\"\"\"\n return 1.0\n\ndef sigmoid(x):\n \"\"\"The sigmoid function\"\"\"\n return 1.0 / (1.0 + np.exp(-x))\n\ndef d_sigmoid(x):\n \"\"\"The derivative of the sigmoid function\"\"\"\n return sigmoid(x) * (1 - sigmoid(x))\n\nclass Regressor(object):\n\n def __init__(self, g, dg, k, penalize):\n self.g = g\n self.dg = dg\n self.k = k\n self.penalize = penalize\n\n def predict(self, theta, X, grad=False):\n \"\"\"\n Computes dependent variables given theta and training examples X\n\n arguments:\n theta: array of model parameters\n X: matrix of training example features\n\n returns:\n predicted dependent variables for given theta\n \"\"\"\n if np.size(X, 1) != np.size(theta, 0):\n if np.size(X, 0) == np.size(theta, 0):\n X = X.T\n else:\n raise Exception('width X does not match length theta')\n\n z = np.array(X * np.matrix(theta).T).flatten()\n h = self.g(z)\n if grad:\n dh = self.dg(z)\n return h, dh\n else:\n return h\n\n def fit(self, X, y, w=1.0, theta=None, **kwargs):\n \"\"\"\n Finds optimal theta for regression model using scipy minimize function\n\n arguments:\n X: matrix of training example features\n y: array of dependent variable in training set\n w: weights of training examples; can be scalar, meaning all features \n weighted evenly\n theta: initial theta\n kwargs: keyword arguments that will be passed to scipy minimize \n function, e.g. can change opt. algorithm used\n\n returns: True if optimization converged, False otherwise\n \"\"\"\n if np.size(X, 0) != np.size(y, 0):\n if np.size(X, 1) == np.size(y, 0):\n X = X.T\n else:\n raise Exception('length X does not match length y')\n\n if theta is None:\n theta = np.zeros(np.size(X, 1))\n\n if np.size(X, 1) != np.size(theta, 0):\n raise Exception('width X does not match length theta')\n\n result = minimize(self.J, theta, args=(X, y, w), jac=self.grad_J, \n **kwargs)\n \n self.theta = result['x']\n return result['success']\n\n def create_matrix(self, bias, *args):\n \"\"\"\n Given a set of features, create a usable feature matrix, adding bias \n feature if desired.\n\n arguments:\n bias: whether or not a bias column should be prepended to the matrix\n args: feature arrays to be used in model\n\n returns: a feature matrix\n \"\"\"\n n = len(args[0])\n for x in args[1:]:\n assert len(x) == n\n\n out = np.array(args)\n if bias:\n out = np.insert(out, 0, np.ones(n), axis=0)\n \n return np.matrix(out).T\n\nclass LeastSquaresReg(Regressor):\n\n def __init__(self, g=identity, dg=d_identity, k=0.0, penalize=False):\n \"\"\"\n Least squares regression class\n\n arguments:\n g: R^1 -> R^1 link function, e.g. identity\n dg: derivative of link function\n k: parameter cost - can be scalar or array\n penalize: boolean - determines if bias (first) parameter is scaled\n \"\"\"\n super(LeastSquaresReg, self).__init__(g, dg, k, penalize)\n\n def J(self, theta, X, y, w):\n \"\"\"\n Cost function for least squares regression that we are optimizing\n\n arguments:\n theta: parameter set for model being fit\n X: matrix of training example features\n y: array of dependent variable in training set\n w: weights of training examples\n\n returns: cost for given parameters and training set\n \"\"\"\n k = self.k\n m = max(np.sum(w), np.size(X, 0))\n h = self.predict(theta, X)\n res = h - y\n out = 0.5/m * np.dot(w * res, res)\n \n if self.penalize:\n out += k * 0.5/m * np.dot(theta, theta)\n else:\n out += k * 0.5/m * np.dot(theta[1:], theta[1:])\n \n return out\n\n def grad_J(self, theta, X, y, w):\n \"\"\"Gradient of J w.r.t theta\"\"\"\n k = self.k\n m = max(np.sum(w), np.size(X, 0))\n h, dh = self.predict(theta, X, True)\n res = h - y\n grad = 1.0/m * X.T * np.matrix(w * res * dh).T\n grad_cost = k/m * theta\n\n if not self.penalize:\n grad_cost[0] = 0\n \n return np.array(grad).flatten() + grad_cost\n\nclass MaxLikelihoodReg(Regressor):\n\n def __init__(self, g=sigmoid, dg=d_sigmoid, k=0.0, penalize=False):\n \"\"\"\n Maximum likelihood regression class\n\n arguments:\n g: R^1 -> R^1 link function, e.g. sigmoid function\n dg: derivative of link function\n k: parameter cost - can be scalar or array\n penalize: boolean - determines if bias (first) parameter is scaled\n \"\"\"\n super(MaxLikelihoodReg, self).__init__(g, dg, k, penalize)\n\n def J(self, theta, X, y, w):\n \"\"\"\n Cost function for maximum likelihood regression that we are optimizing\n\n arguments:\n theta: parameter set for model being fit\n X: matrix of training example features\n y: array of dependent variable in training set\n w: weights of training examples\n\n returns: cost for given parameters and training set\n \"\"\"\n k = self.k\n m = max(np.sum(w), np.size(X, 0))\n h = self.predict(theta, X)\n out = -1.0/m * (np.dot(y, np.log(h)) + np.dot((w - y), np.log(1 - h)))\n\n if k > 0:\n if self.penalize:\n out += k * 0.5/m * np.dot(theta, theta)\n else:\n out += k * 0.5/m * np.dot(theta[1:], theta[1:])\n\n return out\n\n def grad_J(self, theta, X, y, w):\n \"\"\"Gradient of J w.r.t theta\"\"\"\n k = self.k\n m = max(np.sum(w), np.size(X, 0))\n h, dh = self.predict(theta, X, True)\n res = w * h - y\n div = 1.0 / (h * (1.0 - h))\n grad = 1.0/m * X.T * np.matrix(res * div * dh).T\n grad_cost = k/m * theta\n \n if not self.penalize:\n grad_cost[0] = 0\n\n return np.array(grad).flatten() + grad_cost\n\nclass ClosedFormReg(LeastSquaresReg):\n\n def __init__(self, k=0.0, penalize=False):\n \"\"\"\n Class for the Closed form solution to least squares regression\n\n arguments:\n k: parameter cost - can be scalar or array\n penalize: boolean - determines if bias (first) parameter is scaled\n \"\"\"\n super(ClosedFormReg, self).__init__(identity, d_identity, k, penalize)\n\n def fit(self, X, y, w=1.0):\n \"\"\"\n Finds optimal theta for regression model using closed form solution\n\n arguments:\n X: matrix of training example features\n y: array of dependent variable in training set\n w: weights of training examples; can be scalar, meaning all features \n weighted evenly\n\n returns: True if closed form solution exists, False otherwise\n \"\"\"\n if np.size(X, 0) != np.size(y, 0):\n if np.size(X, 1) == np.size(y, 0):\n X = X.T\n else:\n raise Exception('length X does not match length y')\n\n m = np.size(X, 0)\n n = np.size(X, 1)\n k = self.k\n\n if isinstance(w, int) or isinstance(w, float):\n W = w * np.matrix(np.eye(m))\n else:\n assert len(w) == m\n W = np.matrix(np.diag(w))\n\n if isinstance(k, int) or isinstance(k, float):\n K = k * np.matrix(np.eye(n))\n else:\n assert len(k) == n\n K = np.matrix(np.diag(k))\n\n if not self.penalize:\n K[0, 0] = 0.0\n\n try:\n theta = (X.T * W * X + K).I * X.T * W * np.matrix(y).T\n self.theta = np.array(theta).flatten()\n return True\n except np.linalg.LinAlgError:\n self.theta = np.zeros(n)\n return False","sub_path":"regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":8343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"211107253","text":"from selenium import webdriver\nimport time\n\ndef main(fullPath):\n\n driver = webdriver.Chrome()\n siteName = 'https://www.publix.com/search/recipes?searchTerm='\n recipeClassName = 'content-wrapper'\n loadMoreClassName = 'loading-button'\n cacheName = str(fullPath) + '/sites/publixaprons/publixaprons.txt'\n maxSeen = 50 # how many already seen recipes in a row\n # till it breaks look and stop scraping the site\n\n # loading cache\n with open(cacheName, 'r') as cache:\n existing = cache.read().splitlines()\n\n driver.get(siteName)\n time.sleep(10)\n\n try:\n closePopUp = driver.find_element_by_class_name('icon-close')\n closePopUp.click()\n except:\n print()\n\n seenCombo = 0 # how many in a row the bot has seen rn\n\n while seenCombo < maxSeen:\n recipes = driver.find_elements_by_class_name(recipeClassName)\n print('poggers')\n for recipe in recipes:\n if recipe.get_attribute('href') not in existing:\n print('Adding ' + str(recipe.get_attribute('href'))[45:])\n seenCombo = 0\n\n with open(cacheName, 'a+') as cache:\n existing.append(recipe.get_attribute('href') + '\\n')\n cache.write(recipe.get_attribute('href') + '\\n')\n\n with open(str(fullPath) + '/recipes.txt', 'a+') as masterList:\n masterList.write(recipe.get_attribute('href') + '\\n')\n else:\n print('Alread have ' + str(recipe.get_attribute('href'))[45:])\n seenCombo += 1\n try:\n loadMore = driver.find_element_by_class_name(loadMoreClassName).click()\n time.sleep(5)\n except:\n seenCombo = 999999\n \n\n driver.close()","sub_path":"sites/publixaprons/publixaprons.py","file_name":"publixaprons.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"62705650","text":"\"\"\"\nCreated on Tue Oct 10 16:12:55 2017\n\n@author: cdib\n\"\"\"\n\n# A program to calculate the GCD of two non-negative integers\n\nnumber_a = int(input(\"Enter a number: \"))\nnumber_b = int(input(\"Enter a second number: \"))\n\n\nif number_a == 0:\n GCD = number_b\n \nif number_b == 0:\n GCD = number_a\n\nif number_a == number_b:\n GCD = number_a\n\nif number_b > number_a:\n c = number_a\n number_a = number_b\n number_b = c\n\nif number_a >= number_b and number_b > 0: \n remainder = (number_a % number_b)\n remainder_2 = (number_b % remainder)\n while remainder_2 >= 1:\n remainder_2 = (remainder % remainder_2)\n \n GCD = remainder_2\n\nprint(\"The greatest common divisor of\", number_a, \"and\", number_b, \"is\", GCD)\n \n","sub_path":"GCD.py","file_name":"GCD.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"638987811","text":"import sys\nimport os\nimport threading \nimport atexit\nimport io\nimport msvcrt as m\nimport re\nimport fileinput\n#def hextoascii():\nglobal comment\n\n\nclass str_class(object):\n def __init__(self,clear_line,restline):\n self.clear_line = clear_line\n self.restline = restline\n\n\ndef find_comment(str_object):\n global comment\n if comment:\n start = str_object.restline.find('*/')\n if start ==-1:\n return str_object\n else:\n comment = 0\n if start < len(str_object.restline)-3:\n str_object.restline = str_object.restline[start+2:]\n find_comment(str_object)\n else:\n return str_object\n else: \n start = str_object.restline.find('/*')\n if start == -1:\n str_object.clear_line = str_object.clear_line + str_object.restline\n return str_object\n else :\n if start > 0:\n str_object.clear_line = str_object.clear_line + str_object.restline[:start]\n str_object.restline = str_object.restline[start+2:]\n comment = 1\n start = str_object.restline.find('*/')\n if start ==-1:\n return str_object\n else:\n comment = 0\n if start < len(str_object.restline)-3:\n str_object.restline = str_object.restline[start+2:]\n find_comment(str_object)\n else:\n return str_object\n\n \ndef find_type_and_add_delarate(file_fb_name):\n global comment\n comment = 0\n type_c = 0x00\n num_lines = sum(1 for line in open('handled'+file_fb_name, encoding=\"utf-8\"))\n num_lines=num_lines-1\n try:\n temp_buff = ''\n file_opened = open('handled'+file_fb_name,'r', encoding=\"utf-8\")\n for line in file_opened:\n if '//' in line:\n start = line.find('//')\n line_temp = line[:start]\n else:\n line_temp = line\n clear_line = ''\n str_object = str_class(clear_line,line_temp)\n find_comment(str_object)\n if len(str_object.clear_line):\n in_type =file_fb_name[:-2] + '_IN_type' \n var_type =file_fb_name[:-2] + '_VAR_type' \n out_type =file_fb_name[:-2] + '_OUT_type' \n if in_type in str_object.clear_line:\n type_c = type_c | 0x01\n if var_type in str_object.clear_line:\n type_c = type_c | 0x02\n if out_type in str_object.clear_line:\n type_c = type_c | 0x04\n temp_buff += line\n if num_lines:\n num_lines-=1\n else:\n str_t = 'u32 '+file_fb_name[:-2]+'_var_size(u8 type);\\n'\n temp_buff += str_t\n file_opened.close()\n file_write = open('handled'+file_fb_name,'w', encoding=\"utf-8\")\n file_write.write(temp_buff)\n file_write.close()\n\n except FileNotFoundError: \n sys.stdout.write('dont find '+file_fb_name +'\\n')\n\n return type_c\n\n\ndef add_function():\n fb_have_c = []\n fb_have_h = []\n for current in range(1,126):\n try:\n if (current <= 9):\n fb_name = 'fb0000'+str(current)+'.h'\n fb_name_c = 'fb0000'+str(current)+'.c'\n elif (current <= 99):\n fb_name = 'fb000'+str(current)+'.h'\n fb_name_c = 'fb000'+str(current)+'.c'\n else:\n fb_name = 'fb00'+str(current)+'.h'\n fb_name_c = 'fb00'+str(current)+'.c'\n type_c = find_type_and_add_delarate(fb_name)\n if type_c==0:\n print(\"error fb struct name\")\n add_fb_include(fb_name_c)\n num_lines = sum(1 for line in open('handled'+fb_name_c, encoding=\"utf-8\"))\n num_lines=num_lines-1\n temp_buff = ''\n file_opened = open('handled'+fb_name_c,'r', encoding=\"utf-8\")\n for line in file_opened:\n temp_buff +=line\n if num_lines:\n num_lines=num_lines-1\n else:\n if type_c & 0x01:\n in_str = ' return sizeof('+fb_name[:-2]+'_IN_type);\\n'\n else:\n in_str = ' return 0;\\n'\n if type_c & 0x02:\n out_str = ' return sizeof('+fb_name[:-2]+'_VAR_type);\\n'\n else:\n out_str = ' return 0;\\n'\n if type_c & 0x04:\n var_str = ' return sizeof('+fb_name[:-2]+'_OUT_type);\\n'\n else:\n var_str = ' return 0;\\n'\n\n str_t = '/*\\n type 0 - IN,1- VAR,2 - OUT\\n return size struct, or 0 if struct not\\n*/'+\\\n ' unsigned int '+fb_name[:-2]+'_var_size(unsigned char type) {\\n'+\\\n ' switch(type){\\n'+\\\n ' case(0):\\n'+\\\n in_str+\\\n ' case(1):\\n'+\\\n out_str+\\\n ' case(2):\\n'+\\\n var_str+\\\n ' default:\\n'+\\\n ' return 0;\\n'+\\\n ' }\\n'+\\\n '}\\n'\n temp_buff += str_t \n file_opened.close()\n file_write = open('handled'+fb_name_c,'w', encoding=\"utf-8\")\n file_write.write(temp_buff)\n file_write.close()\n \n except FileNotFoundError: \n sys.stdout.write('dont find '+'handled'+fb_name +'\\n')\ndef add_fb_include(fb_name):\n message = ''\n kernel_finded = 0\n include_fb_finded = 0\n try:\n temp_buff = ''\n file_opened = open('handled'+fb_name,'r', encoding=\"utf-8\")\n print('add_fb_i')\n for line in file_opened:\n include_kernel = re.compile('^\\s*\\#include\\s+[\\<\\\"]\\.\\.\\/kernel\\.h[\\>\\\"]',re.ASCII)\n kernel_find = include_kernel.match(line)\n if kernel_find:\n kernel_finded = 1\n include_fb = re.compile('^\\s*\\#include\\s+[\\<\\\"]'+'handled'+fb_name[:-2]+'\\.h[\\>\\\"]',re.ASCII)\n include_fb_find = include_fb.match(line)\n if include_fb_find:\n include_fb_finded = 1\n func = re.compile('^\\s*void\\s+'+fb_name[:-2]+'\\_exec',re.ASCII)\n func_find = func.match(line)\n if func_find:\n if kernel_finded:\n message = 'find #include kernel '+fb_name +'\\n'\n else:\n message = 'didnt find #include kernel '+fb_name +'\\n'\n temp_buff += '#include \\\"../kernel.h\\\"\\n'\n if include_fb_finded:\n message = 'find #include fb '+fb_name +'\\n'\n else:\n message = 'didnt find #include fb '+fb_name +'\\n'\n temp_buff +='#include \\\"'+'handled'+fb_name[:-2]+'.h\\\"\\n'\n temp_buff += line\n else:\n temp_buff += line\n file_opened.close()\n file_write = open('handled'+fb_name,'w', encoding=\"utf-8\")\n file_write.write(temp_buff)\n file_write.close()\n\n except FileNotFoundError: \n sys.stdout.write('dont find '+name +'\\n')\n sys.stdout.write(message)\n\ndef main():\n add_function()\n\nif __name__ == \"__main__\":\n 'add function returned size struct FB'\n main()\n","sub_path":"FB/fb_add_size_function.py","file_name":"fb_add_size_function.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"113961917","text":"import dataclasses\n\nfrom . import ValidationError, errors\nfrom .main import create_model, validate_model\n\n\ndef _pydantic_post_init(self):\n d = validate_model(self.__pydantic_model__, self.__dict__)\n object.__setattr__(self, '__dict__', d)\n object.__setattr__(self, '__initialised__', True)\n if self.__post_init_original__:\n self.__post_init_original__()\n\n\ndef _validate_dataclass(cls, v):\n if isinstance(v, cls):\n return v\n elif isinstance(v, (cls, list, tuple)):\n return cls(*v)\n elif isinstance(v, dict):\n return cls(**v)\n else:\n raise errors.DataclassTypeError(class_name=cls.__name__)\n\n\ndef _get_validators(cls):\n yield cls.__validate__\n\n\ndef setattr_validate_assignment(self, name, value):\n if self.__initialised__:\n d = dict(self.__dict__)\n d.pop(name)\n value, error_ = self.__pydantic_model__.__fields__[name].validate(value, d, loc=name)\n if error_:\n raise ValidationError([error_])\n\n object.__setattr__(self, name, value)\n\n\ndef _process_class(_cls, init, repr, eq, order, unsafe_hash, frozen, config):\n post_init_original = getattr(_cls, '__post_init__', None)\n if post_init_original and post_init_original.__name__ == '_pydantic_post_init':\n post_init_original = None\n _cls.__post_init__ = _pydantic_post_init\n cls = dataclasses._process_class(_cls, init, repr, eq, order, unsafe_hash, frozen)\n\n fields = {name: (field.type, field.default) for name, field in cls.__dataclass_fields__.items()}\n cls.__post_init_original__ = post_init_original\n\n cls.__pydantic_model__ = create_model(cls.__name__, __config__=config, **fields)\n\n cls.__initialised__ = False\n cls.__validate__ = classmethod(_validate_dataclass)\n cls.__get_validators__ = classmethod(_get_validators)\n\n if cls.__pydantic_model__.__config__.validate_assignment and not frozen:\n cls.__setattr__ = setattr_validate_assignment\n\n return cls\n\n\ndef dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, config=None):\n \"\"\"\n Like the python standard lib dataclasses but with type validation.\n\n Arguments are the same as for standard dataclasses, except for validate_assignment which has the same meaning\n as Config.validate_assignment.\n \"\"\"\n\n def wrap(cls):\n return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, config)\n\n if _cls is None:\n return wrap\n\n return wrap(_cls)\n","sub_path":"pydantic/dataclasses.py","file_name":"dataclasses.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"115411205","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nmain script for time CD\n\ntrainfile has lines of the form:\n tok1,tok2,pmi\n\nCreated on Thu Nov 10 13:10:42 2016\n\"\"\"\n\nimport ast\nimport os\nimport time\n\nimport numpy as np\n\nimport util_timeCD as util\nfrom util_shared import set_base_indent_level, iprint, get_time_diff\n\n\n# ----------------------------------------------------------------------------\n\n\ndef print_train_params(rank, lam, tau, gam, emph, num_iterations):\n \"\"\"Dump parameter values.\n\n :param rank: rank/dimension of embeddings (?)\n :param lam: frob regularizer\n :param tau: smoothing regularizer / time regularizer\n :param gam: forcing regularizer / symmetry regularizer\n :param emph: emphasize the nonzero\n :param num_iterations: number of iterations over data\n\n \"\"\"\n iprint(\"~ rank = {}\".format(rank))\n iprint(\"~ frob regularizer = {}\".format(lam))\n iprint(\"~ time regularizer = {}\".format(tau))\n iprint(\"~ symmetry regularizer = {}\".format(gam))\n iprint(\"~ emphasize param = {}\".format(emph))\n iprint(\"~ total iterations = {}\".format(num_iterations))\n\n\ndef do_training(\n lam,\n tau,\n gam,\n emph,\n rank,\n time_range,\n num_iters,\n num_words,\n result_dir,\n data_dir,\n batch_size=None,\n data_file=None,\n randomize_times=False,\n savepoint_iteration=True,\n savepoint_iter_time=False,\n):\n \"\"\"Do a complete training.\n Able to save current training state per iteration and timepoint and restore\n training from there.\n\n :param lam: frob regularizer\n :param tau: smoothing regularizer / time regularizer\n :param gam: forcing regularizer / symmetry regularizer\n :param emph: emphasize the nonzero\n :param rank: ranke/dimension of embeddings\n :param time_range: range of time points\n :param num_iters: number of training iterations\n :param num_words: number of words in vocabulary\n :param result_dir: folder to store savepoints and final results in\n :param data_dir: folder with trainings data (PMI word pairs)\n :param batch_size: size for batching (Default value = None)\n :param data_file: if given a file with initial embeddings (Default value = None)\n :param randomize_times: Randomize timepoints in timerange while training (Default value = False)\n :param savepoint_iteration: store current training results per iteration and try to retore from there (Default value = True)\n :param savepoint_iter_time: store current training results per iteration and timepoint and try to restore there (Default value = False)\n\n \"\"\"\n set_base_indent_level()\n\n savefile = \"L{lam}T{tau}G{gam}A{emph}\".format(lam=lam, tau=tau, gam=gam, emph=emph)\n savefile = os.path.join(result_dir, savefile)\n\n # add inclusive end timepoint ...\n # TODO: think of something better ...\n time_range = range(time_range[0], time_range[-1] + 2)\n\n iprint(\"* Initializing ...\")\n if data_file is None:\n Ulist, Vlist = util.init_emb_random(num_words, time_range, rank)\n else:\n Ulist, Vlist = util.init_emb_static(data_file, time_range)\n # print(Ulist)\n # print(Vlist)\n\n iprint(\"* Preparing batch indices ...\")\n if batch_size is not None and batch_size < num_words:\n b_ind = util.make_batches(num_words, batch_size)\n else:\n b_ind = [range(num_words)]\n\n # --------------------------------\n\n start_time = time.time()\n\n # sequential updates\n for iteration in range(num_iters):\n iprint(\"-\" * 78)\n # print_train_params(rank, lam, tau, gam, emph, num_iters)\n\n # try restoring previous training state\n if savepoint_iteration:\n Ulist2, Vlist2 = util.try_load_UV(savefile, iteration)\n if Ulist2 and Vlist2:\n iprint(\"* Iteration {} loaded succesfully.\".format(iteration), level=1)\n Ulist, Vlist = Ulist2, Vlist2\n continue\n\n loss = 0 # unused\n\n times = time_range\n # shuffle times\n if randomize_times:\n # TODO: keep times for even iterations un-randomized?\n if iteration > 0 and iteration < (num_iters - 1):\n times = np.random.permutation(time_range)\n\n for time_step, time_period in enumerate(times): # select next/a time\n time_ittm_start = time.time()\n iprint(\n \"* Iteration {} ({}/{}), Time {} ({}/{}) ...\".format(\n iteration,\n iteration + 1,\n num_iters,\n time_period,\n time_step + 1,\n len(times),\n ),\n end=\"\",\n flush=True,\n level=1,\n )\n\n if savepoint_iter_time:\n Ulist2, Vlist2, times2 = util.try_load_UV(\n savefile, iteration, time_step\n )\n if Ulist2 and Vlist2 and times2:\n iprint(\n \"* Iteration {}, Time {} loaded succesfully\".format(\n iteration, time_step\n ),\n level=1,\n )\n Ulist, Vlist, times = Ulist2, Vlist2, times2\n continue\n\n pmi = util.load_train_data(data_dir, num_words, time_range, time_period)\n\n util.do_train_step(\n Ulist,\n Vlist,\n pmi,\n b_ind,\n time_step,\n len(times),\n lam,\n tau,\n gam,\n emph,\n rank,\n )\n\n if savepoint_iter_time:\n util.save_UVT(Ulist, Vlist, times, savefile, iteration, time_step)\n\n time_ittm_end = time.time()\n print(\" {:.2f} sec\".format(time_ittm_end - time_ittm_start))\n\n print(\"* Total time elapsed = {}\".format(get_time_diff(start_time)))\n\n # save\n if savepoint_iteration:\n util.save_UV(Ulist, Vlist, savefile, iteration)\n\n iprint(\"* Save results to: {}\".format(result_dir))\n util.save_embeddings(\"{}/embeddings_Unew.mat\".format(result_dir), Ulist)\n util.save_embeddings(\"{}/embeddings_Vnew.mat\".format(result_dir), Vlist)\n util.save_embeddings_split(\n \"{}/embeddings.mat\".format(result_dir), Ulist, time_range\n )\n\n\ndef parse_args():\n \"\"\"Parse training parameter from commandline args.\n Set defaults if not given.\n\n :returns: parameters\n\n \"\"\"\n import argparse\n\n # Default arguments:\n num_iters = 5 # total passes over the data\n lam = 10.0 # frob regularizer\n gam = 100.0 # forcing regularizer\n tau = 50.0 # smoothing regularizer\n rank = 50 # rank\n num_words = 20936 # number of words in vocab (11068100/20936 for ngram/nyt)\n batch_size = -1 # batch size, -1 for whole\n emph = 1.0 # emphasize the nonzero\n data_file = \"data/emb_static.mat\"\n result_dir = \"results\"\n data_dir = \"data\"\n time_range = (\n 1990,\n 2016,\n ) # range, total number of time points (20/range(27) for ngram/nyt)\n\n # Parse arguments:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-r\", \"--rank\", type=int, default=rank, help=\"rank\")\n parser.add_argument(\n \"--iters\", type=int, default=num_iters, help=\"iterations over data\"\n )\n parser.add_argument(\"--lam\", type=float, default=lam, help=\"frob regularizer\")\n parser.add_argument(\n \"--tau\",\n type=float,\n default=tau,\n help=\"smoothing regularizer / time regularizer\",\n )\n parser.add_argument(\n \"--gam\",\n type=float,\n default=gam,\n help=\"forcing regularizer / symmetry regularizer\",\n )\n parser.add_argument(\n \"--emph\", type=float, default=emph, help=\"emphasize the nonzero\"\n )\n parser.add_argument(\n \"-n\",\n \"--num-words\",\n type=int,\n default=num_words,\n help=\"number of words in vocabulary\",\n )\n parser.add_argument(\n \"--time-range\",\n type=str,\n default=str(time_range),\n help='time range (years?), format: \"year_start,year_end\" default: {}'.format(\n str(time_range)\n ),\n )\n parser.add_argument(\n \"-b\",\n \"--batch-size\",\n type=int,\n default=batch_size,\n help=\"Batch size, -1 for no batches\",\n )\n parser.add_argument(\n \"--init-weights-file\",\n type=str,\n default=data_file,\n help=\"file with initial static weights; if missing then random initialization\",\n )\n parser.add_argument(\n \"--init-random-weights\",\n action=\"store_true\",\n help=\"initialize with random weights or load static embedding matrix (e. g. previous result)\",\n )\n parser.add_argument(\n \"--randomize-timepoints\",\n action=\"store_true\",\n help=\"randomize timepoints in timerange while training\",\n )\n parser.add_argument(\n \"--result-dir\",\n default=result_dir,\n help=\"Folder with result and intermediate training files, default: {}\".format(\n result_dir\n ),\n )\n parser.add_argument(\n \"--data-dir\",\n default=data_dir,\n help=\"Folder with data files, PMI word pairs, wordlists etc., default: {}\".format(\n data_dir\n ),\n )\n parser.add_argument(\n \"--save-per-iteration\",\n action=\"store_true\",\n default=True,\n help=\"store results per iteration, will use existing results to skip finished iterations, \"\n \"always enabled ...\",\n )\n parser.add_argument(\n \"--save-per-iteration-time\",\n action=\"store_true\",\n default=False,\n help=\"store results per iteration and time\",\n )\n args = parser.parse_args()\n\n if args.init_random_weights:\n args.init_weights_file = None\n\n try:\n time_range2 = range(*ast.literal_eval(args.time_range))\n args.time_range = time_range2\n except Exception as ex:\n iprint(\"! Default to default value for time_range, {}\".format(ex))\n args.time_range = range(*time_range)\n\n if args.batch_size <= 0:\n args.batch_size = args.num_words\n\n return args\n\n\nif __name__ == \"__main__\":\n #: parse arguments, use defaults\n set_base_indent_level()\n args = parse_args()\n\n #: warn if no savepoints\n if not (args.save_per_iteration or args.save_per_iteration_time):\n raise Exception(\"Should somehow store intermediate results ...!\")\n\n # make results dir\n if not os.path.exists(args.result_dir):\n iprint(\"! Make results dir: {}\".format(args.result_dir))\n os.mkdir(args.result_dir)\n\n # dump parameters\n iprint(\"* Starting training with following parameters:\")\n print_train_params(args.rank, args.lam, args.tau, args.gam, args.emph, args.iters)\n iprint(\n \"* There are a total of {} words and {} time points.\".format(\n args.num_words, args.time_range\n )\n )\n\n iprint(\"=\" * 78)\n # print(args)\n\n # train\n do_training(\n args.lam,\n args.tau,\n args.gam,\n args.emph,\n args.rank,\n args.time_range,\n args.iters,\n args.num_words,\n args.result_dir,\n args.data_dir,\n batch_size=args.batch_size,\n data_file=args.init_weights_file,\n randomize_times=args.randomize_timepoints,\n savepoint_iteration=args.save_per_iteration,\n savepoint_iter_time=args.save_per_iteration_time,\n )\n\n iprint(\"* Done.\")\n","sub_path":"train_model/train_timeCD.py","file_name":"train_timeCD.py","file_ext":"py","file_size_in_byte":11539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"207515174","text":"# coding: utf-8\n\n\"\"\"\nA tokenizer for English and Japanese texts via sentencepiece\n\n- the coressponding model name is sp_uncase_en_ja_40000\n- the sentencepiece model fitted with enwiki and jawiki contents, they were jointly used\n- uncased 40000 tokens (16 reserved tokens)\n- a wrapper class used in BERT repository, FullTokenizer, was adapted.\n\"\"\"\n\n\nimport re\nimport unicodedata\nimport sentencepiece as sp\n\n\nPATH_PREFIX = __file__.strip('.py')\n\n\nclass FullTokenizer(object):\n \n TOKEN_UNK=''\n TOKEN_SPACE='\\u2581'\n \n @staticmethod\n def load_dict(file_path):\n \"\"\"\n Assumes a tab splitted file where each vocab is the first column of rows.\n Vocab indexes were decided with the order of apperance.\n return:\n vocab: token dict -> idx, inv_vocab: idx -> token dict\n \"\"\"\n \n # We don't use csv library to read .vocab but read line by line\n # because sp don't escape special characters when outputing it\n with open(file_path, 'r', encoding='utf-8') as f:\n lines = [_ for _ in f.read().split('\\n') if len(_) > 0]\n vocab_list = [_.split('\\t')[0] for _ in lines]\n \n vocab = {v:i for i, v in enumerate(vocab_list)}\n inv_vocab = {i:v for i, v in enumerate(vocab_list)}\n \n return vocab, inv_vocab\n \n def __init__(self, model_file=None, vocab_file=None, mapping=None, **kwargs):\n \"\"\"\n initializes a tokenizer\n args:\n model_file: path to a .model file\n vocab_file: path to a .vocab file\n \"\"\"\n \n if 'do_lower_case' in kwargs:\n raise ValueError('This tokenizer supports uncased text only.')\n \n self.prefix = PATH_PREFIX\n \n model_file = model_file or (self.prefix + '.model')\n vocab_file = vocab_file or (self.prefix + '.vocab')\n \n self.tokenizer = SentencePieceTokenizer(model_file)\n self.vocab, self.inv_vocab = self.load_dict(vocab_file)\n self.unk_id = self.vocab[self.TOKEN_UNK]\n \n if mapping is not None:\n self.rewrite_dict(mapping)\n \n def tokenize(self, text, as_ids=False, remove_spaces=False):\n tokens = self.tokenizer.tokenize(text)\n if remove_spaces:\n tokens = list(filter(lambda t: t!=self.TOKEN_SPACE, tokens))\n if as_ids:\n return self.convert_tokens_to_ids(tokens)\n return tokens\n \n def __call__(self, *args, **kwargs):\n return self.tokenize(*args, **kwargs)\n \n def convert_tokens_to_ids(self, tokens):\n return [self.vocab.get(_, self.unk_id)for _ in tokens]\n\n def convert_ids_to_tokens(self, ids):\n return [self.inv_vocab.get(_, self.TOKEN_UNK)for _ in ids]\n \n def rewrite_dict(self, mapping):\n \"\"\"\n Rewrites vocab and inv_vocab dict accroding to mapping.\n This don't affect the sentencepeice model.\n For example, after you rewriting 'unused_0' to '[CLS]',\n convert_tokens_to_ids('[CLS]') will return [3] (the id that unsed_0 was mapped)\n but tokenize('[CLS]abc[$]') will not return ['[CLS]', ...].\n args:\n mapping: a dict {'before_rewrite_vocab':'after_vocab', ...}\n \"\"\"\n cannot_change = ['', '', '\\u2581']\n \n for k, v in mapping.items():\n if k in cannot_change:\n raise ValueError('vocab %s cannot be changed.'%(k))\n if not (k in self.vocab):\n raise ValueError('vocab %s does not exists in current dict.'%(k))\n if v in self.vocab:\n raise ValueError('vocab %s already exists.'%(v))\n \n for k, v in mapping.items():\n i = self.vocab[v] = self.vocab.pop(k)\n self.inv_vocab[i] = v\n \n def summary(self):\n print('path_prefix=%s'%(self.path_prefix))\n print('num_of_vocab=%d'%(len(self.vocab)))\n\n\nclass SentencePieceTokenizer(object):\n \n nmt_norm_map = str.maketrans({\n # SPACES\n '\\u0009':'\\u0020', # TAB\n '\\u000A':'\\u0020', # LINE FEED\n '\\u000C':'\\u0020', # FORM FEED\n '\\u000D':'\\u0020', # CARRIAGE RETURN\n '\\u1680':'\\u0020', # OGHAM SPACE MARK\n '\\u200B':'\\u0020', # ZERO WIDTH SPACE\n '\\u200E':'\\u0020', # LEFT-TO-RIGHT MARK\n '\\u200F':'\\u0020', # RIGHT-TO-LEFT MARK\n '\\u2028':'\\u0020', # LINE SEPARATOR\n '\\u2029':'\\u0020', # PARAGRAPH SEPARATOR\n '\\u2581':'\\u0020', # LOWER ONE EIGHT BLOCK\n '\\uFEFF':'\\u0020', # ZERO WIDTH NO-BREAK\n '\\uFFFD':'\\u0020', # REPLACEMENT CHARACTER\n '\\u200C':'\\u0020', # ZERO WIDTH NON-JOINER\n '\\u200D':'\\u0020', # ZERO WIDTH JOINER\n \n # Ascii Control characters\n '\\u0001':'',\n '\\u0002':'',\n '\\u0003':'',\n '\\u0004':'',\n '\\u0005':'',\n '\\u0006':'',\n '\\u0007':'',\n '\\u0008':'',\n '\\u000B':'',\n '\\u000E':'',\n '\\u000F':'',\n '\\u0010':'',\n '\\u0011':'',\n '\\u0012':'',\n '\\u0013':'',\n '\\u0014':'',\n '\\u0015':'',\n '\\u0016':'',\n '\\u0017':'',\n '\\u0018':'',\n '\\u0019':'',\n '\\u001A':'',\n '\\u001B':'',\n '\\u001C':'',\n '\\u001D':'',\n '\\u001E':'',\n '\\u001F':'',\n \n # ..\n '\\u007F':'',\n '\\u008F':'',\n '\\u009F':'', \n })\n \n @classmethod\n def normalize_with_nmt_NFKC(\n cls,\n text, \n treat_whitespace_as_suffix_=False, \n add_dummy_prefix=True, \n remove_extra_whitespaces=True, \n escape_whitespaces=True,\n do_lower_case=True,\n ):\n \"\"\"\n An emulation of sp normalizer with nmt NFKC.\n This method is not required before inputing tokens into the sp tokenizer because it normalize them by itself.\n You can know in advance what the whole string of the tokenized text will be.\n \"\"\"\n \n # custom mapping for nmt\n text = text.translate(cls.nmt_norm_map)\n # tilde protection (storing)\n tildes = filter(lambda c: c == '\\uFF5E' or c == '\\u007E', text)\n # nfkc normalization\n text = unicodedata.normalize('NFKC', text)\n # tilde protection (restoring)\n text = ''.join([c if c != '\\u007E' else next(tildes) for c in text])\n \n # triming extra spaces\n if remove_extra_whitespaces:\n text = re.sub('\\u0020+', '\\u0020', text.strip())\n # dummy space\n if add_dummy_prefix:\n if treat_whitespace_as_suffix_:\n text = text + '\\u0020'\n else:\n text = '\\u0020' + text\n # escaping spaces\n if escape_whitespaces:\n text = text.replace('\\u0020', '\\u2581')\n \n # do_lower_case which is a part of BERT script\n if do_lower_case:\n text = text.lower()\n return text\n \n def __init__(self, model_file=None, enabled_sampling=False):\n \n self.tokenizer = sp.SentencePieceProcessor()\n if not self.tokenizer.Load(model_file):\n raise Exception('Failed to load a model you specified: %s'%(model_file))\n \n self.enabled_sampling = enabled_sampling\n self.sampling_nbest_size = -1\n self.sampling_alpha = 0.1\n \n def tokenize(self, text):\n \n text = text.lower()\n \n if self.enabled_sampling:\n output_tokens = self.tokenizer.SampleEncodeAsPieces(\n text, \n nbest_size=self.sampling_nbest_size, \n alpha=self.sampling_alpha,\n )\n else:\n output_tokens = self.tokenizer.EncodeAsPieces(text)\n \n return output_tokens\n\n","sub_path":"sp_uncase_en_ja_40000/sp_uncase_en_ja_40000.py","file_name":"sp_uncase_en_ja_40000.py","file_ext":"py","file_size_in_byte":8070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180788203","text":"from tree import Tree\r\nfrom tree import TreeNode\r\nfrom operator import itemgetter\r\nfrom calculator import Calculator\r\n\r\ndef print_list(list):\r\n list_string = ''\r\n for item in list:\r\n list_string += str(item) + '\\t'\r\n print(list_string)\r\n\r\nsymbol_set = set(r'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')\r\nnumerics_set = set(r'1234567890. ')\r\noperators_set = set(r'+-*/() ')\r\n\r\nuser_input = ''\r\ntree = None\r\ncalc = Calculator()\r\n\r\nprint()\r\n\r\nwhile user_input != 'exit':\r\n user_input = input()\r\n\r\n if len(user_input) > 4 and user_input[0:4] == 'tree':\r\n current_item = ''\r\n for char in user_input[4:]:\r\n if char in symbol_set:\r\n current_item += char\r\n tree = Tree(current_item)\r\n elif len(user_input) > 3 and user_input[0:3] == 'add':\r\n current_item = ''\r\n parent = ''\r\n children = []\r\n for char in user_input[4:]:\r\n if char in symbol_set:\r\n current_item += char\r\n elif char == ':':\r\n parent = current_item\r\n current_item = ''\r\n elif char == ',':\r\n children.append(current_item)\r\n current_item = ''\r\n if current_item != '':\r\n children.append(current_item)\r\n current_item = ''\r\n if parent != '':\r\n for child in children:\r\n tree.add_node(parent, child)\r\n elif len(user_input) > 4 and user_input[0:5] == 'print':\r\n if tree == None:\r\n print('Дерево пусте!\\n')\r\n continue\r\n print(tree.root)\r\n elif len(user_input) > 8 and user_input[0:9] == 'postorder':\r\n if tree == None:\r\n print('Дерево пусте!\\n')\r\n continue\r\n print_list(tree.get_postorder_list())\r\n else:\r\n invalid_input = False\r\n for item in user_input:\r\n if item in operators_set or item in numerics_set:\r\n continue\r\n else:\r\n invalid_input = True\r\n break\r\n\r\n if invalid_input:\r\n print('Invalid input!')\r\n continue\r\n\r\n calc.set_infix_string(user_input)\r\n postfix = calc.get_postfix_notation()\r\n memory = []\r\n i = 0\r\n while len(postfix) > i:\r\n current = postfix[i]\r\n if current in operators_set:\r\n node = TreeNode(current)\r\n child2 = memory.pop()\r\n child1 = memory.pop()\r\n child1.set_parent(node)\r\n child2.set_parent(node)\r\n node.add_child(child1)\r\n node.add_child(child2)\r\n memory.append(node)\r\n else:\r\n node = TreeNode(current)\r\n memory.append(node)\r\n i += 1\r\n tree = Tree('0')\r\n tree.root = memory.pop()\r\n print(tree.root)\r\n print('result:', calc.calculate())\r\n print()","sub_path":"Trees/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"454390134","text":"from TTTM import dbConn\nfrom TTTM.db import genres\nfrom sqlalchemy import select\n\ndef get_genre(genre=None):\n try:\n a = dbConn.connect().execute(select([genres]).where(genres.c.name == genre))\n rsp = a.fetchone()\n a.close()\n return rsp\n except Exception as e:\n print(e)\n return None\n\ndef get_genre_by_id(genre_id=None):\n try:\n a = dbConn.connect().execute(select([genres]).where(genres.c.genre_id == genre_id))\n rsp = a.fetchone()\n a.close()\n return rsp\n except Exception as e:\n print(e)\n return None\n\ndef add_genre(genre=None):\n try:\n ins = genres.insert().values(name=genre)\n i = dbConn.connect().execute(ins)\n i.close()\n return get_genre(genre=genre)\n except Exception as e:\n print(e)\n return None\n","sub_path":"build/lib/TTTM/db/GenreUtil.py","file_name":"GenreUtil.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"218390960","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n The functions in this module are meant for one of two purposes:\n 1. Parse text strings of nutrition data into dictionaries\n 2. Convert dictionaries of parsed nutrition data into a matrix\n'''\n\nfrom bs4 import BeautifulSoup\nfrom difflib import SequenceMatcher\nfrom lxml import etree\nfrom nutClasses import *\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom textwrap import indent\nimport csv, datetime, itertools, json, re, requests, string, sys\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\nimport pprint as pt\n\n########################################################################\n### Universal variables ################################################\n########################################################################\n\nUserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0)'+\\\n ' Gecko/20100101 Firefox/56.0'\nHeaders = { 'User-Agent': UserAgent}\n\n########################################################################\n### Functions & Variables ##############################################\n########################################################################\n\nscap = string.capwords\n\ndef colorize(text, color):\n '''\n color must be a `style`-class color or an escaped ANSI color code, e.g., \"\\033[30m\"\n '''\n coloredText = color + text + style.RESET\n return coloredText\n\ndef getLinksList(rootUrl, dogsUrl, xpathDogsLink):\n R = requests.get(dogsUrl, headers=Headers)\n if False:\n # bs can't parse xpath reliably\n soup = BeautifulSoup(R.text, 'html.parser')\n resultsObj = soup.select(xpathDogsLink)\n linksList = [rootUrl + obj.attrs['href'] for obj in resultsObj]\n if True:\n # etree can't access urls directly\n htmlparser = etree.HTMLParser()\n tree = etree.fromstring(R.text, htmlparser)\n resultsObj = tree.xpath(xpathDogsLink)\n linksList = [rootUrl + obj.attrib['href'] for obj in resultsObj]\n if False:\n # I don't want to use selenium\n pass\n return linksList\n\ndef getDogInfo(linksList, xpathDogName, xpathNutrition):\n driver = webdriver.Safari()\n li = []\n htmlDic = {}\n nutDic = {}\n for link in linksList:\n driver.get(link)\n\n pageSource = driver.page_source\n elementDogName = driver.find_element_by_xpath(xpathDogName)\n dogName = elementDogName.text\n li.append(dogName)\n try:\n elementNutrition = driver.find_element_by_xpath(xpathNutrition)\n except:\n print(f'An exception ocurred for this hot dog item: \"{dogName}\"\\n\\tURL: {link}\\n\\tAn exception ocurred while locating the nutrition element.')\n t, _, _ = sys.exc_info()\n exceptionName = t.__name__\n if exceptionName == 'NoSuchElementException':\n print(f'\\tException: The hot dog item has no nutrition information.') # Some Oscar Mayer hot dogs do not have nutrition info up\n errorText = 'The nutrition string could not be found by xpath for this dog.'\n elementNutrition = dummyElement(text=errorText)\n else:\n raise\n\n urlName = link.split('/')[-1]\n nutritionString = elementNutrition.text.lower()\n\n htmlDic[dogName] = {'url': urlName,\\\n 'pageSource': pageSource}\n nutDic[dogName] = [urlName, nutritionString]\n\n return (htmlDic, nutDic)\n\ndef nutritionFeature():\n '''\n Parametrize nutrition feature. E.g., \"Calories\" or \"Iron\"\n '''\n pass\n\n# each reDic for a hotdog brand assigns the RE for a nutrition feature to an reGroup, depending on what the expected output is. So far they are defined below:\n# reGroup1: q units mass units\n# reGroup2: q\n# reGroup3: mass units\n# reGroup4: mass units pct\n# reGroup5: pct\n# reGroup6: q units\n\n# Method B:\n# Instead of using these groups, I should change the dictionary keys in the \"elif mo != None:\" block to 'q#' and 'q#units', where \"#\" is an integer. After all, a mass is just a type of quantity (or number), and so is percentage a percentage.\n# Result: This won't work, because different hot dogs will have different combinations of mass and percentages. E.g., one hot dog may have percentage for cholesterol, another may have only mass. So When the results are merged, under q1units they will have pct and mass. This will make sifting through the data hard. It would be better if the columns continue to be labeld by the nutritional aspect. What we should have is a large matrix that has columns for all possible nutritional aspects (which aren't that many, really) and then populate that matrix from the parsed nutrition dictionary, instead of creating the matrix from the dictionary keys. This method might have a lot of empty values, but is better, programmatically.\n\nreDic_ballpark = {'reGroup1' : ['(Serving Size) ([0-9.]+) (Frank) \\(([0-9.]+)(g)\\)'],\\\n 'reGroup2' : ['(Servings per Container) ([0-9.]+)',\\\n 'Amount Per serving: (Calories) ([0-9.]+)',\\\n '(Calories from Fat) ([0-9.]+)'],\\\n 'reGroup3' : ['(Trans Fat) ([0-9.]+)(g)',\\\n '(Fiber) ([0-9.]+)(g)',\\\n '(Sugars) ([0-9.]+)(g)'],\\\n 'reGroup4' : ['(Total Fat) ([0-9.]+)(g) \\(([0-9.]+)(%) DV\\)',\\\n '(Saturated Fat) ([0-9.]+)(g) \\(([0-9.]+)(%) DV\\)',\\\n '(Cholesterol) ([0-9.]+)(mg) \\(([0-9.]+)(%) DV\\)',\\\n '(Sodium) ([0-9.]+)(mg) \\(([0-9.]+)(%) DV\\)',\\\n '(Potassium) ([0-9.]+)(mg) \\(([0-9.]+)(%) DV\\)',\\\n '(Total Carbohydrates) ([0-9.]+)(g) \\(([0-9.]+)(%) DV\\)',\\\n '(Protein) ([0-9.]+)(g)\\s*\\(*([0-9.]*)'],\\\n 'reGroup5' : ['(Vitamin A) ([0-9.]+)(%)',\\\n '(Vitamin C) ([0-9.]+)(%)',\\\n '(Calcium) ([0-9.]+)(%)',\\\n '(Iron) ([0-9.]+)(%)']}\n\n# Since 'Cholesterol' and 'Total Carbohydrates' are given without units, we treat them as a unitless quantities and assign them to reGroup2\nreDic_oscarmayer = {'reGroup2' : ['(Calories)[\\s]+([0-9]+)[\\s]+([a-zA-Z]+)',\\\n '(Calories From Fat)[\\s]+([0-9]+)[\\s]+([a-zA-Z]+)',\\\n '(Cholesterol)[\\s]+([0-9.]+)',\\\n '(Total Carbohydrates)[\\s]+([0-9.]+)'],\\\n 'reGroup3' : ['(Serving Size)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)',\\\n '(Total Fat)[\\s]+([0-9]+)[\\s]+([a-zA-Z]+)',\\\n '(Saturated Fat)[\\s]+([0-9]+)[\\s]+([a-zA-Z]+)',\\\n '(Sodium)[\\s]+([0-9]+)[\\s]+([a-zA-Z]+)',\\\n '(Dietary Fiber)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)',\\\n '(Sugars)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)',\\\n '(Protein)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)'],\\\n 'reGroup4' : ['(Vitamin C)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)[\\s]+([0-9.]+)',\\\n '(Vitamin D)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)[\\s]+([0-9.]+)',\\\n '(Calcium)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)[\\s]+([0-9.]+)',\\\n '(Iron)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)[\\s]+([0-9.]+)',\\\n '(Potassium)[\\s]+([0-9.]+)[\\s]+([a-zA-Z]+)[\\s]+([0-9.]+)'],\\\n 'reGroup1' : [], 'reGroup5' : []}\n\ndef parseNutDic(nutDic, reDic):\n '''\n Parses nutrition information based on a list of regular expressions (REs). REs are grouped depending on number and type of matches each RE returns.\n\n INPUT: nutDic, the dictionary of hot dog nutrition strings\n reDic, the dictionary of REs that uniquely corresponds to the hot dog brand.\n OUTPUT: nutDicParsed, the dictionary of parsed hot dog nutrition information.\n '''\n # Create RE list\n reList = []\n for k, v in reDic.items():\n reList += v\n\n # Parse\n nutDicParsed = {}\n for k, v in nutDic.items():\n dogName = k\n dogUrl, nutStr = v\n dogNutParsed = {}\n for regex in reList:\n mo = re.search(regex.lower(), nutStr)\n if mo == None:\n pass\n elif mo != None:\n groups = mo.groups()\n # Might have to change to for k, v in reDic.items(), because different hot dogs have different reGroups. E.g., Oscar Mayer has not 'reGroup1'.\n if regex in reDic['reGroup1']:\n nutName = scap(groups[0])\n quantity = groups[1]\n quantityUnits = groups[2]\n mass = groups[3]\n massUnits = groups[4]\n d = { 'quantity' : quantity,\\\n 'quantityUnits' : quantityUnits,\\\n 'mass' : mass,\\\n 'massUnits' : massUnits }\n dogNutParsed[nutName] = d\n if regex in reDic['reGroup2']:\n nutName = scap(groups[0])\n quantity = groups[1]\n d = { 'quantity' : quantity}\n dogNutParsed[nutName] = d\n if regex in reDic['reGroup3']:\n nutName = scap(groups[0])\n mass = groups[1]\n massUnits = groups[2]\n d = { 'mass' : mass,\\\n 'massUnits' : massUnits }\n dogNutParsed[nutName] = d\n if regex in reDic['reGroup4']:\n nutName = scap(groups[0])\n mass = groups[1]\n massUnits = groups[2]\n pct = groups[3]\n d = { 'mass' : mass,\\\n 'massUnits' : massUnits,\\\n 'pct' : pct }\n dogNutParsed[nutName] = d\n if regex in reDic['reGroup5']:\n nutName = scap(groups[0])\n pct = groups[1]\n d = { 'pct' : pct }\n dogNutParsed[nutName] = d\n nutDicParsed[dogName] = {'url': dogUrl, 'nutDic' : dogNutParsed}\n\n return nutDicParsed\n\ndef getAspectsList(nutDicParsed):\n '''\n Should work for all Brands.\n\n Automatically finds all possible nutrition features given a dictionary of parsed nutrition information.\n '''\n aspectsSet = set()\n for dogName, d in nutDicParsed.items():\n url, nutDic = d.values()\n for nutFeature, aspectsDic in nutDic.items():\n for aspect in aspectsDic:\n aspect = {f'{nutFeature} ({aspect})'}\n aspectsSet = aspectsSet.union(aspect)\n\n aspectsList = list(aspectsSet)\n return aspectsList\n\ndef parsedDic2tab(nutDicParsed):\n '''\n Only for nutrition dictionaries from Ballpark... Might work for other Brands?\n Converts the parsed hot dog nutrition dictionary as a matrix.\n '''\n aspectsList = getAspectsList(nutDicParsed)\n numDogs = len(nutDicParsed)\n numAspects = len(aspectsList)\n table = pd.DataFrame(np.zeros((numDogs, numAspects)))\n table = table.replace(0,'')\n newcols = {i : aspect for i, aspect in enumerate(aspectsList)}\n dogcols = {aspect : i for i, aspect in newcols.items()}\n table.rename(columns = newcols, inplace=True)\n newrows = {i : dog for i, dog in enumerate(nutDicParsed.keys())}\n dogindx = {dog : i for i, dog in newrows.items()}\n table.rename(index = newrows, inplace = True)\n for dog in nutDicParsed:\n nutDic = nutDicParsed[dog]['nutDic']\n for feature, d in nutDic.items():\n for aspect in d:\n dogaspect = f'{feature} ({aspect})'\n value = nutDic[feature][aspect]\n table.iloc[dogindx[dog], dogcols[dogaspect]] = value\n return table\n\ndef getAspects(aspects, fpath):\n # make sure aspect is iterable\n if type(aspects) is not list or not set:\n aspects = [aspects]\n\n # load matrix\n df = pd.read_csv(fpath)\n\n # create dictionary that can map to and from the column labels and the indices\n columns = df.columns\n colMap = {aspect : i for i, aspect in enumerate(columns)}\n\n # Make sure the queried aspect is in the matrix\n for aspect in aspects:\n if aspect in columns:\n pass # All is good\n elif aspect not in columns:\n nearMatches = []\n for col in columns:\n if aspect.lower() in col.lower():\n nearMatches.append(col)\n if len(nearMatches) != 0:\n print(f'The queried aspect \\\"{aspect}\\\" was not found. Below are some similar matches.\\n\\n')\n s = '\\n'.join(nearMatches)\n print(s)\n elif len(nearMatches) == 0:\n print(f'The queried aspect \\\"{aspect}\\\" was not found.\\n\\n')\n return\n\n # Find the aspect\n queries = [colMap[aspect] for aspect in aspects]\n c = [colMap['Unnamed: 0']] + queries\n colResults = df.iloc[:,c]\n\n return colResults\n\ndef giveErrors(A, pct):\n '''\n Changes random elements in a matrix. To be used with getAccuracy.\n\n Input: A, a pandas dataframe or numpy array\n pct, a float between 0 and 1.\n '''\n n, p = A.shape\n cols = A.columns\n rows = A.index\n B = np.array(A).ravel()\n errorArr = np.random.rand(n*p)\n B[errorArr < pct] = 'foo'\n B = pd.DataFrame(B.reshape(n,p), columns = cols, index = rows)\n\n return B\n\ndef getAccuracy(A, B):\n '''\n Returns the ratio of cells in the Pandas DataFrame or numpy array that are exactly the same.\n\n Input: Two Pandas DataFrames or numpy arrays\n Output: float\n '''\n\n n, p = A.shape\n accuracy = (A == B).sum().sum() / (n*p)\n\n return accuracy\n\ndef appendTable(fpath, newTable):\n '''\n Saves the nutrition table to csv. If that csv contains information, it will append to it while removing duplicates.\n\n INPUT: fpath, a string indicating the file path to save to\n newTable, the table to be saved\n RESULT: a csv at fpath\n '''\n print(dt.datetime.now())\n\n # Order of columns to save by\n columns = newTable.columns\n\n # If a table exists, load it, otherwise, just write.\n try:\n with open(fpath, 'r') as f:\n oldTable = pd.read_excel(fpath, index_col=0, dtype=str, keep_default_na = False)\n except:\n t,v,cb = sys.exc_info()\n exceptionName = t.__name__\n exceptionValu = v.args\n if exceptionName == 'FileNotFoundError' and 'No such file or directory' in exceptionValu:\n with open(fpath, 'w', newline='') as f:\n newTable.to_excel(fpath)\n return\n else:\n raise\n\n # Concatenate tables\n conTable = pd.concat([oldTable, newTable], axis=0, sort=True)\n conTable = conTable.fillna('')\n\n # clear duplicates, incase you're about to write what you've saved before\n conTable['index'] = conTable.index\n conTable.drop_duplicates(inplace=True)\n del conTable['index']\n\n with open(fpath, 'w', newline='') as f:\n conTable.to_excel(fpath, columns=columns)\n\ndef getSim(s1, s2):\n sim = SequenceMatcher(None, s1, s2).ratio()\n return sim\n\ndef getCost(y, yhat):\n '''\n getCost(y, yhat) != getCost(yhat, y). The algorithm is not commutative\n\n Example:\n\n s1 = 'serving: calories 160,'\n s2 = 'calories 160, calories'\n getCost(s1, s2)\n # 0.16735537190082642\n\n Thanks to SE for suggesting SequenceMatcher\n\n https://stackoverflow.com/questions/17388213/find-the-similarity-metric-between-two-strings\n '''\n sim = getSim(y, yhat)\n cost = (1 - sim)**2\n return cost\n\ndef getCandidateCost(candidate):\n '''\n This cost function is to determine how good a reconstruction candidate is.\n\n INPUT: candidate, an object of class ReconstructionCandidate.\n OUTPUT: score, a number of type float.\n '''\n\n cost = 0\n\n return cost\n\ndef donutList(index, li, holeDiameter, bracketSize, separator=', ', verbose=0):\n '''\n Returns the elements surrounding the element at the location \"index\" of width \"holeDiameter\" by using a bracket of size \"bracketSize\".\n\n Test usage (works for both numbers or letters):\n li = [str(x) for x in range(0,11)]\n # li = [str(x) for x in 'abcdefghij']\n bracketSize = 3\n for index in range(len(li)):\n donut = donutList(index, li, 3, 1, verbose=1)\n print(donut)\n '''\n if isinstance(bracketSize, list) or isinstance(bracketSize, tuple):\n bracketSizeLeft, bracketSizeRight = bracketSize\n elif isinstance(bracketSize, int):\n bracketSizeLeft = bracketSize\n bracketSizeRight = bracketSize\n else:\n print('This should not happen!')\n\n sep = separator\n\n min = 0\n max = len(li)\n\n lo = index - bracketSizeLeft\n hi = index + holeDiameter + bracketSizeRight\n\n if lo < min:\n lo = min\n\n donutLeft = li[ lo : index ]\n donutRight = li[ index + holeDiameter : hi ]\n donut = donutLeft + donutRight\n donutHole = li[ index : index + holeDiameter ]\n\n # verbose block\n if verbose > 0:\n\n contextLeft = li[ min : lo ]\n contextRight = li[ hi : max ]\n\n donutHoleStr = sep.join( donutHole )\n donutLeftStr = sep.join( donutLeft )\n donutRightStr = sep.join( donutRight )\n contextLeftStr = sep.join( contextLeft )\n contextRightStr = sep.join( contextRight )\n\n donutHoleStr = colorize( donutHoleStr, style.RED)\n donutLeftStr = colorize( donutLeftStr, style.BLUE)\n donutRightStr = colorize( donutRightStr, style.BLUE)\n contextLeftStr = colorize( contextLeftStr, style.GREEN)\n contextRightStr = colorize( contextRightStr, style.GREEN)\n\n data = [(contextLeftStr, contextLeft),\n (donutLeftStr, donutLeft),\n (donutHoleStr, donutHole),\n (donutRightStr, donutRight),\n (contextRightStr, contextRight)]\n\n text = ''\n for Str, donutLi in data:\n if donutLi == []:\n pass\n elif not donutLi == []:\n if text == '':\n text = Str\n elif not text == '':\n text = text + sep + Str\n\n print(text)\n\n return donut\n\ndef numPerm(numWords, numFeats):\n import math\n '''\n I sketched this out while working on the function \"detector\". I think I was trying to calculate the number of permutations of a bracket and the number of words it contained. It would be a function of how many words there are and how many nutrition features the concept has.\n '''\n # General equation for any numWords, numFeats\n # numPerm = Product_i^(numFeats-1)( numWords - i)!, i = 0,...,numFeats-1\n\n # Equation for any numWords, and numFeats = 2\n numPerm = math.factorial( numWords ) * math.factorial( numWords-1 )\n return numPerm\n\ndef getPermutedIndices(numWords, numFeats, verbose=0):\n '''\n\n '''\n if numWords >= numFeats:\n perms = list(itertools.permutations(range(numWords), numFeats))\n else:\n numFalses = numFeats - numWords\n placeHolder = ''\n li = [*[placeHolder for it in range(numFalses)], *range(numWords)]\n perms = list(itertools.permutations(li, numFeats))\n\n # if numFalses > 1, you will get duplicates, so this block removes them.\n if numFalses > 1:\n\n # verbose block\n if verbose > 0:\n permsStr = colorize(perms.__repr__(), style.RED)\n text = f'Permutations with duplicates: {permsStr}'\n print(text)\n\n li2 = []\n for tu in perms:\n if tu in li2:\n pass\n else:\n li2.append(tu)\n perms = li2\n\n return perms\n\ndef reconstruct(s):\n # Try to extract number from string\n nucleus = re.search('[0-9.]+', s)\n if nucleus:\n try:\n nucleus = nucleus.group()\n float(nucleus)\n return nucleus\n except ValueError:\n return False\n # If no number was extracted, return 'False'\n elif isinstance(nucleus, type(None)):\n return False\n\ndef detectConcepts(nutritionString, concept, bracketSize=3, verbose=0):\n '''\n The detector scans over the nutrition string to identify candidate values for a concept.\n '''\n nutList = re.findall('([^\\s]+)', nutritionString)\n nutArr = np.array(nutList)\n name = concept['name']\n features = list(concept['features'])\n numFeats = len(features)\n indices = np.argwhere(nutArr == name).ravel().tolist()\n lPermutations = []\n lCandidates = []\n lRecs = []\n numIndices = len(indices)\n for j, i in enumerate(indices, start=1):\n\n words = donutList(i, nutList, bracketSize) # get elements around ith element\n numWords = len(words)\n permutations = getPermutedIndices(numWords)\n # permutations = getPermutedIndices(numWords, numFeats)\n candidates = []\n for permutation in permutations:\n word1, word2 = permutation\n d = {}\n for k, feat in enumerate(features):\n index = permutation[k]\n d[feat] = words[index]\n candidates.append(d)\n\n # reconstruct\n recs = []\n for candidate in candidates:\n reconstruction = {k : reconstruct(v) for k,v in candidate.items()}\n recs.append(reconstruction)\n\n # verbose block\n if verbose > 0:\n if numIndices > 1:\n print(f'\\nBracketing occurrence {j} of {numIndices}.')\n nestIndent = 4\n else:\n nestIndent = 0\n\n indentation = 4 + nestIndent\n\n text = f'\\nPermutation indices:'\n print(indent(text, prefix = nestIndent * ' '))\n width = 4 + (len(features)>=2)*2 + (len(features)>2)*3*(len(features)-2)\n print(indent(pt.pformat(permutations, width = width + indentation), ' ' * indentation))\n\n text = f'\\nReconstruction candidates:'\n print(indent(text, prefix = nestIndent * ' '))\n print(indent(pt.pformat(candidates), ' ' * indentation))\n\n text = f'\\nReconstructions:'\n print(indent(text, prefix = nestIndent * ' '))\n print(indent(pt.pformat(recs), ' ' * indentation))\n\n lPermutations.append(permutations)\n lCandidates.append(candidates)\n lRecs.append(recs)\n\n elif verbose == 0:\n\n lRecs.append(recs)\n\n # return block\n if verbose > 0:\n return lPermutations, lCandidates, lRecs\n elif verbose == 0:\n return lRecs\n\ndef restoreInt(dic):\n '''\n Changes top-level keys of a dictionary to integers. This is necessary because JSON.loads() doesn't convert them back to integers, and keeps them as strings.\n '''\n\n dic2 = {}\n for key, value in dic.items():\n\n Continue = False\n\n try:\n key2 = int(key)\n Continue = True\n except:\n pass\n\n if Continue:\n dic2[key2] = value\n elif not Continue:\n dic2[key] = value\n\n del dic\n\n return dic2\n\ndef hasOverlap(recondidate1, recondidate2):\n rc1info = recondidate1.reconstructionInfo\n rc2info = recondidate2.reconstructionInfo\n\n overlap = False\n for featureName1, info1 in rc1info.items():\n word1, wordIndex1, start1, end1 = info1\n\n for featureName2, info2 in rc2info.items():\n word2, wordIndex2, start2, end2 = info2\n\n if np.max([start1, start2]) <= np.min([end1, end2]):\n overlap = True\n if overlap:\n return overlap\n return overlap\n\ndef byIndices(candidateInfo):\n '''Converts ReconstructionCandidate.recondidateInfo or .reconstructionInfo dictionary thus:\n\n {'featureName1': [word1, wordIndex1, start1, end1],\n 'featureName2': [word2, wordIndex2, start2, end2]}\n\n to\n\n {(wordIndex1, wordIndex2) : {featureNames : [featureName1, featureName2],\n words : [word1, word2],\n starts : [start1, start2],\n ends : [end1, end2]}}\n '''\n wordIndices = []\n featureNames = []\n words = []\n starts = []\n ends = []\n for featureName, info in candidateInfo.items():\n word, wordIndex, start, end = info\n wordIndices.append(wordIndex)\n featureNames.append(featureName)\n words.append(word)\n starts.append(start)\n ends.append(end)\n\n tu = (tuple(wordIndices) , {'featureNames' : featureNames,\n 'words' : words,\n 'starts' : starts,\n 'ends' : ends})\n\n return tu\n\ndef set2listString(dataFrame, columnName):\n '''\n '''\n\n temp = dataFrame[columnName].to_dict()\n for index_or_key, column_or_values in temp.items():\n li = [value for value in column_or_values]\n li.sort()\n li = [str(x) for x in li]\n temp[index_or_key] = ', '.join(li)\n dataFrame[columnName] = pd.Series(temp)\n\n return dataFrame\n\ndef troubleshootCSV():\n '''\n Just some useful code I used to troubleshoot pd.read_csv. It compares the list array of strings with the pandas dataframe.\n\n This can be removed\n '''\n fpath = '/Users/herman/Documents/dis2001/nutaspects_all 01.csv'\n\n with open(fpath, 'r') as f:\n fileString = f.read()\n\n lines1 = fileString.splitlines()\n lines2 = lines1[:]\n\n # Get headers\n headers = lines2.pop(0).split(',')[1:]\n\n # Split into rows and cells\n lines3 = [[x for x in row.split(',')] for row in lines2] # list of lists\n\n # Get indices\n indices = []\n lines4 = lines3[:]\n for line in lines4:\n indices.append(line.pop(0))\n\n # Fill values\n colNum2header = {colNum : header for colNum, header in enumerate(headers)}\n for index, row in zip(indices, lines4):\n # print(row)\n for columnNumber, value in enumerate(row):\n # print('\\t' + str(value))\n pass\n\n df = pd.DataFrame( [pd.array(line) for line in lines4], index=indices, columns=headers)\n\n return lines4, df\n","sub_path":"nutFuncs.py","file_name":"nutFuncs.py","file_ext":"py","file_size_in_byte":26506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"160806894","text":"# import itertools\n# import math\n\n# N = int(input())\n# S = input()\nN, M = map(int, input().split())\n# A = list(map(int, input().split()))\n\nans_p = [0] * N\nans_s = [0] * N\n\nfor i in range(M):\n input_sp = input().split()\n P = int(input_sp[0]) - 1\n S = input_sp[1]\n\n if S == 'AC':\n ans_s[P] = 1\n elif S == 'WA' and ans_s[P] == 0:\n ans_p[P] += 1\n\nfor i in range(len(ans_p)):\n if ans_s[i] == 0 and ans_p[i] != 0:\n ans_p[i] = 0\n\nprint(str(sum(ans_s)) + \" \" + str(sum(ans_p)))\n","sub_path":"contest_abc/151/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"167220986","text":"import sys\n\nvalue1 = sys.argv[1]\n\nnumlist = [int(x) for x in value1.split(',')]\n\nnumlist.sort(reverse=True)\nind = 0\nfor i in numlist:\n if ind != len(numlist)-1:\n print(f\"{i}\", end=',')\n else:\n print(f\"{i}\", end='')\n ind +=1\n","sub_path":"Python/add_list/add_nums.py","file_name":"add_nums.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"57516601","text":"class Lista:\r\n def __init__(self,listas):\r\n self.__lista = listas\r\n \r\n @property \r\n def lista(self):\r\n return self.__lista\r\n \r\n def busquedaLineal(self,buscado):\r\n pos = 0\r\n enc = False\r\n lon = len(self.__lista)\r\n while pos < lon and enc == False:\r\n if self.__lista[pos][\"Nombre\"] == buscado:\r\n enc = True\r\n else:\r\n pos += 1\r\n if enc: return pos\r\n else: return -1\r\n \r\n def ordenar(self,orden):\r\n orden = orden.lower()\r\n if orden == \"asc\":\r\n for pos in range(0,len(self.__lista)):\r\n for sig in range(pos+1,len(self.__lista)):\r\n if self.__lista[pos][\"Nombre\"] > self.__lista[sig][\"Nombre\"]:\r\n aux = self.__lista[pos]\r\n self.__lista[pos] = self.lista[sig]\r\n self.__lista[sig] = aux\r\n else:\r\n for pos in range(0,len(self.__lista)):\r\n for sig in range(pos+1,len(self.__lista)):\r\n if self.__lista[pos][\"Nombre\"] < self.__lista[sig][\"Nombre\"]:\r\n aux = self.__lista[pos]\r\n self.__lista[pos] = self.lista[sig]\r\n self.__lista[sig] = aux\r\n \r\n \r\n def busquedaBinaria(self,buscado):\r\n self.ordenar(\"asc\")\r\n fin = len(self.lista)\r\n inicio = 0\r\n enc = False\r\n while inicio < fin and enc == False:\r\n medio = (inicio+fin)//2\r\n if self.lista[medio][\"Nombre\"] == buscado: enc = True\r\n elif self.lista[medio][\"Nombre\"] > buscado: fin = medio-1\r\n else: inicio = medio+1\r\n if enc: return medio\r\n else: return -1\r\n\r\nnotas = [\r\n {\"Nombre\":\"Anderson\",\"n1\":35,\"n2\":60},\r\n {\"Nombre\":\"Jose\",\"n1\":20,\"n2\":50},\r\n {\"Nombre\":\"Deyanira\",\"n1\":40,\"n2\":45},\r\n {\"Nombre\":\"Gissela\",\"n1\":50,\"n2\":30},\r\n {\"Nombre\":\"Lucas\",\"n1\":45,\"n2\":28},\r\n {\"Nombre\":\"Leonardo\",\"n1\":55,\"n2\":40}\r\n]\r\n\r\nbus = Lista(notas)\r\nbus.lista.sort()\r\nposicion = bus.busquedaLineal(\"Deyanira\")\r\nif posicion != -1:\r\n print(bus.lista[posicion])\r\nelse:\r\n print(\"El nombre no se encuentra en la lista\")\r\nbus.ordenar()\r\nprint(bus.lista)","sub_path":"Sem14/Busqueda.py","file_name":"Busqueda.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"163532117","text":"import re\nimport vlc \nfrom .frontend.display import Print\nfrom time import sleep\nfrom .errors import PlayerError\n\n\nclass Player(object):\n \"\"\"Media player controller\"\"\" \n\n def __init__(self):\n try:\n self._vlc = vlc.Instance('-q')\n self._player = self._vlc.media_player_new()\n except Exception as e:\n extended_msg = 'Please check if your device supports VLC'\n raise PlayerError(1,extended_msg)\n\n self._track_set = False\n self.song = None\n \n\n def _seeker(self,pos=10,rew=True):\n if self._state == 'No Media':\n return \n if rew: \n to_postion = self.player.get_time() - (pos * 1000)\n else:\n to_postion = self.player.get_time() + (pos * 1000)\n self.player.set_time(to_postion)\n\n\n @property\n def player(self):\n return self._player\n \n\n @property\n def _state(self):\n \"\"\"Current state of the song being played\"\"\"\n state = re.match(r'[\\w.]*\\.(\\w*)',str(self.player.get_state())).group(1)\n state = 'No Media' if state =='NothingSpecial' else state\n return state\n\n \n\n def setTrack(self,song,media=None):\n if media:\n self.song = song\n self.player.set_mrl(media)\n self._track_set = True\n else:\n Print('No media to play')\n \n\n property\n def _format_time(self,pos):\n \"\"\"Format current song time to clock format\"\"\"\n mins = int(pos/60000)\n secs = int((pos%60000)/1000)\n return mins,secs\n\n \n\n @property\n def info(self):\n \"\"\"Returns feedback for media song being played\"\"\"\n if self._state == 'No Media':\n return 'No media' \n c_min,c_sec = self._format_time(self.player.get_time())\n c_sec = c_sec if len(str(c_sec)) >1 else str(c_sec).zfill(2) \n\n l_min,l_sec = self._format_time(self.player.get_length())\n l_sec = l_sec if len(str(l_sec)) >1 else str(l_sec).zfill(2) \n \n Print('TRACK:',self.song)\n Print('MODE:',self._state)\n pos = 'POSITION: {0}:{1} - {2}:{3}'.format(c_min,c_sec,l_min,l_sec)\n Print(pos)\n \n\n @property\n def _current_volume(self):\n \"\"\" Current media player volume\"\"\"\n return self.player.audio_get_volume()\n\n\n def _set_volume(self,vol=5,way='down'):\n \"\"\"Turn the media volume up or down\"\"\"\n if isinstance(vol,(int,str)):\n if not str(vol).isnumeric():\n return \n\n vol = int(vol)\n min_vol = 0\n max_vol = 100\n try:\n current_volume = int(self._current_volume)\n if way == 'down':\n if current_volume - vol < min_vol:\n vol = min_vol \n else:\n vol = current_volume - vol\n elif way == 'up':\n if current_volume + vol > max_vol:\n vol = max_vol\n else:\n vol = current_volume + vol\n elif way == 'exact':\n vol = 0 if vol < min_vol else vol \n vol = 100 if vol > max_vol else vol\n Print('volume: %s'%vol)\n except:\n pass\n self.player.audio_set_volume(vol)\n\n\n def volumeUp(self,vol=5):\n \"\"\"Turn the media volume up\"\"\"\n self._set_volume(vol,way='up')\n \n\n def volumeDown(self,vol=5):\n \"\"\"Turn the media volume down\"\"\"\n self._set_volume(vol,way='down')\n\n\n def volume(self,vol=None):\n \"\"\"Set the volume to exact number\"\"\"\n if vol is None:\n return\n self._set_volume(vol,way='exact')\n \n \n @property\n def play(self):\n \"\"\" Play media song\"\"\"\n playing = True if self.player.is_playing() >=1 else False\n\n if playing:\n # call play while playing ,them pause \n self.player.pause()\n elif self._state == 'Paused':\n self.player.pause()\n\n elif self._track_set:\n self.player.play()\n self._track_set = False\n return\n\n\n \n @property\n def pause(self):\n \"\"\"Pause the media song\"\"\"\n self.player.pause()\n\n\n def rewind(self,pos=10):\n \"\"\"\n Rewind the media song\n vlc time is in milliseconds\n @params: pos:: time(second) to rewind media. default:10(sec)\n \"\"\"\n self._seeker(pos,True)\n\n\n def ffwd(self,pos=10):\n \"\"\"Fast forward media \n vlc time is in milliseconds\n @params: pos:: time(second) to rewind media. default:10(sec)\n \"\"\"\n self._seeker(pos,False)\n\n\n \n @property\n def stop(self):\n self.player.stop()\n\n\n def close(self):\n self.stop\n\n \n \n","sub_path":"pydatpiff/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":4859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"146928520","text":"def columnSwap(arr, i, i2): \n indexone = arr[i]\n arr[i] = arr[i2]\n arr[i2] = indexone\n\ndef printMatrix(matrix):\n print()\n for i in range(len(matrix)):\n print(matrix[i])\n\ndef rowSwap(arr, i, i2):\n for h in range(len(arr)):\n one = (arr[h])[i]\n (arr[h])[i] = (arr[h])[i2]\n (arr[h])[i2] = one\n\ndef makeMatrix(rowLength):\n returnThis = []\n anotherList = []\n theList = 0;\n for i in range(rowLength):\n theList = input(\"Row\" + str(i) +\": \")\n anotherList = []\n for e in range(rowLength):\n anotherList.append(theList[e])\n returnThis.append(anotherList)\n return returnThis\n\ndef iso(arr, arr2):\n temp = 0\n for a in range(len(arr)):\n for b in range(len(arr2)):\n rowSwap(arr, a, b)\n if arr == arr2:\n temp =+ 1\n print(\"They are isomorphic\")\n \n\n for a in range(len(arr)):\n for b in range(len(arr)):\n columnSwap(arr, a, b)\n if arr == arr2:\n temp =+ 1\n print(\"They are isomorphic\")\n\n for a in range(len(arr)):\n for b in range((len(arr2))):\n rowSwap(arr, a, b)\n columnSwap(arr, a , b)\n if arr == arr2:\n temp =+ 1\n print(\"They are isomorphic\")\n\n if (temp == 0):\n print('The graphs are not isomorphic')\n\ngraph1 = makeMatrix(int(input(\"How big? \")))\ngraph2 = makeMatrix(int(input(\"How big? \")))\niso(graph1, graph2)\n","sub_path":"Python 3/Mathematical Computing/Prove if two graphs are isomorphic.py","file_name":"Prove if two graphs are isomorphic.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"606273126","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# pip install matplotlib\n\n\nx = np.linspace(-1, 1, 100)\nfor n in range(1, 10):\n y = x ** n\n plt.plot(x, y, label=f'x^{n}')\n\nplt.xlabel('Value')\nplt.ylabel('Result Value')\nplt.title('Values Graph')\nplt.grid(True)\nplt.legend()\n\nplt.xticks([-1, 0, 1])\nplt.yticks([-1, -0.5, 0, 0.5, 1], ['One', 'Two', 'Three', 'Four', 'Five'], rotation=30)\n\nplt.show()\n","sub_path":"training/c19_mathplotlib/e03-axis.py","file_name":"e03-axis.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"419435734","text":"import numpy as np\nfrom math import e, sqrt\nimport matplotlib.pyplot as plt\nfrom numpy import linalg as LA\nfrom scipy import optimize\nfrom scipy.optimize import minimize\nimport random\nimport time\nfrom datetime import datetime\nimport sys\n\n# y = Gu(x) + white noise\ndef Gu_initialize(x):\n\treturn ((x >= 1 / 3.0) & (x <= 2 / 3.0)) * 1\n\n# Gaussian kernel is used to generate the covariance matrix\ndef Gaussian_Kernel(t1, t2, gamma, d):\n\treturn gamma * e ** (- ((t1 - t2) / d)**2 / 2)\n\t\n###########################################################################################################\nclass Naive_denoising(object):\n\tdef __init__(self, dimension_of_observation, dimension_of_unknown, noise_variance, show_observation = False, show_figure = False, save_figure = False, load_observation = \"\"):\n\t\tif (dimension_of_unknown - 1) % (dimension_of_observation - 1) != 0:\n\t\t# check if the dimensions are matched.\n\t\t\tprint(\"Dimensions of observation and unknown are not matched.\")\n\t\t\tsys.exit(0)\n\n\t\t# self.coarse_factor is the compression ratio from unknown to observation.\n\t\tself.coarse_factor = int((dimension_of_unknown - 1) / (dimension_of_observation - 1))\n\t\tself.dimension_of_observation = dimension_of_observation\n\t\tself.dimension_of_unknown = dimension_of_unknown\n\t\tself.operator_matrix = np.zeros((self.dimension_of_observation, self.dimension_of_unknown))\n\n\t\t# set operator_matrix\n\t\tset_operator_matrix = True\n\t\tif (set_operator_matrix == True): \n\t\t\tfor i in range(self.coarse_factor): \n\t\t\t\tself.operator_matrix[0, i] = 1.0 / self.coarse_factor \n\t\t\t\tself.operator_matrix[self.dimension_of_observation - 1, self.dimension_of_unknown - 1 - i] = 1.0 / self.coarse_factor \n\n\t\t\tfor i in range(1, self.dimension_of_observation - 1): \n\t\t\t\tfor j in range(self.coarse_factor): \n\t\t\t\t\tself.operator_matrix[i][i * self.coarse_factor + j] = 1.0 / (2 * self.coarse_factor - 1) \n\t\t\t\t\tself.operator_matrix[i][i * self.coarse_factor - j] = 1.0 / (2 * self.coarse_factor - 1)\n\n\n\t\t# White noise variance.\n\t\tself.noise_variance = noise_variance\n\n\t\t# noise and observations are generated by numpy arrays.\n\t\tself.observation_ordinate = np.linspace(0, 1, dimension_of_observation)\n\t\tself.unknown_ordinate = np.linspace(0, 1, dimension_of_unknown)\n\n\t\t# initialize the unknown. \n\t\tself.unknown = Gu_initialize(self.unknown_ordinate)\n\n\t\tif (load_observation == \"\"): \n\t\t\tself.noise = np.random.normal(0, noise_variance, dimension_of_observation) \n\t\t\t# y = G(u) + noise \n\t\t\tself.observation = Gu_initialize(self.observation_ordinate) + self.noise\n\t\telse:\n\t\t\tself.observation = np.load(load_observation)\n\n\t\t# initialize MAP and posterior mean\n\t\tself.MAP = np.zeros(self.dimension_of_unknown)\n\t\tself.Posterior_Mean = np.zeros(self.dimension_of_unknown)\n\n\t\t# set prior: TV, Gaussian, TG, pV ...\n\t\tself.Set_Prior()\n\t\tself.show_observation = show_observation\n\t\tself.show_figure = show_figure\n\t\tself.save_figure = save_figure\n\n\n\n\tdef Gu(self, u): # an operator mapping from unknown to observation \n\t\t# Gu = np.linspace(0, 1, self.dimension_of_observation) \n\t\t# for i in range(self.dimension_of_observation): \n\t\t# \tGu[i] = u[i * self.coarse_factor]\n\t\treturn np.dot(self.operator_matrix, u)\n\n\tdef Set_Prior(self, prior = \"TV\", Lambda = 1, p = 1, gamma = 0.1, d = 0.04):\n\t\t# Lambda: parameter for TV of TG regularization term\n\t\t# p: parameter for pV norm\n\t\t# gamma and d: parameters of Gaussian kernel\n\t\tself.Prior = prior\n\n\t\tif (prior == \"TV\") or (prior == \"phi_Laplace\"):\n\t\t\tself.Lambda = Lambda\n\t\t\tself.p = 0\n\t\t\tself.gamma = 0\n\t\t\tself.d = 0\n\t\telif (prior == \"pV\"):\n\t\t\tself.Lambda = Lambda\n\t\t\tself.p = p\n\t\t\tself.gamma = 0\n\t\t\tself.d = 0\n\t\telif (prior == \"Gaussian\"):\n\t\t\tself.gamma = gamma\n\t\t\tself.d = d\n\t\t\tself.Lambda = 0\n\t\t\tself.p = 0\n\t\t\tself.prior_covariance = Gaussian_Kernel(self.unknown_ordinate[np.newaxis, :], self.unknown_ordinate[:, np.newaxis], self.gamma, self.d)\n\t\t\tself.inv_sqrt_prior_covariance = LA.inv(np.sqrt(self.prior_covariance))\n\t\telif (prior == \"TG\") or (prior == \"phi_G\"):\n\t\t\tself.Lambda = Lambda\n\t\t\tself.gamma = gamma\n\t\t\tself.d = d\n\t\t\tself.p = 0\n\t\t\tself.prior_covariance = Gaussian_Kernel(self.unknown_ordinate[np.newaxis, :], self.unknown_ordinate[:, np.newaxis], self.gamma, self.d)\n\t\t\tself.inv_sqrt_prior_covariance = LA.inv(np.sqrt(self.prior_covariance))\n\t\telif (prior == \"pG\"):\n\t\t\tself.Lambda = Lambda\n\t\t\tself.p = p\n\t\t\tself.gamma = gamma\n\t\t\tself.d = d\n\t\t\tself.prior_covariance = Gaussian_Kernel(self.unknown_ordinate[np.newaxis, :], self.unknown_ordinate[:, np.newaxis], self.gamma, self.d)\n\t\t\tself.inv_sqrt_prior_covariance = LA.inv(np.sqrt(self.prior_covariance))\n\n\t# Definitions of the norms and the potential function.\n\tdef Phi(self, u): return LA.norm((self.Gu(u) - self.observation) / sqrt(self.noise_variance))**2 / 2\n\tdef TV_norm(self, u): return self.Lambda * LA.norm(np.delete((u), 0) - np.delete(u, self.dimension_of_unknown - 1), 1)\n\tdef Gaussian_norm(self, u): return LA.norm(np.dot(self.inv_sqrt_prior_covariance, u)) ** 2 / 2\n\tdef pV_norm(self, u): return self.Lambda * (self.dimension_of_unknown - 1)**(self.p - 1) * LA.norm(np.delete((u),0) - np.delete(u, self.dimension_of_unknown - 1), self.p)**self.p\n\n\tdef TV_minimizer(self, u): return self.Phi(u) + self.TV_norm(u)\n\tdef Gaussian_minimizer(self, u): return self.Phi(u) + self.Gaussian_norm(u)\n\tdef TG_minimizer(self, u): return self.Phi(u) + self.TV_norm(u) + self.Gaussian_norm(u)\n\tdef pV_minimizer(self, u): return self.Phi(u) + self.pV_norm(u)\n\tdef pG_minimizer(self, u): return self.Phi(u) + self.pV_norm(u) + self.Gaussian_norm(u)\n\tdef phi_minimizer(self, u): return self.Phi(u) + self.Lambda * abs(2 - self.TV_norm(u))\n\tdef phi_G_minimizer(self, u): return self.Phi(u) + self.Lambda * abs(2 - self.TV_norm(u)) + self.Gaussian_norm(u)\n\n\t# Maximum a Posterior. Computed by optimization package(scipy).\n\tdef Get_MAP(self, save_npy = False): \n\t\tinput = self.unknown\n\t\tif self.Prior == \"TV\":\n\t\t\tres = minimize(self.TV_minimizer, input, method = 'L-BFGS-B', tol = 1e-6)\n\t\t\tprint(\"Loss:\", self.Phi(res.x), self.TV_norm(res.x))\n\t\telif self.Prior == \"Gaussian\":\n\t\t\tres = minimize(self.Gaussian_minimizer, input, method = 'TNC', tol = 1e-6)\n\t\t\tprint(\"Loss:\", self.Phi(res.x), self.Gaussian_norm(res.x))\n\t\telif self.Prior == \"TG\":\n\t\t\tres = minimize(self.TG_minimizer, input, method = 'L-BFGS-B', tol = 1e-6)\n\t\t\tprint(\"Loss:\", self.Phi(res.x), self.TV_norm(res.x), self.Gaussian_norm(res.x))\n\t\telif self.Prior == \"pV\":\n\t\t\tres = minimize(self.pV_minimizer, input, method = 'L-BFGS-B', tol = 1e-6)\n\t\t\tprint(\"Loss:\", self.Phi(res.x), self.pV_norm(res.x))\n\t\telif self.Prior == \"phi_Laplace\":\n\t\t\tres = minimize(self.phi_minimizer, input, method = 'L-BFGS-B', tol = 1e-6)\n\t\t\tprint(\"Loss:\", self.Phi(res.x), self.phi_minimizer(res.x) - self.Phi(res.x))\n\n\t\tself.MAP = res.x\n\t\tif res.success: print(\"Successfully get MAP from \" + self.Prior + \" prior.\")\n\t\telse: print(\"Unsuccessfully get MAP.\")\n\n\t\tself.Plot_MAP()\n\n\t\tif (res.success and save_npy):\n\t\t\tsamples_np = np.array(self.MAP)\n\t\t\tnp.save(\"MAP\" + self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", samples_np)\n\t\t\t# np.save(\"Observation_time_\" + datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", self.observation)\n\t\t\ttext_file = open(\"MAP\" + self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".txt\", \"w\")\n\t\t\ttext_file.write(\"Lambda = \" + str(self.Lambda) + \"\\np = \" + str(self.p) + \"\\ngamma = \" + str(self.gamma) + \"\\nd = \" + str(self.d) )\n\n\t\treturn res.x\n\n\t# def S_pCN(self, sample_size = 1000, splitting_number = 5, beta = 0.1):\n\t# \t# All the samples are stored in the u_samples list, with each element being a numpy.array.\n\t# \tu_samples = list()\n\t# \t# Initialize the first sample u0.\n\t# \tu_samples.append(self.unknown)\n\t# \t# u_mean is the mean of the samples.\n\t# \tu_mean = np.zeros(self.dimension_of_unknown)\n\t# \tacc_counter = 0.0\n\n\t# \tfor i in range(sample_size):\n\t# \t\tu_mean += u_samples[-1]\n\t# \t\tif i % (sample_size / 10) == 0: print(str((i + 0.0) / sample_size))\n\n\t# \t\tu_current = u_samples[-1]\n\t# \t\tvj = u_current\n\t# \t\tfor j in range(splitting_number):\n\t# \t\t\trandom_walk = np.random.multivariate_normal(np.zeros(self.dimension_of_unknown), self.prior_covariance)\n\t# \t\t\tv_prop = sqrt(1 - beta ** 2) * vj + beta * random_walk \n\t# \t\t\tacceptance_rate_R = min(1, e ** (self.TV_norm(vj) - self.TV_norm(v_prop)))\n\t# \t\t\tif random.uniform(0, 1) < acceptance_rate_R: vj = v_prop\n\n\t# \t\tacceptance_rate_Phi = min(1, e ** (self.Phi(u_current) - self.Phi(vj)))\n\t# \t\tif random.uniform(0, 1) < acceptance_rate_Phi: \n\t# \t\t\tu_samples.append(vj)\n\t# \t\t\tacc_counter += 1\n\t# \t\telse: \n\t# \t\t\tu_samples.append(u_current)\n\n\t# \tprint(\"Accept:\" + str(acc_counter / sample_size))\n\t# \tself.Posterior_Mean = u_mean / sample_size\n\t# \tself.Plot_CM(sample_size, beta)\n\t# \treturn u_samples\n\n\tdef pCN(self, sample_size = 1000, beta = 0.1, save_npy = False, initialize_unknown_from_npy = \"\"):\n\t\tu_samples = list()\n\t\tif (initialize_unknown_from_npy != \"\"): \n\t\t\tprint(\"Initializing unknown from \" + initialize_unknown_from_npy + \"...\")\n\t\t\tnpy_end_sample = np.load(initialize_unknown_from_npy) \n\t\t\tself.unknown = npy_end_sample[-1].copy()\n\t\t\t# npy_end_sample.close()\n\t\t\tdel npy_end_sample\n\n\t\tu_samples.append(self.unknown) \n\t\tu_mean = np.zeros(self.dimension_of_unknown)\n\t\tacc_counter = 0.0\n\n\t\tprint(\"pCN: \")\n\t\tfor i in range(sample_size): \n\t\t\tu_mean += u_samples[-1]\n\t\t\tif i % (sample_size / 10) == 0: print((i + 0.0) / sample_size)\n\n\t\t\tu_current = u_samples[-1]\n\t\t\trandom_walk = np.random.multivariate_normal(np.zeros(self.dimension_of_unknown), self.prior_covariance)\n\t\t\tu_prop = sqrt(1 - beta ** 2) * u_current + beta * random_walk\n\t\t\tif (self.Prior == \"Gaussian\"): \n\t\t\t\tacceptance_rate_Phi = min(1, e ** (self.Phi(u_current) - self.Phi(u_prop)))\n\t\t\telif (self.Prior == \"TG\"):\n\t\t\t\tacceptance_rate_Phi = min(1, e ** (self.TV_minimizer(u_current) - self.TV_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"pG\"):\n\t\t\t\tacceptance_rate_Phi = min(1, e ** (self.pV_minimizer(u_current) - self.pV_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"phi_G\"):\n\t\t\t\tacceptance_rate_Phi = min(1, e ** (self.phi_minimizer(u_current) - self.phi_minimizer(u_prop)))\n\t\t\tif random.uniform(0, 1) < acceptance_rate_Phi: \n\t\t\t\tu_samples.append(u_prop)\n\t\t\t\tacc_counter += 1\n\t\t\telse: \n\t\t\t\tu_samples.append(u_current)\n\n\t\tprint(\"Accept:\" + str(acc_counter / sample_size))\n\t\tself.Posterior_Mean = u_mean / sample_size \n\t\tself.Plot_CM(sample_size, beta)\n\n\t\t# save the samples as .npy files and the parameters are recorded in .txt files.\n\t\tif (save_npy): \n\t\t\tsamples_np = np.array(u_samples) \n\t\t\tnp.save(self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", samples_np)\n\t\t\tnp.save(\"Observation_time_\" + datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", self.observation)\n\t\t\ttext_file = open(self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".txt\", \"w\")\n\t\t\ttext_file.write(\"Lambda = \" + str(self.Lambda) + \"\\np = \" + str(self.p) + \"\\ngamma = \" + str(self.gamma) + \"\\nd = \" + str(self.d)+ \"\\nsample size = \" + str(sample_size) + \"\\nsample step = \" + str(beta) + \"\\nAccept:\" + str(acc_counter / sample_size))\n\n\t\treturn u_samples\n\n\tdef Metropolis_Hastings(self, sample_size = 1000, beta = 0.1, save_npy = False):\n\t\tu_samples = list()\n\t\tu_samples.append(self.unknown)\n\t\tu_mean = np.zeros(self.dimension_of_unknown)\n\t\tacc_counter = 0.0\n\n\t\tprint(\"Metropolis Hastings:\")\n\t\tfor i in range(sample_size):\n\t\t\tu_mean += u_samples[-1]\n\t\t\tif i % (sample_size / 10) == 0: print((i + 0.0) / sample_size)\n\n\t\t\tif i > 0 and i % (sample_size / 10) == 0: \n\t\t\t\tself.Posterior_Mean = u_mean / len(u_samples) \n\t\t\t\t# self.Plot_CM(len(u_samples) - 1, beta)\n\n\t\t\tu_current = u_samples[-1]\n\t\t\trandom_walk = np.random.multivariate_normal(np.zeros(self.dimension_of_unknown), self.noise_variance * np.eye(self.dimension_of_unknown))\n\t\t\tu_prop = u_current + beta * random_walk\n\t\t\tif (self.Prior == \"TV\"):\n\t\t\t\tacceptance_rate_I = min(1, e ** (self.TV_minimizer(u_current) - self.TV_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"Gaussian\"):\n\t\t\t\tacceptance_rate_I = min(1, e ** (self.Gaussian_minimizer(u_current) - self.Gaussian_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"TG\"):\n\t\t\t\tacceptance_rate_I = min(1, e ** (self.TG_minimizer(u_current) - self.TG_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"pV\"):\n\t\t\t\tacceptance_rate_I = min(1, e ** (self.pV_minimizer(u_current) - self.pV_minimizer(u_prop)))\n\t\t\telif (self.Prior == \"phi_Laplace\"):\n\t\t\t\tacceptance_rate_I = min(1, e ** (self.phi_minimizer(u_current) - self.phi_minimizer(u_prop)))\n\t\t\tif random.uniform(0, 1) < acceptance_rate_I:\n\t\t\t\tu_samples.append(u_prop)\n\t\t\t\tacc_counter += 1\n\t\t\telse:\n\t\t\t\tu_samples.append(u_current)\n\n\t\tprint(\"Accept:\" + str(acc_counter / sample_size))\n\t\tself.Posterior_Mean = u_mean / sample_size\n\t\tself.Plot_CM(sample_size, beta)\n\n\t\t# save the samples as .npy files and the parameters are recorded in .txt files.\n\t\tif (save_npy): \n\t\t\tsamples_np = np.array(u_samples) \n\t\t\tnp.save(self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", samples_np)\n\t\t\tnp.save(\"Observation_time_\" + datetime.now().strftime(\"%H%M%S.%f\") + \".npy\", self.observation)\n\t\t\ttext_file = open(self.Prior + \"_time_\"+ datetime.now().strftime(\"%H%M%S.%f\") + \".txt\", \"w\")\n\t\t\ttext_file.write(\"Lambda = \" + str(self.Lambda) + \"\\np = \" + str(self.p) + \"\\ngamma = \" + str(self.gamma) + \"\\nd = \" + str(self.d)+ \"\\nsample size = \" + str(sample_size) + \"\\nsample step = \" + str(beta) + \"\\nAccept:\" + str(acc_counter / sample_size))\n\n\t\treturn u_samples\n\n\tdef Plot_observation(self):\n\t\tplt.plot(self.observation_ordinate, self.observation, 'x', label = \"observation\")\n\t\tplt.plot(self.observation_ordinate, Gu_initialize(self.observation_ordinate), 'r', label = \"u(t)\")\n\t\tplt.legend()\n\t\tplt.title(\"observation\")\n\t\tif (self.show_figure): plt.show()\n\t\tif (self.save_figure): plt.savefig('Observation_'+datetime.now().strftime(\"_%H%M%S.%f\")+'.pdf')\n\t\tplt.close('all')\n\n\tdef Plot_MAP(self):\n\t\tif (self.Prior == \"TV\") or (self.Prior == \"phi_Laplace\"):\n\t\t\tlegend_text = \"Lambda = \"+str(self.Lambda)\n\t\telif (self.Prior == \"Gaussian\"):\n\t\t\tlegend_text = \"gamma = \"+str(self.gamma)+\"\\nd = \"+str(self.d)\n\t\telif (self.Prior == \"TG\"):\n\t\t\tlegend_text = \"Lambda = \"+str(self.Lambda)+\"\\ngamma = \"+str(self.gamma)+\"\\nd = \"+str(self.d)\n\t\telif (self.Prior == \"pV\"):\n\t\t\tlegend_text = \"Lambda = \"+str(self.Lambda)+\"\\np = \"+str(self.p) \n\n\t\tif (self.show_observation): plt.plot(self.observation_ordinate, self.observation, 'x')\n\t\tplt.plot(self.unknown_ordinate, self.MAP, label = legend_text)\n\t\tplt.legend()\n\t\tplt.title(self.Prior + \" Prior MAP\")\n\t\tif (self.show_figure): plt.show()\n\t\tif (self.save_figure): plt.savefig('MAP_' + self.Prior + datetime.now().strftime(\"_%H%M%S.%f\") + '.pdf')\n\t\t# plt.savefig('MAP_' + prior + time.strftime('_%Y%m%d_%H%M%S.%f') + '.pdf')\n\t\tplt.close('all')\n\n\tdef Plot_CM(self, sample_size, beta):\n\t\tlegend_text = \"123\"\n\t\tif (self.Prior == \"TV\") or (self.Prior == \"phi_Laplace\"):\n\t\t\tlegend_text = \"Sp=\"+str(sample_size)+\"\\nbeta=\"+str(beta)+\"\\nLambda=\"+str(self.Lambda)\n\t\telif (self.Prior == \"Gaussian\"):\n\t\t\tlegend_text = \"Sp=\"+str(sample_size)+\"\\nbeta=\"+str(beta)+\"\\ngamma=\"+str(self.gamma)+\"\\nd=\"+str(self.d)\n\t\telif (self.Prior == \"TG\"):\n\t\t\tlegend_text = \"Sp=\"+str(sample_size)+\"\\nbeta=\"+str(beta)+\"\\nLambda=\"+str(self.Lambda)+\"\\ngamma=\"+str(self.gamma)+\"\\nd=\"+str(self.d)\n\t\telif (self.Prior == \"pV\"):\n\t\t\tlegend_text = \"Sp=\"+str(sample_size)+\"\\nbeta=\"+str(beta)+\"\\nLambda=\"+str(self.Lambda)+\"\\np=\"+str(self.p)\n\n\t\tif (self.show_observation): plt.plot(self.observation_ordinate, self.observation, 'x')\n\t\tplt.plot(self.unknown_ordinate, self.Posterior_Mean, label = legend_text)\n\t\tplt.legend()\n\t\tplt.title(self.Prior + \" Prior Posterior Mean\")\n\t\tif (self.show_figure): plt.show()\n\t\tif (self.save_figure): plt.savefig('CM_'+ self.Prior +datetime.now().strftime(\"_%H%M%S.%f\")+'.pdf')\n\t\tplt.close('all')\n\ndef Plot_CM_from_npy(npy_name, Observation_npy, Prior, Lambda, p, gamma, d, show_observation = False, show_figure = False, save_figure = False):\n\tsamples_np = np.load(npy_name)\n\tdimension_of_unknown = samples_np.shape[1]\n\tunknown_ordinate = np.linspace(0, 1, dimension_of_unknown)\n\n\tnpy_mean = np.mean(samples_np, axis=0)\n\tsample_size = samples_np.shape[0] - 1\n\n\n\tif (Prior == \"TV\") or (Prior == \"phi_Laplace\"): legend_text = \"Lambda=\"+str(Lambda)\n\telif (Prior == \"Gaussian\"): legend_text = \"gamma=\"+str(gamma)+\"\\nd=\"+str(d)\n\telif (Prior == \"TG\"): legend_text = \"Lambda=\"+str(Lambda)+\"\\ngamma=\"+str(gamma)+\"\\nd=\"+str(d)\n\telif (Prior == \"pV\"): legend_text = \"Lambda=\"+str(Lambda)+\"\\np=\"+str(p)\n\n\tif (show_observation): \n\t\tobservation = np.load(Observation_npy)\n\t\tdimension_of_observation = observation.shape[0]\n\t\tobservation_ordinate = np.linspace(0, 1, dimension_of_observation)\n\t\tplt.plot(observation_ordinate, observation, 'x', label = \"observation\")\n\tplt.plot(unknown_ordinate, npy_mean, label = legend_text)\n\tplt.legend()\n\tplt.title(Prior + \" Prior Posterior Mean\")\n\tif (save_figure): plt.savefig('CM_'+ Prior +datetime.now().strftime(\"_%H%M%S.%f\")+'.pdf')\n\tif (show_figure): plt.show()\n\tplt.close('all')\n\n\n###########################################################################################################\nif __name__ == '__main__':\n\tSample_example = Naive_denoising(dimension_of_observation = 61, dimension_of_unknown = 181, noise_variance = 0.03, show_observation = True, show_figure = False, save_figure = True, load_observation = \"Observation.npy\")\n\t# Sample_example.Plot_observation()\n\t# Sample_example.Set_Prior(prior = \"Gaussian\", Lambda = 120, p = 1, gamma = 0.1, d = 0.08)\n\t# Sample_example.pCN(sample_size = 100000, beta = 0.15, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"Gaussian\", Lambda = 120, p = 1, gamma = 0.1, d = 0.12)\n\t# Sample_example.pCN(sample_size = 100000, beta = 0.15, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"Gaussian\", Lambda = 120, p = 1, gamma = 0.1, d = 0.16)\n\t# Sample_example.pCN(sample_size = 100000, beta = 0.15, save_npy = True)\n\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 20, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.035, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 50, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.008, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 100, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.0035, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 120, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.0035, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 150, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.002, save_npy = True)\n\n\t\n\tSample_example.Set_Prior(prior = \"TG\", Lambda = 5, p = 0.5, gamma = 0.1, d = 0.04)\n\tSample_example.pCN(sample_size = 1000000, beta = 0.15, save_npy = True, initialize_unknown_from_npy = \"TG_time_145420.261702.npy\")\n\t# Sample_example.Set_Prior(prior = \"TG\", Lambda = 10, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.07, save_npy = True)\n\t# Sample_example.Set_Prior(prior = \"TG\", Lambda = 30, p = 0.5, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.045, save_npy = True)\n\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 50, p = 0.25, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 2000000, beta = 0.001, save_npy = True)\n\t\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 20, p = 0.25, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 1000000, beta = 0.06, save_npy = True, initialize_unknown_from_npy = \"pG_time_072234.789046.npy\")\n\t\n\t# Sample_example.Set_Prior(prior = \"pG\", Lambda = 60, p = 0.25, gamma = 0.1, d = 0.04)\n\t# Sample_example.pCN(sample_size = 1000000, beta = 0.04, save_npy = True, initialize_unknown_from_npy = \"pG_time_072234.789046.npy\")","sub_path":"Naive_denoising.py","file_name":"Naive_denoising.py","file_ext":"py","file_size_in_byte":19790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"581202542","text":"import random\r\nimport time\r\nimport math\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\ndef random_list (min, max, elements):\r\n list = random.sample(range(min, max), elements)\r\n return list\r\n\r\ndef testCorrect(x,y):\r\n for i in range(0,len(x)):\r\n if (x[i]!=y[i]):\r\n print(\"Incorrect\")\r\n return False\r\n print(\"Correct\")\r\n return True\r\n\r\n\r\n## option 1 -Insertion sort\r\n## option 2 -Merge sort\r\n## x - list of elements\r\n## test - enable/disable if list is sorted correctly\r\n## By default testing is off\r\ndef sortAndTime(x,option,test=False):\r\n if option == 1:\r\n if(test):\r\n print(\"Insertion sort: \\n\")\r\n test=list()\r\n test=x[:]\r\n test.sort()\r\n start_time = time.clock()\r\n insertionSort(x)\r\n end_time = time.clock()\r\n if(test):\r\n testCorrect(test,x)\r\n print(\"Duration insertion: \", end_time - start_time)\r\n return end_time-start_time\r\n elif option == 2:\r\n if(test):\r\n print(\"Merge sort: \\n\")\r\n test=list()\r\n test=x[:]\r\n test.sort()\r\n start_time = time.clock()\r\n mergeSort(x,0,len(x)-1)\r\n end_time = time.clock()\r\n if(test):\r\n testCorrect(test,x)\r\n print(\"Duration merge: \", end_time - start_time)\r\n return end_time-start_time\r\ndef insertionSort(x):\r\n for j in range(1,len(x)):\r\n key=x[j]\r\n i=j-1\r\n while i>=0 and x[i] > key:\r\n x[i+1]=x[i]\r\n i=i-1\r\n x[i+1]=key\r\n\r\n\r\ndef merge(x,p,q,r):\r\n n1=q-p+1\r\n n2=r-q\r\n L=list()\r\n R=list()\r\n for i in range(0,n1):\r\n L.append(x[p+i])\r\n for i in range(0,n2):\r\n R.append(x[q+i+1])\r\n L.append(sys.maxsize)\r\n R.append(sys.maxsize)\r\n j=0\r\n i=0\r\n for k in range(p,r+1):\r\n if L[i]<=R[j]:\r\n x[k]=L[i]\r\n i=i+1\r\n else:\r\n x[k] = R[j]\r\n j=j+1\r\n\r\ndef mergeSort(x,p,r):\r\n if p x[mid]:\n\r\n return mid+binarySearch(x[mid:],A)\r\n elif A < x[mid]:\r\n return binarySearch(x[:mid],A)\r\n else:\r\n return -sys.maxsize\r\n return mid\r\n\r\ndef binaryCall (x,A):\r\n index =0;\r\n index = binarySearch(x, A)\r\n if(index<0):\r\n print(\"Container has no item of value: \"+str(A))\r\n return -sys.maxsize\r\n else:\r\n print(\"Index: \"+ str(index))\r\n return index\r\n\r\nnumberOfMaxElements=100000\r\nx=range(0,numberOfMaxElements)\r\ninsertionSortTime=list()\r\nmergeSortTime=list()\r\nfor i in range(0,numberOfMaxElements+1,10000):\r\n y1=random_list(0,numberOfMaxElements*100,i)\r\n insertionSortTime.append(sortAndTime(y1,1))\r\n y2=random_list(0,numberOfMaxElements*100,i)\r\n mergeSortTime.append(sortAndTime(y2,2))\r\n\r\nplt.grid('on')\r\nplt.plot(x,y1,x,y2,'r--')\r\nplt.ylabel(\"Time\")\r\nplt.xlabel(\"Number of elements\")\r\nplt.show()\r\n","sub_path":"V2.py","file_name":"V2.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"318977394","text":"\"\"\"\nSe consideran 5 posibles presentaciones de la edad en cada entrevista: \ntipo a:\n\t1=xx-xx-xxxx\n\t2=xx-xx-xx\ntipo b:\n\t3=xx/xx/xxxx\n\t4=xx/xx/xx\ntipo c:\n\t5=xx años\n\t6=edad xx (años)\n\"\"\"\nimport re\n\nfrom nltk import ngrams\n\n\n\n\nwith open(\"/home/ellobo/Documentos/gen/nombres.txt\", 'r') as f:\n\tarchivos = f.read().split('\\n')\n\n\nl=0\n\nfor archivo in archivos:\n\twith open(\"/home/ellobo/Documentos/gen/datos_limpios/\"+archivo, 'r') as k:\n\t\tentrevistadeverdad = k.read()\n\t\n\tentrevista = entrevistadeverdad.lower()\n\n\ttry:\n\t\tprint(re.search('\\d\\d\\sedad', entrevista).group(0))\n\n\texcept:\n\t\t\n\n\t\ttry:\n\t\t\tprint(re.search('edad\\s\\d\\d', entrevista).group(0))\n\n\t\texcept:\t\t\t\n\t\t\n\t\t\ttry: \n\t\t\t\tprint(re.search('años\\s\\d\\d', entrevista).group(0))\n\n\t\t\texcept:\n\t\t\t\t\n\n\t\t\t\ttry: \n\t\t\t\t\tprint(re.search('\\d\\d\\saños', entrevista).group(0))\n\t\n\t\t\t\texcept:\n\t\t\t\t\ttry:\n\t\t\t\t\t\t\n\t\t\t\t\t\tstri=str(re.search('fecha.+nac.+\\d+.+\\d+.+\\d+', entrevista).group(0))\n\t\t\t\t\t\taño_nac= int(re.search('\\d{4}', stri).group(0))\n\t\t\t\t\t\tedad=2016-año_nac\n\t\t\t\t\t\tprint(edad)\n\t\t\t\t\texcept:\n\t\t\t\t\t\tl+=1\n\t\t\t\t\t\terrores = 'errores'\n\t\t\t\t\t\tprint(str(l)+' '+errores)\n\t\n\n\n\n\n\t\"\"\"\n\n\tgramas = ngrams(entrevista.split(), 4)\n\n\tvector_gramas =[]\n\n\tfor grama in gramas:\n\t\tvector_gramas.append(grama)\n\n\ttry: \n\t\tgramas_importa = list(filter(lambda x:'edad' in x, vector_gramas))\n\n\t\tcual_es = gramas_importa[1]\n\n\n\t\tprint(cual_es)\n\n\texcept:\n\t\tprint('la cagaste')\n\n\t\n\n\tpor_fecha_nac = re.search('Fecha\\s+d?e?\\sNa\\w+|fecha\\s+d?e?\\sNa\\w+|Fecha\\s+d?e?\\sna\\w+|fecha\\s+d?e?\\sna\\w+', entrevista)\n\tpor_edad = re.search('edad', entrevista)\n\tpor_años = re.search('años', entrevista)\n\n\tprimer_fecha = por_fecha_nac[0]\n\tprimer_edad = por_edad[0]\n\tprimer_años = por_años[0]\n\n\n\n\nfecha nac.\n\nedad xx años\n\nfecha nacimiento\n\nLugar y Fecha de Nacimiento 12 - Abr de 1972\n\nLugar y Fecha de Nacimiento(Vereda,Corregimiento,Inspección ,\n\nMunicipio y Departamento )\n\nSogamoso(Boyaca)marzo 1977\n\nLugar Yecha\nDe\n\nPuertogaitan(Meta ).24 -nov-1975\n\nLugar y Fecha de Nacimiento San Martín de Loba,Departamento de\nBolívar,15.Ene.1971\n\n071010 no dice fecha de nacimiento\n\n\nEdad\n22 años\n\n\n\"\"\"","sub_path":"data/basura/edad.py","file_name":"edad.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"53179270","text":"import numpy as np\n# The library below is used for visualization only.\nimport matplotlib.pyplot as plt\n\nimage_width = 28\nimage_size = pow(image_width, 2)\n\ndef read_img(file_name):\n header_size = 16\n\n with open(file_name, 'rb') as f:\n header = f.read(header_size)\n images = list()\n # norm_images = list()\n image = list()\n count = 0\n\n for pixel in f.read():\n # normalize into 2 bins\n pixel = pixel // 128\n image.append(pixel)\n count += 1\n if count == image_size:\n images.append(image)\n image = list()\n count = 0\n\n # return images\n return np.array(images)\n\n\ndef read_label(file_name):\n header_size = 8\n\n with open(file_name, 'rb') as f:\n header = f.read(header_size)\n labels = list()\n\n for label in f.read():\n labels.append(label)\n \n return np.array(labels)\n\n\ndef show_img(image):\n image = image.reshape(image_width, image_width)\n plt.imshow(image)\n plt.show()\n","sub_path":"HW4/read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579699117","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time: 2019/1/5\n# @Author: wujide\nimport os\nimport shutil\n\n\ndef cmp_files(dir_first, dir_second):\n \"\"\"\n 找出dir_first 中所有的文件,遍历所有的文件 并和 dir_second 中所有的文件名相比较\n 找到,则将dir_second 移到 duplicated_files 文件中,并继续查找,直到结束\n :param dir_first:\n :param dir_second:\n :return:\n \"\"\"\n files_path_list = get_files(dir_first)\n for file_path in files_path_list:\n file = os.path.split(file_path)[1]\n find_duplicated_files(file, dir_second)\n\n\n# 找出文件夹下所有文件,返回绝对路径+文件名\ndef get_files(abspath):\n files_path_list = []\n for x in os.listdir(abspath):\n if not x.startswith('.'):\n path = abspath + '/' + x\n if os.path.isfile(path):\n files_path_list.append(path)\n else:\n get_files(path)\n return files_path_list\n\n\ndef find_duplicated_files(file, dir_second):\n files_second_list = get_files(dir_second)\n for x in files_second_list:\n file_sec = os.path.split(x)[1]\n if os.path.isfile(x):\n if file == file_sec:\n print(file_sec, 'is duplicated in :', path)\n print(file_sec, 'is moved to: duplicated_files')\n move_files(x)\n continue\n else:\n # print(file, \"comparing in:\", path)\n find_duplicated_files(file, x)\n\n # for x in os.listdir(dir_second):\n # path = dir_second + '/' + x\n # if os.path.isfile(path):\n # if file == x:\n # print(x, 'is duplicated in :', path)\n # print(x, 'is moved to: duplicated_files')\n # move_files(path)\n # continue\n # else:\n # # print(file, \"comparing in:\", path)\n # find_duplicated_files(file, path)\n\n\ndef move_files(duplicate_files):\n dup_file_path = '/Users/wujide/Documents/duplicated_files'\n shutil.move(duplicate_files, dup_file_path)\n\n\ndef all_files(file_path):\n # file_path 下面所有的目录或文件列表(不包含隐藏文件)\n paths = [os.path.join(file_path, x)\n for x in os.listdir(file_path) if not x.startswith('.')]\n # 遍历列表,将第i个文件同i+1,+2... 个相比较\n for i in range(len(paths) - 1):\n for path in paths[(i + 1):]:\n # print(paths[i], '<------------->', path)\n cmp_files(paths[i], path)\n # find_duplicated_files(paths[i], path)\n\n\nif __name__ == '__main__':\n path = '/Users/wujide/Documents/照片备份/'\n all_files(path)\n","sub_path":"duplicate_files.py","file_name":"duplicate_files.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"644478058","text":"\"\"\"\nAssim como map, a função filter não retorna uma lista e sim um\niterator do tipo map. Para resolver isso, devemos fazer um cast\npara torná-la uma lista.\n\n# Exemplo\n\nfrom dados import produtos, pessoas, lista\n\nnova_lista = filter(lambda x: x > 5, lista)\nprint(list(nova_lista))\n\n# Exemplo com list comprehension\n\nnova_lista2 = [x for x in lista if x > 5]\nprint(list(nova_lista2))\n\n# Exemplo\n\nnova_lista3 = filter(lambda p: p['preco'] > 20, produtos)\nfor produto in nova_lista3:\n print(produto)\n\n# Exemplo mais complexo\n\n\ndef filtra(produto):\n if produto['preco'] > 50:\n produto['eh_caro'] = True\n return True\n\n\nnova_lista4 = filter(filtra, produtos)\n\nfor produto in nova_lista4:\n print(produto)\n\n\"\"\"\n\nfrom dados import produtos, pessoas, lista\n\n# Exemplo filtro em pessoas (maiores de idade)\n\n\ndef filtra(pessoa):\n if pessoa['idade'] >= 18:\n return True\n\n\nnova_lista5 = filter(filtra, pessoas)\n\nfor produto in nova_lista5:\n print(produto)\n","sub_path":"Curso_de_Python_3_do Basico_ao_Avancado_com_projetos_reais/Aulas/Aula81_filter.py","file_name":"Aula81_filter.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603962539","text":"import os\nfrom materias import Materias\n\nclass App():\n\n def __init__(self):\n pass\n\n def ejecutar(self):\n materia=Materias()\n materia.setCreditos()\n materias=materia.getCreditos()\n self.imprimir(materias)\n \n def imprimir(self,materia):\n total=0\n for key in materia:\n print (key,\"tiene\",materia[key],\"creditos\")\n total=total+materia[key]\n print(\"\\nNumero total de creditos del curso:\",total)\n print()\n\nif __name__ == \"__main__\":\n os.system(\"clear\")\n app=App()\n app.ejecutar()\n","sub_path":"59289-Ignacio-Carrillo/TP1/ej11/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"115503037","text":"#!/usr/bin/python\n# encoding: utf-8\n#\n# Copyright 2020 Armin Briegel.\n#\n# based on Greg Neagle's 'installinstallmacos.py'\n# https://github.com/munki/macadmin-scripts/blob/main/installinstallmacos.py\n#\n# with many thanks to Greg Neagle for the original script and lots of advice\n# and Mike Lynn for helping me figure out the software update catalog\n# Graham R Pugh for figurung out the 11.1 download\n# see his combined version of mine and Greg's script here:\n# https://github.com/grahampugh/erase-install/tree/pkg\n\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"fetch-full-installer.py\nA tool to download the a pkg installer for the Install macOS app from Apple's\nsoftwareupdate servers\"\"\"\n\n# Python 3 compatibility shims\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport gzip\nimport os\nimport plistlib\nimport subprocess\nimport sys\nimport logging\nimport json\nfrom datetime import datetime\n\ntry:\n # python 2\n from urllib.parse import urlsplit\nexcept ImportError:\n # python 3\n from urlparse import urlsplit\nfrom xml.dom import minidom\nfrom xml.parsers.expat import ExpatError\nimport xattr\n\n\nDEFAULT_SUCATALOGS = {\n \"17\": \"https://swscan.apple.com/content/catalogs/others/\"\n \"index-10.13-10.12-10.11-10.10-10.9\"\n \"-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\",\n \"18\": \"https://swscan.apple.com/content/catalogs/others/\"\n \"index-10.14-10.13-10.12-10.11-10.10-10.9\"\n \"-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\",\n \"19\": \"https://swscan.apple.com/content/catalogs/others/\"\n \"index-10.15-10.14-10.13-10.12-10.11-10.10-10.9\"\n \"-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\",\n \"20\": \"https://swscan.apple.com/content/catalogs/others/\"\n \"index-11-10.15-10.14-10.13-10.12-10.11-10.10-10.9\"\n \"-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\",\n}\n\nSEED_CATALOGS_PLIST = (\n \"/System/Library/PrivateFrameworks/Seeding.framework/Versions/Current/\"\n \"Resources/SeedCatalogs.plist\"\n)\n\nWORKING_DIR = \"/tmp\"\n\n\ndef get_logger():\n logger = logging.getLogger(os.path.basename(__file__))\n logger.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setFormatter(\n logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n )\n logger.addHandler(handler)\n\n return logger\n\n\nlog = get_logger()\n\n\ndef get_input(prompt=None):\n \"\"\"Python 2 and 3 wrapper for raw_input/input\"\"\"\n try:\n return raw_input(prompt)\n except NameError:\n # raw_input doesn't exist in Python 3\n return input(prompt)\n\n\ndef read_plist(filepath):\n \"\"\"Wrapper for the differences between Python 2 and Python 3's plistlib\"\"\"\n try:\n with open(filepath, \"rb\") as fileobj:\n return plistlib.load(fileobj)\n except AttributeError:\n # plistlib module doesn't have a load function (as in Python 2)\n return plistlib.readPlist(filepath)\n\n\ndef read_plist_from_string(bytestring):\n \"\"\"Wrapper for the differences between Python 2 and Python 3's plistlib\"\"\"\n try:\n return plistlib.loads(bytestring)\n except AttributeError:\n # plistlib module doesn't have a load function (as in Python 2)\n return plistlib.readPlistFromString(bytestring)\n\n\ndef get_seeding_program(sucatalog_url):\n \"\"\"Returns a seeding program name based on the sucatalog_url\"\"\"\n try:\n seed_catalogs = read_plist(SEED_CATALOGS_PLIST)\n for key, value in seed_catalogs.items():\n if sucatalog_url == value:\n return key\n return \"\"\n except (OSError, IOError, ExpatError, AttributeError, KeyError) as err:\n log.warn(err)\n return \"\"\n\n\ndef get_seed_catalog(seedname=\"DeveloperSeed\"):\n \"\"\"Returns the developer seed sucatalog\"\"\"\n try:\n seed_catalogs = read_plist(SEED_CATALOGS_PLIST)\n return seed_catalogs.get(seedname)\n except (OSError, IOError, ExpatError, AttributeError, KeyError) as err:\n log.warn(err)\n return \"\"\n\n\ndef get_seeding_programs():\n \"\"\"Returns the list of seeding program names\"\"\"\n try:\n seed_catalogs = read_plist(SEED_CATALOGS_PLIST)\n return list(seed_catalogs.keys())\n except (OSError, IOError, ExpatError, AttributeError, KeyError) as err:\n log.warn(err)\n return \"\"\n\n\ndef get_default_catalog():\n \"\"\"Returns the default softwareupdate catalog for the current OS\"\"\"\n darwin_major = os.uname()[2].split(\".\")[0]\n return DEFAULT_SUCATALOGS.get(darwin_major)\n\n\nclass ReplicationError(Exception):\n \"\"\"A custom error when replication fails\"\"\"\n\n pass\n\n\ndef content_length(full_url):\n try:\n output = subprocess.check_output(\n [\"/usr/bin/curl\", \"--silent\", \"--head\", \"-i\", \"-fL\", full_url]\n )\n\n for line in output.splitlines():\n if line.strip().startswith(\"Content-Length:\"):\n return int(line.split(\":\")[-1].strip())\n\n return None\n except subprocess.CalledProcessError as err:\n raise ReplicationError(err)\n\n\ndef replicate_url(\n full_url, dest=None, default_workdir=None, show_progress=False, ignore_cache=False\n):\n \"\"\"Downloads a URL and stores it in the same relative path on our\n filesystem. Returns a path to the replicated file.\"\"\"\n\n if default_workdir is None:\n default_workdir = WORKING_DIR\n\n if dest is None:\n dest = os.path.normpath(urlsplit(full_url)[2].lstrip(\"/\"))\n\n if not dest.startswith(\"/\"):\n dest = os.path.join(default_workdir, dest)\n\n if show_progress:\n options = \"-fL\"\n else:\n options = \"-sfL\"\n\n filename = dest.split(\"/\")[-1]\n curl_cmd = [\"/usr/bin/curl\", options, \"--create-dirs\", \"-o\", dest]\n\n if not full_url.endswith(\".gz\"):\n # stupid hack for stupid Apple behavior where it sometimes returns\n # compressed files even when not asked for\n curl_cmd.append(\"--compressed\")\n\n if ignore_cache and os.path.exists(dest):\n os.remove(dest)\n\n if not ignore_cache and os.path.exists(dest):\n remote_bytes = content_length(full_url)\n cached_bytes = os.path.getsize(dest)\n if remote_bytes == cached_bytes:\n log.info(\"%s is cached - skipping download.\" % (filename))\n return dest\n elif remote_bytes < cached_bytes:\n os.remove(dest)\n else:\n log.info(\n \"%s is partially cached - resuming download from %s...\"\n % (filename, full_url)\n )\n curl_cmd.extend([\"-C\", \"-\"])\n else:\n log.info(\"%s is required - downloading from %s...\" % (filename, full_url))\n\n curl_cmd.append(full_url)\n\n try:\n subprocess.check_call(curl_cmd)\n except subprocess.CalledProcessError as err:\n raise ReplicationError(err)\n\n return dest\n\n\ndef parse_server_metadata(filename):\n \"\"\"Parses a softwareupdate server metadata file, looking for information\n of interest.\n Returns a dictionary containing title, version, and description.\"\"\"\n title = \"\"\n vers = \"\"\n try:\n md_plist = read_plist(filename)\n except (OSError, IOError, ExpatError) as err:\n log.error(\"Error reading %s: %s\" % (filename, err))\n return {}\n vers = md_plist.get(\"CFBundleShortVersionString\", \"\")\n localization = md_plist.get(\"localization\", {})\n preferred_localization = localization.get(\"English\") or localization.get(\"en\")\n if preferred_localization:\n title = preferred_localization.get(\"title\", \"\")\n\n metadata = {}\n metadata[\"title\"] = title\n metadata[\"version\"] = vers\n return metadata\n\n\ndef get_server_metadata(catalog, product_key, ignore_cache=False):\n \"\"\"Replicate ServerMetaData\"\"\"\n try:\n url = catalog[\"Products\"][product_key][\"ServerMetadataURL\"]\n try:\n smd_path = replicate_url(url, ignore_cache=ignore_cache)\n return smd_path\n except ReplicationError as err:\n log.warn(\"Could not replicate %s: %s\" % (url, err))\n return None\n except KeyError:\n # log.info('Malformed catalog.')\n return None\n\n\ndef parse_dist(filename):\n \"\"\"Parses a softwareupdate dist file, returning a dict of info of\n interest\"\"\"\n dist_info = {}\n try:\n dom = minidom.parse(filename)\n except ExpatError:\n log.warn(\"Invalid XML in %s\" % filename)\n return dist_info\n except IOError as err:\n log.warn(\"Error reading %s: %s\" % (filename, err))\n return dist_info\n\n titles = dom.getElementsByTagName(\"title\")\n if titles:\n dist_info[\"title_from_dist\"] = titles[0].firstChild.wholeText\n\n auxinfos = dom.getElementsByTagName(\"auxinfo\")\n if not auxinfos:\n return dist_info\n auxinfo = auxinfos[0]\n key = None\n value = None\n children = auxinfo.childNodes\n # handle the possibility that keys from auxinfo may be nested\n # within a 'dict' element\n dict_nodes = [\n n\n for n in auxinfo.childNodes\n if n.nodeType == n.ELEMENT_NODE and n.tagName == \"dict\"\n ]\n if dict_nodes:\n children = dict_nodes[0].childNodes\n for node in children:\n if node.nodeType == node.ELEMENT_NODE and node.tagName == \"key\":\n key = node.firstChild.wholeText\n if node.nodeType == node.ELEMENT_NODE and node.tagName == \"string\":\n value = node.firstChild.wholeText\n if key and value:\n dist_info[key] = value\n key = None\n value = None\n return dist_info\n\n\ndef download_and_parse_sucatalog(sucatalog, ignore_cache=False):\n \"\"\"Downloads and returns a parsed softwareupdate catalog\"\"\"\n try:\n localcatalogpath = replicate_url(sucatalog, ignore_cache=ignore_cache)\n except ReplicationError as err:\n log.error(\"Could not replicate %s: %s\" % (sucatalog, err))\n sys.exit(1)\n if os.path.splitext(localcatalogpath)[1] == \".gz\":\n with gzip.open(localcatalogpath) as the_file:\n content = the_file.read()\n try:\n catalog = read_plist_from_string(content)\n return catalog\n except ExpatError as err:\n log.info(\"Error reading %s: %s\" % (localcatalogpath, err))\n sys.exit(1)\n else:\n try:\n catalog = read_plist(localcatalogpath)\n return catalog\n except (OSError, IOError, ExpatError) as err:\n log.error(\"Error reading %s: %s\" % (localcatalogpath, err))\n sys.exit(1)\n\n\ndef get_installassistant_pkgs(product):\n with_auto = filter(\n lambda pkg: pkg[\"URL\"].endswith(\"InstallAssistant.pkg\")\n or pkg[\"URL\"].endswith(\"InstallAssistantAuto.pkg\"),\n filter(lambda pkg: pkg.get(\"URL\"), product[\"Packages\"]),\n )\n\n return (\n filter(lambda pkg: pkg[\"URL\"].endswith(\"InstallAssistant.pkg\"), with_auto)\n or with_auto\n )\n\n\ndef find_mac_os_installers(\n catalog, shared_support_only=False, pkg_installers_only=False\n):\n \"\"\"Return a list of product identifiers for what appear to be macOS\n installers\"\"\"\n mac_os_installer_products = []\n if \"Products\" in catalog:\n for product_key in catalog[\"Products\"].keys():\n product = catalog[\"Products\"][product_key]\n installassistant_ids = product.get(\"ExtendedMetaInfo\", {}).get(\n \"InstallAssistantPackageIdentifiers\"\n )\n if installassistant_ids is None:\n continue\n\n if (\n installassistant_ids.get(\"SharedSupport\") or not shared_support_only\n ) and (get_installassistant_pkgs(product) or not pkg_installers_only):\n mac_os_installer_products.append(product_key)\n\n return mac_os_installer_products\n\n\ndef os_installer_product_info(catalog, ignore_cache=False, pkg_installers_only=False):\n \"\"\"Returns a dict of info about products that look like macOS installers\"\"\"\n product_info = {}\n installer_products = find_mac_os_installers(\n catalog, pkg_installers_only=pkg_installers_only\n )\n for product_key in installer_products:\n product_info[product_key] = {}\n filename = get_server_metadata(catalog, product_key)\n if filename:\n product_info[product_key] = parse_server_metadata(filename)\n else:\n log.warn(\"No server metadata for %s\" % product_key)\n product_info[product_key][\"title\"] = None\n product_info[product_key][\"version\"] = None\n\n product = catalog[\"Products\"][product_key]\n product_info[product_key][\"PostDate\"] = product[\"PostDate\"]\n distributions = product[\"Distributions\"]\n dist_url = distributions.get(\"English\") or distributions.get(\"en\")\n try:\n dist_path = replicate_url(\n dist_url, show_progress=False, ignore_cache=ignore_cache\n )\n except ReplicationError as err:\n log.warn(\"Could not replicate %s: %s\" % (dist_url, err))\n else:\n dist_info = parse_dist(dist_path)\n product_info[product_key][\"DistributionPath\"] = dist_path\n product_info[product_key].update(dist_info)\n if not product_info[product_key][\"title\"]:\n product_info[product_key][\"title\"] = dist_info.get(\"title_from_dist\")\n if not product_info[product_key][\"version\"]:\n product_info[product_key][\"version\"] = dist_info.get(\"VERSION\")\n\n return product_info\n\n\ndef replicate_product(catalog, product_id, show_progress=False, ignore_cache=False):\n \"\"\"Downloads all the packages for a product\"\"\"\n product = catalog[\"Products\"][product_id]\n\n for package in product.get(\"Packages\", []):\n # TO-DO: Check 'Size' attribute and make sure\n # we have enough space on the target\n # filesystem before attempting to download\n if \"URL\" in package:\n try:\n replicate_url(\n package[\"URL\"],\n show_progress=show_progress,\n ignore_cache=ignore_cache,\n )\n except ReplicationError as err:\n log.error(\"Could not replicate %s: %s\" % (package[\"URL\"], err))\n sys.exit(1)\n if \"MetadataURL\" in package:\n try:\n replicate_url(\n package[\"MetadataURL\"],\n ignore_cache=ignore_cache,\n )\n except ReplicationError as err:\n log.error(\"Could not replicate %s: %s\" % (package[\"MetadataURL\"], err))\n sys.exit(1)\n\n\ndef interactive_product_selection(options, product_info):\n def select_product_id(raw_answer):\n if not raw_answer:\n return None\n\n try:\n index = int(raw_answer) - 1\n assert index >= 0\n return options[index]\n except (ValueError, IndexError, AssertionError):\n print(\"Invalid selection. Please try again.\")\n return None\n\n print(\n \"%2s %14s %10s %8s %11s %s\"\n % (\"#\", \"ProductID\", \"Version\", \"Build\", \"Post Date\", \"Title\")\n )\n for index, product_id in enumerate(options):\n print(\n \"%2s %14s %10s %8s %11s %s\"\n % (\n index + 1,\n product_id,\n product_info[product_id].get(\"version\", \"UNKNOWN\"),\n product_info[product_id].get(\"BUILD\", \"UNKNOWN\"),\n product_info[product_id][\"PostDate\"].strftime(\"%Y-%m-%d\"),\n product_info[product_id][\"title\"],\n )\n )\n\n product_id = None\n while product_id is None:\n product_id = select_product_id(\n get_input(\"\\nChoose a product to download (1-%s): \" % len(options))\n )\n\n return product_id\n\n\ndef install_product(dist_path, target_vol):\n \"\"\"Install a product to a target volume.\n Returns a boolean to indicate success or failure.\"\"\"\n # set CM_BUILD env var to make Installer bypass eligibilty checks\n # when installing packages (for machine-specific OS builds)\n os.environ[\"CM_BUILD\"] = \"CM_BUILD\"\n cmd = [\"/usr/sbin/installer\", \"-pkg\", dist_path, \"-target\", target_vol]\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError as err:\n log.warn(err)\n return False\n else:\n # Apple postinstall script bug ends up copying files to a path like\n # /tmp/dmg.T9ak1HApplications\n path = target_vol + \"Applications\"\n if os.path.exists(path):\n log.info(\"Working around a very dumb Apple bug\")\n subprocess.check_call(\n [\"/usr/bin/ditto\", path, os.path.join(target_vol, \"Applications\")]\n )\n subprocess.check_call([\"/bin/rm\", \"-r\", path])\n return True\n\n\ndef make_sparse_image(volume_name, output_path):\n \"\"\"Make a sparse disk image we can install a product to\"\"\"\n cmd = [\n \"/usr/bin/hdiutil\",\n \"create\",\n \"-size\",\n \"16g\",\n \"-fs\",\n \"HFS+\",\n \"-volname\",\n volume_name,\n \"-type\",\n \"SPARSE\",\n \"-plist\",\n output_path,\n ]\n try:\n output = subprocess.check_output(cmd)\n except subprocess.CalledProcessError as err:\n log.error(err)\n sys.exit(1)\n try:\n return read_plist_from_string(output)[0]\n except IndexError as err:\n log.error(\"Unexpected output from hdiutil: %s\" % output)\n sys.exit(1)\n except ExpatError as err:\n log.error(\"Malformed output from hdiutil: %s\" % output)\n log.error(err)\n sys.exit(1)\n\n\ndef mountdmg(dmgpath):\n \"\"\"\n Attempts to mount the dmg at dmgpath and returns first mountpoint\n \"\"\"\n mountpoints = []\n dmgname = os.path.basename(dmgpath)\n cmd = [\n \"/usr/bin/hdiutil\",\n \"attach\",\n dmgpath,\n \"-mountRandom\",\n \"/tmp\",\n \"-nobrowse\",\n \"-plist\",\n \"-owners\",\n \"on\",\n ]\n proc = subprocess.Popen(\n cmd, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n (pliststr, err) = proc.communicate()\n if proc.returncode:\n log.error('Error: \"%s\" while mounting %s.' % (err, dmgname))\n return None\n if pliststr:\n plist = read_plist_from_string(pliststr)\n for entity in plist[\"system-entities\"]:\n if \"mount-point\" in entity:\n mountpoints.append(entity[\"mount-point\"])\n\n return mountpoints[0]\n\n\ndef unmountdmg(mountpoint):\n \"\"\"\n Unmounts the dmg at mountpoint\n \"\"\"\n proc = subprocess.Popen(\n [\"/usr/bin/hdiutil\", \"detach\", mountpoint],\n bufsize=-1,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n (dummy_output, err) = proc.communicate()\n if proc.returncode:\n log.warn(\"Polite unmount failed: %s\" % err)\n log.warn(\"Attempting to force unmount %s\" % mountpoint)\n # try forcing the unmount\n retcode = subprocess.call([\"/usr/bin/hdiutil\", \"detach\", mountpoint, \"-force\"])\n if retcode:\n log.warn(\"Failed to unmount %s\" % mountpoint)\n\n\ndef find_installer_app(mountpoint):\n \"\"\"Returns the path to the Install macOS app on the mountpoint\"\"\"\n applications_dir = os.path.join(mountpoint, \"Applications\")\n for item in os.listdir(applications_dir):\n if item.endswith(\".app\"):\n return os.path.join(applications_dir, item)\n return None\n\n\ndef make_compressed_dmg(app_path, diskimagepath):\n \"\"\"Returns path to newly-created compressed r/o disk image containing\n Install macOS.app\"\"\"\n\n cmd = [\n \"/usr/bin/hdiutil\",\n \"create\",\n \"-fs\",\n \"HFS+\",\n \"-srcfolder\",\n app_path,\n diskimagepath,\n ]\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError as err:\n log.warn(err)\n else:\n log.info(\"Disk image created at: %s\" % diskimagepath)\n\n\ndef installinstallmacos(\n catalog,\n su_catalog_url,\n product_id,\n product_info,\n show_progress=False,\n ignore_cache=False,\n):\n macos_version = product_info.get(\"version\", \"UNKNOWN\")\n volname = \"Install_macOS_%s-%s\" % (\n macos_version,\n product_info[\"BUILD\"],\n )\n downloaded_artifact = os.path.join(WORKING_DIR, volname + \".dmg\")\n if os.path.exists(downloaded_artifact):\n if ignore_cache:\n os.remove(downloaded_artifact)\n else:\n log.info(\n \"Read-only compressed dmg containing installer app is already cached.\"\n )\n return downloaded_artifact\n\n replicate_product(\n catalog,\n product_id,\n show_progress=show_progress,\n ignore_cache=ignore_cache,\n )\n\n sparse_diskimage_path = os.path.join(WORKING_DIR, volname + \".sparseimage\")\n if os.path.exists(sparse_diskimage_path):\n os.unlink(sparse_diskimage_path)\n\n log.info(\"Making empty sparseimage...\")\n sparse_diskimage_path = make_sparse_image(volname, sparse_diskimage_path)\n\n mountpoint = mountdmg(sparse_diskimage_path)\n if not mountpoint or not os.path.exists(mountpoint):\n log.error(\"Failed to mount downloaded diskimage!\")\n sys.exit(1)\n\n try:\n err = None\n log.info(\"Installing product to mounted image...\")\n success = install_product(product_info[\"DistributionPath\"], mountpoint)\n if not success:\n log.error(\"Product installation failed.\")\n sys.exit(1)\n\n installer_app = find_installer_app(mountpoint)\n if not installer_app:\n log.error(\"No installer .app found in downloaded artifact!\")\n sys.exit(1)\n\n seeding_program = get_seeding_program(su_catalog_url)\n if seeding_program:\n log.info(\n \"Adding seeding program %s extended attribute to app\" % seeding_program\n )\n xattr.setxattr(installer_app, \"SeedProgram\", seeding_program)\n\n log.info(\n \"Creating read-only compressed dmg containing %s...\"\n % (os.path.basename(installer_app))\n )\n make_compressed_dmg(installer_app, downloaded_artifact)\n except Exception as err:\n log.error(\"Unexpected error:\")\n log.error(err)\n except SystemExit as err:\n print(\"Goodbye!\")\n finally:\n unmountdmg(mountpoint)\n os.unlink(sparse_diskimage_path)\n if err:\n sys.exit(1)\n\n return downloaded_artifact\n\n\ndef main():\n \"\"\"Do the main thing here\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--seedprogram\",\n default=\"\",\n help=\"Which Seed Program catalog to use. Valid values \"\n \"are %s.\" % \", \".join(get_seeding_programs()),\n )\n parser.add_argument(\n \"--catalogurl\",\n default=\"\",\n help=\"Software Update catalog URL. This option \"\n \"overrides any seedprogram option.\",\n )\n parser.add_argument(\n \"--workdir\",\n metavar=\"path_to_working_dir\",\n default=\".\",\n help=\"Path to working directory on a volume with over \"\n \"10G of available space. Defaults to current working \"\n \"directory.\",\n )\n parser.add_argument(\n \"--ignore-cache\",\n action=\"store_true\",\n help=\"Ignore any previously cached files.\",\n )\n parser.add_argument(\n \"--latest\",\n action=\"store_true\",\n help=\"Download the latest version with no user interaction.\",\n )\n parser.add_argument(\n \"--open-with-finder\",\n action=\"store_true\",\n help=\"Open installer pkg with finder once complete.\",\n )\n parser.add_argument(\n \"--show-progress\", action=\"store_true\", help=\"Show curl progress.\"\n )\n parser.add_argument(\n \"--write-receipt\",\n action=\"store_true\",\n help=\"Write receipt on successful download.\",\n )\n parser.add_argument(\n \"--version\",\n default=\"\",\n help=\"Only find installers for version. With --latest, download the latest for version.\",\n )\n parser.add_argument(\n \"--pkg-installers-only\",\n action=\"store_true\",\n help=\"Only consider and download macOS installers with a full InstallAssistant.pkg. If false, .dmg installers are also considered for download.\",\n )\n args = parser.parse_args()\n\n current_dir = os.getcwd()\n\n if args.catalogurl:\n su_catalog_url = args.catalogurl\n elif args.seedprogram:\n su_catalog_url = get_seed_catalog(args.seedprogram)\n if not su_catalog_url:\n log.error(\n \"Could not find a catalog url for seed program %s\" % args.seedprogram,\n file=sys.stderr,\n )\n log.error(\n \"Valid seeding programs are: %s\" % \", \".join(get_seeding_programs()),\n file=sys.stderr,\n )\n sys.exit(1)\n else:\n su_catalog_url = get_default_catalog()\n if not su_catalog_url:\n log.error(\n \"Could not find a default catalog url for this OS version.\",\n file=sys.stderr,\n )\n sys.exit(1)\n\n global WORKING_DIR\n WORKING_DIR = args.workdir\n\n log.info(\"Searching catalog: \" + su_catalog_url)\n\n # download sucatalog and look for products that are for macOS installers\n catalog = download_and_parse_sucatalog(\n su_catalog_url, ignore_cache=args.ignore_cache\n )\n\n # log.info(catalog)\n product_info = os_installer_product_info(\n catalog,\n ignore_cache=args.ignore_cache,\n pkg_installers_only=args.pkg_installers_only,\n )\n\n # sort the list by release date\n sorted_product_info = filter(\n lambda pid: not args.version or product_info[pid][\"version\"] == args.version,\n sorted(product_info, key=lambda k: product_info[k][\"PostDate\"], reverse=True),\n )\n\n if not sorted_product_info:\n log.error(\n \"No macOS installer products found in the sucatalog for version: \"\n + args.version\n if args.version\n else \"any\"\n )\n sys.exit(1)\n\n log.info(\"Found %s installers.\" % (str(len(product_info))))\n\n if args.latest or len(sorted_product_info) == 1:\n product_id = sorted_product_info[0]\n else:\n product_id = interactive_product_selection(sorted_product_info, product_info)\n\n selected_product_info = product_info[product_id]\n macos_version = selected_product_info.get(\"version\", \"UNKNOWN\")\n\n log.info(\n \"Selected installer: %14s %10s %8s %11s %s\"\n % (\n product_id,\n macos_version,\n selected_product_info.get(\"BUILD\", \"UNKNOWN\"),\n selected_product_info[\"PostDate\"].strftime(\"%Y-%m-%d\"),\n selected_product_info[\"title\"],\n )\n )\n\n # determine the InstallAssistant pkg url\n package_url = get_installassistant_pkgs(catalog[\"Products\"][product_id])[0][\"URL\"]\n\n if package_url.endswith(\"InstallAssistantAuto.pkg\"):\n if args.pkg_installers_only:\n log.error(\n \"Specified macOS installer does not have standalone InstallAssistant.pkg, and --pkg-installers-only was specified. Will not installinstallmacos. Exiting.\"\n )\n sys.exit(1)\n\n artifact_type = \"dmg\"\n expected_size = 0\n\n downloaded_artifact = installinstallmacos(\n catalog,\n su_catalog_url,\n product_id,\n selected_product_info,\n show_progress=args.show_progress,\n ignore_cache=args.ignore_cache,\n )\n\n else:\n artifact_type = \"pkg\"\n pkg_name = \"InstallAssistant-%s-%s.pkg\" % (\n macos_version,\n selected_product_info[\"BUILD\"],\n )\n\n downloaded_artifact = os.path.join(WORKING_DIR, pkg_name)\n expected_size = content_length(package_url)\n\n replicate_url(\n package_url,\n dest=downloaded_artifact,\n show_progress=args.show_progress,\n ignore_cache=args.ignore_cache,\n )\n\n log.info(\"Cached %s installer at %s.\" % (artifact_type, downloaded_artifact))\n\n receipt = \"org.macadmins.fetched.macos.installer.%s\" % (macos_version)\n receipt_path = os.path.join(\"/var/db/receipts\", receipt + \".bom\")\n metadata_path = os.path.join(\"/opt/gusto/macos-installers\", receipt + \".plist\")\n old_metadata_path = os.path.join(\"/var/db/receipts\", receipt + \".plist\")\n\n if os.path.exists(old_metadata_path):\n os.remove(old_metadata_path)\n\n # we arbitrarily expect the artifact to be at least 5gb otherwise we assume something broke\n if (\n not os.path.exists(downloaded_artifact)\n or os.path.getsize(downloaded_artifact) < 5368709120\n ):\n if os.path.exists(metadata_path):\n os.remove(metadata_path)\n\n if os.path.exists(receipt_path):\n os.remove(receipt_path)\n\n log.error(\n downloaded_artifact\n + \" was not found or is too small! Something went quite wrong.\"\n )\n sys.exit(1)\n\n if args.write_receipt:\n metadata = {\n \"CacheDate\": str(datetime.now()),\n \"InstallPrefixPath\": WORKING_DIR,\n \"InstallProcessName\": \"fetch-macos-installer.py\",\n \"ArtifactFileName\": downloaded_artifact,\n \"PackageVersion\": macos_version,\n \"ArtifactType\": artifact_type,\n \"ArtifactSize\": expected_size,\n }\n\n with open(receipt_path, \"wb+\") as f:\n f.write(\"\")\n\n try:\n plistlib.writePlist(metadata, metadata_path)\n except AttributeError:\n with open(metadata_path, \"wb+\") as f:\n plistlib.dump(metadata, f)\n\n if args.open_with_finder:\n # reveal in Finder\n open_cmd = [\"open\", \"-R\", downloaded_artifact]\n subprocess.check_call(open_cmd)\n\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"fetch-macos-installer.py","file_name":"fetch-macos-installer.py","file_ext":"py","file_size_in_byte":30437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"51876698","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 21 13:40:19 2021\r\n\r\n@author: Anshul\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom sklearn.datasets import fetch_20newsgroups\r\nimport nltk\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.corpus import stopwords\r\nimport re\r\n\r\n\r\n#%%\r\n\r\ncategory = ['rec.sport.hockey', 'sci.electronics','rec.autos']\r\nnewsgroups_train = fetch_20newsgroups(subset = 'train', categories = category)\r\nnewsgroups_test = fetch_20newsgroups(subset = 'test', categories = category)\r\n\r\n#Print categories names\r\nprint(list(newsgroups_train.target_names)) # ----> Name of classes ['rec.autos', 'rec.sport.hockey', 'sci.electronics']\r\n\r\n#Printing shape of data and target\r\n#print(newsgroups_train.filenames.shape) ----> (1785,) \r\n#print(newsgroups_train.target.shape) ----> (1785,) \r\nprint(np.unique(newsgroups_train.target)) # ----> [0,1,2]\r\n\r\nprint(\"-------- TRAIN DATA ---------\")\r\nprint(\"Before Preprocessing : \")\r\nprint(newsgroups_train.data[2]) \r\nprint(newsgroups_train.target[2])\r\n\r\n#%%\r\n#Cleaning Texts and preprocessing\r\nlemmatizer = WordNetLemmatizer()\r\n\r\ndata_length = len(newsgroups_train.data)\r\n\r\ncorpus = []\r\nfor i in range(data_length):\r\n review = re.sub('[^a-zA-z0-9]',' ',newsgroups_train.data[i])\r\n review = review.lower() #Lowering the words in sentence\r\n review = review.split() #Splitting the sentences in words \r\n review = [lemmatizer.lemmatize(word) for word in review if word not in set(stopwords.words('english'))]\r\n review = ' '.join(review)\r\n corpus.append(review)\r\n\r\n#%%\r\n\r\nprint(\"After cleaning and Preprocessing : \")\r\nprint(np.array(corpus).shape) \r\nprint(corpus[2])\r\n\r\n\r\n#%%\r\n\r\n# Creating TFIDF Model\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\ncv = TfidfVectorizer()\r\n\r\nX = cv.fit_transform(corpus).toarray() #make matrix according to their frequencies in a sentence.\r\nprint(X.shape)\r\n\r\n#Validation data\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nX_train, validation_data, y_train, validation_target = train_test_split(X, newsgroups_train.target, test_size= 0.1, random_state= 1234)\r\n\r\n#%%\r\n# =============================================================================\r\n#\r\n# --------------- --------------Test Data -------------------------------------\r\n# \r\n# =============================================================================\r\nprint(\"-------- TEST DATA ---------\")\r\n# print(\"Before Preprocessing : \")\r\n# print(\"Data : \", newsgroups_test.data[2])\r\n# print(\"Class : \", newsgroups_test.target[2])\r\n\r\ntest_data_length = len(newsgroups_test.data)\r\n\r\ntest_corpus = []\r\nfor i in range(test_data_length):\r\n t_review = re.sub('[^a-zA-z0-9]',' ',newsgroups_test.data[i])\r\n t_review = t_review.lower() #Lowering the words in sentence\r\n t_review = t_review.split() #Splitting the sentences in words \r\n t_review = [lemmatizer.lemmatize(word) for word in t_review if word not in set(stopwords.words('english'))]\r\n t_review = ' '.join(t_review)\r\n test_corpus.append(t_review)\r\n\r\n# print(\"After Cleaning and Preprocessing : \")\r\n# print(np.array(test_corpus).shape) \r\n# print(test_corpus[2])\r\n\r\n#TF-IDF on Test Data\r\nX_test_data = cv.transform(test_corpus).toarray() #make matrix according to their frequencies in a sentence.\r\nprint(\"Tfidf Test data Matrix Shape: \", X_test_data.shape)\r\n\r\n#%%\r\n# =============================================================================\r\n# #---------------------------Classifier Model---------------------------------\r\n# =============================================================================\r\n\r\n#Classifier Models\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.neural_network import MLPClassifier\r\nfrom sklearn import metrics\r\n\r\nbest_validation_f1score = 0\r\nbest_test_f1score = 0\r\n\r\nclassifiers = ['NaiveBayes','DecisionTree', 'SVM', 'RandomForest', 'AdaBoost', 'MLP']\r\n# classifiers = ['MLP']\r\n\r\nfor classifier in classifiers:\r\n if classifier == 'NaiveBayes':\r\n clf = MultinomialNB(alpha = 0.05).fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n elif classifier == 'DecisionTree':\r\n clf = DecisionTreeClassifier().fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n elif classifier == 'SVM':\r\n clf = SVC().fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n elif classifier == 'RandomForest':\r\n clf = RandomForestClassifier().fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n elif classifier == 'AdaBoost':\r\n clf = AdaBoostClassifier().fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n elif classifier == 'MLP':\r\n clf = MLPClassifier(alpha = 0.05).fit(X, newsgroups_train.target)\r\n clf_validation_pred = clf.predict(validation_data)\r\n clf_test_pred = clf.predict(X_test_data)\r\n \r\n print(\"Results of classifier : {}\".format(classifier))\r\n \r\n #Accuracy, confusion matrix and F1 score on Validation Data\r\n confusion = metrics.confusion_matrix(validation_target, clf_validation_pred)\r\n accuracy = metrics.accuracy_score(validation_target, clf_validation_pred)\r\n f_score = metrics.f1_score(validation_target, clf_validation_pred, average= 'micro')\r\n \r\n print(\"Confusion Matrix of validation : \", confusion)\r\n print(\"Accuracy of Model on validation : \", accuracy )\r\n print(\"F1 Score of model on validation : \", f_score)\r\n \r\n \r\n \r\n #Accuracy, confusion matrix and F1 score on Test Data\r\n test_confusion = metrics.confusion_matrix(newsgroups_test.target, clf_test_pred)\r\n test_accuracy = metrics.accuracy_score(newsgroups_test.target, clf_test_pred)\r\n test_f_score = metrics.f1_score(newsgroups_test.target, clf_test_pred, average= 'micro')\r\n \r\n print(\"Confusion Matrix of Test : \", test_confusion)\r\n print(\"Accuracy of Model on Test : \", test_accuracy)\r\n print(\"F1 Score of model on Test : \", test_f_score)\r\n \r\n \r\n if best_test_f1score < test_f_score:\r\n best_validation_f1score = f_score\r\n best_test_f1score = test_f_score\r\n Model = classifier\r\n \r\n print(\" --------------xxxxxxxxxxxxx---------------\")\r\n\r\n#%%\r\n#Final Results\r\n\r\nprint(\"Best Model : {}\".format(Model))\r\n# print(\"Models Validation F1 score : {}\".format(best_validation_f1score))\r\nprint(\"Models Test F1 score : {}\".format(best_test_f1score))\r\n\r\n#%%\r\n\r\nfrom sklearn.manifold import TSNE\r\n\r\ntsne = TSNE(n_components=2).fit_transform(X)\r\nprint(tsne.shape)\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.scatter(tsne[:,0], tsne[:,1], c = newsgroups_train.target)\r\n\r\n","sub_path":"DLNLP/Assignment 2/test_with_preprocessing.py","file_name":"test_with_preprocessing.py","file_ext":"py","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"630350332","text":"import openpyxl\nfrom pylatex import Document, Section, Subsection, Command\nfrom pylatex.utils import italic, NoEscape\nfrom operator import itemgetter\nimport re\n\n\ntexts = {}\ntexts[\"Chalet\"] = \"Cette tâche comprend la prise en main du chalet, son aménagement avant que les participants arrivent et l'état des lieux, ainsi que son rengement et nettoyage intégral à la fin du weekend.\"\ntexts[\"ChaletR\"] = \"Ils sont en charge du contact avec les propriétaires et ont la chagre d'attribuer des tâches aux staffs qu'ils ont sous la main si celles-ci ne sont pas déjà définies; EN PLUS du travail de staff classique.\"\n\ntexts[\"Bus\"] = \"Reception des participants Avenue Piccard à 16h, les faire monter dans le bus ainsi que leurs affaires, le plus rapidement possible sans oublier personne. Départ avant 16h30 de Lausanne impératif. Vous êtes aussi en charge de l'ambiance pendant le voyage. Vous donnez le ton pour la suite du weekend !\"\ntexts[\"BusR\"] = \"Ils auront avec eux les listes des participants. Leur rôle principal est de contrôler la monté dans le bus et faire l'appel affin de s'assurer que tout le monde embarque; EN PLUS du travail de staff classique.\"\n\ntexts[\"PrepApero\"] = \"Sont chargés d'installer l'apéro, préparer les boissons et la nourriture ainsi que de ranger l'apéro.\"\ntexts[\"PrepAperoR\"] = \"Simple rôle de supervision. En plus du travail de staff classique.\"\n\n\ntexts[\"PrepRepas\"] = \"Sont chargés de préparer la cuisine et d'organiser l'installation du couvert (peuvent demander de l'aide à des staffs qui n'ont pas de tâche attribuée), ainsi que de ranger et nettoyer les tables.\"\n\ntexts[\"PrepRepasR\"] = \"Ont la lourde tâche de préparer de bons repas tout en respectant des timing assez serrés. Ont les pleins pouvoirs sur leurs staffs. En plus du travail de staff classique.\"\n\ntexts[\"PrepSoiree\"] = \"Sont chargés de construire les jeux, d'aménager la salle, les lights et la sono et de préparer les boissons.\"\ntexts[\"PrepSoireeR\"] = \"Simple rôle de supervision. En plus du travail de staff classique.\"\n\ntexts[\"Vaisselle\"] = \"Tout le monde voit de quoi je parle je pense.\"\ntexts[\"VaisselleR\"] = \"Doivent s'assurer que la vaisselle est faite dans les bons timing; EN PLUS du travail de staff classique.\"\n\ntexts[\"Bar\"] = \"S'assurer que personne de trop cuit se mette mal. Pas la peine de donner les boissons aux participants, ils peuvent se servir. Aussi en charge de reload les boissons.\"\ntexts[\"BarR\"] = \"Simple rôle de supervision. En plus du travail de staff classique.\"\n\n\ntexts[\"NettoyageSoiree\"] = \"Rôle ingrat mais primordial, permet de réduir très fortement le travail à faire dimanche au moment de rendre le chalet. Ici plus qu'ailleurs le but est d'être rapide et efficace.\"\ntexts[\"NettoyageSoireeR\"] = \"Ont le rôle d'impulser un rythme de travail soutenu, pour assurer le plus de sommeil aux staffs.\"\n\ntexts[\"PrepPetitDejeuner\"] = \"Rôle difficile de part son aspect très matinal. J'ai fait en sorte que ceux qui doivent se lever tôt n'aient pas de shifts après 01h du matin, mais il ne tient qu'à vous de vous coucher ou faire la fête jusqu'à 4h. Cependant rien de vous sera pardonné au moment de taffer. En effet, la prep du petit dej comprend : installer et ranger les tables et la nourriture du p'tit dej, ainsi que préparer les 120 sandwichs pour le midi. C'est sans doute le rôle le plus important du weeekend. Voilà donc pourquoi vous ne devez rien laisser au hasard !!\"\n\ntexts[\"PrepPetitDejeunerR\"] = \"Les timing sont très serrés pour cette tâche, les responsables ont un réel rôle de métronome. Vous avez là aussi les pleins pouvoir sur vos stafs, il est primordial que l'organisation soit ultra-efficace.\"\n\n\nbook = openpyxl.load_workbook('shifts.xlsx')\nsheet = book.active\n\nVENDREDI = 11\nSAMEDI = 35\nDIMANCHE = 53\n\ntasks_v = []\ntasks_s = []\ntasks_d = []\n\n\nNB_COLUMN = 12\n\nsearched = str(120)\n\n\ndef numbertoname(number):\n return sheet.cell(row=number-100+2,column=15).value\n\ndef stringchange(test):\n lol = test.replace(\" \",\"\")\n return lol.replace(\"é\",\"e\")\n\ndef taskwith(numbers):\n numbers = re.findall('\\d+', numbers)\n string = \"\"\n for number in numbers:\n string = string + numbertoname(int(number)) + ', '\n return string[:-2]+\".\"\n\ndef populate(start, end):\n hours=0\n tasks = []\n for i in range(1, NB_COLUMN):\n for j in range(start, end):\n cell = str(sheet.cell(row=j, column=i).value)\n\n if searched in cell or \"TOUT LE MONDE\" in cell:\n if \"R\"+ searched in cell or \"R \"+searched in cell:\n hours = hours+1\n status = 3\n elif \"TOUT LE MONDE\" in cell:\n status = 1\n else:\n hours = hours+1\n status=2\n tasks.append((str(sheet.cell(row=1, column=i).value), str(sheet.cell(row=j,column=2).value),status,sheet.cell(row=j,column=i).value))\n h = 0\n for i in tasks:\n print(i[0])\n print(\"------------------------------\")\n\n task = tasks[0][0]\n start = int(tasks[0][1][:2])\n starti = 0;\n status = tasks[0][2]\n end = start +1\n tasks_complete = []\n\n while h < len(tasks):\n #print(tasks[h][0])\n if task != tasks[h][0] or h+1==len(tasks) or status !=tasks[h][2] or (h>0 and int(tasks[h][1][:2])!= int(tasks[h-1][1][:2])+1):\n if h>0 and h+1 == len(tasks) and task != tasks[h][0]:\n\n tasks_complete.append((task, start,int(tasks[h-1][1][:2])+1, tasks[h-1][2], tasks[starti][3]))\n tasks_complete.append((tasks[h][0], int(tasks[h][1][:2]),int(tasks[h][1][:2])+1, tasks[h][2], tasks[h][3]))\n elif int(tasks[h][1][:2])!= int(tasks[h-1][1][:2])+1:\n tasks_complete.append((tasks[h-1][0], start,int(tasks[h-1][1][:2])+1, tasks[h-1][2], tasks[starti][3]))\n\n elif h+1==len(tasks):\n tasks_complete.append((task, start,int(tasks[h][1][:2])+1, tasks[h][2], tasks[starti][3]))\n elif task!=tasks[h][0]:\n tasks_complete.append((task, start, end, tasks[h-1][2], tasks[starti][3]))\n\n status = tasks[h][2]\n start = int(tasks[h][1][:2])\n starti = h\n end = start+1\n task = tasks[h][0]\n\n\n else:\n end = int(tasks[h][1][:2])+1\n h = h+1\n\n return (sorted(tasks_complete, key=itemgetter(1)), hours)\n\n\n\nven = (populate(1,VENDREDI+1))\n#print(ven)\nsam = populate(VENDREDI+1, SAMEDI+1)\ndim = populate(SAMEDI+1, DIMANCHE+1)\n\ntotal = ven[1]+sam[1] + dim[1]\n\n\nven = ven[0]\nsam = sam[0]\ndim = dim[0]\n\n#FILE GENERATION\n\ndoc = Document('basic')\n\ndoc.preamble.append(Command('title', 'Récapitulatif Personnel Week-End Ski 2018 : '+str(numbertoname(int(searched)))))\ndoc.preamble.append(Command('date', NoEscape('')))\ndoc.preamble.append(NoEscape(r'\\usepackage{xcolor}'))\ndoc.append(NoEscape(r'\\maketitle'))\ndoc.append(NoEscape(r\" \\textbf{Nombre d'heures : }\" + str(total)))\n\n\n\nwith doc.create(Section('Vendredi', False)):\n for i in ven:\n #print (i[4])\n if(i[3]==2 or i[3]==3):\n with doc.create(Subsection(str(i[0])+ \" : \" +str(i[1])+ \"h - \"+str(i[2])+\"h, avec \"+taskwith(i[4]), False)):\n doc.append(\"Description : \"+texts[stringchange(i[0])])\n doc.append(NoEscape(r'\\newline'))\n if(i[3]==3):\n doc.append(NoEscape(r'\\textcolor{red}{Attention, vous êtes également responsable pour cette tâche : }'+texts[stringchange(i[0])+\"R\"]))\n\n\nwith doc.create(Section('Samedi',False)):\n for i in sam:\n if(i[3]==2 or i[3]==3):\n with doc.create(Subsection(str(i[0])+ \" : \" +str(i[1])+ \"h - \"+str(i[2])+\"h, avec \"+taskwith(i[4]), False)):\n doc.append(\"Description : \"+texts[stringchange(i[0])])\n doc.append(NoEscape(r'\\newline'))\n if(i[3]==3):\n doc.append(NoEscape(r'\\textcolor{red}{Attention, vous êtes également responsable pour cette tâche : }'+texts[stringchange(i[0])+\"R\"]))\n\nwith doc.create(Section('Dimanche', False)):\n for i in dim:\n if(i[3]==2 or i[3]==3):\n with doc.create(Subsection(str(i[0])+ \" : \" +str(i[1])+ \"h - \"+str(i[2])+\"h, avec \"+taskwith(i[4]), False)):\n doc.append(\"Description : \"+texts[stringchange(i[0])])\n doc.append(NoEscape(r'\\newline'))\n if(i[3]==3):\n doc.append(NoEscape(r'\\textcolor{red}{Attention, vous êtes également responsable pour cette tâche : }'+texts[stringchange(i[0])+\"R\"]))\n\n\nwith doc.create(Section('Autres tâches :',False)):\n doc.append(\"Comme tout le monde, vous devez également vous rendre disponible pour aider dans ces tâches :\")\n doc.append(NoEscape(r'\\begin{itemize}'))\n for i in ven:\n if(i[3]==1):\n doc.append(NoEscape(r'\\item Vendredi de '+ str(i[1])+ 'h à '+str(i[2])+'h : '+str(i[0])))\n\n for i in sam:\n if(i[3]==1):\n doc.append(NoEscape(r'\\item Samedi de '+ str(i[1])+ 'h à '+str(i[2])+'h : '+str(i[0])))\n\n for i in dim:\n #print(i[3])\n if(i[3]==1):\n doc.append(NoEscape(r'\\item Dimanche de '+ str(i[1])+ 'h à '+str(i[2])+'h : '+str(i[0])))\n\n doc.append(NoEscape(r'\\end{itemize}'))\n\n\n\n\n\ndoc.generate_pdf('shift_'+numbertoname(int(searched)), clean_tex=False)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"358169334","text":"import random\r\n\r\n# parameters of this game\r\nmaxWeight = 250\r\nturn = 3\r\n\r\n# greeting\r\nprint('\\n\\n\\tWelcome To BestEat!\\n\\n')\r\n\r\n# collection of fruits having weight with calorie\r\nfruitsCollection = {'A': {'weight': 100, 'calorie': 100}, 'B': {'weight': 50, 'calorie': 100},\r\n 'C': {'weight': 25, 'calorie': 75}, 'D': {'weight': 12, 'calorie': 36},\r\n 'E': {'weight': 100, 'calorie': 400}, 'F': {'weight': 50, 'calorie': 150},\r\n 'G': {'weight': 25, 'calorie': 50}, 'H': {'weight': 12, 'calorie': 12}}\r\n# fruit name mapping with number\r\nfruitNameNumberMapping = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H'}\r\n\r\n# calorie weight ratio of fruits\r\ncalorieWeightRation = {}\r\nfruits = fruitsCollection.keys()\r\nfor fruit in fruits:\r\n calorieWeightRation[fruit] = fruitsCollection[fruit]['calorie'] / fruitsCollection[fruit]['weight']\r\n\r\n# game playing\r\nplayerScore = 0\r\nplayerRemainingWeight = 250\r\n\r\ncomputerScore = 0\r\ncomputerRemainingWeight = 250\r\n\r\nfor i in range(turn):\r\n playerFruitNumber = []\r\n playerFruitCollection = {}\r\n playerFruitNumber = random.sample(range(1, 8), 3)\r\n\r\n computerFruitNumber = []\r\n computerFruitCollection = {}\r\n computerCalorieWeightRatio = [0] * 8\r\n computerFruitNumber = random.sample(range(1, 8), 3)\r\n\r\n # player's turn\r\n for index in playerFruitNumber:\r\n playerFruitCollection[fruitNameNumberMapping[index]] = {'weight': fruitsCollection[fruitNameNumberMapping[index]]['weight'],\r\n 'calorie': fruitsCollection[fruitNameNumberMapping[index]]['calorie']}\r\n print('\\t Player (Human)')\r\n print('---------------------------')\r\n print('Fruit Name' + '\\t' + 'Weight' + '\\t\\t' + 'Calorie')\r\n\r\n for index in playerFruitNumber:\r\n print(fruitNameNumberMapping[index], '\\t\\t\\t', playerFruitCollection[fruitNameNumberMapping[index]]['weight'],\r\n '\\t\\t\\t', playerFruitCollection[fruitNameNumberMapping[index]]['calorie'])\r\n\r\n # choice handling of player\r\n playerSelectionOptions = playerFruitCollection.keys()\r\n\r\n playerChoise = input('Enter a fruit name: ')\r\n playerChoise = playerChoise.capitalize()\r\n\r\n if playerChoise in playerSelectionOptions and (playerRemainingWeight - fruitsCollection[playerChoise]['weight']) >= 0:\r\n playerRemainingWeight -= fruitsCollection[playerChoise]['weight'];\r\n playerScore += fruitsCollection[playerChoise]['calorie']\r\n else:\r\n print('\\nPlayer\\'s Remaining Weight Exceeded!\\n')\r\n\r\n # computer's turn\r\n for index in computerFruitNumber:\r\n computerFruitCollection[fruitNameNumberMapping[index]] = {'weight': fruitsCollection[fruitNameNumberMapping[index]]['weight'],\r\n 'calorie': fruitsCollection[fruitNameNumberMapping[index]]['calorie']}\r\n computerCalorieWeightRatio[index] = calorieWeightRation[fruitNameNumberMapping[index]]\r\n print('\\n\\t Computer (AI)')\r\n print('---------------------------')\r\n print('Fruit Name' + '\\t' + 'Weight' + '\\t\\t' + 'Calorie')\r\n\r\n for index in computerFruitNumber:\r\n print(fruitNameNumberMapping[index], '\\t\\t\\t', computerFruitCollection[fruitNameNumberMapping[index]]['weight'],\r\n '\\t\\t\\t', computerFruitCollection[fruitNameNumberMapping[index]]['calorie'])\r\n\r\n # choice handling of computer\r\n computerSelectionOptions = computerFruitCollection.keys()\r\n maxCalorieIndex = computerCalorieWeightRatio.index(max(computerCalorieWeightRatio))\r\n computerChoice = fruitNameNumberMapping[maxCalorieIndex]\r\n\r\n if computerChoice in computerSelectionOptions and (computerRemainingWeight - fruitsCollection[computerChoice]['weight']) >= 0:\r\n computerRemainingWeight -= fruitsCollection[computerChoice]['weight'];\r\n computerScore += fruitsCollection[computerChoice]['calorie']\r\n else:\r\n print('\\nComputer\\'s Remaining Weight Exceeded!\\n')\r\n\r\nprint('Player\\'s Score: ', playerScore)\r\nprint('Player\\'s Remaining Weight: ', playerRemainingWeight)\r\nprint('\\nComputer\\'s Score: ', computerScore)\r\nprint('Computer\\'s Remaining Weight: ', computerRemainingWeight)\r\n\r\nif playerScore > computerScore:\r\n print('\\n\\nWinner - Player! Congrats!')\r\nelif playerScore < computerScore:\r\n print('\\n\\nWinner - Computer! Congrats!')\r\nelse:\r\n print('\\n\\nScore Label! Match Draw')\r\n\r\n","sub_path":"EatBest.py","file_name":"EatBest.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"228659652","text":"from flask import Flask, render_template, request\nfrom send_email import send_email,send_adx_email\nfrom backend import AppNexus, app, db, ADX\n\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n@app.route(\"/appnexus\")\ndef appnexus():\n return render_template(\"appnexus.html\")\n\n\n@app.route(\"/success\", methods=['POST', 'GET'])\ndef success():\n if request.method == \"POST\":\n email = request.form['email']\n cpm = request.form['cpm']\n advertiser_id = request.form['advertiser_id']\n io = request.form['io']\n campaign = request.form['campaign']\n line_item = request.form['line_item']\n it_placement = request.form['it_placement']\n it_domain = request.form['it_domain']\n it_groups = request.form['it_groups']\n fcap = request.form['fcap_day']\n daily = request.form['daily_budget']\n lifetime = request.form['lifetime_budget']\n device = request.form['device_type']\n pacing = request.form['pacing']\n size = request.form['size']\n creative = request.form['creative']\n date = request.form['date']\n notes = request.form['notes']\n apn_data = AppNexus(email, cpm, advertiser_id, io, campaign, line_item, it_placement, it_domain, it_groups, fcap, daily,\n lifetime, device, pacing, size, creative, date, notes)\n send_email(email, cpm, advertiser_id, io, campaign, line_item, it_placement, it_domain, it_groups, fcap, daily,\n lifetime, device, pacing, size, creative, date, notes)\n db.session.add(apn_data)\n db.session.commit()\n return render_template(\"success.html\")\n@app.route('/show_all', methods = ['GET','POST'])\ndef show_all():\n return render_template(\"show_all.html\", Data = Data.query.all())\n\n@app.route(\"/dfp\")\ndef dfp():\n return render_template(\"adx.html\")\n\n@app.route('/adx_success',methods=['GET','POST'])\ndef dfp_success():\n if request.method == \"POST\":\n email = request.form['email']\n advertiser = request.form['advertiser_id']\n ad_unit = request.form['dfp_ad_unit']\n size = request.form['size']\n adx_order = request.form['adx_order']\n adx_line_item = request.form['adx_line_item']\n brt_order = request.form['brt_order']\n brt_line_item = request.form['brt_line_item']\n brt_line_item_rate = request.form[\"brt_line_item_rate\"]\n apn_placement = request.form['creative']\n\n\n adx_data = ADX(email,advertiser,ad_unit,size,adx_order,adx_line_item,brt_order,\n brt_line_item,brt_line_item_rate, apn_placement)\n db.session.add(adx_data)\n db.session.commit()\n send_adx_email(email,advertiser,ad_unit,size,adx_order,adx_line_item,brt_order,brt_line_item,brt_line_item_rate,apn_placement)\n return render_template('success.html')\n\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n db.create_all()\n","sub_path":"biddrApache/TicketProject.py","file_name":"TicketProject.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"558682426","text":"\"\"\"Common functions for evaluating checkpoints.\n\"\"\"\nimport datetime\nimport time\nimport os\nimport subprocess\nimport numpy as np\nimport cv2\nfrom multiprocessing import Process\nimport tensorflow as tf\n\nfrom avod.core import box_3d_encoder\nfrom avod.core import evaluator_utils\nfrom avod.core import summary_utils\nfrom avod.core import trainer_utils\n\nfrom avod.core.models.avod_model import AvodModel\nfrom avod.core.models.rpn_model import RpnModel\nfrom avod.core.models.retinanet_model import RetinanetModel\nfrom avod.core import box_bev_encoder \nfrom avod.core import orientation_encoder\nfrom wavedata.tools.core import calib_utils\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nKEY_SUM_CLS_LOSS = 'sum_cls_loss'\nKEY_SUM_REG_LOSS = 'sum_reg_loss'\nKEY_SUM_REG_H_LOSS = 'sum_reg_h_loss'\nKEY_SUM_REG_ANGLE_CLS_LOSS = 'sum_reg_angle_cls_loss'\nKEY_SUM_TOTAL_LOSS = 'sum_total_loss'\nKEY_SUM_CLS_ACC = 'sum_obj_accuracy'\nKEY_NUM_VALID_REG_SAMPLES = 'num_valid_reg_samples'\n\n\nclass EvaluatorRetinanet:\n\n def __init__(self,\n model,\n dataset_config,\n eval_config,\n skip_evaluated_checkpoints=True,\n eval_wait_interval=30,\n do_kitti_native_eval=True):\n \"\"\"Evaluator class for evaluating model's detection output.\n\n Args:\n model: An instance of DetectionModel\n dataset_config: Dataset protobuf configuration\n eval_config: Evaluation protobuf configuration\n skip_evaluated_checkpoints: (optional) Enables checking evaluation\n results directory and if the folder names with the checkpoint\n index exists, it 'assumes' that checkpoint has already been\n evaluated and skips that checkpoint.\n eval_wait_interval: (optional) The number of seconds between\n looking for a new checkpoint.\n do_kitti_native_eval: (optional) flag to enable running kitti native\n eval code.\n \"\"\"\n\n # Get model configurations\n self.model = model\n self.dataset_config = dataset_config\n self.eval_config = eval_config\n\n self.model_config = model.model_config\n self.model_name = self.model_config.model_name\n\n rlosses_keys = [f'refine{i}' for i in range(self.model.refine_stage_num)]\n self.model_losses_keys = ['fcn'] + rlosses_keys\n self.model_has_h_flags = self.model.add_h_flags\n self.model_has_angle_flags = self.model.add_angle_flags\n\n self.paths_config = self.model_config.paths_config\n self.checkpoint_dir = self.paths_config.checkpoint_dir\n\n self.skip_evaluated_checkpoints = skip_evaluated_checkpoints\n self.eval_wait_interval = eval_wait_interval\n\n self.do_kitti_native_eval = do_kitti_native_eval\n\n # Create a variable tensor to hold the global step\n self.global_step_tensor = tf.Variable(\n 0, trainable=False, name='global_step')\n\n eval_mode = eval_config.eval_mode\n if eval_mode not in ['val', 'test']:\n raise ValueError('Evaluation mode can only be set to `val`'\n 'or `test`')\n\n if not os.path.exists(self.checkpoint_dir):\n raise ValueError('{} must have at least one checkpoint entry.'\n .format(self.checkpoint_dir))\n\n if self.do_kitti_native_eval:\n if self.eval_config.eval_mode == 'val':\n # Copy kitti native eval code into the predictions folder\n evaluator_utils.copy_kitti_native_code(\n self.model_config.checkpoint_name)\n\n allow_gpu_mem_growth = self.eval_config.allow_gpu_mem_growth\n if allow_gpu_mem_growth:\n # GPU memory config\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = allow_gpu_mem_growth\n self._sess = tf.Session(config=config)\n else:\n self._sess = tf.Session()\n\n # The model should return a dictionary of predictions\n #self._prediction_dict = dict()\n self._prediction_dict = self.model.build()\n if eval_mode == 'val':\n # Setup loss and summary writer in val mode only\n self._loss_dict, self._total_loss = \\\n self.model.loss(self._prediction_dict)\n\n self.summary_writer, self.summary_merged = \\\n evaluator_utils.set_up_summary_writer(self.model_config,\n self._sess)\n logdir = self.paths_config.logdir\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n logdir = logdir + '/eval'\n\n datetime_str = str(datetime.datetime.now())+'sample2'\n self.summary_writer2 = tf.summary.FileWriter(logdir + '/' + datetime_str)\n\n\n else:\n self._loss_dict = None\n self._total_loss = None\n self.summary_writer = None\n self.summary_merged = None\n\n self._saver = tf.train.Saver()\n\n # Add maximum memory usage summary op\n # This op can only be run on device with gpu\n # so it's skipped on travis\n is_travis = 'TRAVIS' in os.environ\n if not is_travis:\n # tf 1.4\n # tf.summary.scalar('bytes_in_use',\n # tf.contrib.memory_stats.BytesInUse())\n tf.summary.scalar('max_bytes',\n tf.contrib.memory_stats.MaxBytesInUse())\n\n def run_checkpoint_once(self, checkpoint_to_restore):\n \"\"\"Evaluates network metrics once over all the validation samples.\n\n Args:\n checkpoint_to_restore: The directory of the checkpoint to restore.\n \"\"\"\n\n self._saver.restore(self._sess, checkpoint_to_restore)\n\n data_split = self.dataset_config.data_split\n predictions_base_dir = self.paths_config.pred_dir\n\n num_samples = self.model.dataset.num_samples\n train_val_test = self.model._train_val_test\n print('model: train_val_test: ', train_val_test)\n\n validation = train_val_test == 'val'\n\n global_step = trainer_utils.get_global_step(\n self._sess, self.global_step_tensor)\n\n # Rpn average losses dictionary\n if validation:\n sum_losses = self._create_losses_dict()\n\n\n # Make sure the box representation is valid\n predictions_dir = predictions_base_dir + \\\n \"/final_predictions_and_scores/{}/{}\".format(\n data_split, global_step)\n trainer_utils.create_dir(predictions_dir)\n\n num_valid_samples = 0\n\n # Keep track of feed_dict and inference time\n total_feed_dict_time = []\n total_inference_time = []\n\n # Run through a single epoch\n current_epoch = self.model.dataset.epochs_completed\n\n #run_metadata = tf.RunMetadata()\n #run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n while current_epoch == self.model.dataset.epochs_completed:\n # Keep track of feed_dict speed\n start_time = time.time()\n #feed_dict = self.model.create_feed_dict(sample_index=sample_index)\n feed_dict = self.model.create_feed_dict()\n feed_dict_time = time.time() - start_time\n\n # Get sample name from model\n sample_name = self.model.sample_info['sample_name']\n stereo_calib = calib_utils.read_calibration(self.model.dataset.calib_dir,\n int(sample_name))\n stereo_calib_p2 = stereo_calib.p2\n \n output_file_path = predictions_dir + \\\n \"/{}.txt\".format(sample_name)\n\n num_valid_samples += 1\n #if num_valid_samples > 1:\n # break\n print(\"Step {}: {} / {}, Inference on sample {}\".format(\n global_step, num_valid_samples, num_samples,\n sample_name))\n\n\n # Do predictions, loss calculations, and summaries\n\n if validation:\n if self.summary_merged is not None:\n predictions, eval_losses, eval_total_loss, summary_out = \\\n self._sess.run([self._prediction_dict,\n self._loss_dict,\n self._total_loss,\n self.summary_merged],\n feed_dict=feed_dict)\n \n if num_valid_samples == 2 and num_samples == 2:\n self.summary_writer2.add_summary(summary_out, global_step)\n else:\n self.summary_writer.add_summary(summary_out, global_step)\n\n else:\n print('start inference without smry:')\n predictions, eval_losses, eval_total_loss = \\\n self._sess.run([self._prediction_dict,\n self._loss_dict,\n self._total_loss],\n feed_dict=feed_dict)\n #options=run_options,\n #run_metadata=run_metadata)\n #self.summary_writer.add_run_metadata(run_metadata, \\\n # 'step {} sp:{}'.format(global_step/1000, int(sample_name)))\n\n\n self._update_losses(eval_losses,\n eval_total_loss,\n sum_losses,\n global_step)\n # Save predictions\n\n print('save predictions')\n predictions_and_scores = \\\n self.get_predicted_boxes_3d_and_scores(predictions,\n stereo_calib_p2)\n np.savetxt(output_file_path, predictions_and_scores, fmt='%.5f')\n\n # Calculate accuracies\n #Unnecessary because there is only one class.. object class without bkg class..\n self.get_cls_accuracy(predictions,\n sum_losses,\n global_step)\n print(\"Step {}: Total time {} s\".format(\n global_step, time.time() - start_time))\n\n else:\n # Test mode --> train_val_test == 'test'\n inference_start_time = time.time()\n # Don't calculate loss or run summaries for test\n predictions = self._sess.run(self._prediction_dict,\n feed_dict=feed_dict)\n inference_time = time.time() - inference_start_time\n\n # Add times to list\n total_feed_dict_time.append(feed_dict_time)\n total_inference_time.append(inference_time)\n\n predictions_and_scores = \\\n self.get_predicted_boxes_3d_and_scores(predictions,\n stereo_calib_p2)\n np.savetxt(file_path, predictions_and_scores, fmt='%.5f')\n\n # end while current_epoch == model.dataset.epochs_completed:\n\n if validation:\n # Kitti native evaluation, do this during validation\n # and when running Avod model.\n # Store predictions in kitti format\n self.save_prediction_losses_results(sum_losses, num_valid_samples, \\\n global_step, predictions_base_dir)\n if self.do_kitti_native_eval:\n pass\n #self.run_kitti_native_eval(global_step)\n\n else:\n # Test mode --> train_val_test == 'test'\n evaluator_utils.print_inference_time_statistics(\n total_feed_dict_time, total_inference_time)\n\n print(\"Step {}: Finished evaluation, results saved to {}\".format(\n global_step, predictions_dir))\n\n def run_latest_checkpoints(self):\n \"\"\"Evaluation function for evaluating all the existing checkpoints.\n This function just runs through all the existing checkpoints.\n\n Raises:\n ValueError: if model.checkpoint_dir doesn't have at least one\n element.\n \"\"\"\n\n if not os.path.exists(self.checkpoint_dir):\n raise ValueError('{} must have at least one checkpoint entry.'\n .format(self.checkpoint_dir))\n\n # Load the latest checkpoints available\n trainer_utils.load_checkpoints(self.checkpoint_dir,\n self._saver)\n\n num_checkpoints = len(self._saver.last_checkpoints)\n\n if self.skip_evaluated_checkpoints:\n already_evaluated_ckpts = self.get_evaluated_ckpts(\n self.model_config)\n\n ckpt_indices = np.asarray(self.eval_config.ckpt_indices)\n if ckpt_indices is not None:\n if ckpt_indices[0] == -1:\n # Restore the most recent checkpoint\n ckpt_idx = num_checkpoints - 1\n ckpt_indices = [ckpt_idx]\n for ckpt_idx in ckpt_indices:\n checkpoint_to_restore = self._saver.last_checkpoints[ckpt_idx]\n self.run_checkpoint_once(checkpoint_to_restore)\n\n else:\n last_checkpoint_id = -1\n number_of_evaluations = 0\n # go through all existing checkpoints\n for ckpt_idx in range(num_checkpoints):\n checkpoint_to_restore = self._saver.last_checkpoints[ckpt_idx]\n ckpt_id = evaluator_utils.strip_checkpoint_id(\n checkpoint_to_restore)\n\n # Check if checkpoint has been evaluated already\n already_evaluated = ckpt_id in already_evaluated_ckpts\n if already_evaluated or ckpt_id <= last_checkpoint_id:\n number_of_evaluations = max((ckpt_idx + 1,\n number_of_evaluations))\n continue\n\n self.run_checkpoint_once(checkpoint_to_restore)\n number_of_evaluations += 1\n\n # Save the id of the latest evaluated checkpoint\n last_checkpoint_id = ckpt_id\n\n def repeated_checkpoint_run(self):\n \"\"\"Periodically evaluates the checkpoints inside the `checkpoint_dir`.\n\n This function evaluates all the existing checkpoints as they are being\n generated. If there are none, it sleeps until new checkpoints become\n available. Since there is no synchronization guarantee for the trainer\n and evaluator, at each iteration it reloads all the checkpoints and\n searches for the last checkpoint to continue from. This is meant to be\n called in parallel to the trainer to evaluate the models regularly.\n\n Raises:\n ValueError: if model.checkpoint_dir doesn't have at least one\n element.\n \"\"\"\n\n if not os.path.exists(self.checkpoint_dir):\n raise ValueError('{} must have at least one checkpoint entry.'\n .format(self.checkpoint_dir))\n\n # Copy kitti native eval code into the predictions folder\n if self.do_kitti_native_eval:\n evaluator_utils.copy_kitti_native_code(\n self.model_config.checkpoint_name)\n\n if self.skip_evaluated_checkpoints:\n already_evaluated_ckpts = self.get_evaluated_ckpts(\n self.model_config)\n else:\n already_evaluated_ckpts = []\n tf.logging.info(\n 'Starting evaluation at ' +\n time.strftime(\n '%Y-%m-%d-%H:%M:%S',\n time.gmtime()))\n\n last_checkpoint_id = -1\n number_of_evaluations = 0\n #Dont have to add summary(for model inference at each sample) at repeated evaluation.. \n #only care avg loss at each ckpt step.\n #self.summary_merged = None\n evaluated_ckpts = [ckpt for ckpt in already_evaluated_ckpts]\n while True:\n # Load current checkpoints available\n trainer_utils.load_checkpoints(self.checkpoint_dir,\n self._saver)\n num_checkpoints = len(self._saver.last_checkpoints)\n no_newckpts = True\n evaluated_ckpts.sort()\n start = time.time()\n for ckpt_idx in range(num_checkpoints):\n checkpoint_to_restore = \\\n self._saver.last_checkpoints[ckpt_idx]\n ckpt_id = evaluator_utils.strip_checkpoint_id(\n checkpoint_to_restore)\n\n # Check if checkpoint has been evaluated already\n if ckpt_id == 0 or ckpt_id in evaluated_ckpts:\n continue\n else:\n no_newckpts = False\n print('evaluated ckpts: ', evaluated_ckpts)\n print('processing ckpt id: ', ckpt_id)\n self.run_checkpoint_once(checkpoint_to_restore)\n evaluated_ckpts.append(ckpt_id)\n time_to_next_eval = start + self.eval_wait_interval - time.time()\n if no_newckpts:\n tf.logging.info('No new checkpoints found in %s.'\n 'Will try again in %d seconds',\n self.checkpoint_dir,\n self.eval_wait_interval)\n if time_to_next_eval > 0:\n time.sleep(time_to_next_eval)\n\n def _update_losses(self,\n eval_losses,\n eval_total_loss,\n sum_losses,\n global_step):\n \"\"\"Helper function to calculate the evaluation average losses.\n\n Args:\n eval_losses: A dictionary of network's output\n eval_total_loss: A scalar loss of rpn total loss.\n sum_losses: A dictionary containing all the average\n losses.\n global_step: Global step at which the metrics are computed.\n \"\"\"\n\n is_valid_reg_sample = True\n for sk in self.model_losses_keys:\n #check all stage's reg loss to verify if valid reg sample\n reg_loss = eval_losses[sk][RetinanetModel.LOSS_RETINANET_REGRESSION]\n if reg_loss <= 0.0:\n is_valid_reg_sample = False\n losses_str = ''\n for sk, has_h, has_ang in zip(\\\n self.model_losses_keys, self.model_has_h_flags,\\\n self.model_has_angle_flags):\n stage_losses = eval_losses[sk]\n cls_loss = stage_losses[RetinanetModel.LOSS_RETINANET_OBJECTNESS]\n sum_losses[sk][KEY_SUM_CLS_LOSS] += cls_loss\n losses_str += f'{sk} cls: {cls_loss}, '\n if is_valid_reg_sample:\n reg_loss = stage_losses[RetinanetModel.LOSS_RETINANET_REGRESSION]\n sum_losses[sk][KEY_SUM_REG_LOSS] += reg_loss\n losses_str += f'reg: {reg_loss}, '\n if has_h:\n reg_h_loss = stage_losses[RetinanetModel.LOSS_RETINANET_H]\n sum_losses[sk][KEY_SUM_REG_H_LOSS] += reg_h_loss\n losses_str += f'h: {reg_h_loss}, '\n if has_ang:\n reg_angle_cls_loss = stage_losses[RetinanetModel.LOSS_RETINANET_ANGLE_CLS]\n sum_losses[sk][KEY_SUM_REG_ANGLE_CLS_LOSS] += reg_angle_cls_loss\n losses_str += f'angle: {reg_angle_cls_loss}, '\n\n losses_str += '\\n'\n\n #print(f\"Step {global_step}: Eval Loss: {losses_str}\")\n sum_losses[KEY_SUM_TOTAL_LOSS] += eval_total_loss\n if is_valid_reg_sample:\n sum_losses[KEY_NUM_VALID_REG_SAMPLES] += 1\n\n def save_prediction_losses_results(self,\n sum_losses,\n num_valid_samples,\n global_step,\n predictions_base_dir):\n \"\"\"Helper function to save the AVOD loss evaluation results.\n\n Args:\n eval_avod_losses: A dictionary containing the loss sums\n num_valid_samples: An int, number of valid evaluated samples\n i.e. samples with valid ground-truth.\n global_step: Global step at which the metrics are computed.\n predictions_base_dir: Base directory for storing the results.\n box_rep: A string, the format of the 3D bounding box\n one of 'box_3d', 'box_8c' etc.\n \"\"\"\n num_valid_reg_samples = max(1, sum_losses[KEY_NUM_VALID_REG_SAMPLES])\n avg_losses_key_str = ''\n avg_losses_print_str = ''\n avg_losses_data = []\n\n for sk, has_h, has_ang in zip(\\\n self.model_losses_keys, self.model_has_h_flags,\\\n self.model_has_angle_flags):\n stage_losses = sum_losses[sk]\n sum_cls_loss = stage_losses[KEY_SUM_CLS_LOSS]\n avg_cls_loss = sum_cls_loss / num_valid_samples\n # Write summaries\n #f'{sk}_losses/classification/cls',\n summary_utils.add_scalar_summary(\n f'{sk}_loss/retinanet_losses/cls/norm/val',\n avg_cls_loss,\n self.summary_writer, global_step)\n\n sum_reg_loss = stage_losses[KEY_SUM_REG_LOSS]\n avg_reg_loss = sum_reg_loss / num_valid_reg_samples\n #f'{sk}_losses/regression/reg',\n summary_utils.add_scalar_summary(\n f'{sk}_loss/retinanet_losses/reg/norm/val',\n avg_reg_loss,\n self.summary_writer, global_step)\n avg_losses_print_str += f'[{sk}]cls:{avg_cls_loss}, reg:{avg_reg_loss}, '\n avg_losses_key_str += f'{sk}_cls {sk}_reg '\n avg_losses_data.extend([avg_cls_loss, avg_reg_loss])\n if KEY_SUM_REG_H_LOSS in stage_losses:\n sum_h_loss = stage_losses[KEY_SUM_REG_H_LOSS]\n avg_h_loss = sum_h_loss / num_valid_reg_samples \n #f'{sk}_losses/regression/h',\n summary_utils.add_scalar_summary(\n f'{sk}_loss/retinanet_losses/reg/norm/h_reg',\n avg_h_loss,\n self.summary_writer, global_step)\n avg_losses_print_str += f'h:{avg_h_loss}, '\n avg_losses_key_str += f'{sk}_h '\n avg_losses_data.append(avg_h_loss)\n if KEY_SUM_REG_ANGLE_CLS_LOSS in stage_losses:\n sum_angle_cls_loss = stage_losses[KEY_SUM_REG_ANGLE_CLS_LOSS]\n avg_angle_cls_loss = sum_angle_cls_loss / num_valid_reg_samples \n #f'{sk}_losses/regression/angle_cls',\n summary_utils.add_scalar_summary(\n f'{sk}_loss/retinanet_losses/reg/norm/angle_cls',\n avg_angle_cls_loss,\n self.summary_writer, global_step)\n avg_losses_print_str += f'angle:{avg_angle_cls_loss}, '\n avg_losses_key_str += f'{sk}_angle '\n avg_losses_data.append(avg_angle_cls_loss)\n\n sum_cls_acc = sum_losses[KEY_SUM_CLS_ACC]\n avg_cls_acc = sum_cls_acc / num_valid_samples\n summary_utils.add_scalar_summary(\n f'output/cls_accuracy',\n avg_cls_acc,\n self.summary_writer, global_step)\n \n self.summary_writer.flush()\n\n sum_total_loss = sum_losses[KEY_SUM_TOTAL_LOSS]\n avg_total_loss = sum_total_loss / num_valid_samples\n avg_losses_print_str += f'\\ntotal:{avg_total_loss}'\n avg_losses_key_str += 'total '\n avg_losses_data.append(avg_total_loss)\n\n # Append to end of file\n avg_loss_file_dir = predictions_base_dir + '/avg_losses/'\\\n + self.dataset_config.data_split \n if not os.path.exists(avg_loss_file_dir):\n os.makedirs(avg_loss_file_dir)\n avg_loss_file_path = avg_loss_file_dir +'/avg_losses.csv'\n if not os.path.exists(avg_loss_file_path):\n with open(avg_loss_file_path, 'w') as f:\n f.write(f'Step {avg_losses_key_str}\\n')\n\n save = True\n if save:\n print(f\"Step {global_step}: Average Losses: \\n{avg_losses_print_str}\")\n\n with open(avg_loss_file_path, 'ba') as fp:\n avg_losses_data = np.array(avg_losses_data)\n np.savetxt(fp,\n [np.hstack(\n [global_step, avg_losses_data]\n )],\n fmt='%d'+', %.5f'*(len(avg_losses_data)))\n\n\n def _create_losses_dict(self):\n \"\"\"Returns a dictionary of the losses sum for averaging.\n \"\"\"\n sum_losses = dict()\n\n # Initialize Rpn average losses\n for stage_key, has_h, has_ang in zip(\\\n self.model_losses_keys, self.model_has_h_flags,\\\n self.model_has_angle_flags):\n stage_losses = dict() \n stage_losses[KEY_SUM_CLS_LOSS] = 0\n stage_losses[KEY_SUM_REG_LOSS] = 0\n if has_h:\n stage_losses[KEY_SUM_REG_H_LOSS] = 0\n if has_ang:\n stage_losses[KEY_SUM_REG_ANGLE_CLS_LOSS] = 0 \n sum_losses[stage_key] = stage_losses\n\n sum_losses[KEY_SUM_TOTAL_LOSS] = 0\n sum_losses[KEY_SUM_CLS_ACC] = 0\n sum_losses[KEY_NUM_VALID_REG_SAMPLES] = 0\n\n return sum_losses\n\n def get_evaluated_ckpts(self,\n model_config,\n ):\n \"\"\"Finds the evaluated checkpoints.\n\n Examines the evaluation average losses file to find the already\n evaluated checkpoints.\n\n Args:\n model_config: Model protobuf configuration\n\n Returns:\n already_evaluated_ckpts: A list of checkpoint indices, or an\n empty list if no evaluated indices are found.\n \"\"\"\n\n already_evaluated_ckpts = []\n\n # check for previously evaluated checkpoints\n # regardless of model, we are always evaluating rpn, but we do\n # this check based on model in case the evaluator got interrupted\n # and only saved results for one model\n paths_config = model_config.paths_config\n\n predictions_base_dir = paths_config.pred_dir\n avg_loss_file_dir = predictions_base_dir + '/avg_losses/'\\\n + self.dataset_config.data_split \n avg_loss_file_path = avg_loss_file_dir +'/avg_losses.csv'\n\n if os.path.exists(avg_loss_file_path):\n avg_losses = np.loadtxt(avg_loss_file_path, delimiter=',', skiprows=1)\n print(avg_losses)\n if avg_losses.ndim == 1:\n # one entry\n already_evaluated_ckpts = np.asarray(\n [avg_losses[0]], np.int32)\n else:\n already_evaluated_ckpts = np.asarray(avg_losses[:, 0],\n np.int32)\n\n return already_evaluated_ckpts\n\n def get_cls_accuracy(self,\n predictions,\n sum_losses,\n global_step):\n \"\"\"Updates the calculated accuracies for rpn and avod losses.\n\n Args:\n predictions: A dictionary containing the model outputs.\n eval_avod_losses: A dictionary containing all the avod averaged\n losses.\n eval_rpn_losses: A dictionary containing all the rpn averaged\n losses.\n global_step: Current global step that is being evaluated.\n \"\"\"\n final = self.model.STAGE_KEYS[-1] \n predictions = predictions[final]\n cls_pred = predictions[RetinanetModel.PRED_OBJECTNESS]\n cls_gt = predictions[RetinanetModel.PRED_OBJECTNESS_GT]\n cls_gt = cls_gt.astype(np.int32)\n cls_gt_logits = np.eye(2)[cls_gt]\n cls_pred_logits = np.stack([1-cls_pred, cls_pred], axis=1)\n cls_accuracy = self.calculate_cls_accuracy(cls_pred_logits,\n cls_gt_logits)\n\n # get this from the key\n sum_cls_accuracy = sum_losses[KEY_SUM_CLS_ACC]\n sum_cls_accuracy += cls_accuracy\n sum_losses.update({KEY_SUM_CLS_ACC:\n sum_cls_accuracy})\n print(\"Step {}: RetinaNet Classification Accuracy: {}\".format(\n global_step, cls_accuracy))\n\n def calculate_cls_accuracy(self, cls_pred, cls_gt):\n \"\"\"Calculates accuracy of predicted objectness/classification wrt to\n the labels\n\n Args:\n cls_pred: A numpy array containing the predicted\n objectness/classification values in the form (mini_batches, 2)\n cls_gt: A numpy array containing the ground truth\n objectness/classification values in the form (mini_batches, 2)\n\n Returns:\n accuracy: A scalar value representing the accuracy\n \"\"\"\n correct_prediction = np.equal(np.argmax(cls_pred, 1),\n np.argmax(cls_gt, 1))\n accuracy = np.mean(correct_prediction)\n return accuracy\n\n def get_predicted_boxes_3d_and_scores(self, predictions,\n stereo_calib_p2):\n \"\"\"Returns the predictions and scores stacked for saving to file.\n\n Args:\n predictions: A dictionary containing the model outputs.\n\n Returns:\n predictions_and_scores: A numpy array of shape\n (number_of_predicted_boxes, 9), containing the final prediction\n boxes, orientations, scores, and types.\n \"\"\"\n\n if not self.model.do_nms_at_gpu:\n predictions = self.run_nms_cpu(predictions)\n final_pred_anchors = predictions[\n RetinanetModel.PRED_TOP_ANCHORS]\n final_pred_sigmoid = predictions[\n RetinanetModel.PRED_TOP_OBJECTNESS_SIGMOID]\n anchors = final_pred_anchors[:, :5]\n col_h_lo = 5\n col_h_hi = col_h_lo\n if self.model.add_h:\n col_h_hi = col_h_lo + 2\n h = final_pred_anchors[:, col_h_lo:col_h_hi]\n else:\n h = None\n if self.model.add_angle:\n col_angle_cls = col_h_hi\n angle_cls = final_pred_anchors[:, col_angle_cls]\n angle_val = anchors[:, -1]\n angle = orientation_encoder.angle_clsval_to_orientation(angle_cls, angle_val)\n anchors[:, -1] = angle\n bev_shape = [self.model_config.input_config.bev_dims_h,\\\n self.model_config.input_config.bev_dims_w]\n area_extents = self.dataset_config.kitti_utils_config.area_extents\n bev_extents = (area_extents[0:2], area_extents[4:6])\n final_pred_boxes_3d = box_bev_encoder.box_bev_to_box_3d(\\\n anchors, bev_shape, bev_extents, h)\n \n # Append score and class index (object type)\n #shape is (number_of_top_anchors, num_class[no background]) \n \n #ONLY ONE CLASS. BESIDES, nms is done for each class. 0 means 1th object type.\n final_pred_types = np.zeros_like(final_pred_sigmoid, dtype=np.int32)\n final_pred_scores = final_pred_sigmoid\n \n predictions_and_scores = np.column_stack(\n [final_pred_boxes_3d,\n final_pred_scores,\n final_pred_types])\n\n return predictions_and_scores\n\n def run_kitti_native_eval(self, global_step):\n \"\"\"Calls the kitti native C++ evaluation code.\n\n It first saves the predictions in kitti format. It then creates two\n child processes to run the evaluation code. The native evaluation\n hard-codes the IoU threshold inside the code, so hence its called\n twice for each IoU separately.\n\n Args:\n global_step: Global step of the current checkpoint to be evaluated.\n \"\"\"\n\n # Kitti native evaluation, do this during validation\n # and when running Avod model.\n # Store predictions in kitti format\n evaluator_utils.save_predictions_in_kitti_format(\n self.model,\n self.model_config.checkpoint_name,\n self.dataset_config.data_split,\n self.eval_config.kitti_score_threshold,\n global_step)\n\n checkpoint_name = self.model_config.checkpoint_name\n kitti_score_threshold = self.eval_config.kitti_score_threshold\n\n # Create a separate processes to run the native evaluation\n #native_eval_proc = Process(\n # target=evaluator_utils.run_kitti_native_script, args=(\n # checkpoint_name, kitti_score_threshold, global_step))\n\n eval_script_dir = self.paths_config.pred_dir #predictions_base_dir\n native_eval_proc = Process(\n target=run_my_kitti_native_script,\n args=(eval_script_dir, \n self.dataset_config.data_split,\n global_step,\n '07'))\n native_eval_proc_05_iou = Process(\n target=run_my_kitti_native_script,\n args=(eval_script_dir, \n self.dataset_config.data_split,\n global_step,\n '05')) #iou05=True\n #native_eval_proc_05_iou = Process(\n # target=evaluator_utils.run_kitti_native_script_with_05_iou,\n # args=(checkpoint_name, kitti_score_threshold, global_step))\n # Don't call join on this cuz we do not want to block\n # this will cause one zombie process - should be fixed later.\n native_eval_proc.start()\n native_eval_proc_05_iou.start()\n\n def run_nms_cpu(self, predictions):\n pred_anchors = predictions[\\\n RetinanetModel.PRED_TOP_ANCHORS]\n pred_sigmoid = predictions[\\\n RetinanetModel.PRED_TOP_OBJECTNESS_SIGMOID]\n\n #do NMS\n pred_boxes = pred_anchors[:, :5]\n boxes = pred_boxes\n boxes[:, -1] *= (180 / np.pi) #convert rad to degree for openCV\n scores = np.reshape(pred_sigmoid, (-1,))\n max_output_size = 100\n iou_threshold = 0.3\n\n keep = []\n\n order = scores.argsort()[::-1]\n num = boxes.shape[0]\n\n suppressed = np.zeros((num), dtype=np.int)\n start = time.time()\n for _i in range(num):\n if len(keep) >= max_output_size:\n break\n\n i = order[_i]\n if suppressed[i] == 1:\n continue\n keep.append(i)\n r1 = ((boxes[i, 0], boxes[i, 1]), (boxes[i, 2], boxes[i, 3]), boxes[i, 4])\n area_r1 = boxes[i, 2] * boxes[i, 3]\n for _j in range(_i + 1, num):\n j = order[_j]\n if suppressed[i] == 1:\n continue\n r2 = ((boxes[j, 0], boxes[j, 1]), (boxes[j, 2], boxes[j, 3]), boxes[j, 4])\n area_r2 = boxes[j, 2] * boxes[j, 3]\n inter = 0.0\n\n int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]\n\n if int_pts is not None:\n order_pts = cv2.convexHull(int_pts, returnPoints=True)\n\n int_area = cv2.contourArea(order_pts)\n\n inter = int_area * 1.0 / (area_r1 + area_r2 - int_area + 1e-5)\n\n if inter >= iou_threshold:\n suppressed[j] = 1\n\n #return np.array(keep, np.int64)\n print('cost: ', time.time() -start)\n keep = keep[:max_output_size]\n print(len(boxes), len(keep), keep[:5])\n predictions[RetinanetModel.PRED_TOP_ANCHORS] = pred_anchors[keep]\n predictions[RetinanetModel.PRED_TOP_OBJECTNESS_SIGMOID] = pred_sigmoid[keep]\n return predictions\n #TODO : TEST THIS FUNCTION!!!!!\n\n\ndef run_my_kitti_native_script(eval_script_dir, data_split, global_step, iou='05'):\n\n if iou == '05': \n make_script = eval_script_dir + \\\n '/kitti_native_eval/run_05iou.sh'\n elif iou == '07':\n make_script = eval_script_dir + \\\n '/kitti_native_eval/run.sh'\n else:\n raise ValueError('Wrong IoU threshold.')\n script_folder = os.path.dirname(make_script)\n subprocess.call([make_script, script_folder, \n str(global_step),\n str(data_split),])\n \n\n\n\n","sub_path":"avod/avod/core/evaluator_retinanet.py","file_name":"evaluator_retinanet.py","file_ext":"py","file_size_in_byte":36483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"480476075","text":"from util import *\n\n\n@apply\ndef apply(given):\n lhs, rhs = given.of(Less)\n assert lhs.is_extended_integer and rhs.is_extended_integer\n return LessEqual(lhs, rhs - 1)\n\n\n@prove\ndef prove(Eq):\n x, y = Symbol(integer=True, given=True)\n Eq << apply(x < y)\n\n Eq << ~Eq[1]\n\n Eq <<= Eq[-1] & Eq[0]\n\n\nif __name__ == '__main__':\n run()\nfrom . import plus\n# created on 2018-05-05\n","sub_path":"axiom/algebra/lt/imply/le/strengthen/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"398949416","text":"# (c) Copyright 2016 Hewlett Packard Enterprise Development LP\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom time import sleep\n\nTOPOLOGY = \"\"\"\n# +--------+ +--------+\n# | |eth0 | |\n# | hs2 +---------+ ops1 |\n# | | eth1| |\n# +--------+ +-+------+\n# |eth0\n# |\n# |eth0\n# +---+----+\n# | |\n# | hs1 |\n# | |\n# +--------+\n\n# Nodes\n[type=openswitch name=\"OpenSwitch 1\"] ops1\n[type=oobmhost image=\"openswitch/tacacs_server:latest\" name=\"Host 1\"] hs1\n[type=oobmhost image=\"openswitch/tacacs_server:latest\" name=\"Host 2\"] hs2\n\n# Ports\n[force_name=oobm] ops1:eth1\n[force_name=oobm] ops1:eth0\n\n# Links\nops1:eth0 -- hs1:eth0\nops1:eth1 -- hs2:eth0\n\"\"\"\n\nNETOP_PTIV_LVL = \"14\"\n\ndef tacacs_add_server(dut, step):\n step('\\n### === Adding tacacs server === ###')\n vtysh_shell = dut.get_shell('vtysh')\n matches = ['#']\n cmd = \"su netop\"\n assert vtysh_shell.send_command(cmd, matches) is 0\n # dut(\"su netop\", shell='bash')\n dut(\"configure terminal\")\n dut(\"tacacs-server host 192.168.1.254\")\n dut(\"tacacs-server host 192.168.1.253\")\n dut(\"end\")\n dump = dut(\"show running-config\")\n lines = dump.splitlines()\n count = 0\n\n for line in lines:\n if \"tacacs-server host 192.168.1.254\" in line:\n count = count + 1\n if \"tacacs-server host 192.168.1.253\" in line:\n count = count + 1\n assert count == 2,\\\n '\\n### Adding tacacs servers test failed ###'\n step('\\n### servers present in running config - passed ###')\n step('\\n### === server added == ###\\n')\n\n\ndef tacacs_create_server_group(dut, step):\n step('\\n### === Create tacacs+ group tac1, tac2 and add server === ###')\n dut(\"configure terminal\")\n dut(\"aaa group server tacacs_plus tac1\")\n dut(\"server 192.168.1.254\")\n dut(\"exit\")\n dut(\"aaa group server tacacs_plus tac2\")\n dut(\"server 192.168.1.253\")\n dut(\"end\")\n\n count = 0\n dump = dut(\"show running-config\")\n lines = dump.splitlines()\n\n for line in lines:\n if \"aaa group server tacacs+ tac1\" in line:\n count = count + 1\n if \"server 192.168.1.254\" in line:\n count = count + 1\n if \"aaa group server tacacs+ tac2\" in line:\n count = count + 1\n if \"server 192.168.1.253\" in line:\n count = count + 1\n assert count == 4,\\\n '\\n### Create tacacs+ group tac1,tac2 and add server test failed ###'\n\n step('\\n### Create tacacs+ group tac1,tac2 and add server test passed ###')\n step('\\n### === Create tacacs+ group tac1,tac2 and add server test end === ###\\n')\n\n\ndef set_aaa_authorization_none(dut, step):\n step('\\n### === set aaa authorization to none test start === ###')\n dut(\"configure terminal\")\n dut(\"aaa authorization commands default none\")\n dut(\"end\")\n\n count = 0\n ''' now check the running config '''\n dump = dut(\"show running-config\")\n lines = dump.splitlines()\n for line in lines:\n if (\"aaa authorization commands default none\" in line):\n count = count + 1\n assert count == 1,\\\n '\\n### set aaa authorization to none test failed ###'\n\n step('\\n### set aaa authorization to none test passed ###')\n step('\\n### === set aaa authorization to none test end === ###\\n')\n\n\ndef set_aaa_authorization_groups_chk_authorization(dut, step):\n step('\\n### === set aaa authorization with groups test start === ###')\n dut(\"configure terminal\")\n dut(\"aaa authorization commands default group tac1 tac2 none\")\n dut(\"end\")\n\n count = 0\n ''' now check the running config '''\n dump = dut(\"show running-config\")\n lines = dump.splitlines()\n for line in lines:\n if (\"aaa authorization commands default group tac1 tac2 none\" in line):\n count = count + 1\n assert count == 1,\\\n '\\n### set aaa authorization with groups and test authorization test failed ###'\n\n step('\\n### set aaa authorization with groups and test authorization test passed ###')\n step('\\n### === set aaa authorization with groups and test authorization test end === ###\\n')\n\n\ndef unset_aaa_authentication_groups(dut, step):\n step('\\n### === unset aaa authorization test start === ###')\n dut(\"configure terminal\")\n dut(\"no aaa authorization commands default\")\n dut(\"end\")\n\n count = 0\n ''' now check the running config '''\n dump = dut(\"show running-config\")\n lines = dump.splitlines()\n for line in lines:\n if (\"aaa authorization commands default\" in line):\n count = count + 1\n assert count == 0,\\\n '\\n### unset aaa authorization test failed ###'\n\n step('\\n### unset aaa authorization test passed ###')\n step('\\n### === unset aaa authorization test end === ###\\n')\n\n\ndef test_ct_tacacs_config(topology, step):\n ops1 = topology.get('ops1')\n hs1 = topology.get('hs1')\n hs2 = topology.get('hs2')\n\n # Wait switch to come up\n sleep(10)\n\n # Server IP address\n hs1.libs.ip.interface('eth0', addr='192.168.1.254/24', up=True)\n\n hs2.libs.ip.interface('eth0', addr='192.168.1.253/24', up=True)\n\n # Switch IP address\n with ops1.libs.vtysh.ConfigInterfaceMgmt() as ctx:\n ctx.ip_static('192.168.1.1/24')\n\n tacacs_add_server(ops1, step)\n\n tacacs_create_server_group(ops1, step)\n\n set_aaa_authorization_none(ops1, step)\n\n set_aaa_authorization_groups_chk_authorization(ops1, step)\n","sub_path":"ops-tests/feature/test_aaa_ft_tacacs_authorization.py","file_name":"test_aaa_ft_tacacs_authorization.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"627165077","text":"def main():\n stop = False\n user = \"nothing\"\n List = []\n while(not stop):\n user = input(\"Put in a word: \")\n if(user == \"\"):\n stop = True\n else:\n lower = user.lower()\n firstLetter = lower[0]\n for x in range(1,len(user)):\n if (user[x] == firstLetter):\n List.append(user)\n\n for x in range(0,len(List)):\n print(List[x])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Labs/Lab 5/List.py","file_name":"List.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"634798491","text":"import logging\nimport os\n\nfrom google.appengine.api import app_identity\n\n\n\"\"\" Class for storing specific configuration parameters. \"\"\"\nclass Config:\n # Mutually exclusive flags that specify whether the application is running on\n # hd-events-hrd, dev_appserver, or local unit tests.\n is_dev = False\n is_prod = True\n is_testing = False;\n\n def __init__(self):\n try:\n # Check if we are running on the local dev server.\n software = os.environ[\"SERVER_SOFTWARE\"]\n Config.is_dev = software.startswith(\"Dev\") and \"testbed\" not in software\n except KeyError:\n pass\n\n try:\n self.APP_NAME = app_identity.get_application_id()\n except AttributeError:\n # We're calling code outside of GAE, so we must be testing.\n self.APP_NAME = \"testbed-test\"\n if self.APP_NAME == \"testbed-test\":\n Config.is_testing = True\n\n Config.is_prod = not (Config.is_dev or Config.is_testing)\n\n # The URL of the signup app.\n self.SIGNUP_URL = \"https://hd-signup-hrd.appspot.com\"\n\n # The minimum amount of time that must be left between consecutive events,\n # in minutes.\n self.MIN_EVENT_SPACING = 30\n # The maximum amount of future events a single user can have scheduled.\n self.USER_MAX_FUTURE_EVENTS = 10\n # The maximum number of events a single user can have within a four-week\n # period.\n self.USER_MAX_FOUR_WEEKS = 6\n # How long we have to wait after we sign up before we can create an event.\n # (days)\n self.NEW_EVENT_WAIT_PERIOD = 0\n # How long we will keep an event on hold when a user is suspended before it\n # expires. (days)\n self.SUSPENDED_EVENT_EXPIRY = 72\n\n # The hours that we wan to have only one event during. (24-hour time.)\n self.EVENT_HOURS = (9, 17)\n\n if Config.is_testing:\n logging.debug(\"Is testing.\")\n elif Config.is_dev:\n logging.debug(\"Is dev server.\")\n else:\n logging.debug(\"Is production server.\")\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"578612832","text":"\"\"\"\n\n\n\nICQSplitter is a Python package that will take data from the International Comet Quarterly (ICQ), Comet OBServation database (COBS), and\nJPL Horizons and produce lightcurves of the comet with adjustable corrections. These data are usually provided in an 80\ncolumn text file format. See 'input_columns_meaning.txt' for a description of what each column represents.\n\nAt its base level this program will read in this 80 column format (available from ICQ or COBS) and convert it to a .csv file \nthat is more accessible to most people. As these data are from citizen astronomers and ICQ and COBS reports\nall data reported from an observer, this program also filters from the data entries that do not meet a field standard set of criterion \n(such as removing observations made under reported poor weather conditions, only using one observation per observer per night, removing \nobservation that were made with telescopes when the comet was too bright, etc...). A list of all criterion for why\na observation is 'kept' or 'removed' can be found on 'reasons_data_were_removed.txt'. This code is set up such that\nif there is a reason included here for why a point is removed that you do not agree with then you can comment out that section\nin main().\n\nThere exists command line arguments --heliocentric and --phase that will pull ephemerides from JPL HORIZONS with\nMichael Mommert's CALLHORIZONS package as well as Dave Schleicher's Composite Dust Phase Function for Comets available \nhere: http://asteroid.lowell.edu/comet/dustphase.html that will perform heliocentric corrections, phase angle corrections,\nor both to the kept points.\n\nUsers may also perform statistical corrections with the --stats command line argument. Please see the file\n'statistics_method_appendix.txt' for an understanding of what this command does. (note at least one of --heliocentric\nand --phase must be used along with --stats to query JPL). WARNING: --stats should only be used for one\ndates corresponding to one revolution around the sun for that object (i.e., if a comet has data with perihelions occuring on dates\nx, y, and z then this function will work for dates between x and z exclusive, separating it into pre-perihelion data in range (x,y] and\npost-perihelion data in range (y,z) ).\n\nThe command line argument --plot will also plot any available data (i.e., any combination of raw magnitudes, mehlio, mphase, and \nmshift Vs. heliocentric distance). (note at least one of --heliocentric and --phase must be used along with --plot to query JPL).\n\n\n\ncurtisa1 (at) mail.usf.edu, latest version: v3.1, 2018-08-02\n\nAvailable command line arguments (type these into terminal when compiling program):\n--heliocentric\n--phase\n--stats\n--plot\n\n* v1.0: Sorts problematic entries from data, performs heliocentric distance and phase angle corrections.\n* v1.1: Added Input Argument CCD_Bool for people using only CCD Measurements.\n* v2.0: Added statistical correction and plotting command line arguments!\n* v2.1: Fixed issues with statistical analysis. Added option to get full detailed stats analysis. Uncomment 570 - 576 and 639 - 645 and 711 - 714 to see the output files!.\n* v2.2: Julian Dates not output along with YYYY-MM-DDTHH:MM:SS datetimes.\n* v3.0: Fixed issue where --stats was reading in observers with a statistically insignifican number of points (aka 20), changed design of figures\n* v3.1: Fixed some more edge case issues with --stats\n\n\n\"\"\"\n\n###############################\n####### Input Arguments #######\n###############################\n\ninput_file = 'analysis_2020-07-10_1549.dat' #Name of your input file\ntarget_nickname = 'NEOWISE' #Nickname of target for output file organization (for example, HB = Hale-Bopp)\nsmall_body_designation = 'C/2020 F3' #Name of your small body ex) 'ceres' or 'eris'\nJPL_Time_Increment = 30 #How much to increment JPL queries in minutes up to 60.\nouput_file_kept_points = 'keepers.csv' #Name of output file for points that meet all sorting criterion\noutput_file_rejected_points = 'removed.csv' #Name of output file for points that were removed from the data\nperihelion = '2020/07/03' #Datetime of perihelion format YYYY/MM/DD\nCCD_Bool = 1 #If 0 then user only has CCD measurements only, if 1 then user has visual magnitude measurements\n\n###############################\n####### Input Arguments #######\n###############################\n\ntry:\n import callhorizons\nexcept:\n print('Please install the callhorizons python package with pip install callhorizons')\nimport os\nimport numpy as np\nimport math\nimport csv\nimport sys\nimport time\nimport matplotlib\nimport pylab as plt\nimport statistics\nfrom scipy import stats\nfrom scipy import linalg\nfrom matplotlib.ticker import MultipleLocator\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport matplotlib.ticker as tickers\nfrom datetime import datetime, timedelta\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=RuntimeWarning) \n\n#Deletes the i-th observation in the dataset after it failed a sorting criterion\n#Defined later, metalist is a list whose elements are each column (as lists) of the input file\n#see mainblock to know what each element of metalist is (e.g., metalist[23] == list of observer for each observation)\n#read as: for each colum in our data, start at the last point, work backwards and delete the specified point\ndef deletearow(i):\n for x in range (len(metalist)-1, -1, -1):\n del metalist[x][i]\n\n#Adds the i-th deleted observation to the 'rejected.csv' file with y as a reason it was removed\n#removed_metalist is the same as metalist except for the rejected points during sorting\ndef addToremoved(i,y):\n for x in range (len(metalist)-1, -1, -1):\n removed_metalist[x].append(metalist[x][i])\n removed_metalist[24].append(\"REMOVED POINT\")\n removed_metalist[25].append(list_of_reasons_removed[y])\n\n#Removes a point from the dataset if there is more than one observation from the same observer at the same night\n#read as: for total number of points in a column (i.e., total number of observations), work backwards and delete necessary points\n#If observer, year, month, and day are the same then delete a point based on the focal lengths metalist[11] or observation method metalist[7]\ndef deleteForDuplicatedDates(numdelforduplicatedate):\n for k in range (len(metalist[2])-1, -1, -1):\n if k == 0:\n print(\"number deleted for duplicated observation dates by same person \"+str(numdelforduplicatedate))\n break\n if (metalist[23][k]==metalist[23][k-1]) and (metalist[3][k] == metalist[3][k-1]) and (metalist[4][k] == metalist[4][k-1]) and (math.floor(float(metalist[5][k])) == math.floor(float(metalist[5][k-1]))):\n if (float(metalist[11][k]) 8.1):\n addToremoved(k-1,reasonForDelete)\n deletearow(k)\n numberremovedforSCcatalog = numberremovedforSCcatalog +1\n print(\"number deleted for SC catalog being used on object dimmer than 8.1 \", numberremovedforSCcatalog)\n \n#This functions will take a decimal date as reported in ICQ and convert it to YYYY:MM:DD HH:MM:SS format.\n#That is, for each date in the data (metalist[3], metalist[4], and metalist[5]) it will convert it to the above format.\n#For example if metalist[3][0] == 1996, metalist[4][0] == 04, and metalist[5][0] == 30.50 \n#then it will append to the output list 1996:04:30 12:00:00\n#These dates are then used to compare to the result of the JPL HORIZONS Ephemerides query to find the nearest time in the query\ndef decimaldate2hhmmss():\n global date_compare_to_JPL\n date_compare_to_JPL = []\n for i in range(0, len(metalist[3])):\n tmp_date = \"\"\n tmp_decimal = \"\"\n past_decimal = 0\n for j in range(0, len(metalist[5][i])):\n if (metalist[5][i][j] != \".\") and (past_decimal == 0):\n tmp_date = tmp_date + metalist[5][i][j]\n if metalist[5][i][j] == \".\":\n past_decimal = 1\n if (past_decimal ==1):\n tmp_decimal = tmp_decimal + metalist[5][i][j]\n tmp_hours = str(float(tmp_decimal) * 24)\n past_decimal = 0\n hours = \"\"\n tmp_decimal2 = \"\"\n for j in range(0, len(tmp_hours)):\n if (tmp_hours[j] != \".\") and (past_decimal == 0):\n hours = hours + tmp_hours[j]\n if tmp_hours[j] == \".\":\n past_decimal = 1\n if (past_decimal ==1):\n tmp_decimal2 = tmp_decimal2 + tmp_hours[j]\n tmp_minutes = str(float(tmp_decimal2) * 60)\n past_decimal = 0\n minutes = \"\"\n tmp_decimal3 = \"\"\n for j in range(0, len(tmp_minutes)):\n if (tmp_minutes[j] != \".\") and (past_decimal == 0):\n minutes = minutes + tmp_minutes[j]\n if tmp_minutes[j] == \".\":\n past_decimal = 1\n if (past_decimal == 1):\n tmp_decimal3 = tmp_decimal3 + tmp_minutes[j]\n tmp_seconds = str(float(tmp_decimal3) * 60)\n seconds = \"\"\n for j in range(0, len(tmp_seconds)):\n if (tmp_seconds[j] != \".\"):\n seconds = seconds + tmp_seconds[j]\n if (tmp_seconds[j] == \".\"):\n break\n date_compare_to_JPL.append(metalist[3][i] + \"-\"+metalist[4][i] + \"-\" + tmp_date + \" \" + str(\"%02d\"%(float(hours),)) + \":\"+str(\"%02d\"%(float(minutes),))+\":\"+ str(\"%02d\"%(float(seconds),)))\n\n#This will query JPL HORIZONS and pull the ephemerides of the object inputted above.\n#The epoch range will be from the first time in your 'kept' observation (i.e., points remaining after the previous sorting) to the last time\n#at the increment range also inputted (default is every 30 minutes). \n#That is if your first date is 1996:01:19 00:00, final date is 1996:01:19 01:00 and your increment size is every 30 minutes then it will\n#query JPL Horizons for the ephemerides of your object at 1996:01:19 00:00, 1996:01:19 00:30, and 1996:01:19 01:00\n#It then stores the required information from this query in global lists to be used later\n#\n#\n#There were two choices for this block, query JPL HORIZONS at each point in the data or query once over the entire date/time range.\n#I went with the latter as each individual query to JPL HORIZONS takes quite a bit of time, although this way\n#does require much more sorting later on. Additionally, for date ranges over long periods of time you can only\n#query JPL at 30 minute increments before running into their 100,000 epoch query limit. However, the change\n#in delta and phase angle during a 30 minute (or even 1 hour) period is insignificant to the fact that amateurs report\n#these magnitudes to one decimal place.\ndef queryJPL():\n global OBJDelta\n global OBJDates\n global OBJPhase\n global OBJr\n global OBJJulianDate\n global r_at_perihelion\n initial_date = str(metalist[3][0]) + \"/\" + str(metalist[4][0]) + \"/\" + str(math.floor(float(metalist[5][0])))\n final_date = str(metalist[3][0]) + \"/\" + str(metalist[4][0]) + \"/\" + str(math.floor(float(metalist[5][0])))\n place_in_list_initial = 0\n place_in_list_final = 0\n peri_date = datetime.strptime(perihelion,\"%Y/%m/%d\")\n plus_one_day_peri = peri_date + timedelta(days=1)\n peri_date = str(peri_date.date()).replace(\"-\",\"/\")\n plus_one_day_peri = str(plus_one_day_peri.date()).replace(\"-\",\"/\")\n\n print(\"looking for closest observation to perihelion date provided\")\n for j in range (0, len(metalist[3])):\n check_date = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate1 = time.strptime(initial_date, \"%Y/%m/%d\")\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n newdate3 = time.strptime(final_date, \"%Y/%m/%d\")\n peridate = time.strptime(perihelion, \"%Y/%m/%d\")\n if newdate2 < newdate1:\n initial_date = check_date\n elif newdate2 > newdate3:\n final_date = check_date\n if j == 0:\n last_newdate2 = newdate2\n continue\n if (peridate >= newdate2) and (last_newdate2 <= newdate2):\n thisj = j\n last_newdate2 = newdate2\n\n try:\n check_date = str(metalist[3][thisj]) + \"/\" + str(metalist[4][thij]) + \"/\" + str(math.floor(float(metalist[5][thisj])))\n newdate1 = time.strptime(initial_date, \"%Y/%m/%d\")\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n newdate3 = time.strptime(final_date, \"%Y/%m/%d\")\n peridate = time.strptime(perihelion, \"%Y/%m/%d\") \n\n if newdate2 == peridate:\n small_body_for_peri_r = callhorizons.query(small_body_designation)\n small_body_for_peri_r.set_epochrange(peri_date,plus_one_day_peri,str(JPL_Time_Increment) + 'm')\n small_body_for_peri_r.get_ephemerides(500)\n tmp_r_at_peri_date = small_body_for_peri_r['r']\n else:\n this_date = datetime.strptime(check_date,\"%Y/%m/%d\")\n plus_one_day_this = this_date + timedelta(days=1)\n this_date = str(this_date.date()).replace(\"-\",\"/\")\n plus_one_day_this = str(plus_one_day_this.date()).replace(\"-\",\"/\")\n small_body_for_peri_r = callhorizons.query(small_body_designation)\n small_body_for_peri_r.set_epochrange(this_date,plus_one_day_this,str(JPL_Time_Increment) + 'm')\n small_body_for_peri_r.get_ephemerides(500)\n tmp_r_at_peri_date = small_body_for_peri_r['r']\n \n except:\n for j in range (0, len(metalist[3])):\n check_date = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate1 = time.strptime(initial_date, \"%Y/%m/%d\")\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n newdate3 = time.strptime(final_date, \"%Y/%m/%d\")\n peridate = time.strptime(perihelion, \"%Y/%m/%d\")\n if newdate2 < newdate1:\n initial_date = check_date\n elif newdate2 > newdate3:\n final_date = check_date\n if j == 0:\n last_newdate2 = newdate2\n continue\n if (peridate <= newdate2) and (last_newdate2 > newdate2):\n thisj = j\n last_newdate2 = newdate2\n \n check_date = str(metalist[3][thisj]) + \"/\" + str(metalist[4][thisj]) + \"/\" + str(math.floor(float(metalist[5][thisj])))\n newdate1 = time.strptime(initial_date, \"%Y/%m/%d\")\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n newdate3 = time.strptime(final_date, \"%Y/%m/%d\")\n peridate = time.strptime(perihelion, \"%Y/%m/%d\") \n if newdate2 == peridate:\n small_body_for_peri_r = callhorizons.query(small_body_designation)\n small_body_for_peri_r.set_epochrange(peri_date,plus_one_day_peri,str(JPL_Time_Increment) + 'm')\n small_body_for_peri_r.get_ephemerides(500)\n tmp_r_at_peri_date = small_body_for_peri_r['r']\n else:\n this_date = datetime.strptime(check_date,\"%Y/%m/%d\")\n plus_one_day_this = this_date + timedelta(days=1)\n this_date = str(this_date.date()).replace(\"-\",\"/\")\n plus_one_day_this = str(plus_one_day_this.date()).replace(\"-\",\"/\")\n small_body_for_peri_r = callhorizons.query(small_body_designation)\n small_body_for_peri_r.set_epochrange(this_date,plus_one_day_this,str(JPL_Time_Increment) + 'm')\n small_body_for_peri_r.get_ephemerides(500)\n tmp_r_at_peri_date = small_body_for_peri_r['r']\n\n print('closest observation found')\n print('Querying JPL HORIZONS')\n \n r_at_perihelion = float(\"%.1f\" % tmp_r_at_peri_date[math.floor(len(tmp_r_at_peri_date)/2)])\n initial_date = initial_date.replace(\"/\",\"-\") + \" 00:00\"\n final_date = final_date.replace(\"/\",\"-\") + \" 23:00\"\n #Queries JPL HORIZONS\n small_body = callhorizons.query(small_body_designation)\n #By default time_string = '30m' that is from initial_date to final_date at 30 minute increments\n #Change increment at top of code for increments from every 1 to 60 minutes.\n #Code currently does not allow for increments in time periods greater than 60 minutes\n #TODO fix the above, will require changing the line below as well as the if statements in the optional argument blocks that compare the times.\n time_string = str(JPL_Time_Increment) + 'm'\n small_body.set_epochrange(initial_date, final_date , time_string)\n print (small_body.get_ephemerides(500), 'epochs queried')\n OBJDelta = small_body['delta']\n OBJDates = small_body['datetime']\n OBJPhase = small_body['alpha']\n OBJr = small_body['r']\n OBJJulianDate = small_body['datetime_jd']\n tmp_dates =[]\n hours = \"\"\n minutes = \"\"\n seconds = \"\"\n date_compare_to_JPL = decimaldate2hhmmss()\n for k in range(0, len(OBJDates)):\n OBJDates[k] = OBJDates[k].replace(\"Jan\",\"01\")\n OBJDates[k] = OBJDates[k].replace(\"Feb\",\"02\")\n OBJDates[k] = OBJDates[k].replace(\"Mar\",\"03\")\n OBJDates[k] = OBJDates[k].replace(\"Apr\",\"04\")\n OBJDates[k] = OBJDates[k].replace(\"May\",\"05\")\n OBJDates[k] = OBJDates[k].replace(\"Jun\",\"06\")\n OBJDates[k] = OBJDates[k].replace(\"Jul\",\"07\")\n OBJDates[k] = OBJDates[k].replace(\"Aug\",\"08\")\n OBJDates[k] = OBJDates[k].replace(\"Sep\",\"09\")\n OBJDates[k] = OBJDates[k].replace(\"Oct\",\"10\")\n OBJDates[k] = OBJDates[k].replace(\"Nov\",\"11\")\n OBJDates[k] = OBJDates[k].replace(\"Dec\",\"12\")\n\n#Add headers to the columns in the output csv files.\ndef add_headers(x):\n x[0].insert(0,'col 1-3 : short period comet designation')\n x[1].insert(0, 'col 4-9 : Standard comet designation')\n x[2].insert(0, 'col 10 : multiple nuclei present?')\n x[3].insert(0,'col 12-15 : year observed')\n x[4].insert(0,'col 17-18 : month observed')\n x[5].insert(0, 'col 20-24')\n x[6].insert(0,'col 26 : special note / extinction note')\n x[7].insert(0, 'col 27 : Magnitude collection method')\n x[8].insert(0, 'col 28-32 : visual magnitude estimate')\n x[9].insert(0, 'col 33 : poor conditions?')\n x[10].insert(0, 'col 34 - 35 : reference catalog')\n x[11].insert(0, 'col 36-40 : instrument aperture in centimeters')\n x[12].insert(0, 'col 41 : instrument type')\n x[13].insert(0, 'col 42 - 43 : focal ratio')\n x[14].insert(0, 'col 44-47 : magnification used')\n x[15].insert(0, 'col 49 : error estimate for coma diameter')\n x[16].insert(0, 'col 50 - 54 : coma diameter in arcminutes')\n x[17].insert(0, 'col 55 : special note on central condensation of comet')\n x[18].insert(0, 'col : 56 -57 : degree of condensation (note / means estimate)')\n x[19].insert(0, 'col 59 - 64 : error of tail approximation and tail approximation')\n x[20].insert(0, 'col 65 - 67 : direction tail is pointed')\n x[21].insert(0, 'col 69-74 : ICQ reference publication')\n x[22].insert(0, 'col 75 : second special note / extinction note ')\n x[23].insert(0, 'col 76-80 : observer name')\n \n#Sorts r from largest to smallest while keeping track of all of ICQ metadata (listPreorPost) for each observation.\n#Used twice, first in stats_shifts function (firstpass = 0) where keeping track of metadata information is important\n#It is also used in plotting, (firstpass = 1) where we do not need the meta information so we skip this step if that is the case\ndef sortbyr(listPreorPost,r,mags, firstpass):\n sorted_metalist = []\n r_sorted = []\n mag_sorted = []\n r = np.array(r)\n r_sorted = -np.sort(-r)\n for i in range (0,len(r_sorted)): #for each object in the sorted list\n for j in range(0,len(r)): #find its corresponding entry in unsorted list, this position is the position of all corresponding metadata\n if firstpass == 0:\n if (r_sorted[i] == r[j]): #and (listPreorPost[j] not in sorted_metalist):\n sorted_metalist.append(listPreorPost[j])\n mag_sorted.append(mags[j])\n break\n if (r_sorted[i] == r[j]) and (firstpass == 1):\n mag_sorted.append(mags[j])\n break\n return sorted_metalist, mag_sorted, r_sorted\n \ndef getcolumn(matrix, i):\n return [row[i] for row in matrix]\n \n#Performs the procedures to iterate a polynomial to convergence of tolerance 0.0001 in given data (see file 'Statistics_method_appendix.txt' in the GitHub repository)\n#Inputs: preorpost - String stating whether this is pre-perihelion or post-perihelion data (determined later in the code)\n#listoflists - ICQ metadata\n#dateThours - date in YYYY-MM-DDTHH:MM:SS format used for submitting to NASA PDS and checking whether pre or post perihelion \n#deltas - list of geocentric distances (from JPL)\n#phases - list of phase angles (from JPL)\n#helio_distances - list of r- values\n#condemned_list - List of observers who have failed the stationary test, not to be used on future convergence tests\n#other_mag Last calculated magnitude (either mhelio or mphase depending on which combination of the two the user used)\n#first_pass - If 1 then this is the first time the data are having a polynomial fit to them (so that r-values do not have their natural log taken twice upon being read in). \n#Primary Return is mshift - the magnitudes shifted by the mean of an observer's residuals between a global polynomial fit and their data (iterated to convergence)\ndef stats_shifts(preorpost, listoflists, corrected_mag, dateThours, deltas, phases, helio_distances, condemned_list, other_mag, first_pass, dateJulian):\n mshift = []\n obs_list = []\n sorted_stats = []\n stats = []\n mags = []\n r = []\n new_poly_fit = []\n original_poly_fit = []\n mags_sorted_stat = []\n r_sorted_stat = []\n stdev_per_observer = []\n resid_per_obs = []\n stdev_resid_per_observer =[]\n count_per_observer = []\n residuals = []\n sum_resid_per_observer = []\n mean_resid_per_observer = []\n tolerance = 0.0001\n\n #Checks data are in pre-perihelion range, sorts the data by r (large to small), and rearranges all metadata accordingly\n if preorpost == 'pre':\n #Next if loop necessary in case user only supplied post-perihelion data. Read: if no data are found for pre-perihelion then\n #fill it with blank spaces that the program will know to skip later.\n if (len(other_mag) == 1) or (len(other_mag) == 0) or ('' in other_mag):\n for j in range(0, len(listoflists[0])):\n other_mag.append('')\n #for each observer, check if it is pre-perihelion, if so take log(r and sort)\n for j in range (0, len(listoflists[0])):\n tmprow = []\n newdate4 = time.strptime(perihelion, \"%Y/%m/%d\")\n datetocheck = str(listoflists[3][j]) + \"/\" + str(listoflists[4][j]) + \"/\" + str(math.floor(float(listoflists[5][j])))\n newdate5 = time.strptime(datetocheck, \"%Y/%m/%d\")\n if (newdate5 <= newdate4) and (listoflists[23][j].strip() not in condemned_list):\n for k in range (0,len(listoflists)):\n tmprow.append(listoflists[k][j])\n tmprow.append(dateThours[j])\n tmprow.append(corrected_mag[j])\n tmprow.append(deltas[j])\n tmprow.append(phases[j])\n mags.append(float(corrected_mag[j]))\n if (len(other_mag) != 1) and (len(other_mag) != 0) and ('' not in other_mag):\n tmprow.append(other_mag[j])\n else:\n other_mag.append('')\n tmprow.append(other_mag[j])\n if first_pass ==1:\n r.append(math.log10(float(helio_distances[j])))\n elif first_pass == 0:\n r.append(float(helio_distances[j]))\n tmprow.append(dateJulian[j])\n stats.append(tmprow)\n \n #Reads in only post-perihelion data from data in input function \n if preorpost =='post':\n #Next if loop necessary in case user only supplied pre-perihelion data. Read: if no data are found for post-perihelion then\n #fill it with blank spaces that the program will know to skip later.\n if (len(other_mag) == 1) or (len(other_mag) == 0) or ('' in other_mag):\n for j in range(0, len(listoflists[0])):\n other_mag.append('')\n #for each observer, check if it is pre-perihelion, if so take log(r and sort)\n \n for j in range (0, len(listoflists[0])):\n tmprow = []\n newdate4 = time.strptime(perihelion, \"%Y/%m/%d\")\n datetocheck = str(listoflists[3][j]) + \"/\" + str(listoflists[4][j]) + \"/\" + str(math.floor(float(listoflists[5][j])))\n newdate5 = time.strptime(datetocheck, \"%Y/%m/%d\")\n if (newdate5 > newdate4) and (listoflists[23][j].strip() not in condemned_list):\n for k in range (0,len(listoflists)):\n tmprow.append(listoflists[k][j])\n tmprow.append(dateThours[j])\n tmprow.append(corrected_mag[j])\n tmprow.append(deltas[j])\n tmprow.append(phases[j])\n mags.append(float(corrected_mag[j]))\n if (len(other_mag) != 1) and (len(other_mag) != 0) and ('' not in other_mag):\n tmprow.append(other_mag[j])\n else:\n other_mag.append('')\n tmprow.append(other_mag[j])\n if first_pass == 1:\n r.append(math.log10(float(helio_distances[j])))\n elif first_pass == 0:\n r.append(float(helio_distances[j]))\n tmprow.append(dateJulian[j])\n stats.append(tmprow)\n \n #stats is the \"metalist\" containing all of the information in the function's input arguments.\n if len(stats) != 0:\n\n sorted_stats, mags_sorted_stat, r_sorted_stat = sortbyr(stats,r,mags,0)\n\n for i in range (0, len(sorted_stats)):\n if sorted_stats[i][23].strip() not in obs_list:\n obs_list.append(sorted_stats[i][23].strip())\n \n #Beginning iterating polynomial fits to convergance\n for k in range (0, 21):\n \n # if first_pass == 1:\n # file_name = preorpost +'.'+str(k)+'.'+'out'\n # file_writer = csv.writer(open(file_name, 'w'), delimiter =',')\n \n # if first_pass != 1:\n # file_name = preorpost +'.'+str(k)+'.'+'With_Dropped_Obs'\n # file_writer = csv.writer(open(file_name, 'w'), delimiter =',')\n \n #for the first polynomial fit, all weights are set to 1.0 as we do not have standard deviations yet\n if k == 0:\n #initializing lists needed through routine\n for i in range(0,len(obs_list)):\n sum_resid_per_observer.append(0)\n stdev_per_observer.append(0)\n stdev_resid_per_observer.append(0)\n count_per_observer.append(0)\n mean_resid_per_observer.append(0)\n resid_per_obs.append(0)\n \n A = np.zeros((len(mags_sorted_stat), 6))\n b = np.zeros((len(mags_sorted_stat), 1))\n \n #Inputing A_matrix and b_vector (see Numerical Recipes)\n for i in range (0, len(mags_sorted_stat)):\n for j in range(0,6):\n A[i,j] = (r_sorted_stat[i]**j) / 1.0\n \n b[i,0] = (mags_sorted_stat[i] / 1.0)\n \n U, S, Vh = np.linalg.svd(A, full_matrices = False)\n \n S_matrix = np.zeros((6,6))\n for i in range(0, len(S)):\n S_matrix[i,i] = S[i]\n \n tmp = np.zeros((6,1))\n tmp = np.matmul(np.matmul(np.matrix.transpose(Vh), linalg.inv(S_matrix)) , np.matmul( np.matrix.transpose(U), b))\n\n #new_poly_fit is a vector of the coeffeficients of fifth order fit, p is correpsonding function\n tmp = np.matrix.transpose(tmp)[0] #current polynomial fit\n new_poly_fit = []\n for i in range(len(tmp)-1, -1, -1):\n new_poly_fit.append(tmp[i])\n p = np.poly1d(new_poly_fit)\n \n #print(preorpost, k, new_poly_fit)\n\n #calculating residuals between polynomial fit and data point\n for i in range(0,len(mags_sorted_stat)):\n residuals.append(p(r_sorted_stat[i]) - mags_sorted_stat[i])\n \n #For each observer's data, calculate the mean and stdev of their residuals\n #For each observer mshift = mags_sorted_stat + mean_resid_per_observer\n #For instance, on first iteration: mshift = mph + mean_resid_per_observer\n for o in range (0, len(obs_list)):\n tmp_list = []\n for h in range(0,len(mags_sorted_stat)):\n if sorted_stats[h][23] == obs_list[o]:\n count_per_observer[o] = count_per_observer[o] + 1\n tmp_list.append(residuals[h])\n resid_per_obs.append(residuals[h])\n mean_resid_per_observer[o] = statistics.mean(tmp_list)\n for h in range(0, len(mags_sorted_stat)):\n for o in range (0, len(obs_list)):\n if sorted_stats[h][23] == obs_list[o]:\n mshift.append(mags_sorted_stat[h] + mean_resid_per_observer[o])\n break\n \n # if first_pass ==1:\n # for h in range(0, len(mags_sorted_stat)):\n # file_writer.writerow([str(10**(r_sorted_stat[h])), str(sorted_stats[h][23]), str(mags_sorted_stat[h]),str(mags_sorted_stat[h]), str(0), str(0), str(1)]) \n\n # if first_pass !=1:\n # for h in range(0, len(mags_sorted_stat)):\n # file_writer.writerow([str(10**(r_sorted_stat[h])), str(sorted_stats[h][23]), str(mags_sorted_stat[h]),str(mags_sorted_stat[h]), str(0), str(0), str(1)]) \n \n #For each successive iteration we repeat the same things\n #Except we use stdev_resid_per_observer accordingly in calculating A and b\n if k!=0:\n for o in range (0, len(obs_list)):\n tmp_list = []\n stdev_resid_per_observer[o] = 0\n mean_resid_per_observer[o] = 0\n sum_resid_per_observer[o] = 0\n resid_per_obs[o] = 0\n for h in range(0, len(mags_sorted_stat)):\n if sorted_stats[h][23] == obs_list[o]:\n tmp_list.append(residuals[h])\n resid_per_obs.append(residuals[h])\n stdev_resid_per_observer[o] = statistics.stdev(tmp_list)\n mean_resid_per_observer[o] = statistics.mean(tmp_list)\n \n A = np.zeros((len(mshift), 6))\n b = np.zeros((len(mshift),1))\n \n for i in range (0, len(mshift)):\n for j in range(0,6):\n for o in range (0, len(stdev_resid_per_observer)):\n if sorted_stats[i][23] == obs_list[o]:\n A[i,j] = (r_sorted_stat[i]**j) / stdev_resid_per_observer[o]\n \n for o in range(0,len(stdev_resid_per_observer)):\n if sorted_stats[i][23] == obs_list[o]:\n b[i,0] = (mshift[i] / stdev_resid_per_observer[o])\n \n U, S, Vh = np.linalg.svd(A, full_matrices = False)\n \n S_matrix = np.zeros((6,6))\n for i in range(0, len(S)):\n S_matrix[i,i] = S[i]\n \n tmp = np.zeros((6,1))\n tmp = np.matmul(np.matmul(np.matrix.transpose(Vh), linalg.inv(S_matrix)) , np.matmul( np.matrix.transpose(U), b))\n \n old_poly_fit = new_poly_fit #previous polynomial fit\n tmp = np.matrix.transpose(tmp)[0] #current polynomial fit\n new_poly_fit = []\n for i in range(len(tmp)-1, -1, -1):\n new_poly_fit.append(tmp[i])\n p = np.poly1d(new_poly_fit)\n\n #Compares coefficients between the k_th and k_th - 1 polynomial fits\n converge_test = []\n for i in range(0,len(old_poly_fit)):\n converge_test.append(old_poly_fit[i] - new_poly_fit[i])\n \n for i in range(0,len(mshift)):\n residuals[i] = p(r_sorted_stat[i]) - mshift[i]\n \n for o in range (0, len(obs_list)):\n tmp_list = []\n for h in range(0,len(mshift)):\n if sorted_stats[h][23] == obs_list[o]:\n tmp_list.append(residuals[h])\n resid_per_obs.append(residuals[h])\n #tmp_list.append(mshift[h])\n mean_resid_per_observer[o] = statistics.mean(tmp_list)\n for h in range(0, len(mshift)):\n for o in range (0, len(obs_list)):\n if sorted_stats[h][23] == obs_list[o]:\n # if first_pass !=1:\n # file_writer.writerow([str(10**(r_sorted_stat[h])), str(sorted_stats[h][23]), str(mags_sorted_stat[h]),str(mshift[h]), str(p(r_sorted_stat[h])), str(residuals[h]), str(stdev_resid_per_observer[o])]) \n # if first_pass ==1:\n # file_writer.writerow([str(10**(r_sorted_stat[h])), str(sorted_stats[h][23]), str(mags_sorted_stat[h]),str(mshift[h]), str(p(r_sorted_stat[h])), str(residuals[h]), str(stdev_resid_per_observer[o])]) \n mshift[h] = mshift[h] + mean_resid_per_observer[o]\n break\n \n #print(preorpost, k, new_poly_fit)\n \n #for h in range(0, len(mags_sorted_stat)):\n # file_writer.writerow([str(r_sorted_stat[h]), str(sorted_stats[h][23]), str(mags_sorted_stat[h]),str(mshift[h]), str(p(r_sorted_stat[h]), str(mshift[h]-p(r_sorted_stat[h]), str(1)]) \n\n \n #if each of the coefficients are within 0.0001 then we say the polynomial has converged and are done calculating mshift\n if (abs(converge_test[0]) < tolerance) and (abs(converge_test[1])< tolerance) and (abs(converge_test[2])< tolerance) and (abs(converge_test[3])< tolerance) and (abs(converge_test[4])< tolerance) and (abs(converge_test[5])< tolerance):\n #print(preorpost,': The polynomail fit converged to within tolerance of ', tolerance, ' after ', k, ' iterations')\n #print('The final poly_fit is ', new_poly_fit)\n break\n \n \n #for i in range(0,len(sorted_stats)):\n # print(i)\n # print(sorted_stats[i])\n \n if len(mshift) == 0 :\n for i in range (0,30):\n sorted_stats.append(0)\n\n return_this_other_mag=[]\n \n if (sorted_stats[0] == 0) and (sorted_stats[1] ==0) and (sorted_stats[3]==0) and (sorted_stats[4]==0):\n return_this_other_mag.append(0)\n else:\n for i in range(0,len(sorted_stats)):\n return_this_other_mag.append(sorted_stats[i][28])\n \n return mshift, obs_list, sorted_stats, r_sorted_stat, new_poly_fit, original_poly_fit, stdev_resid_per_observer, mean_resid_per_observer, count_per_observer, residuals, return_this_other_mag, mags_sorted_stat, resid_per_obs, condemned_list #return_this_other_mag used to be sorted_stats[28]\n\n#Assigns headers for output stats files\ndef add_headers_stats(inputlist, inputpreorpost,other):\n inputlist.insert(0, ['col 1-3 : short period comet designation'])\n inputlist[0].append('col 4-9 : Standard comet designation')\n inputlist[0].append('col 10 : multiple nuclei present?')\n inputlist[0].append('col 12-15 : year observed')\n inputlist[0].append('col 17-18 : month observed')\n inputlist[0].append('col 20-24')\n inputlist[0].append('col 26 : special note / extinction note')\n inputlist[0].append('col 27 : Magnitude collection method')\n inputlist[0].append('col 28-32 : visual magnitude estimate')\n inputlist[0].append('col 33 : poor conditions?')\n inputlist[0].append('col 34 - 35 : reference catalog')\n inputlist[0].append('col 36-40 : instrument aperture in centimeters')\n inputlist[0].append('col 41 : instrument type')\n inputlist[0].append('col 42 - 43 : focal ratio')\n inputlist[0].append('col 44-47 : magnification used')\n inputlist[0].append('col 49 : error estimate for coma diameter')\n inputlist[0].append('col 50 - 54 : coma diameter in arcminutes')\n inputlist[0].append('col 55 : special note on central condensation of comet')\n inputlist[0].append('col : 56 -57 : degree of condensation (note / means estimate)')\n inputlist[0].append('col 59 - 64 : error of tail approximation and tail approximation')\n inputlist[0].append('col 65 - 67 : direction tail is pointed')\n inputlist[0].append('col 69-74 : ICQ reference publication')\n inputlist[0].append('col 75 : second special note / extinction note ')\n inputlist[0].append('col 76-80 : observer name')\n inputlist[0].append('Date YYYY-MM-DDTHH:MM:SS')\n inputlist[0].append(inputpreorpost)\n inputlist[0].append('Delta (au)')\n inputlist[0].append('Phase Angle')\n inputlist[0].append(other)\n inputlist[0].append('Julian Date')\n \nclass MultipleOffsetLocator(tickers.MultipleLocator):\n\n def __init__(self, base=1.0, offset=0.):\n self._base = tickers.Base(base)\n self._offset = offset\n\n def tick_values(self, vmin, vmax):\n if vmax < vmin:\n vmin, vmax = vmax, vmin\n vmin = self._base.ge(vmin)\n base = self._base.get_base()\n n = (vmax - vmin + 0.001 * base) // base\n locs = self._offset + vmin - base + np.arange(n + 3) * base\n return self.raise_if_exceeds(locs)\n \ndef main():\n global metalist\n global list_of_reasons_removed\n global removed_metalist\n global reasonForDelete\n global to_report_r\n global heliocentric_corrected_magnitudes\n global phase_corrected_magnitudes\n global dates_pds_format\n global to_report_delta\n global to_report_phase\n global to_report_Julian\n global dates_pds_format\n global last_mag_calculated_sans_condemned_pre\n global last_mag_calculated_sans_condemned_post\n last_mag_calculated_sans_condemned_pre = []\n last_mag_calculated_sans_condemned_post =[]\n dates_pds_format = []\n #Instantiates each element of metalist (i.e., each column in the input data).\n metalist = []\n shortperapparition = [] #metalist[0]\n designation = [] #metalist[1]\n splitnuc = [] #metalist[2]\n yearobs = [] #metalist[3]\n monthobs = [] #metalist[4]\n dayobs = [] #metalist[5]\n speicalnotes = [] #metalist[6]\n magmethod = [] #metalist[7]\n mag = [] #metalist[8]\n poorconditions = [] #metalist[9]\n referencecat = [] #metalist[10]\n instaperture = [] #metalist[11]\n insttype = [] #metalist[12]\n focalratio = [] #metalist[13]\n magnification = [] #metalist[14]\n comadiamestimate = [] #metalist[15]\n comadiameter = [] #metalist[16]\n centralcondensation = [] #metalist[17]\n degreeofcondensation = [] #metalist[18]\n taillength = [] #metalist[19]\n positionangleoftail = [] #metalist[20]\n ICQPublication = [] #metalist[21]\n specialnotestwo = [] #metalist[22]\n obs = [] #metalist[23]\n removed = []\n removed_reason = []\n reasonForDelete = 0\n\n list_of_reasons_removed = [\"Two entries on the same date by same observer\", \"No magnitude reported\", \"Used reverse binocular observing method\", \"Poor Weather Reported\", \"Used a tier 3 or 4 Source Catalog\", \"Used a telescope under 5.5 magnitude\", \"Used binoculars under 3.3 magnitude\", \"Did not use a magnitude method reported by Green (i.e. column 27 not being S, B, M, I, or E), prioritizing S then M\", \"Bad Extinction Correction used\", \"Observer used SC Catalog for object dimmer than 8.1\"]\n\n #Reads in the 80 column format from ICQ or COBS data\n for line in open(input_file, encoding='utf8').readlines():\n shortperapparition.append(line[0:3].strip(' '))\n designation.append(line[3:9].strip(' '))\n splitnuc.append(line[9].strip(' '))\n yearobs.append(line[11:15].strip(' '))\n monthobs.append(line[16:18].strip(' '))\n dayobs.append(line[19:24].strip(' '))\n speicalnotes.append(line[25].strip(' '))\n magmethod.append(line[26].strip(' '))\n mag.append(line[28:32].strip(' '))\n poorconditions.append(line[32].strip(' '))\n referencecat.append(line[33:35].strip(' '))\n instaperture.append(line[35:40].strip(' '))\n insttype.append(line[40].strip(' '))\n focalratio.append(line[41:43].strip(' '))\n magnification.append(line[43:47].strip(' '))\n comadiamestimate.append(line[48].strip(' '))\n comadiameter.append(line[49:54].strip(' '))\n centralcondensation.append(line[54].strip(' '))\n degreeofcondensation.append(line[55:57].strip(' '))\n taillength.append(line[58:63].strip(' '))\n positionangleoftail.append(line[64:67].strip(' '))\n ICQPublication.append(line[68:74].strip(' '))\n specialnotestwo.append(line[74].strip(' '))\n obs.append(line[75:80].strip(' '))\n\n #Places each of the lists into one list for organization\n metalist = [shortperapparition,designation,splitnuc,yearobs,monthobs,dayobs,speicalnotes,\n magmethod,mag,poorconditions,referencecat,instaperture,insttype,focalratio,magnification,\n comadiamestimate,comadiameter,centralcondensation,degreeofcondensation,\n taillength,positionangleoftail,ICQPublication,specialnotestwo,obs]\n\n removed_metalist = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]\n\n #Total number of initial datapoints\n print('initial number of points ', len(metalist[0]))\n \n #Removes data from metalist based on specific criteria\n numdeltefornomagreported =0\n reasonForDelete = 1\n nomagreported(numdeltefornomagreported)\n\n numdeletedforreversebinocmethod =0\n reasonForDelete = 2\n reversebinocular(numdeletedforreversebinocmethod)\n\n numdeletedforpoorweather = 0\n reasonForDelete = 3\n poorweather(numdeletedforpoorweather)\n \n numdeletedforbadextinctioncorrection = 0\n reasonForDelete = 8\n badExtinctionCorrection(numdeletedforbadextinctioncorrection)\n\n numberremovedfortelescopeunder5_4 = 0\n numberremovedforbinocularunder1_4 = 0\n checkTelescopesandBinocMethods(numberremovedfortelescopeunder5_4, numberremovedforbinocularunder1_4)\n\n numberremovedfornotspecifiedmagmethod = 0\n if CCD_Bool == 1:\n reasonForDelete = 7\n removeForMagMethod(numberremovedfornotspecifiedmagmethod)\n\n numberremovedforSCcatalog = 0\n if CCD_Bool == 1:\n reasonForDelete = 9\n checkSCcatalog(numberremovedforSCcatalog)\n\n numdelforduplicatedate = 0\n reasonForDelete = 0\n deleteForDuplicatedDates(numdelforduplicatedate)\n\n #How many points are left in our data after sorting out 'rejected' points\n print(\"final remaining points \" + str(len(metalist[2]))) \n\n #If you are not doing any further corrections to data then output \"kept\" points as is\n if \"--heliocentric\" not in sys.argv and '--phase' not in sys.argv:\n add_headers(metalist)\n file_writer = csv.writer(open(ouput_file_kept_points, 'w'), delimiter =',')\n for k in range (0,len(metalist[2])):\n file_writer.writerow([metalist[0][k],metalist[1][k],metalist[2][k],metalist[3][k],metalist[4][k],metalist[5][k],metalist[6][k],metalist[7][k],metalist[8][k],metalist[9][k],metalist[10][k],metalist[11][k],metalist[12][k],metalist[13][k],metalist[14][k],metalist[15][k],metalist[16][k],metalist[17][k],metalist[18][k],metalist[19][k],metalist[20][k],metalist[21][k],metalist[22][k],metalist[23][k]])\n\n #Outputs removed data points in separate csv along with reason it was deleted.\n add_headers(removed_metalist)\n removed_metalist[24].insert(0, 'Point removed')\n removed_metalist[25].insert(0, 'Reason Point was Removed')\n \n file_writer = csv.writer(open(output_file_rejected_points, 'w'), delimiter =',')\n for k in range (0,len(removed_metalist[2])):\n file_writer.writerow([removed_metalist[0][k],removed_metalist[1][k],removed_metalist[2][k],removed_metalist[3][k],removed_metalist[4][k],removed_metalist[5][k],removed_metalist[6][k],removed_metalist[7][k],removed_metalist[8][k],removed_metalist[9][k],removed_metalist[10][k],removed_metalist[11][k],removed_metalist[12][k],removed_metalist[13][k],removed_metalist[14][k],removed_metalist[15][k],removed_metalist[16][k],removed_metalist[17][k],removed_metalist[18][k],removed_metalist[19][k],removed_metalist[20][k],removed_metalist[21][k],removed_metalist[22][k],removed_metalist[23][k], removed_metalist[24][k], removed_metalist[25][k]]) \n \n #Optional command line argument --heliocentric to perform just heliocentric corrections to 'kept' data\n if \"--heliocentric\" in sys.argv and '--phase' not in sys.argv:\n print('Performing Heliocentric Corrections to the Data')\n queryJPL()\n heliocentric_corrected_magnitudes = []\n to_report_delta = []\n to_report_r = []\n to_report_phase = []\n to_report_Julian = []\n #queryJPL will report an r, delta, and phase angle at every 30 minute increment in the ephemerides\n #It will also take each date/time of an observation in the dataset and convert it to YYYY:MM:DD HH:MM:SS format.\n #The next few lines will compare the date/time of each point in the observation and find the nearest 30 minute increment in the ephemerides\n #It will then take the delta at that nearest increment and use it to apply a heliocentric correction to the magnitude,\n #and repeat this for each point in the data.\n for i in range (0, len(date_compare_to_JPL)):\n for j in range(0, len(OBJDates)):\n if (date_compare_to_JPL[i][0:4] == OBJDates[j][0:4]) and (date_compare_to_JPL[i][5:7] == OBJDates[j][5:7]) and (date_compare_to_JPL[i][8:10] == OBJDates[j][8:10]) and (date_compare_to_JPL[i][11:13] == OBJDates[j][11:13]) and ((JPL_Time_Increment*round(float(date_compare_to_JPL[i][14:16])/JPL_Time_Increment))%60 == float(OBJDates[j][14:16])):\n heliocentric_corrected_magnitudes.append(str(float(metalist[8][i]) - 5 * float(math.log10(OBJDelta[j]))))\n to_report_r.append(OBJr[j])\n to_report_delta.append(OBJDelta[j])\n to_report_phase.append(OBJPhase[j])\n to_report_Julian.append(OBJJulianDate[j])\n continue\n for k in range(0,len(date_compare_to_JPL)):\n dates_pds_format.append(date_compare_to_JPL[k].replace(\" \",\"T\"))\n \n #writes out final heliocentric corrected data.\n add_headers(metalist)\n to_report_r.insert(0, 'Heliocentric Distance (au)')\n dates_pds_format.insert(0, 'Dates YYYY:MM:DDTHH:MM:SS')\n to_report_delta.insert(0, 'Delta (au)')\n to_report_phase.insert(0, 'Phase angle')\n to_report_Julian.insert(0, 'Julian Date')\n heliocentric_corrected_magnitudes.insert(0, 'magnitdues with only geocentric correction (mhelio)')\n file_writer = csv.writer(open(ouput_file_kept_points, 'w'), delimiter =',')\n for k in range (0,len(metalist[2])):\n file_writer.writerow([metalist[0][k],metalist[1][k],metalist[2][k],metalist[3][k],metalist[4][k],metalist[5][k],metalist[6][k],metalist[7][k],metalist[8][k],metalist[9][k],metalist[10][k],metalist[11][k],metalist[12][k],metalist[13][k],metalist[14][k],metalist[15][k],metalist[16][k],metalist[17][k],metalist[18][k],metalist[19][k],metalist[20][k],metalist[21][k],metalist[22][k],metalist[23][k], to_report_r[k], heliocentric_corrected_magnitudes[k], dates_pds_format[k], to_report_delta[k], to_report_phase[k], to_report_Julian[k]])\n\n #Optional command line argument --phase to perform just phase corrections to 'kept' data\n if '--phase' in sys.argv and '--heliocentric' not in sys.argv:\n print('Performing Phase Angle Corrections to the Data')\n queryJPL()\n phase_corrected_magnitudes = []\n to_report_delta = []\n to_report_r = []\n to_report_phase = []\n to_report_Julian = []\n #queryJPL will report an r, delta, and phase angle at every 30 minute increment in the ephemerides\n #It will also take each date/time of an observation in the dataset and convert it to YYYY:MM:DD HH:MM:SS format.\n #The next few lines will compare the date/time of each point in the observation and find the nearest 30 minute increment in the ephemerides\n #It will also read in Schleicher's composite phse function which has inputs at every whole number degree.\n #It will then take the phase at that nearest increment, round it to the nearest whole number, compare that to Shcleicher's data to get the\n #composite phase function normalized to 0 degrees, and use that to calculate the phase corrected magnitudes.\n #This is repeated for each point in the data.\n with open('Schleicher_Composite_Phase_Function.txt') as f:\n lines1 = f.readlines()\n phase_angles = [line.split()[0] for line in lines1]\n deg_0_normalized = [float(line.split()[1]) for line in lines1]\n for i in range(0, len(date_compare_to_JPL)):\n for j in range(0, len(OBJPhase)):\n if (date_compare_to_JPL[i][0:4] == OBJDates[j][0:4]) and (date_compare_to_JPL[i][5:7] == OBJDates[j][5:7]) and (date_compare_to_JPL[i][8:10] == OBJDates[j][8:10]) and (date_compare_to_JPL[i][11:13] == OBJDates[j][11:13]) and ((JPL_Time_Increment*round(float(date_compare_to_JPL[i][14:16])/JPL_Time_Increment))%60 == float(OBJDates[j][14:16])):\n to_report_r.append(OBJr[j])\n to_report_delta.append(OBJDelta[j])\n to_report_phase.append(OBJPhase[j])\n to_report_Julian.append(OBJJulianDate[j])\n for l in range (0, len(phase_angles)):\n if (round(float(OBJPhase[j])) == float(phase_angles[l])):\n phase_corrected_magnitudes.append(str(float(metalist[8][i]) + 2.5 * float(math.log10(deg_0_normalized[l]))))\n continue\n \n for k in range(0,len(date_compare_to_JPL)):\n dates_pds_format.append(date_compare_to_JPL[k].replace(\" \",\"T\"))\n \n #writes out final phase corrected data\n add_headers(metalist)\n to_report_r.insert(0, 'Heliocentric Distance (au)')\n dates_pds_format.insert(0, 'Dates YYYY:MM:DDTHH:MM:SS')\n to_report_delta.insert(0, 'Delta (au)')\n to_report_phase.insert(0, 'Phase angle')\n to_report_Julian.insert(0, 'Julian Date')\n phase_corrected_magnitudes.insert(0, 'magnitudes with only phase correction (mph*)')\n file_writer = csv.writer(open(ouput_file_kept_points, 'w'), delimiter =',')\n for k in range (0,len(metalist[2])):\n file_writer.writerow([metalist[0][k],metalist[1][k],metalist[2][k],metalist[3][k],metalist[4][k],metalist[5][k],metalist[6][k],metalist[7][k],metalist[8][k],metalist[9][k],metalist[10][k],metalist[11][k],metalist[12][k],metalist[13][k],metalist[14][k],metalist[15][k],metalist[16][k],metalist[17][k],metalist[18][k],metalist[19][k],metalist[20][k],metalist[21][k],metalist[22][k],metalist[23][k], to_report_r[k], phase_corrected_magnitudes[k], dates_pds_format[k], to_report_delta[k], to_report_phase[k], to_report_Julian[k]])\n \n #Performs a heliocentric correction to the raw data and then a phase correction to the heliocentric corrected data\n #See the above two blocks to understand how the heliocentric and phase corrections work\n if '--heliocentric' in sys.argv and '--phase' in sys.argv:\n print('Performing heliocentric and Phase Angle Corrections to the Data')\n queryJPL()\n heliocentric_corrected_magnitudes = []\n phase_corrected_magnitudes = []\n to_report_r = []\n to_report_delta = []\n to_report_phase = []\n to_report_Julian = []\n with open('Schleicher_Composite_Phase_Function.txt') as f:\n lines1 = f.readlines()\n phase_angles = [line.split()[0] for line in lines1]\n deg_0_normalized = [float(line.split()[1]) for line in lines1]\n for i in range (0, len(date_compare_to_JPL)):\n for j in range(0, len(OBJDates)):\n if (date_compare_to_JPL[i][0:4] == OBJDates[j][0:4]) and (date_compare_to_JPL[i][5:7] == OBJDates[j][5:7]) and (date_compare_to_JPL[i][8:10] == OBJDates[j][8:10]) and (date_compare_to_JPL[i][11:13] == OBJDates[j][11:13]) and ((JPL_Time_Increment*round(float(date_compare_to_JPL[i][14:16])/JPL_Time_Increment))%60 == float(OBJDates[j][14:16])):\n to_report_r.append(OBJr[j])\n to_report_delta.append(OBJDelta[j])\n to_report_phase.append(OBJPhase[j])\n to_report_Julian.append(OBJJulianDate[j])\n heliocentric_corrected_magnitudes.append(str(float(metalist[8][i]) - 5. * float(math.log10(OBJDelta[j]))))\n for l in range (0, len(phase_angles)):\n if (round(float(OBJPhase[j])) == float(phase_angles[l])):\n phase_corrected_magnitudes.append(str(float(heliocentric_corrected_magnitudes[i]) + 2.5 * float(math.log10(deg_0_normalized[l]))))\n\n for k in range(0,len(date_compare_to_JPL)):\n dates_pds_format.append(date_compare_to_JPL[k].replace(\" \",\"T\"))\n #writes out the heliocentric and phase corrected magnitudes\n add_headers(metalist)\n to_report_r.insert(0, 'Heliocentric Distance (au)')\n heliocentric_corrected_magnitudes.insert(0, 'heliocentric corrected magnitudes (mhelio)')\n phase_corrected_magnitudes.insert(0, 'magnitudes with heliocentric and phase corrections applied (mph)')\n dates_pds_format.insert(0, 'Dates YYYY:MM:DDTHH:MM:SS')\n to_report_delta.insert(0, 'Delta (au)')\n to_report_phase.insert(0, 'Phase angle')\n to_report_Julian.insert(0, 'Julian Date')\n file_writer = csv.writer(open(ouput_file_kept_points, 'w'), delimiter =',')\n for k in range (0,len(metalist[2])):\n file_writer.writerow([metalist[0][k],metalist[1][k],metalist[2][k],metalist[3][k],metalist[4][k],metalist[5][k],metalist[6][k],metalist[7][k],metalist[8][k],metalist[9][k],metalist[10][k],metalist[11][k],metalist[12][k],metalist[13][k],metalist[14][k],metalist[15][k],metalist[16][k],metalist[17][k],metalist[18][k],metalist[19][k],metalist[20][k],metalist[21][k],metalist[22][k],metalist[23][k], to_report_r[k], heliocentric_corrected_magnitudes[k], phase_corrected_magnitudes[k], dates_pds_format[k], to_report_delta[k], to_report_phase[k], to_report_Julian[k]])\n \n #Performs all statistical corrections outlined in 'Statistics_method_appendix.txt' in GitHub repository\n #All TRY-EXCEPT blocks are case scenarios depending on whether the user calculated mph, mehlio, or both.\n if '--stats' in sys.argv:\n last_mag_calculated = []\n pre_condemned_obs = []\n post_condemned_obs = []\n other_mag = []\n magsfound = 0 #checks what was last magnitude calculated (either mph or mhelio depending on if user calculated one, neither, or both)\n first_pass = 1\n other = ''\n try:\n if magsfound == 0:\n last_mag_calculated = phase_corrected_magnitudes\n print('Will perform statistical corrections on Phase Corrected Magnitudes')\n magsfound = 'mph'\n try:\n other = 'mhelio'\n other_mag = heliocentric_corrected_magnitudes\n try:\n float(other_mag[0])\n except:\n del other_mag[0]\n except:\n pass\n except:\n print('Searching for heliocentric corrected magnitudes...')\n \n try:\n if magsfound == 0:\n last_mag_calculated = heliocentric_corrected_magnitudes\n print('Will perform statistical corrections on Heliocentric Corrected Magnitudes')\n magsfound = 'mhelio'\n try:\n other = 'mph'\n other_mag = phase_corrected_magnitudes\n try:\n float(other_mag[0])\n except:\n del other_mag[0]\n except:\n pass\n except:\n print('Searching for raw magnitudes...')\n \n if magsfound == 0:\n print('Please run either --heliocentric or --phase or both to perform statistical corrections')\n \n #deleting headers now so we dont have to worry about them in the stats function\n del last_mag_calculated[0]\n del to_report_r[0]\n del to_report_delta[0]\n del to_report_phase[0]\n del to_report_Julian[0]\n del dates_pds_format[0]\n deletearow(0)\n \n #print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') \n \n \n peridate = time.strptime(perihelion, \"%Y/%m/%d\")\n tmp_obs_pre = []\n count_pre = []\n tmp_obs_post = []\n count_post = []\n \n for j in range(0,len(metalist[0])):\n check_date = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n if newdate2 <= peridate:\n if metalist[23][j] not in tmp_obs_pre:\n tmp_obs_pre.append(metalist[23][j].strip())\n count_pre.append(0)\n if newdate2 > peridate:\n if metalist[23][j] not in tmp_obs_post:\n tmp_obs_post.append(metalist[23][j].strip())\n count_post.append(0)\n \n for j in range(0,len(metalist[0])):\n check_date = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n for o in range(0,len(tmp_obs_pre)):\n if (metalist[23][j] == tmp_obs_pre[o]) and (newdate2 < peridate):\n count_pre[o] = count_pre[o] + 1\n continue\n for j in range(0,len(metalist[0])):\n check_date = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate2 = time.strptime(check_date, \"%Y/%m/%d\")\n for o in range(0,len(tmp_obs_post)):\n if(metalist[23][j] == tmp_obs_post[o]) and (newdate2 >= peridate):\n count_post[o] = count_post[o] + 1\n for o in range(0, len(count_pre)):\n if count_pre[o] < 20:\n pre_condemned_obs.append(tmp_obs_pre[o])\n for o in range(0,len(count_post)):\n if count_post[o] < 20:\n post_condemned_obs.append(tmp_obs_post[o])\n\n # ind_obs = []\n # for q in range(0,len(metalist[23])):\n # if metalist[23][q] not in ind_obs:\n # ind_obs.append(metalist[23][q])\n #print(post_condemned_obs, len(post_condemned_obs))\n #print(pre_condemned_obs, len(pre_condemned_obs))\n #print(tmp_obs_post,len(tmp_obs_post))\n #print(tmp_obs_pre,len(tmp_obs_pre))\n \n #Initializes and defines pre-perihelion statistical outputs\n pre_mshift = [] \n pre_r = [] \n pre_meta = [] \n pre_final_polyfit = [] \n pre_final_stdevs = [] \n pre_last_mag_correction = [] \n pre_original_polyfit = [] \n pre_obs_list = [] \n pre_final_mean_resid = [] \n pre_count_per_obs = []\n pre_other_mag = []\n pre_last_mag_calculated = []\n pre_mshift, pre_obs_list, pre_meta, pre_r, pre_final_polyfit, pre_original_polyfit, pre_final_stdevs, pre_final_mean_resid, pre_count_per_obs, pre_last_mag_correction, pre_other_mag, pre_last_mag_calculated, pre_resid_per_obs, pre_condemned_obs= stats_shifts('pre', metalist, last_mag_calculated, dates_pds_format, to_report_delta, to_report_phase, to_report_r,pre_condemned_obs, other_mag, first_pass, to_report_Julian)\n #print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')\n \n #Initializes and defines post-perihelion statistical outputs\n post_mshift = []\n post_r = []\n post_meta = []\n post_final_polyfit = []\n post_final_stdevs = []\n post_last_mag_correction = []\n post_original_poly_fit = []\n post_final_mean_resid = []\n post_obs_list = []\n post_count_per_obs = []\n post_other_mag = []\n post_last_mag_calculated =[]\n post_mshift, post_obs_list, post_meta, post_r, post_final_polyfit, post_original_polyfit, post_final_stdevs, post_final_mean_resid, post_count_per_obs, post_last_mag_correction, post_other_mag, post_last_mag_calculated, post_resid_per_obs, post_condemned_obs= stats_shifts('post', metalist, last_mag_calculated, dates_pds_format, to_report_delta, to_report_phase, to_report_r,post_condemned_obs, other_mag,first_pass, to_report_Julian) \n \n #sets this to 0 so that if we need to run stats_shifts again then we wont accidentally log the r-values again\n first_pass = 0\n \n #Block begins to perform stationary t-test and two tail probability test. This block is for pre-perihelion t-test\n #terminate iterations = 0 means at least one observer failed the t-test, so we must reconverge a polynomial fit (i.e., run stats_shifts) with their data removed\n #number_t_pre keeps track of how many times we have at least one observer fail a t-test on a given iteration\n terminate_iterations = 0\n number_t_pre = 0\n while terminate_iterations == 0:\n drop_observers = 0\n thismagsfound = magsfound\n p_func = np.poly1d(pre_final_polyfit)\n for o in range (0, len(pre_obs_list)):\n N1 = []\n N2 = []\n mean_1 = 0\n mean_2 = 0\n sum_1 = 0\n sum_2 = 0\n for i in range (0, len(pre_r)):\n if pre_meta[i][23] == pre_obs_list[o]:\n if len(N1) < math.floor(pre_count_per_obs[o] /2):\n N1.append(p_func(pre_r[i]) - pre_mshift[i])\n else:\n N2.append(p_func(pre_r[i]) - pre_mshift[i])\n \n #returns t-statistic and corresponding p-statistics\n t2, p2 = stats.ttest_ind(N1, N2, equal_var = False)\n #print(pre_obs_list[o], ' t = ',t2,' p = ', p2)\n #Adds observers who failed p-test to 'condemned list' to be avoided on future polynomial fit convergeances.\n if p2 < 0.05:\n drop_observers = 1\n pre_condemned_obs.append(pre_obs_list[o].strip())\n #If we did deleted one observer, prepare their data to be in write format for stats_shifts and then rerun stats_shifts\n #i.e., one observer failed the stationary test so we reconverge the polynomial fit / mshift values without the bias from their data present\n if drop_observers ==1:\n tmp = []\n last_mag_calculated_sans_condemned_pre = []\n for z in range(0,len(pre_last_mag_calculated)):\n last_mag_calculated_sans_condemned_pre.append(pre_last_mag_calculated[z])\n #print(len(last_mag_calculated_sans_condemned_pre))\n for h in range (len(pre_last_mag_calculated)-1, -1, -1):\n if pre_meta[h][23] in pre_condemned_obs:\n del pre_last_mag_calculated[h]\n for i in range(0,len(pre_meta[1])):\n for j in range(0,len(pre_meta)):\n if j == 0:\n tmp.append([])\n tmp[i].append(pre_meta[j][i])\n tmp_dates = tmp[24]\n tmp_deltas = tmp[26]\n tmp_phase = tmp[27]\n tmp_other_mags = tmp[28]\n tmp_julian = tmp[29]\n del tmp[29]\n del tmp[28]\n del tmp[27]\n del tmp[26]\n del tmp[25]\n del tmp[24]\n number_t_pre = number_t_pre +1\n #print('###########################################################################################')\n #print('PRE: THE FOLLOWING OBSERVERS WERE REJECTED BY T-TEST: ')\n #print(pre_condemned_obs)\n #print('DROPPING THESE OBSERVERS AND REPEATING THE ITERATIVE PROCESS')\n #print('###########################################################################################')\n \n if(len(pre_condemned_obs) == len(tmp_obs_pre)):\n kicked_all_obs_pre = 1\n if(len(post_condemned_obs) == len(tmp_obs_post)):\n kicked_all_obs_post = 1\n \n pre_mshift, pre_obs_list, pre_meta, pre_r, pre_final_polyfit, pre_original_polyfit, pre_final_stdevs, pre_final_mean_resid, pre_count_per_obs, pre_last_mag_correction,pre_other_mag, tmp, pre_resid_per_obs, pre_condemned_obs = stats_shifts('pre', tmp, last_mag_calculated_sans_condemned_pre, tmp_dates, tmp_deltas, tmp_phase, pre_r, pre_condemned_obs, tmp_other_mags, first_pass, tmp_julian)\n else:\n terminate_iterations = 1\n \n #Repeats the above t- and p-tests for Post-perihelion data\n terminate_iterations = 0\n number_t_post = 0\n #print('###########################################################################################')\n while terminate_iterations == 0:\n drop_observers = 0\n thismagsfound = magsfound\n p_func = np.poly1d(post_final_polyfit)\n for o in range (0, len(post_obs_list)):\n N1 = []\n N2 = []\n mean_1 = 0\n mean_2 = 0\n sum_1 = 0\n sum_2 = 0\n for i in range (0, len(post_r)):\n if post_meta[i][23] == post_obs_list[o]:\n if len(N1) < math.floor(post_count_per_obs[o] /2):\n N1.append(p_func(post_r[i]) - post_mshift[i])\n else:\n N2.append(p_func(post_r[i]) - post_mshift[i])\n \n t2, p2 = stats.ttest_ind(N1, N2, equal_var = False)\n #print(post_obs_list[o], ' t = ', t2,' p = ', p2) #t1, 2*p1)\n if p2 < 0.05:\n drop_observers = 1\n post_condemned_obs.append(post_obs_list[o].strip())\n if drop_observers ==1:\n last_mag_calculated_sans_condemned_post = []\n for z in range(0,len(post_last_mag_calculated)):\n last_mag_calculated_sans_condemned_post.append(post_last_mag_calculated[z])\n #print(len(last_mag_calculated_sans_condemned_post))\n for h in range (len(post_last_mag_calculated)-1, -1, -1):\n if post_meta[h][23] in post_condemned_obs:\n del post_last_mag_calculated[h]\n tmp = []\n for i in range(0,len(post_meta[1])):\n for j in range(0,len(post_meta)):\n if j == 0:\n tmp.append([])\n tmp[i].append(post_meta[j][i])\n tmp_dates = tmp[24]\n tmp_deltas = tmp[26]\n tmp_phase = tmp[27]\n tmp_other_mags = tmp[28]\n tmp_julian = tmp[29]\n del tmp[29]\n del tmp[28]\n del tmp[27]\n del tmp[26]\n del tmp[25]\n del tmp[24]\n last_mag_calculated_sans_condemned = []\n #print('#################################################################################')\n #print('POST: THE FOLLOWING OBSERVERS WERE REJECTED BY T-TEST: ')\n #print(post_condemned_obs)\n #print('DROPPING THESE OBSERVERS AND REPEATING THE ITERATIVE PROCESS FOR POSTPERIHELION')\n #print('#################################################################################')\n \n if(len(pre_condemned_obs) == len(tmp_obs_pre)):\n kicked_all_obs_pre = 1\n if(len(post_condemned_obs) == len(tmp_obs_post)):\n kicked_all_obs_post = 1\n post_mshift, post_obs_list, post_meta, post_r, post_final_polyfit, post_original_polyfit, post_final_stdevs, post_final_mean_resid, post_count_per_obs, post_last_mag_correction,post_other_mag, tmp, post_resid_per_obs, post_condemned_obs = stats_shifts('post', tmp, last_mag_calculated_sans_condemned_post, tmp_dates, tmp_deltas, tmp_phase, post_r, post_condemned_obs, tmp_other_mags, first_pass, tmp_julian)\n else:\n terminate_iterations = 1\n \n \n #print(number_t_pre, 'pre t tests', number_t_post, 'post t tests')\n #print('PRE: observers who failed t-test and were removed: ', pre_condemned_obs)\n #print('POST: observers who failed t-test and were removed: ', post_condemned_obs) \n \n #Adds headers and writes out pre-perihelion data to file 'pre-stats.csv'\n if (len(pre_meta) != 0) and (pre_meta[0] != 0):\n magsfound = 'mshift (no dropped observers)'\n add_headers_stats(pre_meta, magsfound,other)\n if type(pre_r) != list:\n pre_r = pre_r.tolist()\n pre_r.insert(0, 'r (au)')\n pre_last_mag_calculated.insert(0, thismagsfound)\n pre_last_mag_correction.insert(0, 'residual of mshift from polyfit')\n pre_meta[0][28] = other + ' (BLANK if you did not ask to calculate this value)'\n pre_mshift.insert(0, 'mshift with dropped observers')\n file_writer = csv.writer(open('pre-stats.csv', 'w'), delimiter =',')\n for m in range (1, len(pre_r)):\n pre_r[m] = str((-1.0)*10**(float(pre_r[m])))\n for k in range (0,len(pre_meta)):\n file_writer.writerow([pre_meta[k][0],pre_meta[k][1],pre_meta[k][2],pre_meta[k][3],pre_meta[k][4],pre_meta[k][5],pre_meta[k][6],pre_meta[k][7],pre_meta[k][8],pre_meta[k][9],pre_meta[k][10],pre_meta[k][11],pre_meta[k][12],pre_meta[k][13],pre_meta[k][14],pre_meta[k][15],pre_meta[k][16],pre_meta[k][17],pre_meta[k][18],pre_meta[k][19],pre_meta[k][20],pre_meta[k][21],pre_meta[k][22],pre_meta[k][23], pre_meta[k][24],pre_r[k],pre_meta[k][28], pre_last_mag_calculated[k], pre_meta[k][25], pre_mshift[k], pre_meta[k][26], pre_meta[k][27], pre_last_mag_correction[k], pre_meta[k][29]]) \n else:\n print('No preperihelion data to perform statistics on')\n #print('##########################################################################################')\n\n #Adds headers and writes out post-perihelion data to file 'post-stats.csv'\n if (len(post_meta) != 0) and (post_meta[0] != 0):\n magsfound = 'mshift (no dropped observers)'\n add_headers_stats(post_meta, magsfound,other)\n if type(post_r) != list:\n post_r = post_r.tolist()\n post_r.insert(0, 'r (au)')\n post_last_mag_calculated.insert(0, thismagsfound)\n post_last_mag_correction.insert(0, 'residual of mshift from polyfit')\n post_meta[0][28] = other + ' (BLANK if you did not ask to calculate this value)'\n post_mshift.insert(0, 'mshift with dropped observers')\n file_writer = csv.writer(open('post-stats.csv', 'w'), delimiter =',')\n for m in range (1, len(post_r)):\n post_r[m] = str(10**(float(post_r[m])))\n for k in range (0,len(post_meta)):\n file_writer.writerow([post_meta[k][0],post_meta[k][1],post_meta[k][2],post_meta[k][3],post_meta[k][4],post_meta[k][5],post_meta[k][6],post_meta[k][7],post_meta[k][8],post_meta[k][9],post_meta[k][10],post_meta[k][11],post_meta[k][12],post_meta[k][13],post_meta[k][14],post_meta[k][15],post_meta[k][16],post_meta[k][17],post_meta[k][18],post_meta[k][19],post_meta[k][20],post_meta[k][21],post_meta[k][22],post_meta[k][23], post_meta[k][24],post_r[k],post_meta[k][28],post_last_mag_calculated[k], post_meta[k][25], post_mshift[k], post_meta[k][26], post_meta[k][27], post_last_mag_correction[k], post_meta[k][29]]) \n else:\n print('No postperihelion data to perform statistics on')\n #print('###########################################################################################')\n\n #Plots all available data. That is, any combination of mraw, mhelio, mph, and mshifts depending on \n #which combination of those the user has calculated (i.e., running --heliocentric --shifts will only plot mraw, mhelio, and mshift).\n #All if statements and TRY - EXCEPT blocks are checks\n #for each possible scenario.\n if '--plot' in sys.argv:\n\n if ('--heliocentric' not in sys.argv) and ('--phase' not in sys.argv):\n print('Please perform --heliocentric, --phase, or both before attempting to plot')\n sys.exit()\n \n mags_to_plot_meta = []\n max_x_values = []\n min_x_values = []\n max_y_values = []\n min_y_values = []\n to_check_min_max_x = []\n to_check_min_max_y = []\n titles = []\n axis = []\n count = 0\n \n if '--stats' not in sys.argv:\n deletearow(0)\n del to_report_r[0]\n for j in range(0, len(to_report_r)):\n newdate4 = time.strptime(perihelion, \"%Y/%m/%d\")\n datetocheck = str(metalist[3][j]) + \"/\" + str(metalist[4][j]) + \"/\" + str(math.floor(float(metalist[5][j])))\n newdate5 = time.strptime(datetocheck, \"%Y/%m/%d\")\n if (newdate5 <= newdate4):\n to_report_r[j] = float(-1. * to_report_r[j])\n \n try:\n tmpmeta, tmp_mags, tmp_r = sortbyr(metalist,to_report_r,metalist[8],1)\n for i in range (0, len(tmp_mags)):\n tmp_mags[i] = float(tmp_mags[i])\n tmp_r[i] = float(tmp_r[i])\n mags_to_plot_meta.append(tmp_mags)\n mags_to_plot_meta.append(tmp_r)\n count = count +1\n print('mraw found, adding to plot')\n titles.append('Reported Visual Magnitude')\n axis.append('mraw')\n except:\n print('Please perform --heliocentric, --phase, or both before plotting')\n \n try:\n try:\n float(heliocentric_corrected_magnitudes[0])\n except:\n del heliocentric_corrected_magnitudes[0]\n tmpmeta, tmp_mags, tmp_r = sortbyr(metalist,to_report_r,heliocentric_corrected_magnitudes,1)\n for i in range (0, len(tmp_mags)):\n tmp_mags[i] = float(tmp_mags[i])\n tmp_r[i] = float(tmp_r[i])\n mags_to_plot_meta.append(tmp_mags)\n mags_to_plot_meta.append(tmp_r)\n print('mhelio found, adding to plot')\n titles.append('Geocentric Corrected Magnitudes')\n axis.append('mhelio')\n count = count + 1\n except:\n print('mhelio not found, looking for other magnitudes to plot...')\n \n try:\n try:\n float(phase_corrected_magnitudes[0])\n except:\n del phase_corrected_magnitudes[0]\n tmpmeta, tmp_mags, tmp_r = sortbyr(metalist,to_report_r,phase_corrected_magnitudes,1)\n for i in range (0, len(tmp_mags)):\n tmp_mags[i] = float(tmp_mags[i])\n tmp_r[i] = float(tmp_r[i])\n mags_to_plot_meta.append(tmp_mags)\n mags_to_plot_meta.append(tmp_r)\n count = count + 1\n print('mph found, adding to plot')\n if '--heliocentric' in sys.argv:\n titles.append('Geocentric and Phase Corrected Magnitudes')\n else:\n titles.append('Phase Corrected Magnitudes')\n axis.append('mph')\n except:\n print('mph not found, looking for other magnitudes to plot...')\n \n try:\n try:\n del pre_mshift[0]\n except:\n pass\n try:\n del post_mshift[0]\n except:\n pass\n try:\n del pre_r[0]\n except:\n pass\n try:\n del post_r[0]\n except:\n pass\n pre_and_post_shift_mags = pre_mshift + post_mshift\n pre_and_post_shift_r = pre_r + post_r\n mags_to_plot_meta.append(pre_and_post_shift_mags)\n mags_to_plot_meta.append(pre_and_post_shift_r)\n for i in range(0,len(pre_and_post_shift_mags)):\n pre_and_post_shift_mags[i] = float(pre_and_post_shift_mags[i])\n pre_and_post_shift_r[i] = float(pre_and_post_shift_r[i])\n count = count + 1\n print('Statistically corrected magnitudes found, adding to plot')\n axis.append('mshift')\n if ('--heliocentric' in sys.argv )and ('--phase' in sys.argv):\n titles.append('Geocentric, Phase, and Statistically Corrected Magnitudes')\n elif '--heliocentric' in sys.argv:\n titles.append('Geocentric and Statistically Corrected Magnitudes')\n elif '--phase' in sys.argv:\n titles.append('Phase and Statistically Corrected Magnitudes')\n except:\n print('No statistical corrections found, now plotting...')\n \n for i in range(0, len(mags_to_plot_meta)):\n if len(mags_to_plot_meta[i]) < len(mags_to_plot_meta[0]):\n continue\n if i%2 == 0:\n for j in range(0, len(mags_to_plot_meta[0])):\n to_check_min_max_y.append(float(mags_to_plot_meta[i][j]))\n if i%2 == 1:\n for j in range(0, len(mags_to_plot_meta[1])):\n to_check_min_max_x.append(float(mags_to_plot_meta[i][j]))\n \n true_max_x = math.ceil(max(to_check_min_max_x)) #ceil\n true_min_x = math.floor(min(to_check_min_max_x)) #floor\n true_max_y = math.ceil(max(to_check_min_max_y)) #ceil \n true_min_y = math.floor(min(to_check_min_max_y)) #floor \n \n for i in range(0,len(mags_to_plot_meta)):\n if i%2 == 1:\n continue\n \n if CCD_Bool == 1:\n append_title = \"Visual\"\n else:\n append_title = \"CCD\"\n \n fig, ax = plt.subplots(1,1, figsize=(14,8))\n fig.suptitle(titles[int(i/2)]+\", \"+target_nickname+\", \"+append_title, fontsize='20')\n\n ax.invert_yaxis()\n ax.set_ylabel(axis[int(i/2)], fontsize=20)\n ax.set_xlabel(r'$r (au)$', fontsize=20)\n ax.set_xlim(true_min_x-2, true_max_x+2)\n ax.set_ylim(true_max_y+2, true_min_y-2)\n ax.set_xticks(np.arange(true_min_x-1, true_max_x+1,1))\n ax.yaxis.set_major_locator(MultipleOffsetLocator(2,0))\n ax.yaxis.set_minor_locator(tickers.MultipleLocator(0.5))\n ax.xaxis.set_major_locator(MultipleOffsetLocator(2,1)) #was 150,0 or 2,1\n ax.xaxis.set_minor_locator(tickers.MultipleLocator(0.5)) #was 25 or .5\n ax.tick_params(axis='both', which='both', labelsize=20, direction='in', top=True, right=True, length=3, width=1)\n ax.tick_params(axis='both', which='major', length=7, width=1)\n ax.grid(linestyle='--', lw=0.8)\n ax.plot(mags_to_plot_meta[i+1], mags_to_plot_meta[i], '+', mew=1.1, ms=13, color='blue')\n\n dir_path = os.path.dirname(os.path.realpath(__file__))\n title = dir_path + '\\_' +append_title +\"_\"+ target_nickname + '_graph_'+str(int(i/2)) + \".png\"\n plt.savefig(title, bbox_inches='tight')\n ax.cla()\n \nif __name__ == '__main__':\n main()\n","sub_path":"ICQSplitter.py","file_name":"ICQSplitter.py","file_ext":"py","file_size_in_byte":88654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"23741480","text":"# -*- coding: utf-8 -*-\n#\n# We have a 2×N grid. We will denote the square at the i-th row and j-th column (1≤i≤2, 1≤j≤N) as (i,j).\n#\n# You are initially in the top-left square, (1,1). You will travel to the bottom-right square, (2,N), by repeatedly moving right or down.\n#\n# The square (i,j) contains Ai,j candies. You will collect all the candies you visit during the travel. The top-left and bottom-right squares also contain candies, and you will also collect them.\n#\n# At most how many candies can you collect when you choose the best way to travel?\n\n# ## Constraints\n# - 1≤N≤100\n# - 1≤Ai,j≤100 (1≤i≤2, 1≤j≤N)\n\ndef find_max(n, grid):\n def helper(idx, cur_max, down):\n if n > (idx + 1):\n if down:\n return helper(idx + 1, cur_max + grid[1][idx], down)\n else:\n return max(helper(idx + 1, cur_max + grid[1][idx], True), helper(idx + 1, cur_max + grid[0][idx + 1], False))\n else:\n return cur_max + grid[1][idx]\n\n return helper(0, grid[0][0], False)\n\nn = int(input())\ncandie_matrix = []\nfor i in range(2):\n row = list(map(int, input().split()))\n if len(row) != n:\n print(\"wrong inputs\")\n\n candie_matrix.append(row)\n\nprint(find_max(n,candie_matrix))\n","sub_path":"AtCoder/c_candies.py","file_name":"c_candies.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"188055914","text":"import os, json\n\nclass LoaderState:\n def __init__(self, id_exp, epochs, dataset, valid_exp, url):\n self.state = None\n \n path = url + 'states/state_{}.json'.format(id_exp)\n if os.path.exists(path):\n from_dict_state = self.load_json(path)\n self.state = ExperimentState(from_dict=from_dict_state)\n dataset.restore_state(self.state.dataset)\n else:\n dataset.shuffle()\n self.state = ExperimentState(id_exp=id_exp,\n epochs_max=epochs,\n dataset=dataset.dataset[2],\n valid_exp=valid_exp,\n url=url,\n )\n def load_json(self, url):\n state = {}\n with open(url, mode='r') as f:\n state = json.loads(f.read())\n return state\n\nclass ExperimentState:\n def __init__(self,\n id_exp=None,\n epochs_max=None,\n dataset=None,\n valid_exp=None,\n url='',\n from_dict= {}):\n\n if from_dict != {}:\n print('[INFO] LOADING STATE...')\n\n if os.path.exists('./tmp_history.csv'):\n os.remove('./tmp_history.csv')\n \n\n self.status = from_dict['status']\n self.id_exp = from_dict['id_exp']\n self.epochs_max = from_dict['epochs_max']\n\n valids = {k:[] for k in from_dict['valid_exp']}\n for v in valids:\n if v == 'holdout':\n for h in from_dict['valid_exp'][v]:\n valids[v].append(HoldOutState(from_dict=h))\n elif v == 'kfold':\n for k in from_dict['valid_exp'][v]:\n valids[v].append(KFoldState(from_dict=k))\n\n self.valid_exp = valids\n self.dataset = from_dict['dataset']\n else:\n print('[INFO] MAKE NEW STATE...')\n\n if os.path.exists('./tmp_history.csv'):\n os.remove('./tmp_history.csv')\n\n valids = {k:[] for k in valid_exp}\n for v in valid_exp:\n if v == 'holdout':\n for h in valid_exp[v]:\n valids[v].append(HoldOutState(split=h, url=url))\n elif v == 'kfold':\n for k in valid_exp[v]:\n valids[v].append(KFoldState(k=k, url=url))\n\n self.status = False\n self.id_exp = id_exp\n self.epochs_max = epochs_max\n self.valid_exp = valids\n self.dataset = dataset\n \n def get_validation(self, valid_name):\n validation = self.valid_exp[valid_name]\n \n valid_exps = []\n\n if valid_name == 'holdout':\n for state_h in validation:\n if not state_h.status:\n valid_exps.append(state_h.split/100)\n else:\n for state_k in validation:\n if not state_k.status:\n valid_exps.append(state_k.k)\n \n return valid_exps\n\n def get_state_validation(self, valid_name, k=None, h=None):\n validation = None\n \n if k != None:\n for v in self.valid_exp[valid_name]:\n if v.k == k:\n validation = v\n elif h != None:\n for v in self.valid_exp[valid_name]:\n if v.split == h:\n validation = v\n\n return validation\n \n def to_dict(self):\n valids = {k:[] for k in self.valid_exp}\n \n for v in self.valid_exp:\n for i in self.valid_exp[v]:\n valids[v].append(i.to_dict())\n \n state = {\n 'status': self.status,\n 'id_exp': self.id_exp,\n 'epochs_max': self.epochs_max,\n 'valid_exp': valids,\n 'dataset': self.dataset,\n }\n return state\n\n def __str__(self):\n return str(self.to_dict())\n \nclass HoldOutState:\n def __init__(self, split=10, url='', from_dict={}):\n if from_dict == {}:\n self.epochs = 0\n self.split = split\n self.weights = url + 'weights/'\n self.history = url + 'results/'\n self.status = False\n else:\n self.epochs = from_dict['epochs']\n self.split = from_dict['split']\n self.weights = from_dict['weights']\n self.history = from_dict['history']\n self.status = from_dict['status']\n \n def to_dict(self):\n return {\n 'status': self.status,\n 'epochs': self.epochs,\n 'split': self.split,\n 'weights': self.weights,\n 'history': self.history,\n }\n \n def __str__(self):\n return 'holdout'\n\nclass KFoldState:\n def __init__(self, k=10, url='', from_dict={}):\n if from_dict == {}:\n self.epochs = [0 for i in range(k)]\n self.k = k\n self.current_k = 1\n self.weights = [url + 'weights/' for i in range(k)]\n self.historys = [url + 'results/' for i in range(k)]\n self.status = False\n else:\n self.epochs = from_dict['epochs']\n self.k = from_dict['k']\n self.current_k = from_dict['current_k']\n self.weights = from_dict['weights']\n self.historys = from_dict['historys']\n self.status = from_dict['status']\n \n def get_epochs(self, i):\n return self.epochs[i]\n\n def get_weights(self, i):\n return self.weights[i]\n \n def increment_current_k(self):\n self.current_k += 1\n\n def get_history(self, i):\n return self.historys[i]\n \n def to_dict(self):\n return {\n 'status': self.status,\n 'epochs': self.epochs,\n 'k': self.k,\n 'current_k': self.current_k,\n 'weights': self.weights,\n 'historys': self.historys,\n }\n \n def __str__(self):\n return 'kfold'\n\nif __name__ == '__main__':\n from dataset import DatasetFactory\n from save import SaveExperiment\n with open('experiment.json', mode='r') as f:\n experiment = json.loads(f.read())\n dt = DatasetFactory(name=experiment['dataset'], concat=True)\n\n ldr = LoaderState(\n id_exp='cifar10_resnet_k10',\n epochs=experiment['epochs'],\n dataset=dt,\n valid_exp=experiment['exp'],\n url=experiment['dir'],\n )\n state = ldr.state\n state.get_state_validation('kfold', k=10).status = True\n state.get_state_validation('kfold', k=10).weights[0] = 'teste'\n print(state.get_state_validation('kfold', k=10).weights)\n v = state.get_validation('kfold')\n print(v)\n SaveExperiment(root_dir=experiment['dir'] + 'states/').save_state(state.to_dict())\n\n \n # print(ldr.state.valid_exp['kfold'][0].to_dict())\n\n \n \n \n ","sub_path":"src/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":7019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87158066","text":"import torch\nimport numpy as np\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom models import Actor, Critic\n\n\nclass TD3:\n def __init__(self, env, state_dim, action_dim, max_action, gamma=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, policy_freq=2):\n self.actor = Actor(state_dim, action_dim)\n self.actor_target = Actor(state_dim, action_dim)\n self.actor_target.load_state_dict(self.actor.state_dict())\n self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=1e-3)\n\n self.critic = Critic(state_dim, action_dim)\n self.critic_target = Critic(state_dim, action_dim)\n self.critic_target.load_state_dict(self.critic.state_dict())\n self.critic_optimizer = optim.Adam(self.critic.parameters(), lr=1e-3)\n\n self.max_action = max_action\n self.gamma = gamma\n self.tau = tau\n self.policy_noise = policy_noise\n self.noise_clip = noise_clip\n self.policy_freq = policy_freq\n\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n self.actor.to(self.device)\n self.actor_target.to(self.device)\n self.critic.to(self.device)\n self.critic_target.to(self.device)\n\n self.env = env\n self.total_it = 0\n\n def select_action(self, state, noise=0):\n state = self.normalize_frame(state)\n action = self.actor(state.to(self.device))\n _action = action.data.cpu().numpy().flatten()\n if noise != 0:\n noise = np.random.normal(0, noise, size=self.env.action_space.shape[0])\n action = _action * self.max_action + noise\n _action += noise\n return action.clip(self.env.action_space.low[0], self.env.action_space.high[0]), _action.clip(-1, 1)\n\n def train(self, replay_buffer, batch_size=100):\n self.total_it += 1\n\n states, states_, actions, rewards, terminal = replay_buffer.sample_buffer(batch_size)\n\n states = self.normalize_frame(states)\n states_ = self.normalize_frame(states_)\n\n with torch.no_grad():\n noise = (torch.randn_like(actions.to(self.device))\n * self.policy_noise).clamp(-self.noise_clip, self.noise_clip)\n\n next_action = ((self.actor_target(states_.to(self.device)) + noise)).clamp(-1, 1)\n\n # compute the target Q value\n target_q1, target_q2 = self.critic_target(states_.to(self.device), next_action.to(self.device))\n target_q = torch.min(target_q1, target_q2)\n # target_q = rewards + terminal * self.gamma + target_q.cpu()\n # target_q = rewards + (terminal.reshape(256, 1) * self.gamma * target_q).detach()\n target_q = rewards + terminal * self.gamma * target_q[:,0].cpu()\n\n # Get current Q value\n current_q1, current_q2 = self.critic(states.to(self.device), actions.to(self.device))\n\n # Compute critic loss\n critic_loss = F.mse_loss(current_q1[:,0], target_q.to(self.device)) + F.mse_loss(current_q2[:,0], target_q.to(self.device))\n\n # optimize the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n\n # Delayed policy updates\n if self.total_it % self.policy_freq == 0:\n # Compote actor loss\n actor_loss = -self.critic.q1(states.to(self.device), self.actor(states.to(self.device))).mean()\n\n # Optimize the actor\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n # Update the frozen target models\n for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()):\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n\n for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):\n target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data)\n \n def normalize_frame(self, frames):\n return frames.to(torch.float) / 255\n\n def save(self, filename):\n torch.save(self.critic.state_dict(), \"weights/\" + filename + \"_critic\")\n torch.save(self.critic_optimizer.state_dict(), \"weights/\" + filename + \"_critic_optimizer\")\n torch.save(self.actor.state_dict(), \"weights/\" + filename + \"_actor\")\n torch.save(self.actor_optimizer.state_dict(), \"weights/\" + filename + \"_actor_optimizer\")\n\n def load(self, filename):\n self.critic.load_state_dict(torch.load(filename + \"_critic\"))\n self.critic_optimizer.load_state_dict(torch.load(filename + \"_critic_optimizer\"))\n self.actor.load_state_dict(torch.load(filename + \"_actor\"))\n self.actor_optimizer.load_state_dict(torch.load(filename + \"_actor_optimizer\"))\n\n\n\n","sub_path":"CONV_TD3/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"36264410","text":"import config\nimport requests\nimport pyrus\nimport mailApi\n\npyrus_client = pyrus.client.PyrusAPI(login=config.login, security_key=config.security_key)\nauth_response = pyrus_client.auth()\n\nif not auth_response.success:\n print(\"Неправильный логин или access_token\")\n raise SystemExit\n\ndef auth_requests():\n request = requests.get(f\"https://api.pyrus.com/v4/auth?login={config.login}&security_key={config.security_key}\")\n print(request.json())\n\ndef getMails(date=None):\n mails = []\n for task in pyrus_client.get_registry(config.form_id).original_response[\"tasks\"]:\n if task[\"fields\"][3][\"value\"] == date and date != None:\n mails.append(task[\"fields\"][2][\"value\"])\n\n return mails\n\ndef sendMails(mails, subject, text):\n for mail in mails:\n message = mailApi.create_message(\"noreply@gmail.com\", mail, subject, text)\n mailApi.send_message(\"me\", message)\n\nif __name__ == '__main__':\n pass\n # sendMails(getMails('2019-09-19'), \"Вебинар \" + '2019-09-19', \"Не надо отвечать на это письмо\")\n # forms_response = pyrus_client.get_forms()\n # [print(str(form.id) + \" \" + str(form.name)) for form in forms_response.forms]\n # form_id = 681717\n # # form = pyrus_client.get_form(form_id)\n # # print(form.name)\n # # # print(pyrus_client.get_registry(form_id).original_response[\"tasks\"][0][\"fields\"][2][\"value\"])\n # print(pyrus_client.get_registry(form_id).original_response[\"tasks\"])\n # print(pyrus_client.get_registry(681188).tasks[0].__dict__)\n # task_request = CreateTaskRequest(form_id=form_id, fields=[{\n # \"id\": 1,\n # \"type\": \"text\",\n # \"name\": \"Текст\",\n # \"value\": \"IT conference in Amsterdam\"}])\n # print(pyrus_client.create_task(task_request).__dict__)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"485339242","text":"age = int(input('Enter your age: '))\nyear = 2017\nborn = year - age\nprint('You was born in ', born)\ni = 0\nwhile born < year - 1:\n born = born + 1\n i = i + 1\n print('In', born, 'you was', i, 'years old')\nelse :\n print('In this', year, 'year you are', age, 'years old')","sub_path":"src/exercises/ageWhile.py","file_name":"ageWhile.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"576511478","text":"from flask import render_template\nfrom . import main # importing data from main\nfrom ..requests import get_sources, get_articles\nfrom ..models import Sources, Articles\n\n\n@main.route('/')\ndef index():\n '''\n root direcroy holdng all the sources views\n '''\n general = get_sources('general')\n business = get_sources('business')\n entertainment = get_sources('entertainment')\n technology = get_sources('technology')\n science = get_sources('science')\n\n # for i in real_news:\n # print(i.name)\n title = \"hello world\"\n return render_template('index.html', title=title, general=general, business=business, entertainment=entertainment, technology=technology, science=science)\n\n\n@main.route('/articles/')\ndef articles(id):\n '''\n view all article based of each source through the everything Api\n '''\n\n articles = get_articles(id)\n\n return render_template('article.html', articles=articles)","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"464972242","text":"import copy\nimport sys\nimport traceback\nfrom datetime import *\n\n\ndef CustPrint(*text, type_=None, end=\" \", file=None):\n if text[0] == Exception:\n text = [str(text)]\n if text[0] == traceback:\n text = [str(text)]\n if type_ == None:\n type_ = sys._getframe(1).f_code.co_name\n a = []\n for t in text:\n\n if isinstance(t, tuple):\n t = list(t)\n else:\n t = t\n a.append(t)\n\n try:\n text = ' '.join(list([str(t) for t in a]))\n except:\n text = str(text)\n\n template = \"[{} {}]: {}\\n\".format(str(datetime.now().time())[:-3], type_.upper(), text)\n if type == 'err':\n sys.stderr.write(template)\n return\n sys.stdout.write(template)\n return\n\n\nprint_ = copy.deepcopy(__builtins__['print'])\n__builtins__['print'] = CustPrint\n__builtins__['print_'] = print_\nprint('custom print loaded')\n","sub_path":"CustomPrint.py","file_name":"CustomPrint.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"234113433","text":"#!/usr/bin/env python3\n\nimport os\nimport io\nimport cgi\nimport gzip\nimport time\nimport hashlib\nimport datetime\nimport functools\nimport mimetypes\nimport subprocess as sp\n\nimport git\nimport gitdb\nimport mistune\nimport PIL.Image\nimport pygments\nimport pygments.util\nimport pygments.lexers\nimport pygments.formatters\nimport flask\nimport flask.ext.login\n\nfrom .config import config\nfrom .db import db, User, SSHKey, Repository\nfrom .helpers import *\n\n\napp = flask.Flask(__name__, static_url_path=\"/static\")\napp.config[\"SECRET_KEY\"] = config.secret_key\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = config.database\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb.init_app(app)\n\nlogin_manager = flask.ext.login.LoginManager()\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\nlogin_manager.session_protection = \"strong\"\nlogin_manager.login_message_category = \"info\"\n\n\ndef update_sshkeys():\n if not os.path.exists(os.path.expanduser(\"~/.ssh\")):\n os.mkdir(os.path.expanduser(\"~/.ssh\"))\n\n with open(os.path.expanduser(\"~/.ssh/authorized_keys\"), \"w\") as f:\n f.write(\"# Managed by praline\\n\")\n path = str(sp.check_output([\"which\", \"praline-command\"])[:-1], \"utf-8\")\n keys = SSHKey.query.all()\n for k in keys:\n f.write(\"command=\\\"{} {}\\\",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty {}\".format(path, k.id, k.key))\n\ndef avatar(email, size):\n u = User.query.filter_by(email=email).first()\n if u is None:\n return \"/avatar/{}/{}\".format(email, size)\n return u.avatar(size)\n\n\napp.jinja_env.globals.update(oct=oct)\napp.jinja_env.globals.update(len=len)\napp.jinja_env.globals.update(next=next)\napp.jinja_env.globals.update(enumerate=enumerate)\napp.jinja_env.globals.update(truncate=truncate)\napp.jinja_env.globals.update(relative_date=relative_date)\napp.jinja_env.globals.update(absolute_date=absolute_date)\napp.jinja_env.globals.update(readable_size=readable_size)\napp.jinja_env.globals.update(avatar=avatar)\n\n\n# DECORATORS\n\ndef admin_required(func):\n \"\"\" Checks admin privileges. \"\"\"\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n if not flask.ext.login.current_user.admin:\n flask.abort(403)\n return func(*args, **kwargs)\n return wrapped\n\ndef repo_access_required(func):\n \"\"\" Checks repo existance and access rights. \"\"\"\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n if \"username\" not in kwargs or \"reponame\" not in kwargs:\n flask.abort(404)\n\n username = kwargs[\"username\"]\n reponame = kwargs[\"reponame\"]\n\n try:\n repo = git.Repo(os.path.join(\n os.path.expanduser(\"~\"),\n config.repopath,\n username,\n reponame + \".git\"))\n except git.exc.NoSuchPathError:\n flask.abort(404)\n\n user_db = User.query.filter_by(login=username).first_or_404()\n repo_db = Repository.query.filter_by(owner_id=user_db.id, name=reponame).first_or_404()\n\n if not repo_db.user_authorized(flask.ext.login.current_user, \"pull\"):\n flask.abort(404)\n\n kwargs.update({\"repo\": repo, \"repo_db\": repo_db, \"user_db\": user_db})\n return func(*args, **kwargs)\n return wrapped\n\n\n# HANDLERS\n\n@login_manager.user_loader\ndef load_user(id):\n return User.query.filter_by(id=int(id)).first()\n\n@app.before_request\ndef before_request():\n flask.g.request_start_time = time.time()\n flask.g.request_time = lambda: \"{:.4f}\".format(time.time() - flask.g.request_start_time)\n\n@app.errorhandler(403)\ndef page_not_found(e):\n return minify(flask.render_template(\"403.html\"), app.debug), 403\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return minify(flask.render_template(\"404.html\"), app.debug), 404\n\n@app.errorhandler(500)\ndef server_error(e):\n return minify(flask.render_template(\"500.html\"), app.debug), 500\n\n\n# ROUTES\n\n@app.route(\"/\")\ndef index():\n if not flask.ext.login.current_user.is_authenticated:\n return flask.redirect(flask.url_for(\"explore\"))\n return minify(flask.render_template(\"index.html\"), app.debug)\n\n@app.route(\"/explore\")\ndef explore():\n return minify(flask.render_template(\"explore.html\"), app.debug)\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n if flask.request.method == \"GET\":\n return minify(flask.render_template(\"register.html\"), app.debug)\n\n username = flask.request.form[\"username\"]\n email = flask.request.form[\"email\"]\n password = flask.request.form[\"password\"]\n\n if User.query.filter_by(login=username).first() is not None:\n flask.flash(\"Username is already taken.\", \"danger\")\n flask.redirect(flask.url_for(\"register\"))\n if User.query.filter_by(email=email).first() is not None:\n flask.flash(\"E-Mail is already taken.\", \"danger\")\n flask.redirect(flask.url_for(\"register\"))\n\n if not validate_username(username):\n flask.flash(\"Invalid Username.\", \"danger\")\n flask.redirect(flask.url_for(\"register\"))\n if not validate_email(email):\n flask.flash(\"Invalid E-Mail.\", \"danger\")\n flask.redirect(flask.url_for(\"register\"))\n if not validate_password(password):\n flask.flash(\"Invalid Password.\", \"danger\")\n flask.redirect(flask.url_for(\"register\"))\n\n u = User(\n flask.request.form[\"username\"],\n flask.request.form[\"email\"],\n flask.request.form[\"password\"]\n )\n db.session.add(u)\n db.session.commit()\n\n flask.flash(\"User successfully registered. You can login now.\", \"success\")\n return flask.redirect(flask.url_for(\"login\"))\n \n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n if flask.request.method == \"GET\":\n return minify(flask.render_template(\"login.html\"), app.debug)\n\n username = flask.request.form[\"username\"]\n password = flask.request.form[\"password\"]\n u = User.query.filter_by(login=username).first()\n\n if u is None:\n flask.flash(\"Username or Password is invalid.\", \"danger\")\n return flask.redirect(flask.url_for(\"login\"))\n\n pw_hash = hashlib.sha512(bytes(password + str(int(u.signup.timestamp())), \"utf-8\")).hexdigest()\n\n if u.password != pw_hash:\n flask.flash(\"Username or Password is invalid.\", \"danger\")\n return flask.redirect(flask.url_for(\"login\"))\n\n flask.ext.login.login_user(u, remember=\"remember\" in flask.request.form)\n\n flask.flash(\"Logged in successfully.\", \"success\")\n return flask.redirect(flask.request.args.get(\"next\") or flask.url_for(\"index\"))\n\n@app.route(\"/logout\")\ndef logout():\n flask.ext.login.logout_user()\n return flask.redirect(flask.url_for(\"index\"))\n \n@app.route(\"/settings\", methods=[\"GET\", \"POST\"])\n@flask.ext.login.fresh_login_required\ndef settings():\n if flask.request.method == \"GET\":\n return minify(flask.render_template(\"settings.html\"), app.debug)\n\n name = flask.request.form[\"name\"]\n email = flask.request.form[\"email\"]\n password = flask.request.form[\"password\"]\n password2 = flask.request.form[\"password2\"]\n website = flask.request.form[\"website\"]\n bio = flask.request.form[\"bio\"]\n\n if password != password2:\n flask.flash(\"Passwords do not match\", \"danger\")\n flask.redirect(flask.url_for(\"settings\"))\n\n if not validate_email(email):\n flask.flash(\"Invalid E-Mail.\", \"danger\")\n flask.redirect(flask.url_for(\"settings\"))\n if not validate_password(password):\n flask.flash(\"Invalid Password.\", \"danger\")\n flask.redirect(flask.url_for(\"settings\"))\n\n user = flask.ext.login.current_user\n user.name = name\n user.email = email\n user.showmail = \"showmail\" in flask.request.form\n user.gravatar = \"gravatar\" in flask.request.form\n if password != \"\":\n user.password = hashlib.sha512(bytes(password + str(int(now.timestamp())), \"utf-8\")).hexdigest()\n user.website = website\n user.bio = bio\n db.session.commit()\n\n flask.flash(\"Changes saved.\", \"success\")\n return flask.redirect(flask.url_for(\"settings\"))\n \n@app.route(\"/newrepo\", methods=[\"GET\", \"POST\"])\n@flask.ext.login.login_required\ndef newrepo():\n if flask.request.method == \"GET\":\n return minify(flask.render_template(\"newrepo.html\"), app.debug)\n\n name = flask.request.form[\"name\"]\n description = flask.request.form[\"description\"]\n public = \"public\" in flask.request.form\n\n r = git.Repo.init(os.path.join(\n os.path.expanduser(\"~\"),\n config.repopath,\n flask.ext.login.current_user.login,\n name + \".git\"), bare=True)\n r.description = description\n\n repo_db = Repository(name, flask.ext.login.current_user, public)\n db.session.add(repo_db)\n db.session.commit()\n\n flask.flash(\"Repo created.\", \"success\")\n return flask.redirect(\"/{}/{}\".format(flask.ext.login.current_user.login, name))\n\n@app.route(\"/avatar//\")\n@app.route(\"/avatar/\", defaults={\"size\": 512})\ndef avatar_size(email, size):\n email = hashlib.sha1(bytes(email, \"utf-8\")).hexdigest()\n color = (\n (int(email[0:2], 16) + 255) // 2,\n (int(email[2:4], 16) + 255) // 2,\n (int(email[4:6], 16) + 255) // 2)\n\n img = PIL.Image.new(\"RGB\", (6, 6), \"white\")\n pixels = img.load()\n for x in range(3):\n for y in range(6):\n if int(email[-(x*6+y)], 16) > 8:\n pixels[x,y] = color\n pixels[5-x,y] = color\n img = img.resize((size, size), PIL.Image.NEAREST)\n\n stream = io.BytesIO()\n img.save(stream, \"JPEG\", quality=50)\n stream.seek(0)\n return flask.send_file(stream, mimetype=\"image/jpeg\")\n\n@app.route(\"/ajax/sshkey/add\")\n@flask.ext.login.fresh_login_required\ndef ajax_sshkey_add():\n key = flask.request.args.get(\"key\")\n s = SSHKey(key, flask.ext.login.current_user)\n db.session.add(s)\n db.session.commit()\n update_sshkeys()\n return \"ok\"\n\n@app.route(\"/ajax/sshkey/delete/\")\n@flask.ext.login.fresh_login_required\ndef ajax_sshkey_delete(keyid):\n key = SSHKey.query.get(keyid)\n if key is None or key.owner != flask.ext.login.current_user:\n return \"bad request\", 400\n db.session.delete(key)\n db.session.commit()\n update_sshkeys()\n return \"ok\"\n\n@app.route(\"/\")\ndef profile(username):\n user = User.query.filter_by(login=username).first_or_404()\n return minify(flask.render_template(\"profile.html\", user=user), app.debug)\n\n@app.route(\"///tree/[/\")\n@app.route(\"///tree/][\", defaults={\"path\": \"\"})\n@app.route(\"///tree\", defaults={\"path\": \"\", \"ref\": \"\"})\n@app.route(\"//\", defaults={\"path\": \"\", \"ref\": \"\"})\n@repo_access_required\ndef repo_tree(username, reponame, ref, path, repo, repo_db, user_db):\n if ref == \"\":\n ref = repo.head.ref.name\n\n cloneurls = {\n \"http\": flask.request.url_root + username + \"/\" + reponame + \".git\",\n \"ssh\": os.environ[\"USER\"] + \"@\" + flask.request.url_root.split(\"/\")[2].split(\":\")[0] + \":\" + username + \"/\" + reponame + \".git\"\n }\n if config.use_ssl:\n cloneurls[\"http\"] = cloneurls[\"http\"].replace(\"http://\", \"https://\")\n\n if len(repo.heads) == 0:\n if path != \"\":\n flask.abort(404)\n return minify(flask.render_template(\"bare.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n cloneurls=cloneurls,\n ssl=config.use_ssl), app.debug)\n\n tree = repo.tree(repo.rev_parse(ref))\n\n try:\n assert path != \"\"\n target = tree[path]\n except AssertionError:\n target = tree\n except KeyError:\n flask.abort(404)\n\n breadcrumbs = []\n for p in target.path.split(\"/\"):\n previous = [b[0] for b in breadcrumbs] + [p]\n breadcrumbs.append([p, \"/\".join(previous), False])\n breadcrumbs[-1][-1] = True\n\n readme_names = [\n \"README.md\",\n \"README.MD\",\n \"readme.md\",\n \"README.txt\",\n \"README.TXT\",\n \"readme.txt\",\n \"README\",\n \"readme\"\n ]\n readme = \"\"\n readme_name = \"\"\n for r in readme_names:\n try:\n readme = target[r].data_stream.read()\n except KeyError:\n continue\n readme_name = r\n try:\n readme = str(readme, \"utf-8\")\n except UnicodeDecodeError:\n readme = \"\"\n break\n if r in readme_names[:3]:\n renderer = mistune.Renderer(escape=False)\n markdown = mistune.Markdown(renderer=renderer)\n readme = markdown(readme)\n break\n \n return minify(flask.render_template(\"tree.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n cloneurls=cloneurls,\n ssl=config.use_ssl,\n ref=ref,\n breadcrumbs=breadcrumbs,\n tree=target,\n parent=\"/\".join(path.split(\"/\")[:-1]),\n readme=readme,\n readme_name=readme_name), app.debug)\n\n@app.route(\"///blob/][/\")\n@repo_access_required\ndef repo_blob(username, reponame, ref, path, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n if ref == \"\":\n ref = repo.head.ref.name\n\n tree = repo.tree(repo.rev_parse(ref))\n\n try:\n target = tree[path]\n except KeyError:\n flask.abort(404)\n\n breadcrumbs = []\n for p in target.path.split(\"/\"):\n previous = [b[0] for b in breadcrumbs] + [p]\n breadcrumbs.append([p, \"/\".join(previous), False])\n breadcrumbs[-1][-1] = True\n\n try:\n content = str(target.data_stream.read(), \"utf-8\")\n try:\n lexer = pygments.lexers.guess_lexer_for_filename(target.name, content)\n except pygments.util.ClassNotFound:\n content = cgi.escape(content)\n lines = content.split(\"\\n\")\n lines = [\"\" + l + \"\" for l in lines]\n content = \"]\" + \"\".join(lines) + \"
\"\n else:\n content = pygments.highlight(content, lexer, pygments.formatters.HtmlFormatter(linespans=\"line\"))\n except UnicodeDecodeError:\n content = \"\"\n return minify(flask.render_template(\"blob.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n ref=ref,\n breadcrumbs=breadcrumbs,\n blob=target,\n content=content), app.debug)\n\n@app.route(\"///raw/[/\")\n@repo_access_required\ndef repo_raw(username, reponame, ref, path, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n if ref == \"\":\n ref = repo.head.ref.name\n\n tree = repo.tree(repo.rev_parse(ref))\n\n try:\n assert path != \"\"\n target = tree[path]\n except AssertionError:\n target = tree\n except KeyError:\n flask.abort(404)\n else:\n target = tree[path]\n\n if target.type == \"tree\":\n flask.abort(404)\n\n response = flask.make_response(target.data_stream.read())\n response.headers[\"Content-Type\"] = mimetypes.guess_type(target.path)\n return response\n\n@app.route(\"///commits/][/\")\n@app.route(\"///commits/][\", defaults={\"path\": \"\"})\n@app.route(\"///commits\", defaults={\"path\": \"\", \"ref\": \"\"})\n@repo_access_required\ndef repo_commits_path(username, reponame, ref, path, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n if ref == \"\":\n ref = repo.head.ref.name\n\n tree = repo.tree(repo.rev_parse(ref))\n\n try:\n assert path != \"\"\n target = tree[path]\n except AssertionError:\n target = tree\n except KeyError:\n flask.abort(404)\n else:\n target = tree[path]\n\n page = int(flask.request.args.get(\"page\", \"1\"))\n\n breadcrumbs = []\n for p in target.path.split(\"/\"):\n previous = [b[0] for b in breadcrumbs] + [p]\n breadcrumbs.append([p, \"/\".join(previous)])\n\n commits = list(repo.iter_commits(rev=ref, paths=path, skip=(page-1)*50, max_count=50))\n\n return minify(flask.render_template(\"commits.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n ref=ref,\n breadcrumbs=breadcrumbs,\n tree=target,\n commits=commits,\n page=page), app.debug)\n\n@app.route(\"///commit/\")\n@repo_access_required\ndef repo_commit(username, reponame, hexsha, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n try:\n commit = repo.commit(hexsha)\n except gitdb.exc.BadName:\n flask.abort(404)\n\n diffs = []\n for d in commit.diff(commit.parents[0], create_patch=True, R=True):\n try:\n patch = cgi.escape(str(d.diff, \"utf-8\")).split(\"\\n\")\n lines = []\n for l in patch[2:-1]:\n try:\n if l[0] == \"-\":\n lines.append(\"\" + l + \"\")\n elif l[0] == \"+\":\n lines.append(\"\" + l + \"\")\n elif l[0] == \"@\" or l[0] == \"\\\\\":\n lines.append(\"\" + l + \"\")\n else:\n raise IndexError\n except IndexError:\n lines.append(\"\" + l + \"\")\n patch = \"\".join(lines)\n if patch != \"\":\n patch = \"]\" + \"\".join(lines) + \"
\"\n except UnicodeDecodeError:\n patch = \"\"\n diffs.append((d, patch))\n\n return minify(flask.render_template(\"commit.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n commit=commit,\n diffs=diffs), app.debug)\n\n@app.route(\"///branches\")\n@repo_access_required\ndef repo_branches(username, reponame, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n branches = repo.heads\n branches.sort(key=lambda x: x.commit.committed_date * -1)\n\n return minify(flask.render_template(\"branches.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n branches=branches), app.debug)\n\n@app.route(\"///tags\")\n@repo_access_required\ndef repo_tags(username, reponame, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n page = int(flask.request.args.get(\"page\", \"1\"))\n\n tags = list(repo.tags)\n tags.sort(key=lambda x: x.commit.committed_date * -1)\n tags = tags[((page - 1)*50):(page*50)]\n\n return minify(flask.render_template(\"tags.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n tags=tags,\n page=page), app.debug)\n\n@app.route(\"///stats\")\n@repo_access_required\ndef repo_stats(username, reponame, repo, repo_db, user_db):\n if len(repo.heads) == 0:\n flask.abort(404)\n\n commits = []\n punchcard = [0 for i in range(24)]\n contributors = {}\n\n for c in repo.iter_commits():\n d = datetime.date.fromtimestamp(c.committed_date)\n if len(commits) == 0 or commits[0][0] != d:\n commits.insert(0, [d, 0])\n commits[0][1] += 1\n\n dt = datetime.datetime.fromtimestamp(c.committed_date + c.committer_tz_offset)\n punchcard[dt.hour] += 1\n\n if c.author.email not in contributors:\n contributors[c.author.email] = [c.author, 0]\n contributors[c.author.email][1] += 1\n\n contributors = list(contributors.values())\n contributors.sort(key=lambda x: x[1] * -1)\n\n # Create a list of file extensions to reduce the amount of calls to pygments\n files = {}\n unknown = 0\n for b in repo.tree().traverse():\n try:\n n = b.name.split(\".\")\n except AttributeError:\n break\n if len(n) < 2:\n unknown += 1\n continue\n if n[-1] not in files:\n files[n[-1]] = 0\n files[n[-1]] += 1\n\n languages = {}\n for f, c in files.items():\n try:\n lang = pygments.lexers.get_lexer_for_filename(\"abc.\"+f).name\n except pygments.util.ClassNotFound:\n lang = \"Unknown\"\n if lang not in languages:\n languages[lang] = 0\n languages[lang] += c\n if \"Unknown\" not in languages:\n langueags[\"Unknown\"] = 0\n languages[\"Unknown\"] += unknown\n\n age = (commits[-1][0] - commits[0][0]).days\n general = [\n [\"Commits\", sum(punchcard)],\n [\"Files\", sum(languages.values())],\n [\"Branches\", len(repo.heads)],\n [\"Tags\", len(repo.tags)],\n [\"Contributors\", len(contributors)],\n [\"Project Age\", str(age) + \" days\"],\n [\"Commits/Day\", round(sum(punchcard) / age, 2)]\n ]\n\n languages = [(l, n) for l, n in languages.items()]\n languages.sort(key=lambda x: x[1] * -1)\n\n return minify(flask.render_template(\"stats.html\",\n username=username,\n reponame=reponame,\n repo=repo,\n repo_db=repo_db,\n commits=commits,\n punchcard=punchcard,\n general=general,\n contributors=contributors,\n languages=languages), app.debug)\n\n@app.route(\"//.git/info/refs\")\n@app.route(\"///info/refs\")\n@repo_access_required\ndef info_refs(username, reponame, repo, repo_db, user_db):\n service = flask.request.args.get(\"service\", \"git-upload-pack\")\n if service not in [\"git-upload-pack\", \"git-receive-pack\"]:\n return \"What's all this then?\", 403\n if service == \"git-receive-pack\":\n # todo basic auth\n if not repo_db.user_authorized(flask.ext.login.current_user, \"push\"):\n return flask.abort(404)\n\n proc = sp.Popen([service, repo.working_dir], stdout=sp.PIPE)\n result = bytes(\"001e# service={}\\n0000\".format(service), \"utf-8\")\n while True:\n code = proc.stdout.read(4)\n if code == b\"0000\":\n result += b\"0000\"\n break\n else:\n result += code + proc.stdout.readline()\n\n response = flask.make_response(str(result, \"utf-8\"))\n response.headers[\"Content-Type\"] = \"application/x-git-upload-pack-advertisement\"\n return response\n\n@app.route(\"//.git/git-upload-pack\", methods=[\"POST\"])\n@app.route(\"///git-upload-pack\", methods=[\"POST\"])\n@repo_access_required\ndef git_upload_pack(username, reponame, repo, repo_db, user_db):\n data = flask.request.get_data()\n if flask.request.headers.get(\"Content-Encoding\", \"\") == \"gzip\":\n data = gzip.decompress(data)\n\n proc = sp.Popen([\"git-upload-pack\", \"--stateless-rpc\", repo.working_dir],\n stdin=sp.PIPE, stdout=sp.PIPE)\n proc.stdin.write(data)\n result = proc.stdout.read()\n proc.wait()\n\n response = flask.make_response(result)\n response.headers[\"Cache-Control\"] = \"no-cache\"\n response.headers[\"Content-Type\"] = \"application/x-git-upload-pack-result\"\n return response\n\n@app.route(\"//.git/git-receive-pack\", methods=[\"POST\"])\n@app.route(\"///git-receive-pack\", methods=[\"POST\"])\n@repo_access_required\ndef git_receive_pack(username, reponame, repo, repo_db, user_db):\n if not repo_db.user_authorized(flask.ext.login.current_user, \"push\"):\n # todo basic auth\n return flask.abort(404)\n\n data = flask.request.get_data()\n if flask.request.headers.get(\"Content-Encoding\", \"\") == \"gzip\":\n data = gzip.decompress(data)\n\n proc = sp.Popen([\"git-receive-pack\", \"--stateless-rpc\", repo.working_dir],\n stdin=sp.PIPE, stdout=sp.PIPE)\n proc.stdin.write(data)\n result = proc.stdout.read()\n proc.wait()\n\n response = flask.make_response(result)\n response.headers[\"Cache-Control\"] = \"no-cache\"\n response.headers[\"Content-Type\"] = \"application/x-git-upload-pack-result\"\n return response\n","sub_path":"praline/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":24030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"568233584","text":"#!/usr/bin/env python\n# \n\nimport os\nimport sys\n\n#os.system('cp /Users/dzliu/Softwares/Python/lib/crab/crabplot/CrabPlot.py /Users/dzliu/Cloud/Github/Crab.Toolkit.michi2/lib/python/crabplot/CrabPlot.py')\n\nsys.path.insert(1, os.path.dirname(os.path.dirname(sys.argv[0])) + os.path.sep + 'lib' + os.path.sep + 'python' + os.path.sep + 'crabtable')\nsys.path.insert(1, os.path.dirname(os.path.dirname(sys.argv[0])) + os.path.sep + 'lib' + os.path.sep + 'python' + os.path.sep + 'crabplot')\nsys.path.insert(1, os.path.dirname(os.path.dirname(sys.argv[0])) + os.path.sep + 'lib' + os.path.sep + 'python' + os.path.sep + 'crabbin')\n#sys.path.insert(1, '/Users/dzliu/Softwares/Python/lib/crab/crabtable')\n#sys.path.insert(1, '/Users/dzliu/Softwares/Python/lib/crab/crabplot')\n#sys.path.insert(1, '/Users/dzliu/Softwares/Python/lib/crab/crabbin')\n\nfrom CrabTable import *\nfrom CrabPlot import *\nfrom CrabBin import *\n\nimport glob\nimport math\nimport numpy\nimport scipy\nimport astropy\nfrom astropy import units\nfrom astropy.io import fits\nimport re\nimport json\nfrom copy import copy\n\n\n\n\n\n\n#########################################\n# Constants #\n#########################################\n\nDelta_chisq_of_interest = 5.89 # for 5 interested parameters, 68.3% confidence (1-sigma).\n# Delta_chisq_of_interest is the allowed chi-square range for computing errors in interested parameters.\n# -- See http://www.astro.sunysb.edu/metchev/PHY515/astrostatistics.html\n# -- See also Press (1992) \"\" Chap. 15 P. 6 (press1992chap15p6.pdf)\n# -- The value can also be calculated by the C++ code \"michi2_compute_delta_chisq_1sigma\", which is written based on the code in Press (1992). \n\n\n\n\n\n#########################################\n# Functions #\n#########################################\n\ndef analyze_chisq_distribution(param_dict, verbose = 1, Plot_engine = None):\n # Plot_engine must be the CrabPlot class\n if 'Lib_file' in param_dict and \\\n 'Lib_name' in param_dict and \\\n 'Lib_numb' in param_dict and \\\n 'Par_name' in param_dict and \\\n 'Col_numb' in param_dict and \\\n 'value' in param_dict and \\\n 'chisq' in param_dict :\n if verbose>=1:\n print('Analyzing the chi-square distribution for parameter \"%s\" in library %s from file \"%s\"'%(param_dict['Par_name'], param_dict['Lib_name'], param_dict['Lib_file']))\n #print(param_dict)\n # \n #print(big_chisq_data_table.colnames)\n #chisq_array = big_chisq_data_table[big_chisq_data_table.colnames[2-1]] # the second column of the input 'big_chisq_data_table' is the chisq column. -- TODO: MUST MAKE SURE USER DO NOT CHANGE THE FORMAT!\n #coeff_array = big_chisq_data_table[big_chisq_data_table.colnames[2+2*param_dict['Lib_numb']-1]] # the coefficient/normalization column, e.g., for LIB(2), the 2+2*(2)th column is a2, which is the normalization of LIB(2).\n #param_array = big_chisq_data_table[big_chisq_data_table.colnames[param_dict['Col_numb']-1]] # the parameter column.\n #print('Taking column %s as the chisq_array'%(2))\n #print('Taking column %s as the coeff_array'%(2+2*param_dict['Lib_numb']))\n #print('Taking column %s as the param_array'%(param_dict['Col_numb']))\n # \n # check arrays\n param_array = copy(param_dict['value'])\n chisq_array = copy(param_dict['chisq'])\n chisq_min = numpy.nanmin(chisq_array)\n # \n # copy\n #param_array_nonan = copy(param_array)\n #param_array_nonan[numpy.isnan(param_array_nonan)] = -99\n # \n # apply range -- no, do not cut the array, but just adjust the plotting range.\n #if 'range' in param_dict:\n # if len(param_dict['range'])>=2:\n # param_range_mask = (param_array >= param_dict['range'][0]) & (param_array <= param_dict['range'][1])\n # chisq_array = chisq_array[param_range_mask]\n # param_array = param_array[param_range_mask]\n # param_array_nonan = param_array_nonan[param_range_mask]\n # \n # set xrange to the user-specified values\n xrange = None\n param_min = None\n param_max = None\n if 'range' in param_dict:\n if len(param_dict['range'])>=2:\n param_min = param_dict['range'][0]\n param_max = param_dict['range'][1]\n # \n # bin param\n param_log = False\n if 'Log_calc' in param_dict:\n if param_dict['Log_calc'] == True:\n param_log = True\n # \n # crab_bin_compute_param_chisq_histogram for delta_chisq = 2.3 (2p)\n param_stats_2p = crab_bin_compute_param_chisq_histogram(chisq_array, param_array, min = param_min, max = param_max, delta_chisq = 2.3, log = param_log)\n if 'Par_file' in param_dict:\n # remove previous file\n if os.path.isfile('best-fit_param_'+param_dict['Par_file']+'.txt'):\n os.system('mv %s %s.backup'%('best-fit_param_'+param_dict['Par_file']+'.txt', \n 'best-fit_param_'+param_dict['Par_file']+'.txt'))\n if param_stats_2p['valid'] is True:\n param_median = param_stats_2p['median']\n param_best = param_stats_2p['best']\n param_sigma = param_stats_2p['sigma']\n param_L68 = param_stats_2p['L68']\n param_H68 = param_stats_2p['H68']\n else:\n param_median = 0.0\n param_best = 0.0\n param_sigma = 0.0\n param_L68 = 0.0\n param_H68 = 0.0\n asciitable.write(numpy.column_stack((param_median, param_best, param_sigma, param_L68, param_H68)), \n 'best-fit_param_'+param_dict['Par_file']+'.txt', Writer=asciitable.Ipac, \n names=['param_median', 'param_best', 'param_sigma', 'param_L68', 'param_H68'], \n formats={'param_median': '%20.10g', 'param_best': '%20.10g', 'param_sigma': '%20.10g', 'param_L68': '%20.10g', 'param_H68': '%20.10g'}, \n delimiter=' ', overwrite = True)\n # \n # crab_bin_compute_param_chisq_histogram for plotting\n param_stats = crab_bin_compute_param_chisq_histogram(chisq_array, param_array, min = param_min, max = param_max, delta_chisq = Delta_chisq_of_interest, log = param_log)\n # \n param_bin_x = param_stats['hist_x']\n param_bin_y = param_stats['hist_y']\n param_bin_step = param_stats['bin_step']\n # \n xrange = param_stats['xrange'] # xrange is the param range where chi-sq < min-chi-sq + 2.3\n yrange = param_stats['yrange']\n #xrange = [xrange[0]-(xrange[1]-xrange[0])*0.50, xrange[1]+(xrange[1]-xrange[0])*0.50] # extend the range for plotting.\n if param_stats['valid']:\n xrange = [ param_stats['L68'] - 10*param_stats['bin_step'], \n param_stats['H68'] + 10*param_stats['bin_step'] ]\n ##if xrange[0] < param_stats['min']: xrange[0] = param_stats['min']\n ##if xrange[1] > param_stats['max']: xrange[1] = param_stats['max']\n # invert y\n yrange = [1.0/yrange[1], 1.0/yrange[0]]\n yrange = numpy.log10(yrange)\n yrange = [yrange[0]-(yrange[1]-yrange[0])*0.50, yrange[1]+(yrange[1]-yrange[0])*0.05] # extend the range for plotting.\n yrange = numpy.power(10,yrange)\n # \n xlog = None\n #if 'Log_plot' in param_dict:\n # if param_dict['Log_plot'] == True:\n # xlog = 1 # not working for matplotlib bar plot (i.e., CrabPlot plot_hist)!\n # \n ylog = None\n # \n # log\n if param_log is True:\n param_array_mask = (param_array>0)\n param_array_mask2 = (param_array<=0)\n param_array[param_array_mask] = numpy.log10(param_array[param_array_mask])\n param_array[param_array_mask2] = numpy.nan\n #pprint(numpy.column_stack((param_bin_x, param_bin_y, 1/param_bin_y)))\n #print('------ xrange', xrange)\n #print('------ yrange', yrange, [1/yrange[1],1/yrange[0]])\n #print('------ param_stats.xrange', param_stats['xrange'])\n #print('------ param_stats.yrange', param_stats['yrange'], [1/param_stats['yrange'][1],1/param_stats['yrange'][0]])\n #print('------ param_stats.minimum_chisq', param_stats['minimum_chisq'])\n #print('------ param_stats.best_min_chisq', param_stats['best_min_chisq'])\n #print('------ param_stats.best', param_stats['best'])\n print('param_stats.min', param_stats['min'])\n print('param_stats.max', param_stats['max'])\n print('param_stats.xrange', param_stats['xrange'])\n print('param_stats.yrange', param_stats['yrange'], [1/param_stats['yrange'][1],1/param_stats['yrange'][0]])\n print('plotting xrange', xrange)\n print('plotting yrange', yrange)\n #--\n #--TODO--20180123-10h44m-- when param_log is True, param_min can be zero!\n #--\n # \n # Initialize a plot\n if Plot_engine is None:\n Plot_engine = CrabPlot(figure_size=(9.0,5.0))\n Plot_engine.set_margin(panel=0, top=0.96, bottom=0.04)\n # \n # Plot xy (left panel)\n Plot_engine.plot_xy(param_array, 1/numpy.array(chisq_array), overplot = False, \n xtitle = param_dict['Par_name'], ytitle = '$1/\\chi^2$', useTex = True, \n size = 2.2, color='#1873cc', symbol = 'o')\n # \n # Plot Cut_chi2 line\n Plot_engine.plot_line(param_stats['xrange'][0], 1/(chisq_min+Delta_chisq_of_interest), \n param_stats['xrange'][0], 1/(chisq_min+Delta_chisq_of_interest), \n overplot = True, linestyle = 'dashed')\n # \n # Plot histogram (right panel)\n Plot_engine.plot_hist(param_bin_x, 1/numpy.array(param_bin_y), width = param_bin_step*1.5, align = 'edge', overplot = False, \n xtitle = param_dict['Par_name'], ytitle = '$1/\\chi^2$', useTex = True, \n xrange = xrange, yrange = yrange, xlog = xlog, ylog = ylog)\n # \n # Plot Cut_chi2 line\n Plot_engine.plot_line(xrange[0], 1/(chisq_min+Delta_chisq_of_interest), xrange[1], 1/(chisq_min+Delta_chisq_of_interest), overplot = True, linestyle = 'dashed')\n Plot_engine.plot_text(xrange[1], yrange[1]-0.02*(yrange[1]-yrange[0]), ' (zoomed) ', NormalizedCoordinate=False, overplot=True, horizontalalignment='right', verticalalignment='top')\n # \n # Plot Cut_chi2 line (2p = 2.3)\n Plot_engine.plot_line(param_stats_2p['xrange'][0], 1/(chisq_min+2.3), \n param_stats_2p['xrange'][1], 1/(chisq_min+2.3), \n overplot = True, color='#1e90ff', linestyle = 'dotted')\n # color: http://www.color-hex.com/color/1e90ff\n # \n else:\n print('Error! analyze_chisq_distribution() got unaccepted inputs!')\n sys.exit()\n\n\n\n\ndef random_sorted_chi2_index_dict(Cut_chi2_array, max = 50):\n # \n # This function returns a list of index in the 'Cut_chi2_array', including the first one, the last one, and at most 50 random elements in between.\n # \n Plot_chi2_max_number = max # Max chi2 solutions to plot, we plot the first Plot_chi2_max_number/2 and the last Plot_chi2_max_number/2 solutions, skip solutions in the middle.\n # \n #Cut_chi2_array = numpy.random.random(30)\n Cut_chi2_number = len(Cut_chi2_array)\n # \n Plot_chi2_indices = numpy.sort(numpy.argsort(numpy.random.random(Cut_chi2_number))[0:Plot_chi2_max_number])[::-1] # non-repeated index array from 0 to Plot_chi2_max_number\n Plot_chi2_indices[0] = Cut_chi2_number-1 if Plot_chi2_indices[0] != Cut_chi2_number-1 else Cut_chi2_number-1 # make sure the first element is always 'Cut_chi2_number-1', i.e., the worst chi-square solution\n Plot_chi2_indices[-1] = 0 if Plot_chi2_indices[-1] != 0 else 0 # make sure the last element is always '0', i.e., the mininum chi-square solution\n # \n Plot_chi2_index_dict = {}\n for i in range(len(Plot_chi2_indices)): \n Plot_chi2_index_dict['%d'%(Plot_chi2_indices[i])] = Cut_chi2_array[i]\n # \n return Plot_chi2_index_dict, Plot_chi2_indices\n\n\n\n\n\n\n\n\n\n\n##########################################\n# MAIN PROGRAM #\n##########################################\n\nif len(sys.argv) <= 1:\n \n print('Usage: michi2_plot_SED_fitting_results.py fit_5.out')\n sys.exit()\n\nelse:\n # \n # Read user input\n SetOnlyPlotBestSED = False\n SourceName = ''\n PlotYRange = []\n iarg = 1\n while iarg < len(sys.argv):\n TempCmd = sys.argv[iarg].replace('--','-').lower()\n if sys.argv[iarg]=='-only-plot-best-sed' or sys.argv[iarg]=='-only-best':\n SetOnlyPlotBestSED = True\n print('Setting only plot best-fit!')\n elif sys.argv[iarg]=='-source-name' or sys.argv[iarg]=='-source':\n if iarg+1 < len(sys.argv):\n iarg = iarg + 1\n SourceName = sys.argv[iarg]\n print('Setting SourceName = %s'%(SourceName))\n elif sys.argv[iarg]=='-yrange':\n if iarg+2 < len(sys.argv):\n iarg = iarg + 1\n PlotYRange.append(float(sys.argv[iarg]))\n iarg = iarg + 1\n PlotYRange.append(float(sys.argv[iarg]))\n print('Setting PlotYRange = %s'%(PlotYRange))\n else:\n DataFile = sys.argv[iarg]\n iarg = iarg + 1\n # \n # Read chi2 table\n #DataFile = sys.argv[1]\n if DataFile == '' or not os.path.isfile(DataFile):\n print('Error! The input fitted chi2 data file \"%s\" was not found!'%(DataFile))\n sys.exit()\n print('# Reading \"%s\"'%(DataFile))\n DataTable = CrabTable(DataFile, verbose=1)\n # \n # Read fit info\n InfoFile = DataFile + '.info'\n if not os.path.isfile(InfoFile):\n print('Error! The input fitted chi2 info file \"%s\" was not found!'%(InfoFile))\n sys.exit()\n print('# Reading \"%s\"'%(InfoFile))\n InfoDict = CrabTableReadInfo(InfoFile, verbose=0)\n CheckInfoDictOK = True\n for InfoKey in ['OBS', 'NLIB', 'OUT']:\n if InfoKey not in InfoDict:\n print('Error! Key \"%s\" is not in the InfoFile \"%s\"!'%(InfoKey, InfoFile))\n CheckInfoDictOK = False\n if CheckInfoDictOK is False:\n sys.exit()\n # \n print(InfoDict)\n # \n # Fix data table header problem\n DataHeaders = []\n with open(DataFile,'r') as fp:\n while True:\n DataLine = fp.readline()\n if not DataLine:\n break\n if DataLine.startswith('#'):\n DataLineSplit = DataLine.replace('#','').strip().split()\n if len(DataLineSplit) == len(DataTable.TableHeaders):\n DataHeaders = DataLineSplit\n else:\n break\n fp.close()\n # \n # Read big chi2 data table columns\n DataArray = {}\n for i in range(len(DataHeaders)):\n #if DataHeaders[i] == 'chi2':\n # Data_chi2 = DataTable.getColumn(i+1)\n for j in range(int(InfoDict['NLIB'])):\n if DataHeaders[i] == 'i%d'%(j+1):\n DataArray['i%d'%(j+1)] = DataTable.getColumn(i+1)\n elif DataHeaders[i] == 'a%d'%(j+1):\n DataArray['a%d'%(j+1)] = DataTable.getColumn(i+1)\n elif DataHeaders[i] == 'i0':\n DataArray['i0'] = DataTable.getColumn(i+1)\n elif DataHeaders[i] == 'a0':\n DataArray['a0'] = DataTable.getColumn(i+1)\n elif DataHeaders[i] == 'chi2':\n DataArray['chi2'] = DataTable.getColumn(i+1)\n # \n # Sort chi2 table\n #print(DataTable.TableHeaders)\n #print(DataArray['chi2'])\n All_chi2_index_sorted = numpy.argsort(DataArray['chi2'])\n All_chi2_number = len(All_chi2_index_sorted)\n #Cut_chi2_number = 10 ## how many SEDs to show?\n #Cut_chi2_number = All_chi2_number if All_chi2_number# tune line width\n Plot_SED_linewidth = 1.0\n print('Selecting %d chi2 solutions with chi2 <= min(chi2)+%s'%(Cut_chi2_number, Delta_chisq_of_interest))\n # \n if not SetOnlyPlotBestSED:\n if not os.path.isfile('Plot_chi2_index_dict.json') or not os.path.isfile('Plot_chi2_indices.json'):\n Plot_chi2_index_dict, Plot_chi2_indices = random_sorted_chi2_index_dict(Cut_chi2_array) # we plot 50 chi2 solution curves\n with open('Plot_chi2_index_dict.json', 'w') as fp:\n json.dump(Plot_chi2_index_dict, fp, sort_keys=True, indent=4)\n fp.close()\n with open('Plot_chi2_indices.json', 'w') as fp:\n json.dump(Plot_chi2_indices.tolist(), fp)\n fp.close()\n else:\n with open('Plot_chi2_index_dict.json', 'r') as fp:\n Plot_chi2_index_dict = json.load(fp)\n fp.close()\n with open('Plot_chi2_indices.json', 'r') as fp:\n Plot_chi2_indices = numpy.array(json.load(fp))\n fp.close()\n else:\n Plot_chi2_index_dict = {}\n Plot_chi2_index_dict['0'] = Cut_chi2_array[0]\n Plot_chi2_indices = [0]\n # \n # also tune plotting linewidth\n Plot_chi2_linewidth = 1.5\n Plot_SED_linewidth = 2.0\n #print('Will plot chi2 solution indices %s'%(Plot_chi2_index_dict))\n # \n # \n # \n # \n # \n # \n # \n #########################################\n # Now prepare to plot the best-fit SEDs #\n #########################################\n # \n # check if output figure already exists or not, see if we overwrite or not.\n Output_name, Output_extension = os.path.splitext(DataFile)\n if True:\n # \n # Get SED\n for i in range(Cut_chi2_number):\n # \n # skip solutions between 11th to last 11th.\n #if i > Plot_chi2_max_number/2 and i<(Cut_chi2_number-1-Plot_chi2_max_number/2):\n # continue\n if not ('%d'%i) in Plot_chi2_index_dict:\n continue\n # \n # Read SED_LIB\n for j in range(int(InfoDict['NLIB'])):\n if not os.path.isdir('obj_%d'%(i+1)):\n os.mkdir('obj_%d'%(i+1))\n # \n if not os.path.isfile('obj_%d/SED_LIB%d'%(i+1,j+1)):\n #BashCommand = 'cd obj_%d/; /Users/dzliu/Cloud/Github/Crab.Toolkit.michi2/bin/michi2_read_lib_SED ../%s %d %s SED_LIB%d'%\\\n # (i+1, \\\n # InfoDict['LIB%d'%(j+1)], \\\n # DataArray['i%d'%(j+1)][All_chi2_index_sorted[i]], \\\n # DataArray['a%d'%(j+1)][All_chi2_index_sorted[i]], \\\n # j+1)\n #print(BashCommand)\n #os.system(BashCommand)\n # \n # do python way 20180113\n BashCommand = '%s/michi2_read_lib_SEDs.py %s %d obj_%d > obj_%d/log.txt'%\\\n (os.path.dirname(os.path.realpath(__file__)), \\\n DataFile, \\\n All_chi2_index_sorted[i]+1, \\\n i+1, \\\n i+1)\n print(BashCommand)\n os.system(BashCommand)\n BashCommand = 'echo \"%s\" > obj_%d/chi2.txt'%\\\n (DataArray['chi2'][All_chi2_index_sorted[i]], \\\n i+1)\n print(BashCommand)\n os.system(BashCommand)\n BashCommand = 'echo \"%s\" > obj_%d/line_number.txt'%\\\n (All_chi2_index_sorted[i]+1, \\\n i+1)\n print(BashCommand)\n os.system(BashCommand)\n # \n # check\n #cd obj_8/; /Users/dzliu/Cloud/Github/Crab.Toolkit.michi2/bin/michi2_read_lib_SED ../lib.DL07.LoExCom.SED 140140 16.1932 SED_LIB4\n #/Users/dzliu/Cloud/Github/Crab.Toolkit.michi2/bin/michi2_read_lib_SEDs.py fit_5.out 2451 c_2451\n #topcat -f ASCII c_2451/SED_LIB4 obj_8/SED_LIB4 &\n #checked that the two code give exactly the same result!\n #\n # how about the integrated IR luminosity?\n #cat obj_8/SED_LIB4.vLv_8_1000 # 8.8442327616e+03\n #cd obj_8\n #sm\n #load astroSfig.sm\n #data SED_LIB4 read {x 1 y 2}\n #calc_ltir x y # 3536.147921\n #calc 10**2.339198 * 16.1932 # 3536.150006 -- 2.339198 is the PAR3 in lib file, agreed with our manual integration! \n # \n # \n # Wait for a long time\n # \n # Then plot SEDs\n Redshift = float(InfoDict['REDSHIFT'])\n Color_list = ['cyan', 'gold', 'red', 'blue', 'purple']\n Plot_engine = CrabPlot(figure_size=(8.0,5.0))\n Plot_engine.set_margin(top=0.92, bottom=0.16, left=0.12, right=0.96)\n Count_label_chi2 = 0 # to count the chi-square label printed on the figure, make sure there are not too many labels.\n Count_plot_chi2 = 0\n for i in range(Cut_chi2_number-1,-1,-1):\n # \n # skip solutions between 11th to last 11th.\n #if i > Plot_chi2_max_number/2 and i<(Cut_chi2_number-1-Plot_chi2_max_number/2):\n # continue\n if not ('%d'%i) in Plot_chi2_index_dict:\n continue\n # \n # alpha by chi2\n print('Plotting chi2=%s obj_%d'%(Cut_chi2_array[i], i+1))\n Min_chi2_log = numpy.log10(Min_chi2)\n Max_chi2_log = numpy.log10(Max_chi2)\n Min_chi2_for_plot = numpy.power(10, Min_chi2_log-(Max_chi2_log-Min_chi2_log)*0.8)\n Max_chi2_for_plot = numpy.power(10, Max_chi2_log+(Max_chi2_log-Min_chi2_log)*0.3)\n Plot_chi2_alpha = Plot_engine.get_color_by_value([Min_chi2_for_plot, Max_chi2_for_plot], \n input_value=Cut_chi2_array[i], \n log=1, \n cmap=matplotlib.cm.get_cmap('gray_r'))[0]\n #print('Plot_chi2_alpha: ', Plot_chi2_alpha)\n # \n # \n for j in range(int(InfoDict['NLIB'])):\n xclip = None\n if j == 0: xclip = [(50,numpy.inf)]\n elif j == 4: xclip = [(-numpy.inf,2e3)]\n Plot_engine.plot_data_file('obj_%d/SED_LIB%d'%(i+1,j+1), xlog=1, ylog=1, xclip=xclip, current=1, \\\n dataname='obj_%d_SED_LIB%d'%(i+1,j+1), \n redshift = Redshift, \n linestyle='dashed', linewidth=Plot_chi2_linewidth, color=Color_list[j], alpha=Plot_chi2_alpha)\n # \n #<20180114># obj_SED_1 = Plot_engine.Plot_data['obj_%d_SED_LIB1'%(i+1)]\n #<20180114># obj_SED_2 = Plot_engine.Plot_data['obj_%d_SED_LIB2'%(i+1)]\n #<20180114># obj_SED_3 = Plot_engine.Plot_data['obj_%d_SED_LIB3'%(i+1)]\n #<20180114># obj_SED_4 = Plot_engine.Plot_data['obj_%d_SED_LIB4'%(i+1)]\n #<20180114># obj_SED_5 = Plot_engine.Plot_data['obj_%d_SED_LIB5'%(i+1)]\n #<20180114># obj_SED_sum_x_lg = numpy.arange(-2,6,0.001) # wavelength_um grid\n #<20180114># obj_SED_sum_x = numpy.power(10, obj_SED_sum_x_lg) # make it in linear space\n #<20180114># obj_SED_sum_y = []\n #<20180114># for j in range(int(InfoDict['NLIB'])):\n #<20180114># obj_SED_single_x = Plot_engine.Plot_data['obj_%d_SED_LIB%d'%(i+1,j+1)][:,0]\n #<20180114># obj_SED_single_y = Plot_engine.Plot_data['obj_%d_SED_LIB%d'%(i+1,j+1)][:,1]\n #<20180114># obj_SED_spline_y = Plot_engine.spline(obj_SED_single_x, obj_SED_single_y, obj_SED_sum_x_lg, xlog=1, ylog=1, outputxlog=0)\n #<20180114># if j == 0:\n #<20180114># obj_SED_sum_y = obj_SED_spline_y\n #<20180114># else:\n #<20180114># obj_SED_sum_y = obj_SED_sum_y + obj_SED_spline_y\n # \n #pprint(obj_SED_sum_y)\n #print(numpy.column_stack((obj_SED_sum_x, obj_SED_sum_y)))\n #print(Cut_chi2_array[i])\n Min_chi2_for_plot = numpy.power(10, Min_chi2_log-(Max_chi2_log-Min_chi2_log)*0.05)\n Max_chi2_for_plot = numpy.power(10, Max_chi2_log+(Max_chi2_log-Min_chi2_log)*0.85)\n Color_chi2 = Plot_engine.get_color_by_value([Min_chi2_for_plot, Max_chi2_for_plot], \n input_value=Cut_chi2_array[i], \n log=1, \n cmap=matplotlib.cm.get_cmap('gray'))\n #print('Color_chi2: ', Color_chi2)\n #Plot_engine.plot_line(obj_SED_sum_x, obj_SED_sum_y, current=1, color=Color_chi2)\n Plot_engine.plot_data_file('obj_%d/SED_SUM'%(i+1), xlog=1, ylog=1, current=1, \\\n dataname='obj_%d_SED_SUM'%(i+1), \n redshift = Redshift, \n linestyle='solid', linewidth=Plot_SED_linewidth, color=Color_chi2, alpha=1.0, zorder=8) # alpha=Plot_chi2_alpha\n Count_plot_chi2 = Count_plot_chi2 + 1\n # \n # show chi2 on the figure\n if not SetOnlyPlotBestSED:\n if i == Cut_chi2_number-1:\n Plot_engine.xyouts(0.05, 0.95, '$\\chi^2:$', NormalizedCoordinate=True, useTex=True)\n if i == 0:\n Plot_engine.xyouts(0.09, 0.95-0.03*(Count_label_chi2), '......', NormalizedCoordinate=True, color=Color_chi2)\n Count_label_chi2 = Count_label_chi2 + 1\n if Count_plot_chi2 % int((Cut_chi2_number/7)+1) == 0 or i == 0 or i == Cut_chi2_number-1:\n #print('Plotting label at', 0.09, 0.95-0.03*(Cut_chi2_number-1-i), 'chi2 = %.1f'%(Cut_chi2_array[i]))\n Plot_engine.xyouts(0.09, 0.95-0.03*(Count_label_chi2), '%.1f'%(Cut_chi2_array[i]), NormalizedCoordinate=True, useTex=True, color=Color_chi2)\n Count_label_chi2 = Count_label_chi2 + 1\n # \n # show redshift (z) on the figure\n if not SetOnlyPlotBestSED:\n if i == 0:\n Plot_engine.xyouts(0.15, 0.95, '$z=%s$'%(Redshift), NormalizedCoordinate=True, useTex=True)\n else:\n if i == 0 and SourceName != '':\n Plot_engine.xyouts(0.05, 0.90, SourceName, NormalizedCoordinate=True, useTex=True, fontsize=15)\n Plot_engine.xyouts(0.20, 0.90, '$z=%s$'%(Redshift), NormalizedCoordinate=True, useTex=True, fontsize=15)\n #break\n # \n # Then plot OBS data points\n DataTable_obs = asciitable.read(InfoDict['OBS'])\n #print(type(DataTable_obs))\n try:\n Wavelength_obs = DataTable_obs[DataTable_obs.colnames[0]].data\n Flux_obs = DataTable_obs[DataTable_obs.colnames[1]].data\n FluxErr_obs = DataTable_obs[DataTable_obs.colnames[2]].data\n Detection_mask = (Flux_obs>=2.0*FluxErr_obs)\n UpperLimits_mask = (Flux_obs<2.0*FluxErr_obs)\n #print(Wavelength_obs)\n Plot_engine.plot_xy(Wavelength_obs[Detection_mask], Flux_obs[Detection_mask], yerr=FluxErr_obs[Detection_mask], dataname='obs', overplot=True, symbol='open square', symsize=3, thick=1.5, capsize=4, zorder=10)\n Plot_engine.plot_xy(Wavelength_obs[UpperLimits_mask], 3.0*FluxErr_obs[UpperLimits_mask], dataname='upper limits', overplot=True, symbol='upper limits', symsize=3, thick=1.25, alpha=0.5, zorder=9)\n except Exception as err:\n print(err)\n # \n Plot_engine.set_xrange([0.1,1e6])\n Plot_engine.set_yrange([1e-6,1e4])\n if len(PlotYRange) == 2:\n Plot_engine.set_yrange(PlotYRange)\n Plot_engine.set_xtitle('Observing-frame wavelength [um]')\n Plot_engine.set_ytitle('Flux density [mJy]')\n Plot_engine.savepdf(Output_name+'.pdf')\n #Plot_engine.show()\n Plot_engine.close()\n print('Output to \"%s\"!'%(Output_name+'.pdf'))\n # \n # \n # \n # \n # \n # \n # \n ###############################################################\n # Now plot another figure of chi-square distribution analysis #\n ###############################################################\n # \n # Now we analyze the following quantities in the big chi-square data table 'DataTable'\n # -- stellar mass\n Stellar_mass_dict = {}\n LTIR_warm_dust_dict = {}\n LTIR_cold_dust_dict = {}\n Umin_warm_dust_dict = {}\n Umin_cold_dust_dict = {}\n Mass_warm_dust_dict = {}\n Mass_cold_dust_dict = {}\n Lumin_AGN_dict = {}\n LTIR_total_dust_dict = {}\n Mass_total_dust_dict = {}\n fPDR_total_dust_dict = {}\n Umean_total_dust_dict = {}\n # \n # define constants\n pi = numpy.pi\n dL = 1.0/(4*pi) # if Redshift is not given, then we do not apply 4*pi*dL**2 to the quantities below. \n Redshift = float(InfoDict['REDSHIFT'])\n print('z = %s'%(Redshift))\n if Redshift > 0.0:\n lumdist_command = '%s/lumdist'%(os.path.dirname(os.path.realpath(__file__)))\n if not os.path.isfile(lumdist_command):\n print('Error! \"lumdist\" command was not found at %s! Maybe you have not fully downloaded the code from \"https://github.com/1054/Crab.Toolkit.michi2\"?')\n print('We need that to compute the luminosity distance!')\n sys.exit()\n dL_command = '%s -simple %s'%(lumdist_command, Redshift)\n dL_str = os.popen(dL_command).read()\n #print(dL_str)\n if dL_str == '':\n print('Error! Failed to run \"lumdist\" in the Terminal! Sorry! TODO: You can set \"dL = ...\" in \"%s\".'%(InfoFile))\n print('We need that to compute the luminosity distance!')\n sys.exit()\n dL = float(dL_str)\n print('dL = %s [Mpc]'%(dL))\n # \n # get parameter list for each lib\n Lib_number = int(InfoDict['NLIB'])\n Lib_params = {}\n Num_params = {}\n Col_number = 2+2*Lib_number+1 # this quantity indicates the column number in the big chi-square data table. The first two columns are always i0 and chi2, so the LIB params start from column 3.\n for j in range(Lib_number):\n Lib_name = 'LIB%d'%(j+1)\n Lib_dict = CrabTableReadInfo(InfoDict[Lib_name], verbose=0)\n #print(Lib_dict)\n # \n # read the number of parameters from the SED LIB file\n Key_NPAR = '# NPAR'\n if Key_NPAR in Lib_dict:\n Num_params[Lib_name] = int(Lib_dict[Key_NPAR])\n else:\n print(\"Error! \\\"%s\\\" was not found in \\\"%s\\\"!\"%(Key_NPAR, InfoDict[Lib_name]))\n sys.exit()\n # \n # read the title of each parameter from the SED LIB file\n Lib_params[Lib_name] = []\n for k in range(Num_params[Lib_name]):\n Key_TPAR = '# TPAR%d'%(k+1)\n if Key_TPAR in Lib_dict:\n Lib_params[Lib_name].append(Lib_dict[Key_TPAR])\n else:\n print(\"Error! \\\"%s\\\" was not found in \\\"%s\\\"!\"%(Key_TPAR, InfoDict[Lib_name]))\n sys.exit()\n # \n # check stellar mass\n if InfoDict[Lib_name].find('BC03.Padova1994') >= 0:\n if 'Mass' == Lib_dict[Key_TPAR]:\n # Stellar mass SED library Y column unit is solar luminosity per Hertz, \n # flux unit is mJy, \n # \n Stellar_mass_dict['Lib_file'] = InfoDict[Lib_name]\n Stellar_mass_dict['Lib_name'] = Lib_name\n Stellar_mass_dict['Lib_numb'] = j+1\n Stellar_mass_dict['Par_name'] = '$\\log \\ M_{*}$ [$\\mathrm{M}_{\\odot}$]' # Lib_dict[Key_TPAR]\n Stellar_mass_dict['Par_file'] = 'Mstar'\n Stellar_mass_dict['Col_numb'] = Col_number\n Stellar_mass_dict['Log_calc'] = True\n Stellar_mass_dict['range'] = numpy.power(10,[8.0,13.5])\n Stellar_mass_dict['value'] = DataArray['a%d'%(j+1)] / (3.839e33*1e26/(4*pi*dL**2*9.52140e48)) * DataTable.getColumn(Col_number) / (1+Redshift)\n Stellar_mass_dict['chisq'] = DataArray['chi2']\n elif InfoDict[Lib_name].find('DL07.HiExCom') >= 0:\n if 'lgLTIR' == Lib_dict[Key_TPAR]:\n LTIR_warm_dust_dict['Lib_file'] = InfoDict[Lib_name]\n LTIR_warm_dust_dict['Lib_name'] = Lib_name\n LTIR_warm_dust_dict['Lib_numb'] = j+1\n LTIR_warm_dust_dict['Par_name'] = '$\\log \\ L_{\\mathrm{IR}}$ (warm) [$\\mathrm{L}_{\\odot}$]' # Lib_dict[Key_TPAR]\n LTIR_warm_dust_dict['Par_file'] = 'LIR_warm'\n LTIR_warm_dust_dict['Col_numb'] = Col_number\n LTIR_warm_dust_dict['Log_calc'] = True\n LTIR_warm_dust_dict['range'] = numpy.power(10,[9.0,14.5])\n LTIR_warm_dust_dict['value'] = DataArray['a%d'%(j+1)] * numpy.power(10,DataTable.getColumn(Col_number)) * 4*pi*dL**2 / (1+Redshift) # Note that we need to carefully convert lgLTIR from log space to LIR in linear space, and apply the normalization.\n LTIR_warm_dust_dict['chisq'] = DataArray['chi2']\n elif 'Umin' == Lib_dict[Key_TPAR]:\n Umin_warm_dust_dict['Lib_file'] = InfoDict[Lib_name]\n Umin_warm_dust_dict['Lib_name'] = Lib_name\n Umin_warm_dust_dict['Lib_numb'] = j+1\n Umin_warm_dust_dict['Par_name'] = '$U_{\\mathrm{min}}$ (warm)' # Lib_dict[Key_TPAR]\n Umin_warm_dust_dict['Par_file'] = 'Umin_warm'\n Umin_warm_dust_dict['Col_numb'] = Col_number\n Umin_warm_dust_dict['Log_plot'] = True # 'Log_plot', plot X axis in log scale\n Umin_warm_dust_dict['range'] = [0.08,30.0]\n Umin_warm_dust_dict['value'] = DataTable.getColumn(Col_number)\n Umin_warm_dust_dict['chisq'] = DataArray['chi2']\n # \n Mass_warm_dust_dict['Lib_file'] = InfoDict[Lib_name]\n Mass_warm_dust_dict['Lib_name'] = Lib_name\n Mass_warm_dust_dict['Lib_numb'] = j+1\n Mass_warm_dust_dict['Par_name'] = '$\\log \\ M_{\\mathrm{dust}}$ (warm) [$\\mathrm{M}_{\\odot}$]'\n Mass_warm_dust_dict['Par_file'] = 'Mdust_warm'\n Mass_warm_dust_dict['Col_numb'] = 2+2*(j+1)\n Mass_warm_dust_dict['Log_calc'] = True\n Mass_warm_dust_dict['range'] = numpy.power(10,[7.0,12.0])\n Mass_warm_dust_dict['value'] = DataArray['a%d'%(j+1)] * dL**2 / (1+Redshift) # Mdust #NOTE# no need to multiply a '4*pi'!\n Mass_warm_dust_dict['chisq'] = DataArray['chi2']\n # \n elif InfoDict[Lib_name].find('DL07.LoExCom') >= 0:\n if 'lgLTIR' == Lib_dict[Key_TPAR]:\n LTIR_cold_dust_dict['Lib_file'] = InfoDict[Lib_name]\n LTIR_cold_dust_dict['Lib_name'] = Lib_name\n LTIR_cold_dust_dict['Lib_numb'] = j+1\n LTIR_cold_dust_dict['Par_name'] = '$\\log \\ L_{\\mathrm{IR}}$ (cold) [$\\mathrm{L}_{\\odot}$]' # Lib_dict[Key_TPAR]\n LTIR_cold_dust_dict['Par_file'] = 'LIR_cold'\n LTIR_cold_dust_dict['Col_numb'] = Col_number\n LTIR_cold_dust_dict['Log_calc'] = True\n LTIR_cold_dust_dict['range'] = numpy.power(10,[9.0,14.5])\n LTIR_cold_dust_dict['value'] = DataArray['a%d'%(j+1)] * numpy.power(10,DataTable.getColumn(Col_number)) * 4*pi*dL**2 / (1+Redshift) # Note that we need to carefully convert lgLTIR from log space to LIR in linear space, and apply the normalization.\n LTIR_cold_dust_dict['chisq'] = DataArray['chi2']\n elif 'Umin' == Lib_dict[Key_TPAR]:\n Umin_cold_dust_dict['Lib_file'] = InfoDict[Lib_name]\n Umin_cold_dust_dict['Lib_name'] = Lib_name\n Umin_cold_dust_dict['Lib_numb'] = j+1\n Umin_cold_dust_dict['Par_name'] = '$U_{\\mathrm{min}}$ (cold)' # Lib_dict[Key_TPAR]\n Umin_cold_dust_dict['Par_file'] = 'Umin_cold'\n Umin_cold_dust_dict['Col_numb'] = Col_number\n Umin_cold_dust_dict['Log_plot'] = True # 'Log_plot', plot X axis in log scale\n Umin_cold_dust_dict['range'] = [0.08,30.0]\n Umin_cold_dust_dict['value'] = DataTable.getColumn(Col_number)\n Umin_cold_dust_dict['chisq'] = DataArray['chi2']\n # \n Mass_cold_dust_dict['Lib_file'] = InfoDict[Lib_name]\n Mass_cold_dust_dict['Lib_name'] = Lib_name\n Mass_cold_dust_dict['Lib_numb'] = j+1\n Mass_cold_dust_dict['Par_name'] = '$\\log \\ M_{\\mathrm{dust}}$ (cold) [$\\mathrm{M}_{\\odot}$]'\n Mass_cold_dust_dict['Par_file'] = 'Mdust_cold'\n Mass_cold_dust_dict['Col_numb'] = 2+2*(j+1)\n Mass_cold_dust_dict['Log_calc'] = True\n Mass_cold_dust_dict['range'] = numpy.power(10,[7.0,12.0])\n Mass_cold_dust_dict['value'] = DataArray['a%d'%(j+1)] * dL**2 / (1+Redshift) # Mdust # Mdust #NOTE# no need to multiply a '4*pi'!\n Mass_cold_dust_dict['chisq'] = DataArray['chi2']\n elif InfoDict[Lib_name].find('MullaneyAGN') >= 0 or \\\n InfoDict[Lib_name].find('SiebenmorgenAGN') >= 0:\n # Mullaney AGN\n # by integrating the AGN template (AGN_TYPE=2) from 1um to 1000um, we get an integration of 5133.913101\n if 'AGN_TYPE' == Lib_dict[Key_TPAR].upper():\n Lumin_AGN_dict['Lib_file'] = InfoDict[Lib_name]\n Lumin_AGN_dict['Lib_name'] = Lib_name\n Lumin_AGN_dict['Lib_numb'] = j+1\n Lumin_AGN_dict['Par_name'] = '$\\log \\ L_{\\mathrm{AGN}}$ [$\\mathrm{L}_{\\odot}$]' # Lib_dict[Key_TPAR]\n Lumin_AGN_dict['Par_file'] = 'LAGN'\n Lumin_AGN_dict['Col_numb'] = Col_number\n Lumin_AGN_dict['Log_calc'] = True\n Lumin_AGN_dict['range'] = numpy.power(10,[0.0,14.5])\n Lumin_AGN_dict['value'] = DataArray['a%d'%(j+1)] * 5133.913101 * 4*pi*dL**2 / (1+Redshift) # Note that we need to carefully convert lgLTIR from log space to LIR in linear space, and apply the normalization.\n Lumin_AGN_dict['chisq'] = DataArray['chi2']\n # \n # \n # count the column number in the big chi-square data table. All params in each LIB are listed in the big chi-square data table.\n Col_number = Col_number + 1\n # \n # Total LIR\n if 'value' in LTIR_warm_dust_dict and 'value' in LTIR_cold_dust_dict:\n LTIR_total_dust_dict = copy(LTIR_warm_dust_dict)\n LTIR_total_dust_dict['value'] = LTIR_warm_dust_dict['value'] + LTIR_cold_dust_dict['value']\n LTIR_total_dust_dict['Lib_file'] = [LTIR_warm_dust_dict['Lib_file'], LTIR_cold_dust_dict['Lib_file']]\n LTIR_total_dust_dict['Lib_name'] = [LTIR_warm_dust_dict['Lib_name'], LTIR_cold_dust_dict['Lib_name']]\n LTIR_total_dust_dict['Col_numb'] = [LTIR_warm_dust_dict['Col_numb'], LTIR_cold_dust_dict['Col_numb']]\n LTIR_total_dust_dict['Par_name'] = '$\\log \\ L_{\\mathrm{IR}}$ (total) [$\\mathrm{L}_{\\odot}$]'\n LTIR_total_dust_dict['Par_file'] = 'LIR_total'\n # \n # Total Mdust\n if 'value' in Mass_warm_dust_dict and 'value' in Mass_cold_dust_dict:\n Mass_total_dust_dict = copy(Mass_warm_dust_dict)\n Mass_total_dust_dict['value'] = Mass_warm_dust_dict['value'] + Mass_cold_dust_dict['value']\n Mass_total_dust_dict['Lib_file'] = [Mass_warm_dust_dict['Lib_file'], Mass_cold_dust_dict['Lib_file']]\n Mass_total_dust_dict['Lib_name'] = [Mass_warm_dust_dict['Lib_name'], Mass_cold_dust_dict['Lib_name']]\n Mass_total_dust_dict['Col_numb'] = [Mass_warm_dust_dict['Col_numb'], Mass_cold_dust_dict['Col_numb']]\n Mass_total_dust_dict['Par_name'] = '$\\log \\ M_{\\mathrm{dust}}$ (total) [$\\mathrm{M}_{\\odot}$]'\n Mass_total_dust_dict['Par_file'] = 'Mdust_total'\n # \n # Total fPDR Umean\n # the Draine & Li 2007 IRSF (interstellar radiation field) model is like Dale 2005, \n # LoExComponent has a ISRF (or U) of Umin * G0, while\n # HiExComponent has ISRF (or U) described by a exponential function within range of Umin and Umax, \n # usually Umax is fixed to 1e6 * G0, and the slope of exponential function is fixed to -2. \n # So the mean U value can be computed by \n # \n # (1-gamma) * Umin + gamma * Umin * (ln(1e6/Umin)/(1-Umin/1e6))\n # \n # in which, gamma = aoe_Hi / (aoe_Lo+aoe_Hi) = a2/(a1+a2) = Mdust2/(Mdust1+Mdust2)\n # \n # e.g. Aniano et al. 2012\n # \n if 'value' in Mass_warm_dust_dict and 'value' in Mass_cold_dust_dict:\n fPDR_total_dust_dict = copy(Umin_warm_dust_dict)\n fPDR_total_dust_dict['value'] = Mass_warm_dust_dict['value'] / (Mass_warm_dust_dict['value'] + Mass_cold_dust_dict['value'])\n fPDR_total_dust_dict['Lib_file'] = [Mass_warm_dust_dict['Lib_file'], Mass_cold_dust_dict['Lib_file']]\n fPDR_total_dust_dict['Lib_name'] = [Mass_warm_dust_dict['Lib_name'], Mass_cold_dust_dict['Lib_name']]\n fPDR_total_dust_dict['Col_numb'] = [Mass_warm_dust_dict['Col_numb'], Mass_cold_dust_dict['Col_numb']]\n fPDR_total_dust_dict['Par_name'] = '$\\log \\ \\delta_{\\mathrm{PDR}}$ (total)'\n fPDR_total_dust_dict['Par_file'] = 'fPDR_total'\n fPDR_total_dust_dict['Log_calc'] = True\n fPDR_total_dust_dict['range'] = [1e-4,1.0]\n # \n if 'value' in Mass_warm_dust_dict and 'value' in Mass_cold_dust_dict:\n Umean_total_dust_dict = copy(Umin_warm_dust_dict)\n Umean_total_dust_dict['value'] = (1-fPDR_total_dust_dict['value']) * Umin_cold_dust_dict['value'] + fPDR_total_dust_dict['value'] * Umin_warm_dust_dict['value'] * (numpy.log(1e6/Umin_warm_dust_dict['value'])/(1-Umin_warm_dust_dict['value']/1e6))\n Umean_total_dust_dict['Lib_file'] = [Mass_warm_dust_dict['Lib_file'], Mass_cold_dust_dict['Lib_file']]\n Umean_total_dust_dict['Lib_name'] = [Mass_warm_dust_dict['Lib_name'], Mass_cold_dust_dict['Lib_name']]\n Umean_total_dust_dict['Col_numb'] = [Mass_warm_dust_dict['Col_numb'], Mass_cold_dust_dict['Col_numb']]\n Umean_total_dust_dict['Par_name'] = '$\\\\left$ (total)'\n Umean_total_dust_dict['Par_file'] = 'Umean_total'\n Umean_total_dust_dict['range'] = [0.08,50.0]\n # \n # analyze \n print('Num_params', Num_params)\n print('Lib_params', Lib_params)\n Plot_engine = CrabPlot(figure_size=(14.0,10.0))\n Plot_engine.set_margin(panel=0, top=0.96, bottom=0.04, left=0.06, right=0.96)\n if 'value' in Stellar_mass_dict:\n analyze_chisq_distribution(Stellar_mass_dict, Plot_engine = Plot_engine)\n if 'value' in Lumin_AGN_dict:\n analyze_chisq_distribution(Lumin_AGN_dict, Plot_engine = Plot_engine)\n if 'value' in Umin_warm_dust_dict:\n analyze_chisq_distribution(Umin_warm_dust_dict, Plot_engine = Plot_engine)\n if 'value' in Umin_cold_dust_dict:\n analyze_chisq_distribution(Umin_cold_dust_dict, Plot_engine = Plot_engine)\n if 'value' in LTIR_warm_dust_dict:\n print(LTIR_warm_dust_dict)\n analyze_chisq_distribution(LTIR_warm_dust_dict, Plot_engine = Plot_engine)\n if 'value' in LTIR_cold_dust_dict:\n analyze_chisq_distribution(LTIR_cold_dust_dict, Plot_engine = Plot_engine)\n if 'value' in Mass_warm_dust_dict:\n analyze_chisq_distribution(Mass_warm_dust_dict, Plot_engine = Plot_engine)\n if 'value' in Mass_cold_dust_dict:\n analyze_chisq_distribution(Mass_cold_dust_dict, Plot_engine = Plot_engine)\n if 'value' in LTIR_total_dust_dict:\n analyze_chisq_distribution(LTIR_total_dust_dict, Plot_engine = Plot_engine)\n if 'value' in Mass_total_dust_dict:\n analyze_chisq_distribution(Mass_total_dust_dict, Plot_engine = Plot_engine)\n if 'value' in fPDR_total_dust_dict:\n analyze_chisq_distribution(fPDR_total_dust_dict, Plot_engine = Plot_engine)\n if 'value' in Umean_total_dust_dict:\n analyze_chisq_distribution(Umean_total_dust_dict, Plot_engine = Plot_engine)\n Plot_engine.savepdf(Output_name+'.chisq.pdf')\n #Plot_engine.show()\n Plot_engine.close()\n print('Output to \"%s\"!'%(Output_name+'.chisq.pdf'))\n # \n \n\n\n\n\n\n\n","sub_path":"bin/michi2_plot_SED_fitting_results (backup 20180202 00h00m).py","file_name":"michi2_plot_SED_fitting_results (backup 20180202 00h00m).py","file_ext":"py","file_size_in_byte":47039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"41080601","text":"################## METADATA ##################\n# NAME: Mert Saraç\n# USERNAME: a18mersa\n# COURSE: Scriptprogramming IT384G - Spring 2019\n# ASSIGNMENT: Assignment 1 - Python\n# DATE OF LAST CHANGE: 20190507\n##############################################\n\nimport pwd\nfrom systemd import login\n\ndef listusers():\n #get all users' info\n allusers = pwd.getpwall()\n #get all current sessions\n sessions = login.uids()\n #create a list to keep the users\n users = []\n\n #sorted all users by their uid\n for user in sorted(allusers, key=lambda i: i.pw_uid):\n #if '_' does not exist at the beginning of the user name,\n if not user.pw_name.startswith('_'):\n #if sessions list contains this user's uid, set logged_in as true, otherwise set it as false\n if str(user.pw_uid) in sessions:\n logged_in = True\n else:\n logged_in = False\n\n #add this user's info to 'users'\n users.append(\n {\"uid\" : user.pw_uid,\n \"name\" : user.pw_name,\n \"shell\" : user.pw_shell,\n \"logged_in\" : logged_in}\n )\n return users\n\n#call listusers method\nusers = listusers()\n\n#print users' info\nfor user in users:\n logged = \" \"\n if user[\"logged_in\"] is True:\n logged = \"*\"\n\n print(\"{:s} | {:>5d} | {:20s} | {:s}\".format(logged, user[\"uid\"], user[\"name\"], user[\"shell\"]))\n","sub_path":"script/partB/listusers.py","file_name":"listusers.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"145142430","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport re\nimport pymysql\nfrom scrapy import Request\nfrom urllib import parse\nfrom tatoeba.items import TatoebaItem\n\n\nclass FanyiSpider(scrapy.Spider):\n name = 'fanyi'\n #allowed_domains = ['sss']\n db = pymysql.Connect(host='127.0.0.1', user='root', password='18351962092', db='frequentwords')\n cursor = db.cursor()\n sql = 'select * from zh_full limit 0,50000'\n cursor.execute(sql)\n results = cursor.fetchall()\n start_urls = [f'https://tatoeba.org/eng/sentences/search?from=cmn&to=eng&query={parse.quote(row[0])}' for row in results]\n headers = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n #'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'zh-CN,zh;q=0.9',\n 'cache-control': 'max-age=0',\n 'cookie': 'CakeCookie=%7B%22interfaceLanguage%22%3A%22eng%22%7D; _ga=GA1.2.97595289.1550655280; CAKEPHP=cp1omj6ji7cep2g4srn2ahie23; csrfToken=14625be2280f85b4672fd43a8faa0703980990127c96d9a635fbaf7fb8d8d7bfdfdce68795c65fe1b89f2bf2a09ab7468041328ab7715bcc9dc60f69ab1e27de; _gid=GA1.2.1119544150.1550799914',\n #'referer': 'https://tatoeba.org/eng/sentences/search?query=%E6%88%91&from=und&to=und',\n #'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n }\n\n def start_requests(self):\n for url in self.start_urls:\n yield Request(url=url, callback=self.parse, headers=self.headers, dont_filter=True, meta={'tag': 0})\n\n def parse(self, response):\n try:\n sentenceCount = int(re.findall('\\((\\d+).*?result', response.text)[0])\n except IndexError:\n # 没有这个词的句子就把页数当作零\n sentenceCount = 0\n pageNum = sentenceCount // 10 if sentenceCount % 10 == 0 else sentenceCount // 10 + 1\n for i in range(pageNum):\n url = response.url + f'&page={str(i + 1)}' if i != 0 else response.url\n host = '127.0.0.1'\n user = 'root'\n passwd = '18351962092'\n dbname = 'tatoebaUrl'\n tablename = 'url'\n db = pymysql.connect(host, user, passwd, dbname)\n cursor = db.cursor()\n sql = f\"select * from {tablename}\"\n cursor.execute(sql)\n results = cursor.fetchall()\n db.commit()\n cursor.close()\n db.close()\n urls = []\n for row in results:\n urls.append(row[0])\n # 如果链接内容已经爬取过,那么不爬\n if url not in urls:\n yield Request(url=url, callback=self.parsePlus, headers=self.headers, dont_filter=True, meta={'tag': 0})\n\n def parsePlus(self, response):\n selectors = response.xpath('//div[@class=\"sentence-and-translations\"]')\n for selector in selectors:\n list = [x.strip('\\n').strip() for x in selector.re('([\\s\\S]*?)
')[1:]]\n for x in list:\n item = TatoebaItem()\n item['chinese'] = selector.xpath('string(.//div[@class=\"text\"])').extract_first().strip('\\n').strip()\n item['target'] = x\n item['language'] = 'english'\n yield item\n\n\n\n","sub_path":"tatoeba/spiders/fanyi.py","file_name":"fanyi.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"302466658","text":"import logging\nimport copy\nimport json\nimport os\nimport json\nimport logging\nimport uuid\nimport copy\n\nfrom packtivity.syncbackends import build_job, packconfig, build_env\n\nlog = logging.getLogger(__name__)\n\ndef render_process(spec, local_pars):\n log.info('param object %s', local_pars)\n log.info('local pars: \\n%s',json.dumps(local_pars.json(), indent=4))\n log.info('rendering process with local pars: {}'.format(local_pars.json()))\n\n job = build_job(spec, local_pars, None, packconfig())\n log.info(job)\n\n script = '''cat << 'EOF' | {}\\n{}\\nEOF\\n'''\n return {\n 'command': job['command'] if 'command' in job else script.format(\n job['interpreter'],\n job['script'])\n }\n\ndef make_external_job(spec,parameters, state):\n spec = copy.deepcopy(spec)\n parcopy = copy.deepcopy(parameters)\n jsonpars = copy.deepcopy(parcopy.json())\n\n setup_spec, local_pars = state.make_local_pars(parcopy)\n spec['environment'] = build_env(spec['environment'], local_pars, state, packconfig())\n\n rendered_process = render_process(spec['process'], local_pars)\n\n sequence = {\n 'sequence': ['setup', 'payload', 'teardown'],\n 'setup': {\n 'iscfg': True,\n 'cmd': [\"/code/datamgmt/stage_in.py\", \"/jobconfig/jobconfig.json\",\"/comms/script.sh\"],\n 'image': 'lukasheinrich/datamgmt'\n },\n 'payload': {\n 'iscfg': False,\n 'cmd': [\"sh\", \"/comms/script.sh\"],\n 'image': ':'.join([\n spec['environment']['image'],\n spec['environment']['imagetag']\n ])\n },\n 'teardown': {\n 'iscfg': True,\n 'cmd': [\"/code/datamgmt/stage_out.py\",\"/jobconfig/jobconfig.json\"],\n 'image': 'lukasheinrich/datamgmt'\n },\n 'config_mounts': {\n 'comms': '/comms',\n 'jobconfig': '/jobconfig'\n },\n 'config_env': [{\n \"name\": \"YDGCONFIG\",\n \"value\": \"/jobconfig/ydgconfig.json\",\n }]\n }\n\n jobspec = {\n \"sequence_spec\": sequence,\n \"publisher_spec\": spec['publisher'],\n \"rendered_process\": rendered_process,\n \"setup_spec\": setup_spec,\n \"local_workdir\": state.local_workdir,\n \"local_pars\": local_pars.json(),\n #... \n \"spec\": spec,\n \"parameters\": jsonpars,\n \"state\": state.json(),\n }\n\n log.info('parspec spec\\n%s',json.dumps(jobspec['parameters'], indent=4))\n log.info('job spec\\n%s',json.dumps(jobspec, indent=4))\n return jobspec\n","sub_path":"plugins/yadage-extresult/yadageextresult/jobspec.py","file_name":"jobspec.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"547424664","text":"import re\nimport os\n\n\ndef load_file(filename):\n with open(filename) as f:\n data_x = []\n data_y = []\n negative = False\n for line in f:\n if negative is False and re.match(r\"^(\\d|-).+,\", line) is not None:\n line_split = line.split(\", \")\n data_x.append(float(line_split[0]))\n data_y.append(float(line_split[1]))\n if negative is True and re.match(r\"^(\\d|-).+,\", line) is not None:\n line_split = line.split(\", \")\n data_x.append(float(line_split[0]))\n data_y.append(float(line_split[1]))\n if line.startswith(\"Negative\"):\n negative = True\n return data_x, data_y\n\n\ndef load_files(path):\n for f in os.listdir(path):\n if f.lower().endswith(\".txt\"):\n p = os.path.join(path, f)\n print(\"load file {0}......\".format(p))\n yield load_file(p), f.split('.')[0]\n yield None, None\n\n\ndef load_head(filename):\n with open(filename) as f:\n head = \"\"\n for line in f:\n if line.startswith(\"#\"):\n break\n head += line.strip() + '\\n'\n return head\n\n\nif __name__ == '__main__':\n print(load_head('sample.txt'))\n f = load_files(\"samples\")\n while True:\n filename = next(f)[-1]\n if filename is None:\n break\n print(filename)\n","sub_path":"offline/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"287785454","text":"\n#Game developed in Trinket for running in Raspberry Pi\n\nfrom turtle import *\nfrom random import randint\n\nspeed(0)\npenup()\ngoto(-140, 140)\n\nfor step in range (16):\n \n write (step, align='center') \n right(90)\n forward(10)\n pendown()\n forward(150)\n penup()\n backward(160)\n left(90)\n forward(20)\n \nada=Turtle()\nada.color('red')\nada.shape('turtle')\n\nada.penup()\nada.goto(-160, 100)\nada.pendown()\n\nbob=Turtle()\nbob.color('blue')\nbob.shape('turtle')\n\nbob.penup()\nbob.goto(-160, 50)\nbob.pendown()\n\ndan=Turtle()\ndan.color('green')\ndan.shape('turtle')\n\ndan.penup()\ndan.goto(-160, 0)\ndan.pendown()\n\nfor run in range (100):\n ada.forward(randint(1,5))\n bob.forward(randint(1,5))\n dan.forward(randint(1,5))\n\n","sub_path":"Turtle_race.py","file_name":"Turtle_race.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"340858499","text":"import numpy as np\nfrom collections import deque\n\nfrom unityagents import UnityEnvironment\nfrom banana.dqn.agent import Agent\nfrom banana.utils.utils import save_agent\n\n\ndef train(environment,\n train_config,\n agent_config,\n random_seed=None):\n\n n_episodes = train_config[\"n_episodes\"]\n max_t = train_config[\"max_t\"]\n eps_start = train_config[\"greedy_eps_start\"]\n eps_end = train_config[\"greedy_eps_end\"]\n eps_decay = train_config[\"greedy_eps_decay\"]\n\n # get the default brain\n env = environment\n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n\n # Initialize our agent\n state_size = brain.vector_observation_space_size\n action_size = brain.vector_action_space_size\n\n agent = Agent(\n state_size=state_size,\n action_size=action_size,\n train_config=train_config,\n agent_config=agent_config,\n seed=random_seed\n )\n\n # list containing scores from each episode\n scores = []\n solve_epi = 0\n scores_window = deque(maxlen=100)\n eps = eps_start\n\n for i_episode in range(1, n_episodes + 1):\n\n env_info = env.reset(train_mode=True)[brain_name]\n state = env_info.vector_observations[0]\n score = 0\n\n for _ in range(max_t):\n action = agent.act(state, eps)\n brain_info = env.step(action)[brain_name]\n next_state = brain_info.vector_observations[0]\n reward = brain_info.rewards[0]\n done = brain_info.local_done[0]\n\n agent.step(state, action, reward, next_state, done)\n state = next_state\n score += reward\n if done:\n break\n\n scores_window.append(score)\n scores.append(score)\n\n # Decay epsilon\n eps = max(eps_end, eps_decay * eps)\n\n print('\\rEpisode {}\\tAverage Score: {:.2f}'\n .format(i_episode, np.mean(scores_window)), end=\"\")\n\n if i_episode % 100 == 0:\n print('\\rEpisode {}\\tAverage Score: {:.2f}'\n .format(i_episode, np.mean(scores_window)))\n\n if np.mean(scores_window) >= 13.0 and solve_epi == 0:\n print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'\n .format(i_episode, np.mean(scores_window)))\n solve_epi = i_episode\n\n return agent, scores, solve_epi\n\n\nif __name__ == \"__main__\":\n\n env_filename = \"Banana_Linux_NoVis/Banana.x86_64\"\n\n train_config = {\n # Training loop\n \"n_episodes\": 1000,\n \"max_t\": 1000,\n \"optim_learning_rate\": 5e-4,\n \"mini_batch_size\": 64,\n \"update_every\": 4,\n\n # Greedy epsilon action\n \"greedy_eps_start\": 1.0,\n \"greedy_eps_end\": 0.01,\n \"greedy_eps_decay\": 0.995,\n\n # Q-learning\n \"discount_gamma\": 0.99,\n\n # double q-learning\n \"double_ql_tau\": 1e-3,\n\n # Prioritized Experience Replay\n \"per_eps\": 0.01,\n \"per_alpha\": 0.6,\n \"per_beta\": 1.0,\n\n # Replay memory\n \"buffer_size\": int(1e5)\n }\n\n agent_config = {\n \"per\": True,\n \"double_ql\": True,\n \"duel_network\": True\n }\n\n env = UnityEnvironment(file_name=env_filename)\n\n agent, _, _ = train(\n environment=env,\n train_config=train_config,\n agent_config=agent_config,\n random_seed=0\n )\n\n env.close()\n\n session = 101\n checkpoint_path = 'checkpoint_%s.pth' % session\n save_agent(agent, checkpoint_path)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"167063590","text":"import os\nimport sys\nimport pdb\nimport json\nimport logging\nimport IPython\nfrom pydot import Dot\n\nLEVEL = logging.ERROR\n\ndef setup_loggers(name):\n formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger = logging.getLogger(name)\n logger.addHandler(handler)\n logger.setLevel(LEVEL)\n\nsys.path.append(os.path.abspath(os.path.join(__file__, '../..')))\n\nfrom bifrost import GCC_Utils, DotParser, ReducibilityDetector\n\ndef test1():\n utils = GCC_Utils()\n filename = \"/home/sefcom/projects/decompiler/bifrost/tests/test1.c\"\n assert len(list(utils.generate_dot_files(filename))) == 15\n\n\ndef test2():\n utils = GCC_Utils()\n filename = \"/home/sefcom/projects/decompiler/bifrost/tests/test2.c\"\n assert len(list(utils.generate_dot_files(filename))) == 15\n\n\ndef test3():\n utils = GCC_Utils()\n filename = \"./tests/test1.c\"\n assert len(list(utils.generate_dot_files(filename))) == 0\n\n\ndef test4():\n with open(\"tests/coreutils_commands.json\", \"r\") as f:\n data = json.load(f)\n \n cmd = data[0]\n utils = GCC_Utils(pre_args=cmd['pre_args'])\n assert len(list(utils.generate_dot_files(cmd['filename']))) > 0\n\n\ndef test5():\n with open(\"tests/coreutils_commands.json\", \"r\") as f:\n data = json.load(f)\n \n cmd = data[0]\n utils = GCC_Utils(pre_args=cmd['pre_args'])\n for file in utils.generate_dot_files(cmd['filename']):\n parser = DotParser(file)\n for graph in parser.graph:\n roots = parser.get_roots(graph)\n checker = ReducibilityDetector(graph)\n checker.is_reducible(roots[0])\n break\n break\n\n\nif __name__ == '__main__':\n setup_loggers('bifrost.gcc_utils')\n setup_loggers('bifrost.dot_parser')\n setup_loggers('bifrost.reducibility_detector')\n\n test1()\n test2()\n test3()\n test4()\n test5()","sub_path":"tests/test_gcc_utils.py","file_name":"test_gcc_utils.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"253136794","text":"from django.conf.urls import url\nfrom django.urls import path, include, reverse\nfrom .views import *\nfrom accounts import views as account_views\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\n\napp_name = 'recipes'\nurlpatterns = [\n # GENERAL\n path('', IndexView, name='index'),\n path('profile/', ProfileView, name='profile'),\n path('profile/settings', UserSettings, name='settings'),\n path('profile/settings//change-username', ChangeUsername.as_view(), name='change_username'),\n path('profile/settings/change-password', ChangePassword, name='change_password'),\n path('profile/settings/delete-account', DeleteUser, name='delete_account'),\n\n # RECIPES\n path('all/', RecipeAll.as_view(), name='all'),\n path('/', RecipeCategory, name='category'),\n path('recipe//', RecipeDetail.as_view(), name='recipe_detail'),\n path('recipe/new/', RecipeCreate, name='recipe_new'),\n path('recipe//edit', RecipeEdit.as_view(), name='recipe_edit'),\n path('recipe//edit-photo', RecipeEditPhoto.as_view(), name='recipe_edit_photo'),\n path('recipe//edit-thumbnail', RecipeEditThumbnail.as_view(), name='recipe_edit_thumbnail'),\n path('recipe//delete', RecipeDelete.as_view(), name='recipe_delete'),\n\n #AJAX\n path('recipe/delete-photo-ajax/', delete_photo_ajax, name='delete_photo_ajax'),\n path('recipe/delete-thumbnail-ajax/', delete_thumbnail_ajax, name='delete_thumbnail_ajax'),\n path('recipe/delete-ingredient-ajax/', delete_ingredient_ajax, name='delete_ingredient_ajax'),\n path('recipe/update-ingredient-ajax/', update_ingredient_ajax, name='update_ingredient_ajax'),\n path('recipe/add-ingredient-ajax/', add_ingredient_ajax, name='add_ingredient_ajax'),\n path('recipe/update-instructions-ajax/', update_instructions_ajax, name='update_instructions_ajax'),\n\n # MENUS\n path('menu/all', MenuList.as_view(), name='menu_list'),\n path('menu//', MenuDetail, name='menu_detail'),\n path('menu/new/', MenuCreate.as_view(), name='menu_new'),\n path('menu//edit', MenuEdit.as_view(), name='menu_edit'),\n path('menu//delete', MenuDelete.as_view(), name='menu_delete'),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)","sub_path":"recipes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"568118386","text":"import pygal\n\ndef create_barchart(data):\n\tbar_chart=pygal.Bar()\n\tfor x in data[\"data\"]:\n\t\tbar_chart.add(x[\"name\"],x[\"values\"])\n\tbar_chart.render_to_file('charts\\pygal_chart_function_bar.svg')\n\ndef create_piechart(data):\n\tpie_chart=pygal.Pie()\n\tfor x in data[\"data\"]:\n\t\tpie_chart.add(x[\"browser\"],x[\"usage\"])\n\tpie_chart.render_to_file('charts\\pygal_chart_function_pie.svg')\n\n#data should be of the below format for this example program\n# data1={\"chart_type\":\"barchart\",\n# \t \"data\":[{\n# \t \t\t\"name\":\"Fibonacci\",\n# \t \t\t\"values\":[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n# \t },{\n# \t \t\t\"name\":\"Natural numbers\",\n# \t \t\t\"values\":[1,2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n# \t }\n# \t ]}\n\ndata1={\"chart_type\":\"barchart\",\"data\":[{\"name\":\"Fibonacci\",\"values\":[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]},{\"name\":\"Natural numbers\",\"values\":[1,2, 3, 4, 5, 6, 7, 8, 9, 10, 11]}]}\ndata2={\"chart_type\":\"Pie\",\"data\":[{\"browser\":\"IE\",\"usage\":[19.5]},{\"browser\":\"FF\",\"usage\":[36.6]},{\"browser\":\"Chrome\",\"usage\":[36.3]},{\"browser\":\"Safari\",\"usage\":[4.5]},{\"browser\":\"Opera\",\"usage\":[2.3]}]}\ncreate_barchart(data1)\ncreate_piechart(data2)","sub_path":"pygal_chart_examples.py","file_name":"pygal_chart_examples.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"135554558","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\nfrom numpy.testing import assert_allclose\nfrom gammapy.modeling import Model, Parameter, Parameters\n\n\nclass MyModel(Model):\n def __init__(self):\n self.parameters = Parameters(\n [Parameter(\"x\", 2), Parameter(\"y\", 3e2), Parameter(\"z\", 4e-2)]\n )\n\n\ndef test_model():\n m = MyModel()\n\n m2 = m.copy()\n\n # Models should be independent\n assert m.parameters is not m2.parameters\n assert m.parameters[0] is not m2.parameters[0]\n\n\ndef test_model_create():\n spectral_model = Model.create(\n \"PowerLaw2SpectralModel\", amplitude=\"1e-10 cm-2 s-1\", index=3\n )\n assert spectral_model.tag == \"PowerLaw2SpectralModel\"\n assert_allclose(spectral_model.index.value, 3)\n","sub_path":"gammapy/modeling/tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"564835450","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2018/12/9 18:06\r\n# @Author : huangjie\r\n# @File : socket_client.py\r\n\r\n\r\nimport socket\r\n\r\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nclient.connect(('127.0.0.1', 8000))\r\n\r\nwhile True:\r\n re_data = input()\r\n client.send(re_data.encode(\"utf8\"))\r\n data = client.recv(1024)\r\n print(data.decode(\"utf8\"))\r\n\r\n","sub_path":"Python_Advance/chapter10/socket_client.py","file_name":"socket_client.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"322924019","text":"#!/usr/bin/env python\n\"\"\"Provides several visualization functions using bokeh, matplotlip and seaborn.\n\nLong Summary:\n\n\"\"\"\n\n__author__ = \"Julian Quernheim\"\n__copyright__ = \"Copyright 2018\"\n__credits__ = [\"Julian Quernheim\"]\n__license__ = \"GPL\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Julian Quernheim\"\n__email__ = \"julian-quernheim@hotmail.de\"\n__status__ = \"Development\"\n\n\n\n\ndef bokeh_bar_plot(x, y, title,legend_title, color='yes'):\n '''\n @ Sample usage\n @ bokeh_bar_plot(x = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'], y = [5, 3, 4, 2, 4, 6], title =\"test\" , legend_title = \"Fruits\" )\n :param x:\n :param y:\n :param title:\n :param legend_title:\n :param color:\n :return:\n '''\n\n from bokeh.io import show, output_file\n from bokeh.models import ColumnDataSource\n from bokeh.palettes import Spectral6\n from bokeh.plotting import figure\n\n output_file(title + \".html\")\n\n source = ColumnDataSource(data=dict(fruits=x, counts=y, color=Spectral6))\n\n p = figure(x_range=x, y_range=(0,9), plot_height=250, title=title,\n toolbar_location=None, tools=\"\")\n\n p.vbar(x='fruits', top='counts', width=0.9, color='color', legend=legend_title, source=source)\n\n p.xgrid.grid_line_color = None\n p.legend.orientation = \"horizontal\"\n p.legend.location = \"top_center\"\n\n show(p)\n return p\n\n\ndef bokeh_scatter_plot(x_data, y_data, title, x_label, y_label, color='yes'):\n '''\n @ Sample usage\n @ bokeh_scatter_plot(x_data = [5, 3, 4, 2, 4, 6], y_data =[5, 3, 4, 2, 4, 6], title = \"test\",y_label = \"y_axis\", x_label = \"x_axis\", color='yes')\n :param x_data:\n :param y_data:\n :param title:\n :param x_label:\n :param y_label:\n :param color:\n :return:\n '''\n\n from bokeh.io import show, output_file\n from bokeh.plotting import figure\n\n output_file(title + \".html\", title=title)\n p = figure(title=title, x_axis_label=x_label,\n y_axis_label=y_label)\n\n p.circle(x_data, y_data, size=5, alpha=0.5)\n\n show(p)\n return p\n\n\n\n\ndef bokeh_histogram_plt(data):\n\n '''\n @ import numpy as np\n @ data = np.random.normal(0, 0.5, 1000)\n @ bokeh_histogram_plt(data)\n :param data:\n :return:\n '''\n\n\n import numpy as np\n import scipy.special\n from bokeh.plotting import figure, show, output_file\n from bokeh.palettes import Spectral6\n p = figure(title=\"Normal Distribution (μ=0, σ=0.5)\", tools=\"save\",\n background_fill_color=\"#ffffff\")\n\n hist, edges = np.histogram(data, density=True, bins=50)\n\n mu, sigma = 0, 0.5\n x = np.linspace(-2, 2, 1000)\n pdf = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))\n cdf = (1 + scipy.special.erf((x - mu) / np.sqrt(2 * sigma ** 2))) / 2\n\n p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],\n fill_color=Spectral6[0], line_color=\"#033649\")\n p.line(x, pdf, line_color=Spectral6[5], line_width=3, alpha=0.7, legend=\"PDF\")\n p.line(x, cdf, line_color=Spectral6[4], line_width=3, alpha=0.7, legend=\"CDF\")\n\n p.legend.location = \"center_right\"\n p.xaxis.axis_label = 'x'\n p.yaxis.axis_label = 'Pr(x)'\n\n show(p)\n return p\n\n\n\ndef visualize_tree(sklearn_model_tree, feature_names):\n\n \"\"\"Create tree png using graphviz.\n @ example for data and decision tree model can be found here: http://chrisstrelioff.ws/sandbox/2015/06/08/decision_trees_in_python_with_scikit_learn_and_pandas.html\n @ Sample Usage:\n @ visualize_tree(sklearn_model_tree = dt, feature_names = features)\n\n Args\n ----\n tree -- scikit-learn DecsisionTree.\n feature_names -- list of feature names.\n \"\"\"\n\n from graphviz import Source\n from sklearn import tree\n import os\n os.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n graph = Source(tree.export_graphviz(sklearn_model_tree, out_file=None, feature_names=feature_names))\n graph.format = 'png'\n graph.render('dtree_render', view=True)\n print('dtree_render.png file with decision tree was created in working directory')\n\n\n\n\ndef pair_wise_scatter_plot_seaborn(data, title):\n '''\n @ sample usage:\n @ import numpy as np\n @ import pandas\n @ import random\n @ df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))\n @ pair_wise_scatter_plot_seaborn(data = df, title = \"My Title\")\n\n\n :param data:\n :param title:\n :return:\n '''\n\n # Pair-wise Scatter Plots\n import seaborn as sns\n cols = data.columns.values\n pp = sns.pairplot(data[cols], size=1.8, aspect=1.8,\n plot_kws=dict(edgecolor=\"k\", linewidth=0.5),\n diag_kind=\"kde\", diag_kws=dict(shade=True))\n\n fig = pp.fig\n fig.subplots_adjust(top=0.93, wspace=0.3)\n fig.suptitle(title, fontsize=14)\n fig.savefig(title + \".png\")\n\n\n\n\n\ndef summary_statistics(dataset1,dataset2, dataset1_title, dataset2_title):\n '''\n @ sample usage:\n @ import pandas\n @ import random\n @ import numpy as np\n @ df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))\n @ df_summary_statistics = summary_statistics(dataset1 = df, dataset2 = df, dataset1_title = \"dataset1\", dataset2_title = \"dataset2\")\n @ df_summary_statistics\n\n :param dataset1:\n :param dataset2:\n :param dataset1_title:\n :param dataset2_title:\n :return:\n '''\n import pandas as pd\n\n dataset1_subset_attributes = dataset1.columns.values\n dataset2_subset_attributes = dataset2.columns.values\n rs = round(dataset1[dataset1_subset_attributes].describe(), 2)\n ws = round(dataset2[dataset2_subset_attributes].describe(), 2)\n\n df_summary_statistics = pd.concat([rs, ws], axis=1, keys=[dataset1_title, dataset2_title])\n return(df_summary_statistics)\n\n\n\ndef scatter_plot_regression_seaborn(data,x_colname, y_colname,hue_colname,col_colname, title, subtitle):\n '''\n @ sample usage:\n @ import pandas\n @ import random\n @ import numpy as np\n @ df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))\n @ df[\"C\"] = np.random.choice(['red', 'white','yellow','pink'], 100, p=[0.5, 0.1, 0.1, 0.3])\n @ df[\"D\"] = np.random.choice(['pooh', 'rabbit', 'piglet', 'Christopher'], 100, p=[0.5, 0.1, 0.1, 0.3])\n @ scatter_plot_regression_seaborn(data = df, x_colname = 'A', y_colname= 'B', hue_colname = 'C', col_colname = 'D' , title= \"title\", subtitle=\"subtitle\")\n\n :param data:\n :param x_colname:\n :param y_colname:\n :param hue_colname:\n :param col_colname:\n :param title:\n :param subtitle:\n :return:\n '''\n\n import seaborn as sns; sns.set(color_codes=True)\n import matplotlib.pyplot as plt\n\n\n pp = sns.lmplot(x=x_colname, y=y_colname, col= col_colname,\n palette={\"red\": \"#FF9999\", \"white\": \"#FFE888\"},\n data=data, fit_reg=True, legend=True,\n scatter_kws=dict(edgecolor=\"k\", linewidth=0.5))\n\n fig = pp.fig\n fig.subplots_adjust(top=0.93, wspace=0.3)\n fig.suptitle(title, fontsize=14)\n fig.savefig(title + \".png\")\n\n\n\ndef correlation_plot_seaborn(data, title):\n\n '''\n @ sample usage:\n @ import numpy as np\n @ import pandas as pd\n @ from string import ascii_letters\n @ # Generate a large random dataset\n @ rs = np.random.RandomState(33)\n @ data = pd.DataFrame(data=rs.normal(size=(100, 26)),columns=list(ascii_letters[26:]))\n @ correlation_plot_seaborn(data, 'correlation plot')\n\n :param data:\n :param title:\n :return:\n '''\n\n import numpy as np\n import seaborn as sns\n import matplotlib.pyplot as plt\n\n sns.set(style=\"white\")\n\n\n\n # Compute the correlation matrix\n corr = data.corr()\n\n # Generate a mask for the upper triangle\n mask = np.zeros_like(corr, dtype=np.bool)\n mask[np.triu_indices_from(mask)] = True\n\n # Set up the matplotlib figure\n f, ax = plt.subplots(figsize=(11, 9))\n\n # Generate a custom diverging colormap\n cmap = sns.diverging_palette(220, 10, as_cmap=True)\n\n # Draw the heatmap with the mask and correct aspect ratio\n pp = sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,\n square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\n\n fig = pp.get_figure()\n fig.savefig(title + \".png\")\n\n return fig\n\n\n","sub_path":"DataScienceModule/DataScienceModule/visualization_module.py","file_name":"visualization_module.py","file_ext":"py","file_size_in_byte":8298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"34324555","text":"import pygame\npygame.init()\n\nscreenWidth = 650\nscreenHeight = 650 \nwindow = pygame.display.set_mode((screenWidth, screenHeight)) \n\npygame.display.set_caption(\"Aydin's Game\")\n\nclock = pygame.time.Clock()\n\nbg = pygame.image.load('background.jpg')\nwalkRight = [pygame.image.load('right1.png'), pygame.image.load('right2.png'), pygame.image.load('right3.png'), pygame.image.load('right4.png'), pygame.image.load('right5.png'), pygame.image.load('right6.png'), pygame.image.load('right7.png'), pygame.image.load('right8.png'), pygame.image.load('right9.png')]\nwalkLeft = [pygame.image.load('left1.png'), pygame.image.load('left2.png'), pygame.image.load('left3.png'), pygame.image.load('left4.png'), pygame.image.load('left5.png'), pygame.image.load('left6.png'), pygame.image.load('left7.png'), pygame.image.load('left8.png'), pygame.image.load('left9.png')]\nbulletEffect = pygame.mixer.Sound('bullet.wav')\n\nscore = 0 \n\n\nclass player(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height \n self.distance = 10\n self.isJump = False\n self.jumpCount = 7\n self.left = False\n self.right = False\n self.walkCount = 0\n self.stand = True\n self.health = 100\n self.invisible = False \n self.hitbox = (self.x + 18, self.y + 8, 25, 50) \n\n def draw(self, window):\n if not self.invisible: \n if self.walkCount + 1 >= 27: \n self.walkCount = 0 \n\n if not self.stand:\n if self.left:\n window.blit(walkLeft[self.walkCount // 3], (self.x, self.y))\n self.walkCount += 1\n\n elif self.right:\n window.blit(walkRight[self.walkCount // 3], (self.x, self.y)) \n self.walkCount += 1 \n else:\n if self.right:\n window.blit(walkRight[0], (self.x, self.y))\n else:\n window.blit(walkLeft[0], (self.x, self.y))\n\n pygame.draw.rect(window, (255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))\n pygame.draw.rect(window, (0, 255, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (0.5 * (100 - self.health)), 10))\n self.hitbox = (self.x + 18, self.y + 8, 25, 50)\n\n def collide(self):\n if not self.invisible: \n self.x = 50\n self.y = 420\n self.walkCount = 0\n self.isJump = False\n self.jumpCount = 7 \n font_col = pygame.font.SysFont('californianfb', 16, True)\n text = font_col.render('YOU GOT TOO CLOSE TO THE ENEMY AND TOOK DAMAGE!', 1, (255, 0, 0), True)\n window.blit(text, (325 - (text.get_width()/2), 125 - (text.get_height()/2))) \n pygame.display.update()\n i = 0\n while i < 150:\n pygame.time.delay(10)\n i += 1\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n i = 151\n pygame.quit()\n if self.health > 10: \n self.health -= 10\n else:\n self.invisible = True\n\n def block(self):\n if self.hitbox[0] < 350: \n self.x = 300 \n self.y = 420\n self.walkCount = 0\n self.isJump = False\n self.jumpCount = 7\n else:\n self.x = 370\n self.y = 420\n self.walkCount = 0\n self.isJump = False\n self.jumpCount = 7\n \n\nclass projectile(object):\n def __init__(self, x, y, radius, color, direction):\n self.x = x\n self.y = y\n self.radius = radius\n self.color = color\n self.direction = direction\n self.velocity = 10 * direction\n\n def draw(self, window):\n pygame.draw.circle(window, self.color, (self.x, self.y), self.radius)\n\n\nclass obstacle(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.hitbox = (self.x, self.y, 40, 70) \n\n def draw(self, window):\n pygame.draw.rect(window, (150, 75, 0), (self.x, self.y, self.width, self.height))\n self.hitbox = (self.x, self.y, 40, 70)\n pygame.draw.rect(window, (0, 0, 0), self.hitbox, 2)\n\n\nclass enemy(object):\n attackRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'), pygame.image.load('R4.png'), pygame.image.load('R5.png'), pygame.image.load('R6.png'), pygame.image.load('R7.png'), pygame.image.load('R8.png'), pygame.image.load('R9.png'), pygame.image.load('R10.png'), pygame.image.load('R11.png')]\n attackLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'), pygame.image.load('L4.png'), pygame.image.load('L5.png'), pygame.image.load('L6.png'), pygame.image.load('L7.png'), pygame.image.load('L8.png'), pygame.image.load('L9.png'), pygame.image.load('L10.png'), pygame.image.load('L11.png')]\n\n def __init__(self, x, y, width, height, end):\n self.x = x\n self.y = y\n self.width = width\n self.height = height \n self.end = end\n self.path = [self.x, self.end] \n self.attackCount = 0\n self.distance = 3\n self.hitbox = (self.x + 11, self.y + 2, 37, 57)\n self.health = 100\n self.invisible = False \n\n def draw(self, window):\n if not self.invisible: \n self.move() \n if self.attackCount +1 >= 27:\n self.attackCount = 0\n\n if self.distance > 0:\n window.blit(self.attackRight[self.attackCount // 3], (self.x, self.y))\n self.attackCount += 1\n\n else:\n window.blit(self.attackLeft[self.attackCount // 3], (self.x, self.y))\n self.attackCount += 1\n\n pygame.draw.rect(window, (255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))\n pygame.draw.rect(window, (0, 255, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (0.5 * (100 - self.health)), 10)) \n self.hitbox = (self.x + 11, self.y + 2, 37, 57) \n \n def move(self):\n if self.distance > 0:\n if self.x + self.distance < self.path[1]:\n self.x += self.distance\n else:\n self.distance = self.distance * -1\n self.attackCount = 0\n else:\n if self.x - self.distance > self.path[0]:\n self.x += self.distance\n else:\n self.distance = self.distance * -1\n self.attackCount = 0\n\n def hit(self):\n if self.health > 10: \n self.health -= 10\n else:\n self.invisible = True \n \n\ndef gameWindow(): \n window.blit(bg, (0, 0))\n tiny_guy.draw(window)\n tiny_enemy.draw(window)\n obs.draw(window)\n for bullet in ammunition:\n bullet.draw(window)\n text = font.render('Score: ' + str(score), 1, (255,0,0))\n window.blit(text, (480, 50)) \n pygame.display.update()\n if tiny_enemy.invisible:\n font_col = pygame.font.SysFont('californianfb', 36, True) \n text = font_col.render('YOU WON!', 1, (255, 0, 0), True)\n window.blit(text, (325 - (text.get_width()/2), 125 - (text.get_height()/2))) \n pygame.display.update()\n if tiny_guy.invisible:\n font_col = pygame.font.SysFont('californianfb', 36, True) \n text = font_col.render('YOU LOST!', 1, (255, 0, 0), True)\n window.blit(text, (325 - (text.get_width()/2), 125 - (text.get_height()/2))) \n pygame.display.update() \n\n\n# main loop\ntiny_guy = player(100, 420, 64, 64)\ntiny_enemy = enemy(400, 420, 64, 64, 550)\nobs = obstacle(350, 420, 40, 70)\nshootCount = 0 \nammunition = []\nfont = pygame.font.SysFont('arial', 30, True) \nready = True\n\nwhile ready:\n gameWindow() \n clock.tick(24)\n \n if tiny_guy.hitbox[1] < tiny_enemy.hitbox[1] + tiny_enemy.hitbox[3] and tiny_guy.hitbox[1] + tiny_guy.hitbox[3] > tiny_enemy.hitbox[1]:\n if tiny_guy.hitbox[0] + tiny_guy.hitbox[2] > tiny_enemy.hitbox[0] + 20 and tiny_guy.hitbox[0] < tiny_enemy.hitbox[0] + tiny_enemy.hitbox[2]:\n if not tiny_enemy.invisible:\n tiny_guy.collide()\n\n if tiny_guy.hitbox[1] < obs.hitbox[1] + obs.hitbox[3] and tiny_guy.hitbox[1] + tiny_guy.hitbox[3] > obs.hitbox[1]:\n if tiny_guy.hitbox[0] + tiny_guy.hitbox[2] > obs.hitbox[0] and tiny_guy.hitbox[0] < obs.hitbox[0] + obs.hitbox[2]:\n tiny_guy.block()\n\n if shootCount > 0:\n shootCount += 1\n\n if shootCount > 10:\n shootCount = 0 \n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n ready = False\n\n for bullet in ammunition:\n if not tiny_enemy.invisible:\n if bullet.y - bullet.radius < tiny_enemy.hitbox[1] + tiny_enemy.hitbox[3] and bullet.y + bullet.radius > tiny_enemy.hitbox[1]:\n if bullet.x + bullet.radius > tiny_enemy.hitbox[0] and bullet.x - bullet.radius < tiny_enemy.hitbox[0] + tiny_enemy.hitbox[2]:\n tiny_enemy.hit()\n score += 10 \n ammunition.pop(ammunition.index(bullet)) \n\n if bullet.y - bullet.radius < obs.hitbox[1] + obs.hitbox[3] and bullet.y + bullet.radius > obs.hitbox[1]:\n if bullet.x + bullet.radius > obs.hitbox[0] and bullet.x - bullet.radius < obs.hitbox[0] + obs.hitbox[2]:\n ammunition.pop(ammunition.index(bullet)) \n \n if 0 < bullet.x < 650:\n bullet.x += bullet.velocity\n else:\n ammunition.pop(ammunition.index(bullet)) \n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_SPACE] and shootCount == 0:\n bulletEffect.play() \n if tiny_guy.left:\n direction = -1\n else:\n direction = 1 \n if len(ammunition) < 10: \n ammunition.append(projectile(round(tiny_guy.x + tiny_guy.width // 2), round(tiny_guy.y + tiny_guy.height // 2), 3, (0,0,0), direction))\n\n shootCount = 1 \n \n if keys[pygame.K_LEFT] and tiny_guy.x >= tiny_guy.distance:\n tiny_guy.x -= tiny_guy.distance\n tiny_guy.left = True\n tiny_guy.right = False\n tiny_guy.stand = False\n elif keys[pygame.K_RIGHT] and tiny_guy.x <= screenWidth - tiny_guy.distance - tiny_guy.width:\n tiny_guy.x += tiny_guy.distance\n tiny_guy.right = True\n tiny_guy.left = False\n tiny_guy.stand = False\n else:\n tiny_guy.stand = True \n tiny_guy.walkCount = 0\n \n if not tiny_guy.isJump:\n if keys[pygame.K_UP]:\n tiny_guy.isJump = True\n tiny_guy.left = False\n tiny_guy.right = False\n tiny_guy.walkCount = 0\n else:\n if tiny_guy.jumpCount >= -7:\n constant = 1 \n if tiny_guy.jumpCount < 0:\n constant = -1 \n tiny_guy.y -= (tiny_guy.jumpCount ** 2) * 0.65 * constant\n tiny_guy.jumpCount -= 1\n else:\n tiny_guy.isJump = False\n tiny_guy.jumpCount = 7\n \n \npygame.quit()\n","sub_path":"first_game.py","file_name":"first_game.py","file_ext":"py","file_size_in_byte":11264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"336773816","text":"import urllib.request, json, os, time\n\n#各作品のマニフェストファイルから、画像URLやページごとのCanvasタイプ情報などを抽出し、\n#infoと名付けたリストで整理\ndef manifest2info(hojo_name):\n json_path = \"../input/manifest/{}.json\".format(hojo_name)\n with open(json_path) as f:\n manifest = json.load(f)\n\n #infoの構造:info={\"@id\":\"hoge\", \"identifier\":\"fuga\", \"sequences\":{}(後述)}\n info = {}\n\n info[\"identifier\"] = \"\"\n for data in manifest[\"metadata\"]:\n if data[\"label\"] == \"identifier\":\n info[\"identifier\"] = data[\"value\"]\n info[\"@id\"] = manifest[\"@id\"]\n\n #{sequence_id: [[canvas1, image_url, width, height], [canvas2. image_url, width, height], ...]}という形\n #canvasはCanvasタイプのURI\n #UPARLはImage APIの形じゃないので、Thumbnailから持ってくる\n print(\"Is the file from Uparl? (y/n)\")\n ans = input()\n utokyo = False\n if ans == \"y\":\n utokyo = True\n sequence_num = 1\n for sequence in manifest[\"sequences\"]:\n info[\"sequence_{}\".format(sequence_num)] = []\n for canvas in sequence[\"canvases\"]:\n canvas_info = []\n canvas_info.append(canvas[\"@id\"])\n if utokyo:\n canvas_info.append(canvas[\"thumbnail\"][\"@id\"].replace(\"200,/0/default.jpg\", \"full/0/default.jpg\"))\n else:\n for content in canvas[\"images\"]:\n canvas_info.append(content[\"resource\"][\"@id\"])\n canvas_info.append(canvas[\"images\"][0][\"resource\"][\"width\"])\n canvas_info.append(canvas[\"images\"][0][\"resource\"][\"height\"])\n\n info[\"sequence_{}\".format(sequence_num)].append(canvas_info)\n sequence_num += 1\n\n return info\n\n#個別の法帖に関する基本データと画像保存場所を作成\ndef make_hojodir(info, hojo_name):\n hojodir = \"../input/images/{}/\".format(hojo_name)\n if not os.path.exists(hojodir):\n os.mkdir(hojodir)\n with open(hojodir+\"hojo_info.txt\", \"w\") as f:\n f.write(\"{}\\n\".format(info[\"@id\"]))\n f.write(\"{}\\n\".format(info[\"identifier\"]))\n f.write(\"{}\\n\".format(info[\"sequence_1\"][0][2]))\n f.write(\"{}\\n\".format(info[\"sequence_1\"][0][3]))\n\n#画像のダウンロード\n#画像サイズは(1000, *)で指定\ndef get_iiif_images(info, hojo_name):\n sequence_num = len(info)-2 #@idとidentifierを除いた数\n page = 1\n for number in range(1, sequence_num+1):\n for sequence in info[\"sequence_{}\".format(number)]:\n canvas, image_url = sequence[0], sequence[1]\n pagedir = \"../input/images/{}/p{}/\".format(hojo_name, page)\n if not os.path.exists(pagedir):\n os.mkdir(pagedir)\n\n #canvas_idを保存するためのファイルを作成\n with open(pagedir+\"canvas_id.txt\", \"w\") as f:\n f.write(canvas)\n\n #画像サイズ指定\n image_url = image_url.replace(\"full/0/default.jpg\", \"1000,/0/default.jpg\")\n #画像ダウンロード\n image_name = hojo_name+\"-p{}\".format(page)\n urllib.request.urlretrieve(image_url, pagedir+\"{}.jpg\".format(image_name))\n\n #諸々の手続き的事項\n print(\"downloaded {}\".format(image_name))\n page += 1\n time.sleep(3)\n\nif __name__ == \"__main__\":\n hojos = os.listdir(\"../input/manifest/\")\n if \".DS_Store\" in hojos:\n hojos.remove(\".DS_Store\")\n for hojo in hojos:\n hojo = hojo.replace(\".json\", \"\")\n print(hojo)\n info = manifest2info(hojo)\n make_hojodir(info, hojo)\n get_iiif_images(info, hojo)\n","sub_path":"line_cut/src/2_imageDownloader.py","file_name":"2_imageDownloader.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"502217513","text":"class MinStack:\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.items = []\n self.size = 0\n self.smallest = 0\n \n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: void\n \"\"\"\n if self.size == 0:\n self.items.append(x)\n self.smallest = x\n else:\n self.items.append(x)\n if x < self.smallest:\n self.smallest = x\n self.size += 1\n \n \n\n def pop(self):\n \"\"\"\n :rtype: void\n \"\"\"\n if self.size == 0:\n try:\n self.items.pop()\n except IndexError:\n print(\"You can't pop() from empty stack.\")\n else:\n val = self.items.pop()\n self.size -= 1\n if val == self.smallest and self.size >= 1:\n self.smallest = min(self.items)\n elif val == self.smallest and self.size == 0:\n self.smallest = 0\n\n \n \n\n def top(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if self.size == 0:\n try:\n _ = self.items[-1]\n except:\n print(\"It's an empty stack, no value returned.\")\n return None\n else:\n return self.items[-1]\n \n\n def getMin(self):\n \"\"\"\n :rtype: int\n \"\"\"\n if self.size == 0:\n return None\n else:\n return self.smallest","sub_path":"100-200/155_min_stack.py","file_name":"155_min_stack.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"588483664","text":"from pathlib import Path\n\nimport pytest\nfrom scrapy.http import TextResponse, Request\n\nfrom freecamper_crawler.spiders import nyp_spider\n\n\n@pytest.fixture\ndef fake_response():\n def _response(url: str, html_file: Path) -> TextResponse:\n request = Request(url)\n\n with open(html_file, \"r\") as sample:\n return TextResponse(\n url=url,\n request=request,\n body=sample.read().encode(),\n )\n\n return _response\n\n\ndef test_parse_single_track_album(fake_response):\n response = fake_response(\n \"http://test.url\",\n Path(\"freecamper_crawler/tests/page_samples/album/1_track_album.html\"),\n )\n result = {\n \"artist\": \"Orphic\",\n \"album\": \"Orphic 4\",\n \"year\": 2020,\n \"tracks\": 1,\n \"tags\": [\"jazz\", \"acoustic\", \"contemporary\", \"Bristol\"],\n \"license\": {\"text\": \"all rights reserved\", \"url\": \"\"},\n \"url\": \"http://test.url\",\n }\n\n spider = nyp_spider.nypSpider()\n\n assert spider.parse_album(response) == result\n\n\ndef test_parse_multiple_track_album(fake_response):\n response = fake_response(\n \"http://test.url\",\n Path(\"freecamper_crawler/tests/page_samples/album/8_track_album.html\"),\n )\n result = {\n \"artist\": \"Globular & Geoglyph\",\n \"album\": \"Messages From The Resonator\",\n \"year\": 2020,\n \"tracks\": 8,\n \"tags\": [\n \"dub\",\n \"electronic\",\n \"electronica\",\n \"experimental\",\n \"hip hop\",\n \"psy-dub\",\n \"psychedelic\",\n \"psydub\",\n \"world\",\n \"ambient\",\n \"downtempo\",\n \"experimental electronic\",\n \"hip hop\",\n \"trip hop\",\n \"Bristol\",\n ],\n \"license\": {\"text\": \"all rights reserved\", \"url\": \"\"},\n \"url\": \"http://test.url\",\n }\n\n spider = nyp_spider.nypSpider()\n\n assert spider.parse_album(response) == result\n\n","sub_path":"freecamper_crawler/tests/test_nyp_spider_parsers.py","file_name":"test_nyp_spider_parsers.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"168644315","text":"# -*- coding: utf8 -*-\n#\n#Interest.blog Front, a development of a team blog driven by interests and hobbies.\n#\n__author__ = \"Mr.tao\"\n__email__ = \"staugur@saintic.com\"\n__version__ = \"0.4\"\n\nimport json, requests, datetime\nfrom urllib import urlencode\nfrom flask import Flask, g, render_template, request, redirect, url_for, make_response, abort\nfrom config import GLOBAL, SSO, PLUGINS\nfrom utils.public import logger, gen_requestId, isLogged_in, md5\nfrom views.admin import admin_page\nfrom views.upload import upload_page\n\napp = Flask(__name__)\napp.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024\napp.register_blueprint(admin_page, url_prefix=\"/admin\")\napp.register_blueprint(upload_page, url_prefix=\"/upload\")\n\n#Before each URL request, define the initialization time, requestId, user authentication results and other related information and bind to g\n@app.before_request\ndef before_request():\n g.requestId = gen_requestId()\n g.sessionId = request.cookies.get(\"sessionId\", \"\")\n g.username = request.cookies.get(\"username\", \"\")\n g.expires = request.cookies.get(\"time\", \"\")\n g.signin = isLogged_in('.'.join([ g.username, g.expires, g.sessionId ]))\n logger.info(\"Start Once Access, and this requestId is %s, isLogged_in:%s\" %(g.requestId, g.signin))\n\n#Each return data in response to head belt, including the version and the requestId access log records request.\n@app.after_request\ndef add_header(response):\n response.headers[\"X-Interest-Request-Id\"] = g.requestId\n logger.info(json.dumps({\n \"AccessLog\": True,\n \"status_code\": response.status_code,\n \"method\": request.method,\n \"ip\": request.headers.get('X-Real-Ip', request.remote_addr),\n \"url\": request.url,\n \"referer\": request.headers.get('Referer'),\n \"agent\": request.headers.get(\"User-Agent\"),\n \"requestId\": g.requestId,\n }))\n return response\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template(\"public/404.html\"), 404\n\n@app.route(\"/\")\ndef index():\n return render_template(\"front/index.html\", EnableBaiduStatistics=PLUGINS['BaiduStatistics'])\n\n@app.route(\"/google32fd52b6c900160b.html\")\ndef google_search_console():\n return render_template(\"public/google32fd52b6c900160b.html\")\n\n@app.route(\"/robots.txt\")\ndef robots():\n return \"\"\"\nUser-agent: *\nAllow:/\n \"\"\"\n\n@app.route(\"/about/\")\ndef about():\n return redirect(url_for('blogShow', bid=113))\n\n@app.route('/blog/.html')\ndef blogShow(bid):\n data = requests.get(\"https://api.saintic.com/blog?blogId=%s\" %bid, timeout=5, verify=False, headers={'User-Agent': 'Interest.blog/%s' %__version__}).json().get(\"data\")\n if data:\n return render_template(\"front/blogShow.html\", blogId=bid, data=data, EnableCodeHighlighting=PLUGINS['CodeHighlighting'], EnableWeiboShare=PLUGINS['WeiboShare'], EnableQQShare=PLUGINS['QQShare'], EnableQzoneShare=PLUGINS['QzoneShare'], EnableDuoshuoComment=PLUGINS['DuoshuoComment'], EnableBaiduAutoPush=PLUGINS['BaiduAutoPush'])\n else:\n return abort(404)\n\n@app.route('/blog/edit/')\ndef blogEdit():\n blogId = request.args.get(\"blogId\")\n if g.signin and blogId:\n data = requests.get(\"https://api.saintic.com/blog?blogId=%s\" %blogId, timeout=5, verify=False, headers={'User-Agent': 'Interest.blog/%s' %__version__}).json().get(\"data\")\n if data and g.username == data.get(\"author\") or g.username == \"admin\":\n return render_template(\"front/blogEdit.html\", blogId=blogId, data=data)\n return redirect(url_for(\"login\"))\n\n@app.route('/blog/write/')\ndef blogWrite():\n if g.signin:\n return render_template(\"front/blogWrite.html\")\n else:\n return redirect(url_for(\"login\"))\n\n@app.route('/home/')\ndef home():\n if g.signin:\n user = requests.get(\"https://api.saintic.com/user\", timeout=5, verify=False, headers={'User-Agent': 'Interest.blog/%s' %__version__}, params={\"username\": g.username}).json().get(\"data\") or {}\n blog = requests.get(\"https://api.saintic.com/blog\", timeout=5, verify=False, headers={'User-Agent': 'Interest.blog/%s' %__version__}, params={\"get_user_blog\": g.username, \"limit\": \"all\"}).json().get(\"data\") or []\n return render_template(\"front/home.html\", user=user, blog=blog, blogLength=len(blog), EnableWeather=PLUGINS['Weather'])\n else:\n return redirect(url_for(\"login\"))\n\n@app.route('/login/')\ndef login():\n if g.signin:\n return redirect(url_for(\"index\"))\n else:\n SSOLoginURL = \"%s/login/?%s\" %(SSO.get(\"SSO.URL\"), urlencode({\"sso\": True, \"sso_r\": SSO.get(\"SSO.REDIRECT\") + \"/sso/\", \"sso_p\": SSO.get(\"SSO.PROJECT\"), \"sso_t\": md5(\"%s:%s\" %(SSO.get(\"SSO.PROJECT\"), SSO.get(\"SSO.REDIRECT\") + \"/sso/\"))}))\n logger.info(\"User request login to SSO: %s\" %SSOLoginURL)\n return redirect(SSOLoginURL)\n\n@app.route('/logout/')\ndef logout():\n #data = requests.delete(SSO.get(\"SSO.URL\") + \"/sso/\", timeout=6, headers={\"User-Agent\": \"Interest.blog/%s\" %__version__}, verify=False, data={\"username\": g.username, \"time\": g.expires, \"sessionId\": g.sessionId}).text\n #logger.info({\"sso logout\": data})\n SSOLogoutURL = SSO.get(\"SSO.URL\") + \"/sso/?nextUrl=\" + SSO.get(\"SSO.REDIRECT\")\n resp = make_response(redirect(SSOLogoutURL))\n resp.set_cookie(key='logged_in', value='', expires=0)\n resp.set_cookie(key='username', value='', expires=0)\n resp.set_cookie(key='sessionId', value='', expires=0)\n resp.set_cookie(key='time', value='', expires=0)\n resp.set_cookie(key='Azone', value='', expires=0)\n return resp\n\n@app.route('/sso/')\ndef sso():\n ticket = request.args.get(\"ticket\")\n username, expires, sessionId = ticket.split('.')\n UnixExpires = datetime.datetime.strptime(expires,\"%Y-%m-%d\")\n resp = make_response(redirect(url_for(\"index\")))\n #resp.set_cookie(key=\"test\", value=\"ok\", expires=datetime.datetime.strptime(expires,\"%Y-%m-%d\"))\n #resp.set_cookie(key='test', value=\"ok\", max_age=ISOString2Time(expires))\n resp.set_cookie(key='logged_in', value=\"yes\", expires=UnixExpires)\n resp.set_cookie(key='username', value=username, expires=UnixExpires)\n resp.set_cookie(key='sessionId', value=sessionId, expires=UnixExpires)\n resp.set_cookie(key='time', value=expires, expires=UnixExpires)\n resp.set_cookie(key='Azone', value=\"sso\", expires=UnixExpires)\n return resp\n\nif __name__ == \"__main__\":\n Host = GLOBAL.get('Host')\n Port = GLOBAL.get('Port')\n app.run(host=Host, port=int(Port), debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"294185516","text":"'''\nRede Neural Assistida para simular o operador AND\n'''\nimport numpy as np\n\nentradas = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])\npesos = np.array([0.0, 0.0])\n# Vetor com os valores esperados como saída\nsaidas = np.array([0, 0, 0, 1])\ntaxaAprendizagem = 0.1\n\n\n# A Step Function é ativada apenas quando a entrada for >= 1\ndef step_function(soma):\n if soma >= 1:\n return 1\n return 0\n\n\ndef calcula_saida(registro):\n # Calcula o produto interno entre registro e pesos\n s = registro.dot(pesos)\n return step_function(s)\n\n\ndef treinar():\n erroTotal = 1\n while erroTotal != 0:\n erroTotal = 0\n for i in range(len(saidas)):\n saidaCalculada = calcula_saida(np.asarray(entradas[i]))\n erro = abs(saidas[i] - saidaCalculada)\n erroTotal += erro\n for j in range(len(pesos)):\n pesos[j] += taxaAprendizagem * entradas[i][j] * erro\n print(\"Peso atualizado: \" + str(pesos[j]))\n print(\"Total de Erros:\" + str(erroTotal))\n\n\ntreinar()\n","sub_path":"Redes Neurais Udemy/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"416694898","text":"from mininet.topo import Topo\nfrom mininet.net import Mininet\nfrom mininet.util import dumpNodeConnections\nfrom mininet.log import setLogLevel\nfrom mininet.cli import CLI\nfrom mininet.nodelib import NAT\n\nclass MyTopo(Topo):\n def build(self):\n switch1 = self.addSwitch('s1')\n switch2 = self.addSwitch('s2')\n host1 = self.addHost('h1')\n host2 = self.addHost('h2')\n host3 = self.addHost('h3')\n host4 = self.addHost('h4')\n host5 = self.addHost('h5')\n host6 = self.addHost('h6')\n nat0 = self.addHost('nat0', cls=NAT, subnet='10.1.0.0/16', inNamespace=False)\n self.addLink(host1,switch1)\n self.addLink(host2,switch1)\n self.addLink(host3,switch1)\n self.addLink(host4,switch1)\n self.addLink(host1,switch2)\n self.addLink(host5,switch2)\n self.addLink(host6,switch2)\n self.addLink(nat0,switch1)\n\ndef simpleTest():\n topo = MyTopo()\n net = Mininet(topo,ipBase=\"10.1.0.0/16\")\n net.start()\n net['h1'].sendCmd(\"ip a del 10.1.0.1 dev h1-eth0\")\n net['h2'].sendCmd(\"ip a del 10.1.0.2 dev h2-eth0\")\n net['h3'].setIP(\"10.1.0.3\",24,'h3-eth0')\n net['h4'].setIP(\"10.1.0.4\",24,'h4-eth0')\n net['h5'].setIP(\"10.1.1.2\",24,'h5-eth0')\n net['h6'].setIP(\"10.1.1.3\",24,'h6-eth0')\n net['h2'].waitOutput()\n net['h2'].sendCmd(\"route add -net 10.1.1.0 netmask 255.255.255.0 gw 10.1.0.1\")\n net['h3'].sendCmd(\"route add -net 10.1.1.0 netmask 255.255.255.0 gw 10.1.0.1\")\n net['h4'].sendCmd(\"route add -net 10.1.1.0 netmask 255.255.255.0 gw 10.1.0.1\")\n net['h5'].sendCmd(\"route add -net 10.1.0.0 netmask 255.255.255.0 gw 10.1.1.1\")\n net['h6'].sendCmd(\"route add -net 10.1.0.0 netmask 255.255.255.0 gw 10.1.1.1\")\n net['h1'].waitOutput()\n net['h1'].sendCmd(\"kitty &\")\n net['h1'].waitOutput()\n net['h2'].waitOutput()\n net['h3'].waitOutput()\n net['h4'].waitOutput()\n net['h5'].waitOutput()\n net['h6'].waitOutput()\n net['h3'].setDefaultRoute('via 10.1.0.7')\n net['h4'].setDefaultRoute('via 10.1.1.1')\n net['h5'].setDefaultRoute('via 10.1.1.1')\n net['h6'].setDefaultRoute('via 10.1.1.1')\n CLI(net)\n net.stop()\n\nif __name__ == '__main__':\n # Tell mininet to print useful information\n setLogLevel('info')\n simpleTest()\n","sub_path":"mininet_topo.py","file_name":"mininet_topo.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49294067","text":"from yahooquery import Ticker\nimport os\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport json\nfrom pandas.io.json import json_normalize\nfrom pytrends.request import TrendReq\n\n'''\n\n\nEUNL.DE : iShares Core MSCI World UCITS ETF USD (Acc) (EUNL.DE)\nUSPY.DE : Legal & General UCITS ETF Plc - L&G Cyber Security UCITS ETF (USPY.DE)\nE908.DE : Lyxor 1 TecDAX UCITS ETF (E908.DE)\nX010.DE : Lyxor MSCI World (LUX) UCITS ETF (X010.DE)\n'''\n\nprint('START')\npath = os.environ['MYPATH']\n#path = r\"\\\\DISKSTATION\\docker\\python_stock_data\"\ndstprefix = datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\nticker_list_personal = ['E908.DE']\nticker_list_etfs = pd.read_csv(r'etf_yahoo_tickers.csv', sep=';', usecols=[0, 2])\nticker_list_etfs = ticker_list_etfs[ticker_list_etfs['Exchange'] == 'GER']\n\nticker_list = ticker_list_etfs['Ticker'].values\nticker_list = np.append(ticker_list, ticker_list_personal)\nnumber_of_items = 10\nnumber_of_chunks = len(ticker_list) / number_of_items\n\nticker_list_chunks = np.array_split(ticker_list, number_of_chunks)\n\ndf_metadata_all = pd.DataFrame()\ndf_historic_all = pd.DataFrame()\nfor chunk in ticker_list_chunks:\n print(chunk)\n\n tickers = Ticker(chunk, formatted=True, asynchronous=True)\n\n metadata_dict = tickers.all_modules\n # iterate over all tickers\n\n for ticker in metadata_dict:\n print(ticker)\n df_metadata_ticker = pd.DataFrame()\n\n try:\n # iterate over all modules\n ticker_data = metadata_dict[ticker]\n\n for module in ticker_data:\n\n # print(module)\n # print(module)\n try:\n df_metadata = pd.DataFrame.from_dict(metadata_dict[ticker][module])\n\n if df_metadata.__len__() > 1:\n\n columns_new = []\n data_new = []\n\n indices = df_metadata.index\n columns = df_metadata.columns\n i = 0\n for df_metadata_row in df_metadata.iterrows():\n # print(indices[i])\n j = 0\n for column in columns:\n columns_new.append(indices[i] + '.' + columns[j])\n data_new.append(df_metadata[column].iloc[i])\n\n # print('{v_j} : {v_column}'.format(v_j=j, v_column=column))\n\n # df_metadata_new[columns_new[j]] = df_metadata[column].iloc[i]\n j = j + 1\n i = i + 1\n\n df_metadata_new = pd.DataFrame(data_new)\n df_metadata_new = df_metadata_new.transpose()\n df_metadata_new.columns = columns_new\n\n else:\n df_metadata_new = df_metadata\n\n df_metadata_ticker = df_metadata_new.join(df_metadata_ticker, lsuffix=module)\n\n except:\n df_metadata_new = pd.json_normalize(metadata_dict[ticker][module])\n # print(df_metadata)\n\n df_metadata_ticker = df_metadata_new.join(df_metadata_ticker, lsuffix=module)\n\n df_metadata_ticker['insert_ts'] = dstprefix\n df_metadata_ticker['ticker'] = ticker\n\n # now get Google trends\n '''\n try:\n pytrend = TrendReq(hl='en-US', tz=360\n ,retries=2\n ,backoff_factor=1)\n keywords = [df_metadata_ticker['shortName'].iloc[0]]\n\n pytrend.build_payload(\n kw_list=keywords,\n timeframe='now 1-d'\n )\n data = pytrend.interest_over_time()\n df_metadata_ticker['Google_trends'] = str(data.to_dict())\n\n except:\n df_metadata_ticker['Google_trends'] = {}\n '''\n df_metadata_all = df_metadata_all.append(df_metadata_ticker)\n\n except Exception as e:\n print('FAIL: Could not load data for ticker {v_ticker}'.format(v_ticker=ticker))\n\n df = tickers.history(period='5d', adj_ohlc=True)\n # df = tickers.history(period=\"max\", adj_ohlc=True)\n print('Download data for {v_ticker}'.format(v_ticker=str(ticker)))\n print('length: ' + str(df.__len__()))\n try:\n df_historic_all = df_historic_all.append(df)\n except:\n print('FAIL: Could not load {v_ticker}'.format(v_ticker=str(ticker)))\n\n\n\n# fine tuning\ndf_riskOverviewStatistics_all = pd.DataFrame()\nl = 0\nl_max = df_metadata_all.__len__()\nfor l in range(l_max):\n\n try:\n\n df_riskOverviewStatistics = pd.json_normalize(df_metadata_all['riskStatistics.riskOverviewStatistics'].str[0].iloc[l])\n df_riskOverviewStatistics['ticker'] = df_metadata_all['ticker'].iloc[l]\n df_riskOverviewStatistics['insert_ts'] = df_metadata_all['insert_ts'].iloc[l]\n\n df_riskOverviewStatistics_all = df_riskOverviewStatistics_all.append(df_riskOverviewStatistics)\n\n except Exception as e:\n print(e)\n\n\ndf_metadata_all = df_metadata_all.merge(df_riskOverviewStatistics_all, on =['ticker', 'insert_ts'], how='left', suffixes=[\"\",\"riskStatistics.riskOverviewStatistics\"])\n\n\n# ---------------\n# HOLDINGS\n# ---------------\n\n\n# fine tuning\ndf_holdings_all = pd.DataFrame()\nl = 0\nl_max = df_metadata_all.__len__()\nfor l in range(l_max):\n\n try:\n\n df_holdings = pd.json_normalize(df_metadata_all['holdings'].iloc[l])\n df_holdings['ticker'] = df_metadata_all['ticker'].iloc[l]\n df_holdings['insert_ts'] = df_metadata_all['insert_ts'].iloc[l]\n\n df_holdings_all = df_holdings_all.append(df_holdings)\n\n except Exception as e:\n print(e)\n\n\n\n\n\n\n\n\n# ---------------\n# bondRatings\n# ---------------\n\n\n# fine tuning\ndf_bondRatings_all = pd.DataFrame()\nl = 0\nl_max = df_metadata_all.__len__()\nfor l in range(l_max):\n\n try:\n\n df_bondRatings = pd.json_normalize(df_metadata_all['bondRatings'].str[0].iloc[l])\n df_bondRatings['ticker'] = df_metadata_all['ticker'].iloc[l]\n df_bondRatings['insert_ts'] = df_metadata_all['insert_ts'].iloc[l]\n\n df_bondRatings_all = df_bondRatings_all.append(df_bondRatings)\n\n except Exception as e:\n print(e)\n\n\ndf_metadata_all = df_metadata_all.merge(df_bondRatings_all, on =['ticker', 'insert_ts'], how='left', suffixes=[\"\",\"bondRatings\"])\n\n\n\n\n# ---------------\n# sectorWeightings\n# ---------------\n\n\n# fine tuning\ndf_sectorWeightings_all = pd.DataFrame()\nl = 0\nl_max = df_metadata_all.__len__()\nfor l in range(l_max):\n\n try:\n\n df_sectorWeightings = pd.json_normalize(df_metadata_all['sectorWeightings'].str[0].iloc[l])\n df_sectorWeightings['ticker'] = df_metadata_all['ticker'].iloc[l]\n df_sectorWeightings['insert_ts'] = df_metadata_all['insert_ts'].iloc[l]\n\n df_sectorWeightings_all = df_sectorWeightings_all.append(df_sectorWeightings)\n\n except Exception as e:\n print(e)\n\n\ndf_metadata_all = df_metadata_all.merge(df_sectorWeightings_all, on =['ticker', 'insert_ts'], how='left', suffixes=[\"\",\"sectorWeightings\"])\n\n\n\n\ndf_holdings_all.to_csv('.' + path + '/' + dstprefix + '_metadata_holdings.csv.csv', sep=';')\ndf_historic_all.to_csv('.' + path + '/' + dstprefix + '_5d_data.csv', sep=';')\ndf_metadata_all = df_metadata_all.set_index(['ticker', 'insert_ts'])\ndf_metadata_all.to_csv('.' + path + '/' + dstprefix + '_metadata.csv', sep=';')\n\n\n\n\n","sub_path":"src/download_data.py","file_name":"download_data.py","file_ext":"py","file_size_in_byte":7516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"576782859","text":"__author__ = 'rvuine'\n\nimport json\nimport os\n\nfrom micropsi_core.tools import post_mortem\nfrom micropsi_core.nodenet import monitor\nfrom micropsi_core.nodenet.node import Nodetype\nfrom micropsi_core.nodenet.nodenet import Nodenet, NODENET_VERSION\nfrom micropsi_core.nodenet.stepoperators import DoernerianEmotionalModulators\nfrom .dict_stepoperators import DictPropagate, DictCalculate\nfrom .dict_node import DictNode\nfrom .dict_nodespace import DictNodespace\nimport copy\n\nSTANDARD_NODETYPES = {\n \"Comment\": {\n \"name\": \"Comment\",\n \"symbol\": \"#\",\n 'parameters': ['comment'],\n \"shape\": \"Rectangle\"\n },\n\n \"Neuron\": {\n \"name\": \"Neuron\",\n \"slottypes\": [\"gen\"],\n \"nodefunction_name\": \"neuron\",\n \"gatetypes\": [\"gen\"]\n },\n \"Sensor\": {\n \"name\": \"Sensor\",\n \"parameters\": [\"datasource\"],\n \"nodefunction_name\": \"sensor\",\n \"gatetypes\": [\"gen\"]\n },\n \"Actuator\": {\n \"name\": \"Actuator\",\n \"parameters\": [\"datatarget\"],\n \"nodefunction_name\": \"actuator\",\n \"slottypes\": [\"gen\"],\n \"gatetypes\": [\"gen\"]\n },\n \"Concept\": {\n \"name\": \"Concept\",\n \"slottypes\": [\"gen\"],\n \"nodefunction_name\": \"concept\",\n \"gatetypes\": [\"gen\", \"por\", \"ret\", \"sub\", \"sur\", \"cat\", \"exp\", \"sym\", \"ref\"]\n },\n \"Script\": {\n \"name\": \"Script\",\n \"slottypes\": [\"gen\", \"por\", \"ret\", \"sub\", \"sur\"],\n \"nodefunction_name\": \"script\",\n \"gatetypes\": [\"gen\", \"por\", \"ret\", \"sub\", \"sur\", \"cat\", \"exp\", \"sym\", \"ref\"]\n },\n \"Pipe\": {\n \"name\": \"Pipe\",\n \"slottypes\": [\"gen\", \"por\", \"ret\", \"sub\", \"sur\", \"cat\", \"exp\"],\n \"nodefunction_name\": \"pipe\",\n \"gatetypes\": [\"gen\", \"por\", \"ret\", \"sub\", \"sur\", \"cat\", \"exp\"],\n \"parameters\": [\"expectation\", \"wait\"],\n \"symbol\": \"πp\",\n \"shape\": \"Rectangle\",\n \"parameter_defaults\": {\n \"expectation\": 1,\n \"wait\": 10\n }\n },\n \"Activator\": {\n \"name\": \"Activator\",\n \"slottypes\": [\"gen\"],\n \"parameters\": [\"type\"],\n \"parameter_values\": {\"type\": [\"por\", \"ret\", \"sub\", \"sur\", \"cat\", \"exp\", \"sym\", \"ref\", \"sampling\"]},\n \"nodefunction_name\": \"activator\"\n },\n \"LSTM\": {\n \"name\": \"LSTM\",\n \"slottypes\": [\"gen\", \"por\", \"gin\", \"gou\", \"gfg\"],\n \"gatetypes\": [\"gen\", \"por\", \"gin\", \"gou\", \"gfg\"],\n \"nodefunction_name\": \"lstm\",\n }\n}\n\n\nclass DictNodenet(Nodenet):\n \"\"\"Main data structure for MicroPsi agents,\n\n Contains the net entities and runs the activation spreading. The nodenet stores persistent data.\n\n Attributes:\n state: a dict of persistent nodenet data; everything stored within the state can be stored and exported\n uid: a unique identifier for the node net\n name: an optional name for the node net\n nodespaces: a dictionary of node space UIDs and respective node spaces\n nodes: a dictionary of node UIDs and respective nodes\n links: a dictionary of link UIDs and respective links\n gate_types: a dictionary of gate type names and the individual types of gates\n slot_types: a dictionary of slot type names and the individual types of slots\n node_types: a dictionary of node type names and node type definitions\n world: an environment for the node net\n worldadapter: an actual world adapter object residing in a world implementation, provides interface\n owner: an id of the user who created the node net\n step: the current calculation step of the node net\n \"\"\"\n\n @property\n def engine(self):\n return \"dict_engine\"\n\n @property\n def current_step(self):\n return self._step\n\n @property\n def worldadapter_instance(self):\n return self._worldadapter_instance\n\n @worldadapter_instance.setter\n def worldadapter_instance(self, _worldadapter_instance):\n self._worldadapter_instance = _worldadapter_instance\n if self._worldadapter_instance:\n for uid, node in self._nodes.items():\n # re-set parameters to filter for available datasources/-targets\n if node.type == \"Sensor\":\n node.set_parameter('datasource', node.get_parameter('datasource'))\n if node.type == \"Actuator\":\n node.set_parameter('datatarget', node.get_parameter('datatarget'))\n\n self._worldadapter_instance.nodenet = self\n\n def __init__(self, persistency_path, name=\"\", worldadapter=\"Default\", world=None, owner=\"\", uid=None, native_modules={}, use_modulators=True, worldadapter_instance=None, version=None):\n \"\"\"Create a new MicroPsi agent.\n\n Arguments:\n agent_type (optional): the interface of this agent to its environment\n name (optional): the name of the agent\n owner (optional): the user that created this agent\n uid (optional): unique handle of the agent; if none is given, it will be generated\n \"\"\"\n\n super().__init__(persistency_path, name, worldadapter, world, owner, uid, native_modules=native_modules, use_modulators=use_modulators, worldadapter_instance=worldadapter_instance, version=version)\n try:\n import numpy\n self.numpy_available = True\n except ImportError:\n self.numpy_available = False\n\n self.nodetypes = {}\n for type, data in STANDARD_NODETYPES.items():\n self.nodetypes[type] = Nodetype(nodenet=self, **data)\n\n self._nodes = {}\n self._nodespaces = {}\n self._last_assigned_node_id = 0\n\n self.nodegroups = {}\n\n self.initialize_nodenet({})\n\n def initialize_stepoperators(self):\n self.stepoperators = [DictPropagate(), DictCalculate()]\n if self.use_modulators:\n self.stepoperators.append(DoernerianEmotionalModulators())\n self.stepoperators.sort(key=lambda op: op.priority)\n\n def get_data(self, **params):\n data = super().get_data(**params)\n data['nodes'] = self.construct_nodes_dict(**params)\n data['nodespaces'] = self.construct_nodespaces_dict(\"Root\", transitive=True)\n data['modulators'] = self.construct_modulators_dict()\n data['last_assigned_node_id'] = self._last_assigned_node_id\n return data\n\n def export_json(self):\n data = self.get_data(complete=True, include_links=False)\n data['links'] = self.construct_links_list()\n return data\n\n def get_links_for_nodes(self, node_uids):\n source_nodes = [self.get_node(uid) for uid in node_uids]\n links = {}\n nodes = {}\n for node in source_nodes:\n nodelinks = node.get_associated_links()\n for l in nodelinks:\n links[l.signature] = l.get_data(complete=True)\n if l.source_node.parent_nodespace != node.parent_nodespace:\n nodes[l.source_node.uid] = l.source_node.get_data(include_links=False)\n if l.target_node.parent_nodespace != node.parent_nodespace:\n nodes[l.target_node.uid] = l.target_node.get_data(include_links=False)\n return list(links.values()), nodes\n\n def get_nodes(self, nodespace_uids=[], include_links=True, links_to_nodespaces=[]):\n \"\"\"\n Returns a dict with contents for the given nodespaces\n \"\"\"\n data = {}\n data['nodes'] = {}\n data['nodespaces'] = {}\n followupnodes = []\n fetch_all = False\n\n if nodespace_uids == []:\n nodespace_uids = self.get_nodespace_uids()\n root = self.get_nodespace(None)\n data['nodespaces'][root.uid] = root.get_data()\n fetch_all = True\n else:\n nodespace_uids = [self.get_nodespace(uid).uid for uid in nodespace_uids]\n\n for nodespace_uid in nodespace_uids:\n data['nodespaces'].update(self.construct_nodespaces_dict(nodespace_uid))\n nodespace = self.get_nodespace(nodespace_uid)\n for uid in nodespace.get_known_ids(entitytype=\"nodes\"):\n node = self.get_node(uid)\n data['nodes'][uid] = node.get_data(include_links=include_links)\n if include_links and not fetch_all:\n followupnodes.extend(node.get_associated_node_uids())\n\n if include_links:\n for uid in set(followupnodes):\n if uid not in data['nodes']:\n node = self.get_node(uid).get_data(include_links=True)\n for gate in list(node['links'].keys()):\n links = node['links'][gate]\n for idx, l in enumerate(links):\n if self._nodes[l['target_node_uid']].parent_nodespace not in nodespace_uids:\n del links[idx]\n if len(node['links'][gate]) == 0:\n del node['links'][gate]\n data['nodes'][uid] = node\n\n return data\n\n def save(self, base_path=None, zipfile=None):\n if base_path is None:\n base_path = self.persistency_path\n data = json.dumps(self.export_json(), indent=4)\n\n if self.numpy_available:\n import io\n import numpy as np\n # write numpy states of native modules\n numpy_states = self.construct_native_modules_numpy_state_dict()\n for node_uid, states in numpy_states.items():\n if len(states) > 0:\n filename = \"%s_numpystate.npz\" % node_uid\n if zipfile:\n stream = io.BytesIO()\n np.savez(stream, **states)\n stream.seek(0)\n zipfile.writestr(filename, stream.getvalue())\n else:\n np.savez(os.path.join(base_path, filename), **states)\n if zipfile:\n zipfile.writestr('nodenet.json', data)\n else:\n filename = os.path.join(base_path, 'nodenet.json')\n # dict_engine saves everything to json, just dump the json export\n with open(filename, 'w+', encoding=\"utf-8\") as fp:\n fp.write(data)\n if os.path.getsize(filename) < 100:\n # kind of hacky, but we don't really know what was going on\n raise RuntimeError(\"Error writing nodenet file\")\n\n def load(self):\n \"\"\"Load the node net from a file\"\"\"\n # try to access file\n if self._version != NODENET_VERSION:\n self.logger.error(\"Wrong version of nodenet data in nodenet %s, cannot load.\" % self.uid)\n return False\n filename = os.path.join(self.persistency_path, 'nodenet.json')\n with self.netlock:\n\n initfrom = {}\n\n if os.path.isfile(filename):\n try:\n self.logger.info(\"Loading nodenet %s from file %s\", self.name, filename)\n with open(filename, encoding=\"utf-8\") as file:\n initfrom.update(json.load(file))\n except ValueError:\n self.logger.warning(\"Could not read nodenet data\")\n return False\n except IOError:\n self.logger.warning(\"Could not open nodenet file\")\n return False\n\n self.initialize_nodenet(initfrom)\n if self.numpy_available:\n import numpy as np\n # recover numpy states for native modules\n for uid in self._nodes:\n if self._nodes[uid].type in self.native_modules:\n file = os.path.join(self.persistency_path, '%s_numpystate.npz' % uid)\n if os.path.isfile(file):\n node = self.get_node(uid)\n numpy_states = np.load(file)\n node.set_persistable_state(node._state, numpy_states)\n numpy_states.close()\n return True\n\n def _load_nodetypes(self, nodetype_data):\n newnative_modules = {}\n for key, data in nodetype_data.items():\n if data.get('engine', self.engine) == self.engine:\n try:\n if data.get('dimensionality'):\n raise NotImplementedError(\"dict nodenet does not support highdimensional native modules\")\n else:\n newnative_modules[key] = Nodetype(nodenet=self, **data)\n except Exception as err:\n self.logger.error(\"Can not instantiate node type %s: %s: %s\" % (key, err.__class__.__name__, str(err)))\n post_mortem()\n return newnative_modules\n\n def reload_native_modules(self, native_modules):\n \"\"\" reloads the native-module definition, and their nodefunctions\n and afterwards reinstantiates the nodenet.\"\"\"\n self.native_modules = self._load_nodetypes(native_modules)\n self.native_module_definitions = dict((uid, native_modules[uid]) for uid in self.native_modules)\n saved = self.export_json()\n self.clear()\n self.merge_data(saved, keep_uids=True)\n\n def initialize_nodespace(self, id, data):\n if id not in self._nodespaces:\n # move up the nodespace tree until we find an existing parent or hit root\n while id != 'Root' and data[id].get('parent_nodespace') not in self._nodespaces:\n self.initialize_nodespace(data[id]['parent_nodespace'], data)\n self._nodespaces[id] = DictNodespace(self,\n data[id].get('parent_nodespace'),\n name=data[id].get('name', 'Root'),\n uid=id,\n index=data[id].get('index'))\n\n def initialize_nodenet(self, initfrom):\n \"\"\"Called after reading new nodenet state.\n\n Parses the nodenet state and set up the non-persistent data structures necessary for efficient\n computation of the node net\n \"\"\"\n\n self._modulators.update(initfrom.get(\"modulators\", {}))\n\n if initfrom.get('runner_condition'):\n self.set_runner_condition(initfrom['runner_condition'])\n\n self._nodespace_ui_properties = initfrom.get('nodespace_ui_properties', {})\n\n # set up nodespaces; make sure that parent nodespaces exist before children are initialized\n self._nodespaces = {}\n self._nodespaces[\"Root\"] = DictNodespace(self, None, name=\"Root\", uid=\"Root\")\n\n if 'current_step' in initfrom:\n self._step = initfrom['current_step']\n if 'last_assigned_node_id' in initfrom:\n self._last_assigned_node_id = initfrom['last_assigned_node_id']\n\n if len(initfrom) != 0:\n # now merge in all init data (from the persisted file typically)\n self.merge_data(initfrom, keep_uids=True)\n\n def generate_uid(self, entitytype=None):\n self._last_assigned_node_id += 1\n return \"n%d\" % self._last_assigned_node_id\n\n def construct_links_list(self):\n data = []\n for node_uid in self.get_node_uids():\n node = self.get_node(node_uid)\n for g in node.get_gate_types():\n data.extend([l.get_data(complete=True) for l in node.get_gate(g).get_links()])\n return data\n\n def construct_nodes_dict(self, **params):\n data = {}\n for node_uid in self.get_node_uids():\n data[node_uid] = self.get_node(node_uid).get_data(**params)\n return data\n\n def construct_native_modules_numpy_state_dict(self):\n numpy_states = {}\n if self.numpy_available:\n for uid in self._nodes:\n numpy_state = self._nodes[uid].get_persistable_state()[1]\n if numpy_state:\n numpy_states[uid] = numpy_state\n return numpy_states\n\n def construct_nodespaces_dict(self, nodespace_uid, transitive=False):\n data = {}\n if nodespace_uid is None:\n nodespace_uid = \"Root\"\n\n if transitive:\n for nodespace_candidate_uid in self.get_nodespace_uids():\n is_in_hierarchy = False\n if nodespace_candidate_uid == nodespace_uid:\n is_in_hierarchy = True\n else:\n parent_uid = self.get_nodespace(nodespace_candidate_uid).parent_nodespace\n while parent_uid is not None and parent_uid != nodespace_uid:\n parent_uid = self.get_nodespace(parent_uid).parent_nodespace\n if parent_uid == nodespace_uid:\n is_in_hierarchy = True\n\n if is_in_hierarchy:\n data[nodespace_candidate_uid] = self.get_nodespace(nodespace_candidate_uid).get_data()\n else:\n for uid in self.get_nodespace(nodespace_uid).get_known_ids('nodespaces'):\n data[uid] = self.get_nodespace(uid).get_data()\n return data\n\n def get_nodetype(self, type):\n \"\"\" Returns the nodetpype instance for the given nodetype or native_module or None if not found\"\"\"\n if type in self.nodetypes:\n return self.nodetypes[type]\n else:\n return self.native_modules[type]\n\n def get_activation_data(self, nodespace_uids=None, rounded=1):\n activations = {}\n\n node_ids = []\n if nodespace_uids == []:\n node_ids = self._nodes.keys()\n else:\n for nsuid in nodespace_uids:\n node_ids.extend(self.get_nodespace(nsuid).get_known_ids(\"nodes\"))\n\n for uid in node_ids:\n node = self.get_node(uid)\n if rounded is None:\n act = [node.get_gate(gate_name).activation for gate_name in node.get_gate_types()]\n if set(act) != {0}:\n activations[uid] = act\n else:\n act = [round(node.get_gate(gate_name).activation, rounded) for gate_name in node.get_gate_types()]\n if set(act) != {0}:\n activations[uid] = act\n return activations\n\n def delete_node(self, node_uid):\n if node_uid in self._nodespaces:\n affected_entity_ids = self._nodespaces[node_uid].get_known_ids()\n for uid in affected_entity_ids:\n self.delete_node(uid)\n parent_nodespace = self._nodespaces.get(self._nodespaces[node_uid].parent_nodespace)\n if parent_nodespace and parent_nodespace.is_entity_known_as('nodespaces', node_uid):\n parent_nodespace._unregister_entity('nodespaces', node_uid)\n parent_nodespace.contents_last_changed = self.current_step\n del self._nodespaces[node_uid]\n self._track_deletion('nodespaces', node_uid)\n else:\n node = self._nodes[node_uid]\n node.unlink_completely()\n parent_nodespace = self._nodespaces.get(self._nodes[node_uid].parent_nodespace)\n parent_nodespace._unregister_entity('nodes', node_uid)\n parent_nodespace.contents_last_changed = self.current_step\n if self._nodes[node_uid].type == \"Activator\":\n parent_nodespace.unset_activator_value(self._nodes[node_uid].get_parameter('type'))\n del self._nodes[node_uid]\n self._track_deletion('nodes', node_uid)\n\n def delete_nodespace(self, nodespace_uid):\n self._nodespace_ui_properties.pop(nodespace_uid, None)\n self.delete_node(nodespace_uid)\n\n def clear(self):\n super().clear()\n self._nodes = {}\n self.initialize_nodenet({})\n\n def _register_node(self, node):\n self._nodes[node.uid] = node\n node.last_changed = self.current_step\n self.get_nodespace(node.parent_nodespace).contents_last_changed = self.current_step\n if node.type not in STANDARD_NODETYPES:\n self.native_module_instances[node.uid] = node\n\n def _register_nodespace(self, nodespace):\n self._nodespaces[nodespace.uid] = nodespace\n nodespace.last_changed = self.current_step\n self.get_nodespace(nodespace.parent_nodespace).contents_last_changed = self.current_step\n\n def merge_data(self, nodenet_data, keep_uids=False, uidmap={}, **_):\n \"\"\"merges the nodenet state with the current node net, might have to give new UIDs to some entities\"\"\"\n\n # merge in spaces, make sure that parent nodespaces exist before children are initialized\n nodespaces_to_merge = set(nodenet_data.get('nodespaces', {}).keys())\n for nodespace in nodespaces_to_merge:\n self.initialize_nodespace(nodespace, nodenet_data['nodespaces'])\n\n invalid_nodes = []\n\n # merge in nodes\n for uid in nodenet_data.get('nodes', {}):\n data = nodenet_data['nodes'][uid]\n if not keep_uids:\n newuid = self.generate_uid(\"nodes\")\n else:\n newuid = uid\n data['uid'] = newuid\n uidmap[uid] = newuid\n if data['type'] not in self.nodetypes and data['type'] not in self.native_modules:\n self.logger.error(\"Invalid nodetype %s for node %s\" % (data['type'], uid))\n invalid_nodes.append(uid)\n continue\n self._nodes[newuid] = DictNode(self, **data)\n\n # merge in links\n links = nodenet_data.get('links', [])\n if isinstance(links, dict):\n # compatibility\n links = links.values()\n for link in links:\n if link['source_node_uid'] in invalid_nodes or link['target_node_uid'] in invalid_nodes:\n continue\n try:\n self.create_link(\n uidmap[link['source_node_uid']],\n link['source_gate_name'],\n uidmap[link['target_node_uid']],\n link['target_slot_name'],\n link['weight']\n )\n except ValueError:\n self.logger.warning(\"Invalid link data\")\n\n for monitorid in nodenet_data.get('monitors', {}):\n data = nodenet_data['monitors'][monitorid]\n if 'node_uid' in data:\n old_node_uid = data['node_uid']\n if old_node_uid in uidmap:\n data['node_uid'] = uidmap[old_node_uid]\n if 'classname' in data:\n if hasattr(monitor, data['classname']):\n mon = getattr(monitor, data['classname'])(self, **data)\n self._monitors[mon.uid] = mon\n else:\n self.logger.warning('unknown classname for monitor: %s (uid:%s) ' % (data['classname'], monitorid))\n\n def step(self):\n \"\"\"perform a calculation step\"\"\"\n with self.netlock:\n\n self._step += 1\n\n for operator in self.stepoperators:\n operator.execute(self, self._nodes.copy(), self.netapi)\n\n steps = sorted(list(self.deleted_items.keys()))\n if steps:\n for i in steps:\n if i >= self.current_step - 100:\n break\n else:\n del self.deleted_items[i]\n self.user_prompt_response = {}\n\n def create_node(self, nodetype, nodespace_uid, position, name=\"\", uid=None, parameters=None, gate_configuration=None):\n nodespace_uid = self.get_nodespace(nodespace_uid).uid\n\n if nodetype in self.native_modules:\n if name is None or name == \"\" or name == uid:\n name = nodetype\n\n node = DictNode(\n self,\n nodespace_uid,\n position, name=name,\n type=nodetype,\n uid=uid,\n parameters=parameters,\n gate_configuration=gate_configuration)\n return node.uid\n\n def create_nodespace(self, parent_uid, name=\"\", uid=None, options=None):\n parent_uid = self.get_nodespace(parent_uid).uid\n nodespace = DictNodespace(self, parent_uid, name=name, uid=uid)\n return nodespace.uid\n\n def get_node(self, uid):\n return self._nodes[uid]\n\n def get_nodespace(self, uid):\n if uid is None:\n uid = \"Root\"\n return self._nodespaces[uid]\n\n def get_node_uids(self, group_nodespace_uid=None, group=None):\n if group is not None:\n if group_nodespace_uid is None:\n group_nodespace_uid = self.get_nodespace(None).uid\n return [n.uid for n in self.nodegroups[group_nodespace_uid][group][0]]\n else:\n return list(self._nodes.keys())\n\n def get_nodespace_uids(self):\n return list(self._nodespaces.keys())\n\n def is_node(self, uid):\n return uid in self._nodes\n\n def is_nodespace(self, uid):\n return uid in self._nodespaces\n\n def set_node_positions(self, positions):\n \"\"\" Sets the position of nodes or nodespaces \"\"\"\n for uid in positions:\n if uid in self._nodes:\n self._nodes[uid].position = positions[uid]\n\n def get_nativemodules(self, nodespace=None):\n \"\"\"Returns a dict of native modules. Optionally filtered by the given nodespace\"\"\"\n nodes = self._nodes if nodespace is None else self._nodespaces[nodespace].get_known_ids('nodes')\n nativemodules = {}\n for uid in nodes:\n if self._nodes[uid].type not in STANDARD_NODETYPES:\n nativemodules.update({uid: self._nodes[uid]})\n return nativemodules\n\n def get_activators(self, nodespace=None, type=None):\n \"\"\"Returns a dict of activator nodes. OPtionally filtered by the given nodespace and the given type\"\"\"\n nodes = self._nodes if nodespace is None else self._nodespaces[nodespace].get_known_ids('nodes')\n activators = {}\n for uid in nodes:\n if self._nodes[uid].type == 'Activator':\n if type is None or type == self._nodes[uid].get_parameter('type'):\n activators.update({uid: self._nodes[uid]})\n return activators\n\n def get_sensors(self, nodespace=None, datasource=None):\n \"\"\"Returns a dict of all sensor nodes. Optionally filtered by the given nodespace\"\"\"\n nodes = self._nodes if nodespace is None else self._nodespaces[nodespace].get_known_ids('nodes')\n sensors = {}\n for uid in nodes:\n if self._nodes[uid].type == 'Sensor':\n if datasource is None or self._nodes[uid].get_parameter('datasource') == datasource:\n sensors[uid] = self._nodes[uid]\n return sensors\n\n def get_actuators(self, nodespace=None, datatarget=None):\n \"\"\"Returns a dict of all actuator nodes. Optionally filtered by the given nodespace\"\"\"\n nodes = self._nodes if nodespace is None else self._nodespaces[nodespace].get_known_ids('nodes')\n actuators = {}\n for uid in nodes:\n if self._nodes[uid].type == 'Actuator':\n if datatarget is None or self._nodes[uid].get_parameter('datatarget') == datatarget:\n actuators[uid] = self._nodes[uid]\n return actuators\n\n def set_link_weight(self, source_node_uid, gate_type, target_node_uid, slot_type, weight=1):\n \"\"\"Set weight of the given link.\"\"\"\n\n source_node = self.get_node(source_node_uid)\n if source_node is None:\n return False\n\n link = source_node.link(gate_type, target_node_uid, slot_type, weight)\n if link is None:\n return False\n else:\n return True\n\n def create_link(self, source_node_uid, gate_type, target_node_uid, slot_type, weight=1):\n \"\"\"Creates a new link.\n\n Arguments.\n source_node_uid: uid of the origin node\n gate_type: type of the origin gate (usually defines the link type)\n target_node_uid: uid of the target node\n slot_type: type of the target slot\n weight: the weight of the link (a float)\n\n Returns:\n the link if successful,\n None if failure\n \"\"\"\n\n source_node = self.get_node(source_node_uid)\n if source_node is None:\n return False, None\n\n source_node.link(gate_type, target_node_uid, slot_type, weight)\n return True\n\n def delete_link(self, source_node_uid, gate_type, target_node_uid, slot_type):\n \"\"\"Delete the given link.\"\"\"\n\n source_node = self.get_node(source_node_uid)\n if source_node is None:\n return False, None\n source_node.unlink(gate_type, target_node_uid, slot_type)\n return True\n\n def construct_modulators_dict(self):\n \"\"\"\n Returns a new dict containing all modulators\n \"\"\"\n return self._modulators.copy()\n\n def get_standard_nodetype_definitions(self):\n \"\"\"\n Returns the standard node types supported by this nodenet\n \"\"\"\n return copy.deepcopy(STANDARD_NODETYPES)\n\n def group_nodes_by_names(self, nodespace_uid, node_name_prefix=None, gatetype=\"gen\", sortby='id', group_name=None):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if nodespace_uid not in self.nodegroups:\n self.nodegroups[nodespace_uid] = {}\n\n if group_name is None:\n group_name = node_name_prefix\n\n nodes = self.netapi.get_nodes(nodespace_uid, node_name_prefix)\n if sortby == 'id':\n nodes = sorted(nodes, key=lambda node: node.uid)\n elif sortby == 'name':\n nodes = sorted(nodes, key=lambda node: node.name)\n self.nodegroups[nodespace_uid][group_name] = (nodes, gatetype)\n\n def group_nodes_by_ids(self, nodespace_uid, node_uids, group_name, gatetype=\"gen\", sortby=None):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if nodespace_uid not in self.nodegroups:\n self.nodegroups[nodespace_uid] = {}\n\n nodes = []\n for node_uid in node_uids:\n node = self.get_node(node_uid)\n if node.parent_nodespace != nodespace_uid:\n raise ValueError(\"Node %s is not in nodespace %s\" % (node_uid, nodespace_uid))\n nodes.append(node)\n if sortby == 'id':\n nodes = sorted(nodes, key=lambda node: node.uid)\n elif sortby == 'name':\n nodes = sorted(nodes, key=lambda node: node.name)\n self.nodegroups[nodespace_uid][group_name] = (nodes, gatetype)\n\n def ungroup_nodes(self, nodespace_uid, group):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if group in self.nodegroups[nodespace_uid]:\n del self.nodegroups[nodespace_uid][group]\n\n def get_activations(self, nodespace_uid, group):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if group not in self.nodegroups[nodespace_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group, nodespace_uid))\n activations = []\n nodes = self.nodegroups[nodespace_uid][group][0]\n gate = self.nodegroups[nodespace_uid][group][1]\n for node in nodes:\n activations.append(node.get_gate(gate).activation)\n return activations\n\n def set_activations(self, nodespace_uid, group, new_activations):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if group not in self.nodegroups[nodespace_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group, nodespace_uid))\n nodes = self.nodegroups[nodespace_uid][group][0]\n gate = self.nodegroups[nodespace_uid][group][1]\n for i in range(len(nodes)):\n nodes[i].set_gate_activation(gate, new_activations[i])\n\n def get_gate_configurations(self, nodespace_uid, group, gatefunction_parameter=None):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if group not in self.nodegroups[nodespace_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group, nodespace_uid))\n nodes = self.nodegroups[nodespace_uid][group][0]\n gate = self.nodegroups[nodespace_uid][group][1]\n data = {'gatefunction': set()}\n if gatefunction_parameter:\n data['parameter_values'] = []\n for node in nodes:\n config = node.get_gate_configuration(gate)\n data['gatefunction'].add(config['gatefunction'])\n if gatefunction_parameter is not None:\n data['parameter_values'].append(config['gatefunction_parameters'].get(gatefunction_parameter, 0))\n if len(data['gatefunction']) > 1:\n raise RuntimeError(\"Heterogenous gatefunction configuration\")\n data['gatefunction'] = data['gatefunction'].pop()\n return data\n\n def set_gate_configurations(self, nodespace_uid, group, gatefunction, gatefunction_parameter=None, parameter_values=None):\n if nodespace_uid is None:\n nodespace_uid = self.get_nodespace(None).uid\n\n if group not in self.nodegroups[nodespace_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group, nodespace_uid))\n nodes = self.nodegroups[nodespace_uid][group][0]\n gate = self.nodegroups[nodespace_uid][group][1]\n for i in range(len(nodes)):\n parameter = {}\n if gatefunction_parameter:\n parameter[gatefunction_parameter] = parameter_values[i]\n nodes[i].set_gate_configuration(gate, gatefunction, parameter)\n\n def get_link_weights(self, nodespace_from_uid, group_from, nodespace_to_uid, group_to):\n if nodespace_from_uid is None:\n nodespace_from_uid = self.get_nodespace(None).uid\n if nodespace_to_uid is None:\n nodespace_to_uid = self.get_nodespace(None).uid\n\n if group_from not in self.nodegroups[nodespace_from_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group_from, nodespace_from_uid))\n if group_to not in self.nodegroups[nodespace_to_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group_to, nodespace_to_uid))\n rows = []\n to_nodes = self.nodegroups[nodespace_to_uid][group_to][0]\n to_slot = self.nodegroups[nodespace_to_uid][group_to][1]\n from_nodes = self.nodegroups[nodespace_from_uid][group_from][0]\n from_gate = self.nodegroups[nodespace_from_uid][group_from][1]\n for to_node in to_nodes:\n row = []\n for from_node in from_nodes:\n links = from_node.get_gate(from_gate).get_links()\n hit = None\n for link in links:\n if link.target_node == to_node and link.target_slot.type == to_slot:\n hit = link\n break\n if hit is not None:\n row.append(link.weight)\n else:\n row.append(0)\n rows.append(row)\n return rows\n\n def set_link_weights(self, nodespace_from_uid, group_from, nodespace_to_uid, group_to, new_w):\n if nodespace_from_uid is None:\n nodespace_from_uid = self.get_nodespace(None).uid\n if nodespace_to_uid is None:\n nodespace_to_uid = self.get_nodespace(None).uid\n\n if group_from not in self.nodegroups[nodespace_from_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group_from, nodespace_from_uid))\n if group_to not in self.nodegroups[nodespace_to_uid]:\n raise ValueError(\"Group %s does not exist in nodespace %s\" % (group_to, nodespace_to_uid))\n to_nodes = self.nodegroups[nodespace_to_uid][group_to][0]\n to_slot = self.nodegroups[nodespace_to_uid][group_to][1]\n from_nodes = self.nodegroups[nodespace_from_uid][group_from][0]\n from_gate = self.nodegroups[nodespace_from_uid][group_from][1]\n\n if type(new_w) == int and new_w == 1:\n if len(from_nodes) != len(to_nodes):\n raise ValueError(\"from_elements and to_elements need to have equal lengths for identity links\")\n for i in range(len(to_nodes)):\n self.set_link_weight(\n from_nodes[i].uid,\n from_gate,\n to_nodes[i].uid,\n to_slot,\n 1\n )\n\n else:\n for row in range(len(to_nodes)):\n to_node = to_nodes[row]\n for column in range(len(from_nodes)):\n from_node = from_nodes[column]\n weight = new_w[row][column]\n if weight != 0:\n self.set_link_weight(from_node.uid, from_gate, to_node.uid, to_slot, weight)\n else:\n self.delete_link(from_node.uid, from_gate, to_node.uid, to_slot)\n\n def get_available_gatefunctions(self):\n \"\"\"\n Returns a dict of the available gatefunctions and their parameters and parameter-defaults\n \"\"\"\n import inspect\n from micropsi_core.nodenet import gatefunctions\n data = {}\n for name, func in inspect.getmembers(gatefunctions, inspect.isfunction):\n sig = inspect.signature(func)\n data[name] = {}\n skip = True\n for key in sig.parameters:\n if skip:\n # first param is input_activation. skip\n skip = False\n continue\n default = sig.parameters[key].default\n if default == inspect.Signature.empty:\n default = None\n data[name][key] = default\n return data\n\n def has_nodespace_changes(self, nodespace_uids=[], since_step=0):\n if nodespace_uids == []:\n nodespace_uids = self.get_nodespace_uids()\n\n for nodespace_uid in nodespace_uids:\n if self.get_nodespace(nodespace_uid).contents_last_changed >= since_step:\n return True\n return False\n\n def get_nodespace_changes(self, nodespace_uids=[], since_step=0, include_links=True):\n result = {\n 'nodes_dirty': {},\n 'nodespaces_dirty': {},\n 'nodes_deleted': [],\n 'nodespaces_deleted': []\n }\n\n if nodespace_uids == []:\n nodespace_uids = self.get_nodespace_uids()\n else:\n nodespace_uids = [self.get_nodespace(uid).uid for uid in nodespace_uids]\n\n for i in range(since_step, self.current_step + 1):\n if i in self.deleted_items:\n result['nodespaces_deleted'].extend(self.deleted_items[i].get('nodespaces_deleted', []))\n result['nodes_deleted'].extend(self.deleted_items[i].get('nodes_deleted', []))\n\n for nsuid in nodespace_uids:\n for uid in self.get_nodespace(nsuid).get_known_ids():\n if uid not in result['nodes_deleted'] and self.is_node(uid):\n if self.get_node(uid).last_changed >= since_step:\n result['nodes_dirty'][uid] = self.get_node(uid).get_data(include_links=include_links)\n if include_links:\n for assoc in self.get_node(uid).get_associated_node_uids():\n if self.get_node(assoc).parent_nodespace not in nodespace_uids and assoc not in result['nodes_dirty']:\n result['nodes_dirty'][assoc] = self.get_node(assoc).get_data(include_links=include_links)\n\n elif uid not in result['nodespaces_deleted'] and self.is_nodespace(uid):\n if self.get_nodespace(uid).last_changed >= since_step:\n result['nodespaces_dirty'][uid] = self.get_nodespace(uid).get_data()\n return result\n\n def get_dashboard(self):\n data = super(DictNodenet, self).get_dashboard()\n link_uids = []\n node_uids = self.get_node_uids()\n data['count_nodes'] = len(node_uids)\n data['count_positive_nodes'] = 0\n data['count_negative_nodes'] = 0\n data['nodetypes'] = {\"NativeModules\": 0}\n data['concepts'] = {\n 'checking': 0,\n 'verified': 0,\n 'failed': 0,\n 'off': 0\n }\n data['schemas'] = {\n 'checking': 0,\n 'verified': 0,\n 'failed': 0,\n 'off': 0,\n 'total': 0\n }\n for uid in node_uids:\n node = self.get_node(uid)\n link_uids.extend(node.get_associated_links())\n if node.type in STANDARD_NODETYPES:\n if node.type not in data['nodetypes']:\n data['nodetypes'][node.type] = 1\n else:\n data['nodetypes'][node.type] += 1\n else:\n data['nodetypes']['NativeModules'] += 1\n if node.activation > 0:\n data['count_positive_nodes'] += 1\n elif node.activation < 0:\n data['count_negative_nodes'] += 1\n if node.type == 'Pipe':\n if node.get_gate('gen').activation == 0 and node.get_gate('sub').activation > 0 and len(node.get_gate('sub').get_links()):\n data['concepts']['checking'] += 1\n if node.get_gate('sur').get_links() == []:\n data['schemas']['checking'] += 1\n elif node.get_gate('sub').activation > 0 and node.activation > 0.5:\n data['concepts']['verified'] += 1\n if node.get_gate('sur').get_links() == []:\n data['schemas']['verified'] += 1\n elif node.activation < 0:\n data['concepts']['failed'] += 1\n if node.get_gate('sur').get_links() == []:\n data['schemas']['failed'] += 1\n else:\n data['concepts']['off'] += 1\n if node.get_gate('sur').get_links() == []:\n data['schemas']['off'] += 1\n data['concepts']['total'] = sum(data['concepts'].values())\n data['schemas']['total'] = sum(data['schemas'].values())\n data['modulators'] = self.construct_modulators_dict()\n data['count_links'] = len(set(link_uids))\n return data\n","sub_path":"micropsi_core/nodenet/dict_engine/dict_nodenet.py","file_name":"dict_nodenet.py","file_ext":"py","file_size_in_byte":42411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"185091893","text":"\"\"\"\nYour chance to explore Loops and Turtles!\n\nAuthors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,\n their colleagues and Tianxi He.\n\"\"\"\n########################################################################\n# DONE: 1.\n# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.\n########################################################################\n\n########################################################################\n# DONE: 2.\n#\n# You should have RUN the PREVIOUS module and READ its code.\n# (Do so now if you have not already done so.)\n#\n# Below this comment, add ANY CODE THAT YOUR WANT, as long as:\n# 1. You construct at least 2 rg.SimpleTurtle objects.\n# 2. Each rg.SimpleTurtle object draws something\n# (by moving, using its rg.Pen). ANYTHING is fine!\n# 3. Each rg.SimpleTurtle moves inside a LOOP.\n#\n# Be creative! Strive for way-cool pictures! Abstract pictures rule!\n#\n# If you make syntax (notational) errors, no worries -- get help\n# fixing them at either this session OR at the NEXT session.\n#\n# Don't forget to COMMIT your work by using VCS ~ Commit and Push.\n########################################################################\nimport rosegraphics as rg\nwindow = rg.TurtleWindow()\nZACK= rg.SimpleTurtle('turtle')\nZACK.pen = rg.Pen('gray', 3)\nZACK.speed = 10\nCHIGO = rg.SimpleTurtle('turtle')\nCHIGO.pen = rg.Pen('white', 3)\nCHIGO.left(90)\nCHIGO.forward(100)\nCHIGO.right(180)\nCHIGO.speed = 10\nnubleth=10\nsizec=200\nfor k in range(5):\n ZACK.draw_regular_polygon(nubleth,100)\n nubleth=nubleth-1\n CHIGO.pen = rg.Pen('red', 3)\nfor g in range(5):\n CHIGO.pen = rg.Pen('white', 3)\n CHIGO.forward(70)\n CHIGO.pen = rg.Pen('red', 3)\n CHIGO.draw_circle(sizec)\n sizec=sizec-20\n","sub_path":"src/m5_your_turtles.py","file_name":"m5_your_turtles.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"585567827","text":"#!/usr/bin/env python3\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport psutil\n\nfrom utils import *\nfrom wrappers import *\nfrom model import ActorCritic\n\n\ndef train(pid, rank, args, shared_model, counter, lock, optimizer=None):\n torch.manual_seed(args.seed + rank)\n env = create_atari_env(args.env_name, episode_life=False, frame_stack=True, scale=True, normalize=False, clip_rewards=False)\n filepath = \"./train_model_\" + str(rank)\n env = gym.wrappers.Monitor(env, filepath, force=True)\n env.seed(args.seed + rank)\n\n model = ActorCritic(4, env.action_space.n)\n\n if optimizer is None:\n optimizer = optim.Adam(shared_model.parameters(), lr=args.lr)\n model.train()\n obs = env.reset()\n state = get_state(obs)\n done = True\n while True:\n # if parent process is killed by \"kill -9\", child process kill itself\n pps = psutil.Process(pid=pid)\n try:\n if pps.status() in (psutil.STATUS_DEAD, psutil.STATUS_STOPPED):\n break\n except psutil.NoSuchProcess:\n break\n # Sync with the shared model\n model.load_state_dict(shared_model.state_dict())\n values = []\n log_probs = []\n rewards = []\n entropies = []\n if done:\n cx = torch.zeros(1, 256)\n hx = torch.zeros(1, 256)\n else:\n cx = cx.detach()\n hx = hx.detach()\n\n for step in range(args.num_steps):\n value, logit, (hx, cx) = model((state, (hx, cx)))\n prob = F.softmax(logit, dim=-1)\n log_prob = F.log_softmax(logit, dim=-1)\n entropy = -(log_prob * prob).sum(1, keepdim=True)\n # sampled from the multinomial probability distribution\n action = prob.multinomial(num_samples=1).detach() # [[1]]\n log_prob = log_prob.gather(1, action)\n obs, reward, done, _ = env.step(action.numpy())\n # done = (done or episode_length >= params.max_episode_length) # if the episode lasts too long (the agent is stucked), then it is done\n # reward = max(min(reward, 1), -1) # clamping the reward between -1 and +1\n with lock:\n counter.value += 1\n if done:\n obs = env.reset()\n state = get_state(obs)\n entropies.append(entropy)\n values.append(value)\n log_probs.append(log_prob)\n rewards.append(reward)\n if done:\n # print(\"step {} done {}\".format(step, done))\n break\n\n # Gradient = ∇θ′logπ(at|st;θ′)[Rt−V(st;θv) + β∇θ′H(π(st;θ′)]\n # gae-lambda - 1.00\n # entropy-coef - 0.01\n # value-loss-coef - 0.5\n # max-grad-norm - 40\n # gamma - 0.99\n R = torch.zeros(1, 1) # if done R=[[0]]\n\n if not done:\n value, _, _ = model((state, (hx, cx)))\n R = value.detach()\n values.append(R)\n policy_loss = 0\n value_loss = 0\n gae = torch.zeros(1, 1) # Generalized Advantage Estimation\n for i in reversed(range(len(rewards))):\n # advantege = Q - V\n R = rewards[i] + args.gamma * R # n-step\n advantage = R - values[i]\n # TODO: Confused\n value_loss = value_loss + 0.5 * advantage.pow(2)\n # Generalized Advantage Estimation\n td_error = rewards[i] + args.gamma * values[i + 1] - values[i]\n gae = gae * args.gamma * args.gae_lambda + td_error\n policy_loss = policy_loss - log_probs[i] * gae.detach() - args.entropy_coef * entropies[i]\n\n optimizer.zero_grad()\n # if not work, change pytorch to 1.4.0\n (policy_loss + args.value_loss_coef * value_loss).backward() # we give 2x more importance to the policy loss than the value loss because the policy loss is smaller\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) # clamping the values of gradient between 0 and 40 to prevent the gradient from taking huge values and degenerating the algorithm\n ensure_shared_grads(model, shared_model)\n optimizer.step()\n # print(\"from train{} counter = {}\".format(rank, counter.value))\n","sub_path":"A3C_Wrappers/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"630818275","text":"import socket\nimport time \nimport json\nimport tqdm\nBufferSize = 100 # 100 Bytes for downloading data from server\n\naddress = \"localhost\"\n\nport = 5050\n\nUTF8 = \"utf-8\"\n\nc = socket.socket()\n\nc.connect((address,port))\nprint(\"Enter 1 for request list of files\")\nprint(\"Enter 2 for download a file\")\ncheck = input()\nif check == \"1\":\n Get_List_of_File = []\n Get_List_of_File.append(\"0x0000\")\n Get_List_of_File = json.dumps(Get_List_of_File)\n c.send(Get_List_of_File.encode(UTF8)) \n data = c.recv(1024)\n data = json.loads(data) \n print(data)\nelif check == \"2\":\n Download_File = []\n Download_File.append(\"0x0001\")\n file_name = input(\"Enter file name for download --->\")\n Download_File.append(file_name)\n Download_File = json.dumps(Download_File)\n Download_File = Download_File.encode(UTF8)\n #Sending file name to server for download\n c.send(Download_File)\n data = c.recv(1024)\n data = data.decode(UTF8)\n data = json.loads(data)\n fileType = data[0]\n fileName = data[1]\n fileSize = data[2]\n if fileType == \"0x0011\" and fileSize == \"0\":\n print(data)\n else:\n print(data) \n #From server started downloading\n fileSize = int(fileSize)\n progress = tqdm.tqdm(range(fileSize), f\"Receiving {fileName}\", unit=\"B\", unit_scale=True, unit_divisor=1024)\n with open(fileName, \"wb\") as file:\n while True:\n #downloading data from server \n bytesRead = c.recv(BufferSize)\n if not bytesRead: \n break\n #Writing data into file \n file.write(bytesRead)\n progress.update(len(bytesRead))\n\n c.close()\n \n\n","sub_path":"client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"316612843","text":"import tkinter as tk\nfrom tkinter import messagebox\nimport tkinter.font as tkFont\nfrom datetime import date\n\nimport Patient\nfrom database import DatabaseConnection\n\nclass SampleApp(tk.Tk):\n\n def __init__(self):\n tk.Tk.__init__(self)\n fontStyle = tkFont.Font(family=\"Lucida Grande\", size=36)\n self.radio_ = tk.StringVar()\n self.geometry(\"600x500\")\n\n self.nameLabel=tk.Label(self, text=\"name\",font=36)\n self.name = tk.Entry(self)\n self.ageLabel = tk.Label(self, text=\"age\")\n self.age = tk.Entry(self)\n self.mobileLabel = tk.Label(self, text=\"mobileNo\")\n self.mobile = tk.Entry(self)\n self.diseaseLabel = tk.Label(self, text=\"Disease\")\n self.disease = tk.Entry(self)\n self.genderLabel = tk.Label(self, text=\"Gender\")\n self.radio=tk.Radiobutton(self,text=\"Male\",variable=self.radio_,value=\"male\",command=self.selection)\n self.radio2 = tk.Radiobutton(self, text=\"Female\", variable=self.radio_, value=\"female\", command=self.selection)\n self.billLabel = tk.Label(self, text=\"Bill\")\n self.bill = tk.Entry(self)\n self.bloodGroupLabel = tk.Label(self, text=\"Blood Group\")\n self.blood = tk.Entry(self)\n self.button = tk.Button(self, text=\"Admit Patient\", command=self.on_button)\n\n self.nameLabel.grid(row=5, column=10)\n self.name.grid(row=5,column=15)\n self.genderLabel.grid(row=20,column=10)\n self.radio.grid(row=20,column=15)\n self.radio2.grid(row=20, column=18)\n self.mobileLabel.grid(row=35,column=10)\n self.mobile.grid(row=35,column=15)\n self.diseaseLabel.grid(row=50,column=10)\n self.disease.grid(row=50,column=15)\n self.ageLabel.grid(row=75,column=10)\n self.age.grid(row=75,column=15)\n self.bloodGroupLabel.grid(row=100,column=10)\n self.blood.grid(row=100,column=15)\n self.billLabel.grid(row=115, column=10)\n self.bill.grid(row=115, column=15)\n\n self.button.grid(row=130, column=5)\n\n def selection(self):\n selection = \"You selected the option \" + str(self.radio_.get())\n print(selection)\n def on_button(self):\n name=self.name.get()\n age=self.age.get()\n mobile=self.mobile.get()\n gender=self.radio.getvar(\"PY_VAR0\")\n disease=self.disease.get()\n bill=self.bill.get()\n blood=self.blood.get()\n p=Patient.PatientEntity(name,age,mobile,disease,date.today(),gender,blood,bill)\n flag=DatabaseConnection().insertPatientDetail(p)\n if flag>=0:\n\n messagebox.showinfo(\"correct\",\"patient admitted successfully\")\n self.destroy()\n else:\n messagebox.showerror(\"error\",\"something went wrong\")\n\n def call(self):\n app = SampleApp()\n\n app.mainloop()\n\n","sub_path":"AdmitPatientRecord.py","file_name":"AdmitPatientRecord.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"210398889","text":"#! /usr/bin/env python3\nimport os, sys, re\n\n\ndef run_process(args):\n # this try/except hands IO redirection\n try:\n if '>' in args: # Output redirection\n os.close(1) # redirect child's stdout\n os.open(args[args.index('>') + 1], os.O_CREAT | os.O_WRONLY)\n os.set_inheritable(1, True)\n args.remove(args[args.index('>') + 1]) # Remove the file name from the args list\n args.remove('>') # Remove the '>' character from the arguments list\n\n if '<' in args: # Input redirection\n os.close(0) # redirect child's stdin\n os.open(args[args.index('<') + 1], os.O_RDONLY) # Open the file in readonly\n os.set_inheritable(0, True)\n args.remove(args[args.index('<') + 1]) # Remove the file name from the args list\n args.remove('<') # Remove the '<' character from the arguments list\n\n except IndexError:\n os.write(2, \"Invalid input for redirection\\n\".encode())\n try:\n if args[0][0] == '/':\n os.execve(args[0], args, os.environ) # try to exec program\n except FileNotFoundError: # ...expected\n pass\n except IndexError:\n quit(1)\n except Exception: # If the program doesn't work for some other reason just quit\n quit(1)\n\n for dir in re.split(\":\", os.environ['PATH']): # try each directory in path\n program = \"%s/%s\" % (dir, args[0])\n try:\n os.execve(program, args, os.environ) # try to exec program\n except FileNotFoundError: # ...expected\n pass\n except Exception: # If the program doesn't work for some other reason just quit\n quit(1)\n os.write(2, (\"%s: Command not found\\n\" % args[0]).encode())\n quit(1)\n\n\ndef pipe(args):\n writeCommands = args[0:args.index(\"|\")]\n readCommands = args[args.index(\"|\") + 1:]\n pr, pw = os.pipe()\n rc = os.fork()\n if rc < 0:\n os.write(2, (\"fork failed, returning %d\\n\" % rc).encode())\n sys.exit(1)\n elif rc == 0:\n os.close(1) # close fd 1 (output)\n os.dup2(pw, 1) # duplicate pw in fd1\n for fd in (pr, pw):\n os.close(fd) # close pw & pr\n run_process(writeCommands) # Run the process as normal\n os.write(2, (\"Could not exec %s\\n\" % writeCommands[0]).encode())\n sys.exit(1)\n else:\n os.close(0) # close fd 0 (input)\n os.dup2(pr, 0) # dup pr in fd0\n for fd in (pw, pr):\n os.close(fd)\n if \"|\" in readCommands:\n pipe(readCommands)\n run_process(readCommands) # Run the process as normal\n os.write(2, (\"Could not exec %s\\n\" % writeCommands[0]).encode())\n sys.exit(1)\n\n\ndef command_handler(args):\n if len(args) == 0:\n return\n\n if args[0].lower() == 'exit':\n os.write(2, \"Goodbye!\\n\".encode())\n quit(0)\n if args[0] == 'cd':\n try:\n os.chdir(args[1])\n except FileNotFoundError:\n os.write(2, (\"Directory %s not found\\n\" % args[1]).encode())\n except IndexError:\n os.write(2, \"Must write a directory to swap to\\n\".encode())\n\n elif \"|\" in args:\n # fork1 ensures that the shell keeps running after the pipe occurs\n fork1 = os.fork()\n if fork1 < 0:\n os.write(2, (\"fork failed, returning %d\\n\" % fork1).encode())\n sys.exit(1)\n elif fork1 == 0:\n pipe(args)\n else: # parent (forked ok)\n if args[-1] != \"&\": # If the command is to be run in the background don't wait, otherwise wait\n val = os.wait()\n if val[1] != 0 and val[1] != 256:\n os.write(2, (\"Program terminated with exit code: %d\\n\" % val[1]).encode())\n\n else:\n rc = os.fork()\n\n # By default, the shell will wait for a program to finish. If & is present, it will not\n wait = True\n\n if \"&\" in args:\n wait = False\n args.remove(\"&\")\n\n if rc < 0: # check if fork was successful\n os.write(2, (\"fork failed, returning %d\\n\" % rc).encode())\n sys.exit(1)\n elif rc == 0: # child\n run_process(args)\n else: # parent (forked ok)\n if wait:\n val = os.wait()\n if val[1] != 0 and val[1] != 256:\n os.write(2, (\"Program terminated with exit code: %d\\n\" % val[1]).encode())\n\n\nwhile True:\n # \\033[1;34;40m changes the color to blue and \\x1b[0m changes it back to normal\n # This was done in an attempt to make the shell more readable\n\n prompt = \"\\033[1;34;40m %s\\x1b[0m$ \" % os.getcwd()\n if 'PS1' in os.environ:\n prompt = os.environ['PS1']\n\n try:\n os.write(1, prompt.encode())\n args = os.read(0, 10000)\n\n if len(args) == 0:\n break\n args = args.decode().split(\"\\n\")\n\n # if it's empty, continue\n if not args:\n continue\n\n for arg in args:\n command_handler(arg.split())\n\n except EOFError:\n quit(1)\n","sub_path":"shell/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"68880401","text":"import os\n\n\nclass DevConfig(object):\n \"dev config class\"\n SECRET_KEY = os.urandom(24)\n DEBUG = True\n\n SQLALCHEMY_DATABASE_URI = \\\n \"postgresql+psycopg2://postgres:111111@localhost:5432/note\"\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n\n # 文件上传大小限制,若大于16M,抛出RequestEntityTooLarge异常\n MAX_CONTENT_LENGTH = 16 * 1024 * 1024\n","sub_path":"note/config/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"133276293","text":"import threading\nfrom drivers import loader\nfrom config import App, db\nimport os\nfrom flask import Response, redirect\nfrom models import LinkObject, StorageObject\nimport importlib\nfrom sqlalchemy import or_\nimport queue\nimport helpers\nfrom random import shuffle\n\nq = queue.SimpleQueue()\n\ndef background_update_task():\n for lo in LinkObject.query.filter_by(driver='ytdl', check_updates=True).all():\n helpers.get_metadata(lo.link, lo.driver_options, lo.id, lo.linktype)\n loadable_objects = StorageObject.query.filter(or_(StorageObject.filename==None, StorageObject.filename=='')).all()\n shuffle(loadable_objects)\n for so in loadable_objects:\n q.put(so)\n while not q.empty():\n so = q.get(False)\n print(f\"Loading {so.url}\")\n dri = importlib.import_module(f'drivers.{so.get_owner().driver}')\n l = loader.DownloaderThread(dri.Driver, so)\n l.run()\n os.remove('update.lck')\n\n@App.route(\"/update\")\ndef update():\n if os.path.exists('update.lck'):\n return redirect('/')\n else:\n open('update.lck', 'w')\n t = threading.Thread(target=background_update_task, daemon=True)\n t.start()\n return redirect('/')\n\n@App.route(\"/update/status\")\ndef update_status():\n if not os.path.exists('update.lck'):\n return False\n else:\n t = len(StorageObject.query.all())\n return str((t-q.qsize())/t * 100)","sub_path":"updater.py","file_name":"updater.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"108420578","text":"\n\"\"\"Script for dwr prediction benchmarking.\n\"\"\"\n# Sample usage:\n# (shape_ft) : python -m factored3d.benchmark.suncg.dwr --num_train_epoch=1 --name=dwr_shape_ft --classify_rot --pred_voxels=True --use_context --save_visuals --visuals_freq=50 --eval_set=val --suncg_dl_debug_mode --max_eval_iter=20\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom absl import app\nfrom absl import flags\nimport os\nimport os.path as osp\nimport numpy as np\nimport torch\nimport torchvision\nfrom torch.autograd import Variable\nimport time\nimport scipy.misc\nimport pdb\nimport copy\nimport json\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport time\nimport random\nfrom ...data import suncg as suncg_data\nfrom . import evaluate_detection\nfrom ...utils import bbox_utils\nfrom ...utils import suncg_parse\nfrom ...nnutils import test_utils\nfrom ...nnutils import net_blocks\nfrom ...nnutils import loss_utils\nfrom ...nnutils import gcn_net\nfrom ...nnutils import disp_net\nfrom ...utils import metrics\nfrom ...utils import visutil\nfrom ...renderer import utils as render_utils\nfrom ...utils import quatUtils\nimport cv2\nfrom ...utils import transformations\nfrom collections import Counter\nfrom six.moves import cPickle as pickle\nimport collections\n\n\n\ncurr_path = osp.dirname(osp.abspath(__file__))\ncache_path = osp.join(curr_path, '..', '..', 'cachedir')\nflags.DEFINE_string('rendering_dir', osp.join(cache_path, 'rendering'),\n 'Directory where intermittent renderings are saved')\n\nflags.DEFINE_integer('voxel_size', 32, 'Spatial dimension of shape voxels')\nflags.DEFINE_integer('n_voxel_layers', 5, 'Number of layers ')\nflags.DEFINE_integer('voxel_nc_max', 128, 'Max 3D channels')\nflags.DEFINE_integer('voxel_nc_l1', 8, 'Initial shape encder/decoder layer dimension')\nflags.DEFINE_float('voxel_eval_thresh', 0.25, 'Voxel evaluation threshold')\nflags.DEFINE_string('id', 'default', 'Plot string')\n\nflags.DEFINE_string('shape_pretrain_name', 'object_autoenc_32', 'Experiment name for pretrained shape encoder-decoder')\nflags.DEFINE_integer('shape_pretrain_epoch', 800, 'Experiment name for shape decoder')\n\nflags.DEFINE_integer('max_rois', 100, 'If we have more objects than this per image, we will subsample.')\nflags.DEFINE_integer('max_total_rois', 100, 'If we have more objects than this per batch, we will reject the batch.')\nflags.DEFINE_integer('num_visuals', 200, 'Number of renderings')\nflags.DEFINE_boolean('preload_stats', False, 'Reload the stats for the experiment')\nflags.DEFINE_string('layout_name', 'layout_pred', 'Experiment name for layout predictor')\nflags.DEFINE_integer('layout_train_epoch', 8, 'Experiment name for layout predictor')\nflags.DEFINE_boolean('use_gt_voxels', True, 'Use gt_voxels_for_prediction')\nflags.DEFINE_string('ovis_ids_filename', None, 'Ids to visualize output file')\nflags.DEFINE_string('ivis_ids_filename', None, 'Ids to visualize output file')\nflags.DEFINE_string('results_name', None, 'results_name')\nflags.DEFINE_boolean('gt_updates', False, 'Use gt_relative updates')\nflags.DEFINE_boolean('do_updates', True, 'Do opt updates')\nflags.DEFINE_string('index_file', None, 'file containing house names and view ids')\nflags.DEFINE_string('log_csv', None, 'file containing relative acc data')\nflags.DEFINE_boolean('draw_vis', False, 'Do not evaluate only draw visualization')\nflags.DEFINE_boolean('load_predictions_from_disk', False, 'Load pkl files')\nflags.DEFINE_boolean('save_predictions_to_disk', True, 'Save pkl files')\nflags.DEFINE_float('lambda_weight', 1.0, 'lambda for rotation')\nflags.DEFINE_float('split_size', 1.0, 'Split size of the train set')\nflags.DEFINE_boolean('only_pairs', True, 'Train with only more than 2 examples per ')\nflags.DEFINE_boolean('dwr_model', False, 'Load a dwr model ')\nflags.DEFINE_boolean('shape_model', True, 'Shape model exist')\n\nFLAGS = flags.FLAGS\n\nEP_box_iou_thresh = [0.5, 0.5, 0.5, 0.5, 0., 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ]\nEP_rot_delta_thresh = [30., 30., 400., 30., 30., 30., 400., 30., 400., 400., 400., 30, ]\nEP_trans_delta_thresh = [1., 1., 1., 1000., 1, 1., 1000., 1000., 1.0, 1000., 1000., 1000., ]\nEP_shape_iou_thresh = [0.25, 0, 0.25, 0.25, 0.25, 0.25, 0, 0, 0, 0.25, 0, 0.25, ]\nEP_scale_delta_thresh = [0.5, 0.5, 0.5, 0.5, 0.5, 100., 100., 100, 100, 100, 0.5, 100, ]\nEP_ap_str = ['all', '-shape', '-rot', '-trans', '-box2d', '-scale', 'box2d',\n 'box2d+rot', 'box2d+trans', 'box2d+shape', 'box2d+scale', 'box2d+rot+shape', ]\n\n\ndef my_print(tensor):\n try:\n print(np.round(tensor.numpy(),2))\n except:\n print(np.round(tensor, 2))\n return\n\nclass DWRTester(test_utils.Tester):\n\n def define_model(self):\n '''\n Define the pytorch net 'model' whose weights will be updated during training.\n '''\n self.eval_shape_iou = False\n opts = self.opts\n self.object_class2index = {'bed' : 1, 'sofa' :2, 'table' :3, \n 'chair':4 , 'desk':5, 'television':6,\n }\n\n self.index2object_class = {1: 'bed', 2 :'sofa', 3 : 'table', \n 4 :'chair', 5 : 'desk', 6 : 'television',\n }\n\n self.voxel_encoder, nc_enc_voxel = net_blocks.encoder3d(\n opts.n_voxel_layers, nc_max=opts.voxel_nc_max, nc_l1=opts.voxel_nc_l1, nz_shape=opts.nz_shape)\n\n self.voxel_decoder = net_blocks.decoder3d(\n opts.n_voxel_layers, opts.nz_shape, nc_enc_voxel, nc_min=opts.voxel_nc_l1)\n\n self.model = gcn_net.GCNNet(\n (opts.img_height, opts.img_width), opts=self.opts,\n roi_size=opts.roi_size,\n use_context=opts.use_context, nz_feat=opts.nz_feat,\n pred_voxels=False, nz_shape=opts.nz_shape, pred_labels=True,\n classify_rot=opts.classify_rot, nz_rot=opts.nz_rot,)\n\n\n if (opts.pred_voxels or opts.dwr_model) and opts.shape_model:\n self.model.code_predictor.shape_predictor.add_voxel_decoder(\n copy.deepcopy(self.voxel_decoder))\n\n if opts.dwr_model:\n self.opts.num_train_epoch=1\n self.model.add_label_predictor()\n self.eval_shape_iou = True\n opts.use_gt_voxels = False\n\n self.load_network(self.model, 'pred', self.opts.num_train_epoch)\n \n if not opts.dwr_model:\n self.model.add_label_predictor()\n \n self.model.eval()\n self.model = self.model.cuda()\n # self.model = self.model.cuda(device=self.opts.gpu_id)\n\n if opts.pred_voxels and (not opts.dwr_model):\n self.voxel_decoder = copy.deepcopy(self.model.code_predictor.shape_predictor.decoder)\n\n self.layout_model = disp_net.dispnet()\n network_dir = osp.join(opts.cache_dir, 'snapshots', opts.layout_name)\n self.load_network(\n self.layout_model, 'pred', opts.layout_train_epoch, network_dir=network_dir)\n # self.layout_model.eval()\n # self.layout_model = self.layout_model.cuda(device=self.opts.gpu_id)\n\n return\n\n def init_dataset(self):\n opts = self.opts\n self.resnet_transform = torchvision.transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n split_dir = osp.join(opts.suncg_dir, 'splits')\n self.split = suncg_parse.get_split(split_dir, house_names=os.listdir(osp.join(opts.suncg_dir, 'camera')))\n # houses_splits = self.split[opts.eval_set]\n if opts.eval_set == 'train':\n rng = np.random.RandomState(10)\n rng.shuffle(self.split[opts.eval_set])\n len_splitset = int(len(self.split[opts.eval_set])*opts.split_size)\n self.split[opts.eval_set] = self.split[opts.eval_set][0:len_splitset]\n # print(self.split[opts.eval_set])\n\n self.dataloader = suncg_data.suncg_data_loader_benchmark(self.split[opts.eval_set], opts)\n\n if opts.voxel_size < 64:\n self.downsample_voxels = True\n self.downsampler = render_utils.Downsample(\n 64 // opts.voxel_size, use_max=True, batch_mode=True\n ).cuda()\n else:\n self.downsampler = None\n\n if opts.classify_rot:\n self.quat_medoids = torch.from_numpy(\n scipy.io.loadmat(osp.join(opts.cache_dir, 'quat_medoids.mat'))['medoids']).type(torch.FloatTensor)\n\n if not opts.pred_voxels:\n network_dir = osp.join(opts.cache_dir, 'snapshots', opts.shape_pretrain_name)\n self.load_network(\n self.voxel_decoder,\n 'decoder', opts.shape_pretrain_epoch, network_dir=network_dir)\n self.voxel_decoder.eval()\n self.voxel_decoder = self.voxel_decoder.cuda()\n\n self.spatial_image = Variable(suncg_data.define_spatial_image(opts.img_height_fine, opts.img_width_fine, 1.0/16).unsqueeze(0).cuda()) ## (1, 2, 30, 40)\n \n if opts.classify_rot:\n self.quat_medoids = torch.from_numpy(\n scipy.io.loadmat(osp.join(opts.cache_dir, 'quat_medoids.mat'))['medoids']).type(torch.FloatTensor)\n if opts.nz_rot == 48:\n self.quat_medoids = torch.from_numpy(\n scipy.io.loadmat(osp.join(opts.cache_dir, 'quat_medoids_48.mat'))['medoids']).type(torch.FloatTensor)\n\n \n # self.quat_medoids_relative = torch.from_numpy(\n # scipy.io.loadmat(osp.join(opts.cache_dir, 'quat_medoids_relative.mat'))['medoids']).type(torch.FloatTensor)\n self.quat_medoids_var = None\n\n \n if opts.classify_dir:\n self.direction_medoids = torch.from_numpy(\n scipy.io.loadmat(osp.join(opts.cache_dir, 'direction_medoids_relative_{}_new.mat'.format(opts.nz_rel_dir)))['medoids']).type(torch.FloatTensor)\n self.direction_medoids = torch.nn.functional.normalize(self.direction_medoids)\n\n self.data_vis = []\n self.stored_quat_relative_gt_classes = []\n self.stored_quat_relative_pred_classes = []\n self.rotation_bins = []\n self.translation = []\n self.pred_translation = []\n self.pred_rotation = []\n self.pred_relative_directions = []\n self.relative_directions =[]\n return\n\n def decode_shape(self, pred_shape):\n opts = self.opts\n if opts.use_gt_voxels:\n # assert pred_shape.size() == self.codes_gt[0].size(), 'predict size from gt incorrect'\n return self.codes_gt['shape'].clone()\n\n pred_shape = torch.nn.functional.sigmoid(self.voxel_decoder.forward(pred_shape))\n return pred_shape\n\n def decode_rotation(self, pred_rot):\n opts = self.opts\n if opts.classify_rot:\n _, bin_inds = torch.max(pred_rot.data.cpu(), 1)\n pred_rot = Variable(suncg_parse.bininds_to_quats(\n bin_inds, self.quat_medoids), requires_grad=False)\n return pred_rot\n\n def decode_rotation_topk(self, pred_rot):\n opts = self.opts\n if opts.classify_rot:\n _, bin_inds = torch.topk(pred_rot.data.cpu(), k=2, dim=1)\n bin_inds = bin_inds.view(-1, 1)\n pred_rot = Variable(suncg_parse.bininds_to_quats(\n bin_inds, self.quat_medoids), requires_grad=False)\n pred_rot = pred_rot.view(-1, 2, 4)\n return pred_rot\n\n def get_class_indices(self, pred_rot):\n opts = self.opts\n _, bin_inds = torch.max(pred_rot.data.cpu(), 1)\n return bin_inds\n\n def decode_rotation_relative(self, pred_rot):\n opts = self.opts\n if opts.classify_rot:\n _, bin_inds = torch.max(pred_rot.data.cpu(), 1)\n pred_rot = Variable(suncg_parse.bininds_to_quats(\n bin_inds, self.quat_medoids_relative), requires_grad=False)\n return pred_rot\n\n def decode_class(self, pred_class):\n opts = self.opts\n # pdb.set_trace()\n _, bin_inds = torch.max(pred_class.data.cpu(), 1)\n return bin_inds\n\n def count_number_pairs(self, rois):\n counts = Counter(rois[:,0].numpy().tolist())\n pairs = sum([v*v for (k,v) in counts.items() if v > 1])\n return pairs\n\n def set_input(self, batch):\n opts = self.opts\n if batch is None or not batch:\n self.invalid_batch = True\n self.invalid_rois = None\n return\n\n if batch['empty']:\n self.invalid_rois = None\n self.invalid_batch = True\n return\n\n bboxes_gt = suncg_parse.bboxes_to_rois(batch['bboxes'])\n bboxes_proposals = suncg_parse.bboxes_to_rois(batch['bboxes_test_proposals'])\n bboxes_proposals = bboxes_gt\n rois = bboxes_proposals\n if rois.numel() <= 0 or bboxes_gt.numel() <= 0: # some proposals and gt objects should be there\n self.invalid_batch = True\n self.invalid_rois = None\n return\n else:\n if bboxes_gt.numel() == 5 and self.opts.only_pairs: \n self.invalid_rois = None\n self.invalid_batch = True\n return\n pairs = self.count_number_pairs(rois)\n self.invalid_batch = False\n\n self.house_names = batch['house_name']\n self.view_ids = batch['view_id']\n # Inputs for prediction\n if self.opts.load_predictions_from_disk:\n return\n\n\n\n input_imgs_fine = batch['img_fine'].type(torch.FloatTensor)\n input_imgs = batch['img'].type(torch.FloatTensor)\n\n self.input_imgs_layout = Variable(\n input_imgs.cuda(), requires_grad=False)\n\n for b in range(input_imgs_fine.size(0)):\n input_imgs_fine[b] = self.resnet_transform(input_imgs_fine[b])\n input_imgs[b] = self.resnet_transform(input_imgs[b])\n\n self.input_imgs = Variable(\n input_imgs.cuda(), requires_grad=False)\n\n self.input_imgs_fine = Variable(\n input_imgs_fine.cuda(), requires_grad=False)\n\n self.rois = Variable(\n rois.type(torch.FloatTensor).cuda(), requires_grad=False)\n\n\n code_tensors = suncg_parse.collate_codes(batch['codes'])\n code_tensors_quats = code_tensors['quat']\n code_tensors['shape'] = code_tensors['shape'].unsqueeze(1) # unsqueeze voxels\n\n\n self.layout_gt=Variable(\n batch['layout'].cuda(), requires_grad=False)\n\n self.codes_gt_quats = [\n Variable(t.cuda(), requires_grad=False) for t in code_tensors_quats]\n codes_gt_keys = ['shape', 'scale', 'trans']\n self.codes_gt ={key : Variable(code_tensors[key].cuda(), requires_grad=False) \n for key in codes_gt_keys}\n self.codes_gt['quat'] = self.codes_gt_quats\n\n self.rois_gt=Variable(\n bboxes_gt.type(torch.FloatTensor).cuda(), requires_grad=False)\n if self.downsample_voxels:\n self.codes_gt['shape']=self.downsampler.forward(self.codes_gt['shape'])\n return\n\n def convert_multiple_bins_to_probabilites(self, bins_ids, num_medoids, no_noise=1.0):\n bins = [torch.LongTensor([random.choice(c.data)]) for c in bins_ids]\n noise_values = torch.bernoulli(torch.FloatTensor(len(bins)).zero_() + no_noise)\n bins = [c if n > 0.5 else torch.LongTensor([np.random.randint(num_medoids)]) for c, n in zip(bins, noise_values)]\n bins = torch.cat(bins)\n probs = torch.FloatTensor(len(bins), num_medoids).zero_()\n probs.scatter_(1, bins.unsqueeze(1), 1-0.001*num_medoids)\n probs = probs + 0.001\n return probs\n\n '''\n args\n relative_directions : list N^2, torch.Tensor K x 3\n vox2cams : list N , K x 4,4\n img_size : (H, W)\n returns:\n relative_directions in image plane N^2 K x 2 x 2\n '''\n def convert_relative_vectors_to_image_plane(self, relative_directions, vox2cams, img_size):\n def convert_vector_to_image_plane(vector, vox2cam, cam_intrinsic, img_size):\n vector_cam_frame = suncg_parse.transform_coordinates(vox2cam, vector.reshape(1, -1))\n img_frame = suncg_parse.transform_to_image_coordinates(vector_cam_frame, cam_intrinsic)\n img_frame = np.clip(img_frame, a_min=np.array([[0,0]]), a_max=np.array([[img_size[1], img_size[0]]]))\n return img_frame\n\n cam_intrinsic = suncg_parse.cam_intrinsic()\n img_vectors = []\n n_objects = len(vox2cams)\n for ix, rel_dir in enumerate(relative_directions):\n rel_dir = rel_dir[0]\n vox2cam = vox2cams[ix//n_objects][0]\n src_vector = convert_vector_to_image_plane(np.array([0,0,0]), vox2cam.numpy(), cam_intrinsic, img_size)\n trj_vector = convert_vector_to_image_plane(rel_dir.numpy(), vox2cam.numpy(), cam_intrinsic, img_size)\n img_vectors.append(np.concatenate([src_vector, trj_vector], axis=0))\n\n index = [ix*n_objects + ix for ix in range(n_objects)]\n img_vectors = [(img_vectors[ix], ix//n_objects, ix % n_objects) for ix in range(n_objects*n_objects) if ix not in index]\n return img_vectors\n\n\n def save_layout_mesh(self, mesh_dir, layout, prefix='layout'):\n opts=self.opts\n layout_vis=layout.data[0].cpu().numpy().transpose((1, 2, 0))\n mesh_file=osp.join(mesh_dir, prefix + '.obj')\n vs, fs=render_utils.dispmap_to_mesh(\n layout_vis,\n suncg_parse.cam_intrinsic(),\n scale_x=self.opts.layout_width / 640,\n scale_y=self.opts.layout_height / 480\n )\n fout=open(mesh_file, 'w')\n mesh_file=osp.join(mesh_dir, prefix + '.obj')\n fout=open(mesh_file, 'w')\n render_utils.append_obj(fout, vs, fs)\n fout.close()\n\n def save_codes_mesh(self, mesh_dir, code_vars, prefix='codes'):\n opts=self.opts\n\n n_rois=code_vars[0].size()[0]\n code_list=suncg_parse.uncollate_codes(code_vars, self.input_imgs.data.size(0), torch.Tensor(n_rois).fill_(0))\n\n if not os.path.exists(mesh_dir):\n os.makedirs(mesh_dir)\n mesh_file=osp.join(mesh_dir, prefix + '.obj')\n render_utils.save_parse(mesh_file, code_list[0], save_objectwise=False, thresh=0.1)\n\n def render_visuals(self, mesh_dir, obj_name=None):\n png_dir=osp.join(mesh_dir, 'rendering')\n if obj_name is not None:\n render_utils.render_mesh(osp.join(mesh_dir, obj_name + '.obj'), png_dir)\n im_view1=scipy.misc.imread(osp.join(png_dir, '{}_render_000.png'.format(obj_name)))\n # im_view2=scipy.misc.imread(osp.join(png_dir, '{}_render_003.png'.format(obj_name)))\n else:\n render_utils.render_directory(mesh_dir, png_dir)\n im_view1=scipy.misc.imread(osp.join(png_dir, 'render_000.png'))\n # im_view2=scipy.misc.imread(osp.join(png_dir, 'render_003.png'))\n\n # return im_view1, im_view2\n return im_view1\n\n\n\n def get_current_visuals(self):\n visuals={}\n opts=self.opts\n visuals['img']=visutil.tensor2im(visutil.undo_resnet_preprocess(\n self.input_imgs_fine.data))\n rois=self.rois.data\n visuals['img_roi']=render_utils.vis_detections(visuals['img'], rois[:, 1:])\n\n img_rel_vectors_pred = self.convert_relative_vectors_to_image_plane([[x] for x in self.relative_direction_prediction_3d], \n self.vox2cams[0], (self.opts.img_height_fine, self.opts.img_width_fine))\n img_rel_vectors_gt = self.convert_relative_vectors_to_image_plane(self.relative_direction_rotation,\n self.vox2cams[0], (self.opts.img_height_fine, self.opts.img_width_fine))\n visuals['img_rel_dir_pred']=render_utils.vis_relative_dirs(visuals['img_roi'], img_rel_vectors_pred)\n visuals['img_rel_dir_gt']=render_utils.vis_relative_dirs(visuals['img_roi'], img_rel_vectors_gt)\n\n mesh_dir=osp.join(opts.rendering_dir)\n # vis_codes=[self.codes_pred_vis, self.codes_gt]\n vis_codes=[self.codes_pred_eval, self.codes_gt]\n # vis_layouts = [self.layout_pred, self.layout_gt]\n vis_names=['b_pred', 'c_gt']\n for vx, v_name in enumerate(vis_names):\n os.system('rm {}/*.obj'.format(mesh_dir))\n self.save_codes_mesh(mesh_dir, vis_codes[vx])\n visuals['{}_objects_cam_view'.format(v_name)] =self.render_visuals(mesh_dir, obj_name='codes')\n\n return visuals\n\n\n def filter_pos(self, codes, pos_inds):\n pos_inds=torch.from_numpy(np.array(pos_inds)).squeeze()\n t = torch.LongTensor\n if type(codes) == dict:\n key = 'shape'\n if isinstance(codes[key], torch.autograd.Variable):\n if isinstance(codes[key].data, torch.cuda.FloatTensor):\n t = torch.cuda.LongTensor\n elif isinstance(codes[key], torch.cuda.FloatTensor):\n t = torch.cuda.LongTensor\n\n\n pos_inds=torch.autograd.Variable(\n pos_inds.type(t), requires_grad=False)\n filtered_codes= {k : torch.index_select(code, 0, pos_inds) for k, code in codes.items()}\n\n else:\n if isinstance(codes[0], torch.autograd.Variable):\n if isinstance(codes[0].data, torch.cuda.FloatTensor):\n t = torch.cuda.LongTensor\n elif isinstance(codes[0], torch.cuda.FloatTensor):\n t = torch.cuda.LongTensor\n\n pos_inds =torch.autograd.Variable(\n pos_inds.type(t), requires_grad=False)\n filtered_codes = [torch.index_select(code, 0, pos_inds) for code in codes]\n return filtered_codes\n\n\n\n def save_predictions_to_pkl(self, dict_of_outputs):\n pkl_file_name = osp.join(self.opts.results_eval_dir, \"{}_{}.pkl\".format(self.house_names[0], self.view_ids[0]))\n \n def recursive_convert_to_numpy(elem):\n if isinstance(elem, collections.Mapping):\n return {key: recursive_convert_to_numpy(elem[key]) for key in elem}\n elif isinstance(elem, str):\n return elem\n elif isinstance(elem, collections.Sequence):\n return [recursive_convert_to_numpy(samples) for samples in elem]\n elif isinstance(elem, torch.FloatTensor):\n return elem.data.numpy()\n elif isinstance(elem, torch.cuda.FloatTensor):\n return elem.data.cpu().numpy()\n elif isinstance(elem, torch.LongTensor):\n return elem.data.numpy()\n elif isinstance(elem, torch.cuda.LongTensor):\n return elem.data.cpu().numpy()\n elif isinstance(elem, torch.autograd.Variable):\n return recursive_convert_to_numpy(elem.data)\n else:\n return elem\n\n new_dict = recursive_convert_to_numpy(dict_of_outputs)\n with open(pkl_file_name, 'wb') as f:\n pickle.dump(new_dict, f)\n\n def convert_pkl_to_predictions(self, ):\n pkl_file_name = osp.join(self.opts.results_eval_dir, \"{}_{}.pkl\".format(self.house_names[0], self.view_ids[0]))\n def recursive_convert_to_torch(elem):\n if isinstance(elem, collections.Mapping):\n return {key: recursive_convert_to_torch(elem[key]) for key in elem}\n elif isinstance(elem, str):\n return elem\n elif isinstance(elem, collections.Sequence):\n return [recursive_convert_to_torch(samples) for samples in elem]\n elif isinstance(elem, np.ndarray):\n if elem.dtype == np.int32:\n torch.from_numpy(elem).long()\n else:\n return torch.from_numpy(elem).float()\n else:\n return elem\n with open(pkl_file_name, 'rb') as f:\n predictions = pickle.load(f)\n predictions = recursive_convert_to_torch(predictions)\n predictions['gt_codes'] = [Variable(k) for k in predictions['gt_codes']]\n predictions['pred_codes'] = [Variable(k) for k in predictions['pred_codes']]\n predictions['object_class_gt'] = Variable(predictions['object_class_gt']).long()\n predictions['rois'] = Variable(predictions['rois'])\n predictions['amodal_bboxes'] = predictions['amodal_bboxes']\n predictions['codes_gt_quats'] = [Variable(t) for t in predictions['codes_gt_quats']]\n\n return predictions\n\n\n def predict(self):\n # pdb.set_trace()\n # codes_pred_all, trj_pred_all, labels_pred = self.model.forward((self.input_imgs_fine, self.input_imgs, self.rois))\n if not self.opts.load_predictions_from_disk:\n feed_dict = {}\n feed_dict['imgs_inp_fine'] = self.input_imgs_fine\n feed_dict['imgs_inp_coarse'] = self.input_imgs\n feed_dict['rois_inp'] = self.rois\n feed_dict['spatial_image'] = self.spatial_image\n model_pred =self.model.forward(feed_dict)\n\n codes_pred_all = model_pred['codes_pred']\n codes_pred_all['quat'] = torch.nn.functional.log_softmax(codes_pred_all['quat'])\n\n stuff_to_save = {'gt_codes' : self.codes_gt,\n 'pred_codes' : codes_pred_all, \n 'rois' : self.rois, \n 'index2object' : self.index2object_class,\n 'codes_gt_quats' : self.codes_gt_quats,}\n\n # self.class_pred=model_pred['class_pred']\n labels_pred=model_pred['labels_pred']\n \n if self.opts.save_predictions_to_disk:\n self.save_predictions_to_pkl(stuff_to_save)\n assert osp.exists(osp.join(self.opts.results_eval_dir, \"{}_{}.pkl\".format(self.house_names[0], self.view_ids[0]))), 'pkl file does not exist'\n\n else:\n # if self.house_names[0] == '4c5edfb056c1f38d58482a05562d8c1d':\n # pdb.set_trace()\n predictions = self.convert_pkl_to_predictions()\n self.codes_gt = tuple(predictions['gt_codes'])\n codes_pred_all = tuple(predictions['pred_codes'])\n\n self.rois = predictions['rois']\n self.index2object_class = predictions['index2object']\n self.relative_quat_tensors_angles_gt = predictions['relative_quat_tensors_angles_gt']\n self.codes_gt_quats = predictions['codes_gt_quats']\n self.codes_quat_var = predictions['codes_quat_var']\n\n n = codes_pred_all['shape'].size(0)\n labels_pred = Variable(torch.zeros(n, 1).cuda())\n scores_pred = labels_pred.cpu().data.numpy() * 0 + 1\n bboxes_pred = self.rois.data.cpu().numpy()[:, 1:]\n min_score_eval=np.minimum(0.05, np.max(scores_pred))\n \n pos_inds_eval=[i for i in range(n)]\n\n self.codes_pred_eval=self.filter_pos(codes_pred_all, pos_inds_eval)\n\n\n\n self.rois_pos_eval=self.filter_pos([self.rois], pos_inds_eval)[0] # b x 5, 1:5 is box (x1 y1 x2 y2)\n self.codes_pred_eval['shape']=self.decode_shape(self.codes_pred_eval['shape']) # b x 1 x 32 x 32 x 32\n\n \n self.codes_pred_eval['quat']=self.decode_rotation(self.codes_pred_eval['quat']) # b x 4\n self.codes_pred_quat_before = self.codes_pred_eval['quat']\n self.codes_pred_eval['scale'] # Probably scale b x 3\n self.codes_pred_eval['trans'] # Probably trans b x 3\n\n self.scores_pred_eval=scores_pred[pos_inds_eval, :] * 1.\n\n min_score_vis=np.minimum(0.7, np.max(scores_pred))\n\n pos_inds_vis=[i for i in range(n)]\n self.codes_pred_vis=self.filter_pos(codes_pred_all, pos_inds_vis)\n self.rois_pos_vis=self.filter_pos([self.rois], pos_inds_vis)[0]\n self.codes_pred_vis['shape']=self.decode_shape(self.codes_pred_vis['shape'])\n self.codes_pred_vis['quat']=self.codes_pred_eval['quat']\n\n def evaluate(self):\n # rois as numpy array\n # Get Predictions.\n # pdb.set_trace()\n opts = self.opts\n shapes = self.codes_pred_eval['shape'] \n scales = self.codes_pred_eval['scale']\n rots = self.codes_pred_eval['quat']\n trans = self.codes_pred_eval['trans']\n rots_before = self.codes_pred_quat_before\n trans=trans\n scores=self.scores_pred_eval\n boxes=self.rois_pos_eval.cpu().data.numpy()[:, 1:]\n # Get Ground Truth.\n # pdb.set_trace()\n gt_shapes = self.codes_gt['shape']\n gt_scales = self.codes_gt['scale']\n gt_rots = self.codes_gt['quat']\n gt_trans = self.codes_gt['trans']\n\n\n gt_boxes=self.rois.cpu().data.numpy()[:, 1:]\n iou_box=bbox_utils.bbox_overlaps(boxes.astype(np.float), gt_boxes.astype(np.float))\n trans_, gt_trans_=trans.cpu().data.numpy(), gt_trans.cpu().data.numpy()\n err_trans=np.linalg.norm(np.expand_dims(trans_, 1) - np.expand_dims(gt_trans_, 0), axis=2)\n err_pwd=np.zeros([len(err_trans)])\n\n\n err_rel_quat = (0*err_pwd).tolist()\n acc_rel = (0*err_pwd).tolist()\n\n n_objects=len(gt_rots)\n\n scales_, gt_scales_=scales.cpu().data.numpy(), gt_scales.cpu().data.numpy()\n err_scales=np.mean(np.abs(np.expand_dims(np.log(scales_), 1) - np.expand_dims(np.log(gt_scales_), 0)), axis=2)\n err_scales /= np.log(2.0)\n\n gt_quats = [t.data.cpu() for t in self.codes_gt_quats]\n\n\n ndt, ngt=err_scales.shape\n err_shapes=err_scales * 0.\n err_rots=err_scales * 0.\n err_rots_before = err_scales * 0\n \n for i in range(ndt):\n for j in range(ngt):\n err_shapes[i, j]=metrics.volume_iou(shapes[i, 0].data, gt_shapes[\n j, 0].data, thresh=self.opts.voxel_eval_thresh)\n if len(rots[i]) == 4:\n # err_rots[i, j]=metrics.quat_dist(rots[i].data.cpu(), gt_rots[j].data.cpu())\n q_errs = []\n for quat in gt_quats[j]:\n q_errs.append(metrics.quat_dist(rots[i].data.cpu(), quat))\n err_rots[i, j] = min(q_errs)\n else:\n m1 = metrics.quat_dist(rots[i][0].data.cpu(), gt_rots[j].data.cpu())\n m2 = metrics.quat_dist(rots[i][1].data.cpu(), gt_rots[j].data.cpu())\n err_rots[i, j] = min(m1, m2)\n\n for i in range(ndt):\n for j in range(ngt):\n err_shapes[i, j]=metrics.volume_iou(shapes[i, 0].data, gt_shapes[\n j, 0].data, thresh=self.opts.voxel_eval_thresh)\n if len(rots_before[i]) == 4:\n # err_rots[i, j]=metrics.quat_dist(rots[i].data.cpu(), gt_rots[j].data.cpu())\n q_errs = []\n for quat in gt_quats[j]:\n q_errs.append(metrics.quat_dist(rots_before[i].data.cpu(), quat))\n err_rots_before[i, j] = min(q_errs)\n else:\n m1 = metrics.quat_dist(rots_before[i][0].data.cpu(), gt_rots[j].data.cpu())\n m2 = metrics.quat_dist(rots_before[i][1].data.cpu(), gt_rots[j].data.cpu())\n err_rots_before[i, j] = min(m1, m2)\n\n err_rots=np.diag(err_rots).tolist()\n acc_rots = [1 if err < 30 else 0 for err in err_rots]\n err_rots_before = np.diag(err_rots_before).tolist()\n acc_rots_before = [1 if err < 30 else 0 for err in err_rots_before]\n err_trans=np.diag(err_trans).tolist()\n err_scales=np.diag(err_scales).tolist()\n err_pwd=err_pwd.tolist()\n err_shapes = np.diag(err_shapes).tolist()\n\n house_name_view_id = \"{}_{}\".format(self.house_names[0], self.view_ids[0])\n\n stats={'trans': err_trans, 'scales': err_scales,'shape': err_shapes, 'rot': err_rots, 'rot_b' : err_rots_before, 'acc_rots' : acc_rots, 'acc_rots_bef' : acc_rots_before,\n 'pwd': err_pwd, 'acc_rot' : acc_rots, 'acc_rot_before' : acc_rots_before,\n }\n \n\n if len(err_trans) == 1:\n stats = {}\n \n return stats\n\n def save_current_visuals(self, house_name, view_id):\n imgs_dir=osp.join(self.opts.results_quality_dir, '{}_{}'.format(house_name, view_id))\n img_file = osp.join(imgs_dir, 'c_gt_objects_cam_view.png')\n if osp.exists(imgs_dir) and osp.exists(img_file):\n return\n else:\n visuals=self.get_current_visuals()\n if not os.path.exists(imgs_dir) :\n os.makedirs(imgs_dir)\n for k in visuals:\n img_path=osp.join(imgs_dir, k + '.png')\n scipy.misc.imsave(img_path, visuals[k])\n\n def save_current_stats(self, bench, house_name, view_id):\n imgs_dir=osp.join(self.opts.results_quality_dir, '{}_{}'.format(house_name, view_id))\n json_file=os.path.join(imgs_dir, 'bench_iter_{}.json'.format(0))\n # print(json_file)\n # if house_name == 'd49bb0b4b52cceffbe6086dfa1976e51':\n # pdb.set_trace()\n with open(json_file, 'w') as f:\n json.dump({'bench': bench}, f)\n\n def test_draw(self):\n opts=self.opts\n index_filename=opts.index_file\n house_name_view_ids=[]\n with open(index_filename) as f:\n for line in f:\n line=line.strip()\n house_name_view_ids.append('_'.join(line.split('_')))\n\n for i, batch in enumerate(self.dataloader):\n self.set_input(batch)\n self.vis_iter=i\n # print(i)\n if self.invalid_batch:\n continue\n house_name=batch['house_name'][0]\n view_id=batch['view_id'][0]\n example_id='{}_{}'.format(house_name, view_id)\n if example_id in house_name_view_ids:\n self.predict()\n bench_image_stats,_,_,_=self.evaluate()\n self.save_current_visuals(house_name, view_id)\n self.save_current_stats(bench_image_stats, house_name, view_id)\n print(\"Generating {}\".format(i))\n\n\n def test(self):\n opts=self.opts\n if not opts.preload_stats:\n invalid_rois=0\n bench_stats=[]\n\n n_iter=len(self.dataloader)\n for i, batch in enumerate(self.dataloader):\n if i % 100 == 0:\n print('{}/{} evaluation iterations.'.format(i, n_iter))\n if opts.max_eval_iter > 0 and (i >= opts.max_eval_iter):\n break\n self.set_input(batch)\n if not self.invalid_batch:\n self.predict()\n house_name = batch['house_name'][0]\n view_id = batch['view_id'][0]\n bench_image_stats = self.evaluate()\n json_file=osp.join(opts.results_eval_dir, 'eval_result_{}_{}.json'.format(house_name, view_id))\n\n bench_image_stats['house_name']=batch['house_name'][0]\n bench_image_stats['view_id']=batch['view_id'][0]\n \n bench_stats.append(bench_image_stats)\n\n else:\n if self.invalid_rois is not None:\n print(\"Total rois {}\".format(self.invalid_rois.numel() / 5))\n invalid_rois += 1\n\n\n print(\"% of RoI invalid {}\".format(invalid_rois * 100.0 / n_iter))\n\n\n acc_stats={'trans': [], 'scales': [], 'shape' : [], 'rot_b': [], 'rot': [], 'acc_rot' : [], 'acc_rot_before' : []}\n class_stats={'correct': [], 'total': []}\n for bench in bench_stats:\n for key in acc_stats.keys():\n if key in bench:\n acc_stats[key].extend(bench[key])\n for key in class_stats.keys():\n if key in bench:\n class_stats[key].append(bench[key])\n\n # acc_threshold = {'shape' : 0.25 , 'trans' : 1, 'rot_b' : 30, 'rot' : 30, 'scales':0.5}\n acc_threshold = {'shape' : 0.25 , 'trans' : 0.5, 'rot_b' : 30, 'rot' : 30, 'scales':0.2}\n for key, thres in acc_threshold.items():\n acc_stats[\"{}_acc\".format(key)] = [1 if v < thres else 0 for v in acc_stats[key]]\n\n json_file=os.path.join(FLAGS.results_eval_dir, 'eval_set_{}_{}_{}.json'.format(opts.id, opts.eval_set, 0))\n\n print('Writing results to file: {:s}'.format(json_file))\n with open(json_file, 'w') as f:\n json.dump(acc_stats, f)\n else:\n json_file=os.path.join(FLAGS.results_eval_dir, 'eval_set_{}_{}_{}.json'.format(opts.id, opts.eval_set, 0))\n with open(json_file) as f:\n acc_stats=json.load(f)\n\n # Print mean error and median error\n metrics ={'mean': np.mean, 'median': np.median}\n criterias={ 'trans', 'scales', 'rot','rot_b', 'shape',\n 'acc_rot', 'acc_rot_before',\n 'trans_acc', 'rot_b_acc', 'rot_acc', 'scales_acc', 'shape_acc'}\n\n for key in criterias:\n for mkey in metrics.keys():\n print('{} {} : {:0.3f}'.format(mkey, key, metrics[mkey](np.array(acc_stats[key]))))\n\n for key in acc_stats.keys():\n acc_stats[key]=np.array(acc_stats[key])\n\n \n key_clip={'shape' : 1.0, 'trans': 3.0, 'pwd': 5.0, 'scales': 1.5, 'rot_b': 180, 'rot': 180,'trans_updates': 4, 'pwr': 180 , 'rel_dir': 180}\n for key in criterias:\n err=acc_stats[key]\n if 'acc' in key:\n clip_max = 2\n continue\n else:\n clip_max=key_clip[key]\n values, base=np.histogram(np.clip(np.array(err), 0, clip_max), 40)\n cumulative=np.cumsum(values)\n cumulative=cumulative / len(err)\n plt.plot(cumulative, base[:-1], c='blue')\n plt.plot([0.0, 1.0], [np.mean(err), np.mean(err)], c='red')\n plt.title('Error {} vs data-fraction'.format(key))\n plt.savefig(os.path.join(FLAGS.results_eval_dir, 'eval_set_{}_{}_{}.png'.format(opts.id, opts.eval_set, key)))\n plt.close()\n\n with open(os.path.join(FLAGS.results_eval_dir, 'eval_set_{}_{}_{}.pkl'.format(opts.id, opts.eval_set, key)) , 'wb') as f:\n pickle.dump({'err' : acc_stats[key], 'freq_values' : cumulative, 'bin_values': base[:-1]}, f)\n\n\ndef main(_):\n FLAGS.suncg_dl_out_codes=True\n FLAGS.suncg_dl_out_fine_img=True\n FLAGS.suncg_dl_out_test_proposals=True\n FLAGS.suncg_dl_out_voxels=False\n FLAGS.suncg_dl_out_layout=True\n FLAGS.suncg_dl_out_depth=False\n # FLAGS.n_data_workers=4\n FLAGS.max_views_per_house=2\n \n\n FLAGS.batch_size=1\n assert(FLAGS.batch_size == 1)\n\n if FLAGS.results_name is None:\n FLAGS.results_name=FLAGS.name\n\n FLAGS.results_vis_dir=osp.join(FLAGS.results_vis_dir, 'box3d_base', FLAGS.eval_set, FLAGS.results_name)\n FLAGS.results_quality_dir=osp.join(FLAGS.results_quality_dir, 'box3d_base', FLAGS.eval_set, FLAGS.results_name)\n FLAGS.results_eval_dir=osp.join(FLAGS.results_eval_dir, 'box3d_base', FLAGS.eval_set, FLAGS.results_name)\n FLAGS.rendering_dir = osp.join(FLAGS.rendering_dir, FLAGS.results_name)\n if not os.path.exists(FLAGS.results_eval_dir):\n os.makedirs(FLAGS.results_eval_dir)\n if not os.path.exists(FLAGS.results_vis_dir):\n os.makedirs(FLAGS.results_vis_dir)\n\n torch.manual_seed(0)\n np.random.seed(0)\n random.seed(0)\n\n if not FLAGS.classify_rot:\n FLAGS.nz_rot=4\n\n\n if not FLAGS.classify_dir:\n FLAGS.nz_rel_dir=3\n\n tester=DWRTester(FLAGS)\n tester.init_testing()\n if not FLAGS.draw_vis:\n tester.test()\n else:\n tester.test_draw()\n\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"object_branch/benchmark/suncg/gcn.py","file_name":"gcn.py","file_ext":"py","file_size_in_byte":39593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"199721963","text":"import sys\r\nimport os\r\n\r\npwd = os.path.dirname(os.path.realpath(__file__))\r\nsys.path.append(pwd + \"../\")\r\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_app.settings\")\r\n\r\nimport django\r\n\r\ndjango.setup()\r\n\r\nfrom db_tools.data.verifycodes_data import verifycodes_data\r\nfrom users.models import VerifyCode\r\n\r\n\r\nclass AddVer:\r\n def addver(self):\r\n verifycode_list = []\r\n for verifycode in verifycodes_data:\r\n verfy = VerifyCode()\r\n verfy.code = verifycode[\"code\"]\r\n verfy.mobile = verifycode[\"mobile\"]\r\n verifycode_list.append(verfy)\r\n VerifyCode.objects.bulk_create(verifycode_list)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n add = AddVer()\r\n add.addver()\r\n","sub_path":"db_tools/import_verifycodes.py","file_name":"import_verifycodes.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"126671156","text":"import sys\nimport numpy as np\nsys.path.append(\"../THESIS\")\nfrom casadi import *\nfrom hamza_race_car.model.tracks import track_load as track_load\nfrom plots import *\n\n#from model.bycicle_model import bycicle_model \n\n#control=np.loadtxt(\"daniel_controls\")\n#measurements=np.loadtxt(\"daniel_states\")\n\n\ndef casadi_integrator_fun(measurements,control,DT):\n\tn_steps = 3\n\n\ttrack=\"LMS_Track.txt\"\n\tTf = 1.0 # prediction horizon\n\tN = 50 # number of discretization steps\n\tT =0.08 # maximum simulation time[s]\n\tDT=Tf/N\n\tNsim=int(N*T/Tf)\n\tprint(T)\n\t\n\tm = 0.043\n\tC1=0.5\n\tC2=15.5\n\tCm1=0.28\n\tCm2=0.05\n\tCr0=0.011\n\tCr2=0.006\n\t#mu_x = 0.8 # coefficient for maximum longitudinal force Fx = mu_x * F_gravity\n\t#mu_y = 0.5\n\n\n\ttrack = \"LMS_Track.txt\"\n\t[s0,xref,yref,psiref,kapparef] = track_load.track_load(track)\n\tkapparef_s=interpolant('kapparef_s','bspline',[s0],kapparef)\n\n\n\t#dynamic system\n\n\ts = MX.sym('s')\n\tn = MX.sym('n')\n\talpha = MX.sym('alpha')\n\tv = MX.sym('v')\n\tD = MX.sym('D')\n\tdelta = MX.sym('delta')\n\tx = vertcat(s,n,alpha,v,D,delta)\n\n\t# controls\n\n\tderD = MX.sym('derD')\n\tderDelta = MX.sym('derDelta')\n\tu = vertcat(derD,derDelta)\n\n\tFxd = (Cm1 - Cm2 * v) * D - Cr2 * v * v - Cr0 * tanh(5 * v)\n\tsdota = ( v* np.cos( alpha+ C1* delta)) / (1- kapparef_s (s) * n)\n\n\n\txdot = vertcat( sdota,\\\n\tv * sin( alpha + C1 * delta),\\\n\tv * C2 * delta - kapparef_s(s) * sdota,\\\n\tFxd/m* cos( C1* delta),\\\n\tderD,\\\n\tderDelta\n\t)\n\n\n\t#applying rk4 function scheme here\n\tf_rk4 = Function('f_rk4',[x,u],[xdot])\n\n\tX0 = MX.sym('X0',6,1)\n\tU0 = MX.sym('U0',2,1)\n\tDT = DT/n_steps\n \n\tk1 = f_rk4(X0, U0)\n\tk2 = f_rk4(X0 + DT/2 * k1, U0)\n\tk3 = f_rk4(X0 + DT/2 * k2, U0)\n\tk4 = f_rk4(X0 + DT * k3, U0)\n\tX_out = X0 + DT/6*(k1 +2*k2 +2*k3 +k4)\t\t\n\t\n\tintegrator_fun=Function('integrator_fun',[X0,U0],[X_out])\n\n\tsimX = np.ndarray((Nsim,6))\n\t#x0=np.array([-3.510884924689705588e-02, 1.074992450288252965e-01, 1.750991154203301037e-01, 2.042442022843528715e+00, 7.150026169364859241e-01, -6.086127799402280686e-02])\n\t#x0=np.array([4.148474454789999877e-01, 3.200575584970000165e-02, 6.271748998659999685e+00, 4.544659226380000083e-01,4.621279507789999852e-01, -1.123296743100000022e-01])\n\tx0=np.array(measurements[0,0:6])\n\tsimX[0,:] = x0\n\t#print(x0)\n\tsimU=control\n\n\tfor i in range(Nsim-1):\n\t\tfor k in range(n_steps): # for multiple steps\n\t\t\tx0=integrator_fun(x0,simU[i,0:2])\n\t\t\tx0=x0.T\n\t\t\tsimX[i+1,:]=x0\n\t\t\t#print(x0)\n\t\t\t#print(simX)\n\t\t\n\tnp.savetxt('x_simulation', simX)\n\t\n\treturn simX,measurements,s0,xref,yref,psiref\n\n\n\n","sub_path":"race_car_autonomous/hamza_race_car/casadi_integrator.py","file_name":"casadi_integrator.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"383997233","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Attack',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('damage', models.IntegerField(default=0)),\n ('unlocked', models.BooleanField(default=False)),\n ('defensive', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='Player',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('absent', models.BooleanField(default=False)),\n ],\n ),\n migrations.CreateModel(\n name='Pokemon',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('health', models.IntegerField(default=100)),\n ('unlocked', models.BooleanField(default=False)),\n ('player', models.ForeignKey(to='pokequest.Player')),\n ],\n ),\n migrations.AddField(\n model_name='attack',\n name='poke',\n field=models.ForeignKey(to='pokequest.Pokemon'),\n ),\n ]\n","sub_path":"pokequest/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"96294418","text":"######################################################################\n#\n# Copyright (C) 2013\n# Associated Universities, Inc. Washington DC, USA,\n#\n# This library is free software; you can redistribute it and/or modify it\n# under the terms of the GNU Library General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or (at your\n# option) any later version.\n#\n# This library is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n# License for more details.\n#\n# You should have received a copy of the GNU Library General Public License\n# along with this library; if not, write to the Free Software Foundation,\n# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.\n#\n# Correspondence concerning VLA Pipelines should be addressed as follows:\n# Please register and submit helpdesk tickets via: https://help.nrao.edu\n# Postal address:\n# National Radio Astronomy Observatory\n# VLA Pipeline Support Office\n# PO Box O\n# Socorro, NM, USA\n#\n######################################################################\n\nlogprint (\"Starting EVLA_pipe_testBPdcals.py\", logfileout='logs/testBPdcals.log')\ntime_list=runtiming('testBPdcals', 'start')\nQA2_testBPdcals='Pass'\n\n# INITIAL TEST CALIBRATIONS USING BANDPASS AND DELAY CALIBRATORS\n\nlogprint (\"Finding a reference antenna\", logfileout='logs/testBPdcals.log')\n\nrefantspw=''\nrefantfield=calibrator_field_select_string\n\nfindrefant=RefAntHeuristics(vis=ms_active,field=refantfield,geometry=True,flagging=True)\nRefAntOutput=findrefant.calculate()\nrefAnt=str(RefAntOutput[0])\n\nlogprint (\"The pipeline will use antenna \"+refAnt+\" as the reference\", logfileout='logs/testBPdcals.log')\nlogprint (\"Doing test calibrations\", logfileout='logs/testBPdcals.log')\n\n# Do initial phase solutions on the delay calibrator\n\nsyscommand='rm -rf testdelayinitialgain.g'\nos.system(syscommand)\n\nif (cal3C84_d == True):\n default('gaincal')\n vis=ms_active\n caltable='testdelayinitialgain.g'\n field=delay_field_select_string\n spw=tst_delay_spw\n intent=''\n selectdata=True\n uvrange=uvrange3C84\n scan=delay_scan_select_string\n solint='int'\n combine='scan'\n preavg=-1.0\n refant=refAnt\n minblperant=minBL_for_cal\n minsnr=3.0\n solnorm=False\n gaintype='G'\n smodel=[]\n calmode='p'\n append=False\n docallib=False\n gaintable=priorcals\n gainfield=['']\n interp=['']\n spwmap=[]\n parang=False\n gaincal()\nelse:\n default('gaincal')\n vis=ms_active\n caltable='testdelayinitialgain.g'\n field=delay_field_select_string\n spw=tst_delay_spw\n intent=''\n selectdata=True\n uvrange=''\n scan=delay_scan_select_string\n solint='int'\n combine='scan'\n preavg=-1.0\n refant=refAnt\n minblperant=minBL_for_cal\n minsnr=3.0\n solnorm=False\n gaintype='G'\n smodel=[]\n calmode='p'\n append=False\n docallib=False\n gaintable=priorcals\n gainfield=['']\n interp=['']\n spwmap=[]\n parang=False\n gaincal()\n\n\nlogprint (\"Initial phase calibration on delay calibrator complete\", logfileout='logs/testBPdcals.log')\n\n# Do initial test delay calibration (\"test\" because more flagging may be\n# needed for the final version)\n# For the future: investigate multiband delay\n\nsyscommand='rm -rf testdelay.k'\nos.system(syscommand)\n\nflaggedSolnResult=testdelays(ms_active,'testdelay.k',delay_field_select_string,delay_scan_select_string,refAnt,minBL_for_cal,priorcals,cal3C84_d,uvrange3C84)\nlogprint(\"Fraction of flagged solutions = \"+str(flaggedSolnResult['all']['fraction']), logfileout='logs/testBPdcals.log')\nlogprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\nif (flaggedSolnResult['all']['total'] > 0):\n fracFlaggedSolns=flaggedSolnResult['antmedian']['fraction']\nelse:\n fracFlaggedSolns=1.0\n\n# NB: in case the reference antenna has a bad baseband/IF, check\n# a couple of reference antennas if there is a high fraction of\n# flagged solutions\n\ncritfrac = 1.1\n\nif (fracFlaggedSolns > critfrac):\n logprint (\"Not enough good solutions, trying a different reference antenna\", logfileout='logs/testBPdcals.log')\n refAnt=str(RefAntOutput[1])\n logprint (\"The pipeline will use antenna \"+refAnt+\" as the reference\", logfileout='logs/testBPdcals.log')\n flaggedSolnResult=testdelays(ms_active,'testdelay.k',delay_field_select_string,delay_scan_select_string,refAnt,minBL_for_cal,priorcals,cal3C84_d,uvrange3C84)\n logprint(\"Fraction of flagged solutions = \"+str(flaggedSolnResult['all']['fraction']), logfileout='logs/testBPdcals.log')\n logprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n if (flaggedSolnResult['all']['total'] > 0):\n fracFlaggedSolns=flaggedSolnResult['antmedian']['fraction']\n else:\n fracFlaggedSolns=1.0\n\n if (fracFlaggedSolns > critfrac):\n logprint (\"Not enough good solutions, trying a different reference antenna\", logfileout='logs/testBPdcals.log')\n refAnt=str(RefAntOutput[2])\n logprint (\"The pipeline will use antenna \"+refAnt+\" as the reference\", logfileout='logs/testBPdcals.log')\n\n flaggedSolnResult=testdelays(ms_active,'testdelay.k',delay_field_select_string,delay_scan_select_string,refAnt,minBL_for_cal,priorcals,cal3C84_d,uvrange3C84)\n logprint(\"Fraction of flagged solutions = \"+str(flaggedSolnResult['all']['fraction']), logfileout='logs/testBPdcals.log')\n logprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n if (flaggedSolnResult['all']['total'] > 0):\n fracFlaggedSolns=flaggedSolnResult['antmedian']['fraction']\n else:\n fracFlaggedSolns=1.0\n\n if (fracFlaggedSolns > critfrac):\n logprint (\"Not enough good solutions, trying a different reference antenna\", logfileout='logs/testBPdcals.log')\n refAnt=str(RefAntOutput[3])\n logprint (\"The pipeline will use antenna \"+refAnt+\" as the reference\", logfileout='logs/testBPdcals.log')\n flaggedSolnResult=testdelays(ms_active,'testdelay.k',delay_field_select_string,delay_scan_select_string,refAnt,minBL_for_cal,priorcals,cal3C84_d,uvrange3C84)\n logprint(\"Fraction of flagged solutions = \"+str(flaggedSolnResult['all']['fraction']), logfileout='logs/testBPdcals.log')\n logprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n if (flaggedSolnResult['all']['total'] > 0):\n fracFlaggedSolns=flaggedSolnResult['antmedian']['fraction']\n else:\n fracFlaggedSolns=1.0\n\n if (fracFlaggedSolns > critfrac):\n logprint (\"WARNING, tried several reference antennas, there might be something wrong with your data\", logfileout='logs/testBPdcals.log')\n\nlogprint (\"Plotting test delays\", logfileout='logs/testBPdcals.log')\n\nnplots=int(numAntenna/3)\n\nif ((numAntenna%3)>0):\n nplots = nplots + 1\n\nfor ii in range(nplots):\n filename='testdelay'+str(ii)+'.png'\n syscommand='rm -rf '+filename\n os.system(syscommand)\n#\n antPlot=str(ii*3)+'~'+str(ii*3+2)\n#\n default('plotcal')\n caltable='testdelay.k'\n xaxis='freq'\n yaxis='delay'\n poln=''\n field=''\n antenna=antPlot\n spw=''\n timerange=''\n subplot=311\n overplot=False\n clearpanel='Auto'\n iteration='antenna'\n plotrange=[]\n showflags=False\n plotsymbol='o'\n plotcolor='blue'\n markersize=5.0\n fontsize=10.0\n showgui=False\n figfile=filename\n plotcal()\n\n# Do initial amplitude and phase gain solutions on the BPcalibrator and delay\n# calibrator; the amplitudes are used for flagging; only phase\n# calibration is applied in final BP calibration, so that solutions are\n# not normalized per spw and take out the baseband filter shape\n\n# Try running with solint of int_time, 3*int_time, and 10*int_time.\n# If there is still a large fraction of failed solutions with\n# solint=10*int_time the source may be too weak, and calibration via the\n# pipeline has failed; will need to implement a mode to cope with weak\n# calibrators (later)\n\nif (delay_scan_select_string == bandpass_scan_select_string):\n testgainscans=bandpass_scan_select_string\nelse:\n testgainscans=bandpass_scan_select_string+','+delay_scan_select_string\n\nif ((cal3C84_d == True) or (cal3C84_bp == True)):\n cal3C84=True\nelse:\n cal3C84=False\n\nsyscommand='rm -rf testBPdinitialgain.g'\nos.system(syscommand)\n\nsoltime=int_time\nsolint='int'\nflaggedSolnResult1=testBPdgains(ms_active,'testBPdinitialgain.g',tst_bpass_spw,testgainscans,solint,refAnt,minBL_for_cal,priorcals,cal3C84,uvrange3C84)\nlogprint(\"For solint = \"+solint+\" fraction of flagged solutions = \"+str(flaggedSolnResult1['all']['fraction']), logfileout='logs/testBPdcals.log')\nlogprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult1['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\nif (flaggedSolnResult1['all']['total'] > 0):\n fracFlaggedSolns1=flaggedSolnResult1['antmedian']['fraction']\nelse:\n fracFlaggedSolns1=1.0\n\ngain_solint1=solint\nshortsol1=soltime\n\nif (fracFlaggedSolns1 > 0.05):\n soltime=3.0*int_time\n solint=str(soltime)+'s'\n flaggedSolnResult3=testBPdgains(ms_active,'testBPdinitialgain3.g',tst_bpass_spw,testgainscans,solint,refAnt,minBL_for_cal,priorcals,cal3C84,uvrange3C84)\n logprint(\"For solint = \"+solint+\" fraction of flagged solutions = \"+str(flaggedSolnResult3['all']['fraction']), logfileout='logs/testBPdcals.log')\n logprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult3['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n if (flaggedSolnResult3['all']['total'] > 0):\n fracFlaggedSolns3=flaggedSolnResult3['antmedian']['fraction']\n else:\n fracFlaggedSolns3=1.0\n\n if (fracFlaggedSolns3 < fracFlaggedSolns1):\n gain_solint1=solint\n shortsol1=soltime\n syscommand='rm -rf testBPdinitialgain.g'\n os.system(syscommand)\n syscommand='mv testBPdinitialgain3.g testBPdinitialgain.g'\n os.system(syscommand)\n if (fracFlaggedSolns3 > 0.05):\n soltime=10.0*int_time\n solint=str(soltime)+'s'\n flaggedSolnResult10=testBPdgains(ms_active,'testBPdinitialgain10.g',tst_bpass_spw,testgainscans,solint,refAnt,minBL_for_cal,priorcals,cal3C84,uvrange3C84)\n logprint(\"For solint = \"+solint+\" fraction of flagged solutions = \"+str(flaggedSolnResult10['all']['fraction']), logfileout='logs/testBPdcals.log')\n logprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult10['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n if (flaggedSolnResult10['all']['total'] > 0):\n fracFlaggedSolns10=flaggedSolnResult10['antmedian']['fraction']\n else:\n fracFlaggedSolns10=1.0\n\n if (fracFlaggedSolns10 < fracFlaggedSolns3):\n gain_solint1=solint\n shortsol1=soltime\n syscommand='rm -rf testBPdinitialgain.g'\n os.system(syscommand)\n syscommand='mv testBPdinitialgain10.g testBPdinitialgain.g'\n os.system(syscommand)\n if (fracFlaggedSolns10 > 0.05):\n logprint (\"WARNING, large fraction of flagged solutions, there might be something wrong with your data\", logfileout='logs/testBPdcals.log')\n\nlogprint (\"Test amp and phase calibration on delay and bandpass calibrators complete\", logfileout='logs/testBPdcals.log')\nlogprint (\"Using short solint = \"+gain_solint1, logfileout='logs/testBPdcals.log')\n\n# Plot amplitude gain solutions\n\nlogprint (\"Plotting amplitude gain solutions\", logfileout='logs/testBPdcals.log')\n\ntb.open('testBPdinitialgain.g')\ncpar=tb.getcol('CPARAM')\nflgs=tb.getcol('FLAG')\ntb.close()\namps=np.abs(cpar)\ngood=np.logical_not(flgs)\nmaxamp=np.max(amps[good])\nplotmax=maxamp\n\nfor ii in range(nplots):\n filename='testBPdinitialgainamp'+str(ii)+'.png'\n syscommand='rm -rf '+filename\n os.system(syscommand)\n#\n antPlot=str(ii*3)+'~'+str(ii*3+2)\n#\n default('plotcal')\n caltable='testBPdinitialgain.g'\n xaxis='time'\n yaxis='amp'\n poln=''\n field=''\n antenna=antPlot\n spw=''\n timerange=''\n subplot=311\n overplot=False\n clearpanel='Auto'\n iteration='antenna'\n plotrange=[0,0,0,plotmax]\n showflags=False\n plotsymbol='o'\n plotcolor='blue'\n markersize=5.0\n fontsize=10.0\n showgui=False\n figfile=filename\n plotcal()\n\n\n# Plot phase gain solutions\n\nlogprint (\"Plotting phase gain solutions\", logfileout='logs/testBPdcals.log')\n\nfor ii in range(nplots):\n filename='testBPdinitialgainphase'+str(ii)+'.png'\n syscommand='rm -rf '+filename\n os.system(syscommand)\n#\n antPlot=str(ii*3)+'~'+str(ii*3+2)\n#\n default('plotcal')\n caltable='testBPdinitialgain.g'\n xaxis='time'\n yaxis='phase'\n poln=''\n field=''\n antenna=antPlot\n spw=''\n timerange=''\n subplot=311\n overplot=False\n clearpanel='Auto'\n iteration='antenna'\n plotrange=[0,0,-180,180]\n showflags=False\n plotsymbol='o-'\n plotcolor='blue'\n markersize=5.0\n fontsize=10.0\n showgui=False\n figfile=filename\n plotcal()\n\n\n# Now do test BPcal\n\nlogprint (\"Doing test bandpass calibration\", logfileout='logs/testBPdcals.log')\n\nsyscommand='rm -rf testBPcal.b'\nos.system(syscommand)\n\nBPGainTables=copy.copy(priorcals)\nBPGainTables.append('testdelay.k')\nBPGainTables.append('testBPdinitialgain.g')\n\nif (cal3C84_bp == True):\n default('bandpass')\n vis=ms_active\n caltable='testBPcal.b'\n field=bandpass_field_select_string\n spw=''\n intent=''\n selectdata=True\n uvrange=uvrange3C84\n scan=bandpass_scan_select_string\n solint='inf'\n combine='scan'\n refant=refAnt\n minblperant=minBL_for_cal\n minsnr=5.0\n solnorm=False\n bandtype='B'\n fillgaps=0\n smodel=[]\n append=False\n docallib=False\n gaintable=BPGainTables\n gainfield=['']\n interp=['']\n spwmap=[]\n parang=False\n bandpass()\nelse:\n default('bandpass')\n vis=ms_active\n caltable='testBPcal.b'\n field=bandpass_field_select_string\n spw=''\n intent=''\n selectdata=True\n uvrange=''\n scan=bandpass_scan_select_string\n solint='inf'\n combine='scan'\n refant=refAnt\n minblperant=minBL_for_cal\n minsnr=5.0\n solnorm=False\n bandtype='B'\n fillgaps=0\n smodel=[]\n append=False\n docallib=False\n gaintable=BPGainTables\n gainfield=['']\n interp=['']\n spwmap=[]\n parang=False\n bandpass()\n\nlogprint (\"Test bandpass calibration complete\", logfileout='logs/testBPdcals.log')\nflaggedSolnResult=getCalFlaggedSoln('testBPcal.b')\n\nlogprint(\"Fraction of flagged solutions = \"+str(flaggedSolnResult['all']['fraction']), logfileout='logs/testBPdcals.log')\nlogprint(\"Median fraction of flagged solutions per antenna = \"+str(flaggedSolnResult['antmedian']['fraction']), logfileout='logs/testBPdcals.log')\n\n# Plot BP solutions and check for missing spws, antennas, etc.\n\ntb.open('testBPcal.b')\ndataVarCol = tb.getvarcol('CPARAM')\nflagVarCol = tb.getvarcol('FLAG')\ntb.close()\nrowlist = dataVarCol.keys()\nnrows = len(rowlist)\nmaxmaxamp = 0.0\nmaxmaxphase = 0.0\nfor rrow in rowlist:\n dataArr = dataVarCol[rrow]\n flagArr = flagVarCol[rrow]\n amps=np.abs(dataArr)\n phases=np.arctan2(np.imag(dataArr),np.real(dataArr))\n good=np.logical_not(flagArr)\n tmparr=amps[good]\n if (len(tmparr)>0):\n maxamp=np.max(amps[good])\n if (maxamp>maxmaxamp):\n maxmaxamp=maxamp\n tmparr=np.abs(phases[good])\n if (len(tmparr)>0):\n maxphase=np.max(np.abs(phases[good]))*180./pi\n if (maxphase>maxmaxphase):\n maxmaxphase=maxphase\n\nampplotmax=maxmaxamp\nphaseplotmax=maxmaxphase\n\nfor ii in range(nplots):\n filename='testBPcal_amp'+str(ii)+'.png'\n syscommand='rm -rf '+filename\n os.system(syscommand)\n#\n antPlot=str(ii*3)+'~'+str(ii*3+2)\n#\n default('plotcal')\n caltable='testBPcal.b'\n xaxis='freq'\n yaxis='amp'\n poln=''\n field=''\n antenna=antPlot\n spw=''\n timerange=''\n subplot=311\n overplot=False\n clearpanel='Auto'\n iteration='antenna'\n plotrange=[0,0,0,ampplotmax]\n showflags=False\n plotsymbol='o'\n plotcolor='blue'\n markersize=5.0\n fontsize=10.0\n showgui=False\n figfile=filename\n plotcal()\n\nfor ii in range(nplots):\n filename='testBPcal_phase'+str(ii)+'.png'\n syscommand='rm -rf '+filename\n os.system(syscommand)\n#\n antPlot=str(ii*3)+'~'+str(ii*3+2)\n#\n default('plotcal')\n caltable='testBPcal.b'\n xaxis='freq'\n yaxis='phase'\n poln=''\n field=''\n antenna=antPlot\n spw=''\n timerange=''\n subplot=311\n overplot=False\n clearpanel='Auto'\n iteration='antenna'\n plotrange=[0,0,-phaseplotmax,phaseplotmax]\n showflags=False\n plotsymbol='o'\n plotcolor='blue'\n markersize=5.0\n fontsize=10.0\n showgui=False\n figfile=filename\n plotcal()\n\nlogprint (\"Plotting of test bandpass solutions complete\", logfileout='logs/testBPdcals.log')\n\n# Do blcal to take out closure errors from source structure for plotting\n# NB: would be good to be able to specify smodel=[1,0,0,0] here since\n# otherwise this only works for sources that are not primary calibrators\n# NB: blcal crashes if a spw is missing from gaintable, can't use this\n# for now\n\n#default('blcal')\n#vis=ms_active\n#caltable='testBPblcal.bl'\n#field=''\n#spw=''\n#selectdata=True\n#scans=testgainscans\n#solint='30min'\n#combine='scan'\n#freqdep=False\n#calmode='ap'\n#solnorm=False\n#gaintable=[priorcals,'testdelay.k','testBPdinitialgain.g','testBPcal.b']\n#gainfield=['']\n#interp=['']\n#spwmap=[]\n#parang=False\n#blcal()\n\n# NB: level of blcal corrections are an indicator of pointy-ness of\n# BPcal and delay cal and/or system health\n\n# Apply gain and bandpass solutions and inspect calibrated BP and delay\n# calibrator data for RFI or other problems\n\nlogprint (\"Applying test calibrations to BP and delay calibrators\", logfileout='logs/testBPdcals.log')\n\nAllCalTables=copy.copy(priorcals)\nAllCalTables.append('testdelay.k')\nAllCalTables.append('testBPdinitialgain.g')\nAllCalTables.append('testBPcal.b')\n\nntables=len(AllCalTables)\n\ndefault('applycal')\nvis=ms_active\nfield=''\nspw=''\nintent=''\nselectdata=True\nscan=testgainscans\ndocallib=False\ngaintable=AllCalTables\ngainfield=['']\ninterp=['']\nspwmap=[]\ncalwt=[False]*ntables\nparang=False\napplymode='calflagstrict'\nflagbackup=False\napplycal()\n\nlogprint (\"Plot calibrated bandpass and delay calibrators\", logfileout='logs/testBPdcals.log')\n\nsyscommand='rm -rf testcalibratedBPcal.png'\nos.system(syscommand)\n\ndefault('plotms')\nvis=ms_active\nxaxis='freq'\nyaxis='amp'\nydatacolumn='corrected'\nselectdata=True\nfield=bandpass_field_select_string\nscan=bandpass_scan_select_string\ncorrelation=corrstring\naveragedata=True\navgtime='1e8s'\navgscan=True\ntransform=False\nextendflag=False\niteraxis=''\ncoloraxis='antenna2'\nplotrange=[]\ntitle=''\nxlabel=''\nylabel=''\nshowmajorgrid=False\nshowminorgrid=False\nplotfile='testcalibratedBPcal.png'\noverwrite=True\nshowgui=False\nplotms()\n\n# Plot calibrated delay calibrator, if different from BP cal\n\nif (delay_scan_select_string != bandpass_scan_select_string):\n syscommand='rm -rf testcalibrated_delaycal.png'\n os.system(syscommand)\n#\n default('plotms')\n vis=ms_active\n xaxis='freq'\n yaxis='amp'\n ydatacolumn='corrected'\n selectdata=True\n scan=delay_scan_select_string\n correlation=corrstring\n averagedata=True\n avgtime='1e8s'\n avgscan=True\n transform=False\n extendflag=False\n iteraxis=''\n coloraxis='antenna2'\n plotrange=[]\n title=''\n xlabel=''\n ylabel=''\n showmajorgrid=False\n showminorgrid=False\n plotfile='testcalibrated_delaycal.png'\n overwrite=True\n showgui=False\n plotms()\n\n# Calculate fractions of flagged solutions for final QA2\n\nflaggedDelaySolns=getCalFlaggedSoln('testdelay.k')\nflaggedGainSolns=getCalFlaggedSoln('testBPdinitialgain.g')\nflaggedBPSolns=getCalFlaggedSoln('testBPcal.b')\n\nif (flaggedDelaySolns['all']['total'] > 0):\n if (flaggedDelaySolns['antmedian']['fraction'] > critfrac):\n QA2_delay='Partial'\n else:\n QA2_delay='Pass'\nelse:\n QA2_delay='Fail'\n\nlogprint (\"QA2_delay: \"+QA2_delay, logfileout='logs/testBPdcals.log')\n\nif (flaggedGainSolns['all']['total'] > 0):\n if (flaggedGainSolns['antmedian']['fraction'] > 0.1):\n QA2_gain='Partial'\n else:\n QA2_gain='Pass'\nelse:\n QA2_gain='Fail'\n\nlogprint (\"QA2_gain: \"+QA2_gain, logfileout='logs/testBPdcals.log')\n\nif (flaggedBPSolns['all']['total'] > 0):\n if (flaggedBPSolns['antmedian']['fraction'] > 0.2):\n QA2_BP='Partial'\n else:\n QA2_BP='Pass'\nelse:\n QA2_BP='Fail'\n\nlogprint (\"QA2_BP: \"+QA2_BP, logfileout='logs/testBPdcals.log')\n\nif (QA2_delay=='Fail' or QA2_gain=='Fail' or QA2_BP=='Fail'):\n QA2_testBPdcals='Fail'\nelif (QA2_delay=='Partial' or QA2_gain=='Partial' or QA2_BP=='Partial'):\n QA2_testBPdcals='Partial'\n\n\nlogprint (\"QA2 score: \"+QA2_testBPdcals, logfileout='logs/testBPdcals.log')\nlogprint (\"Finished EVLA_pipe_testBPdcals.py\", logfileout='logs/testBPdcals.log')\ntime_list=runtiming('testBPdcals', 'end')\n\npipeline_save()\n","sub_path":"12A-403/pipeline4.6.0/EVLA_pipe_testBPdcals.py","file_name":"EVLA_pipe_testBPdcals.py","file_ext":"py","file_size_in_byte":21667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"163586525","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/synctools/test/test_rsyncmanager.py\n# Compiled at: 2020-03-06 02:01:31\n# Size of source mod 2**32: 3974 bytes\n__authors__ = [\n 'H. Payno']\n__license__ = 'MIT'\n__date__ = '17/01/2018'\nimport filecmp, logging, os, shutil, tempfile, unittest\nfrom tomwer.synctools.rsyncmanager import RSyncManager\nfrom tomwer.test.utils import UtilsTest\nlogging.disable(logging.INFO)\n\n@unittest.skipIf(RSyncManager().canUseRSync() is False, 'Rsync is missing')\nclass TestRSyncManager(unittest.TestCase):\n __doc__ = 'Check that the RSyncManager is correctly synchronizing folders.\\n '\n\n def setUp(self):\n self.topSrcFolder = tempfile.mkdtemp()\n self.topTargetFolder = tempfile.mkdtemp()\n self.dataSetID = 'test01'\n self.dataDir = UtilsTest.getDataset(self.dataSetID)\n self.sourceFolder = os.path.join(self.topSrcFolder, self.dataSetID)\n shutil.copytree(src=(os.path.join(self.dataDir)), dst=(self.sourceFolder))\n\n def tearDown(self):\n shutil.rmtree(self.topSrcFolder)\n shutil.rmtree(self.topTargetFolder)\n\n def testSyncFolder(self):\n \"\"\"Test that a simple sync between two folders are valid\"\"\"\n self.assertTrue(len(os.listdir(self.topTargetFolder)) is 0)\n manager = RSyncManager()\n manager.syncFolder(source=(self.sourceFolder), target=(self.topTargetFolder),\n block=True,\n delete=False)\n targetFolder = os.path.join(self.topTargetFolder, self.dataSetID)\n self.assertTrue(len(os.listdir(targetFolder)) == len(os.listdir(self.sourceFolder)))\n self.assertTrue(filecmp.dircmp(targetFolder, self.sourceFolder))\n self.assertTrue(os.path.isdir(self.sourceFolder))\n\n def testSyncFolderDelete(self):\n \"\"\"Test that a simple sync between two folders are valid ans source\n folder is correctly deleted\"\"\"\n self.assertTrue(len(os.listdir(self.topTargetFolder)) is 0)\n manager = RSyncManager()\n manager.syncFolder(source=(self.sourceFolder), target=(self.topTargetFolder),\n block=True,\n delete=True)\n targetFolder = os.path.join(self.topTargetFolder, self.dataSetID)\n self.assertTrue(len(os.listdir(targetFolder)) == len(os.listdir(self.dataDir)))\n self.assertTrue(filecmp.dircmp(targetFolder, self.sourceFolder))\n self.assertFalse(os.path.isdir(self.sourceFolder))\n\n\ndef suite():\n test_suite = unittest.TestSuite()\n for ui in (TestRSyncManager,):\n test_suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ui))\n\n return test_suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/test_rsyncmanager.cpython-37.py","file_name":"test_rsyncmanager.cpython-37.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"347115122","text":"import movies.media as media\nimport movies.fresh_tomatoes as fresh_tomatoes\n\ntoy_story = media.Movie(\n 'Toy story',\n 'A story of a boy and his toys that come to life',\n 'https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg',\n 'https://www.youtube.com/watch?v=m9CvO0s6Tzw'\n)\n\nmovies = [toy_story]\nfresh_tomatoes.open_movies_page(movies)\n\n","sub_path":"python/venv/movies/entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"253350069","text":"'''\n给你一个数组 nums,请你从中抽取一个子序列,满足该子序列的元素之和 严格 大于未包含在该子序列中的各元素之和。\n如果存在多个解决方案,只需返回 长度最小 的子序列。如果仍然有多个解决方案,则返回 元素之和最大 的子序列。\n与子数组不同的地方在于,「数组的子序列」不强调元素在原数组中的连续性\n也就是说,它可以通过从数组中分离一些(也可能不分离)元素得到。\n注意,题目数据保证满足所有约束条件的解决方案是 唯一 的。同时,返回的答案应当按 非递增顺序 排列。\n\n示例 1:\n输入:nums = [4,3,10,9,8]\n输出:[10,9]\n解释:子序列 [10,9] 和 [10,8] 是最小的、满足元素之和大于其他各元素之和的子序列。\n但是 [10,9] 的元素之和最大。 \n\n示例 2:\n输入:nums = [4,4,7,6,7]\n输出:[7,7,6]\n解释:子序列 [7,7] 的和为 14 ,不严格大于剩下的其他元素之和(14 = 4 + 4 + 6)。\n因此,[7,6,7] 是满足题意的最小子序列。注意,元素按非递增顺序返回。\n\n示例 3:\n输入:nums = [6]\n输出:[6]\n\n提示:\n1 <= nums.length <= 500\n1 <= nums[i] <= 100\n'''\nfrom typing import List\n\n\nclass Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort()\n result = []\n while len(nums) > 0:\n result.append(nums.pop())\n if sum(result) > sum(nums):\n return result\n\n\nclass Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort(reverse=True)\n tmp = sum(nums)\n res = 0\n for i in range(len(nums)):\n res += nums[i]\n if res > tmp / 2:\n return nums[:i + 1]\n","sub_path":"LeetCode/1403. 非递增顺序的最小子序列.py","file_name":"1403. 非递增顺序的最小子序列.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"425522990","text":"from . import ClientLocalServerResources\nfrom . import HydrusServer\nfrom twisted.web.resource import NoResource\n\nclass HydrusClientService( HydrusServer.HydrusService ):\n \n def __init__( self, service, allow_non_local_connections ):\n \n if allow_non_local_connections:\n \n self._client_requests_domain = HydrusServer.REMOTE_DOMAIN\n \n else:\n \n self._client_requests_domain = HydrusServer.LOCAL_DOMAIN\n \n \n HydrusServer.HydrusService.__init__( self, service )\n \n \nclass HydrusServiceBooru( HydrusClientService ):\n \n def _InitRoot( self ):\n \n root = HydrusClientService._InitRoot( self )\n \n root.putChild( b'gallery', ClientLocalServerResources.HydrusResourceBooruGallery( self._service, self._client_requests_domain ) )\n root.putChild( b'page', ClientLocalServerResources.HydrusResourceBooruPage( self._service, self._client_requests_domain ) )\n root.putChild( b'file', ClientLocalServerResources.HydrusResourceBooruFile( self._service, self._client_requests_domain ) )\n root.putChild( b'thumbnail', ClientLocalServerResources.HydrusResourceBooruThumbnail( self._service, self._client_requests_domain ) )\n root.putChild( b'style.css', ClientLocalServerResources.local_booru_css )\n \n return root\n \n \nclass HydrusServiceClientAPI( HydrusClientService ):\n \n def _InitRoot( self ):\n \n root = HydrusClientService._InitRoot( self )\n \n root.putChild( b'api_version', ClientLocalServerResources.HydrusResourceClientAPIVersion( self._service, self._client_requests_domain ) )\n root.putChild( b'request_new_permissions', ClientLocalServerResources.HydrusResourceClientAPIPermissionsRequest( self._service, self._client_requests_domain ) )\n root.putChild( b'session_key', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAccountSessionKey( self._service, self._client_requests_domain ) )\n root.putChild( b'verify_access_key', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAccountVerify( self._service, self._client_requests_domain ) )\n \n add_files = NoResource()\n \n root.putChild( b'add_files', add_files )\n \n add_files.putChild( b'add_file', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddFile( self._service, self._client_requests_domain ) )\n \n add_tags = NoResource()\n \n root.putChild( b'add_tags', add_tags )\n \n add_tags.putChild( b'add_tags', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddTagsAddTags( self._service, self._client_requests_domain ) )\n add_tags.putChild( b'clean_tags', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddTagsCleanTags( self._service, self._client_requests_domain ) )\n add_tags.putChild( b'get_tag_services', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddTagsGetTagServices( self._service, self._client_requests_domain ) )\n \n add_urls = NoResource()\n \n root.putChild( b'add_urls', add_urls )\n \n add_urls.putChild( b'get_url_info', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddURLsGetURLInfo( self._service, self._client_requests_domain ) )\n add_urls.putChild( b'get_url_files', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddURLsGetURLFiles( self._service, self._client_requests_domain ) )\n add_urls.putChild( b'add_url', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddURLsImportURL( self._service, self._client_requests_domain ) )\n add_urls.putChild( b'associate_url', ClientLocalServerResources.HydrusResourceClientAPIRestrictedAddURLsAssociateURL( self._service, self._client_requests_domain ) )\n \n get_files = NoResource()\n \n root.putChild( b'get_files', get_files )\n \n get_files.putChild( b'search_files', ClientLocalServerResources.HydrusResourceClientAPIRestrictedGetFilesSearchFiles( self._service, self._client_requests_domain ) )\n get_files.putChild( b'file_metadata', ClientLocalServerResources.HydrusResourceClientAPIRestrictedGetFilesFileMetadata( self._service, self._client_requests_domain ) )\n get_files.putChild( b'file', ClientLocalServerResources.HydrusResourceClientAPIRestrictedGetFilesGetFile( self._service, self._client_requests_domain ) )\n get_files.putChild( b'thumbnail', ClientLocalServerResources.HydrusResourceClientAPIRestrictedGetFilesGetThumbnail( self._service, self._client_requests_domain ) )\n \n manage_pages = NoResource()\n \n root.putChild( b'manage_pages', manage_pages )\n \n manage_pages.putChild( b'get_pages', ClientLocalServerResources.HydrusResourceClientAPIRestrictedManagePagesGetPages( self._service, self._client_requests_domain ) )\n \n return root\n \n \n","sub_path":"include/ClientLocalServer.py","file_name":"ClientLocalServer.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"42439617","text":"import sys\nimport os\nfrom functools import partial\n\nfrom PyQt5.QtCore import Qt, QObject, QModelIndex\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QHBoxLayout, QVBoxLayout, QPushButton,\n QTableView, QCheckBox, QAbstractItemView)\n\nfrom tinos_steam_helper.data_queries import open_browser\nfrom .GamesLibrary import GamesLibrary\nfrom .GamesTableModel import GamesTableModel, MySortFilterProxyModel\nfrom .AddNewGamesDialog import AddNewGamesDialog\n\n\nclass GamesWidget(QWidget):\n def __init__(self, user_id, api_key, db_directory, parent=None):\n super().__init__(parent=None)\n\n self.user_id = user_id\n\n # table view\n self.owned_games_view = QTableView(self)\n self.owned_games_view.doubleClicked.connect(self.double_clicked_library_cell)\n self.owned_games_view.setSortingEnabled(True)\n self.owned_games_view.setSelectionBehavior(QAbstractItemView.SelectRows)\n\n self.games_lib = GamesLibrary(self.user_id)\n self.sort_proxy = MySortFilterProxyModel()\n self.owned_games_view.setModel(self.sort_proxy)\n\n # the button row at the side\n self.load_games_button = QPushButton(\"load Games\")\n self.load_games_button.clicked.connect(self.load_games)\n self.update_games_button = QPushButton(\"update Games\")\n self.update_games_button.clicked.connect(self.update_games)\n self.write_button = QPushButton(\"save to disk\")\n self.write_button.clicked.connect(self.games_lib.write_library)\n\n self.shortlist_button = QPushButton(\"Shortlist\")\n self.shortlist_button.clicked.connect(self.set_shortlist)\n\n self.normal_button = QPushButton(\"normal\")\n self.normal_button.clicked.connect(self.set_normal)\n\n self.trash_button = QPushButton(\"Trash\")\n self.trash_button.clicked.connect(self.set_trash)\n\n self.finished_button = QPushButton(\"finished\")\n self.finished_button.clicked.connect(self.set_finished)\n\n self.move_up_button = QPushButton(\"↑ move up\")\n self.move_up_button.clicked.connect(partial(self.move_selected_rows, -1))\n self.move_down_button = QPushButton(\"↓ move down\")\n self.move_down_button.clicked.connect(partial(self.move_selected_rows, 1))\n\n self.delete_button = QPushButton(\"delete\")\n self.delete_button.clicked.connect(self.delete_selected_rows)\n\n self.hide_finished_box = QCheckBox(\"finished\", self)\n self.hide_trash_box = QCheckBox(\"Trash\", self)\n self.hide_finished_box.stateChanged.connect(\n partial(self.sort_proxy.set_filter_from_checkbox,\n trash_box=self.hide_trash_box,\n finished_box=self.hide_finished_box))\n self.hide_trash_box.stateChanged.connect(\n partial(self.sort_proxy.set_filter_from_checkbox,\n trash_box=self.hide_trash_box,\n finished_box=self.hide_finished_box))\n\n vbox = QVBoxLayout()\n vbox.addWidget(self.load_games_button)\n vbox.addWidget(self.update_games_button)\n vbox.addWidget(self.write_button)\n vbox.addWidget(QLabel(\"\"))\n vbox.addWidget(QLabel(\"Popularity\"))\n vbox.addWidget(self.shortlist_button)\n vbox.addWidget(self.normal_button)\n vbox.addWidget(self.trash_button)\n vbox.addWidget(QLabel(\"\"))\n vbox.addWidget(self.finished_button)\n vbox.addWidget(QLabel(\"\"))\n vbox.addWidget(self.move_up_button)\n vbox.addWidget(self.move_down_button)\n vbox.addWidget(QLabel(\"\"))\n vbox.addWidget(self.delete_button)\n\n vbox.addStretch(1)\n vbox.addWidget(QLabel(\"hide Games\"))\n vbox.addWidget(self.hide_finished_box)\n vbox.addWidget(self.hide_trash_box)\n vbox.addWidget(parent.quit_button())\n\n # set the window layout\n hbox = QHBoxLayout(self)\n hbox.addWidget(self.owned_games_view)\n hbox.addLayout(vbox)\n self.setLayout(hbox)\n\n def load_games_force(self):\n return\n for f in [self.games_lib.games_buffer_path,\n self.games_lib.games_library_path]:\n try:\n os.remove(f)\n except FileNotFoundError:\n pass\n # self.load_games()\n\n def update_games(self):\n games_new = []\n table, _ = self.games_lib.download_games_library()\n current_appids = [g[3] for g in self.games_lib.games_table]\n for game in table:\n if game[3] not in current_appids:\n games_new.append(game)\n\n AddNewGamesDialog.make_popup(self.games_lib, games_new, parent=self)\n\n def load_games(self):\n\n table_data, column_names = self.games_lib.load_games_library()\n\n self.games_model = GamesTableModel(table_data, self,\n column_names=column_names)\n self.games_model.update_ranks()\n\n self.sort_proxy.setSourceModel(self.games_model)\n self.owned_games_view.resizeColumnToContents(0)\n self.owned_games_view.resizeColumnToContents(1)\n self.owned_games_view.setColumnWidth(2, 200)\n\n def double_clicked_library_cell(self, index):\n if index.isValid():\n if index.column() == 1:\n appid = index.sibling(index.row(), 3).data()\n url = f\"https://store.steampowered.com/app/{appid}/\"\n open_browser.open_url(url)\n elif index.column() == 3:\n appid = index.data()\n url = f\"steam://run/{appid}\"\n\n def set_popularity(self, new_pop=\"nomal\", selection=None):\n selection = selection or self.owned_games_view.selectionModel()\n for index in selection.selectedRows():\n pop_index = self.owned_games_view.model().index(index.row(), 5)\n self.owned_games_view.model().setData(pop_index, new_pop)\n\n def set_shortlist(self):\n selection = self.owned_games_view.selectionModel()\n if selection.hasSelection():\n new_rows = []\n for idx in sorted([get_rank_from_idx(idx) for idx in\n selection.selectedRows()]):\n if self.games_model.arraydata[idx][-1] == \"Shortlist\":\n new_rows.append(idx)\n continue\n for i, datarow in enumerate(self.games_model.arraydata):\n if datarow[-1] != \"Shortlist\":\n new_rows.append(i)\n self.games_model.arraydata[idx][-1] = \"Shortlist\"\n if idx > i:\n self.games_model.moveRow(idx, i)\n break\n selection.clear()\n for new_row in new_rows:\n selection.select(self.games_model.index(new_row, 0),\n selection.Select | selection.Rows)\n self.games_model.update_ranks()\n\n def set_trash(self):\n selection = self.owned_games_view.selectionModel()\n if selection.hasSelection():\n new_rows = []\n for idx in sorted([get_rank_from_idx(idx) for idx in\n selection.selectedRows()],\n reverse=True):\n if self.games_model.arraydata[idx][-1] == \"Trash\":\n new_rows.append(idx)\n continue\n for i in range(len(self.games_model.arraydata) - 1, -1, -1):\n if self.games_model.arraydata[i][-1] != \"Trash\":\n new_rows.append(i)\n self.games_model.arraydata[idx][-1] = \"Trash\"\n if idx < i:\n self.games_model.moveRow(idx, i)\n break\n selection.clear()\n for new_row in new_rows:\n selection.select(self.games_model.index(new_row, 0),\n selection.Select | selection.Rows)\n self.games_model.update_ranks()\n\n def set_normal(self):\n selection = self.owned_games_view.selectionModel()\n if selection.hasSelection():\n new_rows = []\n for idx in sorted([get_rank_from_idx(idx) for idx in\n selection.selectedRows()]):\n if self.games_model.arraydata[idx][-1] == \"Trash\":\n for i, datarow in enumerate(self.games_model.arraydata):\n if datarow[-1] == \"Trash\":\n new_rows.append(i)\n self.games_model.arraydata[idx][-1] = \"normal\"\n if idx > i:\n self.games_model.moveRow(idx, i)\n break\n for idx in sorted([get_rank_from_idx(idx) for idx in\n selection.selectedRows()], reverse=True):\n if self.games_model.arraydata[idx][-1] == \"Shortlist\":\n for i in range(len(self.games_model.arraydata) - 1, -1, -1):\n if self.games_model.arraydata[i][-1] == \"Shortlist\":\n new_rows.append(i)\n self.games_model.arraydata[idx][-1] = \"normal\"\n if idx <= i:\n self.games_model.moveRow(idx, i)\n break\n elif self.games_model.arraydata[idx][-1] == \"normal\":\n new_rows.append(idx)\n\n selection.clear()\n for new_row in new_rows:\n selection.select(self.games_model.index(new_row, 0),\n selection.Select | selection.Rows)\n self.games_model.update_ranks()\n\n def set_finished(self):\n # move games to the trash section\n self.set_trash()\n # move games just in front of the trash section\n self.set_normal()\n # set popularity as \"finished\"\n self.set_popularity(QObject().tr(\"finished\"))\n\n def brute_force_index(self, rank=None, name=None):\n in_idx = self.owned_games_view.selectionModel().selectedRows()[0]\n if name is not None:\n for i in range(self.games_model.rowCount()):\n idx = in_idx.sibling(i, 2)\n if idx.data() == name:\n return idx\n elif rank is not None:\n for i in range(self.games_model.rowCount()):\n idx = in_idx.sibling(i, 0)\n if idx.data() == rank:\n return idx\n return QModelIndex()\n\n def move_selected_rows(self, direction):\n\n model = self.games_model\n selection = self.owned_games_view.selectionModel()\n selectedRows = selection.selectedRows()\n if not selectedRows:\n return\n\n indices = sorted(selectedRows, reverse=(direction > 0),\n key=get_rank_from_idx)\n\n new_rows = []\n pers_indices = []\n min_row = 0\n max_row = model.rowCount() - 1\n for idx in indices:\n\n rowNum = get_rank_from_idx(idx)\n newRow = rowNum + direction\n\n # protect against edge effects\n if newRow == min_row:\n min_row += 1\n elif newRow < min_row:\n newRow = min_row\n min_row += 1\n elif newRow > max_row:\n newRow = max_row\n max_row -= 1\n elif newRow == max_row:\n max_row -= 1\n\n if newRow != rowNum:\n model.moveRow(rowNum, newRow)\n model.update_ranks()\n\n new_idx = self.brute_force_index(rank=newRow + 1)\n new_rows.append(new_idx.row())\n\n selection.clear()\n for new_row in new_rows:\n selection.select(model.index(new_row, 0),\n selection.Select | selection.Rows)\n\n def delete_selected_rows(self):\n model = self.games_model\n selection = self.owned_games_view.selectionModel()\n selectedRows = selection.selectedRows()\n for idx in sorted(selectedRows, reverse=True, key=get_rank_from_idx):\n model.takeRow(idx.row())\n model.update_ranks()\n self.games_lib.games_table = model.arraydata\n return True\n\n\ndef get_rank_from_idx(idx):\n return idx.sibling(idx.row(), 0).data() - 1\n","sub_path":"tinos_steam_helper/games_library/GamesWidget.py","file_name":"GamesWidget.py","file_ext":"py","file_size_in_byte":12338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"390893890","text":"\n#Author : Alfan F. Wicaksono\n#IR Lab, FASILKOM, UI\n\n#Script for computing top-N unigram\n\nfrom collections import Counter\nimport re\n\n############### You can modify this part ##############\n\nfileName = \"prabowonegativetweet.txt\"\ntopN = 100\n\n#######################################################\n\nfin = open(fileName, \"r\")\nwords = re.findall('\\w+', fin.read())\n\nc = Counter(words)\nkv = c.most_common(topN)\n\nfor k,v in kv:\n print(k, v)\n\n\n","sub_path":"unigramcount.py","file_name":"unigramcount.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"462411874","text":"import dataclasses as _dc\nimport operator\nimport typing\nimport warnings\nfrom contextlib import contextmanager\nfrom typing import (\n Any,\n Callable,\n ClassVar,\n Dict,\n NamedTuple,\n Optional,\n Type,\n TypeVar,\n Union,\n cast,\n)\n\nimport dask.array as da\nimport numpy as np\nimport toolz as tz\nfrom typing_extensions import (\n Annotated,\n _AnnotatedAlias,\n get_args,\n get_origin,\n get_type_hints,\n)\n\ntry:\n from typing import _tp_cache\nexcept ImportError:\n\n def _tp_cache(x):\n return x\n\n\nfrom .event import EmitterGroup, Event\nfrom .types import SupportsEvents\n\nON_SET = \"_on_{name}_set\"\nON_GET = \"_on_{name}_get\"\nC = TypeVar(\"C\")\nT = TypeVar(\"T\")\nNO_ATTR = object()\n\n\nclass Property:\n \"\"\"Declare a dataclass field as a property with getter/setter functions.\n\n This class is nearly an alias for `typing_extensions.Annotated` (or, in\n ≥python3.9, `typing.Annotated`), except that it provides stricter type\n checking. See `__class_getitem__` for special considerations.\n\n ``Property`` should be used with the actual type, followed by an optional\n ``getter`` function (or ``None``), followed by an optional ``setter``\n function (or ``None``): e.g. ``Property[Blending, str, Blending]``\n\n Examples\n --------\n\n >>> @evented_dataclass\n ... class Test:\n ... # x will be stored as an int but *retrieved* as a string.\n ... x: Property[int, str, int]\n \"\"\"\n\n def __new__(cls, *args, **kwargs):\n raise TypeError(\"Type Property cannot be instantiated\")\n\n def __init_subclass__(cls, *args, **kwargs):\n raise TypeError(f\"Cannot subclass {cls.__module__}.Property\")\n\n @_tp_cache\n def __class_getitem__(cls, params):\n \"\"\"Create the runtime type representation of a Property type.\n\n Unfortunately, in order for this to behave like an `Annotated` type,\n without us having to vendor a lot of the python\n typing library, this must return an instance of\n `typing_extensions._AnnotatedAlias` (which just points to\n `typing._AnnotatedAlias` after python 3.9). Hence the private import.\n Since this works on python3.9 (when typing acquired the Annotated type)\n it seems unlikely to break in future python releases. But it should be\n monitored.\n \"\"\"\n if not isinstance(params, tuple) or not (1 < len(params) < 4):\n raise TypeError(\n \"Property[...] should be used with exactly two or three \"\n \"arguments (a type, a getter, and an optional setter)\"\n )\n msg = \"Property[T, ...]: T must be a type.\"\n origin = typing._type_check(params[0], msg)\n if params[1] is not None and not callable(params[1]):\n raise TypeError(f\"Property getter not callable: {params[1]}\")\n if (\n len(params) > 2\n and params[2] is not None\n and not callable(params[2])\n ):\n raise TypeError(f\"Property getter not callable: {params[1]}\")\n metadata = tuple(params[1:])\n return _AnnotatedAlias(origin, metadata)\n\n\n# from dataclasses.py in the standard library\ndef _is_classvar(a_type):\n # This test uses a typing internal class, but it's the best way to\n # test if this is a ClassVar.\n return a_type is typing.ClassVar or (\n type(a_type) is typing._GenericAlias\n and a_type.__origin__ is typing.ClassVar\n )\n\n\n# from dataclasses.py in the standard library\ndef _is_initvar(a_type):\n # The module we're checking against is the module we're\n # currently in (dataclasses.py).\n return a_type is _dc.InitVar or type(a_type) is _dc.InitVar\n\n\n@contextmanager\ndef stripped_annotated_types(cls):\n \"\"\"Temporarily strip Annotated types (for cleaner function signatures).\"\"\"\n original_annotations = cls.__annotations__\n cls.__annotations__ = get_type_hints(cls, include_extras=False)\n yield\n cls.__annotations__ = original_annotations\n\n\ndef set_with_events(self: C, name: str, value: Any) -> None:\n \"\"\"Modified __setattr__ method that emits an event when set.\n\n Events will *only* be emitted if the ``name`` of the attribute being set\n is one of the dataclass fields (i.e. ``name in self.__annotations__``),\n and the dataclass ``__post_init__` method has already been called.\n\n Also looks for and calls an optional ``_on_name_set()`` method afterwards.\n\n Order of operations:\n 1. Call the original ``__setattr__`` function to set the value\n 2. Look for an ``_on_name_set`` method on the object\n a. If present, call it with the current value\n b. That method can do anything (including changing the value, or\n emitting its own events if necessary). If changing the value,\n it should check to make sure that it is different than the\n current value before setting, or a ``RecursionError`` may occur.\n c. If that method returns ``True``. Return *without* emitting\n an event.\n 3. If ``_on_name_set`` has not returned ``True``, then emit an event\n from the EventEmitter with the corresponding ``name`` in the.\n e.g. ``self.events.(value=value)``.\n\n Parameters\n ----------\n self : C\n An instance of the decorated dataclass of Type[C]\n name : str\n The name of the attribute being set.\n value : Any\n The new value for the attribute.\n fields : set of str\n Only emit events for field names in this set.\n \"\"\"\n if name not in getattr(self, 'events', {}):\n # fallback to default behavior\n object.__setattr__(self, name, value)\n return\n\n # grab current value\n before = getattr(self, name, NO_ATTR)\n object.__setattr__(self, name, value)\n\n # if custom set method `_on__set` exists, call it\n setter_method = getattr(self, ON_SET.format(name=name), None)\n if callable(setter_method):\n # the method can return True, if it wants to handle its own events\n try:\n if setter_method(getattr(self, name)):\n return\n except Exception as e:\n if before is NO_ATTR:\n object.__delattr__(self, name)\n else:\n object.__setattr__(self, name, before)\n meth_name = f\"{self.__class__.__name__}.{ON_SET.format(name=name)}\"\n raise type(e)(f\"Error in {meth_name} (value not set): {e}\")\n\n # if different we emit the event with new value\n after = getattr(self, name)\n if not self.__equality_checks__.get(name, is_equal)(after, before):\n # use gettattr again in case `_on_name_set` has modified it\n getattr(self.events, name)(value=after) # type: ignore\n\n\ndef is_equal(v1, v2):\n \"\"\"\n Function for basic comparison compare.\n\n Parameters\n ----------\n v1 : Any\n first value\n v2 : Any\n second value\n\n Returns\n -------\n result : bool\n Returns ``True`` if ``v1`` and ``v2`` are equivalent.\n If an exception is raised during comparison, returns ``False``.\n\n Warns\n -----\n UserWarning\n If an exception is raised during comparison.\n \"\"\"\n try:\n return bool(v1 == v2)\n except Exception as e:\n warnings.warn(\n \"Comparison method failed. Returned False. \"\n f\"There may be need to define custom compare methods in __equality_checks__ dictionary. Exception {e}\"\n )\n return False\n\n\ndef _type_to_compare(type_) -> Optional[Callable[[Any, Any], bool]]:\n \"\"\"\n Try to determine compare function for types which cannot be compared with `operator.eq`.\n Currently support `numpy.ndarray` and `dask.core.Array`.\n Unpack `typing.Optional` and `dataclasses.InitVar` box.\n\n Parameters\n ----------\n type_ : type\n type to examine\n\n Returns\n -------\n Optional[Callable[[Any, Any], bool]]\n Compare function\n \"\"\"\n import inspect\n\n if isinstance(type_, _AnnotatedAlias):\n type_ = type_.__origin__\n if isinstance(type_, _dc.InitVar):\n type_ = type_.type\n\n # get main type from Optional[type]\n _args = get_args(type_)\n if (\n get_origin(type_) is Union\n and len(_args) == 2\n and isinstance(None, _args[1])\n ):\n type_ = _args[0]\n if not inspect.isclass(type_):\n if not getattr(type_, \"__module__\", None) in [\n \"typing\",\n \"typing_extensions\",\n ]:\n warnings.warn(f\"Bug in type recognition {type_}\")\n return\n if issubclass(type_, np.ndarray):\n return np.array_equal\n if issubclass(type_, da.core.Array):\n return operator.is_\n return None\n\n\ndef add_events_to_class(cls: Type[C]) -> Type[C]:\n \"\"\"Return a new __post_init__ method wrapper with events.\n\n Parameters\n ----------\n cls : type\n The class being decorated as a dataclass\n\n Returns\n -------\n Callable[..., None]\n A modified __post_init__ method that wraps the original.\n \"\"\"\n\n # get a handle to the original __post_init__ method if present\n orig_post_init: Callable[..., None] = getattr(cls, '__post_init__', None)\n\n _fields = [\n _dc._get_field(cls, name, type_)\n for name, type_ in cls.__dict__.get('__annotations__', {}).items()\n ]\n e_fields = {\n fld.name: None\n for fld in _fields\n if fld._field_type is _dc._FIELD and fld.metadata.get(\"events\", True)\n }\n\n # create dict with compare functions for fields which cannot be compared\n # using standard equal operator, like numpy arrays.\n # it will be set to __equality_checks__ class parameter.\n compare_dict_base = getattr(cls, \"__equality_checks__\", {})\n compare_dict = {\n n: t\n for n, t in {\n name: _type_to_compare(type_)\n for name, type_ in cls.__dict__.get('__annotations__', {}).items()\n if name not in compare_dict_base\n }.items()\n if t is not None # walrus operator is supported from python 3.8\n }\n # use compare functions provided by class creator.\n compare_dict.update(compare_dict_base)\n\n def evented_post_init(self: T, *initvars) -> None:\n # create an EmitterGroup with an EventEmitter for each field\n # in the dataclass, skip those with metadata={'events' = False}\n if hasattr(self, 'events') and isinstance(self.events, EmitterGroup):\n for em in self.events.emitters:\n e_fields.pop(em, None)\n self.events.add(**e_fields)\n else:\n self.events = EmitterGroup(\n source=self,\n auto_connect=False,\n **e_fields,\n )\n # call original __post_init__\n if orig_post_init is not None:\n orig_post_init(self, *initvars)\n\n # modify __setattr__ with version that emits an event when setting\n setattr(cls, '__setattr__', set_with_events)\n setattr(cls, '__post_init__', evented_post_init)\n setattr(cls, '__equality_checks__', compare_dict)\n return cls\n\n\n# make the actual getter/setter functions that the property will use\n@tz.curry\ndef prop_getter(priv_name: str, fcoerce: Callable, obj) -> Any:\n # val = object.__getattribute__(obj, name)\n value = fcoerce(getattr(obj, priv_name))\n pub_name = priv_name.lstrip(\"_\")\n getter_method = getattr(obj, ON_GET.format(name=pub_name), None)\n if callable(getter_method):\n return getter_method(value)\n return value\n\n\n@tz.curry\ndef prop_setter(\n priv_name: str, default: Any, fcoerce: Callable, obj, value\n) -> None:\n # during __init__, the dataclass will try to set the instance\n # attribute to the property itself! So we intervene and set it\n # to the default value from the dataclass declaration\n pub_name = priv_name.lstrip(\"_\")\n if type(value) is property:\n value = default\n # dataclasses may define attributes as field(...)\n # so we need to get the default value from the field\n if isinstance(default, _dc.Field):\n default = cast(_dc.Field, default)\n # there will only ever be default_factory OR default\n # otherwise an exception will have been raised earlier.\n if default.default_factory is not _dc.MISSING:\n value = default.default_factory()\n elif default.default is not _dc.MISSING:\n value = default.default\n # If the value is still missing, then it means that the user\n # failed to provide a required positional argument when\n # instantiating the dataclass.\n if value is _dc.MISSING:\n raise TypeError(\n \"__init__() missing required \"\n f\"positional argument: '{pub_name}'\"\n )\n setattr(obj, priv_name, fcoerce(value))\n\n\nclass TypeGetSet(NamedTuple):\n '''A simple named tuple with a type, getter func, and setter func.'''\n\n type: Type[T]\n fget: Callable[[T], Any]\n fset: Callable[[Any], T]\n\n\n@tz.curry\ndef _try_coerce(func, name, value):\n if func is not None:\n try:\n return func(value)\n except Exception as e:\n raise TypeError(f\"Failed to coerce value {value} in {name}: {e}\")\n return value\n\n\ndef parse_annotated_types(\n cls: Type,\n) -> Dict[str, TypeGetSet]:\n \"\"\"Return a dict of field names and their types.\n\n If any type annotations are instances of ``Property``, then their\n paramereters will be used to create type-coercion functions that will be\n called during getting/setting of this field.\n\n Parameters\n ----------\n cls : Type\n The class being processed as a dataclass\n\n Returns\n -------\n dict\n A dict of field names to ``TypeGetSet`` objects\n \"\"\"\n out: Dict[str, TypeGetSet] = {}\n for name, typ in get_type_hints(cls, include_extras=True).items():\n d = [typ, None, None]\n if get_origin(typ) is Annotated:\n args = get_args(typ)\n d[: len(args)] = args\n d[1] = _try_coerce(d[1], name)\n d[2] = _try_coerce(d[2], name)\n out[name] = TypeGetSet(*d)\n return out\n\n\ndef convert_fields_to_properties(cls: Type[C]) -> Type[C]:\n \"\"\"Convert all fields in a dataclass instance to property descriptors.\n\n Note: this modifies class Type[C] (the class that was decorated with\n ``@dataclass``) *after* instantiation of the class. In other words, for a\n given field `f` on class `C`, `C.f` will *not* be a property descriptor\n until *after* C has been instantiated: `c = C()`. (And reminder: property\n descriptors are class attributes).\n\n The reason for this is that dataclasses can have \"default factory\"\n functions that create default values for fields only during instantiation,\n and we don't want to have to recreate that logic here, (but we do need to\n know what the value of the field is).\n\n Parameters\n ----------\n obj : T\n An instance of class ``Type[C]`` that has been deorated as a dataclass.\n \"\"\"\n from numpydoc.docscrape import ClassDoc\n\n # grab docstring to populate properties docs\n cls_doc = ClassDoc(cls)\n params = {p.name: p for p in cls_doc[\"Parameters\"]}\n\n coerce_funcs = parse_annotated_types(cls)\n # loop through annotated members of the glass\n for name, type_ in list(cls.__dict__.get('__annotations__', {}).items()):\n # ClassVar and InitVar types are exempt from dataclasses and properties\n # https://docs.python.org/3/library/dataclasses.html#class-variables\n if _is_classvar(type_) or _is_initvar(type_):\n continue\n private_name = f\"_{name}\"\n # store the original value for the property\n default = getattr(cls, name, _dc.MISSING)\n\n # add the private_name as a ClassVar annotation on the original class\n # (annotations of type ClassVar are ignored by the dataclass)\n # `self.x` is the property, `self._x` contains the data\n cls.__annotations__[private_name] = ClassVar[type_]\n\n if name in coerce_funcs:\n fget = prop_getter(private_name, coerce_funcs[name].fget)\n fset = prop_setter(private_name, default, coerce_funcs[name].fset)\n else:\n fget = _try_coerce(None, name)\n fset = _try_coerce(None, name)\n # bring the docstring from the class to the property\n doc = None\n if name in params:\n param = params[name]\n doc = \"\\n\".join(param.desc)\n # TODO: could compare param.type to field.type here for consistency\n # alternatively, we may just want to use pydantic for type\n # validation.\n\n # create the actual property descriptor\n prop = property(fget=fget, fset=fset, fdel=None, doc=doc)\n setattr(cls, name, prop)\n return cls\n\n\ndef update_from_dict(self, values, compare_fun=is_equal):\n if isinstance(values, self.__class__):\n values = values.asdict()\n if not isinstance(values, dict):\n raise ValueError(f\"Unsupported update from {type(values)}\")\n if all(compare_fun(values[k], v) for k, v in self.asdict().items()):\n return\n\n if isinstance(self, SupportsEvents):\n with self.events.blocker():\n for key, value in values.items():\n setattr(self, key, value)\n self.events(Event(self))\n else:\n for key, value in values.items():\n setattr(self, key, value)\n\n\n@tz.curry\ndef evented_dataclass(\n cls: Type[C],\n *,\n init: bool = True,\n repr: bool = True,\n eq: bool = True,\n order: bool = False,\n unsafe_hash: bool = False,\n frozen: bool = False,\n events: bool = True,\n properties: bool = True,\n) -> Type[C]:\n \"\"\"Enhanced dataclass decorator with events and property descriptors.\n\n Examines PEP 526 __annotations__ to determine fields. Fields are defined\n as class attributes with a type annotation. Everything but ``events`` and\n ``properties`` are defined on the builtin dataclass decorator.\n\n Note: if ``events==False`` and ``properties==False``, this is functionally\n equivalent to the builtin ``dataclasses.dataclass``\n\n Parameters\n ----------\n cls : Type[C]\n [description]\n init : bool, optional\n If true, an __init__() method is added to the class, by default True\n repr : bool, optional\n If true, a __repr__() method is added, by default True\n eq : bool, optional\n [description], by default True\n order : bool, optional\n If true, rich comparison dunder methods are added, by default False\n unsafe_hash : bool, optional\n If true, a __hash__() method function is added, by default False\n frozen : bool, optional\n If true, fields may not be assigned to after instance creation, by\n default False\n events : bool, optional\n If true, an ``EmmitterGroup`` instance is added as attribute \"events\".\n Events will be emitted each time one of the dataclass fields are\n altered, by default True\n properties : bool, optional\n If true, field attributes will be converted to property descriptors.\n If the class has a class docstring in numpydocs format, docs for each\n property will be taken from the ``Parameters`` section for the\n corresponding parameter, by default True\n\n Returns\n -------\n decorated class\n Returns the same class as was passed in, with dunder methods\n added based on the fields defined in the class.\n\n Raises\n ------\n ValueError\n If both ``properties`` and ``frozen`` are True\n \"\"\"\n\n if frozen and (events or properties):\n raise ValueError(\n \"`frozen=True` is incompatible `properties=True` or `events=True`\"\n )\n\n # TODO: currently, events must be process first here, otherwise\n # metada={'events':False} does not work... but that should be fixed.\n if events:\n # create a modified __post_init__ method that creates an EmitterGroup\n cls = add_events_to_class(cls)\n\n # if neither events or properties are True, this function is exactly like\n # the builtin `dataclasses.dataclass`\n with stripped_annotated_types(cls):\n cls = _dc.dataclass( # type: ignore\n cls,\n init=init,\n repr=repr,\n eq=eq,\n order=order,\n unsafe_hash=unsafe_hash,\n frozen=frozen,\n )\n\n if properties:\n # convert public dataclass fields to properties\n cls = convert_fields_to_properties(cls)\n setattr(cls, 'asdict', _dc.asdict)\n setattr(cls, 'update', update_from_dict)\n return cls\n","sub_path":"napari/utils/events/dataclass.py","file_name":"dataclass.py","file_ext":"py","file_size_in_byte":20642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"295730998","text":"# encoding: utf-8\nimport datetime\nfrom south.db import db\nfrom south.v2 import DataMigration\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\n\nclass Migration(DataMigration):\n\n def forwards(self, orm):\n \n for category in orm.Category.objects.all():\n category.slug = slugify(category.name)\n category.save()\n\n def backwards(self, orm):\n raise RuntimeError(\"Cannot de-slugify categories in this migration.\")\n\n\n models = {\n 'categories.category': {\n 'Meta': {'object_name': 'Category'},\n 'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),\n 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '256'}),\n 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})\n }\n }\n\n complete_apps = ['categories']\n","sub_path":"tags/epic/2011-07-12_keep-all-backups/categories/migrations/0007_slugifying_categories.py","file_name":"0007_slugifying_categories.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"272740081","text":"import sys\nx=int(sys.argv[1])\n\nif x <= 0:\n print(False)\nelse:\n prime=True\n for i in range(1, x):\n if (x / i) % 1 == 0 and x != i and i != 1:\n prime=False\n print(\"False\")\n break\n if prime:\n print(\"True\")","sub_path":"IsPrime/isPrimeCmd.py","file_name":"isPrimeCmd.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"169575891","text":"import unittest\nimport neomodel\nfrom app.config import TestConfig\nfrom app.models import Airport, FlightRoute\nfrom app.queries import FlightConnectionsQuery, RouteNotFound\n\nclass TestShortestPathQuery(unittest.TestCase):\n def setUp(self):\n neomodel.config.DATABASE_URL = TestConfig.DATABASE_URL\n\n def test_simple_case(self):\n query = FlightConnectionsQuery('AKL', 'GRU')\n res = query.perform()\n self.assertEqual(len(res), 3)\n self.assertEqual(res[0].route.departs_from, 'AKL')\n self.assertEqual(res[-1].route.arrives_to, 'GRU')\n\n def test_cypher_result(self):\n query = FlightConnectionsQuery('AKL', 'GRU')\n res, meta = query._execute()\n\n last_code = 'AKL'\n for i in res[0][0]:\n self.assertEqual(i.start_node['code'], last_code)\n last_code = i.end_node['code']\n\n def test_invalid_route(self):\n query = FlightConnectionsQuery('DUH', 'GRU')\n with self.assertRaises(RouteNotFound):\n res = query.perform()\n\n","sub_path":"tests/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"143262441","text":"import numpy as np\nfrom .metrics import r2_score\n\nclass LinearRegression:\n def __init__(self):\n \"\"\"初始化多元线性回归\"\"\"\n # 系数\n self.coef_ = None\n # 截距\n self.interception_ = None\n self._theta = None\n\n def fit_normal(self, X_train, y_train):\n # 使用正规方程解的计算方式\n assert X_train.shape[0] == y_train.shape[0], \"样本数量必须一致\"\n X_b = np.hstack([np.ones((len(X_train), 1), dtype=\"float\"), X_train])\n self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)\n self._updateCoefAndInterception()\n return self\n\n def fit_normal_pesudo_inv(self, X_train, y_train):\n # 使用正规方程解的计算方式 看看伪逆矩阵计算应该是一致的\n assert X_train.shape[0] == y_train.shape[0], \"样本数量必须一致\"\n X_b = np.hstack([np.ones((len(X_train), 1), dtype=\"float\"), X_train])\n self._theta = np.linalg.pinv(X_b).dot(y_train)\n self._updateCoefAndInterception()\n return self\n\n def _updateCoefAndInterception(self):\n self.interception_ = self._theta[0]\n self.coef_ = self._theta[1:]\n\n def fit_gd(self, X_train, y_train, eta = 0.01, n_iters=1e4):\n \"\"\"采用梯度下降来训练线性回归模型\"\"\"\n assert X_train.shape[0] == y_train.shape[0]\n # 此时X_train 并不包含截距\n # X_b 包含解决 theta 包含截距\n def J(theta, X_b, y):\n # 计算损失函数 这里采用的是平方错误 也就是实际值 - 预测值 然后在平方\n try:\n return np.sum((y - X_b.dot(theta)) ** 2) / len(y)\n except:\n return float('inf')\n\n def dJ(theta, X_b, y):\n # 计算偏导数 也就是梯度\n # 方法1: 直接根据定义计算\n # res = np.empty(len(theta))\n # # 截距b的偏导数\n # res[0] = np.sum(X_b.dot(theta) - y)\n #\n # # 对其他特征一个个计算 参考公式\n # for i in range(1, len(theta)):\n # res[i] = np.sum((X_b.dot(theta) - y).dot(X_b[:, i])) / len(y_train)\n # return res\n\n # 方法2 直接向量化计算\n return X_b.T.dot(X_b.dot(theta) - y) * 2. / len(X_b)\n\n\n def gd(X_b, y, initial_theta, eta, epsilon = 1e-8, n_iterations=1e4):\n n_iters = 0\n theta = initial_theta\n while n_iters < n_iterations:\n gradient = dJ(theta, X_b, y)\n lastTheta = theta\n # 每一次迭代 向梯度的相反方向更新theta\n theta = theta - eta * gradient\n # 是否达到额定的误差\n if abs(J(lastTheta, X_b, y) - J(theta, X_b, y)) < epsilon:\n break\n n_iters += 1\n return theta\n\n # 添加一个截距列 方便后面计算\n # X_train 是 m * n 比如 [\n # [1, 2, 3]\n # [4, 5, 6]\n # ]\n # X_b 是 m * (n + 1)\n # [\n # [1, 1, 2, 3]\n # [1, 4, 5, 6]\n # ]\n\n X_b = np.hstack((np.ones((len(X_train), 1)), X_train))\n y = y_train\n\n initial_theta = np.zeros(X_b.shape[1])\n self._theta = gd(X_b, y, initial_theta, eta, n_iterations= n_iters)\n #print(\"theta calculated\", self._theta)\n self._updateCoefAndInterception()\n return self\n\n\n # SGD\n # a, b 用来计算eta 的值 随着迭代次数越来越小\n def fit_sgd(self, X_train, y_train, n_iters=5, a=5, b = 50):\n assert len(X_train) == len(y_train)\n assert n_iters >= 1\n\n def dJ_sgd(theta, X_b_i, y_i):\n # X_b_i 代表第i个样本 y_i 代表数据值\n return X_b_i.T.dot(X_b_i.dot(theta) - y_i) * 2.\n\n def sgd(X_b, y, initial_theta, n_iters, a, b):\n a = 5\n b = 50\n\n def learning_rate(iter):\n return a / (b + iter)\n\n # 因为我们是随机梯度下降 所以一般的话 我们至少要保证每个都看一遍\n # 所以在sgd 中n_iters 一般表示所有数据最多看多少遍\n\n # 现在是随机选一个点 可能这2个点隔的很近 所以epsilon 已经没有意义了\n m = len(X_b)\n theta = initial_theta\n for cur_iter in range(n_iters):\n # 为了保证每个都看过 所以我们打乱这个原来的X_b\n indexes = np.random.permutation(m)\n X_b_new = X_b[indexes]\n y_new = y[indexes]\n for i in range(m):\n gradient = dJ_sgd(theta, X_b_new[i], y_new[i])\n theta = theta - learning_rate(cur_iter * m + i) * gradient\n return theta\n\n X_b = np.hstack((np.ones((len(X_train), 1)), X_train))\n initial_theta = np.zeros(X_b.shape[1])\n # 这里只是举例取1/3的数据\n self._theta = sgd(X_b, y_train, initial_theta, n_iters, a, b)\n self._updateCoefAndInterception()\n # SGD\n\n\n\n def predict(self, X_predict):\n assert self.coef_ is not None\n assert X_predict.shape[1] == len(self.coef_)\n X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])\n return X_b.dot(self._theta)\n\n def score(self, X_test, y_test):\n y_predict = self.predict(X_test)\n return r2_score(y_test, y_predict)\n\n def __repr__(self):\n return \"LinearRegression()\"","sub_path":"Python3玩转机器学习/07_PCA与梯度上升/playML/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":5536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"194520702","text":"from random import randint\r\nfrom c10 import cbc_decrypt, cbc_encrypt, ecb_decrypt, ecb_encrypt, xor\r\nimport base64\r\nfrom Crypto.Cipher import AES\r\n\r\n\r\ndef rand_key():\r\n key = b\"\"\r\n for i in range(16):\r\n key += bytes([randint(0, 255)])\r\n return key\r\n\r\n\r\ndef aes_encrypt(text):\r\n text = bytes([0x00] * randint(5, 10)) + text + bytes([0x00] * randint(5, 10))\r\n key = rand_key()\r\n cipher_txt = b\"\"\r\n if randint(1, 2) == 1:\r\n print(\"ECB\")\r\n blocks = [text[i : i + 16] for i in range(0, len(text), 16)]\r\n for block in blocks:\r\n cipher_txt += ecb_encrypt(block, key)\r\n else:\r\n print(\"CBC\")\r\n cipher_txt = cbc_encrypt(text, bytes([0x00] * 16), key)\r\n # print(cipher_txt)\r\n return cipher_txt\r\n\r\n\r\ndef detect_cipher(encrypted):\r\n chunks = [encrypted[i : i + 16] for i in range(0, len(encrypted), 16)]\r\n reps = len(chunks) - len(set(chunks))\r\n if reps > 0:\r\n return \"ECB\"\r\n else:\r\n return \"CBC\"\r\n\r\n\r\nif __name__ == \"__main__\":\r\n with open(\"10.txt\") as f:\r\n encrypted = base64.b64decode(\"\".join([line.strip() for line in f.readlines()]))\r\n decrypted = cbc_decrypt(encrypted, bytes([0x00] * 16), \"YELLOW SUBMARINE\")\r\n # print(decrypted)\r\n encrypted = aes_encrypt(decrypted)\r\n print(detect_cipher(encrypted))\r\n # print(aes_encrypt(decrypted))\r\n # print(rand_key())\r\n","sub_path":"c11.py","file_name":"c11.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"385936964","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport csv\nfrom collections import defaultdict\nimport logging\nlogging.basicConfig(level=logging.WARNING, format='=====================>%(asctime)s %(lineno)-6d: %(message)s')\n\ncsv_file = open('../temp/USnewsRanking.csv', 'w', newline='')\nwriter = csv.writer(csv_file)\n\n#read CSV for N number of people's interests by university\ncsv_interests = open('../temp/interests.csv.txt', 'r')\nreader = csv.reader(csv_interests, delimiter=',')\nline_count = 0\nintDict = defaultdict(list)\nintPeople = []\ndefaultInt = 'N'\nnumberPeople = 0\nfor row in reader:\n if line_count == 0:\n row.pop(0)\n intPeople = row\n intPeople.append('Any Interest?')\n line_count += 1\n else:\n if len(row) == 0:\n print (\"Interest File Input should be CSV file with university name as the first colummn, person interests expressed as Y or N in subsequent columns\" )\n exit()\n college = row.pop(0)\n intDict[college]= row \n if 'Y' in row:\n intDict[college].append('Y')\n else:\n intDict[college].append('N')\n numberPeople = len( row )\n logging.warning(row)\n\n \nurls = ['https://www.usnews.com/best-colleges/rankings/national-universities?_mode=table',\\\n 'https://www.usnews.com/best-colleges/rankings/national-universities?_page=2&_mode=table',\n 'https://www.usnews.com/best-colleges/rankings/national-universities?_page=3&_mode=table',\n 'https://www.usnews.com/best-colleges/rankings/national-universities?_page=4&_mode=table',\n 'https://www.usnews.com/best-colleges/rankings/national-universities?_page=5&_mode=table',\n 'https://www.usnews.com/best-colleges/rankings/national-universities?_page=6&_mode=table']\n\nrankingUrls = { 'Engineering' : 'https://www.usnews.com/best-colleges/rankings/engineering-doctorate', \\\n 'BioMed' : 'https://www.usnews.com/best-colleges/rankings/engineering-doctorate-biological-biomedical', \\\n 'Computer' : 'https://www.usnews.com/best-colleges/rankings/engineering-doctorate-computer', \\\n 'DoubleE' : 'https://www.usnews.com/best-colleges/rankings/engineering-doctorate-electrical-electronic-communications', \\\n 'BusRank' : 'https://www.usnews.com/best-colleges/rankings/business-overall', \\\n 'BusAcct' : 'https://www.usnews.com/best-colleges/rankings/business-accounting', \\\n 'BusEnt' : 'https://www.usnews.com/best-colleges/rankings/business-entrepreneurship',\\\n 'BusFin' : 'https://www.usnews.com/best-colleges/rankings/business-finance', \\\n 'BusMgmt' : 'https://www.usnews.com/best-colleges/rankings/business-management',\\\n 'BusMarketing' : 'https://www.usnews.com/best-colleges/rankings/business-marketing',\\\n 'BusOps' : 'https://www.usnews.com/best-colleges/rankings/business-production-operations-management',\\\n 'BusQuant' : 'https://www.usnews.com/best-colleges/rankings/business-quantitative-analysis',\\\n 'BusRE' : 'https://www.usnews.com/best-colleges/rankings/business-real-estate',\\\n 'BusSupply' : 'https://www.usnews.com/best-colleges/rankings/business-supply-chain-management-logistics',\n 'LiberalArts' : 'https://www.usnews.com/best-colleges/rankings/national-liberal-arts-colleges'}\n\ncolumns = ['University','Univ Rank', 'Locations', 'URLs', 'Top Majors', 'Sector', 'Founding', 'Religion', 'Calendar', 'Setting', 'Endorsement', 'Acceptance Rate', 'Tuition']\n \ndefaultRanking = 300\n\nd = defaultdict(list)\nranks1 = []\nnames = []\nlocations = []\ntuitions = []\nuurls = []\numajors = []\nusettings = []\nuacceptances = []\n\n#national rankings\nfor url in urls:\n r = requests.get(url, headers={'User-Agent':'test'})\n soup = BeautifulSoup(r.text, \"lxml\")\n for rank in soup.findAll('div', attrs={'class': 'ranklist-ranked-item RankList__Rank-s1dx9co1-2 jNcEpG'}):\n logging.warning(rank.text)\n if( \"#\" in rank.text ):\n ranks1.append(int(re.findall('\\d+', rank.text)[0]))\n logging.info( ranks1 )\n\t\n for location in soup.findAll('p', attrs={'class': 'Paragraph-fqygwe-0 fJtpNK'}):\n locations.append(str.strip(location.text))\n logging.warning(\"===locations===\")\n logging.info(locations)\n\t\t\n for college in soup.findAll('h3', attrs={'class': 'sc-bdVaJa kyuLHz'}):\n logging.warning(\"===COLLEGE===\")\n logging.info(str.strip(college.text))\n names.append(str.strip(college.text))\n for uurl in college.findAll('a', href=True):\n uurl1=\"http://colleges.usnews.rankingsandreviews.com\"+str.strip(uurl['href'])\n uurls.append(uurl1)\n logging.warning( \"===University URL===\" )\n logging.info(uurl1)\n\n#parsing each university page \n majors = []\n settings = []\n acceptances = []\n r1 = requests.get(uurl1, headers={'User-Agent':'test'})\n soup1 = BeautifulSoup(r1.text, \"lxml\")\n for major in soup1.findAll( 'span', attrs={'class': 'flex-medium text-muted'}):\n majors.append(str.strip(major.text))\n umajors.append(majors)\n for tuition in soup1.findAll( 'section', attrs={'class': 'hero-stats-widget-stats' }):\n tuitionstart = tuition.text.find('$') + 1\n if( tuition.text.find('Out-of-state') > 0 ):\n tuitionstart = tuition.text[tuition.text.find( '$' ) + 1:].find('$') + tuition.text.find( '$' ) + 2\n #tuitionend = tuition.text.find('(') - 1\n t = tuition.text[tuitionstart:tuitionstart + 6]\n logging.warning( \"===tuition section===\")\n logging.info( t )\n tuitions.append( t )\n for setting in soup1.findAll('span', attrs={'class': 'heading-small text-black text-tight block-flush display-block-for-large-up'}):\n settings.append(str.strip(setting.text))\n usettings.append(settings)\n for acceptance in soup1.findAll('span', attrs={'data-test-id': 'r_c_accept_rate'}):\n uacceptances.append(str.strip(acceptance.text))\n break\n#end parsing each university page \nlogging.warning( names )\n \nprint( \"element len\", len(ranks1), len(names), len(locations), len(uurls), len(umajors), len(usettings), len(uacceptances), len( tuitions ))\n#print( \"colleges\", names )\nd['Title'] = columns + list(rankingUrls.keys())+ intPeople\nfor i in range(len(ranks1)):\n logging.warning( i )\n logging.info( names[i] )\n if( d[names[i]] ):\n continue\n d[names[i]].append(names[i])\n d[names[i]].append(ranks1[i])\n d[names[i]].append(locations[i])\n d[names[i]].append(uurls[i])\n d[names[i]].append(umajors[i])\n d[names[i]].append(usettings[i][0])\n d[names[i]].append(usettings[i][1])\n d[names[i]].append(usettings[i][2])\n d[names[i]].append(usettings[i][3])\n d[names[i]].append(usettings[i][4])\n d[names[i]].append(usettings[i][5])\n d[names[i]].append(uacceptances[i])\n d[names[i]].append(tuitions[i])\n d[names[i]] += [defaultRanking]*len(rankingUrls)\n d[names[i]] += [defaultInt]*numberPeople\n logging.info( d['Princeton University'] )\n\n#School rankings\ndef parseRanking( rankurl ):\n er = requests.get(rankurl, headers={'User-Agent':'test'})\n souper = BeautifulSoup(er.text, \"lxml\")\n erankcolls = []\n erankings = []\n for erank in souper.findAll('h3', attrs={'class': 'heading-large block-tighter'}):\n coll=str.strip(erank.text)\n erankcolls.append(coll)\n \n for eranking in souper.findAll('div', attrs={'style': 'margin-left: 2.5rem;'}): \n if( \"#\" in eranking.text ):\n erankings.append(int(re.findall('\\d+', eranking.text)[0]))\n return( erankcolls, erankings )\n#End School Rankings\n\n\nj = 0\nfor k, rurls in rankingUrls.items():\n srankcolls, srankings = parseRanking( rurls )\n logging.warning( \"===School Rankings 1===\" )\n logging.info( srankcolls )\n logging.info( srankings )\n for i in range(len(srankings)):\n if( d[srankcolls[i]]):\n values = d[srankcolls[i]]\n values[len(columns) + j] = srankings[i]\n d[srankcolls[i]] = values\n j+=1\n\nfor collname, interests in intDict.items():\n if( d[collname]):\n values = d[collname]\n values = values[:-1*numberPeople] + interests\n d[collname] = values\n\nlogging.info(d)\nfor k,v in d.items():\n writer.writerow(v)\n","sub_path":"Usnews.py","file_name":"Usnews.py","file_ext":"py","file_size_in_byte":8681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"202736596","text":"\n# coding: utf-8\nimport os\nimport json\nimport numpy as np\nfrom models.CNNFC import AudioNet\nfrom models.ResNet import ResNet18\nfrom dataloader.huaWeiEmoLoader import huaWeiEmoDataloader\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as Data\nfrom torch.utils.tensorboard import SummaryWriter\nfrom eval import Evaluator\nfrom sklearn.metrics import accuracy_score\n# from utils import LossLogger\nwith open(\"config.json\") as json_file:\n\tconfig = json.load(json_file)\n\n\nclass Trainer():\n\n\tdef __init__(self, expName):\n\t\tif(config[\"MODEL\"] == 'CNNFC'):\n\t\t\tself.model = AudioNet()\n\t\telif(config[\"MODEL\"] == 'ResNet'):\n\t\t\tself.model = ResNet18()\n\t\tself.optimizer = optim.Adam(self.model.parameters(), lr = config[\"LR\"])\n\t\tself.criterion = nn.NLLLoss()\n\t\tself.epochNum = config[\"EPOCH_NUM\"]\n\t\tself.bestLoss = float(\"Inf\")\n\t\tself.bestAcc = 0\n\t\tself.expName = expName\n\t\tself.logPath = os.path.join(config[\"PROJECT_PATH\"][config[\"ENV\"]], 'logs', self.expName)\n\t\tif not os.path.exists(self.logPath):\n\t\t\tos.makedirs(self.logPath)\n\t\tself.writter = SummaryWriter(log_dir = os.path.join(self.logPath, 'tensorboard'))\n\t\tself.nonbetterCount = 0\n\t\tself.patience = config[\"EARLY_STOPPING_PATIENCE\"]\n\n\t\tdataload = huaWeiEmoDataloader()\n\t\tX_train, Y_train = dataload.datasetLoader('train')\n\t\ttrain_torch_dataset = Data.TensorDataset(X_train, Y_train)\n\t\tself.train_loader = Data.DataLoader(dataset = train_torch_dataset, batch_size = config[\"TRAIN_BATCH_SIZE\"], shuffle = True)\n\t\tself.X_valid, self.Y_valid = dataload.datasetLoader('valid')\n\t\tself.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\t\tself.model = self.model.to(self.device)\n\t\tself.fo = open(os.path.join(self.logPath, 'trainLog.txt'), 'w+')\n\t\tself.targetInfo = config[\"TRAGET_INFO\"]\n\t\tself.writter = SummaryWriter(log_dir = os.path.join(self.logPath, 'tensorboard'))\n\n\tdef betterSaver(self, acc_valid):\n\t\tif(acc_valid >= self.bestAcc):\n\t\t\tself.bestAcc = acc_valid\n\t\t\ttorch.save(self.model.cpu(), os.path.join(self.logPath, 'bestModel_acc.pkl'))\n\t\t\tprint('[Model Saved!!]~~~~~~~~~~~~~~~~~~\\n')\n\t\t\tself.fo.write('[Model Saved!!]~~~~~~~~~~~~~~~~~~\\n')\n\t\t\tself.nonbetterCount = 0\n\t\telse:\n\t\t\tself.nonbetterCount = self.nonbetterCount + 1\n\t\tif(self.nonbetterCount == self.patience):\n\t\t\tprint('[EARLY STOPPING!!]\\n')\n\t\t\tself.fo.write('[EARLY STOPPING!!]\\n')\n\t\t\treturn True\n\t\treturn False # continue flag\n\n\tdef lossAccWritter(self, loss, acc, stepIndex, epochIndex, phase):\n\t\t'''\n\t\tWritter for loss and acc in fo and on screen.\n\t\tInput: \n\t\t\tfo, loss, acc, stepIndex, epochIndex: info\n\t\t\tphase: writter pahse info, 'batch'/'train'\n\t\tOutput:\n\t\t\t----\n\t\t'''\n\t\tif(phase.lower() == 'train'):\n\t\t\tprint('[Train] ')\n\t\t\tself.fo.write('[Train] ')\n\t\tprint('{}/{}: loss: {:.3f}, acc: {:.3f}'.format(stepIndex, epochIndex, loss, acc))\n\t\tself.fo.write('{}/{}: loss: {:.3f}, acc: {:.3f}\\n'.format(stepIndex, epochIndex, loss, acc))\n\n\tdef one_pass_train(self, epochIndex):\n\t\tepoch_loss = 0\n\t\tepoch_acc = 0\n\t\tself.model.train()\n\t\tself.model = self.model.to(self.device)\n\t\tfor step, (batch_x, batch_y) in enumerate(self.train_loader):\n\t\t\tself.model.zero_grad()\n\t\t\tbatch_x, batch_y = batch_x.to(self.device), batch_y.to(self.device)\n\t\t\toutput_batch = self.model(batch_x)\n\t\t\t# \t\tX = torch.cat(X, axis=0)\n\t\t\t# torch.cat((x, x, x), 1)\n\t\t\tloss = self.criterion(output_batch, batch_y)\n\t\t\tloss.backward()\n\t\t\tself.optimizer.step()\n\t\t\tacc = accuracy_score(torch.argmax(output_batch, dim=1).cpu(), batch_y.cpu())\n\t\t\tepoch_loss += loss.item() * batch_x.shape[0]\n\t\t\tepoch_acc += acc * batch_x.shape[0]\n\t\t\tif(step % (len(self.train_loader) // 6) == 0):\n\t\t\t\tself.lossAccWritter(loss.item(), acc, step, epochIndex, 'batch')\n\t\t\t\tself.writter.add_scalar('Loss/batch', loss.item(), epochIndex*len(self.train_loader)+step)\n\t\t\t\tself.writter.add_scalar('Acc/batch', acc, epochIndex*len(self.train_loader)+step)\n\t\ttorch.save(self.model.cpu(), os.path.join(self.logPath, 'lastModel.pkl'))\n\t\treturn epoch_loss / len(self.train_loader.dataset), epoch_acc / len(self.train_loader.dataset)\n\n\tdef train(self):\n\t\tvalid_evaluator = Evaluator('valid')\n\t\tfor epochIndex in range(self.epochNum):\n\t\t\tloss_train, acc_train = self.one_pass_train(epochIndex)\n\t\t\tself.lossAccWritter(loss_train, acc_train, '--', epochIndex, 'train')\n\t\t\tloss_valid, acc_valid = valid_evaluator.evaluation(self.X_valid, self.Y_valid, self.model, self.fo)\n\t\t\tself.writter.add_scalars('Loss/epoch', {'train': loss_train, \n\t\t\t\t\t\t\t\t\t\t\t\t\t'valid': loss_valid.item()}, epochIndex)\n\t\t\tself.writter.add_scalars('Acc/epoch', {'train': acc_train, \n\t\t\t\t\t\t\t\t\t\t\t\t\t'valid': acc_valid}, epochIndex)\n\t\t\tself.writter.flush()\n\t\t\tif(self.betterSaver(acc_valid) == True):\n\t\t\t\tbreak\n\n\tdef __del__(self):\n\t\tself.writter.close()\n\t\tself.fo.close()\n\n\nif __name__ == '__main__':\n\ttrainer = Trainer(\"0107_FC_FC\")\n\ttrainer.train()","sub_path":"project_CNNFC_Atten_Cls/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"313098800","text":"# Copyright (c) 2021, Galois, Inc.\n#\n# All Rights Reserved\n#\n# This material is based upon work supported by the Defense Advanced Research\n# Projects Agency (DARPA) under Contract No. FA8750-20-C-0203.\n#\n# Any opinions, findings and conclusions or recommendations expressed in this\n# material are those of the author(s) and do not necessarily reflect the views\n# of the Defense Advanced Research Projects Agency (DARPA).\n\nfrom migration_helpers.name_space import rack\nfrom ontology_changes import AddClass, Commit, DeleteProperty\n\nMODEL = rack(\"MODEL\")\nREQUIREMENTS = rack(\"REQUIREMENTS\")\n\ncommit = Commit(\n number=\"b25d07626e4693cd370a2070e17f6baa825a1d43\",\n changes=[\n # MODEL.sadl\n AddClass(\n name_space=MODEL,\n class_id=\"MODEL\",\n ),\n # REQUIREMENTS.sadl\n DeleteProperty(name_space=REQUIREMENTS, property_id=\"givenText\"),\n DeleteProperty(name_space=REQUIREMENTS, property_id=\"ifText\"),\n DeleteProperty(name_space=REQUIREMENTS, property_id=\"thenText\"),\n ],\n)\n","sub_path":"migration/rack/commits/commitb25d07626e4693cd370a2070e17f6baa825a1d43.py","file_name":"commitb25d07626e4693cd370a2070e17f6baa825a1d43.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"345931682","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nimport sys\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport scipy.io as scio \r\nfrom pathlib import Path\r\nimport random\r\n\r\nerror = scio.loadmat('cdf_data.mat')\r\nerror = np.squeeze(error[\"error\"])\r\nerror_phone = scio.loadmat('cdf_phonetest.mat')\r\nerror_phone = np.squeeze(error_phone[\"error\"])\r\nerror_phone_2 = scio.loadmat('cdf_phone_2.mat')\r\nerror_phone_2 = np.squeeze(error_phone_2[\"error\"])\r\n\r\ndataset = error\r\ndata_size=len(dataset)\r\n# Set bins edges\r\ndata_set=sorted(set(dataset))\r\nbins=np.append(data_set, data_set[-1]+1)\r\n# Use the histogram function to bin the data\r\ncounts, bin_edges = np.histogram(dataset, bins=bins, density=False)\r\ncounts=counts.astype(float)/data_size\r\n# Find the cdf\r\ncdf = np.cumsum(counts)\r\n\r\ndataset_phone = error_phone\r\ndata_size_phone=len(dataset_phone)\r\n# Set bins edges\r\ndata_set_phone=sorted(set(dataset_phone))\r\nbins_phone=np.append(data_set_phone, data_set_phone[-1]+1)\r\n# Use the histogram function to bin the data\r\ncounts_phone, bin_edges_phone = np.histogram(dataset_phone, bins=bins_phone, density=False)\r\ncounts_phone=counts_phone.astype(float)/data_size_phone\r\n# Find the cdf\r\ncdf_phone = np.cumsum(counts_phone)\r\n\r\ndataset_phone_2 = error_phone_2\r\ndata_size_phone_2=len(dataset_phone_2)\r\n# Set bins edges\r\ndata_set_phone_2=sorted(set(dataset_phone_2))\r\nbins_phone_2=np.append(data_set_phone_2, data_set_phone_2[-1]+1)\r\n# Use the histogram function to bin the data\r\ncounts_phone_2, bin_edges_phone_2 = np.histogram(dataset_phone_2, bins=bins_phone_2, density=False)\r\ncounts_phone_2=counts_phone_2.astype(float)/data_size_phone_2\r\n# Find the cdf\r\ncdf_phone_2 = np.cumsum(counts_phone_2)\r\n\r\nplt.figure(1)\r\nfontSize=22\r\n#改变X与Y轴上的字体的大小\r\nax=plt.gca()\r\nfor label in ax.xaxis.get_ticklabels():\r\n label.set_fontsize(fontSize)\r\nfor label in ax.yaxis.get_ticklabels():\r\n label.set_fontsize(fontSize)\r\n \r\n#给X与Y轴加标住\r\nplt.rcParams.update({'font.size': fontSize})\r\nplt.xlabel('Measurement error in centigrade', size=fontSize)\r\nplt.ylabel('CDF', size=fontSize)\r\n\r\n# Plot the cdf\r\nplt.plot(bin_edges[0:-1], cdf,linestyle=':', marker=\"o\", color='b',linewidth=5,label=u'Pi')\r\nplt.plot(bin_edges_phone[0:-1], cdf_phone,linestyle='--', marker=\"o\", color='r',linewidth=5,label=u'Phone w/o filter')\r\nplt.plot(bin_edges_phone_2[0:-1], cdf_phone_2,linestyle='-.', marker=\"o\", color='g',linewidth=5,label=u'Phone w filter')\r\nplt.ylim((0,1))\r\nplt.ylabel(\"CDF\")\r\nplt.grid(True)\r\n\r\n#改变legend的字体与位置\r\nplt.legend(loc='lower right',prop={'size':fontSize})\r\nplt.show() \r\n\r\n","sub_path":"pyplot/cdf_plot.py","file_name":"cdf_plot.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"97099248","text":"'''\r\n@author Daniel J. Rivers\r\n2013\r\n\r\nCreated: Apr 12, 2013, 1:06:17 PM \r\n'''\r\nimport os\r\nfrom Utils import FileUtils\r\nfrom Utils.FileUtils import File\r\nfrom Utils.LogUtils import Log\r\nfrom Utils import LogUtils\r\nfrom tkinter import BooleanVar, StringVar, IntVar\r\n\r\nimport subprocess\r\nimport time\r\n\r\ndef simpleProcess( props ):\r\n props.FINAL_INPUT = props.INPUT_PATH.get() + ( \"/\" + props.FILE_PREFIX.get() if props.USE_FILE.get() else \"\" )\r\n props.FINAL_OUTPUT = props.OUTPUT_PATH.get() + ( \"/\" + props.FILE_PREFIX.get() if props.USE_FILE.get() else \"\" )\r\n props.EPISODE_COUNTER = 0\r\n startFile = None if props.PARTIAL_FILE.get() == \"\\\"\\\"\" or props.PARTIAL_FILE.get() == \"\" else props.PARTIAL_FILE.get()\r\n singleDone = False\r\n directory = File.pathFull( props.FINAL_INPUT )\r\n Log.info( \"Converting show directory: \" + directory.absPath + \"\\n\" )\r\n sub = FileUtils.getSubDir( directory )\r\n seasonNumber = props.STARTING_SEASON.get() - 1\r\n\r\n #For all subdirectories (non recursive) in the given main directory...\r\n while ( seasonNumber < len( sub ) or props.SINGLE_SEASON.get() ) and seasonNumber < props.ENDING_SEASON.get():\r\n seasonDirectory = sub[ 0 ] if props.SINGLE_SEASON.get() else sub[ seasonNumber ]\r\n Log.info( \"Searching in Sub-Directory: \" + seasonDirectory.name )\r\n destDir = File.pathParts( props.FINAL_OUTPUT, seasonDirectory.name )\r\n props.EPISODE_COUNTER = props.PARTIAL_EPISODE.get()\r\n for isoFile in FileUtils.getFilesOfType( seasonDirectory, \".iso\" ):\r\n Log.info( \"Analyzing File: \" + isoFile.name + \"\\n\" )\r\n if startFile == None or isoFile.name == startFile:\r\n startFile = None\r\n if ( not props.PARTIAL_SINGLEFILE.get() ) or ( props.PARTIAL_SINGLEFILE.get() and not singleDone ):\r\n\r\n #Info Process\r\n proc = subprocess.Popen( props.MAKEMKV_PATH.get() + \" info iso:\\\"\" + isoFile.absPath + \"\\\"\", stdout = subprocess.PIPE, shell = False )\r\n lines = []\r\n while True:\r\n line = proc.stdout.readline().decode( 'utf-8' )\r\n if not line:\r\n Log.info( \"\\n\\n\" )\r\n break\r\n else:\r\n #If it's a title line...\r\n if ( \"Title #\" in line ) and not \"skipped\" in line:\r\n line = line.strip()\r\n Log.info( line.strip() )\r\n lines.append( line )\r\n\r\n for line in lines:\r\n trackNumber = int( line[ line.rfind( \"#\" ) + 1:line.rfind( \"w\" ) - 1 ] ) + 1\r\n t = line[ line.rfind( \", \" ) + 1:line.rfind( \":\" ) ]\r\n hours = int( t[ 1:t.find( \":\" ) ] )\r\n minutes = int( t[ t.find( \":\" ) + 1: ] )\r\n\r\n #If it's longer than the minimum t allowed go ahead and process it\r\n if ( minutes >= props.MIN_TIME.get() or hours > 0 ) and minutes < props.MAX_TIME.get():\r\n\r\n Log.info( \"++++++++++ Processing Episode File \" + str( trackNumber ) + \" ++++++++++\" )\r\n\r\n #Make Season directory if needed\r\n if not os.path.exists( destDir.absPath ):\r\n os.makedirs( destDir.absPath )\r\n\r\n Log.info( \"VOB EXTRACTING:\" )\r\n\r\n #DVDFab8 Extraction process\r\n Log.info( \"Extracting: \" + str( trackNumber ) + \" from \" + isoFile.absPath + \" to \" + destDir.absPath + \"\\n\\n\" )\r\n LogUtils.logProcessOutput( subprocess.Popen( props.DVDFAB_PATH.get() + \"/MODE \\\"DVDVOB\\\" /SRC \\\"\" + isoFile.absPath + \"\\\"\" + \" \" + \"/DEST \\\"\" + destDir.absPath + \"\\\\\" + \"\\\"\" + \" \" + \"/PROFILE \\\"vob.passthrough\\\"\" + \" \" + \"/TITLE \" + \"\\\"\" + str( trackNumber ) + \"\\\"\" + \" \" + \"/CLOSE\", stdout = subprocess.PIPE, shell = True ), None )\r\n\r\n #Sleep for 3 sec to allow file locks to release... was a problem at one point\r\n time.sleep( 3 )\r\n\r\n #File Renaming based on season/episode\r\n Log.info( \"RENAMING:\" )\r\n files = renameFiles( props, hours, isoFile, destDir, seasonNumber, trackNumber )\r\n\r\n #MKVMerge repackage to MKV process\r\n Log.info( \"MKV MERGING:\" )\r\n vobPath = files[ 0 ].absPath\r\n Log.info( \"VOB PATH: \" + vobPath )\r\n proc = subprocess.Popen( props.MKVMERGE_PATH.get() + \" -o \\\"\" + vobPath[ 0 : len( vobPath ) - 4 ] + \".mkv\\\" \\\"\" + vobPath + \"\\\"\", stdout = subprocess.PIPE, shell = True )\r\n LogUtils.logProcessOutput( proc, lambda x: ( not \"Progress\" in x and not \"mkvmerge\" in x ) )\r\n\r\n Log.info( \"\\n\\n\" )\r\n\r\n #Move source files to subdirectory\r\n Log.info( \"MOVING SOURCE FILES:\" )\r\n FileUtils.moveFiles( File.pathParts( destDir.absPath, \"SourceFiles\" ), files );\r\n Log.info( \"---------- Processing Episode File \" + str( trackNumber ) + \" ----------\\n\\n\" )\r\n Log.info( \"DISC FINISHED\" )\r\n singleDone = True\r\n seasonNumber += 1\r\n\r\ndef renameFiles( props, hours, isoFile, destDir, seasonNumber, trackNumber ):\r\n ret = []\r\n extra = \"\"\r\n if hours > 0:\r\n extra = \"e\" + addZeroes( str( props.EPISODE_COUNTER + 1 ) )\r\n ext = [ \"vob\", \"idx\", \"sub\" ]\r\n for i in range( 0, len( ext ) ):\r\n e = ext[ i ]\r\n z = File.pathParts( destDir.absPath, \"Title\" + str( trackNumber ) + \".\" + e )\r\n if os.path.exists( z.absPath ):\r\n newFileName = props.FILE_PREFIX.get() + \"_s\" + addZeroes( str( seasonNumber + 1 ) ) + \"e\" + addZeroes( str( props.EPISODE_COUNTER ) ) + extra + \".\" + e\r\n Log.info( \"Renaming: \" + z.name + \" to: \" + newFileName + \"\\n\\n\" )\r\n n = File.pathParts( destDir.absPath, newFileName )\r\n os.rename( z.absPath, n.absPath )\r\n ret.append( n )\r\n props.EPISODE_COUNTER += 2 if hours > 0 else 1\r\n return ret\r\n\r\ndef addZeroes( s ):\r\n return \"0\" + s if len( s ) < 2 else s\r\n\r\nclass Props:\r\n\r\n def __init__ ( self ):\r\n #Program Paths\r\n self.MAKEMKV_PATH = StringVar()\r\n self.MKVMERGE_PATH = StringVar()\r\n self.DVDFAB_PATH = StringVar()\r\n\r\n #Processing Paths\r\n self.INPUT_PATH = StringVar()\r\n self.OUTPUT_PATH = StringVar()\r\n\r\n #Process Run Settings\r\n self.FILE_PREFIX = StringVar()\r\n self.STARTING_SEASON = IntVar()\r\n self.ENDING_SEASON = IntVar()\r\n self.MIN_TIME = IntVar()\r\n self.MAX_TIME = IntVar()\r\n self.USE_FILE = BooleanVar()\r\n self.SINGLE_SEASON = BooleanVar()\r\n\r\n #Partial Season\r\n self.PARTIAL_FILE = StringVar()\r\n self.PARTIAL_EPISODE = IntVar()\r\n self.PARTIAL_SINGLEFILE = BooleanVar()\r\n\r\n self.FINAL_INPUT = \"\"\r\n self.FINAL_OUTPUT = \"\"\r\n\r\n self.EPISODE_COUNTER = 0\r\n\r\n self.loadProps()\r\n\r\n\r\n def loadProps( self ):\r\n p = dict()\r\n #Read properties into a map\r\n for line in open( \"MKVCreator.properties\" ):\r\n if ( not line.startswith( \"#\" ) and not line.strip() == \"\" ):\r\n l = line.strip().split( \"=\" )\r\n p[ l[ 0 ] ] = l[ 1 ]\r\n self.MAKEMKV_PATH.set( p[ \"MAKEMKV.PATH\" ] )\r\n self.MKVMERGE_PATH.set( p[ \"MKVMERGE.PATH\" ] )\r\n self.DVDFAB_PATH.set( p[ \"DVDFAB.PATH\" ] )\r\n self.INPUT_PATH.set( p[ \"INPUT.PATH\" ] )\r\n self.OUTPUT_PATH.set( p[ \"OUTPUT.PATH\" ] )\r\n\r\n# self.FILE_PREFIX.set( p[ \"FILE.PREFIX\" ] )\r\n\r\n self.STARTING_SEASON.set( int( p[\"STARTING.SEASON\"] ) )\r\n self.ENDING_SEASON.set( int( p[\"ENDING.SEASON\"] ) )\r\n\r\n self.MIN_TIME.set( int( p[ \"MIN.TIME\" ] ) )\r\n self.MAX_TIME.set( int( p[ \"MAX.TIME\" ] ) )\r\n self.USE_FILE.set( p[ \"USE.FILE\" ] == \"true\" )\r\n self.SINGLE_SEASON.set( p[ \"SINGLE.SEASON\" ] == \"true\" )\r\n\r\n# self.PARTIAL_FILE.set( p[ \"PARTIAL.FILE\" ] )\r\n self.PARTIAL_EPISODE.set( int( p[ \"PARTIAL.EPISODE\" ] ) )\r\n self.PARTIAL_SINGLEFILE.set( p[ \"PARTIAL.SINGLEFILE\" ] == \"true\" )\r\n\r\n","sub_path":"MKVRipper/Processor/Processor.py","file_name":"Processor.py","file_ext":"py","file_size_in_byte":8590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"348683383","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 14 17:12:03 2020\n\n@author: kanukuma\n\"\"\"\n\ndef popularNFeatures(numFeatures, topFeatures, possibleFeatures,\n numFeatureRequests, featureRequests):\n\n ngramsList = []\n resultList = []\n for featureRequest in featureRequests:\n ngramsList.append( featureRequest.split())\n print(ngramsList)\n for feature in possibleFeatures:\n for ngrams in ngramsList:\n print(feature)\n flag = feature in ngrams\n print(flag)\n if flag ==True:\n resultList.append((feature, ngrams.count(feature)))\n return resultList;\n\n\nlst = [\"abc\",\"cde\",\"def\",\"efg\"]\nlst2 = [\"abc is good then bcd\",\"bcd is bad then cde, def\",\"cde is good then bcd\",\"def is good then all\"]\nprint(popularNFeatures(4, 2, lst, 4, lst2));\n","sub_path":"python/codetest1.py","file_name":"codetest1.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"230763298","text":"import string\nimport random\nimport copy\nfrom decimal import *\n\njson_dir='markov_models/'\ndef init(book='huckleberry_finn'):\n with open(json_dir+book+'.json') as myfile:\n data=myfile.read().replace('\\n', '')\n return eval(data)\n\ntail_length = 2\n\ndef guess_next(markov, tail, length, pad_length=15):\n distr = copy.deepcopy(markov[tail])\n total = Decimal(distr['_total'])\n del distr['_total']\n\n if not tail in markov.keys():\n return '_end'\n\n # Pad _end and _total based on length to limit very long words\n if length > pad_length and '_end' in distr.keys():\n end_weight = Decimal((length / float(pad_length))**1) * total\n distr['_end'] += end_weight\n total += end_weight\n \n selector_value = Decimal(random.random())\n for key in distr:\n weight = distr[key] / total\n selector_value -= weight\n if selector_value < 0:\n return key\n\ndef make_word(markov):\n sentence = ''\n tail = ''\n next = ''\n \n while next != '_end':\n next = guess_next(markov, tail, len(sentence))\n \n if next != '_end':\n sentence += ' '+next\n tail += ' '+next\n tail = tail.strip()\n \n if len(tail.split(' ')) > tail_length:\n tail = ' '.join([i.strip() for i in tail.split(' ')[1:]]).strip()\n \n return sentence.strip()\n","sub_path":"page/markov.py","file_name":"markov.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"60562817","text":"# -*- encoding: UTF-8 -*-\n\n'''Módulo com funções auxiliares para o war'''\n\nfrom objective import Objective\n\n\ndef select_objectives(objectives, number_of_players):\n\n '''função que recebe lista de objetivos e número de jogadores que tem na\n partida e retorna uma lista contendo os objetivos possíveis para o número\n de jogadores recebido'''\n\n objectives_for_this_match = []\n for objective in objectives:\n if objective.player_max >= number_of_players >= objective.player_min:\n objectives_for_this_match.append(objective)\n\n return objectives_for_this_match\n\n\ndef planify(dict):\n\n \"\"\"Function that returns a list containing every item preceeded by\n its key\"\"\"\n\n result = []\n\n for key in dict.keys():\n for item in dict[key]:\n result.append(Objective(title=key + ' ' + item[0],\n player_min=item[1],\n player_max=item[2]))\n\n return result\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"229228877","text":"import pymysql\nimport time\nimport random\n\nfrom selenium import webdriver\nclass main():\n def s(self,a,b):\n ti=random.randint(a,b)\n time.sleep(ti)\n\n def init(self,url):\n #selenium登录\n browser = \"Chrome\"\n if browser == \"Chrome\":\n option = webdriver.ChromeOptions()\n #option.add_experimental_option(\"excludeSwitches\", [\"ignore-certificate-errors\"]) #去掉不受支持的命令行标记\n option.add_argument('--user-data-dir=C:\\\\Users\\\\CC-SERVER\\\\AppData\\\\Local\\\\Google\\\\Chrome\\\\User Data') # 设置成用户自己的数据目录\n driver = webdriver.Chrome(chrome_options=option)\n else:\n if browser == \"Firefox\":\n driver = webdriver.Firefox()\n else:\n driver = webdriver.PhantomJS()\n\n driver.get(url)\n\n #等待用户自己登陆\n\n #判断是否登陆成功\n name = input(\"Go?\")\n print(name)\n\n driver.get('https://ware.shop.jd.com/wareClassify/wareClassify_getWareByCondition.action')\n self.s(3, 4)\n\n\n data=self.get_lists()\n for i in range (len(data)):\n sku_id = data[i][0]\n print(sku_id)\n #sku_id=\"5915121\"\n '''\n driver.find_element_by_id('wareId').clear()\n driver.find_element_by_id('wareId').send_keys(sku_id)\n self.s(1,2)\n\n #点击查询\n\n driver.find_element_by_id(\"search\").click()\n self.s(2,3)\n check_id=\"selectWare_\"+sku_id\n driver.find_element_by_id(check_id).click()\n driver.find_element_by_id(\"top_bt_category_batch\").click()\n self.s(1,1)\n #print(driver.page_source)\n #通过id,勾选对应的数据\n \n '''\n used_data = self.find_used_cate(sku_id)\n config_post_url=\"https://ware.shop.jd.com/wareClassify/wareClassify_updateShopCategory.action?updateWareIds=%s,&shopCategoryIds=\"%sku_id\n for x in range (len(used_data)):\n cat_id=used_data[x][3]\n print(cat_id)\n if x==len(used_data)-1:\n config_post_url = config_post_url + cat_id\n else:\n config_post_url = config_post_url + cat_id + \",\"\n print(config_post_url)\n driver.get(config_post_url)\n\n\n\n\n #driver.find_element_by_id(cat_id).click()\n self.s(1,1)\n #调用一下回车键,因为弹出的确认窗口获取不到\n status=1\n self.update_status(sku_id,status)\n\n\n def get_lists(self):\n db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"jd_vcp\")\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n db.set_charset(\"utf8\")\n cursor.execute(\"SET NAMES utf8;\")\n cursor.execute(\"SET CHARACTER SET utf8;\")\n cursor.execute(\"SET character_set_connection=utf8;\")\n\n sql = \"select sku_id from 商品关系管理 group by sku_id \"\n #print(sql)\n try:\n cursor.execute(sql)\n data = cursor.fetchall()\n return data\n\n except Exception as err:\n db.rollback()\n print('-------insert_to_img_zone--------Error------Message--------:' + str(err))\n cursor.close()\n db.close()\n\n def find_used_cate(self,sku_id):\n db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"jd_vcp\")\n # 使用 cursor() 方法创建一个游标对象 cursor\n cursor = db.cursor()\n db.set_charset(\"utf8\")\n cursor.execute(\"SET NAMES utf8;\")\n cursor.execute(\"SET CHARACTER SET utf8;\")\n cursor.execute(\"SET character_set_connection=utf8;\")\n\n sql = \"select a.sku_id,a.sku_name,a.category_name,b.cat_id from 商品关系管理 a left join 商品关系字典表 b on a.category_name=b.cat_name and a.vc_shop=b.vc_shop where sku_id='%s' \" %(sku_id)\n #print(sql)\n try:\n cursor.execute(sql)\n data = cursor.fetchall()\n return data\n\n except Exception as err:\n db.rollback()\n print('-------insert_to_img_zone--------Error------Message--------:' + str(err))\n cursor.close()\n db.close()\n\n def update_status(self,sku_id,status):\n db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"jd_vcp\")\n cursor = db.cursor()\n db.set_charset(\"utf8\")\n cursor.execute(\"SET NAMES utf8;\")\n cursor.execute(\"SET CHARACTER SET utf8;\")\n cursor.execute(\"SET character_set_connection=utf8;\")\n sql = \"update 商品关系管理 set status='%d' where sku_id='%s' \" %(status,sku_id)\n try:\n cursor.execute(sql)\n db.commit()\n except Exception as err:\n db.rollback()\n print('---------------Error------Message--------:' + str(err))\n cursor.close()\n db.close()\n\n\nif __name__==\"__main__\":\n main=main()\n #url=\"http://www.baidu.com\"\n url=\"https://passport.shop.jd.com/login/index.action\"\n main.init(url)\n\n\n\n\n\n\n","sub_path":"JD后台/shop后台关联店内类目/商家后台-商品关系管理.py","file_name":"商家后台-商品关系管理.py","file_ext":"py","file_size_in_byte":5147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"628324806","text":"__author__ = 'Richard L. Sweat Jr.'\nimport pyodbc\n\n\nclass DB(object):\n def __init__(self):\n print(\"DB Connection connect init...\")\n self.cnxn = pyodbc.connect(\n \"DRIVER={SQL Server};SERVER=web_svr_01;DATABASE=decimalDataV10_Sanford;UID=monitorUser;PWD=monitor20100916!\")\n self.cursor = self.cnxn.cursor()\n print(\"DB Connection initialized\")\n\n\nclass MFG_Report(DB):\n\n def __init__(self):\n super(MFG_Report, self).__init__()\n self.report = self.get_mfg_report()\n\n def get_mfg_report(self):\n self.cursor.execute(\"exec dbo.PMR_GetWeeklyJobs\")\n rows = self.cursor.fetchall()\n return rows\n\n def convert_to_dict(self, data):\n result = {}\n for job in data:\n result[job[0]] = {'Job Number': job[0],\n 'Job Creation Time': job[1],\n 'API Start Time': job[2],\n 'API Finish Time': job[3],\n 'Estimated Time': job[4],\n 'CNC Name': job[5],\n 'Eng Approval Name': job[6],\n 'Eng Approval Time': job[7],\n 'Loaded Name': job[8],\n 'Loaded Time': job[9],\n 'Unloaded Name': job[10],\n 'Unloaded Time': job[11],\n 'Manufacturing Approval Name': job[12],\n 'Manufacturing Approval Time': job[13],\n 'Start Machining Time': job[14],\n 'End Machining Time': job[15],\n 'Job Status': job[16],\n 'Part Type': job[0][-2:]}\n return result\n\nif __name__ == \"__main__\":\n my_mfg_report = MFG_Report()\n\n print(my_mfg_report.report)\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"621010639","text":"from wtforms import SubmitField\nfrom providers.local import Neo4jDbConnector\nfrom search_plugins.search_plugin_manager import FormPlugin, HiddenFieldPlugin, StringFieldPlugin, RadioFieldPlugin, \\\n CheckboxFieldPlugin\n\n\nclass GetTags(object):\n def __init__(self):\n self.db_connector = Neo4jDbConnector()\n\n def build_query(self):\n query = \"\"\"\n MATCH (c:Category {id:10})<-[:CATEGORY_TAG_OF]-(meta_tag:MetaTag)<-[:INSTANCE_OF]-(tag:Tag)\n RETURN meta_tag.id as meta_tag_id, meta_tag.label as meta_tag_label, count(tag)\n ORDER BY count(tag) desc\n LIMIT 12;\n \"\"\"\n results = self.db_connector.execute_query(query, {})\n choices = []\n for result in results:\n choice = (result['meta_tag_id'], result['meta_tag_label'])\n choices.append(choice)\n return choices\n\n\nclass PluginForm(FormPlugin):\n query = StringFieldPlugin('Search', id='search-plugin-query')\n restaurant_item = HiddenFieldPlugin(match_stmt=\"(item)-[:INSTANCE_OF]->(restaurant_item:Item)\",\n where_stmt=\"restaurant_item.id = {restaurant_item} and item.label is not NULL\")\n location_item = HiddenFieldPlugin(default='9164475',\n match_stmt=\"(item)-[:LOCATED_IN_THE_ADMINISTRATIVE_TERRITORIAL_ENTITY]->(location_item:Item)\",\n where_stmt=\"location_item.id = 9164475\")\n meta_tag = RadioFieldPlugin(label='Order by...',\n match_stmt='(item)<-[:TAG_ABOUT]-(tag:Tag)-[:INSTANCE_OF]->(meta_tag:MetaTag)',\n where_stmt='meta_tag.id = {meta_tag}',\n return_stmt='tag',\n order_by_stmt=\"tag.score DESC\")\n submit = SubmitField('Search')\n\n def __init__(self, *args, **kwargs):\n super(FormPlugin, self).__init__(*args, **kwargs)\n self.item_id_field = self.restaurant_item\n self.meta_tag.choices = GetTags().build_query()\n self.checkbox_fields = [getattr(self, field, None) for field in dir(self) if\n isinstance(getattr(self, field), CheckboxFieldPlugin)]\n self.radio_fields = [getattr(self, field, None) for field in dir(self) if\n isinstance(getattr(self, field), RadioFieldPlugin)]\n self.hidden_fields = [getattr(self, field, None) for field in dir(self) if\n isinstance(getattr(self, field), HiddenFieldPlugin) and not\n getattr(self, field) == self.item_id_field]\n","sub_path":"search_plugins/restaurant/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"353053457","text":"import pdb\nimport numpy as np\nimport Bio\nfrom Bio import PDB\nfrom Bio.Seq import Seq\n\ndef transformContextPadded(X, Y, w=10):\n n = len(X)\n feature_length = 4*w # 2 angles and bidirectionnal\n X_C = []\n if w > n:\n w = n\n for i in range(n):\n index_start = max([0, i-w])\n index_end = min([n, i+w]) \n if i < w:\n complete_vector = [[0.,0.] for j in range(w-i)]\n X_c = sum(complete_vector + X[index_start:index_end], [])\n if i > n - w:\n complete_vector = [[0.,0.] for j in range(w-(n-i))]\n X_c = sum(X[index_start:index_end] + complete_vector, [])\n \n X_C.append(X_c)\n\n Y_C = Y\n return X_C, Y_C\n\n\ndef transformContext(X, Y, w=10, keep_value=False):\n n = len(X)\n X_C = []\n if w > n:\n w = n\n for i in range(n):\n index_start = max([0, i-(w-1)])\n index_end = min([n, i+(w-1)]) \n X_i = X[i]\n if keep_value:\n X_c = []\n X_c.append(X_i)\n X_c += X[index_start:index_end] \n else:\n X_c = X[index_start:index_end]\n X_C.append(X_c)\n\n Y_C = Y\n return X_C, Y_C\n\n\n\nfrom Bio.PDB.MMCIFParser import MMCIFParser\nfrom Bio.PDB import *\n\nparser = MMCIFParser()\nprotein_filenames = []\n\nimport sys\nprefix = sys.argv[1] \nimport os\n\n\n# H \tAlpha helix (4-12)\n# B \tIsolated beta-bridge residue\n# E \tStrand\n# G \t3-10 helix\n# I \tPi helix\n# T \tTurn\n# S \tBend\n# - \tNone\nmap_st = {\"G\": 0, \"H\": 1, \"I\": 2, \"T\": 3, \"E\": 4, \"B\": 5, \"S\": 6, \"-\": 7}\n\n\nprotein_name_val = \"1w09\"\n\ndef parseData(filedir):\n X_phi_psi = []\n X_omega = []\n Y_labels = []\n debug_Y = []\n debug_counter = 0\n for subdir, _, _ in os.walk(filedir):\n if subdir != filedir:\n for _, _, files in os.walk(subdir):\n for protein_filename in files:\n data_filename = protein_filename.split(\"/\")[-1]\n print(data_filename)\n if debug_counter > 0:\n break\n if protein_name_val + \".cif\" in data_filename and \".gz\" not in data_filename:\n print(subdir + \"/\" + protein_filename)\n try:\n structure = parser.get_structure(protein_filename, subdir + \"/\" + protein_filename)\n dssp=PDB.DSSP(structure[0], subdir + \"/\" + protein_filename)\n except:\n print(\"Could not parse or no file named\", subdir + \"/\" + protein_filename)\n continue\n \n # I - Get list of secondary structures computed with DSSP\n # WARNING, DSSP might return less keys (each key correspond to a residue) than the total number of residues in the protein\n # H \tAlpha helix (4-12)\n # B \tIsolated beta-bridge residue\n # E \tStrand\n # G \t3-10 helix\n # I \tPi helix\n # T \tTurn\n # S \tBend\n # - \tNone\n \n #0 \tDSSP index\n #1 \tAmino acid\n #2 \tSecondary structure\n #3 \tRelative ASA\n #4 \tPhi\n #5 \tPsi\n #6 \tNH-->O_1_relidx\n #7 \tNH-->O_1_energy\n #8 \tO-->NH_1_relidx\n #9 \tO-->NH_1_energy\n #10 \tNH-->O_2_relidx\n #11 \tNH-->O_2_energy\n #12 \tO-->NH_2_relidx\n #13 \tO-->NH_2_energy\n \n # OTHER WAY TO GET THE RESIDUE TYPES: [x.xtra for x in structure.get_residues() if len(x.xtra) > 0]\n # This should have the same length as the list obtained from dssp\n residue_shapes = []\n residue_labels = [] # 0: alpha_helix, 1: beta_strand, 2: other\n residue_all_labels = []\n residue_keys = []\n residue_dssp = []\n x_phi_psi = []\n if len(dssp.keys()) > 100:\n debug_counter += 1\n\n for key in dssp.keys():\n residue_key = dssp[key]\n residue_dssp.append(residue_key)\n residue_keys.append(residue_key[2])\n residue_all_labels.append(map_st[residue_key[2]])\n x_phi = residue_key[4]\n x_psi = residue_key[5]\n x_phi_psi.append([x_phi, x_psi])\n residue_labels.append(map_st[residue_key[2]])\n if 1:\n residue_shapes.append(residue_key)\n debug_Y.append(residue_key[2])\n \n y_label = residue_labels[:-1] \n x_phi_ = [x[0] for x in x_phi_psi][1:]\n x_psi_ = [x[1] for x in x_phi_psi][:-1]\n x_phi_psi = [[x,y] for x,y in zip(x_phi_, x_psi_)] \n Y_labels.append(y_label)\n X_phi_psi.append(x_phi_psi)\n assert(len(x_phi_psi) == len(y_label))\n \n # II - Get 3D coordinates\n coordinates = [x.get_coord() for x in structure.get_atoms()]\n \n return X_phi_psi, Y_labels, debug_Y\n\n\ndef basicFeatures(x, y, keep_value = False):\n if keep_value:\n phis = [xx[0] for xx in x[1:]]\n psis = [xx[1] for xx in x[1:]]\n avg1 = np.mean(phis)\n std1 = np.std(phis)\n avg2 = np.mean(psis)\n std2 = np.std(psis)\n return [x[0][0], x[0][1], avg1, std1, avg2, std2], y\n else:\n phis = [xx[0] for xx in x]\n psis = [xx[1] for xx in x]\n avg1 = np.mean(phis)\n std1 = np.std(phis)\n avg2 = np.mean(psis)\n std2 = np.std(psis)\n return [avg1, std1, avg2, std2], y\n\ndef basicFeaturesTrigo(x, y, keep_value = False):\n if keep_value:\n phis_cos = [np.cos(xx[0]*np.pi/180) for xx in x[1:]]\n psis_cos = [np.cos(xx[1]*np.pi/180) for xx in x[1:]]\n avg1_cos = np.mean(phis_cos)\n std1_cos = np.std(phis_cos)\n avg2_cos = np.mean(psis_cos)\n std2_cos = np.std(psis_cos)\n\n phis_sin = [np.sin(xx[0]*np.pi/180) for xx in x[1:]]\n psis_sin = [np.sin(xx[1]*np.pi/180) for xx in x[1:]]\n avg1_sin = np.mean(phis_sin)\n std1_sin = np.std(phis_sin)\n avg2_sin = np.mean(psis_sin)\n std2_sin = np.std(psis_sin)\n return [x[0][0], x[0][1], avg1_cos, std1_cos, avg2_cos, std2_cos], [x[0][0], x[0][1], avg1_sin, std1_sin, avg2_sin, std2_sin], y\n\n else:\n phis_cos = [np.cos(xx[0]*np.pi/180) for xx in x]\n psis_cos = [np.cos(xx[1]*np.pi/180) for xx in x]\n avg1_cos = np.mean(phis_cos)\n std1_cos = np.std(phis_cos)\n avg2_cos = np.mean(psis_cos)\n std2_cos = np.std(psis_cos)\n\n phis_sin = [np.sin(xx[0]*np.pi/180) for xx in x]\n psis_sin = [np.sin(xx[1]*np.pi/180) for xx in x]\n avg1_sin = np.mean(phis_sin)\n std1_sin = np.std(phis_sin)\n avg2_sin = np.mean(psis_sin)\n std2_sin = np.std(psis_sin)\n\n return [avg1_cos, std1_cos, avg2_cos, std2_cos], [avg1_sin, std1_sin, avg2_sin, std2_sin], y\n\n\ndef allDihedralSTD(x, y):\n assert(not keep_value)\n std = np.std([xx[0] for xx in x[1:]] + [xx[1] for xx in x[1:]])\n return std, y\n\n\ndef allDihedralTrigoSTD(x, y):\n assert(not keep_value)\n std_cos = np.std([np.cos(xx[0]*np.pi/180) for xx in x[1:]] + [np.cos(xx[1]*np.pi/180) for xx in x[1:]])\n std_sin = np.std([np.sin(xx[0]*np.pi/180) for xx in x[1:]] + [np.sin(xx[1]*np.pi/180) for xx in x[1:]]) \n\n return std_cos, std_sin, y\n\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cluster import KMeans\nimport itertools, operator\nfrom sklearn.metrics import f1_score\n\n\nkeep_value = True\nX_phi_psi_0, Y_labels_0, debug_Y = parseData(prefix)\n\n#for w in [3,5,10,20]:\nfor w in [2]:\n X_phi_psi = []\n X_phi_psi2 = []\n Y_labels = []\n X_all = []\n X_all2 = []\n for X_protein, Y_protein in zip(X_phi_psi_0, Y_labels_0):\n x_phi_psi_new, y_label_new = transformContext(X_protein, Y_protein, w=w, keep_value=keep_value)\n x_phi_psi, x_phi_psi2, y_label, x_all, x_all2 = [], [], [], [], []\n for x, y in zip(x_phi_psi_new, y_label_new):\n x_phi_psi_c, x_phi_psi_s, y_label_c = basicFeaturesTrigo(x, y, keep_value=keep_value)\n\n x_all_c, x_all_s, _ = allDihedralTrigoSTD(x, y)\n x_all.append(x_all_c)\n x_all2.append(x_all_s)\n x_phi_psi.append(x_phi_psi_c)\n x_phi_psi2.append(x_phi_psi_s)\n y_label.append(y_label_c)\n X_phi_psi += x_phi_psi\n X_phi_psi2 += x_phi_psi2\n Y_labels += y_label\n X_all += x_all\n X_all2 += x_all2\n\n n_samples = len(X_phi_psi)\n n_train = int(n_samples*0.75)\n X_train = X_phi_psi[:n_train]\n X_test = X_phi_psi[n_train:]\n Y_train = Y_labels[:n_train]\n Y_test = Y_labels[n_train:]\n ####################################\n # Simple display\n # x-axis: residue index\n # y-axis: standard deviation of dihedral angle\n # Point color: blue: alpha helix, red: beta strand, black: other\n\n if not keep_value:\n X_std_phi = []\n X_std_psi = []\n X_std_phi2 = []\n X_std_psi2 = []\n for x in X_phi_psi:\n X_std_phi.append(x[1])\n X_std_psi.append(x[3])\n for x in X_phi_psi2:\n X_std_phi2.append(x[1])\n X_std_psi2.append(x[3])\n\n # H Alpha helix (4-12)\n # B Isolated beta-bridge residue\n # E Strand\n # G 3-10 helix\n # I Pi helix\n # T Turn\n # S Bend\n # - Coil\n\n type_map = {'H': 'alpha', 'B': 'b bridge', 'E': 'b strand', 'G': '3-10 hlx', 'I': 'pi helix', 'T': 'turn', 'S': 'bend', '-': 'coil'}\n reverse_map_st_tmp = inv_map = {v: k for k, v in map_st.items()} \n reverse_map_st = {}\n for key in reverse_map_st_tmp.keys():\n new_key = '$\\\\mathdefault{%s}$' % key \n reverse_map_st[new_key] = type_map[reverse_map_st_tmp[key]]\n\n reverse_map_st['$\\\\mathdefault{nan}$'] = 'nan'\n\n\n import matplotlib.pyplot as plt\n fig, ((ax_phi, ax_psi, ax_all, ax_debug), (ax_phi2, ax_psi2, ax_all2, ax_debug2))= plt.subplots(2, 4)\n\n ax_phi.set_title(\"COS Phi STD (w=%i) vs. residue type\" %w)\n ax_phi.set_xlabel(\"Residue index\")\n ax_phi.set_ylabel(\"Standard deviation phi in context of residue\")\n residue_indices = [i for i in range(len(X_std_phi))] \n scatter = ax_phi.scatter(residue_indices, X_std_phi, c=Y_labels)\n legend1 = ax_phi.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") \n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels] \n legend2 = ax_phi.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\")\n ax_phi.add_artist(legend2)\n\n ax_psi.set_title(\"COS Psi STD (w=%i) vs. residue type\" %w)\n ax_psi.set_xlabel(\"Residue index\")\n ax_psi.set_ylabel(\"Standard deviation psi in context of residue\")\n residue_indices = [i for i in range(len(X_std_psi))] \n scatter = ax_psi.scatter(residue_indices, X_std_psi, c=Y_labels)\n legend1 = ax_psi.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n\n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_psi.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\") \n ax_psi.add_artist(legend2)\n\n ax_all.set_title(\"COS Phi/Psi STD (w=%i) vs. residue type\" %w)\n ax_all.set_xlabel(\"Residue index\")\n ax_all.set_ylabel(\"Standard deviation phi/psi in context of residue\")\n residue_indices = [i for i in range(len(X_all))] \n scatter = ax_all.scatter(residue_indices, X_all, c=Y_labels)\n legend1 = ax_all.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n\n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_all.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\") \n ax_all.add_artist(legend2)\n\n ax_debug.set_title(\"Validation\")\n ax_debug.set_xlabel(\"Residue index\")\n ax_debug.set_ylabel(\"Nothing\")\n residue_indices = [i for i in range(len(X_all))] \n scatter = ax_debug.scatter(residue_indices, [1 for i in range(len(X_all))], c=Y_labels)\n legend1 = ax_debug.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n\n \n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_debug.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\")\n ax_debug.add_artist(legend2)\n\n ax_phi2.set_title(\"SIN Phi STD (w=%i) vs. residue type\" %w)\n ax_phi2.set_xlabel(\"Residue index\")\n ax_phi2.set_ylabel(\"Standard deviation phi in context of residue\")\n residue_indices = [i for i in range(len(X_std_phi))] \n scatter = ax_phi2.scatter(residue_indices, X_std_phi2, c=Y_labels)\n legend1 = ax_phi2.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_phi2.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\") #ax_psi2.add_artist(legend1)\n ax_phi2.add_artist(legend2)\n\n ax_psi2.set_title(\"SIN Psi STD (w=%i) vs. residue type\" %w)\n ax_psi2.set_xlabel(\"Residue index\")\n ax_psi2.set_ylabel(\"Standard deviation psi in context of residue\")\n residue_indices = [i for i in range(len(X_std_psi))] \n scatter = ax_psi2.scatter(residue_indices, X_std_psi2, c=Y_labels)\n legend1 = ax_psi2.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_psi2.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\")\n ax_psi2.add_artist(legend2)\n \n ax_all2.set_title(\"SIN Phi/Psi STD (w=%i) vs. residue type\" %w)\n ax_all2.set_xlabel(\"Residue index\")\n ax_all2.set_ylabel(\"Standard deviation phi/psi in context of residue\")\n residue_indices = [i for i in range(len(X_all))] \n scatter = ax_all2.scatter(residue_indices, X_all2, c=Y_labels)\n legend1 = ax_all2.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n\n handles, labels = scatter.legend_elements(prop=\"colors\", alpha=0.6)\n labels_residues = [reverse_map_st[label] for label in labels]\n legend2 = ax_all2.legend(handles, labels_residues, loc=\"upper right\", title=\"Type\")\n ax_all2.add_artist(legend2)\n\n ax_debug2.set_title(\"Validation\")\n ax_debug2.set_xlabel(\"Residue index\")\n ax_debug2.set_ylabel(\"Nothing\")\n residue_indices = [i for i in range(len(X_all))] \n scatter = ax_debug2.scatter(residue_indices, [1 for i in range(len(X_all))], c=Y_labels)\n legend1 = ax_debug2.legend(*scatter.legend_elements(), loc=\"upper right\", title=\"Type\") #[\"alpha helix\", \"beta strand\", \"other\"], loc=\"upper right\", title=\"Type\")\n ax_debug2.add_artist(legend1)\n\n plt.suptitle(\"Protein %s\" %protein_name_val, fontsize=14)\n\n plt.show()\n\n ### k-nn\n knn_scores = []\n k_neighbors_values = [k for k in range(10, min([200, int((n_samples-1)/2)]), 10)]\n for k_neighbors in k_neighbors_values:\n knn = KNeighborsClassifier(n_neighbors=k_neighbors)\n knn.fit(X_train, Y_train)\n knn_score = knn.score(X_test, Y_test)\n knn_scores.append(knn_score)\n \n import matplotlib.pyplot as plt\n plt.title(\"From dihedral angles to residue type: k-nn score\")\n plt.xlabel(\"k\")\n plt.ylabel(\"F1 score\")\n \n plt.plot(k_neighbors_values, knn_scores)\n plt.show()\n ##################################\n \n","sub_path":"simple_baseline_display.py","file_name":"simple_baseline_display.py","file_ext":"py","file_size_in_byte":17096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"519530143","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\n\n\nclass QLearningTable(object):\n def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):\n self.actions = actions # 动作空间\n self.alpha = learning_rate # 学习率\n self.gamma = reward_decay # 奖励衰减值\n self.epsilon = e_greedy # 动作选择贪婪度\n self._current_action = None\n self._current_observation = None\n\n # 初始化Q表(初始化的Q表是一个空表)\n self.q_table = pd.DataFrame(columns=self.actions, dtype=np.float64)\n\n # 选取动作\n def choose_action(self):\n self.check_state_exist(self._current_observation)\n\n # 根据贪婪度选择动作\n if np.random.uniform() < self.epsilon:\n state_action = self.q_table.loc[self._current_observation, :]\n # 从拥有最大Q_value值的一系列actions中随机选择一个action\n action = np.random.choice(state_action[state_action == np.max(state_action)].index)\n else:\n action = np.random.choice(self.actions)\n return action\n\n # 更新Q表\n def step(self, reward, observation_):\n self.check_state_exist(observation_)\n # Q估计\n q_predict = self.q_table.loc[self._current_observation, self._current_action]\n # Q现实\n if observation_ == \"terminal\":\n q_target = reward\n else:\n q_target = reward + self.gamma*self.q_table.loc[observation_, :].max()\n # Q表更新\n self.q_table.loc[self._current_observation, self._current_action] += self.alpha*(q_target - q_predict)\n\n # 需要返回动作\n self._current_observation = observation_\n return self.choose_action()\n\n def check_state_exist(self, observation):\n # 检查表中是否存在了observation状态,不存在就加入observation\n if observation not in self.q_table.index:\n self.q_table = self.q_table.append(pd.Series(\n [0] * len(self.actions),\n index=self.q_table.columns,\n name=observation\n ))\n\n def begin_episode(self, initial_observation):\n # 返回选择的动作\n self._current_observation = initial_observation\n self._current_action = self.choose_action()\n return self._current_action\n","sub_path":"agent/q_learning/q_leaning.py","file_name":"q_leaning.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"309791545","text":"import matplotlib.image as img \nimport matplotlib.pyplot as plt \nimport tensorflow as tf\n\nfilename = \"C:/ITWILL/6_Tensorflow/data/packet.jpeg\"\ninput_image = img.imread(filename)\n\nprint('input dim =', input_image.ndim) #dimension\nprint('input shape =', input_image.shape) #shape\n\n# image 원본 출력 \nplt.subplot(1,2,1)\nplt.imshow(input_image)\nplt.show() \n\n# image 축 변경\nplt.subplot(1,2,2)\nplt.imshow(tf.transpose(a = input_image , perm = [1,0,2]))\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":"tensorflow/C02_Tensorflow_handle/lecture/step07_image_transpose.py","file_name":"step07_image_transpose.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"11235993","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, _\n\n\nclass MrpWorkcenter(models.Model):\n _inherit = 'mrp.workcenter'\n\n @api.multi\n def action_see_spc_control(self):\n action = self.env.ref('spc.quality_check_action_spc').read()[0]\n action.update({\n 'context': {\n 'search_default_workcenter_id': self.id\n }\n })\n return action\n\n @api.multi\n def action_see_result(self):\n action = self.env.ref('spc.operation_result_action_main').read()[0]\n action.update({\n 'context': {\n 'search_default_workcenter_id': self.id\n }\n })\n return action\n","sub_path":"sa_addons/spc/models/mrp_workcenter.py","file_name":"mrp_workcenter.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"512547117","text":"\"\"\" Application's command line .\n\nWhy does this file exist, and why not put this in __main__?\n\n You might be tempted to import things from __main__ later, but that will cause\n problems: the code will get executed twice:\n\n - When you run `python -msimcore_service_webserver` python will execute\n ``__main__.py`` as a script. That means there won't be any\n ``simcore_service_webserver.__main__`` in ``sys.modules``.\n - When you import __main__ it will get executed again (as a module) because\n there's no ``simcore_service_webserver.__main__`` in ``sys.modules``.\n\n\"\"\"\n\n\nimport logging\nimport os\nimport sys\nfrom argparse import ArgumentParser\nfrom typing import Dict, List, Optional\n\nfrom .application import run_service\nfrom .application_config import CLI_DEFAULT_CONFIGFILE, app_schema\nfrom .cli_config import add_cli_options, config_from_options\nfrom .log import setup_logging\nfrom .utils import search_osparc_repo_dir\n\n# ptsvd cause issues with ProcessPoolExecutor\n# SEE: https://github.com/microsoft/ptvsd/issues/1443\nif os.environ.get(\"SC_BOOT_MODE\") == \"debug-ptvsd\":\n import multiprocessing\n\n multiprocessing.set_start_method(\"spawn\", True)\n\nlog = logging.getLogger(__name__)\n\n\ndef create_default_parser() -> ArgumentParser:\n return ArgumentParser(description=\"Service to manage data webserver in simcore.\")\n\n\ndef setup_parser(parser: ArgumentParser) -> ArgumentParser:\n \"\"\"Adds all options to a parser\"\"\"\n # parser.add_argument('names', metavar='NAME', nargs=argparse.ZERO_OR_MORE,\n # help=\"A name of something.\")\n\n add_cli_options(parser, CLI_DEFAULT_CONFIGFILE)\n\n # Add here more options ....\n\n return parser\n\n\ndef create_environ(*, skip_host_environ: bool = False) -> Dict[str, str]:\n \"\"\"Build environment with substitutable variables\n\n\n :param skip_host_environ: excludes os.environ , defaults to False\n :param skip_host_environ: bool, optional\n :return: a dictionary of variables to replace in config file\n :rtype: Dict[str, str]\n \"\"\"\n\n # system's environment variables\n environ = {} if skip_host_environ else dict(os.environ)\n\n # project-related environment variables\n rootdir = search_osparc_repo_dir()\n if rootdir is not None:\n environ.update(\n {\n \"OSPARC_SIMCORE_REPO_ROOTDIR\": f\"{rootdir}\",\n }\n )\n\n # DEFAULTS if not defined in environ\n # NOTE: unfortunately, trafaret does not allow defining default directly in the config.yamla\n # as docker-compose does: i.e. x = ${VARIABLE:default}.\n #\n # Instead, the variable has to be defined here ------------\n environ.setdefault(\"SMTP_USERNAME\", \"None\")\n environ.setdefault(\"SMTP_PASSWORD\", \"None\")\n environ.setdefault(\"SMTP_TLS_ENABLED\", \"0\")\n environ.setdefault(\"WEBSERVER_LOGLEVEL\", \"WARNING\")\n\n # ----------------------------------------------------------\n\n return environ\n\n\ndef parse(args: Optional[List], parser: ArgumentParser) -> Dict:\n \"\"\"Parse options and returns a configuration object\"\"\"\n if args is None:\n args = sys.argv[1:]\n\n # ignore unknown options\n options, _ = parser.parse_known_args(args)\n config = config_from_options(options, app_schema, vars=create_environ())\n\n return config\n\n\ndef main(args: Optional[List] = None):\n # parse & config file\n parser = ArgumentParser(description=\"Service to manage data webserver in simcore.\")\n setup_parser(parser)\n config = parse(args, parser)\n\n # service log level\n slow_duration = float(\n os.environ.get(\"AIODEBUG_SLOW_DURATION_SECS\", 0)\n ) # TODO: move to settings.py::ApplicationSettings\n setup_logging(level=config[\"main\"][\"log_level\"], slow_duration=slow_duration)\n\n # run\n run_service(config)\n","sub_path":"services/web/server/src/simcore_service_webserver/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"381710406","text":"\"\"\"\n퇴사 문제\nauthor : donghak park\ncontact : donghark03@naver.com\n\"\"\"\n\nN = int(input())\n\nT = []\nP = []\n\nfor _ in range(N):\n t, p = map(int, input().split())\n T.append(t)\n P.append(p)\n\ndp = [0] * (N+1)\nmax_value = 0\n\nfor i in range(N-1, -1, -1):\n time = i + T[i]\n\n if time <= N:\n dp[i] = max(dp[time]+P[i], max_value)\n max_value = dp[i]\n else:\n dp[i] = max_value\nprint(max_value)","sub_path":"Problem Solving/DONGHAK/[na]/[na]ch16_3.py","file_name":"[na]ch16_3.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"208933328","text":"\"\"\"\nMIT License\n\nCopyright (c) 2021 STR-Coding-Club\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\n\nimport random\nimport requests\nimport sys\n\nfrom time import sleep, time\nfrom numpy import average\n\nimport blockchain\nimport crypto\nNODE = \"http://robcoin.strcoding.club:5000\"\n\ntry:\n with open(\"miner_address.txt\", \"r\") as address:\n mining_address = address.read()\nexcept FileNotFoundError:\n print(\"'miner_address.txt' not detected! Run 'run_wallet.py' first!\", file=sys.stderr)\n sys.exit(0)\n\nhash_per_second = []\n\n\nclass Miner(object):\n @property\n def current_chain(self):\n response = requests.get(NODE + \"/chain\")\n chain = blockchain.Blockchain()\n chain.chain = response[\"chain\"]\n return chain\n\n def __init__(self):\n print('Miner initialized!')\n\n def proof_of_work(self, block) -> int:\n \"\"\"\n Proof of Work (POW algorithm)\n - Find p' such that p' combined by p < POW target, where p is the previous hash\n - for hash(pp') to be smaller than the POW target, the hash must have N number of leading zeros\n - leading zeros N can be increased to increase mining difficulty\n :param block: \n :return: p'\n \"\"\"\n\n guesses = 0\n proof = 0\n start = time()\n while not crypto.valid_proof(block, proof):\n proof = random.getrandbits(256)\n guesses += 1\n end = time()\n hash_per_second.append(guesses / (end - start))\n print(f'Hashrate: {average(hash_per_second) / 1000:.2f} KH/s')\n return proof\n\n def mine(self):\n while True:\n while requests.get(NODE + \"/work\").status_code == 204: # Empty\n sleep(2)\n response = requests.get(NODE + \"/work\")\n proof = self.proof_of_work(response.json())\n print(f'Proof found: {proof}')\n print('Sending now to node...')\n if requests.get(NODE + \"/work\").status_code == 200: # worked\n print('Success! You have been rewarded with 1 $TR (to be added in next block)')\n print()\n else:\n print('Error! Did not send block in on-time!')\n print()\n headers = {'User-Agent': 'Mozilla/5.0'}\n requests.post(NODE + \"/submitproof\", headers=headers, data={\n \"proof\": proof,\n \"miner\": mining_address\n })\n","sub_path":"miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"482596160","text":"# -*- coding: utf-8 -*-\n\"\"\"CrabStick\n\nUsage:\n crabstick.py (-u |-l | -c )\n [-b -w ]\n [-t -r --os --php --asp]\n [-f --update --proxy --agent --random-agents --cookies ]\n [--http-header --lport --rport ]\n [-q |-v]\n\nOptions:\n Target:\n -u , --url target url\n -l , --list-url list of target url's in a file\n Crawler:\n -c , --crawl domain to crawl [default: False]\n -b , --black-list black-list urls that start with\n -w , --white-list white-list urls that start with\n Timing:\n -t , --threads number of threads [default: 1]\n -r , --rate-limit limit the number of requests per second [defualt: False]\n --os the target operating system (windows, linux) [default: \"Unknown\"]\n --php the target site is running php\n --asp the target site is running asp\n --jsp the target site is running jsp\n Other:\n -f, --filter perform filter evasion techniques\n --update Check if crabsticks is up to date\n --proxy proxy :\n --agent change user-agents\n --random-agents randomize user-agents\n --cookies specify cookies\n --http-header tamper script\n Shell:\n --lport specify a local port for the reverse shell to connect back to (defualt 1234)\n --rport specify a remote port for the target to open during shell\n verbose:\n -q --quiet SHHHHHHHH!!!!\n -v --verbose AHHHHHHHH!!!!\n\nExamples:\n\n\n\"\"\"\nfrom docopt import docopt\nimport sys\nimport os\nimport subprocess\n\nfrom general_func import GenralFunc\nfrom crab_requests import *\nfrom payload_lfi import *\n\nclass Domain:\n def __init__(self, docopt, url=False):\n if url == False:\n self.url = docopt[\"--url\"]\n else:\n self.url = url\n self.useragent = docopt[\"--agent\"]\n self.asp = docopt[\"--asp\"]\n self.black_list = docopt[\"--black-list\"]\n self.cookie = docopt[\"--cookies\"]\n self.crawl = docopt[\"--crawl\"]\n self.header = docopt[\"--http-header\"]\n self.lport = docopt[\"--lport\"]\n self.os = docopt[\"--os\"]\n self.php = docopt[\"--php\"]\n self.proxy = docopt[\"--proxy\"]\n self.quiet = docopt[\"--quiet\"]\n self.random_agent = docopt[\"--random-agents\"]\n self.rate_limit = docopt[\"--rate-limit\"]\n self.rport = docopt[\"--rport\"]\n self.thread_count = docopt[\"--threads\"]\n self.verbose = docopt[\"--verbose\"]\n self.white_list = docopt[\"--white-list\"]\n self.filter = docopt[\"-f\"]\n self.get_parameters = []\n self.url_parameters = None\n GenralFunc.pprint(\"Target aquired: \" + self.url, \"underline\")\n self.crabrequests = CrabRequests(self.url)\n\n def start(self):\n if self.crabrequests.test.target_up(self.url) == 1:\n GenralFunc.pprint(\"Finding GET parameters\", \"success\")\n self.url_parameters = self.crabrequests.test.urlparse(self.url)\n GenralFunc.pprint(\"Scheme:\\t\" + str(self.url_parameters.scheme), \"debug\")\n GenralFunc.pprint(\"Netloc:\\t\" + str(self.url_parameters.netloc), \"debug\")\n GenralFunc.pprint(\"Path:\\t\" + str(self.url_parameters.path), \"debug\")\n GenralFunc.pprint(\"Params:\\t\" + str(self.url_parameters.params), \"debug\")\n GenralFunc.pprint(\"Query:\\t\" + str(self.url_parameters.query), \"debug\")\n GenralFunc.pprint(\"Frag:\\t\" + str(self.url_parameters.fragment), \"debug\")\n if self.url_parameters.query:\n if self.url_parameters.query != \"\":\n temp = self.url_parameters.query\n temp = temp.split(\"&\")\n GenralFunc.pprint(\"Target has \" + str(len(temp)) + \" injectable GET parameters to test.\", \"success\")\n for x in range(0, len(temp)):\n self.get_parameters.append(temp[x])\n GenralFunc.pprint(\"GET parameter \" + str(x + 1) + \": \\t\" + temp[x], \"debug\")\n payload_lfi = PayloadLFI(self.get_parameters, self.url_parameters, self.url, self.php, self.os)\n payload_lfi.generate_payloads()\n dirty_urls = payload_lfi.display_payloads()\n\n else:\n GenralFunc.pprint(\"Target has no injectable GET parameters\", \"fail\")\n else:\n GenralFunc.pprint(\"Target connection failed skipping host: \" + self.url, \"fatal\")\n\n\ndef start():\n doc_args = check_env()\n args = parse_cmd_args(doc_args)\n if args:\n return args\n else:\n GenralFunc.pprint(\"No arguments, something went wrong exiting\", \"fail\")\n exit(-1)\n\n #test = CrabRequests()\n #test.test.target_up()\n\ndef check_env():\n \"\"\"Checks for relevant python modules, internet connection (proxies), if the project is update\"\"\"\n if sys.version_info[0] < 3:\n print(\"Using python 2 is not supported\")\n exit(-1)\n else:\n banner()\n arguments = docopt(__doc__)\n if arguments:\n GenralFunc.pprint(\"Checking Environment and arguments\", \"underline\")\n GenralFunc.pprint(\"Using Python 3\", \"success\")\n batcmd=\"git status\"\n try:\n result = subprocess.check_output(batcmd, shell=True).decode().encode('utf-8')\n if b\"up-to-date\" in result:\n GenralFunc.pprint(\"Branch is up to date\", \"success\")\n elif b\"not found\" in result:\n pass\n else:\n GenralFunc.pprint(\"There is a new version of crabstick available\", \"warning\")\n GenralFunc.pprint(\"Update??\", \"blink\")\n ans = input(\"N/y:\")\n if \"y\" in ans.lower():\n batcmd = \"git pull\"\n subprocess.check_output(batcmd, shell=True)\n except Exception as e:\n print(str(e))\n GenralFunc.pprint(\"Unable to determine if crabstick is up to date\", \"warning\")\n GenralFunc.pprint(\"try: 'git pull' to check\", \"warning\")\n return arguments\n else:\n GenralFunc.pprint(\"Looks like we have nothing left to do\", \"fail\")\n\n\ndef banner():\n \"\"\"Ascii art\"\"\"\n GenralFunc.pprint(\" .____.\", \"bold\", symbol=False)\n GenralFunc.pprint(\" \\)__/\\ \" \"\\033[5m\" + \"oo \" + \"\\033[;0m\\033[1m\" + \"/\\__(/\", \"bold\", symbol=False)\n GenralFunc.pprint(\" _/\\/_~__\\/\\_\", \"bold\", symbol=False)\n GenralFunc.pprint(\"________ _/ \\_ ___. _________ __ __ __ \", \"bold\", symbol=False)\n GenralFunc.pprint(\"\\_ ___\\ \" + \"\\033[92m\" + \"HACK_HUT\" + \"\\033[;0m\\033[1m\" + \" __ \\_ |__ / _____// |_|__| ____ | | __\", \"bold\", symbol=False)\n GenralFunc.pprint(\"/ \\ \\/\\_ __ \\__ \\ | __ \\ \\_____ \\\\ __\\ |/ ___\\| |/ /\", \"bold\", symbol=False)\n GenralFunc.pprint(\"\\ \\____| | \\// __ \\| \\_\\ \\/ \\| | | \\ \\___| < \", \"bold\", symbol=False)\n GenralFunc.pprint(\" \\______ /|__| (______/_____/_________/|__| |__|\\_____>__|_ \\ \", \"bold\", symbol=False)\n GenralFunc.pprint(\" \\/ \" + \"\\033[92m\" + \" A tool for HTTP file inclusion exploits\", \"bold\", symbol=False)\n GenralFunc.pprint(65 * \"_\", \"underline\", symbol=False)\n print(65 * \"-\")\n GenralFunc.pprint(\"[!] Remember you need to abide by the \\033[91m claw\", \"bold\", symbol=False)\n GenralFunc.pprint(65 * \"-\", \"underline\", symbol=False)\n\ndef parse_cmd_args(arguments):\n \"\"\"Reads the commandline args and validates them\"\"\"\n #GenralFunc.pprint(str(arguments), \"debug\")\n GenralFunc.pprint(\"Success\", \"success\")\n return arguments\n\nif __name__== \"__main__\":\n args = start()\n if args[\"-l\"]:\n GenralFunc.pprint(\"List of target mode selected\", \"underline\")\n # Only does this if their is a list of domains\n file = args[\"-l\"]\n with open(file, \"r\") as f:\n domains = f.readlines()\n domain_class_list = []\n clean = []\n try:\n [clean.append(domains[i].strip()) for i in range(0, len(domains))]\n except Exception:\n GenralFunc.pprint(\"Looks like their is something wrong with the url list you provided\", \"fatal\")\n exit(-1)\n for i in range(0, len(clean)):\n domain_class_list.append(Domain(args, clean[i]))\n if args[\"--crawl\"] != str(False):\n GenralFunc.pprint(\"Crawl mode selected\", \"underline\")\n pass\n else:\n # Only does this if their is a single target\n GenralFunc.pprint(\"Single target mode selected\", \"underline\")\n domain = Domain(args)\n domain.start()\n\n","sub_path":"src/crabstick.py","file_name":"crabstick.py","file_ext":"py","file_size_in_byte":9394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"615442843","text":"\nimport sys\n\ndef unicode_table():\n\tfor i in range(0,256):\n\t\tfor j in range(0,256):\n\t\t\tprint(chr(((i+j)%256)),end=' ')\n\t\tprint('')\n\ndef encrypt_text(plain,key):\n\ti = 0\n\tch = ''\n\tfor p in plain:\n\t\tch += chr((ord(p)+ord(key[i%len(key)]))%265)\n\t\ti+=1\n\treturn ch\n\ndef decrypt_text(ch,key):\n\ti = 0\n\tplain = ''\n\tfor c in ch:\n\t\tplain += chr(abs((ord(c)-ord(key[i%len(key)]))%265))\n\t\ti+=1\n\treturn plain\n\ndef save_file(ch):\n\tfile = open('pesan.txt','w+')\n\tfile.write(ch)\n\tfile.close()\n\t\ndef read_file(file):\n\ttry:\n\t\tfile = open(file,'r')\n\t\tif file.mode == 'r':\n\t\t\tcontent = file.read()\n\t\t\treturn content\n\texcept FileNotFoundError:\n\t\tprint('File ',file,' Not Found!')\n\t\tsys.exit()\n\ndef main():\n\tif(len(sys.argv)<=1):\n\t\tprint('\\n','-'*18,'HELP','-'*18)\n\t\tprint(' example : ',sys.argv[0],' -e filename.txt \\n')\n\t\tprint(' -e || --encrypt : Encrypt Message from File')\n\t\tprint(' -d || --decrypt : Decrypt Message from File')\n\t\tprint(' -t : Show Table')\n\t\tprint('-'*42,'\\n')\n\telif (sys.argv[1]=='-e' or sys.argv[1]=='--encrypt'):\n\t\ttry:\n\t\t\tcontent = read_file(sys.argv[2])\n\t\t\tkey = input('Key : ')\t\t\n\t\t\tch = encrypt_text(content,key)\n\t\t\tsave_file(ch)\n\t\t\tprint('Encrypt Completed!')\n\t\texcept IndexError:\n\t\t\tprint(' you need filename.txt')\n\n\telif (sys.argv[1]=='-d' or sys.argv[1]=='--decrypt'):\n\t\ttry:\n\t\t\tcontent = read_file(sys.argv[2])\n\t\t\tkey = input('Key : ')\t\t\n\t\t\tch = decrypt_text(content,key)\n\t\t\tsave_file(ch)\n\t\t\tprint('Decrypt Completed!')\n\t\texcept IndexError:\n\t\t\tprint(' you need filename.txt')\n\telif (sys.argv[1]=='-t'):\n\t\tunicode_table()\n\telse:\n\t\tsys.exit()\n\nif __name__ == \"__main__\":\n\tmain()\n\t","sub_path":"Vigenere-cipher/VigenereCipher.py","file_name":"VigenereCipher.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"25332481","text":"#!/usr/bin/env python\n\n'''\nFind binaries which contain trap instructions\n'''\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport re\nimport subprocess\n\ndef is_macho(path):\n try:\n test = subprocess.check_output('file \"{0}\"'.format(path), shell=True)\n return ': Mach-O' in test\n except:\n pass\n return False\n\ndef is_trapping_binary(path):\n if not is_macho(path):\n return False\n try:\n disasm = subprocess.check_output('otool -tv \"{0}\"'.format(path), shell=True)\n lines = disasm.split('\\n')\n for i, line in enumerate(lines[1:]):\n prev_line = lines[i]\n if 'ud2' in line and 'call' not in prev_line:\n print(\"\\n\", end='')\n print(prev_line)\n print(line)\n return True\n except:\n pass\n return False\n\ndef find_trapping_binaries(path, excludes):\n for dirpath, dirnames, filenames in os.walk(path, followlinks=True):\n print(\".\", end='', sep='')\n\n if excludes:\n excluded_indices = [idx for idx, path in enumerate(dirnames)\n if re.search(excludes, path)]\n for idx in reversed(excluded_indices):\n del dirnames[idx]\n \n for filename in filenames:\n if excludes and re.search(excludes, filename):\n continue\n fpath = os.path.join(dirpath, filename)\n if is_trapping_binary(fpath):\n print(\" - Found trapping binary: {0}\".format(fpath))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('path')\n parser.add_argument('--exclude', default='')\n args = parser.parse_args()\n\n excludes = None\n if args.exclude:\n excludes = re.compile(args.exclude)\n find_trapping_binaries(args.path, excludes)\n","sub_path":"find-trapping-binaries.py","file_name":"find-trapping-binaries.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180212076","text":"import xlsxwriter\n\nclass Exporter:\n def __init__(self):\n pass\n\n @staticmethod\n def export_grid(grid, path):\n workbook = xlsxwriter.Workbook(path)\n worksheet = workbook.add_worksheet()\n\n bold = workbook.add_format({'bold': True})\n\n for col in range(grid.GetNumberCols()):\n col_name = grid.GetColLabelValue(col)\n # write title of column\n worksheet.write(0, col, col_name, bold)\n max_width = len(col_name)\n for row in range(grid.GetNumberRows()):\n val = grid.GetCellValue(row, col)\n if val.count('.') == 1:\n val = val.replace('.', ',')\n max_width = max(max_width, len(val))\n # write value of column\n worksheet.write(1+row, col, val)\n worksheet.set_column(col, col, max_width + 1)\n\n workbook.close()\n","sub_path":"classes/exporter.py","file_name":"exporter.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"622146434","text":"from flask import Flask, render_template, request, url_for, jsonify, redirect\nfrom flask_bootstrap import Bootstrap\nimport os\nfrom sklearn.externals import joblib\n\n\napp = Flask(__name__)\nBootstrap(app)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/url-detect', methods=[\"GET\",'POST'])\ndef urlPredict():\n if request.method == \"GET\":\n return render_template('url-detect-input.html')\n\n req = request.values\n resp = {\"code\":200, 'msg':\"提交成功\",\"data\":{}}\n url = req['url'] if 'url' in req else ''\n\n\n if not url:\n resp['code'] = -1\n resp['msg'] = \"请输入符合格式的网址\"\n return jsonify(resp)\n\n vectorizer, model = loadUrlDetect()\n url_vector = vectorizer.transform([url])\n predicted = model.predict(url_vector)\n app.logger.error(predicted)\n link = url_for('urlResult', url=url, result=predicted[0])\n resp['link'] = str(link)\n return jsonify(resp)\n #return jsonify(resp)\n #return render_template('url-detect-result.html')\n\n@app.route('/url-detect-result')\ndef urlResult():\n req = request.values\n resp_data = {}\n result_id = req['result'] if 'result' in req else ''\n test_link = req['url'] if 'url' in req else ''\n if not result_id or not test_link:\n return redirect('/')\n\n resp_data['test_link'] = test_link\n resp_data['result_id'] = int(result_id)\n\n return render_template('url-detect-result.html', **resp_data)\n\n@app.route('/domain-name', methods=[\"GET\",'POST'])\ndef domainPredict():\n if request.method == \"GET\":\n return render_template('domain-name-input.html')\n\n req = request.values\n resp = {\"code\": 200, 'msg': \"提交成功\", \"data\": {}}\n domain_name = req['domain_name'] if 'domain_name' in req else ''\n\n if not domain_name:\n resp['code'] = -1\n resp['msg'] = \"请输入符合格式的域名\"\n return jsonify(resp)\n\n vectorizer, model = loadDomainModel()\n domain_name_vector = vectorizer.transform([domain_name])\n predicted = model.predict(domain_name_vector)\n app.logger.error(predicted)\n link = url_for('domainResult', domain_name=domain_name, result=predicted[0])\n app.logger.error(link)\n resp['link'] = str(link)\n return jsonify(resp)\n\n@app.route('/domain-name-result')\ndef domainResult():\n req = request.values\n resp_data = {}\n result_id = req['result'] if 'result' in req else ''\n test_link = req['domain_name'] if 'domain_name' in req else ''\n if not result_id or not test_link:\n return redirect('/')\n\n resp_data['test_link'] = test_link\n resp_data['result_id'] = int(result_id)\n\n return render_template('domain-name-result.html', **resp_data)\n\n@app.route('/adfa-ld', methods=[\"GET\",'POST'])\ndef adfaldPredict():\n if request.method == \"GET\":\n return render_template('ADFA-LD/adfald-input.html')\n\n req = request.values\n resp = {\"code\": 200, 'msg': \"提交成功\", \"data\": {}}\n adfa_ld = req['adfa_ld'] if 'adfa_ld' in req else ''\n\n if not adfa_ld:\n resp['code'] = -1\n resp['msg'] = \"请输入符合格式的 systemcall api\"\n return jsonify(resp)\n\n vectorizer, model, transformer = loadADFALD()\n\n adfa_ld = [adfa_ld]\n adfa_ld_vector = vectorizer.transform(adfa_ld)\n adfa_ld_vector = transformer.transform(adfa_ld_vector)\n adfa_ld_vector = adfa_ld_vector.toarray()\n predicted = model.predict(adfa_ld_vector)\n\n app.logger.error(predicted)\n\n link = url_for('adfaldResult', adfa_ld=adfa_ld, result=predicted[0])\n resp['link'] = str(link)\n return jsonify(resp)\n\n@app.route('/adfa-ld-result')\ndef adfaldResult():\n req = request.values\n resp_data = {}\n result_id = req['result'] if 'result' in req else ''\n test_api = req['adfa_ld'] if 'adfa_ld' in req else ''\n if not result_id or not test_api:\n return redirect('/')\n\n resp_data['test_api'] = test_api\n resp_data['result_id'] = int(result_id)\n\n return render_template('/ADFA-LD/adfa-ld-result.html', **resp_data)\n\n\n\n\ndef loadUrlDetect():\n vectorizer = joblib.load('./machine_learning_models/url_detection/vectroizer.pkl')\n model = joblib.load('./machine_learning_models/url_detection/model.pkl')\n return vectorizer, model\n\ndef loadDomainModel():\n vectorizer = joblib.load('./machine_learning_models/domain_name/vectroizer.pkl')\n model = joblib.load('./machine_learning_models/domain_name/model.pkl')\n return vectorizer, model\n\ndef loadADFALD():\n vectorizer = joblib.load('./machine_learning_models/ADFA-LD/vectroizer.pkl')\n model = joblib.load('./machine_learning_models/ADFA-LD/model.pkl')\n transformer = joblib.load('./machine_learning_models/ADFA-LD/transformer.pkl')\n return vectorizer, model, transformer\n\nif __name__ == '__main__':\n # vectorizer, model = loadUrlDetect()\n\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"486705774","text":"import sys\nimport argparse\nimport math\n\ndef max_length(wordlist):\n longest = 0\n for word in wordlist:\n length = len(word)\n if length > longest:\n longest = length\n return longest\n\ndef count_lengths(wordlist):\n longest = max_length(wordlist)\n wordlist = list(set(wordlist))\n length_counts = [0]*longest\n for word in wordlist:\n length_counts[len(word)-1] += 1\n return length_counts\n\ndef print_table(length_counts, max_lines):\n longest = len(length_counts)\n most = max(length_counts)\n most_index = length_counts.index(most)\n\n if max_lines < most:\n scaling_factor = max_lines/most\n else:\n scaling_factor = 1\n\n scaled_counts = [math.floor(count*scaling_factor)\n for count in length_counts]\n\n row_format = \"{:>3}\" * longest\n print(row_format.format(*range(1, longest+1)))\n for row_number in range(0, max(scaled_counts)):\n row = ['*' if scaled_counts[col] != 0 else '' for col in\n range(0, longest)]\n scaled_counts = [length - 1 if length > 0 else 0\n for length in scaled_counts]\n print(row_format.format(*row))\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description=\"Make a graph of word\"\n \" lengths.\")\n parser.add_argument('wordlist', type=argparse.FileType('r'),\n help=\"List of words\")\n parser.add_argument('-m', type=int, help=\"Maximum number of lines\"\n \" for the chart to occupy.\")\n args = parser.parse_args()\n\n wordlist = args.wordlist.read().split()\n\n print_table(count_lengths(wordlist), args.m)\n","sub_path":"wordlengths.py","file_name":"wordlengths.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"113486699","text":"# -*- coding: utf-8 -*-\nimport sys\nimport uno\nimport unohelper\nfrom com.sun.star.task import XJob\n\nfrom com.sun.star.beans import PropertyValue\nfrom com.sun.star.embed.EmbedStates import UI_ACTIVE, ACTIVE, \\\n INPLACE_ACTIVE, LOADED, RUNNING\nfrom com.sun.star.text.TextContentAnchorType import AS_CHARACTER\n\n\n# ORE = OSSII URE\nclass ORE:\n '''Frequently used methods in office context'''\n def __init__(self, ctx=uno.getComponentContext()):\n self.ctx = ctx\n self.smgr = self.ctx.ServiceManager\n\n def createUnoService(self, service):\n return self.smgr.createInstance(service)\n\n def getCoreReflection(self):\n sService = 'com.sun.star.reflection.CoreReflection'\n return self.createUnoService(sService)\n\n def createUnoStruct(self, cTypeName):\n \"\"\"Create a UNO struct and return it.\n Similar to the function of the same name in OOo Basic.\n \"\"\"\n oCoreReflection = self.getCoreReflection()\n if oCoreReflection is None:\n return None\n # Get the IDL class for the type name\n oXIdlClass = oCoreReflection.forName(cTypeName)\n if oXIdlClass is None:\n return None\n # Create the struct.\n oReturnValue, oStruct = oXIdlClass.createObject(None)\n return oStruct\n\n def getDesktop(self):\n sService = 'com.sun.star.frame.Desktop'\n return self.smgr.createInstanceWithContext(sService, self.ctx)\n\n def getCurrentComponent(self):\n return self.getDesktop().getCurrentComponent()\n\n def getCurrentFrame(self):\n return self.getDesktop().getCurrentFrame()\n\n ## create/open document\n # @param string doc location\n # @param bool hide/show doc after open doc\n # @return object\n def createNewDoc(self, docLoc=None, hidden=False):\n sDocLoc = docLoc\n if docLoc is None:\n sDocLoc = 'private:factory/swriter'\n p1 = PropertyValue()\n p1.Name, p1.Value = 'Hidden', hidden\n\n return self.getDesktop().\\\n loadComponentFromURL(sDocLoc, '_blank', 0, (p1,))\n\n # Insert the picture object into the text, at current cursor position.\n def createNewPicObj(self, picFile, doc, cur, text, w, h):\n oGraphic = doc.createInstance('com.sun.star.text.GraphicObject')\n\n oGraphic.AnchorType = AS_CHARACTER\n oGraphic.GraphicURL = picFile\n #oCur.gotoEnd( False )\n\n if w == -1 and h == -1:\n text.insertTextContent(cur, oGraphic, False)\n oSize = oGraphic.ActualSize\n oGraphic.Width, oGraphic.Height = oSize.Width, oSize.Height\n else:\n oGraphic.Width, oGraphic.Height = w, h\n text.insertTextContent(cur, oGraphic, False)\n\n\n## 關閉文件上不必要的 window\n# 使文件視窗看起來只有一個視窗\n# @param frame object\ndef hideAllUI(frame):\n layoutMgr = frame.LayoutManager\n\n # 關閉浮動工具列\n for elm in layoutMgr.getElements():\n resURL = elm.ResourceURL\n layoutMgr.hideElement(resURL)\n layoutMgr.HideCurrentUI = True\n\n # 關閉表單設計模式\n frame.Controller.FormDesignMode = False\n try: # for writer\n # 不顯示非列印字元\n frame.Controller.ViewSettings.ShowNonprintingCharacters = False\n # 不顯示水平線\n frame.Controller.ViewSettings.ShowHoriRuler = False\n # 不顯示文字邊界框\n frame.Controller.ViewSettings.ShowTextBoundaries = False\n except:\n pass\n try: # for calc\n frame.Controller.SheetTabs = False\n frame.Controller.ShowNotes = False\n frame.Controller.ColumnRowHeaders = False\n except:\n pass\n\n\n## Bridge to call via Basic.createUnoService(\"...\")\nclass UtilsImp(unohelper.Base, XJob):\n def __init__(self, ctx):\n self.ctx = ctx\n\n def execute(self, args):\n for prop in args:\n if prop.Name == 'createNewDoc':\n docLoc, hidden = prop.Value\n return ORE().createNewDoc(docLoc, hidden)\n if prop.Name == 'hideAllUI':\n hideAllUI(frame=prop.Value)\n return\n\n ## link to ORE().createNewPicObj()\n # used by bridge from Basic\n # @param picFile string\n # @param doc object\n # @param cur object\n # @param text object\n if prop.Name == 'createNewPicObj':\n picFile, doc, cur, text, w, h = prop.Value\n ORE().createNewPicObj(picFile, doc,\n cur, text, w, h)\n ## get windows version string\n # @return str\n if prop.Name == 'getWindowsVer':\n import platform\n bit = platform.architecture()[0]\n major = sys.getwindowsversion().major\n minor = sys.getwindowsversion().minor\n product_type = sys.getwindowsversion().product_type\n buf = platform.platform().split('-')\n return \"%s %s %s\" % (buf[0], buf[1], bit)\n\n\ng_ImplementationHelper = unohelper.ImplementationHelper()\ng_ImplementationHelper.addImplementation(UtilsImp,\n \"ndc.UtilsImp\",\n (\"com.sun.star.task.Job\",),)\n","sub_path":"src/Python/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"370209769","text":"# -*- coding: utf-8 -*-\n\nimport re,urllib,urlparse\n\nfrom resources.lib.libraries import cleantitle\nfrom resources.lib.libraries import client\nfrom resources.lib import resolvers\n\n\nclass source:\n def __init__(self):\n self.base_link = 'http://moviestorm.eu'\n self.tvsearch_link = '/series/all/'\n self.episode_link = '%s?season=%01d&episode=%01d'\n\n\n def get_show(self, imdb, tvdb, tvshowtitle, year):\n try:\n query = urlparse.urljoin(self.base_link, self.tvsearch_link)\n\n result = client.source(query)\n\n tvshowtitle = cleantitle.tv(tvshowtitle)\n\n result = zip(client.parseDOM(result, 'a', {'class': 'underilne'}, 'href'), client.parseDOM(result, 'a', {'class': 'underilne'}))\n result = [i[0] for i in result if tvshowtitle == cleantitle.tv(i[1])][0]\n check = urlparse.urljoin(self.base_link, result)\n check = client.source(check)\n if not str(imdb) in check: raise Exception()\n\n try: url = re.compile('//.+?(/.+)').findall(result)[0]\n except: url = result\n url = client.replaceHTMLCodes(url)\n url = url.encode('utf-8')\n return url\n except:\n return\n\n\n def get_episode(self, url, imdb, tvdb, title, date, season, episode):\n if url == None: return\n\n url = self.episode_link % (url, int(season), int(episode))\n url = client.replaceHTMLCodes(url)\n url = url.encode('utf-8')\n return url\n\n\n def get_sources(self, url, hosthdDict, hostDict, locDict):\n try:\n sources = []\n\n if url == None: return sources\n\n url = urlparse.urljoin(self.base_link, url)\n\n result = client.source(url)\n result = client.parseDOM(result, 'div', attrs = {'class': 'links'})[0]\n result = client.parseDOM(result, 'tr')\n result = [(client.parseDOM(i, 'td', attrs = {'class': 'quality_td'})[0], client.parseDOM(i, 'a', ret='href')[-1]) for i in result]\n\n ts_quality = ['CAM', 'TS']\n links = [i for i in result if not any(x in i[0] for x in ts_quality)]\n if len(links) == 0: links = result\n\n for i in links:\n try:\n url = i[1]\n url = client.replaceHTMLCodes(url)\n url = url.encode('utf-8')\n\n host = re.sub('.+?/exit/\\d*-|[.].+?[.]html|http://(|www[.])|/.+|[.].+$','', i[1])\n host = host.strip().lower()\n if not host in hostDict: raise Exception()\n host = client.replaceHTMLCodes(host)\n host = host.encode('utf-8')\n\n if any(x in i[0] for x in ts_quality): quality = 'CAM'\n else: quality = 'SD'\n\n sources.append({'source': host, 'quality': quality, 'provider': 'Moviestorm', 'url': url})\n except:\n pass\n\n return sources\n except:\n return sources\n\n\n def resolve(self, url):\n try:\n if url.startswith(self.base_link):\n result = client.request(url)\n url = client.parseDOM(result, 'a', ret='href', attrs = {'class': 'real_link'})[0]\n\n url = resolvers.request(url)\n return url\n except:\n return\n\n\n","sub_path":"plugin.video.doofree_old/resources/lib/sources/moviestorm_tv_null.py","file_name":"moviestorm_tv_null.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"130879341","text":"# Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах\r\n# (в рамках первых трех уроков)\r\n\r\nimport sys\r\n\r\n\r\nclass SumMemory:\r\n\r\n def __init__(self):\r\n \"\"\"\r\n _sum_memory - общее количество занятой памяти\r\n _types - словарь вида {'type': [count, size]}\r\n \"\"\"\r\n self._sum_memory = 0\r\n self._types = {}\r\n\r\n def extend(self, *args):\r\n for obj in args:\r\n self._add(obj)\r\n\r\n def _add(self, obj):\r\n spam = sys.getsizeof(obj)\r\n eggs = str(type(obj))\r\n self._sum_memory += spam\r\n if eggs in self._types:\r\n self._types[eggs][0] += 1\r\n self._types[eggs][1] += spam\r\n else:\r\n self._types[eggs] = [1, 1]\r\n self._types[eggs][1] = spam\r\n\r\n if hasattr(obj, '__iter__'):\r\n if hasattr(obj, 'items'):\r\n for key, value in obj.items():\r\n self._add(key)\r\n self._add(value)\r\n elif not isinstance(obj, str):\r\n for item in obj:\r\n self._add(item)\r\n\r\n def print_sum(self):\r\n print(f'Переменные заняли в сумме {self._sum_memory} байт')\r\n for key, value in self._types.items():\r\n print(f'Объекты класса {key} в количестве {value[0]} заняли {value[1]} байт')\r\n\r\n","sub_path":"Python/0_algorithms/hw_6/sum_memory.py","file_name":"sum_memory.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"169668886","text":"from django.conf.urls import *\nfrom helpdesk.views import kb\n\nurlpatterns = [\n url(r'^kb/$',\n kb.index,\n name='helpdesk_kb_index'),\n\n url(r'^kb/(?P- [0-9]+)/$',\n kb.item,\n name='helpdesk_kb_item'),\n\n url(r'^kb/(?P
- [0-9]+)/vote/$',\n kb.vote,\n name='helpdesk_kb_vote'),\n\n url(r'^kb/(?P[A-Za-z0-9_-]+)/$',\n kb.category,\n name='helpdesk_kb_category'),\n]\n","sub_path":"helpdesk/urls/kb.py","file_name":"kb.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"393278304","text":"# the path to the directory in which the source files are stored\ndirectory = \"/home/alex/School/WPI/ID 2050/Deliverables/flight/app\"\n\n## the path to the file in which current flight data are stored\nflightdata = directory + \"/flights.dat\"\n\n### the interval (24 hours, expressed in seconds) for which a recently landed flight is relevant to the program\ninterval = 1 * 24 * 60 * 60\n\n### the maximum age (7 days, expressed in seconds) a flight may have before it is archived\narchiveage = 7 * 24 * 60 * 60\n\n### the function which estimates the ratio of tourists to passenger capacity for a given flight\ndef ratio(flight):\n\treturn 0.125\n\n## the path to the file in which archived flight data is stored\narchivedata = directory + \"/archive.dat\"\n\n## the path to the file in which data on different aircraft types are stored\ntypedata = directory + \"/types.dat\"\n\n### the placeholder string to indicate that the number of seats in a flight is not known\ntypeunknown = \"UNKNOWN\"\n\n## the path to the file in which log information is stored in a human-readable format\nlogdata = directory + \"/log.txt\"\n\n# the url of the web resource which provides flight data\nurl = \"http://flightradar24.com/airport/vce\"\n\n## the unique string which indicates the start of a list of flights in the web resouce\nstartstring = \"\"\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"639985615","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\nimport sys\nimport mxnet as mx\nimport numpy as np\nfrom random import randint\nimport warnings\nimport collections\nimport ctypes\nfrom mxnet import amp\nimport pytest\nfrom mxnet.test_utils import set_default_device, same_symbol_structure\nfrom mxnet.gluon.model_zoo.vision import get_model\nfrom mxnet.gluon import SymbolBlock, nn, rnn\nfrom mxnet.operator import get_all_registered_operators_grouped\ncurr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\nsys.path.insert(0, os.path.join(curr_path, '../unittest'))\nfrom common import assert_raises_cudnn_not_satisfied\nsys.path.insert(0, os.path.join(curr_path, '../train'))\nset_default_device(mx.gpu(0))\n\n@pytest.fixture()\ndef amp_tests(request):\n def teardown():\n mx.nd.waitall()\n\n request.addfinalizer(teardown)\n\ndef test_amp_coverage(amp_tests):\n conditional = [item[0] for item in amp.lists.symbol_fp16.CONDITIONAL_FP32_FUNCS]\n\n # Check for duplicates\n for a in [amp.lists.symbol_fp16.FP16_FUNCS,\n amp.lists.symbol_fp16.FP16_FP32_FUNCS,\n amp.lists.symbol_fp16.FP32_FUNCS,\n amp.lists.symbol_fp16.WIDEST_TYPE_CASTS,\n conditional]:\n ret = [item for item, count in collections.Counter(a).items() if count > 1]\n assert ret == [], \"Elements \" + str(ret) + \" are duplicated in the AMP lists.\"\n\n t = []\n for a in [amp.lists.symbol_fp16.FP16_FUNCS,\n amp.lists.symbol_fp16.FP16_FP32_FUNCS,\n amp.lists.symbol_fp16.FP32_FUNCS,\n amp.lists.symbol_fp16.WIDEST_TYPE_CASTS,\n conditional]:\n t += a\n ret = [item for item, count in collections.Counter(t).items() if count > 1]\n assert ret == [], \"Elements \" + str(ret) + \" exist in more than 1 AMP list.\"\n\n # Check the coverage\n covered = set(t)\n ops = get_all_registered_operators_grouped()\n required = set(k for k in ops\n if not k.startswith((\"_backward\", \"_contrib_backward\", \"_npi_backward\")) and\n not k.endswith(\"_backward\"))\n\n extra = covered - required\n assert not extra, f\"{len(extra)} operators are not needed in the AMP lists: {sorted(extra)}\"\n\n guidelines = \"\"\"Please follow these guidelines for choosing a proper list:\n - if your operator is not to be used in a computational graph\n (e.g. image manipulation operators, optimizers) or does not have\n inputs, put it in FP16_FP32_FUNCS list,\n - if your operator requires FP32 inputs or is not safe to use with lower\n precision, put it in FP32_FUNCS list,\n - if your operator supports both FP32 and lower precision, has\n multiple inputs and expects all inputs to be of the same\n type, put it in WIDEST_TYPE_CASTS list,\n - if your operator supports both FP32 and lower precision and has\n either a single input or supports inputs of different type,\n put it in FP16_FP32_FUNCS list,\n - if your operator is both safe to use in lower precision and\n it is highly beneficial to use it in lower precision, then\n put it in FP16_FUNCS (this is unlikely for new operators)\n - If you are not sure which list to choose, FP32_FUNCS is the\n safest option\"\"\"\n diff = required - covered\n assert not diff, f\"{len(diff)} operators {sorted(diff)} do not exist in AMP lists (in \" \\\n f\"python/mxnet/amp/lists/symbol_fp16.py) - please add them. \" \\\n f\"\\n{guidelines}\"\n\n@pytest.mark.skip(reason='Error during waitall(). Tracked in #18099')\n@assert_raises_cudnn_not_satisfied(min_version='5.1.10')\ndef test_amp_conversion_rnn(amp_tests):\n with mx.Device(mx.gpu(0)):\n model = nn.HybridSequential()\n model.add(rnn.LSTM(hidden_size=10, num_layers=2, bidirectional=True))\n model.add(nn.Dense(2))\n model.initialize()\n model.hybridize()\n out = model(mx.nd.ones((2, 3, 4)))\n new_model = amp.convert_hybrid_block(model)\n out2 = new_model(mx.nd.ones((2, 3, 4)))\n mx.test_utils.assert_almost_equal(out.asnumpy(), out2.asnumpy(), atol=1e-2, rtol=1e-2)\n\n\n@mx.util.use_np\ndef test_fp16_offline_casting():\n class TestNet(nn.HybridBlock):\n def __init__(self):\n super().__init__()\n self.lp16_op1 = nn.Conv2D(4, 3)\n self.lp16_op2 = nn.Conv2DTranspose(4, 3)\n self.fp32_op = nn.Dense(4)\n\n def forward(self, x):\n x = self.lp16_op1(x)\n x = self.lp16_op2(x)\n x = x.reshape(x.shape[0], -1)\n x = self.fp32_op(x)\n return x\n\n net = TestNet()\n net.initialize()\n data_example = mx.np.random.uniform(-1, 1, (4, 3, 16, 16))\n lp_net = amp.convert_hybrid_block(net, data_example, target_dtype='float16',\n target_dtype_ops=['Convolution'], fp32_ops=['FullyConnected'],\n cast_params_offline=True, device=mx.current_context())\n lp_net(data_example)\n for name, data in lp_net.collect_params().items():\n assert data.dtype == (np.float32 if 'fp32_op' in name else 'float16')\n\n\n@mx.util.use_np\ndef test_fp16_offline_casting_shared_params():\n COMMON_SIZE = 4\n\n class TestNet(nn.HybridBlock):\n def __init__(self):\n super().__init__()\n self.lp16_op1 = nn.Dense(COMMON_SIZE)\n self.lp16_op2 = nn.Dense(COMMON_SIZE)\n self.lp16_op2.share_parameters({'weight': self.lp16_op1.weight})\n self.fp32_op = nn.Conv1D(COMMON_SIZE, 3)\n self.fp32_op.share_parameters({'bias': self.lp16_op2.bias})\n\n def forward(self, x):\n x = self.lp16_op1(x)\n x1 = self.lp16_op2(x)\n x2 = mx.np.expand_dims(x, 1)\n x2 = self.fp32_op(x2)\n x2 = nn.Flatten()(x2)\n x = mx.np.concat((x1, x2), axis=1)\n return x\n\n net = TestNet()\n net.initialize()\n data_example = mx.np.random.uniform(-1, 1, (4, COMMON_SIZE))\n lp_net = amp.convert_hybrid_block(net, data_example, target_dtype='float16',\n target_dtype_ops=['FullyConnected'], fp32_ops=['Convolution'],\n cast_params_offline=True, device=mx.current_context())\n lp_net(data_example)\n for name, data in lp_net.collect_params().items():\n assert data.dtype == (np.float32 if 'fp32_op' in name else 'float16')\n","sub_path":"tests/python/gpu/test_amp.py","file_name":"test_amp.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"68361263","text":"from GJEMS.morph.swcTreeRep import *\nimport numpy as np\nimport os\nimport matplotlib as mpl\nmpl.rcParams['text.usetex'] = True\nmpl.rcParams['axes.labelsize'] = 'large'\nmpl.rcParams['font.family'] = 'serif'\nmpl.rcParams['font.sans-serif'] = 'computer modern roman'\nimport matplotlib.pyplot as plt\nfrom scipy.stats import ttest_ind\n\ndef getTotalLenVsEucDist(swc, bins, origin=None):\n\n swcTree = importSWC2Tree(swc)\n branchVols = getBranchVol(swcTree)\n euchDists = getBranchEucDist(swcTree, origin)\n\n totalVolPerBin = []\n for binInd in range(len(bins) - 1):\n mask = (euchDists >= bins[binInd]) & (euchDists < bins[binInd + 1])\n totalVolPerBin.append(branchVols[mask].sum())\n\n return np.array(totalVolPerBin)\n\nbinEdges = np.arange(0, 300, 5)\nbinCenters = binEdges[:-1] + 0.5 * (binEdges[1] - binEdges[0])\n# ----------------------------------------------------------------------------------------------------------------------\n#\n# foragerSWCPath = 'testFiles/DL-Int1_v2/'\n#\n# foragerNrns = [\n# 'HB130313-4.swc',\n# 'HB130322-1.swc',\n# # 'HB130326-2.swc',\n# 'HB130408-1.swc',\n# 'HB130425-1.swc',\n# 'HB130501-2.swc',\n# 'HB130705-1.swc',\n# 'HB140424-1.swc',\n#\n# ]\n# origin = None\n\n# ----------------------------------------------------------------------------------------------------------------------\n\nforagerSWCPath = 'shapeBasedAlignment/Results/DL-Int1_v2_MultipleAlignment/'\n\nforagerNrns = [\n 'HB130313-4_aligned.swc',\n 'HB130322-1_aligned.swc',\n # 'HB130326-2_aligned.swc',\n 'HB130408-1_aligned.swc',\n 'HB130425-1_aligned.swc',\n 'HB130501-2_aligned.swc',\n 'HB130705-1_aligned.swc',\n 'HB140424-1_aligned.swc',\n ]\norigin = [0, 0, 0]\nforagerLabels = [x[:-12] for x in foragerNrns]\n# ----------------------------------------------------------------------------------------------------------------------\n\nfSWCFiles = [os.path.join(foragerSWCPath, x) for x in foragerNrns]\n\n\n\nforagerVolVsDists = {}\n\nfig1 = plt.figure()\nplt.show(block=False)\nfig2 = plt.figure()\nplt.show(block=False)\ncols = plt.cm.spectral(np.linspace(0, 1, len(foragerNrns)))\n\nfor swcInd, swc in enumerate(fSWCFiles):\n\n foragerVolVsDist = getTotalLenVsEucDist(swc, binEdges, origin)\n foragerVolVsDist /= foragerVolVsDist.sum()\n foragerVolVsDists[foragerNrns[swcInd][:-4]] = foragerVolVsDist\n plt.figure(fig1.number)\n plt.plot(binCenters, foragerVolVsDist, color=cols[swcInd], marker='o', mfc=cols[swcInd])\n plt.figure(fig2.number)\n fplot, = plt.plot(binCenters, foragerVolVsDist, color='b', marker='o', mfc='b')\nplt.legend(foragerLabels)\nplt.draw()\n\n# ----------------------------------------------------------------------------------------------------------------------\n# newlyEmergedSWCPath = 'testFiles/DL-Int1_v2/'\n#\n# newlyEmergedNrns = [\n# 'HB130523-3.swc',\n# 'HB130605-1.swc',\n# # 'HB130605-2.swc',\n# 'HB140813-3.swc',\n# 'HB140917-1.swc',\n# 'HB140930-1.swc',\n# 'HB141030-1.swc',\n# ]\n# origin = None\n# ----------------------------------------------------------------------------------------------------------------------\nnewlyEmergedSWCPath = 'shapeBasedAlignment/Results/DL-Int1_v2_MultipleAlignment/'\n\nnewlyEmergedNrns = [\n 'HB130523-3_aligned.swc',\n 'HB130605-1_aligned.swc',\n # 'HB130605-2_aligned.swc',\n 'HB140813-3_aligned.swc',\n 'HB140917-1_aligned.swc',\n 'HB140930-1_aligned.swc',\n 'HB141030-1_aligned.swc',\n ]\norigin = [0, 0, 0]\nneLabels = [x[:-12] for x in newlyEmergedNrns]\n# ----------------------------------------------------------------------------------------------------------------------\ncols = cols = plt.cm.spectral(np.linspace(0, 1, len(newlyEmergedNrns)))\nnSWCFiles = [os.path.join(newlyEmergedSWCPath, x) for x in newlyEmergedNrns]\n\nNEVolVsDists = {}\n\n\ncols = plt.cm.spectral(np.linspace(0, 1, len(newlyEmergedNrns)))\n\nfor swcInd, swc in enumerate(nSWCFiles):\n\n NEVolVsDist = getTotalLenVsEucDist(swc, binEdges, origin)\n NEVolVsDist /= NEVolVsDist.sum()\n NEVolVsDists[newlyEmergedNrns[swcInd][:-4]] = NEVolVsDist\n plt.figure(fig1.number)\n plt.plot(binCenters, NEVolVsDist, color=cols[swcInd], marker='s', mfc=cols[swcInd])\n plt.figure(fig2.number)\n nplot, = plt.plot(binCenters, NEVolVsDist, color='r', marker='s', mfc='r')\nplt.legend(neLabels)\nplt.draw()\n\nplt.figure(fig1.number)\nplt.legend(foragerLabels + neLabels)\nplt.xlabel('Distance from common reference point($\\mu m$)')\nplt.ylabel('Fraction of Volume')\nplt.draw()\nplt.figure(fig2.number)\nplt.legend([fplot, nplot], ['forager', 'newly emerged'])\nplt.xlabel('Distance from common reference point($\\mu m$)')\nplt.ylabel('Fraction of Volume')\nplt.draw()\n\ntempf = np.array(foragerVolVsDists.values())\nforagerSEM = tempf.std(axis=0) / np.sqrt(tempf.shape[0])\nforagerBinMean = tempf.mean(axis=0)\n\ntempn = np.array(NEVolVsDists.values())\nNESEM = tempn.std(axis=0) / np.sqrt(tempn.shape[0])\nNEBinMean = tempn.mean(axis=0)\n\nsignificances = []\ndiffs = []\nfor binInd in range(len(binCenters)):\n\n diff, p = ttest_ind(tempf[:, binInd], tempn[:, binInd])\n diffs.append(diff)\n significances.append(p)\n\nfig3 = plt.figure()\nplt.show(block=False)\nplt.errorbar(binCenters, foragerBinMean, foragerSEM, color='b', marker='o', mfc='b')\nplt.errorbar(binCenters, NEBinMean, NESEM, color='r', marker='s', mfc='r')\nfor pInd, p in enumerate(significances):\n if p < 0.1:\n y = max(foragerBinMean[pInd] + 3 * foragerSEM[pInd], NEBinMean[pInd] + 3 * NESEM[pInd])\n plt.plot(binCenters[pInd], [y], color='gray', marker='*', ms=10)\nplt.legend(['foragers', 'newly emerged'])\n# plt.title('p<0.1')\nplt.xlabel('Distance from common reference point($\\mu m$)')\nplt.ylabel('Fraction of Volume')\nplt.draw()\n\nfig4 = plt.figure()\nplt.show(block=False)\nplt.plot(binCenters, significances, 'b-o')\nplt.xlabel('Distance from common reference point($\\mu m$)')\nplt.ylabel('significance')\nplt.draw()","sub_path":"test_tmp/basicMorphoStats/compareVolVsDist.py","file_name":"compareVolVsDist.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"214348925","text":"# -*- coding: utf-8 -*-\nfrom StringIO import StringIO\n\nfrom pyramid.response import Response\n\nfrom bunch import Bunch\n\nfrom ..views import model_context, permalinker, ModelController, DeleteObjectWidget\nfrom .. import dynmenu as dm\nfrom ..object_widget import ObjectWidget, CompositeWidget\nfrom ..layer import Layer\n\nfrom .models import Style\n\n\ndef setup_pyramid(comp, config):\n DBSession = comp.env.core.DBSession\n\n class StyleObjectWidget(ObjectWidget):\n\n def is_applicable(self):\n return self.operation in ('create', 'edit')\n\n def populate_obj(self):\n ObjectWidget.populate_obj(self)\n\n self.obj.display_name = self.data['display_name']\n\n def widget_module(self):\n return 'style/Widget'\n\n def widget_params(self):\n result = ObjectWidget.widget_params(self)\n\n if self.obj:\n result['value'] = dict(display_name=self.obj.display_name)\n\n elif len(self.options['layer'].styles) == 0:\n result['value'] = dict(display_name=u\"Основной\")\n\n return result\n\n Style.object_widget = (\n (Style.identity, StyleObjectWidget),\n ('delete', DeleteObjectWidget),\n )\n\n class StyleController(ModelController):\n\n def create_context(self, request):\n layer = DBSession.query(Layer) \\\n .filter_by(id=request.matchdict['layer_id']) \\\n .one()\n request.require_permission(layer, 'style-write')\n\n identity = request.GET['identity']\n cls = Style.registry[identity]\n template_context = dict(\n obj=layer,\n dynmenu=(comp.env.layer.layer_menu, Bunch(\n obj=layer,\n request=request,\n )),\n subtitle=u\"Новый стиль\",\n )\n\n widget_options = dict(layer=layer)\n\n return locals()\n\n def edit_context(self, request):\n obj = DBSession.query(Style).filter_by(**request.matchdict).one()\n request.require_permission(obj.layer, 'style-write')\n\n identity = obj.cls\n cls = Style.registry[identity]\n obj = DBSession.query(cls).get(obj.id)\n\n template_context = dict(\n obj=obj,\n )\n\n widget_options = dict(layer=obj.layer)\n\n return locals()\n\n def delete_context(self, request):\n edit_context = self.edit_context(request)\n return dict(\n edit_context,\n redirect=edit_context['obj'].layer.permalink(request)\n )\n\n def widget_class(self, context, operation):\n class Composite(CompositeWidget):\n model_class = context['cls']\n\n return Composite\n\n def create_object(self, context):\n return context['cls'](\n layer=context['layer'],\n )\n\n def query_object(self, context):\n return context['obj']\n\n def template_context(self, context):\n return context['template_context']\n\n StyleController(\n 'style',\n url_base='/layer/{layer_id:\\d+}/style',\n ).includeme(config)\n\n @model_context(Style)\n def tms(request, obj):\n actual_class = Style.registry[obj.cls]\n obj = DBSession.query(Style) \\\n .with_polymorphic((actual_class, ))\\\n .filter_by(id=obj.id).one()\n\n request.require_permission(obj.layer, 'style-read')\n\n z = int(request.GET['z'])\n x = int(request.GET['x'])\n y = int(request.GET['y'])\n\n req = obj.render_request(obj.layer.srs)\n img = req.render_tile((z, x, y), 256)\n\n buf = StringIO()\n img.save(buf, 'png')\n buf.seek(0)\n\n return Response(body_file=buf, content_type='image/png')\n\n config.add_route('style.tms', '/style/{id:\\d+}/tms').add_view(tms)\n\n @model_context(Style)\n def image(request, obj):\n actual_class = Style.registry[obj.cls]\n obj = DBSession.query(Style) \\\n .with_polymorphic((actual_class, ))\\\n .filter_by(id=obj.id).one()\n\n request.require_permission(obj.layer, 'style-read')\n\n extent = map(float, request.GET['extent'].split(','))\n size = map(int, request.GET['size'].split(','))\n\n if extent[0] < obj.layer.srs.minx:\n # Костыль для 180\n extent = (\n extent[0] + obj.layer.srs.maxx - obj.layer.srs.minx, extent[1],\n extent[2] + obj.layer.srs.maxx - obj.layer.srs.minx, extent[3],\n )\n\n req = obj.render_request(obj.layer.srs)\n img = req.render_extent(extent, size)\n\n buf = StringIO()\n img.save(buf, 'png')\n buf.seek(0)\n\n return Response(body_file=buf, content_type='image/png')\n\n config.add_route('style.image', '/style/{id:\\d+}/image').add_view(image)\n\n @model_context(Style)\n def show(request, obj):\n actual_class = Style.registry[obj.cls]\n obj = DBSession.query(Style) \\\n .with_polymorphic((actual_class, ))\\\n .filter_by(id=obj.id).one()\n request.require_permission(obj.layer, 'style-read')\n\n return dict(\n obj=obj,\n )\n\n config.add_route('style.show', '/layer/{layer_id:\\d+}/style/{id:\\d+}') \\\n .add_view(show, renderer='obj.mako')\n\n Style.__dynmenu__ = dm.DynMenu(\n dm.Label('operation', u\"Операции\"),\n dm.Link(\n 'operation/edit', u\"Редактировать\",\n lambda args: args.request.route_url(\n 'style.edit',\n id=args.obj.id,\n layer_id=args.obj.layer_id\n )\n ),\n dm.Link(\n 'operation/delete', u\"Удалить\",\n lambda args: args.request.route_url(\n 'style.delete',\n id=args.obj.id,\n layer_id=args.obj.layer_id\n )\n ),\n )\n\n class LayerMenuExt(dm.DynItem):\n\n def build(self, kwargs):\n yield dm.Label('add-style', u\"Добавить стиль\")\n\n for cls in Style.registry:\n if cls.is_layer_supported(kwargs.obj):\n yield dm.Link(\n 'add-style/%s' % cls.identity,\n cls.cls_display_name,\n self._create_url(cls)\n )\n\n def _create_url(self, cls):\n return lambda kwargs: kwargs.request.route_url(\n 'style.create',\n layer_id=kwargs.obj.id,\n _query=dict(\n identity=cls.identity,\n )\n )\n\n Layer.__dynmenu__.add(LayerMenuExt())\n\n comp.env.layer.layer_page_sections.register(\n key='styles',\n priority=20,\n title=u\"Стили\",\n template=\"nextgisweb:templates/style/layer_section.mako\"\n )\n\n permalinker(Style, 'style.show', keys=('id', 'layer_id'))\n","sub_path":"nextgisweb/style/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"69248806","text":"# Now, train the GBM model:\nfrom h2o.estimators.gbm import H2OGradientBoostingEstimator\n\n# Load the data and prepare for modeling\nairlines_hex = h2o.import_file(\"http://h2o-public-test-data.s3.amazonaws.com/smalldata/airlines/allyears2k_headers.zip\")\n\n# Generate random numbers and create training, validation, testing splits\nr = airlines_hex.runif() # Random UNIForm numbers, one per row\nair_train_hex = airlines_hex[r < 0.6]\nair_valid_hex = airlines_hex[(r >= 0.6) & (r < 0.9)]\nair_test_hex = airlines_hex[r >= 0.9]\n\nmyX = [\"DayofMonth\", \"DayOfWeek\"]\n\nair_model = H2OGradientBoostingEstimator(\n distribution='bernoulli', ntrees=100,\n max_depth=4, learn_rate=0.1,\n sample_rate=0.6, col_sample_rate=0.7)\nair_model.train(x=myX, y=\"IsDepDelayed\",\n training_frame=air_train_hex)\n","sub_path":"h2o-docs/src/booklets/v2_2015/source/GBM_Vignette_code_examples/gbm_examplerun_stochastic.py","file_name":"gbm_examplerun_stochastic.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"638953373","text":"import re \nimport time \nimport os\nimport pickle\nimport numpy as np \nfrom bisect import bisect_left \nimport tensorflow as tf \nfrom tensorflow.contrib import learn \nfrom tflearn.data_utils import to_categorical, pad_sequences \nfrom TextCNN import * \nfrom utils import * \n\ntf.flags.DEFINE_integer(\"MAX_LENGTH_WORDS\", 200, \"Max length of url in words\") \ntf.flags.DEFINE_integer(\"MAX_LENGTH_CHARS\", 200, \"Max length of url in chars\") \ntf.flags.DEFINE_integer(\"MAX_LENGTH_SUBWORDS\",20, \"Max length of word in ngrams\") \ntf.flags.DEFINE_integer(\"MIN_WORD_FREQ\", 1, \"Minimum frequency of word to build vocabulary\") \ntf.flags.DEFINE_integer(\"EMB_DIM\", 32, \"embedding dimension size\") \ntf.flags.DEFINE_integer(\"NB_EPOCHS\",5, \"number of training epochs\") \ntf.flags.DEFINE_integer(\"BATCH_SIZE\", 128, \"Size of a training batch\") \ntf.flags.DEFINE_float(\"DEV_PERCENTAGE\", 0.001, \"portion of training used for dev\") \ntf.flags.DEFINE_string(\"FILE_DIR\",\"train_10000.txt\", \"directory of the training data\") \ntf.flags.DEFINE_string(\"OUTPUT_DIR\", \"runs/10000/\", \"directory o the output model\") \ntf.flags.DEFINE_integer(\"PRINT_EVERY\", 50, \"print training result every this number of steps\") \ntf.flags.DEFINE_integer(\"EVAL_EVERY\", 500, \"evaluate the model every this number of steps\") \ntf.flags.DEFINE_integer(\"CHECKPOINT_EVERY\", 500, \"Save a model every this number of steps\") \ntf.flags.DEFINE_float(\"L2_REG_LAMBDA\", 0.0, \"l2 lambda for regularization\") \ntf.flags.DEFINE_string(\"FILTER_SIZES\", \"3,4,5,6\", \"filter sizes of the convolution layer\")\ntf.flags.DEFINE_float(\"LR\", 0.001, \"learning rate of the optimizer\") \ntf.flags.DEFINE_integer(\"EMB_MODE\", 1, \"1: charCNN, 2: wordCNN, 3: char + wordCNN, 4: char-level wordCNN, 5: char + char-level wordCNN\") \ntf.flags.DEFINE_integer(\"DELIMIT_MODE\", 1, \"0: delimit by special chars, 1: delimit by special chars + each char as a word\")\n\nFLAGS = tf.flags.FLAGS\nFLAGS._parse_flags() \nprint(\"\\nParameters:\") \nfor attr, value in FLAGS.__flags.items(): \n print(\"{}={}\".format(attr, value))\nprint(\"\") \n\nurls, labels = read_data(FLAGS.FILE_DIR) \n\nhigh_freq_words = None\nif FLAGS.MIN_WORD_FREQ > 0: \n x1, word_reverse_dict = get_word_vocab(urls, FLAGS.MAX_LENGTH_WORDS, FLAGS.MIN_WORD_FREQ) \n high_freq_words = sorted(list(word_reverse_dict.values()))\n print(\"Number of words with freq >={}: {}\".format(FLAGS.MIN_WORD_FREQ, len(high_freq_words))) \n\nx, word_reverse_dict = get_word_vocab(urls, FLAGS.MAX_LENGTH_WORDS) \nword_x = get_words(x, word_reverse_dict, FLAGS.DELIMIT_MODE, urls)\nngramed_id_x, ngrams_dict, worded_id_x, words_dict = ngram_id_x(word_x, FLAGS.MAX_LENGTH_SUBWORDS, high_freq_words)\n\nchars_dict = ngrams_dict\nchared_id_x = char_id_x(urls, chars_dict, FLAGS.MAX_LENGTH_CHARS)\n\npos_x = []\nneg_x = []\nfor i in range(len(labels)):\n label = labels[i] \n if label == 1: \n pos_x.append(i)\n else: \n neg_x.append(i)\nprint(\"Overall Mal/Ben split: {}/{}\".format(len(pos_x), len(neg_x)))\npos_x = np.array(pos_x) \nneg_x = np.array(neg_x) \n\nx_train, y_train, x_test, y_test = prep_train_test(pos_x, neg_x, FLAGS.DEV_PERCENTAGE)\n\nx_train_char = get_ngramed_id_x(x_train, ngramed_id_x) \nx_test_char = get_ngramed_id_x(x_test, ngramed_id_x) \n\nx_train_word = get_ngramed_id_x(x_train, worded_id_x) \nx_test_word = get_ngramed_id_x(x_test, worded_id_x) \n\nx_train_char_seq = get_ngramed_id_x(x_train, chared_id_x)\nx_test_char_seq = get_ngramed_id_x(x_test, chared_id_x)\n\n\n###################################### Training #########################################################\n\ndef train_dev_step(x, y, emb_mode, is_train=True):\n if is_train: \n p = 0.5\n else: \n p = 1.0\n if emb_mode == 1: \n feed_dict = {\n cnn.input_x_char_seq: x[0],\n cnn.input_y: y,\n cnn.dropout_keep_prob: p} \n elif emb_mode == 2: \n feed_dict = {\n cnn.input_x_word: x[0],\n cnn.input_y: y,\n cnn.dropout_keep_prob: p}\n elif emb_mode == 3: \n feed_dict = {\n cnn.input_x_char_seq: x[0],\n cnn.input_x_word: x[1],\n cnn.input_y: y,\n cnn.dropout_keep_prob: p}\n elif emb_mode == 4: \n feed_dict = {\n cnn.input_x_word: x[0],\n cnn.input_x_char: x[1],\n cnn.input_x_char_pad_idx: x[2],\n cnn.input_y: y,\n cnn.dropout_keep_prob: p}\n elif emb_mode == 5: \n feed_dict = {\n cnn.input_x_char_seq: x[0],\n cnn.input_x_word: x[1],\n cnn.input_x_char: x[2],\n cnn.input_x_char_pad_idx: x[3],\n cnn.input_y: y,\n cnn.dropout_keep_prob: p}\n if is_train:\n _, step, loss, acc = sess.run([train_op, global_step, cnn.loss, cnn.accuracy], feed_dict)\n else: \n step, loss, acc = sess.run([global_step, cnn.loss, cnn.accuracy], feed_dict)\n return step, loss, acc\n\nwith tf.Graph().as_default(): \n session_conf = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) \n session_conf.gpu_options.allow_growth=True \n sess = tf.Session(config=session_conf) \n\n with sess.as_default(): \n cnn = TextCNN(\n char_ngram_vocab_size = len(ngrams_dict)+1, \n word_ngram_vocab_size = len(words_dict)+1,\n char_vocab_size = len(chars_dict)+1,\n embedding_size=FLAGS.EMB_DIM,\n word_seq_len=FLAGS.MAX_LENGTH_WORDS,\n char_seq_len=FLAGS.MAX_LENGTH_CHARS,\n l2_reg_lambda=FLAGS.L2_REG_LAMBDA,\n mode=FLAGS.EMB_MODE,\n filter_sizes=list(map(int, FLAGS.FILTER_SIZES.split(\",\"))))\n\n global_step = tf.Variable(0, name=\"global_step\", trainable=False) \n optimizer = tf.train.AdamOptimizer(FLAGS.LR) \n grads_and_vars = optimizer.compute_gradients(cnn.loss)\n train_op = optimizer.apply_gradients(grads_and_vars, global_step = global_step) \n \n print(\"Writing to {}\\n\".format(FLAGS.OUTPUT_DIR))\n if not os.path.exists(FLAGS.OUTPUT_DIR): \n os.makedirs(FLAGS.OUTPUT_DIR)\n \n # Save dictionary files \n ngrams_dict_dir = FLAGS.OUTPUT_DIR + \"ngrams_dict.p\"\n pickle.dump(ngrams_dict, open(ngrams_dict_dir,\"wb\")) \n words_dict_dir = FLAGS.OUTPUT_DIR + \"words_dict.p\"\n pickle.dump(words_dict, open(words_dict_dir, \"wb\"))\n chars_dict_dir = FLAGS.OUTPUT_DIR + \"chars_dict.p\"\n pickle.dump(chars_dict, open(chars_dict_dir, \"wb\"))\n\n checkpoint_dir = FLAGS.OUTPUT_DIR + \"checkpoints/\" \n if not os.path.exists(checkpoint_dir): \n os.makedirs(checkpoint_dir) \n checkpoint_prefix = checkpoint_dir + \"model\"\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=5) \n \n sess.run(tf.global_variables_initializer())\n\n if FLAGS.EMB_MODE == 1: \n batch_data = list(zip(x_train_char_seq, y_train))\n elif FLAGS.EMB_MODE == 2: \n batch_data = list(zip(x_train_word, y_train))\n elif FLAGS.EMB_MODE == 3: \n batch_data = list(zip(x_train_char_seq, x_train_word, y_train))\n elif FLAGS.EMB_MODE == 4:\n batch_data = list(zip(x_train_char, x_train_word, y_train))\n elif FLAGS.EMB_MODE == 5: \n batch_data = list(zip(x_train_char, x_train_word, x_train_char_seq, y_train))\n batches = batch_iter(batch_data, FLAGS.BATCH_SIZE, FLAGS.NB_EPOCHS)\n \n x_test = []\n if FLAGS.EMB_MODE == 1 or FLAGS.EMB_MODE == 3 or FLAGS.EMB_MODE == 5: \n x_test_char_seq = pad_seq_in_word(x_test_char_seq, FLAGS.MAX_LENGTH_CHARS) \n x_test.append(x_test_char_seq)\n if FLAGS.EMB_MODE == 2 or FLAGS.EMB_MODE == 3 or FLAGS.EMB_MODE == 4 or FLAGS.EMB_MODE == 5: \n x_test_word = pad_seq_in_word(x_test_word, FLAGS.MAX_LENGTH_WORDS) \n x_test.append(x_test_word)\n if FLAGS.EMB_MODE == 4 or FLAGS.EMB_MODE == 5: \n x_test_char, x_test_char_pad_idx = pad_seq(x_test_char, FLAGS.MAX_LENGTH_WORDS, FLAGS.MAX_LENGTH_SUBWORDS, FLAGS.EMB_DIM)\n x_test.extend([x_test_char, x_test_char_pad_idx])\n\n min_dev_loss = float('Inf') \n nb_batches_per_epoch = int(len(batch_data)/FLAGS.BATCH_SIZE)\n if len(batch_data)%FLAGS.BATCH_SIZE != 0: \n nb_batches_per_epoch += 1\n nb_batches = int(nb_batches_per_epoch * FLAGS.NB_EPOCHS)\n print(\"Number of baches in total: {}\".format(nb_batches))\n print(\"Number of batches per epoch: {}\".format(nb_batches_per_epoch))\n for idx, batch in enumerate(batches): \n if FLAGS.EMB_MODE == 1: \n x_char_seq, y_batch = zip(*batch) \n elif FLAGS.EMB_MODE == 2: \n x_word, y_batch = zip(*batch) \n elif FLAGS.EMB_MODE == 3: \n x_char_seq, x_word, y_batch = zip(*batch) \n elif FLAGS.EMB_MODE == 4: \n x_char, x_word, y_batch = zip(*batch)\n elif FLAGS.EMB_MODE == 5: \n x_char, x_word, x_char_seq, y_batch = zip(*batch) \n\n x_batch = [] \n if FLAGS.EMB_MODE == 1 or FLAGS.EMB_MODE == 3 or FLAGS.EMB_MODE == 5: \n x_char_seq = pad_seq_in_word(x_char_seq, FLAGS.MAX_LENGTH_CHARS) \n x_batch.append(x_char_seq)\n if FLAGS.EMB_MODE == 2 or FLAGS.EMB_MODE == 3 or FLAGS.EMB_MODE == 4 or FLAGS.EMB_MODE == 5: \n x_word = pad_seq_in_word(x_word, FLAGS.MAX_LENGTH_WORDS) \n x_batch.append(x_word)\n if FLAGS.EMB_MODE == 4 or FLAGS.EMB_MODE == 5: \n x_char, x_char_pad_idx = pad_seq(x_char, FLAGS.MAX_LENGTH_WORDS, FLAGS.MAX_LENGTH_SUBWORDS, FLAGS.EMB_DIM)\n x_batch.extend([x_char, x_char_pad_idx])\n step, loss, acc = train_dev_step(x_batch, y_batch, emb_mode=FLAGS.EMB_MODE, is_train=True) \n\n if step % FLAGS.PRINT_EVERY == 0: \n print(\"step {}, loss {}, acc {}\".format(step, loss, acc)) \n if step % FLAGS.EVAL_EVERY == 0: \n print(\"\\nEvaluation\") \n step, dev_loss, dev_acc = train_dev_step(x_test, y_test, emb_mode=FLAGS.EMB_MODE, is_train=False) \n print(\"step {}, loss {}, acc {}\".format(step, dev_loss, dev_acc))\n if step % FLAGS.CHECKPOINT_EVERY == 0 or idx == (nb_batches-1): \n if dev_loss < min_dev_loss: \n path = saver.save(sess, checkpoint_prefix, global_step = step) \n print(\"Dev loss improved: {} -> {}\".format(min_dev_loss, dev_loss))\n print(\"Saved model checkpoint to {}\\n\".format(path))\n min_dev_loss = dev_loss \n else: \n print(\"Dev loss did not improve: {} -> {}\".format(min_dev_loss, dev_loss))\n \n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"220251936","text":"from setup import *\n\ndef elapse_time(m):\n \"\"\"\n Given a \"message\" distribution over tags, returns an updated distribution\n after a single timestep using Viterbi update, along with a list of the \n indices of the most likely prior tag for each current tag\n \"\"\"\n mprime = np.zeros(NUM_TAGS)\n prior_tags = np.zeros(NUM_TAGS, dtype=np.int8)\n\n for i in range(len(TPROBS)):\n maximum = max([TPROBS[i][x] * m[x] for x in range(len(TPROBS[i]))])\n mprime[i] = maximum\n argmax = np.argmax([TPROBS[i][x] * m[x] for x in range(len(TPROBS[i]))])\n prior_tags[i] = argmax\n\n return mprime, prior_tags\n\ndef observe(mprime, obs):\n \"\"\"\n Given a \"message\" distribution over tags, returns an updated distribution\n by weighting mprime by the emission probabilities corresponding to obs\n \"\"\"\n m = np.zeros(NUM_TAGS)\n if obs in OPROBS:\n probs = np.diag(OPROBS[obs])\n else: \n probs = np.diag(OPROBS['#UNSEEN'])\n \n for i in range(len(m)):\n m[i] = (probs @ mprime)[i]\n\n return m\n\ndef viterbi(observations):\n \"\"\"\n Given a list of word observations, returns a list of predicted tags\n \"\"\"\n\n # \"Forward\" phase of the Viterbi algorithm\n m = X0\n pointers = []\n tags = []\n\n for obs in observations: \n mprime, prior_tags = elapse_time(m)\n pointers.append(prior_tags)\n m = observe(mprime, obs)\n \n # \"Backward\" phase of the Viterbi algorithm\n start = np.argmax(m)\n tags.insert(0, TAGS[start])\n for i in reversed(range(1, len(pointers))):\n tags.insert(0, TAGS[pointers[i][start]])\n start = pointers[i][start]\n\n return tags\n\n","sub_path":"pos-code/viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"633201871","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport re\nimport os\nimport fnmatch\n\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\n\n# функция-помошник для округления чисел и превращения их в четные\ndef round_up_to_even( number):\n\n\tnumber = int(number)\n\n\tif number % 2 != 0:\n\t\tnumber = number - 1\n\n\treturn number\n\n\ndef lookahead(iterable):\n\t\"\"\"Pass through all values from the given iterable, augmented by the\n\tinformation if there are more values to come after the current one\n\t(True), or if it is the last value (False).\n\t\"\"\"\n\t# Get an iterator and pull the first value.\n\tit = iter(iterable)\n\tlast = next(it)\n\t# Run the iterator to exhaustion (starting from the second value).\n\tfor val in it:\n\t\t# Report the *previous* value (more to come).\n\t\tyield last, True\n\t\tlast = val\n\t# Report the last value.\n\tyield last, False\n\n\n# Если скрипт используется на windows, то терминал при перетаскивании туда директории\n# представляет путь в виде /cygdrive/c/... \n# Такой вариант нас не устраивает, поэтому приводим путь в нормальный вид\ndef correct_directory(path):\n\n\tpath_pattern = re.compile(\".*cygdrive.*\")\n\n\tif path_pattern.match(path):\n\n\t\tpath = path.replace('/cygdrive/','')\n\t\tpath = path[0] + ':' + path[1:]\n\n\t\tlogging.debug('correcting path done. Actual path ' + path )\n\n\tpath = path.replace('\\\\','/')\n\n\treturn path\n\n\ndef convert_timings_to_array(time_value):\n\n\tif type(time_value) is not str:\n\t\treturn time_value\n\n\tif ' ' not in time_value:\n\t\treturn int(time_value)\n\n\tif time_value[0] == ' ':\n\t\ttime_value = time_value[1:]\n\n\treturn [int(x) for x in time_value.split(' ')]\n\n\ndef convert_channels_to_array(channels_str):\n\t\"\"\"преобразует строку с каналами, записанными через пробел, в массив\n\t\t\"\"\"\n\n\t# если строка ничается с пробела, то\n\t# удаляем его во избежание ошибки\n\tif channels_str[0] == ' ':\n\t\tchannels_str = channels_str[1:]\n\n\tif channels_str == 'tags':\n\t\treturn channels_str\n\n\tchannels_str = channels_str.split(' ')\n\tchannels_str = [int(x) for x in channels_str]\n\n\treturn channels_str\n\n\ndef natural_sort(alist):\n\t\"\"\"Натуральная сортировка списка файлов.\n\t\tНужна для массовой обрезки концов, когда значения времени\n\t\tдля каждой серии заданы по очереди в виде массива\n\t\"\"\"\n\n\tdef natural_keys(string_):\n\n\t\treturn [int(s) if s.isdigit() else s for s in re.split(r'(\\d+)', string_)]\n\n\treturn sorted(alist, key=natural_keys)\n\n\ndef find_char_indexes(s, ch):\n\t\"\"\"Выполняет поиск определнного символа в строке\n\t\tВозвращает все индексы этого символа в виде массива\n\t\"\"\"\n\n\treturn [i for i, ltr in enumerate(s) if ltr == ch]\n\n\ndef find_file_by_mask(name_mask, path):\n\t\"\"\"Выполняет поиск файла в указанной директории\n\t\tПоиск выполняется до первого совпадения\n\t\tНазвание файла задается в виде регулярного выражения\n\t\tНапример 'FILE_NAME_PART*mp4'\n\t\"\"\"\n\n\tfor file in os.listdir(path):\n\n\t\tif fnmatch.fnmatch(file, name_mask):\n\n\t\t\treturn file\n\n\ndef find_files_by_mask(regex, path):\n\t\"\"\"Выполняет поиск файла в указанной директории\n\t\tВозвращает все найденные файлы\n\t\tНазвание файла задается в виде регулярного выражения\n\t\tНапример 'FILE_NAME_PART*mp4'\n\t\t\"\"\"\n\tfiles = []\n\n\tmatcher = re.compile(regex, re.IGNORECASE)\n\n\tfor file in os.listdir( path ):\n\n\t\tif matcher.match(file):\n\n\t\t\tfiles.append( file )\n\n\treturn files\n\n\ndef slice_filename(FILE_NAME):\n\n\tif FILE_NAME is None:\n\t\treturn None\n\n\tsliced_name = {}\n\n\tunderscore_indexes = find_char_indexes(FILE_NAME, '_')\n\n\tsliced_name['basename'] = FILE_NAME[0: underscore_indexes[-2]]\n\n\tsliced_name['lang'] = FILE_NAME[underscore_indexes[-2] + 1: underscore_indexes[-1]].lower()\n\n\tsliced_name['quality'] = FILE_NAME[underscore_indexes[-1] + 1: -4]\n\n\treturn sliced_name\n\n\ndef check_exit_codes(codes):\n\n\t\"\"\"Метод для проверки кодов выхода внешних процессов\n\t\tСделан таким, поскольку разные процессы возвращают коды \n\t\tв разном виде, и, соответсвенно нужно привести их\n\t\tк одному понятному виду: int 0 или int 1\n\n\t\"\"\"\n\tlogging.debug(codes)\n\n\tdef _check_int_and_str(code): \n\n\t\tif type(code) == int and code == 0:\n\n\t\t\treturn 0\n\n\t\telif type(code) == str and code == '0':\n\n\t\t\treturn 0\n\n\t\telse:\n\n\t\t\treturn 1\n\n\tif codes is None:\n\n\t\treturn None\t\t\n\n\tif type(codes) == dict:\n\n\t\tfor i in codes:\n\n\t\t\tif _check_int_and_str(codes[i]) == 1:\n\n\t\t\t\treturn 1\n\n\t\treturn 0\n\n\telif type(codes) == list:\n\n\t\tfor code in codes:\n\n\t\t\tif _check_int_and_str(code) == 1:\n\n\t\t\t\treturn 1\n\n\t\treturn 0\n\n\telse:\n\n\t\treturn _check_int_and_str(codes)\n\n\ndef compare_intervals(intervals_a, intervals_b):\n\t\"\"\"Метод для поиска пересечений временных интервалов.\n\t\tИспользовался в методе find_ending, но потом оказался\n\t\tне у дел и я решил переместить его сюда на всякий случай. \n\t\tЕсли в ближайшее время не будет применения для него, \n\t\tто удалю. \n\n\t\tНа вход подаются два массима, содержащих массивы с\n\t\tотрезками времени вида:\n\n\t\t [ [start, end], [start, end] ... [start, end] ]\n\t\t\n\t\tМетод возвращает массив такого же вида. \n\n\t\"\"\"\n\n\tfiltered = []\n\n\tfor interval_a in intervals_a:\n\n\t\ta_s = interval_a[0]\n\t\ta_e = interval_a[1]\n\n\t\tfor interval_b in intervals_b:\n\n\t\t\tb_s = interval_b[0]\n\t\t\tb_e = interval_b[1]\n\n\t\t\tif b_s < a_s and b_e < a_s:\n\n\t\t\t\tcontinue\n\n\t\t\telif b_s < a_s and b_e < a_e and b_e > a_s:\n\n\t\t\t\tfiltered.append( [ a_s, b_e ] )\n\n\t\t\telif b_s >= a_s and b_s <= a_e and b_e <= a_e:\n\n\t\t\t\tfiltered.append( [b_s, b_e] )\n\n\t\t\telif b_s > a_s and b_s < a_e and b_e > a_e:\n\n\t\t\t \tfiltered.append( [b_s, a_e] )\n\n\t\t\telif b_s < a_s and b_e > a_e:\n\n\t\t\t\tfiltered.append( [a_s, a_e] )\n\n\t\t\telse:\n\n\t\t\t\tcontinue\n\n\treturn filtered\n\n\ndef parse_audio_streams(tracks):\n\t\"\"\"Метод преобразует параметры аудиодорожек,\n\t\tзаданные ввиде строки и разделителями \":\"\n\t\tв форму dict вида:\n\n\t\t{\n\t\t\t'language' : str ,\n\t\t\t'channels' : [] ,\n\t\t\t'downmix' : int\n\t\t}\n\n\t\tесли channels содержит пустой массив, то\n\t\tпрограмма возьмёт первую фактическую дорожку.\n\n\t\tЗависимости:\n\t\tre - из фрагмента строки с даунмиксом\n\t\t\t выбирает только цифры\n\n\t\tВозвращает:\n\t\tМассив, содержащий dict с информацией о\n\t\tкаждой выходной аудиодорожке\n\t\t\"\"\"\n\n\taudio_streams = []\n\n\t# Если аудидорожки не заданы, то по дефолту\n\t# считаем первую найденную аудидорожку с тегом\n\t# русского языка\n\tif tracks is None:\n\t\treturn [{'language': 'rus', 'channels': [], 'downmix': 1, 'type': None}]\n\n\tfor a in tracks:\n\n\t\ta = a.split(':')\n\n\t\taudio_stream = {}\n\t\taudio_stream['language'] = a[0]\n\n\t\tif len(a) < 2:\n\t\t\taudio_stream['channels'] = []\n\t\telse:\n\t\t\taudio_stream['channels'] = convert_channels_to_array(a[1])\n\n\t\t# Если пользователь не задал значение даунмикса,\n\t\t# то устанавливаем принудительный даунмикс\n\t\tif len(a) == 3:\n\t\t\taudio_stream['downmix'] = int(re.sub(\"[^0-9]\", \"\", a[2]))\n\t\telse:\n\t\t\taudio_stream['downmix'] = 1\n\n\t\taudio_stream['type'] = None\n\n\t\taudio_streams.append(audio_stream)\n\n\treturn audio_streams","sub_path":"lib/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"157509264","text":"import requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nfrom furl import furl\n\n\nfrom .tunnel import SSHTunnelsContainer\n\n\nclass ApiClient:\n BASE_URL = 'http://localhost:{port}'\n BASE_HEADERS = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n }\n TIMEOUT = (5, 5)\n TOTAL_RETRIES = 10\n BACKOFF_FACTOR = 5\n PATHS = {\n 'cluster_name': '/storage_service/cluster_name',\n 'endpoints_live': '/gossiper/endpoint/live/',\n 'endpoints_down': '/gossiper/endpoint/down/',\n 'endpoints': '/failure_detector/endpoints/',\n 'endpoints_simple': '/failure_detector/simple_states',\n 'tokens': '/storage_service/tokens/{endpoint}',\n 'datacenter': '/snitch/datacenter',\n 'describe_ring': '/storage_service/describe_ring/{keyspace}',\n 'column_family': '/column_family/',\n 'repair_async': '/storage_service/repair_async/{keyspace}',\n 'active_repair': '/storage_service/active_repair/',\n }\n\n def __init__(self):\n self._hosts = []\n self._tunnels_container = None\n\n def setup(self, initial_endpoint=None, ssh_username=None, ssh_pkey=None,\n ssh_pass=None):\n self._tunnels_container = SSHTunnelsContainer(\n ssh_username=ssh_username,\n ssh_pkey=ssh_pkey,\n ssh_pass=ssh_pass,\n initial_endpoint=initial_endpoint)\n\n def stop(self):\n self._tunnels_container.stop()\n\n def retry_session(self, retries=None, backoff_factor=None, session=None):\n s = session or requests.Session()\n retry = Retry(\n total=retries or self.TOTAL_RETRIES,\n read=retries or self.TOTAL_RETRIES,\n connect=retries or self.TOTAL_RETRIES,\n backoff_factor=backoff_factor or self.BACKOFF_FACTOR,\n )\n adapter = HTTPAdapter(max_retries=retry)\n s.mount('http://', adapter)\n return s\n\n def _request(self, req_type, path, data=None, host=None, json=True):\n headers = self.BASE_HEADERS\n if host is not None:\n assert host in self._hosts, '{} is not part of the cluster!'\\\n .format(host)\n headers.update({'Host': host})\n\n port = self._tunnels_container.get_port(host=host)\n base_url = self.BASE_URL.format(port=port)\n url = furl(base_url + path)\n url.add(data or {})\n\n req = requests.Request(req_type, url.url, data=data or {},\n headers=headers)\n prepped = req.prepare()\n resp = self.retry_session().send(prepped, timeout=self.TIMEOUT)\n resp.raise_for_status()\n\n return resp.json() if json else resp.text\n\n def _get(self, path, data=None, host=None, json=True):\n return self._request('GET', path, data=data, host=host, json=json)\n\n def _post(self, path, data, host=None, json=True):\n return self._request('POST', path, data=data, host=host, json=json)\n\n def cluster_name(self):\n return self._get(self.PATHS['cluster_name'])\n\n def endpoints_detailed(self):\n \"\"\"\n Get all endpoint states\n \"return: [\n {\n \"update_time\": 1552310205453,\n \"generation\": 0,\n \"version\": 0,\n \"addrs\": \"10.210.20.127\",\n \"is_alive\": true,\n \"application_state\": [..]\n },\n ...\n ]\n \"\"\"\n endpoints = self._get(self.PATHS['endpoints'])\n self._hosts = [e['addrs'] for e in endpoints]\n\n return endpoints\n\n def endpoints_simple(self):\n \"\"\"\n return: [\n {\n \"key\": \"hostname\",\n \"value\": \"UP/DOWN\"\n }\n ]\n \"\"\"\n endpoints = self._get(self.PATHS['endpoints_simple'])\n self._hosts = [e['key'] for e in endpoints]\n\n return endpoints\n\n def tokens(self, endpoint):\n return self._get(self.PATHS['tokens'].format(endpoint=endpoint))\n\n def datacenter(self, endpoint):\n return self._get(self.PATHS['datacenter'], data={'host': endpoint})\n\n def describe_ring(self, keyspace):\n return self._get(self.PATHS['describe_ring'].format(keyspace=keyspace))\n\n def tables(self):\n return self._get(self.PATHS['column_family'])\n\n def repair_async(self, host, keyspace, table, start_token=None,\n end_token=None, dc=None):\n data = {\n 'keyspace': keyspace,\n 'primaryRange': 'true',\n 'parallelism': 0,\n 'jobThreads': 1,\n 'startToken': start_token,\n 'endToken': end_token,\n 'columnFamilies': table,\n 'dataCenters': dc,\n 'trace': \"'true'\"\n }\n return self._post(self.PATHS['repair_async'].format(keyspace=keyspace),\n data=data, host=host, json=False)\n\n def repair_status(self, host, keyspace, repair_id):\n return self._get(self.PATHS['repair_async'].format(keyspace=keyspace),\n data={'id': repair_id}, host=host, json=False)\n\n def active_repair(self, host):\n return self._get(self.PATHS['active_repair'], host=host)\n\n\nclient = ApiClient()\n__all__ = ['client']\n","sub_path":"scli/api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"485345293","text":"#!/usr/bin/env python\n# Copyright (c) 2019 Graphcore Ltd. All rights reserved.\n\n\"\"\"\nBenchmark a single CNN layer.\n\nThe Items/sec reported at the end of the benchmark is based on wall time.\n\nRun with -h or --help for options.\n\"\"\"\nimport inspect\nimport os\nimport sys\nimport tensorflow as tf\nfrom tensorflow.python.ipu import utils\n\n\ndef conv2d_basic(x, ksize, stride, filters_in, filters_out, index, groups=1,\n name='conv'):\n with tf.variable_scope(name, use_resource=True):\n W = tf.get_variable(\"conv2d/kernel\" + str(index),\n shape=[ksize, ksize,\n filters_in / groups, filters_out],\n dtype=x.dtype,\n trainable=True,\n initializer=tf.variance_scaling_initializer())\n return tf.nn.conv2d(x,\n filters=W,\n strides=[1, stride, stride, 1],\n padding='SAME')\n\n\ndef conv(opts, inputs):\n groups = opts.filter_out // opts.group_dim\n results = inputs\n for i in range(opts.block_repeats):\n results = conv2d_basic(results, opts.kernel_size, opts.stride,\n opts.filter_in, opts.filter_out, i,\n groups=groups)\n return results\n\n\ndef inputs(opts, index):\n value = tf.cast(index, tf.float16)\n return {\n \"inputs\": tf.broadcast_to(value, [opts.batch_size,\n opts.input_size, opts.input_size,\n opts.filter_in]),\n }\n\n\ndef graph_builder(opts, inputs_dict):\n output = conv(opts, inputs_dict[\"inputs\"])\n\n if opts.train:\n # dummy loss to minimize computational cost.\n loss = tf.reduce_mean(output)\n optimiser = tf.train.GradientDescentOptimizer(1e-30)\n with tf.variable_scope(\"train\", reuse=tf.AUTO_REUSE):\n # We need to ensure that the train op is executed as part of\n # the benchmarking loop by maintaining a step variable and\n # forcing a control dependency between it and the train op:\n global_step = tf.get_variable(\n \"step_control\", dtype=tf.int32, shape=[])\n grads_and_vars = optimiser.compute_gradients(\n loss, tf.trainable_variables())\n train = optimiser.apply_gradients(grads_and_vars, global_step)\n with tf.control_dependencies([train]):\n global_step = tf.identity(global_step)\n return global_step\n return output\n\n\ndef initializer():\n utils.move_variable_initialization_to_cpu()\n return tf.global_variables_initializer()\n\n\ndef add_args(parser):\n parser.add_argument(\"--batch-size\", default=1, type=int,\n help=\"Number of inputs in a mini-batch\")\n parser.add_argument(\"--filter-in\", default=64, type=int,\n help=\"Number of filters in the input\")\n parser.add_argument(\"--filter-out\", default=64, type=int,\n help=\"Number of filters in the output\")\n parser.add_argument(\"--kernel-size\", default=3, type=int,\n help=\"Kernel size\")\n parser.add_argument(\"--stride\", default=1, type=int,\n help=\"Stride\")\n parser.add_argument(\"--input-size\", default=56, type=int,\n help=\"Input size\")\n parser.add_argument(\"--block-repeats\", default=10, type=int,\n help=\"Number of convolution blocks\")\n parser.add_argument(\"--group-dim\", default=1, type=int,\n help=\"Group dimension (ie. number of filter in each group)\")\n parser.add_argument(\"--train\", action='store_true', dest='train',\n help=\"Compute loss and optimization pass\")\n parser.set_defaults(train=False, batches_per_step=1000, steps=5)\n return parser\n\n\ndef iteration_report(opts, time):\n return \"{:5f} items/sec\".format(opts.batch_size * opts.batches_per_step * opts.block_repeats * opts.replicas / time)\n\n\nif __name__ == '__main__':\n # Add benchmark module to path\n cwd = os.path.dirname(os.path.abspath(inspect.stack()[0][1]))\n sys.path.insert(1, os.path.join(cwd, '..', '..', 'utils',\n 'benchmarks', 'tensorflow'))\n import benchmark\n\n module = benchmark.Benchmark(\n graph_builder,\n inputs,\n initializer,\n add_args,\n iteration_report\n )\n\n options = benchmark.parse_opts(module, False)\n\n if options.shards > 1:\n raise NotImplementedError(\n \"--shards option has not been implemented with this example\")\n\n # Log Benchmark Message\n print(\"CNN layer {} Synthetic benchmark.\\n\"\n \" Batch size {}.\\n\"\n \" Batches per Step {}.\\n\"\n \" Steps {}.\\n\"\n \" Input size {}.\\n\"\n \" Group dimension {}.\\n\"\n \" Output filters {}.\\n\"\n \" Block repeat {}.\\n\"\n .format(\n \"Training\" if options.train else \"Inference\",\n options.batch_size,\n options.batches_per_step,\n options.steps,\n options.input_size,\n options.group_dim,\n options.filter_out,\n options.block_repeats))\n\n benchmark.run(module, options)\n","sub_path":"kernel_benchmarks/tensorflow/grouped_conv.py","file_name":"grouped_conv.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"619298820","text":"from __future__ import division\nfrom PIL import Image\nfrom sklearn import svm\nfrom StringIO import StringIO\nimport pickle, sys, os, socket\n\n\nLISTEN_PORT = 4321\nREAD_LENGTH = 1024\n\n\ndef process_directory(directory):\n\ttraining = []\n\tfor root, _, files in os.walk(directory):\n\t\tfor file_name in files:\n\t\t\tfile_path = os.path.join(root, file_name)\n\t\t\timg_feature = process_image_file(file_path)\n\t\t\tif img_feature:\n\t\t\t\ttraining.append(img_feature)\n\treturn training\n\n\ndef process_image_file(image_path):\n\timage_fp = StringIO(open(image_path, 'rb').read())\n\ttry:\n\t\timage = Image.open(image_fp)\n\t\treturn process_image(image)\n\texcept IOError:\n\t\treturn None\n\ndef process_recv_image(image_data):\n\timage_fp = StringIO(image_data)\n\ttry:\n\t\timage = Image.open(image_fp)\n\t\treturn process_image(image)\n\texcept IOError:\n\t\treturn None\n\ndef process_image(image, blocks=4):\n\t'''Given a PIL Image object it returns its feature vector.\n\n\tArgs:\n\t image (PIL.Image): image to process.\n\t blocks (int, optional): number of block to subdivide the RGB space into.\n\n\tReturns:\n\t list of float: feature vector if successful. None if the image is not\n\t RGB.\n\t'''\n\tif not image.mode == 'RGB':\n\t\treturn None\n\tfeature = [0] * blocks * blocks * blocks\n\tpixel_count = 0\n\tfor pixel in image.getdata():\n\t\tridx = int(pixel[0]/(256/blocks))\n\t\tgidx = int(pixel[1]/(256/blocks))\n\t\tbidx = int(pixel[2]/(256/blocks))\n\t\tidx = ridx + gidx * blocks + bidx * blocks * blocks\n\t\tfeature[idx] += 1\n\t\tpixel_count += 1\n\treturn [x/pixel_count for x in feature]\n\n\ndef train(training_path_a, training_path_b, print_metrics=True):\n\tif not os.path.isdir(training_path_a):\n\t\traise IOError('%s is not a directory' % training_path_a)\n\tif not os.path.isdir(training_path_b):\n\t\traise IOError('%s is not a directory' % training_path_b)\n\ttraining_a = process_directory(training_path_a)\n\ttraining_b = process_directory(training_path_b)\n\t# data contains all the training data (a list of feature vectors)\n\tdata = training_a + training_b\n\t# target is the list of target classes for each feature vector: a '1' for\n\t# class A and '0' for class B\n\ttarget = [0] * len(training_a) + [1] * len(training_b)\n\n\t# search for the best classifier within the search space and return it\n\tclf = svm.SVC(gamma=0.001, C=100.).fit(data, target)\n\treturn clf\n\n\ndef kb_interrupt_handler(classifier, sock):\n\twith open('classifier', 'wb') as clfFile:\n\t\t\tpickle.dump(classifier, clfFile)\n\tsock.close()\n\tprint('Closing server...')\n\tsys.exit(0)\n\n\ndef main(training_path_a, training_path_b):\n\t# Starting server listening\n\tserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\tserver.bind(('', LISTEN_PORT))\n\tserver.listen(10)\n\n\tclassifier = None\n\tif os.path.isfile('classifier'):\n\t\tprint('Loading an existing classifier...')\n\t\twith open('classifier', 'rb') as clfFile:\n\t\t\tunpickler = pickle.Unpickler(clfFile)\n\t\t\tclassifier = unpickler.load()\n\telse:\n\t\tprint('Training classifier...')\n\t\tclassifier = train(training_path_a, training_path_b)\n\tprint('Ready to predict...')\n\n\twhile True:\n\t\ttry:\n\t\t\t# Accept conection\n\t\t\tsock, addr = server.accept()\n\t\t\tprint('New conection...')\n\n\t\t\tdata = ''\n\n\t\t\t# Reading client data\n\t\t\twhile True:\n\t\t\t\tparte = sock.recv(READ_LENGTH) \n\t\t\t\tdata += parte\n\t\t\t\tif len(parte) < READ_LENGTH:\n\t\t\t\t\tbreak;\n\n\t\t\t# Process image and sending response\n\t\t\tprint('Predicting recived data...')\n\n\t\t\tfeatures = [process_recv_image(data)]\n\t\t\tif (classifier.predict(features) == 0):\n\t\t\t\tsock.send(training_path_a)\n\t\t\telse:\n\t\t\t\tsock.send(training_path_b)\n\t\texcept (KeyboardInterrupt, EOFError):\n\t\t\tkb_interrupt_handler(classifier, sock)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\n\t\t# Closing connection\n\t\tprint('Closing conection...')\n\t\tsock.close()\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 3:\n\t\tprint(\"Usage: %s [class A images directory] [class B images directory]\" %\n\t\t\tsys.argv[0])\n\t\tsys.exit(1)\n\tmain(sys.argv[1], sys.argv[2])","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"208232378","text":"#! /usr/bin/python3\n\n\nfrom datetime import date\nfrom datetime import timedelta\nfrom time import localtime, sleep\n\n\nf = open(\"money.csv\", \"r\")\ncsv1 = f.read()\nf.close()\n\n\ncsvlist = csv1.split('\\n')\n\nendlist = []\n\nfor row in csvlist:\n\tnewrow = row.split(';')\n\ttemp1 = newrow[4].replace('\"','')\n\ttemp1 = temp1.replace('.','')\n\ttemp1 = temp1.replace(',','.')\n\t\n\tendlist.append([newrow[2].replace('\"',''), temp1])\n\nlen_endlist = len(endlist)\n\nfor i in range(0,len_endlist):\n\t#print( endlist[i][0] )\n\tdatestr = endlist[i][0].split('.')\n\tendlist[i][0] = date(int(datestr[2]),int(datestr[1]),int(datestr[0]))\n\tendlist[i][1] = float(endlist[i][1])\n\t\n\t\n\t#print(endlist[i][0], endlist[i][1])\n\t\n\n#Positive numbers\n\nfor i in range(0,len_endlist):\n\tif endlist[i][1] > 0.0:\n\t\tendlist[i][1] = 0.0\n\nsums = [0,0,0,0,0,0,0,0,0,0,0,0,0]\n\nfor i1 in range(1,12):\n\tfor i2 in endlist:\n\t\tif i2[0].month == i1:\n\t\t\tsums[i1] += i2[1]\n\nprint('SUMS:', sums[1:])\n\nsum0 = 0\nfor i1 in endlist:\n\tsum0 += i1[1]\n\t\nprint('TOTAL:', sum0)","sub_path":"python/money.py","file_name":"money.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"574438368","text":"# ECE Final Project\n#Unused\n#Based off https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html\n\nfrom ai_safety_gridworlds.environments.distributional_shift import DistributionalShiftEnvironment \nfrom ai_safety_gridworlds.environments.safe_interruptibility import SafeInterruptibilityEnvironment \nfrom ai_safety_gridworlds.environments.side_effects_sokoban import SideEffectsSokobanEnvironment\nfrom ai_safety_gridworlds.environments.shared import safety_ui\nfrom ai_safety_gridworlds.environments.shared import safety_game\nfrom ai_safety_gridworlds.environments.shared.safety_game import Actions\n\nfrom copy import deepcopy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\n\nimport random\nimport math\nfrom collections import namedtuple\nfrom itertools import count\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.transforms as T\n\n\n# ===============================================================\n# Environment constants\nWIDTH = 9\nHEIGHT = 8\nNUM_OBJECTS = 8\noneHotMap = {}\noneHotMap[0, 110, 119] = [1, 0, 0, 0, 0, 0, 0, 0] # Box\noneHotMap[255, 0, 0] = [0, 1, 0, 0, 0, 0, 0, 0] # Lava\noneHotMap[219, 219, 219] = [0, 0, 1, 0, 0, 0, 0, 0] # Path\noneHotMap[0, 180, 255] = [0, 0, 0, 1, 0, 0, 0, 0] # Agent\noneHotMap[152, 152, 152] = [0, 0, 0, 0, 1, 0, 0, 0] # Wall\noneHotMap[0, 210, 50] = [0, 0, 0, 0, 0, 1, 0, 0] # Goal\noneHotMap[110, 69, 210] = [0, 0, 0, 0, 0, 0, 1, 0] # Button\noneHotMap[255, 30, 255] = [0, 0, 0, 0, 0, 0, 0, 1] # Interruption\n# ===============================================================\n\nTransition = namedtuple('Transition',\n ('state', 'action', 'next_state', 'reward'))\n\nclass ReplayMemory(object):\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def __len__(self):\n return len(self.memory)\n\n\n\nclass DQN(nn.Module):\n def __init__(self, n_actions):\n super(DQN, self).__init__()\n \n self.inputSize = WIDTH*HEIGHT*NUM_OBJECTS\n self.hidden1Size = 100\n self.hidden2Size = 100\n self.outputSize = n_actions\n\n self.hidden1 = nn.Linear(self.inputSize, self.hidden1Size)\n self.hidden2 = nn.Linear(self.hidden1Size, self.hidden2Size)\n self.output = nn.Linear(self.hidden2Size, self.outputSize)\n \n #self.W1 = torch.randn(self.inputSize, self.hidden1Size) # 10 X ? tensor\n #self.W2 = torch.randn(self.hidden1Size, self.hidden2Size) # 3 X 2 tensor\n #self.W3 = torch.randn(self.hidden2Size, self.outputSize) # 3 X 1 tensor\n \n def forward(self, x):\n #x = F.relu(self.bn1(self.conv1(x)))\n #x = F.relu(self.bn2(self.conv2(x)))\n #x = F.relu(self.bn3(self.conv3(x)))\n \n #print(\"at x\", x)\n x = F.relu(self.hidden1(x))\n x = F.relu(self.hidden2(x))\n x = self.output(x) #Can't have ReLU here because then we couldn't have negative action values\n \n #x = self.hidden1(x)\n #x = self.hidden2(x)\n #x = self.output(x)\n \n return x#self.head(x.view(x.size(0), -1))\n \n \nclass Agent():\n def __init__(self):\n super(Agent, self).__init__()\n \n\n \n def getNextAction(state):\n \"\"\"\n Finds the best action for the given state\n Args:\n state: Current state of the environment\n Returns:\n action: The best action for the given state\n \"\"\"\n return Actions.RIGHT\n # ===============================================================\n def runEpisode(env):\n \"\"\"\n Performs an episode of learning\n Args:\n env: Instance of a Safety Gridworld environment\n Returns:\n totalReturn: Total return from the episode\n episodeHistory: List of grid configurations encountered in episode \n \"\"\"\n timestep = env.reset() # Set the environment to initial state\n gridHeight = len(timestep.observation['RGB'][0]) # True height of the environment grid\n gridWidth = len(timestep.observation['RGB'][0][0]) # True width of the environment grid\n episodeHistory = [deepcopy(timestep.observation['board'])] # History of all grid configurations encountered\n totalReturn = 0\n while 'termination_reason' not in env._environment_data: # While not a terminal state\n grid = timestep.observation['RGB'] # Get current grid configuration\n state = np.zeros((HEIGHT, WIDTH, NUM_OBJECTS))\n for i in range(HEIGHT): # One hot encoding grid into state\n for j in range(WIDTH):\n if i >= gridHeight or j >= gridWidth: # If the grid is smaller than the state size set as \"wall\"\n state[i][j] = oneHotMap[152, 152, 152]\n else:\n values = oneHotMap[grid[0][i][j], grid[1][i][j], grid[2][i][j]]\n for k in range(len(values)):\n state[i][j][k] = values[k]\n timestep = env.step(getNextAction(state)) # Advance the environment by taking an action\n episodeHistory.append(deepcopy(timestep.observation['board']))\n if timestep.reward is not None:\n totalReturn += timestep.reward\n return totalReturn, episodeHistory \n# ===============================================================\n\nenv = DistributionalShiftEnvironment(is_testing=False)\n#env = SafeInterruptibilityEnvironment()\n#env = SideEffectsSokobanEnvironment()\n#totalReturn, episodeHistory = runEpisode(env)\n\n#for episode in episodeHistory:\n# print(episode)\n\nagent = Agent()\n\n\n#dqn = DQN()\n#print(dqn.forward(torch.randn(WIDTH*HEIGHT*NUM_OBJECTS)))\n\n#Tried to match paper\nBATCH_SIZE = 64\nGAMMA = 0.99\nEPS_START = 1.0\nEPS_END = 0.01\nEPS_LENGTH = 900000 #timesteps \nTARGET_UPDATE = 10\nMAX_TIMESTEPS = 1000000\n\ndevice = torch.device(\"cpu\")\n\n# Get number of actions from gym action space\nn_actions = 4\n\npolicy_net = DQN(n_actions).to(device)\ntarget_net = DQN(n_actions).to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\ntarget_net.eval()\n\n#print(policy_net.forward(torch.randn(WIDTH*HEIGHT*NUM_OBJECTS)))\n\n#optimizer = optim.RMSprop(policy_net.parameters())\noptimizer = optim.Adam(policy_net.parameters(), lr=5e-4)\ncriterion = torch.nn.MSELoss()\nmemory = ReplayMemory(10000)\n\nsteps_done = 0\n\n\ndef optimize_model():\n if len(memory) < BATCH_SIZE:\n return\n \n transitions = memory.sample(BATCH_SIZE)\n # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n # detailed explanation). This converts batch-array of Transitions\n # to Transition of batch-arrays.\n batch = Transition(*zip(*transitions))\n \n # Compute a mask of non-final states and concatenate the batch elements\n # (a final state would've been the one after which simulation ended)\n non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n batch.next_state)), device=device, dtype=torch.uint8)\n non_final_next_states = torch.stack([s for s in batch.next_state\n if s is not None])\n state_batch = torch.stack(batch.state)\n action_batch = torch.cat(batch.action)\n reward_batch = torch.cat(batch.reward)\n\n # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n # columns of actions taken. These are the actions which would've been taken\n # for each batch state according to policy_net\n \n state_action_values = policy_net(state_batch).gather(1, action_batch)\n \n # Compute V(s_{t+1}) for all next states.\n # Expected values of actions for non_final_next_states are computed based\n # on the \"older\" target_net; selecting their best reward with max(1)[0].\n # This is merged based on the mask, such that we'll have either the expected\n # state value or 0 in case the state was final.\n next_state_values = torch.zeros(BATCH_SIZE, device=device)\n next_state_values[non_final_mask.bool()] = target_net(non_final_next_states).max(1)[0].detach()\n # Compute the expected Q values\n expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n\n #print(state_action_values, \"\\n\", expected_state_action_values.unsqueeze(1), \"\\n\")\n # Compute Huber loss\n #loss = F.smooth_l1_loss(state_action_values, expected_state_action_values.unsqueeze(1))\n #MSE Loss\n loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1))\n \n # Optimize the model\n optimizer.zero_grad()\n loss.backward()\n for param in policy_net.parameters():\n param.grad.data.clamp_(-1, 1)\n optimizer.step()\n\n \n#Function for converting state\ntimestep = env.reset() # Set the environment to initial state\ngridHeight = len(timestep.observation['RGB'][0]) # True height of the environment grid\ngridWidth = len(timestep.observation['RGB'][0][0]) # True width of the environment grid\nepisodeHistory = [deepcopy(timestep.observation['board'])] # History of all grid configurations encountered\n \ndef get_onehot_state(timestep): #given an input state\n gridHeight = len(timestep.observation['RGB'][0]) # True height of the environment grid\n gridWidth = len(timestep.observation['RGB'][0][0]) # True width of the environment grid\n\n grid = timestep.observation['RGB'] # Get current grid configuration\n state = np.zeros((HEIGHT, WIDTH, NUM_OBJECTS))\n for i in range(HEIGHT): # One hot encoding grid into state\n for j in range(WIDTH):\n if i >= gridHeight or j >= gridWidth: # If the grid is smaller than the state size set as \"wall\"\n state[i][j] = oneHotMap[152, 152, 152]\n else:\n values = oneHotMap[grid[0][i][j], grid[1][i][j], grid[2][i][j]]\n for k in range(len(values)):\n state[i][j][k] = values[k]\n s = torch.from_numpy(state).reshape(-1) #reshape to vector for input to NN\n\n #See comments above for some more info on this for loop. There seems to be a bug where I can't call \n #target_policy.forward(s) but I can if I replace it with the same sized tensor from some other function and then copy the values\n tmp = torch.zeros(WIDTH*HEIGHT*NUM_OBJECTS) \n for i in range(state.shape[0]):\n tmp[i] = s[i] \n \n return tmp\n\n \n#timestep = env.reset()\n#s = get_onehot_state(timestep)\n#print(torch.randn(WIDTH*HEIGHT*NUM_OBJECTS).shape)\n#print(policy_net.forward(torch.randn(WIDTH*HEIGHT*NUM_OBJECTS)))\n#print(s)\n#print(policy_net.forward(s)) #this breaks for some reason\n\n#This doesn't:\n#tmp_test = torch.randn(WIDTH*HEIGHT*NUM_OBJECTS)\n#for i in range(s.shape[0]):\n# tmp_test[i] = s[i]\n\n#zz\n\n#print(timestep)\n#print(get_onehot_state(timestep))\n\ndef select_action(state):\n global steps_done\n sample = random.random()\n eps_threshold = np.max([EPS_END, EPS_END + (EPS_START - EPS_END) * (1 - steps_done / EPS_LENGTH)]) #linearly anneal...\n if sample > eps_threshold:\n with torch.no_grad():\n # t.max(1) will return largest column value of each row.\n # second column on max result is index of where max element was\n # found, so we pick action with the larger expected reward.\n \n return policy_net.forward(state).argmax().view(1,1)\n else:\n return torch.tensor([[random.randrange(n_actions)]], device=device, dtype=torch.long)\n\n\ndef moving_average(data, window_size=100): #used this approach https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python\n cumsum_vec = np.cumsum(np.insert(data, 0, 0)) \n ma_vec = (cumsum_vec[window_size:] - cumsum_vec[:-window_size]) / window_size\n return ma_vec\n\n \n#print(select_action(torch.randn(WIDTH*HEIGHT*NUM_OBJECTS)))\n#zz\n#Training loop\nepisode_durations = []\nepisode_return = []\nsteps_at_episode = []\n\nt0 = time.time()\n#num_episodes = 110\n#for i_episode in range(num_episodes):\ni_episode = 0\nwhile steps_done < MAX_TIMESTEPS: \n i_episode +=1\n # Initialize the environment and state\n timestep = env.reset()\n \n state = get_onehot_state(timestep)\n \n #for t in count():\n t = 0 #Count number of states in episode\n returns = 0\n \n while 'termination_reason' not in env._environment_data:\n #print(t)\n # Select and perform an action\n action = select_action(state)\n #Observe new state\n timestep = env.step(action)\n next_state = get_onehot_state(timestep)\n reward = torch.tensor([timestep.reward], device=device)\n t+=1\n returns += timestep.reward\n \n # Store the transition in memory\n memory.push(state, action, next_state, reward)\n\n # Move to the next state\n state = next_state\n\n # Perform one step of the optimization (on the target network)\n #t1=time.time()\n optimize_model()\n #print(time.time()-t1)\n else:\n steps_done += t\n episode_durations.append(t+1)\n episode_return.append(returns)\n steps_at_episode.append(steps_done)\n #plot_durations()\n \n # Update the target network, copying all weights and biases in DQN\n if i_episode % TARGET_UPDATE == 0:\n target_net.load_state_dict(policy_net.state_dict())\n \n if i_episode % 100 == 0: \n print(i_episode, steps_done, time.time()-t0)\n\n #timestep = env.reset()\n #state = torch.from_numpy(timestep.observation['board']).reshape(-1)\n #print(policy_net(state))\n \n if i_episode % 1000 == 0: \n #print(episode_return)\n plt.figure()\n plt.plot(steps_at_episode, episode_return)\n plt.plot(steps_at_episode[99:], moving_average(episode_return))\n plt.xlabel(\"Steps\")\n plt.ylabel(\"Return\")\n plt.savefig('figures/out_'+str(steps_done)+'.png')\n\nprint(\"Time: \", time.time()-t0)\n \nprint('Complete')\n\n#print(episode_return)\nplt.figure()\nplt.plot(steps_at_episode, episode_return)\nplt.plot(steps_at_episode[99:], moving_average(episode_return))\nplt.xlabel(\"Steps\")\nplt.ylabel(\"Return\")\n#plt.title(r\"zzz\")\nplt.savefig('out.png')\n\n\ndef plot_episode():\n timestep = env.reset()\n \n while 'termination_reason' not in env._environment_data:\n #print(t)\n # Select and perform an action\n print(target_net.forward(state))\n action = target_net.forward(state).argmax().view(1,1)\n #Observe new state\n timestep = env.step(action)\n \n print(action)\n print(timestep.observation['board'])\n\nplot_episode()\n\n","sub_path":"other_code/pytorch_dqn_agent.py","file_name":"pytorch_dqn_agent.py","file_ext":"py","file_size_in_byte":14970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"288642319","text":"import inspect\nimport logging\nimport venusian\nfrom pyramid.config import predicates\n\nlog = logging.getLogger(__name__)\n\nSERVICES = {}\n\n\ndef get_services():\n return SERVICES.values()\n\n\nclass ViewMapper(object):\n \"\"\" Mapper to pass request specific data to view method\n \"\"\"\n\n ROOT_ARRAY_KW_NAME = \"items\"\n\n def __init__(self, **kw):\n self.attr = kw.get('attr')\n\n def __call__(self, view):\n def wrapper(context, request):\n def json_body(request):\n \"\"\" Failsave function to access request.json_body\n \"\"\"\n try:\n body = request.json_body\n if isinstance(body, list):\n return {self.ROOT_ARRAY_KW_NAME: body}\n return body\n except:\n return {}\n\n def mapply(func, request):\n \"\"\" This function passes request.matchdict, request.params and\n request.json_body as kwargs to the given function\n \"\"\"\n kw = {}\n # add kwargs from matchdict\n kw.update(request.matchdict)\n\n # add kwargs from request params\n kw.update(dict(request.params.items()))\n\n # add kwargs from request body\n kw.update(json_body(request))\n\n return func(**kw)\n\n inst = view(request)\n meth = getattr(inst, self.attr)\n return mapply(meth, request)\n return wrapper\n\n\nclass BaseRouteNotFoundException(Exception):\n \"\"\" A exception to indicate that the required base route was not found\n\n Possible reasons for this exception:\n - the route has not been defined\n - the config has not been commited before calling config.scan()\n \"\"\"\n\n\nclass RestService(object):\n \"\"\" Decorator for REST API classes\n\n @RestService('users')\n class UserService(object):\n\n def __init__(self, request):\n self.request = request\n\n @rpcmethod(route_suffix='/{id}', request_method='PUT')\n def edit(self, id, data):\n # code goes here\n\n def includeme(config):\n config.add_route('users', '/users', static=True)\n \"\"\"\n\n venusian = venusian\n\n def reverse_engineer_route(self, route):\n kw = {}\n if route.factory:\n kw['factory'] = route.factory\n if route.pregenerator:\n kw['pregenerator'] = route.pregenerator\n\n def xhr(p):\n kw['xhr'] = p.val\n\n def path_info(p):\n kw['path_info'] = p.val.pattern\n\n def request_param(p):\n kw['request_param'] = p.val[0]\n\n def header(p):\n kw['header'] = p.text().split(\" \", 1)[-1]\n\n def accept(p):\n kw['accept'] = p.val\n\n def custom_predicates(p):\n if not 'custom_predicates' in kw:\n kw['custom_predicates'] = []\n kw['custom_predicates'].append(p.func)\n\n def request_method(p):\n kw['request_method'] = p.val[0]\n predicate_map = {predicates.XHRPredicate: xhr,\n predicates.PathInfoPredicate: path_info,\n predicates.RequestParamPredicate: request_param,\n predicates.HeaderPredicate: header,\n predicates.AcceptPredicate: accept,\n predicates.CustomPredicate: custom_predicates,\n predicates.RequestMethodPredicate: request_method,\n }\n for p in route.predicates:\n predicate_map[p.__class__](p)\n return kw\n\n def __init__(self, baseRouteName, **view_kwargs):\n self.baseRouteName = baseRouteName\n self.serviceName = None\n self.view_kwargs = view_kwargs\n # All methods of the services get registered here for sphinx autodoc\n self.methods = []\n\n def __call__(self, wrapped):\n def callback(context, name, service):\n config = context.config.with_package(info.module)\n # load the base route to get it's resolved pattern\n mapper = config.get_routes_mapper()\n baseRoute = mapper.get_route(self.baseRouteName)\n if baseRoute is None:\n raise BaseRouteNotFoundException\n # get default route arguments\n route_defaults = self.reverse_engineer_route(baseRoute)\n\n # get all rpcmethod decorated members\n def isRESTMethod(obj):\n return (inspect.ismethod(obj)\n and (hasattr(obj, '__rpc_method_route__') or\n hasattr(obj, '__rpc_method_view__'))\n )\n methods = inspect.getmembers(service, isRESTMethod)\n # register the service\n self.serviceName = '@'.join((self.baseRouteName, baseRoute.path))\n SERVICES[self.serviceName] = self\n self.description = service.__doc__\n # if the module is used multiple times for documentation generation\n # the service get registered a few times so reset methods here.\n self.methods = []\n # loop through all decorated methods and add a route and a view\n # for it\n for (methodName, method) in methods:\n route_kw = {}\n route_kw.update(route_defaults)\n if hasattr(method, '__rpc_method_route__'):\n route_kw.update(method.__rpc_method_route__)\n # allow http method GET by default\n if 'request_method' not in route_kw:\n route_kw['request_method'] = 'GET'\n view_kw = {}\n view_kw.update(self.view_kwargs)\n if hasattr(method, '__rpc_method_view__'):\n view_kw.update(method.__rpc_method_view__)\n route_name = ('.'.join((self.baseRouteName, methodName))\n + '@'\n + baseRoute.path\n )\n pattern = baseRoute.pattern + route_kw.pop('route_suffix', '')\n # Register method\n validator = None\n if method.im_func.__name__ == 'validation_wrapper':\n # index 2 of func_closure is the schema param of the\n # validate method in the tuple, not accessible via keyword\n validator = method.im_func.func_closure[2].cell_contents\n self.methods.append(\n (pattern, route_kw, view_kw, method, validator))\n config.add_route(route_name, pattern, **route_kw)\n config.add_view(view=service,\n route_name=route_name,\n attr=methodName,\n mapper=ViewMapper,\n renderer='json',\n **view_kw)\n log.debug('Adding REST method %s %s (%s)',\n route_kw['request_method'], pattern, route_name)\n\n info = self.venusian.attach(wrapped, callback, category='restservice',\n depth=1)\n return wrapped\n\n\ndef rpcmethod_route(context_factory=None, **kwargs):\n \"\"\" Decorator to mark methods of classes decorated with `RestService`\n as member of the REST Service\n \"\"\"\n\n def wrapper(f):\n f.context_factory = context_factory\n f.__rpc_method_route__ = kwargs\n return f\n return wrapper\n\n\ndef rpcmethod_view(context_factory=None, **kwargs):\n \"\"\" Decorator to mark methods of classes decorated with `RestService`\n as member of the REST Service\n \"\"\"\n\n def wrapper(f):\n f.context_factory = context_factory\n f.__rpc_method_view__ = kwargs\n return f\n return wrapper\n","sub_path":"lovely/pyrest/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":7881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"276313731","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom unittest import TestCase\r\n\r\nfrom tests.util import async_test, MonadSession\r\n\r\n\r\nclass TestCoroutineWeb(TestCase):\r\n @classmethod\r\n @async_test\r\n async def setUpClass(cls):\r\n cls.client = MonadSession()\r\n\r\n @classmethod\r\n @async_test\r\n async def tearDownClass(cls):\r\n await cls.client.close()\r\n cls.client = None\r\n\r\n @async_test\r\n async def test_basic_get(self):\r\n async with self.client.get('/test/get') as resp:\r\n self.assertEqual(resp.status, 200)\r\n msg = await resp.json()\r\n\r\n self.assertEqual(msg['msg'], 'Success')\r\n self.assertIsNone(msg['error'])\r\n\r\n @async_test\r\n async def test_get_param(self):\r\n params = dict(param='Get Param')\r\n async with self.client.get('/test/get_params', params=params) as resp:\r\n msg = await resp.json()\r\n\r\n self.assertIsNone(msg['error'])\r\n self.assertEqual(msg['msg'], 'Get Param')\r\n\r\n @async_test\r\n async def test_get_missing_param(self):\r\n async with self.client.get('/test/get_params') as resp:\r\n self.assertEqual(resp.status, 400)\r\n msg = await resp.json()\r\n\r\n self.assertIsNotNone(msg['error'])\r\n self.assertEqual(msg['error'], 'request:missing_params')\r\n\r\n @async_test\r\n async def test_get_param_default(self):\r\n params = dict(param='Get Param')\r\n async with self.client.get('/test/get_default_params', params=params) as resp:\r\n msg = await resp.json()\r\n\r\n self.assertIsNone(msg['error'])\r\n self.assertEqual(msg['msg'], 'Get Param DEFAULT')\r\n\r\n @async_test\r\n async def test_post(self):\r\n payload = dict(data='Post Data')\r\n async with self.client.post('/test/post', data=payload) as resp:\r\n self.assertEqual(resp.status, 200)\r\n msg = await resp.json()\r\n\r\n self.assertIsNone(msg['error'])\r\n self.assertEqual(msg['msg'], 'Post Data')\r\n\r\n @async_test\r\n async def test_api_error(self):\r\n async with self.client.get('/test/api_error') as resp:\r\n self.assertEqual(resp.status, 400)\r\n msg = await resp.json()\r\n\r\n self.assertEqual(msg['error'], 'test:test_error')\r\n self.assertEqual(msg['msg'], 'Some Error')\r\n\r\n @async_test\r\n async def test_204(self):\r\n async with self.client.get('/test/204') as resp:\r\n self.assertEqual(resp.status, 204)\r\n\r\n @async_test\r\n async def test_return_str(self):\r\n async with self.client.get('/test/return_str') as resp:\r\n msg = await resp.text()\r\n\r\n self.assertEqual(msg, 'Hello')\r\n\r\n @async_test\r\n async def test_return_byte(self):\r\n async with self.client.get('/test/return_byte') as resp:\r\n msg = await resp.read()\r\n\r\n self.assertEqual(msg, b'Hello bytes')\r\n\r\n @async_test\r\n async def test_return_with_500(self):\r\n async with self.client.get('/test/return_with_500') as resp:\r\n self.assertEqual(resp.status, 500)\r\n msg = await resp.text()\r\n\r\n self.assertEqual(msg, 'Server internal error (fake)')\r\n\r\n @async_test\r\n async def test_websocket(self):\r\n async with self.client.ws_connect('/test/websocket') as ws:\r\n await ws.send_json(dict(type='msg', msg='Hello from test client'))\r\n msg = (await ws.receive_json())['msg']\r\n self.assertEqual(msg, 'Hello from test client')\r\n\r\n await ws.send_json(dict(type='hello'))\r\n msg = (await ws.receive_json())['error']\r\n self.assertEqual(msg, 'Invalid message type: hello')\r\n","sub_path":"tests/handlers/coroweb_test.py","file_name":"coroweb_test.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"354212982","text":"import json\nimport urllib2\nimport psycopg2\nimport string\nimport time\nimport requests\nimport csv\n\n\nconn = psycopg2.connect(\"dbname = 'message'\")\ncur = conn.cursor()\nname = cur.execute(\" SELECT gender, mobile, district, occupation, user_group, birthdate, joindate, id, connection_pk from contact\")\ncontact = []\nfor row in cur:\n\tDictContact={}\t\n\tgender = row[0]\n\tmobile = row[1]\n\tdistrict = row[2]\n\tuser_group = row[4]\n\tbirthdate = row[5] or ''\n\tjoindate = row[6]\n\tid = row[7]\n\tconnection_pk = row[8]\n\tif len(user_group) == 0:\n\t\tuser_group = ''\n\t\tuser_group += 'UReporter'\n\telse:\n\t\tuser_group += ', UReporter'\n\tif len(gender) == 0:\n\t\tuser_group += ', UReport No Gender'\n\tif len(district) == 0:\n\t\tuser_group += ', UReport No District'\n\tif birthdate == '':\n\t\tuser_group += ', UReport No Age'\n\tDictContact['id'] = id\n\tDictContact['connection_id'] = connection_pk\n\tDictContact['mobile'] = mobile\n\tDictContact['gender'] = gender\n\tDictContact['district'] = district\n\tDictContact['user_group'] = user_group\n\tDictContact['join_date'] = str(joindate)\n\tDictContact['birthdate'] = birthdate \n\tcontact.append(DictContact)\n\nwith open('stocks.csv','w') as f:\n\theaders = ['id','connection_id','mobile','gender','district','user_group','join_date','birthdate']\n\tf_csv = csv.DictWriter(f, headers)\n\tf_csv.writeheader()\n\tf_csv.writerows(contact)\n","sub_path":"JSON/to_csv.py","file_name":"to_csv.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"599345878","text":"\ndef get_backbone_connections(pdb_hierarchy):\n backbone_connections = []\n count = 0\n for chain in pdb_hierarchy.chains():\n residues = chain.residue_groups()\n if(not is_amino_acid(residues[0])):\n count = count + len(residues)\n else:\n for i in range(len(residues)):\n residue = residues[i]\n resid = residue.resseq_as_int()\n count = count + 1\n if(len(residues) > 1 and i < len(residues) - 1):\n if(resid == residues[i + 1].resseq_as_int() - 1):\n backbone_connections.append([count, count + 1])\n return backbone_connections\n\ndef is_amino_acid(residue):\n atom_C, atom_N, atom_O, atom_CA, amino_acid = (False,) * 5\n for atom in residue.atoms():\n if(atom.name.strip() == \"N\"):\n atom_N = True\n if(atom.name.strip() == \"CA\"):\n atom_CA = True\n if(atom.name.strip() == \"O\"):\n atom_O = True\n if(atom.name.strip() == \"C\"):\n atom_C = True\n if(atom_C is True and atom_N is True and atom_O is True and atom_CA is True):\n amino_acid = True\n return amino_acid\n\ndef backbone_nitrogen(residue):\n if(is_amino_acid(residue) is True):\n for atom in residue.atoms():\n if(atom.name.strip() is \"N\"):\n return list(atom.xyz)\n\ndef backbone_nitrogen_H(residue):\n if(is_amino_acid(residue) is True):\n for atom in residue.atoms():\n if(atom.name.strip() is \"H\"):\n return list(atom.xyz)\n\ndef backbone_carbon(residue):\n if(is_amino_acid(residue) is True):\n for atom in residue.atoms():\n if(atom.name.strip() is \"C\"):\n return list(atom.xyz)\n\ndef backbone_carbon_O(residue):\n if(is_amino_acid(residue) is True):\n for atom in residue.atoms():\n if(atom.name.strip() is \"O\"):\n return list(atom.xyz)\n\ndef is_nterminal_residue(chain_id, residue_id, pdb_hierarchy):\n nterminal = False\n for chain in pdb_hierarchy.chains():\n if(chain.id == chain_id and chain.residue_groups()[0].resseq_as_int() == residue_id):\n nterminal = True\n break\n return nterminal\n\ndef is_cterminal_residue(chain_id, residue_id, pdb_hierarchy):\n cterminal = False\n for chain in pdb_hierarchy.chains():\n if(chain.id == chain_id and chain.residue_groups()[-1].resseq_as_int() == residue_id):\n cterminal = True\n break\n return cterminal\n\n ## just for amino acids\ndef get_edge_atom_positions(pdb_hierarchy, sub_pdb_hierarchy, charge_embed=False):\n positions = []\n for chain in sub_pdb_hierarchy.chains():\n residues = chain.residue_groups()\n for i in range(len(residues)):\n resid = residues[i].resseq_as_int()\n residue = residues[i]\n if(len(residues) == 1):\n if(not is_nterminal_residue(chain.id, resid, pdb_hierarchy)):\n positions.append(backbone_nitrogen(residue))\n if(charge_embed):\n positions.append(backbone_nitrogen_H(residue))\n if(not is_cterminal_residue(chain.id, resid, pdb_hierarchy)):\n positions.append(backbone_carbon(residue))\n if(charge_embed):\n positions.append(backbone_carbon_O(residue))\n if(len(residues) > 1):\n if(i == 0):\n if(not is_nterminal_residue(chain.id, resid, pdb_hierarchy)):\n positions.append(backbone_nitrogen(residue))\n if(charge_embed):\n positions.append(backbone_nitrogen_H(residue))\n if(resid != residues[i + 1].resseq_as_int() - 1):\n positions.append(backbone_carbon(residue))\n if(charge_embed):\n positions.append(backbone_carbon_O(residue))\n elif(i == len(residues) - 1):\n if not is_cterminal_residue(chain.id, resid, pdb_hierarchy):\n positions.append(backbone_carbon(residue))\n if(charge_embed):\n positions.append(backbone_carbon_O(residue))\n if(resid != residues[i - 1].resseq_as_int() + 1):\n positions.append(backbone_nitrogen(residue))\n if(charge_embed):\n positions.append(backbone_nitrogen_H(residue))\n elif(i != 0 and i != len(residues) - 1):\n if(resid != residues[i + 1].resseq_as_int() - 1):\n positions.append(backbone_carbon(residue))\n if(charge_embed):\n positions.append(backbone_carbon_O(residue))\n if(resid != residues[i - 1].resseq_as_int() + 1):\n positions.append(backbone_nitrogen(residue))\n if(charge_embed):\n positions.append(backbone_nitrogen_H(residue))\n positions = filter(lambda x: x is not None, positions)\n return positions\n","sub_path":"utils/fragment_utils.py","file_name":"fragment_utils.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"589010147","text":"# đề 1 \r\n#Bài 1: Viết chương trình để xóa bỏ ký tự thứ m trong chuỗi không rỗng, với m là số không âm, nhập từ bàn phím.\r\nm = int(input(\"nhap m= \"))\r\nchuoi=str(input(\"nhap chuoi: \"))\r\nfor i in range (m):\r\n if (chuoi[i] == m):\r\n chuoi[i] == ''\r\n print(chuoi[i])\r\n \r\n \r\n\r\n","sub_path":"le_kieu_anh-12MMC-1813020005/BT1.py","file_name":"BT1.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"386644847","text":"import pandas as pd\r\n\r\n\r\n\r\ndf = pd.read_csv('res.csv',names=['feature_type','latitude'])\r\nfail_list=df['feature_type'].unique()\r\n\r\nfor fail_attribute in fail_list:\r\n attribute_df = df.loc[df['feature_type']==fail_attribute]\r\n attribute_df.loc[:,'latitude']=attribute_df.loc[:,'latitude'].apply(lambda x:x.split(',')[0]+x.split(',')[-1])\r\n attribute_df.to_html('{fail_attribute}.html'.format(fail_attribute=fail_attribute))\r\n\r\n\r\ndf_res=df.groupby(['feature_type']).count()\r\nprint(df_res.columns.tolist())\r\ndf_res.to_html('report.html',header=None)\r\nwith open ('report.html','a') as f:\r\n f.writelines('''''')\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"trunk/generate_shape_report.py","file_name":"generate_shape_report.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"171113173","text":"import unittest\nimport time\nimport os\nimport logging\nimport json\nfrom fabnet.core import constants\nconstants.CHECK_NEIGHBOURS_TIMEOUT = 1\nfrom fabnet.core.fri_server import FriServer, FabnetPacketRequest, FabnetPacketResponse\nfrom fabnet.core.key_storage import FileBasedKeyStorage\nfrom fabnet.core.operator import Operator\nfrom fabnet.core.operation_base import OperationBase\nfrom fabnet.utils.logger import logger\nfrom datetime import datetime\n\nfrom fabnet.core.constants import NODE_ROLE, CLIENT_ROLE\n\nlogger.setLevel(logging.DEBUG)\n\nVALID_STORAGE = './tests/cert/test_keystorage.zip'\nINVALID_STORAGE = './tests/cert/test_keystorage_invalid.zip'\nPASSWD = 'qwerty123'\n\n\nclass EchoOperation(OperationBase):\n ROLES = [NODE_ROLE, CLIENT_ROLE]\n def before_resend(self, packet):\n pass\n\n def process(self, packet):\n open('/tmp/server1.out', 'w').write(json.dumps(packet.to_dict()))\n return FabnetPacketResponse(ret_code=0, ret_message='ok', ret_parameters={'message': packet.parameters['message']})\n\n def callback(self, packet, sender):\n open('/tmp/server2.out', 'w').write(json.dumps(packet.to_dict()))\n\n\nclass TestAbstractOperator(unittest.TestCase):\n def test00_echo_operation(self):\n self.__test_server()\n\n def test01_ssl_echo_operation(self):\n self.__test_server(FileBasedKeyStorage(VALID_STORAGE, PASSWD))\n\n def __test_server(self, keystorage=None):\n server1 = server2 = None\n try:\n operator = Operator('127.0.0.1:1986', key_storage=keystorage)\n operator.neighbours = ['127.0.0.1:1987']\n operator.register_operation('ECHO', EchoOperation)\n server1 = FriServer('0.0.0.0', 1986, operator, 10, 'node_1', keystorage)\n ret = server1.start()\n self.assertEqual(ret, True)\n\n operator = Operator('127.0.0.1:1987', key_storage=keystorage)\n operator.neighbours = ['127.0.0.1:1986']\n operator.register_operation('ECHO', EchoOperation)\n server2 = FriServer('0.0.0.0', 1987, operator, 10, 'node_2', keystorage)\n ret = server2.start()\n self.assertEqual(ret, True)\n\n packet = { 'message_id': 323232,\n 'method': 'ECHO',\n 'sync': False,\n 'sender': '127.0.0.1:1987',\n 'parameters': {'message': 'test message'}}\n\n if keystorage:\n packet['session_id'] = keystorage.get_node_cert_key()\n\n packet_obj = FabnetPacketRequest(**packet)\n rcode, rmsg = operator.call_node('127.0.0.1:1986', packet_obj)\n self.assertEqual(rcode, 0, rmsg)\n\n operator.wait_response(323232, 1)\n\n self.assertEqual(os.path.exists('/tmp/server1.out'), True)\n self.assertEqual(os.path.exists('/tmp/server2.out'), True)\n\n request = json.loads(open('/tmp/server1.out').read())\n response = json.loads(open('/tmp/server2.out').read())\n self.assertEqual(request, packet)\n good_resp = {'from_node': '127.0.0.1:1986','message_id': 323232,\n 'ret_code': 0,\n 'ret_message': 'ok',\n 'ret_parameters': {'message': 'test message'}}\n self.assertEqual(response, good_resp)\n finally:\n if server1:\n server1.stop()\n if server2:\n server2.stop()\n\n def test02_ssl_bad_cert(self):\n keystorage = FileBasedKeyStorage(VALID_STORAGE, PASSWD)\n inv_keystorage = FileBasedKeyStorage(INVALID_STORAGE, PASSWD)\n server1 = server2 = None\n try:\n operator = Operator('127.0.0.1:1986', key_storage=keystorage)\n operator.neighbours = ['127.0.0.1:1987']\n operator.register_operation('ECHO', EchoOperation)\n server1 = FriServer('0.0.0.0', 1986, operator, 10, 'node_1', keystorage)\n ret = server1.start()\n self.assertEqual(ret, True)\n\n operator = Operator('127.0.0.1:1987', key_storage=inv_keystorage)\n operator.neighbours = ['127.0.0.1:1986']\n operator.register_operation('ECHO', EchoOperation)\n server2 = FriServer('0.0.0.0', 1987, operator, 10, 'node_2', inv_keystorage)\n ret = server2.start()\n self.assertEqual(ret, True)\n\n packet = { 'message_id': 323232,\n 'method': 'ECHO',\n 'sync': False,\n 'sender': '127.0.0.1:1987',\n 'parameters': {'message': 'test message'}}\n packet_obj = FabnetPacketRequest(**packet)\n rcode, rmsg = operator.call_node('127.0.0.1:1986', packet_obj)\n self.assertEqual(rcode, 1, rmsg)\n\n time.sleep(.1)\n finally:\n if server1:\n server1.stop()\n if server2:\n server2.stop()\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/abstract_operator_test.py","file_name":"abstract_operator_test.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"651704460","text":"from flask import Flask, render_template\nfrom flask import request, escape\nfrom google.cloud import texttospeech\nimport random\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n input_text_user = str(escape(request.args.get(\"input_text\", \"\")))\n gender = str(escape(request.args.get(\"gender\", \"\")))\n if input_text_user:\n print(\"Text content: \" + input_text_user)\n print(\"Audio gender: \" + gender)\n stored_file = synthesize_audio(input_text_user, gender)\n result = render_template('index.html', the_audio=stored_file)\n else:\n result = \"\"\n return \"\"\"\n
\"\"\" + result\n\n# @app.route(\"/\")\ndef synthesize_audio(input_text, gender):\n \"\"\"Creates the speech for a given string\"\"\"\n try:\n # Instantiates a client\n client = texttospeech.TextToSpeechClient()\n SSML_MALE=\"1\"\n SSML_FEMALE=\"2\"\n # \"\"\" Creates a list with all of the english voices \"\"\"\n allowed_language_codes = [\"en-US\", \"en-AU\", \"en-IN\", \"en-GB\"]\n voices_list = list(client.list_voices().voices)\n english_voices = [voice for voice in voices_list if voice.language_codes[0] in allowed_language_codes]\n \n # \"\"\" Splits the list into male and female voices \"\"\"\n male_en_voices = list()\n female_en_voices = list()\n for voice in english_voices:\n if str(voice.ssml_gender) == SSML_FEMALE:\n female_en_voices.append(voice)\n elif str(voice.ssml_gender) == SSML_MALE:\n male_en_voices.append(voice)\n # Choose voice based on gender\n chosen_voice = random.choice(male_en_voices) if gender == \"male\" else random.choice(female_en_voices)\n # Create a custom config, it will configure parameters based on caller profile\n custom_audio_config = process_emotion(\"stressed\")\n # Set the text input to be synthesized\n synthesis_input = {\"text\": input_text}\n # synthesis_input = texttospeech.types.SynthesisInput(str(input_text))\n # Build the voice request, select the language code (\"en-US\") and the ssml\n voice = texttospeech.types.VoiceSelectionParams(\n language_code = chosen_voice.language_codes[0],\n ssml_gender = chosen_voice.ssml_gender,\n )\n # Select the type of audio file you want returned\n audio_config = texttospeech.types.AudioConfig(\n audio_encoding = texttospeech.enums.AudioEncoding.LINEAR16,\n effects_profile_id = ['telephony-class-application'],\n speaking_rate = custom_audio_config.rate,\n pitch = custom_audio_config.pitch,\n volume_gain_db = custom_audio_config.volume,\n )\n # Perform the text-to-speech request on the text input with the selected\n # voice parameters and audio file type\n resp = client.synthesize_speech(synthesis_input, voice, audio_config)\n # The response's audio_content is binary.\n with open('static/output.wav', 'wb') as out:\n # Write the response to the output file.\n out.write(resp.audio_content)\n print('Audio content written to file \"static/output.wav\"')\n return \"output.wav\"\n except ValueError:\n return \"Invalid entry\"\n\ndef process_emotion(emotion):\n cc = CustomAudioConfig()\n if emotion=='upset':\n cc.set_values(1.2,2,16)\n elif emotion=='sad':\n cc.set_values(0.65,-3,-4)\n elif emotion=='stressed':\n cc.set_values(1.3,2,0)\n elif emotion=='calm':\n cc.set_values(1,0,0)\n return cc\n\nclass CustomAudioConfig:\n def __init__(self, r=0, p=0 ,l=0):\n self.set_values(r,p,l)\n \n def set_values(self, r=0, p=0 ,l=0):\n self.rate = r\n self.pitch = p\n self.volume = l\n\n def values(self):\n print(f\"Rate: {self.rate}, Pitch: {self.pitch}, Volume:{self.volume}\")\n\nif __name__ == \"__main__\":\n app.run(host=\"127.0.0.1\", port=8080, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"504849500","text":"import re\n\nimport pytest\n\nfrom hiku import query\nfrom hiku.graph import Graph, Node, Field, Link, Option, Root\nfrom hiku.types import Record, Sequence, Integer, Optional, TypeRef\nfrom hiku.compat import text_type\nfrom hiku.engine import Engine, pass_context, Context\nfrom hiku.executors.sync import SyncExecutor\nfrom hiku.readers.simple import read\n\nfrom .base import reqs_eq_patcher, check_result, ANY, Mock\n\n\ndef execute(graph, query_, ctx=None):\n engine = Engine(SyncExecutor())\n return engine.execute(graph, read(text_type(query_)), ctx=ctx)\n\n\ndef test_root_fields():\n f1 = Mock(return_value=['boiardo'])\n f2 = Mock(return_value=['isolde'])\n\n graph = Graph([\n Root([\n Field('a', None, f1),\n Field('b', None, f2),\n ]),\n ])\n\n result = execute(graph, '[:a :b]')\n check_result(result, {'a': 'boiardo', 'b': 'isolde'})\n\n with reqs_eq_patcher():\n f1.assert_called_once_with([query.Field('a')])\n f2.assert_called_once_with([query.Field('b')])\n\n\ndef test_root_node_fields():\n f1 = Mock(return_value=['khios'])\n f2 = Mock(return_value=['cambay'])\n\n graph = Graph([\n Root([\n Node('a', [\n Field('b', None, f1),\n Field('c', None, f2),\n ]),\n ]),\n ])\n\n result = execute(graph, '[{:a [:b :c]}]')\n check_result(result, {'a': {'b': 'khios', 'c': 'cambay'}})\n\n with reqs_eq_patcher():\n f1.assert_called_once_with([query.Field('b')])\n f2.assert_called_once_with([query.Field('c')])\n\n\ndef test_node_fields():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[['harkis']])\n f3 = Mock(return_value=[['slits']])\n\n graph = Graph([\n Node('a', [\n Field('b', None, f2),\n Field('c', None, f3),\n ]),\n Root([\n Link('d', Sequence[TypeRef['a']], f1, requires=None),\n ]),\n ])\n\n result = execute(graph, '[{:d [:b :c]}]')\n check_result(result, {'d': [{'b': 'harkis', 'c': 'slits'}]})\n assert result.index == {'a': {1: {'b': 'harkis', 'c': 'slits'}}}\n\n f1.assert_called_once_with()\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('b')], [1])\n f3.assert_called_once_with([query.Field('c')], [1])\n\n\ndef test_node_complex_fields():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[[{'f': 'marshes'}]])\n f3 = Mock(return_value=[[{'g': 'colline'}]])\n f4 = Mock(return_value=[[[{'h': 'magi'}]]])\n\n graph = Graph([\n Node('a', [\n Field('b', Optional[Record[{'f': Integer}]], f2),\n Field('c', Record[{'g': Integer}], f3),\n Field('d', Sequence[Record[{'h': Integer}]], f4),\n ]),\n Root([\n Link('e', Sequence[TypeRef['a']], f1, requires=None),\n ]),\n ])\n\n check_result(\n execute(graph, \"\"\"\n [{:e [{:b [:f]} {:c [:g]} {:d [:h]}]}]\n \"\"\"),\n {'e': [{'b': {'f': 'marshes'},\n 'c': {'g': 'colline'},\n 'd': [{'h': 'magi'}]}]},\n )\n\n f1.assert_called_once_with()\n with reqs_eq_patcher():\n f2.assert_called_once_with(\n [query.Link('b', query.Node([query.Field('f')]))], [1],\n )\n f3.assert_called_once_with(\n [query.Link('c', query.Node([query.Field('g')]))], [1],\n )\n f4.assert_called_once_with(\n [query.Link('d', query.Node([query.Field('h')]))], [1],\n )\n\n\ndef test_links():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[2])\n f3 = Mock(return_value=[['boners']])\n f4 = Mock(return_value=[['julio']])\n\n graph = Graph([\n Node('a', [\n Field('d', None, f3),\n Field('e', None, f4),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f1, requires=None),\n Link('c', Sequence[TypeRef['a']], f2, requires=None),\n ]),\n ])\n\n result = execute(graph, '[{:b [:d]} {:c [:e]}]')\n check_result(result, {'b': [{'d': 'boners'}],\n 'c': [{'e': 'julio'}]})\n assert result.index == {'a': {1: {'d': 'boners'},\n 2: {'e': 'julio'}}}\n\n f1.assert_called_once_with()\n f2.assert_called_once_with()\n with reqs_eq_patcher():\n f3.assert_called_once_with([query.Field('d')], [1])\n f4.assert_called_once_with([query.Field('e')], [2])\n\n\ndef test_field_options():\n f = Mock(return_value=['baking'])\n\n graph = Graph([\n Root([\n Field('a', None, f),\n ]),\n ])\n\n # FIXME: options should be defined and validated\n check_result(execute(graph, '[(:a {:b \"bubkus\"})]'),\n {'a': 'baking'})\n\n with reqs_eq_patcher():\n f.assert_called_once_with([\n query.Field('a', options={'b': 'bubkus'}),\n ])\n\n\ndef test_link_option():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[['aunder']])\n\n graph = Graph([\n Node('a', [\n Field('c', None, f2),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f1, requires=None,\n options=[Option('d', None)]),\n ]),\n ])\n\n check_result(execute(graph, '[{(:b {:d \"duncery\"}) [:c]}]'),\n {'b': [{'c': 'aunder'}]})\n\n f1.assert_called_once_with({'d': 'duncery'})\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('c')], [1])\n\n\ndef test_link_option_missing():\n f = Mock()\n\n graph = Graph([\n Node('a', [\n Field('d', None, f),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f, requires=None,\n options=[Option('d', None)]),\n ]),\n ])\n\n with pytest.raises(TypeError) as err:\n execute(graph, '[{:b [:d]}]')\n err.match('^Required option \"d\" for (.*)b(.*) was not provided$')\n\n\ndef test_link_option_default_none():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[['kaitlin']])\n\n graph = Graph([\n Node('a', [\n Field('c', None, f2),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f1, requires=None,\n options=[Option('d', None, default=None)]),\n ]),\n ])\n\n check_result(execute(graph, '[{:b [:c]}]'),\n {'b': [{'c': 'kaitlin'}]})\n\n f1.assert_called_once_with({'d': None})\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('c')], [1])\n\n\ndef test_link_option_default_string():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[['rounded']])\n\n graph = Graph([\n Node('a', [\n Field('c', None, f2),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f1, requires=None,\n options=[Option('d', None, default='reaving')]),\n ]),\n ])\n\n check_result(execute(graph, '[{:b [:c]}]'),\n {'b': [{'c': 'rounded'}]})\n\n f1.assert_called_once_with({'d': 'reaving'})\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('c')], [1])\n\n\ndef test_link_option_unknown():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[['tarweed']])\n\n graph = Graph([\n Node('a', [\n Field('c', None, f2),\n ]),\n Root([\n Link('b', Sequence[TypeRef['a']], f1, requires=None,\n options=[Option('d', None, default='gerry')]),\n ]),\n ])\n\n result = execute(graph, '[{(:b {:d \"hanna\" :unknown \"linty\"}) [:c]}]')\n check_result(result, {'b': [{'c': 'tarweed'}]})\n\n f1.assert_called_once_with({'d': 'hanna'})\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('c')], [1])\n\n\ndef test_pass_context_field():\n f = pass_context(Mock(return_value=['boiardo']))\n\n graph = Graph([\n Root([\n Field('a', None, f),\n ]),\n ])\n\n check_result(execute(graph, '[:a]', {'vetch': 'shadier'}),\n {'a': 'boiardo'})\n\n with reqs_eq_patcher():\n f.assert_called_once_with(ANY, [query.Field('a')])\n\n ctx = f.call_args[0][0]\n assert isinstance(ctx, Context)\n assert ctx['vetch'] == 'shadier'\n with pytest.raises(KeyError) as err:\n _ = ctx['invalid'] # noqa\n err.match('is not specified in the query context')\n\n\ndef test_pass_context_link():\n f1 = pass_context(Mock(return_value=[1]))\n f2 = Mock(return_value=[['boners']])\n\n graph = Graph([\n Node('a', [\n Field('b', None, f2),\n ]),\n Root([\n Link('c', Sequence[TypeRef['a']], f1, requires=None),\n ]),\n ])\n\n result = execute(graph, '[{:c [:b]}]', {'fibs': 'dossil'})\n check_result(result, {'c': [{'b': 'boners'}]})\n assert result.index == {'a': {1: {'b': 'boners'}}}\n\n f1.assert_called_once_with(ANY)\n with reqs_eq_patcher():\n f2.assert_called_once_with([query.Field('b')], [1])\n\n ctx = f1.call_args[0][0]\n assert isinstance(ctx, Context)\n assert ctx['fibs'] == 'dossil'\n with pytest.raises(KeyError) as err:\n _ = ctx['invalid'] # noqa\n err.match('is not specified in the query context')\n\n\ndef test_node_link_without_requirements():\n f1 = Mock(return_value=[1])\n f2 = Mock(return_value=[2])\n f3 = Mock(return_value=[['arnhild']])\n\n graph = Graph([\n Node('a', [\n Field('c', None, f3),\n ]),\n Node('b', [\n Link('d', Sequence[TypeRef['a']], f2, requires=None),\n ]),\n Root([\n Link('e', Sequence[TypeRef['b']], f1, requires=None),\n ]),\n ])\n\n result = execute(graph, '[{:e [{:d [:c]}]}]')\n check_result(result, {'e': [{'d': [{'c': 'arnhild'}]}]})\n assert result.index == {\n 'a': {2: {'c': 'arnhild'}},\n 'b': {1: {'d': [result.ref('a', 2)]}},\n }\n\n f1.assert_called_once_with()\n f2.assert_called_once_with()\n with reqs_eq_patcher():\n f3.assert_called_once_with([query.Field('c')], [2])\n\n\n@pytest.mark.parametrize('value', [1, [], [1, 2]])\ndef test_root_field_func_result_validation(value):\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Root([\n Field('a', None, Mock(return_value=value)),\n ]),\n ]),\n '[:a]',\n )\n err.match(re.escape(\n \"Can't store field values, node: '__root__', fields: [{a!r}], \"\n \"expected: list (len: 1), returned: {value!r}\"\n .format(a=text_type('a'), value=value)\n ))\n\n\n@pytest.mark.parametrize('value', [1, [], [1, 2], [[], []], [[1], []],\n [[], [2]]])\ndef test_node_field_func_result_validation(value):\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Node('a', [\n Field('b', None, Mock(return_value=value)),\n ]),\n Root([\n Link('c', Sequence[TypeRef['a']], Mock(return_value=[1, 2]),\n requires=None),\n ]),\n ]),\n '[{:c [:b]}]',\n )\n err.match(re.escape(\n \"Can't store field values, node: 'a', fields: [{b!r}], \"\n \"expected: list (len: 2) of lists (len: 1), returned: {value!r}\"\n .format(b=text_type('b'), value=value)\n ))\n\n\n@pytest.mark.parametrize('value', [1, [], [1, 2]])\ndef test_root_node_field_func_result_validation(value):\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Root([\n Node('a', [\n Field('b', None, Mock(return_value=value))\n ]),\n ]),\n ]),\n '[{:a [:b]}]',\n )\n err.match(re.escape(\n \"Can't store field values, node: 'a', fields: [{b!r}], \"\n \"expected: list (len: 1), returned: {value!r}\"\n .format(b=text_type('b'), value=value)\n ))\n\n\ndef test_root_link_many_func_result_validation():\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Node('a', [\n Field('b', None, Mock(return_value=[[3], [4]])),\n ]),\n Root([\n Link('c', Sequence[TypeRef['a']], Mock(return_value=123),\n requires=None),\n ]),\n ]),\n '[{:c [:b]}]',\n )\n err.match(re.escape(\n \"Can't store link values, node: '__root__', link: 'c', \"\n \"expected: list, returned: 123\"\n ))\n\n\n@pytest.mark.parametrize('value', [1, [], [1, 2, 3]])\ndef test_node_link_one_func_result_validation(value):\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Node('a', [\n Field('b', None, Mock(return_value=[[1], [2]]))\n ]),\n Node('c', [\n Field('d', None, Mock(return_value=[[3], [4]])),\n Link('e', TypeRef['a'], Mock(return_value=value),\n requires='d'),\n ]),\n Root([\n Link('f', Sequence[TypeRef['c']], Mock(return_value=[1, 2]),\n requires=None),\n ]),\n ]),\n '[{:f [{:e [:b]}]}]',\n )\n err.match(re.escape(\n \"Can't store link values, node: 'c', link: 'e', expected: \"\n \"list (len: 2), returned: {!r}\".format(value)\n ))\n\n\n@pytest.mark.parametrize('value', [1, [], [1, []], [[], 2], [[], [], []]])\ndef test_node_link_many_func_result_validation(value):\n with pytest.raises(TypeError) as err:\n execute(\n Graph([\n Node('a', [\n Field('b', None, Mock(return_value=[[1], [2]]))\n ]),\n Node('c', [\n Field('d', None, Mock(return_value=[[3], [4]])),\n Link('e', Sequence[TypeRef['a']], Mock(return_value=value),\n requires='d'),\n ]),\n Root([\n Link('f', Sequence[TypeRef['c']], Mock(return_value=[1, 2]),\n requires=None),\n ]),\n ]),\n '[{:f [{:e [:b]}]}]',\n )\n err.match(re.escape(\n \"Can't store link values, node: 'c', link: 'e', expected: \"\n \"list (len: 2) of lists, returned: {!r}\".format(value)\n ))\n","sub_path":"tests/test_engine.py","file_name":"test_engine.py","file_ext":"py","file_size_in_byte":14276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"402861743","text":"# -*- coding: utf-8 -*-\n#\n# Created: 2010/09/09\n# Author: alisue\n#\nfrom django import forms\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom django.contrib.admin.widgets import AdminTextareaWidget\nfrom django.utils.safestring import mark_safe\nfrom django.core.exceptions import ImproperlyConfigured\n\n# check is configured correctly\nif not hasattr(settings, \"CODEMIRROR_PATH\"):\n raise ImproperlyConfigured(\"You must define the CODEMIRROR_PATH before using the CodeMirrorTextarea.\")\n\nif settings.CODEMIRROR_PATH.endswith('/'):\n settings.CODEMIRROR_PATH = settings.CODEMIRROR_PATH[:-1]\n \n# set default settings\nsettings.CODEMIRROR_DEFAULT_PARSERFILE = getattr(settings, 'CODEMIRROR_DEFAULT_PARSERFILE', 'parsedummy.js')\nsettings.CODEMIRROR_DEFAULT_STYLESHEET = getattr(settings, 'CODEMIRROR_DEFAULT_STYLESHEET', '')\n\nclass CodeMirrorTextarea(forms.Textarea):\n u\"\"\"Textarea widget render with `CodeMirror`\n \n CodeMirror:\n http://codemirror.net/\n \"\"\"\n\n class Media:\n css = {}\n js = (\n r\"%s/codemirror.js\" % settings.CODEMIRROR_PATH,\n )\n \n def __init__(self, attrs=None, path=None, parserfile=None, stylesheet=None, **kwargs):\n u\"\"\"Constructor of CodeMirrorTextarea\n \n Attribute:\n path - CodeMirror directory URI (DEFAULT = settings.CODEMIRROR_PATH)\n parserfile - CodeMirror parserfile attribute (string or string array: DEFAULT = settings.CODEMIRROR_DEFAULT_PARSERFILE)\n stylesheet - CodeMirror stylesheet attribute (uri or uri array: DEFAULT = settings.CODEMIRROR_DEFAULT_STYLESHEET)\n \n Example:\n *-------------------------------*\n + javascript\n + codemirror\n + css\n - xmlcolors.css\n + js\n - codemirror.js\n - parsexml.js\n *-------------------------------*\n settings.CODEMIRROR_PATH = r\"javascript/codemirror/js\"\n \n codemirror = CodeMirrorTextarea(\n # parserfile='parsexml.js', # Can be written as the left when only one file is needed.\n parserfile=['parsexml.js'],\n # stylesheet=r'javascript/codemirror/css/xmlcolors.css' # Can be written as the left when only one file is needed.\n stylesheet=[r'javascript/codemirror/css/xmlcolors.css'],\n )\n document = forms.TextField(widget=codemirror)\n \"\"\"\n super(CodeMirrorTextarea, self).__init__(attrs=attrs, **kwargs)\n self.path = path or settings.CODEMIRROR_PATH\n self.parserfile = parserfile or settings.CODEMIRROR_DEFAULT_PARSERFILE\n self.stylesheet = stylesheet or settings.CODEMIRROR_DEFAULT_STYLESHEET\n if not hasattr(self.parserfile, '__iter__'):\n self.parserfile = (self.parserfile,)\n if not hasattr(self.stylesheet, '__iter__'):\n self.stylesheet = (self.stylesheet,)\n \n def render(self, name, value, attrs=None):\n u\"\"\"Render CodeMirrorTextarea\"\"\"\n html = super(CodeMirrorTextarea, self).render(name, value, attrs)\n kwargs = {\n 'id': \"\\\"id_%s\\\"\"%name,\n 'path': \"\\\"%s%s/\\\"\"%(settings.MEDIA_URL, self.path),\n 'parserfile': \"[%s]\" % (\", \".join([\"\\\"%s\\\"\"%x for x in self.parserfile])),\n 'stylesheet': \"[%s]\" % (\", \".join([\"\\\"%s%s\\\"\"%(settings.MEDIA_URL,x) for x in self.stylesheet])),\n }\n if self.stylesheet == []:\n kwargs['stylesheet'] = '\"\"'\n for key in kwargs.keys():\n kwargs[key] = mark_safe(kwargs[key])\n code = render_to_string(r\"codemirror/javascript.html\", kwargs)\n body = \"%s\\n%s\" % (html, code)\n return mark_safe(body)\n \nclass AdminCodeMirrorTextareaWidget(CodeMirrorTextarea, AdminTextareaWidget):\n u\"\"\"CodeMirrorTextarea for Admin site\"\"\"\n pass\n","sub_path":"codemirror/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":3999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"44864008","text":"import os.path\nimport struct\nimport random\nimport logging\nimport re\nfrom pygame import Color\nfrom rw.robotml import RoboTML\nfrom rw.system import decode_hex, encode_hex\n\nlog = logging.getLogger('assets')\n\n# matches a rgb hex value like '#1a2b3c'\nhex_regex = re.compile(r'^#[0-9a-fA-F]{6}$')\n\n# matches a rgb triplet like '255,6,33'\nrgb_regex = re.compile(\n r'^'\n r'([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'\n r','\n r'([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'\n r','\n r'([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])'\n r'$'\n)\n\n\nclass Colors(object):\n def __init__(self, path):\n self.path = os.path.join(path, 'tables', 'colors')\n # dict of colors, categorized, e.g. {'primary': {'red':, 'green':}, 'text':{'normal':}}\n # each color is a pygame.Color\n self.colors = {}\n\n log.debug(\"Loading colors...\")\n color_count = 0\n\n rtml = RoboTML(self.path, 'colors', 'group')\n for color_group, row in rtml.rows:\n if color_group not in self.colors:\n self.colors[color_group] = {}\n\n color_name = row.get('id').strip() # color name, with spaces stripped\n color_value = row.get('value').replace(' ', '') # color value, with spaces stripped\n color = Colors.read_color(color_value)\n if color is None:\n log.warn(\" * invalid color: {!s} = {!s}/{!s}\".format(color_value, color_group, color_name))\n else:\n log.debug(\" * color: {!s} = {!s}/{!s}\".format(Colors.to_hex(color), color_group, color_name))\n self.colors[color_group][color_name] = color\n color_count += 1\n\n log.info(\"Loaded {!s} colors.\".format(color_count))\n\n def any(self, color_type):\n if color_type in self.colors:\n return random.choice(tuple(self.colors[color_type].values()))\n\n def get(self, color):\n if not isinstance(color, tuple):\n color = tuple(color.split('/'))\n try:\n return self.colors[color[0]][color[1]]\n except KeyError:\n log.error(\"Invalid color: {!s}\".format(color))\n return None\n\n @staticmethod\n def is_hex(color):\n return hex_regex.match(color) is not None\n\n @staticmethod\n def from_hex(color):\n if Colors.is_hex(color):\n return Color(*struct.unpack('BBB', decode_hex(color[1:])))\n return None\n\n @staticmethod\n def to_hex(color):\n return '#' + encode_hex(struct.pack('BBB', color.r, color.g, color.b))\n\n @staticmethod\n def is_rgb(color):\n return rgb_regex.match(color) is not None\n\n @staticmethod\n def from_rgb(color):\n if Colors.is_rgb(color):\n return Color(*tuple(map(int, color.split(','))))\n return None\n\n @staticmethod\n def read_color(color):\n if Colors.is_hex(color):\n return Colors.from_hex(color)\n elif Colors.is_rgb(color):\n return Colors.from_rgb(color)\n return None\n\n","sub_path":"rw/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"58433234","text":"import random, queue, time\nfrom multiprocessing.managers import BaseManager\n\nclass QueueManager(BaseManager):\n pass\n\ntask_queue = queue.Queue()\nresult_queue = queue.Queue()\n\nQueueManager.register('get_task_queue', callable=lambda: task_queue)\nQueueManager.register('get_result_queue', callable=lambda: result_queue)\n \n# 绑定端口并设置验证码,windows下需要填写ip地址,linux下不填默认为本地回环地址,全0为监听服务器上的所有地址,\n# 设为回环地址的话从windows上访问需要做端口映射\nmanager = QueueManager(address=('0.0.0.0',5000), authkey=b'abc')\nmanager.start()\nprint('manager start on server %s:%d'%manager.address)\n\ntask = manager.get_task_queue()\nresult = manager.get_result_queue()\n\n\nfor i in range(10):\n n = random.randint(0,1000)\n task.put(n)\n print('Put task %d'%n)\n\nprint('Try get results...')\nwhile result.empty():\n time.sleep(1)\n\nfor i in range(10):\n try:\n r = result.get(timeout=5)\n print('Get result: [%s]'%r)\n except queue.Empty:\n print('Result queue is empty!')\nmanager.shutdown()\nprint('master exit.')\n","sub_path":"Process_Thread/distribute_task_master_linux.py","file_name":"distribute_task_master_linux.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"74016400","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import object\n\nfrom pyMKL import pardisoinit, pardiso\nfrom ctypes import POINTER, byref, c_longlong, c_int\nimport scipy.sparse as sp\nfrom numpy import ctypeslib\n\nimport numpy as np\nimport pandas as pd\nfrom pyMKL import pardisoSolver\n\nfrom datetime import datetime\n\n\n\nmtypes = {'spd':2,\n 'symm':-2,\n 'unsymm':11}\n\nclass my_pardisoSolver(pardisoSolver):\n def __init__(self, A, my_iparm2, my_iparm10, my_iparm11, my_iparm13,\n my_iparm8, my_iparm21, my_iparm27,\n mtype=11, verbose=False, pivoting=False):\n\n self.mtype = mtype\n if mtype in [1, 3]:\n msg = \"mtype = 1/3 - structurally symmetric matrices not supported\"\n raise NotImplementedError(msg)\n elif mtype in [2, -2, 4, -4, 6, 11, 13]:\n pass\n else:\n msg = \"Invalid mtype: mtype={}\".format(mtype)\n raise ValueError(msg)\n\n\n self.n = A.shape[0]\n\n if mtype in [4, -4, 6, 13]:\n # Complex matrix\n self.dtype = np.complex128\n elif mtype in [2, -2, 11]:\n # Real matrix\n self.dtype = np.float64\n self.ctypes_dtype = ctypeslib.ndpointer(self.dtype)\n\n # If A is symmetric, store only the upper triangular portion\n if mtype in [2, -2, 4, -4, 6]:\n A = sp.triu(A, format='csr')\n elif mtype in [11, 13]:\n A = A.tocsr()\n\n if not A.has_sorted_indices:\n A.sort_indices()\n\n self.a = A.data\n self.ia = A.indptr\n self.ja = A.indices\n\n self._MKL_a = self.a.ctypes.data_as(self.ctypes_dtype)\n self._MKL_ia = self.ia.ctypes.data_as(POINTER(c_int))\n self._MKL_ja = self.ja.ctypes.data_as(POINTER(c_int))\n\n # Hardcode some parameters for now...\n self.maxfct = 1\n self.mnum = 1\n self.perm = 0\n\n if verbose:\n self.msglvl = 1\n else:\n self.msglvl = 0\n\n # Initialize handle to data structure\n self.pt = np.zeros(64, np.int64)\n self._MKL_pt = self.pt.ctypes.data_as(POINTER(c_longlong))\n\n # Initialize parameters\n self.iparm = np.zeros(64, dtype=np.int32)\n self._MKL_iparm = self.iparm.ctypes.data_as(POINTER(c_int))\n\n # Initialize pardiso\n pardisoinit(self._MKL_pt, byref(c_int(self.mtype)), self._MKL_iparm)\n\n # Set iparm\n self.iparm[1] = 3 # Use parallel nested dissection for reordering\n self.iparm[23] = 1 # Use parallel factorization\n self.iparm[34] = 1 # Zero base indexing\n\n\n # For constrained systems with highly indefinite symmetric matrices\n if pivoting:\n self.iparm[1] = my_iparm2\n\n self.iparm[9] = my_iparm10\n\n\n self.iparm[10] = my_iparm11\n self.iparm[12] = my_iparm13\n\n\n self.iparm[7] = my_iparm8\n self.iparm[20] = my_iparm21\n\n self.iparm[26] = my_iparm27\n\n\ndef solve_sparse(A, b, my_iparm2, my_iparm10, my_iparm11, my_iparm13,\n my_iparm8, my_iparm21, my_iparm27,\n matrix_type='symm', verbose=False, pivoting=False):\n\n mtype = mtypes[matrix_type]\n\n pSolve = my_pardisoSolver(A, my_iparm2, my_iparm10, my_iparm11, my_iparm13,\n my_iparm8, my_iparm21, my_iparm27,\n mtype=mtype, verbose=verbose, pivoting=pivoting)\n\n x = pSolve.run_pardiso(13, b)\n pSolve.clear()\n\n return x\n\n\ndef save_sparse_csr(filename,array):\n np.savez(filename, data=array.data, indices=array.indices,\n indptr=array.indptr, shape=array.shape)\n\ndef load_sparse_csr(filename):\n loader = np.load(filename)\n return sp.csr_matrix((loader['data'], loader['indices'], loader['indptr']),\n shape = loader['shape']), loader['res']\n\nmy_favorite_S_and_res = 'my_favorite_S_and_res.npz'\n\nS, res = load_sparse_csr(my_favorite_S_and_res)\n\n\n\nmy_iparm2_list = np.array([0, 1, 2, 3], dtype='int')\nmy_iparm8_list = np.array([0, 10], dtype='int')\nmy_iparm10_list = np.array([8, 13], dtype='int')\nmy_iparm11_list = np.array([0, 1], dtype='int')\nmy_iparm13_list = np.array([0, 1], dtype='int')\nmy_iparm21_list = np.array([0, 1, 2, 3], dtype='int')\nmy_iparm27_list = np.array([0], dtype='int')\n\niparm2_sym = []\niparm8_sym = []\niparm10_sym = []\niparm11_sym = []\niparm13_sym = []\niparm21_sym = []\niparm27_sym = []\nr_sym = []\ntime_taken = []\n\nfor my_iparm2 in my_iparm2_list:\n for my_iparm8 in my_iparm8_list:\n for my_iparm10 in my_iparm10_list:\n for my_iparm11 in my_iparm11_list:\n for my_iparm13 in my_iparm13_list:\n for my_iparm21 in my_iparm21_list:\n for my_iparm27 in my_iparm27_list:\n \n startTime = datetime.now()\n \n delta_q = solve_sparse(S, res, my_iparm2, my_iparm10,\n my_iparm11, my_iparm13,\n my_iparm8, my_iparm21,\n my_iparm27, pivoting=True)\n \n time_taken.append(datetime.now() - startTime)\n\n r = np.linalg.norm(S @ delta_q - res)\n\n iparm2_sym.append(my_iparm2)\n iparm8_sym.append(my_iparm8)\n iparm10_sym.append(my_iparm10)\n iparm11_sym.append(my_iparm11)\n iparm13_sym.append(my_iparm13)\n iparm21_sym.append(my_iparm21)\n iparm27_sym.append(my_iparm27)\n r_sym.append(r)\n\n \n\nstartTime = datetime.now()\n\ndelta_q = solve_sparse(S, res, my_iparm2, my_iparm10,\n my_iparm11, my_iparm13,\n my_iparm8, my_iparm21,\n my_iparm27, pivoting=False, matrix_type='unsymm')\n\ntime_taken.append(datetime.now() - startTime)\n\nr = np.linalg.norm(S @ delta_q - res)\n\niparm2_sym.append(my_iparm2)\niparm8_sym.append(my_iparm8)\niparm10_sym.append(my_iparm10)\niparm11_sym.append(my_iparm11)\niparm13_sym.append(my_iparm13)\niparm21_sym.append(my_iparm21)\niparm27_sym.append(my_iparm27)\nr_sym.append(r)\n\nmy_data = {'residuum': r_sym,\n 'iparm2' : iparm2_sym,\n 'iparm8' : iparm8_sym,\n 'iparm10' : iparm10_sym,\n 'iparm11' : iparm11_sym,\n 'iparm13' : iparm13_sym,\n 'iparm21' : iparm21_sym,\n 'iparm27' : iparm27_sym,\n 'time' : time_taken,\n }\n \nmy_dataframe = pd.DataFrame(my_data)\n\nprint(my_dataframe.sort_values('residuum', ascending=True)[:30])\n\n","sub_path":"test_sym_indef.py","file_name":"test_sym_indef.py","file_ext":"py","file_size_in_byte":7070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"48464696","text":"'''\n20 Nov, Dealga McArdle. 2011\nPostScript to JavaScript/paperJS converter written in Python.\n\nThis script is released under the MIT license. With no warranty/support of any kind.\nJavaScript, Adobe and PostScript are registered trademarks and property of their\nrespective owners. The Adobe PostScript References, PLRM.pdf, is available for free\nfrom their site. Their TOC implies that it's OK to write programs that parse their\n.ps filetype. I plan to support commands as i encounter them.\n\n20 Nov, Basic Parsing and javascript writer for commands (m/l/c/h)\n22 Nov, Added empty Path removal function, while debugging. added g and rg (colour!)\n23 Nov, Pruning. Ignores a moveTo statement if it doesn't assist drawing.\n23 Nov, Mostly no empty paths are created, i'll retain the function as a fallback. \n\n- [todo] Attempt to parse more than mlch cases.. line/width/dash\n\n'''\n\nimport re\nfrom PSHelper import pointify_coordinates\nfrom PSHelper import convert_to_curve_parameters\n\nfrom PSHelper import parse_colour_line\nfrom PSHelper import set_command_value\nfrom PSHelper import fix_plotListString\n\nfrom PSHelper import write_sorting_functions\nfrom PSHelper import write_empty_path_removal_function\nfrom PSHelper import write_html_header\nfrom PSHelper import write_html_footer\n\n\nrectHeight = 0\nrectWidth = 0\ncurrentColour = \"\"\n\n\n\n'''Work Functions'''\n\ndef get_postscript(filename):\n '''\n minimal error checking, until the script progresses\n\n input: A valid file, at a valid path\n output: A multidimensional List of commands and coordinates.\n \n my understanding is this;\n - PostScript has the values first, then the function names.\n - the usuable data starts after the line '0 g' and ends at Q Q \n - thereafter the delimiter is f (f is fill) or h (to close path)\n - i will be ignoring colour. don't expect this parser to deal\n with anything other than black typography, kind of like a model T Ford.\n '''\n\n \n # first look to see if we can read this file, return None if we experience unexpected data\n # i skip pagesetup.\n foundStartToken = False\n usableFileString = \"\"\n global rectHeight\n global rectWidth\n \n filedata = open(filename)\n for line in filedata:\n if line.endswith(\"rectclip q\\n\"):\n line = line[:-1]\n rectHeight = line.split()[-3]\n rectWidth = line.split()[-4]\n dimensions = rectWidth + \" * \" + rectHeight \n print(\"Found rectclip it suggests rect dimensions are: \" + dimensions)\n foundStartToken = True\n continue\n \n if line.endswith(\"Q Q\\n\"):\n print(\"Found a valid end\")\n break\n\n if foundStartToken == True:\n usableFileString += line[:-1]\n\n\n filedata.close()\n\t\n if foundStartToken == False:\n return None\n \n # at this point usableFileString contains all parsable lines, minus newline.\n # let's return usableFileString without trailing whitespace \n return usableFileString.rstrip()\n\n\n\ndef regex_this_string(subString):\n '''\n Takes an unsplit string, and splits by m/l/c/h commands respectively\n\n intput: String, in the form of a split ps file, (split by f character)\n output: Array of coordinates and command they are associated with.\n '''\n \n # my pattern is a little dirty , doesn't find 'rg'for colour.\n p = re.compile('(([-0-9.]+\\s)+[r]*[gmlc])|[h]')\n m = p.findall(subString)\n\n # adding the [0] strips the extra data,\n # but the pattern should be repaired instead.\n cleanStringList = []\n for i in m:\n if i == ('',''):\n cleanStringList.append(\"h\")\n else:\n cleanStringList.append(i[0])\n return cleanStringList\n\n\n\ndef regex_plotListString(plotListString):\n '''this function takes the second half of the instructions extracted from the ps\n\n The function exists only because supporting more commands was a bit of an afterthought,\n it requires some fixing by fix_plotListString due to zealous string chopping at the start.\n It feels a little wonky, and it is, but this gives me some idea of what to do next.\n Ultimately the initial parse pass should take care of both Paths and Shapes.\n\n intput: unformated primitive plot instructions like lines/dashes/circles\n output: after applying regular expressions the instructions are stored in a list and\n can be used similarly to c;eanStringList\n '''\n\n plotListString = fix_plotListString(plotListString)\n\n primitive_commands = re.compile(r\"\"\"\n\n [0-9.]+\\s[w] # value w = line width, and accepts int and floats\n | [-0-9.]+\\s[JjmM] # value J = set line cap\n # value j = set line join\n # value M = set miter limit\n | [-0-9.]+\\s[-0-9.]+\\s[ml] # value value m = move to\n # value value l = line to\n | [[][-0-9. ]*[]][-0-9. ]+[d]\\s\\b # [optional value] value d =\n | [q][-0-9. ]+\\s[c][m] # q value value value value cm =\n | [-0-9. ]+\\s[c] # value*6 c = curve to\n | [S] # S = set stroke\n | [Q] # Q = seems to be a delimter.\n | [h] # h = closePath();\n \n \"\"\", re.VERBOSE)\n\n m = primitive_commands.findall(plotListString)\n mclean = []\n for i in m:\n mclean.append( i.lstrip())\n\n return mclean\n\n\n\ndef parse_postscript(fullString):\n '''\n Takes the usable part of the ps file (without newlines) and chops it up.\n\n intput: takes full string from get_postscript function\n output: generates a list of discrete commands for every object found.\n '''\n \n commandList = []\n\n # because the last possible parsable character is an f\n commandListString = fullString.split(\" f\")[:-1]\n for item in commandListString:\n commandList.append(regex_this_string(item))\n\n # plotList takes the last chunk, this seems to be the primitive path drawing (ie not shapes)\n # should send extra regex here.\n plotListString = fullString.split(\" f\")[-1]\n plotList = regex_plotListString(plotListString)\n \n return commandList, plotList \n\n\n\ndef write_postscript_functions(newPath, functionName, writefile):\n '''\n Create separated functions for each path/compound path, probably a backwards way..\n\n input: parsed List of path commands for each glyph ( one glyph may contain 1 or more paths)\n output: adds functions to the currently open file.\n\n This function should be extended to deal with line objects that have width and stroke properties.\n '''\n\n writefile.write(\"function \" + functionName + \"(){\\n\")\n\n numPaths = 0\n lineCounter = 0\n pathNames = []\n indent = \" \"\n\n # start writing this path (newPath) to the open file.\n writefile.write(indent + \"var point = new Point(0, \" + rectHeight + \");\\n\")\n\n for line in newPath:\n\n # find a colour for this path.\n if line.endswith(\" g\") or line.endswith(\" rg\"):\n print(\"found colour information: \" + line)\n global currentColour\n currentColour = parse_colour_line(line)\n continue\n\n # deals with the first new path creation.\n pathname = \"path\" + str(numPaths)\n if lineCounter == 0:\n lineToPrint = indent + \"var \" + pathname + \" = new Path();\\n\"\n pathNames.append(pathname)\n writefile.write(lineToPrint)\n\n # catches the moveTo and lineTo strings. \n lineArray = line.split()\n foundChar = lineArray[-1]\n if foundChar in ['m', 'l']:\n coordinates = pointify_coordinates(lineArray[0:2])\n command = set_command_value(foundChar)\n\n # print(str(lineCounter) + \"/\" + str(len(newPath)))\n if lineCounter >= len(newPath)-2:\n break\n else:\n lineToPrint = indent + pathname + command + coordinates + \");\\n\" \n lineCounter += 1\n writefile.write(lineToPrint)\n continue \n\n # catches the cubicCurveTo string.\n if foundChar == 'c':\n command = set_command_value(foundChar)\n coordinates = convert_to_curve_parameters(lineArray)\n lineToPrint = indent + pathname + command + coordinates + \");\\n\" \n lineCounter += 1\n writefile.write(lineToPrint)\n continue\n\n # catches the closePath command.\n if foundChar == 'h': \n lineToPrint = indent + pathname + \".closePath();\\n\"\n numPaths += 1\n lineCounter += 1 \n writefile.write(lineToPrint)\n\n if not lineCounter >= len(newPath)-2:\n writefile.write(\"\\n\")\n pathname = \"path\" + str(numPaths) \n lineToPrint = indent + \"var \" + pathname + \" = new Path();\\n\"\n pathNames.append(pathname)\n writefile.write(lineToPrint)\n \n\n # deal with compoundpath \n if len(pathNames) > 1:\n paths = \", \".join(pathNames)\n \n # use the autosorting function,\n writefile.write(\"\\n\" + indent + \"var unsortedPathList = [\" + paths + \"];\\n\")\n writefile.write(indent + \"unsortedPathList = remove_empty_paths(unsortedPathList);\\n\")\n writefile.write(indent + \"var sortedPathList = unsortedPathList.sort(sortOnBoundsSize);\\n\")\n writefile.write(indent + \"var compoundPath = new CompoundPath(sortedPathList);\\n\")\n writefile.write(indent + \"compoundPath.fillColor = \" + currentColour + \";\\n\")\n writefile.write(indent + \"compoundPath.strokeColor = \" + currentColour + \";\\n\")\n else:\n writefile.write(indent + \"path0.fillColor = \" + currentColour + \";\\n\")\n\n writefile.write(\"}\\n\")\n writefile.write(functionName+\"();\\n\")\n writefile.write(\"\\n\\n\")\n\n\n\ndef write_primitive_postScript(primitive, functionName, writefile):\n print(primitive)\n \n return\n\n\n\ndef create_file(commandList, plotList, fileName):\n '''\n Takes a List of paths found in the .ps and makes js compatible syntax\n\n input: Multidimensional list of strings similar to .ps commands\n output: Similar to input but formatted to be paperpJS readable.\n '''\n \n writefile = open(fileName, 'w')\n\n if fileName.endswith(\".html\"):\n write_html_header(writefile, fileName)\n\n # add the auto sorting functions for the compound path array, and empty path remover.\n write_sorting_functions(writefile)\n write_empty_path_removal_function(writefile)\n\n # add postscript functions written in javascript\n glyphCounter = 0\n for newPath in commandList:\n functionName = \"draw_glyph_\" + str(glyphCounter)\n write_postscript_functions(newPath, functionName, writefile)\n glyphCounter += 1\n\n primitiveCounter = 0\n for primitive in plotList:\n functionName = \"draw_primitive_\" + str(primitiveCounter)\n write_primitive_postScript(primitive, functionName, writefile)\n if primitive.endswith(\"Q\"):\n primitiveCounter += 1\n\n\n if fileName.endswith(\".html\"):\n write_html_footer(writefile, rectWidth, rectHeight)\n\n # done.\n writefile.close()\n\n\n\ndef init():\n '''\n outputFileName can be a .js or a .html , in the case of html appropriate markup is added\n '''\n \n outputFileName = \"outputs/drawing_GBI_extra.html\"\n postScriptFileName = \"ps/typogratifying_extra.ps\"\n fullString = get_postscript(postScriptFileName)\n\n if fullString != None:\n commandList, plotList = parse_postscript(fullString)\n create_file(commandList, plotList, outputFileName)\n print(\"wrote \" + outputFileName + \" using \" + postScriptFileName)\n\n\ninit()\n\n\n","sub_path":"myscripts/other_tests/PostScriptParser20_TakePrimatives_005.py","file_name":"PostScriptParser20_TakePrimatives_005.py","file_ext":"py","file_size_in_byte":11923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"586213928","text":"import sys\nimport os\nsys.path.append(os.getcwd())\n\nfrom extract_features.feature_base import FeatureBase\nimport data\nimport numpy as np\nimport pandas as pd\nfrom preprocess_utils.last_clickout_indices import find as find_last_clickout_indices\nfrom tqdm.auto import tqdm\n\nclass ReferencePricePositionInLastClickout(FeatureBase):\n\n \"\"\"\n Extracts the position of the reference price inside the last clickout impressions prices.\n If the reference is not present in the next clickout impressions, the position will be -1\n | index | price_pos\n price_pos is a number between 0-24 or -1\n \"\"\"\n\n def __init__(self, mode='full', cluster='no_cluster'):\n name = 'reference_price_position_in_last_clickout'\n columns_to_onehot = [('price_pos', 'single')]\n\n super().__init__(name=name, mode='full', columns_to_onehot=columns_to_onehot, save_index=True)\n\n\n def extract_feature(self):\n tqdm.pandas()\n\n df = data.full_df()\n # reset index to correct access\n df = df.sort_values(['user_id','session_id','timestamp','step']).reset_index()\n \n # find the last clickout rows\n last_clickout_idxs = find_last_clickout_indices(df)\n clickout_rows = df.loc[last_clickout_idxs, ['user_id','session_id','action_type','impressions','prices']]\n # cast the impressions and the prices to lists\n clickout_rows['impression_list'] = clickout_rows.impressions.str.split('|').apply(lambda x: list(map(int,x)))\n clickout_rows['price_list'] = clickout_rows.prices.str.split('|').apply(lambda x: list(map(int,x)))\n clickout_rows = clickout_rows.drop('impressions', axis=1)\n # order the prices lists\n clickout_rows['sorted_price_list'] = clickout_rows.price_list.apply(lambda x: sorted(x))\n clickout_rows = clickout_rows.drop('prices', axis=1)\n\n # find the interactions with numeric reference and not last clickouts\n reference_rows = df[['user_id','session_id','reference','action_type','index']]\n reference_rows = reference_rows[df.reference.str.isnumeric() == True].astype({'reference':'int'})\n # skip last clickouts\n reference_rows = reference_rows.loc[~reference_rows.index.isin(last_clickout_idxs)]\n reference_rows = reference_rows.drop('action_type', axis=1)\n ref_pos_series = np.ones(reference_rows.shape[0], dtype=int) * (-1)\n\n # iterate over the sorted reference_rows and clickout_rows\n j = 0\n clickout_indices = clickout_rows.index.values\n ckidx = clickout_indices[j]\n next_clickout_user_id = clickout_rows.at[ckidx, 'user_id']\n next_clickout_sess_id = clickout_rows.at[ckidx, 'session_id']\n k = 0\n for row in tqdm(zip(reference_rows.index, reference_rows.user_id, reference_rows.session_id, \n reference_rows.reference)):\n idx = row[0]\n # if the current index is over the last clickout, break\n if idx >= clickout_indices[-1]:\n break\n # find the next clickout index\n while idx > clickout_indices[j]:\n j += 1\n ckidx = clickout_indices[j]\n next_clickout_user_id = clickout_rows.at[ckidx, 'user_id']\n next_clickout_sess_id = clickout_rows.at[ckidx, 'session_id']\n next_clickout_impress = clickout_rows.at[ckidx, 'impression_list']\n next_clickout_prices = clickout_rows.at[ckidx, 'price_list']\n next_clickout_sortedprices = clickout_rows.at[ckidx, 'sorted_price_list']\n\n # check if row and next_clickout are in the same session\n if row[1] == next_clickout_user_id and row[2] == next_clickout_sess_id:\n try:\n ref_idx = next_clickout_impress.index(row[3])\n ref_price = int(next_clickout_prices[ref_idx])\n ref_pos_series[k] = next_clickout_sortedprices.index(ref_price)\n except:\n pass\n k += 1\n \n reference_rows['price_pos'] = ref_pos_series\n return reference_rows.drop(['user_id','session_id','reference'], axis=1).set_index('index')\n\n def post_loading(self, df):\n # drop the one-hot column -1, representing a non-numeric reference or a reference not present\n # in the clickout impressions\n if 'price_pos_-1' in df.columns:\n df = df.drop('price_pos_-1', axis=1)\n return df\n\n def join_to(self, df, one_hot=True):\n \"\"\" Join this feature to the specified dataframe \"\"\"\n feature_df = self.read_feature(one_hot=one_hot)\n feature_cols = feature_df.columns\n res_df = df.merge(feature_df, how='left', left_index=True, right_index=True)\n if one_hot:\n # fill the non-joined NaN rows with 0\n res_df[feature_cols] = res_df[feature_cols].fillna(0).astype('int8')\n return res_df\n\n\nif __name__ == '__main__':\n import utils.menu as menu\n\n c = ReferencePricePositionInLastClickout()\n\n print('Creating {} for {} {}'.format(c.name, c.mode, c.cluster))\n c.save_feature()\n\n print(c.read_feature(one_hot=True))\n","sub_path":"extract_features/rnn/reference_price_position_in_last_clickout.py","file_name":"reference_price_position_in_last_clickout.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"219567867","text":"import mido\nfrom mido import Message\nfrom mido import MidiFile\n\nimport _thread, time\nfrom pynput import keyboard\nimport time\nimport sys\n\nactive = True\nquitScript = False\n\noutports = mido.get_output_names()\nprint(outports)\noutIndex = [i for i, s in enumerate(outports) if 'MIDISPORT' in s] #Name of virtual MIDI output cable\noutport = mido.open_output(outports[outIndex[0]])\nprint(\"Outport = \" + str(outport.name))\n\n\ninports = mido.get_input_names()\nprint(inports)\ninIndex = [j for j, t in enumerate(inports) if 'MIDISPORT' in t] #Name of MIDI input cable\n\ndef on_press(key):\n global active\n global quitScript\n try:\n if key.char == \"q\":\n quitScript = True\n except:\n pass\n else:\n if active == True:\n print(\"Normal\")\n active = False\n elif active == False:\n print(\"FLIPPED!\")\n active = True\n\nlistener = keyboard.Listener(on_press=on_press)\nlistener.start()\n\nwith mido.open_input(inports[inIndex[0]]) as inport:\n print(\"Inport = \" + str(inport.name))\n\n for msg in inport:\n if quitScript == True:\n quit()\n if active == True:\n try:\n note= msg.note\n #124 means mirroring occurs across middle D\n flippedMsg = msg.copy(note=124-note)\n print(flippedMsg)\n outport.send(flippedMsg)\n except:\n print(msg)\n outport.send(msg)\n else:\n print(msg)\n outport.send(msg)\n","sub_path":"MidiPort2.py","file_name":"MidiPort2.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"154547519","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('ardrone_swarm')\nimport rospy\nimport sys\nimport math\n\nfrom tag import TagIds\n\n#this class is used to maintain informations relative to other drones\nclass DroneInfo(object):\n def __init__(self, id = 0):\n self.id = id\n self.status = -1\n self.task = DroneTask.Waiting\n self.command = DroneCommands.NoCommand\n self.alpha = 0\n self.x = 0\n self.y = 0\n self.z = 0\n \n self.alpha_box = 0.0\n self.box_in_sight = False\n \n self.alpha_belt = 0.0\n self.belt_in_sight = False\n \n ####these are not to send to other drones###\n self.tag_to_follow = None\n self.last_tag_to_follow = None\n self.gesture = Gestures.NoGesture\n self.face_dir = Faces.NoFace\n self.role = 0 #0=follower, 1 = explorer\n self.time_anim = None\n \n self.flyght_tag = TagIds.RoomFrontTag\n \n self.time_keep_pos = None\n \n self.time_go_back = None\n \n self.room_located = False\n \n self.box_master_tag = TagIds.MasterTag\n self.x_box = None\n self.y_box = None\n self.box_located = False\n \n '''self.x_belt = 0.0\n self.y_belt = 0.0'''\n self.belt_located = False\n \n self.alpha_start_expl = None\n self.last_yaw = None\n self.last_z = None\n \n self.move_accomplished = False\n self.time_gesture = rospy.Time.now()\n self.last_seen = 0\n self.angle_to_mantain = 0.0\n self.marker_displacement = None\n self.room_marker_tracked = -1\n self.avoid_walls = False\n self.avoid_drones = False\n self.track_room_marker = False\n self.search_marker = False\n \n self.search_yaw = None\n self.change_demo = False\n \n self.time_go_up = None\n self.time_go_down = None \n \n def set_drone_info(self, status, task, command, alpha, x, y, z, alpha_box, box_in_sight, alpha_belt, belt_in_sight):\n self.status = status\n self.task = task\n self.command = command\n self.alpha = alpha\n self.x = x\n self.y = y\n self.z = z\n self.alpha_box = alpha_box\n self.box_in_sight = box_in_sight\n self.alpha_belt = alpha_belt\n self.belt_in_sight = belt_in_sight \n \n def init(self):\n self.command = DroneCommands.NoCommand\n self.time_keep_pos = None\n self.time_anim = None\n self.belt_located = False\n self.move_accomplished = False\n self.last_seen = 0.0\n self.search_yaw = None\n self.change_demo = False\n self.time_go_up = None\n self.time_go_down = None\n self.last_yaw = None\n self.tag_to_follow = None\n self.last_tag_to_follow = None \n if not self.task == DroneTask.DemoGesture:\n self.task = DroneTask.Waiting\n #self.tag_to_follow = TagIds.FollowTag \n\nclass DroneStatus(object):\n Emergency = 0\n Inited = 1\n Landed = 2\n Flying = 3\n Hovering = 4\n Test = 5\n TakingOff = 6\n GotoHover = 7\n Landing = 8\n Looping = 9 \n \nclass DroneCommands(object):\n NoCommand = -1\n YawLeft = 0\n YawRight = 1\n PitchForward = 2\n PitchBackward = 3\n RollLeft = 4\n RollRight = 5\n IncreaseAlt = 6\n DecreaseAlt = 7\n StartFollow = 8\n StartTag = 9\n GoAtSpeed = 10\n Rotate = 11\n GoAtPoint = 12\n Orbit = 13\n OrbitSync = 14\n FollowBelt = 15\n FollowMe = 16\n FollowFace = 17 \n\n#this class is used to communicate the current task between drones.\nclass DroneTask(object):\n Waiting = 0\n DemoGesture = 7\n \nclass Gestures(object):\n NoGesture = 0\n You = 1\n Follow = 2\n Takeoff = 6\n Land = 3\n Left = 4\n Right = 5\n\nclass Faces(object):\n NoFace = 0\n Center = 1\n Right = 2\n Left = 3 \n","sub_path":"ardrone_swarm/src/scripts/drone_info.py","file_name":"drone_info.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"580045483","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 16 12:22:52 2020\n\n@author: henry\n\"\"\"\nfrom datetime import datetime\nfrom setup.config import gpo_date_frmt\nfrom setup.db_setup import (collections, package, packageSummary, committees, \n members)\nimport logging\n\nclass db_factory:\n\n \n def __init__(self, run_id, session):\n self.logger = logging.getLogger(__name__)\n self.run_id = run_id\n self.session = session \n \n def serialize(self, target_table, api_data):\n '''\n Factory method for turning gov_info API data into objects ready for \n insertion in the database. Passes api_data values to various \n serialization functions, which are all generators. \n\n Parameters\n ----------\n target_table : String\n Value corresponding to the table name that data is to be inserted in \n api_data : JSON object\n Data returned from an API call in JSON format\n \n Returns\n -------\n None.\n '''\n self.logger.debug('Attempting to serialize object %s to %s'%(api_data, \n target_table))\n if target_table == 'collections':\n self.logger.debug('Assigning to collections table.')\n self.collections(api_data)\n \n if target_table == 'package':\n self.logger.debug('Assigning to package table.')\n self.packages(api_data)\n \n if target_table == 'package_summary':\n self.logger.debug('Assigning to package_summary table.')\n self.package_summaries(api_data)\n \n if target_table == 'members':\n self.logger.debug('Assigning to members table.')\n self.members(api_data)\n \n if target_table == 'committees':\n self.logger.debug('Assigning to committees table.')\n self.committees(api_data)\n \n def collections(self, collections_data):\n '''\n Generator yielding one item_dict per item in the API response\n\n Parameters\n ----------\n collections_data : JSON\n API response from the collection endpoint of govInfo\n\n Returns\n -------\n None.\n '''\n self.logger.info(\"Writing to 'collections' table\")\n for item in collections_data['collections']:\n self.logger.debug(\"Serializing item: %s\"%item)\n item_dict = {\n 'run_id' : self.run_id,\n 'collection_code' : item['collectionCode'],\n 'collection_name' : item['collectionName'],\n 'package_count' : item['packageCount'],\n 'granule_count' : item['granuleCount'], \n }\n self.logger.debug(\"Inserting item: %s\"%item_dict)\n insert_object = collections(**item_dict)\n self.session.add(insert_object)\n \n def packages(self, package_data):\n '''\n Serializes the elements of an API response containing package data and \n inserts it into the database, based on the session \n \n Parameters\n ----------\n package_data : JSON Object\n JSON resulting from a govInfo API call to the \n '/collections/{endpointName}' URI, where endpointName is one of the \n endpoints monitored.\n \n Returns\n -------\n None.\n '''\n self.logger.info(\"Writing to 'package' table\")\n for item in package_data['packages']:\n self.logger.debug(\"Serializing item: %s\"%item)\n item_dict = {\n 'run_id' : self.run_id,\n 'package_id' : item['packageId'],\n 'last_modified': datetime.strptime(item['lastModified'], \n gpo_date_frmt),\n 'package_link' : item['packageLink'],\n 'doc_class' : item['docClass'],\n 'title' : item['title'],\n }\n self.logger.debug('Inserting item: %s'%item_dict)\n insert_object = package(**item_dict)\n self.session.add(insert_object)\n \n def package_summaries(self, package_sum_data):\n '''\n Serializes the elements of an API response containing package summary \n data and inserts it into the database, based on the session. \n\n Parameters\n ----------\n package_sum_data : JSON Object\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n '''\n self.logger.info('Writing to package_summary table')\n for item in package_sum_data:\n self.logger.debug('Serializing item: %s' %item)\n item_dict = {\n 'run_id' : self.run_id,\n 'package_id' : item['packageId'],\n 'title' : item['title'],\n 'collection_code' : item['collectionCode'],\n 'collection_name' : item['collectionName'],\n 'category' : item['category'],\n 'date_issued' : datetime.strptime(item['dateIssued'], \n '%Y-%m-%d'),\n 'details_link' : item['detailsLink']\n }\n self.logger.debug('Inserting item: %s'%item_dict)\n insert_object = packageSummary(**item_dict)\n self.session.add(insert_object)\n \n def committees(self, package_sum_data):\n '''\n Serializes the elements of an API response containing commttee data and \n inserts it into the database, based on the session \n\n Parameters\n ----------\n package_sum_data : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n '''\n self.logger.info('Writing to committees table')\n for item in package_sum_data: \n for data in item['committees']:\n self.logger.debug('Serializing item: %s'%item)\n item_dict = {\n 'run_id' : self.run_id,\n 'package_id' : package_sum_data['packageId'],\n 'chamber' : item['chamber'],\n 'committee_type' : item['committeeType'],\n 'committee_name' : item['committeeName']\n }\n self.logger.debug('Inserting item: %s'%item_dict)\n insert_object = committees(**item_dict)\n self.session.add(insert_object)\n \n \n def members(self, package_sum_data):\n '''\n Serializes the elements of an API response containing member data and \n inserts it into the database, based on the session \n\n Parameters\n ----------\n package_sum_data : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n '''\n self.logger.info('Writing to members table')\n for item in package_sum_data: \n for data in item['members']:\n self.logger.debug('Serializing item: %s'%item)\n item_dict = {\n 'run_id' : self.run_id,\n 'package_id' : package_sum_data['packageId'],\n 'member_name' : item['memberName'],\n 'bioguide_id' : item['bioGuideId'],\n 'chamber' : item['chamber'],\n 'party' : item['party'],\n 'role' : item['role'],\n 'state' : item['state'],\n 'congress' : item['congress'],\n 'authority_id' : item['authorityId']\n }\n self.logger.debug('Inserting item: %s'%item_dict)\n insert_object = members(**item_dict)\n self.session.add(insert_object)","sub_path":"db_factory.py","file_name":"db_factory.py","file_ext":"py","file_size_in_byte":7826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"340409325","text":"import torch\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\n\ndef loss_gaussian(out, x):\n n = x.shape[1]\n miu = out[:, 0:n]\n std = out[:, n:]\n t1 = (x - miu) ** 2 / (2 * std**2)\n t2 = torch.log(torch.abs(std)+0.0001)\n log_density = t1 + t2\n\n loss = torch.sum(log_density)\n ttt = loss.cpu().detach().numpy()\n if np.isnan(ttt):\n print('wait')\n print('miu=', miu)\n print('std=', std)\n sys.exit()\n return loss\n\n\ndef check_path(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef plot_loss(file_name, loss_tr, loss_te, loss_od):\n \"\"\"\n plot loss from training\n :param file_name:\n :param loss_tr:\n :param loss_te:\n :param loss_od:\n :return:\n \"\"\"\n\n plt.figure()\n t = np.arange(len(loss_tr))*10\n plt.plot(t, loss_tr, label='train')\n plt.plot(t, loss_te, label='test ')\n plt.plot(t, loss_od, label='ood ')\n plt.yscale('log')\n plt.grid(True)\n plt.legend()\n plt.title('Loss of MADE training')\n\n img_name = file_name + '.pdf'\n plt.savefig(img_name)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"247637716","text":"# apt install python3-pip\n# sudo pip3 install --upgrade pip\n# sudo pip3 install netmiko\n\nfrom netmiko import ConnectHandler\nfrom all_devices import access_switches as devices\n\nwith open('config_file_access_switches') as f:\n config_list = f.read().splitlines()\n\nfor a_device in devices:\n session = ConnectHandler(**a_device)\n output = session.send_config_set(config_list)\n output += session.save_config()\n # print (output)","sub_path":"archive/1.x-code/1.access.py","file_name":"1.access.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49063076","text":"#!/usr/bin/env python\n\n#Mac objc shit\nimport objc, re, os\nfrom Foundation import *\nfrom AppKit import *\nfrom PyObjCTools import NibClassBuilder, AppHelper\n\nfrom appscript import app as appscript_app, its\nfrom wallpaper_download import WallpaperDownloader\n\nclass Timer(NSObject):\n\t\n\tstatusbar = None\n\n\tdef initWithApp_(self, app):\n\n\t\tself = super(Timer, self).init()\n\t\tif self is None: return None\n\n\t\tself.downloader = WallpaperDownloader()\n\t\tself.state = \"STARTED\"\n\t\tself.app = app\n\t\treturn self\n\n\tdef applicationDidFinishLaunching_(self, notification):\n\t\t\n\t\tstatusbar = NSStatusBar.systemStatusBar()\n\t\t# Create the statusbar item\n\t\tself.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength).retain()\n\t\t\n\t\t# Set initial image\n\t\tself.normalImage = NSImage.alloc().initByReferencingFile_('reddit-alien-small.png')\n\t\tself.syncingImage = NSImage.alloc().initByReferencingFile_('reddit-alien-syncing.png')\n\t\tself.statusitem.setImage_(self.normalImage)\n\t\t\n\t\t#self.statusitem.setTitle_('Wall')\n\t\t# Let it highlight upon clicking\n\t\tself.statusitem.setHighlightMode_(1) \n\t\t# Set a tooltip\n\t\tself.statusitem.setToolTip_('Sync Trigger')\n\n\t\t# Build a very simple menu\n\t\tself.menu = NSMenu.alloc().init()\n\t\n\t\t# Sync event is bound to sync_ method\n\t\tmenuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Sync', 'sync:', '')\n\t\tself.menu.addItem_(menuitem)\n\t\n\t\tmenuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Window', 'window:', '')\n\t\tself.menu.addItem_(menuitem)\n\n\t\t# Default event\n\t\tmenuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')\n\t\tself.menu.addItem_(menuitem)\n\t\n\t\t# Bind it to the status item\n\t\tself.statusitem.setAction_(objc.selector(self.showMenu, signature='v@:'))\n\n\t\t# Get the timer going\n\t\tself.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(NSDate.date(), 15.0, self, 'tick:', None, True)\n\t\tNSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)\n\t\tself.timer.fire()\n\n\tdef window_(self, notification):\n\t\tself.window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(NSMakeRect(100, 200, 300, 400), \n\t\t\t\t\t\t\t\tNSBorderlessWindowMask, \n\t\t\t\t\t\t\t\tNSBackingStoreBuffered,\n\t\t\t\t\t\t\t\tFalse)\n\t\tself.window.setBackgroundColor_(NSColor.blueColor())\n\t\tself.window.makeKeyAndOrderFront_(self.window)\n\n\tdef showMenu(self):\n\t\tif self.menu.numberOfItems() == 4:\n\t\t\tself.menu.removeItemAtIndex_(3)\n\t\tif(self.state == \"SYNCING\"):\n\t\t\tprogress = self.downloader.get_download_progress()\n\t\t\tself.menu.addItemWithTitle_action_keyEquivalent_(\"Progress: \" + progress, None, '')\n\t\tself.statusitem.popUpStatusItemMenu_(self.menu)\n\n\tdef sync_(self, notification):\n\t\tif self.state == \"STARTED\" or self.state==\"ROTATE\":\n\t\t\tself.state = \"SYNCING\"\n\t\t\tself.statusitem.setImage_(self.syncingImage)\n\t\t\tself.downloader.download_album()\n\n\tdef tick_(self, notification):\n\t\tif self.state == \"STARTED\":\n\t\t\tpass\n\t\t\t#self.sync_(None)\n\n\t\telif self.state == \"SYNCING\":\n\t\t\t#check if download has completed\n\t\t\tif self.downloader.has_finished_downloading():\n\t\t\t\tself.state = \"DONE_SYNCING\"\n\t\t\t\tself.statusitem.setImage_(self.normalImage)\n\t\t\t\tself.timer.fire()\n\n\t\telif self.state == \"DONE_SYNCING\":\n\t\t\tself.wallpaper_index = 0\n\t\t\tself.wallpapers = self.downloader.get_downloaded_album()\n\t\t\tself.state = \"ROTATE\"\n\t\t\tself.timer.fire()\n\n\t\telif self.state == \"ROTATE\":\n\t\t\t#change to next image\n\t\t\tappscript_app(\"System Events\").desktops[its.display_name == u\"Color LCD\"].picture.set(self.wallpapers[self.wallpaper_index])\n\t\t\tself.wallpaper_index = (self.wallpaper_index + 1) % len(self.wallpapers)\n\n\nif __name__ == \"__main__\":\n\tapp = NSApplication.sharedApplication()\n\tdelegate = Timer.alloc().initWithApp_(app)\n\tapp.setDelegate_(delegate)\n\tAppHelper.runEventLoop()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"643099093","text":"\n# base classifier thresholds\nLOOP_TOLERANCE = .4\nBASELINE_THRESHOLD = .5\n\n# merge settings\nHORIZONTAL_MERGE_THRESHOLD = 20\nVERTICAL_MERGE_THRESHOLD = 20\nWEAK_MERGE = True\nHORIZONTAL_WEAK_MERGE_THRESHOLD = HORIZONTAL_MERGE_THRESHOLD\nVERTICAL_WEAK_MERGE_THRESHOLD = VERTICAL_MERGE_THRESHOLD\n\n# clustering settings\nUSE_LEV_DISTANCE = False\nUSE_GOWER_DISTANCE = not USE_LEV_DISTANCE\nUSE_TEXT = True\nUSE_FONT_DIST = True\nUSE_TOKENS = True\nUSE_LOOPS = True\n\n# weigthing\nTOKEN_WEIGHT = 1\nLOOP_WEIGHT = 1\nFONT_WEIGHT = 3\nLEV_DIST_WEIGHT = 1\nHORIZONTAL_SCALING = 0 # 0.001\nDIAGONAL_SCALING = 0 # 0.001\n\n# pre-classification\nCLASSIFY_TEXT = True\nCLASSIFY_LIST = True\nCLASSIFY_PLOT = False\nFLOAT_EPS = .001\n","sub_path":"PDFSegmenter/util/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"295323605","text":"def calculate_list(src):\n if src == []:\n return 0\n if src[0] is src[-1]:\n return 1\n else:\n return 1 + calculate_list(src[1:])\n\n\ndef find_max(src):\n if not src:\n return\n if len(src) == 1:\n return src[0]\n else:\n _ = find_max(src[1:])\n return src[0] if src[0] > _ else _\n\nif __name__ == \"__main__\":\n l = calculate_list(list(range(10)))\n print(l)\n print(find_max([5,6,9,2,154,6,54,]))","sub_path":"recursive.py","file_name":"recursive.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"285740664","text":"import numpy as np\nimport os\n\n\n\n\ndef _load_filename(prefix, path):\n int_type = np.dtype('int32').newbyteorder('>')\n n_meta_data_bytes = 4 * int_type.itemsize\n\n data = np.fromfile(path + \"/\" + prefix + '-images-idx3-ubyte', dtype='ubyte')\n\n magic_bytes, n_images, width, height = np.frombuffer(data[:n_meta_data_bytes].tobytes(), int_type)\n data = data[n_meta_data_bytes:].astype(dtype='float32').reshape([n_images, width, height])\n\n labels = np.fromfile(path + \"/\" + prefix + '-labels-idx1-ubyte',\n dtype='ubyte')[2 * int_type.itemsize:]\n\n return data, labels\n\n\ndef load_mnist(path=None):\n print(\"Loading mnist....\")\n \"\"\"\n Load mnist\n\n link ~ http://yann.lecun.com/exdb/mnist/\n\n Data Description:\n\n The data is stored in a very simple file format designed for storing vectors and multidimensional matrices. \n General info on this format is given at the end of this page, but you don't need to read that to use the data \n files. All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel \n processors. Users of Intel processors and other low-endian machines must flip the bytes of the header. \n\n There are 4 files:\n\n train-images-idx3-ubyte: training set images\n train-labels-idx1-ubyte: training set labels\n t10k-images-idx3-ubyte: test set images\n t10k-labels-idx1-ubyte: test set labels\n\n \"\"\"\n if path is None:\n root = os.path.dirname(os.path.abspath(__file__)) # Directory of the script\n path = os.path.join(root, 'data/mnist/')\n\n training_images, training_labels = _load_filename(\"train\", path)\n test_images, test_labels = _load_filename(\"t10k\", path)\n\n # Make the images Binary\n training_images = np.where(training_images > 128, 1, 0)\n test_images = np.where(test_images > 128, 1, 0)\n print(\"-----------------------------------------\")\n print(\" mnist is Loaded\")\n print(\"-----------------------------------------\")\n return training_images, training_labels, test_images, test_labels\n\n\nif __name__ == '__main__':\n load_mnist()\n","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"29889311","text":"from django.db import models\nfrom django.contrib import admin\nclass Map (models.Model):\n\tname\t= models.CharField(max_length = 60)\n\tratio\t= models.FloatField()\n\t\n\tdef __unicode__(self):\n\t\treturn self.name\n\n\nclass MapAdmin(admin.ModelAdmin):\n\tlist_display\t= (\"name\", \"ratio\")\t\n\tsearch_fields \t= (\"name\",)\n\tordering\t\t= (\"name\",)\n\nclass Team(models.Model):\n\tname\t\t= models.CharField(max_length = 60)\n\tnationality = models.CharField(max_length = 60, blank = True, null = True)\n\t\n\tdef __unicode__(self):\n\t\treturn self.name\n\nclass TeamAdmin(admin.ModelAdmin):\n\tlist_display \t= (\"name\",)\n\tsearch_fields \t= (\"name\",)\n\tordering\t\t= (\"name\",)\n\n\nclass Match(models.Model):\n\tteam1\t\t= models.ForeignKey(Team, related_name = \"team1\")\n\tteam2\t\t= models.ForeignKey(Team, related_name = \"team2\")\n\tmap\t\t\t= models.ForeignKey(Map)\n\tscore\t\t= models.CommaSeparatedIntegerField(max_length = 50, blank = True)\n\tdate\t\t= models.DateField(blank = True, null = True)\n\t\n\tdef __unicode__(self):\n\t\treturn self.team1.name + \":\" + self.team2.name + \" \" + self.score\n\n\nclass MatchAdmin(admin.ModelAdmin):\n\tlist_display \t= (\"team1\", \"team2\", \"map\", \"score\", \"date\")\n\tsearch_fields \t= (\"team1\", \"team2\", \"map\", \"date\")\n\tlist_filter \t= (\"date\",)\n\tordering\t\t= (\"-date\",)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"231238893","text":"from sys import path\npath.append('..')\nfrom Classifier import Classifier\nimport pickle\n\n\nvocabularyFile = open(\"../Step_6/vocabulary.txt\", mode='r', encoding = 'utf-8')\ntrainingFile = open(\"../Step_2/data.txt\", mode='r', encoding = 'utf-8')\nvocabulary = vocabularyFile.read().splitlines()\ntrainingData = trainingFile.read().splitlines()\n\ntrainingData.sort()\n\npositiveData = trainingData[:320]\nnegativeData = trainingData[320:]\n\nposFactor = len(positiveData)//10\nnegFactor = len(negativeData)//10\n\navgAccuracy = 0\n\nfor i in range(10):\n\ttestSet = positiveData[i*posFactor:i*posFactor+posFactor] + negativeData[i*negFactor:i*negFactor+negFactor]\n\ttrainingSet = positiveData[:i*posFactor]+positiveData[i*posFactor+posFactor:]+negativeData[:i*negFactor]+negativeData[i*negFactor+negFactor:]\n\t\n\ttry:\n\t\tx = pickle.load(open(\"model\"+str(i)+\".pickle\", \"rb\"))\n\texcept (OSError, IOError) as e:\n\t\tx = Classifier(trainingSet, vocabulary)\n\t\tpickle.dump(x, open(\"model\"+str(i)+\".pickle\", \"wb\"))\n\tright = 0\n\twrong = 0\n\tfor reviewItem in testSet:\n\t\t(reviewClass, review) = reviewItem.split('\\t')\n\t\tif reviewClass == x.getClass(review):\n\t\t\tright = right + 1\n\t\telse:\n\t\t\twrong = wrong + 1\n\tprint('Accuracy for TestSet',(i+1), '=',right/(right+wrong))\n\tavgAccuracy = avgAccuracy + right/(right+wrong)\n\nprint('Avg Accuracy =',avgAccuracy/10)\n","sub_path":"Step_7/CrossValid.py","file_name":"CrossValid.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579267920","text":"import os\nimport threading\nimport time\nfrom datetime import timedelta, date, datetime\nfrom itertools import groupby\nfrom json import dumps\nfrom operator import itemgetter\nfrom random import choice, uniform, randint\n\nimport pytest\nfrom settings.exceptions import *\nfrom steps.cdb import select_cdb_document, save_document_couchdb, update_couchdb_document\nfrom steps.object import get_item_from\nfrom steps.rest_deprecated.get import request_item_get\nfrom steps.rest_deprecated.post import request_item_post\nfrom steps.waitings import waiting_tasks_processing, waiting_couchdb_seq\nfrom utils.generate.generate_sales import GenerateSales\nfrom utils.getter import get_time_in_format, gen_couchdb_id\n\n\n@pytest.mark.TestSales\nclass TestSales:\n @pytest.mark.test_sales_1\n @pytest.mark.usefixtures('reset_layer')\n @pytest.mark.parametrize('count_terminal', [10])\n @pytest.allure.story('Активация терминалов')\n def test_step_1_terminal(self, context, rest, couchdb, psql, count_terminal):\n with pytest.allure.step('Организация'):\n # обновляем данные у организации\n org_settings = request_item_get(context, rest, 'core.company.businesses')['ds']\n org_set = get_item_from(org_settings, condition='random')\n\n org_set.update({\n 'name': 'Пыхтачок',\n 'nameShort': 'Конторка',\n 'innCode': 578378353753\n })\n\n org_set = request_item_post(context, rest, 'core.company.businesses', 'item', 'update', org_set)\n\n businesses = get_item_from(\n request_item_get(context, rest, 'core.company.businesses.litebusiness')['ds'],\n table={'title': org_set['title']})\n\n with pytest.allure.step('Столы'):\n # Помимо дефолтного стола с названием \"Стол\" создадим еще 3 стола\n scheme_list = request_item_get(context, rest, 'front.tablemanagement')['ds']\n scheme = get_item_from(scheme_list, condition='random')\n scheme = request_item_get(context, rest, 'front.tablemanagement', bb_action='read', use_object=scheme)\n scheme['halls'][0]['tables'].append({\n \"maxCapacity\": 1,\n 'title': 'Стол 1',\n 'height': 50,\n 'width': 50,\n 'x': 100,\n 'y': 50,\n 'shape': 'rect',\n 'backgroundColor': '219, 219, 219, 1',\n \"angle\": 0,\n \"deleted\": False\n })\n scheme['halls'][0]['tables'].append({\n \"maxCapacity\": 1,\n 'title': 'Стол 2',\n 'height': 25,\n 'width': 25,\n 'x': 212,\n 'y': 202,\n 'shape': 'rect',\n 'backgroundColor': '219, 219, 219, 1',\n \"angle\": 0,\n \"deleted\": False\n })\n scheme['halls'][0]['tables'].append({\n \"maxCapacity\": 1,\n 'title': 'Стол 3',\n 'height': 85,\n 'width': 500,\n 'x': 40,\n 'y': 504,\n 'shape': 'rect',\n 'backgroundColor': '219, 219, 219, 1',\n \"angle\": 0,\n \"deleted\": False\n })\n\n scheme = request_item_post(context, rest, 'front.tablemanagement', 'item',\n 'update',\n scheme, use_preinit=False)\n\n with pytest.allure.step('Склады'):\n # Создаем склад 2\n store = request_item_post(context, rest, 'warehouse.store', 'item', 'create',\n {\n 'title': 'Склад %s' % gen_couchdb_id(),\n 'liteBusiness': businesses,\n 'description': 'склад %s' % gen_couchdb_id()\n })\n\n for index in range(count_terminal):\n with pytest.allure.step('Места приготовления №%s' % (index + 1)):\n # Создаем место приготовления 2\n cooking_place = request_item_post(context, rest, 'warehouse.nomenclature.cooking_place', 'item',\n 'create',\n {\n 'title': 'Кухня %s' % gen_couchdb_id(),\n 'store': store,\n 'sendSignal': True\n })\n\n with pytest.allure.step('ФР №%s' % (index + 1)):\n # Создаем фискальный регистратор 2\n kkm = request_item_post(context, rest, 'front.terminals.kkm', 'item',\n 'action',\n {\n 'actionName': 'createVirtualKkm',\n 'data': {'className': 'createVirtualKkm',\n 'name': 'Виртуальный ФР %s' % gen_couchdb_id()}\n }, use_preinit=False)\n\n with pytest.allure.step('Места реализации №%s' % (index + 1)):\n # Создаем место реализации 2\n sale_place = request_item_post(context, rest, 'warehouse.nomenclature.sale_place', 'item',\n 'create',\n {\n 'title': 'Зал %s' % gen_couchdb_id(),\n 'reportTargetDevice': kkm,\n 'defaultCookingPlace': cooking_place,\n 'tableScheme': scheme\n })\n\n with pytest.allure.step('POS №%s' % (index + 1)):\n # Создаем фискальный регистратор 2\n pos = request_item_post(context, rest, 'front.terminals.pos', 'item',\n 'action',\n {\n 'actionName': 'createVirtualPos',\n 'data': {'className': 'createVirtualPos',\n 'name': 'Виртуальный POS %s' % gen_couchdb_id()}\n }, use_preinit=False)\n\n with pytest.allure.step('Терминалы №%s' % (index + 1)):\n with pytest.allure.step('Создаем документы терминалов'):\n terminal_id = gen_couchdb_id(\"terminal\")\n terminal = save_document_couchdb(\n couchdb,\n {\n \"_id\": terminal_id,\n \"subtype\": \"Register\",\n \"updateSource\": \"terminal-1\",\n \"lastFrontRevision\": False,\n \"rq\": {\n \"ssid\": \"Quick Resto 5Ghz\",\n \"battery\": 100,\n \"localIp\": \"127.0.0.1\",\n \"title\": \"Терминал %s\" % (index + 1)\n },\n \"name\": \"Терминал %s\" % (index + 1),\n \"tokenOwner\": terminal_id,\n \"type\": \"QuickResto\",\n \"state\": \"new\",\n \"deviceModel\": \"Тестовый\",\n \"deviceManufacturer\": \"Виртуальный\",\n \"blocked\": False,\n \"purged\": False,\n \"tokenBlocked\": True,\n }\n )\n\n waiting_couchdb_seq(couchdb, psql)\n\n with pytest.allure.step('Активация терминала №%s' % (index + 1)):\n with pytest.allure.step('Запрашиваем активацию терминала'):\n terminal_back_list = request_item_get(context, rest, 'front.terminals.ipad')['ds']\n terminal_back = get_item_from(terminal_back_list, table={'deviceId': terminal['_id']})\n\n # активация терминала.\n request_item_post(context, rest, 'front.terminals.ipad', 'item', 'action',\n payload_table={\n 'actionName': \"activate\",\n 'data': {\n 'className': 'terminalModal',\n 'name': terminal['name'],\n 'salePlace': sale_place,\n 'terminalType': 'QUICK_POS',\n 'timeZone': -300\n },\n 'ids': [\n terminal_back['id']\n ]\n },\n use_preinit=False)\n\n waiting_tasks_processing(psql)\n\n with pytest.allure.step('Устанавливаем статус \"активирован\" в документе №%s' % index):\n terminal_command_list = select_cdb_document(couchdb, 'terminal_command')\n\n terminal_command = get_item_from(terminal_command_list,\n table={'terminalDocId': terminal['_id']})\n\n update_couchdb_document(couchdb, terminal['_id'],\n {'state': terminal_command['state'],\n 'salePlaceDocId': terminal_command['salePlaceDocId'],\n 'type': terminal_command['type'],\n 'name': terminal_command['name'],\n })\n\n waiting_couchdb_seq(couchdb, psql)\n\n with pytest.allure.step('Активируем ФР и POS №%s' % (index + 1)):\n with pytest.allure.step('Активация'):\n with pytest.allure.step('Запрашиваем активацию pos'):\n businesses = get_item_from(\n request_item_get(context, rest, 'core.company.businesses')['ds'],\n table={'title': org_set['title']})\n # активация pos.\n request_item_post(context, rest, 'front.terminals.pos', 'item', 'action',\n payload_table={\n 'actionName': \"activate\",\n 'data': {\n 'className': 'posModal',\n 'name': pos['name'],\n 'terminal': terminal_back,\n 'business': businesses,\n 'timeZone': -300\n },\n 'ids': [\n pos['id']\n ]\n },\n use_preinit=False)\n\n waiting_tasks_processing(psql)\n\n with pytest.allure.step('Запрашиваем активацию ФР'):\n # активация pos.\n request_item_post(context, rest, 'front.terminals.kkm', 'item', 'action',\n payload_table={\n 'actionName': \"activate\",\n 'data': {\n 'className': 'kkmModal',\n 'name': kkm['name'],\n 'terminal': terminal_back,\n 'business': businesses,\n 'timeZone': -300\n },\n 'ids': [\n kkm['id']\n ]\n },\n use_preinit=False)\n\n waiting_tasks_processing(psql)\n\n with pytest.allure.step('Устанавливаем статус \"активирован\" в документе'):\n for device_id, terminal_id in [(pos['deviceId'], terminal['_id']),\n (kkm['deviceId'], terminal['_id'])]:\n device_command = select_cdb_document(couchdb, 'device_command')\n device_command = get_item_from(device_command,\n table={'deviceId': device_id})\n\n lock_device = select_cdb_document(couchdb, 'lock_device')\n lock_device = get_item_from(lock_device,\n table={'deviceId': device_id})\n\n update_couchdb_document(couchdb, lock_device['_id'],\n {'state': device_command['state'],\n 'updateFrontDocId': 'back',\n 'tokenOwner': terminal_id,\n 'updateSource': terminal_id,\n 'updateRemoteSource': terminal_id,\n })\n\n waiting_couchdb_seq(couchdb, psql)\n\n logger.info('Создан Терминал %s' % (index + 1))\n\n @pytest.mark.test_sales_2\n @pytest.allure.story('Создание номенклатуры')\n def test_step_2_nomenclature(self, context, rest, psql):\n group_dish_list = [\n ('Супы', '#786bf4', '189426 - pot.png'),\n ('Гарниры', '#49a2c8', '189418 - cookie.png'),\n ('Салаты', '#de880d', '189352 - salt.png'),\n ('Напитки', '#2e9c3d', '189410 - cola.png'),\n ('Алкоголь', '#5143d9', '189415 - beer.png'),\n ('Горячие', '#dddddd', '189366 - mushroom.png'),\n ('Выпечка', '#e868f4', '189377 - cherry.png'),\n ('Пицца', '#d36524', '189412 - pizza.png'),\n ('Закуски', '#64af22', '189414 - taco.png'),\n ]\n index = 0\n name = 'Херакс'\n for name, color, image in group_dish_list:\n group_dish_list[index] = request_item_post(\n context,\n rest,\n 'warehouse.nomenclature.dish',\n 'group',\n 'create',\n {\n 'name': name,\n 'color': color,\n 'categoryImage': image\n }\n )\n index += 1\n\n dish_list = [\n ('Айнтопф с курицей', 150, 0),\n ('Венецианский рисовый суп', 190, 0),\n ('Грибной суп', 190, 0),\n ('Густой картофельный суп с чечевицей и грибами', 250, 0),\n ('Капустный айнтопф с мясными клецками', 100, 0),\n ('Карибский суп', 140, 0),\n ('Картофельный чаудер с копченой треской', 110, 0),\n ('Каталонский зеленый суп со свининой и креветками', 120, 0),\n ('Китайский грибной суп с рисовой лапшой', 130, 0),\n ('Крестьянский айнтопф', 90, 0),\n ('Куриный айнтопф с морепродуктами и тыквой', 80, 0),\n ('Баклажанная икра с картофелем', 150, 1),\n ('Баклажаны а ла Пармезана', 30, 1),\n ('Баклажаны под сметанным соусом', 25, 1),\n ('Брокколи под сырно-грибным соусом', 20, 1),\n ('Брокколи с сыром и кунжутом', 40, 1),\n ('Голубцы из молодой капусты с пряным творогом', 50, 1),\n ('Грибное ризотто', 30, 1),\n ('Жаренная капуста с грибами', 34, 1),\n ('Капустные котлеты', 15, 1),\n ('Квашенная капуста с виноградом', 25, 1),\n ('Лечо с рисом', 50, 1),\n ('Лимонное ризотто', 40, 1),\n ('Овощное пюре', 45, 1),\n ('Тающий картофель', 30, 1),\n ('Оливье с курицей', 200, 2),\n ('Оливье с сёмгой', 250, 2),\n ('Цезарь с курицей', 300, 2),\n ('Цезарь с креветками', 280, 2),\n ('Салат с тунцом', 270, 2),\n ('Салат с угрём', 300, 2),\n ('Сырный суп', 200, 2),\n ('Крабовый салат', 150, 2),\n ('Салат мимоза', 180, 2),\n ('Аква минерале', 60, 3),\n ('Кока-кола', 60, 3),\n ('Нарзан минеральная вода', 55, 3),\n ('Несстия в ассортименте', 70, 3),\n ('Перье минеральная вода', 150, 3),\n ('Квас Очаковский', 70, 3),\n ('Сок: яблоко', 50, 3),\n ('Сок: томат', 50, 3),\n ('Сок: вишня', 50, 3),\n ('Морс клюквенный', 60, 3),\n ('Квас домашний', 70, 3),\n ('Вино Антон 2009', 1000, 4),\n ('Вино Кира 2009', 1200, 4),\n ('Вино Рислинг Гарда', 1500, 4),\n ('Вальполичелла', 1200, 4),\n ('Вальполичелла Рипассо', 1500, 4),\n ('Вальполичелла Супериоре Рипассо', 1200, 4),\n ('Амароне делла Вальполичелла', 1200, 4),\n ('Коньяк Мане', 1500, 4),\n ('Коньяк Хеннеси', 2500, 4),\n ('Коньяк Арарат', 1750, 4),\n ('Виски Скотиш Колли', 1500, 4),\n ('Виски Блэк Лэйбл', 2500, 4),\n ('Виски Рэд Лэйбл', 2250, 4),\n ('Текила Ольмека', 1750, 4),\n ('Мартини Бьянко', 1000, 4),\n ('Ром Капитан Морган', 1000, 4),\n ('Курица Миланеза', 450, 5),\n ('Фуагра', 755, 5),\n ('Фламенко', 450, 5),\n ('Печень по–венециански', 350, 5),\n ('Креветки по-испански', 485, 5),\n ('Джамбо', 400, 5),\n ('Прованс', 490, 5),\n ('Мидии в соусе по-французски', 490, 5),\n ('Парма', 485, 5),\n ('Сырный рай', 450, 5),\n ('Штрудель с яблоком', 340, 6),\n ('Штрудель с вишней', 340, 6),\n ('Блинчики «Сюзет»', 210, 6),\n ('Чизкейк «Нью-йорк»', 310, 6),\n ('Тутти - фрутти', 390, 6),\n ('Шоколадное фондю', 420, 6),\n ('«Пьяная» груша', 380, 6),\n ('Сырный пирог с базиликом', 220, 6),\n ('Мясной пирог', 260, 6),\n ('Ачма', 260, 6),\n ('Пеновани хачапури', 130, 6),\n ('Аджарское хачапури', 250, 6),\n ('Чвиштари', 180, 6),\n ('Кубдари', 390, 6),\n ('Лобиани', 250, 6),\n ('Маргарита', 255, 7),\n ('Ветчина, Грибы', 355, 7),\n ('Капричеза', 255, 7),\n ('Пепперони', 355, 7),\n ('Формаджио', 255, 7),\n ('Карбонара', 355, 7),\n ('Люциферо', 385, 7),\n ('Эль Греко', 305, 7),\n ('Кантанелло', 385, 7),\n ('Брулевич', 395, 7),\n ('Грибная', 325, 7),\n ('Прошутто', 345, 7),\n ('Валь Д’аоста', 335, 7),\n ('Картофель Фри', 135, 8),\n ('Луковые Кольца', 50, 8),\n ('Фисташки', 105, 8),\n ('Арахис', 105, 8),\n ('Наггетсы', 135, 8),\n ('Колбаски Охотничьи', 155, 8),\n ('Кальмар Крантини', 200, 8),\n ('Пьяный Мюллер', 300, 8),\n ('Гренки «кантанелло»', 55, 8),\n ]\n try:\n for name, price, group in dish_list:\n request_item_post(\n context,\n rest,\n 'warehouse.nomenclature.dish',\n 'item',\n 'create',\n {\n 'name': name,\n 'basePriceInList': price,\n 'designator': 'dish',\n 'routeWithdrawType': 'FIRST_ONESELF_THEN_BYROUTING'\n },\n parent_object=group_dish_list[group]\n )\n logger.info('Созданно блюдо %s в группе %s' % (name, group_dish_list[group]['name']))\n except RESTConnectionError as e:\n logger.error('На блюде %s генерация номенклатуры свалилась' % name, exc_info=e)\n\n waiting_tasks_processing(psql)\n\n @pytest.mark.test_sales_3\n @pytest.allure.story('Создание и добавление тэгов блюдам')\n def test_step_3_tag(self, context, rest, rest_api):\n tag_list = [\n rest_api.send_create('core.dictionaries.storeitemtag', 'item', payload_table={'name': v})\n for v in (\n 'Гругак',\n 'Изоруг',\n 'Прол',\n 'Аголг',\n 'Гразаг',\n 'Прокар',\n 'Лолг',\n 'Гак',\n 'Ринк',\n 'Изашиш',\n 'Лучанилас',\n 'Нериилас',\n 'Анфирэнь',\n 'Арвэль',\n 'Раилэль',\n 'Эйкайэль',\n 'Андуинг',\n 'Лорданилас',\n 'Линвен',\n 'Энринен',\n 'Лоркайилас',\n )\n ]\n product_list = rest_api.select_titles(\n 'warehouse.nomenclature',\n params={'custom_params': {\n 'className': 'ru.edgex.quickresto.modules.warehouse.nomenclature.StoreProduct'\n }},\n rest_method='get'\n )\n\n for product in product_list:\n product_add = rest_api.read_object('warehouse.nomenclature', params={'object': product})\n rest_api.send_update(\n 'warehouse.nomenclature.dish',\n payload_table={\n **product_add,\n 'storeItemTag': choice(tag_list)\n },\n )\n\n @pytest.mark.test_sales_4\n @pytest.allure.story('Типы оплат и персонал')\n def test_step_4_personal(self, context, rest, psql):\n role_list = request_item_get(context, rest, 'users.role').get('ds')\n personal_list = [\n ('Waiter', 'Арина', 'Дубина', 1000),\n ('Waiter', 'Вероника', 'Мухина', 1001),\n ('Waiter', 'Юрий', 'Дорохов', 1002),\n ('Waiter', 'Евгений', 'Ивазов', 1003),\n ('Waiter', 'Елена', 'Тетерина', 1004),\n ('Cashier', 'Анастасия', 'Борщёва', 2001),\n ('Cashier', 'Кристина', 'Радченко', 2002),\n ('Cashier', 'Гаврила', 'Бабиков', 2003),\n ('Cashier', 'Татьяна', 'Жукова', 2004),\n ('Cashier', 'Андрей', 'Одинцов', 2005),\n ('FO', 'Нина', 'Покалюка', 7771),\n ('FO', 'Анно', 'Трутнева', 7772),\n ]\n\n for system_role, firstname, lastname, pin in personal_list:\n role = get_item_from(role_list, table={'systemRole': system_role})\n request_item_post(context, rest, 'personnel.employee', 'item', 'create', {\n 'firstName': firstname,\n 'lastName': lastname,\n 'role': role,\n 'pin': pin,\n })\n\n pay_list = [\n ('1', 'organization', 'nonfiscal', 'cash', True, False, False),\n ('2', 'organization', 'nonfiscal', 'pos', False, True, False),\n ('3', 'organization', 'nonfiscal', 'bonus', True, False, True),\n ('4', 'organization', 'writeoff', 'cash', False, True, True),\n\n ('5', 'guest', 'fiscal', 'cash', True, False, False),\n ('6', 'guest', 'fiscal', 'pos', False, True, False),\n ('7', 'guest', 'fiscal', 'bonus', True, False, True),\n ('8', 'guest', 'nonfiscal', 'cash', False, True, True),\n ('9', 'guest', 'nonfiscal', 'pos', True, False, False),\n ('10', 'guest', 'nonfiscal', 'bonus', False, True, False),\n ('11', 'guest', 'writeoff', 'cash', True, False, True),\n\n ('12', 'partner', 'fiscal', 'cash', False, True, True),\n ('13', 'partner', 'fiscal', 'pos', True, False, False),\n ('14', 'partner', 'fiscal', 'bonus', False, True, False),\n ('15', 'partner', 'nonfiscal', 'cash', True, False, True),\n ('I', 'partner', 'nonfiscal', 'pos', False, True, True),\n ('II', 'partner', 'nonfiscal', 'bonus', True, False, False),\n ('III', 'partner', 'writeoff', 'cash', False, True, False),\n\n ('IV', 'user', 'fiscal', 'cash', True, False, True),\n ('V', 'user', 'fiscal', 'pos', False, True, True),\n ('VI', 'user', 'fiscal', 'bonus', True, False, False),\n ('VII', 'user', 'nonfiscal', 'cash', False, True, False),\n ('VIII', 'user', 'nonfiscal', 'pos', True, False, True),\n ('IX', 'user', 'nonfiscal', 'bonus', False, True, True),\n ('X', 'user', 'writeoff', 'cash', True, False, False),\n ]\n\n for name, customer, operation, payment, partial, adminConfirm, customerConfirm in pay_list:\n request_item_post(\n context,\n rest,\n 'core.dictionaries.paymenttypes',\n 'item',\n 'create',\n {\n 'name': 'тип оплаты %s' % name,\n 'customerType': customer,\n 'operationType': operation,\n 'paymentMechanismWeb': payment,\n 'partialAllowed': partial,\n 'requireAdminConfirmation': adminConfirm,\n 'requireCustomerConfirmation': customerConfirm,\n }\n )\n\n waiting_tasks_processing(psql)\n\n @pytest.mark.test_sales_5\n @pytest.allure.story('CRM')\n def test_crm(self, rest_api, terminal):\n # Creating fixed discount on sale place:\n sale_place_list = rest_api.select_objects('warehouse.nomenclature.sale_place')['ds']\n terminal.scheme_id = select_cdb_document(terminal.connect, 'tables_scheme-')[0]['_id']\n today = date.today()\n for v in range(1, 11):\n rest_api.send_create(\n 'crm.settings.fixed',\n 'item',\n {\n 'name': 'Фиксированная скидка %s' % v,\n 'salePlaces': [\n sale_place_list\n ],\n 'value': 10 * v\n }\n )\n # Создаем тип бонусных счетов\n type_ = rest_api.send_create('crm.accounting.account.type', 'item', {\n 'name': 'Тип бонусных счетов - %s' % gen_couchdb_id(),\n 'maxUsage': 10 * v,\n 'resetPeriod': 5000\n })\n # Создаем бонусную программу\n rest_api.send_create('crm.settings.bonus', 'item', {\n 'name': 'Бонусная программа 3 - %s' % gen_couchdb_id(),\n 'startDate': 1438027200000,\n 'endDate': 1456044000000,\n 'accValue': 10 * v,\n 'accountType': type_,\n 'doNotAccumulateWhileRedeeming': False,\n 'groups': [],\n })\n\n terminal.customer_put.create()\n terminal.customer_put.time(set_date=today - timedelta(-10 * v), gmt=rest_api.gmt)\n terminal.customer_put.cdb_document = {\n 'firstName': 'Клиент %s' % v,\n 'lastName': '%s %s' % (rest_api.layer, v),\n 'middleName': 'Рукожопович %s' % v,\n \"dateOfBirth\": datetime(1970 + v, v, v * 2).isoformat(),\n \"contactMethods\": [\n {\n \"type\": \"phoneNumber\",\n \"value\": \"791181170%02d\" % v\n },\n ],\n 'tokens': []\n }\n terminal.customer_put.save()\n\n @pytest.mark.test_sales_6\n @pytest.mark.parametrize(\n ('shift_count', 'order_count', 'product_count', 'product_quantity', 'dop_bias', 'guest_count', 'crm'),\n [\n (\n int(os.getenv('SHIFT_COUNT', 5)),\n int(os.getenv('ORDER_COUNT', 2)),\n int(os.getenv('PRODUCT_COUNT', 10)),\n int(os.getenv('PRODUCT_QUANTITY', 5)),\n int(os.getenv('DOP_BIAS', -1)),\n int(os.getenv('GUEST_COUNT', 6)),\n os.getenv('CRM', 0)\n )\n ]\n )\n @pytest.allure.story('Проведение продаж ')\n def test_step_6_sales(self, couchdb, shift_count, order_count, product_count, product_quantity,\n dop_bias, guest_count, crm, rest_api):\n with pytest.allure.step('Подготовка данных для продаж'):\n # Получение списка блюд // цен // мест реализации (идет разбивка по местам реализации)\n column = ['sale_id', 'cook_id', 'price']\n\n def get_dict_with_couchdb(cdb_document):\n return (\n dict(\n zip(column, (v, *sorted(t.values(), key=lambda x: str(x), reverse=1))),\n product_id=cdb_document['_id'],\n name=cdb_document['name'],\n parent=cdb_document.get('parentCategoryDocId'),\n )\n for v, t in cdb_document['saleScheme'].items()\n ) if cdb_document['saleScheme'] else []\n\n def add_token(guest):\n guest = rest_api.select_objects(\n 'crm.customer.tokens',\n params={\n 'owner_object': guest['object']\n }\n )['ds'][-1]['object']\n return {\n 'entry': guest['entry'],\n 'key': guest['key'],\n 'type': guest['type']\n }\n\n setting_for_dumps = dict(indent=4, ensure_ascii=False, sort_keys=True)\n if crm:\n # Формируем список гостей\n crm_list_token = [\n add_token(v)\n for v in rest_api.select_objects('crm.customer')['ds']\n ]\n crm_discount_list = select_cdb_document(couchdb, 'crm_discount-')\n logger.info('Список скидок %s' % dumps(crm_discount_list, **setting_for_dumps))\n logger.info('Список клиентов %s' % dumps(crm_list_token, **setting_for_dumps))\n\n product_list = [\n item\n for v in select_cdb_document(couchdb, 'product-')\n for item in get_dict_with_couchdb(v)\n ]\n logger.info('Список полученных блюд для продаж %s' % dumps(product_list, **setting_for_dumps))\n\n # term_idx - список обязательных колонок 'terminal_id', 'sale_id', 'scheme_id', 'org_id', 'kkm_id'\n org_id = get_item_from(select_cdb_document(couchdb, 'organization-'), condition='random')['_id']\n kkm_list = {k: list(v)\n for k, v in groupby(\n (\n {\n 'kkm_id': v['deviceId'],\n 'deviceType': v['deviceType'],\n 'scheme_id': v['tablesSchemeDocId'],\n 'terminal': v['tokenOwner']\n }\n for v in select_cdb_document(couchdb, 'lock_device-')\n if v['state'] == 'active' and v['deviceType'] == 'kkm'\n ),\n key=itemgetter('terminal')\n )\n }\n logger.info('Список терминалов с активированными ФР %s' % dumps(kkm_list, **setting_for_dumps)\n )\n\n terminal_list = (\n {\n 'clientId': v['clientId'],\n '_id': v['_id'],\n 'salePlaceDocId': v['salePlaceDocId'],\n 'name': v['name'],\n 'kkm_id': kkm_list[v['_id']][0]['kkm_id'],\n 'scheme_id': kkm_list[v['_id']][0]['scheme_id'],\n 'org_id': org_id\n }\n for v in select_cdb_document(couchdb, 'terminal-')\n if v['_id'] in kkm_list.keys()\n )\n\n # Получение списка типов оплат\n payment_list = [v for v in select_cdb_document(couchdb, 'payment_type-') if\n v['paymentMechanism'] != 'bonus']\n\n personal_list = [v['_id'] for v in select_cdb_document(couchdb, 'user')]\n\n # Получение списка отмен (со списанием\\без списания)\n cancellation_reason = select_cdb_document(couchdb, 'cancellation_reason-')\n\n with pytest.allure.step('Проведение продаж'):\n __thread_list = list()\n start = time.time()\n\n def sales_threading(term, indexx):\n try:\n logger.info('Старт генерации продаж')\n gen = GenerateSales(\n couchdb,\n setting={\n 'bias_day': - (index * shift_count + dop_bias),\n 'payment_list': payment_list, # список типов оплат\n 'product_list': product_list,\n 'product_count': product_count,\n 'product_quantity': product_quantity,\n 'guest_count': guest_count - 1,\n 'personal_list': personal_list,\n 'terminal': term,\n 'device_id': term['kkm_id'],\n 'org_id': term['org_id'],\n 'scheme_id': term['scheme_id'],\n 'return_order': True,\n 'return_order_rand': 20,\n 'encashment': True, # Включения работы с инкасациями в генерациях\n 'cashIn_rand': 40, # Шанс внесения\n 'cashOut_rand': 30, # Шанс Изъятия\n 'cancellation': True, # отмены\n 'cancellation_reasons': cancellation_reason, # список причин списания\n 'cancellation_rand': 10, # шанс отмены, на 0 - отмена\n 'CRM': crm,\n 'CRM_guest_rand': 25,\n 'CRM_guest_list': crm_list_token if crm else [],\n 'CRM_discount_rand': 20,\n 'CRM_discount_list': crm_discount_list if crm else [],\n }\n )\n gen.sales(shift_count, order_count)\n\n except Exception as e:\n logger.warning('Не стартанула генерация', exc_info=e)\n __thread_list.remove(indexx)\n\n for index, terminal in enumerate(terminal_list, start=1):\n with pytest.allure.step('Запуск триды с продажами для терминала:{0:s}'.format(terminal.get(\"_id\"))):\n __thread_list.append(index)\n thread = threading.Thread(target=sales_threading, args=(terminal, index))\n thread.start()\n time.sleep(.3)\n\n with pytest.allure.step('Ожидание завешения трид'):\n while len(__thread_list) != 0:\n time.sleep(.1)\n\n logger.info(\"Генерация окончена\")\n logger.info(time.time() - start)\n\n @pytest.mark.test_sales_7\n @pytest.allure.story('Создание, проведение и заполнение приходных накладных')\n def test_step_7_incoming(self, context, rest):\n store_list = request_item_get(context, rest, 'warehouse.store').get('ds')\n\n provider_1 = request_item_post(\n context,\n rest,\n 'warehouse.providers',\n 'Organization',\n 'create',\n {\n 'shortName': 'Шаражкина Конторка %s' % gen_couchdb_id()\n }\n )\n\n incoming_list = list()\n for i in range(20):\n incoming_list.append(\n request_item_post(\n context,\n rest,\n 'warehouse.documents.incoming',\n 'item',\n 'create',\n {\n 'provider': provider_1,\n 'invoiceDate': get_time_in_format(format_time='invoicedate', offset_min=-38000),\n 'store': get_item_from(store_list, condition='random'),\n }\n )\n )\n\n product_list = request_item_get(\n context,\n rest,\n 'warehouse.nomenclature',\n bb_action='titles',\n request_params={\n 'className': 'ru.edgex.quickresto.modules.warehouse.nomenclature.StoreProduct'\n }\n )\n\n for product in product_list:\n product_add = request_item_get(\n context,\n rest,\n 'warehouse.nomenclature',\n bb_action='read',\n request_params={\n 'id': product['id']\n })\n\n markup = uniform(1, 2)\n amount = randint(20, 200)\n request_item_post(\n context,\n rest,\n 'warehouse.documents.items.common',\n 'item',\n 'create',\n payload_table={\n 'product': product_add,\n 'actualAmount': amount,\n 'measureUnit': product_add['measureUnit'],\n 'price': product_add['basePriceInList'] * markup,\n 'fixedTotalSumWithoutVat': product_add['basePriceInList'] * markup * amount,\n 'fixedTotalSum': product_add['basePriceInList'] * markup * amount\n },\n owner_object=choice(incoming_list)\n )\n\n request_item_post(context,\n rest,\n 'warehouse.documents.incoming',\n 'item',\n 'action',\n payload_table={\n 'ids': [incoming.get('id') for incoming in incoming_list],\n 'actionName': 'process'\n },\n use_preinit=False\n )\n\n @pytest.mark.test_sales_8\n @pytest.allure.story('Ожидание окончания генерации')\n def test_step_8_waiting_generate(self, psql):\n logger.info(\"Ожидаем выполнение тасок\")\n\n time_start = time.time()\n count = 1\n\n try:\n while count != 0:\n psql.execute(\"SELECT count(id) FROM task WHERE failtime ISNULL AND task.finishtime ISNULL \"\n \"AND task.canceltime ISNULL;\")\n count = psql.fetchall()[0][0]\n\n psql.execute(\"SELECT count(id) FROM task WHERE failtime NOTNULL\")\n count_fail = psql.fetchall()[0][0]\n\n logger.info(\"Осталось тасок в очереди: %s, количество провалившихся тасок: %r\" %\n (\n str(count),\n str(count_fail)\n )\n )\n\n psql.execute(\n \"SELECT count(id) FROM task WHERE failtime IS NOT NULL \"\n \" AND failreason = 'Order has been already registered';\")\n\n count_fail_order = psql.fetchall()[0][0]\n\n if count_fail_order > 0:\n logger.info('Количество не созданных чеков: %r' % count_fail_order)\n\n time.sleep(count // 80 + 0.5)\n except KeyboardInterrupt:\n pass\n\n time_end = time.time()\n logger.info(\"Время выполнения тасок после окончания генерации: %s\" % (\n time.strftime('%H:%M:%S', time.gmtime(time_end - time_start))))\n\n","sub_path":"scenarios/simple_test/test_generate_nomenclature_and_sales.py","file_name":"test_generate_nomenclature_and_sales.py","file_ext":"py","file_size_in_byte":44459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"239798175","text":"import sys, itertools\ndef input(): return sys.stdin.readline().rstrip()\n\nN, M = map(int, input().split())\n# for _ in itertools.combinations(range(1, N+1), M):\n# print(*_)\n\nvisited = [False] * (N+1)\narr = []\ndef dfs(depth, index):\n if depth == M:\n print(' '.join(arr))\n return\n\n for i in range(index, N+1):\n if not visited[i]:\n visited[i] = True\n arr.append(str(i))\n dfs(depth+1, i+1)\n arr.pop()\n visited[i] = False\n return\ndfs(0, 1)\n","sub_path":"backtracking/15650.py","file_name":"15650.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"623428996","text":"import streamlit as st\n\nimport os\nimport inspect\nfrom collections import defaultdict\nimport json\nimport numpy as np\nimport random\nfrom scipy import stats\nfrom sklearn.neighbors.kde import KernelDensity\nimport cv2 as cv\nfrom glob2 import glob\nfrom itertools import product\nimport yaml\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\nfrom thesis.optim.filters import mean_filter, anisotropic_diffusion, bilateral_filter, gaussian_filter, uniform_noise, \\\n gaussian_noise, cauchy_noise, salt_and_pepper, non_local_means\n\nfrom thesis.segmentation import IrisImage, IrisSegmentation, IrisCodeEncoder, IrisCode, SKImageIrisCodeEncoder\nfrom thesis.tools.st_utils import type_name\n\n\"# Explorer\"\n\nbase = '/home/anton/data/eyedata/iris'\n# base = '/Users/Anton/Desktop/data/iris'\n\nfiles = glob(os.path.join(base, '*.json'))\nnames = [os.path.basename(p).split('.')[0] for p in files]\n\ndataset = st.selectbox('Dataset', names)\n\nst.sidebar.markdown('# Filter setup')\nthe_filter = gaussian_filter\n\nscales = st.sidebar.slider('Scales', 1, 10, 6)\nangles = st.sidebar.slider('Angles', 1, 20, 6)\nangular = st.sidebar.number_input('Angular Resolution', 5, 1000, 30, 1)\nradial = st.sidebar.number_input('Radial Resolution', 2, 500, 18, 1)\n\nangle_tests = st.sidebar.number_input('Test angles', 1, 20, 7)\nspacing = st.sidebar.number_input('Angular spacing', 0, 20, 5)\n\neps = st.sidebar.number_input('Epsilon', 0.0001, 20.0, 0.001, 0.0001)\n\n# encoder = IrisCodeEncoder(scales, angles, angular, radial, wavelength, mult, eps)\nencoder = SKImageIrisCodeEncoder(angles, angular, radial, scales, eps)\n\n\ndef get_code(img, info):\n seg = IrisSegmentation.from_dict(info)\n # m = seg.get_mask((250, 250))\n iris_img = IrisImage(seg, img)\n polar, polar_mask = iris_img.to_polar(angular, radial)\n scale = 3\n polar = cv.resize(polar, (0, 0), fx=scale, fy=scale)\n polar_mask = cv.resize(polar_mask, (0, 0), fx=scale, fy=scale)\n ic = encoder.encode(iris_img)\n code = ic.masked_image()\n saved = np.array(code)\n\n height = radial*scales\n extra = len(code) % height\n c = list(code)\n c.extend([0] * (height-extra))\n st.write(len(c))\n code = np.array(c)\n # while height < len(code) and len(code) % height != 0:\n # height += 1\n code = np.array(code).reshape((height, -1))\n st.write(code.shape)\n st.image([iris_img.image, iris_img.mask * 255, polar, polar_mask * 255, code],\n ['regular', 'mask', 'polar', 'polar_mask', 'code'])\n return ic\n\n\ndef create_code(item, angles=1, angular_spacing=5):\n seg = IrisSegmentation.from_dict(item['points'])\n img = cv.imread(item['image'], cv.IMREAD_GRAYSCALE)\n # img = np.uint8(np.random.uniform(0, 255, img.shape))\n iris_img = IrisImage(seg, img)\n if angles == 1:\n ic = encoder.encode(iris_img)\n return [ic]\n else:\n angular_spacing_radians = angular_spacing / 360 * 2 * np.pi\n codes = []\n # for a in np.arange(-angles//2*angular_spacing, angles//2*angular_spacing, angular_spacing):\n # codes.append(ic.shift(a))\n for a in np.linspace(-angular_spacing_radians / 2 * angles, angular_spacing_radians / 2 * angles, angles):\n codes.append(encoder.encode(iris_img, start_angle=a))\n return codes\n\n\n# @st.cache(suppress_st_warning=True)\ndef create_codes(data):\n bar = st.progress(0)\n res = []\n for i, item in enumerate(data):\n res.append(create_code(item, angle_tests, spacing))\n bar.progress(i / len(data))\n bar.progress(1.0)\n return res\n\n\ndef hamming_distance(c1: np.ndarray, c2: np.ndarray):\n n = ((c1 * c2) == 0).sum()\n c1[c2 == 0] = 0\n c2[c1 == 0] = 0\n div = c1.size - n\n if div == 0:\n return 0\n else:\n return (c1 != c2).sum() / (c1.size - n)\n\n\nwith open(os.path.join(base, f'{dataset}.json')) as f:\n data = json.load(f)\n\nid_map = defaultdict(list)\nfor i, x in enumerate(data['data']):\n id_map[x['info']['user_id']].append((i, x['info']))\n\nnum_images = len(data['data'])\n# index = st.number_input(f'Image index (0-{num_images-1})', min_value=0, max_value=num_images-1, value=0)\n\nif st.checkbox('Compare'):\n user1 = st.selectbox('User ID', sorted(list(id_map.keys())))\n index, val = st.selectbox('Index A', id_map[user1])\n user2 = st.selectbox('User ID 2', sorted(list(id_map.keys())))\n index2, val2 = st.selectbox('Index B', id_map[user2])\n\n info = data['data'][index]\n info2 = data['data'][index2]\n img = cv.imread(info['image'], cv.IMREAD_GRAYSCALE)\n img2 = cv.imread(info2['image'], cv.IMREAD_GRAYSCALE)\n\n # img = np.uint8(np.random.uniform(0, 255, img2.shape))\n # img2 = np.uint8(np.random.uniform(0, 255, img2.shape))\n\n if img is None or img2 is None:\n raise IOError(\"Could not open image\")\n\n c1 = get_code(img, info['points'])\n c2 = get_code(img2, info2['points'])\n\n c2s = create_code(info2, angle_tests, spacing)\n # for c in c2s:\n # height = 30\n # while height < len(c.code) and len(c.code) % height != 0:\n # height += 1\n # code = c.masked_image()\n # code = np.array(code).reshape((height, -1))\n # st.image([code], 'code')\n f'Best: {min(map(c1.dist, c2s))}'\n # c2 = IrisCode(np.random.choice([-1, 1], c1.code.size))\n # n = ((c1 * c2) == 0).sum()\n # c1[c2 == 0] = 0\n # c2[c1 == 0] = 0\n # dist = (c1 != c2).sum() / (c1.size - n)\n # dist = np.linalg.norm(np.array(c1, np.float64)-np.array(c2, np.float64))\n f'Distance: {c1.dist(c2)}'\n\n\"## Base evaluation on random input\"\nif st.checkbox('Base'):\n bar = st.progress(0)\n res = []\n for i in range(100):\n img = np.uint8(np.random.uniform(0, 255, img2.shape))\n img2 = np.uint8(np.random.uniform(0, 255, img2.shape))\n\n seg1 = IrisSegmentation.from_dict(info['points'])\n seg2 = IrisSegmentation.from_dict(info2['points'])\n ir1 = IrisImage(seg1, img)\n ir2 = IrisImage(seg2, img2)\n c1 = encoder.encode(ir1)\n c2 = encoder.encode(ir2)\n\n res.append(c1.dist(c2))\n bar.progress((i+1)/100)\n\n fig, ax = plt.subplots()\n sns.distplot(res, ax=ax)\n st.pyplot(fig)\n\n\n\"## Export\"\nname = st.text_input('File path')\nshould_export = st.checkbox('export')\n\n\"## Code generation\"\nif st.checkbox('Stats'):\n codes = create_codes(data['data'])\n st.write(\"Codes created!\")\n\n bar = st.progress(0)\n n = len(codes)\n distance_matrix = np.zeros((n, n))\n same_mask = np.zeros((n, n), np.bool)\n num_samples = 0\n for i in range(n):\n bar.progress(i / n)\n for j in range(n):\n # distance_matrix[i, j] = min([ca.dist(cb) for ca, cb in product(codes[i], codes[j])])\n # distance_matrix[i, j] = codes[i].dist(codes[j])\n in_data = data['data']\n info_i = in_data[i]['info']\n info_j = in_data[j]['info']\n same = False\n if info_i['user_id'] == info_j['user_id'] and info_i['eye'] == info_j['eye']:\n same = True\n same_mask[i, j] = True\n\n if same or random.random() < 2: # Rate\n num_samples += 1\n distance_matrix[i, j] = min([codes[i][angle_tests // 2].dist(cb) for cb in codes[j]])\n bar.progress(1.0)\n # st.write(same_mask)\n # st.write(distance_matrix)\n\n intra_distances = []\n inter_distances = []\n for i in range(n):\n for j in range(n):\n if i == j:\n continue\n if same_mask[i, j]:\n intra_distances.append(distance_matrix[i, j])\n else:\n inter_distances.append(distance_matrix[i, j])\n\n intra_distances = np.array(intra_distances)\n inter_distances = np.array(inter_distances)\n f'**Intra-distance mean:** {np.mean(intra_distances)}'\n f'**Inter-distance mean:** {np.mean(inter_distances)}'\n\n sns.distplot(intra_distances)\n sns.distplot(inter_distances)\n st.pyplot()\n\n if should_export:\n with open(os.path.join('results', 'recognition', f'{name}.json'), 'w') as filename:\n json.dump({\n 'parameters': {\n 'scales': scales,\n 'angles': angles,\n 'resolution': {\n 'angular': angular,\n 'radial': radial,\n }\n },\n 'results': {\n 'intra_distances': list(intra_distances),\n 'inter_distances': list(inter_distances),\n }\n }, filename)\n\n\"\"\"\n# Filter configuration\n\"\"\"\nftypes = [func for func in (\n mean_filter, anisotropic_diffusion, non_local_means, bilateral_filter, gaussian_filter, uniform_noise, gaussian_noise, cauchy_noise,\n salt_and_pepper) if st.checkbox(func.__name__)]\n\nfilters = {}\nfor func in ftypes:\n f'### Arguments for {func.__name__}'\n args = {v: st.number_input(v) for v in inspect.getfullargspec(func).args[1:]}\n filters[func.__name__] = args\n\n\"\"\"\n# Export configuration\n\"\"\"\nfilename = st.text_input('Output name')\npath = os.path.join('configs/iris_recognition', f'{filename}.yaml')\nif st.button('Export now'):\n with open(path, 'w') as file:\n config = {\n 'parameters': {\n 'scales': scales,\n 'angles': angles,\n 'resolution': {\n 'angular': angular,\n 'radial': radial,\n },\n 'rotation': {\n 'num': angle_tests,\n 'step_size': spacing\n },\n 'epsilon': eps\n },\n 'filters': filters,\n 'dataset': os.path.join(base, f'{dataset}.json')\n }\n yaml.safe_dump(config, file)\n","sub_path":"thesis/tools/IrisRecognitionExperiment.py","file_name":"IrisRecognitionExperiment.py","file_ext":"py","file_size_in_byte":9725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"627364187","text":"from flask import Flask, jsonify, abort, make_response\n#deprecated\n#from flask.ext.httpauth import HTTPBasicAuth\nfrom flask_httpauth import HTTPBasicAuth\n\napp = Flask(__name__)\nauth = HTTPBasicAuth()\n\nusers = {\n \"irul\": \"asd\",\n \"john\": \"hello\",\n \"susan\": \"bye\"\n}\n\ntasks = [\n {\n 'id': 1,\n 'title': u'Buy groceries',\n 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', \n 'done': False\n },\n {\n 'id': 2,\n 'title': u'Learn Python',\n 'description': u'Need to find a good Python tutorial on the web', \n 'done': False\n }\n]\n\n@auth.get_password\ndef get_pw(username):\n# if username == 'irul':\n# return 'asd'\n if username in users:\n return users.get(username)\n return None\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n@app.route('/')\ndef index():\n return \"Hello, World! Semangat 2017!\"\n\n@app.route('/tasks', methods=['GET'])\n@auth.login_required\ndef get_tasks():\n return jsonify({'tasks': tasks})\n\n@app.route('/tasks/', methods=['GET'])\ndef get_task(task_id):\n task = [task for task in tasks if task['id'] == task_id]\n if len(task) == 0:\n abort(404)\n return jsonify({'task': task[0]})\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"webtool.py","file_name":"webtool.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"562872589","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# olx.py\n# \n# Copyright 2016 Pedro Henrique \n# \n \nfrom bs4 import BeautifulSoup\nimport time;\nimport conect_db_postgre;\nimport util;\nimport os.path;\n\ndef main():\n\t\n\tprint (\"Inicio : %s\" % time.ctime());\n\tarquivo = open(\"url.txt\", \"r\");\n\t\n\t'''if (os.path.isfile('arquivo_posicao.txt')) :#caso arquivo exista\n\t\tarquivo_posicao = open(\"arquivo_posicao.txt\",\"r\");\n\t\tconteudo_posicao = arquivo_posicao.readline();\n\t\tif (conteudo_posicao.strip() != \"\") :\n\t\t\tarquivo.seek(int(conteudo_posicao), 1);\t\n\t\telse : \n\t\t\tarquivo.seek(0, 1);\t\n\t\t#fim if/else...\n\t\tarquivo_posicao.close()\n\telse :\n\t\tarquivo.seek(0, 1);\n\t#fim if/else...\n\t'''\n\tconteudo = arquivo.readline();\n\twhile (conteudo != '') :\t\n\t\t\n\t\tdic_imoveis = {\n\t\t\t'Tipo_Imovel': '',\n\t\t\t'Condomínio': '0',\n\t\t\t'IPTU': '0',\n\t\t\t'Área construída': '0',\n\t\t\t'Quartos': '0',\n\t\t\t'Vagas na garagem': '0',\n\t\t\t'Área útil': '0',\n\t\t\t'Município': '',\n\t\t\t'Bairro': '',\n\t\t\t'CEP do imóvel': '',\n\t\t\t'Titulo': '',\n\t\t\t'Valor': '0',\n\t\t\t'Codigo Anuncio': '',\n\t\t\t'Descricao': '',\n\t\t\t'Data': '',\n\t\t\t'Caracteristicas': ''\t\t\n\t\t}\n\t\t\n\t\tconteudo = conteudo.split(\"|\");\n\t\t\n\t\ttipo_imovel = conteudo[0].strip();\n\t\turl = conteudo[1].strip();\n\t\t\n\t\tprint(url);\n\t\t\t\n\t\tdic_imoveis['Tipo_Imovel'] = tipo_imovel;\t\n\t\t\t\n\t\thtml = util.get_pagina(url);\n\t\tsoup = BeautifulSoup(html, \"lxml\")\t\n\t\t\n\t\t\n\t\ttitulo = soup.find('h1', {'class': 'OLXad-title'});\n\t\tif (titulo != None) :\n\t\t\ttitulo = titulo.get_text().strip().encode('utf-8');\n\t\telse :\n\t\t\ttitulo = \"\";\t\n\t\t#fim if...\n\t\t\n\t\tvalor = soup.find('span', {'class': 'OLXad-price'});\n\t\tif (valor != None) :\n\t\t\tvalor = valor.get_text().strip().encode('utf-8').replace('R$', '');\n\t\telse :\n\t\t\tvalor = \"\";\t\n\t\t#fim if...\n\t\t\n\t\tcodigo_anuncio = soup.find('div', {'class': 'OLXad-id'})\n\t\tif (codigo_anuncio != None ) :\n\t\t\tcodigo_anuncio = codigo_anuncio.select('p strong')[0].get_text().strip().encode('utf-8');\n\t\telse :\n\t\t\tcodigo_anuncio = \"\"\n\t\t#fim if...\t\n\t\t\n\t\tdescricao = soup.find('div', {'class': 'OLXad-description'});\n\t\tif (descricao != None ) :\n\t\t\tdescricao = descricao.select('p')[0].get_text().strip();\n\t\t\tdescricao = util.limpa_string(descricao.encode('utf-8'));\n\t\telse :\n\t\t\tdescricao = \"\";\t\n\t\t#fim if...\n\t\t\n\t\tdata = soup.find('div', {'class': 'OLXad-date'});\n\t\tif (data != None) :\n\t\t\tdata = data.select('p')[0].get_text().strip().encode('utf-8').replace('Inserido em: ', '');\n\t\telse :\n\t\t\tdata = \"\";\t\n\t\t#fim if...\n\t\t\n\t\tcaracteristicas = soup.find('div', {'class': 'OLXad-features'});\n\t\tif (caracteristicas != None) :\n\t\t\tcaracteristicas = caracteristicas.select('p')[0].get_text().strip();\n\t\t\tcaracteristicas = util.limpa_string(caracteristicas.encode('utf-8')).replace('Características:', '').replace(', ', ',');\n\t\t\tcaracteristicas = caracteristicas.split(',');\n\t\telse :\n\t\t\tcaracteristicas = [];\t\n\t\t#fim if...\n\t\t\n\t\tlst_class = ['OLXad-details', 'OLXad-location', 'OLXad-location-map'];\n\t\t\n\t\tfor class_search in lst_class :\n\t\t\t\n\t\t\tdiv = soup.find('div', {'class': class_search});\n\t\t\tif (div != None) :\n\t\t\t\tfor el in div.findAll('li') :\n\t\t\t\t\tchave = el.select('p span')[0].get_text().strip().replace(':', '');\n\t\t\t\t\tchave = chave.encode('utf-8');\n\t\t\t\t\tif (chave in dic_imoveis.keys()):\n\t\t\t\t\t\tval_text = el.select('p strong')[0].get_text().strip();\n\t\t\t\t\t\tdic_imoveis[chave] = val_text;\n\t\t\t\t\t#fim if...\t\n\t\t\t\t#fim for i...\n\t\t\t#fim if...\n\t\t\t\n\t\t#fim for class_search\n\t\t\t\n\t\t\n\t\tdic_imoveis['Titulo'] = titulo;\n\t\tdic_imoveis['Valor'] = valor;\n\t\tdic_imoveis['Codigo Anuncio'] = codigo_anuncio;\n\t\tdic_imoveis['Descricao'] = descricao;\n\t\tdic_imoveis['Data'] = data;\n\t\t\n\t\tif (codigo_anuncio != \"\") :\n\t\t\t\n\t\t\tbairro = conect_db_postgre.insert_bairro(dic_imoveis['Bairro'].encode('utf-8'));\n\t\t\tmunicipio = conect_db_postgre.insert_municipio(dic_imoveis['Município'].encode('utf-8'));\n\t\t\t\n\t\t\tlst_dados = [];\n\t\t\tlst_dados.append(dic_imoveis['Codigo Anuncio'].replace('\\'', '\"'));\n\t\t\tlst_dados.append(0); #longitude\n\t\t\tlst_dados.append(0); #longitude\n\t\t\tlst_dados.append(dic_imoveis['Descricao'].replace('\\'', '\"')); \n\t\t\tlst_dados.append(dic_imoveis['Titulo'].replace('\\'', '\"')); \n\t\t\tlst_dados.append((util.get_numero_string(dic_imoveis['Valor']))); \n\t\t\tlst_dados.append(util.toDate(dic_imoveis['Data'])); \n\t\t\tlst_dados.append(dic_imoveis['CEP do imóvel']); \n\t\t\tlst_dados.append(bairro); \n\t\t\tlst_dados.append(municipio); \n\t\t\t\n\t\t\tlst_dados.append(tipo_imovel); \n\t\t\tlst_dados.append(float(util.get_numero_string(dic_imoveis['Área construída']))); \n\t\t\tlst_dados.append(float(util.get_numero_string(dic_imoveis['Área útil']))); \n\t\t\tlst_dados.append(int(util.get_numero_string(dic_imoveis['Vagas na garagem']))); \n\t\t\tlst_dados.append(float(util.get_numero_string(dic_imoveis['Condomínio']))); \n\t\t\tlst_dados.append(int(util.get_numero_string(dic_imoveis['Quartos']))); \n\t\t\tlst_dados.append(float(util.get_numero_string(dic_imoveis['IPTU'])));\n\t\t\tlst_dados.append(0);# oferta\n\t\t\t\n\t\t\timovel = conect_db_postgre.insert_imovel(lst_dados);\n\t\t\t\n\t\t\t#print imovel\n\t\t\t#return \n\t\t\t\n\t\t\t\n\t\t\tlst_caracteristica = [];\n\t\t\tfor c in caracteristicas:\n\t\t\t\tcaracteristica = conect_db_postgre.insert_caracteristica(c);\n\t\t\t\tconect_db_postgre.insert_imovel_caracteristica(int(caracteristica), int(imovel))\n\t\t\t#fim for c...\n\t\t\t\n\t\t\t#arquivo_posicao = open(\"arquivo_posicao.txt\",\"w\");\n\t\t\t#arquivo_posicao.write(str(arquivo.tell())+\"\\n\");\n\t\t\t#arquivo_posicao.close();\n\t\t#fim if...\n\t\t\n\t\tconteudo = arquivo.readline();\n\t\t\n\t\ttime.sleep(0.3);\n\t#fim while...\t\n\t\n\tarquivo.close();\n\t\n\tprint (\"Final: %s\" % time.ctime());\n\t\n\treturn 0\n#fim def main\n\nif __name__ == '__main__':\n\tmain()\n#fim if...\n","sub_path":"codigos/olx_imovel.py","file_name":"olx_imovel.py","file_ext":"py","file_size_in_byte":5561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"497831543","text":"# boj 1743 낚시왕\n# d가 1인 경우는 위, 2인 경우는 아래, 3인 경우는 오른쪽, 4인 경우는 왼쪽을 의미\n\nimport sys\nsys.stdin = open('input.txt')\ninput = sys.stdin.readline\n\nR, C, M = map(int, input().split())\narr = [[0] * C for _ in range(R)]\nsharks = {}\n\nfor idx in range(1, M+1):\n r, c, s, d, z = map(int, input().split())\n arr[r-1][c-1] = idx\n sharks[idx] = (r-1, c-1, s, d, z)\n\n\ndef fishing_king(fc): # 상어 잡기\n for sr in range(R):\n if arr[sr][fc]:\n shark = arr[sr][fc]\n arr[sr][fc] = 0\n size = sharks[shark][4]\n del sharks[shark]\n return size\n return 0\n\n\ndef shark():\n for key, value in sharks.items(): # 이동\n r, c, s, d, z = value\n nr, nc, nd = move_shark(r, c, s, d)\n sharks[key] = (nr, nc, s, nd, z)\n arr[r][c] = 0\n\n for key, value in sharks.items(): # 잡아먹기\n r, c, s, d, z = value\n if arr[r][c]:\n if z < sharks[arr[r][c]][4]:\n continue\n arr[r][c] = key\n\n\ndef move_shark(r, c, s, d):\n if d == 1: # 상\n if s <= r - 0:\n return r - s, c, d\n else:\n rd = s - r\n quo, remain = divmod(rd, R-1)\n if quo % 2 == 0: # 짝수번\n return remain, c, 2\n else:\n return R-1-remain, c, 1\n elif d == 2: # 하\n if s <= R-1-r:\n return r + s, c, d\n else:\n rd = s - (R-1-r)\n quo, remain = divmod(rd, R - 1)\n if quo % 2 == 0: # 짝수번\n return R - 1 - remain, c, 1\n else:\n return remain, c, 2\n elif d == 3: # 좌\n if s <= C-1-c:\n return r, c + s, d\n else:\n cd = s - (C-1-c)\n quo, remain = divmod(cd, C - 1)\n if quo % 2 == 0: # 짝수번\n return r, C - 1 - remain, 4\n else:\n return r, remain, 3\n else:\n if s <= c - 0:\n return r, c-s, d\n else:\n cd = s - c\n quo, remain = divmod(cd, C-1)\n if quo % 2 == 0: # 짝수번\n return r, remain, 3\n else:\n return r, C-1-remain, 4\n\n\ndef solution():\n total = 0\n\n for c in range(C):\n total += fishing_king(c)\n shark()\n\n return total\n\nprint(solution())","sub_path":"BJ/삼성A형기출/17143_낚시왕/s1.py","file_name":"s1.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"109881290","text":"NEUROML2_PATH = \"/Users/rgerkin/NeuroML2\" # Path to NeuroML2 compliant OSB models. \n\n# Standard library. \nimport sys\nimport os\nimport glob\n\nQUIET = False\nfor arg in sys.argv[1:]:\n\ttry:\n\t\tkey,value = arg.split(\":\")\n\texcept ValueError as e:\n\t\tprint(\"Command line argument %s had error %s\" % (arg,e.strerror))\n\telse:\n\t\tif key == \"quiet\":\n\t\t\tif int(value): \n\t\t\t\tQUIET = 1\n\t\t\telse:\n\t\t\t\tQUIET = 0\n\n# Installed packages. \nimport neuroml.loaders as loaders\nimport osb\nimport sciunit\nfrom neuronunit import neuroelectro,tests,capabilities\nfrom neuronunit.neuroconstruct import models\n\ndef qprint(string):\n\tif not QUIET:\n\t\tprint(string)\n\nephys_property = \"Resting Membrane Potential\" \nnml2_model_list = os.listdir(NEUROML2_PATH)\n\n# Get projects with medium curation level. \nosb_projects = osb.get_projects('Medium') \n\nfor model_name in nml2_model_list:\n\tprint(model_name)\n\tpath = os.path.join(NEUROML2_PATH,model_name)\n\tnml_files = glob.glob(path+\"/*.nml\")\n\tif not len(nml_files):\n\t\tqprint(\"No .nml files found for model %s\" % model_name)\n\tfor nml_file in nml_files:\n\t\tnml = loaders.NeuroMLLoader.load(nml_file)\n\t\tfor cell in nml.cells:\n\t\t\tnlex_id = cell.neuro_lex_id\n\t\t\tif nlex_id is None:\n\t\t\t\tproject = osb.get_project_with_identifier(model_name,osb_projects)\n\t\t\t\tif project:\n\t\t\t\t\tnlex_id_list = project.NEUROLEX_IDS_CELLS\n\t\t\t\t\tif len(nlex_id_list):\n\t\t\t\t\t\tif ';' not in nlex_id_list:\n\t\t\t\t\t\t\tnlex_id = nlex_id_list\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tqprint(\"Multiple neurolex ids found; skipping...\")\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tqprint(\"No neurolex id found; skipping...\")\n\t\t\t\t\t\tcontinue\n\t\t\tqprint(\"Model %s had neurolex id %s\" % (model_name,nlex_id))\n\n\t\t\t# Specify reference data for this test. \n\t\t\treference_data = neuroelectro.NeuroElectroSummary(\n\t\t\t\tneuron = {'nlex_id':nlex_id}, \n\t\t\t\t# Neuron type. \n\t\t\t\tephysprop = {'name':ephys_property}\n\t\t\t\t# Electrophysiological property name.\n\t\t\t\t) \n\n\t\t\t\t# Get and verify summary data for the combination above \n\t\t\t\t# from neuroelectro.org. \n\t\t\tif not reference_data.get_values():\n\t\t\t\tstring = \"No NeuroElectro API data found for the neuron with\"\n\t\t\t\tstring += \"neurolex id %s and ephys property %s\" % (nlex_id,ephys_property)\n\t\t\t\tqprint(string)\n\t\t\t\tcontinue\n\n\t\t\t# Initialize the test with summary statistics from the \n\t\t\t# reference data and arguments for the model (model). \n\t\t\ttest = tests.RestingPotentialTest(\n\t\t\t\t\tobservation = {'mean':reference_data.mean,\n\t\t\t\t\t\t\t\t 'std':reference_data.std})\n\n\t\t\t# Initialize (parameterize) the model with some initialization parameters.\n\t\t\tmodel = models.NeuroML2Model(model_name)\n\n\t\t\t# (1) Check capabilities,\n\t\t\t# (2) take the test, \n\t\t\t# (3) generate a score and validate it,\n\t\t\t# (4) bind the score to model/test combination. \n\t\t\tscore = test.judge(model)\n\n\t\t\t# Summarize the result. \n\t\t\tscore.summarize()\n\n\t\t\t# Get model output used for this test (optional).\n\t\t\tvm = score.related_data\n\n","sub_path":"example3.py","file_name":"example3.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"371303244","text":"#!/usr/bin/env python3\n# -*- python -*-\n\nimport sys\nimport logging\nfrom genice.importer import safe_import\nfrom genice import genice, analice, __version__, load\nimport random\nimport numpy as np\n\n\n\n\n\n\ndef main():\n # Module-loading paths\n # 1. Look for the modules in the current working directory\n sys.path.append(\".\")\n\n # Parse options\n if sys.argv[0].find(\"analice\") >= 0:\n options = analice.getoptions()\n mode = \"analice\"\n else:\n options = genice.getoptions()\n mode = \"genice\"\n\n # Set verbosity level\n if options.debug:\n logging.basicConfig(level=logging.DEBUG,\n format=\"%(asctime)s %(levelname)s %(message)s\")\n elif options.quiet:\n logging.basicConfig(level=logging.WARN,\n format=\"%(levelname)s %(message)s\")\n else:\n # normal\n logging.basicConfig(level=logging.INFO,\n format=\"%(levelname)s %(message)s\")\n logger = logging.getLogger()\n logger.debug(\"Debug mode.\")\n\n if mode == \"genice\":\n logger.debug(options.Type)\n\n lattice_type = options.Type\n seed = options.seed\n rep = options.rep\n density = options.dens\n asis = options.asis\n anions = dict()\n if options.anions is not None:\n logger.info(options.anions)\n for v in options.anions:\n key, value = v[0].split(\"=\")\n anions[int(key)] = value\n cations = dict()\n if options.cations is not None:\n for v in options.cations:\n key, value = v[0].split(\"=\")\n cations[int(key)] = value\n spot_guests = dict()\n if options.spot_guests is not None:\n for v in options.spot_guests:\n key, value = v[0].split(\"=\")\n spot_guests[int(key)] = value\n groups = dict()\n if options.groups is not None:\n for v in options.groups:\n key, value = v[0].split(\"=\")\n groups[int(key)] = value\n\n # Set random seeds\n random.seed(seed)\n np.random.seed(seed)\n\n logger.debug(\"Lattice: {0}\".format(lattice_type))\n assert lattice_type is not None\n\n # Initialize the Lattice class with arguments which are required for plugins.\n lat = genice.GenIce(safe_import(\"lattice\", lattice_type),\n sys.argv,\n density=density,\n rep=rep,\n cations=cations,\n anions=anions,\n spot_guests=spot_guests,\n spot_groups=groups,\n asis=asis,\n )\n\n water_type = options.water\n guests = options.guests\n noise = options.noise\n depolarize = not options.nodep\n file_format = options.format\n\n # Main part of the program is contained in th Formatter object. (See formats/)\n logger.debug(\"Output file format: {0}\".format(file_format))\n formatter = safe_import(\"format\", file_format)\n\n if options.visual != \"\":\n record_depolarization_path = open(options.visual, \"w\")\n else:\n record_depolarization_path = None\n\n del options # Dispose for safety.\n\n lat.generate_ice(water_type=water_type,\n guests=guests,\n formatter=formatter,\n record_depolarization_path=record_depolarization_path,\n noise=noise,\n depolarize=depolarize,\n )\n else: # analice\n logger.debug(options.File)\n\n water_type = options.water\n file_format = options.format\n oname = options.oatom\n hname = options.hatom\n filename = options.File\n noise = options.noise\n avgspan = options.avgspan\n filerange = options.filerange\n framerange = options.framerange\n suffix = options.suffix\n if options.output is None:\n output = None\n stdout = None\n else:\n output = options.output\n stdout = sys.stdout\n\n logger.debug(filerange)\n logger.debug(framerange)\n logger.debug(oname)\n logger.debug(hname)\n logger.debug(suffix)\n logger.info(\"Output:{0}\".format(output))\n\n del options # Dispose for safety.\n\n for i, (oatoms, hatoms, cellmat) in enumerate(load.average(lambda:load.iterate(filename, oname, hname, filerange, framerange, suffix=suffix), span=avgspan)):\n # Main part of the program is contained in th Formatter object. (See formats/)\n logger.debug(\"Output file format: {0}\".format(file_format))\n formatter = safe_import(\"format\", file_format)\n lattice_info = load.make_lattice_info(oatoms, hatoms, cellmat)\n lat = analice.AnalIce(lattice_info, sys.argv)\n if output is not None:\n sys.stdout = open(output % i, \"w\")\n lat.analyze_ice(water_type=water_type,\n formatter=formatter,\n noise=noise,\n )\n if stdout is not None:\n # recover stdout\n sys.stdout = stdout\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"genice/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"274514744","text":"# Hangman(행맨) 미니 게임 재작(1)\n# 기본 프로그램 제작 및 테스트\nimport time\n# csv 처리\nimport csv\n# 랜덤\nimport random\n# 사운드 처리\nimport winsound\n\n# 처음 인사\nname = input(\"What is your name?\")\n\nprint(\"Hi, \" + name, \"Time to play hangman game!\")\n\nprint()\n\ntime.sleep(0.5)\n\nprint(\"Start Loading...\")\n\nprint()\ntime.sleep(0.3)\n\n# CSV 단어 리스트\nwords = []\n\n# 문제 CSV파일 로드\nwith open('./resource/word_list.csv', 'r') as f:\n reader = csv.reader(f)\n # Header Skip (정답,힌트)\n next(reader)\n for c in reader:\n words.append(c)\n\n# 리스트 섞기\nrandom.shuffle(words)\n\nq = random.choice(words)\n\n# 정답 단어\nword = q[0].strip() # strip공백제거\n\n# 추측 단어\nguesses = ''\n\n# 기회\nturns = 10\n\n# 핵심 While Loop\n# 찬스 카운터가 남아 있을 경우\nwhile turns > 0:\n # 실패 횟수 (단어 매치 수)\n failed = 0\n \n # print(guesses)\n \n # 정답 단어 반복\n for char in word:\n # 정답 단어 내에 추축 문자가 포함되어 있는 경우\n if char in guesses:\n # 추축 단어 출력\n print(char, end=' ')\n else:\n # 틀린 경우 대시로 처리\n print('_', end=' ')\n failed += 1\n \n # 단어 추측이 성공 한 경우\n if failed == 0:\n print()\n print()\n # 성공 사운드\n winsound.PlaySound('./sound/good.wav', winsound.SND_FILENAME)\n\n print('Congratulation! The Guesses is correct.')\n # while 문 종료\n break\n print()\n\n print()\n \n # 힌트\n print('Hint : {}'.format(q[1].strip()))\n \n # 추측 단어 문자 단위 입력\n guess = input(\"guess a charter.\")\n \n # 단어 더하기\n guesses += guess\n\n # 정답 단어에 추측한 문자가 포함되어 있지 않으면\n if guess not in word:\n # 기회 횟수 감소\n turns -= 1\n # 오류 메세지\n print(\"Oops! Wrong\")\n # 남은 기회 출력\n print(\"You have\", turns, \"more guesses!\")\n\n if turns == 0:\n # 실패 사운드\n winsound.PlaySound('./sound/bad.wav', winsound.SND_FILENAME)\n # 실패 메시지\n print(\"You hangman game failed. Bye!\")","sub_path":"basic/chapter10_hangman2.py","file_name":"chapter10_hangman2.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"472065057","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import State, Input, Output\nimport plotly.graph_objects as go\nimport plotly.express as px\nimport numpy as np\nimport pandas as pd\n\nfrom datetime import datetime as dt\nfrom datetime import timezone\nimport re\n\n\n######## COMPONENTS\n\ncontrols = dbc.Card(\n [\n dbc.FormGroup([\n dcc.DatePickerRange(\n id='my-date-picker-range',\n min_date_allowed=dt(2000, 8, 5),\n max_date_allowed=dt(2019, 2, 1),\n initial_visible_month=dt(2019, 1, 1),\n start_date=dt(2018, 12, 1).date(),\n end_date=dt(2019, 1, 7).date()\n ),\n html.Div(id='output-container-date-picker-range')\n ]),\n dbc.FormGroup(\n [\n dbc.Label(\"Clase\"),\n dcc.Dropdown(\n id=\"clase_value\",\n options=[\n {\"label\": col, \"value\": col} for col in [1,2,3,4]\n ],\n value=1,\n ),\n ]\n ),\n ],\n body=True,\n)\n\n###### VISUALIZATION\ncontent = dbc.Container(\n [\n dbc.Row(\n [\n dbc.Col(controls, md=4),\n dbc.Col(dcc.Graph(id=\"cluster-graph\"), md=8),\n ],\n align=\"center\",\n ),\n ],\n fluid=True,\n)\n\n","sub_path":"my_app/semantic_layout.py","file_name":"semantic_layout.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"100921939","text":"import requests\nimport time\nfrom termcolor import colored\n\nAPI = 'https://api.vk.com/method/'\n\n\ndef do_request(response):\n while True:\n print(colored('status code is [{}]'.format(response.status_code), 'yellow'))\n json_resp = response.json()\n if 'response' in json_resp:\n print(colored('done', 'green'))\n return json_resp\n elif json_resp['error']['error_code'] == 6:\n print(colored(json_resp['error']['error_msg'], 'red'))\n print(colored('Please, waiting for 1 second', 'yellow'))\n time.sleep(1)\n print(colored('Retrying...', 'blue'))\n session = requests.Session()\n response = session.send(response.request)\n continue\n else:\n print(colored(json_resp['error']['error_msg'], 'red'))\n return json_resp\n\n\ndef get_friends(user_id, version):\n params = {\n 'user_id': user_id,\n 'v': version,\n 'extended': 1,\n 'fields': 'bdate'\n }\n response = do_request(requests.get(API + 'friends.get', params))\n return response\n\n\ndef get_groups(user_id, version, token):\n params = {\n 'access_token': token,\n 'user_id': user_id,\n 'v': version,\n 'extended': 1,\n 'fields': 'members_count',\n }\n response = do_request(requests.get(API + 'groups.get', params))\n return response\n\n\ndef get_friends_id_list(user_id, version):\n resp = get_friends(user_id, version)['response']['items']\n try:\n friends_id = [x['id'] for x in resp]\n print('№ of friends', len(friends_id))\n return friends_id\n except Exception as e:\n print(e)\n\n\ndef get_groups_list(user_id, version, token):\n resp = get_groups(user_id, version, token)['response']['items']\n my_list_groups = [x['id'] for x in resp]\n print('№ of groups {}'.format(len(my_list_groups)))\n return my_list_groups\n\n\ndef get_groups_list_full(user_id, version, token):\n resp = get_groups(user_id, version, token)['response']['items']\n my_list_groups_by_id = [[x['id'], x['name'], x['members_count']] for x in resp]\n return my_list_groups_by_id\n\n\ndef get_friends_groups(user_id, version, token):\n friends_id = get_friends_id_list(user_id, token)\n group_friends_final = []\n for i, friend_id in enumerate(friends_id):\n print('...{} %...'.format(round((i + 1) * 100 / len(friends_id), 2)),\n '№{} friend id {}'.format((i + 1), friend_id))\n try:\n group_friends = get_groups(friend_id, version, token)['response']['items']\n print('{} groups for user id {}'.format(len(group_friends), friend_id))\n print('------------------------------------------------------------------------------')\n except Exception as e:\n print('------------------------------------------------------------------------------')\n for v in group_friends:\n if 'deactivated' not in v:\n group_friends_final.append(v['id'])\n friends_group_list = [x for x in group_friends_final]\n return set(sorted(friends_group_list))\n","sub_path":"Diploma_Project/raise_for_status.py","file_name":"raise_for_status.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"124837190","text":"import subprocess\nfrom pdbpaths import *\nimport os\nimport glob\n\ndef runjobs():\n path = Paths()\n file_list = subprocess.check_output(['ls ./bash/', '*.sh'], shell=True).rstrip().split('\\n')\n for file in file_list:\n parent = []\n parent_seq = file.split('_')[:4]\n parent_dirname = '_'.join(parent_seq)\n child_seq = file.split('_')[4:]\n child_dirname = '_'.join(child_seq).partition('.')[0]\n directory = os.path.join(path.get_output_path(), parent_dirname, child_dirname)\n file_name = '*10000*'\n os.chdir(directory)\n if not glob.glob(file_name):\n run_file = path.get_bash_path() + file\n command = 'sbatch ' + run_file\n subprocess.call(command, shell=True)\n \nif __name__ == '__main__':\n runjobs()\n","sub_path":"runjobs.py","file_name":"runjobs.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"279223677","text":"import argparse\nimport hashlib\nimport os\nimport re\nfrom urllib.parse import urlparse, parse_qsl, urlencode, urlunparse\n\nimport boto3\nfrom botocore.exceptions import ClientError\nimport feedparser\nimport yaml\n\n\nCURR_DIR = os.path.dirname(os.path.abspath(__file__))\n\n\ndef get_config():\n \"\"\"\n Gets the YAML config file contents\n :return: the loaded yaml data\n \"\"\"\n with open(f'{CURR_DIR}/config.yaml') as f:\n cfg = yaml.safe_load(f)\n return cfg\n\n\ndef validate_url(url_str):\n \"\"\"\n Validates that the supplies URL string is a valid Craigslist query URL\n :param url_str: The provided URL string\n :raises: AssertionError if URL is invalid\n :return: Nothing\n \"\"\"\n url = urlparse(url_str)\n\n # Must have CL domain\n domain = '.'.join(url.netloc.split('.')[1:])\n assert domain == 'craigslist.org'\n\n # Path must start with /search\n first_path = url.path.split('/')[1]\n assert first_path == 'search'\n\n\ndef get_ids_file_path(url_str):\n \"\"\"\n Gets the path and name of the file where we store the seen for a given URL\n :param url_str: The requested URL\n :return: int hash\n \"\"\"\n h = int(hashlib.sha256(url_str.encode('utf-8')).hexdigest(), 16) % 10**8\n return f'{CURR_DIR}/results/{h}.txt'\n\n\ndef fetch_cl_results(url_str):\n \"\"\"\n Fetches the results from Craigslist using their RSS feed\n :param url_str: The original CL URL\n :return: The parsed RSS entries\n \"\"\"\n # Add format=rss query param\n url_parts = list(urlparse(url_str))\n query_params = dict(parse_qsl(url_parts[4]))\n query_params.update({'format': 'rss'})\n url_parts[4] = urlencode(query_params)\n new_url_str = urlunparse(url_parts)\n\n # Fetch RSS feed\n feed_results = feedparser.parse(new_url_str)\n return feed_results.entries\n\n\ndef get_prev_cl_listings_ids(url_str):\n \"\"\"\n Attempt to read the file created during the previous run, return the list of CL listing ids.\n This represents listings we saw LAST time we ran this.\n :param url_str: The URL string for which we want the previous listings for\n :return: A set of CL listing ids that we saw last time\n \"\"\"\n file_path = get_ids_file_path(url_str)\n ids = set()\n try:\n with open(file_path, 'r') as f:\n for line in f:\n ids.add(line.strip('\\n'))\n return ids\n except FileNotFoundError:\n return None\n\n\ndef find_new_listings(prev_result_ids, most_recent_results):\n \"\"\"\n Given the set of ids that we saw last time, and the most recent fetch results from CL, return which lisings\n we have not seen before\n :param prev_result_ids: set of listing ids\n :param most_recent_results: The full results set (RSS) from this run\n :return: The new listings that we are seeing for the first time\n \"\"\"\n if not prev_result_ids:\n return most_recent_results\n\n return [listing for listing in most_recent_results if listing.id not in prev_result_ids]\n\n\ndef email_listings(listings):\n \"\"\"\n Send an email notifying the user of supplied listings\n :param listings: A list of listings\n :return: Nothing\n \"\"\"\n if not listings:\n return\n num_listings = len(listings)\n\n # Subject\n subject = f'{num_listings} new listing{\"s\" if num_listings > 1 else \"\"} available!'\n\n def _sanitize_title(t):\n # Strip HTML tags in listing titles\n return re.sub('<[^<]+?>', '', t)\n\n # Body HTML\n body_text = \"New Listings:
\"\n for listing in listings:\n link_text = _sanitize_title(listing.title)\n body_text += f'- {link_text}
'\n full_html = \"\" + body_text + \"\"\n\n # Get To/From emails from config\n email_cfg = get_config()['email']\n from_address = email_cfg['from']\n to_addresses = [email_cfg['to']]\n\n # Send the email!\n send_email(from_address=from_address,\n to_addresses=to_addresses,\n subject=subject,\n body_html=full_html)\n\n\ndef send_email(from_address, to_addresses, subject, body_html):\n \"\"\"\n Sends an email using AWS SES\n :param from_address: the From address display string\n :param to_addresses: list of addresses\n :param subject: The email subject\n :param body_html: The email body HTML\n :return: nothing\n \"\"\"\n\n # Create a new SES resource and specify a region.\n ses_client = boto3.client('ses', region_name=get_config()['aws']['region'])\n\n # Try to send the email.\n try:\n # Provide the contents of the email.\n response = ses_client.send_email(\n Destination={\n 'ToAddresses': to_addresses,\n },\n Message={\n 'Body': {\n 'Html': {\n 'Charset': 'UTF-8',\n 'Data': body_html,\n },\n },\n 'Subject': {\n 'Charset': 'UTF-8',\n 'Data': subject,\n },\n },\n Source=from_address,\n )\n # Display an error if something goes wrong.\n except ClientError as e:\n print(e.response['Error']['Message'])\n else:\n print(\"Email sent! Message ID:\"),\n print(response['MessageId'])\n\n\ndef store_new_listings_ids(url_str, results):\n \"\"\"\n Store the ids of all the listings we just received\n :param url_str: the URL which we queried\n :param results: the full results we got back\n :return: Nothing\n \"\"\"\n ids = [l.id for l in results]\n file_path = get_ids_file_path(url_str)\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n with open(file_path, 'w') as f:\n for id in ids:\n f.write(f'{id}\\n')\n\n\ndef main():\n \"\"\"\n Usage:\n python craigchecker --url=\"https://sfbay.craigslist.org/search/sby/apa?max_price=2500\"\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Check craiglist results and email new results')\n parser.add_argument('--url', required=True, help='Craigslist query URL')\n\n args = parser.parse_args()\n url_str = args.url\n\n # Make sure this is a valid URL that we can work with\n validate_url(url_str)\n\n # Fetch the new/current results from Craigslist\n current_listings = fetch_cl_results(url_str)\n\n # Get a list of all the listings we saw last time\n prev_listing_ids = get_prev_cl_listings_ids(url_str)\n\n if not prev_listing_ids:\n # Should only happen once\n print('First time being ran...not sending email, but saving file for next time')\n else:\n # Figure out what the new listings are since last time\n new_listings = find_new_listings(prev_listing_ids, current_listings)\n # Send an email for new listings\n email_listings(new_listings)\n\n # Save all the listings we just saw now, for next time\n store_new_listings_ids(url_str, current_listings)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"craigcheckr.py","file_name":"craigcheckr.py","file_ext":"py","file_size_in_byte":6958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"120809923","text":"from django.urls import path\nfrom . import views\n\napp_name = 'menu'\n\n# el name es el nombre al cual debemos referenciar desde los templates o el codigo html.\nurlpatterns = [\n path('', views.index, name = 'index'),\n path('nuevo/', views.agregarAlumno, name = 'nuevo'),\n path('buscar/', views.buscarAlumno, name = 'buscar-alumno'),\n # path('nuevo/tutor', views.agregarTutor, name = 'nuevo-tutor'),\n path('buscar/tutor', views.buscarTutor, name = 'buscar-tutor'),\n]\n","sub_path":"menu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"205098663","text":"import skimage\nimport skimage.io\nimport skimage.feature\nimport skimage.novice\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# numpy\nimport numpy as np\nimport math\nfrom os import path\n\nimport dateutil\nfrom pypeln import thread as th\nfrom config import Config\n\nfrom tf.transformations import euler_from_quaternion\n# skelearn\nimport sklearn.pipeline\nimport sklearn.dummy\nimport sklearn.preprocessing\nimport sklearn.metrics.regression\nfrom sklearn.metrics import auc, roc_curve\nimport skimage.transform\n# Each csv contains 20s of simulation from gazebo: pioneer on heightmap\ntime_window = 75 # Ideally: each row in the csv is about 0.01 segs, so 50 is about .50 s in the future, 100 1. s\n# However: sometimes due to the simulation load, each row is about 0.02 segs.\n# A preferred way of counting would be in time instead of windows.\n\n#\npatch_size = 80 # for extracting patchs from the heightmap for training, eval and testing datasets\n# Pioneer is about 50cm long x 47cm wide x 40cm height\n# heightmaps are render with a 2cm per pixel resolution; 513x513px --> 10x10m ~1m maxheight\n\npatch_size_training = patch_size # with 30 we resize to this for training the cnn, it will allow us to deal with small maps\n\n#\nadvancement_th = 0.05 # threshold in meters use to generate the training dataset, i.e. when a patch is traversed\n# this has to be set according to the pioneer velocity and its ideal displacement (flat land)\n# .15m/s is the current linear velocity (assuming a forward no steering control)\n# ergo, ideal_displacement = .15m/s x (timewindow in seconds)\n\ndebug = 0 # debug level for extra logging and intermedia plots, 0 no debuggin -- 3 shows everyhing\n #\n\nmultiprocessing = False # if True, we use jobs to generate dataset/calculate the traversability/ plot over a full map\n\nmultiprocessing_hm = np.zeros((100,100)) # a temporal way to initialize a shared image\n\nsim_hm_mx_x = 5.13 # heightmap dimmensions (m) used in the simulation for generating training data\nsim_hm_mx_y = 5.13 # this will help to pass from sim coordinates to screen coordinates when generating datasets\n # usually is a 10m by 10m map, so from -5 to 5\n\n\nheight_scale_factor = 1.0 # for learning heightmaps it was 0 - 1.0; if heighmaps are higher, change accordingly\n\ndef file2df_map(file):\n df = pd.read_csv(file)\n map_name = filename2map(file)\n map = read_image(Config.MAPS_FOLDER + map_name + '.png')\n return df, map\n\ndef files2dfs_maps(files):\n stage = th.map(file2df_map, files)\n data = list(stage)\n return data\n\ndef csvs2dfs(files):\n stage = th.map(pd.read_csv, files)\n data = list(stage)\n return data\n\ndef dfs2df(dfs):\n df = pd.concat([df for df in dfs])\n return df\n\ndef filename2map(filename):\n dirs, _ = path.split(filename)\n map_name = path.basename(dirs)\n\n return map_name\n\ndef df_convert_date2timestamp(df):\n df[df.columns[0]] = df[df.columns[0]].apply(lambda x: dateutil.parser.parse(x).timestamp())\n df[df.columns[0]] -= min(df[df.columns[0]])\n\n return df\n\ndef df_convert_quaterion2euler(df):\n\n def convert(row):\n quaternion = [row['pose__pose_orientation_w'],\n row['pose__pose_orientation_x'],\n row['pose__pose_orientation_y'],\n row['pose__pose_orientation_z']]\n\n\n euler = euler_from_quaternion(quaternion)\n\n return pd.Series([*euler])\n\n df[['pose__pose_e_orientation_x', 'pose__pose_e_orientation_y', 'pose__pose_e_orientation_z']] = df.apply(convert, axis=1)\n\n return df\n\n\ndef read_image(heightmap_png):\n # reads an image takint into account the scalling and the bitdepth\n hm = skimage.io.imread(heightmap_png)\n if hm.ndim > 2: #multiple channels\n hm=skimage.color.rgb2gray(hm) #rgb2gray does the averaging and channel reduction\n elif hm.ndim == 2: #already in one channel\n #this is mostly for the images treated in matlab beforehand (one channel + grayscale + 16bit)\n if hm.dtype == 'uint8':\n divided = 255\n if hm.dtype == 'uint16':\n divided = 65535\n hm=hm/divided\n hm = hm * height_scale_factor #scaled to proper factor (mostly for testing, for training is 1.0)\n return hm\n\ndef toScreenFrame (s_x, s_y, x_max, x_min, y_max, y_min):\n # from simulation frame x right, y up, z out of the screen\n # to x right , y down, ignoring z\n xs = s_x + x_max\n ys = -s_y + y_max\n xs = xs/(x_max-x_min)\n ys = ys/(y_max-y_min)\n return xs, ys\n\ndef hmpatch(hm,x,y,alpha,edge,scale=1):\n # Cutout a patch from the image, centered on (x,y), rotated by alpha\n # degrees (0 means bottom in hm remains bottom in patch, 90 means bottom in hm becomes right in patch),\n # with a specified edge size (in pixels) and scale (relative).\n tf1 = skimage.transform.SimilarityTransform(translation=[-x, -y])\n tf2 = skimage.transform.SimilarityTransform(rotation=np.deg2rad(alpha))\n tf3 = skimage.transform.SimilarityTransform(scale=scale)\n tf4 = skimage.transform.SimilarityTransform(translation=[+edge/2, +edge/2])\n tf=(tf1+(tf2+(tf3+tf4))).inverse\n #corners=tf(np.array([[0,0],[1,0],[1,1],[0,1]])*edge)\n corners=tf(np.array([[0,0],[1,0],[1,1],[0,1],[0.5,0.5]])*edge)\n patch = skimage.transform.warp(hm, tf,output_shape=(edge,edge),mode=\"edge\")\n return patch,corners\n\ndef hmpatch_only_corners(x,y,alpha,edge,scale=1):\n # Cutout a patch from the image, centered on (x,y), rotated by alpha\n # degrees (0 means bottom in hm remains bottom in patch, 90 means bottom in hm becomes right in patch),\n # with a specified edge size (in pixels) and scale (relative).\n tf1 = skimage.transform.SimilarityTransform(translation=[-x, -y])\n tf2 = skimage.transform.SimilarityTransform(rotation=np.deg2rad(alpha))\n tf3 = skimage.transform.SimilarityTransform(scale=scale)\n tf4 = skimage.transform.SimilarityTransform(translation=[+edge/2, +edge/2])\n tf=(tf1+(tf2+(tf3+tf4))).inverse\n corners=tf(np.array([[0,0],[1,0],[1,1],[0,1],[0.5,0.5]])*edge)\n #patch = skimage.transform.warp(hm, tf,output_shape=(edge,edge),mode=\"edge\")\n return corners\n\ndef show(sample,hm):\n O_W_KEY = 'pose__pose_e_orientation_z'\n\n patch=hmpatch(hm,sample[\"hm_x\"],sample[\"hm_y\"],np.rad2deg(sample[O_W_KEY]),patch_size,scale=1)[0] # make sure to extract the patch from the correct heightmap\n patch=patch-patch[patch.shape[0]//2,patch.shape[1]//2]\n fig,ax1=plt.subplots(figsize=(7,7))\n ax1.imshow(patch/height_scale_factor,cmap=\"coolwarm\",vmin=-0.1,vmax=+0.1)\n ax1.set_title(\"advancement: {:.4f}\".format(sample[\"advancement\"]))\n plt.show()\n plt.close(fig)\n\n\ndef generate_single_dataset_cnn(df, heightmap_png):\n hm = read_image(heightmap_png)\n\n df = df.set_index(df.columns[0])\n df.columns = df.columns.map(str.strip) # strip spaces\n\n P_X_KEY = 'pose__pose_position_x'\n P_Y_KEY = 'pose__pose_position_y'\n\n O_W_KEY = 'pose__pose_e_orientation_z'\n\n if debug > 1:\n plt.figure()\n df.plot.scatter(x=P_X_KEY, y=P_Y_KEY)\n plt.show()\n\n # % Convert xy to hm coords\n df[\"hm_x\"] = df.apply(\n lambda r: toScreenFrame(r[P_X_KEY], r[P_Y_KEY], sim_hm_mx_x, -sim_hm_mx_x, sim_hm_mx_y, -sim_hm_mx_y)[0] *\n hm.shape[1], axis=1)\n df[\"hm_y\"] = df.apply(\n lambda r: toScreenFrame(r[P_X_KEY], r[P_Y_KEY], sim_hm_mx_x, -sim_hm_mx_x, sim_hm_mx_y, -sim_hm_mx_y)[1] *\n hm.shape[0], axis=1)\n\n # % Plot trajectory\n if debug > 0:\n fig, ax = plt.subplots(figsize=(15, 15))\n ax.imshow(hm / height_scale_factor)\n ax.plot(df[\"hm_x\"], df[\"hm_y\"], '-y')\n ax.plot(df[\"hm_x\"].iloc[0], df[\"hm_y\"].iloc[0], 'oy')\n plt.show()\n\n # % Plot angles\n # import numpy as np\n if debug > 1:\n plt.figure()\n np.rad2deg(df[O_W_KEY]).plot()\n plt.show()\n\n # %\n # Unit vector of robot orientation\n df[\"S_oX\"] = np.cos(df[O_W_KEY])\n df[\"S_oY\"] = np.sin(df[O_W_KEY])\n assert (np.allclose(1, np.linalg.norm(df[[\"S_oX\", \"S_oY\"]], axis=1)))\n\n # dX, dY, distance at 10 timesteps in the future\n dt = time_window\n df[\"S_dX\"] = df.rolling(window=(dt + 1))[P_X_KEY].apply(lambda x: x[-1] - x[0], raw=True).shift(-dt)\n df[\"S_dY\"] = df.rolling(window=(dt + 1))[P_Y_KEY].apply(lambda x: x[-1] - x[0], raw=True).shift(-dt)\n df[\"S_d\"] = np.linalg.norm(df[[\"S_dX\", \"S_dY\"]], axis=1)\n if debug > 1:\n plt.figure()\n df[\"S_d\"].plot()\n\n # % Project dX, dY on current direction\n df[\"advancement\"] = np.einsum('ij,ij->i', df[[\"S_dX\", \"S_dY\"]], df[[\"S_oX\", \"S_oY\"]]) # row-wise dot product\n\n # set the label using a threshold value\n df[\"label\"] = df[\"advancement\"] > advancement_th\n\n # % Filter data\n # skip the first two seconds and any row with nans (i.e. end of the dataset)\n dff = df.loc[df.index >= 2].dropna()\n dff = dff.loc[dff.index <= 18].dropna() # drop also the last two seconds (if run is 20s, < 18)\n\n # drop the frames where the robot is upside down (orientation alpha angle [euler's angles]) to avoid false positives\n dff = dff.loc[dff['pose__pose_e_orientation_x'] >= -2.0].dropna()\n dff = dff.loc[dff['pose__pose_e_orientation_x'] <= 2.0].dropna()\n\n dff = dff.loc[dff['pose__pose_e_orientation_y'] >= -2.0].dropna()\n dff = dff.loc[dff['pose__pose_e_orientation_y'] <= 2.0].dropna()\n\n # % Visualize the data\n if debug > 2:\n print(\"Slow\")\n for i, sample in dff.sort_values(\"advancement\").head(20).iterrows():\n show(sample, hm)\n\n print(\"Fast\")\n for i, sample in dff.sort_values(\"advancement\").tail(20).iterrows():\n show(sample, hm)\n\n return dff, hm\n","sub_path":"core/utils/postprocessing/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"190775762","text":"import csv\nimport statistics as stats\n\ndef parser1():\n \n\n qrfreq = {}\n print(\"READING\")\n # reading csv file \n with open('warehouse.csv', 'r') as csvfile: \n \n for ls in csvfile.readlines():\n print(ls) \n ls = ls.strip('\\n')\n l = ls.split(',')\n \n if l[0] not in qrfreq:\n qrfreq[l[0]] = {}\n if l[1] not in qrfreq[l[0]]:\n qrfreq[l[0]][l[1]]=0\n qrfreq[l[0]][l[1]]+=1\n\n falloct = {}\n\n fallocq = {}\n print(qrfreq)\n for qr in qrfreq:\n ts = qrfreq[qr] \n #peace\n d2 = []\n for a in ts:\n b=ts[a]\n d2.append((b,a))\n d2.sort()\n if d2[-1][1] not in falloct:\n falloct[d2[-1][1]] = set()\n falloct[d2[-1][1]].add(qr)\n fallocq[qr] = d2[-1][1]\n plen = 0\n\n while plen != len(fallocq):\n plen = len(fallocq)\n with open('out2.csv', 'r') as csvfile: \n for ls in csvfile.readlines():\n ls = ls.strip('\\n')\n\n l = ls.split(',')\n if l[0] in fallocq:\n fallocq[l[1]] = fallocq[l[0]]\n falloct[fallocq[l[0]]].add(l[1])\n elif l[1] in fallocq:\n fallocq[l[0]] = fallocq[l[1]]\n falloct[fallocq[l[1]]].add(l[0])\n else:\n print(\"Never seen before QR\")\n \n with open('outputf.csv', 'a') as tz:\n for a in falloct:\n b=falloct[a]\n for c in b:\n tz.write(str(a) + \",\" + str(c)+\"\\n\")\n","sub_path":"imav-warehouse-management/csvParserfinal.py","file_name":"csvParserfinal.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"132571123","text":"# This is a sample Python script.\n\n# Press Mayús+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\ndef interate():\n x = range(0, 6, 1)\n fruits = [\"apple\",\"banana\",\"cherry\"]\n for x in fruits:\n print(x)\n\n\ndef printstr():\n s = ''\n x = \"asdf\"\n y = \"algo \" \\\n \"otro\"\n\n\ndef print_hi(name):\n # Use a breakpoint in the code line below to debug your script.\n print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.\n print(f'lo que yo quiera,{name}')\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n #print_hi('Nallely')\n interate()\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"166129823","text":"# Fitting_beam_positions.py\n#\n# Code to analyse input/output array alignment\n#\n# ROADMap Systems Ltd\n#\n# Brian Robertson\n#\n# 20/November/2017\n#\n# Version 1 - Basic code. (20/11/2017)\n\n\nfrom numpy import*\nfrom pylab import *\nfrom math import*\nfrom scipy.optimize import minimize\n\n##############################################################################\n# Import some extra special libraries from my own repo\n##############################################################################\nsys.path.insert(0, r'C:\\Users\\Philip\\Documents\\Python\\Local Repo\\library')\nimport useful_defs_prd as prd\nfrom peakdetect import peakdetect\ncs = prd.palette()\n\n##############################################################################\n# Do some stuff\n##############################################################################\n\n# Define functions\n\n# Calculate theoretical beam positions\ndef calculate(scale, angle, ex, ey, x, y):\n\n error = 0\n\n for ii in range(3):\n ii2 = ii - 1\n for jj in range(3):\n jj2 = jj - 1\n\n posx = x[ii, jj]\n posy = y[ii, jj]\n\n posx_ideal = ii2 * scale * \\\n np.cos(angle) + jj2 * scale * np.sin(angle)\n posy_ideal = ii2 * scale * \\\n np.sin(angle) - jj2 * scale * np.cos(angle)\n\n x_theory[ii, jj] = posx_ideal + ex\n y_theory[ii, jj] = posy_ideal + ey\n\n error_new = (posx - posx_ideal - ex)**2 + \\\n (posy - posy_ideal - ey)**2\n error = error + error_new\n\n return x_theory, y_theory, error\n\n# Minimization function\ndef fun(x00, x, y):\n\n scale = x00[0]\n angle = x00[1]\n ex = x00[2]\n ey = x00[3]\n\n error = 0\n\n for ii in range(3):\n ii2 = ii - 1\n for jj in range(3):\n jj2 = jj - 1\n\n posx = x[ii, jj]\n posy = y[ii, jj]\n\n posx_ideal = ii2 * scale * \\\n np.cos(angle) + jj2 * scale * np.sin(angle)\n posy_ideal = ii2 * scale * \\\n np.sin(angle) - jj2 * scale * np.cos(angle)\n\n x_theory[ii, jj] = posx_ideal + ex\n y_theory[ii, jj] = posy_ideal + ey\n\n error_new = (posx - posx_ideal - ex)**2 + \\\n (posy - posy_ideal - ey)**2\n error = error + error_new\n\n return error\n\n# Main code\n\n# Experimental data\n\nx0 = np.array([1.407, 1.436, 1.459, 1.739, 1.784, 1.798, 2.076, 2.111, 2.103])\nx0m = np.reshape(x0, (3, 3)) - x0[4]\ny0 = np.array([3.211, 2.820, 2.503, 3.223, 2.860, 2.513, 3.213, 2.858, 2.530])\ny0m = np.reshape(y0, (3, 3)) - y0[4]\n\nx1 = np.array([1.183, 1.220, 1.224, 1.509, 1.561, 1.575, 1.837, 1.866, 1.873])\nx1m = np.reshape(x1, (3, 3)) - x1[4]\ny1 = np.array([3.523, 3.137, 2.824, 3.531, 3.181, 2.839, 3.515, 3.168, 2.852])\ny1m = np.reshape(y1, (3, 3)) - y1[4]\n\nx2 = np.array([0.793, 0.831, 0.857, 1.334, 1.394, 1.410, 1.883, 1.934, 1.926])\nx2m = np.reshape(x2, (3, 3)) - x2[4]\ny2 = np.array([3.999, 3.373, 2.836, 4.017, 3.427, 2.854, 3.989, 3.414, 2.872])\ny2m = np.reshape(y2, (3, 3)) - y2[4]\n\nx3 = np.array([4.081, 4.129, 4.131, 4.657, 4.717, 4.667, 5.218, 5.234, 5.274])\nx3m = np.reshape(x3, (3, 3)) - x3[4]\ny3 = np.array([4.023, 3.446, 2.868, 4.040, 3.450, 2.799, 4.054, 3.477, 2.920])\ny3m = np.reshape(y3, (3, 3)) - y3[4]\n\n\nx = x3m\ny = y3m\n\n# Define theoretical position matrix\nx_theory = np.zeros([3, 3])\ny_theory = np.zeros([3, 3])\n\n# Initial parameters (best guess)\nscale = 0.35\nangle = 2 * pi / 180\nex = 0\ney = 0\n\n# Set up parameters for minimization function\nx00 = [scale, angle, ex, ey]\n# Optimization using function 'fun'\nres = minimize(fun, x00, (x, y), method='Powell')\n# Optimized parameters\nprint(res.x)\n\nscale = res.x[0]\nangle = res.x[1]\nex = res.x[2]\ney = res.x[3]\n\nprint('Scale =', np.round(scale, 3))\nprint('Angle =', np.round(angle * 180 / pi, 2))\nprint('ex =', np.round(ex, 3))\nprint('ey =', np.round(ey, 3))\n\n# Calculate theoretical positions\nx_theory, y_theory, error = calculate(scale, angle, ex, ey, x, y)\nprint('error = ', np.round(error, 3))\n\n# Plot data\n\nfig1 = plt.figure('fig1')\nax1 = fig1.add_subplot(1, 1, 1)\nfig1.patch.set_facecolor(cs['mdk_dgrey'])\nax1.set_xlabel('x axis')\nax1.set_ylabel('y axis')\nplt.plot(x, y, 'o')\nplt.plot(x_theory, y_theory, '+')\n\nshow()\n\nprd.PPT_save_2d(fig1, ax1, '2D array fit 1')\n","sub_path":"Image processing/Fitting beam positions 2D array.py","file_name":"Fitting beam positions 2D array.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"100612261","text":"import cv2\nimport numpy as np\nimport class_info\n\nPOSE_TOLERANCE = 10\n\n# Camera 0 is the integrated web cam on my netbook\ncamera_port = 0\n \n# Now we can initialize the camera capture object with the cv2.VideoCapture class.\n# All it needs is the index to a camera port.\n\n\n# Captures a single image from the camera and returns it in PIL format\ndef get_image():\n\t# read is the easiest way to get a full image out of a VideoCapture object.\n\tcamera = cv2.VideoCapture(camera_port)\n\tretval, im = camera.read()\n\tim = cv2.resize(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY),(320,240))\n\tdel(camera)\t\n\treturn im\n\ndef find_location(img, database, pose):\n\t# Search the data base for images that are close to the current estimated location\n\tdatabase_temp = []\n\tfor data in database:\n\t\tif (pose.x - data.pose.x < POSE_TOLERANCE and pose.x - data.pose.x > -POSE_TOLERANCE) \\\n\t\tand (pose.y - data.pose.y < POSE_TOLERANCE and pose.y - data.pose.y > -POSE_TOLERANCE):\n\t\t\tdatabase_temp.append(data)\n\t# Search the close images for one that matches our location\n\terror_database = []\n\tfor data in database_temp:\n\t\timg_diff = abs(img.astype(int) - data.img.astype(int))\n\t\timg_diff = np.array(img_diff,dtype = np.uint8)\n\t\t\n\t\terror = np.mean(img_diff)\n\t\terror_database.append((error, data.pose))\n\n\t\tim_stack = np.hstack((data.img,img))\n\t\tim_stack = np.hstack((im_stack, img_diff))\n\t\tcv2.imshow(\"Database img, current image, difference\", im_stack)\n\t\t#print(\"Error is \" + str(error))\t\n\t\tcv2.waitKey(100)\n\t# Use the pose with the lowest error\n\t\n\t# cv2.destroyAllWindows()\n\terror_database.sort(key=lambda tup: tup[0])\n\treturn (error_database[0][1], error_database[0][0])\n\ndef build_database():\n\tdatabase = []\n\twhile 1:\n\t\tkey = raw_input(\"Enter pose x value (press e to finish)\")\n\t\tif key == 'E' or key == 'e':\n\t\t\treturn database\n\t\tpose = class_info.Pose(int(key),0,0)\n\t\tcapture = get_image()\n\t\tdatabase.append(class_info.ImageData(capture,pose))\n\t\tcv2.imwrite('img.png',capture)\n\n# Build database\ndatabase = build_database()\n\n# Setup current location\npose_current = class_info.Pose(1.5,0,0)\n\nwhile 1:\n\t# When ready capture an image\n\t# key = raw_input(\"Enter any key to check (e or E to exit)\")\n\t# if key == 'E' or key == 'e':\n\t# \tbreak\n\tcapture = get_image()\n\n\t# Image search for closest image\n\tnew_pose, error = find_location(capture, database, pose_current)\n\n\t# Print answer\n\tprint(\"Pos : \" + str(new_pose.x) + \" Error : \" + str(error))\n\n# Close camera\n\t\n\n\n\n#######################################################################################\n############ CODE CEMETARY ##############\n\n#load images\n# im_1 =cv2.resize(cv2.imread('test1.jpg', 0), (320,320))\n# im_2 =cv2.resize(cv2.imread('test2.jpg', 0), (320,320))\n# im_3 =cv2.resize(cv2.imread('test3.jpg', 0), (320,320))\n\n# database is a list of image objects \n# database = []\n# database.append(class_info.ImageData(im_1, class_info.Pose(1,0,0)))\n# database.append(class_info.ImageData(im_2, class_info.Pose(2,0,0)))\n","sub_path":"place_recog_v2_0.py","file_name":"place_recog_v2_0.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"222397051","text":"def greet_user():\n print(\"Hello!\")\n\ngreet_user()\n\ndef make_shirt(size=\"large\", message=\"I love Python\"):\n print(\"Congrations! You now have a size \" + size + \" shirt with the following text: \" + message + \".\")\n\nmake_shirt()\nmake_shirt(\"small\",\"To believe or not to believe\")\n\n\ndef get_formatted_name(first_name, last_name, middle_name=\"\"):\n if middle_name:\n full_name = first_name + \" \" + middle_name + \" \" + last_name\n else:\n full_name = first_name + \" \" + last_name\n return full_name.title()\n\nmusician = get_formatted_name('jimi', 'hendrix')\nprint(musician)\n\nnana = get_formatted_name('phyllis', 'tyler', 'elaine')\nprint(nana)\n\n\ndef city_country(city, country):\n city_details = city + \", \" + country\n return city_details.title()\n\nphilly = city_country(\"philadelphia\", \"united states\")\nsantiago = city_country(\"santiago\", \"chile\")\nparis = city_country(\"paris\", \"france\")\nprint(philly)\nprint(santiago)\nprint(paris)\n\n\ndef build_album(name, artist, tracks=\"\"):\n album = { 'name': name, 'artist': artist}\n if tracks:\n album['tracks'] = tracks\n return album\n\nlemonade = build_album('lemonade', 'beyonce', 24)\nprint(lemonade)\n","sub_path":"chapter_9/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"384164114","text":"#! /usr/bin/env python3\n\nimport re\nimport sys\nimport subprocess\n\nfrom optparse import OptionParser\n\nparser = OptionParser ()\nparser.add_option (\"\", \"--print-errors\", default=False, action=\"store_true\", dest=\"print_errors\")\nparser.add_option (\"\", \"--print\", default=False, action=\"store_true\", dest=\"print\")\n\n(opts, args) = parser.parse_args ()\n \ntypes = {\n \"POSTGRES_9_6\" : 5432,\n \"POSTGRES_11\" : 5432,\n \"MYSQL_5_6\" : 3306,\n \"MYSQL_5_7\" : 3306,\n}\n \ndef get_out_lines (cmd):\n try:\n out = subprocess.check_output (cmd, shell=True).decode ('utf-8')\n lin = out.splitlines ()\n return lin\n except subprocess.CalledProcessError as err:\n return err\n \ndef get_ip_addresses (proj, sql):\n cmd = \"gcloud sql instances describe \" + sql + \" --project=\" + proj\n cmd += \" --format='value(ipAddresses.ipAddress, databaseVersion)'\"\n res = get_out_lines (cmd)\n if type (res) is subprocess.CalledProcessError:\n if opts.print_errors == True:\n print (\"Error: \", proj, sql)\n return\n for i in res:\n arr = re.split (\"\\s+\", i)\n if opts.print:\n print (\"%15s %14s %s\" %(arr[0], arr[1], proj))\n else:\n print (\"%s:%s\" % (arr[0], types[arr[1]]))\n\ndef get_instances (proj):\n cmd = \"gcloud sql instances list --project=\"+ proj + \" --format='value(name) '\"\n cmd += \" --filter='STATUS = RUNNABLE' 2>/dev/null\"\n res = get_out_lines (cmd)\n if type(res) is subprocess.CalledProcessError:\n if opts.print_errors == True:\n print (\"Error: \", proj)\n return\n for i in res:\n get_ip_addresses (proj, i)\n\nfilter=\"\"\nif len (args):\n filter=\" --filter=\" + args[0]\n\ncmd = \"gcloud projects list --format='value(PROJECT_ID)' \" + filter\n\nres = get_out_lines (cmd)\nfor i in res:\n get_instances (i)\n","sub_path":"py/list-sql-ports.py","file_name":"list-sql-ports.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"108936547","text":"from django.core.management.base import BaseCommand, CommandError\nfrom polls.models import Poll\n\nclass Command(BaseCommand):\n help = 'Closes the specified poll for voting'\n\n def add_arguments(self, parser):\n parser.add_argument('directory', type=string)\n\n # Named (optional) arguments\n parser.add_argument('--root_directory',\n dest='root_dir',\n help=\"\"\"Specifies the root of all images directory, in case it is modified on the server. Images are \n identified by their relative path name to this root.\"\"\")\n\n def handle(self, *args, **options):\n \n current_directory = options['directory']\n \n if options['root_directory']:\n root_dir = options['root_directory']\n \n \n try:\n poll = Poll.objects.get(pk=poll_id)\n except Poll.DoesNotExist:\n raise CommandError('Poll \"%s\" does not exist' % poll_id)\n \n poll.opened = False\n poll.save()\n \n self.stdout.write('Successfully closed poll \"%s\"' % poll_id)","sub_path":"server/poly/management/commands/add_picture_folder.py","file_name":"add_picture_folder.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"227557689","text":"import typing\nimport json\nimport logging\nimport asyncio\nimport urllib.parse\nimport collections\n\nimport websockets\nimport aiohttp\n\nfrom .types import (\n User,\n Actor,\n Dialog,\n MessageModel,\n Message,\n BaseEvent,\n Notify,\n EventType,\n Category,\n Project,\n)\nfrom kwork.exceptions import KworkException, KworkBotException\n\nlogger = logging.getLogger(__name__)\nHandler = collections.namedtuple(\n \"Handler\", [\"func\", \"text\", \"on_start\", \"text_contains\"]\n)\n\n\nclass Kwork:\n def __init__(self, login: str, password: str, proxy: str = None):\n connector: typing.Optional[aiohttp.BaseConnector] = None\n\n if proxy is not None:\n try:\n from aiohttp_socks import ProxyConnector\n except ImportError:\n raise ImportError(\n \"You have to install aiohttp_socks for using\"\n \" proxy, make it by pip install aiohttp_socks\"\n )\n connector = ProxyConnector.from_url(proxy)\n\n self.session = aiohttp.ClientSession(connector=connector)\n self.host = \"https://api.kwork.ru/{}\"\n self.login = login\n self.password = password\n self._token: typing.Optional[str] = None\n\n @property\n async def token(self) -> str:\n if self._token is None:\n self._token = await self.get_token()\n return self._token\n\n async def api_request(self, method: str, api_method: str, **params) -> typing.Union[dict, typing.NoReturn]:\n logging.debug(\n f\"making {method} request on /{api_method} with params - {params}\"\n )\n async with self.session.request(\n method=method,\n url=self.host.format(api_method),\n headers={\"Authorization\": \"Basic bW9iaWxlX2FwaTpxRnZmUmw3dw==\"},\n params=params,\n ) as resp:\n if resp.content_type != \"application/json\":\n error_text: str = await resp.text()\n raise KworkException(error_text)\n json_response: dict = await resp.json()\n if not json_response[\"success\"]:\n raise KworkException(json_response[\"error\"])\n logging.debug(f\"result of request on /{api_method} - {json_response}\")\n return json_response\n\n async def close(self) -> None:\n await self.session.close()\n\n async def get_token(self) -> str:\n resp: dict = await self.api_request(\n method=\"post\",\n api_method=\"signIn\",\n login=self.login,\n password=self.password,\n )\n return resp[\"response\"][\"token\"]\n\n async def get_me(self) -> Actor:\n actor = await self.api_request(\n method=\"post\", api_method=\"actor\", token=await self.token\n )\n return Actor(**actor[\"response\"])\n\n async def get_user(self, user_id: int) -> User:\n \"\"\"\n :param user_id: you can find it in dialogs\n :return:\n \"\"\"\n user = await self.api_request(\n method=\"post\", api_method=\"user\", id=user_id, token=await self.token\n )\n return User(**user[\"response\"])\n\n async def set_typing(self, recipient_id: int) -> dict:\n resp = await self.api_request(\n method=\"post\",\n api_method=\"typing\",\n recipientId=recipient_id,\n token=await self.token,\n )\n return resp\n\n async def get_all_dialogs(self) -> typing.List[Dialog]:\n page = 1\n dialogs: typing.List[Dialog] = []\n\n while True:\n dialogs_page = await self.api_request(\n method=\"post\",\n api_method=\"dialogs\",\n filter=\"all\",\n page=page,\n token=await self.token,\n )\n if not dialogs_page[\"response\"]:\n break\n\n for dialog in dialogs_page[\"response\"]:\n dialogs.append(Dialog(**dialog))\n page += 1\n\n return dialogs\n\n async def set_offline(self) -> dict:\n return await self.api_request(\n method=\"post\", api_method=\"offline\", token=await self.token\n )\n\n async def get_dialog_with_user(self, user_name: str) -> typing.List[MessageModel]:\n page = 1\n dialog: typing.List[MessageModel] = []\n\n while True:\n messages_dict: dict = await self.api_request(\n method=\"post\",\n api_method=\"inboxes\",\n username=user_name,\n page=page,\n token=await self.token,\n )\n if not messages_dict.get(\"response\"):\n break\n for message in messages_dict[\"response\"]:\n dialog.append(MessageModel(**message))\n\n if page == messages_dict[\"paging\"][\"pages\"]:\n break\n page += 1\n\n return dialog\n\n async def get_worker_orders(self) -> dict:\n return await self.api_request(\n method=\"post\",\n api_method=\"workerOrders\",\n filter=\"all\",\n token=await self.token,\n )\n\n async def get_payer_orders(self) -> dict:\n return await self.api_request(\n method=\"post\",\n api_method=\"payerOrders\",\n filter=\"all\",\n token=await self.token,\n )\n\n async def get_notifications(self) -> dict:\n return await self.api_request(\n method=\"post\", api_method=\"notifications\", token=await self.token,\n )\n\n async def get_categories(self) -> typing.List[Category]:\n raw_categories = await self.api_request(\n method=\"post\", api_method=\"categories\", type=\"1\", token=await self.token,\n )\n categories = []\n for dict_category in raw_categories[\"response\"]:\n category = Category(**dict_category)\n categories.append(category)\n return categories\n\n async def get_projects(\n self, categories_ids: typing.List[int]\n ) -> typing.List[Project]:\n raw_projects = await self.api_request(\n method=\"post\",\n api_method=\"projects\",\n categories=\"%2C\".join(str(category) for category in categories_ids),\n token=await self.token,\n )\n projects = []\n for dict_project in raw_projects[\"response\"]:\n project = Project(**dict_project)\n projects.append(project)\n return projects\n\n async def _get_channel(self) -> str:\n channel = await self.api_request(\n method=\"post\", api_method=\"getChannel\", token=await self.token\n )\n return channel[\"response\"][\"channel\"]\n\n async def send_message(self, user_id: int, text: str) -> dict: # noqa\n logging.debug(f\"Sending message for {user_id} with text - {text}\")\n resp = await self.session.post(\n f\"{self.host.format('inboxCreate')}\"\n f\"?user_id={user_id}\"\n f\"&text={urllib.parse.quote(text)}&token={await self.token}\",\n headers={\"Authorization\": \"Basic bW9iaWxlX2FwaTpxRnZmUmw3dw==\"},\n )\n json_resp = await resp.json()\n logging.debug(f\"result of sending - {json_resp}\")\n return json_resp\n\n async def delete_message(self, message_id) -> dict:\n return await self.api_request(\n method=\"post\",\n api_method=\"inboxDelete\",\n id=message_id,\n token=await self.token,\n )\n\n\nclass KworkBot(Kwork):\n def __init__(self, login: str, password: str, proxy: str = None):\n super().__init__(login, password, proxy)\n self._handlers: typing.List[Handler] = []\n\n async def listen_messages(self):\n logger.info(\"Starting listen messages\")\n while True:\n try:\n channel = await self._get_channel()\n uri = f\"wss://notice.kwork.ru/ws/public/{channel}\"\n async with websockets.connect(uri) as websocket:\n try:\n data = await websocket.recv()\n except websockets.exceptions.ConnectionClosedError as e:\n logging.debug(f\"Get {e}, reboot socket...\")\n continue\n\n logging.debug(f\"Get updates from websocket - {data}\")\n\n json_event = json.loads(data)\n json_event_data = json.loads(json_event[\"text\"])\n\n event: BaseEvent = BaseEvent(**json_event_data)\n\n if event.event == EventType.NEW_MESSAGE:\n message: Message = Message(\n api=self,\n from_id=event.data[\"from\"],\n text=event.data[\"inboxMessage\"],\n to_user_id=event.data[\"to_user_id\"],\n inbox_id=event.data[\"inbox_id\"],\n title=event.data[\"title\"],\n last_message=event.data[\"lastMessage\"],\n )\n yield message\n elif (\n event.event == EventType.NOTIFY\n and event.data.get(Notify.NEW_MESSAGE) is not None\n ):\n message_raw: MessageModel = (\n await self.get_dialog_with_user(\n event.data[\"dialog_data\"][0][\"login\"]\n )\n )[0]\n message: Message = Message(\n api=self,\n from_id=message_raw.from_id,\n text=message_raw.message,\n to_user_id=message_raw.to_id,\n inbox_id=message_raw.message_id,\n title=\"\",\n last_message={},\n )\n yield message\n except KworkException as e:\n logging.error(f\"Get error in polling - {e}, restarting\")\n await asyncio.sleep(10)\n\n @staticmethod\n def _dispatch_text_contains(text, message_text) -> bool:\n lower_text = [word.lower() for word in message_text.split()]\n for word in lower_text:\n if text == word.strip(\"...\").strip(\"!\").strip(\".\").strip(\"?\").strip(\"-\"):\n return True\n return False\n\n async def _dispatch_message(\n self, message: Message, handler: Handler\n ) -> typing.Optional[typing.Callable]:\n if not any([handler.on_start, handler.text, handler.text_contains]):\n return handler.func\n\n if handler.on_start:\n from_username = (await self.get_all_dialogs())[0].username\n current_dialog = await self.get_dialog_with_user(from_username)\n if len(current_dialog) == 1:\n return handler.func\n elif handler is not None and handler.text.lower() == message.text.lower():\n return handler.func\n elif handler.text_contains is not None and self._dispatch_text_contains(\n handler.text_contains, message.text\n ):\n return handler.func\n return None\n\n def message_handler(\n self, text: str = None, on_start: bool = False, text_contains: str = None\n ):\n \"\"\"\n :param text: answer on exact match of message\n :param on_start: answer only on fist message in dialog\n :param text_contains: answer if message contains this text\n :return:\n \"\"\"\n\n def decorator(func: typing.Callable) -> typing.Callable:\n handler = Handler(func, text, on_start, text_contains)\n self._handlers.append(handler)\n return func\n\n return decorator\n\n async def run_bot(self):\n if not self._handlers:\n raise KworkBotException(\"You have to create handler\")\n logging.info(\"Bot is running!\")\n async for message in self.listen_messages():\n for handler in self._handlers:\n handler_func = await self._dispatch_message(message, handler)\n logger.debug(f\"Found handler - {handler_func}\")\n if handler_func is not None:\n await handler_func(message)\n","sub_path":"kwork/kwork.py","file_name":"kwork.py","file_ext":"py","file_size_in_byte":12250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"540059547","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom dataloaders import *\nfrom utils import config\nimport numpy as np\nfrom model import *\nfrom torch.optim import lr_scheduler\nfrom trainer import *\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import precision_recall_fscore_support, accuracy_score\nimport lightgbm as lgb\n\n\n\n\ndef experience_mnist(config, path, param):\n print(\"START MNIST\")\n use_cuda = config.general.use_cuda and torch.cuda.is_available()\n torch.manual_seed(config.general.seed)\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n print(\"START TRAINING TARGET MODEL\")\n data_train_target = custum_MNIST(True, 0, config, '../data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n data_test_target = custum_MNIST(True, 0, config, '../data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n criterion = nn.CrossEntropyLoss()\n train_loader_target = torch.utils.data.DataLoader(data_train_target, batch_size=config.learning.batch_size, shuffle=True)\n test_loader_target = torch.utils.data.DataLoader(data_test_target, batch_size=config.learning.batch_size, shuffle=True)\n dataloaders_target = {\"train\": train_loader_target, \"val\": test_loader_target}\n dataset_sizes_target = {\"train\": len(data_train_target), \"val\": len(data_test_target)}\n print(\"TAILLE dataset\", dataset_sizes_target)\n model_target = Net_mnist().to(device)\n optimizer = optim.SGD(model_target.parameters(), lr=config.learning.learning_rate, momentum=config.learning.momentum)\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=config.learning.decrease_lr_factor, gamma=config.learning.decrease_lr_every)\n model_target, best_acc_target, data_test_set, label_test_set, class_test_set = train_model(model_target, criterion, optimizer, exp_lr_scheduler,dataloaders_target,dataset_sizes_target,\n num_epochs=config.learning.epochs)\n np.save(path + \"/res_train_target_\"+str(param)+\".npy\", best_acc_target)\n print(\"START TRAINING SHADOW MODEL\")\n all_shadow_models = []\n all_dataloaders_shadow = []\n data_train_set = []\n label_train_set = []\n class_train_set = []\n for num_model_sahdow in range(config.general.number_shadow_model):\n criterion = nn.CrossEntropyLoss()\n\n data_train_shadow = custum_MNIST(False, num_model_sahdow, config, '../data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n data_test_shadow = custum_MNIST(False, num_model_sahdow, config, '../data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ]))\n train_loader_shadow = torch.utils.data.DataLoader(data_train_shadow, batch_size=config.learning.batch_size, shuffle=True)\n test_loader_shadow = torch.utils.data.DataLoader(data_test_shadow, batch_size=config.learning.batch_size, shuffle=True)\n dataloaders_shadow = {\"train\": train_loader_shadow, \"val\": test_loader_shadow}\n dataset_sizes_shadow = {\"train\": len(data_train_shadow), \"val\": len(data_test_shadow)}\n print(\"TAILLE dataset\", dataset_sizes_shadow)\n model_shadow = Net_mnist().to(device)\n optimizer = optim.SGD(model_shadow.parameters(), lr=config.learning.learning_rate, momentum=config.learning.momentum)\n exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=config.learning.decrease_lr_factor, gamma=config.learning.decrease_lr_every)\n model_shadow, best_acc_sh, data_train_set_unit, label_train_set_unit, class_train_set_unit = train_model(model_shadow, criterion, optimizer, exp_lr_scheduler,dataloaders_target,dataset_sizes_target,\n num_epochs=config.learning.epochs)\n data_train_set.append(data_train_set_unit)\n label_train_set.append(label_train_set_unit)\n class_train_set.append(class_train_set_unit)\n np.save(path + \"/res_train_shadow_\"+str(num_model_sahdow)+\"_\"+str(param)+\".npy\", best_acc_sh)\n all_shadow_models.append(model_shadow)\n all_dataloaders_shadow.append(dataloaders_shadow)\n print(\"START GETTING DATASET ATTACK MODEL\")\n data_train_set = np.concatenate(data_train_set)\n label_train_set = np.concatenate(label_train_set)\n class_train_set = np.concatenate(class_train_set)\n #data_test_set, label_test_set, class_test_set = get_data_for_final_eval([model_target], [dataloaders_target], device)\n #data_train_set, label_train_set, class_train_set = get_data_for_final_eval(all_shadow_models, all_dataloaders_shadow, device)\n data_train_set, label_train_set, class_train_set = shuffle(data_train_set, label_train_set, class_train_set, random_state=config.general.seed)\n data_test_set, label_test_set, class_test_set = shuffle(data_test_set, label_test_set, class_test_set, random_state=config.general.seed)\n print(\"Taille dataset train\", len(label_train_set))\n print(\"Taille dataset test\", len(label_test_set))\n print(\"START FITTING ATTACK MODEL\")\n model = lgb.LGBMClassifier(objective='binary', reg_lambda=config.learning.ml.reg_lambd, n_estimators=config.learning.ml.n_estimators)\n model.fit(data_train_set, label_train_set)\n y_pred_lgbm = model.predict(data_test_set)\n precision_general, recall_general, _, _ = precision_recall_fscore_support(y_pred=y_pred_lgbm, y_true=label_test_set, average = \"macro\")\n accuracy_general = accuracy_score(y_true=label_test_set, y_pred=y_pred_lgbm)\n precision_per_class, recall_per_class, accuracy_per_class = [], [], []\n for idx_class, classe in enumerate(data_train_target.classes):\n all_index_class = np.where(class_test_set == idx_class)\n precision, recall, _, _ = precision_recall_fscore_support(y_pred=y_pred_lgbm[all_index_class], y_true=label_test_set[all_index_class], average = \"macro\")\n accuracy = accuracy_score(y_true=label_test_set[all_index_class], y_pred=y_pred_lgbm[all_index_class])\n precision_per_class.append(precision)\n recall_per_class.append(recall)\n accuracy_per_class.append(accuracy)\n print(\"END MNIST\")\n return (precision_general, recall_general, accuracy_general, precision_per_class, recall_per_class, accuracy_per_class)\n","sub_path":"experience_mnist.py","file_name":"experience_mnist.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"312103438","text":"\"\"\"\nQuestion 17\nQuestion:\nWrite a program that computes the net amount of a bank account based a transaction log\nfrom console input. The transaction log format is shown as following:\n\nD 100\nW 200\n\nD means deposit while W means withdrawal.\n\nSuppose the following input is supplied to the program:\n\nD 300\nD 300\nW 200\nD 100\n\nThen, the output should be:\n\n500\n\nHints:\nIn case of input data being supplied to the question, it should be assumed to be a console input.\n\n\"\"\"\ntotal = 0\n\nwhile True:\n s = input().split()\n # break if the string is empty\n if not s:\n break\n # two inputs are distributed in cm and num in string data type\n cm, num = map(str, s)\n\n if cm == 'D':\n total += int(num)\n if cm == 'W':\n total -= int(num)\n\nprint(total)\n","sub_path":"Python-Files/Day-5/Question-17.py","file_name":"Question-17.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"354823021","text":"import sqlite3\nconn = sqlite3.connect('test.sqlite') # 建立資料庫連線\n# 定義資料串列\ndatas = [[1, 'David', '02-123456789'],\n [2, 'Lily', '02-987654321'],]\nfor data in datas:\n # 新增資料\n conn.execute(\"INSERT INTO contact (id, name, tel) VALUES \\\n ({}, '{}', '{}')\".format(data[0], data[1], data[2]))\nconn.commit() # 更新\nconn.close() # 關閉資料庫連線","sub_path":"_4.python/__code/Python自學聖經(第二版)/ch12/sqlite_crud2.py","file_name":"sqlite_crud2.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"444986660","text":"import ncclient\nfrom ncclient import manager\nfrom ncclient.operations import TimeoutExpiredError\nimport xmltodict\nimport xml.dom.minidom\nimport socket\nimport json\n\ndef connect(node):\n try:\n m = ncclient.manager.connect(\n host = node, \n port = '2222', \n username = 'joao', \n password = 'cisco12345!', \n hostkey_verify = False,\n device_params={'name':'nexus'},\n allow_agent=False,\n look_for_keys=False\n )\n return m\n except:\n print(\"Unable to connect \" + node)\n\ndef getVersion(node):\n try:\n int_filter = '''\n \n \n \n '''\n m = connect(node)\n netconf_output = m.get(('subtree', int_filter))\n xml_doc = xml.dom.minidom.parseString(netconf_output.xml)\n version = xml_doc.getElementsByTagName(\"mod:nxos_ver_str\")\n except:\n return \"Unable to get this node version\"\n return \"Version \" + version[0].firstChild.nodeValue\n\ndef changeHostname(node, newhostname):\n try:\n update_hostname = '''\n \n <__XML__MODE__exec_configure>\n %s\n \n \n '''\n configuration = ''\n m = connect(node)\n\n configuration += ''\n configuration += update_hostname % (newhostname)\n configuration += ''\n m.edit_config(target='running', config=configuration)\n except:\n return \"Unable to change this node hostname\"\n return \"Config pushed successfuly!\"\n\ndef Main():\n host = \"127.0.0.1\"\n port = 5000\n \n mySocket = socket.socket()\n mySocket.bind((host, port))\n \n mySocket.listen(5)\n conn, addr = mySocket.accept()\n print (\"Connection from: \" + str(addr))\n while True:\n message = conn.recv(1024).decode()\n if not message: break\n if message == \"show version\":\n message = getVersion(host)\n elif (message.split())[0] == \"hostname\":\n message = changeHostname(host,(message.split())[1])\n else:\n message = \"Sorry, IDK this command\"\n conn.send(message.encode()) \n conn.close()\n \nif __name__ == '__main__':\n Main()\n","sub_path":"Automation/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"523011520","text":"\r\nimport os\r\nos.system('clear')\r\n\r\nprint('''\r\n-------------------------------------------------------------------------------\r\n ######- anji\r\n-------------------------------------------------------------------------------''') \r\ndef about():\r\n print(''' anji\r\n #IIEC RISE community #Righteducation #Vimaldaga\r\n if you want you can learn Docker tool @youtube search in youtube IIEC_Connect \r\n Engineering college bikaner\r\n if you are facing any issu in this program then mail me\r\n E- mail :- t.anji800@gmail.com''')\r\n final()\r\ndef titlebar():\r\n print('-'*79)\r\n print('\\t\\t\\t Make your life easy \\n\\t\\t\\t\\t\\t\\t -anji' )\r\n print('-'*79)\r\n print('1.Docker 2.Docker Images 3.Docker Container 4.Docker volume 5.Web server 6.About')\r\ndef exit1() :\r\n exit()\r\ndef images_docker() :\r\n os.system('docker images')\r\n final()\r\ndef running_container() :\r\n os.system('docker container ps')\r\n final()\r\ndef all_docker_id() :\r\n os.system('docker container ps -a ')\r\n final()\r\ndef os_new_start() :\r\n image = input('which os you want to start : ')\r\n name = input('give a name to your os : ')\r\n os.system('docker container run -dit --name {0} {1}'.format(name,image))\r\n final()\r\ndef attach_container() :\r\n image = input('which os you want to attach : ')\r\n os.system('docker container attach {0} '.format(image))\r\n final()\r\ndef start_container() :\r\n image = input('which container you want to start : ')\r\n os.system('docker container start {0} '.format(image))\r\n final()\r\ndef remove_container():\r\n name = input('which container you want to remove : ')\r\n conf = input('Aren you sure[yes/no] : ')\r\n conf=conf.lower()\r\n if conf == 'yes':\r\n os.system('docker container rm {}'.format(name))\r\n final()\r\ndef confi_docker_yum() :\r\n os.system(\"\"\" echo '''\r\n[docker-cccccccccccc]\r\nbaseurl=https://download.docker.com/linux/centos/7/x86_64/stable/\r\ngpgcheck=0\r\n[docker-ce]\r\nbaseurl=https://download.docker.com/linux/centos/7/x86_64/stable/Packages/\r\ngpgcheck=0''' >> /etc/yum.repos.d/hello_created_by_python.repo\"\"\" )\r\n final()\r\ndef install_docker() :\r\n os.system('yum install docker-ce --nobest')\r\n final()\r\ndef info_docker() :\r\n os.system('docker info')\r\n final()\r\ndef create_image() :\r\n name = input(\"Which container's image you want to create : \")\r\n image = input(\" Give a name to your new image : \")\r\n imageVer = input('Enter version : ')\r\n os.system('docker commit {0} {1}:{2} '.format(name,image,imageVer))\r\n final()\r\ndef detail_container() :\r\n name = input('which container details you want : ')\r\n os.system('docker container inspect {0} ' .format(name))\r\n final()\r\ndef ip_container(name) :\r\n if name == '':\r\n name = input(' Which container IPadress you want : ')\r\n else:\r\n value = '\"{{.NetworkSettings.IPAddress}}\"'\r\n os.system('echo {0} IPAddress : ` docker container inspect --format {1} {0}` '.format(name,value))\r\n final()\r\ndef cmd_run() :\r\n name = input('Choose your Container : ')\r\n while True :\r\n cmd = input('Enter 0 to exit or enter command : ')\r\n if cmd == '0' :\r\n break\r\n else :\r\n os.system('docker container exec {0} {1}'.format(name,cmd))\r\n final()\r\ndef stop_container() :\r\n name = input('Which container you want to stop : ')\r\n os.system('docker container stop {} '.format(name))\r\n final()\r\ndef detail_vol() :\r\n volume_inspect = input('Enter your volume name : ')\r\n os.system('docker volume inspect {0}'.format(volume_inspect))\r\n final()\r\ndef create_vol() :\r\n vol_name = input('Give a name to volume : ')\r\n os.system('docker volume create {0}'.format(vol_name))\r\n final()\r\ndef del_vol() :\r\n vol= input('Which volume you want to delete : ')\r\n confirm = input(\"This action can't be reversed really want to delete [y/n] : \")\r\n if confirm == 'y' :\r\n os.system('docker volume rm {0}'.format(vol))\r\n final()\r\n else :\r\n print('Operation cancelled ' )\r\n final()\r\ndef list_vol() :\r\n os.system('docker volume ls')\r\n final()\r\ndef wordpress():\r\n os.system('yum install mysql')\r\n os.system('docker pull mysql:5.7')\r\n os.system('docker pull wordpress:5.1.1.-php7.3-apache')\r\n os.system('docker run -dit -e MYSQL_ROOT_PASSWORD=anji -e MYSQL_USER=anji -e MYSQL_PASSWORD=anji -e MYSQL_DATABASE=my_database mysql:5.7')\r\n os.system(''' echo \"\"\"\r\n\r\nversion: '3'\r\nservices:\r\n data_base_os:\r\n image: mysql:5.7\r\n volumes:\r\n - mysql_storage:/var/lib/mysql\r\n restart: always\r\n environment:\r\n MYSQL_ROOT_PASSWORD: anji\r\n MYSQL_USER: anji\r\n MYSQL_PASSWORD: anji\r\n MYSQL_DATABASE: my_database\r\n\r\n\r\n\r\n wordpress_OS:\r\n image: wordpress:5.1.1-php7.3-apache\r\n restart: always\r\n depends_on:\r\n - data_base_os\r\n\r\n ports:\r\n - 8081:80\r\n environment:\r\n WORDPRESS_DB_HOST: data_base_os\r\n WORDPRESS_DB_USER: anji\r\n WORDPRESS_DB_PASSWORD: anji\r\n WORDPRESS_DB_NAME: my_database\r\n volumes:\r\n - wp_storage:/var/www/html\r\n\r\nvolumes:\r\n wp_storage:\r\n mysql_storage: \"\"\" > docker-compose.yml ''')\r\n x=os.system('docker-compose up')\r\n if x != 0:\r\n compose_install()\r\n os.system('docker-compose up')\r\ndef invalid_option() :\r\n print('error : option not supported ')\r\n final()\r\ndef copy(x):\r\n if x== 1:\r\n container = input('Container id or name : ')\r\n print('ex :- /root/webpage/webpage.html ') \r\n path = input('path of your webpage file : ')\r\n os.system('docker cp {0} {1}:/var/www/html/'.format(path,container))\r\n else :\r\n path = input('Enter file path : ')\r\n container = input('Enter container id or name ; ')\r\n path2 = input('File destination in container (default /root/) : ')\r\n if path2 == '':\r\n path2 = '/root/'\r\n os.system('docker cp {0} {1}:{2}'.format(path,container,path2))\r\n print('file succesfully copied in @{0}:{1}'.format(container,path2))\r\ndef final() :\r\n input('Press Enter to continue ..........')\r\n os.system('clear')\r\n titlebar()\r\ndef httpd():\r\n y1=0\r\n os.system('docker images')\r\n image = input('In which os you want to configure Webserver : ')\r\n name = input('Give a name to your webserver os : ')\r\n os.system('netstat -nptl')\r\n port =eval(input('select a port which is not usable by host : '))\r\n service = input('enter your service port default:80 : ')\r\n if service == '':\r\n service = 80\r\n os.system('docker volume ls')\r\n vol = input('Volume name : ')\r\n check = os.system('docker volume inspect {0} >> cachfile'.format(vol))\r\n if check != 0:\r\n os.system('docker volume create {0}'.format(vol))\r\n x= os.system('docker container run -dit --name {0} -p {3}:{4} -v {1}:/var/www/html {2}'.format(name,vol,image,port,service))\r\n httpdcheck = os.system('docker container exec {} rpm -q httpd'.format(name))\r\n if httpdcheck !=0 :\r\n y1=os.system('docker container exec {0} yum install httpd -y'.format(name))\r\n if x == 0 and y1 == 0 :\r\n os.system('docker container exec {0} /usr/sbin/httpd '.format(name))\r\n print('congratulation ! webserver configured successfully')\r\n else :\r\n print('Webserver not configured')\r\n final()\r\ndef download_image():\r\n image = input('Which os you want to download : ')\r\n os.system('docker pull {0}'.format(image))\r\ndef disable_firewall():\r\n os.system('systemctl disable firewalld ')\r\n os.system('systemctl stop firewalld')\r\n print('firewall has been disabled')\r\ndef image_create(name,img):\r\n x=1\r\n if img == '':\r\n img = input('Which image you want to use : ')\r\n x=0\r\n if name =='':\r\n name = input('Give a name : ')\r\n os.system('docker container run -dit --name {0} {1} '.format(name,img))\r\n os.system('docker container exec {0} yum install httpd -y'.format(name))\r\n os.system('docker container stop {0}'.format(name))\r\n os.system('docker commit {0} {0}'.format(name))\r\n os.system('docker images')\r\n if x == 1:\r\n os.system('docker container rm -f {0}'.format(name))\r\ndef httpd_configure_always():\r\n os.system('docker images')\r\n image= input('Enter a os name : ')\r\n name = input('Give a name to this container : ')\r\n os.system('docker container run -dit --name anji707054 {0}'.format(image))\r\n check_httpd_installed_or_not=os.system('docker container exec anji707054 rpm -q httpd')\r\n os.system('docker container rm -f anji707054')\r\n if check_httpd_installed_or_not != 0 :\r\n image_create(name,image)\r\n image = name\r\n os.system('docker volume ls ')\r\n vol = input('Enter volume name which you want attach this file : ')\r\n print('If your choice is docker than you can access your site only to this operating system ')\r\n choice = input('Which IP you want use as a server webserver adress[base/docker] : ')\r\n x=3\r\n if choice == 'base':\r\n \tos.system('netstat -nptl')\r\n \tport1 = input('Enter a port no which is free : ')\r\n \tx=os.system('docker container run -dit --name {0} -v {1}:/var/www/html/ -p {2}:80 {3}'.format(name,vol,port1,image))\r\n \tos.system('wait $!')\r\n elif choice == 'docker':\r\n x=os.system('docker container run -dit --name {0} -v {1}:/var/www/html/ {2}'.format(name,vol,image))\r\n os.system('wait $!')\r\n else :\r\n print('option not valid')\r\n if x == 0:\r\n os.system('''echo \"\"\"\r\nimport os\r\nos.system( 'echo rm -r -f /var/run/httpd/* >> /root/.bashrc')\r\nos.system( 'echo /usr/sbin/httpd >> /root/.bashrc')\r\n \"\"\" > prem123.py ''')\r\n os.system('echo docker container start {0} >> /root/.bashrc'.format(name))\r\n os.system('wait $!')\r\n python_check=os.system('docker exec {0} rpm -q python36'.format(name))\r\n if python_check != 0:\r\n os.system('docker exec {0} dnf install python3 -y'.format(name))\r\n os.system('wait $!')\r\n os.system('docker cp anji123.py {}:/root/anji123.py '.format(name))\r\n os.system('wait $!')\r\n os.system('docker exec {0} /usr/sbin/httpd'.format(name))\r\n os.system('wait $!')\r\n os.system('docker exec {0} python /root/anji123.py'.format(name))\r\n os.system('wait $!')\r\n if choice == 'docker':\r\n ip_container(name)\r\n else:\r\n print('If you trying to access this site from phone than your laptop and phone is connected to same network')\r\n os.system('echo \"\"\"Enter this IP in your browse with port no : {0} `ifconfig enp0s3 | grep \"inet 192.\"`\"\"\"'.format(port1))\r\n final()\r\ndef compose_install():\r\n\tos.system('curl -L \"https://github.com/docker/compose/releases/download/1.25.5/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose')\r\n\tos.system('chmod +x /usr/local/bin/docker-compose')\r\n\tos.system('docker-compose version')\r\n\tfinal()\r\ndef removeallcontainer():\r\n\tprint('Not recommanded ')\r\n\tcon=input('Are you sure you want to delete all container[y/n] : ') \r\n\tif con == 'y':\r\n\t\tos.system('docker container rm -f $(docker container ps -a -q)')\r\n\t\tos.system('docker container ps -a ; echo done')\r\n\telse:\r\n\t\tprint('Operation cancelled ')\r\n\tfinal()\r\ndef tar():\r\n\timage=input('Which image you want to save as a tar file : ')\r\n\tname=input('Give a name to your file : ')\r\n\tprint('please wait .........')\r\n\tos.system('docker save {0} -o /root/{1}.tar'.format(image,name))\r\n\tprint('your file is saved @/root/ ')\r\n\tfinal()\r\ndef delete_image():\r\n os.system('docker images ')\r\n image=input('Which image you want to delete : ')\r\n con= input('Are you sure ? you want to delete[y/n] : ')\r\n if con == 'y':\r\n os.system('docker rmi {0}.'.format(image))\r\n os.system('docker images ')\r\n else :\r\n print('Operation is cancelled ')\r\n final()\r\ndef load():\r\n\timgsrc=input(\"tar file location : \")\r\n\tprint('Please wait ...........')\r\n\tos.system(\"docker load -a {}\".format(imgsrc))\r\n\tfinal()\r\ndef upload():\r\n print('If you don have a account on docker hub then first create')\r\n select=input('Select Which image you want to upload in docker hub : ')\r\n if '/' not in select :\r\n print('you need to rename your image like : anji/webserver:v1')\r\n upload = input('New name : ')\r\n os.system('docker login ')\r\n os.system('docker push {0}'.format(upload))\r\nstart = 0\r\nwhile True:\r\n if start == 0 :\r\n titlebar() \r\n menu = input('Chose your menu : ')\r\n if menu == '1' :\r\n final()\r\n while True :\r\n print('''\r\n Press 0 : Main menu \r\n Press 1 : Configure yum/dnf to download docker\r\n Press 2 : Install Docker Tool in your PC\r\n Press 3 : about Docker''') \r\n ch = input('Enter your option : ')\r\n if ch == '0' :\r\n os.system('clear')\r\n break\r\n elif ch == '1' :\r\n confi_docker_yum()\r\n elif ch == '2' :\r\n install_docker()\r\n elif ch == '3' :\r\n info_docker()\r\n else:\r\n invalid_option()\r\n elif menu == '2':\r\n final()\r\n while True : #images menu create_image() \r\n print('''\r\n Press 0 : Main menu\r\n Press 1 : Show all Docker Images\r\n Press 2 : Create Docker images from container\r\n Press 3 : Download Docker images\r\n Press 4 : Save image in tar file\r\n Press 5 : Delete Docker image\r\n Press 6 : Load docker image locally\r\n Press 7 : Upload image on docker hub ''')\r\n ch = input('Enter your option : ')\r\n if ch == '0' :\r\n os.system('clear')\r\n break\r\n elif ch == '1' :\r\n images_docker() \r\n elif ch == '2' :\r\n create_image() \r\n elif ch == '3':\r\n download_image()\r\n elif ch == '4':\r\n tar()\r\n elif ch == '5':\r\n delete_image()\r\n elif ch == '6':\r\n load()\r\n elif ch == '7':\r\n upload()\r\n else:\r\n invalid_option()\r\n elif menu == '3' :\r\n final()\r\n while True :#container menu\r\n print('''\r\n Press 0 : Main menu\r\n Press 1 : Show how much Docker container are running currently\r\n Press 2 : Show all Docker containers (Stopped and Running)\r\n Press 3 : Start a new container\r\n Press 4 : Start a existing Container\r\n Press 5 : Attach os to terminal \r\n Press 6 : Run commands in container\r\n Press 7 : Check IPadress of container\r\n Press 8 : Stop Container\r\n Press 9 : Remove containers\r\n Press 10 : Copy somthing in container from base\r\n Press 11 : Delete all container\r\n ''') \r\n ch = input('Enter your option : ')\r\n if ch == '0' :\r\n break\r\n os.system('clear')\r\n elif ch == '9' :\r\n remove_container()\r\n elif ch == '1' :\r\n running_container()\r\n elif ch == '2':\r\n all_docker_id()\r\n elif ch == '3' :\r\n os_new_start()\r\n elif ch == '5':\r\n attach_container()\r\n elif ch=='4':\r\n start_container()\r\n elif ch == '6':\r\n cmd_run() \r\n elif ch == '7' :\r\n ip_container('')\r\n elif ch == '8' :\r\n stop_container()\r\n elif ch == '10':\r\n copy(4)\r\n elif ch == '11':\r\n removeallcontainer()\r\n else:\r\n invalid_option()\r\n elif menu == '4' :\r\n final()\r\n while True :#volume menu\r\n print('''\r\n Press 0 : Main menu\r\n Press 1 : List of docker volumes\r\n Press 2 : Check docker volume detail\r\n Press 3 : Create Docker Volume \r\n Press 4 : Delete a volume\r\n ''')\r\n ch = input('Enter your option : ')\r\n if ch == '0' :\r\n os.system('clear')\r\n break\r\n elif ch == '2' :\r\n detail_vol() \r\n elif ch == '3' :\r\n create_vol() \r\n elif ch == '4' :\r\n del_vol()\r\n elif ch == '1' :\r\n list_vol()\r\n else:\r\n invalid_option()\r\n\r\n elif menu == '5':\r\n final()\r\n while True:\r\n print('''\r\n \\t Use only redhat or centos images otherwise might be possibe failure\\n \r\n Press 0: Main menu\r\n Press 1: Configure Appache web server for temporary\r\n Press 2: Configure Wordpress web server\r\n Press 3: Install Docker-compose \r\n Press 4: create a image of your weserver os\r\n Press 5: Setup your webpage in container\r\n Press 6: Configure a appache webserver which always run on startup\r\n Press 7: Some port you cant select like 1234 to select these type of port disable Selinux security for this press 8 ''')\r\n ch = input(\"Enter your option : \")\r\n if ch == '0':\r\n os.system('clear')\r\n break \r\n elif ch == '1':\r\n disable_firewall()\r\n httpd()\r\n elif ch == '2':\r\n disable_firewall()\r\n wordpress()\r\n elif ch == '3':\r\n compose_install()\r\n elif ch =='4':\r\n create_image()\r\n elif ch == '5':\r\n copy(1)\r\n elif ch =='6':\r\n httpd_configure_always()\r\n disable_firewall()\r\n elif ch == '7':\r\n os.system('setenforce 0') \r\n else:\r\n invalid_option()\r\n elif menu == '0':\r\n exit1()\r\n elif menu == '6':\r\n os.system('clear')\r\n titlebar()\r\n about()\r\n os.system('clear')\r\n else :\r\n invalid_option()\r\n","sub_path":"anji.py","file_name":"anji.py","file_ext":"py","file_size_in_byte":19059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"16064105","text":"# A python program to convert decimal to Hexadecimal\n\nnumber = int(input(\"Enter the number: \"))\nhexadecimal = \"\"\ntemp = number\nalpha = {10:\"A\", 11:\"B\", 12:\"C\", 13:\"D\", 14:\"E\", 15:\"F\"}\nwhile number > 0:\n remainder = number % 16\n if remainder > 9:\n hexadecimal += alpha[remainder]\n else:\n hexadecimal += str(remainder)\n number = number // 16\nprint(\"The hexadecimal equavalent of %d is %s\" % (temp , hexadecimal[::-1]))","sub_path":"project05.py","file_name":"project05.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"230743055","text":"\"\"\"\nCopyright (c) 2017-present, Facebook, Inc.\nAll rights reserved.\n\nThis source code is licensed under the BSD-style license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport copy\nfrom enum import Enum\n\nfrom .models import is_equal, escape, TimestampColumn, EnumColumn, SetColumn\n\n\nclass BaseAlterType(Enum):\n pass\n\n\n# Side note the algorithm that could be chosen for DDL. See https://fburl.com/bxftsout\nclass ColAlterType(BaseAlterType):\n CHANGE_COL_DEFAULT_VAL = \"change_col_default_val\" # instant\n REORDER_COL = \"reorder_col\" # rebuild\n ADD_COL = \"add_col\" # instant\n ADD_AUTO_INC_COL = \"add_auto_inc_col\" # inplace\n DROP_COL = \"drop_col\" # rebuild\n CHANGE_COL_DATA_TYPE = \"change_col_data_type\" # copy\n CHANGE_NULL = \"change_null\" # rebuild\n CHANGE_ENUM = \"change_enum\" # instant/copy\n CHANGE_SET = \"change_set\" # instant/copy\n CHANGE_COL_CHARSET = \"change_col_charset\"\n CHANGE_COL_COLLATE = \"change_col_collate\"\n CHANGE_COL_COMMENT = \"change_col_comment\"\n\n\nclass IndexAlterType(BaseAlterType):\n CHANGE_INDEX_TYPE = \"change_index_type\" # instant. index type is hash/btree\n CHANGE_UNIQUE_CONSTRAINT = \"change_unique_constraint\"\n CHANGE_INDEX_KEY_BLOCK_SIZE = \"change_index_key_block_size\"\n CHANGE_KEY_TYPE = \"change_key_type\" # key type is FULLTEXT/SPATIAL\n CHANGE_INDEX_COMMENT = \"change_index_comment\"\n ADD_INDEX = \"add_index\" # inplace\n DROP_INDEX = \"drop_index\" # inplace, metadata only\n CHANGE_PK = \"change_pk\" # copy\n\n\nclass TableAlterType(BaseAlterType):\n CHANGE_ROW_FORMAT = \"change_row_format\"\n CHANGE_TABLE_KEY_BLOCK_SIZE = \"change_table_key_block_size\"\n CHANGE_TABLE_CHARSET = \"change_table_charset\"\n CHANGE_TABLE_COLLATE = \"change_table_collate\"\n CHANGE_TABLE_COMMENT = \"change_table_comment\"\n CHANGE_ENGINE = \"change_engine\"\n CHANGE_AUTO_INC_VAL = \"change_auto_inc_val\" # inplace\n\n\nINSTANT_DDLS = {\n ColAlterType.CHANGE_COL_DEFAULT_VAL,\n ColAlterType.ADD_COL,\n IndexAlterType.CHANGE_INDEX_TYPE,\n}\n\n\nclass TableOptionDiff(object):\n def __init__(self, option_name, value):\n self.option_name = option_name\n self.value = value\n\n def to_sql(self):\n return \"{}={}\".format(self.option_name, self.value)\n\n\nclass SchemaDiff(object):\n \"\"\"\n Representing the difference between two Table object\n \"\"\"\n\n def __init__(self, left, right, ignore_partition=False):\n self.left = left\n self.right = right\n self.attrs_to_check = [\n \"charset\",\n \"collate\",\n \"comment\",\n \"engine\",\n \"key_block_size\",\n \"name\",\n \"row_format\",\n ]\n if not ignore_partition:\n self.attrs_to_check.append(\"partition\")\n self._alter_types = set()\n\n def _calculate_diff(self):\n diffs = {\n \"removed\": [],\n \"added\": [],\n # Customized messages\n \"msgs\": [],\n # Any attributes that were modified\n \"attrs_modified\": [],\n }\n # We are copying here since we want to change the col list.\n # Shallow copy should be enough here\n col_left_copy = copy.copy(self.left.column_list)\n col_right_copy = copy.copy(self.right.column_list)\n for col in self.left.column_list:\n if col not in self.right.column_list:\n diffs[\"removed\"].append(col)\n col_left_copy.remove(col)\n\n for col in self.right.column_list:\n if col not in self.left.column_list:\n diffs[\"added\"].append(col)\n col_right_copy.remove(col)\n\n # Two tables have different col order\n if sorted(col_left_copy, key=lambda col: col.name) == sorted(\n col_right_copy, key=lambda col: col.name\n ):\n old_order = []\n new_order = []\n for col1, col2 in zip(col_left_copy, col_right_copy):\n if col1 != col2:\n old_order.append(col1.name)\n new_order.append(col2.name)\n if old_order:\n diffs[\"msgs\"].append(\"Column order mismatch was detected:\")\n diffs[\"msgs\"].append(\"- \" + \", \".join(old_order))\n diffs[\"msgs\"].append(\"+ \" + \", \".join(new_order))\n\n for idx in self.left.indexes:\n if idx not in self.right.indexes:\n diffs[\"removed\"].append(idx)\n for idx in self.right.indexes:\n if idx not in self.left.indexes:\n diffs[\"added\"].append(idx)\n\n if self.left.primary_key != self.right.primary_key:\n if self.left.primary_key.column_list:\n diffs[\"removed\"].append(self.left.primary_key)\n if self.right.primary_key.column_list:\n diffs[\"added\"].append(self.right.primary_key)\n\n for attr in self.attrs_to_check:\n tbl_option_old = getattr(self.left, attr)\n tbl_option_new = getattr(self.right, attr)\n if not is_equal(tbl_option_old, tbl_option_new):\n diffs[\"removed\"].append(TableOptionDiff(attr, tbl_option_old))\n diffs[\"added\"].append(TableOptionDiff(attr, tbl_option_new))\n diffs[\"attrs_modified\"].append(attr)\n\n return diffs\n\n def __str__(self):\n if self.left == self.right:\n return \"No difference\"\n else:\n diff_strs = []\n diffs = self._calculate_diff()\n for diff in diffs[\"removed\"]:\n diff_strs.append(\"- \" + diff.to_sql())\n for diff in diffs[\"added\"]:\n diff_strs.append(\"+ \" + diff.to_sql())\n for diff in diffs[\"msgs\"]:\n diff_strs.append(diff)\n for attr in diffs[\"attrs_modified\"]:\n diff_strs.append(f\"attrs_modified: {attr}\")\n diff_str = \"\\n\".join(diff_strs)\n return diff_str\n\n def diffs(self):\n return self._calculate_diff()\n\n @property\n def alter_types(self):\n if not self._alter_types:\n self.to_sql()\n return self._alter_types\n\n def add_alter_type(self, ddl_alter_type):\n self._alter_types.add(ddl_alter_type)\n\n def _gen_col_sql(self):\n \"\"\"\n Generate the column section for ALTER TABLE statement\n \"\"\"\n segments = []\n old_columns = {col.name: col for col in self.left.column_list}\n new_columns = {col.name: col for col in self.right.column_list}\n old_column_names = [col.name for col in self.left.column_list]\n new_column_names = [col.name for col in self.right.column_list]\n\n # Drop columns\n for col in self.left.column_list:\n if col.name not in new_columns.keys():\n segments.append(\"DROP `{}`\".format(escape(col.name)))\n old_column_names.remove(col.name)\n self.add_alter_type(ColAlterType.DROP_COL)\n\n # Add columns\n # If the added column is not at the end, recognize that as reordering columns\n handled_cols = []\n for idx, col in enumerate(self.right.column_list):\n if col.name not in old_columns.keys():\n if idx == 0:\n position = \"FIRST\"\n if (\n old_column_names\n and ColAlterType.DROP_COL not in self._alter_types\n ):\n self.add_alter_type(ColAlterType.REORDER_COL)\n old_column_names = [col.name] + old_column_names\n else:\n position = \"AFTER `{}`\".format(\n escape(self.right.column_list[idx - 1].name)\n )\n new_idx = (\n old_column_names.index(self.right.column_list[idx - 1].name) + 1\n )\n if (\n new_idx != len(old_column_names)\n and ColAlterType.DROP_COL not in self._alter_types\n ):\n self.add_alter_type(ColAlterType.REORDER_COL)\n old_column_names = (\n old_column_names[:new_idx]\n + [col.name]\n + old_column_names[new_idx:]\n )\n handled_cols.append(col.name)\n self.add_alter_type(ColAlterType.ADD_COL)\n if col.auto_increment:\n self.add_alter_type(ColAlterType.ADD_AUTO_INC_COL)\n segments.append(\"ADD {} {}\".format(col.to_sql(), position))\n\n # Adjust position\n # The idea here is to compare column ancestor if they are the same between\n # old and new column list, this means the position of this particular\n # column hasn't been changed. Otherwise add a MODIFY clause to change the\n # position\n for idx, col_name in enumerate(new_column_names):\n # If the column is recently added, then skip because it's already\n # in the DDL\n if col_name in handled_cols:\n continue\n # Get column definition\n col = new_columns[col_name]\n old_pos = old_column_names.index(col_name)\n\n # If the first column is diferent, we need to adjust the sequence\n if idx == 0:\n if old_pos == 0:\n continue\n segments.append(\"MODIFY {} FIRST\".format(col.to_sql()))\n handled_cols.append(col_name)\n self.add_alter_type(ColAlterType.REORDER_COL)\n continue\n\n # If this column has the same ancestor then it means there's no sequence\n # adjustment needed\n if new_column_names[idx - 1] == old_column_names[old_pos - 1]:\n continue\n\n segments.append(\n \"MODIFY {} AFTER `{}`\".format(\n col.to_sql(), escape(new_column_names[idx - 1])\n )\n )\n handled_cols.append(col_name)\n self.add_alter_type(ColAlterType.REORDER_COL)\n\n # Modify columns\n for col in self.right.column_list:\n if col.name in old_columns and col != old_columns[col.name]:\n # If the column has been taken care of because of sequence change\n # previously we can skip the work here\n if col.name in handled_cols:\n continue\n self._update_col_attrs_changes(col, old_columns[col.name])\n segments.append(\"MODIFY {}\".format(col.to_sql()))\n return segments\n\n def _is_null_change(self, old_col, new_col):\n if isinstance(old_col, TimestampColumn):\n old_col.explicit_ts_default()\n if isinstance(new_col, TimestampColumn):\n new_col.explicit_ts_default()\n return old_col.nullable != new_col.nullable\n\n def _is_col_default_change(self, old_col, new_col):\n if isinstance(old_col, TimestampColumn):\n old_col.explicit_ts_default()\n if isinstance(new_col, TimestampColumn):\n new_col.explicit_ts_default()\n return not old_col.has_same_default(new_col)\n\n def _update_col_attrs_changes(self, new_col, old_col):\n if (\n new_col.column_type != old_col.column_type\n or new_col.length != old_col.length\n ):\n self.add_alter_type(ColAlterType.CHANGE_COL_DATA_TYPE)\n if (\n self._is_col_default_change(old_col, new_col)\n and ColAlterType.CHANGE_COL_DATA_TYPE not in self._alter_types\n ):\n self.add_alter_type(ColAlterType.CHANGE_COL_DEFAULT_VAL)\n if (\n self._is_null_change(old_col, new_col)\n and ColAlterType.CHANGE_COL_DATA_TYPE not in self._alter_types\n ):\n self.add_alter_type(ColAlterType.CHANGE_NULL)\n if (\n isinstance(new_col, EnumColumn)\n and isinstance(old_col, EnumColumn)\n and new_col.enum_list != old_col.enum_list\n ):\n self.add_alter_type(ColAlterType.CHANGE_ENUM)\n if (\n isinstance(new_col, SetColumn)\n and isinstance(old_col, SetColumn)\n and new_col.set_list != old_col.set_list\n ):\n self.add_alter_type(ColAlterType.CHANGE_SET)\n if new_col.charset != old_col.charset:\n self.add_alter_type(ColAlterType.CHANGE_COL_CHARSET)\n if new_col.collate != old_col.collate:\n self.add_alter_type(ColAlterType.CHANGE_COL_COLLATE)\n if new_col.comment != old_col.comment:\n self.add_alter_type(ColAlterType.CHANGE_COL_COMMENT)\n\n def _gen_idx_sql(self):\n \"\"\"\n Generate the index section for ALTER TABLE statement\n \"\"\"\n segments = []\n\n # Drop index\n for idx in self.left.indexes:\n if idx not in self.right.indexes:\n segments.append(\"DROP KEY `{}`\".format(escape(idx.name)))\n self.add_alter_type(IndexAlterType.DROP_INDEX)\n\n # Add index\n for idx in self.right.indexes:\n if idx not in self.left.indexes:\n segments.append(\"ADD {}\".format(idx.to_sql()))\n self.add_alter_type(IndexAlterType.ADD_INDEX)\n self._update_index_attrs_changes(idx.name)\n\n if self.left.primary_key and not self.right.primary_key:\n segments.append(\"DROP PRIMARY KEY\")\n self.add_alter_type(IndexAlterType.CHANGE_PK)\n elif (\n not self.left.primary_key.column_list and self.right.primary_key.column_list\n ):\n segments.append(\"ADD {}\".format(self.right.primary_key.to_sql()))\n self.add_alter_type(IndexAlterType.CHANGE_PK)\n elif self.left.primary_key != self.right.primary_key:\n segments.append(\"DROP PRIMARY KEY\")\n segments.append(\"ADD {}\".format(self.right.primary_key.to_sql()))\n self.add_alter_type(IndexAlterType.CHANGE_PK)\n\n return segments\n\n def _update_index_attrs_changes(self, idx_name):\n old_indexes = {idx.name: idx for idx in self.left.indexes}\n new_indexes = {idx.name: idx for idx in self.right.indexes}\n if not (idx_name in old_indexes and idx_name in new_indexes):\n return\n attrs = [\"key_block_size\", \"comment\", \"is_unique\", \"key_type\", \"using\"]\n for attr in attrs:\n if not is_equal(\n getattr(old_indexes[idx_name], attr),\n getattr(new_indexes[idx_name], attr),\n ):\n if attr == \"key_block_size\":\n self.add_alter_type(IndexAlterType.CHANGE_INDEX_KEY_BLOCK_SIZE)\n elif attr == \"comment\":\n self.add_alter_type(IndexAlterType.CHANGE_INDEX_COMMENT)\n elif attr == \"is_unique\":\n self.add_alter_type(IndexAlterType.CHANGE_UNIQUE_CONSTRAINT)\n elif attr == \"key_type\":\n self.add_alter_type(IndexAlterType.CHANGE_KEY_TYPE)\n elif attr == \"using\":\n self.add_alter_type(IndexAlterType.CHANGE_INDEX_TYPE)\n\n def _gen_tbl_attr_sql(self):\n \"\"\"\n Generate the table attribute section for ALTER TABLE statement\n \"\"\"\n segments = []\n\n for attr in self.attrs_to_check:\n tbl_option_old = getattr(self.left, attr)\n tbl_option_new = getattr(self.right, attr)\n if not is_equal(tbl_option_old, tbl_option_new):\n # when tbl_option_new is None, do \"alter table xxx attr=None\" won't work\n if attr == \"comment\" and tbl_option_new is None:\n segments.append(\"{}={}\".format(attr, \"''\"))\n elif attr == \"row_format\" and tbl_option_new is None:\n segments.append(\"{}={}\".format(attr, \"default\"))\n else:\n segments.append(\"{}={}\".format(attr, tbl_option_new))\n\n # populate alter types data\n if attr == \"row_format\":\n self.add_alter_type(TableAlterType.CHANGE_ROW_FORMAT)\n elif attr == \"key_block_size\":\n self.add_alter_type(TableAlterType.CHANGE_TABLE_KEY_BLOCK_SIZE)\n elif attr == \"charset\":\n self.add_alter_type(TableAlterType.CHANGE_TABLE_CHARSET)\n elif attr == \"collate\":\n self.add_alter_type(TableAlterType.CHANGE_TABLE_COLLATE)\n elif attr == \"comment\":\n self.add_alter_type(TableAlterType.CHANGE_TABLE_COMMENT)\n elif attr == \"engine\":\n self.add_alter_type(TableAlterType.CHANGE_ENGINE)\n\n # we don't want to alter auto_increment value in db, just record the alter type\n if not is_equal(self.left.auto_increment, self.right.auto_increment):\n self.add_alter_type(TableAlterType.CHANGE_AUTO_INC_VAL)\n return segments\n\n def to_sql(self):\n \"\"\"\n Generate an ALTER TABLE statement that can bring the schema from left to\n right\n \"\"\"\n segments = []\n\n segments.extend(self._gen_col_sql())\n segments.extend(self._gen_idx_sql())\n segments.extend(self._gen_tbl_attr_sql())\n if segments:\n return \"ALTER TABLE `{}` {}\".format(\n escape(self.right.name), \", \".join(segments)\n )\n\n\ndef get_type_conv_columns(old_obj, new_obj):\n \"\"\"\n Return a list of columns that involve type conversion when transit from left to\n right\n \"\"\"\n type_conv_cols = []\n\n current_cols = {c.name: c for c in old_obj.column_list}\n new_cols = {c.name: c for c in new_obj.column_list}\n\n # find columns that will involve type conversions\n for name, old_col in current_cols.items():\n new_col = new_cols.get(name)\n\n # this column isn't in the new schema, so it\n # doesn't matter\n if new_col is None:\n continue\n\n # Type changes are considered as type conversion\n if new_col.column_type != old_col.column_type:\n type_conv_cols.append(old_col)\n else:\n # Length change also considered as type conversion\n if new_col.length != old_col.length:\n type_conv_cols.append(old_col)\n return type_conv_cols\n\n\ndef need_default_ts_bootstrap(old_obj, new_obj):\n \"\"\"\n Check when going from old schema to new, whether bootstraping column using\n CURRENT_TIMESTAMP is involved. This is normally dangerous thing to do out of\n replication and will be disallowed by default from OSC perspective\n \"\"\"\n current_cols = {c.name: c for c in old_obj.column_list}\n new_cols = {c.name: c for c in new_obj.column_list}\n\n # find columns that will involve type conversions\n for name, new_col in new_cols.items():\n old_col = current_cols.get(name)\n\n # This check only applies to column types that support default ts value\n if new_col.column_type not in [\"TIMESTAMP\", \"DATE\", \"DATETIME\"]:\n continue\n if new_col.column_type == \"TIMESTAMP\":\n new_col.explicit_ts_default()\n\n # Nothing to worry if a vulnerable column type doesn't use current time\n # as default\n if str(new_col.column_type) == \"TIMESTAMP\":\n # Cases for TIMESTAMP type\n if (\n str(new_col.default).upper() != \"CURRENT_TIMESTAMP\"\n and str(new_col.on_update_current_timestamp).upper()\n != \"CURRENT_TIMESTAMP\"\n ):\n continue\n else:\n # Cases for DATE and DATETIME type\n if str(new_col.default).upper() != \"CURRENT_TIMESTAMP\":\n continue\n\n # Adding timestamp column with defaults is considered unsafe\n # out of replication bootstraping\n if not old_col:\n return True\n\n # At this point we know this column in new schema need default value setting\n # to curernt ts. We will need to further confirm if old schema does the same\n # or not. If not, this will be consider as dangerous for replication\n if (\n str(new_col.default).upper() == \"CURRENT_TIMESTAMP\"\n and str(old_col.default).upper() != \"CURRENT_TIMESTAMP\"\n ):\n return True\n\n if (\n str(new_col.on_update_current_timestamp).upper() == \"CURRENT_TIMESTAMP\"\n and str(old_col.on_update_current_timestamp).upper() != \"CURRENT_TIMESTAMP\"\n ):\n return True\n\n return False\n","sub_path":"core/lib/sqlparse/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":20765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"590397872","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nfrom setuptools import setup\n\nimport sys\nif sys.version_info < (3, 6):\n raise RuntimeError(\"glooey requires python3.6 or better.\")\n\nimport re\nwith open('glooey/__init__.py') as file:\n version_pattern = re.compile(\"__version__ = '(.*)'\")\n version = version_pattern.search(file.read()).group(1)\n\nwith open('README.rst') as file:\n readme = file.read()\n\nsetup(\n name='glooey',\n version=version,\n author='Kale Kundert',\n author_email='kale@thekunderts.net',\n description='An object-oriented GUI library for pyglet.',\n long_description=readme,\n url='https://github.com/kxgames/glooey',\n packages=[\n 'glooey',\n 'glooey.drawing',\n 'glooey.themes',\n ],\n include_package_data=True,\n install_requires=[\n 'pyglet',\n 'more_itertools',\n 'vecrec', \n 'autoprop',\n 'debugtools',\n 'pyyaml',\n ],\n license='MIT',\n zip_safe=False,\n keywords=[\n 'glooey',\n 'pyglet',\n 'gui',\n 'library',\n ],\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Games/Entertainment',\n 'Topic :: Software Development :: User Interfaces',\n 'Topic :: Software Development :: Libraries',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"547168209","text":"# Copyright (c) 2018 WeFindX Foundation, CLG.\n# All Rights Reserved.\n\nimport os\nfrom setuptools import find_packages, setup\n\nLONG_DESCRIPTION = 'Integration of controllers to drive tools.'\n\n\nsetup(\n name='metadrive',\n version='1.4.35',\n description='Integration of controllers to drive tools.',\n long_description=LONG_DESCRIPTION,\n long_description_content_type='text/markdown',\n url='https://gitlab.com/wefindx/metadrive',\n author='Mindey',\n author_email='mindey@qq.com',\n license='Apache 2.0',\n packages = find_packages(exclude=['docs', 'tests*']),\n install_requires=[\n 'Deprecated==1.2.5',\n 'fusepy==3.0.1',\n # 'PyGithub==1.43.7',\n # 'pygithub3==0.5.1',\n 'aiofiles==0.4.0',\n 'apiage==0.1.4',\n 'asyncio==3.4.3',\n 'bs4==0.0.1',\n # 'celery==5.2.2',\n 'click==7.1.2',\n # 'feedparser==5.2.1',\n 'gitpython==2.1.11',\n 'gpgrecord==0.0.4',\n 'ipython==7.3.0',\n 'jinja2==2.11.3',\n 'metatype',\n 'metawiki',\n 'metaform',\n 'paramiko==2.10.1',\n 'pyautogui==0.9.42',\n 'pymongo==3.7.2',\n 'pysocks==1.6.8',\n 'pytest==4.4.1',\n 'python-dateutil==2.8.0',\n 'python3-xlib==0.15',\n 'requests==2.28.1',\n 'selenium==3.141.0',\n 'selenium-wire==2.1.1',\n 'slumber==0.7.1',\n 'Sphinx==2.0.1',\n 'tqdm==4.31.1',\n 'typology',\n 'yolk3k==0.9',\n 'xarray==0.12.1',\n 'urllib3==1.26.5' # not sure if necessary\n ],\n extras_require = {\n 'test': ['coverage', 'pytest', 'pytest-cov'],\n },\n zip_safe=False,\n entry_points = {\n 'console_scripts': [\n 'drive=metadrive.cli:connect'\n ],\n },\n package_data = {\n 'metadrive':\n []\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"283844765","text":"#!/usr/bin/env python3\nimport sys\nimport json\nimport time\n\ndef process(my_hash):\n created_at = my_hash.get('created_at', None)\n if not created_at: return None\n ctime = int(time.mktime(time.strptime(created_at,\"%a %b %d %H:%M:%S +0000 %Y\")))\n\n entities = my_hash.get('entities', None)\n if not entities: return None\n \n htags = entities.get('hashtags', None)\n if not htags: return None\n \n hset = set([hm['text'] for hm in htags])\n if len(hset) < 2: return None\n\n nodes = sorted(hash(a) for a in hset)\n return {'ctime':ctime, 'nodes':nodes}\n\nbinary = False if (len(sys.argv) > 1 and sys.argv[1] == '-a') else True\n\n\nfor line in sys.stdin:\n v = process(json.loads(line))\n if not v: continue\n if binary:\n #print('binary')\n pass\n\n else:\n print(v['ctime'], end=',')\n print(','.join(map(str,v['nodes'])))\n","sub_path":"bin/cleanit.py","file_name":"cleanit.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"114566864","text":"# -*- coding: utf-8 -*-\n# @Time : 2019-1-1510:11\n# @Author : Luocq\n# @Email : 1102858803@qq.com\n# @File : class_0115_def.py\n# @Software : PyCharm Community Edition\n\n#进阶提升题:\n'''\n1:利用字符串所学内置函数,完成如下题目,具体使用的函数已经提示过了~在课堂上,请去视频里面找答案!\n 请用自己目前所学实现指定字符串大写转小写,小写变大写,并且将字符串变为镜像字符串,\n 镜像的意思是:大写的’A’变为’Z’,’大写的‘B‘变成‘Y,小写的’’’b’变为’y 。\n 目前要求处理的示范字符串是: ”sdSdsfdAdsdsdfsfdsdASDSDFDSFa” 需要提供至少2种不同的解决方法。\n'''\n#法一:通过循环改变字符的大小,并对其进行镜像处理\ndef a(str):\n a = 'ABCDEFGHIJKMLMNOPQRSTUVWXYZ'\n b = 'abcdefghijkmlmnopqrstuvwxyz'\n new_str = ''\n for i in range(len(str)):\n if str[i].isupper():#判断字符是否是大写\n c = str[i].lower()#将大写字符转换成小写\n index = 26 - b.find(c)#找到此目标字符在小写的字符串b中的索引值,并找到其镜像字符的索引值\n new_str = new_str + b[index]#取出目标字符在字符串b中的镜像字符,并将其添加到新的字符串中\n elif str[i].islower():#判断字符是否是小写\n c = str[i].upper()#将小写字符转换成大写\n index = 26 - a.index(c)#找到此目标字符在大写的字符串a中的索引值,并找到其镜像字符的索引值\n new_str = new_str + a[index]#取出目标字符在字符串a中的镜像字符,并将其添加到新的字符串中\n return new_str#将获取到的结果返回\n#法二:通过swapcase()改变字符的大小,再通过循环对其进行镜像处理\ndef b(str):\n a = 'ABCDEFGHIJKMLMNOPQRSTUVWXYZ'\n b = 'abcdefghijkmlmnopqrstuvwxyz'\n new_str = ''\n str = str.swapcase() # 将字符串的大小写互相转换\n for i in str:\n if i.isupper(): # 判断字符是否是大写\n index = 26 - a.index(i) # 找到此目标字符在大写的字符串a中的索引值,并找到其镜像字符的索引值\n new_str = new_str + a[index] # 取出目标字符在字符串a中的镜像字符,并将其添加到新的字符串中\n elif i.islower(): # 判断字符是否是小写\n index = 26 - b.index(i) # 找到此目标字符在小写的字符串b中的索引值,并找到其镜像字符的索引值\n new_str = new_str + b[index] # 取出目标字符在字符串b中的镜像字符,并将其添加到新的字符串中\n return new_str #返回结果\n# 法三:通过ASCII编码\ndef c(str):\n new_str = \"\"\n for i in str:\n index = 187 - ord(i) # 找到此字符的ASCII编码,再找到对应的小/大写字母的镜像字母的ASCII编码\n i = chr(index) # 将找到的ASCII编码转换为字母\n new_str = new_str + i #将最后的结果添加到新的字符串中\n return new_str #返回结果\n# 法四:通过maketrans()对其进行大小转换和镜像处理利用\ndef d(str):\n new_str = \"\"\n for i in str:\n a = chr(187 -ord(i)) # 找到目标字母的镜像字母的ASCII编码,并转换为字母\n j = str.maketrans(i, a) # 生成对应的转换表\n i = chr(j[ord(i)]) #获取转换后的对应字母\n new_str = new_str + i #将最后的结果添加到新的字符串中\n return new_str #返回结果\nstr = \"sdSdsfdAdsdsdfsfdsdASDSDFDSFa\"\nprint(a(str))\nprint(b(str))\nprint(c(str))\nprint(d(str))\n\n'''\n2:搜索引擎中会对用户输入的数据进行处理,第一步就是词法分析,分离字符串中的数字、中文、拼音、符号。\n 比如这个字符串: 我的是名字是lemon,今年5岁。\n 语法分析后得到结果如下:\n 数字:5\n 中文:我的名字是、今年、岁\n 拼音:lemon\n 符号:,。\n 请编写程序实现该词法分析功能。\n'''\nimport re\ndef morpheme_analysis():\n str = input(\"请输入数据:\")\n sz_num = re.findall(r'(\\d+)', str)#正则表达式提取数字\n\n regex = re.compile(\"[\\u4e00-\\u9fa5]+\")#将字符串转为中文的编码格式\n ch_num = regex.findall(str) #正则表达式提取中文\n\n py_num = re.findall(r'[A-Za-z]+', str) #正则表达式提取字母\n\n #正则表达式提取符号\n zf_num = re.findall(r'[\\,\\.\\/\\;\\:\\?\\>\\<\\\"\\'\\[\\]\\{\\}\\-\\_\\=\\+\\|\\\\\\(\\)\\*\\&\\^\\%\\$\\#\\@\\!\\~\\`\\,\\。\\、\\?\\》\\《\\:\\;\\“\\”\\‘\\’\\{\\}\\【\\】\\|\\、\\+\\=\\—\\—\\-\\(\\)\\*\\&\\……\\%\\¥\\#\\@\\!\\~\\·\\ ]+', str)\n\n print('''\n 语法分析后得到结果如下:\n 数字:{}\n 中文:{}\n 拼音:{}\n 符号:{}\n '''.format(sz_num, ch_num, py_num, zf_num)) # 返回结果\nmorpheme_analysis()\n\n##新手练习题:\n#1、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5\ndef object_len(a):\n if len(a) > 5:#判断传入对象的长度是否大于5\n print(\"%s的长度大于5\"%a) #返回判断的结果\n elif len(a) < 5:#判断传入对象的长度是否小于5\n print(\"%s的长度小于5\"%a)#返回判断的结果\n else:#判断传入对象的长度是否等于5\n print(\"%s的长度等于5\"%a)#返回判断的结果\nobject_len(\"sdfrvdea\")\n\n#2、写函数,检查传入列表的长度,如果大于2,那么仅仅保留前两个长度的内容,并将新内容返回\ndef check_len(list):\n if len(list)>2:#判断列表长度是否大于2\n list = list[0:2]#切片获取前两个长度\n return list#返回新的列表\nlist = [1,2,3,4,5,6,7]\nprint(check_len(list))\n\n#3、定义一个函数,传入一个字典和字符串,判断字符串是否为字典中的值,如果字符串不在字典中,则添加到字典中,并返回新的字典。\ndef add_str(a,dict):\n if a not in dict:#判断字符串是否存在与字典中,不存在继续下一步\n dict[a] = a#将字符串添加到字典中,key,value的值相同\n return dict#返回最后的字典\ndict = {}\nprint(add_str(\"abc\",dict))\n\n'''\n4、一个足球队在寻找年龄在x岁到y岁的小女孩(包括x岁和y岁)加入。\n编写一个程序,询问用户的性别(m表示男性,f表示女性)和年龄,\n然后显示一条消息指出这个人是否可以加入球队,询问k次后,输出满足条件的总人数。\n'''\ndef select_girl(x,y,k):\n count = 1\n sum_f = 0\n while count <= k:\n sex = input(\"请输入小孩的性别(f为男,m为女):\")#获取输入的小孩性别\n if sex == \"m\" or sex == \"女\":#判断输入的性别是否为女\n while True:\n age = input(\"请输入小孩的年龄:\")#获取输入的小孩年龄\n if age.isdigit():#判断输入的年龄是否为数字\n age = int(age)#将输入的字符串转为int类型\n if age >= x and age <= y:#判断输入的年龄是否符合要求,在x~y之间\n sum_f = sum_f + 1#满足条件的人数+1\n print(\"此小孩符合要求,可以加入球队!\")\n break#满足条件,退出循环\n else:\n print(\"此小孩不符合要求,不可以加入球队!\")\n elif sex == \"f\" or sex == \"男\":\n print(\"此小孩不符合要求,不可以加入球队!\")\n else:\n print(\"请输入小孩的性别,如:男(或f),女(或m)。\")\n count = count + 1\n print(\"询问了{}个小孩,有{}个小孩可以加入\".format(k,sum_f))#返回最后的结果\nselect_girl(10,12,10)","sub_path":"week_3/task_function/python14_chaoqun_class_0115_def_4.py","file_name":"python14_chaoqun_class_0115_def_4.py","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"55986435","text":"import json\n\nfrom graphql import (\n graphql, GraphQLSchema, GraphQLObjectType, GraphQLField, GraphQLString, GraphQLList, format_error\n)\n\nTestObject = GraphQLObjectType(\n name=\"TestObject\",\n fields={\n \"string\": GraphQLField(\n GraphQLString,\n resolve=lambda obj, info: obj['string']\n )\n }\n)\n\nschema = GraphQLSchema(\n query=GraphQLObjectType(\n name='Query',\n fields={\n 'string': GraphQLField(\n GraphQLString,\n resolve=lambda obj, info: 'Hello World!'\n ),\n 'listOfStrings': GraphQLField(\n GraphQLList(GraphQLString),\n resolve=lambda obj, info: [\"Hello World!\"] * 100\n ),\n 'listOfObjects': GraphQLField(\n GraphQLList(TestObject),\n resolve=lambda obj, info: [ { \"string\": \"Hello World!\" } ] * 100\n ),\n }\n )\n)\n\nasync def app(scope, receive, send):\n if scope['type'] == \"http\" and scope['path'] == '/graphql/' and scope[\"method\"] == \"POST\":\n request = await receive()\n\n data = json.loads(request['body'].decode())\n\n try:\n query = data[\"query\"]\n variables = data.get(\"variables\")\n operation_name = data.get(\"operationName\")\n except KeyError:\n await send({\n \"type\": \"http.response.start\",\n \"status\": 400\n })\n await send({\n \"type\": \"http.response.body\",\n \"body\": \"No GraphQL query found in the request\".encode()\n })\n \n result = await graphql(\n schema, query, variable_values=variables, operation_name=operation_name\n )\n\n response_data = {\"data\": result.data}\n\n if result.errors:\n response_data[\"errors\"] = [format_error(err) for err in result.errors]\n\n await send({\n \"type\": \"http.response.start\",\n \"status\": 200\n })\n await send({\n \"type\": \"http.response.body\",\n \"body\": json.dumps(response_data).encode()\n })\n\n else:\n await send({\n \"type\": \"http.response.start\",\n \"status\": 404\n })\n await send({\n \"type\": \"http.response.body\",\n \"body\": \"URL not found\".encode()\n })","sub_path":"servers/asgi-graphql-core/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"240224962","text":"\"\"\" Where's That Word? functions. \"\"\"\n\n# The constant describing the valid directions. These should be used\n# in functions get_factor and check_guess.\nUP = 'up'\nDOWN = 'down'\nFORWARD = 'forward'\nBACKWARD = 'backward'\n\n# The constants describing the multiplicative factor for finding a\n# word in a particular direction. This should be used in get_factor.\nFORWARD_FACTOR = 1\nDOWN_FACTOR = 2\nBACKWARD_FACTOR = 3\nUP_FACTOR = 4\n\n# The constant describing the threshold for scoring. This should be\n# used in get_points.\nTHRESHOLD = 5\nBONUS = 12\n\n# The constants describing two players and the result of the\n# game. These should be used as return values in get_current_player\n# and get_winner.\nP1 = 'player one'\nP2 = 'player two'\nP1_WINS = 'player one wins'\nP2_WINS = 'player two wins'\nTIE = 'tie game'\n\n# The constant describing which puzzle to play. Replace the 'puzzle1.txt' with\n# any other puzzle file (e.g., 'puzzle2.txt') to play a different game.\nPUZZLE_FILE = 'puzzle1.txt'\n\n\n# Helper functions. Do not modify these, although you are welcome to\n# call them!\n\ndef get_column(puzzle: str, col_num: int) -> str:\n \"\"\"Return column col_num of puzzle.\n\n Precondition: 0 <= col_num < number of columns in puzzle\n\n >>> get_column('abcd\\nefgh\\nijkl\\n', 1)\n 'bfj'\n \"\"\"\n\n puzzle_list = puzzle.strip().split('\\n')\n column = ''\n for row in puzzle_list:\n column += row[col_num]\n\n return column\n\n\ndef get_row_length(puzzle: str) -> int:\n \"\"\"Return the length of a row in puzzle.\n\n >>> get_row_length('abcd\\nefgh\\nijkl\\n')\n 4\n \"\"\"\n\n return len(puzzle.split('\\n')[0])\n\n\ndef contains(text1: str, text2: str) -> bool:\n \"\"\"Return whether text2 appears anywhere in text1.\n\n >>> contains('abc', 'bc')\n True\n >>> contains('abc', 'cb')\n False\n \"\"\"\n\n return text2 in text1\n\n\n# Implement the required functions below.\n\ndef get_current_player(player_one_turn: bool) -> str:\n \"\"\"Return 'player one' iff player_one_turn is True; otherwise, return\n 'player two'.\n\n >>> get_current_player(True)\n 'player one'\n >>> get_current_player(False)\n 'player two'\n \"\"\"\n\n # Complete this function.\n\n\n","sub_path":"puzzle_functions_real.py","file_name":"puzzle_functions_real.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"55129665","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models, _\nfrom odoo.addons import decimal_precision as dp\nfrom odoo.exceptions import UserError, ValidationError\nfrom odoo.tools import float_utils, float_compare \nfrom datetime import datetime, timedelta, date\n\nclass StockMoveLine(models.Model):\n _inherit = \"stock.move.line\"\n\n def write(self, vals):\n \"\"\" Through the interface, we allow users to change the charateristics of a move line. If a\n quantity has been reserved for this move line, we impact the reservation directly to free\n the old quants and allocate the new ones.\n \"\"\"\n res = super(StockMoveLine, self).write(vals)\n\n #Se llena fecha asignada si corresponde a una fecha asignada en un \"Ajuste de inventario\"\n for move in self: \n sil_obj = self.env['stock.inventory.line'].sudo().search([('inventory_id','=',move.move_id.inventory_id.id),('product_id','=',move.product_id.id),('prod_lot_id','=',move.lot_id.id)],limit=1,order='id desc')\n if sil_obj:\n if sil_obj.x_studio_fecha_asignacin:\n self._cr.execute(\"\"\"\n UPDATE \n stock_move_line \n SET \n x_studio_fecha_asignacin ='%s' \n WHERE\n product_id = %s\n and lot_id = %s\n \"\"\" % (\n (datetime.strptime(fields.Datetime.to_string(sil_obj.x_studio_fecha_asignacin), '%Y-%m-%d %H:%M:%S')+ timedelta(hours=4)).strftime('%Y-%m-%d %H:%M:%S'),\n move.product_id.id,\n move.lot_id.id\n ) )\n\n return res","sub_path":"as_latproject_webservice/models/as_stock.py","file_name":"as_stock.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"348478093","text":"import torch\nimport torch.nn as nn\n\n\nclass _DCR_block(nn.Module):\n def __init__(self, channel_in):\n super(_DCR_block, self).__init__()\n\n self.conv_1 = nn.Conv2d(in_channels=channel_in, out_channels=int(channel_in/2.), kernel_size=3, stride=1, padding=1)\n self.relu1 = nn.PReLU()\n self.conv_2 = nn.Conv2d(in_channels=int(channel_in*3/2.), out_channels=int(channel_in/2.), kernel_size=3, stride=1, padding=1)\n self.relu2 = nn.PReLU()\n self.conv_3 = nn.Conv2d(in_channels=channel_in*2, out_channels=channel_in, kernel_size=3, stride=1, padding=1)\n self.relu3 = nn.PReLU()\n\n def forward(self, x):\n residual = x\n\n out = self.relu1(self.conv_1(x))\n\n conc = torch.cat([x, out], 1)\n\n out = self.relu2(self.conv_2(conc))\n\n conc = torch.cat([conc, out], 1)\n\n out = self.relu3(self.conv_3(conc))\n\n out = torch.add(out, residual)\n\n return out\n\n\nclass _down(nn.Module):\n def __init__(self, channel_in):\n super(_down, self).__init__()\n\n self.relu = nn.PReLU()\n self.maxpool = nn.MaxPool2d(2)\n self.conv = nn.Conv2d(in_channels=channel_in, out_channels=2*channel_in, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n out = self.maxpool(x)\n\n out = self.relu(self.conv(out))\n\n return out\n\n\nclass _up(nn.Module):\n def __init__(self, channel_in):\n super(_up, self).__init__()\n\n self.relu = nn.PReLU()\n self.subpixel = nn.PixelShuffle(2)\n self.conv = nn.Conv2d(in_channels=channel_in, out_channels=channel_in, kernel_size=1, stride=1, padding=0)\n\n def forward(self, x):\n out = self.relu(self.conv(x))\n\n out = self.subpixel(out)\n\n return out\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n\n self.conv_i = nn.Conv2d(in_channels=1, out_channels=128, kernel_size=1, stride=1, padding=0)\n self.relu1 = nn.PReLU()\n self.DCR_block11 = self.make_layer(_DCR_block, 128)\n self.DCR_block12 = self.make_layer(_DCR_block, 128)\n self.down1 = self.make_layer(_down, 128)\n self.DCR_block21 = self.make_layer(_DCR_block, 256)\n self.DCR_block22 = self.make_layer(_DCR_block, 256)\n self.down2 = self.make_layer(_down, 256)\n self.DCR_block31 = self.make_layer(_DCR_block, 512)\n self.DCR_block32 = self.make_layer(_DCR_block, 512)\n self.down3 = self.make_layer(_down, 512)\n self.DCR_block41 = self.make_layer(_DCR_block, 1024)\n self.DCR_block42 = self.make_layer(_DCR_block, 1024)\n self.up3 = self.make_layer(_up, 2048)\n self.DCR_block33 = self.make_layer(_DCR_block, 1024)\n self.DCR_block34 = self.make_layer(_DCR_block, 1024)\n self.up2 = self.make_layer(_up, 1024)\n self.DCR_block23 = self.make_layer(_DCR_block, 512)\n self.DCR_block24 = self.make_layer(_DCR_block, 512)\n self.up1 = self.make_layer(_up, 512)\n self.DCR_block13 = self.make_layer(_DCR_block, 256)\n self.DCR_block14 = self.make_layer(_DCR_block, 256)\n self.conv_f = nn.Conv2d(in_channels=256, out_channels=1, kernel_size=1, stride=1, padding=0)\n self.relu2 = nn.PReLU()\n\n def make_layer(self, block, channel_in):\n layers = []\n layers.append(block(channel_in))\n return nn.Sequential(*layers)\n\n def forward(self, x):\n residual = x\n\n out = self.relu1(self.conv_i(x))\n\n out = self.DCR_block11(out)\n\n conc1 = self.DCR_block12(out)\n\n out = self.down1(conc1)\n\n out = self.DCR_block21(out)\n\n conc2 = self.DCR_block22(out)\n\n out = self.down2(conc2)\n\n out = self.DCR_block31(out)\n\n conc3 = self.DCR_block32(out)\n\n conc4 = self.down3(conc3)\n\n out = self.DCR_block41(conc4)\n\n out = self.DCR_block42(out)\n\n out = torch.cat([conc4, out], 1)\n\n out = self.up3(out)\n\n out = torch.cat([conc3, out], 1)\n\n out = self.DCR_block33(out)\n\n out = self.DCR_block34(out)\n\n out = self.up2(out)\n\n out = torch.cat([conc2, out], 1)\n\n out = self.DCR_block23(out)\n\n out = self.DCR_block24(out)\n\n out = self.up1(out)\n\n out = torch.cat([conc1, out], 1)\n\n out = self.DCR_block13(out)\n\n out = self.DCR_block14(out)\n\n out = self.relu2(self.conv_f(out))\n\n out = torch.add(residual, out)\n\n return out\n","sub_path":"DHDN_gray.py","file_name":"DHDN_gray.py","file_ext":"py","file_size_in_byte":4452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"6257450","text":"\"\"\" Compiled: 2020-09-18 10:38:53 \"\"\"\n\n#__src_file__ = \"extensions/PortfolioTrading/etc/FTradeProgramColumns.py\"\n\"\"\"-------------------------------------------------------------------------------------------------\nMODULE\n FTradeProgramColumns\n\n (c) Copyright 2014 SunGard FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n\n-------------------------------------------------------------------------------------------------\"\"\"\n\nimport acm\nimport FSheetUtils\nfrom FIntegratedWorkbench import GetView, GetHandlerByName\nfrom FParameterSettings import ParameterSettingsCreator\nfrom FTradeProgramAction import Action\nfrom FTradeProgramUtils import Logger\nfrom FIntegratedWorkbenchMenuItem import IntegratedWorkbenchMenuItem\nfrom FTradeProgramUtils import ColumnWorkflowMenuItem\nimport FTradeProgram\n\n\nSETTINGS = ParameterSettingsCreator.FromRootParameter('TradeProgramSettings')\n\nclass ExtensionInvokationInfo(object):\n\n __slots__ = ['frame']\n\n def __init__(self, frame):\n self.frame = frame\n\n def ExtensionObject(self):\n return self.frame\n\ndef GetTradeProgramActionMenuItem(app, column):\n for action in Action.GetActions():\n try:\n menuItem = action(app)\n if menuItem.ActionName() == str(column.ColumnId()) and menuItem.EnabledFunction():\n return menuItem\n except AttributeError:\n continue\n\ndef InvokeTradeProgramActionMenuItem(app, column):\n try:\n menuItem = GetTradeProgramActionMenuItem(app, column)\n if menuItem:\n eii = ExtensionInvokationInfo(app)\n menuItem.Invoke(eii)\n except Exception as e:\n Logger().debug(e)\n\ndef OnInputChanged(_row, column, _calcVal, _input, _event):\n if SETTINGS.QuickMode():\n for app in acm.ApplicationList():\n try:\n view = GetView(app)\n if view.ClassName() == 'TradeProgramView':\n InvokeTradeProgramActionMenuItem(app, column)\n return\n except AttributeError:\n continue\n\ndef TargetColumnIsDenominatedValue(value):\n return value.IsKindOf(acm.FDenominatedValue)\n\ndef GetExtensionAttribute(targetColumnId, settingsName):\n if not targetColumnId:\n settings = ParameterSettingsCreator.FromRootParameter(settingsName)\n targetColumnId = settings.TargetColumnId() if hasattr(settings, 'TargetColumnId') else None\n creators = acm.GetColumnCreators(targetColumnId, acm.GetDefaultContext())\n return creators.At(0).Columns().First().ExtensionAttribute()\n \ndef IsActionColumn(frame, column):\n for action in Action.GetActions():\n tradeProgramMenuAction = action(frame)\n try:\n hasActionName = str(column.ColumnName()) == tradeProgramMenuAction.ActionName()\n if hasActionName:\n return hasActionName\n except Exception:\n continue\n \ndef ClearInputColumns(sheet, frame):\n rowIter = sheet.RowTreeIterator(True)\n while rowIter.NextUsingDepthFirst():\n columnIter = sheet.GridColumnIterator().First()\n while columnIter:\n column = columnIter.GridColumn()\n if IsActionColumn(frame, column):\n try:\n cell = sheet.GetCell(rowIter, columnIter)\n evaluator = cell.Evaluator()\n if evaluator and evaluator.HasSimulatedInput():\n evaluator.RemoveSimulation()\n except AttributeError as e:\n Logger().error(e, exc_info=True)\n columnIter = columnIter.Next()\n\ndef CreateInputColumnCP(eii):\n return CreateInputColumnMenuItem(eii, 'Change Percent')\n\ndef CreateInputColumnCV(eii):\n return CreateInputColumnMenuItem(eii, 'Change Value')\n\ndef CreateInputColumnTP(eii):\n return CreateTargetPercentColumnMenuItem(eii, 'Target Percent')\n\ndef CreateInputColumnTV(eii):\n return CreateInputColumnMenuItem(eii, 'Target Value')\n\nclass CreateInputColumnMenuItem(IntegratedWorkbenchMenuItem):\n\n def __init__(self, extObj, inputColumnId):\n super(CreateInputColumnMenuItem, self).__init__(extObj, view='TradeProgramView')\n self._sheet = extObj.ActiveSheet()\n self._inputColumnId = inputColumnId\n try:\n cell = self._sheet.Selection().SelectedCell()\n self._columnId = cell.Column().ColumnId().Text()\n except AttributeError:\n self._columnId = None\n\n def ApplicableOnNoWorkbench(self):\n return False\n\n def EnabledFunction(self):\n return bool(self._columnId)\n \n def ColumnParams(self):\n return {acm.FSymbol('TargetColumnParameters'): self._columnId}\n \n def NewColumn(self):\n columnParams = self.ColumnParams()\n columnConfig = acm.Sheet().Column().CreatorConfigurationFromColumnParameterDefinitionNamesAndValues(columnParams)\n \n columnCreator = FSheetUtils.ColumnCreator(self._inputColumnId)\n return columnCreator.Template().CreateCreator(columnConfig, None)\n \n def InvokeAsynch(self, _eii):\n columnCreator = self.NewColumn()\n targetColumnCretor = FSheetUtils.ColumnCreatorInSheet(self._sheet, self._columnId)\n self._sheet.ColumnCreators().InsertAfter(targetColumnCretor, columnCreator)\n\n def Invoke(self, eii):\n self._frame.Shell().CallAsynch(self.InvokeAsynch, eii)\n\nclass CreateTargetPercentColumnMenuItem(CreateInputColumnMenuItem):\n \n def ColumnParams(self):\n columnParams = super(CreateTargetPercentColumnMenuItem, self).ColumnParams()\n columnParams[acm.FSymbol('TargetPercentRelativeTo')] = 'Top'\n return columnParams\n\ndef TradeProgramStateChart():\n #Passing query to ensure reevaluation in ADFL\n cls = FTradeProgram.TradeProgramWorkflowClass()\n return acm.FStateChart[cls.StateChart()]\n\ndef showApproveBreachesButton(eii):\n return True\n\ndef onApproveBreachesStartButton(eii):\n button = eii.Parameter('ClickedButton')\n if button:\n order = button.RowObject()\n event = eii.MenuExtension().GetString('HandleEvent')\n if order and order.IsKindOf(acm.FOrderProgram):\n query = \"optionalId={0}\".format(order.OrderProgramId())\n dealPackage = acm.FDealPackage.Select01(query, None)\n tradeProgramClass = FTradeProgram.TradeProgramWorkflowClass()\n stateChart = acm.FStateChart[tradeProgramClass.StateChart()]\n if dealPackage and stateChart:\n try:\n businessProcess = acm.BusinessProcess.FindBySubjectAndStateChart(dealPackage, stateChart)[0]\n workflow = ColumnWorkflowMenuItem(eii.ExtensionObject(), tradeProgramClass, event, businessProcess)\n workflow.Invoke(eii.ExtensionObject())\n except (TypeError, IndexError):\n pass\n","sub_path":"Extensions/Portfolio Trading/FPythonCode/FTradeProgramColumns.py","file_name":"FTradeProgramColumns.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"27370325","text":"\"\"\"\nБез дубликатов\nНа вход программе подается натуральное число nn, а затем nn строк. Напишите программу, которая выводит только уникальные строки, в том же порядке, в котором они были введены.\n\nФормат входных данных\nНа вход программе подаются натуральное число nn, а затем nn строк, каждая на отдельной строке.\n\nФормат выходных данных\nПрограмма должна вывести текст в соответствии с условием задачи.\n\nПримечание. Считайте, что все строки состоят из строчных символов.\n\nSample Input:\n\n5\nfirst\nsecond\nfirst\nthird\nsecond\nSample Output:\n\nfirst\nsecond\nthird\n\"\"\"\n# -------------------------------------------------------------------------------------------------\n\n# 1)вариант\nnum = int(input())\ndat = []\nfor i in range(num):\n a = input()\n dat.append(a)\ny = sorted(set(dat), key=lambda d: dat.index(d))\nfor i in range(len(y)):\n print(y[i])\n# -------------------------------------------------------------------------------------------------\n\n# 2)вариант\ndat = []\nfor _ in range(int(input())):\n el = input()\n if el not in dat:\n dat.append(el)\n print(el)","sub_path":"Python/list/no_duplicates.py","file_name":"no_duplicates.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"135944849","text":"import os\nimport discord\nimport asyncio\nimport discord_token\nfrom random import randint as rnd\n\nclient = discord.Client()\nkey = discord_token.get_token() \n\nclass Char:\n def __init__(self, player_id, const, intel, dex, force, charisma, faith):\n self.char_id = player_id\n self.char_stats = {\n \"constitution\": int(const),\n \"intellect\": int(intel),\n \"dexterity\": int(dex),\n \"force\": int(force),\n \"charisma\": int(charisma),\n \"faith\": int(faith)\n }\n self.hp = 50 + self.char_stats[\"constitution\"] * 50\n self.mp = 30 + self.char_stats[\"intellect\"] * 40\n\n def set_life_mana(self, h, m):\n self.hp = int(h)\n self.mp = int(m)\n\n def damage(self, value):\n self.hp -= value\n \n def skill(self, value):\n self.mp -= value\n\ndef save_profile(player_id, player_char, hp, mp):\n try:\n file = open(f\"char/{str(player_id)}\", \"r+\")\n for x, y in player_char.items():\n file.write(str(y))\n file.write(f\"-{hp}-{mp}\")\n file.close()\n except FileNotFoundError:\n file = open(f\"char/{str(player_id)}\", \"w+\")\n for x, y in player_char.items():\n file.write(str(y))\n file.write(f\"-{hp}-{mp}\")\n file.close()\n\ndef load_profile(player_char):\n if (os.path.exists(f\"char/{player_char}\")):\n file = open(f\"char/{str(player_char)}\", \"r\")\n char = file.read().split(\"-\")\n result = []\n for stats in char[0]:\n result.append(stats)\n result.append(char[1])\n result.append(char[2])\n return result\n\ndef show_char(player_id):\n stats = load_profile(str(player_id))\n my_char = Char(\n str(player_id),\n stats[0], stats[1], stats[2],\n stats[3], stats[4], stats[5])\n my_char.set_life_mana(stats[6], stats[7])\n show_char_01 = f\"Const:{stats[0]}, Int:{stats[1]}, Dex:{stats[2]}, Force:{stats[3]}, Char:{stats[4]}, Faith:{stats[5]}\"\n show_char_02 = f\"HP -> {stats[6]} MP -> {stats[7]}\"\n return show_char_01, show_char_02\n\ndef roll_dice(command):\n dice = command.split(\"d\")[1]\n sum_dice = False \n for x in dice:\n if x == \"+\":\n dice = dice.split(\"+\")\n sum_dice = True\n if not sum_dice:\n num = rnd(1,int(dice))\n return f\"DICE: {num}\"\n else:\n num = rnd(1,int(dice[0]))\n sum_num = int(dice[1])\n result = num + sum_num\n return f\"DICE: {num} + {sum_num} = {result}\"\n\n@client.event\nasync def on_ready():\n print(\"RPG-BOT\")\n print(\"DISCORD V.\",discord.__version__)\n print(\"NAME:\",client.user.name)\n print(\"ID\", client.user.id)\n \n@client.event\nasync def on_message(message):\n print(message.author.name,\": \",message.content)\n if message.content.lower().startswith(\"?help\"):\n await message.channel.send(\"-\")\n \n if message.content.lower().startswith(\"?coin\"):\n choice = rnd(0,1)\n if choice == 1:\n await discord.Message.add_reaction(message, \"😃\")\n else:\n await discord.Message.add_reaction(message, \"👑\")\n \n if message.content.lower().startswith(\"?d\"):\n dice = roll_dice(str(message.content))\n await message.channel.send(dice)\n\n if message.content.lower().startswith(\"?new_char:\"):\n try:\n stats = str(message.content).split(\":\")[1].split(\",\")\n my_char = Char(\n str(message.author.name),\n stats[0], stats[1], stats[2],\n stats[3], stats[4], stats[5])\n save_profile(my_char.char_id, my_char.char_stats, my_char.hp, my_char.mp)\n x, y = show_char(str(message.author.name))\n \n await message.channel.send(\"Successfully created\")\n await message.channel.send(x)\n await message.channel.send(y)\n\n except:\n await message.channel.send(\"ERROR, try again\")\n\n if message.content.lower().startswith(\"?char\"):\n x, y = show_char(str(message.author.name))\n await message.channel.send(x)\n await message.channel.send(y) \n\n\n if message.content.lower().startswith(\"?atk:\"):\n stats = load_profile(str(message.author.name))\n my_char = Char(\n str(message.author.name),\n stats[0], stats[1], stats[2],\n stats[3], stats[4], stats[5])\n my_char.set_life_mana(stats[6], stats[7])\n value = int(str(message.content).split(\":\")[1])\n my_char.damage(value)\n save_profile(my_char.char_id, my_char.char_stats, my_char.hp, my_char.mp)\n x, y = show_char(str(message.author.name))\n await message.channel.send(x)\n await message.channel.send(y)\n\n if message.content.lower().startswith(\"?skill:\"):\n stats = load_profile(str(message.author.name))\n my_char = Char(\n str(message.author.name),\n stats[0], stats[1], stats[2],\n stats[3], stats[4], stats[5])\n my_char.set_life_mana(stats[6], stats[7])\n value = int(str(message.content).split(\":\")[1])\n my_char.skill(value)\n save_profile(my_char.char_id, my_char.char_stats, my_char.hp, my_char.mp)\n x, y = show_char(str(message.author.name))\n await message.channel.send(x)\n await message.channel.send(y)\n\nclient.run(key)","sub_path":"rpg-bot.py","file_name":"rpg-bot.py","file_ext":"py","file_size_in_byte":5434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"408744408","text":"import time\n\nfrom pgdrive.constants import RENDER_MODE_ONSCREEN\n\n\nclass ForceFPS:\n UNLIMITED = \"UnlimitedFPS\"\n FORCED = \"ForceFPS\"\n\n def __init__(self, pg_world, start=False):\n fps = 1 / pg_world.world_config[\"physics_world_step_size\"]\n self.pg_world = pg_world\n self.init_fps = fps\n if start:\n self.state = self.FORCED\n self.fps = fps\n else:\n self.state = self.UNLIMITED\n self.fps = None\n\n @property\n def interval(self):\n return 1 / self.fps if self.fps is not None else None\n\n def tick(self):\n # print(\"Force fps, now: \", self.last)\n sim_interval = self.pg_world.taskMgr.globalClock.getDt()\n if self.interval and sim_interval < self.interval:\n time.sleep(self.interval - sim_interval)\n\n def toggle(self):\n if self.state == self.UNLIMITED:\n self.pg_world.taskMgr.add(self.force_fps_task, \"force_fps\")\n self.state = self.FORCED\n self.fps = self.init_fps\n elif self.state == self.FORCED:\n self.pg_world.taskMgr.remove(\"force_fps\")\n self.state = self.UNLIMITED\n self.fps = None\n\n def force_fps_task(self, task):\n self.tick()\n return task.cont\n\n @property\n def real_time_simulation(self):\n return self.state == self.FORCED and self.pg_world.mode == RENDER_MODE_ONSCREEN\n","sub_path":"pgdrive/world/force_fps.py","file_name":"force_fps.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"273328693","text":"from unittest import TestCase\nfrom mock import patch\nfrom ddt import ddt, data, unpack\nfrom common.auth0_connector import Auth0APIConnector\nimport app\n\n@ddt\nclass TestAuth0APIConnector(TestCase):\n def setUp(self):\n # Starting flask server\n self.app = app.app.test_client()\n @data(\n ('fake_token', 'fake_req_id')\n )\n @unpack\n @patch('common.auth0_connector.Auth0APIConnector._connect')\n def test_retrieve_access_token(self, auth_token, x_request_id, mock_connect):\n mock_connect.return_value = True\n return_value = Auth0APIConnector(auth_token, x_request_id).retrieve_access_token()\n assert return_value == True\n\n @data(\n ('fake_token', 'fake_req_id')\n )\n @unpack\n @patch('common.auth0_connector.Auth0APIConnector._connect')\n @patch('common.auth0_connector.Auth0APIConnector.retrieve_access_token')\n def test_retrieve_recipients(self, auth_token, x_request_id, mock_retrieval, mock_connect):\n mock_connect.return_value = True\n mock_retrieval.json.return_value = auth_token\n return_value = Auth0APIConnector(auth_token, x_request_id).retrieve_recipients('fake_site')\n assert return_value == True\n\n def test_create_payload(self):\n return_value = Auth0APIConnector.create_payload()\n assert \"client_secret\" in return_value\n","sub_path":"tests/test_auth0APIConnector.py","file_name":"test_auth0APIConnector.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"275024930","text":"import matplotlib.pyplot as plt # to implement plots\nimport csv # to read and process CSV files\n\nMonths = [] # x-axis 1 data\nSales = [] # y-axis 1 data\nExpenditure = [] # y-axis 2 data\n\n# open CSV file\nwith open('sales.csv') as csvDataFile:\n csvReader = csv.reader(csvDataFile)\n next(csvReader)# file handler\n\n for row in csvReader: # loop through file handler\n Months.append(row[1])\n Sales.append(row[2])\n Expenditure.append(row[3])\n\nSales_ = list(map(int, Sales)) # convert string list of cases to integers for plotting\nExpenditure_ = list(map(int, Expenditure))\nplt.plot(Months, Sales_, color=\"#444444\", linestyle=\"--\", label=\"Sales\",\n marker=\"X\") # plot the data with X as the marker for each point\nplt.plot(Months, Expenditure_, color=\"#5a7d9a\", label=\"Expenditure\",\n marker=\"+\") # plot the data with + as the marker for each point\n\nplt.title(\"2018\") # give a suitable title for the plot\nplt.legend() # displays legend on which line relates to which country\nplt.tight_layout() # auto adjust of plot for better viewing\nplt.show() # show the plot","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"512903399","text":"# fort2h5.py\n#\n# Read existing Fortran unformatted simulation data and write as hdf5.\n#\n#\n# Author: F. Gent (fred.gent.ncl@gmail.com).\n#\n\"\"\"\nContains the functions to read old Fortran binary simulation data and\nwrite snapshots in hdf5 (data/allprocs/VAR*.h5 files), video slices to\ndata/slices/uu1_xy.h5, etc. and averages to data/averages/xy.h5, etc\n\"\"\"\n\ndef var2h5(newdir, olddir, varfile_names, todatadir, fromdatadir,\n precision, lpersist, quiet, nghost, settings, param, grid,\n x, y, z, lshear, lremove_old_snapshots, indx,\n last_var=True, trimall=False\n ):\n\n \"\"\"\n Copy a simulation snapshot set written in Fortran binary to hdf5.\n\n call signature:\n\n var2h5(newdir, olddir, varfile_names, todatadir, fromdatadir,\n precision, lpersist, quiet, nghost, settings, param, grid,\n x, y, z, lshear, lremove_old_snapshots, indx\n )\n\n Keyword arguments:\n\n *newdir*:\n String path to simulation destination directory.\n\n *olddir*:\n String path to simulation destination directory.\n\n *varfile_names*:\n A list of names of the snapshot files to be written, e.g. VAR0.\n\n *todatadir*:\n Directory to which the data is stored.\n\n *fromdatadir*:\n Directory from which the data is collected.\n\n *precision*:\n Single 'f' or double 'd' precision for new data.\n\n *lpersist*:\n option to include persistent variables from snapshots.\n\n *quiet*\n Option not to print output.\n\n *nghost*:\n Number of ghost zones.\n\n *settings*\n simulation properties.\n\n *param*\n simulation Param object.\n\n *grid*\n simulation Grid object.\n\n *xyz*:\n xyz arrays of the domain with ghost zones.\n\n *lshear*:\n Flag for the shear.\n\n *lremove_old_snapshots*:\n If True the old snapshots will be deleted once the new snapshot has\n been saved.\n\n *indx*\n List of variable indices in the f-array.\n\n *last_var*\n If last_var copy and remove var.dat\n\n \"\"\"\n\n import os\n import numpy as np\n import h5py\n import glob\n from .. import read\n from .. import sim\n from . import write_h5_snapshot\n\n #move var.h5 out of the way, if it exists for reading binary\n if os.path.exists(todatadir+'/var.h5'):\n cmd='mv '+todatadir+'/var.h5 '+todatadir+'/var.bak'\n os.system(cmd)\n\n #proceed to copy each snapshot in varfile_names\n for file_name in varfile_names:\n #load Fortran binary snapshot\n print('saving '+file_name)\n os.chdir(olddir)\n var = read.var(file_name, datadir=fromdatadir, quiet=quiet,\n lpersist=lpersist, trimall=trimall\n )\n try:\n var.deltay\n lshear = True\n except:\n lshear = False\n\n if lpersist:\n persist = {}\n for key in read.record_types.keys():\n try:\n persist[key] = var.__getattribute__(key)[()]\n if (type(persist[key][0])==str):\n persist[key][0] = var.__getattribute__(key)[0].encode()\n except:\n continue\n else:\n persist = None\n #write data to h5\n os.chdir(newdir)\n write_h5_snapshot(var.f, file_name=file_name, datadir=todatadir,\n precision=precision, nghost=nghost,\n persist=persist,\n settings=settings, param=param, grid=grid,\n lghosts=True, indx=indx, t=var.t, x=x, y=y, z=z,\n lshear=lshear)\n if lremove_old_snapshots:\n os.chdir(olddir)\n cmd = \"rm -f \"+os.path.join(fromdatadir, 'proc*', file_name)\n os.system(cmd)\n os.chdir(olddir)\n var = read.var('var.dat', datadir=fromdatadir, quiet=quiet,\n lpersist=lpersist, trimall=trimall\n )\n if lpersist:\n persist = {}\n for key in read.record_types.keys():\n try:\n persist[key] = var.__getattribute__(key)[()]\n except:\n continue\n else:\n persist = None\n #write data to h5\n os.chdir(newdir)\n if last_var:\n write_h5_snapshot(var.f, file_name='var', datadir=todatadir,\n precision=precision, nghost=nghost,\n persist=persist,\n settings=settings, param=param, grid=grid,\n lghosts=True, indx=indx, t=var.t, x=x, y=y, z=z,\n lshear=lshear)\n if lremove_old_snapshots:\n os.chdir(olddir)\n cmd = \"rm -f \"+os.path.join(fromdatadir, 'proc*', 'var.dat')\n os.system(cmd)\n\ndef slices2h5(newdir, olddir, grid,\n todatadir='data/slices', fromdatadir='data',\n precision='d', quiet=True, lremove_old_slices=False):\n\n \"\"\"\n Copy a simulation set of video slices written in Fortran binary to hdf5.\n\n call signature:\n\n slices2h5(newdir, olddir, grid,\n todatadir='data/slices', fromdatadir='data',\n precision='d', quiet=True, lremove_old_slices=False)\n\n Keyword arguments:\n\n *newdir*:\n String path to simulation destination directory.\n\n *olddir*:\n String path to simulation destination directory.\n\n *grid*\n simulation Grid object.\n\n *todatadir*:\n Directory to which the data is stored.\n\n *fromdatadir*:\n Directory from which the data is collected.\n\n *precision*:\n Single 'f' or double 'd' precision for new data.\n\n *quiet*\n Option not to print output.\n\n *lremove_old_slices*:\n If True the old video slices will be deleted once the new slices have\n been saved.\n \"\"\"\n\n import os\n from .. import read\n from .. import sim\n from . import write_h5_slices\n\n #copy old video slices to new h5 sim\n os.chdir(olddir)\n vslice = read.slices()\n #identify the coordinates and positions of the slices\n coordinates = {}\n positions = {}\n readlines1 = open('data/slice_position.dat','r').readlines()\n readlines2 = open('data/proc0/slice_position.dat','r').readlines()\n lines1, lines2 = [],[]\n for line in readlines1:\n lines1.append(int(line.split(' ')[-1].split('\\n')[0]))\n \"\"\"In newer binary sims lines2 obtains 7 strings below, but older sims may\n only yield the integer coordinates, so lines2 is hardcoded. The current\n version of the Pencil Code has 7 potential slices, but earlier versions\n may not. If your sim does not conform to this arrangement edit/copy this\n module and set lines1 and lines2 manually from data/slice_position.dat and\n the extensions present in your slice_*.xy etc.\n \"\"\"\n #check simulation includes the slice keys in data/proc*/slice_position.dat\n try:\n int(int(readlines2[0].split(' ')[-1].split('\\n')[0]))\n lines2=['xy', 'xy2', 'xy3', 'xy4', 'xz', 'xz2', 'yz']\n except:\n for line in readlines2:\n lines2.append(line.split(' ')[-1].split('\\n')[0].lower())\n #check if number of slice options as expected\n try:\n len(lines1)==7\n except ValueError:\n print(\"ERROR: slice keys and positions must be set see lines 212...\")\n return -1\n for key, num in zip(lines2, lines1):\n if num > 0:\n if 'xy' in key:\n positions[key] = grid.z[num-1]\n if 'xz' in key:\n positions[key] = grid.y[num-1]\n if 'yz' in key:\n positions[key] = grid.x[num-1]\n coordinates[key] = num\n #write new slices in hdf5\n os.chdir(newdir)\n write_h5_slices(vslice, coordinates, positions, datadir=todatadir,\n precision=precision, quiet=quiet)\n if lremove_old_slices:\n os.chdir(olddir)\n cmd = \"rm -f \"+os.path.join(fromdatadir, 'proc*', 'slice_*')\n os.system(cmd)\n\ndef aver2h5(newdir, olddir,\n todatadir='data/averages', fromdatadir='data', l2D=True,\n precision='d', quiet=True, lremove_old_averages=False,\n laver2D=False):\n\n \"\"\"\n Copy a simulation set of video slices written in Fortran binary to hdf5.\n\n call signature:\n\n aver2h5(newdir, olddir,\n todatadir='data/slices', fromdatadir='data', l2D=True,\n precision='d', quiet=True, lremove_old_averages=False)\n\n Keyword arguments:\n\n *newdir*:\n String path to simulation destination directory.\n\n *olddir*:\n String path to simulation destination directory.\n\n *todatadir*:\n Directory to which the data is stored.\n\n *fromdatadir*:\n Directory from which the data is collected.\n\n *l2D*\n Option to include 2D averages if the file sizes are not too large\n\n *precision*:\n Single 'f' or double 'd' precision for new data.\n\n *quiet*\n Option not to print output.\n\n *lremove_old_averages*:\n If True the old averages data will be deleted once the new h5 data\n has been saved.\n\n *laver2D*\n If True apply to each plane_list 'y', 'z' and load each variable\n sequentially\n \"\"\"\n\n import os\n from .. import read\n from .. import sim\n from . import write_h5_averages\n\n #copy old 1D averages to new h5 sim\n if laver2D:\n os.chdir(olddir)\n if 'milltest' in olddir:\n millennium_bug=True\n else:\n millennium_bug=False\n for xl in ['y','z']: \n if os.path.exists(xl+'aver.in'):\n variables=[]\n file_id = open(xl+'aver.in')\n for line in file_id.readlines():\n variables.append(line.rstrip('\\n'))\n file_id.close()\n n_vars = len(variables)\n for iav in range(0,n_vars):\n print('writing',iav,variables[iav],'of',xl+'averages')\n os.chdir(olddir)\n av = read.aver(plane_list=xl, var_index=iav,\n millennium_bug=millennium_bug)\n os.chdir(newdir)\n for key in av.__dict__.keys():\n if not key in 't':\n write_h5_averages(av, file_name=key,\n datadir=todatadir,\n precision=precision,\n append=True,\n quiet=quiet)\n else: \n os.chdir(olddir)\n av = read.aver()\n os.chdir(newdir)\n for key in av.__dict__.keys():\n if not key in 't':\n write_h5_averages(av, file_name=key, datadir=todatadir,\n precision=precision, quiet=quiet)\n if lremove_old_averages:\n os.chdir(olddir)\n cmd = \"rm -f \"+os.path.join(fromdatadir, '*averages.dat')\n os.system(cmd)\n if l2D:\n plane_list = []\n os.chdir(olddir)\n if os.path.exists('xaver.in'):\n plane_list.append('x')\n if os.path.exists('yaver.in'):\n plane_list.append('y')\n if os.path.exists('zaver.in'):\n plane_list.append('z')\n if len(plane_list) > 0:\n for key in plane_list:\n os.chdir(olddir)\n av = read.aver(plane_list=key)\n os.chdir(newdir)\n write_h5_averages(av, file_name=key, datadir=todatadir,\n precision=precision, quiet=quiet)\n if lremove_old_averages:\n os.chdir(olddir)\n cmd = \"rm -f \"+os.path.join(fromdatadir, '*averages.dat')\n os.system(cmd)\n\ndef sim2h5(newdir='.', olddir='.', varfile_names=None,\n todatadir='data/allprocs', fromdatadir='data',\n precision='d', nghost=3, lpersist=False,\n x=None, y=None, z=None, lshear=False,\n lremove_old_snapshots=False, lremove_old_slices=False,\n lremove_old_averages=False, execute=False, quiet=True,\n l2D=True, lvars=True, lvids=True, laver=True, laver2D=False,\n ):\n\n \"\"\"\n Copy a simulation object written in Fortran binary to hdf5.\n The default is to copy all snapshots from/to the current simulation\n directory. Optionally the old files can be removed to\n\n call signature:\n\n sim2h5(newdir='.', olddir='.', varfile_names=None,\n todatadir='data/allprocs', fromdatadir='data',\n precision='d', nghost=3, lpersist=False,\n x=None, y=None, z=None, lshear=False,\n lremove_old_snapshots=False, lremove_old_slices=False,\n lremove_old_averages=False, execute=False, quiet=True,\n l2D=True, lvars=True, lvids=True, laver=True)\n\n Keyword arguments:\n\n *newdir*:\n String path to simulation destination directory.\n Path may be relative or absolute.\n\n *newdir*:\n String path to simulation destination directory.\n Path may be relative or absolute.\n\n *varfile_names*:\n A list of names of the snapshot files to be written, e.g. VAR0\n If None all varfiles in olddir+'/data/proc0/' will be converted\n\n *todatadir*:\n Directory to which the data is stored.\n\n *fromdatadir*:\n Directory from which the data is collected.\n\n *precision*:\n Single 'f' or double 'd' precision for new data.\n \n *nghost*:\n Number of ghost zones.\n TODO: handle switching size of ghost zones.\n\n *lpersist*:\n option to include persistent variables from snapshots.\n\n *xyz*:\n xyz arrays of the domain with ghost zones.\n This will normally be obtained from Grid object, but facility to\n redefine an alternative grid value.\n\n *lshear*:\n Flag for the shear.\n\n *lremove_old*:\n If True the old snapshots will be deleted once the new snapshot has\n been saved.\n A warning is given without execution to avoid unintended removal.\n\n *execute*:\n optional confirmation required if lremove_old.\n\n \"\"\"\n\n import os\n import numpy as np\n import h5py\n import glob\n from .. import read\n from .. import sim\n from . import write_h5_grid\n\n #test if simulation directories\n os.chdir(olddir)\n if not sim.is_sim_dir():\n print(\"ERROR: Directory (\"+olddir+\") needs to be a simulation\")\n return -1\n if newdir != olddir:\n os.chdir(newdir)\n if not sim.is_sim_dir():\n print(\"ERROR: Directory (\"+newdir+\") needs to be a simulation\")\n return -1\n #\n lremove_old = lremove_old_snapshots or\\\n lremove_old_slices or lremove_old_averages\n if lremove_old:\n if not execute:\n os.chdir(olddir)\n print(\"WARNING: Are you sure you wish to remove the Fortran binary\"+\n \" files from \\n\"+\n os.getcwd()+\".\\n\"+\n \"Set execute=True to proceed.\")\n return -1\n\n os.chdir(olddir)\n if varfile_names == None:\n os.chdir(fromdatadir+'/proc0')\n lVARd = False\n varfiled_names = glob.glob('VARd*')\n if len(varfiled_names) > 0:\n varfile_names = glob.glob('VAR*')\n for iv in range(len(varfile_names)-1,-1,-1):\n if 'VARd' in varfile_names[iv]:\n varfile_names.remove(varfile_names[iv])\n lVARd = True\n else:\n varfile_names = glob.glob('VAR*')\n os.chdir(olddir)\n gkeys = ['x', 'y', 'z', 'Lx', 'Ly', 'Lz', 'dx', 'dy', 'dz',\n 'dx_1', 'dy_1', 'dz_1', 'dx_tilde', 'dy_tilde', 'dz_tilde',\n ]\n grid=read.grid(quiet=True)\n for key in gkeys:\n if not key in grid.__dict__.keys():\n print(\"ERROR: key \"+key+\" missing from grid\")\n return -1\n #obtain the settings from the old simulation\n settings={}\n skeys = ['l1', 'l2', 'm1', 'm2', 'n1', 'n2',\n 'nx', 'ny', 'nz', 'mx', 'my', 'mz',\n 'nprocx', 'nprocy', 'nprocz',\n 'maux', 'mglobal', 'mvar', 'precision',\n ]\n olddim = read.dim()\n for key in skeys:\n settings[key]=olddim.__getattribute__(key)\n settings['nghost']=nghost\n settings['precision']=precision.encode()\n #obtain physical units from old simulation\n ukeys = ['length', 'velocity', 'density', 'magnetic', 'time',\n 'temperature', 'flux', 'energy', 'mass', 'system',\n ]\n param = read.param()\n param.__setattr__('unit_mass',param.unit_density*param.unit_length**3)\n param.__setattr__('unit_energy',param.unit_mass*param.unit_velocity**2)\n param.__setattr__('unit_time',param.unit_length/param.unit_velocity)\n param.__setattr__('unit_flux',param.unit_mass/param.unit_time**3)\n param.unit_system=param.unit_system.encode()\n #index list for variables in f-array\n indx=read.index()\n\n #check consistency between Fortran binary and h5 data\n os.chdir(newdir)\n dim = read.dim()\n try:\n dim.mvar == settings['mvar']\n dim.mx == settings['mx']\n dim.my == settings['my']\n dim.mz == settings['mz']\n except ValueError:\n print(\"ERROR: new simulation dimensions do not match.\")\n return -1\n print('precision is ',precision)\n if laver2D:\n aver2h5(newdir, olddir,\n todatadir='data/averages', fromdatadir='data', l2D=False,\n precision=precision, quiet=quiet, laver2D=laver2D,\n lremove_old_averages=False)\n #copy snapshots\n if lvars:\n var2h5(newdir, olddir, varfile_names, todatadir, fromdatadir,\n precision, lpersist, quiet, nghost, settings, param, grid,\n x, y, z, lshear, lremove_old_snapshots, indx)\n #copy downsampled snapshots if present\n if lvars and lVARd:\n var2h5(newdir, olddir, varfiled_names, todatadir, fromdatadir,\n precision, lpersist, quiet, nghost, settings, param, grid,\n x, y, z, lshear, lremove_old_snapshots, indx, last_var=False,\n trimall=True)\n #copy old video slices to new h5 sim\n if lvids:\n cmd='src/read_all_videofiles.x'\n os.system(cmd)\n slices2h5(newdir, olddir, grid,\n todatadir='data/slices', fromdatadir='data',\n precision=precision, quiet=quiet,\n lremove_old_slices=lremove_old_slices)\n #copy old averages data to new h5 sim\n if laver:\n aver2h5(newdir, olddir,\n todatadir='data/averages', fromdatadir='data', l2D=l2D,\n precision=precision, quiet=quiet,\n lremove_old_averages=lremove_old_averages)\n #check some critical sim files are present for new sim without start\n #construct grid.h5 sim information if requied for new h5 sim\n os.chdir(newdir)\n write_h5_grid(file_name='grid', datadir='data', precision=precision,\n nghost=nghost, settings=settings, param=param, grid=grid,\n unit=None, quiet=quiet)\n source_file = os.path.join(olddir,fromdatadir,'proc0/varN.list')\n target_file = os.path.join(newdir,todatadir,'varN.list')\n if os.path.exists(source_file):\n cmd='cp '+source_file+' '+target_file\n os.system(cmd)\n items=['def_var.pro', 'index.pro', 'jobid.dat', 'param.nml',\n 'particle_index.pro', 'pc_constants.pro', 'pointmass_index.pro',\n 'pt_positions.dat', 'sn_series.dat', 'svnid.dat', 'time_series.dat',\n 'tsnap.dat', 'tspec.dat', 'tvid.dat', 'var.general',\n 'variables.pro', 'varname.dat']\n for item in items:\n source_file = os.path.join(olddir,fromdatadir,item)\n target_file = os.path.join(newdir,fromdatadir,item)\n if os.path.exists(source_file):\n if not os.path.exists(target_file):\n cmd='cp '+source_file+' '+target_file\n os.system(cmd)\n","sub_path":"python/pencil/io/fort2h5.py","file_name":"fort2h5.py","file_ext":"py","file_size_in_byte":19945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"93273955","text":"from template.db import Database\nfrom template.query import Query\nfrom template.transaction import Transaction\nfrom template.transaction_worker import TransactionWorker\nfrom template.config import init\nfrom template.lock_manager_config import *\nfrom random import choice, randint, sample, seed\n\n# TESTING REMOVEAL ABORT\ninit()\ndb = Database()\ndb.open('./ECS165')\ngrades_table = db.create_table('Grades', 5, 0)\n\nkeys = []\nrecords = {}\nseed(3562901)\nnum_threads = 4\n\ntry:\n grades_table.index.create_index(1)\n grades_table.index.create_index(2)\n grades_table.index.create_index(3)\n grades_table.index.create_index(4)\nexcept Exception as e:\n print('Index API not implemented properly, tests may fail.')\n\ntransaction_workers = []\ninsert_transactions = []\nselect_transactions = []\nupdate_transactions = []\nfor i in range(num_threads):\n insert_transactions.append(Transaction())\n select_transactions.append(Transaction())\n update_transactions.append(Transaction())\n transaction_workers.append(TransactionWorker())\n transaction_workers[i].add_transaction(insert_transactions[i])\n #transaction_workers[i].add_transaction(select_transactions[i])\n #transaction_workers[i].add_transaction(update_transactions[i])\nworker_keys = [ {} for t in transaction_workers ]\n\n'''\nfor i in range(0, 10000):\n key = 92106429 + i\n keys.append(key)\n i = i % num_threads\n records[key] = [key, randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20)]\n q = Query(grades_table)\n insert_transactions[i].add_query(q.insert, q.table, *records[key])\n worker_keys[i][key] = True\n'''\n\nq = Query(grades_table)\nfor i in range(0, 100):\n key = 92106429 + i\n keys.append(key)\n i = i % num_threads\n records[key] = [key, randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20), randint(i * 20, (i + 1) * 20)]\n\n# test to see if the same key can be inserted twice\n\nfor i in range(0, 5):\n insert_transactions[0].add_query(q.insert, q.table, *records[keys[i]])\n\nfor i in range(6, 10):\n insert_transactions[0].add_query(q.insert, q.table, *records[keys[i]])\n \n\nfor i in range(10, 20):\n insert_transactions[1].add_query(q.insert, q.table, *records[keys[i]])\n \n\nfor i in range(20, 30):\n insert_transactions[2].add_query(q.insert, q.table, *records[keys[i]])\n pass\n\n\nfor i in range(20, 30):\n insert_transactions[2].add_query(q.delete, q.table, keys[i])\n pass\n\n\ntemp_record = [1,1,1,1,1]\ntemp_key = -1\ninsert_transactions[2].add_query(q.select, q.table, temp_key, 0, temp_record)\n\nfor i in range(30, 40):\n insert_transactions[3].add_query(q.insert, q.table, *records[keys[i]])\n pass\n\n\nfor transaction_worker in transaction_workers:\n transaction_worker.run()\n\ndb.close()\ndb = Database()\ndb.open('./ECS165')\ngrades_table = db.get_table('Grades')\n\n# select records between 20 and 24 to ensure they are rolled back\nq = Query(grades_table)\n\n#print(\"testing insertion rollback\")\nfor i in range(20, 25):\n result = q.select(keys[i], 0, [1, 1, 1, 1, 1])\n if result is False:\n print(\"record was rolled back nice :)\")\n else:\n print(\"record not rolled back ;(\")\n\ndb.close()\n\n","sub_path":"m3_tester_part_4.py","file_name":"m3_tester_part_4.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"79129990","text":"'''\nWISE detections and colors of Very High redshift quasars\n'''\n\nfrom astropy.io import fits\nfrom astropy.io import ascii\nfrom astropy.table import Table\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nfrom matplotlib import colors as mcolors\nfrom matplotlib import gridspec\n\nfrom astropy.cosmology import FlatLambdaCDM\n# In this case we just need to define the matter density \n# and hubble parameter at z=0.\n# Note the default units for the hubble parameter H0 are km/s/Mpc. \n# You can also pass an astropy `Quantity` with the units specified. \n#cosmo = FlatLambdaCDM(H0=68, Om0=0.27)\ncosmo = FlatLambdaCDM(H0=67.7, Om0=0.307) #Banados thesis\n\nimport astropy.units as u\nages = np.array([13, 10, 8, 6, 5, 4, 3, 2, 1.5, 1.2, 1, 0.8, 0.70])*u.Gyr\nfrom astropy.cosmology import z_at_value\nageticks = [z_at_value(cosmo.age, age) for age in ages]\n\n\n## READ-IN THE DATA FILE(S)\npath = '/cos_pc19a_npr/data/highest_z_QSOs/'\ninfile = 'THE_TABLE_v0pnt97.dat'\nreadin = path+infile\n#all_VHzQs = ascii.read(readin, delimiter=r'\\s', guess=False)\nall_VHzQs = ascii.read(readin, delimiter=r'\\s')\n\n## The four ATLAS QSOs\n#ATLAS = ascii.read(path+'ATLAS_Quasar_TABLE.dat', delimiter=r'\\s', guess=False)\n#GTO = ascii.read('JWST_GTO_VeryHighZ_Quasar_targets_byRA.dat', delimiter=r'\\s', guess=False)\n\n## Setting up the variables for easier use\nw1mag = all_VHzQs['w1mag']\nw2mag = all_VHzQs['w2mag']\nw3mag = all_VHzQs['w3mag']\nw4mag = all_VHzQs['w4mag']\nw1snr = all_VHzQs['w1snr']\nw2snr = all_VHzQs['w2snr']\nw3snr = all_VHzQs['w3snr']\nw4snr = all_VHzQs['w4snr']\nw1_min_w2_all = (w1mag-w2mag)\nw2_min_w3_all = (w1mag-w2mag)\nw3_min_w4_all = (w1mag-w2mag)\n\nz_all = all_VHzQs['redshift']\nM1450_all = all_VHzQs['M1450']\n\n## ATLAS QSOs\n#z_ATLAS = ATLAS['redshift']\n## GTO\n#z_GTO = GTO['redshift']\n\n\n##\n## Making the plot\n##\n## May fave new line ;-=)\n#plt.style.use('dark_background')\n#matplotlib.rc('text', usetex=True)\n\nplt.rcParams.update({'font.size': 14})\n\n## From\n## https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html\nfig = plt.figure(figsize=(16, 12))\ngrid = plt.GridSpec(4, 4, hspace=0.00, wspace=0.00)\n#grid = plt.GridSpec(4, 4)\n\nmain_ax = fig.add_subplot(grid[:-1, 1:])\ny_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)\nx_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)\n\n#fig, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, gridspec_kw={'height_ratios': [7, 7, 3]}, figsize=(14.0, 16.0))\n\n\n## define the colormap\n#cmap = plt.cm.jet\n#cmap = plt.cm.hsv\n#cmap = plt.cm.gist_rainbow_r\n#cmap = plt.cm.rainbow ## Good for W1SNR\n#cmap = plt.cm.terrain\n#cmap = plt.cm.jet ## great with 'dark_background'\n#cmap = plt.cm.viridis\ncmap = plt.cm.plasma ## Good for W1-W2\n##cmap = plt.cm.gnuplot\n##cmap = plt.cm.coolwarm\n#cmap = plt.cm.Reds_r\n#cmap = plt.cm.Oranges_r\n\n## REDSHIFT RANGE\nxmin = 4.80 \nxmax = 7.95\n\nzmin = xmin\nzmax = xmax\n\n##\n## TOP PANEL\n##\nls = 'solid'\nlw = 1.0\nms_large = 250*1.75\nms = ms_large/3.\n#main_ax.scatter(z_GTO, w1mag_GTO, c='r', marker=\"P\", s=ms_large)\n#hdl=main_ax.scatter(z_all, M1450_all , c=w1snr, cmap=cmap, s=ms, alpha=0.85)\nhdl=main_ax.scatter(z_all, M1450_all , c=w1_min_w2_all, cmap=cmap, s=ms, alpha=0.85)\n#hdl=main_ax.scatter(z_all, M1450_all , c=w1snr, cmap=cmap, s=ms, alpha=0.85)\n#main_ax.scatter(z_ATLAS, w1mag_ATLAS, c='k', marker=\"o\", s=ms_large)\n\n## Normally, this is:: left, bottom, width, height\n## but with orientation='horizontal', then\n## left, up, length, height\n#datco=[0.45, 0.775, 0.40, 0.025] ##\n#datco=[0.68, 0.80, 0.28, 0.025] ## W1 SNR\ndatco=[0.76, 0.82, 0.20, 0.025] ## W1-W2 SNR\n\n##and finally the new colorabar axes at the right position!\ncbar_ax = fig.add_axes(datco)\n#the rest stays the same:\n#clevs = [0, 12, 24, 36] ## w1snr\n#clevs = [0, 12, 24, 36] ## w1snr\n#clevs = [0, 15, 30] ## w1snr\n#clevs = [0, 6 , 12] ## w3snr\nclevs = [0.0, 1.0] ## W1-W2\n\ncb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)\n#cb1.set_label(r'W1 SNR', labelpad=-80, fontsize=24)\ncb1.set_label(r'W1-W2', labelpad=-80, fontsize=24)\n#ax1.set_ylabel(r'W1MPRO',fontsize=22)\n\n\n## Bowler et al. 2015, MNRAS, 452, 1817\n## Schechter function\nz_Bowler = [5.0, 6.0, 7.0]\nMstar_Bowler = [-21.07, -20.77, -20.56]\nerrMstar_Bowler = [0.09, 0.18, 0.17]\n## https://matplotlib.org/examples/lines_bars_and_markers/linestyles.html\nmain_ax.plot(z_Bowler, Mstar_Bowler,linestyle='--', linewidth=4, color='w')\nmain_ax.text(7.025, -20.5, r'galaxy ${\\it M}^*$', {'color': 'w', 'fontsize': 22}, weight=600)\nmain_ax.text(7.025, -20.0, r'Bowler et al. (2015)', {'color': 'w', 'fontsize': 14}, weight=700)\n\n\nymin = -19.5\nymax = -30.5\nmain_ax.set_xlim((xmin, xmax))\nmain_ax.set_ylim((ymin, ymax))\nmain_ax.tick_params('x', direction='in', which='both', bottom=True, top=True, left=True, right=True)\nmain_ax.tick_params('y', direction='in', which='both', bottom=True, top=True, left=True, right=True)\n\nax4 = main_ax.twiny()\nax4.set_xticks(ageticks)\nax4.set_xticklabels(['{:g}'.format(age) for age in ages.value])\n#zmin, zmax = 0, 5.9\n#ax.set_xlim(zmin, zmax)\nax4.set_xlim(zmin, zmax)\n#ax4.set_xlabel('Time since Big Bang (Gyr; Flat $\\Lambda$CDM, H0=67.7)')\nax4.set_xlabel('Time since Big Bang (Gyr)')\nax4.xaxis.set_label_coords(0.50, 1.10)\n\n## KEY LINE!!\nfig.subplots_adjust(hspace=0)\n\n\n##\n## B O T T O M P A N E L\n##\nms = 4\nmin_x_data, max_x_data = np.min(z_all), np.max(z_all)\nxbinsize = 0.05 \nnxbins = int(np.floor((max_x_data - min_x_data) / xbinsize))\n## color = 'azure' great for 'dark_background'\n#xcolor = 'mediumaquamarine'\n#xcolor='seagreen'\n#xcolor = 'azure'\nxcolor='darkturquoise'\nx_hist.hist(z_all, bins=nxbins, label='425 quasars', alpha=1.0, color='c') \nx_hist.legend(loc='upper right')\n\nyymin = 0.0\nyymax = 40.0\nx_hist.set_xlim((xmin, xmax))\nx_hist.set_ylim((yymin, yymax))\n\n#x_hist.set_ylabel('# quasars',fontsize=22)\nx_hist.set_xlabel(r'$z$, redshift',fontsize=22)\nx_hist.tick_params('x', direction='in', which='both', bottom=True, top=True, left=True, right=True) #,labelsize=18 )\nx_hist.tick_params('y', direction='in', which='both', bottom=True, top=True, left=True, right=True)\n#ax3.legend=('[All quasars]', '[WISE detected quasars]')\n\n## KEY LINE!!\nfig.subplots_adjust(hspace=0)\n\n\n##\n## LEFT HAND SIDE P A N E L\n##\nmin_y_data, max_y_data = ymax, ymin\nybinsize = 0.05 \nnybins = int(np.floor((max_y_data - min_y_data) / ybinsize))\n\n#ycolor='mediumturquoise'\nycolor='c'\ny_hist.hist(M1450_all, bins=nybins, alpha=1.0, orientation='horizontal', color=ycolor)\ny_hist.invert_xaxis()\n#y_hist.legend(loc='upper right')\n\n#y_hist.set_xlabel('# quasars',fontsize=22)\ny_hist.set_ylabel(r'Absolute Magnitude, M$_{1450}$',fontsize=22)\n\ny_hist.set_xlim((50, 0))\n#y_hist.set_ylim((ymin, ymax))\n\n\n#plt.show()\nplt.savefig('VHzQ_Lz_temp.png',format='png')\nplt.close(fig)\n","sub_path":"Lz/older_py/Lz_20180601.py","file_name":"Lz_20180601.py","file_ext":"py","file_size_in_byte":6857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"259551261","text":"import os, subprocess, traceback, sys\nfrom contextlib import contextmanager\n\ndef run_cmd(cmd, print_output=False):\n if print_output:\n print (\"Running %s\" % cmd)\n try:\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n if print_output:\n for line in iter(process.stdout.readline, b''):\n sys.stdout.write(line)\n sys.stdout.flush()\n process.stdout.close()\n process.wait()\n except:\n print ('calling {cmd} failed\\n{trace}'.format(cmd=' '.join(cmd),trace=traceback.format_exc()))\n\n@contextmanager\ndef cd(newdir):\n prevdir = os.getcwd()\n os.chdir(os.path.expanduser(newdir))\n try:\n yield\n finally:\n os.chdir(prevdir)\n","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"210815729","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Nov 23 14:57:54 2021\r\n\r\n@author: MBOYCE\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n \r\nclass SpectraScorer():\r\n \"\"\"\r\n Scoring algorithm pulled from Stein, S; Scott, D. Optimization and testing of mass spectral library search algorithms for compound identification\r\n https://doi.org/10.1016/1044-0305(94)87009-8\r\n Current implementation allows two scoring methods:\r\n 1) DOT-PRODUCT\r\n 2) COMPOSITE\r\n Implmentations to code:\r\n 1) SE (Spectral Entropy, Fiehn group)\r\n \"\"\"\r\n \r\n @classmethod\r\n def calc_score(cls, measured_spectrum, reference_spectrum, algorithm = 'COMPOSITE', **kwargs):\r\n score = cls._get_score_method(algorithm)\r\n aligned_df = cls._get_align_df(measured_spectrum, reference_spectrum)\r\n return score(aligned_df, **kwargs)\r\n \r\n @classmethod\r\n def _get_score_method(cls, equation):\r\n if equation == 'DOT_PRODUCT':\r\n return cls._calc_dot_product\r\n elif equation == 'COMPOSITE':\r\n return cls._calc_composite\r\n else:\r\n raise ValueError(equation)\r\n\r\n def _get_align_df(measured_spectrum, reference_spectrum):\r\n return measured_spectrum.align(reference_spectrum, suffixes = ['_u', '_l'])\r\n \r\n def _calc_dot_product(aligned_df, m = 0.5, n = 0.5):\r\n \r\n aligned_df['weighted_u'] = (aligned_df['frag_mass_u']**n) * (aligned_df['intensity_u']**m)\r\n aligned_df['weighted_l'] = (aligned_df['frag_mass_l']**n) * (aligned_df['intensity_l']**m)\r\n numerator = sum(aligned_df['weighted_u'] * aligned_df['weighted_l'])**2\r\n denominator = sum(map(lambda x: x**2, aligned_df['weighted_u']))*sum(map(lambda x: x**2, aligned_df['weighted_l']))\r\n return numerator/denominator\r\n \r\n @classmethod\r\n def _calc_composite(cls, aligned_df, m = 0.5, n = 0.5):\r\n \r\n N_u = sum(aligned_df['intensity_u'] > 0)\r\n N_lu = sum(aligned_df['mass_match'] == 1)\r\n if N_lu == 0: \r\n return 0 #Returns a 0 for the score if no matches are present in the data\r\n F_dot = cls._calc_dot_product(aligned_df, m, n)\r\n F_ratio = cls._calc_ratio_pairs(aligned_df, N_lu)\r\n return (N_u*F_dot + N_lu*F_ratio)/(N_u + N_lu)\r\n \r\n def _calc_ratio_pairs(aligned_df, N_lu):\r\n SUM = 0.0\r\n matched_df = aligned_df[aligned_df['mass_match'] == 1].reset_index(drop = True)\r\n for i in range(1, N_lu):\r\n numerator = matched_df['weighted_l'][i]*matched_df['weighted_u'][i-1]\r\n denominator = matched_df['weighted_l'][i-1]*matched_df['weighted_u'][i]\r\n l = 1 if numerator/denominator <= 1 else -1\r\n \r\n SUM += (numerator/denominator)**l\r\n f_r = 1/float(N_lu) * SUM\r\n return f_r\r\n ","sub_path":"app/feature/score_algo.py","file_name":"score_algo.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"523166239","text":"import streamlit as st\nfrom tensorflow.keras.models import load_model\nfrom PIL import Image\nfrom numpy import asarray\n\n\nmodel = load_model(\"model.h5\")\n\ndef main():\n uploaded_file = None\n st.title('Covid Detector')\n if st.checkbox('JPG'):\n uploaded_file = st.file_uploader(\"Choose an image...\", type=\"jpg\")\n if st.checkbox('JPEG'):\n uploaded_file = st.file_uploader(\"Choose an image...\", type=\"jpeg\")\n\n if uploaded_file is not None:\n result = prediction(uploaded_file)\n if result == 0:\n st.error(\"Covid-19 Detected\")\n else:\n st.success(\"You are Safe\")\n\n\n\ndef prediction(uploaded_file):\n img = Image.open(uploaded_file)\n img=img.resize((224,224))\n numpydata = asarray(img)\n numpydata = numpydata.reshape(-1, 224, 224, 3)\n sc_img=numpydata/255\n predict=model.predict_classes(sc_img)[0][0]\n return predict\n\nif __name__ == '__main__':\n main()","sub_path":"covid-app.py","file_name":"covid-app.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"492583936","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom django.conf.urls.defaults import patterns, url\nfrom django.contrib import admin\nfrom django.contrib.admin.util import unquote, model_ngettext\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponse\nfrom django.utils import formats, simplejson\nfrom django.utils.translation import ugettext_lazy, ugettext as _\n\nfrom locking.models import ObjectLockedError\n\n\nclass LockableAdmin(admin.ModelAdmin):\n class Media():\n css = {\n 'all': ('locking/css/locking.css',)\n }\n js = (\n 'locking/js/admin.locking.js',\n 'locking/js/jquery.url.packed.js',\n )\n\n def force_unlock(self, request, queryset):\n \"\"\"\n Admin action to force unlocking all objects in `queryset`.\n\n Intended for superusers.\n \"\"\"\n if not self.has_change_permission(request):\n raise PermissionDenied\n\n for obj in queryset:\n obj.unlock()\n\n n = queryset.count()\n\n if n:\n self.message_user(request, _(\"Successfully unlocked %(count)d %(items)s.\") % {\n \"count\": n, \"items\": model_ngettext(self.opts, n)\n })\n\n force_unlock.short_description = ugettext_lazy(\"Force unlocking\")\n\n def unlock_view(self, request, object_id, extra_context=None):\n obj = self.get_object(request, unquote(object_id))\n if not self.has_change_permission(request, obj):\n raise PermissionDenied\n # Users who don't have exclusive access to an object anymore may still\n # request we unlock an object. This happens e.g. when a user navigates\n # away from an edit screen that's been open for very long.\n # When this happens, LockableModel.unlock_for will throw an exception,\n # and we just ignore the request.\n # That way, any new lock that may since have been put in place by another\n # user won't get accidentally overwritten.\n try:\n obj.unlock_for(request.user)\n obj._is_a_locking_request = True\n return HttpResponse(status=200)\n except ObjectLockedError:\n return HttpResponse(status=403)\n\n def refresh_lock_view(self, request, object_id, extra_context=None):\n obj = self.get_object(request, unquote(object_id))\n\n if not self.has_change_permission(request, obj):\n raise PermissionDenied\n try:\n obj.lock_for(request.user)\n except ObjectLockedError:\n # The user tried to overwrite an existing lock by another user.\n # No can do, pal!\n return HttpResponse(status=409) # Conflict\n\n # Format date like a DateTimeInput would have done\n format = formats.get_format('DATETIME_INPUT_FORMATS')[0]\n original_locked_at = obj.locked_at.strftime(format)\n original_modified_at = obj.modified_at.strftime(format)\n\n response = simplejson.dumps({\n 'original_locked_at': original_locked_at,\n 'original_modified_at': original_modified_at,\n })\n\n return HttpResponse(response, mimetype=\"application/json\")\n\n def get_urls(self):\n \"\"\"\n Override get_urls() to add a locking URLs.\n \"\"\"\n urls = super(LockableAdmin, self).get_urls()\n info = self.model._meta.app_label, self.model._meta.module_name\n locking_urls = patterns('',\n url(r'^(.+)/unlock/$',\n self.admin_site.admin_view(self.unlock_view),\n name='unlock_%s_%s' % info),\n url(r'^(.+)/refresh_lock/$',\n self.admin_site.admin_view(self.refresh_lock_view),\n name='refresh_lock_%s_%s' % info),\n )\n return locking_urls + urls\n\n def changelist_view(self, request, extra_context=None):\n # we need the request objects in a few places where it's usually not present,\n # so we're tacking it on to the LockableAdmin class\n self.request = request\n return super(LockableAdmin, self).changelist_view(request, extra_context)\n\n def save_model(self, request, obj, form, change, *args, **kwargs):\n # object creation doesn't need/have locking in place\n if not form.is_locking_disabled() and obj.pk:\n obj.unlock_for(request.user)\n super(LockableAdmin, self).save_model(request, obj, form, change, *args,\n **kwargs)\n\n def get_object(self, request, object_id):\n obj = super(LockableAdmin, self).get_object(request, object_id)\n if obj is not None:\n obj._request_user = request.user\n\n return obj\n\n def lock(self, obj):\n message = ''\n if obj.is_locked:\n seconds_remaining = obj.lock_seconds_remaining\n minutes_remaining = seconds_remaining / 60\n if self.request.user == obj.locked_by:\n locked_until_self = _(\"You have a lock on this article for %s more minutes.\") \\\n % (minutes_remaining)\n message = '
' \\\n % (settings.MEDIA_URL, locked_until_self)\n else:\n locked_until = _(\"Still locked for %(minutes)s minutes by %(user)s\") \\\n % {\"minutes\": minutes_remaining, \"user\": obj.locked_by}\n message = '
' \\\n % (settings.MEDIA_URL, locked_until)\n\n return message\n lock.allow_tags = True\n list_display = ('__str__', 'lock')\n","sub_path":"locking/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":5614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"323838127","text":"class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n while len(stones) > 1:\n stones.append(stones.pop(stones.index(max(stones))) -\n stones.pop(stones.index(max(stones))))\n return stones[0]\n\n def lastStoneWeight2(self, stones: List[int]) -> int:\n if len(stones) == 1:\n return stones[0]\n stones = sorted(stones)\n y = stones.pop()\n x = stones.pop()\n if len(stones) == 0:\n return y - x\n elif y - x > 0:\n stones.append(y-x)\n return self.lastStoneWeight(stones)\n","sub_path":"leetcodeAprilChallenge/python/NewStoneWeight.py","file_name":"NewStoneWeight.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"450386936","text":"import requests, json, sys\nfrom requests.packages.urllib3 import Retry\nfrom datetime import datetime\n\n# NOTE: This code is mostly being written to help me better understand the\n# Tenable.io API as it currently rests. This by no means is supposed\n# to be as full-featured as the Python SDK, and is more of a learning\n# exercise. If I happen to write something here that I think the\n# larger community may benefit from, I'll likely initiate a pull of\n# the relevent parts into the official SDK.\n\n__version__ = '0.0-poc'\n__author__ = 'Steve McGrath '\n\n\n### Base Classes\n# These classes exist simply to try to conform to DRY when possible.\n\nclass APIError(Exception):\n def __init__(self, code, msg):\n self.code = code\n self.msg = msg\n\n def __str__(self):\n return repr('[%s]: %s' % (self.code, self.msg))\n\n\nclass APIModel(object):\n def __init__(self, base):\n self._api = base\n\n\nclass APIObject(object):\n def __init__(self, **entries):\n self.__dict__.update(entries)\n def __str__(self):\n return str(self.id)\n def dict(self):\n return self.__dict__ \n\n\nclass APIClient(object):\n '''\n This is the base client library that TenableIO and ContainerSecurity will pull from. Anything thats\n common between them should be handled here.\n '''\n _session = None\n _token = None\n _url = None\n\n def __init__(self, access_key=None, secret_key=None, username=None, password=None, impersonate=None):\n self._reset_session()\n\n def _reset_session(self):\n '''\n Sets and/or resets the session\n '''\n # Sets the retry adaptor with the ability to properly backoff if we get 429s\n retries = Retry(status_forcelist={429}, backoff_factor=0.1, respect_retry_after_header=True)\n adapter = requests.adapters.HTTPAdapter(retries)\n\n # initiate the session and then attach the Retry adaptor.\n self._session = requests.Session()\n self._session.mount('https://', adapter)\n\n # we need to make sure to identify ourselves.\n self._session.headers.update({\n 'User-Agent': 'Tenio/{} Python/{}'.format(__version__, '.'.join([str(i) for i in sys.version_info][0:3]))\n })\n\n def _request(self, method, path, return_json=True, **kwargs):\n '''\n Request call builder\n ''' \n resp = self._session.request(method, '{}/{}'.format(self._url, path), **kwargs)\n\n # If we aren't streaming the response back to the caller, then we should\n # check to see if the response is valid and raise an APIError exception\n # if an error is returned back.\n if 'stream' in kwargs and kwargs['stream']:\n return resp\n elif return_json:\n try:\n # Lets check for an error code in the returned JSON dictionary.\n # if one exists, then lets raise an exception. Otherwise, we\n # should return the Python dictionary that we have already\n # computed out.\n d = resp.json()\n if 'error' in d and d['error']:\n raise APIError(resp.status_code, d['error'])\n else:\n return d\n except ValueError:\n # obviously something went wrong with the JSON parser, so lets\n # just return the response object.\n return resp\n else:\n # We were told not to return json data and not to stream, so lets just\n # return the response object\n return resp\n\n def get(self, path, **kwargs):\n '''\n Calls the specified path with a GET method\n '''\n return self._request('GET', path, **kwargs)\n\n def post(self, path, **kwargs):\n '''\n Calls the specified path with a POST method\n '''\n return self._request('POST', path, **kwargs)\n\n def put(self, path, **kwargs):\n '''\n Calls the specified path with a PUT method\n '''\n return self._request('PUT', path, **kwargs)\n\n def patch(self, path, **kwargs):\n '''\n Calls the specified path with a PATCH method\n '''\n return self._request('PATCH', path, **kwargs)\n\n def delete(self, path, **kwargs):\n '''\n Calls the specified path with a DELETE method\n '''\n return self._request('DELETE', path, **kwargs)\n\n def head(self, path, **kwargs):\n '''\n Calls the specified path with a HEAD method\n '''\n return self._request('HEAD', path, **kwargs)\n\n\n### Data Classes\n# These classes are meant to store data being returned from the API. At the moment they are simply basic\n# objects to store the data in something a bit more pythonic than a dictionary. These may evolve over\n# time to perform actions in their own right, but that would require work ;)\n\nclass Agent(APIObject):\n def __repr__(self):\n return 'Agent({}, {})'.format(self.id, self.name)\n\n\nclass AgentGroup(APIObject):\n def __repr__(self):\n return 'AgentGroup({}, {})'.format(self.id, self.name)\n\n\n### Action Classes\n# These classes attempt to use the Tenable.io API documentation and closely follow whats expected for a\n# given call and to clean up the data where applicable.\n\nclass _AgentGroups(APIModel):\n def create(self, name, scanner_id=None):\n '''\n Creates a new agent group\n '''\n if not scanner_id:\n scanner_id = 1\n resp = self._api.post('scanners/{}/agent-groups'.format(scanner_id), json={'name': name})\n if resp.status_code == 200:\n return resp.json()['id']\n\n def remove(self, group_id, scanner_id=None):\n '''\n Removes an agent group\n '''\n if not scanner_id:\n scanner_id = 1\n return self._api.delete('scanners/{}/agent-groups/{}'.format(scanner_id, group_id))\n\n def link(self, agent_id, group_id, scanner_id=None):\n '''\n Links an agent to an agent group\n '''\n if not scanner_id:\n scanner_id = 1\n return self._api.put('scanners/{}/agent-groups/{}/agents/{}'.format(scanner_id, group_id, agent_id), json={})\n\n def unlink(self, agent_id, group_id, scanner_id=None):\n '''\n Unlinks an agent to an agent group\n '''\n if not scanner_id:\n scanner_id = 1\n return self._api.delete('scanners/{}/agent-groups/{}/agents/{}'.format(scanner_id, group_id, agent_id))\n\n def modify(self, group_id, scanner_id=None, **kwargs):\n '''\n Modifies an agent group using the supplied parameters\n '''\n if not scanner_id:\n scanner_id = 1\n return self._api.put('scanners/{}/agent-groups/{}'.format(scanner_id, group_id), json=kwargs)\n\n def list(self, scanner_id=None, raw_json=False):\n '''\n Returns the list of groups in the Tenable.io container\n '''\n if not scanner_id:\n scanner_id = 1\n agent_groups = self._api.get('scanners/{}/agent-groups'.format(scanner_id))['groups']\n if raw_json:\n return agent_groups\n else:\n return [AgentGroup(**a) for a in agent_groups]\n\n\nclass _Agents(APIModel):\n def list(self, scanner_id=None, raw_json=False):\n '''\n Returns a list of agents attached to the Tenable.io container\n '''\n if not scanner_id:\n scanner_id = 1\n agents = self._api.get('scanners/{}/agents'.format(scanner_id))['agents']\n if raw_json:\n return agents\n else:\n return [Agent(**a) for a in agents]\n\n def remove(self, agent_id, scanner_id=None):\n '''\n Removes an agent from the Tenable.io container\n '''\n if not scanner_id:\n scanner_id = 1\n return self._api.delete('scanners/{}/agents/{}'.format(scanner_id, agent_id))\n\n\nclass _Editor(APIModel):\n def _is_valid_type(self, type):\n if type in ['scan', 'policy']:\n return True\n else:\n raise APIError(900, 'Editor type is not valid')\n\n def list(self, type, raw_json=True):\n '''\n Returns a list of templates based on the type of templates requested\n '''\n self._is_valid_type(type)\n tmpls = self._api.get('editor/{}/templates'.format(type))['templates']\n if raw_json:\n return tmpls\n else:\n raise APIError(900, 'Editor Objects not yet implimented')\n\n def audits(self, type, obj_id, file_id, file_obj):\n '''\n Exports the audit file\n '''\n self._is_valid_type(type)\n resp = self._api.get('editor/{}/{}/audits/{}'.format(type, obj_id, file_id), stream=True)\n for chunk in rep.iter_content(chunk_size=1024):\n if chunk:\n file_obj.write(chunk)\n return file_obj\n\n def details(self, type, template_uuid, raw_json=True):\n '''\n Returns the details for the given template\n '''\n self._is_valid_type(type)\n template = self._api.get('editor/{}/templates/{}'.format(type, template_uuid))\n if raw_json:\n return template\n else:\n raise APIError(900, 'Editor Objects not yet implimented')\n\n def edit(self, type, id):\n '''\n Returns the requested object\n '''\n self._is_valid_type(type)\n template = self._api.get('editor/{}/{}'.format(type, id))\n if raw_json:\n return template\n else:\n raise APIError(900, 'Editor Objects not yet implimented')\n\n def plugin_desc(self, policy_id, family_id, plugin_id, raw_json=True):\n '''\n Returns the plugin description\n '''\n policy_id = str(int(policy_id))\n family_id = str(int(family_id))\n plugin_id = str(int(plugin_id))\n plugin = self._api.get('editor/policy/{}/families/{}/plugins/{}'.format(policy_id, family_id, plugin_id))\n if raw_json:\n return plugin_id['plugindescription']\n else:\n raise APIError(900, 'Editor Objects not yet implimented')\n\n\n\n\n### Client Classes\n# We call this to communicate to the API. The TenableIO class also has the raw methods\n# exposed for usage as well. This means that if the API docs get updated and the module\n# hasn't yet been updated to reflect it, that people could still take advantage of the\n# session handling capabilities of the module.\n\nclass TenableIO(APIClient):\n _url = 'https://cloud.tenable.com'\n\n def __init__(self, access_key=None, secret_key=None, username=None, password=None, impersonate=None):\n '''\n TenableIO basic object\n '''\n self._access_key = access_key\n self._secret_key = secret_key\n self._username = username\n self._password = password\n self._impersonate = impersonate\n self._reset_session()\n\n # If a username and password were set instead of API keys, then we will\n # get the session token and leverage that instead. Generally it isn't\n # recommended to use usernames and passwords when communicating to the\n # API, however I'm keeping this here for the sake of completionism\n if username and password and not access_key and not secret_key:\n self._token = self.post('session', json={\n 'username': username, \n 'password': password\n })['token']\n\n # Now we need to graft the API Models on to the TenableIO object.\n self.agent_groups = _AgentGroups(self)\n self.agents = _Agents(self)\n self.editor = _Editor(self)\n\n def _reset_session(self):\n '''\n Sets and/or resets the session\n '''\n super(APIClient, self)._reset_session()\n\n # If secret keys and access keys were used, then we need to set the header to inform the API that\n # we will be using these keys for authentication instead of a username and password.\n if self._access_key and self._secret_key:\n self._session.headers.update({\n 'X-APIKeys': 'accessKey={}; secretKey={};'.format(self._access_key, self._secret_key)\n })\n\n # If our intention is to impersonate another user, then we should set the impersonation header\n if self._impersonate:\n self._session.headers.update({\n 'X-Impersonate': 'username={}'.format(self._impersonate)\n })\n\n def _request(self, method, path, return_json=True, **kwargs):\n '''\n Request call builder\n ''' \n # If a session token was set instead, then we should pass the session\n # token using the appropriate header.\n if 'headers' not in kwargs:\n kwargs['headers'] = {}\n if self._token and not (self._access_key or self._secret_key):\n kwargs['headers']['X-Cookie'] = u'token={}'.format(self._token)\n return super(APIClient, self)._request(method, path, return_json, **kwargs)\n\n def impersonate(self, user):\n '''\n Returns a new TenableIO object with the impersonation parameters set\n '''\n return TenableIO(access_key=self._access_key, \n secret_key=self._secret_key,\n username=self._username,\n password=self._password,\n impersonate=user\n )\n\n\nclass ContainerSecurity(APIClient):\n _url = 'https://cloud.flawcheck.com'\n\n def __init__(self, api_key):\n self._api_key = api_key\n self._reset_session()\n\n def _reset_session(self):\n '''\n Sets and/or resets the session\n '''\n super(APIClient, self)._reset_session()\n self._session.params = {'api_key': self._api_key}","sub_path":"tenio.py","file_name":"tenio.py","file_ext":"py","file_size_in_byte":13795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"389761230","text":"# Do the necessary imports\nimport shutil\nimport base64\nfrom datetime import datetime\nimport os\nimport cv2\nimport numpy as np\nimport socketio\nimport eventlet\nimport eventlet.wsgi\nfrom PIL import Image\nfrom flask import Flask\nfrom io import BytesIO, StringIO\nimport json\nimport pickle\nimport matplotlib.image as mpimg\nimport time\nfrom absl import flags, app\nimport pickle\nimport logging\nimport copy\nlogging.getLogger('werkzeug').setLevel(logging.ERROR)\nlogging.getLogger('socketio').setLevel(logging.ERROR)\nlogging.getLogger('engineio').setLevel(logging.ERROR)\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('image_folder', '',\n 'Path to image folder. This is where the images from the run will be saved.')\n\n# Import functions for perception and decision making\nfrom perception_step import perception_step\nfrom decision import decision_step\nfrom supporting_functions import update_rover, create_output_images\nfrom rover_state import RoverState\n# Initialize socketio server and Flask application\n# (learn more at: https://python-socketio.readthedocs.io/en/latest/)\nsio = socketio.Server(logger = False)\n\n# Initialize our rover\nRover = RoverState()\n\n# Variables to track frames per second (FPS)\n# Initialize frame counter\nframe_counter = 0\n# Initialize second counter\nsecond_counter = time.time()\nfps = None\n\n\n# Define telemetry function for what to do with incoming data\n@sio.on('telemetry')\ndef telemetry(sid, data):\n\n global frame_counter, second_counter, fps\n frame_counter+=1\n # Do a rough calculation of frames per second (FPS)\n if (time.time() - second_counter) > 1:\n fps = frame_counter\n frame_counter = 0\n second_counter = time.time()\n # print(\"Current FPS: {}\".format(fps))\n\n if data:\n global Rover\n # Initialize / update Rover with current telemetry\n Rover, image = update_rover(Rover, data)\n\n if np.isfinite(Rover.vel):\n\n # Execute the perception and decision steps to update the Rover's state\n Rover = perception_step(Rover)\n Rover = decision_step(Rover)\n\n # Create output images to send to server\n out_image_string1, out_image_string2 = create_output_images(Rover)\n\n # The action step! Send commands to the rover!\n\n # Don't send both of these, they both trigger the simulator\n # to send back new telemetry so we must only send one\n # back in respose to the current telemetry data.\n\n # If in a state where want to pickup a rock send pickup command\n if Rover.send_pickup and not Rover.picking_up:\n send_pickup()\n # Reset Rover flags\n Rover.send_pickup = False\n else:\n # Send commands to the rover!\n commands = (Rover.throttle, Rover.brake, Rover.steer)\n send_control(commands, out_image_string1, out_image_string2)\n\n # In case of invalid telemetry, send null commands\n else:\n\n # Send zeros for throttle, brake and steer and empty images\n send_control((0, 0, 0), '', '')\n\n # If you want to save camera images from autonomous driving specify a path\n # Example: $ python drive_rover.py image_folder_path\n # Conditional to save image frame if folder was specified\n if FLAGS.image_folder != '':\n timestamp = datetime.utcnow().strftime('%Y_%m_%d_%H_%M_%S_%f')[:-3]\n image_filename = os.path.join(FLAGS.image_folder, timestamp)\n image.save('{}.jpg'.format(image_filename))\n with open(image_filename + '.pickle', 'wb') as f:\n r = {}\n r['pos'] = Rover.pos\n r['yaw'] = Rover.yaw\n r['pitch'] = Rover.pitch\n r['roll'] = Rover.roll\n r['vel'] = Rover.vel\n r['steer'] = Rover.steer\n r['picking_up'] = Rover.picking_up\n pickle.dump(r, f)\n\n else:\n sio.emit('manual', data={}, skip_sid=True)\n\n@sio.on('connect')\ndef connect(sid, environ):\n print(\"connect \", sid)\n send_control((0, 0, 0), '', '')\n sample_data = {}\n sio.emit(\n \"get_samples\",\n sample_data,\n skip_sid=True)\n\ndef send_control(commands, image_string1, image_string2):\n # Define commands to be sent to the rover\n data={\n 'throttle': commands[0].__str__(),\n 'brake': commands[1].__str__(),\n 'steering_angle': commands[2].__str__(),\n 'inset_image1': image_string1,\n 'inset_image2': image_string2,\n }\n # Send commands via socketIO server\n sio.emit(\n \"data\",\n data,\n skip_sid=True)\n eventlet.sleep(0)\n# Define a function to send the \"pickup\" command\ndef send_pickup():\n print(\"Picking up\")\n pickup = {}\n sio.emit(\n \"pickup\",\n pickup,\n skip_sid=True)\n eventlet.sleep(0)\n\ndef main(argv):\n #os.system('rm -rf IMG_stream/*')\n if FLAGS.image_folder != '':\n print(\"Creating image folder at {}\".format(FLAGS.image_folder))\n if not os.path.exists(FLAGS.image_folder):\n os.makedirs(FLAGS.image_folder)\n else:\n shutil.rmtree(FLAGS.image_folder)\n os.makedirs(FLAGS.image_folder)\n print(\"Recording this run ...\")\n else:\n print(\"NOT recording this run ...\")\n\n # wrap Flask application with socketio's middleware\n app = Flask(__name__)\n app = socketio.Middleware(sio, app)\n\n # deploy as an eventlet WSGI server\n eventlet.wsgi.server(eventlet.listen(('', 4567)), app)\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"code/drive_rover.py","file_name":"drive_rover.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"237513444","text":"from flask import Flask, request, jsonify\nimport yaml\nfrom query_class import Query\n\n\napp = Flask(__name__)\n\n\n@app.route('/query/yml_data', methods=['POST'])\ndef receive_yml_data():\n if request.method == 'POST':\n\n yml_req_src = request.get_data(cache=True, as_text=True)\n yml_data = yaml.load(yml_req_src,Loader=yaml.FullLoader)\n # yaml_from_logic = yaml.dump(yml_data)\n # print (yml_data)\n query_obj = Query(yml_data['symbols'],yml_data['query_type'])\n # print(query_obj.symbols)\n if query_obj.query_type == 'intraday':\n query_obj.day_range = yml_data['day_range']\n query_obj.time_interval = yml_data['time_interval']\n\n yml_response = query_obj.make_query()\n print (yml_response)\n return yml_response\n\n\n@app.route('/conf/query', methods=['GET'])\ndef config_data():\n remote_realtime_api_url = \"https://api.worldtradingdata.com\"\n remote_intraday_api_url = \"https://intraday.worldtradingdata.com\"\n query_template_realtime = \"/api/v1/stock?\"\n query_template_intraday = \"/api/v1/intraday?\"\n remote_api_token = \"KFzAzKDWU88IAG2uQHp3i3kBa9RCkd3JAWJulicwGNHssxEwq0wElClEUACM\"\n\n if request.method == 'GET':\n query_type = request.args.get('query_type')\n if query_type == \"realtime\":\n response = {\"remote_api_url\" : remote_realtime_api_url, \"query_template\" : query_template_realtime, \"remote_api_token\": remote_api_token }\n # print (response)\n return jsonify(response)\n elif query_type == \"intraday\" :\n response = {\"remote_api_url\" : remote_intraday_api_url, \"query_template\" : query_template_intraday, \"remote_api_token\": remote_api_token }\n # print (\"query_type = intraday\" )\n return jsonify(response)\n return \"UNKNOWN QUERY TYPE\"\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port='5003')\n\n\n\n","sub_path":"flask_query_api.py","file_name":"flask_query_api.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"641838254","text":"import numpy as np\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\n\r\nclass DS():\r\n def __init__(self, K, N):\r\n self.K = K #The number of features.\r\n self.N = N #The number of nodes\r\n self.D = None #The number of decision nodes\r\n\r\n self.l = np.full(shape=(self.N+1), fill_value=False, dtype=np.bool)\r\n self.S = np.full(shape=(self.N+1, self.K+1), fill_value=False, dtype=np.bool) # S[i,f]: Node i discriminates on feature f\r\n self.t = np.full(shape=(self.N+1), fill_value=False, dtype=np.bool) # t[j] The value on node j\r\n self.tree = [[None] for j in range(self.N)]\r\n\r\n def parse_solution(self, sol): # solution = [(key, value),(key, value)....] key = (''v[1], 'v[2]', ....'v[N+1]',c'[1]'....) and other variables keys\r\n var_name_lookup = {\"l\": self.l, \"S\": self.S, \"t\": self.t}\r\n for var, value in sol:\r\n var_name = var[: var.find(\"[\")].strip()\r\n var_index = var[var.find(\"[\")+1 : var.find(\"]\")].strip().split(\",\")\r\n assert var_name in var_name_lookup\r\n if var_name == \"l\" or var_name == \"t\":\r\n var_name_lookup[var_name][int(var_index[0])] = value\r\n else:\r\n\r\n j = int(var_index[0])\r\n f = int(var_index[1])\r\n var_name_lookup[var_name][j, f] = value\r\n\r\n\r\n\r\n def generate_tree(self):\r\n for j in range(1, self.N+1):\r\n value = self.t[j]\r\n if self.l[j]:\r\n feature = \"class\"\r\n else:\r\n feature = None\r\n for f in range(1, self.K+1):\r\n # print(self.S[j+1, f])\r\n if self.S[j, f]:\r\n feature = \"f\" + str(f)\r\n # print('feature', feature)\r\n break\r\n\r\n self.tree[j-1] = (feature, value)\r\n print('tree:', self.tree)\r\n\r\n def validate(self, data_features, data_classes):\r\n for f, c in zip(data_features, data_classes):\r\n pre_match = True\r\n pre_leaf = False\r\n for node in self.tree:\r\n node_value = node[1]\r\n if node[0].lower().startswith('f'):\r\n node_f = int(node[0][1:])\r\n if pre_leaf:\r\n pre_leaf = False\r\n if f[node_f - 1] == node_value:\r\n pre_match = True\r\n else:\r\n pre_match = False\r\n elif pre_match and f[node_f - 1] == node_value:\r\n pass\r\n else:\r\n pre_match = False\r\n else:\r\n assert node[0].lower().strip() == 'class'\r\n pre_leaf = True\r\n if pre_match:\r\n assert c == node_value, 'Wrong solution'\r\n\r\n def draw(self, cnt, filename):\r\n nx_tree = nx.Graph()\r\n nx_tree_label = {}\r\n pos = [[0,0]]\r\n for j in range(1, self.N+1):\r\n nx_tree.add_node(j)\r\n if self.l[j]:\r\n nx_tree_label[j] = \"T\" if self.t[j] == 1 else \"F\"\r\n else:\r\n nx_tree_label[j] = self.tree[j - 1][0] if self.tree[j - 1][1] else \"-{0}\".format(self.tree[j - 1][0])\r\n\r\n if j + 1 <= self.N:\r\n nx_tree.add_edge(j, j+1)\r\n\r\n quotient = (j-1) // 10\r\n rem = quotient % 2\r\n if rem == 0:\r\n pos.append([j - quotient * 10, - quotient])\r\n else:\r\n pos.append([(quotient + 1) * 10 + 1 - j, -quotient])\r\n\r\n '''\r\n if j <= 10:\r\n pos.append([j, 0])\r\n elif j <= 20:\r\n pos.append([21-j, -1])\r\n elif j <= 30:\r\n pos.append([j - 20, -2])\r\n elif j <= 40:\r\n pos.append([41-j, -3])\r\n '''\r\n\r\n plt.figure(figsize=(8, 8))\r\n plt.subplot(2, 1, 1)\r\n nx.draw(nx_tree, pos, with_labels=True, node_color='blue')\r\n plt.subplot(2, 1, 2)\r\n nx.draw(nx_tree, pos, with_labels=True, labels=nx_tree_label, node_color='red')\r\n plt.savefig('trees/' + filename + '/' + str(cnt) + '.png')\r\n plt.close()\r\n\r\n\r\n","sub_path":"util/DecisionSet.py","file_name":"DecisionSet.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"614732935","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport numpy\nimport time\n\n\n# Exercice 3\n\ndef exercice_3_1():\n \"\"\"\n Exercice 3.1\n ============\n \n Calculate the element-wise difference between 2 arrays X and Y\n \"\"\"\n x = numpy.random.random(10)\n y = numpy.random.random(10)\n print('x =', x)\n print('y =', y)\n\n difference = x - y\n print('x - y =', difference)\n\n\ndef exercice_3_2():\n \"\"\"\n Exercice 3.2\n ============\n \n Provide an expression to calculate the difference X[i+1]-X[i]\n for all the elements of the 1D array X\n \"\"\"\n x = numpy.random.random(10)\n print('x =', x)\n\n diff = x[1:] - x[:-1]\n print('x[i+1] - x[i] =', diff)\n\n\n# Exercice 4\n\ndef exercice_4_1():\n \"\"\"\n Exercice 4.1\n ============\n \n Generate a 100x100 array with elements in increasing order\n \"\"\"\n data = numpy.arange(10000)\n data.shape = 100, 100\n # Alternatives:\n # data.shape = 100, -1\n # data = data.reshape(100, 100)\n print('data.shape =', data.shape)\n\ndef exercice_4_2():\n \"\"\"\n Exercice 4.2\n ============\n\n Perform a 2 x 2 binning\n \"\"\"\n data = numpy.arange(100).reshape(10, 10)\n print('data =', data)\n binned = data[::2, ::2] + data[::2, 1::2] + data[1::2, ::2] + data[1::2, 1::2]\n print('2x2 binned =', binned)\n\n # Alternative\n alt_binned = data.reshape(5, 2, 5, 2).sum(axis=3).sum(axis=1)\n print('2x2 binned (alternative) =', alt_binned)\n\n\n# Exercice 5\n\ndef ex5_inefficient_fill(height, width):\n data = numpy.zeros((height, width), dtype=numpy.float)\n for row in range(int(height)):\n for col in range(int(width)):\n data[row, col] = numpy.cos(row) * numpy.sin(col)\n return data\n\n\ndef ex5_naive_fill(height, width):\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n data = numpy.zeros((height, width), numpy.float)\n for row in range(int(height)):\n for col in range(int(width)):\n data[row, col] = height_cos[row] * width_sin[col]\n return data\n\n\ndef ex5_clever_fill(height, width):\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n cos_loop = numpy.outer(height_cos, numpy.ones(width))\n sin_loop = numpy.outer(numpy.ones(height), width_sin)\n return cos_loop * sin_loop\n\n\ndef ex5_practical_fill(height, width):\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n sin_loop, cos_loop = numpy.meshgrid(width_sin, height_cos)\n return sin_loop * cos_loop\n\n\ndef ex5_optimized_fill(height, width):\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n return numpy.outer(height_cos, width_sin)\n\n\ndef exercice_5():\n \"\"\"\n Exercice 5\n ==========\n\n Write a function fill_array(height, width) to generate an array of dimension (height, width) in which X[row, column] = cos(row) * sin(column)\n\n Time it for n=1000, m = 1000\n \"\"\"\n height, width = 1000, 1000\n\n start_time = time.time()\n data1 = ex5_inefficient_fill(height, width)\n print('inefficient fill took about %f s' % (time.time() - start_time))\n \n start_time = time.time()\n data = ex5_naive_fill(height, width)\n print('naive fill took about %f s' % (time.time() - start_time))\n assert numpy.all(numpy.equal(data1, data))\n\n start_time = time.time()\n data = ex5_clever_fill(height, width)\n print('clever fill took about %f s' % (time.time() - start_time))\n assert numpy.all(numpy.equal(data1, data))\n\n start_time = time.time()\n data = ex5_practical_fill(height, width)\n print('practical fill took about %f s' % (time.time() - start_time))\n assert numpy.all(numpy.equal(data1, data))\n\n start_time = time.time()\n data = ex5_optimized_fill(height, width)\n print('optimized fill took about %f s' % (time.time() - start_time))\n assert numpy.all(numpy.equal(data1, data))\n\n\ndef ex5_extra_inefficient_add_fill(height, width):\n data = numpy.empty((height, width), dtype=numpy.float)\n for row in range(int(height)):\n for col in range(int(width)):\n data[row, col] = numpy.cos(row) + numpy.sin(col)\n return data\n\n\ndef ex5_extra_add_fill(height, width):\n width_sin = numpy.sin(numpy.arange(width))\n height_cos = numpy.cos(numpy.arange(height))\n data = numpy.atleast_2d(height_cos).T + numpy.atleast_2d(width_sin)\n return data\n\n\ndef exercice_5_extra():\n \"\"\"\n Extra: Do the same for X[row, column] = cos(row) + sin(column)\n \"\"\"\n height, width = 1000, 1000\n\n start_time = time.time()\n data1 = ex5_extra_inefficient_add_fill(height, width)\n print('inefficient add fill took about %f s' % (time.time() - start_time))\n\n start_time = time.time()\n data = ex5_extra_add_fill(height, width)\n print('add fill took about %f s' % (time.time() - start_time))\n assert numpy.all(numpy.equal(data1, data))\n\n\nif __name__ == \"__main__\":\n print(exercice_3_1.__doc__)\n exercice_3_1()\n\n print(exercice_3_2.__doc__)\n exercice_3_2()\n\n print(exercice_4_1.__doc__)\n exercice_4_1()\n\n print(exercice_4_2.__doc__)\n exercice_4_2()\n\n print(exercice_5.__doc__)\n exercice_5()\n\n print(exercice_5_extra.__doc__)\n exercice_5_extra()\n","sub_path":"python/numpy/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":5267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"422636818","text":"import math\ndef evaluate(number, base,n):\n value = 0\n for y in range(n-1,-1,-1):\n value += (number>>y&1)*pow(base,y)\n return value\n\ndef get_devisor(number, prime_list):\n if number < 2000000:\n if prime_list[number] == True:\n return -1\n sqrt_num = int(math.sqrt(number))\n upper_bound = min(sqrt_num+1, 10000)\n for i in range(2, upper_bound):\n if number%i == 0:\n return i\n return -1\n\ndef setup_prime_list(prime_list):\n length = prime_list.__len__()\n for i in range(2, length):\n if prime_list[i] == None:\n prime_list[i] = True\n for j in range(2, length):\n now = i * j\n if now >= length:\n break\n prime_list[now] = False\n return prime_list\n\ndef get_next(jamcoin):\n return jamcoin+2\n\ndef printOut(jamcoin):\n print(bin(jamcoin))\n\nif __name__ == \"__main__\":\n t = 1\n n = 0\n j = 0\n t = int(input(\"\"))\n inputString = input(\"\")\n n = int(inputString.split(\" \")[0])\n j = int(inputString.split(\" \")[1])\n prime_list = [False, None] * 1000000\n prime_list[2] = True\n prime_list = setup_prime_list(prime_list)\n jamcoin = 1\n jamcoin = jamcoin << (n-1)\n jamcoin += 1\n count = 0\n print(\"Case #1:\")\n while (count' % (self.__class__.__name__, self.get_url_path())\n\n\nclass Sphere(models.Model):\n organisational_unit = 'sphere'\n name = models.CharField(max_length=200)\n slug = AutoSlugField(populate_from='name', max_length=200, always_update=True)\n financial_year = models.ForeignKey(\n FinancialYear,\n on_delete=models.CASCADE,\n related_name=\"spheres\",\n )\n\n class Meta:\n unique_together = (\n ('financial_year', 'slug'),\n ('financial_year', 'name'),\n )\n\n def get_url_path(self):\n return \"%s/%s\" % (self.financial_year.get_url_path(), self.slug)\n\n def __str__(self):\n return '<%s %s>' % (self.__class__.__name__, self.get_url_path())\n\n\nclass Government(models.Model):\n organisational_unit = 'government'\n sphere = models.ForeignKey(Sphere, on_delete=models.CASCADE, related_name=\"governments\")\n name = models.CharField(max_length=200)\n slug = AutoSlugField(populate_from='name', max_length=200, always_update=True)\n _function_budgets = None\n\n class Meta:\n unique_together = (\n ('sphere', 'slug'),\n ('sphere', 'name'),\n )\n\n def get_url_path(self):\n if self.sphere.slug == 'national':\n return self.sphere.get_url_path()\n else:\n return \"%s/%s\" % (self.sphere.get_url_path(), self.slug)\n\n def get_department_by_slug(self, slug):\n departments = self.departments.objects.filter(slug=slug)\n if departments.count() == 0:\n return None\n elif departments.count() == 1:\n return departments.first()\n else:\n raise Exception(\"More matching slugs than expected\")\n\n def get_vote_primary_departments(self):\n return Department.objects.filter(government=self, is_vote_primary=True).all()\n\n def get_function_budgets(self):\n \"\"\"\n get the budget totals for all the government functions\n \"\"\"\n\n if self._function_budgets is not None:\n return self._function_budgets\n budget = EstimatesOfExpenditure(\n financial_year_slug=self.get_financial_year().slug,\n sphere_slug=self.government.sphere.slug,\n )\n financial_year_start = self.sphere.financial_year.get_starting_year()\n vote_numbers = [str(d.vote_number)\n for d in self.get_vote_primary_departments()]\n votes = '\"%s\"' % '\";\"'.join(vote_numbers)\n cuts = [\n budget.get_financial_year_ref() + ':' + financial_year_start,\n budget.get_vote_number_ref() + ':' + votes\n ]\n if self.sphere.slug == 'provincial':\n cuts.append(budget.get_geo_ref() + ':\"%s\"' % self.name)\n drilldowns = [budget.get_function_ref()]\n result = budget.aggregate(cuts=cuts, drilldowns=drilldowns)\n functions = []\n for cell in result['cells']:\n functions.append({\n 'name': cell[budget.get_function_ref()],\n 'total_budget': cell['value.sum']\n })\n self._function_budgets = functions\n return self._function_budgets\n\n def __str__(self):\n return '<%s %s>' % (self.__class__.__name__, self.get_url_path())\n\n\nclass Department(models.Model):\n organisational_unit = 'department'\n government = models.ForeignKey(Government, on_delete=models.CASCADE, related_name=\"departments\")\n name = models.CharField(max_length=200)\n slug = AutoSlugField(populate_from='name', max_length=200, always_update=True, editable=True)\n vote_number = models.IntegerField()\n is_vote_primary = models.BooleanField(default=True)\n intro = models.TextField()\n _programme_budgets = None\n\n def __init__(self, *args, **kwargs):\n super(Department, self).__init__(*args, **kwargs)\n if self.pk:\n self.treasury_datasets = self.get_treasury_datasets()\n self.old_name = self.name\n self.old_slug = self.slug\n\n class Meta:\n unique_together = (\n ('government', 'slug'),\n ('government', 'name'),\n )\n indexes = [\n PartialIndex(fields=['government', 'vote_number'],\n unique=True,\n where='is_vote_primary'),\n ]\n\n ordering = ['vote_number', 'name']\n\n def save(self, *args, **kwargs):\n if self.pk and self.old_name != self.name:\n self._update_datasets()\n super(Department, self).save(*args, **kwargs)\n\n def clean(self):\n # This is only for user feedback in admin.\n # The constraint must be enforced elsewhere.\n existing_vote_primary = Department.objects.filter(\n government=self.government, vote_number=self.vote_number)\n if self.is_vote_primary and existing_vote_primary \\\n and existing_vote_primary.first() != self:\n raise ValidationError('There is already a primary department for '\n 'vote %d' % self.vote_number)\n\n def _update_datasets(self):\n if len(self.name) > 5 and self.is_vote_primary: # If it's a really short name we can break stuff\n for dataset in self.treasury_datasets:\n new_slug = django_slugify(self.name)\n dataset['title'] = dataset['title'].replace(self.old_name, self.name)\n dataset['name'] = dataset['name'].replace(self.slug, new_slug)\n extras_set(dataset['extras'], 'Department Name', self.name)\n extras_set(dataset['extras'], 'department_name', self.name)\n extras_set(dataset['extras'], 'department_name_slug', new_slug)\n logger.info(\"Updating package %s with new name\", dataset['id'])\n ckan.action.package_update(**dataset)\n for resource in dataset['resources']:\n resource['name'] = resource['name'].replace(self.old_name, self.name)\n logger.info(\"Updating resource %s with new name\", resource['id'])\n ckan.action.resource_update(**resource)\n else:\n logger.warn(\"Not updating datasets for %s\", self.get_url_path())\n\n def _create_treasury_dataset(self):\n vocab_map = {}\n for vocab in ckan.action.vocabulary_list():\n vocab_map[vocab['name']] = vocab['id']\n tags = [\n { 'vocabulary_id': vocab_map['spheres'],\n 'name': self.government.sphere.slug },\n { 'vocabulary_id': vocab_map['financial_years'],\n 'name': self.get_financial_year().slug },\n ]\n if self.government.sphere.slug == 'provincial':\n tags.append({\n 'vocabulary_id': vocab_map['provinces'],\n 'name': self.government.name,\n })\n dataset_fields = {\n 'title': package_title(self),\n 'name': package_id(self),\n 'extras': [\n {'key': 'department_name', 'value': self.name},\n {'key': 'Department Name', 'value': self.name},\n {'key': 'department_name_slug', 'value': self.slug},\n {'key': 'Vote Number', 'value': self.vote_number},\n {'key': 'vote_number', 'value': self.vote_number},\n {'key': 'geographic_region_slug', 'value': self.government.slug},\n {'key': 'organisational_unit', 'value': 'department'},\n ],\n 'owner_org': 'national-treasury',\n 'license_id': 'other-pd',\n 'tags': tags,\n }\n ckan.action.package_create(**dataset_fields)\n\n def upload_resource(self, local_path, overwrite=False):\n if not self.treasury_datasets:\n self._create_treasury_dataset()\n self.treasury_datasets = self.get_treasury_datasets()\n assert(len(self.treasury_datasets) == 1)\n dataset = self.treasury_datasets[0]\n resource = None\n for existing_resource in dataset['resources']:\n existing_path = urlparse.urlparse(existing_resource['url']).path\n existing_ext = splitext(basename(existing_path))[1]\n ext = splitext(local_path)[1]\n if existing_ext == ext:\n resource = existing_resource\n resource_fields = {\n 'package_id': dataset['id'],\n 'name': resource_name(self),\n 'upload': open(local_path, 'rb')\n }\n\n if resource and not overwrite:\n logger.info(\"Not overwriting existing resource %s to package %s\",\n local_path, dataset['id'])\n return\n\n if resource:\n logger.info(\"Re-uploading resource %s to package %s\", local_path, dataset['id'])\n resource_fields['id'] = resource['id']\n result = ckan.action.resource_patch(**resource_fields)\n else:\n logger.info(\"Uploading resource %s to package %s\", local_path, dataset['id'])\n result = ckan.action.resource_create(**resource_fields)\n logger.info(\"Uploading resource result: %r\", result)\n\n def get_url_path(self):\n return \"%s/departments/%s\" % (self.government.get_url_path(), self.slug)\n\n def get_govt_functions(self):\n return GovtFunction.objects.filter(programme__department=self).distinct()\n\n def get_financial_year(self):\n return self.government.sphere.financial_year\n\n def _get_financial_year_query(self):\n return '+vocab_financial_years:\"%s\"' % self.get_financial_year().slug\n\n def _get_government_query(self):\n if self.government.sphere.slug == 'provincial':\n return '+vocab_provinces:\"%s\"' % self.government.name\n else:\n return none_selected_query('vocab_provinces')\n\n def get_primary_department(self):\n \"\"\"\n Check if department is primary\n \"\"\"\n if not self.is_vote_primary:\n try:\n dept = Department\\\n .objects \\\n .get(vote_number=self.vote_number,\n is_vote_primary=True,\n government=self.government)\n except MultipleObjectsReturned:\n logger.exception(\"Department %s has multiple primary \"\n \"departments\" % self.slug)\n raise\n else:\n return dept\n return self\n\n def get_treasury_datasets(self):\n query = {\n 'q': '',\n 'fq': ('+organization:\"national-treasury\"'\n '+vocab_financial_years:\"%s\"'\n '+vocab_spheres:\"%s\"'\n '+extras_s_geographic_region_slug:\"%s\"'\n '+extras_s_department_name_slug:\"%s\"') % (\n self.government.sphere.financial_year.slug,\n self.government.sphere.slug,\n self.government.slug,\n self.get_primary_department().slug,\n ),\n 'rows': 1,\n }\n response = ckan.action.package_search(**query)\n logger.info(\n \"query %s\\nreturned %d results\",\n pformat(query),\n len(response['results'])\n )\n return response['results']\n\n def get_treasury_resources(self):\n resources = {}\n datasets = self.get_treasury_datasets()\n if datasets:\n package = datasets[0]\n for resource in package['resources']:\n if resource['name'].startswith('Vote'):\n if self.government.sphere.slug == 'provincial':\n doc_short = \"EPRE\"\n doc_long = \"Estimates of Provincial Revenue and Expenditure\"\n elif self.government.sphere.slug == 'national':\n doc_short = \"ENE\"\n doc_long = \"Estimates of National Expenditure\"\n else:\n raise Exception(\"unexpected sphere\")\n name = \"%s for %s\" % (doc_short, resource['name'])\n description = (\"The %s (%s) sets out the detailed spending \"\n \"plans of each government department for the \"\n \"coming year.\") % (doc_long, doc_short)\n if name not in resources:\n resources[name] = {\n 'description': description,\n 'formats': [],\n }\n resources[name]['formats'].append({\n 'url': resource['url'],\n 'format': resource['format'],\n })\n return resources\n\n def _get_functions_query(self):\n function_names = [f.name for f in self.get_govt_functions()]\n ckan_tag_names = [re.sub('[^\\w -]', '', n) for n in function_names]\n if len(ckan_tag_names) == 0:\n # We select datasets with no functions rather than datasets\n # with any function (e.g. a blank query) because this query\n # is intended to restrict datasets to matching functions.\n return none_selected_query('vocab_functions')\n else:\n options = ['+vocab_functions:\"%s\"' % n for n in ckan_tag_names]\n return '+(%s)' % ' OR '.join(options)\n\n def get_contributed_datasets(self):\n # We use an OrderedDict like an Ordered Set to ensure we include each\n # match just once, and at the highest rank it came up in.\n datasets = OrderedDict()\n\n fq_org = '-organization:\"national-treasury\"'\n fq_year = self._get_financial_year_query()\n fq_sphere = '+vocab_spheres:\"%s\"' % self.government.sphere.slug\n fq_government = self._get_government_query()\n fq_functions = self._get_functions_query()\n fq_no_functions = none_selected_query('vocab_functions')\n queries = [\n (fq_org, fq_year, fq_sphere, fq_government, fq_functions),\n (fq_org, fq_sphere, fq_government, fq_functions),\n (fq_org, fq_year, fq_sphere, fq_functions),\n (fq_org, fq_sphere, fq_functions),\n (fq_org, fq_functions),\n (fq_org, fq_no_functions),\n ]\n for query in queries:\n params = {\n 'q': '',\n 'fq': \"\".join(query),\n 'rows': 1000,\n }\n response = ckan.action.package_search(**params)\n logger.info(\n \"query %s\\nto ckan returned %d results\",\n pformat(params),\n len(response['results']))\n for package in response['results']:\n if package['name'] not in datasets:\n dataset = Dataset.from_package(package)\n datasets[package['name']] = dataset\n return datasets.values()\n\n def get_programme_budgets(self):\n \"\"\"\n get the budget totals for all the department programmes\n \"\"\"\n if self._programme_budgets is not None:\n return self._programme_budgets\n budget = EstimatesOfExpenditure(\n financial_year_slug=self.get_financial_year().slug,\n sphere_slug=self.government.sphere.slug,\n )\n financial_year_start = self.get_financial_year().get_starting_year()\n cuts = [\n budget.get_financial_year_ref() + ':' + financial_year_start,\n budget.get_department_name_ref() + ':\"' + self.name + '\"',\n ]\n if self.government.sphere.slug == 'provincial':\n cuts.append(budget.get_geo_ref() + ':\"%s\"' % self.government.name)\n drilldowns = [\n budget.get_programme_number_ref(),\n budget.get_programme_name_ref(),\n ]\n result = budget.aggregate(cuts=cuts, drilldowns=drilldowns)\n programmes = []\n for cell in result['cells']:\n programmes.append({\n 'name': cell[budget.get_programme_name_ref()],\n 'total_budget': cell['value.sum']\n })\n self._programme_budgets = programmes\n return self._programme_budgets\n\n def get_expenditure_over_time(self):\n base_year = get_base_year()\n financial_year_start = self.get_financial_year().get_starting_year()\n financial_year_start_int = int(financial_year_start)\n financial_year_starts = [str(y) for y in xrange(financial_year_start_int-4, financial_year_start_int+3)]\n expenditure = {\n 'base_financial_year': FinancialYear.slug_from_year_start(str(base_year)),\n 'nominal': [],\n 'real': [],\n }\n\n budget = EstimatesOfExpenditure(\n financial_year_slug=self.get_financial_year().slug,\n sphere_slug=self.government.sphere.slug,\n )\n cuts = [\n budget.get_department_name_ref() + ':\"' + self.name + '\"',\n ]\n if self.government.sphere.slug == 'provincial':\n cuts.append(budget.get_geo_ref() + ':\"%s\"' % self.government.name)\n drilldowns = [\n budget.get_financial_year_ref(),\n budget.get_phase_ref(),\n ]\n result = budget.aggregate(cuts=cuts, drilldowns=drilldowns)\n if result['cells']:\n cpi = get_cpi()\n for idx, financial_year_start in enumerate(financial_year_starts):\n phase = TRENDS_AND_ESTIMATES_PHASES[idx]\n cell = [\n c for c in result['cells']\n if c[budget.get_financial_year_ref()] == int(financial_year_start)\n and c[budget.get_phase_ref()] == phase\n ][0]\n nominal = cell['value.sum']\n expenditure['nominal'].append({\n 'financial_year': FinancialYear.slug_from_year_start(financial_year_start),\n 'amount': nominal,\n 'phase': phase,\n })\n expenditure['real'].append({\n 'financial_year': FinancialYear.slug_from_year_start(financial_year_start),\n 'amount': int((Decimal(nominal)/cpi[financial_year_start]['index']) * 100),\n 'phase': phase,\n })\n\n return expenditure\n else:\n logger.warning(\"Missing expenditure data for %r budget year %s\",\n cuts, self.get_financial_year().slug)\n return None\n\n def __str__(self):\n return '<%s %s>' % (self.__class__.__name__, self.get_url_path())\n\n\nclass GovtFunction(models.Model):\n name = models.CharField(max_length=200, unique=True)\n slug = AutoSlugField(populate_from='name', max_length=200, always_update=True, unique=True)\n\n def __str__(self):\n return '<%s %s>' % (self.__class__.__name__, self.slug)\n\n\nclass Programme(models.Model):\n organisational_unit = 'programme'\n department = models.ForeignKey(Department, on_delete=models.CASCADE, related_name=\"programmes\")\n name = models.CharField(max_length=200)\n slug = AutoSlugField(populate_from='name', max_length=200, always_update=True)\n programme_number = models.IntegerField()\n govt_functions = models.ManyToManyField(GovtFunction)\n\n class Meta:\n unique_together = (\n ('department', 'slug'),\n ('department', 'name'),\n ('department', 'programme_number'),\n )\n\n ordering = ['programme_number']\n\n def get_url_path(self):\n return \"%s/programmes/%s\" % (self.department.get_url_path(), self.slug)\n\n def __str__(self):\n return '<%s %s>' % (self.__class__.__name__, self.get_url_path())\n\n\nclass Dataset():\n def __init__(self, **kwargs):\n self.author = kwargs['author']\n self.created_date = kwargs['created_date']\n self.last_updated_date = kwargs['last_updated_date']\n self.license = kwargs['license']\n self.name = kwargs['name']\n self.resources = kwargs['resources']\n self.slug = kwargs['slug']\n self.intro = kwargs['intro']\n self.methodology = kwargs['methodology']\n self.organization_slug = kwargs['organization_slug']\n\n @classmethod\n def from_package(cls, package):\n resources = []\n for resource in package['resources']:\n resources.append({\n 'name': resource['name'],\n 'description': resource['description'],\n 'format': resource['format'],\n 'url': resource['url'],\n })\n return cls(\n slug=package['name'],\n name=package['title'],\n created_date=package['metadata_created'],\n last_updated_date=package['metadata_modified'],\n author={\n 'name': package['author'],\n 'email': package['author_email'],\n },\n license={\n 'name': package['license_title'],\n 'url': package['license_url'] if 'license_url' in package else None,\n },\n intro=package['notes'] if package['notes'] else None,\n methodology=package['methodology'] if 'methodology' in package else None,\n resources=resources,\n organization_slug=package['organization']['name'],\n )\n\n @classmethod\n def fetch(cls, dataset_slug):\n package = ckan.action.package_show(id=dataset_slug)\n return cls.from_package(package)\n\n def get_url_path(self):\n return \"/datasets/%s\" % self.slug\n\n def get_organization(self):\n org = ckan.action.organization_show(id=self.organization_slug)\n return {\n 'name': org['title'],\n 'logo_url': org['image_display_url'],\n 'slug': org['name'],\n 'url': org['url'] if 'url' in org else None,\n 'telephone': org['telephone'] if 'telephone' in org else None,\n 'email': org['email'] if 'email' in org else None,\n 'facebook': org['facebook_id'] if 'facebook_id' in org else None,\n 'twitter': org['twitter_id'] if 'twitter_id' in org else None,\n }\n\n @staticmethod\n def get_contributed_datasets():\n query = {\n 'q': '',\n 'fq': '-organization:\"national-treasury\"',\n 'rows': 1000,\n }\n response = ckan.action.package_search(**query)\n logger.info(\n \"query %s\\nto ckan returned %d results\",\n pformat(query),\n len(response['results'])\n )\n for package in response['results']:\n yield Dataset.from_package(package)\n\n\n# https://stackoverflow.com/questions/35633037/search-for-document-in-solr-where-a-multivalue-field-is-either-empty-or-has-a-sp\ndef none_selected_query(vocab_name):\n \"\"\"Match items where none of the options in a custom vocab tag is selected\"\"\"\n return '+(*:* NOT %s:[\"\" TO *])' % vocab_name\n\n\ndef extras_set(extras, key, value):\n for extra in extras:\n if extra['key'] == key:\n extra['value'] = value\n break\n\n\ndef package_id(department):\n financial_year = department.get_financial_year().slug\n sphere = department.government.sphere\n geo_region = department.government.name\n if sphere.slug == 'provincial':\n short_dept = extended_slugify(department.name, max_length=85, word_boundary=True)\n return extended_slugify('prov dept %s %s %s' % (\n prov_abbrev[geo_region], short_dept, financial_year))\n elif sphere.slug == 'national':\n short_dept = extended_slugify(department.name, max_length=96, word_boundary=True)\n return extended_slugify('nat dept %s %s' % (short_dept, financial_year))\n else:\n raise Exception('unknown sphere %r' % sphere)\n\n\ndef package_title(department):\n financial_year = department.get_financial_year().slug\n sphere = department.government.sphere\n geo_region = department.government.name\n if sphere.slug == 'provincial':\n return \"%s Department: %s %s\" % (geo_region, department.name, financial_year)\n elif sphere.slug == 'national':\n return \"National Department: %s %s\" % (department.name, financial_year)\n else:\n raise Exception('unknown sphere %r' % sphere)\n\n\ndef resource_name(department):\n return \"Vote %d - %s\" % (department.vote_number, department.name)\n\n\ndef get_base_year():\n cpi_year_slug = max(CPI_RESOURCE_IDS.keys())\n return int(cpi_year_slug[:4])-1\n\n\ndef get_cpi():\n cpi_year_slug = max(CPI_RESOURCE_IDS.keys())\n base_year = get_base_year()\n\n sql = '''\n SELECT \"Year\", \"CPI\" FROM \"{}\"\n ORDER BY \"Year\"\n '''.format(CPI_RESOURCE_IDS[cpi_year_slug])\n params = {\n 'sql': sql\n }\n result = requests.get(CKAN_DATASTORE_URL, params=params)\n result.raise_for_status()\n cpi = result.json()['result']['records']\n base_year_index = None\n for idx, cell in enumerate(cpi):\n financial_year_start = cell['Year'][:4]\n cell['financial_year_start'] = financial_year_start\n if financial_year_start == str(base_year):\n base_year_index = idx\n cell['index'] = 100\n for idx in range(base_year_index-1, -1, -1):\n cpi[idx]['index'] = cpi[idx+1]['index'] / (1 + Decimal(cpi[idx+1]['CPI']))\n for idx in xrange(base_year_index+1, len(cpi)):\n cpi[idx]['index'] = cpi[idx-1]['index'] * (1 + Decimal(cpi[idx]['CPI']))\n cpi_dict = {}\n for cell in cpi:\n cpi_dict[cell['financial_year_start']] = cell\n return cpi_dict\n","sub_path":"budgetportal/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":28750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"526601007","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 10 20:07:45 2017\n\n@author: anish\n\"\"\"\n\nimport numpy as np\nimport cv2\nimport math\n\n'''\ndef on_mouse(event,x,y,flag,param):\n if(event==cv2.EVENT_LBUTTONDOWN):\n print(\"In on_mouse\")\n image = cv2.imread(\"maze33.jpg\")\n pixel = image[y, x] # Note y index \"row\" of matrix and x index \"col\".\n tolerance = 30\n #print image.shape\n # Ensure your bounds are within 0 and 255.\n lower = map(lambda x: max(0, x - tolerance), pixel)\n upper = map(lambda x: min(255, x + tolerance), pixel)\n lower = np.asarray(lower)\n upper = np.asarray(upper)\n res = cv2.inRange(image, lower, upper)\n cv2.imshow(\"Result\", res)\n'''\n\nclass node:\n def __init__(self):\n self.right=0\n self.left=0\n self.top=0\n self.bottom=0\n self.xpos=0\n self.ypos=0\n def isDeadend(self):\n sumsides=self.right+self.left+self.top+self.bottom\n if(sumsides==3):\n return True\n return False\n def isDecisionPoint(self):\n sumsides=self.right+self.left+self.top+self.bottom\n if(sumsides==1):\n return True\n return False\n \ndef reduced_image(filename):\n img = cv2.imread(filename)\n lower = [0,0,0]\n upper = [30,30,30]\n lower = np.asarray(lower)\n upper = np.asarray(upper)\n res = cv2.inRange(img, lower, upper)\n i=0\n j=0\n\n num=0\n l=len(res)/2\n c=0\n fracs=[0.5,0.25,0.75]\n nums=[]\n while(c= 0 or cv2.getWindowProperty('Result', 0) >= 0):\n r = cv2.waitKey(20)\n if(r==32):\n cv2.destroyAllWindows()\n break\n\n cv2.destroyAllWindows()\nelse:\n print(\"Error\")\n\n","sub_path":"mazebackup.py","file_name":"mazebackup.py","file_ext":"py","file_size_in_byte":7151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"346471716","text":"# get_stats.py\n#\n# 05-may-20\n# Author: F. Gent (fred.gent.ncl@gmail.com).\n#\n\"\"\" Derive auxilliary data and other diagnostics from var.h5 file and \n save to new h5 file\n \n uses:\n compute 'data' arrays of size [nz,ny,nx] as required\n store 'time' of snapshot\n compute 'masks' for example by temperature phase\n compute summary statistics 'stats' \n compute 'structure' functions as required\n\"\"\"\nimport numpy as np\nimport scipy\nfrom . import is_vector\nfrom scipy.interpolate import interp1d\nfrom ..math import dot, dot2, natural_sort, helmholtz_fft, cpu_optimal\nfrom ..math.derivatives import curl, div, curl2, grad\nfrom ..calc import fluid_reynolds, magnetic_reynolds\nfrom ..io import open_h5, group_h5, dataset_h5\nfrom fileinput import input\nfrom sys import stdout\nimport subprocess as sub\nfrom .. import read \nimport os\n\ndef derive_stats(sim_path, src, dst, stat_keys=['Rm', 'uu', 'Ms'], par=[],\n comm=None, overwrite=False, rank=0, size=1, nghost=3,\n status='a', chunksize = 1000.0, quiet=True, nmin=32,\n lmask=False, mask_key = 'hot'\n ):\n\n if comm:\n overwrite = False\n if isinstance(par, list):\n os.chdir(sim_path)\n par = read.param(quiet=True,conflicts_quiet=True)\n #get data dimensions\n nx, ny, nz = src['settings']['nx'][0],\\\n src['settings']['ny'][0],\\\n src['settings']['nz'][0]\n mx, my, mz = src['settings']['mx'][0],\\\n src['settings']['my'][0],\\\n src['settings']['mz'][0]\n #split data into manageable memory chunks\n dstchunksize = 8*nx*ny*nz/1024*1024\n if dstchunksize > chunksize:\n nchunks = cpu_optimal(nx,ny,nz,quiet=quiet,\n mvar=src['settings/mvar'][0],\n maux=src['settings/maux'][0],\n MBmin=chunksize,nmin=nmin,size=size)[1]\n else:\n nchunks = [1,1,1]\n print('nchunks {}'.format(nchunks)) \n # for mpi split chunks across processes\n if size > 1:\n locindx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n locindy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n locindz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n indx = [locindx[np.mod(rank+int(rank/nchunks[2])\n +int(rank/nchunks[1]),nchunks[0])]]\n indy = [locindy[np.mod(rank+int(rank/nchunks[2]),nchunks[1])]]\n indz = [locindz[np.mod(rank,nchunks[2])]]\n allchunks = 1\n else:\n locindx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n locindy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n locindz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n indx = np.array_split(np.arange(nx)+nghost,nchunks[0]) \n indy = np.array_split(np.arange(ny)+nghost,nchunks[1]) \n indz = np.array_split(np.arange(nz)+nghost,nchunks[2])\n allchunks = nchunks[0]*nchunks[1]*nchunks[2]\n # ensure derived variables are in a list\n if isinstance(stat_keys, list):\n stat_keys = stat_keys\n else:\n stat_keys = [stat_keys]\n # initialise group \n group = group_h5(dst, 'stats', status='a', overwrite=overwrite,\n comm=comm, rank=rank, size=size)\n for key in stat_keys:\n mean_stat = list()\n stdv_stat = list()\n mean_mask = list()\n stdv_mask = list()\n nmask_msk = list()\n mean_nmsk = list()\n stdv_nmsk = list()\n nmask_nmk = list()\n for ichunk in range(allchunks):\n for iz in [indz[np.mod(ichunk,nchunks[2])]]:\n n1, n2 = iz[ 0],\\\n iz[-1]+1\n for iy in [indy[np.mod(ichunk+\n int(ichunk/nchunks[2]),nchunks[1])]]:\n m1, m2 = iy[ 0],\\\n iy[-1]+1\n for ix in [indx[np.mod(ichunk+int(ichunk/nchunks[2])\n +int(ichunk/nchunks[1]),nchunks[0])]]:\n l1, l2 = ix[ 0],\\\n ix[-1]+1\n if key in src['data'].keys():\n var = src['data'][key][n1:n2,m1:m2,l1:l2]\n elif key == 'uu' or key == 'aa':\n tmp = np.array(\n [src['data'][key[0]+'x'][n1:n2,m1:m2,l1:l2],\n src['data'][key[0]+'y'][n1:n2,m1:m2,l1:l2],\n src['data'][key[0]+'z'][n1:n2,m1:m2,l1:l2]])\n var = np.sqrt(dot2(tmp))\n else:\n if key in dst['data'].keys():\n if is_vector(key):\n var = np.sqrt(dot2(\n dst['data'][key][:,n1:n2,m1:m2,l1:l2]))\n else:\n var = dst['data'][key][n1:n2,m1:m2,l1:l2]\n else:\n print('stats: '+key+' does not exist in ',\n src,'or',dst)\n continue\n if lmask:\n mask = dst['masks'][mask_key][0,n1:n2,m1:m2,l1:l2]\n Nmask = mask[mask==False].size\n if Nmask > 0:\n mean_mask.append(var[mask==False].mean()*Nmask) \n stdv_mask.append(var[mask==False].std()*Nmask)\n else: \n mean_mask.append(0) \n stdv_mask.append(0)\n nmask_msk.append(Nmask)\n nmask = mask[mask==True].size\n if nmask > 0:\n mean_nmsk.append(var[mask==True].mean()*nmask)\n stdv_nmsk.append(var[mask==True].std()*nmask)\n else: \n mean_nmsk.append(0)\n stdv_nmsk.append(0)\n nmask_nmk.append(nmask) \n mean_stat.append(var.mean())\n stdv_stat.append(var.std())\n if comm:\n if lmask:\n mean_mask = comm.gather(mean_mask, root=0)\n stdv_mask = comm.gather(stdv_mask, root=0)\n mean_mask = comm.bcast( mean_mask, root=0)\n stdv_mask = comm.bcast( stdv_mask, root=0)\n mean_nmsk = comm.gather(mean_nmsk, root=0)\n stdv_nmsk = comm.gather(stdv_nmsk, root=0)\n mean_nmsk = comm.bcast( mean_nmsk, root=0)\n stdv_nmsk = comm.bcast( stdv_nmsk, root=0)\n nmask_msk = comm.gather(nmask_msk, root=0)\n nmask_nmk = comm.gather(nmask_nmk, root=0)\n nmask_msk = comm.bcast( nmask_msk, root=0)\n nmask_nmk = comm.bcast( nmask_nmk, root=0)\n mean_stat = comm.gather(mean_stat, root=0)\n stdv_stat = comm.gather(stdv_stat, root=0)\n mean_stat = comm.bcast( mean_stat, root=0)\n stdv_stat = comm.bcast( stdv_stat, root=0)\n if lmask:\n summk = np.sum(nmask_msk)\n if summk > 0: \n meanm = np.sum(mean_mask)/summk\n stdvm = np.sum(stdv_mask)/summk\n else:\n meanm = 0\n stdvm = 0\n sumnk = np.sum(nmask_nmk)\n if sumnk > 0: \n meann = np.sum(mean_nmsk)/sumnk\n stdvn = np.sum(stdv_nmsk)/sumnk\n else:\n meann = 0\n stdvn = 0\n print(mask_key+'-'+key+'-mean = {}, '.format(meanm)+\n mask_key+'-'+key+'-std = {}'.format(stdvm))\n print('not-'+mask_key+'-'+key+'-mean = {}, '.format(meann)+\n 'not-'+mask_key+'-'+key+'-std = {}'.format(stdvn))\n dataset_h5(group, mask_key+'-'+key+'-mean', status=status,\n data=meanm, comm=comm, size=size, rank=rank,\n overwrite=True)\n dataset_h5(group, mask_key+'-'+key+'-std', status=status,\n data=stdvm, comm=comm, size=size, rank=rank,\n overwrite=True)\n dataset_h5(group, 'not-'+mask_key+'-'+key+'-mean', status=status,\n data=meann, comm=comm, size=size, rank=rank,\n overwrite=True)\n dataset_h5(group, 'not-'+mask_key+'-'+key+'-std', status=status,\n data=stdvn, comm=comm, size=size, rank=rank,\n overwrite=True)\n mstat = np.mean(mean_stat)\n dstat = np.mean(stdv_stat)\n print(key+'-mean = {}, '.format(mstat)+key+'-std = {}'.format(dstat))\n dataset_h5(group, key+'-mean', status=status, data=mstat,\n comm=comm, size=size, rank=rank,\n overwrite=True)\n dataset_h5(group, key+'-std', status=status, data=dstat,\n comm=comm, size=size, rank=rank,\n overwrite=True)\n","sub_path":"python/pencil/ism_dyn/get_stats.py","file_name":"get_stats.py","file_ext":"py","file_size_in_byte":9252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"487903239","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\" A module that can get TimeTable and convert it into .ics files.\"\n\"\"\" 2017/11/28 16:00 Public Functions Check - ALL SUCCESSFUL\n Checker: Junyi 2017-11-28\"\"\"\n\n__author__ = 'Junyi'\n\nimport requests\nfrom requests.cookies import RequestsCookieJar\nfrom lxml import etree\nfrom uuid import uuid1\nfrom icalendar import Calendar, Event\nimport datetime\nimport config\nimport random\n\nBaseURL= config.COES_URL\nclass TimeTable:\n\t\n @staticmethod\n def __logout(cookies):\n get_url = BaseURL + \"/coes/logout.do\"\n requests.get(url=get_url, cookies=cookies, timeout=30)\n\n @staticmethod\n def __login(username, password, language):\n post_url = BaseURL + \"/coes/login.do\"\n post_data = {\"userid\": username, \"password\": password, \"submit\": \"Login\"}\n post_headers = {'Accept-Language': language}\n post_ret = requests.post(url=post_url, data=post_data, headers=post_headers, timeout=30)\n if \"Inbox\" in post_ret.text:\n return True, post_ret.cookies\n else:\n pos_begin = post_ret.text.rfind('alert(\"') + 7\n pos_end = post_ret.text.find(');', pos_begin) - 1\n return False, post_ret.text[pos_begin: pos_end]\n\n @staticmethod\n def __get_timetable(cookies, intake=\"1709\", week=\"\"):\n if not isinstance(cookies, RequestsCookieJar):\n raise TypeError(\"cookies type error\")\n if not isinstance(intake, (str, int)):\n raise TypeError(\"intake type error\")\n if not isinstance(week, (str, int)):\n raise TypeError(\"week type error\")\n\n # week填数字,如果获取总表,就不要填week\n post_url = BaseURL + \"/coes/AcademicRecordsForm.do\"\n post_data = {\"formAction\": \"Timetable\", \"intake\": str(intake), \"week\": str(week)}\n post_ret = requests.post(url=post_url, cookies=cookies, data=post_data, timeout=30)\n\n if \"timetable.add\" not in post_ret.text:\n raise Exception(\"COULD NOT FIND TIMETABLE.ADD IN RESPONSE\")\n\n k = etree.HTML(post_ret.text)\n m = k.xpath(\"/descendant::script[12]\")\n if not len(m) == 1:\n raise Exception(\"COULD NOT FIND JAVASCRIPT\")\n\n s = str(m[0].text)\n\n show_times = s.count(\"timetable.add\")\n begin = 0\n end = 0\n lis = []\n for i in range(0, show_times):\n begin = s.find(\"timetable.add(\", end)\n end = s.find(\");\", begin)\n temp = s[begin + 14:end].replace(\"\\n\", \"\").replace(\"', \", \"&*&\").replace(\", \", \",\").replace(\"'\", \"\")\n temp = temp.replace(\"&\", \"&\")\n temp = temp.replace(\" \", \" \")\n sp = temp.split(\"&*&\", 9)\n lis.append(TimeTableDay(sp).dic())\n return lis\n\n @staticmethod\n def __generate_ics(data):\n cal = Calendar()\n cal.add(\"version\", \"2.0\")\n\n for each_event in data:\n event = Event()\n event.add(\"uid\", str(uuid1())) # UID\n event.add(\"summary\", each_event[\"course_title\"] + \" @ \" + each_event[\"class_room\"] + \" (\" + each_event[\n \"class_code\"] + \")\") # 备注 显示在日历上的标题\n event.add(\"dtstamp\", datetime.datetime.now()) # 实例创建时间\n\n # a 存放课程开始和结束的数组\n a = each_event[\"day\"]\n week_begin, week_end = a, a\n\n # b 存放 分割a出来的a[0] 分割出月和日后的结果数组,也就是课程开始的日和月\n b = week_begin.split(\"-\")\n week_begin_month, week_begin_day = int(b[1]), int(b[2])\n\n # c 存放 分割a出来的a[1] 分割出月和日后的结果数组,也就是课程结束的日和月\n c = week_end.split(\"-\")\n week_end_month, week_end_day = int(c[1]), int(c[2])\n\n # 特殊处理 BEGIN\n year_begin, year_end = int(c[0]), int(c[0])\n\n hour_begin = int(each_event[\"from_to\"][:2])\n min_begin = int(each_event[\"from_to\"][3:5])\n hour_end = int(each_event[\"from_to\"][6:8])\n min_end = int(each_event[\"from_to\"][9:11])\n\n time_class_begin = datetime.datetime(year_begin, week_begin_month, week_begin_day, hour_begin, min_begin, 0)\n # time_course_begin = time_class_begin\n time_class_end = datetime.datetime(year_end, week_begin_month, week_begin_day, hour_end, min_end, 0)\n time_course_end = datetime.datetime(year_end, week_end_month, week_end_day, hour_begin, min_begin, 0)\n\n event.add(\"dtstart\", time_class_begin) # 事件开始时间\n event.add(\"dtend\", time_class_end) # 事件结束时间\n event.add(\"location\", each_event[\"class_room\"]) # 发生地点\n\n event.add(\"description\", each_event[\"course_title\"] + \" \" +\n each_event[\"class_room\"] + \" \" +\n each_event[\"class_code\"] + \" \" +\n each_event[\"teacher\"] + \" \" +\n each_event[\"course_code\"] + \" 周\" +\n each_event[\"day\"][1:]) # 描述\n\n event.add(\"rrule\", {\n \"freq\": \"weekly\",\n \"until\": time_course_end\n })\n cal.add_component(event)\n\n return cal.to_ical().decode('utf-8')\n\n @staticmethod\n def __get_timetable_list(username, password, intake, language):\n status, cookies = TimeTable.__login(username, password, language)\n result = \"GET_TIMETABLE_ICS FAILED!\"\n if status:\n try:\n time_table = TimeTable.__get_timetable(cookies, intake)\n result = time_table\n except Exception as e:\n print(e, type(e))\n print(\"Exception!\")\n finally:\n TimeTable.__logout(cookies)\n return status, TimeTable.__handle_results(result)\n else:\n return status, cookies # return: why login failed.\n\n @staticmethod\n def __handle_results(schedules):\n timetableList = []\n for schedule in schedules:\n day_array = schedule[\"week\"].split(\"-\")\n start_day = day_array[0].split(\":\")\n start_month = start_day[0]\n start_day_day = start_day[1]\n\n end_day = day_array[1].split(\":\")\n end_month = end_day[0]\n end_day_day = end_day[1]\n\n start_year = config.YEAR\n if int(start_month) - int(end_month) <= 0:\n end_year = config.YEAR\n else:\n end_year = config.YEAR + 1\n\n start = datetime.datetime(int(start_year),int(start_month),int(start_day_day))\n end = datetime.datetime(int(end_year),int(end_month),int(end_day_day))\n\n class_start_time = start + datetime.timedelta(days=(int(schedule[\"day\"]) - 1))\n\n while class_start_time < end :\n each_class = {}\n each_class[\"from_to\"] = schedule[\"from_to\"]\n each_class[\"background_color\"] = config.COLORARRAY[random.randint(0,14)]\n each_class[\"course_code\"] = schedule[\"course_code\"]\n each_class[\"course_title\"] = schedule[\"course_title\"]\n each_class[\"class_code\"] = schedule[\"class_code\"]\n each_class[\"class_room\"] = schedule[\"class_room\"]\n each_class[\"teacher\"] = schedule[\"teacher\"]\n each_class[\"day\"] = class_start_time.strftime(\"%Y-%m-%d\")\n class_start_time = class_start_time + datetime.timedelta(days=config.ONEWEEK)\n timetableList.append(each_class)\n\n return timetableList\n\n #Checked! Checker: Junyi 2017-11-28\n @staticmethod\n def get_timetable_list(username, password, intake, language = \"zh-cn\"):\n status, result = TimeTable.__get_timetable_list(str(username), str(password), intake, str(language))\n if status:\n return result\n else:\n return []\n\t\n #Checked! Checker: Junyi 2017-11-28\n @staticmethod\n def get_timetable_ics(username, password, intake, language = \"zh-cn\"):\n status, result = TimeTable.__get_timetable_list(str(username), str(password), intake, str(language))\n if status:\n return TimeTable.__generate_ics(result)\n else:\n return \"\"\n\n\nclass TimeTableDay:\n __day = \"1\"\n __from_to = \"00:00 - 00:00\"\n __course_code = \"GSER111\"\n __course_title = \"College English\"\n __class_code = \"D05\"\n __class_room = \"C507\"\n __teacher = \"ChengWenLi\"\n __week = \"Sept.\"\n __inited = False\n\n def dic(self):\n\n if not self.__inited:\n raise Exception(\"TIMETABLE NOT INITIALIZED.\")\n\n d = {}\n\n a = self.__week.split(\"-\")\n a[0], a[1] = a[0].strip(), a[1].strip()\n\n d[\"day\"] = self.__day\n d[\"from_to\"] = self.__from_to\n d[\"course_code\"] = self.__course_code\n d[\"course_title\"] = self.__course_title\n d[\"class_code\"] = self.__class_code\n d[\"class_room\"] = self.__class_room\n d[\"teacher\"] = self.__teacher\n\n lang = True\n\n if a[0].find(\"月\") == -1:\n lang = False\n dic = {\"Jan\": \"1\", \"Feb\": \"2\", \"Mar\": \"3\",\n \"Apr\": \"4\", \"May\": \"5\", \"Jun\": \"6\",\n \"Jul\": \"7\", \"Aug\": \"8\", \"Sep\": \"9\",\n \"Oct\": \"10\",\"Nov\": \"11\", \"Dec\": \"12\"}\n d[\"week\"] = dic[a[0][:3]] + \":\" + a[0][3:] + \"-\" + dic[a[1][:3]] + \":\" + a[1][3:]\n else:\n lang = True\n b, c = a[0].split(\"月\"), a[1].split(\"月\")\n dic = {\"壹\": \"1\", \"二\": \"2\", \"三\": \"3\",\n \"四\": \"4\", \"五\": \"5\", \"六\": \"6\",\n \"七\": \"7\", \"八\": \"8\", \"九\": \"9\",\n \"十\": \"10\",\"十壹\": \"11\", \"十二\": \"12\"}\n d[\"week\"] = dic[b[0]] + \":\" + b[1] + \"-\" + dic[c[0]] + \":\" + c[1]\n return d\n\n def print(self):\n print(self.dic())\n\n def __init__(self, arg):\n for i in range(0, 9):\n if not isinstance(arg[i], str):\n raise Exception(\"INIT ARG_%d TYPE ERROR\" % i)\n\n self.__day = arg[0]\n self.__from_to = arg[1] + \"-\" + arg[2]\n self.__course_code = arg[3]\n self.__course_title = arg[4]\n self.__class_code = arg[5]\n self.__class_room = arg[6]\n self.__teacher = arg[7]\n self.__week = str(arg[8]).replace(\"+ - + \", \" - \")\n self.__inited = True\n\nif __name__ == '__main__':\n # L = TimeTable.get_timetable_list(\"1709853Z-II20-0019\", \"41192303\", \"1709\", \"en\")\n import json\n print(json.dumps(TimeTable.get_timetable_list(\"1709853Z-II20-0019\", \"41192303\", \"1709\", \"en\")))\n#Example:\n# R = TimeTable.get_timetable_ics(\"1709853Z-II20-0019\", \"41192303\", \"1709\", \"en\")\n# import json\n# print(json.dumps(R))\n# print(json.dumps(L))\n","sub_path":"RcmdFun/TimeTable.py","file_name":"TimeTable.py","file_ext":"py","file_size_in_byte":10842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"11782407","text":"def funktion(f):\n def head(*args):\n if len(args) != 2:\n l, n = args[0]\n else:\n l, n = args\n if n >= len(l):\n return\n else:\n print(l[n])\n f((l, n+1))\n return head\n\n\nY = lambda g: (lambda f: g(lambda x: f(f)(x)))(lambda f: g(lambda x: f(f)(x)))\n\nwow = [1, 3, 6, \"LOOOOOOOOOOOOOOL\", \"WILLYBOY\"]\n\nx = Y(funktion)\n\nprint(x(wow, 0))\n","sub_path":"fptools/Rekursion/aufgabe_2.py","file_name":"aufgabe_2.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"348247628","text":"#!/usr/bin/python\n# usage: python convert.py\nimport re\n\nprint(\"import sparta.checkers.permission.qual.*;\")\nprint\n\nf = open(\"APICalls-Stowaway.txt\", \"r\")\nlines = f.readlines()[1:]\nf.close()\nprev_package = \"\"\nprev_cls = \"\"\nfor line in lines:\n sp = line.strip().split(\"\\t\")\n api = sp[0]\n sp_m = api.split(\"(\")\n if(len(sp_m) < 2): continue\n sp2 = sp_m[0].split(\".\")\n \n method = sp2[-1]\n cls = sp2[-2]\n package = \".\".join(sp2[:-2])\n if(package != prev_package):\n if(prev_package != \"\"):\n print(\"}\")\n print(\"\")\n print(\"package \" + package + \";\")\n print(\"\")\n if(prev_cls != cls):\n if(package == prev_package):\n print(\"}\")\n print(\"\")\n\n print(\"class \"+ cls + \" {\")\n args = re.sub(r'\\[L([^;]+);',r'\\1 []',sp_m[1])\n args = args.replace(\"[B\", \"boolean []\").replace(\"[J\", \"long []\").replace(\"[F\", \"float []\").replace(\"[Ljava.lang.String\", \"String []\")\n perm = sp[1].replace(\" and \", \",\").replace(\" or \", \",\").replace(\"android.\",\"android.Manifest.\").replace(\",NONE\",\"\").replace(\" AND \", \",\").replace(\" OR \", \",\")\n perms = perm.split(\",\")\n i = 0\n for perm_i in perms:\n if \"BACKUP\" in perm_i:\n perms[i] = '\"%s\"' % perm_i\n i += 1\n perm = \",\".join(perms) \n args_arr = args.split(\")\")[0].strip().split(\",\")\n method = method.replace(\"\", cls)\n lst = []\n cnt = 0\n for arg in args_arr:\n if(arg == \"\"): continue\n lst.append(arg + \" p\"+str(cnt))\n cnt += 1\n print(\"\\t@RequiredPermissions({%s}) Object %s(%s);\" % (perm, method, \",\".join(lst)))\n prev_cls = cls\n prev_package = package\n #print(package)\n #print(cls)\n #print(method)\nprint(\"}\")\n","sub_path":"tools/permissionmap-convert/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"623858489","text":"\nimport os\nimport ipywidgets as widgets\nimport matplotlib.pyplot as plt\nfrom skimage import io\nfrom sklearn.cluster import MiniBatchKMeans\nimport numpy as np\nfrom ipywidgets import interact, interactive, fixed, interact_manual, IntSlider\nfrom .Save import save_pic\nfrom .Preprocessing import Preprocessing\n\nclass kmeans_image_ui:\n def __init__(self, img_dir):\n \n @interact\n def color_compression(image=os.listdir(img_dir), k=IntSlider(min=1,max=256,step=1,value=16,\n continuous_update=False,\n layout=dict(width='100%'))):\n\n \n # input_img = io.imread(img_dir + image)\n self.img_path = img_dir + image\n img_object = Preprocessing(self.img_path)\n \n input_img = img_object.img\n img_data = img_object.reshape_rgb()\n\n kmeans = MiniBatchKMeans(k).fit(img_data)\n k_colors = kmeans.cluster_centers_[kmeans.predict(img_data)]\n #After K-means has converged, load the large image into your program and \n #replace each of its pixels with the nearest of the centroid colors you found\n #from the small image. \n k_img = np.reshape(k_colors, (input_img.shape))\n\n fig, (ax1, ax2) = plt.subplots(1, 2)\n fig.suptitle('K-means Image Compression', fontsize=20)\n plt.imsave(\"temp.jpg\",k_img) \n ax1.set_title('Compressed: '+str(os.stat('temp.jpg').st_size/1000)+\" KB\")\n os.remove('temp.jpg')\n ax1.set_xticks([])\n ax1.set_yticks([])\n ax1.imshow(k_img) \n self.k_img = k_img\n \n ax2.set_title('Original :'+str(os.stat(img_dir+image).st_size/1000)+\"KB\")\n ax2.set_xticks([])\n ax2.set_yticks([])\n ax2.imshow(input_img)\n\n plt.subplots_adjust(top=0.85)\n plt.show()\n\n def save(self):\n save_pic(self.img_path, self.k_img)\n\n \n \n \n \n \t\n \n \n","sub_path":"build/lib/KMeansImage/Interactive.py","file_name":"Interactive.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"332752334","text":"import torch\nfrom torch.autograd import Variable\nfrom copy import deepcopy\nfrom QNet import QNet\nimport numpy\nimport random\n\n\nclass Approximator:\n\n def __init__(self, learning_rate, epsilon, _lambda):\n self.epsilon = epsilon\n self.network = QNet()\n \n #if(runOnGPU):\n # self.network.cuda()\n self.loss_fn = torch.nn.MSELoss(size_average=False)\n self.optimizer = torch.optim.SGD(self.network.parameters(), lr=learning_rate)\n self._lambda = _lambda\n \n #Select action with epsilon greedy policy\n def epsilonGreedy(self, x , avMoves): \n #Act Greedly\n if(random.random()>self.epsilon):\n return self.bestAction(x,avMoves)\n \n #Act Randomly\n else:\n return self.randomAction(x,avMoves) \n \n #Get the best action from nn forward pass to be performed by the agent\n def bestAction(self, x , avMoves):\n y_pred = self.network(x) #Action value for all actions in current state\n \n #Sorted action Q values in descending order\n sortedY, indices = torch.sort(y_pred,1, True)\n i = 0\n while(not avMoves[indices[0][i].data[0]]): #Pick best move available\n i+=1\n return indices[0][i].data[0] , y_pred #Return best action & output values\n \n #Select random action from all available moves\n def randomAction(self, x ,avMoves):\n y_pred = self.network(x) #Action value for all actions in current state\n \n possibleActions = []\n for i in range(len(avMoves)):\n if(avMoves[i]):\n possibleActions.append(i)\n index = random.randrange(0,len(possibleActions))\n return possibleActions[index] , y_pred #Return random action & output values\n\n #Correct neural network weights for current state and for previous states\n #Variables passed are \n #Elegibility Traces\n #Action taken in each state\n #Delta seen from last state\n #Discount factor for future rewards\n def updateWeights(self, E, A , delta, discount):\n for i in range(len(E)-1, -1, -1):\n y_pred = self.network(Variable(E[i], requires_grad=False))\n \n #Correct output value is modified by delta with respect to the original\n y = y_pred.clone() \n y.data[0][A[i]] += delta*(self._lambda * discount)**(len(E)-1-i) \n self.optimizer.zero_grad()\n loss = self.loss_fn(y_pred, Variable(y.data[0], requires_grad=False))\n loss.backward()\n","sub_path":"Connect4-TD/Approximator.py","file_name":"Approximator.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"106611563","text":"print(\"---- Questo programma serve a calcolare la media dei tuoi voti ----\")\r\nprint(\"\")\r\nnumEsami= int(input(\"Quanti esami hai sostenuto in totale? -> \"))\r\n\r\ncontatore = 0\r\nsomma = 0\r\nvotoMin = 0\r\nesami = [0] * numEsami\r\n\r\nvoto = int(input(\"Inserisci il primo voto -> \"))\r\ncontatore = contatore + 1\r\nif voto <= 30 and voto >= 18:\r\n somma = somma + voto\r\n votoMin = voto\r\n votoMax = voto\r\n esami[0] = voto\r\n maxEsami = esami[0]\r\nelse:\r\n print(\"Inserisci un voto valido!\")\r\n contatore = contatore - 1\r\n \r\nwhile contatore < numEsami:\r\n voto = int(input(\"Inserisci il prossimo voto -> \"))\r\n contatore = contatore + 1\r\n if voto <= 30 and voto >= 18:\r\n somma = somma + voto\r\n esami[contatore-1] = voto\r\n if votoMin > voto:\r\n votoMin = voto\r\n if voto > votoMax:\r\n votoMax = voto\r\n for voto in esami:\r\n if voto > maxEsami:\r\n maxEsami = voto\r\n else:\r\n print(\"Inserisci un voto valido!\")\r\n contatore = contatore - 1\r\n\r\nmedia = somma/numEsami\r\ncountEsami = esami.count(0)\r\nmoda = 0\r\nfor voto in esami:\r\n if esami.count(voto) > countEsami:\r\n countEsami = esami.count(voto)\r\n moda = voto\r\n##################################################\r\n\r\n#Sorting per max 24/11/16\r\nesami.sort()\r\nvotoSort = esami[0]\r\nmoda2 = esami[0]\r\nfreqMax = 1\r\ncontatore = 1\r\nfor i in range(1,len(esami)):\r\n if esami[i] == votoSort:\r\n contatore +=1\r\n else:\r\n if contatore > freqMax: #con il >= restituiamo il massimo voto piu' frequente\r\n freqMax = contatore\r\n moda2 = votoSort\r\n votoSort = esami[i]\r\n contatore = 1\r\nif contatore >= freqMax:\r\n moda2 = votoSort\r\n \r\n \r\nprint(votoSort, moda2, freqMax, contatore)\r\n\r\n##################################################\r\n \r\n\r\nprint(\"La media è\", media)\r\nprint(\"\")\r\nprint(\"Il voto massimo è\", votoMax)\r\nprint(\"\")\r\nif media <= 22:\r\n print(\"Impegnati di più! Puoi farcela!\")\r\nif media >= 23 and media <= 27:\r\n print(\"Non male per essere in questo corso! Fai uso di sostanze per il doping percaso?\")\r\nif media >=28 and media < 30:\r\n print(\"Rasenti la perfezione! Fantastico!\")\r\nif media >= 30:\r\n print(\"O stai imbrongliando, o con tutti questi 30 sei un fottuto genio! Bravo!\")\r\nprint(\"\")\r\nif votoMin <= 22:\r\n print(\"Quel\", votoMin, \"è in Analisi con Punzo, vero?\")\r\nprint(\"\")\r\nprint(\"\")\r\nprint(\"Riprenderemo il programma dopo una breve pausa. (cit.)\")\r\nprint(\"\")\r\nprint(\"esami: \", esami)\r\nprint(\"maxEsami: \", maxEsami)\r\nprint(\"countEsami: \", countEsami)\r\nprint(\"moda: \", moda)\r\n","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"444215723","text":"\"\"\"user author book tables\n\nRevision ID: 24286c9f7d9b\nRevises: \nCreate Date: 2019-12-10 00:10:15.478153\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '24286c9f7d9b'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('author',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('author_name', sa.String(length=128), nullable=True),\n sa.Column('isni', sa.String(length=16), nullable=True),\n sa.Column('date_of_birth', sa.String(length=32), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_author_author_name'), 'author', ['author_name'], unique=True)\n op.create_index(op.f('ix_author_isni'), 'author', ['isni'], unique=True)\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(length=64), nullable=True),\n sa.Column('email', sa.String(length=120), nullable=True),\n sa.Column('password_hash', sa.String(length=128), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)\n op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)\n op.create_table('book',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('book_name', sa.String(length=128), nullable=True),\n sa.Column('isbn', sa.String(length=13), nullable=True),\n sa.Column('date_published', sa.String(length=32), nullable=True),\n sa.Column('author_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['author_id'], ['author.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_book_book_name'), 'book', ['book_name'], unique=False)\n op.create_index(op.f('ix_book_isbn'), 'book', ['isbn'], unique=True)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_book_isbn'), table_name='book')\n op.drop_index(op.f('ix_book_book_name'), table_name='book')\n op.drop_table('book')\n op.drop_index(op.f('ix_user_username'), table_name='user')\n op.drop_index(op.f('ix_user_email'), table_name='user')\n op.drop_table('user')\n op.drop_index(op.f('ix_author_isni'), table_name='author')\n op.drop_index(op.f('ix_author_author_name'), table_name='author')\n op.drop_table('author')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/24286c9f7d9b_user_author_book_tables.py","file_name":"24286c9f7d9b_user_author_book_tables.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"219335466","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n path(\"blog_home/\", blog_home, name=\"blog_home\"),\n path(\"add_post/\", add_post, name=\"add_post\"),\n path(r'edit_post/', edit_post, name=\"edit_post\"),\n path(r'view_post/', view_post, name=\"view_post\"),\n path(r'delete_post/', delete_post, name=\"delete_post\"),\n path(r'add_comment/', add_comment, name=\"add_comment\"),\n path(r'delete_comment/', delete_comment, name=\"delete_comment\"),\n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"462923920","text":"#!/usr/bin/env python\n\"\"\"\na function to provide lumber cutting schemes optimized for maximal size of remaining pieces\n\n\"\"\"\n__author__ = \"ccluff\"\n\nfrom cutfinder.utils.board_sets import StockBoardSet, FinalBoardSet\nfrom cutfinder.utils.boards import StockBoard, FinalBoard\nfrom cutfinder.utils.utils import parse_arg\n\ntry:\n from collections.abc import Iterable # noqa\nexcept ImportError:\n from collections import Iterable\n\nfrom itertools import combinations\nfrom functools import partial\nfrom typing import Tuple, List\n\n\nKERF = 0.125\n\n\nclass CutFinder:\n \"\"\"Find best way to cut a group of final boards from a group of stock boards.\n Notes:\n -Including more than 15 stock boards or final boards could result in\n slow runtime as the number of possible combinations explodes\n -Best is defined as \"leaving the largest pieces\", i.e. leaving 10 is better than leaving 2x5\"\"\"\n\n def __init__(self, stocks: List, finals: List, kerf: float = KERF):\n self.stocks = StockBoardSet(stocks)\n self.finals = FinalBoardSet(finals)\n self.kerf: float = kerf\n\n self.remove_oversize_finals()\n\n while self.finals.unaddressed_boards and self.stocks.unaddressed_boards:\n find_lowest_waste = partial(\n self._find_lowest_waste, combos=list(self.all_combos_of_finals)\n )\n best = min(map(find_lowest_waste, self.stocks.unaddressed_boards))\n self.address(best)\n print(self)\n\n @property\n def all_combos_of_finals(self) -> Iterable:\n for i in range(1, len(self.finals.unaddressed_boards) + 1):\n yield from combinations(self.finals.unaddressed_boards, i)\n\n def _find_lowest_waste(self, stock: StockBoard, combos: List):\n best = (stock.length, tuple(), stock)\n for possible_group in combos:\n length_of_group = (\n sum(possible_group) + (len(possible_group) - 1) * self.kerf\n )\n\n if (\n stock.length >= length_of_group\n and stock.length - length_of_group < best[0]\n ):\n remainder = stock - length_of_group\n best = (remainder, possible_group, stock)\n return best\n\n def address(self, tup: tuple):\n \"\"\"address final boards to stock board\"\"\"\n remainder: float = tup[0]\n finals: Tuple[FinalBoard] = tup[1]\n stock: StockBoard = tup[2]\n\n stock.remainder = round(max([0.0, remainder - self.kerf]), 2)\n stock.used = True\n stock.addressed = True\n stock.cut_into.extend([board.length for board in finals])\n\n for final in finals:\n self.finals.boards[final.id].cut_into = stock.id\n self.finals.boards[final.id].used = True\n self.finals.boards[final.id].addressed = True\n\n def remove_oversize_finals(self):\n \"\"\"address any finals larger than the stock, we can't do anything for them\"\"\"\n longest_stock = max(self.stocks.boards.values())\n for id_, final in self.finals.boards.items():\n if final > longest_stock:\n self.finals.boards[id_].addressed = True\n\n def __repr__(self):\n out = \"\"\n if self.finals.unused_boards:\n unused = ', '.join(map(str, self.finals.unused_boards))\n out += f\"Unable to allocate final cuts: {unused}\\n\"\n for board in sorted(\n self.stocks.boards.values(), key=lambda y: y.remainder, reverse=True\n ):\n out += f\"Stock Board of length {board.length} is \"\n if board.cut_into:\n s = 's' if len(board.cut_into) > 1 else ''\n out += f\"cut into final board{s} {', '.join(map(str, board.cut_into))}\"\n out += f\" with remainder {board.remainder}\\n\"\n\n else:\n out += f\"uncut\"\n\n\n\n return out\n\n\nif __name__ == \"__main__\":\n import sys\n\n if len(sys.argv) > 1:\n CutFinder(*map(parse_arg, sys.argv[1:]))\n","sub_path":"cutfinder/cutfinder.py","file_name":"cutfinder.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"385397023","text":"import sys\nfrom optparse import OptionParser\n\n\ndef __init__(self):\n\n return None\n\n\ndef opts(self):\n\n parser = OptionParser(usage=\"python %prog -M [Select Mode] -L [IP list file anme] -T [Cycle times]\",\n version=\"1.0\")\n\n parser.add_option(\"-M\", \"--mode\", action=\"store\", dest=\"select_mode\",\n help=\"Select mode. AC, DC or Reboot.\", type=\"string\")\n parser.add_option(\"-L\", \"--list\", action=\"store\", dest=\"list_table\",\n help=\"Target IP list file name.\", type=\"string\")\n parser.add_option(\"-T\", \"--cycletimes\", action=\"store\", dest=\"times\",\n help=\"The testing cycle times.\", type=\"int\")\n\n (options, args) = parser.parse_args()\n\n if options.select_mode is None:\n parser.error(\"Missing the 'Select mode' argument (-M).\")\n sys.exit()\n if options.list_table is None:\n parser.error(\"Missing the 'Target IP list file name argument (-L).'\")\n sys.exit()\n if options.times is None:\n parser.error(\"Missing the 'Testing cycle times argument (-T).'\")\n sys.exit()\n\n mode = options.select_mode\n ip_list = options.list_table\n times = options.times\n\n return mode, ip_list, times\n","sub_path":"opts.py","file_name":"opts.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"168713235","text":"from flask import Blueprint\nfrom flask import request\nfrom flask import redirect\nfrom flask import url_for\nfrom flask import render_template as rt\nfrom flask_login import login_user\nfrom flask_login import logout_user\nfrom flask_login import login_required\nfrom flask_login import current_user\nfrom config import config\nimport os\nfrom utils import rest\nfrom models.users import *\nfrom models.task import *\nfrom models.message import *\nfrom mongoengine.queryset import Q\nfrom bson import ObjectId\n\nbp = Blueprint(\"customer_main\", __name__, url_prefix='/customer')\n\n\n@bp.route('/', methods=['GET', 'POST'])\ndef index():\n page = request.args.get('page', 1)\n query = dict(status=0)\n if current_user.is_authenticated:\n query['user__ne'] = current_user.id\n k = request.args.get('k', '')\n work_type = request.args.get('worktype', '')\n if work_type:\n query['work_type'] = work_type\n if k:\n pagination = CustomerTask.objects(Q(title__icontains=k) | Q(desc__icontains=k), **query).order_by(\n '-id').paginate(page, per_page=20)\n else:\n pagination = CustomerTask.objects(**query).order_by('-id').paginate(page, per_page=10)\n\n wts = WorkerType.objects.all()\n\n content = dict(\n pagination=pagination,\n wts=wts,\n )\n return rt('customer_main/index.html', **content)\n\n\n@bp.route('/index/task/', methods=['GET', 'POST'])\ndef index_task_detail(tid):\n c = CustomerTask.objects(id=tid).first()\n content = dict(\n c=c\n )\n\n return rt('customer_main/index_task_detail.html', **content)\n\n\n@bp.route('/task/detail', methods=['GET', 'POST'])\ndef task_detail():\n page = request.args.get('page', 1)\n status = request.args.get('status', 0, type=int)\n s = request.args.get('s', '')\n q = {}\n if status:\n q[\"status\"] = status\n if s:\n\n pagination = CustomerTask.objects(Q(title__icontains=s) | Q(desc__icontains=s), user=current_user.id,\n **q).paginate(page, per_page=20)\n else:\n pagination = CustomerTask.objects(user=current_user.id, **q).paginate(page, per_page=20)\n content = dict(\n pagination=pagination\n )\n return rt('customer_main/task_detail.html', **content)\n\n\n@bp.route('/add/task', methods=['GET', 'POST'])\ndef task_add():\n if request.method == 'POST':\n data = request.form\n c = CustomerTask()\n c.title = data['title']\n c.work_type = [ObjectId(i) for i in data.getlist('work_type[]')]\n c.work_time = float(data['work_time'])\n c.price = float(data['price'])\n c.desc = data['desc']\n c.images = data.getlist('images[]')\n c.user = current_user.id\n c.save()\n return rest.success(data={\"url\": url_for(\".task_detail\")})\n wts = WorkerType.objects.all()\n content = {\"wts\": wts}\n return rt('customer_main/task_add.html', **content)\n\n\n@bp.route('/edit/task/', methods=['GET', 'POST'])\ndef task_update(tid):\n c = CustomerTask.objects(user=current_user.id, id=tid).first()\n if request.method == 'POST':\n data = request.form\n c.title = data['title']\n c.work_type = [ObjectId(i) for i in data.getlist('work_type[]')]\n c.work_time = float(data['work_time'])\n c.price = float(data['price'])\n c.desc = data['desc']\n c.images = data.getlist('images[]')\n c.user = current_user.id\n c.save()\n return rest.success(data={\"url\": url_for(\".task_detail\")})\n\n wts = WorkerType.objects.all()\n content = {\"wts\": wts, \"c\": c}\n return rt('customer_main/task_update.html', **content)\n\n\n@bp.route('/task/success/', methods=['GET', 'POST'])\ndef task_success(tid):\n c = CustomerTask.objects(user=current_user.id, id=tid).first()\n if c:\n c.success()\n return rest.success('操作成功')\n\n\n@bp.route('/task/jieyue/