diff --git "a/2974.jsonl" "b/2974.jsonl" new file mode 100644--- /dev/null +++ "b/2974.jsonl" @@ -0,0 +1,651 @@ +{"seq_id":"243917478","text":"from pathlib import Path\nfrom setuptools import setup, find_packages\n\ntry:\n from squidpy import __email__, __author__, __version__, __maintainer__\nexcept ImportError:\n __author__ = __maintainer__ = \"Theislab\"\n __email__ = \", \".join(\n [\n \"giovanni.palla@helmholtz-muenchen.de\",\n \"hannah.spitzer@helmholtz-muenchen.de\",\n ]\n )\n __version__ = \"1.1.1\"\n\nsetup(\n name=\"squidpy\",\n use_scm_version=True,\n setup_requires=[\"setuptools_scm\"],\n version=__version__,\n author=__author__,\n author_email=__email__,\n maintainer=__author__,\n maintainer_email=__email__,\n description=Path(\"README_pypi.rst\").read_text(\"utf-8\").splitlines()[2],\n long_description=Path(\"README_pypi.rst\").read_text(\"utf-8\"),\n long_description_content_type=\"text/x-rst; charset=UTF-8\",\n url=\"https://github.com/theislab/squidpy\",\n download_url=\"https://pypi.org/project/squidpy/\",\n project_urls={\n \"Documentation\": \"https://squidpy.readthedocs.io/en/stable\",\n \"Source Code\": \"https://github.com/theislab/squidpy\",\n },\n license=\"BSD\",\n platforms=[\"Linux\", \"MacOSX\"],\n packages=find_packages(),\n zip_safe=False,\n install_requires=[l.strip() for l in Path(\"requirements.txt\").read_text(\"utf-8\").splitlines()],\n extras_require=dict(\n dev=[\"pre-commit>=2.9.0\", \"towncrier>=21.3.0\"],\n test=[\"tox>=3.20.1\", \"pytest-mock\"],\n docs=[\n l.strip()\n for l in (Path(\"docs\") / \"requirements.txt\").read_text(\"utf-8\").splitlines()\n if not l.startswith(\"-r\")\n ],\n interactive=[\"PyQt5>=5.15.0\", \"napari>=0.4.8,<0.5\"],\n ),\n classifiers=[\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Science/Research\",\n \"Natural Language :: English\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: POSIX :: Linux\",\n \"Operating System :: MacOS :: MacOS X\",\n \"Typing :: Typed\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Environment :: Console\",\n \"Framework :: Jupyter\",\n \"Intended Audience :: Science/Research\",\n \"Topic :: Scientific/Engineering :: Bio-Informatics\",\n \"Topic :: Scientific/Engineering :: Visualization\",\n ],\n keywords=sorted(\n [\n \"single-cell\",\n \"bio-informatics\",\n \"spatial transcriptomics\",\n \"spatial data analysis\",\n \"image analysis\",\n \"spatial data analysis\",\n ]\n ),\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603571218","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport cv2\nfrom albumentations import (\n Compose,\n GaussianBlur,\n CLAHE,\n RandomBrightness,\n RandomContrast,\n RandomSnow,\n RandomRain,\n RandomFog,\n RandomSunFlare,\n RandomShadow,\n CoarseDropout,\n Equalize,\n)\nfrom sklearn.utils import shuffle\n\n\ndef random_flip(image, steering_angle):\n if np.random.rand() < 0.5:\n return cv2.flip(image, 1), -steering_angle\n\n return image, steering_angle\n\n\ndef random_translate(image, steering_angle, range_x=100, range_y=100):\n trans_x = range_x * (np.random.rand() - 0.5)\n trans_y = range_y * (np.random.rand() - 0.5)\n result_steering_angle = steering_angle + trans_x * 0.002\n trans_m = np.float32([[1, 0, trans_x], [0, 1, trans_y]])\n h, w = image.shape[:2]\n result_image = cv2.warpAffine(image, trans_m, (w, h))\n\n return result_image, result_steering_angle\n\n\ndef augment_data(image, steering_angle):\n h, w = image.shape[:2]\n\n result_image = np.copy(image)\n result_steering_angle = steering_angle\n\n result_image, result_steering_angle = random_flip(result_image, result_steering_angle)\n # result_image, result_steering_angle = random_translate(result_image, result_steering_angle)\n aug = Compose(\n [\n # GaussianBlur(blur_limit=5, p=0.5),\n RandomBrightness(limit=0.1, p=0.5),\n RandomContrast(limit=0.1, p=0.5),\n # CLAHE(p=0.5),\n # Equalize(p=0.5),\n # RandomSnow(p=0.5),\n # RandomRain(p=0.5),\n # RandomFog(p=0.5),\n # RandomSunFlare(p=0.5),\n RandomShadow(p=0.5),\n CoarseDropout(\n max_holes=4,\n max_height=h // 30,\n max_width=w // 30,\n min_holes=1,\n min_height=h // 40,\n min_width=w // 40,\n p=0.5,\n ),\n ],\n p=1,\n )\n result_image = aug(image=result_image)[\"image\"]\n\n return result_image, result_steering_angle\n\n\nSTEERING_OFFSET = [0, 0.4, -0.4]\n\n\ndef choose_image(triple, steering_angle):\n no = np.random.randint(3)\n return triple[no], steering_angle + STEERING_OFFSET[no]\n\n\ndef batch_generator(triples, steering_angles, batch_size, is_training=True):\n total = len(triples)\n h, w, c = triples.shape[2:]\n\n result_images = np.empty([batch_size, h, w, c])\n result_steer_angles = np.empty(batch_size)\n while True:\n i = 0\n for idx in np.random.permutation(total):\n triple = triples[idx]\n steering_angle = steering_angles[idx]\n\n if is_training and np.random.rand() < 0.6:\n image, steering_angle = choose_image(triple, steering_angle)\n image, steering_angle = augment_data(image, steering_angle)\n else:\n image = triple[0]\n\n result_images[i] = image\n result_steer_angles[i] = steering_angle\n\n i += 1\n if i == batch_size:\n break\n\n yield result_images, result_steer_angles\n","sub_path":"data_loader/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"425338742","text":"from reportportal_client.core.rp_file import RPFile as RPFile\nfrom reportportal_client.core.rp_issues import Issue as Issue\nfrom reportportal_client.core.rp_responses import RPResponse as RPResponse\nfrom reportportal_client.static.abstract import AbstractBaseClass\nfrom reportportal_client.static.defines import Priority as Priority\nfrom typing import Any, Callable, ByteString, Dict, IO, List, Optional, Text, Union\n\nclass HttpRequest:\n session_method: Callable = ...\n url: Text = ...\n data = Optional[Union[Dict, List[Union[tuple, ByteString]], IO]] = ...\n json = Optional[Dict] = ...\n verify = Optional[bool] = ...\n def __init__(self,\n session_method: Callable,\n url: Text,\n data = Optional[Union[Dict, List[Union[tuple, ByteString, IO]]]],\n json = Optional[Dict],\n verify=Optional[bool]) -> None: ...\n def make(self) -> RPResponse: ...\n\n\nclass RPRequestBase(metaclass=AbstractBaseClass):\n __metaclass__: AbstractBaseClass = ...\n _http_request: Optional[HttpRequest] = ...\n _priority: Priority = ...\n _response: Optional[RPResponse] = ...\n def __init__(self) -> None: ...\n def __lt__(self, other: RPRequestBase) -> bool: ...\n @property\n def http_request(self) -> HttpRequest: ...\n @http_request.setter\n def http_request(self, value: HttpRequest) -> None: ...\n @property\n def priority(self) -> Priority: ...\n @priority.setter\n def priority(self, value: Priority) -> None: ...\n @property\n def response(self) -> Optional[RPResponse]: ...\n @response.setter\n def response(self, value: RPResponse) -> None: ...\n def payload(self) -> Dict: ...\n\nclass LaunchStartRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n mode: Text = ...\n name: Text = ...\n rerun: bool = ...\n rerun_of: Text = ...\n start_time: Text = ...\n uuid: Text = ...\n def __init__(self,\n name: Text,\n start_time: Text,\n attributes: Optional[List] = ...,\n description: Optional[Text] = ...,\n mode: Text = ...,\n rerun: bool = ...,\n rerun_of: Optional[Text] = ...,\n uuid: Optional[Text] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass LaunchFinishRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n end_time: Text = ...\n status: Text = ...\n def __init__(self,\n end_time: Text,\n status: Optional[Text] = ...,\n attributes: Optional[List] = ...,\n description: Optional[Text] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass ItemStartRequest(RPRequestBase):\n attributes: List = ...\n code_ref: Text = ...\n description: Text = ...\n has_stats: bool = ...\n launch_uuid: Text = ...\n name: Text = ...\n parameters: List = ...\n retry: bool = ...\n start_time: Text = ...\n type_: Text = ...\n uuid: Text = ...\n unique_id: Text = ...\n def __init__(self,\n name: Text,\n start_time: Text,\n type_: Text,\n launch_uuid: Text,\n attributes: Optional[List] = ...,\n code_ref: Optional[Text] = ...,\n description: Optional[Text] = ...,\n has_stats: bool = ...,\n parameters: Optional[List] = ...,\n retry: bool = ...,\n uuid: Optional[Any] = ...,\n unique_id: Optional[Any] = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass ItemFinishRequest(RPRequestBase):\n attributes: List = ...\n description: Text = ...\n end_time: Text = ...\n issue: Issue = ...\n launch_uuid: Text = ...\n status: Text = ...\n retry: bool = ...\n def __init__(self,\n end_time: Text,\n launch_uuid: Text,\n status: Text,\n attributes: Optional[List] = ...,\n description: Optional[Any] = ...,\n issue: Optional[Issue] = ...,\n retry: bool = ...) -> None: ...\n @property\n def payload(self) -> Dict: ...\n\nclass RPRequestLog(RPRequestBase):\n file: RPFile = ...\n launch_uuid: Text = ...\n level: Text = ...\n message: Text = ...\n time: Text = ...\n item_uuid: Text = ...\n def __init__(self,\n launch_uuid: Text,\n time: Text,\n file: Optional[RPFile] = ...,\n item_uuid: Optional[Text] = ...,\n level: Text = ...,\n message: Optional[Text] = ...) -> None: ...\n def __file(self) -> Dict: ...\n @property\n def payload(self) -> Dict: ...\n\nclass RPLogBatch(RPRequestBase):\n default_content: Text = ...\n log_reqs: List[RPRequestLog] = ...\n def __init__(self, log_reqs: List[RPRequestLog]) -> None: ...\n def __get_file(self, rp_file: RPFile) -> tuple: ...\n def __get_files(self) -> List: ...\n def __get_request_part(self) -> Dict: ...\n @property\n def payload(self) -> Dict: ...\n","sub_path":"reportportal_client/core/rp_requests.pyi","file_name":"rp_requests.pyi","file_ext":"pyi","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"30976393","text":"\"\"\"\n\n:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.\nThe source code contained or described here in and all documents related\nto the source code (\"Material\") are owned by Intel Corporation or its\nsuppliers or licensors. Title to the Material remains with Intel Corporation\nor its suppliers and licensors. The Material contains trade secrets and\nproprietary and confidential information of Intel or its suppliers and\nlicensors.\n\nThe Material is protected by worldwide copyright and trade secret laws and\ntreaty provisions. No part of the Material may be used, copied, reproduced,\nmodified, published, uploaded, posted, transmitted, distributed, or disclosed\nin any way without Intel's prior express written permission.\n\nNo license under any patent, copyright, trade secret or other intellectual\nproperty right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or\notherwise. Any license under such intellectual property rights must be express\nand approved by Intel in writing.\n\n:organization: INTEL MCG PSI\n:summary: Use Case WCDMA CLIP.\n:since: 19/03/2013\n:author: rbertolx\n\"\"\"\n\n# pylint: disable=C0103\n# Disable this pylint error due to ACS naming convention\n\nimport time\n\nfrom UtilitiesFWK.Utilities import Global\n\nfrom LAB_WCDMA_VC_BASE import LabWcdmaVcBase\n\n\nclass LabWcdmaVcClip(LabWcdmaVcBase):\n\n \"\"\"\n Class implementing the CLIP test.\n Setup: Build 3G connection with DUT.\n Test:\n step 1: turn the CLIP off on the network simulator.\n step 2: call the DUT from network simulator. (No need to answer the call)\n step 3: check in the call logs of the DUT that the call number has not\n been displayed.\n step 4: turn the CLIP on on the network simulator.\n step 5: call the DUT from network simulator. (No need to answer the call)\n step 6: check in the DUT call logs that the call number has been displayed.\n WARNING: does not test if the *#30# call returns the right info.\n \"\"\"\n\n def __init__(self, tc_name, global_config):\n \"\"\"\n Constructor\n \"\"\"\n\n # Call WCDMA voice call base Init function\n LabWcdmaVcBase.__init__(self, tc_name, global_config)\n\n self._phone_number = \\\n str(self._tc_parameters.get_param_value(\"PHONE_NUMBER\"))\n if self._phone_number.upper() == \"[PHONE_NUMBER]\":\n self._phone_number = str(self._device.get_phone_number())\n\n#------------------------------------------------------------------------------\n def run_test(self):\n \"\"\"\n Execute the test\n \"\"\"\n # Call WCDMA VoiceCall base run_test function\n LabWcdmaVcBase.run_test(self)\n # Release any previous call (Robustness)\n self._voice_call_api.release()\n # Turn off the CLIP.\n self._ns_voice_call_3g.include_calling_party_number(\"OFF\")\n # Calling the DUT from the network simulator.\n self._ns_voice_call_3g.mt_originate_call()\n # Waiting for the phone to receive the call, not need to answer the\n # call.\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n self._voice_call_api.wait_for_state(self._uecmd_types.\n VOICE_CALL_STATE.INCOMING,\n self._call_setup_time)\n # pylint: enable=E1101\n # Once the alerting state has been reached release the call on the\n # network simulator.\n self._ns_voice_call_3g.voice_call_network_release()\n time.sleep(self._wait_btwn_cmd)\n # Getting the last call information from DUT.\n (number, call_type, _sim) = self._voice_call_api.get_last_call_details()\n # Checking the last call type is missed.\n self._logger.info(\"Checking last call type is MISSED.\")\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n if call_type != str(self._uecmd_types.VOICE_CALL_TYPE.MISSED):\n # pylint: enable=E1101\n return (Global.FAILURE, \"Last call should be MISSED, is: %s\"\n % call_type)\n # Checking the last call number not displayed on the DUT.\n self._logger.info(\"Checking last call number is private\")\n # \"\" is the phone number returned when the number is unknown\n if number != \"\":\n return (Global.FAILURE, \"The CLIP is not included but the phone\"\n \" number was shown. Incoming number: %s\"\n % number)\n time.sleep(self._wait_btwn_cmd)\n # Turn the CLIP on.\n self._ns_voice_call_3g.include_calling_party_number(\"ON\")\n self._ns_voice_call_3g.set_calling_party_pi(\"ALLOWED\")\n # Set the phone number the network simulator will use to call the DUT.\n self._ns_voice_call_3g.set_calling_party_number(self._phone_number)\n # Calling the DUT from the network simulator.\n self._ns_voice_call_3g.mt_originate_call()\n # Waiting for the phone to receive the call, not need to answer the\n # call.\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n self._voice_call_api.wait_for_state(self._uecmd_types.\n VOICE_CALL_STATE.INCOMING,\n self._call_setup_time)\n # pylint: enable=E1101\n self._ns_voice_call_3g.voice_call_network_release()\n time.sleep(self._wait_btwn_cmd)\n # Getting the last call information from DUT.\n (number, call_type, _sim) = self._voice_call_api.get_last_call_details()\n # Checking the last call type is missed.\n self._logger.info(\"Checking last call type is MISSED.\")\n # pylint: disable=E1101\n # As pylint is not able to resolve enum types\n if call_type != str(self._uecmd_types.VOICE_CALL_TYPE.MISSED):\n # pylint: enable=E1101\n return (Global.FAILURE, \"Last call should be MISSED, is: %s\"\n % call_type)\n # Checking the last call number is the expected one.\n self._logger.info(\"Checking last call number is displayed on DUT and\"\n \" is the same as the one given as parameter.\")\n if number != self._phone_number:\n return (Global.FAILURE, \"The CLIP is included but the phone\"\n \" number shown on the DUT is not the same\"\n \" as the one set on the network\"\n \" simulator. Incoming number: %s\" % number)\n return Global.SUCCESS, \"No errors\"\n\n#------------------------------------------------------------------------------\n def tear_down(self):\n \"\"\"\n Closing the test.\n \"\"\"\n # Turn off the CLIP.\n self._ns_voice_call_3g.include_calling_party_number(\"OFF\")\n # Release all possible ongoing calls.\n self._ns_voice_call_3g.voice_call_network_release()\n # Call WCDMA VoiceCall base tear_down function\n LabWcdmaVcBase.tear_down(self)\n return Global.SUCCESS, \"No errors\"\n","sub_path":"ACS_v.18.20.4_1/ACS/acs_test_scripts/UseCase/Communication/VoiceCall/LAB_WCDMA_VC_CLIP.py","file_name":"LAB_WCDMA_VC_CLIP.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506944705","text":"class Solution:\n # @param A, a list of integers\n # @return a boolean\n def canJump(self, A):\n maxSteps = 0\n for i in range(len(A[:-1])):\n maxSteps = max(maxSteps - 1, A[i])\n if maxSteps < 1:\n return False\n return True\n","sub_path":"jump_game.py","file_name":"jump_game.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598344996","text":"import numpy as np\nfrom functools import partial\nfrom ompl import util as ou\nfrom ompl import base as ob\nfrom ompl import control as oc\nfrom ompl import geometric as og\nfrom scipy.integrate import odeint\n\nfrom gym_urbandriving.planning import Trajectory\n\n\n# Dynamics model for our car. Ydim of car should be 40 (default)\ndef integrator(state, t, acc, delta_f):\n x, y, vel, rad_angle = state\n # Differential equations\n beta = np.arctan((20. / (20. + 20.)) * np.tan(delta_f))\n dx = vel * np.cos(rad_angle + beta)\n dy = vel * -np.sin(rad_angle + beta)\n dangle = (vel / 20.) * np.sin(beta)\n dvel = acc\n output = [dx, dy, dvel, dangle]\n return output\n\nclass RRTMPlanner:\n def __init__(self, agents, planner=None, time=None, goal= None, prune = None, selection = None):\n \"\"\"\n A Kino-Dynamic Planner for multiple agents. \n \n Parameters\n ----------\n agents : list \n Agents to be planned over\n planner : str\n Type of Planner to use\n time : float\n Duration to run Planenr\n goal, prune, selection: float\n Parameters of planner, which can be searched over\n \"\"\"\n self.agents = agents\n self.num_agents = len(agents)\n\n self.path = []\n self.planner = planner\n self.time = time\n self.goal = goal\n self.prune = prune\n self.selection = selection\n\n\n def plan(self, state):\n \"\"\"\n Generate a plan for the agents\n \n Parameters\n ----------\n state : state of the enviroment\n The plan is generated starting at this state\n\n Returns:\n ----------\n paths: a list of Trajectories with mode 'cs' (ie. controls to generate the desired trajectory)\n If no trjaectory is found, returns None\n \"\"\"\n\n start_state = state\n # construct the state space we are planning in\n # State space will be [x, y, vel, angle]\n # Note: I found docs for ODEStateSpace and MorseStateSpace\n space = ob.RealVectorStateSpace(4*self.num_agents)\n \n \n # set the bounds for the R^2 part of SE(2)\n bounds = ob.RealVectorBounds(4*self.num_agents)\n \n for i in range(self.num_agents):\n car_idx = i*4\n bounds.setLow(car_idx, 0)\n bounds.setLow(car_idx+1, 0)\n bounds.setLow(car_idx+2, 0) # This is the velocity component. Set to a negative number to allow backtracking\n bounds.setLow(car_idx+3, 0)\n bounds.setHigh(car_idx+0, state.dimensions[0]) \n bounds.setHigh(car_idx+1, state.dimensions[1])\n bounds.setHigh(car_idx+2, 5)\n bounds.setHigh(car_idx+3, 2*np.pi)\n\n space.setBounds(bounds)\n\n # create a control space\n cspace = oc.RealVectorControlSpace(space, 2*self.num_agents)\n\n # set the bounds for the control space\n cbounds = ob.RealVectorBounds(2*self.num_agents)\n for i in range(self.num_agents):\n cbounds.setLow(-3.)\n cbounds.setHigh(3.)\n\n cspace.setBounds(cbounds)\n\n def isStateValid(spaceInformation, state):\n # perform collision checking or check if other constraints are\n # satisfied\n for i in range(self.num_agents):\n car_idx = i*4\n start_state.dynamic_objects[i].shapely_obj = None\n start_state.dynamic_objects[i].x = state[car_idx]\n start_state.dynamic_objects[i].y = state[car_idx+1]\n start_state.dynamic_objects[i].angle = state[car_idx+3]\n if start_state.collides_any(i):\n return False\n return spaceInformation.satisfiesBounds(state)\n\n def propagate(start, control, duration, state):\n # State propogator to allow ompl to step to another state given a list of actions\n assert(duration == 1.0)\n\n for i in range(self.num_agents):\n\n car_idx = i*4\n cntr_idx = i*2\n\n # Rest of these lines are from car kinematic step functions\n action = (control[cntr_idx], control[cntr_idx+1])\n obj = start_state.dynamic_objects[i]\n\n if obj.dynamics_model == \"kinematic\":\n state[car_idx], state[car_idx+1], state[car_idx+2], state[car_idx+3] = \\\n obj.kinematic_model_step(action, start[car_idx], start[car_idx+1], start[car_idx+2], start[car_idx+3])\n else:\n state[car_idx], state[car_idx+1], state[car_idx+2], state[car_idx+3] = \\\n obj.point_model_step(action, start[car_idx], start[car_idx+1], start[car_idx+2], start[car_idx+3])\n\n\n # define a simple setup class\n ss = oc.SimpleSetup(cspace)\n ss.setStateValidityChecker(ob.StateValidityCheckerFn(partial(isStateValid, ss.getSpaceInformation())))\n ss.setStatePropagator(oc.StatePropagatorFn(propagate))\n\n # create a start state\n start = ob.State(space)\n\n for i in range(self.num_agents):\n car_idx = i*4\n start()[car_idx] = state.dynamic_objects[i].x\n start()[car_idx+1] = state.dynamic_objects[i].y\n start()[car_idx+2] = state.dynamic_objects[i].vel\n start()[car_idx+3] = state.dynamic_objects[i].angle\n\n goal = ob.State(space);\n\n # create a goal state\n for i in range(self.num_agents):\n car_idx = i*4\n goal_state = state.dynamic_objects[i].destination\n \n goal()[car_idx] = goal_state[0]\n goal()[car_idx+1] = goal_state[1]\n goal()[car_idx+2] = goal_state[2]\n goal()[car_idx+3] = goal_state[3]\n\n\n # set the start and goal states\n ss.setStartAndGoalStates(start, goal, 0.05)\n # (optionally) set planner\n si = ss.getSpaceInformation()\n\n\n if self.planner == 'RRT':\n planner = oc.RRT(si) # this is the default\n elif self.planner == 'SST':\n planner = oc.SST(si)\n elif self.planner == 'EST':\n planner = oc.EST(si)\n elif self.planner == 'KPIECE':\n planner = oc.KPIECE1(si)\n else:\n planner = oc.RRT(si)\n\n if not self.selection is None:\n planner.setSelectionRadius(self.selection)\n if not self.prune is None:\n planner.setPruningRadius(self.prune)\n \n if not self.goal is None:\n planner.setGoalBias(self.goal)\n\n ss.setPlanner(planner)\n # (optionally) set propagation step size\n si.setPropagationStepSize(1) # Propagation step size should be 1 to match our model\n \n # attempt to solve the problem\n if not self.time == None:\n solved = ss.solve(self.time) # 30 second time limit\n else: \n solved = ss.solve(60.0)\n\n if solved:\n # prints the path to screen\n print(\"Found solution:\\n%s\" % ss.getSolutionPath())\n path = ss.getSolutionPath().printAsMatrix()\n path = [l.split(\" \") for l in path.splitlines()]\n\n num_controls = 2*self.num_agents+1\n \n path = [[float(i) for i in l][-num_controls:] for l in path][1:]\n paths = []\n for i in range(self.num_agents):\n car_idx = i*2\n agent_path = Trajectory(mode='cs')\n\n for control in path:\n for r in range(int(control[-1])):\n agent_path.add_point([control[car_idx],control[car_idx+1]])\n \n paths.append(agent_path)\n return paths\n else:\n return None\n \n \n\n \n \n","sub_path":"gym_urbandriving/planning/rrt_multi_planner.py","file_name":"rrt_multi_planner.py","file_ext":"py","file_size_in_byte":7819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162413594","text":"# ******************************************************\n# ✥ Title :- Python loops\n# ✥ Author :- Gautam Khatter 🧐\n# ✥ Date :- 28 December 2020\n# ******************************************************\n# ✥ Program to calculate the sum of all even numbers \n# 1-100 including 1 and 100\n# ******************************************************\n\n# For loops with range()\n#eg - for number in range(1, 10, 3):\n# print(number)\n# 1 - 10 is the range and 3 is the step size for this range.\n\nsum_even = 0\nfor even in range(0,101,2):\n sum_even += even\n\nprint(f\"The sum of even numbers b/w 1 and 100 is {sum_even}\")","sub_path":"Day 5/Coding-exercise5.3.py","file_name":"Coding-exercise5.3.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"423094989","text":"import heapq\n\n\nclass Solution(object):\n\n def rearrangeString(self, str, k):\n if not str:\n return str\n if k ==0:\n return str\n h = []\n d = {}\n for s in str:\n if s not in d:\n d[s] = 1\n else:\n d[s] += 1\n for key, value in d.items():\n heapq.heappush(h, (-value, key))\n\n ans = []\n l = len(str)\n while l > 0:\n temp = []\n iterationLength = min(l, k)\n if len(h) < iterationLength:\n return \"\"\n for i in range(iterationLength):\n (value, c) = heapq.heappop(h)\n ans.append(c)\n value += 1\n if value != 0:\n temp.append((value, c))\n l -= 1\n for i in temp:\n heapq.heappush(h, i)\n\n return \"\".join(ans)\n\n\ntestClass = Solution()\n\nprint(testClass.rearrangeString(\"aaadbbcc\", 2))\n","sub_path":"Google/358.py","file_name":"358.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591591196","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (c) 2005-2006 CamptoCamp\n# Copyright (c) 2006-2010 OpenERP S.A\n# Copyright (c) 2011 Thamini S.à.R.L\n#\n# WARNING: This program as such is intended to be used by professional\n# programmers who take the whole responsibility of assessing all potential\n# consequences resulting from its eventual inadequacies and bugs\n# End users who are looking for a ready-to-use solution with commercial\n# guarantees and support are strongly advised to contract a Free Software\n# Service Company\n#\n# This program is Free Software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n##############################################################################\n\nimport time\n\nfrom openerp.report import report_sxw\nfrom common_report_header import common_report_header\n\nclass report_partner_balance_common(report_sxw.rml_parse, common_report_header):\n def __init__(self, cr, uid, name, context):\n super(report_partner_balance_common, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n# 'get_salesperson': self.get_salesperson,\n# 'get_partner': self.get_partner,\n 'get_data': self.get_data,\n 'get_data_lines': self.get_data_lines,\n 'get_data_reconciled': self.get_data_reconciled,\n 'time': time,\n })\n self.context = context\n \n# def get_salesperson(self, data):\n# user_ids = []\n# # target_move = data['form'].get('target_move', 'all')\n# date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n# # \n# if data['form']['result_selection'] == 'customer':\n# account_type = ['receivable']\n# elif data['form']['result_selection'] == 'supplier':\n# account_type = ['payable']\n# else:\n# account_type = ['payable','receivable']\n# \n# user_ids = self._get_salesperson(account_type, date_from)\n# return self.pool.get('res.users').browse(self.cr, self.uid, user_ids)\n# \n# def get_partner(self, data):\n# partner_ids = []\n# target_move = data['form'].get('target_move', 'all')\n# date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n# \n# if data['form']['result_selection'] == 'customer':\n# account_type = ['receivable']\n# elif data['form']['result_selection'] == 'supplier':\n# account_type = ['payable']\n# else:\n# account_type = ['payable','receivable']\n# \n# partner_ids = self._get_partner(data['form'], account_type, date_from, target_move)\n# return self.pool.get('res.partner').browse(self.cr, self.uid, partner_ids)\n \n def get_data(self, partner, user_id, data):\n #print \"===get_data===\",partner\n self.total_account = []\n self.model = self.context.get('active_model')\n docs = self.pool.get(self.model).browse(self.cr, self.uid, self.context.get('active_id'))\n \n# target_move = data['form'].get('target_move', 'all')\n date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))\n date_to = data['form'].get('date_to', time.strftime('%Y-%m-%d'))\n if data['form']['result_selection'] == 'customer':\n account_type = ['receivable']\n elif data['form']['result_selection'] == 'supplier':\n account_type = ['payable']\n else:\n account_type = ['payable','receivable']\n\n #without_partner_movelines = self._get_move_lines_with_out_partner_sum(partner, user_id, data['form'], account_type, date_from, date_to)\n tot_list = self.total_account\n partner_movelines = self._get_partner_move_lines_sum(data['form'], account_type, date_to, 'posted')\n #print \"====partner_movelines====\",partner_movelines\n# for i in range(7):\n# self.total_account[i] += tot_list[i]\n movelines = partner_movelines# + without_partner_movelines\n docargs = {\n 'get_partner_lines': movelines,\n 'get_direction': self.total_account,\n }\n return docargs\n \n def get_data_lines(self, partner, result_selection, aml_ids):\n pay_lines = self._get_partner_move_lines_payment(partner, result_selection, aml_ids)\n return pay_lines\n \n def get_data_reconciled(self, result_selection, aml_id):\n rec_lines = self._get_partner_move_lines_reconciled(result_selection, aml_id)\n return rec_lines\n \n \n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"aos_partner_subsidiary_ledger/report/account_partner_balance.py","file_name":"account_partner_balance.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167243790","text":"# -*- coding: utf-8 -*-\n\"\"\"\n创建时间:Tue Feb 5 21:37:22 2019\n描述:展示不平衡的数据对模型的影响\n作者: PM.LiuGang\nReview:190311\n遗留:\n----------------------------------\nnp.random.multvariate_normal:\nmean = [0, 0]\ncov = [[1, 0], [0, 100]] # diagonal covariance\nimport matplotlib.pyplot as plt\nx, y = np.random.multivariate_normal(mean, cov, 5000).T\nplt.plot(x, y, 'x')\nplt.axis('equal')\nplt.show()\n\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport warnings\n\nfrom sklearn import metrics\nfrom sklearn.linear_model import LogisticRegression\n\nplt.rcParams[\"font.sans-serif\"] = [\"SimHei\"]\nwarnings.filterwarnings('ignore')\n\n\ndef generateData(n):\n '''\n 产生均衡的逻辑回归数据\n '''\n np.random.seed(4060)\n mean = [0,0]\n cov = [[1, 0], [0, 1]]\n # 生成多元正态分布矩阵 X.shape=(n,2)\n X = np.random.multivariate_normal(mean, cov, n) \n beta = np.array([1, -1]).reshape(2, 1)\n error = np.random.logistic(size=n).reshape(-1, 1)\n # Y.shape = (2000,1) true + 0 = 1;False + 0 = 0\n Y = (np.dot(X, beta) + error > 0) + 0 \n return X, Y\n\n\ndef unbalanceData(X, Y, zeroTimes):\n '''\n 通过将类别0的数据重复zeroTimes次,将均衡数据集变为非均衡数据集\n 平衡:Y=0 1010 X=0 990 非平衡:Y=0 1010 X=0 990*zeroTimes\n \n Parameters\n ----------\n X : np.ndarray\n 数据集-不含标签\n Y : np.ndarray\n 数据集的标签\n zeroTimes : int\n 数据重复的次数\n Returns\n -------\n X0X1 : np.ndarray\n 非平衡数据集-不含标签\n Y0Y1 : np.ndarray\n 非平衡数据集的标签\n '''\n # 为什么X0,Y0是(np.array,np.arrar)结构 \n # np.where的返回结果 np.where(condition)->tuple of ndarrays\n # np.where(Y==0)[0]取出索引(行数)\n X0 = np.repeat(X[np.where(Y == 0)[0]], zeroTimes, axis=0) # X0.shape = (990 * zeroTimes, 2)\n Y0 = np.repeat(Y[np.where(Y == 0)[0]], zeroTimes, axis=0) # Y0.shape =(990*n,1)\n X1 = X[np.where(Y > 0)[0]] # shape (1010,1)\n Y1 = Y[np.where(Y > 0)[0]]\n X0X1 = np.append(X0, X1, axis=0)\n Y0Y1 = np.append(Y0, Y1, axis=0)\n return X0X1, Y0Y1\n\n\ndef logitModel(X, Y):\n '''\n 搭建逻辑回归模型,并得到预测结果\n '''\n model = LogisticRegression(C=1e4) # 为了消除惩罚项的干扰,将惩罚系数设为很大\n model.fit(X, Y.ravel())\n pred = model.predict(X)\n return pred\n\n\ndef visualize(ratios, predPositive, truePositive, aucs, accuracies,\n title):\n '''\n 将模型可视化\n \n Parameters\n ----------\n ratios : [float,float,float,....,n(zeroTimes)]\n 原始数据集里Y>0的占比\n predPositive : np.array [int,int,int,...,n(zeroTimes)]\n 通过model预测标签Y>0的数目\n truePositive : np.array [int,int,int,...,n(zeroTimes)]\n 数据集中原始标签Y>0的数目\n aucs : [float,float,float,....,n(zeroTimes)]\n auc的面积\n accuracies : [float,float,float,....,n(zeroTimes)]\n auc的准确率\n Returns\n -------\n \n '''\n fig = plt.figure(figsize=(8, 3), dpi=80)\n ax = fig.add_subplot(1, 2, 1)\n plt.suptitle(title) # 图标总标题\n ax.plot(ratios, predPositive, label='%s' % '预测结果里类别1的个数')\n ax.plot(ratios, truePositive, 'k--', label='%s' % '原始数据集里类别1的个数')\n ax.set_xlabel(\"原始数据集Y>0的占比\")\n ax.set_ylabel(\"原始数据集Y>0的数量\")\n ax.set_xlim([0, 0.5])\n ax.invert_xaxis() # 将x或y轴逆序显示\n plt.legend(shadow=True, loc='best')\n\n ax1 = fig.add_subplot(1, 2, 2)\n ax1.plot(ratios, aucs, 'r', label='%s' % '曲线下的面积(AUC)')\n ax1.plot(ratios, accuracies, 'k-', label='%s' % '准确度(ACC)')\n ax1.set_xlabel(\"原始数据集Y>0的占比\")\n ax1.set_ylabel(\"Value\")\n ax1.set_xlim([0, 0.5])\n ax1.set_ylim([0.5, 1])\n ax1.invert_xaxis()\n plt.legend(shadow=True, loc='best')\n\n\ndef evaluateModel(Y, pred,title=None):\n '''\n 评估模型效果,其中包括ACC、AUC以及预测结果中类别1的个数\n \n Parameters\n ----------\n Y : np.array [array([]), array([]), array([]), array([])...]\n 数据集的类标签\n pred : np.array [array([]), array([]), array([]), array([])...]\n 模型预测数据的类标签 \n '''\n predPositive = [] \n truePositive = [] \n aucs = [] \n accuracies = [] \n ratios = [] \n for i in range(len(Y)):\n ratios.append(len(Y[i][Y[i] > 0]) / float(len(Y[i])))\n predPositive.append(len(pred[i][pred[i] > 0]))\n truePositive.append(len(Y[i][Y[i] > 0]))\n fpr, tpr, _ = metrics.roc_curve(Y[i], pred[i]) # fpr,tpr,_->array([x,x,x])\n accuracies.append(metrics.accuracy_score(Y[i], pred[i]))\n aucs.append(metrics.auc(fpr, tpr))\n visualize(ratios, predPositive, truePositive, aucs, accuracies,\n title=title)\n\n\ndef balanceData(X, Y):\n '''\n 通过调整各个类别的比重,解决非均衡数据集的问题\n '''\n positiveWeight = len(Y[Y > 0]) / float(len(Y))\n classWeight = {1: 1. / positiveWeight, \\\n 0: 1. / (1 - positiveWeight)}\n model = LogisticRegression(class_weight=classWeight, C=1e4)\n model.fit(X, Y.ravel())\n pred = model.predict(X)\n return pred\n\n\ndef imbalanceDataEffect():\n '''\n 展示非均衡数据集对搭建模型的影响\n '''\n X, Y = generateData(2000)\n trueY = []\n predY = []\n balancePredY = []\n for zeroTimes in np.arange(1, 100): # 为什么改成4,只有两幅图\n _X, _Y = unbalanceData(X, Y, zeroTimes)\n trueY.append(_Y) \n predY.append(logitModel(_X, _Y))\n balancePredY.append(balanceData(_X, _Y))\n evaluateModel(trueY, predY, title=\"非平衡数据集\")\n evaluateModel(trueY, balancePredY, title=\"平衡数据集\")\n\n\nif __name__ == '__main__':\n imbalanceDataEffect()\n","sub_path":"Desktop/myself/reader/数据科学_从线性回归到深度学习/p134.py","file_name":"p134.py","file_ext":"py","file_size_in_byte":5938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"592618096","text":"# coding: utf-8\n\n# Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual\n# ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações.\n\nuser = str(input(\"Nome de usuário: \"))\npwd = str(input(\"Senha: \"))\n\nwhile pwd == user:\n print(\"\\nSenha inválida. Não digite senha igual ao nome de usuário.\\n\")\n pwd = str(input(\"Senha: \"))\n","sub_path":"PythonBrasil/03_EstruturaDeRepeticao/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628096267","text":"from __future__ import absolute_import, print_function\n\nimport click\nimport signal\nfrom django.conf import settings\n\nfrom sentry.runner.decorators import configuration\n\n\n@click.command()\n@click.option('--topic', multiple=True, required=True,\n help='Topic(s) to consume from.')\n@click.option('--consumer-group', default='sentry-consumers',\n help='Consumer group name.')\n@click.option('--bootstrap-server', default=['localhost:9092'], multiple=True,\n help='Kafka bootstrap server(s) to use.')\n@click.option('--max-batch-size', default=10000,\n help='Max number of messages to batch in memory before committing offsets to Kafka.')\n@click.option('--max-batch-time-ms', default=60000,\n help='Max length of time to buffer messages in memory before committing offsets to Kafka.')\n@click.option('--auto-offset-reset', default='error', type=click.Choice(['error', 'earliest', 'latest']),\n help='Kafka consumer auto offset reset.')\n@configuration\ndef consumer(**options):\n from batching_kafka_consumer import BatchingKafkaConsumer\n from sentry.consumer import ConsumerWorker\n\n known_topics = {x['topic'] for x in settings.KAFKA_TOPICS.values()}\n topics = options['topic']\n for topic in topics:\n if topic not in known_topics:\n raise RuntimeError(\"topic '%s' is not one of: %s\" % (topic, known_topics))\n\n consumer = BatchingKafkaConsumer(\n topics=options['topic'],\n worker=ConsumerWorker(),\n max_batch_size=options['max_batch_size'],\n max_batch_time=options['max_batch_time_ms'],\n bootstrap_servers=options['bootstrap_server'],\n group_id=options['consumer_group'],\n auto_offset_reset=options['auto_offset_reset'],\n )\n\n def handler(signum, frame):\n consumer.signal_shutdown()\n\n signal.signal(signal.SIGINT, handler)\n\n consumer.run()\n","sub_path":"src/sentry/runner/commands/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"172576288","text":"#! python3\r\n\r\n'''\r\n解压被huffman编码后的文件\r\n'''\r\n\r\nimport sys\r\nfrom huffman import *\r\nfrom constant import * # 导入常量\r\n\r\ndef read_weights(fin):\r\n '''\r\n 读取频率表\r\n fin: 文件对象\r\n '''\r\n weights = [ int.from_bytes(fin.read(FOUR), 'little') for i in range(CHAR_NUM)]\r\n\r\n return weights\r\n\r\n\r\ndef decoding(fin, fout, root, total, num):\r\n '''\r\n 解码文件\r\n fin: 输入文件对象\r\n fout: 输出文件对象\r\n root: huffman树的根节点\r\n total: 要解码的串的长度(字节为单位)\r\n num: 最后一个字节的有效位数\r\n '''\r\n cur = root # cur指向当前节点\r\n for byte in range(total):\r\n code = int.from_bytes(fin.read(1), 'little') # 读入一个字节的编码串, 并转换为整数\r\n # debug{\r\n #print('code=%s' % code)\r\n #sys.exit()\r\n # }\r\n n = num if byte==total-1 else BYTE_SIZE\r\n for bit in range(n):\r\n if code & MASKS[bit]:\r\n # 此位为1, 向右子树移动\r\n cur = cur.right\r\n #print('cur = cur.right') # debug\r\n else:\r\n # 此为为0, 向左子树移动\r\n cur = cur.left\r\n #print('cur = cur.left') # debug\r\n \r\n if not (cur.left or cur.right):\r\n # 左右子树都为空, 表示到达叶节点\r\n char = cur.char\r\n #print(char)\r\n #sys.exit()\r\n fout.write(char.to_bytes(1, 'little'))\r\n cur = root # 重新从根节点开始\r\n \r\n\r\ndef decompress(input_file, output_file):\r\n '''\r\n input_file: 输入文件\r\n output_file: 输出文件\r\n '''\r\n fin = open(input_file, 'rb')\r\n fout = open(output_file, 'wb')\r\n\r\n fin.seek(-(FOUR*2),2) # 文件最后的8字节是编码串的长度(字节为单位),和最后一个字节编码的有效位数\r\n total = int.from_bytes(fin.read(FOUR), 'little')\r\n num = int.from_bytes(fin.read(FOUR), 'little')\r\n\r\n #print('total=%s, num=%s' % (total, num)) # debug\r\n\r\n # 读取字符的频率列表\r\n fin.seek(total, 0)\r\n weights = read_weights(fin)\r\n\r\n # debug{\r\n #logfile = input_file + '.log1'\r\n #with open(logfile, 'w') as fd:\r\n # fd.write(str(weights))\r\n # }\r\n\r\n # 构建huffman树\r\n huff_tree = HuffTree()\r\n huff_tree.build_huffman_tree(weights)\r\n\r\n #print('huff_tree.root.right.char=%s' % huff_tree.root.right.char) # debug\r\n\r\n #print('huff_tree.root.right(%s,%s)' % (huff_tree.root.right.left, huff_tree.root.right.right) ) # debug\r\n\r\n # 解码后输出到输出文件\r\n fin.seek(0, 0)\r\n decoding(fin, fout, huff_tree.root, total, num)\r\n\r\n fin.close()\r\n fout.close()\r\n\r\n print('%s decompress as %s' % (input_file, output_file) )\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 2:\r\n print('usage: python %s file_name' % sys.argv[0])\r\n sys.exit()\r\n \r\n input_file = sys.argv[1]\r\n output_file = input_file.rsplit('.', 1)[0] # \r\n decompress(input_file, output_file)","sub_path":"decompress.py","file_name":"decompress.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386737896","text":"#!/usr/bin/python\n# coding:utf-8\n''' dis '''\ndef dis_shortest_path(graph):\n vnum = graph.vertex_num()\n paths = [None]*vnum\n count = 0\n cands=PrioQueue([(0,v0,v0)])\n while count < vnum and not cands.is_empty():\n plen,u,vmin = cands.dequeue()\n if paths[vmin]:\n continue\n paths[vmin]=(u,plen) #v0到vmin的前一个顶点是u,最短路径是plen\n for v,w in graph.out_edges(vmin):\n if not path[v]:\n cands.enqueue((plen+w,vmin,v))\n count += 1\n return paths\n\n\n\n \n","sub_path":"application/dis.py","file_name":"dis.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322538183","text":"from datetime import timedelta\nfrom celery.schedules import crontab\n\nCELERYBEAT_SCHEDULE = {\n 'ptask': {\n 'task': 'tasks.period_task',\n 'schedule': timedelta(seconds=5),\n },\n}\n\nCELERY_RESULT_BACKEND = 'redis://localhost:6379/0'\nCELERY_TIMEZONE = 'Asia/Shanghai'","sub_path":"distributed-queue/celery_config.py","file_name":"celery_config.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"456347733","text":"import discord\nimport asyncio\nfrom discord.ext import commands\nfrom discord import FFmpegPCMAudio\nimport random\n\n\nclass JayCog(commands.Cog):\n\n client = discord.Client()\n\n def __init__(self, bot):\n self.bot = bot\n self.bot_message = None\n self.ready = None\n\n # commands for your cog go here\n @commands.command()\n async def rps(self, ctx, rlt : str):\n possible = [\"rock\", \"paper\", \"scissors\"]\n r_choice = random.choice(possible)\n if rlt:\n if rlt == 'rock':\n if r_choice == 'paper':\n await ctx.send('I won! I picked '+r_choice)\n elif r_choice == 'scissors':\n await ctx.send('I lost :( I picked '+r_choice)\n\n elif rlt == 'paper':\n if r_choice == 'rock':\n await ctx.send('I lost :( I picked '+r_choice)\n elif r_choice == 'scissors':\n await ctx.send('I won! I picked '+r_choice)\n\n elif rlt == 'scissors':\n if r_choice == 'rock':\n await ctx.send('I won! I picked '+r_choice)\n elif r_choice == 'paper':\n await ctx.send('I lost :( I picked '+r_choice)\n\n elif rlt == r_choice:\n await ctx.send('Draw!')\n else:\n await ctx.send('You must write rock, paper or scissors')\n else:\n await ctx.send('You must write rock, paper or scissors')\n\n @commands.command(aliases=[\"pt\", \"piano\", \"playpiano\"])\n async def pianotime(self, ctx):\n self.ready = False\n try:\n vc = ctx.message.author.voice.channel\n self.vcl = await vc.connect()\n except:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=ctx.message.author.avatar_url, name=ctx.message.author.display_name + \", you're not in a vc! Please connect to one before playing the piano\")\n await ctx.send(embed=embed)\n return\n\n self.notes = ['🎹', '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬']\n msg = \"\"\"Heyy {} it's Piano Time! It's Discord's Hack Week, Let's get Frizzy! \n \n Reactions: \n :musical_keyboard:\n :regional_indicator_a:\n :regional_indicator_b:\n :regional_indicator_c:\n :regional_indicator_d:\n :regional_indicator_e:\n :regional_indicator_f:\n :regional_indicator_g:\n\n React to this message to play!\"\"\".format(ctx.message.author.display_name)\n embed = discord.Embed(description=msg)\n embed.set_author(icon_url=ctx.message.author.avatar_url, name=ctx.message.author.display_name + \" brought a piano!\")\n embed.colour = ctx.message.author.colour if hasattr(ctx.message.author, \"colour\") else discord.Colour.default()\n self.bot_message = await ctx.send(embed=embed)\n\n for note in self.notes:\n await self.bot_message.add_reaction(note)\n\n \n \n source = FFmpegPCMAudio('music/better sounds/call_ringing_beat.wav')\n self.vcl.play(source)\n await ctx.send(\"You will be able to play in just a sec ;)\")\n await asyncio.sleep(12)\n self.ready = True\n \n @commands.command(aliases=[\"stop\"]) \n async def pianostop(self, ctx):\n await self.vcl.disconnect()\n\n\n @commands.Cog.listener()\n async def on_reaction_add(self, reaction, user):\n if not reaction.message == self.bot_message and not self.ready:\n return\n \n if reaction.emoji not in self.notes:\n await reaction.remove(user)\n\n if not user.voice.channel.id:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=user.avatar_url, name=user.display_name + \", you're not in a vc! Please connect to one before playing the piano\")\n await reaction.message.channel.send(embed=embed)\n\n try:\n if reaction.emoji == \"🎹\":\n g3 = FFmpegPCMAudio('music/better sounds/c5.wav')\n self.vcl.play(g3)\n\n elif reaction.emoji == \"🇦\":\n a4 = FFmpegPCMAudio('music/better sounds/d5.wav')\n self.vcl.play(a4)\n\n elif reaction.emoji == \"🇧\":\n b4 = FFmpegPCMAudio('music/better sounds/e5.wav')\n self.vcl.play(b4)\n\n elif reaction.emoji == \"🇨\":\n c4 = FFmpegPCMAudio('music/better sounds/f5.wav')\n self.vcl.play(c4)\n\n elif reaction.emoji == \"🇩\":\n d4 = FFmpegPCMAudio('music/better sounds/g5.wav')\n self.vcl.play(d4)\n\n elif reaction.emoji == \"🇪\":\n e4 = FFmpegPCMAudio('music/better sounds/a6.wav')\n self.vcl.play(e4)\n\n elif reaction.emoji == \"🇫\":\n f4 = FFmpegPCMAudio('music/better sounds/b6.wav')\n self.vcl.play(f4)\n\n elif reaction.emoji == \"🇬\":\n g4 = FFmpegPCMAudio('music/better sounds/c6.wav')\n self.vcl.play(g4)\n except discord.errors.ClientException:\n pass\n\n\n @commands.Cog.listener()\n async def on_reaction_remove(self, reaction, user):\n if not reaction.message == self.bot_message and not self.ready:\n return\n\n if not user.voice.channel.id:\n embed = discord.Embed(colour=0xff0000)\n embed.set_author(icon_url=user.avatar_url, name=user.display_name + \"You're not in a vc! Please connect to one before playing the piano\")\n await reaction.message.channel.send(embed=embed)\n try:\n if reaction.emoji == \"🎹\":\n c5 = FFmpegPCMAudio('music/better sounds/c5.wav')\n self.vcl.play(c5)\n\n elif reaction.emoji == \"🇦\":\n d5 = FFmpegPCMAudio('music/better sounds/d5.wav')\n self.vcl.play(d5)\n\n elif reaction.emoji == \"🇧\":\n e5 = FFmpegPCMAudio('music/better sounds/e5.wav')\n self.vcl.play(e5)\n\n elif reaction.emoji == \"🇨\":\n f5 = FFmpegPCMAudio('music/better sounds/f5.wav')\n self.vcl.play(f5)\n\n elif reaction.emoji == \"🇩\":\n g5 = FFmpegPCMAudio('music/better sounds/g5.wav')\n self.vcl.play(g5)\n\n elif reaction.emoji == \"🇪\":\n a6 = FFmpegPCMAudio('music/better sounds/a6.wav')\n self.vcl.play(a6)\n\n elif reaction.emoji == \"🇫\":\n b6 = FFmpegPCMAudio('music/better sounds/b6.wav')\n self.vcl.play(b6)\n\n elif reaction.emoji == \"🇬\":\n c6 = FFmpegPCMAudio('music/better sounds/c6.wav')\n self.vcl.play(c6)\n except discord.errors.ClientException:\n pass\n \n\n \ndef setup(bot):\n bot.add_cog(JayCog(bot))\n","sub_path":"cogs/jaycog.py","file_name":"jaycog.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350063918","text":"# Pratham Darooka\n\nprint(\"Welcone to PD's Echo Bot! I will repeat anything you say.\")\n\nto_echo = \"\"\n\nwhile(to_echo != \"-1\"):\n to_echo = input(\"What would you like me to repeat? (Enter -1 to quit) \")\n if(to_echo != \"-1\"):\n print(\"You said: \" + to_echo)\n\n# END\n","sub_path":"src/cpp/Project_Echobot/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268378271","text":"def solution(N, stages):\r\n answer = []\r\n fail = {}\r\n n_user = len(stages)\r\n for i in range(1, N+1):\r\n if(stages.count(i)==0):\r\n fail[i] = 0.0\r\n else:\r\n fail[i] = stages.count(i)/n_user\r\n n_user -= stages.count(i)\r\n answer = sorted(fail, key=lambda x: fail[x],reverse=True)\r\n \r\n return answer\r\n\r\nif __name__ == \"__main__\":\r\n print(solution(5, [2, 1, 2, 6, 2, 4, 3, 3]))\r\n print(\"=========================\")\r\n print(solution(4, [4,4,4,4,4]))","sub_path":"ACM/Programmers/pythoncode/42889.py","file_name":"42889.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"640757652","text":"#coding:utf-8\nimport requests\nimport unittest\nfrom common.login import LG\nfrom common.logger import Log\nclass Test_pay(unittest.TestCase):\n def setUp(self):\n self.s = requests.session()\n self.lgin = LG(self.s) #实例化登录类\n self.uid_token = self.lgin.gettoken_loginbyUID() #直接取第二部登录\n self.header = {'User-Agent': 'LanTingDoctor/1.3.1 (iPad; iOS 10.1.1; Scale/2.00)',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-Hans-CN;q=1',\n 'Content-Type': 'application/json',\n 'requestApp': '3',\n 'requestclient': '2',\n 'versionForApp': '2.0',\n 'Authorization': 'Basic YXBpTGFudGluZ0BtZWRsYW5kZXIuY29tOkFwaVRobWxkTWxkQDIwMTM=',\n 'Connection': 'keep-alive'}\n self.log = Log()\n def test_pay(self):\n u'测试支付接口,已购买的课程,去支付'\n self.log.info('开始测试支付接口,已购买的课程,去支付')\n url = 'http://api.exam.wrightin.com/v1/mldProductPay'\n json_data = {\"payType\":\"0\",\n \"product_type\":\"2\",\n \"token\":self.uid_token,\n \"product_code\":\"K00001\"\n }\n r = self.s.post(url,headers = self.header,json=json_data)\n print(r.json())\n global out_trad_num #设置为全局变量供下一case调用\n out_trad_num= r.json()['data']\n #print(out_trad_num)\n #global order_id\n #order_id = r.json()['data']['order_id']\n self.assertEqual('您已购买 不能重复购买',r.json()['note'],msg='支付请求状态不是200')\n self.log.info('支付接口,已购买的课程,去支付测试结束')\n\n def test_pay(self):\n u'测���支付接口,未购买的课程,去支付'\n self.log.info('开始测试支付接口,未购买的课程,去支付')\n url = 'http://api.exam.wrightin.com/v1/mldProductPay'\n\n json_data = {\"payType\":\"0\",\n \"product_type\":\"2\",\n \"token\":self.uid_token,\n \"product_code\":\"K00008\"\n }\n\n r = self.s.post(url,headers = self.header,json=json_data)\n print(r.json())\n global out_trad_num #设置为全局变量供下一case调用\n out_trad_num= r.json()['data']\n self.assertEqual('请求成功.',r.json()['note'],msg='支付请求状态没成功')\n self.log.info('支付接口,未购买的课程,去支付测试结束')\n\n\n def test_pay_success(self):\n u'测试支付后的确认接口(未支付的orderid)'\n self.log.info('测试支付后的确认接口(未支付的orderid)')\n url = 'http://api.exam.wrightin.com/v1/mldProductPaySucessReq'\n\n json_data = {\"payType\":\"0\",\n \"out_trade_no\":\"\",\n \"token\":self.uid_token,\n \"orderid\":\"309251BA4A7C9A2C95C0F0A908DD3D66\"\n }\n\n r = self.s.post(url,headers=self.header,json=json_data)\n #print('未支付',r.json())\n self.assertEqual(201,r.json()['code'],msg=('未支付的orderid,支付确认接口有问题'))\n self.log.info('支付后的确认接口(未支付的orderid)测试结束')\n def tearDown(self):\n self.s.close()\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"case/Lesson/testPaySuccess.py","file_name":"testPaySuccess.py","file_ext":"py","file_size_in_byte":3477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"191876391","text":"t = open('corpus.txt', encoding='iso-8859-1').read()\nd = {'a':0, 'b':0, 'd':0, 'e':0, 'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0, 'nh':0, 'o':0, 's':0, 'u':0, 'v':0, 'w':0, 'y':0, 'z':0}\nw = 0\ns = 0\nn = False\nfor c in t:\n\t\tif c in 'AaÁá':\n\t\t\t\td['a'] += 1\n\t\tif c in 'BbPp': # misspelling-friendly\n\t\t\t\td['b'] += 1\n\t\tif c in 'DdTt': # this is the most frequent one\n\t\t\t\td['d'] += 1\n\t\tif c in 'EeÉé':\n\t\t\t\td['e'] += 1\n\t\tif c in 'Hh':\n\t\t\t\tif n:\n\t\t\t\t\t\td['n'] -= 1\n\t\t\t\t\t\td['nh'] += 1\n\t\t\t\t\t\tn = False\n\t\t\t\telse:\n\t\t\t\t\t\td['h'] += 1\n\t\tif c in 'IiÍí':\n\t\t\t\td['i'] += 1\n\t\tif c in 'Jj':\n\t\t\t\td['j'] += 1\n\t\tif c in 'KkGg':\n\t\t\t\td['k'] += 1\n\t\tif c in 'LlRr':\n\t\t\t\td['l'] += 1\n\t\tif c in 'Mm':\n\t\t\t\td['m'] += 1\n\t\tif c in 'Nn':\n\t\t\t\td['n'] += 1\n\t\t\t\tn = True\n\t\t\t\tcontinue\n\t\tif c in 'OoÓó':\n\t\t\t\td['o'] += 1\n\t\tif c in 'Ss':\n\t\t\t\td['s'] += 1\n\t\tif c in 'UuÚú':\n\t\t\t\td['u'] += 1\n\t\tif c in 'VvFf':\n\t\t\t\td['v'] += 1\n\t\tif c in 'Ww':\n\t\t\t\td['w'] += 1\n\t\tif c in 'YyÝý':\n\t\t\t\td['y'] += 1\n\t\tif c in 'Zz':\n\t\t\t\td['z'] += 1\n\t\tif c == ' ':\n\t\t\t\tw += 1\n\t\tif c == '\\n':\n\t\t\t\tw += 1\n\t\t\t\ts += 1\n\t\tn = False\nif __name__ == '__main__':\n\t\tt = sum(d.values())\n\t\tprint('Frequencies in alphabetical order:')\n\t\tfor i in d:\n\t\t\t\tp = str(round(d[i] / t * 10000))\n\t\t\t\tprint('{}: {} ({}%)'.format(i, d[i], p[:-2] + '.' + p[-2:]))\n\t\tprint('Frequencies in frequency order:')\n\t\tfor i in reversed(sorted(d, key=d.get)):\n\t\t\t\tp = str(round(d[i] / t * 10000))\n\t\t\t\tprint('{}: {} ({}%)'.format(i, d[i], p[:-2] + '.' + p[-2:]))\n\t\tprint('Number of words:', w)\n\t\tprint('Number of sentences:', s)\n","sub_path":"corpus_analyzer.py","file_name":"corpus_analyzer.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470076024","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport json\nimport sys\nfrom bs4 import BeautifulSoup\n\n\ndef create_result_object():\n tmp = dict()\n tmp['lists'] = list()\n tmp['error'] = False\n tmp['error_msg'] = ''\n return tmp\n\n\ndef search_for_movies(movie_name):\n \"\"\"\n 输入电影英文名,通过filmxy进行查找\n :param string movie_name: must be english, and must be separated by space between each word\n :return:\n \"\"\"\n url_search_page = 'http://www.filmxy.com/?s=%s&quality=&genre=&song=' % movie_name.replace(' ', '+')\n request_search_page = requests.get(url_search_page)\n soup_search_page = BeautifulSoup(request_search_page.text, \"html.parser\")\n\n return_object = create_result_object()\n tmp_list = return_object['lists']\n # 每个查找结果包含一个电影\n # 查找结果格式如下\n #
......
\n movie_cover = each.find('div', class_='post-thumb').img['src']\n\n # 查找前往电影主页面的URL\n # 格式如下 ...\n url_to_movie_page = each.find('a', class_='par-link')['href']\n tmp_list.append({'cover': movie_cover, 'url': url_to_movie_page})\n\n return return_object\n\n\nif __name__ == \"__main__\":\n print(json.dumps(search_for_movies(sys.argv[1])))\n","sub_path":"python-verysimple-crawler/GetFilm/search_film.py","file_name":"search_film.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"569984148","text":"from transcriptic.protocol import Protocol, Ref, Incubate, Pipette\nfrom transcriptic.api import Connection\n\nprotocol = Protocol()\n\nmutant1 = protocol.ref_new('mutant1', 'micro-1.5', storage='cold_4')\nmutant2 = protocol.ref_new('mutant2', 'micro-1.5', storage='cold_4')\nmutant3 = protocol.ref_new('mutant3', 'micro-1.5', storage='cold_4')\nmutant4 = protocol.ref_new('mutant4', 'micro-1.5', storage='cold_4')\nenzyme = protocol.ref_new('enzyme', '96-flat', storage='ambient')\nsubstrate = protocol.ref_new('substrate', '96-flat', storage='cold_20')\ntrash = protocol.ref_new('trash', '96-deep', discard=True) \n\n#thaw a pre-made 96-well substrate plate \nprotocol.incubate('substrate', 'ambient', '15:minute')\n\n#aliquot mutants\nprotocol.distribute(\n mutant1.well(0), \n enzyme.wells_from('A1', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant2.well(0), \n enzyme.wells_from('A4', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant3.well(0), \n enzyme.wells_from('A7', 24, columnwise=True), \n '25:microliter', )\n\nprotocol.distribute(\n mutant4.well(0), \n enzyme.wells_from('A10', 24, columnwise=True), \n '25:microliter', )\n\n#generalize to \n# for i, mutant in mutants \n# distribute(mutant.well(0),enzyme.wells(i*4,24,columnwise=True),'25:microliter')\n\n# initiate reaction\n# how long will this take? \n# ideally < 100 s \nprotocol.transfer(\n substrate.all_wells(),\n enzyme.all_wells(),\n '25:microliter',\n mix_after=True,\n mix_vol=\"25:microliter\",\n repetitions=2, )\n\n# 20 reads \nfor i in range(1,21):\n protocol.absorbance('enzyme', enzyme.all_wells(),\n '420:nanometer', 'data%s' % i)\n protocol.incubate('enzyme', 'ambient', '30:second')\n\n#submit\nconn = Connection().organization('siegel-lab-uc-davis')\nconn.project('p177ufku98k8j').submit(protocol, title=\"Bagel assay\")\n","sub_path":"bagel-assay.py","file_name":"bagel-assay.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101087417","text":"#!/usr/local/bin/python3\n# Scores 23.53/100\nINF = float('inf')\ndef getLine(func):\n return list(map(func, input().split()))\n\ndef getEdge():\n l = input().split()\n na = l[0]\n nb = l[1]\n dist = int(l[2])\n return (na, nb, dist)\n\ndef makeGraph(nodes, edges, graph):\n for edge in edges:\n na = nodes.index(edge[0])\n nb = nodes.index(edge[1])\n graph[na][nb] = edge[2]\n return\n\ndef dijkstras(graph, source):\n n = len(graph)\n visited = [False for i in range(n)]\n tovisit = [source]\n dist = [INF for i in range(n)]\n dist[source] = 0\n while len(tovisit) > 0:\n u = tovisit.pop()\n if (visited[u]):\n continue\n visited[u] = True\n for i in range(n):\n if graph[u][i]:\n tovisit.append(i)\n if dist[i] > graph[u][i] + dist[u]:\n dist[i] = graph[u][i] + dist[u]\n return dist\n\nif __name__ == \"__main__\":\n # Input problem\n line = getLine(int)\n n = line[0]\n m = line[1]\n k = line[2]\n nodes = getLine(str)\n edges = [getEdge() for _ in range(m)]\n path = getLine(str)\n\n\n # Make Adjacency Matrix\n graph = [[None for _ in range(n)] for _ in range(n)]\n for i in range(n):\n graph[i][i] = 0\n makeGraph(nodes, edges, graph)\n # print(graph)\n\n # Make precomputed Dijkstras Matrix\n #efficientGraph = [dijkstras(graph, i) for i in range(n)]\n # print(efficientGraph)\n\n # Calculate Costs\n cost = 0\n\n prev = path[0]\n cost = 0\n for next_ in path:\n i = nodes.index(prev)\n j = nodes.index(next_)\n cost += dijkstras(graph, i)[j]#efficientGraph[i][j]\n prev = next_\n print(cost)\n\n","sub_path":"pineapple-service/solutions/solution_inefficient.py","file_name":"solution_inefficient.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258633396","text":"from xlrd import open_workbook\nfrom xlutils.copy import copy\nimport re\n\n#lembrar de converter os arquivos xlsx para xls\n\n#IO excel antigo\nwb = open_workbook(r'C:\\Users\\carmando\\Documents\\Dev\\excel\\UNIFOR-CUCM7.xls')\nxl_sheet = wb.sheet_by_index(0)\nnrows0 = xl_sheet.nrows-1\nncols0 = xl_sheet.ncols-1\n#IO excel novo\nwb1 = open_workbook(r'C:\\Users\\carmando\\Documents\\Dev\\excel\\UNIFOR-CUCM11.xls')\nxl_sheet1 = wb1.sheet_by_index(0)\nnrows1 = xl_sheet1.nrows-1\nncols1 = xl_sheet1.ncols-1\n\n#returnline('valor', numerodalinha, xl_sheet ou xl_sheet1)\ndef returnline(sep, rows, sheet):\n\tfor i in range(rows):\n\t\tif sheet.cell(i,1).value == sep:\n\t\t\treturn i\n\treturn False\n\nfor j in range(nrows0):\n\tgetdata = xl_sheet.cell(j, 1).value\n\tif j != 0:\n\t\t#getdata = re.sub(r'\\.0', '', str(getdata))\n\t\tif not returnline(getdata, nrows1, xl_sheet1):\n\t\t\tgetdata = re.sub(r'\\.0', '', str(getdata))\n\t\t\tprint(str(getdata) + \" não está na planilha nova.\")\n#print(j)","sub_path":"old/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"636077050","text":"from uuid import UUID\n\nimport typer\n\n\ndef main(user_id: UUID):\n typer.echo(f\"USER_ID is {user_id}\")\n typer.echo(f\"UUID version is: {user_id.version}\")\n\n\nif __name__ == \"__main__\":\n typer.run(main)\n","sub_path":"docs_src/parameter_types/uuid/tutorial001.py","file_name":"tutorial001.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623100632","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport datetime\nimport khayyam\nfrom base_app.classes.debug import Debug\nfrom admin_app.handlers.base import BaseHandler\nfrom base_app.models.mongodb.about_us.about_us import AboutUsModel\n\n__author__ = 'Morteza'\n\n\nclass AdminGeneralSettingsAboutUsHandler(BaseHandler):\n def get(self):\n self.data['now'] = datetime.datetime.now()\n self.render('admin/admin_settings/about_us.html', **self.data)\n\n def post(self):\n try:\n d = dict()\n self.check_sent_value(\"start-date\", d, \"start_date\", u\"تاریخ شروع را وارد کنید.\")\n self.check_sent_value(\"end-date\", d, \"end_date\", u\"تاریخ پایان را وارد کنید.\")\n self.check_sent_value(\"body\", d, \"body\", u\"محتوای صفحه را وارد کنید.\")\n if not len(self.errors):\n from scrubber import Scrubber\n d['body'] = Scrubber().scrub(d['body'])\n d['start_date'] = khayyam.JalaliDatetime().strptime(d['start_date'] + ' 00:00:00', '%Y/%m/%d %H:%M:%S').todatetime()\n d['end_date'] = khayyam.JalaliDatetime().strptime(d['end_date'] + ' 00:00:00', '%Y/%m/%d %H:%M:%S').todatetime()\n if d['start_date'] == d['end_date']:\n self.messages = [u\"تاریخ شروع و پایان را درست وارد کنید.\"]\n self.write(self.result)\n return\n\n a = AboutUsModel(**d).save()['value']\n if a == 'EXIST':\n self.messages = [u\"در این بازه درباره ما وجود دارد.\"]\n self.write(self.result)\n return\n self.status = True\n else:\n self.messages = self.errors\n self.write(self.result)\n except:\n Debug.get_exception(sub_system='admin', severity='error', tags='admin > login')\n self.write(self.error_result)","sub_path":"admin_app/handlers/setting/about_us.py","file_name":"about_us.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628771207","text":"import logging\r\nimport os\r\nfrom App.config import getConfiguration\r\nfrom collective.sentry.browser.interfaces import IUserInfo\r\nfrom collective.sentry.config import ALLOWED_JS\r\nfrom collective.sentry.config import IGNORED_JS\r\nfrom collective.sentry.config import IGNORED_JS_ERRORS\r\nfrom collective.sentry.config import DSN_ENV_VAR\r\nfrom collective.sentry.config import ENVIRONMENT_ENV_VAR\r\nfrom collective.sentry.config import RELEASE_ENV_VAR\r\nfrom collective.sentry.config import SEND_ANYWAY_ENV_VAR\r\nfrom collective.sentry.config import TRACK_JS_ENV_VAR\r\nfrom Products.Five import BrowserView\r\nfrom zope.component import getMultiAdapter\r\n\r\n\r\nlogger = logging.getLogger('collective.sentry')\r\n\r\n\r\nSENTRY_INIT = \"\"\"Raven.config('%s', {\r\n whiteListUrls: [%s],\r\n ignoreErrors: [%s],\r\n ignoreUrls: [%s],\r\n environment: '%s',\r\n release: '%s'\r\n}).install();\r\nRaven.setUserContext(%s);\r\nconsole.log('raven installed');\r\n\"\"\"\r\n\r\n\r\nclass SentryConfig(BrowserView):\r\n \"\"\" Config js for Sentry\r\n \"\"\"\r\n\r\n def __call__(self):\r\n result = \"\"\r\n dsn = \"\"\r\n error_log = self.context.get('error_log', None)\r\n allowed_urls = os.environ.get(ALLOWED_JS, '')\r\n ignore_urls = os.environ.get(IGNORED_JS, '')\r\n ignore_errors = os.environ.get(IGNORED_JS_ERRORS, '')\r\n environment = os.environ.get(ENVIRONMENT_ENV_VAR, '')\r\n release = os.environ.get(RELEASE_ENV_VAR, '')\r\n ignore_errors = os.environ.get(IGNORED_JS_ERRORS, '')\r\n if error_log:\r\n props = error_log.getProperties()\r\n dsn = props.get('getsentry_dsn', \"\")\r\n track = props.get('track_js', False)\r\n if not track:\r\n track = bool(os.environ.get(TRACK_JS_ENV_VAR, False))\r\n send_anyway = os.environ.get(SEND_ANYWAY_ENV_VAR, '')\r\n if track and getConfiguration().debug_mode and not send_anyway:\r\n track = False\r\n logger.info(\r\n 'Zope is in debug mode. Not sending JS errors to sentry')\r\n dsn = dsn and dsn or os.environ.get(DSN_ENV_VAR, '')\r\n if dsn and track:\r\n adapter = getMultiAdapter((self.context, self.request), IUserInfo)\r\n user_data = str(adapter.get_user_data())\r\n result = SENTRY_INIT % (dsn,\r\n allowed_urls,\r\n ignore_errors,\r\n ignore_urls,\r\n environment,\r\n release,\r\n user_data)\r\n elif dsn and not track:\r\n logger.debug(\r\n 'JS tracking not enabled. Not sending JS errors to sentry')\r\n else:\r\n logger.debug(\"There is no GetSentry DSN set. Not \"\r\n \"configuring Sentry for JS\")\r\n\r\n self.request.response.setHeader('Content-Type',\r\n 'application/javascript')\r\n\r\n return result\r\n","sub_path":"collective/sentry/track_js.py","file_name":"track_js.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"243933816","text":"# Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration\n\nfrom AthenaCommon.Logging import logging\nlogging.getLogger().info(\"Importing %s\", __name__)\n\nfrom six import with_metaclass\n\nfrom GaudiKernel.GaudiHandles import \\\n GaudiHandle,GaudiHandleArray,\\\n PublicToolHandle,PublicToolHandleArray,\\\n PrivateToolHandle,PrivateToolHandleArray,\\\n ServiceHandle\n\nfrom AthenaCommon.JobProperties import JobProperty,jobproperties\n\n\nimport os,sys,copy,re,subprocess\n\n# for backwards compat of clients. TO BE REMOVED !!!\nfrom AthenaCommon.ConfiguredFactory import getProperty\n\n# logger to use for normal output\nlogMuon = logging.getLogger(\"MuonRec\")\n# logger to use for resilience output\nlogMuonResil = logging.getLogger(\"Resilience.MuonRec\")\n\nfrom AthenaCommon.ConfigurableMeta import ConfigurableMeta\nfrom AthenaCommon.Configurable import Configurable,ConfigurableAlgTool,ConfigurableService\n\nclass ExtraFlags(object):\n ## Set value of flag or add new flag (if not yet present). Return set value\n ## If first argument is a JobProperty, both the name and the value will be taken from it, and no second argument should be given.\n ## If the second argument is a JobProperty, it's value will be taken (with get_Value()).\n def setFlag(self,name,value=None):\n if isinstance(name,JobProperty):\n if value is not None:\n raise ValueError(\"ExtraFlags.setValue(): No second argument should be given if first argument is a JobProperty args=(%s,%r)\" % (name._context_name,value) )\n return setattr(self, name.__name__, name.get_Value())\n\n elif isinstance(value,JobProperty):\n value = value.get_Value()\n\n return setattr(self,name,value)\n \n \n ## Set value of flag if not yet present. Return set value.\n ## If first argument is a JobProperty, both the name and the value will be taken from it, and no second argument should be given.\n ## If the second argument is a JobProperty, it's value will be taken (with get_Value()).\n def setFlagDefault(self,name,value=None):\n jp = name\n if isinstance(jp,JobProperty):\n if value is not None:\n raise ValueError(\"ExtraFlags.setDefault(): No second argument should be given if first argument is a JobProperty args=(%s,%r)\" % (jp._context_name,value) )\n name = jp.__name__\n try:\n return getattr(self,name)\n except AttributeError:\n return setattr(self,name,jp.get_Value())\n \n elif isinstance(value,JobProperty):\n value = value.get_Value()\n\n return setattr(self,name,value)\n\n \n\n\n\n\n# Add easy setting of user defaults to Configurables\n# NB ideally should be added to class Configurable\nclass ConfiguredBaseMeta(ConfigurableMeta):\n ## Technical note: It is important that the user defaults are stored\n # separately from the C++ defaults. This distinction is used in the\n # ConfigurableFactory: the C++ default tools/services can optionally\n # be instantiated (steered by configureAllDependencies arg to ConfigurableFactory __init__)\n def __new__( self, name, bases, dct ):\n # prepare for custom defaults\n\n newclass = type.__new__( self, name, bases, dct )\n if issubclass(newclass,Configurable):\n newclass = ConfigurableMeta.__new__( self, name, bases, dct )\n\n # add default class members\n d = '_userDefaults'\n## print(\"%r: adding new class member %s\" % (newclass,d))\n setattr(newclass,d,{})\n # fill in the missing defaults from bases\n for b in bases:\n try:\n newd = getattr(newclass,d)\n for n,v in getattr(b,d).items():\n if n not in newd:\n## print(\"%r.%s: adding default %s=%r from %r\" % (newclass,d,n,v,b))\n newd[n] = v\n except AttributeError:\n pass\n\n return newclass\n\n\n\n## @brief Add-in helper base class for configured configurable classes.\n#\n# Derived classes can set user default propoerties in a convenient way.\n# Defaults can be set with setDefaultProperty() and setDefaultProperties().\n# In the __init__ of the derived class, one should call applyDefaultProperties() *before*\n# calling the __init__ of the base class\n#\n# Arguments to the constructor are almost the same as for any Configurable.\n# @arg \\c name the instance name\n# @arg \\c args the dictionary container of keyword arguments (rather than the named arguments one by one),\n# which is being passed to the derived class __init__\n#\n# Example use:
\n# \n# class DerivedConfigurable(SomeAutoGenConfigurable,ConfiguredBase):\n# def __init__(self,name,**kwargs):\n# self.applyUserDefaults(kwargs,name)\n# super(DerivedConfigurable,self).__init__(name,**kwargs)\n#\n# DerivedConfigurable.setDefaultProperties( prop1Name = prop1Value,\n# prop2Name = \"prop2String\",\n# toolHandle = \"ConfigurableInstanceName\" ) # in conjuction with ConfigurableFactory\n# \n#\n# NB This functionality should ideally be added directly to class Configurable\n#\nclass ConfiguredBase (with_metaclass (ConfiguredBaseMeta, object)):\n __slots__ = ()\n\n\n def __init__(self,name,args):\n self.applyUserDefaults(args,name)\n\n\n ## Set user default (not C++ default). Includes type checking.\n @classmethod\n def setDefaultProperty(cls,propertyName,value):\n # choose according to expected type\n try:\n prop = cls._properties[propertyName]\n except KeyError:\n raise AttributeError(\"%s does not have property %s\" % (cls.__name__,propertyName))\n\n errorAllowedTypes = None\n cxxdefault = prop.default\n if type(cxxdefault) == type(value):\n cls._userDefaults[propertyName] = copy.copy(value)\n elif isinstance(cxxdefault,PublicToolHandle):\n if value is None:\n cls._userDefaults[propertyName] = PublicToolHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = PublicToolHandle(value)\n elif isinstance(value,ConfigurableAlgTool):\n cls._userDefaults[propertyName] = PublicToolHandle(value.getFullName())\n elif isinstance(value,PublicToolHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,PublicToolHandle,ConfigurableAlgTool\"\n \n elif isinstance(cxxdefault,PublicToolHandleArray):\n if value is None:\n cls._userDefaults[propertyName] = PublicToolHandleArray()\n elif type(value) == list:\n cls._userDefaults[propertyName] = PublicToolHandleArray(value)\n elif isinstance(value,PublicToolHandleArray):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"list,PublicToolHandleArray\"\n \n elif isinstance(cxxdefault,PrivateToolHandle):\n if value is None:\n cls._userDefaults[propertyName] = PrivateToolHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = PrivateToolHandle(value)\n elif isinstance(value,ConfigurableAlgTool):\n cls._userDefaults[propertyName] = copy.deepcopy(value)\n elif isinstance(value,PrivateToolHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,PrivateToolHandle,ConfigurableAlgTool\"\n \n elif isinstance(cxxdefault,PrivateToolHandleArray):\n if value is None:\n cls._userDefaults[propertyName] = PrivateToolHandleArray()\n elif type(value) == list:\n cls._userDefaults[propertyName] = PrivateToolHandleArray(value)\n elif isinstance(value,PrivateToolHandleArray):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"list,PrivateToolHandleArray\"\n \n elif isinstance(cxxdefault,ServiceHandle):\n if value is None:\n cls._userDefaults[propertyName] = ServiceHandle(\"\")\n elif type(value) == str:\n cls._userDefaults[propertyName] = ServiceHandle(value)\n elif isinstance(value,ConfigurableService):\n cls._userDefaults[propertyName] = ServiceHandle(value.getFullName())\n elif isinstance(value,ServiceHandle):\n cls._userDefaults[propertyName] = copy.copy(value)\n else:\n errorAllowedTypes = \"str,ServiceHandle,ConfigurableService\"\n\n else:\n cls._userDefaults[propertyName] = value\n\n if errorAllowedTypes:\n raise TypeError( \"Setting default property %s.%s with wrong type. Expected %s got %s\" %\n (cls.__name__,propertyName,errorAllowedTypes,type(value).__name__) )\n\n\n @classmethod\n def setDefaultProperties(cls,**kwargs):\n for name,value in kwargs.items():\n cls.setDefaultProperty(name,value)\n # for debug\n # cls.printDefaultProperties()\n\n\n @classmethod\n def getUserDefaults(cls):\n return copy.copy(cls._userDefaults)\n\n\n ## return user default for given propertyName. Returns None is no user default is set\n @classmethod\n def getUserDefault(cls,propertyName):\n return cls._userDefaults[propertyName]\n\n\n @classmethod\n def applyUserDefaults(cls,args,name=None):\n logger = None\n if name is not None: logger = logging.getLogger(name)\n if logger: logger.verbose(\"Applying user defaults to arguments:\")\n for prop,default in cls._userDefaults.items():\n if prop not in args:\n args[prop] = default\n if logger: logger.verbose(\"%s = %r\", prop, default)\n else:\n if logger: logger.verbose(\"not setting default %s = %r because value already set to %r\", prop, default, args[prop])\n\n \n @classmethod\n def printUserDefaults(cls):\n print(\"User default properties of class %s\" % cls.__name__)\n for n,v in cls._userDefaults.items():\n print(\" %s = %r\" % (n,v))\n\n\n \n\n\n# end of class ConfiguredBase\n\n\n#\n# Some extra functionality for JobProperties\n#\n\nclass AutoLoadContainer(object):\n def __init__(self,moduleName=None,containerName=None,parentContainer=jobproperties):\n self._parentContainer = parentContainer\n if moduleName and containerName:\n self._moduleName = moduleName\n self._containerName = containerName\n\n def setContainer(self,moduleName,containerName):\n self._moduleName = moduleName\n self._containerName = containerName\n\n def setParent(self,parent):\n self._parentContainer = parent\n\n def load(self,moduleName=None,containerName=None):\n \"\"\"Load the JobProperty container in container module.\n If arguments not given (or None), then use stored members\"\"\"\n if not moduleName:\n moduleName = self._moduleName\n if not containerName:\n containerName = self._containerName\n # import the module. The module should itself\n # add its propertycontainer to toplevel jobproperties\n if moduleName not in sys.modules:\n logMuon.info(\"Auto-loading container %s from module %s\", containerName, moduleName)\n # import the (top) module\n mod = __import__(moduleName)\n # get lowest-level module\n for m in moduleName.split('.')[1:]:\n mod = getattr(mod,m)\n # add container\n contClass = getattr(mod,containerName)\n if not hasattr(self._parentContainer,contClass.__name__):\n self._parentContainer.add_Container(contClass)\n logMuon.info(\"Adding container %s to %s\",containerName,self._parentContainer.__name__)\n else:\n logMuon.debug(\"Container %s already in %s\",containerName,self._parentContainer.__name__)\n\n def unload(self,moduleName=None,containerName=None):\n \"\"\"Unload the JobProperty container, and the container module.\n If arguments not given (or None), then use stored members\"\"\"\n if not moduleName:\n moduleName = self._moduleName\n if not containerName:\n containerName = self._containerName\n try:\n mod = sys.modules[moduleName]\n except KeyError:\n # not there, nothing to be done\n pass\n else:\n # remove container\n contClass = getattr(mod,containerName)\n contInst = getattr(self._parentContainer,contClass.__name__,None)\n if contInst is not None:\n logMuon.info(\"Removing container %s from %s\",containerName,self._parentContainer.__name__)\n self._parentContainer.del_Container(contClass)\n\n# end of class AutoLoadContainer\n\n\nclass AutoLoadContainerJobProperty(JobProperty):\n \"\"\"JobPropertyBaseClass to auto-load a JobPropertyContainer.\n The derived class must have a member:\n Loader = AutoLoadContainer()\n The default allowedTypes is bool.\"\"\"\n\n allowedTypes=['bool']\n\n # Loader = AutoLoadContainer() # needed in derived class\n\n def _do_action(self):\n global logMuon\n try:\n self.Loader.load()\n except (ImportError,AttributeError):\n from AthenaCommon.AthenaCommonFlags import athenaCommonFlags\n if athenaCommonFlags.AllowIgnoreConfigError():\n logMuonResil.error(\"Error importing %s. Switching off %s\", self.Loader._moduleName,self.__name__)\n self.set_Off()\n else: # do not allow config error\n raise\n\n def _undo_action(self):\n self.Loader.unload()\n\n\ndef fillJobPropertyContainer(container,modname):\n import sys\n mod = sys.modules[modname]\n propertiesList = []\n for n,p in vars(mod).items():\n if isinstance(p,type) and issubclass(p,JobProperty) and p.__module__ == modname and \\\n 'JobProperty' not in n:\n container.add_JobProperty(p)\n propertiesList.append(getattr(container,p.__name__))\n return propertiesList\n\n\n\n## @brief JobProperty base class to make a summary boolean out of a number of booleans\n#\n# The list of JobProperties to control must be given in @c _properties (a list of refs).\n# If this property is set to False than set_Off() is called on all controlled properties.\n# If this property is set to True than set_On() is called on all controlled properties,\n# which means they will the get value they have been assigned (can be True or False).\n# The value of this property returns the logical OR of all the controlled values.\nclass SummaryJobProperty(JobProperty):\n statusOn = True\n allowedTypes = ['bool']\n StoredValue = True\n _properties = [] # list of bool properties to control. To be set in derived class\n\n\n def __init__(self,context=''):\n super(SummaryJobProperty,self).__init__(context)\n self.__class__._log = logging.getLogger(self._context_name)\n \n\n def _update_action(self):\n if self.statusOn and self.StoredValue:\n for p in self._properties:\n if p is not self:\n self._log.info(\"%s.set_On()\", p.__name__)\n p.set_On()\n else:\n for p in self._properties:\n if p is not self:\n self._log.info(\"%s.set_Off()\", p.__name__)\n p.set_Off()\n\n\n def _do_action(self):\n self._update_action()\n\n def _undo_action(self):\n self._update_action()\n\n ## Return logical OR of controlled properties\n def get_Value(self):\n for p in self._properties:\n if p.get_Value(): return True\n return False\n\n\n\n## Set the default value of JobProperty @c prop to @c value \ndef setJobPropertyDefault(prop,value):\n global logMuon\n if value != prop.__class__.StoredValue:\n mess = \"Changing default %s = %r\" % ( prop.__name__, value )\n if prop.__class__.StoredValue is not prop.StoredValue:\n mess += \" (current value: %r)\" % prop.get_Value()\n logMuon.info(mess)\n prop.__class__.StoredValue = value\n\n\n# Return full name of JobProperty, including parent containers,\n# but excluding the top container \"JobProperties\"\ndef JobPropertyFullName(prop):\n fullname = prop._context_name\n # remove redundant prefix\n pre = 'JobProperties.'\n if fullname.startswith(pre): fullname = fullname[len(pre):]\n return fullname\n\ndef hasJobPropertyBeenSet(prop):\n return prop.StoredValue is not prop.__class__.StoredValue\n\n\nclass _ContestResult:\n __slots__ = ( 'winner', 'loser' )\n def __init__(self,winner,loser):\n self.winner = winner\n self.loser = loser\n \n\n#\n# Compare 2 competing JobProperties and decide who's value wins.\n# Strategy:\n# 1. locked property wins\n# 2. set property wins\n# 3. In case of draw, @c prop1 wins\ndef _whoWins( prop1, prop2, logger = logMuon ):\n # 1. locked property wins\n if prop1.is_locked() and not prop2.is_locked():\n winner = prop1\n loser = prop2\n reason = 'it is locked'\n elif not prop1.is_locked() and prop2.is_locked():\n winner = prop2\n loser = prop1\n reason = 'it is locked'\n # 2. set property wins\n elif hasJobPropertyBeenSet(prop1) and not hasJobPropertyBeenSet(prop2):\n winner = prop1\n loser = prop2\n reason = 'it has the value set by user'\n elif not hasJobPropertyBeenSet(prop1) and hasJobPropertyBeenSet(prop2):\n winner = prop2\n loser = prop1\n reason = 'it has the value set by user'\n # Draw: chose prop1\n else:\n winner = prop1\n loser = prop2\n reason = 'it has precedence (both not locked and not set)'\n logger.debug('%s=%r vs %s=%r : %s=%r wins because %s',\n JobPropertyFullName(prop1), prop1.get_Value(),\n JobPropertyFullName(prop2), prop2.get_Value(),\n JobPropertyFullName(winner),winner.get_Value(),\n reason)\n # return the result\n return _ContestResult(winner,loser)\n\n## synchronise @c toProp to @c fromProp (both JobProperties)\ndef syncFlags( toProp, fromProp, logger = logMuon, ignoreLock = False ):\n toValue = toProp.get_Value()\n fromValue = fromProp.get_Value()\n if toValue == fromValue: return # nothing to do\n if toProp.is_locked():\n if not ignoreLock:\n logger.warning('%s is locked. Not synchronising with %s', JobPropertyFullName(toProp), JobPropertyFullName(fromProp))\n else:\n logger.warning('Overriding lock in setting %s = %r (synchronising with %s)', JobPropertyFullName(toProp), fromValue, JobPropertyFullName(fromProp))\n override_lock_and_set_Value(toProp, fromValue)\n else:\n logger.info('Setting %s = %r (synchronising with %s)', JobPropertyFullName(toProp), fromValue, JobPropertyFullName(fromProp))\n toProp.set_Value( fromValue )\n\n## synchronise flags, where the strongest wins.\n# Strategy:\n# 1. locked property wins\n# 2. set property wins\n# 3. In case of draw, @c prop1 wins\ndef syncWinningFlag( prop1, prop2, logger = logMuon, ignoreLock = False ):\n if prop1.get_Value() != prop2.get_Value():\n contest = _whoWins( prop1, prop2, logger )\n _syncFlags( contest.loser, contest.winner, logger, ignoreLock )\n\n\n\n\ndef override_lock_and_set_Value(prop,value):\n \"\"\"Set value of JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_Value(value)\n prop._locked = oldLock\n\ndef override_lock_and_set_On(prop):\n \"\"\"call set_On() on JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_On()\n prop._locked = oldLock\n\ndef override_lock_and_set_Off(prop):\n \"\"\"call set_Off() on JobProperty, ignoring lock\"\"\"\n oldLock = prop._locked\n prop._locked = False\n prop.set_Off()\n prop._locked = oldLock\n\n\ndef dumpDetFlags(filename='config.txt'):\n \"\"\"Append DetFlags printout to config file\"\"\"\n # add DetFlags\n from AthenaCommon.DetFlags import DetFlags\n import sys\n confFile = open(filename,'a')\n # redirect stdout to file\n sys.stdout, confFile = confFile, sys.stdout \n print(\"Detector flags:\")\n DetFlags.Print()\n # put back stdout to screen\n sys.stdout, confFile = confFile, sys.stdout \n confFile.close()\n\n\n\nclass RecConfigInfo(object):\n \"\"\"Small class to contain some info on the expanded reco tag\"\"\"\n def __init__(self,configTag,defaultPackage='MuonRecExample'):\n self.configTag = configTag\n configParts = configTag.split('.')\n # fill in the missing pieces\n nParts = len(configParts)\n # class name is always the last part\n self.className = configParts[-1]\n defaultModule = self.className\n if nParts == 1:\n # default package, default module\n self.packageName = defaultPackage\n self.moduleName = defaultModule\n elif nParts == 2:\n # default package, explicit module\n self.packageName = defaultPackage\n self.moduleName = configParts[-2]\n else:\n # explicit package, explicit module\n self.packageName = configParts[0]\n self.moduleName = '.'.join(configParts[1:-1])\n # full python module name\n self.fullModuleName = self.packageName + '.' + self.moduleName\n # make full configTag\n self.fullTag = self.fullModuleName + '.' + self.className\n # make short configName\n shortParts = [ self.className ]\n if self.moduleName != defaultModule:\n shortParts.insert(0,self.moduleName)\n if self.packageName != defaultPackage:\n shortParts.insert(0,self.packageName)\n self.shortTag = '.'.join(shortParts)\n \n# end of class RecConfigInfo\n\n\n\n# ugly hack in case we run outside of athena (e.g. in diffConfig.py)\ndef uglyHackedInclude(jobOptions):\n global ToolSvc,ServiceMgr\n from AthenaCommon.Include import include\n import __main__\n if not hasattr(__main__,'include'):\n include.setShowIncludes(False)\n include.setClean(False)\n setattr(__main__,'include',include)\n if not hasattr(__main__,\"ToolSvc\"):\n setattr(__main__,\"ToolSvc\",ToolSvc)\n if not hasattr(__main__,\"ServiceMgr\"):\n setattr(__main__,\"ServiceMgr\",ServiceMgr)\n\n include(jobOptions)\n","sub_path":"MuonSpectrometer/MuonReconstruction/MuonRecExample/python/MuonRecUtils.py","file_name":"MuonRecUtils.py","file_ext":"py","file_size_in_byte":22719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234642822","text":"\n# Project: \t\tCS426 Spring 2018, Team #23: SkyWarden Senior Project, Aerial Drone Notification System (ADNS) \n# Team:\t\t\tRony Calderon, Bryan Kline, Jia Li, Robert Watkins\n# Subsystem:\tGround Base Unit\n# File name:\tParser.py \n# Description:\tParser class implementation\t\n#\t\t\t\tParser class parses, reassembles, and formats input from the subsystem on-board\n#\t\t\t\tthe drone coming in over the serial port from the receiver for use in the ground \n#\t\t\t\tbase unit \n\nfrom SerialPort import SerialPort\n\nclass Parser:\n\n\t__serialPort = None\n\t__parsedInput = None\n\t__serialReadSize = None\n\n\t# Name:\t\t\tParameterized constructor\n\t# Description:\tParser class parameterized constructor which takes in baud rate and timeout\n\t# \t\t\t\tvalues which are used to create a SerialPort object\n\t# Parameters:\tTakes in two ints which are the baud rate and timeout value needed in the \n\t# \t\t\t\tconstructor of the SerialPort object\n\t# Return:\t\tNone\n\tdef __init__(self, baudRate, timeOut, readinSize):\n\n\t\tself.__serialReadSize = readinSize\n\n\t\t# SerialPort object created with baud rate and timeout values passed into the constructor \n\t\tself.__serialPort = SerialPort(baudRate, timeOut, readinSize) \n\n\n\t# Name:\t\t\tgetSerialInput\n\t# Description:\tParser class method which continually reads in from the serial port through \n\t# \t\t\t\tthe SerialPort object and formats and concatenates the portions of the input, \n\t# \t\t\t\tremoving artifacts added by PySerial and checking for a decimal point\n\t# Parameters:\tNone\n\t# Return:\t\tReturns a list containing the value from the receiver as a string and char\n\t# \t\t\t\tindicating what type of value it is\n\tdef getSerialInput(self):\n\t\t\n\t\tdotBool = False\n\n\t\t# for reading in an entire line at a time from the serial port\n\t\tif self.__serialReadSize == 1:\n\t\t\t\n\t\t\t# reads in an entire line from the serial port\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\n\t\t\t# leading and trailing characters are parsed off the line and the outputList is built \n\t\t\t# from the parsed line\n\t\t\toutputList = [inputValue[2]]\n\t\t\toutputString = inputValue[3:-4]\n\t\t\toutputString = outputString.replace('\\\\', \"\")\n\t\t\toutputList.append(outputString)\n\n\t\t# for reading in data from the serial port one byte at a time\n\t\tif read.__serialReadSize == 0:\n\n\t\t\t# grabbing the first portion of the input, which enters in the format: b'1'\n\t\t\t# where 1 is the value coming in, the final values being: b'\\', b'r', b'\\', b'n'\n\t\t\t# which, along with the 'b', and ''' chars, are removed\n\t\t\t\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\n\t\t\tinputValue.split(\"'\")\n\t\t\tvalue = \"\"\n\n\t\t\t# while the first '\\' char of the carriage return, \\r\\n, has not been encountered, the \n\t\t\t# the first char in the string is retained and outputList is built from each one\n\t\t\t\n\t\t\twhile inputValue[2] != \"\\\\\":\n\t\t\t\t# skips errant, additional '.' chars if they are present in the input\n\t\t\t\tif inputValue[2] == '.':\n\t\t\t\t\tif not dotBool:\n\t\t\t\t\t\tdotBool = True\n\t\t\t\t\t\tvalue += inputValue[2]\n\t\t\t\telse:\n\t\t\t\t\tvalue += inputValue[2] \t\n\n\t\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\t\tinputValue.split(\"'\")\n\n\t\t\t# a list is built from the input, making the first char in the input the first\n\t\t\t# element in the list which is a control char which marks whether the input is a\n\t\t\t# voltage, with a 'v', or as a proximity reading, with any char from 'a' to 'n' \n\t\t\t# and the second element the input value itself\t\t\n\t\t\tif len(value) > 1:\n\t\t\t\toutputList = [str(value[0]), str(value[1:])]\n\t\t\telse:\n\t\t\t\toutputList = value \n\n\t\t\tinputValue = str(self.__serialPort.serialRead())\n\t\t\n\t\t# method call to trimValue to trim excess trailing digits from the input which will\n\t\t# then be returned\n\t\toutputList = self.trimValue(outputList)\n\t\t\n\t\t# the serial port buffer is flushed\n\t\tself.__serialPort.flushSerialPort()\n\t\t\n\t\treturn outputList\n\n\n\t# Name:\t\t\ttrimValue\n\t# Description:\tParser class method which takes in a list containing as the second element\n\t# \t\t\t\ta string which is to have trailing digits trimmed off depending whether the \n\t# \t\t\t\tstring corresponds to a voltage or a proximity reading\n\t# Parameters:\tTakes in a list containing a control char marking the type of value which is\n\t# \t\t\t\tbeing recieved from the serial port, which is the second element in the list\n\t# Return:\t\tReturns the list that was taken in but with the string containing the value\n\t# \t\t\t\ttrimmed down to the proper size for use in other classes in the ground unit\n\tdef trimValue(self, outputList):\n\t\t\n\t\tindex = 1\n\t\tvoltLimit = 6\n\t\tproxLimit = 5\n\n\t\tif outputList != None and len(outputList) > 1 and len(outputList[1]) > 0:\n\t\t\tlistSize = len(outputList[1])\n\n\t\t\t# if the first element in the list is not a valid control then return None\n\t\t\tif outputList[0] < 'a' or outputList[0] > 'z':\n\t\t\t\treturn None\n\n\t\t\t# the input value is iterated through and there are non-numeric chars in the\n\t\t\t# string, return None\n\t\t\twhile index < listSize:\n\t\t\t\tif outputList[1][index] >= 'a' and outputList[1][index] <= 'z':\n\t\t\t\t\treturn None\n\t\t\t\tindex += 1\n\n\t\t\t# if the input value is a voltage, enforce a string size of 5\n\t\t\tif outputList[0] == 'v' and listSize > 6:\n\t\t\t\toutputList[1] = outputList[1][:-(listSize - voltLimit)]\n\t\t\t# else if the input value is proximity, enforce a string size of 4\n\t\t\telif len(outputList) > 0 and outputList[0] >= 'a' and outputList[0] <= 'l' and listSize > 5:\n\t\t\t\toutputList[1] = outputList[1][:-(listSize- proxLimit)]\n\n\t\treturn outputList\n\n\n\t# Name:\t\t\tparsePipeInput\n\t# Description:\tParser class method which takes in a value and immediately returns it; provides for\n\t# \t\t\t\tfurther parsing if necessary in the future by way of keeping other parsing methods\n\t# \t\t\t\tintact\n\t# Parameters:\tTakes in a value which is forwarded\n\t# Return:\t\tReturns the value passed into the method\n\tdef parsePipeInput(self, inputValue):\n\n\t\treturn inputValue\t\n\n","sub_path":"SkyWarden Aerial Drone Notification System/Ground Base Unit and GUI Subsystems/Ground Unit Source Code/Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"345298531","text":"import numpy as np\nimport random\nimport sys\nimport os\n\n\n# TIME_SLOTS = 1\nNUM_CHANNELS = 2\nNUM_USERS = 3\nNUM_SIZE = 3\nATTEMPT_PROB = 0.6\nCHANNEL_CAPACITY = 7\n# GAMMA = 0.90\n\nclass env_network:\n def __init__(self,num_users,num_channels, num_size,attempt_prob, table, channel_capacity):\n self.ATTEMPT_PROB = attempt_prob\n self.NUM_USERS = num_users\n self.NUM_CHANNELS = num_channels\n self.NUM_SIZE = num_size\n self.CHANNEL_CAPACITY = channel_capacity\n self.table = table\n self.REWARD = -1\n\n # self.action_space = np.arange((self.NUM_CHANNELS+1)*self.NUM_SIZE)\n self.action_space = np.arange((NUM_CHANNELS+1) * NUM_SIZE**NUM_SIZE)\n self.channel_space = np.arange(self.NUM_CHANNELS+1)\n self.size_space = np.arange(self.NUM_SIZE) + 1\n self.users_action = np.zeros([self.NUM_USERS],np.int32)\n self.users_observation = np.zeros([self.NUM_USERS],np.int32)\n\n def reset(self):\n pass\n\n def sample(self):\n #生成action,维度为(num_users,)\n mode = []\n index_list = []\n check_index = []\n\n x = list(np.random.choice(self.channel_space,size=self.NUM_USERS))\n Y = np.random.choice(self.size_space,size=3)#每次来的包的个数是固定的,但是大小是可变的\n y = [list(np.random.choice(Y, size =3)) for i in range(self.NUM_USERS)]\n\n for i in range(1, self.NUM_SIZE + 1):\n for j in range(1, self.NUM_SIZE + 1):\n for k in range(1, self.NUM_SIZE + 1):\n check_index.append([i,j,k])\n\n for i in range(len(y)):\n index_list.append(check_index.index(y[i]))\n\n res = list(zip(x, index_list))\n index = np.array(res)\n # array([[0, 1],\n # [0, 2],\n # [2, 0]])\n for i in range(len(index)):\n mode.append(self.table[index[i][0]][index[i][1]])\n mode1 = np.array(mode)\n return mode1 #array([1,2,6]) shape=(3,)\n\n\n # def step(self, action):#形参action是通过sample()得到的,是模式的集合\n # # print\n # assert (action.size) == self.NUM_USERS\n # channel_alloc_frequency = np.zeros([self.NUM_CHANNELS + 1], np.int32) # 0 for no chnnel access\n # # size_alloc_frequency = np.zeros([self.NUM_SIZE], np.int32)\n # obs = []\n # reward = np.zeros([self.NUM_USERS])\n # j = 0\n # for each in action:\n # prob = random.uniform(0, 1)\n #\n # x, y = np.where( self.table == each)\n # index = np.array(list(zip(x,y)))\n #\n # if prob <= self.ATTEMPT_PROB:\n # self.users_action[j] = each # action\n # channel_alloc_frequency[index[0][0]] += 1\n # # size_alloc_frequency[index[0][1]] += 1\n #\n # j += 1\n #\n # for i in range(1, len(channel_alloc_frequency)):\n # if channel_alloc_frequency[i] > 1:\n # channel_alloc_frequency[i] = 0\n #\n # for i in range(len(action)):\n # x, y = np.where(self.table == self.users_action[i])\n # index = np.array(list(zip(x, y)))\n #\n # self.users_observation[i] = channel_alloc_frequency[index[0][0]]\n # if self.users_action[i] == 0: # accessing no channel\n # self.users_observation[i] = 0\n # if self.users_action[i] == 1: # accessing no channel\n # self.users_observation[i] = 0\n # if self.users_action[i] == 2: # accessing no channel\n # self.users_observation[i] = 0\n #\n # if self.users_observation[i] == 1:\n # reward[i] = 1 + np.exp(-1 * index[0][1])\n # if self.users_observation[i] == 0:\n # reward[i] = 0\n # obs.append((self.users_observation[i], reward[i]))\n #\n # residual_channel_capacity = channel_alloc_frequency[1:]\n # residual_channel_capacity = 1 - residual_channel_capacity\n # obs.append(residual_channel_capacity)\n # return obs\n def step(self, action):#形参action是通过sample()得到的,是模式的集合\n # print\n assert (action.size) == self.NUM_USERS\n channel_alloc_frequency = np.zeros([self.NUM_CHANNELS + 1], np.int32) # 0 for no chnnel access\n # size_alloc_frequency = np.zeros([self.NUM_SIZE], np.int32)\n obs = []\n reward = np.zeros([self.NUM_USERS])\n j = 0\n\n check_index = []\n for x in range(1, self.NUM_SIZE + 1):\n for y in range(1, self.NUM_SIZE + 1):\n for z in range(1, self.NUM_SIZE + 1):\n check_index.append([x, y, z])\n\n for each in action:\n prob = random.uniform(0, 1)\n\n x, y = np.where( self.table == each)\n index = np.array(list(zip(x,y)))\n\n if prob <= self.ATTEMPT_PROB:\n self.users_action[j] = each # action\n channel_alloc_frequency[index[0][0]] += 1\n # size_alloc_frequency[index[0][1]] += 1\n j += 1\n\n for i in range(1, len(channel_alloc_frequency)):\n if channel_alloc_frequency[i] > 1:\n channel_alloc_frequency[i] = 0\n\n for i in range(len(action)):\n x, y = np.where(self.table == self.users_action[i])\n index = np.array(list(zip(x, y)))#array([[×, ×]]\n\n self.users_observation[i] = channel_alloc_frequency[index[0][0]]\n if self.users_action[i] >=0 and self.users_action[i] < self.NUM_SIZE**self.NUM_SIZE : # accessing no channel,table的第一行\n self.users_observation[i] = 0\n\n if self.users_observation[i] == 1:\n if sum(check_index[index[0][1]]) <= self.CHANNEL_CAPACITY:\n reward[i] = 1\n else:\n reward[i] = 1 + np.power(np.e, (-1 * sum(np.random.choice(check_index[index[0][1]], size = 2))))\n else:\n reward[i] = 0\n obs.append((self.users_observation[i], reward[i]))\n\n # residual_channel_capacity = channel_alloc_frequency[1:]\n # residual_channel_capacity = 1 - residual_channel_capacity\n # obs.append(residual_channel_capacity)\n obs.append(channel_alloc_frequency)\n return obs\n\n\n\n\n\n","sub_path":"multi_user_network_env.py","file_name":"multi_user_network_env.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341712495","text":"class Solution:\n \"\"\"\n @param n: an integer\n @return: return a string\n \"\"\"\n\n def lastFourDigitsOfFn(self, n):\n # write your code here\n class Matrix:\n def __init__(self, a, b, c, d):\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n\n def matrix_mul(A, B):\n C = Matrix(0, 0, 0, 0)\n C.a = (A.a * B.a + A.b * B.c) % 10000\n C.b = (A.a * B.b + A.b * B.d) % 10000\n C.c = (A.c * B.a + A.d * B.c) % 10000\n C.d = (A.c * B.b + A.d * B.d) % 10000\n return C\n\n def matrix_pow(n):\n m = Matrix(0, 0, 0, 0)\n if n == 1:\n m = Matrix(1, 1, 1, 0)\n elif (n & 1) == 0:\n m = matrix_pow(n >> 1)\n m = matrix_mul(m, m)\n elif (n & 1) == 1:\n m = matrix_pow((n - 1) >> 1)\n m = matrix_mul(m, m)\n m = matrix_mul(m, Matrix(1, 1, 1, 0))\n return m\n\n if n == 0: return '0'\n if n == 1: return '1'\n matrix = matrix_pow(n)\n res = str(matrix.b) # matrix.b is Fn\n return res.lstrip('0')\n","sub_path":"lintcode/949-fibonacci-ii.py","file_name":"949-fibonacci-ii.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"401803517","text":"# \"\"\"бинарный поиск хариянов в массиве\"\"\"\n# ВНИМАНИЯ чтобы можно было искать бинарные обьекты(цифры ) обязаьельно массив должен быть отсортерован\n# например мы ищем в массиве цифру которого нет и как можно найти эта цифра может стоять между цифрами вот тогда та что справа больше left_boundary та что слева то что меньше\n#искать правуб и левую границу цифры которого нет\n#каждому и сортировке и нахождению границ будет отдельная функция\n\"\"\"рекурентная функция\"\"\"\ndef left_bound(a,key):#переменная далась и а это массив а key это цифра которую ищем в этом массиве\n left=-1#это из за того что у нас правая половина меньше надо начинать с -1\n rigth=len(a) #а правая больше из-за этого и правая важная и до конца до лен будет идти\n while rigth-left>1:#если они все больше 1 то херачат цикл\n middle=(left+rigth)//2#тут находят серидину\n if a[middle] NoneType\n \t\"\"\"\n self.symbol = symbol\n self.row = row\n self.col = col\n self.num_sprouts_eaten = num_sprouts_eaten\n\n def set_location(self,row,col):\n \"\"\"\n \t (Rat, int, int) -> NoneType\n \t\"\"\"\n self.row = row\n self.col = col\n\n def eat_sprout(self):\n \"\"\"\n \t (Rat) -> NoneType\n \t\"\"\"\n self.num_sprouts_eaten += 1\n\n def __str__(self):\n \"\"\"\n \t (Rat) -> str\n \t symbol at (row, col) ate num_sprouts_eaten sprouts.\n \t\"\"\"\n return \"{0} at ({1}, {2}) ate {3} sprouts.\".format(self.symbol,self.row,self.col,self.num_sprouts_eaten)\n\n # Write your Rat methods here.\n\nclass Maze:\n \"\"\" A 2D maze. \"\"\"\n def __init__(self,maze,rat_1,rat_2,num_sprouts_left = 3):\n \"\"\"\n \t (Maze, list of list of str, Rat, Rat) -> NoneType\n \t\"\"\"\n self.maze = maze\n self.rat_1 = rat_1\n self.rat_2 = rat_2\n self.num_sprouts_left = num_sprouts_left\n\n def is_wall(self,row,col):\n return self.maze[row][col] == WALL\n\n def get_character(self,row,col):\n if row == self.rat_1.row and col == self.rat_1.col:\n return self.rat_1.symbol\n elif row == self.rat_2.row and col == self.rat_2.col:\n return self.rat_2.symbol\n else:\n return self.maze[row][col]\n\n def move(self,rat,vertical_direction,horizontal_direction):\n row = rat.row\n col = rat.col\n height = len(self.maze)\n width = len(self.maze[0])\n if vertical_direction == UP and row + UP >= 0:\n char = self.maze[row + UP][col]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row + UP,col)\n self.maze[row + UP][col] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row + UP,col)\n return True\n elif char == WALL:\n return False\n elif vertical_direction == DOWN and row + DOWN <= height:\n char = self.maze[row + DOWN][col]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row + DOWN,col)\n self.maze[row + DOWN][col] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row + DOWN,col)\n return True\n elif char == WALL:\n return False\n elif horizontal_direction == LEFT and col + LEFT >= 0:\n char = self.maze[row][col + LEFT]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row,col + LEFT)\n self.maze[row][col + LEFT] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row,col + LEFT)\n return True\n elif char == WALL:\n return False\n elif horizontal_direction == RIGHT and col + RIGHT <= width:\n char = self.maze[row][col + RIGHT]\n if char == SPROUT:\n rat.eat_sprout()\n rat.set_location(row,col + RIGHT)\n self.maze[row][col + RIGHT] = HALL\n self.num_sprouts_left -= 1\n return True\n elif char == HALL:\n rat.set_location(row,col + RIGHT)\n return True\n elif char == WALL:\n return False\n\n def __str__(self):\n temp = \"\"\n for row in range(len(self.maze)):\n for col in range(len(self.maze[row])):\n if self.rat_1.row == row and self.rat_1.col == col:\n temp += self.rat_1.symbol\n elif self.rat_2.row == row and self.rat_2.col == col:\n temp += self.rat_2.symbol\n else:\n temp += self.maze[row][col]\n temp += \"\\n\"\n temp += str(self.rat_1)+\"\\n\"\n temp += str(self.rat_2)\n return temp\n\n # Write your Maze methods here.","sub_path":"rat_race_copy/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406033766","text":"from threading import Thread\r\nimport multiprocessing\r\nimport time\r\nimport robin_stocks\r\nimport math\r\nimport pdb\r\nfrom urllib3.exceptions import ProtocolError\r\n\r\nfile = open('data.txt', mode='r')\r\ndata = []\r\nfor line in file:\r\n if line.strip('\\n') == 'True':\r\n data.append(True)\r\n if line.strip('\\n') == 'False':\r\n data.append(False)\r\n if line.strip('\\n') == '-1':\r\n data.append(None)\r\n else:\r\n data.append(line.strip('\\n'))\r\n\r\nsell_price = data[0]\r\nbuy_price = data[1]\r\nhave_doge = data[2]\r\nquantity = data[3]\r\nfile.close()\r\n\r\nrobin_stocks.authentication.login('username', 'password')\r\n\r\n\r\ndef setup():\r\n global quantity, buy_price\r\n quantity = float(robin_stocks.crypto.get_crypto_positions('quantity_available')[0])\r\n print(\"Quantity available: \" + str(quantity))\r\n if quantity > 0.0:\r\n buy_price = float(robin_stocks.orders.get_all_crypto_orders()[0]['price'])\r\n sell_mode()\r\n else:\r\n buy_mode()\r\n\r\n\r\ndef buy_mode():\r\n global buy_price, have_doge, sell_price, quantity\r\n old_created = (robin_stocks.orders.get_all_crypto_orders()[0]['created_at'])\r\n print('BUYING MODE')\r\n cash = (0.85 * (float(robin_stocks.profiles.load_account_profile('portfolio_cash')))).__round__(2)\r\n doge_price = stat_tracker.price\r\n amount = float(cash / doge_price).__round__()\r\n flag = False\r\n while True:\r\n if stat_tracker.direction == -1:\r\n flag = False\r\n continue\r\n elif not flag:\r\n flag = True\r\n time.sleep(1.5)\r\n elif flag:\r\n break\r\n\r\n print(robin_stocks.orders.order_buy_crypto_by_quantity('DOGE', amount, 'mark_price'))\r\n print('order placed')\r\n time.sleep(0.5)\r\n print('checking for transaction')\r\n flag = False\r\n while True:\r\n trades = robin_stocks.orders.get_all_crypto_orders()[0]\r\n if trades['created_at'] != old_created:\r\n if not flag:\r\n flag = True\r\n print('found transaction. will alert when purchase confirmed.')\r\n\r\n if trades['state'] == 'filled':\r\n average = trades['average_price']\r\n buy_price = float(average)\r\n print(\"Purchased \" + str(cash * 0.9) + \" worth of Doge coin at \" + str(average)\r\n + \" per coin\")\r\n have_doge = True\r\n save_data(sell_price, buy_price, have_doge, quantity)\r\n sell_mode()\r\n\r\n doge_price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n\r\n if (doge_price - float(trades['price'])) >= 0.00002 or \\\r\n (doge_price - float(trades['price'])) <= -0.00002:\r\n robin_stocks.cancel_all_crypto_orders()\r\n print(\"Price change. Order has been canceled. Trying again\")\r\n buy_mode()\r\n\r\n\r\ndef sell_mode():\r\n global buy_price, have_doge, sell_price, quantity\r\n\r\n old_created = (robin_stocks.orders.get_all_crypto_orders()[0]['created_at'])\r\n quantity = robin_stocks.crypto.get_crypto_positions('quantity_available')[0]\r\n doge_price = stat_tracker.price\r\n while True:\r\n if stat_tracker.price > float(buy_price):\r\n if (stat_tracker.price - buy_price) >= 0.000005:\r\n set_speed = stat_tracker.true_speed\r\n while True:\r\n if stat_tracker.true_speed > set_speed:\r\n set_speed = stat_tracker.true_speed\r\n if stat_tracker.true_speed + stat_tracker.true_speed <= set_speed:\r\n break\r\n else:\r\n print('Price still rising, waiting to sell. True speed = ' + str(stat_tracker.true_speed))\r\n continue\r\n\r\n print(robin_stocks.orders.order_sell_crypto_by_quantity(\"DOGE\", quantity, 'mark_price'))\r\n print('sell order placed')\r\n time.sleep(0.4)\r\n print('checking for transaction')\r\n flag = False\r\n\r\n while True:\r\n trades = robin_stocks.orders.get_all_crypto_orders()[0]\r\n if trades['created_at'] != old_created:\r\n if not flag:\r\n flag = True\r\n print('found transaction. will alert when purchase confirmed.')\r\n\r\n if trades['state'] == 'filled':\r\n sell_price = trades['average_price']\r\n quantity = trades['quantity']\r\n print(str(quantity) + \" DOGE coins sold at market price \" + str(doge_price))\r\n save_data(sell_price, buy_price, have_doge, quantity)\r\n buy_mode()\r\n\r\n doge_price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n\r\n if (stat_tracker.price - float(trades['price'])) <= -0.00002:\r\n robin_stocks.cancel_all_crypto_orders()\r\n print(\"Price raised. Order has been canceled. Trying again\")\r\n sell_mode()\r\n else:\r\n print(\"SELL MODE | Doge price: \" + str(doge_price) + '\\t| SO CLOSE |\\t' + 'Bought Doge: ' + str(\r\n buy_price)\r\n + \" | Price difference: \" + str((doge_price - buy_price).__round__(9)))\r\n time.sleep(0.4)\r\n\r\n else:\r\n print('\\tSELL MODE | Price = ' + str(stat_tracker.price) + '\\t\\t Buy Price = ' + str(\r\n buy_price) + '\\t\\t Speed = ' +\r\n str(stat_tracker.speed) + '\\t\\t True Speed = ' + str(stat_tracker.true_speed) + '\\t\\t Direction = ' + str(stat_tracker.direction))\r\n time.sleep(0.4)\r\n\r\n\r\ndef save_data(sell, buy, have, quan):\r\n file1 = open('data.txt', 'w+')\r\n if sell is None:\r\n sell = -1\r\n if buy is None:\r\n buy = -1\r\n if quan is None:\r\n quan = -1\r\n file1.write(str(sell) + '\\n' + str(buy) + '\\n' + str(have) + '\\n' + str(quan))\r\n file1.close()\r\n\r\n\r\nclass StatTracker(object):\r\n\r\n def __init__(self):\r\n\r\n self.direction = 0\r\n self.speed = 0\r\n self.true_speed = 0\r\n self.last_30 = []\r\n self.price = 0\r\n self.sum = 0\r\n\r\n thread = Thread(target=self.run, args=())\r\n thread.daemon = True\r\n thread.start()\r\n\r\n def run(self):\r\n while True:\r\n price = float(robin_stocks.crypto.get_crypto_quote(\"DOGE\")['mark_price'])\r\n self.last_30.insert(0, price)\r\n try:\r\n if self.last_30[60] is not None:\r\n self.last_30.__delitem__(60)\r\n except IndexError:\r\n pass\r\n\r\n if len(self.last_30) > 1:\r\n if self.last_30[1] - self.last_30[0] < 0:\r\n self.direction = 1\r\n elif self.last_30[1] - self.last_30[0] > 0:\r\n self.direction = -1\r\n else:\r\n self.direction = 0\r\n for x in range(len(self.last_30) - 1):\r\n self.sum += (self.last_30[x + 1] - self.last_30[x])\r\n self.sum *= 100000\r\n self.speed = (self.sum / (len(self.last_30) - 1)).__round__(6)\r\n self.speed *= -1\r\n self.sum = 0\r\n if len(self.last_30) > 5:\r\n self.true_speed = (((self.last_30[0] - self.last_30[1])\r\n + (self.last_30[1] - self.last_30[2])\r\n + (self.last_30[2] - self.last_30[3])\r\n + (self.last_30[3] - self.last_30[4])\r\n + (self.last_30[4] - self.last_30[5])) / 5)\r\n self.price = self.last_30[0]\r\n time.sleep(0.3)\r\n\r\n\r\nstat_tracker = StatTracker\r\nwhile True:\r\n while True:\r\n try:\r\n stat_tracker = StatTracker()\r\n setup()\r\n except ConnectionError:\r\n print(\"Connection Error.\")\r\n continue\r\n except ProtocolError:\r\n print(\"Protocol Error\")\r\n continue\r\n except OSError:\r\n print(\"OS Error\")\r\n continue\r\n except RecursionError:\r\n print(\"Recursion Error\")\r\n continue\r\n\r\n","sub_path":"RobinHood1.py","file_name":"RobinHood1.py","file_ext":"py","file_size_in_byte":8403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60477999","text":"\"\"\"\nImplementation of flexx.event in JS via PyScript.\n\"\"\"\n\nimport json\n\nfrom flexx.pyscript import py2js as py2js_\nfrom flexx.pyscript.parser2 import get_class_definition\n\nfrom flexx.event._emitters import BaseEmitter, Property\nfrom flexx.event._handler import HandlerDescriptor, Handler\nfrom flexx.event._hasevents import HasEvents\n\n\nObject = Date = undefined = None # fool pyflake\n\nreprs = json.dumps\n\n\ndef py2js(*args, **kwargs):\n kwargs['inline_stdlib'] = False\n kwargs['docstrings'] = False\n return py2js_(*args, **kwargs)\n\n\nclass HasEventsJS:\n \"\"\" An implementation of the HasEvents class in PyScript. It has\n some boilerplate code to create handlers and emitters, but otherwise\n shares most of the code with the Python classes by transpiling their\n methods via PyScript. This ensures that the Python and JS\n implementation of this event system have the same API and behavior.\n \n The Python version of this class has a ``JSCODE`` attribute that\n contains the auto-generated JavaScript for this class.\n \"\"\"\n \n _HANDLER_COUNT = 0\n _IS_HASEVENTS = True\n \n def __init__(self, init_handlers=True):\n \n # Init some internal variables\n self.__handlers = {}\n self.__props_being_set = {}\n self.__initial_pending_events = []\n \n # Create properties\n for name in self.__properties__:\n self.__handlers.setdefault(name, [])\n self['_' + name + '_value'] = None # need *something*\n for name in self.__properties__:\n func = self['_' + name + '_func']\n creator = self['__create_' + func.emitter_type]\n creator(name)\n if func.default is not undefined:\n self._set_prop(name, func.default, True)\n \n # Create emitters\n for name in self.__emitters__:\n self.__handlers.setdefault(name, [])\n func = self['_' + name + '_func']\n self.__create_Emitter(name)\n \n # Init handlers and properties now, or later?\n if init_handlers:\n self._init_handlers()\n \n def __init_handlers(self, initial_pending_events):\n # Create handlers\n # Note that methods on_xxx are converted by the HasEvents meta class\n for name in self.__handlers__:\n func = self['_' + name + '_func']\n self[name] = self.__create_Handler(func, name, func._connection_strings)\n # Emit events for properties\n for ev in initial_pending_events:\n self._emit(ev)\n \n def __connect(self, func, *connection_strings):\n # The JS version (no decorator functionality)\n \n if len(connection_strings) == 0:\n raise RuntimeError('connect() (js) needs one or more connection strings.')\n \n for s in connection_strings:\n if not (isinstance(s, str) and len(s)):\n raise ValueError('Connection string must be nonempty strings.')\n \n if not callable(func):\n raise TypeError('connect() decotator requires a callable.')\n return self.__create_Handler(func, func.name or 'anonymous', connection_strings)\n \n def __create_PyProperty(self, name):\n self.__create_Property(name)\n \n def __create_Property(self, name):\n private_name = '_' + name + '_value'\n def getter():\n return self[private_name]\n def setter(x):\n self._set_prop(name, x)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Readonly(self, name):\n private_name = '_' + name + '_value'\n def getter():\n return self[private_name]\n def setter(x):\n raise AttributeError('Readonly %s is not settable' % name)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Emitter(self, name):\n def getter():\n return self._get_emitter(name)\n def setter(x):\n raise AttributeError('Emitter %s is not settable' % name)\n opts = {'enumerable': True, 'configurable': True, # i.e. overloadable\n 'get': getter, 'set': setter}\n Object.defineProperty(self, name, opts)\n \n def __create_Handler(self, func, name, connection_strings):\n \n # Create function that becomes our \"handler object\"\n def handler(*events):\n return func.apply(self, events)\n \n # Attach methods to the function object (this gets replaced)\n HANDLER_METHODS_HOOK # noqa\n \n # Init handler\n that = self\n HasEvents.prototype._HANDLER_COUNT += 1\n handler._name = name\n handler._id = 'h' + str(HasEvents.prototype._HANDLER_COUNT)\n handler._ob = lambda : that # no weakref in JS\n handler._init(connection_strings, self)\n \n return handler\n\n\ndef get_HasEvents_js():\n \"\"\" Get the final code for the JavaScript version of the HasEvents class.\n \"\"\"\n # Start with our special JS version\n jscode = py2js(HasEventsJS, 'HasEvents')\n # Add the Handler methods\n code = '\\n'\n for name, val in sorted(Handler.__dict__.items()):\n if not name.startswith('__') and callable(val):\n code += py2js(val, 'handler.' + name, indent=1)[4:]\n code += '\\n'\n jscode = jscode.replace('HANDLER_METHODS_HOOK', code)\n # Add the methods from the Python HasEvents class\n code = '\\n'\n for name, val in sorted(HasEvents.__dict__.items()):\n if name.startswith(('__', '_HasEvents__')) or not callable(val):\n continue\n code += py2js(val, 'HasEvents.prototype.' + name)\n code += '\\n'\n jscode += code\n # Almost done\n jscode = jscode.replace('new Dict()', '{}').replace('new Dict(', '_pyfunc_dict(')\n return jscode\n\n\nHasEventsJS.JSCODE = get_HasEvents_js()\n\n\ndef create_js_hasevents_class(cls, cls_name, base_class='HasEvents.prototype'):\n \"\"\" Create the JS equivalent of a subclass of the HasEvents class.\n \n Given a Python class with handlers, properties and emitters, this\n creates the code for the JS version of this class. It also supports\n class constants that are int/float/str, or a tuple/list thereof.\n The given class does not have to be a subclass of HasEvents.\n \n This more or less does what HasEventsMeta does, but for JS.\n \"\"\"\n \n assert cls_name != 'HasEvents' # we need this special class above instead\n \n handlers = []\n emitters = []\n properties = []\n total_code = []\n funcs_code = [] # functions and emitters go below class constants\n const_code = []\n err = ('Objects on JS HasEvents classes can only be int, float, str, '\n 'or a list/tuple thereof. Not %s -> %r.')\n \n total_code.append('\\n'.join(get_class_definition(cls_name, base_class)).rstrip())\n prefix = '' if cls_name.count('.') else 'var '\n total_code[0] = prefix + total_code[0]\n \n # Functions to ignore\n special_funcs = ['_%s_func' % name for name in \n (cls.__handlers__ + cls.__emitters__ + cls.__properties__)]\n OK_MAGICS = ('__properties__', '__emitters__', '__handlers__',\n '__proxy_properties__', '__emitter_flags__')\n \n for name, val in sorted(cls.__dict__.items()):\n name = name.replace('_JS__', '_%s__' % cls_name.split('.')[-1]) # fix mangling\n funcname = '_' + name + '_func'\n if name in special_funcs:\n pass\n elif isinstance(val, BaseEmitter):\n if isinstance(val, Property):\n properties.append(name)\n else:\n emitters.append(name)\n # Add function def\n code = py2js(val._func, cls_name + '.prototype.' + funcname)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n # Mark to not bind the func\n t = '%s.prototype.%s.nobind = true;'\n funcs_code.append(t % (cls_name, funcname))\n # Has default val?\n if isinstance(val, Property) and val._defaults:\n default_val = json.dumps(val._defaults[0])\n t = '%s.prototype.%s.default = %s;'\n funcs_code.append(t % (cls_name, funcname, default_val))\n # Add type of emitter\n t = '%s.prototype.%s.emitter_type = %s;'\n emitter_type = val.__class__.__name__\n funcs_code.append(t % (cls_name, funcname, reprs(emitter_type)))\n funcs_code.append('')\n elif isinstance(val, HandlerDescriptor):\n handlers.append(name)\n # Add function def\n code = py2js(val._func, cls_name + '.prototype.' + funcname)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n # Mark to not bind the func\n t = '%s.prototype.%s.nobind = true;'\n funcs_code.append(t % (cls_name, funcname))\n # Add connection strings to the function object\n t = '%s.prototype.%s._connection_strings = %s;'\n funcs_code.append(t % (cls_name, funcname, reprs(val._connection_strings)))\n funcs_code.append('')\n elif callable(val):\n code = py2js(val, cls_name + '.prototype.' + name)\n code = code.replace('super()', base_class) # fix super\n funcs_code.append(code.rstrip())\n funcs_code.append('')\n elif name in OK_MAGICS:\n t = '%s.prototype.%s = %s;'\n const_code.append(t % (cls_name, name, reprs(val)))\n elif name.startswith('__'):\n pass # we create our own __emitters__, etc.\n else:\n try:\n serialized = json.dumps(val)\n except Exception as err: # pragma: no cover\n raise ValueError('Attributes on JS HasEvents class must be '\n 'JSON compatible.\\n%s' % str(err))\n #const_code.append('%s.prototype.%s = JSON.parse(%s)' %\n # (cls_name, name, reprs(serialized)))\n const_code.append('%s.prototype.%s = %s;' % (cls_name, name, serialized))\n \n if const_code:\n total_code.append('')\n total_code.extend(const_code)\n if funcs_code:\n total_code.append('')\n total_code.extend(funcs_code)\n total_code.append('')\n return '\\n'.join(total_code)\n\n\nif __name__ == '__main__':\n # Testing ...\n from flexx import event\n class Foo(HasEvents):\n @event.prop\n def foo(self, v=0):\n return v\n \n print(HasEventsJS.JSCODE)\n print(len(HasEventsJS.JSCODE))\n #print(create_js_hasevents_class(Foo, 'Foo'))\n","sub_path":"flexx/event/_js.py","file_name":"_js.py","file_ext":"py","file_size_in_byte":10933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476527018","text":"\"\"\"\r\nBase Operator\r\n\r\nAll Operations should inherit from this class, it will help ensure a common\r\nstructure to Operation classes and provide some common functionality and\r\ninterfaces.\r\n\r\nThis Base Operator is relatively complex but serves to simplify the\r\nimplementation of functional Operators so engineers can focus on handling data,\r\nnot getting a pipeline to work.\r\n\"\"\"\r\nimport abc # abstract base class library\r\nimport inspect\r\nimport functools\r\nimport hashlib\r\nimport time\r\nimport datetime\r\nimport types\r\nimport sys\r\nimport networkx as nx # type:ignore\r\nfrom gva.logging import get_logger # type:ignore\r\nfrom ..runner import go, finalize, attach_writer, attach_writers\r\nfrom typing import Union, List\r\nfrom ...errors import RenderErrorStack\r\nfrom ...data.formats import dictset\r\nfrom ...utils.json import parse, serialize\r\n\r\n# This is the hash of the code in the version function we don't ever want this\r\n# method overidden, so we're going to make sure the hash still matches\r\nVERSION_HASH = \"54ebb39c76dd9159475b723dc2467e2a6a9c4cf794388c9f8c7ec0a777c90f17\"\r\n# This is the hash of the code in the __call__ function we don't ever want this\r\n# method overidden, so we're going to make sure the hash still matches\r\nCALL_HASH = \"3bf4f5fd5986a799cb29db45620cddeffebb1cf09a3af946e68d28370f65d194\"\r\n\r\n\r\n# inheriting ABC is part of ensuring that this class only ever\r\n# interited from\r\nclass BaseOperator(abc.ABC):\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Operator Base Class\r\n\r\n You are expected to override the execute method with the logic of the\r\n operation, this should return None, if the pipeline should terminate\r\n at this operation (for example, if the Operator filters records),\r\n return a tuple of (data, context), or a generator/list of (data,\r\n context).\r\n\r\n The '__call__' and 'version' methods should not be overriden, steps\r\n are taken to help ensure they aren't.\r\n\r\n - retry_count: the number of times to attempt an operation before\r\n aborting, this defaults to 2 and is limited between 1 and 5\r\n - retry_wait: the number of seconds to wait between retries, this\r\n defaults to 5 and is limited between 1 and 300\r\n - rolling_failure_window: the number of previous operations to\r\n remember the success/failure, when >50% of the operations in this\r\n window are failures, the job aborts. This defaults to 10 and is\r\n limited between 1 (single failure aborts) and 100\r\n \"\"\"\r\n self.graph = None # part of drawing dags\r\n self.records_processed = 0 # number of times this operator has been run\r\n self.execution_time_ns = 0 # nano seconds of cpu execution time\r\n self.errors = 0 # number of errors\r\n self.commencement_time = None # the time processing started\r\n self.first_run = True # so some things only run once\r\n self.logger = get_logger() # get the GVA logger\r\n\r\n # read retry settings, clamp values to practical ranges\r\n self.retry_count = self._clamp(kwargs.get('retry_count', 2), 1, 5)\r\n self.retry_wait = self._clamp(kwargs.get('retry_wait', 5), 1, 300)\r\n rolling_failure_window = self._clamp(kwargs.get('rolling_failure_window', 10), 1, 100)\r\n self.last_few_results = [1] * rolling_failure_window # track the last n results\r\n\r\n # Detect version and __call__ being overridden\r\n # call_hash = self.hash(inspect.getsource(self.__call__))\r\n # if call_hash != CALL_HASH:\r\n # raise Exception(F\"Operator's __call__ method must not be overridden - discovered hash was {call_hash}\")\r\n # version_hash = self.hash(inspect.getsource(self.version))\r\n # if version_hash != VERSION_HASH:\r\n # raise Exception(F\"Operator's version method must not be overridden - discovered hash was {version_hash}\")\r\n\r\n\r\n @abc.abstractmethod\r\n def execute(self, data: dict = {}, context: dict = {}):\r\n \"\"\"\r\n YOU MUST OVERRIDE THIS METHOD\r\n\r\n This is where the main logic for the Operator is implemented.\r\n It should expect a single record and return:\r\n\r\n - None = do not continue further through the flow\r\n - (data, context) = pass data to the next operation\r\n - list(data, context) = run the next operator multiple times\r\n\r\n The list can be a generator.\r\n \"\"\"\r\n raise NotImplementedError(\"execute method must be overridden\") # pragma: no cover\r\n\r\n def __call__(self, data: dict = {}, context: dict = {}):\r\n \"\"\"\r\n DO NOT OVERRIDE THIS METHOD\r\n\r\n This method wraps the `execute` method, which must be overridden, to\r\n to add management of the execution such as sensors and retries.\r\n \"\"\"\r\n if self.first_run:\r\n self.first_run = False\r\n self.commencement_time = datetime.datetime.now()\r\n self.records_processed += 1\r\n attempts_to_go = self.retry_count\r\n while attempts_to_go > 0:\r\n try:\r\n start_time = time.perf_counter_ns()\r\n outcome = self.execute(data, context)\r\n my_execution_time = time.perf_counter_ns() - start_time\r\n self.execution_time_ns += my_execution_time\r\n # add a success to the last_few_results list\r\n self.last_few_results.append(1)\r\n self.last_few_results.pop(0)\r\n break\r\n except Exception as err:\r\n self.errors += 1\r\n attempts_to_go -= 1\r\n if attempts_to_go:\r\n self.logger.error(F\"{self.__class__.__name__} - {type(err).__name__} - {err} - retry in {self.retry_wait} seconds ({context.get('uuid')})\")\r\n time.sleep(self.retry_wait)\r\n else:\r\n error_log_reference = ''\r\n error_reference = err\r\n try:\r\n error_payload = (\r\n F\"timestamp : {datetime.datetime.today().isoformat()}\\n\"\r\n F\"operator : {self.__class__.__name__}\\n\"\r\n F\"error type : {type(err).__name__}\\n\"\r\n F\"details : {err}\\n\"\r\n \"----------------------------------------------------------------------------------------------------\\n\"\r\n F\"{RenderErrorStack()}\\n\"\r\n \"--------------------------------------------- context --------------------------------------------\\n\"\r\n F\"{context}\\n\"\r\n \"---------------------------------------------- data ----------------------------------------------\\n\"\r\n F\"{data}\\n\"\r\n \"----------------------------------------------------------------------------------------------------\\n\")\r\n error_log_reference = self.error_writer(error_payload) # type:ignore\r\n except Exception as err:\r\n self.logger.error(F\"Problem writing to the error bin, a record has been lost. {type(err).__name__} - {err} - {context.get('uuid')}\")\r\n finally:\r\n # finally blocks are called following a try/except block regardless of the outcome\r\n self.logger.error(F\"{self.__class__.__name__} - {type(error_reference).__name__} - {error_reference} - tried {self.retry_count} times before aborting ({context.get('uuid')}) {error_log_reference}\")\r\n outcome = None\r\n # add a failure to the last_few_results list\r\n self.last_few_results.append(0)\r\n self.last_few_results.pop(0)\r\n\r\n # message tracing\r\n if context.get('trace', False):\r\n data_hash = self.hash(data)\r\n context['execution_trace'].add_block(data_hash=data_hash,\r\n operator=self.__class__.__name__,\r\n operator_version=self.version(),\r\n execution_ns=my_execution_time,\r\n data_block=serialize(data))\r\n self.logger.trace(F\"{context.get('uuid')} {self.__class__.__name__} {data_hash}\")\r\n\r\n # if there is a high failure rate, abort\r\n if sum(self.last_few_results) < (len(self.last_few_results) / 2):\r\n self.logger.critical(F\"Failure Rate for {self.__class__.__name__} over last {len(self.last_few_results)} executions is over 50%, aborting.\")\r\n sys.exit(1)\r\n\r\n return outcome\r\n\r\n def read_sensors(self):\r\n \"\"\"\r\n Format data about the transformation, this can be overridden but it\r\n should include this information\r\n \"\"\"\r\n response = {\r\n \"operator\": self.__class__.__name__,\r\n \"version\": self.version(),\r\n \"records_processed\": self.records_processed,\r\n \"error_count\": self.errors,\r\n \"execution_sec\": self.execution_time_ns / 1e9\r\n }\r\n if self.commencement_time:\r\n response['commencement_time'] = self.commencement_time.isoformat()\r\n return response\r\n\r\n @functools.lru_cache(1)\r\n def version(self):\r\n \"\"\"\r\n DO NOT OVERRIDE THIS METHOD.\r\n\r\n The version of the operator code, this is intended to facilitate\r\n reproducability and auditability of the pipeline. The version is the\r\n last 12 characters of the hash of the source code of the 'execute'\r\n method. This removes the need for the developer to remember to\r\n increment a version variable.\r\n\r\n Hashing isn't security sensitive here, it's to identify changes\r\n rather than protect information.\r\n \"\"\"\r\n source = inspect.getsource(self.execute)\r\n full_hash = hashlib.sha224(source.encode())\r\n return full_hash.hexdigest()[-12:]\r\n\r\n def __del__(self):\r\n # do nothing - prevents errors if someone calls super().__del__\r\n pass\r\n\r\n def error_writer(self, record):\r\n # this is a stub to be overridden\r\n raise ValueError('no error_writer attached')\r\n\r\n def __gt__(self, next_operators: Union[List[nx.DiGraph], nx.DiGraph]):\r\n \"\"\"\r\n Smart flow/DAG builder. This allows simple flows to be defined using\r\n the following syntax:\r\n\r\n Op1 > Op2 > Op3\r\n\r\n The builder adds support functions to the resulting 'flow' object.\r\n \"\"\"\r\n # make sure the next_operator is iterable\r\n if not isinstance(next_operators, list):\r\n next_operators = [next_operators]\r\n if self.graph:\r\n # if I have a graph already, build on it\r\n graph = self.graph\r\n else:\r\n # if I don't have a graph, create one\r\n graph = nx.DiGraph()\r\n graph.add_node(F\"{self.__class__.__name__}-{id(self)}\", function=self)\r\n for operator in next_operators:\r\n if isinstance(operator, nx.DiGraph):\r\n # if we're pointing to a graph, merge with the current graph,\r\n # we need to find the node with no incoming nodes we identify\r\n # the entry-point\r\n graph = nx.compose(operator, graph)\r\n graph.add_edge(\r\n F\"{self.__class__.__name__}-{id(self)}\",\r\n [node for node in operator.nodes() if len(graph.in_edges(node)) == 0][0],\r\n )\r\n elif issubclass(type(operator), BaseOperator):\r\n # otherwise add the node and edge and set the graph further\r\n # down the line\r\n graph.add_node(F\"{operator.__class__.__name__}-{id(operator)}\", function=operator)\r\n graph.add_edge(F\"{self.__class__.__name__}-{id(self)}\", F\"{operator.__class__.__name__}-{id(operator)}\")\r\n operator.graph = graph\r\n else:\r\n label = type(operator).__name__\r\n if hasattr(operator, '__name__'):\r\n label = operator.__name__\r\n # deepcode ignore return~not~implemented: Error is a TypeError\r\n raise TypeError(F\"Operator {label} must inherit BaseOperator, this error also occurs when the Operator has not been correctly instantiated.\")\r\n # this variable only exists to build the graph, we don't need it\r\n # anymore so destroy it\r\n self.graph = None\r\n\r\n # extend the base DiGraph class with flow helper functions\r\n graph.run = types.MethodType(go, graph)\r\n graph.finalize = types.MethodType(finalize, graph)\r\n graph.attach_writer = types.MethodType(attach_writer, graph)\r\n graph.attach_writers = types.MethodType(attach_writers, graph)\r\n\r\n return graph\r\n\r\n def _clamp(self, value, low_bound, high_bound):\r\n \"\"\"\r\n 'clamping' is fixing a value within a range\r\n \"\"\"\r\n if value <= low_bound:\r\n return low_bound\r\n if value >= high_bound:\r\n return high_bound\r\n return value\r\n\r\n def hash(self, block):\r\n try:\r\n bytes_object = serialize(block)\r\n except:\r\n bytes_object = str(block)\r\n raw_hash = hashlib.sha256(bytes_object.encode())\r\n hex_hash = raw_hash.hexdigest()\r\n return hex_hash\r\n","sub_path":"gva/flows/operators/base_operator.py","file_name":"base_operator.py","file_ext":"py","file_size_in_byte":13594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69940747","text":"\"\"\"Prvočísla.\"\"\"\n\n# Imports\nimport math\nimport random\n\n__author__ = 'Daniel Jurča'\n__version__ = '1.0.0'\n__email__ = 'd_jurca@utb.cz'\n__status__ = 'Work in progress'\n\n\ndef VolbaAkce():\n \"\"\"\n Volba metody.\n\n Uživatel zvolí, jestli chce zjistit,\n zda je zadané číslo n prvočíslo,\n nebo vypsat prvočísla po číslo n\n \"\"\"\n print(\"Akce:\")\n print(\"1 : Ověření, zda je zadané číslo prvočíslem\")\n print(\"2 : Vypsání prvočísel po n\")\n global akce\n akce = input(\"Vyberte možnost (1/2): \")\n print()\n return akce\n\n\ndef OvereniHodnotyAkce(akce):\n \"\"\"Ověření, zda je volba akce správná.\"\"\"\n try:\n global typAkce\n typAkce = int(akce)\n if typAkce == 1 or typAkce == 2:\n return True\n else:\n return False\n except ValueError:\n return False\n\n\ndef VolbaCisla():\n \"\"\"Volba čísla n.\"\"\"\n global zadaneCislo\n zadaneCislo = input(\"Zadejte číslo n: \")\n return zadaneCislo\n\n\ndef OvereniHodnotyCisla(zadaneCislo):\n \"\"\"Ověření, zda je zadané číslo integer.\"\"\"\n try:\n global cislo\n cislo = int(zadaneCislo)\n if cislo >= 0:\n return True\n else:\n return False\n except ValueError:\n return False\n\n\ndef Determinacni(cislo):\n \"\"\"Jednoduchá metoda.\"\"\"\n if cislo == 1:\n return False\n if cislo == 2:\n return True\n if cislo % 2 == 0:\n return False\n\n i = 3\n while i <= math.sqrt(cislo):\n if cislo % i == 0:\n return False\n i = i+2\n\n return True\n\n\ndef Fermat(cislo):\n \"\"\"Fermatovo prvočíslo, složitější metoda.\"\"\"\n if (cislo > 1):\n for time in range(3):\n nahodneCislo = random.randint(2, cislo)-1\n if (pow(nahodneCislo, cislo-1, cislo) != 1):\n return False\n return True\n else:\n return False\n\n\ndef UrciPrvocislo(cislo):\n \"\"\"Určení prvočísla.\n\n Unittest:\n >>> UrciPrvocislo(421)\n 421 je prvočíslo\n Metoda: determinační\n\n >>> UrciPrvocislo(8)\n 8 není prvočíslo\n Metoda: determinační\n\n >>> UrciPrvocislo(1010)\n 1010 není prvočíslo\n Metoda: Statistická - Fermatova\n\n >>> UrciPrvocislo(1033)\n 1033 je prvočíslo\n Metoda: Statistická - Fermatova\n \"\"\"\n if cislo < 1000:\n if Determinacni(cislo) is True:\n print(str(cislo) + \" je prvočíslo\")\n else:\n print(str(cislo) + \" není prvočíslo\")\n print(\"Metoda: determinační\")\n elif cislo >= 1000:\n if Fermat(cislo) is True:\n print(str(cislo) + \" je prvočíslo\")\n else:\n print(str(cislo) + \" není prvočíslo\")\n print(\"Metoda: Statistická - Fermatova\")\n\n\ndef VypisPrvocisel(cislo):\n \"\"\"Výpis prvočísel do čísla n.\n\n Unittest:\n >>> VypisPrvocisel(10)\n Prvočísla:\n 2 3 5 7\n\n >>> VypisPrvocisel(100)\n Prvočísla:\n 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97\n\n >>> VypisPrvocisel(1)\n Prvočísla:\n \n \"\"\"\n print(\"Prvočísla:\")\n f = \"\"\n for num in range(2, cislo+1):\n if all(num % i != 0 for i in range(2, num)):\n f += str(num) + ' '\n f = f[:-1]\n print(f)\n\n\ndef ProvedAkci(typAkce, cislo):\n \"\"\"Provede zvolenou akci.\n\n Unittest:\n >>> ProvedAkci(3, 0)\n Chyba u volby akce\n\n >>> ProvedAkci(2, 10)\n Prvočísla:\n 2 3 5 7\n\n >>> ProvedAkci(1, 11)\n 11 je prvočíslo\n Metoda: determinační\n \"\"\"\n if typAkce == 1:\n UrciPrvocislo(cislo)\n elif typAkce == 2:\n VypisPrvocisel(cislo)\n else:\n print(\"Chyba u volby akce\")\n\n\ndef main():\n \"\"\"Spuštění programu.\"\"\"\n VolbaAkce()\n while OvereniHodnotyAkce(akce) is False:\n print(\"Zadejte číslo 1 nebo 2\")\n print()\n VolbaAkce()\n\n VolbaCisla()\n while OvereniHodnotyCisla(zadaneCislo) is False:\n print(\"n musí být celé číslo\")\n print()\n VolbaCisla()\n\n ProvedAkci(typAkce, cislo)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Primes/Primes.py","file_name":"Primes.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296928205","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg_top = cv2.imread('Images/demo01.jpg')\nprint('img_right size :',img_top.shape)\nimg_top_gray = cv2.cvtColor(img_top,cv2.COLOR_BGR2GRAY)\n\nimg_bot = cv2.imread('Images/demo02.jpg')\nimg_bot_gray = cv2.cvtColor(img_bot,cv2.COLOR_BGR2GRAY)\n\nsift = cv2.xfeatures2d.SIFT_create()\n# find key points\nkp1, des1 = sift.detectAndCompute(img_top_gray,None)\nkp2, des2 = sift.detectAndCompute(img_bot_gray,None)\n\n#cv2.imshow('original_image_left_keypoints',cv2.drawKeypoints(img_,kp1,None))\n\n#FLANN_INDEX_KDTREE = 0\n#index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n#search_params = dict(checks = 50)\n#match = cv2.FlannBasedMatcher(index_params, search_params)\nmatch = cv2.BFMatcher()\nmatches = match.knnMatch(des1,des2,k=2)\n\ngood = []\nfor m,n in matches:\n if m.distance < 0.18*n.distance:\n good.append(m)\nprint(\"特征点匹配的对数:\",len(good))\n\ndraw_params = dict(matchColor=(0,255,0),\n singlePointColor=None,\n flags=2)\n\nimg3 = cv2.drawMatches(img_top,kp1,img_top,kp2,good,None,**draw_params)\n#cv2.imshow(\"original_image_drawMatches.jpg\", img3)\n#good = good[0:4]\nMIN_MATCH_COUNT = 10\nif len(good) > MIN_MATCH_COUNT:\n src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,2)\n dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,2)\n print(len(src_pts))\n M,mask = cv2.findHomography(dst_pts, src_pts,cv2.RANSAC,5.0)\n print(\"findHo-M:\",M)\n print(\"输入序列点的长度:\",len(src_pts))\n print(\"len(mask) :\",len(mask))\n print(\"mask\", mask)\n h,w = img_top_gray.shape\n pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)\n print(pts)\n dst = cv2.perspectiveTransform(pts, M)\n img2 = cv2.polylines(img_top_gray,[np.int32(dst)],True,255,3, cv2.LINE_AA)\n #cv2.imshow(\"original_image_overlapping.jpg\", img2)\n cv2.namedWindow('windows',0)\n cv2.resizeWindow('windows', (800, 600))\n cv2.imshow('windows', img2)\n\nelse:\n print(\"Not enought matches are found - %d/%d\", (len(good)/MIN_MATCH_COUNT))\n\ndst = cv2.warpPerspective(img_bot ,M,(img_top.shape[1]+1000, img_top.shape[0]+1000))\nplt.figure()\nplt.imshow(dst)\n#cv2.imshow('warpPerspective', dst)\ndst[0:2000,0:img_top.shape[1]] = img_top[0:2000,:]\nplt.figure(3)\ndst = cv2.cvtColor(dst,cv2.COLOR_BGR2RGB)\nplt.imshow(dst)\nplt.show()\n","sub_path":"几何变换/单应性(homography)/demo02-stitch-Sift.py","file_name":"demo02-stitch-Sift.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"289206894","text":"test_case_number = int(input())\n\nresult = \"\"\n\nfor loop_number in range(test_case_number):\n input_case = input()\n test_case = [int(number) for number in input_case.split(\" \")]\n\n # 내부에서 바로 해당 테스트케이스에 대해서 계산\n total = sum(test_case)\n avg = round(total/len(test_case))\n if loop_number+1 == test_case_number:\n result += f\"#{loop_number+1} {avg}\"\n else:\n result += f\"#{loop_number+1} {avg}\\n\"\n\nprint(result)\n","sub_path":"PYTHON/SWEXPERT/익스퍼트미분류/D1/2071_평균값_구하기.py","file_name":"2071_평균값_구하기.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462302343","text":"'''\nCreated by auto_sdk on 2015.12.22\n'''\nfrom tmallsdk.api.base import RestApi\nclass AlitripTicketSkuPriceModifyRequest(RestApi):\n\tdef __init__(self,domain='gw.api.taobao.com',port=80):\n\t\tRestApi.__init__(self,domain, port)\n\t\tself.item_id = None\n\t\tself.outer_id = None\n\t\tself.price = None\n\t\tself.sku_id = None\n\n\tdef getapiname(self):\n\t\treturn 'taobao.alitrip.ticket.sku.price.modify'\n","sub_path":"tmallsdk/api/rest/AlitripTicketSkuPriceModifyRequest.py","file_name":"AlitripTicketSkuPriceModifyRequest.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514516921","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup\nfrom pyblocksim.release import __version__\n\nwith open(\"requirements.txt\") as requirements_file:\n requirements = requirements_file.read()\n\nsetup(\n name='pyblocksim',\n version=__version__,\n author='Carsten Knoll',\n author_email='Carsten.Knoll@tu-dresden.de',\n packages=['pyblocksim'],\n url='https://github.com/TUD-RST/pycartan',\n license='GPL3',\n description='Python library for block-oriented modeling and simlation in control theory',\n long_description=\"\"\"Pyblocksim aims to mitigate the lack of a tool like Simulink (or scicos)\nin the world of python based scientific computing.\nIt aims to enable you to quickly implement a model of a dynamic system\nwhich is suited to be modeled by the feedback-free\ndirected interconnection of blocks such as transfer functions.\n \"\"\",\n keywords='control theory, simulation, modelling, feedback',\n install_requires=requirements,\n)\n","sub_path":"pypi_install_script/pyblocksim-0.3.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"157868127","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom models.lorentzian_model import DualLorentzianModel, SlopedNoiseLorentzianModel\nimport data\nfrom data_analyzing.misc import *\n\nsavetime = True\ndo_plot = False\nSA_index = \"1\"\nSQ_index = [str(i) for i in range(3, 20)]\n\nif __name__ == \"__main__\":\n sorted = sort_data(data.SEPARATION_SWEEP)\n \"\"\"\n plot the whole folder\n \"\"\"\n if do_plot:\n for key in sorted[\"Hetero\"].keys():\n x, raw = np.loadtxt(sorted[\"Hetero\"][key][1], delimiter=\",\").T\n x, bg = np.loadtxt(sorted[\"HeteroBG\"][key][1], delimiter=\",\").T\n y = normalize(raw, bg)\n plt.plot(x, y, lw=0.5)\n plt.xlabel(\"Frequency(Hz)\")\n plt.ylabel(\"Amplitude(dBm)\")\n plt.title(key)\n plt.show()\n plt.cla()\n \"\"\"\n read from .spe\n \"\"\"\n spe = parse_spe(sorted[\"Hetero\"][SA_index][0])\n P_mon = float(spe[\"PowerMonFinal\"])\n P_ref = float(spe[\"PowerRefFinal\"])\n P_mon_factor = float(spe[\"PmonFactor\"])\n P_ref_factor = float(spe[\"PrefFactor\"])\n P_mon_blue = float(spe[\"PowerMonBlue\"])\n P_mon_Cool = float(spe[\"PowerMonCool\"])\n omega_m = float(spe[\"OmegaM\"])\n separation1 = float(spe[\"PLLOffset1\"])\n separation2 = float(spe[\"PLLOffset2\"])\n \"\"\"\n sideband asymmetry on single trace\n \"\"\"\n data = np.loadtxt(sorted[\"Hetero\"][SA_index][1], delimiter=\",\").T\n background = np.loadtxt(sorted[\"HeteroBG\"][SA_index][1], delimiter=\",\").T\n x = data[0]\n y = normalize(data[1], background[1])\n model = DualLorentzianModel()\n model.observe(x, y)\n if savetime:\n opt, std = model.least_square_fit(x, y)\n else:\n opt, std = model.mcmc_fit()\n a1, a2, p1, p2, w_m = opt[:5]\n plt.plot(x, y, label=\"data\", lw=0.5)\n plt.plot(x, model.get_func()(x, opt[:-1]), label=\"fit\", lw=0.5)\n plt.legend()\n plt.xlabel(\"frequency(Hz)\")\n plt.ylabel(\"amplitude(dBm)\")\n plt.show()\n # make sure that left peak goes to a1\n if p1 > p2:\n a1, a2 = a2, a1\n if abs(separation2 - separation1 - omega_m) < abs(separation1 - omega_m):\n a1, a2 = a2, a1\n print(opt)\n n_f = 1 / ((P_mon_Cool * a2) / (P_mon_blue * a1) - 1)\n print(\"n_f from sideband asymmetry:\")\n print(n_f)\n # the coefficient between area and (scattering rate * occupation)\n alpha = a1 * w_m / (P_mon_Cool * n_f)\n \"\"\"\n handle all SQ data in squeezing folder\n \"\"\"\n for key in SQ_index:\n # read from .spe\n spe = parse_spe(sorted[\"Hetero\"][key][0])\n P_mon_blue = float(spe[\"PowerMonBlue\"])\n P_mon_Cool = float(spe[\"PowerMonCool\"])\n # smallest overlapped peak, induct n_beta\n x, data = np.loadtxt(sorted[\"Hetero\"][key][1], delimiter=\",\").T\n x, background = np.loadtxt(sorted[\"HeteroBG\"][key][1], delimiter=\",\").T\n y = normalize(data, background)\n model = SlopedNoiseLorentzianModel()\n model.observe(x, y)\n if savetime:\n opt, std = model.least_square_fit(x, y)\n else:\n opt, std = model.mcmc_fit()\n a, p0, w = opt[:3]\n n_beta = a * w / (alpha * (P_mon_Cool - P_mon_blue))\n r = np.arctanh(np.sqrt(P_mon_blue / P_mon_Cool))\n maximum_quadrature = np.exp(-2 * r) * (1 + 2 * n_beta)\n print(\"key:\")\n print(key)\n print(\"estimated n_beta:\")\n print(n_beta)\n print(\"estimated maximum of X1 quadrature:\")\n print(maximum_quadrature)\n","sub_path":"data_analyzing/scripts/single_separation_sweep.py","file_name":"single_separation_sweep.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214904601","text":"import vimeo\nimport keys\nfrom pprint import pprint\nimport webbrowser\n\nv = vimeo.VimeoClient(\n key=keys.YOUR_CLIENT_ID,\n secret=keys.YOUR_CLIENT_SECRET)\ntry:\n token = v.load_client_credentials()\n pprint(token)\n v = vimeo.VimeoClient(\n token=token,\n key=keys.YOUR_CLIENT_ID,\n secret=keys.YOUR_CLIENT_SECRET)\n videos = v.get('/videos?query=vegas local').json()['data'][:1]\n for video in videos:\n url = video['uri'][8:]\n name = video['name']\n likes = video['metadata']['connections']['likes']['total']\n embed = video['embed']\n pprint(video)\n print(name, url, likes, embed)\n # webbrowser.open_new_tab(url)\nexcept vimeo.auth.GrantFailed:\n print(\"Fail Authentication\")\n\n\n#'","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75034469","text":"'''\nSolution:\n1. To merge k sorted lists, maintain a min heap so that it always maintains k maximum elements at a particular\n point of time and releases min element in those k elements in O(1) operation.\n2. Push into minHeap all head nodes (take care of null checks)\n2. Extract the minNode and move the pointer forward in that corresponding list (take care of null checks)\n\nTime Complexity: O(n.logk) | Space Complexity: O(k)\n\n--- Passed all testcases successfully on Leetcode.\n'''\n\n\nfrom heapq import heappush as push\nfrom heapq import heappop as pop\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass MergeKLists:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n\n # custom less than comparator using a lambda function taking ListNode objects x and y as parameters\n lessThan = lambda x, y: x.val < y.val\n ListNode.__lt__ = lessThan\n\n # initialize an empty list which acts as min heap\n minHeapK = []\n\n # create a dummy head and start the cursor from that node\n dummyHead = ListNode(-1)\n cursorNode = dummyHead\n\n # push into minHeap all head nodes (take care of null checks)\n for i in range(len(lists)):\n currHead = lists[i]\n if (currHead != None):\n push(minHeapK, currHead)\n\n # pop min node and add it to the main linked list, and also push its next node into the min heap (if not null)\n while (len(minHeapK) > 0):\n\n minNode = pop(minHeapK) # pop the min node in the heap\n\n cursorNode.next = minNode\n if (minNode.next != None): # push to the heap only if next node exists\n push(minHeapK, minNode.next)\n\n cursorNode = minNode # update cursor node\n\n # return dummy head's next node\n return dummyHead.next","sub_path":"MergeKSortedLists.py","file_name":"MergeKSortedLists.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"510053966","text":"def income_statement_analysis(income_statement, symbol = 0, log=False):\r\n \r\n '''\r\n Graphically gives an overview of the various income statement items overtime.\r\n When selecting multiple symbols, you are able to visually see the difference\r\n between the companies. \r\n \r\n Parameters\r\n ----------\r\n income_statement : DataFrame\r\n The data created with the cashflows() function.\r\n \r\n symbol : string or list\r\n Company ticker(s) either displayed as a string for one company or as a list\r\n when multiple companies are selected.\r\n\r\n log : boolean\r\n Default on False. Gives the option to convert everything in log values.\r\n \r\n Returns\r\n -------\r\n The following graphs:\r\n total revenue\r\n cost of revenue\r\n general expenses\r\n research development\r\n operating profit\r\n net income\r\n\r\n '''\r\n\r\n import lxml\r\n from lxml import html\r\n import requests\r\n import numpy as np\r\n import pandas as pd\r\n import matplotlib.pyplot as plt\r\n \r\n if symbol == 0:\r\n page = requests.get('https://finance.yahoo.com/trending-tickers')\r\n tree = html.fromstring(page.content)\r\n table = tree.xpath('//table')\r\n symbol = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]['Symbol'].to_list()\r\n print('No input is given thus using the Trending Tickers from Yahoo Finance: https://finance.yahoo.com/trending-tickers')\r\n \r\n total_revenue = pd.DataFrame(index=income_statement.index)\r\n cost_of_revenue = pd.DataFrame(index=income_statement.index)\r\n general_expenses = pd.DataFrame(index=income_statement.index)\r\n research_development = pd.DataFrame(index=income_statement.index)\r\n operating_profit = pd.DataFrame(index=income_statement.index)\r\n net_income = pd.DataFrame(index=income_statement.index)\r\n \r\n \r\n if type(symbol) == list:\r\n if log == True:\r\n import warnings\r\n warnings.filterwarnings('ignore', category=RuntimeWarning)\r\n for x in symbol:\r\n if x in income_statement:\r\n try:\r\n total_revenue[x] = np.log(income_statement[x,'Total Revenue'])\r\n cost_of_revenue[x] = np.log(income_statement[x,'Cost of Revenue'])\r\n general_expenses[x] = np.log(income_statement[x, 'Selling General and Administrative'])\r\n research_development[x] = np.log(income_statement[x,'Research Development'])\r\n operating_profit[x] = np.log(income_statement[x,'Operating Income or Loss'])\r\n net_income[x] = np.log(income_statement[x,'Net Income From Continuing Ops'])\r\n \r\n except KeyError:\r\n continue\r\n \r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()\r\n\r\n else:\r\n for x in symbol:\r\n if x in income_statement:\r\n try:\r\n total_revenue[x] = income_statement[x,'Total Revenue']\r\n cost_of_revenue[x] = income_statement[x,'Cost of Revenue']\r\n general_expenses[x] = income_statement[x, 'Selling General and Administrative']\r\n research_development[x] = income_statement[x,'Research Development']\r\n operating_profit[x] = income_statement[x,'Operating Income or Loss']\r\n net_income[x] = income_statement[x,'Net Income From Continuing Ops']\r\n\r\n except KeyError:\r\n continue\r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()\r\n \r\n else:\r\n total_revenue[symbol] = income_statement[symbol,'Total Revenue']\r\n cost_of_revenue[symbol] = income_statement[symbol,'Cost of Revenue']\r\n general_expenses[symbol] = income_statement[symbol, 'Selling General and Administrative']\r\n research_development[symbol] = income_statement[symbol,'Research Development']\r\n operating_profit[symbol] = income_statement[symbol,'Operating Income or Loss']\r\n net_income[symbol] = income_statement[symbol,'Net Income From Continuing Ops']\r\n\r\n fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(15,15))\r\n total_revenue.plot.bar(ax=axes[0,0], rot=0).set_title('Total Revenue')\r\n cost_of_revenue.plot.bar(ax=axes[0,1], rot=0).set_title('Cost of Revenue (COGS)')\r\n general_expenses.plot.bar(ax=axes[1,0], rot=0).set_title('Selling, General and Administrative Expenses (SG&A)')\r\n research_development.plot.bar(ax=axes[1,1], rot=0).set_title('Research Development')\r\n operating_profit.plot.bar(ax=axes[2,0], rot=0).set_title('Operating Income or Loss')\r\n net_income.plot.bar(ax=axes[2,1], rot=0).set_title('Net Income From Continuing Ops')\r\n plt.show()","sub_path":"FundamentalAnalysis/income_statement_analysis.py","file_name":"income_statement_analysis.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287075359","text":"from __future__ import print_function\nfrom time import sleep\nfrom time import time\nfrom copy import copy\nimport os\nimport sys\nimport math\nsys.path.append('../')\nsys.path.append('../pieces')\n\nfrom random import random\nfrom pieces import ChessPiece\nfrom Board import Board\n\nclass SimulatedAnnealing:\n\tdef __init__(self, request, max_attempt, cooling_rate, temp):\n\t\t\"\"\"This constructs SimulatedAnnealing instance and create Board object.\n\n\t\tParameters\n\t\t----------\n\t\trequest : dictionary\n\t\t\tDictionary of list of piece.\n\n\t\tReturns\n\t\t-------\n\t\tnothing\n\t\t\"\"\"\n\t\tself.__TEMP = temp\n\t\tself.__COOLING_RATE = cooling_rate\n\t\tself.__MAX_ATTEMPTS = max_attempt\n\n\t\tself.__request = request\n\t\tself.__board = Board(request)\n\n\tdef print_immediately(self, attempts, current_heuristic, temp):\n\t\t\"\"\"This method prints Board UI.\n\n\t\tParameters\n\t\t----------\n\t\tattempts : int\n\t\t\tCurrent attempts in t.\n\t\tcurrent_heuristic : int\n\t\t\tCurrent heuristic in t.\n\t\ttemp : int\n\t\t\tCurrent temperature in t.\n\n\t\tReturns\n\t\t-------\n\t\tvoid\n\t\t\tPrints Board UI.\n\t\t\"\"\"\n\t\tprint(\"Attempts\\t\\t= \" + str(attempts))\n\t\tprint(\"Current Heuristic\\t= \" + str(current_heuristic))\n\t\tprint(\"Current Temperature\\t= \" + str(temp), end='\\n\\n')\n\t\tself.__board.draw()\n\t\tsleep(0.025)\n\t\tos.system('clear')\n\n\tdef cooling_down(self, temp):\n\t\t\"\"\"This method returns temp after cooling down.\n\n\t\tParameters\n\t\t----------\n\t\ttemp : int\n\t\t\tCurrent temperature to cool down.\n\n\t\tReturns\n\t\t-------\n\t\tint\n\t\t\treturns colder temperature.\n\n\t\t\"\"\"\n\t\treturn temp * self.__COOLING_RATE\n\n\tdef boltzman_dist(self, e, e1, temp):\n\t\t\"\"\"This method performs boltzman distribution where exp(-(loss/temp)).\n\n\t\tParameters\n\t\t----------\n\t\te1 : int\n\t\t\tNeighbor's heuristic.\n\t\te : int\n\t\t\tCurrent heuristic.\n\t\ttemp : int\n\t\t\tCurrent temperature.\n\n\t\tReturns\n\t\t-------\n\t\tint\n\t\t\tProbability by boltzman.\n\n\t\t\"\"\"\n\t\treturn math.exp((e1 - e) / temp)\n\n\tdef start(self):\n\t\t\"\"\"This method performs simulated annealing algorithm.\n\t\tReturns\n\t\t-------\n\t\tvoid\n\t\t\"\"\"\n\t\tattempts = 1\n\t\tcolors = len(self.__board.get_colors())\n\n\t\tbest = None\n\t\tbest_board = None\n\n\t\tif (colors > 1):\n\t\t\tbest = {'a' : 0, 'b' : -999 ,'total': -999}\n\t\telse:\n\t\t\tbest = {'a' : 999, 'b' : 0, 'total': -999}\n\n\t\t#Calculate current heuristic\n\t\tcurrent_heuristic = self.__board.calculate_heuristic()\n\n\t\t#Start\n\t\tstart = round(time(), 3)\n\n\t\twhile (attempts < self.__MAX_ATTEMPTS):\n\t\t\t#Initialize temperature\n\t\t\ttemp = self.__TEMP\n\t\t\tprint(\"Attempts\\t= \" + str(attempts))\n\n\t\t\t#when temp < 1 -> prob nearly to zero\n\t\t\twhile (temp > 1):\n\t\t\t\t# For the fastest performance, do not update Board UI\n\t\t\t\tself.print_immediately(attempts, current_heuristic, temp)\n\n\t\t\t\t#Call random_pick from board\n\t\t\t\tpiece = self.__board.random_pick()\n\n\t\t\t\t#Store position of piece (temporer)\n\t\t\t\told_position = {'x' : piece.get_x(), 'y' : piece.get_y()}\n\n\t\t\t\t#Random position by call random_move function\n\t\t\t\trand_position = self.__board.random_move()\n\n\t\t\t\t#Replace current position of piece with rand_position\n\t\t\t\tpiece.set_x(rand_position['x'])\n\t\t\t\tpiece.set_y(rand_position['y'])\n\n\t\t\t\t#Calculate heuristic after change to new position\n\t\t\t\theuristic = self.__board.calculate_heuristic()\n\n\t\t\t\tif (current_heuristic['total'] < heuristic['total']):\n\t\t\t\t\t#Absolutely accept the changes, get maximum heuristic\n\t\t\t\t\tcurrent_heuristic = heuristic\n\t\t\t\telse:\n\t\t\t\t\tprobability = self.boltzman_dist(current_heuristic['total'], heuristic['total'], temp)\n\t\t\t\t\tif (random() <= probability):\n\t\t\t\t\t\t#Accept the changes\n\t\t\t\t\t\tcurrent_heuristic = heuristic\n\t\t\t\t\telse:\n\t\t\t\t\t\t#Restore the position of piece, not accept the changes\n\t\t\t\t\t\tpiece.set_x(old_position['x'])\n\t\t\t\t\t\tpiece.set_y(old_position['y'])\n\n\t\t\t\t\ttemp = self.cooling_down(temp)\n\n\t\t\t\tif (current_heuristic['total'] == 0 and colors == 1):\n\t\t\t\t\tfinish = round(time(), 3)\n\t\t\t\t\tos.system('clear')\n\t\t\t\t\tprint(\"Yeay, solution found after\", str(attempts), \"attempt(s)!\")\n\t\t\t\t\tprint(\"Elapsed time = \" + str(finish-start) + \" seconds\\n\")\n\t\t\t\t\tself.__board.draw()\n\t\t\t\t\tprint(\" \", str(current_heuristic['a']), '', str(current_heuristic['b']))\n\t\t\t\t\treturn\n\n\t\t\t#Check if current heuristic is better than current best\n\t\t\tif (best['total'] < current_heuristic['total']):\n\t\t\t\tbest = current_heuristic\n\t\t\t\tbest_board = copy(self.__board)\n\n\t\t\t#Restart by reinitialize the board\n\t\t\tself.__board = Board(self.__request)\n\n\t\t\t#Calculate current heuristic\n\t\t\tcurrent_heuristic = self.__board.calculate_heuristic()\n\n\t\t\t#Increment the attempts\n\t\t\tattempts+=1\n\t\t\tsleep(0.03)\n\t\t\tos.system('clear')\n\n\t\t#Maximum attempts reached\n\t\tfinish = round(time(), 3)\n\n\t\tos.system('clear')\n\n\t\tprint(\"S.A Algorithm approximates global optimum (with \", attempts, \" attempts)\")\n\t\tprint(\"Elapsed time = \" + str(finish - start) + \" seconds\\n\")\n\t\tbest_board.draw()\n\t\tprint(\" \", best['a'] , \" \", best['b'])\n\n\t\treturn\n","sub_path":"algorithm/SimulatedAnnealing.py","file_name":"SimulatedAnnealing.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347806520","text":"'''\n prerequisites:\n 0. create a twitter account\n 1. obtain your access tokens: https://apps.twitter.com/\n 1.0 create new app\n 2. install tweepy (pip install tweepy)\n\n credit:\n http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html\n http://adilmoujahid.com/posts/2014/07/twitter-analytics/\n https://pythonprogramming.net/twitter-api-streaming-tweets-python-tutorial/\n\n Tweet JSON:, use http://jsonviewer.stack.hu/ to view object\n https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json\n\n rate limiting:\n https://developer.twitter.com/en/docs/basics/rate-limiting\n\n streaming rate limiting:\n https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting.html\n'''\n\n#Import the necessary methods from tweepy library\nfrom tweepy.streaming import StreamListener\nfrom tweepy import OAuthHandler\nfrom tweepy import Stream\nimport json\nimport time\nimport requests\n\n#get keys from: https://apps.twitter.com/\n#consumer key, consumer secret, access token, access secret.\nckey = '9D2w3iTfxI4bTzFeOc614d86l'\ncsecret = 'DCOGCqDrahobYeB9oOHD0VYuOL5PH8PnWTXEkbGL9OhZpuc5lQ'\natoken = '955940903658631168-kL0fVS7uk6bn1KCBkbQ3oIZn9v23OGS'\nasecret = 'XbYHSyrVZSLEatrk3IVs23ScEWi2vPu2825g44aOJHARf'\n#\nURIs={}\nclass listener(StreamListener):\n\n def on_data(self, data):\n #learn about tweet json structure: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json\n try:\n tweetJson = json.loads(data)\n\n #tweet = tweetJson['text']\n username = tweetJson['user']['screen_name']\n links = tweetJson['entities']['urls']\n except:\n return True\n if( len(links) != 0 and tweetJson['truncated'] == False ):\n links = self.getLinksFromTweet(links)\n\n print( username )\n for l in links:\n try:\n r = requests.head(l, allow_redirects=True, timeout=10)\n if( r.status_code > 199 and r.status_code < 300):\n print(r.history)\n print('\\t', r.url)\n if 'https://twitter' not in r.url:\n URIs[r.url] = r.history\n except:\n return True\n print ()\n print(len(URIs))\n print()\n if len(URIs) > 1000:\n f = open('test','a')\n for key, value in URIs.items():\n f.write(key + '\\n')\n print(key)\n return False\n #time.sleep(5)\n\n return True\n def getLinksFromTweet(self, linksDict):\n links = []\n for uri in linksDict:\n links.append( uri['expanded_url'] )\n\n return links\n\n def on_error(self, status):\n print( status )\n\n if status == 420:\n #returning False in on_data disconnects the stream\n return False\n return True\n\n\nauth = OAuthHandler(ckey, csecret)\nauth.set_access_token(atoken, asecret)\nwhile( len(URIs) < 1000):\n try:\n twitterStream = Stream(auth, listener())\n twitterStream.filter(track=['olympics'])\n except:\n pass\n","sub_path":"A2/twt.py","file_name":"twt.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"51091411","text":"from codebase.core import *\nfrom codebase.util import *\nimport pandas as pd\n\nproject_name = 'Ecoli'\nGSM_name = \"/ijo1366.xml\"\nlpfile_name = \"mingenome_Ecoli.lp\"\n\ndata_dir = \"./data/\" + project_name\nGSM_dir = \"./data/\" + project_name + GSM_name\nsequence_dir = \"./data/\" + project_name + \"/NC_000913.3\"\noffrxn_f = None\n\n### setup input #####\n# util = utility(sequence_dir)\n# util.getAllGenesfromGB()\n# util.get_promoter_end_loc()\n# util.move_start_site_to_back(data_dir)\n# util.exchange_promoter_key_value(data_dir)\n# util.map_genes_between_models(data_dir)\n\n# ### run MinGenome algorithm #####\nmg = MinGenome(GSM_dir)\nmodel = mg.modelCobra(data_dir,offrxn_f)\n\neg_f = \"./data/\" + project_name + \"/essentialGene.txt\"\n# eg_f = \"./data/\" + project_name + \"/essentialGenes_Daniel.txt\"\nparameters_f = \"./data/\" + project_name + \"/genes_and_promoters.xlsx\"\nabundance_f = \"./data/\" + project_name + \"/cumulative_abundance.tab\"\n# reg_f = \"./data/\" + project_name + \"/regulatorGene.txt\"\nreg_f = None\nTU_Json_file=\"./data/\" + project_name + \"/gene_promoter_dict.json\"\nlpfilename=\"./out/\" + lpfile_name\n\nmg.build_abundance_MIP_by_Cobrapy(model, 0.98,\n\t\t eg_f,parameters_f,abundance_f, reg_f,TU_Json_file,lpfilename)\n\n","sub_path":"src/maxabundance_ecoli.py","file_name":"maxabundance_ecoli.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"290807584","text":"\n\nimport logging\nimport json\n\n\n\nfrom lib._flask.flask import (\n Flask, render_template, url_for, \n jsonify, Response, request\n)\n\n\n\n#from src.scorer import Scorer\n#from src.classes import Task\n#from src.generator import TimeSlotGenerator\n\nfrom src.scheduler import Scheduler\n\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef hello_world():\n return render_template('hello.html')\n\n\n\n@app.route('/get_schedule/')\ndef get_schedule(hours=4):\n \n \n \n hours = int(hours)\n scheduler = Scheduler(int(hours))\n \n \n\n return json.dumps(scheduler.schedule)\n \n\n\n\n\n\nif __name__ == '__main__':\n app.run()\n\n","sub_path":"web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601446733","text":"# loading packages\nimport time\n\ndef time_function(f, *args):\n\t\"\"\"\n\tCall a function f with args and return the time (in ms) that \n\tit took to execute.\n\t\"\"\"\n\ttic = time.time()\n\tf(*args)\n\ttoc = time.time()\n\n\treturn (toc - tic) * 1000","sub_path":"Sorting/utilities/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"568034667","text":"import math\nfrom scipy.io import wavfile\nimport matplotlib.pyplot as plt\n\ne = math.e\npi = math.pi\n\nAUDIO_FILE = \"./violin.wav\"\n\nclass SpectrumAnalyzer:\n\n def __init__(self):\n self.SAMPLE_RATE = 44100\n plt.style.use('dark_background')\n\n def exp(self, x : float) -> \"Eulers Formula\":\n return math.cos(x) + complex(math.sin(x))\n\n def magnitude(self, real : float, imaginary : complex) -> \"Magnitude of a Vector\":\n return math.sqrt(real ** 2 + imaginary.real ** 2)\n\n def DFT(self, samples : list) -> \"Discrete Fourier Transform\":\n N = len(samples)\n freqBins = []\n\n for i in range(0, int(N/2)):\n Σ = 0\n\n for n in range(0, N):\n Σ += samples[n] * self.exp(-(2 * pi * i * n) / N)\n \n freqBins.append(2 * self.magnitude(Σ.real, Σ.imag) / N)\n\n return freqBins\n\n def graphResults(self):\n samples = self.loadAudioData()\n freqDomain = self.DFT(samples)\n \n fig, ax = plt.subplots(2, sharex=True)\n\n fig.suptitle('Discrete Fourier Transform')\n\n ax[0].plot(samples)\n ax[1].plot(freqDomain)\n\n ax[0].grid(color='#5a5a5a')\n ax[1].grid(color='#5a5a5a')\n\n plt.show()\n\n plt.plot(freqDomain)\n plt.show()\n\n return self.getStrongestFrequency(freqDomain, samples)\n\n def getStrongestFrequency(self, frequency_domain, samples):\n return frequency_domain.index(max(frequency_domain)) / len(samples) * (self.SAMPLE_RATE / 2) \n\n def loadAudioData(self):\n self.SAMPLE_RATE, samples = wavfile.read(AUDIO_FILE)\n samples = samples[100000: 101000] # Get first 500 data points\n\n channel_1 = [channel[0] for channel in samples]\n channel_2 = [channel[1] for channel in samples]\n\n return channel_1\n\nif __name__ == '__main__':\n dft = SpectrumAnalyzer()\n max_freq = dft.graphResults()\n\n print(\"-\" * 50)\n print(f\"Max frequency: {str(max_freq)} Hz\")\n print(\"-\" * 50)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109264096","text":"file_txt = open(\"file.txt\", \"r\")\n\nlines = file_txt.readlines()\nfile_txt.close()\n\ncounter = len(lines)\n\nfor line in lines:\n\tline = line.replace(\"\\n\", \"\").split(\" \")\n\tfor item in line:\n\t\tif line.count(item) > 1:\n\t\t\tcounter -= 1\n\t\t\tbreak\n\nprint(\"\\nValid skyphrases: \", counter)\n\n\n\n\n\n\n\n#\n# file_txt = open('file.txt', \"r\")\n#\n# lines = file_txt.readlines()\n# file_txt.close()\n#\n#\n# counter = len(lines)\n# which_line = 0\n# for line in lines:\n# \twhich_line += 1\n# \tline = line.replace(\"\\n\", \"\").split(\" \")\n# \t# print(line)\n# \tfor item in line:\n# \t\tif line.count(item)>1:\n# \t\t\tprint (which_line, item )\n# \t\t\t# print(line.count(item))\n# \t\t\tcounter -= 1\n# \t\t\tbreak\n#\n#\n#\n#\n# print('Valid skyphrases: ',counter)","sub_path":"Chapter2_task1.py","file_name":"Chapter2_task1.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"561347527","text":"# https://leetcode.com/problems/search-in-rotated-sorted-array/description/\n\n\nclass Solution:\n def search(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n\n size = len(nums)\n if size == 0: return -1\n\n l, r = 0, size-1\n while l <= r:\n m = (l + r) // 2\n if target == nums[m]: return m\n\n if nums[m] > nums[r]:\n if nums[l] <= target < nums[m]:\n r = m - 1\n else: l = m + 1\n else:\n if nums[m] < target <= nums[r]:\n l = m + 1\n else: r = m - 1\n\n return -1\n","sub_path":"_PYTHON_/_problems_/_LC_/algorithms/search_in_rotated_sorted_array.py","file_name":"search_in_rotated_sorted_array.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286910046","text":"# Andrew Ingrassia\r\n# HackerRank\r\n# Find a String\r\n\r\n\r\n\"\"\"\r\nTASK:\r\n In this challenge, the user enters a string and a substring. You have to print the number of times that the\r\n substring occurs in the given string. String traversal will take place from left to right, not from right to left.\r\n\r\nNOTE:\r\n String letters are case-sensitive.\r\n\r\nINPUT FORMAT:\r\n a. The first line of input contains the original string.\r\n b. The next line contains the substring.\r\n\r\nCONSTRAINTS:\r\n a. 1 <= len(string) <= 200\r\n b. Each character in the string is an ascii character.\r\n\r\nOUTPUT FORMAT:\r\n Output the integer number indicating the total number of occurrences of the substring in the original string.\r\n\r\nSAMPLE INPUT:\r\n ABCDCDC\r\n CDC\r\n\r\nSAMPLE OUTPUT:\r\n 2\r\n\"\"\"\r\n\r\n\r\ndef count_substring(s, sub_s):\r\n num_occurrences = 0 # initialize sub_s occurrence count to 0\r\n for i in range(len(s)): # for every element in range(0, len(s))...\r\n if s[i:].startswith(sub_s): # traverses string from left to right, looking for occurrences of 'sub_s'\r\n num_occurrences += 1 # each time an occurrence is located, 'num_occurrences' increases by 1\r\n return num_occurrences # returns the final 'num_occurrences' count\r\n\r\n\r\nif __name__ == '__main__':\r\n string = input().strip() # strips 'string' into a list of characters\r\n sub_string = input().strip() # strips 'sub_string' into a list of characters\r\n count = count_substring(string, sub_string) # runs the 'count_substring' function\r\n print(count) # prints the result\r\n","sub_path":"find_a_string.py","file_name":"find_a_string.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130929972","text":"\n\ndef getWin(price, risk, weScore, theyScore):\n award = (price.price - 1) * risk\n if price.team_id is None:\n if weScore.score == theyScore.score:\n return award\n else:\n return -risk\n elif price.team_id == weScore.team_id:\n scoreDiff = weScore.score - theyScore.score\n elif price.team_id == theyScore.team_id:\n scoreDiff = theyScore.score - weScore.score\n else:\n self.app.log.error('No score found for price. priceId=%s, priceTeamId=%s, weScoreTeamId=%s, theyScoreTeamId=%s' %\n (price.price_id, price.team_id, weScore.team_id, theyScore.team_id))\n return\n handicap = float(price.handicap)\n if handicap == 0:\n return award if scoreDiff > 0 else -risk\n elif handicap % 1 == 0:\n if scoreDiff + handicap == 0:\n return 0\n elif scoreDiff + handicap > 0:\n return award\n else:\n return -risk\n elif handicap % 0.5 == 0:\n return award if scoreDiff + handicap > 0 else -risk\n elif handicap % 0.25 == 0:\n return 0\n #complicated\n pass\n","sub_path":"mind/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349362654","text":"from random import random, randint\r\nimport math\r\n\r\ndef paso(pos,dim):\r\n d=randint(0,dim-1)\r\n if (random()<0.5):\r\n pos[d] += -1\r\n else:\r\n pos[d] += 1\r\n return pos\r\n\r\n\r\ndef experimento(largo, dim, dimTotal, vectorPasos):\r\n pos = [0] * dim\r\n conteo=0\r\n for t in range(largo):\r\n pos=paso(pos,dim)\r\n conteo+=1\r\n if all([p==0 for p in pos]):\r\n vectorPasos[dimTotal]=conteo\r\n return True\r\n\r\n vectorPasos[dimTotal] = 0\r\n return False\r\n\r\ndim=[]\r\nlargo=[]\r\n\r\ntotal=50\r\nfor i in range(1, 9):\r\n regresos = 0\r\n contador=0\r\n contadorPasos = []\r\n for replica in range(total) :\r\n for larg in range(1,6):\r\n largo.append(larg)\r\n dim.append(i)\r\n contador+=1\r\n contadorPasos.append(contador)\r\n regresos += experimento(pow(2, largo[larg-1]+4), dim[i-1], contador-1, contadorPasos)\r\n print('Probabilidad de regresos: ', regresos / contador, dim[i - 1])\r\n print('Regresos: ', regresos)\r\n print('Dimension: ', i)\r\n print('Vector pasos ', contadorPasos)\r\n print('Minimo: ', min(contadorPasos))\r\n print('Maximo: ', max(contadorPasos))\r\n print('Promedio ', sum( contadorPasos)/len(contadorPasos))\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"browniano.py","file_name":"browniano.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"526277633","text":"# Global Benchmark Database (GBD)\n# Copyright (C) 2020 Markus Iser, Karlsruhe Institute of Technology (KIT)\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport sys\nimport bz2\nimport gzip\nimport lzma\nimport io\n\n__all__ = ['eprint', 'read_hashes', 'confirm', 'open_cnf_file', 'is_number']\n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef open_cnf_file(filename, mode):\n \"\"\"\n Opens a CNF file (this is badly guarded, by file-extension only)\n \"\"\"\n obj = None\n if filename.endswith('.cnf.gz'):\n obj = gzip.open(filename, mode)\n elif filename.endswith('.cnf.bz2'):\n obj = bz2.open(filename, mode)\n elif filename.endswith('.cnf.lzma') or filename.endswith('.cnf.xz'):\n obj = lzma.open(filename, mode)\n elif filename.endswith('.cnf'):\n obj = open(filename, mode)\n else:\n raise Exception(\"Unknown File Extension. Use .cnf, .cnf.bz2, .cnf.lzma, .cnf.xz, or .cnf.gz\")\n \n if 'b' in mode:\n return io.BufferedReader(obj, io.DEFAULT_BUFFER_SIZE * 8)\n else:\n return obj\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef read_hashes():\n eprint(\"Reading hashes from stdin ...\")\n hashes = list()\n try:\n while True:\n line = sys.stdin.readline().split()\n if len(line) == 0:\n return hashes\n hashes.extend(line)\n except KeyboardInterrupt:\n return hashes\n return hashes\n\n\ndef confirm(prompt='Confirm', resp=False):\n \"\"\"\n prompts for yes or no response from the user. Returns True for yes and False for no.\n 'resp' should be set to the default value assumed by the caller when user simply types ENTER.\n \"\"\"\n if resp:\n prompt = '%s [%s]|%s: ' % (prompt, 'y', 'n')\n else:\n prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')\n\n while True:\n ans = input(prompt)\n if not ans:\n return resp\n if ans not in ['y', 'Y', 'n', 'N']:\n print('please enter y or n.')\n continue\n if ans == 'y' or ans == 'Y':\n return True\n if ans == 'n' or ans == 'N':\n return False\n","sub_path":"gbd_tool/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"427946302","text":"import os\nimport logging\n\nimport dialogflow\nfrom google.api_core.exceptions import InvalidArgument\n\nfrom telegram import Bot\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nMONITORING_CHAT_ID = os.getenv('MONITORING_CHAT_ID')\nMONITORING_TOKEN = os.getenv('MONITORING_TOKEN')\nMONITORING_BOT = Bot(token=MONITORING_TOKEN)\n\n\nclass LoggerForTelegram(logging.Handler):\n\n def emit(self, record):\n log_entry = self.format(record)\n MONITORING_BOT.send_message(chat_id=MONITORING_CHAT_ID, text=log_entry)\n\n\nlogger = logging.getLogger(\"logger for telegram\")\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(LoggerForTelegram())\n\nDIALOGFLOW_PROJECT_ID = os.getenv('PROJECT_ID')\nDIALOGFLOW_LANGUAGE_CODE = 'ru-RU'\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = os.getenv('GA-KEY-CLIENT')\n\n\ndef start(bot, update):\n \"\"\"Send a message when the command /start is issued.\"\"\"\n update.message.reply_text('Здравствуйте!')\n\n\ndef answer(bot, update):\n telegram_id = update.update_id\n dialogflow_client = dialogflow.SessionsClient()\n dialogflow__session = dialogflow_client.session_path(DIALOGFLOW_PROJECT_ID, telegram_id)\n\n text_to_be_analyzed = update.message.text\n text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)\n\n query_input = dialogflow.types.QueryInput(text=text_input)\n\n try:\n response = dialogflow_client.detect_intent(session=dialogflow__session, query_input=query_input)\n except InvalidArgument as err:\n logger.critical(err)\n raise\n\n update.message.reply_text(response.query_result.fulfillment_text)\n\n\ndef error(bot, update, error):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n\ndef main():\n \"\"\"Start the bot.\"\"\"\n\n logger.info('bot started')\n\n TOKEN = os.getenv(\"TELEGRAM_TOKEN\")\n updater = Updater(TOKEN)\n\n dp = updater.dispatcher\n dp.add_handler(CommandHandler(\"start\", start))\n dp.add_handler(MessageHandler(Filters.text, answer))\n\n # log all errors\n dp.add_error_handler(error)\n\n # Start the Bot\n updater.start_polling()\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n updater.idle()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"telegram_support_bot.py","file_name":"telegram_support_bot.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546356060","text":"# logger/urls.py\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('daily/', views.dailyUpdate, name='daily'),\n path('weekly/', views.weeklyUpdate, name='weekly'),\n path('success/', views.successView, name='success'),\n]","sub_path":"logger/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138723416","text":"'''\nCreated on 7 Feb 2015\n\n@author: campbell\n'''\nimport media\nimport fresh_tomatoes \n\n# data - creating instances of class Movie from media.py\ntoy_story3 = media.Movie(\"Toy Story 3\",\n \"2010\",\n \"The toys are mistakenly delivered to a day-care center instead of the attic right before Andy leaves for college, and it's up to Woody to convince the other toys that they weren't abandoned and to return home.\",\n \"Lee Unkrich\",\n \"John Lasseter (story), Andrew Stanton (story)\",\n \"Tom Hanks, Tim Allen, Joan Cusack\",\n \"https://upload.wikimedia.org/wikipedia/en/thumb/6/69/Toy_Story_3_poster.jpg/220px-Toy_Story_3_poster.jpg\",\n \"https://www.youtube.com/watch?v=JcpWXaA2qeg\")\nplatoon = media.Movie(\"Platoon\",\n \"1986\",\n \"A young recruit in Vietnam faces a moral crisis when confronted with the horrors of war and the duality of man.\",\n \"Oliver Stone\",\n \"Oliver Stone\",\n \"Charlie Sheen, Tom Berenger, Willem Dafoe\",\n \"https://upload.wikimedia.org/wikipedia/en/a/a9/Platoon_posters_86.jpg\",\n \"https://www.youtube.com/watch?v=AykiF9YYF2U\")\nthe_deer_hunter = media.Movie(\"The Deer Hunter\",\n \"1978\",\n \"An in-depth examination of the ways in which the U.S. Vietnam war impacts and disrupts the lives of people in a small industrial town in Pennsylvania.\",\n \"Michael Cimino\",\n \"Michael Cimino (story), Deric Washburn (story)\",\n \"Robert De Niro, Christopher Walken, John Cazale\",\n \"https://upload.wikimedia.org/wikipedia/en/5/57/The_Deer_Hunter_poster.jpg\",\n \"https://www.youtube.com/watch?v=3Gqit3zVmyc\")\napocalypse_now = media.Movie(\"Apocalypse Now\",\n \"1979\",\n \"During the Vietnam War, Captain Willard is sent on a dangerous mission into Cambodia to assassinate a renegade colonel who has set himself up as a god among a local tribe.\",\n \"Francis Ford Coppola (as Francis Coppola)\",\n \"John Milius, Francis Ford Coppola\",\n \"Martin Sheen, Marlon Brando, Robert Duvall\",\n \"https://upload.wikimedia.org/wikipedia/en/c/c2/Apocalypse_Now_poster.jpg\",\n \"https://www.youtube.com/watch?v=snDR7XsSkB4\")\nfull_metal_jacket = media.Movie(\"Full Metal Jacket\",\n \"1987\",\n \"A pragmatic U.S. Marine observes the dehumanizing effects the U.S.-Vietnam War has on his fellow recruits from their brutal boot camp training to the bloody street fighting in Hue.\",\n \"Stanley Kubrick\",\n \"Gustav Hasford (novel), Stanley Kubrick (screenplay)\",\n \"Matthew Modine, R. Lee Ermey, Vincent D'Onofrio\",\n \"https://upload.wikimedia.org/wikipedia/en/9/99/Full_Metal_Jacket_poster.jpg\",\n \"https://www.youtube.com/watch?v=UuWmCVdwhKg\")\na2001_a_space_odyssey = media.Movie(\"2001: A Space Odyssey\",\n \"1968\",\n \"Humanity finds a mysterious, obviously artificial, object buried beneath the Lunar surface and, with the intelligent computer H.A.L. 9000, sets off on a quest.\",\n \"Stanley Kubrick\",\n \"Stanley Kubrick (screenplay), Arthur C. Clarke (screenplay)\",\n \"Keir Dullea, Gary Lockwood, William Sylvester\",\n \"https://upload.wikimedia.org/wikipedia/en/e/ef/2001_A_Space_Odyssey_Style_B.jpg\",\n \"https://www.youtube.com/watch?v=N6ywMnbef6Y\")\nforrest_gump = media.Movie(\"Forrest Gump\",\n \"1994\",\n \"Forrest Gump, while not intelligent, has accidentally been present at many historic moments, but his true love, Jenny Curran, eludes him.\",\n \"Robert Zemeckis\",\n \"Winston Groom (novel), Eric Roth (screenplay)\",\n \"Tom Hanks, Robin Wright, Gary Sinise\",\n \"http://content7.flixster.com/movie/11/17/36/11173677_det.jpg\",\n \"https://www.youtube.com/watch?v=bLvqoHBptjg\")\navatar = media.Movie(\"Avatar\",\n \"2009\",\n \"A Paraplegic Marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home..\",\n \"James Cameron\",\n \"James Cameron\",\n \"Sam Worthington, Zoe Saldana, Sigourney Weaver\",\n \"https://upload.wikimedia.org/wikipedia/en/b/b0/Avatar-Teaser-Poster.jpg\",\n \"https://www.youtube.com/watch?v=_Tkc5pQp_JE\")\ngoodfellas = media.Movie(\"Goodfellas\",\n \"1990\",\n \"Henry Hill and his friends work their way up through the mob hierarchy.\",\n \"Martin Scorsese\",\n \"Nicholas Pileggi (book), Nicholas Pileggi (screenplay)\",\n \"Robert De Niro, Ray Liotta, Joe Pesci\",\n \"https://upload.wikimedia.org/wikipedia/en/7/7b/Goodfellas.jpg\",\n \"https://www.youtube.com/watch?v=YH-7he92XfI\")\n\n# load data in list for idplaying in module fresh_tomatoes\nmovies = [toy_story3, forrest_gump, avatar, goodfellas, a2001_a_space_odyssey, full_metal_jacket, apocalypse_now, the_deer_hunter, platoon]\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_centre.py","file_name":"entertainment_centre.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"231556103","text":"# -*- coding: utf-8 -*-\n\nfrom Acquisition import aq_base\nfrom Acquisition import aq_parent\n\nfrom OFS.SimpleItem import SimpleItem\n\nfrom zope.component import adapts\n\nfrom zope.interface import Interface\nfrom zope.interface import implements\n\nfrom zope.formlib import form\n\nfrom Products.CMFCore.utils import getToolByName\n\nfrom Products.CMFPlone.utils import _createObjectByType\n\nfrom Products.CMFPlacefulWorkflow.PlacefulWorkflowTool import \\\n WorkflowPolicyConfig_id\n\nfrom plone.app.contentrules.browser.formhelper import AddForm\nfrom plone.app.contentrules.browser.formhelper import EditForm\n\nfrom plone.app.form.widgets.uberselectionwidget import UberSelectionWidget\n\nfrom plone.contentrules.rule.interfaces import IRuleElementData\nfrom plone.contentrules.rule.interfaces import IExecutable\n\nfrom plone.app.contentrules.actions.move import MoveActionExecutor\n\nfrom DateTime import DateTime\n\nfrom sc.contentrules.groupbydate.interfaces import IGroupByDateAction, ViewFail\n\nfrom sc.contentrules.groupbydate.config import STRUCTURES\n\nfrom sc.contentrules.groupbydate.config import DEFAULTPOLICY\n\nfrom sc.contentrules.groupbydate import MessageFactory as _\n\n\nclass GroupByDateAction(SimpleItem):\n \"\"\"\n \"\"\"\n implements(IGroupByDateAction, IRuleElementData)\n\n base_folder = ''\n structure = '%Y/%m/%d'\n container = ('folder', 'Folder')\n default_view = 'folder_listing'\n\n element = 'sc.contentrules.actions.groupbydate'\n\n @property\n def summary(self):\n return _(u\"Move the item under ${base_folder} using ${structure}\"\n u\" structure\",\n mapping=dict(base_folder=self.base_folder,\n structure=self.structure))\n\n\nclass GroupByDateActionExecutor(MoveActionExecutor):\n \"\"\"The executor for this action.\n \"\"\"\n implements(IExecutable)\n adapts(Interface, IGroupByDateAction, Interface)\n\n def __init__(self, context, element, event):\n self.context = context\n self.element = element\n self.event = event\n self.wt = getToolByName(context, 'portal_workflow')\n\n def __call__(self):\n ''' Executes action, moving content to a date based folder structure\n '''\n context = self.context\n self._pstate = context.unrestrictedTraverse('@@plone_portal_state')\n self._portal = self._pstate.portal()\n self._portalPath = list(self._portal.getPhysicalPath())\n\n # Get event object\n obj = self.event.object\n\n # This should get us a DateTime or a datetime (dexterity)\n objDate = obj.effective_date\n\n base_folder = self.element.base_folder\n structure = self.element.structure\n\n folder = self._base_folder(str(base_folder), obj)\n\n if folder is None:\n self.error(obj, _(u\"Base folder ${target} does not exist.\",\n mapping={'target': base_folder}))\n return False\n\n destFolder = self._createFolderStructure(folder,\n structure, date=objDate)\n destFolderRelPath = self._relPathToPortal(destFolder)\n\n self.element.target_folder = '/'.join(destFolderRelPath)\n\n # Move object\n result = super(GroupByDateActionExecutor, self).__call__()\n self.element.target_folder = None\n return result\n\n def _relPathToPortal(self, obj):\n ''' Given an object we return it's relative path to portal\n '''\n portalPath = self._portalPath\n return list(obj.getPhysicalPath())[len(portalPath):]\n\n def _base_folder(self, base_folder, obj):\n ''' Given a base_folder string and the object triggering the event, we\n return the base object to be used by this action.\n '''\n # Large portions of this code came from Products.ATContentTypes\n # TODO: a package to deal with this kind of stuff (string to object?)\n # sanitize a bit: you never know, with all those win users out there\n relPath = base_folder.replace(\"\\\\\", \"/\")\n\n if relPath[0] == '/':\n # someone didn't enter a relative path.\n # let's go with it\n path = relPath.split('/')[1:]\n else:\n folders = relPath.split('/')\n\n # set the path to the object path\n path = self._relPathToPortal(aq_parent(obj))\n\n # now construct an aboslute path based on the relative custom path\n # eat away from 'path' whenever we encounter a '..'\n # in the relative path apend all other elements other than ..\n for folder in folders:\n if folder == '..':\n # chop off one level from path\n if path == []:\n # can't chop off more\n # just return this path and leave the loop\n break\n else:\n path = path[:-1]\n elif folder == '.':\n # don't really need this but for being complete\n # strictly speaking some user may use a . aswell\n pass # do nothing\n else:\n path.append(folder)\n\n if not (path == []):\n # As we will traverse from portal, there is no need to\n # have its path in the way\n path = '/'.join(path)\n try:\n baseFolder = self._portal.unrestrictedTraverse(path)\n except AttributeError:\n baseFolder = None\n except KeyError:\n baseFolder = None\n else:\n baseFolder = self._portal\n return baseFolder\n\n def _createFolderStructure(self, folder, structure='ymd', date=None):\n ''' Create a folder structure and then return our innermost folder\n '''\n if not date:\n date = DateTime()\n\n # BBB:to avoid breaking old rules\n if structure in [k for k, v in STRUCTURES]:\n if structure == 'ymd':\n dateFormat = '%Y/%m/%d'\n elif structure == 'ym':\n dateFormat = '%Y/%m'\n elif structure == 'y':\n dateFormat = '%Y'\n else:\n # Create a list stating if the folder should be hiddden from \n # navigation\n should_exclude = ['ee' in i for i in structure.split('/')]\n # Now remove all the 'h' that may be in the structure\n dateFormat = structure.replace('ee','')\n\n date = date.strftime(dateFormat)\n\n folderStructure = [str(p) for p in date.split('/')]\n\n container = self.element.container\n default_view = self.element.default_view\n for (fId, exclude) in zip(folderStructure, should_exclude):\n if not fId in folder.objectIds():\n _createObjectByType(container, folder, id=fId,\n title=fId, description=fId)\n folder = folder[fId]\n folder.setLayout(default_view)\n self._addWorkflowPolicy(folder)\n if exclude:\n folder.setExcludeFromNav(True)\n else:\n folder = folder[fId]\n return folder\n\n def _addWorkflowPolicy(self, folder, policy=DEFAULTPOLICY):\n ''' After creating a new folder, add a workflow policy in it\n and update its security settings\n '''\n wt = self.wt\n cmf_placeful = folder.manage_addProduct['CMFPlacefulWorkflow']\n cmf_placeful.manage_addWorkflowPolicyConfig()\n # Set the policy for the config\n pc = getattr(folder, WorkflowPolicyConfig_id)\n pc.setPolicyIn(policy)\n wfs = wt.getChainFor(folder)\n for wf_id in wfs:\n wf = wt.getWorkflowById(wf_id)\n change = wf.updateRoleMappingsFor(folder)\n if change and hasattr(aq_base(folder), 'reindexObject'):\n folder.reindexObject(idxs=['allowedRolesAndUsers'])\n\n\nclass GroupByDateAddForm(AddForm):\n \"\"\"\n An add form for the group by date action\n \"\"\"\n form_fields = form.FormFields(IGroupByDateAction)\n label = _(u\"Add group by date folder action\")\n description = _(u\"A content rules action to move an item to a folder\"\n u\" structure.\")\n form_name = _(u\"Configure element\")\n\n def update(self):\n self.setUpWidgets()\n self.form_reset = False\n\n data = {}\n errors, action = self.handleSubmit(self.actions, data, self.validate)\n # the following part will make sure that previous error not\n # get overriden by new errors. This is usefull for subforms. (ri)\n if self.errors is None:\n self.errors = errors\n else:\n if errors is not None:\n self.errors += tuple(errors)\n\n if errors:\n if (len(errors) == 1) and (isinstance(errors[0], ViewFail)):\n # We send a message if validation of view is false and\n # is the only error.\n self.status = _('The view is not available in that container')\n result = action.failure(data, errors)\n else:\n self.status = _('There were errors')\n result = action.failure(data, errors)\n elif errors is not None:\n self.form_reset = True\n result = action.success(data)\n else:\n result = None\n\n self.form_result = result\n\n def create(self, data):\n a = GroupByDateAction()\n form.applyChanges(a, self.form_fields, data)\n return a\n\n def handleSubmit(self, actions, data, default_validate=None):\n\n for action in actions:\n if action.submitted():\n errors = action.validate(data)\n if errors is None and default_validate is not None:\n errors = default_validate(action, data)\n return errors, action\n\n return None, None\n\n\nclass GroupByDateEditForm(EditForm):\n \"\"\"\n An edit form for the group by date action\n \"\"\"\n form_fields = form.FormFields(IGroupByDateAction)\n form_fields['base_folder'].custom_widget = UberSelectionWidget\n label = _(u\"Edit group by date action\")\n description = _(u\"A content rules action to move an item to a folder\"\n u\" structure.\")\n form_name = _(u\"Configure element\")\n\n def update(self):\n self.setUpWidgets()\n self.form_reset = False\n\n data = {}\n errors, action = self.handleSubmit(self.actions, data, self.validate)\n # the following part will make sure that previous error not\n # get overriden by new errors. This is usefull for subforms. (ri)\n if self.errors is None:\n self.errors = errors\n else:\n if errors is not None:\n self.errors += tuple(errors)\n\n if errors:\n if (len(errors) == 1) and (isinstance(errors[0], ViewFail)):\n # We send a message if validation of view is false and\n # is the only error.\n self.status = _(u'The view is not available in that container')\n result = action.failure(data, errors)\n else:\n self.status = _(u'There were errors')\n result = action.failure(data, errors)\n elif errors is not None:\n self.form_reset = True\n result = action.success(data)\n else:\n result = None\n\n self.form_result = result\n\n def handleSubmit(self, actions, data, default_validate=None):\n\n for action in actions:\n if action.submitted():\n errors = action.validate(data)\n if errors is None and default_validate is not None:\n errors = default_validate(action, data)\n return errors, action\n\n return None, None\n","sub_path":"sc/contentrules/groupbydate/actions/groupbydate.py","file_name":"groupbydate.py","file_ext":"py","file_size_in_byte":11912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387426756","text":"# (C) Datadog, Inc. 2010-2016\n# All rights reserved\n# Licensed under Simplified BSD License (see LICENSE)\n\nimport os\nimport pytest\nfrom datadog_checks.stubs import aggregator\nfrom datadog_checks.dotnetclr import DotnetclrCheck\nfrom datadog_checks.dotnetclr.dotnetclr import DEFAULT_COUNTERS\n\n# for reasons unknown, flake8 says that pdh_mocks_fixture is unused, even though\n# it's used below. noqa to suppress that error.\nfrom datadog_test_libs.win.pdh_mocks import pdh_mocks_fixture, initialize_pdh_tests # noqa: F401\n\nHERE = os.path.abspath(os.path.dirname(__file__))\nMINIMAL_INSTANCE = {\n 'host': '.',\n}\n\nINSTANCE_WITH_TAGS = {\n 'host': '.',\n 'tags': ['tag1', 'another:tag']\n}\n\n\n@pytest.fixture\ndef Aggregator():\n aggregator.reset()\n return aggregator\n\n\nCHECK_NAME = 'active_directory'\n\nINSTANCES = [\n '_Global_',\n 'Microsoft.Exchange.Search.Service',\n 'UMWorkerProcess',\n 'umservice',\n 'w3wp',\n 'Microsoft.Exchange.Store.Worker',\n 'Microsoft.Exchange.EdgeSyncSvc',\n 'MSExchangeDelivery',\n 'MSExchangeFrontendTransport',\n 'Microsoft.Exchange.Store.Service',\n 'EdgeTransport',\n 'MSExchangeTransport',\n 'Microsoft.Exchange.UM.CallRouter',\n 'MSExchangeTransportLogSearch',\n 'MSExchangeThrottling',\n 'MSExchangeHMWorker',\n 'MSExchangeSubmission',\n 'Microsoft.Exchange.ServiceHost',\n 'Microsoft.Exchange.RpcClientAccess.Service',\n 'noderunner',\n 'msexchangerepl',\n 'MSExchangeMailboxReplication',\n 'MSExchangeMailboxAssistants',\n 'ForefrontActiveDirectoryConnector',\n 'Microsoft.Exchange.AntispamUpdateSvc',\n 'Ec2Config',\n 'Microsoft.Exchange.Directory.TopologyService',\n 'WMSvc',\n 'MSExchangeHMHost',\n 'Microsoft.Exchange.Diagnostics.Service',\n 'hostcontrollerservice',\n 'Microsoft.ActiveDirectory.WebServices',\n]\n\n\n# flake8 then says this is a redefinition of unused, which it's not.\n@pytest.mark.usefixtures(\"pdh_mocks_fixture\") # noqa: F811\ndef test_basic_check(Aggregator, pdh_mocks_fixture):\n initialize_pdh_tests()\n instance = MINIMAL_INSTANCE\n c = DotnetclrCheck(CHECK_NAME, {}, {}, [instance])\n c.check(instance)\n\n for metric_def in DEFAULT_COUNTERS:\n metric = metric_def[3]\n for inst in INSTANCES:\n Aggregator.assert_metric(metric, tags=[\"instance:%s\" % inst], count=1)\n\n assert Aggregator.metrics_asserted_pct == 100.0\n","sub_path":"dotnetclr/tests/test_dotnetclr.py","file_name":"test_dotnetclr.py","file_ext":"py","file_size_in_byte":2384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347502038","text":"\n# Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada o programa deverá perguntar se\n# o usuário quer ou não continuar. No final mostre:\n# A) Quantas pessoas tem mais de 18 anos.\n# B) Quantos homens foram cadastrados.\n# C) Quantas mulheres tem menos de 20 anos.\n\nseparador = ('─' * 40)\ntotal18 = totalHomens = totalMulheres20 = 0\n\nwhile True:\n print(separador)\n idade = int(input('Idade: '))\n\n sexo = ' '\n while sexo not in 'MF':\n sexo = str(input('Sexo: [M/F] ')).strip().upper()[0]\n\n if idade >= 18:\n total18 += 1\n if sexo == 'M':\n totalHomens += 1\n if sexo == 'F' and idade < 20:\n totalMulheres20 += 1\n print(separador)\n resposta = ' '\n while resposta not in 'SN':\n resposta = str(input('Quer continuar? [S/N} ')).strip().upper()[0]\n if resposta == 'N':\n break\n\nprint(separador)\nprint(f'Total de pessoas com mais de 18 anos foi {total18}')\nprint(f'Ao todo temos {totalHomens} homens cadastrados')\nprint(f'E temos {totalMulheres20} mulheres com menos de 20 anos')\nprint(separador)","sub_path":"exercicios/ex069a.py","file_name":"ex069a.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474722352","text":"from util.utils import (math, Vector, backsolve, cap, defaultPD, defaultThrottle,\n shot_valid, side, sign)\n\nmax_speed = 2300\nthrottle_accel = 2/3 * 100\nbrake_accel = Vector(x=-3500)\nboost_per_second = 33 + (1/3)\njump_max_duration = 0.2\njump_speed = 291 + (2/3)\njump_acc = 1458 + (1/3)\n\n\nclass atba:\n def __init__(self, exit_distance=500, exit_flip=True):\n self.exit_distance = exit_distance\n self.exit_flip = exit_flip\n\n def run(self, agent):\n target = agent.ball.location\n car_to_target = target - agent.me.location\n distance_remaining = car_to_target.flatten().magnitude()\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to drive through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n target.x = cap(target.x, -750, 750)\n\n local_target = agent.me.local(target - agent.me.location)\n\n angles = defaultPD(agent, local_target)\n defaultThrottle(agent, 1400)\n\n agent.controller.boost = False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if distance_remaining < self.exit_distance:\n agent.pop()\n if self.exit_flip:\n agent.push(flip(local_target))\n elif abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and distance_remaining / velocity > 2.0:\n agent.push(flip(local_target))\n elif abs(angles[1]) > 2.8 and velocity < 200:\n agent.push(flip(local_target, True))\n elif agent.me.airborne:\n agent.push(recovery(target))\n\n\nclass wave_dash:\n # This is a straight-line only version of flip()\n # TODO - Refine jumping\n def __init__(self, boost=False):\n self.step = 0\n self.boost = boost\n\n def run(self, agent):\n # if agent.me.velocity.flatten().magnitude() > 100:\n # target = agent.me.velocity.flatten().normalize() * 100 + Vector(z=50)\n # else:\n # target = agent.me.forward.flatten() * 100 + Vector(z=50)\n\n # local_target = agent.me.local(target)\n # defaultPD(agent, local_target)\n\n if self.step <= 5:\n self.step += 1\n agent.controller.pitch = 1\n agent.controller.yaw = agent.controller.role = 0\n\n if self.step == 0:\n pass\n elif self.step < 3:\n agent.controller.jump = True\n elif self.step < 4:\n agent.controller.jump = False\n else:\n if (agent.me.location + (agent.me.velocity * 0.2)).z < 5:\n agent.controller.jump = True\n agent.controller.pitch = -1\n agent.controller.yaw = agent.controller.role = 0\n agent.pop()\n elif not agent.me.airborne:\n agent.pop()\n\n\nclass Aerial:\n def __init__(self, ball_intercept, intercept_time):\n self.target = ball_intercept\n self.intercept_time = intercept_time\n self.jumping = True\n self.time = -1\n self.jump_time = -1\n self.counter = 0\n\n def run(self, agent):\n if not agent.shooting:\n agent.shooting = True\n\n if self.time is -1:\n elapsed = 0\n self.time = agent.time\n agent.print(f\"Hit ball via aerial {round(agent.me.location.dist(self.target), 4)}uu's away in {round(self.intercept_time - self.time, 4)}s\")\n else:\n elapsed = agent.time - self.time\n\n T = self.intercept_time - agent.time\n xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T ** 2\n vf = agent.me.velocity + agent.gravity * T\n if self.jumping:\n if self.jump_time == -1:\n jump_elapsed = 0\n self.jump_time = agent.time\n else:\n jump_elapsed = agent.time - self.jump_time\n\n tau = jump_max_duration - jump_elapsed\n\n if jump_elapsed == 0:\n vf += agent.me.up * jump_speed\n xf += agent.me.up * jump_speed * T\n\n vf += agent.me.up * jump_acc * tau\n xf += agent.me.up * jump_acc * tau * (T - 0.5 * tau)\n\n vf += agent.me.up * jump_speed\n xf += agent.me.up * jump_speed * (T - tau)\n\n if jump_elapsed < jump_max_duration:\n agent.controller.jump = True\n elif elapsed >= jump_max_duration and self.counter < 3:\n agent.controller.jump = False\n self.counter += 1\n elif elapsed < 0.3:\n agent.controller.jump = True\n else:\n self.jumping = jump_elapsed <= 0.3 # jump_max_duration\n else:\n agent.controller.jump = False\n\n delta_x = self.target - xf\n direction = delta_x.normalize()\n\n agent.line(agent.me.location, self.target, agent.renderer.white())\n agent.line(self.target - Vector(z=100), self.target + Vector(z=100), agent.renderer.red())\n agent.line(agent.me.location, direction, agent.renderer.green())\n\n defaultPD(agent, agent.me.local(delta_x if delta_x.magnitude() > 50 else self.target))\n\n if jump_max_duration <= elapsed and elapsed < 0.3 and self.counter ** 3:\n agent.controller.roll = agent.controller.pitch = agent.controller.yaw = agent.controller.steer = 0\n\n if agent.me.forward.angle3D(direction) < 0.3:\n if delta_x.magnitude() > 50:\n agent.controller.boost = 1\n agent.controller.throttle = 0\n else:\n agent.controller.boost = 0\n agent.controller.throttle = cap(0.5 * throttle_accel * T * T, 0, 1)\n else:\n agent.controller.boost = agent.controller.throttle = 0\n\n still_valid = shot_valid(agent, self, threshold=250, target=self.target)\n\n if T <= 0 or not still_valid:\n if not still_valid:\n agent.print(\"Aerial is no longer valid\")\n\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(ball_recovery())\n\n def is_viable(self, agent):\n T = self.intercept_time - agent.time\n xf = agent.me.location + agent.me.velocity * T + 0.5 * agent.gravity * T * T\n vf = agent.me.velocity + agent.gravity * T\n\n if not agent.me.airborne:\n vf += agent.me.up * (2 * jump_speed + jump_acc * jump_max_duration)\n xf += agent.me.up * (jump_speed * (2 * T - jump_max_duration) + jump_acc * (T * jump_max_duration - 0.5 * jump_max_duration ** 2))\n\n delta_x = self.target - xf\n f = delta_x.normalize()\n phi = f.angle3D(agent.me.forward)\n turn_time = 0.7 * (2 * math.sqrt(phi / 9))\n\n tau1 = turn_time * cap(1 - 0.3 / phi, 0, 1)\n required_acc = (2 * delta_x.magnitude()) / ((T - tau1) * (T - tau1))\n ratio = required_acc / agent.boost_accel\n tau2 = T - (T - tau1) * math.sqrt(1 - cap(ratio, 0, 1))\n velocity_estimate = vf + agent.boost_accel * (tau2 - tau1) * f\n boost_estimate = (tau2 - tau1) * 30\n enough_boost = boost_estimate < 0.95 * agent.me.boost\n enough_time = abs(ratio) < 0.9\n enough_speed = velocity_estimate.normalize(True)[1] < 0.9 * max_speed\n\n return enough_speed and enough_boost and enough_time\n\n\nclass flip:\n # Flip takes a vector in local coordinates and flips/dodges in that direction\n # cancel causes the flip to cancel halfway through, which can be used to half-flip\n def __init__(self, vector, cancel=False):\n self.vector = vector.normalize()\n self.pitch = abs(self.vector.x) * -sign(self.vector.x)\n self.yaw = abs(self.vector.y) * sign(self.vector.y)\n self.cancel = cancel\n # the time the jump began\n self.time = -1\n # keeps track of the frames the jump button has been released\n self.counter = 0\n\n def run(self, agent):\n if agent.gravity.z == 3250:\n agent.pop()\n\n if self.time == -1:\n elapsed = 0\n self.time = agent.time\n else:\n elapsed = agent.time - self.time\n\n if elapsed < 0.15:\n agent.controller.jump = True\n elif elapsed >= 0.15 and self.counter < 3:\n agent.controller.jump = False\n self.counter += 1\n elif elapsed < 0.3 or (not self.cancel and elapsed < 0.9):\n agent.controller.jump = True\n agent.controller.pitch = self.pitch\n agent.controller.yaw = self.yaw\n else:\n agent.pop()\n agent.push(recovery())\n\n\nclass brake:\n def run(self, agent):\n speed = agent.me.local(agent.me.velocity).x\n if speed > 0:\n agent.controller.throttle = -1\n if speed < 25:\n agent.pop()\n elif speed < 0:\n agent.controller.throttle = 1\n if speed > -25:\n agent.pop()\n else:\n agent.pop()\n\n\nclass goto:\n # Drives towards a designated (stationary) target\n # Optional vector controls where the car should be pointing upon reaching the target\n # TODO - slow down if target is inside our turn radius\n def __init__(self, target, vector=None, direction=1, brake=False):\n self.target = target\n self.vector = vector\n self.direction = direction\n self.brake = brake\n\n def run(self, agent, manual=False):\n car_to_target = self.target - agent.me.location\n distance_remaining = car_to_target.flatten().magnitude()\n\n agent.dbg_2d(distance_remaining)\n agent.line(self.target - Vector(z=500), self.target + Vector(z=500), [255, 0, 255])\n\n if (not self.brake and distance_remaining < 350) or (self.brake and distance_remaining < (agent.me.local(agent.me.velocity).x ** 2 * -1) / (2 * brake_accel.x)):\n if not manual:\n agent.pop()\n\n if self.brake:\n agent.push(brake())\n return\n\n if self.vector != None:\n # See commends for adjustment in jump_shot or aerial for explanation\n side_of_vector = sign(self.vector.cross(Vector(z=1)).dot(car_to_target))\n car_to_target_perp = car_to_target.cross(Vector(z=side_of_vector)).normalize()\n adjustment = car_to_target.angle(self.vector) * distance_remaining / 3.14\n final_target = self.target + (car_to_target_perp * adjustment)\n else:\n final_target = self.target\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_target = agent.me.local(final_target - agent.me.location)\n\n angles = defaultPD(agent, local_target, self.direction)\n defaultThrottle(agent, 2300, self.direction)\n\n if len(agent.friends) > 0 and agent.me.local(agent.me.velocity).x < 250 and agent.controller.throttle > 0.75 and min(agent.me.location.flat_dist(car.location) for car in agent.friends) < 251:\n agent.push(flip(Vector(y=250)))\n return\n\n if agent.me.boost < 30 or (agent.playstyle is agent.playstyles.Defensive and agent.predictions['self_from_goal'] < 4000):\n agent.controller.boost = False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and distance_remaining / velocity > 2:\n agent.push(flip(local_target))\n elif abs(angles[1]) > 2.8 and velocity < 200 and distance_remaining / velocity > 2:\n agent.push(flip(local_target, True))\n elif agent.me.airborne:\n agent.push(recovery(self.target))\n\n\nclass dynamic_backcheck:\n def __init__(self):\n self.start_time = None\n self.goto = goto(Vector(), brake=True)\n\n def run(self, agent):\n if self.start_time is None:\n self.start_time = agent.time\n\n ball_loc = agent.ball.location.y * side(agent.team)\n\n if agent.time - self.start_time > 0.5 or agent.playstyle is agent.playstyles.Defensive or ball_loc > 2560:\n agent.pop()\n return\n\n target = Vector(y=(ball_loc + 1280) * side(agent.team))\n\n if agent.ball.location.x > 2560:\n target.x = 2560 if ball_loc <= 0 else 1024\n elif agent.ball.location.x < -2560:\n target.x = -2560 if ball_loc <= 0 else -1024\n\n self_to_target = agent.me.location.dist(target)\n\n if self_to_target > 250:\n self.goto.target = target\n self.goto.vector = agent.ball.location\n self.goto.run(agent, manual=True)\n\n if self_to_target < 500:\n agent.controller.boost = False\n agent.controller.throttle = cap(agent.controller.throttle, -0.75, 0.75)\n\n\nclass retreat:\n def __init__(self):\n self.counter = 0\n self.goto = goto(Vector(), brake=True)\n self.facing = False\n\n def run(self, agent):\n if agent.ball.location.y * side(agent.team) < 2560 and agent.playstyle is not agent.playstyles.Defensive:\n agent.pop()\n return\n\n team_to_ball = [car.location.flat_dist(agent.ball.location) for car in agent.friends if car.location.y * side(agent.team) >= agent.ball.location.y * side(agent.team) - 50 and abs(car.location.x) < abs(agent.ball.location.x)]\n self_to_ball = agent.me.location.flat_dist(agent.ball.location)\n team_to_ball.append(self_to_ball)\n team_to_ball.sort()\n\n if len(agent.friends) <= 1 or (agent.ball.location.x <= 900 and agent.ball.location.x >= -900) or len(team_to_ball) <= 1:\n target = agent.friend_goal.location\n elif team_to_ball[-1] == self_to_ball:\n target = agent.friend_goal.right_post if abs(agent.ball.location.x) > 900 else agent.friend_goal.left_post\n else:\n target = agent.friend_goal.left_post if abs(agent.ball.location.x) > 900 else agent.friend_goal.right_post\n\n target = target.copy()\n\n if agent.ball.location.y * side(agent.team) > 4620 and target == agent.friend_goal.location:\n target.y = (agent.ball.location.y * side(agent.team) + 250) * side(agent.team)\n else:\n target = target + Vector(y=-245 * side(agent.team))\n\n target = target.flatten()\n\n agent.line(target, target + Vector(z=100))\n\n if target.flat_dist(agent.me.location) < 100:\n if abs(agent.me.local(agent.me.velocity).x) > 10 and not self.facing:\n agent.push(brake())\n return\n\n if self.facing or (abs(agent.me.local(agent.me.velocity).x) < 10 and Vector(x=1).angle(agent.me.local(agent.ball.location - agent.me.location)) > 0.25):\n self.facing = True\n if self.counter == 0:\n agent.controller.jump = True\n elif self.counter == 2:\n agent.pop()\n agent.push(ball_recovery())\n self.counter += 1\n return\n\n agent.pop()\n else:\n self.goto.target = target\n self.goto.run(agent, manual=True)\n\n\nclass goto_boost:\n # very similar to goto() but designed for grabbing boost\n # if a target is provided the bot will try to be facing the target as it passes over the boost\n def __init__(self, boost):\n self.boost = boost\n self.start_time = None\n\n def run(self, agent):\n if self.start_time is None:\n self.start_time = agent.time\n\n car_to_boost = self.boost.location - agent.me.location\n distance_remaining = car_to_boost.flatten().magnitude()\n\n agent.line(self.boost.location - Vector(z=500), self.boost.location + Vector(z=500), [0, 255, 0])\n\n target = None if self.boost.large else agent.ball.location\n\n if target is not None:\n vector = (target - self.boost.location).normalize()\n side_of_vector = sign(vector.cross(Vector(z=1)).dot(car_to_boost))\n car_to_boost_perp = car_to_boost.cross(Vector(z=side_of_vector)).normalize()\n adjustment = car_to_boost.angle(vector) * distance_remaining / 3.14\n final_target = self.boost.location + (car_to_boost_perp * adjustment)\n car_to_target = (target - agent.me.location).magnitude()\n else:\n adjustment = 9999\n car_to_target = 0\n final_target = self.boost.location\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_target = agent.me.local(final_target - agent.me.location)\n\n angles = defaultPD(agent, local_target)\n defaultThrottle(agent, 2300)\n\n agent.controller.boost = self.boost.large if abs(angles[1]) < 0.3 else False\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n velocity = 1+agent.me.velocity.magnitude()\n if not self.boost.active or agent.me.boost >= 80.0 or distance_remaining < 350:\n agent.pop()\n elif agent.me.airborne:\n agent.push(recovery(target))\n elif abs(angles[1]) < 0.05 and velocity > 600 and velocity < 2150 and (distance_remaining / velocity > 2.0 or (adjustment < 90 and car_to_target/velocity > 2.0)):\n agent.push(flip(local_target))\n elif agent.time - self.start_time > 2.5:\n agent.pop()\n\n\nclass jump_shot:\n # Hits a target point at a target time towards a target direction\n # Target must be no higher than 300uu unless you're feeling lucky\n # TODO - speed\n def __init__(self, ball_location, intercept_time, shot_vector, direction=1):\n self.ball_location = ball_location\n self.intercept_time = intercept_time\n # The direction we intend to hit the ball in\n self.shot_vector = shot_vector\n # The point we dodge at\n # 172 is the 92uu ball radius + a bit more to account for the car's hitbox\n self.dodge_point = self.ball_location - (self.shot_vector * 172)\n # whether the car should attempt this backwards\n self.direction = direction\n # controls how soon car will jump based on acceleration required. max 584\n # bigger = later, which allows more time to align with shot vector\n # smaller = sooner\n self.jump_threshold = 400\n # Flags for what part of the routine we are in\n self.jumping = False\n self.dodging = False\n self.counter = 0\n\n def run(self, agent):\n agent.shooting = True\n raw_time_remaining = self.intercept_time - agent.time\n # Capping raw_time_remaining above 0 to prevent division problems\n time_remaining = cap(raw_time_remaining, 0.001, 10.0)\n car_to_ball = self.ball_location - agent.me.location\n # whether we are to the left or right of the shot vector\n side_of_shot = sign(self.shot_vector.cross(Vector(z=1)).dot(car_to_ball))\n\n car_to_dodge_point = self.dodge_point - agent.me.location\n car_to_dodge_perp = car_to_dodge_point.cross(Vector(z=side_of_shot)) # perpendicular\n distance_remaining = car_to_dodge_point.magnitude()\n\n speed_required = distance_remaining / time_remaining\n acceleration_required = backsolve(self.dodge_point, agent.me, time_remaining, 0 if not self.jumping else agent.gravity.z)\n local_acceleration_required = agent.me.local(acceleration_required)\n\n # The adjustment causes the car to circle around the dodge point in an effort to line up with the shot vector\n # The adjustment slowly decreases to 0 as the bot nears the time to jump\n adjustment = car_to_dodge_point.angle(self.shot_vector) * distance_remaining / 2.0 # size of adjustment\n # factoring in how close to jump we are\n adjustment *= (cap(self.jump_threshold - (acceleration_required.z), 0, self.jump_threshold) / self.jump_threshold)\n # we don't adjust the final target if we are already jumping\n final_target = self.dodge_point + ((car_to_dodge_perp.normalize() * adjustment) if not self.jumping else 0) + Vector(z=50)\n # Ensuring our target isn't too close to the sides of the field, where our car would get messed up by the radius of the curves\n\n # Some adjustment to the final target to ensure it's inside the field and we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n local_final_target = agent.me.local(final_target - agent.me.location)\n\n # drawing debug lines to show the dodge point and final target (which differs due to the adjustment)\n agent.line(agent.me.location, self.dodge_point, agent.renderer.white())\n agent.line(self.dodge_point-Vector(z=100), self.dodge_point+Vector(z=100), agent.renderer.red())\n agent.line(final_target-Vector(z=100), final_target+Vector(z=100), agent.renderer.green())\n\n # Calling our drive utils to get us going towards the final target\n angles = defaultPD(agent, local_final_target, self.direction)\n defaultThrottle(agent, speed_required, self.direction)\n\n agent.line(agent.me.location, agent.me.location + (self.shot_vector*200), agent.renderer.white())\n\n agent.controller.boost = False if abs(angles[1]) > 0.3 or agent.me.airborne else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) and self.direction == 1 else agent.controller.handbrake\n\n if not self.jumping:\n if raw_time_remaining <= 0 or (speed_required - 2300) * time_remaining > 45 or not shot_valid(agent, self):\n # If we're out of time or not fast enough to be within 45 units of target at the intercept time, we pop\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n if agent.me.airborne:\n agent.push(recovery())\n elif local_acceleration_required.z > self.jump_threshold and local_acceleration_required.z > local_acceleration_required.flatten().magnitude():\n # Switch into the jump when the upward acceleration required reaches our threshold, and our lateral acceleration is negligible\n self.jumping = True\n else:\n if (raw_time_remaining > 0.2 and not shot_valid(agent, self, 150)) or raw_time_remaining <= -0.9 or (not agent.me.airborne and self.counter > 0):\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(recovery())\n elif self.counter == 0 and local_acceleration_required.z > 0 and raw_time_remaining > 0.083:\n # Initial jump to get airborne + we hold the jump button for extra power as required\n agent.controller.jump = True\n elif self.counter < 3:\n # make sure we aren't jumping for at least 3 frames\n agent.controller.jump = False\n self.counter += 1\n elif raw_time_remaining <= 0.1 and raw_time_remaining > -0.9:\n # dodge in the direction of the shot_vector\n agent.controller.jump = True\n if not self.dodging:\n vector = agent.me.local(self.shot_vector)\n self.p = abs(vector.x) * -sign(vector.x)\n self.y = abs(vector.y) * sign(vector.y) * self.direction\n self.dodging = True\n # simulating a deadzone so that the dodge is more natural\n agent.controller.pitch = self.p if abs(self.p) > 0.2 else 0\n agent.controller.yaw = self.y if abs(self.y) > 0.3 else 0\n\n\nclass generic_kickoff:\n def __init__(self):\n self.flip = False\n\n def run(self, agent):\n if self.flip:\n agent.kickoff_done = True\n agent.pop()\n return\n\n target = agent.ball.location + Vector(y=200*side(agent.team))\n local_target = agent.me.local(target - agent.me.location)\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n agent.controller.boost = True\n\n distance = local_target.magnitude()\n\n if distance < 550:\n self.flip = True\n agent.push(flip(agent.me.local(agent.foe_goal.location - agent.me.location)))\n\n\nclass recovery:\n # Point towards our velocity vector and land upright, unless we aren't moving very fast\n # A vector can be provided to control where the car points when it lands\n def __init__(self, target=None):\n self.target = target\n\n def run(self, agent):\n if self.target is not None:\n local_target = agent.me.local((self.target - agent.me.location).flatten())\n else:\n local_target = agent.me.local(agent.me.velocity.flatten())\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n if not agent.me.airborne:\n agent.pop()\n\n\nclass ball_recovery:\n def run(self, agent):\n local_target = agent.me.local((agent.ball.location - agent.me.location).flatten())\n\n defaultPD(agent, local_target)\n agent.controller.throttle = 1\n if not agent.me.airborne:\n agent.pop()\n\n\nclass short_shot:\n # This routine drives towards the ball and attempts to hit it towards a given target\n # It does not require ball prediction and kinda guesses at where the ball will be on its own\n def __init__(self, target):\n self.target = target\n self.start_time = None\n\n def run(self, agent):\n agent.shooting = True\n\n if self.start_time is None:\n self.start_time = agent.time\n\n car_to_ball, distance = (agent.ball.location - agent.me.location).normalize(True)\n ball_to_target = (self.target - agent.ball.location).normalize()\n\n relative_velocity = car_to_ball.dot(agent.me.velocity-agent.ball.velocity)\n if relative_velocity != 0:\n eta = cap(distance / cap(relative_velocity, 400, 2300), 0, 1.5)\n else:\n eta = 1.5\n\n # If we are approaching the ball from the wrong side the car will try to only hit the very edge of the ball\n left_vector = car_to_ball.cross(Vector(z=1))\n right_vector = car_to_ball.cross(Vector(z=-1))\n target_vector = -ball_to_target.clamp(left_vector, right_vector)\n final_target = agent.ball.location + (target_vector*(distance/2))\n\n # Some adjustment to the final target to ensure we don't try to dirve through any goalposts to reach it\n if abs(agent.me.location.y) > 5150:\n final_target.x = cap(final_target.x, -750, 750)\n\n agent.line(final_target-Vector(z=100), final_target + Vector(z=100), [255, 255, 255])\n\n angles = defaultPD(agent, agent.me.local(final_target-agent.me.location))\n defaultThrottle(agent, 2300 if distance > 1600 else 2300-cap(1600*abs(angles[1]), 0, 2050))\n agent.controller.boost = False if agent.me.airborne or abs(angles[1]) > 0.3 else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) else agent.controller.handbrake\n\n if abs(angles[1]) < 0.05 and (eta < 0.45 or distance < 150):\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n agent.push(flip(agent.me.local(car_to_ball)))\n elif agent.time - self.start_time > 3:\n agent.pop()\n agent.shooting = False\n agent.shot_weight = -1\n agent.shot_time = -1\n\n\nclass block_ground_shot:\n def __init__(self):\n self.ball_location = None\n self.intercept_time = None\n self.direction = None\n self.brake = False\n\n def run(self, agent):\n agent.shooting = True\n agent.shot_weight = agent.max_shot_weight - 1\n if self.ball_location is None or not shot_valid(agent, self, threshold=75):\n self.ball_location, self.intercept_time, self.direction = self.get_intercept(agent)\n\n if self.ball_location is None:\n agent.shooting = False\n agent.shot_weight = -1\n agent.pop()\n return\n\n agent.shot_time = self.intercept_time\n t = self.intercept_time - agent.time\n\n # if we ran out of time, just pop\n # this can be because we were successful or not - we can't tell\n if t < -0.3:\n agent.shooting = False\n agent.shot_weight = -1\n agent.pop()\n return\n\n if self.brake:\n if agent.ball.location.dist(agent.me.location) < 250 and agent.ball.location.y * side(agent.team) + 10 < agent.me.location.y and agent.ball.location.z < 190:\n agent.pop()\n agent.flip(agent.me.local(agent.ball.location))\n else:\n # current velocity\n u = agent.me.local(agent.me.velocity).x\n a = brake_accel.x\n # calculate how much distance we need to slow down\n x = (u ** 2 * -1) / (2 * a)\n\n if self.ball_location.dist(agent.me.location) <= x:\n self.brake = True\n agent.push(brake())\n return\n\n agent.line(self.ball_location.flatten(), self.ball_location.flatten() + Vector(z=250), color=[255, 0, 255])\n angles = defaultPD(agent, agent.me.local(self.ball_location - agent.me.location), self.direction)\n # We want to get there before the ball does, so take the time we have and get 3 fifths of it\n required_speed = cap(agent.me.location.dist(self.ball_location) / ((self.intercept_time - agent.time) * (3/5)), 600, 2275)\n defaultThrottle(agent, required_speed, self.direction)\n\n agent.controller.boost = False if abs(angles[1]) > 0.3 else agent.controller.boost\n agent.controller.handbrake = True if abs(angles[1]) >= 2.3 or (agent.me.local(agent.me.velocity).x >= 1400 and abs(angles[1]) > 1.5) and self.direction == 1 else False\n\n def is_viable(self, agent):\n self.ball_location, self.intercept_time, self.direction = self.get_intercept(agent)\n if self.ball_location is None:\n return False\n\n agent.print(f\"Block ground shot {round(self.ball_location.dist(agent.me.location), 4)}uu's away in {round(self.intercept_time - agent.time, 4)}s (Direction: {self.direction})\")\n return True\n\n def get_intercept(self, agent):\n struct = agent.predictions['ball_struct']\n intercepts = []\n\n i = 30 # Begin by looking 0.3 seconds into the future\n while i < struct.num_slices:\n intercept_time = struct.slices[i].game_seconds\n time_remaining = intercept_time - agent.time\n\n ball_location = Vector(struct.slices[i].physics.location.x, struct.slices[i].physics.location.y, struct.slices[i].physics.location.z)\n\n if abs(ball_location.y) > 5212:\n break\n\n last_ball_location = Vector(struct.slices[i-2].physics.location.x, struct.slices[i-2].physics.location.y, struct.slices[i-2].physics.location.z)\n ball_velocity = Vector(struct.slices[i].physics.velocity.x, struct.slices[i].physics.velocity.y, struct.slices[i].physics.velocity.z).magnitude()\n\n i += 15 - cap(int(ball_velocity//150), 0, 13)\n\n if time_remaining < 0 or ball_location.z > 120 or ball_location.flat_dist(agent.friend_goal.location) > last_ball_location.flat_dist(agent.friend_goal.location):\n continue\n\n car_to_ball = ball_location - agent.me.location\n direction, distance = car_to_ball.normalize(True)\n\n forward_angle = direction.angle(agent.me.forward)\n backward_angle = math.pi - forward_angle\n\n forward_time = time_remaining - (forward_angle * 0.318)\n backward_time = time_remaining - (backward_angle * 0.418)\n\n forward_flag = forward_time > 0 and (distance / forward_time) < 1800\n backward_flag = distance < 1500 and backward_time > 0 and (distance / backward_time) < 1200\n\n if forward_flag or backward_flag:\n intercepts.append((\n ball_location,\n intercept_time,\n 1 if forward_flag else -1\n ))\n\n if len(intercepts) == 0:\n return None, None, None\n\n intercepts = list(filter(lambda i: i[1] - agent.time < 3, intercepts))\n\n intercepts.sort(key=lambda i: agent.me.location.dist(i[0]))\n\n final = (None, None, None)\n last_speed = math.inf\n\n for intercept in intercepts:\n speed = agent.me.location.dist(intercept[0]) / ((intercept[1] / agent.time) * (3/5))\n if abs(speed - 1100) < abs(last_speed - 1100):\n final = intercept\n last_speed = speed\n\n return final\n","sub_path":"RLBotPack/VirxEB/util/routines.py","file_name":"routines.py","file_ext":"py","file_size_in_byte":33883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26240873","text":"from liberapay.exceptions import MissingPaymentAccount\nfrom liberapay.models.exchange_route import ExchangeRoute\nfrom liberapay.payin.common import resolve_destination\nfrom liberapay.testing import Harness, EUR\n\n\nclass TestPayins(Harness):\n\n def test_resolve_destination(self):\n alice = self.make_participant('alice')\n bob = self.make_participant('bob')\n carl = self.make_participant('carl')\n team = self.make_participant('team', kind='group')\n alice.set_tip_to(team, EUR('10'))\n\n # Test without payment account\n team.add_member(bob)\n with self.assertRaises(MissingPaymentAccount):\n resolve_destination(self.db, team, 'stripe', alice, 'FR', EUR('10'))\n\n # Test without payment account at the requested provider\n stripe_account_bob = self.add_payment_account(bob, 'stripe')\n with self.assertRaises(MissingPaymentAccount):\n resolve_destination(self.db, team, 'paypal', alice, 'US', EUR('10'))\n\n # Test with a single member and the take at zero\n account = resolve_destination(self.db, team, 'stripe', alice, 'GB', EUR('7'))\n assert account == stripe_account_bob\n\n # Test with two members but only one payment account\n team.add_member(carl)\n account = resolve_destination(self.db, team, 'stripe', alice, 'CH', EUR('8'))\n assert account == stripe_account_bob\n\n # Test with two members but only one payment account at the requested provider\n paypal_account_carl = self.add_payment_account(carl, 'paypal')\n account = resolve_destination(self.db, team, 'stripe', alice, 'BE', EUR('42'))\n assert account == stripe_account_bob\n\n # Test with two members and both takes at zero\n stripe_account_carl = self.add_payment_account(carl, 'stripe')\n account = resolve_destination(self.db, team, 'stripe', alice, 'PL', EUR('5.46'))\n assert account == stripe_account_bob\n account = resolve_destination(self.db, team, 'paypal', alice, 'PL', EUR('99.9'))\n assert account == paypal_account_carl\n\n # Test with two members and one non-zero take\n team.set_take_for(bob, EUR('1'), bob)\n account = resolve_destination(self.db, team, 'stripe', alice, 'RU', EUR('50.02'))\n assert account == stripe_account_bob\n account = resolve_destination(self.db, team, 'paypal', alice, 'RU', EUR('33'))\n assert account == paypal_account_carl\n\n # Test with two members and two different non-zero takes\n team.set_take_for(carl, EUR('2'), carl)\n account = resolve_destination(self.db, team, 'stripe', alice, 'BR', EUR('10'))\n assert account == stripe_account_carl\n account = resolve_destination(self.db, team, 'stripe', alice, 'BR', EUR('1'))\n assert account == stripe_account_carl\n account = resolve_destination(self.db, team, 'paypal', alice, 'BR', EUR('5'))\n assert account == paypal_account_carl\n\n # Check that members are cycled through\n alice_card = ExchangeRoute.insert(\n alice, 'stripe-card', 'x', 'chargeable', remote_user_id='x'\n )\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('2'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('1'))\n assert pt.destination == stripe_account_bob.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('4'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('10'))\n assert pt.destination == stripe_account_carl.pk\n payin, pt = self.make_payin_and_transfer(alice_card, team, EUR('2'))\n assert pt.destination == stripe_account_bob.pk\n","sub_path":"tests/py/test_payins.py","file_name":"test_payins.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330441791","text":"# Copyright 2018-2019 QuantumBlack Visual Analytics Limited\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\n# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS\n# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# The QuantumBlack Visual Analytics Limited (“QuantumBlack”) name and logo\n# (either separately or in combination, “QuantumBlack Trademarks”) are\n# trademarks of QuantumBlack. The License does not grant you any right or\n# license to the QuantumBlack Trademarks. You may not use the QuantumBlack\n# Trademarks or any confusingly similar mark as a trademark for your product,\n# or use the QuantumBlack Trademarks in any other manner that might cause\n# confusion in the marketplace, including but not limited to in advertising,\n# on websites, or on software.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest import mock\n\nimport pytest\n\nfrom kedro.contrib.io.pyspark import SparkJDBCDataSet\nfrom kedro.io import DataSetError\n\n\n@pytest.fixture\ndef spark_jdbc_args():\n return {\"url\": \"dummy_url\", \"table\": \"dummy_table\"}\n\n\n@pytest.fixture\ndef spark_jdbc_args_credentials(spark_jdbc_args):\n args = spark_jdbc_args\n args.update({\"credentials\": {\"user\": \"dummy_user\", \"password\": \"dummy_pw\"}})\n return args\n\n\n@pytest.fixture\ndef spark_jdbc_args_save_load(spark_jdbc_args):\n args = spark_jdbc_args\n connection_properties = {\"properties\": {\"driver\": \"dummy_driver\"}}\n args.update(\n {\"save_args\": connection_properties, \"load_args\": connection_properties}\n )\n return args\n\n\ndef test_missing_url():\n error_message = (\n \"`url` argument cannot be empty. Please provide a JDBC\"\n \" URL of the form ``jdbc:subprotocol:subname``.\"\n )\n with pytest.raises(DataSetError, match=error_message):\n SparkJDBCDataSet(url=None, table=\"dummy_table\")\n\n\ndef test_missing_table():\n error_message = (\n \"`table` argument cannot be empty. Please provide\"\n \" the name of the table to load or save data to.\"\n )\n with pytest.raises(DataSetError, match=error_message):\n SparkJDBCDataSet(url=\"dummy_url\", table=None)\n\n\ndef mock_save(arg_dict):\n mock_data = mock.Mock()\n data_set = SparkJDBCDataSet(**arg_dict)\n data_set.save(mock_data)\n return mock_data\n\n\ndef test_save(spark_jdbc_args):\n data = mock_save(spark_jdbc_args)\n data.write.jdbc.assert_called_with(\"dummy_url\", \"dummy_table\")\n\n\ndef test_save_credentials(spark_jdbc_args_credentials):\n data = mock_save(spark_jdbc_args_credentials)\n data.write.jdbc.assert_called_with(\n \"dummy_url\",\n \"dummy_table\",\n properties={\"user\": \"dummy_user\", \"password\": \"dummy_pw\"},\n )\n\n\ndef test_save_args(spark_jdbc_args_save_load):\n data = mock_save(spark_jdbc_args_save_load)\n data.write.jdbc.assert_called_with(\n \"dummy_url\", \"dummy_table\", properties={\"driver\": \"dummy_driver\"}\n )\n\n\n@mock.patch(\"kedro.contrib.io.pyspark.spark_jdbc.SparkSession.builder.getOrCreate\")\ndef mock_load(mock_get_or_create, arg_dict):\n spark = mock_get_or_create.return_value\n data_set = SparkJDBCDataSet(**arg_dict)\n data_set.load()\n return spark\n\n\ndef test_load(spark_jdbc_args):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args)\n spark.read.jdbc.assert_called_with(\"dummy_url\", \"dummy_table\")\n\n\ndef test_load_credentials(spark_jdbc_args_credentials):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args_credentials)\n spark.read.jdbc.assert_called_with(\n \"dummy_url\",\n \"dummy_table\",\n properties={\"user\": \"dummy_user\", \"password\": \"dummy_pw\"},\n )\n\n\ndef test_load_args(spark_jdbc_args_save_load):\n # pylint: disable=no-value-for-parameter\n spark = mock_load(arg_dict=spark_jdbc_args_save_load)\n spark.read.jdbc.assert_called_with(\n \"dummy_url\", \"dummy_table\", properties={\"driver\": \"dummy_driver\"}\n )\n\n\ndef test_cant_pickle():\n import pickle\n\n with pytest.raises(pickle.PicklingError):\n pickle.dumps(SparkJDBCDataSet(\"bob\", \"test\"))\n","sub_path":"tests/contrib/io/pyspark/test_spark_jdbc.py","file_name":"test_spark_jdbc.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"114249348","text":"# Copyright 2009-2023 NTESS. Under the terms\n# of Contract DE-NA0003525 with NTESS, the U.S.\n# Government retains certain rights in this software.\n#\n# Copyright (c) 2009-2023, NTESS\n# All rights reserved.\n#\n# This file is part of the SST software package. For license\n# information, see the LICENSE file in the top level directory of the\n# distribution.\nimport sst\n\n# Define SST core options\nsst.setProgramOption(\"stop-at\", \"10us\")\n\n\n# Set up sender using anonymous subcomponent\nloader0 = sst.Component(\"Loader0\", \"coreTestElement.SubComponentLoader\")\nloader0.addParam(\"clock\", \"1.5GHz\")\nloader0.addParam(\"unnamed_subcomponent\", \"coreTestElement.SubCompSender\")\nloader0.addParam(\"sendCount\", 15)\nloader0.enableAllStatistics()\n\n# Set up receiver using anonymous subcomponent\nloader1 = sst.Component(\"Loader1\", \"coreTestElement.SubComponentLoader\")\nloader1.addParam(\"clock\", \"1.0GHz\")\nloader1.addParam(\"unnamed_subcomponent\", \"coreTestElement.SubCompReceiver\")\nloader1.enableAllStatistics()\n\n# Set up link\nlink = sst.Link(\"myLink\")\nlink.connect((loader0, \"port0\", \"5ns\"), (loader1, \"port0\", \"5ns\"))\n\nsst.setStatisticLoadLevel(1)\n","sub_path":"tests/subcomponent_tests/test_sc_a.py","file_name":"test_sc_a.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"412034243","text":"import numpy\r\nimport ANN\r\nimport csv\r\nimport random\r\nimport Hawk\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndef best(fitness):\r\n\tmax_fitness = 0\r\n\tpos = -1\r\n\tfor i in range(len(fitness)):\r\n\t\tif fitness[i] > max_fitness:\r\n\t\t\tmax_fitness = fitness[i]\r\n\t\t\tpos = i\r\n\treturn pos\r\n\r\ndef Calculate_mean(pop_weights_mat):\r\n\tmean = pop_weights_mat[0]\r\n\tfor i in range(1,len(pop_weights_mat)):\r\n\t\tmean += pop_weights_mat[i]\r\n\treturn mean/len(pop_weights_mat)\r\n\r\ndef load_data():\r\n data_inputs = []\r\n with open('datasets/breast_wisconsin.csv','r') as csvfile:\r\n rows = csv.reader(csvfile)\r\n for row in rows:\r\n row = numpy.array(row,dtype = float)\r\n data_inputs.append(row)\r\n # data_output = [row[-1] for row in data_inputs]\r\n # data_input = [row[:-1] for row in data_inputs]\r\n data_outputs = []\r\n with open('datasets/label_wisconsin.csv','r') as csvfile:\r\n rows = csv.reader(csvfile)\r\n for row in rows:\r\n row = numpy.array(row,dtype = float)\r\n data_outputs.append(row)\r\n return data_inputs,data_outputs\r\n\r\ndata_inputs, data_outputs = load_data()\r\n\r\nminmax = ANN.dataset_minmax(data_inputs)\r\nANN.normalize_dataset(data_inputs, minmax)\r\ndata_inputs = numpy.array(data_inputs)\r\ndata_outputs = numpy.array(data_outputs)\r\ndata_inputs, X, data_outputs, y = train_test_split(data_inputs, data_outputs,test_size = 0.15, random_state = 1)\r\n\r\nprint(data_inputs.shape)\r\n\r\nsol_per_pop = 12\r\nnum_generations = 100\r\n\r\n# HL1_neurons = data_inputs.shape[1] * 2 #for cancer_patient\r\n# HL2_neurons = int(data_inputs.shape[1]/2)\r\n# output_neurons = 3\r\n\r\nHL1_neurons = data_inputs.shape[1] * 2 #for cancer_patient\r\nHL2_neurons = int(data_inputs.shape[1]/2)\r\noutput_neurons = 2\r\n\r\nweight_range_1 = -1\r\nweight_range_2 = 1\r\n\r\ninitial_pop_weights = []\r\nfor curr_sol in numpy.arange(0, sol_per_pop):\r\n\tinput_HL1_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(data_inputs.shape[1], HL1_neurons))\r\n\tHL1_HL2_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL1_neurons, HL2_neurons))\r\n\tHL2_output_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL2_neurons, output_neurons))\r\n\tinitial_pop_weights.append(numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights]))\r\n\r\npop_weights_mat = numpy.array(initial_pop_weights)\r\n\r\nfitness = ANN.fitness(pop_weights_mat, data_inputs,data_outputs, activation=\"tanh\")\r\nbest_index = best(fitness)\r\nrabbit = pop_weights_mat[best_index]\r\nE_value = []\r\nbest_result = []\r\nbest_pop = []\r\nmean_fitness = []\r\nmax_f = []\r\naccuracies = numpy.empty(shape=(num_generations))\r\nsigma = pow(((1.33*.707)/(.9064*1.5*pow(2,.25))),2/3)\r\nfor generation in range(num_generations):\r\n\tprint(\"Generation : \", generation)\r\n\tfitness = ANN.fitness(pop_weights_mat, data_inputs,data_outputs, activation=\"tanh\")\r\n\tprint(fitness)\r\n\tbest_index = best(fitness)\r\n\tmax_f.append(fitness[best_index])\r\n\trabbit = pop_weights_mat[best_index]\r\n\r\n\taccuracies[generation] = fitness[best_index]\r\n\tMean_pop_weight = Calculate_mean(pop_weights_mat)\r\n\tmean_fitness.append(Calculate_mean(fitness))\r\n\tfor i in range(len(pop_weights_mat)):\r\n\t\tif i == best_index:\r\n\t\t\tcontinue\r\n\t\tinput_HL1_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(data_inputs.shape[1], HL1_neurons))\r\n\t\tHL1_HL2_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL1_neurons, HL2_neurons))\r\n\t\tHL2_output_weights = numpy.random.uniform(low=weight_range_1, high=weight_range_2, size=(HL2_neurons, output_neurons))\r\n\t\tS = []\r\n\t\tS.append(numpy.array([input_HL1_weights, HL1_HL2_weights, HL2_output_weights]))\r\n\t\tS = numpy.array(S)\r\n\t\tbase_E = 2*random.random() - 1\r\n\t\tJ = 2*(1 - random.random())\r\n\t\tr = random.random()\r\n\t\tE = 2*base_E*(1 - generation/num_generations)\r\n\t\tE_value.append(E)\r\n\t\tif abs(E) >= 1:\r\n\t\t\trand_hawk_index = random.randrange(0,sol_per_pop)\r\n\t\t\twhile(rand_hawk_index != i):\r\n\t\t\t\trand_hawk_index = random.randrange(0,sol_per_pop)\r\n\t\t\trand_hawk = pop_weights_mat[rand_hawk_index]\r\n\t\t\tpop_weights_mat[i] = Hawk.update_hawk1(pop_weights_mat[i], rabbit, Mean_pop_weight, rand_hawk, weight_range_1, weight_range_2) #update using eq 1\r\n\t\telse:\r\n\t\t\tif r >= .5 and abs(E) >= .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk2(pop_weights_mat[i], rabbit, J, E) #update using eq 4\r\n\t\t\telif r >= .5 and abs(E) < .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk3(pop_weights_mat[i], rabbit, E) #update using eq6\r\n\t\t\telif r < .5 and abs(E) >= .5:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk4(pop_weights_mat[i], rabbit, J, E, sigma, S, data_inputs, data_outputs) #update using eq10\r\n\t\t\telse:\r\n\t\t\t\tpop_weights_mat[i] = Hawk.update_hawk5(pop_weights_mat[i], rabbit, Mean_pop_weight, J, E, sigma, S, data_inputs, data_outputs) #update using eq11\r\n\r\n\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.plot(E_value)\r\nplt.show()\r\nx = [i for i in range(0,100)]\r\nfig, ax = plt.subplots()\r\nax.plot(x,mean_fitness)\r\nax.plot(x, max_f)\r\nplt.show()\r\nbest_weights = rabbit\r\nacc, predictions = ANN.predict_outputs(best_weights, X, y, activation=\"tanh\")\r\n# print(fitness[best_index])\r\nprint(acc)\r\n","sub_path":"Code/main_Hawk.py","file_name":"main_Hawk.py","file_ext":"py","file_size_in_byte":5214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"18794482","text":"from water_line import *\nfrom wave_crest import *\n\nDATA_BASE = \"/home/patchgreen99/surf/\"\nSOURCE = \"static/\"\n\ndef update():\n\n img = cv2.imread(DATA_BASE+SOURCE+\"latest.jpg\")\n img = img[100:700, 0:1600]\n\n y, img = draw(img)\n crest_draw(img, y)\n\n cv2.imwrite(DATA_BASE+SOURCE+\"ready.jpg\", img)","sub_path":"python/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623110284","text":"\n\n#calss header\nclass _VALE():\n\tdef __init__(self,): \n\t\tself.name = \"VALE\"\n\t\tself.definitions = [u'used in the name of some valleys: ', u'a valley: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_vale.py","file_name":"_vale.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"390928613","text":"import argparse\nimport torch\nfrom torch.nn.utils import parameters_to_vector, vector_to_parameters\nfrom torch.utils.data import DataLoader\nfrom pathlib import Path\n\nfrom utils import load_model\nfrom problems import CVRP\n\n\ndef fitness(dataset, model, params):\n # Need a dataloader to batch instances\n dataloader = DataLoader(dataset, batch_size=1000)\n\n # Make var works for dicts\n batch = next(iter(dataloader))\n \n # Set the model parameters\n vector_to_parameters(params, model.parameters())\n\n # Run the model\n # model.eval() #? keep?\n model.set_decode_type('greedy')\n with torch.no_grad():\n length, log_p, pi = model(batch, return_pi=True)\n\n return length.mean()\n\n\ndef train(num_epochs, num_samples, vis_iter, save_iter, sigma, lr, problem_size, dataset_size, mirror_sampling, load_source):\n # setup\n torch.manual_seed(1234)\n\n savedir = f'saved_params/cvrp_{problem_size}'\n Path(savedir).mkdir(parents=True, exist_ok=True)\n\n model, _ = load_model(f'pretrained/cvrp_{problem_size}/')\n\n if load_source is not None:\n params = torch.load(f'{savedir}/{load_source}')\n print(f'Starting with pretrained model {load_source}')\n else:\n params = torch.load(f'{savedir}/base')\n print('Starting with untrained model')\n params.requires_grad = False\n\n dataset = CVRP.make_dataset(size=problem_size, num_samples=dataset_size)\n\n # report starting fitness\n print(f'Fitness started at \\t{fitness(dataset, model, params).item()}')\n print('-' * 19)\n\n # training loop\n fitness_history = []\n for epoch in range(num_epochs):\n\n # estimate gradient\n grad = 0\n for _ in range(num_samples):\n eps = torch.randn_like(params)\n grad += fitness(dataset, model, params + sigma * eps) * eps\n if mirror_sampling:\n grad += fitness(dataset, model, params - sigma * eps) * (-eps)\n\n if mirror_sampling:\n grad /= 2 * num_samples * sigma\n else:\n grad /= num_samples * sigma\n\n # update parameters by following gradient\n params -= lr * grad\n\n # print current fitness\n if epoch % vis_iter == vis_iter - 1:\n f = fitness(dataset, model, params).item()\n print(f'Epoch {epoch + 1}/{num_epochs} \\t\\t{f}')\n fitness_history.append(f)\n\n # save current parameters\n if epoch % save_iter == save_iter - 1:\n torch.save(params, f'{savedir}/epoch_{epoch + 1}')\n with open(f'{savedir}/fitness_history', 'w') as f:\n f.write(str(fitness_history))\n\n\nparser = argparse.ArgumentParser(description='Finetune the trained attention model using OpenAI\\'s natural evolution strategy')\nparser.add_argument('--epochs', default=10000, type=int)\nparser.add_argument('--samples', default=10, type=int)\nparser.add_argument('--vis_iter', default=1, type=int)\nparser.add_argument('--save_iter', default=10, type=int)\nparser.add_argument('--sigma', default=0.01, type=float)\nparser.add_argument('--lr', default=1e-6, type=float)\nparser.add_argument('--problem_size', default=100, type=int)\nparser.add_argument('--dataset_size', default=100, type=int)\nparser.add_argument('--mirror_sampling', default=True, type=bool)\nparser.add_argument('--load_source', '-l', default=None, type=str)\nargs = parser.parse_args()\n\ntrain(args.epochs, args.samples, args.vis_iter, args.save_iter, args.sigma, args.lr, args.problem_size, args.dataset_size, args.mirror_sampling, args.load_source)\n","sub_path":"evolve/vrp_evolve.py","file_name":"vrp_evolve.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87628054","text":"# This file was used to produce Figure 5\n\nfrom mpl_toolkits import basemap as bm\nfrom matplotlib import pyplot as plt\nfrom matplotlib import colors\nimport numpy as np\nimport pandas as pd\nimport numpy.ma as ma\nimport matplotlib.gridspec as gridspec\n\nD0 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_january')\nD1 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_february')\nD2 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_june')\nD3 = pd.read_pickle('/home/riqo/surface_snow_files/average_values_october')\n\nround_O = np.around(D1['delta_O_snow']/5, decimals=0)*5\n\n##some fake data\nlat = D1['latitude'][:]\nlon = np.hstack((D1['longitude'], D1['longitude'][:1]))\nlon, lat = np.meshgrid(lon, lat)\n\ndelta_O_snow0 = np.hstack((D0['delta_O_snow'], D0['delta_O_snow'][:,:1]))\ndelta_O_snow1 = np.hstack((D1['delta_O_snow'], D1['delta_O_snow'][:,:1]))\ndelta_O_snow2 = np.hstack((D2['delta_O_snow'], D2['delta_O_snow'][:,:1]))\ndelta_O_snow3 = np.hstack((D3['delta_O_snow'], D3['delta_O_snow'][:,:1]))\n\nmost_northern_point = 133\n\nminimum = min(\n np.nanmin(D0['delta_O_snow'][most_northern_point:,:]), np.nanmin(D1['delta_O_snow'][most_northern_point:,:]),\n np.nanmin(D2['delta_O_snow'][most_northern_point:,:]), np.nanmin(D3['delta_O_snow'][most_northern_point:,:])\n)\n\nmaximum = max(\n np.nanmax(D0['delta_O_snow'][most_northern_point:,:][np.nonzero(D0['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D1['delta_O_snow'][most_northern_point:,:][np.nonzero(D1['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D2['delta_O_snow'][most_northern_point:,:][np.nonzero(D2['delta_O_snow'][most_northern_point:,:])]),\n np.nanmax(D3['delta_O_snow'][most_northern_point:,:][np.nonzero(D3['delta_O_snow'][most_northern_point:,:])])\n)\n\nrounded_minimum = np.around(minimum/5, decimals=0)*5\nrounded_maximum = np.around(maximum/5, decimals=0)*5\n\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(6,6))\n\naxes[0,0].set_title('January')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[0,0])\nm.drawcoastlines(linewidth=0.5)\n\naxes[0,1].set_title('February')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[0,1])\nm.drawcoastlines(linewidth=0.5)\n\naxes[1,0].set_title('June')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[1,0])\nm.drawcoastlines(linewidth=0.5)\n\naxes[1,1].set_title('October')\nm = bm.Basemap(projection='spstere', boundinglat=-65, lon_0=180, resolution='l', ax = axes[1,1])\nm.drawcoastlines(linewidth=0.5)\n\nx,y = m(lon,lat)\n\npcol0 = axes[0,0].pcolormesh(x, y, delta_O_snow0, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol1 = axes[0,1].pcolormesh(x, y, delta_O_snow1, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol2 = axes[1,0].pcolormesh(x, y, delta_O_snow2, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\npcol3 = axes[1,1].pcolormesh(x, y, delta_O_snow3, cmap='viridis', vmin = rounded_minimum, vmax = rounded_maximum)\n\n##producing a mask -- seems to only work with full coordinate limits\nlons2 = np.linspace(-180,180,10000)\nlats2 = np.linspace(-90,90,5000)\nlon2, lat2 = np.meshgrid(lons2,lats2)\nx2,y2 = m(lon2,lat2)\npseudo_data = np.ones_like(lon2)\nmasked = bm.maskoceans(lon2,lat2,pseudo_data)\nmasked.mask = ~masked.mask\n\n##plotting the mask\ncmap = colors.ListedColormap(['w'])\npcol0 = axes[0,0].pcolormesh(x2, y2, masked, cmap=cmap)\npcol1 = axes[0,1].pcolormesh(x2, y2, masked, cmap=cmap)\npcol2 = axes[1,0].pcolormesh(x2, y2, masked, cmap=cmap)\npcol3 = axes[1,1].pcolormesh(x2, y2, masked, cmap=cmap)\n\n#fig.subplots_adjust(wspace=0.1, hspace=0.1)\n\nFigures_paths = '/home/riqo/Figures/'\n\nplt.savefig(Figures_paths + 'Figure5')\n\nplt.show()\n\n\n","sub_path":"Analysis/Figures5-7/Figure5.py","file_name":"Figure5.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"507769382","text":"#!/usr/bin/python3\n# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8# coding=utf-8\n#import sys\nimport pymysql\nimport traceback \nimport datetime ,time\n\n\n\ndef connectdb():\n print('Creating Connection...')\n db = pymysql.connect(host=\"test.csxyg8gxd1zd.us-east-2.rds.amazonaws.com\",user=\"admin\",passwd=\"LYC438sby\",db=\"IT493\",charset=\"utf8\")\n print('Connect successfully ...')\n return db ;\n\n\ndef query(db,sql=\"select * from Orders\"):\n cursor=db.cursor()\n\n try:\n cursor.execute(sql)\n results=cursor.fetchall()\n for line in results:\n print (str(line))\n except:\n traceback.print_exc() \n print (\"ERROR :unable fetch data\")\n\ndef insertQ(db,sql = \"\"\"INSERT INTO Orders(OrderID) VALUES (10)\"\"\"):\n cursor=db.cursor()\n\n try:\n # 执行sql语句\n cursor.execute(sql)\n # 提交到数据库执行\n db.commit()\n print(\"Insert successfully\")\n except:\n # 如果发生错误则回滚\n traceback.print_exc() \n db.rollback()\n print(\"Insert faliure\")\n\n\n\ndef OrderTable(db,lim):\n print(\"-----------------------------Order Table----------------------------------\")\n\n if lim == 'all':\n sql=\"select * from Orders\"\n elif lim == \"Pending\" or lim == \"pending\":\n sql=\"select * from Orders where OrderStatus = 'Pending'\"\n\n else:\n print(\"wrong input\")\n pass\n query(db,sql)\n \n\n\n \n\ndef main():\n db=connectdb()\n #query(db,sql=\"Describe Orders\")\n\n OrderTable(db,lim=\"Pending\")\n\n #insertQ(db)\n \n db.close()\n\nif __name__=='__main__':\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"351328998","text":"# commands\nCOMMAND = 'command-request'\nBCOMMAND = 'bcommand-request'\nREGISTER = 'command-register'\nLOGIN = 'command-login'\nSTATUS = 'command-status'\nDEBUG_BREAK = 'command-debugbreak'\nHANDSHAKE = 'command-handshake'\nBATTLE = 'command-battle'\nCHALLENGE = 'command-challenge'\nMOVE = 'command-move'\nRENAME = 'command-rename'\nTEMPLATE = 'command-template'\nBUILD = 'bcommand-build'\nFORCE = 'bcommand-force'\nACTION = 'bcommand-action'\n\n# args\nDEBUG_LEVEL = 'arg-debug_level'\nUSERNAME = 'arg-username'\nPASSWORD = 'arg-password'\nVERBOSE = 'arg-verbose'\nTARGET = 'arg-target'\nDIRECTION = 'arg-direction'\nUNIT = 'arg-unit'\n\nNORTH = 'arg-north'\nSOUTH = 'arg-south'\nEAST = 'arg-east'\nWEST = 'arg-west'\n\n# responses\nLOGIN_REQUIRED = 'response-login_required'\nERR_COMMAND = 'response-error_running_command'\nERR_PROCESS = 'response-error_processing_command'\nMISS_COMMAND = 'response-missing_command'\nBAD_ARGS = 'response-bad_args'\nILLEGAL = 'response-illegal_request'\n\nerrors = [\n ERR_COMMAND,\n ERR_PROCESS,\n MISS_COMMAND,\n BAD_ARGS,\n ILLEGAL,\n]","sub_path":"game_files/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14840218","text":"import Global\nimport pygame\nimport sqlite3\nimport Combo\nimport HP_bar\nimport Bezier_curve\nimport Pony_bar\nimport random\nimport Battle\n\n#constant\nclass Local(object):\n\t@staticmethod\n\tdef load_CM(pony_list):\n\t\tconn=sqlite3.connect(Global.database_name)\n\t\tc=conn.cursor()\n\t\tconst=c.execute('''select var, value\n\t\t\tfrom const\n\t\t\twhere field=\"CM_board\"''')\n\t\tfor var, value in const :\n\t\t\tif var == \"background\" :\n\t\t\t\tpic=pygame.image.load(value).convert()\n\t\t\t\tCM_board.background=pygame.transform.scale(pic,\n\t\t\t\t\t\tLocal.window_size)\n\t\t\t\tbreak\n\t\tfor i in pony_list :\n\t\t\tCM_list=c.execute('''\n\t\t\tselect CM.id, CM.name, CM.pic\n\t\t\tfrom cutie_mark as CM, pony, pony_CM\n\t\t\twhere CM.id=pony_CM.CM_id and\n\t\t\t\tpony.id=pony_CM.pony_id and\n\t\t\t\tpony.id=%d ''' % i)\n\t\t\tfor ID, name, filename in CM_list:\n\t\t\t\tif name in Cutie_mark.CM_name :\n\t\t\t\t\tcontinue\n\t\t\t\tCutie_mark.add_CM(ID, name, filename)\n\n\t@staticmethod\n\tdef init():\n\t\tGlobal.load_const(Local, \"CM_board\")\n\nLocal.init()\n\nclass Cutie_mark(object):\n\tCM_len=0\n\tCM_ID=[]\n\tCM_name=[]\n\tCM_pic=[]\n\n\t@classmethod\n\tdef end(cls):\n\t\tcls.CM_len=0\n\t\tcls.CM_ID=[]\n\t\tcls.CM_name=[]\n\t\tcls.CM_pic=[]\n\n\t@staticmethod\n\tdef CM_pos_to_screen_pos(pos):\n\t\tx, y=pos\n\t\tx*=Local.CM_size[0]\n\t\ty*=Local.CM_size[1]\n\t\tx+=Local.left_top_point[0]\n\t\ty+=Local.left_top_point[1]\n\t\treturn (x, y)\n\n\t@staticmethod\n\tdef CM_pos_to_screen_pos_middle(pos):\n\t\tx, y=CM_pos_to_screen_pos(pos)\n\t\tx+=Local.CM_size[0]/2\n\t\ty+=Local.CM_size[0]/2\n\t\treturn (x, y)\n\n\t@staticmethod\n\tdef screen_pos_to_CM_pos(pos):\n\t\tx, y = pos\n\t\tx-=Local.left_top_point[0]\n\t\ty-=Local.left_top_point[1]\n\t\tpx=x/Local.CM_size[0]\n\t\tpy=y/Local.CM_size[1]\n\t\tif px<0 or px > Local.board_size[0]-1 :\n\t\t\treturn (-1, -1)\n\t\tif py<0 or py > Local.board_size[1]-1 :\n\t\t\treturn (-1, -1)\n\t\treturn (px, py)\n\n\t@classmethod\n\tdef add_CM(cls, ID, name, filename):\n\t\tpic=pygame.image.load(filename).convert()\n\t\tpic=pygame.transform.scale(pic, Local.CM_size)\n\t\tpic.set_colorkey(Local.mask)\n\t\tcls.CM_ID.append(ID)\n\t\tcls.CM_name.append(name)\n\t\tcls.CM_pic.append(pic)\n\t\tcls.CM_len+=1\n\n\tdef draw(self):\n\t\tif self.index < 0 :\n\t\t\treturn\n\t\tif self.count==0 :\n\t\t\tpos=self.screen_pos2\n\t\t\tGlobal.screen.blit(self.CM_pic[self.index],pos)\n\t\telse :\n\t\t\tx1, y1=self.screen_pos1\n\t\t\tx2, y2=self.screen_pos2\n\t\t\ta=self.count_max - self.count\n\t\t\tb=self.count_max\n\t\t\tx=(x2-x1)*a/b+x1\n\t\t\ty=(y2-y1)*a/b+y1\n\t\t\tpos=(x, y)\n\t\t\tindex=self.index\n\t\t\tGlobal.screen.blit(self.CM_pic[index],pos)\n\n\tdef move_from(self, pos, counter):\n\t\tself.pos1=pos\n\t\tself.screen_pos1=self.CM_pos_to_screen_pos(pos)\n\t\tself.count=counter\n\t\tself.count_max=counter\n\n\tdef tick(self):\n\t\tif self.count :\n\t\t\tself.count-=1\n\t\t\treturn False\n\t\treturn True\n\n\tdef done(self):\n\t\treturn self.count == 0\n\n\tdef __init__(self, pos, index):\n\t\tself.pos2=pos\n\t\tself.screen_pos2=self.CM_pos_to_screen_pos(pos)\n\t\tself.count=0\n\t\tself.index=index\n\nclass Holding_CM(Cutie_mark):\n\t@classmethod\n\tdef start(cls):\n\t\tcls.pos=(-1, -1)\n\t\tcls.index=-1\n\n\t@classmethod\n\tdef hold(cls, pos, index):\n\t\tcls.pos=pos\n\t\tcls.index=index\n\n\t@classmethod\n\tdef release(cls):\n\t\tcls.pos=(-1, -1)\n\t\tcls.index=-1\n\n\t@classmethod\n\tdef move(cls, pos):\n\t\tcls.pos=pos\n\n\t@classmethod\n\tdef tick(cls):\n\t\treturn True\n\n\t@classmethod\n\tdef draw(cls):\n\t\tif cls.index < 0 :\n\t\t\treturn\n\t\tx, y=pygame.mouse.get_pos()\n\t\tGlobal.screen.blit(cls.CM_pic[cls.index],\n\t\t\t[x-Local.CM_size[0]/2,\n\t\t\ty-Local.CM_size[1]/2])\n\nclass CM_board(object):\n\tWAITING=0 #waiting for player move the cutie mark\n\tHOLDING=1 #player is holding the cutie mark\n\tELIMINATING=2 #eliminating cutie mark\n\tFALLING=3 #cutie mark falling\n\tLOCKED=4\n\tWAITING_TO_BE_UNLOCKED=5\n\tboard=[[Cutie_mark((x, y),0) for y in range(0, 5)]\n\t\t\tfor x in range(0, 6)]\n\n\t@classmethod\n\tdef start(cls, pony_list):\n\t\tcls.mode=cls.WAITING_TO_BE_UNLOCKED\n\t\tcls.first_time_eliminate=False\n\t\tcls.count=0\n\t\tHolding_CM.start()\n\t\tLocal.load_CM(pony_list)\n\t\tcls.gen_board()\n\n\t@staticmethod\n\tdef end():\n\t\tCutie_mark.end()\n\n\t@classmethod\n\tdef change_mode(cls, mode):\n\t\tif mode == cls.ELIMINATING :\n\t\t\tcls.first_time_eliminate=True\n\t\telif mode == cls.WAITING_TO_BE_UNLOCKED :\n\t\t\tBattle.notify_done()\n\t\tcls.mode=mode\n\n\t@classmethod\n\tdef draw(cls):\n\t\tpos=Local.left_top_point\n\t\tGlobal.screen.blit(cls.background, pos)\n\t\tfor column in cls.board :\n\t\t\tfor CM in column :\n\t\t\t\tCM.draw()\n\t\tHolding_CM.draw()\n\n\t@classmethod\n\tdef add_CM(cls, pos, index):\n\t\tx, y=pos\n\t\tcls.board[x][y].index=index\n\n\t@classmethod\n\tdef add_moving(cls, pos1, pos2, index, counter):\n\t\tx, y=pos2\n\t\tcls.board[x][y].move_from(pos1, counter)\n\t\tcls.board[x][y].index=index\n\n\t@classmethod\n\tdef unlock(cls):\n\t\tcls.change_mode(cls.WAITING)\n\n\t@classmethod\n\tdef check(cls, x, y, index=None, board=None):\n\t\t#outside of the board\n\t\tif x<0 or x>=Local.board_size[0] :\n\t\t\treturn 0\n\t\tif y<0 or y>=Local.board_size[1] :\n\t\t\treturn 0\n\t\t#index is different\n\t\tif index!=None and index != cls.board[x][y].index :\n\t\t\treturn 0\n\t\t#first call, index is the same as the board\n\t\tif index==None :\n\t\t\tindex=cls.board[x][y].index\n\t\t\tif index == -1 :\n\t\t\t\treturn 0\n\t\tif board==None :\n\t\t\tboard=[]\n\t\t\tfor ax in range(0, Local.board_size[0]):\n\t\t\t\ty_row=[]\n\t\t\t\tfor ay in range(0, Local.board_size[1]):\n\t\t\t\t\ty_row.append(0)\n\t\t\t\tboard.append(y_row)\n\t\telif board[x][y] == 1 :\n\t\t\treturn 0\n\t\tboard[x][y]=1\n\t\tcount=1\n\t\tcount+=cls.check(x+1, y, index, board)\n\t\tcount+=cls.check(x-1, y, index, board)\n\t\tcount+=cls.check(x, y+1, index, board)\n\t\treturn count\n\n\t@classmethod\n\tdef eliminate(cls, x, y, index=None):\n\t\tif x<0 or x>=Local.board_size[0] :\n\t\t\treturn 0\n\t\tif y>=Local.board_size[1] :\n\t\t\treturn 0\n\t\tif index!=None and index != cls.board[x][y].index :\n\t\t\treturn 0\n\t\tif index==None :\n\t\t\tindex=cls.board[x][y].index\n\t\tcls.board[x][y].index=-1\n\t\tpoint=Local.point\n\t\tname=Cutie_mark.CM_name[index]\n\t\tBezier_curve.CM_to_pony((x, y), name, point)\n\t\tcls.eliminate(x+1, y, index)\n\t\tcls.eliminate(x-1, y, index)\n\t\tcls.eliminate(x, y+1, index)\n\n\t@classmethod\n\tdef eliminate_mode(cls):\n\t\tfor y in range(0, Local.board_size[1]):\n\t\t\tfor x in range(0, Local.board_size[0]):\n\t\t\t\tcount=cls.check(x, y)\n\t\t\t\tif count>=Local.eliminate_threshold :\n\t\t\t\t\tcls.eliminate(x, y)\n\t\t\t\t\tcls.first_time_eliminate=False\n\t\t\t\t\tcls.count=Local.eliminate_count\n\t\t\t\t\tCombo.add_combo(1)\n\t\t\t\t\treturn\n\t\tif cls.first_time_eliminate :\n\t\t\tcls.change_mode(cls.LOCKED)\n\t\telse:\n\t\t\tcls.change_mode(cls.FALLING)\n\n\t@classmethod\n\tdef fall(cls, x, y):\n\t\tup_y=y-1\n\t\twhile up_y >= 0 :\n\t\t\tif cls.board[x][up_y].index > -1 :\n\t\t\t\tcls.add_moving((x, up_y),(x, y),\n\t\t\t\t\tcls.board[x][up_y].index,\n\t\t\t\t\tLocal.fall_count)\n\t\t\t\tcls.board[x][up_y].index=-1\n\t\t\t\treturn\n\t\t\tup_y-=1\n\t\tindex=random.randint(0, Cutie_mark.CM_len-1)\n\t\tcls.add_moving((x, -1), (x, y), index, Local.fall_count)\n\n\t@classmethod\n\tdef fall_mode(cls):\n\t\tfor y in range(Local.board_size[1]-1, -1, -1):\n\t\t\tfor x in range(Local.board_size[0]-1, -1, -1):\n\t\t\t\tif cls.board[x][y].index == -1 :\n\t\t\t\t\tcls.fall(x, y)\n\t\tcls.change_mode(cls.ELIMINATING)\n\n\t@classmethod\n\tdef release(cls):\n\t\tif cls.mode != cls.HOLDING :\n\t\t\treturn False\n\t\tcls.change_mode(cls.ELIMINATING)\n\t\tx, y=Holding_CM.pos\n\t\tcls.add_CM((x, y), Holding_CM.index)\n\t\tHolding_CM.release()\n\t\tHP_bar.hp_mode()\n\n\t@classmethod\n\tdef move(cls, pos):\n\t\tif cls.mode != cls.HOLDING :\n\t\t\treturn\n\t\tif pos == (-1, -1) :\n\t\t\tcls.release()\n\t\t\treturn\n\t\tif Holding_CM.pos==pos :\n\t\t\treturn\n\t\thx, hy=Holding_CM.pos\n\t\tnx, ny=pos\n\t\tindex=cls.board[hx][hy].index\n\t\tcls.add_moving((nx, ny), (hx, hy),\n\t\t\tcls.board[nx][ny].index, Local.moving_count)\n\t\tcls.board[nx][ny].index=-1\n\t\tHolding_CM.move(pos)\n\n\t@classmethod\n\tdef hold(cls, pos):\n\t\tif cls.mode != cls.WAITING :\n\t\t\treturn False\n\t\tif pos == (-1, -1) :\n\t\t\treturn False\n\t\tx, y=pos\n\t\tHP_bar.time_mode(Local.motion_time)\n\t\tcls.change_mode(cls.HOLDING)\n\t\tHolding_CM.hold((x, y), cls.board[x][y].index)\n\t\tcls.board[x][y].index=-1\n\t\treturn True\n\n\t@classmethod\n\tdef tick(cls):\n\t\tif cls.mode==cls.HOLDING:\n\t\t\tif HP_bar.time_up() :\n\t\t\t\tcls.release()\n\t\tif cls.count :\n\t\t\tcls.count-=1\n\t\t\tdone=False\n\t\telse :\n\t\t\tdone=True\n\t\tfor column in cls.board :\n\t\t\tfor CM in column :\n\t\t\t\tdone&=CM.tick()\n\t\tdone&=Holding_CM.tick()\n\t\tif not done :\n\t\t\treturn\n\t\tif cls.mode==cls.LOCKED :\n\t\t\tif Bezier_curve.animation_done() :\n\t\t\t\tcls.change_mode(cls.WAITING_TO_BE_UNLOCKED)\n\t\tif cls.mode==cls.ELIMINATING:\n\t\t\tcls.eliminate_mode()\n\t\telif cls.mode==cls.FALLING:\n\t\t\tcls.fall_mode()\n\n\t@classmethod\n\tdef gen_board(cls):\n\t\tCM_len=Cutie_mark.CM_len-1\n\t\tfor x in range(0, Local.board_size[0]):\n\t\t\tfor y in range(0, Local.board_size[1]):\n\t\t\t\tCM=random.randint(0, CM_len)\n\t\t\t\tcls.add_moving((x, -1),(x, y), CM,\n\t\t\t\t\tLocal.fall_count)\n\nstart=CM_board.start\nend=CM_board.end\ndraw=CM_board.draw\ntick=CM_board.tick\nmove=CM_board.move\nhold=CM_board.hold\nrelease=CM_board.release\ngen_board=CM_board.gen_board\nunlock=CM_board.unlock\nscreen_pos_to_CM_pos=Cutie_mark.screen_pos_to_CM_pos\nCM_pos_to_screen_pos_middle=Cutie_mark.CM_pos_to_screen_pos_middle\nCM_pos_to_screen_pos=Cutie_mark.CM_pos_to_screen_pos\n","sub_path":"bin/CM_board.py","file_name":"CM_board.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"518160255","text":"\"\"\"practiceme URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,include\n#from django.conf.urls import path\nfrom django.conf import settings\nfrom appatt.views import ( index, user_login, user_logout,\n success, ProfileUpdate, MyProfile)\n\n#from apphi.views import Product_Createview\nurlpatterns = [\n\n path('admin/', admin.site.urls),\n #path('we/', views.Product_Createview.as_view()),\n #product('go/', views.Product_Formview.as_view()),\n path('employee/', include('appatt.urls')),\n path('login/', user_login, name=\"user_login\"),\n path('success/', success, name=\"user_success\"),\n path('logout/', user_logout, name=\"user_logout\"),\n path('profile/', MyProfile.as_view(), name=\"my_profile\"),\n path('profile/update', ProfileUpdate.as_view(), name=\"update_profile\"),\n \n\n\n\n\n\n\n\n\n\n ]","sub_path":"practiceme/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213504994","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This script is used to synthesize generated parts of this library.\"\"\"\n\nimport re\n\nimport synthtool as s\nfrom synthtool import gcp\nfrom synthtool.languages import python\n\ngapic = gcp.GAPICBazel()\ncommon = gcp.CommonTemplates()\nversions = [\"v1beta1\", \"v1\"]\n\n\n# ----------------------------------------------------------------------------\n# Generate automl GAPIC layer\n# ----------------------------------------------------------------------------\nfor version in versions:\n library = gapic.py_library(\n service=\"automl\",\n version=version,\n bazel_target=f\"//google/cloud/automl/{version}:automl-{version}-py\",\n include_protos=True\n )\n\n\n s.move(library, excludes=[\"README.rst\", \"docs/index.rst\", \"setup.py\", \"*.tar.gz\"])\n\n# Add TablesClient and GcsClient to v1beta1\ns.replace(\nf\"google/cloud/automl_v1beta1/__init__.py\",\n\"\"\"from \\.services\\.auto_ml import AutoMlClient\nfrom \\.services\\.prediction_service import PredictionServiceClient\"\"\",\n\"\"\"from .services.auto_ml import AutoMlClient\nfrom .services.prediction_service import PredictionServiceClient\nfrom .services.tables.gcs_client import GcsClient\nfrom .services.tables.tables_client import TablesClient\"\"\"\n)\n\ns.replace(\n f\"google/cloud/automl_v1beta1/__init__.py\",\n f\"\"\"__all__ = \\(\"\"\",\n \"\"\"__all__ = (\"GcsClient\", \"TablesClient\",\"\"\"\n)\n\ns.replace(\n \"docs/automl_v1beta1/services.rst\",\n \"\"\"(google\\.cloud\\.automl_v1beta1\\.services\\.prediction_service\n :members:\n :inherited-members:)\"\"\",\n \"\"\"\\g<1>\\n.. automodule:: google.cloud.automl_v1beta1.services.tables\n :members:\n :inherited-members:\"\"\"\n)\n\n# ----------------------------------------------------------------------------\n# Add templated files\n# ----------------------------------------------------------------------------\ntemplated_files = common.py_library(\n unit_cov_level=82, cov_level=83, samples=True, microgenerator=True,\n unit_test_extras=[\"pandas\", \"storage\"],\n system_test_extras=[\"pandas\", \"storage\"]\n)\n\npython.py_samples(skip_readmes=True)\n\ns.move(templated_files)\n\n# TODO(busunkim): Use latest sphinx after microgenerator transition\ns.replace(\"noxfile.py\", \"\"\"['\"]sphinx['\"]\"\"\", '\"sphinx<3.0.0\"')\n# TODO(busunkim): Remove after microgenerator transition.\n# This is being added to AutoML because the proto comments are long and\n# regex replaces are a brittle temporary solution.\ns.replace(\n\"noxfile.py\",\n\"\"\"'-W', # warnings as errors\n\\s+'-T', \\# show full traceback on exception\"\"\",\n\"\"\"\"-T\", # show full traceback on exception\"\"\")\n\n\n# install with extras (pandas, storage)\ns.replace(\n \"noxfile.py\",\n \"\"\"session\\.install\\(['\"]-e['\"], ['\"]\\.['\"]\\)\"\"\",\n \"\"\"session.install(\"-e\", \".[pandas,storage]\")\"\"\",\n)\n\ns.shell.run([\"nox\", \"-s\", \"blacken\"], hide_output=False)\n","sub_path":"synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":3341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286996367","text":"import arcpy, os\nFC_Frontage_Roads = arcpy.GetParameterAsText(0)\nFC_Centerlines = arcpy.GetParameterAsText(1)\nRouted_SubFiles = arcpy.GetParameterAsText(2)\nDistrict_Boundaries = arcpy.GetParameterAsText(3)\nMPO_Boundaries = arcpy.GetParameterAsText(4)\noutputFolder = arcpy.GetParameterAsText(5)\nscracthSpace = outputFolder + os.sep + \"scratchSpace\" + os.sep\n\nif not os.path.exists(scracthSpace):\n\tos.makedirs(scracthSpace)\n\ninputs_to_merge = [Routed_SubFiles, FC_Centerlines, FC_Frontage_Roads]\nFC_roadways_merged = scracthSpace + \"temp_FC_roadways_merged.shp\"\nDistrict_Boundaries_w_o_MPO = scracthSpace + \"temp_District_Boundaries_w_o_MPO.shp\"\n\n\nintersect_features1 = [FC_roadways_merged, MPO_Boundaries]\nFC_roads_by_MP0 = scracthSpace + \"temp_FC_roads_by_MPO.shp\"\n\nintersect_features2 = [FC_roadways_merged, District_Boundaries_w_o_MPO]\nFC_roads_by_District = scracthSpace + \"temp_FC_roads_by_District.shp\"\n\nFinal_FC_Roads_by_MPO = outputFolder + os.sep + \"FC_Roads_by_MPO.shp\"\nFinal_FC_Roads_by_Districts = outputFolder + os.sep + \"FC_Roads_by_Districts.shp\"\n\narcpy.SetProgressor(\"step\", \"Merging... Please Wait (this can take a while)\", 0,9,1)\narcpy.AddMessage(\"Merging Datasets:\\n%s\\n%s\\n%s\" % (inputs_to_merge[0],inputs_to_merge[1],inputs_to_merge[2]))\narcpy.Merge_management(inputs_to_merge, FC_roadways_merged)\narcpy.AddMessage(\"File Created: %s\\n\" % FC_roadways_merged)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Erase Analysis...\") \narcpy.AddMessage(\"Creating Distrct Bounadries without MPOs\")\narcpy.Erase_analysis(District_Boundaries, MPO_Boundaries, District_Boundaries_w_o_MPO )\narcpy.AddMessage(\"File Created: %s\\n\" % District_Boundaries_w_o_MPO )\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Intersect Analysis...\") \narcpy.AddMessage(\"Intersecting... %s\\nby... %s\" % (intersect_features1[0], intersect_features1[1]))\narcpy.Intersect_analysis(intersect_features1, FC_roads_by_MPO, \"ALL\", \"\", \"LINE\")\narcpy.AddMessage(\"File Created: %s\\n\" % FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Intersect Analysis...\") \narcpy.AddMessage(\"Intersecting... %s\\nby... %s\" % (intersect_features2[0], intersect_features2[1]))\narcpy.Intersect_analysis(intersect_features2, FC_roads_by_District, \"ALL\", \"\", \"LINE\")\narcpy.AddMessage(\"File Created: %s\\n\" % FC_roads_by_District)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Dissolving by MPO...\") \narcpy.AddMessage(\"Dissolving... %s\\nby... FUNCL_2008 and MPO_LBL\" % FC_roads_by_MP0)\narcpy.Dissolve_management(FC_roads_by_MP0, Final_FC_Roads_by_MPO, \"FUNCL_2008;MPO_LBL\", \"\", \"MULTI_PART\", \"DISSOLVE_LINES\")\narcpy.AddMessage(\"File Created: %s\\n\" % Final_FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Dissolving by District...\") \narcpy.AddMessage(\"Dissolving... %s\\nby... FUNCL_2008 and DIST_NM\" % FC_roads_by_District)\narcpy.Dissolve_management(FC_roads_by_District, Final_FC_Roads_by_Districts, \"FUNCL_2008;DIST_NM\", \"\", \"MULTI_PART\", \"DISSOLVE_LINES\")\narcpy.AddMessage(\"File Created: %s\\n\" % Final_FC_Roads_by_Districts)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Adding Field...\")\narcpy.AddMessage(\"Adding Field TTL_MILES to %s...\" % Final_FC_Roads_by_MPO)\narcpy.AddField_management(Final_FC_Roads_by_MPO, \"TTL_MILES\", \"FLOAT\", \"9\", \"4\", \"\", \"\", \"NON_NULLABLE\", \"NON_REQUIRED\")\narcpy.AddMessage(\"Field add complete\\n\")\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Adding Field...\")\narcpy.AddMessage(\"Adding Field TTL_MILES to %s...\" % Final_FC_Roads_by_Districts)\narcpy.AddField_management(Final_FC_Roads_by_Districts, \"TTL_MILES\", \"FLOAT\", \"9\", \"4\", \"\", \"\", \"NON_NULLABLE\", \"NON_REQUIRED\")\narcpy.AddMessage(\"Field add complete\\n\")\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Calculating Field...\")\narcpy.AddMessage(\"Calculating Total Length in Miles for field TTL_MILES in\\n%s\" % Final_FC_Roads_by_MPO)\narcpy.CalculateField_management(Final_FC_Roads_by_MPO, \"TTL_MILES\", \"!shape.length@miles!\", \"PYTHON_9.3\")\narcpy.AddMessage(\"%s - Done!\\n\" % Final_FC_Roads_by_MPO)\narcpy.SetProgressorPosition()\n\narcpy.SetProgressorLabel(\"Calculating Field...\")\narcpy.AddMessage(\"Calculating Total Length in Miles for field TTL_MILES in\\n%s\" % Final_FC_Roads_by_Districts)\narcpy.CalculateField_management(Final_FC_Roads_by_Districts, \"TTL_MILES\", \"!shape.length@miles!\", \"PYTHON_9.3\")\narcpy.AddMessage(\"%s - Done!\\n\" % Final_FC_Roads_by_Districts)\narcpy.ResetProgressor()","sub_path":"standalone/Mileage By Functional Class.py","file_name":"Mileage By Functional Class.py","file_ext":"py","file_size_in_byte":4435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325097476","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom itertools import combinations\nfrom collections import deque\n\nclass BatchGenerator(object):\n\n def __init__(self, batch_size, data):\n self.batch_size = batch_size\n self.data = data\n self.ix = 0\n self.buffer = deque([])\n self._finish = False\n\n def next(self):\n if self._finish:\n return 'No data!'\n\n while len(self.buffer) < self.batch_size:\n items_list = self.data[self.ix]\n self.buffer.extend(combinations(items_list, 2))\n\n if self.ix == len(self.data) - 1:\n self._finish = True\n self.ix = 0\n else:\n self.ix += 1\n d = [self.buffer.popleft() for _ in range(self.batch_size)]\n\n d = np.array([[i[0], i[1]] for i in d])\n batch = d[:, 0]\n labels = d[:, 1]\n\n return batch, labels\n\n @property\n def finish(self):\n return self._finish\n\n def resume(self):\n\n self.ix = 0\n self._finish = False\n\n @property\n def current_percentage(self):\n return (self.ix / self.data.shape[0]) * 100\n\nclass Item2Vec(object):\n def __init__(self, processor, embedding_size, num_negatives, learning_rate, batch_size, epochs=10, step=0, save_path=None):\n self.vocab_size = len(processor.item_list)\n self.embed_dim = embedding_size\n self.num_negatives = num_negatives\n self.learning_rate = learning_rate\n self.batch_size = batch_size\n self.epochs = epochs\n self.save_path = save_path\n self.step = step\n\n self.item_counts = processor.item_counts\n self.train_loss = []\n\n self._init_graphs()\n\n def _init_graphs(self):\n self.graph = tf.Graph()\n with self.graph.as_default():\n self.batch = tf.placeholder(dtype=tf.int32, shape=[self.batch_size])\n self.labels = tf.placeholder(dtype=tf.int32, shape=[self.batch_size])\n true_logits, sampled_logits = self.forward(self.batch, self.labels)\n self.loss = self.nce_loss(true_logits, sampled_logits)\n self.train_op = self.optimize(self.loss)\n\n self.saver = tf.train.Saver()\n init = tf.global_variables_initializer()\n self.sess = tf.Session()\n self.sess.run(init)\n\n def forward(self, batch, labels):\n\n init_width = 0.5 / self.embed_dim\n embed = tf.Variable(tf.random_uniform([self.vocab_size, self.embed_dim], -init_width, init_width), name='word_embedding')\n self.embed = embed\n\n softmax_w = tf.Variable(tf.zeros([self.vocab_size, self.embed_dim]), name=\"softmax_weights\")\n softmax_b = tf.Variable(tf.zeros([self.vocab_size]), name=\"softmax_bias\")\n\n labels_matrix = tf.reshape(tf.cast(labels, dtype=tf.int64), [self.batch_size, 1])\n\n # Negative sampling\n sampled_ids, _, _ = tf.nn.fixed_unigram_candidate_sampler(\n true_classes=labels_matrix,\n num_true=1,\n num_sampled=self.num_negatives,\n unique=True,\n range_max=self.vocab_size,\n distortion=0.75,\n unigrams=self.item_counts)\n\n # Embeddings for examples: [batch_size, embed_dim]\n example_emb = tf.nn.embedding_lookup(embed, batch)\n\n # Weights for labels: [batch_size, embed_dim]\n true_w = tf.nn.embedding_lookup(softmax_w, labels)\n # Biases for labels: [batch_size, 1]\n true_b = tf.nn.embedding_lookup(softmax_b, labels)\n\n # Weights for sampled ids: [batch_size, embed_dim]\n sampled_w = tf.nn.embedding_lookup(softmax_w, sampled_ids)\n # Biases for sampled ids: [batch_size, 1]\n sampled_b = tf.nn.embedding_lookup(softmax_b, sampled_ids)\n\n # True logits: [batch_size, 1]\n true_logits = tf.reduce_sum(tf.multiply(example_emb, true_w), 1) + true_b\n\n # Sampled logits: [batch_size, num_sampled]\n sampled_b_vec = tf.reshape(sampled_b, [self.num_negatives])\n sampled_logits = tf.matmul(example_emb, sampled_w, transpose_b=True) + sampled_b_vec\n\n return true_logits, sampled_logits\n\n def nce_loss(self, true_logits, sampled_logits):\n true_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.ones_like(true_logits), logits=true_logits)\n\n sampled_xent = tf.nn.sigmoid_cross_entropy_with_logits(\n labels=tf.zeros_like(sampled_logits), logits=sampled_logits)\n\n nce_loss_tensor = (tf.reduce_sum(true_xent) +\n tf.reduce_sum(sampled_xent)) / self.batch_size\n\n return nce_loss_tensor\n\n def optimize(self, loss):\n optimizer = tf.train.GradientDescentOptimizer(self.learning_rate)\n train_op = optimizer.minimize(loss)\n\n return train_op\n\n @property\n def embeddings(self):\n return self.embed.eval(session=self.sess)\n\n def get_factors(self, embeddings, item_index_data):\n embedding_size = embeddings.shape[1]\n\n factors = []\n\n for i in item_index_data:\n if len(i) == 0:\n factors.append(list(np.full(embedding_size, 0)))\n else:\n factors.append(list(np.mean(embeddings[i], axis=0)))\n\n return np.array(factors)\n\n def get_norms(self, e):\n norms = np.linalg.norm(e, axis=-1)\n norms[norms == 0] = 1e-10\n return norms\n\n def calu_similar(self, embeddings, queryid, norms, N):\n scores = embeddings.dot(embeddings[queryid]) / norms\n best = np.argpartition(scores, -N)[-N:]\n return sorted(zip(best, scores[best] / norms[queryid]), key=lambda x: -x[1])\n\n def similar_items(self, embeddings, item_index_data, queyid, N=10):\n\n e = self.get_factors(embeddings, item_index_data)\n norms = self.get_norms(e)\n result = []\n for index, score in self.calu_similar(e, queyid, norms, N):\n result.append((index, score))\n\n return result\n\n def fit(self, item_index_data):\n avg_loss = 0\n\n for epoch in range(self.epochs):\n print(\"epoch: {}\".format(epoch))\n generator = BatchGenerator(self.batch_size, item_index_data)\n loss_list = []\n while not generator.finish:\n batch, labels = generator.next()\n feed_dict = {self.batch: batch, self.labels: labels}\n _, loss = self.sess.run([self.train_op, self.loss], feed_dict=feed_dict)\n\n loss_list.append(loss)\n self.step += 1\n print(\"step: {}, loss: {:.9f}\".format(self.step, loss))\n self.train_loss.append(np.mean(loss_list))\n self.embed = self.embeddings\n\n def predict(self, item_index_data, queyid, top_N=10):\n \"\"\"\"\"\"\n return self.similar_items(self.embed, item_index_data, queyid, N=top_N)\n\n\nif __name__ == '__main__':\n from item2vec.utils.movie_process import MovieProcessor\n config = {\n \"embedding_size\": 8,\n \"num_negatives\": 30,\n \"learning_rate\": 0.5,\n \"batch_size\": 64,\n \"epochs\": 50,\n \"step\": 0,\n \"save_path\": \"result/\",\n }\n processor = MovieProcessor()\n config['processor'] = processor\n model = Item2Vec(**config)\n model.fit(processor.item_index_data)\n result = model.predict(processor.item_index_data, 10)\n xs = np.arange(1, config['epochs'] + 1)\n plt.plot(xs, model.train_loss, color='red', linestyle=\"solid\", marker=\"o\")\n\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"loss\")\n plt.title(\"item2vec\")\n plt.legend(['train-loss'])\n plt.show()\n print(result)\n # generator = BatchGenerator(32, processor.item_index_data)\n # while not generator.finish:\n # batch, labels = generator.next()\n # print(batch, labels)\n","sub_path":"src/item2vec/movie_item2vec.py","file_name":"movie_item2vec.py","file_ext":"py","file_size_in_byte":7869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153131082","text":"import falcon\nfrom tasks import app, long_task\nfrom celery.result import AsyncResult\n\n\nclass QuoteResource:\n def on_get(self, req, resp):\n \"\"\"Handles GET requests\"\"\"\n quote = {\n 'quote': (\n \"I've always been more interested in \"\n \"the future than in the past.\"\n ),\n 'author': 'Grace Hopper - Alejandro'\n }\n resp.media = quote\n\n\nclass TaskResource:\n def on_get(self, req, res):\n t = long_task.delay(2, 3)\n res.status = falcon.HTTP_200\n res.media = {'task_id': t.id}\n\n\nclass TaskStatus:\n def on_get(self, req, res, task_id):\n task_result = AsyncResult(task_id)\n result = {\n 'status': task_result.status,\n 'result': task_result.result\n }\n res.status = falcon.HTTP_200\n res.media = result\n\n\nclass TasksResource:\n def on_get(self, req, res):\n # http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#inspecting-workers\n curr = app.control.inspect(['celery@fsociety-ubuntu'])\n res.status = falcon.HTTP_200\n res.media = curr.active()\n\n\napi = falcon.API()\napi.add_route('/quote', QuoteResource())\napi.add_route('/start', TaskResource())\napi.add_route('/task/{task_id}/status', TaskStatus())\napi.add_route('/tasks', TasksResource())\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"500387359","text":"from django.shortcuts import render , get_object_or_404\nfrom operator import itemgetter\nimport requests\nimport json\nimport adal\nfrom django.http import JsonResponse\nfrom django.core.paginator import Paginator\n\n\n#Function to extract patient data based on id,all patients\npid=\"\"\nTOKEN=\"\"\nencounter_id=\"\"\nobservation_id=\"\"\nurl=\"\"\nResource=\"\"\ndef home(request):\n # oauth 2.0 --FHIR SERVER AUTHORIZATION\n # Opening JSON file\n f = open('app/credentials.json')\n data = json.load(f)\n TENANT_ID = data.get('TENANT_ID')\n CLIENT = data.get('CLIENT_ID')\n KEY = data.get('CLIENT_SECRET')\n authority_url = 'https://login.microsoftonline.com/' + TENANT_ID\n global Resource\n Resource=data.get('RESOURCE_ID')\n context = adal.AuthenticationContext(authority_url)\n global token\n token = context.acquire_token_with_client_credentials(\n resource=Resource,\n client_id=CLIENT,\n client_secret=KEY)\n global TOKEN\n TOKEN = token[\"accessToken\"]\n\n # Get Patient by id\n if request.method == \"POST\":\n lst = []\n global pid\n pid = request.POST.get('ID', '')\n url = Resource+\"/Patient/{}\".format(pid)\n newHeaders = {'Content-type': 'application/json',\"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n data = response.json()\n if response.ok:\n l = []\n resourceType = data['resourceType']\n l.append(resourceType)\n\n id = data['id']\n l.append(id)\n\n try:\n birth = data['birthDate']\n except:\n birth = \"No data available\"\n l.append(birth)\n\n try:\n gender = data['gender']\n except:\n gender = \"No data available\"\n l.append(gender)\n\n try:\n name = data['name'][0]['family']\n except:\n name = \"No data available\"\n l.append(name)\n\n try:\n address = data['address'][0]['city']\n except:\n address = \"No data available\"\n l.append(address)\n lst.append(l)\n param = {'param': lst,\"id\":pid}\n return render(request, 'app/home.html', param)\n #all patients\n elif request.method == 'GET':\n url = Resource+\"/Patient?_count=20\"\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders, verify=False)\n data = response.json()\n lst = []\n # next_pge_url = response.json()['link'][0].get('url')\n key_to_lookup = 'entry'\n if key_to_lookup in data:\n entry = data['entry']\n for all_data in entry:\n l = []\n resourceType = all_data['resource']['resourceType']\n l.append(resourceType)\n\n id = all_data['resource']['id']\n l.append(id)\n\n try:\n birth = all_data['resource']['birthDate']\n except:\n birth = \"No data available\"\n l.append(birth)\n\n try:\n gender = all_data['resource']['gender']\n except:\n gender = \"No data available\"\n l.append(gender)\n\n try:\n name = all_data['resource']['name'][0]['family']\n except:\n name = \"No data available\"\n l.append(name)\n\n try:\n address = all_data['resource']['address'][0]['city']\n except:\n address = \"No data available\"\n l.append(address)\n\n lst.append(l)\n param = {'param':lst}\n return render(request, 'app/home.html', param)\n else:\n l = []\n resourceType =\"No data found\"\n l.append(resourceType)\n\n id = \"No data found\"\n l.append(id)\n\n birth = \"No data found\"\n l.append(birth)\n\n gender = \"No data found\"\n l.append(gender)\n\n name = \"No data found\"\n l.append(name)\n\n address = \"No data found\"\n l.append(address)\n\n lst.append(l)\n param = {'param':lst}\n return render(request, 'app/home.html', param)\n\ndef observation(request):\n lst = []\n id = pid\n if id is None:\n obsparam = {'obsparam': \"No patient id found\"}\n return render(request, 'app/home.html', obsparam)\n else:\n url = Resource+\"/Observation?patient={}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n data = response.json()\n if 'entry' not in data.keys():\n print(\"NO Observation available\")\n else:\n entry = data['entry']\n for all_data in entry:\n l = []\n resourceType = all_data['resource']['resourceType']\n l.append(resourceType)\n\n id = all_data['resource']['id']\n global observation_id\n observation_id = id\n l.append(id)\n\n try:\n reference = all_data['resource']['subject'].get('reference')\n except:\n reference = \"No data available\"\n l.append(reference)\n\n try:\n display = all_data['resource']['code']['coding'][0].get('display')\n except:\n display = \"No data available\"\n l.append(display)\n\n try:\n res = list(map(itemgetter('coding'), all_data['resource']['category']))\n category = res[0][0]['display']\n except:\n category = \"No data available\"\n l.append(category)\n\n try:\n v1 = all_data['resource']['valueQuantity'].get('value')\n v2 = all_data['resource']['valueQuantity'].get('unit')\n value = str(v1) + \" \" + str(v2)\n except:\n value = \"No data available\"\n l.append(value)\n lst.append(l)\n obsparam = {'obsparam': lst,'observation_id':observation_id}\n return render(request, 'app/home.html', obsparam)\n\ndef encounter(request):\n lst = []\n if pid is None:\n obsparam = {'obsparam': \"No patient id found\"}\n return render(request, 'app/home.html', obsparam)\n else:\n url = Resource+\"/Encounter?patient={}\".format(pid)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n data = response.json()\n if 'entry' not in data.keys():\n print(\"NO Encounter available\")\n else:\n entry = data['entry']\n for all_data in entry:\n l = []\n try:\n resourceType = all_data['resource']['resourceType']\n except:\n resourceType = \"No data available\"\n l.append(resourceType)\n\n try:\n id = all_data['resource']['id']\n global encounter_id\n encounter_id=id\n except:\n id = \"No data available\"\n l.append(id)\n\n try:\n priority = all_data['resource']['priority']['coding'][0]['display']\n except:\n priority = \"No data available\"\n l.append(priority)\n\n try:\n reason = list(map(itemgetter('coding'), all_data['resource']['reasonCode']))\n reasonCode = reason[0][0]['display']\n except:\n reasonCode = \"No data available\"\n l.append(reasonCode)\n\n try:\n admitSource = all_data['resource']['hospitalization']['admitSource']['coding'][0]['display']\n except:\n admitSource = \"No data available\"\n l.append(admitSource)\n\n try:\n serviceProvider = all_data['resource']['serviceProvider'].get('reference')\n except:\n serviceProvider = \"No data available\"\n l.append(serviceProvider)\n\n lst.append(l)\n encounter_param = {'encounter_param': lst,'encounter_id':encounter_id}\n return render(request, 'app/home.html', encounter_param)\n\ndef jsonviewPatient(request,id):\n id = str(id)\n url = Resource+\"/Patient/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formatted_patient= json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formatted_patient}\n return JsonResponse(json_data,content_type='application/json')\n\ndef jsonviewObservation(request,id):\n id = str(id)\n url = Resource+\"/Observation/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formated_observation=json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formated_observation}\n # return render(request,'app/jsondata.html',param)\n return JsonResponse(json_data,content_type='application/json')\n\ndef jsonviewEncounter(request,id):\n id = str(id)\n url = Resource+\"/Encounter/{}\".format(id)\n newHeaders = {'Content-type': 'application/json', \"Authorization\": \"Bearer %s\" % TOKEN}\n response = requests.get(url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n # json_formated_encounter=json.dumps(json_data, sort_keys = True, indent = 4)\n # param = {'param':json_formated_encounter}\n # return render(request,'app/jsondata.html',param)\n return JsonResponse(json_data,content_type='application/json')\n\ndef url(request):\n if request.method == \"POST\":\n json_data=''\n url = request.POST.get('URL', '')\n newHeaders = {'Content-type': 'application/json',\"Authorization\": \"Bearer %s\" %TOKEN}\n response = requests.get(Resource+\"/\"+url, headers=newHeaders,verify=False)\n if response.ok:\n json_data = response.json()\n return JsonResponse(json_data,content_type='application/json',safe=False)\n\ndef error_404_view(request,exception):\n return render(request,'app/404.html')\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130376043","text":"# encoding: utf-8\nimport requests, simplejson\nfrom service.ticket.ticket_base_service import TicketBaseService\n\nmcenter_ip = \"10.254.50.54\"\nmcenter_port = \"30042\"\nusername = 'zabbix'\npassword = 'cernet@123'\n\nticket_project_url = 'http://%s:%s/work/ticket-project-count/' % (mcenter_ip, mcenter_port)\nticket_date_url = 'http://%s:%s/work/ticket-date-count/' % (mcenter_ip, mcenter_port)\nticket_list_url = 'http://%s:%s/work/ticketslist/' % (mcenter_ip, mcenter_port)\ntry:\n get_token = requests.post(\n 'http://%s:%s/api-token-auth/' % (mcenter_ip, mcenter_port),\n data={\"username\": username, \"password\": password},\n ).json()\nexcept:\n print(\"Can not connect url:http://%s:%s/api-token-auth/\" % (mcenter_ip, mcenter_port))\n\ntry:\n token = get_token['token']\nexcept:\n print(get_token)\nheaders = {\n 'Authorization': 'JWT ' + token,\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\",\n}\nfield_list, flag = TicketBaseService.get_ticket_base_field_list(ticket_id)\nparams = {}\nfor i in field_list:\n if i['field_key'] == 'start_time':\n params['start_time'] = str(i['field_value'])\n elif i['field_key'] == 'end_time':\n params['end_time'] = str(i['field_value'])\n elif i['field_key'] == 'to_project_id':\n params['to_project'] = str(i['field_value'])\n\nticket_project = requests.get(ticket_project_url, params=params, headers=headers).json()\nticket_date = requests.get(ticket_date_url, params=params, headers=headers).json()\n\npost_data = {\n 'search': [\n {\n 'key': 'gmt_created',\n 'action': 'gte',\n 'value': params['start_time']\n },\n {\n 'key': 'gmt_created',\n 'action': 'lte',\n 'value': params['end_time']\n },\n {\n 'key': 'to_project_id',\n 'action': 'eq',\n 'value': params['to_project']\n },\n ],\n 'page': 1,\n 'page_size': 100000,\n}\nheaders['Content-Type'] = 'application/json'\nticket_mc = requests.post(ticket_list_url, data=simplejson.dumps(post_data), headers=headers).json()\nticket_list = []\nfor i in ticket_mc['results']:\n ticket_list.append({\n 'title': i['title'],\n 'ticket_id': i['ticket_id'],\n 'workflow_name': i['workflow_name'],\n 'creator': i['creator'],\n 'gmt_created': i['gmt_created'].replace('T', ' ')\n })\n\nticket_table_list = {\n 'columns': [\n {\n 'tooltip': True,\n 'title': '标题',\n 'key': 'title',\n 'width': 300,\n 'align': 'left',\n 'sortable': True\n },\n {\n 'title': '工作流名称',\n 'key': 'workflow_name',\n 'align': 'center',\n 'sortable': True\n },\n {\n 'title': '创建人',\n 'key': 'creator',\n 'align': 'center',\n 'sortable': True\n },\n {\n 'title': '创建时间',\n 'key': 'gmt_created',\n 'align': 'center',\n },\n ],\n 'data': ticket_list,\n}\n\nres_list = {\n 'ticket_project': ticket_project,\n 'ticket_date': ticket_date,\n 'ticket_table_list': ticket_table_list\n}\nTicketBaseService.update_ticket_custom_field(ticket_id,{\"report_forms\": str(res_list)})\ntry:\n requests.patch('http://%s:%s/report/changeticketfield/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({'state_name':'结束'}), headers=headers)\n a = requests.patch('http://%s:%s/report/changeticketstate/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({\"state_id\": 10057}), headers=headers).json()\n print(a)\nexcept:\n pass\ntry:\n requests.patch('http://%s:%s/work/changeticketfield/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({'state_name':'结束'}), headers=headers)\n a = requests.patch('http://%s:%s/work/changeticketstate/%s/' % (mcenter_ip, mcenter_port, ticket_id),data=simplejson.dumps({\"state_id\": 10057}), headers=headers).json()\n print(a)\nexcept:\n pass\n\n\n","sub_path":"media/workflow_script/ticket_count.py","file_name":"ticket_count.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534110935","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/autobahntestsuite/case/case2_9.py\n# Compiled at: 2018-12-17 11:51:20\nfrom case import Case\n\nclass Case2_9(Case):\n DESCRIPTION = 'Send unsolicited pong with payload. Send ping with payload. Verify pong for ping is received.'\n EXPECTATION = \"Nothing in reply to own Pong, but Pong with payload echo'ed in reply to Ping. Clean close with normal code.\"\n\n def onOpen(self):\n payload = 'ping payload'\n self.expected[Case.OK] = [('pong', payload)]\n self.expectedClose = {'closedByMe': True, 'closeCode': [self.p.CLOSE_STATUS_CODE_NORMAL], 'requireClean': True}\n self.p.sendFrame(opcode=10, payload='unsolicited pong payload')\n self.p.sendFrame(opcode=9, payload=payload)\n self.p.closeAfter(1)","sub_path":"pycfiles/autobahntestsuite-0.8.1-py2.7/case2_9.py","file_name":"case2_9.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211339348","text":"# -*- coding: utf-8 -*-\n# Copyright 2014-2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom mock import Mock, NonCallableMock\n\nfrom twisted.internet import defer\n\nimport synapse.types\nfrom synapse.api.errors import AuthError, SynapseError\nfrom synapse.handlers.profile import MasterProfileHandler\nfrom synapse.types import UserID\n\nfrom tests import unittest\nfrom tests.utils import setup_test_homeserver\n\n\nclass ProfileHandlers(object):\n def __init__(self, hs):\n self.profile_handler = MasterProfileHandler(hs)\n\n\nclass ProfileTestCase(unittest.TestCase):\n \"\"\" Tests profile management. \"\"\"\n\n @defer.inlineCallbacks\n def setUp(self):\n self.mock_federation = Mock()\n self.mock_registry = Mock()\n\n self.query_handlers = {}\n\n def register_query_handler(query_type, handler):\n self.query_handlers[query_type] = handler\n\n self.mock_registry.register_query_handler = register_query_handler\n\n hs = yield setup_test_homeserver(\n self.addCleanup,\n http_client=None,\n handlers=None,\n resource_for_federation=Mock(),\n federation_client=self.mock_federation,\n federation_server=Mock(),\n federation_registry=self.mock_registry,\n ratelimiter=NonCallableMock(spec_set=[\"can_do_action\"]),\n )\n\n self.ratelimiter = hs.get_ratelimiter()\n self.ratelimiter.can_do_action.return_value = (True, 0)\n\n self.store = hs.get_datastore()\n\n self.frank = UserID.from_string(\"@1234ABCD:test\")\n self.bob = UserID.from_string(\"@4567:test\")\n self.alice = UserID.from_string(\"@alice:remote\")\n\n yield self.store.create_profile(self.frank.localpart)\n\n self.handler = hs.get_profile_handler()\n self.hs = hs\n\n @defer.inlineCallbacks\n def test_get_my_name(self):\n yield self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n\n displayname = yield self.handler.get_displayname(self.frank)\n\n self.assertEquals(\"Frank\", displayname)\n\n @defer.inlineCallbacks\n def test_set_my_name(self):\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n self.assertEquals(\n (\n yield defer.ensureDeferred(\n self.store.get_profile_displayname(self.frank.localpart)\n )\n ),\n \"Frank Jr.\",\n )\n\n # Set displayname again\n yield defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank\"\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_displayname(self.frank.localpart)), \"Frank\",\n )\n\n @defer.inlineCallbacks\n def test_set_my_name_if_disabled(self):\n self.hs.config.enable_set_displayname = False\n\n # Setting displayname for the first time is allowed\n yield self.store.set_profile_displayname(self.frank.localpart, \"Frank\")\n\n self.assertEquals(\n (yield self.store.get_profile_displayname(self.frank.localpart)), \"Frank\",\n )\n\n # Setting displayname a second time is forbidden\n d = defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.frank), \"Frank Jr.\"\n )\n )\n\n yield self.assertFailure(d, SynapseError)\n\n @defer.inlineCallbacks\n def test_set_my_name_noauth(self):\n d = defer.ensureDeferred(\n self.handler.set_displayname(\n self.frank, synapse.types.create_requester(self.bob), \"Frank Jr.\"\n )\n )\n\n yield self.assertFailure(d, AuthError)\n\n @defer.inlineCallbacks\n def test_get_other_name(self):\n self.mock_federation.make_query.return_value = defer.succeed(\n {\"displayname\": \"Alice\"}\n )\n\n displayname = yield self.handler.get_displayname(self.alice)\n\n self.assertEquals(displayname, \"Alice\")\n self.mock_federation.make_query.assert_called_with(\n destination=\"remote\",\n query_type=\"profile\",\n args={\"user_id\": \"@alice:remote\", \"field\": \"displayname\"},\n ignore_backoff=True,\n )\n\n @defer.inlineCallbacks\n def test_incoming_fed_query(self):\n yield self.store.create_profile(\"caroline\")\n yield self.store.set_profile_displayname(\"caroline\", \"Caroline\")\n\n response = yield self.query_handlers[\"profile\"](\n {\"user_id\": \"@caroline:test\", \"field\": \"displayname\"}\n )\n\n self.assertEquals({\"displayname\": \"Caroline\"}, response)\n\n @defer.inlineCallbacks\n def test_get_my_avatar(self):\n yield self.store.set_profile_avatar_url(\n self.frank.localpart, \"http://my.server/me.png\"\n )\n\n avatar_url = yield self.handler.get_avatar_url(self.frank)\n\n self.assertEquals(\"http://my.server/me.png\", avatar_url)\n\n @defer.inlineCallbacks\n def test_set_my_avatar(self):\n yield defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/pic.gif\",\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/pic.gif\",\n )\n\n # Set avatar again\n yield defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/me.png\",\n )\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/me.png\",\n )\n\n @defer.inlineCallbacks\n def test_set_my_avatar_if_disabled(self):\n self.hs.config.enable_set_avatar_url = False\n\n # Setting displayname for the first time is allowed\n yield self.store.set_profile_avatar_url(\n self.frank.localpart, \"http://my.server/me.png\"\n )\n\n self.assertEquals(\n (yield self.store.get_profile_avatar_url(self.frank.localpart)),\n \"http://my.server/me.png\",\n )\n\n # Set avatar a second time is forbidden\n d = defer.ensureDeferred(\n self.handler.set_avatar_url(\n self.frank,\n synapse.types.create_requester(self.frank),\n \"http://my.server/pic.gif\",\n )\n )\n\n yield self.assertFailure(d, SynapseError)\n","sub_path":"tests/handlers/test_profile.py","file_name":"test_profile.py","file_ext":"py","file_size_in_byte":7281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"455642405","text":"#!/ccs/proj/geo112/hzfmer/summit/opt/anaconda3/bin/python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.signal import butter, sosfilt, sosfiltfilt\nfrom scipy.fftpack import fft\nimport os\nfrom filter_BU import filt_B\nfrom read_params import read_params\n\n\nplt.tight_layout()\nrcparams = {'font.size': 16,\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'legend.fontsize': 10,\n 'axes.titlesize': 16,\n 'axes.labelsize': 14,\n 'lines.linewidth': 2}\nplt.rcParams.update(rcparams)\n\n\nargs = read_params()\n\nntskp, wstep = args['NTISKP'], args['WRITE_STEP']\nskip = wstep * ntskp\ndt = args['DT']\nnt = np.int(args['TMAX'] / dt)\nt = np.linspace(0, nt * dt, nt // ntskp)\nnx, ny, nz = args['X'], args['Y'], args['Z']\nbase_x = args['SXRGO'].strip('\\'')\nbase_y = args['SYRGO'].strip('\\'')\nbase_z = args['SZRGO'].strip('\\'')\nout_dir = base_x.strip('/')[0]\nprint(base_x, type(base_x))\n\n\nN = 4\n# np.random.seed()\nix = np.random.randint(nx, size=N)\niy = np.random.randint(ny, size=N)\nvx = np.zeros((N, nt // ntskp))\nfor i in range(1, nt // skip):\n print(\"i=\", i)\n idx = np.arange((i - 1) * wstep, i * wstep)\n v = np.fromfile(base_x + f'{i * skip:07d}', dtype='f').reshape(-1, ny, nx)\n for j in range(N):\n vx[j, idx] = v[:, iy[j], ix[j]]\n\nvx = filt_B(vx, 1 / dt, 0, 1)\nfig, ax = plt.subplots(N, 1, figsize=(6, 6))\nfig.suptitle(f'VX at {N} sites')\nfor j in range(N):\n ax[j].plot(t, vx[j, :], label=f'X={ix[j]}, Y={iy[j]}')\n ax[j].set_ylabel('VX (m/s)')\n ax[j].legend(loc=1)\nax[N - 1].set_xlabel('Time (s)')\nfig.savefig('ssmgrm_rand_sites.png', dpi=300, bbox='tight', pad_inches=0.1)\n\n","sub_path":"LA/gp_rupture_test/LA/gp_rupture_test/scripts/plot_ssmgrm.py","file_name":"plot_ssmgrm.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"401676887","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: N.A.Amjad\n\"\"\"\nfrom neuralFramework.EventData import EventData\nfrom RBMAlgorithm import RBMAlgorithm\nfrom surprise import NormalPredictor\nfrom neuralFramework.Evaluator import Evaluator\n\nimport random\nimport numpy as np\n\ndef LoadEventData():\n ed = EventData()\n print(\"Loading Event ratings...\")\n data = ed.loadEventData()\n # ed.loadEventData() returns the rating dataset\n print(\"\\nComputing event popularity ranks so we can measure novelty later...\")\n rankings = ed.getPopularityRanks()\n # ranking reperesents the popularity ranking \n return (ed, data, rankings)\n\n\ndef TrainModel():\n np.random.seed(0)\n random.seed(0)\n# Load up common data set for the recommender algorithms\n (ed, evaluationData, rankings) = LoadEventData()\n# ed - EventData object\n# evaluateData - rating dataset\n# ranking - Popularity ranking for each event\n\n# Construct an Evaluator to evaluate them\n# Initally creates training set and test set \n evaluator = Evaluator(evaluationData, rankings)\n\n# Just make random recommendations\n Random = NormalPredictor()\n evaluator.AddAlgorithm(Random, \"Random\")\n\n# RBM\n# Just sets the epochs,hidden layer count,Batch Size and etc\n RBM = RBMAlgorithm(epochs=20)\n evaluator.AddAlgorithm(RBM, \"RBM\")\n\n\n# Fight!\n evaluator.Evaluate(True)\n evaluator.FitAndDump()\n \ndef TestModel(algo,testSubject):\n (ed, evaluationData, rankings) = LoadEventData()\n evaluator = Evaluator(evaluationData, rankings)\n evaluator.AddAlgorithm(algo, \"RBM\")\n # evaluator.Evaluate(False)\n recs = evaluator.SampleTopNRecs(ed,algo = algo, testSubject = testSubject)\n return recs\n \n ","sub_path":"Amjad/RBMBakeOff.py","file_name":"RBMBakeOff.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"498779941","text":"\"\"\"\nCollection of TensorFlow gradient functions, wrapped to fit Ivy syntax and signature.\n\"\"\"\n\n# global\nimport tensorflow as _tf\n\n# local\nimport ivy\nfrom ivy.core.container import Container\n\n\ndef variable(x):\n with _tf.device('/' + ivy.dev_str(x).upper()):\n return _tf.Variable(x, trainable=True)\n\n\ndef is_variable(x):\n return isinstance(x, _tf.Variable)\n\n\ndef execute_with_gradients(func, xs):\n with _tf.GradientTape() as tape:\n func_ret = func(xs)\n if isinstance(func_ret, tuple):\n y = func_ret[0]\n rest = func_ret[1:]\n else:\n y = func_ret\n rest = tuple()\n grads = Container(tape.gradient(y, xs))\n return (y, grads, *rest)\n\n\ndef gradient_descent_update(ws, dcdws, lr):\n ws.map(lambda w, key_chain: w.assign(w - (dcdws if key_chain == '' else dcdws.at_key_chain(key_chain)) * lr))\n return ws\n\n\ndef adam_update(ws, dcdws, lr, mw, vw, step, beta1=0.9, beta2=0.999, epsilon=1e-7):\n step = _tf.cast(step, _tf.float32)\n mw = dcdws.map(lambda dcdw, kc: beta1 * mw.at_key_chain(kc) + (1 - beta1) * dcdw)\n dcdws_sqrd = dcdws.map(lambda dcdw, _: dcdw ** 2)\n vw = dcdws_sqrd.map(lambda dcdw_sqrd, kc: beta2 * vw.at_key_chain(kc) + (1 - beta2) * dcdw_sqrd)\n beta1_pow = beta1 ** step\n beta2_pow = beta2 ** step\n alpha = lr * (1 - beta2_pow)**0.5 / (1 - beta1_pow + epsilon)\n ws.map(lambda w, kc: w.assign(w - alpha * mw.at_key_chain(kc) / (vw.at_key_chain(kc) ** 0.5 + epsilon)))\n return ws, mw, vw\n\n\nstop_gradient = _tf.stop_gradient\n","sub_path":"ivy/tensorflow/core/gradients.py","file_name":"gradients.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489598869","text":"\"\"\"\"\nFile for storing various variable and parameters\n\"\"\"\n\n'''Variables and Parameters'''\nHSV_Lower_Threshold = 150\nGaussian_K_Size = 11\nGaussian_Sigma = 0\nMorph_Element_Size = 13\nMedian_K_Size = 3\nCapture_Box_Count = 9\nCapture_Box_Dimension = 20\nCapture_Box_Separation_X = 8\nCapture_Box_Separation_Y = 18\nCapture_Position_X = 500\nCapture_Position_Y = 150\n\n'''Starting Point'''\nCapture_Region_X_Begin = 0.5\n\n'''Ending Point'''\nCapture_Region_Y_End = 0.8\nFinger_Threshold_Lower = 2.0\nFinger_Threshold_Upper = 3.8\n\n'''Factor of Width of Full Frame'''\nRadius_Threshold = 0.04\nFirst_Iteration = True\nFinger_Count_History = [0, 0]\n","sub_path":"src/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41442645","text":"from spacy.tokens import Token, Doc, Span\nfrom medcat.utils.normalizers import TokenNormalizer\nimport spacy\nimport os\n\nclass Pipe(object):\n r''' A wrapper around the standard spacy pipeline.\n\n Args:\n tokenizer (`spacy.tokenizer.Tokenizer`):\n What will be used to split text into tokens, can be anything built as a spacy tokenizer.\n config (`medcat.config.Config`):\n Global config for medcat.\n\n Properties:\n nlp (spacy.language.):\n The base spacy NLP pipeline.\n '''\n def __init__(self, tokenizer, config):\n self.nlp = spacy.load(config.general['spacy_model'], disable=config.general['spacy_disabled_components'])\n if config.preprocessing['stopwords'] is not None:\n self.nlp.Defaults.stop_words = set(config.preprocessing['stopwords'])\n self.nlp.tokenizer = tokenizer(self.nlp)\n\n\n def add_tagger(self, tagger, name, additional_fields=[]):\n r''' Add any kind of a tagger for tokens.\n\n Args:\n tagger (`object/function`):\n Any object/function that takes a spacy doc as an input, does something\n and returns the same doc.\n name (`str`):\n Name for this component in the pipeline.\n additional_fields (`List[str]`):\n Fields to be added to the `_` properties of a token.\n '''\n self.nlp.add_pipe(tagger, name='tag_' + name, first=True)\n # Add custom fields needed for this usecase\n Token.set_extension('to_skip', default=False, force=True)\n\n # Add any additional fields that are required\n for field in additional_fields:\n Token.set_extension(field, default=False, force=True)\n\n\n def add_token_normalizer(self, config, spell_checker=None):\n token_normalizer = TokenNormalizer(spell_checker=spell_checker, config=config)\n self.nlp.add_pipe(token_normalizer, name='token_normalizer', last=True)\n\n # Add custom fields needed for this usecase\n Token.set_extension('norm', default=None, force=True)\n\n\n def add_ner(self, ner):\n r''' Add NER from CAT to the pipeline, will also add the necessary fields\n to the document and Span objects.\n\n '''\n self.nlp.add_pipe(ner, name='cat_ner', last=True)\n\n Doc.set_extension('ents', default=[], force=True)\n Span.set_extension('confidence', default=-1, force=True)\n Span.set_extension('id', default=0, force=True)\n # Do not set this property if a vocabulary apporach is not used, this name must\n #refer to a name2cuis in the cdb.\n Span.set_extension('detected_name', default=None, force=True)\n Span.set_extension('link_candidates', default=None, force=True)\n\n\n def add_linker(self, linker):\n r''' Add entity linker to the pipeline, will also add the necessary fields\n to Span object.\n\n linker (object/function):\n Any object/function created based on the requirements for a spaCy pipeline components. Have\n a look at https://spacy.io/usage/processing-pipelines#custom-components\n '''\n self.nlp.add_pipe(linker, name='cat_linker', last=True)\n Span.set_extension('cui', default=-1, force=True)\n Span.set_extension('context_similarity', default=-1, force=True)\n\n\n def add_meta_cat(self, meta_cat, name):\n self.nlp.add_pipe(meta_cat, name=name, last=True)\n\n # Only the meta_anns field is needed, it will be a dictionary \n #of {category_name: value, ...}\n Span.set_extension('meta_anns', default=None, force=True)\n\n\n def __call__(self, text):\n return self.nlp(text)\n","sub_path":"medcat/pipe.py","file_name":"pipe.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"449737688","text":"#!/usr/bin/python3\n\nclass people:\n a = 123\n __weight = 0 # 定义私有属性\n def __init__(self, realpart, imagpart, w):\n self.r = realpart\n self.i = imagpart\n self.__weight = w\n print(self.__weight)\n def func(self):\n print('r = %.2f and i = %.2f' %(self.r, self.i))\n return 'hello world'\n\nclass stu(people):\n g = ''\n def __init__(self, realpart, imagpart, w, grade):\n #调用父类的构函\n people.__init__(self, realpart, imagpart, w)\n self.g = grade\n #覆写父类的方法\n def func(self):\n print('r = %.2f and i = %.2f and g = %d' %(self.r, self.i, self.g))\n\n# 实例化类\nx = people(2.0, 4.5, 'fuck')\ns = stu(3.0, 2.0, 'you', 5)\n\n# 访问类的属性和方法\nprint(\"people 类的属性 i 为:\", x.a)\nprint(\"people 类的方法 f 输出为:\", x.func())\nprint((x.r), (x.i))\n\nprint((s.r), (s.i), (s.g), (s.a))\ns.func()\n\n#????????????????????????????????????\nclass Vector:\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def __str__(self):\n return 'Vector (%d, %d)' % (self.a, self.b)\n \n def __add__(self, other):\n return Vector(self.a + other.a, self.b + other.b)\n\nv1 = Vector(2,10)\nv2 = Vector(5,-2)\nprint (v1 + v2)\n\n\n","sub_path":"6_class.py","file_name":"6_class.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"459672814","text":"import pandas as pd\nimport pytest\n\n\n@pytest.mark.functions\n@pytest.mark.parametrize(\n \"invert,expected\",\n [\n (False, [\"a\", \"Bell__Chart\", \"cities\"]),\n (True, [\"decorated-elephant\", \"animals@#$%^\"]),\n ],\n)\ndef test_select_columns(dataframe, invert, expected):\n columns = [\"a\", \"Bell__Chart\", \"cities\"]\n df = dataframe.select_columns(search_column_names=columns, invert=invert)\n\n pd.testing.assert_frame_equal(df, dataframe[expected])\n\n\n@pytest.mark.functions\n@pytest.mark.parametrize(\n \"invert,expected\",\n [\n (False, [\"Bell__Chart\", \"a\", \"animals@#$%^\"]),\n (True, [\"decorated-elephant\", \"cities\"]),\n ],\n)\ndef test_select_columns_glob_inputs(dataframe, invert, expected):\n columns = [\"Bell__Chart\", \"a*\"]\n df = dataframe.select_columns(search_column_names=columns, invert=invert)\n\n pd.testing.assert_frame_equal(df, dataframe[expected])\n","sub_path":"tests/functions/test_select_columns.py","file_name":"test_select_columns.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183494399","text":"import sklearn\nimport numpy as np\nimport pandas as pd\nimport dill as pickle\n\nfrom keras.models import load_model\n\n\nclass RNN(object):\n\n def __init__(self):\n with open('models/feature_scalers.pickle', 'rb') as f:\n self.feature_scalers = pickle.load(f)\n\n self.model = load_model('models/lstm.h5', compile=False)\n self.historic_data = pd.read_csv('data/clean/DK-DK2.csv',\n parse_dates=['datetime'],\n index_col='datetime')\n\n self.features = self.make_sequences(self.historic_data)\n\n self.targets = [k for k in list(self.features) if 'carbon_intensity_avg(t+' in k]\n self.features.drop(columns=self.targets, inplace=True)\n\n def predict(self, start):\n features = self.features.loc[start].values.reshape(1, 1, -1)\n prediction = self.model.predict(features)\n prediction = prediction.reshape(-1, 1)\n feature_scalers = [v for k, v in self.feature_scalers.items() if k in self.targets]\n return np.array([s.inverse_transform(v) for s, v in zip(feature_scalers, prediction)]).flatten()\n\n @staticmethod\n def make_sequences(data, n_tstep=24*4, n_target=24):\n\n cols, names = list(), list()\n\n # input sequence (t-n, ... t-1)\n for i in range(n_tstep, 0, -1):\n cols.append(data.shift(i))\n names += [f'{var}(t-{i})' for var in list(data)]\n\n # forecast sequence (t, t+1, ... t+n)\n for i in range(0, n_target):\n cols.append(data.carbon_intensity_avg.shift(-i))\n names.append(f'carbon_intensity_avg(t+{i})')\n\n agg = pd.concat(cols, axis=1)\n agg.columns = names\n return agg.dropna()\n","sub_path":"models/RNN.py","file_name":"RNN.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"382034955","text":"from django.conf.urls import url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom . import views\n\nurlpatterns = [\n url(r'^upload/$', views.model_form_upload, name='model_form_upload'),\n url(r'^editar/(?P\\d+)$', views.editar_t, name='editar_t'),\n url(r'^datospasa/(?P\\d+)$', views.form_pasa, name='form_pasa'),\n url(r'^consultar/$', views.buscar, name='buscar'),\n url(r'^consultar/p$', views.buscar_p, name='buscar_p'),\n url(r'^consultar/t$', views.buscar_t, name='buscar_t'),\n url(r'^consultar/s$', views.buscar_s, name='buscar_s'),\n url(r'^consultar/view/(?P\\d+)$', views.view_p, name='view_p'),\n url(r'^consultar/pasa/(?P\\d+)$', views.view_s, name='view_s'),\n url(r'^$', views.index, name='index'),\n\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"SIGPAE/SIGPAE/historia1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"51135141","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nimport torch\nfrom rl.lib.nets import MLP\nfrom rl.lib.on_policy import reward_to_go, run\n\n\ndef policy_loss(logits, actions, advantages, eps):\n \"\"\"\n :param logits: (batch_size, act_dim) 2d array output of the policy\n :param actions (batch_size)\n :param advantages (batch_size)\n :return: A scalar value representing the loss\n \"\"\"\n batch_size = logits.shape[0]\n log_probs = logits.log_softmax(dim=1)[np.arange(batch_size), actions]\n\n # Negate so you can minimize\n return -torch.mean(log_probs * rewards)\n\n\ndef train(env, epochs=100, policy_lr=1e-2, v_lr=1e-3, train_v_iters=80, batch_size=5000):\n obs_dim = env.observation_space.shape[0]\n act_dim = env.action_space.n\n policy = MLP(dims=(obs_dim, 24, 24, act_dim)).float()\n V = MLP(dims=(obs_dim, 32, 32, 1)).float()\n\n policy_optimizer = torch.optim.Adam(policy.parameters(), lr=policy_lr)\n v_optimizer = torch.optim.Adam(V.parameters(), lr=v_lr)\n mean_rewards = []\n for i in range(epochs):\n states, actions, logits, rewards = run(env, batch_size, policy)\n mean_reward = sum([sum(ep_rewards) for ep_rewards in rewards]) / len(rewards)\n print(f'Episode {i + 1}: Mean Reward = {mean_reward:.2f}')\n mean_rewards.append(mean_reward)\n\n states_tensor = torch.Tensor(states)\n actions_tensor = torch.tensor(actions)\n logits_tensor = torch.stack(logits).squeeze(dim=1)\n\n values = V(states_tensor).squeeze(dim=1)\n weighted_rewards = reward_to_go(rewards, gamma=0.99)\n weighted_rewards_tensor = torch.Tensor(weighted_rewards)\n advantages = weighted_rewards_tensor - values\n epoch_loss = policy_loss(logits_tensor, actions_tensor, advantages)\n\n policy.zero_grad()\n epoch_loss.backward(retain_graph=True)\n policy_optimizer.step()\n\n for _ in range(train_v_iters):\n values = V(states_tensor).squeeze(dim=1)\n value_loss = torch.nn.MSELoss()(values, weighted_rewards_tensor)\n V.zero_grad()\n value_loss.backward()\n v_optimizer.step()\n\n return policy, mean_rewards\n\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v1')\n policy, mean_rewards = train(env)\n\n plt.plot(mean_rewards)\n plt.show()\n\n for i in range(10):\n _, _, _, rewards = run(env, 1, policy, render=True)\n total_reward = sum(rewards[0])\n print(f'Episode {i}: Reward = {total_reward}')\n\n env.close()\n\n","sub_path":"rl/ppo.py","file_name":"ppo.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580044001","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 9 23:07:31 2018\n\n@author: Tuan Nguyen @ quangtuan1412@gmail.com\n\n\"\"\"\nimport sqlite3 as sql\n\nif __name__ == \"__main__\":\n db = sql.connect('parking.sql')\n db.execute(\"CREATE TABLE card(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, cardnumber CHAR NOT NULL)\")\n db.commit()\n db.close()\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272128699","text":"\n\"\"\"\n\nToday, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video!\n\nContext\nGiven a 2D Array, A :\n\n1 1 1 0 0 0\n0 1 0 0 0 0\n1 1 1 0 0 0\n0 0 0 0 0 0\n0 0 0 0 0 0\n0 0 0 0 0 0\nWe define an hourglass in A to be a subset of values with indices falling in this pattern in A's graphical representation:\n\na b c\n d\ne f g\nThere are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass' values.\n\nTask\nCalculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.\n\n\"\"\"\nfrom __future__ import print_function\nfrom data_structure import OrderedDict\n\ndef __main__():\n \"\"\"\n\n row_size = raw_input(prompt=\"Enter row size\")\n column_size = raw_input(prompt=\"Enter column size\")\n subset_array_size = raw_input(prompt=\"Enter subset array size\")\n\n \"\"\"\n row_size, column_size, subset_array_size = 6, 6, 3\n twoD_array=[[],[]]\n\n for _ in xrange(6):\n twoD_array.append(map(int, raw_input().rstrip().split()))\n\n subset_sum_dict = add_possible_subset(row_size, column_size, subset_array_size)\n calculate_subset_sum(twoD_array, subset_sum_dict, 3)\n max_i = max(subset_sum_dict, key=subset_sum_dict.get)\n\n print_sub_set(max_i, twoD_array)\n\n max_sum = max(subset_sum_dict.values())\n print(max_sum)\n\n\ndef add_possible_subset(row_size=6, column_size=6, subset_array_size=3):\n subset_sum_dict = OrderedDict()\n for i in xrange(0, row_size-subset_array_size+1):\n for j in xrange(0, column_size-subset_array_size+1):\n subset_sum_dict[\"{},{}\".format(i, j)] = 0\n return subset_sum_dict\n\n\n\ndef calculate_subset_sum(twoD_array, subset_sum_dict, subset_array_size=3):\n for key in subset_sum_dict.keys():\n row, col = map(int, key.split(\",\", 1))\n sum = 0\n for i in xrange(row, row+subset_array_size, 2):\n for j in xrange(col, col+subset_array_size):\n sum += twoD_array[i][j]\n mid_i, mid_j = row + int(subset_array_size/2), col + int(subset_array_size/2)\n sum += twoD_array[mid_i][mid_j]\n subset_sum_dict[\"{},{}\".format(row, col)] = sum\n\n\ndef print_sub_set(max_i, twoD_array):\n row, col = map(int, max_i.split(\",\", 1))\n for i in xrange(row, row + 3, 2):\n for j in xrange(col, col + 3):\n print(twoD_array[i][j], end=\" \")\n print()\n if i == row + 3 - 1:\n break\n print(\" {}\".format(twoD_array[row + 1][col + 1]))\n\n\ndef test_add_possible_subset():\n d = add_possible_subset()\n assert 16 == len(d)\n\n\ndef test_calculate_subset_sum():\n subset_sum_dict = add_possible_subset()\n twoD_array = [[1, 1, 1, 0, 0, 0],\n [0, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [0, 0, 2, 4, 4, 0],\n [0, 0, 0, 2, 0, 0],\n [0, 0, 1, 2, 4, 0]]\n calculate_subset_sum(twoD_array, subset_sum_dict, 3)\n\n print(subset_sum_dict)\n max_i = max(subset_sum_dict, key=subset_sum_dict.get)\n\n print_sub_set(max_i, twoD_array)","sub_path":"30_days_challenge/Day11_2D_Arrays.py","file_name":"Day11_2D_Arrays.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108089441","text":"#\n# Monte Carlo valuation of European call options with NumPy (log version)\n# Much faster than other Monte Carlo simulations\n#\nimport math\nfrom numpy import *\n# Star import for shorter code\nfrom time import time\n\nrandom.seed(20000)\nt0 = time()\n\n# Parameters\nS0 = 100.; K = 105.; T = 1.0; r = 0.05; sigma = 0.2\nM = 50; dt = T / M; I = 250000\n\n# Simulating I paths with M time steps\nS = S0 * exp(cumsum((r - 0.5 * sigma ** 2) * dt\n + sigma * math.sqrt(dt)\n + random.standard_normal((M + 1, I)), axis = 0))\n \nS[0] = S0\n\n# Calculating the Monteo Carlo estimator\nC0 = math.exp(-r * T) * sum(maximum(S[-1] - K, 0)) / I\n\n# Results output\ntnp2 = time() - t0\nprint(\"European Option Value %7.3f\" % C0)\nprint(\"Duration in Seconds %7.3f\" % tnp2)\n\n","sub_path":"montecarlo.py","file_name":"montecarlo.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245669133","text":"#!/usr/bin/python3\n\n# Context\n# Given a 6 x 6 2D Array, A:\n\n# 1 1 1 0 0 0\n# 0 1 0 0 0 0\n# 1 1 1 0 0 0\n# 0 0 0 0 0 0\n# 0 0 0 0 0 0\n# 0 0 0 0 0 0\n# We define an hourglass in A to be a subset of values with indices falling in\n# this pattern in A's graphical representation:\n\n# a b c\n# d\n# e f g\n# There are 16 hourglasses in A, and an hourglass sum is the sum of an\n# hourglass' values.\n\n# Task\n# Calculate the hourglass sum for every hourglass in A, then print the\n# maximum hourglass sum.\n\n# Input Format\n# There are 6 lines of input, where each line contains 6 space-separated\n# integers describing 2D Array A; every value in A will be in the\n# inclusive range of -9 to 9.\n\n# Constraints\n# -9 <= A[i][j] <= 9\n# 0 <= i,j <= 5\n\n# Output Format\n# Print the largest (maximum) hourglass sum found in A.\n\n# Sample Input\n\n# 1 1 1 0 0 0\n# 0 1 0 0 0 0\n# 1 1 1 0 0 0\n# 0 0 2 4 4 0\n# 0 0 0 2 0 0\n# 0 0 1 2 4 0\n# Sample Output\n\n# 19\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n# Complete the array2D function below.\ndef array2D(arr):\n res = list()\n for i in range(4):\n for j in range(4):\n result = sum(arr[i][j:j+3]) + arr[i+1][j+1] + sum(\n arr[i+2][j:j+3])\n res.append(result)\n return(max(res))\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n arr = []\n\n for _ in range(6):\n arr.append(list(map(int, input().rstrip().split())))\n\n result = array2D(arr)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"30-days-of-code/Day_11:_2D_Arrays.py","file_name":"Day_11:_2D_Arrays.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"393000032","text":"import functools\nimport sys\n\nimport geopandas as gpd\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nfrom scipy.stats import binom\n\nfrom carbonplan_forests import utils\n\n\ndef integrated_risk(p):\n return (1 - binom.cdf(0, 10, p)) * 100\n\n\nargs = sys.argv\n\nif len(args) < 2:\n raise ValueError('must specify dataset')\ndataset = args[1]\n\nprecision = {'biomass': 2, 'fire': 3, 'drought': 3, 'insects': 3, 'biophysical': 3}\n\nds = xr.open_zarr(f'data/{dataset}.zarr')\n\nif dataset == 'fire':\n scenarios = ['ssp245', 'ssp370', 'ssp585']\n for scenario in scenarios:\n keys = list(\n filter(lambda a: a is not None, [k if scenario in k else None for k in ds.data_vars])\n )\n ds[scenario] = functools.reduce(lambda a, b: a + b, [ds[key] for key in keys]) / len(keys)\n\nif dataset in ['fire', 'biomass', 'drought', 'insects']:\n scenarios = ['ssp245', 'ssp370', 'ssp585']\n targets = ds['year'].values\n\n a = np.concatenate([ds[scenario].values for scenario in scenarios], axis=0)\n\n if dataset == 'fire':\n a = integrated_risk(a)\n\n a[np.isnan(a)] = 0\n r, c = np.nonzero(a.max(axis=0))\n lat, lon = utils.rowcol_to_latlon(r, c, res=4000)\n\n df = pd.DataFrame()\n\n for s, scenario in enumerate(scenarios):\n for y, year in enumerate(targets):\n key = str(s) + '_' + str(y)\n a = ds[scenario].sel(year=year).values\n\n if dataset == 'fire':\n a = integrated_risk(a)\n\n a[np.isnan(a)] = 0\n df[key] = np.round(a[r, c], precision[dataset])\n\nif dataset == 'biophysical':\n a = ds['biophysical'].values\n a = -a\n a[np.isnan(a)] = 0\n a[a < 0.25 * a.max()] = 0\n a = a.astype('float64')\n r, c = np.nonzero(a)\n lat, lon = utils.rowcol_to_latlon(r, c, res=4000)\n\n df = pd.DataFrame()\n df['0'] = np.round(a[r, c], precision[dataset])\n\ngdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(lon, lat))\ngdf.to_file(f'data/{dataset}.geojson', driver='GeoJSON')\n","sub_path":"scripts/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463079741","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"\nPretrain GPT in static graph mode.\n\"\"\"\nimport argparse\nimport math\nimport os\nimport random\nimport time\n\nos.path.expandvars('$HOME')\nos.path.expanduser('~')\n\nimport numpy as np\nimport paddle\nimport paddle.distributed.fleet as fleet\nfrom paddle.distributed.fleet.meta_optimizers.sharding.utils import save_persistables\nfrom paddlenlp.transformers import GPTModel, GPTForPretraining, GPTPretrainingCriterion\nfrom paddlenlp.transformers import GPTTokenizer, GPTChineseTokenizer\nfrom paddlenlp.ops import Topology, get_rng_state_tracker\nfrom paddlenlp.utils.log import logger\nimport paddlenlp.ops as ops\nfrom visualdl import LogWriter\n\nfrom dataset import create_pretrained_dataset\nfrom args import parse_args\nimport lr\n\nMODEL_CLASSES = {\n \"gpt\": (GPTForPretraining, GPTTokenizer),\n \"gpt-cn\": (GPTForPretraining, GPTChineseTokenizer),\n}\n\n\ndef create_data_holder(args):\n \"\"\"creat data holder\"\"\"\n tokens = paddle.static.data(\n name=\"tokens\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n loss_mask = paddle.static.data(\n name=\"loss_mask\", shape=[-1, args.max_seq_len], dtype=\"float32\")\n attention_mask = paddle.static.data(\n name=\"attention_mask\",\n shape=[-1, 1, args.max_seq_len, args.max_seq_len],\n dtype=\"float32\")\n position_ids = paddle.static.data(\n name=\"position_ids\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n labels = paddle.static.data(\n name=\"labels\", shape=[-1, args.max_seq_len], dtype=\"int64\")\n return [tokens, loss_mask, attention_mask, position_ids, labels]\n\n\ndef dist_optimizer(args, topo):\n default_global_batch_size = topo.data_info.size * args.micro_batch_size\n if args.global_batch_size is None:\n args.global_batch_size = default_global_batch_size\n\n bsz_per_dp = args.global_batch_size // topo.data_info.size\n micro_batch_size = args.micro_batch_size\n assert args.global_batch_size % micro_batch_size == 0, \"cannot do gradient accumulate, global_batch_size: {} micro_batch_size: {}\".format(\n args.global_batch_size, micro_batch_size)\n acc_steps = bsz_per_dp // micro_batch_size\n\n exec_strategy = paddle.fluid.ExecutionStrategy()\n exec_strategy.num_threads = 2\n exec_strategy.num_iteration_per_drop_scope = 1\n\n dist_strategy = fleet.DistributedStrategy()\n dist_strategy.execution_strategy = exec_strategy\n dist_strategy.nccl_comm_num = 3\n\n dist_strategy.recompute = args.use_recompute\n dist_strategy.pipeline = args.pp_degree > 1\n\n if args.use_amp:\n dist_strategy.amp = True\n dist_strategy.amp_configs = {\n \"custom_white_list\": [\n 'softmax',\n 'layer_norm',\n 'gelu',\n ],\n \"custom_black_list\": ['c_softmax_with_cross_entropy'],\n \"init_loss_scaling\": 32768,\n \"use_dynamic_loss_scaling\": True,\n }\n if args.use_sharding:\n dist_strategy.sharding = True\n dist_strategy.sharding_configs = {\n \"segment_broadcast_MB\": 32,\n \"sharding_degree\": args.sharding_degree,\n \"mp_degree\": args.mp_degree,\n \"pp_degree\": args.pp_degree,\n \"dp_degree\": args.dp_degree,\n \"optimize_offload\": False,\n }\n if args.pp_degree > 1:\n dist_strategy.pipeline_configs = {\n \"schedule_mode\": \"1F1B\",\n \"micro_micro_batch_size\": micro_batch_size,\n \"accumulate_steps\": acc_steps,\n }\n else:\n assert acc_steps == 1, \"Only support accumulate steps in piplinemode. Please set you global_batch_size={}\".format(\n default_global_batch_size)\n\n return dist_strategy\n\n\ndef get_train_data_file(args):\n files = [\n os.path.join(args.input_dir, f) for f in os.listdir(args.input_dir)\n if (os.path.isfile(os.path.join(args.input_dir, f)) and \"npz_\" not in\n str(f))\n ]\n\n data_file = files[0]\n return data_file\n\n\ndef init_static_with_params(model, dygraph_params, topo, prog=None):\n from paddlenlp.utils.tools import dygraph_params_to_static\n static_params = dygraph_params_to_static(model, dygraph_params, topo)\n if prog is None:\n prog = paddle.static.default_main_program()\n paddle.static.set_program_state(prog, static_params)\n\n\ndef run_evaluate(data_loader,\n exe,\n program,\n iter_steps,\n log_writer,\n global_step,\n args,\n epoch,\n is_last,\n eval_fetch,\n task_name=\"valid\"):\n all_loss = []\n local_time = time.time()\n\n for eval_step, batch in enumerate(data_loader):\n loss_return = exe.run(program, feed=batch, fetch_list=eval_fetch)\n if is_last:\n all_loss.append(float(loss_return[0]))\n if eval_step >= iter_steps - 1:\n if not is_last:\n break\n average_loss = sum(all_loss) / len(all_loss)\n logger.info(\n \"%s step %d, epoch: %d, batch: %d, loss: %f, speed: %.0f tokens/s\"\n % (task_name, global_step, epoch, eval_step, average_loss,\n iter_steps * args.micro_batch_size * args.max_seq_len /\n (time.time() - local_time)))\n log_writer.add_scalar(task_name + \"_loss\", average_loss,\n global_step)\n break\n\n\ndef do_train(args):\n # Initialize the paddle and paddle fleet execute environment\n paddle.enable_static()\n fleet.init(is_collective=True)\n\n # Create the random seed for the worker\n random.seed(args.seed)\n np.random.seed(args.seed)\n paddle.seed(args.seed)\n get_rng_state_tracker().add('global_seed', args.seed)\n get_rng_state_tracker().add('local_seed',\n args.seed + fleet.worker_index() + 2021)\n\n assert args.device in [\n \"cpu\", \"gpu\", \"xpu\"\n ], \"Invalid device! Available device should be cpu, gpu, or xpu.\"\n place = paddle.set_device(args.device)\n\n worker_num = fleet.worker_num()\n worker_index = fleet.worker_index()\n\n assert args.pp_degree == 1, \"Please use gpt-3 example to train GPT with pipline prallelism.\"\n assert args.mp_degree == 1, \"Please use gpt-3 example to train GPT with model prallelism.\"\n\n topo = Topology(\n device_rank=worker_index,\n world_size=worker_num,\n dp_degree=args.dp_degree,\n pp_degree=args.pp_degree,\n sharding_degree=args.sharding_degree,\n mp_degree=args.mp_degree)\n\n logger.info(\"The topo of hybrid parallelism:\\n{}\".format(topo))\n\n dist_strategy = dist_optimizer(args, topo)\n\n # Create log write, train results show on last card of pipeline.\n if topo.is_last:\n log_writer_path = os.path.join(\n args.output_dir, \"train_log\",\n \"{}_globalbsz_{}_amp_{}_recompute_{}_card_{}\".format(\n args.model_name_or_path, args.global_batch_size, args.use_amp,\n args.use_recompute, worker_index).lower())\n if os.path.exists(log_writer_path):\n import shutil\n shutil.rmtree(log_writer_path)\n log_writer = LogWriter(log_writer_path)\n\n # Define the input data in the static mode\n\n model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\n pretrained_models_list = list(\n model_class.pretrained_init_configuration.keys())\n\n data_file = get_train_data_file(args)\n main_program = paddle.static.default_main_program()\n startup_program = paddle.static.default_startup_program()\n with paddle.static.program_guard(main_program, startup_program):\n with paddle.utils.unique_name.guard():\n with paddle.static.device_guard('gpu:0'):\n data_holders = create_data_holder(args)\n [tokens, loss_mask, attention_mask, position_ids,\n labels] = data_holders\n\n tokenizer = tokenizer_class.from_pretrained(\n args.model_name_or_path)\n eos_id = tokenizer.eos_token_id\n\n train_data_loader, valid_data_loader, test_data_loader = create_pretrained_dataset(\n args,\n data_file,\n data_world_size=topo.data_info.size,\n data_world_rank=topo.data_info.rank,\n eos_id=eos_id,\n max_seq_len=args.max_seq_len,\n places=paddle.static.cuda_places(),\n data_holders=data_holders,\n pipeline_mode=False, )\n\n if args.model_name_or_path in pretrained_models_list:\n model_config = model_class.pretrained_init_configuration[\n args.model_name_or_path]\n\n model_config[\n \"hidden_dropout_prob\"] = args.hidden_dropout_prob\n model_config[\n \"attention_probs_dropout_prob\"] = args.attention_probs_dropout_prob\n model_config[\"topo\"] = topo\n\n model = GPTForPretraining(GPTModel(**model_config))\n else:\n model, _ = GPTForPretraining.from_pretrained(\n args.model_name_or_path,\n hidden_dropout_prob=args.hidden_dropout_prob,\n attention_probs_dropout_prob=args.\n attention_probs_dropout_prob,\n topo=topo)\n\n # Create the model for the gpt pretrain\n preds = model(tokens, position_ids, attention_mask)\n\n criterion = GPTPretrainingCriterion(topo)\n loss = criterion(preds, labels, loss_mask)\n\n # Create the learning_rate sheduler and optimizer\n if args.decay_steps is None:\n args.decay_steps = args.max_steps\n warmup_step = args.warmup_rate * args.decay_steps\n\n # TODO @ZHUI Use paddle network to support lr scheduler\n lr_scheduler = lr.CosineAnnealingWithWarmupDecay(\n max_lr=args.max_lr,\n min_lr=args.min_lr,\n warmup_step=warmup_step,\n decay_step=args.decay_steps)\n\n clip = None\n if args.grad_clip > 0:\n clip = paddle.fluid.clip.GradientClipByGlobalNorm(\n clip_norm=args.grad_clip)\n\n decay_param = [\n p.name for n, p in model.named_parameters()\n if not any(nd in n for nd in [\"bias\", \"norm\"])\n ]\n\n optimizer = paddle.optimizer.AdamW(\n learning_rate=lr_scheduler,\n beta1=args.adam_beta1,\n beta2=args.adam_beta2,\n epsilon=args.adam_epsilon,\n grad_clip=clip,\n weight_decay=args.weight_decay,\n apply_decay_param_fun=lambda x: x in decay_param)\n\n # alias\n optimizer.apply_optimize = optimizer._apply_optimize\n\n if args.use_recompute:\n dist_strategy.recompute = True\n dist_strategy.recompute_configs = {\n \"checkpoints\": model.gpt.checkpoints\n }\n\n # Use the fleet api to compile the distributed optimizer\n optimizer = fleet.distributed_optimizer(\n optimizer, strategy=dist_strategy)\n\n optimizer.minimize(loss)\n logger.info(f'final strategy: {fleet._final_strategy()}')\n logger.info(\"The training meta optimizer is/are %s\" %\n fleet._get_applied_meta_list())\n\n program_desc_dir = os.path.join(args.output_dir, \"program_desc\")\n if not os.path.isdir(program_desc_dir):\n os.mkdir(program_desc_dir)\n\n with open(program_desc_dir + \"/main_program.txt.%d\" % worker_index,\n 'w') as f:\n f.write(str(main_program))\n\n with open(program_desc_dir + \"/startup_program.txt.%d\" % worker_index,\n 'w') as f:\n f.write(str(startup_program))\n\n # Define the Executor for running the static model\n exe = paddle.static.Executor(place)\n exe.run(startup_program)\n test_program = main_program.clone(for_test=True)\n\n if args.model_name_or_path not in pretrained_models_list:\n logger.info(\"Try to load checkpoint from %s \" % args.model_name_or_path)\n dygrah_path = os.path.join(args.model_name_or_path,\n \"model_state.pdparams\")\n static_path = os.path.join(args.model_name_or_path, \"static_vars\")\n\n flag_loaded = False\n if os.path.exists(static_path):\n if args.mp_degree > 1:\n logger.warning(\"MP should init with dygraph params\")\n else:\n logger.info(\"Loading parameters from %s\" % static_path)\n paddle.static.load(main_program, static_path, exe)\n flag_loaded = True\n\n if not flag_loaded and os.path.exists(dygrah_path):\n if args.sharding_degree > 1:\n logger.warning(\"Sharding should init with static vars\")\n else:\n logger.info(\"Loading parameters from %s\" % dygrah_path)\n init_static_with_params(\n model,\n paddle.load(\n dygrah_path, return_numpy=True),\n topo,\n main_program)\n flag_loaded = True\n\n if not flag_loaded:\n logger.error(\"No checkpoint load.\")\n\n global_step = 0\n tic_train = time.time()\n epoch = 0\n learning_rate = main_program.global_block().vars[\"learning_rate_0\"]\n while True:\n fetchs = []\n if topo.is_last:\n fetchs = [loss, learning_rate]\n\n # Bug fix, if not call valid_data_loader, the enumerate will call valid_data_loader\n # many times. and start a new random dataloader.\n valid_data_loader = valid_data_loader()\n test_data_loader = test_data_loader()\n\n for step, batch in enumerate(train_data_loader()):\n global_step += 1\n ret = exe.run(main_program,\n feed=batch,\n fetch_list=fetchs,\n use_program_cache=True)\n # In the new 2.0 api, must call this function to change the learning_rate\n lr_scheduler.step()\n\n if global_step % args.logging_freq == 0:\n if topo.is_last:\n loss_return, lr_return = ret\n speed = args.logging_freq / (time.time() - tic_train)\n logger.info(\n \"global step %d, epoch: %d, batch: %d, loss: %.9f, speed: %.2f steps/s, ips: %.0f tokens/s, learning rate: %.5e\"\n % (global_step, epoch, step, loss_return[0], speed,\n speed * args.global_batch_size * args.max_seq_len,\n lr_return[0]))\n log_writer.add_scalar(\"loss\", loss_return[0], global_step)\n log_writer.add_scalar(\"learning_rate\", lr_return[0],\n global_step)\n tic_train = time.time()\n\n if args.check_accuracy:\n if global_step >= args.max_steps:\n return\n else:\n continue\n\n if global_step % args.eval_freq == 0:\n # TODO, check the input data of validation\n eval_fetch = []\n if topo.is_last:\n eval_fetch = [loss]\n\n run_evaluate(valid_data_loader, exe, test_program,\n args.eval_iters, log_writer, global_step, args,\n epoch, topo.is_last, eval_fetch, \"valid\")\n tic_train = time.time()\n\n if global_step % args.save_steps == 0 or global_step >= args.max_steps:\n output_dir = os.path.join(args.output_dir,\n \"model_%d\" % global_step)\n logger.debug(\"saving models to {}\".format(output_dir))\n save_persistables(exe,\n os.path.join(output_dir, \"static_vars\"),\n main_program)\n if global_step == args.save_steps:\n model.init_config[\"init_args\"][0].init_config.pop(\"topo\",\n None)\n model.save_pretrained(output_dir)\n tokenizer.save_pretrained(output_dir)\n tic_train = time.time()\n\n if global_step >= args.max_steps:\n eval_fetch = []\n if topo.is_last:\n eval_fetch = [loss]\n\n run_evaluate(test_data_loader, exe, test_program,\n args.test_iters, log_writer, global_step, args,\n epoch, topo.is_last, eval_fetch, \"test\")\n del train_data_loader\n return\n epoch += 1\n\n\nif __name__ == \"__main__\":\n config = parse_args(MODEL_CLASSES)\n do_train(config)\n","sub_path":"Paddle_ChineseBert/PaddleNLP/examples/language_model/gpt/run_pretrain_static.py","file_name":"run_pretrain_static.py","file_ext":"py","file_size_in_byte":17765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234656361","text":"from django.conf import settings\nfrom django.shortcuts import render\nfrom django.views.decorators.http import require_POST\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.views.generic import View\nfrom apps.courtroom.models import Courtroom\nfrom .forms import AddSkyvisCaseForm, EditSkyvisCaseForm, DeleteSkyvisCaseForm\nfrom .models import SkyvisCase\nfrom utils import restful\nfrom utils.pagination import get_pagination_data\nfrom utils.decorators import skyvis_superuser_required\n\n\nclass SkyvisCaseView(View):\n def get(self, request, case_no=None):\n count = settings.ONE_PAGE_NEWS_COUNT\n try:\n page = int(request.GET.get('p', 1))\n case_no = request.GET.get('case_no')\n except:\n page = 1\n if case_no:\n skyvis_cases = SkyvisCase.objects.filter(case_no__icontains=case_no)\n else:\n skyvis_cases = SkyvisCase.objects.all()\n paginator = Paginator(skyvis_cases, count)\n try:\n page_obj = paginator.page(page)\n except PageNotAnInteger:\n page_obj = paginator.page(1)\n except EmptyPage:\n page_obj = paginator.page(1)\n context_data = get_pagination_data(paginator, page_obj, count=count)\n courtrooms = Courtroom.objects.all()\n context = {\n 'skyvis_cases': page_obj.object_list,\n 'courtrooms': courtrooms,\n 'page_obj': page_obj,\n 'paginator': paginator,\n 'case_no': case_no,\n 'total': skyvis_cases.count()\n }\n context.update(context_data)\n return render(request, 'cases/skyvis-cases.html', context=context)\n\n def http_method_not_allowed(self, request, *args, **kwargs):\n return render(request, 'errors/403.html')\n\n\n@skyvis_superuser_required\n@require_POST\ndef add_skyvis_case(request):\n form = AddSkyvisCaseForm(request.POST)\n if form.is_valid():\n courtroom = request.POST.get('courtroom')\n department_name = request.POST.get('department_name')\n case_no = request.POST.get('case_no')\n catalog_id = request.POST.get('catalog_id')\n case_cause = request.POST.get('case_cause')\n phrase = request.POST.get('phrase')\n begin_time = request.POST.get('begin_time')\n hls = request.POST.get('hls')\n mp4 = request.POST.get('mp4')\n poster = request.POST.get('poster')\n room_name = request.POST.get('room_name')\n description = request.POST.get('description')\n cbr = request.POST.get('cbr')\n judge = request.POST.get('judge')\n party = request.POST.get('party')\n status = request.POST.get('status')\n push_status = request.POST.get('push_status')\n if not Courtroom.objects.filter(pk=courtroom):\n return restful.params_error(message='添加失败,法院不存在')\n else:\n try:\n SkyvisCase.objects.create(\n courtroom_id=courtroom, department_name=department_name, case_no=case_no, catalog_id=catalog_id,\n case_cause=case_cause, phrase=phrase, begin_time=begin_time, hls=hls, mp4=mp4, poster=poster,\n room_name=room_name, description=description, cbr=cbr, judge=judge, party=party, status=status,\n push_status=push_status\n )\n return restful.ok()\n except:\n return restful.server_error(message='添加天宇威视案件失败,服务器内部错误')\n else:\n return restful.params_error(message=form.get_errors())\n\n\n@skyvis_superuser_required\n@require_POST\ndef edit_skyvis_case(request):\n form = EditSkyvisCaseForm(request.POST)\n if form.is_valid():\n pk = request.POST.get('pk')\n courtroom = request.POST.get('courtroom')\n department_name = request.POST.get('department_name')\n case_no = request.POST.get('case_no')\n catalog_id = request.POST.get('catalog_id')\n case_cause = request.POST.get('case_cause')\n phrase = request.POST.get('phrase')\n begin_time = request.POST.get('begin_time')\n hls = request.POST.get('hls')\n mp4 = request.POST.get('mp4')\n poster = request.POST.get('poster')\n room_name = request.POST.get('room_name')\n description = request.POST.get('description')\n cbr = request.POST.get('cbr')\n judge = request.POST.get('judge')\n party = request.POST.get('party')\n status = request.POST.get('status')\n push_status = request.POST.get('push_status')\n try:\n SkyvisCase.objects.filter(pk=pk).update(\n courtroom_id=courtroom, department_name=department_name, case_no=case_no, catalog_id=catalog_id,\n case_cause=case_cause, phrase=phrase, begin_time=begin_time, hls=hls, mp4=mp4, poster=poster,\n room_name=room_name, description=description, cbr=cbr, judge=judge, party=party, status=status,\n push_status=push_status\n )\n return restful.result(message='编辑成功')\n except:\n return restful.params_error(message='编辑失败,天宇威视案件不存在')\n else:\n return restful.params_error(message=form.get_errors())\n\n\n@skyvis_superuser_required\n@require_POST\ndef delete_skyvis_case(request):\n form = DeleteSkyvisCaseForm(request.POST)\n if form.is_valid():\n pk = request.POST.get('pk')\n try:\n SkyvisCase.objects.filter(pk=pk).delete()\n return restful.ok()\n except:\n return restful.params_error(message='删除案件失败,该案件正在被使用')\n else:\n return restful.params_error(message=form.get_errors())\n","sub_path":"apps/cases/skyvis_case_views.py","file_name":"skyvis_case_views.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"568774052","text":"# 策略模式\n#\n# 定义:定义一系列的算法把它们一个个封装起来,并且使它们可相互替换.该模式使得算法可独立于使用它的客户而变化\n#\n# 角色:抽象策略,具体策略,上下文\n#\n# 适用场景:许多相关的类仅仅是行为有异,需使用一个算法的不同变体,算法使用了客户端无需知道的数据,一个类中的多个行为以多个条件语句存在可以将其封装在不同的策略类中\n#\n# 优点:定义了一系列可重用的算法和行为,消除了一些条件语句,可提供相同行为的不同实现\n#\n# 缺点:客户必须了解不同的策略,策略与上下文之间的通信开销,增加了对象的数目\n\nfrom abc import ABCMeta, abstractmethod\nimport random\n\n#抽象策略\nclass Sort(metaclass=ABCMeta):\n @abstractmethod\n def sort(self,data):\n pass\n\n#具体策略\nclass QuickSort(Sort):\n\n def quick_sort(self,data,left,right):\n if left=tmp:\n right -= 1\n data[left] = data[right]\n\n while left.*)=(?P.*)$', views.words_detail),\n]\n","sub_path":"definitions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161414779","text":"# coding=utf8\n__author__ = 'sunyi'\n\nimport unittest\nfrom time import sleep\nfrom PageObjects.page import Page\n\nclass TestPage(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.p = Page(None)\n\n @classmethod\n def tearDownClass(cls):\n cls.p = None\n\n def setUp(self):\n pass\n\n def test_open_page(self):\n self.p.browser.get(\"http://www.baidu.com\")\n sleep(10)\n assert self.p.title() is not None\n assert u\"百度\" in self.p.title()\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"TestSuites/testPage.py","file_name":"testPage.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"491306680","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\n\nclass Room():\n def __init__(self, name, description, inventory):\n self.name = name\n self.description = description\n inventory_item = inventory.split(\" \")\n self.inventory = [*inventory_item]\n self.n_to = None\n self.s_to = None\n self.e_to = None\n self.w_to = None\n\n def room_direction(self, direction):\n if direction == 'n':\n return self.n_to\n elif direction == 's':\n return self.s_to\n elif direction == 'e':\n return self.e_to\n elif direction == 'w':\n return self.w_to\n else:\n return None\n\n def __str__(self):\n return f'{self.name}, \\n{self.description} You see, tucked away in a dusty corner, {self.inventory}'\n\n def remove_item(self, item):\n self.inventory.remove(item)\n\n def add_item(self, item):\n self.inventory.append(item)","sub_path":"projects/graph/adv/rooms.py","file_name":"rooms.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"293470995","text":"from ai_safety_gridworlds.environments import boat_race\n\nfrom ai_safety_gridworlds.environments.friend_foe import FriendFoeEnvironment\nfrom ai_safety_gridworlds.environments.shared import safety_game\nimport numpy as np\nimport random\nimport time\nfrom IPython.display import clear_output\n\nclass foe:\n def init(self, env):\n self.env=env\n self.actions = safety_game.Actions\n\n self.actions_dict = {'Left': self.actions.LEFT.value, 'Right': self.actions.RIGHT.value,\n 'Up': self.actions.UP.value, 'Down': self.actions.DOWN.value, 'Quit': self.actions.QUIT.value}\n\n\n def run_experiment(self):\n self.env.reset()\n print(\"Reward before action...\",self.env.episode_return)\n a= self.env.step(self.actions.RIGHT.value)\n b= self.env.step(self.actions.RIGHT.value)\n c= self.env.step(self.actions.DOWN.value)\n d = self.env.step(self.actions.DOWN.value)\n g = self.env.step(self.actions.LEFT.value)\n h = self.env.step(self.actions.LEFT.value)\n i = self.env.step(self.actions.UP.value)\n j = self.env.step(self.actions.UP.value)\n k = self.env.step(self.actions.QUIT.value)\n print(\"Reward after action...\", self.env.episode_return)\n print(\"Reward after action...\", self.env.get_overall_performance())\n\n print(a,b,c,d,g,h,i,j,k)\n\n print(self.actions_dict)\n print(self.actions_dict.keys())\n\nenv = FriendFoeEnvironment()\nfoe = foe()\nfoe.init(env)\nfoe.run_experiment()\n\nprint(\"Observation_Matrix -->\")\n\nobservation= np.array([[35., 35., 35., 35., 35.],\n [35., 42., 78., 42., 35.],\n [35., 65., 78., 78., 35.],\n [35., 78., 78., 78., 35.],\n [35., 78., 78., 78., 35.],\n [35., 35., 35., 35., 35.]])\n\n\nprint(observation)\n\nprint(\"\")\n\nObservation_Size_FriendFoe = observation.shape\nprint (\"Observation_Size of FriendFoeEnvironment\")\nprint(\"********************************************\")\nprint(Observation_Size_FriendFoe)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ai_safety_gridworlds/experiments/foe.py","file_name":"foe.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472661296","text":"import numpy as np\n\n\n\nvec_bitstring_3 = np.vectorize(lambda x: np.binary_repr(x,width=3) )\n\n\ndef board_to_int(v):\n t = vec_bitstring_3(v)\n return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2)\n\ndef int_to_board(i):\n #i = '154444257952488798331863040'\n s = bin(int(i))[2:].zfill(108)\n v = np.array([int(s[i:i+3],2) for i in range(0,len(s),3)],dtype=int)\n return v.reshape((6,6))\n\n\ndef split_int(i):\n s = bin(int(i))[2:].zfill(108)\n s1 = s[:54]\n s2 = s[54:]\n i1 = int(s1,2)\n i2 = int(s2,2)\n return(i1,i2)\n\ndef combine_ints(i1,i2):\n s1 = bin(int(i1))[2:].zfill(54) \n s2 = bin(int(i2))[2:].zfill(54) \n return int(s1+s2,2)\n\n\n \n\n\n\n\n\n t = vec_bitstring_3(v)\n return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2)\n\n v = np.array([int(s[i:i+3],2) for i in range(0,len(s),3)],dtype=int)","sub_path":"Analytics/shared_code/OLD/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14981817","text":"import posixpath\nimport sys\n\nfrom docker import DockerClient\nfrom docker.errors import ImageNotFound\nfrom progress.bar import Bar\n\n\ndef split_tag(name, strip_namespace=False):\n if strip_namespace:\n name = posixpath.basename(name)\n\n suffix_parts = name.split(':')\n\n if len(suffix_parts) == 2:\n name, tag = suffix_parts\n else:\n name, = suffix_parts\n tag = 'latest'\n\n return name, tag\n\n\ndef pull_image(client, src):\n src_repo, src_tag = split_tag(src)\n bar = Bar()\n results = client.api.pull(src_repo, src_tag, stream=True, decode=True)\n\n print('')\n\n for result in results:\n status = result.get('status')\n\n if 'id' in result:\n if status == 'Downloading' or status == 'Extracting':\n output = '{id}: {status} {progress}'.format(**result)\n bar.writeln(output)\n elif status == 'Download complete' or status == 'Pull complete':\n bar.clearln()\n print('{id}: {status}'.format(**result))\n\n bar.finish()\n bar.clearln()\n\n return client.images.get(src)\n\n\ndef push_image(client, dest_repo, dest_tag):\n bar = Bar()\n results = client.images.push(dest_repo, dest_tag, stream=True, decode=True)\n\n print('')\n\n for result in results:\n status = result.get('status')\n\n if 'id' in result:\n if status == 'Pushing':\n output = '{id}: {status} {progress}'.format(**result)\n bar.writeln(output)\n elif status == 'Pushed':\n bar.clearln()\n print('{id}: {status}'.format(**result))\n\n bar.finish()\n bar.clearln()\n\n\ndef run(docker: DockerClient, options: dict) -> None:\n src_name, src_tag = split_tag(options['src'], strip_namespace=True)\n\n if options['dest']:\n dest_name, dest_tag = split_tag(\n options['dest'], strip_namespace=bool(options['namespace'])\n )\n else:\n dest_name = src_name\n dest_tag = src_tag\n\n dest_repo = posixpath.join(options['namespace'], dest_name)\n dest = '{repo}:{tag}'.format(repo=dest_repo, tag=dest_tag)\n\n print('Source: {src}'.format(src=options['src']))\n print('Dest: {dest}'.format(dest=dest))\n\n if options['dry_run']:\n return\n\n try:\n image = docker.images.get(options['src'])\n except ImageNotFound:\n if options['pull']:\n src_repo, _ = split_tag(options['src'])\n image = pull_image(docker, options['src'])\n else:\n sys.exit('image `%s` not found' % options['src'])\n\n image.tag(dest_repo, dest_tag)\n\n if options['push']:\n try:\n push_image(docker, dest_repo, dest_tag)\n print('Pushed {dest}'.format(dest=dest))\n except KeyboardInterrupt:\n pass\n","sub_path":"dockrane/commands/transfer_image.py","file_name":"transfer_image.py","file_ext":"py","file_size_in_byte":2795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"2635938","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 ('catalog', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CartItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cart_id', models.CharField(max_length=50)),\n ('date_added', models.DateTimeField(auto_now_add=True)),\n ('user_quantity', models.PositiveSmallIntegerField(default=1)),\n ('product_url', models.URLField(verbose_name=b'Product URL')),\n ('product_stock', models.ForeignKey(to='catalog.ProductStock')),\n ],\n options={\n 'ordering': ['date_added'],\n 'db_table': 'my_cart',\n },\n ),\n ]\n","sub_path":"cart/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"71383107","text":"#!/usr/bin/env python3\n\nfrom flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/first_call', methods=['POST'])\ndef first_callback():\n if request.method == 'POST':\n result = request.data\n id = request.args.get(\"id\")\n name = request.form.get('name')\n client_ip = request.remote_addr\n print('client IP:',client_ip)\n print('id:', id)\n print('name:', name)\n print('client data:',request.json)\n\n return \"OK\"\n\n\n@app.route('/second_call', methods=['GET'])\ndef second_callback():\n if request.method == 'GET':\n #....\n pass\n\n return \"OK\"\n\nif __name__ == '__main__':\n app.debug = True\n app.run(\"127.0.0.1\")\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554996749","text":"\"\"\"\nThis script is responsible for updating the local data based on the\nGoogle Drive information in this folder: https://drive.google.com/drive/u/3/folders/10XzxPdk6z5kF4-0fp-XSh_LEO6kzh1kE.\n\nCoaching staff is expected to update this folder (and all sub-folders) with correct XML files\nas they become available.\n\"\"\"\n\nfrom pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nimport google_auth_oauthlib.flow\n\n\n# Authorizes the app with Google - requires user interaction\n\nimport sys, os\nimport Constants\n# print(Constants.BASE_DIR)\n# print(Constants.BACKEND_DIR)\n\nsecrets = os.path.join(Constants.BACKEND_DIR, \"client_secrets.json\")\ncreds = os.path.join(Constants.BACKEND_DIR, \"mycreds.json\")\nxml_path = os.path.join(Constants.BACKEND_DIR, \"xml_data/\")\nsecrets = '/' + secrets\ncreds = '/' + creds\nxml_path = '/' + xml_path\n\n# print(secrets)\n# print(creds)\n# print(xml_path)\n\nGoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets\n#\n# flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(\n# secrets,\n# scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])\n#\n# flow.redirect_uri = 'https://www.example.com/oauth2callback'\n\n#\n# authorization_url, state = flow.authorization_url(\n# # Enable offline access so that you can refresh an access token without\n# # re-prompting the user for permission. Recommended for web server apps.\n# access_type='offline',\n# # Enable incremental authorization. Recommended as a best practice.\n# include_granted_scopes='true')\n\ngauth = GoogleAuth()\n# Try to load saved client credentials\ngauth.LoadCredentialsFile(creds)\nif gauth.credentials is None:\n # Authenticate if they're not there\n gauth.LocalWebserverAuth()\nelif gauth.access_token_expired:\n# Refresh them if expired\n gauth.Refresh()\nelse:\n # Initialize the saved creds\n gauth.Authorize()\n# Save the current credentials to a file\ngauth.SaveCredentialsFile(creds)\n\ndrive = GoogleDrive(gauth)\n# root_file_list = drive.ListFile({'q': \"'root' in parents and trashed=false\"}).GetList()\n# for obj in file_list:\n# print('title: %s, id: %s' % (file1['title'], file1['id']))\n# xml_files = root_file_list[0]\n# print(xml_files)\nimport os\nfrom populate_db import fill_all_xml\n\ndef fetch_new_xml():\n xml_folder_id = \"10XzxPdk6z5kF4-0fp-XSh_LEO6kzh1kE\"\n xml_file_list = drive.ListFile({'q': \"'{}' in parents and trashed=false\".format(xml_folder_id)}).GetList()\n new_files = False\n for dir in xml_file_list:\n # print('--title: {}, id: {}'.format(dir['title'], dir['id']))\n for data_file in drive.ListFile({'q': \"'{}' in parents and trashed=false\".format(dir[\"id\"])}).GetList():\n # print('----title: {}, id: {}'.format(data_file['title'], data_file['id']))\n # Download this file in the appropriate directory if it isn't already there\n filename = \"{}/{}/{}\".format(xml_path, dir['title'], data_file['title'])\n if not os.path.isfile(filename):\n new_files = True\n # print(\"------File doesn't exist, adding to database\")\n # Only download the file if it's not already in the data\n file_obj = drive.CreateFile({'id': data_file[\"id\"]})\n if not os.path.exists(\"{}/{}\".format(xml_path, dir['title'])):\n os.makedirs(\"{}/{}\".format(xml_path, dir['title']))\n file_obj.GetContentFile(filename) # Download file to proper directory\n\n if new_files:\n fill_all_xml()\n\n\ndef main():\n fetch_new_xml()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"app/xml_downloader.py","file_name":"xml_downloader.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370470494","text":"import sys\r\n\r\nfrom PyQt5 import QtWidgets, QtGui\r\n\r\nimport design\r\nimport mechanics\r\n\r\nclass App(QtWidgets.QMainWindow, design.Ui_MainWindow):\r\n def __init__(self):\r\n super().__init__()\r\n self.setupUi(self)\r\n # механика игры\r\n self.bank = mechanics.Bank(1000)\r\n self.deck = [mechanics.Card(value, color) for value in mechanics.VALUES for color in mechanics.COLORS]\r\n self.hand = []\r\n self.state = 'start'\r\n # графика для карт\r\n self.gcards = {}\r\n for i in range(len(self.deck)): \r\n self.gcards[self.deck[i]] = f':/res/cards/{str(i + 1)}.png'\r\n\r\n \r\n\r\n # коннектим кнопки и карты\r\n self.startGame.clicked.connect(self.main_button)\r\n self.card1.clicked.connect(self.card1_clicked)\r\n self.card2.clicked.connect(self.card2_clicked)\r\n self.card3.clicked.connect(self.card3_clicked)\r\n self.card4.clicked.connect(self.card4_clicked)\r\n self.card5.clicked.connect(self.card5_clicked)\r\n\r\n self.change_state()\r\n\r\n def change_state(self):\r\n if self.state == 'start':\r\n # механика\r\n self.marked_for_swap = []\r\n self.wageSize.setMinimum(0)\r\n self.wageSize.setMaximum(self.bank.money)\r\n self.wageSize.setEnabled(True)\r\n self.wageSize.valueChanged.connect(self.change_wage)\r\n self.deck, self.hand = mechanics.return_cards(self.deck, self.hand)\r\n # тексты\r\n self.earned.setText(\"\")\r\n self.yourMoney.setText(f'У тебя ${self.bank.money}. Крути для ставки!')\r\n self.startGame.setText('СТАРТ')\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(\":/res/cards/back.png\"))\r\n # смена состояния\r\n self.state = 'trade'\r\n\r\n elif self.state == 'trade':\r\n # механика\r\n self.bank.bets(self.wageSize.value())\r\n self.last_bet = self.bank.bet\r\n self.lcdNumber.display(self.bank.bet)\r\n self.wageSize.setEnabled(False)\r\n self.deck, self.hand = mechanics.give_cards(self.deck, self.hand)\r\n # тексты\r\n self.yourMoney.setText('Выбери карты для обмена')\r\n self.startGame.setText('ПОМЕНЯТЬ')\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(self.gcards[self.hand[i]]))\r\n # смена состояния\r\n self.state = 'retry'\r\n\r\n elif self.state == 'retry':\r\n # механика\r\n self.deck, self.hand = mechanics.swap_cards(self.deck, self.hand, self.marked_for_swap)\r\n result = mechanics.check_hand(self.hand)\r\n self.bank.returns(self.bank.bet * mechanics.REWARDS[result])\r\n self.marked_for_swap = []\r\n # тексты\r\n self.startGame.setText('ЕЩЕ РАЗ')\r\n self.yourMoney.setText(f'Твоя комбинация: {result}')\r\n self.earned.setText(f\"ТВОЙ ВЫИГРЫШ: {self.wageSize.value() * mechanics.REWARDS[result]}\")\r\n # изображения\r\n for i in range(mechanics.HAND_SIZE):\r\n self.cardplaces[i].setPixmap(QtGui.QPixmap(self.gcards[self.hand[i]]))\r\n # смена состояния\r\n self.state = 'start' if self.bank.money > 0 else 'lost'\r\n \r\n \r\n def main_button(self):\r\n if self.state == 'start':\r\n self.change_state()\r\n\r\n elif self.state == 'trade':\r\n self.change_state()\r\n\r\n elif self.state == 'retry':\r\n self.change_state()\r\n\r\n\r\n def change_wage(self):\r\n result = round(self.wageSize.value()/10) * 10 if round(self.wageSize.value()/10) * 10 <= self.bank.money else self.wageSize.value()\r\n self.wageSize.setValue(result)\r\n self.lcdNumber.display(result)\r\n\r\n def card1_clicked(self):\r\n self.card_clicked(0, self.card1)\r\n\r\n def card2_clicked(self):\r\n self.card_clicked(1, self.card2)\r\n\r\n def card3_clicked(self):\r\n self.card_clicked(2, self.card3)\r\n\r\n def card4_clicked(self):\r\n self.card_clicked(3, self.card4)\r\n\r\n def card5_clicked(self):\r\n self.card_clicked(4, self.card5)\r\n\r\n def card_clicked(self, card, cardplace):\r\n if self.state == 'retry':\r\n if card in self.marked_for_swap:\r\n cardplace.setPixmap(QtGui.QPixmap(self.gcards[self.hand[card]]))\r\n self.marked_for_swap.remove(card)\r\n print(str(self.marked_for_swap),'unmarked')\r\n else:\r\n cardplace.setPixmap(QtGui.QPixmap(\":/res/cards/back.png\"))\r\n self.marked_for_swap.append(card)\r\n print(str(self.marked_for_swap),'marked')\r\n \r\ndef main():\r\n app = QtWidgets.QApplication(sys.argv)\r\n window = App()\r\n window.showNormal()\r\n app.exec_()\r\n\r\nif __name__ == '__main__':\r\n print(__file__)\r\n main()","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"455515390","text":"\"\"\"\nFront end for duckbill\n\"\"\"\nfrom __future__ import with_statement\n__ver__=\"$Id: FrontEndApp.py,v 1.30 2007/03/30 00:35:53 sabren Exp $\"\n\nimport duckbill\nimport sixthday\nimport zebra\nimport weblib\nfrom duckbill import Account, Event, Subscription\nfrom contextlib import contextmanager\n\n\n\nclass FrontEndApp(sixthday.AdminApp):\n\n def act_(self):\n self.create_account()\n\n def jumpto_accounts(self, accounts, searchOnly):\n if len(accounts) == 0:\n raise IndexError(\"not found\")\n elif len(accounts) == 1 and not searchOnly:\n self.input[\"ID\"] = accounts[0].ID\n self.show_account()\n else:\n self.write(\"

search results:

\")\n self.write(\"
    \")\n for a in accounts:\n self.write('
  • ')\n self.write('%s (%s)' % (a.account, a.status))\n self.write('
  • ')\n self.write(\"
      \")\n\n\n def act_jump(self):\n if self.input.get(\"jumpto\"):\n jump = self.input[\"jumpto\"]\n try:\n if jump.startswith(\"#\"):\n self.input[\"ID\"]=self.clerk.match(Event,\n refnum=jump[1:])[0].ID\n self.edit_event()\n \n\n elif jump.count(\" \"):\n fn, ln = jump.split(\" \", 1)\n kw = {}\n if fn != \"*\": kw['fname']=fn\n if ln != \"*\": kw['lname']=ln\n res = self.clerk.match(Account, **kw)\n elif jump.count(\"@\"):\n res = self.clerk.match(Account, email=jump)\n else:\n res = self.clerk.match(Account, account=jump)\n \n if not res:\n subs = self.clerk.match(Subscription, username=jump)\n res = [s.account for s in subs]\n\n if res:\n self.jumpto_accounts(res, self.input.has_key('searchOnly'))\n else:\n self.write(\"%s sub/acct not found\" % jump)\n \n except IndexError:\n self.write(\"%s not found\" % jump)\n \n \n else:\n self.write(\"no value given for jump\")\n \n\n def requireAccountID(self):\n assert self.model.get(\"accountID\"), \"no accountID given\"\n\n\n ### accounts ############################################\n\n def show_account(self):\n self.generic_show(Account, \"sho_account\")\n\n def edit_account(self):\n self.generic_show(Account, \"frm_account\")\n\n def create_account(self):\n self.generic_create(Account, \"frm_account\")\n\n def save_account(self):\n acct = self.generic_save(Account)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(acct.ID))\n\n @contextmanager\n def accountUpdate(self, paramName=\"accountID\"):\n try:\n assert self.input.get(paramName), \"give me an accountID\"\n acc = self.clerk.fetch(Account, ID=int(self.input[paramName]))\n yield acc\n except:\n raise\n else:\n acc = self.clerk.store(acc)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(acc.ID))\n\n def act_close_account(self):\n assert self.input.get(\"reason\"), \"give me a reason\"\n with self.accountUpdate(paramName='ID') as acc:\n acc.close(self.input[\"reason\"])\n assert acc.status == 'closed', \"??!\"\n\n def act_catchup(self):\n with self.accountUpdate() as acc:\n acc.postCharges()\n\n def act_stop_autobill(self):\n with self.accountUpdate() as acc:\n acc.postCharges()\n acc.lastfour=''\n acc.cardinfo=None\n acc.autobill=False\n\n def act_grace(self):\n with self.accountUpdate() as acc:\n acc.grace(why=self.input['note'], untilWhen=self.input['expires'])\n\n\n ### subscriptions ############################################\n\n\n def create_subscription(self):\n self.requireAccountID()\n self.generic_create(Subscription, \"frm_subscription\")\n\n def edit_subscription(self):\n self.generic_show(Subscription, \"frm_subscription\")\n \n def save_subscription(self):\n if self.input.get(\"ID\"):\n s = self.generic_save(Subscription)\n else:\n self.requireAccountID()\n a = self.clerk.fetch(Account, ID=self.model[\"accountID\"])\n s = self._getInstance(Subscription)\n s.account = a\n s = self.clerk.store(s)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(s.account.ID))\n \n ### events ############################################\n\n def create_event(self):\n self.requireAccountID() \n self.generic_create(Event, \"frm_event\")\n\n def edit_event(self):\n self.generic_show(Event, \"frm_event\")\n\n #@TODO: save_event and save_subscription are almost identical!\n def save_event(self):\n if self.input.get(\"ID\"):\n e = self.generic_save(Event)\n else:\n self.requireAccountID()\n a = self.clerk.fetch(Account,ID=self.model[\"accountID\"])\n e = self._getInstance(Event)\n e.account = a\n e = self.clerk.store(e)\n self.redirect(\"index.py?action=show&what=account&ID=%i\"\n % int(e.account.ID))\n\n def getCheckedEvents(self):\n eids = self.input.get(\"eventID\", ())\n if type(eids) == tuple:\n ids = eids\n else:\n ids = (eids,)\n return [self.clerk.fetch(Event, ID=eid) for eid in ids]\n\n def jumpToAccount(self, accID):\n self.redirect(\"index.py?action=show&what=account&ID=%s\" % accID)\n\n def act_void(self):\n for e in self.getCheckedEvents():\n e.event = 'void'\n e.note = \"void: \" + e.note\n self.clerk.store(e)\n self.jumpToAccount(self.input[\"accountID\"])\n\n def die(self, msg):\n assert 0, msg # @TODO: fix this\n\n def fetchAccount(self, account):\n try:\n return self.clerk.fetch(Account, account=account)\n except LookupError:\n self.die(\"couldn't find destination account\") \n\n def act_move_events(self):\n acc = self.fetchAccount(self.input[\"dest_account\"])\n for e in self.getCheckedEvents():\n acc.events << e\n self.clerk.store(acc)\n self.jumpToAccount(acc.ID)\n","sub_path":"duckbill/trunk/duckbill/FrontEndApp.py","file_name":"FrontEndApp.py","file_ext":"py","file_size_in_byte":6719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302976911","text":"import requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport wget\nimport os\nfrom os import path\nimport ssl\nimport datetime\n\nfrom gcloud import storage\nfrom google.cloud import storage\n\n\nclient_secret = input('Put in Path/to/client_secrets.json: ')\nDestination_Folder = input('Path/to/Working/folder/: ')\n\nstorage_client = storage.Client.from_service_account_json(client_secret)\nbucketName = input('GCS bucket name: ')\nbucket = storage_client.get_bucket(bucketName)\n\n# To be able to track and differentiate between the different times of running\n# the script, the timestamp is used to create a folder.\nnow = datetime.datetime.now()\nfolder_id = now.strftime('%Y%m%d' + '-' + '%H%M%S')\n\ndest_folder = Destination_Folder + folder_id + '/'\n\n# product_search.csv and products_catalog.csv are automatically created\n# product_search.csv is the file that is used with the Product Search API\n# products_catalog.csv contains all the information scraped on the image\nproduct_search = Destination_Folder + 'product_search.csv'\nproducts_catalog = Destination_Folder + 'products_catalog.csv'\n\nos.makedirs(dest_folder, exist_ok=True)\n\nimage_store = 'gs://prod-search-tool/'\n\nif (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)):\n ssl._create_default_https_context = ssl._create_unverified_context\n\n# To collect which page to scrape from\nurl = input('What page will you scrape from: ')\nhtml = requests.get(url)\nsoup = BeautifulSoup(html.text, 'html.parser')\n\n\npage = soup.body\npageTags = soup.find_all(\"div\", {\"class\": \"product\"})\nos.makedirs(dest_folder, exist_ok=True)\n\n\n# This allows to download to the local computer\ndef dld(dest_folder, src):\n try:\n wget.download(src, out=dest_folder)\n except Exception:\n print(Exception)\n #continue\n\n# This creates the header of the product_search.csv\ndef product_search_header():\n with open(Destination_Folder + 'product_search.csv', 'w') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow(['image_uri', 'image_id', 'product_set_id', 'product_id', 'product_category', \\\n 'product_display_name', 'labels', 'bounding_poly'])\n\n# This creates the header of the products_catalog.csv\ndef products_catalog_header():\n with open(Destination_Folder + 'products_catalog.csv', 'w') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow(['imageUrl', 'image_id', 'product_set_id', 'productId', 'product_category', \\\n 'name', 'labels', 'bounding_poly', 'src', 'productPage', 'availability', 'gcsLink'])\n\n# This downloads the images to the Google Bucket\ndef gdld(product_id, src, bucket, bucketName):\n #bucket = storage_client.get_bucket(bucket)\n try:\n bucket.blob(product_id).upload_from_string(src)\n print('gs://' + bucket.blob(product_id).path_helper(bucketName, filename))\n return 'gs://' + bucket.blob(product_id).path_helper(bucketName, filename)\n except:\n print('Didn\\'t upload')\n\n# This uploads a file to the Google Bucket from the local computer.\n# In this case, it will be for the product_search.csv and products_catalog.csv files\ndef gdld_up(filename, bucket):\n #bucket = storage_client.get_bucket(bucket)\n print('Uploading ' + filename)\n try:\n bucket.blob(filename).upload_from_filename(Destination_Folder + filename)\n print(bucket.blob(filename).path(bucket, filename))\n return bucket.blob(filename).path(bucket, filename)\n except:\n print(filename + ' doesn\\'t exist on local computer')\n\n# This downloads a file from the Google Bucket to the local computer.\n# In this case, it will be for the product_search.csv and products_catalog.csv files\ndef gdld_dn(filename, bucket):\n #bucket = storage_client.get_bucket(bucket)\n print('Downloading ' + filename)\n blob = bucket.get_blob(filename)\n blob.download_to_filename(Destination_Folder + filename)\n\n# This checks if the file exists in the bucket already.\n# Usually before downloading to the local computer\ndef gdld_chk(filename, bucket):\n print('Checking for ' + filename)\n #bucket = storage_client.get_bucket(bucket)\n print(bucket.get_blob(filename))\n return bucket.get_blob(filename)\n\n\n# Check if the file is in the bucket. If it is, download, else, indicate so that the\n# file can be created locally.\nprint()\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n if gdld_chk(filename, bucket) == None:\n print(filename + ' not in GCS bucket')\n else:\n print('Downloading ' + filename + ' from GCS bucket')\n gdld_dn(filename, bucket)\n print()\n\nprint()\nfor page in pageTags:\n container_a = page.find('a')\n container_img = container_a.find('img')\n\n container_href = container_a.get('href')\n product_id = container_img.get('data-pid')\n #image_uri = image_store + product_id + '.jpg'\n image_id = ''\n product_set_id = 'athome' # merchant_id\n product_id = container_img.get('data-pid')\n product_category = 'general-v1' # category\n product_display_name = container_img.get('title')\n labels = ''\n bounding_poly = ''\n src = container_img.get('src')\n product_page = 'https://athome.com' + container_href\n product_availability = container_img.get('data-stock')\n\n image_uri = gdld(product_id, src, bucket, bucketName)\n\n\n if (path.exists(product_search) == False):\n print('no existing product_search file. Creating...')\n product_search_header()\n\n with open(Destination_Folder + 'product_search.csv', 'a') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow([image_uri, image_id, product_set_id, product_id, product_category, \\\n product_display_name, labels, bounding_poly])\n\n\n if (path.exists(products_catalog) == False):\n print('no existing products_catalog file. Creating...')\n products_catalog_header()\n\n with open(Destination_Folder + 'products_catalog.csv', 'a') as csvfile:\n tagwriter = csv.writer(csvfile, delimiter=',')\n tagwriter.writerow([image_uri, image_id, product_set_id, product_id, product_category, \\\n product_display_name, labels, bounding_poly, src, product_page, \\\n product_availability])\n\n print('-'*50)\n\nprint()\n# Upload the files to GCS\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n gdld_up(filename, bucket)\n\nprint()\n# Confirm that the files were properly uploaded.\nfor filename in ['product_search.csv', 'products_catalog.csv']:\n gdld_chk(filename, bucket)\n\nprint('Check bucket for new images. Confirm complete')\n\n\n\n","sub_path":"imageDownloader8.py","file_name":"imageDownloader8.py","file_ext":"py","file_size_in_byte":6718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421352200","text":"\"\"\"ArticleBlog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,re_path\nfrom ArticleBlog.views import *\n# from ArticleBlog.views import index,introduce,index1\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('index/',index),\n re_path(r'^$',index),\n re_path(r'page/(?P\\d{1,2})',page_list),\n # re_path(r'^introduce/(?P\\w+)/(?P\\d{1,2})$',introduce)\n path('tv/',template_variable),\n path('tl/',template_label),\n]\n","sub_path":"ArticleBlog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211993493","text":"import tensorflow as tf \nfrom tools.lazy_property import lazy_property\n\nclass SoftMaxModel(object):\n def __init__(self):\n self.inputs = tf.placeholder('float32', (None, 4), name=\"inputs\")\n self.labels = tf.placeholder('float32', (None, 3), name=\"labels\")\n self.learning_rate = 0.01\n self.prediction\n self.infer\n\n @lazy_property\n def prediction(self):\n fully_connect_layer = tf.contrib.layers.fully_connected(\n inputs=self.inputs,\n num_outputs=3,\n activation_fn = None,\n weights_initializer = tf.contrib.layers.xavier_initializer(),\n biases_initializer = tf.contrib.layers.xavier_initializer(), \n )\n return fully_connect_layer\n\n @lazy_property\n def loss(self):\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.labels, logits=self.prediction), name=\"loss\")\n return loss\n\n @lazy_property\n def optimizer(self):\n optimze = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.loss)\n return optimize\n\n @lazy_property\n def infer(self):\n result = tf.nn.softmax(self.prediction, name=\"softmax\")\n inference = tf.argmax(result, 1, name=\"infer\")\n return inference","sub_path":"cha4_test/3_softmax/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519117159","text":"#!/usr/bin/env python3\nimport rospy\nfrom time import sleep\nfrom std_msgs.msg import Float64, Bool\nfrom blobs_msgs.msg import BlobArray\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\npub_vel = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n\nmove_flag = True\nrotate_flag = True\nalr_park = False\nvis_park = False\nparking = False\nAuto = 0\nintegral = 0\nx = 0\ny = 0\ntime = 0.0\ndist = 0\nrot = 0\nsx = 0\nsy = 0\ndef cbError(error):\n\tglobal integral, move_flag, rotate_flag, parking\n\tif move_flag and not parking:\n\t\tvelocity = Twist()\n\t\tproportional = 0.0037*error.data\n\t\tintegral = 0.000005*error.data\n\t\tup = proportional + integral\n\t\tvelocity.angular.z = up\n\t\tif rotate_flag:\n\t\t\tvelocity.linear.x = 0.08 - 0.05*abs(up)\n\t\telse:\n\t\t\tvelocity.linear.x = 0.0\n\t\tpub_vel.publish(velocity)\n\ndef visError(msg):\n\tglobal move_flag, rotate_flag, alr_park, vis_park, parking, x, y, time\n\tidd = msg.blobs[0].id\n\tif not parking:\n\t\tif idd == 0 and not move_flag:\n\t\t\tmove_flag = True\n\t\telif idd == 1:\n\t\t\tmove_flag = False\n\t\t\tvstop = Twist()\n\t\t\tvstop.angular.z = 0.0\n\t\t\tvstop.linear.x = 0.0\n\t\t\tpub_vel.publish(vstop)\n#\t\telif idd == 2:\n#\t\t\ttime = rospy.get_time()\n#\t\t\tif y > -0.6 and x > 1.0 and not alr_park and not vis_park:\n#\t\t\t\trospy.loginfo('parking!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n#\t\t\t\tvis_park = True\n#\t\t\t\talr_park = True\n#\t\telif idd == 3:\n#\t\t\tif x < -1:\n#\t\t\t\tmove_flag = False\n#\t\t\t\trospy.loginfo('labirint')\n\ndef Addons(msg):\n\tglobal x, y, sx, sy\n\ty = msg.pose.pose.position.y - sy - 1.7\n\tx = msg.pose.pose.position.x - sx\n\tif sx == 0:\n\t\trospy.loginfo('ss')\n\t\tsx = x\n\t\tsy = y + 1.7\n\ndef Distance(msg):\n\tglobal dist\n\tdist = msg.ranges\n\ndef loop():\n\tglobal time, vis_park, move_flag, rotate_flag, parking, flag6, dist, Auto\n\trosy.loginfo('NOOOOO!')\n\tif not parking and vis_park:\n\t\tif 1.8 > rospy.get_time() - time > 1.25 and Auto != 1:\n\t\t\trospy.loginfo(dist[0])\n\t\t\tif dist[0] < 1.0:\n\t\t\t\tAuto = 1\n\t\t\telse:\n\t\t\t\tAuto = 2\n\t\tif rospy.get_time() - time > 2:\n\t\t\tvis_park = False\n\t\t\tparking = True\n\t\t\tParking()\n\t\t\tparking = False\n\ndef Parking():\n\tglobal dist, Auto\n\tv_stop, v_right, v_left, v_go = Twist(), Twist(), Twist(), Twist()\n\tv_stop.angular.z = 0.0\n\tv_stop.linear.x = 0.0\n\tv_go.angular.z = 0.0\n\tv_go.linear.x = 0.15\n\tv_right.angular.z = -0.4\n\tv_right.linear.x = 0.0\n\tv_left.angular.z = 0.4\n\tv_left.linear.x = 0.0\n\trospy.loginfo(Auto)\n\tsr = 1\n\tst = 2\n\tpub_vel.publish(v_left)\n\tsleep(sr)\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\tif Auto == 2:\n\t\trospy.loginfo('машинка 1')\n\t\tParking2()\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\tif Auto == 1:\n\t\trospy.loginfo('машинка 2')\n\t\tParking2()\n\tpub_vel.publish(v_go)\n\tsleep(st)\n\trospy.loginfo('vse')\n\ndef Parking2():\n\tv_stop, v_right, v_left, v_go = Twist(), Twist(), Twist(), Twist()\n\tv_stop.angular.z = 0.0\n\tv_stop.linear.x = 0.0\n\tv_go.angular.z = 0.0\n\tv_go.linear.x = 0.15\n\tv_right.angular.z = -0.4\n\tv_right.linear.x = 0.0\n\tv_left.angular.z = 0.4\n\tv_left.linear.x = 0.0\n\tsr = 3\n\tsm = 1.7\n\tpub_vel.publish(v_right)\n\tsleep(sr)\n\tpub_vel.publish(v_go)\n\tsleep(sm)\n\tpub_vel.publish(v_stop)\n\trospy.sleep(1)\n\tpub_vel.publish(v_left)\n\tsleep(sr * 2)\n\tpub_vel.publish(v_go)\n\tsleep(sm)\n\tpub_vel.publish(v_right)\n\tsleep(sr)\n\tpub_vel.publish(v_stop)\n\nif __name__ == '__main__':\n\trospy.init_node('line_control')\n\trospy.Subscriber('/error_lane', Float64, cbError, queue_size=1)\n\trospy.Subscriber('/new_blobs', BlobArray, visError, queue_size=1)\n\trospy.Subscriber('/odom', Odometry, Addons, queue_size=1)\n\trospy.Subscriber('/scan', LaserScan, Distance, queue_size=1)\n\twhile not rospy.is_shutdown():\n\t\ttry:\n\t\t\trospy.sleep(0.05)\n#\t\t\tloop()\n\t\texcept KeyboardInterrupt:\n\t\t\tbreak\n","sub_path":"line_controll_Adrian.py","file_name":"line_controll_Adrian.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"650468639","text":"from django import forms\nfrom main_gusto.models import *\n\n\nclass BannerForm(forms.ModelForm):\n\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput(attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n\n class Meta():\n model = Banner\n fields = ('title', 'photo', 'is_visible')\n\n\nclass CategoryForm(forms.ModelForm):\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n category_order = forms.IntegerField(widget=forms.NumberInput(attrs={ 'placeholder': 'Номер', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n is_special = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'special',}))\n\n class Meta():\n model = Category\n fields = ('title', 'category_order', 'is_visible', 'is_special')\n\n\nclass DishForm(forms.ModelForm):\n\n categories = Category.objects.order_by('title')\n CATEGORY_CHOICES = []\n for item in categories:\n CATEGORY_CHOICES.append((item, item.title))\n\n CHOICES = [('True', 'Да'),\n ('False', 'Нет')]\n\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n\n category = forms.ModelChoiceField(queryset=categories)\n\n description = forms.CharField(max_length=600,\n widget=forms.Textarea(\n attrs={'name': 'desc', 'id': 'desc', 'class': 'form-control',\n 'rows': '4', 'placeholder': 'Описание',\n 'required': 'required'}))\n price = forms.DecimalField(widget=forms.NumberInput(attrs={ 'placeholder': 'Цена', 'class': 'form-control',\n 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n is_visible = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(\n attrs={'name': 'visible'}))\n\n class Meta():\n model = Dish\n fields = ('title', 'category', 'description', 'price', 'photo', 'is_visible')\n\n\nclass EventForm(forms.ModelForm):\n\n title = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'type': 'text', 'id': 'title', 'class': 'form-control',\n 'placeholder': 'Название', 'required': 'required'}))\n photo = forms.ImageField(widget=forms.ClearableFileInput( attrs={ 'placeholder': 'Фото', 'class': 'form-control',\n 'required': 'required'}))\n description = forms.CharField()\n event_date = forms.DateInput()\n event_time = forms.TimeInput()\n price = forms.DecimalField()\n\n class Meta():\n model = Events\n fields = ('title', 'photo', 'description', 'event_date', 'event_time', 'price')\n","sub_path":"menu_format/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"197837122","text":"from typing import List\nfrom functools import reduce\n\nif __name__ == '__main__':\n floats: List[float] = [12.3554, 4.02, 5.777, 2.12, 3.13, 4.44, 11.0001]\n names: List[str] = [\"Vanes\", \"Alen\", \"Jana\", \"William\", \"Richards\", \"Joy\"]\n numbers: List[int] = [22, 33, 10, 6894, 11, 2, 1]\n\n new_floats = map(lambda x: round(x ** 3, 3), floats)\n print(list(new_floats))\n new_names = filter(lambda x: len(x) > 4, names)\n print(list(new_names))\n new_numbers = reduce(lambda x, y: x * y, numbers)\n print(new_numbers)\n","sub_path":"Module30/01_new_lists/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"603247350","text":"#!/usr/bin/env python3\n\nimport math\nimport time\n\nimport magicbot\nimport wpilib\n\nfrom ctre import CANTalon\nfrom robotpy_ext.control.button_debouncer import ButtonDebouncer\nfrom networktables import NetworkTables\n\nfrom components.chassis import Chassis\nfrom components.gears import GearAligner, GearDepositor\nfrom components.range_finder import RangeFinder\nfrom components.vision import Vision\nfrom components.winch import Winch\nfrom automations.filters import RangeFilter, VisionFilter\nfrom automations.manipulategear import ManipulateGear\nfrom automations.profilefollower import ProfileFollower\nfrom automations.winch import WinchAutomation\nfrom utilities.bno055 import BNO055\n\n\nclass Robot(magicbot.MagicRobot):\n # Sensors\n range_finder = RangeFinder\n vision = Vision\n vision_filter = VisionFilter\n\n # Chassis must come before RangeFilter\n # ProfileFollower should come before Chassis\n profilefollower = ProfileFollower\n chassis = Chassis\n range_filter = RangeFilter\n\n # Other automations\n manipulategear = ManipulateGear\n winch_automation = WinchAutomation\n\n # Other actuators\n gear_aligner = GearAligner\n gear_depositor = GearDepositor\n winch = Winch\n\n def createObjects(self):\n '''Create motors and stuff here'''\n\n # Objects that are created here are shared with all classes\n # that declare them. For example, if I had:\n # self.elevator_motor = wpilib.TalonSRX(2)\n # here, then I could have\n # class Elevator:\n # elevator_motor = wpilib.TalonSRX\n # and that variable would be available to both the MyRobot\n # class and the Elevator class. This \"variable injection\"\n # is especially useful if you want to certain objects with\n # multiple different classes.\n\n # create the imu object\n self.bno055 = BNO055()\n\n # the SmartDashboard network table allows you to send\n # information to a html dashboard. useful for data display\n # for drivers, and also for plotting variables over time\n # while debugging\n self.sd = NetworkTables.getTable('SmartDashboard')\n\n # create the joystick and gamepad on the appropriate ports\n self.joystick = wpilib.Joystick(0)\n self.gamepad = wpilib.XboxController(1)\n\n # create the button debouncers, used to stop a single press from being\n # counted every control loop iteration\n self.joystick_buttons = [ButtonDebouncer(\n self.joystick, buttonnum=i, period=0.5) for i in range(13)]\n self.gamepad_buttons = [ButtonDebouncer(\n self.gamepad, buttonnum=i, period=0.5) for i in range(13)]\n\n self.drive_motor_a = CANTalon(2)\n self.drive_motor_b = CANTalon(5)\n self.drive_motor_c = CANTalon(4)\n self.drive_motor_d = CANTalon(3)\n self.gear_aligner_motor = CANTalon(14)\n\n # create the winch motor; set it so that it pulls the robot up\n # the rope for a positive setpoint\n self.winch_motor = CANTalon(11)\n self.winch_motor.setInverted(True)\n\n self.rope_lock_solenoid = wpilib.DoubleSolenoid(forwardChannel=0,\n reverseChannel=1)\n\n self.gear_push_solenoid = wpilib.Solenoid(2)\n self.gear_drop_solenoid = wpilib.Solenoid(3)\n self.gear_drop_solenoid.set(True)\n\n # set the throttle to be sent to the chassis\n self.throttle = 1.0\n # set the direction of the forward/back movement of the robot\n self.direction = 1.0\n\n self.range_finder_counter = wpilib.Counter(0, mode=wpilib.Counter.Mode.kPulseLength)\n # dio for the vision LEDs to be switched on or off\n self.led_dio = wpilib.DigitalOutput(1)\n\n self.compressor = wpilib.Compressor()\n\n def putData(self):\n # update the data on the smart dashboard\n\n # put the inputs to the dashboard\n self.sd.putNumber(\"gyro\", self.bno055.getHeading())\n # if self.manipulategear.current_state == \"align_peg\":\n self.sd.putNumber(\"range\", self.range_finder.getDistance())\n self.sd.putNumber(\"climb_current\", self.winch_motor.getOutputCurrent())\n self.sd.putNumber(\"rail_pos\", self.gear_aligner.get_rail_pos())\n self.sd.putNumber(\"raw_rail_pos\", self.gear_aligner_motor.getPosition())\n self.sd.putNumber(\"error_differential\",\n self.drive_motor_a.getClosedLoopError()\n - self.drive_motor_c.getClosedLoopError())\n self.sd.putNumber(\"velocity\", self.chassis.get_velocity())\n self.sd.putNumber(\"left_speed_error\", self.drive_motor_a.getClosedLoopError())\n self.sd.putNumber(\"right_speed_error\", self.drive_motor_c.getClosedLoopError())\n self.sd.putNumber(\"x_throttle\", self.chassis.inputs[0])\n self.sd.putNumber(\"z_throttle\", self.chassis.inputs[2])\n self.sd.putNumber(\"filtered_x\", self.vision_filter.x)\n self.sd.putNumber(\"filtered_dx\", self.vision_filter.dx)\n self.sd.putNumber(\"vision_filter_x_variance\", self.vision_filter.filter.P[0, 0])\n self.sd.putNumber(\"vision_filter_dx_variance\", self.vision_filter.filter.P[1, 1])\n self.sd.putNumber(\"vision_filter_covariance\", self.vision_filter.filter.P[0, 1])\n self.sd.putNumber(\"filtered_range\", self.range_filter.filter.x_hat[0, 0])\n self.sd.putNumber(\"range_filter_variance\", self.range_filter.filter.P[0, 0])\n self.sd.putNumber(\"time\", time.time())\n self.sd.putNumber(\"vision_predicted_range\", self.range_filter.vision_predicted_range())\n self.sd.putNumber(\"vision_predicted_target_dist\", self.vision.derive_target_range())\n\n def teleopInit(self):\n '''Called when teleop starts; optional'''\n self.sd.putString(\"state\", \"stationary\")\n self.gear_aligner.reset_position()\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n self.profilefollower.stop()\n self.winch.enable_compressor()\n self.vision.enabled = False\n self.logger.info(\"TELEOP INIT RANGE: %s\" % (self.range_finder.getDistance()))\n self.logger.info(\"TELEOP INIT FILTER RANGE: %s\" % (self.range_filter.range))\n\n def disabledInit(self):\n # prevent pyntlogger from continuing to log if it is running\n self.sd.putBoolean(\"log\", False)\n\n def disabledPeriodic(self):\n self.putData()\n self.vision_filter.execute()\n self.range_filter.execute()\n\n def teleopPeriodic(self):\n '''Called on each iteration of the control loop'''\n self.putData()\n\n # enable the compressor only if the chassis is moving below the\n # threshold speed, and the winch is not running, in order to prevent\n # brownouts\n self.compressor.setClosedLoopControl(self.chassis.compressor_enabled\n and self.winch.compressor_enabled)\n\n # check for button inputs\n\n # force restart or start of the gear state machine\n with self.consumeExceptions():\n if self.gamepad_buttons[8].get() or self.joystick_buttons[1].get():\n self.manipulategear.engage(force=True)\n\n # force restart or start of the winch state machine\n with self.consumeExceptions():\n if self.gamepad_buttons[7].get() or self.joystick_buttons[3].get():\n self.winch_automation.engage(force=True)\n\n # tell pyntlogger that we want to start logging\n with self.consumeExceptions():\n if self.joystick_buttons[7].get():\n self.sd.putBoolean(\"log\", True)\n\n # reset the gear & winch state machines\n with self.consumeExceptions():\n if self.joystick_buttons[2].get():\n if self.manipulategear.is_executing:\n self.manipulategear.done()\n self.gear_aligner.reset_position()\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n\n # force stop the winch state machine and winch motor\n with self.consumeExceptions():\n if self.joystick_buttons[4].get():\n if self.winch_automation.is_executing:\n self.winch_automation.done()\n self.winch.rotate(0)\n\n # force the winch motor to spin at max speed, and close the piston\n # that holds the rope in place\n with self.consumeExceptions():\n if self.joystick_buttons[5].get():\n if self.winch_automation.is_executing:\n self.winch_automation.done()\n self.winch.rotate(1.0)\n self.winch.close_piston()\n\n # toggle the position of the winch piston\n with self.consumeExceptions():\n if self.joystick_buttons[6].get():\n self.winch.locked = not self.winch.locked\n\n # retract and lock the gear bucket\n with self.consumeExceptions():\n if self.joystick_buttons[12].get():\n self.gear_depositor.retract_gear()\n self.gear_depositor.lock_gear()\n\n # push the gear bucket forward while shutting it\n with self.consumeExceptions():\n if self.joystick_buttons[10].get() or self.gamepad_buttons[1].get():\n self.manipulategear.engage(initial_state=\"forward_closed\", force=True)\n\n # Set direction and speed of control inputs from driver when specific\n # buttons are pressed\n if (not self.gamepad.getRawButton(5) and\n not self.gamepad.getRawButton(6) and\n not self.gamepad.getRawAxis(3) > 0.9):\n # normal operating mode\n self.throttle = 1\n self.direction = 1\n self.sd.putString(\"camera\", \"front\")\n elif self.gamepad.getRawButton(5):\n # reverse direction of translation\n self.throttle = 1\n self.direction = -1\n self.sd.putString(\"camera\", \"back\")\n elif self.gamepad.getRawButton(6):\n # slow down\n self.throttle = 0.5\n self.direction = 1\n self.sd.putString(\"camera\", \"back\")\n elif self.gamepad.getRawAxis(3) > 0.9:\n # slow down and reverse direction of translation\n self.throttle = 0.5\n self.direction = -1\n self.sd.putString(\"camera\", \"back\")\n\n # POV buttons on joystick move gear rail left and right for alignment\n # with chute\n if self.joystick.getPOV() == 90:\n if not self.manipulategear.is_executing:\n self.gear_aligner.move_right()\n elif self.joystick.getPOV() == 270:\n if not self.manipulategear.is_executing:\n self.gear_aligner.move_left()\n\n if 1.5 < abs(self.chassis.get_velocity()) and not self.manipulategear.is_executing:\n self.gear_aligner.set_position(0)\n\n # set control inputs to chassis after rescaling\n linear_input = (\n self.direction * -rescale_js(\n self.gamepad.getRawAxis(1), deadzone=0.05, exponential=30))\n # rotational speed. compensate for reduced throttle by increasing\n # rate, so that when linear speed is reduced, rotational input stays\n # the same for the drivers\n angular_input = -rescale_js(\n self.gamepad.getRawAxis(4), deadzone=0.05, exponential=30,\n rate=0.3 if self.throttle == 1 else 1/self.throttle)\n # y axis (left right) input is 0, as a tank drive can not translate\n # sideways\n self.chassis.inputs = [linear_input, 0, angular_input, self.throttle]\n\n # allow co-driver to manually turn on the vision LEDs\n self.vision.led_on = self.joystick.getRawButton(11)\n\n\n# utility function to rescale joystick inputs and make them exponential rather\n# than linear\ndef rescale_js(value, deadzone=0.0, exponential=0.0, rate=1.0):\n value_negative = 1.0\n if value < 0:\n value_negative = -1.0\n value = -value\n # Cap to be +/-1\n if abs(value) > 1.0:\n value /= abs(value)\n # Apply deadzone\n if abs(value) < deadzone:\n return 0.0\n elif exponential == 0.0:\n value = (value - deadzone) / (1 - deadzone)\n else:\n a = math.log(exponential + 1) / (1 - deadzone)\n value = (math.exp(a * (value - deadzone)) - 1) / exponential\n return value * value_negative * rate\n\n\nif __name__ == '__main__':\n wpilib.run(Robot)\n","sub_path":"robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":12396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"223608177","text":"import random as r\ncnt1=1000000\ncnt2 = 0\n\nfor i in range(cnt1):\n x=r.random()\n y=r.random()\n if (x**2+y**2)<1 :\n cnt2+=1\nprint(4.0*cnt2/cnt1)\n\n\n\n","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124032905","text":"# -*- coding: utf-8 -*-\n\"\"\"\nBenenMatch_NL spider created on the top of ATSSpider\n\nscrapy crawl benenmatch_nl -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.banenmatch.nl/job_search/\"\n\nSeed URL:\n http://www.banenmatch.nl/job_search/\n\"\"\"\n\nfrom re import compile\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import ConvertDateString, Prefix, Replace\n\npattern = {\n 'date': compile(r'(\\d{1,2}-\\d{1,2}-\\d{4})'),\n 'ref_number': compile(r'vacature-(\\d+)'),\n}\n\n\nclass BenenMatch_NL(ATSSpider):\n\n name = 'benenmatch_nl'\n\n def parse(self, response):\n \"\"\"\n Parse each job urls via GET method\n \"\"\"\n sel = Selector(response)\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//div[@id=\"searchresult\"]/h2/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n\n for h2 in sel.xpath(\n '//div/div[@id=\"searchresult\"]/h2[@class=\"jobtitle\"]'\n ):\n href = h2.xpath('./a/@href').extract()\n if href:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'company': h2.xpath(\n './following-sibling::div[@class=\"region-search\" and position() = 1]/text()'\n ).extract(),\n 'raw_data': h2.xpath(\n './following-sibling::text()[1]'\n ).extract(),\n },\n url=urljoin(response.url, '/%s' % href[0])\n )\n # pagination\n next_page = sel.xpath(\n '//div[@class=\"pagination\"]/a[contains(text(), \"Volgende\")]/@href'\n ).extract()\n if next_page:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, '/%s' % next_page[0])\n )\n\n def parse_job(self, response):\n \"\"\"\n Parse all required information\n \"\"\"\n sel = Selector(response)\n\n loader = BrightcorpItemLoader(selector=sel)\n raw_data = response.meta.get('raw_data')\n if raw_data:\n raw_data = raw_data[0].split('|')\n for index, item in enumerate(raw_data):\n if 'Dienstverband:' in item:\n loader.add_value(\n 'jobtype', item, Replace('Dienstverband:')\n )\n elif 'Ervaring:' in item:\n loader.add_value(\n 'experiencerequirements', item, Replace('Ervaring:')\n )\n elif 'Opleiding:' in item:\n loader.add_value(\n 'qualifications', item, Replace('Opleiding:')\n )\n elif index == 1:\n loader.add_value(\n 'jobcategory', item\n )\n loader.add_xpath(\n 'title',\n '//div[@class=\"job-right\"]/div[@id=\"print\"]/h1/text()'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n Prefix('%s-' % self.name),\n re=pattern['ref_number']\n )\n loader.add_value('url', response.url)\n loader.add_value(\n 'company',\n response.meta.get('company')\n )\n loader.add_xpath(\n 'date',\n '//div[@class=\"main\"]/div[@class=\"job-left\"]/div[@class=\"job-left-content\"]/text()[3]',\n ConvertDateString('%d-%m-%Y'),\n re=pattern['date']\n )\n loader.add_xpath(\n 'location',\n '//div[@class=\"job-right\"]/div/table/tr/td/strong[contains(text(), \"Locatie\")]/../following-sibling::td[1]/text()'\n )\n loader.add_xpath(\n 'description',\n '//div/div[@id=\"job-description\"]'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/benenmatch_nl.py","file_name":"benenmatch_nl.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652292805","text":"import RPi.GPIO as GPIO\nimport time\nimport Adafruit_ADS1x15\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nELECTRO_MAG_PIN = 23\nGPIO.setup(ELECTRO_MAG_PIN, GPIO.OUT)\n\nPOWER_CONTROL = 19 # should be 21 but didn't include level conversion for p chan\nGPIO.setup(POWER_CONTROL, GPIO.OUT)\nGPIO.output(POWER_CONTROL, True) # turn on power for hall sensor\nGPIO.output(ELECTRO_MAG_PIN, False) # turn off power for magnet\n\nnum_avg_tests = 10\nadc = Adafruit_ADS1x15.ADS1015()\nADC = { '3_3' : 1, 'side': 0, 'hall': 2 }\ndef sample_hall(tests=num_avg_tests):\n sum_hall = 0\n for i in range(tests):\n sum_hall += adc.read_adc(ADC['hall'], gain=1) * 4\n hall = sum_hall / tests\n return hall\n\nelectro_off_hall = sample_hall(50)\nprint(\"hall is %d mv with no magnet\" % electro_off_hall)\nwhile True:\n\n print(True)\n GPIO.output(ELECTRO_MAG_PIN, True)\n time.sleep(0.1)\n electro_on_hall = sample_hall(50)\n print(electro_off_hall - electro_on_hall)\n if electro_off_hall - electro_on_hall > 40:\n print(\"PASS\")\n else:\n print(\"FAIL\")\n time.sleep(0.9)\n\n print(False)\n GPIO.output(ELECTRO_MAG_PIN, False)\n time.sleep(1.0)\n","sub_path":"electromag-test/electro.py","file_name":"electro.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540612652","text":"#!/usr/bin/env python3\n\nfrom typing import List, Set, Dict, Tuple, Optional\nfrom datetime import datetime\n\nimport json\nimport time\nimport requests\nimport sqlite3\n\nimport settings\nimport database\nfrom temperature import readTemp\n\nconn = sqlite3.connect(settings.database)\n\ndef turnFurnaceOn() -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/furnace/on')\n print(r.text)\n except:\n pass\n\n\ndef turnFurnaceOff() -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/furnace/off')\n print(r.text)\n except:\n pass\n\n\ndef getDesiredTemp() -> Optional[float]:\n try:\n r = requests.get(f'http://{settings.webserver}/temperature/desired')\n try:\n res = json.loads(r.text)\n return float(res['temperature'])\n except:\n print(f\"error: {r.text} can not be parsed\")\n except:\n return None\n\n\ndef setDesiredTemp(temp) -> None:\n try:\n r = requests.post(f'http://{settings.webserver}/temperature/setdesired/{temp}')\n except:\n pass\n\n\ndef checkSchedules(c: sqlite3.Cursor) -> None:\n schedules = database.getSchedules(c)\n if schedules is None: return\n\n now = datetime.now()\n nows = now.hour*3600 + now.minute*60 + now.second\n\n # weekday(): monday = 0, sunday = 6\n # dow: monday = 6, sunday = 0\n dow = 6 - now.today().weekday()\n\n # mask: monday = 0b1000000\n # sunday = 0b0000001\n mask = 1 << dow\n\n for start, end, temp, days in schedules:\n #{\n print(\"checking schedule: \", start, end, temp, bin(days), bin(mask))\n if mask & days == mask and nows > start and nows < end:\n print(\"settings temp: \", temp)\n setDesiredTemp(temp)\n return\n #}\n\n print(\"no active schedules\")\n setDesiredTemp(settings.minimumSafeTemperature)\n\n\ndef main():\n c = conn.cursor()\n database.init(c)\n conn.commit()\n\n while True:\n #{\n checkSchedules(c)\n desiredTemp = getDesiredTemp()\n\n currTemp = readTemp()\n database.saveTemperature(c, currTemp)\n conn.commit()\n print(currTemp)\n\n # if there is a response from the web server\n if desiredTemp is not None:\n #{\n\n if currTemp < desiredTemp:\n turnFurnaceOn()\n\n elif currTemp + settings.buff > desiredTemp:\n turnFurnaceOff()\n\n #}\n\n # sleep before the next loop\n time.sleep(settings.sleepIntervalSec)\n #}\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"thermostat.py","file_name":"thermostat.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139950290","text":"#! /usr/bin/python\r\n\r\nimport json\r\n\r\n# for leaves, value is the secret coeff\r\nclass Node:\r\n def __init__(self, id, left, right, value):\r\n self.id = id\r\n self.left = left\r\n self.right = right\r\n self.value = value\r\n \"\"\"\r\n def __str__(self):\r\n choices = \"coeff=\" + str(self.coeff) + \"; \\t l_j=[\" + str(self.j0) + \",\" + str(self.j1) + \",\" + str(\r\n self.j2) + \",\" + str(self.j3) + \"]\" if self.left else \"S_j=[\" + str(self.j0) + \",\" + str(\r\n self.j1) + \",\" + str(self.j2) + \",\" + str(self.j3) + \"]\"\r\n children = \"(\" + (str(self.left.id) if self.left else \"x\") + \",\" + (\r\n str(self.right.id) if self.right else \"x\") + \"), \\t\" if self.left else \" =>\\t\"\r\n return (str(self.id) + \": \\t\" + children + choices)\r\n \"\"\"\r\n\r\ndef Atojson(node):\r\n return ([node.id, node.left.id, node.right.id, node.value] if node.left else [\r\n node.id, None, None, node.value])\r\n\r\n\r\nlength = 0\r\ntreearray = []\r\nidcount = 0\r\n\r\ndef newnode(left, right, value):\r\n global length\r\n length = length + 1\r\n node = Node(length, left, right, value)\r\n return (node)\r\n\r\ndef newnodefromarray(node):\r\n result = newnode(None, None, node[3])\r\n return (result)\r\n\r\ndef reconstruct(nodes):\r\n global length\r\n length = 0\r\n nodearray = []\r\n for i in range(len(nodes)):\r\n nodearray.append(newnodefromarray(nodes[i]))\r\n for i in range(len(nodes)):\r\n nodearray[i].left = nodearray[nodes[i][1] - 1] if nodes[i][1] else None\r\n nodearray[i].right = nodearray[nodes[i][2] - 1] if nodes[i][2] else None\r\n return (nodearray[len(nodes) - 1])\r\n\r\ndef treetoarray(node):\r\n global treearray\r\n if (node.left == None):\r\n treearray.append(Atojson(node))\r\n else:\r\n treetoarray(node.left)\r\n treetoarray(node.right)\r\n treearray.append(Atojson(node))\r\n\r\ndef writejson(obj, filename):\r\n global treearray\r\n global idcount\r\n idcount = 1\r\n addid(obj)\r\n treearray = []\r\n treetoarray(obj)\r\n with open(filename, \"w\") as output:\r\n json.dump(treearray, output)\r\n\r\ndef readjson(filename):\r\n with open(filename, \"rb\") as input:\r\n return (json.load(input))\r\n\r\ndef printnodes(node):\r\n if (node.left == None):\r\n print(node)\r\n else:\r\n printnodes(node.left)\r\n printnodes(node.right)\r\n print(node)\r\n\r\ndef addid(node):\r\n global idcount\r\n if(node.left==None):\r\n node.id=idcount\r\n idcount=idcount+1\r\n else:\r\n addid(node.left)\r\n addid(node.right)\r\n node.id=idcount\r\n idcount=idcount+1","sub_path":"Frodo/BinaryTree1D.py","file_name":"BinaryTree1D.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434937879","text":"import requests\r\nres = requests.get(\"http://google.com\")\r\nres.raise_for_status()\r\n#print(\"웹 스크래핑을 시진행합니다.\") # 만약 res의 주소값이 문제가 생겼을 경우 바로 오류를 일으켜 중단시킨다.\r\n\r\n#print(\"응답 코드 : \",res.status_code) # 200이면 정상\r\n\r\n# if res.status_code == requests.codes.ok:\r\n# print(\"정상입니다.\")\r\n# else:\r\n# print(\"문제가 생겼습니다. [에러코드 \",res.status_code,\"]\")\r\n\r\n\r\nprint(len(res.text))\r\nprint(res.text)\r\n\r\nwith open(\"myopen.html\", \"w\",encoding=\"utf8\") as f:\r\n f.write(res.text)","sub_path":"webscreaping_basic/3_requests.py","file_name":"3_requests.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"594382818","text":"\r\n# this example test the speed of IDX \r\nimport os,sys,math, numpy as np\r\nimport shutil\r\nfrom OpenVisus import *\r\n\r\nKB,MB,GB=1024,1024*1024,1024*1024*1024\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef GenerateRandomData(dims, dtype):\r\n\t\"\"\"\r\n\thalf data will be zero, half will be random\r\n\tin case you want to test with compression having a 50% compression ratio\r\n\t\"\"\"\r\n\t\r\n\tW,H,D=dims\r\n\tret=np.zeros((D, H, W),dtype=convert_dtype(dtype.get(0).toString()))\r\n\t\r\n\tif ret.dtype==numpy.float32 or ret.dtype==numpy.float64:\r\n\t\tret[0:int(D/2),:,]=np.random.rand(int(D/2), H, W,dtype=ret.dtype)\r\n\t\t\t\r\n\telif ret.dtype==numpy.uint16 :\r\n\t\tret[0:int(D/2),:,]=np.random.randint(0, 65535, (int(D/2), H, W),dtype=ret.dtype)\r\n\t\t\t\r\n\telif ret.dtype==numpy.uint8 :\r\n\t\tret[0:int(D/2),:,]=np.random.randint(0, 255 , (int(D/2), H, W),dtype=ret.dtype)\r\n\t\t\t\r\n\telse:\r\n\t\traise Exception(\"internal error\")\r\n\t\t\r\n\treturn ret\t\r\n\r\n# /////////////////////////////////////////////////////\r\ndef ReadFileSequentially(filename):\r\n\tfile=File()\r\n\tAssert(file.open(filename, \"r\"))\r\n\tcursor=0\r\n\tarray=Array(1* GB, DType.fromString(\"uint8\")) \r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tif not file.read(cursor,array.c_size(),array.c_ptr()):\r\n\t\t\t\tcursor=0\r\n\t\t\telse:\r\n\t\t\t\tcursor+=array.c_size()\r\n\t\t\t\tyield array.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\tfile.close()\r\n\tdel file\r\n\r\n# /////////////////////////////////////////////////////\r\ndef ReadFullResBlocks(filename, blocksize=0):\r\n\tfile=File()\r\n\tAssert(file.open(filename, \"r\"))\r\n\ttotsize=os.path.getsize(filename)\r\n\tnblocks=totsize/blocksize\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tarray=Array(blocksize, DType.fromString(\"uint8\"))\r\n\t\t\tblockid=np.random.randint(0,nblocks)\r\n\t\t\tfile.read(blockid * blocksize,array.c_size(),array.c_ptr())\r\n\t\t\tyield array.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\tfile.close()\r\n\tdel file\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef CreateIdxDataset(filename, DIMS=None, dtype=None, blocksize=0, default_layout=\"rowmajor\",default_compression=\"\"):\r\n\r\n\tprint(\"Creating idx dataset\", filename,\"...\")\r\n\r\n\tdtype=DType.fromString(dtype)\r\n\tbitsperblock=int(math.log(int(blocksize/dtype.getByteSize()),2))\r\n\tAssert(int(pow(2,bitsperblock)*dtype.getByteSize())==blocksize)\r\n\r\n\tfield=Field(\"data\")\r\n\tfield.dtype=dtype\r\n\tfield.default_layout=default_layout\r\n\tfield.default_compression=default_compression\r\n\t\r\n\tCreateIdx(url=filename, rmtree=True, \r\n\t\tdims=DIMS,\r\n\t\tfields=[field], \r\n\t\tbitsperblock=bitsperblock, \r\n\t\tblocksperfile=-1, # one file\r\n\t\tfilename_template=\"./\" + os.path.basename(filename)+\".bin\")\r\n\r\n\t# fill with fake data\r\n\tdb=LoadDataset(filename)\r\n\t\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.disableWriteLock()\r\n\t\r\n\taccess.beginWrite()\r\n\tfor blockid in range(db.getTotalNumberOfBlocks()):\r\n\t\twrite_block = db.createBlockQuery(blockid, ord('w'), Aborted())\r\n\t\tnsamples=write_block.getNumberOfSamples().toVector()\r\n\t\tbuffer=GenerateRandomData(nsamples,dtype)\r\n\t\twrite_block.buffer=Array.fromNumPy(buffer, bShareMem=True)\r\n\t\tdb.executeBlockQueryAndWait(access, write_block)\r\n\t\tAssert(write_block.ok())\r\n\taccess.endWrite()\t\r\n\t\r\n\tdel access\r\n\tdel db\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef ReadIdxBlockQuery(filename):\r\n\tdb=LoadDataset(filename)\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.beginRead()\r\n\tnblocks=db.getTotalNumberOfBlocks()\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tblockid=np.random.randint(0,nblocks)\r\n\t\t\tquery = db.createBlockQuery(blockid)\r\n\t\t\tdb.executeBlockQuery(access, query)\r\n\t\t\tAssert(query.ok())\r\n\t\t\tyield query.buffer.c_size()\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\taccess.endRead()\r\n\tdel access\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef ReadIdxBoxQuery(filename, dims):\r\n\tdb=LoadDataset(filename)\r\n\tDIMS=db.getLogicSize()\r\n\taccess = IdxDiskAccess.create(db)\r\n\taccess.disableAsync()\r\n\taccess.beginRead()\r\n\tsamplesize=db.getField().dtype.getByteSize()\r\n\ttry:\r\n\t\twhile True:\r\n\t\t\tx=np.random.randint(0,DIMS[0]/dims[0])*dims[0]\r\n\t\t\ty=np.random.randint(0,DIMS[1]/dims[1])*dims[1]\r\n\t\t\tz=np.random.randint(0,DIMS[2]/dims[2])*dims[2]\r\n\t\t\tBlockQuery.global_stats().resetStats()\r\n\t\t\tdata=db.read(logic_box=[(x,y,z),(x+dims[0],y+dims[1],z+dims[2])],access=access)\r\n\t\t\tAssert(data.nbytes==dims[0]*dims[1]*dims[2]*samplesize)\r\n\t\t\tN=BlockQuery.global_stats().getNumRead()\r\n\t\t\t# print(N)\r\n\t\t\tyield data.nbytes\r\n\texcept GeneratorExit:\r\n\t\tpass\r\n\taccess.endRead()\r\n\tdel access\r\n\r\n# ////////////////////////////////////////////////////////////////\r\ndef TimeIt(name, gen, max_seconds=60):\r\n\tuser=next(gen) # skip any headers (open/close file)\r\n\tUSER, DISK, NCALLS, T1=0,0,0,Time.now()\r\n\twhile T1.elapsedSec()0 and total_val>0):\r\n\r\n BATCH_SIZE = 100\r\n IMG_SHAPE = 224\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, horizontal_flip=True)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE,IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, rotation_range=45)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE, IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255, zoom_range=0.5)\r\n\r\n train_data_gen = image_gen.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE, IMG_SHAPE))\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen_train = tf.keras.preprocessing.image.ImageDataGenerator(\r\n rescale=1./255,\r\n rotation_range=40,\r\n width_shift_range=0.2,\r\n height_shift_range=0.2,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True,\r\n fill_mode='nearest')\r\n\r\n train_data_gen = image_gen_train.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=train_dir,\r\n shuffle=True,\r\n target_size=(IMG_SHAPE,IMG_SHAPE),\r\n class_mode='sparse')\r\n\r\n augmented_images = [train_data_gen[0][0][0] for i in range(5)]\r\n\r\n image_gen_val = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)\r\n\r\n val_data_gen = image_gen_val.flow_from_directory(batch_size=BATCH_SIZE,\r\n directory=validation_dir,\r\n target_size=(IMG_SHAPE, IMG_SHAPE),\r\n class_mode='binary') # class_mode='binary' if the model contains only two classes\r\n\r\n L = os.listdir('C:/MAMP/htdocs/enter_exit_saved_model' + db_num)\r\n if (len(L)>0):\r\n feature_extractor = tf.keras.experimental.load_from_saved_model('C:/MAMP/htdocs/enter_exit_saved_model' + db_num,\r\n custom_objects={'KerasLayer': hub.KerasLayer})\r\n\r\n feature_extractor.build((None, 224, 224, 3))\r\n\r\n model = tf.keras.models.Sequential()\r\n for layer in feature_extractor.layers[:-1]:\r\n model.add(layer)\r\n for layer in model.layers:\r\n layer.trainable = False\r\n model.add(tf.keras.layers.Dense(m, activation='softmax', name=\"output\"))\r\n\r\n else:\r\n URL = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2\"\r\n feature_extractor = hub.KerasLayer(URL,\r\n input_shape=(224, 224, 3))\r\n\r\n feature_extractor.trainable = False\r\n\r\n model = tf.keras.Sequential([\r\n feature_extractor,\r\n tf.keras.layers.Dense(m, activation='softmax', name=\"output\")\r\n ])\r\n\r\n epochs = int(epoch)\r\n model.summary()\r\n\r\n model.compile(optimizer='adam',\r\n loss='sparse_categorical_crossentropy',\r\n metrics=['accuracy'])\r\n\r\n earlystop_callback = tf.keras.callbacks.EarlyStopping(\r\n monitor='val_accuracy', min_delta=0.0001,\r\n patience=2)\r\n\r\n history = model.fit_generator(\r\n train_data_gen,\r\n steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))),\r\n epochs=epochs,\r\n callbacks=[earlystop_callback],\r\n validation_data=val_data_gen,\r\n validation_steps=int(np.ceil(total_val / float(BATCH_SIZE)))\r\n )\r\n\r\n acc = history.history['acc']\r\n val_acc = history.history['val_acc']\r\n\r\n loss = history.history['loss']\r\n val_loss = history.history['val_loss']\r\n\r\n epochs_range = range(epochs)\r\n\r\n fig = plt.figure(figsize=(8, 8))\r\n plt.subplot(1, 2, 1)\r\n plt.plot(epochs_range, acc, label='Training Accuracy')\r\n plt.plot(epochs_range, val_acc, label='Validation Accuracy')\r\n plt.legend(loc='lower right')\r\n plt.title('Training and Validation Accuracy')\r\n\r\n plt.subplot(1, 2, 2)\r\n plt.plot(epochs_range, loss, label='Training Loss')\r\n plt.plot(epochs_range, val_loss, label='Validation Loss')\r\n plt.legend(loc='upper right')\r\n plt.title('Training and Validation Loss')\r\n # plt.show()\r\n\r\n fig.savefig('C:/MAMP/htdocs/my_plot2_' + db_num + '.png')\r\n mydir = \"C:/MAMP/htdocs/enter_exit_saved_model\" + db_num\r\n L = os.listdir(mydir)\r\n if (len(L)>0):\r\n for i in L:\r\n ch = mydir + '/' + i\r\n try:\r\n shutil.rmtree(ch)\r\n except:\r\n os.remove(ch)\r\n\r\n export_path = tf.keras.experimental.export_saved_model(model, r'C:\\MAMP\\htdocs\\enter_exit_saved_model' + db_num)\r\n\r\n label_names = sorted(train_data_gen.class_indices.items(), key=lambda pair:pair[1])\r\n label_names = np.array([key.title() for key, value in label_names])\r\n\r\n L = os.listdir(r\"C:\\MAMP\\htdocs\\enter_exit_validation\" + db_num)\r\n for ch in L:\r\n dir = \"C:/MAMP/htdocs/enter_exit_validation\" + db_num + \"/\" + ch\r\n L2 = os.listdir(dir)\r\n for ch2 in L2:\r\n dir2 = \"C:/MAMP/htdocs/enter_exit\" + db_num + \"/\" + ch + '/' + ch2\r\n pic = dir + '/' + ch2\r\n try:\r\n shutil.move(pic, dir2)\r\n except:\r\n os.mkdir(\"C:/MAMP/htdocs/enter_exit\" + db_num + \"/\" + ch)\r\n shutil.move(pic, dir2)\r\n\r\n L2 = os.listdir(r\"C:\\MAMP\\htdocs\\enter_exit_validation\" + db_num)\r\n if (len(L2) > 0):\r\n for i in L2:\r\n ch = 'C:/MAMP/htdocs/enter_exit_validation' + db_num + '/' + i\r\n try:\r\n shutil.rmtree(ch)\r\n except:\r\n os.remove(ch)\r\n","sub_path":"online_learning_enter_exit2.py","file_name":"online_learning_enter_exit2.py","file_ext":"py","file_size_in_byte":8832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250906612","text":"import dataclasses\nfrom contextlib import suppress\nfrom inspect import cleandoc\nfrom typing import Any, Dict, Generic, Optional, Type, TypeVar\n\nimport django\nimport django.db.models\nimport strawberry\nfrom strawberry import UNSET\nfrom strawberry.annotation import StrawberryAnnotation\nfrom strawberry.exceptions import PrivateStrawberryFieldError\nfrom strawberry.field import UNRESOLVED\nfrom strawberry.private import is_private\n\nfrom . import utils\nfrom .fields.field import StrawberryDjangoField\nfrom .fields.types import (\n get_model_field,\n is_optional,\n resolve_model_field_name,\n resolve_model_field_type,\n)\nfrom .settings import strawberry_django_settings as django_settings\n\n\n_type = type\n\n\ndef get_type_attr(type_, field_name: str):\n attr = getattr(type_, field_name, UNSET)\n if attr is UNSET:\n attr = getattr(type_, \"__dataclass_fields__\", {}).get(field_name, UNSET)\n return attr\n\n\ndef get_field(\n django_type: \"StrawberryDjangoType\",\n field_name: str,\n field_annotation: Optional[StrawberryAnnotation] = None,\n):\n if field_annotation and is_private(field_annotation.annotation):\n raise PrivateStrawberryFieldError(field_name, django_type.origin)\n attr = get_type_attr(django_type.origin, field_name)\n\n if utils.is_field(attr):\n field = django_type.field_cls.from_field(attr, django_type)\n else:\n field = django_type.field_cls(\n default=attr,\n type_annotation=field_annotation,\n )\n\n field.python_name = field_name\n if field_name in django_type.origin.__dict__.get(\"__annotations__\", {}):\n # store origin django type for further usage\n field.origin_django_type = django_type\n\n if field_annotation:\n # annotation of field is used as a class type\n field.type_annotation = field_annotation\n field.is_auto = utils.is_auto(field_annotation)\n\n try:\n # resolve the django_name and check if it is relation field. django_name\n # is used to access the field data in resolvers\n django_name = field.django_name or field_name\n model_field = get_model_field(django_type.model, django_name)\n field.django_name = resolve_model_field_name(\n model_field, django_type.is_input, django_type.is_filter\n )\n field.is_relation = model_field.is_relation\n\n # Use the Django field help_text if no other description is available.\n settings = django_settings()\n if not field.description and settings[\"FIELD_DESCRIPTION_FROM_HELP_TEXT\"]:\n model_field_help_text = getattr(model_field, \"help_text\", \"\")\n field.description = str(model_field_help_text) or None\n except django.core.exceptions.FieldDoesNotExist:\n if field.django_name or field.is_auto:\n raise # field should exist, reraise caught exception\n model_field = None\n\n if field.is_relation:\n # change relation field type to auto if field is inherited from another\n # type. for example if field is inherited from output type but we are\n # configuring field for input type\n if not utils.is_similar_django_type(django_type, field.origin_django_type):\n field.is_auto = True\n\n # Only set the type_annotation for auto fields if they don't have a base_resolver.\n # Since strawberry 0.139 the type_annotation has a higher priority than the\n # resolver's annotation, and that would force our automatic model resolution to be\n # used instead of the resolver's type annotation.\n if field.is_auto and not field.base_resolver:\n # resolve type of auto field\n field_type = resolve_model_field_type(model_field, django_type)\n field.type_annotation = StrawberryAnnotation(field_type)\n\n if field.type_annotation and is_optional(\n model_field, django_type.is_input, django_type.is_partial\n ):\n field.type_annotation.annotation = Optional[field.type_annotation.annotation]\n\n if django_type.is_input:\n if field.default is dataclasses.MISSING:\n # strawberry converts UNSET value to MISSING, let's set\n # it back to UNSET. this is important especially for partial\n # input types\n # TODO: could strawberry support UNSET default value?\n field.default_value = UNSET\n field.default = UNSET\n\n return field\n\n\ndef get_fields(django_type: \"StrawberryDjangoType\"):\n annotations = utils.get_annotations(django_type.origin)\n fields: Dict[str, StrawberryDjangoField] = {}\n seen_fields = set()\n\n # collect all annotated fields\n for field_name, field_annotation in annotations.items():\n with suppress(PrivateStrawberryFieldError):\n fields[field_name] = get_field(django_type, field_name, field_annotation)\n seen_fields.add(field_name)\n\n # collect non-annotated strawberry fields\n for field_name in dir(django_type.origin):\n if field_name in seen_fields:\n continue\n attr = getattr(django_type.origin, field_name)\n if not utils.is_strawberry_field(attr):\n continue\n field = get_field(django_type, field_name)\n fields[field_name] = field\n\n return list(fields.values())\n\n\n_O = TypeVar(\"_O\", bound=type)\n_M = TypeVar(\"_M\", bound=django.db.models.Model)\n\n\n@dataclasses.dataclass\nclass StrawberryDjangoType(Generic[_O, _M]):\n origin: _O\n model: Type[_M]\n is_input: bool\n is_partial: bool\n is_filter: bool\n filters: Any\n order: Any\n pagination: Any\n field_cls: Type[StrawberryDjangoField]\n\n\ndef process_type(\n cls,\n model: Type[django.db.models.Model],\n *,\n filters=UNSET,\n pagination=UNSET,\n order=UNSET,\n field_cls=UNSET,\n **kwargs,\n):\n original_annotations = cls.__dict__.get(\"__annotations__\", {})\n\n if not field_cls or field_cls is UNSET:\n field_cls = StrawberryDjangoField\n\n django_type = StrawberryDjangoType(\n origin=cls,\n model=model,\n is_input=kwargs.get(\"is_input\", False),\n is_partial=kwargs.pop(\"partial\", False),\n is_filter=kwargs.pop(\"is_filter\", False),\n filters=filters,\n order=order,\n pagination=pagination,\n field_cls=field_cls,\n )\n\n fields = get_fields(django_type)\n\n # update annotations and fields\n cls.__annotations__ = cls_annotations = {}\n for field in fields:\n annotation = None\n\n if field.type_annotation and field.type_annotation.annotation:\n annotation = field.type_annotation.annotation\n elif field.base_resolver and field.base_resolver.type_annotation:\n annotation = field.base_resolver.type_annotation.annotation\n\n # UNRESOLVED is not a valid annotation, it is just an indication that the type\n # could not be resolved. In this case just fallback to None\n if annotation is UNRESOLVED:\n annotation = None\n\n # TODO: should we raise an error if annotation is None here?\n\n cls_annotations[field.name] = annotation\n setattr(cls, field.name, field)\n\n # Strawberry >= 0.92.0 defines `is_type_of` for types implementing\n # interfaces if the attribute has not been set yet. It allows only\n # instances of `cls` to be returned, we should allow model instances\n # too.\n if not hasattr(cls, \"is_type_of\"):\n cls.is_type_of = lambda obj, _info: isinstance(obj, (cls, model))\n\n # Get type description from either kwargs, or the model's docstring\n settings = django_settings()\n description = kwargs.pop(\"description\", None)\n if not description and settings[\"TYPE_DESCRIPTION_FROM_MODEL_DOCSTRING\"]:\n description = cleandoc(model.__doc__) or None\n\n strawberry.type(cls, description=description, **kwargs)\n\n # restore original annotations for further use\n cls.__annotations__ = original_annotations\n cls._django_type = django_type\n\n return cls\n\n\ndef type(model, *, filters=UNSET, **kwargs):\n def wrapper(cls):\n return process_type(cls, model, filters=filters, **kwargs)\n\n return wrapper\n\n\ndef input(model, *, partial=False, **kwargs):\n return type(model, partial=partial, is_input=True, **kwargs)\n\n\ndef mutation(model, **kwargs):\n return type(model, **kwargs)\n","sub_path":"strawberry_django/type.py","file_name":"type.py","file_ext":"py","file_size_in_byte":8238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321386468","text":"# 属性(Property)是通过__init__函数定义,并通过self传递给实例的一种数据类型。\n# 属性值的初始化\n# 在__init__里直接初始化值\nclass Box():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\nT1 = Box()\nprint(T1.length) # 0\n\n\n# 传递参数初始化\nclass Box2():\n def __init__(self,length1,width1,height1):\n self.length = length1\n self.width = width1\n self.height = height1\n\nT2 = Box2(12,13,15)\nprint(T2.length) # 12\n# 属性值的修改\n# 直接对属性值进行修改\nclass Box3():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\nT3 = Box3()\nprint(T3.length) # 0\nT3.length = 99\nprint('修改后的属性值%d'%(T3.length)) # 修改后的属性值99\n\n# 通过方法对属性值进行修改\nclass Box4():\n def __init__(self):\n self.length = 0\n self.width = 0\n self.height = 0\n def property_update(self,length1):\n self.length = length1\n\nT4 = Box4()\nT4.property_update(45)\nprint('通过方法赋值之后属性值%d'%(T4.length))\n# 通过方法赋值之后属性值45\n\n# 把类赋值给属性\nclass Color():\n def __init__(self,index=0):\n self.set_color = ['red','black','green','white']\n self.index = index\n def setColor(self):\n return self.set_color[self.index]\n\nclass Box5():\n def __init__(self,length2,width2,height2,cl=0):\n self.length = length2\n self.width = width2\n self.height = height2\n self.color = Color(cl).setColor()\n def volume(self):\n return self.length*self.width*self.height\n\nmy_Box5 = Box5(10,20,30,1)\nprint(my_Box5.color) # black\n\n \n","sub_path":"python_basis/07_Object_oriented_class/class_property.py","file_name":"class_property.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59239938","text":"import os\nfrom os import PathLike\nimport sys\nimport xml.etree.ElementTree as ET\nfrom typing import List, Dict, Union\n\nfrom dere.corpus_io import CorpusIO\nfrom dere.corpus import Corpus, Instance, Span, Frame, Filler\nfrom dere.taskspec import TaskSpecification, SpanType\n\n\nclass CQSACorpusIO(CorpusIO):\n def load(self, path: str, load_gold: bool = True) -> Corpus:\n if os.path.isdir(path):\n paths: List[str] = []\n for dirpath, dirnames, filenames in os.walk(path):\n paths.extend(\n [\n os.path.join(dirpath, fn)\n for fn in filenames\n if fn.endswith(\".xml\")\n ]\n )\n else:\n paths = [path]\n path = \"/\".join(path.split(\"/\")[:-1])\n corpus = Corpus()\n for file_path in paths:\n self._populate_corpus_from_file(corpus, path, file_path, load_gold)\n return corpus\n\n def _populate_corpus_from_file(self, corpus: Corpus, root_path: str, path: str, load_gold: bool) -> None:\n relative_path = path[len(root_path):]\n while relative_path.startswith(\"/\"):\n relative_path = relative_path[1:]\n doc_id, _ = relative_path.rsplit(\".\", 1)\n tree = ET.parse(path)\n root = tree.getroot()\n # self._construct_instance(corpus, root, doc_id)\n\n for child in root.getchildren():\n if child.tag in [\"HEADING\", \"PARAGRAPH\"]:\n instance = self._construct_instance(corpus, child, doc_id, load_gold)\n\n def _construct_instance(\n self,\n corpus: Corpus,\n element: ET.Element,\n doc_id: str,\n load_gold: bool\n ) -> Instance:\n instance = corpus.new_instance(\"\", doc_id)\n ids: Dict[str, Filler] = {}\n self._populate_instance(element, instance, ids, load_gold)\n instance.text = instance.text.replace(\"\\n\", \" \")\n self._link_instance(element, instance, ids)\n return instance\n\n def _populate_instance(\n self, element: ET.Element, instance: Instance, ids: Dict[str, Filler], load_gold: bool\n ) -> None:\n if ids is None:\n ids = {}\n if element.text is not None:\n instance.text += element.text\n for child in element.getchildren():\n left = len(instance.text)\n self._populate_instance(child, instance, ids, load_gold)\n right = len(instance.text)\n span = None\n span_type = self._task_spec.span_type_lookup(child.tag)\n if load_gold and span_type is not None:\n span = instance.new_span(span_type, left, right, \"gold\")\n instance.spans.append(span)\n ids[child.attrib[\"id\"]] = span\n frame_type = self._task_spec.frame_type_lookup(child.tag)\n if load_gold and frame_type is not None:\n frame = instance.new_frame(frame_type, \"gold\")\n if span is not None:\n slot = frame.slot_lookup(frame_type.name)\n if slot is not None:\n slot.add(span)\n instance.frames.append(frame)\n ids[child.attrib[\"id\"]] = frame\n if child.tail is not None:\n instance.text += child.tail\n\n def _link_instance(\n self, element: ET.Element, instance: Instance, ids: Dict[str, Filler]\n ) -> None:\n for element in element.iter():\n if \"id\" in element.attrib and element.attrib[\"id\"] in ids:\n frame = ids[element.attrib[\"id\"]]\n if isinstance(frame, Frame):\n for attrib, value in element.attrib.items():\n slot = frame.slot_lookup(attrib)\n if slot is not None:\n if value in ids:\n filler = ids[value]\n slot.add(filler)\n","sub_path":"dere/corpus_io/cqsa_corpus_io.py","file_name":"cqsa_corpus_io.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"140112107","text":"# Combining conditions with AND instead of nested if statements\n# Combining operators allows you to handle complex rules in your code but you must test your code very carefully to avoid introducing errors\n# A student makes honour roll if their average grade is >= 85 and their lowest grade is not below 70\ngpa = float(input('What was your Grade Point Average? '))\n# lowest_grade = input('What was your lowest grade? ')\n# lowest_grade = float(lowest_grade)\nlowest_grade = float(input('What was your lowest grade? '))\n\nif gpa >= .85 and lowest_grade >= .70: # used the and statement here\n honour_roll = True\nelse:\n honour_roll = False\nif honour_roll:\n print('You made honour roll!!')\n","sub_path":"complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"369253845","text":"# write a program to create a student class and create a object to it\n# and call the method talk to display the student data.\n\nclass Student:\n def __init__(self,id,name,roll,course,college,fees):\n self.id=id\n self.name=name\n self.roll=roll # declaring instance variable\n self.course=course\n self.college=college\n self.fees=fees\n def talk(self):\n print(\"student ID :\",self.id)\n print(\"student name :\",self.name) # initializing the instance variable.\n print(\"student roll :\",self.roll)\n print(\"student course :\",self.course)\n print(\"student college :\",self.college)\n print(\"student fees :\",self.fees)\ns=Student(101,\"bhushan\",23,\"MCA\",\"K K Wagh college\",25500) # creating an object.\ns.talk()\n","sub_path":"student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"618360640","text":"# -*- coding: utf-8 -*-\n__author__ = 'fwj'\n\nfor i in range(100, 999):\n a = int(i / 100)\n b = int(i / 10 % 10)\n c = int(i % 10)\n #print(a, b, c)\n if i == (a * a * a + b * b * b + c * c * c):\n print(i)","sub_path":"test/test_13.py","file_name":"test_13.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"620288108","text":"#!/usr/bin/python3\n####################################################################################################\n\nimport re\nimport random\nimport time\nfrom lib.ui import UI\nfrom lib.script import Script\nfrom lib.cli.facebook.openbmc import OpenBMC\n\nclass OpenBMC_0070(Script):\n def __init__(self, dut, job_id=\"\", image_server = 'None'):\n headline = ['Monitoring All Sensors']\n purpose = [\n 'To verify all sensors can be accessed.', \n ' Using the \"sensors-util\" command on openBMC to get the current view for all sensors.', \n ' (ltc4151-i2c-7-6f is PS21 sensors, only for PSU21, need to insert the DC PSU into PS2)']\n\n self.__dut = dut[1]\n self.prompt = self.__dut.ssh_credentials[5]\n super().__init__(headline, purpose, script_path=__file__,job_id=job_id)\n # Start logging the script.\n super().beginLog()\n\n def run(self):\n \"\"\"\n Function Name: run\n Purpose: Executes the steps defined by this test case.\n \"\"\"\n\n # initialize serial, Telnet and TELNET UI with SystemMgmt APIs.\n self.__SSH = super().initUI(self.__dut.ssh_credentials, self.__dut.platform, OpenBMC)\n self.__fail_count = 0\n\n # Do not surround assignment operator = with spaces in paranthesised expressions.\n self.__SSH.send('sensor-util all \\r')\n self.__SSH.expect(self.prompt, timeout= 180)\n \n if self.__fail_count == 0:\n UI.log('PASS', 'BMC_0070 Monitoring All Sensors is passed.')\n else:\n UI.log('FAIL', 'BMC_0070 Monitoring All Sensors is failed.')\n\n def stop(self):\n # Terminate interfaces and restore settings.\n self.__SSH.close()\n # Stop logging the script.\n super().endLog()","sub_path":"Facebook/openbmc_0070.py","file_name":"openbmc_0070.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"129351887","text":"import unittest2\n\nfrom shuffled import Shuffled\n\n\nclass TestShuffled(unittest2.TestCase):\n def test_normal(self):\n for i in range(0, 1000, 100):\n with self.subTest(i=i):\n shuffled_range = Shuffled(i)\n self.assertEqual(sorted(list(shuffled_range)), list(range(i)))\n\n def test_seed(self):\n for seed in (b'', b'\\x00', b'\\x01'):\n with self.subTest(seed=seed):\n self.assertEqual(list(Shuffled(20, seed)), list(Shuffled(20, seed)))\n","sub_path":"tests/test_shuffled.py","file_name":"test_shuffled.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109855994","text":"from readthedocs.settings.base import CommunityBaseSettings\n\nimport os\nenviron = os.environ\n\n\nclass CommunitySettings(CommunityBaseSettings):\n MIDDLEWARE_CLASSES = (\n 'readthedocs.core.middleware.ProxyMiddleware',\n 'readthedocs.core.middleware.FooterNoSessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.http.ConditionalGetMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'linaro_django_pagination.middleware.PaginationMiddleware',\n 'readthedocs.core.middleware.SubdomainMiddleware',\n 'readthedocs.core.middleware.SingleVersionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n )\n USE_SUBDOMAIN = environ.get('USE_SUBDOMAIN', False)\n PRODUCTION_DOMAIN = environ.get('HOSTNAME', 'localhost')\n WEBSOCKET_HOST = environ.get('WEBSOCKET_HOST')\n SESSION_COOKIE_DOMAIN = environ.get('HOSTNAME', 'localhost')\n \n ALLOWED_HOSTS = ['*']\n SITE_ROOT = environ['ROOT']\n DEBUG = False\n \n STATIC_ROOT = os.path.join(environ['STATIC_ROOT'], 'static')\n MEDIA_ROOT = os.path.join(environ['STATIC_ROOT'], 'media')\n STATICFILES_DIRS = [\n os.path.join(SITE_ROOT, 'readthedocs', 'static'),\n ]\n\n STATIC_URL = '/static/'\n print('settings values')\n print(STATIC_ROOT)\n print(STATICFILES_DIRS)\n print(MEDIA_ROOT)\n\n ES_HOSTS = ['readthedocs-elasticsearch-client:9200']\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': environ['POSTGRES_DB'],\n 'USER': environ['POSTGRES_USER'],\n 'PASSWORD': environ['POSTGRES_PASSWORD'],\n 'HOST': environ.get('POSTGRES_HOST', 'readthedocs-postgresql'),\n 'PORT': environ.get('READTHEDOCS_POSTGRESQL_SERVICE_PORT', 5432),\n },\n }\n\n ALLOW_PRIVATE_REPOS = True\n REDIS_PORT = environ.get('READTHEDOCS_REDIS_SERVICE_PORT', '6379')\n BROKER_URL = 'redis://readthedocs-redis:' + REDIS_PORT + '/0'\n CELERY_ALWAYS_EAGER = False\n CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']\n CELERY_RESULT_BACKEND = 'redis://readthedocs-redis:' + REDIS_PORT + '/0'\n CORS_ORIGIN_REGEX_WHITELIST = ['^.+$']\n CORS_ALLOW_HEADERS = list(CommunityBaseSettings.CORS_ALLOW_HEADERS) + ['csrftoken']\n CSRF_COOKIE_SECURE = False\n CSRF_COOKIE_HTTPONLY = False\n \n #EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n \n SLUMBER_API_HOST = 'http://localhost:8080'\n SLUMBER_USERNAME = 'admin'\n SLUMBER_PASSWORD = 'admin'\n\n _ = gettext = lambda s: s\n\n LANGUAGES = (\n ('en', gettext('English')),\n )\n\n @property\n def LOGGING(self): # noqa\n logging = super(CommunityProdSettings, self).LOGGING\n logging['formatters']['default']['format'] = '[%(asctime)s] ' + self.LOG_FORMAT\n return logging\n \n LOG_FORMAT = '%(name)s:%(lineno)s[%(process)d]: %(levelname)s %(message)s'\n \n LOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'default': {\n 'format': LOG_FORMAT,\n 'datefmt': '%d/%b/%Y %H:%M:%S',\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'default'\n },\n },\n 'loggers': {\n 'readthedocs': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n 'django': {\n 'handlers':['console'],\n 'propagate': False,\n 'level':'DEBUG',\n },\n '': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': False,\n },\n },\n }\n ALLOW_ADMIN = True\n\nCommunitySettings.load_settings(__name__)\n","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"484806983","text":"\n\"\"\"\nFrequency of elements in an array\n\"\"\"\n\narr=[1,7,1,2,5,7,1,2]\nn=len(arr)\nvisited=[False]*n\n# print(visited)\nfor i in range(n):\n count = 1\n if visited[i]==True:\n continue\n for j in range(i+1,n):\n if arr[i]==arr[j]:\n count+=1\n visited[j]=True\n if(j==n-1):\n print(\"Frequency of element {} is {}\".format(arr[i],count))\n","sub_path":"Arrays/16_frequency of elements in an array.py","file_name":"16_frequency of elements in an array.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238024730","text":"'''\nFor strings S and T, we say \"T divides S\" if and only if S = T + ... + T (T concatenated with itself 1 or \nore times)\n\nReturn the largest string X such that X divides str1 and X divides str2.\n\n \n\nExample 1:\n\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\nExample 2:\n\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\nExample 3:\n\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n \n\nNote:\n\n1 <= str1.length <= 1000\n1 <= str2.length <= 1000\nstr1[i] and str2[i] are English uppercase letters.\n'''\n\ndef gcd_of_strings(str1, str2):\n result = ''\n \n def gcd(a, b):\n length = len(b) / len(a)\n if int(length) != length:\n return False \n return a * length == b\n\n result = ''\n for i in range(1, len(str1) + 1):\n sub_sequence = str1[:i]\n if len(sub_sequence) > len(str2): \n return result\n if gcd(sub_sequence, a) and gcd(sub_sequence, b):\n result = sub_sequence\n\n return result \n","sub_path":"algorithms/strings/gcd_of_string.py","file_name":"gcd_of_string.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"4742476","text":"#!/usr/bin/python3\n\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\nfrom PyQt5.QtCore import QThread, pyqtSignal\nimport serial.tools.list_ports\nimport pyqtgraph as pg\nimport numpy as np\nimport serial\nimport datetime\nimport time\nfrom collections import deque\n\ndef getComPorts():\n tempPorts = []\n ports = serial.tools.list_ports.comports()\n for port in ports:\n tempPorts.append(str(port))\n return tempPorts\n\ndef isStringAnInt(s):\n try:\n int(s)\n return True\n except ValueError:\n return False\n\n# Serial Object\nser = None\nserialbaudrate = 115200\nserialtimeout = 1\nserval2torqueNm = (125.0/2048.0)*(4.44822/1.0)*(0.15) #(125lbs/2048points)*(4.44822N/1lbs)*(0.15m)\n\n# Global Data\nreferencesignalchannel = None\nmeasuredsignalchannel = None\ntopborder = None\nbottomborder = None\nmvctable = {'pf': None, 'df': None, 'dfpf': None}\npercentmvc = 0.3\nvolreflexflexion = None\nrefsignaltype = None\nrefsignalfreq = None\nserialvals = None\ndef getSerialResponse():\n global ser\n endtime = time.time() + 0.5\n serialstring = \"\"\n while (time.time() < endtime):\n newchar = ser.read().decode()\n serialstring += newchar\n if (newchar == '>'):\n break\n return serialstring.strip('<>')\n\n\nclass VolReflexTrialThread(QThread):\n supplyDaqReadings = pyqtSignal(float, float, float)\n printToVolReflexLabel = pyqtSignal(str)\n\n def __init__(self):\n QThread.__init__(self)\n\n def getMeasRefSignals(self):\n global measuredsignalchannel\n global referencesignalchannel\n global serialvals\n ser.write(b'<2>')\n serialstring = getSerialResponse()\n serialvals = serialstring.split(',')\n measuredval = int(serialvals[measuredsignalchannel])\n referenceval = int(serialvals[referencesignalchannel])\n return [referenceval, measuredval]\n\n def getMinMaxRefLevels(self):\n if (volreflexflexion == \"DF\"):\n maxreferenceval = percentmvc*mvctable['df']\n minreferenceval = 0\n elif (volreflexflexion == \"PF\"):\n maxreferenceval = 0\n minreferenceval = -(percentmvc*mvctable['pf'])\n elif (volreflexflexion == \"DFPF\"):\n maxreferenceval = percentmvc*mvctable['dfpf']\n minreferenceval = -maxreferenceval\n\n referencevalspan = maxreferenceval - minreferenceval\n return [minreferenceval, maxreferenceval, referencevalspan]\n\n def waitForNewZeroLevel(self):\n whatever = 0\n\n def standardRun(self):\n global topborder\n global bottomborder\n global refsignaltype\n global refsignalfreq\n global serialvals\n self.printToVolReflexLabel.emit(\"Rest Phase\")\n starttime = time.time()\n zeroduration = 5\n zerocount = 0\n zerolevel = 0\n endtime = starttime + zeroduration\n while (time.time() < endtime):\n [referenceval, measuredval] = self.getMeasRefSignals()\n zerocount = zerocount + 1\n zerolevel = zerolevel + (measuredval - zerolevel)/zerocount\n progressbarval = round(100*(time.time() - starttime)/zeroduration)\n self.supplyDaqReadings.emit(0, 0, progressbarval)\n\n zerolevel = int(zerolevel)\n measuredvalqueue = deque([0, 0, 0])\n [minreferenceval, maxreferenceval, referencevalspan] = self.getMinMaxRefLevels()\n starttime = time.time()\n if refsignaltype == 'sine':\n period = 1/refsignalfreq\n trialduration = 20*period + 5 #trial will last 20 periods plus a 5 second adjustment period\n else:\n trialduration = 60\n endtime = starttime + trialduration\n self.printToVolReflexLabel.emit(\"Match the Reference Line\")\n while (time.time() < endtime):\n [referenceval, measuredval] = self.getMeasRefSignals()\n measuredvalqueue.popleft()\n measuredvalqueue.append(serval2torqueNm*(measuredval - zerolevel))\n measuredval = np.mean(measuredvalqueue)\n referenceval = int(serialvals[referencesignalchannel])\n if (measuredval < bottomborder):\n measuredval = bottomborder\n elif (measuredval > topborder):\n measuredval = topborder\n\n if (refsignaltype in ['prbs']): #PRBS input\n if (referenceval > 2048): #high input\n referenceval = maxreferenceval\n else: #low input\n referenceval = minreferenceval\n elif (refsignaltype in ['sine']):\n referenceval = minreferenceval + (referenceval/4095)*referencevalspan # this assumes A/D measurements from the 12-bit DAQ\n\n\n progressbarval = round(100*(time.time() - starttime)/trialduration)\n self.supplyDaqReadings.emit(measuredval, referenceval, progressbarval)\n\n self.supplyDaqReadings.emit(0,0,0)\n self.printToVolReflexLabel.emit(\"Done\")\n ser.write(b'<1>')\n\n def stepRun(self):\n whatever = 0\n\n def run(self):\n global refsignaltype\n if refsignaltype in ['sine', 'prbs', 'other']:\n self.standardRun()\n elif refsignaltype in ['step']:\n self.stepRun()\n\n\nclass MainWindow(QtWidgets.QMainWindow):\n\n # Class Data\n\n # Setting Data\n _patientnumber = None\n _comport = None\n _serialstatus = None\n\n # MVC Trial Data\n _mvctrialflexion = None\n _mvctrialfilename = None\n _mvcfiletoimport = None\n _mvctrialcounter = 0\n _mvctrialrepetition = 0\n _mvctimer = None\n\n # MVC import\n _mvcdffile = None\n _mvcpffile = None\n\n # Voluntary Reflex Trial data\n _volreflexankleposition = None\n _volreflexfilename = None\n _volreflexreferencesignal = None\n _volreflextrialnumber = None\n\n\n def __init__(self):\n super(MainWindow, self).__init__()\n ag = QDesktopWidget().availableGeometry()\n self.setGeometry(0, 0, 1366, 650)\n uic.loadUi('ResearchGui.ui', self)\n self.show()\n self.startSettingsTab()\n\n # Initialize Settings Tab Lists\n def refreshComPortList(self):\n self.list_comport.clear()\n ports = getComPorts()\n for port in ports:\n self.list_comport.addItem(port)\n\n def initReferenceSignalList(self):\n self.list_referencesignal.clear()\n for channel in range(0,8):\n self.list_referencesignal.addItem(\"Channel {}\".format(channel))\n\n def initMeasuredSignalList(self):\n self.list_measuredsignal.clear()\n for channel in range(0,8):\n self.list_measuredsignal.addItem(\"Channel {}\".format(channel))\n\n # Button functions\n def selectComPort(self):\n portobj = self.list_comport.selectedItems()\n for i in list(portobj):\n selectedport = str(i.text())\n selectedportparts = selectedport.split(\" \")\n self._comport = selectedportparts[0]\n self.lbl_comport.setText(self._comport)\n\n def selectReferenceSignalChannel(self):\n global referencesignalchannel\n channelobj = self.list_referencesignal.selectedItems()\n for i in list(channelobj):\n selectedchannel = str(i.text())\n selectedchannelparts = selectedchannel.split(\" \")\n referencesignalchannel = int(selectedchannelparts[1])\n self.lbl_referencesignal.setText(\"Channel {}\".format(referencesignalchannel))\n\n def selectMeasuredSignalChannel(self):\n global measuredsignalchannel\n channelobj = self.list_measuredsignal.selectedItems()\n for i in list(channelobj):\n selectedchannel = str(i.text())\n selectedchannelparts = selectedchannel.split(\" \")\n measuredsignalchannel = int(selectedchannelparts[1])\n self.lbl_measuredsignal.setText(\"Channel {}\".format(measuredsignalchannel))\n\n def setPatientNumber(self):\n tempStr = self.lineedit_patientnumber.text()\n self.lbl_patientnumbererror.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)\n if (isStringAnInt(tempStr)):\n tempInt = int(tempStr)\n if (tempInt >= 0 and tempInt <= 99 ):\n self._patientnumber = tempInt\n self.lbl_patientnumber.setText(\"{}\".format(self._patientnumber))\n self.lbl_patientnumbererror.setText(\"\")\n self.completeMvcTrialFilename()\n self.completeVoluntaryReflexFilename()\n else:\n self._patientnumber = None\n self.lbl_patientnumber.setText(\"\")\n self.lbl_patientnumbererror.setText(\"Integer Must Be Between 0-99\")\n else:\n self._patientnumber = None\n self.lbl_patientnumber.setText(\"\")\n self.lbl_patientnumbererror.setText(\"Patient Number Must Be An Integer\")\n\n def resetSerial(self):\n global ser\n if (self._comport is None):\n self.lbl_serialstatus.setText(\"Select COM Port\")\n elif ((self._comport is not None) and (isinstance(ser, serial.Serial))):\n try:\n ser.close()\n ser = serial.Serial(port=self._comport, baudrate=serialbaudrate, timeout=serialtimeout)\n self.lbl_serialstatus.setText(\"Connected\")\n except serial.SerialException as e:\n self.lbl_serialstatus.setText(\"Error Connecting\")\n elif ((self._comport is not None) and (not isinstance(ser, serial.Serial))):\n try:\n ser = serial.Serial(port=self._comport, baudrate=serialbaudrate, timeout=serialtimeout)\n self.lbl_serialstatus.setText(\"Connected\")\n except serial.SerialException as e:\n self.lbl_serialstatus.setText(\"Error Connecting\")\n\n def setMvcTrialFlexion(self, btn_mvcflexion):\n tempStr = btn_mvcflexion.text()\n if ( tempStr == \"Plantarflexion\" ):\n self._mvctrialflexion = \"PF\"\n elif (tempStr == \"Dorsiflexion\" ):\n self._mvctrialflexion = \"DF\"\n self.completeMvcTrialFilename()\n\n def completeMvcTrialFilename(self):\n if (self._patientnumber is not None and self._mvctrialflexion is not None):\n self._mvctrialfilename = \"Patient{}_MVC_{}.txt\".format(self._patientnumber, self._mvctrialflexion)\n self.lbl_mvcmeasurementfilename.setText(self._mvctrialfilename)\n else:\n self._mvctrialfilename = None\n self.lbl_mvcmeasurementfilename.setText(\"Complete Settings\")\n\n\n def startMvcTrial(self):\n global ser\n # Exit routine if settings aren't complete\n if (self.lbl_mvcmeasurementfilename.text() == \"Complete Settings\"):\n self.lbl_mvctriallivenotes.setText(\"Complete Settings\")\n return\n\n # Check if serial is connected\n if ser is None:\n self.lbl_mvctriallivenotes.setText(\"Connect Serial Before Proceeding\")\n return\n elif isinstance(ser, serial.Serial):\n ser.flushInput()\n ser.write(b'<8>')\n serialstring = getSerialResponse()\n # Check if sd card is inserted\n if (serialstring == \"False\"):\n self.lbl_mvctriallivenotes.setText(\"Insert SD Card\")\n return\n elif (serialstring == \"\"):\n self.lbl_mvctriallivenotes.setText(\"No SD Card Response\")\n return\n else:\n self.lbl_mvctriallivenotes.setText(\"Something has gone very badly...\")\n return\n\n # Start Writing Process\n ser.write(b'<6,6,0>') # Insert Value into 6th channel of daq reading for post-process flag\n n = datetime.datetime.now()\n startStr = \"<0,{},{},{},{},{},{},{}>\".format(self._mvctrialfilename, n.year, n.month, n.day, n.hour, n.minute, n.second)\n bStartStr = str.encode(startStr)\n ser.write(bStartStr)\n serialstring = getSerialResponse()\n if (len(serialstring) != 0): # This would happen if there was an unexpected error with the DAQ\n self.lbl_mvctriallivenotes.setText(serialstring)\n return\n\n self._mvctrialcounter = 0\n self._mvctrialrepetition = 0\n self._mvctimer = QtCore.QTimer()\n self._mvctimer.timeout.connect(self.mvcTrialHandler)\n self._mvctimer.start(1000)\n\n def mvcTrialHandler(self):\n firstrestend = 5\n firstflexend = firstrestend + 5\n secondrestend = firstflexend + 15\n secondflexend = secondrestend + 5\n thirdrestend = secondflexend + 15\n thirdflexend = thirdrestend + 5\n if (self._mvctrialcounter < firstrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Flex in {}\".format(firstrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= firstrestend and self._mvctrialcounter < firstflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(firstflexend - self._mvctrialcounter))\n elif (self._mvctrialcounter >= firstflexend and self._mvctrialcounter < secondrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Rest. Flex in {}\".format(secondrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= secondrestend and self._mvctrialcounter < secondflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(secondflexend - self._mvctrialcounter))\n elif (self._mvctrialcounter >= secondflexend and self._mvctrialcounter < thirdrestend):\n ser.write(b'<6,6,0>')\n self.lbl_mvctriallivenotes.setText(\"Rest. Flex in {}\".format(thirdrestend-self._mvctrialcounter))\n elif (self._mvctrialcounter >= thirdrestend and self._mvctrialcounter < thirdflexend):\n ser.write(b'<6,6,1>')\n self.lbl_mvctriallivenotes.setText(\"Goooo!!! {}\".format(thirdflexend - self._mvctrialcounter))\n else:\n ser.write(b'<1>')\n self.lbl_mvctriallivenotes.setText(\"Done\")\n self._mvctimer.stop()\n self._mvctimer.deleteLater()\n\n self._mvctrialcounter += 1\n\n\n def getMvcFile(self):\n #Open filedialog box\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n files, _ = QFileDialog.getOpenFileNames(self, \"QFileDialog.getOpenFileNames()\", \"\",\n \"Text Files (*.txt)\", options=options)\n if files:\n for f in files:\n if (f.find('MVC') == -1):\n self.lbl_mvctriallivenotes.setText(\"Please Select MVC File\")\n else:\n tempfullfilepath = f\n f = f.split('/')\n f = f[-1] # now f is just the filename\n tempfilename = f\n f = f.strip('.txt')\n f = f.split('_')\n tempflexion = f[-1]\n temppatientnumber = f[0]\n temppatientnumber = int(temppatientnumber.strip(\"Patient\"))\n if ( temppatientnumber != self._patientnumber):\n self.lbl_mvctriallivenotes.setText(\"Patient Number does not match. Import aborted\")\n else:\n if (tempflexion == 'DF'):\n self._mvcdffile = tempfullfilepath\n self.lbl_mvctriallivenotes.setText(\"\")\n self.lineedit_mvcmanual.setText(tempfilename)\n elif (tempflexion == 'PF'):\n self._mvcpffile = tempfullfilepath\n self.lbl_mvctriallivenotes.setText(\"\")\n self.lineedit_mvcmanual.setText(tempfilename)\n else:\n self.lbl_mvctriallivenotes.setText(\"Filename does not specify flexion\")\n\n def importMvcFiles(self):\n global measuredsignalchannel\n global mvctable\n if measuredsignalchannel is None:\n self.lbl_mvctriallivenotes.setText('Set Measured Signal Channel')\n return\n tempfilestoimport = []\n if self._mvcdffile is not None:\n tempfilestoimport.append(self._mvcdffile)\n if self._mvcpffile is not None:\n tempfilestoimport.append(self._mvcpffile)\n\n if (len(tempfilestoimport)==0):\n self.lbl_mvctriallivenotes.setText('Choose file to import')\n return\n\n for f in tempfilestoimport:\n if (f.find('DF') != -1):\n tempflexion = 'DF'\n elif (f.find('PF') != -1):\n tempflexion = 'PF'\n else:\n self.lbl_mvctriallivenotes.setText(\"Flexion direction was not found in file during import\")\n return\n tempdata = np.loadtxt(fname=f, delimiter=',')\n flagcol = tempdata[:,6]\n measuredsigdata = tempdata[:, measuredsignalchannel]\n # get indices where 'rest' or 'flex' periods end\n rest_flex_ending_indices = [0]\n currentflag = flagcol[0]\n for i in range(1, len(flagcol)):\n if (flagcol[i] != currentflag):\n currentflag = flagcol[i]\n rest_flex_ending_indices.append(i)\n elif (i==(len(flagcol)-1)):\n rest_flex_ending_indices.append(i+1)\n for i in range(1, len(rest_flex_ending_indices)):\n if ((rest_flex_ending_indices[i] - rest_flex_ending_indices[i-1]) < 4000):\n self.lbl_mvctriallivenotes.setText(\"Rest or flex period was less than 4000 readings. Check data\")\n return\n mvcserialvals = []\n for i in range(0,3):\n restbeginindex = rest_flex_ending_indices[i*2]\n restendindex = rest_flex_ending_indices[i*2 + 1]\n flexbeginindex = rest_flex_ending_indices[i*2 + 1]\n flexendindex = rest_flex_ending_indices[i*2 + 2]\n restmeasurements = measuredsigdata[restbeginindex+500:restendindex-500] # limit rest measurements just in case the patient flexed early or late\n mvcmeasaurements = measuredsigdata[flexbeginindex:flexendindex]\n zerolevel = int(restmeasurements.mean())\n if (tempflexion == 'DF'):\n mvcserialvals.append(int(mvcmeasaurements.max() - zerolevel))\n elif (tempflexion == 'PF'):\n mvcserialvals.append(int(mvcmeasaurements.min() - zerolevel))\n\n if (tempflexion == 'DF'):\n mvcserialval = abs(max(mvcserialvals))\n mvctable['pf'] = mvcserialval*serval2torqueNm\n self.tablewidget_mvc.setItem(0, 0, QTableWidgetItem(str(round(mvctable['pf'],2))))\n elif (tempflexion == 'PF'):\n mvcserialval = abs(min(mvcserialvals))\n mvctable['df'] = mvcserialval*serval2torqueNm\n self.tablewidget_mvc.setItem(0, 1, QTableWidgetItem(str(round(mvctable['df'],2))))\n self.setDfPfMvc()\n\n def setDfPfMvc(self):\n global mvctable\n if mvctable['pf'] is not None and mvctable['df'] is not None:\n mvctable['dfpf'] = np.mean([abs(mvctable['pf']), abs(mvctable['df'])])\n else:\n mvctable['dfpf'] = None\n\n def customizeSetupTab(self):\n # Expand table widget column\n self.tablewidget_mvc.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n # Setup MVC Trial Flexion Button Group\n self.mvctrialflexionbuttongroup = QButtonGroup(self)\n self.mvctrialflexionbuttongroup.addButton(self.rbtn_mvcmeasurementpf)\n self.mvctrialflexionbuttongroup.addButton(self.rbtn_mvcmeasurementdf)\n self.mvctrialflexionbuttongroup.buttonClicked.connect(self.setMvcTrialFlexion)\n\n def customizeVoluntaryReflexMeasurementTab(self):\n # Add pyqtgraph plot\n\n # Set axes properties\n xAxisItem = pg.AxisItem(orientation='bottom', showValues=False)\n yAxisItem = pg.AxisItem(orientation='left', showValues=True)\n xAxisItem.showLabel(False)\n yAxisItem.showLabel(False)\n\n # Initialize plot\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n self.plotwin = pg.GraphicsLayoutWidget()\n self.layout_pyqtgraph.addWidget(self.plotwin)\n self.plt = self.plotwin.addPlot(row=0, col=0, rowspan=1, colspan=1, axisItems={'left': yAxisItem, 'bottom': xAxisItem})\n self.plt.setRange(xRange=(0, 1), yRange=(-1, 1), padding=0.0)\n\n # Init lines\n self.reference_line = pg.PlotCurveItem()\n self.measured_line = pg.PlotCurveItem()\n self.zero_line = pg.PlotCurveItem()\n\n # Define line properties and set properties\n reference_line_pen = pg.mkPen(color='c', width=30, style=QtCore.Qt.SolidLine)\n measured_line_pen = pg.mkPen(color='r', width=10, style=QtCore.Qt.SolidLine)\n zero_line_pen = pg.mkPen(color='k', width=5, style=QtCore.Qt.DashLine)\n\n self.measured_line.setPen(measured_line_pen)\n self.zero_line.setPen(zero_line_pen)\n self.reference_line.setPen(reference_line_pen)\n\n # Set lines in initial position\n xdata = np.array([0, 1])\n ydata = np.array([0, 0])\n self.reference_line.setData(x=xdata, y=ydata)\n self.measured_line.setData(x=xdata, y=ydata)\n self.zero_line.setData(x=xdata, y=ydata)\n\n # Add lines to plot\n self.plt.addItem(self.reference_line)\n self.plt.addItem(self.measured_line)\n self.plt.addItem(self.zero_line)\n\n # Redo Ankle Position Radiobutton text\n self.rbtn_volreflex5pf.setText(u' 5\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex10pf.setText(u'10\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex15pf.setText(u'15\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex20pf.setText(u'20\\N{DEGREE SIGN} PF')\n self.rbtn_volreflex0.setText(u' 0\\N{DEGREE SIGN}')\n self.rbtn_volreflex5df.setText(u' 5\\N{DEGREE SIGN} DF')\n self.rbtn_volreflex10df.setText(u'10\\N{DEGREE SIGN} DF')\n\n # Group Ankle Position RadioButtons\n self.volreflexanklepositionbuttongroup = QButtonGroup(self)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex5pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex10pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex15pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex20pf)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex0)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex5df)\n self.volreflexanklepositionbuttongroup.addButton(self.rbtn_volreflex10df)\n self.volreflexanklepositionbuttongroup.buttonClicked.connect(self.setVoluntaryReflexAnklePosition)\n\n # Group Voluntary Reflex Flexion RadioButtons\n self.volreflexflexionbuttongroup = QButtonGroup(self)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexdf)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexpf)\n self.volreflexflexionbuttongroup.addButton(self.rbtn_volreflexdfpf)\n self.volreflexflexionbuttongroup.buttonClicked.connect(self.setVoluntaryReflexFlexion)\n\n # Group Voluntary Reflex Sinusoid Freqency RadioButtons\n self.volreflexrefsigbtngroup = QButtonGroup(self)\n # Sinusoid Buttons\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig1) #0.25 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig2) #0.50 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig3) #0.75 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig4) #1.00 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig5) #1.25 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig6) #1.50 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig7) #1.75 Hz\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig8) #2.00 Hz\n # Other reference signal radiobutons\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_prbs) #PRBS\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_step) #Step\n self.volreflexrefsigbtngroup.addButton(self.rbtn_refsig_other) #Other\n\n self.volreflexrefsigbtngroup.buttonClicked.connect(self.setReferenceSignal)\n\n # Connect Trial Spinbox\n self.spinboxtrialnumber.valueChanged.connect(self.setVoluntaryReflexTrialNumber)\n\n def minimizeWindow(self):\n self.showNormal()\n self.showMinimized()\n\n def maximizeWindow(self):\n self.showNormal()\n self.showMaximized()\n\n def closeWindow(self):\n QApplication.quit()\n\n def setVoluntaryReflexTrialNumber(self, newvalue):\n if (newvalue == 0):\n self._volreflextrialnumber = None\n else:\n self._volreflextrialnumber = int(newvalue)\n self.completeVoluntaryReflexFilename()\n\n def setReferenceSignal(self, btn_volreflexreferencesignal):\n global refsignaltype\n global refsignalfreq\n btntext = btn_volreflexreferencesignal.text()\n if (btntext == \"Other\"):\n self._volreflexreferencesignal = None\n refsignaltype = 'other'\n refsignalfreq = None\n elif (btntext == \"PRBS\"):\n refsignaltype = 'prbs'\n refsignalfreq = None\n self._volreflexreferencesignal = btntext\n elif (btntext == \"Step\"):\n refsignaltype = 'step'\n refsignalfreq = None\n self._volreflexreferencesignal = btntext\n else:\n refsignaltype = 'sine'\n # get sinusoid frequency\n freqtext = btntext\n hzind = freqtext.find('Hz')\n freqtext = freqtext[0:hzind]\n refsignalfreq = float(freqtext)\n # make frequency info ready to add to filename\n btntext = btntext.replace(\" \", \"\")\n self._volreflexreferencesignal = btntext.replace(\".\", \"-\")\n self.completeVoluntaryReflexFilename()\n\n def setVoluntaryReflexAnklePosition(self, btn_volreflexankleposition):\n tempAnklePosition = btn_volreflexankleposition.objectName()\n if ( tempAnklePosition == \"rbtn_volreflex0\" ):\n self._volreflexankleposition = \"Neutral\"\n elif ( tempAnklePosition == \"rbtn_volreflex5df\"):\n self._volreflexankleposition = \"5DF\"\n elif ( tempAnklePosition == \"rbtn_volreflex10df\"):\n self._volreflexankleposition = \"10DF\"\n elif ( tempAnklePosition == \"rbtn_volreflex5pf\"):\n self._volreflexankleposition = \"5PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex10pf\"):\n self._volreflexankleposition = \"10PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex15pf\"):\n self._volreflexankleposition = \"15PF\"\n elif ( tempAnklePosition == \"rbtn_volreflex20pf\"):\n self._volreflexankleposition = \"20PF\"\n else:\n self._volreflexankleposition = None\n self.completeVoluntaryReflexFilename()\n\n def setVoluntaryReflexFlexion(self, btn_volreflexflexion):\n global topborder\n global bottomborder\n global mvctable\n global percentmvc\n global volreflexflexion\n tempFlexion = btn_volreflexflexion.text()\n if ( tempFlexion == \"Plantarflexion\" ):\n volreflexflexion = \"PF\"\n if (mvctable['pf'] is None):\n self.lbl_volreflexlivenotes.setText('Import PF MVC Trial Readings')\n else:\n #Set Plot Ranges for Test\n self.lbl_trialflexionmvc.setText(str(round(mvctable['pf'],2)))\n refsignalmax = 0\n refsignalmin = -(percentmvc*mvctable['pf'])\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.3*refsignalspan\n bottomborder = refsignalmin-0.6*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n elif (tempFlexion == \"Dorsiflexion\" ):\n volreflexflexion = \"DF\"\n if (mvctable['df'] is None):\n self.lbl_volreflexlivenotes.setText('Import DF MVC Trial Readings')\n else:\n #Set Plot Ranges for Test\n self.lbl_trialflexionmvc.setText(str(round(mvctable['df'],2)))\n refsignalmax = (percentmvc*mvctable['df'])\n refsignalmin = 0\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.6*refsignalspan\n bottomborder = refsignalmin-0.3*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n elif (tempFlexion == \"Dorsiflexion-Plantarflexion\"):\n volreflexflexion = \"DFPF\"\n if (mvctable['dfpf'] is None):\n self.lbl_volreflexlivenotes.setText('Import DF and PF MVC Trial Readings')\n else:\n avgmvc = mvctable['dfpf']\n self.lbl_trialflexionmvc.setText(str(round(avgmvc, 2)))\n refsignalmax = percentmvc*avgmvc\n refsignalmin = -percentmvc*avgmvc\n refsignalspan = abs(refsignalmax - refsignalmin)\n topborder = refsignalmax+0.3*refsignalspan\n bottomborder = refsignalmin-0.3*refsignalspan\n self.plt.setRange(xRange=(0,1), yRange=(bottomborder, topborder), padding=0.0)\n else:\n volreflexflexion = None\n self.completeVoluntaryReflexFilename()\n\n def completeVoluntaryReflexFilename(self):\n global volreflexflexion\n # Check if Ankle Position, Flexion and Patient Number are set. If not, exit routine\n if (self._volreflexankleposition is None or volreflexflexion is None or self._patientnumber is None):\n self.lbl_volreflexfilename.setText(\"Complete Settings\")\n return\n\n self._volreflexfilename = \"PatNo{}_VR_AnklePos{}_{}\".format(self._patientnumber, self._volreflexankleposition, volreflexflexion)\n # Optional parameters\n if (self._volreflexreferencesignal is not None):\n self._volreflexfilename = self._volreflexfilename + \"_{}\".format(self._volreflexreferencesignal)\n if (self._volreflextrialnumber is not None):\n self._volreflexfilename = self._volreflexfilename + \"_Trial{}\".format(self._volreflextrialnumber)\n # Finalize filename\n self._volreflexfilename = self._volreflexfilename + \".txt\"\n self.lbl_volreflexfilename.setText(self._volreflexfilename)\n\n def startVoluntaryReflexTrail(self):\n global ser\n global measuredsignalchannel\n global referencesignalchannel\n #Check Settings\n if (self._volreflextrialthread.isRunning()):\n self.lbl_volreflexlivenotes.setText(\"Thread Is Already Running\")\n return\n self.lbl_volreflexlivenotes.setText(\"\")\n if (measuredsignalchannel is None):\n self.lbl_volreflexlivenotes.setText(\"Set Measured Signal Channel\")\n return\n if (referencesignalchannel is None):\n self.lbl_volreflexlivenotes.setText(\"Set Reference Signal Channel\")\n return\n if not (isinstance(ser, serial.Serial)):\n self.lbl_volreflexlivenotes.setText(\"Connect Serial Device\")\n return\n if (self._volreflexankleposition is None):\n self.lbl_volreflexlivenotes.setText(\"Set Ankle Positon\")\n return\n if (volreflexflexion is None):\n self.lbl_volreflexlivenotes.setText(\"Set Flexion\")\n return\n\n # Ensure channels reading correct voltage Ranges\n voltagerangecommand_measuredsignal = \"<5,{},1>\".format(measuredsignalchannel) # assuems -5V to +5V readings\n voltagerangecommand_referencesignal = \"<5,{},0>\".format(referencesignalchannel) # assumes 0-5V readings\n ser.write(str.encode(voltagerangecommand_measuredsignal))\n ser.write(str.encode(voltagerangecommand_referencesignal))\n # Start Writing Process\n ser.write(b'<6,6,0>') # Insert Value into 6th channel of daq reading for post-process flag\n n = datetime.datetime.now()\n startStr = \"<0,{},{},{},{},{},{},{}>\".format(self._volreflexfilename, n.year, n.month, n.day, n.hour, n.minute, n.second)\n bStartStr = str.encode(startStr)\n ser.write(bStartStr) #start writing to sd\n serialstring = getSerialResponse()\n if (len(serialstring) != 0): # This would happen if there was an unexpected error with the DAQ\n self.lbl_volreflexlivenotes.setText(serialstring)\n return\n self._volreflextrialthread.start()\n\n def initVoluntaryReflexTrialThread(self):\n self._volreflextrialthread = VolReflexTrialThread()\n self._volreflextrialthread.printToVolReflexLabel.connect(self.printToVolReflexLabel)\n self._volreflextrialthread.supplyDaqReadings.connect(self.updateVolReflexPlot)\n\n def updateVolReflexPlot(self, measuredval, referenceval, progressbarval):\n #Update Progressbar\n self.prog_volreflextrial.setValue(progressbarval)\n self.prog_volreflextrial.update()\n\n #Update Plot\n self.reference_line.setData(x=np.array([0,1]),\n y=np.array([referenceval, referenceval]))\n self.measured_line.setData(x=np.array([0,1]),\n y=np.array([measuredval, measuredval]))\n self.plt.update()\n\n def printToVolReflexLabel(self, inputStr):\n self.lbl_volreflexlivenotes.setText(inputStr)\n\n def connectButtonsInSetupTab(self):\n self.btn_selectcomport.clicked.connect(self.selectComPort)\n self.btn_refreshcomlist.clicked.connect(self.refreshComPortList)\n self.btn_selectreferencesignal.clicked.connect(self.selectReferenceSignalChannel)\n self.btn_selectmeasuredsignal.clicked.connect(self.selectMeasuredSignalChannel)\n self.btn_setpatientnumber.clicked.connect(self.setPatientNumber)\n self.btn_resetserial.clicked.connect(self.resetSerial)\n self.btn_startmvctrial.clicked.connect(self.startMvcTrial)\n self.btn_getmvcfiles.clicked.connect(self.getMvcFile)\n self.btn_importmvcfiles.clicked.connect(self.importMvcFiles)\n self.btn_startvolreflextrial.clicked.connect(self.startVoluntaryReflexTrail)\n self.btn_minimize.clicked.connect(self.minimizeWindow)\n self.btn_maximize.clicked.connect(self.maximizeWindow)\n self.btn_close.clicked.connect(self.closeWindow)\n self.btn_setmvcmanual.clicked.connect(self.setmvcmanual)\n\n def setmvcmanual(self):\n mvctable['df'] = float(self.lineedit_dfmvcman.text())\n mvctable['pf'] = float(self.lineedit_pfmvcman.text())\n self.tablewidget_mvc.setItem(0, 0, QTableWidgetItem(str(round(mvctable['pf'],2))))\n self.tablewidget_mvc.setItem(0, 1, QTableWidgetItem(str(round(mvctable['df'],2))))\n self.setDfPfMvc()\n\n def startSettingsTab(self):\n\n # Complete GUI Programming\n self.customizeSetupTab()\n self.customizeVoluntaryReflexMeasurementTab()\n\n # Init Settings Tab Lists\n self.refreshComPortList()\n self.initReferenceSignalList()\n self.initMeasuredSignalList()\n\n # Connect buttons\n self.connectButtonsInSetupTab()\n\n #Init Voluntary Reflex Trial Thread\n self.initVoluntaryReflexTrialThread()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec_())\n","sub_path":"ResearchGUI/VoluntaryReflexGui.py","file_name":"VoluntaryReflexGui.py","file_ext":"py","file_size_in_byte":35832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368981812","text":"#!/usr/bin/python\n\nimport random, sys\nfrom optparse import OptionParser\n\nclass comm:\n def __init__(self, filename, filename2):\n if filename == '-':\n g = open(filename2, 'r')\n self.lines2 = g.readlines()\n g.close()\n self.lines1 = sys.stdin.readlines()\n elif filename2 == '-':\n f = open(filename, 'r')\n self.lines1 = f.readlines()\n f.close()\n self.lines2 = sys.stdin.readlines()\n else:\n f = open(filename, 'r')\n self.lines1 = f.readlines()\n f.close()\n g = open(filename2, 'r')\n self.lines2 = g.readlines()\n g.close()\n\n def difference_output(self, is_unsorted, col_1_suppressed, col_2_suppressed, col_3_suppressed):\n print_string = \"\"\n if is_unsorted == \"False\":\n file_set = 1\n a = 0\n b = 0\n lines1_length = len(self.lines1)\n lines2_length = len(self.lines2)\n while (len(self.lines1) > 0 or len(self.lines2) > 0):#TODO: change and to or\n if(len(self.lines1) <= 0):\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n for i in range(len(self.lines2)):\n print_string+= self.lines2[i]# + \"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n for i in range(len(self.lines2)):\n print_string+= \"\\t\"+self.lines2[i]# + \"\\n\"\n sys.stdout.write(print_string)\n return\n if(len(self.lines2) <= 0):\n if(col_1_suppressed == \"False\"):\n for i in range(len(self.lines1)):\n print_string+= self.lines1[i]# + \"\\n\"\n \n sys.stdout.write(print_string)\n return\n if(file_set == 1):\n for i in range(len(self.lines1)):\n for j in range(len(self.lines2)):\n # print \"File 1: \" + self.lines1[i]\n # print \"File 2: \" + self.lines2[j]\n if self.lines1[i] == self.lines2[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines1[i]#+\"\\n\"\n self.lines1.remove(self.lines1[i])\n self.lines2.remove(self.lines2[j])\n break\n elif j == len(self.lines2)-1:\n if(col_1_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n self.lines1.remove(self.lines1[i])\n break\n lines1_length-=1;\n if (len(self.lines1) != 0 and len(self.lines2)!=0):\n #print \"1: \" + self.lines1[0]\n #print \"2: \" + self.lines2[0]\n if(self.lines1[0] < self.lines2[0]):\n file_set = 1 \n else:\n file_set = 2\n if(file_set == 2):\n for i in range(len(self.lines2)):\n for j in range(len(self.lines1)):\n #print \"File 2: \" + self.lines2[i]\n #print \"File 1: \" + self.lines1[j]\n if self.lines2[i] == self.lines1[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines2[i]#+\"\\n\"\n self.lines1.remove(self.lines1[j])\n self.lines2.remove(self.lines2[i])\n break\n elif j == len(self.lines1)-1:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n print_string += self.lines2[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n print_string += \"\\t\" + self.lines2[i]#+\"\\n\"\n self.lines2.remove(self.lines2[i])\n break\n lines2_length-=1;\n if (len(self.lines1) != 0 and len(self.lines2)!=0):\n #print \"1: \" + self.lines1[0]\n #print \"2: \" + self.lines2[0]\n if(self.lines1[0] < self.lines2[0]):\n file_set = 1\n else:\n file_set = 2\n sys.stdout.write(print_string)\n return\n \n else:\n for i in range(len(self.lines1)):\n for j in range(len(self.lines2)):\n \n if self.lines1[i] == self.lines2[j]:\n if(col_1_suppressed == \"True\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"True\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\"+self.lines1[i]#+\"\\n\"\n elif(col_1_suppressed == \"False\" and col_2_suppressed == \"False\" and col_3_suppressed == \"False\"):\n print_string += \"\\t\\t\" + self.lines1[i]#+\"\\n\"\n self.lines2.remove(self.lines2[j])\n break\n\n elif j == len(self.lines2)-1:\n if(col_1_suppressed == \"False\"):\n print_string += self.lines1[i]#+\"\\n\"\n for i in range(len(self.lines2)):\n if(col_1_suppressed == \"False\" and col_2_suppressed == \"False\"):\n print_string += \"\\t\" + self.lines2[i]\n elif(col_1_suppressed == \"True\" and col_2_suppressed == \"False\"):\n print_string += self.lines2[i]\n else:\n break\n sys.stdout.write(print_string)\n return\n \n\n\ndef main():\n version_msg = \"%prog 2.0\"\n usage_msg = \"\"\"%prog [OPTION]... FILE\n\nOutput randomly selected lines from FILE.\"\"\"\n\n parser = OptionParser(version=version_msg,\nusage=usage_msg)\n parser.add_option(\"-u\", \"--unsorted\",\n action=\"store_true\", dest=\"is_unsorted\", default=\"False\", help=\"determines whether function is sorted or unsorted.\")\n parser.add_option(\"-1\", \"--suppress_col_1\", \n action=\"store_true\", dest=\"col_1_suppressed\", default=\"False\", help=\"choose to suppress column 1 in the output.\")\n parser.add_option(\"-2\", \"--suppress_col_2\",\n action=\"store_true\", dest=\"col_2_suppressed\", default=\"False\", help=\"choose to suppress column 2 in the output.\")\n parser.add_option(\"-3\", \"--suppress_col_3\", \n action=\"store_true\", dest=\"col_3_suppressed\", default=\"False\", help=\"choose to suppress column 3 in the output.\")\n options, args = parser.parse_args(sys.argv[1:])\n\n try:\n is_unsorted = str(options.is_unsorted)\n except:\n parser.error(\"invalid value for UNSORTED: {0}\".\n format(options.is_unsorted))\n try:\n col_1_suppressed = str(options.col_1_suppressed)\n except:\n parser.error(\"invalid value for COL_1_SUPPRESSED: {0}\".\n format(options.col_1_suppressed))\n try:\n col_2_suppressed = str(options.col_2_suppressed)\n except:\n parser.error(\"invalid value for COL_2_SUPPRESSED: {0}\".\n format(options.col_2_suppressed))\n try:\n col_3_suppressed = str(options.col_3_suppressed)\n except:\n parser.error(\"invalid value for COL_3_SUPPRESSED: {0}\".\n format(options.col_3_suppressed))\n\n if len(args) != 2: #TODO: check this\n parser.error(\"wrong number of operands\")\n \n file_1 = args[0]\n file_2 = args[1]\n #TODO: check if '-' is input\n try:\n generator = comm(file_1, file_2)\n generator.difference_output(is_unsorted, col_1_suppressed, col_2_suppressed, col_3_suppressed)\n except IOError(errno, strerror):\n parser.error(\"I/O error({0}): {1}\".\n format(errno, strerror))\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Assignment 3/comm.py","file_name":"comm.py","file_ext":"py","file_size_in_byte":10182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241112024","text":"from django.db import models\nfrom django.contrib.auth import get_user_model\nfrom phonenumber_field.modelfields import PhoneNumberField\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(\n get_user_model(),\n related_name='profile',\n on_delete=models.CASCADE,\n verbose_name='User'\n )\n phone_number = PhoneNumberField(\n null=False,\n blank=False,\n verbose_name='Phone Number'\n )\n\n def __str__(self):\n return self.user.get_full_name() + \"'s Profile\"\n\n class Meta:\n db_table = 'profiles'\n verbose_name = 'Profile'\n verbose_name_plural = 'Profiles'\n","sub_path":"source/accounts/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41205750","text":"#!/usr/bin/env python\n#coding: utf-8\n__author__ = 'xors'\nfrom setuptools import setup, find_packages\n# from distutils.core import setup\nimport sys\n\nreload(sys).setdefaultencoding(\"UTF-8\")\n\nsetup(\n name='lugati',\n version='0.1.5',\n author='Sergey Grigorev',\n author_email='dev@lugati.ru',\n packages=find_packages(),\n url='http://lugati.ru',\n download_url = 'https://github.com/xorsnn/lugati/zipball/master',\n license = 'MIT license',\n description = u'Основные процедуры и функции lugati_cms.'.encode('utf8'),\n classifiers=(\n 'Development Status :: 4 - Beta',\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Natural Language :: Russian',\n )\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130882862","text":"from gluon.storage import Storage\nsettings = Storage()\n\nsettings.migrate = True\nsettings.title = 'Swing Donor'\nsettings.subtitle = 'donate where it counts'\nsettings.author = 'Austin Gage'\nsettings.author_email = 'austingage72@gmail.com'\nsettings.keywords = ''\nsettings.description = ''\nsettings.layout_theme = 'Default'\nsettings.database_uri = 'sqlite://storage.sqlite'\nsettings.security_key = 'f1ccad9d-54c6-4fbf-b6fa-90862e0d0477'\nsettings.email_server = 'logging'\nsettings.email_sender = 'you@example.com'\nsettings.email_login = ''\nsettings.login_method = 'local'\nsettings.login_config = ''\nsettings.plugins = []\n","sub_path":"models/0.py","file_name":"0.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"184805292","text":"def is_palindrome(n):\n s = str(n)\n result = True\n while len(s) > 1:\n if s[0] != s[-1]:\n result = False\n break\n else:\n s = s[1:-1]\n return result\n\ndef advance(n):\n return n + int(str(n)[::-1])\n\ndef lychrel_seq(n, maxiters = 50, verbose = False):\n current = n\n for i in range(maxiters):\n if verbose:\n print(current)\n current = advance(current)\n if is_palindrome(current):\n break\n elif i == maxiters - 1:\n i = None\n\n return i\n\n\nif __name__ == \"__main__\":\n lychrels = 0\n\n for i in range(1,10001):\n a = lychrel_seq(i)\n if a == None:\n lychrels += 1\n\n print(lychrels)\n","sub_path":"e55.py","file_name":"e55.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"550802800","text":"\"\"\"Forms for the reports app.\"\"\"\n\nimport datetime as dt\n\nfrom django import forms\nfrom django.utils.timezone import make_aware\n\nfrom inventory.models import Supplier\n\n\nclass ReorderReportForm(forms.Form):\n \"\"\"Form for creating reorder reports.\"\"\"\n\n supplier = forms.ModelChoiceField(queryset=Supplier.objects.filter(active=True))\n date_from = forms.DateField(widget=forms.DateInput(attrs={\"class\": \"datepicker\"}))\n date_to = forms.DateField(widget=forms.DateInput(attrs={\"class\": \"datepicker\"}))\n\n def clean(self):\n \"\"\"Make date range timezone aware.\"\"\"\n cleaned_data = super().clean()\n cleaned_data[\"date_from\"] = self.convert_date(cleaned_data[\"date_from\"])\n cleaned_data[\"date_to\"] = self.convert_date(cleaned_data[\"date_to\"])\n return cleaned_data\n\n def convert_date(self, date):\n \"\"\"Return a datetime.date as a timezone aware datetime.datetime.\"\"\"\n return make_aware(dt.datetime.combine(date, dt.datetime.min.time()))\n","sub_path":"reports/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408879527","text":"import json\n\nclass Videos:\n def __init__(self):\n try:\n with open(\"videos1.json\", \"r\") as f:\n self.videos = json.load(f)\n except FileNotFoundError:\n self.videos = []\n\n def all(self):\n return self.videos\n\n def get(self, id):\n video = [video for video in self.all() if video['id'] == id]\n if video:\n return video[0]\n return []\n\n def create(self, data):\n self.videos.append(data)\n self.save_all()\n\n def save_all(self):\n with open(\"videos1.json\", \"w\") as f:\n json.dump(self.videos, f)\n\n def update(self, id, data):\n video = self.get(id)\n if video:\n index = self.videos.index(video)\n self.videos[index] = data\n self.save_all()\n return True\n return False\n\n\n def delete(self, id):\n video = self.get(id)\n if video:\n self.videos.remove(video)\n self.save_all()\n return True\n return False\n\n\n\nvideos = Videos()\n\n\n\n","sub_path":"video_library_rest/data_rest.py","file_name":"data_rest.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"548756623","text":"import csv\nimport os.path\n\n\ndef csv_profile_writer_to_local(profiles, filename, fieldnames):\n file_exists = os.path.isfile(filename)\n with open(filename, 'a') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n if not file_exists:\n writer.writeheader() # file doesn't exist yet, write a header\n for p in profiles:\n writer.writerow(p.dictstyle())\n","sub_path":"university_counselor/b17706spark_usedcars/i2SGScrapy/quora/profile_writer.py","file_name":"profile_writer.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559993384","text":"from os import sys, path\nfrom random import randint\nfrom finite_automata import FiniteAutomata\nimport json\n\n# Class acts as a parser.\n# parametrs: fileName - the source of the toy language source code\nclass Scanner:\n # Consturctor for the Scanner, takes as a parameter the fileName consisting of the\n # source code that we want our lexer to tokenize\n def __init__(self, fileName):\n # filename refers to the toy language source code\n self.fileName = fileName\n # file to store the program internal form\n self.outputFileName = path.splitext(path.basename(fileName))[0] + \"_pif.txt\"\n # clear file if already exist\n open(self.outputFileName, 'w').close()\n # file to store the identifiers table\n self.outputIdentifiersTable = path.splitext(path.basename(fileName))[0] + \"_id_table.txt\"\n # file to store the constants table\n self.outputConstantsTable = path.splitext(path.basename(fileName))[0] + \"_const_table.txt\"\n # hashtable for all the program symbols (if, for, while, else, int, float, etc)\n self.symbolsTable = {}\n # hashtable for storing the identifiers, as a pair identifier -> integer id\n self.identifiersTable = {}\n # hashtable for storing the identifiers, as a pair constant -> integer id\n self.constantsTable = {}\n # load all the toy language symbols\n self.populateSymbolsTable()\n # Finite automatas\n with open('symbols.json') as f:\n self.symbols_fa = FiniteAutomata(json.load(f))\n with open('identifier.json') as f:\n self.identifers_fa = FiniteAutomata(json.load(f))\n with open('constant.json') as f:\n self.constants_fa = FiniteAutomata(json.load(f))\n\n # method loads symbol table in memory from the disc\n def populateSymbolsTable(self):\n try:\n # open the file\n f = open(\"symbols.dat\")\n # iterate through its lines\n for line in f.readlines():\n # get the symbol and the symbol id\n (symbol, sid) = line.split()\n # add to the symbols table\n self.symbolsTable[symbol] = sid\n except IOError:\n # In case there is no such file, fail fast!\n print(\"> Error: Symbols file not found!\")\n sys.exit()\n\n # method returns a random integer that is not in the values array\n def randomNotIn(self, values):\n # returns a random vaue between 1 and 100000\n r = randint(1, 100000)\n # while that value already exists in the array values\n while r in values:\n # generate a new one\n r = randint(1, 100000)\n # return the number generated\n return r\n\n # method append buff to the file outputFileName\n def appendToOutput(self, buff):\n # open file\n with open(self.outputFileName, \"a\") as f:\n # write the string buff as a new line\n f.write(buff + \" \")\n\n # method write the identifier and constant tables\n def writeTables(self):\n # open file for identifiers table\n with open(self.outputIdentifiersTable, \"w\") as f:\n # iterate through the identifiers table\n for (key, val) in self.identifiersTable.iteritems():\n # write the pair on a new line\n f.write(\"%s %s\\n\" % (key, val))\n # open file for constant table\n with open(self.outputConstantsTable, \"w\") as f:\n # iterate through the constants table\n for (key, val) in self.constantsTable.iteritems():\n # write the pair on a new line\n f.write(\"%s %s\\n\" % (key, val))\n\n # method prints the symbol to the program internal form file output\n def addSymbol(self, _symbol):\n # if the symbol is in the symbol table\n if _symbol in self.symbolsTable:\n # print it\n self.appendToOutput(str(self.symbolsTable[_symbol]))\n return True\n else:\n # return false because _symbol is not a valid symbol, and then throw an error\n return False\n\n # method prints identifier and it's id to the output file\n def addIdentifier(self, _id):\n # assign a new, unused integer id for the current identifier\n if _id not in self.identifiersTable:\n self.identifiersTable[_id] = self.randomNotIn(self.identifiersTable.values())\n # print to program internal form output file\n self.appendToOutput(\n self.symbolsTable[\"identifier\"])\n return True\n\n # method adds a constant to the table and prints it to the output file\n def addConstant(self, _val):\n # assign a new, unsued integer id for the current identifier\n if _val not in self.constantsTable:\n self.constantsTable[_val] = self.randomNotIn(self.constantsTable.values())\n # print to the program internl form output file\n self.appendToOutput(\n self.symbolsTable[\"constant\"])\n return True\n\n # method tokenize the source file\n def tokenize(self):\n try:\n # read the file\n f = open(self.fileName, \"r\")\n # iterate on all the read lines\n for (i, line) in enumerate(f.readlines()):\n program = line\n while program != \"\":\n program = program.strip()\n # get the longest accepted prefix among all of the 3 finite automatas\n _sym = self.symbols_fa.longest_accepted_prefix(program)\n _id = self.identifers_fa.longest_accepted_prefix(program)\n _const = self.constants_fa.longest_accepted_prefix(program)\n # some of the symbols are also accepted identifiers (eg: while, int, etc)\n # in case they are eqla, symbols have higher priority\n if _sym == _id:\n _id = None\n if _id is not None and _id != \"\":\n if len(_id) > 250:\n print(\"> Error: Identifier has too many characters, line %d.\" % (i + 1))\n sys.exit(1)\n # add the token to the interal hashmaps\n self.addIdentifier(_id)\n program = program[len(_id):]\n elif _sym is not None and _sym != \"\":\n self.addSymbol(_sym)\n program = program[len(_sym):]\n elif _const is not None and _const != \"\":\n self.addConstant(_const)\n program = program[len(_const):]\n else:\n print(\"> Error: Syntax error. Unexpected token at line %d:%s\" % (i + 1, program))\n sys.exit(1)\n self.writeTables()\n except IOError:\n print(\"> Error: Source file not found!\")\n sys.exit(1)\n\n# method scans and tokenize the filename source code\ndef scan(filename):\n # create the scaner\n s = Scanner(filename)\n # call the tokenize method\n s.tokenize()\n\n# if name is main\nif __name__ == '__main__':\n # get the first argument of the args\n # log it\n if len(sys.argv) > 1:\n print(\"> Scanning \" + str(sys.argv[1]) + \"...\")\n # scan that filename\n scan(sys.argv[1])\n else:\n scan(\"main.cpp\")\n print(\"> Done\")\n\n","sub_path":"ubb/lftc/lab5/gcc.py","file_name":"gcc.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481280729","text":"import decimal\nimport uuid\nfrom datetime import datetime\n\nfrom flask import request\nfrom flask_restplus import Resource, reqparse\n\nfrom ..models.mine_expected_document import MineExpectedDocument\n\nfrom app.extensions import api\nfrom ....utils.access_decorators import requires_role_mine_view, requires_role_mine_create, requires_any_of, MINE_VIEW, MINE_CREATE, MINESPACE_PROPONENT\nfrom ....utils.resources_mixins import UserMixin, ErrorMixin\n\n\nclass ExpectedDocumentResource(Resource, UserMixin, ErrorMixin):\n parser = reqparse.RequestParser()\n parser.add_argument(\n 'document', type=dict, required=True, help='document to change', location=\"json\")\n\n @api.doc(\n params={\n 'exp_doc_guid':\n 'Required: Mine number or guid. returns list of expected documents for the mine'\n })\n @requires_role_mine_view\n def get(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n mine_exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if mine_exp_doc is None:\n return self.create_error_payload(404, 'Expected document not found'), 404\n return {'expected_document': mine_exp_doc.json()}\n\n @api.doc(params={'exp_doc_guid': 'Required: Mine number or guid. Updates expected document'})\n @requires_any_of([MINE_CREATE, MINESPACE_PROPONENT])\n def put(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n\n exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if exp_doc is None:\n return self.create_error_payload(\n 404, f'expected_document with guid \"{exp_doc_guid}\" not found'), 404\n\n data = self.parser.parse_args()\n updated_doc = data['document']\n if str(exp_doc.exp_document_guid) != updated_doc['exp_document_guid']:\n return self.create_error_payload(500, 'exp_document does not match guid provided'), 500\n\n exp_doc.exp_document_name = updated_doc.get('exp_document_name')\n exp_doc.exp_document_description = updated_doc.get('exp_document_description')\n if updated_doc.get('due_date') is not None:\n exp_doc.due_date = updated_doc.get('due_date')\n\n exp_doc.received_date = updated_doc.get('received_date')\n exp_doc.exp_document_description = updated_doc.get('exp_document_description')\n\n updated_doc_status = updated_doc.get('exp_document_status')\n if updated_doc_status is not None:\n updated_doc_status_code = updated_doc_status.get('exp_document_status_code')\n if updated_doc_status_code is not None:\n exp_doc.exp_document_status_code = updated_doc_status_code\n\n exp_doc.save()\n return {'expected_document': exp_doc.json()}\n\n @api.doc(params={'exp_doc_guid': 'Required: Mine number or guid. Deletes expected document.'})\n @requires_role_mine_create\n def delete(self, exp_doc_guid=None):\n if exp_doc_guid is None:\n return self.create_error_payload(404, 'Must provide a expected document guid.'), 404\n exp_doc = MineExpectedDocument.find_by_exp_document_guid(exp_doc_guid)\n if exp_doc is not None:\n exp_doc.active_ind = False\n exp_doc.save()\n return {'status': 200, 'message': 'expected_document deleted successfully.'}\n return self.create_error_payload(\n 404, f'expected_document with guid \"{exp_doc_guid}\" not found'), 404\n","sub_path":"python-backend/app/api/documents/expected/resources/documents.py","file_name":"documents.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"577108931","text":"import logging \n\nlog_config = {\n \"MethodNotSupported\" : {\"level\": 40,\n \"message\": \"Method not supported for more than one choice\"},\n \"InvalidChoice\": {\"level\": 40,\n \"message\": \"Choices doesn't have your current state\"},\n \"NaN\": {\"level\": 40,\n \"message\": \"You need to choose from available numbers 🔢 on board to mark your location\"},\n \"OutOfRange\": {\"level\": 40,\n \"message\": \"You can run but can't hide 👟, choose a number that is available\"},\n \"Won\": {\"level\": 20,\n \"message\": \"You have won this match 🏆, rematch?\"},\n \"Tie\": {\"level\": 20,\n \"message\": \"You've both outsmarted each other, 🤼 try again?\"},\n \"End\": {\"level\": 20,\n \"message\": \"Hope you had as much fun 👻, as I had while writing this.\"},\n \"Start\": {\"level\": 20,\n \"message\": \"Match Started! 🏁\"}\n}\n\n\nlogging.basicConfig(filename=\"logfile.log\", \n format='%(asctime)s %(message)s', \n filemode='w') \nlogger = logging.getLogger() \nlogger.setLevel(logging.DEBUG) \n\ndef log(case):\n print(log_config[case]['message'])\n logger.log(log_config[case]['level'], log_config[case]['message'])\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410702664","text":"import socket\r\nHost = '127.0.0.1'\r\nPort = 65432\r\n\r\nwith socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s: #creating socket\r\n s.bind((Host,Port)) #binding Socket\r\n s.listen() #listening for connection\r\n conn, addr = s.accept() #accepting connection\r\n with conn:\r\n print(\"conected by\",addr)\r\n while True:\r\n data = conn.recv(1024) #reciving data\r\n if not data:\r\n break #if no data is being recived then clossing connection\r\n conn.sendall(data) #sending back recived data\r\n\r\n","sub_path":"Assignment-1-Socket-Programming/Dharmick/echo-server.py","file_name":"echo-server.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60868096","text":"from utils import line_to_dictionary\nimport random\n\nclass RandomVariable:\n def __init__(self,args):\n params = line_to_dictionary(args)\n print(params)\n min = params.get(\"min\", None)\n if min != None:\n self.min = int(min)\n else:\n self.min = 0\n max = params.get(\"max\", None)\n if max != None:\n self.max = int(max)\n else:\n self.max = 1000\n\n def eval(self):\n return random.randint(self.min, self.max)\n","sub_path":"src/ApiTester/variables/random_variable.py","file_name":"random_variable.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"562548125","text":"from i3Deep import utils\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nimport os\r\nfrom skimage import measure\r\nimport copy\r\nimport argparse\r\nfrom shutil import copyfile\r\nimport time\r\nimport subprocess\r\nimport signal\r\nfrom evaluate import evaluate\r\nimport pickle\r\nimport random\r\nimport multiprocessing as mp\r\nfrom functools import partial\r\nimport pandas as pd\r\nfrom pathlib import Path\r\nimport GeodisTK\r\nimport shutil\r\nimport json\r\nimport i3Deep.mask_recommendation.my_method as my_method\r\nimport i3Deep.mask_recommendation.deep_i_geos as deep_i_geos\r\nimport i3Deep.mask_recommendation.graph_cut as graph_cut\r\nimport i3Deep.mask_recommendation.random_walker as random_walker\r\nimport i3Deep.mask_recommendation.watershed as watershed\r\nfrom scipy.ndimage.measurements import center_of_mass\r\nimport pandas as pd\r\n\r\n\r\n# def recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size, deepigeos=0):\r\n# image_filenames = utils.load_filenames(image_path)\r\n# prediction_filenames = utils.load_filenames(prediction_path)\r\n# uncertainty_filenames = utils.load_filenames(uncertainty_path)\r\n# gt_filenames = utils.load_filenames(gt_path)\r\n# total_recommended_slices = 0\r\n# total_gt_slices = 0\r\n#\r\n# for i in tqdm(range(len(uncertainty_filenames))):\r\n# uncertainty, affine, spacing, header = utils.load_nifty(uncertainty_filenames[i])\r\n# prediction, _, _, _ = utils.load_nifty(prediction_filenames[i])\r\n# gt, _, _, _ = utils.load_nifty(gt_filenames[i])\r\n# if deepigeos != 0:\r\n# image, _, _, _ = utils.load_nifty(image_filenames[i])\r\n# adapted_slice_gap = adapt_slice_gap(uncertainty, slice_gap, default_size)\r\n# # indices_dim_0: Sagittal\r\n# # indices_dim_1: Coronal\r\n# # indices_dim_2: Axial\r\n# indices_dim_0, indices_dim_1, indices_dim_2 = find_best_slices_func(prediction, uncertainty, num_slices, adapted_slice_gap)\r\n# recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n# gt_slices = comp_infected_slices(gt)\r\n# total_recommended_slices += recommended_slices\r\n# total_gt_slices += gt_slices\r\n# print(\"name: {} recommended slices: {}, gt slices: {}, ratio: {}\".format(os.path.basename(uncertainty_filenames[i]), recommended_slices, gt_slices, recommended_slices / gt_slices))\r\n# # print(\"indices_dim_0: {}, indices_dim_1: {}, indices_dim_2: {}\".format(indices_dim_0, indices_dim_1, indices_dim_2))\r\n# filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n# if deepigeos != 0:\r\n# if deepigeos == 1:\r\n# geodisc_lambda = 0.99\r\n# else:\r\n# geodisc_lambda = 0.0\r\n# geodisc_map = filtered_mask.astype(np.uint8)\r\n# geodisc_map[geodisc_map < 0] = 0\r\n# filtered_mask = GeodisTK.geodesic3d_raster_scan(image.astype(np.float32).squeeze(0), geodisc_map, spacing.astype(np.float32), geodisc_lambda, 1)\r\n# utils.save_nifty(save_path + os.path.basename(uncertainty_filenames[i])[:-7] + \"_0001.nii.gz\", filtered_mask, affine, spacing, header, is_mask=True)\r\n# total_ratio = total_recommended_slices / total_gt_slices\r\n# print(\"total recommended slices: {}, total gt slices: {}, total ratio: {}\".format(total_recommended_slices, total_gt_slices, total_ratio))\r\n# return total_ratio\r\n\r\n\r\ndef recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, params):\r\n prediction_filenames = utils.load_filenames(prediction_path)\r\n uncertainty_filenames = utils.load_filenames(uncertainty_path)\r\n gt_filenames = utils.load_filenames(gt_path)\r\n\r\n # start_time = time.time()\r\n print(\"Starting slice recommendation...\")\r\n results = pool.map(partial(recommend_slices_single_case,\r\n prediction_filenames=prediction_filenames, uncertainty_filenames=uncertainty_filenames, gt_filenames=gt_filenames,\r\n save_path=save_path, find_best_slices_func=find_best_slices_func, params=params),\r\n range(len(uncertainty_filenames)))\r\n print(\"Finished slice recommendation.\")\r\n # print(\"Recommend slices elapsed time: \", time.time() - start_time)\r\n # results = np.asarray(results)\r\n # total_recommended_slices = results[:, 0]\r\n # total_gt_slices = results[:, 1]\r\n # total_recommended_slices = np.sum(total_recommended_slices)\r\n # total_gt_slices = np.sum(total_gt_slices)\r\n # total_ratio = total_recommended_slices / total_gt_slices\r\n # print(\"total recommended slices: {}, total gt slices: {}, total ratio: {}\".format(total_recommended_slices, total_gt_slices, total_ratio))\r\n return results\r\n\r\n\r\ndef recommend_slices_single_case(i, prediction_filenames, uncertainty_filenames, gt_filenames, save_path, find_best_slices_func, params, debug=False):\r\n uncertainty, affine, spacing, header = utils.load_nifty(uncertainty_filenames[i])\r\n prediction, _, _, _ = utils.load_nifty(prediction_filenames[i])\r\n gt, _, _, _ = utils.load_nifty(gt_filenames[i])\r\n params[\"slice_gap\"] = adapt_slice_gap(uncertainty, params[\"slice_gap\"], params[\"default_size\"])\r\n # indices_dim_0: Sagittal\r\n # indices_dim_1: Coronal\r\n # indices_dim_2: Axial\r\n filtered_mask, recommended_slices, recommended_patch_area = find_best_slices_func(prediction, gt, uncertainty, params, os.path.basename(gt_filenames[i]))\r\n slices = gt.shape[2]\r\n gt_slices = comp_infected_slices(gt)\r\n size = np.prod(gt.shape)\r\n infection_size = gt_slices * np.prod(gt.shape[:2])\r\n prediction_slices = comp_infected_slices(prediction)\r\n if debug:\r\n print(\"name: {}, slices: {}, gt inf slices: {}, pred inf slices: {}, rec slices: {}, rec slice ratio: {}, rec slice inf ratio: {}, patch ratio: {}, patch inf ratio: {}\".format(\r\n os.path.basename(uncertainty_filenames[i]),\r\n slices,\r\n gt_slices,\r\n prediction_slices,\r\n recommended_slices,\r\n recommended_slices / slices,\r\n recommended_slices / gt_slices,\r\n recommended_patch_area / size,\r\n recommended_patch_area / infection_size))\r\n utils.save_nifty(save_path + os.path.basename(uncertainty_filenames[i])[:-7] + \"_\" + str(modality).zfill(4) + \".nii.gz\", filtered_mask, affine, spacing, header, is_mask=True)\r\n results = {}\r\n results[\"total_slices\"] = slices\r\n results[\"gt_infected_slices\"] = gt_slices\r\n results[\"pred_infected_slices\"] = prediction_slices\r\n results[\"recommended_slices\"] = recommended_slices\r\n results[\"size\"] = size\r\n results[\"infection_size\"] = infection_size\r\n results[\"recommended_patch_area\"] = recommended_patch_area\r\n return results\r\n\r\n\r\ndef adapt_slice_gap(mask, slice_gap, default_size):\r\n return int((mask.shape[0] / default_size) * slice_gap)\r\n\r\n\r\ndef find_best_slices_baseline_V1(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension without a min slice gap.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n indices_dim_0 = random.sample(range(uncertainty.shape[0]), num_slices)\r\n indices_dim_1 = random.sample(range(uncertainty.shape[1]), num_slices)\r\n indices_dim_2 = random.sample(range(uncertainty.shape[2]), num_slices)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_baseline_V2(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension within equidistant distances.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n def get_indices(axis):\r\n slice_sectors = np.linspace(0, uncertainty.shape[axis], num_slices, endpoint=True).astype(int)\r\n indices = [random.randint(slice_sectors[i-1], slice_sectors[i]) for i in range(1, len(slice_sectors)-1)]\r\n return indices\r\n\r\n indices_dim_0 = get_indices(0)\r\n indices_dim_1 = get_indices(1)\r\n indices_dim_2 = get_indices(2)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_baseline_V3(prediction, gt, uncertainty, params):\r\n \"Find random slices in every dimension within equidistant distances.\"\r\n _, recommended_slices, _ = find_best_slices_V7(prediction, gt, uncertainty, params)\r\n num_slices = int(recommended_slices / 3)\r\n\r\n def get_start_end_index(axis):\r\n _axis = [0, 1, 2]\r\n _axis.remove(axis)\r\n _axis = tuple(_axis)\r\n prediction_dim = np.sum(prediction, axis=_axis)\r\n start = (prediction_dim!=0).argmax()\r\n prediction_dim = np.flip(prediction_dim)\r\n end = (prediction_dim!=0).argmax()\r\n end = len(prediction_dim) - end\r\n return start, end\r\n\r\n def get_indices(axis):\r\n start, end = get_start_end_index(axis)\r\n slice_sectors = np.linspace(start, end, num_slices, endpoint=True).astype(int)\r\n # print(\"Start: {}, end: {}, slice_sectors: {}\".format(start, end, slice_sectors))\r\n indices = [random.randint(slice_sectors[i-1], slice_sectors[i]) for i in range(1, len(slice_sectors)-1)]\r\n return indices\r\n\r\n indices_dim_0 = get_indices(0)\r\n indices_dim_1 = get_indices(1)\r\n indices_dim_2 = get_indices(2)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V1(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension without a min slice gap.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)[:params[\"num_slices\"]]\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)[:params[\"num_slices\"]]\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)[:params[\"num_slices\"]]\r\n # dim_0 = uncertainty_dim_0[indices_dim_0]*-1\r\n # dim_1 = uncertainty_dim_1[indices_dim_1]*-1\r\n # dim_2 = uncertainty_dim_2[indices_dim_2]*-1\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V2(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices, slice_gap)\r\n # dim_0 = uncertainty_dim_0[indices_dim_0]*-1\r\n # dim_1 = uncertainty_dim_1[indices_dim_1]*-1\r\n # dim_2 = uncertainty_dim_2[indices_dim_2]*-1\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V3(prediction, gt, uncertainty, params):\r\n # Threshold uncertainty values\r\n # Find and partition blobs\r\n # For each blob:\r\n # Find center of mass:\r\n # Mean of X\r\n # Mean of Y\r\n # Mean of Z\r\n # Place three planes in center with normal pointing X, Y and Z\r\n # Done\r\n # V4 include uncertainties with V2\r\n indices_dim_0, indices_dim_1, indices_dim_2 = [], [], []\r\n prediction = utils.normalize(prediction)\r\n prediction[prediction >= 0.5] = 1\r\n prediction[prediction < 0.5] = 0\r\n labeled = measure.label(prediction, background=False, connectivity=2)\r\n unique, counts = np.unique(labeled, return_counts=True)\r\n unique = unique[1:] # Remove zero / background\r\n counts = counts[1:] # Remove zero / background\r\n sorted_indices = np.argsort(counts)[::-1]\r\n unique = unique[sorted_indices][:5]\r\n\r\n # blob_masks = []\r\n # for label in unique:\r\n # blob_mask = copy.deepcopy(labeled)\r\n # blob_mask[blob_mask != label] = 0\r\n # blob_mask[blob_mask == label] = 1\r\n # # sub_blob_masks = partition_blob(blob_mask)\r\n # # blob_masks.extend(sub_blob_masks)\r\n # blob_masks.append(blob_mask)\r\n\r\n for label in unique:\r\n blob_mask = copy.deepcopy(labeled)\r\n blob_mask[blob_mask != label] = 0\r\n blob_mask[blob_mask == label] = 1\r\n def find_center(dim):\r\n dims = [0, 1, 2]\r\n dims.remove(dim)\r\n blob_mask_dim = np.sum(blob_mask, axis=tuple(dims))\r\n nonzero_indices = np.nonzero(blob_mask_dim)\r\n min_index = np.min(nonzero_indices)\r\n max_index = np.max(nonzero_indices)\r\n center = int(min_index + ((max_index - min_index) / 2))\r\n return center\r\n indices_dim_0.append(find_center(0))\r\n indices_dim_1.append(find_center(1))\r\n indices_dim_2.append(find_center(2))\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V4(prediction, gt, uncertainty, params):\r\n indices_dim_0_V2, indices_dim_1_V2, indices_dim_2_V2 = find_best_slices_V2(prediction, uncertainty, num_slices, slice_gap)\r\n indices_dim_0_V3, indices_dim_1_V3, indices_dim_2_V3 = find_best_slices_V3(prediction, uncertainty, num_slices, slice_gap)\r\n indices_dim_0 = np.concatenate((indices_dim_0_V2, indices_dim_0_V3), axis=0)\r\n indices_dim_1 = np.concatenate((indices_dim_1_V2, indices_dim_1_V3), axis=0)\r\n indices_dim_2 = np.concatenate((indices_dim_2_V2, indices_dim_2_V3), axis=0)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V5(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap. Take merge indices from every dim and take only the best ignoring the dims.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices*100, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices*100, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices*100, slice_gap)\r\n sum_dim_0 = uncertainty_dim_0[indices_dim_0]\r\n sum_dim_1 = uncertainty_dim_0[indices_dim_1]\r\n sum_dim_2 = uncertainty_dim_0[indices_dim_2]\r\n dim_0_indices = np.ones(len(sum_dim_0)) * 0\r\n dim_1_indices = np.ones(len(sum_dim_1)) * 1\r\n dim_2_indices = np.ones(len(sum_dim_2)) * 2\r\n sum = np.concatenate([sum_dim_0, sum_dim_1, sum_dim_2], axis=0)\r\n dim_indices = np.concatenate([dim_0_indices, dim_1_indices, dim_2_indices], axis=0)\r\n indices_dim = np.concatenate([indices_dim_0, indices_dim_1, indices_dim_2], axis=0)\r\n indices = np.argsort(sum)[:num_slices]\r\n dim_indices = dim_indices[indices]\r\n indices_dim = indices_dim[indices]\r\n indices_dim_0, indices_dim_1, indices_dim_2 = [], [], []\r\n for i in range(len(indices)):\r\n if dim_indices[i] == 0:\r\n indices_dim_0.append(indices_dim[i])\r\n elif dim_indices[i] == 1:\r\n indices_dim_1.append(indices_dim[i])\r\n else:\r\n indices_dim_2.append(indices_dim[i])\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V6(prediction, gt, uncertainty, params):\r\n \"Find best slices based on maximum 2D plane uncertainty in every dimension with a min slice gap. Weight uncertainty based on slice prediction sum.\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n prediction_dim_0 = np.sum(prediction, axis=(1, 2))\r\n prediction_dim_1 = np.sum(prediction, axis=(0, 2))\r\n prediction_dim_2 = np.sum(prediction, axis=(0, 1))\r\n prediction_dim_0 = utils.normalize(prediction_dim_0)\r\n prediction_dim_1 = utils.normalize(prediction_dim_1)\r\n prediction_dim_2 = utils.normalize(prediction_dim_2)\r\n uncertainty_dim_0 = uncertainty_dim_0 * prediction_dim_0\r\n uncertainty_dim_1 = uncertainty_dim_1 * prediction_dim_1\r\n uncertainty_dim_2 = uncertainty_dim_2 * prediction_dim_2\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, num_slices, slice_gap)\r\n indices_dim_1 = filter_indices(indices_dim_1, num_slices, slice_gap)\r\n indices_dim_2 = filter_indices(indices_dim_2, num_slices, slice_gap)\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V7(prediction, gt, uncertainty, params, name):\r\n \"Like V2, but filters out all slices with less than 40% of summed uncertainty than that of the max slice\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_1 = filter_indices(indices_dim_1, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_2 = filter_indices(indices_dim_2, params[\"num_slices\"], params[\"slice_gap\"])\r\n uncertainty_dim_0 *= -1\r\n uncertainty_dim_1 *= -1\r\n uncertainty_dim_2 *= -1\r\n\r\n def filter_by_required_uncertainty(uncertainty_dim, indices_dim):\r\n min_required_uncertainty = uncertainty_dim[indices_dim[0]] * params[\"min_uncertainty\"]\r\n indices_dim = [index_dim for index_dim in indices_dim if uncertainty_dim[index_dim] >= min_required_uncertainty]\r\n return indices_dim\r\n\r\n indices_dim_0 = filter_by_required_uncertainty(uncertainty_dim_0, indices_dim_0)\r\n indices_dim_1 = filter_by_required_uncertainty(uncertainty_dim_1, indices_dim_1)\r\n indices_dim_2 = filter_by_required_uncertainty(uncertainty_dim_2, indices_dim_2)\r\n\r\n num_infected_slices = comp_infected_slices(prediction)\r\n num_infected_slices = int((num_infected_slices * params[\"max_slices_based_on_infected_slices\"]) / 3)\r\n if num_infected_slices == 0:\r\n num_infected_slices = 1\r\n indices_dim_0 = indices_dim_0[:num_infected_slices]\r\n indices_dim_1 = indices_dim_1[:num_infected_slices]\r\n indices_dim_2 = indices_dim_2[:num_infected_slices]\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n recommended_patch_area = np.prod(filtered_mask[:, :, 0].shape)\r\n\r\n # indices_dim_0: Sagittal\r\n # indices_dim_1: Coronal\r\n # indices_dim_2: Axial\r\n chosen_slices = {}\r\n chosen_slices[\"Subject\"] = name\r\n chosen_slices[\"Sagittal\"] = [int(index) for index in indices_dim_0]\r\n chosen_slices[\"Coronal\"] = [int(index) for index in indices_dim_1]\r\n chosen_slices[\"Axial\"] = [int(index) for index in indices_dim_2]\r\n with open(choosen_slices_export_path + name[:-7] + '.json', 'w', encoding='utf-8') as f:\r\n json.dump(chosen_slices, f, ensure_ascii=False, indent=4)\r\n\r\n return filtered_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V8(prediction, gt, uncertainty, params, min_uncertainty=0.15, max_slices_based_on_infected_slices=0.20, roi_uncertainty=0.95):\r\n \"Like V2, but filters out all slices with less than 40% of summed uncertainty than that of the max slice, and computes ROIs that capture 95% of uncertainty\"\r\n uncertainty_dim_0 = np.sum(-1*uncertainty, axis=(1, 2))\r\n uncertainty_dim_1 = np.sum(-1*uncertainty, axis=(0, 2))\r\n uncertainty_dim_2 = np.sum(-1*uncertainty, axis=(0, 1))\r\n indices_dim_0 = np.argsort(uncertainty_dim_0)\r\n indices_dim_1 = np.argsort(uncertainty_dim_1)\r\n indices_dim_2 = np.argsort(uncertainty_dim_2)\r\n indices_dim_0 = filter_indices(indices_dim_0, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_1 = filter_indices(indices_dim_1, params[\"num_slices\"], params[\"slice_gap\"])\r\n indices_dim_2 = filter_indices(indices_dim_2, params[\"num_slices\"], params[\"slice_gap\"])\r\n uncertainty_dim_0 *= -1\r\n uncertainty_dim_1 *= -1\r\n uncertainty_dim_2 *= -1\r\n\r\n def filter_by_required_uncertainty(uncertainty_dim, indices_dim):\r\n min_required_uncertainty = uncertainty_dim[indices_dim[0]] * min_uncertainty\r\n indices_dim = [index_dim for index_dim in indices_dim if uncertainty_dim[index_dim] >= min_required_uncertainty]\r\n return indices_dim\r\n\r\n indices_dim_0 = filter_by_required_uncertainty(uncertainty_dim_0, indices_dim_0)\r\n indices_dim_1 = filter_by_required_uncertainty(uncertainty_dim_1, indices_dim_1)\r\n indices_dim_2 = filter_by_required_uncertainty(uncertainty_dim_2, indices_dim_2)\r\n\r\n num_infected_slices = comp_infected_slices(prediction)\r\n num_infected_slices = int((num_infected_slices * max_slices_based_on_infected_slices) / 3)\r\n # num_infected_slices = int(num_infected_slices * max_slices_based_on_infected_slices)\r\n if num_infected_slices == 0:\r\n num_infected_slices = 1\r\n indices_dim_0 = indices_dim_0[:num_infected_slices]\r\n indices_dim_1 = indices_dim_1[:num_infected_slices]\r\n indices_dim_2 = indices_dim_2[:num_infected_slices]\r\n\r\n recommended_slices = len(indices_dim_0) + len(indices_dim_1) + len(indices_dim_2)\r\n filtered_mask = filter_mask(gt, indices_dim_0, indices_dim_1, indices_dim_2)\r\n\r\n def find_patches(filtered_mask, uncertainty, indices_dim_0, indices_dim_1, indices_dim_2):\r\n # Find objects based on uncertainty\r\n # Crop objects\r\n # for each object: patch_mask[object] = filtered_mask[object]\r\n if method == \"my_method\" or method == \"DeepIGeos1\" or method == \"DeepIGeos2\":\r\n patch_mask = np.zeros_like(filtered_mask)\r\n else:\r\n patch_mask = np.ones_like(filtered_mask) * -1\r\n recommended_patch_area = 0\r\n indices_dim_all = [indices_dim_0, indices_dim_1, indices_dim_2]\r\n\r\n for axis in range(3):\r\n for index in indices_dim_all[axis]:\r\n # center = np.rint(center_of_mass(uncertainty[index, :, :])).astype(int)\r\n center = np.rint(center_of_mass(np.moveaxis(uncertainty, axis, 0)[index, :, :])).astype(int)\r\n total_mass = np.sum(np.moveaxis(uncertainty, axis, 0)[index, :, :])\r\n roi_size = 5\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]):\r\n while total_mass * roi_uncertainty > np.sum(np.moveaxis(uncertainty, axis, 0)[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]):\r\n roi_size += 1\r\n # recommended_patch_area += roi_size*roi_size*4\r\n patch_mask_tmp = np.moveaxis(patch_mask, axis, 0)\r\n filtered_mask_tmp = np.moveaxis(filtered_mask, axis, 0)\r\n filtered_mask_tmp_patch = filtered_mask_tmp[index, center[0] - roi_size:center[0] + roi_size, center[1] - roi_size:center[1] + roi_size]\r\n recommended_patch_area += filtered_mask_tmp_patch.size\r\n patch_mask_tmp[index, center[0] - roi_size:center[0] + roi_size, center[1] - roi_size:center[1] + roi_size] = filtered_mask_tmp_patch\r\n patch_mask = np.moveaxis(patch_mask_tmp, 0, axis)\r\n filtered_mask = np.moveaxis(filtered_mask_tmp, 0, axis)\r\n # patch_mask[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size] = filtered_mask[index, center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size]\r\n\r\n\r\n # for index in indices_dim_1:\r\n # center = np.rint(center_of_mass(uncertainty[:, index, :])).astype(int)\r\n # total_mass = np.sum(uncertainty[:, index, :])\r\n # roi_size = 1\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size]):\r\n # roi_size += 1\r\n # recommended_patch_area += roi_size * roi_size * 4\r\n # patch_mask[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size] = filtered_mask[center[0]-roi_size:center[0]+roi_size, index, center[1]-roi_size:center[1]+roi_size]\r\n # for index in indices_dim_2:\r\n # center = np.rint(center_of_mass(uncertainty[:, :, index])).astype(int)\r\n # total_mass = np.sum(uncertainty[:, :, index])\r\n # roi_size = 1\r\n # while total_mass * roi_uncertainty > np.sum(uncertainty[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index]):\r\n # roi_size += 1\r\n # recommended_patch_area += roi_size * roi_size * 4\r\n # patch_mask[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index] = filtered_mask[center[0]-roi_size:center[0]+roi_size, center[1]-roi_size:center[1]+roi_size, index]\r\n return patch_mask, recommended_patch_area\r\n\r\n patch_mask, recommended_patch_area = find_patches(filtered_mask, uncertainty, indices_dim_0, indices_dim_1, indices_dim_2)\r\n # recommended_patch_area = np.prod(filtered_mask[:, :, 0])\r\n return patch_mask, recommended_slices, recommended_patch_area\r\n\r\n\r\ndef find_best_slices_V9(prediction, uncertainty, slice_gap, params):\r\n \"Idee: V2, aber nur die slices nehmen die noch min 60% so viel uncertainty haben wie die erste slice + für jede slice den Bereich eingrenzen der 70% der Uncertainty umfasst\"\r\n \"Neue metriken dafür machen: selektierte anzahl pixel / gesamt anzahl pixel ; selektierte anzahl infected pixel / gesamt anzahl infected pixel ; Absolute anzahl von selektieren patches\"\r\n pass\r\n\r\n\r\ndef find_best_slices_V10(prediction, uncertainty, slice_gap, params):\r\n \"\"\"Idee für V5: V2 aber uncertainties 5 Grad drehen, resamplen V2 ausführen, das ganze 360/5=72 mal\"\"\"\r\n pass\r\n\r\n\r\n\r\n# def partition_blob(blob_mask):\r\n# def find_side_length(blob_mask, dim):\r\n# dims = [0, 1, 2]\r\n# dims.remove(dim)\r\n# blob_mask_dim = np.sum(blob_mask, axis=tuple(dims))\r\n# nonzero_indices = np.nonzero(blob_mask_dim)\r\n# min_index = np.min(nonzero_indices)\r\n# max_index = np.max(nonzero_indices)\r\n# side_length = max_index - min_index\r\n# return side_length\r\n# return [blob_mask]\r\n\r\n\r\ndef filter_indices(indices, num_slices, slice_gap):\r\n index = 1\r\n while index < len(indices) and index < num_slices: # TODO: index < num_slices: Wrong as not every index is accepted, so index should go over num_slices, but not more that len(acquired_slices)\r\n tmp = indices[:index]\r\n if np.min(np.abs(tmp - indices[index])) <= slice_gap: # TODO: Replace indices[index] with just index? indices[index] is a sum.\r\n indices = np.delete(indices, index)\r\n else:\r\n index += 1\r\n indices = indices[:num_slices]\r\n return indices\r\n\r\n\r\ndef filter_mask(mask, indices_dim_0, indices_dim_1, indices_dim_2):\r\n slices = np.zeros_like(mask)\r\n\r\n for index in indices_dim_0:\r\n slices[int(index), :, :] = 1\r\n\r\n for index in indices_dim_1:\r\n slices[:, int(index), :] = 1\r\n\r\n for index in indices_dim_2:\r\n slices[:, :, int(index)] = 1\r\n\r\n # filtered_mask = copy.deepcopy(mask)\r\n # filtered_mask = np.logical_and(filtered_mask, slices)\r\n if method == \"my_method\" or method == \"DeepIGeos1\" or method == \"DeepIGeos2\" or method == \"P_Net_BrainTumor\" or method == \"P_Net_Pancreas\":\r\n filtered_mask = np.zeros_like(mask)\r\n else:\r\n filtered_mask = np.ones_like(mask) * -1\r\n unique = np.unique(mask)\r\n for label in unique:\r\n filtered_mask[(slices == 1) & (mask == label)] = label\r\n\r\n return filtered_mask\r\n\r\n\r\ndef comp_infected_slices(mask):\r\n mask_slices = np.sum(mask, axis=(0, 1))\r\n mask_slices = np.count_nonzero(mask_slices)\r\n return mask_slices\r\n\r\n\r\ndef eval_all_hyperparameters(save_dir, version, method, default_params, params, devices, parallel):\r\n result_params = {}\r\n key_name = str(list(params.keys()))\r\n pbar = tqdm(total=sum([len(params[param_key]) for param_key in params.keys()]))\r\n for param_key in params.keys():\r\n result_param_values = {}\r\n for param_value in params[param_key]:\r\n current_params = copy.deepcopy(default_params)\r\n current_params[param_key] = param_value\r\n result = eval_single_hyperparameters(current_params, parallel)\r\n result_param_values[param_value] = result\r\n pbar.update(1)\r\n #print(\"Results saved.\")\r\n result_params[param_key] = result_param_values\r\n with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \"_\" + key_name + \".pkl\", 'wb') as handle:\r\n pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n result_params[param_key] = result_param_values\r\n with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \"_\" + key_name + \".pkl\", 'wb') as handle:\r\n pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n pbar.close()\r\n # print(\"Saving hyperparam evaluation...\")\r\n # with open(save_dir + \"hyperparam_eval_results_\" + version + \"_\" + method + \".pkl\", 'wb') as handle:\r\n # pickle.dump(result_params, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n print(\"Hyperparam evaluation finished.\")\r\n\r\n\r\ndef eval_test_set(save_dir, version, method, params, parallel):\r\n result = eval_single_hyperparameters(params, parallel)\r\n with open(save_dir + version + \"_\" + method + \"_\" + uncertainty_quantification + \".pkl\", 'wb') as handle:\r\n pickle.dump(result, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n return\r\n\r\n\r\ndef eval_single_hyperparameters(params, parallel, debug=False):\r\n print(\"Starting hyperparam evaluation...\")\r\n print(params)\r\n if not reuse:\r\n shutil.rmtree(recommended_masks_path, ignore_errors=True)\r\n Path(recommended_masks_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(refined_prediction_save_path, ignore_errors=True)\r\n Path(refined_prediction_save_path).mkdir(parents=True, exist_ok=True)\r\n if not parallel and not reuse:\r\n # total_ratio = recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n recommended_result = None\r\n elif not reuse:\r\n recommended_result = recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, recommended_masks_path, find_best_slices_func, params)\r\n else:\r\n recommended_result = None\r\n prediction_result = compute_predictions()\r\n # prediction_result = None\r\n if debug:\r\n print(\"inf slice ratio: {}, inf patch ratio: {}\".format(np.sum([r[\"recommended_slices\"] for r in recommended_result]) / np.sum([r[\"gt_infected_slices\"] for r in recommended_result]),\r\n np.sum([r[\"recommended_patch_area\"] for r in recommended_result]) / np.sum([r[\"infection_size\"] for r in recommended_result])))\r\n return {\"recommended_result\": recommended_result, \"prediction_result\": prediction_result}\r\n\r\n\r\n# def grid_search(save_dir, version, slice_gap_list, num_slices_list, default_size, devices, parallel):\r\n# results = []\r\n# if os.path.isfile(save_dir + \"grid_search_results_\" + version + \".pkl\"):\r\n# with open(save_dir + \"grid_search_results_\" + version + \".pkl\", 'rb') as handle:\r\n# results = pickle.load(handle)\r\n# print(results)\r\n# for slice_gap in slice_gap_list:\r\n# for num_slices in num_slices_list:\r\n# print(\"slice_gap: {}, default_size: {}, num_slices: {}\".format(slice_gap, default_size, num_slices))\r\n# if not parallel and not reuse:\r\n# # total_ratio = recommend_slices(image_path, prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n# pass\r\n# elif not reuse:\r\n# total_ratio = recommend_slices_parallel(prediction_path, uncertainty_path, gt_path, save_path, find_best_slices_func, num_slices, slice_gap, default_size)\r\n# else:\r\n# total_ratio = -1\r\n# mean_dice_score, median_dice_score = compute_predictions()\r\n# results.append({\"slice_gap\": slice_gap, \"num_slices\": num_slices, \"total_ratio\": total_ratio, \"mean_dice_score\": mean_dice_score, \"median_dice_score\": median_dice_score})\r\n# with open(save_dir + \"grid_search_results_\" + version + \".pkl\", 'wb') as handle:\r\n# pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n# print(results)\r\n\r\n\r\ndef compute_predictions():\r\n if method == \"my_method\" or method == \"P_Net_BrainTumor\" or method == \"P_Net_Pancreas\" or method == \"P_Net_Covid\":\r\n recommended_result = my_method.compute_predictions(devices, recommended_masks_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, method)\r\n # elif method == \"DeepIGeos1\":\r\n # recommended_result = deep_i_geos.compute_predictions(devices, recommended_masks_path, image_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, 0.99)\r\n # elif method == \"DeepIGeos2\":\r\n # recommended_result = deep_i_geos.compute_predictions(devices, recommended_masks_path, image_path, prediction_path, gt_path, refined_prediction_save_path, refinement_inference_tmp, model, class_labels, 0.00)\r\n elif method == \"GraphCut1\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"GraphCut2\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"GraphCut3\":\r\n recommended_result = graph_cut.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", method, modality, class_labels)\r\n elif method == \"random_walker\":\r\n recommended_result = random_walker.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", modality, class_labels)\r\n elif method == \"watershed\":\r\n recommended_result = watershed.compute_predictions(image_path, recommended_masks_path, gt_path, refined_prediction_save_path + \"/\", modality, class_labels)\r\n return recommended_result\r\n\r\n\r\ndef pkl2csv(filename):\r\n with open(filename, 'rb') as handle:\r\n results = pickle.load(handle)\r\n\r\n index = np.sort(np.unique([result[\"slice_gap\"] for result in results]))\r\n columns = np.sort(np.unique([result[\"num_slices\"] for result in results]))\r\n df = pd.DataFrame(index=index, columns=columns)\r\n # slice_gap, num_slices\r\n for result in results:\r\n df.at[result[\"slice_gap\"], result[\"num_slices\"]] = [result[\"total_ratio\"], result[\"dice_score\"]]\r\n print(df)\r\n df.to_csv(filename[:-4] + \".csv\")\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"-t\", \"--task\", help=\"Set the task name\", required=True)\r\n parser.add_argument(\"-m\", \"--model\", help=\"Set the model name\", required=True)\r\n parser.add_argument(\"-s\", \"--set\", help=\"val/test\", required=True)\r\n parser.add_argument(\"-v\", \"--version\", help=\"Set the version\", required=True)\r\n parser.add_argument(\"-uq\", \"--uncertainty_quantification\", help=\"Set the type of uncertainty quantification method to use\", required=True)\r\n parser.add_argument(\"-um\", \"--uncertainty_measure\", help=\"Set the type of uncertainty measure to use\", required=True)\r\n parser.add_argument(\"--parallel\", action=\"store_true\", default=False, help=\"Set the version\", required=False)\r\n parser.add_argument(\"-method\", help=\"Set the method\", required=True)\r\n parser.add_argument(\"-modality\", help=\"Set the modality number\", required=True)\r\n parser.add_argument(\"--reuse\", action=\"store_true\", default=False, help=\"Reuse recommended masks from last run\", required=False)\r\n parser.add_argument(\"-a\", \"--apply\", help=\"Apply for inference (infer) or hyperparameter evaluation (eval)\", required=True)\r\n args = parser.parse_args()\r\n devices = [0, 1, 2]\r\n\r\n version = str(args.version)\r\n uncertainty_quantification = str(args.uncertainty_quantification)\r\n uncertainty_measure = str(args.uncertainty_measure)\r\n\r\n if version == \"V1\":\r\n find_best_slices_func = find_best_slices_V1\r\n elif version == \"V2\":\r\n find_best_slices_func = find_best_slices_V2\r\n elif version == \"V3\":\r\n find_best_slices_func = find_best_slices_V3\r\n elif version == \"V4\":\r\n find_best_slices_func = find_best_slices_V4\r\n elif version == \"V5\":\r\n find_best_slices_func = find_best_slices_V5\r\n elif version == \"V6\":\r\n find_best_slices_func = find_best_slices_V6\r\n elif version == \"V7\":\r\n find_best_slices_func = find_best_slices_V7\r\n elif version == \"V8\":\r\n find_best_slices_func = find_best_slices_V8\r\n elif version == \"BV1\":\r\n find_best_slices_func = find_best_slices_baseline_V1\r\n elif version == \"BV2\":\r\n find_best_slices_func = find_best_slices_baseline_V2\r\n elif version == \"BV3\":\r\n find_best_slices_func = find_best_slices_baseline_V3\r\n else:\r\n raise RuntimeError(\"find_best_slices_func unknown\")\r\n\r\n if uncertainty_quantification == \"e\":\r\n uncertainty_quantification = \"ensemble\"\r\n elif uncertainty_quantification == \"t\":\r\n uncertainty_quantification = \"tta\"\r\n elif uncertainty_quantification == \"m\":\r\n uncertainty_quantification = \"mcdo\"\r\n else:\r\n raise RuntimeError(\"uncertainty_quantification unknown\")\r\n\r\n if uncertainty_measure == \"b\":\r\n uncertainty_measure = \"bhattacharyya_coefficient\"\r\n elif uncertainty_measure == \"e\":\r\n uncertainty_measure = \"predictive_entropy\"\r\n elif uncertainty_measure == \"v\":\r\n uncertainty_measure = \"predictive_variance\"\r\n else:\r\n raise RuntimeError(\"uncertainty_measure unknown\")\r\n\r\n task = args.task # \"Task072_allGuided_ggo\"\r\n model = args.model\r\n set = args.set # \"val\"\r\n method = args.method\r\n task_path = \"/gris/gris-f/homelv/kgotkows/datasets/nnUnet_datasets/nnUNet_raw_data/nnUNet_raw_data/\" + task + \"/\"\r\n base_path = task_path + \"refinement_\" + set + \"/\"\r\n image_path = base_path + \"/images/\"\r\n prediction_path = base_path + \"/basic_predictions/\"\r\n uncertainty_path = base_path + \"/uncertainties/\" + uncertainty_quantification + \"/\" + uncertainty_measure + \"/\"\r\n gt_path = base_path + \"/labels/\"\r\n recommended_masks_path = base_path + \"/recommended_masks/\" + version + \"/\" + method + \"/\"\r\n choosen_slices_export_path = base_path + \"/choosen_slices_export/\" + version + \"/\" + method + \"/\"\r\n refined_prediction_save_path = base_path + \"/refined_predictions/\" + method\r\n grid_search_save_path = base_path + \"/GridSearchResults/\"\r\n test_set_save_path = base_path + \"/eval_results/raw/\"\r\n refinement_inference_tmp = base_path + \"/refinement_inference_tmp/part\"\r\n modality = int(args.modality)\r\n reuse = args.reuse\r\n\r\n pool = mp.Pool(processes=8) # 8\r\n if not reuse:\r\n shutil.rmtree(recommended_masks_path, ignore_errors=True)\r\n Path(recommended_masks_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(refined_prediction_save_path, ignore_errors=True)\r\n Path(refined_prediction_save_path).mkdir(parents=True, exist_ok=True)\r\n shutil.rmtree(choosen_slices_export_path, ignore_errors=True)\r\n Path(choosen_slices_export_path).mkdir(parents=True, exist_ok=True)\r\n\r\n with open(task_path + \"dataset.json\") as f:\r\n class_labels = json.load(f)\r\n class_labels = np.asarray(list(class_labels[\"labels\"].keys())).astype(int)\r\n\r\n # slice_gap = [20] # [20, 25]\r\n # num_slices = [12]\r\n # grid_search(grid_search_save_path, version, slice_gap, num_slices, 1280, devices, args.parallel)\r\n\r\n if args.apply == \"eval\":\r\n\r\n default_params = {}\r\n default_params[\"slice_gap\"] = 20 # 20\r\n default_params[\"num_slices\"] = 12\r\n default_params[\"max_slices_based_on_infected_slices\"] = 0.28 # 0.5, 0.23\r\n default_params[\"min_uncertainty\"] = 0.0 # 0.0, 0.15\r\n default_params[\"default_size\"] = 1280\r\n\r\n params = {}\r\n # params[\"slice_gap\"] = [10, 15, 20, 25, 30, 40, 50, 70, 80, 90, 100, 110, 120, 130]\r\n # params[\"num_slices\"] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\r\n # params[\"max_slices_based_on_infected_slices\"] = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]\r\n params[\"min_uncertainty\"] = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]\r\n params_list = [params]\r\n\r\n # params_list = [{\"slice_gap\": [10, 15, 20, 25, 30, 40, 50, 70, 80, 90, 100, 110, 120, 130]},\r\n # {\"num_slices\": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]},\r\n # {\"max_slices_based_on_infected_slices\": [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5]},\r\n # {\"min_uncertainty\": [0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4]}]\r\n\r\n for params in params_list:\r\n eval_all_hyperparameters(grid_search_save_path, version, method, default_params, params, devices, args.parallel)\r\n\r\n elif args.apply == \"infer\":\r\n test_set_params = {}\r\n test_set_params[\"slice_gap\"] = 30 # 20\r\n test_set_params[\"num_slices\"] = 12 # 12\r\n test_set_params[\"max_slices_based_on_infected_slices\"] = 0.23\r\n test_set_params[\"min_uncertainty\"] = 0.10\r\n test_set_params[\"default_size\"] = 1280\r\n\r\n eval_test_set(test_set_save_path, version, method, test_set_params, args.parallel)\r\n else:\r\n raise RuntimeError(\"Apply unknown.\")\r\n\r\n pool.close()\r\n pool.join()\r\n print(\"Test\")\r\n","sub_path":"i3Deep/mask_recommendation/mask_recommendation.py","file_name":"mask_recommendation.py","file_ext":"py","file_size_in_byte":45150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14870027","text":"from rest_framework import status\nfrom rest_framework.test import APITestCase\n\nfrom legalaid.tests.views.test_base import CLACheckerAuthBaseApiTestMixin\n\n\nfrom legalaid.tests.views.mixins.eligibility_check_api import \\\n EligibilityCheckAPIMixin\n\n\nclass EligibilityCheckTestCase(\n EligibilityCheckAPIMixin, CLACheckerAuthBaseApiTestMixin, APITestCase\n):\n\n def test_can_change_notes(self):\n data = {\n 'notes': 'new notes',\n 'your_problem_notes': 'ipsum lorem2',\n }\n response = self.client.patch(\n self.detail_url, data=data, format='json',\n HTTP_AUTHORIZATION=self.get_http_authorization()\n )\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n # checking the changed properties\n self.resource.your_problem_notes = data['your_problem_notes']\n self.resource.notes = data['notes']\n self.assertEligibilityCheckEqual(response.data, self.resource)\n\n def assertEligibilityCheckEqual(self, data, check):\n self.assertEqual(data['reference'], unicode(check.reference))\n self.assertEqual(data['category'], check.category.code if check.category else None)\n self.assertEqual(data['your_problem_notes'], check.your_problem_notes)\n self.assertEqual(data['notes'], check.notes)\n self.assertEqual(len(data['property_set']), check.property_set.count())\n self.assertEqual(data['dependants_young'], check.dependants_young)\n self.assertEqual(data['dependants_old'], check.dependants_old)\n self.assertPersonEqual(data['you'], check.you)\n self.assertPersonEqual(data['partner'], check.partner, partner=True)\n","sub_path":"cla_backend/apps/checker/tests/api/test_eligibility_check_api.py","file_name":"test_eligibility_check_api.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"548867671","text":"import glob\nimport sys\nimport os\nimport numpy\nimport pylab\nimport healpy\nimport pyfits\n\nimport ugali.utils.healpix\n#import uagli.utils.projector\nimport ugali.candidate.associate\n\npylab.ion()\n\n############################################################\n\"\"\"\ndatadir = '/Users/keithbechtol/Documents/DES/projects/calibration/Y2N/data/catalog'\ninfiles = glob.glob('%s/starcat_y2n_gr_v3_00000*.fits'%(datadir))\ndata_array = []\nfor infile in infiles:\n print infile\n reader = pyfits.open(infile)\n data_array.append(reader[1].data)\n reader.close()\nprint 'Assembling data...'\ndata = numpy.concatenate(data_array)\n\n############################################################\n\nprint 'Applying cuts...'\ncut = (data['WAVG_MAG_PSF_G'] < 23.5) \\\n & ((data['WAVG_MAG_PSF_G'] - data['WAVG_MAG_PSF_R']) < 1.) \\\n & (numpy.fabs(data['SPREAD_MODEL_R']) < 0.003 + data['SPREADERR_MODEL_R'])\n#& (numpy.fabs(data['WAVG_SPREAD_MODEL_R']) < 0.003 + data['SPREADERR_MODEL_R'])\ndata = data[cut]\n\n############################################################\n\nprint 'Pixelizing...'\nnpix_256 = healpy.nside2npix(256)\npix_256 = ugali.utils.healpix.angToPix(256, data['RA'], data['DEC'])\nm_256 = numpy.histogram(pix_256, numpy.arange(npix_256 + 1))[0].astype(float)\nm_256[m_256 == 0.] = healpy.UNSEEN \n\"\"\"\n############################################################\n\nsave = False\n\ninfiles = glob.glob('results_midway_v8/*.csv')\n\nra_array = []\ndec_array = []\nsig_array = []\nr_array = []\ndistance_modulus_array = []\nfor infile in infiles:\n data = numpy.recfromcsv(infile)\n if data.shape == (0,):\n continue\n\n if data['ra'].shape == ():\n ra_array.append([data['ra']])\n dec_array.append([data['dec']])\n sig_array.append([data['sig']])\n r_array.append([data['r']])\n distance_modulus_array.append([data['distance_modulus']])\n else:\n ra_array.append(data['ra'])\n dec_array.append(data['dec'])\n sig_array.append(data['sig'])\n r_array.append(data['r'])\n distance_modulus_array.append(data['distance_modulus'])\n\nsig_array = numpy.concatenate(sig_array)\nindex_sort = numpy.argsort(sig_array)\nsig_array = sig_array[index_sort]\nra_array = numpy.concatenate(ra_array)[index_sort]\ndec_array = numpy.concatenate(dec_array)[index_sort]\nr_array = numpy.concatenate(r_array)[index_sort]\ndistance_modulus_array = numpy.concatenate(distance_modulus_array)[index_sort]\n\n### Run Associations ###\n\ncatalog_array = ['McConnachie12', 'Harris96', 'Corwen04', 'Nilson73', 'Webbink85', 'Kharchenko13', 'WEBDA14','ExtraDwarfs','ExtraClusters']\ncatalog = ugali.candidate.associate.SourceCatalog()\nfor catalog_name in catalog_array:\n catalog += ugali.candidate.associate.catalogFactory(catalog_name)\nassociation_array = []\nassociation_angsep_array = numpy.tile(180., len(sig_array))\nfor ii in range(0, len(sig_array)):\n glon, glat = ugali.utils.projector.celToGal(ra_array[ii], dec_array[ii])\n idx1, idx2, angsep = catalog.match(glon, glat, tol=0.5, nnearest=1)\n match = catalog[idx2]\n if len(match) > 0:\n association_array.append(match[0]['name'].replace(' ', '_'))\n association_angsep_array[ii] = angsep\n else:\n association_array.append('NONE')\nassociation_array = numpy.array(association_array)\n \n\n#cut = ((r_array < 0.21) | (r_array > 0.31)) & (sig_array > 5.9) & (distance_modulus_array < 23.)# & (distance_modulus_array > 20.)\n#cut = (r_array < 0.2) & (sig_array > 7.) & (dec_array < -40.)\n#cut = (r_array < 0.2) & (sig_array > 5.6) & (sig_array < 5.7)\n#cut = (r_array > 0.2) & (sig_array > 10)\n#cut = (r_array > 0.2) & (r_array < 0.28) & (sig_array > 9.)# & (sig_array < 7.)\n#cut = (r_array < 0.2) & (sig_array > 7.)\n#cut = (r_array < 0.2) & (sig_array > 6.) & (sig_array < 7.)\n#cut = (r_array < 0.2) & (sig_array > 5.5) & (sig_array < 6.)\ncut = numpy.logical_not((r_array > 0.2) | \\\n (((numpy.char.count(association_array, 'NGC_') > 0) | \\\n (numpy.char.count(association_array, 'UGC_') > 0) | \\\n (numpy.char.count(association_array, 'IC_') > 0)) & (association_angsep_array < 0.2))) & (sig_array > 5.5)\n\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 55.20, -37.50) < 0.1\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 56.36, -60.44) < 0.1\n#cut = ugali.utils.projector.angsep(ra_array, dec_array, 67.01, -44.34) < 0.1\n\nsig_cut_array = [5.5, 6., 6.5, 7., 10.]\nfor sig_cut in sig_cut_array:\n print(sig_cut, numpy.sum((sig_array > sig_cut) & (r_array < 0.2)))\n\nfor ii in range(0, numpy.sum(cut)):\n print(ra_array[cut][ii], dec_array[cut][ii], sig_array[cut][ii], association_array[cut][ii], association_angsep_array[cut][ii]) \n\nfor ra, dec, distance_modulus in zip(ra_array[cut], dec_array[cut], distance_modulus_array[cut]):\n outfile = 'candidate_%.2f_%.2f.png'%(ra, dec)\n if distance_modulus < 30.:\n pass\n os.system('cp figs_midway_v8/%s figs_temp/.'%(outfile))\n #os.system('open figs_midway_v1/%s'%(outfile))\n\n#sys.exit('DONE')\n\n\"\"\"\npylab.figure()\n#pylab.scatter(ra_array[cut], dec_array[cut], c=sig_array[cut])\npylab.scatter(ra_array, dec_array, c=sig_array, edgecolor='none')\ncolorbar = pylab.colorbar()\ncolorbar.set_label(r'Significance ($\\sigma$)')\n\"\"\"\n\ngc_catalog = ugali.candidate.associate.catalogFactory('Harris96')\nsat_catalog = ugali.candidate.associate.catalogFactory('McConnachie12')\n\nra_ngc, dec_ngc = list(zip(*[[54.63, -35.45],\n [11.78, -20.76],\n [51.59, -21.34],\n [28.25, -13.74],\n [50.59, -37.26],\n [51.62, -35.72],\n [319.12, -48.36],\n [45.40, -14.85],\n [66.93, -55.02]]))\n\nra_des, dec_des, name_des = list(zip(*[[53.92, -54.05, 'Ret II'],\n [56.09, -43.53, 'Eri II'],\n [343.06, -58.57, 'Tuc II'],\n [43.87, -54.11, 'Hor I'],\n [317.20, -51.16, 'Kim 2'],\n [70.95, -50.28, 'Pic I'],\n [354.99, -54.41, 'Phe II'],\n [35.69, -52.28, 'Eri III'],\n [344.18, -50.16, 'Gru I'],\n [49.13, -50.02, 'Hor II'],\n [8.51, -49.04, 'Luque 1']]))\n\nra_des_new, dec_des_new, name_des_new = list(zip(*[[331.06, -46.47, 'Gru II'],\n [359.04, -59.63, 'Tuc III'],\n [82.85, -28.03, 'Col I'], # Rock solid\n #[32.29, -12.17, 'Cet II'],\n [0.668, -60.888, 'Tuc IV'],\n [354.37, -63.26, 'Tuc V'], # Also solid\n #[70.95, -50.29, 'New'], # Pic I\n #[94.85, -50.33, 'New'],\n #[67.01, -44.34, 'New'],\n [56.36, -60.44, 'Many faint stars'],\n [30.02, 3.35, 'Wide near S82']]))\n #[8.51, -49.04, 'Luque 1'],\n #[344.19, -50.16, 'New'], # Grus I\n #[317.21, -51.16, 'New'], # Ind I\n #[55.20, -37.50, 'New'],\n #[14.08, -18.36, 'New'],\n #[348.73, -42.56, 'New']])\n\n# Cannot immediately rule out\n#55.20, -37.50 # Looks OK, but there is a somewhat bright neaby galaxy in Aladin viewer, needs further investigation\n#317.21, -51.16 # Very compact, very few stars, no association, clean in Aladin viewer, Ind I\n#81.18, -54.69 # Not super compelling, but possibly a low surface brightness overdensity\n#14.08, -18.36 # Very sparse if there at all, but stars line up nicely along isochrone, overdensity visible in map, no association, clean in Aladin viewer\n#21.76, -6.04 # Right on edge of footprint, so a bit hard to tell\n#24.37, -34.44 # Nothing obviously wrong, but not many stars at MSTO\n#26.83, -51.93 # Spotty\n#30.37, -3.26 # Whiting 1\n#344.19, -50.16 # Looks pretty good, no association, clean in Aladin viewer, Grus I\n#348.73, -42.56 # A good example of something at a distance that makes very difficult to distinguish from foreground, but an apparent overdensity\n#38.80, 3.84 # Sketchy\n#43.90, -60.05 # Overdensity is somewhat visible in the map, MSTO just below g ~ 23\n#56.36, -60.44 # Clear overdensity, no association, clean in Aladin viewer \n#58.76, -49.61 # AM 1\n#64.70, -24.09 # Sparse, but slight overdensity visible\n#66.19, -21.19 # Eri\n#67.01, -44.34 # Clearly visible overdensity, very sparse, but stars line up on isochrone, no association, clean in Aladin viewer\n#70.95, -50.29 # Looks very good, no association, clean in Aladin viewer, Pic I\n#94.85, -50.33 # Possibly very near, no association, clean in Aladin viewer\n\n#[343.04, -58.59, 'New 2'], Tuc II\n#[43.89, -54.12, 'New 3'], Hor I\n\n#ra_des, dec_des, name_des = zip(*[[359.04, -59.63, 'Tuc III']])\n\n#m_256 = numpy.load('density_map_nside_512.npy')\nm_256 = numpy.load('/Users/keithbechtol/Documents/DES/projects/mw_substructure/des/y2n/skymap/density_map_nside_1024_v6.npy')\nm_256[m_256 == 0.] = healpy.UNSEEN\n\npylab.figure(num='map1', figsize=(16, 10))\nhealpy.mollview(m_256, \n fig='map1', cmap='binary', xsize=6400, min=0.5 * numpy.median(m_256[m_256 > 0.]), max=4. * numpy.median(m_256[m_256 > 0.]),\n unit='Stellar Density',\n title='Inclusive')\npylab.xlim(-1, 0.55)\npylab.ylim(-0.85, 0.2)\nhealpy.projscatter(ra_array, dec_array, c=sig_array, edgecolor='none', lonlat=True, vmin=5., vmax=25.)\nif save:\n pylab.savefig('compile_map_inclusive.png', dpi=150, bbox_inches='tight')\n\npylab.figure(num='map2', figsize=(16, 10))\nhealpy.mollview(m_256, \n fig='map2', cmap='binary', xsize=6400, min=0.5 * numpy.median(m_256[m_256 > 0.]), max=4. * numpy.median(m_256[m_256 > 0.]),\n unit='Stellar Density',\n title=r'Cleaned: size < 0.2 deg & significance > 6 $\\sigma$ & m - M < 23.')\npylab.xlim(-1, 0.55)\npylab.ylim(-0.85, 0.2)\nhealpy.projscatter(ra_array[cut], dec_array[cut], c=sig_array[cut], edgecolor='none', lonlat=True, vmin=5., vmax=25.)\n#healpy.projscatter(ra_array, dec_array, c=sig_array, edgecolor='none', lonlat=True, vmin=5., vmax=25.)\nhealpy.projscatter(ra_des, dec_des, edgecolor='red', facecolor='none', marker='o', s=40, lonlat=True)\nhealpy.projscatter(ra_des_new, dec_des_new, edgecolor='blue', facecolor='none', marker='o', s=50, lonlat=True)\nhealpy.projscatter(gc_catalog.data['ra'], gc_catalog.data['dec'], edgecolor='red', facecolor='none', marker='x', s=40, lonlat=True)\nhealpy.projscatter(sat_catalog.data['ra'], sat_catalog.data['dec'], edgecolor='blue', facecolor='none', marker='x', s=40, lonlat=True)\nhealpy.projscatter(ra_ngc, dec_ngc, edgecolor='green', facecolor='none', marker='x', s=40, lonlat=True)\nif save:\n pylab.savefig('compile_map_clean.png', dpi=150, bbox_inches='tight')\n\n\n#pylab.figure()\n#pylab.scatter(ra_array, dec_array, c=sig_array, edgecolor='none', vmin=5., vmax=25.)\n#pylab.scatter(ra_array[cut], dec_array[cut], c=sig_array[cut], edgecolor='none', vmin=5., vmax=25.)\n#pylab.colorbar()\n#pylab.scatter(ra_des, dec_des, c='black', edgecolor='black', marker='x')\n\n\npylab.figure()\n#pylab.hist(distance_modulus_array[(r_array < 0.2) & (sig_array > 8.)], bins=numpy.arange(16.25, 24.25, 0.5))\npylab.hist(distance_modulus_array, bins=numpy.arange(16.25, 24.25, 0.5))\npylab.xlabel('m - M (mag)')\npylab.ylabel('N')\npylab.savefig('compile_hist_distance_modulus.png', dpi=150, bbox_inches='tight')\n\npylab.figure()\npylab.hist(r_array, bins=numpy.arange(0.005, 0.315, 0.01))\npylab.xlabel('Size (deg)')\npylab.ylabel('N')\npylab.xlim(0., 0.30)\nif save:\n pylab.savefig('compile_hist_size.png', dpi=150, bbox_inches='tight')\n\ncut_dirty = (r_array > 0.2) | \\\n (((numpy.char.count(association_array, 'NGC_') > 0) | \\\n (numpy.char.count(association_array, 'UGC_') > 0) | \\\n (numpy.char.count(association_array, 'IC_') > 0)) & (association_angsep_array < 0.2))\n\npylab.figure()\npylab.yscale('log', nonposy='clip')\npylab.ylim(0.1, 1.e3)\npylab.hist(sig_array, bins=numpy.linspace(5, 25, 41), color='green', alpha=0.5, label='All')\npylab.hist(sig_array[~cut_dirty], bins=numpy.linspace(5, 25, 41), color='green', label='r < 0.2 deg & no large galaxy association')\npylab.xlabel(r'Significance ($\\sigma$)')\npylab.ylabel('N')\npylab.legend(loc='upper right', frameon=False)\nif save:\n pylab.savefig('compile_hist_significance.png', dpi=150, bbox_inches='tight')\n #pylab.savefig('figs_summary_v8/compile_hist_significance.png', dpi=150, bbox_inches='tight')\n\npylab.figure()\npylab.scatter(sig_array, r_array, c=distance_modulus_array, edgecolor='none')\ncolorbar = pylab.colorbar()\ncolorbar.set_label('m - M (mag)')\npylab.xlabel(r'Significance ($\\sigma$)')\npylab.ylabel('Size (deg)')\npylab.xlim(4., 26.)\npylab.ylim(0., 0.32)\nif save:\n pylab.savefig('compile_scatter.png', dpi=150, bbox_inches='tight')\n\nfor ii in range(0, len(ra_des)):\n angsep = ugali.utils.projector.angsep(ra_des[ii], dec_des[ii], ra_array, dec_array)\n outfile = 'candidate_%.2f_%.2f.png'%(ra_array[numpy.argmin(angsep)], dec_array[numpy.argmin(angsep)])\n #print name_des[ii], sig_array[numpy.argmin(angsep)], outfile\n print('| %s | %.2f, %.2f | %.2f | {{thumbnail(%s, size=400)}} |'%(name_des[ii], ra_des[ii], dec_des[ii], sig_array[numpy.argmin(angsep)], outfile))\n os.system('cp figs_midway_v8/%s figs_reported/.'%(outfile))\n\nfor ii in range(0, len(ra_des_new)):\n angsep = ugali.utils.projector.angsep(ra_des_new[ii], dec_des_new[ii], ra_array, dec_array)\n outfile = 'candidate_%.2f_%.2f.png'%(ra_array[numpy.argmin(angsep)], dec_array[numpy.argmin(angsep)])\n #print name_des_new[ii], ra_des_new[ii], dec_des_new[ii], sig_array[numpy.argmin(angsep)], outfile\n print('| %s | %.2f, %.2f | %.2f | {{thumbnail(%s, size=400)}} |'%(name_des_new[ii], ra_des_new[ii], dec_des_new[ii], sig_array[numpy.argmin(angsep)], outfile))\n os.system('cp figs_midway_v8/%s figs_seed/.'%(outfile))\n\n\noutfile = 'simple_binner_compiled_v8.csv'\nwriter = open(outfile, 'w')\nwriter.write('sig, ra, dec, distance_modulus, r, association, association_angsep\\n')\nfor ii in range(0, len(sig_array)):\n writer.write('%10.2f, %10.2f, %10.2f, %10.2f, %10.2f, %30s, %10.2f\\n'%(sig_array[ii], \n ra_array[ii], dec_array[ii], distance_modulus_array[ii], \n r_array[ii],\n association_array[ii], association_angsep_array[ii]))\nwriter.close()\n","sub_path":"ugali/simple/extra/compile_results_v3.py","file_name":"compile_results_v3.py","file_ext":"py","file_size_in_byte":15173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"653424833","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2012 Martin Ueding \n\nimport optparse\nimport json\nimport sys\n\nimport parser\nimport writer\n\ndef main():\n options, args = _parse_args()\n\n filename = args[0]\n\n imported = parser.parse(filename, options.read_format)\n\n if options.outfile is not None:\n outfile = open(options.outfile, \"w\")\n else:\n outfile = sys.stdout\n\n writer.write(imported, outfile, options.write_format)\n\n if options.outfile is not None:\n outfile.close()\n\ndef _parse_args():\n \"\"\"\n Parses the command line arguments.\n\n @return: Tuple with options and (positional) arguments.\n @rtype: tuple\n \"\"\"\n parser = optparse.OptionParser(usage=\"\", description=\"\")\n parser.add_option(\"-o\", dest=\"outfile\", default=None, help=\"File to write to\")\n parser.add_option(\"-w\", dest=\"write_format\", default=\"pidgin\", help=\"Write format. [default: %default]\")\n parser.add_option(\"-r\", dest=\"read_format\", default=\"adium\", help=\"Read format. [default: %default]\")\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"adium-importer.py","file_name":"adium-importer.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332117406","text":"import shutil\nimport subprocess # nosec\nfrom functools import cached_property\nfrom typing import Optional\nfrom xml.etree.ElementTree import Element, ElementTree # nosec\nfrom xml.etree.ElementTree import fromstring as elementtree_fromstring # nosec\n\nfrom django.core.files.uploadedfile import TemporaryUploadedFile\n\n\nclass VisualMediaFileException(Exception):\n pass\n\n\nclass VisualMediaFile:\n _FFMPEG_COMMAND = \"ffmpeg\"\n _IMAGEMAGICK_CONVERT_COMMAND = \"convert\"\n _MEDIAINFO_COMMAND = \"mediainfo\"\n _REQUIRED_COMMANDS = [_FFMPEG_COMMAND, _IMAGEMAGICK_CONVERT_COMMAND, _MEDIAINFO_COMMAND]\n _MEDIAINFO_XML_NAMESPACES = {\n \"mediainfo_ns\": \"https://mediaarea.net/mediainfo\",\n }\n ALLOWED_IMAGE_FORMATS = [\"GIF\", \"JPEG\", \"PNG\", \"WebP\"]\n ALLOWED_VIDEO_FORMATS = [\"MPEG-4\", \"WebM\"]\n ALLOWED_MEDIA_FORMATS = ALLOWED_IMAGE_FORMATS + ALLOWED_VIDEO_FORMATS\n\n def __init__(self, file: TemporaryUploadedFile) -> None:\n self._file = file\n self._content = file.read()\n self._info_xml_tree: Optional[ElementTree] = None\n self._initialize()\n\n @classmethod\n def check_dependencies(cls) -> None:\n commands = cls._REQUIRED_COMMANDS\n for item in commands:\n if not shutil.which(item):\n raise FileNotFoundError(f'Command \"{item}\" not found')\n\n @staticmethod\n def get_element_path_text(source_element: Element, path: str, default=None, namespaces=None) -> Optional[str]:\n return source_element.findtext(path, default=default, namespaces=namespaces)\n\n @classmethod\n def get_element_path_int(cls, source_element: Element, path: str, default=None, namespaces=None) -> Optional[int]:\n text = cls.get_element_path_text(source_element, path, default=default, namespaces=namespaces)\n if isinstance(text, int):\n return text\n if isinstance(text, str):\n return int(text, 10)\n return default\n\n @staticmethod\n def _run_command(*args, **kwargs) -> subprocess.CompletedProcess:\n kwargs.update({\"capture_output\": True, \"check\": True})\n return subprocess.run(args, **kwargs) # nosec # pylint: disable=subprocess-run-check\n\n @cached_property\n def duration(self) -> Optional[float]:\n if not self.is_video:\n return None\n track = self._media_track_element\n duration = self.get_element_path_text(\n track, \"mediainfo_ns:Duration\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n if duration is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return float(duration)\n\n @cached_property\n def height(self) -> int:\n track = self._media_track_element\n height = self.get_element_path_int(track, \"mediainfo_ns:Height\", namespaces=self._MEDIAINFO_XML_NAMESPACES)\n if height is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return height\n\n @property\n def is_video(self) -> bool:\n return self.media_format in self.ALLOWED_VIDEO_FORMATS\n\n @cached_property\n def media_format(self) -> str:\n general_track = self._general_track_element\n media_format = self.get_element_path_text(\n general_track, \"mediainfo_ns:Format\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n if media_format not in self.ALLOWED_MEDIA_FORMATS:\n raise VisualMediaFileException(f\"{media_format} is not acceptable as a media\")\n return media_format\n\n @cached_property\n def size(self) -> int:\n return self._file.size\n\n @cached_property\n def width(self) -> int:\n track = self._media_track_element\n width = self.get_element_path_int(track, \"mediainfo_ns:Width\", namespaces=self._MEDIAINFO_XML_NAMESPACES)\n if width is None:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n return width\n\n @cached_property\n def _general_track_element(self):\n root = self._info_xml_tree.getroot()\n return root[1][0]\n\n @cached_property\n def _media_track_element(self):\n root = self._info_xml_tree.getroot()\n tracks = root[1]\n if not self.is_video:\n track = tracks.findall('mediainfo_ns:track[@type=\"Image\"]', self._MEDIAINFO_XML_NAMESPACES)[0]\n else:\n track = tracks.findall('mediainfo_ns:track[@type=\"Video\"]', self._MEDIAINFO_XML_NAMESPACES)[0]\n return track\n\n def _initialize(self) -> None:\n try:\n media_info = self._run_command(\n self._MEDIAINFO_COMMAND,\n \"--Output=XML\",\n self._file.temporary_file_path(),\n ).stdout.decode(\"utf-8\")\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Error processing media file\") from exc\n\n self._info_xml_tree = ElementTree(elementtree_fromstring(media_info))\n general_track = self._general_track_element\n\n if self.is_video:\n video_stream_count = self.get_element_path_int(\n general_track, \"mediainfo_ns:VideoCount\", namespaces=self._MEDIAINFO_XML_NAMESPACES\n )\n\n if video_stream_count is None or video_stream_count < 1:\n raise VisualMediaFileException(\"Media file might be corrupted\")\n\n if video_stream_count > 1:\n raise VisualMediaFileException(\"Media file has too many video streams\")\n\n # Access all visual media property to make sure exceptions are thrown\n # during initialization rather than later.\n _ = self.duration\n _ = self.height\n _ = self.width\n\n def generate_thumbnail_content(self, resize_dimension: str = \"200\", quality: str = \"85\") -> bytes:\n if self.is_video:\n try:\n primary_image_content = self._run_command(\n self._FFMPEG_COMMAND,\n \"-v\",\n \"quiet\",\n \"-y\",\n \"-i\",\n \"pipe:\",\n \"-ss\",\n # Extract frame from middle of the video.\n f\"{self.duration / 2}\", # type: ignore\n \"-vframes\",\n \"1\",\n \"-f\",\n \"image2\",\n \"pipe:\",\n input=self._content,\n ).stdout\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Could not generate video thumbnail\") from exc\n else:\n primary_image_content = self._content\n\n input_pipe = \"-\"\n\n # Select only the first frame if input file is an animated gif.\n if self.media_format == \"GIF\":\n input_pipe = f\"{input_pipe}[0]\"\n\n try:\n return self._run_command(\n self._IMAGEMAGICK_CONVERT_COMMAND,\n \"-verbose\",\n \"-resize\",\n resize_dimension,\n \"-strip\",\n \"-quality\",\n quality,\n input_pipe,\n \"webp:-\",\n input=primary_image_content,\n ).stdout\n except subprocess.CalledProcessError as exc:\n raise VisualMediaFileException(\"Could not generate thumbnail\") from exc\n","sub_path":"fuchan/utils/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":7323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"263159680","text":"# Given a string and true length of string, replace all whitespace with \"%20\"\n# input: \"Mr John Smith \", 13\n# output: \"Mr%20John%20Smith\"\n\n\ndef urlify(string, n):\n if not len(string):\n return ''\n\n encoder = '%20'\n result = ''\n\n for i in range(n):\n char = string[i]\n if char == ' ':\n result += encoder\n else:\n result += char\n\n return result\n\n\ndef main():\n base = ''\n happy = 'Mr John Smith '\n\n print(urlify(base, 0))\n print(urlify(happy, 13))\n\n\nmain()\n","sub_path":"python/string/urlify.py","file_name":"urlify.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265055574","text":"\"\"\"\n@author : Rakesh Roshan\n@contact : rakesh.roshan@affineanalytics.com\n\nA set of functions to start the API serverand listen to the requests.\nReturns the JSON output from running models and IOU their outputs.\n\"\"\"\nimport cv2\nimport json\nfrom flask import Flask, url_for, send_from_directory, request, jsonify\nimport logging, os\nfrom werkzeug import secure_filename\nimport classifier_new\n\nfrom PIL import Image\nfrom binascii import a2b_base64\n\n\napp = Flask(__name__)\n## Logs are logged into the server.log file.\nfile_handler = logging.FileHandler('server.log')\napp.logger.addHandler(file_handler)\napp.logger.setLevel(logging.INFO)\nPROJECT_HOME = os.path.dirname(os.path.realpath(__file__))\n\n\n@app.route('/testpost', methods = ['POST'])\ndef api_root():\n \"\"\"\n Reads the image from request.\n Runs the model.\n Returns the JSON output.\n Args: HTTP post request with an image file specified to the key 'image'\n \"\"\"\n app.logger.info('Project_Home:' + PROJECT_HOME)\n if request.method == 'POST':\n #print(request.form['image'])\n ## Read the image file.\n #img = request.form['image']\n #print(request.form['image'].encode('utf-8'))\n #img = base64.b64decode(request.form['image'].encode('utf-8')).decode('utf-8')\n #img = request.form['image'].decode('base64')\n #imgData = request.form['image'][:-1]\n #imgData = imgData[22:] \n #print(imgData)\n #img = base64.b64decode(imgData)\n encoded = request.form['image'].split(\",\", 1)[1] \n print(encoded)\n #img_data = b64decode(encoded)\n img_data = a2b_base64(encoded)\n with open(\"test_images/test_32.png\", \"wb\") as f:\n f.write(img_data)\n rgba_image = Image.open(\"test_images/test_32.png\")\n rgb_image = rgba_image.convert('RGB')\n rgb_image.save(\"test_images/test.png\")\n response = classifier_new.main(classifier_new.parse_arguments([])) \n print(response)\n ## Return the JSON response to the API request.\n return jsonify({'data': response}) \n #return response\n else:\n \treturn \"Where is the image?\"\n\n@app.route('/testget', methods = ['GET'])\ndef test_get():\n return \"Tested Get.\"\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False)\n","sub_path":"versions/api_server_v1.0.py","file_name":"api_server_v1.0.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"159579832","text":"import sys\nfrom time import time\n\nimport numpy as np\nimport cv2\n\nimport depthai\n\nimport consts.resource_paths\n\n\nprint('depthai.__version__ == %s' % depthai.__version__)\n\n\ncmd_file = consts.resource_paths.device_depth_cmd_fpath\nif len(sys.argv) > 1 and sys.argv[1] == \"debug\":\n cmd_file = ''\n print('depthai will not load cmd file into device.')\n\n\ncounter = 0\n\nstreams_list = ['left', 'right', 'depth', 'meta_d2h']\n\npipieline = depthai.create_pipeline(\n streams=streams_list,\n cmd_file=cmd_file,\n calibration_file=consts.resource_paths.calib_fpath,\n config_file=consts.resource_paths.pipeline_config_fpath\n )\n\n\nt_start = time()\nframe_count = {}\nframe_count_prev = {}\nfor s in streams_list:\n frame_count[s] = 0\n frame_count_prev[s] = 0\n\n\nwhile True:\n data_list = pipieline.get_available_data_packets()\n\n for packet in data_list:\n if packet.stream_name == 'depth':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n elif packet.stream_name == 'meta_d2h':\n data = packet.getData()\n print('meta_d2h counter: ' + str(data[0]))\n\n elif packet.stream_name == 'left':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n elif packet.stream_name == 'right':\n frame_bgr = packet.getData()\n cv2.putText(frame_bgr, \"fps: \" + str(frame_count_prev[packet.stream_name]), (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0))\n cv2.imshow(packet.stream_name, frame_bgr)\n else:\n print('Packet : ' + packet.stream_name)\n\n frame_count[packet.stream_name] += 1\n\n if cv2.waitKey(1) == ord('q'):\n break\n\n t_curr = time()\n if t_start + 1.0 < t_curr:\n t_start = t_curr\n\n for s in streams_list:\n frame_count_prev[s] = frame_count[s]\n frame_count[s] = 0\n\nprint('py: DONE.')\n","sub_path":"python-api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465490730","text":"# This module sets up arbitrary initial data to be input later froma file in terms of\n# the variables used in BSSN_RHSs.py\n# \n# **Input variables needed for spacetime evolution**:\n# * Conformal factor, psi_in\n# * Desired coordinate system\n# * Desired initial lapse $\\alpha_in$ and shift $\\beta^i_in$\n# \n# **Transformation to curvilinear coordinates**:\n# * Once the above variables have been set in Cartesian coordinates, we will apply the appropriate coordinate transformations and tensor rescalings ([described in the BSSN NRPy+ tutorial module](Tutorial-BSSNCurvilinear.ipynb))\n\n# Step P0: Load needed modules\nimport numpy as np\nimport sympy as sp\nimport NRPy_param_funcs as par\nfrom outputC import *\nimport indexedexp as ixp\nimport BSSN_SF.CartesianADMID_to_BSSNCurvilinearID as ctob\nimport BSSN_SF.BSSN_ID_function_string as bIDf\n\nthismodule = \"ID_array_psi\"\npsi_in = par.Cparameters(\"REAL\", thismodule, [\"psi_in\"], \"\")\nalpha_in = par.Cparameters(\"REAL\", thismodule, [\"alpha_in\"], \"\")\n\ndef ID_array_psi():\n global Cartxyz, gammaCartDD, KCartDD, alphaCart, betaCartU, BCartU\n \n # Step 0: Set spatial dimension (must be 3 for BSSN)\n DIM = 3\n par.set_parval_from_str(\"grid::DIM\",DIM)\n Cartxyz = ixp.declarerank1(\"Cartxyz\")\n\n # Step 1: Set psi, the conformal factor:\n psi = psi_in \n\n # Step 2: Set all needed ADM variables in Cartesian coordinates\n gammaCartDD = ixp.zerorank2()\n KCartDD = ixp.zerorank2() # K_{ij} = 0 for these initial data\n for i in range(DIM):\n gammaCartDD[i][i] = psi**4\n\n alphaCart = alpha_in\n betaCartU = ixp.zerorank1() # We generally choose \\beta^i = 0 for these initial data\n BCartU = ixp.zerorank1() # We generally choose B^i = 0 for these initial data\n \n cf,hDD,lambdaU,aDD,trK,alpha,vetU,betU = \\\n ctob.Convert_Cartesian_ADM_to_BSSN_curvilinear(Cartxyz, gammaCartDD,KCartDD,alphaCart,betaCartU,BCartU)\n \n global returnfunction\n returnfunction = bIDf.BSSN_ID_function_string(cf,hDD,lambdaU,aDD,trK,alpha,vetU,betU)","sub_path":"BSSN_SF/ID_array_psi.py","file_name":"ID_array_psi.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"571448504","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 26 11:02:19 2020\n\n@author: richieBao-caDesign设计(cadesign.cn)\n\"\"\"\n\n#位于百度地图POI数据的抓取与地理空间点地图/1. 百度地图POI数据的抓取-单个分类实现与地理空间点地图/1.1 单个分类POI爬取\ndef baiduPOI_dataCrawler(query_dic,bound_coordinate,partition,page_num_range,poi_fn_list=False):\n #所调用的库及辅助文件\n import coordinate_transformation as cc \n import urllib, json, csv,os,pathlib\n \n '''function-百度地图开放平台POI数据爬取'''\n urlRoot='http://api.map.baidu.com/place/v2/search?' #数据下载网址,查询百度地图服务文档\n #切分检索区域\n xDis=(bound_coordinate['rightTop'][0]-bound_coordinate['leftBottom'][0])/partition\n yDis=(bound_coordinate['rightTop'][1]-bound_coordinate['leftBottom'][1])/partition \n #判断是否要写入文件\n if poi_fn_list:\n for file_path in poi_fn_list:\n fP=pathlib.Path(file_path)\n if fP.suffix=='.csv':\n poi_csv=open(fP,'w',encoding='utf-8')\n csv_writer=csv.writer(poi_csv) \n elif fP.suffix=='.json':\n poi_json=open(fP,'w',encoding='utf-8')\n num=0\n jsonDS=[] #存储读取的数据,用于.json格式数据的保存\n #循环切分的检索区域,逐区下载数据\n print(\"Start downloading data...\")\n for i in range(partition):\n for j in range(partition):\n leftBottomCoordi=[bound_coordinate['leftBottom'][0]+i*xDis,bound_coordinate['leftBottom'][1]+j*yDis]\n rightTopCoordi=[bound_coordinate['leftBottom'][0]+(i+1)*xDis,bound_coordinate['leftBottom'][1]+(j+1)*yDis]\n for p in page_num_range: \n #更新请求参数\n query_dic.update({'page_num':str(p),\n 'bounds':str(leftBottomCoordi[1]) + ',' + str(leftBottomCoordi[0]) + ','+str(rightTopCoordi[1]) + ',' + str(rightTopCoordi[0]),\n 'output':'json',\n })\n\n url=urlRoot+urllib.parse.urlencode(query_dic)\n data=urllib.request.urlopen(url)\n responseOfLoad=json.loads(data.read()) \n if responseOfLoad.get(\"message\")=='ok':\n results=responseOfLoad.get(\"results\") \n for row in range(len(results)):\n subData=results[row]\n baidu_coordinateSystem=[subData.get('location').get('lng'),subData.get('location').get('lat')] #获取百度坐标系\n Mars_coordinateSystem=cc.bd09togcj02(baidu_coordinateSystem[0], baidu_coordinateSystem[1]) #百度坐标系-->火星坐标系\n WGS84_coordinateSystem=cc.gcj02towgs84(Mars_coordinateSystem[0],Mars_coordinateSystem[1]) #火星坐标系-->WGS84\n \n #更新坐标\n subData['location']['lat']=WGS84_coordinateSystem[1]\n subData['detail_info']['lat']=WGS84_coordinateSystem[1]\n subData['location']['lng']=WGS84_coordinateSystem[0]\n subData['detail_info']['lng']=WGS84_coordinateSystem[0] \n \n if csv_writer:\n csv_writer.writerow([subData]) #逐行写入.csv文件\n jsonDS.append(subData)\n num+=1 \n print(\"No.\"+str(num)+\" was written to the .csv file.\")\n if poi_json: \n json.dump(jsonDS,poi_json)\n poi_json.write('\\n')\n poi_json.close()\n if poi_csv:\n poi_csv.close()\n print(\"The download is complete.\")\n return jsonDS\n\n\n#位于百度地图POI数据的抓取与地理空间点地图/1. 百度地图POI数据的抓取-单个分类实现与地理空间点地图/1.2 将.csv格式的POI数据转换为pandas的DataFrame\ndef csv2df(poi_fn_csv):\n import pandas as pd\n from benedict import benedict #benedict库是dict的子类,支持键列表(keylist)/键路径(keypath),应用该库的flatten方法展平嵌套的字典,准备用于DataFrame数据结构\n import csv\n '''function-转换.csv格式的POI数据为pandas的DataFrame'''\n n=0\n with open(poi_fn_csv, newline='',encoding='utf-8') as csvfile:\n poi_reader=csv.reader(csvfile)\n poi_dict={} \n poiExceptions_dict={}\n for row in poi_reader: \n if row:\n try:\n row_benedict=benedict(eval(row[0])) #用eval方法,将字符串字典\"{}\"转换为字典{}\n flatten_dict=row_benedict.flatten(separator='_') #展平嵌套字典\n poi_dict[n]=flatten_dict\n except: \n print(\"incorrect format of data_row number:%s\"%n) \n poiExceptions_dict[n]=row\n n+=1\n #if n==5:break #因为循环次数比较多,在调试代码时,可以设置停止的条件,节省时间与方��数据查看\n poi_df=pd.concat([pd.DataFrame(poi_dict[d_k].values(),index=poi_dict[d_k].keys(),columns=[d_k]).T for d_k in poi_dict.keys()], sort=True,axis=0)\n # print(\"_\"*50)\n for col in poi_df.columns:\n try:\n poi_df[col]=pd.to_numeric(poi_df[col])\n except:\n pass\n #print(\"%s data type is not converted...\"%(col))\n print(\"_\"*50)\n print(\".csv to DataFrame is completed!\")\n #print(poi_df.head()) #查看最终DataFrame格式下POI数据\n #print(poi_df.dtypes) #查看数据类型\n return poi_df\n\n\n#位于百度地图POI数据的抓取与地理空间点地图/1.1 多个分类POI爬取|1.2 批量转换.csv格式数据为GeoDataFrame/1.2.1 定义提取文件夹下所有文件路径的函数\ndef filePath_extraction(dirpath,fileType):\n import os\n '''以所在文件夹路径为键,值为包含该文件夹下所有文件名的列表。文件类型可以自行定义 '''\n filePath_Info={}\n i=0\n for dirpath,dirNames,fileNames in os.walk(dirpath): #os.walk()遍历目录,使用help(os.walk)查看返回值解释\n i+=1\n if fileNames: #仅当文件夹中有文件时才提取\n tempList=[f for f in fileNames if f.split('.')[-1] in fileType]\n if tempList: #剔除文件名列表为空的情况,即文件夹下存在不为指定文件类型的文件时,上一步列表会返回空列表[]\n filePath_Info.setdefault(dirpath,tempList)\n return filePath_Info\n\n\n#频数分布计算\ndef frequency_bins(df,bins):\n import pandas as pd\n '''function-频数分布计算'''\n\n #A-组织数据\n column_name=df.columns[0]\n column_bins_name=df.columns[0]+'_bins'\n df[column_bins_name]=pd.cut(x=df[column_name],bins=bins,right=False) #参数right=False指定为包含左边值,不包括右边值。\n df_bins=df.sort_values(by=[column_name]) #按照分割区间排序\n df_bins.set_index([column_bins_name,df_bins.index],drop=False,inplace=True) #以price_bins和原索引值设置多重索引,同时配置drop=False参数保留原列。\n #print(df_bins.head(10))\n\n #B-频数计算\n dfBins_frequency=df_bins[column_bins_name].value_counts() #dropna=False \n dfBins_relativeFrequency=df_bins[column_bins_name].value_counts(normalize=True) #参数normalize=True将计算相对频数(次数) dividing all values by the sum of values\n dfBins_freqANDrelFreq=pd.DataFrame({'fre':dfBins_frequency,'relFre':dfBins_relativeFrequency})\n #print(dfBins_freqANDrelFreq)\n\n #C-组中值计算\n dfBins_median=df_bins.median(level=0)\n dfBins_median.rename(columns={column_name:'median'},inplace=True)\n #print(dfBins_median)\n\n #D-合并分割区间、频数计算和组中值的DataFrame格式数据。\n df_fre=dfBins_freqANDrelFreq.join(dfBins_median).sort_index().reset_index() #在合并时会自动匹配index\n #print(ranmen_fre)\n\n #E-计算频数比例\n df_fre['fre_percent%']=df_fre.apply(lambda row:row['fre']/df_fre.fre.sum()*100,axis=1)\n\n return df_fre\n\n\n#convert points .shp to raster 将点数据写入为raster数据。使用raster.SetGeoTransform,栅格化数据。参考GDAL官方代码\ndef pts2raster(pts_shp,raster_path,cellSize,field_name=False):\n from osgeo import gdal, ogr,osr\n '''\n function - 将.shp格式的点数据转换为.tif栅格(raster)\n \n Paras:\n pts_shp - .shp格式点数据文件路径\n raster_path - 保存的栅格文件路径\n cellSize - 栅格单元大小\n field_name - 写入栅格的.shp点数据属性字段\n '''\n #定义空值(没有数据)的栅格数值 Define NoData value of new raster\n NoData_value=-9999\n \n #打开.shp点数据,并返回地理区域范围 Open the data source and read in the extent\n source_ds=ogr.Open(pts_shp)\n source_layer=source_ds.GetLayer()\n x_min, x_max, y_min, y_max=source_layer.GetExtent()\n \n #使用GDAL库建立栅格 Create the destination data source\n x_res=int((x_max - x_min) / cellSize)\n y_res=int((y_max - y_min) / cellSize)\n target_ds=gdal.GetDriverByName('GTiff').Create(raster_path, x_res, y_res, 1, gdal.GDT_Float64) #gdal的数据类型 gdal.GDT_Float64,gdal.GDT_Int32...\n target_ds.SetGeoTransform((x_min, cellSize, 0, y_max, 0, -cellSize))\n outband=target_ds.GetRasterBand(1)\n outband.SetNoDataValue(NoData_value)\n\n #向栅格层中写入数据\n if field_name:\n gdal.RasterizeLayer(target_ds,[1], source_layer,options=[\"ATTRIBUTE={0}\".format(field_name)])\n else:\n gdal.RasterizeLayer(target_ds,[1], source_layer,burn_values=[-1]) \n \n #配置投影坐标系统\n spatialRef=source_layer.GetSpatialRef()\n target_ds.SetProjection(spatialRef.ExportToWkt()) \n \n outband.FlushCache()\n return gdal.Open(raster_path).ReadAsArray()\n\n\ndef pts_geoDF2raster(pts_geoDF,raster_path,cellSize,scale):\n from osgeo import gdal,ogr,osr\n import numpy as np\n from scipy import stats\n '''\n function - ���GeoDaraFrame格式的点数据转换为栅格数据\n \n Paras:\n pts_geoDF - GeoDaraFrame格式的点数据\n raster_path - 保存的栅格文件路径\n cellSize - 栅格单元大小\n scale - 缩放核密度估计值\n '''\n #定义空值(没有数据)的栅格数值 Define NoData value of new raster\n NoData_value=-9999\n x_min, y_min,x_max, y_max=pts_geoDF.geometry.total_bounds\n\n #使用GDAL库建立栅格 Create the destination data source\n x_res=int((x_max - x_min) / cellSize)\n y_res=int((y_max - y_min) / cellSize)\n target_ds=gdal.GetDriverByName('GTiff').Create(raster_path, x_res, y_res, 1, gdal.GDT_Float64 )\n target_ds.SetGeoTransform((x_min, cellSize, 0, y_max, 0, -cellSize))\n outband=target_ds.GetRasterBand(1)\n outband.SetNoDataValue(NoData_value) \n \n #配置投影坐标系统\n spatialRef = osr.SpatialReference()\n epsg=int(pts_geoDF.crs.srs.split(\":\")[-1])\n spatialRef.ImportFromEPSG(epsg) \n target_ds.SetProjection(spatialRef.ExportToWkt())\n \n #向栅格层中写入数据\n #print(x_res,y_res)\n X, Y = np.meshgrid(np.linspace(x_min,x_max,x_res), np.linspace(y_min,y_max,y_res))\n positions=np.vstack([X.ravel(), Y.ravel()])\n values=np.vstack([pts_geoDF.geometry.x, pts_geoDF.geometry.y]) \n print(\"Start calculating kde...\")\n kernel=stats.gaussian_kde(values)\n Z=np.reshape(kernel(positions).T, X.shape)\n print(\"Finish calculating kde!\")\n print(values)\n \n outband.WriteArray(Z*scale) \n outband.FlushCache()\n print(\"conversion complete!\")\n return gdal.Open(raster_path).ReadAsArray()\n\n\ndef start_time():\n import datetime\n '''\n function-计算当前时间\n '''\n start_time=datetime.datetime.now()\n print(\"start time:\",start_time)\n return start_time\n\ndef duration(start_time):\n import datetime\n '''\n function-计算持续时间\n\n Paras:\n start_time - 开始时间\n '''\n end_time=datetime.datetime.now()\n print(\"end time:\",end_time)\n duration=(end_time-start_time).seconds/60\n print(\"Total time spend:%.2f minutes\"%duration)","sub_path":"notebook/BaiduMapPOIcollection_ipynb/util_poi.py","file_name":"util_poi.py","file_ext":"py","file_size_in_byte":12248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"586383660","text":"import tensorflow as tf\nimport keras.backend as K\nimport numpy as np\n# import matplotlib.pyplot as plt\n\n\ndef loss(y_true, y_pred): # designed loss function\n err = y_true - y_pred\n lost = 0\n\n less0 = tf.less_equal(err, 0) # find elements less than 0 as True\n cast1 = tf.cast(less0, dtype=tf.float32) # convert bool to 0/1\n\n greater0 = tf.greater(err, 0) # find elements greater than 0 as True\n cast2 = tf.cast(greater0, dtype=tf.float32) # convert bool to 0/1\n\n err1 = tf.where(less0, err, cast1) # elements less than 0\n err2 = tf.where(greater0, err, cast2) # elements greater than 0\n\n lost += 1 - K.exp((-K.log(0.5)) * (err1 / 20))\n lost += 1 - K.exp((K.log(0.5)) * (err2 / 5))\n\n return K.mean(lost)\n\n\ndef score(err): # score function , plot the scatters\n # err = y_true - y_pred\n if err < 0:\n score = np.exp(-np.log(0.5)*(err/20))\n elif err > 0:\n score = np.exp(np.log(0.5)*(err/5))\n else:\n score = 1\n return score\n\n\n\n","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207901836","text":"from typing import Union, List\nfrom mp_api.client import MPRester\nfrom pyiron_atomistics.atomistics.structure.has_structure import HasStructure\nfrom pyiron_atomistics.atomistics.structure.structurestorage import StructureStorage\nfrom pyiron_atomistics.atomistics.structure.atoms import pymatgen_to_pyiron, Atoms\n\n\nclass MPQueryResults(HasStructure):\n def __init__(self, results):\n \"\"\"\n\n Args:\n docs (list of dicts): query results from Materials Project, should be obtained with use_document_model=False\n \"\"\"\n self._results = results\n self._material_ids = [r[\"material_id\"] for r in results]\n\n def _translate_frame(self, frame):\n try:\n return self._material_ids.index(frame)\n except ValueError:\n raise KeyError(f\"material id {frame} not among results!\") from None\n\n def __iter__(self):\n yield from self.iter_structures()\n\n def _get_structure(self, frame, wrap_atoms=True):\n return pymatgen_to_pyiron(self._results[frame][\"structure\"])\n\n def _number_of_structures(self):\n return len(self._results)\n\n def to_list(self):\n \"\"\"\n Get a list of queried structures.\n\n Returns:\n list: structures\n \"\"\"\n return [pymatgen_to_pyiron(r[\"structure\"]) for r in self._results]\n\n def to_storage(self):\n \"\"\"\n Get a StructureStorage of queried structures.\n\n The materials project id is used as the identifier.\n\n Returns:\n :class:`~.StructureStorage`: structures\n \"\"\"\n store = StructureStorage()\n for i, structure in enumerate(self):\n store.add_structure(structure, identifier=self._material_ids[i])\n return store\n\n\nclass MaterialsProjectFactory:\n \"\"\"\n Convenience interface to the Materials Project Structure Database.\n\n Usage is only possible with an API key obtained from the Materials Project. To do this, create an account with\n them, login and access `this webpage `.\n\n Once you have a key, either pass it as the `api_key` parameter in the methods of this object or export an\n environment variable, called `MP_API_KEY`, in your shell setup.\n \"\"\"\n\n @staticmethod\n def search(\n chemsys: Union[str, List[str]], api_key=None, **kwargs\n ) -> MPQueryResults:\n \"\"\"\n Search the database for all structures matching the given query.\n\n Note that `chemsys` takes distint values for unaries, binaries and so! A query with `chemsys=[\"Fe\", \"O\"]` will\n return iron structures and oxygen structures, but no iron oxide structures. Similarily `chemsys=[\"Fe-O\"]` will\n not return unary structures.\n\n All keyword arguments for filtering from the original API are supported. See the\n `original docs `_ for them.\n\n Search for all iron structures:\n\n >>> pr = Project(...)\n >>> irons = pr.create.structure.materialsproject.search(\"Fe\")\n >>> irons.number_of_structures\n 10\n\n The returned :class:`~.MPQueryResults` object implements :class:`~.HasStructure` and can be accessed with the\n material ids as a short-hand\n\n >>> irons.get_structure(1) == irons.get_structure('mp-13')\n True\n\n Search for all structures with Al, Li that are on the T=0 convex hull:\n\n >>> alli = pr.create.structure.materialsproject.search(['Al', 'Li', 'Al-Li'], is_stable=True)\n >>> len(alli)\n 6\n\n Args:\n chemsys (str, list of str): confine search to given elements; either an element symbol or multiple element\n symbols seperated by dashes; if a list of strings is given return structures matching either of them\n api_key (str, optional): if your API key is not exported in the environment flag MP_API_KEY, pass it here\n **kwargs: passed verbatim to :meth:`mp_api.MPRester.summary.search` to further filter the results\n\n Returns:\n :class:`~.MPQueryResults`: resulting structures from the query\n \"\"\"\n rest_kwargs = {\n \"use_document_model\": False, # returns results as dictionaries\n \"include_user_agent\": True, # send some additional software version info to MP\n }\n if api_key is not None:\n rest_kwargs[\"api_key\"] = api_key\n with MPRester(**rest_kwargs) as mpr:\n results = mpr.summary.search(\n chemsys=chemsys, **kwargs, fields=[\"structure\", \"material_id\"]\n )\n return MPQueryResults(results)\n\n @staticmethod\n def by_id(\n material_id: Union[str, int],\n final: bool = True,\n conventional_unit_cell: bool = False,\n api_key=None,\n ) -> Union[Atoms, List[Atoms]]:\n \"\"\"\n Retrieve a structure by material id.\n\n This is how you would ask for the iron ground state:\n\n >>> pr = Project(...)\n >>> pr.create.structure.materialsproject.by_id('mp-13')\n Fe: [0. 0. 0.]\n tags:\n spin: [(0: 2.214)]\n pbc: [ True True True]\n cell:\n Cell([[2.318956, 0.000185, -0.819712], [-1.159251, 2.008215, -0.819524], [2.5e-05, 0.000273, 2.459206]])\n\n\n Args:\n material_id (str): the id assigned to a structure by the materials project\n api_key (str, optional): if your API key is not exported in the environment flag MP_API_KEY, pass it here\n final (bool, optional): if set to False, returns the list of initial structures,\n else returns the final structure. (Default is True)\n conventional_unit_cell (bool, optional): if set to True, returns the standard conventional unit cell.\n (Default is False)\n\n Returns:\n :class:`~.Atoms`: requested final structure if final is True\n list of :class:~.Atoms`: a list of initial (pre-relaxation) structures if final is False\n\n Raises:\n ValueError: material id does not exist\n \"\"\"\n rest_kwargs = {\n \"include_user_agent\": True, # send some additional software version info to MP\n }\n if api_key is not None:\n rest_kwargs[\"api_key\"] = api_key\n with MPRester(**rest_kwargs) as mpr:\n if final:\n return pymatgen_to_pyiron(\n mpr.get_structure_by_material_id(\n material_id=material_id,\n final=final,\n conventional_unit_cell=conventional_unit_cell,\n )\n )\n else:\n return [\n pymatgen_to_pyiron(mpr_structure)\n for mpr_structure in (\n mpr.get_structure_by_material_id(\n material_id=material_id,\n final=final,\n conventional_unit_cell=conventional_unit_cell,\n )\n )\n ]\n","sub_path":"pyiron_atomistics/atomistics/structure/factories/materialsproject.py","file_name":"materialsproject.py","file_ext":"py","file_size_in_byte":7091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236226863","text":"from keras.models import Sequential, load_model\r\nfrom keras.preprocessing import image\r\nfrom keras.layers import Conv2D, MaxPooling2D\r\nfrom keras.layers import Activation, Dropout, Flatten, Dense\r\nfrom keras import backend as K\r\nfrom keras import applications\r\nimport cv2\r\nimport keras\r\nimport numpy as np\r\nimport os\r\nfrom keras.optimizers import Adam\r\nfrom directory_management import *\r\nfrom models_configuration import *\r\n# import image_processing as ip\r\nimport image_threshold as it\r\nfrom PIL import ImageFont, ImageDraw, Image\r\n\r\napparel_model_path = \"bottleneck_fc_model.h5\"\r\n\r\napparel_labels = [\"Batik\", \"Jacket\", \"Polo\", \"Shirt\", \"T-Shirt\"]\r\n\r\nimg_width, img_height = 150, 150\r\nb, g, r, a = 255, 255, 255, 0\r\n\r\n# for feature extraction\r\npre_model = applications.VGG16(include_top=False, weights='imagenet')\r\n\r\ndef load_models():\r\n\tapparel = load_model(apparel_model_path)\r\n\r\n\tadam = Adam(lr=0.0001)\r\n\tapparel.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\r\n\treturn apparel\r\n\r\napparel_model = load_models()\r\n\r\ndef resize_image(event):\r\n\tnew_width = event.width\r\n\tnew_height = event.height\r\n\timage = copy_of_image.resize((new_width, new_height))\r\n\tphoto = ImageTk.PhotoImage(image)\r\n\tlabel.config(image = photo)\r\n\tlabel.image = photo #avoid garbage collection\r\n\r\ndef loadimage(input_image, image_source):\r\n\tif image_source == 'camera':\r\n\t\tcv2.imwrite('temp.jpg', input_image)\r\n\t\timg = getfeature('temp.jpg')\r\n\telif image_source == 'image':\r\n\t\timg = getfeature(input_image)\r\n\treturn img\r\n\r\ndef show_top_three(class_prob):\r\n\tpred_list = np.argsort(class_prob)[0]\r\n\tprint (pred_list)\r\n\ttopidx = []\r\n\ttoplabels = []\r\n\tj = 0\r\n\tlabels = apparel_labels\r\n\tfor i in range(-1, -4, -1):\r\n\t\tidx = pred_list[i]\r\n\t\ttopidx.append(idx)\r\n\t\ttoplabels.append(labels[idx])\r\n\t\tprint(topidx[j])\r\n\t\tprint(toplabels[j])\r\n\t\tj += 1\r\n\treturn topidx, toplabels\r\n\r\ndef getprediction(input_image, image_source):\r\n\timg = loadimage(input_image, image_source)\r\n\tprediction, topidx, toplabels = [], [], []\r\n\t# predict result\r\n\tprediction = apparel_model.predict(img)\r\n\ttopidx, toplabels = show_top_three(prediction)\r\n\tprint(prediction)\r\n\treturn toplabels\r\n\r\n# extract feature from image\r\ndef getfeature(input_image):\r\n img = image.load_img(input_image, target_size=(img_height, img_width))\r\n x = image.img_to_array(img)\r\n x = np.expand_dims(x, axis=0)\r\n x = preprocess_input(x)\r\n features = pre_model.predict(x)\r\n return features\r\n\r\ndef live_processing():\r\n cap = cv2.VideoCapture(0)\r\n cam_width = cap.get(3) # float\r\n cam_width = int(cam_width)\r\n window_width = cam_width\r\n cam_height = cap.get(4) # float\r\n cam_height = int(cam_height)\r\n window_height = cam_height\r\n while True:\r\n ret, frame = cap.read()\r\n cv2.rectangle(frame, (140, 100), (500, 380), (0, 255, 0), 2) \r\n croppedframe = frame[100:-100, 140:-140]\r\n \r\n appareltoplabels = getprediction(croppedframe, \"camera\")\r\n fontpath = \"C:\\\\Users\\\\ACER\\\\Desktop\\\\COMP6065-Artificial_Intelligence\\\\ProjectAI\\\\image-classification\\\\fonts\\\\VAGRundschrift.ttf\"\r\n font = ImageFont.truetype(fontpath, 28)\r\n img_pil = Image.fromarray(frame)\r\n draw = ImageDraw.Draw(img_pil)\r\n # draw.text((145, 95), 'press SPACE to capture an image', font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 96), '#1 ' + appareltoplabels[0], font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 68), '#2 ' + appareltoplabels[1], font = font, fill = (b, g, r, a))\r\n draw.text((10, window_height - 40), '#3 ' + appareltoplabels[2], font = font, fill = (b, g, r, a))\r\n img = np.array(img_pil)\r\n\r\n cv2.imshow('camera', img)\r\n\r\n key = cv2.waitKey(1)\r\n if key == 27:\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n break\r\n elif key == 32:\r\n ret, currframe = cap.read()\r\n cv2.imwrite('capture.jpg', currframe)\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n break\r\n return appareltoplabels","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271985187","text":"from typing import Any, List\nfrom pyot.pipeline import pipelines\nimport aiohttp\nimport asyncio\nimport uuid\n\n\nfrom logging import getLogger\nLOGGER = getLogger(__name__)\n\n\nclass Gatherer:\n '''\n Scraper that wraps asyncio.gather, automatically create a session that\n is reused across the statements provided to get data even faster.\n\n For executing mass non-pyot coroutines, please use Queue instead.\n Unlike Queue, workers are fake workers, they only represent the size of the chunk to gather.\n '''\n workers: int\n session_class: Any\n log_level: int\n cancel_on_raise: bool\n statements: List\n responses: List\n\n def __init__(self, workers: int = 25, log_level: int = 10, cancel_on_raise: bool = False):\n self.workers = workers\n self.cancel_on_raise = cancel_on_raise\n self.log_level = log_level\n self.statements = []\n\n async def __aenter__(self) -> \"Gatherer\":\n self.session_id = uuid.uuid4()\n self.session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False, limit=self.workers))\n for pipeline in pipelines.values():\n pipeline.sessions[self.session_id] = self.session\n LOGGER.log(self.log_level, f\"[Trace: Pyot Gatherer] Created session '{self.session_id}'\")\n return self\n\n async def __aexit__(self, *args):\n await self.session.close()\n for pipeline in pipelines.values():\n pipeline.sessions.pop(self.session_id)\n LOGGER.log(self.log_level, f\"[Trace: Pyot Gatherer] Closed session '{self.session_id}'\")\n return\n\n async def gather(self):\n '''Awaitable, starts the scraping process and saves results to `responses`.\n \n Gatherings are done by chunks, the size of the chunk is determined by the number of workers.\n '''\n for i in range(len(self.statements)):\n try:\n self.statements[i] = self.statements[i].get\n except Exception:\n raise RuntimeError(f\"[Trace: Pyot Gatherer] Failed to add session id to statements at index {i}, \"\n \"make sure that only Pyot objects are included and 'get()' is not passed on the statements\")\n\n try:\n self.responses = []\n splits = int(len(self.statements)/self.workers)+1\n for s in range(splits):\n bucket = []\n for st in self.statements[s*self.workers:(s+1)*self.workers if s+1 < splits else None]:\n bucket.append(asyncio.create_task(st(sid=self.session_id)))\n await asyncio.sleep(0.01)\n self.responses.extend(await asyncio.gather(*bucket, return_exceptions=False if self.cancel_on_raise else True))\n return self.responses\n except Exception as e:\n for task in bucket:\n task.cancel()\n LOGGER.warning(f\"[Trace: Pyot Gatherer] All statements of session '{self.session_id}' are cancelled due to exception: {e}\")\n raise\n","sub_path":"pyot/core/gatherer.py","file_name":"gatherer.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"127916855","text":"# root/app/db/crud/expenses.py\n\nfrom fastapi import Path, HTTPException\nfrom fastapi.encoders import jsonable_encoder\n\nfrom sqlalchemy.orm import Session\n\nfrom app.db.models import expenses as models\nfrom app.db.schemas import expenses as schemas\n\n\nclass ExpenseCRUD:\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def list_expenses(\n db: Session,\n ):\n \"\"\" List all the categories\n \"\"\"\n return db.query(models.Expense).all()\n\n @staticmethod\n def get_expense_by_id(\n db: Session,\n expense_id: int = Path(..., title=\"Expense ID\"),\n ):\n \"\"\" Filter expense by ID\n \"\"\"\n return db.query(models.Expense).filter(\n models.Expense.id == expense_id\n ).first()\n\n # @staticmethod\n # def get_expense_by_category(\n # db: Session,\n # name: str = Path(..., title=\"Groceries\"),\n # ):\n # \"\"\" Filter categories by name\n # \"\"\"\n # return db.query(models.Expense).filter(\n # models.Expense.name == name\n # ).first()\n\n @staticmethod\n def create_expense(\n db: Session,\n expense: schemas.Expense\n ):\n \"\"\" Create new expense\n \"\"\"\n new_expense = models.Expense(**expense.dict())\n db.add(new_expense)\n db.commit()\n db.refresh(new_expense)\n return new_expense\n\n @staticmethod\n def update_expense_by_id(\n db: Session,\n expense_name: str,\n new_expense: models.Expense\n ):\n \"\"\" Update existing season\n \"\"\"\n data = jsonable_encoder(new_expense)\n print(data, new_expense)\n expense = db.query(models.Expense).filter(\n models.Expense.name == expense_name\n ).first()\n\n if not expense:\n raise HTTPException(404, \"NOT FOUND\")\n expense.id = new_expense.id\n expense.name = new_expense.name\n db.commit()\n db.refresh(expense)\n return expense\n\n @staticmethod\n def remove_expense_by_id(\n db: Session,\n expense_id: int,\n ):\n \"\"\" Delete existing expense by id\n \"\"\"\n print(\"ID: \", expense_id)\n expense = db.query(models.Expense).filter(\n models.Expense.id == expense_id\n ).first()\n if not expense:\n # TODO: Exception\n print(\"[INFO]: Not found!\")\n return None\n db.delete(expense)\n db.commit()\n return expense\n\n # @staticmethod\n # def remove_expense_by_category(\n # db: Session,\n # category_name: str,\n # ):\n # \"\"\" Delete existing expense by category\n # \"\"\"\n # # TODO: Implement filtering by another class attribute\n","sub_path":"app/db/crud/expenses.py","file_name":"expenses.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"511959116","text":"import torch\nfrom pytorch_transformers import RobertaModel, RobertaTokenizer, RobertaForMaskedLM\nimport numpy as np\nfrom copy import deepcopy\nimport re\nimport pandas as pd\n\n\n# OPTIONAL: if you want to have more information on what's happening, activate the logger as follows\nimport logging\nlogging.basicConfig(level=logging.INFO)\n\n\nuse_cuda = torch.cuda.is_available()\ndevice = torch.device('cuda:0' if use_cuda else 'cpu')\n\npath_to_wsc = '../data/wsc_data/enhanced.tense.random.role.syn.voice.scramble.freqnoun.tsv'\nwsc_datapoints = pd.read_csv(path_to_wsc, sep='\\t')\n\ndef find_sub_list(sl,l):\n sl = [item for item in sl]\n l = [item for item in l]\n results=[]\n sll=len(sl)\n for ind in (i for i,e in enumerate(l) if e==sl[0]):\n if l[ind:ind+sll]==sl:\n results.append((ind,ind+sll))\n return results\n\ndef replace_pronoun(tokenized_text, pronoun_index, tokenized_option):\n tokenized_text = tokenized_text[:pronoun_index] + tokenized_option + tokenized_text[pronoun_index:]\n new_pronoun_index = pronoun_index + len(tokenized_option)\n tokenized_text.pop(new_pronoun_index)\n return tokenized_text\n\n# Load pre-trained model tokenizer (vocabulary)\ntokenizer = RobertaTokenizer.from_pretrained('roberta-large')\n\ncorrect_preds = 0\ncorrect_preds_enhanced = 0\nstability_match = 0\n\nall_preds = 0\n\n# Load pre-trained model (weights)\nmodel = RobertaForMaskedLM.from_pretrained('roberta-large')\nmodel.eval()\n\nfor q_index, dp_split in wsc_datapoints.iterrows():\n if dp_split['text_voice_switch'].replace(' ', '') != '-' and dp_split['text_voice_switch'].replace(' ', ''):\n\n # Tokenized input\n correct_answer = dp_split['correct_answer']\n\n #check for empty\n text = dp_split['text_original'].strip().lower()\n text = re.sub(' +', ' ', text)\n print(text, \" text\")\n\n text_enhanced = dp_split['text_syn'].lower()\n text_enhanced = re.sub(' +', ' ', text_enhanced)\n\n\n tokenized_text = tokenizer.encode(text, add_special_tokens=True)\n tokenized_enhanced_text = tokenizer.encode(text_enhanced, add_special_tokens=True)\n print(tokenized_text, \"tokenized_text\")\n\n tokens_pre_word_piece_A = dp_split['answer_a'].strip().lower()\n tokens_pre_word_piece_B = dp_split['answer_b'].strip().lower()\n\n tokens_pre_word_piece_A_syn = dp_split['answer_a_syn'].strip().lower()\n tokens_pre_word_piece_B_syn = dp_split['answer_b_syn'].strip().lower()\n\n print(tokens_pre_word_piece_A , \" tokens_pre_word_piece_A \")\n print(tokens_pre_word_piece_B , \" tokens_pre_word_piece_B \")\n\n\n pronoun = 'because ' + dp_split['pron'].lower()\n print(pronoun, \"pronoun\")\n pronoun_index_orig = int(dp_split['pron_index'])\n pronoun_index_orig_enhanced = int(dp_split['pron_index_syn'])\n\n tokenized_option_A = tokenizer.encode(tokens_pre_word_piece_A, add_special_tokens=True)[1:-1]\n tokenized_option_B = tokenizer.encode(tokens_pre_word_piece_B, add_special_tokens=True)[1:-1]\n\n tokenized_option_A_syn = tokenizer.encode(tokens_pre_word_piece_A_syn, add_special_tokens=True)[1:-1]\n tokenized_option_B_syn = tokenizer.encode(tokens_pre_word_piece_B_syn, add_special_tokens=True)[1:-1]\n\n tokenized_pronoun = tokenizer.encode(pronoun, add_special_tokens=True)\n print(tokenized_pronoun, \"tokenized_pronoun\")\n\n tokenized_option_A_len_syn = len(tokenized_option_A_syn)\n tokenized_option_B_len_syn = len(tokenized_option_B_syn)\n tokenized_option_A_len = len(tokenized_option_A)\n tokenized_option_B_len = len(tokenized_option_B)\n\n print(tokenized_option_A, \"tokenized_option A\")\n print(tokenized_option_B, \"tokenized_option B\")\n\n print(tokenized_option_A_syn, \"tokenized_option A syn\")\n print(tokenized_option_B_syn, \"tokenized_option B syn\")\n\n matched_pronouns_text = find_sub_list([tokenized_pronoun[-2]], tokenized_text)\n matched_pronouns_enhanced_text = find_sub_list([tokenized_pronoun[-2]], tokenized_enhanced_text)\n\n first_indices_text = np.array([mp[0] for mp in matched_pronouns_text])\n first_indices_text_enhanced = np.array([mp[0] for mp in matched_pronouns_enhanced_text])\n\n print(matched_pronouns_text, \"matched_pronouns_text\")\n print(matched_pronouns_enhanced_text, \"matched_pronouns_text_enhanced\")\n\n correct_idx_text = (np.abs(first_indices_text - pronoun_index_orig)).argmin()\n correct_idx_text_enhanced = (np.abs(first_indices_text_enhanced - pronoun_index_orig_enhanced)).argmin()\n print(correct_idx_text_enhanced, \" correct_idx_text_enhanced\")\n\n pronoun_index_text = matched_pronouns_text[correct_idx_text][0]\n pronoun_index_text_enhanced = matched_pronouns_enhanced_text[correct_idx_text_enhanced][0]\n print(pronoun_index_text_enhanced, \" pronoun_index_text_enhanced\")\n\n tokenized_text_A = replace_pronoun(tokenized_text, pronoun_index_text, tokenized_option_A)\n tokenized_text_B = replace_pronoun(tokenized_text, pronoun_index_text, tokenized_option_B)\n\n tokenized_text_enhanced_A = replace_pronoun(tokenized_enhanced_text, pronoun_index_text_enhanced, tokenized_option_A_syn)\n tokenized_text_enhanced_B = replace_pronoun(tokenized_enhanced_text, pronoun_index_text_enhanced, tokenized_option_B_syn)\n\n print(tokenized_text_A, \"tokenized_text_A\")\n print(tokenized_text_enhanced_A, \"tokenized_text_enhanced_A\")\n\n matched_A_text = find_sub_list(tokenized_option_A, tokenized_text_A)\n matched_B_text = find_sub_list(tokenized_option_B, tokenized_text_B)\n\n matched_A_text_enhanced = find_sub_list(tokenized_option_A_syn, tokenized_text_enhanced_A)\n matched_B_text_enhanced = find_sub_list(tokenized_option_B_syn, tokenized_text_enhanced_B)\n\n print(matched_A_text, \"matched A\")\n print(matched_A_text_enhanced, \"matched A enhanced\")\n\n masked_indices_A_text = [m for m in matched_A_text if m[0] == pronoun_index_text][0]\n masked_indices_A_text_enhanced = [m for m in matched_A_text_enhanced if m[0] == pronoun_index_text_enhanced][0]\n\n masked_indices_B_text = [m for m in matched_B_text if m[0] == pronoun_index_text][0]\n masked_indices_B_text_enhanced = [m for m in matched_B_text_enhanced if m[0] == pronoun_index_text_enhanced][0]\n\n #get index item\n masked_indices_items_A_text = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0],masked_indices_A_text[1] + 1),tokenized_option_A)]\n masked_indices_items_A_text_enhanced = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0], masked_indices_A_text_enhanced[1] +1 ),tokenized_option_A_syn)]\n\n masked_indices_items_B_text = [(index, item) for index, item in\n zip(range(masked_indices_A_text[0], masked_indices_B_text[1] + 1),tokenized_option_B)]\n masked_indices_items_B_text_enhanced = [(index, item) for index, item in\n zip(range(masked_indices_B_text[0], masked_indices_B_text_enhanced[1] + 1),\n tokenized_option_B_syn)]\n\n\n for masked_index in range(masked_indices_A_text[0], masked_indices_A_text[1]):\n tokenized_text_A[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_A, \"tokenized_text A MASKED\")\n\n for masked_index in range(masked_indices_A_text_enhanced[0], masked_indices_A_text_enhanced[1]):\n tokenized_text_enhanced_A[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_enhanced_A, \"tokenized_enchanced_text A MASKED\")\n\n for masked_index in range(masked_indices_B_text[0], masked_indices_B_text[1]):\n tokenized_text_B[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_B, \"tokenized_text B MASKED\")\n\n for masked_index in range(masked_indices_B_text_enhanced[0], masked_indices_B_text_enhanced[1]):\n tokenized_text_enhanced_B[masked_index] = tokenizer.encode('')[0]\n print(tokenized_text_enhanced_B, \"tokenized_enchanced_text B MASKED\")\n\n\n # Convert token to vocabulary indices\n indexed_tokens_A = tokenized_text_A #tokenizer.encode(' '.join(tokenized_text_A), add_special_tokens=True)\n indexed_tokens_B = tokenized_text_B #tokenizer.encode(' '.join(tokenized_text_B), add_special_tokens=True)\n\n #enhanced\n indexed_tokens_A_enhanced = tokenized_text_enhanced_A #tokenizer.encode(' '.join(tokenized_text_enhanced_A), add_special_tokens=True)\n indexed_tokens_B_enhanced = tokenized_text_enhanced_B #tokenizer.encode(' '.join(tokenized_text_enhanced_B), add_special_tokens=True)\n\n\n # Convert inputs to PyTorch tensors\n tokens_tensor_A = torch.tensor([indexed_tokens_A])\n tokens_tensor_B = torch.tensor([indexed_tokens_B])\n\n #enhanced\n tokens_tensor_A_enhanced = torch.tensor([indexed_tokens_A_enhanced])\n tokens_tensor_B_enhanced = torch.tensor([indexed_tokens_B_enhanced])\n\n\n # If you have a GPU, put everything on cuda\n tokens_tensor_A = tokens_tensor_A.to(device=device)\n tokens_tensor_B = tokens_tensor_B.to(device=device)\n\n\n model.to(device=device)\n\n # Predict all tokens\n total_logprobs_A = 0\n total_logprobs_B = 0\n\n total_logprobs_A_enhanced = 0\n total_logprobs_B_enhanced = 0\n\n with torch.no_grad():\n probs_A = model(tokens_tensor_A)#, segments_tensors_A) #, masked_lm_labels = masked_lm_labels_A)\n probs_B = model(tokens_tensor_B)#, segments_tensors_B) #, masked_lm_labels = masked_lm_labels_B)\n\n probs_A_enhanced = model(tokens_tensor_A_enhanced) # , segments_tensors_A) #, masked_lm_labels = masked_lm_labels_A)\n probs_B_enhanced = model(tokens_tensor_B_enhanced) # , segments_tensors_B) #, masked_lm_labels = masked_lm_labels_B)\n\n logprobs_A = torch.nn.functional.log_softmax(probs_A[0], dim=-1)\n logprobs_B = torch.nn.functional.log_softmax(probs_B[0], dim=-1)\n print(logprobs_A.shape, \"logprobs_A\")\n\n logprobs_A_enhanced = torch.nn.functional.log_softmax(probs_A_enhanced[0], dim=-1)\n logprobs_B_enhanced = torch.nn.functional.log_softmax(probs_B_enhanced[0], dim=-1)\n\n print(\"-----------A---------------\")\n\n for index_item in masked_indices_items_A_text:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n #print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_A += logprobs_A[0,index,item].item()\n\n for index_item in masked_indices_items_A_text_enhanced:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n # print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_A_enhanced += logprobs_A_enhanced[0, index, item].item()\n\n print(\"-----------B---------------\")\n\n for index_item in masked_indices_items_B_text:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n #print(probs_A[0, index, item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_B += logprobs_B[0,index,item].item()\n\n for index_item in masked_indices_items_B_text_enhanced:\n index, item = index_item\n print(index, tokenizer.decode(item), \" : index, item\")\n # print(probs_A[0,index,item].item(), \" : probs_A[0,index,item].item()\")\n total_logprobs_B_enhanced += logprobs_B_enhanced[0, index, item].item()\n\n\n print(total_logprobs_A / tokenized_option_A_len , \" total_probs_A / tokenized_option_A_len\")\n print(total_logprobs_B / tokenized_option_B_len , \" total_probs_B / tokenized_option_B_len\")\n print(correct_answer.strip().strip('.').replace(' ', ''), \" correct_answer\")\n\n print(total_logprobs_A_enhanced / tokenized_option_A_len, \" total_probs_A / tokenized_option_A_len\")\n print(total_logprobs_B_enhanced / tokenized_option_B_len, \" total_probs_B / tokenized_option_B_len\")\n print(correct_answer.strip().strip('.').replace(' ', ''), \" correct_answer\")\n\n max_index = np.argmax([total_logprobs_A / tokenized_option_A_len, total_logprobs_B / tokenized_option_B_len ])\n max_index_enhanced = np.argmax([total_logprobs_A_enhanced / tokenized_option_A_len, total_logprobs_B_enhanced\n / tokenized_option_B_len ])\n\n prediction = \"A\" if max_index == 0 else \"B\"\n prediction_enhanced = \"A\" if max_index_enhanced == 0 else \"B\"\n\n print(prediction, \" prediction\")\n print(prediction_enhanced, \" prediction enhanced\")\n\n if prediction == correct_answer.strip().strip('.').replace(' ', ''):\n correct_preds += 1\n if prediction_enhanced == correct_answer .strip().strip('.').replace(' ', ''):\n correct_preds_enhanced += 1\n if prediction_enhanced == prediction:\n stability_match += 1\n\n all_preds += 1\n print(\"#############################################################################\")\n else:\n continue\n\naccuracy = correct_preds/all_preds\nprint(all_preds, \" : all_preds\")\nprint(correct_preds, \" : correct_preds\")\nprint(accuracy, \" : accuracy\")\n\naccuracy_enhanced = correct_preds_enhanced/all_preds\nprint(all_preds, \" : all_preds\")\nprint(correct_preds_enhanced, \" : correct_preds enhanced\")\nprint(accuracy_enhanced, \" : accuracy_enhancedy\")\n\nprint(stability_match, \": stability_match\")\nprint(stability_match / all_preds , \": stability_match %\")","sub_path":"wsc/run_synonyms_roberta.py","file_name":"run_synonyms_roberta.py","file_ext":"py","file_size_in_byte":14063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"305407669","text":"from __future__ import division\nimport numpy as np\n\nfrom numpy import pi, sqrt, exp, power, log, log10\nfrom scipy.interpolate import interp1d\nfrom scipy.special import erf, lambertw\nfrom scipy.optimize import brentq\n\n#########################################\n\n\ndef interp_fn(array):\n \"\"\"\n An interpolator for log-arrays spanning many orders of magnitude.\n\n Parameters\n ----------\n array : An array of shape (N, 2) from which to interpolate.\n \"\"\"\n\n array[array < 1.e-300] = 1.e-300 # regularizing small numbers\n\n def fn(x): return 10**interp1d(log10(array[:, 0]),\n log10(array[:, 1]), fill_value='extrapolate')(log10(x))\n\n return fn\n\n\ndef zeros(fn, arr, *args):\n \"\"\"\n Find where a function crosses 0. Returns the zeroes of the function.\n\n Parameters\n ----------\n fn : function\n arr : array of arguments for function\n *args : any other arguments the function may have\n \"\"\"\n\n # the reduced function, with only the argument to be solved for (all other arguments fixed):\n def fn_reduced(array): return fn(array, *args)\n\n # the array of values of the function:\n fn_arr = fn_reduced(arr)\n\n # looking where the function changes sign...\n sign_change_arr = np.where(np.logical_or((fn_arr[:-1] < 0.) * (fn_arr[1:] > 0.),\n (fn_arr[:-1] > 0.) * (fn_arr[1:] < 0.))\n )[0]\n\n # or, just in case, where it is exactly 0!\n exact_zeros_arr = np.where(fn_arr == 0.)[0]\n\n # defining the array of 0-crossings:\n cross_arr = []\n\n # first, interpolating between the sign changes\n if len(sign_change_arr) > 0:\n for i in range(len(sign_change_arr)):\n cross_arr.append(\n brentq(fn_reduced, arr[sign_change_arr[i]],\n arr[sign_change_arr[i] + 1])\n )\n\n # and then adding those places where it is exactly 0\n if len(exact_zeros_arr) > 0:\n for i in range(len(exact_zeros_arr)):\n cross_arr.append(arr[exact_zeros_arr[i]])\n\n # sorting the crossings in increasing order:\n cross_arr = np.sort(np.array(cross_arr))\n\n return cross_arr\n\n\ndef treat_as_arr(arg):\n \"\"\"\n A routine to cleverly return scalars as (temporary and fake) arrays. True arrays are returned unharmed. Thanks to Chen!\n \"\"\"\n\n arr = np.asarray(arg)\n is_scalar = False\n\n # making sure scalars are treated properly\n if arr.ndim == 0: # it is really a scalar!\n arr = arr[None] # turning scalar into temporary fake array\n is_scalar = True # keeping track of its scalar nature\n\n return arr, is_scalar\n\n\ndef load_dct(dct, key):\n \"\"\"Used to load and determine if dict has a key\n\n :param dct: the dictionary to be interrogated\n :param key: the key to be tried\n\n \"\"\"\n\n try:\n res = dct[key]\n is_success = True\n except KeyError:\n res = None\n is_success = False\n return res, is_success\n\n\ndef scientific(val, output='string'):\n \"\"\"Convert a number to the scientific form\n\n :param val: number(s) to be converted\n :param output: LaTeX \"string\" form or \"number\" form. (Default: 'string')\n\n \"\"\"\n\n val, is_scalar = treat_as_arr(val)\n exponent, factor = [], []\n string = []\n\n for vali in val:\n expi = int(np.log10(vali))\n faci = vali / 10**expi\n # save it\n exponent.append(expi)\n factor.append(faci)\n if round(faci) == 1.:\n string.append(r\"$10^{{{:.0f}}}$\".format(expi))\n else:\n string.append(\n r\"${{{:.0f}}} \\times 10^{{{:.0f}}}$\".format(faci, expi))\n exponent = np.array(exponent)\n factor = np.array(factor)\n string = np.array(string)\n\n if is_scalar:\n exponent = np.squeeze(exponent)\n factor = np.squeeze(factor)\n string = np.squeeze(string)\n if output == 'string':\n res = string\n elif output == 'number':\n res = (factor, exponent)\n return res\n","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"64434099","text":"from __future__ import absolute_import\n\nimport logging\nimport unittest\n\nimport tests\nfrom sanskrit_data.db import in_memory\nfrom sanskrit_data.schema.common import JsonObject\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(levelname)s: %(asctime)s {%(filename)s:%(lineno)d}: %(message)s \"\n)\n\nclass TestDBRoundTrip(unittest.TestCase):\n\n def setUp(self):\n self.test_db = in_memory.InMemoryDb(db_name_frontend=\"dummy\")\n\n def tearDown(self):\n pass\n\n def test_update_doc(self):\n doc = JsonObject()\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n updated_doc[\"xyz\"] = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(updated_doc)\n logging.debug(updated_doc)\n self.assertNotEqual(updated_doc, None)\n self.assertEqual(\"xyz\" in updated_doc, True)\n updated_doc = self.test_db.find_by_id(updated_doc[\"_id\"])\n self.assertNotEqual(updated_doc, None)\n\n\n def test_delete_doc_find_by_id(self):\n doc = JsonObject()\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n doc_id = updated_doc[\"_id\"]\n self.test_db.delete_doc(doc_id)\n self.assertEqual(self.test_db.find_by_id(doc_id), None)\n\n\n def test_find(self):\n doc = JsonObject()\n doc.xyz = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n found_doc = next(self.test_db.find(find_filter={\"xyz\": \"xyzvalue\"}))\n self.assertTrue(JsonObject.make_from_dict(updated_doc).equals_ignore_id(JsonObject.make_from_dict(found_doc)))\n\n def test_find_one(self):\n doc = JsonObject()\n doc.xyz = \"xyzvalue\"\n updated_doc = self.test_db.update_doc(doc.to_json_map())\n logging.debug(updated_doc)\n found_doc = self.test_db.find_one(find_filter={\"xyz\": \"xyzvalue\"})\n self.assertTrue(JsonObject.make_from_dict(updated_doc).equals_ignore_id(JsonObject.make_from_dict(found_doc)))\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/db/db_interface_test.py","file_name":"db_interface_test.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411757022","text":"import logging\nimport time\nimport shutil\nimport os\nimport re\nimport hashlib\n\nfrom pedsnetdcc.db import StatementSet, Statement, StatementList\nfrom pedsnetdcc.dict_logging import secs_since\nfrom pedsnetdcc.schema import (primary_schema)\nfrom pedsnetdcc.utils import (check_stmt_err, check_stmt_data, combine_dicts,\n get_conn_info_dict, vacuum, stock_metadata)\nfrom sh import Rscript\n\nlogger = logging.getLogger(__name__)\nNAME_LIMIT = 30\nIDX_OBS_LIKE_TABLE_SQL = 'create index {0} on {1}.observation_derivation_recover ({2})'\nFK_OBS_LIKE_TABLE_SQL = 'alter table {0}.observation_derivation_recover add constraint {1} foreign key ({2}) references {3}({4})'\nGRANT_OBS_LIKE_TABLE_SQL = 'grant select on table {0}.observation_derivation_recover to {1}'\nDROP_PK_CONSTRAINT_SQL = \"\"\"alter table {0}.observation_derivation_recover drop constraint if exists xpk_observation_derivation_recover;\n alter table {0}.observation_derivation_recover drop constraint if exists observation_derivation_recover_pkey;\"\"\"\nDROP_NULL_SQL = 'alter table {0}.observation_derivation_recover alter column observation_id drop not null;'\nADD_SITE_SQL = \"\"\"UPDATE {0}.observation_derivation_recover SET site = '{1}';\"\"\"\nADD_DCC_SITE_SQL = \"\"\"UPDATE {0}.observation_derivation_recover o SET site=p.site \n FROM (select person_id, site from {0}.person)p WHERE o.person_id = p.person_id;\"\"\"\nRENAME_SQL = \"\"\"ALTER TABLE IF EXISTS {0}.observation_derivation_recover_misc\n RENAME TO observation_derivation_recover;\"\"\"\n\n\ndef _fill_concept_names(conn_str, schema):\n fill_concept_names_sql = \"\"\"UPDATE {0}.observation_derivation_recover zs\n SET observation_concept_name=v.observation_concept_name,\n observation_type_concept_name=v.observation_type_concept_name, \n qualifier_concept_name=v.qualifier_concept_name, \n unit_concept_name=v.unit_concept_name, \n value_as_concept_name=v.value_as_concept_name\n FROM ( SELECT\n z.observation_id AS observation_id,\n v1.concept_name AS observation_concept_name, \n v3.concept_name AS observation_type_concept_name, \n v4.concept_name AS qualifier_concept_name, \n v5.concept_name AS unit_concept_name,\n v6.concept_name AS value_as_concept_name\n FROM {0}.observation_derivation_recover AS z\n LEFT JOIN vocabulary.concept AS v1 ON z.observation_concept_id = v1.concept_id\n LEFT JOIN vocabulary.concept AS v3 ON z.observation_type_concept_id = v3.concept_id\n LEFT JOIN vocabulary.concept AS v4 ON z.qualifier_concept_id = v4.concept_id\n LEFT JOIN vocabulary.concept AS v5 ON z.unit_concept_id = v5.concept_id\n LEFT JOIN vocabulary.concept AS v6 ON z.value_as_concept_id = v6.concept_id\n ) v\n WHERE zs.observation_id = v.observation_id\"\"\"\n\n fill_concept_names_msg = \"adding concept names\"\n\n # Add concept names\n add_observation_concept_stmt = Statement(fill_concept_names_sql.format(schema), fill_concept_names_msg)\n\n # Execute the add concept names statement and ensure it didn't error\n add_observation_concept_stmt.execute(conn_str)\n check_stmt_err(add_observation_concept_stmt, 'add concept names')\n\n # If reached without error, then success!\n return True\n\n\ndef _fill_age_in_months(conn_str, schema):\n fill_add_age_in_months_sql = \"\"\"\n create or replace function {0}.last_month_of_interval(timestamp, timestamp)\n returns timestamp strict immutable language sql as $$\n select $1 + interval '1 year' * extract(years from age($2, $1)) + interval '1 month' * extract(months from age($2, $1))\n $$;\n comment on function {0}.last_month_of_interval(timestamp, timestamp) is\n 'Return the timestamp of the last month of the interval between two timestamps';\n\n create or replace function {0}.month_after_last_month_of_interval(timestamp, timestamp)\n returns timestamp strict immutable language sql as $$\n select $1 + interval '1 year' * extract(years from age($2, $1)) + interval '1 month' * (extract(months from age($2, $1)) + 1)\n $$;\n comment on function {0}.month_after_last_month_of_interval(timestamp, timestamp) is\n 'Return the timestamp of the month AFTER the last month of the interval between two timestamps';\n\n create or replace function {0}.days_in_last_month_of_interval(timestamp, timestamp)\n returns double precision strict immutable language sql as $$\n select extract(days from {0}.month_after_last_month_of_interval($1, $2) - {0}.last_month_of_interval($1, $2))\n $$;\n comment on function {0}.days_in_last_month_of_interval(timestamp, timestamp) is\n 'Return the number of days in the last month of the interval between two timestamps';\n\n create or replace function {0}.months_in_interval(timestamp, timestamp)\n returns double precision strict immutable language sql as $$\n select extract(years from age($2, $1)) * 12 + extract(months from age($2, $1)) + extract(days from age($2, $1))/{0}.days_in_last_month_of_interval($1, $2)\n $$;\n comment on function {0}.months_in_interval(timestamp, timestamp) is\n 'Return the number of months (double precision) between two timestamps.\n The number of years/months/days is computed by PostgreSQL''s\n extract/date_part function. The fractional months value is\n computed by dividing the extracted number of days by the total\n number of days in the last month overlapping the interval; note\n that this is not a calendar month but, say, the number of days\n between Feb 2, 2001 and Mar 2, 2001. You should be able to obtain\n the original timestamp from the resulting value, albeit with great\n difficulty.';\n\n update {0}.observation_derivation_recover od\n set observation_age_in_months=subquery.observation_age_in_months\n from (select observation_id, \n {0}.months_in_interval(p.birth_datetime, o.observation_datetime::timestamp without time zone) as observation_age_in_months\n from {0}.observation_derivation_recover o\n join {0}.person p on p.person_id = o.person_id) AS subquery\n where od.observation_id=subquery.observation_id;\"\"\"\n\n fill_add_age_in_months_msg = \"adding age in months\"\n\n # Add age in months\n add_age_in_months_stmt = Statement(fill_add_age_in_months_sql.format(schema), fill_add_age_in_months_msg)\n\n # Execute the add concept names statement and ensure it didn't error\n add_age_in_months_stmt.execute(conn_str)\n check_stmt_err(add_age_in_months_stmt, 'add age in months')\n\n # If reached without error, then success!\n return True\n\n\ndef _copy_to_obs_table(conn_str, schema):\n copy_to_sql = \"\"\"INSERT INTO {0}.observation(\n observation_concept_id, observation_date, observation_datetime, \n observation_source_concept_id, observation_source_value, \n observation_type_concept_id, qualifier_concept_id, qualifier_source_value, \n unit_concept_id, unit_source_value, value_as_concept_id, value_as_number, \n value_as_string, observation_age_in_months, observation_concept_name, \n observation_source_concept_name, observation_type_concept_name, \n qualifier_concept_name, unit_concept_name, value_as_concept_name, site, \n observation_id, site_id, provider_id, visit_occurrence_id, person_id\n )\n (select observation_concept_id, observation_date, observation_datetime, \n observation_source_concept_id, observation_source_value, \n observation_type_concept_id, qualifier_concept_id, qualifier_source_value, \n unit_concept_id, unit_source_value, value_as_concept_id, value_as_number, \n value_as_string, observation_age_in_months, observation_concept_name, \n observation_source_concept_name, observation_type_concept_name, \n qualifier_concept_name, unit_concept_name, value_as_concept_name, site, \n observation_id, site_id, provider_id, visit_occurrence_id, person_id\n from {0}.observation_derivation_recover) ON CONFLICT DO NOTHING\"\"\"\n\n copy_to_msg = \"copying {0} to observation\"\n\n # Insert observations into observation table\n copy_to_stmt = Statement(copy_to_sql.format(schema), copy_to_msg)\n\n # Execute the insert observations statement and ensure it didn't error\n copy_to_stmt.execute(conn_str)\n check_stmt_err(copy_to_stmt, 'insert observations')\n\n # If reached without error, then success!\n return True\n\n\ndef _create_argos_file(config_path, config_file, schema, password, conn_info_dict):\n with open(os.path.join(config_path, config_file), 'wb') as out_config:\n out_config.write('{' + os.linesep)\n out_config.write('\"src_name\": \"Postgres\",' + os.linesep)\n out_config.write('\"src_args\": {' + os.linesep)\n out_config.write('\"host\": \"' + conn_info_dict.get('host') + '\",' + os.linesep)\n out_config.write('\"port\": 5432,' + os.linesep)\n out_config.write('\"dbname\": \"' + conn_info_dict.get('dbname') + '\",' + os.linesep)\n out_config.write('\"user\": \"' + conn_info_dict.get('user') + '\",' + os.linesep)\n out_config.write('\"password\": \"' + password + '\",' + os.linesep)\n out_config.write('\"bigint\": \"integer\",' + os.linesep)\n out_config.write('\"options\": \"-c search_path=' + schema + ',vocabulary\"' + os.linesep)\n out_config.write('}' + os.linesep)\n out_config.write('}' + os.linesep)\n\n\ndef _fix_site_info(file_path, site, schema):\n try:\n with open(os.path.join(file_path, 'site', 'site_info.R'), 'r') as site_file:\n file_data = site_file.read()\n file_data = file_data.replace('', site)\n file_data = file_data.replace('', schema)\n with open(os.path.join(file_path, 'site', 'site_info.R'), 'w') as site_file:\n site_file.write(file_data)\n except:\n # this query package may not have this file\n return False\n\n return True\n\n\ndef _fix_run(file_path, site):\n try:\n with open(os.path.join(file_path, 'site', 'run.R'), 'r') as site_file:\n file_data = site_file.read()\n file_data = file_data.replace('', site)\n with open(os.path.join(file_path, 'site', 'run.R'), 'w') as site_file:\n site_file.write(file_data)\n except:\n # this query package may not have this file\n return False\n\n return True\n\n\ndef _make_index_name(column_name):\n \"\"\"\n Create an index name for a given table/column combination with\n a NAME_LIMIT-character (Oracle) limit. The table/column combination\n `provider.gender_source_concept_name` results in the index name\n `pro_gscn_ae1fd5b22b92397ca9_ix`. We opt for a not particularly\n human-readable name in order to avoid collisions, which are all too\n possible with columns like provider.gender_source_concept_name and\n person.gender_source_concept_name.\n :param str table_name:\n :param str column_name:\n :rtype: str\n \"\"\"\n table_name = 'recover_derivation'\n table_abbrev = \"obs_\" + table_name[:3]\n column_abbrev = ''.join([x[0] for x in column_name.split('_')])\n md5 = hashlib.md5(\n '{}.{}'.format(table_name, column_name).encode('utf-8')). \\\n hexdigest()\n hashlen = NAME_LIMIT - (len(table_abbrev) + len(column_abbrev) +\n 3 * len('_') + len('ix'))\n return '_'.join([table_abbrev, column_abbrev, md5[:hashlen], 'ix'])\n\n\ndef run_r_obs_recover(conn_str, site, password, search_path, model_version, id_name, copy,\n limit=False, owner='loading_user'):\n \"\"\"Run an R script.\n\n * Create argos file\n * Run R Script\n\n :param str conn_str: database connection string\n :param str site: site to run script for\n :param str password: user's password\n :param str search_path: PostgreSQL schema search path\n :param str model_version: pedsnet model version, e.g. 2.3.0\n :param str id_name: name of the id (ex. dcc or onco)\n :param bool copy: if True, copy results to output directory\n :param bool limit: if True, limit permissions to owner\n :param str owner: owner of the to grant permissions to\n :returns: True if the function succeeds\n :rtype: bool\n :raises DatabaseError: if any of the statement executions cause errors\n \"\"\"\n\n package = 'observation_derivation_recover'\n config_file = site + \"_\" + package + \"_argos_temp.json\";\n conn_info_dict = get_conn_info_dict(conn_str)\n\n # Log start of the function and set the starting time.\n log_dict = combine_dicts({'site': site, },\n conn_info_dict)\n logger.info(combine_dicts({'msg': 'starting R Script'},\n log_dict))\n start_time = time.time()\n logger_msg = 'observation_derivation_recover'\n schema = primary_schema(search_path)\n\n if password == None:\n pass_match = re.search(r\"password=(\\S*)\", conn_str)\n password = pass_match.group(1)\n\n source_path = os.path.join(os.sep, 'app', package)\n dest_path = os.path.join(source_path, site)\n # delete any old versions\n if os.path.isdir(dest_path):\n shutil.rmtree(dest_path)\n # copy base files to site specific\n shutil.copytree(source_path, dest_path)\n # create the Argos congig file\n _create_argos_file(dest_path, config_file, schema, password, conn_info_dict)\n # modify site_info and run.R to add actual site\n _fix_site_info(dest_path, site, schema)\n _fix_run(dest_path, site)\n\n query_path = os.path.join(os.sep, 'app', package, site, 'site', 'run.R')\n # Run R script\n Rscript(query_path, '--verbose=1', _cwd='/app', _fg=True)\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished R Script',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n stmts = StatementSet()\n\n # Drop primary key.\n stmts.clear()\n drop_pk_stmt = Statement(DROP_PK_CONSTRAINT_SQL.format(schema))\n stmts.add(drop_pk_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'drop pk failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # Add drop null statement.\n stmts.clear()\n drop_stmt = Statement(DROP_NULL_SQL.format(schema))\n stmts.add(drop_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'drop null failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # Add site statement.\n stmts.clear()\n if site == 'dcc':\n add_stmt = Statement(ADD_DCC_SITE_SQL.format(schema))\n else:\n add_stmt = Statement(ADD_SITE_SQL.format(schema, site))\n stmts.add(add_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, logger_msg.format('Run'))\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'add site failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n\n # add observation_ids\n okay = _add_observation_ids(conn_str, site, search_path, model_version, id_name)\n if not okay:\n return False\n\n # Add the concept_names\n logger.info({'msg': 'add concept names'})\n okay = _fill_concept_names(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'concept names added'})\n\n # Add age in months\n logger.info({'msg': 'add age in months'})\n okay = _fill_age_in_months(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'age in months added'})\n\n # Add indexes (same as observation)\n stmts.clear()\n logger.info({'msg': 'adding indexes'})\n col_index = ('observation_concept_id', 'observation_date', 'person_id',\n 'visit_occurrence_id', 'observation_age_in_months', 'site',)\n\n for col in col_index:\n idx_name = _make_index_name(col)\n idx_stmt = Statement(IDX_OBS_LIKE_TABLE_SQL.format(idx_name, schema, col))\n stmts.add(idx_stmt)\n\n # Execute the statements in parallel.\n stmts.parallel_execute(conn_str)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'adding indexes failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'indexes added'})\n\n # Add foreign keys (same as observation)\n stmts.clear()\n logger.info({'msg': 'adding foreign keys'})\n col_fk = ('observation_concept_id', 'person_id', 'provider_id',\n 'qualifier_concept_id', 'observation_type_concept_id',\n 'unit_concept_id', 'value_as_concept_id',\n 'visit_occurrence_id',)\n\n for fk in col_fk:\n fk_len = fk.count('_')\n if \"concept_id\" in fk:\n base_name = '_'.join(fk.split('_')[:fk_len - 1])\n ref_table = \"vocabulary.concept\"\n ref_col = \"concept_id\"\n else:\n base_name = ''.join(fk.split('_')[:1])\n ref_table = '_'.join(fk.split('_')[:fk_len])\n ref_col = fk\n fk_name = \"fk_obs_\" + base_name + \"_recover\"\n fk_stmt = Statement(FK_OBS_LIKE_TABLE_SQL.format(schema,\n fk_name, fk, ref_table,\n ref_col))\n stmts.add(fk_stmt)\n\n # Execute the statements in parallel.\n stmts.parallel_execute(conn_str)\n\n # Execute statements and check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'adding foreign keys failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'foreign keys added'})\n\n # Copy to the observation table\n if copy:\n logger.info({'msg': 'copy to observation'})\n okay = _copy_to_obs_table(conn_str, schema)\n if not okay:\n return False\n logger.info({'msg': 'copied to observation'})\n\n # Set permissions\n stmts.clear()\n logger.info({'msg': 'setting permissions'})\n if limit:\n users = (owner,)\n else:\n users = ('peds_staff', 'dcc_analytics')\n\n for usr in users:\n grant_stmt = Statement(GRANT_OBS_LIKE_TABLE_SQL.format(schema, usr))\n stmts.add(grant_stmt)\n\n # Check for any errors and raise exception if they are found.\n for stmt in stmts:\n try:\n stmt.execute(conn_str)\n check_stmt_err(stmt, 'Observation Derivation Recover')\n except:\n logger.error(combine_dicts({'msg': 'Fatal error',\n 'sql': stmt.sql,\n 'err': str(stmt.err)}, log_dict))\n logger.info(combine_dicts({'msg': 'granting permissions failed',\n 'elapsed': secs_since(start_time)},\n log_dict))\n raise\n logger.info({'msg': 'permissions set'})\n\n # Vacuum analyze tables for piney freshness.\n logger.info({'msg': 'begin vacuum'})\n vacuum(conn_str, model_version, analyze=True, tables=['observation_derivation_recover'])\n logger.info({'msg': 'vacuum finished'})\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished Observation Derivation Recover',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n # If reached without error, then success!\n return True\n\n\ndef _clear_fake_ids(conn_str, schema):\n # Clear \"fake\" ids\n fake_id_sql = \"update {0}.observation_derivation_covid set observation_id = NULL\"\n fake_id_msg = \"clearing 'fake' ids\"\n\n # Clear Ids\n logger.info({'msg': 'begin clearing \"fake\" ids'})\n fake_id_stmt = Statement(fake_id_sql.format(schema),\n fake_id_msg)\n\n # Execute the clear \"fake\" ids statement and ensure it didn't error\n fake_id_stmt.execute(conn_str)\n check_stmt_err(fake_id_stmt, 'clear \"fake\" ids')\n logger.info({'msg': '\"fake ids cleared'})\n\n # If reached without error, then success!\n return True\n\n\ndef _add_observation_ids(conn_str, site, search_path, model_version, id_name):\n \"\"\"Add observation ids for the derivation table\n\n * Find how many ids needed\n * Update observation_id with new value\n * Create sequence\n * Set sequence starting number\n * Assign observation ids\n * Make observation_id the primary key\n\n :param str conn_str: database connection string\n :param str site: site for derivation\n :param str search_path: PostgreSQL schema search path\n :param str model_version: pedsnet model version, e.g. 2.3.0\n :param str id_name: name of the id (ex. dcc or onco)\n :returns: True if the function succeeds\n :rtype: bool\n :raises DatabaseError: if any of the statement executions cause errors\n \"\"\"\n\n new_id_count_sql = \"\"\"SELECT COUNT(*)\n FROM {0}.observation_derivation_recover WHERE observation_id IS NULL\"\"\"\n new_id_count_msg = \"counting new IDs needed for observation_derivation_recover\"\n lock_last_id_sql = \"\"\"LOCK {last_id_table_name}\"\"\"\n lock_last_id_msg = \"locking {table_name} last ID tracking table for update\"\n\n update_last_id_sql = \"\"\"UPDATE {last_id_table_name} AS new\n SET last_id = new.last_id + '{new_id_count}'::bigint\n FROM {last_id_table_name} AS old RETURNING old.last_id, new.last_id\"\"\"\n update_last_id_msg = \"updating {table_name} last ID tracking table to reserve new IDs\" # noqa\n create_seq_observation_sql = \"create sequence if not exists {0}.{1}_obs_derivation_recover_seq\"\n create_seq_observation_msg = \"creating observation_derivation_recover sequence\"\n set_seq_number_sql = \"alter sequence {0}.{1}_obs_derivation_recover_seq restart with {2};\"\n set_seq_number_msg = \"setting sequence number\"\n add_observation_ids_sql = \"\"\"update {0}.observation_derivation_recover set observation_id = nextval('{0}.{1}_obs_derivation_recover_seq')\n where observation_id is null\"\"\"\n add_observation_ids_msg = \"adding the observation ids to the observation_derivation_recover table\"\n pk_observation_id_sql = \"alter table {0}.observation_derivation_recover add primary key (observation_id)\"\n pk_observation_id_msg = \"making observation_id the primary key\"\n\n conn_info_dict = get_conn_info_dict(conn_str)\n\n # Log start of the function and set the starting time.\n log_dict = combine_dicts({'site': site, },\n conn_info_dict)\n\n logger = logging.getLogger(__name__)\n\n logger.info(combine_dicts({'msg': 'starting observation_id assignment'},\n log_dict))\n start_time = time.time()\n schema = primary_schema(search_path)\n table_name = 'observation'\n\n # Mapping and last ID table naming conventions.\n last_id_table_name_tmpl = id_name + \"_{table_name}_id\"\n metadata = stock_metadata(model_version)\n\n # Get table object and start to build tpl_vars map, which will be\n # used throughout for formatting SQL statements.\n table = metadata.tables[table_name]\n tpl_vars = {'table_name': table_name}\n tpl_vars['last_id_table_name'] = last_id_table_name_tmpl.format(**tpl_vars)\n\n # Build the statement to count how many new ID mappings are needed.\n new_id_count_stmt = Statement(new_id_count_sql.format(schema), new_id_count_msg)\n\n # Execute the new ID mapping count statement and ensure it didn't\n # error and did return a result.\n new_id_count_stmt.execute(conn_str)\n check_stmt_err(new_id_count_stmt, 'assign observation ids')\n check_stmt_data(new_id_count_stmt, 'assign observation ids')\n\n # Get the actual count of new ID maps needed and log it.\n tpl_vars['new_id_count'] = new_id_count_stmt.data[0][0] + 1\n logger.info({'msg': 'counted new IDs needed', 'table': 'observation_derivation_recover',\n 'count': tpl_vars['new_id_count']})\n\n # Build list of two last id table update statements that need to\n # occur in a single transaction to prevent race conditions.\n update_last_id_stmts = StatementList()\n update_last_id_stmts.append(Statement(\n lock_last_id_sql.format(**tpl_vars),\n lock_last_id_msg.format(**tpl_vars)))\n update_last_id_stmts.append(Statement(\n update_last_id_sql.format(**tpl_vars),\n update_last_id_msg.format(**tpl_vars)))\n\n # Execute last id table update statements and ensure they didn't\n # error and the second one returned results.\n update_last_id_stmts.serial_execute(conn_str, transaction=True)\n\n for stmt in update_last_id_stmts:\n check_stmt_err(stmt, 'assign observation ids')\n check_stmt_data(update_last_id_stmts[1],\n 'assign observation ids')\n\n # Get the old and new last IDs from the second update statement.\n tpl_vars['old_last_id'] = update_last_id_stmts[1].data[0][0]\n tpl_vars['new_last_id'] = update_last_id_stmts[1].data[0][1]\n logger.info({'msg': 'last ID tracking table updated',\n 'table': table_name,\n 'old_last_id': tpl_vars['old_last_id'],\n 'new_last_id': tpl_vars['new_last_id']})\n\n logger.info({'msg': 'begin observation id sequence creation'})\n # Create the observation id sequence (if it doesn't exist)\n observation_seq_stmt = Statement(create_seq_observation_sql.format(schema, site),\n create_seq_observation_msg)\n\n # Execute the create the observation id sequence statement and ensure it didn't error\n observation_seq_stmt.execute(conn_str)\n check_stmt_err(observation_seq_stmt, 'create observation id sequence')\n logger.info({'msg': 'observation id sequence creation complete'})\n\n # Set the sequence number\n logger.info({'msg': 'begin set sequence number'})\n seq_number_set_stmt = Statement(set_seq_number_sql.format(schema, site, (tpl_vars['old_last_id'] + 1)),\n set_seq_number_msg)\n\n # Execute the set the sequence number statement and ensure it didn't error\n seq_number_set_stmt.execute(conn_str)\n check_stmt_err(seq_number_set_stmt, 'set the sequence number')\n logger.info({'msg': 'set sequence number complete'})\n\n # Add the observation ids\n logger.info({'msg': 'begin add observation ids'})\n add_observation_ids_stmt = Statement(add_observation_ids_sql.format(schema, site),\n add_observation_ids_msg)\n\n # Execute the add the observation ids statement and ensure it didn't error\n add_observation_ids_stmt.execute(conn_str)\n check_stmt_err(add_observation_ids_stmt, 'add the observation ids')\n logger.info({'msg': 'add observation ids complete'})\n\n # Make observation Id the primary key\n logger.info({'msg': 'begin add primary key'})\n pk_observation_id_stmt = Statement(pk_observation_id_sql.format(schema),\n pk_observation_id_msg)\n\n # Execute the Make observation Id the primary key statement and ensure it didn't error\n pk_observation_id_stmt.execute(conn_str)\n check_stmt_err(pk_observation_id_stmt, 'make observation Id the primary key')\n logger.info({'msg': 'primary key created'})\n\n # Log end of function.\n logger.info(combine_dicts({'msg': 'finished adding observation ids',\n 'elapsed': secs_since(start_time)}, log_dict))\n\n # If reached without error, then success!\n return True\n","sub_path":"pedsnetdcc/r_obs_recover.py","file_name":"r_obs_recover.py","file_ext":"py","file_size_in_byte":29506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"40906853","text":"# Copyright (C) 2019 The Raphielscape Company LLC.\n#\n# Licensed under the Raphielscape Public License, Version 1.c (the \"License\");\n# you may not use this file except in compliance with the License.\n#\n\"\"\"\nThis module updates the userbot based on chtream revision\n\"\"\"\n\nfrom os import remove, execl\nimport sys\n\nfrom git import Repo\nfrom git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError\n\nfrom userbot import CMD_HELP, bot, HEROKU_MEMEZ, HEROKU_API_KEY, HEROKU_APP_NAME\nfrom userbot.events import register\n\n\nasync def gen_chlog(repo, diff):\n ch_log = ''\n d_form = \"%d/%m/%y\"\n for c in repo.iter_commits(diff):\n ch_log += f'•[{c.committed_datetime.strftime(d_form)}]: {c.summary} <{c.author}>\\n'\n return ch_log\n\n\nasync def is_off_br(br):\n off_br = ['master']\n for k in off_br:\n if k == br:\n return 1\n return\n\n\n@register(outgoing=True, pattern=\"^.chl(?: |$)(.*)\")\nasync def chtream(ch):\n \"For .update command, check if the bot is up to date, update if specified\"\n await ch.edit(\"`Checking for updates, please wait....`\")\n conf = ch.pattern_match.group(1).lower()\n off_repo = 'https://github.com/Hack12R/HardcoreUserbot.git'\n\n try:\n txt = \"`Oops.. Updater cannot continue due to some problems occured`\\n\\n**LOGTRACE:**\\n\"\n repo = Repo()\n except NoSuchPathError as error:\n await ch.edit(f'{txt}\\n`directory {error} is not found`')\n return\n except GitCommandError as error:\n await ch.edit(f'{txt}\\n`Early failure! {error}`')\n return\n except InvalidGitRepositoryError:\n repo = Repo.init()\n await ch.edit(\n \"`Warning: Force-Syncing to the latest stable code from repo.`\\\n \\nI may lose my downloaded files during this update.\"\n )\n origin = repo.create_remote('chtream', off_repo)\n origin.fetch()\n repo.create_head('master', origin.refs.master)\n repo.heads.master.checkout(True)\n\n ac_br = repo.active_branch.name\n if not await is_off_br(ac_br):\n await ch.edit(\n f'**[UPDATER]:**` Looks like you are using your own custom branch ({ac_br}). \\\n in that case, Updater is unable to identify which branch is to be merged. \\\n please checkout to any official branch`')\n return\n\n try:\n repo.create_remote('chtream', off_repo)\n except BaseException:\n pass\n\n ch_rem = repo.remote('chtream')\n ch_rem.fetch(ac_br)\n changelog = await gen_chlog(repo, f'HEAD..chtream/{ac_br}')\n\n if not changelog:\n await ch.edit(f'\\n`WEW Your BOT is` **up-to-date** `with` **{ac_br}**\\n')\n return\n\n if conf != \"w\":\n changelog_str = f'**New UPDATE available for [{ac_br}]:\\n\\nCHANGELOG:**\\n`{changelog}`'\n if len(changelog_str) > 4096:\n await ch.edit(\"`Ooof Changelog is too big, sending it as a file.`\")\n file = open(\"output.txt\", \"w+\")\n file.write(changelog_str)\n file.close()\n await ch.client.send_file(\n ch.chat_id,\n \"output.txt\",\n reply_to=ch.id,\n )\n remove(\"output.txt\")\n else:\n await ch.edit(changelog_str)\n await ch.respond(\n \"`do \\\".update now \\\" to update\\nif using Heroku`\")\n return\n\n await ch.edit('`New update found, updating...`')\n ch_rem.fetch(ac_br)\n await ch.edit('`Successfully Updated!\\n'\n 'Bot is restarting... Wait for a second!`')\n await install_requirements()\n await bot.disconnect()\n # Spin a new instance of bot\n execl(sys.executable, sys.executable, *sys.argv)\n # Shut the existing one down\n exit()\n\n\nCMD_HELP.update({\n 'update':\n \".chl\\\n\\nUsage: Checks if the main userbot repository has any updates and shows a changelog if so.\\\n\\n\\n.update\\\n\\nUsage: Updates your userbot, if there are any updates in the main userbot repository.\"\n})\n","sub_path":"userbot/plugins/changelog.py","file_name":"changelog.py","file_ext":"py","file_size_in_byte":3959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"617801414","text":"from . import tf_record\n\nimport tensorflow as tf\n\nimport os\n\n\ndef classificator_pipeline(tf_records_path, target_size=(128, 128), batch_size=1, io_parallel_calls=1, file_parsing_parallelism=1,\n augmentation_parallelism=1):\n print(\"Reading from \" + tf_records_path)\n\n filenames = tf.data.Dataset.list_files(tf_records_path, shuffle=True).repeat()\n dataset = tf.data.TFRecordDataset(filenames, compression_type='GZIP', num_parallel_reads=io_parallel_calls)\n dataset = dataset.map(map_func=tf_record.ClassificatorTFRecordHandler.parse_tf_record,\n num_parallel_calls=file_parsing_parallelism)\n\n def f(x, y):\n x = tf.cast(x, tf.dtypes.float32)\n x = tf.reshape(x, (1024, 1024, 1))\n x = tf.clip_by_value(x, 0.0, 500.0)\n #x = tf.image.random_brightness(x, 1.)\n #x = tf.image.adjust_gamma(x, 1, 1)\n\n y = tf.one_hot(y, 2)\n return x, y\n\n\n dataset = dataset.map(f, num_parallel_calls=augmentation_parallelism)\n\n # map_and_batch also available but our batch size is < 100\n dataset = dataset.batch(batch_size)\n\n # Reshape\n resize = lambda x, y: (tf.image.resize(x, target_size), y)\n dataset = dataset.map(resize, num_parallel_calls=augmentation_parallelism).prefetch(1)\n\n return dataset\n\n\nif __name__ == '__main__':\n\n #tf.enable_eager_execution()\n tf_records_path = os.path.join(tf_record.TF_RECORDS_PATH, 'classificator_0/*.tfrecords')\n dataset = classificator_pipeline(tf_records_path)\n\n img = iter(dataset)\n img = next(img)\n\n for data in iter(dataset):\n #print(img[0].shape, img[1])\n print(data[1])#, data[0].shape)\n\n import matplotlib.pyplot as plt\n\n print(img[0].shape)\n print(img[1].shape)\n print(img[1])\n print(img[0][0,:,:,0].shape)\n plt.imshow(img[0][0,:,:,0], cmap='Greys_r')\n plt.show()\n","sub_path":"src/classificator/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"612686935","text":"import os\nimport pandas as pd\n\ndef read_results_file(fname):\n df = pd.read_csv(fname)\n return df\n\n\ndef read_offset_dir(dirname):\n list_df = []\n for file in os.listdir(dirname):\n fname = dirname + \"/\" + file\n list_df.append(read_results_file(fname))\n return list_df\n\n\ndef aggregate_data_frames(list_df, groupby_columns, reduced_columns):\n if set(groupby_columns) - set(reduced_columns):\n raise ValueError(\"error in specifiying visualization dataframe columns\")\n total_df = pd.concat(list_df)\n return total_df[reduced_columns].groupby(groupby_columns).mean()\n\n\nlist_df = read_offset_dir(\"../simulation_res/0/\")\ntotaldf = aggregate_data_frames(list_df,[\"buyer\",\"turn\"],[\"buyer\",\"turn\",\"budget\"])\nprint(totaldf)\n\n\n","sub_path":"tests/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"85215634","text":"# 给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。\n\n\nclass Solution:\n def groupAnagrams(self, strs):\n \"\"\"\n :type strs: List[str]\n :rtype: List[List[str]]\n \"\"\"\n dic = {}\n\n for i in strs:\n key = ''.join(sorted(i))\n if key not in dic:\n dic[key] = [i]\n else:\n dic[key].append(i)\n return list(dic.values())\n\n def groupAnagrams1(self, strs):\n from collections import defaultdict\n # defaultdict属于内建函数dict的一个子类,调用工厂函数提供缺失的值\n prime = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]\n lookup = defaultdict(list)\n for string in strs:\n key_val = 1\n for char in string:\n key_val *= prime[ord(char) - ord('a')]\n lookup[key_val].append(string)\n return list(lookup.values())\n\n\ns = Solution()\nprint(s.groupAnagrams([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\nprint(s.groupAnagrams1([\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]))\n","sub_path":"leetcode049_字母异位词分组.py","file_name":"leetcode049_字母异位词分组.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638284928","text":"#!/usr/bin/env python\n\n# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\nimport Jetson.GPIO as GPIO\nimport time\n\n# Pin Definitions\ninput_pin1 = 12 #18 # BCM pin 18, BOARD pin 12\ninput_pin2 = 13 \n\ndef main():\n prev_value1 = None\n prev_value2 = None\n # Pin Setup:\n GPIO.setmode(GPIO.BOARD) # BCM pin-numbering scheme from Raspberry Pi\n GPIO.setup(input_pin1, GPIO.IN) # set pin as an input pin\n GPIO.setup(input_pin2, GPIO.IN)\n print(\"Starting demo now! Press CTRL+C to exit\")\n try:\n while True:\n value1 = GPIO.input(input_pin1)\n if value1 != prev_value1:\n if value1 == GPIO.HIGH:\n value_str1 = \"HIGH\"\n print(\"high\")\n else:\n value_str1 = \"LOW\"\n print(\"low\")\n print(\"Value read from pin {} : {}\".format(input_pin1,\n value_str1))\n prev_value1 = value1\n\n value2 = GPIO.input(input_pin2)\n if value2 != prev_value2:\n if value2 == GPIO.HIGH:\n value_str2 = \"HIGH\"\n print(\"high\")\n else:\n value_str2 = \"LOW\"\n print(\"low\")\n print(\"Value read from pin {} : {}\".format(input_pin2,\n value_str2))\n prev_value2 = value2\n time.sleep(1)\n finally:\n GPIO.cleanup()\n\nif __name__ == '__main__':\n main()\n","sub_path":"simple_input.py","file_name":"simple_input.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"414717766","text":"\n\n'''\nAn Array of integers is given, both +ve and -ve.\nYou need to find the two elements such that their sum is closest to zero.\n\nExample\nnum_list = [1, 4, 45, 6, 10, -1]\npair (1, -1)\n\nLINK:\nhttps://www.geeksforgeeks.org/two-elements-whose-sum-is-closest-to-zero/\n'''\n\n\ndef find_pair_sorting(num_list, n):\n num_list.sort()\n print(num_list)\n abs_sum = 10**9\n l_num = r_num = -1\n\n i = 0\n j = n - 1\n\n while i < j:\n temp_sum = num_list[i] + num_list[j]\n # print(temp_sum, abs_sum)\n if abs(temp_sum) < abs(abs_sum):\n abs_sum = temp_sum\n l_num = num_list[i]\n r_num = num_list[j]\n\n if temp_sum > 0:\n j -= 1\n else:\n i += 1\n return (l_num, r_num)\n\n\n# Driver program to test the functions\ndef main():\n num_list = [1, 4, 45, 6, 10, -1]\n required_sum = 0\n result = find_pair_sorting(num_list, len(num_list))\n if result:\n print(f\"number with sum nearest to zero, number = {result}\")\n else:\n print(\"Array doesn't have two elements with the given sum\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Algorithm/searching/find_pairs_with_sum_closest_to_zero.py","file_name":"find_pairs_with_sum_closest_to_zero.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228484758","text":"import csv \nimport os.path\n\nfrom classes.ice_cream import IceCream\nfrom classes.freezer import Freezer\n\nmy_path = os.path.abspath(os.path.dirname(__file__))\npath = os.path.join(my_path, \"../data/freezer.csv\")\n\n\nclass Interface:\n def __init__(self, name):\n self.name = name\n self.ice_cream = IceCream.all_ice_cream()\n self.ice_cream_freezer = Freezer.all_freezer()\n self.ice_cream_menu()\n\n def ice_cream_menu(self):\n while True:\n user_input = int(input(\"\"\"\n\n 1. Make Batch of Ice cream.\n 2. Place Ice cream in freezer.\n 3. Take Ice cream batch from freezer.\n 4. Check status of Ice cream batches.\n 5. 1 hour time elapse.\n 6. Quit\n\n \"\"\"))\n if user_input == 1:\n self.make_batch()\n elif user_input == 2:\n self.into_freezer()\n elif user_input == 3:\n self.takeout_freezer() \n elif user_input == 4:\n self.Status_ice_cream() \n elif user_input == 5:\n self.time_lapse()\n elif user_input == 6:\n break\n\n def make_batch(self):\n ice_cream_data = {'flavor': 'batch_number'}\n\n ice_cream_data['flavor'] = input(\"\\n\\nWhat flavor of icecream would you like to make?\\n\\n\")\n ice_cream_data['batch_number'] = input(\"\\n\\nWhat batch number is this?\\n\\n\")\n ice_cream_data['status'] = 'watery'\n\n IceCream.make_batch(self,ice_cream_data)\n print('you just created xxxx batch')\n\n def into_freezer(self):\n \n \n # return batches\n with open(path, 'w', newline='') as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames = [\"batch_number\", \"flavor\", \"status\",\"in_freezer\"])\n writer.writeheader()\n batch_number = input('What Batch Number would you like to put into the freezer?')\n if len(self.ice_cream) == 0:\n print(\"Your are out of icecream\")\n for batch in self.ice_cream:\n if batch.batch_number == batch_number:\n self.ice_cream_freezer.append(batch)\n batch_number=batch.batch_number\n flavor=batch.flavor\n status=batch.status\n in_freezer= \"y\"\n writer.writerow({\"batch_number\": batch_number, \"flavor\": flavor, \"status\": status,\"in_freezer\": in_freezer})\n \n # \n # print (f'Batches in the freezer are: {self.freezer_inv}')\n\n \n\n # def time_lapse(self):\n\n \n","sub_path":"classes/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"37295941","text":"import numpy as np\n\n\ndef set_seeds(comm):\n \"\"\"\n This function guaranties different seeds on different processors\n \"\"\"\n if comm is None:\n return\n\n rank = comm.Get_rank()\n size = comm.Get_size()\n maxint = np.iinfo(np.int32).max\n if rank == 0:\n seed = []\n for i in range(size):\n new_seed = np.random.randint(0, high=maxint)\n while new_seed in seed:\n new_seed = np.random.randint(0, high=maxint)\n seed.append(new_seed)\n else:\n seed = None\n\n # Scatter the seeds to the other processes\n seed = comm.scatter(seed, root=0)\n\n # Update the seed\n np.random.seed(seed)\n\n if size > 1:\n # Verify that numpy rand produces different result on the processors\n random_test = np.random.randint(low=0, high=100, size=100)\n sum_all = np.zeros_like(random_test)\n comm.Allreduce(random_test, sum_all)\n if np.allclose(sum_all, size * random_test):\n msg = \"The seeding does not appear to have any effect on Numpy's \"\n msg += \"rand functions!\"\n raise RuntimeError(msg)\n\n\ndef num_processors():\n \"\"\"Return the number of processors.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n num_proc = comm.Get_size()\n except ImportError:\n num_proc = 1\n return num_proc\n\n\ndef mpi_allreduce(msg):\n \"\"\"Wraps the allreduce method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.allreduce(msg)\n except ImportError:\n value = msg\n return value\n\n\ndef mpi_bcast(msg, root=0):\n \"\"\"Wraps the broadcast method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.bcast(msg, root=root)\n except ImportError:\n value = msg\n return value\n\n\ndef mpi_rank():\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n except ImportError:\n rank = 0\n return rank\n\n\ndef mpi_allgather(msg):\n \"\"\"Wraps the allgather method.\"\"\"\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n value = comm.allgather(msg)\n except ImportError:\n value = [msg]\n return value\n\ndef mpi_barrier():\n try:\n from mpi4py import MPI\n comm = MPI.COMM_WORLD\n comm.barrier()\n except ImportError:\n pass\n\n\ndef has_mpi():\n try:\n from mpi4py import MPI\n return True\n except ImportError:\n pass\n return False\n\n\ndef mpi_communicator():\n try:\n from mpi4py import MPI\n return MPI.COMM_WORLD\n except ImportError:\n pass\n return None\n\n\ndef mpi_max():\n try:\n from mpi4py import MPI\n return MPI.MAX\n except ImportError:\n pass\n return None\n\n\ndef mpi_sum():\n try:\n from mpi4py import MPI\n return MPI.SUM\n except ImportError:\n pass\n return None","sub_path":"cemc/mcmc/mpi_tools.py","file_name":"mpi_tools.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"345387175","text":"# encoding: UTF-8\n\nfrom __future__ import division\n\nimport os\nfrom collections import OrderedDict\n\nfrom six import text_type\n\nfrom vnpy.trader.vtConstant import (DIRECTION_LONG, DIRECTION_SHORT,\n OFFSET_OPEN, OFFSET_CLOSE,\n STATUS_ALLTRADED, STATUS_CANCELLED, STATUS_REJECTED)\nfrom vnpy.trader.uiQt import QtWidgets\nfrom vnpy.trader.app.algoTrading.algoTemplate import AlgoTemplate\nfrom vnpy.trader.app.algoTrading.uiAlgoWidget import AlgoWidget, QtWidgets\n\nfrom tdexApi import Tdex\nimport json\n\nREST_HOST = 'https://tl.tdex.com/openapi/v1'\nbase_dir = os.path.join(os.getcwd())\nfilePath = os.path.join(base_dir, 'TDEX_connect.json')\n\nf = file(filePath)\nsetting = json.load(f)\n\napiKey = str(setting['apiKey'])\napiSecret = str(setting['apiSecret'])\n# print(apiKey, apiSecret)\n\noptions = {\n 'apiKey': apiKey,\n 'apiSecret': apiSecret,\n 'url': REST_HOST,\n}\n\ntdex = Tdex(options)\n\nSTATUS_FINISHED = set([STATUS_ALLTRADED, STATUS_CANCELLED, STATUS_REJECTED])\n\n\n########################################################################\nclass StopAlgo(AlgoTemplate):\n \"\"\"停止单算法,也可以用于止损单\"\"\"\n \n templateName = u'STOP 条件委托'\n\n #----------------------------------------------------------------------\n def __init__(self, engine, setting, algoName):\n \"\"\"Constructor\"\"\"\n super(StopAlgo, self).__init__(engine, setting, algoName)\n \n # 参数,强制类型转换,保证从CSV加载的配置正确\n self.vtSymbol = str(setting['vtSymbol']) # 合约代码\n self.direction = text_type(setting['direction']) # 买卖\n self.stopPrice = float(setting['stopPrice']) # 触发价格\n self.totalVolume = float(setting['totalVolume']) # 数量\n self.offset = text_type(setting['offset']) # 开平\n self.priceAdd = float(setting['priceAdd']) # 下单时的超价\n \n self.vtOrderID = '' # 委托号\n self.tradedVolume = 0 # 成交数量\n self.orderStatus = '' # 委托状态\n if self.vtSymbol == 'BTCUSD.TDEX':\n self.vtSymbol = 'XBTUSD.BITMEX'\n self.subscribe(self.vtSymbol)\n self.paramEvent()\n self.varEvent()\n \n #----------------------------------------------------------------------\n def onTick(self, tick):\n \"\"\"\"\"\"\n # 如果已经发出委托,则忽略行情事件\n if self.vtOrderID:\n return\n\n data = {\n 'depth': 5,\n }\n\n depthData = tdex.orderBook(data)\n # 获取行情\n if not depthData or depthData['status'] != 0:\n self.writeLog('获取TDEX行情接口异常')\n print(depthData)\n return\n\n depthData = depthData['data']\n askList = depthData['asks']\n bidList = depthData['bids']\n \n # 如果到达止损位,才触发委托\n if (self.direction == DIRECTION_LONG and \n tick.lastPrice >= self.stopPrice):\n # 计算超价委托价格\n price = self.stopPrice + self.priceAdd\n \n # 避免价格超过涨停价\n # if tick.upperLimit:\n # price = min(price, tick.upperLimit)\n \n # func = self.buy\n # 发出委托\n dataBuy = {\n 'cid': 1,\n 'side': 0,\n 'scale': 20,\n 'volume': int(self.totalVolume),\n 'visible': -1,\n 'price': int(price),\n }\n resBuy = tdex.futuresOpen(dataBuy)\n print(resBuy)\n if resBuy['status'] == 0:\n self.writeLog(u'委托买入%s,数量%s,价格%s' % (self.vtSymbol, str(self.totalVolume), price))\n self.stop()\n else:\n price = self.stopPrice - self.priceAdd\n \n # if tick.lowerLimit:\n # price = max(price, tick.lowerLimit)\n \n # func = self.sell\n dataSell = {\n 'cid': 1,\n 'side': 1,\n 'scale': 20,\n 'volume': int(self.totalVolume),\n 'visible': -1,\n 'price': int(price),\n }\n resSell = tdex.futuresOpen(dataSell)\n print(resSell)\n if resSell['status'] == 0:\n self.writeLog(u'委托卖出%s,数量%s,价格%s' % (self.vtSymbol, str(self.totalVolume), price))\n self.stop()\n # self.vtOrderID = func(self.vtSymbol, price, self.volume, offset=self.offset)\n \n # msg = u'停止单已触发,代码:%s,方向:%s, 价格:%s,数量:%s' %(self.vtSymbol,\n # self.direction,\n # self.stopPrice,\n # self.totalVolume)\n # self.writeLog(msg)\n \n # 更新变量\n self.varEvent() \n \n #----------------------------------------------------------------------\n def onTrade(self, trade):\n \"\"\"\"\"\"\n pass\n \n #----------------------------------------------------------------------\n def onOrder(self, order):\n \"\"\"\"\"\"\n self.tradedVolume = order.tradedVolume\n self.orderStatus = order.status\n \n if self.orderStatus in STATUS_FINISHED:\n self.stop()\n \n self.varEvent()\n \n #----------------------------------------------------------------------\n def onTimer(self):\n \"\"\"\"\"\"\n pass\n \n #----------------------------------------------------------------------\n def onStop(self):\n \"\"\"\"\"\"\n self.writeLog(u'停止算法')\n self.varEvent()\n \n #----------------------------------------------------------------------\n def varEvent(self):\n \"\"\"更新变量\"\"\"\n d = OrderedDict()\n d[u'算法状态'] = self.active\n d[u'委托号'] = self.vtOrderID\n d[u'成交数量'] = self.tradedVolume\n d[u'委托状态'] = self.orderStatus\n d['active'] = self.active\n self.putVarEvent(d)\n \n #----------------------------------------------------------------------\n def paramEvent(self):\n \"\"\"更新参数\"\"\"\n d = OrderedDict()\n if self.vtSymbol == 'XBTUSD.BITMEX':\n self.vtSymbol = 'BTCUSD.TDEX'\n d[u'代码'] = self.vtSymbol\n d[u'方向'] = self.direction\n d[u'触发价格'] = self.stopPrice\n d[u'数量'] = self.totalVolume\n # d[u'开平'] = self.offset\n self.putParamEvent(d)\n\n\n########################################################################\nclass StopWidget(AlgoWidget):\n \"\"\"\"\"\"\n \n #----------------------------------------------------------------------\n def __init__(self, algoEngine, parent=None):\n \"\"\"Constructor\"\"\"\n super(StopWidget, self).__init__(algoEngine, parent)\n \n self.templateName = StopAlgo.templateName\n \n #----------------------------------------------------------------------\n def initAlgoLayout(self):\n \"\"\"\"\"\"\n self.lineSymbol = QtWidgets.QLineEdit()\n \n self.comboDirection = QtWidgets.QComboBox()\n self.comboDirection.addItem(DIRECTION_LONG)\n self.comboDirection.addItem(DIRECTION_SHORT)\n self.comboDirection.setCurrentIndex(0)\n \n self.spinPrice = QtWidgets.QDoubleSpinBox()\n self.spinPrice.setMinimum(0)\n self.spinPrice.setMaximum(1000000000)\n self.spinPrice.setDecimals(8)\n \n self.spinVolume = QtWidgets.QDoubleSpinBox()\n self.spinVolume.setMinimum(0)\n self.spinVolume.setMaximum(1000000000)\n self.spinVolume.setDecimals(6)\n \n self.comboOffset = QtWidgets.QComboBox()\n self.comboOffset.addItems(['', OFFSET_OPEN, OFFSET_CLOSE])\n self.comboOffset.setCurrentIndex(0)\n \n self.spinPriceAdd = QtWidgets.QDoubleSpinBox()\n self.spinPriceAdd.setMinimum(0)\n self.spinPriceAdd.setMaximum(1000000000)\n self.spinPriceAdd.setDecimals(8) \n \n buttonStart = QtWidgets.QPushButton(u'启动')\n buttonStart.clicked.connect(self.addAlgo)\n buttonStart.setMinimumHeight(100)\n \n Label = QtWidgets.QLabel\n \n grid = QtWidgets.QGridLayout()\n grid.addWidget(Label(u'代码'), 0, 0)\n grid.addWidget(self.lineSymbol, 0, 1)\n grid.addWidget(Label(u'方向'), 1, 0)\n grid.addWidget(self.comboDirection, 1, 1)\n grid.addWidget(Label(u'价格'), 2, 0)\n grid.addWidget(self.spinPrice, 2, 1)\n grid.addWidget(Label(u'数量'), 3, 0)\n grid.addWidget(self.spinVolume, 3, 1)\n # grid.addWidget(Label(u'开平'), 4, 0)\n # grid.addWidget(self.comboOffset, 4, 1)\n grid.addWidget(Label(u'超价'), 5, 0)\n grid.addWidget(self.spinPriceAdd, 5, 1) \n \n return grid\n \n #----------------------------------------------------------------------\n def getAlgoSetting(self):\n \"\"\"\"\"\"\n setting = OrderedDict()\n setting['templateName'] = StopAlgo.templateName\n setting['vtSymbol'] = str(self.lineSymbol.text())\n setting['direction'] = text_type(self.comboDirection.currentText())\n setting['stopPrice'] = float(self.spinPrice.value())\n setting['totalVolume'] = float(self.spinVolume.value())\n setting['offset'] = text_type(self.comboOffset.currentText())\n setting['priceAdd'] = float(self.spinPriceAdd.value())\n \n return setting\n \n \n","sub_path":"vnpy/trader/app/algoTrading/algo/stopAlgo.py","file_name":"stopAlgo.py","file_ext":"py","file_size_in_byte":9861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"84154262","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/6/10\n\n@author: chen hangting\n\nthis script transform mat file with cell to npy\n\"\"\"\n\nimport h5py\nimport numpy as np\nimport os\n\nPATHMATROOT=(r'H:\\TUT2017\\rawWaveletL',r'H:\\TUT2017\\rawWaveletR')\nPATHNPYROOT=r'H:\\TUT2017\\rawWavelet'\n\nframeNum=(0,7,16,25,34,43,52,61,70,79,92)\nfilterNum=92\n\n\nfor mode in ('development','evaluation',):\n fileList=os.listdir(os.path.join(PATHMATROOT[0],mode,'audio'))\n for f in fileList:\n print(f)\n PATHREADL=os.path.join(PATHMATROOT[0],mode,'audio',f)\n PATHREADR=os.path.join(PATHMATROOT[1],mode,'audio',f)\n matL=h5py.File(PATHREADL)\n matR=h5py.File(PATHREADR)\n dataL=[matL[e[0]][:] for e in matL['U_2']['signal']]\n dataR=[matR[e[0]][:] for e in matR['U_2']['signal']]\n for s in range(len(frameNum)-1):\n start=frameNum[s]\n end=frameNum[s+1]\n data=[*dataL[start:end],*dataR[start:end]]\n data=np.concatenate(data,axis=0).T\n PATHSAV=os.path.join(PATHNPYROOT,str(s),mode,'audio',f[0:-4])\n np.save(PATHSAV,data)","sub_path":"script/features/rawWavelet/mat2npy.py","file_name":"mat2npy.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264451738","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 19:28:23 2020\n\n@author: masat\n\"\"\"\n\nN = int(input())\ns_list = []\nt_list = []\nfor i in range(N):\n s, t = input().split()\n s_list.append(s)\n t_list.append(int(t))\nX = input()\n\nk = s_list.index(X)\n\ntime = 0\nfor i in range(k+1, N):\n time += t_list[i]\n\nprint(time)\n\n","sub_path":"AtCoder_Python3/dwacon6th/dwacon6th_A_HH1.py","file_name":"dwacon6th_A_HH1.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96720270","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nfrom mip import*\r\n\r\n# lendo dados de entrada\r\ncsv = open(sys.argv[1], \"r\")\r\n\r\nlines = csv.readlines()\r\ndata = lines[0].split(\";\")\r\n\r\nn = int(data[0])\r\nL = int(data[1])\r\nm = int(data[2])\r\n\r\nws = lines[1].split(\";\")\r\nbs = lines[2].split(\";\")\r\n\r\nw = []\r\nb = []\r\n\r\nfor i in range(len(ws)):\r\n w.append(int(ws[i]))\r\n\r\nfor i in range(len(bs)):\r\n b.append(int(bs[i]))\r\n\r\ncsv.close()\r\n\r\n# criando o modelo\r\nmodel = Model(\"Corte Unidimensional\")\r\n\r\n# criando variáveis\r\nx = { (i,j) : model.add_var(var_type = INTEGER) for i in range(m) for j in range(n) }\r\ny = [ model.add_var(var_type = BINARY) for j in range(n) ]\r\n\r\n# criando restrições\r\nfor i in range(m):\r\n model += xsum(x[i,j] for j in range(n)) >= b[i]\r\n\r\nfor j in range(n):\r\n model += xsum(w[i] * x[i,j] for i in range(m)) <= L * y[j]\r\n\r\nfor j in range(1,n):\r\n model += y[j] <= y[j - 1]\r\n\r\n# criando função objetivo\r\nmodel += xsum(y[j] for j in range(n))\r\n\r\n# resolvendo o modelo\r\nmodel.optimize()\r\n\r\n# imprimindo o modelo\r\nprint(\"z = {model.objective_value}\\n\".format(**locals()))\r\nfor (i,j) in x.keys():\r\n if x[i,j].x > 0.1:\r\n value = x[i,j].x\r\n print(\"x({i},{j}) = {value}\\n\".format(**locals()))\r\n","sub_path":"praticas/atividade_05/corte_unidimensional.py","file_name":"corte_unidimensional.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281435758","text":"#!/usr/bin/env python\nimport roslib; roslib.load_manifest('roboint')\nimport rospy\nimport tf\nfrom math import *\nfrom geometry_msgs.msg import Twist, TransformStamped, Point32, PoseWithCovarianceStamped\nfrom sensor_msgs.msg import Range\nfrom nav_msgs.msg import Odometry\nfrom roboint.msg import Motor\nfrom roboint.msg import Inputs\n\n\nclass RoboExplorer:\n\tdef __init__(self):\n\t\trospy.init_node('robo_explorer')\n\n\t\tself.x = 0\n\t\tself.y = 0\n\t\tself.alpha = 0\n\t\tself.last_in = None\n\t\tself.tf_broadcaster = tf.broadcaster.TransformBroadcaster()\n\t\tself.last_time = rospy.Time.now()\n\t\tself.x_last = 0\n\t\tself.y_last = 0\n\t\tself.alpha_last = 0\n\n\t\t# Distance between both wheels in meter (18.55cm)\n\t\tself.wheel_dist = float(rospy.get_param('~wheel_dist', \"0.1855\"))\n\t\t# Size of wheel Diameter in meter (5.15cm) * gear ratio (0.5) = 2.575cm \n\t\tself.wheel_size = float(rospy.get_param('~wheel_size', \"0.02575\"))\n\t\t# Speed to PWM equation gradiant (The m in pwm = speed*m+b)\n\t\tself.speed_gradiant = float(rospy.get_param('~speed_gradiant', \"64.3\"))\n\t\t# Speed to PWM equation constant (The b in pwm = speed*m+b)\n\t\tself.speed_constant = float(rospy.get_param('~speed_constant', \"-1.7\"))\n\n\t\tself.pub_motor = rospy.Publisher(\"ft/set_motor\", Motor, queue_size=16)\n\t\tself.pub_sonar = rospy.Publisher(\"sonar\", Range, queue_size=16)\n\t\tself.pub_odom = rospy.Publisher(\"odom\", Odometry, queue_size=16)\n\t\t\n\t\trospy.Subscriber(\"cmd_vel\", Twist, self.cmdVelReceived)\n\t\trospy.Subscriber(\"ft/get_inputs\", Inputs, self.inputsReceived)\n\t\trospy.Subscriber(\"initialpose\", PoseWithCovarianceStamped, self.posReceived)\n\n\t\trospy.spin()\n\t\n\tdef posReceived(self, msg):\n\t\tself.x = msg.pose.pose.position.x\n\t\tself.y = msg.pose.pose.position.y\n\t\torientation = msg.pose.pose.orientation\n\t\tangles = tf.transformations.euler_from_quaternion([orientation.x, orientation.y, orientation.z, orientation.w])\n\t\tself.alpha = angles[2]\n\n\tdef inputsReceived(self, msg):\n\t\tcurrent_time = rospy.Time.now()\n\n\t\tself.update_odometry(msg, current_time)\n\t\tif (current_time - self.last_time).to_nsec() > 100e6: # send every 100ms\n\t\t\tself.send_odometry(msg, current_time)\n\t\t\tself.send_range(msg, current_time)\n\t\t\tself.last_time = current_time\n\n\tdef update_odometry(self, msg, current_time):\n\t\tin_now = msg.input[:2]\n\t\tif self.last_in is not None:\n\t\t\tin_diff = [abs(a - b) for a, b in zip(in_now, self.last_in)] # get changed inputs\n\t\t\t# fix in_diff from actual motor direction\n\t\t\tif msg.output[1] > 0: # left reverse\n\t\t\t\tin_diff[0] = -in_diff[0]\n\t\t\telif msg.output[0] == 0 and msg.output[1] == 0: # left stop\n\t\t\t\tin_diff[0] = 0\n\t\t\tif msg.output[3] > 0: # right reverse\n\t\t\t\tin_diff[1] = -in_diff[1]\n\t\t\telif msg.output[2] == 0 and msg.output[3] == 0: # right stop\n\t\t\t\tin_diff[1] = 0\n\n\t\t\tdist_dir = (in_diff[1] - in_diff[0]) * self.wheel_size*pi/8 # steps_changed in different direction => m\n\t\t\tdelta_alpha = dist_dir/self.wheel_dist\n\n\t\t\tdist = (in_diff[0] + in_diff[1])/2.0 * self.wheel_size*pi/8 # steps_changed same direction => m\n\n\t\t\tdelta_x = cos(self.alpha + delta_alpha/2)*dist\n\t\t\tdelta_y = sin(self.alpha + delta_alpha/2)*dist\n\n\t\t\tself.alpha += delta_alpha\n\t\t\tif self.alpha > 2*pi:\n\t\t\t\tself.alpha -= 2*pi\n\t\t\telif self.alpha < -2*pi:\n\t\t\t\tself.alpha += 2*pi\n\t\t\tself.x += delta_x\n\t\t\tself.y += delta_y\n\n\t\tself.last_in = in_now\n\n\tdef send_odometry(self, msg, current_time):\n\t\t# speeds\n\t\tdt = (current_time - self.last_time).to_sec()\n\t\tvx = sqrt((self.x - self.x_last)**2 + (self.y - self.y_last)**2) / dt\n\t\tif (msg.output[0]-msg.output[1] + msg.output[2]-msg.output[3]) < 0:\n\t\t\t# moving backward\n\t\t\tvx*=-1\n\t\tvalpha = (self.alpha - self.alpha_last) / dt\n\t\tself.x_last = self.x\n\t\tself.y_last = self.y\n\t\tself.alpha_last = self.alpha\n\n\t\t# since all odometry is 6DOF we'll need a quaternion created from yaw\n\t\todom_quat = tf.transformations.quaternion_from_euler(0, 0, self.alpha)\n\n\t\t# first, we'll publish the transform over tf\n\t\tself.tf_broadcaster.sendTransform((self.x, self.y, 0.0), odom_quat, current_time, \"base_link\", \"odom\")\n\n\t\t# next, we'll publish the odometry message over ROS\n\t\todom = Odometry()\n\t\todom.header.stamp = current_time\n\t\todom.header.frame_id = \"/odom\"\n\n\t\t# set the position\n\t\todom.pose.pose.position.x = self.x\n\t\todom.pose.pose.position.y = self.y\n\t\todom.pose.pose.position.z = 0.0\n\t\todom.pose.pose.orientation.x = odom_quat[0]\n\t\todom.pose.pose.orientation.y = odom_quat[1]\n\t\todom.pose.pose.orientation.z = odom_quat[2]\n\t\todom.pose.pose.orientation.w = odom_quat[3]\n\n\t\t# set the velocity\n\t\todom.child_frame_id = \"base_link\"\n\t\todom.twist.twist.linear.x = vx\n\t\todom.twist.twist.linear.y = 0.0\n\t\todom.twist.twist.angular.z = valpha\n\n\t\t# publish the message\n\t\tself.pub_odom.publish(odom)\n\t\t\n\tdef send_range(self, msg, current_time):\n\t\t# ultra sonic range finder\n\t\tscan = Range()\n\t\tscan.header.stamp = current_time\n\t\tscan.header.frame_id = \"forward_sensor\"\n\t\tscan.radiation_type = 0\n\t\tscan.field_of_view = 60*pi/180\n\t\tscan.min_range = 0.0\n\t\tscan.max_range = 4.0\n\t\tscan.range = msg.d1/100.0\n\t\tself.pub_sonar.publish(scan)\n\n\t# test with rostopic pub -1 cmd_vel geometry_msgs/Twist '[0, 0, 0]' '[0, 0, 0]'\n\tdef cmdVelReceived(self, msg):\n\t\ttrans = msg.linear.x\n\t\trot = msg.angular.z # rad/s\n\n\t\t# handle rotation as offset to speeds\n\t\tspeed_offset = (rot * self.wheel_dist)/2.0 # m/s\n\n\t\t# handle translation\n\t\tspeed_l = 0\n\t\twish_speed_left = trans - speed_offset\n\t\tif abs(wish_speed_left) > 0:\n\t\t\tspeed_l = self.speed_gradiant*abs(wish_speed_left) + self.speed_constant\n\t\t\tif wish_speed_left < 0:\n\t\t\t\tspeed_l*=-1\n\t\tspeed_r = 0\n\t\twish_speed_right = trans + speed_offset\n\t\tif abs(wish_speed_right) > 0:\n\t\t\tspeed_r = self.speed_gradiant*abs(wish_speed_right) + self.speed_constant\n\t\t\tif wish_speed_right < 0:\n\t\t\t\tspeed_r*=-1\n\n\t\t# check limits\n\t\tif speed_l < -7: speed_l = -7\n\t\telif speed_l > 7: speed_l = 7\n\t\tif speed_r < -7: speed_r = -7\n\t\telif speed_r > 7: speed_r = 7\n\n\t\t#print \"Speed wanted: %.2f m/s %.2f rad/s, set: %d %d\" % (trans, rot, round(speed_l), round(speed_r))\n\n\t\toutmsg = Motor()\n\t\toutmsg.num = 0\n\t\toutmsg.speed = round(speed_l)\n\t\tself.pub_motor.publish(outmsg)\n\t\t\n\t\toutmsg = Motor()\n\t\toutmsg.num = 1\n\t\toutmsg.speed = round(speed_r)\n\t\tself.pub_motor.publish(outmsg)\n\nif __name__ == '__main__':\n\tRoboExplorer()\n","sub_path":"scripts/robo_explorer.py","file_name":"robo_explorer.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"44022153","text":"import os\nimport sys\nimport math\nimport operator\nimport collections \n\nN = 3204\nk1 = 1.2\nk2 = 100\nb= 0.75\ndoc_length = collections.OrderedDict()\ninverted_index_dict = {}\nterm_freq_in_each_doc = {}\ndoc_token_info= {}\n\ninverted_list = []\ntokens_in_each_doc = []\nvisited_terms = []\ncacm_rel = []\ntotal_avg_prec = 0\ntotal_reciprocal_rank = 0\nmean_reciprocal_rank = 0\n\n\ndef bm25_intermediate_fn(query,avdl,inverted_index_dict,count,R,rel_docs,doc_token_info,f5):\n global total_avg_prec\n global mean_avg_precision\n global total_reciprocal_rank\n global mean_reciprocal_rank\n \n bm25_score= {}\n bm25_ranked_list = []\n query=query.split()\n visited_terms = []\n for term in query:\n r = 0\n #checking whether the score is already calculated for that term\n if term not in visited_terms:\n visited_terms.append(term)\n #checking whether query term is in the inverted index\n if term in inverted_index_dict.keys():\n values=inverted_index_dict[term]\n n=len(values)\n for item in values:\n #storing the frequency of the term for that doc\n frequency = item[1]\n #checking whether the document is in the list of relevant documents for that query\n if item[0] in rel_docs:\n if term in doc_token_info[item[0]]:\n r+=1\n dl=doc_length[item[0]]\n #calculating the frequency of the term in the query\n query_freq = query.count(term)\n #calculating the BM25 score\n s = calculate_BM25(frequency,dl,query_freq,n,avdl,R,r)\n doc=item[0]\n if doc in bm25_score.keys():\n bm25_score[doc]+=s\n else:\n bm25_score[doc] = s\n\n\n bm25_ranked_list =sorted(bm25_score.items(), key=operator.itemgetter(1), reverse=True)\n\n documents = [x[0] for x in bm25_ranked_list]\n\n precision = {}\n recall = {}\n total_retrieved_docs = 0\n rel = 0\n avg_precision = 0\n sum_precision = 0\n #calculating precision and recall\n for doc in documents:\n total_retrieved_docs+=1\n if doc in rel_docs:\n rel+=1\n if rel ==1 :\n total_reciprocal_rank+=(float(1/total_retrieved_docs))\n precision[doc] = float(rel/total_retrieved_docs)\n sum_precision = sum_precision+float(precision[doc])\n if R == 0:\n recall[doc] = 0.0\n else:\n recall[doc] = float(rel/R)\n else:\n precision[doc] = float(rel/total_retrieved_docs)\n if R==0:\n recall[doc] =0.0\n else:\n recall[doc] = float(rel/R)\n\n if R!=0:\n avg_precision = float(sum_precision/R)\n total_avg_prec = float(total_avg_prec+avg_precision)\n\n #Put count==7 for stemming and 64 for stopping\n if count ==64:\n \n #For stemming divide by 7, for stooping divide by 52\n mean_avg_prec = float(total_avg_prec/52)\n\n mean_reciprocal_rank = float(total_reciprocal_rank/52)\n\n f6 = open(\"F://IR//Project Files//Precision_at_K_BM25_general.txt\",'a+',encoding='utf-8')\n\n #For stemming uncomment this\n #f6 = open(\"F://IR//Project Files//Task3Stemmed//Precision_at_K_BM25_stemmed.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f6 = open(\"F://IR//Project Files//Task3Stopped//Precision_at_K_BM25_stopped.txt\",'a+',encoding='utf-8')\n\n if len(bm25_ranked_list)<100:\n x=len(bm25_ranked_list)\n else:\n x=100\n \n for i in range(x):\n document = str(bm25_ranked_list[i][0])\n if document in rel_docs:\n relevance = \"R\"\n else:\n relevance = \"NR\"\n f5.write('{:10} {:2} {:40} {:5} {:30} {:10} {:40} {:20}'.format(\"\" + str(count), \"Q0\", \"\" + document, \"\" + str(i+1), \"\" + str(bm25_ranked_list[i][1]),\n relevance, \"\" + str(precision[document]), \"\" + str(recall[document])) + '\\n')\n if ((i+1)==5 or (i+1)==20):\n f6.write(\"Precision @ K= \"+str(i+1)+\" for query number : \"+str(count)+\" is : \"+str(precision[document])+\"\\n\")\n\n\n # Put count==7 for stemming and 64 for stopping\n if count ==64:\n f5.write(\"Mean Average Precision (MAP) : \"+str(mean_avg_prec)+\"\\n\")\n f5.write(\"Mean Reciprocal Rank (MRR) : \"+str(mean_reciprocal_rank))\n\n f4=open(\"F://IR//Project Files//Relevant_Docs_for_each_query.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f4=open(\"F://IR//Project Files//Task3Stopped//Relevant_Docs_for_each_stopped_query.txt\",'a+',encoding='utf-8')\n \n #For stemming uncomment this\n #f4=open(\"F://IR//Project Files//Task3Stemmed//Relevant_Docs_for_each_stemmed_query.txt\",'a+',encoding='utf-8')\n \n f4.write(str(count)+\" \")\n for j in range(10):\n f4.write(bm25_ranked_list[j][0]+\" \")\n f4.write(\"\\n\")\n \n\n\ndef calculate_BM25(freq,doclen,qf,n,avdl,R,r):\n x = float(doclen/avdl)\n x = (b*x)\n z = (1-b)\n K = (k1*(z+x))\n p1 = float((r+0.5)/(R-r+0.5))\n p2 = float((n-r+0.5)/(N-n-R+r+0.5))\n temp=(p1/p2)\n p3 = math.log(temp if temp>0 else 1)\n p4 = float(((k1+1)*freq)/(K+freq))\n p5 = float(((k2+1)*qf)/(k2+qf))\n score = (p3*p4*p5)\n\n return score\n \n\n\ndef main():\n \n\n f5=open(\"F://IR//Project Files//bm25_general_corpus_results.txt\",'a+',encoding='utf-8')\n \n #For stopping uncomment this\n #f5=open(\"F://IR//Project Files//Task3Stopped//bm25_stopped_corpus_results.txt\",'a+',encoding='utf-8')\n \n #For stemming uncomment this\n #f5=open(\"F://IR//Project Files//Task3Stemmed//bm25_stemmed_corpus_results.txt\",'a+',encoding='utf-8')\n \n count = 0\n path = \"F://IR//Project Files//CACMCORPUS//\"\n sum_doc_length = 0\n #calculating the document length for every document\n for filename in os.listdir(path):\n temp = str(filename)\n temp=temp.rstrip('.txt')\n fi= open(path+filename,'r',encoding=\"utf-8\").readlines()\n dl=len(fi)\n doc_length[temp]=dl\n sum_doc_length+=dl\n \n #calculating avdl \n avdl = float(sum_doc_length/N)\n\n #Retrieving the dictionary of inverted list of unigrams\n \n #For stemming uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//inverted_index_stemmed_unigrams.txt\",'r',encoding='utf-8') as f:\n\n #For stopping uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//inverted_index_stopped_unigrams.txt\",'r',encoding='utf-8') as f: \n with open(\"F://IR//Project Files//inverted_index_unigrams.txt\",'r',encoding='utf-8') as f:\n for val in f:\n inverted_list.append(eval(val))\n\n #storing the inverted index in a dictionary\n for row in inverted_list: \n inverted_index_dict[row[0]]=row[1]\n\n #retrieving the dictionary of tokens in each doc\n #with open (\"F://IR//Project Files//Stopped and Stemmed Files_Task3//terms_in_docs_stopped.txt\",'r',encoding='utf-8') as f2:\n \n #For stemming uncomment this \n #with open (\"F://IR//Project Files//Stopped and Stemmed Files_Task3//terms_in_docs_stemmed.txt\",'r',encoding='utf-8') as f2: \n with open (\"F://IR//Project Files//terms_in_docs.txt\",'r',encoding='utf-8') as f2:\n for val in f2:\n tokens_in_each_doc.append(eval(val))\n\n for row in tokens_in_each_doc:\n doc_token_info[row[0]] = row[1]\n\n\n with open (\"F://IR//Project Files//cacm_rel.txt\",'r',encoding='utf-8') as f3:\n for line in f3.readlines():\n l=line.split()\n cacm_rel.append(l)\n\n\n f5.write('{:10} {:2} {:40} {:5} {:30} {:10} {:40} {:20}'.format(\"QueryId\", \"Q0\", \"DocumentName\", \"Rank\", \" Score\",\n \"Relevance\", \" Precision\", \" Recall\") + '\\n\\n')\n\n #For stopping uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//query_stopped.txt\",'r',encoding=\"utf-8\") as fi :\n \n #For stemming uncomment this\n #with open(\"F://IR//Project Files//Stopped and Stemmed Files_Task3//query_stemmed.txt\",'r',encoding=\"utf-8\") as fi :\n with open(\"F://IR//Project Files//query.txt\",'r',encoding=\"utf-8\") as fi : \n for query in fi:\n count = count + 1\n R = 0\n rel_docs = []\n for row in cacm_rel:\n if count ==int(row[0]):\n R += 1\n rel_docs.append(row[2])\n\n bm25_intermediate_fn(query,avdl,inverted_index_dict,count,R,rel_docs,doc_token_info,f5)\n \n \n \n\n\n \n\n \n \nmain()\n \n","sub_path":"BM25.py","file_name":"BM25.py","file_ext":"py","file_size_in_byte":8815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257587299","text":"from mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n# X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])\n# nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)\n# distances, indices = nbrs.kneighbors(X)\n# print(indices)\n\n\niris = datasets.load_iris()\niris_data = iris.data\niris_labels = iris.target\nprint(iris_data[0], iris_data[79], iris_data[100])\nprint(iris_labels[0], iris_labels[79], iris_labels[100])\n\nnp.random.seed(42)\nindices = np.random.permutation(len(iris_data))\nn_training_samples = 12\nlearnset_data = iris_data[indices[:-n_training_samples]]\nlearnset_labels = iris_labels[indices[:-n_training_samples]]\ntestset_data = iris_data[indices[-n_training_samples:]]\ntestset_labels = iris_labels[indices[-n_training_samples:]]\nprint(learnset_data[:4], learnset_labels[:4])\nprint(testset_data[:4], testset_labels[:4])\n","sub_path":".history/example-knn_20190225055338.py","file_name":"example-knn_20190225055338.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"259462611","text":"# coding: utf-8\n\nimport time, re\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.hotelurbano.com\")\nassert \"Hotel Urbano\" in driver.title\ntime.sleep(3)\n\n#Entra na ṕágina de pacotes\nelemClick = driver.find_element_by_class_name('mapx-header-click-pacotes')\nelemClick.click()\ntime.sleep(2)\n\n#Entra na ṕágina de pacotes\nassert \"PACOTES\" in driver.page_source\ntime.sleep(3)\n\n#Entra em um hotel\nelemClick = driver.find_element_by_class_name('offer-card offer-card--desktop')\nelemClick.click()\ntime.sleep(5)\n\nassert \"VIAJAR\" in driver.page_source\n\n\n","sub_path":"Tester/Teste.Selenium.Python/Tester/Teste.Pacotes.2.py","file_name":"Teste.Pacotes.2.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"496057344","text":"#!/usr/bin/python3\n\"\"\" Fabric script that distributes an archive to a web server. \"\"\"\nfrom fabric.api import env, put, run\nfrom os.path import exists\nenv.hosts = [\"35.237.133.118\", \"3.90.191.97\"]\n\n\ndef do_deploy(archive_path):\n \"\"\" Deploy an archive to the web server. \"\"\"\n if exists(archive_path) is False:\n return False\n try:\n file_tgz = archive_path.split(\"/\")[1] # filename.tgz\n file_name = file_tgz.split(\".\")[0] # filename\n path = \"/data/web_static/releases/\"\n put(archive_path, \"/tmp/\")\n run(\"mkdir -p {}{}/\".format(path, file_name))\n # Uncompress the archive to the folder.\n run(\"tar -xzf /tmp/{} -C {}{}/\".format(file_tgz, path, file_name))\n # Deletes the collected file\n run(\"rm /tmp/{}\".format(file_tgz))\n run(\"mv {0}{1}/web_static/* {0}{1}\".format(path, file_name))\n run(\"rm -rf {}{}/web_static\".format(path, file_name))\n run(\"rm -rf /data/web_static/current\")\n run(\"ln -s {}{}/ /data/web_static/current\".format(path, file_name))\n\n return True\n except Exception:\n return False\n","sub_path":"2-do_deploy_web_static.py","file_name":"2-do_deploy_web_static.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26271868","text":"#!/usr/bin/python3\n\"\"\"This module defines the view Place\"\"\"\n\nfrom models.place import Place\nfrom models.user import User\nfrom models.city import City\nfrom models.state import State\nfrom models.amenity import Amenity\nfrom . import app_views\nfrom flask import jsonify, abort, request\nfrom models import storage\nfrom os import getenv\nSTORAGE_TYPE = getenv('HBNB_TYPE_STORAGE')\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_places(city_id=None):\n \"\"\"Retrieves the list of all Place objects from a determinated City\n\n Args:\n city_id (city_id, optional): id to search an city. Defaults to None.\n\n Returns:\n Response: If the state_id is not linked to any City object,\n raise a 404 error\n If everythin is right return\n a list of all places with response 200\n \"\"\"\n\n list_ = []\n city = storage.get(City, city_id)\n if city:\n places = city.places\n for place in places:\n list_.append(place.to_dict())\n return jsonify(list_), 200\n abort(404)\n\n\n@app_views.route('/places/', methods=['GET'], strict_slashes=False)\ndef get_place(place_id=None):\n \"\"\"Retrieves a Place Object\n\n Args:\n place_id (str, optional): id to search a Place. Defaults to None.\n\n Returns:\n Response: If the state_id is not linked to any Place object,\n raise a 404 error or\n if everything is right return a list\n with the Place with response 200\n \"\"\"\n\n place = storage.get(Place, place_id)\n return place.to_dict() if place else abort(404)\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id=None):\n \"\"\"Deletes a Place object\n\n Args:\n place_id (str, optional): id of the place to be deleted.\n Defaults to None.\n\n Returns:\n HTTP-Response: If the place_id is not linked to any place object,\n raise a 404 error or Returns an empty dictionary\n with the status code 200\n \"\"\"\n\n place = storage.get(Place, place_id)\n if place:\n storage.delete(place)\n storage.save()\n return jsonify({}), 200\n else:\n abort(404)\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef save_place(city_id=None):\n \"\"\"[Creates a Place]\n\n Args:\n city_id (str, optional): id of the city where the place\n have to be created. Defaults to None.\n\n Returns:\n [HTTP-Response]: If the HTTP request body is not valid JSON,\n raise a 400 error with the message Not a JSON\n If the dictionary doesn’t contain the key 'name',\n raise a 400 error with the message 'Missing name'\n Returns the new City with the status code 201\n \"\"\"\n\n body = request.get_json()\n city = storage.get(City, city_id)\n if city is None:\n abort(404)\n\n if not request.is_json:\n return jsonify(error='Not a JSON'), 400\n\n if \"user_id\" not in body.keys():\n return jsonify(error=\"Missing user_id\"), 400\n user = storage.get(User, body['user_id'])\n\n if user is None:\n abort(404)\n if \"name\" not in body.keys():\n return jsonify(error=\"Missing name\"), 400\n place = Place(city_id=city_id, **body)\n place.save()\n return jsonify(place.to_dict()), 201\n\n\n@app_views.route('/places/', methods=['PUT'], strict_slashes=False)\ndef put_place(place_id=None):\n \"\"\"Updates a Place object\n\n Args:\n place_id ([str], optional): Id of the Place object to be updated.\n Defaults to None.\n\n Returns:\n [HTTP-Response]: If the place_id is not linked to any Place object,\n raise a 404 error\n If the HTTP request body is not valid JSON,\n raise a 400 error with the message Not a JSON\n If everything is right\n returns the Amenity object with the status code 200\n \"\"\"\n\n body = request.get_json()\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n elif not request.is_json:\n return jsonify(error='Not a JSON'), 400\n\n for k, v in body.items():\n if k in ['id', 'updated_at', 'updated_at', 'user_id', 'city_id']:\n continue\n setattr(place, k, v)\n place.save()\n return jsonify(place.to_dict()), 200\n\n\n@app_views.route('/places_search', methods=['POST'], strict_slashes=False)\ndef places_search():\n \"\"\"\n Retrieves all Place objects depending of the JSON in the body\n of the request\n \"\"\"\n\n if request.get_json() is None:\n abort(400, description=\"Not a JSON\")\n\n data = request.get_json()\n\n if data and len(data):\n states = data.get('states', None)\n cities = data.get('cities', None)\n amenities = data.get('amenities', None)\n\n if not data or not len(data) or (\n not states and\n not cities and\n not amenities):\n places = storage.all(Place).values()\n list_places = []\n for place in places:\n list_places.append(place.to_dict())\n return jsonify(list_places)\n\n list_places = []\n if states:\n states_obj = [storage.get(State, s_id) for s_id in states]\n for state in states_obj:\n if state:\n for city in state.cities:\n if city:\n for place in city.places:\n list_places.append(place)\n\n if cities:\n city_obj = [storage.get(City, c_id) for c_id in cities]\n for city in city_obj:\n if city:\n for place in city.places:\n if place not in list_places:\n list_places.append(place)\n\n if amenities:\n if not list_places:\n list_places = storage.all(Place).values()\n amenities_obj = [storage.get(Amenity, a_id) for a_id in amenities]\n list_places = [place for place in list_places\n if all([am in place.amenities\n for am in amenities_obj])]\n\n places = []\n for p in list_places:\n d = p.to_dict()\n d.pop('amenities', None)\n places.append(d)\n\n return jsonify(places)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364926131","text":"#__author__ = 'Sam_to'\n#coding:utf-8\n\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\nclass Example(QtGui.QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n self.initUI()\n\n def initUI(self):\n\n slider = QtGui.QSlider(QtCore.Qt.Horizontal, self)\n slider.setFocusPolicy(QtCore.Qt.NoFocus)\n slider.setGeometry(30, 40, 10, 30)\n self.connect(slider, QtCore.SIGNAL('valueChanged(int)'), self.changeValue)\n\n self.label = QtGui.QLabel(self)\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n self.label.setGeometry(160, 40, 80, 30)\n\n self.setWindowTitle('Slider')\n self.setGeometry(300, 300, 250, 150)\n\n\n def changeValue(self, value):\n\n if value == 0:\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n elif value > 0 and value <= 30:\n self.label.setPixmap(QtGui.QPixmap('icons/exit.png'))\n elif value >30 and value <= 80:\n self.label.setPixmap(QtGui.QPixmap('icons/open.png'))\n else:\n self.label.setPixmap(QtGui.QPixmap('icons/web.png'))\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n ex = Example()\n ex.show()\n app.exec_()\n","sub_path":"pyqt_std/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"170915991","text":"from sklearn import tree\nimport numpy as np\nimport scipy\n\ncurrlist = [\"USDJPY\",\"USDEUR\",\"USDGBP\",\"EURJPY\",\"EURGBP\",\"GBPJPY\"]\nsample_num = 20\nmax_sample_range=550\nmin_later = 5\n\ninittime = 600\nendtime = 750\n\n\n\nsample_range = range(0,max_sample_range)\n\nfor i in range(0, len(currlist)):\n filename='./'+currlist[i]+'.dat'\n exec('dataset'+str(i)+' = np.loadtxt(filename,skiprows=1,usecols=range(0,3))')\n\ndataset = []\nfor i in sample_range:\n sample = []\n for j in range(0,sample_num):\n data = np.zeros((len(currlist)), dtype=np.float)\n for k in range(0,len(currlist)):\n exec('data[k] = dataset'+str(k)+'[i+j,2]')\n sample.append(data)\n sample = np.reshape(sample,(sample_num*len(currlist)))\n dataset.append([sample])\ndataset = np.squeeze(dataset)\n\n\nlabels = np.zeros(max_sample_range,dtype=np.int)\nfor i in sample_range:\n if dataset1[sample_num+i+min_later,2] > dataset1[sample_num+i,2]:\n labels[i] = 1\n else:\n labels[i] = 0\npred_binary = tree.DecisionTreeClassifier()\npred_binary = pred_binary.fit(dataset, labels)\n\nmaxeval = 700\n\nmoney = 0\nbet = 20\n\n\ncountwins = 0\ncounter = 0\nfor i in np.arange(inittime,endtime,min_later):\n currdata = []\n for j in np.arange(sample_num,0,-1):\n data = np.zeros((len(currlist)), dtype=np.float)\n for k in range(0,len(currlist)):\n exec('data[k] = dataset'+str(k)+'[i-j,2]')\n currdata.append(data)\n currdata = np.reshape(currdata,(sample_num*len(currlist)))\n currdata = currdata.reshape(1,-1)\n prediction = pred_binary.predict(currdata)\n if dataset1[i+min_later,2] > dataset1[i,2]:\n reality = 1\n else:\n reality = 0\n if prediction == reality:\n countwins +=1\n money += bet*1.5\n else:\n money -= bet\n counter = counter+1\n\n#print(money)\n#print(countwins)\nprint(countwins/counter)\n#print('tottiem =',endtime-inittime)\n","sub_path":"DecisionTree/simulate_binary.py","file_name":"simulate_binary.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499723791","text":"from django.shortcuts import render\nfrom django.db.models import F\nfrom rest_framework import status\nfrom rest_framework.generics import (\n ListAPIView,\n RetrieveAPIView,\n CreateAPIView,\n UpdateAPIView,\n GenericAPIView,\n)\n\nfrom rest_framework.mixins import (\n UpdateModelMixin,\n)\nfrom rest_framework.response import Response\nfrom django.db.models import Q\nfrom .models import Poll, PollAnswer, Comment, PollVote, gen_slug\nfrom .serializers import PollSerializer, PollAnswerSerializer, CommentSerializer, PollVoteSerializer\nfrom .paginators import PollPagination, CommentPagination\n\nfrom .utils import gen_slug\n\nMAX_ANSWERS_ON_POLL = 10\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n return x_forwarded_for.split(',')[0]\n else:\n return request.META.get('REMOTE_ADDR')\n\ndef vote_exists(request, poll):\n user_ip = get_client_ip(request)\n vote = PollVote.objects.filter(Q(user_ip=user_ip) & Q(poll=poll))\n return vote.count() > 0\n\ndef create_vote(request, poll):\n user_ip = get_client_ip(request)\n PollVote.objects.create(user_ip=user_ip, poll=poll)\n\ndef count_answers(poll):\n answers = PollAnswer.objects.filter(poll=poll)\n return answers.count()\n\nclass PollListView(ListAPIView):\n serializer_class = PollSerializer\n pagination_class = PollPagination\n\n def get_queryset(self):\n search = self.request.query_params.get('search', None)\n if search is not None:\n search = search.split()\n word = search[0].lower()\n condition = Q(question__icontains=word)\n for kw in search[1:]:\n word = kw.lower()\n condition |= Q(question__icontains=word)\n return Poll.objects.filter(condition).order_by('-created_at')\n else:\n return Poll.objects.all().order_by('-created_at')\n \nclass PollDetailView(RetrieveAPIView):\n lookup_field = 'slug'\n queryset = Poll.objects.all()\n serializer_class = PollSerializer\n\n def retrieve(self, request, *args, **kwargs):\n instance = self.get_object()\n serializer = self.get_serializer(instance)\n data = serializer.data\n data['is_author'] = data.get('author', None) == get_client_ip(request)\n data.pop('author')\n return Response(data)\n\nclass PollCreateView(CreateAPIView):\n serializer_class = PollSerializer\n\n def perform_create(self, serializer):\n question = self.request.data.get('question')\n slug = gen_slug(question)\n answers = self.request.data.get('answers')\n allow_multiple = self.request.data.get('allow_multiple')\n allow_comments = self.request.data.get('allow_comments')\n user_ip = get_client_ip(self.request)\n\n if bool(answers) and len(answers) >= 2 and len(answers) <= 10:\n poll = Poll.objects.create(\n question=question, \n allow_multiple=allow_multiple, \n allow_comments=allow_comments,\n author=user_ip,\n )\n\n for answer in answers:\n PollAnswer.objects.create(answer=answer, poll=poll)\n\n return poll\n else:\n print('Poll should contain at least 2 answers!')\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n instance = self.perform_create(serializer)\n \n serialized_data = serializer.data \n serialized_data['slug'] = instance.slug\n \n headers = self.get_success_headers(serializer.data)\n return Response(serialized_data, status=status.HTTP_201_CREATED, headers=headers)\n\nclass PollAnswerListView(ListAPIView):\n serializer_class = PollAnswerSerializer\n\n def get_queryset(self):\n slug = self.kwargs['slug']\n poll = Poll.objects.get(slug=slug)\n return PollAnswer.objects.filter(poll=poll) \n \nclass CommentListView(ListAPIView):\n serializer_class = CommentSerializer\n pagination_class = CommentPagination\n\n def get_queryset(self):\n slug = self.kwargs['slug']\n poll = Poll.objects.get(slug=slug)\n return Comment.objects.filter(poll=poll).order_by('-created_at')\n\nclass CommentCreateView(CreateAPIView):\n serializer_class = CommentSerializer\n\n def perform_create(self, serializer):\n poll = Poll.objects.get(slug=self.kwargs['slug'])\n\n if poll.allow_comments:\n serializer.save(poll=poll)\n else:\n print('Comments aren\\'t allowed on the poll \"' +\\\n poll.question + '\"!')\n\nclass PollVoteView(ListAPIView):\n serializer_class = PollVoteSerializer\n\n def get_queryset(self):\n user_ip = get_client_ip(self.request)\n poll = Poll.objects.get(slug=self.kwargs['slug'])\n return PollVote.objects.filter(Q(user_ip=user_ip) & Q(poll=poll))\n\nclass VoteAddView(UpdateAPIView):\n serializer_class = PollAnswerSerializer\n queryset = PollAnswer.objects.all()\n\n def perform_update(self, serializer):\n answerIds = self.request.query_params.get('choices', None)\n \n if answerIds is not None:\n answerIds = answerIds.split(',')\n for i in range(len(answerIds)):\n answerIds[i] = int(answerIds[i])\n\n answer = PollAnswer.objects.get(id=answerIds[0])\n\n if not vote_exists(self.request, answer.poll):\n if not answer.poll.allow_multiple:\n answerIds = answerIds[:1]\n \n PollAnswer.objects.filter(id__in=answerIds).update(votes=F('votes')+1)\n create_vote(self.request, answer.poll)\n else:\n print('Poll \"' + poll.question + '\" already voted!')\n\n\n\n\n\n\n ","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300859746","text":"from rest_framework import serializers\nfrom . import models\nfrom django.db.models import Q\n\nclass CompletedVisitSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Visit\n queryset = models.Visit.objects.filter(is_submitted=True)\n\nclass StudentSerializer(serializers.ModelSerializer):\n# caregivers = CaregiverSerializer(many=True)\n num_contacts = serializers.SerializerMethodField()\n num_noshows = serializers.SerializerMethodField()\n num_complete = serializers.SerializerMethodField()\n\n def get_num_complete(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True, type='complete'):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n def get_num_noshows(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True, type='noshow'):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n def get_num_contacts(self, obj):\n qs = {}\n for v in obj.visits.filter(is_submitted=True):\n qs_id = v.answerset.questionset_id;\n if qs_id not in qs:\n qs[qs_id] = 0\n qs[qs_id] += 1\n return qs\n\n class Meta:\n model = models.Student\n fields = ('name', 'key', 'grade', 'num_contacts', 'num_noshows', 'num_complete')\n\nclass StaffSerializer(serializers.ModelSerializer):\n status = serializers.ReadOnlyField(source='status.name')\n class Meta:\n model = models.Staff\n fields = ('name', 'status', 'key', 'is_visit_1_trained', 'is_visit_2_trained')\n\nclass SchoolSerializer(serializers.ModelSerializer):\n staff = serializers.SerializerMethodField() #'get_staff')\n #staff = StaffSerializer(many=True)\n trained1_staff = serializers.SerializerMethodField('get_trained1')\n trained2_staff = serializers.SerializerMethodField('get_trained2')\n\n def get_staff(self, obj):\n return StaffSerializer(instance=obj.staff.filter(is_active=True), many=True).data\n\n def get_trained1(self, obj):\n q = Q(school=obj) | Q(secondary_schools=obj)\n q = q & Q(is_visit_1_trained=True)\n staff = models.Staff.objects.filter(is_active=True).filter(q)\n #staff = obj.staff.filter(is_visit_1_trained__isnull=False).exclude(is_site_coordinator=True)\n return StaffSerializer(instance=staff, many=True).data\n\n def get_trained2(self, obj):\n q = Q(school=obj) | Q(secondary_schools=obj)\n q = q & Q(is_visit_2_trained=True)\n staff = models.Staff.objects.filter(is_active=True).filter(q) #.exclude(is_site_coordinator=True)\n #staff = obj.staff.filter(is_visit_2_trained__isnull=False).exclude(is_site_coordinator=True)\n return StaffSerializer(instance=staff, many=True).data\n\n class Meta:\n model = models.School\n depth = 2\n fields = ('name', 'district', 'staff', 'trained1_staff', 'trained2_staff')\n\nclass VisitSerializer(serializers.ModelSerializer):\n staff1 = StaffSerializer()\n student = StudentSerializer()\n questionset = serializers.ReadOnlyField(source=\"answerset.questionset_id\")\n\n class Meta:\n model = models.Visit\n","sub_path":"visit/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271608468","text":"\nfrom tkinter import *\nimport numpy as np\n\nclass RefiEval:\n def __init__(self):\n window = Tk()\n window.title(\"Refinance Evaluator\")\n\n # Loan inputs\n Label(window, text=\"Loan Amount: \", font=\"Helvetica 16\").grid(row=1, column=1, sticky=W)\n Label(window, text=\"Interest Rate: \", font=\"Helvetica 16\").grid(row=2, column=1, sticky=W)\n Label(window, text=\"Term (years): \", font=\"Helvetica 16\").grid(row=3, column=1, sticky=W)\n Label(window, text=None).grid(row=4, column=1, sticky=W)\n\n #outputs\n Label(window, text=\"Payment: \", font=\"Helvetica 16\").grid(row=5, column=1, sticky=W)\n Label(window, text=\"Total Payments: \", font=\"Helvetica 16\").grid(row=6, column=1, sticky=W)\n\n #Variable que guarda el input\n self.pv = StringVar()\n self.interest_rate = StringVar()\n self.term = StringVar()\n\n #Variables para imprimir pmt\n self.pmt = StringVar()\n self.total = StringVar()\n\n #cajas de texto para manejar inputs y outputs\n\n Entry(window, textvariable=self.pv,\n justify=RIGHT).grid(row=1, column=2, padx=(0, 5))\n\n Entry(window, textvariable=self.interest_rate,\n justify=RIGHT).grid(row=2, column=2, padx=(0, 5))\n\n Entry(window, textvariable=self.term,\n justify=RIGHT).grid(row=3, column=2, padx=(0, 5))\n\n Label(window, textvariable=self.pmt,\n font=\"Helvetica 16 bold\",\n justify=RIGHT).grid(row=5, column=2, sticky=E)\n\n Label(window, textvariable=self.total,\n font=\"Helvetica 16 bold\",\n justify=RIGHT).grid(row=6, column=2, sticky=E)\n\n Button(window, text=\"Calculate Payment\",\n command=self.calcPayment,\n font=\"Helvetica 14\").grid(row=7, column=2, padx=(60, 5), pady=5)\n\n #Variables de refinanciamiento\n self.old_pmt = StringVar()\n self.timeleft = StringVar()\n self.refi_cost = StringVar()\n\n #Widgets de refinanciamiento\n Label(window, text=\"Current Payment: \",\n font=\"Helvetica 16\").grid(row=8, column=1, sticky=W)\n\n Label(window, text=\"Time Remaining: \",\n font=\"Helvetica 16\").grid(row=9, column=1, sticky=W)\n\n Label(window, text=\"Cost of Refi: \",\n font=\"Helvetica 16\").grid(row=10, column=1, sticky=W)\n\n\n #Entradas de evaluacion\n Entry(window, textvariable=self.old_pmt,\n justify=RIGHT).grid(row=8, column=2, padx=(0,5))\n\n Entry(window, textvariable=self.timeleft,\n justify=RIGHT).grid(row=9, column=2, padx=(0,5))\n\n Entry(window, textvariable=self.refi_cost,\n justify=RIGHT).grid(row=10, column=2, padx=(0,5))\n\n #Variables de Salida para la evaluacion\n self.monthly_savings = StringVar()\n self.payback = StringVar()\n self.overall_savings = StringVar()\n\n Label(window, text=\"Monthly Savings: \",\n font=\"Helvetica 16\").grid(row=11, column=1, sticky=W)\n\n Label(window, text=\"Payback in Months: \",\n font=\"Helvetica 16\").grid(row=12, column=1, sticky=W)\n\n Label(window, text=\"Overall Savings: \",\n font=\"Helvetica 16\").grid(row=13, column=1, sticky=W)\n\n # Mostrar outputs\n Label(window, textvariable=self.monthly_savings,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=11, column=2, sticky=E)\n Label(window, textvariable=self.payback,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=12, column=2, sticky=E)\n Label(window, textvariable=self.overall_savings,\n font=\"Helvetica 12 bold\",\n justify=RIGHT).grid(row=13, column=2, sticky=E)\n\n Button(window, text=\"Eval Refi\",\n font=\"Helvetica 14\",\n command=self.evalRefi).grid(row=14, column=2, padx=(100, 5), pady=5)\n\n\n\n window.mainloop()\n\n\n\n def calcPayment(self):\n pv = float(self.pv.get())\n rate = float(self.interest_rate.get())\n term = int(self.term.get())\n\n pmt = np.pmt(rate / 1200, term * 12, -pv, 0)\n total = pmt * 12 * term\n\n self.pmt.set(\"$\" + format(pmt, \"5,.2f\"))\n self.total.set(\"$\" + format(total, \"8,.2f\"))\n\n def evalRefi(self):\n pmt = self.pmt.get()\n pmt = pmt[1:]\n pmt = float(pmt[:pmt.find(',')] + pmt[pmt.find(',')+1:])\n\n total = self.total.get()\n total = total[1:]\n total = float(total[:total.find(',')] + total[total.find('.')+1:])\n\n #perform comparison ??\n old_pmt = float(self.old_pmt.get())\n monthly_savings = old_pmt - pmt\n\n refi_cost = float(self.refi_cost.get())\n payback = refi_cost / monthly_savings\n old_remaining = float(self.timeleft.get()) * 12 * float(self.old_pmt.get())\n overall_savings = old_remaining - total\n\n self.monthly_savings.set(\"$\" + format(monthly_savings, \"5,.2f\"))\n self.payback.set(format(payback, \"5.2f\") + \" months\")\n self.overall_savings.set(\"$\" + format(overall_savings, \"8,.2f\"))\n\n\nRefiEval()\n","sub_path":"Refinance Calculator/7_refin_eval.py","file_name":"7_refin_eval.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"337148284","text":"import numpy as np\nimport pandas as pd\nfrom geopy.distance import vincenty\nfrom mpl_toolkits.basemap import Basemap\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pylab as plt\nfrom atmPy.general import timeseries\nfrom pyhdf.SD import SD, SDC\nfrom matplotlib.colors import LinearSegmentedColormap\n\n\ndef get_cmap(norm='linear', log_min=None, reverse=False):\n colors = np.array([np.array([0.0, 4., 76.]) / 255.,\n np.array([49., 130., 0.0]) / 255.,\n np.array([255, 197., 98.]) / 255.,\n np.array([245., 179., 223.]) / 255.,\n np.array([1, 1, 1]),\n ])\n\n if norm == 'linear':\n steps = np.linspace(0, 1, len(colors))\n elif norm == 'log':\n steps = np.logspace(log_min, 0, len(colors))\n steps[0] = 0\n\n if reverse:\n colors = colors[::-1]\n\n r = np.zeros((len(colors), 3))\n r[:, 0] = steps\n r[:, 1] = colors[:, 0]\n r[:, 2] = colors[:, 0]\n\n g = np.zeros((len(colors), 3))\n g[:, 0] = steps\n g[:, 1] = colors[:, 1]\n g[:, 2] = colors[:, 1]\n\n b = np.zeros((len(colors), 3))\n b[:, 0] = steps\n b[:, 1] = colors[:, 2]\n b[:, 2] = colors[:, 2]\n\n cdict = {'red': r,\n 'green': g,\n 'blue': b\n }\n\n hag_cmap = LinearSegmentedColormap('hag_cmap', cdict)\n hag_cmap.set_bad('black')\n return hag_cmap\n\n\ndef read_file(fname):\n out = Calipso(fname)\n return out\n\n\n\ndef get_total_attenuated_backscattering(hdf, datetime, bins):\n totattback = hdf.select('Total_Attenuated_Backscatter_532')\n data = totattback[:]\n data[data == -9999.0] = np.nan\n totbackatt_df = pd.DataFrame(data, index=datetime, columns=bins)\n # ts = timeseries.TimeSeries_2D(totbackatt_df)\n ts = Total_Attenuated_Backscattering(totbackatt_df)\n return ts\n\ndef generate_altitude_data(level = 1):\n if level != 1:\n raise ValueError('not implemented yet')\n # list taken from https://www-calipso.larc.nasa.gov/resources/calipso_users_guide/data_summaries/l1b/index.php#Table01\n layer_list = [{'alt_layerbottom': 30.1 * 1e3, 'start_bin': 1, 'end_bin':33, 'v_resolution': 300, 'h_resolution': 5000},\n {'alt_layerbottom': 20.2 * 1e3, 'start_bin': 34, 'end_bin':88, 'v_resolution': 180, 'h_resolution': 5/3 * 1e3},\n {'alt_layerbottom': 8.3 * 1e3, 'start_bin': 89, 'end_bin':288, 'v_resolution': 60, 'h_resolution': 1000},\n {'alt_layerbottom': -0.5 * 1e3, 'start_bin': 289, 'end_bin':578, 'v_resolution': 30, 'h_resolution': 300},\n {'alt_layerbottom': -2 * 1e3, 'start_bin': 579, 'end_bin':583, 'v_resolution': 300, 'h_resolution': 300}\n ]\n layer_data = pd.DataFrame(layer_list)\n\n bins = np.zeros(583)\n\n top_of_layer = 40* 1e3\n for index, row in layer_data.iterrows():\n start = int(row['start_bin']-1)\n end = int(row['end_bin'])\n shape = bins[start :end].shape[0]\n new_bins = np.linspace(row['alt_layerbottom'], top_of_layer, shape, endpoint=False)[::-1]\n top_of_layer = row['alt_layerbottom']\n layer_thickness = (new_bins[:-1] - new_bins[1:]).mean()\n bins[start :end] = new_bins\n # bins[start :end] = row['alt_layerbottom'] + (np.arange(bins[start :end].shape[0]) * row['v_resolution'])[::-1]\n return bins\n\n\n# def plot_on_map(self, projection='aeqd', resolution = 'c', points_of_interest = None, three_d=False):\n# \"\"\"Plots a map of the flight path\n#\n# Note\n# ----\n# packages: matplotlib-basemap,\n#\n# Arguments\n# ---------\n# three_d: bool.\n# If flight path is plotted in 3D. unfortunately this does not work very well (only costlines)\n# \"\"\"\n#\n# data = self.data.copy()\n# data = data.loc[:,['Lon','Lat']]\n# data = data.dropna()\n#\n# lon_center = (data.Lon.values.max() + data.Lon.values.min()) / 2.\n# lat_center = (data.Lat.values.max() + data.Lat.values.min()) / 2.\n#\n# points = np.array([data.Lat.values, data.Lon.values]).transpose()\n# distances_from_center_lat = np.zeros(points.shape[0])\n# distances_from_center_lon = np.zeros(points.shape[0])\n# for e, p in enumerate(points):\n# distances_from_center_lat[e] = vincenty(p, (lat_center, p[1])).m\n# distances_from_center_lon[e] = vincenty(p, (p[0], lon_center)).m\n#\n# lat_radius = distances_from_center_lat.max()\n# lon_radius = distances_from_center_lon.max()\n# scale = 1\n# border = scale * 2 * np.array([lat_radius, lon_radius]).max()\n#\n# height = border + lat_radius\n# width = border + lon_radius\n# if not three_d:\n# if projection == 'mill':\n# bmap = Basemap(projection='mill',llcrnrlat=-90,urcrnrlat=90,\\\n# llcrnrlon=-180,urcrnrlon=180,resolution='c')\n#\n# elif projection == 'aeqd':\n# bmap = Basemap(projection=projection,\n# lat_0=lat_center,\n# lon_0=lon_center,\n# width=width,\n# height=height,\n# resolution=resolution)\n# else:\n# raise ValueError('projection ')\n# # Fill the globe with a blue color\n# wcal = np.array([161., 190., 255.]) / 255.\n# boundary = bmap.drawmapboundary(fill_color=wcal)\n#\n# grau = 0.9\n# continents = bmap.fillcontinents(color=[grau, grau, grau], lake_color=wcal)\n# costlines = bmap.drawcoastlines()\n# x, y = bmap(data.Lon.values, data.Lat.values)\n# path = bmap.plot(x, y,\n# color='m')\n#\n# # return bmap\n#\n# else:\n# bmap = Basemap(projection=projection,\n# lat_0=lat_center,\n# lon_0=lon_center,\n# width=width,\n# height=height,\n# resolution=resolution)\n#\n# fig = plt.figure()\n# ax = Axes3D(fig)\n# ax.add_collection3d(bmap.drawcoastlines())\n# x, y = bmap(self.data.Lon.values, self.data.Lat.values)\n# # ax.plot(x, y,self.data.Altitude.values,\n# # color='m')\n# N = len(x)\n# for i in range(N - 1):\n# color = plt.cm.jet(i / N)\n# ax.plot(x[i:i + 2], y[i:i + 2], self.data.Altitude.values[i:i + 2],\n# color=color)\n# if points_of_interest:\n# for point in points_of_interest:\n#\n# lat,lon = point.pop('loc_lat_lon')\n# x,y = bmap(lon,lat)\n# ax = plt.gca()\n#\n# try:\n# annotation = point.pop('annotation')\n# annotation_kwargs = point.pop('annotations_kwargs')\n# except KeyError:\n# annotation = None\n#\n#\n# g, = bmap.plot(x,y)\n# g.set(**point)\n#\n# if annotation:\n# anno = ax.annotate(annotation, (x,y), **annotation_kwargs)\n# return bmap\n\ndef plot_on_map(self, bmap_kwargs=None, estimate_extend=True, costlines = True, continents = True, background = None, points_of_interest=None, three_d=False, verbose = False):\n \"\"\"\n\n Args:\n bmap_kwargs:\n estimate_extend:\n costlines:\n background: str [None]\n options are 'bluemarble', 'shadedrelief', 'etopo'\n points_of_interest:\n three_d:\n verbose:\n\n Returns:\n\n \"\"\"\n\n data = self.data.copy()\n data = data.loc[:, ['Lon', 'Lat']]\n data = data.dropna()\n\n if not bmap_kwargs:\n bmap_kwargs = {'projection': 'aeqd',\n 'resolution': 'c'}\n\n if estimate_extend:\n if bmap_kwargs['projection'] == 'aeqd':\n lon_center = (data.Lon.values.max() + data.Lon.values.min()) / 2.\n lat_center = (data.Lat.values.max() + data.Lat.values.min()) / 2.\n\n points = np.array([data.Lat.values, data.Lon.values]).transpose()\n distances_from_center_lat = np.zeros(points.shape[0])\n distances_from_center_lon = np.zeros(points.shape[0])\n for e, p in enumerate(points):\n distances_from_center_lat[e] = vincenty(p, (lat_center, p[1])).m\n distances_from_center_lon[e] = vincenty(p, (p[0], lon_center)).m\n\n lat_radius = distances_from_center_lat.max()\n lon_radius = distances_from_center_lon.max()\n scale = 1\n border = scale * 2 * np.array([lat_radius, lon_radius]).max()\n\n height = border + lat_radius\n width = border + lon_radius\n bmap_kwargs['lat_0'] = lat_center\n bmap_kwargs['lon_0'] = lon_center\n bmap_kwargs['width'] = width\n bmap_kwargs['height'] = height\n\n elif bmap_kwargs['projection'] == 'mill':\n bmap_kwargs['llcrnrlat'] = -90\n bmap_kwargs['urcrnrlat'] = 90\n bmap_kwargs['llcrnrlon'] = -180\n bmap_kwargs['urcrnrlon'] = 180\n\n if verbose:\n print('bmap_kwargs: {}'.format(bmap_kwargs))\n\n bmap = Basemap(**bmap_kwargs)\n if not three_d:\n wcal = np.array([161., 190., 255.]) / 255.\n\n if background == 'bluemarbel':\n bmap.bluemarble()\n elif background == 'etopo':\n bmap.etopo()\n elif background == 'shadedrelief':\n bmap.shadedrelief()\n elif not background:\n # Fill the globe with a blue color\n bmap.drawmapboundary(fill_color=wcal)\n else:\n raise ValueError('\"{}\" is not a valid background!'.format(background))\n\n if continents:\n grau = 0.9\n bmap.fillcontinents(color=[grau, grau, grau], lake_color=wcal)\n\n if costlines:\n bmap.drawcoastlines()\n\n x, y = bmap(data.Lon.values, data.Lat.values)\n path = bmap.plot(x, y,\n color='m')\n\n # return bmap\n\n else:\n fig = plt.figure()\n ax = Axes3D(fig)\n ax.add_collection3d(bmap.drawcoastlines())\n x, y = bmap(self.data.Lon.values, self.data.Lat.values)\n # ax.plot(x, y,self.data.Altitude.values,\n # color='m')\n N = len(x)\n for i in range(N - 1):\n color = plt.cm.jet(i / N)\n ax.plot(x[i:i + 2], y[i:i + 2], self.data.Altitude.values[i:i + 2],\n color=color)\n\n if points_of_interest:\n for point in points_of_interest:\n\n lat, lon = point.pop('loc_lat_lon')\n x, y = bmap(lon, lat)\n ax = plt.gca()\n\n try:\n annotation = point.pop('annotation')\n annotation_kwargs = point.pop('annotations_kwargs')\n except KeyError:\n annotation = None\n\n g, = bmap.plot(x, y)\n g.set(**point)\n\n if annotation:\n anno = ax.annotate(annotation, (x, y), **annotation_kwargs)\n return bmap\n\n\ndef get_closest2location(path, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\"\"\"\n\n def get_dist(row, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\n \"\"\"\n dist = vincenty(location, (row['Lat'], row['Lon']))\n # print(row)\n return dist.km\n\n get_distance2location(path, location)\n data = path.data.copy()\n closest = data.sort_values('distance').iloc[[0]]\n return closest\n\n\ndef get_distance2location(path, location):\n \"\"\"Ads a collumn to path.data.\n Args\n ----\n location: tuple\n (lat,lon)\"\"\"\n\n def get_dist(row, location):\n \"\"\"\n Args\n ----\n location: tuple\n (lat,lon)\n \"\"\"\n dist = vincenty(location, (row['Lat'], row['Lon']))\n # print(row)\n return dist.km\n\n dist = path.data.apply(lambda x: get_dist(x, location), axis=1)\n path.data['distance'] = dist\n return\n\n\ndef get_path(hdf, datetime):\n lon = hdf.select('Longitude')[:][:, 0]\n lat = hdf.select('Latitude')[:][:, 0]\n loc_ts = Path(pd.DataFrame({'Lon': lon, 'Lat': lat}, index=datetime))\n return loc_ts\n\ndef get_datetime(hdf):\n time = hdf.select('Profile_UTC_Time')\n time.dimensions()\n td = time[:].transpose()[0]\n day, date = np.modf(td)\n datetime = pd.to_datetime(date.astype(int), format = '%y%m%d') + pd.to_timedelta(day, unit='d')\n return datetime\n\nclass Path(timeseries.TimeSeries):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._closest_location = None\n self._closest = None\n self._radius = None\n self._in_radius = None\n\n plot_on_map = plot_on_map\n\n def get_closest2location(self, location):\n if location == self._closest_location:\n return self._closest\n else:\n self._closest_location = location\n self._closest = get_closest2location(self, location)\n return self._closest\n\n def get_all_in_radius(self, location, radius):\n self.get_closest2location(location)\n if (location != self._closest_location) or (radius != self._radius):\n self._closest_location = location\n self._radius = radius\n self._in_radius = self.data.distance <= radius\n return self._in_radius\n\n\nclass Total_Attenuated_Backscattering(timeseries.TimeSeries_2D):\n def plot(self, *args, **kwargs):\n f, a, pc, cb = super().plot(*args, **kwargs)\n a.set_ylabel('Altitude (m)')\n a.set_xlabel('')\n if cb:\n cb.set_label('Total attenuated backscattering')\n return f, a, pc, cb\n\n\n\n\nclass Calipso(object):\n def __init__(self, fname):\n self._hdf = SD(fname, SDC.READ)\n self._reset()\n self._inradius = None\n self._ts = None\n self._bs = None\n\n # self._zoom_d = None\n\n def _reset(self):\n self._path = None\n self._totattback = None\n\n\n @property\n def _timestamps(self):\n if type(self._ts).__name__ == 'NoneType':\n self._ts = get_datetime(self._hdf)\n # if type(self._inradius).__name__ != 'NoneType':\n # self._ts = self._ts[self._inradius]\n return self._ts\n\n @property\n def _bins(self):\n if type(self._bs).__name__ == 'NoneType':\n self._bs = generate_altitude_data(level = 1)\n return self._bs\n\n @property\n def total_attenuated_backscattering(self):\n if not self._totattback:\n self._totattback = get_total_attenuated_backscattering(self._hdf, self._timestamps, self._bins)\n if type(self._inradius).__name__ != 'NoneType':\n self._totattback = Total_Attenuated_Backscattering(self._totattback.data[self._inradius])\n return self._totattback\n\n # @total_attenuated_backscattering.setter\n # def total_attenuated_backscattering(self,value):\n # self._totattback = Total_Attenuated_Backscattering(value)\n\n @property\n def path(self):\n if not self._path:\n self._path = get_path(self._hdf, self._timestamps)\n if type(self._inradius).__name__ != 'NoneType':\n self._path = Path(self._path.data[self._inradius])\n # if self._zoom:\n # self._path.data\n return self._path\n\n # @path.setter\n # def path(self,value):\n # self._path = Path(value)\n\n def limit2location(self, location, radius):\n \"\"\"This will limit all data to data that is in a certain radius around a location\"\"\"\n self._inradius = self.path.get_all_in_radius(location, radius)\n self._reset()\n\n# if self._path:\n# self.path = self.path.data[inradius]\n# if self._totattback:\n# self.total_attenuated_backscattering = self.total_attenuated_backscattering.data[inradius]\n# if self._ts:\n# self._timestamps = self._timestamps[inradius]\n\n","sub_path":"atmPy/data_archives/calipso/calipso.py","file_name":"calipso.py","file_ext":"py","file_size_in_byte":15961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294247121","text":"import pexpect\n\nchild = pexpect.spawn(\"test/victim\")\nchild.setecho(False)\nchild.sendline(\"hello\")\nchild.expect(\"ECHO: hello\")\n\nreptyr = pexpect.spawn(\"./reptyr %d\" % (child.pid,))\nreptyr.sendline(\"world\")\nreptyr.expect(\"ECHO: world\")\n\nchild.sendline(\"final\")\nchild.expect(pexpect.EOF)\n\nreptyr.sendeof()\nreptyr.expect(pexpect.EOF)\nassert not reptyr.isalive()\n","sub_path":"test/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"358575340","text":"'''\nTrain self-supervised task (rotation prediction) task; current good dataset to use is quaternion_shivin or quaternion_objpred; \nCurrently have a pre-trained model for this, which is referenced in semi_sup script\n'''\n\nimport numpy as np\nimport argparse\nimport os\nimport itertools\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport pickle\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nfrom autolab_core import YamlConfig, RigidTransform\nfrom unsupervised_rbt import TensorDataset\nfrom unsupervised_rbt.models import ResNetSiameseNetwork, InceptionSiameseNetwork\nfrom unsupervised_rbt.losses.shapematch import ShapeMatchLoss, ShapeMatchLoss_Lie\nfrom perception import DepthImage, RgbdImage\n\nfrom tools.data_gen_quat import create_scene\nfrom tools.utils import *\n\nimport trimesh\nfrom pyrender import (Scene, IntrinsicsCamera, Mesh,\n Viewer, OffscreenRenderer, RenderFlags, Node)\nfrom pyquaternion import Quaternion\nimport cv2\n\ndef Plot_Bad_Predictions(dataset, predicted_quats, indices, name = \"worst\"):\n \"\"\"Takes in the dataset, predicted quaternions, and indices of the \n worst predictions in the validation set\n \"\"\"\n for i in indices:\n datapoint = dataset.get_item_list(test_indices[i:i+1])\n predicted_quat = predicted_quats[i]\n plt.figure(figsize=(15,5))\n plt.subplot(131)\n fig1 = plt.imshow(datapoint[\"depth_image1\"][0][0], cmap='gray', vmin=np.min(datapoint[\"depth_image1\"][0][0]))\n plt.title('Stable pose')\n plt.subplot(132)\n fig2 = plt.imshow(datapoint[\"depth_image2\"][0][0], cmap='gray')\n plt.title('True Quat: ' + Quaternion_String(datapoint[\"quaternion\"][0]))\n plt.subplot(133)\n fig3 = plt.imshow(Plot_Predicted_Rotation(datapoint, predicted_quat), cmap='gray')\n plt.title('Pred Quat: ' + Quaternion_String(predicted_quat))\n fig1.axes.get_xaxis().set_visible(False)\n fig1.axes.get_yaxis().set_visible(False)\n fig2.axes.get_xaxis().set_visible(False)\n fig2.axes.get_yaxis().set_visible(False)\n fig3.axes.get_xaxis().set_visible(False)\n fig3.axes.get_yaxis().set_visible(False)\n plt.savefig(\"plots/worst_preds/\" + name + \"_pred_\" + str(datapoint['obj_id'][0]) + \"_\"\n + str(1- np.dot(predicted_quat, datapoint['quaternion'].flatten()))[2:5])\n print(1 - np.dot(predicted_quat, datapoint['quaternion'].flatten()))\n # plt.show()\n plt.close()\n\ndef Plot_Predicted_Rotation(datapoint, predicted_quat):\n object_id, pose_matrix = datapoint['obj_id'], datapoint['pose_matrix'][0]\n config = YamlConfig(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..',\n 'cfg/tools/data_gen_quat.yaml'))\n scene, renderer = create_scene(data_gen=False)\n dataset_name_list = ['3dnet', 'thingiverse', 'kit']\n mesh_dir = config['state_space']['heap']['objects']['mesh_dir']\n mesh_dir_list = [os.path.join(mesh_dir, dataset_name) for dataset_name in dataset_name_list]\n obj_config = config['state_space']['heap']['objects']\n mesh_lists = [os.listdir(mesh_dir) for mesh_dir in mesh_dir_list]\n obj_id = 0\n for mesh_dir, mesh_list in zip(mesh_dir_list, mesh_lists):\n for mesh_filename in mesh_list:\n obj_id += 1\n if obj_id != object_id:\n continue\n\n # load object mesh\n mesh = trimesh.load_mesh(os.path.join(mesh_dir, mesh_filename))\n obj_mesh = Mesh.from_trimesh(mesh)\n object_node = Node(mesh=obj_mesh, matrix=np.eye(4))\n scene.add_node(object_node)\n # print(pose_matrix)\n ctr_of_mass = pose_matrix[0:3, 3]\n\n new_pose = Quaternion_to_Rotation(predicted_quat, ctr_of_mass) @ pose_matrix\n scene.set_pose(object_node, pose=new_pose)\n return renderer.render(scene, flags=RenderFlags.DEPTH_ONLY)\n\ndef get_points(obj_ids, points_poses):\n points = [point_clouds[obj_id] / scales[obj_id] * 10 for obj_id in obj_ids]\n # print(batch[\"pose_matrix\"][0])\n points = [points_poses[i] @ points[i] for i in range(len(obj_ids))]\n points = torch.Tensor(points).to(device)\n # print(points[:,:5])\n return points\n\ndef train(dataset, batch_size, first=False):\n '''Train model specified in main and return training loss and classification accuracy'''\n model.train()\n train_loss = 0\n\n # train_indices = dataset.split('train')[0][:10000]\n train_indices = dataset.split('train')[0]\n # train_indices = dataset.split('train2')[0][:10000]\n\n N_train = len(train_indices)\n n_train_steps = N_train//batch_size\n\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n optimizer.zero_grad()\n\n for step in tqdm(range(n_train_steps)):\n batch = dataset.get_item_list(train_indices[step*batch_size: (step+1)*batch_size])\n # depth_image1 = Quantize(batch[\"depth_image1\"])\n # depth_image2 = Quantize(batch[\"depth_image2\"])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n \n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).float().to(device)\n # if step > 20:\n # for i in range(batch_size):\n # plt.subplot(121)\n # depth_image_show1 = depth_image1[i][0]\n # plt.imshow(depth_image_show1, cmap='gray')\n # plt.subplot(122)\n # depth_image_show2 = depth_image2[i][0]\n # plt.imshow(depth_image_show2, cmap='gray')\n # plt.title('Transform: {}'.format(transform_batch[i]))\n # plt.show()\n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n\n pred_transform = model(im1_batch, im2_batch)\n # if config['loss'] == 'cosine' or first:\n # loss = loss_func(pred_transform, transform_batch, ones)\n loss = loss_func(pred_transform, transform_batch)\n # sm_loss = loss_func2(pred_transform, transform_batch, points).item()\n # else:\n # loss = loss_func2(pred_transform, transform_batch, points)\n # sm_loss = loss.item()\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n # train_loss += sm_loss\n train_loss += loss.item()\n\n # if step % 100 == 0:\n # print(pred_transform[:3])\n # print(transform_batch[:3])\n # print(loss_func(pred_transform, transform_batch, points))\n\n return train_loss/n_train_steps\n\ndef test(dataset, batch_size):\n \"\"\"\n Return loss and classification accuracy of the model on the test data\n \"\"\"\n model.eval()\n test_loss, total = 0, 0\n\n # test_indices = dataset.split('train')[1][:1000]\n test_indices = dataset.split('train')[1]\n # test_indices = dataset.split('train2')[1][:64*100]\n n_test = len(test_indices)\n n_test_steps = n_test // batch_size\n\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n\n with torch.no_grad():\n for step in tqdm(range(n_test_steps)):\n batch = dataset.get_item_list(test_indices[step*batch_size: (step+1)*batch_size])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).to(device)\n pred_transform = model(im1_batch, im2_batch)\n total += transform_batch.size(0)\n\n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n # if config['loss'] == 'cosine':\n # loss = loss_func(pred_transform, transform_batch, ones)\n loss = loss_func(pred_transform, transform_batch)\n\n # sm_loss = loss_func2(pred_transform, transform_batch, points)\n # test_loss += sm_loss.item()\n test_loss += loss.item()\n\n return test_loss/n_test_steps\n\ndef parse_args():\n \"\"\"Parse arguments from the command line.\n -config to input your own yaml config file. Default is unsup_rbt_train_quat.yaml\n -dataset to input a name for your dataset. Should start with quaternion\n --test to generate a graph of your train and validation loss\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--test', action='store_true')\n parser.add_argument('--worst_pred', action='store_true')\n default_config_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n '..',\n 'cfg/tools/unsup_rbt_train_quat.yaml')\n parser.add_argument('-config', type=str, default=default_config_filename)\n parser.add_argument('-dataset', type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n \"\"\"Train on a dataset or generate a graph of the training and validation loss.\n Current Datasets: \n 72obj_occ: ~130,000 points, image 1 random rectangles, 57 train, 15 test\n uniform30, uniform45, uniform60: ~143,940 points, occlusions, angles sampled uniformly from 0-30,0-45,0-60\n 564obj_250rot: 546(18 not available because of stable pose?) obj with more than 300 points\n best_scores: obj > 300 points, 257 obj, 500 rot. score >= 40. 128293\n 546obj_dr: obj > 300 points. Occlusion is now w background pixels. ~130k. Initial pose from SO3\n best_scoresv2: occlusion is now w background pixels. 82 obj > 300 pts, 1800 rot, score >= 156.52. 163930. 16 obj in val\n 546obj: obj > 300 points, 300 rot. Initial pose has random translation. ~160k\n best_scoresv3: Initial pose translation. 82 obj > 300 pts, 2000 rot, score >= 156.52. 163930. 16 obj in val\n 546objv2: No pose translation, no dr.\n 546objv3: DR with pose sampling 0-45 degrees from stable pose\n best_scoresv4: No pose translation, no dr.\n best_scoresv5: DR with pose sampling 0-45 degrees from stable pose\n 546objv4: DR with background, Translation(+-0.02,+-0.02,0-0.2), 45 degree from stable pose, 300 rot\n best_scoresv6: DR with background, Translation(+-0.02,+-0.02,0-0.2), 45 degree from stable pose, 300 rot\n 546objv5: DR with background, Translation(+-0.01,+-0.01,0-0.05), 45 degree from stable pose, 300 rot, z buffer (0.4,2)\n \"\"\"\n args = parse_args()\n config = YamlConfig(args.config)\n dataset_name = args.dataset + \"/\"\n args.dataset = os.path.join('/nfs/diskstation/projects/unsupervised_rbt', args.dataset)\n dataset = TensorDataset.open(args.dataset)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n \n prefix = \"lie\"\n prefix += \"_blk\" + str(config['n_blocks']) + \"_emb\" + str(config[\"embed_dim\"])\n prefix += \"_reg\" + str(config[\"reg\"]) + \"_drop\" + str(config[\"dropout\"])\n loss_history = \"results/\" + dataset_name + prefix + \".p\"\n histdata = \"results/\" + dataset_name + prefix + \"_histdata.txt\"\n loss_plot_fname = \"plots/\" + dataset_name + prefix + \"_loss.png\"\n rot_plot_fname = \"plots/\" + dataset_name + prefix + \"_rot.png\"\n best_epoch_dir = \"models/\" + dataset_name + prefix + \".pt\"\n print(\"fname prefix\", prefix)\n\n model = ResNetSiameseNetwork(3, config['n_blocks'], config['embed_dim'], config['dropout'], norm=False).to(device)\n\n # point_clouds = pickle.load(open(\"cfg/tools/data/point_clouds\", \"rb\"))\n point_clouds = pickle.load(open(\"cfg/tools/data/point_clouds300\", \"rb\"))\n scales = pickle.load(open(\"cfg/tools/data/scales\", \"rb\"))\n\n # optimizer = optim.Adam(model.parameters())\n optimizer = optim.Adam(model.parameters(), lr=1e-4, weight_decay=10**(-1 * config['reg']))\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5,gamma=0.9)\n loss_func = nn.L1Loss()\n # loss_func = nn.CosineEmbeddingLoss()\n loss_func2 = ShapeMatchLoss_Lie()\n\n if not args.test:\n if not os.path.exists(args.dataset + \"/splits/train\"):\n obj_id_split = np.loadtxt(\"cfg/tools/data/train_split\")\n val_indices = []\n for i in range(dataset.num_datapoints):\n if dataset.datapoint(i)[\"obj_id\"] in obj_id_split:\n val_indices.append(i)\n\n print(\"Created Train Split\")\n dataset.make_split(\"train\", train_pct=0.8, val_indices= val_indices)\n if not os.path.exists(args.dataset + \"/splits/train2\"):\n dataset.make_split(\"train2\", train_pct=0.8)\n\n train_losses, test_losses = [], []\n min_loss = 100000\n # model.load_state_dict(torch.load(\"models/uniform30_1e7.pt\"))\n\n for epoch in range(config['num_epochs']):\n\n train_loss = train(dataset, config['batch_size'], first = (epoch == 0))\n test_loss = test(dataset, config['batch_size'])\n scheduler.step()\n train_losses.append(train_loss)\n test_losses.append(test_loss)\n print((\"Epoch %d, Train Loss = %f, Test Loss = %f\" %\n (epoch, train_loss, test_loss)) + \" for \" + prefix)\n pickle.dump({\"train_loss\": train_losses, \"test_loss\": test_losses,\n }, open(loss_history, \"wb\"))\n # torch.save(model.state_dict(), final_epoch_dir)\n if test_loss < min_loss:\n torch.save(model.state_dict(), best_epoch_dir)\n min_loss = test_loss\n\n else:\n Plot_Loss(loss_history, loss_plot_fname)\n\n # model.load_state_dict(torch.load(final_epoch_dir))\n model.load_state_dict(torch.load(best_epoch_dir))\n # display_conv_layers(model)\n model.eval()\n test_loss, test_loss2, test_loss3, total = 0, 0, 0, 0\n\n # test_indices = dataset.split('train')[1][:1000]\n test_indices = dataset.split('train')[1]\n # test_indices = dataset.split('train2')[1]\n n_test = len(test_indices)\n batch_size = 1\n ones = torch.Tensor(np.ones(batch_size)).to(device)\n n_test_steps = n_test // batch_size\n\n true_quaternions = []\n pred_quaternions = []\n losses, angle_vs_losses = [], []\n with torch.no_grad():\n for step in tqdm(range(n_test_steps)):\n batch = dataset.get_item_list(test_indices[step*batch_size: (step+1)*batch_size])\n depth_image1 = batch[\"depth_image1\"]\n depth_image2 = batch[\"depth_image2\"]\n\n im1_batch = Variable(torch.from_numpy(depth_image1).float()).to(device)\n im2_batch = Variable(torch.from_numpy(depth_image2).float()).to(device)\n transform_batch = Variable(torch.from_numpy(batch[\"lie\"])).to(device)\n pred_transform = model(im1_batch, im2_batch)\n # print(\"True Vector: {}, Predicted Vector: {}\".format(transform_batch, pred_transform))\n total += transform_batch.size(0)\n\n # loss = loss_func(pred_transform, transform_batch, ones).item()\n loss = loss_func(pred_transform, transform_batch).item()\n # angle_loss = np.arccos(1-loss) * 180 / np.pi * 2 # Don't use, always underestimates error.\n \n obj_ids = batch[\"obj_id\"]\n points_poses = batch[\"pose_matrix\"][:,:3,:3]\n points = get_points(obj_ids, points_poses)\n sm_loss = loss_func2(pred_transform, transform_batch, points).item()\n\n # true_quaternions.extend(transform_batch.cpu().numpy())\n # pred_quaternions.extend(pred_transform.cpu().numpy())\n\n # true_quat = transform_batch.cpu().numpy()[0]\n # angle = np.arccos(true_quat[3]) * 180 / np.pi * 2\n # print(true_quat[3], angle)\n losses.append(loss)\n # angle_vs_losses.append([angle,loss,sm_loss])\n # angle_vs_losses.append([angle,loss])\n test_loss += loss\n test_loss2 += sm_loss\n # np.savetxt(histdata, np.array(angle_vs_losses))\n mean_loss = test_loss/total\n # mean_angle_loss = np.arccos(1-mean_cosine_loss)*180/np.pi*2\n # Plot_Angle_vs_Loss(true_quaternions, losses, mean_loss, rot_plot_fname)\n # Plot_Small_Angle_Loss(true_quaternions, losses, mean_loss)\n # Plot_Axis_vs_Loss(true_quaternions, losses, mean_loss)\n\n if args.worst_pred:\n biggest_losses = np.argsort(losses)[-5:-1]\n smallest_losses_idx = np.argsort(losses)\n smallest_losses = []\n for i in smallest_losses_idx:\n if true_quaternions[i][3] < 0.975:\n smallest_losses.append(i)\n if len(smallest_losses) >= 5:\n break\n Plot_Bad_Predictions(dataset, pred_quaternions, biggest_losses)\n Plot_Bad_Predictions(dataset, pred_quaternions, np.array(smallest_losses), \"best\")\n\n print(\"Mean L1 loss is: \", test_loss/total)\n # print(\"Mean Angle loss is: \", mean_angle_loss)\n print(\"Mean SM loss is: \", test_loss2/total)\n\n\n","sub_path":"tools/unsup_rbt_train_lie.py","file_name":"unsup_rbt_train_lie.py","file_ext":"py","file_size_in_byte":17481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"420624805","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/kvlayer/_decorators.py\n# Compiled at: 2015-07-31 13:31:44\nimport time, logging\nfrom functools import wraps\n\ndef retry(retry_exceptions=[\n Exception], retry_attempts=3):\n \"\"\"\n Configurable decorator that will retry after intermittent failures.\n\n @type retry_exceptions: list\n @param retry_exceptions: List of exceptions that will be retried.\n\n @type retry_attempts: integer\n @param retry_attempts: Number of times to retry a function after it has failed\n \"\"\"\n\n def decorator(method):\n\n @wraps(method)\n def wrapper(*args, **kwargs):\n tries = 0\n while 1:\n try:\n tries += 1\n return method(*args, **kwargs)\n break\n except Exception as exc:\n if not any([ isinstance(exc, e) for e in retry_exceptions ]) or tries > retry_attempts:\n raise\n else:\n logging.warn('Retrying because of exception', exc_info=True)\n time.sleep(3 * tries)\n\n return wrapper\n\n return decorator","sub_path":"pycfiles/kvlayer-0.5.9-py2.7/_decorators.py","file_name":"_decorators.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281989932","text":"#!/bin/py\n# -*-coding:utf-8-*-\n\nclass halfquery():\n L = []\n x = 0\n low = 0\n high = len(L)\n def __init__(self,L=[],x=0):\n self.L=L\n self.x=x\n self.high=len(L)\n\n def seek(self):\n while self.lowself.x:\n self.high=middle\n continue\n elif self.L[middle]i:\n\t\t\t\t\tmatrix[i][j]=1\n\t\treturn\n\t\n\tfor i in range(B):\n\t\tfor j in range(B-1):\n\t\t\tif j>i:\n\t\t\t\tmatrix[i][j]=1\n\t\n\tn=2**(B-3)\n\tind=B-2\n\t\n\twhile M>0:\n\t\tif M>=n:\n\t\t\tM-=n\n\t\t\tmatrix[ind][B-1]=1\n\t\tn//=2\n\t\tind-=1\n\t\n\treturn\n\t\n\nf=open(\"B-small-attempt0.in\",\"r+\")\ng=open(\"output.txt\",\"w+\")\n\nT=int(f.readline())\n\nfor i in range(1,1+T):\n\t[B,M]=[int(i) for i in f.readline().split()]\n\t\n\tmatrix=[[0 for i in range(B)] for i in range(B)]\n\t\n\tif M>2**(B-2):\n\t\tans=\"IMPOSSIBLE\"\n\telse:\n\t\tans=\"POSSIBLE\"\n\t\tsolve(B,M)\n\t\n\tg.write(\"Case #{}: {}\\n\".format(i,ans))\n\t\n\tif ans[0]==\"P\":\n\t\tfor j in range(B):\n\t\t\tfor k in range(B):\n\t\t\t\tg.write(\"{}\".format(matrix[j][k]))\n\t\t\tg.write(\"\\n\")\n\n\nf.close()\ng.close()","sub_path":"solutions_5744014401732608_0/Python/MathProgrammer/prob2.py","file_name":"prob2.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536747792","text":"with open(\"C-small-attempt0.in\") as f:\r\n\tdat = f.read().splitlines()\r\n\r\ndef get_prime(n):\r\n\tfor i in range(2,int(n**0.5)+1):\r\n\t\tif n%i == 0:\r\n\t\t\treturn i\r\n\treturn -1\r\ndef ninbase(digs,base):\r\n\tn = 0\r\n\tmul = 1\r\n\tfor d in digs:\r\n\t\tn += mul*d\r\n\t\tmul *= base\r\n\treturn n\r\n\t\r\nn = int(dat[0])\r\nout = [\"Case #1:\"]\r\n\r\nN = int(dat[1].split()[0])\r\nJ = int(dat[1].split()[1])\r\n\t\r\nfor jc in range(2**(N-1)+1,2**N-1,2):\r\n\tjc = str(bin(jc))[2:]\r\n\t#print(jc)\r\n\t\t\r\n\tjcd = list(jc)[::-1]\r\n\tjcd = [int(jj) for jj in jcd]\r\n\tprimes = []\r\n\tfor base in range(2,11):\r\n\t\tn = ninbase(jcd,base)\r\n\t\tprimes.append(get_prime(n))\r\n\t\tif -1 in primes:\r\n\t\t\tbreak\r\n\t#print(primes)\r\n\t\t\r\n\tif -1 not in primes:\r\n\t\tout.append(jc+\" \"+\" \".join([str(p) for p in primes]))\r\n\t\tprint(out[-1])\r\n\tif out.__len__() == J+1:\r\n\t\tbreak\r\n\r\nassert out.__len__() == 1+J\r\nof = open(\"out.txt\",\"w\")\r\nof.write(\"\\n\".join(out))\r\nof.close()\r\n\r\n\r\n\r\n","sub_path":"solutions_5738606668808192_0/Python/FXilip/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635009058","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.metrics import r2_score\nimport matplotlib.pyplot as plt\n\ndataset = pd.read_csv('Apple.csv')\n\nx = dataset.iloc[:,[1,2,3,5,6]].values\ny = dataset.iloc[:,4].values\n\nfrom sklearn.model_selection import train_test_split\ntrain_x, test_x, train_y, test_y = train_test_split(x,y,test_size = 0.1)\n\nfrom sklearn.tree import DecisionTreeRegressor\nregressor = DecisionTreeRegressor()\nregressor.fit(train_x,train_y)\n\nprint('DecisionTree------------------------------')\nacc = r2_score(test_y,regressor.predict(test_x))\nprint(round(acc,6))\nprint(sum((regressor.predict(test_x) - test_y)**2))\nprint('\\n')\n\nfrom sklearn.ensemble import RandomForestRegressor\nrand_regressor = RandomForestRegressor(n_estimators=100)\nrand_regressor.fit(train_x,train_y)\n\nprint('RandomForestRegressor--------------------------')\nacc = r2_score(test_y,rand_regressor.predict(test_x))\nprint(round(acc,6))\nprint(sum((rand_regressor.predict(test_x) - test_y)**2))\nprint('\\n')\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg = PolynomialFeatures(degree=2)\nX_poly = poly_reg.fit_transform(train_x)\nlin_reg = LinearRegression()\nlin_reg.fit(X_poly,train_y)\n\nprint('Polynomial----------------------------------')\nacc = r2_score(test_y, lin_reg.predict(poly_reg.fit_transform(test_x)))\nprint(round(acc,6))\nprint(sum((lin_reg.predict(poly_reg.fit_transform(test_x)) - test_y)**2))\nprint('\\n')\n\nprint('Linear--------------------------------------')\nlin_reg2 = LinearRegression()\nlin_reg2.fit(train_x,train_y)\n\nacc = r2_score(test_y,lin_reg2.predict(test_x))\nprint(round(acc,6))\nprint(sum((lin_reg2.predict(test_x) - test_y)**2))\nprint('\\n')\n\n'''\n\nLESS TRAINING LINEAR regressION WINS\n\nWITH MORE TRAINING CHOOSE RANDOM FOREST\n\n\nResults =\n1. Polynomial - 7/14 VS DecisionTree - 7/14\n\nGOOD TRAINING\n\n2. linear - 5/13 VS Random - 8/13\n'''\n\n'''\nPolynomial - 4/10 VS DecisionTree - 6/10\n\nLinear - 6/10 VS Random - 4/10\n '''\n","sub_path":"1__ML_TRACK/TESTING/compare_dec_tree_rand_fo.py","file_name":"compare_dec_tree_rand_fo.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167577869","text":"#!/usr/bin/python\n\n'''\n\nmsppg.py Multiwii Serial Protocol Parser Generator\n\nCopyright (C) Rob Jones, Alec Singer, Chris Lavin, Blake Liebling, Simon D. Levy 2015\n\nThis code is free software: you can redistribute it and/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 of the \nLicense, or (at your option) any later version.\n\nThis code is distributed in the hope that it will be useful, \nbut WITHOUT ANY WARRANTY without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License \nalong with this code. If not, see .\n'''\n\nfrom sys import exit, argv, stderr\nfrom subprocess import call\nimport os\nimport json\nfrom pkg_resources import resource_string\nfrom optparse import OptionParser\n\ndef clean(string):\n cleaned_string = string[1: len(string) - 1]\n return cleaned_string\n\ndef mkdir_if_missing(dirname):\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n\ndef error(errmsg):\n print(errmsg)\n exit(1)\n\n\nclass CodeEmitter(object):\n\n def __init__(self, folder, ext):\n\n mkdir_if_missing('output/%s' % folder)\n self._copyfile('%s.makefile' % folder, '%s/Makefile' % folder)\n\n self.indent = ' '\n\n self.type2size = {'byte': 1, 'short' : 2, 'float' : 4, 'int' : 4}\n\n def _copyfile(self, src, dst):\n\n outfile = open('output/' + dst, 'w')\n outfile.write(self._getsrc(src))\n outfile.close()\n\n def warning(self, cmt):\n\n return cmt + ' AUTO-GENERATED CODE: DO NOT EDIT!!!\\n\\n'\n\n # Helper for writing parameter list with type declarations\n def _write_params(self, outfile, argtypes, argnames, prefix = ''):\n\n outfile.write('(')\n outfile.write(prefix)\n for argtype,argname in zip(argtypes, argnames):\n outfile.write(self.type2decl[argtype] + ' ' + argname)\n if argname != argnames[-1]:\n outfile.write(', ')\n outfile.write(')')\n\n\n def _paysize(self, argtypes):\n\n return sum([self.type2size[atype] for atype in argtypes])\n \n def _msgsize(self, argtypes):\n\n return self._paysize(argtypes)\n\n\n def _getsrc(self, filename):\n\n return resource_string('msppg', filename)\n \n def _getargnames(self, message):\n\n return [argname for (argname,_) in self._getargs(message)]\n\n def _getargtypes(self, message):\n\n return [argtype for (_,argtype) in self._getargs(message)]\n\n def _getargs(self, message):\n\n return [(argname,argtype) for (argname,argtype) in \n zip(message[1], message[2]) if argname.lower()!='comment']\n\n\n# Python emitter ============================================================================\n\nclass PythonEmitter(CodeEmitter):\n\n def _copy_example(self, name, protocol):\n\n CodeEmitter._copyfile(self, '%s-%s.py' % (protocol, name), 'python/' + ('%s.py' % name))\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'python', 'py')\n \n self._copy_example('getimu', protocol)\n self._copy_example('getrc', protocol)\n self._copy_example('imudisplay', protocol)\n self._copy_example('setrc', protocol)\n\n mkdir_if_missing('output/python/msppg')\n\n self._copyfile('setup.py', 'python/setup.py')\n\n self.output = open('./output/python/msppg/__init__.py', 'w')\n\n self._write(self.warning('#'))\n\n self.type2pack = {'byte' : 'B', 'short' : 'h', 'float' : 'f', 'int' : 'i'}\n\n self._write(self._getsrc('%s-top-py' % protocol) + '\\n')\n\n for msgtype in msgdict.keys():\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n if msgid < 200:\n self._write(4*self.indent + ('if self.message_id == %d:\\n\\n' % msgstuff[0]))\n self._write(5*self.indent + 'if hasattr(self, \\'' + msgtype + '_Handler\\'):\\n\\n')\n self._write(6*self.indent + 'self.%s_Handler(*struct.unpack(\\'' % msgtype)\n for argtype in self._getargtypes(msgstuff):\n self._write('%s' % self.type2pack[argtype])\n self._write(\"\\'\" + ', self.message_buffer))\\n\\n')\n\n self._write(self._getsrc('bottom-py') + '\\n')\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n if protocol == 'msp':\n\n self._write(self.indent + 'def serialize_' + msgtype + '(self')\n for argname in self._getargnames(msgstuff):\n self._write(', ' + argname)\n self._write('):\\n\\n')\n self._write(self.indent*2 + 'message_buffer = struct.pack(\\'')\n for argtypes in self._getargtypes(msgstuff):\n self._write(self.type2pack[argtype])\n self._write('\\'')\n for argname in self._getargnames(msgstuff):\n self._write(', ' + argname)\n self._write(')\\n\\n')\n self._write(self.indent*2 + \n ('msg = chr(len(message_buffer)) + chr(%s) + message_buffer\\n\\n' % msgid))\n self._write(self.indent*2 + 'return \\'$M%c\\' + msg + chr(_CRC8(msg))\\n\\n' %\n ('>' if msgid < 200 else '<'))\n\n if protocol == 'mavlink' or msgid < 200:\n\n self._write(self.indent + 'def set_%s_Handler(self, handler):\\n\\n' % msgtype) \n self._write(2*self.indent + 'self.%s_Handler = handler\\n\\n' % msgtype)\n\n if protocol == 'msp' and msgid < 200:\n\n self._write(self.indent + 'def serialize_' + msgtype + '_Request(self):\\n\\n')\n self._write(2*self.indent + 'return \\'$M<\\' + chr(0) + chr(%s) + chr(%s)\\n\\n' % \n (msgid, msgid))\n\n def _write(self, s):\n\n self.output.write(s)\n\n# C++ / Arduino emitter ============================================================================\n\nclass CPPEmitter(CodeEmitter):\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'cpp', 'cpp')\n mkdir_if_missing('output/cpp/msppg')\n self._copyfile('msp-example.cpp', 'cpp/msp-example.cpp')\n\n mkdir_if_missing('output/arduino')\n mkdir_if_missing('output/arduino/MSPPG')\n mkdir_if_missing('output/arduino/MSPPG/examples')\n mkdir_if_missing('output/arduino/MSPPG/examples/imuexample')\n self._copyfile('msp-imuexample.ino', 'arduino/MSPPG/examples/imuexample/msp-imuexample.ino')\n\n self.type2decl = {'byte': 'byte', 'short' : 'short', 'float' : 'float', 'int' : 'int'}\n\n self.coutput = open('./output/cpp/msppg/msppg.cpp', 'w')\n self.houtput = open('./output/cpp/msppg/msppg.h', 'w')\n\n self.acoutput = open('./output/arduino/MSPPG/msppg.cpp', 'w')\n self.ahoutput = open('./output/arduino/MSPPG/msppg.h', 'w')\n\n self._cwrite(self.warning('//'))\n\n self._hwrite(self._getsrc('msp-top-h'))\n \n self._cwrite('\\n' + self._getsrc('msp-top-cpp'))\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n self._hwrite(self.indent*2 + 'MSP_Message serialize_%s' % msgtype)\n self._write_params(self.houtput, argtypes, argnames)\n self._write_params(self.ahoutput, argtypes, argnames)\n self._hwrite(';\\n\\n')\n\n # Write handler code for incoming messages\n if msgid < 200:\n\n self._cwrite(5*self.indent + ('case %s: {\\n\\n' % msgdict[msgtype][0]))\n nargs = len(argnames)\n offset = 0\n for k in range(nargs):\n argname = argnames[k]\n argtype = argtypes[k]\n decl = self.type2decl[argtype]\n self._cwrite(6*self.indent + decl + ' ' + argname + ';\\n')\n self._cwrite(6*self.indent + \n 'memcpy(&%s, &this->message_buffer[%d], sizeof(%s));\\n\\n' % \n (argname, offset, decl))\n offset += self.type2size[argtype]\n self._cwrite(6*self.indent + 'this->handlerFor%s->handle_%s(' % (msgtype, msgtype))\n for k in range(nargs):\n self._cwrite(argnames[k])\n if k < nargs-1:\n self._cwrite(', ')\n self._cwrite(');\\n')\n self._cwrite(6*self.indent + '} break;\\n\\n')\n \n self._hwrite(self.indent*2 + 'MSP_Message serialize_%s_Request();\\n\\n' % msgtype)\n self._hwrite(self.indent*2 + \n 'void set_%s_Handler(class %s_Handler * handler);\\n\\n' % (msgtype, msgtype))\n\n self._hwrite(self.indent + 'private:\\n\\n')\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n \n if msgid < 200:\n self._hwrite(2*self.indent + \n 'class %s_Handler * handlerFor%s;\\n\\n' % (msgtype, msgtype));\n\n self._hwrite('};\\n');\n\n self._cwrite(self._getsrc('bottom-cpp'))\n \n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n # Incoming messages\n if msgid < 200:\n\n # Declare handler class\n self._hwrite('\\n\\n' + 'class %s_Handler {\\n' % msgtype)\n self._hwrite('\\n' + self.indent + 'public:\\n\\n')\n self._hwrite(2*self.indent + '%s_Handler() {}\\n\\n' % msgtype)\n self._hwrite(2*self.indent + 'virtual void handle_%s' % msgtype)\n self._write_params(self.houtput, argtypes, argnames)\n self._write_params(self.ahoutput, argtypes, argnames)\n self._hwrite('{ }\\n\\n')\n self._hwrite('};\\n\\n')\n \n # Write handler method\n self._cwrite('void MSP_Parser::set_%s_Handler(class %s_Handler * handler) {\\n\\n' %\n (msgtype, msgtype))\n self._cwrite(self.indent + 'this->handlerFor%s = handler;\\n' % msgtype)\n self._cwrite('}\\n\\n')\n\n # Write request method\n self._cwrite('MSP_Message MSP_Parser::serialize_%s_Request() {\\n\\n' % msgtype)\n self._cwrite(self.indent + 'MSP_Message msg;\\n\\n')\n self._cwrite(self.indent + 'msg.bytes[0] = 36;\\n')\n self._cwrite(self.indent + 'msg.bytes[1] = 77;\\n')\n self._cwrite(self.indent + 'msg.bytes[2] = %d;\\n' % 60 if msgid < 200 else 62)\n self._cwrite(self.indent + 'msg.bytes[3] = 0;\\n')\n self._cwrite(self.indent + 'msg.bytes[4] = %d;\\n' % msgid)\n self._cwrite(self.indent + 'msg.bytes[5] = %d;\\n\\n' % msgid)\n self._cwrite(self.indent + 'msg.len = 6;\\n\\n')\n self._cwrite(self.indent + 'return msg;\\n')\n self._cwrite('}')\n\n\n # Add parser method for serializing message\n self._cwrite('MSP_Message MSP_Parser::serialize_%s' % msgtype)\n self._write_params(self.coutput, argtypes, argnames)\n self._write_params(self.acoutput, argtypes, argnames)\n self._cwrite(' {\\n\\n')\n self._cwrite(self.indent + 'MSP_Message msg;\\n\\n')\n msgsize = self._msgsize(argtypes)\n self._cwrite(self.indent + 'msg.bytes[0] = 36;\\n')\n self._cwrite(self.indent + 'msg.bytes[1] = 77;\\n')\n self._cwrite(self.indent + 'msg.bytes[2] = 62;\\n')\n self._cwrite(self.indent + 'msg.bytes[3] = %d;\\n' % msgsize)\n self._cwrite(self.indent + 'msg.bytes[4] = %d;\\n\\n' % msgid)\n nargs = len(argnames)\n offset = 5\n for k in range(nargs):\n argname = argnames[k]\n argtype = argtypes[k]\n decl = self.type2decl[argtype]\n self._cwrite(self.indent + \n 'memcpy(&msg.bytes[%d], &%s, sizeof(%s));\\n' % (offset, argname, decl))\n offset += self.type2size[argtype]\n self._cwrite('\\n')\n self._cwrite(self.indent + \n 'msg.bytes[%d] = CRC8(&msg.bytes[3], %d);\\n\\n' % (msgsize+5, msgsize+2))\n self._cwrite(self.indent + 'msg.len = %d;\\n\\n' % (msgsize+6))\n self._cwrite(self.indent + 'return msg;\\n')\n self._cwrite('}\\n\\n')\n \n def _cwrite(self, s):\n\n self.coutput.write(s)\n self.acoutput.write(s)\n\n def _hwrite(self, s):\n\n self.houtput.write(s)\n self.ahoutput.write(s)\n\n# Java emitter =======================================================================================\n\nclass JavaEmitter(CodeEmitter):\n\n def __init__(self, msgdict, protocol):\n\n CodeEmitter.__init__(self, 'java', 'java')\n\n self._copyfile('msp-example.java', 'java/msp-example.java')\n\n mkdir_if_missing('output/java/edu')\n mkdir_if_missing('output/java/edu/wlu')\n mkdir_if_missing('output/java/edu/wlu/cs')\n mkdir_if_missing('output/java/edu/wlu/cs/msppg')\n\n self.type2decl = {'byte': 'byte', 'short' : 'short', 'float' : 'float', 'int' : 'int'}\n self.type2bb = {'byte': '', 'short' : 'Short', 'float' : 'Float', 'int' : 'Int'}\n\n self.output = open('./output/java/edu/wlu/cs/msppg/MSP_Parser.java', 'w')\n\n self._write(self.warning('//'))\n\n self._write(self._getsrc('msp-top-java'))\n\n # Write handler cases for incoming messages\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n if msgid < 200:\n\n self._write(6*self.indent + 'case (byte)%d:\\n' % msgid)\n self._write(7*self.indent + 'if (this.%s_handler != null) {\\n' % msgtype)\n self._write(8*self.indent + 'this.%s_handler.handle_%s(\\n' % (msgtype, msgtype));\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n nargs = len(argnames)\n\n offset = 0\n for k in range(nargs):\n argtype = argtypes[k]\n self._write(8*self.indent + 'bb.get%s(%d)' % (self.type2bb[argtype], offset))\n offset += self.type2size[argtype]\n if k < nargs-1:\n self._write(',\\n')\n self._write(');\\n')\n\n self._write(7*self.indent + '}\\n')\n self._write(7*self.indent + 'break;\\n\\n')\n\n self._write(self._getsrc('bottom-java'))\n\n for msgtype in msgdict.keys():\n\n msgstuff = msgdict[msgtype]\n msgid = msgstuff[0]\n\n argnames = self._getargnames(msgstuff)\n argtypes = self._getargtypes(msgstuff)\n\n # For messages from FC\n if msgid < 200:\n\n # Declare handler\n self._write(self.indent + 'private %s_Handler %s_handler;\\n\\n' % (msgtype, msgtype))\n self._write(self.indent + \n 'public void set_%s_Handler(%s_Handler handler) {\\n\\n' % (msgtype, msgtype))\n self._write(2*self.indent + 'this.%s_handler = handler;\\n' % msgtype)\n self._write(self.indent + '}\\n\\n')\n\n # Write serializer for requests\n self._write(self.indent + 'public byte [] serialize_%s_Request() {\\n\\n' % msgtype)\n paysize = self._paysize(argtypes)\n msgsize = self._msgsize(argtypes)\n self._write('\\n' + 2*self.indent + 'byte [] message = new byte[6];\\n\\n')\n self._write(2*self.indent + 'message[0] = 36;\\n')\n self._write(2*self.indent + 'message[1] = 77;\\n')\n self._write(2*self.indent + 'message[2] = 60;\\n')\n self._write(2*self.indent + 'message[3] = 0;\\n')\n self._write(2*self.indent + 'message[4] = (byte)%d;\\n' % msgid)\n self._write(2*self.indent + 'message[5] = (byte)%d;\\n\\n' % msgid)\n self._write(2*self.indent + 'return message;\\n')\n self._write(self.indent + '}\\n\\n')\n\n # Write serializer method for messages from FC\n self._write(self.indent + 'public byte [] serialize_%s' % msgtype)\n self._write_params(self.output, argtypes, argnames)\n self._write(' {\\n\\n')\n paysize = self._paysize(argtypes)\n msgsize = self._msgsize(argtypes)\n self._write(2*self.indent + 'ByteBuffer bb = newByteBuffer(%d);\\n\\n' % paysize)\n for (argname,argtype) in zip(argnames,argtypes):\n self._write(2*self.indent + 'bb.put%s(%s);\\n' % (self.type2bb[argtype], argname))\n self._write('\\n' + 2*self.indent + 'byte [] message = new byte[%d];\\n' % (msgsize+6))\n self._write(2*self.indent + 'message[0] = 36;\\n')\n self._write(2*self.indent + 'message[1] = 77;\\n')\n self._write(2*self.indent + 'message[2] = %d;\\n' % (62 if msgid < 200 else 60))\n self._write(2*self.indent + 'message[3] = %d;\\n' % msgsize)\n self._write(2*self.indent + 'message[4] = (byte)%d;\\n' %msgdict[msgtype][0]) \n self._write(2*self.indent + 'byte [] data = bb.array();\\n')\n self._write(2*self.indent + 'for (int k=0; k 2:\r\n\t\t\treturn i\r\n\t\tz = z*z + point\r\n\treturn 0\r\n\r\n\r\n# Main function intialises & creates grid. Dependent on _mandel_calc & _plotting.\r\ndef fn_mandelbrot_main(x_min, x_max, y_min, y_max, num_grid_pts, tolerance):\r\n\treal = np.linspace(x_min, x_max, num_grid_pts)\r\n\timag = np.linspace(y_min, y_max, num_grid_pts)\r\n\tvalues = np.empty((num_grid_pts, num_grid_pts))\r\n\tfor i in range(num_grid_pts):\r\n\t\tfor j in range(num_grid_pts):\r\n\t\t\tvalues[j, i] = fn_mandel_calc(real[i] + 1j*imag[j], tolerance)\r\n\tfn_plotting(values, tolerance, x_min, x_max, y_min, y_max)\r\n\treturn\r\n\r\nprint(\"This code will compute the mandelbrot set for a user defined number of points between uer defined boundaries.\\n\")\r\nprint(\"The tolerance is the number of times a specific point will be interated on to determine if it is in the set.\\n\")\r\nprint(\"A plot is saved to file and then printed to screen.\\n\")\r\nprint(\"Note that -2 -> x -> 2 & -2 -> y -> 2 encompass the set.\\n\")\r\n\r\n# Sample grids to run.\r\n# _mandelbrot_main(-2, 2, -2, 2, 1000, 100)\r\n# _mandelbrot_main(0, .5, .5, 1.0, 1000, 100)\r\n# _mandelbrot_main(.5, .6, .3, .4, 1000, 100)\r\n# _mandelbrot_main(.34, .36, .50, 5.2, 1000, 100\r\n# _mandelbrot_main(.30, .32, .56, .58, 1000, 100)\r\n# _mandelbrot_main(.36, .38, .58, .60, 1000, 50)\r\n\r\nG_x_min = float(input(\"Input x_min:\"))\r\nG_x_max = float(input(\"Input x_max:\"))\r\nG_y_min = float(input(\"Input y_min:\"))\r\nG_y_max = float(input(\"Input y_max:\"))\r\nG_num_grid_pts = int(input(\"Input num_grid_pts:\"))\r\nG_tolerance = int(input(\"Input tolerance:\"))\r\n\r\nprint('Computing set ...')\r\nfn_mandelbrot_main(G_x_min, G_x_max, G_y_min, G_y_max, G_num_grid_pts, G_tolerance)\r\n","sub_path":"Mandelbrot_Main.py","file_name":"Mandelbrot_Main.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483800912","text":"# coding=utf-8\n# from . import downloader, outputer, html_parser, html_arranger, spider_config\nimport downloader, outputer, html_arranger, html_parser, spider_config\n\n\nclass spider_main(object):\n def __init__(self):\n self.downloader = downloader.downloader()\n self.outputer = outputer.Outputer()\n self.parser = html_parser.Parser()\n self.arrange = html_arranger.Arrange()\n\n def craw(self, root_url, pic_type):\n content = self.downloader.download(root_url)\n parse_data = self.parser.html_parse(content)\n return_data = self.outputer.output(parse_data, pic_type)\n if return_data['errcode'] == 0:\n print('success!!!!!!')\n\n\nif __name__ == \"__main__\":\n data_list = spider_config.SpiderConfig().url_config()\n for data in data_list:\n root_url = data['url']\n pic_type = data['type']\n object_spider = spider_main()\n object_spider.craw(root_url, pic_type)\n","sub_path":"Camera/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"206133476","text":"\nimport sys\nsys.path.insert(0, '..')\n\nfrom utils import data\nimport os\nimport sklearn\nimport numpy as np\nimport pandas as pd\nfrom sklearn.svm import SVR\nfrom sklearn.model_selection import train_test_split\nimport json\n\n# ------------ HYPERPARAMETERS -------------\nBASE_PATH = '../COVID-19/csse_covid_19_data/'\n# time_window = 28\ntime_windows = [5, 14, 20]\nkernels = ['rbf', 'sigmoid']\nconfirmed = os.path.join(\n BASE_PATH, \n 'csse_covid_19_time_series',\n 'covid_time_series_converted_US.csv')\n# ------------------------------------------\n\nif __name__ == \"__main__\":\n # ----------- Feature Processing -----------\n print(\"🌈 Feature processing\")\n confirmed = data.load_csv_data(confirmed)\n\n cases, labels = data.get_cases_chronologically(confirmed)\n\n # ---------- Training and Testing ----------\n loss_data = []\n for k in kernels:\n for w in time_windows:\n names, features, targets, targets_smoothed = data.make_features_smoothed(cases, labels, w)\n names, features, targets, targets_smoothed = data.select_random_smoothed(100, names, features, targets, targets_smoothed)\n regre = SVR(kernel=k)\n X_train, X_test, y_train, y_test, s_train, s_test = data.train_test_split_triple(features, targets, targets_smoothed, test_size=0.2)\n print(\"🏃🏻‍♂️ Started training (Kernel: %s, Window: %d)\" % (k, w))\n regre.fit(X_train, y_train)\n print(\"✨ Testing\")\n print(X_test, y_test)\n loss = regre.score(X_test, y_test)\n print(X_test, s_test)\n loss_s = regre.score(X_test, s_test)\n print(\"💯 Loss: \", loss)\n print(\"💯 Loss (smoothed): \", loss_s)\n loss_data.append([k, w, loss, loss_s])\n\n pd.DataFrame(loss_data).to_csv(\"results/SVR_diff_smoothed.csv\")","sub_path":"exp/exp_smooth_svr.py","file_name":"exp_smooth_svr.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287304513","text":"# title : crawling event data in pathetic old Korean marathon website\n# website : http://www.roadrun.co.kr/schedule/\n# Korean : 마라톤 웹사이트 이벤트(2016부터) 데이터 크롤링\n\n# -*- coding: utf-8 -*-\nimport re\nimport datetime\nimport requests\nimport json\nimport forecastio\nfrom bs4 import BeautifulSoup\n\ntoday = datetime.datetime.now()\nprint('Working Date : {}'.format(today))\n\n# count total annual event\ndef count_annual_event():\n read = requests.get(\"http://www.roadrun.co.kr/schedule/list.php?today=1451574000&todays=Y\")\n soup = BeautifulSoup(read.content, 'html.parser')\n try:\n table = soup.find('body').find_all('table')[10:11]\n trs = [tr for tr in table][0].find_all('tr')\n total = int(len(trs)/2)\n if total == 0:\n print(\"Can't read data table from original website\")\n else:\n print(\"Ready to crawl {} marathon events since 2016.\".format(total))\n\n except:\n print(\"Can't crawl data from website.\")\n return(total)\n\ndef extract_event_data(url):\n read = requests.get(str(url))\n read.encoding = 'euc-kr'\n soup = BeautifulSoup(read.content, 'html.parser')\n table = soup.find_all('table')[1]\n info = [s.strip() for s in table.text.splitlines() if s]\n info = list(filter(None, info))[1::2]\n #join description\n info[11:len(info)] = [' '.join(info[11:len(info)])]\n return(info)\n\ndef get_all_events_data(start):\n #store all data in empty list\n all_data = []\n total = int(count_annual_event())\n #get final URL query\n end = int(start) + total\n print(\"Collecting data... wait for a second.\")\n try:\n for i in range(start, end):\n url = 'http://www.roadrun.co.kr/schedule/view.php?no={}'.format(i)\n new_data = extract_event_data(url) #values\n if len(new_data) != 9:\n all_data.append(new_data)\n print(\"Merge all events data...\")\n except:\n print(\"Fail to read contents\")\n print(\"{} events are empty.\".format(total-len(all_data)))\n return(data_formatting(all_data))\n\ndef data_formatting(data):\n keys = [\"title\", \"host\", \"email\", \"date\", \"phone\", \"race\", \"city\",\n \"location\", \"host\", \"application_period\", \"website\", \"description\",\n \"latitude\", \"longitude\", \"map_url\", \"temperature\", \"weather\"]\n\n #str_keys = ['대회명', '대표자명', 'E-mail', '대회일시', '전화번호', '대회종목',\n # '대회지역', '대회장소', '주최단체', '접수기간', '홈페이지', '기타소개']\n\n #formatted date string:\n for i in range(len(data)):\n #remove empty data string\n data[i] = [x.replace(x, '.') if x in keys else x for x in data[i]]\n # formatted 'date'\n date = list(map(int, re.findall('\\d+', data[i][3])))\n # wrong user input\n # covert 12 hour to 24 hour\n if '오후' in data[i][3]:\n date[3] += 12\n # wrong user input (1000 hour or 1300 hour)\n date = [10 if x==1000 else x for x in date]\n date = [13 if x==1300 else x for x in date]\n data[i][3] = datetime.datetime(*date).strftime(\"%Y/%m/%d %H:%M\")\n\n # formatted 'application_period'\n try:\n data[i][9] = '{}/{}/{} - {}/{}/{}'.format(*(re.findall('\\d+', data[i][9])))\n except IndexError:\n print(\"Found unexpected 'application_period' type. But it will be ignored.\")\n pass\n\n #get location data\n location = re.sub(',', ' ', data[i][7])\n #get map data\n geocode = get_map_data(location)\n #get weather data\n weather = get_weather_data(geocode[0], geocode[1], date)\n data[i] = [*data[i], *geocode, *weather]\n\n data[i] = dict(zip(keys, data[i]))\n data = sorted(data, key=lambda k: k['date'], reverse=True)\n print('Data formatting...')\n return(data)\n\n# daum mpa API\ndef get_map_data(place):\n baseUrl = 'https://apis.daum.net/local/v1/search/keyword.json'\n params = {'apikey':'317394cebdea4b6359a849bcf994be38', 'sort':1, 'query':place}\n content = requests.get(baseUrl, params=params).json()\n mapData = content['channel']['item']\n try:\n if len(mapData) == 0: #can't search place\n place = ' '.join(place.split()[:-1])\n return (get_map_data(place))\n else:\n mapData = mapData[0]\n map_list = [mapData['latitude'], mapData['longitude'], 'http://map.daum.net/link/map/{}'.format(mapData['id'])]\n return (map_list)\n except KeyError:\n map_list = ['', '', '']\n return (map_list)\n\n# forcase.io API\ndef get_weather_data(latitude, longitude, date):\n apikey = \"d5e9ae1a96b8e4a1509ceba9e8ebd92d\"\n formatted_date = datetime.datetime(*date)\n if len(longitude) == 0:\n weather_list = ['', 'null']\n return(weather_list)\n else:\n try:\n forecast = forecastio.load_forecast(apikey, latitude, longitude, time=formatted_date)\n weather = forecast.currently()\n weather_list = [('{}°C'.format(weather.temperature)), weather.icon]\n return(weather_list)\n except:\n weather_list = ['', 'null']\n return(weather_list)\n\n# read evevnt data since first event in 2016\n# link: http://www.roadrun.co.kr/schedule/view.php?no=6198\nall_data = (get_all_events_data(6198))\nprint(\"Ready to save {} events in file\".format(len(all_data)))\n\nwith open(\"event_data.py\", \"w\") as f:\n try:\n f.write('# -*- coding: utf-8 -*-\\nevent_dict={}'.format(str(all_data)))\n print(\"event_data.py Updated all data successfully!\")\n except:\n print(\"event_data.py Error processing\")\n","sub_path":"myrun/event_script.py","file_name":"event_script.py","file_ext":"py","file_size_in_byte":5663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434688791","text":"from chem_lex.ChemlabTokens import unit_prefix, supported_units\n#import\nfrom element import Element\ndef convertTo(el, num, Unit, newUnit):\n ### need to redo with the parser\n if(Unit in unit_prefix and newUnit in unit_prefix):\n result = convertPrefix(num,Unit,newUnit)\n elif (Unit in supported_units and newUnit in supported_units):\n result = convertUnit(el, num,Unit,newUnit)\n elif(Unit == 'None'):\n Unit='base'\n result = convertPrefix(num,Unit,newUnit)\n elif(newUnit=='None'):\n newUnit='base'\n result = convertPrefix(num,Unit,newUnit)\n else:\n raise TypeError(\"Invalid Units\")\n return result\n\ndef convertWeight(el ,num, Unit, newUnit):\n ### Converts weight related to an element\n if not isinstance(el, Element):\n raise TypeError(\"Not an element. Cannot perform operation\")\n else:\n amu = el.dictionary['atomic_weight']\n if(Unit=='g'):\n if(newUnit=='mol'):\n result= num/amu\n elif(newUnit=='atoms'):\n mol = num/amu\n result = mol * (6.02*(10**23))\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit == 'mol'):\n if newUnit=='atoms':\n result = result = num*(6.02*(10**23))\n if newUnit=='g':\n result = num*amu\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='atoms'):\n if newUnit=='mol':\n result = num/(6.02*(10**23))\n if newUnit=='g':\n mol = num/(6.02*(10**23))\n result = mol * amu\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n\n return result\n\n\npre = {'G': 10**9, # GIGA\n'M': 10**6, # MEGA\n'k': 10**3, # KILO\n'h': 10**2, # HECTOR\n'da': 10**1, # DEKA\n'base':1,\n'd': 10**(-1), # DECI\n'c': 10**(-2), # CENTI\n'm': 10**(-3), # MILLI\n'u': 10**(-6), # MICRO\n'n': 10**(-9), # NANO\n'p': 10**(-12), # PICO\n'f': 10**(-15),\n}\ndef convertPrefix(num,Unit,newUnit):\n CNum = num * pre[Unit]\n result = CNum/pre[newUnit]\n return result\n\nLongitud = {'ft','me','mi'}\nWeight = {'g','mol','atoms'}\nTemp = {'K','C','F'}\n\ndef convertUnit(el, num , Unit,newUnit):\n if (Unit in Longitud):\n result = convertLong(num, Unit,newUnit)\n elif (Unit in Weight):\n result = convertWeight(el,num, Unit,newUnit)\n elif (Unit in Temp):\n result = convertTemp(num, Unit,newUnit)\n return result\n\ndef convertLong(num, Unit,newUnit):\n if (Unit == 'ft'):\n if (newUnit=='me'):\n result = num/3.2808\n elif newUnit=='mi':\n result = num/5280\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif Unit == 'me':\n if newUnit == 'ft':\n result = num*3.2808\n elif newUnit=='mi':\n result = num/1609\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n\n elif Unit == 'mi':\n if newUnit == 'ft':\n result = num*5280\n elif newUnit=='me':\n result = num*1609\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n return result\n\n\ndef convertTemp(num, Unit, newUnit):\n if(Unit=='K'):\n if(newUnit=='C'):\n result = num - 273.15\n elif(newUnit=='F'):\n result = num * (9/5) - 459.67\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='C'):\n if(newUnit=='K'):\n result = num + 273.15\n elif(newUnit=='F'):\n result = (num * (9/5)) + 32\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n elif(Unit=='F'):\n if(newUnit=='C'):\n result = (num -32) * (5/9)\n elif(newUnit=='K'):\n result = (num +459.67 )*(5/9)\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n else:\n raise TypeError(\"It's not possible to make that conversion\")\n return result\n","sub_path":"src/feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474109481","text":"\"\"\"\r\nsource:\r\nhttps://stackoverflow.com/questions/65498782/how-to-dump-confusion-matrix-using-tensorboard-logger-in-pytorch-lightning\r\nhttps://pytorch-lightning.readthedocs.io/en/latest/starter/introduction_guide.html\r\nhttps://medium.com/pytorch/introduction-to-captum-a-model-interpretability-library-for-pytorch-d236592d8afa\r\nhttps://en.wikipedia.org/wiki/Multinomial_distribution\r\n\"\"\"\r\n\r\nimport torch\r\nimport cv2\r\nimport os\r\nimport json\r\nimport torch.nn as nn\r\nimport numpy as np\r\nfrom pathlib import Path\r\nimport torchvision\r\nfrom torchvision import datasets, models, transforms\r\nfrom torch.utils.data.sampler import Sampler\r\nimport albumentations as A\r\nfrom albumentations.pytorch import ToTensorV2\r\nimport pytorch_lightning as pl\r\nfrom pytorch_lightning import Trainer\r\nfrom sklearn.metrics import accuracy_score, confusion_matrix\r\nfrom matplotlib import pyplot as plt\r\nimport itertools\r\n\r\n\r\nclass AlbumentationsTransform:\r\n def __init__(self):\r\n self.img_transforms = A.Compose(\r\n [\r\n A.Resize(224, 224), A.RGBShift(), A.HorizontalFlip(p=0.5),\r\n A.VerticalFlip(p=0.2), A.ChannelShuffle(0.2), A.ColorJitter(p=0.5),\r\n A.Cutout(num_holes=3, max_h_size=24, max_w_size=24, \r\n fill_value=0, always_apply=False, p=0.5),\r\n A.ShiftScaleRotate(scale_limit=0.5, rotate_limit=0, shift_limit=0.1, p=1, border_mode=0),\r\n A.PadIfNeeded(min_height=224, min_width=224, always_apply=True, border_mode=0),\r\n A.IAAAdditiveGaussianNoise(p=0.2),\r\n A.IAAPerspective(p=0.5),\r\n A.RandomBrightnessContrast(p=0.5),\r\n A.OneOf(\r\n [\r\n A.CLAHE(p=1),\r\n A.RandomBrightness(p=1),\r\n A.RandomGamma(p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.OneOf(\r\n [\r\n A.IAASharpen(p=1),\r\n A.Blur(blur_limit=3, p=1),\r\n A.MotionBlur(blur_limit=3, p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.OneOf(\r\n [\r\n A.RandomContrast(p=1),\r\n A.HueSaturationValue(p=1),\r\n ],\r\n p=0.9,\r\n ),\r\n A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),\r\n ToTensorV2(),\r\n ])\r\n def __call__(self, img):\r\n img = np.array(img)\r\n return self.img_transforms(image = img).copy()\r\n\r\n\r\nclass ImbalancedDatasetSampler(Sampler):\r\n def __init__(self, dataset):\r\n self.indices = list(range(len(dataset)))\r\n self.num_samples = len(self.indices)\r\n label_to_count = {}\r\n for idx in self.indices:\r\n label = self._get_label(dataset, idx)\r\n if label in label_to_count:\r\n label_to_count[label] += 1\r\n else:\r\n label_to_count[label] = 1\r\n weights = [1.0 / label_to_count[self._get_label(dataset, idx)]\r\n for idx in self.indices]\r\n self.weights = torch.DoubleTensor(weights)\r\n\r\n def _get_label(self, dataset, idx):\r\n return dataset[idx][1]\r\n\r\n def __iter__(self):\r\n # torch.multinomial - Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribution\r\n # located in the corresponding row of tensor input.\r\n return (self.indices[i] for i in torch.multinomial(\r\n self.weights, self.num_samples, replacement=True))\r\n\r\n def __len__(self):\r\n return self.num_samples\r\n\r\n\r\nclass ClassificationTrainer(pl.LightningModule):\r\n def __init__(self, hparams = {\r\n 'epochs_num': 100,\r\n 'batch_size': 32,\r\n 'lr': 0.001,\r\n \"train_valid_test_split\": [0.8, 0.1, 0.1],\r\n }, model_type='resnet50',\r\n dataset_path = 'dataset',\r\n folders_structure = {\r\n \"models_folder\": str(Path(__file__).parent / \"models\"),\r\n \"confusion_matrix_folder\": str(Path(__file__).parent / \"confusion_matrix\"),\r\n \"test_img_folder\": str(Path(__file__).parent / \"test_img_folder\"),\r\n \"metadata_json_folder\": str(Path(__file__).parent / \"metadata_json\")\r\n }):\r\n super().__init__()\r\n self._hparams = hparams\r\n self.model_type = model_type\r\n self.dataset_path = dataset_path\r\n self.folders_structure = folders_structure\r\n self.model_metadata = {\r\n 'hparams': hparams,\r\n 'model_type':model_type,\r\n 'dataset_path': dataset_path, \r\n 'folders_structure': folders_structure\r\n }\r\n\r\n self.img_transform = transforms.Compose([AlbumentationsTransform()])\r\n self.criterion = nn.CrossEntropyLoss()\r\n\r\n self.model = self._load_specific_model()\r\n self._split_dataset_to_dataloaders_and_return_classes()\r\n self._create_dir_structure()\r\n\r\n self.last_best_valid_error = 10000000000.0\r\n self.test_images = []\r\n self.test_losses = []\r\n self.test_true = []\r\n self.test_pred = []\r\n\r\n def _load_specific_model(self):\r\n number_of_classes = self._get_number_of_classes()\r\n if self.model_type == 'resnet50':\r\n model = models.resnet50(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet50'\r\n elif self.model_type == 'resnet18':\r\n model = models.resnet18(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(512, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet18'\r\n elif self.model_type == 'resnet34':\r\n model = models.resnet34(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet34'\r\n elif self.model_type == 'resnet101':\r\n model = models.resnet101(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet101'\r\n elif self.model_type == 'resnet152':\r\n model = models.resnet152(pretrained=True).to(self.device)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.fc = nn.Sequential(\r\n nn.Linear(2048, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'resnet152'\r\n elif self.model_type == 'vgg16':\r\n model = models.vgg16(pretrained=True)\r\n for param in model.parameters():\r\n param.requires_grad = False\r\n model.classifier = nn.Sequential(\r\n nn.Linear(25088, 128),\r\n nn.ReLU(inplace=True),\r\n nn.Linear(128, number_of_classes)).to(self.device)\r\n model = model.to(self.device)\r\n model.name = 'vgg16'\r\n return model\r\n\r\n def _get_number_of_classes(self):\r\n return len([ f.path for f in os.scandir(self.dataset_path) if f.is_dir() ])\r\n\r\n def _split_dataset_to_dataloaders_and_return_classes(self):\r\n dataset = datasets.ImageFolder(self.dataset_path, self.img_transform)\r\n self.classes = dataset.classes\r\n self.class_to_idx = dataset.class_to_idx\r\n self.model_metadata.update(\r\n {\r\n 'classes': self.classes,\r\n 'class_to_idx': self.class_to_idx,\r\n }\r\n )\r\n train_size = int(self._hparams['train_valid_test_split'][0]*len(dataset))\r\n valid_size = int(self._hparams['train_valid_test_split'][1]*len(dataset))\r\n test_size = int(self._hparams['train_valid_test_split'][2]*len(dataset))\r\n rest = len(dataset) - train_size - valid_size - test_size\r\n train_size += rest\r\n train_set, valid_set, test_set = torch.utils.data.random_split(dataset,\r\n [train_size, valid_size, test_size])\r\n self.train_set = train_set\r\n self.valid_set = valid_set\r\n self.test_set = test_set\r\n\r\n def _create_dir_structure(self):\r\n for _, path in self.folders_structure.items():\r\n os.makedirs(path, exist_ok=True)\r\n\r\n def forward(self, x):\r\n return self.model(x)\r\n\r\n def train_dataloader(self):\r\n train_dataloader = torch.utils.data.DataLoader(self.train_set,\r\n sampler=ImbalancedDatasetSampler(self.train_set),\r\n batch_size=self._hparams['batch_size'])\r\n return train_dataloader\r\n \r\n def val_dataloader(self):\r\n val_dataloader = torch.utils.data.DataLoader(self.valid_set, sampler=ImbalancedDatasetSampler(self.valid_set),\r\n batch_size=self.hparams['batch_size'])\r\n return val_dataloader\r\n\r\n def test_dataloader(self):\r\n test_dataloader = torch.utils.data.DataLoader(self.test_set, sampler=ImbalancedDatasetSampler(self.test_set),\r\n batch_size=self.hparams['batch_size'])\r\n return test_dataloader\r\n\r\n def training_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('train_loss', loss)\r\n return loss\r\n\r\n def validation_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('valid_loss', loss)\r\n\r\n ps = torch.exp(pred)\r\n top_p, top_class = ps.topk(1, dim=1)\r\n equals = top_class == y.view(*top_class.shape)\r\n accuracy = torch.mean(equals.type(torch.FloatTensor)).item()\r\n self.log('accuracy_loss', accuracy)\r\n if loss < self.last_best_valid_error:\r\n self.last_best_valid_error = loss\r\n self.save_model(loss=loss.item(), acc=accuracy, mode='valid')\r\n return loss\r\n\r\n def test_step(self, batch, batch_nb):\r\n x,y = batch\r\n if isinstance(x, dict):\r\n x = x['image']\r\n pred = self(x)\r\n loss = self.criterion(pred, y)\r\n self.log('test_loss_per_batch', loss)\r\n\r\n ps = torch.exp(pred)\r\n top_p, top_class = ps.topk(1, dim=1)\r\n equals = top_class == y.view(*top_class.shape)\r\n accuracy = torch.mean(equals.type(torch.FloatTensor)).item()\r\n self.log('test_accuracy_per_batch', accuracy)\r\n\r\n self.test_images.append(x)\r\n self.test_losses.append(loss.item())\r\n self.test_true += y.tolist()\r\n self.test_pred += top_class.tolist()\r\n return loss\r\n\r\n def test_epoch_end(self, outputs):\r\n test_img_paths = self.save_and_convert_test_images_to_paths(self.test_images)\r\n self.test_pred = [ i[0] for i in self.test_pred ]\r\n\r\n loss = sum(self.test_losses) / len(self.test_losses)\r\n self.log('test_loss_per_epoch', loss)\r\n\r\n accuracy = accuracy_score(self.test_true, self.test_pred)\r\n self.log('test_accuracy_per_epoch', accuracy)\r\n\r\n conf_matrix = confusion_matrix(self.test_true, self.test_pred)\r\n conf_matrix_path = os.path.join(self.folders_structure['confusion_matrix_folder'], 'conf_matrix_plot.jpg')\r\n plot_confusion_matrix(conf_matrix, conf_matrix_path, self.classes)\r\n\r\n self.model_metadata.update(\r\n {\r\n 'y_true': self.test_true,\r\n 'y_pred': self.test_pred,\r\n 'test_accuracy': accuracy,\r\n 'test_loss': loss,\r\n 'conf_matrix': conf_matrix.tolist()\r\n }\r\n )\r\n self.save_metadata()\r\n self.save_model(loss=loss, acc=accuracy, mode='test')\r\n return \r\n\r\n def save_and_convert_test_images_to_paths(self, test_images):\r\n test_images_paths = []\r\n for batch_idx , test_image in enumerate(test_images):\r\n if test_image.shape[0] > 1:\r\n for image_idx , i_image in enumerate(test_image):\r\n i_image = self._inv_normalize_tensor(i_image)\r\n img_path = os.path.join(self.folders_structure['test_img_folder'], str(batch_idx) + '_'+ str(image_idx)+'.jpg')\r\n torchvision.utils.save_image(i_image, img_path)\r\n test_images_paths.append(img_path)\r\n else:\r\n test_image = self._inv_normalize_tensor(test_image)\r\n img_path = os.path.join(self.folders_structure['test_img_folder'], str(batch_idx) + '.jpg')\r\n torchvision.utils.save_image(test_image, img_path)\r\n test_images_paths.append(img_path)\r\n return test_images_paths\r\n\r\n def _inv_normalize_tensor(self, tensor):\r\n tensor = torch.squeeze(tensor, 0)\r\n inv_normalize = transforms.Normalize(\r\n mean=[-0.485/0.229, -0.456/0.224, -0.406/0.255],\r\n std=[1/0.229, 1/0.224, 1/0.255]\r\n )\r\n return inv_normalize(tensor)\r\n\r\n def configure_optimizers(self):\r\n return torch.optim.Adam(self.model.parameters(), lr=self._hparams['lr'])\r\n\r\n def save_metadata(self):\r\n json_path = os.path.join(self.folders_structure['metadata_json_folder'], 'metadata.json')\r\n with open(json_path, 'w') as file:\r\n json.dump(self.model_metadata, file)\r\n\r\n def save_model(self, loss=0.0, acc=0.0, mode='valid'):\r\n model_name = mode+'_'+'loss_' + str(round(loss, 4)) + '_accuracy_' + str(round(acc, 4)) + '.pth'\r\n model_save_path = os.path.join(self.folders_structure['models_folder'], model_name)\r\n torch.save(self.model, model_save_path)\r\n\r\ndef plot_confusion_matrix(cm, save_path,\r\n target_names,\r\n title='Confusion matrix',\r\n cmap=None,\r\n normalize=False):\r\n accuracy = np.trace(cm) / np.sum(cm).astype('float')\r\n misclass = 1 - accuracy\r\n if cmap is None:\r\n cmap = plt.get_cmap('Blues')\r\n fig = plt.figure(figsize=(8, 6))\r\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\r\n plt.title(title)\r\n plt.colorbar()\r\n\r\n if target_names is not None:\r\n tick_marks = np.arange(len(target_names))\r\n plt.xticks(tick_marks, target_names, rotation=45)\r\n plt.yticks(tick_marks, target_names)\r\n if normalize:\r\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\r\n thresh = cm.max() / 1.5 if normalize else cm.max() / 2\r\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\r\n if normalize:\r\n plt.text(j, i, \"{:0.4f}\".format(cm[i, j]),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n else:\r\n plt.text(j, i, \"{:,}\".format(cm[i, j]),\r\n horizontalalignment=\"center\",\r\n color=\"white\" if cm[i, j] > thresh else \"black\")\r\n plt.tight_layout()\r\n plt.ylabel('True label')\r\n plt.xlabel('Predicted label\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\r\n fig.savefig(save_path, dpi=fig.dpi)\r\n return fig\r\n\r\n\r\nif __name__ == '__main__':\r\n torch.cuda.empty_cache()\r\n dataset_path = 'cat_vs_dog_test_dataset'\r\n model1 = ClassificationTrainer(dataset_path=dataset_path)\r\n checkpoint_save_path = str(Path(__file__).parent / '')\r\n trainer = Trainer(gpus=0, benchmark=True, \r\n max_epochs=1, default_root_dir=checkpoint_save_path,\r\n check_val_every_n_epoch=1,\r\n # resume_from_checkpoint=checkpoint_path \r\n )\r\n trainer.test(model1)\r\n","sub_path":"klasyfikacja, trainskrypt jeden zeby wszytkie wyszkolic/code_video.py","file_name":"code_video.py","file_ext":"py","file_size_in_byte":17911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308184244","text":"import torch\nimport math\nimport os\nimport glob\nimport re\nimport logging\nimport shutil\n\nfrom .transformers_utils import MARIAN_GROUP_MEMBERS\nfrom transformers.models.mbart.tokenization_mbart50 import FAIRSEQ_LANGUAGE_CODES\n\nfrom genienlp.metrics import computeBLEU\nfrom genienlp.util import get_mbart_lang\n\nlogger = logging.getLogger(__name__)\n\n\ndef shift_tokens_right(input_ids, pad_token_id):\n \"\"\"\n Shift input ids one token to the right, and wrap the last non pad token (usually ).\n Adopted from huggingface's finetune.py code\n \"\"\"\n prev_output_tokens = input_ids.clone()\n index_of_eos = (input_ids.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)\n prev_output_tokens[:, 0] = input_ids.gather(1, index_of_eos).squeeze()\n prev_output_tokens[:, 1:] = input_ids[:, :-1]\n return prev_output_tokens\n\n\ndef freeze_params(model):\n for par in model.parameters():\n par.requires_grad = False\n\n\ndef unfreeze_params(model):\n for par in model.parameters():\n par.requires_grad = True\n\n\ndef freeze_embeds(model):\n \"\"\"Freeze token embeddings and positional embeddings for bart, just token embeddings for t5.\"\"\"\n if hasattr(model, 'model'):\n freeze_params(model.model.shared)\n for d in [model.model.encoder, model.model.decoder]:\n freeze_params(d.embed_positions)\n freeze_params(d.embed_tokens)\n else:\n freeze_params(model.shared)\n for d in [model.encoder, model.decoder]:\n freeze_params(d.embed_tokens)\n\ndef unfreeze_embeds(model):\n \"\"\"Unfreeze token embeddings and positional embeddings for bart, just token embeddings for t5.\"\"\"\n if hasattr(model, 'model'):\n unfreeze_params(model.model.shared)\n for d in [model.model.encoder, model.model.decoder]:\n unfreeze_params(d.embed_positions)\n unfreeze_params(d.embed_tokens)\n else:\n unfreeze_params(model.shared)\n for d in [model.encoder, model.decoder]:\n unfreeze_params(d.embed_tokens)\n\ndef check_args(args):\n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 1)[1] in MARIAN_GROUP_MEMBERS:\n if not args.tgt_lang:\n raise ValueError('For translation task using Marian model, if target language is a group of languages, '\n 'you have to specify the --tgt_lang flag.')\n elif args.tgt_lang not in MARIAN_GROUP_MEMBERS[args.model_name_or_path.rsplit('-', 1)[1]]:\n if args.tgt_lang == 'pl':\n args.tgt_lang = 'pol'\n elif args.tgt_lang == 'fa':\n args.tgt_lang = 'pes'\n else:\n raise ValueError(\n 'Target language is not in the model group languages, please specify the correct target language.')\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 2)[1] in MARIAN_GROUP_MEMBERS:\n if not args.src_lang:\n raise ValueError('For translation task using Marian model, if source language is a group of languages, '\n 'you have to specify the --src_lang flag.')\n elif args.src_lang not in MARIAN_GROUP_MEMBERS[args.model_name_or_path.rsplit('-', 2)[1]]:\n if args.src_lang == 'pl':\n args.src_lang = 'pol'\n elif args.src_lang == 'fa':\n args.src_lang = 'pes'\n raise ValueError(\n 'Source language is not in the model group languages, please specify the correct source language.')\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 1)[1] not in MARIAN_GROUP_MEMBERS and args.tgt_lang:\n logger.warning('Target language should not be provided when using Marian models with single target language,'\n ' otherwise the translation outputs will be incorrect; thus we ignore the target language you provided...')\n args.tgt_lang = None\n \n if args.model_type == 'marian' and args.model_name_or_path.rsplit('-', 2)[1] not in MARIAN_GROUP_MEMBERS and args.src_lang:\n logger.warning('Source language should not be provided when using Marian models with single source language,'\n ' otherwise the translation outputs will be incorrect; thus we ignore the source language you provided...')\n args.src_lang = None\n \n if args.model_type == 'mbart' and not (args.tgt_lang and args.src_lang):\n raise ValueError('Source and Target language should be provided when using mBART cc25 model')\n \n # adjust language ids for mbart models\n if args.model_type in ['mbart', 'mbart50']:\n if args.src_lang not in FAIRSEQ_LANGUAGE_CODES:\n args.src_lang = get_mbart_lang(args.src_lang)\n if args.tgt_lang not in FAIRSEQ_LANGUAGE_CODES:\n args.tgt_lang = get_mbart_lang(args.tgt_lang)\n\ndef sort_checkpoints(output_dir):\n return list(sorted(glob.glob(os.path.join(output_dir, \"checkpointepoch=*.ckpt\"), recursive=True)))\n\n\ndef get_transformer_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, dimension):\n num_warmup_steps = max(1, num_warmup_steps)\n\n def lr_lambda(current_step):\n current_step += 1\n return 1. / math.sqrt(dimension) * min(1 / math.sqrt(current_step), current_step / (num_warmup_steps * math.sqrt(num_warmup_steps)))\n\n return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda)\n\n\n\ndef _rotate_checkpoints(args, checkpoint_prefix, use_mtime=False):\n if not args.save_total_limit:\n return\n if args.save_total_limit <= 0:\n return\n\n # Check if we should delete older checkpoint(s)\n glob_checkpoints = glob.glob(os.path.join(args.output_dir, '{}-*'.format(checkpoint_prefix)))\n if len(glob_checkpoints) <= args.save_total_limit:\n return\n\n ordering_and_checkpoint_path = []\n for path in glob_checkpoints:\n if use_mtime:\n ordering_and_checkpoint_path.append((os.path.getmtime(path), path))\n else:\n regex_match = re.match('.*{}-([0-9]+)'.format(checkpoint_prefix), path)\n if regex_match and regex_match.groups():\n ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))\n\n checkpoints_sorted = sorted(ordering_and_checkpoint_path)\n checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]\n number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - args.save_total_limit)\n checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]\n for checkpoint in checkpoints_to_be_deleted:\n logger.info(\"Deleting older checkpoint [{}] due to args.save_total_limit\".format(checkpoint))\n shutil.rmtree(checkpoint)\n\n\ndef compute_metrics(generations, golds, reduction='average'):\n \"\"\"\n Inputs:\n generations: a list of list of strings; generations[i] is a list of all generated outputs of the model for example i\n golds: a list of strings; golds[i] is the gold answer for example i\n reduction: how we should compute an example's metrics from its multiple generations\n \"\"\"\n total_bleu = 0.0\n # all_bleu = []\n total_exact_match = 0.0\n count = 0.0\n for idx, output in enumerate(generations):\n bleu_score = 0.0\n exact_match = 0.0\n for sample in output:\n if reduction == 'average':\n bleu_score += computeBLEU([sample], [[golds[idx]]])\n else:\n bleu_score = max(bleu_score, computeBLEU([sample], [[golds[idx]]]))\n if re.sub('\\s+', '', sample).lower() == re.sub('\\s+', '', golds[idx]).lower():\n if reduction == 'average':\n exact_match += 1\n else:\n exact_match = max(exact_match, 1)\n if reduction == 'average':\n bleu_score /= len(output)\n exact_match /= len(output)\n total_bleu += bleu_score\n total_exact_match += exact_match\n count += 1\n\n return {'bleu': total_bleu/count, 'em': total_exact_match/count*100}\n\n\n","sub_path":"genienlp/paraphrase/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":8047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523044605","text":"import argparse\nimport re\n\nparser = argparse.ArgumentParser()\nparser.add_argument('bib')\nparser.add_argument('aux')\nargs = parser.parse_args()\n\nwith open(args.bib) as fp:\n text = fp.read()\n available_keys = set(key.strip() for key in re.findall(r'@\\w+{([^-].*?),', text))\n\nwith open(args.aux) as fp:\n text = fp.read()\n used_keys = set(key.strip() for key in re.findall(r'\\\\abx@aux@cite\\{(.*?)\\}', text))\n\nprint(f'found {len(available_keys)} available keys')\nprint(f'found {len(used_keys)} used keys')\nprint('unused keys:')\nprint('\\n'.join(sorted(available_keys - used_keys)))\n","sub_path":"manuscript/uncited.py","file_name":"uncited.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281734908","text":"from classes import PlayingCard\nimport random\n\ndef get_full_shuffled_deck_of_cards():\n\n \"\"\"\n This function returns a 52 card deck plus one wild card as a list\n \"\"\"\n\n #Make a deck of cards list, and a copy to modify\n deck_of_cards_without_wildcard = [PlayingCard(value, suit) for value in PlayingCard.values for suit in PlayingCard.suits]\n full_deck_of_cards = deck_of_cards_without_wildcard[:]\n\n #Make the wildcard a special card and add one to the deck\n wildcard = PlayingCard(\"*\", None) \n full_deck_of_cards.insert(52, wildcard)\n\n #Shuffle and return your deck\n random.shuffle(full_deck_of_cards)\n return full_deck_of_cards\n\ndef get_hands_of_cards(number_of_hands, cards_per_hand):\n \"\"\"\n This functions takes two integers (number of hands and cards per hand) \n and returns a list containing the hands requested\n \"\"\"\n card_hands = []\n shuffled_deck = get_full_shuffled_deck_of_cards()\n \n for hand in range(number_of_hands):\n hand = []\n for card in range(cards_per_hand):\n hand.append(shuffled_deck[card].value)\n shuffled_deck.pop(card)\n hand.sort()\n card_hands.append(hand)\n \n return card_hands\n\ndef is_four_of_a_kind(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is four of a kind\n \"\"\"\n for card in hand:\n if hand.count(card) is 4:\n return True\n\ndef is_full_house(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is a full house\n \"\"\"\n two_cards = False\n three_cards = False\n for card in hand:\n if hand.count(card) is 3:\n three_cards = True\n if hand.count(card) is 2:\n two_cards = True\n \n if two_cards and three_cards:\n return True\n\ndef is_straight(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is a straight\n \"\"\"\n int_converted_hand = []\n for card in hand:\n if card == 'T':\n card = 10\n if card == 'J':\n card = 11\n if card == 'Q':\n card = 12\n if card == 'K':\n card = 13\n if card == 'A':\n card = 14\n if card is not '*':\n int_converted_hand.append(int(card))\n\n range_list=list(range(min(int_converted_hand), max(int_converted_hand)+1))\n if int_converted_hand == range_list:\n return True\n\ndef is_three_of_a_kind(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it is three of a kind\n \"\"\"\n two_cards = False\n three_cards = False\n for card in hand:\n if hand.count(card) is 3:\n three_cards = True\n if hand.count(card) is 2:\n two_cards = True\n \n if three_cards:\n if not two_cards:\n return True\n\ndef is_two_pair(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if the hand has two pair\n \"\"\"\n pair_count = 0\n for card in hand:\n if hand.count(card) is 2:\n pair_count = pair_count + 1\n if pair_count == 4:\n return True\n\n\ndef is_pair(hand):\n \"\"\"\n This functions takes the hand (list) and returns true if it has one pair\n \"\"\"\n pair_count = 0\n for card in hand:\n if hand.count(card) is 2:\n pair_count = pair_count + 1\n if pair_count == 2:\n return True\n\ndef find_high_card(hand):\n \"\"\"\n This functions takes the hand (list) and returns the highest card\n \"\"\"\n high_card = max(hand)\n return high_card\n\ndef compare_hands(hands):\n \"\"\"\n This functions takes the hand (list), finds the score of the hand, compares the scores and tell you who won (or if it is a tie)\n \"\"\"\n hand_scores = []\n for index, hand in enumerate(hands):\n print(f'Hand number {index + 1}: {hand}')\n if is_full_house(hand):\n print(f'Full House in hand number {index + 1 } \\n')\n hand_scores.append(7)\n continue\n if is_four_of_a_kind(hand):\n print(f'Four of a kind in hand number {index + 1} \\n')\n hand_scores.append(6)\n continue\n if is_three_of_a_kind(hand):\n print(f'Three of a kind in hand number {index + 1} \\n')\n hand_scores.append(5)\n continue\n if is_straight(hand):\n print(f'Hand number {index + 1} is a straight \\n')\n hand_scores.append(4)\n continue\n if is_two_pair(hand):\n print(f'Hand number {index + 1} has two pair \\n')\n hand_scores.append(3)\n continue\n if is_pair(hand):\n print(f'Hand number {index + 1} has a single pair \\n')\n hand_scores.append(2)\n continue\n elif find_high_card(hand):\n hand_scores.append(1)\n high_card = find_high_card(hand)\n print(f'Hand number {index + 1} has a high card of {high_card} \\n')\n else:\n hand_scores.append(0)\n\n if len(set(hand_scores)) <= 1:\n print(\"Its a tie!\")\n\n else:\n winning_hand_score = max(hand_scores)\n winning_hand_index = hand_scores.index(winning_hand_score)\n print(f'Hand number {winning_hand_index + 1} wins!')\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"595572325","text":"\"\"\"Update name of Notification relationship field on Conditions and Actions;\n\nRevision ID: cf086d0211a\nRevises: 17350373a143\nCreate Date: 2014-06-01 10:56:21.323915\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'cf086d0211a'\ndown_revision = '17350373a143'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.alter_column('action', 'notification', new_column_name='notification_id')\n op.alter_column('condition', 'notification', new_column_name='notification_id')\n","sub_path":"alembic/versions/cf086d0211a_update_name_of_notification_.py","file_name":"cf086d0211a_update_name_of_notification_.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"526357510","text":"# To funkcijo prijazno podarjam vsem, ki bodo programirali v eni vrstici. :)\r\n# Kako jo uporabiti, je v navodilih. Kdor je ne potrebuje, naj jo ignorira.\r\ndef vsa_polja(s, v):\r\n \"\"\"\r\n Generiraj vse koordinate (x, y) za polje s podano širino in višino\r\n Args:\r\n s (int): širina\r\n v (int): višina\r\n\r\n Returns:\r\n generator parov polj\r\n \"\"\"\r\n return ((x, y) for x in range(s) for y in range(v))\r\n\r\n\r\n########################\r\n# Za oceno 6\r\n\r\ndef sosedov(x, y, mine):\r\n st_sosedov = 0\r\n if (x + 1, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y + 1) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y) in mine:\r\n st_sosedov += 1\r\n if (x - 1, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x + 1, y - 1) in mine:\r\n st_sosedov += 1\r\n if (x + 1, y) in mine:\r\n st_sosedov += 1\r\n return st_sosedov\r\n\r\n\r\ndef najvec_sosedov(mine, s, v):\r\n max = 0\r\n res = (0, 0)\r\n for (x, y) in vsa_polja(s, v):\r\n tmp_max = sosedov(x, y, mine)\r\n if tmp_max > max:\r\n max = tmp_max\r\n res = (x, y)\r\n return res\r\n\r\n\r\ndef brez_sosedov(mine, s, v):\r\n brez = set()\r\n for (x, y) in vsa_polja(s, v):\r\n if sosedov(x, y, mine) == 0:\r\n brez.add((x, y))\r\n return brez\r\n\r\n\r\ndef po_sosedih(mine, s, v):\r\n res = {\r\n 0: set(),\r\n 1: set(),\r\n 2: set(),\r\n 3: set(),\r\n 4: set(),\r\n 5: set(),\r\n 6: set(),\r\n 7: set(),\r\n 8: set()\r\n }\r\n for (x, y) in vsa_polja(s, v):\r\n st_sosedov = sosedov(x, y, mine)\r\n res[st_sosedov].add((x, y))\r\n return res\r\n\r\n\r\n########################\r\n# Za oceno 7\r\n\r\ndef dolzina_poti(pot):\r\n dolzina = 0\r\n for i in range(len(pot) - 1):\r\n x1, y1 = pot[i]\r\n x2, y2 = pot[i + 1]\r\n dolzina += abs(x1 - x2)\r\n dolzina += abs(y1 - y2)\r\n return dolzina\r\n\r\n\r\ndef varen_premik(x0, y0, x1, y1, mine):\r\n x = x0 - x1\r\n y = y0 - y1\r\n smer = True # true za x, false za y\r\n negative = False\r\n dolzina = x\r\n if abs(x) < abs(y):\r\n smer = False\r\n dolzina = y\r\n if dolzina < 0:\r\n negative = True\r\n if (x0, y0) in mine:\r\n return False\r\n for i in range(abs(dolzina) + 1):\r\n if (x0, y0) in mine:\r\n return False\r\n if smer:\r\n if negative == True:\r\n x0 += 1\r\n else:\r\n x0 -= 1\r\n else:\r\n if negative == True:\r\n y0 += 1\r\n else:\r\n y0 -= 1\r\n return True\r\n\r\n\r\ndef varna_pot(pot, mine):\r\n if len(pot) > 0:\r\n if pot[0] in mine:\r\n return False\r\n for i in range(len(pot) - 1):\r\n x0, y0 = pot[i]\r\n x1, y1 = pot[i + 1]\r\n if varen_premik(x0, y0, x1, y1, mine) == False:\r\n return False\r\n return True\r\n\r\n\r\n########################\r\n# Za oceno 8\r\n\r\ndef polje_v_mine(polje):\r\n mine = set()\r\n polje = polje.split(\" \")\r\n for y in range(len(polje)):\r\n vrstica = polje[y]\r\n for x in range(len(vrstica)):\r\n if vrstica[x] == \"X\":\r\n mine.add((x, y))\r\n return mine, len(polje[0]), len(polje)\r\n\r\n\r\n########################\r\n# Za oceno 9\r\n#\r\n# Vse funkcije za oceno 6 in 7 morajo biti napisane v eni vrstici.\r\n\r\n\r\n########################\r\n# Za oceno 10\r\n\r\ndef preberi_pot(ukazi):\r\n \"\"\"\r\n Za podani seznam ukazov (glej navodila naloge) vrni pot.\r\n\r\n Args:\r\n ukazi (str): ukazi, napisani po vrsticah\r\n\r\n Returns:\r\n list of tuple of int: pot\r\n \"\"\"\r\n\r\n\r\ndef zapisi_pot(pot):\r\n \"\"\"\r\n Za podano pot vrni seznam ukazov (glej navodila naloge).\r\n\r\n Args:\r\n pot (list of tuple of int): pot\r\n\r\n Returns:\r\n str: ukazi, napisani po vrsticah\r\n \"\"\"\r\n\r\n\r\n","sub_path":"code/batch-2/vse-naloge-brez-testov/DN7-M-076.py","file_name":"DN7-M-076.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"479797222","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 12 15:20:16 2018\n\n@author: owo\n\"\"\"\n\nimport sys\nsys.path.append(r'./library')\n\nimport numpy as np\n#import matplotlib.pyplot as plt\nfrom ErrorVariance import Error_variance\nfrom DOY2GPSweek import DOY2GPSweek\nfrom Satellite_Calculate import Satellite_Calculate\nfrom LeastSquaresPositioning import Positioning\nfrom ErrorModule import Error_module\nfrom TimeBreakDown import TimeBreakDown\nfrom NDataRead import NDataRead\nimport xyz2llh\nimport xyz2enu\nfrom CustomValue import *\n\nglobal S_phase_data_path\nglobal S_aeosv_data_path\nglobal S_n_data_path\nglobal S_ans_position_path\n\nS_phase_data_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/phase_data/'\nS_aeosv_data_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/aeosv_data/'\nS_n_data_path = '/pub3/man4781747/GPS_data/n_data/'\nS_ans_position_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/position_data/'\nS_DGPS_Correction_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/DGPS_Correction_data/'\nS_GIMRIM_TEC_path = '/pub3/man4781747/GPS_data/data20{0:02d}{1:03d}/GIM_svTEC/'\n\nS_phase_data_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/phase_data/'\nS_aeosv_data_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/aeosv_data/'\nS_n_data_path = 'D:/Ddddd/python/2003/Odata/test/n_data/'\nS_ans_position_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/position_data/'\nS_DGPS_Correction_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/DGPS_Correction_data/'\nS_GIMRIM_TEC_path = 'D:/Ddddd/python/2003/Odata/test/data20{0:02d}{1:03d}/GIM_svTEC/'\n\ndef ez2do_every_thing(I_year,I_doy,S_station_name,F_elevation_filter=15.,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='No',Beta='No'):\n C_NData = NDataRead(S_n_data_path.format(I_year,I_doy)+'n_data_{0:02d}{1:03d}.npy'.format(I_year,I_doy)) \n Ay_Pr_C1_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseC1.npy'.format(I_year,I_doy,S_station_name))[:,:32]\n Ay_AnsPosition_Rover = np.load(S_ans_position_path.format(I_year,I_doy)+'{2}{0:02d}{1:03d}_position.npy'.format(I_year,I_doy,S_station_name))[0,:]\n Ay_TimeRaw_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phasetime.npy'.format(I_year,I_doy,S_station_name))[:,0:6]\n Ay_Time_Rover = Ay_TimeRaw_Rover[:,3]*3600.+Ay_TimeRaw_Rover[:,4]*60.+Ay_TimeRaw_Rover[:,5]\n\n if S_ion_model=='C1P2':\n Ay_Pr_P2_Rover = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseP2.npy'.format(I_year,I_doy,S_station_name))[:,:32]\n Ay_Pr_P2_Rover[np.where(Ay_Pr_C1_Rover==0)]=0\n Ay_Pr_C1_Rover[np.where(Ay_Pr_P2_Rover==0)]=0 \n \n if S_DGPS != 'No':\n Ay_Pr_C1_Base = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phaseC1.npy'.format(I_year,I_doy,S_DGPS))[:,:32]\n Ay_AnsPosition_Base = np.load(S_ans_position_path.format(I_year,I_doy)+'{2}{0:02d}{1:03d}_position.npy'.format(I_year,I_doy,S_DGPS))[0,:]\n Ay_TimeRaw_Base = np.load(S_phase_data_path.format(I_year,I_doy)+'30s/'+'{2}{0:02d}{1:03d}phasetime.npy'.format(I_year,I_doy,S_DGPS))[:,0:6]\n Ay_Time_Base = Ay_TimeRaw_Base[:,3]*3600.+Ay_TimeRaw_Base[:,4]*60.+Ay_TimeRaw_Base[:,5]\n# '''\n# test\n# '''\n if Beta != 'No':\n global Ay_base_sTEC,Ay_rover_sTEC\n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC_no_kickout/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'fitted_sTEC_no_kickout/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n \n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'30s/s{0}{1:03d}.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'30s/s{0}{1:03d}.npy'.format(S_station_name, I_doy))[:,:32]\n# Ay_base_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'s{0}{1:03d}_fit.npy'.format(S_DGPS, I_doy))[:,:32]\n# Ay_rover_sTEC = np.load(S_aeosv_data_path.format(I_year,I_doy)+'s{0}{1:03d}_fit.npy'.format(S_station_name, I_doy))[:,:32]\n Ay_base_sTEC[np.isnan(Ay_base_sTEC)] = 0\n Ay_rover_sTEC[np.isnan(Ay_rover_sTEC)] = 0\n\n I_loop_num = 0\n test = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n test_DGPS = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n test_GDOP = np.zeros((len(Ay_Pr_C1_Rover[:,0]),1))\n test_GDOP_DGPS = np.zeros((len(Ay_Pr_C1_Rover[:,0]),1))\n Ay_OutPut_xyz = np.zeros((len(Ay_Pr_C1_Rover[:,0]),3))\n \n test_dTEC = np.zeros((2880,32))\n \n Lst_DGPSSateSum = []\n \n for I_time_chose in range(len(Ay_Pr_C1_Rover[:,0])):\n# for I_time_chose in range(1):\n# for I_time_chose in np.zeros(1).astype('int')+332:\n# for I_time_chose in np.arange(161, 164,1):\n# try:\n S_info = \"\\r{0} ,Y:{1:02d} ,D:{2:03d} ,Elevation:{5:2.2f} ,ionofree:{4} ,DGPS:{6} ,now in {3:2.2f}%\\r\".format(S_station_name,\n I_year,\n I_doy,\n (I_time_chose/float(len(Ay_Pr_C1_Rover[:,0])))*100 \n ,S_ion_model,\n F_elevation_filter,\n S_DGPS)\n print(S_info,end='')\n C_TimeRover = TimeBreakDown(Ay_Time_Rover[I_time_chose])\n Ay_NDataChose_Rover, Ay_SateChoseNum_Rover = C_NData.GetData(Ay_Pr_C1_Rover[I_time_chose], C_TimeRover.F_TimeTotal)\n# print(Ay_Pr_C1_Rover[I_time_chose,4])\n# print(Ay_SateChoseNum_Rover)\n if len(np.where(Ay_Pr_C1_Rover[I_time_chose,:] != 0.)[0]) >= 4: \n Ay_PrChose_C1_Rover = Ay_Pr_C1_Rover[I_time_chose,Ay_SateChoseNum_Rover] \n if S_ion_model=='C1P2':\n Ay_PrChose_P2_Rover = Ay_Pr_P2_Rover[I_time_chose,Ay_SateChoseNum_Rover] \n \n\n F_GPSWeek_Sec= (float(DOY2GPSweek(I_year,I_doy))%10)*24*60*60 \n Ay_ReceiverDelay_Rover = 0\n\n Mobj_sate_cal = Satellite_Calculate(Ay_NDataChose_Rover)\n Ay_SateTimeDelay_Rover = Mobj_sate_cal.get_sate_clock_error(Ay_PrChose_C1_Rover,C_TimeRover.I_TimeInt,C_TimeRover.F_TimeDecimal,F_GPSWeek_Sec)\n sva_Rover = Mobj_sate_cal.sva\n tgd_Rover = Mobj_sate_cal.tgd\n (Ay_xk,Ay_yk,Ay_zk,Ay_SateTimeDelay_Rover) = Mobj_sate_cal.get_sate_position(\n C_TimeRover.I_TimeInt,C_TimeRover.F_TimeDecimal,\n F_GPSWeek_Sec,Ay_SateTimeDelay_Rover,Ay_PrChose_C1_Rover) \n \n Mobj_error_variance = Error_variance()\n Ay_vare = Mobj_error_variance.vare(sva_Rover)\n Ay_vmeas = Mobj_error_variance.vmeas()\n if I_loop_num == 0:\n F_test_point_x = 0.000000001\n F_test_point_y = 0.\n F_test_point_z = 0.\n Ay_guess_position = np.array([[F_test_point_x],[F_test_point_y],[F_test_point_z]])\n I_loop_num = 1\n Ay_elevation = np.zeros(len(Ay_xk)) + np.pi/2\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_fix_position = np.array([100,100,100])\n TF_tgd_fix = True\n I_loop_break = 0\n# for i in range(2):\n while abs(Ay_fix_position[0]) > 1e-4 or abs(Ay_fix_position[1]) > 1e-4 or abs(Ay_fix_position[2]) > 1e-4:\n Ay_guess_position_llh = np.zeros((3,len(Ay_PrChose_C1_Rover)))\n for j in range(len(Ay_PrChose_C1_Rover)):\n Ay_guess_position_llh[:,j] = np.array([xyz2llh.xyz2llh(Ay_guess_position[0],Ay_guess_position[1],Ay_guess_position[2]).xyz()])\n \n Ay_varerr = Mobj_error_variance.varerr(Ay_elevation,S_ion_model)\n\n Mobj_delay = Error_module()\n if S_ion_model == 'broadcast' or S_DGPS != 'No':\n S_n_data_path_ = S_n_data_path.format(I_year,I_doy)+'n_data_{0:02d}{1:03d}_ion.npy'.format(I_year,I_doy)\n Ay_dion = Mobj_delay.iono_model_broadcast(I_year,I_doy,\n Ay_guess_position_llh[0,:]*np.pi/180.,\n Ay_guess_position_llh[1,:]*np.pi/180.,\n Ay_elevation,\n Ay_enu_resever_sate,\n C_TimeRover.F_TimeTotal,\n S_n_data_path_\n )\n else:\n Ay_dion = 0\n Ay_vion = Mobj_error_variance.vion(I_loop_break,S_ion_model,Ay_dion,S_DGPS)\n if S_trp_model == 'saastamoinen':\n Ay_dtrp = Mobj_delay.saastamoinen_model(Ay_guess_position_llh[0,:]*np.pi/180.,\n Ay_guess_position_llh[1,:]*np.pi/180.,\n Ay_guess_position_llh[2,:],\n Ay_elevation,\n 0.6)\n else: \n Ay_dtrp = 0\n Ay_vtrp = Mobj_error_variance.vtrp(I_loop_break,S_trp_model,Ay_elevation)\n Ay_error_variance_all = Ay_varerr + Ay_vmeas + Ay_vare + Ay_vion + Ay_vtrp \n Ay_error_variance_all = np.zeros_like(Ay_error_variance_all)+1\n Ay_beacon_position = np.array([Ay_xk,Ay_yk,Ay_zk])\n Ay_guess_range_list_first = np.copy(Ay_beacon_position)\n for nn in range(len(Ay_guess_range_list_first[0,:])):\n Ay_guess_range_list_first[:,nn] -= Ay_guess_position[:,0]\n Ay_guess_range_list = np.sum((Ay_guess_range_list_first)**2,0)**0.5\n Ay_guess_range_list_ = np.sum((Ay_guess_range_list_first)**2,0)**0.5 + F_OMGE*(Ay_xk*Ay_guess_position[1]-Ay_yk*Ay_guess_position[0])/F_C\n if TF_tgd_fix:\n F_gamma = F_f1_hz**2/F_f2_hz**2\n if S_ion_model != 'C1P2':\n Ay_P1_P2 = (1.0-F_gamma)*tgd_Rover*F_C\n Ay_PrChose_C1_Rover = Ay_PrChose_C1_Rover - Ay_P1_P2/(1.0-F_gamma)\n# print(Ay_pseudo_range[-1])\n else:\n Ay_PrChose_C1_Rover = (F_gamma*Ay_PrChose_C1_Rover - Ay_PrChose_P2_Rover)/(F_gamma-1)\n TF_tgd_fix = False\n# print(Ay_dion)\n Ay_pseudo_range_fix = Ay_PrChose_C1_Rover + F_C*Ay_SateTimeDelay_Rover - Ay_ReceiverDelay_Rover - Ay_dtrp -Ay_dion\n# print(Ay_pseudo_range_fix) \n Mobj_get_position_fst = Positioning(Ay_pseudo_range_fix[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list_[np.where(Ay_elevation > F_elevation_filter/180*np.pi)],\n Ay_beacon_position[:,np.where(Ay_elevation > F_elevation_filter/180*np.pi)[0]],\n Ay_guess_position,\n Ay_error_variance_all[np.where(Ay_elevation > F_elevation_filter/180*np.pi)])\n \n '''\n 更新下列數值\n Ay_guess_position\n Ay_resever_time_delay\n Ay_enu_resever_sate\n Ay_elevation\n Ay_fix_position\n '''\n Ay_guess_position = Mobj_get_position_fst.Positioning_results()[0]\n Ay_ReceiverDelay_Rover = Mobj_get_position_fst.Positioning_results()[1] + Ay_ReceiverDelay_Rover\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_elevation = np.arctan2( (Ay_enu_resever_sate[:,2]),np.sum(Ay_enu_resever_sate[:,0:2]**2,1)**0.5 )\n Ay_fix_position = Mobj_get_position_fst.Positioning_results()[2]\n \n# print(Ay_ReceiverDelay_Rover)\n# print(Ay_enu_resever_sate)\n# print(Ay_elevation)\n \n \n if I_loop_break > 10:\n print('test_break')\n break\n I_loop_break += 1\n \n Ay_OutPut_xyz[I_time_chose] = Ay_guess_position[:,0]\n test_GDOP[I_time_chose,0] = Mobj_get_position_fst.F_GDOP\n Ay_ENU = xyz2enu.xyz2enu(np.array([Ay_guess_position[:,0]]),\n np.array([Ay_AnsPosition_Rover])\n ).return_enu()\n test[I_time_chose] = Ay_ENU[0,:]\n if S_DGPS != 'No':\n C_TimeBase = TimeBreakDown(Ay_Time_Base[I_time_chose])\n Ay_NDataChose_Base, Ay_SateChoseNum_Base = C_NData.GetData(Ay_Pr_C1_Base[I_time_chose], C_TimeBase.F_TimeTotal)\n \n '''\n Mobj_sate_cal_DGPS_before : 基站衛星計算 Mobj\n Ay_delta_t_sv_DGPS_before : 基站衛星時鐘誤差\n Ay_pseudo_range_DGPS_berofe : 基站選取的偽距\n Ay_xk_DGPS_before,Ay_yk_DGPS_before,Ay_zk_DGPS_before\n : 基站衛星位置 ECEF\n '''\n Ay_PrChose_C1_Base = Ay_Pr_C1_Base[I_time_chose,Ay_SateChoseNum_Base] \n \n Mobj_SateCal_Base = Satellite_Calculate(Ay_NDataChose_Base)\n Ay_SateTimeDelay_Base = Mobj_SateCal_Base.get_sate_clock_error(Ay_PrChose_C1_Base,\n C_TimeBase.I_TimeInt,\n C_TimeBase.F_TimeDecimal,\n F_GPSWeek_Sec)\n# sva_DGPS_before = Mobj_sate_cal_DGPS_before.sva\n tgd_Base = Mobj_SateCal_Base.tgd\n (Ay_xk_Base,Ay_yk_Base,Ay_zk_Base,Ay_SateTimeDelay_Base) = Mobj_SateCal_Base.get_sate_position(\n C_TimeBase.I_TimeInt,C_TimeBase.F_TimeDecimal,\n F_GPSWeek_Sec,Ay_SateTimeDelay_Base,Ay_PrChose_C1_Base)\n\n '''\n 基站 TGD修正\n '''\n\n Ay_P1_P2_DGPS = (1.0-F_gamma)*tgd_Base*F_C\n Ay_PrChose_C1_Base = Ay_PrChose_C1_Base - Ay_P1_P2_DGPS/(1.0-F_gamma)\n \n '''\n ### 基站衛星位置 ###\n Ay_beacon_position_DGPS_before(x,y,z) (3,N)\n '''\n Ay_SatePosition_Base = np.array([Ay_xk_Base,Ay_yk_Base,Ay_zk_Base])\n \n '''\n ### 基站真實距離計算 ###\n Ay_guess_range_list_DGPS_before 基站\"不\"考慮旋轉後的真實距離\n Ay_guess_range_list_DGPS_before_ 基站考慮旋轉後的真實距離\n '''\n Ay_guess_range_list_DGPS_before_first = np.copy(Ay_SatePosition_Base)\n for nn in range(len(Ay_guess_range_list_DGPS_before_first[0,:])):\n Ay_guess_range_list_DGPS_before_first[:,nn] -= Ay_AnsPosition_Base\n Ay_guess_range_list_DGPS_before_ = np.sum((Ay_guess_range_list_DGPS_before_first)**2,0)**0.5 + F_OMGE*(Ay_xk_Base*Ay_AnsPosition_Base[1]-Ay_yk_Base*Ay_AnsPosition_Base[0])/F_C\n\n \n \n '''\n 基站/測站 衛星配對\n Ay_sate_match_raver : 測站衛星位置碼\n Ay_pseudo_range_DGPS_chose_rover : 測站偽距選取\n Ay_sate_match_base : 基站衛星位置碼\n Ay_pseudo_range_DGPS_chose_base : 基站偽距選取\n '''\n \n if Beta != 'No':\n I_time_index = int(round(C_TimeRover.F_TimeTotal/30))\n Ay_TEC_chose_base_index = np.where(Ay_base_sTEC[I_time_index,:] != 0)[0]\n Ay_TEC_chose_rover_index = np.where(Ay_rover_sTEC[I_time_index,:] != 0)[0]\n\n Lst_sate_match = list(set(Ay_SateChoseNum_Rover)&\n set(Ay_SateChoseNum_Base)&\n set(Ay_TEC_chose_base_index)&\n set(Ay_TEC_chose_rover_index))\n \n Ay_sate_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sate_match_base = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sTEC_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sTEC_match_base = np.zeros(len(Lst_sate_match)).astype('int') \n\n for I_sate_chose in range(len(Lst_sate_match)):\n Ay_sate_match_raver[I_sate_chose] = int(np.where(Ay_SateChoseNum_Rover == Lst_sate_match[I_sate_chose])[0])\n Ay_sate_match_base[I_sate_chose] = int(np.where(Ay_SateChoseNum_Base == Lst_sate_match[I_sate_chose])[0])\n Ay_sTEC_match_raver[I_sate_chose] = int(np.where(Ay_TEC_chose_rover_index == Lst_sate_match[I_sate_chose])[0])\n Ay_sTEC_match_base[I_sate_chose] = int(np.where(Ay_TEC_chose_base_index == Lst_sate_match[I_sate_chose])[0])\n \n Ay_TECChose_Base = Ay_base_sTEC[I_time_index,Ay_TEC_chose_base_index][Ay_sTEC_match_base]\n Ay_TECChose_Rover = Ay_rover_sTEC[I_time_index,Ay_TEC_chose_rover_index][Ay_sTEC_match_raver]\n \n else:\n Lst_sate_match = list(set(Ay_SateChoseNum_Rover)&\n set(Ay_SateChoseNum_Base)) \n \n Ay_sate_match_raver = np.zeros(len(Lst_sate_match)).astype('int')\n Ay_sate_match_base = np.zeros(len(Lst_sate_match)).astype('int') \n \n for I_sate_chose in range(len(Lst_sate_match)):\n Ay_sate_match_raver[I_sate_chose] = int(np.where(Ay_SateChoseNum_Rover == Lst_sate_match[I_sate_chose])[0])\n Ay_sate_match_base[I_sate_chose] = int(np.where(Ay_SateChoseNum_Base == Lst_sate_match[I_sate_chose])[0])\n\n Ay_TECChose_Base = 0\n Ay_TECChose_Rover = 0\n\n Ay_pseudo_range_DGPS_chose_rover = Ay_PrChose_C1_Rover[Ay_sate_match_raver[:]]\n Ay_pseudo_range_DGPS_chose_base = Ay_PrChose_C1_Base[Ay_sate_match_base[:]]\n \n\n \n\n Ay_TEC_delay_base = Ay_TECChose_Base*(40.3*(10**16))/((F_f1_hz*10**6)**2)\n Ay_TEC_delay_rover = Ay_TECChose_Rover*(40.3*(10**16))/((F_f1_hz*10**6)**2)\n \n \n for i in range(3):\n Ay_beacon_position = np.array([Ay_xk,Ay_yk,Ay_zk])\n Ay_guess_range_list_first = np.copy(Ay_beacon_position)\n for nn in range(len(Ay_guess_range_list_first[0,:])):\n Ay_guess_range_list_first[:,nn] -= Ay_guess_position[:,0]\n Ay_guess_range_list = np.sum((Ay_guess_range_list_first)**2,0)**0.5\n Ay_guess_range_list_ = np.sum((Ay_guess_range_list_first)**2,0)**0.5 + F_OMGE*(Ay_xk*Ay_guess_position[1]-Ay_yk*Ay_guess_position[0])/F_C\n \n '''\n Ay_pseudo_range_fix_DGPS : 測站修過 DGPS 的偽距\n 測站偽距 - ( 基站偽距 - 基站真實距離(修過自轉) ) - 測站時鐘誤差\n \n Mobj_get_position_DGPS : 定位矩陣(\n Ay_pseudo_range_fix_DGPS : 測站修過 DGPS 的偽距\n Ay_guess_range_list : 猜測點與測站衛星距離(m) 無修正轉動\n Ay_guess_range_list_ : 猜測點與測站衛星距離(m) 有修正轉動\n Ay_beacon_position : 測站衛星位置\n Ay_guess_position : 猜測點\n Ay_error_variance_all : 品質權重\n )\n '''\n \n Ay_pseudo_range_fix_DGPS = (Ay_pseudo_range_DGPS_chose_rover-Ay_TEC_delay_rover) - ((Ay_pseudo_range_DGPS_chose_base-Ay_TEC_delay_base) - Ay_guess_range_list_DGPS_before_[Ay_sate_match_base[:]]) - Ay_ReceiverDelay_Rover\n# Ay_pseudo_range_fix_DGPS = (Ay_pseudo_range_DGPS_chose_rover) - ((Ay_pseudo_range_DGPS_chose_base) - Ay_guess_range_list_DGPS_before_[Ay_sate_match_base[:]]) - Ay_ReceiverDelay_Rover\n#\n# print(test_dTEC[I_time_index,Ay_TEC_chose_base_index])\n# print(test_dTEC[I_time_index,Ay_TEC_chose_base_index[Ay_sTEC_match_base]])\n# print(Ay_TEC_delay_rover-Ay_TEC_delay_base)\n# test_dTEC[I_time_index,Ay_TEC_chose_base_index[Ay_sTEC_match_base]] = Ay_TEC_delay_rover-Ay_TEC_delay_base\n\n\n\n\n Mobj_get_position_DGPS = Positioning(Ay_pseudo_range_fix_DGPS[np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_guess_range_list_[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)],\n Ay_beacon_position[:,Ay_sate_match_raver[:]][:,np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)[0]],\n Ay_guess_position,\n Ay_error_variance_all[Ay_sate_match_raver[:]][np.where(Ay_elevation[Ay_sate_match_raver[:]] > F_elevation_filter/180*np.pi)])\n '''\n 更新下列數值\n Ay_guess_position\n Ay_resever_time_delay\n Ay_enu_resever_sate\n Ay_elevation\n '''\n Ay_guess_position = Mobj_get_position_DGPS.Positioning_results()[0]\n Ay_ReceiverDelay_Rover = Mobj_get_position_DGPS.Positioning_results()[1] + Ay_ReceiverDelay_Rover\n Ay_enu_resever_sate = xyz2enu.xyz2enu(np.array([Ay_xk,Ay_yk,Ay_zk]).T,Ay_guess_position.T).return_enu()\n Ay_elevation = np.arctan2( (Ay_enu_resever_sate[:,2]),np.sum(Ay_enu_resever_sate[:,0:2]**2,1)**0.5 )\n Ay_ENU = xyz2enu.xyz2enu(np.array([Ay_guess_position[:,0]]),\n np.array([Ay_AnsPosition_Rover])\n ).return_enu()\n test_DGPS[I_time_chose] = Ay_ENU[0,:]\n Ay_fix_position = Mobj_get_position_DGPS.Positioning_results()[2]\n# print(Ay_fix_position)\n# print(Mobj_get_position_DGPS.Positioning_results()[1])\n test_GDOP_DGPS[I_time_chose,0] = Mobj_get_position_DGPS.F_GDOP\n Lst_DGPSSateSum.append(len(Ay_TEC_delay_base))\n# except:\n# test[I_time_chose] = np.nan\n# test_DGPS[I_time_chose] = np.nan\n# print('ERROR')\n plt.plot(Lst_DGPSSateSum)\n return test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC\n\n \nif __name__ == '__main__':\n# I_year = 3\n# I_doy = 324\n#\n#\n# S_station = 'woos'\n# test,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='gust')\n\n\n I_year = 15\n I_doy = 73\n\n\n S_station = 'sun1'\n test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp',Beta='Yes')\n# test,Ay_OutPut_xyz,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2')\n# np.save(r'D:\\google drive\\我der碩士論文\\磁暴\\磁暴各定位結果\\woos_DPGS_gust_v2sfit_nearest版.npy', test_DGPS)\n# np.save(r'D:\\google drive\\我der碩士論文\\磁暴\\磁暴各定位結果\\woos_DPGS_gust_GDOP_v2sfit_nearest版.npy', test_GDOP_DGPS)\n \n\n# test,test_DGPS,test_GDOP,test_GDOP_DGPS,test_dTEC = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp')\n \n\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen')\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2',S_trp_model='saastamoinen')\n# I_year = 3\n# I_doy = 324\n#\n# S_station = 'woos'\n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='gust')\n## \n# test,test_DGPS = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='broadcast',S_trp_model='saastamoinen',S_DGPS='fenp')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_broadcast.npy'.format(I_doy,S_station ),test)\n#\n# test = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='No')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_noionfree.npy'.format(I_doy,S_station ),test)\n# \n# test = ez2do_every_thing(I_year,I_doy,S_station,S_ion_model='C1P2')\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\{1}_sin_{0:03d}_C1P2.npy'.format(I_doy,S_station ),test)\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\sun1_sin_{0:03d}_broadcast.npy'.format(I_day),test_ENU)\n#\n\n# np.save(r'D:\\Ddddd\\python\\2003\\Odata\\test\\2003324data\\sun1_sin_{0:03d}_noionfree.npy'.format(I_day),test_ENU) ","sub_path":"python_code/GPS定位完整版/GNSS_positioning_argv_ver3.py","file_name":"GNSS_positioning_argv_ver3.py","file_ext":"py","file_size_in_byte":28380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257258650","text":"import torchvision\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('--surgered_part', action=\"store\", required=True,\n type=str, help=\"Part to be surgered\")\n\nargs = parser.parse_args()\n\nresnet = torchvision.models.resnet101(pretrained=True).cuda()\n\n# total_resnet_params = 0\n# for elem in resnet.parameters():\n# total_resnet_params += elem.numel()\ntotal_resnet_params = 44549160 # No need to be recomputed each time\nprint(f'{total_resnet_params:,}')\n\nlayer, block = args.surgered_part.split('.')\nsurgered = eval(f\"resnet.layer{layer}[{block}]\")\n\nsurgered_block_params = 0\nfor tensor in surgered.parameters():\n surgered_block_params += tensor.numel()\n\nprint(surgered)\n\nprint(f\"Layer {layer} block {block} contains {surgered_block_params:,} parameters\")\npercent = surgered_block_params / total_resnet_params * 100\nprint(f\"This correspond to {percent:.2f}%\")\n","sub_path":"imagenet/nb_params_in_block.py","file_name":"nb_params_in_block.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434165806","text":"import json\n\nfrom flask import Flask\nfrom flask import request\nfrom flask import jsonify\nfrom flask import send_file\n\nfrom modifiers.crossdomain import crossdomain\n\nfrom modules.dashboard.dashboard import Dashboard\nfrom modules.newsfeed.newsfeed import Newsfeed\n\napp = Flask(__name__)\n\ndashboard = None\nnewsfeed = None\n\n@app.route(\"/\")\n@crossdomain(origin=\"*\")\ndef echo():\n return 'Hello World!!!'\n\n@app.route(\"/dashboard\", methods=['GET'])\n@crossdomain(origin='*')\ndef dashboards():\n access_token = request.headers['access_token']\n since= request.args.get('since')\n until= request.args.get('until')\n if until == None: until = '-0 year'\n return jsonify(dashboard.get_dashboard(access_token,since,until))\n\n@app.route(\"/dashboard/getalltops/\", methods=['GET'])\n@crossdomain(origin='*')\ndef getAllTops(uid):\n return jsonify(dashboard.get_all_top(uid))\n\n@app.route('/getwordcloud/', methods=['GET'])\n@crossdomain(origin='*')\ndef get_wordcloud(uid):\n filename = \"assets/wordcloud/%s.png\" % uid\n return send_file(filename, mimetype='image/png')\n\n@app.route(\"/newsfeed/\", methods=['GET'])\n@crossdomain(origin='*')\ndef newsfeed(uid):\n access_token = request.headers['access_token']\n return jsonify(newsfeed.get_newsfeed(access_token, uid))\n\n@app.route(\"/newsfeed/next/\", methods=['GET'])\n@crossdomain(origin='*')\ndef newsfeed_next(uid):\n access_token = request.headers['access_token']\n return jsonify(newsfeed.get_next_newsfeed(access_token, uid))\n\n@app.route('/userlikes/', methods=['POST'])\n@crossdomain(origin='*')\ndef user_likes(uid):\n content = request.json\n newsfeed.collect_like_posts(uid, content['meta_data'])\n return jsonify(content)\n\n@app.route('/userdislikes/', methods=['POST'])\n@crossdomain(origin='*')\ndef user_dislikes(uid):\n content = request.json\n newsfeed.collect_dislike_posts(uid, content['meta_data'])\n return jsonify(content)\n\n@app.route('/image/', methods=['POST'])\n@crossdomain(origin='*')\ndef images(uid):\n return request.json\n\ndef generate_config():\n config_dict = {\n \"server\": {\n \"host\": \"localhost\",\n \"port\": 8080\n },\n \"database\": {\n \"host\": \"localhost\",\n \"port\": 4040\n }\n }\n try:\n config = open('config.json', 'w')\n json.dump(config_dict, config, indent=4)\n config.close()\n print(\"Message : success to generate config.json.\")\n except IOError as error:\n print(\"Error : failed to generate config.json.\")\n \n\nif __name__ == \"__main__\":\n try:\n config_file = open('config.json', 'r')\n config = json.load(config_file)\n config_file.close()\n dashboard = Dashboard()\n newsfeed = Newsfeed()\n app.run(config[\"server\"][\"host\"], config[\"server\"][\"port\"])\n except IOError as error:\n print(\"Error : could not found config.json.\")\n print(\"Message : generating config...\")\n generate_config()\n except KeyError as error:\n print(\"Error : incorrect name. please check your config.json file.\")\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"312749475","text":"'''\nfourier transform\n\n입력 신호를 보고 숨겨진 주파수를 찾아라.\nsin, cos으로 구성된 신호, 주파수와 진폭을 어떻게 구하는가.\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nfmax=1000 # 찾을 최대 주파수\ndt = 1/fmax # 샘플링 주기. 0.001 sec.\nN = fmax # 샘플 개수.\n\n# 샘플 시각\nt = np.arange(0, N)*dt # 0~2초를 균일하게 2000개로 나눔.\n# original signal ; 60Hz, 120Hz 사용.\ns = 0.8*np.sin(2*np.pi*80*t)-0.4*np.cos(2*np.pi*80*t)\\\n +0.3*np.sin(2*np.pi*250*t)+0.3*np.cos(2*np.pi*250*t)\n\n# detect signal ; noise added 노이즈가 추가된 신호. x\n# x = s + 0.8*np.random.randn(N)\nx = s + 0.1*np.random.randn(N)\n\nplt.subplot(3,1,1)\nplt.plot(t[0:200], s[0:200], label='signal')\nplt.plot(t[0:200], x[0:200], label='x')\nplt.legend()\nplt.xlabel('time'), plt.ylabel('x(t)'), plt.grid()\n# plt.show()\n\n# fourier spectrum...\ndf = fmax/N\nf = np.arange(0,N)*df # 1Hz 2Hz, ... ,fmax Hz.\nxf = np.fft.fft(x)/N\n\nplt.subplot(3,1,2)\ncnt = fmax\nplt.plot(f[0:cnt], np.abs(xf[0:cnt]))\nplt.xlabel('freq(Hz)'), plt.ylabel('abs(xf)'), plt.grid()\n# plt.show()\n\n# 퓨리에 스펙트럼에서 peak를 치는 곳의 주파수 성분들을 사용하면 된다.\n\n# get Top N\nprint('f=', f)\nxf2 = np.abs(xf[0:cnt])\n# print('xf2=', xf2)\n# print('xf mean=', np.mean(xf2))\n# print('sort=', -np.sort(-xf2))\nrankidx = np.argsort(-xf2)\n# print(rankidx)\nfor i in range(4):\n # print(i, rank[i])\n print(f[rankidx[i]], xf2[rankidx[i]])\n\n# draw by fft top.\nplt.subplot(3,1,3)\n# t 0~200\nyf = np.zeros((N,))\nfor i in range(4):\n freq = f[rankidx[i]]\n amp = xf2[rankidx[i]]\n print('freq, and amp = ', freq, amp, xf[rankidx[i]])\n amp1 = xf[rankidx[i]].real\n amp2 = xf[rankidx[i]].imag\n print(xf[rankidx[i]])\n # real은 cos\n # imagine은 sin 인데, 부호는 반대로 한다.\n amp2 = amp2 * -1\n yf += amp1*np.cos(2*np.pi*freq*t)+amp2*np.sin(2*np.pi*freq*t)\n\nplt.plot(t[0:200], s[0:200], label='signal')\nplt.plot(t[0:200], yf[0:200], label='fft')\nplt.legend()\nplt.show()\n\n","sub_path":"math/fourier04_2.py","file_name":"fourier04_2.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331452444","text":"def fact(n):\n\tif n==1:\n\t\treturn 1\n\treturn n*fact(n-1)\nn = input('请输入n:')\nn = int(n)\nprint(fact(n))\n\n\n# 利用递归函数移动汉诺塔:\ndef move(n, a, b, c):\n if n == 1:\n print('move', a, '-->', c)\n else:\n move(n-1, a, c, b)\n move(1, a, b, c)\n move(n-1, b, a, c)\n\nmove(2, 'A', 'B', 'C')","sub_path":"fact.py","file_name":"fact.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540361405","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Carolina Aguilar\n# Copyright (C) 2016 Carlos Jenkins\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,\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\n\"\"\"\nID optical recognition pipeline based on OpenCV and Tesseract.\n\"\"\"\n\nfrom __future__ import unicode_literals, absolute_import\nfrom __future__ import print_function, division\n\nimport cv2\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom traceback import format_exc\n\nfrom six import add_metaclass\n\n\nlog = logging.getLogger(__name__)\n\n\n@add_metaclass(ABCMeta)\nclass TunnablePipeline(object):\n\n ESCAPE_KEY = ord('\\x1b')\n DELTA_KEY = ord('-')\n\n def __init__(self):\n\n # Global delta for tunnable parameters modification\n self._delta = 1\n\n # Mapping between the tunnable parameter and it's output\n self._tune = {}\n\n # Mapping between a key and the tunnable parameter\n self._keys_map = {}\n\n # Boolean that enables the pipeline execution\n self._execute_pipeline = True\n\n def register_tunnable(self, name, initial_value, tunning_key):\n\n if name in self._tune:\n raise Exception(\n 'Name \"{}\" already registered'.format(name)\n )\n\n key_code = ord(tunning_key)\n if key_code in self._keys_map:\n raise Exception(\n 'Tunning key \"{}\" already registered'.format(tunning_key)\n )\n\n self._tune[name] = initial_value\n self._keys_map[key_code] = name\n\n def get_tunnable(self, name):\n return self._tune[name]\n\n def handle_keys(self):\n \"\"\"\n Handle keys commands:\n\n - Press ESC to exit.\n - Press - to change delta for tunning (between +1 and -1)\n - Press any of the tunning parameters keys to modify that parameter.\n \"\"\"\n key = cv2.waitKey(1)\n if key < 0:\n return True\n key &= 0xFF\n\n if key == self.ESCAPE_KEY:\n return False\n\n if key == self.DELTA_KEY:\n self._delta *= -1\n log.info('Delta changed to: {}'.format(self._delta))\n return True\n\n if key in self._keys_map:\n self._tune[self._keys_map[key]] += self._delta\n log.info(\n 'New values for tunning parameters:\\n{}'.format(\n self._tune\n )\n )\n self._execute_pipeline = True\n return True\n\n log.debug('Unknown key pressed: {} ({})'.format(chr(key), key))\n return True\n\n @abstractmethod\n def run(self):\n pass\n\n @abstractmethod\n def pipeline(self, frame):\n pass\n\n\nclass TunnableVideo(TunnablePipeline):\n\n def run(self):\n\n camera = None\n try:\n # Open camera\n camera = cv2.VideoCapture(0)\n\n keep_running = True\n while keep_running:\n\n # Read frame\n success, frame = camera.read()\n if not success:\n raise Exception('Failed to read from camera')\n\n # Execute pipeline\n if self._execute_pipeline:\n try:\n self.pipeline(frame)\n except:\n self._execute_pipeline = False\n log.error('Pipeline crashed :(')\n log.debug(format_exc())\n\n # Display error to the user\n cv2.putText(\n frame,\n 'Pipeline crashed :(',\n (30, 30), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)\n )\n cv2.imshow('frame', frame)\n\n # Handle command keys\n keep_running = self.handle_keys()\n\n finally:\n if camera is not None:\n camera.release()\n cv2.destroyAllWindows()\n\n\nclass IdCardPipeline(TunnableVideo):\n\n def __init__(self):\n super(IdCardPipeline, self).__init__()\n\n tunnables = [\n # Adaptive threshol\n ('adaptive_c', 40, 'c'),\n ('adaptive_block_size', 75, 'b'),\n # Gaussian blu, # Gaussi\n ('gaussian_kernel_width', 3, 'w'),\n ('gaussian_kernel_height', 3, 'h'),\n ('gaussian_deviation_x', 0, 'x'),\n ('gaussian_deviation_y', -10, 'y'),\n ]\n\n for tunnable in tunnables:\n self.register_tunnable(*tunnable)\n\n def pipeline(self, frame):\n tn = self.get_tunnable\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n adaptive = cv2.adaptiveThreshold(\n gray,\n # maxValue: Non-zero value assigned to the pixels for which\n # the condition is satisfied\n 255,\n cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY,\n # blockSize: Size of a pixel neighborhood that is used to\n # calculate a threshold value for the pixel: 3, 5, 7, and\n # so on.\n tn('adaptive_block_size'),\n # C: Constant subtracted from the mean or weighted mean.\n # Normally, it is positive but may be zero or negative as\n # well.\n tn('adaptive_c'),\n )\n blur = cv2.GaussianBlur(\n adaptive,\n # ksize: sigmaX: Gaussian kernel size. ksize.width and\n # ksize.height can differ but they both must be positive and\n # odd. Or, thesigmaY: y can be zero's and then they are\n # computed from sigma.\n (\n tn('gaussian_kernel_width'),\n tn('gaussian_kernel_height')\n ),\n # sigmaX: Gaussian kernel standard deviation in X direction.\n tn('gaussian_deviation_x'),\n # sigmaY: Gaussian kernel standard deviation in Y direction;\n # if sigmaY is zero, it is set to be equal to sigmaX,\n # if both sigmas are zeros, they are computed from\n # ksize.width and ksize.height, respectively\n # tunning_parameters['gaussian_deviation_y']\n )\n\n cv2.imshow('frame', frame)\n cv2.imshow('gray', gray)\n cv2.imshow('adaptive', adaptive)\n cv2.imshow('blur', blur)\n\n\nFORMAT = '%(asctime)s:::%(levelname)s:::%(message)s'\nLEVELS = {\n 0: logging.ERROR,\n 1: logging.WARNING,\n 2: logging.INFO,\n 3: logging.DEBUG,\n}\nLEVEL = 3\n\n\nif __name__ == '__main__':\n logging.basicConfig(format=FORMAT, level=LEVELS[LEVEL])\n pipeline = IdCardPipeline()\n pipeline.run()\n","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"377097307","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2016 Pharmadus. All Rights Reserved\n# $Óscar Salvador $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import models, fields, api\n\n\nclass StockLocation(models.Model):\n _inherit = 'stock.location'\n\n finished_product_location = fields.Boolean('Is a finished product location?',\n default=False)\n\n\nclass StockPickingType(models.Model):\n _inherit = 'stock.picking.type'\n\n product_drop_default = fields.Boolean('Default picking type for product drop?',\n default=False)\n\n @api.one\n def check_only_one_product_drop(self):\n # Only one can be active in each warehouse\n picking_types = self.search([\n ('warehouse_id', '=', self.warehouse_id.id),\n ('code', '=', 'internal'),\n ('product_drop_default', '=', True),\n ('id', '<>', self.id)\n ])\n for pt in picking_types:\n pt.product_drop_default = False\n\n @api.model\n def create(self, vals):\n res = super(StockPickingType, self).create(vals)\n\n if res and res.product_drop_default:\n res.check_only_one_product_drop()\n\n return res\n\n @api.multi\n def write(self, vals):\n res = super(StockPickingType, self).write(vals)\n\n if vals.get('product_drop_default', False):\n for pt in self:\n pt.check_only_one_product_drop()\n\n return res","sub_path":"project-addons/product_drop/models/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"426343039","text":"def create_model(opt):\n model = opt['model']\n\n if model == 'sr':\n from .SR_model import SRModel as M\n elif model == 'srgan':\n from .SRGAN_model import SRGANModel as M\n elif model == 'sftgan':\n from .SFTGAN_ACD_model import SFTGAN_ACD_Model as M\n else:\n raise NotImplementedError('Model [%s] not recognized.' % model)\n m = M(opt)\n print('Model [%s] is created.' % m.__class__.__name__)\n return m\n","sub_path":"codes/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"519031881","text":"import os\nimport shutil\nfrom subprocess import Popen, check_output\nimport time\n\npartitions = [\"students\", \"gpulong\"] # order == priority\njobbers = {0:\"studentsgo\", 1: \"longgo\"} # sbatch creator for each partition\n\nme = check_output([\"whoami\"])[:-1].decode(\"utf-8\") # only worx when nobody else has koss in their name <3\nshellext = \".sh\"\n\ndef wait_for_green_light(partitions=partitions, my_jobs_per_partition=[2,6], update=10):\n \"\"\" waits until my squeue has a place\"\"\"\n\n while True:\n\n print(f\"Waiting for another {update} seconds to check if there's an opening on any of: {partitions}\")\n\n time.sleep(update)\n\n partition_with_slot = -1\n\n sq = str(check_output([\"squeue\"])).split(\"\\\\n\")\n for i, part in enumerate(partitions):\n\n # check if partition is empty enough\n allowed_num_jobs_here = my_jobs_per_partition[i]\n\n part_sq = [ job for job in sq if len(job.split()) > 5 and part in job.split()[1] ]\n my_part_sq = [ job for job in part_sq if len(job.split()) > 5 and me in job.split()[3] ] # relies on job name not having whitespace ! FIXME\n \n if len(my_part_sq) < allowed_num_jobs_here:\n partition_with_slot = i\n break\n\n if partition_with_slot != -1:\n return partition_with_slot\n\ndef main(args):\n dry = \"dry\" in args\n clean = \"clean\" in args\n\n search_space = {}\n search_space[\"hops\"] = [(\"k_hops\",), \\\n [(1,),(2,),(3,)]]\n search_space[\"feed\"] = [(\"kb_input_feeding\",\"kb_feed_rnn\"),\\\n [(False, False), (True, False), (True, True)]]\n search_space[\"enc\"] = [(\"kb_max_dims\",\"posEncKBkeys\"),\\\n [([256], False), ([16,32], False), ([256],True)]]\n\n\n architectures = [\"rnn\"] # remember to add if case for tfstyletf\n init = \"GridInit\"\n path = \"configs/kvr/grid/\"\n ext = \".yaml\"\n models = \"modelsgrid/\"\n\n architecture = architectures[0] # for the moment: only do gridsearch for RNN\n _arch_cfg = architecture + init + ext \n arch_config = path + _arch_cfg\n \n if clean:\n # to clean all configs from /configs/kvr/grid/\n _tf_cfg = \"tf\"+init+ext\n tmp = path+\"tmp/\"\n if not os.path.isdir(tmp):\n os.mkdir(tmp)\n for main_cfg in [ _arch_cfg, _tf_cfg ]:\n if os.path.isfile(path+main_cfg):\n shutil.move(path+main_cfg, tmp+main_cfg)\n else:\n assert os.path.isfile(tmp+main_cfg), f\"init config '{main_cfg}' found in neither of {path} or {tmp}\"\n Popen(\"rm \"+path+\"*\", shell=True ).wait() # remove all generated configs\n for main_cfg in [ _arch_cfg, _tf_cfg ]:\n shutil.move(tmp+main_cfg, path+main_cfg)\n os.rmdir(tmp)\n exit(\"Cleaned all grid configs from \"+path)\n\n for k in search_space[\"hops\"][1]:\n for false_ff_rnn in search_space[\"feed\"][1]:\n for oneD_twoD_pos in search_space[\"enc\"][1]:\n\n gridcombo = architecture+str(k[0])+str(int(false_ff_rnn[0]))+str(int(false_ff_rnn[1]))+\"x\"+\"x\".join([str(dim) for dim in oneD_twoD_pos[0]])+\"x\"+str(int(oneD_twoD_pos[1]))\n\n new_cfg = path+gridcombo+ext\n\n ### check if model directory exists; if yes then continue ###\n existing_models = str(check_output([\"ls\", models])).split(\"\\\\n\")\n\n skip_job = False\n for model in existing_models:\n if gridcombo in model:\n skip_job = True\n break\n if skip_job: continue\n ### end check ###\n \n if not dry:\n free_partition = wait_for_green_light()\n\n Popen([f\"cp {arch_config} {new_cfg}\"], shell=True).wait() # copy the default config for this architecture into a new one\n assert os.path.isfile(new_cfg), (os.listdir(path), arch_config, new_cfg) # confirm the copying worked lol\n\n # k_hops, kb_input_feeding, kb_feed_rnn, kb_max_dims, posEncKBkeys\n cfg_param_valuations = {}\n\n for dimension, options in [(\"hops\", k), (\"feed\", false_ff_rnn), (\"enc\", oneD_twoD_pos)]:\n cfg_params_dim = search_space[dimension][0]\n for i, p in enumerate(cfg_params_dim):\n cfg_param_valuations[p] = options[i]\n\n for param, setting in cfg_param_valuations.items():\n\n param_regex_replace = f\"s/{param}: [^#]*#/{param}: {setting} #/g\"\n Popen('sed -i '+f'\\\"{param_regex_replace}\\\" '+new_cfg, shell=True).wait()\n \n \n Popen(\"cat \"+ new_cfg, shell=True).wait() # REMOVE THIS\n\n if not dry:\n Popen(f\"./{jobbers[free_partition]+shellext} {gridcombo}\",shell=True).wait()\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) > 1:\n sys.exit(main(sys.argv[1:]))\n else:\n main([])\n","sub_path":"gridsearch.py","file_name":"gridsearch.py","file_ext":"py","file_size_in_byte":5125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"511984384","text":"'''\nCreated on Jan 5, 2014\n\n@author: nelson\n'''\nfrom django import forms\n\n\nclass Input_trad(forms.Form):\n frase = forms.CharField(widget=forms.Textarea(\n attrs={\n 'class':'text',\n 'rows':5, \n 'cols':50,\n 'wrap':'SOFT',\n 'style':'overflow: hidden; resize:none; height: 187px;',\n 'placeholder':'Insira texto'}), \n required=True)\n resultado = forms.CharField(max_length=200, widget=forms.Textarea(\n attrs={\n 'rows':5, \n 'cols':50, \n 'placeholder':'Texto traduzido'}),\n required=False)\n \n #CHOICES = ('pten', 'enpt', 'ptcn') \n #lingua = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)\n\n \nclass ShowBest(forms.Form):\n #best_trans = forms.ChoiceField(max_length=100)\n escolhida = forms.ChoiceField(widget=forms.Select)\n ","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"401363189","text":"# Copyright 2011-2013 GRNET S.A. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials\n# provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS\n# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# The views and conclusions contained in the software and\n# documentation are those of the authors and should not be\n# interpreted as representing official policies, either expressed\n# or implied, of GRNET S.A.\n\nfrom django.http import HttpResponse\n\nimport gd\nimport os\n\nfrom cStringIO import StringIO\n\nimport rrdtool\n\nfrom Crypto.Cipher import AES\nfrom base64 import urlsafe_b64decode\nfrom hashlib import sha256\n\nfrom synnefo_stats import settings\n\nfrom synnefo.util.text import uenc\nfrom snf_django.lib.api import faults, api_method\n\nfrom logging import getLogger\nlog = getLogger(__name__)\n\n\ndef read_file(filepath):\n f = open(filepath, \"r\")\n\n try:\n data = f.read()\n finally:\n f.close()\n\n return data\n\n\ndef draw_cpu_bar(fname, outfname=None):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n\n try:\n values = rrdtool.fetch(fname, \"AVERAGE\")[2][-20:]\n except rrdtool.error:\n values = [(0.0, )]\n\n v = [x[0] for x in values if x[0] is not None]\n if not v:\n # Fallback in case we only get NaNs\n v = [0.0]\n # Pick the last value\n value = v[-1]\n\n image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT))\n\n border_color = image.colorAllocate(settings.BAR_BORDER_COLOR)\n white = image.colorAllocate((0xff, 0xff, 0xff))\n background_color = image.colorAllocate(settings.BAR_BG_COLOR)\n\n if value >= 90.0:\n line_color = image.colorAllocate((0xff, 0x00, 0x00))\n elif value >= 75.0:\n line_color = image.colorAllocate((0xda, 0xaa, 0x00))\n else:\n line_color = image.colorAllocate((0x00, 0xa1, 0x00))\n\n image.rectangle((0, 0),\n (settings.WIDTH - 1, settings.HEIGHT - 1),\n border_color, background_color)\n image.rectangle((1, 1),\n (int(value / 100.0 * (settings.WIDTH - 2)),\n settings.HEIGHT - 2),\n line_color, line_color)\n image.string_ttf(settings.FONT, 8.0, 0.0,\n (settings.WIDTH + 1, settings.HEIGHT - 1),\n \"CPU: %.1f%%\" % value, white)\n\n io = StringIO()\n image.writePng(io)\n io.seek(0)\n data = io.getvalue()\n io.close()\n return data\n\n\ndef draw_net_bar(fname, outfname=None):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n\n try:\n values = rrdtool.fetch(fname, \"AVERAGE\")[2][-20:]\n except rrdtool.error:\n values = [(0.0, 0.0)]\n\n v = [x for x in values if x[0] is not None and x[1] is not None]\n if not v:\n # Fallback in case we only get NaNs\n v = [(0.0, 0.0)]\n\n rx_value, tx_value = v[-1]\n\n # Convert to bits\n rx_value = rx_value * 8 / 10 ** 6\n tx_value = tx_value * 8 / 10 ** 6\n\n max_value = (int(max(rx_value, tx_value) / 50) + 1) * 50.0\n\n image = gd.image((settings.IMAGE_WIDTH, settings.HEIGHT))\n\n border_color = image.colorAllocate(settings.BAR_BORDER_COLOR)\n white = image.colorAllocate((0xff, 0xff, 0xff))\n background_color = image.colorAllocate(settings.BAR_BG_COLOR)\n\n tx_line_color = image.colorAllocate((0x00, 0xa1, 0x00))\n rx_line_color = image.colorAllocate((0x00, 0x00, 0xa1))\n\n image.rectangle((0, 0),\n (settings.WIDTH - 1, settings.HEIGHT - 1),\n border_color, background_color)\n image.rectangle((1, 1),\n (int(tx_value / max_value * (settings.WIDTH - 2)),\n settings.HEIGHT / 2 - 1),\n tx_line_color, tx_line_color)\n image.rectangle((1, settings.HEIGHT / 2),\n (int(rx_value / max_value * (settings.WIDTH - 2)),\n settings.HEIGHT - 2),\n rx_line_color, rx_line_color)\n image.string_ttf(settings.FONT, 8.0, 0.0,\n (settings.WIDTH + 1, settings.HEIGHT - 1),\n \"TX/RX: %.2f/%.2f Mbps\" % (tx_value, rx_value), white)\n\n io = StringIO()\n image.writePng(io)\n io.seek(0)\n data = io.getvalue()\n io.close()\n return data\n\n\ndef draw_cpu_ts(fname, outfname):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n outfname += \"-cpu.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1d\", \"-e\", \"-20s\",\n #\"-t\", \"CPU usage\",\n \"-v\", \"%\",\n #\"--lazy\",\n \"DEF:cpu=%s:value:AVERAGE\" % fname,\n \"LINE1:cpu#00ff00:\")\n\n return read_file(outfname)\n\n\ndef draw_cpu_ts_w(fname, outfname):\n fname = os.path.join(fname, \"cpu\", \"virt_cpu_total.rrd\")\n outfname += \"-cpu-weekly.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1w\", \"-e\", \"-20s\",\n #\"-t\", \"CPU usage\",\n \"-v\", \"%\",\n #\"--lazy\",\n \"DEF:cpu=%s:value:AVERAGE\" % fname,\n \"LINE1:cpu#00ff00:\")\n\n return read_file(outfname)\n\n\ndef draw_net_ts(fname, outfname):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n outfname += \"-net.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1d\", \"-e\", \"-20s\",\n \"--units\", \"si\",\n \"-v\", \"Bits/s\",\n \"COMMENT:\\t\\t\\tAverage network traffic\\\\n\",\n \"DEF:rx=%s:rx:AVERAGE\" % fname,\n \"DEF:tx=%s:tx:AVERAGE\" % fname,\n \"CDEF:rxbits=rx,8,*\",\n \"CDEF:txbits=tx,8,*\",\n \"LINE1:rxbits#00ff00:Incoming\",\n \"GPRINT:rxbits:AVERAGE:\\t%4.0lf%sbps\\t\\g\",\n \"LINE1:txbits#0000ff:Outgoing\",\n \"GPRINT:txbits:AVERAGE:\\t%4.0lf%sbps\\\\n\")\n\n return read_file(outfname)\n\n\ndef draw_net_ts_w(fname, outfname):\n fname = os.path.join(fname, \"interface\", \"if_octets-eth0.rrd\")\n outfname += \"-net-weekly.png\"\n\n rrdtool.graph(outfname, \"-s\", \"-1w\", \"-e\", \"-20s\",\n \"--units\", \"si\",\n \"-v\", \"Bits/s\",\n \"COMMENT:\\t\\t\\tAverage network traffic\\\\n\",\n \"DEF:rx=%s:rx:AVERAGE\" % fname,\n \"DEF:tx=%s:tx:AVERAGE\" % fname,\n \"CDEF:rxbits=rx,8,*\",\n \"CDEF:txbits=tx,8,*\",\n \"LINE1:rxbits#00ff00:Incoming\",\n \"GPRINT:rxbits:AVERAGE:\\t%4.0lf%sbps\\t\\g\",\n \"LINE1:txbits#0000ff:Outgoing\",\n \"GPRINT:txbits:AVERAGE:\\t%4.0lf%sbps\\\\n\")\n\n return read_file(outfname)\n\n\ndef decrypt(secret):\n # Make sure key is 32 bytes long\n key = sha256(settings.STATS_SECRET_KEY).digest()\n\n aes = AES.new(key)\n return aes.decrypt(urlsafe_b64decode(secret)).rstrip('\\x00')\n\n\navailable_graph_types = {'cpu-bar': draw_cpu_bar,\n 'net-bar': draw_net_bar,\n 'cpu-ts': draw_cpu_ts,\n 'net-ts': draw_net_ts,\n 'cpu-ts-w': draw_cpu_ts_w,\n 'net-ts-w': draw_net_ts_w\n }\n\n\n@api_method(http_method='GET', token_required=False, user_required=False,\n format_allowed=False, logger=log)\ndef grapher(request, graph_type, hostname):\n try:\n hostname = decrypt(uenc(hostname))\n except (ValueError, TypeError):\n raise faults.BadRequest(\"Invalid encrypted virtual server name\")\n fname = uenc(os.path.join(settings.RRD_PREFIX, hostname))\n if not os.path.isdir(fname):\n raise faults.ItemNotFound('No such instance')\n\n outfname = uenc(os.path.join(settings.GRAPH_PREFIX, hostname))\n draw_func = available_graph_types[graph_type]\n\n response = HttpResponse(draw_func(fname, outfname),\n status=200, content_type=\"image/png\")\n response.override_serialization = True\n\n return response\n","sub_path":"snf-stats-app/synnefo_stats/grapher.py","file_name":"grapher.py","file_ext":"py","file_size_in_byte":8977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302607561","text":"import pylab\n\ndef init():\n\tglobal times, prices\n\ttimes = []\n\tprices = []\n\tinit = 1\n\twith open(\"BHP.csv\", \"r\") as file:\n\t\tfor line in file:\n\t\t\tif(init == 1):\n\t\t\t\tinit = 0\n\t\t\t\tcontinue\n\t\t\tc = line.split(\",\")\n\t\t\ttime = c[0]\n\t\t\tprice = float(c[4])\n\t\t\ttimes.append(time)\n\t\t\tprices.append(price)\n\n\n\t\t\t\n\ndef observe():\n\tglobal times, prices\n\tpylab.subplot(2,1,1)\n\tpylab.plot(prices)\n\tmin_price = min(prices)\n\tmax_price = max(prices)\n\tpylab.ylim(min_price-10, max_price+10)\n\tpylab.xticks([])\n\tpylab.subplot(2,2,3)\t\n\tpylab.plot([1,2,3,4], [1,2,3,4])\n\tpylab.subplot(2,2,4)\n\tpylab.plot([1,2,3,4], [2,3,4,5])\n\tpylab.show()\n\ninit()\nobserve()\n","sub_path":"subplot_test.py","file_name":"subplot_test.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368771935","text":"'''\nCreated on Apr 16, 2017\n\n@author: tianyu\n'''\nimport time\nimport Layer\nimport theano\nimport numpy as np\nimport numpy.random as rng\nimport theano.tensor as T\nimport theano.tensor.nnet as nn\nimport theano.tensor.nlinalg as nlg\nimport theano.sparse.basic as S\nimport theano.sparse\nimport scipy.sparse as sp\nimport Datasets\n\ndef quickMul(a,b):\n li = np.transpose(np.nonzero(a))\n rows = []\n columns = []\n data = []\n size = theano.sparse.basic.csm_shape(a)[0].eval()\n for i in li:\n row = i[0]\n column = i[1]\n rows.append(row)\n columns.append(column)\n data.append(a[row,column]*b[row,column])\n return sp.csr_matrix((data,(rows,columns)), shape=(size, size))\n\nclass SmoothAE(object):\n \n def __init__(self, inputSize, learningRule = None, costFunction = None):\n \"\"\"Initialize the parameters for the Smooth Auto Encoder\n\n :type inputData: theano.tensor.TensorType\n :param inputData: symbolic variable that describes the input of the\n architecture (one minibatch)\n\n \"\"\"\n \n \"\"\" Hyper-parameters \"\"\"\n # Sub-space dimension \n self._k = 3\n \n # Learning rate\n self._eta = 5e-1\n self._eta_increase_ratio = 1.2\n self._eta_max = 1e-1\n \n # Regularization penalty\n self._lamb = 1e-1\n \n # epoch num\n self._epochNum = 0\n \n \"\"\" Initalize \"\"\"\n self._inputNum = inputSize\n \n # user define grad because auto generated grad not working correctly\n # grad of relu\n d_relu = lambda x: np.greater_equal(x,0)*1.\n \n sig = lambda x: 1/(1+np.exp(-x))\n \n def d_sig(x):\n tmp = sig(x)\n return tmp * (1 - tmp)\n \n # Layers\n self._smoothLayer = Layer.Layer(nodeNum = self._inputNum)\n self._contextLayer = Layer.Layer(nodeNum = self._inputNum)\n self._contextLayer.setAverageOut(S.structured_dot(T.as_tensor_variable([rng.rand(self._inputNum)]),Datasets.W).eval()[0])\n self._wmatrixLayer = Layer.Layer(nodeNum = self._k, activation = nn.relu, grad = d_relu)\n# self._outputLayer = Layer.Layer(nodeNum = self._inputNum, activation = sig, grad = d_sig)\n self._outputLayer = Layer.Layer(nodeNum = self._inputNum)\n \n self._layers = [self._smoothLayer,self._contextLayer,self._wmatrixLayer,self._outputLayer]\n \n # Connections\n # input layer to smooth Layer\n # 1-self._alpha\n# self._alpha = theano.shared(0.5)\n self._alpha = 0.5\n \n rat = np.sqrt(self._inputNum * self._k)\n # smooth layer to context layer\n # 1\n \n # context layer to smooth layer\n # W * self._alpha\n \n # smooth layer to h matrix layer\n # _h_star, _b_star\n _values = np.asarray(rng.uniform(low=0.1/rat,high=1./rat,size=(self._inputNum, self._k)))\n# self._h_star = theano.shared(value=_values, name='W_star', borrow=True)\n# self._b_star = theano.shared(np.zeros(self._k))\n self._h_star = _values\n self._b_star = np.zeros(self._k)\n \n # h matrix layer to output layer\n # _w, _b \n _values = np.asarray(rng.uniform(low=0.1/rat,high=1./rat,size=(self._k, self._inputNum)))\n# self._h = theano.shared(value=_values, name='W', borrow=True)\n# self._b = theano.shared(np.zeros(self._inputNum))\n self._h = _values\n self._b = np.zeros(self._inputNum)\n \n # one epoch\n def learn(self,inputData):\n if not len(inputData[0]) == self._inputNum:\n raise ValueError(\"Input number error: get \" + str(len(inputData[0])) + \", expect \" + str(self._inputNum))\n self._miniBatchSize = len(inputData)\n \n self._err = 0;\n h_change = np.zeros((self._k,self._inputNum))\n# b_change = np.zeros(self._inputNum)\n h_star_change = np.zeros((self._inputNum,self._k))\n# b_star_change = np.zeros(self._k)\n alpha_change = 0\n \n self._W=[]\n self._W_in=[]\n self._O=[]\n self._O_in=[]\n self._d_alpha=[]\n count = 0\n \n for sample in inputData:\n t0 = time.time()\n count += 1\n \n \"\"\" define neural network \"\"\"\n \"\"\" Forward \"\"\"\n # define input layer \n x = sample\n # define smooth layer\n # smooth function is f_(t+1) = alpha * W * f_t + (1-alpha) * f_0\n smIn = self._alpha * T.transpose(S.structured_dot(Datasets.W,T.transpose(T.as_tensor_variable([self._contextLayer.getAverageOut()])))).eval()[0] + np.multiply(x,1-self._alpha)\n smOut = self._smoothLayer.computeOut(smIn)\n# print(time.time()-t0)\n # define context layer\n # coIn = smOut\n # coOut = self._contextLayer.computeOut(coIn)\n \n # define h matrix layer\n# hmIn = np.dot(smOut,self._h_star) + self._b_star\n wmIn = np.dot(smOut,self._h_star)\n wmOut = self._wmatrixLayer.computeOut(wmIn)\n \n self._W_in.append(np.copy(wmIn))\n self._W.append(np.copy(wmOut))\n \n # define out layer\n# ouIn = np.dot(hmOut,self._h) + self._b\n ouIn = np.dot(wmOut,self._h)\n ouOut = self._outputLayer.computeOut(ouIn)\n \n self._O_in.append(np.copy(ouIn))\n self._O.append(np.copy(ouOut))\n \n # error function\n terr = ((x - ouOut) ** 2).sum()\n self._err += terr\n # update context layer\n self._contextLayer.computeOut(self._smoothLayer.getOutValues())\n \n \"\"\" Back propagation \"\"\"\n # error for out layer\n self._outputLayer.setErrors(\n (sample - self._outputLayer.getOutValues()) \n * self._outputLayer.getGrad()(self._outputLayer.getOutValues()))\n # error for h matrix layer\n self._wmatrixLayer.setErrors(\n np.dot(self._outputLayer.getErrors(),np.transpose(self._h)) \n * self._wmatrixLayer.getGrad()(self._wmatrixLayer.getOutValues()))\n # error for smooth layer\n self._smoothLayer.setErrors(\n (np.dot(self._wmatrixLayer.getErrors(),np.transpose(self._h_star))\n + self._contextLayer.getAverageError()) / 2\n * self._smoothLayer.getGrad()(self._smoothLayer.getOutValues()))\n # error for context layer\n# print(time.time()-t0)\n self._contextLayer.setErrors(\n self._alpha\n * S.structured_dot(T.as_tensor_variable([self._smoothLayer.getErrors()]),Datasets.W).eval()[0]\n * self._contextLayer.getGrad()(self._contextLayer.getOutValues()))\n# print(time.time()-t0)\n \n \"\"\" update weights\"\"\"\n h_change += np.dot(np.transpose([self._wmatrixLayer.getOutValues()]), [self._outputLayer.getErrors()])\n# b_change += self._outputLayer.getErrors()\n h_star_change += np.dot(np.transpose([self._smoothLayer.getOutValues()]), [self._wmatrixLayer.getErrors()])\n# b_star_change += self._wmatrixLayer.getErrors()\n# print(time.time()-t0)\n alpha_change_c = S.sp_sum(quickMul(Datasets.W,S.structured_dot(S.transpose(sp.csr_matrix(np.asarray([self._contextLayer.getAverageOut()]))), sp.csr_matrix(np.asarray([self._smoothLayer.getErrors()]))).eval())).eval()/Datasets.W_SUM \n alpha_change_i = np.sum(np.multiply(x,self._smoothLayer.getErrors()))/self._inputNum\n alpha_change += alpha_change_c - alpha_change_i\n# print(time.time()-t0)\n# atmp = S.sp_sum(S.mul(Datasets.W,S.dot(S.transpose(sp.csr_matrix(np.asarray([self._contextLayer.getAverageOut()]))), sp.csr_matrix(np.asarray([self._smoothLayer.getErrors()]))))).eval()\n# alpha_change_c = atmp/Datasets.NON_ZEROS\n# alpha_change_i = np.sum(self._smoothLayer.getErrors())/self._inputNum\n# alpha_change += alpha_change_c - alpha_change_i \n# self._d_alpha.append([np.copy(alpha_change_c),np.copy(alpha_change_i),np.copy(alpha_change)])\n self._d_alpha.append(np.copy(alpha_change))\n \n# Datasets.log(str(count) + \"/\" + str(len(inputData)) + \"err:\" + str(terr) + \"(\" + str(time.time()-t0) + \"s)\")\n# print(\"____________\")\n \n \"\"\" update network\"\"\"\n \n t0 = time.time()\n \n h_change /= self._miniBatchSize\n# b_change /= self._miniBatchSize\n h_star_change /= self._miniBatchSize\n# b_star_change /= self._miniBatchSize\n alpha_change /= self._miniBatchSize\n \n self._d_h = np.copy(h_change)\n# self._d_b = b_change\n self._d_h_star = np.copy(h_star_change)\n \n for layer in self._layers:\n layer.update()\n \n # penalty extra err\n a = T.matrix()\n f_penalty = theano.function([a], self._lamb * nlg.trace(T.dot(S.structured_dot(a,Datasets.L),T.transpose(a))))\n penalty = f_penalty(self._h)\n f_h_change = theano.function([a],-2 * self._lamb * T.transpose(S.structured_dot(Datasets.L,T.transpose(a))))\n h_change2 = f_h_change(self._h)\n \n self._hpe = h_change2\n \n # update weight\n self._h += self._eta * h_change + h_change2\n# self._b += self._eta * b_change\n self._h_star += self._eta * h_star_change\n# self._b_star += self._eta * b_star_change\n# self._alpha += self._eta * alpha_change\n self._alpha += 0.1 * alpha_change\n\n if self._alpha > 0.899: self._alpha = 0.899\n if self._alpha < 0: self._alpha = 0\n \n Datasets.log(\"err=\" + str(self._err / self._miniBatchSize) + \" penalty=\" + str(penalty))\n self._err = self._err / self._miniBatchSize + penalty \n# if self._eta 1000):\n self.save()\n break\n if(self._err < 0.01):\n self.save()\n break\n if epoch_num % 1 == 0:\n self.save(\"_\" + str(epoch_num))\n \n def save(self,str=\"\"):\n Datasets.dmpnp(\"w\" + str, self._W)\n Datasets.dmpnp(\"w_in\" + str, self._W_in)\n Datasets.dmpnp(\"o\" + str, self._O)\n Datasets.dmpnp(\"o_in\" + str, self._O_in)\n Datasets.dmpnp(\"h\" + str, self._h)\n Datasets.dmpnp(\"h_star\" + str, self._h_star)\n# Datasets.dmpnp(\"B\" + str, self._b)\n# Datasets.dmpnp(\"B_star\" + str, self._b_star)\n Datasets.dmpnp(\"d_alpha\" + str, self._d_alpha)\n Datasets.dmpnp(\"d_h\" + str, self._d_h)\n# Datasets.dmpnp(\"d_b\" + str, self._d_b)\n Datasets.dmpnp(\"d_h_star\" + str, self._d_h_star)\n# Datasets.dmpnp(\"d_b_star\" + str, self._d_b_star)\n Datasets.dmpnp(\"hpe\" + str, self._hpe)\n Datasets.dmpnp(\"s_err\" + str, self._smoothLayer.getAverageError())\n Datasets.dmpnp(\"c_err\" + str, self._contextLayer.getAverageError())\n Datasets.dmpnp(\"h_err\" + str, self._wmatrixLayer.getAverageError())\n Datasets.dmpnp(\"o_err\" + str, self._outputLayer.getAverageError())\n Datasets.dmpnp(\"s_out\" + str, self._smoothLayer.getAverageOut())\n Datasets.dmpnp(\"c_out\" + str, self._contextLayer.getAverageOut())\n# Datasets.dmpnp(\"h_out\" + str, self._wmatrixLayer.getAverageOut())\n# Datasets.dmpnp(\"o_out\" + str, self._outputLayer.getAverageOut())\n \ndef test_SmoothAE():\n data = Datasets.samples\n network = SmoothAE(len(Datasets.labels))\n network.train(data)\n \nif __name__ == '__main__':\n test_SmoothAE()","sub_path":"Main/SmoothAE.py","file_name":"SmoothAE.py","file_ext":"py","file_size_in_byte":12373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271196669","text":"from rest_framework.routers import DefaultRouter\nfrom .views import (RfqSupplierHeaderViewSet, RfqSupplierDetailViewSet,\n QuotationSupplierHeaderViewSet, QuotationSupplierDetailViewSet)\n\nrouter = DefaultRouter()\nrouter.register(r'rfq_header',RfqSupplierHeaderViewSet, basename='rfq_header')\nrouter.register(r'rfq_detail',RfqSupplierDetailViewSet, basename='rfq_detail')\nrouter.register(r'quotation_header_supplier',QuotationSupplierHeaderViewSet, basename='quotation_header')\nrouter.register(r'quotation_detail_supplier',QuotationSupplierDetailViewSet, basename='quotation_detail')\n\n\nurlpatterns = router.urls\n","sub_path":"backend/supplier/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"10217876","text":"import unittest\n# simple_solver(https://github.com/ptigas/simple-CAPTCHA-solver)\nfrom captcha_decoder import decoder\nfrom captcha import captcha_to_string\nfrom PIL import Image\n\npath2expected = {\n 'capcha_07-12 00:33:15.png': 'CTCH',\n 'capcha_07-12 00:28:33.png': 'CP8F',\n 'capcha_07-12 00:26:43.png': 'CWJB',\n 'capcha_07-11 23:34:23.png': 'CQ3R'\n}\n\n\ndef format_result(expected, actual):\n result = \"True\" if expected == actual else \"False\"\n return f\"{result} {expected} {actual}\"\n\n\nclass TestCapchaSolvers(unittest.TestCase):\n\n def test_simple_solver(self):\n solver = decoder\n print(\"\\n\".join(format_result(answer, solver(path)) for path,\n answer in path2expected.items()))\n\n def test_solver(self):\n def solver(path):\n return captcha_to_string(Image.open(path))\n print(\"\\n\".join(format_result(expected, solver(path)) for path,\n expected in path2expected.items()))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_captcha_solver.py","file_name":"test_captcha_solver.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11618698","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl='https://baike.baidu.com/item/%E5%8C%97%E4%BA%AC%E5%9C%B0%E9%93%81/408485'\r\nuser_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'\r\nheaders = {'User-Agent': user_agent}\r\n\r\ndef get_all_subway_links(url):\r\n page = requests.get(url,headers=headers)\r\n soup =BeautifulSoup(page.content,'html.parser',from_encoding='utf-8') #page.content表示被解析的html格式的内容,html.parser表示解析用的解析器\r\n links=set()\r\n for link in page.text.findAll('table')[0].findAll('a'):\r\n links.add('http://baike.baidu.com/item/' + link.get_text())\r\n\r\n return list(links)\r\n\r\nlinks=get_all_subway_links(url)\r\nprint(links)\r\n","sub_path":"Course/part2/code_work1.py","file_name":"code_work1.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161960829","text":"from flask_injector import inject\nfrom stores.models.entities import Database\nfrom pony.orm import db_session, ObjectNotFound\n\n\nclass StoreService:\n @inject\n def __init__(self, db: Database):\n self.db = db\n\n @db_session\n def add_store(self, store_name):\n\n if self.db.model.Store.select(lambda s: s.store_name == store_name):\n return {'message': \"Store with name '{}' is already in use.\".format(store_name)}, 409\n\n store_db = self.db.model.Store(\n store_name=store_name\n )\n\n return store_db.to_dict(), 201\n\n @db_session\n def delete_store_by_store_name(self, store_name):\n\n store = self.db.model.Store.select(lambda s: s.store_name == store_name)\n\n if store:\n if store.first().items:\n return {'message': \"Store with name: '{}' has items in it.\".format(store_name)}, 403\n\n store.delete()\n return {'message': \"Store '{}' deleted\".format(store_name)}, 200\n\n return {'message': \"Store with name: '{}' does not exist.\".format(store_name)}, 404\n\n @db_session\n def get_store_by_store_name(self, store_name):\n\n store = self.db.model.Store.select(lambda s: s.store_name == store_name).first()\n\n if store:\n return store.to_dict(), 200\n\n return {'message': \"Store with name: '{}' does not exist.\".format(store_name)}, 404\n\n @db_session\n def get_stores(self):\n stores = self.db.model.Store.select()[:]\n\n result = [store.to_dict() for store in stores]\n\n return result, 200\n\n @db_session\n def get_store_items(self, store_name):\n store = self.db.model.Store.select(lambda s: s.store_name == store_name).first()\n\n items = [item.to_dict() for item in store.items]\n\n return items, 200\n","sub_path":"stores/services/StoreService.py","file_name":"StoreService.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56911016","text":"import argparse\nimport logging\nfrom customexceptions.ReadabilityErrors import ArgumentParsingError\nfrom config.AppConfiguration import DEFAULT_OUTPUT_FILE_NAME\nfrom pathlib import Path,PurePath\n \nclass ParseArguments: \n def processArgs() -> dict:\n \"\"\"\n Method to receive system arguments, parse them and pass on to Lisiblite processor\n Either an input file or text content is necessary along with output format and output file name\n :return: The argument values in a dictonary\n \"\"\"\n parser = argparse.ArgumentParser(description = 'Calculate readability of a text, either input text or file is required along with output filename and format. Input file will have precedence over text.')\n parser.add_argument('-t', '--text', help='The text on which processing would be done needs to be within double quotes and 500 characters long')\n parser.add_argument('-o', '--output-file', help='The name of the output file containing readability metrics', required=True)\n parser.add_argument('-i', '--input-file', help='The name of the input file on which processing would be done' , type=argparse.FileType('r'))\n parser.add_argument('-f', '--format', help='The format of the output file, default is CSV',choices =['pdf','csv'], default = 'csv')\n args = parser.parse_args()\n inputText = args.text\n inputFile = args.input_file\n outputFile = args.output_file\n outputFormat = '.' + args.format\n outputFile = ParseArguments.validateArgs(inputFile,inputText,outputFile,outputFormat)\n return dict(text = inputText, file = inputFile, output = outputFile, format = outputFormat)\n \n \n def validateArgs(inputFile,inputText,outputFile,outputFormat):\n \"\"\"\n Method to validate all system arguments\n :return: The output file name\n \"\"\"\t\n if not inputFile:\n if not inputText:\n raise ArgumentParsingError('Either input file or text is necessary for computing readability')\n elif len(inputText) < 500:\n logging.debug(inputText)\n raise ArgumentParsingError('Input text length has to be minimum 500 for computing readability, currently has {} characters only'.format(len(inputText)))\n logging.debug(inputText)\n logging.info(f'Using input text')\n \n else:\n logging.info(f'Using input file {inputFile}')\n try:\n if not Path(outputFile).suffix:\n Path(outputFile).mkdir(parents=True, exist_ok=True)\n outputFile = Path(outputFile,DEFAULT_OUTPUT_FILE_NAME).with_suffix(outputFormat)\n else:\n outPath = PurePath(outputFile)\n Path(outPath.parent).mkdir(parents=True, exist_ok=True)\n outputFile = Path(outPath.parent,DEFAULT_OUTPUT_FILE_NAME).with_suffix(outputFormat)\n with open(outputFile, 'w'): pass \n except OSError:\n raise ArgumentParsingError(f'Output file cannot be written to due to permission issue')\n logging.info(f'Using output file {outputFile}')\n return outputFile\n \n \n \nif __name__ == '__main__':\n logging.info('calling')\n ParseArguments.processArgs()","sub_path":"code/arg_parser.py","file_name":"arg_parser.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"311762672","text":"########\n#### setup.py: script to build and help development of the Vulnerability catalog.\n#### Date: 2019-Jun-13\n#### Version: 2.2.0\n#### Author: Daniel Avelino https://daavelino.github.io\n########\n\nimport sys\n\nMINIMAL_PYTHON_VERSION = (3, 6, 0)\n\npython_version = True\nif sys.version_info.major < MINIMAL_PYTHON_VERSION[0]:\n python_version = False\nif sys.version_info.major == MINIMAL_PYTHON_VERSION[0]:\n if sys.version_info.minor < MINIMAL_PYTHON_VERSION[1]:\n python_version = False\nif not python_version:\n min_python = str(MINIMAL_PYTHON_VERSION[0]) + '.' \\\n + str(MINIMAL_PYTHON_VERSION[1]) + '.' \\\n + str(MINIMAL_PYTHON_VERSION[2])\n error = '\\n[Warning]:\\n\\nMissing Python ' + min_python + \\\n ' (or greater).\\n\\n' + \\\n 'Please, get it at https://www.python.org/downloads.\\n\\n' + \\\n 'Aborting.\\n\\n'\n sys.stderr.write(error)\n sys.exit(1)\n \nimport secrets # secrets is New in Python 3.6.\nimport shutil\nimport os\nimport subprocess\nimport getpass\nimport re\nimport json\nimport time\n\nfrom pathlib import Path\n\nglobal PROJECT_NAME\nglobal APP_NAME\nglobal HOME_DIR\nglobal PYTHON_EXE\n\n\nPROJECT_NAME = 'base'\nAPP_NAME = 'catalog'\nHOME_DIR = Path(os.getcwd())\nBASE_DIR = Path(os.path.join(HOME_DIR, PROJECT_NAME,))\nPYTHON_EXE = os.path.split(Path(sys.executable))[-1]\nPIP_EXE = PYTHON_EXE.replace('python', 'pip')\n\ndef tuple_comparison(a, b):\n '''\n Evaluate tuples 'a' and 'b' as an ordered list of numbers \n and returns True if a >= b\n '''\n control = False\n for i in range(0, len(b)):\n if int(a[i]) >= int(b[i]):\n control = True\n break\n \n return control\n\n######## System properties:\ndef get_os():\n '''\n Returns a dictionary with OS system and version.\n The returned values are:\n\n Linux: 'linux'\n Windows: 'win32'\n Windows/Cygwin: 'cygwin'\n Mac OS X: 'darwin'\n '''\n env = dict()\n env['system'] = sys.platform\n \n return env\n\ndef check_parameters():\n allowed_params = {\n 'build': \"setup and builds the project from the scratch (with test data).\\n\",\n 'build-only': \"Just build project, without load data or create users.\\n\",\n 'build-novenv': \"same as 'build', but do not uses Python venv.\\n\",\n 'clean': \"remove all project related files.\\n\",\n 'createstartscript': \"creates the platform specific Catalog start script.\\n\",\n 'createsuperuser': \"creates an admin user to the catalog.\\n\",\n 'database': \"Setup an alternative database instead of default sqlite.\\n\",\n 'deep-clean': \"remove all project related files and venv structure.\\n\",\n 'loadtestdata': \"Add some test data into database.\\n\",\n 'templates': \"updates project's Templates, forms and static files only.\\n\",\n 'update-js': \"updates external JavaScript dependencies\\n\",\n 'urlsviews': \"updates project's Urls and Views only.\\n\" \n }\n # one and only one allowed parameter has to be passed.\n if (len(sys.argv) == 2) and (sys.argv[1] in allowed_params.keys()):\n param = sys.argv[1] # Because argv[0] is the file name.\n return param\n else:\n sys.stderr.write('\\nUsage:' + sys.argv[0] + ' , where are:\\n\\n')\n for i in allowed_params.items():\n sys.stderr.write(' ' + i[0] + ': ' + i[1])\n sys.stderr.write('\\nExiting.\\n')\n sys.exit(1)\n\ndef check_venv():\n ''' Check if Python's virtual environment is activated.'''\n param = check_parameters()\n if param == 'build-novenv':\n return True\n elif param == 'clean' or param == 'deep-clean':\n pass\n else:\n if 'VIRTUAL_ENV' not in os.environ.keys():\n message = \"\\n[Warning]: You are not using a Virtual environment.\\n\\n\\n\" \\\n + \"**** If not sure, type [ctrl]+[c] to exit. ****\\n\\n\\n\" \\\n + \" We encourage the usage of a Virtual environment in a non dedicated system.\\n\\n\" \\\n + \" You can activate it by:\\n\\n\" \\\n + \" 1. create a new Virtual environment directory by running:\\n\\n\" \\\n + \" \" + PYTHON_EXE + \" -m venv venv\\n\\n\" \\\n + \" 2. load it by running:\\n\" \\\n + \" 'source venv/bin/activate' (Linux/MacOs system)\\n\" \\\n + \" 'venv\\\\Scripts\\\\Activate.bat' (Windows system)\\n\\n\" \\\n + \" If you choose not use a Virtual environment, remember that you can remove the installed dependencies by running\\n\\n\" \\\n + \" 'pip uninstall -r requirements.txt' \\n\\n\"\n \n sys.stdout.write(message)\n time.sleep(10)\n \n return True\n\n return True\n\ndef check_pip():\n '''Check if pip is installed. If not, install it properly.'''\n try:\n import pip\n except ImportError: # Exit, since it is a required dependency.\n sys.stdout.write('\\n[Warning] Missing pip.\\n')\n sys.stdout.write('Please, install it first from here (https://pip.pypa.io), or from your package manager.\\nExiting.\\n')\n sys.exit(1)\n\ndef check_requirements():\n '''Ensure requirements.txt is satisfied.'''\n os.system(PIP_EXE + ' ' + 'install -r requirements.txt')\n sys.stdout.write('Done\\n')\n\ndef check_system_reqs():\n check_pip()\n check_requirements()\n\ndef deep_clean(control):\n '''Cleaning out old project structure'''\n env = get_os()\n system = env['system']\n sys.stdout.write('Cleaning out old project structure...\\n')\n \n if control == 'deep-clean':\n if 'VIRTUAL_ENV' in os.environ.keys():\n message = \"\\n[Warning]:\\n\\n\" \\\n + \"Please disable the Virtual environment first by running:\\n\\n\" \\\n + \" 'deactivate'\\n\\n\" \\\n + \"and run this script again. Aborting.\\n\"\n sys.stderr.write(message)\n sys.exit(-1)\n else:\n target = Path(os.path.join(os.path.curdir, 'venv'))\n if target.is_dir():\n shutil.rmtree(target)\n target = Path(os.path.join(os.path.curdir, 'base'))\n if target.is_dir():\n shutil.rmtree(target)\n\n\n if system.startswith('linux') or system.startswith('darwin'):\n filename = 'run.sh'\n if system.startswith('win32'):\n filename = 'run.bat'\n if os.path.isfile(filename):\n os.remove(filename)\n sys.stdout.write('Done\\n')\n\n \n######## End of System properties.\n\n######## Django properties:\ndef start_django_project():\n '''Starts Django's project creation.'''\n sys.stdout.write('Starting creating Django structure...\\n')\n os.system('django-admin startproject' + ' ' + PROJECT_NAME)\n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py startapp' + ' ' + APP_NAME)\n os.chdir(HOME_DIR)\n sys.stdout.write('Done\\n')\n\ndef importing_settings():\n '''\n Applying settings from \n metadata/settings/settings.py\n into project's structure\n '''\n sys.stdout.write('Copy settings.py from metadata...\\n')\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'settings', \\\n 'settings.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'base', 'settings.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_datamodel():\n '''\n Applying catalog data models from\n metadata/models/catalog/models.py and\n metadata/models/catalog/admin.py \n into project's structure.\n '''\n env = get_os()\n sys.stdout.write('Copy data models...\\n')\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'models', \\\n 'catalog', \\\n 'models.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'models.py')\n shutil.copy(src_path, dst_path)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'models', \\\n 'catalog', \\\n 'admin.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'admin.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n sys.stdout.write('Applying data models...\\n')\n os.chdir(PROJECT_NAME)\n os.system(PYTHON_EXE + ' ' + 'manage.py makemigrations' + ' ' + APP_NAME)\n os.system(PYTHON_EXE + ' ' + 'manage.py sqlmigrate' \\\n + ' ' \\\n + APP_NAME \\\n + ' ' \\\n + '0001')\n os.system(PYTHON_EXE + ' ' + 'manage.py migrate')\n os.chdir(BASE_DIR)\n sys.stdout.write('Done\\n')\n\ndef set_urls():\n '''\n Applying settings from \n metadata/urls/catalog/urls.py and\n metadata/urls/catalog/urls.py\n into project's structure.\n '''\n sys.stdout.write('Setting Urls...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'urls', \\\n 'admin', \\\n 'urls.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'base', 'urls.py') \n shutil.copy(src_path, dst_path)\n src_path = os.path.join(os.path.curdir,\\\n 'metadata', \\\n 'urls', \\\n 'catalog', \\\n 'urls.py')\n dst_path = os.path.join(os.path.curdir, 'base', 'catalog', 'urls.py')\n shutil.copy(src_path, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_views():\n '''\n Applying settings from \n metadata/views/catalog/* \n into project's structure.\n '''\n sys.stdout.write('Setting Views...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir,'metadata', \\\n 'views', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \n 'catalog', )\n for i in os.listdir(src_path):\n fsrc = os.path.join(src_path, i)\n shutil.copy(fsrc, dst_path)\n sys.stdout.write('Done\\n')\n\ndef set_templates():\n '''\n Applying settings from \n metadata/templates/catalog/*\n into project's structure.\n '''\n sys.stdout.write('Setting templates...\\n')\n os.chdir(HOME_DIR)\n files = [\n 'add.html',\n 'converter.html',\n 'delete.html',\n 'detail.html',\n 'fastupdate.html',\n 'home.html',\n 'index.html',\n 'panorama.html',\n 'search.html',\n 'update.html',\n 'upload.html'\n ]\n tmpl_srcdir = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'templates', \\\n 'catalog',)\n tmpl_dstdir = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'templates', \\\n 'catalog',)\n tmpl_main_path = os.path.join(tmpl_srcdir, 'tmpl_main.html')\n # ensuring tmpl_dstdir exists:\n if not Path(tmpl_dstdir).is_dir():\n os.makedirs(tmpl_dstdir)\n # reading tmpl_main.html data content:\n fd = open(tmpl_main_path, 'rb') # 'rb' to avoid encoding problems.\n tmpl_main_data = fd.read()\n fd.close()\n for i in files:\n tmp = ''\n tmp = i.split('.')\n context = tmp[0]\n # the template files with custom content are :\n content_file = context + '_custom_content.html'\n content_file = os.path.join(tmpl_srcdir, content_file)\n fd = open(content_file, 'rb') # 'rb' to avoid encoding problems.\n custom_data = fd.read()\n fd.close()\n # all these templates are wrapped to tmpl_main.html (tmpl_main_data)\n tmpl_final_file = os.path.join(tmpl_dstdir, i)\n fd = open(tmpl_final_file, 'wb') # 'wb' to avoid encoding problems.\n data = tmpl_main_data.replace(b'__INSERT_CUSTOM_CONTENT__', \\\n bytes(custom_data))\n fd.write(data)\n fd.close()\n\n '''\n Put risk/cvss calculators into Add form templates.\n It will look for the __RISK_CALCULATOR__ and \n __CVSS_CALCULATOR__ tags.\n '''\n calculators = {\n 'cvss': 'cvss_custom_content.html',\n 'risk': 'risk_custom_content.html'\n }\n modals = {\n '1': 'tmpl_calculators_modal.html'\n }\n templates_with_calculator = [\n 'add.html',\n 'update.html',\n 'fastupdate.html']\n for i in templates_with_calculator:\n #### Insert [risk,cvss]_custom_content.html\n risk_calc_path = os.path.join(tmpl_srcdir, calculators['risk'])\n cvss_calc_path = os.path.join(tmpl_srcdir, calculators['cvss'])\n modal_path = os.path.join(tmpl_srcdir, modals['1'])\n target_template = os.path.join(tmpl_dstdir, i)\n\n fd = open(risk_calc_path, 'rb')\n risk_calc_data = fd.read()\n fd.close()\n fd = open(cvss_calc_path, 'rb')\n cvss_calc_data = fd.read()\n fd.close()\n fd = open(modal_path, 'rb')\n modal_data = fd.read()\n fd.close()\n fd = open(target_template, 'rb')\n target_data = fd.read()\n fd.close()\n\n if (b'__CALCULATORS_MODAL__' in target_data):\n target_data = target_data.replace(b'__CALCULATORS_MODAL__',bytes(modal_data))\n if (b'__RISK_CALCULATOR__' in target_data):\n target_data = target_data.replace(b'__RISK_CALCULATOR__',bytes(risk_calc_data))\n if (b'__CVSS_CALCULATOR__' in target_data):\n target_data = target_data.replace(b'__CVSS_CALCULATOR__',bytes(cvss_calc_data))\n \n fd = open(target_template, 'wb') # 'wb' to avoid encoding problems.\n fd.write(target_data)\n fd.close() \n sys.stdout.write('Done\\n')\n\ndef set_login_template():\n sys.stdout.write('Setting login template...\\n')\n os.chdir(HOME_DIR)\n tmpl_srcdir = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'templates', \\\n 'catalog', \\\n 'login.html')\n tmpl_dstdir = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'templates', \\\n 'catalog',)\n if not Path(tmpl_dstdir).is_dir():\n os.makedirs(tmpl_dstdir)\n shutil.copy(tmpl_srcdir, tmpl_dstdir)\n sys.stdout.write('Done\\n')\n\ndef set_admin_template():\n # we just need to put static files in the right place.\n sys.stdout.write('Setting admin template confs:\\n')\n os.chdir(HOME_DIR) \n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py collectstatic --noinput')\n os.chdir(HOME_DIR) \n sys.stdout.write('Done\\n')\n\ndef set_forms():\n sys.stdout.write('Setting Forms...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir,'metadata', \\\n 'forms', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', )\n for i in os.listdir(src_path):\n fsrc = os.path.join(src_path,i)\n shutil.copy(fsrc, dst_path)\n os.chdir(HOME_DIR)\n sys.stdout.write('Done\\n')\n\ndef set_static_files():\n sys.stdout.write('Setting Static Files...\\n')\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'metadata', \\\n 'static', \\\n 'catalog', )\n dst_path = os.path.join(os.path.curdir, \\\n 'base', \\\n 'catalog', \\\n 'static', )\n if Path(dst_path).is_dir():\n shutil.rmtree(dst_path)\n shutil.copytree(src_path, dst_path)\n os.chdir(HOME_DIR) \n sys.stdout.write('Done\\n')\n\ndef deployment_checklist():\n sys.stdout.write('Deployment checklist...\\n')\n # https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n key = secrets.token_hex(64)\n src_path = os.path.join(HOME_DIR, \\\n 'metadata', \\\n 'settings', \\\n 'settings.py')\n dst_path = os.path.join(HOME_DIR, 'base', \\\n 'base', \\\n 'settings.py')\n # Open template file and copy its content to avoid data appending:\n fd = open(src_path, 'r')\n data = fd.read()\n fd.close()\n # https://goo.gl/PtCXNN\n fd = open(dst_path, 'w')\n data = data.replace('__SECRET_KEY__', key)\n fd.write(data)\n fd.close()\n sys.stdout.write('Done\\n')\n\ndef load_test_data():\n sys.stdout.write('Loading data from test/data-md.json\\n')\n env = get_os()\n CURR_DIR = os.path.curdir\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'test', \\\n 'data', \\\n 'data-md.json')\n fixturename_path = os.path.join(HOME_DIR, \\\n 'base', \\\n 'catalog', \\\n 'fixturename',) \n if not Path(fixturename_path).is_dir():\n os.mkdir(fixturename_path)\n shutil.copy(src_path, fixturename_path)\n os.chdir(PROJECT_NAME)\n fixturename_file = os.path.join(os.path.pardir, \\\n fixturename_path, \\\n 'data-md.json')\n os.system(PYTHON_EXE + ' ' + 'manage.py loaddata' + ' ' + fixturename_file)\n os.chdir(CURR_DIR) \n sys.stdout.write('Done\\n')\n\ndef load_default_risk_questions():\n sys.stdout.write('Loading default Risk Questions...\\n')\n CURR_DIR = os.path.curdir\n env = get_os()\n os.chdir(HOME_DIR)\n src_path = os.path.join(os.path.curdir, \\\n 'test', \\\n 'data', \\\n 'riskQuestions-example.json')\n fixturename_path = os.path.join(HOME_DIR, \\\n 'base', \\\n 'catalog', \\\n 'fixturename',) \n if not Path(fixturename_path).is_dir():\n os.mkdir(fixturename_path)\n shutil.copy(src_path, fixturename_path)\n os.chdir(PROJECT_NAME)\n fixturename_file = os.path.join(os.path.pardir, \\\n fixturename_path, \\\n 'riskQuestions-example.json')\n os.system(PYTHON_EXE + ' ' + 'manage.py loaddata' + ' ' + fixturename_file)\n os.chdir(CURR_DIR) \n sys.stdout.write('Done\\n')\n\ndef create_superuser():\n env = get_os()\n os.chdir(BASE_DIR)\n os.system(PYTHON_EXE + ' ' + 'manage.py createsuperuser')\n os.chdir(HOME_DIR)\n\ndef set_database():\n # https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n env = get_os()\n default_database = {\n 'default': {\n 'ENGINE': '',\n 'NAME': '',\n 'USER': '',\n 'PASSWORD':'',\n 'HOST': '',\n 'PORT':''\n }\n }\n available_databases = {\n # 'key': ['DB friendly name', 'ENGINE', 'NAME', 'USER', 'PASS', HOST', 'PORT', 'db binding']\n '1': ['PostgreSQL', 'django.db.backends.postgresql', '', '', '', '127.0.0.1', '5432', 'psycopg2'],\n '2': ['MySQL', 'django.db.backends.mysql', '', '', '', '127.0.0.1', '3306', 'mysql-connector-python'],\n '3': ['Oracle', 'django.db.backends.oracle', '', '', '', '127.0.0.1', '1521', 'cx_Oracle'],\n '4': ['SQLite3', 'django.db.backends.sqlite3', \"os.path.join(BASE_DIR, 'db.sqlite3')\", '', '', '', '', None]\n }\n sys.stdout.write('\\nAvailable databases:\\n')\n for i in available_databases.keys():\n sys.stdout.write(i + ' - ' + available_databases[i][0] + '\\n') \n chosen_db = input('\\nWhich one would you like to use? ')\n while chosen_db not in available_databases.keys():\n chosen_db = input('Choose one of the numbers above: ')\n sys.stdout.write('\\nLet us set' + available_databases[chosen_db][0] + 'database:')\n default_database['default']['ENGINE'] = available_databases[chosen_db][1]\n default_database['default']['NAME'] = input('Database name: ' \\\n + available_databases[chosen_db][2]) \\\n or available_databases[chosen_db][2]\n default_database['default']['USER'] = input('Database user name: ' \\\n + available_databases[chosen_db][3]) \\\n or available_databases[chosen_db][3]\n default_database['default']['PASSWORD'] = getpass.getpass('User password:')\n pwd_verify = getpass.getpass('User password (again):')\n while default_database['default']['PASSWORD'] != pwd_verify:\n sys.stdout.write('Password mismatch.')\n default_database['default']['PASSWORD'] = getpass.getpass('User password:')\n pwd_verify = getpass.getpass('User password (again):')\n default_database['default']['HOST'] = input('Database Host address (' \\\n + available_databases[chosen_db][5] \\\n + '):') \\\n or available_databases[chosen_db][5]\n default_database['default']['PORT'] = input('Database Port (' \\\n + available_databases[chosen_db][6] \\\n + '):') \\\n or available_databases[chosen_db][6]\n #### Altering settings.py DATABASE entry:\n settings_path = os.path.join(os.curdir, 'base', 'base', 'settings.py')\n f = open(settings_path, 'r')\n data = f.read()\n f.close()\n regex = r\"DATABASES = (.*)}\\n\" # Thanks to https://regex101.com/r/lH0jK9/1\n subst = json.dumps(default_database, indent=4)\n subst = subst.replace('\"', '\\'')\n subst = 'DATABASES = ' + subst + '\\n'\n result = re.sub(regex, subst, data, 0, re.DOTALL)\n ### Since 'NAME': value is a path, it could not be treated as a string.\n if available_databases[chosen_db][0] == 'SQLite3':\n result = result.replace(\"'NAME': 'os.path.join(BASE_DIR, 'db.sqlite3')',\", \\\n \"'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\")\n f = open(settings_path, 'w')\n f.write(result)\n f.close()\n #### Check if Database bindings is installed:\n db_binding = available_databases[chosen_db][7]\n try:\n import db_binding\n except ImportError: \n os.system(PIP_EXE + ' ' + 'install ' + db_binding)\n set_datamodel()\n \ndef create_startscripts():\n env = get_os()\n system = env['system']\n if system.startswith('linux') or system.startswith('darwin'):\n filename = 'run.sh'\n f = open(filename, 'w')\n data = '#!/bin/bash\\n\\n' \\\n + 'ADDRESS=\"\"\\n' \\\n + 'if [[ $1 ]]; then\\n' \\\n + ' ADDRESS=$1\\n' \\\n + 'fi\\n' \\\n + 'if [[ -d ./venv ]]; then\\n' \\\n + ' source venv/bin/activate\\n\\n' \\\n + 'fi\\n' \\\n + 'cd base\\n' \\\n + PYTHON_EXE + ' manage.py runserver $ADDRESS &\\n' \\\n + 'cd ..\\n'\n f.write(data)\n f.close()\n os.chmod(filename, 0o755)\n\n if system.startswith('win32'):\n filename = 'run.bat'\n f = open(filename, 'w')\n data = '@echo off\\n\\n' \\\n + 'set ADDRESS=\"\"\\n' \\\n + 'if not [%~1] == [] (set ADDRESS=%1)\\n' \\\n + 'if exist venv (\\n' \\\n + ' call venv\\\\Scripts\\\\activate.bat\\n' \\\n + ')\\n' \\\n + 'cd base\\n' \\\n + PYTHON_EXE + ' manage.py runserver %ADDRESS%\\n' \\\n + 'cd ..\\n'\n f.write(data)\n f.close()\n\ndef update_js():\n '''\n Needs to take care about the licences as well. See ./LICENSES for more info.\n '''\n pass\n\n\ndef run():\n check_pip()\n check_venv()\n param = check_parameters()\n\n if param == 'build':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_superuser()\n create_startscripts()\n\n if param == 'build-only':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_startscripts()\n\n if param == 'build-novenv':\n check_parameters()\n get_os()\n check_system_reqs()\n deep_clean('none')\n start_django_project()\n importing_settings()\n set_datamodel()\n set_urls()\n set_views()\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n load_default_risk_questions()\n deployment_checklist()\n create_superuser()\n create_startscripts()\n \n if param == 'clean':\n deep_clean('none')\n \n if param == 'createsuperuser':\n create_superuser()\n\n if param == 'database':\n set_database()\n\n if param == 'deep-clean':\n deep_clean('deep-clean')\n\n if param == 'templates':\n set_templates()\n set_login_template()\n set_forms()\n set_static_files()\n set_admin_template()\n\n if param == 'urlsviews':\n set_urls()\n set_views()\n \n if param == 'loadtestdata':\n load_test_data()\n\n if param == 'createstartscript':\n create_startscripts()\n\n if param == 'update-js':\n update_js()\n\n\nrun()\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":26634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13856136","text":"# -*- encoding: utf8 -*-\n'''\nCashier 클래스에는 기존에 burger_price라는 클래스 변수와 take_order라는 메서드가 있었습니다.(추가하세요)\n\n'''\nclass Employee: \n \"\"\" 직원 클래스 \"\"\"\n\n company_name = \"코드잇 버거\" # 가게이름\n raise_percentage = 1.03 # 시급 인상률\n\n def __init__(self,name,wage):\n \"\"\"인스턴스 변수 설정\"\"\"\n self.name = name # 이름\n self.wage = wage # 시급\n \n def raise_pay(self):\n \"\"\"시급을 인상하는 메소드\"\"\"\n self.wage *= self.raise_percentage\n\n def __str__(self):\n \"\"\" 직원 정보를 문자열로 리턴하는 메소드 \"\"\"\n return Employee.company_name + ' 직원: ' + self.name\n\n\nclass Cashier(Employee):\n raise_percentage = 1.05\n burger_price = 4000\n\n def __init__(self, name, wage,number_sold):\n # self.name = name # 부모 클래스의 내용과 동일 [방법1 ]\n # self.wage = wage # 부모 클래스의 내용과 동일\n\n # Employee.__init__(self,name,wage) [방법2] \n super().__init__(name,wage) #[방법3] super() 쓸떼는 SELF 파라미터 빼야함.\n self.number_sold = number_sold # 자식 클래스에서 인스턴스 변수부분을 새롭게 추가한 부분임.\n \n def take_order(self, money_received):\n \"\"\"주문과 돈을 받고 거스름돈을 리턴함.\"\"\"\n if Cashier.burger_price > money_received:\n print('돈이 충분하지 않아요. 돈을 다시 계산해 주세요.')\n return money_received\n else: \n self.number_sold += 1\n change = money_received - Cashier.burger_price\n return change\n\n def __str__(self):\n return Cashier.company_name + \" 계산대 직원: \"+self.name\n\nclass DeliveryMan(Employee):\n pass\n\nyoung = Cashier('강영훈', 8900,0)\n\nyoung.raise_pay()\nprint(young.wage)\n\nprint(young.take_order(7000))\nprint(young.take_order(3000))\n\nprint(young.burger_price)\nprint(Cashier.burger_price)\n\nprint(young.number_sold)\nprint(young)","sub_path":"파이썬/객체지향프로그래밍/객체지향프로그래밍이란/OOP_4개의기둥/상속/08_상속4_기능추가.py","file_name":"08_상속4_기능추가.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"644318857","text":"class QryKegiatanSekolah:\n\n def __init__(self,parentForm,FormObj):\n self.form = parentForm\n self.app = parentForm.ClientApplication\n self.FormView = None\n\n def Show(self):\n self.ShowFixedAssetData()\n self.FormContainer.Show()\n\n def ShowFixedAssetData(self):\n Beasiswa = self.Beasiswa\n uipart = self.uipart\n\n Beasiswa.OQLText = \" Select from SchoolYear as Beasiswa \\\n \\\n ( SchoolYear, \\\n SchoolYearCode, \\\n self \\\n );\"\n Beasiswa.DisplayData()\n\n def Hapus(self,key):\n if (self.app.ConfirmDialog('Yakin Tahun Ajaran Ini Akan Dihapus ?')):\n params = self.app.CreateValues(['key',key])\n retval = self.form.CallServerMethod('Proses',params)\n status = retval.FirstRecord\n if status.IsErr ==1:\n self.app.ShowMessage(status.ErrMessage)\n return 0\n else :\n self.app.ShowMessage('Tahun Ajaran Telah Dihapus')\n\n\n","sub_path":"dialogs/master/QryTahunAjaran_intr.py","file_name":"QryTahunAjaran_intr.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"417870131","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\ndef build_linked_list(array: list):\n if len(array) == 0:\n return None\n head = curr = ListNode(array[0])\n for i in range(1, len(array)):\n curr.next = ListNode(array[i])\n curr = curr.next\n return head\n\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n\n def reverse(_head: ListNode):\n curr, prev = _head, None\n while curr:\n _next = curr.next\n curr.next = prev\n curr, prev = _next, curr\n return prev\n\n slow, fast = head, head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if fast:\n slow = slow.next\n\n p, q = head, reverse(slow)\n while q:\n if p.val != q.val:\n return False\n p, q = p.next, q.next\n\n return True\n\n\ndef test_solution():\n head = build_linked_list([1, 2])\n assert not Solution().isPalindrome(head)\n\n head = build_linked_list([1, 2, 2, 1])\n assert Solution().isPalindrome(head)\n\n\nif __name__ == '__main__':\n test_solution()\n","sub_path":"link_list/classic/234_palindrome_linked_list.py","file_name":"234_palindrome_linked_list.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"285995562","text":"import numpy as np\nfrom music21 import stream\n\nfrom libs.harmony import chordDissScore, ChordIntvDiss\nfrom libs.m21 import get_min_ql\n\n\ndef cfDissScore(cf1: stream.Part, cf2: stream.Part):\n assert cf1.quarterLength == cf2.quarterLength\n min_ql = min(get_min_ql(cf1), get_min_ql(cf2))\n diss = 0\n for offset in np.arange(0, cf1.highestTime, min_ql):\n ch1 = cf1.getElementsByOffset(offset,\n mustFinishInSpan=False,\n mustBeginInSpan=False)[0]\n ch2 = cf2.getElementsByOffset(offset,\n mustFinishInSpan=False,\n mustBeginInSpan=False)[0]\n diss += chordDissScore(ch1, ch2)\n #ch2.addLyric(f'{round(chordDissScore(ch1, ch2), 2)}')\n return diss\n\ndef melDissScore(mel1: stream.Part, mel2: stream.Part):\n diss = 0\n mel1.flat.attachIntervalsBetweenStreams(mel2.flat)\n for nt in mel1.flat.notes:\n itv = nt.editorial.harmonicInterval\n if itv is not None and itv.noteStart.offet == itv.noteEnd.offset:\n diss += ChordIntvDiss[itv.semitones % 12] * min(itv.noteStart.duration.quarterLength,\n itv.noteEnd.duration.quarterLength)\n return diss\n\n","sub_path":"filters/rating.py","file_name":"rating.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228686593","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom .forms import CustomUserCreationForm,CustomUserChangeForm\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm\nfrom django.contrib.auth import get_user_model\nfrom .models import User\nfrom movies.models import Review, Movie, Genre\nfrom django.contrib.auth.decorators import login_required\n\n\n\n\ndef indexs(request):\n Users = User.objects.all()\n context = {\n 'Users':Users\n }\n return render(request,'accounts/indexs.html',context)\n\n# Create your views here.\ndef signup(request):\n if request.user.is_authenticated:\n return redirect('movies:index')\n if request.method == 'POST':\n form = CustomUserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('movies:index')\n else:\n form = CustomUserCreationForm()\n context = {\n 'form':form\n }\n return render(request,'accounts/signup.html',context)\n \ndef login(request):\n if request.user.is_authenticated:\n return redirect('movies:index')\n if request.method == 'POST':\n form = AuthenticationForm(request,request.POST)\n if form.is_valid():\n user = form.get_user()\n auth_login(request,user)\n return redirect('movies:index')\n else:\n form = AuthenticationForm()\n context = {\n 'form':form\n }\n return render(request,'accounts/login.html',context)\n\ndef logout(request):\n auth_logout(request)\n return redirect('movies:index')\n\ndef profile(request, account_pk):\n User = get_user_model()\n user = get_object_or_404(User,pk=account_pk)\n context = {\n 'user_profile':user\n }\n genres_score = [0] * 21\n counts = [0] * 21\n reviews = user.review_set.order_by('-score')\n for review in reviews:\n genres_score[review.movie_id.genre_id.id] += review.score\n counts[review.movie_id.genre_id.id] += 1\n ## 장르별 평균점수 계산\n avg_genre = [0] * 21\n for i in range(len(avg_genre)):\n if counts[i] == 0:\n continue\n avg_genre[i] = int(genres_score[i]/counts[i])\n genre = avg_genre.index(max(avg_genre)) # 장르별 점수 최고점\n movies = Movie.objects.filter(genre_id_id=genre).order_by('-audience')\n user_watch_movie = set()\n for r in user.review_set.all():\n user_watch_movie.add(r.movie_id)\n my_movies = []\n if not user_watch_movie:\n genres = Genre.objects.all()\n my_movies = genres[0].movie_set.all()\n else:\n for movie in movies:\n if movie in user_watch_movie:\n continue\n my_movies.append(movie)\n if len(my_movies) == 10:\n break\n context.update({'my_movies': my_movies})\n return render(request,'accounts/profile.html',context)\n\ndef follow(request, account_pk):\n User = get_user_model()\n obama = get_object_or_404(User,pk=account_pk)\n if obama != request.user:\n if request.user in obama.followers.all():\n obama.followers.remove(request.user)\n else:\n obama.followers.add(request.user)\n return redirect('accounts:profile',account_pk)\n\n@login_required\ndef update(request):\n if request.method == 'POST':\n form = CustomUserChangeForm(request.POST, instance=request.user)\n if form.is_valid():\n form.save()\n return redirect('movies:index')\n else:\n form = CustomUserChangeForm(instance=request.user)\n context = {\n 'form': form\n }\n return render(request, 'accounts/login.html', context)\n\n\n@login_required\ndef password_change(request):\n if request.method == 'POST':\n form = PasswordChangeForm(request.user, request.POST)\n if form.is_valid():\n form.save()\n update_session_auth_hash(request, form.user)\n return redirect('movies:index')\n else:\n form = PasswordChangeForm(request.user) # 반드시 첫번째 인자로 user\n context = {\n 'form': form\n }\n return render(request, 'accounts/login.html', context)","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14474426","text":"# Игра \"Крестики-Нолики\"\n\nfrom IPython.display import clear_output\nimport random\n\ndef display_board(board):\n clear_output()\n print(board[7]+'|'+board[8]+'|'+board[9])\n print(board[4]+'|'+board[5]+'|'+board[6])\n print(board[1]+'|'+board[2]+'|'+board[3])\n \ndef player_input():\n '''\n OUTPUT = (Player1 marker, Player2 marker)\n '''\n marker=''\n while not (marker =='X' or marker =='О'):\n marker = input('Игрок1 - выберите X или О:').upper()\n if marker == 'X':\n return ('X', 'O')\n else:\n return ('O', 'X')\n \ndef place_marker(board, marker, position):\n board[position] = marker\n\ndef win_check(board, mark):\n (board[1]==board[2]==board[3]==mark) or (board[4]==board[5]==board[6]==mark) or (board[7]==board[8]==board[9]==mark) or (board[1]==board[4]==board[7]==mark) or (board[2]==board[5]==board[8]==mark) or (board[3]==board[6]==board[9]==mark) or (board[1]==board[5]==board[9]==mark) or (board[3]==board[5]==board[7]==mark)\ndef choose_first():\n flip = random.randint(0, 1)\n if flip==0:\n return 'Игрок1'\n else:\n return 'Игрок2'\ndef space_check(board, position):\n return board[position] ==' '\ndef full_board_check(board):\n for i in range(1, 10):\n if space_check(board, i):\n return False\n return True\ndef player_choice(board):\n position = 0\n \n while position not in [1, 2, 3, 4, 5, 6, 7, 8, 9] or not space_check(board, position):\n position = int(input('Укажите поле: (1-9)'))\n return position\ndef replay():\n choice = input('Хотите играть снова? Введите Yes или No')\n return choice == 'Yes'\n\nprint('Добро пожаловать в игру Крестики-Нолики')\n\nwhile True:\n the_board=[' ']*10\n player1_marker, player2_marker = player_input()\n turn = choose_first()\n print(turn +' ходит первый')\n play_game = input('Вы готовы играть? Yer or No')\n \n if play_game == 'Yes':\n game_on=True\n else:\n game_on=False\n while game_on:\n if turn == 'Игрок1':\n display_board(the_board)\n position = player_choice(the_board)\n place_marker(the_board, player1_marker, position)\n if win_check(the_board, player1_marker):\n display_board(the_board)\n print('Игрок1 выиграл')\n game_on=False\n else:\n if full_board_check(the_board):\n display_board(the_board)\n print('Ничья')\n game_on=False\n else:\n turn == 'Игрок2'\n \n \n else:\n display_board(the_board)\n position = player_choice(the_board)\n place_marker(the_board, player2_marker, position)\n if win_check(the_board, player2_marker):\n display_board(the_board)\n print('Игрок2 выиграл')\n game_on=False\n else:\n if full_board_check(the_board):\n display_board(the_board)\n print('Ничья')\n game_on=False\n else:\n turn == 'Игрок1'\n \n \n if not replay():\n break","sub_path":"First_Project.py","file_name":"First_Project.py","file_ext":"py","file_size_in_byte":3391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"494896187","text":"from twisted.words.protocols import irc\nfrom txircd.modbase import Command\nfrom txircd.utils import irc_lower\nfrom fnmatch import fnmatch\n\nclass ListCommand(Command):\n def onUse(self, user, data):\n for cichanname, channel in self.ircd.channels.iteritems():\n if data[\"chanfilter\"] is not None:\n filterMatch = False\n for filterEntry in data[\"chanfilter\"]:\n if fnmatch(cichanname, filterEntry):\n filterMatch = True\n break\n if not filterMatch:\n continue\n cdata = {\n \"channel\": channel,\n \"name\": channel.name,\n \"users\": len(channel.users),\n \"topic\": channel.topic if channel.topic else \"\"\n }\n extraData = { \"user\": user, \"cdata\": cdata }\n user.commandExtraHook(\"LIST\", extraData)\n if \"cdata\" not in extraData or not extraData[\"cdata\"]:\n continue\n else:\n user.sendMessage(irc.RPL_LIST, cdata[\"name\"], str(cdata[\"users\"]), \":[{}] {}\".format(cdata[\"channel\"].modeString(user), cdata[\"topic\"]))\n user.sendMessage(irc.RPL_LISTEND, \":End of channel list\")\n \n def processParams(self, user, params):\n if user.registered > 0:\n user.sendMessage(irc.ERR_NOTYETREGISTERED, \"LIST\", \":You have not registered\")\n return {}\n if params:\n chanFilter = irc_lower(params[0]).split(\",\")\n else:\n chanFilter = None\n return {\n \"user\": user,\n \"chanfilter\": chanFilter\n }\n\nclass Spawner(object):\n def __init__(self, ircd):\n self.ircd = ircd\n \n def spawn(self):\n return {\n \"commands\": {\n \"LIST\": ListCommand()\n }\n }\n \n def cleanup(self):\n del self.ircd.commands[\"LIST\"]","sub_path":"txircd/modules/cmd_list.py","file_name":"cmd_list.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"190413080","text":"name = input('이름 입력 : ')\nscore = int(input('점수 입력 : '))\ngrade = '' # 학점 평가\n\nif score >= 90 :\n grade = 'A'\nelif score >= 80 :\n grade = 'B'\nelif score >= 70 :\n grade = 'C'\nelif score >= 60 :\n grade = 'D'\nelse:\n grade = 'F'\n\nprint(f'이름 : {name}\\n'\n f'점수 : {score}\\n'\n f'학점 : {grade}')","sub_path":"command/ifTest2.py","file_name":"ifTest2.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"197232040","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport os\nfrom torch.utils import data\nfrom os import makedirs\nimport torchvision\nfrom PIL import Image\nimport sys\nimport copy\nimport matplotlib.pyplot as plt\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(1, 32, 3, 1)\n self.conv2 = nn.Conv2d(32, 64, 3, 1)\n self.dropout1 = nn.Dropout2d(0.25)\n self.dropout2 = nn.Dropout2d(0.5)\n self.fc1 = nn.Linear(9216, 128)\n self.fc2 = nn.Linear(128, 10)\n # self.sm1 = nn.Softmax()\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n x = self.conv2(x)\n x = F.max_pool2d(x, 2)\n x = self.dropout1(x)\n x = torch.flatten(x, 1)\n x = self.fc1(x)\n x = F.relu(x)\n x = self.dropout2(x)\n x = self.fc2(x)\n # x = self.sm1(x)\n return x\n\ndef numpy_loader(input):\n item = np.load(input)/255.0\n return Image.fromarray(item)\n\ndef evaluate_model_for_accuracy(model, device, data_loader):\n model.eval()\n\n correct = 0\n with torch.no_grad():\n # outF = open(\"myOutFile.txt\", \"w\")\n for data, target in data_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n # print(output)\n pred = output.argmax(dim=1, keepdim=True)\n # torch.save(output, \"tensor-pytorch.txt\")\n # outF.write(str(output))\n # outF.write(str(pred))\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n print('\\n Accuracy: {}/{} ({:.0f}%)\\n'.format(\n correct, len(data_loader.dataset),\n 100. * correct / len(data_loader.dataset)))\n\n\ndef evaluate_adv_images(model, device, kwargs, mean, std, data_loader):\n batch_size = 100\n model.eval()\n\n adv_data_loader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder('adv_images', #Change this to your adv_images folder\n loader=numpy_loader,\n extensions='.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=batch_size, **kwargs)\n\n given_dataset = []\n adv_images = []\n labels = []\n with torch.no_grad():\n for data, target in data_loader:\n data, target = data.to(device), target.to(device)\n if len(given_dataset) ==0:\n given_dataset = data.squeeze().detach().cpu().numpy()\n else:\n given_dataset = np.concatenate([given_dataset, data.squeeze().detach().cpu().numpy()],\n axis=0)\n\n for data, target in adv_data_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n label = target.squeeze().detach().cpu().numpy()\n softmax_values = torch.nn.Softmax()(output).cpu().numpy()[np.arange(batch_size), label]\n adv_images = data\n labels = target\n\n\n #Checking the range of generated images\n adv_images_copy = copy.deepcopy(adv_images)\n for k in range(adv_images_copy.shape[0]):\n image_ = adv_images_copy[k, :, :]\n\n for t, m, s in zip(image_, mean, std):\n t.mul_(s).add_(m)\n\n image = image_.squeeze().detach().cpu().numpy()\n image = 255.0 * image\n print(image)\n if np.min(image) < 0 or np.max(image) > 255:\n print('Generated adversarial image is out of range.')\n sys.exit()\n\n adv_images = adv_images.squeeze().detach().cpu().numpy()\n labels = labels.squeeze().detach().cpu().numpy()\n\n\n #Checking for equation 2 and equation 3\n if all([x > 0.8 for x in softmax_values.tolist()]):\n print('Softmax values for all of your adv images are greater than 0.8')\n S = 0\n for i in range(10):\n label_indices = np.where(labels==i)[0]\n a_i = adv_images[label_indices, :, :]\n for k in range(10):\n image = a_i[k, :, :]\n S = S + np.min(\n np.sqrt(\n np.sum(\n np.square(\n np.subtract(given_dataset, np.tile(np.expand_dims(image, axis=0), [1000,1,1]))\n ),axis=(1,2))))\n\n print('Value of S : {:.4f}'.format(S / 100))\n\n else:\n print('Softmax values for some of your adv images are less than 0.8')\n\n\nimport os, shutil\n\n\ndef remove_files_in_dir(folder):\n try:\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n except Exception as e:\n print('Failed to delete. Reason: %s' % (e))\n\ndef generate_adv_images(model, device, kwargs):\n model.eval()\n\n # forSoftMaxList = torch.cuda.FloatTensor()\n sfMax = []\n\n targeted_class_labelsList = []\n image_namesList = []\n maxImages = 10\n advImageID = 1\n targetList=[]\n targetDict={}\n mean = (0.1307,)\n std = (0.3081,)\n\n with torch.enable_grad():\n\n path = 'D:/MComp/CS5260 Deep Learning and NN-2/Assignment_1/Assignment_1/data/'\n dataLoader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder(path,\n loader=numpy_loader,\n extensions='.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=100, **kwargs) #hardcoding batch size to load the class one by one\n\n given_dataset = []\n for data1, target1 in dataLoader:\n data1, target1 = data1.to(device), target1.to(device)\n if len(given_dataset) ==0:\n given_dataset = data1.squeeze().detach().cpu().numpy()\n else:\n given_dataset = np.concatenate([given_dataset, data1.squeeze().detach().cpu().numpy()],\n axis=0)\n\n epsilon =0.6\n iterNum =[60, 100, 50, 84, 50, 70, 70, 82, 50, 60]\n epsilonarr = [0.81, 0.65, 0.8, 0.6, 0.8, 0.81, 0.8, 0.81, 1.0, 0.81]\n\n for i in range(1):\n\n adv_images = []\n targeted_class_labels = []\n image_names = []\n print(\"Epsilon Value: \" + str(epsilonarr))\n print(\"Iteration number : \" + str(iterNum))\n # epsilonarr = np.ones(10)\n # epsilonarr = epsilonarr * epsilon\n\n targetID = 0\n totalSoftmaxList = []\n maxIndex=[]\n Sval=0\n for labelCount in range(10):\n # epsilonarr[1]=0.65\n # if labelCount == 1:\n # iterNum=40\n adv_imagesList = torch.cuda.FloatTensor()\n softMaxList = []\n\n\n for data_f, target_f in dataLoader:\n data, target = data_f.to(device), target_f.to(device)\n targetCopy = torch.LongTensor(100,).zero_().to(device)\n originalLabel = target[0].item()\n if (originalLabel == labelCount) | (epsilonarr[labelCount] == 0):\n # targetID+=1\n continue\n data.requires_grad = True\n\n targetCopy += targetID\n\n for name, param in model.named_parameters():\n # print(name, param.requires_grad)\n param.requires_grad = False\n maxim = (1.0 - mean[0])/std[0]\n minim = (0.0 - mean[0])/std[0]\n\n def clip(data_tensor, minimum, maximum):\n return torch.autograd.Variable(torch.clamp(data_tensor, min=minimum, max=maximum), requires_grad=True)\n # return torch.clamp(data_tensor, min=minimum, max=maximum)\n\n def norm_custom(data):\n data_unnorm = data * std[0] + mean[0]\n maxim = data_unnorm.max(axis=1)[0].max()\n minim = data_unnorm.min(axis=1)[0].min()\n return torch.autograd.Variable((data_unnorm - minim) / (maxim - minim), requires_grad=True)\n\n # data_norm = clip(data, minim, maxim)\n data_norm = torch.autograd.Variable(data.clone(), requires_grad=True)\n iter = 0\n\n while iter <= iterNum[labelCount]:\n # print(iter+1, '->', data_norm.requires_grad)\n model.zero_grad()\n data_norm.grad = None\n output = model.forward(data_norm)\n outSoftMax = F.softmax(output, dim=1)\n loss = F.cross_entropy(outSoftMax, targetCopy)\n loss.backward()\n gradient = data_norm.grad.data.sign()\n data_norm.data = data_norm.data - epsilonarr[labelCount] * gradient\n data_norm = clip(data_norm, minim, maxim)\n\n ##Cancel comment out for stopping iter if already 10 values above 0.8\n\n # out_max1 = outSoftMax.max(axis=1)\n # indices1 = out_max1[0].detach().cpu().numpy().argsort()\n # out_arg_max1 = out_max1[1].cpu().numpy()\n # idx1 = 99\n # image_iter1 = 0\n # counter = 0\n # while image_iter1 < 5 and idx1 >= 0:\n # if (out_arg_max1[indices1[idx1].item()].item() == targetCopy[0].item()) & (out_max1[0][indices1[idx1].item()].item() >= 0.8) :\n # image_iter1 +=1\n # idx1-=1\n # if (image_iter1 == 3):\n # print(\"Iteration stopped for \" + str(originalLabel) + \" at iter \" + str(iter))\n # break\n\n iter += 1\n\n # data_norm = data.detach().clone().type(torch.cuda.IntTensor).type(torch.cuda.FloatTensor)\n # data_norm = norm_custom(data)\n with torch.no_grad():\n output = model(data_norm)\n outSoftMax = F.softmax(output, dim=1)\n out_max = outSoftMax.max(axis=1)\n # print(indices)\n out_arg_max = out_max[1].cpu().numpy()\n indices = out_max[0].detach().cpu().numpy().argsort()\n\n #For finding S\n Sarray = []\n adv_images1 = data_norm.squeeze().detach().cpu().numpy()\n # labels1 = out_arg_max\n # label_indices = np.where(labels1 == labelCount)[0]\n # a_i = adv_images1[label_indices,:,:]\n a_i = adv_images1\n for k in range(len(a_i)):\n image= a_i[k,:,:]\n Sarray.append(np.min(np.sqrt(np.sum(np.square(np.subtract(given_dataset, np.tile(np.expand_dims(image, axis=0), [1000,1,1]))),axis=(1,2)))))\n\n sSortIndex = np.asarray(Sarray).argsort()\n\n sValitem=0\n image_iter = 0\n idx = 99\n while image_iter < 10 and idx >= 0:\n\n if out_arg_max[sSortIndex[idx].item()].item() == labelCount: #Assuming the perturbed image wrongly classifies with high prob\n adv_imagesList = torch.cat([adv_imagesList, data_norm[sSortIndex[idx].item()]], dim=0)\n softMaxList.append(out_max[0][sSortIndex[idx].item()].item())\n # sValitem = sValitem+ Sarray[sSortIndex[idx].item()]\n\n\n # targeted_class_labelsList.append(originalLabel)\n # image_namesList.append(f'sasi_{image_iter}_{out_arg_max[indices[idx].item()].item()}_{output[indices[idx].item()][out_arg_max[indices[idx].item()].item()].item()}')\n image_iter +=1\n idx -= 1\n # print(\"Sval of \" + str(labelCount) + \" : \" + str(sValitem/len(Sarray)))\n\n # # For epsilon adjustment\n # softmaxIndex = sorted(range(len(softMaxList)), key=softMaxList.__getitem__)\n #\n # if(len(softMaxList)>=10):\n # if softMaxList[softmaxIndex[len(softMaxList)-10]] > 0.8:\n # epsilonarr[labelCount] = 0\n # print(\"Epsilon stopped for \" + str(labelCount))\n\n remove_files_in_dir(os.path.join(os.getcwd(), f'adv_imgs_{labelCount}'))\n # os.mkdir(f'adv_imgs_{labelCount}')\n # for idx, img in enumerate(adv_imagesList):\n # img_t = (img.detach().cpu().numpy() * std[0] + mean[0]) * 255\n # im = Image.fromarray(img_t.reshape(28, 28).astype('uint8'), mode='L')\n # im.save(f'adv_imgs_{labelCount}/i_{idx}_{softMaxList[idx]}.jpg')\n\n # pixels = np.array((img * 255).cpu().detach().numpy(), dtype='int')\n # pixels = pixels.reshape((28, 28))\n # plt.imsave(\n # f'adv_imgs_{labelCount}/sasi_{idx}_{softMaxList[idx]}.jpeg',\n # pixels)\n\n\n\n #Sort the image list adn indices\n adv_imagesList4dim = adv_imagesList[:,None,:, :]\n with torch.no_grad():\n outputAdvList = model(adv_imagesList4dim)\n outSoftMaxAdvList = F.softmax(outputAdvList, dim=1)\n outAdvMax = outSoftMaxAdvList.max(axis=1)\n indicesAdvList = outAdvMax[0].detach().cpu().numpy().argsort()\n outAdvArgMax = outAdvMax[1].cpu().numpy()\n\n for idx, img in enumerate(adv_imagesList):\n img_t = (img.detach().cpu().numpy() * std[0] + mean[0]) * 255\n im = Image.fromarray(img_t.reshape(28, 28).astype('uint8'), mode='L')\n im.save(f'adv_imgs_{labelCount}/i_{idx}_{outAdvMax[0][idx].item()}_{outAdvArgMax[idx].item()}.jpg')\n\n #For finding final 10 based on S score\n FinalSarray = []\n Finaladv_images1 = adv_imagesList4dim.squeeze().detach().cpu().numpy()\n # labels1 = out_arg_max\n # label_indices = np.where(labels1 == labelCount)[0]\n # a_i = adv_images1[label_indices,:,:]\n Finala_i = Finaladv_images1\n for k in range(len(Finala_i)):\n Finalimage = Finala_i[k, :, :]\n FinalSarray.append(np.min(np.sqrt(\n np.sum(np.square(np.subtract(given_dataset, np.tile(np.expand_dims(Finalimage, axis=0), [1000, 1, 1]))),\n axis=(1, 2)))))\n\n FinalsSortIndex = np.asarray(FinalSarray).argsort()\n\n image_iter_advlist = 0\n idx_advList = len(adv_imagesList4dim)-1\n SvalIndividual= 0\n while image_iter_advlist < 10 and idx_advList >= 0:\n\n if (outAdvArgMax[FinalsSortIndex[idx_advList].item()].item() == labelCount) & (outAdvMax[0][FinalsSortIndex[idx_advList].item()].item() > 0.8):\n adv_images.append(adv_imagesList4dim[FinalsSortIndex[idx_advList]])\n totalSoftmaxList.append(outAdvMax[0][FinalsSortIndex[idx_advList].item()].item())\n maxIndex.append(outAdvMax[1][FinalsSortIndex[idx_advList].item()].item())\n Sval = Sval + FinalSarray[FinalsSortIndex[idx_advList].item()]\n SvalIndividual =SvalIndividual + FinalSarray[FinalsSortIndex[idx_advList].item()]\n # with torch.no_grad():\n # sfMax.append((F.softmax(model(adv_imagesList4dim[indicesAdvList[idx_advList]][:,None,:,:]), dim=1)).max(axis=1)[0].item())\n # forSoftMaxList = torch.cat([forSoftMaxList, adv_imagesList4dim[indicesAdvList[idx_advList].item()]], dim=0)\n targeted_class_labels.append(labelCount)\n image_names.append(\n f'sasi_{image_iter_advlist}_{outAdvArgMax[FinalsSortIndex[idx_advList].item()].item()}_{outSoftMaxAdvList[FinalsSortIndex[idx_advList].item()][outAdvArgMax[FinalsSortIndex[idx].item()].item()].item()}')\n image_iter_advlist += 1\n idx_advList -= 1\n # print(\"Minimum Softmax of \" + str(labelCount) + \":\" + str(\n # min(totalSoftmaxList[10 * labelCount:10 * labelCount + 10])))\n # print(\"Maximum Softmax of \" + str(labelCount) + \":\" + str(\n # max(totalSoftmaxList[10 * labelCount:10 * labelCount + 10])))\n print(SvalIndividual/10)\n targetID+=1 # break\n # print(\"Done -> \"+str(labelCount))\n # forSoftMaxList = forSoftMaxList[:,None, :, :]\n # with torch.no_grad():\n # SMoutputAdvList = model(forSoftMaxList)\n # softMaxValsFinal = F.softmax(SMoutputAdvList, dim=1)\n # sFmAX = softMaxValsFinal.max(axis=1)[0]\n print(\"S Value: \" + str(Sval/len(maxIndex)))\n if len(adv_images) < 100:\n print(\"Not enough images generated\")\n iterNum = [i + 1 for i in iterNum]\n\n return adv_images,image_names,targeted_class_labels\n\ndef main():\n # Settings\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch-size', type=int, default=5)\n parser.add_argument('--no-cuda', action='store_true', default=False,help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')\n parser.add_argument('--model_path', type=str, default='model/mnist_cnn.pt')\n parser.add_argument('--data_folder', type=str, default='data')\n\n\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n mean = (0.1307,)\n std = (0.3081,)\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n data_loader = torch.utils.data.DataLoader(\n torchvision.datasets.DatasetFolder('D:/MComp/CS5260 Deep Learning and NN-2/Assignment_1/Assignment_1/data',\n loader= numpy_loader,\n extensions= '.npy',\n transform=transforms.Compose([transforms.ToTensor(),\n transforms.Normalize(mean, std)])),\n batch_size=args.batch_size, **kwargs)\n\n model = Net().to(device)\n\n model.load_state_dict(torch.load(args.model_path))\n\n # evaluate_model_for_accuracy(model, device, data_loader)\n\n adv_images,image_names,class_labels = generate_adv_images(model, device, kwargs)\n #Implement this method to generate adv images\n #statisfying constraints mentioned in the assignment discription\n\n save_folder = 'adv_images'\n remove_files_in_dir(os.path.join(save_folder))\n\n for image,image_name,class_label in zip(adv_images,image_names,class_labels):\n for t, m, s in zip(image, mean, std):\n t.mul_(s).add_(m)\n\n image_to_save = image.squeeze().detach().cpu().numpy()\n image_to_save = 255.0 * image_to_save\n\n if np.min(image_to_save) < 0 or np.max(image_to_save) > 255:\n print('Generated adversarial image is out of range.')\n sys.exit()\n if not os.path.exists(os.path.join(save_folder,str(class_label))):\n makedirs(os.path.join(save_folder,str(class_label)))\n\n np.save(os.path.join(save_folder,str(class_label),image_name), image_to_save)\n\n evaluate_adv_images(model,device,kwargs,mean,std,data_loader)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"mnist_code.py","file_name":"mnist_code.py","file_ext":"py","file_size_in_byte":21071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"426299699","text":"#coding=gbk\nimport re\nimport os\n\ndef run_dir(path_original, path_saveNew):\n pathdir_original = os.listdir(path_original) # 列出原始样本文件夹下的文件名和文件夹名\n for name in pathdir_original: # 对文件名进行循环\n if os.path.isfile(path_original + \"\\\\\" + name): # 如果name是一个文件,这里传入的路径必须是绝对路径才可以判断\n # if name[-5:]=='.arff':\n # continue\n print(path_original + \"\\\\\" + name)\n if name=='del_smote_info.csv' or name=='del_cca_info.csv':\n continue\n else:\n os.rename(path_original + \"\\\\\" + name,path_original + \"\\\\\" + name[:-4]+'.arff')# 改文件名\n '''读取文件'''\n f_r = open(path_original+ \"\\\\\" + name[:-4]+'.arff', 'r')\n inData = f_r.readlines() # 读取文件数据,以列表形式返回\n numAttribute = len(re.split(r'[\\s,\\t]+', inData[0].strip())) # 属性列的个数\n dataSet = list() # 用于存储格式化之后的数据\n for line in inData:\n line = line.strip() # 将line开头和结尾的空行去掉\n strList = re.split(r'[\\s,\\t]+', line) # strList为返回的列表,列表中的元素为str类型\n '''将strList中的str类型的元素转换为float类型,方便计算'''\n numList = list()\n for item in strList:\n num = float(item)\n numList.append(num)\n dataSet.append(numList)\n f_r.close()\n '''写入文件'''\n f_w = open(path_saveNew+ \"\\\\\" + name[:-4]+'.arff', 'w')\n '''arff格式写入'''\n f_w.write('% Title: ' + path_saveNew+ \"\\\\\" + name[:-4]+'.arff' + '\\n\\n')\n f_w.write('@RELATION ' + path_saveNew+ \"\\\\\" + name[:-4]+'.arff' + '\\n\\n')\n for i in range(numAttribute - 1):\n f_w.write('@ATTRIBUTE ' + str(i + 1) + ' NUMERIC\\n')\n f_w.write('@ATTRIBUTE class {0,1}\\n\\n')\n f_w.write('@data\\n')\n for i in range(len(dataSet)): # 因为之前在第一行加了12345.。。所以要删去\n if i == -1:\n continue\n else:\n for j in range(len(dataSet[i])):\n if j < len(dataSet[i]) - 1:\n f_w.write(str(dataSet[i][j]) + ',')\n else:\n f_w.write(str(int(dataSet[i][j])))\n f_w.write('\\n')\n f_w.close()\n\n else: # 如果name是一个文件夹\n path1 = path_original + \"\\\\\" + name # 更新原始数据集路径\n os.mkdir(path_saveNew + \"\\\\\" + name) # 创建和原始数据集文件夹一致的文件夹,用于保存采样的结果\n path2 = path_saveNew + \"\\\\\" + name # 更新保存数据的路径为新创建的文件夹\n run_dir(path1, path2) # 调用循环采样的方法,循环调用\nif __name__ == '__main__':\n\n path_original=\"E:\\Papers_dataset\\ResempledDataSet\\CCA_all_1_arff\"\n path_saveNew=\"E:\\Papers_dataset\\ResempledDataSet\\CCA_all_2_arff\"\n run_dir(path_original,path_saveNew)","sub_path":"LearningText/toArff.py","file_name":"toArff.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404057602","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom labellines import labelLine, labelLines\n\nax = plt.axes()\n\n\n# Ensure that the next plot doesn't overwrite the first plot\npoint = np.array([0, 0, 0])\nnormal = np.array([1, 0, 0])\n\n# a plane is a*x+b*y+c*z+d=0\n# [a,b,c] is the normal. Thus, we have to calculate\n# d and we're set\nd = -point.dot(normal)\n\n# create x,y\n# zz, yy = np.meshgrid(range(-2, 2, 0.5), range(-2, 2, 1))\nzz, yy = np.meshgrid(np.linspace(-2., 2., num=5), np.linspace(-2., 2., num=5))\nxx = yy*0\n# calculate corresponding z\nz = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]\n\n# plot the surface\nplt3d = plt.subplot(projection='3d')\nplt3d.plot_wireframe(0, yy, zz)\nplt3d.quiver(0, 0, 0, 1., 0, 0., colors = 'black', linewidths=2, arrow_length_ratio=0.2)\nplt3d.text(1, 0, 0, \"U=Vector $(1,1,0)$\")\nplt3d.text(0, -2, 2.5, \"$U^{\\perp}$=The Plane $x=0$\", (1,1,1.5))\n# plt3d.text(5, 5, 5, \"(5,5,5)\")\nplt3d.set_xticks(range(-2, 3))\nplt3d.set_yticks(range(-2, 3))\nplt3d.set_zticks(range(-2, 3))\nplt3d.set_xlim([-2,2])\nplt3d.set_ylim([-2,2])\nplt3d.set_zlim([-2,2])\nplt3d.set_xlabel('X axis')\nplt3d.set_ylabel('Y axis')\nplt3d.set_zlabel('Z axis')\n\nplt.show()\n","sub_path":"code/graphs/vector-u-and-its-orthogonal-complement-plane-u-perp.py","file_name":"vector-u-and-its-orthogonal-complement-plane-u-perp.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"558785659","text":"\"\"\"This example makes a reactor geometry, neutronics model and performs a TBR\nsimulation. A selection of materials are used from refrenced sources to\ncomplete the neutronics model.\"\"\"\n\nimport neutronics_material_maker as nmm\nimport openmc\nimport paramak\n\n\ndef make_model_and_simulate():\n \"\"\"Makes a neutronics Reactor model and simulates the TBR with specified materials\"\"\"\n\n # based on\n # http://www.euro-fusionscipub.org/wp-content/uploads/WPBBCP16_15535_submitted.pdf\n firstwall_radial_thickness = 3.0\n firstwall_armour_material = \"tungsten\"\n firstwall_coolant_material = \"He\"\n firstwall_structural_material = \"eurofer\"\n firstwall_armour_fraction = 0.106305\n firstwall_coolant_fraction = 0.333507\n firstwall_coolant_temperature_k = 400\n firstwall_coolant_pressure_Pa = 8e6\n firstwall_structural_fraction = 0.560188\n\n firstwall_material = nmm.Material.from_mixture(\n name=\"firstwall_mat\",\n materials=[\n nmm.Material.from_library(\n name=firstwall_coolant_material,\n temperature=firstwall_coolant_temperature_k,\n pressure=firstwall_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=firstwall_structural_material),\n nmm.Material.from_library(name=firstwall_armour_material),\n ],\n fracs=[\n firstwall_coolant_fraction,\n firstwall_structural_fraction,\n firstwall_armour_fraction,\n ],\n percent_type=\"vo\"\n )\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n blanket_rear_wall_coolant_material = \"H2O\"\n blanket_rear_wall_structural_material = \"eurofer\"\n blanket_rear_wall_coolant_fraction = 0.3\n blanket_rear_wall_structural_fraction = 0.7\n # units of Kelvin, equivalent 200 degrees C\n blanket_rear_wall_coolant_temperature = 473.15\n blanket_rear_wall_coolant_pressure = 1e6 # units of Pa\n\n blanket_rear_wall_material = nmm.Material.from_mixture(\n name=\"blanket_rear_wall_mat\",\n materials=[\n nmm.Material.from_library(\n name=blanket_rear_wall_coolant_material,\n temperature=blanket_rear_wall_coolant_temperature,\n pressure=blanket_rear_wall_coolant_pressure,\n ),\n nmm.Material.from_library(\n name=blanket_rear_wall_structural_material),\n ],\n fracs=[\n blanket_rear_wall_coolant_fraction,\n blanket_rear_wall_structural_fraction,\n ],\n percent_type=\"vo\")\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n blanket_lithium6_enrichment_percent = 60\n blanket_breeder_material = \"Li4SiO4\"\n blanket_coolant_material = \"He\"\n blanket_multiplier_material = \"Be\"\n blanket_structural_material = \"eurofer\"\n blanket_breeder_fraction = 0.15\n blanket_coolant_fraction = 0.05\n blanket_multiplier_fraction = 0.6\n blanket_structural_fraction = 0.2\n blanket_breeder_packing_fraction = 0.64\n blanket_multiplier_packing_fraction = 0.64\n blanket_coolant_temperature_k = 773.15\n blanket_coolant_pressure_Pa = 1e6\n blanket_breeder_temperature_k = 873.15\n blanket_breeder_pressure_Pa = 8e6\n\n blanket_material = nmm.Material.from_mixture(\n name=\"blanket_mat\",\n materials=[\n nmm.Material.from_library(\n name=blanket_coolant_material,\n temperature=blanket_coolant_temperature_k,\n pressure=blanket_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=blanket_structural_material),\n nmm.Material.from_library(\n name=blanket_multiplier_material,\n packing_fraction=blanket_multiplier_packing_fraction,\n ),\n nmm.Material.from_library(\n name=blanket_breeder_material,\n enrichment=blanket_lithium6_enrichment_percent,\n packing_fraction=blanket_breeder_packing_fraction,\n temperature=blanket_breeder_temperature_k,\n pressure=blanket_breeder_pressure_Pa,\n ),\n ],\n fracs=[\n blanket_coolant_fraction,\n blanket_structural_fraction,\n blanket_multiplier_fraction,\n blanket_breeder_fraction,\n ],\n percent_type=\"vo\"\n )\n\n # based on\n # https://www.sciencedirect.com/science/article/pii/S2352179118300437\n divertor_coolant_fraction = 0.57195798876\n divertor_structural_fraction = 0.42804201123\n divertor_coolant_material = \"H2O\"\n divertor_structural_material = \"tungsten\"\n divertor_coolant_temperature_k = 423.15 # equivalent to 150 degrees C\n divertor_coolant_pressure_Pa = 5e6\n\n divertor_material = nmm.Material.from_mixture(\n name=\"divertor_mat\",\n materials=[\n nmm.Material.from_library(\n name=divertor_coolant_material,\n temperature=divertor_coolant_temperature_k,\n pressure=divertor_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(name=divertor_structural_material),\n ],\n fracs=[divertor_coolant_fraction, divertor_structural_fraction],\n percent_type=\"vo\"\n )\n\n # based on\n # https://pdfs.semanticscholar.org/95fa/4dae7d82af89adf711b97e75a241051c7129.pdf\n center_column_shield_coolant_fraction = 0.13\n center_column_shield_structural_fraction = 0.57\n center_column_shield_coolant_material = \"H2O\"\n center_column_shield_structural_material = \"tungsten\"\n center_column_shield_coolant_temperature_k = 423.15 # equivalent to 150 degrees C\n center_column_shield_coolant_pressure_Pa = 5e6\n\n center_column_shield_material = nmm.Material.from_mixture(\n name=\"center_column_shield_mat\",\n materials=[\n nmm.Material.from_library(\n name=center_column_shield_coolant_material,\n temperature=center_column_shield_coolant_temperature_k,\n pressure=center_column_shield_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(\n name=center_column_shield_structural_material),\n ],\n fracs=[\n center_column_shield_coolant_fraction,\n center_column_shield_structural_fraction,\n ],\n percent_type=\"vo\")\n\n # based on\n # https://pdfs.semanticscholar.org/95fa/4dae7d82af89adf711b97e75a241051c7129.pdf\n inboard_tf_coils_conductor_fraction = 0.57\n inboard_tf_coils_coolant_fraction = 0.05\n inboard_tf_coils_structure_fraction = 0.38\n inboard_tf_coils_conductor_material = \"copper\"\n inboard_tf_coils_coolant_material = \"He\"\n inboard_tf_coils_structure_material = \"SS_316L_N_IG\"\n inboard_tf_coils_coolant_temperature_k = 303.15 # equivalent to 30 degrees C\n inboard_tf_coils_coolant_pressure_Pa = 8e6\n\n inboard_tf_coils_material = nmm.Material.from_mixture(\n name=\"inboard_tf_coils_mat\",\n materials=[\n nmm.Material.from_library(\n name=inboard_tf_coils_coolant_material,\n temperature=inboard_tf_coils_coolant_temperature_k,\n pressure=inboard_tf_coils_coolant_pressure_Pa,\n ),\n nmm.Material.from_library(\n name=inboard_tf_coils_conductor_material),\n nmm.Material.from_library(\n name=inboard_tf_coils_structure_material),\n ],\n fracs=[\n inboard_tf_coils_coolant_fraction,\n inboard_tf_coils_conductor_fraction,\n inboard_tf_coils_structure_fraction,\n ],\n percent_type=\"vo\")\n\n # makes the 3d geometry\n my_reactor = paramak.BallReactor(\n inner_bore_radial_thickness=1,\n inboard_tf_leg_radial_thickness=30,\n center_column_shield_radial_thickness=60,\n divertor_radial_thickness=50,\n inner_plasma_gap_radial_thickness=30,\n plasma_radial_thickness=300,\n outer_plasma_gap_radial_thickness=30,\n firstwall_radial_thickness=firstwall_radial_thickness,\n # http://www.euro-fusionscipub.org/wp-content/uploads/WPBBCP16_15535_submitted.pdf\n blanket_radial_thickness=100,\n blanket_rear_wall_radial_thickness=3,\n elongation=2.75,\n triangularity=0.5,\n number_of_tf_coils=16,\n rotation_angle=360,\n )\n\n source = openmc.Source()\n # sets the location of the source to x=0 y=0 z=0\n source.space = openmc.stats.Point((my_reactor.major_radius, 0, 0))\n # sets the direction to isotropic\n source.angle = openmc.stats.Isotropic()\n # sets the energy distribution to 100% 14MeV neutrons\n source.energy = openmc.stats.Discrete([14e6], [1])\n\n # makes the neutronics material\n neutronics_model = paramak.NeutronicsModel(\n geometry=my_reactor,\n source=source,\n materials={\n 'inboard_tf_coils_mat': inboard_tf_coils_material,\n 'center_column_shield_mat': center_column_shield_material,\n 'divertor_mat': divertor_material,\n 'firstwall_mat': firstwall_material,\n 'blanket_mat': blanket_material,\n 'blanket_rear_wall_mat': blanket_rear_wall_material},\n cell_tallies=['TBR'],\n simulation_batches=5,\n simulation_particles_per_batch=1e4,\n )\n\n # starts the neutronics simulation\n neutronics_model.simulate()\n\n # prints the simulation results to screen\n print('TBR', neutronics_model.results['TBR'])\n\n\nif __name__ == \"__main__\":\n make_model_and_simulate()\n","sub_path":"examples/example_neutronics_simulations/segmented_blanket_ball_reactor.py","file_name":"segmented_blanket_ball_reactor.py","file_ext":"py","file_size_in_byte":9592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368644314","text":"import torch\nimport torch.utils as utils\nimport torchvision\nfrom torchvision import transforms\nfrom torch import nn\nfrom torch import backends\nfrom torchvision import datasets\nfrom torchvision.transforms.functional import to_pil_image\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot\nfrom PIL import Image\nimport numpy as np\nimport argparse\nimport os\nimport math\nimport time as timer\nfrom datetime import datetime\nfrom torch.utils.tensorboard import SummaryWriter\nfrom glob import glob\nfrom skimage import io\n\nimport imgaug as ia\nimport imgaug.augmenters as iaa\n\n# Reproducibility: asignar la misma seed a todas las librerías para que a ejecuciones iguales obtengamos\n# resultados iguales\ntorch.manual_seed(1)\nif torch.cuda.is_available():\n torch.cuda.manual_seed_all(1)\nnp.random.seed(1)\n#torch.backends.cudnn.deterministic = True\n#torch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.enabled = True\n\nfrom Dataset import MyDataset\nimport utils as aux\nimport metrics as metrics\nfrom UNet import UNet\nfrom UNetModes import UNetFull\n\n\ndef main(opt, model_version, ds_version, data_augmentation, inverted_freq, weather):\n\n params = {'num_epochs': 60,\n 'batch_size': 10,\n 'num_classes': 19,\n 'start_features':32,\n 'adam_learning_rate': 1E-3,\n 'adam_aux_learning_rate': 5E-4,\n 'adam_weight_decay': 1E-4,\n 'sgd_learning_rate': 1E-1,\n 'sgd_weight_decay': 1E-4,\n 'sgd_momentum': 0.9,\n 'device': torch.device(\"cuda\"),\n 'dataset_url': '/home/jupyter/it6/utils/',\n 'log_dir': '/home/jupyter/it6/runs/',\n 'file_suffix':'_split_urls'\n }\n\n params['device'] = torch.device(\"cuda\") if torch.cuda.is_available() else 'cpu'\n da = 'da.' if data_augmentation == 'y' else ''\n inv = 'inv.' if inverted_freq == 'y' else ''\n we = 'we' if weather == 'y' else ''\n experiment_id = opt + '.' + model_version + '.' + ds_version + \".\"+ da + inv + we\n\n #We include the set of parameters we are working with in this experiment\n print(params)\n # Creamos las transformaciones para las imagenes y targets\n #Creamos las listas para las transformaciones\n joint_transformations, joint_transformations_vt, img_transformations, img_transformations_vt = [], [], [], []\n\n #Añadimos el Resize\n joint_transformations.append(aux.Resize(256,512))\n joint_transformations_vt.append(aux.Resize(256,512))\n\n #En caso de Data Augmentation, se añade un Random Horizontal Flip y el ajuste de parametros de imagen\n if data_augmentation == \"y\":\n print('set Data Augmentation\\n')\n joint_transformations.append(aux.RandomHorizontalFlip())\n img_transformations.append(torchvision.transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1))\n\n if weather == 'y':\n print('set weather\\n')\n img_transformations.append(aux.Weather()) # La transformacion online para VT la haremos en el Dataset\n\n #añadimos la transformacion final para tensor en las img\n img_transformations.append(torchvision.transforms.ToTensor())\n img_transformations_vt.append(torchvision.transforms.ToTensor())\n\n #In the case of DeepLabv3, we apply the recommended normalization\n if model_version == 'deeplab':\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n img_transformations.append(torchvision.transforms.Normalize(mean, std))\n img_transformations_vt.append(torchvision.transforms.Normalize(mean, std))\n\n #Aplicamos la transformacion conjunta sobre img y target\n joint_transforms = aux.JointCompose(joint_transformations)\n joint_transforms_vt = aux.JointCompose(joint_transformations_vt)\n\n #Aplicamos solo la transformacion sobre img\n img_transforms = torchvision.transforms.Compose(img_transformations)\n img_transforms_vt = torchvision.transforms.Compose(img_transformations_vt)\n\n #Definimos temporizadores\n #Arrancamos el temporizador\n start = torch.cuda.Event(enable_timing=True)\n end = torch.cuda.Event(enable_timing=True)\n start_total = torch.cuda.Event(enable_timing=True)\n end_total = torch.cuda.Event(enable_timing=True)\n\n\n # Creamos los datasets y dataloaders\n train_dataset = MyDataset(version=ds_version, split='train', joint_transform=joint_transforms, img_transform=img_transforms, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'])\n train_loader = utils.data.DataLoader(train_dataset, batch_size=params['batch_size'], shuffle=True, num_workers=4)\n\n val_dataset = MyDataset(version=ds_version, split='val', joint_transform=joint_transforms_vt, img_transform=img_transforms_vt, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'], add_weather= weather == 'y')\n val_loader = utils.data.DataLoader(val_dataset, batch_size=params['batch_size'], shuffle=False, num_workers=4)\n\n test_dataset = MyDataset(version=ds_version, split='test', joint_transform=joint_transforms_vt, img_transform=img_transforms_vt, url_csv_file=params['dataset_url'], file_suffix=params['file_suffix'], add_weather= weather == 'y')\n test_loader = utils.data.DataLoader(test_dataset, batch_size=params['batch_size'], shuffle=False, num_workers=4)\n\n def train_one_epoch(train_loader, net, optimizer, criterion, hparams):\n\n # Activate the train=True flag inside the model\n net.train()\n\n device = hparams['device']\n batch_size = hparams['batch_size']\n train_loss, train_accs = 0, 0\n train_iou = {}\n times_per_step_iteration = []\n times_per_metric_iteration = []\n times_per_iteration = []\n for batch_index, (img, target) in enumerate(train_loader):\n #Arrancamos temporizador general\n start_total.record()\n img, target = img.to(device), target.to(device)\n optimizer.zero_grad()\n\n # Arrancamos temporizador para inferencia\n start.record()\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n\n target = target.long()\n\n\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n pred = aux.get_predicted_image(output)\n\n #Paramos temporizador de inferencia\n end.record()\n torch.cuda.synchronize()\n times_per_step_iteration.append(start.elapsed_time(end))\n\n # Accuracy\n #Arrancamos temporizador para métricas\n start.record()\n\n # Desvinculamos el valor de los nuevos targets y los pasamos a CPU para calcular las métricas\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n train_loss += loss.item()\n # Devuelve values, indices. Los indices son el nº de feature map (clase) en la que se encuentra el valor más alto en el pixel\n train_accuracy = metrics.calculate_accuracy(output, target) #, predicted\n train_accs += train_accuracy\n\n\n iou_inds = metrics.calculate_iou(pred, target)\n for key in iou_inds:\n if key not in train_iou:\n train_iou[key] = iou_inds[key]\n else:\n train_iou[key] += iou_inds[key]\n\n #Paramos temporizador para métricas\n end.record()\n torch.cuda.synchronize()\n times_per_metric_iteration.append(start.elapsed_time(end))\n\n #Paramos temporizador general\n end_total.record()\n torch.cuda.synchronize()\n times_per_iteration.append(start_total.elapsed_time(end))\n\n avg_time_taken = sum(times_per_iteration)/len(times_per_iteration)\n avg_time_step_taken = sum(times_per_step_iteration)/len(times_per_step_iteration)\n avg_time_metrics_taken = sum(times_per_metric_iteration)/len(times_per_metric_iteration)\n\n\n print('Average Time spent total: {:.02f}s'.format(avg_time_taken*1e-3))\n print('Average Time spent by steps: {:.02f}s'.format(avg_time_step_taken*1e-3))\n print('Average Time spent by metrics: {:.02f}s'.format(avg_time_metrics_taken*1e-3))\n print('Average Time spent by data load: {:.02f}s'.format(avg_time_taken*1e-3-avg_time_step_taken*1e-3-avg_time_metrics_taken*1e-3))\n\n\n train_loss = train_loss / (len(train_loader.dataset) / batch_size)\n train_accs = 100 * (train_accs / (len(train_loader.dataset) / batch_size))\n train_iou = metrics.convert_batched_iou(train_iou, (len(train_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(train_iou)\n mIoU_desc = metrics.miou_to_string(train_iou)\n return train_loss, train_accs, mIoU, mIoU_desc\n\n\n def val_one_epoch(val_loader, net):\n\n net.eval()\n device = params['device']\n batch_size = params['batch_size']\n val_loss = 0\n val_acc = 0\n val_iou = {}\n pred = 0\n with torch.no_grad():\n for batch_index, (img, target) in enumerate(val_loader):\n img, target = img.to(device), target.to(device)\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n \n if batch_index == 0:\n first_pred = output\n \n target = target.long()\n\n loss = criterion(output, target).item()\n val_loss += loss\n\n pred = aux.get_predicted_image(output)\n # Desvinculamos el valor de los nuevos targets y los pasamos a CPU para calcular las métricas\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n\n # compute number of correct predictions in the batch\n val_accuracy = metrics.calculate_accuracy(output, target)\n val_acc += val_accuracy\n iou_inds = metrics.calculate_iou(pred, target)\n\n for key in iou_inds:\n if key not in val_iou:\n val_iou[key] = iou_inds[key]\n else:\n val_iou[key] += iou_inds[key]\n #print('Batch index: {}, loss: {}, accuracy: {:.2f}%'.format(batch_index, loss, val_accuracy * 100))\n # Average acc across all correct predictions batches now\n val_loss = val_loss / (len(val_loader.dataset) / batch_size)\n val_acc = 100 * (val_acc / (len(val_loader.dataset) / batch_size))\n val_iou = metrics.convert_batched_iou(val_iou, (len(val_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(val_iou)\n\n #print('\\nValidation set: Average loss: {:.4f}, Accuracy: {:.0f}%, mIoU: {:.4f}\\n'.format(val_loss, val_acc, mIoU))\n mIoU_desc = metrics.miou_to_string(val_iou)\n return val_loss, val_acc, mIoU, mIoU_desc, first_pred\n\n\n def test_model(test_loader, net):\n\n net.eval()\n device = params['device']\n batch_size = params['batch_size']\n test_loss = 0\n test_acc = 0\n test_iou = {}\n with torch.no_grad():\n for batch_index, (img, target) in enumerate(test_loader):\n img, target = img.to(device), target.to(device)\n\n if model_version == 'deeplab':\n output = net(img)['out']\n else:\n output = net(img)\n\n target = target.long()\n loss = criterion(output, target).item()\n test_loss += loss\n\n pred = aux.get_predicted_image(output)\n\n output, target, pred = output.detach().cpu(), target.detach().cpu(), pred.detach().cpu()\n # compute number of correct predictions in the batch\n test_accuracy = metrics.calculate_accuracy(output, target)\n test_acc += test_accuracy\n\n iou_inds = metrics.calculate_iou(pred, target)\n\n for key in iou_inds:\n if key not in test_iou:\n test_iou[key] = iou_inds[key]\n else:\n test_iou[key] += iou_inds[key]\n\n test_loss = test_loss / (len(test_loader.dataset) / batch_size)\n test_acc = 100 * (test_acc / (len(test_loader.dataset) / batch_size))\n test_iou = metrics.convert_batched_iou(test_iou, (len(test_loader.dataset) / batch_size))\n mIoU = metrics.get_mIoU(test_iou)\n\n mIoU_desc = metrics.miou_to_string(test_iou)\n return test_loss, test_acc, mIoU, mIoU_desc\n\n\n #####################\n ## Build the net here\n if model_version == 'linear':\n print('set linear unet\\n')\n model = UNet(num_classes=params['num_classes'], start_features=params['start_features'])\n elif model_version == 'deeplab':\n print('set DeepLabv3\\n')\n model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained_backbone=True)\n model.classifier[-1] = nn.Conv2d(256, params['num_classes'], 1)\n else:\n print('set ' + str(model_version) + ' unet\\n')\n model = UNetFull(num_classes=params['num_classes'], start_features=params['start_features'], bilinear=model_version == 'bilinear')\n\n ###################\n\n writer_date = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n run_path = params['log_dir'] + '/' + experiment_id\n run_data_folder = run_path + '/' + writer_date\n tb_writer_train = SummaryWriter(log_dir= run_data_folder + \"/train\")\n tb_writer_val = SummaryWriter(log_dir= run_data_folder + \"/val\")\n images_train, targets_train = next(iter(train_loader))\n images_val, targets_val = next(iter(val_loader))\n\n aux.write_tensorboard_inicio(tb_writer_train,tb_writer_val, model, images_train, images_val, targets_val)\n\n ##################\n\n model.to(params['device'])\n net_params = model.parameters()\n\n\n #Depending on the inverted frequency parameter we apply this parameter as a weight to balance the Loss Function\n if inverted_freq == 'y':\n print('set Inverted Frequency weights \\n')\n num_pixels_per_class = [127414939, 21058643, 79041999, 2269832, 3038496, 4244760, 720425, 1911074, 55121339, 4008424, 13948699, 4204816, 465832, 24210293, 925225, 813190, 805591, 341018, 1430722]\n\n norm_weights = [(num_pixels/sum(num_pixels_per_class)) for num_pixels in num_pixels_per_class]\n inverted_weights = [(1/num_pixels) for num_pixels in norm_weights]\n inverted_weights = torch.FloatTensor(inverted_weights).to(params['device'])\n criterion = torch.nn.CrossEntropyLoss(weight=inverted_weights, ignore_index=255)\n else:\n criterion = torch.nn.CrossEntropyLoss(ignore_index=255)\n\n\n if opt == 'adam':\n print('set adam optimizer\\n')\n optimizer = torch.optim.Adam(net_params, lr=params['adam_learning_rate'], betas=(0.9, 0.999), eps=1e-08, weight_decay=params['adam_weight_decay'], amsgrad=False)\n elif opt == 'sgd':\n print('set SGD optimizer\\n')\n optimizer = torch.optim.SGD(net_params, lr=params['sgd_learning_rate'],momentum= params['sgd_momentum'], weight_decay=params['sgd_weight_decay'])\n\n best_epoch_miou, added_targg = 0, False\n\n print('Dataset train images: {}, dataset val images: {}'.format(len(train_loader.dataset), len(val_loader.dataset)))\n\n train_losses, train_acc_hist, val_losses, val_acc_hist, mIoU_hist_train, mIoU_hist_val = [], [], [], [], [], []\n for epoch in range(1, params['num_epochs'] +1):\n\n # Compute & save the average training loss for the current epoch\n print('#################### Epoch: {} ####################\\n'.format(epoch))\n\n aux.print_timestamp('Inicio training epoch {}'.format(epoch))\n train_loss, train_acc, train_mIoU, mIoU_desc_train = train_one_epoch(train_loader, model, optimizer, criterion, params)\n print('Training set: Average loss {:.4f}, Average accuracy {:.2f}%, mIoU: {:.2f}\\n{}\\n'.format(train_loss, train_acc, train_mIoU, mIoU_desc_train))\n\n aux.print_timestamp('Inicio validacion epoch {}'.format(epoch))\n val_loss, val_acc, val_mIoU, mIoU_desc_val, first_pred = val_one_epoch(val_loader, model)\n print('Validation set: Average loss: {:.4f}, Mean accuracy: {:.2f}%, mIoU: {:.2f}\\n{}\\n'.format(val_loss, val_acc, val_mIoU, mIoU_desc_val))\n\n train_mAP = sum(train_acc_hist) / epoch # params['num_epochs']\n val_mAP = sum(val_acc_hist) / epoch # params['num_epochs']\n\n if val_mIoU > best_epoch_miou:\n best_epoch_miou = val_mIoU\n print('Guardamos el modelo en epoch {} ( mIoU {:.2f})'.format(epoch, val_mIoU))\n aux.save_model(model, run_data_folder +'/best')\n aux.write_tensorboard_best_IoU(tb_writer_val, val_mIoU, epoch)\n\n train_acc_hist.append(train_acc)\n val_acc_hist.append(val_acc)\n\n mIoU_hist_train.append(train_mIoU)\n mIoU_hist_val.append(val_mIoU)\n\n\n aux.write_tensorboard_epoch(tb_writer_train, tb_writer_val,run_data_folder, first_pred[0], epoch, train_loss, train_acc, val_loss, val_acc, train_mIoU, val_mIoU, train_mAP, val_mAP)\n\n aux.save_model(model, run_data_folder +'/last')\n print('Fin del entrenamiento\\n')\n\n tb_writer_train.close()\n tb_writer_val.close()\n\n #############\n #####Test####\n #############\n model = aux.load_model(run_data_folder +'/best')\n print('Dataset test images: {}'.format(len(test_loader.dataset)))\n test_loss, test_acc, mIoU, mIoU_desc = test_model(test_loader, model)\n print('Test set: Average loss: {:.4f}, Mean accuracy: {:.2f}%, mIoU: {:.2f}%\\n{}\\n'.format(test_loss, test_acc, mIoU, mIoU_desc))\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-opt', '--optimizer', default='adam', help='Optimizer for the execution')\n parser.add_argument('-net', '--network', default='trans', help='Model version (with/out concatenations), Unet or DeepLabv3')\n parser.add_argument('-ds', '--dataset', default='cityscapes', help='cityscapes full dataset, it6 skim version')\n parser.add_argument('-da', '--data_augmentation', default='n', help='Apply data augmentation, random horizontal flip and color jitter')\n parser.add_argument('-invf', '--inverted_freq', default='n', help='Apply inverted frequency to the criterion')\n parser.add_argument('-weather', '--weather', default='n', help='Apply weatherdata augmentation, cloud, rain, snow and fog')\n args = parser.parse_args()\n print('{}, {}, {}, {}, {}, {}'.format(args.optimizer, args.network, args.dataset, args.data_augmentation, args.inverted_freq, args.weather))\n\n main(opt= args.optimizer, model_version=args.network, ds_version=args.dataset, data_augmentation=args.data_augmentation, inverted_freq=args.inverted_freq, weather=args.weather)\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":18996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162853861","text":"import os\nimport math\n\nimport numpy\nimport yaml\n\nimport ilisa.observations\n\n\ndef pointingGrid(NrAzDirs=8, NrElDirs=7):\n \"\"\"Returns a tuple of LOFAR beamctl directions strings of a spherical\n grid of pointings around zenith.\"\"\"\n # Nr of pointings NrAzDirs*NrElDirs+1 (where 1 is zenith)\n # should be less than 61 if they are to fit in one lane.\n az = numpy.linspace(0, 2*math.pi, NrAzDirs+1)\n numpy.delete(az, NrAzDirs)\n az = az-0*math.pi/4\n el = numpy.linspace(0, math.pi/2, NrElDirs+1)\n numpy.delete(el, NrElDirs)\n pntGridStrs = []\n # El Major:\n for ElDirNr in range(NrElDirs):\n for AzDirNr in range(NrAzDirs):\n nextPnting = str(az[AzDirNr])+\",\"+str(el[ElDirNr])+\",AZELGEO\"\n pntGridStrs.append(nextPnting)\n zenith = '0.0,'+str(math.pi/2)+',AZELGEO'\n pntGridStrs.append(zenith)\n return tuple(pntGridStrs)\n\n\ndef pointing_str2tuple(beamctldirarg):\n \"\"\"Convert a beamctl direction string into direction tuple.\n\n Parameters\n ----------\n beamctldirarg : str\n String with format 'angle1,angle2,refsys'\n\n Returns\n -------\n dirtuple : tuple or None\n Direction tuple defined as (angle1: float, angle2: float, refsys: str)\n or None if beamctldirarg was not correct format.\n \"\"\"\n try:\n angle1str, angle2str, refsys = beamctldirarg.split(',')\n angle1, angle2 = float(angle1str), float(angle2str)\n # TODO should check that refsys is one of the valid refsys strings.\n dirtuple = (angle1, angle2, refsys)\n return dirtuple\n except ValueError:\n return None\n\n\ndef std_pointings(directionterm='?'):\n \"\"\"Find beamctl direction string based on direction term.\n\n Parameters\n ----------\n directionterm : str, '?', '', or None\n Source name or term for a direction. E.g. 'Z' for Zenith\n or 'Cas-A' for Cassiopeia A.\n\n Returns\n -------\n beamctldir : str\n Argument suitable for beamctl direction arguments --anadir and\n --digdir. If directionterm is None it will return all the direction terms it\n knows. If it is '', then it will return an empty direction ',,'.\n\n Raises\n ------\n KeyError\n Thrown if directionterm is not understood.\n \"\"\"\n term2beamstr = { # 1e-6 rad < 1arcsec\n '': ',,',\n 'N': str(0*math.pi/2)+',0.,AZELGEO',\n 'E': str(1*math.pi/2)+',0.,AZELGEO',\n 'S': str(2*math.pi/2)+',0.,AZELGEO',\n 'W': str(3*math.pi/2)+',0.,AZELGEO',\n 'Z': '0.,'+str(math.pi/2)+',AZELGEO',\n 'CasA': '6.123487,1.026515,J2000', # Alternative to 'Cas-A'\n 'Cas-A': '6.123487,1.026515,J2000', # 3C-461\n 'Cyg-A': '5.233660,0.710940,J2000', # 3C-405\n 'Tau-A': '1.459672,0.384225,J2000', # 3C-144\n 'Vir-A': '3.276086,0.216265,J2000', # 3C-274\n 'Sun': '0.,0.,SUN',\n 'Jupiter': '0.,0.,JUPITER',\n 'Moon': '0.,0.,MOON',\n 'NCP': '0.,'+str(math.pi/2)+',ITRF'\n }\n if directionterm is '?':\n return term2beamstr.keys()\n if directionterm in term2beamstr:\n return term2beamstr[directionterm]\n elif directionterm is None:\n return None\n else:\n raise KeyError('Requested source {} unknown.'.format(directionterm))\n\n\ndef normalizebeamctldir(gendirstr):\n \"\"\"Parse a general direction string.\n\n Parameters\n ----------\n gendirstr : str\n This could be one of the direction terms or it could a beamctl\n direction string.\n\n Returns\n -------\n beamctldirstr : str\n The beamctl direction string corresponding to input gendirstr. If gendirstr is\n None, then beamctldirstr is None.\n \"\"\"\n if gendirstr is None:\n return None\n beamctldir = pointing_str2tuple(gendirstr)\n if beamctldir is None:\n try:\n beamctldirstr = std_pointings(gendirstr)\n except:\n raise ValueError('General direction term {} unknown.'.format(gendirstr))\n else:\n beamctldirstr = gendirstr\n return beamctldirstr\n\n\ndef lookupsource(src_name):\n \"\"\"Lookup the pointing direction for the name of a source stored in user created\n files.\n\n Parameters\n ----------\n src_name : str\n Name of source.\n\n Returns\n -------\n pointing : tuple\n Length 3 tuple with (az, el, ref).\n\n \"\"\"\n src_database = {}\n user_srcs_dir = os.path.join(ilisa.observations.user_data_dir, 'sources')\n user_srcs_files = os.listdir(user_srcs_dir)\n\n for user_srcs_file in user_srcs_files:\n with open(os.path.join(user_srcs_dir, user_srcs_file)) as usf:\n srcs_data = yaml.load(usf)\n for source_entry in srcs_data:\n source_name = source_entry['source']\n pointingstr = source_entry['pointing']\n src_database[source_name] = pointing_str2tuple(pointingstr)\n try:\n pointing = src_database[src_name]\n except KeyError:\n raise RuntimeError('Source {} not found in {}.'.format(src_name,\n user_srcs_files))\n return pointing","sub_path":"ilisa/observations/directions.py","file_name":"directions.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465840942","text":"import requests\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\nURL = 'https://news.google.com/topics/CAAqLQgKIidDQkFTRndvSkwyMHZNR1ptZHpWbUVnWmxjeTAwTVRrYUFrMVlLQUFQAQ?hl=es-419&gl=MX&ceid=MX%3Aes-419'\n\nif __name__ == '__main__':\n response = requests.get(URL)\n\n # Cron \n\n if response.status_code == 200:\n content = response.text\n\n soup = BeautifulSoup(content, 'html.parser')\n\n now = datetime.now().strftime('%d_%m_%Y %H_%M')\n print(now)\n # newa_dia_mes_ano.txt\n with open(f'news/news_{now}.text', 'w+') as file:\n #print(soup.prettify())\n for element in soup.find_all('h3', class_='ipQwMb ekueJc RD0gLb', limit=20):\n\n title = element.a.text\n #print(title)\n file.write(title + '\\n')\n \n print('Archivo generado de manera exitosa')\n\n","sub_path":"cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"78817736","text":"import os\nfrom datetime import datetime \nfrom flask import request, jsonify\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom bson.objectid import ObjectId\nfrom app import app, mongo\nfrom app.schemas import validate_complaint, validate_complaint_update\nimport logger\n\nROOT_PATH = os.environ.get('ROOT_PATH')\nLOG = logger.get_root_logger(__name__, filename=os.path.join(ROOT_PATH, 'output.log'))\n\n\n@app.route('/complaints', methods=['GET', 'POST', 'DELETE', 'PATCH'])\ndef complaint():\n ''' route read complaints'''\n if request.method == 'GET':\n query = request.args\n data = mongo.db.complaints.find({})\n data = list(data)\n return jsonify({'ok': True, 'data': data}), 200\n\n\n data = request.get_json()\n\n if request.method == 'POST':\n # user = get_jwt_identity()\n # if data['creator_email'] == user['email'] : # change to use id instead of email\n data = validate_complaint(data)\n if data['ok'] :\n data = data['data']\n data['timestamp'] = str(datetime.today())\n insert_id = mongo.db.complaints.insert_one(data)\n # print type(insert_id)\n return_data = mongo.db.complaints.find_one({'_id' : insert_id.inserted_id})\n return jsonify({'ok': True, 'data': return_data}), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400\n # else:\n # jsonify({'ok': False, 'message': 'No user with that email is found!'}), 400\n\n if request.method == 'DELETE':\n if data.get('id', None) is not None:\n db_response = mongo.db.complaints.delete_one({'_id': ObjectId(data['id'])})\n if db_response.delete_count == 1:\n response = {'ok': True, 'message': 'record deleted'}\n else:\n response = {'ok': True, 'message': 'no record found'}\n return jsonify(response), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400\n\n if request.method == 'PATCH':\n data = validate_complaint_update(data)\n if data['ok']:\n data = data['data']\n mongo.db.complaints.update_one(\n {'_id': ObjectId(data['id'])}, {'$set': data['payload']}\n )\n return jsonify({'ok': True, 'message': 'record updated'}), 200\n else:\n return jsonify({'ok': False, 'message': 'Bad request parameters: {}'.format(data['message'])}), 400\n\n\n@app.route('/list/complaint/user/', methods=['GET'])\ndef list_complaints(email):\n ''' route to get all complaints for a user '''\n #user = {'id': user_id}\n if request.method == 'GET':\n # query = request.args\n # email = query.get('email')\n data = mongo.db.complaints.find({'creator_email' : email})\n # if query.get('group', None):\n # return_data = {}\n # for complaint in data:\n # try:\n # return_data[complaint['status']].append(complaint)\n # except:\n # return_data[complaint['status']] = [complaint]\n # else:\n return_data = list(data)\n return jsonify({'ok': True, 'data': return_data})\n\n@app.route('/complaint/user', methods=['GET'])\ndef user_complaint():\n query = request.args \n data = mongo.db.complaints.find_one(query)\n return jsonify(data), 200","sub_path":"modules/app/controllers/complaint.py","file_name":"complaint.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492879609","text":"# Python 3\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n sol = [0]\n buy = 0\n for i in range(1, len(prices)):\n if prices[i] > prices[buy]:\n sol.append(max(sol[-1], prices[i]-prices[buy]))\n else:\n buy = i\n sol.append(sol[-1])\n res = sol[-1]\n sell = len(prices)-1\n for i in range(len(prices)-2, 0, -1):\n if prices[i] < prices[sell]:\n res = max(res, sol[i-1]+prices[sell]-prices[i])\n else:\n sell = i\n return res\n \n\n","sub_path":"leetcode/123__BestTimetoBuyandSellStockIII.py","file_name":"123__BestTimetoBuyandSellStockIII.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"291609464","text":"# -*- coding: utf-8 -*-\nmatriz=[]\nM=int(input(\"Digite o número M de quadras no sentido Norte/Sul:\"))\nN=int(input(\"Digite o número N de quadras no sentido Leste/Oeste:\"))\nfor i in range (0,M,1):\n m=[]\n for j in range (0,N,1):\n m.append(int(input(\"valor da quadra: \")))\n matriz.append(m)\nprint(matriz)\nc=[]\nfor j in range (0,N,1):\n soma=0\n for i in range (0,M,1):\n soma += matriz[i][j]\n c.append(soma)\nfor i in range(0,M,1):\n if c[i]<=c[i+1]:\n print(c)\n \n \n\n\n\n\n \n \n \n \n \n \n ","sub_path":"moodledata/vpl_data/452/usersdata/289/104007/submittedfiles/avenida.py","file_name":"avenida.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"66050933","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = 'Vasiliy Ermilov, e-mail: inkz@xakep.ru, telegram: inkz1'\n\nimport logging\nimport re\nfrom AbstractParser import AbstractParser\nfrom src.RegExpressionsLib import LinuxHttpdAccessLogRegex\n\n\nclass LinuxHttpdAccessLogParser(AbstractParser):\n\tmessage_format = 'LinuxHttpdAccessLogParser'\n\tlog_type = 'http_access'\n\tpaths = []\n\n\tdef __init__(self):\n\t\tlogging.info('Initiating http access log parser')\n\n\tdef _parse(self, line):\n\t\tmatch = re.match(LinuxHttpdAccessLogRegex.TYPE_1, line)\n\t\tmatch_type2 = None\n\n\t\tif match is None:\n\t\t\tmatch_type2 = re.match(LinuxHttpdAccessLogRegex.TYPE_2, line)\n\t\t\tif match_type2 is None:\n\t\t\t\treturn 0\n\t\t\telse:\n\t\t\t\tresult = dict(timestamp = match_type2.group(2), ip = match_type2.group(1), request_type = match_type2.group(3),\n\t\t address = match_type2.group(4), protocol = match_type2.group(5), status = match_type2.group(6),\n\t\t length = match_type2.group(7),\n\t\t referrer = match_type2.group(8), user_agent = match_type2.group(9))\n\n\t\telse:\n\t\t\tresult = dict(timestamp = match.group(2), ip = match.group(1), request_type = match.group(3),\n\t\t\t address = match.group(4), protocol = match.group(5), status = match.group(6), length = match.group(7),\n\t\t\t referrer = match.group(8), user_agent = match.group(9), extra_info = match.group(10))\n\t\treturn result\n","sub_path":"agents/linux/parsers/LinuxHttpdAccessLogParser.py","file_name":"LinuxHttpdAccessLogParser.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340150932","text":"import tensorflow as tf\nfrom models.model_util import sequence_length_op\n\n\ndef two_phase_train_graph(loss, predictions, mode, is_pretrain, params):\n estimator_spec = None\n if mode == tf.estimator.ModeKeys.PREDICT:\n estimator_spec = tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n else:\n if mode == tf.estimator.ModeKeys.TRAIN:\n with tf.name_scope('train_op'):\n optimizer = tf.train.AdamOptimizer(learning_rate=params.learning_rate)\n # compute the gradient\n if is_pretrain:\n var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='pretrain')\n else:\n var_list = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='train')\n\n gradient = optimizer.compute_gradients(loss, var_list=var_list)\n capped_gradient = [(tf.clip_by_norm(grad, params.clip_grad_norm), var) for grad, var in gradient]\n train_op = optimizer.apply_gradients(capped_gradient, global_step=tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)\n elif mode == tf.estimator.ModeKeys.EVAL:\n perplexity = tf.metrics.mean(tf.exp(loss))\n estimator_spec = tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops={\n 'perplexity': perplexity\n })\n return estimator_spec\n","sub_path":"models/train_graph.py","file_name":"train_graph.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554135140","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom PIL import Image, ImageDraw\nfrom core import HPError\n\n\nclass LengthError(HPError):\n\n def __init__(self, message):\n self.message = message\n\n def __str__(self):\n return self.message\n\n\ndef show(coord, types):\n if len(coord) != len(types):\n raise LengthError('Lengths of arguments are not the same.')\n minx = 0\n maxx = 0\n miny = 0\n maxy = 0\n for i in range(len(coord)):\n x = coord[i][0]\n y = coord[i][1]\n minx = min(minx, x)\n maxx = max(maxx, x)\n miny = min(miny, y)\n maxy = max(maxy, y)\n\n width = maxx-minx+1\n height = maxy-miny+1\n\n field = []\n for i in range(width):\n field.append([])\n for j in range(height):\n field[i].append(None)\n\n for i in range(len(coord)):\n x = coord[i][0] - minx\n y = coord[i][1] - miny\n field[x][y] = types[i]\n\n for j in range(height):\n for i in range(width):\n c = field[i][j]\n if c is None:\n c = \" \"\n print(c, end=\" \")\n print(\"\")\n\ndef mkimg(coord, types, bgcolor=(0xff, 0xff, 0xff),\n size=20, gap=20, compact=True):\n BLACK=(0x00, 0x00, 0x00)\n if len(coord) != len(types):\n raise LengthError('Lengths of arguments are not the same.')\n if compact:\n minx = 0\n maxx = 0\n miny = 0\n maxy = 0\n for i in range(len(coord)):\n x = coord[i][0]\n y = coord[i][1]\n minx = min(minx, x)\n maxx = max(maxx, x)\n miny = min(miny, y)\n maxy = max(maxy, y)\n else:\n length = len(coord)\n minx = -length\n maxx = length\n miny = -length\n maxy = length\n\n width = maxx-minx+1\n height = maxy-miny+1\n box_side = size + gap\n half = box_side / 2\n\n screen = (width * box_side, height * box_side)\n img = Image.new('RGB', screen, bgcolor)\n drw = ImageDraw.Draw(img)\n\n fill = (BLACK, bgcolor)\n pre = ((coord[0][0]-minx)*box_side,\n (coord[0][1]-miny)*box_side)\n for i in range(1, len(coord)):\n x = (coord[i][0]-minx)*box_side\n y = (coord[i][1]-miny)*box_side\n drw.line(((pre[0]+half, pre[1]+half), (x+half, y+half)),\n BLACK, 2)\n drw.rectangle(((pre[0]+gap/2, pre[1]+gap/2),\n (pre[0]+gap/2+size, pre[1]+gap/2+size)),\n fill[types[i-1]], BLACK)\n pre = (x, y)\n drw.rectangle(((pre[0]+gap/2, pre[1]+gap/2),\n (pre[0]+gap/2+size, pre[1]+gap/2+size)),\n fill[types[-1]], BLACK)\n\n return img\n","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"632814289","text":"from node import Node\n\n\nclass AstarAlgorithm:\n \"\"\"\n 1. Добавить стартовую клетку в открытый список (при этом её значения G, H и F равны 0).\n 2. Повторять следующие шаги:\n - Ищем в открытом списке клетку с наименьшим значением величины F, делаем её текущей.\n - Удаляем текущую клетку из открытого списка и помещаем в закрытый список.\n - Для каждой из соседних, к текущей клетке, клеток:\n - Если клетка непроходима или находится в закрытом списке, игнорируем её.\n - Если клетка не в открытом списке, то добавляем её в открытый список, при этом рассчитываем для неё значения G, H и F, и также устанавливаем ссылку родителя на текущую клетку.\n - Если клетка находится в открытом списке, то сравниваем её значение G со значением G таким, что если бы к ней пришли через текущую клетку. Если сохранённое в проверяемой клетке значение G больше нового, то меняем её значение G на новое, пересчитываем её значение F и изменяем указатель на родителя так, чтобы она указывала на текущую клетку.\n - Останавливаемся, если:\n - В открытый список добавили целевую клетку (в этом случае путь найден).\n - Открытый список пуст (в этом случае к целевой клетке пути не существует).\n 3. Сохраняем путь, двигаясь назад от целевой точки, проходя по указателям на родителей до тех пор, пока не дойдём до стартовой клетки.\n \n Sources:\n https://vitalissius.github.io/A-Star-Pathfinding-for-Beginners/\n \"\"\"\n\n def __init__(self, initial_state, parent=None, action=None, goal=None, h_strategy='misplaced'):\n self.initial_state = initial_state\n self.parent = parent\n self.action = action\n self.goal = goal\n self.h_strategy = h_strategy\n self.close_set_size = 0\n\n def fit(self):\n final_node, close_set_size = AstarAlgorithm.__algorithm_iter(\n init_node=Node(self.initial_state, self.parent, self.action, self.goal, self.h_strategy),\n )\n self.close_set_size = close_set_size\n return final_node.find_solution()\n\n @staticmethod\n def __algorithm_iter(init_node):\n open_list = [init_node]\n open_hash_set = {init_node.hash_value}\n close_hash_set = set()\n\n while len(open_list) > 0:\n # find node with minimum f-value\n node = min(open_list, key=lambda x: x.f)\n\n # remove node from open-list and add to close-list\n open_list.remove(node)\n open_hash_set.remove(node.hash_value)\n close_hash_set.add(node.hash_value)\n\n # generate childs of this state\n neighbors = node.generate_child()\n for n in neighbors:\n if n.hash_value in close_hash_set:\n continue\n\n if n.hash_value not in open_hash_set:\n open_list.append(n)\n open_hash_set.add(n.hash_value)\n else:\n open_node = open_list[open_list.index(n)]\n if open_node.depth > n.depth:\n open_list.remove(open_node)\n open_list.append(n)\n for node in open_list:\n if node.is_goal:\n return node, len(close_hash_set)\n return None, 0\n","sub_path":"ai-kau-course/02-lab/a_star.py","file_name":"a_star.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"565161964","text":"from flask_script import Manager, Server\nfrom flask_migrate import Migrate, MigrateCommand\nfrom main import app, db, User, Post, Comment, Tag\n\n# 通過app對象和SQLAlchemy的實例初始化了Migrate對象,然後讓遷移命令可以通過\n# manage.py db 來調用。\nmigrate = Migrate(app, db)\n\n # 把app傳給Manager,以初始化Flask Script\nmanager = Manager(app)\n # 添加一些命令。這裡運行的服務器跟通過main.py運行的普通開發服務器是一樣的。\nmanager.add_command('server', Server())\nmanager.add_command('db', MigrateCommand)\n\n # 創建一個python命令行,並且在應用上下文中執行。\n@manager.shell\ndef make_shell_context():\n # 返回的dict會告訴Flask Script在打開命令行時,進行一些默認的導入工作。\n return dict(app=app, db=db, User=User, Post=Post,\n Comment=Comment, Tag=Tag)\n # !! 每新增一個模型,都會在這邊導入並添加到dict中。\n\n'''\n* 通過manage.py來運行命列在將來是十分必要的,因為一些擴展\n 只有在Flask應用對象被創建之後才會被初始化。\n* 直接運行默認的python命令行能讓這些擴展返回錯誤\n'''\nif __name__ == '__main__':\n manager.run()\n\n\n\n\n\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434669371","text":"from typing import List\nfrom bisect import insort, bisect\nfrom collections import defaultdict\n\n\nclass Solution(object):\n def lengthOfLIS(self, nums: List[int]) -> int:\n if len(nums) <= 1:\n return len(nums)\n\n max_value = 0\n\n d = defaultdict(int)\n lst = list()\n for num in nums:\n\n index = bisect(lst, num)\n\n if index == 0:\n d[num] = 1\n\n elif index == len(lst):\n max_value += 1\n d[num] = max_value\n\n elif lst[index - 1] < num:\n d[num] = max(d[num], d[lst[index - 1]] + 1)\n max_value = max(max_value, d[num])\n else:\n d[num] = max(max_value, d[num])\n insort(lst, num)\n print(d)\n return max(d.values())\n\n\n# class Solution:\n# def lengthOfLIS(self, nums: List[int]) -> int:\n# if len(nums) <= 1:\n# return len(nums)\n#\n# dp = [1] * len(nums)\n# max_length = 1\n#\n# for i in range(1, len(nums)):\n# for j in range(0, i):\n# if nums[i] > nums[j] and dp[i] < dp[j] + 1:\n# dp[i] = dp[j] + 1\n# if dp[i] > max_length:\n# max_length = dp[i]\n#\n# return max_length\n\nfrom collections import Counter\n\n\ndef a(string):\n cd = Counter(string)\n\n if cd[\"1\"] == 0:\n if cd[\"0\"] > 2:\n return \"Impossible\"\n else:\n return string\n\n ans = \"\"\n while cd[\"0\"] > 1 and cd[\"1\"] > 0:\n ans = \"00\" + ans\n cd[\"0\"] -= 2\n ans = \"1\" + ans\n cd[\"1\"] -= 1\n if cd[\"0\"] == 1:\n if cd[\"1\"] == 0:\n return \"0\" + ans\n else:\n return \"Impossible\"\n return cd[\"1\"] * \"1\" + ans\n\n\nif __name__ == '__main__':\n print(a(\"01110\"))\n print(a(\"000\"))\n # S = Solution()\n # a = S.lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])\n # print(a)\n\n # lst = list()\n # print(bisect(lst, 1000))\n #\n # insort(lst, 2)\n # insort(lst, 10)\n # insort(lst, 1)\n # print(lst)\n #\n # print(bisect(lst, 1000))\n # print(bisect(lst, 1))\n # print(bisect(lst, 1.5))\n # print(bisect(lst, 0))\n","sub_path":"src/p0300/python3/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"251546639","text":"import logging\nimport numpy as np\nfrom keras.utils import Sequence\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\n\n\nclass MyGenerator(Sequence):\n \"\"\"\n Generator class to read examples straight from file.\n \"\"\"\n\n def __init__(self, x_filenames, y_filenames, n_channels, n_points, n_padding, batch_size):\n self.x_filenames = x_filenames\n self.y_filenames = y_filenames\n self.batch_size = batch_size\n self.n_points = n_points\n self.n_padding = n_padding\n self.n_channels = n_channels\n\n def __len__(self):\n return int(np.ceil(len(self.x_filenames) / float(self.batch_size)))\n\n def __getitem__(self, idx):\n x_batch = self.x_filenames[idx * self.batch_size: (idx + 1) * self.batch_size]\n y_batch = self.y_filenames[idx * self.batch_size: (idx + 1) * self.batch_size]\n x = np.empty((len(x_batch), self.n_points+2*self.n_padding, self.n_points+2*self.n_padding, self.n_channels))\n y = np.empty((len(y_batch), self.n_points, self.n_points, self.n_channels))\n for i, xbatch in enumerate(x_batch):\n x_tmp = np.load(xbatch)['X_train']\n for j in range(self.n_channels):\n x[i, :, :, j] = np.pad(x_tmp[:, :, j],\n ((self.n_padding, self.n_padding), (self.n_padding, self.n_padding)), 'wrap')\n y[i] = np.load(y_batch[i])['y_train']\n return x, y\n\n\nclass MyKerasCNN():\n \"\"\"\n Class of Convolutional Neural Nework (CNN).\n \"\"\"\n\n def __init__(self, n_points, activation_function):\n self.n_points = n_points\n self.n_channels = 3\n self.act_fun = activation_function\n self.model = None\n\n def deconv_cnn_model(self, loss_func, opt, n_kernels, kernel_size):\n \"\"\"Simple Deconvolutional Convolutional Neural Network.\n :param loss_func: loss function\n :param opt: optimizer\n :param n_kernels: number of kernels\n :param kernel_size: tuple of sizes of kernels\n :return: model\n \"\"\"\n n_padding = int((kernel_size[0] + kernel_size[1] - 2)/2)\n print(n_padding)\n input_shape = (2*n_padding+self.n_points, 2*n_padding+self.n_points, self.n_channels)\n model = Sequential() # Initialize model\n # Deconv CNN\n model.add(Conv2D(n_kernels, kernel_size=(1, kernel_size[0]), activation=self.act_fun,\n kernel_initializer='he_normal',\n input_shape=input_shape, padding='valid'))\n model.add(Conv2D(n_kernels, kernel_size=(kernel_size[0], 1), activation=self.act_fun,\n kernel_initializer='he_normal', padding='valid'))\n model.add(Conv2D(3, kernel_size=(kernel_size[1], kernel_size[1]), activation=self.act_fun,\n kernel_initializer='he_normal', padding='valid'))\n # compile model\n model.compile(loss=loss_func, optimizer=opt)\n logging.info(model.summary())\n self.model = model\n return self.model\n\n def deconv_cnn_noise_model(self, loss_func, opt, n_kernels, kernel_size):\n \"\"\" Deconvolutional Convolutional Neural Network joined with denoising CNN.\n :param loss_func: loss function\n :param opt: optimizer\n :param n_kernels: number of kernels\n :param kernel_size: tuple of sizes of kernels\n :return: model\n \"\"\"\n # create model\n input_shape = (int(3 / 2 * self.n_points), int(3 / 2 * self.n_points), self.n_channels)\n model = Sequential() # Initialize model\n # # Deconv CNN\n model.add(Conv2D(n_kernels, kernel_size=(1, kernel_size[0]), activation=self.act_fun, kernel_initializer='he_normal',\n input_shape=input_shape, padding='valid'))\n model.add(Conv2D(n_kernels, kernel_size=(kernel_size[0], 1), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n model.add(Conv2D(512, kernel_size=(kernel_size[1], kernel_size[1]), kernel_initializer='he_normal',\n padding='valid'))\n # Denoising CNN\n model.add(Conv2D(512, kernel_size=(1, 1), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n model.add(Conv2D(3, kernel_size=(8, 8), activation=self.act_fun, kernel_initializer='he_normal',\n padding='valid'))\n\n # compile model\n model.compile(loss=loss_func, optimizer=opt)\n logging.info(model.summary())\n self.model = model\n return self.model\n","sub_path":"nn_keras.py","file_name":"nn_keras.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"289124545","text":"# Daniel Chen\n# January 1st, 2019 is a Tuesday. Given this information and your knowledge of the days of the week, write a program that takes in a date within 2019 and returns the day of the week (Monday, Tuesday, etc...)\n# 21 March 2019\n\n# List solution because elifs are long and I don't know how to use dictionaries\nmonths = ['january', 'february', 'march', 'april', 'may', 'june', 'july', \n'august', 'september', 'october', 'november', 'december']\ndaysinmonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] # Change for leap year\ndaysinweek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n\ndef day_validation():\n try:\n global day\n day = int(input('Day (e.g.: 1): '))\n if day > 0 and day < 32:\n pass\n else:\n print('Not a valid date. Try again.')\n day_validation()\n except ValueError:\n print('Not an integer. Try again.')\n day_validation()\n except KeyboardInterrupt:\n day_validation()\n\ndef month_validation():\n global months\n global dayincurrentmonth\n global printmonth\n month = input('Month (e.g.: January or 1): ')\n if month.lower() in months:\n dayincurrentmonth = daysinmonth[months.index(month.lower())]\n printmonth = month[:1].upper() + month[1:].lower()\n elif int(month) > 0 and int(month) < 13:\n dayincurrentmonth = daysinmonth[int(month) - 1]\n printmonth = months[int(month) - 1]\n printmonth = printmonth[:1].upper() + printmonth[1:].lower()\n else:\n print('Not a month.')\n month_validation()\n\n\nmonth_validation()\nday_validation()\n\ndays = day + dayincurrentmonth\nrelevant_days = (days + 2) % 7 # Change ' + 2 ' to whatever day of the week to update (e.g.: next year would be +3)\nprint(str(daysinweek[relevant_days - 1]) + ', ' + printmonth + ' ' + str(day) + ', 2019') # Change to update year\n\n# Longer solution using elif\nmonth = input('Month (e.g.: January or 1): ')\nmonth = month.lower()\n\nday = int(input('Day (e.g.: 1): '))\n\nif day < 0 or day > 32:\n print('Not a valid date.')\n exit()\n\nif month == 'january' or int(month) == 1: # Breaks with leap years\n monthdays = 0\n printmonth = ', January '\nelif month == 'february' or int(month) == 2:\n monthdays = 31\n printmonth = ', February '\nelif month == 'march' or int(month) == 3:\n monthdays = 59\n printmonth = ', March '\nelif month == 'april' or int(month) == 4:\n monthdays = 90\n printmonth = ', April '\nelif month == 'may' or int(month) == 5:\n monthdays = 120\n printmonth = ' May '\nelif month == 'june' or int(month) == 6:\n monthdays = 151\n printmonth = ', June '\nelif month == 'july' or int(month) == 7:\n monthdays = 181\n printmonth = ', July '\nelif month == 'august' or int(month) == 8:\n monthdays = 212\n printmonth = ', August '\nelif month == 'september' or int(month) == 9:\n monthdays = 243\n printmonth = ', September '\nelif month == 'october' or int(month) == 10:\n monthdays = 273\n printmonth = ', October '\nelif month == 'november' or int(month) == 11:\n monthdays = 304\n printmonth = ', November '\nelif month == 'december' or int(month) == 12:\n monthdays = 334\n printmonth = ', December '\nelse:\n print('Not a valid month.')\n exit()\n\ndays = monthdays + day\nrelevant_days = (days + 2) % 7 - 1\nif relevant_days == 0:\n print('Sunday' + printmonth + str(day) + ', 2019') # Change to update year\nelif relevant_days == 1:\n print('Monday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 2:\n print('Tuesday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 3:\n print('Wednesday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 4:\n print('Thursday' + printmonth + str(day) + ', 2019')\nelif relevant_days == 5:\n print('Friday' + printmonth + str(day) + ', 2019')\nelse:\n print('Saturday' + printmonth + str(day) + ', 2019')","sub_path":"Scripting/logicchallenge.py","file_name":"logicchallenge.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"395044291","text":"\"\"\"\nTheJMGroup spider created on the top of ATSSpider\n\nscrapy crawl thejmgroup -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.thejmgroup.com/job-search\"\n\nSample URL:\n https://www.thejmgroup.com/job-search\n\"\"\"\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, RemoveBadElements, md5_hash\n\n\nclass TheJMGroup(ATSSpider):\n\n name = 'thejmgroup'\n\n def parse(self, response):\n sel = Selector(response)\n # set expected job count\n if not self.expected_job_count_set:\n expected_count = sel.xpath(\n '//div/h6[@class=\"job-count\"]/text()'\n ).extract()\n if expected_count:\n self.expected_job_count = expected_count[0]\n for href in sel.xpath(\n '//div/div/div/div[@class=\"list-box\"]/h4/a/@href'\n ).extract():\n yield Request(\n callback=self.parse_job_callback(),\n url=href\n )\n\n # pagination\n next_page = filter(None, sel.xpath(\n '//div[contains(@class, \"pagination-btm\")]/a[@class=\"next-arrow right\"]/@href'\n ).extract())\n if next_page:\n yield Request(\n callback=self.parse,\n url=next_page[0]\n )\n\n def parse_job(self, response):\n \"\"\"\n Extract all required information.\n \"\"\"\n sel = Selector(response)\n\n loader = BrightcorpItemLoader(selector=sel)\n loader.add_xpath(\n 'title',\n '//div/h1[@class=\"job-title\"]/text()'\n )\n loader.add_xpath(\n 'location',\n '//div/span[@class=\"location-icon\"]/following-sibling::a[1]/text()'\n )\n loader.add_value(\n 'referencenumber',\n response.url,\n md5_hash,\n Prefix('%s-' % self.name)\n )\n loader.add_value('url', response.url)\n loader.add_xpath(\n 'description',\n '//div/h2[contains(text(), \"Job Description\")]/..',\n RemoveBadElements(['img', ])\n )\n loader.add_xpath(\n 'baseSalary',\n '//div[contains(text(), \"salary-text\")]/a/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//div/span[@class=\"detail-job-type-icon\"]/following-sibling::a[1]/text()'\n )\n loader.add_value('apply_url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/thejmgroup.py","file_name":"thejmgroup.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20162824","text":"from BaseModel import *\nimport os\nfrom Endereco import *\n\nclass Empresa(BaseModel):\n nome= CharField()\n cnpj = CharField()\n ehFornecedor = IntegerField()\n email = CharField()\n endereco = ForeignKeyField(Endereco)\n def __str__ (self):\n return \"Empresa \"+self.nome+\" com CNPJ \"+self.cnpj+\" localizada em \"+str(self.endereco)+\" pode ser contada através do e-mail \"+self.email+\". \"+ehFornecedor(self.ehFornecedor)\n\ndef ehFornecedor(valor):\n if valor==1:\n return \"Essa empresa é fornecedora\"\n else: \n return \"Essa empresa não é fornecedora\"\n\nif __name__ == '__main__':\n \n if os.path.exists(arq):\n os.remove(arq)\n\n try:\n db.connect()\n db.create_tables([Pais,Estado,Cidade,Endereco,Empresa])\n except OperationalError as e:\n print(\"Erro ao criar tabela: \"+str(e))\n\n pais1 = Pais.create(nomePais=\"Brasil\")\n pais2 = Pais.create(nomePais=\"Estados Unidos\")\n\n estado1 = Estado.create(nomeEstado=\"Santa Catarina\", pais = pais1)\n estado2 = Estado.create(nomeEstado=\"Rio Grande do Sul\", pais = pais1)\n estado3 = Estado.create(nomeEstado=\"New York\", pais = pais2)\n estado4 = Estado.create(nomeEstado=\"Ohio\", pais = pais2)\n\n cidade1 = Cidade.create(nomeCidade=\"Indaial\", estado = estado1)\n cidade2 = Cidade.create(nomeCidade=\"Blumenau\", estado = estado1)\n cidade3 = Cidade.create(nomeCidade=\"Santa Maria\", estado = estado2)\n cidade4 = Cidade.create(nomeCidade=\"Buffalo\", estado = estado3)\n cidade5 = Cidade.create(nomeCidade=\"Toronto\", estado = estado4)\n\n endereco1 = Endereco.create(codigo=1, nomeBairro=\"Salto do Norte\", nomeRua=\"Rua Benardino\", numero=144, cidade=cidade2)\n endereco2 = Endereco.create(codigo=2, nomeBairro=\"Mulde\", nomeRua=\"Rua Boa Esperança\", numero=100, cidade=cidade1)\n endereco3 = Endereco.create(codigo=2, nomeBairro=\"Rosedale\", nomeRua=\"Main Street\", numero=98, cidade=cidade5)\n endereco4 = Endereco.create(codigo=2, nomeBairro=\"Manchers\", nomeRua=\"3 Avenue\", numero=14, cidade=cidade4)\n\n empresa1 = Empresa.create(nome=\"Empresa 1\", cnpj=\"01010010101\", ehFornecedor=1, email=\"teste.teste@gmail.com\", endereco=endereco4)\n empresa2 = Empresa.create(nome=\"Empresa 2\", cnpj=\"01010010122\", ehFornecedor=0, email=\"teste1.teste1@gmail.com\", endereco=endereco1)\n empresa3 = Empresa.create(nome=\"Empresa 3\", cnpj=\"01010010133\", ehFornecedor=1, email=\"teste2.teste2@gmail.com\", endereco=endereco2)\n\n todos = Empresa.select()\n for empresa in todos:\n print(empresa)\n ","sub_path":"Trabalho2/Empresa.py","file_name":"Empresa.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238205222","text":"#\n# OBJECTIVE - to create a list of dictionaries, and not add the dictionary to the\n# list if it is missing any of two specific keys.\n#\n# USE CASE - use findings to create a script that will take an artifactory repository\n# export and walk the export directory searching for .pom or .jar files, and when\n# found get its relative path. Using those values, create a curl command to upload\n# them to another instance of artifactory.\n#\n\nartifactSetList = []\n\n# dict of three\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\1.0\", \"pomFile\" : \"Toe-1.0.pom\", \"jarFile\" : \"Toe-1.0.jar\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of two - pom\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\2.0\", \"pomFile\" : \"Toe-2.0.pom\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of two - jar\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\3.0\", \"jarFile\" : \"Toe-3.0.jar\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\n# dict of one\nartifactSet = {\"deployPath\" : \"\\\\tic\\\\tac\\\\toe\\\\4.0\"}\nif 'jarFile' or 'pomFile' in artifactSet:\n artifactSetList.append(artifactSet)\n print(len(artifactSet))\n\nprint(artifactSetList)\n\nfor s in artifactSetList:\n for key in s:\n print(key + ' \\t ' + s[key])\n","sub_path":"py/learnDict.py","file_name":"learnDict.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"314007507","text":"from ai import AI\nimport random\nimport math\nimport collections\nfrom ai.mctsstate import MCTSState, define_neighbours\nfrom ai.mcts import MCTS\n\nclass SD_StupidAI(AI):\n \"\"\"\n Smart drafting : plays randomly like the stupid AI, except for the drafting (placement) phase where it uses MCTS with UCT to find the best countries.\n \"\"\"\n\n def start(self):\n define_neighbours(self.player.world)\n self.mcts = MCTS()\n\n def initial_placement(self, empty, remaining):\n if empty:\n terri = {t.name: (None if t.owner == None else t.owner.name) for t in self.world.territories.values()}\n action = self.mcts.UCTSearch(MCTSState(self.player, terri))\n return action\n else:\n t = random.choice(list(self.player.territories))\n return t\n\n def attack(self):\n for t in self.player.territories:\n for a in t.connect:\n if a.owner != self.player:\n if t.forces > a.forces:\n yield (t, a, None, None)\n\n def reinforce(self, available):\n border = [t for t in self.player.territories if t.border]\n result = collections.defaultdict(int)\n for i in range(available):\n t = random.choice(border)\n result[t] += 1\n return result\n","sub_path":"ai/sd_stupid.py","file_name":"sd_stupid.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"378099726","text":"# Definition for singly-linked list:\n# class ListNode(object):\n# def __init__(self, x):\n# self.value = x\n# self.next = None\n#\ndef rearrangeLastN(l, n):\n head = l\n tail = l\n while(n != 0):\n head = head.next\n n -= 1\n \n if head == None or head == l:\n return l\n while(head.next != None):\n tail = tail.next\n head = head.next\n \n \n list_head = tail.next\n list_tail = head\n tail.next = None\n list_tail.next = l\n return list_head\n ","sub_path":"Interviews Practice/Linked List/rearrangeLastN.py","file_name":"rearrangeLastN.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"305430109","text":"from prj001.models.geninfo import GeneralInfo\n\n\ndef get_group_info(sf=None, obj=None, type=None, request=None):\n '''返回同组数据'''\n if not type:\n of_groups = sf.request.user.groups.all()\n else:\n of_groups = request.user.groups.all()\n users = [group.user_set.all() for group in of_groups]\n gen_objects = None\n\n _ID = set()\n for u in users:\n for user in u:\n _ID.add(user.id)\n\n if not _ID:\n _ID.add(sf.request.user.id)\n\n if not type:\n gen_objects = obj.objects.filter(owner__in=_ID).order_by('-serial')\n return (gen_objects, _ID)\n\n\ndef get_all_group_info(obj=None, is_not_info=None):\n '''返回所有的信息(包括不同组)'''\n if is_not_info and obj:\n return obj.objects.all().order_by('-pk')\n if obj:\n return obj.objects.all().order_by('-serial')\n return GeneralInfo.objects.all().order_by('-serial')\n","sub_path":"prj001/utils/group_info.py","file_name":"group_info.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"141491690","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n' 项目初始化'\nimport functools\nimport hashlib\nimport json\nimport re\n\nimport flask\nimport werkzeug\nimport yaml\n\nfrom flask_cachecontrol import FlaskCacheControl\nfrom werkzeug.exceptions import PreconditionRequired\n\n__author__ = 'Andrew Wen'\n\n\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\nfrom flask_cors import CORS\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_mail import Mail\nfrom flask_moment import Moment\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\nfrom flasgger import Swagger\n\nfrom config import config\n\n\nbootstrap = Bootstrap()\nmail = Mail()\nmoment = Moment()\ndb = SQLAlchemy()\n\n\nlogin_manager = LoginManager()\nlogin_manager.session_protection = 'strong'\nlogin_manager.login_view = 'auth.login'\nlogin_manager.login_message = u\"请登录系统后进行操作!\"\nlogin_manager.login_message_category = \"info\"\n\n\n\n\n\ndef create_app(config_name):\n\n app = Flask(__name__)\n\n CORS(app, supports_credentials=True)\n\n app.config.from_object(config[config_name])\n config[config_name].init_app(app)\n\n bootstrap.init_app(app)\n mail.init_app(app)\n moment.init_app(app)\n db.init_app(app)\n db.app = app\n\n toolbar = DebugToolbarExtension()\n toolbar.init_app(app)\n\n login_manager.init_app(app)\n\n init_swagger(app)\n\n\n\n\n # 蓝图注册\n from pyfw.system import system_blue\n app.register_blueprint(system_blue, url_prefix='/api/v1/common')\n\n\n\n return app\n\n\ndef init_swagger(app_c):\n \"\"\"\n 初始化swagger文档生成\n 语法参考 : https://huangwenchao.gitbooks.io/swagger/content/\n :param app_c:\n :return:\n \"\"\"\n\n\n\n # 获取版本\n version = ''\n with open('./pyfw/__init__.py') as f:\n version = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]', f.read(), re.MULTILINE).group(1)\n\n template = None\n\n with open('./swagger/template.yaml',encoding='utf-8') as f:\n\n template = yaml.load(f)\n\n\n template[\"info\"][\"version\"]=version\n # api文档模板\n # template = {\n # \"swagger\": \"2.0\",\n # \"info\": {\n # \"title\": \"基础框架api\",\n # \"description\": \"本文档描述基础开发框架相关api\",\n # \"version\": version\n # }\n # #\"host\": \"mysite.com\", # overrides localhost:500\n # #\"basePath\": \"/api\", # base bash for blueprint registration\n # # \"schemes\": [\n # # \"http\",\n # # \"https\"\n # # ],\n # # \"operationId\": \"getmyData\",\n # # \"definitions\": {\n # # \"Palette\": {\n # # \"type\": \"object\",\n # # \"properties\": {\n # # \"palette_name\": {\n # # \"type\": \"array\",\n # # \"items\": {\n # # \"$ref\": \"#/definitions/Color\"\n # # }\n # # }\n # # }\n # # },\n # # \"Color\": {\n # # \"type\": \"string\"\n # # }\n # # }\n # }\n\n #print(template)\n template[\"definitions\"][\"user\"]={\n \"type\": \"object\",\n \"properties\": {\n \"palette_name\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/definitions/Color\"\n }\n }\n }\n }\n\n swagger = Swagger(app_c, template=template)\n\n return app_c","sub_path":"code/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":3402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"63275363","text":"import discord\nimport asyncio\nimport json\nfrom discord.ext.commands import Bot\nfrom discord.ext import commands\nimport platform\nimport dbInterface\n\n# Here you can modify the bot's prefix and description and wether it sends help in direct messages or not.\ndiscordBot = Bot(description=\"TestBot\", command_prefix=\"!\", pm_help=True)\nUsers = dict()\n\n\ndef getToken():\n data = json.load(open('token.json'))\n return data[\"token\"]\n\n\n# This is what happens everytime the bot launches.\n@discordBot.event\nasync def on_ready():\n print('Logged in as')\n print(discordBot.user.name)\n print(discordBot.user.id)\n\n for member in discordBot.get_all_members():\n Users[member.name] = dbInterface.History(member.name, member.id)\n Users[member.name].logMessage(\"ASDF\")\n\n\n@discordBot.event\nasync def on_message(message):\n if message.author == discordBot.user:\n return\n\n Users[message.author.name].logMessage(message.content)\n\n await discordBot.process_commands(message)\n\n\n@discordBot.command()\nasync def ping(*args):\n await discordBot.say(\":ping_pong: Pong!\")\n\n\n@discordBot.command()\nasync def pong(*args):\n await discordBot.say(\":ping_pong: Ping!\")\n\n\n@discordBot.command(pass_context=True)\nasync def history(ctx, num):\n await discordBot.say(Users[ctx.message.author.name].getLastMessages(num))\n\n\ndiscordBot.run(getToken())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103046412","text":"# version code c2eb1c41017f+\n# Please fill out this stencil and submit using the provided submission script.\n\nfrom resources.matutil import *\nfrom resources.GF2 import one\nfrom resources.vecutil import zero_vec\nfrom resources.echelon import transformation\n\n\n## 1: (Problem 7.9.2) Recognizing Echelon Form\n# Write each matrix as a list of row lists\n\n# Definition 7.1.1: An m × n matrix A is in echelon form if it satisfies the following condition: for any row, if that\n# row’s first nonzero entry is in position k then every previous row’s first nonzero entry is in some position less\n# than k.\n\n# If a row of a matrix in echelon form is all zero then every subsequent row must also be all zero...\n\nechelon_form_1 = [[1, 2, 0, 2, 0],\n [0, 1, 0, 3, 4],\n [0, 0, 2, 3, 4],\n [0, 0, 0, 2, 0],\n [0, 0, 0, 0, 4]]\n\nechelon_form_2 = [[0, 4, 3, 4, 4],\n [0, 0, 4, 2, 0],\n [0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0]]\n\nechelon_form_3 = [[1, 0, 0, 1],\n [0, 0, 0, 1],\n [0, 0, 0, 0]]\n\nechelon_form_4 = [[1, 0 ,0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 0],\n [0, 0, 0, 0]]\n\n\n\n## 2: (Problem 7.9.3) Is it echelon?\ndef is_echelon(A):\n '''\n Input:\n - A: a list of row lists\n Output:\n - True if A is in echelon form\n - False otherwise\n Examples:\n >>> is_echelon([[1,1,1],[0,1,1],[0,0,1]])\n True\n >>> is_echelon([[0,1,1],[0,1,0],[0,0,1]])\n False\n >>> is_echelon([[1,1]])\n True\n >>> is_echelon([[1]])\n True\n >>> is_echelon([[1],[1]])\n False\n >>> is_echelon([[0]])\n True\n >>> is_echelon([[0],[1]])\n False\n >>> is_echelon([[0, 0], [1, 0], [0, 1]])\n False\n '''\n first_non_zero_idx_per_row = []\n cols = len(A[0])\n rows = len(A)\n\n for irow in range(rows):\n row_non_zero_entry_idx = None\n for icol in range(cols):\n v = A[irow][icol]\n if v != 0:\n row_non_zero_entry_idx = icol\n break\n first_non_zero_idx_per_row.append(row_non_zero_entry_idx)\n if irow > 0:\n prior_row_non_zero_entry_idx = first_non_zero_idx_per_row[irow - 1]\n if row_non_zero_entry_idx != None and (prior_row_non_zero_entry_idx == None or \\\n row_non_zero_entry_idx <= prior_row_non_zero_entry_idx):\n return False\n\n return True\n\n\n# NOTE: for 7.9.4 and 7.9.5 I used solver.solve. Remember to take the result and multiply the matrix to check\n# e.g. M = listlist2mat(...), V = list2vec([...]), b = solve(M, V), M * b - V (is almost zero)\n\n## 3: (Problem 7.9.4) Solving with Echelon Form: No Zero Rows\n# Give each answer as a list\n\nechelon_form_vec_a = [1, 0, 3, 0]\nechelon_form_vec_b = [-3, 0, -2, 3]\nechelon_form_vec_c = [-5, 0, 2, 0, 2]\n\n\n## 4: (Problem 7.9.5) Solving with Echelon Form\n# If a solution exists, give it as a list vector.\n# If no solution exists, provide \"None\" (without the quotes).\n\nsolving_with_echelon_form_a = None\nsolving_with_echelon_form_b = [21, 0, 2, 0, 0]\n\n\n## 5: (Problem 7.9.6) Echelon Solver\ndef echelon_solve(rowlist, label_list, b):\n '''\n Input:\n - rowlist: a list of Vecs\n - label_list: a list of labels establishing an order on the domain of\n Vecs in rowlist\n - b: a vector (represented as a list)\n Output:\n - Vec x such that rowlist * x is b\n >>> D = {'A','B','C','D','E'}\n >>> U_rows = [Vec(D, {'A':one, 'E':one}), Vec(D, {'B':one, 'E':one}), Vec(D,{'C':one})]\n >>> b_list = [one,0,one]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec({'B', 'C', 'A', 'D', 'E'},{'B': 0, 'C': one, 'A': one})\n True\n >>> U_rows = [ \\\n Vec(D, {'A': one, 'C': one, 'D': one}), \\\n Vec(D, {'B': one, 'E': one}), \\\n Vec(D, {'C': one, 'E': one}), \\\n Vec(D, {'E': one}) \\\n ]\n >>> b_list = [one, 0, one, one]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec(D,{'A': one, 'B': one, 'E': one})\n True\n >>> U_rows = [ \\\n Vec(D, {'A': one, 'B': one, 'D': one}), \\\n Vec(D, {'B': one, 'D': one, 'E': one}), \\\n Vec(D, {'C': one, 'E': one}), \\\n Vec(D, {}) \\\n ]\n >>> b_list = [one, 0, one, 0]\n >>> cols = ['A', 'B', 'C', 'D', 'E']\n >>> echelon_solve(U_rows, cols, b_list) == Vec(D,{'A': one, 'C': one})\n True\n '''\n x = zero_vec(rowlist[0].D)\n b_rev = list(reversed(b))\n for ixrow, row in enumerate(reversed(rowlist)):\n non_zero_labels = [label for label in label_list if row[label] != 0]\n if not len(non_zero_labels): continue\n x[non_zero_labels[0]] = b_rev[ixrow] - sum([x[label] * row[label] for label in label_list])\n # print(\"ixrow: {0}\\tnon_zero_labels: {1}\\tb: {2}\\tsum: {3}\\trow: {4}\\tx: {5}\".format(ixrow, non_zero_labels, b[ixrow], sum([x[label] * one for label in non_zero_labels[1:]]), repr(row), repr(x)))\n return x\n\n\n## 6: (Problem 7.9.7) Solving General Matrices via Echelon\ndef solve(A, b):\n \"\"\"\n :param A: Matrix R x C\n :param b: Vector R\n :return: Vector C 'x' solving Ax=b\n >>> M = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), { \\\n ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one, \\\n ('b', 'A'): one, ('b', 'D'): one, \\\n ('c', 'A'): one, ('c', 'B'): one, ('c', 'C'): one, ('c', 'D'): one, \\\n ('d', 'C'): one, ('d', 'D'): one \\\n })\n >>> v = Vec(M.D[0], {'a': one, 'c': one})\n >>> solve(M, v)\n \"\"\"\n M = transformation(A)\n U = M*A\n col_label_list = sorted(A.D[1])\n U_rows_dict = mat2rowdict(U)\n row_list = [U_rows_dict[i] for i in sorted(U_rows_dict)]\n # return echelon_solve(row_list,col_label_list, M*b)\n # print(row_list, col_label_list, repr(M * b))\n return row_list, col_label_list, M * b\n\n\nM = Mat(({'a', 'b', 'c', 'd'}, {'A', 'B', 'C', 'D'}), {\n ('a', 'A'): one, ('a', 'B'): one, ('a', 'D'): one,\n ('b', 'A'): one, ('b', 'D'): one,\n ('c', 'A'): one, ('c', 'B'): one, ('c', 'C'): one, ('c', 'D'): one,\n ('d', 'C'): one, ('d', 'D'): one\n})\nv = Vec(M.D[0], {'a': one, 'c': one})\nechelon_solve_args = solve(M, v)\n\nrow_list = echelon_solve_args[0] # Provide as a list of Vec instances\nlabel_list = echelon_solve_args[1] # Provide as a list\nb = [echelon_solve_args[2][label] for label in sorted(echelon_solve_args[2].D)] # Provide as a list of GF(2) values\n\n\nA7 = Mat(({'a', 'b', 'c', 'd', 'e'}, {'A', 'B', 'C', 'D', 'E'}), {\n ('a', 'D'): one,\n ('b', 'D'): one, ('b', 'E'): one,\n ('c', 'A'): one, ('c', 'D'): one,\n ('d', 'A'): one, ('d', 'E'): one,\n ('e', 'A'): one\n})\nM7 = Mat(({0, 1, 2, 3, 4}, A7.D[0]), {\n (0, 'c'): one,\n (1, 'a'): one,\n (2, 'a'): one, (2, 'b'): one,\n (3, 'b'): one, (3, 'c'): one, (3, 'd'): one,\n (4, 'a'): one, (4, 'c'): one, (4, 'e'): one\n})\nMA7 = Mat((M7.D[0], A7.D[1]), {\n (0, 'A'): one, (0, 'D'): one,\n (1, 'D'): one,\n (2, 'E'): one\n})\ndef rows_of_M_times_A_equaling_zero_vec(M, A):\n \"\"\"\n Determine rows u of M such that u * A = 0 (Note that these are vectors in the null space of the transpose A^T)\n :param M: P (rows) x Q (cols) matrix\n :param A: R x P matrix\n :return: set row numbers of M\n >>> rows_of_M_times_A_equaling_zero_vec(M7, A7)\n {3, 4}\n >>> rows_of_M_times_A_equaling_zero_vec(M8, A8)\n {4}\n \"\"\"\n zv = zero_vec(A.D[1])\n return {k for k, v in mat2rowdict(M).items() if v * A == zv}\n\n\n## 7: (Problem 7.9.8) Nullspace A\nnull_space_rows_a = rows_of_M_times_A_equaling_zero_vec(M7, A7) # Put the row numbers of M from the PDF\n\n\nA8 = Mat(({'a', 'b', 'c', 'd', 'e'}, {'A', 'B', 'C', 'D', 'E'}), {\n ('a', 'D'): one,\n ('b', 'D'): one, ('b', 'E'): one,\n ('c', 'A'): one, ('c', 'D'): one,\n ('d', 'A'): one, ('d', 'B'): one, ('d', 'C'): one, ('d', 'E'): one,\n ('e', 'A'): one, ('e', 'D'): one\n})\nM8 = Mat(({0, 1, 2, 3, 4}, A7.D[0]), {\n (0, 'c'): one,\n (1, 'c'): one, (1, 'd'): one,\n (2, 'a'): one,\n (3, 'a'): one, (3, 'b'): one,\n (4, 'c'): one, (4, 'e'): one\n})\n## 8: (Problem 7.9.9) Nullspace B\nnull_space_rows_b = rows_of_M_times_A_equaling_zero_vec(M8, A8) # Put the row numbers of M from the PDF\n\n","sub_path":"grading/Gaussian_Elimination_problems.py","file_name":"Gaussian_Elimination_problems.py","file_ext":"py","file_size_in_byte":8366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"165827441","text":"\nclass Word:\n word = '' # :: String\n sectionDefinition = [] # :: [Section]\n relatedForms = [] # :: [String]\n synonyms = [] # :: Synonyms\n nearbyWords = [] # :: [String]\n\n def __repr__(self):\n out = \"[Word]\\n\" + self.word + \"\\n\"\n\n out += \"[Definition]\\n\"\n for i in range(0, len(self.sectionDefinition)):\n out += str(self.sectionDefinition[i])\n\n out += \"[Related Forms]\\n\"\n row_width = 3\n counter = 0\n for i in range(0, len(self.relatedForms)):\n out += str(self.relatedForms[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n\n out += \"\\n\"\n out += \"[Synonyms]\\n\"\n row_width = 3\n counter = 0\n for i in range(0, len(self.synonyms)):\n out += str(self.synonyms[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n\n out += \"\\n\"\n out += \"[Nearby Words]\\n\"\n for i in range(0, len(self.nearbyWords)):\n out += str(self.nearbyWords[i]) + \",\\t\"\n counter += 1\n if(counter >= row_width):\n out += '\\n'\n counter = 0\n return out\n\n def __init__(self, word, section_definition, related_forms, synonyms, nearby_words):\n self.word = word\n self.relatedForms = related_forms\n self.synonyms = synonyms\n self.sectionDefinition = section_definition\n self.nearbyWords = nearby_words\n\n def __eq__(self, other):\n \"\"\"Overrides the default implementation\"\"\"\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n return False\n\n def __gt__(self, other):\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n\n def __lt__(self, other):\n if isinstance(other, str):\n return self.word == other\n elif isinstance(other, Word):\n return self.word == other.word\n\n # def __gt__(self, other):\n # s_len = len(self.word)\n # o_len = len(other.word)\n # min_len = min(s_len, o_len)\n # for i in range(0, min_len):\n # cs = ord(self.word[i])\n # co = ord(other.word[i])\n # if(cs > co):\n # return True\n # elif(cs < co):\n # return False\n #\n # return s_len > o_len\n #\n # def __lt__(self, other):\n # s_len = len(self.word)\n # o_len = len(other.word)\n # min_len = min(s_len, o_len)\n # for i in range(0, min_len):\n # cs = ord(self.word[i])\n # co = ord(other.word[i])\n # if (cs < co):\n # return True\n # elif (cs > co):\n # return False\n #\n # return s_len < o_len\n\n def addSection(self, partofspeech, section):\n if(section != []):\n section = Section(partofspeech, section)\n self.sectionDefinition.append(section)\n","sub_path":"Word.py","file_name":"Word.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339620495","text":"import random\r\nDNA='ATACAG'\r\nw='ATCG'\r\ns=''\r\nN=random.randint(5,10)\r\nfor j in range(N):\r\n a=random.sample(w,1)\r\n s=s+a[0]\r\nDNA=s\r\nprint(DNA)\r\nA=[5,5,5,0] #CHNO\r\nT=[5,6,2,2]\r\nC=[4,5,3,1]\r\nG=[5,5,5,1]\r\nDNAf=[15,31,3,13,2]\r\nx1=[0,0,0,0]\r\ndef formula1(DNA1):\r\n global x1;\r\n An=0\r\n Tn=0\r\n Cn=0\r\n Gn=0\r\n for i in range(len(DNA1)):\r\n if(DNA1[i]=='A'):\r\n An=An+1\r\n if(DNA1[i]=='T'):\r\n Tn=Tn+1\r\n if(DNA1[i]=='C'):\r\n Cn=Cn+1\r\n if(DNA1[i]=='G'):\r\n Gn=Gn+1\r\n\r\n x1=[An, Tn ,Cn,Gn,len(DNA1)]\r\n\r\n\r\n#print(x1)\r\ndef Molecules():\r\n global A,T,C,G,DNAf\r\n #print(A)\r\n C1=x1[0]*A[0]+x1[1]*T[0]+x1[2]*C[0]+x1[3]*G[0]+x1[4]*DNAf[0]\r\n H=x1[0]*A[1]+x1[1]*T[1]+x1[2]*C[1]+x1[3]*G[1]+x1[4]*DNAf[1]\r\n N=x1[0]*A[2]+x1[1]*T[2]+x1[2]*C[2]+x1[3]*G[2]+x1[4]*DNAf[2]\r\n O=x1[0]*A[3]+x1[1]*T[3]+x1[2]*C[3]+x1[3]*G[3]+x1[4]*DNAf[3]\r\n P=x1[4]*DNAf[4]\r\n HC='C'+str(C1)+'H'+str(H)+'N'+str(N)+'-O_'+str(O)+'P'+str(P)\r\n print('DNA Molecule ', HC)\r\nflag=0\r\nNAME=\"HARISH RAVI\"\r\nprint('Bio Lesson')\r\nprint('Proteins make amino acids.There are about 20 Amino Acids, three base pairs code for an amino acid which can be represented with A-Z and 6 extra dummy acids. An extra base pair X has to be added to code for some letters as some codes are redundant and blanks are hard to find. Eg : the triplet ATA codes for I, there is ATCG base pairs and complementary in where A=T and C=G double strand. RNA has U instead of T.')\r\nprint('There is 3D folding and active sites which is great')\r\n\r\nw='ATCG'\r\nflag=0\r\ndef translate(seq): \r\n \r\n table = { \r\n 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', \r\n 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', \r\n 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', \r\n 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', \r\n 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', \r\n 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', \r\n 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', \r\n 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', \r\n 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', \r\n 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', \r\n 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', \r\n 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', \r\n 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', \r\n 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', \r\n 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', \r\n 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', \r\n } \r\n protein =\"\" \r\n if len(seq)%3 == 0: \r\n for i in range(0, len(seq), 3): \r\n codon = seq[i:i + 3] \r\n protein+= table[codon] \r\n return protein \r\n\r\ndef revtranslate(seq): \r\n \r\n table = { \r\n 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', \r\n 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', \r\n 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', \r\n 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', \r\n 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', \r\n 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', \r\n 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', \r\n 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', \r\n 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', \r\n 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', \r\n 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', \r\n 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', \r\n 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', \r\n 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', \r\n 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', \r\n 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W',\r\n 'XXX':' ', 'ATX':'U','AXT':'O','XAG':'X','XTG':'B',\r\n 'XTA':'J','XTA':'J','XGA':'Z','.':'.'\r\n } \r\n DNA =\"\" \r\n table2 = {v: k for k, v in table.items()}\r\n for i in range(0, len(seq)): \r\n \r\n DNA+= table2[seq[i]] \r\n return DNA\r\ndef RNA(seq): \r\n \r\n table3 = { \r\n 'A':'U','T':'A','C':'G','G':'C','X':'X','.':'.'\r\n } \r\n RNA =\"\" \r\n \r\n for i in range(0, len(seq)): \r\n \r\n RNA+= table3[seq[i]] \r\n return RNA\r\n\r\n\r\nprotein=NAME\r\nprint('Protein ',protein,'length ', len(protein))\r\nDNA=revtranslate(protein)\r\nRNA=RNA(DNA)\r\nprint('DNA ',DNA, 'length ', len(DNA))\r\n\r\nprint('RNA ',RNA,'length ', len(RNA))\r\n\r\nformula1(DNA)\r\nMolecules()\r\n\r\n\r\n","sub_path":"DNAAt5.py","file_name":"DNAAt5.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"388820681","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('avatar', '0001_initial'),\n ('quiz', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Challenge',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('request_datetime', models.DateTimeField(default=datetime.datetime.now, blank=True)),\n ('status', models.IntegerField(default=1, choices=[(1, b'Requested'), (2, b'Accepted'), (3, b'Rejected'), (4, b'Finished')])),\n ('challengee', models.ForeignKey(related_name='challenge_challengee', to='avatar.Avatar')),\n ('challenger', models.ForeignKey(related_name='challenge_challenger', to='avatar.Avatar')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeQuestion',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('challenge', models.ForeignKey(to='challenge.Challenge')),\n ('question', models.ForeignKey(to='quiz.Question')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeResult',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('start_datetime', models.DateTimeField(default=datetime.datetime.now, blank=True)),\n ('completion_datetime', models.DateTimeField(null=True)),\n ('total_time', models.IntegerField(null=True)),\n ('correct_rate', models.FloatField(null=True, blank=True)),\n ('winner', models.NullBooleanField()),\n ('challenge', models.ForeignKey(to='challenge.Challenge')),\n ('participant', models.ForeignKey(to='avatar.Avatar')),\n ],\n ),\n migrations.CreateModel(\n name='ChallengeWaitlist',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True)),\n ('type', models.CharField(max_length=100)),\n ('request_datetime', models.DateTimeField()),\n ('challenger', models.ForeignKey(to='avatar.Avatar')),\n ],\n ),\n migrations.AlterUniqueTogether(\n name='challengeresult',\n unique_together=set([('challenge', 'participant')]),\n ),\n ]\n","sub_path":"challenge/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308793853","text":"# -*- coding: utf-8 -*-\r\n\r\ndef get_current_semestar(cursor):\r\n query = \"SELECT * FROM trenutni_semestar\"\r\n cursor.execute(query)\r\n for (id_semestra, skolska_godina, tip_semestra) in cursor:\r\n return {\"skolska_godina\" : skolska_godina,\r\n \"tip_semestra\" : tip_semestra}\r\n\r\n\r\nGROUP_ID_BAZA = {}\r\ndef get_group_id(cursor, broj_grupe, trenutni_semestar):\r\n if broj_grupe in GROUP_ID_BAZA:\r\n return GROUP_ID_BAZA[broj_grupe]\r\n\r\n query = \"SELECT id_grupe FROM grupa \" \\\r\n \"JOIN semestar ON grupa.id_semestra = semestar.id_semestra AND grupa.broj = %s AND semestar.školska_godina= %s AND \" \\\r\n \"semestar.tip_semestra = %s\"\r\n cursor.execute(query, (broj_grupe, trenutni_semestar['skolska_godina'], trenutni_semestar['tip_semestra']))\r\n for (id_grupe, ) in cursor:\r\n GROUP_ID_BAZA[broj_grupe] = id_grupe\r\n return id_grupe\r\n\r\n\r\nSEMESTAR_ID_BAZA = {}\r\ndef get_semestar_id(cursor, broj_grupe, trenutni_semestar):\r\n if broj_grupe in SEMESTAR_ID_BAZA:\r\n return SEMESTAR_ID_BAZA[broj_grupe]\r\n if broj_grupe[0] == '1':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 1\r\n else:\r\n broj_semestra = 2\r\n elif broj_grupe[0] == '2':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 3\r\n else:\r\n broj_semestra = 4\r\n elif broj_grupe[0] == '3':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 5\r\n else:\r\n broj_semestra = 6\r\n elif broj_grupe[0] == '4':\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = 7\r\n else:\r\n broj_semestra = 8\r\n else: #Ponovci\r\n if trenutni_semestar['tip_semestra'] == 'zimski':\r\n broj_semestra = -1\r\n else:\r\n broj_semestra = -2\r\n\r\n query = \"SELECT id_semestra FROM semestar \" \\\r\n \"WHERE školska_godina = %s AND broj_semestra = %s\"\r\n cursor.execute(query, (trenutni_semestar['skolska_godina'], broj_semestra))\r\n for (id_semestra, ) in cursor:\r\n SEMESTAR_ID_BAZA[broj_grupe] = id_semestra\r\n return id_semestra\r\n\r\n\r\nTEACHER_ID_BAZA = {}\r\ndef get_teacher_id(cursor, ime, prezime, tip):\r\n if (ime, prezime, tip) in TEACHER_ID_BAZA:\r\n return TEACHER_ID_BAZA[(ime, prezime, tip)]\r\n query = \"SELECT id_nastavnika FROM nastavnik \" \\\r\n \"WHERE nastavnik.ime = %s AND nastavnik.prezime = %s AND nastavnik.tip = %s\"\r\n cursor.execute(query, (ime, prezime, tip))\r\n for (id_nastavnika, ) in cursor:\r\n TEACHER_ID_BAZA[(ime, prezime, tip)] = id_nastavnika\r\n return id_nastavnika\r\n\r\nCOURSE_ID_BAZA = {}\r\ndef get_course_id(cursor, naziv):\r\n if naziv in COURSE_ID_BAZA:\r\n return COURSE_ID_BAZA[naziv]\r\n query = \"SELECT id_predmeta FROM predmet \" \\\r\n \"WHERE predmet.naziv = %s\"\r\n cursor.execute(query, (naziv,))\r\n for (id_predmeta, ) in cursor:\r\n COURSE_ID_BAZA[naziv] = id_predmeta\r\n return id_predmeta\r\n","sub_path":"getters.py","file_name":"getters.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"510111382","text":"\ndef OtorisasiClick(sender, context):\n app = context.OwnerForm.ClientApplication\n key = context.KeyObjConst\n\n ph = app.CreateValues(['key', key])\n frm = app.CreateForm('AQH/fOtorTransCicilanAQH', 'fOtorTransCicilanAQH', 0, ph, None)\n frm.FormContainer.Show()\n context.Refresh()\n\n","sub_path":"menus/popupmenus/AQH/MnuOtorisasiCicilanAQH.py","file_name":"MnuOtorisasiCicilanAQH.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"306138628","text":"class Solution(object):\r\n def isPalindrome(self, x):\r\n \"\"\"\r\n :type x: int\r\n :rtype: bool\r\n \"\"\"\r\n ans = True\r\n if x<0:\r\n ans = False\r\n else:\r\n x = str(abs(x))\r\n for i in range(round(len(x)/2)): # necessary to have round()\r\n j = len(x)-i-1\r\n if x[i]!=x[j]:\r\n ans = False\r\n return ans\r\n\r\n# test case\r\nprint(Solution().isPalindrome(1221))","sub_path":"#9 Palindrome Number.py","file_name":"#9 Palindrome Number.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122893652","text":"\"\"\"\nCar(d)-Up\nversion 0.1\nby 2020 BINUS ASO School of Engineering Students for 6th Semester Project\nLast updated: 16/05/2019\n- Added session module for variable sharing between requests (17)\n- Added capability to get userID from sqlite database (53-60)\n- Added capability to send userID via mqtt to target device (pre-defined topic) (77-78)\n- Added mqtt_button request handler (83-87)\nGitHub link : https://github.com/VincentReynardS/CardUp/tree/master/RPi\n\"\"\"\n\n\n\nimport sqlite3\n\nfrom flask import Flask, flash, request, redirect, url_for, render_template, session\nfrom werkzeug.utils import secure_filename\nfrom flask_mqtt import Mqtt\n\napp = Flask('__name__')\n\napp.config['MQTT_BROKER_URL'] = '192.168.43.87' #ganti dengan IP address device broker\napp.config['MQTT_BROKER_PORT'] = 1883\napp.config['MQTT_CLIENT_ID'] = 'flask-mqtt'\n\nmqtt = Mqtt(app)\n# socketio = SocketIO(app)\n# bootstrap = Bootstrap(app)\n\n# data = {\n# \"payload\": \"\",\n# \"rooms\": \"\",\n# \"rfids\": \"\",\n# }\n\n@app.route('/')\ndef home():\n \"\"\"Home.\"\"\"\n # return render_template('home.html')\n return redirect(url_for('login'))\n\n@app.route('/login')\ndef login():\n \"\"\"Login\"\"\"\n return render_template('login.html')\n\n@app.route('/order', methods = ['POST', 'GET'])\ndef order():\n \"\"\"Order\"\"\"\n result = request.form\n if result['username'] == 'Vincent' and result['password'] == '123456':\n user = (result['username'],)\n conn = sqlite3.connect('Project micro.db')\n c = conn.cursor()\n c.execute('''SELECT ID_kartu FROM CUSTOMER\n WHERE customerName =?''', user)\n userID = c.fetchall()[0]\n print(userID[0])\n session['userID'] = userID\n return render_template('order.html')\n else:\n return 'Login failed'\n\n@app.route('/result', methods = ['POST', 'GET'])\ndef result():\n \"\"\"Result\"\"\"\n result = request.form\n if result['order']:\n car = (result['car'],)\n conn = sqlite3.connect('Project micro.db')\n c = conn.cursor()\n c.execute('''SELECT * FROM REGISTER\n WHERE mobil =?''', car)\n data = c.fetchall()[0]\n conn.close()\n userID = session.get('userID')\n mqtt.publish('rental/00001', userID[0])\n return render_template('result.html', data=data)\n else:\n return 'Order failed'\n\n@app.route('/mqtt_button', methods = ['POST', 'GET'])\ndef mqtt_button():\n command = request.form\n mqtt.publish('rental/00001', 'Hello!')\n return render_template('mqtt_button.html')\n\n# @mqtt.on_connect()\n# def handle_connect(client, userdata, flags, rc):\n# \"\"\"Connect MQTT Server.\"\"\"\n# mqtt.subscribe('inTopic', 2)\n\n# @mqtt.on_message()\n# def handle_mqtt_message(client, userdata, message):\n# \"\"\"Get MQTT message.\"\"\"\n# msg = message.payload.decode()\n# print(msg)\n# socketio.emit('mqtt_message', data=msg)\n\nif __name__ == '__main__':\n app.secret_key = 'super secret key'\n app.run(host='0.0.0.0', port='5000', debug=True)\n app.config['SESSION_TYPE'] = 'filesystem'","sub_path":"RPi/flaskServer.py","file_name":"flaskServer.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20116781","text":"from pricestf import get_price\n\ndef prctf_err():\n print(\"Something went wrong with module 'pricestf' while loading current prices!\")\n input(\"Press any key to quit!\")\n quit()\n\ntry:\n key_current = get_price(\"Mann Co. Supply Crate Key\")\n earbuds_current = get_price(\"Earbuds\")\n\n if type(key_current) == type(0) or type(earbuds_current) == type(0):\n prctf_err()\nexcept:\n prctf_err()\n\nkey_sell = key_current[\"sell_price\"][\"metal\"]\nearbuds_sell = float(str(earbuds_current[\"sell_price\"][\"keys\"]) + \".\" + str(int(round(earbuds_current[\"sell_price\"][\"metal\"] / key_sell, 2) * 100)))\n\ndef calculate(amount, type):\n data = {}\n if type == \"scrap\":\n data[\"scrap\"] = amount\n data[\"rec\"] = amount / 3\n data[\"ref\"] = amount / 9\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"rec\":\n data[\"scrap\"] = amount * 3\n data[\"rec\"] = amount\n data[\"ref\"] = amount / 3\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"ref\":\n data[\"scrap\"] = amount * 9\n data[\"rec\"] = amount * 3\n data[\"ref\"] = amount\n data[\"key\"] = data[\"ref\"] / key_sell\n data[\"earbuds\"] = data[\"key\"] / earbuds_sell\n elif type == \"key\":\n ref = amount * key_sell\n data[\"scrap\"] = ref * 9\n data[\"rec\"] = ref * 3\n data[\"ref\"] = ref\n data[\"key\"] = amount\n data[\"earbuds\"] = amount / earbuds_sell\n elif type == \"earbuds\":\n key = amount * earbuds_sell\n ref = key * key_sell\n data[\"scrap\"] = ref * 9\n data[\"rec\"] = ref * 3\n data[\"ref\"] = ref\n data[\"key\"] = key\n data[\"earbuds\"] = amount\n else:\n print(\"Unknown type: \" + type)\n return(0)\n\n for i in data:\n data[i] = round(data[i], 2)\n \n return(data)\n","sub_path":"tf2calc/tf2calc.py","file_name":"tf2calc.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92872101","text":"from os import system\nfrom os.path import exists\nimport base64 ## png encoding\nimport math\n#from . import basic ## convert_svg_to_png\nfrom .convert_svg_to_png import MONOSPACE_FONT_FAMILY, convert_svg_to_png\nfrom .html_colors import CB_RED, CB_GREEN, CB_BLUE, CB_ORANGE, CB_PURPLE\n\n\n## these are not actually defined by the language...\nall_text_height = {20:15.5, 100:75.}\nall_text_width = {20:12.5, 100:60.}\n\ndef rgb_from_fraction(fraction, cmap=None):\n\n assert fraction >=0 and fraction<=1\n\n fraction = float(fraction)\n\n if cmap is None:\n if fraction<0.5:\n i = 2*fraction*256\n\n #green = min(200,2*i)\n green = int( min(200,(200*i)/128) )\n blue = max(0,int( min(255,510-2*i) ))\n red = 0\n else:\n i = 2*(fraction-0.5)*256\n red = int( min(255,2*i) )\n green = int( max(0,min(200,400 - (200*i)/128)) )\n #green = min(200,510-2*i)\n blue = 0\n else:\n color_tuple = cmap(fraction)[:3]\n red, green, blue = [min(255,int(x*255)) for x in color_tuple]\n\n assert 0<=red <=255\n assert 0<=green<=255\n assert 0<=blue <=255\n\n return '#{:02x}{:02x}{:02x}'.format(red,green,blue)\n\n\n # return '\\n'\\\n # .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0],\n # fill, stroke )\n\ndef rectangle( upper_left, lower_right, fill, stroke, stroke_width=1, dashed=False ):\n stroke_dasharray_style= ';stroke-dasharray:5,5' if dashed else ''\n return '\\n'\\\n .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0],\n fill, stroke, stroke_width, stroke_dasharray_style )\n\ndef create_file( cmds, width, height, filename, create_png = False, background_color=None, use_xlink=False ):\n out = open( filename,'w')\n extra = '' if not use_xlink else 'xmlns:xlink=\"http://www.w3.org/1999/xlink\"'\n out.write('\\n'\\\n .format(int(width),int(height),extra))\n if background_color:\n out.write(rectangle( (0,0), (width,height), background_color, 'white', 0 ) )\n out.write('\\n'.join(cmds)+'\\n')\n out.write('\\n')\n out.close()\n\n if create_png:\n assert filename.endswith('.svg')\n pngfile = filename[:-4]+'.png'\n convert_svg_to_png( filename, pngfile )\n\n\n## this will work if oldfile was created using create_file\n## returns: cmds, old_width, old_height\n## cmds do not include the newline from the original file\n## ie, they could go right into create_file\n##\n## matplotlib seems to generate files that are sized in pt units, which is a bit of a nuisance\n## converting between them is something like #px = 1.25 * #pt\n## pt = 1/72 inch, so inch = 72pt = 72*1.25=72*5/4 = 18*5 = 90px\n## but somewhere on the web somebody says the new standard is 1inch=96px...\n## at least that's what I get when I run convert on a matplotlib generated svg to make a png\n## ( 576pt x 864pt goes to 720px x 1080px )\n##\ndef embed_file( oldfile, x_shift, y_shift ):\n cmds = [] ##\n cmds = [''.format(x_shift,y_shift) ]\n for line in open(oldfile,'r'):\n if line.startswith(\"')\n return cmds, old_width, old_height\n\n## returns a single line\n## note that we have to set use_xlink=True when we call create_file in order for the link to work here:\n##\ndef embed_pngfile( pngfile, width, height, x0, y0, aspect=None ):\n assert exists( pngfile )\n encoded = base64.b64encode(open(pngfile, \"rb\").read()).decode('ascii')\n #encoded = base64.b64encode(open(pngfile, \"rb\").read())\n\n asp = '' if aspect==None else 'preserveAspectRatio=\"{}\"'.format(aspect)\n\n cmd = ''\\\n .format( width, height, x0, y0, asp, encoded )\n return cmd\n\n\ndef make_text( text, lower_left, fontsize,\n extra_tag = None, font_family = MONOSPACE_FONT_FAMILY, color = \"black\", font_weight = \"normal\" ):\n assert font_weight in ['normal','bold']\n cmd = '{}\\n'\\\n .format( lower_left[0], lower_left[1], fontsize, font_weight, font_family, color, text )\n return cmd\n\n\nclass SVG_tree_plotter:\n def __init__( self, cmap=None ):\n self.cmds = []\n self.cmap = cmap\n\n def make_line( self, p0, p1, line_width, normalized_score, extra_tag=None, color=None ):\n\n if normalized_score==None:\n #color='black'\n color = '#aaaaaa' # gray\n elif color==None:\n color = rgb_from_fraction(normalized_score, cmap=self.cmap)\n\n if p0[0] == p1[0]: ## vertical line, get width exactly right\n x = p0[0] ; y0 = min(p0[1],p1[1]) ; y1 = max(p0[1],p1[1] )\n\n upper_left = ( x-line_width/2.0, y0 )\n lower_right = ( x+line_width/2.0, y1 )\n cmd = rectangle( upper_left, lower_right, color, color )\n\n elif p0[1] == p1[1]: ## horizontal line, get width exactly right\n y = p0[1] ; x0 = min(p0[0],p1[0]) ; x1 = max(p0[0],p1[0] )\n\n upper_left = ( x0, y-line_width/2.0 )\n lower_right = ( x1, y+line_width/2.0 )\n cmd = rectangle( upper_left, lower_right, color, color )\n else:\n cmd = '\\n'\\\n .format( p0[0], p0[1], p1[0], p1[1], 0.5*line_width,color )\n self.cmds.append( cmd )\n\n def make_text( self, text, p, fontsize, extra_tag=None ):\n color = 'black'\n ## shift so that p is the lower right\n textwidth = fontsize*0.6 * len(text)\n cmd = '{}\\n'\\\n .format( p[0]-textwidth, p[1], fontsize, MONOSPACE_FONT_FAMILY, color, text )\n self.cmds.append( cmd )\n\n def write( self, out ):\n out.write('\\n'.join( self.cmds )+'\\n' )\n\n\n\ndef color_stack( upper_left, lower_right, letters, colors, values ):\n fontsize= 20\n fontwidth = all_text_width [fontsize]\n fontheight = all_text_height[fontsize]\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n ## draw them proportional to their values\n total = sum(values)\n\n ## draw from the top down\n height_sum = 0.\n lines = []\n\n for (letter,(color,value)) in zip( letters, list(zip( colors, values )) ):\n my_height = height * float(value)/total\n height_sum += my_height\n my_x = upper_left[0]\n my_y = upper_left[1] + height_sum\n\n ## we are going to have to scale\n x_scale = float( width ) / fontwidth\n y_scale = float( my_height ) / fontheight\n\n #print letter, 'my_height:',my_height, 'y_scale:',y_scale,'fontheight:',fontheight,'my_xy:',my_x,my_y\n\n ## we need to translate so that\n lines.append( '{}\\n'\\\n .format( my_x / x_scale, my_y / y_scale, fontsize, MONOSPACE_FONT_FAMILY, color,\n x_scale, y_scale, letter ) )\n\n #lines.append( '{}\\n'\\\n # .format( my_x , my_y , fontsize, color, letter ) )\n return ''.join( lines )\n\n\ndef text_in_box( upper_left, lower_right, text, color ):\n fontsize= 100\n\n fontwidth = all_text_width [fontsize]\n fontheight = all_text_height[fontsize]\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n ## we are going to have to scale\n x_scale = float( width ) / (fontwidth * len(text))\n y_scale = float( height ) / fontheight\n\n #print text, 'height:',height, 'y_scale:',y_scale,'fontheight:',fontheight,'my_xy:'\n\n ## we need to translate so that\n return '{}\\n'\\\n .format( float(upper_left [0]) / x_scale,\n float(lower_right[1]) / y_scale,\n fontsize, MONOSPACE_FONT_FAMILY, color, x_scale, y_scale, text )\n\n\n\ndef protein_logo(\n upper_left,\n lower_right,\n pwm,\n scale={}, ## scale[pos] should be in range [0,1]\n xmag = 1.0, # make the letters wider by this factor\n xmag_W = 1.0,\n):\n\n aacolor = {}\n for aa in \"G\" :aacolor[aa] = CB_ORANGE #\"orange\" ## special for glycine\n for aa in \"STYC\" :aacolor[aa] = CB_GREEN #\"green\"\n for aa in \"NQ\" :aacolor[aa] = CB_PURPLE #\"purple\"\n for aa in \"KRH\" :aacolor[aa] = CB_BLUE #\"blue\"\n for aa in \"DE\" :aacolor[aa] = CB_RED #\"red\"\n for aa in \"P\" :aacolor[aa] = \"black\" ## for right now\n for aa in \"AWFLIMV\" :aacolor[aa] = \"black\" ## do we want to make W,F something different??\n for aa in \"J\":aacolor[aa] = \"green\"\n for aa in \".-\":aacolor[aa] = \"black\"\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n N = len(list(pwm.keys()))\n\n letter_width = float(width) / N\n\n cmds = []\n\n for pos in range(N):\n l = [(y,x) for x,y in pwm[pos].items() ]\n l.sort()\n l.reverse()\n ## start from the top\n col_scale = scale.get(pos,1.0)\n assert col_scale>=0 and col_scale<=1.00001\n scaled_height = col_scale * height\n upper_y = lower_right[1] - scaled_height\n\n totfreq=0.0\n for freq,aa in l:\n if freq * scaled_height>1: ## at least one pixel high\n y0 = upper_y + totfreq * scaled_height\n y1 = upper_y + (totfreq+freq) * scaled_height\n extra_x = (letter_width*(xmag_W-1.0)/2 if aa=='W' else\n letter_width*(xmag -1.0)/2)\n x0 = upper_left[0] + pos*letter_width - extra_x\n x1 = upper_left[0] + (pos+1)*letter_width + extra_x\n cmds.append( text_in_box( (x0,y0), (x1,y1), aa, aacolor[aa] ) )\n totfreq += freq\n #print pos,aa,freq,totfreq,sum(pwm[pos].values()),pwm[pos]\n assert abs(totfreq-1.0)<1e-2\n\n return '\\n'.join(cmds)+'\\n'\n\ndef generic_logo( upper_left, lower_right, pwm ):\n\n color = 'black'\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n N = len(list(pwm.keys()))\n\n column_width = float(width) / N\n\n cmds = []\n\n for pos in range(N):\n l = [(y,x) for x,y in pwm[pos].items() ]\n l.sort()\n l.reverse()\n ## start from the top\n totfreq=0\n for freq,aa in l:\n if freq<1e-3:continue\n y0 = upper_left[1] + totfreq * height\n y1 = upper_left[1] + (totfreq+freq) * height\n x0 = upper_left[0] + pos *column_width\n x1 = upper_left[0] + (pos+1)*column_width\n cmds.append( text_in_box( (x0,y0), (x1,y1), aa, color ) )\n totfreq += freq\n return '\\n'.join(cmds)+'\\n'\n\n\ndef make_stack( upper_left, lower_right, l ):\n x0 = upper_left [0]\n x1 = lower_right[0]\n\n width = lower_right[0] - upper_left[0]\n height = lower_right[1] - upper_left[1]\n\n l.sort()\n l.reverse()\n\n total = sum([x[0] for x in l])\n totval = 0\n cmds = []\n for vwc in l:\n if len(vwc) == 2:\n val,word = vwc\n color = 'black'\n else:\n assert len(vwc) == 3\n val,word,color = vwc\n y0 = upper_left[1] + height * float(totval) / total\n y1 = upper_left[1] + height * float(totval+val) / total\n cmds.append( text_in_box( (x0,y0), (x1,y1), word, color ) )\n totval+=val\n\n return '\\n'.join(cmds)+'\\n'\n\n\n\ndef enrichment_glyph_marker_old(marker_id):\n cmd = \"\"\"\n \n \n \"\"\".format(marker_id)\n return cmd\n\ndef enrichment_glyph_old( center, arrow_length, arrow_width, fontsize, marker_id, enrichment ):\n line_text_sep = 2.\n if enrichment>1: ## up arrow, text at the top\n line_p0 = [ center[0], center[1] + arrow_length/2. ]\n line_p1 = [ center[0], center[1] - arrow_length/2. ]\n text_lower_y = line_p1[1] - line_text_sep\n enrichment_text = '{:.1f}'.format(enrichment)\n else:\n line_p0 = [ center[0], center[1] - arrow_length/2. ]\n line_p1 = [ center[0], center[1] + arrow_length/2. ]\n text_lower_y = line_p1[1] + line_text_sep + 0.75 * fontsize\n enrichment_text = '{:.1f}'.format(1.0/enrichment)\n text_lower_x = center[0] - 0.6 * fontsize * 0.5 * len(enrichment_text)\n\n\n\n ## define the marker\n cmds = []\n cmds.append(\n ''\\\n .format( line_p0[0], line_p0[1], line_p1[0], line_p1[1], marker_id, arrow_width ) )\n cmds.append( make_text( enrichment_text, [ text_lower_x, text_lower_y ], fontsize ) )\n\n return cmds\n\n# eg_marker_id_prefix = 'eg_'\n# eg_max_arrow_heads = 6\n\n# def enrichment_glyph_markers():\n# global eg_marker_id_prefix\n# global eg_max_arrow_heads\n\n# for heads in range(1,eg_max_arrow_heads+1):\n# markerid = '{}{}'.format( eg_marker_id_prefix, heads )\n\n# cmd = \"\"\"\n# \n# \n# \"\"\".format(marker_id)\n# return cmd\n\ndef enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment, add_rectangle = False, box_color = 'gold' ):\n cmds = []\n\n num_heads = int(math.floor( abs( math.log(enrichment,2.) ) ))\n if num_heads<1:\n return cmds\n\n head_sep = 3. * arrow_width\n head_width = 3. * arrow_width\n head_slant = 1.\n\n if enrichment>1: ## up arrow, text at the top\n line_p0 = [ center[0], center[1] + arrow_length/2. ]\n line_p1 = [ center[0], center[1] - arrow_length/2. ]\n head_step = 1 * head_sep\n else:\n line_p0 = [ center[0], center[1] - arrow_length/2. ]\n line_p1 = [ center[0], center[1] + arrow_length/2. ]\n head_step = -1 * head_sep\n\n if add_rectangle:\n ## put a nice rounded rectangle around the outside\n rect_x0 = center[0] - head_width - arrow_width\n rect_y0 = center[1] - arrow_length/2 - arrow_width\n rect_width = 2*(head_width+arrow_width)\n rect_height = arrow_length + 2*arrow_width\n rect_round = 3.0 * arrow_width\n\n cmds.append( ''\\\n .format( rect_x0, rect_y0, rect_width, rect_height, rect_round, rect_round,\n box_color, box_color ))\n\n\n ## make the line\n cmds.append( ''\\\n .format( line_p0[0], line_p0[1], line_p1[0], line_p1[1], arrow_width ) )\n\n ## now make the heads\n\n for head in range(num_heads):\n for xsign in [1,-1]:\n x1 = line_p0[0]\n x2 = x1 + xsign * head_width\n y1 = line_p1[1] + head * head_step\n y2 = y1 + head_slant * head_step\n\n cmds.append( ''\\\n .format( x1,y1,x2,y2, arrow_width ) )\n\n if False: ## add shifted white line\n y_shift = arrow_width * head_step / head_sep\n cmds.append( ''\\\n .format( x1,y1+y_shift,x2,y2+y_shift, arrow_width ) )\n\n\n return cmds\n\n\nif __name__ == '__main__':\n cmds = []\n # marker_id = 'tri'\n # cmds.append( enrichment_glyph_marker( marker_id ) )\n center = [50,50]\n arrow_length = 40.\n arrow_width = 3.\n enrichment = 2.01\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n center = [100,50]\n enrichment = 45.01\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n center = [250,50]\n enrichment = 0.49\n cmds += enrichment_glyph_cmds( center, arrow_length, arrow_width, enrichment )\n\n svgfile = 'tmp.svg'\n width = 300\n height = 100\n\n create_file( cmds, width, height, svgfile, create_png=True, background_color='red' )\n\n\n\n\n\n # out = open('tmp3.svg','w')\n\n # out.write( '\\n' )\n\n # texts = [ ( (0,0), (500,300), 'DUDE' ),\\\n # ( (100,350), (700,400), 'TEST' ) ]\n\n\n # for (upper_left,lower_right,text) in texts:\n\n\n # out.write( '\\n'\\\n # .format( upper_left[0], upper_left[1], lower_right[1]-upper_left[1], lower_right[0]-upper_left[0] ) )\n\n # out.write( text_in_box( upper_left, lower_right, text ) )\n\n\n # out.write( '\\n' )\n","sub_path":"tcrdock/tcrdist/tcrdist_svg_basic.py","file_name":"tcrdist_svg_basic.py","file_ext":"py","file_size_in_byte":18089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122154010","text":"# Merge two sorted linked lists and return it as a new list. \n# The new list should be made by splicing together the nodes of the first two lists.\n\n# @param two ListNodes (two head of list node)\n# @return a ListNode (the head node of the linkedList)\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n dummy = ListNode(0)\n cur = dummy\n while l1 and l2:\n if l1.val <= l2.val:\n cur.next = l1\n cur = cur.next\n l1 = l1.next\n else:\n cur.next = l2\n cur = cur.next\n l2 = l2.next\n if l1:\n cur.next = l1\n else:\n cur.next = l2\n \n return dummy.next\n \n","sub_path":"LinkedList/021-Merge Two Sorted Lists/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"133592554","text":"#!/usr/bin/env python\n# coding=utf8\n\nfrom importlib import import_module\n\n\ndef get_experiments(model, box):\n exp_class = ''.join(map(str.capitalize, [*model.split(\"_\"), box]))\n model = model.replace(\"reference_\", \"\")\n model = model.replace(\"coarse_\", \"\")\n module = import_module(\".%s\" % model,\n package='th_fallfilm.experiments')\n return getattr(module, exp_class)\n","sub_path":"th_fallfilm/experiments/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"363540764","text":"Disk1 = 'Disk1'\r\nDisk2 = 'Disk2'\r\nPole1 = 'Pole1'\r\nPole2 = 'Pole2'\r\nPole3 = 'Pole3'\r\n\r\nDISKS = ['Disk1', 'Disk2']\r\nPOLES = ['Pole1', 'Pole2', 'Pole3']\r\nLITERALS = [Disk1, Disk2, Pole1, Pole2, Pole3]\r\n\r\ndef On(A,B):\r\n return (\"On\", A, B)\r\n\r\ndef Clear(A):\r\n return (\"Clear\", A)\r\n\r\ndef Smaller(A, B):\r\n return (\"Smaller\", A, B)\r\n\r\nINIT = set([\r\n Clear(Disk1),\r\n On(Disk1, Disk2),\r\n On(Disk2, Pole1),\r\n Clear(Pole2),\r\n Clear(Pole3),\r\n Smaller(Disk1, Pole1),\r\n Smaller(Disk1, Pole2),\r\n Smaller(Disk1, Pole3),\r\n Smaller(Disk1, Disk2),\r\n Smaller(Disk2, Pole1),\r\n Smaller(Disk2, Pole2),\r\n Smaller(Disk2, Pole3),\r\n])\r\n\r\nGOAL = set([\r\n On(Disk1, Disk2),\r\n On(Disk2, Pole3)\r\n])\r\n\r\n# ACTIONS\r\n\r\ndef Move(STATE, Disk, Source, Dest):\r\n if Clear(Disk) in STATE and On(Disk, Source) in STATE and Clear(Dest) in STATE and Smaller(Disk, Dest) in STATE:\r\n STATE.add( On(Disk, Dest) )\r\n STATE.remove( On(Disk, Source) )\r\n STATE.remove( Clear( Dest ) )\r\n STATE.add( Clear( Source ) )\r\n return True\r\n else:\r\n return False\r\n\r\ndef UnMove(STATE, Disk, Source, Dest):\r\n if On(Disk, Dest) in STATE and On(Disk, Source) not in STATE and Clear(Dest) not in STATE and Clear(Source) in STATE:\r\n STATE.remove( On(Disk, Dest) )\r\n STATE.add( On(Disk, Source) )\r\n STATE.add( Clear( Dest ) )\r\n STATE.remove( Clear( Source ) )\r\n return True\r\n else:\r\n return False\r\n\r\n# actions is just a list of pairs of functions to do or undo an action\r\n# in general we could make things general and check for function arity\r\n# but currently the code only works with Disk, Source, Dest\r\nACTIONS = [ (Move, UnMove) ]\r\n","sub_path":"towers2.py","file_name":"towers2.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"210634257","text":"import os\n\nfrom base_backend.utils.exceptions import EnvironmentVariableNotSetException\n\n\ndef get_environment_variable(name: str, raise_exception: bool = True, default=None):\n \"\"\"\n Method to retrieve envrionment variables.\n @param name: The name of the environment variable to retrieve\n @param raise_exception: Indicate whether or not an exception should be raised if the variable does not have a value and there's no default set.\n @param default: Default value to return if the environment variable is not set. Setting this will ensure that no exception is returned.\n \"\"\"\n val = os.environ.get(name, default)\n\n if raise_exception and val is None:\n raise EnvironmentVariableNotSetException(\n f\"{name} is a required environment variable.\"\n )\n\n return val\n","sub_path":"base_backend/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"625864261","text":"\"\"\"\nThe :mod:`sklearn.gp_search` includes utilities to fine-tune the parameters\nof an estimator through a Gaussian Process model.\n\"\"\"\nfrom __future__ import print_function\n\n# Author: Sebastien Dubois ,\n# License: BSD 3 clause\n\nimport numpy as np\nfrom scipy.stats import norm\n\nfrom .gaussian_process import GaussianProcessRegressor\nfrom .cross_validation import check_cv\nfrom .cross_validation import _fit_and_score\nfrom .metrics.scorer import check_scoring\nfrom .base import is_classifier, clone\nfrom .grid_search import BaseSearchCV\n\n\n\ndef sample_candidates(n_candidates, param_bounds, param_isInt):\n\n n_parameters = param_isInt.shape[0]\n candidates = []\n\n for k in range(n_parameters):\n if param_isInt[k]:\n k_sample = np.asarray(\n np.random.rand(n_candidates)\n * np.float(param_bounds[k][1]-param_bounds[k][0])\n + param_bounds[k][0],\n dtype=np.int32)\n else:\n k_sample = np.asarray(\n np.random.rand(n_candidates)\n * np.float(param_bounds[k][1]-param_bounds[k][0])\n + param_bounds[k][0])\n candidates.append(k_sample)\n\n candidates = np.asarray(candidates)\n candidates = candidates.T\n\n return compute_unique(candidates)\n\n\ndef compute_ei(predictions, sigma, y_best):\n ei_array = np.zeros(predictions.shape[0])\n for i in range(ei_array.shape[0]):\n z = (y_best - predictions[i]) / sigma[i]\n ei_array[i] = sigma[i] * (z * norm.cdf(z) + norm.pdf(z))\n\n return ei_array\n\n\ndef compute_unique(a):\n # keep only unique values in the ndarray a\n # http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array\n\n b = np.ascontiguousarray(a).view(\n np.dtype((np.void, a.dtype.itemsize * a.shape[1]))\n )\n _, idx = np.unique(b, return_index=True)\n idx = np.sort(idx)\n\n return a[idx]\n\n\ndef is_in_ndarray(item, a):\n # look for element item in ndarray a\n # returns True if item is in a, and its index\n\n k = 0\n idx_val = np.asarray(range(a.shape[0]))\n idxk = range(a.shape[0])\n while(k < a.shape[1]):\n idxk = (a[idxk, k] == item[k])\n if np.sum(idxk > 0):\n k += 1\n idx_val = idx_val[idxk]\n idxk = list(idx_val)\n else:\n return False, 0\n\n return True, idx_val[0]\n\n\n\nclass GPSearchCV(BaseSearchCV):\n \"\"\"\n Parameters\n ----------\n\n parameters : dict, parameter space on which to optimize the estimator\n The keys of the dictionnary should be the names of the parameters,\n and the values should be lists of length 2; the first element being\n the type of the parameter ('int', 'float' or 'cat' [for categorical]),\n and the second element being a list of either the bounds between which\n to search (for 'int' and 'float') or the values the parameter can take\n (for 'cat')\n Example : parameters = {'kernel' : ['cat', ['rbf', 'poly']],\n 'd' : ['int', [1,3]],\n 'C' : ['float',[1,10])}\n\n estimator : 1) sklearn estimator or 2) callable\n 1 : object type that implements the \"fit\" and \"predict\" methods,\n as a classifier or a pipeline\n 2 : a function that computes the output given a dictionnary of\n parameters. The returned value should be a list of one or more\n floats if score_format == 'cv', and a float if score_format ==\n 'avg'\n\n X : array-like, shape = [n_samples, n_features]\n Training vector, where n_samples in the number of samples and\n n_features is the number of features.\n\n y : array-like, shape = [n_samples] or [n_samples, n_output], optional\n Target relative to X for classification or regression;\n None for unsupervised learning.\n\n fit_params : dict, optional\n Parameters to pass to the fit method.\n\n scoring : string, callable or None, optional\n A string (see sklearn's model evaluation documentation) or\n a scorer callable object / function with signature\n ``scorer(estimator, X, y)``.\n Default is None.\n\n cv : integer or cross-validation generator, optional\n Relevant if the estimator is an sklearn object.\n If an integer is passed, it is the number of folds.\n Specific cross-validation objects can be passed, see\n sklearn.cross_validation module for the list of possible objects\n Default is 5.\n\n acquisition function : string, optional\n Function to maximize in order to choose the next parameter to test.\n - Simple : maximize the predicted output\n - UCB : maximize the upper confidence bound\n - EI : maximizes the expected improvement\n Default is 'UCB'\n\n n_iter : int\n Total number of iterations to perform (including n_init and\n n_final_iter).\n Default is 100.\n\n n_init : int, optional\n Number of random iterations to perform before the smart search.\n Default is 30.\n\n n_final_iter : int, optional\n Number of final iterations, ie. smart iterations but with\n acquisition_function == 'Simple'\n Default is 5.\n\n n_candidates : int, optional\n Number of random candidates to sample for each GP iterations\n Default is 500.\n\n nugget : float, optional\n The nugget to set for the Gaussian Process.\n Default is 1.e-10.\n\n\n Attributes\n ----------\n\n best_parameter_ : dict, the parameter set, from those tested by the\n method _fit, that maximizes the mean of the cross-validation results.\n\n tested_parameters_ : ndarray, the parameters tested by _fit\n\n\n Examples\n -------\n >>> from sklearn.datasets import load_digits\n >>> iris = load_digits()\n >>> X, y = iris.data, iris.target\n >>> clf = RandomForestClassifier(n_estimators=20)\n >>> parameters = {\"max_depth\": ['int', [3, 3]],\n \"max_features\": ['int', [1, 11]],\n \"min_samples_split\": ['int', [1, 11]],\n \"min_samples_leaf\": ['int', [1, 11]],\n \"bootstrap\": ['cat', [True, False]],\n \"criterion\": ['cat', [\"gini\", \"entropy\"]]}\n\n >>> search = GPSearchCV(parameters,\n estimator=clf,\n X=X,\n y=y,\n n_iter=20)\n >>> search._fit()\n\n \"\"\"\n\n def __init__(self,\n estimator,\n parameters,\n scoring=None,\n fit_params=None,\n cv=None,\n acquisition_function='UCB',\n refit=True,\n n_init=10,\n n_iter=20,\n n_candidates=500,\n gp_params={},\n verbose=0):\n\n self.estimator = estimator\n self.parameters = parameters\n self.n_parameters = len(parameters)\n self.scoring = scoring\n self.acquisition_function = acquisition_function\n self.n_iter = n_iter\n self.n_init = n_init\n self.refit = refit\n self.n_candidates = n_candidates\n self.gp_params = gp_params\n self.param_names = list(parameters.keys())\n self.param_is_int = np.array([0 if (parameters[k][0] == 'float')\n else 1 for k in self.param_names])\n self.param_bounds = np.zeros((self.n_parameters, 2))\n self.verbose = verbose\n self.fit_params = fit_params if fit_params is not None else {}\n self.cv = cv\n\n self.best_parameter_ = None\n self.tested_parameters_ = None\n self.cv_scores_ = None\n\n if callable(estimator):\n self._callable_estimator = True\n if self.verbose > 0:\n print('Estimator is a callable and not an sklearn Estimator')\n else:\n self._callable_estimator = False\n\n if not self._callable_estimator:\n self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)\n\n # init param_bounds\n for i in range(self.n_parameters):\n if parameters[self.param_names[i]][0] == 'cat':\n self.param_bounds[i, 0] = 0\n self.param_bounds[i, 1] = \\\n len(parameters[self.param_names[i]][1])\n else:\n self.param_bounds[i] = \\\n np.array(parameters[self.param_names[i]][1])\n if parameters[self.param_names[i]][0] == 'int':\n self.param_bounds[i, 1] += 1\n\n if self.verbose > 0:\n print(self.parameters)\n print(self.param_names)\n print(self.param_is_int)\n print(self.param_bounds)\n\n\n def _vector_to_dict(self, vector_parameter):\n dict_parameter = dict.fromkeys(self.param_names)\n for i in range(self.n_parameters):\n if self.parameters[self.param_names[i]][0] == 'cat':\n dict_parameter[self.param_names[i]] = \\\n (self.parameters[self.param_names[i]][1])[\n int(vector_parameter[i])]\n elif self.parameters[self.param_names[i]][0] == 'int':\n dict_parameter[self.param_names[i]] = int(vector_parameter[i])\n else:\n dict_parameter[self.param_names[i]] = vector_parameter[i]\n\n return dict_parameter\n\n\n def _evaluate_params(self, X, y, params):\n \"\"\"\n The score function to call in order to evaluate the quality\n of the parameter params\n\n Parameters\n ----------\n tested_parameter : dict, the parameter to test\n\n Returns\n -------\n score : the mean of the CV score\n \"\"\"\n\n if not self._callable_estimator:\n cv = check_cv(self.cv, X, y,\n classifier=is_classifier(self.estimator))\n cv_score = [_fit_and_score(\n clone(self.estimator), X, y, self.scorer_,\n train, test, False, params,\n self.fit_params, return_parameters=True)\n for train, test in cv]\n\n n_test_samples = 0\n score = 0\n for tmp_score, tmp_n_test_samples, _, _ in cv_score:\n tmp_score *= tmp_n_test_samples\n n_test_samples += tmp_n_test_samples\n score += tmp_score\n score /= float(n_test_samples)\n\n else:\n score = self.estimator(params)\n\n return score\n\n\n def fit(self, X, y=None):\n \"\"\"\n Run the hyper-parameter optimization process\n\n Returns\n -------\n tested_parameters_ : ndarray, the parameters tested during the process\n\n cv_scores_ : array of the mean CV results of the parameters tested\n \"\"\"\n\n n_tested_parameters = 0\n tested_parameters = np.zeros((self.n_iter, self.n_parameters))\n cv_scores = np.zeros(self.n_iter)\n\n # Initialize with random candidates #\n init_candidates = sample_candidates(\n self.n_init, self.param_bounds, self.param_is_int)\n self.n_init = init_candidates.shape[0]\n\n for i in range(self.n_init):\n dict_candidate = self._vector_to_dict(init_candidates[i, :])\n cv_score = self._evaluate_params(X, y, dict_candidate)\n\n if self.verbose > 0:\n print('Step ' + str(i) + ' - Hyperparameter '\n + str(dict_candidate) + ' ' + str(cv_score))\n\n is_in, idx = is_in_ndarray(\n init_candidates[i, :],\n tested_parameters[:n_tested_parameters, :])\n if not is_in:\n tested_parameters[n_tested_parameters, :] = \\\n init_candidates[i, :]\n cv_scores[n_tested_parameters] = cv_score\n n_tested_parameters += 1\n else:\n if self.verbose > 0:\n print('Hyperparameter already tesed')\n cv_scores[idx] = (cv_scores[idx] + cv_score) / 2.\n\n for i in range(self.n_iter-self.n_init):\n\n # Model with a Gaussian Process\n gp = GaussianProcessRegressor(**self.gp_params)\n gp.fit(tested_parameters[:n_tested_parameters, :],\n cv_scores[:n_tested_parameters])\n\n # Sample candidates and predict their corresponding\n # acquisition values\n candidates = sample_candidates(self.n_candidates,\n self.param_bounds,\n self.param_is_int)\n if self.acquisition_function == 'UCB':\n predictions, std = gp.predict(candidates, return_std=True)\n upperBound = predictions + 1.96 * std\n best_candidate = candidates[np.argmax(upperBound)]\n\n elif self.acquisition_function == 'EI':\n predictions, std = gp.predict(candidates, return_std=True)\n y_best = np.max(cv_scores)\n ei = compute_ei(predictions, std, y_best)\n best_candidate = candidates[np.argmax(ei)]\n\n else:\n print('WARNING : acquisition_function not implemented yet : '\n + self.acquisition_function)\n\n dict_candidate = self._vector_to_dict(best_candidate)\n cv_score = self._evaluate_params(X, y, dict_candidate)\n if self.verbose > 0:\n print('Step ' + str(i+self.n_init) + ' - Hyperparameter '\n + str(dict_candidate) + ' ' + str(cv_score))\n\n is_in, idx = is_in_ndarray(\n best_candidate,\n tested_parameters[:n_tested_parameters, :])\n if not is_in:\n tested_parameters[n_tested_parameters, :] = best_candidate\n cv_scores[n_tested_parameters] = cv_score\n n_tested_parameters += 1\n else:\n if self.verbose > 0:\n print('Hyperparameter already tesed')\n cv_scores[idx] = (cv_scores[idx] + cv_score) / 2.\n\n best_idx = np.argmax(cv_scores[:n_tested_parameters])\n vector_best_param = tested_parameters[best_idx]\n best_parameter = self._vector_to_dict(vector_best_param)\n\n # store\n self.best_parameter_ = best_parameter\n self.tested_parameters_ = tested_parameters[:n_tested_parameters, :]\n self.scores_ = cv_scores[:n_tested_parameters]\n\n if self.verbose > 0:\n print('\\nTested ' + str(n_tested_parameters) + ' parameters')\n print('Max cv score ' + str(cv_scores[best_idx]))\n print('Best parameter ' + str(tested_parameters[best_idx]))\n print(best_parameter)\n\n if self.refit:\n # fit the best estimator using the entire dataset\n # clone first to work around broken estimators\n best_estimator = clone(self.estimator).set_params(\n **best_parameter)\n if y is not None:\n best_estimator.fit(X, y, **self.fit_params)\n else:\n best_estimator.fit(X, **self.fit_params)\n self.best_estimator_ = best_estimator\n\n return self\n","sub_path":"sklearn/gp_search.py","file_name":"gp_search.py","file_ext":"py","file_size_in_byte":15269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"639760221","text":"# -*- coding: utf-8 -*-\nimport locale\nimport subprocess\n\nimport psutil\n\nprint(locale.getdefaultlocale())\n\nimport argparse\nimport os\nimport random\nimport signal\nimport sys\nimport time\n\nfrom appium import webdriver\nfrom appium.webdriver.common.touch_action import TouchAction\n\nfrom libs.vmsmodify import VMSModifyHandler\n\nprint(\"The Python path used = %s\" % sys.executable)\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Unsupported value encountered.')\n\n\n# 创建解析步骤\napp_parser = argparse.ArgumentParser(description='Process some args.')\napp_parser.add_argument('--s', dest='remote_server', action='store', default='http://127.0.0.1:4723/wd/hub',\n help='The Appium server')\napp_parser.add_argument('--d', dest='dest_device', action='store', default='127.0.0.1:21523',\n help='The device, Use: adb devices to list')\napp_parser.add_argument('--a', dest='auto_ahk_file_prex', action='store', default='',\n help='Assign the auto hot key file')\napp_parser.add_argument('--v', dest='vmid', action='store', default=0,\n help='Assign the vms id')\napp_parser.add_argument('--enableads', dest='enable_ads', action='store', type=str2bool,\n nargs='?', help='enable click ads')\n\n# 解析参数步骤\napp_args = app_parser.parse_args()\napp_current_dir = os.path.dirname(os.path.abspath(__file__))\n\n# 日志\nimport logging.handlers\n\nlog_file_path = os.path.join(app_current_dir, 'vmid-{}-run.log'.format(app_args.vmid))\nif os.path.isfile(log_file_path):\n try:\n os.remove(log_file_path)\n except:\n pass\n\nhandler = logging.handlers.RotatingFileHandler(log_file_path,\n maxBytes=1024 * 1024 * 50, backupCount=1) # 实例化 handler\nfmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'\nformatter = logging.Formatter(fmt) # 实例化 formatter\nhandler.setFormatter(formatter) # 为 handler 添加 formatter\nlogger = logging.getLogger('tst') # 获取名为 tst 的 logger\nlogger.addHandler(handler) # 为 logger 添加 handler\nlogger.setLevel(logging.DEBUG)\n\nvmsH = VMSModifyHandler(logger=logger)\n\n\nclass RunningHelper(object):\n @staticmethod\n def get_flag_file(vmid):\n flag_file = os.path.join(app_current_dir, 'can-stop-vmid-{}-f.flag'.format(vmid))\n return flag_file\n\n @staticmethod\n def is_vm_is_running(vmid):\n return vmsH.vm_is_running(vmid)\n\n @staticmethod\n def create_can_stop_vm_flag_file(flag_file):\n if not os.path.isfile(flag_file):\n try:\n open(flag_file, \"w+\").close()\n except Exception:\n logger.exception(\"Error:\")\n\n @staticmethod\n def remove_can_stop_vm_flag_file(flag_file):\n if os.path.isfile(flag_file):\n try:\n os.remove(flag_file)\n except Exception:\n logger.exception(\"Error:\")\n\n\n# 全局配置\nglobal_config = {\n # 'max_urls_count': random.randint(12, 24), # 一般情况下, 持续2个小时,是相当长的了\n 'max_urls_count': random.randint(20 * 24 * 3, 20 * 24 * 7), # 一般情况下, 1小时,最多生产20,一般要求3天,查看一次\n 'run_count': 0,\n 'run_to_get_urls_count': 0, # 运行获取url的机器运行计数\n}\n\nglobals_drivers = {}\nall_sub_process = []\n\nglobal_use_buildin_vpn = True # 是否使用VM中内置的VPN\n\n\ndef get_now_time():\n millis = int(round(time.time() * 1000))\n return millis\n\n\ndef get_random_driver_id():\n \"\"\"\n 获取随机的driver_id\n :return:\n \"\"\"\n new_id = '+{}{}'.format(\"\".join(random.sample(\"abcdefghijklmnopqrstuvwxyz\", 2)), get_now_time())\n return new_id\n\n\ndef sys_exit(message):\n \"\"\"\n 系统退出\n \"\"\"\n logger.info(message)\n logger.info(\"The system is about to exit ...\")\n exit(0)\n\n\nclass OldToolHelper(object):\n @staticmethod\n def sample_touch(driver):\n try:\n eye1 = TouchAction(driver)\n eye1.press(x=random.randint(100, 150),\n y=random.randint(100, 150)).release()\n time.sleep(1)\n except Exception:\n logger.exception(\"Error:\")\n finally:\n pass\n\n @staticmethod\n def auto_scroll_page(driver):\n \"\"\"\n 自动从上到下滚动,处理页面滑动问题\n \"\"\"\n try:\n logger.info(\"Start Auto Scroll\")\n total_width = driver.execute_script(\"return document.body.offsetWidth\")\n total_height = driver.execute_script(\n \"return document.body.parentNode.scrollHeight\")\n viewport_width = driver.execute_script(\"return document.body.clientWidth\")\n viewport_height = driver.execute_script(\"return window.innerHeight\")\n logger.info(\"Total: ({0}, {1}), Viewport: ({2},{3})\".format(\n total_width, total_height, viewport_width, viewport_height))\n\n rectangles = []\n\n i = 0\n while i < total_height:\n ii = 0\n top_height = i + viewport_height\n\n if top_height > total_height:\n top_height = total_height\n\n while ii < total_width:\n top_width = ii + viewport_width\n\n if top_width > total_width:\n top_width = total_width\n\n logger.info(\"Appending rectangle ({0},{1},{2},{3})\".format(ii, i, top_width, top_height))\n rectangles.append((ii, i, top_width, top_height))\n\n ii = ii + viewport_width\n\n i = i + viewport_height\n\n previous = None\n part = 0\n for rectangle in rectangles:\n if not previous is None:\n driver.execute_script(\"window.scrollTo({0}, {1})\".format(rectangle[0], rectangle[1]))\n logger.info(\"Scrolled To ({0},{1})\".format(rectangle[0], rectangle[1]))\n time.sleep(round(random.uniform(0.2, 1.6), 2))\n\n if rectangle[1] + viewport_height > total_height:\n offset = (rectangle[0], total_height - viewport_height)\n else:\n offset = (rectangle[0], rectangle[1])\n\n part = part + 1\n previous = rectangle\n\n logger.info(\"Finishing chrome full page scroll workaround...\")\n return True\n except Exception:\n logger.exception(\"Error:\")\n\n @staticmethod\n def random_scroll_up(driver):\n \"\"\"\n 随机往上滚动\n :return:\n \"\"\"\n try:\n if round(random.uniform(0.2, 0.9), 2) < 0.5:\n return\n\n logger.info(\"Start random_scroll_up\")\n total_width = driver.execute_script(\"return document.body.offsetWidth\")\n total_height = driver.execute_script(\n \"return document.body.parentNode.scrollHeight\")\n viewport_width = driver.execute_script(\"return document.body.clientWidth\")\n viewport_height = driver.execute_script(\"return window.innerHeight\")\n logger.info(\"Total: ({0}, {1}), Viewport: ({2},{3})\".format(\n total_width, total_height, viewport_width, viewport_height))\n\n # 先记录所有区间\n rectangles = []\n i = 0\n while i < total_height:\n ii = 0\n top_height = i + viewport_height\n if top_height > total_height:\n top_height = total_height\n while ii < total_width:\n top_width = ii + viewport_width\n if top_width > total_width:\n top_width = total_width\n logger.info(\"Appending rectangle ({0},{1},{2},{3})\".format(ii, i, top_width, top_height))\n rectangles.append((ii, i, top_width, top_height))\n ii = ii + viewport_width\n i = i + viewport_height\n\n # 随机回滚的位置\n all_rectangle_count = len(rectangles)\n cur_index = 0\n max_rectangle_count = max(0, random.randint(0, all_rectangle_count) - 1)\n rectangles.reverse()\n for rectangle in rectangles:\n if cur_index >= max_rectangle_count:\n break\n cur_index += 1\n\n driver.execute_script(\"window.scrollTo({0}, {1})\".format(rectangle[0], rectangle[1]))\n logger.info(\"Scrolled To ({0},{1})\".format(rectangle[0], rectangle[1]))\n time.sleep(round(random.uniform(0.2, 0.6), 2))\n\n logger.info(\"Finishing chrome random page scroll workaround...\")\n except Exception:\n logger.exception(\"Error:\")\n\n\ndef get_enable_click_ads():\n \"\"\"\n 检测是否可以点击广告\n (1)时间允许\n (2)随机告知是否可以\n :return:\n \"\"\"\n\n # Step1: 检测时间是否在范围内\n time_enable = False\n cur_time = time.localtime()\n cur_time_hour = int(cur_time.tm_hour)\n # 上午的情况,对应为美国区的晚上\n if cur_time_hour in range(11, 18):\n time_enable = round(random.uniform(0.2, 12), 2) >= 4.8\n\n # 凌晨的情况,对应美国区的下午\n if cur_time_hour in range(0, 11):\n time_enable = True and round(random.uniform(0.2, 12), 2) >= 1\n\n # 下午晚上可以点击少量广告的情况下,对应美国区的上午到中午时段\n if cur_time_hour in range(18, 25):\n time_enable = True and round(random.uniform(0.2, 12), 2) >= 1.8\n\n # Step2: 获取随机范围\n return time_enable\n\n\ndef common_process_call(loginfo='', commandList=[]):\n '''\n 公共调用子进程函数\n :param loginfo:\n :param commandList:\n :return:\n '''\n try:\n proc = subprocess.Popen(commandList,\n cwd=os.path.join(app_current_dir, 'scripts', app_args.auto_ahk_file_prex),\n shell=True)\n all_sub_process.append(proc)\n return_code = proc.wait()\n logger.info(return_code)\n return 1\n\n except Exception:\n logger.exception(\"Error:\")\n finally:\n time.sleep(5)\n\n return 0\n\n\ndef start_scroll_up_to_down():\n return common_process_call(\"Trying start_scroll_up_to_down...\", ['AutoHotkey', 'scrolluptodown.ahk'])\n\n\ndef start_auto_scroll_up_or_down():\n return common_process_call(\"Trying start_auto_scroll_up_or_down...\", ['AutoHotkey', 'scrollupordown.ahk'])\n\n\ndef start_vpn():\n return common_process_call(\"Trying start_vpn...\", ['AutoHotkey', 'runvpn.ahk'])\n\n\ndef auto_click_ads():\n return common_process_call(\"Trying click ads...\", ['AutoHotkey', 'clickads.ahk'])\n\n\ndef auto_close_tab_page():\n return common_process_call(\"Trying auto_close_tab_page...\", ['AutoHotkey', 'closetab.ahk'])\n\n\ndef starup(want_open_url, app_args):\n has_error = False\n now_driver_id = get_random_driver_id()\n try:\n desired_caps = {\n 'platformName': 'Android',\n 'platformVersion': '5.1.1',\n 'deviceName': app_args.dest_device,\n \"udid\": app_args.dest_device, # \"127.0.0.1:21533\", 查看:设备通讯端口,adb devices。 https://www.cnblogs.com/Nefeltari/p/5603163.html\n 'unicodeKeyboard': True,\n 'resetKeyboard': True,\n 'browserName': 'Chrome',\n 'nativeWebScreenshot': True,\n 'androidScreenshotPath': 'target/screenshots',\n # 'appPackage': 'com.android.chrome',\n 'clearSystemFiles': True,\n 'avdLaunchTimeout': 60000,\n 'avdReadyTimeout': 60000,\n # 'noReset': False,\n 'gpsEnabled': True,\n # 'appActivity': 'BrowserActivity',\n 'newCommandTimeout': 60000,\n 'autoWebviewTimeout': 60000,\n # 'appWaitDuration': 30000,\n 'chromeOptions': {\n # 为了防止出现Chrome的欢迎界面,你需要开启模拟器或者真机的开发者Debug选项。这个选项在手机或者模拟器的“设置”中\n 'args': [\n '--disable-fre',\n '--disable-popup-blocking',\n '--disable-infobars',\n '--allow-running-insecure-content',\n '--no-first-run',\n '--disable-web-security',\n # '--user-data-dir=/data/data/com.android.chrome/cache',\n '--test-type'\n ]\n },\n }\n\n # expressVPN:\n # app.romanysoft@gmail.com\n # hGFjNk5R\n # EUONFNPKASP5WXYVCEVOUEA\n\n logger.info(\"Starting webdriver ...\")\n logger.info(\"remote server address : %s\" % app_args.remote_server)\n\n globals_drivers[now_driver_id] = webdriver.Remote(app_args.remote_server, desired_caps)\n cur_driver = globals_drivers[now_driver_id]\n\n # 获取屏幕的size\n try:\n size = cur_driver.get_window_size()\n logger.info(\"Device Size = {}\".format(size))\n except Exception:\n pass\n\n logger.info(\"Open %s\" % want_open_url)\n\n global_config['run_to_get_urls_count'] = global_config['run_to_get_urls_count'] + 1\n logger.info(\"This is already an attempt to open a Web page = %d \" % (global_config['run_to_get_urls_count']))\n\n # 设置加载时间超时处理\n max_page_load_timeout = random.randint(90, 180) # 加大支持timeout的时间, 让浏览更逼真\n max_script_timeout = random.randint(60, 90) # 加大支持脚本执行的timeout时间,让浏览更逼真\n\n # 是否开启快速浏览模式\n # 快速浏览模式,将降低很多指标参数,不点击广告等等\n # enable_quick_browser_mode = round(random.uniform(0.1, 12), 2) <= random.randint(3, 6)\n enable_quick_browser_mode = get_enable_quick_browser_mode()\n if enable_quick_browser_mode:\n logger.info(\"开启快速浏览模式 ....\")\n max_page_load_timeout = random.randint(60, 90)\n max_script_timeout = random.randint(30, 60)\n\n # 设置加载及延时时间控制\n globals_drivers[now_driver_id].set_page_load_timeout(max_page_load_timeout)\n globals_drivers[now_driver_id].set_script_timeout(max_script_timeout)\n\n # 打开网页\n try:\n # 移除可以停止的标志文件\n RunningHelper.remove_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n # 执行打开网页\n globals_drivers[now_driver_id].get(want_open_url)\n except Exception:\n logger.exception(\"Error:\")\n logger.info('time out after %d seconds when loading page' % max_page_load_timeout)\n\n # print(u\"正在获取当前环境 ...\")\n # 获取当前上下文环境\n # current_context = driver.current_context\n # contexts = driver.contexts\n\n # 可以滚动一下\n cfg_enable_auto_scroll = True\n if cfg_enable_auto_scroll:\n logger.info(\"网页已经加载完成,可以从上到下滚动了 ...\")\n start_scroll_up_to_down()\n time.sleep(random.randint(15, 30))\n\n # 随机回滚一下\n cfg_enable_scroll_up = True and round(random.uniform(1, 12), 2) >= 3\n if cfg_enable_scroll_up:\n time.sleep(random.randint(3, 5))\n logger.info(\"现在可以向上滚动页面了 ...\")\n start_auto_scroll_up_or_down()\n\n # 让网页自己休息一会\n cfg_enable_web_wait = 1\n if cfg_enable_web_wait == 1:\n logger.info(\"让网页自己先安静一下...\")\n min_sleep_secs = random.randint(5, 30)\n time.sleep(min_sleep_secs)\n\n # 判断是否为快速浏览模式\n if enable_quick_browser_mode:\n start_auto_scroll_up_or_down()\n time.sleep(3)\n\n if round(random.uniform(1, 12), 2) >= 5:\n start_auto_scroll_up_or_down()\n time.sleep(3)\n\n if app_args.enalbe_ads: # 如果可以点击\n auto_click_ads()\n\n start_auto_scroll_up_or_down()\n time.sleep(random.randint(5, 25))\n\n # 非快速浏览模式,可以尝试点击广告\n else:\n # 可以尝试点击广告了\n logger.info(\"尝试点击广告...\")\n start_auto_scroll_up_or_down()\n auto_click_ads()\n cfg_enable_web_wait_after_ads = 1\n\n if cfg_enable_web_wait_after_ads == 1:\n logger.info(\"点击广告后,需要等待一会...\")\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(10)\n\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(5)\n start_auto_scroll_up_or_down()\n auto_click_ads()\n\n if round(random.uniform(1, 12), 2) >= 5:\n min_sleep_secs = random.randint(15, 30)\n time.sleep(min_sleep_secs)\n start_auto_scroll_up_or_down()\n\n # 停顿后,可以执行点击操作广告工作,也可以点击关闭标签的操作\n if round(random.uniform(1, 12), 2) >= 3:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 4:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(random.randint(1, 10))\n start_auto_scroll_up_or_down()\n\n if round(random.uniform(1, 12), 2) >= 6:\n time.sleep(random.randint(1, 10))\n auto_click_ads()\n start_auto_scroll_up_or_down()\n\n # 自动关闭标签页面\n auto_close_tab_page()\n if round(random.uniform(1, 12), 2) >= 5:\n time.sleep(random.randint(2, 5))\n\n # 关闭后台进程\n stop_all_back_procs(all_sub_process)\n\n # 浏览完成后,可以关闭了\n logger.info(\"浏览网页完成,即将关闭该网页...\")\n\n has_error = False\n global_config['run_count'] = global_config['run_count'] + 1\n except Exception:\n logger.exception(\"Error:\")\n has_error = True\n finally:\n logger.info(\"pages that are currently open count = %d\" % global_config['run_count'])\n try:\n globals_drivers[now_driver_id].quit()\n # 创建可以关闭VM的标记文件\n RunningHelper.create_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n except Exception:\n logger.exception(\"Error:\")\n if has_error:\n # 重新开启刷屏处理\n browser_boot(app_args)\n if global_config['run_count'] > global_config['max_urls_count']:\n sys_exit(\"The number of pages opened has reached the maximum requirement\")\n\n\ndef get_enable_quick_browser_mode():\n # Step1: 检测时间是否在范围内\n time_enable_ads_browser = False\n cur_time = time.localtime()\n cur_time_hour = int(cur_time.tm_hour)\n\n # 中国晚上的情况,美国区的上午到中午\n if cur_time_hour in range(18, 25):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 2\n\n # 中国凌晨的情况,美国中午到下午\n elif cur_time_hour in range(0, 12):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 1.5\n\n # 中国下午的情况,美国凌晨到上午\n elif cur_time_hour in range(12, 18):\n time_enable_ads_browser = True and round(random.uniform(1, 12), 2) >= 9\n\n try:\n if not app_args.enable_ads: # 如果系统要求不能使用点击广告,启动快速浏览模式\n return True\n finally:\n pass\n\n # Step2: 获取随机范围\n enable_quick_browser_mode = not time_enable_ads_browser\n return enable_quick_browser_mode\n\n\ndef browser_boot(app_args):\n sort_indexs = []\n with open(\"urls.txt\", \"r\") as fhandler:\n all_urls = []\n while True:\n file_url = fhandler.readline()\n if not file_url:\n break\n format_url = file_url.replace('\\n', '')\n all_urls.append(format_url)\n\n for index in range(len(all_urls)):\n sort_indexs.append(index)\n\n logger.info(\"Now process the web page count: %d\" % len(sort_indexs))\n\n # 让列表乱序处理\n random.shuffle(sort_indexs)\n for cur_index in sort_indexs:\n cur_url = all_urls[cur_index]\n cur_url = cur_url.strip()\n if cur_url != '':\n # must check vm is running\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n while not vm_is_running:\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n time.sleep(2)\n\n starup(cur_url, app_args)\n logger.info(\"Prepare the next web page url ... index=%d\" % cur_index)\n time.sleep(random.randint(6, 12))\n else:\n continue\n\n\ndef stop_all_back_procs(proc_list):\n for proc in proc_list:\n # (1)尝试terminate\n try:\n if proc:\n proc.kill()\n except Exception:\n logger.exception('Error:')\n\n # (2)尝试使用psutil来处理\n try:\n if proc:\n psutil.Process(proc.pid).terminate()\n except Exception:\n logger.exception('Error:')\n\n\ndef keyboardInterruptHandler(signal, frame):\n logger.info(\"KeyboardInterrupt (ID: {}) has been caught. Cleaning up...\".format(signal))\n\n exit(0)\n\n\ndef exit_callback():\n logger.info('exit is done')\n stop_all_back_procs(all_sub_process)\n logger.info('exit ....')\n\n\nif __name__ == \"__main__\":\n try:\n sys.exitfunc = exit_callback\n signal.signal(signal.SIGINT, keyboardInterruptHandler)\n\n # 移除可以停止的标志文件\n RunningHelper.remove_can_stop_vm_flag_file(RunningHelper.get_flag_file(app_args.vmid))\n\n # must check vm is running\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n while not vm_is_running:\n vm_is_running = RunningHelper.is_vm_is_running(app_args.vmid)\n time.sleep(2)\n\n if global_use_buildin_vpn:\n start_vpn()\n browser_boot(app_args)\n except Exception:\n logger.exception(\"Error:\")\n finally:\n stop_all_back_procs(all_sub_process)\n exit(0)\n","sub_path":"Python-Books/code-projects/auto-appium-android/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":22952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525190464","text":"numeros = [0] * 6\n\n# Ler os valores\nfor i in range(6):\n numeros[i] = int(input('Valor: '))\n\n# Verificar se são distintos\ndistintos = True\nfor i in range(6):\n # Verificar se o números da vez (i) é igual algum valor que\n # está após ele (j) na coleção.\n for j in range(i + 1, 6):\n # Se forem iguais, podemos concluir que a coleção não é distinta\n if (numeros[i] == numeros[j]):\n distintos = False\n break # pode parar de verificar\n if (distintos == False):\n break\n\nif (distintos == True):\n print(\"Números distintos\")\nelse:\n print(\"Números não distintos\")\n","sub_path":"semana_09/formulario/questao_03.py","file_name":"questao_03.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352652872","text":"# function\r\n# function return type \r\nusername = input('Enter user name : ')\r\npassword = input('Enter user password : ')\r\n\r\ndef login():\r\n user = 'micky'\r\n pwd = 'python123'\r\n if user == username and pwd == password:\r\n return 'yes'\r\n else:\r\n print('Login Failed') \r\n\r\ndef deposite():\r\n if login() == 'yes':\r\n print()\r\n print('Welcome to Deposite Section ..')\r\n amount = float(input('Enter amount to deposite : '))\r\n m_amount = 5000\r\n bal = m_amount +amount\r\n print()\r\n print('Total Amount is : ',bal)\r\n else:\r\n print('Try Again')\r\n\r\n\r\ndef withdraw():\r\n if login() == 'yes':\r\n print()\r\n print('Welcome to Withdraw Section ..')\r\n amount = float(input('Enter amount to withdraw : '))\r\n m_amount = 5000\r\n bal = m_amount - amount\r\n print()\r\n print('Balance Amount is : ',bal)\r\n else:\r\n print('Try Again')\r\n\r\n\r\nl1 = ['Deposite : d1','Withdraw : w1']\r\nprint('Welcome to Python Bank ..')\r\nprint()\r\nprint('Services are : ',l1)\r\nprint()\r\nv1 = input('Select your service option : ')\r\nif v1 == 'd1':\r\n deposite()\r\nelif v1 == 'w1':\r\n withdraw() \r\nelse:\r\n print('Service not available..')\r\n\r\n\r\n\r\n\r\n","sub_path":"Core_Python/Day-13/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77778765","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, tan, sqrt, asin, acos\nimport VelocityTrapezoidal\n\nOM = 3\nA = 1\ntheta_0 = 0.2\ndt = 0.001\n\nclass TrapezoidalMotion_mod():\n def __init__(self, max_velocity, max_acceleration_tangential, max_acceleration_normal, initial_pos=0, initial_vel=0, initial_curvature=0, dt=0.001):\n self.MAX_ACCELERATION_TANGENTIAL = max_acceleration_tangential\n self.MAX_ACCELERATION_NORMAL = max_acceleration_normal\n self.MAX_ACCELERATION = sqrt(self.MAX_ACCELERATION_NORMAL**2 + self.MAX_ACCELERATION_TANGENTIAL**2)\n self.MAX_VELOCITY = max_velocity\n\n self.MAX_VELOCITY_var = max_velocity\n \n self.old_pos = initial_pos\n self.old_pos_ref = initial_pos\n self.old_vel = initial_vel\n self.pos = initial_pos\n self.vel = initial_vel\n self.acc = 0\n\n self.total_displacement = self.old_pos_ref - self.old_pos\n\n self.t_a = 0\n self.T = 0\n self.t_f = 0\n self.t_i = 0\n self.delta_time = dt\n self.current_time = 0\n\n self.curvature = self._calc_curvature()\n\n\n def _calc_limited_vel(self):\n velocity = sqrt(self.MAX_ACCELERATION_NORMAL/self._calc_curvature())\n return velocity\n\n def _calc_max_vel(self):\n # print(self._calc_limited_vel(), self.MAX_VELOCITY)\n return min(self.MAX_VELOCITY, self._calc_limited_vel())\n\n\n def _calc_curvature(self):\n x = self.current_time\n dot_f = A*cos(OM*x+theta_0)*OM\n ddot_f = -A*sin(OM*x+theta_0)*OM*OM\n k = abs(ddot_f/(pow((1+dot_f*dot_f),(3/2))))\n return k\n\n def _calc_normal_acceleration(self):\n return self.vel**2*self._calc_curvature()\n\n def _calc_tangential_acceleration(self):\n return (self.vel-self.old_vel)/self.delta_time\n\n def update(self, pos_ref, time):\n self.current_time = time\n self.old_vel = self.vel\n if(self.old_pos_ref != pos_ref):\n self.old_pos = self.pos\n self.old_pos_ref = pos_ref\n self.t_i = time\n\n self.MAX_VELOCITY_var = self._calc_max_vel()\n self.t_a = (self.MAX_VELOCITY_var - abs(self.vel))/self.MAX_ACCELERATION\n self.t_d = (self.vel)/self.MAX_ACCELERATION\n self.total_displacement = abs(pos_ref - self.pos)\n # self.T = t_a + t_d\n self.T = (self.total_displacement*self.MAX_ACCELERATION+self.MAX_VELOCITY_var**2)/(self.MAX_ACCELERATION*self.MAX_VELOCITY_var)\n self.t_f = self.T + time\n\n self.calculateTrapezoidalProfile()\n\n\n def calculateTrapezoidalProfile(self):\n # if(self.t_i <= self.current_time and self.current_time <= self.t_i+self.t_a):\n if(self.delta_time <= self.t_a):\n # print(\"+ Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos + 1/2*self.MAX_ACCELERATION*((self.current_time - self.t_i)**2)\n self.vel = self.vel + self.MAX_ACCELERATION*self.delta_time\n # print(self.vel)\n self.acc = self.MAX_ACCELERATION\n\n # elif(self.t_i + self.t_a < self.current_time and self.current_time <= self.t_f - self.t_a):\n elif(self.delta_time > self.t_a and self.delta_time < self.T - self.t_a - self.t_d):\n # print(\"0 Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos + self.MAX_ACCELERATION*((self.current_time-self.t_i-(self.t_a/2))**2)\n self.vel = self.MAX_VELOCITY_var\n self.acc = 0\n \n # elif(self.t_f - self.t_a < self.current_time and self.current_time <= self.t_f):\n elif(self.delta_time >= self.T - self.t_a - self.t_d and self.delta_time <= self.t_d):\n # print(\"- Acc\")\n self.pos = self.pos + self.vel*self.delta_time\n # self.pos = self.old_pos_ref - (0.5*self.MAX_ACCELERATION*((self.t_f-self.current_time-self.t_i)**2))\n self.vel = self.vel - self.MAX_ACCELERATION*self.delta_time\n self.acc = -self.MAX_ACCELERATION\n\ndef plotter(plot_data):\n # plt.subplot()\n # Add the units to the axis\n\n fig = plt.figure()\n ax = plt.subplot(511)\n ax.plot(plot_data[\"pos_x_setpoint\"], plot_data[\"pos_y_setpoint\"], label=\"Setpoint-Trajectory\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n # ax.set(title=\"Position\", xlabel='x(m)', ylabel='y(m)')\n ax.set_title(\"Position\",fontsize=12)\n ax.set_xlabel(\"x(m)\",fontsize=7)\n ax.set_ylabel('y(m)', fontsize=7)\n\n\n ax = plt.subplot(512)\n ax.plot(plot_data[\"time\"], plot_data[\"curvature\"], \"--\", label=\"Curvature\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Curvature vs. Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('k', fontsize=7)\n \n ax = plt.subplot(513)\n ax.plot(plot_data[\"pos_x_setpoint\"], plot_data[\"pos_y_setpoint\"], label=\"Setpoint-Trajectory\")\n ax.plot(plot_data[\"time\"], plot_data[\"pos_y_real\"], label=\"Real-Trajectory\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Position\",fontsize=12)\n ax.set_xlabel(\"x(m)\",fontsize=7)\n ax.set_ylabel('y(m)', fontsize=7) \n\n ax = plt.subplot(514)\n ax.plot(plot_data[\"time\"], plot_data[\"velocity\"], label=\"Velocity\")\n ax.plot(plot_data[\"time\"], plot_data[\"max_velocity\"], \"--\", label=\"Max Velocity Planning\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Velocity vs Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('v(m/s)', fontsize=7) \n\n ax = plt.subplot(515)\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration\"], label=\"Total Acceleration\")\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration_tangential\"], \"--\", label=\"Tangential Acceleration\")\n ax.plot(plot_data[\"time\"], plot_data[\"acceleration_normal\"], \"--\", label=\"Normal Acceleration\")\n ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left',borderaxespad=0.)\n ax.set_title(\"Acceleration vs Time\",fontsize=12)\n ax.set_xlabel(\"t(s)\",fontsize=7)\n ax.set_ylabel('a\\n(m/s^2)', fontsize=7)\n\n # Add the units to the axis\n fig.canvas.set_window_title('Plotting')\n plt.tight_layout()\n fig.tight_layout()\n\n plt.show()\n\ndef motion_equation(t):\n x = t\n y = A*sin(OM*x+theta_0)\n return x,y\n\ndef const_motion(t, y_const=1):\n x = t\n y = y_const\n return x,y\n\ndef const_step_motion(t, t_change=1, y_const=1):\n if(t < t_change):\n return const_motion(t, y_const=1)\n else:\n return motion_equation(t)\n \n\ndef main(time):\n total_steps = int(time/dt)\n\n MAX_VELOCITY = 1.5\n MAX_ACCELERATION_TANGENTIAL = 10\n MAX_ACCELERATION_NORMAL = 6\n MAX_ACCELERATION = sqrt(MAX_ACCELERATION_TANGENTIAL**2 + MAX_ACCELERATION_NORMAL**2)\n \n traj_planner = TrapezoidalMotion_mod(max_velocity=MAX_VELOCITY, max_acceleration_normal=MAX_ACCELERATION_NORMAL, max_acceleration_tangential=MAX_ACCELERATION_TANGENTIAL, initial_pos=motion_equation(0)[1], initial_vel=0, dt=dt)\n # In this planner we don't care about the limits related to the normal or tangential acceleration which leads to not having the correct constraint to the max velocity which is function of curvature and max tangential acceleration\n traj_planner2 = VelocityTrapezoidal.TrapezoidMotion(max_velocity=MAX_VELOCITY,max_acceleration=MAX_ACCELERATION, initial_pos=motion_equation(0))\n\n\n plot_data = {\"time\": [0],\n \"pos_x_setpoint\": [0], \"pos_y_setpoint\": [motion_equation(0)[1]], \"curvature\": [traj_planner._calc_curvature()],\n \"pos_y_real\": [0],\n \"velocity\": [0], \"velocity_x\": [0], \"velocity_y\": [0], \"max_velocity\": [0],\n \"acceleration\": [0], \"acceleration_tangential\": [0], \"acceleration_normal\": [0],\n\n \"pos_y_real2\": [0],\n \"velocity2\": [0],\n \"acceleration2\": [0]}\n\n for s in range(1, total_steps):\n pos = motion_equation(s*dt)\n # pos = const_motion(s*dt)\n # pos = const_step_motion(s*dt)\n traj_planner.update(pos[1], s*dt)\n traj_planner2.update(pos[1], s*dt)\n curvature = traj_planner._calc_curvature()\n\n plot_data[\"pos_x_setpoint\"].append(pos[0])\n plot_data[\"pos_y_setpoint\"].append(pos[1])\n plot_data[\"max_velocity\"].append(traj_planner.MAX_VELOCITY_var)\n # plot_data[\"pos_y_real\"].append(traj_planner.pos)\n plot_data[\"pos_y_real\"].append(traj_planner2.pos)\n plot_data[\"velocity\"].append(traj_planner.vel)\n plot_data[\"acceleration\"].append(sqrt(traj_planner._calc_normal_acceleration()**2 + traj_planner._calc_tangential_acceleration()**2))\n plot_data[\"acceleration_tangential\"].append(traj_planner._calc_tangential_acceleration())\n plot_data[\"acceleration_normal\"].append(traj_planner._calc_normal_acceleration())\n \n plot_data[\"curvature\"].append(curvature) \n plot_data[\"time\"].append(s*dt)\n\n plotter(plot_data)\n\n\nif __name__ == \"__main__\":\n main(4)\n","sub_path":"Assignment1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49463420","text":"\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef main():\n url = \"https://movie.douban.com/cinema/later/beijing/\"\n head = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36',\n 'Referer': 'https://time.geekbang.org/column/article/101855',\n 'Connection': 'keep-alive'}\n init_page = requests.get(url,headers=head).content\n init_soup = BeautifulSoup(init_page, 'lxml')\n\n all_movies = init_soup.find('div', id=\"showing-soon\")\n for each_movie in all_movies.find_all('div', class_=\"item\"):\n all_a_tag = each_movie.find_all('a')\n all_li_tag = each_movie.find_all('li')\n\n movie_name = all_a_tag[1].text\n url_to_fetch = all_a_tag[1]['href']\n movie_date = all_li_tag[0].text\n\n response_item = requests.get(url_to_fetch,headers=head).content\n soup_item = BeautifulSoup(response_item, 'lxml')\n img_tag = soup_item.find('img')\n\n print('{} {} {}'.format(movie_name, movie_date, img_tag['src']))\n\n\nmain()\n","sub_path":"Y2021/core-python-demo/demo/douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234319646","text":"# coding: utf-8\n__author__ = \"2019/3/27 12:03\"\n__time__ = \"Quzard\"\n\n\ndef find_minimum(array):\n if len(array) == 0:\n return None\n smallest_index = 0\n smallest = array[smallest_index]\n for i in range(len(array)):\n if smallest > array[i]:\n smallest = array[i]\n smallest_index = i\n return smallest_index\n\n\ndef choose_sort(array):\n new_list = []\n for i in range(len(array)):\n new_list.append(array.pop(find_minimum(array)))\n return new_list\n","sub_path":"选择排序.py","file_name":"选择排序.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118487727","text":"\ndef standard_interpolation(dataframe, name_to_interp=None, axis=1):\n \"\"\"Interpolate data by splitting the difference between \n increment years over intermediate years\n\n Args:\n dataframe (df): dataset to interpolate\n name_to_interp (str): name of columm if dataframe has\n year index\n axis (int or str): if 1 or \"columns\" interpolate \n over column, if 0 or \"index\", \n interpolate over row\n\n\n Returns:\n dataframe [df]: dataframe with \n interpolated data\n \"\"\" \n if axis == 1 | axis == 'columns': \n if name_to_interp:\n increment_years = list(dataframe[[name_to_interp]].dropna().index)\n else:\n raise AttributeError('standard_interpolation method missing name_to_interp')\n\n elif axis == 0 | axis == 'index': \n increment_years = list(dataframe.columns)\n\n\n for index, y_ in enumerate(increment_years):\n if index > 0:\n year_before = increment_years[index - 1]\n num_years = y_ - year_before\n resid_year_before = dataframe.xs(year_before)['residual']\n resid_y_ = dataframe.xs(y_)['residual']\n increment = 1 / num_years\n for delta in range(num_years):\n value = resid_year_before * (1 - increment * delta) + \\\n resid_y_ * (increment * delta)\n year = year_before + delta\n dataframe.loc[year, 'interp_resid'] = value\n return dataframe","sub_path":"EnergyIntensityIndicators/utilites/standard_interpolation.py","file_name":"standard_interpolation.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"477862888","text":"# Authors: Avrahami Israeli (isabrah)\r\n# Python version: 3.7\r\n# Last update: 24.4.2019\r\n\r\n#! /usr/bin/env python\r\nimport os\r\nimport sys\r\nif sys.platform == 'linux':\r\n sys.path.append('/data/home/isabrah/reddit_canvas/reddit_project_with_yalla_cluster/reddit-tools')\r\nimport datetime\r\nimport commentjson\r\nimport sys\r\nimport r_place_drawing_classifier.pytorch_cnn.utils as pytorch_cnn_utils\r\nfrom srs_words_embedding.utils import sentences_yielder\r\nimport pickle\r\nfrom gensim.test.utils import common_texts, get_tmpfile\r\nfrom gensim.models import Word2Vec\r\nfrom sr_classifier.reddit_data_preprocessing import RedditDataPrep\r\nimport re\r\n\r\n###################################################### Configurations ##################################################\r\nconfig_dict = commentjson.load(open(os.path.join(os.getcwd(), 'srs_words_emnedding_config.json')))\r\nmachine = 'yalla' if sys.platform == 'linux' else os.environ['COMPUTERNAME']\r\ndata_path = config_dict['data_dir'][machine]\r\n########################################################################################################################\r\nstart_time = datetime.datetime.now()\r\npytorch_cnn_utils.set_random_seed(seed_value=config_dict[\"random_seed\"])\r\n\r\nif __name__ == \"__main__\":\r\n # update args of the configuration dictionary which can be known right as we start the run\r\n config_dict['machine'] = machine\r\n dp_obj = RedditDataPrep(is_submission_data=True, remove_stop_words=False, most_have_regex=None)\r\n sr_objects_path = os.path.join(data_path, 'sr_objects')\r\n sr_files = [f for f in os.listdir(sr_objects_path) if re.match(r'sr_obj.*\\.p', f)]\r\n # looping over all files found in the directory\r\n for loop_idx, f_name in enumerate(sr_files):\r\n cur_sr = pickle.load(open(os.path.join(sr_objects_path, f_name), \"rb\"))\r\n start_time = datetime.datetime.now()\r\n if loop_idx % 10 == 0 and loop_idx != 0:\r\n duration = (datetime.datetime.now() - start_time).seconds\r\n print(\"Finished handling {} sr objects. Took us up to now: {} sec\".format(loop_idx, duration))\r\n full_tok_text = sentences_yielder(dp_obj=dp_obj, sr_obj=cur_sr, config_dict=config_dict, verbose=True)\r\n if len(full_tok_text) < 50:\r\n print(\"sr {} has only {} sentences, skipping it\".format(cur_sr.name, len(full_tok_text)))\r\n continue\r\n model = Word2Vec(full_tok_text, size=300, window=5, min_count=3, workers=20, sg=0)\r\n model.train(sentences=full_tok_text, total_examples=model.corpus_count, epochs=model.epochs)\r\n saving_file = os.path.join(config_dict['data_dir'][machine], \"embedding\", \"embedding_per_sr\")\r\n # check if the directory exists, if not - we'll create one\r\n if not os.path.isdir(saving_file):\r\n os.makedirs(saving_file)\r\n saving_file = os.path.join(saving_file, cur_sr.name + \"_model_\" + str(config_dict[\"model_version\"] + \".model\"))\r\n model.save(saving_file)\r\n duration = (datetime.datetime.now() - start_time).seconds\r\n print(\"Model built for sr {}, corpus size: {}, time: {} sec\".format(cur_sr.name, len(model.wv.vocab), duration))\r\n # model.wv['i'] # will print the numpy vector representation of the word i\r\n # after going over all submissions, we add it to the object itself\r\n # case cv_splits were not initialized before - we'll do it here for the first time\r\n\r\n\r\n\r\n","sub_path":"srs_words_embedding/main_srs_words_embedding.py","file_name":"main_srs_words_embedding.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"88833780","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom news.models import Post\nfrom intros.models import Page\nfrom haystack.views import SearchView\nfrom search.forms import SimpleSearchForm\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'tida.views.home', name='home'),\n # url(r'^tida/', include('tida.foo.urls')),\n \n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n \n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n \n url(r'^/?$', TemplateView.as_view(template_name='index.html')),\n url(r'^account/', include('account.urls')),\n url(r'^news/', include('news.urls')),\n url(r'^contact/', include('contact.urls')),\n url(r'^search/', SearchView(form_class=SimpleSearchForm), name='haystack_search'),\n url(r'^(?P[a-z]+)/$', DetailView.as_view(model=Page,\n context_object_name=\"page\",\n template_name='intros/intro.html')),\n url(r'^dancer/', include('dancer.urls')),\n url(r'^repertory/', include('repertory.urls')),\n url(r'^collection/', include('collection.urls')),\n url(r'^video/', include('video.urls')),\n url(r'^reference/', include('reference.urls')),\n )\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n (r'%s(?P.*)' % settings.MEDIA_URL[1:], 'django.views.static.serve', \n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"tida/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100771389","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\n\n# 用tf自带波斯顿房价数据测试DNN模型\nboston=load_boston()\nprint(\"data of boston:\",boston.data.shape)\nprint(\"target of boston:\",boston.target.shape)\nboston_df = pd.DataFrame(np.c_[boston.data, boston.target], columns=np.append(boston.feature_names, 'MEDV'))\nLABEL_COLUMN = ['MEDV']\nFEATURE_COLUMNS = [f for f in boston_df if not f in LABEL_COLUMN]\n\nx_train, x_test, y_train, y_test = train_test_split(boston_df[FEATURE_COLUMNS], boston_df[LABEL_COLUMN], test_size=0.3)\nprint(' 训练集:{}\\n 测试集:{}'.format(x_train.shape, x_test.shape))\n\n\nfeature_columns = [tf.contrib.layers.real_valued_column(k) for k in FEATURE_COLUMNS]\nregressor = tf.contrib.learn.DNNRegressor(feature_columns=feature_columns,\n hidden_units=[64, 128],\n model_dir='E:/tensorflow/tmp/test1')\n\ndef input_fn(df, label):\n feature_cols = {k: tf.constant(df[k].values) for k in FEATURE_COLUMNS}\n label = tf.constant(label.values)\n return feature_cols, label\n\ndef train_input_fn():\n '''训练阶段使用的 input_fn'''\n return input_fn(x_train, y_train)\n\ndef test_input_fn():\n '''测试阶段使用的 input_fn'''\n return input_fn(x_test, y_test)\n\nregressor.fit(input_fn=train_input_fn, steps=5000)\nev = regressor.evaluate(input_fn=test_input_fn, steps=1)\nprint('ev: {}'.format(ev))\npredict = regressor.predict(input_fn=test_input_fn, as_iterable=False)\nprint('预测值: %s' % predict[:10])\nprint('实际值: %s'% y_test[:10])\n\n\n","sub_path":"tensorflow-nn-2.py","file_name":"tensorflow-nn-2.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364113132","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .forms import ScannerUploadForm\nfrom .models import File\n\n# Create your views here.\ndef scan(request):\n\treturn render(request, 'scan.html')\n\ndef scan_pdf_to_form(request):\n\tcontext = {}\n\tform = ScannerUploadForm(request.POST or None)\n\tif request.method == \"POST\":\n\t\tfiles = request.FILES.getlist('com_asprise_scannerjs_images[]')\n\t\tif form.is_valid() and len(files) <= 5:\n\t\t\tform_data = form.save(commit=False)\n\t\t\tform_data.save()\n\t\t\tfor chunk in files:\n\t\t\t\tfile = File()\n\t\t\t\tfile.uploader = form_data\n\t\t\t\tfile.image = chunk\n\t\t\t\tfile.save()\n\n\tcontext['form'] = form\n\treturn render(request, 'scan_pdf_to_form.html', context)\n","sub_path":"uploader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304231493","text":"class Node:\r\n def __init__(self, data):\r\n self.val = data\r\n self.left = None\r\n self.right = None\r\n\r\n\r\ndef lca(root, v1, v2):\r\n if root == None:\r\n return root\r\n if root.val == v1 or root.val == v2:\r\n return root\r\n left = lca(root.left, v1, v2)\r\n right = lca(root.right, v1, v2)\r\n\r\n if left != None and right != None:\r\n return root\r\n else:\r\n if left != None:\r\n return left\r\n elif right != None:\r\n return right\r\n\r\n\r\nroot = Node(4)\r\nroot.left = Node(2)\r\nroot.right = Node(7)\r\nroot.left.left = Node(1)\r\nroot.left.right = Node(3)\r\nroot.right.left = Node(6)\r\n\r\nancestor = lca(root, 1, 7)\r\nprint(ancestor.val)\r\n","sub_path":"tree/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283744583","text":"def test_connect(connection, events, writer, schedule, flush):\n \"\"\" Connection.Connect opens a writer, triggers CLIENT_CONNECT \"\"\"\n schedule(connection.connect())\n flush()\n assert connection.connected\n assert not writer.closed\n assert events.triggered(\"CLIENT_CONNECT\")\n\n\ndef test_already_connected(connection, events, writer, schedule, flush):\n \"\"\" Does not trigger CLIENT_CONNECT multiple times \"\"\"\n schedule(connection.connect(), connection.connect())\n flush()\n assert not writer.closed\n assert events.triggered(\"CLIENT_CONNECT\")\n\n\ndef test_disconnect_before_connect(connection, events, schedule, flush):\n \"\"\" disconnect before connect does nothing \"\"\"\n schedule(connection.disconnect())\n flush()\n assert not connection.connected\n assert not events.triggered(\"CLIENT_CONNECT\")\n assert not events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_disconnect(writer, patch_connection, events, connection,\n schedule, flush):\n \"\"\" Connection.disconnect closes writer, triggers CLIENT_DISCONNECT \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n assert not connection.connected\n assert writer.closed\n assert connection.writer is None\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_already_disconnected(connection, events, schedule, flush):\n \"\"\" Does not trigger CLIENT_DISCONNECT multiple times \"\"\"\n schedule(connection.connect(),\n connection.disconnect(),\n connection.disconnect())\n flush()\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_send_before_connected(connection, writer):\n \"\"\" Nothing happens when sending before connecting \"\"\"\n assert not connection.connected\n connection.send(\"test\")\n assert not writer.used\n\n\ndef test_send_disconnected(connection, writer, schedule, flush):\n \"\"\" Nothing happens when sending after disconnecting \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n connection.send(\"test\")\n assert not writer.used\n\n\ndef test_send_strips(connection, writer, loop):\n \"\"\" Send strips whitespace from string \"\"\"\n loop.run_until_complete(connection.connect())\n connection.send(\" a b c | @#$ d \")\n assert writer.used\n assert writer.has_written(\"a b c | @#$ d\\n\")\n\n\ndef test_read_before_connected(connection, reader, loop):\n \"\"\" Nothing happens when reading before connecting \"\"\"\n value = loop.run_until_complete(connection.read())\n assert not value\n assert not reader.used\n\n\ndef test_read_disconnected(connection, reader, schedule, flush, loop):\n \"\"\" Nothing happens when reading after disconnecting \"\"\"\n schedule(connection.connect(), connection.disconnect())\n flush()\n value = loop.run_until_complete(connection.read())\n assert not value\n assert not reader.used\n\n\ndef test_read_eoferror(connection, reader, loop):\n \"\"\" Nothing to read \"\"\"\n loop.run_until_complete(connection.connect())\n value = loop.run_until_complete(connection.read())\n assert not value\n assert reader.used\n\n\ndef test_read_strips(connection, reader, loop):\n \"\"\" newline and space characters are stripped off \"\"\"\n reader.push(\" a b c | @#$ d \\n\")\n loop.run_until_complete(connection.connect())\n value = loop.run_until_complete(connection.read())\n assert value == \"a b c | @#$ d\"\n assert reader.has_read(\" a b c | @#$ d \\n\")\n\n\ndef test_run_without_message(connection, events, loop):\n \"\"\" Connection.run should connect, read empty, disconnect, return \"\"\"\n loop.run_until_complete(connection.run())\n assert events.triggered(\"CLIENT_CONNECT\")\n assert events.triggered(\"CLIENT_DISCONNECT\")\n\n\ndef test_run_trigger_command(connection, reader, events, eventparams, loop):\n eventparams[\"PRIVMSG\"] = [\"nick\", \"user\", \"host\", \"target\", \"message\"]\n reader.push(\":nick!user@host PRIVMSG #target :this is message\")\n received = []\n\n @events.on(\"PRIVMSG\")\n def receive(nick, user, host, target, message):\n received.extend([nick, user, host, target, message])\n\n loop.run_until_complete(connection.run())\n assert reader.has_read(\":nick!user@host PRIVMSG #target :this is message\")\n assert events.triggered(\"PRIVMSG\")\n assert received == [\"nick\", \"user\", \"host\", \"#target\", \"this is message\"]\n\n\ndef test_run_trigger_unknown_command(connection, reader, events, loop):\n reader.push(\"unknown_command\")\n loop.run_until_complete(connection.run())\n\n assert reader.has_read(\"unknown_command\")\n assert not events.triggered(\"unknown_command\")\n","sub_path":"tests/test_connection.py","file_name":"test_connection.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"112125138","text":"## Model parameters\nmodel_hidden_size = 256\nmodel_embedding_size = 256\nmodel_num_layers = 3\n\n\n## Training parameters\nlearning_rate_init = 1e-4\nspeakers_per_batch = 64\nutterances_per_speaker = 10\n\n## Mel-filterbank\nmel_window_length = 25 # In milliseconds\nmel_window_step = 10 # In milliseconds\nmel_n_channels = 40\n\n\n## Audio\nsampling_rate = 16000\n# Number of spectrogram frames in a partial utterance\npartials_n_frames = 160 # 1600 ms\n# Number of spectrogram frames at inference\ninference_n_frames = 80 # 800 ms\n\n\n## Voice Activation Detection\n# Window size of the VAD. Must be either 10, 20 or 30 milliseconds.\n# This sets the granularity of the VAD. Should not need to be changed.\nvad_window_length = 30 # In milliseconds\n# Number of frames to average together when performing the moving average smoothing.\n# The larger this value, the larger the VAD variations must be to not get smoothed out.\nvad_moving_average_width = 8\n# Maximum number of consecutive silent frames a segment can have.\nvad_max_silence_length = 6\n\n\n## Audio volume normalization\naudio_norm_target_dBFS = -30\n\nlibrispeech_datasets = {\n \"train\": {\n \"clean\": [\"LibriSpeech/train-clean-100\", \"LibriSpeech/train-clean-360\"],\n \"other\": [\"LibriSpeech/train-other-500\"]\n },\n \"test\": {\n \"clean\": [\"LibriSpeech/test-clean\"],\n \"other\": [\"LibriSpeech/test-other\"]\n },\n \"dev\": {\n \"clean\": [\"LibriSpeech/dev-clean\"],\n \"other\": [\"LibriSpeech/dev-other\"]\n },\n}\nlibritts_datasets = {\n \"train\": {\n \"clean\": [\"LibriTTS/train-clean-100\", \"LibriTTS/train-clean-360\"],\n \"other\": [\"LibriTTS/train-other-500\"]\n },\n \"test\": {\n \"clean\": [\"LibriTTS/test-clean\"],\n \"other\": [\"LibriTTS/test-other\"]\n },\n \"dev\": {\n \"clean\": [\"LibriTTS/dev-clean\"],\n \"other\": [\"LibriTTS/dev-other\"]\n },\n}\nvoxceleb_datasets = {\n \"voxceleb1\" : {\n \"train\": [\"VoxCeleb1/wav\"],\n \"test\": [\"VoxCeleb1/test_wav\"]\n },\n \"voxceleb2\" : {\n \"train\": [\"VoxCeleb2/dev/aac\"],\n \"test\": [\"VoxCeleb2/test_wav\"]\n }\n}\n\nother_datasets = [\n \"LJSpeech-1.1\",\n \"VCTK-Corpus/wav48\",\n]\n\nanglophone_nationalites = [\"australia\", \"canada\", \"ireland\", \"uk\", \"usa\"]\n","sub_path":"encoder/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"129996469","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom numpy import *\n\nclass KnnClassifier(object):\n\n def __init__(self,labels,samples):\n \"\"\" 教師データを使って分類器を初期化する \"\"\"\n\n self.labels = labels\n self.samples = samples\n\n def classify(self,point,k=3):\n \"\"\" pointを教師データ中のk個の最近傍を使って分類し、\n ラベルを返す \"\"\"\n\n # 全教師データへの距離を計算する\n dist = array([L2dist(point,s) for s in self.samples])\n\n # ソートする\n ndx = dist.argsort()\n\n # k個の最近傍を保持するのに辞書を用いる\n votes = {}\n for i in range(k):\n label = self.labels[ndx[i]]\n votes.setdefault(label,0)\n votes[label] += 1\n\n return max(votes, key=lambda x: votes.get(x))\n\ndef L2dist(p1,p2):\n return sqrt( sum( (p1-p2)**2) )\n","sub_path":"sample_code/chap8/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443322645","text":"import tkinter as tk\n\nfrom tkinter import filedialog\nfrom tkinter import *\nfrom tkinter import TOP, E\n\nfrom Client import menu\n\n\nclass UploadPage(tk.Frame):\n def __init__(self, frame, gui):\n # parameter: frame\n # parameter: gui\n\n \"\"\"\n Init the frame.\n \"\"\"\n tk.Frame.__init__(self, frame)\n\n \"\"\"\n Creates a Label to display 'Upload'.\n \"\"\"\n label = tk.Label(self, text=\"Upload\")\n label.pack(side=TOP)\n\n # Frame used for organization\n top = tk.Frame(self)\n top.pack(side=TOP)\n\n # Frame used for organization\n bottom = tk.Frame(self)\n bottom.pack(side=TOP)\n\n \"\"\"\n Creates a Label to display 'Filename'.\n \"\"\"\n filenameText = tk.Label(top, text=\"Filename\")\n filenameText.grid(row=0, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the name of the file.\n \"\"\"\n self.filenameInput = tk.Entry(top)\n self.filenameInput.grid(row=0, column=1)\n\n \"\"\"\n Creates a Label to display 'Category'.\n \"\"\"\n categoryText = tk.Label(top, text=\"Category\")\n categoryText.grid(row=1, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the category of the file.\n \"\"\"\n self.categoryInput = tk.Entry(top)\n self.categoryInput.grid(row=1, column=1)\n\n \"\"\"\n Creates a Label to display 'Keywords'.\n \"\"\"\n keywordsText = tk.Label(top, text=\"Keywords\")\n keywordsText.grid(row=2, sticky=E)\n\n \"\"\"\n Creates a Entry to display a textbox for the client to enter the keywords of the file.\n \"\"\"\n self.keywordsInput = tk.Entry(top)\n self.keywordsInput.grid(row=2, column=1)\n\n \"\"\"\n Creates and adds a upload button.\n Takes all text the client enters and\n uploads the file with the corresponding information.\n \"\"\"\n uploadButton = tk.Button(bottom, text=\"Upload\",\n command=lambda: self.upload(gui,\n self.filenameInput.get(),\n self.categoryInput.get(),\n self.keywordsInput.get()))\n uploadButton.grid(row=0)\n\n \"\"\"\n Creates and adds a back button.\n Takes the client back to menu page when clicked on.\n \"\"\"\n backButton = tk.Button(bottom, text=\"Back\",\n command=lambda: self.back(gui))\n backButton.grid(row=0, column=1)\n\n def upload(self, gui, filename, category, keywords):\n gui.filename = filedialog.askopenfilename(initialdir=\"/\", title=\"Select file\")\n print(gui.filename)\n self.filenameInput.insert(0, gui.filename)\n response = gui.getClient().upload(filename, category, keywords)\n\n # self.filenameInput.delete(0, 'end')\n # self.categoryInput.delete(0, 'end')\n # self.keywordsInput.delete(0, 'end')\n\n def back(self, gui):\n # parameter: gui -> The GUI that is being used.\n\n \"\"\"\n Empties the textboxes before heading back to the starting page.\n \"\"\"\n self.filenameInput.delete(0, 'end')\n self.categoryInput.delete(0, 'end')\n self.keywordsInput.delete(0, 'end')\n\n \"\"\"\n Goes back to the starting page.\n \"\"\"\n gui.show_frame(menu.MenuPage)\n","sub_path":"Client/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"81638474","text":"from flask import Flask\nfrom webargs import fields\nfrom webargs.flaskparser import use_kwargs\n\napp = Flask(__name__)\n\n\n# @app.route(\"//\")\n# @use_kwargs({'name': fields.Str(required=False,location='query'), 'name0': fields.Str(required=False,location='query')})\n# def index( lang_code, **kargs):\n# print('#'*10, kargs)\n\n# return \"Hello \" + lang_code\n\n# from webargs import fields\n# from webargs.flaskparser import use_args\n\n# http://127.0.0.1:5000/user/1?per_page=101\n@app.route('/user/')\n@use_kwargs({'per_page': fields.Int(missing=100)}, location=\"query\")\ndef user_detail(per_page, uid):\n return ('The user page for user {uid}, '\n 'showing {per_page} posts.').format(uid=uid,\n per_page=per_page)\n\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"i03Python-API-Development-Fundamentals/ch6email_confirmation/i3webargs_demo.py","file_name":"i3webargs_demo.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"181157983","text":"#!/usr/env/bin python3\n#-*-encoding:utf-8-*-\n\nfrom multiprocessing import Process\nimport os\n\ndef run_proc(name):\n print('Run child process %s(%s)'%(name, os.getpid()))\n\nif __name__ == '__main__':\n print('Parent process %s'% os.getpid())\n i = 10\n while i > 0 :\n p = Process(target=run_proc, args=('test%d'%i,))\n p.start()\n i = i - 1\n print('Child process end')","sub_path":"multithread/multidemo.py","file_name":"multidemo.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302539581","text":"import re\nimport os\nimport json\nimport jose\nimport time\nimport requests\nfrom http import HTTPStatus\nfrom jose import jwk, jwt\nfrom jose.utils import base64url_decode\n\n\ndef lambda_handler(event, context):\n region = os.environ['AWS_DEFAULT_REGION']\n user_pool_id = os.environ['USER_POOL_ID']\n client_id = os.environ['CLIENT_ID']\n account_id = event['requestContext']['accountId']\n api_id = event['requestContext']['apiId']\n stage = event['requestContext']['stage']\n print(f'region:{region}, account_id:{account_id}, api_id:{api_id}, stage:{stage}, user_pool_id:{user_pool_id}')\n\n policy = AuthPolicy('', account_id)\n policy.region = region\n policy.restApiId = api_id\n policy.stage = stage\n\n try:\n # Validate IdToken\n token = event['headers']['Authorization']\n user_agent = event['headers']['User-Agent']\n validate_token(token, region, user_pool_id, client_id, user_agent)\n\n # Allow user to call APIGateway.\n policy.allowAllMethods()\n response = policy.build()\n print(response)\n return response\n except InvalidTokenError as e:\n policy.denyAllMethods()\n response = policy.build()\n response['context'] = {'message': e}\n print(response)\n return response\n except Exception as e:\n raise e\n\n\ndef validate_token(token: str, region: str, user_pool_id: str, client_id: str, user_agent: str):\n # Validate whether to match local public key and remote one.\n keys_url = f'https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json'\n headers = jwt.get_unverified_headers(token)\n print(f'token:{token}')\n\n response = requests.get(keys_url)\n keys = json.loads(response.text)['keys']\n target_key = None\n for key in keys:\n if key['kid'] == headers['kid']:\n target_key = key\n if target_key is None:\n raise InvalidTokenError('Invalid public key in headers.')\n\n # Validate signature of JWT.\n public_key = jwk.construct(target_key)\n print(f'public_key:{public_key}')\n message = token.rsplit('.', 1)[0].encode('utf-8') # message = header + payload\n signature = token.rsplit('.', 1)[1].encode('utf-8')\n decode_signature = base64url_decode(signature)\n print(f'message:{message}')\n print(f'signature:{signature}')\n print(f'decode_signature:{decode_signature}')\n\n if not public_key.verify(message, decode_signature):\n raise InvalidTokenError('Invalid token signature.')\n\n # Validate expire of JWT.\n claims = jwt.get_unverified_claims(token)\n if time.time() > claims['exp']:\n raise InvalidTokenError('Token is expired.')\n\n # Validate aud claim which includes Client ID in Cognito.\n if claims['aud'] != client_id:\n raise InvalidTokenError('Invalid aud(Cognito Client ID).')\n\n # Validate UserAgent in header. This is allowed cognito-authorizer only.\n if user_agent != 'cognito-authorizer':\n raise InvalidTokenError('Invalid UserAgent.')\n\n\nclass InvalidTokenError(Exception):\n pass\n\n\nclass HttpVerb:\n GET = 'GET'\n POST = 'POST'\n PUT = 'PUT'\n PATCH = 'PATCH'\n HEAD = 'HEAD'\n DELETE = 'DELETE'\n OPTIONS = 'OPTIONS'\n ALL = '*'\n\n\nclass AuthPolicy(object):\n # The AWS account id the policy will be generated for. This is used to create the method ARNs.\n awsAccountId = ''\n # The principal used for the policy, this should be a unique identifier for the end user.\n principalId = ''\n # The policy version used for the evaluation. This should always be '2012-10-17'\n version = '2012-10-17'\n # The regular expression used to validate resource paths for the policy\n pathRegex = '^[/.a-zA-Z0-9-\\*]+$'\n\n '''Internal lists of allowed and denied methods.\n\n These are lists of objects and each object has 2 properties: A resource\n ARN and a nullable conditions statement. The build method processes these\n lists and generates the approriate statements for the final policy.\n '''\n allowMethods = []\n denyMethods = []\n\n # The API Gateway API id. By default this is set to '*'\n restApiId = '*'\n # The region where the API is deployed. By default this is set to '*'\n region = '*'\n # The name of the stage used in the policy. By default this is set to '*'\n stage = '*'\n\n def __init__(self, principal, awsAccountId):\n self.awsAccountId = awsAccountId\n self.principalId = principal\n self.allowMethods = []\n self.denyMethods = []\n\n def _addMethod(self, effect, verb, resource, conditions):\n '''Adds a method to the internal lists of allowed or denied methods. Each object in\n the internal list contains a resource ARN and a condition statement. The condition\n statement can be null.'''\n if verb != '*' and not hasattr(HttpVerb, verb):\n raise NameError('Invalid HTTP verb ' + verb + '. Allowed verbs in HttpVerb class')\n resourcePattern = re.compile(self.pathRegex)\n if not resourcePattern.match(resource):\n raise NameError('Invalid resource path: ' + resource + '. Path should match ' + self.pathRegex)\n\n if resource[:1] == '/':\n resource = resource[1:]\n\n resourceArn = 'arn:aws:execute-api:{}:{}:{}/{}/{}/{}'.format(self.region, self.awsAccountId, self.restApiId, self.stage, verb, resource)\n\n if effect.lower() == 'allow':\n self.allowMethods.append({\n 'resourceArn': resourceArn,\n 'conditions': conditions\n })\n elif effect.lower() == 'deny':\n self.denyMethods.append({\n 'resourceArn': resourceArn,\n 'conditions': conditions\n })\n\n def _getEmptyStatement(self, effect):\n '''Returns an empty statement object prepopulated with the correct action and the\n desired effect.'''\n statement = {\n 'Action': 'execute-api:Invoke',\n 'Effect': effect[:1].upper() + effect[1:].lower(),\n 'Resource': []\n }\n\n return statement\n\n def _getStatementForEffect(self, effect, methods):\n '''This function loops over an array of objects containing a resourceArn and\n conditions statement and generates the array of statements for the policy.'''\n statements = []\n\n if len(methods) > 0:\n statement = self._getEmptyStatement(effect)\n\n for curMethod in methods:\n if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:\n statement['Resource'].append(curMethod['resourceArn'])\n else:\n conditionalStatement = self._getEmptyStatement(effect)\n conditionalStatement['Resource'].append(curMethod['resourceArn'])\n conditionalStatement['Condition'] = curMethod['conditions']\n statements.append(conditionalStatement)\n\n if statement['Resource']:\n statements.append(statement)\n\n return statements\n\n def allowAllMethods(self):\n '''Adds a '*' allow to the policy to authorize access to all methods of an API'''\n self._addMethod('Allow', HttpVerb.ALL, '*', [])\n\n def denyAllMethods(self):\n '''Adds a '*' allow to the policy to deny access to all methods of an API'''\n self._addMethod('Deny', HttpVerb.ALL, '*', [])\n\n def allowMethod(self, verb, resource):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed\n methods for the policy'''\n self._addMethod('Allow', verb, resource, [])\n\n def denyMethod(self, verb, resource):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of denied\n methods for the policy'''\n self._addMethod('Deny', verb, resource, [])\n\n def allowMethodWithConditions(self, verb, resource, conditions):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of allowed\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''\n self._addMethod('Allow', verb, resource, conditions)\n\n def denyMethodWithConditions(self, verb, resource, conditions):\n '''Adds an API Gateway method (Http verb + Resource path) to the list of denied\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition'''\n self._addMethod('Deny', verb, resource, conditions)\n\n def build(self):\n '''Generates the policy document based on the internal lists of allowed and denied\n conditions. This will generate a policy with two main statements for the effect:\n one statement for Allow and one statement for Deny.\n Methods that includes conditions will have their own statement in the policy.'''\n if ((self.allowMethods is None or len(self.allowMethods) == 0) and\n (self.denyMethods is None or len(self.denyMethods) == 0)):\n raise NameError('No statements defined for the policy')\n\n policy = {\n 'principalId': self.principalId,\n 'policyDocument': {\n 'Version': self.version,\n 'Statement': []\n }\n }\n\n policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Allow', self.allowMethods))\n policy['policyDocument']['Statement'].extend(self._getStatementForEffect('Deny', self.denyMethods))\n\n return policy\n","sub_path":"custom-authorizar/authorizer.py","file_name":"authorizer.py","file_ext":"py","file_size_in_byte":9668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"216327799","text":"#---------------\n# Display Test Results\n#-----------\n# Run configuration for each query\ndef get_test_results(hs, qcxs, qdat, cfgx=0, nCfg=1, nocache_testres=False,\n test_results_verbosity=2):\n nQuery = len(qcxs)\n dcxs = hs.get_indexed_sample()\n test_uid = qdat.get_query_uid(hs, qcxs)\n cache_dir = join(hs.dirs.cache_dir, 'experiment_harness_results')\n io_kwargs = dict(dpath=cache_dir, fname='test_results', uid=test_uid,\n ext='.cPkl')\n\n if test_results_verbosity == 2:\n print('[harn] test_uid = %r' % test_uid)\n\n # High level caching\n if not params.args.nocache_query and (not nocache_testres):\n qx2_bestranks = io.smart_load(**io_kwargs)\n if qx2_bestranks is None:\n print('[harn] qx2_bestranks cache returned None!')\n elif len(qx2_bestranks) != len(qcxs):\n print('[harn] Re-Caching qx2_bestranks')\n elif not qx2_bestranks is None:\n return qx2_bestranks, [[{0: None}]] * nQuery\n #raise Exception('cannot be here')\n mc3.ensure_nn_index(hs, qdat, dcxs)\n nPrevQ = nQuery * cfgx\n qx2_bestranks = []\n\n # Make progress message\n msg = textwrap.dedent('''\n ---------------------\n [harn] TEST %d/%d\n ---------------------''')\n mark_progress = util.simple_progres_func(test_results_verbosity, msg, '.')\n total = nQuery * nCfg\n # Perform queries\n TEST_INFO = True\n # Query Chip / Row Loop\n for qx, qcx in enumerate(qcxs):\n count = qx + nPrevQ + 1\n mark_progress(count, total)\n if TEST_INFO:\n print('qcx=%r. quid=%r' % (qcx, qdat.get_uid()))\n try:\n res_list = mc3.execute_query_safe(hs, qdat, [qcx], dcxs)\n except mf.QueryException as ex:\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n print('Harness caught Query Exception: ')\n print(ex)\n print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n if params.args.strict:\n raise\n else:\n qx2_bestranks += [[-1]]\n continue\n\n assert len(res_list) == 1\n bestranks = []\n for qcx2_res in res_list:\n assert len(qcx2_res) == 1\n res = qcx2_res[qcx]\n gt_ranks = res.get_gt_ranks(hs=hs)\n #print('[harn] cx_ranks(/%4r) = %r' % (nChips, gt_ranks))\n #print('[harn] cx_ranks(/%4r) = %r' % (NMultiNames, gt_ranks))\n #print('ns_ranks(/%4r) = %r' % (nNames, gt_ranks))\n _bestrank = -1 if len(gt_ranks) == 0 else min(gt_ranks)\n bestranks += [_bestrank]\n # record metadata\n qx2_bestranks += [bestranks]\n if qcx % 4 == 0:\n sys.stdout.flush()\n print('')\n qx2_bestranks = np.array(qx2_bestranks)\n # High level caching\n util.ensuredir(cache_dir)\n io.smart_save(qx2_bestranks, **io_kwargs)\n\n return qx2_bestranks\n\n","sub_path":"_graveyard/get_test_results.py","file_name":"get_test_results.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116888752","text":"from django.urls import path\nfrom .views import HomeView, customerProfile, productList, createProduct, update_product, delete_product, registerPage, loginPage, logoutUser, userPage, customerList, orderList, shippingAddress, billingAddress, adminAccount\n\napp_name = 'dashboard'\n\nurlpatterns = [\n path('dashboard/', HomeView, name=\"dashboard-home\"),\n path('dashboard/customer-profile//', customerProfile, name=\"customer-profile\"),\n path('dashboard/product-list/', productList, name=\"dashboard-product-list\"),\n path('dashboard/create-product/', createProduct.as_view(), name=\"create-product\"),\n path('dashboard/update-product//', update_product, name=\"update-product\"),\n path('dashboard/delete-product//', delete_product, name=\"delete-product\"),\n\n path('dashboard/customer-list/', customerList, name=\"customer-list\"),\n path('dashboard/order-list/', orderList, name=\"order-list\"),\n\n path('dashboard/register/', registerPage, name=\"dashboard-register\"),\n path('dashboard/login/', loginPage, name=\"dashboard-login\"),\n path('dashboard/logout/', logoutUser, name=\"dashboard-logout\"),\n\n path('dashboard/account/', adminAccount, name=\"dashboard-account\"),\n\n path('dashboard/user-page/', userPage.as_view(), name=\"user-page\"),\n\n path('shipping-address//', shippingAddress, name=\"shipping-address\"),\n path('billing-address//', billingAddress, name=\"billing-address\"),\n]","sub_path":"dashboard/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339133519","text":"import typing\n\nfrom napari.utils.colormaps.colormap import Colormap\nfrom napari.utils.colormaps.colormap_utils import AVAILABLE_COLORMAPS\nfrom pydantic import Field\n\nfrom PartSegCore.color_image.color_data import sitk_labels\nfrom PartSegCore.utils import BaseModel\n\nNum = typing.Union[int, float]\n\n\nclass Color(BaseModel):\n \"\"\"\n store color information\n\n :param red: red color value\n :param green: green color value\n :param blue: blue color value\n :param alpha: alpha value\n \"\"\"\n\n red: float = Field(ge=0.0, le=1.0)\n green: float = Field(ge=0.0, le=1.0)\n blue: float = Field(ge=0.0, le=1.0)\n alpha: float = Field(1, ge=0.0, le=1.0)\n\n def as_tuple(self):\n return (self.red, self.green, self.blue, self.alpha)\n\n @classmethod\n def from_tuple(cls, tup):\n \"\"\"\n create color from tuple\n\n :param tup: tuple of color values\n :return: color\n \"\"\"\n return cls(red=tup[0], green=tup[1], blue=tup[2], alpha=tup[3] if len(tup) > 3 else 1)\n\n def is_close(self, other: \"Color\", epsilon: float = 1e-6) -> bool:\n \"\"\"\n check if color is close to other color\n\n :param other: other color\n :param epsilon: epsilon value\n :return: True if colors are close\n \"\"\"\n return (\n abs(self.red - other.red) < epsilon\n and abs(self.green - other.green) < epsilon\n and abs(self.blue - other.blue) < epsilon\n and abs(self.alpha - other.alpha) < epsilon\n )\n\n\nstarting_colors = [\"red\", \"green\", \"blue\", \"magenta\", \"inferno\", \"magma\"]\n\ndefault_colormap_dict = {name: AVAILABLE_COLORMAPS[name] for name in starting_colors}\ndefault_colormap_dict.update(AVAILABLE_COLORMAPS)\ndefault_colormap_dict.update(\n {\n f\"{k}_reversed\": Colormap(v.colors[::-1], controls=1 - v.controls[::-1])\n for k, v in AVAILABLE_COLORMAPS.items()\n if not k.endswith(\"_k\")\n }\n)\n\n\ndefault_label_dict = {\"default\": sitk_labels}\n","sub_path":"package/PartSegCore/color_image/base_colors.py","file_name":"base_colors.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"380578834","text":"from selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nimport time\r\n\r\n\r\nclass WebDriver(object):\r\n def __init__(self, proxy):\r\n self.PROXY = proxy\r\n options = webdriver.ChromeOptions()\r\n # options.add_argument('headless') # Запускаем бразуер бещ GUI (без графичиской оболочки)\r\n options.add_argument(r\"user-data-dir=C:\\Users\\moonz\\AppData\\Local\\Google\\Chrome\")\r\n options.add_argument('--proxy-server=%s' % self.PROXY)\r\n self.driver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\", chrome_options=options)\r\n\r\n\r\n def start(self):\r\n try:\r\n self.driver.get(\"https://yandex.ru/internet/\")\r\n time.sleep(10)\r\n except Exception as error:\r\n print(error)\r\n\r\n finally:\r\n self.driver.close()\r\n time.sleep(2)\r\n self.driver.quit()\r\n time.sleep(2)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nPROXY = '167.99.158.48:443' # Работает только с HTTPS\r\na = WebDriver(PROXY)\r\na.start()\r\n","sub_path":"SEO/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588554084","text":"import numpy as np\nimport wandb\n\n\ndef reset_trackers(jumps):\n trackers = dict()\n trackers[\"epoch_losses\"] = np.zeros(jumps + 1)\n trackers[\"value_losses\"] = np.zeros(jumps + 1)\n trackers[\"policy_losses\"] = np.zeros(jumps + 1)\n trackers[\"reward_losses\"] = np.zeros(jumps + 1)\n trackers[\"nce_losses\"] = np.zeros(jumps + 1)\n trackers[\"nce_accs\"] = np.zeros(jumps + 1)\n trackers[\"value_errors\"] = np.zeros(jumps + 1)\n trackers[\"reward_errors\"] = np.zeros(jumps + 1)\n trackers[\"mean_pred_values\"] = np.zeros(jumps + 1)\n trackers[\"mean_pred_rewards\"] = np.zeros(jumps + 1)\n trackers[\"mean_target_values\"] = np.zeros(jumps + 1)\n trackers[\"mean_target_rewards\"] = np.zeros(jumps + 1)\n trackers[\"pred_entropy\"] = np.zeros(jumps + 1)\n trackers[\"target_entropy\"] = np.zeros(jumps + 1)\n trackers[\"iterations\"] = np.zeros(1)\n\n return trackers\n\n\ndef update_trackers(trackers,\n reward_losses,\n nce_losses,\n nce_accs,\n policy_losses,\n value_losses,\n epoch_losses,\n value_errors,\n reward_errors,\n pred_values,\n pred_rewards,\n target_values,\n target_rewards,\n pred_entropy,\n target_entropy):\n trackers[\"iterations\"] += 1\n trackers[\"nce_losses\"] += np.array(nce_losses)\n trackers[\"nce_accs\"] += np.array(nce_accs)\n trackers[\"reward_losses\"] += np.array(reward_losses)\n trackers[\"policy_losses\"] += np.array(policy_losses)\n trackers[\"value_losses\"] += np.array(value_losses)\n trackers[\"epoch_losses\"] += np.array(epoch_losses)\n trackers[\"value_errors\"] += np.array(value_errors)\n trackers[\"reward_errors\"] += np.array(reward_errors)\n trackers[\"mean_pred_values\"] += np.array(pred_values)\n trackers[\"mean_pred_rewards\"] += np.array(pred_rewards)\n trackers[\"mean_target_values\"] += np.array(target_values)\n trackers[\"mean_target_rewards\"] += np.array(target_rewards)\n trackers[\"pred_entropy\"] += np.array(pred_entropy)\n trackers[\"target_entropy\"] += np.array(target_entropy)\n\n\ndef summarize_trackers(trackers):\n iterations = trackers[\"iterations\"]\n nce_losses = np.array(trackers[\"nce_losses\"] / iterations)\n nce_accs = np.array(trackers[\"nce_accs\"] / iterations)\n reward_losses = np.array(trackers[\"reward_losses\"] / iterations)\n policy_losses = np.array(trackers[\"policy_losses\"] / iterations)\n value_losses = np.array(trackers[\"value_losses\"] / iterations)\n epoch_losses = np.array(trackers[\"epoch_losses\"] / iterations)\n value_errors = np.array(trackers[\"value_errors\"] / iterations)\n reward_errors = np.array(trackers[\"reward_errors\"] / iterations)\n pred_values = np.array(trackers[\"mean_pred_values\"] / iterations)\n pred_rewards = np.array(trackers[\"mean_pred_rewards\"] / iterations)\n target_values = np.array(trackers[\"mean_target_values\"] / iterations)\n target_rewards = np.array(trackers[\"mean_target_rewards\"] / iterations)\n pred_entropy = np.array(trackers[\"pred_entropy\"] / iterations)\n target_entropy = np.array(trackers[\"target_entropy\"] / iterations)\n\n return nce_losses, nce_accs, reward_losses, value_losses, policy_losses, \\\n epoch_losses, value_errors, reward_errors, pred_values, \\\n target_values, pred_rewards, target_rewards, pred_entropy, \\\n target_entropy\n\n\ndef log_results(trackers,\n steps,\n prefix='train',\n verbose_print=True,):\n\n iterations = trackers[\"iterations\"]\n if iterations == 0:\n # We did nothing since the last log, so just quit.\n return\n\n nce_losses, nce_accs, reward_losses, value_losses, policy_losses, \\\n epoch_losses, value_errors, reward_errors, pred_values, target_values,\\\n pred_rewards, target_rewards, pred_entropies, target_entropies = summarize_trackers(trackers)\n\n print(\n \"{} Epoch: {}, Epoch L.: {:.3f}, NCE L.: {:.3f}, NCE A.: {:.3f}, Rew. L.: {:.3f}, Policy L.: {:.3f}, Val L.: {:.3f}, Rew. E.: {:.3f}, P. Rews {:.3f}, T._Rs. {:.3f}, Val E.: {:.3f}, P. Vs. {:.3f}, T._Vs. {:.3f}, P. Ents. {:.3f}, T. Ents. {:.3f}\".format(\n prefix.capitalize(),\n steps,\n np.mean(epoch_losses),\n np.mean(nce_losses),\n np.mean(nce_accs),\n np.mean(reward_losses),\n np.mean(policy_losses),\n np.mean(value_losses),\n np.mean(reward_errors),\n np.mean(pred_rewards),\n np.mean(target_rewards),\n np.mean(value_errors),\n np.mean(pred_values),\n np.mean(target_values),\n np.mean(pred_entropies),\n np.mean(target_entropies),\n ))\n\n for i in range(len(epoch_losses)):\n jump = i\n if verbose_print:\n print(\n \"{} Jump: {}, Epoch L.: {:.3f}, NCE L.: {:.3f}, NCE A.: {:.3f}, Rew. L.: {:.3f}, Policy L.: {:.3f}, Val L.: {:.3f}, Rew. E.: {:.3f}, P. Rs. {:.3f}, T._Rs. {:.3f}, Val E.: {:.3f}, P. Vs. {:.3f}, T._Vs. {:.3f}, P. Ents. {:.3f}, T. Ents. {:.3f}\".format(\n prefix.capitalize(),\n jump,\n epoch_losses[i],\n nce_losses[i],\n nce_accs[i],\n reward_losses[i],\n policy_losses[i],\n value_losses[i],\n reward_errors[i],\n pred_rewards[i],\n target_rewards[i],\n value_errors[i],\n pred_values[i],\n target_values[i],\n pred_entropies[i],\n target_entropies[i]))\n\n wandb.log({prefix + 'Jump {} loss'.format(jump): epoch_losses[i],\n prefix + 'Jump {} NCE loss'.format(jump): nce_losses[i],\n prefix + 'Jump {} NCE acc'.format(jump): nce_accs[i],\n prefix + \"Jump {} Reward Loss\".format(jump): reward_losses[i],\n prefix + 'Jump {} Value Loss'.format(jump): value_losses[i],\n prefix + \"Jump {} Reward Error\".format(jump): reward_errors[i],\n prefix + \"Jump {} Policy loss\".format(jump): policy_losses[i],\n prefix + \"Jump {} Value Error\".format(jump): value_errors[i],\n prefix + \"Jump {} Pred Rewards\".format(jump): pred_rewards[i],\n prefix + \"Jump {} Target Rewards\".format(jump): target_rewards[i],\n prefix + \"Jump {} Pred Values\".format(jump): pred_values[i],\n prefix + \"Jump {} Target Values\".format(jump): target_values[i],\n prefix + \"Jump {} Pred Entropies\".format(jump): pred_entropies[i],\n prefix + \"Jump {} Target Entropies\".format(jump): target_entropies[i],\n 'FM epoch': steps})\n\n wandb.log({prefix + ' loss': np.mean(epoch_losses),\n prefix + ' NCE loss': np.mean(nce_losses),\n prefix + ' NCE acc': np.mean(nce_accs),\n prefix + \" Reward Loss\": np.mean(reward_losses),\n prefix + ' Value Loss': np.mean(value_losses),\n prefix + \" Reward Error\": np.mean(reward_errors),\n prefix + \" Policy loss\": np.mean(policy_losses),\n prefix + \" Value Error\": np.mean(value_errors),\n prefix + \" Pred Rewards\".format(jump): np.mean(pred_rewards),\n prefix + \" Pred Values\".format(jump): np.mean(pred_values),\n prefix + \" Target Rewards\".format(jump): np.mean(target_rewards),\n prefix + \" Target Values\".format(jump): np.mean(target_values),\n prefix + \" Pred Entropies\".format(jump): np.mean(pred_entropies),\n prefix + \" Target Entropies\".format(jump): np.mean(target_entropies),\n 'FM epoch': steps})\n\n","sub_path":"src/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"70319065","text":"from abstracts import Signature\nfrom threemon.reader import EventTypes\nfrom threemon import process_pb2, registry_pb2, file_pb2\nfrom report import mapping\n\n\n\"\"\"line would be a parsed entry from the onemon json file.\ndelshadowcopies expects an entry of the \"*onemon.Process\" category\nand looks for the command key and keywords like 'wmic shadowcopy\ndelete' or 'vssadmin delete shadows'£\nSuited for Windows 7 & 10\n\"\"\"\n\nclass DelShadowCopy(Signature):\n\n event_types = {\n EventTypes.PROCESS: {process_pb2.Create}\n }\n\n description = \"A shadowcopy was deleted\"\n TTPS = [\"T1490\"]\n events = {}\n\n _vssadmin_tokens = [\"vssadmin\", \"delete\", \"shadows\"]\n _wmic_tokens = [\"wmic\", \"shadowcopy\", \"delete\"]\n\n def process_event(self, process):\n if all(token in process.command.lower()\n for token in self._vssadmin_tokens):\n self.events = mapping(self.events, process)\n self.trigger()\n if all(token in process.command.lower()\n for token in self._wmic_tokens):\n self.events = mapping(self.events, process)\n self.trigger()\n\nclass CryptoRegistries(Signature):\n\n event_types = {\n EventTypes.REGISTRY: {\n registry_pb2.QueryValueKey,registry_pb2.OpenKeyEx,\n registry_pb2.EnumerateKey,registry_pb2.CreateKeyEx\n }\n }\n \n description = \"Query to Microsoft's cryptography registry key found\"\n TTPS = [\"None\"]\n events = {}\n \n _regkey = \"REGISTRY\\\\MACHINE\\\\SOFTWARE\\\\WOW6432Node\\\\Microsoft\\\\Cryptography\"\n\n def registry_event(self, registry):\n if self._regkey.upper() in registry.path.upper():\n self.events = mapping(self.events, registry)\n self.trigger()\n\n\nclass FileOpsFrequency(Signature):\n\n event_types = {\n EventTypes.FILE: {\n file_pb2.OpenRead, file_pb2.OpenModify,\n file_pb2.Rename, file_pb2.Delete, file_pb2.CreateModify\n }\n }\n\n description = \"Unusual high frequency of file operations detected\"\n TTPS = [\"T1486\"]\n events = {}\n\n threshold = 40\n fileops = 0\n \n def checkfrequency(self, file):\n self.fileops += 1\n if self.fileops > self.threshold:\n self.events = mapping(self.events, file)\n self.trigger()\n","sub_path":"sigs/ransomware.py","file_name":"ransomware.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"447501402","text":"from prettytable import PrettyTable #Libreria para imprimir la tabla al final \nimport sys #Libreria para usar los argumentos de la linea de comando\n\n\nf = open(\"gramatica.txt\", \"r\")\nreglas=[]\nproducciones=[]\ntotalProducciones=0\n\nfor elemento in f:\n ruleList = elemento.replace(\"\\n\",\"\").split('->') \n if ruleList[1]==\"/\" and ruleList [0]!= \"S\":\n producciones.append(ruleList[0])\n elif ruleList[1]==\"/\" and ruleList [0]== \"S\":\n totalProducciones=1\n else:\n ruleList.append(0) #El tercer elemento de la lista representa el cursor(elemento)\n reglas.append(ruleList)\n\nfor elemento in reglas:\n for elem in producciones:\n if elem in elemento[1]:\n if elemento[0]==\"S\" and elemento[1]==elem:\n totalProducciones=1\n else:\n reglas.append([elemento[0],elemento[1].replace(elem,\"\"),0])\n \nreglas.append(['$',\"S\",0]) #Agregamos la regla S' --> S (representando S' con $)\n\n#Funcion que elimina reglas repetidas de una lista \ndef reglasRepetidas(r):\n newlist =[]\n for elem in r:\n if not(elem in newlist):\n newlist.append(elem)\n newlist.reverse()\n return newlist\n\n#Funcion que nos dice si un simbolo es terminal \ndef esNoTerminal (x):\n return x.istitle() or x==\"$\"\n\n#Funcion que nos regresa las reglas derivadas a partir de la lectura del cursor\ndef derivacion(r):\n if (esFinal(r)):\n return [r]\n \n reglasEstado=[]\n lol=r[1][r[2]]\n if(esNoTerminal(r[1][r[2]])):\n for x in reglas:\n if( x[0] == r[1][r[2]] ):\n reglasEstado.append(x) \n for y in reglasEstado:\n reglasEstado=reglasEstado+derivacion(y)\n \n reglasEstado.append(r)\n return reglasEstado\n\n#Funcion que nos dice si el conjunto de reglas de un estado pasa la prueba DK\ndef reglaDK(rul):\n reglas =[]\n reglas.extend(rul)\n lecturaFinal=[] \n if(len(rul)==1 and esFinal(rul[0])):\n return True,[],[]\n\n \n for r in reglas:\n r[2]=r[2]+1\n if esFinal(r):\n lecturaFinal.append(r)\n \n for rl in rul:\n for final in lecturaFinal:\n if rl[1][rl[2]-1] == final[1][final[2]-1] and rl!= final:\n return (False,rl,final)\n \n for r in rul:\n r[2]=r[2]-1\n \n return (True,[],[])\n \n \n \n#Funcion que nos dice si una regla tiene el apuntador al final \ndef esFinal(r):\n return(r[2]==len(r[1]))\n \n#Funcion principal de generacion de estado\ndef nuevoEstado(r,i):\n idE=i\n estados=[]\n e=[]\n transiciones={}\n rules= reglasRepetidas(derivacion(r))\n dk,r1,r2 = reglaDK(rules)\n if not (dk):\n sys.exit( \"La gramatica no cumple la regla DK por conflicto con las siguientes reglas en el mismo estado:\"+str(r1)+str(r2))\n \n else:\n for regla in rules:\n if not(esFinal(regla)): \n reglaAux = regla[:]\n reglaAux[2]= reglaAux[2]+1\n if not(reglaAux in rules):\n newid = i+1\n transiciones.update( {regla[1][regla[2]] : newid} )\n e,i=nuevoEstado(reglaAux,newid)\n else:\n transiciones.update( {regla[1][regla[2]] : idE} )\n e=[]\n #Basicamente crear la transicion a si mismo,\n else:\n #Si es terminal, debe crearse el estado \n e = [i,rules,{},True]\n estados.append(e)\n return estados,i\n estados=estados+e\n estados.append([idE,rules,transiciones,False])\n return estados,i\n\n#Funcion que construye la tabla LR0 a partir del automata\ndef construyeTabla(aut):\n t=[]\n nt=[]\n for r in reglas:\n for ch in r[1]:\n if not(esNoTerminal(ch) or ch in t):\n t.append(ch)\n elif esNoTerminal(ch) and not( ch in nt):\n nt.append(ch)\n t.sort() \n len_terminales=len(t) \n terminales=t[:] \n t.append(\"FDC\")\n t=t+nt\n\n tablaLR0 = [[\"\" for x in range(len(t))] for y in range(len(aut))] #Creamos la tabla LR0 vacia\n \n for estado in aut:\n if not(estado[3]): #Es decir, si el estado es no terminal\n for transicion in estado[2]:\n if esNoTerminal(transicion):\n tablaLR0[estado[0]-1][t.index(transicion)] = estado[2][transicion]\n else:\n tablaLR0[estado[0]-1][t.index(transicion)] = (\"d\"+str(estado[2][transicion]))\n else:\n if(estado[1][0][0]==\"$\"):\n tablaLR0[estado[0]-1][t.index(\"FDC\")]=\"aceptar\"\n elif (estado[1][0][0]==\"S\"):\n tablaLR0[estado[0]-1][t.index(\"FDC\")]=str(estado[1][0][0])+\"->\"+str(estado[1][0][1])\n else:\n for celda in terminales:\n tablaLR0[estado[0]-1][t.index(celda)]=str(estado[1][0][0])+\"->\"+str(estado[1][0][1]) \n if totalProducciones==1:\n tablaLR0[0][t.index(\"FDC\")]=\"aceptar\"\n return(tablaLR0,t)\n \n \n#------------------------------------------------\n#Ejecucion del programa \n\nautomata =nuevoEstado(reglas[-1],1)[0]\nautomata.sort(key=lambda x: x[0])\nlr0,encabezado=construyeTabla(automata)\n\n#uso de prettytalbe\nt = PrettyTable(encabezado)\nfor row in lr0:\n t.add_row(row)\nprint(t)\n\n\n#------------------------------------------------\ncadena=\"b\"\nstack=[]\n\nsimboloEspecial=1\nstack.append(simboloEspecial)\nsimbolo=cadena[0]\ncadena=cadena[1:]\nvalorTabla = lr0[simboloEspecial-1][encabezado.index(simbolo)]\nwhile valorTabla != \"aceptar\":\n if \"d\" in valorTabla:\n stack.append(simbolo)\n simboloEspecial=(int)(valorTabla.replace(\"d\",\"\"))\n stack.append(simboloEspecial)\n if len(cadena)==0:\n simbolo = \"FDC\"\n else:\n simbolo=cadena[0]\n cadena=cadena[1:]\n elif \"->\" in valorTabla:\n for char in valorTabla.split('->')[1]: \n stack.pop()\n stack.pop()\n simboloEspecial=(int)(stack[-1])\n stack.append(valorTabla.split('->')[0])\n simboloEspecial=(int)(lr0[simboloEspecial-1][encabezado.index(valorTabla.split('->')[0])])\n stack.append(simboloEspecial)\n else:\n sys.exit(\"La gramatica no puede procesar la cadena\")\n valorTabla=lr0[simboloEspecial-1][encabezado.index(simbolo)]\nif simbolo != \"FDC\":\n sys.exit(\"La cadena no es aceptada por la gramatica\")\nelse:\n print(\"La cadena es ACEPTADA por la gramatica\")\n","sub_path":"practica7/LR0.py","file_name":"LR0.py","file_ext":"py","file_size_in_byte":6507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160182249","text":"# import sys\n# sys.setrecursionlimit(10 ** 6)\n# import bisect\n# from collections import deque\n# from decorator import stop_watch\n#\n#\n# @stop_watch\ndef solve(N, M, PY):\n ken = [0] * (N + 1)\n PY = [PY[i] + [i] for i in range(M)]\n PY.sort(key=lambda x: x[1])\n for i in range(M):\n p, y, s = PY[i]\n ken[p] += 1\n PY[i].append(ken[p])\n PY.sort(key=lambda x: x[2])\n for p, y, s, n in PY:\n print(('000000' + str(p))[-6:] + ('000000' + str(n))[-6:])\n\n\nif __name__ == '__main__':\n N, M = map(int, input().split())\n PY = [[int(i) for i in input().split()] for _ in range(M)]\n solve(N, M, PY)\n\n # # test\n # from random import randint, sample\n # from func import random_str\n # N, M = 10 ** 5, 10 ** 5\n # PY = sample([[randint(1, 5), 10 ** 8 - i] for i in range(M)], M)\n # solve(N, M, PY)\n","sub_path":"AtCoderBeginnerContest/1XX/113/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"395113333","text":"import sys, pygame\r\nimport random\r\nfrom pygame.locals import *\r\nfrom math import *\r\nimport json\r\nfrom tkinter import *\r\nfrom Verificar import*\r\nfrom Registrar import*\r\n\r\npygame.init()\r\n\r\nWIDTH = 1156\r\nHEIGHT = 650\r\nSCREEN = pygame.display.set_mode((WIDTH,HEIGHT))\r\nFPS = pygame.time.Clock()\r\n\r\npygame.display.set_caption('PyDeathRace')\r\n\r\npista = pygame.transform.scale(pygame.image.load('Menu.png').convert(),(WIDTH,HEIGHT))\r\n\r\ndef menu ():\r\n \r\n events = pygame.event.get()\r\n for event in events:\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == K_e:\r\n Menu2 ()\r\n if event.key == K_r:\r\n Menu1 ()\r\n\r\n\r\ndef main():\r\n\r\n while True:\r\n \r\n #Test if the game has been quit\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n if event.type == KEYDOWN:\r\n if event.key == K_ESCAPE:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n SCREEN.blit(pista,(0,0))\r\n menu ()\r\n\r\n\r\n\r\n pygame.display.update()\r\n FPS.tick(60)\r\n \r\nif __name__ == '__main__': main()\r\n","sub_path":"proyectos/scastro-proyecto1/código/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"94815475","text":"import pandas as pd\nimport requests\n\n\ncitations = '../metadata/ICPSR_citations_metadata.json'\ncitations_df = pd.read_json(citations)\nunique_dois = pd.DataFrame(data=citations_df[citations_df['pubIdSchema'] == 'doi']['pubId'].unique(), columns=['doi'])\n\ndef get_final_url(doi):\n '''\n Given a row in a data frame, if that row has a pubId that is a doi\n go fetch that resource and return the final url\n '''\n doi_url = 'https://dx.doi.org/{}'.format(doi)\n print(doi_url)\n try:\n res = requests.get(doi_url, timeout=10)\n final_url = res.url\n except Exception as e:\n print(\"Resource not available for {}: {}\".format(doi_url, e))\n final_url = None\n print(\"Coming back with {} - {}\".format(doi, final_url))\n return (doi, final_url)\n\n\nunique_dois_list = list(unique_dois['doi'])\n\nprint(\"Fethcing {} dois\".format(len(unique_dois_list)))\n\n\nimport csv\n\nwith open('../metadata/resolved_dois.csv', 'w') as outfile:\n\twriter = csv.writer(outfile)\n\tfor i,e in enumerate(unique_dois_list):\n\t\tprint(\"adding item at index {}\".format(i))\n\t\twriter.writerow(get_final_url(e))\t\n","sub_path":"Dataset-Extraction/notebooks/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"475766233","text":"# Create a program using maths and f-Strings that tells us how many days, weeks, months we have left if we live until 90 years old.\n# It will take your current age as the input and output a message with our time left in this format:\n# You have x days, y weeks, and z months left.\n# Where x, y and z are replaced with the actual calculated numbers.\n\n\nage = input(\"What is your current age?\")\n\ndiff = 90 - int(age)\nyear = int(diff) * 365\nweeks = int(diff) * 52\nmonths =int(diff) * 12\nprint(f\" You have {year} days, {weeks} weeks, and {months} months left\")","sub_path":"4-days-of-code-python/Day 2/life-in-weeks.py","file_name":"life-in-weeks.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"577624096","text":"############################################################################\n# Project: Forest Dynamics at the 'Woods of the World'\n# Title: Calculation of the fractional light recieved by each stand\n# Author: James Gilmore\n# Email: james.gilmore@pgr.reading.ac.uk.\n# Version: 1.2.0\n# Date: 12/01/16\n# Status: Operational\n############################################################################\n\n#Initialising the python script\nfrom __future__ import absolute_import, division, print_function\nfrom scipy.integrate import quad, dblquad\nimport matplotlib.pyplot as plt\nfrom array import array\nimport numpy as np\nimport time, os, csv, sys\n\n############################################################################\n#Pre-requiste: Define all of the equations needed for the GLE equation\n\n#Define the equitorial coordinate system ##(All Equations Correct)##\nzenith = lambda H, dec, lat: np.arcsin(np.sin(lat)*np.sin(dec)+np.cos(lat)*np.cos(dec)*np.cos(H)) #GOOD\nazimuth = lambda lat, dec, zenith: np.arccos((np.sin(dec)-np.sin(zenith)*np.sin(lat))/(np.cos(zenith)*np.cos(lat))) #GOOD\ndec = lambda Jday: np.arcsin(np.sin(np.radians(-23.44))*np.cos((np.radians(360)/365.24)*(Jday+10)+(np.radians(360)/np.pi)*0.0167*np.sin((np.radians(360)/365.24)*(Jday-2))))*57.2957795 #GOOD\nhe = lambda Jday: 0.17*np.sin((4*np.pi*(Jday-80))/373)-0.129*np.sin((2*np.pi*(Jday-8))/355) #GOOD\ngam2 = lambda h: -15*np.floor(h) #GOOD\ngam = lambda h: 15.0*np.floor(h/15.0) #GOOD\nH = lambda hl, gaml, gam, he: (np.pi/12)*(hl-(24*(gaml-gam)/360)+he-12) #GOOD\ntd = lambda Jday: (2*np.pi*(np.floor(Jday)-1))/365 #GOOD\n\n#Define the equations specific to the NBGW ##(All Equations Correct)##\nSolElvNBGW = lambda h, day: zenith(H(h, np.radians(-4.15176), gam(0), he(day)), np.radians(dec(day)), np.radians(51.83756))*57.2957795\n#SolAziNBGW = lambda h, day: np.piecewise(h, [h < 12.01854275271367, h >= 12.01854275271366], [lambda h: azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795, lambda h: 360-azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795])\n\ndef SolAziNBGW(h,day):\n\treturn azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795 if h < 12.01854275271367 else 360-azimuth(np.radians(51.83756), np.radians(dec(day)), np.radians(SolElvNBGW(h,day)))*57.2957795\n\n#### Be careful for SolAziNBGW: Put hours in double format (i.e. 3am is 3.0 NOT 3)\n\n#Define the Dawn and Dusk equations (The sunrise and sunset times can be solved for the condition when the angle from horizon reach 0deg using the Zenith equation)\nDawn = lambda day: 11.9952 - 3.81972*np.arccos(1.27249*np.tan(np.arcsin(0.397789*np.cos(0.172029 + 0.0172029*day + 0.0334*np.sin(0.0172029*(-2. + day)))))) - 0.17*np.sin(0.03369*(-80. + day)) + 0.129*np.sin(0.0176991*(-8. + day))\nDusk = lambda day: 11.9952 + 3.81972*np.arccos(1.27249*np.tan(np.arcsin(0.397789*np.cos(0.172029 + 0.0172029*day + 0.0334*np.sin(0.0172029*(-2. + day)))))) - 0.17*np.sin(0.03369*(-80. + day)) + 0.129*np.sin(0.0176991*(-8. + day))\n\n#Clear Sky and Beam Fraction Coefficients ##(All Equations Correct)##\nacoff = lambda w, mp: np.exp(-(0.465+0.134*w)*(0.179+0.421*np.exp(-0.721*mp))*mp)\nmp = lambda A, z: ((288-0.0065*z)/288)**5.256/(np.sin(A)+0.15*(A+3.885)**-1.253)\nw = lambda Tdpt: np.exp(-0.0592+0.06912*Tdpt) #good\nkb = lambda kt: -10.627*kt**5 + 15.307*kt**4 - 5.205*kt**3 + 0.994*kt**2 - 0.059*kt + 0.002\nBeamNBGW = lambda h, day: kb(acoff(w(21), mp(np.radians(SolElvNBGW(h, day)),0)))\nClearNBGW = lambda h, day: 24*(2.044*SolElvNBGW(h, day)+0.12964*SolElvNBGW(h, day)**2-1.941*10**(-3)*SolElvNBGW(h, day)**3+7.591*10**(-6)*SolElvNBGW(h, day)**4)*0.1314\n\n#Rotational Matrix required for positioning of trees and shades\nRM = lambda x: np.array([[np.cos(x), -np.sin(x)], [np.sin(x), np.cos(x)]])\n\n#Import the data of the tree set in the correct columnar form (X, Y, Height, Crown Height, Crown Width):\nX, Y, HE, CH, CW = np.genfromtxt(\"GillyShadingTIFull.csv\", dtype=float, delimiter=',', usecols=(0, 1, 2, 3, 4), unpack=True, skiprows=1)\n\n############################################################################\n#The Gilly Light Equaton\n\n\"There are 3 stages to determining the amount of sunlight present at a location\"\n\"for a given year:\"\n\"(1) The first requires solving the Gilly Shade Criterion Function (GSCF) which\"\n\"determines if any entities are casting a shadow on position n,o\"\n\"(2) Combine the GSCF with the Beam Sky Radiation factor for each position in time\"\n\"to determine the amount of avaliable sunlight when no shade is cast.\"\n\"(3) Solve for h*day interations in time and summerise each step and compare to a\"\n\"point with full light avaliability to normalised the equation between 0 and 1.\"\n\ndef GLE(iter=len(X), daymin=105, daymax=263, hspa=10, nmin=0, nmax=60, omin=0, omax=60, spacings=1):\n\t\n\t############################################################################\n\t#Initalise the variables for this function\n\n\tit=0 #iterator counter\n\ttreeskip=0 #Number of trees skipped\n\tAllTrees=0 #Number of trees processed\n\t\n\tts = np.zeros(nmax)\n\tKMatrix = np.zeros([iter, 2]) \n\tKMatrixCrown = np.zeros([iter, 2]) \n\tKMatrixHeight = np.zeros([iter, 2]) \n\tKMatrixTot = np.zeros(iter)\n\tKMatrixTotTot = np.zeros([nmax/spacings,omax/spacings])\n\tGillyTop = np.zeros([nmax/spacings,omax/spacings])\n\tGillyBottom = np.zeros([nmax/spacings,omax/spacings])\n\tGillyLight = np.zeros([nmax/spacings,omax/spacings])\n\tnpos = np.zeros((nmax-nmin)/spacings)\n\topos = np.zeros((omax-omin)/spacings)\n\ttstart = time.time()\n\teps = sys.float_info.epsilon\n\tnp.set_printoptions(threshold='nan')\n\t\n\t############################################################################\n\t############################################################################\n\t#Determine amount of sunlight for each position over the whole year.\n\t\n\tfor day in xrange(daymin, daymax):\n\t\t#Calculate equally spacing times for the particular day.\n\t\thmax = (Dusk(day)-Dawn(day))/hspa\n\t\th_day = np.arange(Dawn(day)+0.1, Dusk(day), hmax)\t\t\n\t\tfor h in xrange(len(h_day)):\n\t\t\tfor o in np.arange(nmin,nmax,spacings):\n\t\t\t\t\t#Update the progress of the GLE equation\n\t\t\t\t\tit+=1\n\t\t\t\t\tts[o] = time.time()\n\t\t\t\t\tos.system('cls' if os.name=='nt' else 'clear')\n\t\t\t\t\t#print(\"Dawn(day)\", Dawn(day))\n\t\t\t\t\t#print(\"Dusk(day)\", Dusk(day))\n\t\t\t\t\t#print(\"iter\", iter, \" KMatrixTot.sum()\", KMatrixTot.sum())\n\t\t\t\t\t#print(GillyTop)\n\t\t\t\t\tprint(\"Trees Skipped Ratio: \", \"%.3f\" % ((treeskip/(AllTrees+eps))*100), \"%\")\n\t\t\t\t\tprint(\"Day: \", day, \" Hour: \", \"%.2f\" % h_day[h], \" O: \", o)\n\t\t\t\t\tprint(\"Time Progressed (s): \", \"%.0f\" % (ts[o]-tstart)),\n\t\t\t\t\tprint(\"Time Left (s): \", \"%.0f\" % ((((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin))-it)*((ts[o]-tstart)/it))),\n\t\t\t\t\tprint(\"Percentage Completed: \", \"%.3f\" % ((1-(((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin))-it)/((1/spacings)*(nmax-nmin)*hspa*(daymax-daymin)))*100), \"%\")\n\t\t\t\t\t\n\t\t\t\t\tfor n in np.arange(omin,omax,spacings):\n\t\t\t\t\t\t#Calculate the GSCF for each entity (Tree or otherwise)\n\t\t\t\t\t\tfor i in xrange(iter):\n\t\t\t\t\t\t\tAllTrees+=1\n\t\t\t\t\t\t\t#This 'if' statement greatly reduces load as it quickly determines if a tree is close to the position n,o and removes from calculation if it isn't\n\t\t\t\t\t\t\tif (np.abs(X[i]-n)-(HE[i]/np.tan(SolElvNBGW(h_day[h],day))) and np.abs(Y[i]-o)-(HE[i]/np.tan(SolElvNBGW(h_day[h],day)))) < 0:\n\t\t\t\t\t\t\t\t#Determines if the width of the shade overlaps with n,o and if so normalises it in binary form\n\t\t\t\t\t\t\t\tKMatrixCrown[i] = (([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[-CW[i]/200,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])/(([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[CW[i]/200,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])\n\t\t\t\t\t\t\t\t#print(KMatrixCrown[i])\n\t\t\t\t\t\t\t\tfor j in xrange(2):\n\t\t\t\t\t\t\t\t\tif KMatrixCrown[i, j] <= 0: #Try >=0?????????\n\t\t\t\t\t\t\t\t\t\tKMatrixCrown[i, j] = 0 #Shaded\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tKMatrixCrown[i, j] = 1 #NOT Shaded\n\t\t\t\t\t\t\t\t#Determines if the height of the shade overlaps with n,o\n\t\t\t\t\t\t\t\tKMatrixHeight[i] = (([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[0,HE[i]])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])/(([X[i], Y[i]]+np.dot(RM(-np.radians(SolAziNBGW(float(h_day[h]),day)-210)),[0,HE[i]-(CH[i]/100)])/np.tan(SolElvNBGW(h_day[h],day)))-[n, o])\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tfor j in xrange(2):\n\t\t\t\t\t\t\t\t\tif KMatrixHeight[i, j] <= 0:\n\t\t\t\t\t\t\t\t\t\tKMatrixHeight[i, j] = 0 #Shaded\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tKMatrixHeight[i, j] = 1 #NOT Shaded\n\t\t\t\t\t\t\t\t#Sum the Height and Crown criterias and them sums the x and y directions\n\t\t\t\t\t\t\t\tKMatrix[i] = KMatrixHeight[i]+KMatrixCrown[i]\n\t\t\t\t\t\t\t\tKMatrixTot[i] = KMatrix[i,0]+KMatrix[i,1] #0: Fully Shaded, 1: 1 directional shaded, 2: NOT Shaded\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\ttreeskip+=1\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 2\n\t\t\t\t\t\t#After all trees have been tested with the GSCF at position n,o we need to combine the x and y directions togeteher\n\t\t\t\t\t\tfor i in xrange(iter):\n\t\t\t\t\t\t\tif KMatrixTot[i] == 0:\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 0 #Shaded\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tKMatrixTot[i] = 1 #NOT Shaded\n\t\t\t\t\t\t#print(KMatrixTot.sum())\n\t\t\t\t\t\t#As long as 1 tree had a light value of 0 then we say position n,o was beening shaded from the sun at that specific time.\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (iter - KMatrixTot.sum()) <= 0: #############This probably should be 'iter - 2 - KMatrixTot.sum()' rather than '-5' from comparison with Wolfram code\n\t\t\t\t\t\t\tKMatrixTotTot[o/spacings,n/spacings] = BeamNBGW(h_day[h],day)\n\t\t\t\t\t\t\t#print(\"NotShade\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t#print(\"Shade\")\n\t\t\t\t\t\t\tKMatrixTotTot[o/spacings,n/spacings] = 0\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Sum up for each time step h and day.\n\t\t\t\t\t\tGillyTop[o/spacings,n/spacings] += KMatrixTotTot[o/spacings,n/spacings]\n\t\t\t\t\t\tGillyBottom[o/spacings,n/spacings] += ClearNBGW(h_day[h],day)\n\t\t\t\t\t\t\n\t############################################################################\n\t#Finally normalise the GLE values with respects to full sunlight\n\t\n\tfor o in np.arange(nmin,nmax,spacings):\n\t\tfor n in np.arange(omin,omax,spacings):\n\t\t\tGillyLight[o/spacings,n/spacings] = GillyTop[o/spacings,n/spacings]/GillyBottom[o/spacings,n/spacings]\n\t\t\t\n\t############################################################################\n\t\n\treturn GillyLight, daymax, hspa, nmin, nmax, omin, omax, spacings, ts[-1], tstart\n\t\n############################################################################\n############################################################################\n#Solve the GLE with a given input parameters\n\nGillyLight, Days, TemporalSpacing, nmin, nmax, omin, omax, SpatialSpacing, tfinal, tstart = GLE(473, 105, 263, 10, 0, 30, 0, 15, 0.5)\nprint(\"\\n\", GillyLight)\n\n#Save the data of 'GillyLight' to csv file.\n\nwith open(\"../rawdata/GLEGridClear_11.csv\", \"wb\") as output:\n\twriter = csv.writer(output, lineterminator='\\n')\n\twriter.writerows(GillyLight)\n\n#Print out post run information.\n\nos.system('cls' if os.name=='nt' else 'clear')\t\nprint(\"Gilly Light Equation Output Information\\n\")\nprint(\"---------------------------------------------------\")\nprint(\"Gilly Light Equation has been solved successfully\")\nprint(\"Some final information about this run:\")\nprint(\"Days: \", Days)\nprint(\"Temporal Spacing: \", TemporalSpacing, \"s\")\nprint(\"Spatial Spacing: \", SpatialSpacing, \"m\")\nprint(\"No. of Grids: \", len(GillyLight))\nprint(\"---------------------------------------------------\")\nprint(\"Time taken to solve GLE: \", \"%.0f\" % (tfinal-tstart), \"s\")\n","sub_path":"analysis/GLE_Grid.py","file_name":"GLE_Grid.py","file_ext":"py","file_size_in_byte":11424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13164030","text":"from PyQt5.QtWidgets import QLineEdit\n\nfrom .base import BaseField\n\n\nclass StringField(BaseField):\n def __init__(self, name, value=None, title=None):\n super().__init__(name, title)\n self.widget = QLineEdit()\n if value is not None:\n self.widget.setText(str(value))\n\n @property\n def value(self):\n value = self.widget.text()\n return value\n","sub_path":"ojoqt/dialog/form/field/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334215727","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 14 21:59:54 2019\n\n@author: Brian Chan\n\"\"\"\n\nfrom keras.datasets import mnist\nfrom keras.models import Sequential \nfrom keras.layers.core import Dense, Activation\nfrom keras.utils import np_utils\n\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n\nX_train = X_train.reshape(60000, 784) \nX_test = X_test.reshape(10000, 784)\nX_train = X_train.astype('float32') \nX_test = X_test.astype('float32') \nX_train /= 255 \nX_test /= 255\n\n\nclasses = 10\nY_train = np_utils.to_categorical(Y_train, classes) \nY_test = np_utils.to_categorical(Y_test, classes)\n\ninput_size = 784\nbatch_size = 100 \nhidden_neurons = 400 \nepochs = 30\n\nmodel = Sequential() \nmodel.add(Dense(hidden_neurons, input_dim=input_size)) \nmodel.add(Activation('relu')) \nmodel.add(Dense(classes, input_dim=hidden_neurons)) \nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adadelta')\n\nmodel.summary()\n\nhistory = model.fit(X_train, Y_train, validation_split = 0.5, batch_size=batch_size, epochs=epochs, verbose=1)\n\nscore = model.evaluate(X_test, Y_test, verbose=1)\nprint('Test accuracy:', score[1]) \n\nfrom matplotlib import pyplot as plt\n#history = model\n#history = model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","sub_path":"Lesson_9/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277936349","text":"# -*- coding: utf-8 -*-\nfrom NotifyToLine import SendMessage # mod.pyのMemberクラスの呼び込み\nfrom MonitorWebPages import MonitorBishHP\n\n# インスタンス化\nmonitor = MonitorBishHP()\nnotify = SendMessage()\n\nwith open(\"./TopNews.txt\", 'r') as file:\n top_news = file.read()\n\nif monitor.is_changed_for_top_news() == True:\n notify.send_line(\n \"\\n\" +\n \"\\n\" + \"BiSH official siteに更新はありません\"+\n \"\\n\" +\n \"\\n\" + \"---------------------------------------\" +\n \"\\n\" + \"***最新情報***\"\n \"\\n\" + top_news +\n \"\\n\" + monitor.url,\n \"./pictures/no_update.jpg\")\nelse:\n notify.send_line(\n \"\\n\" +\n \"\\n\" + \"BiSH official siteに更新がありました\" +\n \"\\n\" +\n \"\\n\" + \"---------------------------------------\" +\n \"\\n\" + \"***最新情報***\"\n \"\\n\" + top_news +\n \"\\n\" + monitor.url,\n \"./pictures/updated.jpg\")\n\n# 更新されたトップニュースを保存\nmonitor.save_top_news()\n","sub_path":"sclipt.py","file_name":"sclipt.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"550068810","text":"import sys\r\nprint(sys.version)\r\nimport pandas as pd\r\n#import math\r\nimport numpy as np\r\nimport polynomial\r\n#import matplotlib.pyplot as plt\r\n\r\ndef p(x, k, i):\r\n total = 1\r\n for j in range(k + 1):\r\n if j != i:\r\n total *= x[i] - x[j]\r\n return total\r\n\r\ndef p1(x_v, x, k):\r\n total = 1\r\n for i in range(k):\r\n total *= x - x_v[i]\r\n return total\r\n\r\ndef f(x, y, k):\r\n total = 0\r\n for i in range(k + 1):\r\n total += y[i] / p(x, k, i)\r\n return total\r\n\r\nclass PolinomModel:\r\n def __init__(self, n):\r\n self.inner_model = None\r\n self.n = n\r\n\r\n def __str__(self):\r\n if not self.inner_model:\r\n return \"Model is empty\"\r\n c = self.inner_model.coefficients\r\n s = str(c[0])\r\n for i in range(1, len(c)):\r\n last = \" - \" + s[1:] if s.startswith(\"-\") else \" + \" + s\r\n s = str(c[i]) + \"*x^\" + str(i) + last\r\n return s\r\n\r\n def fit(self, x, y):\r\n self.inner_model = polynomial.polynomial(x, y, self.n)\r\n\r\n def predict(self, x):\r\n return [self.inner_model.getval(i) for i in x]\r\n # result = []\r\n # for item in x:\r\n # total = 0\r\n # for i in range(self.n + 1):\r\n # total += self.c[i]*p1(self.x, item, i)\r\n # result.append(total)\r\n # return result\r\n\r\ndef compare(predict, real):\r\n diff = (predict - real)\r\n diff = diff*diff\r\n diff = np.sqrt(diff.sum()/len(diff))\r\n return diff\r\n\r\ndef cross_validation(index, k = 2, shuffle = True, seed = 1):\r\n rand = np.random.RandomState(seed)\r\n ind = rand.choice(index, size = len(index),replace = False) if shuffle else index\r\n for i in range(0,k):\r\n training = [x for j,x in enumerate(ind) if j % k != i]\r\n validation = [x for j,x in enumerate(ind) if j % k == i]\r\n yield training, validation\r\n\r\ndef cv_model(model, dataset, value, response, cv_folds):\r\n results_learn = []\r\n results_valid = []\r\n for i in range(cv_folds):\r\n for train_index, valid_index in cross_validation(dataset.index, seed = i):\r\n #print(train_index, valid_index)\r\n try:\r\n train_set = dataset.ix[train_index]\r\n valid_set = dataset.ix[valid_index]\r\n model.fit(np.array(train_set.drop(response, axis=1)[value]),\r\n np.array(train_set[response]))\r\n predict_learn = model.predict(np.array(train_set[value]))\r\n predict_valid = model.predict(np.array(valid_set[value]))\r\n results_learn.append(compare(predict_learn, np.array(train_set[response])))\r\n results_valid.append(compare(predict_valid, np.array(valid_set[response])))\r\n except np.linalg.LinAlgError:\r\n pass\r\n #print(\"Warn LinAlgError\")\r\n #print(results)\r\n return (np.mean(results_learn), np.std(results_learn), np.mean(results_valid), np.std(results_valid))\r\n\r\ndef tune_polinom(dataset, value, response, cv_folds, max_n):\r\n results = []\r\n for i in range(max_n + 1):\r\n print(\"CV on \" + str(i) + \" degree model\")\r\n results.append(cv_model(PolinomModel(i), dataset, value, response, cv_folds))\r\n return pd.DataFrame(results, index=range(max_n + 1), columns=[\"mean_learn\", \"std_learn\", \"mean_valid\", \"std_valid\"])\r\n\r\ndataset_learn_name = \"learn.txt\"\r\ndataset_test_name = \"test.txt\"\r\ncv_folds = 20\r\nmax_n = 20\r\n\r\nprint(\"Training model. dataset:\" + dataset_learn_name + \", folds: \" + str(cv_folds) + \", max n: \" + str(max_n))\r\ndataset_learn = pd.read_csv(dataset_learn_name, header=None, sep=\"\\t\")\r\ncolumns = dataset_learn.columns\r\ntune_results = tune_polinom(dataset_learn, columns[0], columns[1], cv_folds, max_n)\r\n#print(tune_results)\r\n#print(tune_results[\"mean_valid\"].idxmin())\r\n\r\nbest_result_n = tune_results[\"mean_valid\"].idxmin()\r\nbest_model = PolinomModel(best_result_n)\r\nbest_model.fit(np.array(dataset_learn[columns[0]]), np.array(dataset_learn[columns[1]]))\r\nprint(\"Best model: \" + str(best_result_n) + \" degree. \" + str(best_model) + \"\\n\")\r\nprint(\"Errors: \")\r\nprint(tune_results.ix[best_result_n])\r\n\r\ndataset_test = pd.read_csv(dataset_test_name, header=None, sep=\"\\t\")\r\ncolumns = dataset_test.columns\r\npredict = best_model.predict(np.array(dataset_test[columns[0]]))\r\nerror_on_test = compare(predict, np.array(dataset_test[columns[1]]))\r\nprint(\"\\nError on test: \" + str(error_on_test))\r\n\r\n#PolinomModel(i)\r\n#print(dataset.shape[0])","sub_path":"2/PolinomInterpolation.py","file_name":"PolinomInterpolation.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"423720223","text":"import json\nimport re\nimport sys\nfrom elasticsearch import Elasticsearch\n\nes = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n\n#sys.argv[1]: mails_paths\n\ndef string_cleaner(sentence):\n return re.sub(r\"[=.:><'•§œ;/)(!?@\\\\\\'\\`\\\"\\_\\n]\", r\"\", sentence)\n\ndef balise_cleaner(sentence):\n regexp_balise = r\"<(c|t|b|\\|a)*[^>]+>\"\n return re.sub(regexp_balise, r\" \", sentence)\n\n# Get all the mails path\ndef get_mails(mails_paths):\n with open(mails_paths, 'r') as paths_list:\n mails_list = [line.strip() for line in paths_list.readlines()]\n print('NOMBRE DE MAILS: {}'.format(len(mails_list)))\n paths_list.close()\n return mails_list\n\n# Build the body of the bilk query\ndef body_builder(mails_list):\n body_meta = []\n body_core = []\n for id_mail, path_mail in enumerate(mails_list):\n body_meta.append(json.JSONEncoder().encode({'index': {'_index': 'hydro_mail', '_type': 'mail', '_id': id_mail}}))\n with open(path_mail, 'r') as mail:\n body_core.append(json.JSONEncoder().encode({'id_mail': path_mail.split('/')[-1], 'content' : balise_cleaner(mail.read())})) \n ## Rajouter un paramètre 'date' provenant des metadonnées et polarimo venant de l'étude de positivité !!!\n mail.close()\n return (body_meta, body_core)\n\n\n# SAVE THE DATA AS A JSON FILE\nwith open('mails.json', 'w') as json_file:\n mails = body_builder(get_mails(sys.argv[1]))\n meta = mails[0]\n core = mails[1]\n for doc in range(len(meta)):\n json_file.write(meta[doc])\n json_file.write('\\n')\n json_file.write(core[doc])\n json_file.write('\\n')\n json_file.close()\n\n\n'''\n# INDEX\nres = es.bulk(index=\"hydro_mail\", doc_type='mail', body= body_builder(get_mails(sys.argv[1])))\nprint('RES: \\n{}'.format(res))\n'''\n","sub_path":"PREPROCESSING/DATA_MANAGER/Elasticsearch/Risk_detection/mail_indexing.py","file_name":"mail_indexing.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366455399","text":"import numpy as np\nimport os, sys\nimport os.path as osp\nimport string\nfrom textwrap import dedent\nfrom numpy.lib.arraysetops import isin\nfrom tqdm import trange\nimport time\nimport psutil\nimport json\nimport subprocess\nfrom subprocess import CalledProcessError\nimport cloudpickle\nimport base64\nimport zlib\nfrom .utils import colorize, setup_logger_kwargs\nfrom .json_utils import convert_json\nfrom .config import DEFAULT_SHORTHAND, WAIT_BEFORE_LAUNCH\nfrom .mpi_utils import mpi_fork\n\nDIV_LINE_WIDTH = 80\n\n\ndef call_experiment(exp_name, thunk, seed=0, num_cpu=1, data_dir=None, datestamp=False, **kwargs):\n \"\"\"\n 使用超参数和configuration运行函数\n \"\"\"\n num_cpu = psutil.cpu_count(logical=False) if num_cpu == \"auto\" else num_cpu\n kwargs[\"seed\"] = seed\n print(colorize(\"Running experiment:\\n\", color=\"cyan\", bold=True))\n print(exp_name + \"\\n\")\n print(colorize(\"with kwargs:\\n\", color=\"cyan\", bold=True))\n kwargs_json = convert_json(kwargs)\n print(json.dumps(kwargs_json, separators=(\",\", \":\\t\"), indent=4, sort_keys=True))\n print(\"\\n\")\n\n if \"logger_kwargs\" not in kwargs:\n kwargs[\"logger_kwargs\"] = setup_logger_kwargs(exp_name, seed, data_dir, datestamp)\n else:\n print(\"Note: Call experiment is not handling logger_kwargs.\\n\")\n\n def thunk_plus():\n if \"env_name\" in kwargs:\n import gym\n env_name = kwargs[\"env_name\"]\n kwargs[\"env_fn\"] = lambda: gym.make(env_name)\n del kwargs[\"env_name\"]\n # Fork into multiple processes\n mpi_fork(num_cpu)\n thunk(**kwargs)\n\n # thunk_plus()\n pickled_thunk = cloudpickle.dumps(thunk_plus)\n encoded_thunk = base64.b64encode(zlib.compress(pickled_thunk)).decode(\"utf-8\")\n # 获取上一层目录下的 run_entrypoint.py 文件\n entrypoint = osp.join(osp.abspath(osp.dirname(osp.dirname(__file__))), \"run_entrypoint.py\")\n cmd = [sys.executable if sys.executable else 'python', entrypoint, encoded_thunk]\n try:\n subprocess.check_call(cmd, env=os.environ)\n except CalledProcessError:\n err_msg = \"\\n\" * 3 + \"=\" * DIV_LINE_WIDTH + \"\\n\" + dedent(\"\"\"\n There appears to have been an error in your experiment.\n\n Check the traceback above to see what actually went wrong. The \n traceback below, included for completeness (but probably not useful\n for diagnosing the error), shows the stack leading up to the \n experiment launch.\n\n \"\"\") + \"=\" * DIV_LINE_WIDTH + \"\\n\" * 3\n print(err_msg)\n raise\n\n logger_kwargs = kwargs[\"logger_kwargs\"]\n plot_cmd = \"python plot.py \" + logger_kwargs[\"output_dir\"]\n plot_cmd = colorize(plot_cmd, \"green\")\n test_cmd = \"python test_policy.py \" + logger_kwargs[\"output_dir\"]\n test_cmd = colorize(test_cmd, \"green\")\n output_msg = \"\\n\" * 5 + \"=\" * DIV_LINE_WIDTH + \"\\n\" + dedent(\"\"\"\\\n End of experiment.\n\n\n Plot results from this run with:\n\n %s\n\n\n Watch the trained agent with:\n\n %s\n\n\n \"\"\" % (plot_cmd, test_cmd)) + \"=\" * DIV_LINE_WIDTH + \"\\n\" * 5\n print(output_msg)\n\n\ndef all_bools(vals):\n return all([isinstance(v, bool) for v in vals])\n\n\ndef valid_str(v):\n \"\"\"\n 将一个或多个值转换为可以放入文件路径的字符串\n \"\"\"\n if hasattr(v, \"__name__\"):\n return valid_str(v.__name__)\n if isinstance(v, tuple) or isinstance(v, list):\n return \"-\".join([valid_str(x) for x in v])\n str_v = str(v).lower()\n valid_chars = \"-_%s%s\" % (string.ascii_letters, string.digits)\n str_v = \"\".join(c if c in valid_chars else \"-\" for c in str_v)\n return str_v\n\n\nclass ExperimentGrid:\n \"\"\"\n 使用grid search 对超参数调优\n \"\"\"\n def __init__(self, name=''):\n self.keys = []\n self.vals = []\n self.shs = []\n self.in_names = []\n self.name(name)\n\n def name(self, _name):\n assert isinstance(_name, str), \"Name has to be a string.\"\n self._name = _name\n\n def print(self):\n \"\"\"\n 输出相关调参信息\n \"\"\"\n print(\"=\" * DIV_LINE_WIDTH)\n # 如果实验名字短,打印一行,如果太长打印两行\n base_msg = \"ExperimentGrid %s runs over parameters: \\n\"\n name_insert = \"[\" + self._name + \"]\"\n if len(base_msg % name_insert) <= 80:\n msg = base_msg % name_insert\n else:\n msg = base_msg % (name_insert + \"\\n\")\n print(colorize(msg, color=\"green\", bold=True))\n\n # list off parameters, shorthands, and possible values.\n for k, v, sh in zip(self.keys, self.vals, self.shs):\n color_k = colorize(k.ljust(40), color=\"cyan\", bold=True)\n print(\"\", color_k, \"[\" + sh + \"]\" if sh is not None else \"\", \"\\n\")\n for i, val in enumerate(v):\n print(\"\\t\" + str(convert_json(val)))\n print()\n\n # 计算变量数量\n nvars_total = int(np.prod([len(v) for v in self.vals]))\n if \"seed\" in self.keys:\n num_seeds = len(self.vals[self.keys.index(\"seed\")])\n nvars_seedless = int(nvars_total / num_seeds)\n else:\n nvars_seedless = nvars_total\n print(\" Variants, counting seeds: \".ljust(40), nvars_total)\n print(\" Variants, not counting seeds: \".ljust(40), nvars_seedless)\n print()\n print(\"=\" * DIV_LINE_WIDTH)\n\n def _default_shorthand(self, key):\n \"\"\"\n 对key做一个shorthand, 用冒号分隔后的每一部分的前三个字母表示, \n 如果前三个字符包含非数字字母, 就直接截掉\n \"\"\"\n valid_chars = \"%s%s\" % (string.ascii_letters, string.digits)\n\n def shear(x):\n return \"\".join(z for z in x[:3] if z in valid_chars)\n\n sh = \"-\".join([shear(x) for x in key.split(\":\")])\n return sh\n\n def add(self, key, vals, shorthand=None, in_name=False):\n \"\"\"\n Add a parameter (key) to the grid config, with potential values (vals).\n Args:\n key (string): Name of parameter.\n\n vals (value or list of values): Allowed values of parameter.\n\n shorthand (string): Optional, shortened name of parameter. For \n example, maybe the parameter ``steps_per_epoch`` is shortened\n to ``steps``. \n\n in_name (bool): When constructing variant names, force the\n inclusion of this parameter into the name.\n \"\"\"\n assert isinstance(key, str), \"Key must be a string.\"\n assert shorthand is None or isinstance(shorthand, str), \"Shorthand must be a string.\"\n if not isinstance(vals, list):\n vals = [vals]\n if DEFAULT_SHORTHAND and shorthand is None:\n shorthand = self._default_shorthand(key)\n self.keys.append(key)\n self.vals.append(vals)\n self.shs.append(shorthand)\n self.in_names.append(in_name)\n\n def variant_name(self, variant):\n \"\"\"\n 给定一个variant变量(有效参数/值组成的字典),创建exp_name\n 用variant构造grid_name, 形式为[variant]_[para_name/shorthand]_[values]\n \"\"\"\n def get_val(v, k):\n \"\"\"\n 从给定变量字典中获得正确值的实用方法.\n 假设参数k描述到嵌套字典的路径,例如k='a:b:c'对应于value=变量['a']['b']['c'].\n \"\"\"\n if k in v:\n return v[k]\n else:\n splits = k.split(\":\")\n k0, k1 = splits[0], \":\".join(splits[1:])\n return get_val(v[k0], k1)\n\n var_name = self._name\n for k, v, sh, inn in zip(self.keys, self.vals, self.shs, self.in_names):\n if (len(v) > 1 or inn) and not (k == \"seed\"):\n # 使用shorthand, 如果不行就用全名\n param_name = sh if sh is not None else k\n param_name = valid_str(param_name)\n # 对参数k,获取其变量值\n variant_val = get_val(variant, k)\n if all_bools(v):\n var_name += (\"_\" + param_name) if variant_val else \"\"\n else:\n var_name += \"_\" + param_name + valid_str(variant_val)\n\n return var_name.lstrip(\"_\")\n\n def _variants(self, keys, vals):\n \"\"\"\n 递归地构建有效变量列表\n \"\"\"\n if len(keys) == 1:\n pre_variants = [dict()]\n else:\n pre_variants = self._variants(keys[1:], vals[1:])\n variants = []\n for val in vals[0]:\n for pre_v in pre_variants:\n v = {}\n v[keys[0]] = val\n v.update(pre_v)\n variants.append(v)\n return variants\n\n def variants(self):\n \"\"\"\n 构造一个字典列表, 每个字典是grid里一个有效的config.\n 对于名称为 ``'full:param:name'``形式的变量参数有特殊的处理.\n 冒号表示参数有内嵌字典结构, 例如\n ==================== ===\n Key Val\n ==================== ===\n ``'base:param:a'`` 1\n ``'base:param:b'`` 2\n ==================== ===\n 表明变量字典的结构为\n variant = {\n base: {\n param : {\n a : 1,\n b : 2\n }\n } \n }\n\n \"\"\"\n flat_variants = self._variants(self.keys, self.vals)\n\n def unflatten_var(var):\n \"\"\"\n 基于key的name, 构建完整结构的字典\n \"\"\"\n new_var = dict()\n unflatten_set = set()\n for k, v in var.items():\n if \":\" in k:\n splits = k.split(\":\")\n k0 = splits[0]\n assert k0 not in new_var or isinstance(new_var[k0], dict), \\\n \"同一个key不能设置多个值.\"\n if not (k0 in new_var):\n new_var[k0] = dict()\n sub_k = \":\".join(splits[1:])\n new_var[k0][sub_k] = v\n unflatten_set.add(k0)\n else:\n assert not (k in new_var), \"同一个key不能设置多个值.\"\n new_var[k] = v\n for k in unflatten_set:\n new_var[k] = unflatten_var(new_var[k])\n return new_var\n\n new_variants = [unflatten_var(var) for var in flat_variants]\n return new_variants\n\n def run(self, thunk, num_cpu=1, data_dir=None, datestamp=False):\n \"\"\"\n 使用'thunk'函数运行grid中每一个变量.\n 'thunk' 必须是可调用函数或者字符串, 如果是string, 必须是参数的名字, 其值都是可调用函数.\n 使用``call_experiment`` 运行实验, 并使用``self.variant_name()``给定实验名字.\n\n 注意:ExperimentGrid.run与call_experiment的参数相同,`seed`除外\n \"\"\"\n self.print()\n # list 所有变量\n variants = self.variants()\n #输出变量名\n var_names = set([self.variant_name(var) for var in variants])\n var_names = sorted(list(var_names))\n line = \"=\" * DIV_LINE_WIDTH\n preparing = colorize(\"Preparing to run the following experiment...\", color=\"green\", bold=True)\n joined_var_names = '\\n'.join(var_names)\n announcement = f\"\\n{preparing}\\n\\n{joined_var_names}\\n\\n{line}\"\n print(announcement)\n\n if WAIT_BEFORE_LAUNCH > 0:\n delay_msg = colorize(dedent(\"\"\"\n Launch delayed to give you a few seconds to review your experiments.\n\n To customize or disable this behavior, change WAIT_BEFORE_LAUNCH in\n spinup/config.py.d\n\n \"\"\"),\n color=\"cyan\",\n bold=True) + line\n print(delay_msg)\n wait, steps = WAIT_BEFORE_LAUNCH, 100\n prog_bar = trange(steps,\n desc=\"launching in...\",\n leave=False,\n ncols=DIV_LINE_WIDTH,\n mininterval=0.25,\n bar_format=\"{desc}: {bar}| {remaining} {elapsed}\")\n for _ in prog_bar:\n time.sleep(wait / steps)\n for var in variants:\n exp_name = self.variant_name(var)\n if isinstance(thunk, str):\n thunk_ = var[thunk]\n del var[thunk]\n else:\n thunk_ = thunk\n\n call_experiment(exp_name=exp_name,\n thunk=thunk_,\n num_cpu=num_cpu,\n data_dir=data_dir,\n datestamp=datestamp,\n **var)\n\n\ndef test_eg():\n eg = ExperimentGrid()\n eg.add(\"test:a\", [1, 2, 3], \"ta\", True)\n eg.add(\"test:b\", [1, 2, 3])\n eg.add(\"some\", [4, 5])\n eg.add(\"why\", [True, False])\n eg.add(\"huh\", 5)\n eg.add(\"no\", 6, in_name=True)\n return eg.variants()\n\n\nif __name__ == \"__main__\":\n a = test_eg()\n print(a)\n b = [{\n 'clip_ratio': 0.1,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.1,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 0,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 10,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [32, 32],\n 'activation': \"\"\n }\n }, {\n 'clip_ratio': 0.2,\n 'seed': 20,\n 'env_name': 'Ant-v2',\n 'ac_kwargs': {\n 'hidden_sizes': [64, 32],\n 'activation': \"\"\n }\n }]\n print(len(b))\n","sub_path":"ddpg/tools/experiment_grid.py","file_name":"experiment_grid.py","file_ext":"py","file_size_in_byte":15483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139832620","text":"#!/usr/bin/env python\n#\n# Copyright (c) 2012-2014 Poul-Henning Kamp \n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n\n\"\"\"\nMemory classes\n\nThese classes can be configured to act as memory for images to be\nanalysed.\n\nIn addition to the numerical value of each location, it is also\npossible to associate up to seven attributes with each location.\nThese can be used to record structural information in the media,\nfor instance relocation flags, write-ability etc.\n\nXXX: Better test-cases needed\nXXX: Need resolution of who controls rendering...\n\n\"\"\"\n\nfrom __future__ import print_function\n\nimport ctypes\n\nDEFINED = (1 << 7)\n\nclass MemError(Exception):\n\tdef __init__(self, adr, reason):\n\t\tsuper(MemError, self).__init__()\n\t\tself.adr = adr\n\t\tself.reason = reason\n\t\tself.value = (\"0x%x:\" % adr + str(self.reason),)\n\tdef __str__(self):\n\t\treturn repr(self.value)\n\nclass address_space(object):\n\t\"\"\"\n\tA vacuous address-space and base-class for actual address-spaces\n\tand memory types\n\t\"\"\"\n\tdef __init__(self, lo, hi, name=\"\"):\n\t\tassert lo <= hi\n\t\tself.lo = lo\n\t\tself.hi = hi\n\t\tself.name = name\n\n\tdef __repr__(self):\n\t\treturn \"\" % (\n\t\t self.name, self.lo, self.hi\n\t\t)\n\n\tdef __getitem__(self, a):\n\t\ta = self._off(a)\n\t\traise MemError(a, \"Undefined\")\n\n\tdef __setitem__(self, a, d):\n\t\ta = self._off(a)\n\t\traise MemError(a, \"Undefined\")\n\n\tdef _off(self, a):\n\t\tif a < self.lo:\n\t\t\traise MemError(a, \"Address too low\")\n\t\tif a >= self.hi:\n\t\t\traise MemError(a, \"Address too high\")\n\t\treturn a - self.lo\n\n\nclass word_mem(address_space):\n\t\"\"\"\n\tWord memory is characteristic for a lot of the earliest computers,\n\tthey could access exactly one word at a time, or possibly fractions\n\tof a word, but the instruction set did not support any \"super-size\"\n\tdata types or access spanning multiple words.\n\n\tTypical examples: Pretty much any ancestor of Von Neumans early\n\tcomputers down to most of the minicomputers from DEC and DG.\n\n\tLargest supported word-width is 64 bits.\n\t\"\"\"\n\n\tdef __init__(self, lo, hi, bits=8, attr=0):\n\t\tassert lo < hi\n\t\tassert bits > 0\n\t\tassert bits <= 64\n\t\tassert attr >= 0\n\t\tassert attr <= 7\n\n\t\tsuper(word_mem, self).__init__(lo, hi)\n\n\t\tself.bits = bits\n\t\tself.fmt = \"%\" + \"0%dx\" % ((bits + 3) // 4)\n\t\tself.undef = \"-\" * ((bits + 3) // 4)\n\t\tself.ascii = (bits & 7) == 0\n\t\tself.lo = lo\n\t\tself.hi = hi\n\t\tself.attr = attr\n\t\tl = hi - lo\n\n\t\tself.msk = (1 << bits) - 1\n\t\tself.amsk = (1 << attr) - 1\n\n\t\tif bits <= 8:\n\t\t\tself.mt = ctypes.c_uint8\n\t\telif bits <= 16:\n\t\t\tself.mt = ctypes.c_uint16\n\t\telif bits <= 32:\n\t\t\tself.mt = ctypes.c_uint32\n\t\telse:\n\t\t\tself.mt = ctypes.c_uint64\n\n\t\tself.m = (self.mt * l)()\n\n\t\tself.at = ctypes.c_uint8\n\t\tself.a = (self.at * l)()\n\n\t\t#self.pm = ctypes.pointer(self.m[0])\n\t\t#self.pa = ctypes.pointer(self.a[0])\n\n\tdef __repr__(self):\n\t\treturn \"\" % (\n\t\t self.lo, self.hi, self.bits, self.attr)\n\n\tdef __getitem__(self, a):\n\t\t\"\"\"Read location\"\"\"\n\t\tb = self._off(a)\n\t\tif not self.a[b] & DEFINED:\n\t\t\traise MemError(a, \"Undefined\")\n\t\treturn self.m[b]\n\n\tdef rd(self, a):\n\t\treturn self[a]\n\n\tdef __setitem__(self, a, d):\n\t\t\"\"\"Write location\"\"\"\n\t\tif d & ~self.msk:\n\t\t\traise MemError(a, \"Data too big (0x%x)\" % d)\n\t\tb = self._off(a)\n\t\tself.m[b] = self.mt(d)\n\t\tself.a[b] |= DEFINED\n\n\tdef wr(self, a, d):\n\t\tself[a] = d\n\n\tdef get_attr(self, a):\n\t\t\"\"\"Get attributes\"\"\"\n\t\tb = self._off(a)\n\t\treturn self.a[b] & self.amsk\n\n\tdef set_attr(self, a, x):\n\t\t\"\"\"Set attributes\"\"\"\n\t\tif x & ~self.amsk:\n\t\t\traise MemError(a, \"Attribute too big (0x%x)\" % x)\n\t\tb = self._off(a)\n\t\tself.a[b] |= x\n\n\tdef clr_attr(self, a, x):\n\t\t\"\"\"Clear attributes\"\"\"\n\t\tif x & ~self.amsk:\n\t\t\traise MemError(a, \"Attribute too big (0x%x)\" % x)\n\t\tb = self._off(a)\n\t\tself.a[b] &= ~x\n\n\tdef do_ascii(self, w):\n\t\t\"\"\"Return an ASCII representation of a value\"\"\"\n\t\ts = \" |\"\n\t\tb = self.bits - 8\n\t\twhile b >= 0:\n\t\t\tif w is None:\n\t\t\t\ts += \" \"\n\t\t\telse:\n\t\t\t\tx = (w >> b) & 0xff\n\t\t\t\tif x > 32 and x < 127:\n\t\t\t\t\ts += \"%c\" % x\n\t\t\t\telse:\n\t\t\t\t\ts += \" \"\n\t\t\tb -= 8\n\t\treturn s + \"|\"\n\n\tdef render(self, pj, lo, hi):\n\t\t\"\"\"\n\t\tRender a location\n\n\t\tXXX: The PJ gets to render the address, but mem\n\t\tXXX: renders the value. Make it consistent.\n\t\t\"\"\"\n\t\tl = list()\n\t\twhile lo < hi:\n\t\t\ts = pj.afmt(lo) + \" \"\n\t\t\ttry:\n\t\t\t\tw = self.rd(lo)\n\t\t\t\ts += self.fmt % w\n\t\t\texcept MemError:\n\t\t\t\tw = None\n\t\t\t\ts += self.undef\n\n\t\t\tif self.amsk > 0x0f:\n\t\t\t\ts += \" /%02x \" % self.get_attr(lo)\n\t\t\telif self.amsk > 0x0:\n\t\t\t\ts += \" /%x \" % self.get_attr(lo)\n\n\t\t\tif self.ascii:\n\t\t\t\ts += self.do_ascii(w)\n\t\t\tlo += 1\n\t\t\tl.append(s)\n\t\treturn l\n\n\nclass byte_mem(word_mem):\n\t\"\"\"\n\tByte memory is characteristic of microcomputers, which typically\n\thad very narrow busses, 4 or 8 bits, but which had instructions\n\tfor operating on wider types than the buswidth.\n\n\tThis introduces the issue of which \"endianess\" but this is not\n\treally attribute of the memory, it is an attribute of the CPU,\n\tinstruction set or interpreted code, so we provide both \"sexes\"\n\tand leave it up to everybody else to use the right one.\n\t\"\"\"\n\n\tdef __init__(self, lo, hi, attr=0):\n\t\tsuper(byte_mem, self).__init__(lo, hi, 8, attr)\n\t\tself.ncol = 4\n\t\tself.ascii = True\n\n\tdef u8(self, a):\n\t\t\"\"\"Unsigned 8-bit byte\"\"\"\n\t\treturn self.rd(a)\n\n\tdef s8(self, a):\n\t\t\"\"\"Signed 8-bit byte\"\"\"\n\t\tb = self.rd(a)\n\t\tif b & 0x80:\n\t\t\tb -= 256\n\t\treturn b\n\n\tdef bu16(self, a):\n\t\t\"\"\"Big Endian Unsigned 16-bit half-word\"\"\"\n\t\tb = self.rd(a) << 8\n\t\tb |= self.rd(a + 1)\n\t\treturn b\n\n\tdef bu32(self, a):\n\t\t\"\"\"Big Endian Unsigned 32-bit word\"\"\"\n\t\tb = self.rd(a) << 24\n\t\tb |= self.rd(a + 1) << 16\n\t\tb |= self.rd(a + 2) << 8\n\t\tb |= self.rd(a + 3)\n\t\treturn b\n\n\tdef bu64(self, a):\n\t\t\"\"\"Big Endian Unsigned 64-bit double-word\"\"\"\n\t\tb = self.rd(a) << 56\n\t\tb |= self.rd(a + 1) << 48\n\t\tb |= self.rd(a + 2) << 40\n\t\tb |= self.rd(a + 3) << 32\n\t\tb |= self.rd(a + 4) << 24\n\t\tb |= self.rd(a + 5) << 16\n\t\tb |= self.rd(a + 6) << 8\n\t\tb |= self.rd(a + 7)\n\t\treturn b\n\n\tdef lu16(self, a):\n\t\t\"\"\"Little Endian Unsigned 16-bit half-word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\treturn b\n\n\tdef lu32(self, a):\n\t\t\"\"\"Little Endian Unsigned 32-bit word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\tb |= self.rd(a + 2) << 16\n\t\tb |= self.rd(a + 3) << 24\n\t\treturn b\n\n\tdef lu64(self, a):\n\t\t\"\"\"Little Endian Unsigned 64-bit double-word\"\"\"\n\t\tb = self.rd(a)\n\t\tb |= self.rd(a + 1) << 8\n\t\tb |= self.rd(a + 2) << 16\n\t\tb |= self.rd(a + 3) << 24\n\t\tb |= self.rd(a + 4) << 32\n\t\tb |= self.rd(a + 5) << 40\n\t\tb |= self.rd(a + 6) << 48\n\t\tb |= self.rd(a + 7) << 56\n\t\treturn b\n\n\tdef bs16(self, a):\n\t\t\"\"\"Big Endian Signed 16-bit half-word\"\"\"\n\t\tb = self.bu16(a)\n\t\tif b & 0x8000:\n\t\t\tb -= 0x10000\n\t\treturn b\n\n\tdef ls16(self, a):\n\t\t\"\"\"Little Endian Signed 16-bit half-word\"\"\"\n\t\tb = self.lu16(a)\n\t\tif b & 0x8000:\n\t\t\tb -= 0x10000\n\t\treturn b\n\n\tdef bs32(self, a):\n\t\t\"\"\"Big Endian Signed 32-bit word\"\"\"\n\t\tb = self.bu32(a)\n\t\tif b & 0x80000000:\n\t\t\tb -= 0x100000000\n\t\treturn b\n\n\tdef ls32(self, a):\n\t\t\"\"\"Little Endian Signed 32-bit word\"\"\"\n\t\tb = self.lu32(a)\n\t\tif b & 0x80000000:\n\t\t\tb -= 0x100000000\n\t\treturn b\n\n\tdef bs64(self, a):\n\t\t\"\"\"Big Endian Signed 64-bit double-word\"\"\"\n\t\tb = self.bu64(a)\n\t\tif b & 0x8000000000000000:\n\t\t\tb -= 0x10000000000000000\n\t\treturn b\n\n\tdef ls64(self, a):\n\t\t\"\"\"Little Endian Signed 64-bit double-word\"\"\"\n\t\tb = self.lu64(a)\n\t\tif b & 0x8000000000000000:\n\t\t\tb -= 0x10000000000000000\n\t\treturn b\n\n\tdef load_data(self, first, step, data):\n\t\tfor i in data:\n\t\t\tself.wr(first, i)\n\t\t\tfirst += step\n\n\tdef load_binfile(self, first, step, filename):\n\t\tfi = open(filename, \"rb\")\n\t\td = bytearray(fi.read())\n\t\tfi.close()\n\t\tself.load_data(first, step, d)\n\n\tdef render(self, pj, lo, hi):\n\t\t\"\"\"\n\t\tRender 'ncol' bytes per line\n\n\t\tXXX: ncol should be parameterized\n\n\t\tXXX: The PJ gets to render the address, but mem\n\t\tXXX: renders the value. Make it consistent.\n\t\t\"\"\"\n\t\tl = list()\n\t\twhile lo < hi:\n\t\t\ts = \"\"\n\t\t\tt = \"\"\n\t\t\ts += pj.afmt(lo) + \" \"\n\t\t\tfor i in range(self.ncol):\n\t\t\t\tif lo + i < hi:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tv = self.rd(lo + i)\n\t\t\t\t\t\ts += \" %02x\" % v\n\t\t\t\t\t\tif v < 32 or v > 126:\n\t\t\t\t\t\t\tt += \" \"\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tt += \"%c\" % v\n\t\t\t\t\texcept MemError:\n\t\t\t\t\t\ts += \" --\"\n\t\t\t\t\t\tt += \" \"\n\t\t\t\telse:\n\t\t\t\t\ts += \" \"\n\t\t\t\t\tt += \" \"\n\t\t\tif self.ascii:\n\t\t\t\ts += \" |\" + t + \"|\"\n\t\t\tl.append(s)\n\t\t\tlo += self.ncol\n\t\treturn l\n\nif __name__ == \"__main__\":\n\tm = word_mem(0x0000, 0x1000, bits=64, attr=3)\n\tprint(m)\n\tprint(type(m.m), ctypes.sizeof(m.m))\n\tm.wr(0x100, 0x123456789)\n\tprint(\"%x\" % m.rd(0x100))\n\tprint(m.get_attr(0x100))\n\tprint(m.get_attr(0x101))\n\tprint(m.set_attr(0x101, 4))\n\tprint(m.get_attr(0x101))\n","sub_path":"pyreveng/mem.py","file_name":"mem.py","file_ext":"py","file_size_in_byte":9733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"169648717","text":"from bs4 import BeautifulSoup\r\nimport lxml\r\nimport requests\r\n\r\nURL = 'https://www.mohfw.gov.in/'\r\n\r\nresponse = requests.get(url=URL)\r\ncovid_data_web = response.text\r\ncovid_data = BeautifulSoup(covid_data_web, parser=\"html.parse\", features=\"lxml\")\r\n\r\n\r\ntotal_data = covid_data.find_all(name='strong', class_='mob-hide')\r\ntotal_data = [data.getText() for data in total_data]\r\ntotal_cases = total_data[1]\r\ntotal_cases = total_cases.replace(u'\\xa0', u' ') + \" Today's Count\"\r\nprint(total_cases)\r\ntotal_recoveries = total_data[3]\r\ntotal_recoveries = total_recoveries.replace(u'\\xa0', u' ') + \" Today's Count\"\r\ntotal_death = total_data[5]\r\ntotal_death = total_death.replace(u'\\xa0', u' ') + \" Today's Count\"\r\n\r\n\r\nvaccinated_data = covid_data.find_all(name='span', class_='coviddata')\r\nvaccinated_data = [data.getText() for data in vaccinated_data]\r\ntotal_vaccinated_people = vaccinated_data[0]\r\ntotal_vaccinated_people = total_vaccinated_people.replace(u'\\xa0', u' ')","sub_path":"covid-help-app/covid_related_data.py","file_name":"covid_related_data.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645824777","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn\nimport pandas as pd\nimport os\nimport sys\nimport time\nimport tensorflow as tf\nfrom sklearn.preprocessing import StandardScaler #用于归一化\n\nfrom tensorflow import keras\n\nprint(tf.__version__)\nprint(sys.version_info)\nfor module in mpl, np, pd, sklearn, tf, keras:\n print(module.__name__, module.__version__)\n\nfashion_mnist = keras.datasets.fashion_mnist\n(x_train_all, y_train_all), (x_test, y_test) = fashion_mnist.load_data() \nx_valid, x_train = x_train_all[:5000], x_train_all[5000:]\ny_valid, y_train = y_train_all[:5000], y_train_all[5000:]\n\nprint(x_valid.shape, y_valid.shape)\nprint(x_train.shape, y_train.shape)\nprint(x_test.shape, y_test.shape)\nprint(np.max(x_train), np.min(x_train))\n\n#数据归一化 x = (x-u)/std\nscalar = StandardScaler()\nx_train_scaled = scalar.fit_transform(x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nx_valid_scaled = scalar.transform(x_valid.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nx_test_scaled = scalar.transform(x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)\nprint(x_test_scaled)\nprint(np.max(x_train_scaled), np.min(x_train_scaled))\n\n\ndef main():\n model = keras.models.Sequential()\n model.add(keras.layers.Flatten(input_shape = [28,28]))\n for _ in range(20):\n model.add(keras.layers.Dense(100, activation = \"relu\"))\n model.add(keras.layers.Dense(10, activation = \"softmax\"))\n\n #relu: y = max(0,x)\n #softmax: x = [x1, x2, x3], y=[e^x1/sum, e^x2/sum, e^x3/sum] sum 是上面三个的和\n\n #sparse的原因:这里y只是一个index,要用sparse_categorical_crossentropy,这个会用onehot把y转成向量\n model.compile(loss=\"sparse_categorical_crossentropy\", optimizer = \"sgd\", metrics = [\"accuracy\"])\n model.summary()\n logdir = '.\\\\dnn-callbacks'\n if not os.path.exists(logdir):\n os.mkdir(logdir)\n output_model_file = os.path.join(logdir, \"fashion_mnist_model.h5\")\n callbacks = [\n keras.callbacks.TensorBoard(logdir),\n keras.callbacks.ModelCheckpoint(output_model_file, save_best_only = True),\n keras.callbacks.EarlyStopping(patience = 5, min_delta = 1e-2)\n ]\n history = model.fit(x_train_scaled, y_train, epochs = 10, validation_data=(x_valid, y_valid), callbacks = callbacks)\n model.evaluate(x_test_scaled, y_test)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"classification/dnn-callback_tf_keras_classification_model.py","file_name":"dnn-callback_tf_keras_classification_model.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"616706088","text":"##############################################################################################################################\n###### SPHERE IN OPEN SPACE ##########################################################################################################\n##############################################################################################################################\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.linalg as linalg\nimport scipy.signal as signal\nimport matplotlib.gridspec as gridspec\nfrom function_e import *\nimport os\nimport sys\nnp.set_printoptions(precision=4)\n# os.environ['OPENBLAS_NUM_THREADS'] = '4'\nimport time\nstart = time.time()\n\n###### MAIN PROGRAM ##########################################################################################################\n## Mau's constants\npi = np.pi\nmicro = 1e-6\nfemto = 1e-15\npeta = 1e15\ncc = 299792458\nmu_0 = pi*4e-7\neps_0 = 1./(mu_0*cc**2)\n##--- PARAMETER ----------------#########################\nscale_light = 1e8\nmicro = 1e-6\nscale_frequ = scale_light/micro # 1e14\ncel = cc/scale_light\nmu0 = mu_0 *scale_light\nep0 = eps_0 *scale_light\n\ne_scale = 1e-1\nr_ellipse_2 = 1*e_scale\n# r_ellipse_2 = 1*e_scale\nxS , yS , zS = 1.2 *e_scale, 1.2 *e_scale, 1.2 *e_scale\nxD1, yD1, zD1 =-1.2 *e_scale,-1.2 *e_scale,-1.2 *e_scale\nxD2, yD2, zD2 = 1.2 *e_scale,-1.2 *e_scale, 1.2 *e_scale\n\nr_source = 10e-2*e_scale\n\n# lambda_m = 0.2*e_scale\nlambda_m = 0.25*e_scale\n# lambda_m = 0.26*e_scale\n# lambda_m = 0.32*e_scale\nD_pml_in = 3*e_scale\npml_size = 4*e_scale\n# pml_size = 3*e_scale\n\n# epsr = 16+1j\n# epsilon_oo = 3.36174\n# omega_p = 1.3388e16/scale_frequ\n# gamma = 7.07592e13/scale_frequ\n\n# epsilon_oo = 1\n# omega_p = 1.26e16/scale_frequ\n# gamma = 1.41e14/scale_frequ\n\nepsilon_oo = 6\nomega_p = 4.572e15/2/scale_frequ\ngamma = 1.332e15/scale_frequ\n\neps_mil = 1\nE_or_H = 0 # electric or magnetic\nPML_or_not = 1\nPML_stype = 0\n# vector0vs1 = 0\t# scalar or vector\ntype_source = 1 # line source or plane wave\nneig = 350\n\npar_gmsh_getdp = open('parameters_gmsh_getdp.dat', 'w')\npar_gmsh_getdp.write('neig = %d;\\n'%(neig))\npar_gmsh_getdp.write('xS = %3.3e;\\n'%(xS))\npar_gmsh_getdp.write('yS = %3.3e;\\n'%(yS))\npar_gmsh_getdp.write('zS = %3.3e;\\n'%(zS))\npar_gmsh_getdp.write('xD1 = %3.3e;\\n'%(xD1))\npar_gmsh_getdp.write('yD1 = %3.3e;\\n'%(yD1))\npar_gmsh_getdp.write('zD1 = %3.3e;\\n'%(zD1))\npar_gmsh_getdp.write('xD2 = %3.3e;\\n'%(xD2))\npar_gmsh_getdp.write('yD2 = %3.3e;\\n'%(yD2))\npar_gmsh_getdp.write('zD2 = %3.3e;\\n'%(zD2))\n# par_gmsh_getdp.write('r_ellipse_1 = %3.3e;\\n'%(r_ellipse_1))\npar_gmsh_getdp.write('r_ellipse_2 = %3.3e;\\n'%(r_ellipse_2))\n# par_gmsh_getdp.write('r_ellipse_3 = %3.3e;\\n'%(r_ellipse_3))\npar_gmsh_getdp.write('r_source = %3.3e;\\n'%(r_source))\npar_gmsh_getdp.write('lambda_m = %3.3e;\\n'%(lambda_m))\npar_gmsh_getdp.write('D_pml_in = %3.3e;\\n'%(D_pml_in))\npar_gmsh_getdp.write('pml_size = %3.3e;\\n'%(pml_size))\npar_gmsh_getdp.write('cel = %3.3e;\\n'%(cel))\npar_gmsh_getdp.write('mu0 = %3.3e;\\n'%(mu0))\npar_gmsh_getdp.write('epsilon0 = %3.3e;\\n'%(ep0))\npar_gmsh_getdp.write('eps_mil_re = %3.3e;\\n'%(eps_mil.real))\npar_gmsh_getdp.write('eps_mil_im = %3.3e;\\n'%(eps_mil.imag))\n# par_gmsh_getdp.write('eps_diff_re = %3.3e;\\n'%(epsr.real ))\n# par_gmsh_getdp.write('eps_diff_im = %3.3e;\\n'%(epsr.imag ))\npar_gmsh_getdp.write('PML = 0.2;\\n')\n# par_gmsh_getdp.write('PML = 0;\\n')\n# par_gmsh_getdp.write('angle = Pi/10;\\n')\npar_gmsh_getdp.write('E_or_H = %d;\\n'%(E_or_H))\npar_gmsh_getdp.write('PML_or_not = %d;\\n'%(PML_or_not))\npar_gmsh_getdp.write('PML_stype = %d;\\n'%(PML_stype))\npar_gmsh_getdp.write('type_source = %d;\\n'%(type_source))\npar_gmsh_getdp.write('epsilon_oo = %3.5e;\\n'%(epsilon_oo))\npar_gmsh_getdp.write('omega_p = %3.5e;\\n'%(omega_p))\npar_gmsh_getdp.write('gamma = %3.5e;\\n'%(gamma))\npar_gmsh_getdp.write('zone1 = 1;\\n')\npar_gmsh_getdp.write('zone2 = 30;\\n')\npar_gmsh_getdp.close()\n\ngmsh_path = ''\ngetdp_path = ''\nif PML_or_not == 1:\n\t# mesh_filename = 'mesh_3D_line.msh'\n\t# mesh_geo = 'mesh_3D_line.geo'\n\tmesh_filename = 'mesh_compute.msh'\n\tmesh_geo = 'mesh_compute.geo'\nelse:\n\tmesh_filename = 'mesh_3D_line_simple.msh'\n\tmesh_geo = 'mesh_3D_line_simple.geo'\n\t## change mesh\n\t# mesh_filename = 'mesh_3D_sphere_simple.msh'\n\t# mesh_geo = 'mesh_3D_sphere_simple.geo'\t\nos.system(gmsh_path+'gmsh '+mesh_geo+' -3 -o '+mesh_filename)\n\n##### SPECTRAL PROBLEM ############################################################################\nslepc_options_pep = ' -pep_max_it 400 -pep_target_magnitude'\nslepc_options_rational = ' -nep_max_it 200 -nep_type nleigs -nep_rational -nep_target_magnitude -petsc_prealloc 100 \\\n\t\t\t\t\t-rg_interval_endpoints -50,50,10,80'# -v 0'\n\t\t\t\t\t# ' -nep_max_it 100 -nep_type nleigs -nep_rational -nep_target_magnitude -rg_interval_endpoints -50,9,-30,50'\nspec_getdp = getdp_path+'getdp spectral_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop -slepc'# -v 0' \nos.system(spec_getdp + slepc_options_rational)\neigs = np.loadtxt('EigenValuesReal.txt',usecols=[5]) + 1j*np.loadtxt('EigenValuesImag.txt',usecols=[5])\nneig = len(eigs)\t\t\t\t\t\n\nplt.figure()\nvpr = np.loadtxt('EigenValuesReal.txt',usecols=[5])\nvpi = np.loadtxt('EigenValuesImag.txt',usecols=[5])\nplt.plot(vpr, vpi, 'C0o',markersize=3 ,mfc='none')\nfor k in range(len(vpr)):\n plt.annotate(k, xy=(vpr[k],vpi[k]), xytext=None, xycoords='data', textcoords='data', arrowprops=None)\nplt.title(\"Eigenvalues\")\nplt.xlabel(\"Re\")\nplt.ylabel(\"Im\")\n\nos.system('rm norm1.txt norm2.txt')\nnorm_getdp = getdp_path+'getdp norm.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_norm -v 0'\nos.system(norm_getdp)\nnorm1 = np.loadtxt('norm1.txt',usecols=[5]) + 1j*np.loadtxt('norm1.txt',usecols=[6] ) \nnorm2 = np.loadtxt('norm2.txt',usecols=[5]) + 1j*np.loadtxt('norm2.txt',usecols=[6] ) \nd1 = 1/cel**2 * ( 2*epsilon_oo*eigs - 1j*gamma*omega_p**2/(eigs+1j*gamma)**2 ) * norm1\nd2 = 2/cel**2 * eigs * norm2 \ndd = d1+d2\n##################################################################################################################################\nN_frequency = 10\nE0_0 = np.zeros((N_frequency,4),dtype=complex)\nE0_1 = np.zeros((N_frequency,4),dtype=complex)\nE0_2 = np.zeros((N_frequency,4),dtype=complex)\nE2 = np.zeros((N_frequency,4))\nE2_all = np.zeros((N_frequency,4))\n\nE0_0t = np.zeros((N_frequency,4),dtype=complex)\nE0_1t = np.zeros((N_frequency,4),dtype=complex)\nE0_2t = np.zeros((N_frequency,4),dtype=complex)\nE2t = np.zeros((N_frequency,4))\nE2_allt = np.zeros((N_frequency,4))\nomegas = np.linspace(25,60,N_frequency)\nfor i,omega0 in enumerate(omegas) :\n\tlambda0 = 2.*pi*cel/omega0\t\n\t# omega0 = 2.*pi*cel/lambda0\n\tepsr = epsilon_oo - omega_p**2/(omega0**2+1j*omega0*gamma) \n\t# print(epsr)\n\tpar_gmsh_getdp = open('parameters_gmsh_getdp.dat', 'a')\n\tpar_gmsh_getdp.write('lambda0 = %3.3e;\\n'%(lambda0))\n\tpar_gmsh_getdp.write('neig = %d;\\n'%(neig))\n\tpar_gmsh_getdp.write('eps_diff_re = %3.3e;\\n'%(epsr.real ))\n\tpar_gmsh_getdp.write('eps_diff_im = %3.3e;\\n'%(epsr.imag ))\n\tpar_gmsh_getdp.close()\n\t############ direct ##################################################################\n\tdirect_getdp = getdp_path+'getdp direct_3D.pro -pre Scattering -msh '+mesh_filename+' -cal -pos postop_scat -v 0' \n\tos.system(direct_getdp)\n\tE2[i,0] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,0] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,0] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,0] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,0] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\n\tE2t[i,0] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,0] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,0] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,0] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,0] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t##### COMPUTE PROJECTION PROBLEM ######################################################### \n\t#### norm ------------------------------------#####\n\tos.system('rm Jns.txt')\n\tJn_getdp = getdp_path+'getdp Jn.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_Jn -v 0'\n\tos.system(Jn_getdp)\n\tJn = np.loadtxt('Jns.txt',usecols=[5]) + 1j*np.loadtxt('Jns.txt',usecols=[6] ) \n\t### Pns 0 #########################\n\tPns0 = Jn/(omega0-eigs)/dd\n\tPns1 = Jn/(omega0-eigs)/dd*(eigs/omega0)\n\t# Pns2 = Jn/(omega0-eigs)/dd*((eigs-33)/(omega0-33))\n\t#####################################################################\t\n\tfile_Pns = open('Pns.dat', 'w')\n\tfor k, Pn in enumerate(Pns0):\n\t file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\tfile_Pns.close()\n\tproject_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\tos.system(project_getdp)\n\tos.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\tprojection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\tos.system(projection_coeff_getdp)\n\tE2[i,1] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,1] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,1] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,1] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,1] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\tE2t[i,1] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,1] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,1] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,1] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,1] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t######2----------------------------------#####\n\tfile_Pns = open('Pns.dat', 'w')\n\tfor k, Pn in enumerate(Pns1):\n\t file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\tfile_Pns.close()\n\tproject_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\tos.system(project_getdp)\n\tos.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\tprojection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\tos.system(projection_coeff_getdp)\n\tE2[i,2] = np.loadtxt('E2.txt')[1]\n\tE2_all[i,2] = np.loadtxt('E2_all.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\tE0_0[i,2] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1[i,2] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2[i,2] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\tE2t[i,2] = np.loadtxt('E2t.txt')[1]\n\tE2_allt[i,2] = np.loadtxt('E2_allt.txt')[1]\n\tE0_txt, E1_txt, E2_txt = np.loadtxt('E0_0t.txt'), np.loadtxt('E0_1t.txt'), np.loadtxt('E0_2t.txt')\n\tE0_0t[i,2] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\tE0_1t[i,2] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\tE0_2t[i,2] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\t# ########3----------------------------------#####\n\t# file_Pns = open('Pns.dat', 'w')\n\t# for k, Pn in enumerate(Pns2):\n\t# file_Pns.write('Pns_re_%d = %3.5e;\\n'%(k,Pn.real))\n\t# file_Pns.write('Pns_im_%d = %3.5e;\\n'%(k,Pn.imag))\n\t# file_Pns.close()\n\t# project_getdp = getdp_path+'getdp projection_3D.pro -pre Projection -msh '+mesh_filename+' -res spectral_3D.res -pos postop_modal -bin -v 0'\n\t# os.system(project_getdp)\n\t# os.system('rm E2.txt E2_all.txt E0_0.txt E0_1.txt E0_2.txt')\n\t# projection_coeff_getdp = getdp_path+'getdp projection_coeff_3D.pro -pre Projection -msh '+mesh_filename+' -cal -pos postop_modal -v 0' \n\t# os.system(projection_coeff_getdp)\n\t# E2[i,3] = np.loadtxt('E2.txt')[1]\n\t# E2_all[i,3] = np.loadtxt('E2_all.txt')[1]\n\t# E0_txt, E1_txt, E2_txt = np.loadtxt('E0_0.txt'), np.loadtxt('E0_1.txt'), np.loadtxt('E0_2.txt')\n\t# E0_0[i,3] = np.sqrt( E0_txt[5]**2 + E0_txt[6]**2 + E0_txt[7]**2 ) + 1j*np.sqrt( E0_txt[8]**2 + E0_txt[9]**2 + E0_txt[10]**2 )\n\t# E0_1[i,3] = np.sqrt( E1_txt[5]**2 + E1_txt[6]**2 + E1_txt[7]**2 ) + 1j*np.sqrt( E1_txt[8]**2 + E1_txt[9]**2 + E1_txt[10]**2 )\n\t# E0_2[i,3] = np.sqrt( E2_txt[5]**2 + E2_txt[6]**2 + E2_txt[7]**2 ) + 1j*np.sqrt( E2_txt[8]**2 + E2_txt[9]**2 + E2_txt[10]**2 )\n\n# os.system(gmsh_path+'gmsh '+mesh_geo+' us.pos up.pos')\n# os.system(gmsh_path+'gmsh '+mesh_geo+' us.pos up.pos -merge compare.geo')\ndumpglob2npz('output.npz',globals()) \nplt.show()","sub_path":"main_3D_PML.py","file_name":"main_3D_PML.py","file_ext":"py","file_size_in_byte":14117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"468116947","text":"# @title Map new RD3 records\r\n# @description for new records, map them to the intermediate table\r\n# @param data input dataset to process\r\n# @param id_suffix content to append to ID, e.g., \"_original\"\r\n# @return a list of dictionaries\r\ndef map_rd3_new_records(data, id_suffix):\r\n out = []\r\n for d in data:\r\n tmp = {}\r\n tmp['id'] = d.get('subject_id') + id_suffix\r\n tmp['EGA'] = d.get('file_ega_id')\r\n tmp['EGApath'] = d.get('file_path')\r\n tmp['name'] = d.get('file_name')\r\n tmp['md5'] = d.get('unencrypted_md5_checksum')\r\n tmp['typeFile'] = d.get('file_type')\r\n tmp['filegroupID'] = d.get('file_group_id')\r\n tmp['batchID'] = d.get('batch_id')\r\n tmp['experimentID'] = d.get('project_experiment_dataset_id')\r\n tmp['sampleID'] = d.get('sample_id')\r\n tmp['subjectID'] = d.get('subject_id')\r\n tmp['sequencingCentre'] = d.get('sequencing_center')\r\n tmp['sequencer'] = d.get('platform_model')\r\n tmp['libraryType'] = d.get('library_source').title()\r\n tmp['capture'] = d.get('library_selection')\r\n tmp['seqType'] = d.get('library_strategy')\r\n tmp['libraryLayout'] = d.get('library_layout')\r\n tmp['tissueType'] = d.get('tissue_type')\r\n tmp['materialType'] = d.get('sample_type')\r\n tmp['project_batch_id'] = d.get('project_batch_id')\r\n tmp['run_ega_id'] = d.get('run_ega_id')\r\n tmp['experiment_ega_id'] = d.get('experiment_ega_id')\r\n out.append(tmp)\r\n return out","sub_path":"archive/novelomics_new_record_mapping.py","file_name":"novelomics_new_record_mapping.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281644403","text":"import tensorflow as tf\nfrom keras.layers import *\nfrom keras.models import Model\nfrom sklearn.metrics import f1_score\n\n\ndef fit_save(model, x, y, batch_size, validation_data, epochs, name=\"model1\"):\n Max = 0\n for i in np.arange(0, epochs):\n\n history = model.fit(x, y, batch_size=batch_size, validation_data=validation_data,\n epochs=1, verbose=0)\n\n y_pred1 = model.predict(validation_data[0])\n y_pred = np.argmax(y_pred1, axis=1)\n\n y_test = np.argmax(validation_data[1], axis=1)\n tmp = f1_score(y_test, y_pred, average=\"macro\")\n if tmp > Max:\n Max = tmp\n model.save(name + \".h5\")\n print('f1 score: ' + str(tmp) + \", max: \" + str(Max))\n\n\ndef fit_generator_save(model, generator, steps_per_epoch, validation_data, epochs, name=\"model1\"):\n max_f1 = 0\n for epoch in np.arange(0, epochs):\n\n history = model.fit_generator(generator, steps_per_epoch=steps_per_epoch,\n epochs=1, verbose=0)\n\n y_prediction = np.argmax(model.predict(validation_data[0]), axis=1)\n y_labels = np.argmax(validation_data[1], axis=1)\n\n current_f1 = f1_score(y_labels, y_prediction, average=\"macro\")\n if current_f1 > max_f1:\n max_f1 = current_f1\n model.save(name + \".h5\")\n print('epoch: ', epoch, 'f1 score: ', current_f1, \"max: \", max_f1)\n\n\nclass KMaxPooling(Layer):\n \"\"\"\n K-max pooling layer that extracts the k-highest activations from a sequence (2nd dimension).\n TensorFlow backend.\n \"\"\"\n\n def __init__(self, k=1, **kwargs):\n super().__init__(**kwargs)\n self.input_spec = InputSpec(ndim=3)\n self.k = k\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], (input_shape[2] * self.k))\n\n def call(self, inputs):\n # swap last two dimensions since top_k will be applied along the last dimension\n shifted_input = tf.transpose(inputs, [0, 2, 1])\n\n # extract top_k, returns two tensors [values, indices]\n top_k = tf.nn.top_k(shifted_input, k=self.k, sorted=True, name=None)[0]\n\n # return flattened output\n return top_k\n\n\ndef build_model1(size):\n input_ecg = Input(shape=(size, 2))\n\n x = Lambda(lambda layer: layer[:, :, 0:1])(input_ecg)\n x1 = Lambda(lambda layer: layer[:, :, 1:2])(input_ecg)\n\n for i in range(5):\n x = Conv1D(32, 5, padding='same')(x)\n\n x = Concatenate(axis=2)([x, x1])\n x = KMaxPooling(k=100)(x)\n\n x = Flatten()(x)\n x = Dense(32, activation=\"relu\")(x)\n output = Dense(2, activation=\"sigmoid\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model2(size):\n input_ecg = Input(shape=(size, 2))\n\n x = Lambda(lambda layer: layer[:, :, 0:1])(input_ecg)\n x1 = Lambda(lambda layer: layer[:, :, 1:2])(input_ecg)\n\n for i in range(5):\n x = Conv1D(32, 5, dilation_rate=i + 1, padding='same')(x)\n\n x = Concatenate(axis=2)([x, x1])\n x = KMaxPooling(k=100)(x)\n\n x = Flatten()(x)\n x = Dense(32, activation=\"relu\")(x)\n output = Dense(2, activation=\"sigmoid\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model3(size):\n input_ecg = Input(shape=size)\n\n layers_leads = []\n for i in range(size[1]):\n tmp = Lambda(lambda layer: layer[:, :, i:i + 1])(input_ecg)\n tmp = Conv1D(20, 150, strides=75)(tmp)\n layers_leads.append(Reshape((-1, 20, 1))(tmp))\n\n x = Concatenate(axis=3)(layers_leads)\n\n resid = Conv2D(7, (3, 3), dilation_rate=1, padding='same')(x)\n for i in np.arange(1, 5):\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(resid)\n x = BatchNormalization()(x)\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(x)\n x = BatchNormalization()(x)\n resid = Concatenate(axis=3)([x, resid])\n\n x = Conv2D(35, (1, 1), dilation_rate=(1, 1))(resid)\n x = BatchNormalization()(x)\n x = AvgPool2D(pool_size=(2, 2))(x)\n\n x = Flatten()(x)\n output = Dense(2, activation=\"softmax\")(x)\n model = Model(input_ecg, output)\n\n return model\n\n\ndef build_model4(size):\n input_ecg = Input(shape=size)\n\n layers_leads = []\n for i in range(size[1]):\n tmp = Lambda(lambda layer: layer[:, :, i:i + 1])(input_ecg)\n tmp = Conv1D(20, 100, strides=50)(tmp)\n layers_leads.append(Reshape((-1, 20, 1))(tmp))\n\n x = Concatenate(axis=3)(layers_leads)\n\n resid = Conv2D(7, (3, 3), dilation_rate=1, padding='same')(x)\n for i in np.arange(1, 3):\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(resid)\n x = BatchNormalization()(x)\n x = Conv2D(7, (3, 3), dilation_rate=(i ** 2, i ** 2), padding='same', activation='relu')(x)\n x = BatchNormalization()(x)\n resid = Concatenate(axis=3)([x, resid])\n\n x = Conv2D(35, (1, 1), dilation_rate=(1, 1))(resid)\n x = BatchNormalization()(x)\n x = AvgPool2D(pool_size=(2, 2))(x)\n\n x = Flatten()(x)\n output = Dense(2, activation=\"softmax\")(x)\n model = Model(input_ecg, output)\n\n return model\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"251866733","text":"from collections import OrderedDict\npairs = [(\"a\", 1), ('b', 10), ('c', 50), ('d', 150)]\n\nod = OrderedDict()\nfor p in pairs:\n od[p[0]] = p[1]\n \n\nprint(od)\n# Перетаскивание в конец\nod.move_to_end('a', last=True)\nprint(od)\n\n# Удалим первый добавленный элемент\nod.popitem(last=False)\nprint(od)","sub_path":"day5/Lect18/order.py","file_name":"order.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"22258259","text":"from getopt import getopt\n\nargs = ['-q', '-b', '/tmp/log.txt', 'file1.txt', 'file2.txt']\noptions, extras = getopt(args, 'b:q')\nprint('options is', options)\nprint('extras is', extras)\n\n# Defaults.\nlogfile = None\nquiet = False\n\n# Override based on command-line options.\nfor (opt, arg) in options:\n if opt == '-b':\n logfile = arg\n elif opt == '-q':\n quiet = True\n else:\n assert False, 'unrecognized option {}'.format(opt)\nprint('Log file is {} and quiet is {}'.format(logfile, quiet))\n","sub_path":"src/configure/getopt_simple.py","file_name":"getopt_simple.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331175493","text":"import os\nimport datetime\nimport json\nimport bcrypt\n\nfrom functools import wraps\n\nfrom flask import Flask,Blueprint,render_template, request, jsonify,send_from_directory,redirect,make_response,url_for,flash\n\nfrom google.cloud import datastore\n\nevents = Blueprint('events', __name__)\n\nDS = datastore.Client()\nEVENT = 'Event'\nUSERSESS = 'Sess'\nSUCCESS = 0\n\nif os.getenv('GAE_ENV','').startswith('standard'):\n EVE = DS.key('Entities','event_root')\n USER = DS.key('Entities','user_root')\nelse:\n EVE = DS.key('Entities','event_dev')\n USER = DS.key('Entities','user_dev')\n\n# check login\ndef login_check(sess):\n\n print(sess)\n if sess == None or sess == '' or len(sess) == 0:\n print('please login')\n return redirect(url_for('auth.login'))\n \n query_key = DS.key(USERSESS,int(sess))\n query = list(DS.query(kind = USERSESS,ancestor = query_key).fetch())\n for i in query:\n print(i)\n if user != i['user'] or (datetime.datetime.now() - datetime.timedelta(hours=1)) > sess_db['exp'].replace(tzinfo = None):\n print('expired')\n return redirect(url_for('auth.logout'))\n \n return SUCCESS\n \n\ndef put_event(name,date_str):\n entity = datastore.Entity(key = DS.key(EVENT,parent=EVE ))\n entity.update({'name':name,'date':date_str})\n DS.put(entity)\n return\n\ndef delete_event(del_id):\n del_k = DS.key(EVENT, del_id,parent=EVE )\n DS.delete(del_k)\n return\n\ndef fetch_events(limit=None):\n if limit != None:\n query = DS.query(kind = EVENT )\n query.order = ['date']\n events = query.fetch(limit = limit)\n else:\n query = DS.query(kind = EVENT )\n query.order = ['date']\n events = query.fetch()\n return events\n\n@events.route('/')\n@events.route('/index')\ndef root():\n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n #return render_template(\"index.html\",user = 'back') \n return render_template('index.html')\n \n\n@events.route('/events',methods = ['GET'])\ndef getEvent():\n print('GET event')\n \n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n \n events = fetch_events()\n payload = []\n content = {}\n for e in events:\n content = {'id':e.id,'name':e['name'],'date':e['date']}\n payload.append(content)\n content = {}\n event_l = {'events':payload}\n print(json.dumps(event_l))\n data = json.dumps(event_l)\n return jsonify(data)\n\n@events.route('/event',methods = ['POST'])\ndef postEvent():\n print('POST event')\n \n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n\n name,date = request.json['name'], request.json['date']\n print(name,date)\n put_event(name,date)\n return ''\n\n@events.route('/event',methods = ['DELETE'])\ndef delEvent():\n print('DEL event')\n\n sess = request.cookies.get('sess')\n result = login_check(sess)\n if result != SUCCESS:\n return result\n \n del_id = request.json['id']\n delete_event(del_id)\n return getEvent()\n","sub_path":"lab2/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"397315374","text":"\"\"\"\nA command line interface to the qcfractal server.\n\"\"\"\n\nimport argparse\n\nimport qcfractal\n\nfrom . import cli_utils\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='A CLI for the QCFractalServer.')\n\n manager = parser.add_argument_group('QueueManager Settings (optional)')\n # This option defaults to None if option not present, -1 if present, or value if provided\n manager.add_argument(\n '--local-manager',\n const=-1,\n default=None,\n action='store',\n nargs='?',\n type=int,\n help='Creates a local pool QueueManager')\n\n server = parser.add_argument_group('QCFractalServer Settings')\n server.add_argument(\"name\", type=str, help=\"The name of the FractalServer and its associated database\")\n server.add_argument(\"--log-prefix\", type=str, default=None, help=\"The logfile prefix to use\")\n server.add_argument(\"--port\", type=int, default=7777, help=\"The server port\")\n server.add_argument(\n \"--security\", type=str, default=None, choices=[None, \"local\"], help=\"The security protocol to use\")\n server.add_argument(\"--database-uri\", type=str, default=\"mongodb://localhost\", help=\"The database URI to use\")\n server.add_argument(\"--tls-cert\", type=str, default=None, help=\"Certificate file for TLS (in PEM format)\")\n server.add_argument(\"--tls-key\", type=str, default=None, help=\"Private key file for TLS (in PEM format)\")\n server.add_argument(\"--config-file\", type=str, default=None, help=\"A configuration file to use\")\n server.add_argument(\"--heartbeat-frequency\", type=int, default=300, help=\"The manager heartbeat frequency.\")\n\n parser._action_groups.reverse()\n\n args = vars(parser.parse_args())\n if args[\"config_file\"] is not None:\n data = cli_utils.read_config_file(args[\"config_file\"])\n\n args = cli_utils.argparse_config_merge(parse, args, data)\n\n return args\n\n\ndef main(args=None):\n\n # Grab CLI args if not present\n if args is None:\n args = parse_args()\n\n # Handle SSL\n ssl_certs = sum(args[x] is not None for x in [\"tls_key\", \"tls_cert\"])\n if ssl_certs == 0:\n ssl_options = None\n elif ssl_certs == 2:\n ssl_options = {\"crt\": args[\"tls_cert\"], \"key\": args[\"tls_key\"]}\n else:\n raise KeyError(\"Both tls-cert and tls-key must be passed in.\")\n\n # Handle Adapters/QueueManagers\n exit_callbacks = []\n\n # Build an optional adapter\n if args[\"local_manager\"]:\n ncores = args[\"local_manager\"]\n if ncores == -1:\n ncores = None\n\n from concurrent.futures import ProcessPoolExecutor\n\n adapter = ProcessPoolExecutor(max_workers=ncores)\n\n else:\n adapter = None\n\n # Build the server itself\n server = qcfractal.FractalServer(\n port=args[\"port\"],\n security=args[\"security\"],\n ssl_options=ssl_options,\n storage_uri=args[\"database_uri\"],\n storage_project_name=args[\"name\"],\n logfile_prefix=args[\"log_prefix\"],\n heartbeat_frequency=args[\"heartbeat_frequency\"],\n queue_socket=adapter)\n\n # Add exit callbacks\n for cb in exit_callbacks:\n server.add_exit_callback(cb[0], *cb[1], **cb[2])\n\n # Register closing\n cli_utils.install_signal_handlers(server.loop, server.stop)\n\n # Blocks until keyboard interupt\n server.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"qcfractal/cli/qcfractal_server.py","file_name":"qcfractal_server.py","file_ext":"py","file_size_in_byte":3369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588516192","text":"from typing import List\nimport torch\nimport numpy as np\n\nfrom simple_einet.utils import SamplingContext, index_one_hot\nfrom simple_einet.layers import AbstractLayer\nfrom simple_einet.distributions import AbstractLeaf\n\n\nclass FactorizedLeaf(AbstractLayer):\n \"\"\"\n A 'meta'-leaf layer that combines multiple scopes of a base-leaf layer via naive factorization.\n\n Attributes:\n base_leaf: Base leaf layer that contains the actual leaf distribution.\n in_features: Number of input features/RVs.\n out_features: Number of output features/RVs. This determines the factorization group size (round(in_features / out_features))\n scopes: One-hot mapping from which in_features correspond to which out_features.\n\n \"\"\"\n\n def __init__(\n self,\n num_features: int,\n num_features_out: int,\n num_repetitions,\n base_leaf: AbstractLeaf,\n ):\n \"\"\"\n Args:\n in_features (int): Number of input features/RVs.\n out_features (int): Number of output features/RVs.\n num_repetitions (int): Number of repetitions.\n base_leaf (Leaf): Base leaf distribution object.\n \"\"\"\n\n super().__init__(num_features, num_repetitions=num_repetitions)\n\n self.base_leaf = base_leaf\n self.num_features_out = num_features_out\n\n # Size of the factorized groups of RVs\n cardinality = int(np.round(self.num_features / self.num_features_out))\n\n # Construct mapping of scopes from in_features -> out_features\n scopes = torch.zeros(num_features, self.num_features_out, num_repetitions)\n for r in range(num_repetitions):\n idxs = torch.randperm(n=self.num_features)\n for o in range(num_features_out):\n low = o * cardinality\n high = (o + 1) * cardinality\n if o == num_features_out - 1:\n high = self.num_features\n scopes[idxs[low:high], o, r] = 1\n\n self.register_buffer(\"scopes\", scopes)\n\n def forward(self, x: torch.Tensor, marginalized_scopes: List[int]):\n # Forward through base leaf\n x = self.base_leaf(x, marginalized_scopes)\n\n # Factorize input channels\n x = x.sum(dim=1)\n\n # Merge scopes by naive factorization\n x = torch.einsum(\"bicr,ior->bocr\", x, self.scopes)\n\n assert x.shape == (\n x.shape[0],\n self.num_features_out,\n self.base_leaf.num_leaves,\n self.num_repetitions,\n )\n return x\n\n def sample(self, num_samples: int = None, context: SamplingContext = None) -> torch.Tensor:\n # Save original indices_out and set context indices_out to none, such that the out_channel\n # are not filtered in the base_leaf sampling procedure\n indices_out = context.indices_out\n context.indices_out = None\n samples = self.base_leaf.sample(context=context)\n num_samples = samples.shape[0]\n\n # Check that shapes match as expected\n if samples.dim() == 4:\n assert samples.shape == (\n context.num_samples,\n self.base_leaf.num_channels,\n self.num_features,\n self.base_leaf.num_leaves,\n )\n elif samples.dim() == 5:\n assert self.num_features == samples.shape[1]\n assert hasattr(self.base_leaf, \"cardinality\")\n assert samples.shape == (\n context.num_samples,\n self.base_leaf.out_features,\n self.base_leaf.cardinality,\n self.base_leaf.num_leaves,\n )\n\n if not context.is_differentiable:\n scopes = self.scopes[..., context.indices_repetition].permute(2, 0, 1)\n rnge_in = torch.arange(self.num_features_out, device=samples.device)\n scopes = (scopes * rnge_in).sum(-1).long()\n indices_in_gather = indices_out.gather(dim=1, index=scopes)\n indices_in_gather = indices_in_gather.view(num_samples, 1, -1, 1)\n\n indices_in_gather = indices_in_gather.expand(-1, samples.shape[1], -1, -1)\n samples = samples.gather(dim=-1, index=indices_in_gather)\n samples.squeeze_(-1) # Remove num_leaves dimension\n else:\n # i_rep = context.indices_repetition.argmax(-1).long()\n # i_out = indices_out.argmax(-1).long()\n # scopes_orig = self.scopes[..., i_rep].permute(2, 0, 1)\n # rnge_in = torch.arange(self.num_features_out, device=samples.device)\n # scopes_orig = (scopes_orig * rnge_in).sum(-1).long()\n # indices_in_gather_orig = i_out.gather(dim=1, index=scopes_orig)\n # indices_in_gather_orig = indices_in_gather_orig.view(num_samples, 1, -1, 1)\n #\n # indices_in_gather_orig = indices_in_gather_orig.expand(-1, samples.shape[1], -1, -1)\n # samples_orig = samples.gather(dim=-1, index=indices_in_gather_orig)\n # samples_orig.squeeze_(-1) # Remove num_leaves dimension\n\n scopes = self.scopes.unsqueeze(0) # make space for batch dim\n r_idx = context.indices_repetition.view(context.num_samples, 1, 1, -1)\n scopes = index_one_hot(scopes, index=r_idx, dim=-1)\n\n indices_in = index_one_hot(indices_out.unsqueeze(1), index=scopes.unsqueeze(-1), dim=2)\n\n indices_in = indices_in.unsqueeze(1) # make space for channel dim\n samples = index_one_hot(samples, index=indices_in, dim=-1)\n\n # assert (samples - samples_orig).sum() < 1e-4\n\n return samples\n\n def extra_repr(self):\n return f\"num_features={self.num_features}, num_features_out={self.num_features_out}\"\n","sub_path":"simple_einet/factorized_leaf_layer.py","file_name":"factorized_leaf_layer.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434655305","text":"'''\n\nvalidate the PCA NN \n\n'''\nimport os, sys \nimport pickle\nimport numpy as np\n\nfrom speculator import SpectrumPCA\nfrom speculator import Speculator\n\nimport matplotlib as mpl \nmpl.use('Agg') \nimport matplotlib.pyplot as plt\n\n#-------------------------------------------------------\n# input \n#-------------------------------------------------------\n#model = 'nmfburst'\n#n_pcas = [30, 60, 30, 30, 30, 30] # number of PCA components \n#archs = ['16x256', '16x256', '16x256', '16x256', '16x256', '16x256'] # architectures\n\n#model = 'nmf_bases'\n#n_pcas = [50, 30, 30]\n#archs = ['8x256', '8x256', '8x256'] # architectures\n#n_pcas = [30, 30, 30, 30, 30, 30]\n#archs = ['10x256', '10x256', '10x256', '10x256', '10x256', '10x256'] # architectures\n\nmodel = 'burst'\nn_pcas = [50, 30, 30]\narchs = ['8x256', '8x256', '8x256'] # architectures\n\nnbatch = 500 \ndesc = 'nbatch250'\n#dat_dir = '/Users/chahah/data/provabgs/'\ndat_dir = '/tigress/chhahn/provabgs/'\n\n# read in wavelenght values \nwave = np.load(os.path.join(dat_dir, 'wave_fsps.npy'))\n\nn_wavebin = len(n_pcas)\nif n_wavebin == 6: \n wave_bins = [ \n (wave < 3000),\n (wave >= 3000) & (wave < 4000),\n (wave >= 4000) & (wave < 5000),\n (wave >= 5000) & (wave < 6000), \n (wave >= 6000) & (wave < 7000),\n (wave >= 7000)]\nelif n_wavebin == 3: \n wave_bins = [\n (wave < 4500), \n (wave >= 4500) & (wave < 6500),\n (wave >= 6500)]\n\n\n# plot loss \nlosses = [\n np.loadtxt(os.path.join(dat_dir,\n 'fsps.%s.seed0_%i.%iw%i.pca%i.%s.%s.loss.dat' % (model, nbatch-1, n_wavebin, i, n_pcas[i], archs[i], desc)))\n for i in range(len(wave_bins))\n ]\n\nfig = plt.figure(figsize=(10,5))\nsub = fig.add_subplot(111)\nfor i, loss in enumerate(losses): \n sub.plot(np.arange(loss.shape[0]), loss[:,2], label='wave bin %i' % i)\n\nsub.legend(loc='upper right')\nsub.set_ylabel('loss', fontsize=25)\nsub.set_yscale('log')\nsub.set_xlabel('Epochs', fontsize=25)\nsub.set_xlim(0, loss.shape[0])\nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.loss.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\n\n# read in test parameters and data\ntheta_test = np.load(os.path.join(dat_dir,\n 'fsps.%s.theta.test.npy' % model)).astype(np.float32)\n_lnspec_test = np.load(os.path.join(dat_dir, \n 'fsps.%s.lnspectrum.test.npy' % model))\n\nprint(theta_test.shape)\n\nlnspec_test = []\nfor wave_bin in wave_bins: \n lnspec_test.append(_lnspec_test[:,wave_bin])\nlnspec_test = np.concatenate(lnspec_test, axis=1) \n\n_wave = [] \nfor wave_bin in wave_bins: \n _wave.append(wave[wave_bin]) \n_wave = np.concatenate(_wave)\n\n# load speculator \nemus = [\n Speculator(\n restore=True, \n restore_filename=os.path.join(dat_dir, \n 'fsps.%s.seed0_%i.%iw%i.pca%i.%s.%s' % \n (model, nbatch-1, n_wavebin, i, n_pcas[i], archs[i], desc))\n )\n for i in range(len(wave_bins))\n ]\n\ndef emu_lnspec(theta):\n lnspec = [emus[i].log_spectrum(theta) for i in range(len(emus))]\n return np.concatenate(lnspec, axis=1)\n\n# reconstructed ln(spec) \nlnspec_recon = emu_lnspec(theta_test) \n\n# plot fractional error\nfig = plt.figure(figsize=(15,5))\n# calculate fraction error \nfrac_dspectrum = 1. - np.exp(lnspec_recon - lnspec_test) \nfrac_dspectrum_quantiles = np.nanquantile(frac_dspectrum, \n [0.0005, 0.005, 0.025, 0.16, 0.5, 0.84, 0.975, 0.995, 0.9995], axis=0)\n\nsub = fig.add_subplot(111)\nsub.fill_between(_wave, frac_dspectrum_quantiles[0], frac_dspectrum_quantiles[-1], \n fc='C0', ec='none', alpha=0.1, label='99.9%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[1], frac_dspectrum_quantiles[-2], \n fc='C0', ec='none', alpha=0.2, label='99%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[2], frac_dspectrum_quantiles[-3], \n fc='C0', ec='none', alpha=0.3, label='95%')\nsub.fill_between(_wave, frac_dspectrum_quantiles[3], frac_dspectrum_quantiles[-4],\n fc='C0', ec='none', alpha=0.5, label='68%')\nsub.plot(_wave, frac_dspectrum_quantiles[4], c='C0', ls='-') \nsub.plot(wave, np.zeros(len(wave)), c='k', ls=':') \n\n# mark +/- 1%\nsub.plot(wave, 0.01 * np.ones(len(wave)), c='k', ls='--', lw=0.5)\nsub.plot(wave, -0.01 * np.ones(len(wave)), c='k', ls='--', lw=0.5)\n\nsub.legend(loc='upper right', fontsize=20)\nsub.set_xlabel('wavelength ($A$)', fontsize=25) \nsub.set_xlim(2.3e3, 1e4) \nsub.set_ylabel(r'$(f_{\\rm emu} - f_{\\rm fsps})/f_{\\rm fsps}$', fontsize=25) \nsub.set_ylim(-0.1, 0.1) \nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\n\n# plot cumulative fractional error\nmean_frac_dspectrum = np.mean(np.abs(frac_dspectrum), axis=1)\nquant = np.quantile(mean_frac_dspectrum, [0.68, 0.95, 0.99, 0.999])\n\nfig = plt.figure(figsize=(8,6))\nsub = fig.add_subplot(111)\nfor q, a in zip(quant[::-1], [0.1, 0.2, 0.3, 0.5]):\n sub.fill_between([0., q], [0., 0.], [1., 1.], alpha=a, color='C0')\n_ = sub.hist(mean_frac_dspectrum, 40, range=(0., 0.05), density=True, histtype='step', cumulative=True, color='k')\nsub.set_xlabel(r'${\\rm mean}_\\lambda \\langle (f_{\\rm emu} - f_{\\rm fsps}) / f_{\\rm fsps} \\rangle$', fontsize=20)\nsub.set_xlim(0., 0.03)\nsub.set_ylabel('cumulative distribution', fontsize=20)\nsub.set_ylim(0., 1.)\nfig.savefig('fsps.%s.%s.%s.%s.valid_emu.cum.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n\noutlier = mean_frac_dspectrum > 0.1\nprint('%i with frac err > 0.1' % np.sum(outlier))\n# plot outliers \nfig = plt.figure(figsize=(15,5))\nsub = fig.add_subplot(111)\nfor i in range(np.sum(outlier)): \n sub.plot(_wave, np.exp(lnspec_test[outlier][i]))\n sub.plot(_wave, np.exp(lnspec_recon[outlier][i]), c='k', ls=':')\nsub.set_xlabel('wavelength ($A$)', fontsize=25) \nsub.set_xlim(2.3e3, 1e4) \nfig.savefig('fsps.%s.%s.%s.%s.outlier.png' % (model, '_'.join(str(nn) for nn in n_pcas), '.'.join(archs), desc), bbox_inches='tight') \n","sub_path":"bin/validate_emu.py","file_name":"validate_emu.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404079265","text":"import os, time\nimport nilearn\nfrom nilearn.regions import Parcellations\nimport re\n\n#%%\n\noutdir = '/home/klug/working_data/ed_transfer_rs/parcellations/parcellation_of_non_segmented'\nmain_path = '/home/klug/working_data/ed_transfer_rs/RS'\n\n# Subject directory pattern in main dir (ex: S01_RS2)\nsubject_dir_pattern = re.compile(\"^S[0-9][0-9]_RS[0-9]$\")\nsubject_sub_path = 'BOLD/realigned_Yeo/coreg/norm/'\n\nn_clusters = 200\n\ndataset = []\nfailed_subjects = []\n\n#%%\n\n\nsubject_dirs = [d for d in os.listdir(main_path)\n if os.path.isdir(os.path.join(main_path, d)) and subject_dir_pattern.match(d)]\nsubject_dirs.sort()\nsubject_dirs = [os.path.join(main_path, d) for d in subject_dirs]\n\n#%%\n\nfor subject_dir in subject_dirs:\n subject_sub_dir = os.path.join(subject_dir, subject_sub_path)\n if not os.path.exists(subject_sub_dir):\n failed_subjects.append(os.path.basename(subject_dir))\n continue\n subject_files = [os.path.join(subject_sub_dir, f) for f in os.listdir(subject_sub_dir) if os.path.isfile(os.path.join(subject_sub_dir, f))]\n subj_img_4d = nilearn.image.load_img(subject_files)\n # all subjects should have 480 time points\n assert subj_img_4d.shape[-1] == 480\n dataset.append(subj_img_4d)\n\n## Parcellation\n\n\n# Computing ward for the first time, will be long... This can be seen by\n# measuring using time\nstart = time.time()\n\n# Agglomerative Clustering: ward\n\n# We build parameters of our own for this object. Parameters related to\n# masking, caching and defining number of clusters and specific parcellations\n# method.\nward = Parcellations(method='ward', n_parcels=n_clusters,\n standardize=False, smoothing_fwhm=2.,\n memory='nilearn_cache', memory_level=1,\n verbose=1)\n# Call fit on functional dataset: single subject (less samples).\nward.fit(dataset)\nprint(\"Ward agglomeration 1000 clusters: %.2fs\" % (time.time() - start))\n\n#%%\n\nward_labels_img = ward.labels_img_\n\n# # Now, ward_labels_img are Nifti1Image object, it can be saved to file\n# # with the following code:\nward_labels_img.to_filename(os.path.join(outdir, f'ward_parcellation_k{n_clusters}.nii.gz'))\n","sub_path":"parcellation/ward_parcellation_wrapper.py","file_name":"ward_parcellation_wrapper.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"235219822","text":"from requests import get\nfrom data import db_session\nfrom data.users import User\nfrom data.activity import Activities\nfrom data.records import Timetable\nimport datetime\n\n# для того, чтобы скопировать всё базу в интернете\n\n\ndef pars_str_to_date(date_str): # переделывает строк в даты в дату\n days, time = date_str.split(' ')\n year, month, day = days.split('-')\n hours, minutes = time.split(':')\n\n date = datetime.datetime(int(year), int(month), int(day), int(hours),\n int(minutes), 0)\n return date\n\n\nway = 'https://vitamin-calculator.herokuapp.com/' # от куда брать\ndb_session.global_init(\"db/vitamin_calculator.sqlite\") # где хранить\nsession = db_session.create_session()\n\n\nall_db = get(f'{way}/api/db').json() # обращается к api и получает всю базу\n\nusers = all_db['db']['users']\ntimetables = all_db['db']['timetable']\nactivities = all_db['db']['activities']\n\nfor user in users:\n if not session.query(User).get(user['id']):\n user_db = User(\n surname=user['surname'],\n name=user['name'],\n age=user['age'],\n email=user['email'],\n hashed_password=user['hashed_password'],\n id=user['id'],\n modified_date=pars_str_to_date(user['modified_date']),\n is_varfarin=user['is_varfarin']\n )\n session.add(user_db)\n\nfor activity in activities:\n if not session.query(Activities).get(activity['id']):\n activity_db = Activities(\n date=pars_str_to_date(activity['date']),\n name=activity['name'],\n id_user=activity['id_user'],\n id=activity['id']\n )\n session.add(activity_db)\n\n\nfor timetable in timetables:\n if not session.query(Timetable).get(timetable['id']):\n timetable_db = Timetable(\n breakfast=timetable['breakfast'],\n dinner=timetable['dinner'],\n supper=timetable['supper'],\n master=timetable['master'],\n vitamin=timetable['vitamin'],\n id=timetable['id'],\n date=timetable['date'],\n is_varfarin=timetable['is_varfarin'],\n percent=timetable['percent'],\n ch_ch_date=timetable['ch_ch_date'],\n color=timetable['color'],\n summ=timetable['summ'],\n status=timetable['status'],\n all_products_varfarin=timetable['all_products_varfarin'],\n all_products=timetable['all_products']\n )\n session.add(timetable_db)\n\n\nsession.commit()\n","sub_path":"synchronization.py","file_name":"synchronization.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428362314","text":"#!/usr/bin/env python\n#coding: utf-8\n\nimport rospy\nfrom mavros_msgs.msg import GlobalPositionTarget, State\n\nfrom sensor_msgs.msg import NavSatFix\nfrom mavros_msgs.srv import CommandBool, CommandBoolRequest, CommandBoolResponse\nfrom mavros_msgs.srv import SetMode, SetModeRequest, SetModeResponse\nfrom geometry_msgs.msg import PoseStamped\nfrom std_msgs.msg import Bool\nimport math\nimport sys, select, os\n\n\n\n\nclass UAVCtl:\n def __init__(self):\n\n self.home_gps_pub = rospy.Publisher('/plane_home_gps',NavSatFix,queue_size=1)\n self.plane_local_pos_pub = rospy.Publisher('/mavros/setpoint_position/local', PoseStamped, queue_size=1)\n self.start_trace_pub = rospy.Publisher('/start_trace', Bool, queue_size=1)\n self.change_attitude_pub = rospy.Publisher('/change_to_attitude', Bool, queue_size=1)\n self.plane_target_pos = PoseStamped()\n self.plane_curr = PoseStamped()\n self.car_pos = PoseStamped()\n self.init_hover_mode = True\n self.change_attitude = Bool()\n self.follow_mode = Bool()\n self.start_trace_msg = Bool()\n self.fail_safe_mode = False\n self.car_distance_x = 0\n self.init_x = 0\n self.init_y = 0\n self.init_z = 3\n self.destination_x = 0\n self.destination_y = 0\n self.delta_x = 0\n self.delta_y = 0\n self.points_num_x = 0 # need how many points to reach pre-position\n self.points_num_y = 0 # need how many points to reach pre-position\n self.point_x = 0\n self.point_y = 0\n self.step_x = 0\n self.step_y = 0\n self.traj_points_count = 0 # increase count in while loop to pub trajectory points\n self.waypoints_num = 0\n self.waypoints_list_x = list()\n self.waypoints_list_y = list()\n self.plan_enable = True\n self.plan_num = 0\n\n \"\"\">>>>>>test in gazebo \"\"\"\n self.uav_state = State()\n self.arm_cmd = CommandBoolRequest()\n rospy.Subscriber('/mavros/state',State, self.state_cb)\n self.arming_client = rospy.ServiceProxy(\"/mavros/cmd/arming\", CommandBool)\n self.set_mode_client = rospy.ServiceProxy(\"/mavros/set_mode\", SetMode)\n self.offb_set_mode = SetModeRequest()\n \"\"\"<<<<<>>>>>test in gazebo, auto arm and take off\"\"\"\n\n\n \"\"\"pub local position for 100 counts\"\"\"\n local_pub_pos = PoseStamped()\n local_pub_pos.pose.position.x = self.init_x\n local_pub_pos.pose.position.y = self.init_y\n local_pub_pos.pose.position.z = self.init_z\n\n count = 0\n while not (rospy.is_shutdown() or count > 50):\n self.plane_local_pos_pub.publish(local_pub_pos)\n print(\"pub local position 50 \")\n rate.sleep()\n count += 1\n\n \"\"\"change Mode\"\"\"\n\n self.arm_cmd.value = True\n\n self.offb_set_mode.base_mode = 0\n self.offb_set_mode.custom_mode = \"OFFBOARD\"\n now = rospy.get_rostime()\n last_request = now.secs\n\n while not (rospy.is_shutdown()):\n self.plane_local_pos_pub.publish(local_pub_pos)\n if((self.uav_state.mode != \"OFFBOARD\") and (rospy.get_rostime().secs-last_request > 2)):\n rospy.loginfo(self.uav_state.mode)\n if((self.set_mode_client.call(self.offb_set_mode) == True) and (self.offb_set_mode.response.mode_sent == True)):\n rospy.loginfo(\" offboard enabled\")\n last_request = rospy.get_rostime().secs\n\n else:\n if((self.uav_state.armed == False) and (rospy.get_rostime().secs-last_request > 2)):\n rospy.loginfo(\" arming...\")\n if (self.arming_client.call(self.arm_cmd).success):\n rospy.loginfo(\" armed\")\n last_request = rospy.get_rostime().secs\n\n if abs(self.plane_curr.pose.position.z - self.init_z) < 0.1:\n rospy.loginfo(\"into hover mode\")\n break\n\n rate.sleep()\n\n \"\"\"<<<<< self.plane_curr.pose.position.x:\n forward_follow = 1\n else:\n forward_follow = -1\n\n self.destination_x = self.car_pos.pose.position.x - forward_follow * self.car_distance_x\n self.destination_y = self.car_pos.pose.position.y\n print(\"car_pos_x:\", self.car_pos.pose.position.x)\n print(\"car_pos_y:\", self.car_pos.pose.position.y)\n print(\"des_x:\", self.destination_x)\n print(\"des_y:\", self.destination_y)\n\n \"\"\" trace mode \"\"\"\n # the distance between curr_position and destination\n self.delta_x = self.destination_x - self.plane_curr.pose.position.x\n self.delta_y = self.destination_y - self.plane_curr.pose.position.y\n if abs(self.delta_x) > 0.5 or abs(self.delta_y) > 0.5:\n print(\"big error \")\n # plan every time, calculate every time\n self.calculate_waypoints(start_x=self.plane_curr.pose.position.x, start_y=self.plane_curr.pose.position.y,end_x=self.destination_x,end_y=self.destination_y)\n\n \"\"\"whether reached the trajectory point or not\"\"\"\n if abs(self.waypoints_list_x[self.traj_points_count] - self.plane_curr.pose.position.x) > 0.2 or abs(self.waypoints_list_y[self.traj_points_count] - self.plane_curr.pose.position.y) > 0.2:\n print(\"reaching the {} trajectory point\".format(self.traj_points_count))\n print(\"x_err between traj_point and curr: \", self.waypoints_list_x[self.traj_points_count] - self.plane_curr.pose.position.x)\n print(\"y_err between traj_point and curr: \", self.waypoints_list_y[self.traj_points_count] - self.plane_curr.pose.position.y)\n self.plane_target_pos.pose.position.x = self.waypoints_list_x[self.traj_points_count]\n self.plane_target_pos.pose.position.y = self.waypoints_list_y[self.traj_points_count]\n else:\n if self.traj_points_count < len(self.waypoints_list_x) - 1:\n self.traj_points_count += 1 # next point\n self.plane_target_pos.pose.position.x = self.waypoints_list_x[self.traj_points_count]\n self.plane_target_pos.pose.position.y = self.waypoints_list_y[self.traj_points_count]\n else:\n self.plane_target_pos.pose.position.x = self.destination_x\n self.plane_target_pos.pose.position.y = self.destination_y\n self.plane_target_pos.pose.position.x = self.destination_x\n self.plane_target_pos.pose.position.y = self.destination_y\n\n self.plane_target_pos.pose.position.z = self.init_z\n self.plane_local_pos_pub.publish(self.plane_target_pos)\n print(\"self.plane_target_pos.pose.position.x: \", self.plane_target_pos.pose.position.x)\n print(\"self.plane_target_pos.pose.position.y: \", self.plane_target_pos.pose.position.y)\n print(\"self.plane_target_pos.pose.position.z: \", self.plane_target_pos.pose.position.z)\n print(\"curr_x: \", self.plane_curr.pose.position.x)\n print(\"curr_y: \", self.plane_curr.pose.position.y)\n print(\"curr_z: \", self.plane_curr.pose.position.z)\n rate.sleep()\n\n\nif __name__ == '__main__':\n uav = UAVCtl()\n uav.ros_node()\n\n\n\n\n","sub_path":"upcore_back/gps_control/scripts/gps_pos_ctl_traj.py","file_name":"gps_pos_ctl_traj.py","file_ext":"py","file_size_in_byte":10488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"640792700","text":"#the guess\n\nnumGuesses = 0\nlow = 0\nhigh = 100\nans = (high + low)/2\nprint('Please think of a number between 0 and 100!')\n\nprint('Is your secret number ' + str(ans) + '?')\nx = raw_input('Enter ''h'' to indicate the guess is too high. Enter ''l'' to indicate the guess is too low. Enter ''c'' to indicate I guessed correctly.')\nnumGuesses += 1;\nwhile x != 'c':\n if x == 'h': high = ans\n elif x == 'l': low = ans\n else: \n print('Sorry, I did not understand your input.')\n ans = (high + low)/2\n print('Is your secret number ' + str(ans) + '?')\n numGuesses += 1;\n x = raw_input('Enter ''h'' to indicate the guess is too high. Enter ''l'' to indicate the guess is too low. Enter ''c'' to indicate I guessed correctly.')\n \nprint('Game over. Your secret number was: ' + str(ans))","sub_path":"guess.py","file_name":"guess.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241400835","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\n\r\n\r\nclass NeuronNetwork:\r\n def __init__(self, input_dim, output_dim, hide_layers, learn_rate=0.01, batch_size=64, iter_num=1000\r\n , act_func='sigmoid'):\r\n \"\"\"\r\n :param input_dim: int\r\n :param output_dim: int\r\n :param hide_layers: array like [20, 10],means two hide layers, dimension 20 and 10\r\n :param act_func: assign the activation function, sigmoid or relu\r\n :param learn_rate: float32\r\n :param batch_size: int\r\n :param iter_num: int\r\n \"\"\"\r\n self.dim_in = input_dim\r\n self.dim_out = output_dim\r\n self.w = []\r\n self.dw = []\r\n self.layer_out = []\r\n self.act_out = []\r\n self.layer_size = len(hide_layers)\r\n self.activation_func = act_func\r\n self.lr = learn_rate\r\n self.iter_num = iter_num\r\n self.batch_size = batch_size\r\n self.w_log = []\r\n self.loss_log = []\r\n self.weights_init(hide_layers)\r\n\r\n @staticmethod\r\n def sigmoid(z):\r\n return 1 / (1 + np.exp(-1 * z))\r\n\r\n def gra_sigmoid(self, z):\r\n fx = self.sigmoid(z)\r\n return fx * (1 - fx)\r\n\r\n @staticmethod\r\n def relu(z):\r\n return np.maximum(z, 0)\r\n\r\n @staticmethod\r\n def gra_relu(z):\r\n z[z <= 0] = 0\r\n z[z > 0] = 1\r\n return z\r\n\r\n def act_function(self, z):\r\n if self.activation_func == 'sigmoid':\r\n return self.sigmoid(z)\r\n elif self.activation_func == 'relu':\r\n return self.relu(z)\r\n else:\r\n raise ValueError('act_func should be \"sigmoid\" or \"relu\"')\r\n\r\n def grad_function(self, z):\r\n if self.activation_func == 'sigmoid':\r\n return self.gra_sigmoid(z)\r\n else:\r\n return self.gra_relu(z)\r\n\r\n def weights_init(self, hide_layers):\r\n if self.layer_size == 1:\r\n self.w.append(np.random.rand(self.dim_in, hide_layers[0]))\r\n self.dw.append(np.zeros((self.dim_in, hide_layers[0])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n\r\n self.w.append(np.random.rand(hide_layers[0], self.dim_out))\r\n self.dw.append(np.zeros((hide_layers[0], self.dim_out)))\r\n self.layer_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n self.act_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n elif self.layer_size == 2:\r\n self.w.append(np.random.rand(self.dim_in, hide_layers[0]))\r\n self.dw.append(np.zeros((self.dim_in, hide_layers[0])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[0])))\r\n\r\n self.w.append(np.random.rand(hide_layers[0], hide_layers[1]))\r\n self.dw.append(np.zeros((hide_layers[0], hide_layers[1])))\r\n self.layer_out.append(np.zeros((self.batch_size, hide_layers[1])))\r\n self.act_out.append(np.zeros((self.batch_size, hide_layers[1])))\r\n\r\n self.w.append(np.random.rand(hide_layers[1], self.dim_out))\r\n self.dw.append(np.zeros((hide_layers[1], self.dim_out)))\r\n self.layer_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n self.act_out.append(np.zeros((self.batch_size, self.dim_out)))\r\n else:\r\n raise ValueError('hide layer size should be: 1 or 2, but got %d' % self.layer_size)\r\n\r\n def calculate(self, x):\r\n \"\"\"\r\n :param x: shape of [batch_size, dim_in]\r\n :return: y_hat, shape of [batch_size, dim_out]\r\n \"\"\"\r\n if self.layer_size == 1:\r\n self.layer_out[0] = x.dot(self.w[0])\r\n self.act_out[0] = self.act_function(self.layer_out[0])\r\n\r\n self.layer_out[1] = self.act_out[0].dot(self.w[1])\r\n self.act_out[1] = self.act_function(self.layer_out[1])\r\n return self.act_out[-1]\r\n else:\r\n self.layer_out[0] = x.dot(self.w[0])\r\n self.act_out[0] = self.act_function(self.layer_out[0])\r\n\r\n self.layer_out[1] = self.act_out[0].dot(self.w[1])\r\n self.act_out[1] = self.act_function(self.layer_out[1])\r\n\r\n self.layer_out[2] = self.act_out[1].dot(self.w[2])\r\n self.act_out[2] = self.act_function(self.layer_out[2])\r\n return self.act_out[-1]\r\n\r\n @staticmethod\r\n def cal_loss(y_hat, y_label):\r\n \"\"\"\r\n :param y_hat: predictions of output, shape of [batch_size, dim_out]\r\n :param y_label: real label, shape of [batch_size, dim_out]\r\n :return: loss, float32\r\n \"\"\"\r\n loss = np.square(y_hat - y_label).sum()\r\n return loss\r\n\r\n def back_propagation(self, x, y_hat, y_label):\r\n \"\"\"\r\n :param x:\r\n :param y_hat: predictions of output, shape of [batch_size, dim_out]\r\n :param y_label: real label, shape of [batch_size, dim_out]\r\n :return: None\r\n \"\"\"\r\n grad_y_hat = 2.0 * (y_hat - y_label)\r\n if self.layer_size == 1:\r\n # calculate dw2\r\n grad_temp = grad_y_hat * self.grad_function(self.layer_out[1])\r\n self.dw[1] = self.act_out[0].T.dot(grad_temp)\r\n # calculate dw2\r\n grad_temp = grad_temp.dot(self.w[1].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[0])\r\n self.dw[0] = x.T.dot(grad_temp)\r\n # update w1 and w2\r\n self.w[0] -= self.lr * self.dw[0]\r\n self.w[1] -= self.lr * self.dw[1]\r\n else:\r\n # calculate dw3\r\n grad_temp = grad_y_hat * self.grad_function(self.layer_out[2])\r\n self.dw[2] = self.act_out[1].T.dot(grad_temp)\r\n # calculate dw2\r\n grad_temp = grad_temp.dot(self.w[2].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[1])\r\n self.dw[1] = self.act_out[0].T.dot(grad_temp)\r\n # calculate dw1\r\n grad_temp = grad_temp.dot(self.w[1].T)\r\n grad_temp = grad_temp * self.grad_function(self.layer_out[0])\r\n self.dw[0] = x.T.dot(grad_temp)\r\n # update w1 and w2 and w3\r\n self.w[0] -= self.lr * self.dw[0]\r\n self.w[1] -= self.lr * self.dw[1]\r\n self.w[2] -= self.lr * self.dw[2]\r\n\r\n def train(self, x_sets, y_sets):\r\n sample_count = len(x_sets)\r\n for i in range(self.iter_num):\r\n batch_index = np.random.choice(sample_count, self.batch_size)\r\n batch_x = x_sets[batch_index]\r\n batch_y = y_sets[batch_index]\r\n batch_y_hat = self.calculate(batch_x)\r\n self.back_propagation(batch_x, batch_y_hat, batch_y)\r\n if i % 50 == 0:\r\n batch_loss = self.cal_loss(batch_y_hat, batch_y)\r\n print('current loss: ',batch_loss)\r\n\r\n\r\nif __name__ == '__main__':\r\n # 生成随机数据集\r\n # np.random.seed(1)\r\n # x_set = np.random.rand(1000, 100)\r\n # y_set = np.random.randint(0, 9, size=1000)\r\n # y_set = np.eye(10)[y_set]\r\n\r\n x_samples = []\r\n y_samples = []\r\n with open('iris.txt') as f:\r\n data = f.readlines()\r\n for sample in data:\r\n try:\r\n x1, x2, x3, x4, label = sample.split(',')\r\n if 'setosa' in label:\r\n label = 0\r\n elif 'versicolor' in label:\r\n label = 1\r\n else:\r\n label = 2\r\n x_samples.append([x1, x2, x3, x4])\r\n y_samples.append(label)\r\n except ValueError:\r\n pass\r\n x_samples = np.array(x_samples, dtype=np.float64)\r\n y_samples = np.eye(3)[y_samples]\r\n\r\n nn = NeuronNetwork(4, 3, [12, 6])\r\n nn.train(x_samples, y_samples)\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"NeuronNetwork.py","file_name":"NeuronNetwork.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279542765","text":"import pandas as pd\nimport os\nimport sys\n\n\ndef main(save_to_file):\n location = os.getcwd() # get present working directory location here\n counter = 0 #keep a count of all files found\n\n #loop through all directories within /text\n for root_file in os.listdir(location+\"/text\"):\n #loop through all wiki dump files in /text subdirectory\n for file in os.listdir(location+\"/text/\"+root_file):\n try:\n #if file is found say so in command line and proceed to convert json data\n if file.startswith(\"wiki_\"):\n print(\"wiki dump file found:\\t\" + str(file))\n temp_json_file = \"text/\"+root_file+\"/\"+file\n converter(temp_json_file, save_to_file)\n counter = counter+1\n except Exception as e:\n raise e\n print(\"No files found here!\")\n print(\"Total files found and converted:\\t\" + str(counter))\n\n\ndef converter(json_file, save_to_file):\n #open file and append what we find\n f = open(save_to_file, \"a\")\n #get pandas dataframe\n pd_obj = pd.read_json(json_file, lines=True)\n #iterate through pandas dataframe\n for index, row in pd_obj.iterrows():\n #print(\"text:\\t:\" + str(row['text']))\n temp_row = row['text'].split('\\n')\n # after splitting by new line, iterate through all substrings\n for i in range(0,len(temp_row)):\n #if i==0 then we know we are reading the title so no checks need to be made\n if i == 0:\n f.write(str(temp_row[i])+\"\\n\")\n #everything else needs to be cleaned\n else:\n #split sentences on periods\n temp_texts = temp_row[i].split('.')\n #strings are cleaned and appended to file\n for text in temp_texts:\n if text == '':\n continue\n elif text[0] == '\\xa0' or text[0] == ' ':\n f.write(str(text[1:])+\".\\n\")\n else:\n f.write(str(text)+\".\\n\")\n print(\"Transfer completed\")\n\nif __name__ == '__main__':\n print(sys.argv[1][:-3]+\"txt\")\n save_to_file = sys.argv[1][:-3]+\"txt\"\n #if our save_to_file already exists want to delete and start with a blank document\n if os.path.isfile(save_to_file):\n os.remove(save_to_file)\n\n main(save_to_file)\n","sub_path":"python/wikiDump_convert.py","file_name":"wikiDump_convert.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"274692062","text":"\nimport sqlite3\nfrom flask import Flask, request, session, g, redirect, url_for, abort\nfrom flask import render_template, flash\nfrom contextlib import closing\nimport bokeh.plotting as p\nfrom model import Entry, User\nfrom database import db_session\n\nDATABASE = r'tmp\\flaskr.db'\nDEBUG = True\nSECRET_KEY = 'dev key'\nUSERNAME = 'admin'\nPASSWORD = 'default'\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n\ndef init_db():\n with closing(connect_db()) as db:\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n\n@app.teardown_request\ndef teardown_request(exception):\n try:\n g.db.close()\n except AttributeError:\n pass\n\n@app.teardown_appcontext\ndef shutdown_session(exception=None):\n db_session.remove()\n\n@app.route('/')\ndef show_entries():\n from bokeh import embed, plotting, resources\n entries = Entry.query.order_by('date').all()\n\n\n all_dia = [i.dia for i in entries]\n all_sys = [i.sys for i in entries]\n all_pulse = [i.pulse for i in entries]\n fig = plotting.figure(toolbar_location='right', width=520, height=350,\n logo=None, x_axis_type='datetime'\n )\n\n x = range(len(all_dia))\n x = [i.date for i in entries]\n fig.line(x, all_dia, color='red')\n fig.line(x, all_sys, color='blue')\n fig.line(x, all_pulse, color='black')\n script, div = embed.components(fig, resources.INLINE)\n return render_template('show_entries.html', entries=entries, script=script,\n div=div)\n\n\n\n@app.route('/add', methods=['POST'])\ndef add_entry():\n if not session.get('logged_in'):\n abort(401)\n form = request.form\n sys, dia, pulse = form['systolic'], form['diatolic'], form['pulse']\n when, side = form['time'], form['side']\n entry = Entry(sys, dia, pulse, side, when)\n db_session.add(entry)\n db_session.commit()\n flash(\"Succesful posted\")\n return redirect(url_for('show_entries'))\n\n\n@app.route('/delete/')\ndef delete_entry(entry_id):\n if not session.get('logged_in'):\n abort(401)\n to_del = Entry.query.get(entry_id)\n db_session.delete(to_del)\n db_session.commit()\n return redirect(url_for('show_entries'))\n\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != app.config['USERNAME']:\n error = 'invalid login'\n elif request.form['password'] != app.config['PASSWORD']:\n error = 'invalid password'\n else:\n session['logged_in'] = True\n flash('logged in!')\n return redirect(url_for('show_entries'))\n return render_template('login.html', error=error)\n\n\n@app.route('/logout')\ndef logout():\n session.pop('logged_in', None)\n flash('Logged out')\n return redirect(url_for('show_entries'))\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"flaskr.py","file_name":"flaskr.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286087042","text":"import logging\n\nfrom celery import task\nfrom django.utils.timezone import now\n\nlogger = logging.getLogger(__name__)\n\n\n@task(name='process_task', ignore_result=True)\ndef process_balanced_task(task_runner_id):\n \"\"\"\n Verifies that the `process_balanced_task.request.id` that was passed\n when this was created is still valid.\n\n Then runs the `run()` function on the `task_runner.balanced_task` and\n schedules another if needed.\n \"\"\"\n from models import TaskRunner\n task_runner = TaskRunner.objects.get(id=task_runner_id)\n\n if (task_runner.task_id != process_balanced_task.request.id\n or task_runner.is_deleted):\n raise Exception(\"No longer a valid task\")\n\n # The good part\n task_runner.balanced_task.run()\n task_runner.last_run = now()\n task_runner.save(force_update=True)\n\n # Pull in any new data from the DB\n task_runner = TaskRunner.objects.get(id=task_runner_id)\n eta = task_runner.next_run()\n\n logger.info('Processed TaskRunner: {bt}'\n ' id: {id} eta:{eta}'.format(\n bt=task_runner.name,\n id=task_runner.id,\n eta=eta))\n if eta:\n # Run the task again.\n task_runner.start()\n","sub_path":"billy/balanced_tasks/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"607737959","text":"import io\nimport uuid\nfrom typing import Iterator, List\n\nfrom memsource import api_rest, constants, models\nfrom memsource.lib import mxliff\n\n\nclass Bilingual(api_rest.BaseApi):\n # Document: https://cloud.memsource.com/web/docs/api#tag/Bilingual-File\n\n def _get_bilingual_stream(self, project_id: int, job_uids: List[str]) -> Iterator[bytes]:\n \"\"\"Common process of bilingualFile.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :return: Downloaded bilingual file with iterator.\n \"\"\"\n return self._post_stream(\n path=\"v1/projects/{}/jobs/bilingualFile\".format(project_id),\n data={\"jobs\": [{\"uid\": job_uid} for job_uid in job_uids]},\n ).iter_content(constants.CHUNK_SIZE)\n\n def get_bilingual_file_xml(self, project_id: int, job_uids: List[str]) -> bytes:\n \"\"\"Download bilingual file and return it as bytes.\n\n This method might use huge memory.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :return: Downloaded bilingual file.\n \"\"\"\n buffer = io.BytesIO()\n\n for chunk in self._get_bilingual_stream(project_id, job_uids):\n buffer.write(chunk)\n\n return buffer.getvalue()\n\n def get_bilingual_file(\n self,\n project_id: int,\n job_uids: List[int],\n dest_file_path: str\n ) -> None:\n \"\"\"Download bilingual file and save it as a file.\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :param dest_file_path: Save bilingual file to there.\n \"\"\"\n with open(dest_file_path, \"wb\") as f:\n for chunk in self._get_bilingual_stream(project_id, job_uids):\n f.write(chunk)\n\n def get_bilingual_as_mxliff_units(\n self,\n project_id: int,\n job_uids: List[str]\n ) -> models.MxliffUnit:\n \"\"\"Download bilingual file and parse it as [models.MxliffUnit]\n\n :param project_id: ID of the project.\n :param job_uids: List of job uids.\n :returns: MxliffUnit\n \"\"\"\n return mxliff.MxliffParser().parse(self.get_bilingual_file_xml(project_id, job_uids))\n\n def upload_bilingual_file_from_xml(self, xml: str) -> List[models.Job]:\n \"\"\"Call uploadBilingualFile API.\n\n :param xml: Upload this file.\n \"\"\"\n extra_headers = {\"Content-Type\": \"application/octet-stream\"}\n self.add_headers(extra_headers)\n\n self._put(\"v1/bilingualFiles\", None, {\n \"file\": (\"{}.mxliff\".format(uuid.uuid1().hex), xml),\n })\n","sub_path":"memsource/api_rest/bilingual.py","file_name":"bilingual.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473431271","text":"###########################\n# findClosestColor.py\n###########################\n\nimport math\n\n#\n# finds the closet color to a pixel from a list of colors\n#\n# returns: the index where the closest color is in list\n#\n# arrayColors: the array holding the average colors from imgs in order\n# pixelColor: the pixel from OG image that program is finding img for\n#\ndef findClosestColor(arrayColors, pixelColor):\n\n # variables used to find min difference and it's index\n minDif = 100000\n minDifIndex = -1\n\n # go through each color in arrayColors and see if it's closer to pixelColor\n # than a pixel before it\n for colorInd in range(len(arrayColors)):\n\n # get the difference in red, green, and blue of 2 pixels\n difRed = abs(arrayColors[colorInd][0] - pixelColor[0])\n difGreen = abs(arrayColors[colorInd][1] - pixelColor[1])\n difBlue = abs(arrayColors[colorInd][2] - pixelColor[2])\n\n # get the \"length\" of the difference vector\n num = difRed ** 2 + difGreen ** 2 + difBlue ** 2\n num = math.sqrt(num)\n\n # update variables if current pixel is smaller\n if num < minDif:\n minDif = num\n minDifIndex = colorInd\n\n return minDifIndex\n","sub_path":"findClosestColor.py","file_name":"findClosestColor.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560870878","text":"from kdtree import KDTree\nfrom sqlalchemy.sql.expression import and_\n\nclass GPSPosition:\n \"\"\"\n Represents a GPS coordinate\n \"\"\"\n \n def __init__(self, longtitude, latitude):\n self.longitude = float(longtitude)\n self.latitude = float(latitude)\n\ndef get_ads_email_filtered(email, longitude, latitude, total):\n from db import Ad\n ads = Ad.query.filter(Ad.contact_email == email).all()\n locations = []\n for ad in ads:\n locations += [ad.location]\n \n return location_sort((longitude, latitude), locations, total)\n\ndef get_ads_cat_filtered(cat_name, longitude, latitude, total):\n from db import Ad, Category\n cat_id = Category.match(cat_name).id\n ads = Ad.query.filter(Ad.category_id == cat_id).all()\n locations = []\n for ad in ads:\n locations += [ad.location]\n return location_sort((longitude, latitude), locations, total)\n\ndef get_ads(longitude, latitude, total):\n \"\"\"\n talks to the db, returns a list of _total_ ads that are near, sorted by proximity. \n \"\"\"\n from db import Location, Ad\n from util import exp\n \n locations = []\n exp_gen = exp()\n exp_no = exp_gen.next()\n \n while len(locations) < int(total) and exp_no < 360000000:\n #location filtered query\n location_conditions = and_(\n Location.latitude <= latitude + exp_no,\n Location.latitude >= latitude - exp_no,\n Location.longitude <= longitude + exp_no,\n Location.longitude >= longitude - exp_no,\n )\n locations = Location.query.filter(location_conditions).all()\n exp_no = exp_gen.next() \n \n return location_sort((longitude, latitude), locations, total)\n\ndef location_sort(point, locations, total):\n \"\"\"\n Given a point, and a list of Location objects, returns a list of Location, capped with a length of _total_, sorted by proximity.\n \"\"\"\n sorted_locations = []\n location_map = {}\n location_data = []\n for l in locations:\n k = (l.longitude, l.latitude)\n if not location_map.has_key(k):\n location_data += [k] \n location_map[k] = [l]\n else: location_map[k] += [l]\n \n location_data_sorted = proximity_filter(point, location_data, total)\n \n for k in location_data_sorted:\n while len(location_map[k]) > 0:\n sorted_locations += [location_map[k][0]]\n del location_map[k][0]\n \n return sorted_locations\n\ndef proximity_filter(point, data, total):\n \"\"\"\n given a point, and a data set of points, we return a list of points, capped with a length of _total_, sorted in proximity.\n \"\"\"\n tree = KDTree.construct_from_data(data)\n return tree.query(query_point=point, t=total)","sub_path":"src/util/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"170670153","text":"from django.contrib import admin\n#from django.contrib.auth.models import Group\nfrom .models import Sensors\n\n\nclass SnippetAdmin(admin.ModelAdmin):\n list_display = ('topic', 'value', 'pub_date')\n list_filter = ('topic', 'pub_date')\n\n\nadmin.site.register(Sensors, SnippetAdmin)\n# admin.site.unregister(Group)\nadmin.site.site_header = 'iot sensor dashboard'\nadmin.site.index_title = 'sam mirkazemi'\nadmin.site.site_title = 'salam :))'\n\nadmin.site.disable_action('delete_selected')\n","sub_path":"dashboard/mqtt/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"592492610","text":"import cv2\nimport numpy as np\n\ndef canyEdgeDetector(image):\n return cv2.Canny(image, 50, 150)\n\n\ndef getROI(image):\n height = image.shape[0]\n width = image.shape[1]\n # Defining Triangular ROI: The values will change as per your camera mounts\n triangle = np.array([[(100, height), (width, height), (width-500, int(height/1.9))]])\n # creating black image same as that of input image\n black_image = np.zeros_like(image)\n # Put the Triangular shape on top of our Black image to create a mask\n mask = cv2.fillPoly(black_image, triangle, 255)\n return cv2.bitwise_and(image, mask)\n\n\n\ndef getLines(image):\n return cv2.HoughLinesP(\n image,\n 0.3,\n np.pi / 180,\n 100,\n np.array([]),\n minLineLength=70,\n maxLineGap=20,\n )\n\n\n#display lines over a image\ndef displayLines(image, lines):\n if lines is not None:\n for line in lines:\n # print(line) --output like [[704 418 927 641]] this is 2d array representing [[x1,y1,x2,y2]] for each line\n x1, y1, x2, y2 = line.reshape(4) # converting to 1d array []\n\n # draw line over black image --(255,0,0) tells we want to draw blue line (b,g,r) values 10 is line thickness\n cv2.line(image, (x1, y1), (x2, y2), (255, 0, 0), 10)\n return image\n\n\n\ndef getLineCoordinatesFromParameters(image, line_parameters):\n slope = line_parameters[0]\n intercept = line_parameters[1]\n y1 = image.shape[0] # since line will always start from bottom of image\n y2 = int(y1 * (3.4 / 5)) # some random point at 3/5\n x1 = int((y1 - intercept) / slope)\n x2 = int((y2 - intercept) / slope)\n return np.array([x1, y1, x2, y2])\n\n\n\n#Avergaes all the left and right lines found for a lane and retuns single left and right line for the the lane\ndef getSmoothLines(image, lines):\n left_fit = [] # will hold m,c parameters for left side lines\n right_fit = [] # will hold m,c parameters for right side lines\n\n for line in lines:\n x1, y1, x2, y2 = line.reshape(4)\n # polyfit gives slope(m) and intercept(c) values from input points\n # last parameter 1 is for linear..so it will give linear parameters m,c\n parameters = np.polyfit((x1, x2), (y1, y2), 1)\n slope = parameters[0]\n intercept = parameters[1]\n\n if slope < 0:\n left_fit.append((slope, intercept))\n else:\n right_fit.append((slope, intercept))\n\n # take averages of all intercepts and slopes separately and get 1 single value for slope,intercept\n # axis=0 means vertically...see its always (row,column)...so row is always 0 position.\n # so axis 0 means over row(vertically)\n left_fit_average = np.average(left_fit, axis=0)\n right_fit_average = np.average(right_fit, axis=0)\n\n # now we have got m,c parameters for left and right line, we need to know x1,y1 x2,y2 parameters\n left_line = getLineCoordinatesFromParameters(image, left_fit_average)\n right_line = getLineCoordinatesFromParameters(image, right_fit_average)\n return np.array([left_line, right_line])\n\n\n\n\n\n\nimage = cv2.imread(\"3.jpg\") #Load Image\n\nedged_image = canyEdgeDetector(image) # Step 1\nroi_image = getROI(edged_image) # Step 2\n\nlines = getLines(roi_image) # Step 3\n#image_with_lines = displayLines(image, lines)\n\nsmooth_lines = getSmoothLines(image, lines) # Step 5\nimage_with_smooth_lines = displayLines(image, smooth_lines) # Step 4\n\ncv2.imshow(\"Output\", image_with_smooth_lines)\ncv2.waitKey(0)","sub_path":"lane-detection-self-driving/laneDetector_images.py","file_name":"laneDetector_images.py","file_ext":"py","file_size_in_byte":3513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515821840","text":"#%%\nimport numpy as np\nfrom numpy.lib.twodim_base import triu_indices_from\nimport pandas as pd\nimport os\nimport pickle\nimport re\nfrom sklearn.utils import validation\nfrom tqdm import tqdm\nimport ast\nfrom sklearn.model_selection import train_test_split\n\nimport random\n#%%\n# load metadata\nmetadata = pd.read_excel(r\"C://Users//Jean-Baptiste//OneDrive//ENSAE//2A//CHU//Prediction_soustype//data//Recueil patients Blastes LAB annoté.xlsx\")\ndata_patient = pd.read_csv(r\"C://Users//Jean-Baptiste//OneDrive//ENSAE//2A//CHU//Prediction_soustype//data//data_patient.csv\")\n#%%\n# load list of patients with folders that can be used (between diagnostic and remission) & list of images\nim_path = r\"C:/Users/Jean-Baptiste/OneDrive/ENSAE/2A/CHU/Prediction_soustype/data\"\nim_test_path = r\"C:/Users/Jean-Baptiste/OneDrive/ENSAE/2A/CHU/Prediction_soustype/data_test\"\n\ndef num_pat(x):\n a=str(x)\n while len(a)<4:\n a = '0'+a\n return(a)\ndef date_sup(date_1, date_2):\n #dit si date1 est post à date2\n if date_1[-2:]>date_2[-2:]:\n return(True)\n if date_1[-2:]date_2[2:-2]:\n return(True)\n if date_1[2:-2]date_2[:2]:\n return(True)\n if date_1[:2]0}\n#%%\n\nfor k,v in images_metadata.items():\n if v['PATIENT_TYPE'] == 'LAL B2':\n new_image = v['IMAGES'][:len(v['IMAGES'])//2]\n v['IMAGES'] = new_image\n\n#%%\n#dict with all images name path and type\n# grouped_images_metadata = {curgroup:[v for k,v in images_metadata.items() if v['PATIENT_TYPE']==curgroup] for curgroup in ('LAL B1','LAL B2','LAL B3')}\ngrouped_images_metadata = {}\nfor curgroup in ('LAL B1','LAL B2','LAL B3'):\n grouped_images_metadata_curgroup = []\n for k,el in images_metadata.items():\n if el['PATIENT_TYPE'] == curgroup:\n for path_image in list(el['IMAGES']):\n name_image = os.path.basename(path_image)\n grouped_images_metadata_curgroup.append([name_image,path_image, curgroup])\n grouped_images_metadata[curgroup] = grouped_images_metadata_curgroup\n#%%\np=0\nfor k,v in images_metadata.items():\n if v['PATIENT_TYPE'] == 'LAL B2':\n p+=len(v['IMAGES'])\nprint(p)\n#%%\npart_rng = np.random.RandomState(seed=45)\n\n# part each group\nfor curgroup in ('LAL B1','LAL B2','LAL B3'):\n samples_is = np.arange(len(grouped_images_metadata[curgroup]))\n train_part = part_rng.choice(a = samples_is, size = len(samples_is)//2, replace = False)\n valid_part = part_rng.choice(a = np.setdiff1d(samples_is, train_part), size = (len(samples_is)-train_part.shape[0])//2, replace = False)\n test_part = np.setdiff1d(np.setdiff1d(samples_is, train_part), valid_part)\n for i in train_part:\n grouped_images_metadata[curgroup][i].append('train')\n for i in valid_part:\n grouped_images_metadata[curgroup][i].append('valid')\n for i in test_part:\n grouped_images_metadata[curgroup][i].append('test')\n\n\n\n\n#%%\np=0\nfor k,v in grouped_images_metadata.items():\n for el in v:\n if el[2]== 'LAL B2':\n p+=1\nprint(p)\n#%%\n#number of images per LAL type\n# LAL B1 : 0\n# LAL B2 : 12124\n# LAL B3 : 1204\n\n\n#%%\n# merge back\nall_metadata = [data for curgroup,elem in grouped_images_metadata.items() for data in elem ]\n\n# debug_df = pd.DataFrame(all_metadata)\n# debug_df.groupby(['GROUP','PART']).sum()\n#%%\n\n# debug_df.groupby(['NAME','PART']).sum()\n\n# create output\n\n\nmeta = dict(train=[],valid=[],test=[])\n\nfor metadata in all_metadata:\n tmp_sublist = [dict(FILE=metadata[0],PATH=metadata[1],GROUP=metadata[2])]\n meta[metadata[3]].extend(tmp_sublist)\n#%%\n\nfor curpart in ('train','valid','test'):\n with open(os.path.join(im_path,\"part_{}.pkl\".format(curpart)), 'wb') as file_pi:\n pickle.dump(meta[curpart], file_pi)\n \nfrom PIL import Image\n \n# get max size of image\nmax_w=0\nmax_h=0\nfor curpart in ('train','valid','test'):\n for meta_elem in tqdm(meta[curpart]):\n cur_w,cur_h=Image.open(os.path.join(im_path,meta_elem['PATH'])).size\n max_w=max(max_w,cur_w)\n max_h=max(max_h,cur_h)\nprint('Max dimensions are: {} x {}'.format(max_w,max_h)) # 263 x 299 # let's choose 320 (10*2^5)\n\n\n# %%\n#debug\nfor k in ('train', 'test', 'valid'):\n for j in ('LAL B1','LAL B2','LAL B3'):\n a=0\n for el in meta[k]:\n if el['GROUP']==j:\n a+=1\n print(j,k,a)\n \n# LAL B1 train 0\n# LAL B2 train 3027\n# LAL B3 train 300\n# LAL B1 test 0\n# LAL B2 test 1514\n# LAL B3 test 151\n# LAL B1 valid 0\n# LAL B2 valid 1514\n# LAL B3 valid 150\n","sub_path":"py/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276632770","text":"from enum import Enum\n\n\nclass AuditAction(Enum):\n \"\"\"\n This Enum class represents Audit Action type.\n \"\"\"\n CANCEL = \"Cancel\"\n START = \"Start\"\n SUBMIT = \"Submit\"\n\n\nclass GetAuditOptionsResponse(object):\n\n def __init__(self,\n release_id=None,\n audit_processing=None,\n can_audit=None,\n can_challenge=None,\n can_edit=None,\n in_audit_mode=None,\n ):\n\n self.release_id = release_id\n self.audit_processing = audit_processing\n self.can_audit = can_audit\n self.can_challenge = can_challenge\n self.can_edit = can_edit\n self.in_audit_mode = in_audit_mode\n\n def to_dict(self):\n return dict(releaseId=self.release_id,\n auditProcessing=self.audit_processing,\n canAudit=self.can_audit,\n canChallenge=self.can_challenge,\n canEdit=self.can_edit,\n inAuditMode=self.in_audit_mode,\n )\n\n @classmethod\n def from_dict(cls, dct):\n return cls(release_id=dct.get(\"releaseId\"),\n audit_processing=dct.get(\"auditProcessing\"),\n can_audit=dct.get(\"canAudit\"),\n can_challenge=dct.get(\"canChallenge\"),\n can_edit=dct.get(\"canEdit\"),\n in_audit_mode=dct.get(\"inAuditMode\"),\n )\n\n\nclass PostAuditActionRequest(object):\n\n def __init__(self, audit_action=None):\n self.audit_action = audit_action\n\n def to_dict(self):\n return dict(auditAction=self.audit_action.value)\n\n @classmethod\n def from_dict(cls, dct):\n return cls(audit_action=AuditAction(dct.get(\"auditAction\")) if dct.get(\"auditAction\") else None) # noqa\n","sub_path":"hpfortify/model/audit.py","file_name":"audit.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294471502","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 5 01:59:34 2019\n\n@author: jones\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n'Importing the datasets'\ndf1 = pd.read_csv('student-mat.csv')\ndf2 = pd.read_csv('student-por.csv')\ndf3 = pd.concat([df1, df2])\ndf3.head()\n\n\n'Data preprocessing and Exploratory analysis'\ndf3.drop_duplicates([\"school\",\"sex\",\"age\",\"address\",\"famsize\",\"Pstatus\",\"Medu\",\n \"Fedu\",\"Mjob\",\"Fjob\",\"reason\",\"nursery\",\"internet\"])\ndf3.columns\ndf3.describe()\n\ndf3.corr()\n\ndf3.info()\n\n'Drop the columns which is not essentials for grade prediction'\ndf3 = df3.drop(['famsize', 'Pstatus', 'Fjob', 'Mjob'], axis=1)\ndf3 = df3.drop(['reason','traveltime', 'studytime', 'failures'], axis=1)\ndf3 = df3.drop(['schoolsup','famsup', 'paid', 'nursery', 'internet', 'freetime'], axis=1)\ndf3 = df3.drop(['higher', 'health'], axis=1)\ndf3.columns\n\n'Visualizing the plots of the data according to the gender'\nplt.pie(df3['sex'].value_counts().to_list(), \n labels=['Female','Male'], colors=['crimson', 'slateblue'],\n autopct='%1.1f%%', startangle=90)\naxis = plt.axis('equal')\n\n'Visualizing the plots of the data according to the guardians nominal'\nplt.pie(df3['guardian'].value_counts().to_list(),\n labels=['mother', 'father', 'other'],\n colors=['darkslateblue', 'mediumorchid', 'steelblue'],\n autopct='%.2f', startangle=90)\nplt.axis('equal')\n\n\n'Given the high correlation between different grades, drop G1 & G2'\ndf3 = df3.drop(['G1', 'G2'], axis=1)\n\n'combine weekdays alcohol consumption with weekend alcohol consumption'\ndf3['Dalc'] = df3['Dalc'] + df3['Walc']\n\n'combine mothers education with fathers education & call it parents education'\ndf3['Pedu'] = df3['Medu'] + df3['Fedu']\n\n'combine goout and absences'\ndf3['goout'] = df3['goout'] + df3['absences']\ndf3 = df3.drop(['Walc','Medu','Fedu','absences'], axis=1)\ndf3.columns\n\n'Getting dummies'\ndf3 = pd.get_dummies(df3, drop_first=True)\ndf3.info()\n\n\n'define target variable and training and test sets'\nX = df3.drop(\"G3\",axis=1)\nY = df3[\"G3\"]\n\n\n'Splitting the dataset into the Training set and Test set'\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\n\n\n'Fitting Multiple Linear Regression to the Training set'\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n' Predicting the Test set results'\ny_pred = regressor.predict(X_test)\n\n'Building Optimal Model using Backward Elimination'\nimport statsmodels.formula.api as sm\nX_opt = X\nregressor_OLS = sm.OLS(endog =Y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n'''\nBackward Eliminiation Process\nDrop the variable which is not significant(p>0.05)\n'''\nX_opt = X.drop(['goout','activities_yes', 'address_U', 'school_MS', 'sex_M', 'guardian_mother'], axis=1)\nregressor_OLS = sm.OLS(endog =Y, exog = X_opt).fit()\nregressor_OLS.summary()\n\n\n","sub_path":"analysis/student_alcohol_consumption.py","file_name":"student_alcohol_consumption.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330907040","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/panel/taurusform.py\n# Compiled at: 2019-08-19 15:09:30\n\"\"\"This module contains taurus Qt form widgets\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport click\nfrom datetime import datetime\nfrom functools import partial\nfrom future.utils import string_types, binary_type\nfrom taurus.external.qt import Qt\nimport taurus.core\nfrom taurus.core import TaurusDevState, DisplayLevel\nfrom taurus.qt.qtcore.mimetypes import TAURUS_ATTR_MIME_TYPE, TAURUS_DEV_MIME_TYPE, TAURUS_MODEL_LIST_MIME_TYPE, TAURUS_MODEL_MIME_TYPE\nfrom taurus.qt.qtgui.container import TaurusWidget, TaurusScrollArea\nfrom taurus.qt.qtgui.button import QButtonBox, TaurusCommandButton\nfrom .taurusmodelchooser import TaurusModelChooser\n__all__ = [\n 'TaurusAttrForm', 'TaurusCommandsForm', 'TaurusForm']\n__docformat__ = 'restructuredtext'\n\ndef _normalize_model_name_case(modelname):\n \"\"\"\n Accepts a model name and returns it in lower case if the models is\n case insensitive. Otherwise it returns the same model name\n \"\"\"\n if taurus.Factory(taurus.getSchemeFromName(modelname)).caseSensitive:\n return modelname\n else:\n return modelname.lower()\n\n\nclass ParameterCB(Qt.QComboBox):\n \"\"\"A custom combobox\"\"\"\n\n def __init__(self, parent=None):\n Qt.QComboBox.__init__(self, parent)\n self.setEditable(True)\n\n def rememberCurrentText(self):\n \"\"\"Adds the current text to the combobox items list (unless it is already there)\"\"\"\n text = self.currentText()\n if self.findText(text) < 0:\n self.addItem(text)\n\n\nclass TaurusForm(TaurusWidget):\n \"\"\"A form containing specific widgets for interacting with\n a given list of taurus attributes and/or devices.\n\n Its model is a list of attribute and/or device names to be shown. Each item\n is represented in a row consisting of a label, a read widget, a write\n widget, a units widget and an \"extra\" widget (some of them may not be shown)\n which are vertically aligned with their counterparts from other items.\n\n By default a :class:`TaurusValue` object is used for each item, but this\n can be changed and specific mappings can be defined using the\n :meth:`setCustomWidgetMap` method.\n\n Item objects can be accessed by index using a list-like notation::\n\n form = TaurusForm()\n form.model = ['sys/tg_test/1'+a for a in ('short_image','/float_scalar','/double_scalar')]\n form[0].labelConfig = 'dev_alias'\n form[-1].writeWidgetClass = 'TaurusWheelEdit'\n print(len(form)) # --> outputs '3' (the length of the form is the number of items)\n\n By default, the form provides global Apply and Cancel buttons.\n\n You can also see some code that exemplifies the use of TaurusForm in :ref:`Taurus\n coding examples ` \"\"\"\n\n def __init__(self, parent=None, formWidget=None, buttons=None, withButtons=True, designMode=False):\n self._children = []\n TaurusWidget.__init__(self, parent, designMode)\n if buttons is None:\n buttons = Qt.QDialogButtonBox.Apply | Qt.QDialogButtonBox.Reset\n self._customWidgetMap = {}\n self._model = []\n self.setFormWidget(formWidget)\n self.setLayout(Qt.QVBoxLayout())\n frame = TaurusWidget()\n frame.setLayout(Qt.QGridLayout())\n self.scrollArea = TaurusScrollArea(self)\n self.scrollArea.setWidget(frame)\n self.scrollArea.setWidgetResizable(True)\n self.layout().addWidget(self.scrollArea)\n self.__modelChooserDlg = None\n self.buttonBox = QButtonBox(buttons=buttons, parent=self)\n self.layout().addWidget(self.buttonBox)\n self._connectButtons()\n self.setContextMenuPolicy(Qt.Qt.ActionsContextMenu)\n self.chooseModelsAction = Qt.QAction('Modify Contents', self)\n self.addAction(self.chooseModelsAction)\n self.chooseModelsAction.triggered.connect(self.chooseModels)\n self.showButtonsAction = Qt.QAction('Show Buttons', self)\n self.showButtonsAction.setCheckable(True)\n self.addAction(self.showButtonsAction)\n self.showButtonsAction.triggered[bool].connect(self.setWithButtons)\n self.setWithButtons(withButtons)\n self.changeLabelsAction = Qt.QAction('Change labels (all items)', self)\n self.addAction(self.changeLabelsAction)\n self.changeLabelsAction.triggered.connect(self.onChangeLabelsAction)\n self.compactModeAction = Qt.QAction('Compact mode (all items)', self)\n self.compactModeAction.setCheckable(True)\n self.addAction(self.compactModeAction)\n self.compactModeAction.triggered[bool].connect(self.setCompact)\n self.setFormatterAction = Qt.QAction('Set formatter (all items)', self)\n self.addAction(self.setFormatterAction)\n self.setFormatterAction.triggered.connect(self.onSetFormatter)\n self.resetModifiableByUser()\n self.setSupportedMimeTypes([TAURUS_MODEL_LIST_MIME_TYPE, TAURUS_DEV_MIME_TYPE,\n TAURUS_ATTR_MIME_TYPE, TAURUS_MODEL_MIME_TYPE, 'text/plain'])\n self.resetCompact()\n self.registerConfigProperty(self.isWithButtons, self.setWithButtons, 'withButtons')\n self.registerConfigProperty(self.isCompact, self.setCompact, 'compact')\n return\n\n def __getitem__(self, key):\n \"\"\"provides a list-like interface: items of the form can be accessed using slice notation\"\"\"\n return self.getItemByIndex(key)\n\n def __len__(self):\n \"\"\"returns the number of items contained by the form\"\"\"\n return len(self.getItems())\n\n def _splitModel(self, modelNames):\n \"\"\"convert str to list if needed (commas and whitespace are considered as separators)\"\"\"\n if isinstance(modelNames, binary_type):\n modelNames = modelNames.decode()\n if isinstance(modelNames, string_types):\n modelNames = str(modelNames).replace(',', ' ')\n modelNames = modelNames.split()\n return modelNames\n\n def setCustomWidgetMap(self, cwmap):\n \"\"\"Sets a map map for custom widgets.\n\n :param cwmap: (dict) a dictionary whose keys are device\n type strings (i.e. see :class:`PyTango.DeviceInfo`) and\n whose values are tuples of classname,args,kwargs\n \"\"\"\n self._customWidgetMap = cwmap\n\n def getCustomWidgetMap(self):\n \"\"\"Returns the map used to create custom widgets.\n\n :return: (dict) a dictionary whose keys are device\n type strings (i.e. see :class:`PyTango.DeviceInfo`) and whose\n values are tuples of classname,args,kwargs\n \"\"\"\n return self._customWidgetMap\n\n @Qt.pyqtSlot('QString', name='modelChanged')\n def parentModelChanged(self, parentmodel_name):\n self.info(\"Parent model changed to '%s'\" % parentmodel_name)\n parentmodel_name = str(parentmodel_name)\n if self.getUseParentModel():\n for obj, model in zip(self.getItems(), self.getModel()):\n obj.setModel('%s/%s' % (parentmodel_name, str(model)))\n\n else:\n self.debug('received event from parent although not using parent model')\n\n def chooseModels(self):\n \"\"\"launches a model chooser dialog to modify the contents of the form\"\"\"\n if self.__modelChooserDlg is None:\n self.__modelChooserDlg = Qt.QDialog(self)\n self.__modelChooserDlg.setWindowTitle('%s - Model Chooser' % str(self.windowTitle()))\n self.__modelChooserDlg.modelChooser = TaurusModelChooser()\n layout = Qt.QVBoxLayout()\n layout.addWidget(self.__modelChooserDlg.modelChooser)\n self.__modelChooserDlg.setLayout(layout)\n self.__modelChooserDlg.modelChooser.updateModels.connect(self.setModel)\n models_and_labels = []\n indexdict = {}\n for m in self.getModel():\n key = _normalize_model_name_case(m)\n indexdict[key] = indexdict.get(key, -1) + 1\n item = self.getItemByModel(m, indexdict[key])\n if item is None:\n label = None\n else:\n try:\n label = str(item.labelWidget().text())\n except:\n label = None\n\n models_and_labels.append((m, label))\n\n self.__modelChooserDlg.modelChooser.setListedModels(models_and_labels)\n self.__modelChooserDlg.show()\n self.__modelChooserDlg.raise_()\n return\n\n def chooseAttrs(self):\n self.info('TaurusForm.chooseAttrs() ahs been deprecated. Use TaurusForm.chooseModels() instead')\n self.chooseModels()\n\n def sizeHint(self):\n return Qt.QWidget.sizeHint(self)\n\n def _connectButtons(self):\n self.buttonBox.applyClicked.connect(self.apply)\n self.buttonBox.resetClicked.connect(self.reset)\n\n def getModel(self):\n return self._model\n\n @Qt.pyqtSlot('QStringList')\n def addModels(self, modelNames):\n \"\"\"Adds models to the existing ones:\n\n :param modelNames: (sequence) the names of the models to be added\n\n .. seealso:: :meth:`removeModels`\n \"\"\"\n modelNames = self._splitModel(modelNames)\n self.setModel(self.getModel() + modelNames)\n\n @Qt.pyqtSlot('QStringList')\n def removeModels(self, modelNames):\n \"\"\"Removes models from those already in the form.\n\n :param modelNames: (sequence) the names of the models to be removed\n\n .. seealso:: :meth:`addModels`\n \"\"\"\n modelNames = self._splitModel(modelNames)\n currentModels = self.getModel()\n for name in modelNames:\n try:\n currentModels.remove(name)\n except:\n self.warning(\"'%s' not in model list\" % name)\n\n self.setModel(currentModels)\n\n def setModelCheck(self, model, check=True):\n if model is None:\n model = []\n model = [ str(m or '') for m in self._splitModel(model) ]\n self.destroyChildren()\n self._model = model\n self.fillWithChildren()\n if self.__modelChooserDlg is not None:\n self.__modelChooserDlg.modelChooser.setListedModels(self._model)\n return\n\n def resetModel(self):\n self.destroyChildren()\n self._model = []\n\n def getFormWidget(self, model=None):\n \"\"\"Returns a tuple that can be used for creating a widget for a given model.\n\n :param model: (str) a taurus model name for which the new item of the\n form will be created\n\n :return: (tuple) a tuple containing a class, a list of\n args and a dict of keyword args. The args and the keyword args\n can be passed to the class constructor\n \"\"\"\n if model is None:\n return (self._defaultFormWidget, (), {})\n else:\n try:\n obj = taurus.Attribute(model)\n return (self._defaultFormWidget, (), {})\n except:\n try:\n obj = taurus.Device(model)\n except:\n self.warning('Cannot handle model \"%s\". Using default widget.' % model)\n return (self._defaultFormWidget, (), {})\n\n try:\n key = obj.getDeviceProxy().info().dev_class\n except:\n return (\n self._defaultFormWidget, (), {})\n\n cwmap = self.getCustomWidgetMap()\n value = cwmap.get(key, self._defaultFormWidget)\n if isinstance(value, type):\n if issubclass(value, self._defaultFormWidget):\n return (value, (), {})\n else:\n return (\n self._defaultFormWidget, (), {'customWidgetMap': {key: value}})\n\n name, args, kwargs = value\n pkgname, klassname = name.rsplit('.', 1)\n try:\n pkg = __import__(pkgname, fromlist=[klassname])\n klass = getattr(pkg, klassname)\n except:\n self.warning('Cannot import \"%s\". Using default widget for \"%s\".' % (name, model))\n return (self._defaultFormWidget, (), {})\n\n if not issubclass(klass, self._defaultFormWidget):\n cwmap = kwargs.get('customWidgetMap', {})\n cwmap.update({key: klass})\n kwargs['customWidgetMap'] = cwmap\n klass = self._defaultFormWidget\n return (\n klass, args, kwargs)\n\n return\n\n def setFormWidget(self, formWidget):\n if formWidget is None:\n from taurus.qt.qtgui.panel import TaurusValue\n self._defaultFormWidget = TaurusValue\n elif issubclass(formWidget, Qt.QWidget):\n self._defaultFormWidget = formWidget\n else:\n raise TypeError('formWidget must be one of None, QWidget. %s passed' % repr(type(formWidget)))\n return\n\n def resetFormWidget(self):\n self.setFormWidget(self, None)\n return\n\n def isWithButtons(self):\n return self._withButtons\n\n def setWithButtons(self, trueFalse):\n self._withButtons = trueFalse\n self.buttonBox.setVisible(self._withButtons)\n self.showButtonsAction.setChecked(self._withButtons)\n\n def resetWithButtons(self):\n self.setWithButtons(True)\n\n def onSetFormatter(self):\n \"\"\"Reimplemented from TaurusBaseWidget\"\"\"\n format = TaurusWidget.onSetFormatter(self)\n if format is not None:\n for item in self.getItems():\n rw = item.readWidget(followCompact=True)\n if hasattr(rw, 'setFormat'):\n rw.setFormat(format)\n\n return format\n\n def setFormat(self, format):\n \"\"\"\n Reimplemented to call setFormat on the taurusvalues\n \"\"\"\n TaurusWidget.setFormat(self, format)\n for item in self.getItems():\n if hasattr(item, 'setFormat'):\n item.setFormat(format)\n\n def setCompact(self, compact):\n self._compact = compact\n for item in self.getItems():\n item.setCompact(compact)\n\n self.compactModeAction.setChecked(compact)\n\n def isCompact(self):\n return self._compact\n\n def resetCompact(self):\n from taurus import tauruscustomsettings\n self.setCompact(getattr(tauruscustomsettings, 'T_FORM_COMPACT', {}))\n\n def dropEvent(self, event):\n \"\"\"reimplemented to support dropping of modelnames in forms\"\"\"\n mtype = self.handleMimeData(event.mimeData(), self.addModels)\n if mtype is None:\n self.info('Invalid model in dropped data')\n else:\n event.acceptProposedAction()\n return\n\n def setModifiableByUser(self, modifiable):\n \"\"\"\n sets whether the user can change the contents of the form\n (e.g., via Modify Contents in the context menu)\n Reimplemented from :meth:`TaurusWidget.setModifiableByUser`\n\n :param modifiable: (bool)\n\n .. seealso:: :meth:`TaurusWidget.setModifiableByUser`\n \"\"\"\n TaurusWidget.setModifiableByUser(self, modifiable)\n self.chooseModelsAction.setEnabled(modifiable)\n self.showButtonsAction.setEnabled(modifiable)\n self.changeLabelsAction.setEnabled(modifiable)\n self.compactModeAction.setEnabled(modifiable)\n for item in self.getItems():\n try:\n item.setModifiableByUser(modifiable)\n except:\n pass\n\n def setRegExp(self, regExp):\n pass\n\n def getRegExp(self):\n pass\n\n def destroyChildren(self):\n for child in self._children:\n self.unregisterConfigurableItem(child)\n child.setModel(None)\n child.deleteLater()\n\n self._children = []\n return\n\n def fillWithChildren(self):\n frame = TaurusWidget()\n frame.setLayout(Qt.QGridLayout())\n frame.layout().addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum, Qt.QSizePolicy.MinimumExpanding))\n parent_name = None\n if self.getUseParentModel():\n parent_model = self.getParentModelObj()\n if parent_model:\n parent_name = parent_model.getFullName()\n for i, model in enumerate(self.getModel()):\n if not model:\n continue\n if parent_name:\n model = '%s/%s' % (parent_name, model)\n klass, args, kwargs = self.getFormWidget(model=model)\n widget = klass(frame, *args, **kwargs)\n widget.setMinimumHeight(20)\n try:\n widget.setCompact(self.isCompact())\n widget.setModel(model)\n widget.setParent(frame)\n except:\n self.warning('an error occurred while adding the child \"%s\". Skipping' % model)\n self.traceback(level=taurus.Debug)\n\n try:\n widget.setModifiableByUser(self.isModifiableByUser())\n except:\n pass\n\n try:\n widget.setFormat(self.getFormat())\n except Exception:\n self.debug('Cannot set format %s to child %s', self.getFormat(), model)\n\n widget.setObjectName('__item%i' % i)\n self.registerConfigDelegate(widget)\n self._children.append(widget)\n\n frame.layout().addItem(Qt.QSpacerItem(0, 0, Qt.QSizePolicy.Minimum, Qt.QSizePolicy.MinimumExpanding))\n self.scrollArea.setWidget(frame)\n self.scrollArea.setMinimumWidth(frame.layout().sizeHint().width() + 20)\n return\n\n def getItemByModel(self, model, index=0):\n \"\"\"returns the child item with given model. If there is more than one item\n with the same model, the index parameter can be used to distinguish among them\n Please note that his index is only relative to same-model items!\"\"\"\n for child in self._children:\n if _normalize_model_name_case(child.getModel()) == _normalize_model_name_case(model):\n if index <= 0:\n return child\n index -= 1\n\n def getItemByIndex(self, index):\n \"\"\"returns the child item with at the given index position. \"\"\"\n return self.getItems()[index]\n\n def getItems(self):\n \"\"\"returns a list of the objects that have been created as childs of the form\"\"\"\n return self._children\n\n def onChangeLabelsAction(self):\n \"\"\"changes the labelConfig of all its items\"\"\"\n keys = [\n '{attr.label}', '{attr.name}', '{attr.fullname}', '{dev.name}',\n '{dev.fullname}']\n msg = 'Choose the label format. \\n' + 'You may use Python format() syntax. The TaurusDevice object\\n' + 'can be referenced as \"dev\" and the TaurusAttribute object\\n' + 'as \"attr\"'\n labelConfig, ok = Qt.QInputDialog.getItem(self, 'Change Label', msg, keys, 0, True)\n if ok:\n for item in self.getItems():\n item.labelConfig = str(labelConfig)\n\n @Qt.pyqtSlot()\n def apply(self):\n self.safeApplyOperations()\n\n @Qt.pyqtSlot()\n def reset(self):\n self.resetPendingOperations()\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n model = Qt.pyqtProperty('QStringList', getModel, TaurusWidget.setModel, resetModel)\n useParentModel = Qt.pyqtProperty('bool', TaurusWidget.getUseParentModel, TaurusWidget.setUseParentModel, TaurusWidget.resetUseParentModel)\n withButtons = Qt.pyqtProperty('bool', isWithButtons, setWithButtons, resetWithButtons)\n modifiableByUser = Qt.pyqtProperty('bool', TaurusWidget.isModifiableByUser, setModifiableByUser, TaurusWidget.resetModifiableByUser)\n compact = Qt.pyqtProperty('bool', isCompact, setCompact, resetCompact)\n\n\nclass TaurusCommandsForm(TaurusWidget):\n \"\"\"A form that shows commands available for a Device Server\"\"\"\n\n def __init__(self, parent=None, designMode=False):\n TaurusWidget.__init__(self, parent, designMode)\n self.setLayout(Qt.QVBoxLayout())\n self._splitter = Qt.QSplitter()\n self._splitter.setOrientation(Qt.Qt.Vertical)\n self.layout().addWidget(self._splitter)\n self._frame = TaurusWidget(self)\n self._frame.setLayout(Qt.QGridLayout())\n self._scrollArea = TaurusScrollArea(self)\n self._scrollArea.setWidget(self._frame)\n self._scrollArea.setWidgetResizable(True)\n self._splitter.addWidget(self._scrollArea)\n self._outputTE = Qt.QTextEdit()\n self._outputTE.setReadOnly(True)\n self._splitter.addWidget(self._outputTE)\n self._cmdWidgets = []\n self._paramWidgets = []\n self._viewFilters = []\n self._defaultParameters = []\n self._sortKey = lambda x: x.cmd_name\n self._operatorViewFilter = lambda x: x.disp_level == DisplayLevel.OPERATOR\n self.modelChanged.connect(self._updateCommandWidgets)\n\n def createConfig(self, allowUnpickable=False):\n \"\"\"\n extending :meth:`TaurusBaseWidget.createConfig`\n :param alllowUnpickable: (bool)\n\n :return: (dict) configurations (which can be loaded with :meth:`applyConfig`).\n\n .. seealso: :meth:`TaurusBaseWidget.createConfig`, :meth:`applyConfig`\n \"\"\"\n configdict = TaurusWidget.createConfig(self, allowUnpickable=allowUnpickable)\n configdict['splitter/state'] = self._splitter.saveState().data()\n return configdict\n\n def applyConfig(self, configdict, **kwargs):\n \"\"\"extending :meth:`TaurusBaseWidget.applyConfig` to restore the splitter config\n\n :param configdict: (dict)\n\n .. seealso:: :meth:`TaurusBaseWidget.applyConfig`, :meth:`createConfig`\n \"\"\"\n TaurusWidget.applyConfig(self, configdict, **kwargs)\n self._splitter.restoreState(Qt.QByteArray(configdict['splitter/state']))\n\n def getModelClass(self):\n \"\"\"see :meth:`TaurusBaseComponent.getModelClass`\"\"\"\n return taurus.core.taurusdevice.TaurusDevice\n\n def _updateCommandWidgets(self, *args):\n \"\"\"\n Inserts command buttons and parameter widgets in the layout, according to\n the commands from the model\n \"\"\"\n dev = self.getModelObj()\n if dev is None:\n self._clearFrame()\n return\n else:\n try:\n commands = sorted(dev.command_list_query(), key=self._sortKey)\n except Exception as e:\n self.warning('Problem querying commands from %s. Reason: %s', dev, e)\n self._clearFrame()\n return\n\n for f in self.getViewFilters():\n commands = list(filter(f, commands))\n\n self._clearFrame()\n layout = self._frame.layout()\n model = self.getFullModelName()\n for row, c in enumerate(commands):\n self.debug('Adding button for command %s' % c.cmd_name)\n button = TaurusCommandButton(command=c.cmd_name, text=c.cmd_name)\n layout.addWidget(button, row, 0)\n button.setModel(model)\n self._cmdWidgets.append(button)\n button.commandExecuted.connect(self._onCommandExecuted)\n import taurus.core.tango.util.tango_taurus as tango_taurus\n in_type = tango_taurus.FROM_TANGO_TO_TAURUS_TYPE[c.in_type]\n if in_type is not None:\n self.debug('Adding arguments for command %s' % c.cmd_name)\n pwidget = ParameterCB()\n if c.cmd_name.lower() in self._defaultParameters:\n for par in self._defaultParameters.get(c.cmd_name.lower(), []):\n pwidget.addItem(par)\n\n if (self._defaultParameters[c.cmd_name.lower()] or [''])[0] == '':\n pwidget.setEditable(True)\n else:\n pwidget.setEditable(False)\n button.setParameters(self._defaultParameters[c.cmd_name.lower()][0])\n pwidget.editTextChanged.connect(button.setParameters)\n pwidget.currentIndexChanged['QString'].connect(button.setParameters)\n pwidget.activated.connect(button.setFocus)\n button.commandExecuted.connect(pwidget.rememberCurrentText)\n layout.addWidget(pwidget, row, 1)\n self._paramWidgets.append(pwidget)\n\n return\n\n def _clearFrame(self):\n \"\"\"destroys all widgets in the scroll area frame\"\"\"\n self._frame = TaurusWidget(self)\n self._frame.setLayout(Qt.QGridLayout())\n self._frame.setModel(self.getModelName())\n self._scrollArea.setWidget(self._frame)\n self._cmdWidgets = []\n self._paramWidgets = []\n\n def _onCommandExecuted(self, result):\n \"\"\"Slot called when the command is executed, to manage the output\n\n :param result: return value from the command. The type depends on the command\n \"\"\"\n timestamp = datetime.now()\n cmdbutton = self.sender()\n output = '%s
      ' % timestamp.strftime('%Y-%m-%d %H:%M:%S') + 'Command: %s
      ' % cmdbutton.getCommand() + 'Pars: %s
      ' % repr(cmdbutton.getParameters()) + 'Return Value:
      %s' % str(result)\n self._outputTE.append(output)\n separator = '

      '\n self._outputTE.append(separator)\n\n def setSortKey(self, sortkey):\n \"\"\"sets the method used to sort the commands (cmd_name by default)\n\n :param sortkey: (callable) a function that takes a :class:`CommandInfo`\n as argument and returns a key to use for sorting purposes\n (e.g. the default sortKey is ``lambda x:x.cmd_name``)\n \"\"\"\n self._sortKey = sortkey\n self._updateCommandWidgets()\n\n def setDefaultParameters(self, params):\n \"\"\"sets the values that will appear by default in the parameters combo box,\n the command combo box for the command will be editable only if the first parameter is an empty string\n\n :param params: (dict) { 'cmd_name': ['parameters string 1', 'parameters string 2' ] }\n\n \"\"\"\n self._defaultParameters = dict((k.lower(), v) for k, v in params.items())\n self._updateCommandWidgets()\n\n def setViewFilters(self, filterlist):\n \"\"\"sets the filters to be applied when displaying the commands\n\n :param filterlist: (sequence) a sequence of command filters.\n All filters will be applied to each command to decide\n whether to display it or not.\n for a command to be plotted, the following condition\n must be true for all filters:\n bool(filter(command))==True\n \"\"\"\n self._viewFilters = filterlist\n self._updateCommandWidgets()\n\n def getViewFilters(self):\n \"\"\"returns the filters used in deciding which commands are displayed\n\n :return: (sequence) a sequence of filters\n \"\"\"\n return self._viewFilters\n\n @Qt.pyqtSlot(bool, name='setCommand')\n def setExpertView(self, expert):\n \"\"\"sets the expert view mode\n\n :param expert: (bool) If expert is True, commands won't be filtered. If\n it is False, commands with display level Expert won't be shown\n \"\"\"\n currentfilters = self.getViewFilters()\n if expert:\n if self._operatorViewFilter in currentfilters:\n currentfilters.remove(self._operatorViewFilter)\n elif self._operatorViewFilter not in currentfilters:\n currentfilters.insert(0, self._operatorViewFilter)\n self.setViewFilters(currentfilters)\n self._expertView = expert\n\n def getSplitter(self):\n \"\"\"returns the splitter that separates the command buttons area from\n the output area\n\n :return: (QSplitter)\"\"\"\n return self._splitter\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n\nclass TaurusAttrForm(TaurusWidget):\n \"\"\"A form that displays the attributes of a Device Server\"\"\"\n\n def __init__(self, parent=None, designMode=False):\n TaurusWidget.__init__(self, parent, designMode)\n self._viewFilters = []\n self._operatorViewFilter = lambda x: x.disp_level == DisplayLevel.OPERATOR\n self.setLayout(Qt.QVBoxLayout())\n self._form = TaurusForm(parent=self)\n self.layout().addWidget(self._form)\n self.registerConfigDelegate(self._form)\n self.modelChanged.connect(self._updateAttrWidgets)\n self._sortKey = lambda x: x.name\n\n def setSortKey(self, sortkey):\n \"\"\"sets the key function used to sort the attributes in the form\n\n :param sortkey: (callable) a function that takes a :class:`AttributeInfo`\n as argument and returns a key to use for sorting purposes\n (e.g. the default sortKey is ``lambda x:x.name``)\n\n \"\"\"\n self._sortKey = sortkey\n self._updateAttrWidgets()\n\n def getModelClass(self):\n \"\"\"see :meth:`TaurusBaseComponent.getModelClass`\"\"\"\n return taurus.core.taurusdevice.TaurusDevice\n\n def _updateAttrWidgets(self):\n \"\"\"Populates the form with an item for each of the attributes shown\n \"\"\"\n try:\n dev = self.getModelObj()\n attrlist = sorted(dev.attribute_list_query(), key=self._sortKey)\n for f in self.getViewFilters():\n attrlist = list(filter(f, attrlist))\n\n attrnames = []\n devname = self.getModelName()\n for a in attrlist:\n attrnames.append('%s/%s' % (devname, a.name))\n\n self.debug('Filling with attribute list: %s' % ('; ').join(attrnames))\n self._form.setModel(attrnames)\n except:\n self.debug('Cannot connect to device')\n self._form.setModel([])\n\n def setViewFilters(self, filterlist):\n \"\"\"sets the filters to be applied when displaying the attributes\n\n :param filterlist: (sequence) a sequence of attr filters. All\n filters will be applied to each attribute name to\n decide whether to display it or not. for an attribute\n to be plotted, the following condition must be true\n for all filters: ``bool(filter(attrname))==True``\n \"\"\"\n self._viewFilters = filterlist\n self._updateAttrWidgets()\n\n def getViewFilters(self):\n \"\"\"returns the filters used in deciding which attributes are displayed\n\n :return: (sequence) a sequence of filters\n \"\"\"\n return self._viewFilters\n\n @Qt.pyqtSlot(bool)\n def setExpertView(self, expert):\n \"\"\"sets the expert view mode\n\n :param expert: (bool) If expert is True, attributes won't be filtered. If\n it is False, attributes with display level Expert won't\n be shown\n \"\"\"\n currentfilters = self.getViewFilters()\n if expert:\n if self._operatorViewFilter in currentfilters:\n currentfilters.remove(self._operatorViewFilter)\n elif self._operatorViewFilter not in currentfilters:\n currentfilters.insert(0, self._operatorViewFilter)\n self.setViewFilters(currentfilters)\n self._expertView = expert\n\n @classmethod\n def getQtDesignerPluginInfo(cls):\n ret = TaurusWidget.getQtDesignerPluginInfo()\n ret['module'] = 'taurus.qt.qtgui.panel'\n ret['container'] = False\n return ret\n\n model = Qt.pyqtProperty('QString', TaurusWidget.getModel, TaurusWidget.setModel, TaurusWidget.resetModel)\n useParentModel = Qt.pyqtProperty('bool', TaurusWidget.getUseParentModel, TaurusWidget.setUseParentModel, TaurusWidget.resetUseParentModel)\n\n\ndef test1():\n \"\"\"tests taurusForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n models = sys.argv[1:]\n else:\n models = None\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n if models is None:\n models = [\n 'sys/tg_test/1/state',\n 'sys/tg_test/1/float_scalar',\n 'sys/tg_test/1/boolean_image',\n 'sys/tg_test/1/float_spectrum',\n 'sys/tg_test/1/status']\n dialog = TaurusForm()\n dialog.setModel(models)\n dialog.setModifiableByUser(True)\n for i, tv in enumerate(dialog.getItems()):\n tv.setDangerMessage('Booooo scaring %d!!!' % i)\n\n dialog.show()\n dialog2 = TaurusForm()\n dialog2.show()\n dialog2.setModifiableByUser(True)\n sys.exit(app.exec_())\n return\n\n\ndef test2():\n \"\"\"tests taurusAttrForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n model = sys.argv[1]\n else:\n model = None\n if model is None:\n model = 'bl97/pc/dummy-01'\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n dialog = TaurusAttrForm()\n dialog.setModel(model)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef test3():\n \"\"\"tests taurusCommandsForm\"\"\"\n import sys\n if len(sys.argv) > 1:\n model = sys.argv[1]\n else:\n model = None\n if model is None:\n model = 'bl97/pc/dummy-01'\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n dialog = TaurusCommandsForm()\n dialog.setModel(model)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef test4():\n \"\"\"tests customwidgetma in taurusforms\"\"\"\n import sys\n from taurus.qt.qtgui.display import TaurusLabel\n from taurus.qt.qtgui.application import TaurusApplication\n app = TaurusApplication(sys.argv, cmd_line_parser=None)\n from taurus.qt.qtgui.panel import TaurusValue\n\n class DummyCW(TaurusValue):\n\n def setModel(self, model):\n print('!!!!! IN DUMMYCW.SETMODEL', model)\n TaurusValue.setModel(self, model + '/double_scalar')\n\n models = [\n 'sys/database/2', 'sys/tg_test/1', 'sys/tg_test/1/short_spectrum',\n 'sys/tg_test/1/state', 'sys/tg_test/1/short_scalar_ro']\n models.append('tango://controls02:10000/expchan/bl97_simucotictrl_1/1')\n map = {'PseudoCounter': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'CTExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'ZeroDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'OneDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'TwoDExpChannel': (\n 'taurus.qt.qtgui.extra_pool.PoolChannelTV', (), {}), \n 'TangoTest': DummyCW, \n 'DataBase': TaurusLabel}\n dialog = TaurusForm()\n dialog.setCustomWidgetMap(map)\n dialog.setModel(models)\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\n@click.command('form')\n@click.option('--window-name', 'window_name', default='Taurus Form', help='Name of the window')\n@click.option('--config', 'config_file', type=click.File('rb'), help='configuration file for initialization')\n@click.argument('models', nargs=-1)\ndef form_cmd(window_name, config_file, models):\n \"\"\"Shows a Taurus form populated with the given model names\"\"\"\n from taurus.qt.qtgui.application import TaurusApplication\n import sys\n app = TaurusApplication(cmd_line_parser=None)\n dialog = TaurusForm()\n dialog.setModifiableByUser(True)\n dialog.setModelInConfig(True)\n dialog.setWindowTitle(window_name)\n dialog.registerConfigProperty(dialog.saveGeometry, dialog.restoreGeometry, 'MainWindowGeometry')\n quitApplicationAction = Qt.QAction(Qt.QIcon.fromTheme('process-stop'), 'Close Form', dialog)\n quitApplicationAction.triggered.connect(dialog.close)\n saveConfigAction = Qt.QAction('Save current settings...', dialog)\n saveConfigAction.setShortcut(Qt.QKeySequence.Save)\n saveConfigAction.triggered.connect(partial(dialog.saveConfigFile, ofile=None))\n loadConfigAction = Qt.QAction('&Retrieve saved settings...', dialog)\n loadConfigAction.setShortcut(Qt.QKeySequence.Open)\n loadConfigAction.triggered.connect(partial(dialog.loadConfigFile, ifile=None))\n dialog.addActions((\n saveConfigAction, loadConfigAction, quitApplicationAction))\n from taurus import tauruscustomsettings\n dialog.setCustomWidgetMap(getattr(tauruscustomsettings, 'T_FORM_CUSTOM_WIDGET_MAP', {}))\n if config_file is not None:\n dialog.loadConfigFile(config_file)\n elif len(models) > 0:\n dialog.setModel(models)\n else:\n dialog.chooseModels()\n dialog.show()\n sys.exit(app.exec_())\n return\n\n\ndef main():\n form_cmd()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/taurus-4.6.1-py2.7/taurusform.py","file_name":"taurusform.py","file_ext":"py","file_size_in_byte":37697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"317140244","text":"\"\"\"Added support for user roles.\n\nRevision ID: 839e29065dc1\nRevises: a8ab43b5fdea\nCreate Date: 2020-09-24 15:07:55.750704\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '839e29065dc1'\ndown_revision = 'a8ab43b5fdea'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('role',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=32), nullable=True),\n sa.Column('default', sa.Boolean(), nullable=True),\n sa.Column('permissions', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n with op.batch_alter_table('role', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_role_default'), ['default'], unique=False)\n\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.add_column(sa.Column('role_id', sa.Integer(), nullable=True))\n batch_op.create_foreign_key(None, 'role', ['role_id'], ['id'])\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('user', schema=None) as batch_op:\n batch_op.drop_constraint(None, type_='foreignkey')\n batch_op.drop_column('role_id')\n\n with op.batch_alter_table('role', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_role_default'))\n\n op.drop_table('role')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/839e29065dc1_added_support_for_user_roles.py","file_name":"839e29065dc1_added_support_for_user_roles.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211961813","text":"import sys,pygame\nfrom pygame import gfxdraw\n\npygame.init()\nscreen = pygame.display.set_mode((600,400))\ntela = pygame.Surface((600, 400))\nwhite=(255,255,255)\nblack=(0,0,0)\nred = (255,0,0)\nlime = (0,255,0)\nblue = (0,0,255)\nyellow = (255,255,0)\naqua = (0,255,255)\nmagenta = (255,0,255)\nsilver = (192,192,192)\ngray = (128,128,128)\nmaroon = (128,0,0)\nolive = (128,128,0)\ngreen = (0,128,0)\npurple = (128,0,128)\nteal = (0,128,128)\nnavy = (0,0,128)\n\nmenu_font = pygame.font.Font(None, 17)\n\nlimpar_txt = menu_font.render(\"Limpar\", True, black)\nlinha_txt = menu_font.render(\"Linha\", True, black)\nretangulo_txt = menu_font.render(\"Retangulo\", True, black)\nquadrado_txt = menu_font.render(\"Quadrado\", True, black)\ncirculo_txt = menu_font.render(\"Circulo\", True, black)\npolilinha_txt = menu_font.render(\"Polilinha\", True, black)\ncurva_txt = menu_font.render(\"Curva\", True, black)\npreenchimento_txt = menu_font.render(\"Preench.\", True, black)\nlista_cores = [white,silver,gray,black,maroon,red,magenta,purple,navy,blue,teal,teal,aqua,lime,green,olive,yellow]\ncolor = black #default\nfuncao = 1 #1 = Bresenham #2=...\npreenchido = False\nmenu_rect = pygame.Rect(0, 0, 100, 400)\nscreen_rect = pygame.Rect(100, 0, 400, 400)\n\nwhite_rect = pygame.Rect(5, 25, 20, 20)\nsilver_rect = pygame.Rect(27, 25, 20, 20)\ngray_rect = pygame.Rect(5, 47, 20, 20)\nblack_rect = pygame.Rect(27, 47, 20, 20)\nmaroon_rect = pygame.Rect(5, 69, 20, 20)\nred_rect = pygame.Rect(27, 69, 20, 20)\nmagenta_rect = pygame.Rect(5, 91, 20, 20)\npurple_rect = pygame.Rect(27, 91, 20, 20)\nnavy_rect = pygame.Rect(5, 113, 20, 20)\nblue_rect = pygame.Rect(27, 113, 20, 20)\nteal_rect = pygame.Rect(5, 135, 20, 20)\naqua_rect = pygame.Rect(27, 135, 20, 20)\nlime_rect = pygame.Rect(5, 157, 20, 20) \ngreen_rect = pygame.Rect(27, 157, 20, 20)\nolive_rect = pygame.Rect(5, 179, 20, 20)\nyellow_rect = pygame.Rect(27, 179, 20, 20)\nlimpar_rect = pygame.Rect(5,200,42,20)\nlinha_rect = pygame.Rect(5,222,42,20)\nretangulo_rect = pygame.Rect(5,244,42,20)\nquadrado_rect = pygame.Rect(5,266,42,20)\npolilinha_rect = pygame.Rect(5,288,42,20)\ncurva_rect = pygame.Rect(5,310,42,20)\ncirculo_rect = pygame.Rect(5,332,42,20)\npreenchimento_rect = pygame.Rect(5,354,42,20)\n\nlista_rect_cores = [white_rect,silver_rect,gray_rect,black_rect,maroon_rect,red_rect,magenta_rect,purple_rect,navy_rect,blue_rect,teal_rect,teal_rect,aqua_rect,lime_rect,green_rect,olive_rect,yellow_rect]\n\ndef desenha_menu():\n\tfor x in range(len(lista_cores)):\n\t\tpygame.draw.rect(screen,lista_cores[x],lista_rect_cores[x])\n\t\tif color == lista_cores[x]:\n\t\t\tborder = 3\n\t\telse:\n\t\t\tborder = 1\n\t\t\tpygame.draw.rect(screen, black, lista_rect_cores[x], border)\n\tpygame.draw.rect(screen,silver,limpar_rect)\n\tscreen.blit(limpar_txt,(7,204))\n\tpygame.draw.rect(screen,silver,linha_rect)\n\tscreen.blit(linha_txt,(7,226))\n\tpygame.draw.rect(screen,silver,retangulo_rect)\n\tscreen.blit(retangulo_txt,(7,248))\n\tpygame.draw.rect(screen,silver,quadrado_rect)\n\tscreen.blit(quadrado_txt,(7,270))\n\tpygame.draw.rect(screen,silver,polilinha_rect)\n\tscreen.blit(polilinha_txt,(7,292))\n\tpygame.draw.rect(screen,silver,curva_rect)\n\tscreen.blit(curva_txt,(7,314))\n\tpygame.draw.rect(screen,silver,circulo_rect)\n\tscreen.blit(circulo_txt,(7,336))\n\tpygame.draw.rect(screen,silver,curva_rect)\n\tscreen.blit(curva_txt,(7,314))\n\tif preenchido == True:\n\t\tpygame.draw.rect(screen,silver,preenchimento_rect)\n\telse:\n\t\tpygame.draw.rect(screen,gray,preenchimento_rect)\n\tscreen.blit(preenchimento_txt,(7,359))\n\n# collision detection for COLOR\ndef escolhe_menu(mouse_pos): \n\tglobal color\n\tglobal funcao\n\tglobal preenchido\n\tif white_rect.collidepoint(mouse_pos):\n\t\tcolor = white\n\telif silver_rect.collidepoint(mouse_pos):\n\t\tcolor = silver\n\telif gray_rect.collidepoint(mouse_pos):\n\t\tcolor = gray\n\telif black_rect.collidepoint(mouse_pos):\n\t\tcolor = black\n\telif maroon_rect.collidepoint(mouse_pos):\n\t\tcolor = maroon\n\telif red_rect.collidepoint(mouse_pos):\n\t\tcolor = red\n\telif magenta_rect.collidepoint(mouse_pos):\n\t\tcolor = magenta\n\telif purple_rect.collidepoint(mouse_pos):\n\t\tcolor = purple\n\telif navy_rect.collidepoint(mouse_pos):\n\t\tcolor = navy\n\telif blue_rect.collidepoint(mouse_pos):\n\t\tcolor = blue\n\telif teal_rect.collidepoint(mouse_pos):\n\t\tcolor = teal\n\telif aqua_rect.collidepoint(mouse_pos):\n\t\tcolor = aqua\n\telif lime_rect.collidepoint(mouse_pos):\n\t\tcolor = lime\n\telif green_rect.collidepoint(mouse_pos):\n\t\tcolor = green\n\telif olive_rect.collidepoint(mouse_pos):\n\t\tcolor = olive\n\telif yellow_rect.collidepoint(mouse_pos):\n\t\tcolor = yellow\n\telif limpar_rect.collidepoint(mouse_pos):\n\t\tlimpa_tela()\n\telif linha_rect.collidepoint(mouse_pos):\n\t\tfuncao = 1\n\telif quadrado_rect.collidepoint(mouse_pos):\n\t\tfuncao = 2\n\telif polilinha_rect.collidepoint(mouse_pos):\n\t\tfuncao = 3\n\telif circulo_rect.collidepoint(mouse_pos):\n\t\tfuncao = 4\n\telif curva_rect.collidepoint(mouse_pos):\n\t\tfuncao = 5\n\telif retangulo_rect.collidepoint(mouse_pos):\n\t\tfuncao = 6\n\telif preenchimento_rect.collidepoint(mouse_pos):\n\t\tpreenchido = not preenchido\n\t\tdesenha_menu()\n\t\tpygame.display.flip()\n\t\t\n\n\ndef limpa_tela():\n\tscreen.fill(white)\n\tdesenha_menu()\n\ttela.blit(screen,(0,0),menu_rect)\n\tpygame.draw.line(screen, black, (55, 40), (55, 360))\n\tpygame.draw.line(screen, black, (59, 40), (59, 360))\n\tpygame.display.flip()\n\n\ndef frange(start, stop, step):#para aceitar float\n\tx = start\n\twhile x < stop:\n\t\tyield x\n\t\tx += step\n\ndef bezier():\n\tcoord = []\n\tcoord[0:1] = pipf()\n\tcoord[2:3] = pipf()\n\tfor t in frange(0,1,0.01):\n\t\tx1,y1 = coord[0] #ponto onde começa da curva\n\t\tx2,y2 = coord[1] #primeiro ponto de controle\n\t\tx3,y3 = coord[2] #segundo ponto de controle\n\t\tx4,y4 = coord[3] #ponto onde termina a curva\n\t\tomt = 1-t\n\t\tomt2 = omt*omt\n\t\tomt3 = omt2*omt\n\t\tt2 = t*t\n\t\tt3 = t2*t\n\t\tx = omt3 * x1 + ((3*omt2)*t*x2) + (3*omt*t2*x3)+t3*x4\n\t\ty = omt3 * y1 + ((3*omt2)*t*y2) + (3*omt*t2*y3)+t3*y4\n\t\t\n\t\tx = int(round(x,0))#arredonda e transforma para inteiro\n\t\ty = int(round(y,0))\n\n\t\tscreen.set_at((x,y),color)\n\t\tpygame.display.flip()\n\ndef circle(): #cx,cy = centro da circunferencia\n\t(cx,cy),(aux1,aux2) = pipf()\n\traio = int(((abs(cx-aux1)**2)+(abs(cy-aux2)**2))**(1/2))\n\tif preenchido:\n\t\tcont = raio\n\telse:\n\t\tcont = 1\n\n\tfor linha in range(cont):\n\t\tx = 0\n\t\ty = raio\n\t\td = 1-raio\n\t\twhile x < y:\n\t\t\tplotCircle(x,y,cx,cy)\n\t\t\tx += 1\n\t\t\tif d < 0:\n\t\t\t\td += 2 * x + 1\n\t\t\telse:\n\t\t\t\ty -= 1\n\t\t\t\td += 2*(x-y) + 1\n\t\traio = raio -1\n\n\tpygame.display.flip()\n\n\ndef plotCircle(x,y,cx,cy):\n\tgfxdraw.pixel(screen,cx+x,cy+y,color)\n\tgfxdraw.pixel(screen,cx-x,cy+y,color)\n\tgfxdraw.pixel(screen,cx+x,cy-y,color)\n\tgfxdraw.pixel(screen,cx-x,cy-y,color)\n\tgfxdraw.pixel(screen,cx+y,cy+x,color)\n\tgfxdraw.pixel(screen,cx-y,cy+x,color)\n\tgfxdraw.pixel(screen,cx+y,cy-x,color)\n\tgfxdraw.pixel(screen,cx-y,cy-x,color)\n\ndef polilinha():\n\tc1, c2 = bresenham(pipf()) #pega esse ultimo ponto\n\n\twhile funcao == 3:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\ta,b,c = pygame.mouse.get_pressed()\n\t\t\t\tif(c == True):\n\t\t\t\t\tbreak #sai do loop ao apertar o botão esquerdo\n\t\t\t\telse:\n\t\t\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t\t\tif (x<59):\n\t\t\t\t\t\tescolhe_menu((x,y))\n\t\t\t\t\t\tif funcao != 3: #se mudar de ferramenta\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tc1, c2 = bresenham([(c1,c2),(x,y)])\n\t\t\tif event.type == pygame.QUIT: sys.exit()\n\ndef pipf(): #ponto final, ponto inicial\n\ti = 0\n\tposic = []\n\twhile i<2:\n\t\tfor e in pygame.event.get():\n\t\t\tif e.type == pygame.QUIT:\n\t\t\t\tsys.exit()\n\t\t\tif e.type == pygame.MOUSEBUTTONDOWN:\n\t\t\t\ta = pygame.mouse.get_pos()\n\t\t\t\tif (a[0]<59):\n\t\t\t\t\tescolhe_menu(a)\n\t\t\t\telse:\n\t\t\t\t\tposic.append(pygame.mouse.get_pos())\n\t\t\t\t\ti = i+1\n\treturn posic\n\n\ndef retangulo():\n\t[(x,y),(x2,y2)] = pipf()\n\tif preenchido:\n\t\tif x>x2:\n\t\t\t(x,y),(x2,y2) = (x2,y2),(x,y)\n\t\twhile(x<=x2):\n\t\t\tbresenham([(x,y),(x,y2)])\n\t\t\tx = x+1\n\telse:\n\t\tbresenham([(x,y),(x2,y)])\n\t\tbresenham([(x,y),(x,y2)])\n\t\tbresenham([(x,y2),(x2,y2)])\n\t\tbresenham([(x2,y),(x2,y2)])\n\ndef linha():\n\tbresenham(pipf())\n\ndef quadrado():\n\t[(x,y),(x2,y2)] = pipf()\n\tif (abs(x-x2)>abs(y-y2)):\n\t\tlado = abs(x-x2)\n\telse:\n\t\tlado = abs(y-y2)\n\tif preenchido:\n\t\tif(x>x2):\n\t\t\t(x,y),(x2,y2) = (x2,y2),(x,y)\n\t\tx,y = x-lado,y-lado\n\t\tx2,y2 = x+lado,y+lado\n\t\twhile(x<=x2):\n\t\t\tbresenham([(x,y),(x,y2)])\n\t\t\tx = x+1\n\telse:\n\t\tbresenham([(x-lado,y-lado),(x-lado,y+lado)]) #Ponto1 ao Ponto2\n\t\tbresenham([(x-lado,y-lado),(x+lado,y-lado)]) #Ponto1 ao Ponto3\n\t\tbresenham([(x+lado,y-lado),(x+lado,y+lado)]) #Ponto3 ao Ponto4\n\t\tbresenham([(x-lado,y+lado),(x+lado,y+lado)]) #Ponto2 ao Ponto4\n\ndef bresenham(coord):\n\tstart = coord[0]\n\tend = coord[1]\n\tx1, y1 = start\n\tx2, y2 = end\n\n\ttam_vert = pygame.display.get_surface().get_height()\n\t\n\tif x1>x2:\n\t\tx1,x2 = x2, x1\n\t\ty1,y2 = y2, y1\n\n\tdx = x2 - x1\n\tdy = abs(y2-y1)\n\n\tif y2-y1 < 0:\n\t\tsinaly = -1\n\telif y2-y1>0:\n\t\tsinaly = 1\n\telse:\n\t\tsinaly = 0\n\n\tif dy>dx:\n\t\tdx, dy = dy, dx\n\t\tmudou = 1\n\telse:\n\t\tmudou = 0\n\t\n\tdy2 = 2*dy \n\tdy2mdx = dy2 - dx #2*dy - dx menos dx\n\tdydx2 = dy2 - 2*dx #2*dy*dx\n\n\tx = x1\n\ty = y1\n\tscreen.set_at((x,y),color)\n\n\tfor i in range(dx):\n\t\tif dy2mdx < 0:\n\t\t\tif mudou >0:\n\t\t\t\ty = y + sinaly\n\t\t\telse:\n\t\t\t\tx = x+1\n\t\t\tdy2mdx = dy2mdx + dy2\n\t\telse:\n\t\t\ty = y+sinaly\n\t\t\tx = x+1\n\t\t\tdy2mdx = dy2mdx + dydx2\n\t\tscreen.set_at((x,y),color)\n\n\tpygame.display.flip()\n\treturn end #retorna o ultimo ponto\n\nlimpa_tela()\nwhile True:\n\tif funcao == 1:\n\t\tlinha()\n\telif funcao == 2:\n\t\tquadrado()\n\telif funcao == 3:\n\t\tpolilinha()\n\telif funcao == 4:\n\t\tcircle()\n\telif funcao == 5:\n\t\tbezier()\n\telif funcao == 6:\n\t\tretangulo()\n\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT: sys.exit()","sub_path":"trab1.py","file_name":"trab1.py","file_ext":"py","file_size_in_byte":9458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"297323473","text":"import glob\nimport os\nfrom pkg_resources import resource_filename\nimport pytest\n\nfrom foyer import Forcefield\n\n\nFF_DIR = resource_filename('foyer', 'forcefields')\nFORCEFIELDS = glob.glob(os.path.join(FF_DIR, '*.xml'))\n\ndef test_load_files():\n ff1 = Forcefield(forcefield_files=FORCEFIELDS)\n assert len(ff1._atomTypes) > 0\n\n ff2 = Forcefield(forcefield_files=FORCEFIELDS[0])\n assert len(ff1._atomTypes) == len(ff2._atomTypes)\n\n ff3 = Forcefield(name='oplsaa')\n assert len(ff1._atomTypes) == len(ff3._atomTypes)\n\ndef test_duplicate_type_definitions():\n with pytest.raises(ValueError):\n ff4 = Forcefield(name='oplsaa', forcefield_files=FORCEFIELDS)\n","sub_path":"foyer/tests/test_forcefield.py","file_name":"test_forcefield.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92094837","text":"from django.conf.urls import url\nfrom .views import MyCourseView,MyFavOrgView,MyFavTeacherView,MyFavCourseView,MyMessageView\nfrom .views import UserImageView,UserInfoView,ChangePwdView\nurlpatterns = [\n #个人信息\n url(r'^info/$',UserInfoView.as_view(),name=\"info\"),\n #修改用户头像\n url(r'^image/upload/$',UserImageView.as_view(),name=\"image\"),\n #修改密码\n url(r'^update/pwd/$',ChangePwdView.as_view(),name=\"pwd\"),\n #修改手机号\n url(r'^update/mobile/$',ChangePwdView.as_view(),name=\"mobile\"),\n #我的课程\n url(r'^mycourse/$',MyCourseView.as_view(),name=\"mycourse\"),\n #我的收藏课程机构\n url (r'^myfavorg',MyFavOrgView.as_view(),name=\"myfavorg\"),\n # 我的收藏课程教师\n url(r'^myfavteacher', MyFavTeacherView.as_view(), name=\"myfavteacher\"),\n # 我的收藏课程\n url(r'^myfavcourse', MyFavCourseView.as_view(), name=\"myfavcourse\"),\n #我的消息\n url(r'^message', MyMessageView.as_view(), name=\"message\"),\n\n\n]\n\n\n\n\n\n\n\n\n\n","sub_path":"apps/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647847779","text":"#!/usr/bin/python3\r\n\r\nimport sqlite3, sys\r\n\r\ndef dict_factory( cursor, row ):\r\n\tresult = {}\r\n\t\r\n\tfor index, column in enumerate( cursor.description ):\r\n\t\tresult[ column[ 0 ] ] = row[ index ]\r\n\t\r\n\treturn result\r\n\r\ndef execute( query, parameters = None ):\r\n\tconnection = sqlite3.connect( 'db/simpledb.sqlite' )\r\n\tconnection.row_factory = dict_factory\r\n\tcursor = connection.cursor()\r\n\r\n\tif parameters is not None:\r\n\t\tfor key in parameters.keys():\r\n\t\t\tvalue = parameters[ key ]\r\n\r\n\t\t\tif type( value ) == str:\r\n\t\t\t\tvalue = \"'\" + value + \"'\"\r\n\r\n\t\t\tquery = query.replace( '${' + str( key ) + '}', str( value ) )\r\n\r\n\tcursor.execute( query )\t\r\n\tresult = cursor.fetchall()\r\n\t\r\n\tconnection.commit()\r\n\tconnection.close()\r\n\r\n\treturn result\r\n\r\nCREATE_TABLE_GAME = \"\"\"\r\n\tCREATE TABLE game (\r\n\t\tid INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL,\r\n\t\tname TEXT NOT NULL,\r\n\t\tlink TEXT NOT NULL,\r\n\t\tintroText TEXT NOT NULL,\r\n\t\ticonImage TEXT NOT NULL,\t\t\r\n\t\tregDateTime DATETIME NOT NULL\r\n\t)\r\n\"\"\"\r\n\r\nCREATE_TABLE_INTROIMAGE = \"\"\"\r\n\tCREATE TABLE introImage (\r\n\t\tgameId INTEGER NOT NULL,\r\n\t\timage TEXT NOT NULL,\r\n\t\torderSeq INTEGER NOT NULL\r\n\t)\r\n\"\"\"\r\n\r\nSELECT_MAX_GAME_ID = \"\"\"\r\n\tSELECT MAX( id ) FROM game\r\n\"\"\"\r\n\r\nSELECT_ICON_INFO = \"\"\"\r\n\tSELECT id, name, iconImage FROM game ORDER BY id\r\n\"\"\"\r\n\r\nSELECT_GAME_INFO = \"\"\"\r\n\tSELECT link, introText FROM game WHERE id = ${id}\r\n\"\"\"\r\n\r\nSELECT_INTRO_IMAGE = \"\"\"\r\n\tSELECT image FROM introImage WHERE gameId = ${id}\r\n\"\"\"\r\n\r\nINSERT_GAME = \"\"\"\r\n\tINSERT INTO game ( name, link, introText, iconImage, regDateTime ) VALUES ( ${name}, ${link}, ${introText}, ${iconImage}, datetime() )\t\r\n\"\"\"\r\n\r\nINSERT_INTROIMAGE = \"\"\"\r\n\tINSERT INTO introImage ( gameId, image, orderSeq ) VALUES ( ${gameId}, ${image}, ${orderSeq} )\r\n\"\"\"","sub_path":"server/db/dbms.py","file_name":"dbms.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424784089","text":"# Copyright 2014-2016 by Akira Yoshiyama .\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nResource class and its manager for services in Compute API v2\n\"\"\"\n\nfrom osclient2 import base\nfrom osclient2 import mapper\nfrom osclient2 import utils\n\n\nclass Service(base.Resource):\n \"\"\"Resource class for services in Compute API v2\"\"\"\n\n def enable(self):\n \"\"\"\n Enable a service on a host\n \"\"\"\n self._manager.enable(host=self.host, binary=self.binary)\n\n def disable(self):\n \"\"\"\n Disable a service on a host\n \"\"\"\n self._manager.disable(host=self.host, binary=self.binary)\n\n def set_disabled_reason(self, reason=None):\n \"\"\"\n Set disabled reason for a service on a host\n\n :param reason=: description\n \"\"\"\n self._manager.set_disabled_reason(host=self.host, binary=self.binary,\n reason=reason)\n\n\nclass Manager(base.Manager):\n \"\"\"Manager class for services in Compute API v2\"\"\"\n\n service_type = 'compute'\n url_resource_path = '/os-services'\n json_resource_key = 'service'\n json_resources_key = 'services'\n\n resource_class = Service\n attr_mapping = [\n ('id', 'id', mapper.Noop, 'Service ID (string)'),\n ('host', 'host', mapper.Noop, 'Hostname ID (string)'),\n ('binary', 'binary', mapper.Noop, 'Program name (string)'),\n ('state', 'state', mapper.Noop, 'State (string)'),\n ('status', 'status', mapper.Noop, 'Status (string)'),\n ('updated_at', 'updated_at', mapper.DateTime,\n 'Updated timestamp (datetime object)'),\n ('availability_zone', 'zone',\n mapper.Resource('nova.v2.availability_zone'),\n 'Availability zone (AvailabilityZone object)'),\n ('disabled_reason', 'disabled_reason', mapper.Noop,\n 'Disabled reason (string)'),\n ]\n\n def create(self):\n raise NotImplementedError()\n\n @utils.resource_method\n def update(self, id, name=None, availability_zone=None):\n \"\"\"\n Create a host aggregate\n\n :param id: ID of the aggregate\n :param name=: name of the host aggregate\n :param availability_zone=: name of availability zone\n \"\"\"\n return super(Manager, self).update(id,\n name=name,\n availability_zone=availability_zone)\n\n def enable(self, host=None, binary=None):\n \"\"\"\n Enable a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path, \"enable\"),\n data=dict(host=host, binary=binary))\n\n def disable(self, host=None, binary=None):\n \"\"\"\n Disable a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path, \"disable\"),\n data=dict(host=host, binary=binary))\n\n def set_disabled_reason(self, host=None, binary=None, reason=None):\n \"\"\"\n Set disabled reason for a service on a host\n\n :param host=: host name (str, required)\n :param binary=: binary name (str, required)\n :param reason=: description (str, required)\n \"\"\"\n self.http.put(utils.join_path(self.url_resource_path,\n \"disable-log-reason\"),\n data=dict(host=host, binary=binary,\n disabled_reason=reason))\n","sub_path":"osclient2/nova/v2/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"23839795","text":"def quadratic(alist):\n for i in alist:\n isSmallest = True\n for x in alist:\n if i > x:\n isSmallest = False\n if isSmallest == True:\n print(str(i) + \" is the smallest number.\")\n\n\nquadratic([14,205, 242, 12, 11, 180, 22, 48])\n\n\ndef linear (alist):\n min = alist[0]\n for i in alist:\n if i < min:\n min = i\n print(str(min) + \" is the smallest number.\") \n\n\nlinear([9, 12, 14, 8, 19, 20]) \n","sub_path":"interactivePython/minimumInAList.py","file_name":"minimumInAList.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"362728933","text":"from flask import Flask\nfrom flask import session as server_session\nfrom flask_restful import Api\nfrom flask_session import Session\nfrom flask_login import LoginManager\nfrom flask_bootstrap import Bootstrap\nimport pyrebase\nimport os\n\n\napp = Flask(__name__)\napi = Api(app)\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = \"login\"\napp.config.from_object(__name__)\ntry:\n with open(\"secret_key\", \"rb\") as read_file:\n app.config[\"SECRET_KEY\"] = read_file.read()\nexcept:\n from gen_secret import generate_secret_key\n generate_secret_key()\n with open(\"secret_key\", \"rb\") as read_file:\n app.config[\"SECRET_KEY\"] = read_file.read()\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\n\nSession(app)\nbootstrap = Bootstrap(app)\n\nfirebaseConfig = {\n \"apiKey\": \"AIzaSyAOt2oJnOJHOLgyFHApNINzAqrtS2B0lcY\",\n \"authDomain\": \"projectmanagementapi.firebaseapp.com\",\n \"databaseURL\": \"https://projectmanagementapi.firebaseio.com\",\n \"projectId\": \"projectmanagementapi\",\n \"storageBucket\": \"projectmanagementapi.appspot.com\",\n \"messagingSenderId\": \"432840428373\",\n \"appId\": \"1:432840428373:web:d4aa71e700009b3bed3ddc\",\n \"measurementId\": \"G-FX9PKEDNE6\"\n}\n\nfirebase = pyrebase.initialize_app(firebaseConfig)\ndb = firebase.database()\n\nfrom app import routes","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207857283","text":"from Environment.environment import UnoEnvironment\nfrom Environment.card import Card\nfrom Environment.player import Player\nfrom Players.HumanPlayer import HumanPlayer\n\n\nclass UnoGame(UnoEnvironment):\n def __init__(self, agent: Player):\n super().__init__(True)\n self.reset(HumanPlayer(), agent)\n self.wait_for_action()\n\n def wait_for_action(self):\n player = self.players[0]\n\n legal_actions = self.get_legal_actions()\n illegal_input = True\n while illegal_input:\n action_input = int(input(\"Input action:\"))\n if 0 <= action_input <= player.get_hand_size():\n if action_input == 0:\n action = 54\n self.played_card = None\n illegal_input = False\n else:\n self.played_card = player.cards[action_input - 1]\n action = player.cards[action_input - 1].action_number\n if action in legal_actions:\n illegal_input = False\n else:\n print(\"You can't do that\")\n else:\n print(\"You can't do that\")\n self.step_with_opp_step(action)\n\n def next_turn(self, skip):\n if skip:\n self.previous_player_index = self.current_player_index\n else:\n self.current_player = self.next_player() # cycles 0 and 1\n self.previous_player_index = self.current_player_index\n self.current_player_index = self.next_player_index()\n\n self.pretty_print_state()\n if self.current_player_index == 0:\n self.wait_for_action()\n\n def skip(self):\n self.pretty_print_state()\n self.wait_for_action()\n\n def pretty_print_state(self):\n print(\"-------------------------------------------------------------------------------------------------------\")\n print(\"Turn \" + str(self.turn))\n Card.pretty_print_cards(self.played_cards[len(self.played_cards) - 1:], False)\n\n for i, player in enumerate(self.players):\n\n if i == self.current_player_index:\n print(\"ACTIVE-\", end='')\n print(player.name + \"'s hand:\")\n if i == 0:\n player.print_hand()\n else:\n print(len(player.cards), \"cards\")\n print(\"-------------------------------------------------------------------------------------------------------\")","sub_path":"Game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470491419","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\nfrom .forms import ContactForm\n\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef contact(request):\n success = False\n\n form = ContactForm(request.POST or None)\n if form.is_valid():\n form.send_email()\n success = True\n form = ContactForm()\n\n context = {\n 'form': form,\n 'success': success\n }\n return render(request, 'contact.html', context)\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"1383178","text":"import csv\nimport re\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as sio\n\nfrom scipy import signal\nimport peakutils\n\n\nclass read_spectrometer():\n def __init__(self):\n\n #regex for sample description classification. example file name: sample1-H20-T20-Nikon10x-001\n self.temperature_re = re.compile('T\\d+.?\\d*')\n self.humidity_re = re.compile('H\\d+.?\\d*-')\n self.spot_number_re = re.compile('sample\\d+-')\n\n #plotting settings\n self.fig = plt.figure(figsize=(12,4), dpi=200)\n self.intensity_lim = (0,1.1) # range of normalised intensity\n self.humidity_lim = (0,100) # range of RH\n self.plot_colour = ['r','g','b','y','k'] # colour scheme for multiple samples\n\n \n def initialise_methods(self):\n ' initialise class methods '\n self.convert_matlab_scan()\n self.format_result()\n self.remove_background(background_scan_number = 0)\n self.format_description()\n self.find_peaks(find_peak_method = 'scipy')\n self.format_peak_data()\n\n \n def convert_matlab_scan(self):\n 'this converts matlab data into np.ndarray '\n self.mat_scan_contents = sio.loadmat(self.folder +'\\\\'+ 'scan.mat')['scan']\n self.scan_result = {}\n # catagorise scan result into spectrum, description and wavelength\n for i in ['spec', 'desc', 'wl']:\n self.scan_result[i] = self.mat_scan_contents[i]\n # total scan numbers\n self.total_scan_number = len(self.scan_result['wl'])\n \n def read_result(self, feature, scan_number): \n '''Return all datapoints with certain features of certain scan\n\n #print(all_datapoints)\n # read value at certain datapoint\n #data_point = 100\n #print(all_datapoints[data_point])'''\n\n all_datapoints = self.scan_result[feature][scan_number][0]\n\n return all_datapoints\n\n def format_result(self):\n 'convert all the information about one sample into a 2d array '\n self.formatted_scan_results = {}\n self.description = {}\n for scan_number in range(self.total_scan_number):\n wavelength_data = self.read_result(feature = 'wl', scan_number = scan_number)\n intensity_data = self.read_result(feature = 'spec', scan_number = scan_number)\n description = self.read_result(feature = 'desc', scan_number = scan_number)\n # form a 2d array with wavelength and spec data\n self.formatted_scan_results[scan_number] = np.vstack((\n np.transpose(wavelength_data), \n np.transpose(intensity_data)))\n self.description[scan_number] = description\n \n def remove_background(self, background_scan_number = 0):\n 'substract background on non-sample area'\n self.background_substracted_scan_results = {}\n # the sample_number of background spectrometer you want to remove\n background_intensity = self.formatted_scan_results[background_scan_number][1] # [1] is the spec\n for scan_number in range(self.total_scan_number):\n self.background_substracted_scan_results[scan_number] = np.vstack(\n (self.formatted_scan_results[scan_number][0],\n self.formatted_scan_results[scan_number][1] - background_intensity)) \n \n def format_description(self):\n 'Use regex to format the description. Exporting sample number, temperature, and humidity'\n self.temperature = {}\n self.humidity = {}\n self.sample_numbers = {}\n for scan_number in range(self.total_scan_number):\n description = self.description[scan_number][0] # convert list to string\n temperature = self.temperature_re.findall(description)\n humidity = self.humidity_re.findall(description)\n sample_number = self.spot_number_re.findall(description)\n\n try:\n temperature = temperature[0].replace('T','').replace('-','')\n except IndexError: \n temperature = '' # if the data is empty, set it to ''\n try:\n humidity = humidity[0].replace('H','').replace('-','')\n except IndexError:\n humidity = '' # if the data is empty, set it to ''\n try:\n # for desc with same sample_number, add them to a list\n sample_number = sample_number[0].replace('sample','').replace('-','')\n if sample_number not in self.sample_numbers:\n self.sample_numbers[sample_number] = []\n self.sample_numbers[sample_number].append(scan_number)\n except IndexError:\n pass\n\n self.temperature[scan_number] = temperature\n self.humidity[scan_number] = humidity\n\n # override the self.sample_numbers\n #self.sample_numbers[0] = range(1,20)\n #self.sample_numbers[1] = (18,29)\n #print(self.formatted_scan_results[3])\n\n def find_peaks(self, find_peak_method):\n 'find peak using scipy'\n self.peak_wavelength = {}\n self.peak_intensity = {}\n if find_peak_method == 'scipy':\n for scan_number in range(self.total_scan_number):\n # for each scan, find peaks\n peak_data_points = signal.find_peaks_cwt(\n self.formatted_scan_results[scan_number][1], np.arange(50,150))\n for peak_data_point in peak_data_points:\n 'filter out the peak thats not in our interested wavelength'\n # convert datapoint into wavelength\n peak_wavelength = float(self.formatted_scan_results[scan_number][0][peak_data_point])\n if peak_wavelength > self.wavelength_lim[0] and peak_wavelength < self.wavelength_lim[1]:\n self.peak_wavelength[scan_number] = peak_wavelength\n self.peak_intensity[scan_number] = self.formatted_scan_results[scan_number][1][peak_data_point]\n break\n\n elif find_peak_method == 'peakutils':\n for scan_number in range(self.total_scan_number):\n # for each scan, find peaks\n peak_data_points = peakutils.indexes(self.formatted_scan_results[scan_number][1], thres=0.5/max(self.formatted_scan_results[scan_number][1]), min_dist=100)\n #peak_data_points = peakutils.interpolate((range(0, len(self.formatted_scan_results[scan_number][1]))), self.formatted_scan_results[scan_number][1])\n for peak_data_point in peak_data_points:\n 'filter out the peak thats not in our interested wavelength'\n # convert datapoint into wavelength\n peak_wavelength = float(self.formatted_scan_results[scan_number][0][peak_data_point])\n if peak_wavelength > self.wavelength_lim[0] and peak_wavelength < self.wavelength_lim[1]:\n self.peak_wavelength[scan_number] = peak_wavelength\n self.peak_intensity[scan_number] = self.formatted_scan_results[scan_number][1][peak_data_point]\n\n\n def format_peak_data(self):\n self.peak_data = {}\n for sample_number in self.sample_numbers.keys():\n self.peak_data[sample_number] = {}\n for i in ['humidity', 'temperature', 'peak_wavelength', 'peak_intensity']:\n self.peak_data[sample_number][i] = []\n for scan_number in self.sample_numbers[sample_number]:\n self.peak_data[sample_number]['humidity'].append(float(self.humidity[scan_number]))\n self.peak_data[sample_number]['temperature'].append(float(self.temperature[scan_number]))\n self.peak_data[sample_number]['peak_wavelength'].append(self.peak_wavelength[scan_number])\n self.peak_data[sample_number]['peak_intensity'].append(self.peak_intensity[scan_number])\n\n\n def plot_spectrum(self, scan_number):\n 'plot spectra with given sample number, optionally show peaks'\n ax = plt.subplot(211)\n scan_number = scan_number -1 # convert scan number to python numbering system (start from 0)\n if scan_number > self.total_scan_number:\n scan_number = self.total_scan_number - 1\n ax.plot(\n self.formatted_scan_results[scan_number][0], #wavelength\n self.formatted_scan_results[scan_number][1], #intensity\n label='sample: {}\\n{}'.format(scan_number + 1, self.description[scan_number]))\n if self.background_substraction is True:\n ax.plot(\n self.background_substracted_scan_results[scan_number][0], #wavelength\n self.background_substracted_scan_results[scan_number][1], #intensity\n label='bg_removed_sample: {}\\n{}'.format(\n scan_number + 1, self.description[scan_number])) \n \n if self.show_peaks is True:\n ax.plot(\n (self.peak_wavelength[scan_number],self.peak_wavelength[scan_number]),\n self.intensity_lim,\n label = 'scipy peaks')\n\n # set range etc\n ax.set_xlim(self.wavelength_lim)\n ax.set_ylim(self.intensity_lim)\n lines, labels = ax.get_legend_handles_labels()\n ax.legend(\n lines, labels,\n scatterpoints=1, fancybox=True, shadow=True, ncol=1,\n fontsize=12, loc=1, bbox_to_anchor=(1.1,1))\n\n def plot_humidity_vs_peaks(self):\n 'plot wavelength change with humidity'\n ax2 = plt.subplot(212)\n for sample_number in self.sample_numbers:\n ax2.scatter(\n self.peak_data[sample_number]['humidity'],\n self.peak_data[sample_number]['peak_wavelength'],\n c = self.plot_colour[int(sample_number)],\n label = 'spot{}'.format(sample_number))\n\n # set range etc\n ax2.set_xlim(self.humidity_lim)\n ax2.set_ylim(self.wavelength_lim)\n ax2.legend(\n scatterpoints=1, fancybox=True, shadow=True, ncol=1,\n fontsize=12, loc=1, bbox_to_anchor=(1.1,1))\n\n\n def export_data(self, filename):\n 'Export data to a csv sheet'\n with open(filename, 'w', newline=\"\") as csvfile:\n csv_writer = csv.writer(csvfile, dialect = 'excel')\n csv_writer.writerow(['scan number','sample description','temperature','humidity','wavelength','intensity'])\n for scan_number in range(self.total_scan_number):\n csv_writer.writerow(\n ['{}'.format(scan_number + 1) ,\n '{}'.format(self.description[scan_number]),\n '{}'.format(self.temperature[scan_number]),\n '{}'.format(self.humidity[scan_number]),\n '{}'.format(self.peak_wavelength[scan_number]),\n '{}'.format(self.peak_intensity[scan_number])])\n\nif __name__ == \"__main__\":\n# visualisation\n spectrometer_result = read_spectrometer()\n # initialise some parameters\n spectrometer_result.folder = r\"D:\\GDrive\\Research\\BIP\\Humidity sensor project\\data\\20170421\"\n spectrometer_result.background_substraction = False # secondary background substraction\n spectrometer_result.show_peaks = True # draw a line at peak positions\n spectrometer_result.wavelength_lim = (400,700) # range of wavelength to plot\n \n spectrometer_result.initialise_methods()\n # plot individual scan\n spectrometer_result.plot_spectrum(1)\n # plot peak wavelength change with relative humidity\n spectrometer_result.plot_humidity_vs_peaks()\n # export data to scan.csv\n spectrometer_result.export_data(spectrometer_result.folder + '\\\\' + 'scan.csv')\n # show matplotlib figure\n plt.show()\n","sub_path":"spectrometer/read_scan.py","file_name":"read_scan.py","file_ext":"py","file_size_in_byte":11784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"402425805","text":"from express.properties.scalar import ScalarProperty\n\n\nclass ReactionEnergyBarrier(ScalarProperty):\n \"\"\"\n Reaction energy barrier.\n \"\"\"\n\n def __init__(self, name, parser, *args, **kwargs):\n super(ReactionEnergyBarrier, self).__init__(name, parser, *args, **kwargs)\n energies = self.parser.reaction_energies()\n self.value = sorted(energies, key=lambda e: abs(e or 0), reverse=True)[0]\n","sub_path":"express/properties/scalar/reaction_energy_barrier.py","file_name":"reaction_energy_barrier.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95370399","text":"'''Write a Python program for all the cases which can check a string contains only a certain set of characters\r\n(in this case a-z, A-Z and 0-9).'''\r\nimport re\r\n\r\ndef is_allowed_specific_character(s):\r\n characterRe = re.compile(r'[^a-zA-Z0-9.]')\r\n s = characterRe.search(s)\r\n return not bool(s)\r\n\r\nprint(is_allowed_specific_character(\"Puneetpsk1609\")) \r\nprint(is_allowed_specific_character(\"85686@psk123_\"))\r\n\r\n\r\nprint()\r\n#Write a Python program that matches a word containing 'ab'.\r\n\r\ndef text_match(t):\r\n p = '\\w*ab.\\w*'\r\n if re.search(p, t):\r\n return \"Match Found! Hurray!!\"\r\n else:\r\n return(\"Oops!! Match not found\")\r\n\r\nprint(text_match(\"Puneet Python Lover\"))\r\nprint(text_match(\"abbbaaababababbbbaaa\"))\r\n\r\nprint()\r\n#Write a Python program to check for a number at the end of a word/sentence.\r\n\r\ndef end_num(s):\r\n text = re.compile(r\".*[0-9]$\")\r\n if text.match(s):\r\n return True\r\n else:\r\n return False\r\n\r\nprint(end_num('ab34de'))\r\nprint(end_num('abc123'))\r\nprint(end_num('abc'))\r\nprint(end_num('12345abcde'))\r\n\r\n\r\n\r\nprint()\r\n#Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given s\r\n\r\nresults = re.finditer(r\"([0-9]{1,3})\", \"Exercises number 1, 9, 11, and 222 are important\")\r\nprint(\"Number of length 1 to 3\")\r\nfor n in results:\r\n print(n.group(0))\r\n\r\n\r\nprint()\r\n#Write a Python program to match a string that contains only uppercase letters\r\n\r\ndef text_match(text):\r\n patterns = '^[a-zA-Z0-9_]*$'\r\n if re.search(patterns, text):\r\n return ('Match Found! Hurray!')\r\n else:\r\n return('Oops! Match not found!!')\r\n\r\nprint(text_match(\"The quick brown fox jumps over the lazy dog.\"))\r\nprint(text_match(\"Python_Exercises_1\"))\r\n","sub_path":"Day13.py","file_name":"Day13.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"159419373","text":"import os\n\n\ndef positive(num1, num2, num3):\n print(\"\\n==Positive==\\n\")\n product = num1 * num2\n i = 1\n nums = []\n while product >= i:\n if product % i == 0:\n nums.append([i, product / i])\n i += 1\n\n answer = []\n for i in range(len(nums)):\n if nums[i][0] + nums[i][1] == num3:\n answer = nums[i]\n if answer:\n return answer\n return \"No Solution\"\n\n\ndef negative(num1, num2, num3):\n print(\"\\n==Negative==\\n\")\n product = abs(num1 * num2)\n i = 1\n nums = []\n while product >= i:\n if product % i == 0:\n nums.append([i, product / i])\n i += 1\n\n answer = []\n for i in range(len(nums)):\n if nums[i][0] - nums[i][1] == num3:\n answer = [-nums[i][1], nums[i][0]]\n elif nums[i][1] - nums[i][0] == num3:\n answer = [nums[i][1], -nums[i][0]]\n if answer:\n return answer\n return \"No Solution\"\n\n\ndef clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n\ndef main():\n while True:\n num1 = int(input(\"Number 1 (first number): \"))\n num2 = int(input(\"Number 2 (second number): \"))\n num3 = int(input(\"Number 3 (sum): \"))\n # product = num1 * num2\n pos_neg = True\n div_err = False\n\n if num1 <= 0 and num2 > 0 and num3 < 0:\n pos_neg = True\n elif (num1 >= 0 and num2 > 0 and num3 > 0) or (num1 <= 0 and num2 < 0 and num3 < 0):\n pos_neg = False\n if num2 == 0:\n print(\"Zero Division Error\")\n div_err = True\n\n if not div_err:\n if pos_neg:\n print(negative(num1, num2, num3))\n if not pos_neg:\n print(positive(abs(num1), abs(num2), abs(num3)))\n input(\"Press Enter to continue: \")\n clear()\n\n\nprint(main())\nclear()\n","sub_path":"Calculators/factoring calculator.py","file_name":"factoring calculator.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"44540049","text":"\"\"\"\nA super basic implementation of the ELO ranking algorithm. The advantage\nof this algorithm is that it's very simple and does not require any more information\nthan an individual match in order to update rankings.\n\nThe downside is that ELO doesn't take into account the actual score, just a win/lose.\n\nIt updates rankings step-wise, and is expected to be called for each game in succession.\n\nhttp://en.wikipedia.org/wiki/Elo_rating_system\n\nEspecially: see http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details\n\"\"\"\nimport logging\nMAX_INCREASE = 32\nINITIAL_RANK = 1500.0\n\ndef update_ranks(game):\n logging.info('Updating rankings based on game %s' % game)\n logging.info('Winner: %s' % game.winner)\n logging.info('Prior ranks: (%s, %s) (%s, %s)' %\n (game.player_1.pseudonym, game.player_1.rank, game.player_2.pseudonym, game.player_2.rank))\n\n player_1 = game.player_1\n player_2 = game.player_2\n\n expected_1 = expected(player_2.rank, player_1.rank)\n expected_2 = expected(player_1.rank, player_2.rank)\n\n if game.winner.key() == game.player_1.key():\n score_1 = 1\n score_2 = 0\n elif game.winner.key() == game.player_2.key():\n score_1 = 0\n score_2 = 1\n else:\n raise \"No winner. Something went wrong.\"\n\n update_player_rank(player_1, score_1, expected_1)\n update_player_rank(player_2, score_2, expected_2)\n\n logging.info('Resulting ranks: (%s, %s) (%s, %s)' %\n (game.player_1.pseudonym, game.player_1.rank, game.player_2.pseudonym, game.player_2.rank))\n\n\ndef expected(rank_1, rank_2):\n return 1 / (1 + 10 ** (float(rank_1 - rank_2) / 400))\n\ndef update_player_rank(player, score, expected):\n logging.info('Updating player rank based on score: %s and expected score: %s' % (score, expected))\n player.rank += (MAX_INCREASE * (score - expected))\n\ndef max_increase(rank):\n \"\"\"\n Determines the maximum possible points that a player can get in any given match\n see http://en.wikipedia.org/wiki/Elo_rating_system#Most_accurate_K-factor\n \"\"\"\n if rank <= 2100:\n return 32\n if 2100 < rank <= 2400:\n return 24\n if 2400 < rank:\n return 16\n\n","sub_path":"lib/elo.py","file_name":"elo.py","file_ext":"py","file_size_in_byte":2108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258046471","text":"\"\"\" Message Type Definitions, organized by class\n\"\"\"\n\n\nclass UI:\n FAMILY = \"ui\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n STATE = BASE + \"state\"\n STATE_REQUEST = BASE + \"state_request\"\n INITIALIZE = BASE + \"initialize\"\n\nclass CONN_UI:\n FAMILY = \"connections_ui\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n SEND_INVITE = BASE + \"send_invite\"\n INVITE_SENT = BASE + \"invite_sent\"\n INVITE_RECEIVED = BASE + \"invite_received\"\n\n REQUEST_RECEIVED = BASE + \"request_received\"\n RESPONSE_RECEIVED = BASE + \"response_received\"\n MESSAGE_RECEIVED = BASE + \"message_received\"\n\n SEND_REQUEST = BASE + \"send_request\"\n REQUEST_SENT = BASE + \"request_sent\"\n\n SEND_RESPONSE = BASE + \"send_response\"\n RESPONSE_SENT = BASE + \"response_sent\"\n\n SEND_MESSAGE = BASE + \"send_message\"\n MESSAGE_SENT = BASE + \"message_sent\"\n\nclass ADMIN_WALLETCONNECTION:\n FAMILY = \"admin_walletconnection\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n CONNECT = BASE + \"connect\"\n DISCONNECT = BASE + \"disconnect\"\n USER_ERROR = BASE + \"user_error\"\n\nclass CONN:\n FAMILY = \"connections\"\n VERSION = \"1.0\"\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/\" + FAMILY + \"/\" + VERSION + \"/\"\n\n INVITE = BASE + \"invite\"\n REQUEST = BASE + \"request\"\n RESPONSE = BASE + \"response\"\n MESSAGE = BASE + \"message\"\n\n\nclass FORWARD:\n BASE = \"did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/routing/1.0/\"\n\n FORWARD_TO_KEY = BASE + \"forward_to_key\"\n FORWARD = BASE + \"forward\"\n","sub_path":"python/message_types.py","file_name":"message_types.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487315323","text":"from django.urls import path\nfrom . import views\n\napp_name='mysite'\nurlpatterns = [\n path('',views.reg),\n path('site',views.site),\n path('register/',views.Register,name='register'),\n path('login/',views.UserLogin,name='login'),\n path('logout/',views.UserLogout,name='login'),\n path('site2',views.st),\n path('site3',views.st2, name='new'),\n]\n\n","sub_path":"PRJ/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26958494","text":"# -*- coding: utf-8 -*-\nimport string\nimport time\nimport math\n\nfrom datetime import datetime\nfrom gensim.models import word2vec\nimport numpy as np\n\nimport torch\nfrom torch.autograd import Variable\nfrom model import Siamese_lstm\nimport torch.nn as nn\n\n\n# 输入:文件名\n# 输出:二维矩阵,每一行代表一个训练样本里的两个句子以及相似度\ndef load_data(filename):\n file = open(filename, 'r', encoding='utf-8')\n result = []\n for line in file:\n # 取第4列到第6列\n # 分别是 相似度 句子1 句子2\n temp = []\n li = line.split('\\t')[4:7]\n temp.append(float(li[0]))\n for sentence in [li[1], li[2]]:\n for punc in string.punctuation:\n sentence = sentence.replace(punc, ' ')\n sentence = sentence.replace(' ', ' ')\n sentence = sentence.strip().split(' ')\n\n temp.append(sentence)\n result.append(temp)\n\n return result\n\n\n# 构建词典\n# 输入是train和dev的数据\ndef get_word_dict(train_data, dev_data):\n word_set = set()\n dict = {}\n # cnt储存字的位置\n cnt = 0\n for data in [train_data, dev_data]:\n for v in data:\n # 句子1和句子2\n for s in [v[1], v[2]]:\n for word in s:\n if word not in word_set:\n word_set.add(word)\n dict[word] = cnt\n cnt += 1\n return dict\n\n\n# 获得表示成向量的词语\n# 输入为数据,字典,以及预训练的embedding模型\ndef get_word_vect(data,word_dict,model):\n result=[]\n # 获取词典长度,加1是为了存放不在词典中出现的单词\n dict_len=len(word_dict)+1\n word_set=set(word_dict.keys())\n\n # 每个词的初始向量\n vector = [0] * 101\n\n # 对每一行操作\n for v in data:\n temp=[]\n temp.append(v[0])\n for s in [v[1],v[2]]:\n # 每个句子表示为二维矩阵,行数是词的个数,列数是词表的大小\n sentence=[]\n for word in s:\n # vector_copy=vector.copy()\n # if word in word_set:\n # vector_copy[word_dict[word]]=1\n # else:\n # vector_copy[-1]=1\n if word in model:\n word_vec=np.append(model[word],0)\n sentence.append([word_vec])\n else:\n vector_copy=vector.copy()\n vector_copy[-1]=1\n sentence.append([vector_copy])\n temp.append(sentence)\n result.append(temp)\n # print(temp)\n return result\n\n\ndef timeSince(since):\n now = time.time()\n s = now - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\nif __name__ == '__main__':\n # ------------------数据处理---------------------------------------\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(\"Now using: \" + str(device))\n\n # 开始时间\n prerocess_start = time.time()\n\n train_data_raw = load_data('data/sts-train.txt')\n dev_data_raw = load_data('data/sts-dev.txt')\n\n word_dict = get_word_dict(train_data_raw, dev_data_raw)\n # dict_len = len(word_dict) + 1\n dict_len=101\n print(\"The length of the word_list is \" + str(dict_len))\n\n # 获取与训练好的模型\n model = word2vec.Word2Vec.load('word2vec_corpus/word2vec.model')\n train_data = get_word_vect(train_data_raw, word_dict,model)\n dev_data = get_word_vect(dev_data_raw, word_dict,model)\n\n print(\"Done preprocessing data, spent \" + timeSince(prerocess_start))\n # ---------------------以上是数据处理部分----------------------------\n\n # ---------------------模型参数--------------------------\n # 输入向量的特征维度\n embed_size = dict_len\n batch_size = 1\n # 隐藏层维度\n hidden_size = 128\n # 单层 LSTM\n num_layers = 1\n # dropout概率\n drop_out_prob = 0\n # 初始化模型\n siamese = Siamese_lstm(embed_size, batch_size, hidden_size, num_layers, drop_out_prob)\n siamese = siamese.to(device)\n # -----------以上是模型参数部分-----------------------\n\n # 学习率\n learning_rate = 0.1\n # 优化器(梯度更新)\n optimizer = torch.optim.Adadelta(filter(lambda x: x.requires_grad, siamese.parameters()), lr=learning_rate)\n # 损失函数\n criterion = nn.MSELoss()\n criterion = criterion.to(device)\n\n # 最好的一次损失\n best_loss = float('inf')\n\n # 迭代次数\n n_epoch = 80\n epoch = 1\n\n train_start_time = time.time()\n\n # 记录所有epoch的训练损失\n all_train_mean_loss=[]\n # 开始训练\n while epoch <= n_epoch:\n print('Start Epoch {} Training...'.format(epoch))\n\n epoch_start_time = time.time()\n\n # loss\n train_loss = []\n\n for idx, data in enumerate(train_data):\n # 获取数据\n original_score = torch.tensor(data[0], dtype=torch.float32).to(device)\n sentence_tensor1 = torch.tensor(data[1], dtype=torch.float32).to(device)\n sentence_tensor2 = torch.tensor(data[2], dtype=torch.float32).to(device)\n\n # 清除梯度\n optimizer.zero_grad()\n # 输出\n output = siamese(sentence_tensor1, sentence_tensor2)\n\n # 如果第0维的值为1则去掉该维度\n # output = output.squeeze(0)\n original_score = Variable(original_score)\n original_score.to(device)\n\n # 误差反向传播\n loss = criterion(output, original_score)\n loss.backward()\n\n # 更新梯度\n optimizer.step()\n train_loss.append(loss.data.cpu())\n print(\"Train this epoch spent: \" + timeSince(epoch_start_time))\n train_mean_loss=sum(train_loss)/len(train_loss)\n print('Epoch %d train mean loss: %f' % (epoch, train_mean_loss))\n all_train_mean_loss.append(train_mean_loss)\n if epoch>=10 and all_train_mean_loss[-1]>all_train_mean_loss[-2]:\n learning_rate=learning_rate/2\n print('!!!!!!!'+str(learning_rate))\n for param_group in optimizer.param_groups:\n param_group['lr'] = learning_rate\n\n # loss\n valid_loss = []\n valid_start_time = time.time()\n for idx, data in enumerate(dev_data):\n original_score = torch.tensor(data[0], dtype=torch.float).to(device)\n sentence_tensor1 = torch.tensor(data[1], dtype=torch.float).to(device)\n sentence_tensor2 = torch.tensor(data[2], dtype=torch.float).to(device)\n\n # input\n output = siamese(sentence_tensor1, sentence_tensor2)\n # output = output.squeeze(0)\n\n original_score = Variable(original_score)\n original_score.to(device)\n\n # loss\n loss = criterion(output, original_score)\n valid_loss.append(loss.data.cpu())\n print(\"Eval this epoch spent: \" + timeSince(valid_start_time))\n print('Epoch %d valid mean loss: %f' % (epoch, sum(valid_loss) / len(valid_loss)))\n\n # 查看与最好的loss的差距\n if np.mean(valid_loss) < best_loss:\n best_loss = np.mean(valid_loss)\n torch.save(siamese.state_dict(), \"lstm_params_with_word_embedding.pkl\")\n # save the best model\n print(\"Epoch %d spent %s\" % (epoch, timeSince(epoch_start_time)))\n epoch += 1\n\n print(\"Train spent \" + timeSince(train_start_time))\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32336855","text":"\nimport igraph\nfrom lnfa import lognormdd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pylab import *\nimport pickle\nimport random as r\nimport math\nfrom binsearch import binsearch\n\n\n\nm=2; mu=0; sigma=1.; alpha=10.; nodes=1000; \n\ncn = [1,1]; ft=[]; fit =[];\ng = [[1],[0]];\ngraph = igraph.Graph()\ngraph.add_vertices(2)\ngraph.add_edges([(0,1)])\nft.append((r.lognormvariate(mu,sigma))**alpha); Fit = ft[0]; fit.append(Fit)\nft.append((r.lognormvariate(mu,sigma))**alpha); Fit += ft[1]; fit.append(Fit)\n\nfor j in range(2,nodes):\n g.append([]); cn.append(m);\n graph.add_vertices(1)\n for i in range(m):\n prob=r.uniform(0,Fit); n = binsearch(prob, fit, j);\n cn[n] += 1;\n g[n].append(j);\n g[j].append(n);\n graph.add_edges([(n,j)])\n ft.append((r.lognormvariate(mu,sigma))**alpha); Fit += ft[j]; fit.append(Fit)\n\nigraph.plot(graph, 'a10.pdf', layout=\"fr\", vertex_label=None,vertex_color=\"blue\", vertex_size=7, edge_width=.1, edge_color=\"gray\")\nigraph.plot(graph, 'a10B.pdf', layout=\"kk\", vertex_label=None, vertex_size=8, edge_width=.1)\n\n\nigraph.plot(graph, layout=\"fr\", vertex_label=None, vertex_size=5, edge_width=.3)\nigraph.plot(graph, layout=\"fr\", vertex_label=None, vertex_size=4, edge_width=.2)\n\n\n","sub_path":"Nonlinear/chigraphlnfa.py","file_name":"chigraphlnfa.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196776439","text":"def alert_build(alert:dict):\n try:\n ts = alert['timestamp'].split('T')\n date = ts[0]\n time = ts[1].split('.')[0]\n\n if 'src_port' in alert.keys():\n src = \"{}:{}\".format(alert['src_ip'],alert['src_port'])\n else:\n src = alert['src_ip']\n if 'dest_port' in alert.keys():\n dst = \"{}:{}\".format(alert['dest_ip'],alert['dest_port'])\n else:\n dst = alert['dest_ip']\n except KeyError:\n return None\n\n return {'time':'{} {}'.format(date,time),\n 'src_dst':'{} -> {}'.format(src,dst),\n 'proto':alert['proto'],\n 'action':alert['alert']['action'],\n 'message':alert['alert']['signature']}\n","sub_path":"backend/sccontrol_helper/alert/alert.py","file_name":"alert.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430186444","text":"#Ejercicio 7\n#Creá un programa que declare una lista y la vaya llenando de números leídos por teclado hasta \n#que se introduzca un número negativo. Una vez hecho esto se deben imprimir los elementos de la lista.\n\nlista = []\nnumero = int(input(\"Introduce un número en la lista:\"))\nwhile numero>=0:\n\tlista.append(numero)\n\tnumero = int(input(\"Introduce un número en la lista:\"))\n\nfor numero in lista:\n\tprint(numero,\" \",end=\"\")\n\n","sub_path":"TP2.py/2.7.py","file_name":"2.7.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438359171","text":"from __future__ import print_function\nimport sys\n\ndef compress(seq):\n\n\tseq = seq.split()\n\tseq.reverse()\n\tresult = []\n\twhile seq:\n\t\tcurrent = seq.pop()\n\t\tcount = 1\n\t\t\n\t\twhile seq and (current == seq[-1]):\n\t\t\tcurrent = seq.pop()\n\t\t\tcount += 1\n\t\tresult.extend([str(count), current])\n\t\n\tfor val in result:\n\t\tprint(val, end=\" \")\n\tprint()\n\n\nwith open(sys.argv[1], 'r') as f:\n\n\tfor line in f:\n\t\tif line:\n\t\t\tline.rstrip()\n\t\t\tcompress(line)","sub_path":"codeeval/easy/128_compressed_sequence/compressedsequence.py","file_name":"compressedsequence.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48875550","text":"# Libraries\r\nimport functions as fun\r\nimport numpy as np\r\nfrom constants import earth_radius, irradiance, mie_coeff, num_wavelengths, ozone_coeff, rayleigh_coeff\r\nfrom math import cos, exp, pi, radians, sin, sqrt, dist\r\nfrom properties import air_density, altitude, dust_density, ozone_density, steps, steps_light, sun_lat\r\n\r\n\r\n# Definitions\r\n# convert altitude from km to m and clamp to avoid intersection issues\r\ncam_altitude = 1000 * max(min(altitude, 59.999), 0.001)\r\ncam_pos = np.array([0, 0, earth_radius + cam_altitude])\r\n# convert sun latitude and longitude to vector\r\nsun_dir = fun.geographical_to_direction(radians(sun_lat), 0)\r\ncoefficients = np.array(\r\n [rayleigh_coeff, 1.11 * mie_coeff, ozone_coeff], dtype=np.object)\r\ndensity_multipliers = np.array([air_density, dust_density, ozone_density])\r\n\r\n\r\ndef ray_optical_depth(ray_origin, ray_dir):\r\n # optical depth along a ray through the atmosphere\r\n ray_end = fun.atmosphere_intersection(ray_origin, ray_dir)\r\n ray_length = dist(ray_origin, ray_end)\r\n # step along the ray in segments and accumulate the optical depth along each segment\r\n segment_length = ray_length / steps_light\r\n segment = segment_length * ray_dir\r\n optical_depth = np.zeros(3)\r\n # the density of each segment is evaluated at its middle\r\n P = ray_origin + 0.5 * segment\r\n\r\n for _ in range(steps_light):\r\n # height above sea level\r\n height = sqrt(np.dot(P, P)) - earth_radius\r\n # accumulate optical depth of this segment\r\n density = np.array([fun.density_rayleigh(\r\n height), fun.density_mie(height), fun.density_ozone(height)])\r\n optical_depth += density\r\n # advance along ray\r\n P += segment\r\n\r\n return optical_depth * segment_length\r\n\r\n\r\ndef single_scattering(ray_dir):\r\n # intersection between camera and top of atmosphere\r\n ray_end = fun.atmosphere_intersection(cam_pos, ray_dir)\r\n # distance from camera to top of atmosphere\r\n ray_length = dist(cam_pos, ray_end)\r\n # to compute the inscattering, we step along the ray in segments and\r\n # accumulate the inscattering as well as the optical depth along each segment\r\n segment_length = ray_length / steps\r\n segment = segment_length * ray_dir\r\n optical_depth = np.zeros(3)\r\n spectrum = np.zeros(num_wavelengths)\r\n # cosine of angle between camera and sun\r\n mu = np.dot(ray_dir, sun_dir)\r\n # phase functions (sr^-1)\r\n phase_function_R = fun.phase_rayleigh(mu)\r\n phase_function_M = fun.phase_mie(mu)\r\n # the density and in-scattering of each segment is evaluated at its middle\r\n P = cam_pos + 0.5 * segment\r\n\r\n for _ in range(steps):\r\n # height above sea level\r\n height = sqrt(np.dot(P, P)) - earth_radius\r\n # evaluate and accumulate optical depth along the ray\r\n densities = np.array([fun.density_rayleigh(\r\n height), fun.density_mie(height), fun.density_ozone(height)])\r\n density = density_multipliers * densities\r\n optical_depth += density * segment_length\r\n\r\n # if the Earth isn't in the way, evaluate inscattering from the sun\r\n if not fun.surface_intersection(P, sun_dir):\r\n optical_depth_light = ray_optical_depth(P, sun_dir)\r\n # attenuation of light\r\n extinction_density = (\r\n optical_depth + density_multipliers * optical_depth_light) * coefficients\r\n attenuation = np.exp(-np.sum(extinction_density))\r\n scattering_density_R = density[0] * rayleigh_coeff\r\n scattering_density_M = density[1] * mie_coeff\r\n # compute spectrum\r\n spectrum += attenuation * \\\r\n (phase_function_R * scattering_density_R +\r\n phase_function_M * scattering_density_M)\r\n\r\n # advance along ray\r\n P += segment\r\n\r\n # spectrum at pixel in radiance (W*m^-2*nm^-1*sr^-1)\r\n return irradiance * spectrum * segment_length\r\n","sub_path":"light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"459234488","text":"import os\nimport datetime\n\ndef get_dates (): # Leave blank to select the current day or alter the dict to pick a date\n\tyear = str(datetime.datetime.now().year)\n\tmonth = str(datetime.datetime.now().month)\n\tday = str(datetime.datetime.now().day)\n\tday_of_year = datetime.datetime.now().timetuple().tm_yday\n\tdoy = str(day_of_year - 0) # set this to go back x number of days \n\t\t\n\tdate= {\n\t\"year\" : year,\n\t\"month\": month,\n\t\"day\" : day,\n\t\"doy\" : doy}\n\t\t\t\n\treturn date\n\ndates = get_dates()\n\t\nyears = [x for x in range(2000,2016)] # Does not look for 2016 data\n\nfor year in years:\n\tcommand = '''python3 fetch_historic.py Q1 {} {} Terra'''.format(str(year),dates['doy'])\n\tprint(command)\n\tos.system(command)\n\t\naqua_years = years[3:] # does not look for 2002 historic data \n\nfor year in aqua_years:\n\tcommand = '''python3 fetch_historic.py Q1 {} {} Aqua'''.format(str(year),dates['doy'])\n\tprint(command)\n\tos.system(command)\n","sub_path":"call_historic.py","file_name":"call_historic.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462334758","text":"# encoding:UTF-8\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('gbk')\n\nimport numpy as np\nfrom numpy.linalg import cholesky\nimport matplotlib.pyplot as plt\nimport pylab\n\n# 直方图\nsampleNo = 1000;\nmu = 85\nsigma = 4\nnp.random.seed(0)\ns = np.random.normal(mu, sigma, sampleNo)\nplt.hist(s, 30, normed=True)\npylab.show()\n\n# 线性图\nx = np.arange(1, 11)\ny = 2 * x + 5\nplt.title(\"Matplotlib demo\")\nplt.xlabel(\"x axis caption\")\nplt.ylabel(\"y axis caption\")\nplt.plot(x, y, 'vb')\nplt.show()\n\nx = np.arange(0, 3 * np.pi, 0.1)\nprint(x)\ny = np.sin(x)\nplt.title(\"sine wave form\")\n# 使用 matplotlib 来绘制点\nplt.plot(x, y)\nplt.show()\n\n# 计算正弦和余弦曲线上的点的 x 和 y 坐标\nx = np.arange(0, 3 * np.pi, 0.1)\ny_sin = np.sin(x)\ny_cos = np.cos(x)\n# 建立 subplot 网格,高为 2,宽为 1\n# 激活第一个 subplot\nplt.subplot(2, 1, 1)\n# 绘制第一个图像\nplt.plot(x, y_sin)\nplt.title('Sine')\n# 将第二个 subplot 激活,并绘制第二个图像\nplt.subplot(2, 1, 2)\nplt.plot(x, y_cos)\nplt.title('Cosine')\n# 展示图像\nplt.show()\n","sub_path":"PythonBase/data_visual/numpy/matplot.py","file_name":"matplot.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536929175","text":"# -*- coding: utf-8 -*-\n\"\"\"Project metadata\n\nInformation describing the project.\n\"\"\"\n\n# The package name, which is also the \"UNIX name\" for the project.\npackage = 'doorpi'\nprog = 'DoorPi'\nproject = \"VoIP Door-Intercomstation with Raspberry Pi\"\nproject_no_spaces = project.replace(' ', '')\nversion = '2.3 #231'\ndescription = 'provide intercomstation to the doorstation by VoIP'\n\nauthors = ['Thomas Meissner']\nauthors_emails = ['motom001@gmail.com']\nauthors_string = ', '.join(authors)\nauthor_strings = []\nfor name, email in zip(authors, authors_emails):\n author_strings.append('{0} <{1}>'.format(name, email))\n\nsupporters = [\n 'Phillip Munz ',\n 'Hermann Dötsch ',\n 'Dennis Häußler ',\n 'Hubert Nusser ',\n 'Michael Hauer ',\n 'missing someone? -> sorry -> mail me'\n]\nsupporter_string = '\\n'.join(supporters)\n\nlicense = 'CC BY-NC 4.0, 2014-2015'\nurl = 'https://github.com/motom001/DoorPi'\nURL_DOORPI_WIKI = url+\"/wiki\"\n\n# created with: http://patorjk.com/software/taag/#p=display&f=Ogre&t=DoorPi\nepilog = '''\n ___ ___ _\n / \\___ ___ _ __ / _ (_) {project}\n / /\\ / _ \\ / _ \\| '__/ /_)/ | version: {version}\n / /_// (_) | (_) | | / ___/| | license: {license}\n/___,' \\___/ \\___/|_| \\/ |_| URL: <{url}>\n\nAuthors: {authors}\nSupporter: {supporters}\n'''.format(\n license = license,\n project = project,\n version = version,\n authors = '\\n'.join(author_strings),\n supporters = '\\n '.join(supporters),\n url = url)\n\n\n","sub_path":"doorpi/resources/metadata/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442169658","text":"#!/opt/anaconda2/bin/python\n\nimport argparse\nimport random\n\nfrom gh_crawler import get_url\nfrom utils.config import get_config\nfrom utils.issuecollector3 import IssueCollector3\nfrom utils.mongo_tools import MongoTools\n\n\nclient,db = MongoTools.get_db()\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--cachedir\", type=str, default='/var/cache/github_dashboard')\nparser.add_argument(\"--start\", type=int)\nargs = parser.parse_args()\n\nconfig = get_config()\nIC = IssueCollector3(args)\nIC.list_issues()\nkeys = IC.get_all_issue_indexes()\n\nif args.start:\n keep = []\n for k in keys:\n number = k.split('/')[-1]\n number = int(number)\n if number >= args.start:\n keep.append(k)\n keys = keep\n\nissues = db.api_issues\nissue_ids = MongoTools.get_data_ids('issues', key='html_url')\npullrequests = db.api_pullrequests\npull_ids = MongoTools.get_data_ids('pullrequests', key='html_url')\ncomment_ids = MongoTools.get_data_ids('comments')\nevent_ids = MongoTools.get_data_ids('events')\nreaction_ids = MongoTools.get_data_ids('reactions')\n\ntotal = len(keys)\nfor idx,key in enumerate(keys):\n #print(key)\n\n ix = IC.index[key]\n raw = IC.get_issue_rawdata_by_key(key)\n\n for x in ['comments', 'events', 'reactions']:\n if not raw[x]:\n continue\n\n missing = []\n for y in raw[x]:\n\n if x == 'comments':\n if y['id'] not in comment_ids:\n missing.append(y)\n\n elif x == 'events':\n if y['id'] not in event_ids:\n missing.append(y)\n\n elif x == 'reactions':\n if y['id'] not in reaction_ids:\n missing.append(y)\n\n if missing:\n print('%s|%s %s' % (idx,total,key))\n res = MongoTools.insert_many_by_type(missing, dtype=x)\n #import epdb; epdb.st()\n\n url = raw['issue']['html_url']\n if url not in issue_ids:\n print('insert issue %s' % url)\n issues.insert_one(raw['issue'])\n elif raw['issue']['updated_at'] != issue_ids[url]:\n # need to udate in place\n issues.replace_one(\n {'html_url': url},\n raw['issue']\n )\n\n if raw['pullrequest']:\n if url not in pull_ids:\n print('insert pull %s' % url)\n pullrequests.insert_one(raw['pullrequest'])\n elif raw['pullrequest']['updated_at'] != pull_ids[url]:\n # need to udate in place\n pullrequests.replace_one(\n {'html_url': url},\n raw['pullrequest']\n )\n\n#import epdb; epdb.st()\nclient.close()\n","sub_path":"sync_mongo_data.py","file_name":"sync_mongo_data.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"438468970","text":"import numpy as np\nimport cv2 as cv\nimport Distance\n\nimage = cv.imread(\"OtherImgs\\goodFrame1.png\")\n\nDistance.setDegPx(image)\ndist, ang, cent, cont = Distance.distanceToGoal(image)\n\ncv.circle(image, cent, 20, (0, 0, 255), 5)\ncv.drawContours(image, cont, 0, (255, 0, 0), 3)\n\ncv.line(image, (int(image.shape[1]/2), 0), (int(image.shape[1]/2), image.shape[0]), (0, 0, 255), 3, lineType=4)\n\ncv.putText(image, \"0.00deg\", (5, 32), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3, 8)\ncv.putText(image, \"0.00ft\", (5, 64), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 3, 8)\ncv.putText(image, \"[MISS]\", (5, 96), cv.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 3, 8)\n\ncv.imshow(\"R-RAAS\", image)\ncv.waitKey(0)\ncv.destroyAllWindows()","sub_path":"ReadOutTest.py","file_name":"ReadOutTest.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"259693363","text":"from numbers import *\nfrom math import *\nimport copy\n\nmd = [[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]],\n [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -1]],\n [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]]]\n\n\nclass quat:\n # builder\n def __init__(self, a=0, b=0, c=0, d=0):\n self.q = [float(a), float(b), float(c), float(d)]\n\n # quaternion as string or for printing\n def __str__(self):\n a = ''\n lab = ['i', 'j', 'k']\n a = str(self.q[0])\n if self.q[1] >= 0:\n a = a + '+'\n for i in range(1, 3):\n if self.q[i + 1] < 0:\n a = a + str(self.q[i]) + lab[i - 1]\n elif self.q[i + 1] >= 0:\n a = a + str(self.q[i]) + lab[i - 1] + '+'\n\n a = a + str(self.q[3]) + lab[2]\n return a\n\n # addition of quaternions\n def __add__(self, ob2):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] + ob2.q[i]\n return s\n # subtraction of quaternions\n\n def __sub__(self, ob2):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] - ob2.q[i]\n return s\n\n # devuleve el negativo de un cuaterion\n def __neg__(self):\n s = quat()\n for i in range(4):\n s.q[i] = - self.q[i]\n return s\n\n # quaternion product (in R3 cross product)\n def __mul__(self, ob2):\n s = quat(0, 0, 0, 0)\n # matrices and vector used in quaternion product (not math just for the index of the quaternion\n or1 = [0, 1, 2, 3]\n or2 = [1, 0, 3, 2]\n\n v = [[1, -1, -1, -1], [1, 1, 1, -1], [1, -1, 1, 1], [1, 1, -1, 1]]\n m = [or1, or2, [i for i in reversed(or2)], [i for i in reversed(or1)]]\n for k in range(4):\n a = 0\n for i in range(4):\n # just for debugging print self.q[m[0][i]]\n # print ob2.q[m[k][i]]\n a = a + (self.q[m[0][i]]) * (float(v[k][i]) * ob2.q[m[k][i]])\n s.q[k] = a\n return s\n\n # product by scalar\n def __rmul__(self, ob):\n s = quat()\n for i in range(4):\n s.q[i] = self.q[i] * ob\n return s\n\n # division of quaternions, quat/quat\n def __div__(self, ob):\n s = quat()\n b = copy.deepcopy(ob)\n ob.C()\n c = (b * ob).q[0]\n s = (self * ob)\n a = (1 / c) * s\n ob.C()\n return a\n\n # norm of a quaternion returns an scalar\n def norm(self):\n s = 0\n for i in range(4):\n s = s + self.q[i] ** 2\n return float(s ** (0.5))\n\n # conjugates a quaternion a: a.C() -> a=a+bi+cj+dk --> a.C()=a-bi-cj-dk\n def C(self):\n s = self\n for i in range(1, 4):\n s.q[i] = s.q[i] * (-1)\n return s\n\n # devuelve el conjugado (no cambia el cuaternion)\n def conj(self):\n s = self\n t = quat(s.q[0], 0, 0, 0)\n for i in range(1, 4):\n t.q[i] = s.q[i] * (-1)\n return t\n\n # method used to create a rotation quaternion to rotate any vector defined as a quaternion\n # with respect to the vector vect theta 'radians'\n def rotQuat(self, theta, vect):\n self.q = [cos(theta / 2.0), vect[0] * sin(theta / 2.0), vect[1] * sin(theta / 2.0),\n vect[2] * sin(theta / 2.0)]\n\n # devuelve la parte real del cuaternion\n def real(self):\n return self.q[0]\n\n # devuelve la parte imaginario\n def ima(self):\n return quat(0, self.q[1], self.q[2], self.q[3])\n\n # devuelve la coordenada i\n def qi(self):\n return self.q[1]\n\n # devuelve la coordenada j\n def qj(self):\n return self.q[2]\n\n # devuelve la coordenada i\n def qk(self):\n return self.q[3]\n\n # Devuleve por coordena\n def __getitem__(self, i):\n return self.q[i]\n\n\n# rotates a vector or a vector defined as a quaternion 0+xi+yj+zk with respect to a quaternion\n\ndef rotate(vect, quatern):\n if \"list\" in str(type(vect)):\n a = quat()\n for i in range(3):\n a.q[i + 1] = vect[i]\n vect = a\n rotq = (quatern * vect) / quatern\n ret = [rotq.q[0], rotq.q[1], rotq.q[2], rotq.q[3]] # original\n return ret\n\n\n# rotates a vector or a vector defined as a quaternion 0+xi+yj+zk with respect to a quaternion\n# lo modifique, no devuleve un cuaternion sino un vector [x,y,z]\ndef rotateV(vect, quatern):\n if \"list\" in str(type(vect)):\n a = quat()\n for i in range(3):\n a.q[i + 1] = vect[i]\n vect = a\n rotq = (quatern * vect) / quatern\n ret = [rotq.q[1], rotq.q[2], rotq.q[3]] # original\n return ret\n\n\n# rotates a vector v_to_rotate theta 'radians' with respect to v_about, both are vectors\n# but it uses quaternions\ndef rotateH(v_to_rotate, theta, v_about):\n a = quat(0, v_to_rotate[0], v_to_rotate[1], v_to_rotate[2])\n b = quat(cos(theta / 2), v_about[0] * sin(theta / 2), v_about[1] * sin(theta / 2), v_about[2] * sin(theta / 2))\n v_rotated = [0, 0, 0]\n vq = rotate(a, b)\n for i in range(4):\n if i < 3:\n v_rotated[i] = vq.q[i + 1]\n return v_rotated\n\n\n# metric tensor defaul basis [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]\n# fe. for Minkowski use [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,-1]]\n# q1T[basis]q2\n# for R3 MT(A,B,[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]])\n\ndef MT(q1, q2, basis=[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]):\n a = [0, 0, 0, 0]\n s = 0\n for i in range(4):\n for j in range(4):\n a[i] = a[i] + q2.q[j] * basis[i][j]\n for i in range(4):\n s = s + q1.q[i] * a[i]\n return s\n\n\ndef quat_to_rotMat(q):\n rm = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n for i in range(3):\n rm[i][i] = MT(q, q, md[i])\n rm[0][1] = 2 * (q.q[1] * q.q[2] - q.q[0] * q.q[3])\n rm[0][2] = 2 * (q.q[1] * q.q[3] + q.q[0] * q.q[2])\n rm[1][0] = 2 * (q.q[1] * q.q[2] + q.q[0] * q.q[3])\n rm[1][2] = 2 * (q.q[2] * q.q[3] - q.q[0] * q.q[1])\n rm[2][0] = 2 * (q.q[1] * q.q[3] - q.q[0] * q.q[2])\n rm[2][1] = 2 * (q.q[3] * q.q[2] + q.q[0] * q.q[1])\n return rm\n\n\ndef norm2(q):\n s = 0\n for i in range(4):\n s = s + q.q[i] ** 2\n return s\n\n\n\"\"\"\nPI = 3.14159265\nv0 = quat()\nv0.rotQuat(PI/3,[0,0,1]) #vector para rotar pi/3 (60 grados) en respecto al eje z\nv1 = copy.deepcopy(v0)\nv1.C()\n#print v0*v1\n\nrot_e1 = rotate([1,0,0],v0) # rotar e_1 60 grados alrededor de z\nrot_e2 = rotate([0,1,0],v0) # rotar e_2 60 grados alrededor de z\n#print rot_e1\nq0 = quat(-0.579, 0.330, -0.276, 0.692)\ninvq0 = quat(-0.579, -0.330, 0.276, -0.692)\n\nq1 = quat(-0.666, 0.038, -0.489, 0.562)\ninvq1 = quat(-0.666, -0.038, 0.489, -0.562)\n\nq3 = invq0*q1\nq4 = q1*invq0\nq5 = q0*invq1\nprint q3\nprint q4\nprint q5 #parece que esto es\n\nrot_e1 = rotate([1,0,0],q5) \nrot_e2 = rotate([0,1,0],q5) \nrot_e3 = rotate([0,0,1],q5) \nprint rot_e1 \nprint rot_e2\nprint rot_e3\nprint sqrt(3)/2\nprint sqrt(2)/2\nprint 2*acos(0.922022)\n\n\nu = [1,2,3]\nI =quat(1,0,0,0)\nq1 = quat(sqrt(2)/2, sqrt(2)/2, 0.0,0.0)\nq2 = quat(sqrt(2)/2, 0.0, -sqrt(2)/2, 0.0)\nq = q2*q1\nq0 = I/q\n\nv1 = rotateV(u,q0)\n\nprint v1\nq = quat(sqrt(2)/2, 0.0, 0.0,sqrt(2)/2)\nprint rotate([1,0,0],q)\n\nqxz = quat(sqrt(2)/2,0,sqrt(2)/2,0)\nqyz = quat(sqrt(2)/2,sqrt(2)/2,0,0)\nqxy = quat(sqrt(2)/2,0,0,sqrt(2)/2)\nqxyyz = qxy * qyz\nqxyxz = qxy * qyz\nq5 = qxz\nrot_e1 = rotate([1,0,0],q5) \nrot_e2 = rotate([0,1,0],q5) \nrot_e3 = rotate([0,0,1],q5) \nprint rot_e1 \nprint rot_e2\nprint rot_e3\n\"\"\"\n","sub_path":"quaternion_lib.py","file_name":"quaternion_lib.py","file_ext":"py","file_size_in_byte":7513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"629138816","text":"import json\nfrom .log import print_log\nimport os\n\n\nclass Update_File():\n\n def update_file(self):\n pass\n try:\n file_path = \"/data/stats/\"\n file_list = os.listdir(file_path)\n tmp_today = {}\n for file_name in file_list:\n f = open(file_path+file_name, \"r\")\n line = f.read()\n line_dict = json.loads(line)\n tmp_today.update(line_dict)\n zero = [0, 0, 0]\n for key in tmp_today:\n tmp_today[key] = zero\n f.close()\n f = open(file_path+file_name, \"w\")\n f.write(json.dumps(tmp_today))\n f.close()\n print_log(\"info\",\"%s has been updated\"%file_name)\n except Exception as e:\n print_log(\"error\",\"%s update failed, because %s\"%(file_name,str(e)))\n\n try:\n os.system(\"sudo rm /usr/local/lib/python3.8/dist-packages/VESA-3.8-project/nohup.out\")\n print_log(\"info\",\"nohup.out has been deleted\")\n except Exception as e:\n print_log(\"error\",\"nohuo.out delete failed, because %s\"%str(e))\n \n def action(self):\n self.update_file()\n\n def add_file(self):\n try:\n file_path = \"/data/stats/\"\n file_list = os.listdir(file_path)\n file_list.remove(\"daily_stats.txt\")\n tmp_today = {}\n for file_name in file_list:\n f = open(file_path + file_name, \"r\")\n line = f.read()\n line_dict = json.loads(line)\n tmp_today.update(line_dict)\n f.close()\n f = open(\"/data/stats/daily_stats.txt\", \"w\")\n f.write(json.dumps(tmp_today))\n f.close()\n print_log(\"info\", \"daily_stats.txt has been updated\")\n except Exception as e:\n print_log(\"error\", \"daily_stats.txt update failed, because %s\" % str(e))\n\n\n","sub_path":"common/update_stats_file.py","file_name":"update_stats_file.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"629456753","text":"from config.config import connection_string\nfrom datetime import datetime, timedelta\nfrom actions.invoice_status import get_state_type_uuid\nimport pandas.io.sql as psql\nimport psycopg2 as pg\n\nconnection = pg.connect(connection_string())\ncursor = connection.cursor()\n\ndef handle(**kwarg):\n csv_id = kwarg[\"csv\"]\n invoices_to_change = kwarg[\"affects\"]\n limit_phrase = \";\" if invoices_to_change == \"*\" else f\" LIMIT {invoices_to_change};\"\n\n # grab invoices on this csv with status of 'Billed'.\n cursor.execute(f\"\"\"SELECT I.\"InvoiceId\"\n FROM \"InvoiceBatch\" IB\n LEFT JOIN \"InvoiceBatchMapping\" IBM ON IBM.\"InvoiceBatchId\" = IB.\"InvoiceBatchId\" AND IB.\"CsvId\" = '{csv_id}'\n LEFT JOIN \"Invoice\" I on IBM.\"InvoiceId\" = I.\"InvoiceId\"\n LEFT JOIN \"InvoiceState\" IT ON I.\"InvoiceId\" = IT.\"InvoiceId\"\n LEFT JOIN \"InvoiceStateType\" IST ON IST.\"InvoiceStateTypeId\" = IT.\"InvoiceStateTypeId\"\n WHERE \"InvoiceStateTypeDesc\" = 'Billed'{limit_phrase}\"\"\")\n update_candidates = cursor.fetchall()\n print(f\"{len(update_candidates)} invoices to be updated.\")\n\n count = 0\n for each in update_candidates:\n # update the invoice meta data column to be:\n # InvoiceDate (\"MM/DD/YYYY\") 15 days prior to today \n # DueDate (\"MM/DD/YYYY\") today\n invoice_id = each[0]\n fifteen_days_ago = datetime.now() - timedelta(15)\n invoice_date = f\"{fifteen_days_ago.month}/{fifteen_days_ago.day}/{fifteen_days_ago.year}\"\n due_date = f\"{datetime.now().month}/{datetime.now().day}/{datetime.now().year}\"\n\n cursor.execute(f\"\"\"UPDATE \"Invoice\" SET \"InvoiceMetadata\" = \"InvoiceMetadata\" || '{{\"InvoiceDate\": \"{invoice_date}\"}}' WHERE \"InvoiceId\" = '{invoice_id}';\"\"\", connection)\n cursor.execute(f\"\"\"UPDATE \"Invoice\" SET \"InvoiceMetadata\" = \"InvoiceMetadata\" || '{{\"DueDate\": \"{due_date}\"}}' WHERE \"InvoiceId\" = '{invoice_id}';\"\"\", connection)\n count += 1\n\n connection.commit()\n connection.close()\n print(f\"\"\"{count} out of {len(update_candidates)} invoices updated.\"\"\")","sub_path":"actions/bill_charge_date.py","file_name":"bill_charge_date.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352612795","text":"\"\"\"\nWrite a Python program that outputs all possible strings formed by using thecharacters c , a , t , d , o ,\nand g exactly once.\n\"\"\"\n\n\ndef f1(iter1, iter2):\n return [[x] + list(iter2) for x in iter1]\n\n\ndef f2():\n characters = {\"c\", \"a\", \"t\", \"d\", \"o\", \"g\"}\n result = [[x] for x in characters]\n new_result = []\n n = 1\n\n while n < len(characters):\n for item in result:\n remainder = characters - set(item)\n new_result += f1(remainder, item)\n result = new_result\n new_result = []\n n = len(result[0])\n return result\n\n\nif __name__ == \"__main__\":\n output = f2()\n assert len(output) == 6 * 5 * 4 * 3 * 2 * 1\n","sub_path":"DSAP/ch01/p_1_29.py","file_name":"p_1_29.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396863896","text":"import pytest\n\nfrom otx.mpa import Stage\nfrom otx.mpa.cls.stage import ClsStage\nfrom tests.test_suite.e2e_test_system import e2e_pytest_unit\nfrom tests.unit.algorithms.classification.test_helper import setup_mpa_task_parameters\n\n\nclass TestOTXClsStage:\n @pytest.fixture(autouse=True)\n def setup(self) -> None:\n self.model_cfg, self.data_cfg, recipie_cfg = setup_mpa_task_parameters(\n task_type=\"incremental\", create_test=True, create_val=True\n )\n self.stage = ClsStage(name=\"\", mode=\"train\", config=recipie_cfg, common_cfg=None, index=0)\n\n @e2e_pytest_unit\n def test_configure(self, mocker):\n mock_cfg_model = mocker.patch.object(ClsStage, \"configure_model\")\n mock_cfg_ckpt = mocker.patch.object(ClsStage, \"configure_ckpt\")\n mock_cfg_data = mocker.patch.object(ClsStage, \"configure_data\")\n mock_cfg_task = mocker.patch.object(ClsStage, \"configure_task\")\n\n fake_arg = {\"pretrained\": True, \"foo\": \"bar\"}\n returned_value = self.stage.configure(self.model_cfg, \"\", self.data_cfg, True, **fake_arg)\n mock_cfg_model.assert_called_once_with(self.stage.cfg, self.model_cfg, True, **fake_arg)\n mock_cfg_ckpt.assert_called_once_with(self.stage.cfg, \"\", fake_arg.get(\"pretrained\", None))\n mock_cfg_data.assert_called_once_with(self.stage.cfg, self.data_cfg, True, **fake_arg)\n mock_cfg_task.assert_called_once_with(self.stage.cfg, True, **fake_arg)\n\n assert returned_value == self.stage.cfg\n\n @e2e_pytest_unit\n def test_configure_model(self):\n fake_arg = {\"ir_model_path\": {\"ir_weight_path\": \"\", \"ir_weight_init\": \"\"}}\n self.stage.configure_model(self.stage.cfg, self.model_cfg, True, **fake_arg)\n\n assert self.stage.cfg.model_task\n\n @e2e_pytest_unit\n def test_configure_data(self, mocker):\n mock_super_cfg_data = mocker.patch.object(Stage, \"configure_data\")\n self.stage.configure_data(self.stage.cfg, self.data_cfg, True, pretrained=None)\n\n mock_super_cfg_data.assert_called_once()\n assert self.stage.cfg.data\n assert self.stage.cfg.data.train\n assert self.stage.cfg.data.val\n\n @e2e_pytest_unit\n def test_configure_task(self, mocker):\n mock_cfg_classes = mocker.patch.object(ClsStage, \"configure_classes\")\n self.stage.configure_task(self.stage.cfg, True)\n\n mock_cfg_classes.assert_called_once()\n\n @e2e_pytest_unit\n def test_configure_classes(self, mocker):\n mocker.patch.object(Stage, \"get_model_classes\", return_value=[\"foo\", \"bar\"])\n mocker.patch.object(Stage, \"get_data_cfg\", return_value=self.data_cfg)\n self.stage.configure_classes(self.stage.cfg)\n\n assert self.stage.model_classes == [\"foo\", \"bar\"]\n\n @e2e_pytest_unit\n def test_configure_configure_topk(self):\n self.stage.cfg.model.head.num_classes = 2\n self.stage.configure_topk(self.stage.cfg)\n\n assert self.stage.cfg.model.head.topk == (1,)\n","sub_path":"tests/unit/mpa/cls/test_cls_stage.py","file_name":"test_cls_stage.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588291108","text":"from rlkit.envs.multitask.multitask_env import MultitaskToFlatEnv\nfrom rlkit.envs.multitask.point2d import MultitaskPoint2DEnv\nfrom rlkit.envs.mujoco.pusher2d import Pusher2DEnv\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nfrom rlkit.exploration_strategies.base import (\n PolicyWrappedWithExplorationStrategy\n)\nfrom rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\nfrom rlkit.exploration_strategies.gaussian_strategy import GaussianStrategy\nfrom rlkit.exploration_strategies.ou_strategy import OUStrategy\nfrom rlkit.launchers.launcher_util import run_experiment\nfrom rlkit.torch.networks import (\n ConcatMlp, TanhMlpPolicy, ImageStatePolicy, ImageStateQ,\n MergedCNN, CNNPolicy,\n)\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.torch.td3.td3 import TD3\nimport rlkit.misc.hyperparameter as hyp\nfrom rlkit.launchers.arglauncher import run_variants\n\nfrom multiworld.core.gym_to_multi_env import GymToMultiEnv\nfrom multiworld.core.image_env import ImageEnv\n\nimport gym\nimport torch\n\ndef her_td3_experiment(variant):\n import multiworld.envs.mujoco\n import multiworld.envs.pygame\n import rlkit.samplers.rollout_functions as rf\n import rlkit.torch.pytorch_util as ptu\n from rlkit.exploration_strategies.base import (\n PolicyWrappedWithExplorationStrategy\n )\n from rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy\n from rlkit.exploration_strategies.gaussian_strategy import GaussianStrategy\n from rlkit.exploration_strategies.ou_strategy import OUStrategy\n from rlkit.torch.grill.launcher import get_video_save_func\n from rlkit.torch.her.her_td3 import HerTd3\n from rlkit.data_management.obs_dict_replay_buffer import (\n ObsDictRelabelingBuffer\n )\n\n if 'env_id' in variant:\n env = gym.make(variant['env_id'])\n else:\n env = variant['env_class'](**variant['env_kwargs'])\n\n imsize = 84\n env = GymToMultiEnv(env.env) # unwrap TimeLimit\n env = ImageEnv(env, non_presampled_goal_img_is_garbage=True)\n\n observation_key = variant['observation_key']\n desired_goal_key = variant['desired_goal_key']\n variant['algo_kwargs']['her_kwargs']['observation_key'] = observation_key\n variant['algo_kwargs']['her_kwargs']['desired_goal_key'] = desired_goal_key\n if variant.get('normalize', False):\n raise NotImplementedError()\n\n achieved_goal_key = desired_goal_key.replace(\"desired\", \"achieved\")\n replay_buffer = ObsDictRelabelingBuffer(\n env=env,\n observation_key=observation_key,\n desired_goal_key=desired_goal_key,\n achieved_goal_key=achieved_goal_key,\n **variant['replay_buffer_kwargs']\n )\n obs_dim = env.observation_space.spaces[observation_key].low.size\n action_dim = env.action_space.low.size\n goal_dim = env.observation_space.spaces[desired_goal_key].low.size\n exploration_type = variant['exploration_type']\n if exploration_type == 'ou':\n es = OUStrategy(\n action_space=env.action_space,\n **variant['es_kwargs']\n )\n elif exploration_type == 'gaussian':\n es = GaussianStrategy(\n action_space=env.action_space,\n **variant['es_kwargs'],\n )\n elif exploration_type == 'epsilon':\n es = EpsilonGreedy(\n action_space=env.action_space,\n **variant['es_kwargs'],\n )\n else:\n raise Exception(\"Invalid type: \" + exploration_type)\n\n use_images_for_q = variant[\"use_images_for_q\"]\n use_images_for_pi = variant[\"use_images_for_pi\"]\n\n qs = []\n for i in range(2):\n if use_images_for_q:\n image_q = MergedCNN(input_width=imsize,\n input_height=imsize,\n output_size=1,\n input_channels=3,\n added_fc_input_size=action_dim,\n **variant['cnn_params'])\n q = ImageStateQ(image_q, None)\n else:\n state_q = ConcatMlp(\n input_size=action_dim + goal_dim,\n output_size=1,\n **variant['qf_kwargs']\n )\n q = ImageStateQ(None, state_q)\n qs.append(q)\n qf1, qf2 = qs\n\n if use_images_for_pi:\n image_policy = CNNPolicy(input_width=imsize,\n input_height=imsize,\n output_size=action_dim,\n input_channels=3,\n **variant['cnn_params'],\n output_activation=torch.tanh,\n )\n policy = ImageStatePolicy(image_policy, None)\n else:\n state_policy = TanhMlpPolicy(\n input_size=goal_dim,\n output_size=action_dim,\n **variant['policy_kwargs']\n )\n policy = ImageStatePolicy(None, state_policy)\n\n exploration_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=policy,\n )\n algorithm = HerTd3(\n env,\n qf1=qf1,\n qf2=qf2,\n policy=policy,\n exploration_policy=exploration_policy,\n replay_buffer=replay_buffer,\n **variant['algo_kwargs']\n )\n if variant.get(\"save_video\", False):\n rollout_function = rf.create_rollout_function(\n rf.multitask_rollout,\n max_path_length=algorithm.max_path_length,\n observation_key=algorithm.observation_key,\n desired_goal_key=algorithm.desired_goal_key,\n )\n video_func = get_video_save_func(\n rollout_function,\n env,\n policy,\n variant,\n )\n algorithm.post_epoch_funcs.append(video_func)\n algorithm.to(ptu.device)\n algorithm.train()\n\ndef experiment(variant):\n\n if variant['normalize']:\n env = NormalizedBoxEnv(env)\n exploration_type = variant['exploration_type']\n if exploration_type == 'ou':\n es = OUStrategy(action_space=env.action_space)\n elif exploration_type == 'gaussian':\n es = GaussianStrategy(\n action_space=env.action_space,\n max_sigma=0.1,\n min_sigma=0.1, # Constant sigma\n )\n elif exploration_type == 'epsilon':\n es = EpsilonGreedy(\n action_space=env.action_space,\n prob_random_action=0.1,\n )\n else:\n raise Exception(\"Invalid type: \" + exploration_type)\n obs_dim = env.observation_space.low.size\n action_dim = env.action_space.low.size\n qf1 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n qf2 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[400, 300],\n )\n policy = TanhMlpPolicy(\n input_size=obs_dim,\n output_size=action_dim,\n hidden_sizes=[400, 300],\n )\n exploration_policy = PolicyWrappedWithExplorationStrategy(\n exploration_strategy=es,\n policy=policy,\n )\n algorithm = TD3(\n env,\n qf1=qf1,\n qf2=qf2,\n policy=policy,\n exploration_policy=exploration_policy,\n **variant['algo_kwargs']\n )\n if ptu.gpu_enabled():\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n # noinspection PyTypeChecker\n variant = dict(\n algo_kwargs=dict(\n base_kwargs=dict(\n num_epochs=1001,\n num_steps_per_epoch=1000,\n num_steps_per_eval=1000,\n max_path_length=100,\n num_updates_per_env_step=4,\n batch_size=128,\n discount=0.99,\n min_num_steps_before_training=4000,\n reward_scale=100,\n render=False,\n collection_mode='online',\n parallel_env_params=dict(\n num_workers=1,\n )\n ),\n her_kwargs=dict(\n observation_key='state_observation',\n desired_goal_key='state_desired_goal',\n ),\n td3_kwargs=dict(),\n ),\n replay_buffer_kwargs=dict(\n max_size=int(1E6),\n fraction_goals_are_rollout_goals=1.0,\n fraction_resampled_goals_are_env_goals=0.0,\n ob_keys_to_save=[],\n ),\n qf_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n policy_kwargs=dict(\n hidden_sizes=[400, 300],\n ),\n algorithm='HER-TD3',\n version='normal',\n es_kwargs=dict(\n max_sigma=.8,\n ),\n exploration_type='ou',\n observation_key='image_observation',\n desired_goal_key='state_observation',\n do_state_exp=True,\n save_video=False,\n\n snapshot_mode='gap_and_last',\n snapshot_gap=100,\n\n cnn_params=dict(\n kernel_sizes=[3, 3],\n n_channels=[16, 16],\n strides=[2, 2],\n pool_sizes=[1, 1],\n hidden_sizes=[400, 300],\n paddings=[0, 0],\n use_batch_norm=False,\n ),\n\n use_images_for_q=True,\n use_images_for_pi=True,\n num_exps_per_instance=3,\n )\n\n n_seeds = 1\n\n search_space = {\n 'exploration_type': [\n 'ou',\n ],\n 'algo_kwargs.base_kwargs.reward_scale': [0.1, 1, 10],\n 'seedid': range(n_seeds),\n 'env_id': ['Humanoid-v2', 'Ant-v2', 'HalfCheetah-v2', 'Hopper-v2', 'Walker2d-v2'],\n 'use_images_for_q': [False],\n 'use_images_for_pi': [False],\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n run_variants(her_td3_experiment, sweeper.iterate_hyperparameters(), run_id=1)\n","sub_path":"experiments/ashvin/imagerl/gym/rl_from_images_conv_state_only.py","file_name":"rl_from_images_conv_state_only.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260119186","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nJobber Bekkers\n10543988\n\nconverts a scv file to a JSON file\n\"\"\"\n\nimport csv\nimport json\n# for my machine the entier pathway must be given, tim knows\nwith open('C:/Users/Jobber/Documents/GitHub/dataprocessing/Problem7/Homework/D3LinkedViews/data.json', 'w') as g:\n with open('C:/Users/Jobber/Documents/GitHub/dataprocessing/Problem7/Homework/D3LinkedViews/LiteracyData.csv') as f:\n # copy the headers from the csv file\n headers = ('SeriesName','SeriesCode','CountryName','CountryCode','Data')\n # read the csv file\n read = csv.DictReader(f, headers)\n # count the rows, as the first rows are usually info on the data not the data itself.\n counter = 1\n info = []\n for row in read:\n if (counter > 1):\n info.append(row)\n counter += 1\n h = json.dump(info, g)\n","sub_path":"Problem7/Homework/D3LinkedViews/convertCSV2JSON.py","file_name":"convertCSV2JSON.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628292591","text":"import time\ndef exp_sum(n):\n\tif n < 0:\n\t\treturn 0\n\tdp = [1]+[0]*n\n\tfor num in xrange(1,n+1):\n\t\tfor i in xrange(num,n+1):\n\t\t\tdp[i] += dp[i-num]\n\treturn dp[-1]\n\nbegin = time.time()\nprint(exp_sum(100))\nperiod = time.time() - begin\nprint(period)\n","sub_path":"datastructures/exp_sum.py","file_name":"exp_sum.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"511641142","text":"import os\nimport re\nimport calendar_scraper as cs\nimport textract\nimport instructor \n\n\nDATE_FORMATS = {\n '1': \"Jan {}, January {}, 1/{}, Jan {}{}, January {}{}, Jan. {}\",\n '2': \"Feb {}, February {}, 2/{}, Feb {}{}, February {}{}, Feb. {}\",\n '3': \"Mar {}, March {}, 3/{}, Mar {}{}, March {}{}, Mar. {}\",\n '4': \"Apr {}, April {}, 4/{}, Apr {}{}, April {}{}, Apr. {}\",\n '5': \"May {}, May {}, 5/{}, May {}{}, May {}{}\",\n '6': \"Jun {}, June {}, 6/{}, Jun {}{}, Jun {}{}, Jun. {}\",\n '11': \"Nov {}, November {}, 11/{}, Sep {}{}, Sep {}{}, Sep. {}\",\n '12': \"Dec {}, December {}, 12/{}, Dec {}{}, Dec {}{}, Dec. {}\"\n}\n\nDAY_SUFFIXES = {\n '1': \"st\",\n '2': \"nd\",\n '3': \"rd\",\n '4': \"th\",\n '5': \"th\",\n '6': \"th\",\n '7': \"th\",\n '8': \"th\",\n '9': \"th\",\n '0': \"th\"\n}\n\n\ndef clean_pdf(directory, syllabus):\n '''\n Cleans a textracted PDF file containing a syllabus: decodes it from utf-8\n format into string text, replaces all special whitespace characters with\n a single white space, and converts the string to all lowercase. Essentially\n makes a textracted PDF easier to read.\n\n Inputs:\n syllabus: (str) Path to a single PDF file containing a syllabus.\n\n Returns:\n The cleaned, easier-to-read PDF text.\n '''\n\n syllabus_text = textract.process(directory + \"/\" + syllabus)\n syllabus_text = syllabus_text.decode('utf-8')\n syllabus_text = re.sub(r\"\\s+\", ' ', syllabus_text)\n syllabus_text = re.sub(r\"\\xad\", \"-\", syllabus_text)\n syllabus_text = re.sub(r\"\\–\", \"-\", syllabus_text)\n syllabus_text = syllabus_text.lower()\n\n return syllabus_text\n\n\ndef iterate_professors(directory):\n '''\n Iterates over all syllabi in a directory and returns a \n dictionary mapping a course name to a professor name \n\n Inputs: \n directory: (str) Path to the directory containing syllabi as PDFs.\n \n Return: \n A dictionary mapping each course to the professor name\n '''\n\n syllabi_dict = {}\n\n for folder in os.listdir(directory):\n quarter = re.search(r'\\D+', folder).group()\n quarter = quarter[0].upper() + quarter[1:]\n year = '20' + re.search(r'\\d+', folder).group()\n subdirectory = directory + \"/\" + folder\n for syllabus in os.listdir(subdirectory):\n syllabus_text = clean_pdf(subdirectory, syllabus)\n dept = re.search(r'[A-Z]{4}', syllabus).group()\n course_num = re.search(r'\\d{5}', syllabus).group()\n syllabi_dict[subdirectory+syllabus] = instructor.get_professor(\n syllabus_text, quarter, year, dept, course_num) \n\n return syllabi_dict\n\n\ndef iterate_through_syllabi(directory, function, year):\n '''\n Carries out a regular expression function on all syllabi in a directory,\n and returns a dictionary mapping each course to the regex function output.\n\n Inputs:\n directory: (str) Path to the directory containing syllabi as PDFs.\n function: A function containing regular expressions that will be \n applied to the text of the syllabi.\n year: (int) year (eg 2018, 2019 etc.)\n \n Returns:\n A dictionary mapping each course to the function output.\n '''\n\n syllabi_dict = {}\n for syllabus in os.listdir(directory):\n syllabus_text = clean_pdf(directory, syllabus)\n syllabi_dict[syllabus] = function(syllabus_text, year) \n\n return syllabi_dict\n\n\ndef check_string(check_this_before, check_this_after, month_formats):\n '''\n splits string surrounding off day string into list of words and \n checks it for other dates or key words that might mislead the function \n that searches of assignments on off days and splices string for only relevant \n surrounding words\n\n Inputs: \n check_this_before: string before off day string to check\n check_this_after: string after off day string to check\n month_formats: months to look for based on which quarter \n\n Returns: \n list of words to search for key words \n '''\n\n month_formats += re.findall(r'\\d{1,2}/\\d{1,2}', check_this_before)\n month_formats += re.findall(r'\\d{1,2}/\\d{1,2}', check_this_after)\n month_formats += ['m','w','th','f']\n check_this_before = check_this_before.split()\n check_this_after = check_this_after.split()\n new_list_before = check_this_before\n\n for word in check_this_before:\n if word in month_formats:\n num = check_this_before.index(word)\n new_list_before = new_list_before[num + 1:]\n new_list_after = check_this_after\n\n for word in check_this_after:\n if word in month_formats:\n num = check_this_after.index(word)\n new_list_after = new_list_after[:num]\n new_list = new_list_before + new_list_after\n\n return new_list\n\n\ndef get_checks(items, text):\n '''\n Gets the string of text to check around a certain indicator word \n\n Inputs:\n items: the indicator word around which we need to check (a match object)\n text: the raw text being searched (str)\n\n Output: \n A tuple, the first element in the tuple is the 50 characters before \n the indicator, to check and the second element is the 50 charactrs \n after the indicator to check \n '''\n\n indicies = items.span()\n check_this_before = text[indicies[0] - 50: indicies[0]]\n check_this_after = text[indicies[1]:indicies[1] + 51]\n\n return check_this_before,check_this_after\n\n\ndef get_numerical_formats(quarter, year, off_day):\n '''\n Obtains the numerical formats for off-days in a given quarter and year, to \n use in regular expressions to find off-days in a syllabus PDF.\n\n Inputs:\n quarter: (str) The quarter of interest.\n year: (int) The year of interest.\n off_day: (str) The name of the off-day we would like to obtain formats\n for.\n\n Returns:\n A list of strings that are the numerical formats of the off-day.\n '''\n\n datetime = cs.get_datetimes_from_calendar(quarter, year)\n month = str(datetime[off_day][0].month)\n day = str(datetime[off_day][0].day)\n suffix = DAY_SUFFIXES[day[-1]]\n\n s = DATE_FORMATS[month].format(\\\n day, day, day, day, suffix, day, suffix, day)\n date_formats = s.split(\", \")\n\n return date_formats\n\n\ndef get_num_assignments(formats, text, month_formats, key_words):\n '''\n Scrape text and return number of assignments due for a given holiday\n\n Inputs: \n formats: formats of holiday words to check for (i.e. \"MLK\", \"Martin Luther King Day\", \"MLK Day\")(\n list of strings )\n text: the syllabi to scrape (str)\n month_formats: months and their formats to check the syllabi for (list of strings)\n key_words: words to check for that indicate an assignment due\n\n Output: \n a tuple, where the first element of the tuple is the number of assignments due \n and the second element of the tuple is a list of match objects to check if \n any assignments are due in the syllabus\n '''\n \n check_list = []\n num_due_assignments = 0 \n for s in formats: \n frag = re.search(s,text)\n check_list.append(frag)\n if frag is not None: \n check = get_checks(frag, text)\n new_list = check_string(check[0], check[1], month_formats)\n for word in new_list: \n if word in key_words:\n num_due_assignments += 1 \n break\n\n return (num_due_assignments, check_list) ","sub_path":"syllabi_scraping/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110835782","text":"import unittest\nfrom getEmailByNonRegex import is_email, get_emails, get_accounts\n\nclass TestGetEmailByRegex(unittest.TestCase):\n\tdef test_is_email(self):\n\t\tself.assertEqual(is_email(\"abcd_aisu123@gmail.com\"), True)\n\t\n\tdef test_get_emails(self):\n\t\tparagraph = \"ajskasjdkf asdfoig asdf1234@kkbox.com and 395ajkd0@gmail.com asdfpoig, asudig zxcvaj. Siif xjkc0234_49@demo.tw djjakzkxc, iiiie.\"\n\t\texpected = [\"asdf1234@kkbox.com\",\"395ajkd0@gmail.com\", \n\t\t\t\t\"xjkc0234_49@demo.tw\"]\n\t\t\n\t\tself.assertEqual(get_emails(paragraph), expected)\n\tdef test_get_accounts(self):\n\t\tparagraph = \"ajskasjdkf asdfoig asdf1234@kkbox.com and 395ajkd0@gmail.com asdfpoig, asudig zxcvaj. Siif xjkc0234_49@demo.tw djjakzkxc, iiiie.\"\n\t\texpected = [\"asdf1234\", \"395ajkd0\", \"xjkc0234_49\"]\n\t\t\n\t\tself.assertEqual(get_accounts(paragraph), expected)\n\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"UnitTestforNonRegex.py","file_name":"UnitTestforNonRegex.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"184437324","text":"import sys\nimport heapq\n\nread = sys.stdin.readline\n\ndef solution(N, M, buses, start, end):\n cities = [[] for _ in range(N + 1)]\n for s, e, w in buses:\n cities[s].append((e, w))\n\n weight = [sys.maxsize for _ in range(N + 1)]; weight[start] = 0\n\n queue = []; heapq.heappush(queue, (weight[start], start))\n\n while queue:\n w, dest = heapq.heappop(queue)\n\n if dest == end: break\n\n for e, w1 in cities[dest]:\n if weight[e] > w + w1:\n weight[e] = w + w1\n heapq.heappush(queue, (weight[e], e))\n \n return weight[end]\n\nif __name__ == '__main__':\n N = int(read())\n M = int(read())\n buses = [list(map(int, read().split())) for _ in range(M)]\n start, end = map(int, read().split())\n\n sys.stdout.write('%d\\n'%solution(N, M, buses, start, end))","sub_path":"1~10000/1916/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147630921","text":"import os\n\nMONGO_PASS = os.environ.get('MONGO_PASS')\nMONGO_USER = os.environ.get('MONGO_USER')\n\nISO_TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ'\n\nCARD_DONE_STATUS = 'Done!'\nCARD_TODO_STATUS = 'To-do'\nCARD_DOING_STATUS = 'Doing'\n\nMONGO_LIST_DONE = 'done_items'\nMONGO_LIST_DOING = 'doing'\nMONGO_LIST_TODO = 'to_do'\n\ndef mapCardsToLocalRepresentation(cards):\n all_card_list = []\n for status, status_list in cards.items():\n for card in status_list:\n all_card_list.append(Card(\n str(card['_id']),\n card['name'],\n getCardStatusFromListName(status),\n card['dateLastActivity']\n ))\n all_card_list.sort(key=cardComparator)\n print(all_card_list)\n return all_card_list\n\n\ndef cardComparator(c):\n return 1 if c.status == CARD_DONE_STATUS else 0\n\n\ndef cardComparatorId(c):\n return int(c.id)\n\n\ndef cardComparatorTimestamp(c):\n return c.last_modified\n\n\ndef getCardStatusFromListName(list_name):\n if list_name == MONGO_LIST_DONE:\n return CARD_DONE_STATUS\n elif list_name == MONGO_LIST_DOING:\n return CARD_DOING_STATUS\n else:\n return CARD_TODO_STATUS\n\n\nclass Card:\n def __init__(self, id, name, status, last_modified):\n self.id = id\n self.status = status\n self.name = name\n self.last_modified = last_modified\n\n","sub_path":"board_utils.py","file_name":"board_utils.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"186754838","text":"from scripts import tools\n\n#INSTALL\npackages = ['python',\n 'python-numpy',\n 'python-pipenv',\n 'tk',\n 'cmake', #installed to build YouCompleteMe vim Plugin\n 'boost', #same as cmake for YouCompleteMe\n 'python-opengl'] #for qutebrowser with webengine backend\ntools.pacaur(packages)\n","sub_path":"scripts/code_env.py","file_name":"code_env.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"435548418","text":"import merakikernel.riotapi.teamapi\nimport cassiopeia.type.dto.team\nimport cassiopeia.dto.teamapi\nimport cassiopeia.dto.requests\n\n\ndef get_teams_by_summoner_id(summoner_ids):\n region = cassiopeia.dto.requests.region\n summoner_ids = \",\".join([str(id_) for id_ in summoner_ids]) if isinstance(summoner_ids, list) else str(summoner_ids)\n response = merakikernel.riotapi.teamapi.summoner_teams(region, summoner_ids)\n\n for id_, teams in response.items():\n response[id_] = [cassiopeia.type.dto.team.Team(team) for team in teams]\n\n return response\n\n\ndef get_teams_by_id(team_ids):\n region = cassiopeia.dto.requests.region\n team_ids = \",\".join(team_ids) if isinstance(team_ids, list) else team_ids\n response = merakikernel.riotapi.teamapi.team(region, team_ids)\n\n for id_, team in response.items():\n response[id_] = cassiopeia.type.dto.team.Team(team)\n\n return response\n\n\ndef patch_api():\n get_teams_by_summoner_id.__doc__ = cassiopeia.dto.teamapi.get_teams_by_summoner_id.__doc__\n cassiopeia.dto.teamapi.get_teams_by_summoner_id = get_teams_by_summoner_id\n\n get_teams_by_id.__doc__ = cassiopeia.dto.teamapi.get_teams_by_id.__doc__\n cassiopeia.dto.teamapi.get_teams_by_id = get_teams_by_id\n","sub_path":"merakikernel/integrations/cassiopeia/teambindings.py","file_name":"teambindings.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31387070","text":"import os\nimport pandas as pd\nimport json\n\n# Loading the entire json as object\nwith open(os.getcwd()+\"/python-utils/files/nyphil.json\") as f:\n df = json.load(f)\n\n# Creating empty lists inorder to append each row after normalizing\ndf1 = []\ndf2 = []\ndf3 = []\ndf4 = []\n\n# Creating programs, works, soloists dataframes through loop\nfor program in df['programs']:\n if(program['id'] == '00646b9f-fec7-4ffb-9fb1-faae410bd9dc-0.1'):\n program_df = pd.json_normalize(program)\n id = program['id']\n df3.append(program_df)\n for work in program['works']:\n work_df = pd.json_normalize(work)\n work_df['id'] = id\n ID = work_df['ID']\n df1.append(work_df)\n if (len(work['soloists']) == 0):\n solo_ = pd.DataFrame()\n solo_['id'] = work_df['id']\n solo_['ID'] = work_df['ID']\n df2.append(solo_)\n else:\n for soloist in work['soloists']:\n solo_df = pd.json_normalize(soloist)\n solo_df['id'] = work_df['id']\n solo_df['ID'] = work_df['ID']\n df2.append(solo_df)\n\n# Creating concerts only dataframe\n# This processing can also be added in the previous loop as well.\nfor program in df['programs']:\n if(program['id'] == '00646b9f-fec7-4ffb-9fb1-faae410bd9dc-0.1'):\n id = program['id']\n for concert in program['concerts']:\n concert_df = pd.json_normalize(concert)\n concert_df['id'] = program['id']\n df4.append(concert_df)\n\n# Concatenating the list to form final dataframes for program, work, concerts, soloists\np_df = pd.concat(df3, sort=False)\np_df.drop(['concerts', 'works'], axis=1, inplace=True)\nw_df = pd.concat(df1, sort=False)\nw_df.drop(['soloists'], axis=1, inplace=True)\ns_df = pd.concat(df2, sort=False)\nc_df = pd.concat(df4, sort=False)\n\n# Merging dataframes one by one\nout_1 = w_df.merge(s_df, how=\"inner\", left_on=['id', 'ID'], right_on=['id', 'ID'])\nout_2 = out_1.merge(c_df, how=\"inner\", left_on=['id'], right_on=['id'])\nout_3 = out_2.merge(p_df, how=\"inner\", left_on=['id'], right_on=['id'])\n\n# Saving all the dataframes separately as well as the output\np_df.to_csv(os.getcwd()+\"/python-utils/files/p_df.csv\", index=False)\nw_df.to_csv(os.getcwd()+\"/python-utils/files/w_df.csv\", index=False)\ns_df.to_csv(os.getcwd()+\"/python-utils/files/s_df.csv\", index=False)\nc_df.to_csv(os.getcwd()+\"/python-utils/files/c_df.csv\", index=False)\nout_3.to_csv(os.getcwd()+\"/python-utils/files/out.csv\", index=False)\n","sub_path":"python-utils/utils/normalising_json.py","file_name":"normalising_json.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327129129","text":"#!/bin/python\nimport json\nimport random\nimport promoterz\n\nfrom copy import deepcopy\n\nimport coreFunctions\n\nimport promoterz.sequence.standard_loop\n\nfrom deap import tools\nfrom deap import algorithms\nfrom deap import base\n\nfrom Settings import getSettings\nimport stratego\nfrom functools import partial\n\n# TEMPORARY ASSIGNMENT OF EVAL FUNCTIONS; SO THINGS REMAIN SANE;\ndef aEvaluate(constructPhenotype, candleSize, DateRange, Individual, gekkoUrl):\n phenotype = constructPhenotype(Individual)\n StratName = stratego.gekko_strategy.createStrategyFile(phenotype)\n phenotype = {StratName:phenotype}\n SCORE = promoterz.evaluation.gekko.Evaluate(candleSize,\n DateRange, phenotype, gekkoUrl)\n return SCORE\ndef bEvaluate(constructPhenotype, candleSize, DateRange, Individual, gekkoUrl):\n phenotype = constructPhenotype(Individual)\n phenotype = {Individual.Strategy: phenotype}\n SCORE = promoterz.evaluation.gekko.Evaluate(candleSize,\n DateRange, phenotype, gekkoUrl)\n return SCORE\n\n\ndef gekko_generations(TargetParameters, GenerationMethod, EvaluationMode, NB_LOCALE=2):\n\n GenerationMethod = promoterz.functions.selectRepresentationMethod(GenerationMethod)\n genconf=getSettings('generations')\n if EvaluationMode == 'indicator':\n Evaluate = aEvaluate\n Strategy = None\n else:\n Evaluate = bEvaluate\n Strategy = EvaluationMode\n\n globalconf = getSettings('Global')\n print(\"Evolving %s strategy;\\n\" % Strategy)\n\n print(\"evaluated parameters ranges:\")\n\n TargetParameters = promoterz.utils.flattenParameters(TargetParameters)\n\n GlobalTools = GenerationMethod.getToolbox(Strategy, genconf, TargetParameters)\n\n\n RemoteHosts = promoterz.evaluation.gekko.loadHostsFile(globalconf.RemoteAWS)\n globalconf.GekkoURLs+=RemoteHosts\n if RemoteHosts:\n print(\"Connected Remote Hosts:\\n%s\" % ('\\n').join(RemoteHosts))\n\n\n for k in TargetParameters.keys():\n print( \"%s%s%s\" % (k, \" \" * (30-len(k)), TargetParameters[k]) )\n\n GlobalTools.register('Evaluate', Evaluate,\n GlobalTools.constructPhenotype, genconf.candleSize)\n\n\n availableDataRange = promoterz.evaluation.gekko.getAvailableDataset(\n exchange_source=genconf.dataset_source)\n\n showdatadaterange = [ promoterz.evaluation.gekko.epochToString(availableDataRange[x])\\\n for x in ['from', 'to'] ]\n\n print(\"using candlestick dataset %s to %s\" % (showdatadaterange[0],\n showdatadaterange[1]))\n\n\n loops = [ promoterz.sequence.standard_loop.standard_loop ]\n World = promoterz.world.World(GlobalTools, loops,\n genconf, globalconf, TargetParameters, NB_LOCALE,\n EnvironmentParameters=availableDataRange)\n\n while World.EPOCH < World.genconf.NBEPOCH:\n World.runEPOCH()\n # RUN ENDS. SELECT INDIVIDUE, LOG AND PRINT STUFF;\n #FinalBestScores.append(Stats['max'])\n print(World.EnvironmentParameters)\n ValidationDataset =\\\n promoterz.evaluation.gekko.globalEvaluationDataset(World.EnvironmentParameters,\n genconf.deltaDays, 12)\n\n for LOCALE in World.locales:\n BestIndividues = tools.selBest(LOCALE.population, genconf.finaltest['NBBESTINDS'])\n\n Z=genconf.finaltest['NBADDITIONALINDS']\n AdditionalIndividues = tools.selTournament(LOCALE.population, Z, Z*2)\n AdditionalIndividues = [ x for x in AdditionalIndividues if x not in BestIndividues ]\n FinalIndividues = BestIndividues + AdditionalIndividues\n\n for FinalIndividue in FinalIndividues:\n\n AssertFitness, FinalProfit=coreFunctions.stratSettingsProofOfViability(World,\n FinalIndividue,\n ValidationDataset)\n print(\"Testing Strategy:\\n\")\n if AssertFitness or FinalProfit > 50:\n FinalIndividueSettings = GlobalTools.constructPhenotype(FinalIndividue)\n\n Show = json.dumps(FinalIndividueSettings, indent=2)\n coreFunctions.logInfo(\"~\" * 18)\n\n\n print(\"Settings for Gekko config.js:\")\n print(Show)\n print(\"Settings for Gekko --ui webpage\")\n coreFunctions.logInfo(coreFunctions.pasteSettingsToUI(FinalIndividueSettings))\n\n print(\"\\nRemember to check MAX and MIN values for each parameter.\")\n print(\"\\tresults may improve with extended ranges.\")\n\n else:\n print(\"Strategy Fails.\")\n\n\n\n print(\"\")\n print(\"\\t\\t.RUN ENDS.\")\n\n\n","sub_path":"evolution_generations.py","file_name":"evolution_generations.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457768643","text":"#module for geometric shapes on the x,y plane\n\nimport math\n\ndef mp(p1,p2): #returns a point in the middle of p1 and p2\n x,y =p1\n x2,y2 =p2\n return ((x+x2)/2,(y+y2)/2)\n\ndef angle_of_vector(vector): #returns the angle between the x axis and the vector\n c1,c2 = vector\n x,y =c1\n x2,y2 =c2\n if(x-x2!=0):\n if(x>x2):\n ceta = ((math.atan((y-y2)/(x-x2))/math.pi)*180)\n else:\n if(y>y2):\n ceta = 180+((math.atan((y-y2)/(x-x2))/math.pi)*180)\n else:\n ceta = -180+((math.atan((y-y2)/(x-x2))/math.pi)*180)\n if(x-x2==0):\n if(y>y2):\n ceta = 90\n else:\n ceta = -90\n return ceta\n\ndef mag_v(vector):\n p1,p2 = vector\n x,y =p1\n x2,y2 =p2\n return(math.sqrt((x-x2)**2+(y-y2)**2))\n \n","sub_path":"geogebra_m.py","file_name":"geogebra_m.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279905608","text":"from web3 import Web3\nimport json\n\n\ndef main():\n w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))\n with open('../build/contracts/MyToken.json', 'r') as fr:\n erc20_json_dict = json.load(fr)\n\n # 1. 查看ganache上的输出,(在shell界面上可以查看,转账记录有etherscan??),如果不能查���可以考虑重新deploy一个合约,得到其地址\n tx_receipt = w3.eth.get_transaction_receipt('0x09d02b76e7b6d4a5a44279caca98f37a5968374dcf13efc985ea3661a7f5bf7e')\n contract_addr = tx_receipt['contractAddress']\n\n # 2. 生成该合约地址的合约对象,有两种方法\n contract = w3.eth.contract(address=contract_addr, abi=erc20_json_dict['abi'])\n\n ContractClass = w3.eth.contract(abi=erc20_json_dict['abi'])\n contract_method2 = ContractClass(address=contract_addr)\n\n # for acc in w3.eth.accounts:\n # print(acc)\n # 3. 如果给予一个没有合约的地址会发生什么?我们来试一试\n # 3.1 使用与合约地址相差一个数字的地址来测试\n # 0xA094d630D172FC529ba5756e5c0af4695C75Cd56 exit\n # 0xA094d630D172FC529ba5756e5c0af4695C75Cd55 not exit\n # contract_test1 = w3.eth.contract(address='0xA094d630D172FC529ba5756e5c0af4695C75Cd55', abi=erc20_json_dict['abi'])\n # contract_test1 cannot pass checksum\n\n # 3.2 使用一个个人账号的地址来测试,这个地址能通过checksum测试\n contract_test2 = w3.eth.contract(address='0xCF156D72bEAEc66678fD33dEBdE574e9CD781F82', abi=erc20_json_dict['abi'])\n # nothing happen,说明能生成该合约对象,但是在发送的时候可能会发生错误\n\n # 4. 查看合约的各种属性,包括了address, abi, bytecode, functions, events\n # 其中functions和events是对abi进行了解析\n print(contract.address)\n print(contract.abi)\n print(contract.bytecode)\n for x in contract.functions:\n print(x)\n for x in contract.events:\n print(x)\n\n print(type(contract.functions.increaseAllowance))\n\n\nif __name__ =='__main__':\n main()","sub_path":"Example18-web3py/tests/2_play_around_on_existing_contract.py","file_name":"2_play_around_on_existing_contract.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470727991","text":"from selenium.webdriver.firefox.webdriver import WebDriver\nfrom fixture.session import SessionHelper\nfrom fixture.group import GroupHelper\nfrom fixture.contacts import ContactHelper\n\n\nclass Application:\n def __init__(self):\n self.wd = WebDriver(capabilities={\"marionette\": False})\n # self.wd.implicitly_wait(5) use for dynamic elements\n self.session = SessionHelper(self)\n self.group = GroupHelper(self)\n self.contacts = ContactHelper(self)\n\n\n def open_home_page(self):\n # open home page\n wd = self.wd\n if not (wd.current_url.endswith(\"addressbook/index.php\") and (len(wd.find_elements_by_name(\"user\")) and len(wd.find_elements_by_name(\"pass\"))) > 0):\n wd.get(\"http://localhost/addressbook/index.php\")\n\n\n def is_valid(self):\n try:\n self.wd.current_url\n return True\n except:\n return False\n\n\n def destroy(self):\n self.wd.quit()","sub_path":"fixture/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"165631968","text":"\"\"\"Classes for caching AWS credentials\"\"\"\nfrom dataclasses import asdict, dataclass, field\nimport time\nfrom typing import Any, Dict, Optional, Type\n\nimport boto3\n\n\n@dataclass(frozen=True)\nclass AWSCredentials:\n \"\"\"Represents a set of AWS Credentials\n\n Args:\n access_key_id: AWS access key id\n secret_access_key: AWS secret access key\n session_token: AWS session token\n expiration: Session expiration as an epoch timestamp int\n \"\"\"\n\n access_key_id: str\n secret_access_key: str\n session_token: str\n expiration: int\n\n def is_expired(self) -> bool:\n \"\"\"Determine if this cache value is within 60 seconds of expiry\n\n Returns:\n True if this session is value is expired, else False.\n \"\"\"\n return int(time.time()) >= self.expiration - 60\n\n def get_session(self, region_name: Optional[str] = None) -> boto3.Session:\n \"\"\"Build a boto3.Session using these credentials\"\"\"\n return boto3.Session(\n aws_access_key_id=self.access_key_id,\n aws_secret_access_key=self.secret_access_key,\n aws_session_token=self.session_token,\n region_name=region_name,\n )\n\n @classmethod\n def from_dict(cls: Type[\"AWSCredentials\"], data: Dict[str, Any]) -> \"AWSCredentials\":\n \"\"\"Build an AWSCredentials object from a dictionary\"\"\"\n return cls(**data)\n\n\n@dataclass(frozen=True)\nclass AWSCredentialsCacheKey:\n \"\"\"Represents a credential cache key\n\n Args:\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n \"\"\"\n\n account_id: str\n role_name: str\n role_session_name: str\n\n def __str__(self) -> str:\n return \":\".join((self.account_id, self.role_name, self.role_session_name))\n\n @classmethod\n def from_str(cls: Type[\"AWSCredentialsCacheKey\"], key: str) -> \"AWSCredentialsCacheKey\":\n account_id, role_name, role_session_name = key.split(\":\")\n return cls(account_id=account_id, role_name=role_name, role_session_name=role_session_name)\n\n\n@dataclass(frozen=True)\nclass AWSCredentialsCache:\n \"\"\"An AWSCredentialsCache is a cache for AWSCredentials.\"\"\"\n\n # https://github.com/PyCQA/pylint/issues/2698\n # pylint: disable=unsupported-assignment-operation,no-member,unsupported-delete-operation,unsubscriptable-object\n\n cache: Dict[AWSCredentialsCacheKey, AWSCredentials] = field(default_factory=dict)\n\n def put(\n self, credentials: AWSCredentials, account_id: str, role_name: str, role_session_name: str\n ) -> None:\n \"\"\"Put an AWSCredentials object into the cache.\n\n Args:\n credentials: credentials to cache\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n \"\"\"\n session = credentials.get_session()\n sts_client = session.client(\"sts\")\n caller_id = sts_client.get_caller_identity()\n # make sure these creds are for the account the caller claims them to be\n if caller_id[\"Account\"] != account_id:\n raise ValueError(\n (\n f\"Credentials {credentials} are not for claimed account_id \"\n f\"{account_id} - they are for {caller_id['Account']}\"\n )\n )\n cache_key = AWSCredentialsCacheKey(account_id, role_name, role_session_name)\n self.cache[cache_key] = credentials\n\n def get(\n self,\n account_id: str,\n role_name: str,\n role_session_name: str,\n region_name: Optional[str] = None,\n ) -> Optional[boto3.Session]:\n \"\"\"Get a boto3 Session from AWSCredentials in the cache. Return None if no matching\n AWSCredentials were found.\n\n Args:\n account_id: session account id\n role_name: session role name\n role_session_name: session role session name\n region_name: session region_name\n\n Returns:\n boto3.Session from credentials if cached, else None.\n \"\"\"\n cache_key = AWSCredentialsCacheKey(account_id, role_name, role_session_name)\n cache_val = self.cache.get(cache_key)\n if cache_val is not None:\n if cache_val.is_expired():\n del self.cache[cache_key]\n else:\n return self.cache[cache_key].get_session(region_name=region_name)\n return None\n\n def to_dict(self) -> Dict[str, Any]:\n return {\"cache\": {str(key): asdict(val) for key, val in self.cache.items()}}\n\n @classmethod\n def from_dict(cls: Type[\"AWSCredentialsCache\"], data: Dict[str, Any]) -> \"AWSCredentialsCache\":\n cache = {\n AWSCredentialsCacheKey.from_str(key=key): AWSCredentials.from_dict(data=val)\n for key, val in data[\"cache\"].items()\n }\n return cls(cache=cache)\n","sub_path":"altimeter/aws/auth/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541969360","text":"import pandas as pd\nimport numpy as np\nimport sqlite3\nimport datetime\nimport json\nimport hmac\nimport hashlib\nimport time\nimport requests\nimport base64\nfrom time import sleep\n\n\n#########################################################\n#\n# HIGH(ER) FREQUENCY TRADING\n# BITFINEX\n# STATIC 30 MIN (TODO: ADD ADDITIONAL TIME PERIODS)\n#\n#############\n\n\n\n\n\n#########\n# REBUILD PROCESSED DB IF NEEDED\n##\n\n# time_period = NONE\n# table_name = 'charts_' + time_period\n\n# # build query with explicit dtypes\n# create_table_query = '''\n# CREATE TABLE\n# IF NOT EXISTS %s (\n# pid text PRIMARY KEY,\n# date text,\n# currency_pair text,\n# min_global_trade_id integer,\n# open float,\n# high float,\n# low float,\n# close float,\n# volume float\n# );''' % table_name\n\n# # # connect to db\n# # conn = sqlite3.connect('db/processed.db')\n# # c = conn.cursor()\n\n# # # create table\n# # c.execute(create_table_query)\n\n# # # commit & close\n# # conn.commit()\n# # conn.close()\n\n\n\n\n\n#####################\n#\n# Initially, I was trading with Poloniex so I used their nomenclature.\n# unfortuantely Bitfinex is a little different, so this \"currency pair map\"\n# is used to standardize the naming.\n#\n########\n \ndef get_cp_map():\n '''\n keeping polo's naming convention for db reasons. updating can be done by hardcoding\n here or by using the update method (though it's best to just hardcode it)\n '''\n \n cp_dict = {\n \n 'USDT_BTC': 'tBTCUSD', 'USDT_BCH': 'tBCHUSD', 'USDT_LTC': 'tLTCUSD',\n 'USDT_ETH': 'tETHUSD', 'USDT_ETC': 'tETCUSD', 'USDT_ZEC': 'tZECUSD',\n 'USDT_XMR': 'tXMRUSD', 'USDT_DASH': 'tDSHUSD', 'USDT_SAN': 'tSANUSD',\n 'USDT_NEO': 'tNEOUSD', 'USDT_IOTA': 'tIOTUSD', 'USDT_OMG': 'tOMGUSD',\n 'USDT_QTUM': 'tQTMUSD', 'USDT_ZRX': 'tZRXUSD', 'USDT_BAT': 'tBATUSD',\n 'USDT_BTG': 'tBTGUSD', 'USDT_SNT': 'tSNTUSD', 'USDT_GNT': 'tGNTUSD',\n 'USDT_FUN': 'tFUNUSD', 'USDT_AVT': 'tAVTUSD', 'USDT_SPANK': 'tSPKUSD',\n 'USDT_EDO': 'tEDOUSD', 'USDT_QASH': 'tQSHUSD', 'USDT_EOS': 'tEOSUSD',\n 'USDT_XRP': 'tXRPUSD'\n }\n\n # map cp for easy indexing\n cp_map = Mapping()\n for cp in cp_dict:\n cp_map[str(cp)] = str(cp_dict[cp])\n \n return cp_map\n\n\n\n# two way dictionary / map for currency pairs\nclass Mapping(dict):\n def __setitem__(self, key, value):\n # Remove any previous connections with these values\n if key in self:\n del self[key]\n if value in self:\n del self[value]\n dict.__setitem__(self, key, value)\n dict.__setitem__(self, value, key)\n\n def __delitem__(self, key):\n dict.__delitem__(self, self[key])\n dict.__delitem__(self, key)\n\n def __len__(self):\n return dict.__len__(self) // 2\n\n\n\n#####################\n#\n# Class to retrieve, process, and store trade history\n#\n########\n\n\nclass TradeHistory():\n \n def __init__(self, time_period, currency_pairs, verbose = False):\n \n self.time_period = time_period\n self.currency_pairs = currency_pairs\n self.cp_map = get_cp_map()\n self.verbose = verbose\n self.pairs_to_update = set(self.currency_pairs)\n self.pairs_updated = set()\n self.processed_table_name = 'charts_' + self.time_period\n \n # load previous 'last trade IDs' for faster db search\n self.last_trade_id_filename = 'db/KEEP_query_optim_utils.csv'\n last_trade_ids = pd.read_csv(self.last_trade_id_filename)\n last_trade_ids.index = last_trade_ids.currency_pair\n self.last_trade_id_dict = dict(last_trade_ids['global_trade_id'].to_dict())\n \n # helper to make a single call for the trade history (limited to 1000 trades)\n def _trade_history_endpoint(self, cp, start, end):\n endpoint = 'https://api.bitfinex.com/v2/trades/%s/hist?limit=1000&start=%s&end=%s' % (cp, start, end)\n return endpoint\n \n # helper, current epoch time\n def _epoch_now(self):\n return int(datetime.datetime.now().timestamp())\n \n # get the date of the latest trade in db, use this as the start date for API calls\n def _get_latest_trade_date(self, cp):\n \n if self.verbose:\n print('\\ngetting trades for:', cp)\n print('finding date of last trade...')\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # using the saved dict, set the last known Global Trade ID for this pair\n last_known_global_trade_id = self.last_trade_id_dict[cp]\n\n # use a subquery (that only pulls in trade history beyond what was last\n # seen, as per the last_trade_id_dict) in order to speed up search\n sub = '''\n SELECT date, currency_pair, trade_id, global_trade_id\n FROM trade_history\n WHERE global_trade_id >= %s\n ''' % last_known_global_trade_id\n\n # get the date of the latest trade\n latest_date_query = '''\n SELECT MAX(date)\n FROM (%s)\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % (sub, cp)\n\n # query for latest date pinged\n start_time = pd.read_sql(latest_date_query, conn).iloc[0][0]\n\n # close connection\n conn.close()\n\n return start_time * 1000\n \n # this will be called if there is no data for respective pair in: self.last_trade_id_dict\n def _get_latest_trade_date_fallback(self, cp):\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # latest date query\n latest_date_query = '''\n SELECT MAX(date)\n FROM trade_history\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % cp\n\n # query for latest date pinged\n start_time = pd.read_sql(latest_date_query, conn).iloc[0][0]\n\n # close connection\n conn.close()\n\n return start_time * 1000\n \n # save the recent trade IDs to a csv so they can be easily loaded next timed\n # note: it is first converted to a df for ease, pandas is just the best :D\n def _save_last_trade_id_dict(self, id_dict):\n\n # convert to df for easy saving\n df = pd.DataFrame([id_dict])\n pairs = df.columns.tolist()\n df = df.T.copy()\n df.columns = ['global_trade_id']\n df['currency_pair'] = pairs\n df = df.reset_index(drop = True).copy()\n \n # write to csv\n df.to_csv(self.last_trade_id_filename, index = False)\n \n return None\n \n # get full trade history for the selected date range, end date defaults to now\n def _get_full_trade_history(self, cp, start_date, end_date = int(datetime.datetime.now().timestamp() * 1000)):\n\n df = pd.DataFrame()\n cp = str(self.cp_map[cp])\n prev_status = pd.to_datetime(end_date, unit = 'ms')\n new_data_len = 1000\n i = 0\n\n # continue to call the api until the limit is not reached\n while new_data_len >= 1000:\n\n try:\n # get the new data\n new_data = pd.read_json(self._trade_history_endpoint(cp, start_date, end_date))\n new_data_len = len(new_data.index)\n\n # set new min and max date\n max_date = int(new_data.iloc[0,1])\n min_date = int(new_data.iloc[-1,1])\n\n # append new trade data to df\n df = df.append(new_data)\n\n # reset the end date based off of the new min date\n end_date = int(min_date)\n\n # limited to ~20 requests per min on this endpoint\n sleep(3)\n i += 1\n\n # handle errors and rate limit issues\n except Exception as e:\n\n # print error\n print(e)\n\n # try/except in case we get an error other than \"Too Many Requests\"\n try:\n # if we get a \"Too Many Requests\" error\n if int(e.status) == 429:\n print('hit rate limit, sleeping for a minute...')\n sleep(60)\n\n # usually it's just a connection reset error so it's okay to continue. consider\n # changing if we get other errors (possibly requiring to return current results)\n except: pass\n \n # print status\n if i % 10 == 0 and self.verbose:\n print('\\nIteration:', i)\n status = pd.to_datetime(min_date, unit = 'ms')\n print('Status:', str(status))\n print('Concentration:', str(prev_status - status))\n prev_status = pd.to_datetime(min_date, unit = 'ms')\n\n # set col names\n df.columns = ['id', 'date', 'amount', 'rate']\n\n return df\n \n # process the raw bfx data so that it matches polo's trade history\n def _process_raw_bfx_trade_history(self, raw_trade_history_df):\n \n raw_trade_history_df['type'] = raw_trade_history_df['amount'].apply(lambda x: 'buy' if np.sign(x) > 0 else 'sell')\n raw_trade_history_df['amount'] = abs(raw_trade_history_df['amount'])\n raw_trade_history_df['total'] = raw_trade_history_df.rate * raw_trade_history_df.amount\n raw_trade_history_df['global_trade_id'] = raw_trade_history_df['id'] * 1000000 # lazy way to accomodate both polo and bfx\n raw_trade_history_df['trade_id'] = 0\n raw_trade_history_df = raw_trade_history_df[[col for col in raw_trade_history_df.columns.tolist() if col != 'id']]\n raw_trade_history_df['date'] = raw_trade_history_df['date'] / 1000\n raw_trade_history_df['date'] = raw_trade_history_df['date'].astype('int')\n\n return raw_trade_history_df\n \n # calculate the number of updates (retrieval of trade history from bfx) during each trading period\n def _n_updates(self, update_interval = 600):\n seconds_left = self.period_end - self._epoch_now()\n n_updates = int(round(seconds_left / update_interval)) + 1\n sleep_time = (seconds_left - (n_updates * 10)) / n_updates\n \n return n_updates, sleep_time\n \n # get latest trade\n def _get_latest_trade_history(self, currency_pairs):\n \n # set empty df for appending\n df = pd.DataFrame()\n\n # get latest trade history for each pair\n for k in currency_pairs:\n \n # retrieve the date to start getting trade data from\n try:\n start_date = self._get_latest_trade_date(k)\n except:\n print('\\n\\nWARNING: Could not find Trade ID in Latest Trade ID dict. Please ensure that this is a new currency pair.\\n\\n')\n start_date = self._get_latest_trade_date_fallback(k)\n \n if self.verbose:\n print('Date of latest trade:', start_date)\n \n # get recent trade history\n tdf = self._get_full_trade_history(k, start_date)\n tdf['currency_pair'] = k\n df = df.append(tdf)\n\n # process data so that it mirrors polo (legacy formatting / structure)\n df = self._process_raw_bfx_trade_history(df)\n df = df.sort_values('date', ascending = True).copy()\n\n return df\n \n # update the trade history db\n def _update_raw_trade_history_db(self, trade_history_df):\n \n if self.verbose: print('\\nadding to db')\n \n # convert to list of dict for easy db update :)\n recs = trade_history_df.to_dict('records')\n\n # connect to db\n conn = sqlite3.connect('db/raw.db')\n c = conn.cursor()\n\n # add values to table using parsed data\n for r in recs:\n c.execute(\"INSERT OR IGNORE INTO trade_history VALUES (?,?,?,?,?,?,?,?)\",\n [r['global_trade_id'],\n r['trade_id'],\n r['date'],\n r['currency_pair'],\n r['type'],\n r['rate'],\n r['amount'],\n r['total']\n ]\n )\n\n # commit changes\n conn.commit()\n conn.close()\n\n print('Successfully added trades to raw db.\\n')\n \n # used as a fallback if the partial/latest trade history cannot be retrieved with help from trade id\n def get_trade_history_from_raw_db(self, cp, recent_only = False):\n \n if recent_only:\n gtid_start = self._get_gtid_start()\n \n # connect to db and load data\n conn = sqlite3.connect('db/raw.db')\n \n # set query based on whether or not there is a global trade id from which to start the query\n if not recent_only:\n get_data_query = '''\n SELECT date, rate, amount, global_trade_id\n FROM trade_history\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % cp\n \n elif recent_only:\n \n sub_query = '''\n SELECT *\n FROM trade_history\n WHERE global_trade_id>=%s\n ''' % gtid_start\n \n get_data_query = '''\n SELECT date, rate, amount, global_trade_id\n FROM (%s)\n WHERE currency_pair=\"%s\"\n AND trade_id=\"0\"\n ''' % (sub_query, cp)\n \n else:\n print('Invalid gtid_start, please enter None or an id (int).')\n return None\n\n # read into pandas\n df = pd.read_sql(get_data_query, conn)\n\n # close connection\n conn.close()\n\n return df\n\n # helper to get timedelta dynamically based off of candle being used\n def _get_timedelta(self):\n\n time_period = self.time_period.lower()\n\n # if candle is in minutes, split it and convert to seconds\n if 'min' in time_period:\n i = int(time_period.split('min')[0])\n sec = i * 60\n td = datetime.timedelta(seconds = sec)\n\n return td\n\n # if candle is in hours, split it and convert to seconds\n elif 'h' in time_period:\n i = int(time_period.split('h')[0])\n sec = i * 60 * 60\n td = datetime.timedelta(seconds = sec)\n\n return td\n\n # and if it's something new....\n else:\n print(time_period, 'is not recognized. Update with correct formatting (\"h\" or \"min\").')\n return None\n\n # helper to deduplicate a list whilst preserving order (unlike set)\n def _dedup_keep_order(self, seq):\n\n seen = set()\n seen_add = seen.add\n deduped = [x for x in seq if not (x in seen or seen_add(x))]\n\n return deduped\n\n def _chart_fillna(self, charts_df):\n \n if self.verbose: print('Some NaN values are found, scrubbing out.')\n\n # select all rows which have ANY NaN values\n nan_rows = charts_df[(charts_df['open'].isnull()) |\n (charts_df['high'].isnull()) |\n (charts_df['low'].isnull()) |\n (charts_df['close'].isnull()) |\n (charts_df['volume'].isnull())\n ].index.tolist()\n\n # add mean and median nan rows as well, as needed\n if self.inc_mean:\n nan_rows_mean = charts_df[charts_df['mean_trade_price'].isnull()].index.tolist()\n nan_rows += nan_rows_mean\n nan_rows = self._dedup_keep_order(nan_rows)\n if self.inc_median:\n nan_rows_median = charts_df[charts_df['median_trade_price'].isnull()].index.tolist()\n nan_rows += nan_rows_median\n nan_rows = self._dedup_keep_order(nan_rows)\n\n # for each of the null rows, take the data from the previous day and set volume to 0\n for row in nan_rows:\n delta = self._get_timedelta()\n charts_df.loc[row] = charts_df.loc[row - delta]\n charts_df.loc[row]['volume'] = 0\n\n return charts_df\n\n # process raw data to get OHLCV charts\n def _get_charts_from_raw(self, raw_trade_history_df, inc_mean = False, inc_median = False):\n\n # init mean and median inclusion\n # ... keeping the functionality, but it's really only useful in this function,\n # ... as the current processed table does not support either feature\n self.inc_mean = inc_mean\n self.inc_median = inc_median\n\n # convert date to dt\n raw_trade_history_df['date'] = pd.to_datetime(raw_trade_history_df['date'], unit = 's')\n raw_trade_history_df.index = raw_trade_history_df['date']\n raw_trade_history_df = raw_trade_history_df.drop('date', 1).copy()\n\n # get OHLCV charts\n charts = raw_trade_history_df['rate'].resample(self.time_period).ohlc()\n charts['volume'] = raw_trade_history_df['amount'].resample(self.time_period).sum().values\n\n # get the minimum trade id for each period -- used for quick db search (global trade id is pk)\n charts['min_global_trade_id'] = raw_trade_history_df['global_trade_id'].resample(self.time_period).min().values\n\n if self.inc_mean:\n charts['mean_trade_price'] = raw_trade_history_df['rate'].resample(self.time_period).mean().values\n if self.inc_median:\n charts['median_trade_price'] = raw_trade_history_df['rate'].resample(self.time_period).median().values\n\n # fill in any nans\n if charts.isnull().any().any():\n charts = self._chart_fillna(charts)\n\n return charts\n # converts a pandas dt str (they call it a timestamp, but it's not the timestamp in python's datetime),\n # that is based in the utc to the appropriate epoch time (timestamp). without this, the .timestep() method\n # assumes local tz (or that's how pandas is defining the tz on conversion)\n def _utc_timestamp(self, pd_utc_dt_str):\n return int(pd_utc_dt_str.replace(tzinfo=datetime.timezone.utc).timestamp())\n \n # pid is the pk and is a concatenatation of the pair and epoch time for easy update\n def _create_pid(self, chart_xdf):\n \n cp_array = chart_xdf.currency_pair.apply(lambda x: x.replace('_','').lower()).values.copy()\n timestamp_array = pd.Series(chart_xdf.index).apply(lambda x: str(self._utc_timestamp(x))).values.copy()\n pid = cp_array + '_' + timestamp_array\n\n return pid\n \n # process the stacked/appended/concatenated pair charts for the processed db\n def _process_charts_for_db(self, chart_xdf):\n\n # add pid and date cols\n chart_xdf['pid'] = self._create_pid(chart_xdf).copy()\n chart_xdf['date'] = pd.Series(chart_xdf.index).apply(lambda x: str(self._utc_timestamp(x))).values.copy()\n\n return chart_xdf\n \n # get the earliest of the latest gtids\n def _get_gtid_start(self):\n\n # get latest data from processed db\n df = self.get_processed_charts_from_db()\n\n # get the earliest trade ID from the last period, and then the period before that\n # this is to prevent incomplete trading periods in beteen updates\n last_gtid = int(df.groupby('currency_pair').max().min_global_trade_id.min())\n df = df[df.min_global_trade_id < last_gtid]\n gtid_start = int(df.groupby('currency_pair').max().min_global_trade_id.min())\n\n return gtid_start\n \n \n \n \n ############\n # EXTERNAL METHODS\n ###\n \n \n # 30 MIN ONLY TIME INVERVALS ONLY (!!!)\n # get the time at which the update trade history loop should be broken\n def get_period_end(self):\n \n '''\n TODO: RE-WRITE IT SO THAT OTHER TIME INTERVALS ARE ACCOMODATED\n '''\n \n # get the current time as a list\n now = [int(i) for i in datetime.datetime.now().strftime('%Y %m %d %H %M').split()]\n \n # determine which part of the hour we are currently in\n if (int(now[4]) - 30) < 0:\n now[4] = 30\n else:\n now[3] += 1\n # if the period end is during midnight, increase the\n # day by one and set it so it is 24hr time compatible\n if now[3] == 24:\n now[2] += 1\n now[3] = 0\n now[4] = 0\n \n # convert period end to epoch\n y, M, d, h, m = now\n period_end = int(datetime.datetime(y, M, d, h, m).timestamp())\n \n return period_end\n \n # method to update raw trade history db\n def update_trade_history(self, currency_pairs, reset_period_end = True, use_break = False):\n \n # need an option for the final post-period update\n if reset_period_end: self.period_end = self.get_period_end()\n \n # loop through each cp and add latest trade history to db\n for cp in currency_pairs:\n\n # get the latest trades and add to db\n df = self._get_latest_trade_history([cp])\n df = df[df.index < self.period_end].copy()\n self._update_raw_trade_history_db(df)\n self.pairs_updated.add(cp)\n\n # save the new last trade IDs\n self.last_trade_id_dict[cp] = int(df.iloc[-1,:].global_trade_id)\n \n del df\n \n # break the loop if the current trading period has ended\n if use_break and self._epoch_now() > self.period_end: break\n \n # and save the trade IDs to a csv for next time\n self._save_last_trade_id_dict(self.last_trade_id_dict)\n \n return None\n \n # method to update the processed trade history / charts db\n def update_processed_db(self, chart_xdf, process = True):\n \n if process:\n chart_xdf = self._process_charts_for_db(chart_xdf).copy()\n \n if self.verbose: print('\\nadding to db')\n\n # convert to list of dict for easy db update :)\n recs = chart_xdf.to_dict('records')\n\n # connect to db\n conn = sqlite3.connect('db/processed.db')\n c = conn.cursor()\n \n # build query and add to table\n # (there should be one or two period overlap, so use REPLACE)\n base_query = 'INSERT OR REPLACE INTO %s VALUES (?,?,?,?,?,?,?,?,?)' % self.processed_table_name\n\n for r in recs:\n c.execute(base_query,\n [r['pid'],\n r['date'],\n r['currency_pair'],\n r['min_global_trade_id'],\n r['open'],\n r['high'],\n r['low'],\n r['close'],\n r['volume']\n ]\n )\n \n # commit changes\n conn.commit()\n conn.close()\n\n print('Successfully updated processed db.')\n \n # retrieves, processes, and inserts all recent (i.e. hasn't\n # been added to processed db) trade history into processed db\n def add_raw_trade_history_to_processed_db(self, recent_only = True):\n \n # set empty dataframe for appending\n xdf = pd.DataFrame()\n\n # retrieve and process raw trade history for each pair\n for cp in self.currency_pairs:\n \n if self.verbose: print('processing', cp)\n df = self.get_trade_history_from_raw_db(cp, recent_only = recent_only)\n df = self._get_charts_from_raw(df).copy()\n df['currency_pair'] = cp\n xdf = xdf.append(df)\n \n # process charts and add to processed db\n self.update_processed_db(xdf)\n \n return None\n \n # load and format the processed data from the charts table\n def get_processed_charts_from_db(self):\n \n # load data from db\n conn = sqlite3.connect('db/processed.db')\n \n q = '''\n SELECT date, open, high, low, close, volume,\n currency_pair, min_global_trade_id\n FROM %s;\n ''' % self.processed_table_name\n \n df = pd.read_sql(q, conn)\n conn.close()\n \n # add dt index\n df.index = pd.to_datetime(df.date, unit = 's')\n df = df.drop('date', 1)\n \n return df\n \n # this will probably change depending on the algorithm, but this reformats / restructures\n # the data so that each column is a pair/feature combo (usdtbtc_close, usdteth_open, etc.)\n def reformat_for_online_algo(self, df, cols_to_include, base_index = 'USDT_BTC'):\n \n # filter down to cols needed\n df = df[cols_to_include + ['currency_pair']].copy()\n\n # init a df with dt index (BTC is default cuz it prob has the most data and is usually used)\n xdf = pd.DataFrame(index = df[df.currency_pair == base_index].index)\n\n # filter down to specific col, clean up name, and join with aggregate df\n for col in cols_to_include:\n for cp in self.currency_pairs:\n tdf = pd.DataFrame(df[df.currency_pair == cp][col]).copy()\n new_cols = [cp.lower().replace('_','') + '_' + col for col in tdf.columns.tolist()]\n tdf.columns = new_cols\n xdf = xdf.join(tdf, how = 'left')\n\n xdf = xdf.dropna().copy()\n\n return xdf\n \n # to be used when starting the bot, this gets the trade history and processes it for trading\n def run(self, update_interval = 600):\n \n self.pairs_updated = set()\n \n # make sure each pair is updated at least once :)\n while self.pairs_updated != self.pairs_to_update:\n \n # set trading period end and how many times history is retrieved each period\n self.period_end = self.get_period_end()\n n_updates, sleep_time = self._n_updates(update_interval = update_interval)\n \n # get trade history until trading period is over\n for i in range(n_updates):\n \n if self.verbose: print('Period End:', self.period_end)\n \n # update the trade history and break if it is the end of the period\n self.update_trade_history(currency_pairs = self.currency_pairs, use_break = True)\n \n # let's figure out where to go from here, shall we?\n now = self._epoch_now()\n if now > self.period_end: break\n if (self.period_end - now) > (sleep_time + 30):\n if self.verbose:\n print('\\n\\nTime left before end of period:', (self.period_end - now))\n print('Sleeping for:', sleep_time, 'seconds\\n\\n')\n sleep(sleep_time)\n \n # if loop ends early, sleep until end of period\n if self.verbose: print('Sleeping until end of the trading period...')\n sleep(self.period_end - now + 2)\n \n # update once more, process, and retrieve\n self.update_trade_history(currency_pairs = currency_pairs, reset_period_end = False)\n self.add_raw_trade_history_to_processed_db()\n latest_charts = self.get_processed_charts_from_db().copy()\n \n return latest_charts\n\n\n\n\n\n\n#####################\n#\n# BFX API Wrapper\n#\n########\n\nclass BFXClient(object):\n \n def __init__(self, key, secret, *args, **kwargs):\n '''\n Stores the username, key, and secret which is used when making POST\n requests to Bitfinex.\n '''\n \n self.BASE_URL = \"https://api.bitfinex.com\"\n self.KEY = key\n self.SECRET = secret\n self.cp_map = get_cp_map()\n \n \n def _nonce(self):\n '''\n Used in authentication. Returns a nonce that always needs to be\n increasing (essentially a unix timestamp)\n '''\n return str(int(round(time.time() * 1000)))\n \n \n def _verbose(self, **kwargs):\n '''\n Helper method to print the endpoint and payload\n '''\n path = kwargs['path']\n payload = kwargs['payload']\n \n print('\\nEndpoint:')\n print(self.BASE_URL + path)\n print('\\nPayload:')\n print(payload)\n \n \n def _headers(self, path, nonce, body):\n \n # create signature\n signature = \"/api\" + path + nonce + body\n \n # byte encode secret and sig\n h = hmac.new(self.SECRET.encode(), signature.encode(), hashlib.sha384)\n signature = h.hexdigest()\n\n return {\n \"bfx-nonce\": nonce,\n \"bfx-apikey\": self.KEY,\n \"bfx-signature\": signature,\n \"content-type\": \"application/json\"\n }\n \n \n def _post(self, **kwargs):\n \n # init args\n path = kwargs['path']\n verbose = kwargs['verbose']\n \n # build request\n nonce = self._nonce()\n body = {}\n rawBody = json.dumps(body)\n headers = self._headers(path, nonce, rawBody)\n \n # print payload for debugging\n if verbose:\n print('\\nEndpoint:')\n print(self.BASE_URL + path)\n print('\\nPayload:')\n print(\"{\"+self.BASE_URL + path + \", headers=\" + str(headers) + \", data=\" + rawBody + \", verify=True)}\")\n \n # post request\n r = requests.post(self.BASE_URL + path, headers = headers, data = rawBody, verify = True)\n \n # print status\n if r.status_code == 200:\n print('\\nSuccess!\\n')\n return r.json()\n else:\n print(r.status_code)\n print(r)\n return None\n \n \n def add_cp_mapping(self, standard_naming_key, bfx_naming_value):\n '''\n Add a new k/v to the bfx symbol map\n '''\n self.cp_map[standard_naming_key] = bfx_naming_value\n print('Successfully added', standard_naming_key)\n \n \n def v1_payload(self, payload):\n '''\n Used to build / pack the payload for Version 1 (v1) of the API.\n v1 is usually used when an action requires the use of the websocket on v2.\n '''\n \n # sign & pack payload\n j = json.dumps(payload)\n b = bytes(j, 'utf-8')\n data = base64.standard_b64encode(b)\n h = hmac.new(self.SECRET.encode(), data, hashlib.sha384)\n signature = h.hexdigest()\n \n packed = {\n \"X-BFX-APIKEY\": self.KEY,\n \"X-BFX-SIGNATURE\": signature,\n \"X-BFX-PAYLOAD\": data\n }\n\n return packed\n \n \n def v1_post(self, path, payload, verify = True):\n '''\n POST helper for v1 of the API\n '''\n \n # pack & sign\n signed_payload = self.v1_payload(payload)\n \n # post request\n r = requests.post(self.BASE_URL + path,\n headers = signed_payload,\n verify = verify\n )\n response = r.json()\n \n return response\n \n \n #########\n # API Actions\n ###\n \n def active_orders(self, verbose = False):\n '''\n Get the active orders for the current user.\n '''\n return self._post(path = '/v2/auth/r/orders', verbose = verbose)\n \n \n def new_order_v1(self, amount, price, side, order_type, symbol,\n exchange = 'bitfinex', verbose = False, print_response = True):\n '''\n Uses v1 API endpoint.\n Create a new order for a specified asset.\n '''\n # set path and build payload\n path = '/v1/order/new'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce(),\n \"symbol\": symbol,\n \"amount\": amount,\n \"price\": price,\n \"exchange\": exchange,\n \"side\": side,\n \"type\": order_type\n }\n \n # post order\n response = self.v1_post(path, payload)\n if verbose: self._verbose(path, payload)\n \n # qa / print response\n try:\n response['order_id']\n print('Success!')\n if print_response:\n return response\n except:\n return response['message']\n \n \n def new_order(self):\n '''\n Uses v2 web socket API.\n Create a new order for a specified asset.\n '''\n pass\n \n \n def get_tickers(self, currency_pairs, use_cp_map = True):\n '''\n Get latest ticker for a specified currency pair.\n '''\n # format symbol for api\n symbol_str = ''\n for cp in currency_pairs:\n if use_cp_map:\n symbol_str += '%s,' % self.cp_map[cp]\n else:\n symbol_str += '%s,' % cp\n symbol_str = symbol_str[:-1]\n \n # call api and add results to df\n path = '/v2/tickers?symbols=%s' % symbol_str\n endpoint = self.BASE_URL + path\n ticker_df = pd.read_json(endpoint)\n ticker_cols = ['symbol', 'bid', 'bid_size', 'ask',\n 'ask_size', 'daily_change', 'daily_change_perc',\n 'last_price', 'volume', 'high', 'low'\n ]\n ticker_df.columns = ticker_cols\n \n # add standard symbol to index\n if use_cp_map:\n ticker_df.index = currency_pairs\n else:\n ticker_df.index = [self.cp_map[cp] for cp in currency_pairs]\n \n return ticker_df\n \n \n def get_last_price(self, currency_pairs):\n '''\n Get a Series of last prices for a list of currencies\n '''\n return self.get_tickers(currency_pairs).last_price\n \n \n def get_balances(self, wallet = 'exchange', verbose = False):\n '''\n Get the current balances for each asset owned.\n \n Wallet Names:\n - Exchange: 'exchange'\n - Margin: 'trading'\n - Funding: 'deposit'\n \n '''\n # set path and payload\n path = '/v1/balances'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce()\n }\n \n # post order\n response = self.v1_post(path, payload)\n if verbose: self._verbose(path = path, payload = payload)\n \n # add to df and filter to wallet type\n balances = pd.DataFrame(response)\n balances = balances[balances.type == wallet][['currency', 'amount', 'available']]\n balances.index = balances.currency.str.upper()\n balances = balances.drop('currency', 1)\n \n return balances\n \n \n def get_wallet_value(self, wallet = 'exchange'):\n '''\n Return the USD value of the specified wallet. Based on the\n last price each asset was traded at.\n '''\n # get current balances for specified wallet\n balances = self.get_balances(wallet = wallet).amount\n \n # return a balance of 0 if there are no assets in the wallet\n if len(balances) == 0 or balances.values.astype('float').sum() < 1:\n return 0.0\n \n # format symbol naming for bfx and joining\n portfolio_bfx_symbols = ['t' + asset.upper() + 'USD' for asset in balances.index]\n balances.index = portfolio_bfx_symbols\n \n # exception for not having USDT in balance\n try: portfolio_bfx_symbols.remove('tUSDUSD')\n except: pass\n\n # get the ticker for each pair\n last_price = self.get_tickers(portfolio_bfx_symbols, use_cp_map = False)[['symbol', 'last_price']].copy()\n \n # join data\n last_price.index = last_price.symbol\n last_price = last_price.drop('symbol', 1)\n last_price['balances'] = balances\n \n # calc value of crypto holdings\n crypto_value = last_price.last_price.astype('float') * last_price.balances.astype('float')\n \n # and then add tether (it's dropped when joining with last_price so you have to add it here/now)\n try: wallet_value = float(crypto_value.sum() + float(balances['tUSDUSD']))\n except: wallet_value = float(crypto_value.sum())\n \n return wallet_value\n \n \n def get_account_value(self):\n '''\n Return the total USDT value of the account\n '''\n wallet_types = {'exchange': 'exchange', 'margin': 'trading', 'funding': 'deposit'}\n account_values = {}\n for k in wallet_types:\n print('Fetching', k)\n account_values[k] = float(self.get_wallet_value(wallet_types[k]))\n \n account_values = pd.DataFrame([account_values])\n account_values['total'] = float(account_values.values.sum())\n account_values = account_values.T.copy()\n account_values.columns = ['USD']\n \n return account_values\n \n \n def transfer_between_wallets(self, amount, currency, from_wallet, to_wallet, verbose = False):\n '''\n Transfer funds from one wallet to another (i.e. Funding to Margin)\n Wallet types: 'exchange', 'trading', 'deposit'\n \n PAYLOAD EXAMPLE:\n amount: \"1.0\"\n currency: \"BTC\"\n walletfrom: \"trading\"\n walletto: \"exchange\"\n \n '''\n # set path and build payload\n path = '/v1/transfer'\n payload = {\n \"request\": path,\n \"nonce\": self._nonce(),\n \"amount\": amount,\n \"currency\": currency,\n \"walletfrom\": from_wallet,\n \"walletto\": to_wallet\n }\n \n # post transfer\n response = self.v1_post(path, payload)\n #if verbose: self._verbose(path, payload)\n \n print(response)\n return None\n\n\n\n#############\n#\n# Actual trader which specifically handles the balancing of the portfolio\n#\n########\n\nclass Trader(BFXClient):\n \n def __init__(self, key, secret):\n \n super(Trader, self).__init__(key, secret)\n #self.type = type_\n \n # abnormal tickers that are shortened by bfx\n self.abnormal_tickers = {'DASH': 'DSH',\n 'IOTA': 'IOT'\n }\n \n # a somewhat specific helper to convert a dict with currency\n # pairs as keys into a dict with the *BFX* ticker symbol\n def _pair_dict_to_ticker_dict(self, pair_dict, ext_ticker_map = {}):\n\n # edit keys in target balance so that they match the index of current balance\n for k in pair_dict:\n pair_dict[k.replace('USDT_', '')] = pair_dict.pop(k)\n\n # some symbols are greater than three chars and bfx shortens them, fix that here :)\n if len(ext_ticker_map) > 0:\n for k in ext_ticker_map:\n pair_dict[ext_ticker_map[k]] = pair_dict.pop(k)\n\n return pair_dict\n\n def get_new_portfolio(self, capital, asset_weights, trading_fee = 0.003):\n '''\n capital: amount of capital to be invested\n asset_weights: Series; currency pair index, and weight / allocation per asset\n '''\n \n capital_per_asset = asset_weights * capital\n capital_per_asset *= (1 - trading_fee)\n last_price = self.get_last_price(asset_weights.index.tolist())\n\n # and get the quantity of each asset\n porfolio = capital_per_asset / last_price\n\n # return all :D\n return porfolio, capital_per_asset\n\n # calculate how much of each coin we need to buy / sell to balance portfolio\n def needed_to_balance(self, target_balance, additional_cp_mapping = {}):\n \n current_balance = self.get_balances()\n \n # check if all owned assets are available\n if (current_balance.amount.astype('float') -\n current_balance.available.astype('float')\n ).sum() > 0:\n print('Available Balance does not equal Total Balance. Please close Open Orders before proceeding.')\n return None\n\n # convert pairs into bfx-client-friendly symbols\n target_balance = self._pair_dict_to_ticker_dict(target_balance, additional_cp_mapping)\n\n # add to df\n current_balance['target_balance'] = pd.Series(target_balance)\n balances = current_balance.copy()\n balances = balances.astype('float')\n del current_balance, target_balance\n\n # add delta\n balances['assets_needed'] = (balances.target_balance - balances.available).round(4)\n\n return balances\n \n def calculate_rebalance(self, asset_weights):\n \n # get the number of each coin needed and the amount of capital for each asset\n porfolio, capital_per_asset = get_new_portfolio(capital = self.get_wallet_value(),\n asset_weights = asset_weights)\n \n # get a df of assets needed and sort by cost\n assets_needed = needed_to_balance(target_balance = dict(portfolio.round(4).to_dict()),\n ext_ticker_map = self.abnormal_tickers)\n \n # add to df\n assets_needed['price'] = pd.Series(self._pair_dict_to_ticker_dict(dict(last_price.to_dict()),\n abnormal_tickers))\n assets_needed['order_cost'] = assets_needed.assets_needed * assets_needed.price\n assets_needed = assets_needed.sort_values('order_cost')\n \n return assets_needed\n \n \n def rebalance_portfolio(self, asset_weights,\n fill_order_premium = 0.0, order_minimum = 25, print_api_response = False):\n \n # calculate what is needed per asset\n asset_balance_df = self.calculate_rebalance(asset_weights).copy()\n\n # drop any orders that are for less than minimum\n asset_balance_df = asset_balance_df[abs(asset_balance_df.order_cost) >= order_minimum].copy()\n\n print('Balancing the following assets:', asset_balance_df.index.tolist())\n\n # loop through each currency and create an order\n for asset in asset_balance_df.index:\n \n print('Balancing', asset)\n \n a = asset_balance_df.loc[asset]\n pair = asset.lower() + 'usd'\n amount = str(abs(a.assets_needed))\n \n if a.assets_needed < 0:\n side = 'sell'\n price = str(a.price * (1 - fill_order_premium))\n \n if a.assets_needed > 0:\n side = 'buy'\n price = str(a.price * (1 + fill_order_premium))\n \n # place order\n self.new_order_v1(amount = amount,\n price = price,\n side = side,\n order_type = 'exchange limit',\n symbol = pair,\n exchange = 'bitfinex',\n verbose = False,\n print_response = print_api_response\n )\n\n sleep(3)\n\n print('\\n\\nSuccessfully balanced portfolio\\n')","sub_path":"rltrader/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":42957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"96984683","text":"#!/usr/bin/env python3\n\"\"\"\nProject Name: github-latest\nFile Name: main.py\nAuthor: Travis Brackney\nClass: Python 230 - Self paced online\nDate Created 10/6/2019\nPython Version: 3.7.2\n\"\"\"\n\n\nimport sys\nimport json\n\nimport requests\n\n# Use Like python githubber.py JASchilz\n# (or another user name)\n\n\ndef get_event_time(username):\n base_url = \"https://api.github.com/\"\n events_url = f\"{base_url}users/{username}/events\"\n\n response = requests.get(events_url)\n parsed = json.loads(response.text)\n return parsed[0]['created_at']\n\n\nif __name__ == \"__main__\":\n username = sys.argv[1]\n\n # Done:\n #\n # 1. Retrieve a list of \"events\" associated with the given user name\n # 2. Print out the time stamp associated with the first event in that list.\n timestamp = get_event_time(username)\n\n print(timestamp)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"482034395","text":"# -*- coding:utf-8 -*-\n\nclass Solution:\n \"\"\"\n Problem:\n 汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。\n 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。\n 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。\n 是不是很简单?OK,搞定它!\n -----------------------------------------\n Think:\n 1、最开始的想法是,如果移动是位数没有超过字符串的位数,那么可以直接切割文本,然后拼接到最后。\n 如果左移的位数超过了字符串的位数,那么 n % length 就是需要左移的位数。\n 2、假设左移动3位置,不采用辅助空间,a = \"abc\",b = \"XYZdef\"反转为;\"cba\"\"fedZYX\"\n 然后再进行反转\n\n -----------------------------------------\n Idea:\n 1、直接计算左移的位数 n % length,然后切割字符串\n 2、通过3次反转获得需要的字符串,假设左移动3位置,不采用辅助空间,a = \"abc\",\n b = \"XYZdef\"反转为;\"cba\"\"fedZYX\",然后把cbafedZYX反转成:\n XYZdefabc\n\n\n -----------------------------------------\n Code[1]:\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n leftmove = n % len(s)\n newtail = s[:leftmove]\n newhead = s[leftmove:]\n return newhead + newtail\n\n -----------------------\n 运行时间:33ms\n 占用内存:5624k\n 量级:O(n)\n 空间:需要额外的空间n\n 优点:容易想到和实现\n 缺点:当字符串非常大时,需要额外的空间\n\n -----------------------------------------\n Code[2]:\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n slength = len(s)\n n = n % slength\n s = list(s) # 为了让字��串可以反转,转为list\n s = self.reversal(s,0,n-1)\n s = self.reversal(s,n,slength-1)\n s = self.reversal(s,0,slength-1)\n return \"\".join([i for i in s])\n\n def reversal(self,s,start,end):\n while start < end:\n s[start],s[end] = s[end],s[start]\n start += 1\n end -= 1\n return s\n\n -----------------------\n 运行时间:48ms\n 占用内存:5632k\n 量级:O(n)\n 空间:不需要额外的空间,但是由于python没有可变字符串,所以转为list纯粹实现下反转思想\n 优点:当字符串非常大时,不需要额外的空间,容易实现\n 缺点:不容易想到\n\n \"\"\"\n def LeftRotateString(self, s, n):\n if (s is \"\"):\n return \"\"\n slength = len(s)\n n = n % slength\n s = list(s) # 为了让字符串可以反转,转为list\n s = self.reversal(s,0,n-1)\n s = self.reversal(s,n,slength-1)\n s = self.reversal(s,0,slength-1)\n return \"\".join([i for i in s])\n\n def reversal(self,s,start,end):\n while start < end:\n s[start],s[end] = s[end],s[start]\n start += 1\n end -= 1\n return s\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n print(solution.LeftRotateString(\"abcXYZdef\",3))\n","sub_path":"code/train/箭指Offer/src/左旋转字符串.py","file_name":"左旋转字符串.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"480665592","text":"from collections import defaultdict\nfrom decimal import Decimal\nfrom _datetime import datetime, timedelta\nfrom enum import Enum\nimport math\nimport random\nimport re\nimport requests\nimport time\n\nfrom vnpy.app.algo_trading import AlgoTemplate\nfrom vnpy.trader.utility import round_to\nfrom vnpy.trader.constant import Direction, Status, OrderType\nfrom vnpy.trader.object import AccountData, OrderData, TradeData, TickData\nfrom vnpy.trader.engine import BaseEngine\n\n\nclass LiquidMiningAlgo(AlgoTemplate):\n \"\"\"\"\"\"\n display_name = \"交易所 流动性挖坑\"\n\n default_setting = {\n \"vt_symbol\": \"\",\n \"price_offset\": 0.05,\n \"price_offset_max\": 0.1,\n \"volume\": 2,\n \"max_volume_ratio\": 0,\n \"interval\": 3,\n \"min_order_level\": 1,\n \"min_order_volume\": 0,\n \"sell_max_volume\": 0,\n \"buy_max_volume\": 0,\n \"auto_trade_volume\": 310,\n \"sell_max_ratio\": 1,\n \"buy_max_ratio\": 1,\n \"reward_ratio\": 0.01,\n \"min_pos\": 50000,\n \"max_pos\": 50000,\n }\n\n variables = [\n \"pos\",\n \"timer_count\",\n \"vt_ask_orderid\",\n \"vt_bid_orderid\"\n ]\n\n def __init__(\n self,\n algo_engine: BaseEngine,\n algo_name: str,\n setting: dict\n ):\n \"\"\"\"\"\"\n super().__init__(algo_engine, algo_name, setting)\n\n # Parameters\n self.vt_symbol = setting[\"vt_symbol\"]\n self.price_offset = setting[\"price_offset\"]\n self.price_offset_max = setting[\"price_offset_max\"]\n self.volume = setting[\"volume\"]\n self.max_volume_ratio = setting.get(\"max_volume_ratio\", 0)\n assert 0 <= self.max_volume_ratio <= 1\n self.interval = setting[\"interval\"]\n self.min_order_level = setting[\"min_order_level\"]\n self.min_order_volume = setting[\"min_order_volume\"]\n self.sell_max_volume = setting[\"sell_max_volume\"]\n self.buy_max_volume = setting[\"buy_max_volume\"]\n self.auto_trade_volume = setting[\"auto_trade_volume\"]\n self.sell_max_ratio = setting[\"sell_max_ratio\"]\n self.buy_max_ratio = setting[\"buy_max_ratio\"]\n self.reward_ratio = setting[\"reward_ratio\"]\n self.min_pos = setting[\"min_pos\"]\n self.max_pos = setting[\"max_pos\"]\n self.enable_ioc = setting.get(\"enable_ioc\", False)\n self.ioc_intervel = setting.get(\"ioc_interval\", self.interval)\n\n # validate setting\n assert self.price_offset <= self.price_offset_max\n assert 0 <= self.min_order_level <= 5\n\n # Variables\n self.pos = 0\n self.timer_count = 0\n self.vt_ask_orderid = \"\"\n self.vt_ask_price = 0.0\n self.vt_bid_orderid = \"\"\n self.vt_bid_price = 0.0\n self.origin_ask_price = 0.00000002\n self.origin_bid_price = 0.00000001\n self.last_ask_price = 0.00000002\n self.last_bid_price = 0.00000001\n self.last_ask_volume = 0.0\n self.last_bid_volume = 0.0\n self.total_ask_volume = 0.0\n self.total_bid_volume = 0.0\n self.ask_order_level = 0\n self.bid_order_level = 0\n\n self.last_tick = None\n self._init_market_accounts(self.vt_symbol)\n\n self.subscribe(self.vt_symbol)\n self.put_parameters_event()\n self.put_variables_event()\n\n def _init_market_accounts(self, active_vt_symbol):\n SYMBOL_SPLITTER = re.compile(r\"^(\\w+)[-:/]?(BTC|ETH|BNB|XRP|USDT|USDC|USDS|TUSD|PAX|DAI)$\")\n market_token_pair = active_vt_symbol.split('.')[0]\n active_market = active_vt_symbol.split('.')[1]\n if not market_token_pair or not active_market:\n self.algo_engine.main_engine.write_log(f\"ERROR: parse active_vt {active_vt_symbol} failed\")\n return False\n\n token_pair_match = SYMBOL_SPLITTER.match(market_token_pair.upper())\n if not token_pair_match:\n self.algo_engine.main_engine.write_log(f\"ERROR: parse symbol {market_token_pair} failed\")\n return False\n\n self.market_vt_tokens = [\n f\"{active_market}.{token_pair_match.group(1)}\",\n f\"{active_market}.{token_pair_match.group(2)}\"\n ]\n self.current_balance = {}\n self._update_current_balance()\n\n def _update_current_balance(self):\n for vt_token in self.market_vt_tokens:\n user_account = self.algo_engine.main_engine.get_account(vt_token)\n if type(user_account) is not AccountData:\n return False\n self.current_balance[vt_token] = user_account.balance\n return True\n\n def on_start(self):\n \"\"\"\"\"\"\n random.seed(time.time())\n self.write_log(f\"开始流动性挖矿: {self.price_offset}, {self.price_offset_max}, {self.volume}, {self.interval}, {self.min_order_level}, {self.min_order_volume}, {self.sell_max_volume}, {self.buy_max_volume}, {self.auto_trade_volume}\")\n self.pricetick = self.algo_engine.main_engine.get_contract(self.vt_symbol).pricetick\n self.volumetick = self.algo_engine.main_engine.get_contract(self.vt_symbol).min_volume\n assert self.pricetick > 0\n\n def on_tick(self, tick: TickData):\n \"\"\"\"\"\"\n self.last_tick = tick\n\n market_price = (tick.ask_price_1 + tick.bid_price_1) / 2\n if self.vt_ask_orderid != \"\":\n self.ask_order_alive_tick += 1\n # if time to kill\n cancel_ask = False\n if self.enable_ioc and self.ask_order_alive_tick > self.ioc_intervel:\n self.write_log(f\"卖单{self.vt_ask_orderid}有效时间{self.ask_order_alive_tick} ticks > {self.ioc_intervel},取消\")\n cancel_ask = True\n if not cancel_ask:\n total_ask_volume = 0\n for num_level in range(1, 6):\n ask_price = getattr(tick, f\"ask_price_{num_level}\")\n if 0 < ask_price < self.last_ask_price:\n total_ask_volume += getattr(tick, f\"ask_volume_{num_level}\")\n # min_ask_price = getattr(tick, f\"ask_price_{self.ask_order_level}\") if self.ask_order_level > 0 else market_price\n # vt_ask_price = round_to(min_ask_price + self.pricetick, self.pricetick)\n vt_ask_price = getattr(tick, f\"ask_price_1\")\n if self.vt_ask_price < vt_ask_price:\n cancel_ask = True\n self.write_log(f\"当前卖单{self.vt_ask_price} 低于最新卖{self.ask_order_level}价 {vt_ask_price},取消\")\n elif self.vt_ask_price > vt_ask_price:\n cancel_ask = True\n self.write_log(f\"当前卖单{self.vt_ask_price} 高于最新卖{self.ask_order_level}价 {vt_ask_price},取消\")\n elif abs(self.total_ask_volume - total_ask_volume) > (self.total_ask_volume / 2):\n cancel_ask = True\n self.write_log(f\"---> 当前卖单{self.vt_ask_price} 取消,因为之前的订单量发生了变化\")\n if cancel_ask:\n self.cancel_order(self.vt_ask_orderid)\n # self.ask_order_alive_tick = 0\n\n if self.vt_bid_orderid != \"\":\n self.bid_order_alive_tick += 1\n # if time to kill\n cancel_bid = False\n if self.enable_ioc and self.bid_order_alive_tick > self.ioc_intervel:\n self.write_log(f\"买单{self.vt_bid_orderid}有效时间{self.bid_order_alive_tick} ticks > {self.ioc_intervel},取消\")\n cancel_bid = True\n if not cancel_bid:\n total_bid_volume = 0\n for num_level in range(1, 6):\n bid_price = getattr(tick, f\"bid_price_{num_level}\")\n if bid_price > self.last_bid_price:\n total_bid_volume += getattr(tick, f\"bid_volume_{num_level}\")\n # max_bid_price = getattr(tick, f\"bid_price_{self.bid_order_level}\") if self.bid_order_level > 0 else market_price\n # vt_bid_price = round_to(max_bid_price - self.pricetick, self.pricetick)\n vt_bid_price = getattr(tick, f\"bid_price_1\")\n if self.vt_bid_price > vt_bid_price:\n cancel_bid = True\n self.write_log(f\"当前买单{self.vt_bid_price} 高于最新买{self.bid_order_level}价 {vt_bid_price},取消\")\n elif self.vt_bid_price < vt_bid_price:\n cancel_bid = True\n self.write_log(f\"当前买单{self.vt_bid_price} 低于最新买{self.bid_order_level}价 {vt_bid_price},取消\")\n elif abs(self.total_bid_volume - total_bid_volume) > (self.total_bid_volume / 2):\n cancel_bid = True\n self.write_log(f\"---> 当前买单{self.vt_bid_price} 取消,因为之前的订单量发生了变化\")\n if cancel_bid:\n self.cancel_order(self.vt_bid_orderid)\n # self.bid_order_alive_tick = 0\n\n def on_timer(self):\n \"\"\"\"\"\"\n if not self.last_tick:\n return\n\n if self.pos < self.min_pos or self.pos > self.max_pos:\n self.cancel_all()\n self.write_log(f\"当前持仓: {self.pos} 超出[{self.min_pos}, {self.max_pos}]范围,停止流动性挖矿\")\n return\n\n self.timer_count += 1\n if self.timer_count < self.interval:\n self.put_variables_event()\n return\n self.timer_count = 0\n self.write_log(f\"当前余额 {self.current_balance}, 持仓 {self.pos}\")\n\n if not self._update_current_balance():\n self.write_log(f\"查询余额失败,上次余额: [{self.current_balance}]\")\n return\n\n use_max_volume = self.max_volume_ratio > 0\n max_volume_ratio = self.max_volume_ratio\n market_price = (self.last_tick.ask_price_1 + self.last_tick.bid_price_1) / 2\n if self.vt_ask_orderid == \"\":\n self.ask_order_level = 0\n for num_level in range(self.min_order_level, 0, -1):\n ask_price = getattr(self.last_tick, f\"ask_price_{num_level}\")\n if 0 < ask_price < market_price * (1 + self.reward_ratio * 0.99):\n self.ask_order_level = num_level\n break\n if self.ask_order_level > 0:\n total_ask_volume = 0\n for num_level in range(1, self.ask_order_level + 1):\n total_ask_volume += getattr(self.last_tick, f\"ask_volume_{num_level}\")\n if total_ask_volume != self.last_ask_volume:\n one_ask_price = getattr(self.last_tick, f\"ask_price_1\")\n one_ask_volume = getattr(self.last_tick, f\"ask_volume_1\")\n min_ask_price = getattr(self.last_tick, f\"ask_price_{self.ask_order_level}\") if self.ask_order_level > 0 else market_price\n vt_ask_price = round_to(min_ask_price + self.pricetick, self.pricetick)\n if self.origin_ask_price == 0.00000002:\n self.origin_ask_price = vt_ask_price\n ask_condition0 = self.last_ask_price == 0.00000002\n ask_condition1 = (self.last_ask_price * (1 - self.price_offset)) < vt_ask_price < (self.last_ask_price * (1 + self.price_offset))\n ask_condition2 = vt_ask_price > (self.origin_ask_price * (1 - self.price_offset_max))\n ask_condition8 = one_ask_price < (self.origin_ask_price * (1 - self.price_offset_max * 2))\n self.write_log(f\"---> 流动性挖矿卖出condition1: {ask_condition1}, condition2: {ask_condition2}\")\n if ask_condition0 or (ask_condition1 and ask_condition2):\n self.last_ask_price = vt_ask_price\n self.vt_ask_price = one_ask_price\n self.total_ask_volume = total_ask_volume\n max_volume = self.current_balance[self.market_vt_tokens[0]] * self.sell_max_ratio\n if 0 < self.sell_max_volume < max_volume:\n max_volume = self.sell_max_volume\n min_volume = self.volume * total_ask_volume\n if self.min_order_volume > 0 and min_volume < self.min_order_volume:\n min_volume = self.min_order_volume\n volume = min_volume if not use_max_volume else max_volume * max_volume_ratio\n if volume >= max_volume:\n volume = max_volume\n self.last_ask_volume = round_to(volume - self.volumetick, self.volumetick)\n self.write_log(f\"流动性挖矿卖出价格: {vt_ask_price}, 量: {self.last_ask_volume}\")\n self.vt_ask_orderid = self.sell(self.vt_symbol, vt_ask_price, self.last_ask_volume)\n self.ask_order_alive_tick = 0\n elif ask_condition8 and one_ask_volume < self.auto_trade_volume:\n self.write_log(f\"---> 流动性挖矿买入低价one_ask_price: {one_ask_price}, one_ask_volume: {one_ask_volume}\")\n self.buy(self.vt_symbol, one_ask_price, one_ask_volume)\n else:\n self.write_log(f\"---> 流动性挖矿卖出下单失败,因为卖单总数量等于上一单数量\")\n else:\n self.write_log(f\"---> 流动性挖矿卖出下单失败,因为没有合适的下单位置\")\n\n if self.vt_bid_orderid == \"\":\n self.bid_order_level = 0\n for num_level in range(self.min_order_level, 0, -1):\n bid_price = getattr(self.last_tick, f\"bid_price_{num_level}\")\n if bid_price > market_price * (1 - self.reward_ratio * 0.99):\n self.bid_order_level = num_level\n break\n if self.bid_order_level > 0:\n total_bid_volume = 0\n for num_level in range(1, self.bid_order_level + 1):\n total_bid_volume += getattr(self.last_tick, f\"bid_volume_{num_level}\")\n if total_bid_volume != self.last_bid_volume:\n one_bid_price = getattr(self.last_tick, f\"bid_price_1\")\n one_bid_volume = getattr(self.last_tick, f\"bid_volume_1\")\n max_bid_price = getattr(self.last_tick, f\"bid_price_{self.bid_order_level}\") if self.bid_order_level > 0 else market_price\n vt_bid_price = round_to(max_bid_price - self.pricetick, self.pricetick)\n if self.origin_bid_price == 0.00000001:\n self.origin_bid_price = vt_bid_price\n bid_condition0 = self.last_bid_price == 0.00000001\n bid_condition1 = (self.last_bid_price * (1 - self.price_offset)) < vt_bid_price < (self.last_bid_price * (1 + self.price_offset))\n bid_condition2 = vt_bid_price < (self.origin_bid_price * (1 + self.price_offset_max))\n bid_condition8 = one_bid_price > (self.origin_bid_price * (1 + self.price_offset_max * 2))\n self.write_log(f\"---> 流动性挖矿买入condition1: {bid_condition1}, condition2: {bid_condition2}\")\n if bid_condition0 or (bid_condition1 and bid_condition2):\n self.last_bid_price = vt_bid_price\n self.vt_bid_price = one_bid_price\n self.total_bid_volume = total_bid_volume\n max_volume = self.current_balance[self.market_vt_tokens[1]] * self.buy_max_ratio / vt_bid_price\n if 0 < self.buy_max_volume < max_volume:\n max_volume = self.buy_max_volume\n min_volume = self.volume * total_bid_volume\n if self.min_order_volume > 0 and min_volume < self.min_order_volume:\n min_volume = self.min_order_volume\n volume = min_volume if not use_max_volume else max_volume * max_volume_ratio\n if volume >= max_volume:\n volume = max_volume\n self.last_bid_volume = round_to(volume - self.volumetick, self.volumetick)\n self.write_log(f\"流动性挖矿买入价格: {vt_bid_price}, 量: {self.last_bid_volume}\")\n self.vt_bid_orderid = self.buy(self.vt_symbol, vt_bid_price, self.last_bid_volume)\n self.bid_order_alive_tick = 0\n elif bid_condition8 and one_bid_volume < self.auto_trade_volume:\n self.write_log(f\"---> 流动性挖矿卖出高价one_bid_price: {one_bid_price}, one_bid_volume: {one_bid_volume}\")\n self.sell(self.vt_symbol, one_bid_price, one_bid_volume)\n else:\n self.write_log(f\"---> 流动性挖矿买入下单失败,因为买单总数量等于上一单数量\")\n else:\n self.write_log(f\"---> 流动性挖矿买入下单失败,因为没有合适的下单位置\")\n self.put_variables_event()\n\n def on_order(self, order: OrderData):\n \"\"\"\"\"\"\n if order.vt_orderid == self.vt_ask_orderid:\n if not order.is_active():\n self.vt_ask_orderid = \"\"\n self.vt_ask_price = 0.0\n elif order.vt_orderid == self.vt_bid_orderid:\n if not order.is_active():\n self.vt_bid_orderid = \"\"\n self.vt_bid_price = 0.0\n self.put_variables_event()\n\n def on_trade(self, trade: TradeData):\n \"\"\"\"\"\"\n if trade.direction == Direction.SHORT:\n self.write_log(f\"流动性挖矿卖单{trade.vt_orderid}成交,价:{trade.price}, 量:{trade.volume}\")\n self.pos -= trade.volume\n elif trade.direction == Direction.LONG:\n self.write_log(f\"流动性挖矿买单{trade.vt_orderid}成交,价:{trade.price}, 量:{trade.volume}\")\n self.pos += trade.volume\n\n self.put_variables_event()\n\n def on_stop(self):\n \"\"\"\"\"\"\n self.write_log(\"停止 流动性挖矿\")\n # self.write_log(f\"账户状态:{self.algo_engine.main_engine.get_all_accounts()}\")\n time.sleep(5)\n","sub_path":"vnpy/app/algo_trading/algos/liquid_mining_algo.py","file_name":"liquid_mining_algo.py","file_ext":"py","file_size_in_byte":18409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77570165","text":"#!/usr/bin/env\n\ntry:\n\tfrom setuptools import setup\nexcept ImportError:\n\tfrom distutils.core import setup\n\nconfig = {\n\t\"description\": \"asks a question, prints the input. simples!\",\n\t\"author\": \"David\",\n\t\"url\": \"none\",\n\t\"download_url\": \"none\",\n\t\"author email\": \"dmt257257@gmail.com\",\n\t\"version\": \"0.1\",\n \"long_description\" : read(\"README\"),\n\t\"install_requires\": [\"nose\"],\n\t\"packages\": [\"usethis_main\", \"tests\"],\n\t\"scripts\": [\"/bin/ask_script\"],\n\t\"name\": \"usethis\"\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"354173464","text":"# -*- coding: utf-8 -*-\n# CREATED ON DATE: 17.11.14\n__author__ = 'vojtek.nowak@gmail.com'\n\nimport json\nfrom pymongo import MongoClient\n\nclient = MongoClient()\ndb = client.test\n\n\ndef to_highcharts(cursor, json_name):\n out_json = {\n 'chart': {\n 'type': 'bar'\n },\n 'title': {\n 'text': 'Crime analysis'\n },\n 'subtitle': {\n 'text': 'Source: http://data.police.uk/data/'\n },\n 'xAxis': {\n 'categories': [data.get('_id') for data in cursor],\n 'title': {\n 'text': None\n }\n },\n 'yAxis': {\n 'min': 0,\n 'title': {\n 'text': '',\n 'align': 'high'\n },\n 'labels': {\n 'overflow': 'justify'\n }\n },\n 'tooltip': {\n 'valueSuffix': ' '\n },\n 'plotOptions': {\n 'bar': {\n 'dataLabels': {\n 'enabled': True\n }\n }\n },\n 'legend': {\n 'layout': 'vertical',\n 'align': 'right',\n 'verticalAlign': 'top',\n 'x': -40,\n 'y': 100,\n 'floating': True,\n 'borderWidth': 1,\n 'backgroundColor': '#FFFFFF',\n 'shadow': True\n },\n 'credits': {\n 'enabled': False\n },\n 'series': [{\n 'name': 'Data',\n 'data': [data.get('count') for data in cursor]\n },\n ]\n }\n\n with open(json_name, 'w') as out_file:\n json.dump(out_json, out_file)\n\n# ilość zakończeń przestępstwa w danym typie.\nto_highcharts(\n cursor=db.crime.aggregate(\n [\n {\n '$group': {'_id': \"$Outcome type\", 'count': {'$sum': 1}}\n },\n {\n '$sort': {'count': -1}\n }\n ])['result'],\n json_name='aggregation1.json')","sub_path":"crime/aggregation1.py","file_name":"aggregation1.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253714154","text":"#!/usr/bin/env python\nimport json\nimport os\n\nimport click\n\nfrom pytorch_tool_th2at.nn_th2at4cpu import NN_TH2AT_CPU\nfrom pytorch_tool_th2at.nn_th2at4gpu import NN_TH2AT_CUDA\n\n\n@click.command()\n@click.option(\n '--th_file',\n '-f',\n multiple=True,\n required=True,\n help='TH file that will be ported'\n)\n@click.option(\n '--output_path',\n '-o',\n required=True,\n help='Output path for the new ATen files'\n)\n@click.option(\n '--pytorch_path',\n '-p',\n required=True,\n help='PyTorch path'\n)\n@click.option(\n '--cpu',\n is_flag=True,\n default=False,\n show_default=True,\n help='Run porting for CPU'\n)\n@click.option(\n '--gpu',\n is_flag=True,\n default=False,\n show_default=True,\n help='Run porting for CUDA'\n)\n@click.option(\n '--file_extra_rules',\n '-r',\n default=None, \n help='The path of the file that add extra rules'\n)\ndef run(\n th_file,\n output_path,\n pytorch_path,\n cpu,\n gpu,\n file_extra_rules\n):\n \"\"\"Run TH to ATen porting.\n\n For each file you want to port use the parameter `-f` or `--th_file`.\n \n If you want to pass more extra rules use the parameter `-r`_or `--file_extra_rules`.\n \n Example of file with extra rules (json format):\n \n \\b\n {\n \"#include \": \"#include \",\n \"kH\": \"kernel_height\",\n \"kW\": \"kernel_width\",\n \"padH\": \"pad_height\",\n \"padW\": \"pad_width\",\n \"sH\": \"stride_height\",\n \"sW\": \"stride_width\",\n \"nBlocksH\": \"n_blocks_height\",\n \"nBlocksW\": \"n_blocks_width\",\n \"shapeCheck\": \"shape_check\"\n }\n\n Example of how to use this command:\n\n \\b\n ./th2at.py --cpu \\\\\n -f VolumetricFullDilatedConvolution.c \\\\\n -o ~/tmp/pytorch \\\\\n -p $PYTORCH_SRC_PATH \\\\ \n -r ~/tmp/th2at.json\n \n \"\"\"\n if cpu == gpu:\n raise Exception(\n 'Specify just CPU or GPU, not both or none of them.'\n )\n \n rules_extra = []\n \n if not os.path.isdir(pytorch_path):\n raise Exception(\n 'The path specified for `pytorch_path` doesn\\'t exist.'\n )\n \n if file_extra_rules:\n if not os.path.isfile(file_extra_rules):\n raise Exception(\n 'The file specified for `file_extra_rules` doesn\\'t exist.'\n )\n with open(file_extra_rules, 'r') as f:\n rules_extra = list(json.load(f).items()) \n \n kwargs = {\n 'output_path': output_path, \n 'pytorch_path': pytorch_path,\n 'th_files': list(th_file),\n 'rules_extra': rules_extra,\n 'rules_name_extra': [] # not implemented yet\n }\n\n if cpu:\n print('[II] CPU mode recognized')\n th2at = NN_TH2AT_CPU(**kwargs)\n else:\n print('[II] GPU mode recognized')\n th2at = NN_TH2AT_CUDA(**kwargs)\n th2at.store_files()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"th2at/th2at.py","file_name":"th2at.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"634125425","text":"from __future__ import division, absolute_import, print_function\nfrom past.builtins import xrange\n\nimport fitsio\nimport numpy as np\nimport esutil\nfrom esutil.cosmology import Cosmo\n\nfrom .configuration import Configuration\nfrom .cluster import ClusterCatalog\nfrom .background import Background\nfrom .mask import get_mask\nfrom .galaxy import GalaxyCatalog\nfrom .catalog import Catalog\nfrom .cluster import Cluster\nfrom .cluster import ClusterCatalog\nfrom .depthmap import DepthMap\nfrom .zlambda import Zlambda\nfrom .zlambda import ZlambdaCorrectionPar\nfrom .redsequence import RedSequenceColorPar\n\n###################################################\n# Order of operations:\n# __init__()\n# _additional_initialization() [override this]\n# run()\n# _setup()\n# _more_setup() [override this]\n# _process_cluster() [override this]\n# _postprocess() [override this]\n# output()\n###################################################\n\nclass ClusterRunner(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, conf, **kwargs):\n if not isinstance(conf, Configuration):\n # this needs to be read\n self.config = Configuration(conf)\n else:\n self.config = conf\n\n # Generic defaults\n self.read_zreds = False\n self.zreds_required = False\n self.use_colorbkg = False\n self.use_parfile = True\n\n # Will want to add stuff to check that everything needed is present?\n\n self._additional_initialization(**kwargs)\n\n def _additional_initialization(self, **kwargs):\n \"\"\"\n \"\"\"\n\n # must be overridden\n self.runmode = None\n self.filetype = None\n\n def _setup(self):\n \"\"\"\n \"\"\"\n self.r0 = self.config.__getattribute__(self.runmode + '_r0')\n self.beta = self.config.__getattribute__(self.runmode + '_beta')\n\n # This always uses the \"percolation\" settings, maybe?\n self.rmask_0 = self.config.percolation_rmask_0\n self.rmask_beta = self.config.percolation_rmask_beta\n self.rmask_gamma = self.config.percolation_rmask_gamma\n self.rmask_zpivot = self.config.percolation_rmask_zpivot\n\n if self.config.percolation_lmask < 0.0:\n self.percolation_lmask = self.config.lval_reference\n else:\n self.percolation_lmask = self.config.percolation_lmask\n\n # maxrad is the maximum dist to match neighbors. maxrad2 is for masking\n # (note this was \"maxdist\" in IDL which was a bad name)\n if self.beta == 0.0:\n # add a small cushion even if we have constant radius\n self.maxrad = 1.2 * self.r0\n self.maxrad2 = 1.2 * self.rmask_0\n else:\n # maximum possible richness is 300\n self.maxrad = self.r0 * (300./100.)**self.beta\n self.maxrad2 = self.rmask_0 * (300./100.)**self.rmask_beta\n\n if self.maxrad2 > self.maxrad:\n self.maxrad = self.maxrad2\n\n # read in background\n if self.use_colorbkg:\n self.cbkg = ColorBackground(self.config.bkgfile_color)\n self.bkg = None\n else:\n self.bkg = Background(self.config.bkgfile)\n self.cbkg = None\n\n # read in parameters\n if self.use_parfile:\n self.zredstr = RedSequenceColorPar(self.config.parfile, fine=True)\n else:\n self.zredstr = RedSequenceColorPar(None, config=self.config)\n\n # And correction parameters\n try:\n self.zlambda_corr = ZlambdaCorrectionPar(self.config.zlambdafile,\n self.config.zlambda_pivot)\n except:\n self.zlambda_corr = None\n\n # read in mask (if available)\n # This will read in the mask and generate maskgals if necessary\n # Will work with any type of mask\n self.mask = get_mask(self.config)\n\n # read in the depth structure\n try:\n self.depthstr = DepthMap(self.config)\n except:\n self.depthstr = None\n\n #self.cosmo = Cosmo()\n self.cosmo = self.config.cosmo\n\n # read in the galaxies\n # WILL NEED TO TRACK IF READING ZREDS\n # Use self.read_zreds to know if we should read them!\n # And self.zreds_required to know if we *must* read them\n\n self.gals = GalaxyCatalog.from_galfile(self.config.galfile,\n nside=self.config.nside,\n hpix=self.config.hpix,\n border=self.config.border)\n\n # default limiting luminosity\n self.limlum = np.clip(self.config.lval_reference - 0.1, 0.01, None)\n\n # Defaults for whether to implement masking, etc\n self.do_percolation_masking = False\n self.do_lam_plusminus = False\n self.use_memradius = False\n self.use_memlum = False\n self.match_centers_to_galaxies = False\n self.min_lambda = -1.0\n self.record_members = False\n self.doublerun = False\n\n def _more_setup(self, *args, **kwargs):\n # This is to be overridden if necessary\n # this can receive all the keywords.\n\n # THIS NEEDS TO SET MEM_MATCH_ID!!!\n # make a common convenience function ... hey!\n\n pass\n\n def _generate_mem_match_ids(self):\n min_id = self.cat.mem_match_id.min()\n max_id = self.cat.mem_match_id.max()\n\n if (min_id == max_id):\n # These are unset: generate them\n self.cat.mem_match_id = np.arange(self.cat.size) + 1\n else:\n # Make sure they are unique\n if np.unique(self.cat.mem_match_id).size != self.cat.size:\n raise RuntimeError(\"Input values for mem_match_id are not unique (and not all unset)\")\n\n def _reset_bad_values(self, cluster):\n cluster.Lambda = -1.0\n cluster.Lambda_e = -1.0\n cluster.scaleval = -1.0\n cluster.z_lambda = -1.0\n cluster.z_lambda_e = -1.0\n\n def _process_cluster(self, cluster):\n # This must be overridden\n raise RuntimeError(\"_process_cluster must have an override\")\n\n def run(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n\n # General setup\n self._setup()\n\n # Setup specific for a given task. Will read in the galaxy catalog.\n self._more_setup(*args, **kwargs)\n\n # Match centers and galaxies if required\n if self.match_centers_to_galaxies:\n i0, i1, dist = self.gals.match_many(self.cat.ra, self.cat.dec, 1./3600.)\n self.cat.refmag[i0] = self.gals.refmag[i1]\n self.cat.refmag_err[i0] = self.gals.refmag_err[i1]\n self.cat.mag[i0, :] = self.gals.mag[i1, :]\n self.cat.mag_err[i0, :] = self.gals.mag[i1, :]\n # do zred stuff when in...\n\n # loop over clusters...\n # at the moment, we are doing the matching once per cluster.\n # if this proves too slow we can prematch bulk clusters as in the IDL code\n\n if self.do_percolation_masking:\n self.pgal = np.zeros(self.gals.size, dtype=np.float32)\n\n self.members = None\n\n if self.doublerun:\n nruniter = 2\n else:\n nruniter = 1\n\n for it in xrange(nruniter):\n\n if self.doublerun:\n # This mode allows two passes, with a sort in between.\n if it == 0:\n print(\"First iteration...\")\n self.do_percolation_masking = False\n else:\n print(\"Second iteration with percolation...\")\n self._doublerun_sort()\n self.do_percolation_masking = True\n self.record_members = True\n\n for cluster in self.cat:\n # Note that the cluster is set with .z if available! (which becomes ._z)\n\n maxmag = cluster.mstar - 2.5*np.log10(self.limlum)\n cluster.find_neighbors(self.maxrad, self.gals, megaparsec=True, maxmag=maxmag)\n\n if cluster.neighbors.size == 0:\n self._reset_bad_values(cluster)\n continue\n\n if self.do_percolation_masking:\n cluster.neighbors.pfree[:] = 1.0 - self.pgal[cluster.neighbors.index]\n else:\n cluster.neighbors.pfree[:] = 1.0\n\n # FIXME: add mean ebv computation here.\n\n if self.depthstr is None:\n # must approximate the limiting magnitude\n # will get this from my des_depth functions...\n raise RuntimeError(\"No depthstr Must be implemented!!!!\")\n else:\n # get from the depth structure\n self.depthstr.calc_maskdepth(self.mask.maskgals,\n cluster.ra, cluster.dec, cluster.mpc_scale)\n\n cluster.lim_exptime = np.median(self.mask.maskgals.exptime)\n cluster.lim_limmag = np.median(self.mask.maskgals.limmag)\n cluster.lim_limmag_hard = self.config.limmag_catalog\n\n # And survey masking (this may be a dummy)\n self.mask.set_radmask(cluster)\n\n # And compute maskfrac here...approximate first computation\n inside, = np.where(self.mask.maskgals.r < 1.0)\n bad, = np.where(self.mask.maskgals.mark[inside] == 0)\n cluster.maskfrac = float(bad.size) / float(inside.size)\n\n # Note that _process_cluster has the index part maybe?\n bad_cluster = self._process_cluster(cluster)\n\n if bad_cluster:\n # This is a bad cluster and we can't continue\n continue\n\n # compute updated maskfrac (always)\n inside, = np.where(self.mask.maskgals.r < cluster.r_lambda)\n bad, = np.where(self.mask.maskgals.mark[inside] == 0)\n cluster.maskfrac = float(bad.size) / float(inside.size)\n\n # compute additional dlambda bits (if desired)\n if self.do_lam_plusminus:\n cluster_temp = cluster.copy()\n\n #cluster_temp.z = cluster.z_lambda - self.config.zlambda_epsilon\n #cluster_temp.update_z(cluster.z_lambda - self.config.zlambda_epsilon)\n cluster_temp.redshift = cluster.z_lambda - self.config.zlambda_epsilon\n lam_zmeps = cluster_temp.calc_richness(self.mask)\n elambda_zmeps = cluster_temp.lambda_e\n #cluster_temp.z = cluster.z_lambda + self.config.zlambda_epsilon\n #cluster_temp.update_z(cluster.z_lambda + self.config.zlambda_epsilon)\n cluster_temp.redshift = cluster.z_lambda + self.config.zlambda_epsilon\n lam_zpeps = cluster_temp.calc_richness(self.mask)\n elambda_zpeps = cluster_temp.lambda_e\n\n cluster.dlambda_dz = (np.log(lam_zpeps) - np.log(lam_zmeps)) / (2. * self.config.zlambda_epsilon)\n cluster.dlambda_dz2 = (np.log(lam_zpeps) + np.log(lam_zmeps) - 2.*np.log(cluster.Lambda)) / (self.config.zlambda_epsilon**2.)\n\n cluster.dlambdavar_dz = (elambda_zpeps**2. - elambda_zmeps**2.) / (2.*self.config.zlambda_epsilon)\n cluster.dlambdavar_dz2 = (elambda_zpeps**2. + elambda_zmeps**2. - 2.*cluster.Lambda_e**2.) / (self.config.zlambda_epsilon**2.)\n\n # and record pfree if desired\n if self.do_percolation_masking:\n # FIXME\n r_mask = (self.rmask_0 * (cluster.Lambda/100.)**self.rmask_beta *\n ((1. + cluster.redshift)/(1. + self.rmask_zpivot))**self.rmask_gamma)\n if (r_mask < cluster.r_lambda):\n r_mask = cluster.r_lambda\n cluster.r_mask = r_mask\n\n lim = cluster.mstar - 2.5*np.log10(self.percolation_lmask)\n\n u, = np.where((cluster.neighbors.refmag < lim) &\n (cluster.neighbors.r < r_mask) &\n (cluster.neighbors.p > 0.0))\n if (u.size > 0):\n self.pgal[cluster.neighbors.index[u]] += cluster.neighbors.p[u]\n\n # and save members\n # Note that this is probably horribly inefficient for memory\n # usage right now, but will start here and fix later if it\n # is a problem.\n\n pfree_temp = cluster.neighbors.pfree[:]\n\n if self.use_memradius or self.use_memlum:\n ok = (cluster.neighbors.p > 0.01)\n\n if self.use_memradius:\n ok &= (cluster.neighbors.r < self.config.percolation_memradius * cluster.r_lambda)\n if self.use_memlum:\n ok &= (cluster.neighbors.refmag < (cluster.mstar - 2.5*np.log10(self.config.percolation_memlum)))\n\n # And set pfree_temp to zero when it is not okay\n pfree_temp[~ok] = 0.0\n else:\n # Only save members where pmem > 0.01 (for space)\n ok = (cluster.neighbors.pmem > 0.01)\n pfree_temp[~ok] = 0.0\n\n if self.record_members:\n memuse, = np.where(pfree_temp > 0.01)\n mem_temp = Catalog.zeros(memuse.size, dtype=self.config.member_dtype)\n\n mem_temp.mem_match_id[:] = cluster.mem_match_id\n mem_temp.z[:] = cluster.z_lambda\n mem_temp.ra[:] = cluster.neighbors.ra[memuse]\n mem_temp.dec[:] = cluster.neighbors.dec[memuse]\n mem_temp.r[:] = cluster.neighbors.r[memuse]\n mem_temp.p[:] = cluster.neighbors.p[memuse]\n mem_temp.pfree[:] = pfree_temp[memuse]\n mem_temp.theta_i[:] = cluster.neighbors.theta_i[memuse]\n mem_temp.theta_r[:] = cluster.neighbors.theta_r[memuse]\n mem_temp.refmag[:] = cluster.neighbors.refmag[memuse]\n mem_temp.refmag_err[:] = cluster.neighbors.refmag_err[memuse]\n # mem_temp.zred[:] = cluster.neighbors.zred[memuse]\n # mem_temp.zred_e[:] = cluster.neighbors.zred_e[memuse]\n mem_temp.chisq[:] = cluster.neighbors.chisq[memuse]\n mem_temp.ebv[:] = cluster.neighbors.ebv[memuse]\n mem_temp.mag[:, :] = cluster.neighbors.mag[memuse, :]\n mem_temp.mag_err[:, :] = cluster.neighbors.mag_err[memuse, :]\n\n # Worried this is going to be slow...\n if self.members is None:\n self.members = mem_temp\n else:\n self.members.append(mem_temp)\n\n\n self._postprocess()\n\n def _postprocess(self):\n # default post-processing...\n\n use, = np.where(self.cat.Lambda >= self.min_lambda)\n self.cat = self.cat[use]\n\n # And crop down members?\n # FIXME\n\n def output(self, savemembers=True, withversion=True, clobber=False):\n \"\"\"\n \"\"\"\n\n # Try with a universal method.\n # It will save the underlying _ndarrays of the Cluster and\n # (optionally) Member catalogs.\n\n fname_base = self.config.outbase\n\n if withversion:\n fname_base += '_redmapper_' + self.config.version\n\n fname_base += '_' + self.filetype\n\n fitsio.write(fname_base + '.fit', self.cat._ndarray, clobber=clobber)\n\n if savemembers:\n fitsio.write(fname_base + '_members.fit', self.members._ndarray, clobber=clobber)\n","sub_path":"redmapper/cluster_runner.py","file_name":"cluster_runner.py","file_ext":"py","file_size_in_byte":15893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"299689160","text":"# 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 # @param a list of ListNode\n # @return a ListNode\n def mergeKLists(self, lists):\n def find_pos(node, nodes, start, end):\n if start == end:\n return start\n i = start + (end - start) / 2\n if nodes[i].val > node.val:\n return find_pos(node, nodes, start, i)\n elif nodes[i].val < node.val:\n return find_pos(node, nodes, i + 1, end)\n return i\n head = None\n heads = sorted([h for h in lists if h is not None],\n key=lambda node: node.val)\n while len(heads) > 0:\n min_node = heads[0]\n heads.pop(0)\n next = min_node.next\n if next is not None:\n i = find_pos(next, heads, 0, len(heads))\n heads.insert(i, next)\n if head is None:\n head = min_node\n head.next = None\n p = head\n else:\n p.next = min_node\n p = p.next\n p.next = None\n return head\n","sub_path":"merge-k-sorted-lists.py","file_name":"merge-k-sorted-lists.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282748327","text":"#!/usr/bin/env python3\n\nimport io\nimport re\nimport sqlite3\nimport requests\nimport threading\nimport subprocess\nimport feedparser\nimport webbrowser\nimport html.parser\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.messagebox import askyesno, showerror\nfrom pathlib import Path\nfrom tkinter.scrolledtext import ScrolledText\nfrom PIL import Image, ImageTk\n\n\nstyle = {\n 'news.viewer.text': {\n 'bg': '#000000',\n 'fg': '#2eff7b',\n 'font': ('roboto', 16, 'normal')\n }\n}\n\n\nclass StreamlinkViewer(threading.Thread):\n def __init__(self, url, quality='worst', **kwargs):\n super().__init__()\n\n # self.daemon = True # powoduje dziwne zawieszenia po kilku odtworzeniach filmów\n\n self._url = url\n self._quality = quality\n\n self._on_start = kwargs['on_start'] if 'on_start' in kwargs else None\n\n def run(self):\n self._run_streamlink(self._url, self._quality)\n\n def _run_streamlink(self, url, quality='worst'):\n # run process in blocking mode\n with subprocess.Popen(['streamlink', url, quality, '-p', 'mpv'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) as p:\n while p.stdout:\n # read lines from stdout\n l = p.stdout.readline()\n if l == b'':\n break\n\n # if certain line is detected then stop blocking main window\n if b'Writing stream to output' in l:\n if callable(self._on_start):\n self._on_start()\n\n\nclass NewsParser(html.parser.HTMLParser):\n def __init__(self):\n super().__init__()\n self._text = ''\n\n self._processed_tags = [] # debug\n\n def handle_endtag(self, tag):\n if tag not in self._processed_tags:\n print(f'Unprocessed tag: {tag}')\n\n def handle_starttag(self, tag, attrs):\n if tag == 'br':\n self._text += '\\n'\n\n self._processed_tags = ['br'] # debug\n\n def handle_data(self, data):\n self._text += data\n\n def get_text(self):\n return self._text.strip()\n\n\nclass AboutDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.transient(master)\n self.title('About')\n self.bind('', self._on_ok_button)\n\n label = tk.Label(self, text='Authors:')\n label.pack(fill=tk.X)\n\n text = tk.Text(self)\n text.insert(tk.END, '''Authors:\n- jaroslaw.janikowski@gmail.com (programming)\n- www.freepik.com(icons) ''')\n text['state'] = tk.DISABLED\n text.pack(fill=tk.BOTH, expand=True)\n\n self._ok_button = tk.Button(self, text='OK', command=self._on_ok_button)\n self._ok_button.pack(anchor=tk.E)\n\n self.wait_visibility()\n self.grab_set()\n self.wait_window()\n\n def _on_ok_button(self, event=None):\n self.grab_release()\n self.destroy()\n\n\nclass FolderDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.title('Add / edit folder')\n self.transient(master)\n self.bind('', self._on_cancel)\n self._result = None\n\n tk.Label(self, text='Folder title').pack(fill=tk.X, padx=2)\n self._folder_title_entry = tk.Entry(self)\n self._folder_title_entry.bind('', self._validate)\n self._folder_title_entry.pack(fill=tk.X, padx=2)\n self._folder_title_entry.focus()\n\n button_cancel = tk.Button(self, text='Cancel', command=self._on_cancel)\n button_cancel.pack(fill=tk.X, padx=2)\n\n self._button_ok = tk.Button(self, text='Ok', state=tk.DISABLED, command=self._on_apply)\n self._button_ok.pack(fill=tk.X, padx=2)\n\n def _on_apply(self, event=None):\n self._result = {\n 'title': self._folder_title_entry.get()\n }\n self.destroy()\n\n def _validate(self, *args):\n b = bool(self._folder_title_entry.get())\n self._button_ok['state'] = (tk.NORMAL if b else tk.DISABLED)\n\n def _on_cancel(self, event=None):\n self._result = None\n self.destroy()\n\n def run(self):\n self.grab_set()\n self.wait_window()\n self.grab_release()\n return self._result\n\n\nclass ChannelDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.title('Add / edit channel info')\n self.transient(master)\n self.bind('', self._on_cancel)\n\n self._result = False # naciśnięto escape lub cancel\n\n tk.Label(self, text='Channel title').pack(fill=tk.X, padx=2)\n self._channel_title_entry = tk.Entry(self)\n self._channel_title_entry.bind('', self._validate)\n self._channel_title_entry.pack(fill=tk.X, padx=2)\n self._channel_title_entry.focus()\n\n tk.Label(self, text='URL').pack(fill=tk.X, padx=2)\n self._channel_url_entry = tk.Entry(self)\n self._channel_url_entry.bind('', self._validate)\n self._channel_url_entry.pack(fill=tk.X, padx=2)\n\n button_cancel = tk.Button(self, text='Cancel', command=self._on_cancel)\n button_cancel.pack(fill=tk.X, padx=2)\n\n self._button_ok = tk.Button(self, text='Ok', state=tk.DISABLED, command=self._on_apply)\n self._button_ok.pack(fill=tk.X, padx=2)\n\n def _validate(self, *args):\n self._autopopulate_form()\n\n b = all([\n self._channel_title_entry.get(),\n self._channel_url_entry.get()\n ])\n\n self._button_ok['state'] = (tk.NORMAL if b else tk.DISABLED)\n\n def _autopopulate_form(self):\n url = self._channel_title_entry.get()\n\n # link do kanału youtube\n m = re.match(r'^https:\\/\\/www\\.youtube\\.com\\/channel\\/([a-zA-Z0-9_\\-]+)$', url)\n if m is not None:\n channel_id = m.group(1)\n self._channel_url_entry.delete(1, tk.END)\n self._channel_url_entry.insert(tk.END, f'https://www.youtube.com/feeds/videos.xml?channel_id={channel_id}')\n self._channel_title_entry.delete(1, tk.END)\n self._channel_title_entry.insert(tk.END, channel_id)\n return True\n\n # link do usera youtube\n m = re.match(r'^https:\\/\\/www\\.youtube\\.com\\/user\\/([a-zA-Z0-9_\\-]+)$', url)\n if m is not None:\n user_id = m.group(1)\n self._channel_url_entry.delete(1, tk.END)\n self._channel_url_entry.insert(tk.END, f'https://www.youtube.com/feeds/videos.xml?user={user_id}')\n self._channel_title_entry.delete(1, tk.END)\n self._channel_title_entry.insert(tk.END, user_id)\n return True\n\n def _on_cancel(self, event=None):\n self._result = None\n self.destroy()\n\n def _on_apply(self, event=None):\n self._result = {\n 'title': self._channel_title_entry.get(),\n 'url': self._channel_url_entry.get()\n }\n self.destroy()\n\n def set_data(self, channel):\n self._channel_title_entry.set(channel['title'])\n self._channel_url_entry.set(channel['url'])\n\n def run(self):\n self.grab_set()\n self.wait_window()\n self.grab_release()\n return self._result\n\n\nclass ProgressDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n # self.geometry('640x480')\n self.title('Operation progress...')\n self.transient(master)\n self.bind('', self._on_escape)\n\n progress_label = tk.Label(self, text='Progress')\n progress_label.grid(row=0, column=0, sticky=tk.EW, padx=2, pady=2)\n self._progressbar = ttk.Progressbar(self, value=0)\n self._progressbar.grid(row=1, column=0, sticky=tk.EW, padx=2, pady=2)\n self._text = tk.Text(self)\n self._text.grid(row=2, column=0, sticky=tk.EW, padx=2, pady=2)\n cancel_btn = tk.Button(self, text='Cancel', command=self._on_escape)\n cancel_btn.grid(row=3, column=0, sticky=tk.E, padx=2, pady=2)\n\n self.columnconfigure(0, weight=1)\n\n def _on_escape(self, event=None):\n self.destroy()\n\n def set_position(self, pos, msg=None):\n self._progressbar['value'] = pos\n if msg:\n self._text.insert(tk.END, msg+'\\n')\n self._text.see(tk.END)\n\n def show(self):\n self.deiconify()\n self.wait_visibility()\n self.grab_set()\n # self.wait_window()\n\n def destroy(self):\n self.withdraw()\n self.grab_release()\n super().destroy()\n\n\nclass WaitDialog(tk.Toplevel):\n def __init__(self, master):\n super().__init__(master)\n self.withdraw()\n self.title('Proszę czekać...')\n self.geometry('250x120')\n self.transient(master)\n self.bind('', self._on_escape)\n\n label = tk.Label(self, text='Operacja w toku, proszę czekać...')\n label.pack(side=tk.TOP, fill=tk.X, expand=True)\n\n def _on_escape(self, event=None):\n self.hide()\n\n def show(self):\n self.deiconify()\n self.wait_visibility()\n self.grab_set()\n # self.wait_window()\n\n def hide(self):\n self.grab_release()\n self.withdraw()\n\n\nclass Application(tk.Tk):\n def __init__(self):\n super().__init__()\n self.geometry('640x480+100+100')\n self.title('news')\n self.bind('', self._on_quit)\n\n self.config(menu=self._create_main_menu())\n\n self._load_resources()\n\n paned_h = ttk.PanedWindow(self, orient=tk.HORIZONTAL)\n paned_h.add(self._create_channel_manager(paned_h), weight=0)\n paned_h.add(self._create_news_viewer(paned_h), weight=1)\n paned_h.pack(fill=tk.BOTH, expand=True)\n\n self._db_connection = sqlite3.connect(Path.home() / '.config' / 'news' / 'news.sqlite3')\n self._db_connection.row_factory = sqlite3.Row\n self._db_cursor = self._db_connection.cursor()\n # self._db_cursor.execute('pragma journal_mode=wal')\n\n self._wait_dlg = WaitDialog(self)\n self._current_news = None\n\n self._load_data()\n\n def _load_resources(self):\n self._icons = {\n 'folder': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/folder.png')),\n 'rss': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/rss.png')),\n 'youtube': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/youtube.png')),\n 'twitch': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/twitch.png')),\n 'like': ImageTk.PhotoImage(Image.open('/usr/share/icons/news/like.png'))\n }\n\n def _load_data(self):\n # dodaj foldery\n folders = {}\n for row in self._db_cursor.execute('select * from folder').fetchall():\n i = self._channel_manager_treeview.insert('', tk.END, text=row['title'], image=self._icons['folder'])\n folders[row['id']] = i\n self._channel_manager_folders[row['title']] = i\n self._channel_manager_title_type[row['title']] = 'folder'\n\n # dodaj kanały\n self._db_cursor.execute('select channel.*, (select count(id) from news where channel_id = channel.id and is_read = 0) as news_count from channel')\n for row in self._db_cursor.fetchall():\n parent_id = ''\n if row['folder_id'] is not None:\n parent_id = folders[row['folder_id']]\n\n # wybór ikony ze względu na źródło danych\n icon = None\n if 'youtube' in row['url']:\n icon = self._icons['youtube']\n elif 'twitch' in row['url']:\n icon = self._icons['twitch']\n else:\n icon = self._icons['rss']\n\n i = self._channel_manager_treeview.insert(parent_id, tk.END, row['id'], text=row['title'], image=icon, values=(row['news_count'],))\n self._channel_manager_channels[row['title']] = i\n self._channel_manager_title_type[row['title']] = 'channel'\n\n def _create_channel_manager(self, master):\n self._channel_manager_channels = {}\n self._channel_manager_folders = {}\n self._channel_manager_title_type = {}\n\n frame = tk.Frame(master, width=200)\n self._channel_manager_treeview = ttk.Treeview(frame, columns=('#news-count',))\n self._channel_manager_treeview.column('#news-count', width=40, stretch=tk.YES)\n self._channel_manager_treeview.grid(row=0, column=0, sticky=tk.NSEW)\n scrollbar_v = tk.Scrollbar(frame, orient=tk.VERTICAL)\n scrollbar_v.grid(row=0, column=1, sticky=tk.NS)\n scrollbar_h = tk.Scrollbar(frame, orient=tk.HORIZONTAL)\n scrollbar_h.grid(row=1, column=0, sticky=tk.EW)\n\n self._channel_manager_treeview['yscrollcommand'] = scrollbar_v.set\n self._channel_manager_treeview['xscrollcommand'] = scrollbar_h.set\n scrollbar_v['command'] = self._channel_manager_treeview.yview\n scrollbar_h['command'] = self._channel_manager_treeview.xview\n\n # drag and drop\n self._dragged_item = None\n self._channel_manager_treeview.bind('', self._on_channel_manager_button_press)\n self._channel_manager_treeview.bind('', self._on_channel_manager_button_release)\n self._channel_manager_treeview.bind('', self._on_channel_manager_motion)\n\n frame.rowconfigure(0, weight=1)\n frame.columnconfigure(0, weight=1)\n\n return frame\n\n def _on_channel_manager_button_press(self, event):\n self._dragged_item = self._channel_manager_treeview.identify_row(event.y)\n\n def _on_channel_manager_button_release(self, event):\n target = self._channel_manager_treeview.identify_row(event.y)\n\n # target nie może trafić do samego siebie\n if target == self._dragged_item:\n return 'break'\n\n # target musi być folderem\n if target not in self._channel_manager_folders.values():\n return 'break'\n\n self._channel_manager_treeview.move(self._dragged_item, target, tk.END)\n\n # zmiana folderu w bazie\n folder_title = tuple(k for k, v in self._channel_manager_folders.items() if v == target)[0]\n channel_title = tuple(k for k, v in self._channel_manager_channels.items() if v == self._dragged_item)[0]\n self._db_cursor.execute('update channel set folder_id = (select id from folder where title = ? limit 1) where title = ?', (folder_title, channel_title))\n\n def _on_channel_manager_motion(self, event):\n self._channel_manager_treeview['cursor'] = 'plus'\n\n def _create_news_viewer(self, master):\n frame = tk.Frame(master)\n self._news_viewer_title = tk.Text(frame, wrap=tk.WORD, height=3, state=tk.DISABLED, cursor='hand1', **style['news.viewer.text'])\n self._news_viewer_title.bind('', self._on_goto_news)\n self._news_viewer_title.grid(row=0, column=0, sticky=tk.NSEW)\n\n self._vote_up_btn = tk.Button(frame, text='0', command=self._on_vote_up, image=self._icons['like'], compound=tk.LEFT)\n self._vote_up_btn.grid(row=0, column=1, sticky=tk.NSEW)\n\n self._news_viewer_text = ScrolledText(frame, wrap=tk.WORD, state=tk.DISABLED, **style['news.viewer.text'])\n self._news_viewer_text.bind('', self._on_up_key)\n self._news_viewer_text.bind('', self._on_down_key)\n self._news_viewer_text.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW)\n\n frame.rowconfigure(0, weight=0)\n frame.rowconfigure(1, weight=1)\n frame.columnconfigure(0, weight=1)\n frame.columnconfigure(1, weight=0)\n\n return frame\n\n def _on_vote_up(self, event=None):\n channel_title = self._current_news['channel_title']\n text = f'{channel_title} {self._current_news[\"title\"]} {self._current_news[\"summary\"]}'.lower()\n\n r = self._recommend_count_words(text)\n self._recommend_update_words(r)\n for word in r:\n self._recommend_update_quality(word)\n\n # uaktualnij wartość na przycisku\n self._current_news = self._db_cursor.execute('select news.*, channel.title as channel_title from news join channel on news.channel_id = channel.id where news.id = ? limit 1', (self._current_news['id'],)).fetchone()\n self._vote_up_btn['text'] = self._current_news['quality']\n\n def _on_down_key(self, event=None):\n self._news_viewer_text.yview_scroll(1, 'units')\n\n def _on_up_key(self, event=None):\n self._news_viewer_text.yview_scroll(-1, 'units')\n\n def _create_main_menu(self):\n menubar = tk.Menu(self, tearoff=False)\n\n app_menu = tk.Menu(self, tearoff=False)\n app_menu.add_command(label='Update all', command=self._on_update_all, accelerator='Ctrl-U')\n self.bind('', self._on_update_all)\n app_menu.add_separator()\n app_menu.add_command(label='Quit', command=self._on_quit, accelerator='Ctrl-Q')\n self.bind('', self._on_quit)\n menubar.add_cascade(label='App', menu=app_menu)\n\n channel_menu = tk.Menu(self, tearoff=False)\n channel_menu.add_command(label='Add channel', command=self._on_add_channel, accelerator='Ctrl-N')\n self.bind('', self._on_add_channel)\n channel_menu.add_command(label='Add folder', command=self._on_add_folder, accelerator='Ctrl-Shift-N')\n self.bind('', self._on_add_folder)\n channel_menu.add_command(label='Remove', command=self._on_remove_channel_or_folder, accelerator='Del')\n self.bind('', self._on_remove_channel_or_folder)\n menubar.add_cascade(label='Channel', menu=channel_menu)\n\n news_menu = tk.Menu(self, tearoff=False)\n news_menu.add_command(label='Next', command=self._on_next_news, accelerator='N')\n self.bind('n', self._on_next_news)\n news_menu.add_command(label='Goto', command=self._on_goto_news, accelerator='G')\n self.bind('g', self._on_goto_news)\n news_menu.add_command(label='Streamlink worst', command=self._on_streamlink_worst, accelerator='1')\n self.bind('1', self._on_streamlink_worst)\n news_menu.add_command(label='Streamlink 360p', command=self._on_streamlink_360p, accelerator='2')\n self.bind('2', self._on_streamlink_360p)\n news_menu.add_separator()\n news_menu.add_command(label='Mark all as read', command=self._on_mark_all_as_read, accelerator='Ctrl-M')\n self.bind('', self._on_mark_all_as_read)\n menubar.add_cascade(label='News', menu=news_menu)\n\n help_menu = tk.Menu(self, tearoff=False)\n help_menu.add_command(label='About', command=self._on_about)\n\n menubar.add_cascade(label='Help', menu=help_menu)\n\n return menubar\n\n def _on_about(self, event=None):\n dlg = AboutDialog(self)\n\n def _on_mark_all_as_read(self, event=None):\n self._db_cursor.execute('update news set is_read = 1')\n for channel_title, channel_iid in self._channel_manager_channels.items():\n self._channel_manager_treeview.set(channel_iid, '#news-count', 0)\n\n def _on_streamlink_360p(self, event=None):\n if self._current_news:\n self._wait_dlg.show()\n v = StreamlinkViewer(self._current_news['url'], '360p', on_start=self._wait_dlg.hide)\n v.start()\n\n def _on_streamlink_worst(self, event=None):\n if self._current_news:\n self._wait_dlg.show()\n v = StreamlinkViewer(self._current_news['url'], 'worst', on_start=self._wait_dlg.hide)\n v.start()\n\n def _on_goto_news(self, event=None):\n if self._current_news:\n webbrowser.open_new_tab(self._current_news['url'])\n\n def _on_next_news(self, event=None):\n # oznacz poprzedni aktywny news jako przeczytany\n if self._current_news:\n self._db_cursor.execute('update news set is_read = 1 where id = ?', (self._current_news['id'],))\n\n # zmniejsz o 1 ilość nieprzeczytanych newsów w tym kanale\n tree_item = self._channel_manager_treeview.selection()[0]\n news_count = int(self._channel_manager_treeview.set(tree_item, '#news-count')) - 1\n if news_count >= 0:\n self._channel_manager_treeview.set(tree_item, '#news-count', news_count)\n\n # znajdź kolejny news\n news = self._db_cursor.execute('select news.*, channel.title as channel_title from news join channel on channel.id = news.channel_id where is_read = 0 order by quality desc limit 1').fetchone()\n\n self._current_news = news\n\n if news is None:\n return 'break'\n\n self._set_news(news)\n\n def _set_news(self, news):\n '''Wybiera news jako aktywny w programie. Parametr to słownik z bazy z tabeli news.'''\n # zaznacz i pokaż kanał w drzewie kanałów\n sel_item = self._channel_manager_channels[news['channel_title']]\n self._channel_manager_treeview.selection_set(sel_item)\n self._channel_manager_treeview.see(sel_item)\n\n # parsuj HTML\n parser = NewsParser()\n parser.feed(news['summary'])\n\n # załaduj treść do przeglądarki\n self._news_viewer_text['state'] = tk.NORMAL\n self._news_viewer_text.delete('1.0', tk.END)\n self._news_viewer_text.insert(tk.END, parser.get_text())\n self._news_viewer_text.mark_set(tk.INSERT, '1.0')\n self._news_viewer_text['state'] = tk.DISABLED\n self._news_viewer_title['state'] = tk.NORMAL\n self._news_viewer_title.delete('1.0', tk.END)\n self._news_viewer_title.insert(tk.END, news['title'])\n self._news_viewer_title['state'] = tk.DISABLED\n self._vote_up_btn['text'] = news['quality']\n\n # zaznacz kontrolkę z treścią aby łatwo przewijać za pomocą strzałek\n self._news_viewer_text.focus()\n\n def _on_remove_channel_or_folder(self, event=None):\n selection = self._channel_manager_treeview.selection()\n if selection is None:\n return\n\n selected_id = selection[0]\n title = self._channel_manager_treeview.item(selected_id, option='text')\n type_ = self._channel_manager_title_type[title]\n\n if not askyesno('Question', f'Do you really want to remove {title}?'):\n return\n\n # usuń z bazy\n if type_ == 'folder':\n # nie można usuwać nie pustych folderów\n if self._channel_manager_treeview.get_children(selected_id):\n showerror('Error', 'Could not remove non empty folder.')\n return\n\n self._db_cursor.execute('delete from folder where title = ?', (title,))\n elif type_ == 'channel':\n self._db_cursor.execute('delete from channel where title = ?', (title,))\n self._db_cursor.execute('delete from news where channel_id = (select channel.id from channel where channel.title = ?)', (title,))\n\n # usuń z listy\n self._channel_manager_treeview.delete(selected_id)\n del self._channel_manager_title_type[title]\n\n def _on_add_folder(self, event=None):\n dlg = FolderDialog(self)\n data = dlg.run()\n if data:\n try:\n self._db_cursor.execute('insert into folder(title) values (?)', (data['title'],))\n item_id = self._channel_manager_treeview.insert('', tk.END, text=data['title'], image=self._icons['folder'])\n self._channel_manager_folders[data['title']] = item_id\n self._channel_manager_treeview.selection_set(item_id)\n self._channel_manager_title_type[data['title']] = 'folder'\n except:\n showerror('Error', 'Error while adding new folder.')\n\n def _on_add_channel(self, event=None):\n dlg = ChannelDialog(self)\n data = dlg.run()\n if data:\n self._db_cursor.execute('insert into channel(title, url) values (?, ?)', (data['title'], data['url']))\n\n icon = 'rss'\n if 'youtube' in data['url']:\n icon = 'youtube'\n elif 'twitch' in data['url']:\n icon = 'twitch'\n\n self._channel_manager_channels[data['title']] = self._channel_manager_treeview.insert('', tk.END, text=data['title'], image=self._icons[icon])\n self._channel_manager_title_type[data['title']] = 'channel'\n\n dlg.destroy()\n\n def _on_update_all(self, event=None):\n channels = self._db_cursor.execute('select * from channel').fetchall()\n channel_count = len(channels)\n\n dlg = ProgressDialog(self)\n dlg.show()\n\n for index, channel in enumerate(channels):\n status = ((index + 1) * 1 / channel_count) * 100\n\n dlg.set_position(status, msg=f\"Pobieram wiadomości z kanału {channel['title']}...\")\n self.update_idletasks()\n\n try:\n resp = requests.get(channel['url'], timeout=10.0)\n except:\n dlg.set_position(status, msg=f\"Nie można pobrać wiadomości dla kanału {channel['title']}.\")\n continue\n\n data = feedparser.parse(io.BytesIO(resp.content))\n news = data['items']\n\n # create list of values\n insert_values = []\n for d in news:\n # sanityzuj tytuł\n title = d['title'].replace('\\n', '')\n insert_values.append((channel['id'], d['title'], d['link'], d['summary']))\n\n # build query with placeholders\n placeholders = [\"(?, ?, ?, ?)\" for t in insert_values]\n insert_sql = f\"\"\"\n insert or ignore into news(\n channel_id,\n title,\n url,\n summary\n )\n values {','.join(placeholders)}\n \"\"\"\n\n # insert\n try:\n self._db_cursor.execute(insert_sql, [d for sublist in insert_values for d in sublist])\n except sqlite3.OperationalError as e:\n pass\n finally:\n # ustal ilość nieprzeczytanych dla tego kanału (returning nie działa dla tej wersji sqlite3)\n inserted_count = self._db_cursor.execute('select count(id) from news where channel_id = ? and is_read = 0', (channel['id'],)).fetchone()[0]\n\n # uaktualnij liczbę nieprzeczytanych w kanale\n channel_item = self._channel_manager_channels[channel['title']]\n self._channel_manager_treeview.set(channel_item, '#news-count', inserted_count)\n\n # uaktualnij wagi newsów\n dlg.set_position(100, msg='Uaktualniam rekomendacje...')\n self._recommend_update_quality_all()\n\n dlg.destroy()\n\n def _recommend_count_words(self, text):\n # usuń znaki specjalne\n spec = '~!@#$%^&*()_+{}:\"|<>?`-=[];\\'\\\\,./'\n for spec_char in spec:\n text = text.replace(spec_char, ' ')\n\n # usuń słowa 3 znakowe lub krótsze\n text = text.split()\n text = list(set([word.lower() for word in text if len(word) > 3]))\n return text\n\n def _recommend_update_words(self, words_count):\n # aktualizuj tabelę words\n for word in words_count:\n sql = 'insert into words(word, weight) values(?, 1) on conflict(word) do update set weight = weight + 1 where word = ?'\n self._db_cursor.execute(sql, (word, word))\n\n def _recommend_update_quality_all(self):\n '''Aktualizuje pole quality dla wszystkich nie przeczytanych newsów'''\n sql = \"select news.id, (channel.title || ' ' || news.title || ' ' || summary) as text from news join channel on channel.id = news.channel_id where is_read = 0\"\n q = self._db_cursor.execute(sql)\n for row in q.fetchall():\n words = list(set([f'\"{i}\"' for i in self._recommend_count_words(row['text'])]))\n words_list = f'({\",\".join(words)})'\n new_quality = self._db_cursor.execute(f'select sum(weight) from words where use = 1 and word in {words_list}').fetchone()[0]\n if new_quality is not None:\n self._db_cursor.execute('update news set quality = ? where id = ?', (new_quality, row['id']))\n\n def _recommend_update_quality(self, word):\n # znajdź wszystkie nie przejrzane zawierajace słowo\n sql = \"select news.id, (channel.title || ' ' || news.title || ' ' || summary) as text from news join channel on channel.id = news.channel_id where is_read = 0 and (channel.title || ' ' || news.title || ' ' || summary) like ? collate nocase\"\n q = self._db_cursor.execute(sql, (f'%{word}%',))\n for row in q:\n words = list(set([f'\"{i}\"' for i in self._recommend_count_words(row['text'])]))\n words_list = f'({\",\".join(words)})'\n new_quality = self._db_cursor.execute(f'select sum(weight) from words where use = 1 and word in {words_list}').fetchone()[0]\n if new_quality is not None:\n self._db_cursor.execute('update news set quality = ? where id = ?', (new_quality, row['id']))\n\n def _on_quit(self, event=None):\n if self._db_connection:\n self._db_connection.commit()\n self._db_connection.close()\n self.quit()\n\n\nif __name__ == '__main__':\n app = Application()\n app.mainloop()\n","sub_path":"news.py","file_name":"news.py","file_ext":"py","file_size_in_byte":29262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"142850075","text":"import rasterio as rst\nimport numpy as np\nbasepath=r\"F:\\WORDWIDE_Resample\\Merge_predict_ssw\\Merge\\\\\"\ndef Union(risk,suit):\n result=np.zeros(risk.shape)\n risk[risk<=suit]=0\n suit[risk > suit] = 0\n result=risk+suit\n return result\ndef get_data(path):\n with rst.open(path, mode='r') as dst:\n suit = dst.read(1)\n profile=dst.profile\n return suit,profile\nyears=['2016','2017','2018','2019']\nmonth=['01','02','03','04','05','06','07','08','09','10','11','12']\nsuitDate=[]\nfor y in years:\n for m in month:\n suitDate.append(y+m)\nriskDate=suitDate\ndel riskDate[0]\nfor i in range(len(suitDate)):\n if suitDate[i]=='201907' or suitDate[i]=='201907' or suitDate[i]=='201910' or suitDate[i]=='201911' or suitDate[i]=='201912':\n continue\n mergepath = basepath + \"Merge\" + suitDate[i]+ '.tif'\n riskpath = basepath + \"Risk/Risk\" +riskDate[i]+ \".tif\"\n suit,profile = get_data(mergepath)\n risk,profile = get_data(riskpath)\n union=Union(risk,suit)\n with rst.open(basepath + \"Union/Union\" + riskDate[i] + \".tif\", mode='w', **profile) as dst:\n dst.write(union, 1)\n print(riskDate[i])\n\n","sub_path":"SeaWind/UninonRiskAndSuit.py","file_name":"UninonRiskAndSuit.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160128595","text":"\n#\n# Populater -- Cross platform string syntax for reliably extracting object data\n#\n# Copyright (c) 2018, Web Heroes Inc.\n#\n# Populater is free software: you can redistribute it and/or modify it under the terms of the GNU\n# General Public License as published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version. See the LICENSE file at the top of the source\n# tree.\n#\n# Populater is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\n# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n\n__author__ = \"Matthew Brisebois\"\n__email__ = \"matthew@webheroes.ca\"\n__copyright__ = \"Copyright (c) 2018 Web Heroes Inc.\"\n__license__ = \"Dual License: GPLv3 (or later) and Commercial (see LICENSE)\"\n\n__all__\t\t\t\t= [\"Populater\", \"isolate\"]\n\n\nimport os, sys\nimport logging\n\nscriptname\t\t\t= os.path.splitext( os.path.basename( sys.argv[0] ) )[0]\nlogging.basicConfig(\n filename\t\t\t= '{0}.log'.format(scriptname),\n level\t\t\t= logging.ERROR,\n datefmt\t\t\t= '%Y-%m-%d %H:%M:%S',\n format\t\t\t= '%(asctime)s.%(msecs).03d [ %(threadName)10.10s ] %(name)-15.15s : %(funcName)-15.15s %(levelname)-8.8s %(message)s',\n)\n\nfrom .\t\t\t\timport isolate\nfrom .populater\t\t\timport Populater\n","sub_path":"python/module/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281714709","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function, unicode_literals\nimport unittest\n\nimport mock\n\nfrom importanize.utils import (\n force_bytes,\n force_text,\n is_site_package,\n is_std_lib,\n list_split,\n list_strip,\n read,\n)\n\n\nclass TestUtils(unittest.TestCase):\n def test_is_std_lib(self):\n self.assertFalse(is_std_lib(\"\"))\n\n stdlib_modules = (\n \"argparse\",\n \"codecs\",\n \"collections\",\n \"copy\",\n \"csv\",\n \"datetime\",\n \"decimal\",\n \"fileinput\",\n \"fnmatch\",\n \"functools\",\n \"glob\",\n \"gzip\",\n \"hashlib\",\n \"hmac\",\n \"importlib\",\n \"io\",\n \"itertools\",\n \"json\",\n \"logging\",\n \"math\",\n \"numbers\",\n \"operator\",\n \"optparse\",\n \"os\",\n \"pickle\",\n \"pprint\",\n \"random\",\n \"re\",\n \"shelve\",\n \"shutil\",\n \"socket\",\n \"sqlite3\",\n \"ssl\",\n \"stat\",\n \"string\",\n \"struct\",\n \"subprocess\",\n \"sys\",\n \"sysconfig\",\n \"tempfile\",\n \"time\",\n \"timeit\",\n \"trace\",\n \"traceback\",\n \"unittest\",\n \"uuid\",\n \"xml\",\n \"zlib\",\n )\n for module in stdlib_modules:\n msg = \"{} should be stdlib\"\n self.assertTrue(is_std_lib(module), msg.format(module))\n\n self.assertFalse(is_std_lib(\"foo\"))\n\n def test_is_site_package(self):\n self.assertFalse(is_site_package(\"\"))\n\n # -- Be sure that stdlib modules are not site-packages\n stdlib_modules = (\"argparse\", \"codecs\")\n for module in stdlib_modules:\n msg = \"{} should not be sitepackages\"\n self.assertFalse(is_site_package(module), msg.format(module))\n\n # -- Be sure that fake modules are not site-packages\n self.assertFalse(is_site_package(\"foo\"))\n\n # -- These packages come from requirements-dev.txt\n site_packages_modules = (\"coverage\", \"mock\", \"rednose\", \"tox\")\n for module in site_packages_modules:\n msg = \"{} should be sitepackages\"\n self.assertTrue(is_site_package(module), msg.format(module))\n\n def test_list_strip(self):\n self.assertListEqual(\n list_strip([\" hello \", \"world\"]), [\"hello\", \"world\"]\n )\n\n @mock.patch(\"importanize.utils.open\", create=True)\n def test_read(self, mock_open):\n actual = read(mock.sentinel.path)\n\n mock_open.assert_called_once_with(mock.sentinel.path, \"rb\")\n mock_open.return_value.__enter__.return_value.read.assert_called_once_with()\n mock_open.return_value.__enter__.return_value.read.return_value.decode.assert_called_once_with(\n \"utf-8\"\n )\n\n self.assertEqual(\n actual,\n (\n mock_open.return_value.__enter__.return_value.read.return_value.decode.return_value\n ),\n )\n\n def test_list_split(self):\n self.assertEqual(\n list(list_split([\"foo\", \"/\", \"bar\"], \"/\")), [[\"foo\"], [\"bar\"]]\n )\n\n def test_force_text(self):\n self.assertEqual(force_text(b\"foo\"), \"foo\")\n self.assertEqual(force_text(\"foo\"), \"foo\")\n\n def test_force_bytes(self):\n self.assertEqual(force_bytes(\"foo\"), b\"foo\")\n self.assertEqual(force_bytes(b\"foo\"), b\"foo\")\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"423188374","text":"import multiprocessing\nimport subprocess\nimport operator\nimport math\nimport os\n\ndef parallel_map(func, elements):\n \"\"\"\n Aplica de forma paralela la función 'func' en toda la colección 'elements'. Básicamente\n sería: res = [func(x) for x in elements] pero paralelamente.\n \"\"\"\n cant = len(elements)\n cpus = multiprocessing.cpu_count()\n chunksize = int(math.ceil(cant / cpus))\n outq = multiprocessing.Queue()\n jobs = []\n for i in range(cpus):\n chunk = elements[chunksize * i:chunksize * (i + 1)]\n thread = multiprocessing.Process(\n target=process_chunk, args=(func, chunk, i, outq))\n jobs.append(thread)\n thread.start()\n\n res = []\n for i in range(cpus):\n res.append(outq.get())\n\n for j in jobs:\n j.join()\n\n res.sort(key=operator.itemgetter(0)) #ordeno por índices de chunks\n # for t in res:\n # self.data.extend(t[1])\n\n\ndef process_chunk(func, chunk, chunk_index, outq):\n res = [func(x) for x in chunk]\n outq.put((chunk_index, res))\n\n\ndef parallel_map2(func, elements, params, cores=None):\n cant = len(elements)\n cpus = cores or multiprocessing.cpu_count()\n chunksize = int(math.ceil(cant / cpus))\n jobs = []\n elements_list = list(elements)\n for i in range(cpus):\n chunk = {e: elements[e] for e in elements_list[chunksize * i:chunksize * (i + 1)]}\n thread = multiprocessing.Process(\n target=process_chunk2, args=(func, chunk, i, params))\n jobs.append(thread)\n thread.start()\n for j in jobs:\n j.join()\n\n\ndef process_chunk2(func, chunk, chunk_index, params):\n func(chunk, chunk_index, params)\n\n\ndef parallel_map_to_file(func, elements, outfile):\n \"\"\"\n Aplica de forma paralela la función 'func' en toda la colección 'elements'. Básicamente\n sería: res = [func(x) for x in elements] pero paralelamente.\n \"\"\"\n cant = len(elements)\n cpus = multiprocessing.cpu_count() * 2\n chunksize = int(math.ceil(cant / cpus))\n jobs = []\n for i in range(cpus):\n chunk = elements[chunksize * i:chunksize * (i + 1)]\n thread = multiprocessing.Process(\n target=process_filechunk, args=(func, chunk, i, outfile))\n jobs.append(thread)\n thread.start()\n for j in jobs:\n j.join()\n # unir archivos\n aux_files = [\"{}_{}\".format(outfile, i) for i in range(cpus)]\n os.system(\"cat \" + \" \".join(aux_files) + \" > \" + outfile)\n for af in aux_files:\n os.remove(af)\n\n\ndef process_filechunk(func, chunk, chunk_index, outfile):\n with open(\"{}_{}\".format(outfile, chunk_index), \"w\") as out:\n for element in chunk:\n res = func(element)\n if res:\n out.write(res + \"\\n\")\n ","sub_path":"scraping/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"295105237","text":"import numpy as np\n\n# Define a class to receive the characteristics of each line detection\nclass Line():\n MINIMUM_PIXEL_COUNT = 500\n\n def __init__(self):\n # x values for detected line pixels\n self.allx = None\n # y values for detected line pixels\n self.ally = None\n # was the line detected in the last iteration?\n self.detected = False\n # x values of the last n fits of the line\n self.recent_xfitted = []\n # average x values of the fitted line over the last n iterations\n self.bestx = None\n # polynomial coefficients of the last n iterations\n self.recent_fits = []\n # polynomial coefficients averaged over the last n iterations\n self.best_fit = None\n # radius of curvature of the line in some units\n self.radius_of_curvature = None\n # distance in meters of vehicle center from the line\n self.line_base_pos = None\n # the count of successive detection failures\n self.successive_failure_count = 0\n\n # line detected but not confirmed\n self.temp_line = None\n # the threshold of successive detection failures. If exceeds, reset and start searching from scratch\n self.successive_failure_threshold = 3\n # the number of *n* fits / iterations to be used for self.bestx and self.best_fit\n self.recent_n = 5\n self.window_height = 80\n self.margin = 100\n self.minpix = 50 # minimum pixels to recenter window\n self.ym_per_pix = 30 / 720 # meters per pixel in y dimension\n self.xm_per_pix = 3.7 / 700 # meters per pixel in x dimension\n\n def detect(self, warped, isLeft):\n self.detected = False\n self.temp_line = None\n allx, ally = self._get_line_pixels(warped, isLeft)\n if len(allx) > Line.MINIMUM_PIXEL_COUNT:\n height = warped.shape[0]\n ploty = np.linspace(0, height-1, height)\n current_fit = np.polyfit(ally, allx, 2)\n x_fitted = current_fit[0]*ploty**2 + current_fit[1]*ploty + current_fit[2]\n x_fitted[x_fitted < 0] = 0\n x_fitted[x_fitted >= warped.shape[1]] = warped.shape[1]-1\n radius_of_curvature = self._measure_curvature(ploty, x_fitted, height)\n\n if self._sanity_check(current_fit, radius_of_curvature):\n self.detected = True\n self.temp_line = Line()\n self.temp_line.allx = allx\n self.temp_line.ally = ally\n self.temp_line.current_fit = current_fit\n self.temp_line.x_fitted = x_fitted\n self.temp_line.line_base_pos = abs(self.temp_line.x_fitted[height-1] - warped.shape[1]/2) * self.xm_per_pix\n self.temp_line.radius_of_curvature = radius_of_curvature\n\n self.radius_of_curvature = radius_of_curvature\n\n if not self.detected:\n self.successive_failure_count += 1\n print('Warning: insufficent pixels detected. isLeft: {}, failures: {}'.format(isLeft, self.successive_failure_count))\n\n return self.temp_line\n\n def _get_line_pixels(self, warped, isLeft):\n nonzero = warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n pixel_indices = []\n if self.best_fit is None or self.successive_failure_count > self.successive_failure_threshold:\n pixel_indices = self._detect_line_pixels(warped, isLeft)\n else:\n # Skip sliding windows to search in a margin around the previous line position\n x_fitted = self.best_fit[0]*(nonzeroy**2) + self.best_fit[1]*nonzeroy + self.best_fit[2]\n pixel_indices = ((nonzerox > (x_fitted - self.margin)) & (nonzerox < (x_fitted + self.margin)))\n\n allx = nonzerox[pixel_indices]\n ally = nonzeroy[pixel_indices]\n return (allx, ally)\n\n # Detect line pixels with sliding windows\n def _detect_line_pixels(self, warped, isLeft):\n # Take a histogram of the bottom half of the image\n histogram = np.sum(warped[int(warped.shape[0]/2):,:], axis=0)\n # Find the peak of the bottom half of the histogram\n # It will be the starting point to detect line pixels\n midpoint = np.int(histogram.shape[0]/2)\n x_base = np.argmax(histogram[:midpoint])\n if not isLeft:\n x_base = np.argmax(histogram[midpoint:]) + midpoint\n # Current positions to be updated for each window\n x_current = x_base\n # Identify the x and y positions of all nonzero pixels in the image\n nonzero = warped.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n # Create empty list to receive lane pixel indices\n pixel_indices = []\n # Choose the number of sliding windows\n nwindows = np.int(np.ceil(warped.shape[0]/self.window_height))\n # Step through the windows one by one\n for window in range(nwindows):\n # Identify window boundaries in x and y (and right and left)\n win_y_low = warped.shape[0] - (window+1)*self.window_height\n win_y_high = warped.shape[0] - window*self.window_height\n win_x_low = x_current - self.margin\n win_x_high = x_current + self.margin\n\n # Identify the nonzero pixels in x and y within the window\n good_indices = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &\n (nonzerox >= win_x_low) & (nonzerox < win_x_high)).nonzero()[0]\n # Append these indices to the lists\n pixel_indices.append(good_indices)\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_indices) > self.minpix:\n x_current = np.int(np.mean(nonzerox[good_indices]))\n\n # Concatenate the array of indices\n pixel_indices = np.concatenate(pixel_indices)\n # print('Detect line pixels with sliding windows. pixels detected: {}'.format(len(pixel_indices)))\n return pixel_indices\n\n def _sanity_check(self, current_fit, radius_of_curvature):\n result = True\n # TBD: find a better algorthim for sanity check. radius_of_curvature is not reliable\n # if self.radius_of_curvature is not None:\n # radius_changed = abs(radius_of_curvature/self.radius_of_curvature - 1)\n # result = (radius_changed <= 0.5)\n # if not result:\n # print('radius changed: {}. old: {}, new: {}'.format(radius_changed, self.radius_of_curvature, radius_of_curvature))\n return result\n\n def _measure_curvature(self, ploty, x_fitted, height):\n # Fit new polynomials to x,y in world space\n x_fit_cr = np.polyfit(ploty*self.ym_per_pix, x_fitted*self.xm_per_pix, 2)\n # Calculate the new radii of curvature\n radius_of_curvature = ((1 + (2*x_fit_cr[0]*height*self.ym_per_pix + x_fit_cr[1])**2)**1.5) / np.absolute(2*x_fit_cr[0])\n # Now our radius of curvature is in meters\n return radius_of_curvature\n\n def detection_confirmed(self, is_valid):\n if is_valid:\n self.allx = self.temp_line.allx\n self.ally = self.temp_line.ally\n self.recent_fits.append(self.temp_line.current_fit)\n if len(self.recent_fits) > self.recent_n:\n self.recent_fits.pop(0)\n self.best_fit = np.average(self.recent_fits, axis=0)\n self.recent_xfitted.append(self.temp_line.x_fitted)\n if len(self.recent_xfitted) > self.recent_n:\n self.recent_xfitted.pop(0)\n self.bestx = np.average(self.recent_xfitted, axis=0)\n self.line_base_pos = self.temp_line.line_base_pos\n if self.successive_failure_count > 0:\n self.successive_failure_count = 0\n else:\n self.successive_failure_count += 1\n","sub_path":"line.py","file_name":"line.py","file_ext":"py","file_size_in_byte":7920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"5232020","text":"import sys\nimport os\nimport time\n\nimport numpy as np\nimport pandas as pd\nimport scipy.linalg as LA\nimport scipy.sparse as spar\nfrom scipy.sparse import csgraph\nimport yaml\n\ndef get_nodes_from_spreadsheet(SSArr):\n \"\"\" get the .edge set from a spreadsheet \"\"\"\n nw = np.int_(np.zeros((sum(sum(SSArr != 0)), 3)))\n nw_row = 0\n for col in range(0, SSArr.shape[1]-1):\n for row in range(col+1, SSArr.shape[0]):\n if SSArr[row, col] != 0:\n nw[nw_row, 0] = int(col)\n nw[nw_row, 1] = int(row)\n nw[nw_row, 2] = 1\n nw_row += 1\n return nw\n\ndef get_clustered_spreadsheet(n_clusters, cluster_width, row_multiplier=1):\n \"\"\" synthetic spreadsheet data with n_clusters (2 : 7) of n_clusters * cluster_width samplse \"\"\"\n n_clusters_array = np.array([3,4,5,7])\n nrows = np.product(n_clusters_array*row_multiplier)\n ncols = n_clusters * cluster_width\n print('spreadsheet matrix size = {} x {} with {} clusters'.format(nrows, ncols, n_clusters))\n SSArr = np.zeros((nrows, ncols))\n row_seg_len = int(nrows / n_clusters)\n print('row_seg_len {} x {} n_clusters '.format(row_seg_len, cluster_width))\n row_0 = 0\n col_0 = 0\n row_fin = row_seg_len\n col_fin = cluster_width\n SSArr[row_0:row_fin, col_0:col_fin] += 1\n for k in range(0, n_clusters-1):\n print('rows = {}:{}\\t\\tcols = {}:{}'.format(row_0, row_fin, col_0, col_fin))\n row_0 = row_fin\n col_0 = col_fin\n row_fin = row_0 + row_seg_len\n col_fin = col_0 + cluster_width\n SSArr[row_0:row_fin, col_0:col_fin] += 1\n print('rows = {}:{}\\t\\tcols = {}:{}'.format(row_0, row_fin, col_0, col_fin))\n return SSArr\n\ndef node_set_to_adj_mat(node_set):\n \"\"\" create and adjacency matrix from a network of nodes with edges\n \"\"\"\n nw_sz = max(max(node_set[:, 0]), max(node_set[:, 1])) + 1\n adj_mat = np.zeros((nw_sz, nw_sz))\n for nodie in node_set:\n adj_mat[nodie[0], nodie[1]] = nodie[2]\n adj_mat[nodie[1], nodie[0]] = nodie[2]\n\n return adj_mat\n\ndef adjacency_matrix_to_node_set(N):\n \"\"\" create a network of nodes with edges from an adjacency matrix\n \"\"\"\n Ntru = LA.triu(N)\n l = []\n for row in range(0, N.shape[0]):\n for col in range(row, N.shape[0]):\n if Ntru[row, col] == 1:\n l.append([row, col, 1])\n\n return np.array(l)\n\ndef symmetric_random_adjacency_matrix(network_dim, pct_nodes=0.3):\n \"\"\" symmetric random adjacency matrix from random set of nodes\n Args:\n network_dim: number of rows and columns in the symmetric output matrix\n pct_nodes: number of connections (nodes) as a function of network size.\n Returns:\n network: a symmetric adjacency matrix (0 or 1 in network_dim x network_dim matrix)\n \"\"\"\n n_nodes = np.int_(np.round(pct_nodes * network_dim**2))\n network = np.zeros((network_dim, network_dim))\n col_0 = np.random.randint(0, network_dim, n_nodes)\n col_1 = np.random.randint(0, network_dim, n_nodes)\n for node in range(0, n_nodes):\n if col_0[node] != col_1[node]:\n network[col_0[node], col_1[node]] = 1\n network = network + network.T\n network[network != 0] = 1\n\n return network\n\ndef get_random_clusters(ncols, number_of_clusters=3):\n \"\"\" get a random set of clusters and construct an encoding matrix from those\n\n Args:\n ncols: number of columns\n number_of_clusters: number of rows\n\n Returns:\n H: encoding of the cluster number array\n C: cluster number array\n \"\"\"\n H0 = np.random.rand(number_of_clusters, ncols)\n C = np.argmax(H0, axis=0)\n H = np.zeros(H0.shape)\n for row in range(0, max(C)+1):\n rowdex = C == row\n H[row, rowdex] = 1\n\n return H, C\n\ndef get_rand_unique_name_list(n_names, name_length):\n \"\"\" get a list of different names\n Args:\n n_names: number of unique names in the output\n name_length: number of characters in each name\n Returns:\n rand_uniq_name_list: list of names\n \"\"\"\n bas = 26\n rand_uniq_name_list = []\n p = np.random.permutation(n_names)\n for nm in range(0, n_names):\n rand_uniq_name_list.append(get_character_seq(base_coef_arr(p[nm], bas, name_length) ))\n\n return rand_uniq_name_list\n\ndef get_character_seq(bas_arr, caps=True):\n \"\"\" get a random sequence of characters\n Args:\n bas_arr: array of numbers in range 0, 25\n caps: use Capital letters ? True or False\n Returns:\n char_arr\n \"\"\"\n if caps:\n alf = np.array(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))\n else:\n alf = np.array(list('abcdefghijklmnopqrstuvwxyz'))\n\n if bas_arr.size == 1:\n char_arr = alf[bas_arr]\n else:\n char_arr = ''\n for c in range(0, int(bas_arr.size)):\n char_arr = char_arr + alf[bas_arr[c]]\n\n return char_arr\n\ndef base_coef_arr(big_n, bas, arr_len):\n \"\"\" convert an integer to an array of position multipliers in input base\n Args:\n big_n: an integer\n bas: the base to convert it to\n arr_len: pad the output with zeros to make it this length\n Returns:\n base_coef_arr: array of integers input integer in new base\n \"\"\"\n n = 1\n while big_n - bas ** n > bas:\n n += 1\n if big_n < bas ** n and n > 1:\n n = n - 1\n\n base_coef_arr = np.int_(np.zeros(arr_len))\n start_pos = arr_len - (n + 1)\n for nb in range(0, n):\n this_pwr = bas ** (n - nb)\n this_digit = int(np.floor(big_n / this_pwr))\n big_n = big_n - this_pwr * this_digit\n base_coef_arr[start_pos] = this_digit\n start_pos += 1\n\n base_coef_arr[start_pos] = int(big_n)\n return base_coef_arr\n\ndef append_dictionary_file(full_file, run_pars):\n \"\"\" Append or create a log file using yaml compatible format \"\"\"\n try:\n with open(full_file, 'a') as appendectomyfile:\n for p in run_pars:\n appendectomyfile.write('{}: {}\\n'.format(p, run_pars[p]))\n except:\n print('an err occurred while trying to append dictionary file')\n\ndef get_test_paramters_dictionary():\n \"\"\" universal dctionary of run parameters \"\"\"\n test_parameters = {\n 'method': 'cc_net_cluster_nmf',\n 'method_1': 'cluster_nmf',\n 'method_2': 'cc_cluster_nmf',\n 'method_3': 'net_cluster_nmf',\n 'method_4': 'cc_net_cluster_nmf',\n 'use_parallel_processing': \"0\",\n 'gg_network_name_full_path': './run_dir/input_data/final_clean_4col.edge',\n 'spreadsheet_name_full_path': './run_dir/input_data/final_clean_full_matrix.df',\n 'results_directory': './run_dir/results',\n 'tmp_directory': './run_dir/tmp',\n 'number_of_clusters': '3',\n 'display_clusters': \"0\",\n 'nmf_conv_check_freq': \"50\",\n 'nmf_max_iterations': \"10000\",\n 'nmf_max_invariance': \"200\",\n 'rwr_max_iterations': \"100\",\n 'rwr_convergence_tolerence': \"0.0001\",\n 'rwr_restart_probability': \"0.7\",\n 'nmf_penalty_parameter': \"1400\",\n 'rows_sampling_fraction': \"0.8\",\n 'cols_sampling_fraction': \"0.8\",\n 'number_of_bootstraps': \"5\"}\n return test_parameters","sub_path":"synthetic_data.py","file_name":"synthetic_data.py","file_ext":"py","file_size_in_byte":7195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"44470676","text":"\"\"\"\n线上订单汇总\n统计的区间范围 上个自然月的数据\n每月的一号自动发送\n\"\"\"\nimport sys\nimport pandas as pd\nimport click\nimport re\n\nsys.path.append('../')\n\nfrom utils.db_utils import fetch_data\nfrom utils.time_utils import *\nfrom utils.mail_utils import send_attachment_mail\nfrom utils.comm_utils import clean_file\n\nlogger = get_logger()\n\n\ndef __calculate_statistics_date(to_str=False):\n current_date = get_current_date_str()\n before_date = date_add(current_date, -1, to_str=to_str)\n start_date = str(before_date.year) + '-' + str(before_date.month).zfill(2) + str('-') + '01'\n return start_date, current_date\n\n\ndef __format_ord_state(val):\n state_mapping = {\n 0: '待付款',\n 1: '待发货',\n 2: '部分发货(中药已发货)',\n 3: '部分发货(西药/成药已发货)',\n 4: '已发货(全部药品已发货)',\n 5: '已取消',\n 6: '已关闭'\n }\n return state_mapping[val] if val in state_mapping else '###'\n\n\ndef __format_pay_state(val):\n state_mapping = {\n 0: '待支付',\n 9: '预支付',\n 1: '支付完成',\n 5: '已退款'\n }\n return state_mapping[val] if val in state_mapping else '###'\n\n\ndef fetch_online_order_data(start_date, end_date):\n sql = f\"\"\"\n select\n inquiry_ord_id 订单编号,\n mobile_order.create_date 创建时间,\n medical_ord_id 结算单号,\n mobile_order.user_name 患者姓名,\n doctor.department 科室,\n user.bill_id 联系方式,\n mobile_order.doctor_name 开方医生,\n round(total_price / 10000,2) 支付金额,\n mobile_order.ord_state 订单状态,\n mobile_order.pay_state 付款状态,\n mobile_order.pay_date 付款时间\n from ord.ord_mobile_medical mobile_order\n inner join sec.sec_app_doctor doctor\n on mobile_order.doctor_id = doctor.id\n inner join user.usr_user user\n on mobile_order.user_id = user.user_id\n where\n -- binding_mechanism = '10000046'\n -- doctor.id IN (SELECT id FROM sec.sec_app_doctor WHERE binding_mechanism = '10000046')\n doctor.id NOT IN(SELECT id FROM sec.sec_app_doctor WHERE binding_mechanism = '10001')\n -- and doctor.recommend_id not in (37,39)\n order by inquiry_ord_id desc\n \"\"\"\n logger.info(f'query sql:{sql}')\n ord_df = fetch_data(sql)\n logger.info(f'total fetch {len(ord_df)}条记录')\n order_columns_origin = ord_df.columns.values.tolist()\n file_name = '线上订单.xlsx'\n writer = pd.ExcelWriter(file_name, engine='xlsxwriter')\n if len(ord_df) > 0:\n ord_df['订单状态'] = ord_df['订单状态'].map(__format_ord_state)\n ord_df['付款状态'] = ord_df['付款状态'].map(__format_pay_state)\n start_date_time = start_date + ' 00:00:00' if len(start_date) <= 10 else start_date\n end_date_time = end_date + ' 00:00:00' if len(end_date) <= 10 else end_date\n logger.info(f'start_date:{start_date_time}')\n logger.info(f'end_date:{end_date_time}')\n ord_df['创建时间'] = ord_df['创建时间'].astype('str')\n f1 = ord_df['创建时间'] > start_date_time\n f2 = ord_df['创建时间'] < end_date_time\n ord_df = ord_df[f1 & f2]\n logger.info(f'after filter:{len(ord_df)} 记录')\n ord_df.to_excel(writer, sheet_name='线上订单原始数据', index=False)\n ord_df['支付金额'] = ord_df['支付金额'].astype('float')\n tmp = ord_df.groupby(['开方医生', '患者姓名', '付款状态']).agg({'支付金额': 'sum'}).reset_index()\n tmp.rename(columns={'支付金额': '支付总金额'}, inplace=True)\n tmp.sort_values(by='支付总金额', ascending=False, inplace=True)\n tmp.to_excel(writer, sheet_name='订单汇总信息', index=False)\n # 设置单元格宽度\n writer.sheets['线上订单原始数据'].set_column(0, ord_df.shape[1] - 1, 20)\n writer.sheets['订单汇总信息'].set_column(0,tmp.shape[1] - 1, 20)\n writer.close()\n else:\n logger.warning(f'统计区间内未发现数据,将生成空的数据')\n sheet_one_df = pd.DataFrame(columns=order_columns_origin)\n sheet_two_df = pd.DataFrame(columns=['开方医生', '患者姓名', '付款状态', '支付总金额'])\n sheet_one_df.to_excel(writer, sheet_name='线上订单原始数据', index=False)\n sheet_two_df.to_excel(writer, sheet_name='订单汇总信息', index=False)\n writer.close()\n return file_name\n\n\n@click.command()\n@click.option('--start_date', default='2021-03-01', help='开始日期')\n@click.option('--end_date', default='2021-04-01', help='结束日期')\n@click.option('--send_mail', default=False, help='是否发送邮件')\ndef run(start_date, end_date, send_mail):\n if start_date == '' and end_date == '':\n start_date, end_date = __calculate_statistics_date()\n pattern = r'^\\d{4}-\\d{2}-\\d{2}$'\n compile = re.compile(pattern)\n f1 = bool(compile.match(start_date))\n f2 = bool(compile.match(end_date))\n if not f1:\n logger.error(f'{start_date} 格式无效,skip...')\n return\n elif not f2:\n logger.error(f'{end_date} 格式无效,skip...')\n return\n else:\n file_name = fetch_online_order_data(start_date, end_date)\n if send_mail:\n subject = f'{start_date}~{end_date}线上订单订单统计'\n content = f'内容详见附件'\n send_attachment_mail(subject=subject, content=content, files=file_name)\n clean_file(file_name)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"daily_report/online_order_report.py","file_name":"online_order_report.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349584230","text":"\"\"\"Base classes\"\"\"\n\nfrom multiprocessing import Queue, Event, SimpleQueue\nfrom queue import Empty, Full\nimport logging\n\nclass Sentinel(object):\n\n \"\"\"\n This class is used to indicate the end of a stream. When a instance of Sentinel is\n passed to a Pipe it will shut itself down.\n \"\"\"\n def __repr__(self):\n return 'sentinel'\n\nclass Logger(object):\n\n \"\"\"\n Logger class used by Pipe. There are five levels of logs: INFO, DEBUG, WARNING, ERROR and CRITICAL.\n By default logger is set to INFO.\n\n :param lvl: log level, one of: info, debug, warning, error or critical\n :return: None\n \"\"\"\n\n def __init__(self, lvl='INFO'):\n self.log_lvl_map = {'INFO':logging.INFO,\n 'DEBUG':logging.DEBUG,\n 'WARNING':logging.WARNING,\n 'ERROR':logging.ERROR,\n 'CRITICAL':logging.CRITICAL}\n\n assert(lvl in self.log_lvl_map), \"log_lvl must be one of: {}\".format(self.log_lvl_map.keys())\n self.lvl = self.log_lvl_map[lvl]\n self.logger = logging.getLogger(\"logger\")\n self.logger.propagate = False\n\n # jupyter already has a logger initialized\n # this avoids initializing it multiple times\n if hasattr(self.logger, 'handler_set'):\n while self.logger.handlers:\n self.logger.handlers.pop()\n ch = logging.StreamHandler()\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(pname)s - %(message)s')\n ch.setFormatter(formatter)\n ch.setLevel(lvl)\n self.logger.addHandler(ch)\n self.logger.setLevel(lvl)\n self.logger.handler_set = True\n\n def log(self, msg, name, lvl='info'):\n\n \"\"\"\n Logs messages.\n\n :param msg: message to log\n :param name: name of logger\n :param lvl: log level, one of: info, debug, warning, error or critical\n :return: None\n \"\"\"\n\n extra = {'pname':name}\n if lvl == 'critical':\n self.logger.critical(msg, extra=extra)\n elif lvl == 'debug':\n self.logger.debug(msg, extra=extra)\n elif lvl == 'warning':\n self.logger.warning(msg, extra=extra)\n elif lvl == 'error':\n self.logger.error(msg, extra=extra)\n else:\n self.logger.info(msg, extra=extra)\n\n\nclass Stream(object):\n\n \"\"\"\n Based off of a multiprocessing queue, Stream handles moving data between Pipe segments.\n\n :param name: String, name of Stream\n :param buffer_size: Int, max size of queue. Will be ignored if queue_type = \"multiprocessing.SimpleQueue\"\n :param timeout: Int, timeout(s) value for Queue.put and Queue.get methods\n :param monitor: Bool, log stream I/O times\n :queue_type: String, multiprocesses queue type to be used.\n Valid types: 'multiprocessing.Queue', 'multiprocessing.SimpleQueue'\n :return: None\n \"\"\"\n\n def __init__(self, name = 'stream', buffer_size=3, timeout=None, monitor=False, queue_type='multiprocessing.Queue'):\n\n assert (queue_type.lower() in ('multiprocessing.queue', 'multiprocessing.simplequeue')), \"Error: invalid queue type\"\n\n if queue_type.lower() == 'multiprocessing.simplequeue':\n self.q = SimpleQueue()\n else:\n self.q = Queue(buffer_size)\n\n self.queue_type = queue_type.lower()\n self.timeout = timeout\n self.buffer_size = buffer_size\n self.name = name\n self.monitor = monitor\n self.pipes_out = [] # Reference to Pipes that put onto this stream\n self.pipes_in = [] # Reference to Pipes that get from this stream\n self.logger = None\n\n def _id(self):\n return str(id(self))\n\n def __hash__(self):\n return int(self._id())\n\n def __eq__(self, other):\n return self.__hash__() == hash(other)\n\n def add_pipe_in(self, pipe_in):\n self.pipes_in.append(pipe_in)\n\n def add_pipe_out(self, pipe_out):\n self.pipes_out.append(pipe_out)\n\n def empty(self):\n return self.q.empty()\n\n def full(self):\n return self.q.full()\n\n def capacity(self):\n return 100.0*self.q.qsize()/self.buffer_size\n\n def set_logger(self, logger):\n self.logger = logger\n\n def flush(self):\n try:\n while True:\n self.q.get_nowait()\n except Empty:\n pass\n\n def get(self, timeout=1):\n\n # While pipes out are running and not empty try to get data\n # timeout value is necessary else get may run indefinitely after pipes out shutdown\n\n x = None\n while (any([p._continue() for p in self.pipes_out]) or not self.q.empty()):\n try:\n if self.queue_type == 'multiprocessing.simplequeue':\n x = self.q.get() #SimpleQueue does not have timeout arg\n else:\n x = self.q.get(timeout=timeout or self.timeout)\n if self.monitor:\n self.logger.log('capacity:{:0.2f}%'.format(self.capacity()), self.name+':get')\n break\n except Empty:\n continue\n return x\n\n def put(self, x, timeout=1):\n\n # While pipes in are running try to put data\n # no need to check if full since Full exception is caught\n # timeout value is necessary else put may run indefinitely after pipes in shutdown\n\n while any([p._continue() for p in self.pipes_in]):\n try:\n if x is None:\n break\n if self.queue_type == 'multiprocessing.simplequeue':\n self.q.put(x) #SimpleQueue does not have timeout arg\n else:\n self.q.put(x, timeout=timeout or self.timeout)\n\n if self.monitor:\n self.logger.log('capacity:{:0.2f}%'.format(self.capacity()), self.name+':put')\n break\n except Full:\n continue\n\nclass Pipe(object):\n\n \"\"\"\n Base class for all pipe segments. Pipes use two sets of Streams: upstreams and downstreams.\n Generally Pipes except data from upstreams and pass downstream after a transformation.\n All pipe segments run on their own thread or process, which allows them to run in\n parallel with other segments.\n\n Number of upstreams should be equal to number of functor args. Likewise, number of downstreams\n should be equal to number of functor outputs.\n\n When Pipe produces a None it will not be passed downstream. In this case nothing will be placed\n on the downstreams. This allows the user to create 'switches' based on internal logic in the functor.\n\n\n Base initializer\n -----------------\n\n :param functor: Python function, class, generator or corountine\n :param name: String associated with pipe segment\n :param upstreams: List of Streams that are inputs to functor\n :param downstreams: List of Streams that are outputs of functor\n :param ignore_exceptions: List of exceptions to ignore while pipeline is running\n :param init_kwargs: Kwargs to initiate class object on process (no used when func_type = 'function')\n :param stateful: Set to True when using a class functor. Class functors must implement a 'run' method\n\n \"\"\"\n\n def __init__(self, functor_obj, name, upstreams=None, downstreams=None,\n ignore_exceptions=None, init_kwargs=None):\n\n # Public methods\n self.functor_obj = functor_obj\n self.name = name\n self.init_kwargs = init_kwargs or {}\n self.upstreams = upstreams or []\n self.downstreams = downstreams or []\n self.ignore_exceptions = ignore_exceptions or []\n\n # Check inputs\n for upstream in self.upstreams:\n assert (isinstance(upstream, Stream)), \"Error: upstreams must be of minipipe.Stream type\"\n for downstream in self.downstreams:\n assert (isinstance(downstream, Stream)), \"Error: downtreams must be of minipipe.Stream type\"\n\n # Private methods\n self._n_desc = 0\n self._n_ances = 0\n self._n_rcvd_term_sigs = 0\n self._n_outputs = len(self.downstreams)\n self._n_inputs = len(self.upstreams)\n self._term_flag = Event()\n self._global_term_flag = None\n self._logger = None\n\n def __repr__(self):\n return self.name\n\n def __copy__(self):\n cls = self.__class__\n cp = cls.__new__(cls)\n cp.__dict__.update(self.__dict__)\n cp._term_flag = Event()\n return cp\n\n def _id(self):\n return str(id(self))\n\n def __hash__(self):\n return int(self._id())\n\n def __eq__(self, other):\n return self.__hash__() == hash(other)\n\n def set_logger(self, logger):\n self._logger = logger\n\n def set_term_flag(self, term_flag):\n self._term_flag = term_flag\n\n def set_global_term_flag(self, term_flag):\n self._global_term_flag = term_flag\n\n def set_upstreams(self, upstreams):\n self.upstreams = upstreams\n self._n_inputs = len(upstreams)\n\n def set_downstreams(self, downstreams):\n self.downstreams = downstreams\n self._n_outputs = len(downstreams)\n\n def get_upstreams(self):\n return self.upstreams\n\n def get_downstreams(self):\n return self.downstreams\n\n def public_vars(self):\n return {k:v for k,v in vars(self).items() if k[0] != '_'}\n\n def reset(self):\n self._n_rcvd_term_sigs = 0\n self._term_flag.clear()\n for stream in self.downstreams:\n stream.flush()\n\n def _in(self):\n x = [stream.get() for stream in self.upstreams]\n self._logger.log(\"in({})\".format([repr(x_i) for x_i in x]), self.name, 'debug')\n return x\n\n def _out(self, x):\n if self._n_outputs <=1:\n x = [x]\n self._logger.log(\"out({})\".format([repr(x_i) for x_i in x]), self.name, 'debug')\n for x_i, stream in zip(x, self.downstreams):\n stream.put(x_i)\n\n def _continue(self):\n return not (self._term_flag.is_set() or self._global_term_flag.is_set())\n\n def _contains_sentinel(self, x):\n for x_i in x:\n if x_i is Sentinel:\n return True\n return False\n\n def _contains_none(self, x):\n for x_i in x:\n if x_i is None:\n return True\n return False\n\n def _terminate_global(self):\n self._global_term_flag.set()\n self._logger.log(\"Global termination\", self.name, \"error\")\n return True\n\n def _terminate_local(self):\n\n # Each time a Sentinel is caught this method is called\n # Pipe segment is only shutdown if its recieved a Sentinel from each Pipe upstream\n # If all upstream Pipes are accounted for:\n # 1) set term flag\n # 2) send 1 Sentinel to each downstream Pipe\n # 3) return True\n\n self._n_rcvd_term_sigs += 1\n if self._n_rcvd_term_sigs < self._n_ances:\n return False\n else:\n self._term_flag.set()\n for _ in range(self._n_desc):\n self._out([Sentinel]*self._n_outputs if self._n_outputs > 1 else Sentinel)\n self._logger.log(\"Local termination\", self.name)\n return True\n\n def run_functor(self):\n # To be implemented in derived classes\n pass\n\n def run_pipe(self, name=None):\n # This method is called once on local process\n\n if name is not None:\n self.name = name\n\n # Check if local_init exists and if so initialize on local process\n if hasattr(self.functor_obj, 'local_init'):\n self.functor_obj.local_init(**self.init_kwargs)\n\n # Check if run method exists, if so use it as functor, otherwise use __call__ method\n if hasattr(self.functor_obj, 'run'):\n self.functor = self.functor_obj.run\n else:\n self.functor = self.functor_obj\n\n try:\n # run functor loop on local process\n self.run_functor()\n\n # check if local_term method exists, if so run once after pipe segment has terminated\n if hasattr(self.functor_obj, 'local_term'):\n self.functor_obj.local_term()\n\n except KeyboardInterrupt:\n self._logger.log(\"KeyboardInterrupt\", self.name, 'error')\n\n\n","sub_path":"minipipe/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593713434","text":"from pathlib import Path\nimport pygame\nfrom pygame.locals import *\n\n\ndef load_image(file, transparent=True):\n data_folder = Path(\"../media\")\n file_to_open = data_folder / file\n\n image = pygame.image.load(str(file_to_open))\n\n if transparent == True:\n image = image.convert()\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey, RLEACCEL)\n else:\n image = image.convert_alpha()\n return image\n","sub_path":"graphic/loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48498173","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Testing :mod:`astropy.cosmology.units`.\"\"\"\n\n##############################################################################\n# IMPORTS\n\nimport pytest\n\nimport astropy.cosmology.units as cu\nimport astropy.units as u\nfrom astropy.cosmology import default_cosmology\nfrom astropy.tests.helper import assert_quantity_allclose\nfrom astropy.utils.compat.optional_deps import HAS_ASDF\nfrom astropy.utils.exceptions import AstropyDeprecationWarning\n\n##############################################################################\n# TESTS\n##############################################################################\n\n\ndef test_has_expected_units():\n \"\"\"\n Test that this module has the expected set of units. Some of the units are\n imported from :mod:`astropy.units`, or vice versa. Here we test presence,\n not usage. Units from :mod:`astropy.units` are tested in that module. Units\n defined in :mod:`astropy.cosmology` will be tested subsequently.\n \"\"\"\n with pytest.warns(AstropyDeprecationWarning, match=\"`littleh`\"):\n assert u.astrophys.littleh is cu.littleh\n\n\ndef test_has_expected_equivalencies():\n \"\"\"\n Test that this module has the expected set of equivalencies. Many of the\n equivalencies are imported from :mod:`astropy.units`, so here we test\n presence, not usage. Equivalencies from :mod:`astropy.units` are tested in\n that module. Equivalencies defined in :mod:`astropy.cosmology` will be\n tested subsequently.\n \"\"\"\n with pytest.warns(AstropyDeprecationWarning, match=\"`with_H0`\"):\n assert u.equivalencies.with_H0 is cu.with_H0\n\n\ndef test_littleh():\n H0_70 = 70 * u.km / u.s / u.Mpc\n h70dist = 70 * u.Mpc / cu.littleh\n\n assert_quantity_allclose(h70dist.to(u.Mpc, cu.with_H0(H0_70)), 100 * u.Mpc)\n\n # make sure using the default cosmology works\n cosmodist = default_cosmology.get().H0.value * u.Mpc / cu.littleh\n assert_quantity_allclose(cosmodist.to(u.Mpc, cu.with_H0()), 100 * u.Mpc)\n\n # Now try a luminosity scaling\n h1lum = 0.49 * u.Lsun * cu.littleh ** -2\n assert_quantity_allclose(h1lum.to(u.Lsun, cu.with_H0(H0_70)), 1 * u.Lsun)\n\n # And the trickiest one: magnitudes. Using H0=10 here for the round numbers\n H0_10 = 10 * u.km / u.s / u.Mpc\n # assume the \"true\" magnitude M = 12.\n # Then M - 5*log_10(h) = M + 5 = 17\n withlittlehmag = 17 * (u.mag - u.MagUnit(cu.littleh ** 2))\n assert_quantity_allclose(withlittlehmag.to(u.mag, cu.with_H0(H0_10)), 12 * u.mag)\n\n\n@pytest.mark.skipif(not HAS_ASDF, reason=\"requires ASDF\")\n@pytest.mark.parametrize('equiv', [cu.with_H0()])\ndef test_equivalencies(tmpdir, equiv):\n from asdf.tests import helpers\n\n tree = {'equiv': equiv}\n\n with pytest.warns(AstropyDeprecationWarning, match=\"`with_H0`\"):\n helpers.assert_roundtrip_tree(tree, tmpdir)\n","sub_path":"astropy/cosmology/tests/test_units.py","file_name":"test_units.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"549848789","text":"import Profile\nimport cmd\nimport sys\n\ndef getArgs(line):\n\treturn line.split(\" \")\n\nclass Commands(cmd.Cmd):\n\tdef __init__(self):\n\t\tcmd.Cmd.__init__(self)\n\t\tself.profiles = {}\n\n\tdef onecmd(self, str):\n\t\t#try:\n\t\t\tcmd.Cmd.onecmd(self, str)\n\t\t#except ValueError:\n\t\t\t#print(\"Failed execute command %s\" % str)\n\n\tdef do_load(self, line):\n\t\tfilename, register = getArgs(line)\n\t\ttry:\n\t\t\tprofile = Profile.Profiler(filename)\n\t\texcept FileNotFoundError:\n\t\t\tprint(\"Failed open file %s\" % filename)\n\t\telse:\n\t\t\tprint(\"Load profile file %s into register %s\" % (filename, register))\n\t\t\tself.profiles[register] = profile\n\n\tdef do_unload(self, line):\n\t\tregister = getArgs(line)\n\t\tif register in self.profiles:\n\t\t\tprint(\"Remove profile at register %s\" % register)\n\t\t\tself.profiles.pop(register)\n\t\telse:\n\t\t\tprint(\"Could not found register %s\" % register)\n\n\tdef do_read(self, line):\n\t\tcategory, register = getArgs(line)\n\t\tif register in self.profiles:\n\t\t\tprofile = self.profiles[register]\n\t\t\tprofile.read(category)\n\n\tdef do_compare(self, line):\n\t\tcategory, r1, r2 = getArgs(line)\n\t\tif r1 in self.profiles and r2 in self.profiles:\n\t\t\tp1 = self.profiles[r1]\n\t\t\tp2 = self.profiles[r2]\n\t\t\tp1.compare(category, p2)\n\n\tdef do_list(self, line):\n\t\tfor r in self.profiles.keys():\n\t\t\tprint(\"\\t%s : \\t%s\" % (r, self.profiles[r]))\n\nif __name__ == \"__main__\":\n\ttry:\n\t\tc = Commands()\n\n\t\tfor i in range(1, len(sys.argv), 2):\n\t\t\tc.do_load(sys.argv[i] + \" \" + sys.argv[i + 1])\n\n\t\tc.cmdloop()\n\texcept KeyboardInterrupt:\n\t\tprint(\"Quit\")\n","sub_path":"ProfilerGraph/Console.py","file_name":"Console.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"567506068","text":"import re\n\ndef inlezen_bestand(file_path):\n students_score = {}\n try:\n with open(file_path, 'r', encoding='utf-8') as fo:\n line = fo.readline()\n while line:\n line = re.sub(r':', ' ', line).strip('\\n').split()\n name_sequence = (line[0], line[1])\n score = line[2:]\n students_score.update({' '.join(name_sequence) : score})\n line = fo.readline()\n fo.close()\n return students_score\n except FileNotFoundError:\n print('the file path you have entered does not exist.')\n\n\nstudents = inlezen_bestand('bronbestanden\\Scores.txt')\n\nfor k,v in students.items():\n print(f'Student: {k} geeft de volgende scores behaald:\\n{v}')\n","sub_path":"week6/oef5.py","file_name":"oef5.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"219308058","text":"# -*- coding: utf-8 -*-\n\n# system libraries\nfrom __future__ import print_function\nfrom mpi4py import MPI\nimport numpy as np\nimport sys, os\n\n# runko + auxiliary modules\nimport pytools # runko python tools\n\n# problem specific modules\nfrom problem import Configuration_Turbulence as Configuration\n\nnp.random.seed(1) # global simulation seed\n\n\n\nif __name__ == \"__main__\":\n\n # --------------------------------------------------\n # initial setup\n do_print = False\n if MPI.COMM_WORLD.Get_rank() == 0:\n do_print = True\n\n if do_print:\n print(\"Running pic.py with {} MPI processes.\".format(MPI.COMM_WORLD.Get_size()))\n\n # --------------------------------------------------\n # Timer for profiling\n timer = pytools.Timer()\n\n timer.start(\"total\")\n timer.start(\"init\")\n timer.do_print = do_print\n\n # --------------------------------------------------\n # parse command line arguments\n args = pytools.parse_args()\n\n # create conf object with simulation parameters based on them\n conf = Configuration(args.conf_filename, do_print=do_print)\n\n # --------------------------------------------------\n # load runko\n\n if conf.threeD:\n # 3D modules\n import pycorgi.threeD as pycorgi # corgi ++ bindings\n import pyrunko.pic.threeD as pypic # runko pic c++ bindings\n import pyrunko.fields.threeD as pyfld # runko fld c++ bindings\n\n elif conf.twoD:\n # 2D modules\n import pycorgi.twoD as pycorgi # corgi ++ bindings\n import pyrunko.pic.twoD as pypic # runko pic c++ bindings\n import pyrunko.fields.twoD as pyfld # runko fld c++ bindings\n\n\n # --------------------------------------------------\n # problem setup\n if True:\n from problem import velocity_profile\n from problem import density_profile\n from problem import insert_em_fields\n\n # --------------------------------------------------\n # setup grid\n grid = pycorgi.Grid(conf.Nx, conf.Ny, conf.Nz)\n grid.set_grid_lims(conf.xmin, conf.xmax, conf.ymin, conf.ymax, conf.zmin, conf.zmax)\n\n # compute initial mpi ranks using Hilbert's curve partitioning\n pytools.balance_mpi(grid, conf)\n\n # load pic tiles into grid\n pytools.pic.load_tiles(grid, conf)\n\n # --------------------------------------------------\n # simulation restart\n\n # create output folders\n if grid.master():\n pytools.create_output_folders(conf)\n\n # get current restart file status\n io_stat = pytools.check_for_restart(conf)\n\n # no restart file; initialize simulation\n if io_stat[\"do_initialization\"]:\n if do_print:\n print(\"initializing simulation...\")\n lap = 0\n\n np.random.seed(1) # sync rnd generator seed for different mpi ranks\n\n # injecting plasma particles\n\n prtcl_stat = pytools.pic.inject(grid, velocity_profile, density_profile, conf)\n\n if do_print:\n print(\"injected:\")\n print(\" e- prtcls: {}\".format(prtcl_stat[0]))\n print(\" e+ prtcls: {}\".format(prtcl_stat[1]))\n\n # inserting em grid\n insert_em_fields(grid, conf)\n else:\n if do_print:\n print(\"restarting simulation from lap {}...\".format(io_stat[\"lap\"]))\n\n # read restart files\n pyfld.read_yee(grid, io_stat[\"read_lap\"], io_stat[\"read_dir\"])\n pypic.read_particles(grid, io_stat[\"read_lap\"], io_stat[\"read_dir\"])\n\n # step one step ahead\n lap = io_stat[\"lap\"] + 1\n\n # --------------------------------------------------\n # static load balancing setup; communicate neighborhood info once\n\n grid.analyze_boundaries()\n grid.send_tiles()\n grid.recv_tiles()\n MPI.COMM_WORLD.barrier()\n\n # load virtual mpi halo tiles\n pytools.pic.load_virtual_tiles(grid, conf)\n\n # --------------------------------------------------\n # load physics solvers\n\n pusher = pypic.BorisPusher() #particle pusher\n fldprop = pyfld.FDTD2() #em field propagator\n fintp = pypic.LinearInterpolator() # particle em interpolator\n currint = pypic.ZigZag() # particle current deposition\n flt = pyfld.Binomial2(conf.NxMesh, conf.NyMesh, conf.NzMesh) # current filter\n\n\n # --------------------------------------------------\n # I/O objects\n\n # quick field snapshots\n fld_writer = pyfld.FieldsWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.stride,\n )\n\n # test particles\n prtcl_writer = pypic.TestPrtclWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.ppc,\n len(grid.get_local_tiles()),\n conf.n_test_prtcls,\n )\n\n # prtcl distribution moments (fluid quantities)\n mom_writer = pypic.PicMomentsWriter(\n conf.outdir,\n conf.Nx,\n conf.NxMesh,\n conf.Ny,\n conf.NyMesh,\n conf.Nz,\n conf.NzMesh,\n conf.stride,\n )\n\n # 3D box peripherals\n if conf.threeD:\n slice_xy_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 0, 1)\n slice_xz_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 1, 1)\n slice_yz_writer = pyfld.FieldSliceWriter( conf.outdir, \n conf.Nx, conf.NxMesh, conf.Ny, conf.NyMesh, conf.Nz, conf.NzMesh, 1, \n 2, 1)\n\n\n # --------------------------------------------------\n # add sinusoidal perturbations with antenna\n if io_stat[\"do_initialization\"]:\n timer.start(\"antenna\")\n\n if conf.twoD:\n from antenna2d import Antenna\n antenna = Antenna(conf.min_mode, conf.max_mode, conf)\n for tile in pytools.tiles_local(grid):\n antenna.add_driving(tile)\n\n elif conf.threeD:\n from antenna3d import Antenna\n antenna = Antenna(conf.max_mode, 2, conf)\n\n for tile in pytools.tiles_local(grid):\n antenna.add_driving(tile)\n\n # --------------------------------------------------\n # sync e and b fields \n\n # mpi e\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n\n # mpi b\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n\n # --------------------------------------------------\n # --------------------------------------------------\n # --------------------------------------------------\n # end of initialization\n\n timer.stop(\"init\")\n timer.stats(\"init\")\n # timer.verbose = 1 # 0 normal; 1 - debug mode\n\n ##################################################\n # simulation time step loop\n\n sys.stdout.flush()\n\n\n # simulation loop\n time = lap * (conf.cfl / conf.c_omp)\n for lap in range(lap, conf.Nt + 1):\n\n # --------------------------------------------------\n # push half B \n t1 = timer.start_comp(\"push_half_b1\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_half_b(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_b2\")\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc1\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # move particles (only locals tiles)\n\n # --------------------------------------------------\n # interpolate fields\n t1 = timer.start_comp(\"interp_em\")\n for tile in pytools.tiles_local(grid):\n fintp.solve(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # push particles in x and u\n t1 = timer.start_comp(\"push\")\n for tile in pytools.tiles_local(grid):\n pusher.solve(tile)\n timer.stop_comp(t1)\n\n ##################################################\n # advance second half B \n\n # --------------------------------------------------\n # push B half\n t1 = timer.start_comp(\"push_half_b2\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_half_b(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_e1\")\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc2\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # advance E\n\n # --------------------------------------------------\n # push E\n t1 = timer.start_comp(\"push_e\")\n for tile in pytools.tiles_all(grid):\n fldprop.push_e(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # current calculation; charge conserving current deposition (only local tiles)\n t1 = timer.start_comp(\"comp_curr\")\n for tile in pytools.tiles_local(grid):\n currint.solve(tile)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # clear virtual current arrays for boundary addition after mpi\n t1 = timer.start_comp(\"clear_vir_cur\")\n for tile in pytools.tiles_virtual(grid):\n tile.clear_current()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # mpi send currents\n t1 = timer.start_comp(\"mpi_cur\")\n grid.send_data(0)\n grid.recv_data(0)\n grid.wait_data(0)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # exchange currents\n t1 = timer.start_comp(\"cur_exchange\")\n for tile in pytools.tiles_all(grid):\n tile.exchange_currents(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # particle communication (only local/boundary tiles)\n\n # --------------------------------------------------\n # local particle exchange (independent operation)\n t1 = timer.start_comp(\"check_outg_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.check_outgoing_particles()\n timer.stop_comp(\"check_outg_prtcls\")\n\n # --------------------------------------------------\n # global mpi exchange (independent operation)\n t1 = timer.start_comp(\"pack_outg_prtcls\")\n for tile in pytools.tiles_boundary(grid):\n tile.pack_outgoing_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # MPI global particle exchange\n # transfer primary and extra data\n t1 = timer.start_comp(\"mpi_prtcls\")\n grid.send_data(3)\n grid.recv_data(3)\n grid.wait_data(3)\n\n # orig just after send3\n grid.send_data(4)\n grid.recv_data(4)\n grid.wait_data(4)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # global unpacking (independent operation)\n t1 = timer.start_comp(\"unpack_vir_prtcls\")\n for tile in pytools.tiles_virtual(grid):\n tile.unpack_incoming_particles()\n tile.check_outgoing_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # transfer local + global\n t1 = timer.start_comp(\"get_inc_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.get_incoming_particles(grid)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # delete local transferred particles\n t1 = timer.start_comp(\"del_trnsfrd_prtcls\")\n for tile in pytools.tiles_local(grid):\n tile.delete_transferred_particles()\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # delete all virtual particles (because new prtcls replace these)\n t1 = timer.start_comp(\"del_vir_prtcls\")\n for tile in pytools.tiles_virtual(grid):\n tile.delete_all_particles()\n timer.stop_comp(t1)\n\n ##################################################\n # filter\n timer.start_comp(\"filter\")\n\n # sweep over npasses times\n for fj in range(conf.npasses):\n\n # update global neighbors (mpi)\n grid.send_data(0)\n grid.recv_data(0)\n grid.wait_data(0)\n\n # get halo boundaries and filter (only local tiles)\n for tile in pytools.tiles_local(grid):\n tile.update_boundaries(grid)\n for tile in pytools.tiles_local(grid):\n flt.solve(tile)\n\n MPI.COMM_WORLD.barrier() # sync everybody\n\n # --------------------------------------------------\n timer.stop_comp(\"filter\")\n\n # --------------------------------------------------\n # add current to E\n t1 = timer.start_comp(\"add_cur\")\n for tile in pytools.tiles_all(grid):\n tile.deposit_current()\n timer.stop_comp(t1)\n\n # comm E\n t1 = timer.start_comp(\"mpi_e2\")\n grid.send_data(1)\n grid.recv_data(1)\n grid.wait_data(1)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # comm B\n t1 = timer.start_comp(\"mpi_b1\")\n grid.send_data(2)\n grid.recv_data(2)\n grid.wait_data(2)\n timer.stop_comp(t1)\n\n # --------------------------------------------------\n # update boundaries\n t1 = timer.start_comp(\"upd_bc0\")\n for tile in pytools.tiles_all(grid):\n tile.update_boundaries(grid)\n timer.stop_comp(t1)\n\n ##################################################\n # data reduction and I/O\n\n timer.lap(\"step\")\n if lap % conf.interval == 0:\n if do_print:\n print(\"--------------------------------------------------\")\n print(\"------ lap: {} / t: {}\".format(lap, time))\n\n timer.stats(\"step\")\n timer.comp_stats()\n timer.purge_comps()\n\n # analyze (independent)\n timer.start(\"io\")\n\n # shrink particle arrays\n for tile in pytools.tiles_all(grid):\n tile.shrink_to_fit_all_particles()\n\n # barrier for quick writers\n MPI.COMM_WORLD.barrier()\n\n # shallow IO\n mom_writer.write(grid, lap) # prtcl moments from vel distribution\n fld_writer.write(grid, lap) # quick field snapshots\n\n #interpolate ex,ey,ez and bx,by,bz to prtcl locations and save\n for tile in pytools.tiles_local(grid):\n fintp.solve(tile)\n prtcl_writer.write(grid, lap) # test particles\n\n if conf.threeD:\n slice_xy_writer.write(grid, lap)\n slice_xz_writer.write(grid, lap)\n slice_yz_writer.write(grid, lap)\n\n # deep IO\n if conf.full_interval > 0 and (lap % conf.full_interval == 0) and (lap > 0):\n pyfld.write_yee(grid, lap, conf.outdir + \"/full_output/\")\n pypic.write_particles(grid, lap, conf.outdir + \"/full_output/\")\n\n # restart IO (overwrites)\n if (lap % conf.restart == 0) and (lap > 0):\n\n # flip between two sets of files\n io_stat[\"deep_io_switch\"] = 1 if io_stat[\"deep_io_switch\"] == 0 else 0\n\n pyfld.write_yee(\n grid, io_stat[\"deep_io_switch\"], conf.outdir + \"/restart/\"\n )\n pypic.write_particles(\n grid, io_stat[\"deep_io_switch\"], conf.outdir + \"/restart/\"\n )\n\n # if successful adjust info file\n MPI.COMM_WORLD.barrier() # sync everybody in case of failure before write\n if grid.rank() == 0:\n with open(conf.outdir + \"/restart/laps.txt\", \"a\") as lapfile:\n lapfile.write(\"{},{}\\n\".format(lap, io_stat[\"deep_io_switch\"]))\n\n timer.stop(\"io\")\n\n timer.stats(\"io\")\n timer.start(\"step\") # refresh lap counter (avoids IO profiling)\n\n sys.stdout.flush()\n\n # next step\n time += conf.cfl / conf.c_omp\n # end of loop\n\n # --------------------------------------------------\n # end of simulation\n\n timer.stop(\"total\")\n timer.stats(\"total\")\n","sub_path":"projects/pic-turbulence/pic.py","file_name":"pic.py","file_ext":"py","file_size_in_byte":17201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554168544","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Dec 11 14:42:24 2015\r\n\r\n@author: wu34\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport utilise\r\n\r\ndef similarityDict2list(input_dict):\r\n\tlist_temp = []\r\n\t# available_list = ['039','044','045','048','049','050','051','052','053','054','056','057','058','059','060','061','063','064','065','066','067','068','069','070','071','072','073','074','075']\r\n\ti = 0 \r\n\tfor key1 in input_dict:\r\n\t\tj = 0 \r\n\t\tfor key2 in input_dict:\r\n\t\t\tif j > i:\r\n\t\t\t\tlist_temp.append(input_dict[key1][key2])\r\n\t\t\tj += 1\r\n\t\ti += 1\r\n\t# print list \r\n\treturn list_temp\r\n\r\n\r\ndef plotSimilarityDistribution(sim = 'TFIDFCosin'):\r\n\tactSimilarity_dict = utilise.SimilarityDict('ActItem',sim)\r\n\tsimilarityList = similarityDict2list(actSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('actSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/actSimilarityDistribution_'+sim)\r\n\r\n\tdietSimilarity_dict = utilise.SimilarityDict('DietItem',sim)\r\n\tsimilarityList = similarityDict2list(dietSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('dietSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/dietSimilarityDistribution_'+sim)\r\n\r\n\tactTypeSimilarity_dict = utilise.SimilarityDict('ActType',sim)\r\n\tsimilarityList = similarityDict2list(actTypeSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('actTypeSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/actTypeSimilarityDistribution_'+sim)\r\n\r\n\tdietTypeSimilarity_dict = utilise.SimilarityDict('DietType',sim)\r\n\tsimilarityList = similarityDict2list(dietTypeSimilarity_dict)\r\n\tplt.figure()\r\n\tplt.hist(similarityList)\r\n\tplt.title('dietTypeSimilarityDistribution_'+sim)\r\n\tplt.xlim(0.0,1.0)\r\n\tplt.savefig('visSimilarityDistributionHist/dietTypeSimilarityDistribution_'+sim)\r\n\r\nplotSimilarityDistribution('jaccard')\r\nplotSimilarityDistribution('novelJaccard')\r\nplotSimilarityDistribution('TFCosin')\r\nplotSimilarityDistribution('TFEclud')\r\nplotSimilarityDistribution('TFIDFCosin')\r\nplotSimilarityDistribution('TFIDFEclud')\r\n","sub_path":"visSimilarityDistribution.py","file_name":"visSimilarityDistribution.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"409500014","text":"from django.shortcuts import render\n\nfrom django.views.generic.base import View\nfrom django.contrib.auth import get_user_model\nfrom django.http import Http404\n\n\n# Create your views here.\n\n# function for the index page\n\n\nclass Index(View):\n model = get_user_model()\n\n def get(self, request, *args, **kwargs):\n if self.request.user.is_authenticated:\n try:\n user_obj = self.model.objects.get(id=request.user.id)\n except self.model.DoesNotExist:\n raise Http404\n print(\"ooooooooooooooo\")\n print(user_obj)\n context={\"user_obj\": user_obj}\n return render(request, 'beyonic_users/index.html', context)\n context={}\n return render(request, 'beyonic_users/index.html', context)","sub_path":"beyonic_users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25934930","text":"if __name__ == \"__main__\":\n headers = {\"Authorization\" : \"KakaoAK \" + KAKAO_REST_KEY}\n res1 = requests.get(\n url=KAKAO_BASE_URL + \"/v3/search/book?target=title&query=코스모스\",\n headers=headers\n )\n\n if res1.status_code == 200:\n books = res1.json()\n for book in books['documents']:\n print(book)\n # print(\"{0:50s} - {1:20s}\".format(str(book['title']), str(book['authors'])))\n else:\n print(\"Error {0}\".format(res1.status_code))","sub_path":"activity list/MOSAIC(Koreatech Start Up)/Crawling/Facebook/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"125490687","text":"from os import listdir\nfrom os.path import isfile, join, isdir\nrootfolder = \"D:/ProjectData/caltech101/101_ObjectCategories/\"\nonlyfolders= [f for f in listdir(rootfolder) if isdir(join(rootfolder, f))]\n\nwith open('pointerList.list1', 'w') as plist:\n\tfor ifolder in onlyfolders:\n\t\tsubfolder = rootfolder + ifolder + \"/\"\n\t\t#folder = \"D:/Users/Bishal Santra/Documents/MATLAB/MTP/neural_generative/caltech101/101_ObjectCategories/cup\"\n\t\tonlyfiles= [join(subfolder, f) for f in listdir(subfolder) if isfile(join(subfolder, f))]\n\t\tplist.write(ifolder+ \"\\n\")\n\t\tplist.write(str(len(onlyfiles)) + \"\\n\")\n\t\twith open(ifolder + \".list2\", \"w\") as wfile:\n\t\t\tfor iname in onlyfiles:\n\t\t\t\twfile.write(iname + \"\\n\")","sub_path":"MTP_Port2/rfiles/flister.py","file_name":"flister.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149608532","text":"import unittest\nimport parity\nimport csv\n\n\nclass FlipCellTests(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n unittest.TestCase.__init__(self, *args, **kwargs)\n self.maxDiff = None\n self.small_grid = self.load_grid_from_csv(\"tests/grids/expected_small_grid.csv\")\n self.small_grid_flipped = self.load_grid_from_csv(\"tests/grids/small_grid_flipped.csv\")\n self.medium_grid = self.load_grid_from_csv(\"tests/grids/expected_medium_grid.csv\")\n self.medium_grid_flipped = self.load_grid_from_csv(\"tests/grids/medium_grid_flipped.csv\")\n self.large_grid = self.load_grid_from_csv(\"tests/grids/expected_large_grid.csv\")\n self.large_grid_flipped = self.load_grid_from_csv(\"tests/grids/large_grid_flipped.csv\")\n\n def load_grid_from_csv(self, csv_file_path):\n grid = []\n with open(csv_file_path) as csv_file:\n reader = csv.reader(csv_file)\n for line in reader:\n grid.append(line)\n return grid\n\n def test_flip_cell(self):\n result_grid = parity.flip_cell(1, 2, self.small_grid)\n self.assertListEqual(result_grid, self.small_grid_flipped)\n\n result_grid = parity.flip_cell(7, 9, self.medium_grid)\n self.assertListEqual(result_grid, self.medium_grid_flipped)\n\n result_grid = parity.flip_cell(26, 75, self.large_grid)\n self.assertListEqual(result_grid, self.large_grid_flipped)\n","sub_path":"parity_project/starter/tests/test_flip_cell.py","file_name":"test_flip_cell.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237045424","text":"import os\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\n# Creating a databse engine in line 6. \n# The engine is an object created by SQL alchemy, this third party library that we're going to be using.\n# os.getenv database URL specifies in an environment variable the database URL. The URL of where my database lives.\n# In my case, that URL is local host, my own computer. But if you've got a database that's living somewhere else on the internet, that might actually be a URL.\n\nengine = create_engine(os.getenv(\"DATABASE_URL\"))\ndb = scoped_session(sessionmaker(bind=engine))\n\n# On line 10, we're creating a scope session. When we take our web application to the internet, we have multiple people that are simultaneously trying to use our website at the same time, we want to make sure that the stuff that person A is doing with the database is kept separate from the stuff that person B is doing with the database.\n# And so creating different sessions for different people is just a way of managing that.\n# We have this object called db which allows us to run SQL commands.\n\ndef main():\n flights = db.execute(\"SELECT origin, destination, duration FROM flights\").fetchall()\n for flight in flights:\n print(f\"{flight.origin} to {flight.destination}, {flight.duration} minutes.\")\n\n# On line 18, I want a query for all of my flight. In the quotation mark, I can specify whatever SQL command I want to run.\n# fetchall query gets all of the results.\n# On line 19 to 20, I print the results out.\n\nif __name__ == \"__main__\":\n main()","sub_path":"My Practice/SQL/list/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"556923108","text":"# Pedro Sanchez\n\n# ==================================================\n# IMPORTS\n# ==================================================\n\nimport numpy as np\nimport math\n\nfrom sklearn.cluster import MiniBatchKMeans, KMeans\nfrom sklearn.metrics.pairwise import euclidean_distances\n\n# ==================================================\n# DEFINE CONSTANTS\n# ==================================================\n\nNUM_DATASET_INSTANCES = 581012\nNUM_TRAINING_INSTANCES = 15120\nNUM_TESTING_INSTANCES = 565892\n\nNUM_FEATURES = 54 + 1\n\nTRAIN_FILE = \"covtype_training.txt\"\nTEST_FILE = \"covtype_testing.txt\"\n\n# ==================================================\n# PARSE DATA FUNCTIONS\n# ==================================================\n\ndef formatFileIntoNumpy(filename):\n\t\n\trawData = open(filename,\"r\")\n\tlines = rawData.read().split(\"\\n\")\n\n\tdata_list = []\n\ty_list = []\n\n\tfor i in range(len(lines)):\n\t\tstring = lines[i].split(\",\")\n\t\ty_list.append(string[NUM_FEATURES-1:])\n\t\tdata_list.append(string[:-1])\n\n\tx = np.ones((len(lines),NUM_FEATURES))\n\ty = np.ones((len(lines),1))\n\n\tfor i in range(len(lines)):\n\t\ty[i] = y_list[i]\n\t\tfor j in range(NUM_FEATURES-1):\n\t\t\tx[i][j] = data_list[i][j]\n\n\treturn x,y\n\n\ndef getData(train_fname, test_fname):\n\tx_train, y_train = formatFileIntoNumpy(train_fname)\n\tx_test, y_test = formatFileIntoNumpy(test_fname)\n\treturn x_train, y_train, x_test, y_test\n\n# ==================================================\n# HELPER FUNCTIONS\n# ==================================================\n\ndef getClusterToLabelMapping(cxl,n):\n\t\n\thi, hiIndex = 0,0\n\tlabel_mappings = [[],[],[],[],[],[],[]]\n\n\tfor i in range(n):\n\t\thi = cxl[i][0]\n\t\tfor j in range(1,n):\n\t\t\tif(hi < cxl[i][j]):\n\t\t\t\thi = cxl[i][j]\n\t\tfor j in range(n):\n\t\t\tif( hi == cxl[i][j] ):\n\t\t\t\tlabel_mappings[i].append(j)\n\n\treturn label_mappings\n\n# ==================================================\n# EXECUTE\n# ==================================================\n\nprint(\"...\")\nx_train, y_train, x_test, y_test = getData(TRAIN_FILE, TEST_FILE)\n\nnum_clusters = 2\n\nwhile( num_clusters <= 3 ):\n\t#fit k_means over training data\n\tk_means = KMeans(n_clusters=num_clusters, init='k-means++', n_init=10).fit(x_train)\n\n\tcentroids = np.ones((num_clusters, NUM_FEATURES))\n\tcentroids = k_means.cluster_centers_\n\n\tprint(centroids)\n\n\ttraining_error = 0.0\n\ttesting_error = 0.0\n\n\t#get cluster predictions based on fit over training data\n\tclusters_train = k_means.predict(x_train)\n\n\n\n\tfor i in range(len(clusters_train)):\n\t\tprint(\"x_train[i]\")\n\t\tprint(x_train[i])\n\t\tprint(\"centroids[clusters_train[i]\")\n\t\tprint(centroids[clusters_train[i]])\n\t\tprint(\"(x_train[i]-centroids[clusters_train[i]])\")\n\t\tprint((x_train[i]-centroids[clusters_train[i]]))\n\t\tprint(\"(x_train[i]-centroids[clusters_train[i]]).transpose()\")\n\t\tprint((x_train[i]-centroids[clusters_train[i]]).transpose())\n\t\tprint(\"np.dot((x_test[i]-centroids[clusters_test[i]]),(x_test[i]-centroids[clusters_test[i]]).transpose())\")\n\t\tprint(np.dot((x_train[i]-centroids[clusters_train[i]]),(x_train[i]-centroids[clusters_train[i]]).transpose()))\n\t\tprint(\"\\n\\n\\n\\n\\n\\n\")\n\t\ttraining_error += np.dot((x_train[i]-centroids[clusters_train[i]]),(x_train[i]-centroids[clusters_train[i]]).transpose())\n\ttraining_error /= NUM_TRAINING_INSTANCES\n\t\n\tclusters_test = k_means.predict(x_test)\n\tfor i in range(len(clusters_test)):\n\t\ttesting_error += np.dot((x_test[i]-centroids[clusters_test[i]]),(x_test[i]-centroids[clusters_test[i]]).transpose())\n\ttesting_error /= NUM_TESTING_INSTANCES\n\t\n\tprint(str(num_clusters)+\",\\t\"+str(training_error)+\",\\t\"+str(testing_error))\n\n\tnum_clusters+=1\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Classifying:Clustering_ForestCoverType_Project/covtype_clustering_error.py","file_name":"covtype_clustering_error.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213334103","text":"\r\nlenght_edge=[]\r\ndef q_squares(lenght, widht, n=0):\r\n while lenght!=0 or widht!=0:\r\n if lenght==widht:\r\n lenght_edge.append(1)\r\n return q_squares(lenght-1, widht - 1, n + 1)\r\n if lenght\", self.showdata_into_entry)\n\n def calc1(self):\n self.calc = Calendar(self.wn, selectmode=\"day\", date_pattern=\"yyyy/mm/dd\")\n self.calc.place(x=520, y=345)\n def getvalue1(self):\n self.from_date_var.set(self.calc.get_date())\n\n def getvalue2(self):\n self.to_date_var.set(self.calc.get_date())\n\n def view_window(self):\n self.screen = Tk()\n self.screen.geometry(\"825x723+680+90\")\n self.screen.config(bg=\"light green\")\n # =====first frame inside view window=======\n self.view_frame = Frame(self.screen, bd=5, bg=\"white\", relief=RIDGE)\n self.view_frame.place(x=10,y=130,width=805,height=580)\n # ========searching======\n lbl_search = Label(self.screen, text=\"Search By:\", font=(\"times new roman\", 25, \"bold\"), fg=\"maroon\",\n bg=\"light green\")\n lbl_search.grid(row=0, column=0, sticky=\"w\", padx=10, pady=10)\n self.combo_search = ttk.Combobox(self.screen, width=13,\n font=(\"times new roman\", 13, \"bold\"), state=\"readonly\")\n self.combo_search[\"values\"] = (\"First_Name\")\n self.combo_search.grid(row=0, column=1, padx=10, pady=10)\n self.search_ent = Entry(self.screen, font=(\"arial\", 12, \"bold\"), bd=1, relief=GROOVE)\n self.search_ent.grid(row=0, column=2, padx=10, pady=10)\n search_btn = Button(self.screen, text=\"Search\", font=(\"times new roman\", 15, \"bold\"), bd=5, fg=\"black\",\n bg=\"white\",\n width=8,command=self.search_data1)\n search_btn.grid(row=0, column=3, padx=10, pady=10)\n searchall_btn = Button(self.screen, text=\"Search All\", font=(\"times new roman\", 15, \"bold\"), bd=5,\n fg=\"black\",\n bg=\"white\",\n width=8,command=self.show_table)\n searchall_btn.grid(row=0, column=4, padx=10, pady=10)\n # =======sorting==========\n lbl_sort = Label(self.screen, text=\"Sort By:\", font=(\"times new roman\", 25, \"bold\"), fg=\"black\",\n bg=\"light green\")\n lbl_sort.place(x=10, y=70)\n combo_sort = ttk.Combobox(self.screen, width=13,\n font=(\"times new roman\", 13, \"bold\"), state=\"readonly\")\n combo_sort[\"values\"] = (\"Student_ID_No\")\n combo_sort.place(x=140, y=76, width=200)\n sort_btn = Button(self.screen, text=\"Sort\", font=(\"times new roman\", 15, \"bold\"), bd=5, fg=\"black\",\n bg=\"yellow\",\n width=8,command=self.sorting)\n sort_btn.place(x=380, y=70)\n #======scrollbar=========\n scroll_x = Scrollbar(self.view_frame, orient=HORIZONTAL)\n scroll_y = Scrollbar(self.view_frame, orient=VERTICAL)\n self.stu_table = ttk.Treeview(self.view_frame, columns=(\"Student_ID_No\",\n \"First_Name\", \"Last_Name\", \"From\",\"To\",\"Total Number of days\",\n \"Number of days present\",\"Number of days absent\"),\n xscrollcommand=scroll_x.set,\n yscrollcommand=scroll_y.set)\n\n scroll_x.pack(side=BOTTOM, fill=X)\n scroll_y.pack(side=RIGHT, fill=Y)\n scroll_x.config(command=self.stu_table .xview)\n scroll_y.config(command=self.stu_table .yview)\n self.stu_table .heading(\"Student_ID_No\", text=\"Student_ID_No\")\n self.stu_table .heading(\"First_Name\", text=\"First_Name\")\n self.stu_table .heading(\"Last_Name\", text=\"Last_Name\")\n self.stu_table .heading(\"From\", text=\"From\")\n self.stu_table .heading(\"To\", text=\"To\")\n self.stu_table .heading(\"Total Number of days\", text=\"Total Number of days\")\n self.stu_table .heading(\"Number of days present\",text=\"Number of days present\")\n self.stu_table .heading(\"Number of days absent\", text=\"Number of days absent\")\n self.stu_table ['show'] = \"headings\"\n self.stu_table .pack(fill=BOTH, expand=1)\n self.show_table()\n self.stu_table .bind(\"\", self.displaydata_into_entry)\n\n def search_data(self):\n try:\n query = \"select ID_No,First_Name,Last_Name from tbl_student where \" + str(\n self.combo_search1.get()) + \"=\" + str(self.search_ent1.get())\n row = self.con_studentattendence.select1(query)\n # print(row)\n if len(row) != 0:\n self.sattent_table.delete(*self.sattent_table.get_children())\n for i in row:\n self.sattent_table.insert('', END, values=i)\n\n\n except Exception as es:\n\n messagebox.showerror(\"error\",f\"error due to {str(es)}\")\n\n\n def showdata_into_entry(self,ev):\n row_cursor=self.sattent_table.focus()\n contents=self.sattent_table.item(row_cursor)\n row=contents['values']\n self.ent_id.delete(0, END)\n self.ent_id.insert(END,row[0])\n self.ent_Name.delete(0, END)\n self.ent_Name.insert(END,row[1])\n self.ent_lname.delete(0, END)\n self.ent_lname.insert(END,row[2])\n\n\n def add(self):\n if self.ent_id.get()==\"\" or self.ent_Name.get()==\"\" or self.ent_lname.get()==\"\" or \\\n self.from_date_var.get()==\"\" or self.to_date_var.get()==\"\" or self.ent_totalday.get()==\"\" or \\\n self.ent_present.get()==\"\" or self.ent_absent.get()==\"\":\n messagebox.showerror(\"Error\",\"All fields are required\")\n\n\n elif self.ent_id.get().isalpha() or self.ent_totalday.get().isalpha() or self.ent_present.get().isalpha() or \\\n self.ent_absent.get().isalpha():\n messagebox.showerror(\"Error\", \"Alphabetical value is not allowed in staff id,total days, present days and absent days\")\n else:\n try:\n\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),\n self.ent_lname.get(),self.from_date_var.get(),\n self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n query=\"insert into tbl_student_attendance values(%s,%s,%s,%s,%s,%s,%s,%s);\"\n values=(stuattendance_obj.get_ID_No(),stuattendance_obj.get_First_Name(),stuattendance_obj.get_Last_Name(),\n stuattendance_obj.get_From(),stuattendance_obj.get_To(),stuattendance_obj.get_Total_days(),\n stuattendance_obj.get_Days_present(),stuattendance_obj.get_Days_absent())\n self.con_studentattendence.insert(query,values)\n messagebox.showinfo(\"error\",\"Data inserted in database successfully\")\n self.clear()\n\n\n except Exception as e:\n messagebox.showerror(\"error\",f\"error due to {str(e)}\")\n\n\n def show_table(self):\n query_select=\"select * from tbl_student_attendance;\"\n row1=self.con_studentattendence.select1(query_select)\n if len(row1)!=0:\n self.stu_table.delete(*self.stu_table.get_children())\n for i in row1:\n self.stu_table.insert('',END,values=i)\n\n def clear(self):\n self.ent_id.delete(0,END)\n self.ent_Name.delete(0, END)\n self.ent_lname.delete(0, END)\n self.from_date_var.set(\"\")\n self.to_date_var.set(\"\")\n self.ent_totalday.delete(0, END)\n self.ent_present.delete(0,END)\n self.ent_absent.delete(0,END)\n\n def displaydata_into_entry(self,ev):\n row_cursor=self.stu_table.focus()\n contents=self.stu_table.item(row_cursor)\n row=contents['values']\n self.ent_id.delete(0, END)\n self.ent_id.insert(END, row[0])\n self.ent_Name.delete(0, END)\n self.ent_Name.insert(END, row[1])\n self.ent_lname.delete(0, END)\n self.ent_lname.insert(END, row[2])\n self.from_date_var.set(row[3])\n self.to_date_var.set(row[4])\n self.ent_totalday.delete(0, END)\n self.ent_totalday.insert(END, row[5])\n self.ent_present.delete(0, END)\n self.ent_present.insert(END, row[6])\n self.ent_absent.delete(0, END)\n self.ent_absent.insert(END, row[7])\n\n def delete(self):\n if self.ent_id.get() == \"\":\n messagebox.showerror(\"error\", \"please enter id nnumber to delete\")\n else:\n\n try:\n query = \"delete from tbl_student_attendance where Student_ID_No=%s;\"\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),\n self.ent_lname.get(),self.from_date_var.get(),\n self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n value = (stuattendance_obj.get_ID_No(),)\n self.con_studentattendence.delete(query, value)\n messagebox.showinfo(\"success\", \"data deleted successfully\",parent=self.screen)\n self.show_table()\n self.clear()\n\n except Exception as es:\n messagebox.showerror(\"error\", f\"error due to {str(es)} \")\n\n def update(self):\n if self.ent_id.get() == \"\":\n messagebox.showerror(\"error\", \"please enter the student id to update student data\")\n else:\n try:\n stuattendance_obj=Model_studentattendance(self.ent_id.get(),self.ent_Name.get(),self.ent_lname.get(),\n self.from_date_var.get(),self.to_date_var.get(),self.ent_totalday.get(),\n self.ent_present.get(),self.ent_absent.get())\n query = \"update tbl_student_attendance set From_date=%s,To_date=%s,Total_days=%s,Present_days=%s,Absent_days=%s where \" \\\n \"Student_ID_No=%s;\"\n values = (\n stuattendance_obj.get_From(),stuattendance_obj.get_To(),stuattendance_obj.get_Total_days(),\n stuattendance_obj.get_Days_present(),stuattendance_obj.get_Days_absent(),stuattendance_obj.get_ID_No())\n self.con_studentattendence.update(query, values)\n messagebox.showinfo(\"success\", \"Data updated successfully\",parent=self.screen)\n self.show_table()\n self.clear()\n\n\n except Exception as es:\n messagebox.showerror(\"error\", f\"error due to {str(es)} \")\n\n def sorting(self):\n query = \"select * from tbl_student_attendance;\"\n records = self.con_studentattendence.select1(query)\n data_list1 = []\n for row in records:\n data_list1.append(row)\n d=self.bubblesort_ascending(data_list1)\n\n\n def bubblesort_ascending(self, list):\n for j in range(len(list)-1):\n for i in range(len(list)-1):\n if list[i] > list[i + 1]:\n list[i],list[i+1]=list[i+1],list[i]\n messagebox.showinfo(\"success\",\"list has been sorted in ascending order bu student id number\",parent=self.screen)\n if len(list)!=0:\n self.stu_table.delete(*self.stu_table.get_children())\n for i in list:\n self.stu_table.insert('',END,values=i)\n\n def search_data1(self):\n query = \"select First_Name from tbl_student_attendance;\"\n records = self.con_studentattendence.select1(query)\n data_list = []\n for row in records:\n data_list.append(row[0])\n ans = self.linear_search(data_list, self.search_ent.get())\n def linear_search(self, data, item):\n for i in data:\n if i == item:\n messagebox.showinfo('Success', 'congrats Name exists in this list',parent=self.screen)\n query1 =\"select * from tbl_student_attendance where First_Name=%s;\"\n values1=(self.search_ent.get(),)\n records1 = self.con_studentattendence.select(query1,values1)\n if len(records1) != 0:\n self.stu_table.delete(*self.stu_table.get_children())\n for row in records1:\n self.stu_table.insert('', END, values=row)\n\n break\n\n else:\n messagebox.showerror('error', 'sorry this Name doesnot exist in this list',parent=self.screen)\n\n\n\n\n# window=Tk()\n# Attendance(window)\n# window.mainloop()","sub_path":"front_end1/Student_attendance_section.py","file_name":"Student_attendance_section.py","file_ext":"py","file_size_in_byte":21954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233687503","text":"# --------------\n# import libraries\nimport numpy as np\nimport pandas as pd\nimport re\n\n# Load data\n##Loading the CSV data onto a Pandas dataframe, and then subsetting as suggested\ndata = pd.read_csv(path, parse_dates = [0], infer_datetime_format = True)\n\n# Sort headlines by date of publish\n##Sorting the data as per publishing date\ndata.sort_values(\"publish_date\", inplace = True)\n\n# Retain only alphabets\n##Retaining only the alphabets\ndata[\"headline_text\"] = data[\"headline_text\"].apply(lambda x: re.sub(\"[^a-zA-Z]\", \" \", x))\n\n# Look at the shape of data\n##Checking the shape of the data\ndata.shape\n\n# Look at the first first five observations\n##Checking the top 5 rows ofthe data\ndata.head()\n\n\n\n\n# --------------\n# import libraries\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport operator\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# Initialize CountVectorizer\n# Transform headlines\n##Intantiating a CountVectorizer object, and fit-transforming the \"headline_text\" column\nvectorizer = CountVectorizer(stop_words = \"english\", max_features = 30000)\nnews = vectorizer.fit_transform(data[\"headline_text\"])\n\n# initialize empty dictionary\n# initialize with 0\n##Initializing an empty dictionary and i as 0\nwords = {}\ni = 0\n\n# Number of time every feature appears over the entire document\n##Calculating the number of times every word/feature appears in the corpus\nsums = np.array(np.sum(news, axis=0)).flatten()\n\n# Loop to map 'sums' to its word\n##Creating a for loop to populate the above dictionary\nfor word in vectorizer.get_feature_names():\n words[word] = sums[i]\n i += 1\n \n# Top 20 most occuring words\n##Seggregating the 20 most occuring words, and capturing tehse and their values\ntop_20 = sorted(words.items(), key = operator.itemgetter(1), reverse = True)[:20]\ntop_20_words = [i[0] for i in top_20]\ntop_20_values = [i[1] for i in top_20]\n\n# Display top 20 words\n##Plotting the 20 most occuring words\nsns.barplot(x = top_20_words, y = top_20_values)\nplt.title(\"Top 20 Words\")\nplt.xlabel(\"Words\")\nplt.ylabel(\"Values\")\nplt.show()\n\n\n\n\n# --------------\n# import libraries\nfrom sklearn.decomposition import TruncatedSVD, LatentDirichletAllocation\nimport pprint\n\n# number of topics\n##Setting a number for topic count\nn_topics = 5\n\n# initialize SVD\n# fit and transform 'news'\n##Intantiating a truncated SVD model, and fit-transforming the vectorized data\nlsa_model = TruncatedSVD(n_components = n_topics, random_state = 2)\nlsa_topic_matrix = lsa_model.fit_transform(news)\n\n\n'''We are not interested in knowing every word of a topic.\nInstead, we want to look at the first (lets say) 10 words\nof a topic'''\n\n\n# empty dictionary to store topic number and top 10 words for every topic \n# loop over every topic\n##Initializing an empty dictionary to iteratively capture topic number and top 10 words for every topic\ntopic_lsa = {}\nfor i, topic in enumerate(lsa_model.components_):\n key = \"Topic {}\".format(i)\n value = [(vectorizer.get_feature_names()[i] + \"*\" + str(topic[i])) for i in topic.argsort()[:-11:-1]]\n topic_lsa[key] = \" + \".join(value)\n \n# pretty print topics\n##Outputting the topic dictionary\npprint.pprint(topic_lsa)\n\n\n\n\n# --------------\n# import libraries\nimport nltk\nimport gensim\nimport gensim.corpora as corpora\nfrom gensim.utils import simple_preprocess\nfrom gensim.models import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\nfrom gensim.utils import simple_preprocess\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords \nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport matplotlib.pyplot as plt\n\n# Function to clean data from stopwords, punctuation marks and lemmatize\ndef clean(doc):\n stop_free = \" \".join([i for i in doc.lower().split() if i not in stop])\n punc_free = ''.join(ch for ch in stop_free if ch not in exclude)\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\n return normalized\n\n\n# Code starts here\n\n# stopwords list\n##Intantiating a stopwords object\nstop = set(stopwords.words(\"english\"))\n\n# string punctuations\n##Setting up a punctuation excluder\nexclude = set(string.punctuation)\n\n# lemmatizer\n##Intantiating a word-lemmatizer object\nlemma = WordNetLemmatizer()\n\n# convert headlines to list\n##Outputting the \"headlines_text\" column as a list\nheadlines = data[\"headline_text\"].tolist()\n\n# cleaned data\n##Cleaning/pre-processing the headlines data\nclean_headlines = [clean(doc).split() for doc in headlines]\n\n# Creating the term dictionary of our courpus, where every unique term is assigned an index\n##Creating the id2word dictionary\ndictionary = corpora.Dictionary(clean_headlines)\n\n# Converting list of documents (corpus) into Document Term Matrix using dictionary prepared above.\n##Creating a word corpus\ndoc_term_matrix = [dictionary.doc2bow(doc) for doc in clean_headlines]\n\n# build LDA model\n# extract topics for headlines\n# pprint topics\n##Intantiating the LDA model, and printing the 5 topics containing only the 10 most relevant words\nlda_model = LdaModel(corpus = doc_term_matrix, num_topics = 5, id2word = dictionary, iterations = 10, random_state = 2)\ntopics = lda_model.print_topics(num_topics = 5, num_words = 10)\npprint.pprint(topics)\n\n# Code ends here\n\n\n\n\n# --------------\n# Can take a long time to run\n# coherence score\n##Intantiating a coherence object, and outputting the coherence score\ncoherence_model_lda = CoherenceModel(model = lda_model, texts = clean_headlines, dictionary = dictionary, coherence = \"c_v\")\ncoherence_lda = coherence_model_lda.get_coherence()\nprint(coherence_lda)\n\n# Function to calculate coherence values\n##Initializing two empty lists, and defining a function to capture coherence values by number of topics\ncoherence_values = []\nmodel_list = []\ndef compute_coherence_values(dictionary, corpus, texts, limit, start = 2, step = 3):\n \"\"\"\n Compute c_v coherence for various number of topics\n\n Parameters:\n ----------\n dictionary : Gensim dictionary\n corpus : Gensim corpus\n texts : List of input texts\n limit : Max num of topics\n\n Returns:\n -------\n model_list : List of LDA topic models\n coherence_values : Coherence values corresponding to the LDA model with respective number of topics\n \"\"\"\n for num_topics in range(2, 50, 6):\n Lda = gensim.models.ldamodel.LdaModel\n model = Lda(doc_term_matrix, num_topics = num_topics, random_state = 2, id2word = dictionary, iterations = 10)\n model_list.append(model)\n coherencemodel = CoherenceModel(model = model, texts = texts, dictionary = dictionary, coherence = \"c_v\")\n coherence_values.append(coherencemodel.get_coherence())\n return model_list, coherence_values\n\nmodel_list, coherence_values = compute_coherence_values(dictionary = dictionary, corpus = doc_term_matrix, texts = clean_headlines, start = 2, limit = 50, step = 6)\n\n# Plotting\n##Plotting coherence values against the number of topics\nx = range(2, 50, 6)\nplt.plot(x, coherence_values)\nplt.xlabel(\"Num Topics\")\nplt.ylabel(\"Coherence score\")\nplt.show()\n\n\n","sub_path":"Topic-Modelling/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497433356","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport torch.distributions as tdist\n\n\"\"\"implementation of the Variational Recurrent Neural Network (VRNN-GMM) from https://arxiv.org/abs/1506.02216 using\nGaussian mixture distributions with fixed number of mixtures for inference, prior, and generating models.\"\"\"\n\n\nclass VRNN_GMM(nn.Module):\n def __init__(self, param, device, bias=False):\n super(VRNN_GMM, self).__init__()\n\n self.y_dim = param.y_dim\n self.u_dim = param.u_dim\n self.h_dim = param.h_dim\n self.z_dim = param.z_dim\n self.n_layers = param.n_layers\n self.n_mixtures = param.n_mixtures\n self.device = device\n\n # feature-extracting transformations (phi_y, phi_u and phi_z)\n self.phi_y = nn.Sequential(\n nn.Linear(self.y_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n self.phi_u = nn.Sequential(\n nn.Linear(self.u_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n self.phi_z = nn.Sequential(\n nn.Linear(self.z_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim))\n\n # encoder function (phi_enc) -> Inference\n self.enc = nn.Sequential(\n nn.Linear(self.h_dim + self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.enc_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim))\n self.enc_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim),\n nn.ReLU(), )\n\n # prior function (phi_prior) -> Prior\n self.prior = nn.Sequential(\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.prior_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim))\n self.prior_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.z_dim),\n nn.ReLU(), )\n\n # decoder function (phi_dec) -> Generation\n self.dec = nn.Sequential(\n nn.Linear(self.h_dim + self.h_dim, self.h_dim),\n nn.ReLU(),\n nn.Linear(self.h_dim, self.h_dim),\n nn.ReLU(), )\n self.dec_mean = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures), )\n self.dec_logvar = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures),\n nn.ReLU(), )\n self.dec_pi = nn.Sequential(\n nn.Linear(self.h_dim, self.y_dim * self.n_mixtures),\n nn.Softmax(dim=1)\n )\n\n # recurrence function (f_theta) -> Recurrence\n self.rnn = nn.GRU(self.h_dim + self.h_dim, self.h_dim, self.n_layers, bias)\n\n def forward(self, u, y):\n\n batch_size = y.size(0)\n seq_len = y.shape[-1]\n\n # allocation\n loss = 0\n # initialization\n h = torch.zeros(self.n_layers, batch_size, self.h_dim, device=self.device)\n\n # for all time steps\n for t in range(seq_len):\n # feature extraction: y_t\n phi_y_t = self.phi_y(y[:, :, t])\n # feature extraction: u_t\n phi_u_t = self.phi_u(u[:, :, t])\n\n # encoder: y_t, h_t -> z_t\n enc_t = self.enc(torch.cat([phi_y_t, h[-1]], 1))\n enc_mean_t = self.enc_mean(enc_t)\n enc_logvar_t = self.enc_logvar(enc_t)\n\n # prior: h_t -> z_t (for KLD loss)\n prior_t = self.prior(h[-1])\n prior_mean_t = self.prior_mean(prior_t)\n prior_logvar_t = self.prior_logvar(prior_t)\n\n # sampling and reparameterization: get a new z_t\n temp = tdist.Normal(enc_mean_t, enc_logvar_t.exp().sqrt())\n z_t = tdist.Normal.rsample(temp)\n # feature extraction: z_t\n phi_z_t = self.phi_z(z_t)\n\n # decoder: h_t, z_t -> y_t\n dec_t = self.dec(torch.cat([phi_z_t, h[-1]], 1))\n dec_mean_t = self.dec_mean(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_logvar_t = self.dec_logvar(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_pi_t = self.dec_pi(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n\n # recurrence: u_t+1, z_t -> h_t+1\n _, h = self.rnn(torch.cat([phi_u_t, phi_z_t], 1).unsqueeze(0), h)\n\n # computing the loss\n KLD = self.kld_gauss(enc_mean_t, enc_logvar_t, prior_mean_t, prior_logvar_t)\n loss_pred = self.loglikelihood_gmm(y[:, :, t], dec_mean_t, dec_logvar_t, dec_pi_t)\n loss += - loss_pred + KLD\n\n return loss\n\n def generate(self, u):\n # get the batch size\n batch_size = u.shape[0]\n # length of the sequence to generate\n seq_len = u.shape[-1]\n\n # allocation\n sample = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n sample_mu = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n sample_sigma = torch.zeros(batch_size, self.y_dim, seq_len, device=self.device)\n\n h = torch.zeros(self.n_layers, batch_size, self.h_dim, device=self.device)\n\n # for all time steps\n for t in range(seq_len):\n # feature extraction: u_t+1\n phi_u_t = self.phi_u(u[:, :, t])\n\n # prior: h_t -> z_t\n prior_t = self.prior(h[-1])\n prior_mean_t = self.prior_mean(prior_t)\n prior_logvar_t = self.prior_logvar(prior_t)\n\n # sampling and reparameterization: get new z_t\n temp = tdist.Normal(prior_mean_t, prior_logvar_t.exp().sqrt())\n z_t = tdist.Normal.rsample(temp)\n # feature extraction: z_t\n phi_z_t = self.phi_z(z_t)\n\n # decoder: z_t, h_t -> y_t\n dec_t = self.dec(torch.cat([phi_z_t, h[-1]], 1))\n dec_mean_t = self.dec_mean(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_logvar_t = self.dec_logvar(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n dec_pi_t = self.dec_pi(dec_t).view(batch_size, self.y_dim, self.n_mixtures)\n\n # store the samples\n sample[:, :, t], sample_mu[:, :, t], sample_sigma[:, :, t] = self._reparameterized_sample_gmm(dec_mean_t,\n dec_logvar_t,\n dec_pi_t)\n\n # recurrence: u_t+1, z_t -> h_t+1\n _, h = self.rnn(torch.cat([phi_u_t, phi_z_t], 1).unsqueeze(0), h)\n\n return sample, sample_mu, sample_sigma\n\n def _reparameterized_sample_gmm(self, mu, logvar, pi):\n\n # select the mixture indices\n alpha = torch.distributions.Categorical(pi).sample()\n\n # select the mixture indices\n idx = logvar.shape[-1]\n raveled_index = torch.arange(len(alpha.flatten()), device=self.device) * idx + alpha.flatten()\n logvar_sel = logvar.flatten()[raveled_index]\n mu_sel = mu.flatten()[raveled_index]\n\n # get correct dimensions\n logvar_sel = logvar_sel.view(logvar.shape[:-1])\n mu_sel = mu_sel.view(mu.shape[:-1])\n\n # resample\n temp = tdist.Normal(mu_sel, logvar_sel.exp().sqrt())\n sample = tdist.Normal.rsample(temp)\n\n return sample, mu_sel, logvar_sel.exp().sqrt()\n\n def loglikelihood_gmm(self, x, mu, logvar, pi):\n # init\n loglike = 0\n\n # for all data channels\n for n in range(x.shape[1]):\n # likelihood of a single mixture at evaluation point\n pred_dist = tdist.Normal(mu[:, n, :], logvar[:, n, :].exp().sqrt())\n x_mod = torch.mm(x[:, n].unsqueeze(1), torch.ones(1, self.n_mixtures, device=self.device))\n like = pred_dist.log_prob(x_mod)\n # weighting by probability of mixture and summing\n temp = (pi[:, n, :] * like)\n temp = temp.sum()\n # log-likelihood added to previous log-likelihoods\n loglike = loglike + temp\n\n return loglike\n\n @staticmethod\n def kld_gauss(mu_q, logvar_q, mu_p, logvar_p):\n # Goal: Minimize KL divergence between q_pi(z|xi) || p(z|xi)\n # This is equivalent to maximizing the ELBO: - D_KL(q_phi(z|xi) || p(z)) + Reconstruction term\n # This is equivalent to minimizing D_KL(q_phi(z|xi) || p(z))\n term1 = logvar_p - logvar_q - 1\n term2 = (torch.exp(logvar_q) + (mu_q - mu_p) ** 2) / torch.exp(logvar_p)\n kld = 0.5 * torch.sum(term1 + term2)\n\n return kld\n","sub_path":"models/model_vrnn_gmm.py","file_name":"model_vrnn_gmm.py","file_ext":"py","file_size_in_byte":8744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536690586","text":"#!/usr/bin/python3\n\"\"\"\n Given a list of non-negative integers representing walls of width 1,\n calculate how much water will be retained after it rains.\n\"\"\"\n\n\ndef retained_water(r, d):\n \"\"\"\n retained_watter - calculate how much water will be retained\n @r: list of retainers\n @d: 0 from left to righ. 1 from right to left\n \"\"\"\n minV = -1\n num_values_between = 0\n sum_values_between = 0\n ret_water = 0\n i = 0\n while i < len(r):\n if r[i] > 0 and minV < 0:\n minV = r[i]\n elif minV > 0 and r[i] < minV:\n num_values_between += 1\n sum_values_between += r[i]\n elif minV > 0 and ((not d and r[i] >= minV) or (d and r[i] > minV)):\n if num_values_between > 0:\n ret_water += (num_values_between * minV)\n ret_water -= sum_values_between\n num_values_between = 0\n sum_values_between = 0\n minV = r[i]\n i += 1\n return ret_water\n\n\ndef rain(walls):\n \"\"\"\n rain - calculate how much water will be retained after it rains\n @walls: list of retainers\n \"\"\"\n if not walls:\n return 0\n return retained_water(walls, 0) + retained_water(walls[::-1], 1)\n","sub_path":"0x10-rain/0-rain.py","file_name":"0-rain.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600063485","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\n\nmu_vec1 = np.array([0,0,0])\ncov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20).T\n\nmu_vec2 = np.array([1,1,1])\ncov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])\nclass2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20).T\n\nfig = plt.figure(figsize=(8,8))\nax = fig.add_subplot(111, projection='3d')\nplt.rcParams['legend.fontsize'] = 10\nax.plot(class1_sample[0,:], class1_sample[1,:], class1_sample[2,:], 'o', markersize=8, color='blue', alpha=0.5, label='class1')\nax.plot(class2_sample[0,:], class2_sample[1,:], class2_sample[2,:], '^', markersize=8, alpha=0.5, color='red', label='class2')\n\nplt.title('Samples for class 1 and class 2')\nax.legend(loc='upper right')\n\nplt.show()\n\nall_samples = np.concatenate((class1_sample, class2_sample), axis=1)\nmean_x=np.mean(all_samples[0,:])\nmean_y=np.mean(all_samples[1,:])\nmean_z=np.mean(all_samples[2,:])\nmean_vector = np.array([[mean_x],[mean_y],[mean_z]])\nscatter_matrix = np.zeros((3,3))\nfor i in range(all_samples.shape[1]):\n scatter_matrix += (all_samples[:,i].reshape(3,1) - mean_vector).dot((all_samples[:,i].reshape(3,1) - mean_vector).T)\n\ncov_mat = np.cov([all_samples[0,:],all_samples[1,:],all_samples[2,:]])\neig_val_sc, eig_vec_sc = np.linalg.eig(scatter_matrix)\neig_val_cov, eig_vec_cov = np.linalg.eig(cov_mat)\n\norder=np.argsort(-eig_val_cov)\nprint(order)\neigh=eig_vec_cov[:,order[0]].reshape([1,3]).T\nmatrix_w_2d = np.hstack((eig_vec_cov[:,order[0]].reshape(3,1), eig_vec_cov[:,order[1]].reshape(3,1)))\ntransformed = np.dot(matrix_w_2d.T,all_samples)\n\nmatrix_w_1d= eig_vec_cov[:,order[0]].reshape(3,1)\ntransformed_1d=np.dot(matrix_w_1d.T,all_samples)\n\nprint(eig_val_cov,np.argsort(-eig_val_cov))\nprint(eig_vec_cov)\nprint(eigh)\nprint(matrix_w_2d)\nprint(transformed.shape)\nprint(matrix_w_1d)\nprint(transformed_1d.shape)\n\n\nplt.plot(transformed[0,0:20], transformed[1,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(transformed[0,20:40], transformed[1,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlim([-4,4])\nplt.ylim([-4,4])\nplt.xlabel('x_values')\nplt.ylabel('y_values')\nplt.legend()\nplt.title('Transformed samples with class labels')\n\nplt.show()\n\nplt.plot(transformed_1d[0,0:20], 'o', markersize=7, color='blue', alpha=0.5, label='class1')\nplt.plot(transformed_1d[0,20:40], '^', markersize=7, color='red', alpha=0.5, label='class2')\n\nplt.xlim([-4,4])\nplt.xlabel('x_values')\nplt.legend()\nplt.title('Transformed samples with class labels')\nplt.show()","sub_path":"PCA_test.py","file_name":"PCA_test.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"266770575","text":"import sys\nimport coordinate\nimport mission\nimport path\nimport file_parser\n\npath_info = {'turn_radius' : 5, \\\n 'path_cushine' : 20, \\\n 'boundary_cushine' : 20, \\\n 'pt_distance' : 10}\n\ndef main():\n # Read the File\n filename = 'data.csv'\n (op_area, search_area, waypoints_list) = file_parser.read_file(filename)\n\n m1 = mission.Mission()\n f1 = mission.Fence()\n\n # Given a takeoff point\n takeoff_pt = coordinate.GeoCoord(38.145495, -76.428166, 200)\n item1 = mission.MissionItem(takeoff_pt, 22)\n m1.add_mission_item(item1)\n\n # Generate path to go over waypts\n waypt_path = path.generate_waypt_path(path_info, takeoff_pt, waypoints_list, op_area)\n for pt in waypt_path:\n item1 = mission.MissionItem(pt, 16)\n m1.add_mission_item(item1)\n\n # Generate search path within search_area\n search_area_path = []\n #search_area_path = path.generate_search_path(path_info, waypt_path[-1], search_area, op_area, 30)\n search_area_path = path.generate_search_path_spiral(path_info, waypt_path[-1], search_area, op_area, 30)\n for pt in search_area_path:\n item1 = mission.MissionItem(pt, 16)\n m1.add_mission_item(item1)\n\n # Add Landing point, assume to be takeoff point as well\n item1 = mission.MissionItem(takeoff_pt, 21)\n m1.add_mission_item(item1)\n\n # Generate Fence from the operational area\n for pt in op_area:\n f1.add_boundary_point(pt)\n\n # Output the mission into file\n f = open('output.mission', 'w')\n f.write(str(m1))\n f.close()\n\n # Output the fence into file\n f = open('output.fence', 'w')\n f.write(str(f1))\n f.close()\n\n\n\n\nmain()\n","sub_path":"flight_path_python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"511698315","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/base/tauruscontroller.py\n# Compiled at: 2019-08-19 15:09:29\n\"\"\"This module provides the set of base class taurus controllers.\"\"\"\nfrom builtins import str\nfrom builtins import object\nimport weakref\nfrom taurus.external.qt import Qt\nfrom taurus.core.taurusbasetypes import DataFormat, TaurusEventType\nfrom taurus.qt.qtgui.util import QT_ATTRIBUTE_QUALITY_PALETTE\nfrom taurus.qt.qtgui.util import QT_DEVICE_STATE_PALETTE\n__all__ = [\n 'TaurusBaseController', 'TaurusAttributeControllerHelper',\n 'TaurusScalarAttributeControllerHelper',\n 'TaurusConfigurationControllerHelper',\n 'updateLabelBackground']\n__docformat__ = 'restructuredtext'\n\nclass TaurusBaseController(object):\n \"\"\"Base class for all taurus controllers\"\"\"\n\n def __init__(self, widget, updateAsPalette=True):\n self._widget = weakref.ref(widget)\n self._updateAsPalette = updateAsPalette\n self._stateObj = None\n self._last_value = None\n self._last_config_value = None\n self._last_error_value = None\n self._setStyle()\n return\n\n def _setStyle(self):\n pass\n\n def usePalette(self):\n return self._updateAsPalette\n\n def widget(self):\n return self._widget()\n\n def modelObj(self):\n return self.widget().getModelObj()\n\n attrObj = configObj = deviceObj = modelObj\n\n def valueObj(self):\n value = self._last_value\n if value is None:\n modelObj = self.modelObj()\n if modelObj is None:\n return\n value = modelObj.getValueObj()\n return value\n\n def value(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'value', None)\n\n def w_value(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'w_value', None)\n\n def quality(self):\n valueObj = self.valueObj()\n return getattr(valueObj, 'quality', None)\n\n def state(self):\n return self._stateObj.state\n\n def getDisplayValue(self, write=False):\n return self.widget().getDisplayValue()\n\n def handleEvent(self, evt_src, evt_type, evt_value):\n if evt_src == self.modelObj():\n if evt_type in (TaurusEventType.Change, TaurusEventType.Periodic):\n if self._last_value is None:\n self.widget().resetFormat()\n self._last_value = evt_value\n elif evt_type == TaurusEventType.Config:\n self._last_config_value = evt_value\n self.widget().resetFormat()\n else:\n self._last_error_value = evt_value\n try:\n self._last_value = self.modelObj().getValueObj()\n except:\n self._last_value = None\n\n self.update()\n return\n\n def eventReceived(self, evt_src, evt_type, evt_value):\n w = self.widget()\n if w is not None:\n w.eventReceived(evt_src, evt_type, evt_value)\n return\n\n def update(self):\n widget = self.widget()\n self._updateConnections(widget)\n self._updateForeground(widget)\n self._updateBackground(widget)\n self._updateToolTip(widget)\n\n def _needsStateConnection(self):\n return False\n\n def _updateConnections(self, widget):\n stateObj, newStateObj = self._stateObj, None\n if self._needsStateConnection():\n newStateObj = self.deviceObj()\n if stateObj != newStateObj:\n if stateObj is not None:\n stateObj.removeListener(self)\n if newStateObj is not None:\n newStateObj.addListener(self)\n elif stateObj is not None:\n stateObj.removeListener(self)\n self._stateObj = newStateObj\n return\n\n def _updateForeground(self, widget):\n pass\n\n def _updateBackground(self, widget):\n pass\n\n def _updateToolTip(self, widget):\n if widget.getAutoTooltip():\n widget.setToolTip(widget.getFormatedToolTip())\n\n\nclass TaurusAttributeControllerHelper(object):\n\n def configObj(self):\n return self.attrObj()\n\n def deviceObj(self):\n attrObj = self.attrObj()\n if attrObj is None:\n return\n else:\n return attrObj.getParentObj()\n\n\nclass TaurusScalarAttributeControllerHelper(TaurusAttributeControllerHelper):\n\n def getDisplayValue(self, write=False):\n valueObj = self.valueObj()\n widget = self.widget()\n if valueObj is None or valueObj.rvalue is None:\n return widget.getDisplayValue()\n else:\n format = self.attrObj().data_format\n if format == DataFormat._0D:\n return self._getDisplayValue(widget, valueObj, None, write)\n idx = widget.getModelIndexValue()\n return self._getDisplayValue(widget, valueObj, idx, write)\n\n def _getDisplayValue(self, widget, valueObj, idx, write):\n try:\n if write:\n value = valueObj.wvalue\n else:\n value = valueObj.rvalue\n if idx is not None and len(idx):\n for i in idx:\n value = value[i]\n\n return widget.displayValue(value)\n except Exception as e:\n return widget.getNoneValue()\n\n return\n\n def displayValue(self, value):\n if value is None:\n return\n else:\n ret = None\n try:\n if self.isScalar():\n format = self.getFormat()\n if self.isNumeric() and format is not None:\n format = self.getFormat()\n ret = self.getFormat() % value\n else:\n ret = str(value)\n elif self.isSpectrum():\n ret = str(value)\n else:\n ret = str(value)\n except:\n raise\n ret = str(value)\n\n return ret\n\n\nclass TaurusConfigurationControllerHelper(object):\n\n def __init__(self):\n self._configParam = None\n return\n\n def attrObj(self):\n return self.configObj()\n\n def deviceObj(self):\n attrObj = self.attrObj()\n if attrObj is None:\n return\n else:\n return attrObj.getParentObj()\n\n @property\n def configParam(self):\n if self._configParam is None:\n self._configParam = self.widget().modelFragmentName or ''\n return self._configParam\n\n def getDisplayValue(self, write=False):\n widget = self.widget()\n model = self.configObj()\n if model is None:\n return widget.getNoneValue()\n else:\n param = self.configParam\n try:\n val = widget.getModelFragmentObj()\n try:\n no_val = getattr(model, 'no_' + param)\n if val.lower() == no_val.lower():\n val = widget.getNoneValue()\n except:\n pass\n\n except AttributeError:\n if param:\n val = str(param)\n attr = self.attrObj()\n if attr is not None:\n val = val.replace('