content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals import unittest2 as unittest import os import json import random import numpy as np import csv import scipy.constants as const from pymatgen.analysis.diffusion_analyzer import DiffusionAnalyzer,\ get_conversion_factor, fit_arrhenius from pymatgen.core.structure import Structure from pymatgen.util.testing import PymatgenTest from monty.tempfile import ScratchDir """ TODO: Change the module doc. """ __author__ = "shyuepingong" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Beta" __date__ = "5/2/13" test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files') if __name__ == '__main__': unittest.main()
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 2, 15069, 357, 66, 8, 350, 4948, 265, 5235, 7712, 4816, 13, 198, 2, 4307, 6169, 739, 262, 2846, 286, 262, 17168, 13789, 13, 198, 198, 6738, 11593, 37443, 834, 1330, 7297, 11, 28000, 1098, 62, ...
2.623145
337
import sympy from .utils import known_equal_pair, contains_incorrect_symbols from .utils import EqualityType from .parsing import logic_parser, UnsafeInputException __all__ = ["check"] KNOWN_PAIRS = dict() def parse_expression(expression_str, *, local_dict=None): """Take a string containing a mathematical expression and return a sympy expression. Wrap the parsing class function parse_expr(...) and catch any exceptions that occur. - 'local_dict' can be a dictionary of (name, sympy.Symbol(...)) pairs, where the string 'name' will not be split up and will be turned into the symbol specified. It may be None. """ try: return logic_parser.parse_expr(expression_str, local_dict=local_dict) except logic_parser.ParsingException: print("Incorrectly formatted expression.") print("Fail: '{}'.".format(expression_str)) return None def exact_match(test_expr, target_expr): """Test if the entered expression exactly matches the known expression. This performs as little simplification of the boolean expression as possible, allowing only the commutativity or AND and OR. Returns True if the sympy expressions have the same internal structure, and False if not. - 'test_expr' should be the untrusted sympy expression to check. - 'target_expr' should be the trusted sympy expression to match against. """ print("[EXACT TEST]") if test_expr == target_expr: print("Exact Match (with '==')") return True elif sympy.srepr(test_expr) == sympy.srepr(target_expr): # This is a (perfectly acceptable) hack for ordering the atoms of each # term, but a more explicit method may be preferable in the future. print("Exact Match (with 'srepr')") return True else: return False def symbolic_equality(test_expr, target_expr): """Test if two expressions are symbolically equivalent. Use the sympy 'simplify_logic' function to simplify the two boolean expressions as much as possible. Two equilvalent expressions MUST simplify to the same thing, and then they can be tested for equivalence again. Returns True if sympy can determine that the two expressions are equal, and returns False if they are not equal. - 'test_expr' should be the untrusted sympy expression to check. - 'target_expr' should be the trusted sympy expression to match against. """ print("[SYMBOLIC TEST]") try: simplified_target = sympy.simplify_logic(target_expr) simplified_test = sympy.simplify_logic(test_expr) if simplified_target == simplified_test or sympy.srepr(simplified_target) == sympy.srepr(simplified_test): print("Symbolic match.") print("INFO: Adding known pair ({0}, {1})".format(target_expr, test_expr)) KNOWN_PAIRS[(target_expr, test_expr)] = EqualityType.SYMBOLIC return True else: return False except NotImplementedError as e: print("{0}: {1} - Can't check symbolic equality!".format(type(e).__name__, str(e).capitalize())) return False def expr_equality(test_expr, target_expr): """Given two sympy expressions: test for exact, symbolic and numeric equality. Check two sympy expressions for equality, throwing a TypeError if either of the provided sympy objects is not an expression. - 'test_expr' should be the untrusted sympy expression to check. - 'target_expr' should be the trusted sympy expression to match against. """ equality_type = EqualityType.EXACT equal = exact_match(test_expr, target_expr) if not equal: # Then try checking for symbolic equality: equality_type = EqualityType.SYMBOLIC equal = symbolic_equality(test_expr, target_expr) return equal, equality_type def general_equality(test_expr, target_expr): """Given two general sympy objects: test for exact, symbolic and numeric equality. - 'test_expr' should be the untrusted sympy object to check. - 'target_expr' should be the trusted sympy object to match against. """ equal, equality_type = known_equal_pair(KNOWN_PAIRS, test_expr, target_expr) # If this is a known pair: return immediately: if equal: return equal, equality_type else: print("[[EXPRESSION CHECK]]") return expr_equality(test_expr, target_expr) def check(test_str, target_str, *, symbols=None, check_symbols=True, description=None, _quiet=False): """The main checking function, calls each of the equality checking functions as required. Returns a dict describing the equality; with important keys being 'equal', and 'equality_type'. The key 'error' is added if something went wrong, and this should always be checked for first. - 'test_str' should be the untrusted string for sympy to parse. - 'target_str' should be the trusted string to parse and match against. - 'symbols' should be a string list or comma separated string of symbols not to split during parsing. - 'check_symbols' indicates whether to verfiy the symbols used in each expression are exactly the same or not; setting this to False will allow symbols which cancel out to be included (probably don't want this in questions). - 'description' is an optional description to print before the checker's output to stdout which can be used to improve logging. - '_quiet' is an internal argument used to suppress some output when this function is called from plus_minus_checker(). """ # Suppress this output if necessary: if not _quiet: print("=" * 50) # For logging purposes, if we have a description: print it! if description is not None: print(description) print("=" * 50) print("[LOGIC]") # If nothing to parse, fail. On server, this will be caught in check_endpoint() if (target_str == "") or (test_str == ""): print("ERROR: No input provided!") if not _quiet: print("=" * 50) return dict(error="Empty string as argument.") # Cleanup the strings before anything is done to them: error_is_test = False try: target_str = logic_parser.cleanup_string(target_str, reject_unsafe_input=True) error_is_test = True test_str = logic_parser.cleanup_string(test_str, reject_unsafe_input=True) except UnsafeInputException: print("ERROR: Input contained non-whitelisted characters!") result = dict(error="Bad input provided!") if error_is_test: print("Test string: '{}'".format(test_str)) result["syntax_error"] = str(True).lower() if not _quiet: print("=" * 50) return result print("Target string: '{}'".format(target_str)) print("Test string: '{}'".format(test_str)) print("[[PARSE EXPRESSIONS]]") # Parse the trusted target expression: target_expr = parse_expression(target_str) # Parse the untrusted test expression: test_expr = parse_expression(test_str) result = dict(target=target_str, test=test_str) if target_expr is None: print("ERROR: TRUSTED EXPRESSION CANNOT BE PARSED!") if not _quiet: print("=" * 50) result["error"] = "Parsing TARGET Expression Failed!" result["code"] = 400 # This is fatal! return result if test_expr is None: print("Incorrectly formatted ToCheck expression.") if not _quiet: print("=" * 50) result["error"] = "Parsing Test Expression Failed!" result["syntax_error"] = str(True).lower() return result result["parsed_target"] = str(target_expr) result["parsed_test"] = str(test_expr) # Now check for symbol match and equality: try: print("Parsed Target: {0}\nParsed ToCheck: {1}".format(target_expr, test_expr)) if check_symbols: # Do we have same set of symbols in each? incorrect_symbols = contains_incorrect_symbols(test_expr, target_expr) if incorrect_symbols is not None: print("[[RESULT]]\nEquality: False") if not _quiet: print("=" * 50) result["equal"] = str(False).lower() result["equality_type"] = EqualityType.SYMBOLIC.value result["incorrect_symbols"] = incorrect_symbols return result # Then check for equality proper: equal, equality_type = general_equality(test_expr, target_expr) except (SyntaxError, TypeError, AttributeError) as e: print("Error when comparing expressions: '{}'.".format(e)) if not _quiet: print("=" * 50) result["error"] = "Comparison of expressions failed: '{}'".format(e) return result print("[[RESULT]]") if equal and (equality_type is not EqualityType.EXACT) and ((target_expr, test_expr) not in KNOWN_PAIRS): print("INFO: Adding known pair ({0}, {1})".format(target_expr, test_expr)) KNOWN_PAIRS[(target_expr, test_expr)] = equality_type print("Equality: {}".format(equal)) if not _quiet: print("=" * 50) result["equal"] = str(equal).lower() result["equality_type"] = equality_type.value return result
[ 11748, 10558, 88, 198, 198, 6738, 764, 26791, 1330, 1900, 62, 40496, 62, 24874, 11, 4909, 62, 1939, 47315, 62, 1837, 2022, 10220, 198, 6738, 764, 26791, 1330, 31428, 6030, 198, 6738, 764, 79, 945, 278, 1330, 9156, 62, 48610, 11, 791, ...
2.665639
3,568
from math import e, log10, pi while True: try: n = int(input()) except EOFError: break if n == 0: print(1) else: print(int(n * log10(n / e) + log10(2 * pi * n) / 2) + 1)
[ 6738, 10688, 1330, 304, 11, 2604, 940, 11, 31028, 198, 198, 4514, 6407, 25, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 220, 220, 220, 299, 796, 493, 7, 15414, 28955, 198, 220, 220, 220, 2845, 412, 19238, 12331, 25, 198...
1.85
120
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import sys import argparse import readline import random import traceback try: import builtins raw_input = getattr(builtins, 'input') except ImportError: pass from game24 import calc, game MSG_MENU_MAIN = '''1. Play (p) 2. Check answer (c) 3. Quit (q)''' MSG_MENU_PLAY = '''1. Definitely no solutions (n) 2. Give me a hint (h) 3. I gave up, show me the answer (s) 4. Back to the main menu (b) 5. Quit the game (q)''' MSG_MENU_SET_END = '''1. One more set (n) 2. Back to the main menu (b) 3. Quit the game (q)''' MSG_MENU_PLAY_RIGHT = '''1. Try other solutions (t) 2. Next hand (n) 3. Show me the answers (s) 4. Quit the game (q)''' MSG_SELECT = 'Your choice: ' MSG_INVALID_INPUT = 'Invalid input!' MSG_MENU_HAND_END = '''1. One more hand (n) 2. Quit this set, back to the main menu (b) 3. Quit the game (q)''' MSG_SELECT = 'Your choice: ' MSG_INVALID_INPUT = 'Invalid input!' MSG_INVALID_INTEGER = 'Invalid integer: %s' MSG_PLAY_NEW_SET = 'Set %d' MSG_PLAY_NEW_HAND = 'Hand %d: %s' MSG_PLAY_INPUT_EXPR = 'Input your solution or one of the above choices: ' MSG_PLAY_RIGHT = 'Good Job!' MSG_PLAY_FIND_BUG = '''Great Job! You not only solved the problem, but also found a bug! Please report to me with the cards and your solution if you don't mind.''' MSG_PLAY_WRONG = "Sorry! It's not correct!" MSG_PLAY_NO_ANSWER = 'Seems no solutions' MSG_PLAY_NO_CARDS = 'Set end, your result' MSG_INPUT_NUMBERS = 'Please input %d integers: ' INPUT_EOF = '\x00' if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 3601, 62, 8818, 11, 7297, 198, 198, 11748, 25064, 198, 11748, 1822, ...
2.5
650
import json import os import boto3 from faker import Faker # DynamoDB object dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(f"TestUsersTable-{os.environ['STAGE']}")
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 275, 2069, 18, 198, 6738, 277, 3110, 1330, 376, 3110, 628, 198, 2, 41542, 11012, 2134, 198, 67, 4989, 375, 65, 796, 275, 2069, 18, 13, 31092, 10786, 67, 4989, 375, 65, 11537, 198, 11487, ...
2.705882
68
# Using Log Files # Settings/Options/System/Environment (use custom variables) # QGIS_LOG_FILE=/qgis_data/log.txt # Restart QGIS # Message to log file: QgsLogger.logMessageToFile("This is a message to a log file.") # Message to QGIS Log Window ( yellow triangle icon in the lower right) QgsMessageLog.logMessage("This is a message from the Python Console", "Python Console", QgsMessageLog.INFO)
[ 2, 8554, 5972, 13283, 198, 198, 2, 16163, 14, 29046, 14, 11964, 14, 31441, 357, 1904, 2183, 9633, 8, 220, 198, 2, 1195, 38, 1797, 62, 25294, 62, 25664, 33223, 80, 70, 271, 62, 7890, 14, 6404, 13, 14116, 198, 2, 8324, 433, 1195, ...
3.262295
122
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
[ 2, 220, 220, 15069, 357, 66, 8, 12131, 350, 37382, 47, 37382, 46665, 13, 1439, 6923, 12224, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, ...
3.773006
163
from logging import getLogger, StreamHandler, DEBUG, Formatter from typing import Dict, Union import re import json import requests import MeCab from neologdn import normalize # ロガー設定 logger = getLogger(__name__) handler = StreamHandler() handler.setLevel(DEBUG) logger.setLevel(DEBUG) logger.addHandler(handler) logger.propagate = False handler.setFormatter(Formatter('[openBD] %(asctime)s - %(message)s'))
[ 6738, 18931, 1330, 651, 11187, 1362, 11, 13860, 25060, 11, 16959, 11, 5178, 1436, 198, 6738, 19720, 1330, 360, 713, 11, 4479, 198, 11748, 302, 198, 11748, 33918, 198, 11748, 7007, 198, 11748, 2185, 34, 397, 198, 6738, 497, 928, 32656, ...
2.971014
138
import paho.mqtt.client as mqtt import ev3dev.ev3 as ev3 import ctypes import numpy as np import sys import cv2 from Sensors.mpu6050.mpu6050 import MPU6050 import smbus from Sensors.odometry import Odometry import sys, serial from serial.tools import list_ports #Create camera sensor object camera = OnBoardCamera()
[ 11748, 279, 17108, 13, 76, 80, 926, 13, 16366, 355, 285, 80, 926, 198, 11748, 819, 18, 7959, 13, 1990, 18, 355, 819, 18, 198, 11748, 269, 19199, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 25064, 198, 11748, 269, 85, 17, 198, ...
3.057143
105
import numpy as np import openmdao.api as om if __name__ == '__main__': check_integrated_surface_force_partials()
[ 11748, 299, 32152, 355, 45941, 198, 11748, 1280, 9132, 5488, 13, 15042, 355, 39030, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 2198, 62, 18908, 4111, 62, 42029, 62, 3174, 62, 3911, 8231, 34...
2.767442
43
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint: disable=line-too-long,too-many-arguments,too-many-locals import json import os import click from platformio import fs from platformio.package.commands.install import install_project_dependencies from platformio.package.manager.platform import PlatformPackageManager from platformio.platform.exception import UnknownBoard from platformio.project.config import ProjectConfig from platformio.project.generator import ProjectGenerator from platformio.project.helpers import is_platformio_project @click.command("init", short_help="Initialize a project or update existing") @click.option( "--project-dir", "-d", default=os.getcwd, type=click.Path( exists=True, file_okay=False, dir_okay=True, writable=True, resolve_path=True ), ) @click.option("-b", "--board", multiple=True, metavar="ID", callback=validate_boards) @click.option("--ide", type=click.Choice(ProjectGenerator.get_supported_ides())) @click.option("-e", "--environment", help="Update existing environment") @click.option("-O", "--project-option", multiple=True) @click.option("--env-prefix", default="") @click.option("--no-install-dependencies", is_flag=True) @click.option("-s", "--silent", is_flag=True)
[ 2, 15069, 357, 66, 8, 1946, 12, 25579, 19193, 9399, 1279, 32057, 31, 24254, 952, 13, 2398, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, ...
3.317029
552
# -*- coding: utf-8 -*- __author__ = 'Kazuyuki TAKASE' __copyright__ = 'PLEN Project Company Inc, and all authors.' __license__ = 'The MIT License (http://opensource.org/licenses/mit-license.php)' # 外部プログラムの読み込み # ============================================================================= from time import sleep from cv2 import VideoCapture, imwrite from wiringpi import * # 定数定義・初期化処理 # ============================================================================= CAMERA_INDEX = 0 MOTION_PIN = 26 camera = VideoCapture(CAMERA_INDEX) wiringPiSetupGpio() # メインループ # ============================================================================= while True: # これ以降を自分で作成 pass
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 834, 9800, 834, 220, 220, 220, 796, 705, 42, 1031, 4669, 11308, 309, 10206, 11159, 6, 198, 834, 22163, 4766, 834, 796, 705, 6489, 1677, 4935, 5834, 3457, 11, 290,...
2.896694
242
#!/bin/python3 # if used ubuntu 20.10 or later, interpreter set as #!/bin/python and use pip instead of pip3 # =================================================================== # # platfrom check # dateutil check and import try: from dateutil.relativedelta import relativedelta except: import os,sys,subprocess if os.name=='nt': subprocess.check_call([sys.executable, "-m", "pip", "install", "dateutil"]) elif os.name=='posix': subprocess.check_call([sys.executable, "-m", "pip3", "install", "dateutil"]) else: raise "Unknow platform, please install 'dateutil' by yourself." from dateutil.relativedelta import relativedelta # =================================================================== # # platfrom check # numpy check and import try: import numpy as np except: import os,sys,subprocess if os.name=='nt': subprocess.check_call([sys.executable, "-m", "pip", "install", "numpy"]) elif os.name=='posix': subprocess.check_call([sys.executable, "-m", "pip3", "install", "numpy"]) else: raise "Unknow platform, please install 'numpy' by yourself." import numpy as np # =================================================================== # import datetime from typing import Union class Time(object): ''' storageForward: True -> storage value in starttime <br> storageForward: False -> storage value in endtime ''' @staticmethod @staticmethod def _set_header(data,header=None): ''' only used to format output data ''' # ----------------------------------------------------------- # # here i'm not sure what data type i need to use. # thus, if data=np.array(obj(dict)), then we need # to use data.item() to get the data try: data=data.item() except: pass # ----------------------------------------------------------- # if header!=None: dummy={} for i,head in enumerate(header): if isinstance(data,dict): for key in data.keys(): if i==0: dummy[key]={} dummy[key][head]=data[key][:,i] else: dummy[head]=data[:,i] return dummy return data @staticmethod def _fixTime(time,data,timeStep:dict,zeroPara:dict,storageForward:bool,outputPara_list:list, starttime:datetime.datetime=None,endtime:datetime.datetime=None): # def _fixTime(time,data,timeStep:dict,ratio:int,zeroPara:dict,storageForward:bool,starttime:datetime.datetime=None,endtime:datetime.datetime=None): ''' zeroPara: set start datetime para season enum: 1: spring 2: summer 3: autumn 4: winter ''' minTime = np.nanmin(time) if starttime==None else starttime maxTime = np.nanmax(time) if endtime==None else endtime # get data_value if isinstance(data,dict): if 'mean' in data.keys(): data=data['mean'] if 'season' in timeStep.keys(): dt = relativedelta(months=3) if not storageForward: time+=dt; time+=datetime.timedelta(microseconds=-1) maxTime+=dt if zeroPara!=None: minTime=minTime.replace(**zeroPara) dummy={} for para in outputPara_list: if para=='quartile': dummy['lower']=[] dummy['median']=[] dummy['upper']=[] else: dummy[para]=[] tummy = [] count = [] # deal with perfix date before a new start i = Time._get_season(minTime.month) year = minTime.year if minTime.month!=12 else minTime.year+1 mask=np.where(time<datetime.datetime(year,3*i,1))[0] t,d,c = Time._nofixTime(time[mask],data[mask],parameter='season',outputPara_list=outputPara_list) tummy+=list(t); count+=list(c) for key in dummy.keys(): dummy[key]+=list(d[key]) minTime=datetime.datetime(year,3*i,1) while minTime<=maxTime: if minTime>max(time): break mask=np.where((time>=minTime) & (time<minTime+dt))[0] t,d,c = Time._nofixTime(time[mask],data[mask],parameter='season',outputPara_list=outputPara_list) tummy+=list(t); count+=list(c) for key in dummy.keys(): dummy[key]+=list(d[key]) minTime+=dt else: dt = relativedelta(**timeStep) if not storageForward: time+=dt; time+=datetime.timedelta(microseconds=-1) maxTime+=dt if zeroPara!=None: minTime=minTime.replace(**zeroPara) # if ratio==None: ratio=0 dummy = {} for para in outputPara_list: if para=='quartile': dummy['lower']=[] dummy['median']=[] dummy['upper']=[] else: dummy[para]=[] tummy = [] count = [] while minTime<=maxTime: mask = np.where((time>=minTime) & (time<minTime+dt))[0] if mask.size==0: minTime+=dt; continue tummy.append(minTime) count.append(np.sum(np.isfinite(data[mask]))) if 'mean' in outputPara_list: dummy['mean'].append(np.nanmean(data[mask],axis=0)) if 'std' in outputPara_list: dummy['std'].append(np.nanstd(data[mask],axis=0)) if 'max' in outputPara_list: dummy['max'].append(np.nanmax(data[mask],axis=0)) if 'min' in outputPara_list: dummy['min'].append(np.nanmin(data[mask],axis=0)) if 'maxTime' in outputPara_list: dummy['maxTime'].append(time[mask][np.argmax(data[mask],axis=0)]) if 'maxTime' in outputPara_list: dummy['minTime'].append(time[mask][np.argmin(data[mask],axis=0)]) if 'quartile' in outputPara_list: dummy['lower'].append(np.nanpercentile(data[mask],25,axis=0)) if ('quartile' in outputPara_list) | ('median' in outputPara_list): dummy['median'].append(np.nanpercentile(data[mask],50,axis=0)) if 'quartile' in outputPara_list: dummy['upper'].append(np.nanpercentile(data[mask],75,axis=0)) # dummy.append(np.nanmean(data[mask],axis=0) if count[-1]>=ratio else np.array([np.nan]*len(data[0]))) minTime+=dt dummy = Time._set_ndarray(dummy) return tummy,dummy,count @staticmethod def _nofixTime(time,data,parameter:str,outputPara_list:list): # def _nofixTime(time,data,parameter:str,ratio:int): ''' parameter: set the datetime parameter (second, minute ...etc) will be used to calculate season enum: 1: winter 2: spring 3: summer 4: autumn ''' season_dict = { 1: 'Winter', 2: 'Spring', 3: 'Summer', 4: 'Autumn', } if parameter.lower()=='season': time_para_list = [Time._get_season(val.month) for val in time] else: time_para_list = [eval(f"val.{parameter}") for val in time] time_para_list = np.array(time_para_list) if time_para_list.size==0: return np.array(np.nan),np.array(np.nan),np.array(np.nan) minTime = np.nanmin(time_para_list) maxTime = np.nanmax(time_para_list) # if ratio==None: ratio=0 # get data_value if isinstance(data,dict): if 'mean' in data.keys(): data=data['mean'] dummy = {} for para in outputPara_list: if para=='quartile': dummy['lower']=[] dummy['median']=[] dummy['upper']=[] else: dummy[para]=[] tummy = [] count = [] for i in range(minTime,maxTime+1): mask = np.where(time_para_list==i)[0] tummy.append(i if parameter.lower()!='season' else [time[mask[0]].year,season_dict[i]]) count.append(np.sum(np.isfinite(data[mask]))) if 'mean' in outputPara_list: dummy['mean'].append(np.nanmean(data[mask],axis=0)) if 'std' in outputPara_list: dummy['std'].append(np.nanstd(data[mask],axis=0)) if 'max' in outputPara_list: dummy['max'].append(np.nanmax(data[mask],axis=0)) if 'min' in outputPara_list: dummy['min'].append(np.nanmin(data[mask],axis=0)) if 'maxTime' in outputPara_list: dummy['maxTime'].append(time[mask][np.argmax(data[mask],axis=0)]) if 'maxTime' in outputPara_list: dummy['minTime'].append(time[mask][np.argmin(data[mask],axis=0)]) if 'quartile' in outputPara_list: dummy['lower'].append(np.nanpercentile(data[mask],25,axis=0)) if ('quartile' in outputPara_list) | ('median' in outputPara_list): dummy['median'].append(np.nanpercentile(data[mask],50,axis=0)) if 'quartile' in outputPara_list: dummy['upper'].append(np.nanpercentile(data[mask],75,axis=0)) # dummy.append(np.nanmean(data[mask],axis=0) if count[-1]>=ratio else np.array([np.nan]*len(data[0]))) dummy = Time._set_ndarray(dummy) return tummy,dummy,count @staticmethod def _get_season(month): ''' enum: 1: winter 2: spring 3: summer 4: autumn ''' return (month%12+3)//3 @staticmethod def set_config(self,init:bool=False,**kwargs) -> None: ''' config['storageForward']: save the value at the start time or not<br> config['outputPara_list]: select output parameter [mean,std,max,min] Arguments: init: Is the initialize status? Default is False If set True, will using the init state. **kwargs: Optional, this work only init set false. config: { asDict: bool, storage: bool, fixTime: bool, zeroStart: bool, selfUpdate: bool, outputPara_list: list = [ mean, std, max, min, maxTime, minTime, quartile, median ] } ''' if init==True: self.config = dict( asDict=False, storageForward=True, fixTime=True, zeroStart=True, selfUpdate=True, outputPara_list=['mean','std','mean'] # ['mean','std','max','min','maxTime','minTime','quartile','median'], ) else: for key in kwargs.keys(): self.config[key] = kwargs[key] def input(self,time: Union[list, np.ndarray],data: Union[list, np.ndarray],dtype:object =float, ratio: Union[int, float]=None,header: list=None,starttime:datetime.datetime=None,endtime:datetime.datetime=None) -> str: ''' time <datetime> : input timelist of data <br> data <numerical>: input data array Arguments: time: list of time series data: list of data set depend on time series dtype: convert type of data elements ratio: require of the data numbers(int) or ratio(float) header: export tag of data header starttime: start of the time endtime: end of the time Returns: return 'Successfully' when process success. ''' self.time = np.array(time) self.data = np.array(data,dtype=dtype) self.ratio = ratio self.header = header self.starttime = starttime self.endtime = endtime self.counts = [] return "Successfully" def isrepeat(self) -> bool: ''' Check weather data repeat depend on time. Returns: check there has repeat datetime in the data set. ''' if len(self.time.reshape(-1))==len(set(self.time)): return False else: return True def second(self,ratio: Union[int, float]=None,base: int=1000) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(seconds=1), zeroPara=dict(microsecond=0),storageForward=self.config['storageForward'], outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(seconds=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='second',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def minute(self,ratio: Union[int, float]=None,base: int=60) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(minutes=1), zeroPara=dict(second=0,microsecond=0),storageForward=self.config['storageForward'], outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(minutes=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='minute',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def hour(self,ratio: Union[int, float]=None,base: int=60) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(hours=1) ,zeroPara=dict(minute=0,second=0,microsecond=0),storageForward=self.config['storageForward'], outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(hours=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='hour',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def day(self,ratio: Union[int, float]=None,base: int=24) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(days=1), zeroPara=dict(hour=0,minute=0,second=0,microsecond=0),storageForward=self.config['storageForward'], outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(days=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='day',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def month(self,ratio: Union[int, float]=None,base: int=30) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(months=1), zeroPara=dict(day=1,hour=0,minute=0,second=0,microsecond=0), outputPara_list=self.config['outputPara_list'],storageForward=self.config['storageForward'], starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(months=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='month',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def season(self,ratio: Union[int, float]=None,base: int=3) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' ''' Spring: March, April, May <br> Summer: June, July, August <br> Autumn: September, October, November <br> Winter: December, January, February ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(season=1), zeroPara=dict(day=1,hour=0,minute=0,second=0,microsecond=0), outputPara_list=self.config['outputPara_list'],storageForward=self.config['storageForward'], starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(season=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='season',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def year(self,ratio:Union[int, float]=None,base:int=12) -> Union[None, tuple, list, dict]: ''' Do statistic method base on config setting. Arguments: ratio: require of the data numbers(int) or ratio(float) base: base number of required data, use on ratio<=1 Returns: structure of return data None: if config.selfUpdate==True, then export data by self.get() tuple or list: if config.selfUpdate==False & config.asDict==False, then return the data as tuple. ( time, data, count ) dict: if config.selfUpdate==False & config.asDict==True, then return the data as dictionary. { time: np.ndarray, data: np.ndarray, count: np.ndarray } ''' if ratio!=None: ratio=int(base*ratio) if ratio<=1 else int(ratio) else: if self.ratio!=None: ratio=int(base*self.ratio) if self.ratio<=1 else int(self.ratio) if self.config['fixTime']: if self.config['zeroStart']: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(years=1), zeroPara=dict(month=1,day=1,hour=0,minute=0,second=0,microsecond=0),storageForward=self.config['storageForward'], outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: tummy,dummy,count = self._fixTime(self.time,self.data,timeStep=dict(years=1), outputPara_list=self.config['outputPara_list'],starttime=self.starttime,endtime=self.endtime) else: # self.config['fixTime']==False tummy,dummy,count = self._nofixTime(self.time,self.data,parameter='year',outputPara_list=self.config['outputPara_list']) dummy = self._QC_numbers(dummy,count,ratio) if self.config['selfUpdate']: self.data = np.array(dummy) self.time = np.array(tummy) self.counts = np.array(count) else: print("This is not object standard operation!") print("You need to set config[selfUpdate]=True and use get method to get the result.") dummy = Time._set_header(dummy,header=self.header) if self.config['asDict']: return dict(time=tummy,data=dummy,counts=count) else: return tummy,dummy,count def get(self,parameter: str=None) -> Union[list, dict, np.ndarray]: ''' export the data from Time factory. Arguments: parameter: select the return parameter. enum: None: { time, data, counts }, config, time, data, counts Returns: select parameter data set. ''' if parameter=='config': return self.config if (parameter==None) and (self.config['asDict']): return dict(time=self.time, data=Time._set_header(self.data,header=self.header), counts=self.counts) if parameter=='time': return self.time if parameter=='data': return Time._set_header(self.data,header=self.header) if parameter=='counts': return self.counts print("Please select the return parameter or set config['asDict']=True.") if __name__ == "__main__": # Implement the object myobj = Time() # Input data import datetime, random st = datetime.datetime(2020,1,1) number = 50000 time = [st+datetime.timedelta(hours=val) for val in range(number)] data = [[random.gauss(10,5) for _ in range(4)] for _ in range(number)] myobj.input(time,data,header=['a','b','c','d']) # Calculate and Get result # myobj.hour(1,500) myobj.set_config(outputPara_list=['mean','std','max','quartile']) myobj.season() myobj.set_config(asDict=True) result = myobj.get() print(result)
[ 2, 48443, 8800, 14, 29412, 18, 198, 2, 611, 973, 20967, 11157, 1160, 13, 940, 393, 1568, 11, 28846, 900, 355, 1303, 48443, 8800, 14, 29412, 290, 779, 7347, 2427, 286, 7347, 18, 198, 198, 2, 38093, 855, 1303, 198, 2, 40315, 6738, 2...
2.018998
15,949
import math
[ 11748, 10688 ]
5.5
2
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. from .backbones.darknet import CSPDarknet, Darknet from .backbones.resnet_vd import Resnet18Vd, Resnet50Vd from .backbones.resnet_vb import Resnet50Vb from .losses.yolov3_loss import YOLOv3Loss from .losses.losses import IOUloss from .losses.iou_losses import MyIOUloss, IouLoss, IouAwareLoss from .losses.fcos_loss import FCOSLoss from .heads.yolov3_head import YOLOv3Head from .heads.yolox_head import YOLOXHead from .heads.fcos_head import FCOSHead from .necks.yolo_pafpn import YOLOPAFPN from .necks.yolo_fpn import YOLOFPN from .necks.fpn import FPN from .architectures.yolo import PPYOLO from .architectures.yolox import YOLOX from .architectures.fcos import FCOS
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 2, 15069, 357, 66, 8, 1946, 12, 1238, 2481, 8336, 85, 4178, 3457, 13, 1439, 2489, 10395, 13, 198, 198, 6738, 764, ...
2.537217
309
#!/usr/bin/env python import numpy as np import kaldiio id2mfcc = kaldiio.load_scp('/home/sangjik/kaldi/egs/voxceleb/v2.smallest/mfcc/raw_mfcc_train.10.scp') for utt_id, mfcc in id2mfcc.items(): #print(utt_id, mfcc.shape) np.save('./tmp_mfcc/{}.npy'.format(utt_id), mfcc)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 479, 37566, 952, 198, 198, 312, 17, 76, 69, 535, 796, 479, 37566, 952, 13, 2220, 62, 1416, 79, 10786, 14, 11195, 14, 82, 648, 73, 11...
1.918367
147
import logging import pathlib import re import os from fnmatch import fnmatch from textwrap import dedent from collections import defaultdict import datajoint as dj from . import lab from . import experiment from . import ephys from . import tracking from .ingest.tracking import TrackingIngest from pipeline.globus import GlobusStorageManager from . import get_schema_name PUBLICATION_TRANSFER_TIMEOUT = 10000 schema = dj.schema(get_schema_name('publication')) log = logging.getLogger(__name__) __all__ = [experiment, ephys] @schema class GlobusStorageLocation(dj.Lookup): """ globus storage locations """ definition = """ globus_alias: varchar(32) # name for location (e.g. 'raw-ephys') --- globus_endpoint: varchar(255) # globus endpoint (user#endpoint) globus_path: varchar(1024) # unix-style path within endpoint """ @property @classmethod def local_endpoint(cls, globus_alias=None): ''' return local endpoint for globus_alias from dj.config expects: globus.local_endpoints: { globus_alias: { 'endpoint': uuid, # UUID of local endpoint 'endpoint_subdir': str, # unix-style path within endpoint 'endpoint_path': str # corresponding local path } ''' le = dj.config.get('custom', {}).get('globus.local_endpoints', None) if le is None or globus_alias not in le: raise dj.DataJointError( "globus_local_endpoints for {} not configured".format( globus_alias)) return le[globus_alias] @schema @schema @schema @schema @schema @schema @schema class ArchivedTrackingVideo(dj.Imported): ''' ArchivedTrackingVideo storage Note: video_file_name tracked here as trial->file map is non-deterministic Directory locations of the form: {Water restriction number}\{Session Date}\video with file naming convention of the form: {Water restriction number}_{camera-position-string}_NNN-NNNN.avi Where 'NNN' is determined from the 'tracking map file' which maps trials to videos as outlined in tracking.py XXX: Using key-source based loookup as is currently done, may have trials for which there is no tracking, so camera cannot be determined to do file lookup, thus videos are missed. This could be resolved via schema adjustment, or file-traversal based 'opportunistic' registration strategy. ''' definition = """ -> ArchivedSession -> tracking.TrackingDevice --- -> DataSet """ key_source = tracking.TrackingDevice * experiment.Session ingest = None # ingest module reference gsm = None # for GlobusStorageManager @classmethod def get_ingest(cls): ''' return tracking_ingest module not imported globally to prevent ingest schema creation for client case ''' log.debug('ArchivedVideoFile.get_ingest()') if cls.ingest is None: from .ingest import tracking as tracking_ingest cls.ingest = tracking_ingest return cls.ingest @classmethod def discover(cls): """ discover files on globus and attempt to register them """ self = cls() globus_alias = 'raw-video' le = GlobusStorageLocation.local_endpoint(globus_alias) lep, lep_sub, lep_dir = (le['endpoint'], le['endpoint_subdir'], le['endpoint_path']) ra, rep, rep_sub = (GlobusStorageLocation() & {'globus_alias': globus_alias}).fetch1().values() smap = {'{}/{}'.format(s['water_restriction_number'], s['session_date']).replace('-', ''): s for s in (experiment.Session() * (lab.WaterRestriction() * lab.Subject.proj()))} tpos_dev = {s['tracking_position']: s['tracking_device'] for s in tracking.TrackingDevice()} # position:device ftmap = {t['file_type']: t for t in (FileType() & "file_type like 'tracking%%'")} skey = None sskip = set() sfiles = [] # {file_subpath:, trial:, file_type:,} gsm = self.get_gsm() gsm.activate_endpoint(lep) gsm.activate_endpoint(rep) for ep, dirname, node in gsm.fts('{}:{}'.format(rep, rep_sub)): vdir = re.match('([a-z]+[0-9]+)/([0-9]{8})/video', dirname) if not vdir or node['DATA_TYPE'] != 'file': continue h2o, sdate = vdir[1], vdir[2] skey_i = '{}/{}'.format(h2o, sdate) if skey_i != skey: if skey and skey in smap: with dj.conn().transaction: try: commit(skey, sfiles) except Exception as e: log.error( 'Exception {} committing {}. files: {}'.format( repr(e), skey, sfiles)) skey, sfiles = skey_i, [] if skey not in smap: if skey not in sskip: log.debug('session {} not known. skipping'.format(skey)) sskip.add(skey) continue fname = node['name'] log.debug('checking {}/{}'.format(dirname, fname)) if '.' not in fname: log.debug('skipping {} - no dot in fname'.format(fname)) continue froot, fext = fname.split('.', 1) ftype = {g['file_type']: g for g in ftmap.values() if fnmatch(fname, g['file_glob'])} if len(ftype) != 1: log.debug('skipping {} - incorrect type matches: {}'.format( fname, ftype)) continue ftype = next(iter(ftype.values()))['file_type'] log.debug('processing as {}'.format(ftype)) file_subpath = '{}/{}'.format(dirname, fname) if ftype == 'tracking-video-map': # e.g. dl55_20190108_side.txt h2o_f, fdate, pos = froot.split('_') sfiles.append({'water_restriction_number': h2o, 'session_date': '{}-{}-{}'.format( sdate[:4], sdate[4:6], sdate[6:]), 'position': pos, 'file_subpath': file_subpath, 'file_type': ftype}) else: # tracking-video-map # e.g. dl41_side_998-0000.avi or dl41_side_998-0000_00.avi h2o_f, pos, video = froot.replace('-', '_').split('_')[:3] sfiles.append({'water_restriction_number': h2o, 'session_date': '{}-{}-{}'.format( sdate[:4], sdate[4:6], sdate[6:]), 'position': pos, 'video': int(video), 'file_subpath': file_subpath, 'file_type': ftype}) def make(self, key): """ discover files in local endpoint and transfer/register """ log.info('ArchivedVideoFile.make(): {}'.format(key)) # {'tracking_device': 'Camera 0', 'subject_id': 432572, 'session': 1} globus_alias = 'raw-video' le = GlobusStorageLocation.local_endpoint(globus_alias) lep, lep_sub, lep_dir = (le['endpoint'], le['endpoint_subdir'], le['endpoint_path']) re = (GlobusStorageLocation & {'globus_alias': globus_alias}).fetch1() rep, rep_sub = re['globus_endpoint'], re['globus_path'] log.info('local_endpoint: {}:{} -> {}'.format(lep, lep_sub, lep_dir)) log.info('remote_endpoint: {}:{}'.format(rep, rep_sub)) h2o = (lab.WaterRestriction & key).fetch1('water_restriction_number') session = (experiment.Session & key).fetch1() sdate = session['session_date'] sdate_sml = "{}{:02d}{:02d}".format(sdate.year, sdate.month, sdate.day) dev = (tracking.TrackingDevice & key).fetch1() trls = (experiment.SessionTrial & key).fetch( order_by='trial', as_dict=True) tracking_ingest = self.get_ingest() tdev = dev['tracking_device'] # NOQA: notused tpos = dev['tracking_position'] camtrial = '{}_{}_{}.txt'.format(h2o, sdate_sml, tpos) vbase = pathlib.Path(lep_dir, h2o, sdate_sml, 'video') campath = vbase / camtrial if not campath.exists(): # XXX: uses 1st found log.warning('trial map {} n/a! skipping.'.format(campath)) return log.info('loading trial map: {}'.format(campath)) vmap = {v: k for k, v in tracking_ingest.TrackingIngest.load_campath(campath).items()} log.debug('loaded video map: {}'.format(vmap)) # add ArchivedSession as_key = {k: v for k, v in key.items() if k in experiment.Session.primary_key} as_rec = {**as_key, 'globus_alias': globus_alias} ArchivedSession.insert1(as_rec, allow_direct_insert=True, skip_duplicates=True) # add DataSet ds_type = 'tracking-video' ds_name = '{}_{}_{}_{}'.format(h2o, sdate.isoformat(), ds_type, tpos) ds_key = {'globus_alias': globus_alias, 'dataset_name': ds_name} ds_rec = {**ds_key, 'dataset_type': ds_type} DataSet.insert1(ds_rec, allow_direct_insert=True) # add ArchivedVideoTracking vt_key = {**as_key, 'tracking_device': tdev} vt_rec = {**vt_key, 'globus_alias': globus_alias, 'dataset_name': ds_name} self.insert1(vt_rec) filetype = 'tracking-video-trial' for t in trls: trial = t['trial'] log.info('.. tracking trial {} ({})'.format(trial, t)) if t['trial'] not in vmap: log.warning('trial {} not in video map. skipping!'.format(t)) continue vmatch = '{}_{}_{}-*'.format(h2o, tpos, vmap[trial]) log.debug('vbase: {}, vmatch: {}'.format(vbase, vmatch)) vglob = list(vbase.glob(vmatch)) if len(vglob) != 1: emsg = 'incorrect videos found in {}: {}'.format(vbase, vglob) log.warning(emsg) raise dj.DataJointError(emsg) vfile = vglob[0].name gfile = '{}/{}/{}/{}'.format( h2o, sdate_sml, 'video', vfile) # subpath srcp = '{}:{}/{}'.format(lep, lep_sub, gfile) # source path dstp = '{}:{}/{}'.format(rep, rep_sub, gfile) # dest path gsm = self.get_gsm() gsm.activate_endpoint(lep) # XXX: cache / prevent duplicate RPC? gsm.activate_endpoint(rep) # XXX: cache / prevent duplicate RPC? log.info('transferring {} to {}'.format(srcp, dstp)) if not gsm.cp(srcp, dstp): emsg = "couldn't transfer {} to {}".format(srcp, dstp) log.error(emsg) raise dj.DataJointError(emsg) pf_key = {**ds_key, 'file_subpath': vfile} pf_rec = {**pf_key, 'file_type': filetype} DataSet.PhysicalFile.insert1({**pf_rec}, allow_direct_insert=True) trk_key = {k: v for k, v in {**key, 'trial': trial}.items() if k in experiment.SessionTrial.primary_key} tv_rec = {**vt_key, **trk_key, **pf_key} self.TrialVideo.insert1({**tv_rec}) def test_flist(fname='globus-index-full.txt'): ''' spoof tester for discover methods expects: f: ep:/path/to/file d: ep:/path/to/direct etc. (aka: globus-shell 'find' output) replace the line: for ep, dirname, node in gsm.fts('{}:{}'.format(rep, rep_sub)): with: for ep, dirname, node in test_flist('globus-list.txt'): to test against the file 'globus-list.txt' ''' with open(fname, 'r') as infile: for l in infile: try: t, fp = l.split(' ') fp = fp.split(':')[1].lstrip('/').rstrip('\n') dn, bn = os.path.split(fp) if t == 'f:': yield ('ep', dn, {'DATA_TYPE': 'file', 'name': bn}) else: yield ('ep', dn, {'DATA_TYPE': 'dunno', 'path': bn}) except ValueError as e: if 'too many values' in repr(e): pass
[ 198, 11748, 18931, 198, 11748, 3108, 8019, 198, 11748, 302, 198, 11748, 28686, 198, 198, 6738, 24714, 15699, 1330, 24714, 15699, 198, 6738, 2420, 37150, 1330, 4648, 298, 198, 6738, 17268, 1330, 4277, 11600, 198, 198, 11748, 1366, 73, 1563...
1.975054
6,494
from .data_reader import ( BetterDatasetReader, SRLDatasetReader ) from .metrics import SRLMetric, BaseF, ExactMatch, FBetaMixMeasure from .models import SpanModel from .modules import ( MLPSpanTyping, SpanTyping, SpanFinder, BIOSpanFinder ) from .predictor import SpanPredictor from .utils import Span
[ 6738, 764, 7890, 62, 46862, 1330, 357, 198, 220, 220, 220, 11625, 27354, 292, 316, 33634, 11, 311, 7836, 27354, 292, 316, 33634, 198, 8, 198, 6738, 764, 4164, 10466, 1330, 311, 7836, 9171, 1173, 11, 7308, 37, 11, 1475, 529, 23850, 1...
3.04902
102
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------ # From: # https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/ml-frameworks/scikit-learn/train-hyperparameter-tune-deploy-with-sklearn/train_iris.py import argparse from pathlib import Path import numpy as np from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from health_azure import submit_to_azure_if_needed if __name__ == "__main__": main()
[ 2, 220, 16529, 22369, 438, 198, 2, 220, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 220, 49962, 739, 262, 17168, 13789, 357, 36393, 737, 4091, 38559, 24290, 287, 262, 29924, 6808, 329, 5964, 1321, 13, 198, 2, ...
3.954082
196
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest from click.testing import CliRunner from pivotpoint import pp from pivotpoint import cli
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 555, 715, 395, 198, 6738, 3904, 13, 33407, 1330, 1012, 72, 49493, 198, 6738, 30355, 4122, 1330, 9788, 198, 6738,...
3.04
50
# -*- coding: utf-8 -*- """rackio/dao/controls.py This module implements Controls Data Objects Access. """ from .core import RackioDAO
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 39638, 952, 14, 67, 5488, 14, 13716, 82, 13, 9078, 198, 198, 1212, 8265, 23986, 36357, 6060, 35832, 8798, 13, 198, 37811, 198, 6738, 764, 7295, 1330, 37927, 952, ...
2.875
48
# coding:utf-8 # 添加PDF书签 from pdf_utils import MyPDFHandler,PDFHandleMode as mode import ConfigParser import sys reload(sys) sys.setdefaultencoding('utf-8') if __name__ == '__main__': main()
[ 2, 19617, 25, 40477, 12, 23, 201, 198, 2, 10545, 115, 119, 27950, 254, 20456, 20046, 99, 163, 255, 122, 201, 198, 6738, 37124, 62, 26791, 1330, 2011, 20456, 25060, 11, 20456, 37508, 19076, 355, 4235, 201, 198, 11748, 17056, 46677, 201...
2.372093
86
from typing import List, Optional, Union import pytest from openff.utilities.utilities import has_executable, has_package def skip_if_missing(package_name: str, reason: Optional[str] = None): """ Helper function to generate a pytest.mark.skipif decorator for any package. This allows tests to be skipped if some optional dependency is not found. Parameters ---------- package_name : str The name of the package that is required for a test(s) reason : str, optional Explanation of why the skipped it to be tested Returns ------- requires_package : _pytest.mark.structures.MarkDecorator A pytest decorator that will skip tests if the package is not available """ if not reason: reason = f"Package {package_name} is required, but was not found." requires_package = pytest.mark.skipif(not has_package(package_name), reason=reason) return requires_package def skip_if_missing_exec(exec: Union[str, List[str]]): """Helper function to generate a pytest.mark.skipif decorator if an executable(s) is not found.""" if isinstance(exec, str): execs: List = [exec] elif isinstance(exec, list): execs: List = exec # type: ignore[no-redef] else: raise ValueError( "Bad type passed to skip_if_missing_exec. " f"Found type {type(exec)}" ) found_exec = False for exec_ in execs: found_exec = found_exec or has_executable(exec_) reason = f"Package {str(exec)} is required, but was not found." mark = pytest.mark.skipif(not found_exec, reason=reason) return mark
[ 6738, 19720, 1330, 7343, 11, 32233, 11, 4479, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 1280, 487, 13, 315, 2410, 13, 315, 2410, 1330, 468, 62, 18558, 18187, 11, 468, 62, 26495, 628, 198, 4299, 14267, 62, 361, 62, 45688, 7, 2649...
2.79046
587
if __name__ == '__main__': test_case_1() test_case_2() test_case_3()
[ 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 628, 198, 198, 9288, 62, 7442, 62, 16, 3419, 198, 9288, 62, 7442, 62, 17, 3419, 198, 9288, 62, 7442, 62, 18, 3419, 198 ]
2.083333
36
"""Test for checking if the response format is proper. Run test_crud before running this.""" import unittest import random import string import json import re import uuid from hydrus.app_factory import app_factory from hydrus.socketio_factory import create_socket from hydrus.utils import set_session, set_doc, set_api_name, set_page_size from hydrus.data import doc_parse, crud from hydra_python_core import doc_maker from hydra_python_core.doc_writer import HydraLink from hydrus.samples import doc_writer_sample from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from hydrus.data.db_models import Base def gen_dummy_object(class_title, doc): """Create a dummy object based on the definitions in the API Doc. :param class_title: Title of the class whose object is being created. :param doc: ApiDoc. :return: A dummy object of class `class_title`. """ object_ = { "@type": class_title } for class_path in doc.parsed_classes: if class_title == doc.parsed_classes[class_path]["class"].title: for prop in doc.parsed_classes[class_path]["class"].supportedProperty: if isinstance(prop.prop, HydraLink) or prop.write is False: continue if "vocab:" in prop.prop: prop_class = prop.prop.replace("vocab:", "") object_[prop.title] = gen_dummy_object(prop_class, doc) else: object_[prop.title] = ''.join(random.choice( string.ascii_uppercase + string.digits) for _ in range(6)) return object_ class ViewsTestCase(unittest.TestCase): """Test Class for the app.""" @classmethod def setUpClass(self): """Database setup before the tests.""" print("Creating a temporary database...") engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) session = scoped_session(sessionmaker(bind=engine)) self.session = session self.API_NAME = "demoapi" self.page_size = 1 self.HYDRUS_SERVER_URL = "http://hydrus.com/" self.app = app_factory(self.API_NAME) self.socketio = create_socket(self.app, self.session) print("going for create doc") self.doc = doc_maker.create_doc( doc_writer_sample.api_doc.generate(), self.HYDRUS_SERVER_URL, self.API_NAME) test_classes = doc_parse.get_classes(self.doc.generate()) test_properties = doc_parse.get_all_properties(test_classes) doc_parse.insert_classes(test_classes, self.session) doc_parse.insert_properties(test_properties, self.session) print("Classes and properties added successfully.") print("Setting up hydrus utilities... ") self.api_name_util = set_api_name(self.app, self.API_NAME) self.session_util = set_session(self.app, self.session) self.doc_util = set_doc(self.app, self.doc) self.page_size_util = set_page_size(self.app, self.page_size) self.client = self.app.test_client() print("Creating utilities context... ") self.api_name_util.__enter__() self.session_util.__enter__() self.doc_util.__enter__() self.client.__enter__() print("Setup done, running tests...") @classmethod def tearDownClass(self): """Tear down temporary database and exit utilities""" self.client.__exit__(None, None, None) self.doc_util.__exit__(None, None, None) self.session_util.__exit__(None, None, None) self.api_name_util.__exit__(None, None, None) self.session.close() def test_Index(self): """Test for the index.""" response_get = self.client.get("/{}".format(self.API_NAME)) endpoints = json.loads(response_get.data.decode('utf-8')) response_post = self.client.post( "/{}".format(self.API_NAME), data=dict(foo="bar")) response_put = self.client.put( "/{}".format(self.API_NAME), data=dict(foo="bar")) response_delete = self.client.delete("/{}".format(self.API_NAME)) assert "@context" in endpoints assert endpoints["@id"] == "/{}".format(self.API_NAME) assert endpoints["@type"] == "EntryPoint" assert response_get.status_code == 200 assert response_post.status_code == 405 assert response_put.status_code == 405 assert response_delete.status_code == 405 def test_EntryPoint_context(self): """Test for the EntryPoint context.""" response_get = self.client.get( "/{}/contexts/EntryPoint.jsonld".format(self.API_NAME)) response_get_data = json.loads(response_get.data.decode('utf-8')) response_post = self.client.post( "/{}/contexts/EntryPoint.jsonld".format(self.API_NAME), data={}) response_delete = self.client.delete( "/{}/contexts/EntryPoint.jsonld".format(self.API_NAME)) assert response_get.status_code == 200 assert "@context" in response_get_data assert response_post.status_code == 405 assert response_delete.status_code == 405 def test_Vocab(self): """Test the vocab.""" response_get = self.client.get("/{}/vocab#".format(self.API_NAME)) response_get_data = json.loads(response_get.data.decode('utf-8')) assert "@context" in response_get_data assert response_get_data["@type"] == "ApiDocumentation" assert response_get_data["@id"] == "{}{}/vocab".format( self.HYDRUS_SERVER_URL, self.API_NAME) assert response_get.status_code == 200 response_delete = self.client.delete( "/{}/vocab#".format(self.API_NAME)) assert response_delete.status_code == 405 response_put = self.client.put( "/{}/vocab#".format(self.API_NAME), data=json.dumps(dict(foo='bar'))) assert response_put.status_code == 405 response_post = self.client.post( "/{}/vocab#".format(self.API_NAME), data=json.dumps(dict(foo='bar'))) assert response_post.status_code == 405 def test_Collections_GET(self): """Test GET on collection endpoints.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: response_get = self.client.get(endpoints[endpoint]) # pdb.set_trace() assert response_get.status_code == 200 response_get_data = json.loads( response_get.data.decode('utf-8')) assert "@context" in response_get_data assert "@id" in response_get_data assert "@type" in response_get_data assert "members" in response_get_data # Check the item URI has the valid format, so it can be dereferenced if len(response_get_data["members"]) > 0: for item in response_get_data["members"]: class_type = item["@type"] if class_type in self.doc.parsed_classes: class_ = self.doc.parsed_classes[class_type]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "GET" in class_methods: item_response = self.client.get( response_get_data["members"][0]["@id"]) assert item_response.status_code == 200 def test_pagination(self): """Test basic pagination""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: response_get = self.client.get(endpoints[endpoint]) assert response_get.status_code == 200 response_get_data = json.loads( response_get.data.decode('utf-8')) assert "view" in response_get_data assert "first" in response_get_data["view"] assert "last" in response_get_data["view"] if "next" in response_get_data["view"]: response_next = self.client.get(response_get_data["view"]["next"]) assert response_next.status_code == 200 response_next_data = json.loads( response_next.data.decode('utf-8')) assert "previous" in response_next_data["view"] break def test_Collections_PUT(self): """Test insert data to the collection.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: collection = self.doc.collections[collection_name]["collection"] dummy_object = gen_dummy_object( collection.class_.title, self.doc) good_response_put = self.client.put( endpoints[endpoint], data=json.dumps(dummy_object)) assert good_response_put.status_code == 201 def test_object_POST(self): """Test replace of a given object using ID.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: collection = self.doc.collections[collection_name]["collection"] class_ = self.doc.parsed_classes[collection.class_.title]["class"] class_methods = [x.method for x in class_.supportedOperation] dummy_object = gen_dummy_object( collection.class_.title, self.doc) initial_put_response = self.client.put( endpoints[endpoint], data=json.dumps(dummy_object)) assert initial_put_response.status_code == 201 response = json.loads( initial_put_response.data.decode('utf-8')) regex = r'(.*)ID (.{36})* (.*)' matchObj = re.match(regex, response["description"]) assert matchObj is not None id_ = matchObj.group(2) if "POST" in class_methods: dummy_object = gen_dummy_object( collection.class_.title, self.doc) post_replace_response = self.client.post( '{}/{}'.format(endpoints[endpoint], id_), data=json.dumps(dummy_object)) assert post_replace_response.status_code == 200 def test_object_DELETE(self): """Test DELETE of a given object using ID.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: collection = self.doc.collections[collection_name]["collection"] class_ = self.doc.parsed_classes[collection.class_.title]["class"] class_methods = [x.method for x in class_.supportedOperation] dummy_object = gen_dummy_object( collection.class_.title, self.doc) initial_put_response = self.client.put( endpoints[endpoint], data=json.dumps(dummy_object)) assert initial_put_response.status_code == 201 response = json.loads( initial_put_response.data.decode('utf-8')) regex = r'(.*)ID (.{36})* (.*)' matchObj = re.match(regex, response["description"]) assert matchObj is not None id_ = matchObj.group(2) if "DELETE" in class_methods: delete_response = self.client.delete( '{}/{}'.format(endpoints[endpoint], id_)) assert delete_response.status_code == 200 def test_object_PUT_at_id(self): """Create object in collection using PUT at specific ID.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: collection = self.doc.collections[collection_name]["collection"] class_ = self.doc.parsed_classes[collection.class_.title]["class"] class_methods = [x.method for x in class_.supportedOperation] dummy_object = gen_dummy_object( collection.class_.title, self.doc) if "PUT" in class_methods: dummy_object = gen_dummy_object( collection.class_.title, self.doc) put_response = self.client.put('{}/{}'.format( endpoints[endpoint], uuid.uuid4()), data=json.dumps(dummy_object)) assert put_response.status_code == 201 def test_endpointClass_PUT(self): """Check non collection Class PUT.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "PUT" in class_methods: dummy_object = gen_dummy_object(class_.title, self.doc) put_response = self.client.put( endpoints[endpoint], data=json.dumps(dummy_object)) assert put_response.status_code == 201 def test_endpointClass_POST(self): """Check non collection Class POST.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "POST" in class_methods: dummy_object = gen_dummy_object(class_.title, self.doc) post_response = self.client.post( endpoints[endpoint], data=json.dumps(dummy_object)) assert post_response.status_code == 200 def test_endpointClass_DELETE(self): """Check non collection Class DELETE.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "DELETE" in class_methods: delete_response = self.client.delete( endpoints[endpoint]) assert delete_response.status_code == 200 def test_endpointClass_GET(self): """Check non collection Class GET.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "GET" in class_methods: response_get = self.client.get(endpoints[endpoint]) assert response_get.status_code == 200 response_get_data = json.loads( response_get.data.decode('utf-8')) assert "@context" in response_get_data assert "@id" in response_get_data assert "@type" in response_get_data def test_IriTemplate(self): """Test structure of IriTemplates attached to collections""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: response_get = self.client.get(endpoints[endpoint]) assert response_get.status_code == 200 response_get_data = json.loads( response_get.data.decode('utf-8')) assert "search" in response_get_data assert "mapping" in response_get_data["search"] collection = self.doc.collections[collection_name]["collection"] class_ = self.doc.parsed_classes[collection.class_.title]["class"] class_props = [x.prop for x in class_.supportedProperty] for mapping in response_get_data["search"]["mapping"]: if mapping["property"] not in ["limit", "offset", "pageIndex"]: assert mapping["property"] in class_props def test_client_controlled_pagination(self): """Test pagination controlled by client with help of pageIndex, offset and limit parameters.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: response_get = self.client.get(endpoints[endpoint]) assert response_get.status_code == 200 response_get_data = json.loads( response_get.data.decode('utf-8')) assert "search" in response_get_data assert "mapping" in response_get_data["search"] # Test with pageIndex and limit params = {"pageIndex": 1, "limit": 2} response_for_page_param = self.client.get(endpoints[endpoint], query_string=params) assert response_for_page_param.status_code == 200 response_for_page_param_data = json.loads( response_for_page_param.data.decode('utf-8')) assert "first" in response_for_page_param_data["view"] assert "last" in response_for_page_param_data["view"] if "next" in response_for_page_param_data["view"]: assert "pageIndex=2" in response_for_page_param_data["view"]["next"] next_response = self.client.get(response_for_page_param_data["view"]["next"]) assert next_response.status_code == 200 next_response_data = json.loads( next_response.data.decode('utf-8')) assert "previous" in next_response_data["view"] assert "pageIndex=1" in next_response_data["view"]["previous"] # Test with offset and limit params = {"offset": 1, "limit": 2} response_for_offset_param = self.client.get(endpoints[endpoint], query_string=params) assert response_for_offset_param.status_code == 200 response_for_offset_param_data = json.loads( response_for_offset_param.data.decode('utf-8')) assert "first" in response_for_offset_param_data["view"] assert "last" in response_for_offset_param_data["view"] if "next" in response_for_offset_param_data["view"]: assert "offset=3" in response_for_offset_param_data["view"]["next"] next_response = self.client.get( response_for_offset_param_data["view"]["next"]) assert next_response.status_code == 200 next_response_data = json.loads( next_response.data.decode('utf-8')) assert "previous" in next_response_data["view"] assert "offset=1" in next_response_data["view"]["previous"] def test_bad_objects(self): """Checks if bad objects are added or not.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: bad_response_put = self.client.put( endpoints[endpoint], data=json.dumps( dict( foo='bar'))) assert bad_response_put.status_code == 400 def test_bad_requests(self): """Checks if bad requests are handled or not.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: collection = self.doc.collections[collection_name]["collection"] class_ = self.doc.parsed_classes[collection.class_.title]["class"] class_methods = [x.method for x in class_.supportedOperation] dummy_object = gen_dummy_object( collection.class_.title, self.doc) initial_put_response = self.client.put( endpoints[endpoint], data=json.dumps(dummy_object)) assert initial_put_response.status_code == 201 response = json.loads( initial_put_response.data.decode('utf-8')) regex = r'(.*)ID (.{36})* (.*)' matchObj = re.match(regex, response["description"]) assert matchObj is not None id_ = matchObj.group(2) if "POST" not in class_methods: dummy_object = gen_dummy_object( collection.class_.title, self.doc) post_replace_response = self.client.post( '{}/{}'.format(endpoints[endpoint], id_), data=json.dumps(dummy_object)) assert post_replace_response.status_code == 405 if "DELETE" not in class_methods: delete_response = self.client.delete( '{}/{}'.format(endpoints[endpoint], id_)) assert delete_response.status_code == 405 def test_Endpoints_Contexts(self): """Test all endpoints contexts are generated properly.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: collection_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if collection_name in self.doc.collections: response_get = self.client.get(endpoints[endpoint]) assert response_get.status_code == 200 context = json.loads( response_get.data.decode('utf-8'))["@context"] response_context = self.client.get(context) response_context_data = json.loads( response_context.data.decode('utf-8')) assert response_context.status_code == 200 assert "@context" in response_context_data class SocketTestCase(unittest.TestCase): """Test Class for socket events and operations.""" @classmethod def setUpClass(self): """Database setup before the tests.""" print("Creating a temporary database...") engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) session = scoped_session(sessionmaker(bind=engine)) self.session = session self.API_NAME = "demoapi" self.page_size = 1 self.HYDRUS_SERVER_URL = "http://hydrus.com/" self.app = app_factory(self.API_NAME) self.socketio = create_socket(self.app, self.session) print("going for create doc") self.doc = doc_maker.create_doc( doc_writer_sample.api_doc.generate(), self.HYDRUS_SERVER_URL, self.API_NAME) test_classes = doc_parse.get_classes(self.doc.generate()) test_properties = doc_parse.get_all_properties(test_classes) doc_parse.insert_classes(test_classes, self.session) doc_parse.insert_properties(test_properties, self.session) print("Classes and properties added successfully.") print("Setting up hydrus utilities... ") self.api_name_util = set_api_name(self.app, self.API_NAME) self.session_util = set_session(self.app, self.session) self.doc_util = set_doc(self.app, self.doc) self.page_size_util = set_page_size(self.app, self.page_size) self.client = self.app.test_client() self.socketio_client = self.socketio.test_client(self.app, namespace='/sync') print("Creating utilities context... ") self.api_name_util.__enter__() self.session_util.__enter__() self.doc_util.__enter__() self.client.__enter__() print("Setup done, running tests...") @classmethod def tearDownClass(self): """Tear down temporary database and exit utilities""" self.client.__exit__(None, None, None) self.doc_util.__exit__(None, None, None) self.session_util.__exit__(None, None, None) self.api_name_util.__exit__(None, None, None) self.session.close() def test_connect(self): """Test connect event.""" socket_client = self.socketio.test_client(self.app, namespace='/sync') data = socket_client.get_received('/sync') assert len(data) > 0 event = data[0] assert event['name'] == 'connect' last_job_id = crud.get_last_modification_job_id(self.session) assert event['args'][0]['last_job_id'] == last_job_id socket_client.disconnect(namespace='/sync') def test_reconnect(self): """Test reconnect event.""" socket_client = self.socketio.test_client(self.app, namespace='/sync') # Flush data of first connect event socket_client.get_received('/sync') # Client reconnects by emitting 'reconnect' event. socket_client.emit('reconnect', namespace='/sync') # Get update received on reconnecting to the server data = socket_client.get_received('/sync') assert len(data) > 0 # Extract the event information event = data[0] assert event['name'] == 'connect' last_job_id = crud.get_last_modification_job_id(self.session) # Check last job id with last_job_id received by client in the update. assert event['args'][0]['last_job_id'] == last_job_id socket_client.disconnect(namespace='/sync') def test_modification_table_diff(self): """Test 'modification-table-diff' events.""" # Flush old received data at socket client self.socketio_client.get_received('/sync') # Set last_job_id as the agent_job_id agent_job_id = crud.get_last_modification_job_id(self.session) # Add an extra modification record newer than the agent_job_id new_latest_job_id = crud.insert_modification_record(method="POST", resource_url="", session=self.session) self.socketio_client.emit('get_modification_table_diff', {'agent_job_id': agent_job_id}, namespace='/sync') data = self.socketio_client.get_received('/sync') assert len(data) > 0 event = data[0] assert event['name'] == 'modification_table_diff' # Check received event contains data of newly added modification record. assert event['args'][0][0]['method'] == "POST" assert event['args'][0][0]['resource_url'] == "" assert event['args'][0][0]['job_id'] == new_latest_job_id def test_socketio_POST_updates(self): """Test 'update' event emitted by socketio for POST operations.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "POST" in class_methods: dummy_object = gen_dummy_object(class_.title, self.doc) # Flush old socketio updates self.socketio_client.get_received('/sync') post_response = self.client.post( endpoints[endpoint], data=json.dumps(dummy_object)) assert post_response.status_code == 200 # Get new socketio update update = self.socketio_client.get_received('/sync') assert len(update) != 0 assert update[0]['args'][0]['method'] == "POST" resource_name = update[0]['args'][0]['resource_url'].split('/')[-1] assert resource_name == endpoints[endpoint].split('/')[-1] def test_socketio_DELETE_updates(self): """Test 'update' event emitted by socketio for DELETE operations.""" index = self.client.get("/{}".format(self.API_NAME)) assert index.status_code == 200 endpoints = json.loads(index.data.decode('utf-8')) for endpoint in endpoints: if endpoint not in ["@context", "@id", "@type"]: class_name = "/".join(endpoints[endpoint].split( "/{}/".format(self.API_NAME))[1:]) if class_name not in self.doc.collections: class_ = self.doc.parsed_classes[class_name]["class"] class_methods = [ x.method for x in class_.supportedOperation] if "DELETE" in class_methods: # Flush old socketio updates self.socketio_client.get_received('/sync') delete_response = self.client.delete( endpoints[endpoint]) assert delete_response.status_code == 200 # Get new update event update = self.socketio_client.get_received('/sync') assert len(update) != 0 assert update[0]['args'][0]['method'] == 'DELETE' resource_name = update[0]['args'][0]['resource_url'].split('/')[-1] assert resource_name == endpoints[endpoint].split('/')[-1] if __name__ == '__main__': message = """ Running tests for the app. Checking if all responses are in proper order. """ unittest.main()
[ 37811, 14402, 329, 10627, 611, 262, 2882, 5794, 318, 1774, 13, 5660, 1332, 62, 6098, 463, 878, 2491, 428, 526, 15931, 201, 198, 11748, 555, 715, 395, 201, 198, 11748, 4738, 201, 198, 11748, 4731, 201, 198, 11748, 33918, 201, 198, 1174...
2.039665
17,320
"""Environment Variables """ import os from dotenv import load_dotenv load_dotenv() HIC_DB_USERNAME = os.environ["HIC_DB_USERNAME"] HIC_DB_PASSWORD = os.environ["HIC_DB_PASSWORD"] HIC_DB_HOST = os.environ["HIC_DB_HOST"] HIC_DB_DATABASE = os.environ["HIC_DB_DATABASE"] MS_SQL_ODBC_DRIVER = os.environ["MS_SQL_ODBC_DRIVER"] MS_SQL_UHL_DWH_HOST = os.environ["MS_SQL_UHL_DWH_HOST"] MS_SQL_UHL_DWH_USER = os.environ["MS_SQL_UHL_DWH_USER"] MS_SQL_UHL_DWH_PASSWORD = os.environ["MS_SQL_UHL_DWH_PASSWORD"] IDENTITY_API_KEY = os.environ["IDENTITY_API_KEY"] IDENTITY_HOST = os.environ["IDENTITY_HOST"] HIC_CONNECTION_STRING = os.environ["HIC_CONNECTION_STRING"] HIC_HOST = os.environ["HIC_HOST"] HIC_USERNAME = os.environ["HIC_USERNAME"] HIC_PASSWORD = os.environ["HIC_PASSWORD"]
[ 37811, 31441, 15965, 2977, 201, 198, 37811, 201, 198, 11748, 28686, 201, 198, 6738, 16605, 24330, 1330, 3440, 62, 26518, 24330, 201, 198, 201, 198, 2220, 62, 26518, 24330, 3419, 201, 198, 201, 198, 201, 198, 39, 2149, 62, 11012, 62, 2...
2.043367
392
# Generated by Django 3.2.9 on 2022-01-03 14:32 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 24, 319, 33160, 12, 486, 12, 3070, 1478, 25, 2624, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.84375
32
import numpy as np def fit_transformation(source, target): """ This function computes the best rigid transformation between two point sets. It assumes that "source" and "target" are with the same length and "source[i]" corresponds to "target[i]". :param source: Nxd array. :param target: Nxd array. :return: A transformation as (d+1)x(d+1) matrix; the rotation part as a dxd matrix and the translation part as a dx1 vector. """ assert source.shape == target.shape center_source = np.mean(source, axis=0) center_target = np.mean(target, axis=0) m = source.shape[1] source_zeromean = source - center_source target_zeromean = target - center_target W = np.dot(source_zeromean.T, target_zeromean) U, S, Vt = np.linalg.svd(W) R = np.dot(Vt.T, U.T) if np.linalg.det(R) < 0: Vt[m - 1, :] *= -1 R = np.dot(Vt.T, U.T) t = center_target.T - np.dot(R, center_source.T) T = np.identity(m + 1) T[:m, :m] = R T[:m, m] = t return T, R, t
[ 11748, 299, 32152, 355, 45941, 628, 198, 4299, 4197, 62, 7645, 1161, 7, 10459, 11, 2496, 2599, 198, 220, 220, 220, 37227, 198, 220, 220, 220, 770, 2163, 552, 1769, 262, 1266, 20831, 13389, 1022, 734, 966, 5621, 13, 632, 18533, 326, ...
2.334831
445
""" [Modular Equation](https://www.codechef.com/MAY21C/problems/MODEQ) Given integers N and M, find the number of ordered pairs (a,b) such that 1≤a<b≤N and ((M mod a) mod b)=((M mod b) mod a). Input The first line contains an integer T, the number of test cases. Then the test cases follow. The only line of each test case contains two integers N, M. Output For each testcase, output in a single line the answer to the problem. Constraints 1≤T≤1000 2≤N≤106 1≤M≤5⋅105 The sum of N over all test cases does not exceed 106. Note: Multiplier for JAVA for this problem is reduced to 1.25 instead of usual 2. Subtasks Subtask #1 (10 points): 1≤T≤10 2≤N≤103 1≤M≤105 Subtask #2 (40 points): 1≤T≤100 2≤N≤105 1≤M≤105 The sum of N over all test cases does not exceed 106. Subtask #3 (50 points): Original Constraints Sample Input 3 3 5 3 6 3 10 Sample Output 2 3 2 Explanation Test Case 1: The valid pairs are {(1,2),(1,3)}. Test Case 2: The valid pairs are {(1,2),(1,3),(2,3)}. Test Case 3: The valid pairs are {(1,2),(1,3)}. """ import sys # Brute Force """ if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) T = data[0] idx = 1 while T > 0: N, M = data[idx: idx + 2] res = 0 for i in range(1, N): for j in range(i + 1, N + 1): if (M % i) % j == (M % j) % i: res += 1 print(res) T -= 1 idx += 2 # Time : 0.58s """ if __name__ == '__main__': T = int(input()) idx = 1 while T > 0: N, M = list(map(int, input().split())) res = 0 mod = dict() for a in range(2, N+1): mod_with_a = M % a res += mod.get(mod_with_a, 1) for b in range(mod_with_a, N+1, a): mod[b] = mod.get(b, 1) + 1 print(res) T -= 1 # Time : 4.92s
[ 37811, 198, 58, 5841, 934, 7889, 341, 16151, 5450, 1378, 2503, 13, 19815, 721, 258, 69, 13, 785, 14, 44, 4792, 2481, 34, 14, 1676, 22143, 14, 49058, 48, 8, 198, 198, 15056, 37014, 399, 290, 337, 11, 1064, 262, 1271, 286, 6149, 147...
2.073626
910
import sys import os import yaml class SingleCrawlerManifestManager(object): """ """ required_files = ["spider_manifest.json", "spider_manifest.py"]
[ 11748, 25064, 198, 11748, 28686, 198, 11748, 331, 43695, 628, 198, 4871, 14206, 34, 39464, 5124, 8409, 13511, 7, 15252, 2599, 198, 220, 220, 220, 37227, 628, 628, 220, 220, 220, 37227, 198, 220, 220, 220, 2672, 62, 16624, 796, 14631, ...
2.813559
59
#!/usr/bin/env python ## # # Send SET_GPS_GLOBAL_ORIGIN and SET_HOME_POSITION messages # ## import rospy from pymavlink.dialects.v10 import ardupilotmega as MAV_APM from mavros.mavlink import convert_to_rosmsg from mavros_msgs.msg import Mavlink class fifo(object): """ A simple buffer """ def send_message(msg, mav, pub): """ Send a mavlink message """ msg.pack(mav) rosmsg = convert_to_rosmsg(msg) pub.publish(rosmsg) print("sent message %s" % msg) def set_global_origin(mav, pub, lat, lon, alt): """ Send a mavlink SET_GPS_GLOBAL_ORIGIN message, which allows us to use local position information without a GPS. """ #target_system = mav.srcSystem target_system = 0 # 0 --> broadcast to everyone lattitude = lat longitude = lon altitude = alt msg = MAV_APM.MAVLink_set_gps_global_origin_message( target_system, lattitude, longitude, altitude) send_message(msg, mav, pub) def set_home_position(mav, pub, lat, lon, alt, _x, _y, _z): """ Send a mavlink SET_HOME_POSITION message, which should allow us to use local position information without a GPS """ target_system = 0 # broadcast to everyone lattitude = lat longitude = lon altitude = alt x = _x y = _y z = _z q = [1, 0, 0, 0] # w x y z approach_x = 0 approach_y = 0 approach_z = 1 msg = MAV_APM.MAVLink_set_home_position_message( target_system, lattitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z) send_message(msg, mav, pub) if __name__=="__main__": rospy.init_node('set_home', anonymous=True) # Global position of the origin lat = 37.4933566 * 1e7 lon = 126.8339491 * 1e7 alt = 200 * 1e3 # x = 3.678 # y = -1.719 # z = 0 x = 0 y = 0 z = 0 set_home(lat, lon, alt, x, y, z)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 2235, 198, 2, 198, 2, 16290, 25823, 62, 38, 3705, 62, 8763, 9864, 1847, 62, 1581, 3528, 1268, 290, 25823, 62, 39069, 62, 37997, 17941, 6218, 198, 2, 198, 2235, 198, 198, 11748, ...
2.081736
991
from __future__ import absolute_import from tests.clims.models.test_substance import SubstanceTestCase from clims.plugins.demo.dnaseq.workflows.sequence import SequenceSimple from clims.api.serializers.models.process_definition import ProcessDefinitionSerializer expected_sequence_simple = { 'id': u'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'fields': [{ 'label': u'Comment', 'help': None, 'required': False, 'choices': [], 'type': u'textarea', 'name': u'comment' }, { 'label': u'Sample prep', 'help': u'The method used for preparing the sample', 'required': True, 'choices': ['microwave', 'mixer'], 'type': u'select', 'name': u'sample_prep' }, { 'label': u'Sequencer', 'help': u'Instrument where the sample will be sequenced', 'required': True, 'choices': ['iPhone', 'Android', 'Bang & Olufsen'], 'type': u'select', 'name': u'sequencer' }, { 'label': u'Sample type', 'help': u'The type of the sample', 'required': True, 'choices': ['DNA', 'RNA'], 'type': u'select', 'name': u'sample_type' }], 'presets': [{ 'variables': { 'sample_prep': 'microwave', 'sequencer': 'Android', 'sample_type': 'DNA' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'Android: DNA prepared with microwave' }, { 'variables': { 'sample_prep': 'mixer', 'sequencer': 'Android', 'sample_type': 'DNA' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'Android: DNA prepared with mixer' }, { 'variables': { 'sample_prep': 'microwave', 'sample_type': 'DNA', 'sequencer': 'iPhone' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'iPhone: DNA prepared with microwave' }, { 'variables': { 'sample_prep': 'microwave', 'sequencer': 'Android', 'sample_type': 'RNA' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'Android: RNA prepared with microwave' }, { 'variables': { 'sample_prep': 'microwave', 'sample_type': 'DNA', 'sequencer': 'Bang & Olufsen' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'Bang & Olufsen: DNA prepared with microwave' }, { 'variables': { 'sample_prep': 'mixer', 'sequencer': 'Android', 'sample_type': 'RNA' }, 'processDefinitionId': 'clims.plugins.demo.dnaseq.workflows.sequence.SequenceSimple', 'name': 'Android: RNA prepared with mixer' }] }
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 6738, 5254, 13, 565, 12078, 13, 27530, 13, 9288, 62, 7266, 301, 590, 1330, 50021, 14402, 20448, 198, 6738, 5424, 82, 13, 37390, 13, 9536, 78, 13, 32656, 589, 80, 13, 1818, 44...
2.111489
1,471
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_login import LoginManager from logging.handlers import SMTPHandler,RotatingFileHandler from flask_mail import Mail, Message import logging,os, smtplib from threading import Thread app = Flask(__name__) app.config.from_object(Config) db = SQLAlchemy(app) migrate = Migrate(app, db) mail = Mail(app) login = LoginManager(app) login.login_view = 'login' from app import routes, models, errors class ThreadedSMTPHandler(SMTPHandler): """ Mimic SMTPHandler from logging module but seperate the actual emission (.emit) in another thread to avoid blocking the main process """ if not app.debug: if app.config['MAIL_SERVER']: auth = None if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']: auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']) secure = None if app.config['MAIL_USE_TLS']: secure = () mail_handler = ThreadedSMTPHandler( mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']), # fromaddr='no-reply@' + app.config['MAIL_SERVER'], fromaddr=app.config['MAIL_USERNAME'], toaddrs=app.config['ADMINS'], subject='Tracker Failure', credentials=auth, secure=() ) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) if not os.path.exists('logs'): os.mkdir('logs') file_handler = RotatingFileHandler('logs/tracker.log', maxBytes=10240, backupCount=10) file_handler.setFormatter(logging.Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.setLevel(logging.INFO) app.logger.info(f'{app.__repr__} - startup')
[ 6738, 42903, 1330, 46947, 198, 6738, 4566, 1330, 17056, 198, 6738, 42903, 62, 25410, 282, 26599, 1330, 16363, 2348, 26599, 198, 6738, 42903, 62, 76, 42175, 1330, 337, 42175, 198, 6738, 42903, 62, 38235, 1330, 23093, 13511, 198, 6738, 1893...
2.341121
856
import re data = input() total_income = 0 while data != "end of shift": pattern_customer = r"\%(?P<customer>[A-Z][a-z]+)\%" customer = re.finditer(pattern_customer, data) is_customer = bool([c.group(0) for c in customer]) pattern_product = r"\<(?P<product>[0-9a-zA-Z\_]+)\>" product = re.finditer(pattern_product, data) is_product = bool([p.group(0) for p in product]) pattern_count = r"\|(?P<count>[0-9]+)\|" count = re.finditer(pattern_count, data) is_count = bool([cnt.group(0) for cnt in count]) pattern_price = r"(?P<price>[0-9]+\.?[0-9]+)\$" price = re.finditer(pattern_price, data) is_price = bool([pr.group(0) for pr in price]) if is_customer and is_product and is_count and is_price: customer_dict = {} for c in re.finditer(pattern_customer, data): customer_dict = c.groupdict() product_dict = {} for p in re.finditer(pattern_product, data): product_dict = p.groupdict() count_dict = {} for cnt in re.finditer(pattern_count, data): count_dict = cnt.groupdict() price_dict = {} for pr in re.finditer(pattern_price, data): price_dict = pr.groupdict() total_product_price = int(count_dict['count']) * float(price_dict['price']) total_income += total_product_price print(f"{customer_dict['customer']}: {product_dict['product']} - {total_product_price:.2f}") data = input() print(f"Total income: {total_income:.2f}")
[ 11748, 302, 198, 198, 7890, 796, 5128, 3419, 198, 23350, 62, 12519, 796, 657, 198, 198, 4514, 1366, 14512, 366, 437, 286, 6482, 1298, 198, 220, 220, 220, 3912, 62, 23144, 263, 796, 374, 1, 59, 4, 7, 30, 47, 27, 23144, 263, 36937, ...
2.298193
664
import cv2 as cv import numpy as np from matplotlib import pyplot as plt if __name__ == '__main__': drawShapes()
[ 11748, 269, 85, 17, 355, 269, 85, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 2603, 29487, 8019, 1330, 12972, 29487, 355, 458, 83, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 3197, ...
2.608696
46
import datetime import pytest from francis.util import ( parse_date, parse_rc, prettytable, ) # FIXME: test multiple > 40 columns
[ 11748, 4818, 8079, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 46754, 271, 13, 22602, 1330, 357, 198, 220, 220, 220, 21136, 62, 4475, 11, 198, 220, 220, 220, 21136, 62, 6015, 11, 198, 220, 220, 220, 2495, 11487, 11, 198, 8, 628, ...
2.666667
57
import math
[ 11748, 10688, 198 ]
4
3
__all__ = ['example_data']
[ 198, 834, 439, 834, 796, 37250, 20688, 62, 7890, 20520, 198 ]
2.545455
11
from xgboost.sklearn import XGBClassifier # from xgb_model import xgb_model_fit # from sklearn.grid_search import GridSearchCV from sklearn.ensemble import VotingClassifier from sklearn.metrics import accuracy_score import pandas as pd from sklearn.model_selection import train_test_split import numpy as np from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier print('\n\n') dtrain = pd.read_csv('../data/cleaned_train_v2.csv').iloc[:, 1:] dtest = pd.read_csv('../data/cleaned_test_v2.csv').iloc[:, 1:] # print(dtrain) loan_ids = dtest.Loan_ID dtest = dtest.iloc[:, 1:] features = np.array(dtrain.iloc[:, 0:-1]) labels = np.array(dtrain.Loan_Status) test = np.array(dtest) # print(features.shape) # Classifier 1 - XGBoost clf1 = XGBClassifier(learning_rate=0.1, n_estimators=1000, max_depth=3, min_child_weight=1, gamma=0.2, subsample=0.8, colsample_bytree=0.8, objective='binary:logistic', nthread=4, scale_pos_weight=1, reg_alpha=69, seed=42) # Classifier 2 - Random Forest clf2 = RandomForestClassifier(bootstrap=True, criterion='gini', max_depth=3, oob_score=True, max_features=3, min_samples_leaf=10, min_samples_split=10, random_state=42, n_jobs=-1) # X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.40, random_state=42) tree = DecisionTreeClassifier(criterion='gini', max_depth=3) clf3 = AdaBoostClassifier(base_estimator=tree, n_estimators=3000, learning_rate=0.03, random_state=42) eclf = VotingClassifier(estimators=[ ('forest', clf2), ('xgboost', clf1), ('adaboost', clf3)], voting='hard') eclf.fit(features, labels) pred = eclf.predict(test) # print(accuracy_score(y_test, pred)) # print("Random Forest Classifier.....") # clf2.fit(X_train, y_train) # pred1 = clf2.predict(X_test) # print(accuracy_score(y_test, pred1)) # print('\nXGBoost Classifier......') # clf1.fit(X_train, y_train) # pred2 = clf1.predict(X_test) # print(accuracy_score(y_test, pred2)) # clf1.fit(features, labels, eval_metric='error') # pred = clf1.predict(test) # print(pred) submission = pd.DataFrame({'Loan_ID': loan_ids, 'Loan_Status': pred}) submission['Loan_Status'] = submission.Loan_Status.map({0: 'N', 1: 'Y'}) submission.to_csv('submission2.csv', index=False) # xgb_model_fit(clf1, features, labels, folds=3) # Classifier 2 - Random Forest # Tuning ```max_depth``` and ```min_child_weight``` # param_dist = { # "max_depth": list(range(1, 8, 2)), # "max_features": list(range(1, 10, 2)), # "min_samples_split": list(range(2, 11, 2)), # "min_samples_leaf": list(range(2, 11, 2)), # "bootstrap": [True, False], # "criterion": ["gini", "entropy"] # } # gs1 = GridSearchCV(estimator=clf2, # param_grid=param_dist, # scoring='accuracy', # n_jobs=-1, # iid=False, # cv=7, # verbose=5) # gs1.fit(features, labels) # # bootstrap=True, criterion=gini, max_depth=3, max_features=3, min_samples_leaf=10, min_samples_split=10, score=0.870588 # # # print(gs1.grid_scores_) # print(gs1.best_params_) # print(gs1.best_score_)
[ 6738, 2124, 70, 39521, 13, 8135, 35720, 1330, 1395, 4579, 9487, 7483, 198, 2, 422, 2124, 22296, 62, 19849, 1330, 2124, 22296, 62, 19849, 62, 11147, 198, 2, 422, 1341, 35720, 13, 25928, 62, 12947, 1330, 24846, 18243, 33538, 198, 6738, ...
2.397207
1,289
from utils import nwise import pkg_resources import re, time, os import itertools import argparse import numpy import json DELIM = u"│" # delim used by onmt def split_infobox(dataset_folder, destination_folder): """ extract box content, field type and position information from infoboxes from original_data *.box.val is the box content (token) *.box.lab is the field type for each token *.box.pos is the position counted from the begining of a field """ bwfile = [os.path.join(destination_folder, 'processed_data', setname, f"{setname}.box.val") for setname in ['train', 'valid', 'test']] bffile = [os.path.join(destination_folder, 'processed_data', setname, f"{setname}.box.lab") for setname in ['train', 'valid', 'test']] bpfile = [os.path.join(destination_folder, 'processed_data', setname, f"{setname}.box.pos") for setname in ['train', 'valid', 'test']] mixb_word, mixb_label, mixb_pos = [], [], [] for setname in ['train', 'valid', 'test']: fboxes = os.path.join(dataset_folder, 'raw', setname, f"{setname}.box") with open(fboxes, mode="r", encoding="utf8") as f: box = [line.strip() for line in f if line.strip()] box_word, box_label, box_pos = [], [], [] for ib in box: item = ib.split('\t') box_single_word, box_single_label, box_single_pos = [], [], [] for it in item: if len(it.split(':')) > 2: continue # print it prefix, word = it.split(':') if '<none>' in word or word.strip() == '' or prefix.strip() == '': continue new_label = re.sub("_[1-9]\d*$", "", prefix) if new_label.strip() == "": continue box_single_word.append(word) box_single_label.append(new_label) if re.search("_[1-9]\d*$", prefix): field_id = int(prefix.split('_')[-1]) box_single_pos.append(field_id if field_id <= 30 else 30) else: box_single_pos.append(1) box_word.append(box_single_word) box_label.append(box_single_label) box_pos.append(box_single_pos) mixb_word.append(box_word) mixb_label.append(box_label) mixb_pos.append(box_pos) print(f'{setname} done') for k, m in enumerate(mixb_word): with open(bwfile[k], "w+") as h: for items in m: for sens in items: h.write(str(sens) + " ") h.write('\n') for k, m in enumerate(mixb_label): with open(bffile[k], "w+") as h: for items in m: for sens in items: h.write(str(sens) + " ") h.write('\n') for k, m in enumerate(mixb_pos): with open(bpfile[k], "w+") as h: for items in m: for sens in items: h.write(str(sens) + " ") h.write('\n') def create_tables(folder): """Here we create the tables.jl files used in PARENT metric We could optimize the code so that step is done in create_input but it's easier and more convienient to just add it there. """ for setname in ['train', 'valid', 'test']: input_filename = os.path.join(folder, 'full', f"{setname}_input.txt") with open(input_filename, mode="r", encoding="utf8") as f: # each line is a table. Each token is a value in the table. # We take the value/label of the token and discard the pos # given that they are written in the right order allvals = list() alllabs = list() for line in f: vals = list() labs = list() for token in line.strip().split(): val, lab, _, __ = token.split(DELIM) vals.append(val) labs.append(lab) allvals.append(vals) alllabs.append(labs) tables = list() for idx, (vals, labs) in enumerate(zip(allvals, alllabs)): table = list() for key, group in itertools.groupby(labs): size = len([_ for _ in group]) vvals, vals = vals[:size], vals[size:] table.append((key, vvals)) assert len(vals) == 0 # we exhausted all tokens tables.append(table) output_filename = os.path.join(folder, 'full', f"{setname}_tables.jl") with open(output_filename, mode="w", encoding="utf8") as f: for table in tables: f.write(json.dumps(table) + '\n') def preprocess(dataset_folder, destination_folder, args): """ We use a triple <f, p+, p-> to represent the field information of a token in the specific field. p+&p- are the position of the token in that field counted from the begining and the end of the field. For example, for a field (birthname, Jurgis Mikelatitis) in an infobox, we represent the field as (Jurgis, <birthname, 1, 2>) & (Mikelatitis, <birthname, 2, 1>) """ print("extracting token, field type and position info from original data ...") time_start = time.time() split_infobox(dataset_folder, destination_folder) reverse_pos(destination_folder) duration = time.time() - time_start print(f"extract finished in {duration:.3f} seconds") print("merging everything into single input file ...") time_start = time.time() create_input(destination_folder) duration = time.time() - time_start print(f"merge finished in {duration:.3f} seconds") print("extracting first sentences from original data ...") time_start = time.time() extract_sentences(dataset_folder, destination_folder, args.first_sentence) duration = time.time() - time_start print(f"extract finished in {duration:.3f} seconds") print("formatting input in human readable format ...") time_start = time.time() create_tables(destination_folder) duration = time.time() - time_start print(f"formatting finished in {duration:.3f} seconds") if __name__ == '__main__': dataset_folder = pkg_resources.resource_filename(__name__, 'wikibio') parser = argparse.ArgumentParser() group = parser.add_argument_group('Destination path') group.add_argument('--dest', '-d', dest='dest', default=dataset_folder, help='Folder where to store the resulting files') parser.add_argument('--first_sentence', action='store_true', help="Activate to keep only the first sentence") main(parser.parse_args())
[ 6738, 3384, 4487, 1330, 299, 3083, 198, 198, 11748, 279, 10025, 62, 37540, 198, 11748, 302, 11, 640, 11, 28686, 198, 11748, 340, 861, 10141, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 198, 11748, 33918, 198, 198, 35, 3698, 3955, ...
2.170321
3,147
#!/usr/bin/env python # -*- coding: utf8 -*- # My imports from __future__ import division import numpy as np import pandas as pd import argparse from utils import _update_par as updateBatch from utils import _run_moog as runMoog from utils import Readmoog from interpolation import interpolator import os def solar_abundance(atom): '''Give atomic number and return solar abundance from Asplund et al. 2009 Input ----- atom : int The atomic number Output ------ abundance : float The solar abundance of the atom ''' if not isinstance(atom, int): raise ValueError('Atomic number need to be an integer') solar = [12.00, 10.93, 1.05, 1.38, 2.70, 8.43, 7.83, 8.69, 4.56, 7.93, 6.24, 7.60, 6.45, 7.51, 5.41, 7.12, 5.50, 6.40, 5.03, 6.34, 3.15, 4.95, 3.93, 5.64, 5.43, 7.47, 4.99, 6.22, 4.19, 4.56, 3.04, 3.65, 2.30, 3.34, 2.54, 3.25, 2.52, 2.87, 2.21, 2.58, 1.46, 1.88, -5.00, 1.75, 0.91, 1.57, 0.94, 1.71, 0.80, 2.04, 1.01, 2.18, 1.55, 2.24, 1.08, 2.18, 1.10, 1.58, 0.72, 1.42, -5.00, 0.96, 0.52, 1.07, 0.30, 1.10, 0.48, 0.92, 0.10, 0.84, 0.10, 0.85, -0.12, 0.85, 0.26, 1.40, 1.38, 1.62, 0.92, 1.17, 0.90, 1.75, 0.65, -5.00, -5.00, -5.00, -5.00, -5.00, -5.00, 0.02, -5.00, -0.54, -5.00, -5.00, -5.00] return solar[atom-1] def recalSingleLine(line, params=None, version=2014, maxiter=40, driver='abfind'): '''Recalibrate a single line and return the new loggf Inputs ------ line : list The line containing (wavelength, element, EP, loggf, EW) in that order params : list/tuple The parameters (Teff, logg, [Fe/H], vt) version : int The version of MOOG driver : str The MOOG driver to use (abfind or ewfind) Output ------ loggf : float The new recalibrated loggf ''' ewdriver = True if driver == 'ewfind' else False fmt = ('%9.3f', '%10.1f', '%9.2f', '%9.3f', '%28.1f') header = 'Wavelength ele EP loggf EW' np.savetxt('temporary.moog', line[:, np.newaxis].T, fmt=fmt, header=header) loggf_old = line[3] a, b = loggf_old-5, loggf_old+5 # extreme values of loggf c = (a+b)/2 for _ in range(maxiter): if c == 0: # Don't evaluate at loggf = 0 c += (abs(a) + abs(b)) / 10 fa = moogAbund(a, ewdriver=ewdriver) fc = moogAbund(c, ewdriver=ewdriver) if fc == 0: return c elif fa*fc < 0: b = c else: a = c c = (a+b)/2 return c if __name__ == '__main__': # pragma: no cover args = _parser() fname = args.input fout1 = 'rawLinelist/%s' % args.output fout2 = 'linelist/%s' % args.output.replace('.ares', '.moog') lines = pd.read_csv(fname, skiprows=2, delimiter=r'\s+', names=['WL', 'num', 'EP', 'loggf', 'ele', 'EW']) if args.parameters is None: params = [5777, 4.44, 0.00, 1.00] else: params = map(float, args.parameters) params[0] = int(params[0]) interpolator(params=params, atmtype=args.model, save=True) cols = ['WL', 'num', 'EP', 'loggf', 'EW'] fmt2 = ('%9.3f', '%10.1f', '%9.2f', '%9.3f', '%28.1f') header1 = 'WL num E.P. loggf ele EWsun\n' header1 += '------- ---- ---- ------ ---- -----' header2 = 'Wavelength ele EP loggf EW' x = lines[cols].values[0][:, np.newaxis].T np.savetxt('temporary.moog', x, fmt=fmt2, header=header2) options = {'driver': args.driver, 'damping': args.damping} updateBatch(line_list='temporary.moog', **options) newloggf = np.zeros(lines.shape[0]) for i, line in enumerate(lines[cols].values): print 'Wavelength: %.3f' % line[0] print 'Old loggf: %.3f' % line[3] zz = recalSingleLine(line, params=params, version=args.moogversion, driver=args.driver) zz = np.log10(zz) if zz > 0 else zz newloggf[i] = zz print 'New loggf: %.3f\n' % newloggf[i] lines['newloggf'] = pd.Series(newloggf) X = lines[['WL', 'num', 'EP', 'newloggf', 'ele', 'EW']] fmt1 = ('%7.2f', '%7.1f', '%9.2f', '%10.3f', '%10s', '%9.1f') print 'Saving results to: %s' % fout1 np.savetxt(fout1, X, fmt=fmt1, header=header1, comments='') X = lines[['WL', 'num', 'EP', 'newloggf', 'EW']] print 'Saving results to: %s' % fout2 np.savetxt(fout2, X, fmt=fmt2, header=header2) os.remove('temporary.moog')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 23, 532, 9, 12, 198, 198, 2, 2011, 17944, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, ...
1.938887
2,389
# Copyright 2019 TerraPower, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Generator, Tuple from armi.settings import caseSettings from armi.reactor import systemLayoutInput class Database: """Abstract class defining the common interface for all Database implementations. Notes ----- This is a pretty anemic set of interfaces, since the different implementations can vary wildly. For now these are the bare minimum interfaces that should be needed to convert one Database format to another, and serve as a common ancestor.""" # Cannot annotate type, because cannot import blueprints, because blueprints cannot # be imported until after plugins are registered, and this module gets imported by # plugins as they are being registered. def genTimeSteps(self) -> Generator[Tuple[int, int], None, None]: """Get a sequence of tuples (cycle, node) that are contained in the database.""" raise NotImplementedError() def genAuxiliaryData(self, ts: Tuple[int, int]) -> Generator[str, None, None]: """ Get a sequence of auxiliary dataset/group names for the passed time step. Returns ------- Generator[str] A generator that produces **absolute** paths to the auxiliary data. Absolute names make it easier for a database version-agnostic converter to find the actual data. """ raise NotImplementedError() def getAuxiliaryDataPath(self, ts: Tuple[int, int], name: str) -> str: """ Get a string describing a path to an auxiliary data location. Parameters ---------- ts The time step that the auxiliary data belongs to name The name of the auxiliary data Returns ------- str An absolute location for storing auxiliary data with the given name for the given time step """ raise NotImplementedError()
[ 2, 15069, 13130, 24118, 13434, 11, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 9...
3.142678
799
import argparse from os import makedirs from os.path import abspath, exists, join, dirname, expanduser import re import subprocess import time import json import threading import socket import sys CONFIG_JSON = """ { "version": 2, "controller": {}, "workers": [ { "transports": [ { "paths": { "ws": { "type": "websocket" }, "/": { "directory": ".", "type": "static" }, "proto": { "directory": ".", "type": "static" } }, "endpoint": { "type": "tcp", "port": 8181, "tls": { "key": "server.key", "certificate": "server.crt" } }, "type": "web" } ], "type": "router", "options": { "pythonpath": [""] }, "realms": [ { "name": "realm1", "roles": [ { "name": "anonymous", "permissions": [ { "uri": "", "match": "prefix", "allow": { "call": true, "register": true, "publish": true, "subscribe": true }, "disclose": { "caller": false, "publisher": false }, "cache": true } ] } ] } ] } ] } """ if __name__ == '__main__': main_entry()
[ 11748, 1822, 29572, 198, 6738, 28686, 1330, 285, 4335, 17062, 198, 6738, 28686, 13, 6978, 1330, 2352, 6978, 11, 7160, 11, 4654, 11, 26672, 3672, 11, 4292, 7220, 198, 11748, 302, 198, 11748, 850, 14681, 198, 11748, 640, 198, 11748, 33918...
1.565299
1,072
import bisect
[ 11748, 47457, 478, 201 ]
3.5
4
import sys shuffle()
[ 11748, 25064, 628, 628, 198, 1477, 18137, 3419, 198 ]
2.777778
9
import json import time import urllib import boto3 import traceback from lab_config import boto_args from boto3.dynamodb.types import TypeDeserializer
[ 11748, 33918, 198, 11748, 640, 198, 11748, 2956, 297, 571, 198, 11748, 275, 2069, 18, 198, 11748, 12854, 1891, 198, 6738, 2248, 62, 11250, 1330, 275, 2069, 62, 22046, 198, 6738, 275, 2069, 18, 13, 67, 4989, 375, 65, 13, 19199, 1330, ...
3.212766
47
# Copyright 2016 SAP SE # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections import signal import time import eventlet eventlet.monkey_patch() from oslo_config import cfg from oslo_log import log as logging from neutron.i18n import _LI, _LW import oslo_messaging from oslo_service import loopingcall from neutron.agent.common import polling from neutron.common import config from neutron.agent import rpc as agent_rpc from neutron.common import constants as n_const from neutron.common import rpc as n_rpc from neutron.common import topics from neutron import context from neutron.i18n import _LE from neutron.db import db_base_plugin_v2 as db_base from neutron.plugins.ml2 import db as db_ml2 from networking_f5_ml2.plugins.ml2.drivers.mech_f5 import constants as f5_constants from oslo_utils import importutils LOG = logging.getLogger(__name__) cfg.CONF.import_group('ml2_f5', 'networking_f5_ml2.plugins.ml2.drivers.mech_f5.config')
[ 2, 15069, 1584, 48323, 7946, 198, 2, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 4...
3.143443
488
import tensorflow as tf import numpy as np tf.set_random_seed(5) n_inputs = 28 n_neurons = 150 n_layers = 3 n_steps = 28 n_outputs = 10 learning_rate = 0.001 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/") X_test = mnist.test.images.reshape((-1, n_steps, n_inputs)) y_test = mnist.test.labels X = tf.placeholder(tf.float32, [None, n_steps, n_inputs]) y = tf.placeholder(tf.int32, [None]) multi_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(num_units=n_neurons) for _ in range(3)]) outputs, states = tf.nn.dynamic_rnn(multi_cell, X, dtype=tf.float32) top_layer_h_state = states[-1][1] logits = tf.layers.dense(top_layer_h_state, n_outputs, name='softmax') x_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits) loss = tf.reduce_mean(x_entropy, name='loss') optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) correct = tf.nn.in_top_k(logits, y, 1) accuracy = tf.reduce_mean(tf.cast(correct, tf.float32)) init = tf.global_variables_initializer() states top_layer_h_state n_epochs = 25 batch_size = 150 with tf.Session() as sess: init.run() for epoch in range(n_epochs): for k in range(mnist.train.num_examples // batch_size): X_batch, y_batch = mnist.train.next_batch(batch_size) X_batch = X_batch.reshape((batch_size, n_steps, n_inputs)) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) acc_train = accuracy.eval(feed_dict={X: X_batch, y: y_batch}) acc_test = accuracy.eval(feed_dict={X: X_test, y: y_test}) print("Epoch", epoch, 'Train acc: ', acc_train, "Test acc: ", acc_test)
[ 11748, 11192, 273, 11125, 355, 48700, 198, 11748, 299, 32152, 355, 45941, 198, 198, 27110, 13, 2617, 62, 25120, 62, 28826, 7, 20, 8, 198, 198, 77, 62, 15414, 82, 796, 2579, 198, 77, 62, 710, 333, 684, 796, 6640, 198, 77, 62, 75, ...
2.287979
757
from os import path import logging from typing import Dict, List, Optional import copy import torch import torch.nn.functional as F from overrides import overrides from allennlp.data import Vocabulary from allennlp.common.params import Params from allennlp.models.model import Model from allennlp.modules import Seq2SeqEncoder, TextFieldEmbedder, FeedForward from allennlp.modules.span_extractors import SelfAttentiveSpanExtractor, EndpointSpanExtractor from allennlp.nn import util, InitializerApplicator, RegularizerApplicator # Import submodules. from dygie.models.coref import CorefResolver from dygie.models.ner import NERTagger from dygie.models.relation import RelationExtractor from dygie.models.events import EventExtractor from dygie.training.joint_metrics import JointMetrics logger = logging.getLogger(__name__) # pylint: disable=invalid-name @Model.register("dygie") class DyGIE(Model): """ TODO(dwadden) document me. Parameters ---------- vocab : ``Vocabulary`` text_field_embedder : ``TextFieldEmbedder`` Used to embed the ``text`` ``TextField`` we get as input to the model. context_layer : ``Seq2SeqEncoder`` This layer incorporates contextual information for each word in the document. feature_size: ``int`` The embedding size for all the embedded features, such as distances or span widths. submodule_params: ``TODO(dwadden)`` A nested dictionary specifying parameters to be passed on to initialize submodules. max_span_width: ``int`` The maximum width of candidate spans. lexical_dropout: ``int`` The probability of dropping out dimensions of the embedded text. initializer : ``InitializerApplicator``, optional (default=``InitializerApplicator()``) Used to initialize the model parameters. regularizer : ``RegularizerApplicator``, optional (default=``None``) If provided, will be used to calculate the regularization penalty during training. display_metrics: ``List[str]``. A list of the metrics that should be printed out during model training. """ @overrides def forward(self, text, spans, ner_labels, coref_labels, relation_labels, trigger_labels, argument_labels, metadata): """ TODO(dwadden) change this. """ # For co-training on Ontonotes, need to change the loss weights depending on the data coming # in. This is a hack but it will do for now. if self._co_train: if self.training: dataset = [entry["dataset"] for entry in metadata] assert len(set(dataset)) == 1 dataset = dataset[0] assert dataset in ["ace", "ontonotes"] if dataset == "ontonotes": self._loss_weights = dict(coref=1, ner=0, relation=0, events=0) else: self._loss_weights = self._permanent_loss_weights # This assumes that there won't be any co-training data in the dev and test sets, and that # coref propagation will still happen even when the coref weight is set to 0. else: self._loss_weights = self._permanent_loss_weights # In AllenNLP, AdjacencyFields are passed in as floats. This fixes it. relation_labels = relation_labels.long() argument_labels = argument_labels.long() # If we're doing Bert, get the sentence class token as part of the text embedding. This will # break if we use Bert together with other embeddings, but that won't happen much. if "bert-offsets" in text: offsets = text["bert-offsets"] sent_ix = torch.zeros(offsets.size(0), device=offsets.device, dtype=torch.long).unsqueeze(1) padded_offsets = torch.cat([sent_ix, offsets], dim=1) text["bert-offsets"] = padded_offsets padded_embeddings = self._text_field_embedder(text) cls_embeddings = padded_embeddings[:, 0, :] text_embeddings = padded_embeddings[:, 1:, :] else: text_embeddings = self._text_field_embedder(text) cls_embeddings = torch.zeros([text_embeddings.size(0), text_embeddings.size(2)], device=text_embeddings.device) text_embeddings = self._lexical_dropout(text_embeddings) # Shape: (batch_size, max_sentence_length) text_mask = util.get_text_field_mask(text).float() sentence_group_lengths = text_mask.sum(dim=1).long() sentence_lengths = 0*text_mask.sum(dim=1).long() for i in range(len(metadata)): sentence_lengths[i] = metadata[i]["end_ix"] - metadata[i]["start_ix"] for k in range(sentence_lengths[i], sentence_group_lengths[i]): text_mask[i][k] = 0 max_sentence_length = sentence_lengths.max().item() # TODO(Ulme) Speed this up by tensorizing new_text_embeddings = torch.zeros([text_embeddings.shape[0], max_sentence_length, text_embeddings.shape[2]], device=text_embeddings.device) for i in range(len(new_text_embeddings)): new_text_embeddings[i][0:metadata[i]["end_ix"] - metadata[i]["start_ix"]] = text_embeddings[i][metadata[i]["start_ix"]:metadata[i]["end_ix"]] #max_sent_len = max(sentence_lengths) #the_list = [list(k+metadata[i]["start_ix"] if k < max_sent_len else 0 for k in range(text_embeddings.shape[1])) for i in range(len(metadata))] #import ipdb; ipdb.set_trace() #text_embeddings = torch.gather(text_embeddings, 1, torch.tensor(the_list, device=text_embeddings.device).unsqueeze(2).repeat(1, 1, text_embeddings.shape[2])) text_embeddings = new_text_embeddings # Only keep the text embeddings that correspond to actual tokens. # text_embeddings = text_embeddings[:, :max_sentence_length, :].contiguous() text_mask = text_mask[:, :max_sentence_length].contiguous() # Shape: (batch_size, max_sentence_length, encoding_dim) contextualized_embeddings = self._lstm_dropout(self._context_layer(text_embeddings, text_mask)) assert spans.max() < contextualized_embeddings.shape[1] if self._attentive_span_extractor is not None: # Shape: (batch_size, num_spans, emebedding_size) attended_span_embeddings = self._attentive_span_extractor(text_embeddings, spans) # Shape: (batch_size, num_spans) span_mask = (spans[:, :, 0] >= 0).float() # SpanFields return -1 when they are used as padding. As we do # some comparisons based on span widths when we attend over the # span representations that we generate from these indices, we # need them to be <= 0. This is only relevant in edge cases where # the number of spans we consider after the pruning stage is >= the # total number of spans, because in this case, it is possible we might # consider a masked span. # Shape: (batch_size, num_spans, 2) spans = F.relu(spans.float()).long() # Shape: (batch_size, num_spans, 2 * encoding_dim + feature_size) endpoint_span_embeddings = self._endpoint_span_extractor(contextualized_embeddings, spans) if self._attentive_span_extractor is not None: # Shape: (batch_size, num_spans, emebedding_size + 2 * encoding_dim + feature_size) span_embeddings = torch.cat([endpoint_span_embeddings, attended_span_embeddings], -1) else: span_embeddings = endpoint_span_embeddings # TODO(Ulme) try normalizing span embeddeings #span_embeddings = span_embeddings.abs().sum(dim=-1).unsqueeze(-1) # Make calls out to the modules to get results. output_coref = {'loss': 0} output_ner = {'loss': 0} output_relation = {'loss': 0} output_events = {'loss': 0} # Prune and compute span representations for coreference module if self._loss_weights["coref"] > 0 or self._coref.coref_prop > 0: output_coref, coref_indices = self._coref.compute_representations( spans, span_mask, span_embeddings, sentence_lengths, coref_labels, metadata) # Prune and compute span representations for relation module if self._loss_weights["relation"] > 0 or self._relation.rel_prop > 0: output_relation = self._relation.compute_representations( spans, span_mask, span_embeddings, sentence_lengths, relation_labels, metadata) # Propagation of global information to enhance the span embeddings if self._coref.coref_prop > 0: # TODO(Ulme) Implement Coref Propagation output_coref = self._coref.coref_propagation(output_coref) span_embeddings = self._coref.update_spans(output_coref, span_embeddings, coref_indices) if self._relation.rel_prop > 0: output_relation = self._relation.relation_propagation(output_relation) span_embeddings = self.update_span_embeddings(span_embeddings, span_mask, output_relation["top_span_embeddings"], output_relation["top_span_mask"], output_relation["top_span_indices"]) # Make predictions and compute losses for each module if self._loss_weights['ner'] > 0: output_ner = self._ner( spans, span_mask, span_embeddings, sentence_lengths, ner_labels, metadata) if self._loss_weights['coref'] > 0: try : output_coref = self._coref.predict_labels(output_coref, metadata) except : output_coref = {} if self._loss_weights['relation'] > 0: output_relation = self._relation.predict_labels(relation_labels, output_relation, metadata) if self._loss_weights['events'] > 0: # Make the trigger embeddings the same size as the argument embeddings to make # propagation easier. if self._events._span_prop._n_span_prop > 0: trigger_embeddings = contextualized_embeddings.repeat(1, 1, 2) trigger_widths = torch.zeros([trigger_embeddings.size(0), trigger_embeddings.size(1)], device=trigger_embeddings.device, dtype=torch.long) trigger_width_embs = self._endpoint_span_extractor._span_width_embedding(trigger_widths) trigger_width_embs = trigger_width_embs.detach() trigger_embeddings = torch.cat([trigger_embeddings, trigger_width_embs], dim=-1) else: trigger_embeddings = contextualized_embeddings output_events = self._events( text_mask, trigger_embeddings, spans, span_mask, span_embeddings, cls_embeddings, sentence_lengths, output_ner, trigger_labels, argument_labels, ner_labels, metadata) if "loss" not in output_coref: output_coref["loss"] = 0 if "loss" not in output_relation: output_relation["loss"] = 0 # TODO(dwadden) just did this part. loss = (self._loss_weights['coref'] * output_coref['loss'] + self._loss_weights['ner'] * output_ner['loss'] + self._loss_weights['relation'] * output_relation['loss'] + self._loss_weights['events'] * output_events['loss']) output_dict = dict(coref=output_coref, relation=output_relation, ner=output_ner, events=output_events) output_dict['loss'] = loss # Check to see if event predictions are globally compatible (argument labels are compatible # with NER tags and trigger tags). # if self._loss_weights["ner"] > 0 and self._loss_weights["events"] > 0: # decoded_ner = self._ner.decode(output_dict["ner"]) # decoded_events = self._events.decode(output_dict["events"]) # self._joint_metrics(decoded_ner, decoded_events) return output_dict @overrides def decode(self, output_dict: Dict[str, torch.Tensor]): """ Converts the list of spans and predicted antecedent indices into clusters of spans for each element in the batch. Parameters ---------- output_dict : ``Dict[str, torch.Tensor]``, required. The result of calling :func:`forward` on an instance or batch of instances. Returns ------- The same output dictionary, but with an additional ``clusters`` key: clusters : ``List[List[List[Tuple[int, int]]]]`` A nested list, representing, for each instance in the batch, the list of clusters, which are in turn comprised of a list of (start, end) inclusive spans into the original document. """ # TODO(dwadden) which things are already decoded? res = {} if self._loss_weights["coref"] > 0: try : res["coref"] = self._coref.decode(output_dict["coref"]) except : pass if self._loss_weights["ner"] > 0: res["ner"] = self._ner.decode(output_dict["ner"]) if self._loss_weights["relation"] > 0: res["relation"] = self._relation.decode(output_dict["relation"]) if self._loss_weights["events"] > 0: res["events"] = output_dict["events"] return res def get_metrics(self, reset: bool = False) -> Dict[str, float]: """ Get all metrics from all modules. For the ones that shouldn't be displayed, prefix their keys with an underscore. """ metrics_coref = self._coref.get_metrics(reset=reset) metrics_ner = self._ner.get_metrics(reset=reset) metrics_relation = self._relation.get_metrics(reset=reset) metrics_events = self._events.get_metrics(reset=reset) if self._loss_weights["ner"] > 0 and self._loss_weights["events"] > 0: metrics_joint = self._joint_metrics.get_metric(reset=reset) else: metrics_joint = {} # Make sure that there aren't any conflicting names. metric_names = (list(metrics_coref.keys()) + list(metrics_ner.keys()) + list(metrics_relation.keys()) + list(metrics_events.keys())) assert len(set(metric_names)) == len(metric_names) all_metrics = dict(list(metrics_coref.items()) + list(metrics_ner.items()) + list(metrics_relation.items()) + list(metrics_events.items()) + list(metrics_joint.items())) # If no list of desired metrics given, display them all. if self._display_metrics is None: return all_metrics # Otherwise only display the selected ones. res = {} for k, v in all_metrics.items(): if k in self._display_metrics: res[k] = v else: new_k = "_" + k res[new_k] = v return res
[ 6738, 28686, 1330, 3108, 198, 11748, 18931, 198, 6738, 19720, 1330, 360, 713, 11, 7343, 11, 32233, 198, 11748, 4866, 198, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 13, 45124, 355, 376, 198, 6738, 23170, 1460, 1330, 23170, 1460, 1...
2.324863
6,572
"""Utility functions.""" import enum import json import struct import subprocess import time import numpy as np # Measurements contain 5 floats (elapsed_time, basket_resistance, # group_resistance, basket_temperature, and group_temperature) and an int # (state, for which 0, 1, 2, and 3 map to START, RUNNING, STOP, and STOPPED, # respectively). FORMAT_STRING = 'fffffi' def compile_and_upload(fqbn, port): """Compiles the Arduino sketch and uploads it to the device. Args: fbqn: str, fully qualified board name. port: str, upload port. """ subprocess.run(['arduino-cli', 'compile', '--fqbn', fqbn, 'espresso-shot']) subprocess.run(['arduino-cli', 'upload', '-p', port, '--fqbn', fqbn, 'espresso-shot']) def find_port_if_not_specified(fqbn, port): """Finds an upload port if it's left unspecified. If `port` is None, then uses `arduino-cli board list` to find all boards connected to the computer with the specified fully qualified board name and sets `port` to that of the first board found. Args: fbqn: str, fully qualified board name. port: str or None, upload port. Returns: port: str, the upload port. Raises: RuntimeError, if `port` is None and no board with the specified fully qualified board name is connected to the computer. """ process = subprocess.Popen( ['arduino-cli', 'board', 'list', '--format', 'json'], stdout=subprocess.PIPE) devices = json.loads(process.communicate()[0].decode('utf-8')) for device in devices: if 'boards' in device and any(board['FQBN'] == fqbn for board in device['boards']): port = port or device['address'] break if port is None: raise RuntimeError('no port specified and no board with the specified ' 'FQBN was found.') return port def read_measurement(serial_port): """Reads a measurement from the serial port. Args: serial_port: Serial, serial port to read from. Returns: tuple of (float, float, float, float, float, int) of form (elapsed_time, basket_resistance, group_resistance, basket_temperature, group_temperature, state). """ return struct.unpack( FORMAT_STRING, serial_port.read(struct.calcsize(FORMAT_STRING))) class MockSerial: """Mock serial port used to test the interface when no device is available. We simulate alternating between pulling a shot for 30 seconds and letting the machine idle for 30 seconds, but we have time run twice as fast for convenience. """
[ 37811, 18274, 879, 5499, 526, 15931, 198, 11748, 33829, 198, 11748, 33918, 198, 11748, 2878, 198, 11748, 850, 14681, 198, 11748, 640, 198, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 24291, 902, 3994, 642, 36016, 357, 417, 28361, 6...
2.862416
894
from setuptools import setup, find_packages setup( name="gitcv", version="0.1", packages=find_packages(), author="Jan Groth", license="MIT License", setup_requires=['pytest-runner'], tests_require=['pytest'] )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 198, 198, 40406, 7, 198, 220, 220, 220, 1438, 2625, 18300, 33967, 1600, 198, 220, 220, 220, 2196, 2625, 15, 13, 16, 1600, 198, 220, 220, 220, 10392, 28, 19796, 62, 43789, 227...
2.597826
92
#!/usr/bin/env python # coding: utf-8 # http://paulbourke.net/fractals/clifford/?curius=373 # In[13]: import numpy as np import math as m import matplotlib.pyplot as plt # In[65]: a = -1.5 b = 1.6 c = 1.2 d = 0.7 # In[66]: # In[ ]: # In[77]: sidelength = 8192 center = (sidelength // 2 , sidelength // 2) grid = np.zeros((sidelength,sidelength)) x,y = 0,0 for i in range(30000000): x,y = update(x,y) posx = int(x * sidelength / 5) + center[0] posy = int(y * sidelength / 4) + center[1] if posx < sidelength and posx >= 0 and posy < sidelength and posy >= 0: grid[posx][posy] += 2 else: print(posx, posy) # print(x,y) # In[74]: max(grid.flatten()), max(np.log(grid.flatten() + 1)) # In[88]: lovely_cmaps = ["YlGn","rainbow", "gnuplot2"] for cmap in lovely_cmaps: plt.figure(figsize=(20,20)) plt.imshow(np.log(grid + 1), cmap=cmap) plt.tick_params( axis='both', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=False, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=False, labelleft=False, left=False, right=False) # labels along the bottom edge are off plt.axis("off") plt.savefig("convergence_orbweaver_{}.png".format(cmap)) print("convergence_orbweaver_{}.png".format(cmap)) plt.show() # In[ ]:
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 2638, 1378, 79, 2518, 6084, 365, 13, 3262, 14, 69, 974, 874, 14, 565, 733, 585, 20924, 22019, 3754, 28, 34770, 220, 198, 198, 2, 554,...
2.169591
684
# -*- coding: utf-8 -*- import discord from discord import Embed from discord.ext import tasks from datetime import datetime import os import requests import random import json TOKEN = os.environ["TOKEN"] client = discord.Client(intents=discord.Intents.all()) # 次回送信予定時刻を06:00-8:30までの間でランダムに設定 time_set = setting_time_set() # 起動時に初回の次回送信時刻を設定 tem_set = set_tem() # Embedの関数 @client.event @client.event @tasks.loop(seconds=60) loop.start() client.run(TOKEN)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 11748, 36446, 201, 198, 6738, 36446, 1330, 13302, 276, 201, 198, 6738, 36446, 13, 2302, 1330, 8861, 201, 198, 6738, 4818, 8079, 1330, 4818, 8079, 201, 198, 11748, 2...
1.882784
273
import os import sys import torch from config import Config from train3 import image_size from model import SiameseNetwork from evaluate3 import TestDataset from torch.utils.data import DataLoader use_gpu = False register_dir = "./data/ct0202a/" threshold = 50 siam_model = None log_lines = [] ## if __name__ == '__main__': register_dir = Config.register_dir dog_id = None dog_img = None exam_dir = None model_path = "./trained/DogSiamese-2.pkl" for a in sys.argv[1:]: if a.lower() == 'gpu': use_gpu = True else: aa = a.split("=") if "dog" == aa[0]: dog_id = aa[1] elif "img" == aa[0]: dog_img = aa[1] elif "exam_dir" == aa[0]: exam_dir = aa[1] elif "model" == aa[0]: model_path = aa[1] else: register_dir = a print('Use gpu:', use_gpu) print('Register dir:', register_dir) print('Dog ID to be checked:', dog_id) print('Dog image to check:', dog_img) if use_gpu: siam_model = SiameseNetwork(image_size).cuda() siam_model.load_state_dict(torch.load(model_path, map_location=torch.device('cuda:0'))) else: siam_model = SiameseNetwork(image_size).cpu() siam_model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu'))) siam_model.eval() if exam_dir: img_paths = [] sum_lines = [] for path, subdirs, files in os.walk(exam_dir): for name in files: img_paths.append(os.path.join(path, name)) img_paths.sort() for i, img in enumerate(img_paths): find_id, similarity = find_dog(img) if find_id: line = "%s = %s (%s)" % (img_paths[i], find_id, similarity) else: line = "%s = None" % (img_paths[i],) sum_lines.append("%s\n" % (line,)) print(line) elif dog_id: is_same = exam_dog(dog_id, dog_img)[0] if is_same: print("Yes, The dog is %s." % (dog_id,)) else: print("No, The dog is not %s." % (dog_id,)) else: find_id, similarity = find_dog(dog_img) if find_id: print("The dog is %s, similarity is %s" % (find_id, similarity)) else: print("Cannot find the dog.") with open("exam.log", "w") as fp: fp.writelines(sum_lines) fp.writelines("\nDetails ==================\n") fp.writelines(log_lines)
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 28034, 198, 6738, 4566, 1330, 17056, 198, 6738, 4512, 18, 1330, 2939, 62, 7857, 198, 6738, 2746, 1330, 15638, 1047, 68, 26245, 198, 6738, 13446, 18, 1330, 6208, 27354, 292, 316, 198, 6738, 28...
1.944067
1,323
"""This module contains auxiliary function which we use in the example notebook.""" import json import matplotlib.patches as mpatches import matplotlib.pyplot as plt from scipy.stats import norm import pandas as pd import numpy as np from grmpy.estimate.estimate_output import calculate_mte from grmpy.read.read import read def process_data(df, output_file): """This function adds squared and interaction terms to the Cainero data set.""" # Delete redundant columns\n", for key_ in ['newid', 'caseid']: del df[key_] # Add squared terms for key_ in ['mhgc', 'cafqt', 'avurate', 'lurate_17', 'numsibs', 'lavlocwage17']: str_ = key_ + 'sq' df[str_] = df[key_] ** 2 # Add interaction terms for j in ['pub4', 'lwage5_17', 'lurate_17', 'tuit4c']: for i in ['cafqt', 'mhgc', 'numsibs']: df[j + i] = df[j] * df[i] df.to_pickle(output_file + '.pkl') def plot_est_mte(rslt, file): """This function calculates the marginal treatment effect for different quartiles of the unobservable V. ased on the calculation results.""" init_dict = read(file) data_frame = pd.read_pickle(init_dict['ESTIMATION']['file']) # Define the Quantiles and read in the original results quantiles = [0.0001] + np.arange(0.01, 1., 0.01).tolist() + [0.9999] mte_ = json.load(open('data/mte_original.json', 'r')) mte_original = mte_[1] mte_original_d = mte_[0] mte_original_u = mte_[2] # Calculate the MTE and confidence intervals mte = calculate_mte(rslt, init_dict, data_frame, quantiles) mte = [i / 4 for i in mte] mte_up, mte_d = calculate_cof_int(rslt, init_dict, data_frame, mte, quantiles) # Plot both curves ax = plt.figure(figsize=(17.5, 10)).add_subplot(111) ax.set_ylabel(r"$B^{MTE}$", fontsize=24) ax.set_xlabel("$u_D$", fontsize=24) ax.tick_params(axis='both', which='major', labelsize=18) ax.plot(quantiles, mte, label='grmpy $B^{MTE}$', color='blue', linewidth=4) ax.plot(quantiles, mte_up, color='blue', linestyle=':', linewidth=3) ax.plot(quantiles, mte_d, color='blue', linestyle=':', linewidth=3) ax.plot(quantiles, mte_original, label='original$B^{MTE}$', color='orange', linewidth=4) ax.plot(quantiles, mte_original_d, color='orange', linestyle=':',linewidth=3) ax.plot(quantiles, mte_original_u, color='orange', linestyle=':', linewidth=3) ax.set_ylim([-0.41, 0.51]) ax.set_xlim([-0.005, 1.005]) blue_patch = mpatches.Patch(color='blue', label='original $B^{MTE}$') orange_patch = mpatches.Patch(color='orange', label='grmpy $B^{MTE}$') plt.legend(handles=[blue_patch, orange_patch],prop={'size': 16}) plt.show() return mte def calculate_cof_int(rslt, init_dict, data_frame, mte, quantiles): """This function calculates the confidence interval of the marginal treatment effect.""" # Import parameters and inverse hessian matrix hess_inv = rslt['AUX']['hess_inv'] / data_frame.shape[0] params = rslt['AUX']['x_internal'] # Distribute parameters dist_cov = hess_inv[-4:, -4:] param_cov = hess_inv[:46, :46] dist_gradients = np.array([params[-4], params[-3], params[-2], params[-1]]) # Process data covariates = init_dict['TREATED']['order'] x = np.mean(data_frame[covariates]).tolist() x_neg = [-i for i in x] x += x_neg x = np.array(x) # Create auxiliary parameters part1 = np.dot(x, np.dot(param_cov, x)) part2 = np.dot(dist_gradients, np.dot(dist_cov, dist_gradients)) # Prepare two lists for storing the values mte_up = [] mte_d = [] # Combine all auxiliary parameters and calculate the confidence intervals for counter, i in enumerate(quantiles): value = part2 * (norm.ppf(i)) ** 2 aux = np.sqrt(part1 + value) / 4 mte_up += [mte[counter] + norm.ppf(0.95) * aux] mte_d += [mte[counter] - norm.ppf(0.95) * aux] return mte_up, mte_d
[ 37811, 1212, 8265, 4909, 37419, 2163, 543, 356, 779, 287, 262, 1672, 20922, 526, 15931, 198, 11748, 33918, 198, 198, 11748, 2603, 29487, 8019, 13, 8071, 2052, 355, 285, 8071, 2052, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 45...
2.392535
1,661
from django.db import models from django.utils.encoding import python_2_unicode_compatible """ Contains the models/tables for the kumbhmela_db.sqlite3 database. Every field has (when necessary) a 'help_text' that explains the meaning of the field. """ __author__ = "Louis Dijkstra" @python_2_unicode_compatible class Drive(models.Model): """ Table/model to represent (a collection of) drive(s). """ label = models.CharField(max_length=50, help_text="Label added to the drive, e.g., 'kumbhmela_5'.") external = models.BooleanField(default=False, help_text="True when the drive is external and false otherwise.") time_added = models.DateTimeField(blank=True, null=True, help_text="Time when the drive was added to the drive bay.") time_removed = models.DateTimeField(blank=True, null=True, help_text="Time when the drive was removed from the drive bay.") whereabouts = models.TextField(max_length=1000, blank=True, help_text="Whereabouts of this drive copy, e.g., who had it lasts, where is it now etc. (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Additional notes on this (collection of) drive(s) (optional).") @python_2_unicode_compatible class DriveCopy(models.Model): """ Every Drive might have several copies. This table/model is used to keep track of them. """ drive = models.ForeignKey(Drive, on_delete=models.CASCADE, help_text="The unique drive it is a copy of.") label = models.CharField(max_length=50, help_text="Label added to the drive, e.g., 'kumbhmela_5II'.") number = models.IntegerField(help_text="Drive copy number.") whereabouts = models.TextField(max_length=1000, blank=True, help_text="Whereabouts of this drive copy, e.g., who had it lasts, where is it now etc. (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Additional notes on this drive copy (optional).") @python_2_unicode_compatible class Person(models.Model): """ Table/Model to represent a person """ name = models.CharField(max_length=100, help_text="First and last name.") email = models.CharField(max_length=200, blank=True, help_text="Email address(es) (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Notes (optional).") @python_2_unicode_compatible class Experiment(models.Model): """ Table/Model to represent the various subexperiments """ # every experiment is linked to a contact person contactperson = models.ForeignKey(Person, on_delete=models.CASCADE, help_text="Main contact person for this subexperiment.") name = models.CharField(max_length=100, help_text="Name of the subexperiment.") number = models.IntegerField(help_text="Number of the subexperiment.") description = models.TextField(max_length=1000, blank=True, help_text="Short description of the experiment (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Additional notes on the subexperiment (optional).") @python_2_unicode_compatible class Format(models.Model): """ Table/model to represent a file format, i.e., the format in which output of a sensor is stored """ extension = models.CharField(max_length=50, help_text="Extension of the file (in small letters!), e.g., '.txt' and not '.TXT'.") description = models.TextField(max_length=10000, blank=True, help_text="Description of the file format (optional).") @python_2_unicode_compatible class Location(models.Model): """ Table/model to represent a (geo)location """ latitude = models.FloatField(blank=True, help_text="Optional.") longitude = models.FloatField(blank=True, help_text="Optional.") description = models.TextField(max_length=1000, blank=True, help_text="Description of the location (optional).") @python_2_unicode_compatible class Sensor(models.Model): """ Table/model to represent a sensor (e.g., camera/GPS device) """ sensor_type = models.CharField(max_length=100, help_text="Short description of the sensor, e.g., 'GoPro Camera'.") location = models.ManyToManyField(Location, blank=True, help_text="The location for this sensor (optional).") format = models.ManyToManyField(Format, blank=True, help_text="The format for the output of this sensor (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Notes for this sensor (optional).") @python_2_unicode_compatible class Source(models.Model): """ Table/model to represent a data source (e.g., 'Local police') """ name = models.CharField(max_length=200, help_text="Name of the data source (e.g., 'Local Police')") note = models.TextField(max_length=1000, blank=True, help_text="Additional notes on this data source (optional).") @python_2_unicode_compatible class File(models.Model): """ The main table/model for this app. It is used to keep track of all files on the various drives for the Kumbh Mela experiment. """ # a file can be stored a several drives: drive = models.ManyToManyField(Drive, through='StorageLocation', help_text="The drives on which the file is stored.") format = models.ForeignKey(Format, on_delete=models.CASCADE, blank=True, null=True, help_text="Format of the file (optional).") experiment = models.ManyToManyField(Experiment, blank=True, help_text="The subexperiment this file belongs to (optional).") source = models.ForeignKey(Source, on_delete=models.CASCADE, blank=True, null=True, help_text="The data source (optional).") sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE, blank=True, null=True, help_text="Sensor used to obtain the data (optional).") location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True, help_text="Location where the recording took place (optional).") time_added = models.DateTimeField(auto_now=True, blank=True, help_text="Time when the drive was added to the drive bay (optional).") size = models.IntegerField(blank=True, null=True, help_text="Size in bytes (optional).") start_recording = models.DateTimeField(blank=True, null=True, help_text="Time when the recording started (optional).") end_recording = models.DateTimeField(blank=True, null=True, help_text="Time when the recording ended (optional).") note = models.TextField(max_length=1000, blank=True, help_text="Additional notes on this file (optional).") def __str__(self): """Returns the file path""" filepaths = set() n_copies = 0 # the number of copies for storagelocation in self.storagelocation_set.all(): filepaths.add(storagelocation.path) n_copies += 1 if n_copies == 1: return ', '.join(filepaths) + ' (1 copy)' return ', '.join(filepaths) + ' (%s copies)'%(int(n_copies)) class StorageLocation(models.Model): """ A location where a specific file is stored. This model/table links files and drives together. (Each file can be stored on multiple drives under different names). """ drive = models.ForeignKey(Drive, on_delete=models.CASCADE) file = models.ForeignKey(File, on_delete=models.CASCADE) path = models.CharField(max_length=300, help_text="Path of the file on the drive.")
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 26791, 13, 12685, 7656, 1330, 21015, 62, 17, 62, 46903, 1098, 62, 38532, 198, 198, 37811, 220, 198, 197, 4264, 1299, 262, 4981, 14, 83, 2977, 329, 262, 479, 2178, ...
2.604258
2,959
"""Plotting methods for warm and cold fronts.""" import numpy import matplotlib matplotlib.use('agg') import matplotlib.colors from gewittergefahr.gg_utils import longitude_conversion as lng_conversion from gewittergefahr.gg_utils import error_checking from generalexam.ge_utils import front_utils from generalexam.plotting import narr_plotting DEFAULT_WARM_FRONT_COLOUR = numpy.array([228., 26., 28.]) / 255 DEFAULT_COLD_FRONT_COLOUR = numpy.array([31., 120., 180.]) / 255 DEFAULT_LINE_WIDTH = 2. DEFAULT_LINE_STYLE = 'solid' DEFAULT_GRID_OPACITY = 0.5 DEFAULT_WF_MARKER_TYPE = 'o' DEFAULT_CF_MARKER_TYPE = '>' DEFAULT_MARKER_SPACING_METRES = 150000. DEFAULT_MARKER_SIZE = 12 DEFAULT_MARKER_COLOUR = numpy.array([31, 120, 180], dtype=float) / 255 def get_colour_map_for_grid(): """Returns colour map for frontal grid (to be used by `plot_frontal_grid`). N = number of colours :return: colour_map_object: Instance of `matplotlib.colors.ListedColormap`. :return: colour_norm_object: Instance of `matplotlib.colors.BoundaryNorm`. :return: colour_bounds: length-(N + 1) numpy array of colour boundaries. colour_bounds[0] and colour_bounds[1] are the boundaries for the 1st colour; colour_bounds[1] and colour_bounds[2] are the boundaries for the 2nd colour; ...; etc. """ main_colour_list = [DEFAULT_WARM_FRONT_COLOUR, DEFAULT_COLD_FRONT_COLOUR] colour_map_object = matplotlib.colors.ListedColormap(main_colour_list) colour_map_object.set_under(numpy.array([1., 1., 1.])) colour_map_object.set_over(numpy.array([1., 1., 1.])) main_colour_bounds = numpy.array( [front_utils.WARM_FRONT_INTEGER_ID - 0.5, front_utils.WARM_FRONT_INTEGER_ID + 0.5, front_utils.COLD_FRONT_INTEGER_ID]) colour_norm_object = matplotlib.colors.BoundaryNorm( main_colour_bounds, colour_map_object.N) colour_bounds = numpy.concatenate(( numpy.array([-100.]), main_colour_bounds, numpy.array([100.]))) return colour_map_object, colour_norm_object, colour_bounds def plot_front_with_markers( line_latitudes_deg, line_longitudes_deg, axes_object, basemap_object, marker_spacing_metres=DEFAULT_MARKER_SPACING_METRES, marker_type=None, front_type_string=None, marker_colour=DEFAULT_MARKER_COLOUR, marker_size=DEFAULT_MARKER_SIZE): """Plots front with markers (instead of a line). P = number of points in line :param line_latitudes_deg: length-P numpy array of latitudes (deg N). :param line_longitudes_deg: length-P numpy array of longitudes (deg E). :param axes_object: Front will be plotted on these axes (instance of `matplotlib.axes._subplots.AxesSubplot`). :param basemap_object: Basemap used to convert lat-long coordinates to x-y (instance of `mpl_toolkits.basemap.Basemap`). :param marker_spacing_metres: Spacing between successive markers. :param marker_type: Marker type (any format accepted by matplotlib). :param front_type_string: [used only if `marker_type is None`] Front type (determines marker type). :param marker_colour: Marker colour (any format accepted by matplotlib). :param marker_size: Marker size (any format accepted by matplotlib). """ error_checking.assert_is_valid_lat_numpy_array(line_latitudes_deg) error_checking.assert_is_numpy_array(line_latitudes_deg, num_dimensions=1) num_points = len(line_latitudes_deg) these_expected_dim = numpy.array([num_points], dtype=int) error_checking.assert_is_numpy_array( line_longitudes_deg, exact_dimensions=these_expected_dim) line_longitudes_deg = lng_conversion.convert_lng_positive_in_west( line_longitudes_deg) error_checking.assert_is_greater(marker_spacing_metres, 0.) if marker_type is None: front_utils.check_front_type(front_type_string) if front_type_string == front_utils.WARM_FRONT_STRING_ID: marker_type = DEFAULT_WF_MARKER_TYPE else: marker_type = DEFAULT_CF_MARKER_TYPE x_coords_metres, y_coords_metres = basemap_object( line_longitudes_deg, line_latitudes_deg) for i in range(num_points - 1): this_x_diff_metres = x_coords_metres[i + 1] - x_coords_metres[i] this_y_diff_metres = y_coords_metres[i + 1] - y_coords_metres[i] this_distance_metres = numpy.sqrt( this_x_diff_metres ** 2 + this_y_diff_metres ** 2) this_num_points = 1 + int(numpy.ceil( this_distance_metres / marker_spacing_metres )) these_x_coords_metres = numpy.linspace( x_coords_metres[i], x_coords_metres[i + 1], num=this_num_points) these_y_coords_metres = numpy.linspace( y_coords_metres[i], y_coords_metres[i + 1], num=this_num_points) axes_object.plot( these_x_coords_metres, these_y_coords_metres, linestyle='None', marker=marker_type, markerfacecolor=marker_colour, markeredgecolor=marker_colour, markersize=marker_size, markeredgewidth=0.1) def plot_polyline( latitudes_deg, longitudes_deg, basemap_object, axes_object, front_type=None, line_colour=None, line_width=DEFAULT_LINE_WIDTH, line_style=DEFAULT_LINE_STYLE): """Plots either warm front or cold front as polyline. P = number of points in polyline :param latitudes_deg: length-P numpy array of latitudes (deg N). :param longitudes_deg: length-P numpy array of longitudes (deg N). :param basemap_object: Instance of `mpl_toolkits.basemap.Basemap`. :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`. :param front_type: Type of front (string). Used only to determine line colour (if `line_colour` is left as None). :param line_colour: Colour (in any format accepted by `matplotlib.colors`). Defaults to `DEFAULT_WARM_FRONT_COLOUR` or `DEFAULT_COLD_FRONT_COLOUR`. :param line_width: Line width (real positive number). :param line_style: Line style (in any format accepted by `matplotlib.lines`). """ error_checking.assert_is_valid_lat_numpy_array(latitudes_deg) error_checking.assert_is_numpy_array(latitudes_deg, num_dimensions=1) num_points = len(latitudes_deg) longitudes_deg = lng_conversion.convert_lng_positive_in_west(longitudes_deg) error_checking.assert_is_numpy_array( longitudes_deg, exact_dimensions=numpy.array([num_points])) if line_colour is None: front_utils.check_front_type(front_type) if front_type == front_utils.WARM_FRONT_STRING_ID: line_colour = DEFAULT_WARM_FRONT_COLOUR else: line_colour = DEFAULT_COLD_FRONT_COLOUR x_coords_metres, y_coords_metres = basemap_object( longitudes_deg, latitudes_deg) axes_object.plot( x_coords_metres, y_coords_metres, color=line_colour, linestyle=line_style, linewidth=line_width) def plot_narr_grid( frontal_grid_matrix, axes_object, basemap_object, first_row_in_narr_grid=0, first_column_in_narr_grid=0, opacity=DEFAULT_GRID_OPACITY): """Plots NARR grid points intersected by a warm front or cold front. This method plots data over a contiguous subset of the NARR grid, which need not be *strictly* a subset. In other words, the "subset" could be the full NARR grid. :param frontal_grid_matrix: See documentation for `front_utils.frontal_grid_to_points`. :param axes_object: Instance of `matplotlib.axes._subplots.AxesSubplot`. :param basemap_object: Instance of `mpl_toolkits.basemap.Basemap`. :param first_row_in_narr_grid: Row 0 in the subgrid is row `first_row_in_narr_grid` in the full NARR grid. :param first_column_in_narr_grid: Column 0 in the subgrid is row `first_column_in_narr_grid` in the full NARR grid. :param opacity: Opacity for colour map (in range 0...1). """ error_checking.assert_is_integer_numpy_array(frontal_grid_matrix) error_checking.assert_is_numpy_array(frontal_grid_matrix, num_dimensions=2) error_checking.assert_is_geq_numpy_array( frontal_grid_matrix, numpy.min(front_utils.VALID_INTEGER_IDS) ) error_checking.assert_is_leq_numpy_array( frontal_grid_matrix, numpy.max(front_utils.VALID_INTEGER_IDS) ) colour_map_object, _, colour_bounds = get_colour_map_for_grid() frontal_grid_matrix = numpy.ma.masked_where( frontal_grid_matrix == front_utils.NO_FRONT_INTEGER_ID, frontal_grid_matrix) narr_plotting.plot_xy_grid( data_matrix=frontal_grid_matrix, axes_object=axes_object, basemap_object=basemap_object, colour_map=colour_map_object, colour_minimum=colour_bounds[1], colour_maximum=colour_bounds[-2], first_row_in_narr_grid=first_row_in_narr_grid, first_column_in_narr_grid=first_column_in_narr_grid, opacity=opacity)
[ 37811, 43328, 889, 5050, 329, 5814, 290, 4692, 29324, 526, 15931, 198, 198, 11748, 299, 32152, 198, 11748, 2603, 29487, 8019, 198, 6759, 29487, 8019, 13, 1904, 10786, 9460, 11537, 198, 11748, 2603, 29487, 8019, 13, 4033, 669, 198, 6738, ...
2.395399
3,738
import sys, collections, pylev from stemming.porter2 import stem #-------------------------------------------------------------- # Author: Scott Wen-tau Yih # Usage: evalQA.py para-ids gold-labels system-predictions # example usage: python propara/eval/evalQA.py tests/fixtures/eval/para_id.test.txt tests/fixtures/eval/gold_labels.test.tsv tests/fixtures/eval/sample.model.test_predictions.tsv #-------------------------------------------------------------- # Data structure for Labels ''' PID -> [TurkerLabels] TurkerLabels = [TurkerQuestionLabel1, TurkerQuestionLabel2, ... ] # labels on the same paragraph from the same Turker TurkerQuestionLabel -> (SID, Participant, Type, From, To) ''' TurkerQuestionLabel = collections.namedtuple('TurkerQuestionLabel', 'sid participant event_type from_location to_location') # Data structure for Predictions ''' PID -> Participant -> SID -> PredictionRecord ''' PredictionRecord = collections.namedtuple('PredictionRecord', 'pid sid participant from_location to_location') # Fixing tokenization mismatch while alinging participants manual_participant_map = { 'alternating current':'alternate current', 'fixed nitrogen':'nitrogen', 'living things':'live thing', 'red giant star':'star', 'refrigerent liquid':'liquid', 'remains of living things':'remains of live thing', "retina's rods and cones":"retina 's rod and cone" } #, 'seedling':'seed'} #---------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------- ''' Read the gold file containing all records where an entity undergoes some state-change: create/destroy/move. ''' #---------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------- # Q1: Is participant X created during the process? # Q2: Participant X is created during the process. At which step is it created? # Q3: Participant X is created at step Y, and the initial location is known. Where is the participant after it is created? #---------------------------------------------------------------------------------------------------------------- # Q4: Is participant X destroyed during the process? # Q5: Participant X is destroyed during the process. At which step is it destroyed? # Q6: Participant X is destroyed at step Y, and its location before destroyed is known. Where is the participant right before it is destroyed? #---------------------------------------------------------------------------------------------------------------- # Q7 Does participant X move during the process? # Q8 Participant X moves during the process. At which steps does it move? # Q9 Participant X moves at step Y, and its location before step Y is known. What is its location before step Y? # Q10 Participant X moves at step Y, and its location after step Y is known. What is its location after step Y? #---------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------- if __name__ == "__main__": main()
[ 11748, 25064, 11, 17268, 11, 279, 2349, 85, 198, 6738, 34807, 13, 26634, 17, 1330, 10717, 198, 198, 2, 47232, 26171, 198, 2, 6434, 25, 4746, 31164, 12, 83, 559, 575, 4449, 198, 2, 29566, 25, 5418, 48, 32, 13, 9078, 31215, 12, 2340...
4.652778
792
from gevent import monkey; monkey.patch_all() import gevent from socketio import socketio_manage from socketio.server import SocketIOServer from socketio.namespace import BaseNamespace from socketio.mixins import RoomsMixin, BroadcastMixin from twisted.internet import reactor, task, defer from twisted.python import log from peerlyDB.network import Server import sys, signal from p2p import P2PNamespace log.startLogging(sys.stdout)
[ 6738, 4903, 1151, 1330, 21657, 26, 21657, 13, 17147, 62, 439, 3419, 198, 198, 11748, 4903, 1151, 198, 198, 6738, 17802, 952, 1330, 17802, 952, 62, 805, 496, 198, 6738, 17802, 952, 13, 15388, 1330, 47068, 40, 2640, 18497, 198, 6738, 17...
3.362963
135
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """API endpoints for executing PPR searches.""" # pylint: disable=too-many-return-statements from http import HTTPStatus from flask import current_app, g, jsonify, request from flask_restx import Namespace, Resource, cors from registry_schemas import utils as schema_utils from ppr_api.exceptions import BusinessException, DatabaseException from ppr_api.models import SearchRequest, SearchResult from ppr_api.resources import utils as resource_utils from ppr_api.services.authz import authorized, is_bcol_help, is_gov_account, is_sbc_office_account, is_staff_account from ppr_api.services.payment import TransactionTypes from ppr_api.services.payment.exceptions import SBCPaymentException from ppr_api.services.payment.payment import Payment from ppr_api.utils.auth import jwt from ppr_api.utils.util import cors_preflight API = Namespace('searches', description='Endpoints for PPR searches.') VAL_ERROR = 'Search request data validation errors.' # Validation error prefix SAVE_ERROR_MESSAGE = 'Account {0} search db save failed: {1}' PAY_REFUND_MESSAGE = 'Account {0} search refunding payment for invoice {1}.' PAY_REFUND_ERROR = 'Account {0} search payment refund failed for invoice {1}: {2}.' # Map api spec search type to payment transaction details description TO_SEARCH_TYPE_DESCRIPTION = { 'AIRCRAFT_DOT': 'Aircraft Airframe DOT Number:', 'BUSINESS_DEBTOR': 'Debtor Business Name:', 'INDIVIDUAL_DEBTOR': 'Debtor Individual Name:', 'MHR_NUMBER': 'Manufactured Home Registration Number:', 'REGISTRATION_NUMBER': 'Registration Number:', 'SERIAL_NUMBER': 'Serial/VIN Number:' } CERTIFIED_PARAM = 'certified' ROUTING_SLIP_PARAM = 'routingSlipNumber' DAT_NUMBER_PARAM = 'datNumber' BCOL_NUMBER_PARAM = 'bcolAccountNumber' @cors_preflight('POST,OPTIONS') @API.route('', methods=['POST', 'OPTIONS']) class SearchResource(Resource): """Resource for executing PPR searches.""" @staticmethod # @TRACER.trace() @cors.crossdomain(origin='*') @jwt.requires_auth def post(): # pylint: disable=too-many-branches,too-many-locals """Execute a new search request using criteria in the request body.""" try: # Quick check: must be staff or provide an account ID. account_id = resource_utils.get_account_id(request) if not account_id: return resource_utils.account_required_response() # Verify request JWT and account ID if not authorized(account_id, jwt): return resource_utils.unauthorized_error_response(account_id) request_json = request.get_json(silent=True) # Validate request against the schema. valid_format, errors = schema_utils.validate(request_json, 'searchQuery', 'ppr') if not valid_format: return resource_utils.validation_error_response(errors, VAL_ERROR) # Perform any extra data validation such as start and end dates here SearchRequest.validate_query(request_json) # Staff has special payment rules and setup. if is_staff_account(account_id) or is_bcol_help(account_id): return staff_search(request, request_json, account_id) query = SearchRequest.create_from_json(request_json, account_id, g.jwt_oidc_token_info.get('username', None)) # Charge a search fee. invoice_id = None payment = Payment(jwt=jwt.get_token_auth_header(), account_id=account_id, details=get_payment_details(query, request_json['type'])) transaction_type = TransactionTypes.SEARCH.value # if gov account user then check if sbc if is_gov_account(jwt): # if SBC staff user (authy, api call) then change transaction type to $10 fee is_sbc = is_sbc_office_account(jwt.get_token_auth_header(), account_id) if is_sbc: transaction_type = TransactionTypes.SEARCH_STAFF.value elif is_sbc is None: # didn't get a succesful response from auth raise BusinessException('Unable to verify possible SBC staff user before payment.', HTTPStatus.INTERNAL_SERVER_ERROR) pay_ref = payment.create_payment(transaction_type, 1, None, query.client_reference_id) invoice_id = pay_ref['invoiceId'] query.pay_invoice_id = int(invoice_id) query.pay_path = pay_ref['receipt'] # Execute the search query: treat no results as a success. try: query.search() # Now save the initial detail results in the search_result table with no # search selection criteria (the absence indicates an incomplete search). search_result = SearchResult.create_from_search_query(query) search_result.save() except Exception as db_exception: # noqa: B902; handle all db related errors. current_app.logger.error(SAVE_ERROR_MESSAGE.format(account_id, repr(db_exception))) if invoice_id is not None: current_app.logger.info(PAY_REFUND_MESSAGE.format(account_id, invoice_id)) try: payment.cancel_payment(invoice_id) except Exception as cancel_exception: # noqa: B902; log exception current_app.logger.error(PAY_REFUND_ERROR.format(account_id, invoice_id, repr(cancel_exception))) raise db_exception return query.json, HTTPStatus.CREATED except SBCPaymentException as pay_exception: return resource_utils.pay_exception_response(pay_exception, account_id) except BusinessException as exception: return resource_utils.business_exception_response(exception) except Exception as default_exception: # noqa: B902; return nicer default error return resource_utils.default_exception_response(default_exception) @cors_preflight('PUT,OPTIONS') @API.route('/<path:search_id>', methods=['PUT', 'OPTIONS']) class SearchDetailResource(Resource): """Resource for processing requests to update the search selection (UI autosave).""" @staticmethod # @TRACER.trace() @cors.crossdomain(origin='*') @jwt.requires_auth def put(search_id): """Execute a search selection update request replacing the current value with the request body contents.""" try: if search_id is None: return resource_utils.path_param_error_response('search ID') # Quick check: must be staff or provide an account ID. account_id = resource_utils.get_account_id(request) if account_id is None: return resource_utils.account_required_response() # Verify request JWT and account ID if not authorized(account_id, jwt): return resource_utils.unauthorized_error_response(account_id) request_json = request.get_json(silent=True) # Validate schema. valid_format, errors = schema_utils.validate(request_json, 'searchSummary', 'ppr') if not valid_format: return resource_utils.validation_error_response(errors, VAL_ERROR) search_request = SearchRequest.find_by_id(search_id) if not search_request: return resource_utils.not_found_error_response('searchId', search_id) # Save the updated search selection. search_request.update_search_selection(request_json) return jsonify(search_request.updated_selection), HTTPStatus.ACCEPTED except DatabaseException as db_exception: return resource_utils.db_exception_response(db_exception, account_id, 'PUT search selection update') except BusinessException as exception: return resource_utils.business_exception_response(exception) except Exception as default_exception: # noqa: B902; return nicer default error return resource_utils.default_exception_response(default_exception) def staff_search(req: request, request_json, account_id: str): """Execute a staff search with special payment validation and methods.""" payment_info = build_staff_payment(req, account_id) # bcol help is no fee; reg staff can be no fee. # FAS is routing slip only. # BCOL is dat number (optional) and BCOL account number (mandatory). # All staff roles including SBC can submit no fee searches. if ROUTING_SLIP_PARAM in payment_info and BCOL_NUMBER_PARAM in payment_info: return resource_utils.staff_payment_bcol_fas() if CERTIFIED_PARAM in payment_info: request_json['certified'] = True query: SearchRequest = SearchRequest.create_from_json(request_json, account_id, g.jwt_oidc_token_info.get('username', None)) # Always create a payment transaction. invoice_id = None payment = Payment(jwt=jwt.get_token_auth_header(), account_id=account_id, details=get_payment_details(query, request_json['type'])) # staff payment pay_ref = payment.create_payment_staff_search(payment_info, query.client_reference_id) invoice_id = pay_ref['invoiceId'] query.pay_invoice_id = int(invoice_id) query.pay_path = pay_ref['receipt'] # Execute the search query: treat no results as a success. try: query.search() # Now save the initial detail results in the search_result table with no # search selection criteria (the absence indicates an incomplete search). search_result = SearchResult.create_from_search_query(query) search_result.save() except Exception as db_exception: # noqa: B902; handle all db related errors. current_app.logger.error(SAVE_ERROR_MESSAGE.format(account_id, repr(db_exception))) if invoice_id is not None: current_app.logger.info(PAY_REFUND_MESSAGE.format(account_id, invoice_id)) try: payment.cancel_payment(invoice_id) except Exception as cancel_exception: # noqa: B902; log exception current_app.logger.error(PAY_REFUND_ERROR.format(account_id, invoice_id, repr(cancel_exception))) raise db_exception return query.json, HTTPStatus.CREATED def build_staff_payment(req: request, account_id: str): """Extract payment information from request parameters.""" payment_info = { 'transactionType': TransactionTypes.SEARCH_STAFF_NO_FEE.value } if is_bcol_help(account_id): return payment_info certified = req.args.get(CERTIFIED_PARAM) routing_slip = req.args.get(ROUTING_SLIP_PARAM) bcol_number = req.args.get(BCOL_NUMBER_PARAM) dat_number = req.args.get(DAT_NUMBER_PARAM) if certified is not None and isinstance(certified, bool) and certified: payment_info[CERTIFIED_PARAM] = True elif certified is not None and isinstance(certified, str) and \ certified.lower() in ['true', '1', 'y', 'yes']: payment_info[CERTIFIED_PARAM] = True if routing_slip is not None: payment_info[ROUTING_SLIP_PARAM] = str(routing_slip) if bcol_number is not None: payment_info[BCOL_NUMBER_PARAM] = str(bcol_number) if dat_number is not None: payment_info[DAT_NUMBER_PARAM] = str(dat_number) if ROUTING_SLIP_PARAM in payment_info or BCOL_NUMBER_PARAM in payment_info: if CERTIFIED_PARAM in payment_info: payment_info['transactionType'] = TransactionTypes.SEARCH_STAFF_CERTIFIED.value else: payment_info['transactionType'] = TransactionTypes.SEARCH_STAFF.value elif CERTIFIED_PARAM in payment_info: # Verify this is allowed. payment_info['transactionType'] = TransactionTypes.SEARCH_STAFF_CERTIFIED_NO_FEE.value return payment_info def get_payment_details(search_request, search_type): """Extract the payment details value from the search request criteria.""" details = { 'label': TO_SEARCH_TYPE_DESCRIPTION[search_type] } if search_request.search_type == SearchRequest.SearchTypes.BUSINESS_DEBTOR.value: details['value'] = search_request.search_criteria['criteria']['debtorName']['business'] elif search_request.search_type == SearchRequest.SearchTypes.INDIVIDUAL_DEBTOR.value: details['value'] = search_request.search_criteria['criteria']['debtorName']['last'] + ', ' +\ search_request.search_criteria['criteria']['debtorName']['first'] else: details['value'] = search_request.search_criteria['criteria']['value'] return details
[ 2, 15069, 10673, 13130, 22783, 286, 3517, 9309, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 705, 34156, 24036, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
2.463243
5,550
from .source import SourceSmartsheets __all__ = ["SourceSmartsheets"]
[ 6738, 764, 10459, 1330, 8090, 7556, 5889, 258, 1039, 198, 198, 834, 439, 834, 796, 14631, 7416, 7556, 5889, 258, 1039, 8973, 198 ]
3.086957
23
from mprl.rl.envs.stratego.stratego_spatial_multiagent_env import SpatialStrategoMultiAgentEnv from progress.bar import Bar import numpy as np import dill from multiprocessing.pool import Pool from multiprocessing import cpu_count
[ 6738, 285, 1050, 75, 13, 45895, 13, 268, 14259, 13, 23104, 2188, 13, 23104, 2188, 62, 2777, 34961, 62, 41684, 25781, 62, 24330, 1330, 1338, 34961, 1273, 4873, 2188, 29800, 36772, 4834, 85, 198, 6738, 4371, 13, 5657, 1330, 2409, 198, 1...
3.25
72
from django.contrib import admin from .models import ToDoItem admin.site.register(ToDoItem) # Register your models here.
[ 6738, 42625, 14208, 13, 3642, 822, 1330, 13169, 198, 6738, 764, 27530, 1330, 1675, 5211, 7449, 198, 198, 28482, 13, 15654, 13, 30238, 7, 2514, 5211, 7449, 8, 198, 198, 2, 17296, 534, 4981, 994, 13, 198 ]
3.324324
37
from __future__ import absolute_import import sys import argparse import where if __name__ == "__main__": sys.exit(main())
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 25064, 198, 11748, 1822, 29572, 198, 198, 11748, 810, 628, 628, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 25064, 13, 37023, 7, 12...
3.022727
44
name = "on-location-change-notifier-slack" add_files = ( "ruleset.py", ) add_modules = True # find modules in directory (folders having __init__.py file) and add them to container extra_commands = ( # ("RUN", "pip install my-wonderful-lib==1.0"), ) labels = { "networking.knative.dev/visibility": "cluster-local", "krules.airspot.dev/type": "ruleset", "krules.airspot.dev/ruleset": name, "configs.krules.airspot.dev/slack-webhooks": "inject" } template_annotations = { "autoscaling.knative.dev/minScale": "1", } #service_account = "my-service-account" triggers = ( { "name": name, "filter": { "attributes": { "type": "subject-property-changed", "propertyname": "location", } } }, ) triggers_default_broker = "class-b" ksvc_sink = "broker:default" ksvc_procevents_sink = "broker:procevents"
[ 198, 3672, 796, 366, 261, 12, 24886, 12, 3803, 12, 1662, 7483, 12, 6649, 441, 1, 198, 198, 2860, 62, 16624, 796, 357, 198, 220, 220, 220, 366, 38785, 316, 13, 9078, 1600, 198, 8, 198, 198, 2860, 62, 18170, 796, 6407, 220, 1303, ...
2.206813
411
#!/usr/bin/python # sound_waves.py v1.1 12-3-2011 Jeff Doak jeff.w.doak@gmail.com import sys import scipy as sp from scipy import linalg from scipy.integrate import dblquad import read_file BOLTZCONST = 1.381e-23 # J/K PLANCKCONST = 6.626e-34 # J*s AVONUM = 6.022e23 # things/mol def dir_cosines(dir,coords=sp.identity(3)): """Returns a vector containing the direction cosines between vector dir, and the coordinate system coords. Default coordinate system is an orthonormal cartesian coordinate system.""" cosines = sp.dot(coords,dir)/linalg.norm(dir) return cosines def make_gamma(dc,C): """ Returns a matrix containing the modified set of elastic constants, C, transformed by the direction cosines, dc. """ Gamma = sp.zeros((3,3)) Gamma[0,0] = dc[0]**2*C[0,0]+dc[1]**2*C[5,5]+dc[2]**2*C[4,4] Gamma[0,0] += 2*dc[1]*dc[2]*C[4,5]+2*dc[2]*dc[0]*C[0,4] Gamma[0,0] += 2*dc[0]*dc[1]*C[0,5] Gamma[1,1] = dc[0]**2*C[5,5]+dc[1]**2*C[1,1]+dc[2]**2*C[3,3] Gamma[1,1] += 2*dc[1]*dc[2]*C[1,3]+2*dc[2]*dc[0]*C[3,5] Gamma[1,1] += 2*dc[0]*dc[1]*C[1,5] Gamma[2,2] = dc[0]**2*C[4,4]+dc[1]**2*C[3,3]+dc[2]**2*C[2,2] Gamma[2,2] += 2*dc[1]*dc[2]*C[2,3]+2*dc[2]*dc[0]*C[2,4] Gamma[2,2] += 2*dc[0]*dc[1]*C[3,4] Gamma[0,1] = dc[0]**2*C[0,5]+dc[1]**2*C[1,5]+dc[2]**2*C[3,4] Gamma[0,1] += dc[1]*dc[2]*(C[3,5]+C[1,4])+dc[2]*dc[0]*(C[0,3]+C[4,5]) Gamma[0,1] += dc[0]*dc[1]*(C[0,1]+C[5,5]) Gamma[0,2] = dc[0]**2*C[0,4]+dc[1]**2*C[3,5]+dc[2]**2*C[2,4] Gamma[0,2] += dc[1]*dc[2]*(C[3,4]+C[2,5])+dc[2]*dc[0]*(C[0,2]+C[4,4]) Gamma[0,2] += dc[0]*dc[1]*(C[0,3]+C[4,5]) Gamma[1,2] = dc[0]**2*C[4,5]+dc[1]**2*C[1,3]+dc[2]**2*C[2,3] Gamma[1,2] += dc[1]*dc[2]*(C[3,3]+C[1,2])+dc[2]*dc[0]*(C[2,5]+C[3,4]) Gamma[1,2] += dc[0]*dc[1]*(C[1,4]+C[3,5]) Gamma[1,0] = Gamma[0,1] Gamma[2,0] = Gamma[0,2] Gamma[2,1] = Gamma[1,2] return Gamma def spherical_integral(C,rho): """ Calculate the integral of a function over a unit sphere. """ # phi - azimuthal angle (angle in xy-plane) # theta - polar angle (angle between z and xy-plane) # ( y , x ) # ( y , x ) #def sfunc(theta,phi,args=()): # return func(theta,phi,args)*sp.sin(theta) integral,error = dblquad(func,0,2*sp.pi,lambda g: 0,lambda h: sp.pi,args=(C,rho)) return integral #direction = sp.array((1.0,1.0,1.0)) #dc = dir_cosines(direction) #C = read_file.read_file(sys.argv[1]) #C.pop(0) #C = sp.array(C,float) #Gamma = make_gamma(dc,C) #density = 7500 #kg/m**3 #density = float(read_file.read_file(sys.argv[2])[0][0]) #rho_c_square = linalg.eigvals(Gamma) #GPa #rho_c_square = rho_c_square*1e9 #Pa #sound_vel = sp.sqrt(rho_c_square/density).real #avg_vel = sp.average(sound_vel) #print Gamma #print direction #print C #print rho_c_square #print rho_c_square.real #print sound_vel," in m/s" #print avg_vel #print spherical_integral(C,density) if __name__ == "__main__": main(sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 198, 2, 2128, 62, 32569, 13, 9078, 410, 16, 13, 16, 1105, 12, 18, 12, 9804, 5502, 2141, 461, 11223, 487, 13, 86, 13, 4598, 461, 31, 14816, 13, 785, 198, 198, 11748, 25064, 198, 11748, 6...
1.815081
1,671
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide a functions and classes to implement a custom JSON encoder for serializing objects for BokehJS. In general, functions in this module convert values in the following way: * Datetime values (Python, Pandas, NumPy) are converted to floating point milliseconds since epoch. * TimeDelta values are converted to absolute floating point milliseconds. * RelativeDelta values are converted to dictionaries. * Decimal values are converted to floating point. * Sequences (Pandas Series, NumPy arrays, python sequences) that are passed though this interface are converted to lists. Note, however, that arrays in data sources inside Bokeh Documents are converted elsewhere, and by default use a binary encoded format. * Bokeh ``Model`` instances are usually serialized elsewhere in the context of an entire Bokeh Document. Models passed trough this interface are converted to references. * ``HasProps`` (that are not Bokeh models) are converted to key/value dicts or all their properties and values. * ``Color`` instances are converted to CSS color values. .. |serialize_json| replace:: :class:`~bokeh.core.json_encoder.serialize_json` ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import annotations import logging # isort:skip log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from json import JSONEncoder from typing import Any, List, Tuple # Bokeh imports from ..settings import settings from .serialization import Buffer, Serialized #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'serialize_json', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- def serialize_json(obj: Any | Serialized[Any], *, pretty: bool | None = None, indent: int | None = None) -> str: ''' Return a serialized JSON representation of objects, suitable to send to BokehJS. This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also be passed, but note that Bokeh models are typically properly serialized in the context of an entire Bokeh document. The resulting JSON always has sorted keys. By default. the output is as compact as possible unless pretty output or indentation is requested. Args: obj (obj) : the object to serialize to JSON format pretty (bool, optional) : Whether to generate prettified output. If ``True``, spaces are added after added after separators, and indentation and newlines are applied. (default: False) Pretty output can also be enabled with the environment variable ``BOKEH_PRETTY``, which overrides this argument, if set. indent (int or None, optional) : Amount of indentation to use in generated JSON output. If ``None`` then no indentation is used, unless pretty output is enabled, in which case two spaces are used. (default: None) Any additional keyword arguments are passed to ``json.dumps``, except for some that are computed internally, and cannot be overridden: * allow_nan * indent * separators * sort_keys Examples: .. code-block:: python >>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3)) >>>print(serialize_json(data)) {"a":[0,1,2],"b":1483228800000.0} >>> print(serialize_json(data, pretty=True)) { "a": [ 0, 1, 2 ], "b": 1483228800000.0 } ''' pretty = settings.pretty(pretty) if pretty: separators=(",", ": ") else: separators=(",", ":") if pretty and indent is None: indent = 2 content: Any buffers: List[Buffer] if isinstance(obj, Serialized): content = obj.content buffers = obj.buffers or [] else: content = obj buffers = [] encoder = PayloadEncoder(buffers=buffers, indent=indent, separators=separators) return encoder.encode(content) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
[ 2, 10097, 32501, 198, 2, 15069, 357, 66, 8, 2321, 532, 33160, 11, 1052, 330, 13533, 11, 3457, 1539, 290, 347, 2088, 71, 25767, 669, 13, 198, 2, 1439, 2489, 10395, 13, 198, 2, 198, 2, 383, 1336, 5964, 318, 287, 262, 2393, 38559, ...
3.62022
1,543
s = input() c = 0 n = int(input()) a = [0]*3 c = 0 for i in range(n): a[i] = input() for i in (a): print(s.count(i))
[ 82, 796, 5128, 3419, 198, 66, 796, 657, 198, 77, 796, 493, 7, 15414, 28955, 198, 64, 796, 685, 15, 60, 9, 18, 198, 66, 796, 657, 198, 1640, 1312, 287, 2837, 7, 77, 2599, 198, 220, 220, 220, 257, 58, 72, 60, 796, 5128, 3419, ...
1.842857
70
# -*- coding: utf-8 -*- from typing import Dict, Any import os import pkg_resources from bag.design import Module yaml_file = pkg_resources.resource_filename(__name__, os.path.join('netlist_info', 'sense_amp_strongarm.yaml')) # noinspection PyPep8Naming class bag_serdes_ec__sense_amp_strongarm(Module): """Module for library bag_serdes_ec cell sense_amp_strongarm. Fill in high level description here. """ @classmethod @classmethod
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 19720, 1330, 360, 713, 11, 4377, 198, 198, 11748, 28686, 198, 11748, 279, 10025, 62, 37540, 198, 198, 6738, 6131, 13, 26124, 1330, 19937, 628, 198, 88, 43695,...
2.274678
233
# flake8: noqa # Converting GFF format with space in lines starting with gi to tab import sys import re fn = sys.argv[1] f = open(fn, "r") for l in f.read().split("\n"): if l.startswith("gi"): print re.sub(" ", "\t", l) else: print l
[ 2, 781, 539, 23, 25, 645, 20402, 198, 2, 35602, 889, 402, 5777, 5794, 351, 2272, 287, 3951, 3599, 351, 308, 72, 284, 7400, 198, 198, 11748, 25064, 198, 11748, 302, 198, 198, 22184, 796, 25064, 13, 853, 85, 58, 16, 60, 198, 69, 7...
2.230769
117
import random from itertools import islice from pysat.solvers import Minicard import numpy as np # from numba import njit, int16 from utils import np_one_hot, softmax # @njit(int16[:,:](int16[:]))
[ 11748, 4738, 198, 6738, 340, 861, 10141, 1330, 318, 75, 501, 198, 6738, 279, 893, 265, 13, 34453, 690, 1330, 1855, 291, 446, 198, 11748, 299, 32152, 355, 45941, 198, 198, 2, 422, 997, 7012, 1330, 299, 45051, 11, 493, 1433, 198, 198,...
2.697368
76
name = "vapetool"
[ 3672, 796, 366, 85, 499, 316, 970, 1, 198 ]
2
9
""" __init__.py.py: """ from pdd_sdk.api.rest import * from pdd_sdk.api.base import FileItem
[ 198, 198, 37811, 198, 834, 15003, 834, 13, 9078, 13, 9078, 25, 198, 37811, 198, 198, 6738, 279, 1860, 62, 21282, 74, 13, 15042, 13, 2118, 1330, 1635, 198, 6738, 279, 1860, 62, 21282, 74, 13, 15042, 13, 8692, 1330, 9220, 7449 ]
2.261905
42
""" Locators for Spring '22 """ eda_lex_locators = { "app_tile": "//one-app-launcher-modal//one-app-launcher-app-tile//a[.='{}']", "app_item": "//a[@data-label='{}']", "frame": "//iframe[contains(@id, '{}') or contains(@title, '{}') or contains(@name, '{}')]", "input_placeholder": "//input[contains(@placeholder,'{}')]", "panel_tab_lookup": "//a/span[text()='{}']", "toast_message": "//div[@id='successToast']/descendant::h2[text()='{}']", "success_message": "//div[@id='successToast']/descendant::h2[text()='{}']", "toast_close": "//div[@id='successToast']/descendant::button[contains(@class, 'slds-notify__close')]", "close_tab": "//*[@data-key='close']/ancestor::button[contains(@class, 'slds-button slds-button_icon-x-small')]", "mailing_address": "//*[contains(@placeholder,'{}')]", "record": { "actions": "//div[contains(@class, 'actionsContainer')]/descendant::a[@title='{}']", "button": "//div[@class='actionsContainer']/button[@title='{}']", "datepicker": "//div[contains(@class,'uiDatePickerGrid')]/table[@class='calGrid']//span[text()='{}']", "edit_button": '//*[@title="{}"]', "list": "//div[contains(@class,'forcePageBlockItem')]//div//div//div//span//span[contains(text(), 'Primary Address Type')]/../../div/div/div/div/a[@class='select']", "related": { "new": "//div[@class='container']/descendant::div[contains(@class, 'slds-card__header')]/header/descendant::span[text()='{}']/ancestor::header/following-sibling::div/descendant::a[@title='New']", "title": "//span[@title='{}']", }, }, "tabs": { "tab": "//div[@class='uiTabBar']/ul[@class='tabs__nav']/li[contains(@class,'uiTabItem')]/a[@class='tabHeader']/span[contains(text(), '{}')]", "spl-tab": "//div[@class='slds-tabs_default']//ul[@class='slds-tabs_default__nav']/li[contains(@class,'slds-tabs_default__item')]/a[text()= '{}']", }, "eda_setup": { "custom_settings": "//a[text()='{}']", "settings_action_button": "//input[@type='submit' and @value='{}']", "setup_owner": "//table[@class='list']/descendant::td", }, "eda_settings": { "action": "//div[@role='banner']/descendant::button[contains(@class, 'settings-{}-bttn')]", "edit": "//div[@class='slds-page-header' and @role='banner']/descendant::span[text()='Edit']/parent::button", "tab": "//div[@id='tabs']/descendant::li[contains(@class, 'slds-text-heading--label')]/a[text()='{}']", "checkbox_default": "//span[text()='{}']/../following-sibling::div/descendant::img", "checkbox": "//span[text()='{}']/../following-sibling::div/descendant::label[contains(@class,'slds-checkbox')]/span[contains(@class, 'slds-checkbox--faux')]", "save": "//div[contains(@class, 'slds-page-header')]/descendant::button[contains(@class, 'settings-save-bttn')]", "system_tab": "//a[contains(text(),'System')]", "affiliations_tab": "//a[contains(text(),'Affiliations')]", "affiliations_check": "//span[text()='Specify Role for Created Affiliations']/../following-sibling::div/div/div/label/span/img[@class = 'copy-start-date checked' and @alt='True']", "auto_enroll_business_organization": "//div/span[text()='Primary Business Organization']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "auto_enroll_educational_institution": "//div/span[text()='Primary Educational Institution']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "auto_enroll_household_account": "//div/span[text()='Primary Household']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "auto_enroll_sports_organization": "//div/span[text()='Primary Sports Organization']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "auto_enroll_university_department": "//div/span[text()='Primary Department']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "primary_affl_unchecked": "//div/span[text()='{}']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "checkbox_ap_affl": "(//label[@class='slds-checkbox']/input[@class='mapping-auto-enroll uiInput uiInputCheckbox uiInput--default uiInput--checkbox'])[1]/following-sibling::span[@class='slds-checkbox--faux']", "primary_affl_edit": "(//label/span[text()='Primary Affl Field: {}']/../../../following-sibling::div/div/div/label)[1]/input/following-sibling::span[@class='slds-checkbox--faux']", "affiliations_role_checkbox": "//input[@class='copy-start-date uiInput uiInputCheckbox uiInput--default uiInput--checkbox']/following-sibling::span", "affiliation_mappings_tab": "//a[contains(text(), 'Affiliation Mappings')]", "courses": "//a[contains(text(),'Courses')]", "duration": "//div[.//span[text()='Duration'] and contains(@class, 'slds-form-element') ]//select//option[@value='60']", "hh_naming_check": "//input[@class='automatic-hh-acc uiInput uiInputCheckbox uiInput--default uiInput--checkbox']/following-sibling::span", "hh_naming_role_checkbox": "//select[@class='admin-account-naming-input-select select uiInput uiInputSelect uiInput--default uiInput--select']//option[@value='{{!{{!FirstName}}}} {{!LastName}} Administrative Account']", "hh_adminfnamelname": "//input[contains(@class,'firstName')]", "course_connections_tab": "//a[contains(text(),'Course Connections')]", "cc_checkbox": "//input[contains(@class,'slds-checkbox')]/parent::label", "student_select": "//select[contains(@class,'student-course-connection-record-type-input-select')]", "faculty_select": "//select[contains(@class,'faculty-course-connection-record-type-input-select')]", "status_student_affl": "//select[contains(@class,'affiliation-role-picklist-input-select')]", "status_spec_affl_not_deleted_former": "//select[contains(@class,'affiliation-status-delete-picklist-input-select')]", "status_current_picklist_affl": "//select[contains(@class,'affiliation-status-picklist-input-select')]", "default_account_model": "//span[text()='Default Account Model']", "store_errors": "//span[text()='Store Errors']", "send_error_notifications": "//span[text()='Send Error Notifications']", "error_notification_recipients": "//span[text()='Error Notification Recipients']", "disable_error_handling": "//span[text()='Disable Error Handling']", "automatic_household_naming": "//span[text()='Automatic Household Naming']", "adminstrative_account_name_format": "//span[text()='Administrative Account Name Format']", "household_account_name_format": "//span[text()='Household Account Name Format']", "batch_processing": "(//td/following-sibling::td[text()='Batch Apex']/following-sibling::td[text()='Processing'])[1]", "just_batch": "(//td/following-sibling::td[text()='Batch Apex'])[1]", "batch_watch": "(//td/following-sibling::td[text()='Batch Apex']/following-sibling::td)[1]", "wait_frame": "//iframe[contains(@title,'Apex Jobs ~ Salesforce - Developer Edition')]", "wait_loc_text": "(//td/following-sibling::td[text()='Batch Apex']/following-sibling::td)[1]", "new_account": "//span[@title='New Account']", "affiliated_accounts": "//span[@title='Affiliated Accounts']", "affiliation_match": "//th[@data-label='Affiliation Key']/../descendant::a[@title='{}']", "edit_button": "//div[@class='slds-button-group']//span[contains(text(), 'Edit')]", "save_button": "//div[@class='slds-button-group']//span[contains(text(), 'Save')]", "administrative_account": "//div/a[text()='{} Administrative Account']", "contact_edit": "//a[@title='Edit']", "en_re_type_validation": "(//div/span[text()='Record Type Validation']/following::div)[1]/div/div/label/span[@class='slds-checkbox--faux']", "ert_validation": "//span/img[@class='affl-record-type-enforced checked' and @alt='True']", "un_ert_validation": "//span/img[@class='affl-record-type-enforced unchecked' and @alt='False']", "delete_rec_affl": "//span/img[@class='delete-prog-enroll checked' and @alt='True']", "un_delete_rec_affl": "//span/img[@class='delete-prog-enroll unchecked' and @alt='False']", "del_rel_affl": "(//div/span[text()='Delete Related Affiliation When Deleting Program Enrollment']/following::div)[1]/div/div/label/span[@class='slds-checkbox--faux']", "specify_role_for_c_affl": "(//div/div/span[text()='Specify Role for Created Affiliations']/following::span)[1]/img[@class='copy-start-date checked' and @alt='True']", "un_specify_role_for_c_affl": "(//div/div/span[text()='Specify Role for Created Affiliations']/following::span)[1]/img[@class='copy-start-date unchecked' and @alt='False']", "specify_r_checkbox": "(//div/span[text()='Specify Role for Created Affiliations']/following::div)[1]/div/div/label/span[@class='slds-checkbox--faux']", "copy_affl_end_date": "//span/img[@class='copy-end-date checked' and @alt='True']", "un_copy_affl_end_date": "//span/img[@class='copy-end-date unchecked' and @alt='False']", "copy_affliation_end_checkbox": "(//div/span[text()='Copy Affiliation End Date from Program Enrollment']/following::div)[1]/div/div/label/span[@class='slds-checkbox--faux']", "copy_affl_start_date": "(//div/div/span[text()='Copy Affiliation Start Date from Program Enrollment']/following::span)[1]/img[@class='copy-start-date checked' and @alt='True']", "un_copy_affl_start_date": "(//div/div/span[text()='Copy Affiliation Start Date from Program Enrollment']/following::span)[1]/img[@class='copy-start-date unchecked' and @alt='False']", "copy_affliation_start_checkbox": "(//div/span[text()='Copy Affiliation Start Date from Program Enrollment']/following::div)[1]/div/div/label/span[@class='slds-checkbox--faux']", "settings_tab": "(//li[@class='slds-tabs__item slds-text-heading--label slds-active' and @role='tab' and @title='Settings'])[1]/a[contains(text(),'Settings')]", "affl_mappings_tab": "//a[contains(text(),'Affiliation Mappings')]", "default_checkbox": "//div[text()='{}']/following-sibling::div/descendant::img", "enable_checkbox": "(//div[text()='{}']/following-sibling::div/descendant::span)[1]", "dropdown_field": "//div[text()='{}']/following-sibling::div/select", "action_button": "//button[text()='{}']", "update_checkbox": "//span[text()='{}']/../following-sibling::div[1]/descendant::span[contains(@class, 'checkbox')]", "add_setting_button": "//span[text()='{}']/../following-sibling::button/span[text()='{}']", }, "eda_settings_new": { "global_action": "//button[text()='{}']", "edc_header": "//h2[contains(@class, 'header')]/descendant::span[text()='{}']", "toast_message": "//div[contains(@class, 'slds-theme--success slds-notify--toast slds-notify slds-notify--toast forceToastMessage')]/descendant::span[text()='{}']", "custom_toast": "//div[contains(@class, 'forceToastMessage')]/descendant::span[contains(@class, 'toastMessage')]", "settings_nav_title": "//div[@data-qa-locator='edaSettingsNavigation']/descendant::a[text()='{}']", "dropdown_input": "//label[text()='{}']/../descendant::button[contains(@class, 'slds-combobox__input')]", "settings_dropdown": "//label[text()='{}']/../descendant::span[text()='{}']", "select_from_list": "//div[text()='{}']/../following-sibling::div/descendant::div[contains(@class, 'list__options')]/descendant::span[text()='{}']", "move_to_selected": "//div[text()='{}']/../following-sibling::div/descendant::button[@type='button' and @title='Move selection to Selected Account Record Types']", "tell_me_more": "//div[text()='{}']/../descendant::a[text()='{}']", "toggle_status": "//span[text()='{}']/../ancestor::lightning-input", "toggle_input": "//span[text()='{}']/../descendant::span[contains(@id, 'toggle')]", "update_button": "//div[text()='{}']/../parent::div/descendant::button[text()='{}']", "footer_button": "//div[contains(@class, 'footer')]/descendant::button[@title='{}']", "app_tile": "//h2[text()='{}']/../descendant::ul/descendant::*[self::div or self::span][text()='{}']", "show_actions_button": "//tr[@data-row-key-value='{}']/descendant::span[text()='Show actions']/ancestor::button[@type='button']", "actions_menu": "//tr[@data-row-key-value='{}']/descendant::span[text()='{}']/ancestor::a[@role='menuitem']", }, "eda_settings_cc": { "default_cc_checkbox": "//div[text()='Enable Course Connections']/following-sibling::div/descendant::img", "dropdown_values": "//div[text()='{}']/following-sibling::div/select/option[text()='{}']", "dropdown_values_count": "//div[text()='{}']/following-sibling::div/select/option", "enable_cc_checkbox": "//div[text()='Enable Course Connections']/following-sibling::div[1]/descendant::span", "enable_cc_warning_enabled": "//div[contains(@class, 'slds-notify') and @role='alert']/descendant::*[@data-key='warning']/../../following-sibling::span[text()='You must enable Course Connections before editing record types.']", "enable_cc_warning_disabled": "//span[contains(@class, 'slds-hide')]/descendant::div[contains(@class, 'slds-notify') and @role='alert']/descendant::*[@data-key='warning']/../../following-sibling::span[text()='You must enable Course Connections before editing record types.']", "updated_dropdown_value": "//div[text()='{}']/following-sibling::div/descendant::span[text()='{}']", "settings_tab": "//div[contains(@class, 'CourseConnections')]/descendant::a[text()='Settings']", "backfill_warning_enabled": "//div[contains(@class, 'slds-notify--alert')]/descendant::span[text()='You must enable Course Connections before running the Course Connections Backfill.']", "backfill_warning_disabled": "//span[contains(@class, 'slds-hide')]/descendant::span[text()='You must enable Course Connections before running the Course Connections Backfill.']", "cc_sub_tabs": "//div[contains(@class, 'CourseConnections')]/descendant::a[text()='{}']", "backfill_button_status": "//span[text()='{}']/parent::button", "backfill_checkbox_status": "//input[contains(@class, 'backfill')]/following-sibling::span[contains(@class, 'checkbox')]", "backfill_checkbox": "//span[text()='I understand and am ready to run Backfill.']/../span[contains(@class, 'checkbox')]", "backfill_toast": "//div[@id='backFillToast']/descendant::span[text()='{}']", }, "eda_settings_program_plans": { "checkbox_read": "(//span[text()='{}']/../following-sibling::div/descendant::img)[1]", "checkbox_edit": "(//span[text()='{}']/../following-sibling::div/descendant::span)[1]", "updated_checkbox_edit": "//span[text()='{}']/../following-sibling::div[1]/descendant::span[contains(@class, 'checkbox')]", }, "eda_settings_affiliations": { "acc_rec_type_edit": "//span[text()='Acc Record Type: {}']/../following-sibling::input[contains(@class, 'mapping-acc-rec-type')]", "acc_rec_type_cleared": "//span[text()='Acc Record Type: ']/../following-sibling::input[contains(@class, 'mapping-acc-rec-type')]", }, "eda_settings_courses": { "text_message": "//span[text()='{}']", }, "eda_settings_accounts_contacts": { "checkbox": "//span[text()='{}']/following::div[1]/descendant::span[text()='{}']/parent::label/span[contains(@class, 'checkbox')]", "checkbox_value": "//span[text()='{}']/following::label[1][contains(@class, 'checkbox')]/span[contains(@class, 'checkbox')]", "checkbox_list": "//span[text()='{}']/../../following-sibling::div[1]/descendant::span[contains(@class, 'checkbox')]", "checkbox_list_read": "//span[text()='{}']/../../following-sibling::div[1]/descendant::img", "dropdown_acc": "//span[text()='{}']/../following-sibling::div[1]/select/option[text()='{}']", }, "eda_settings_relationships": { "dropdown_read": "//span[text()='{}']/../following-sibling::div[1]/descendant::span", "dropdown_value": "//span[text()='{}']/../following-sibling::div/descendant::select/option[text()='{}']", "new_reciprocal_setting": "//div[contains(@class, 'newrecsetting')]/descendant::span[text()='{}']/following::input[1]", "sub_tab": "//div[@id='relTabs']/descendant::li[contains(@class, 'slds-text-heading--label')]/a[text()='{}']", "active_checkbox": "//span[text()='{}']/following::input[contains(@class, 'new-rec-sett')]/../span[contains(@class, 'checkbox')]", "add_setting_button": "//div[contains(@class, 'newrecsetting')]/descendant::span[text()='{}']", "settings_count": "//span[contains(@class, 'Checkbox')]/img[contains(@class, 'rec-settg')]", "new_settings": "(//div[@class='newrecsetting']/preceding-sibling::div[1]/div)[last()-{}]/span[contains(@class, 'rec-settg-{}') and text()='{}']", "new_setting_edit": "(//div[@class='newrecsetting']/preceding-sibling::div[1]/div)[last()-{}]/descendant::input[contains(@class, 'rec-settg-{}')]/../label/span[text()='{}: {}']", "new_setting_checkbox": "(//div[@class='newrecsetting']/preceding-sibling::div[1]/div)[last()-1]/descendant::img[contains(@class, 'rec-settg-{}')]", "new_setting_checkbox_edit": "(//div[@class='newrecsetting']/preceding-sibling::div[1]/div)[last()-1]/descendant::input[contains(@class, 'rec-settg-{}')]/../span[contains(@class, 'checkbox')]", "delete_setting_icon": "//span[text()='{}: {}']/following::lightning-icon[1][contains(@class, 'delete')]", "removed_setting": "//span[contains(@class, 'rec-settg-{}') and text()='{}']", "removed_autoc_setting": "//span[contains(@class, 'autoc-settg-{}') and text()='{}']", "updtate_setting_name": "//span[text()='Name: {}']/../following-sibling::input[contains(@class, 'rec-settg-{}')]", "update_setting_name_cleared": "//span[text()='Name: ']/../following-sibling::input[contains(@class, 'rec-settg-name')]", "update_setting_rest": "(//span[text()='Name: {}']/following::input[contains(@class, 'rec-settg-{}')])[1]", "updated_setting": "//span[contains(@class, 'rec-settg-name') and text()='{}']/following::div/span[contains(@class, 'rec-settg-{}') and text()='{}']", "test_locator": "(//div[@class='newrecsetting']/preceding-sibling::div[1]/div)[last()-2]/descendant::input[contains(@class, 'rec-settg-neutral')]", "new_autocreate_setting": "//div[contains(@class, 'newautocsetting')]/descendant::span[text()='{}']/following::input[1]", "campaign_type_textarea": "//div[contains(@class, 'newautocsetting')]/descendant::span[text()='{}']/following::textarea", "new_settings_autoc": "(//div[@class='newautocsetting']/preceding-sibling::div[1]/div)[last()-{}]/span[contains(@class, 'autoc-settg-{}') and text()='{}']", "new_autoc_setting_edit": "(//div[@class='newautocsetting']/preceding-sibling::div[1]/div)[last()-{}]/descendant::input[contains(@class, 'autoc-settg-{}')]/../label/span[text()='{}: {}']", "new_campaign_types_edit": "(//div[@class='newautocsetting']/preceding-sibling::div[1]/div)[last()-{}]/descendant::textarea[contains(@class, 'autoc-settg-{}')]/../label/span[text()='{}: {}']", }, "eda_settings_system": { "default_checkbox": "//span[text()='{}']/../following-sibling::div[1]/descendant::img", "default_dropdown_value": "//span[text()='{}']/../following-sibling::div[1]/descendant::span[text()='{}']", "admin_success_toast": "//div[@id='adminSuccessToast']/descendant::h2", "hh_success_toast": "//div[@id='hhSuccessToast']/descendant::h2", "other_accname_format": "//span[text()='{}']/../preceding-sibling::div[1]/descendant::input", "other_dropdown_value": "//span[text()='{}']/../preceding-sibling::div[1]/descendant::span[text()='{}']", "recipient_type_value": "//span[text()='{}']/../following-sibling::div/descendant::select/option[@value='{}']", "recipient_name": "//label[text()='{}']/../div/descendant::input", "recipient_lookup": "//div[contains(@class, 'lookup') and text()='{}']", }, "account_types": { "administrative": "//span[contains(text(),'Administrative')]/parent::*", "household": "//span[text()='Household Account']/preceding-sibling::span", "account_checkbox": "//div[contains(@class,'slds-form-element__control')]//span[contains(text(),'{}')]", "save": "//button[contains(@class, 'slds-button')]/span[text()='Save']/..", "edit": "//button[contains(@class, 'slds-button')]/span[text()='Edit']/..", "cancel": "//button[contains(@class, 'slds-button')]/span[text()='Cancel']/..", }, "contact": { "new_button": "//a[@title='New']//div[@title='New']", "first_name": "//input[contains(@class,'firstName')]", "last_name": "//input[contains(@class,'lastName')]", "save_button": "//button[@title='Save']", "program_enrollment_new_button": "//div[contains(@class, 'windowViewMode-normal')]//span[text()='Program Enrollments']/following-sibling::span[@title='(0)']/ancestor::header/following-sibling::div/descendant::a[@title='New']", }, "program_plans": { "program_plan": "(//a[@title='Program Plans'])[2]/span/span", "new_button": "//a[@title='New']//div[@title='New']/..", "pp_name": "//div//div//div//div//div//div//div//label//span[contains(text(), 'Program Plan Name')]//../following-sibling::input", "save_button": "//div[contains(@class, 'inlineFooter')]/descendant::button[@title='Save']", }, "plan_requirement": { "error": "//div[contains(@class, 'pageLevelErrors')]/descendant::li[text()='{}']", "parent_plan_req_name": "//div[contains(@class, 'slds-modal__container')]/descendant::span[text()='Parent Plan Requirement']/../following-sibling::div/descendant::span[text()='{}']", "plan_requirement_name": "//div[contains(@class, 'slds-modal__container')]/descendant::span[text()='Plan Requirement Name']/../following-sibling::input", "program_plan_name": "//td/a[@title='{}']", "program_plan": "//div[contains(@class, 'slds-modal__container')]/descendant::span[text()='Program Plan']/../following-sibling::div/descendant::span[text()='{}']", "delete_field": "//div[contains(@class, 'slds-modal__container')]/descendant::span[text()='{}']/../following-sibling::div/descendant::span[text()='{}']/following-sibling::a[@class='deleteAction']", "toast_message": "//lightning-icon[contains(@class, 'toastIcon') and contains(@class, 'slds-icon-utility-success')]", }, "course_offering": { "search_courses": "//div/input[@title='Search Courses']", "new_button": "//a[@title='New']//div[@title='New']/..", "new_course_button": "//span[@class='itemLabel slds-truncate slds-show--inline-block slds-m-left--xx-small' and contains(text(), 'New Course')]", "save_button": "(//span[@class=' label bBody' and text()='Save']/ancestor::button[contains(@class, 'slds-button')])[3]", "next_save_button": "//div[contains(@class, 'inlineFooter')]/descendant::button[@title='Save']", "final_save_button": "(//span[@class=' label bBody' and text()='Save'])[3]/ancestor::button", }, "settings_health_check": { "run_health_check_button": "//button[@title='{}']", "health_check_header": "//h2[contains(@class, 'header')]/span[text()='{}']", "last_run_date": "//button[@title='Run Health Check']/preceding::div[1]", "expand_button": "//button[@title='Expand these results' and contains(@aria-controls, '{}')]", "all_checks_status": "//div[text()='{}']/following-sibling::div/div[contains(@class, 'text')]", "status_value": "//div[contains(@id, '{}')]/descendant::td/descendant::lightning-base-formatted-text[text()='{}']/ancestor::td/preceding-sibling::th[@data-label='Status']/descendant::lightning-base-formatted-text", "recommended_fix_value": "//div[contains(@id, '{}')]/descendant::td/descendant::lightning-base-formatted-text[text()='{}']/ancestor::tr/descendant::td[@data-label='Recommended Fix']/descendant::lightning-base-formatted-text", }, "term": { "new_term_button": "//span[@class='itemLabel slds-truncate slds-show--inline-block slds-m-left--xx-small' and contains(text(), 'New Term')]//..", "save_button": "(//span[@class=' label bBody' and contains(text(), 'Save')])[5]/..", "account": "//div//input[@title='Search Accounts']", "search_terms": "//input[@title='Search Terms']", "course_offering_id": "//span[contains(text(), 'Course Offering ID')]//../following-sibling::input", }, "custom_settings": { "hierarchy_settings": "//a[text()='Hierarchy Settings']", "manage": "//span/input[@value='Manage']", "no_records": "//table//td[text()='No records to display.']", "custom_settings_frame": "//iframe[contains(@title,'Custom Settings ~ Salesforce')]", "custom_settings_definition": "//iframe[contains(@title,'Custom Setting Definition ~ Salesforce')]", "custom_settings_h_settings": "//iframe[contains(@title,'Custom Setting Hierarchy Settings ~ Salesforce')]", }, "new_account": "//span[@title='New Account']", "new_account_next_button": "//button[contains(@class, 'slds-button')]//span[@class=' label bBody' and text()='Next']", "new_account_name": "//label/span[text()='Account Name']/following-sibling::span/following::input[1]", "new_account_save_button": "//div[contains(@class, 'slds-modal__footer')]/descendant::button[@title='Save']", "account_record_type": "//span[contains(text(), '{}')]", "new_program_enrollment_save_button": "//div[contains(@class, 'inlineFooter')]/descendant::button[@title='Save']", "affiliated_accounts_count": "//span[text()='Affiliated Accounts']/following-sibling::span[contains(@title, '(1)')]", "custom_settings_title": "//a/mark[text()='{}']", "program_enrollments_count": "//span[text()='Program Enrollments']/following-sibling::span[contains(@title, '(1)')]", "programenrollment_account": "//div[@class='autocompleteWrapper slds-grow']//input[@class=' default input uiInput uiInputTextForAutocomplete uiInput--default uiInput--input uiInput uiAutocomplete uiInput--default uiInput--lookup']", "list_of_departments": "//button[contains(@class, 'slds-button slds-button--neutral')]//span[@class=' label bBody' and text()='Next']", "tab": "//div[@class='uiTabBar']/ul[@class='tabs__nav']/li[contains(@class,'uiTabItem')]/a[@class='tabHeader']/span[contains(text(), '{}')]", "account_list": '//tbody/tr/th[.//span[contains(@class, "slds-grid")]]/descendant::a[text()="{}"]', "header_field_value": '//*[contains(@class, "slds-page-header__detail")][.//*[@title="{}"]]//*[text()="{}"]', "modal": { "checkbox": '//div[contains(@class,"uiInputCheckbox")]/label/span[text()="{}"]/../following-sibling::input[@type="checkbox"]', "save": "//div[contains(@class, 'footer') or contains(@class, 'Footer')]/descendant::button[@title='Save']", }, "accounts_contacts_settings_locators": { "copy_from": "//select[@class='contact-preferred-phone-picklist-input-select select uiInput uiInputSelect uiInput--default uiInput--select']", "disable_checked": "(//span[text()='Disable Preferred Phone enforcement']/following::div/div/div/label/input/following-sibling::span)[1]", "disable_preferred_phone": "//div/span[text()='Disable Preferred Phone enforcement']/following::div[1]/div/div/label/span/img[@alt='False']", "enhanced_preferred_clear": "//div/span[text()='Enable Enhanced Preferred Phone Functionality']/following::div[1]/div/div/label/span/img[@alt='False']", "enhanced_preferred_clear_faux": "//span[text()='Enable Enhanced Preferred Phone Functionality']/following::div[1]/div/div/label/input/following::span[1]", "enhanced_preferred_set": "//span[text()='Enable Enhanced Preferred Phone Functionality']/following::div[1]/div/div/label/span/img[@alt='True']", "enhanced_preferred_set_faux": "//span[text()='Enable Enhanced Preferred Phone Functionality']/following::div[1]/div/div/label/input/following::span[1]", "preferred_phone_active": "//div/span[text()='Disable Preferred Phone enforcement']/following::div[1]/div/div/label/span/img[@alt='True']", }, "relationships_settings_locators": { "sub_tab": "//div[@id='relTabs']/descendant::li[contains(@class, 'slds-text-heading--label')]/a[text()='{}']", }, "contacts_locators": { "contact_save": "//div[contains(@class,'modal-footer')]//button[@title='Save']//span[text()='Save']", "header": "//a[@title='Contacts']//span", "select_contact": "//a[@title='{} {}']", "preferred_phone": "//span//span[contains(text(),'Preferred Phone')]", "preferred_phone_home_dropdown": "//span//span[contains(text(),'Preferred Phone')]/following::span/following::a", "preferred_tab": "//div[@class='select-options']/descendant::a[@title='Home Phone']", "phone_verify_has_number": "(//div//span[text()='Phone']/../following-sibling::div//span[not( text()='123-123-1234')])[1]", "preferred_error_message": "//li[contains(text(), 'The phone selected for Preferred Phone can')]", "which_preferred_error_message": "//li[contains(text(), 'Tell us which Phone is preferred.')]", "field_for_work_phone": "//div//label//span[contains(text(),'Work Phone')]/../following-sibling::input", "which_footer_cancel": "//div[contains(@class,'footer')]/button[@title='Cancel']//span[text()='Cancel']", "footer_save": "//div[contains(@class,'modal-footer')]//span[text()='Save']", "accounts_contacts": "//a[contains(text(),'Accounts and Contacts')]", "details_tab": "//div[contains(@class,'normal')]//span[@class='title' and text()='Details']", "phone_home": "//span[text()='Home Phone']/../following-sibling::input", "run_cleanup": "//button[text()='Run Cleanup']", "phone_verify": "//div//span[text()='Home Phone']/../following-sibling::div//span//span[text()='123-123-1234']", "home_phone_verify": "//span[text()='Home Phone']/../following::div//span//span[text()='123-123-1234']", "successful_run": "//span[text()='The process was queued successfully. An email will be sent at the completion of the job.']", "apex_jobs": "//a/mark[text()='{}']", "primary_business_organization": "(//span[text()='Primary Business Organization']/following::div/div/div/div/input[@title='Search Accounts'])[1]", "button_save_affiliation": "//button[@title='Save']//span[text()='Save']", "delete_icon": "//span[@class='deleteIcon']", }, "affiliations_locators": { "header": "//a[@title='EDA Settings']//span", "tab": "//div[@id='tabs']/descendant::li[contains(@class, 'slds-text-heading--label')]/a[text()='{}']", "edit": "//button[contains(@class, 'slds-button') and @type='button']/span[text()='Edit']/..", "checkbox": "//span[text()='{}']/../following-sibling::div/descendant::label[contains(@class,'slds-checkbox')]/span[contains(@class, 'slds-checkbox--faux')]", "save": "//div[contains(@class, 'slds-page-header')]/descendant::button[contains(@class, 'settings-save-bttn')]", "sub_tab": "//div[@id='afflTabs']/descendant::li[contains(@class, 'slds-text-heading--label')]/a[text()='{}']", "edit_button": "//div[@class='slds-button-group']//span[contains(text(), 'Edit')]", "save_button": "//div[@class='slds-button-group']//span[contains(text(), 'Save')]", "un_ert_validation": "//span/img[@class='affl-record-type-enforced unchecked' and @alt='False']", "un_delete_rec_affl": "//span/img[@class='delete-prog-enroll unchecked' and @alt='False']", "specify_role_for_c_affl": "(//div/div/span[text()='Specify Role for Created Affiliations']/following::span)[1]/img[@class='copy-start-date checked' and @alt='True']", "copy_affl_end_date": "//span/img[@class='copy-end-date checked' and @alt='True']", "copy_affl_start_date": "(//div/div/span[text()='Copy Affiliation Start Date from Program Enrollment']/following::span)[1]/img[@class='copy-start-date checked' and @alt='True']", "affiliations_former": "//div/div/following::div/span[text()='Former']", "affiliations_student": "(//div/div/span[@class='uiOutputText' and text()='Role Specified for Created Affiliations']/following::div[@class='slds-col slds-size--1-of-2'])[1]/span[text()='Student']", "affiliations_current": "//div/div/following::div[@class='slds-col slds-size--1-of-2']/span[text()='Current']", "account_record_type_academic_program": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='Academic Program']", "contact_primary_affl_field_primary_academic_program": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Academic Program']", "auto_enroll_academic_program": "//div/span[text()='Primary Academic Program']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll checked' and @alt='True']", "auto_enrollment_edit_mode_status_academic_program": "(//span[text()='Primary Affl Field: Primary Academic Program']/../../../following-sibling::div/following-sibling::div/div/label/span[text()='Status: Current']/following::input)[1]", "ae_em_status_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "auto_enrollment_edit_mode_role_academic_program": "(//span[text()='Primary Affl Field: Primary Academic Program']/../../../following-sibling::div/following-sibling::div/div/label/span[text()='Role: Student']/following::input)[1]", "ae_em_role_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "auto_enrollment_read_mode_status_academic_program": "(//div/span[text()='Primary Academic Program']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='Current']", "auto_enrollment_read_mode_role_academic_program": "(//div/span[text()='Primary Academic Program']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='Student']", "account_record_type_business_organization": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='Business Organization']", "contact_primary_affl_field_primary_business_organization": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Business Organization']", "auto_enroll_business_organization": "//div/span[text()='Primary Business Organization']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "ae_em_bo_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-acc-rec-type input']", "auto_enrollment_edit_mode_role_business_organization": "(//span[text()='Primary Affl Field: Primary Business Organization']/../../../following-sibling::div/following-sibling::div/following-sibling::div//span[text()='Role: ']/following::input)[1]", "ae_em_pbo_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-affl-field input']", "auto_enrollment_read_mode_status_business_organization": "(//div/span[text()='Primary Business Organization']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='']", "ae_enroll_bo_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "auto_enrollment_read_mode_role_business_organization": "(//div/span[text()='Primary Business Organization']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='']", "ae_enroll_bo_status_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "account_record_type_educational_institution": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='Educational Institution']", "contact_primary_affl_field_primary_educational_institution": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Educational Institution']", "auto_enroll_educational_institution": "//div/span[text()='Primary Educational Institution']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "auto_enrollment_read_mode_status_educational_institution": "(//div/span[text()='Primary Educational Institution']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='']", "auto_enrollment_read_mode_role_educational_institution": "(//div/span[text()='Primary Educational Institution']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='']", "ei_art_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-acc-rec-type input']", "ei_cpaf_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-affl-field input']", "ei_aes_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "ed_aer_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "account_record_type_household_account": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='Household Account']", "contact_primary_affl_field_primary_household": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Household']", "auto_enroll_household_account": "//div/span[text()='Primary Household']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "auto_enrollment_read_mode_status_household_account": "(//div/span[text()='Primary Household']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='']", "auto_enrollment_read_mode_role_household_account": "(//div/span[text()='Primary Household']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='']", "ha_art_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-acc-rec-type input']", "ha_cpaf_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-affl-field input']", "ha_aes_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "ha_aer_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "account_record_type_sports_organization": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='Sports Organization']", "contact_primary_affl_field_primary_sports_organization": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Sports Organization']", "auto_enroll_sports_organization": "//div/span[text()='Primary Sports Organization']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "auto_enrollment_read_mode_status_sports_organization": "(//div/span[text()='Primary Sports Organization']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='']", "auto_enrollment_read_mode_role_sports_organization": "(//div/span[text()='Primary Sports Organization']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='']", "so_art_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-acc-rec-type input']", "pso_cpaf_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-affl-field input']", "so_aes_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "so_aer_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "account_record_type_university_department": "//span[@class='mapping-acc-rec-type uiOutputText' and text()='University Department']", "contact_primary_affl_field_primary_department": "//span[@class='mapping-affl-field uiOutputText' and text()='Primary Department']", "auto_enroll_university_department": "//div/span[text()='Primary Department']/../following-sibling::div[1]//span/img[@class='mapping-auto-enroll unchecked' and @alt='False']", "auto_enrollment_read_mode_status_university_department": "(//div/span[text()='Primary Department']/../following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-status uiOutputText' and text()='']", "auto_enrollment_read_mode_role_university_department": "(//div/span[text()='Primary Department']/../following-sibling::div/following-sibling::div/following-sibling::div)[1]/span[@class='mapping-enroll-role uiOutputText' and text()='']", "ud_art_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-acc-rec-type input']", "ud_cpaf_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-affl-field input']", "ud_aes_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-status input']", "ud_aer_em_empty": "(//div[@class='slds-tabs__content slds-show']/div[@class='slds-grid slds-wrap']/div/following::div/label/input/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div/following::div)[1]//label/following-sibling::input[@class='mapping-enroll-role input']", "account_record_type_input": "//label/span[text()='Account Record Type']/../following-sibling::input", "primary_affl_field_input": "//label/span[text()='Primary Affl Field']/../following-sibling::input", "auto_enrollment": "(//label/span[text()='Auto-Enrollment']/following::br/following::div/label/input/following-sibling::span)[1][@class='slds-checkbox--faux']", "status_mapping_field_input": "//label/span[text()='Status']/../following-sibling::input", "role_mapping_field_input": "//label/span[text()='Role']/../following-sibling::input", "acc_record_type": "//label/span[text()='Acc Record Type: {}']/following::input[1][@class='mapping-acc-rec-type input' and @type='text']", "contact_primary_affl_field": "//label/span[text()='Primary Affl Field: {}']/following::input[1][@class='mapping-affl-field input' and @type='text']", "art_ap_input_affl_empty": "(//label/span[text()='Acc Record Type: ']/following::input[1][@class='mapping-acc-rec-type input' and @type='text'])[1]", "paf_pap_input_affl_empty": "(//label/span[text()='Primary Affl Field: ']/following::input[1][@class='mapping-affl-field input' and @type='text'])[1]", } }
[ 37811, 15181, 2024, 329, 8225, 705, 1828, 37227, 198, 198, 18082, 62, 2588, 62, 17946, 2024, 796, 1391, 198, 220, 220, 220, 366, 1324, 62, 40927, 1298, 366, 1003, 505, 12, 1324, 12, 38722, 2044, 12, 4666, 282, 1003, 505, 12, 1324, 1...
2.497148
20,509
''' Things to do: An exe / chrome extension automatically run the script Automatically export the text file to a server/client. ''' from pynput.keyboard import Key, Listener count = 0 keys = [] with Listener(on_press = on_press, on_release = on_release) as listener: listener.join()
[ 201, 198, 7061, 6, 201, 198, 22248, 284, 466, 25, 201, 198, 220, 220, 220, 1052, 409, 68, 1220, 32030, 7552, 220, 201, 198, 220, 220, 220, 6338, 1057, 262, 4226, 201, 198, 220, 220, 220, 17406, 4142, 10784, 262, 2420, 2393, 284, 2...
2.620968
124
# -*- coding: utf-8 -*- """ Created on Sat Mar 6 21:10:57 2021 @author: geoto """ #clear list item=mylist3.clear() print(item) print('-----------------------------------------------') #reverse list print(mylist) list_rev=mylist.reverse()#reverse() used inplace=True so the change takes immediate effect on mylist print(mylist) listaa=[19,5,34,74,2,43] print(listaa) xxx=listaa.sort() #sort() used inplace=True so the change takes immediate effect on the listaa #sort list print(listaa) #to avoid that we can use the sorted() method as inplace=false in this case a_list=[1,5,9,3,8,4] print(sorted(a_list)) print(a_list) # create list with zeros zero_list=[0]*3 print(zero_list) # adding lists f_list=[1,2,3,4,5] s_list=[6,7,8,9,10] n_list=f_list+s_list print(n_list) # new list part of original list o_list=[1,2,3,4,5,6,7,8,9,10] n_list=o_list[3:7] #returns 4,5,6,7 (indices,3,4,5,6) print(n_list) lstrev=o_list[::-1]#returns list elements in reverse order lst2=o_list[::2]# returns list elements of step 2 print(lstrev) print(lst2) # if list b = list a, then changes will be applied to both lists list_a=[1,2,3,4,5] list_b=list_a list_b.insert(0,0) print(list_a) print(list_b) print('\r') #with copy list_a=[1,2,3,4,5] list_b=list_a.copy() list_b.insert(0,0) print(list_a) print(list_b) #with list list_a=[1,2,3,4,5] list_b=list(list_a) list_b.insert(0,0) print(list_a) print(list_b) # with slices #with copy list_a=[1,2,3,4,5] list_b=list_a[:] list_b.insert(0,0) print(list_a) print(list_b) # calculation within lists first_list=[1,2,3,4,5] second_list=[x*x*x for x in first_list] print(second_list)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 41972, 319, 7031, 1526, 220, 718, 2310, 25, 940, 25, 3553, 33448, 201, 198, 201, 198, 31, 9800, 25, 4903, 2069, 201, 198, 37811, 201, 198, 220, ...
2.107407
810
from pathlib import Path from typing import Dict, Optional, Sequence, Tuple from warnings import simplefilter import matplotlib.pyplot as plt import numpy as np import pandas as pd from statsmodels.regression.linear_model import OLS from statsmodels.tools import add_constant from tqdm import tqdm import etl from epimargin.estimators import analytical_MPVS from epimargin.etl.commons import download_data from epimargin.etl.covid19india import data_path, get_time_series, load_all_data from epimargin.model import Model, ModelUnit from epimargin.plots import PlotDevice, plot_RR_est, plot_T_anomalies from epimargin.smoothing import convolution from epimargin.utils import cwd, days simplefilter("ignore") root = cwd() data = root/"data" figs = root/"figs" gamma = 0.2 smoothing = 12 CI = 0.95 # private data state_cases = pd.read_csv(data/"Bihar_cases_data_Jul23.csv", parse_dates=["date_reported"], dayfirst=True) state_ts = state_cases["date_reported"].value_counts().sort_index() district_names, population_counts, _ = etl.district_migration_matrix(data/"Migration Matrix - District.csv") populations = dict(zip(district_names, population_counts)) # first, look at state level predictions ( dates, RR_pred, RR_CI_upper, RR_CI_lower, T_pred, T_CI_upper, T_CI_lower, total_cases, new_cases_ts, anomalies, anomaly_dates ) = analytical_MPVS(state_ts, CI = CI, smoothing = convolution(window = smoothing)) plot_RR_est(dates, RR_pred, RR_CI_upper, RR_CI_lower, CI, ymin=0, ymax=4)\ .title("Bihar: Reproductive Number Estimate Comparisons")\ .xlabel("Date")\ .ylabel("Rt", rotation=0, labelpad=20) plt.ylim(0, 4) # public data paths = { "v3": [data_path(_) for _ in (1, 2)], "v4": [data_path(_) for _ in range(3, 13)] } for target in paths['v3'] + paths['v4']: download_data(data, target) dfn = load_all_data( v3_paths = [data/filepath for filepath in paths['v3']], v4_paths = [data/filepath for filepath in paths['v4']] ) state_ts = get_time_series(dfn, "detected_state").loc["Bihar"] district_names, population_counts, _ = etl.district_migration_matrix(data/"Migration Matrix - District.csv") populations = dict(zip(district_names, population_counts)) # first, look at state level predictions (dates_public, RR_pred_public, RR_CI_upper_public, RR_CI_lower_public, T_pred_public, T_CI_upper_public, T_CI_lower_public, total_cases_public, new_cases_ts_public, anomalies_public, anomaly_dates_public) = analytical_MPVS(state_ts.Hospitalized, CI = CI, smoothing = convolution(window = smoothing)) plt.plot(dates_public, RR_pred_public, label = "Estimated $R_t$", color = "midnightblue") plt.fill_between(dates_public, RR_CI_lower_public, RR_CI_upper_public, label = f"{100*CI}% CI", color = "midnightblue", alpha = 0.3) plt.legend(["private data estimate", "public data estimate"]) plt.show() np.random.seed(33) Bihar = Model([ModelUnit("Bihar", 99_000_000, I0 = T_pred[-1], RR0 = RR_pred[-1], mobility = 0)]) Bihar.run(14, np.zeros((1,1))) t_pred = [dates[-1] + pd.Timedelta(days = i) for i in range(len(Bihar[0].delta_T))] Bihar[0].lower_CI[0] = T_CI_lower[-1] Bihar[0].upper_CI[0] = T_CI_upper[-1] plot_T_anomalies(dates, T_pred, T_CI_upper, T_CI_lower, new_cases_ts, anomaly_dates, anomalies, CI) plt.scatter(t_pred, Bihar[0].delta_T, color = "tomato", s = 4, label = "Predicted Net Cases") plt.fill_between(t_pred, Bihar[0].lower_CI, Bihar[0].upper_CI, color = "tomato", alpha = 0.3, label="99% CI (forecast)") PlotDevice().title("Bihar Net Daily Cases: Private Data Projection vs. Public Reported Data").xlabel("Date").ylabel("Cases") plt.plot(dates_public, new_cases_ts_public, "k-", alpha = 0.6, label="Empirical Public Data") plt.legend() plt.semilogy() plt.ylim(0, 2000) plt.show() # # now, do district-level estimation # smoothing = 10 # district_time_series = state_cases.groupby(["geo_reported", "date_reported"])["date_reported"].count().sort_index() # migration = np.zeros((len(district_names), len(district_names))) # estimates = [] # max_len = 1 + max(map(len, district_names)) # with tqdm([etl.replacements.get(dn, dn) for dn in district_names]) as districts: # for district in districts: # districts.set_description(f"{district :<{max_len}}") # try: # (dates, RR_pred, RR_CI_upper, RR_CI_lower, *_) = analytical_MPVS(district_time_series.loc[district], CI = CI, smoothing = convolution(window = smoothing)) # estimates.append((district, RR_pred[-1], RR_CI_lower[-1], RR_CI_upper[-1], project(dates, RR_pred, smoothing))) # except (IndexError, ValueError): # estimates.append((district, np.nan, np.nan, np.nan, np.nan)) # estimates = pd.DataFrame(estimates) # estimates.columns = ["district", "Rt", "Rt_CI_lower", "Rt_CI_upper", "Rt_proj"] # estimates.set_index("district", inplace=True) # estimates.to_csv(data/"Rt_estimates.csv") # print(estimates)
[ 6738, 3108, 8019, 1330, 10644, 198, 6738, 19720, 1330, 360, 713, 11, 32233, 11, 45835, 11, 309, 29291, 198, 6738, 14601, 1330, 2829, 24455, 198, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 299, 32152, 355, ...
2.571354
1,913
#!/usr/bin/env python3 # Copyright 2021 Steve Palmer """Generate a complete list of test numbers and names.""" import collections import inspect import generic_testing TestRecord = collections.namedtuple("TestRecord", ["class_", "testname", "test_number"]) if __name__ == "__main__": Main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 15069, 33448, 6542, 18918, 198, 198, 37811, 8645, 378, 257, 1844, 1351, 286, 1332, 3146, 290, 3891, 526, 15931, 198, 198, 11748, 17268, 198, 11748, 10104, 198, 198, 11748, 14276, ...
3.318681
91
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """An example of using custom classes and coder for grouping operations. This workflow demonstrates registration and usage of a custom coder for a user- defined class. A deterministic custom coder is needed to use a class as a key in a combine or group operation. This example assumes an input file with, on each line, a comma-separated name and score. """ from __future__ import absolute_import import argparse import logging import sys import apache_beam as beam from apache_beam import coders from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_beam.typehints import typehints from apache_beam.typehints.decorators import with_output_types from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions class Player(object): """A custom class used as a key in combine/group transforms.""" class PlayerCoder(coders.Coder): """A custom coder for the Player class.""" def encode(self, o): """Encode to bytes with a trace that coder was used.""" # Our encoding prepends an 'x:' prefix. return 'x:%s' % str(o.name) # Annotate the get_players function so that the typehint system knows that the # input to the CombinePerKey operation is a key-value pair of a Player object # and an integer. @with_output_types(typehints.KV[Player, int]) def run(args=None): """Runs the workflow computing total points from a collection of matches.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument('--input', required=True, help='Input file to process.') parser.add_argument('--output', required=True, help='Output file to write results to.') known_args, pipeline_args = parser.parse_known_args(args) # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level). pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True with beam.Pipeline(options=pipeline_options) as p: # Register the custom coder for the Player class, so that it will be used in # the computation. coders.registry.register_coder(Player, PlayerCoder) (p # pylint: disable=expression-not-assigned | ReadFromText(known_args.input) # The get_players function is annotated with a type hint above, so the type # system knows the output type of the following operation is a key-value # pair of a Player and an int. Please see the documentation for details on # types that are inferred automatically as well as other ways to specify # type hints. | beam.Map(get_players) # The output type hint of the previous step is used to infer that the key # type of the following operation is the Player type. Since a custom coder # is registered for the Player class above, a PlayerCoder will be used to # encode Player objects as keys for this combine operation. | beam.CombinePerKey(sum) | beam.Map(lambda (k, v): '%s,%d' % (k.name, v)) | WriteToText(known_args.output)) if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run()
[ 2, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428, 670, 329, 3224, 1321, 5115, 6634, 9238, 13, 198, 2, 383, ...
3.253968
1,260
# -*- coding: utf-8 -*- # Generated by Django 1.11.22 on 2019-11-21 23:29 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 1157, 13, 1828, 319, 13130, 12, 1157, 12, 2481, 2242, 25, 1959, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198...
2.923077
65
import http from unittest.mock import Mock, patch import pytest from django.conf import settings from django.test import override_settings from django.urls import reverse from rest_framework import status from buyer import models from core.tests.test_views import reload_module, reload_urlconf @pytest.mark.django_db @patch('sigauth.helpers.RequestSignatureChecker.test_signature', Mock(return_value=True)) @pytest.mark.django_db @patch('sigauth.helpers.RequestSignatureChecker.test_signature', Mock(return_value=True)) @patch('core.views.get_file_from_s3') @override_settings(STORAGE_CLASS_NAME='default') @override_settings(AWS_STORAGE_BUCKET_NAME_DATA_SCIENCE='my_db_buket')
[ 11748, 2638, 198, 6738, 555, 715, 395, 13, 76, 735, 1330, 44123, 11, 8529, 198, 198, 11748, 12972, 9288, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9288, 1330, 20957, 62, 33692, 198, 6738, 42625, 14208,...
2.9869
229
import mock from mock import patch import unittest from cfgm_common.vnc_db import DBBase from svc_monitor import config_db from svc_monitor import loadbalancer_agent from vnc_api.vnc_api import * import argparse import ConfigParser # end setUp # end tearDown # end create_pool #end create_hm_obj # end create_hm # end update_pool # end update_vip # end create_pool_members # end create_pool_member # end create_project # end create_vn # end obj_to_dict # end create_vmi # end create_iip # end create_vip # end test_add_delete_pool_with_members_vip # end test_add_delete_pool_with_members_vip_hm # end test_update_pool # Test the case where vip is deleted before the pool # end test_update_pool # end test_update_pool_members_add_delete # end test_update_pool_member_props # end test_update_pool_members_add_delete # end test_update_vip # end test_update_vip # end test_update_vip_persistance_type # end test_add_delete_pool_with_members_vip_hm # end test_add_delete_multiple_pools #end F5LBTest(unittest.TestCase):
[ 11748, 15290, 198, 6738, 15290, 1330, 8529, 198, 11748, 555, 715, 395, 198, 6738, 30218, 39870, 62, 11321, 13, 85, 10782, 62, 9945, 1330, 20137, 14881, 198, 6738, 264, 28435, 62, 41143, 1330, 4566, 62, 9945, 198, 6738, 264, 28435, 62, ...
2.566893
441
#!/usr/bin/env python from docutils.core import publish_string, publish_parts from docutils.readers.standalone import Reader from nose.config import Config from nose.plugins.manager import BuiltinPluginManager import nose import nose.commands import nose.tools import os import re import time doc_word.priority = 100 root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) print "Main..." tpl = open(os.path.join(root, 'index.html.tpl'), 'r').read() pat = re.compile(r'^.*(Basic usage)', re.DOTALL) txt = nose.__doc__.replace(':: python','::') txt = pat.sub(r'\1', txt) # cut from 'about the name' down (goes to end of page) pat = re.compile(r'^(.*?)(About the name.*$)', re.DOTALL) txt, coda = pat.search(txt).groups() docs = publish_parts(txt, reader=DocReader(), writer_name='html') docs.update({'version': nose.__version__, 'date': time.ctime()}) docs['coda'] = publish_parts(coda, writer_name='html')['body'] #print "Tools..." #tools = publish_parts(nose.tools.__doc__, writer_name='html') #docs['tools'] = tools['body'] print "Commands..." cmds = publish_parts(nose.commands.__doc__, reader=DocReader(), writer_name='html') docs['commands'] = cmds['body'] print "Changelog..." changes = open(os.path.join(root, 'CHANGELOG'), 'r').read() changes_html = publish_parts(changes, reader=DocReader(), writer_name='html') docs['changelog'] = changes_html['body'] print "News..." news = open(os.path.join(root, 'NEWS'), 'r').read() news_html = publish_parts(news, reader=DocReader(), writer_name='html') docs['news'] = news_html['body'] print "Usage..." conf = Config(plugins=BuiltinPluginManager()) usage_txt = conf.help(nose.main.__doc__).replace( 'mkindex.py', 'nosetests') docs['usage'] = '<pre>%s</pre>' % usage_txt out = tpl % docs index = open(os.path.join(root, 'index.html'), 'w') index.write(out) index.close() readme = open(os.path.join(root, 'README.txt'), 'w') readme.write(nose.__doc__) readme.close()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 2205, 26791, 13, 7295, 1330, 7715, 62, 8841, 11, 7715, 62, 42632, 198, 6738, 2205, 26791, 13, 961, 364, 13, 1481, 17749, 1330, 25342, 198, 6738, 9686, 13, 11250, 1330, 17056...
2.65906
745
# Generated by Django 3.1.13 on 2021-09-21 15:33 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 1485, 319, 33448, 12, 2931, 12, 2481, 1315, 25, 2091, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295,...
2.840909
44
"""Simulation where an agent will get all collectibles spawn randomly """ import sys sys.path.append("../") from westworld.environment import GridEnvironment from westworld.agents import BaseGridAgent from westworld.objects import BaseObstacle,BaseTrigger,BaseCollectible from westworld.simulation import Simulation from westworld.colors import * #================================================================================================== # BASE CLASSES #================================================================================================== #================================================================================================== # SIMULATION #================================================================================================== # Setup agents agent = Agent(1,1,color = RED) # Setup collectibles as random spawner collectible_spawner = lambda x,y : Collectible(x,y,color = WHITE) # Setup environment env = GridEnvironment(20,10,30,objects = [agent]) env.spawn(collectible_spawner,10) env.render() # Prepare simulation sim = Simulation(env,fps = 30,name="CollectiblesSimple") if __name__ == "__main__": sim.run_episode(n_steps = 200,save = True)
[ 37811, 8890, 1741, 810, 281, 5797, 481, 651, 477, 2824, 18764, 10922, 15456, 198, 37811, 628, 198, 198, 11748, 25064, 198, 17597, 13, 6978, 13, 33295, 7203, 40720, 4943, 198, 198, 6738, 7421, 6894, 13, 38986, 1330, 24846, 31441, 198, 67...
4.160535
299
# AUTHOR = PAUL KEARNEY # STUDENT ID = G00364787 # DATE = 2018-02-24 # # STUDENT ID = G00364787 # EXERCISE 04 # projectEuler problem 2 # references used # http://www.tutorialspoint.com/python/python_basic_operators.htm # https://www.tutorialspoint.com/python/python_strings.htm # https://stackoverflow.com/questions/9120059/odd-even-string-python # # function to calculate the FIBONACCI value for input value n def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i # setup working storage num = 0 total = 0 result = 0 total = 0 ok = 1 opStr = "" # main routine while result < 4000000 and ok == 1: result = fib(num) if (result < 4000000): if (result %2 == 0 ): total = total+result else: ok = 0 num = num + 1 # program output to screen opStr = "The sum of the even numbers 'under' 4 million is "+ str(total) print(opStr)
[ 2, 44746, 796, 8147, 6239, 509, 17133, 36231, 220, 220, 201, 198, 2, 49348, 3525, 4522, 796, 402, 11245, 2414, 41019, 201, 198, 2, 360, 6158, 796, 2864, 12, 2999, 12, 1731, 201, 198, 2, 201, 198, 2, 49348, 3525, 4522, 796, 402, 11...
2.294118
459
def plot_tuning_curve(resp, ori, ax=None): """Plot single neuron responses as a function of stimulus orientation Args: resp (numpy array): n_stimuli x n_neurons matrix with responses of each neuron whose tuning curve to plot. Can also be a 1D array of length n_stimuli to plot tuning curve of a single neuron. ori (numpy array): 1D array of length stimuli with orientations of each stimulus, in radians ax (matplotlib axes): axes onto which to plot """ if ax is None: ax = plt.gca() ax.plot(np.rad2deg(ori), resp, '.-') ax.set_xticks(np.linspace(-90, 90, 5)) ax.set_xlabel('stimulus orientation') ax.set_ylabel('neuron response') def plot_dim_reduction(resp, ori, ax=None): """Plot dimensionality-reduced population responses (using tSNE) Args: resp (numpy array): n_stimuli x n_neurons matrix with population responses ori (numpy array): 1D array of length stimuli with orientations of each stimulus, in radians ax (matplotlib axes): axes onto which to plot """ if ax is None: ax = plt.gca() # First do PCA to reduce dimensionality to 200 dimensions so that tSNE is faster resp_lowd = PCA(n_components=min(200, resp.shape[1])).fit_transform(resp) # Then do tSNE to reduce dimensionality to 2 dimensions resp_lowd = TSNE(n_components=2).fit_transform(resp_lowd) # Plot dimensionality-reduced population responses # on 2D axes, with each point colored by stimulus orientation scat = ax.scatter(resp_lowd[:, 0], resp_lowd[:, 1], c=np.rad2deg(ori), cmap='twilight') cbar = plt.colorbar(scat, ax=ax, label='stimulus orientation') ax.set_xlabel('dimension 1') ax.set_ylabel('dimension 2') ax.set_xticks([]) ax.set_yticks([]) # Aggregate all responses into one dict resp_dict = {} resp_dict['V1 data'] = resp_v1 for k, v in resp_model.items(): label = 'model\nlayer %s' % k resp_dict[label] = v # Plot tuning curves and dimensionality-reduced responses next to each other with plt.xkcd(): figsize = 4 fig, axs = plt.subplots(2, len(resp_dict), figsize=(len(resp_dict) * figsize, 2 * figsize)) for i, (label, resp) in enumerate(resp_dict.items()): axs[0, i].set_title('%s responses' % label) # Plot tuning curves of three random neurons ineurons = np.random.choice(resp.shape[1], 3, replace=False) # indices of three random neurons plot_tuning_curve(resp[:, ineurons], ori, axs[0, i]) # Plot dimensionality-reduced population responses plot_dim_reduction(resp, ori, axs[1, i]) plt.tight_layout() plt.show()
[ 4299, 7110, 62, 28286, 278, 62, 22019, 303, 7, 4363, 11, 22812, 11, 7877, 28, 14202, 2599, 198, 220, 37227, 43328, 2060, 43164, 9109, 355, 257, 2163, 286, 19819, 12852, 628, 220, 943, 14542, 25, 198, 220, 220, 220, 1217, 357, 77, 32...
2.805464
915
# # @section License # # The MIT License (MIT) # # Copyright (c) 2016-2017, Erik Moqvist # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # This file is part of the Pumbaa project. # import harness from harness import assert_raises import ssl import socket import socket_stub TESTCASES = [ (test_print, "test_print"), (test_client, "test_client"), (test_server, "test_server") ]
[ 2, 198, 2, 2488, 5458, 13789, 198, 2, 198, 2, 383, 17168, 13789, 357, 36393, 8, 198, 2, 198, 2, 15069, 357, 66, 8, 1584, 12, 5539, 11, 22722, 4270, 44179, 396, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, ...
3.475369
406
#!/usr/bin/env python #-*- coding:utf-8 -*- __author__ = 'weihaoxuan' from celery import task from confile_process import process import models import os # import ansible_api @task @task @task @task @task @task @task @task @task
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 12, 9, 12, 19617, 25, 40477, 12, 23, 532, 9, 12, 198, 834, 9800, 834, 796, 705, 42990, 3099, 1140, 7258, 6, 198, 198, 6738, 18725, 1924, 1330, 4876, 198, 6738, 1013, 576, 62, ...
2.474227
97
"""Build and Version QuerySet classes.""" import datetime import logging from django.db import models from django.db.models import Q from django.utils import timezone from readthedocs.builds.constants import ( BUILD_STATE_FINISHED, BUILD_STATE_TRIGGERED, EXTERNAL, ) from readthedocs.core.permissions import AdminPermission from readthedocs.core.utils.extend import SettingsOverrideObject from readthedocs.projects import constants from readthedocs.projects.models import Project log = logging.getLogger(__name__) __all__ = ['VersionQuerySet', 'BuildQuerySet', 'RelatedBuildQuerySet'] class VersionQuerySetBase(models.QuerySet): """Versions take into account their own privacy_level setting.""" use_for_related_fields = True def __init__(self, *args, internal_only=False, external_only=False, **kwargs): """ Overridden to pass extra arguments from the manager. Usage: import functools ManagerClass.from_queryset( functools.partial(VersionQuerySet, internal_only=True) ) :param bool internal_only: If this queryset is being used to query internal versions only. :param bool external_only: If this queryset is being used to query external versions only. """ self.internal_only = internal_only self.external_only = external_only super().__init__(*args, **kwargs) def _add_from_user_projects(self, queryset, user, admin=False, member=False): """Add related objects from projects where `user` is an `admin` or a `member`.""" if user and user.is_authenticated: projects_pk = ( AdminPermission.projects( user=user, admin=admin, member=member, ) .values_list('pk', flat=True) ) user_queryset = self.filter(project__in=projects_pk) queryset = user_queryset | queryset return queryset def public( self, user=None, project=None, only_active=True, include_hidden=True, only_built=False, ): """ Get all allowed versions. .. note:: External versions use the `Project.external_builds_privacy_level` field instead of its `privacy_level` field. """ queryset = self._public_only() if user: if user.is_superuser: queryset = self.all() else: queryset = self._add_from_user_projects(queryset, user) if project: queryset = queryset.filter(project=project) if only_active: queryset = queryset.filter(active=True) if only_built: queryset = queryset.filter(built=True) if not include_hidden: queryset = queryset.filter(hidden=False) return queryset.distinct() class BuildQuerySet(models.QuerySet): """ Build objects that are privacy aware. i.e. they take into account the privacy of the Version that they relate to. """ use_for_related_fields = True def _add_from_user_projects(self, queryset, user, admin=False, member=False): """Add related objects from projects where `user` is an `admin` or a `member`.""" if user and user.is_authenticated: projects_pk = ( AdminPermission.projects( user=user, admin=admin, member=member, ) .values_list('pk', flat=True) ) user_queryset = self.filter(project__in=projects_pk) queryset = user_queryset | queryset return queryset def public(self, user=None, project=None): """ Get all allowed builds. Builds are public if the linked version and project are public. .. note:: External versions use the `Project.external_builds_privacy_level` field instead of its `privacy_level` field. """ queryset = ( self.filter( version__privacy_level=constants.PUBLIC, version__project__privacy_level=constants.PUBLIC, ) .exclude(version__type=EXTERNAL) ) queryset |= self.filter( version__type=EXTERNAL, project__external_builds_privacy_level=constants.PUBLIC, project__privacy_level=constants.PUBLIC, ) if user: if user.is_superuser: queryset = self.all() else: queryset = self._add_from_user_projects( queryset, user, admin=True, member=True, ) if project: queryset = queryset.filter(project=project) return queryset.distinct() def concurrent(self, project): """ Check if the max build concurrency for this project was reached. - regular project: counts concurrent builds - translation: concurrent builds of all the translations + builds of main project .. note:: If the project/translation belongs to an organization, we count all concurrent builds for all the projects from the organization. :rtype: tuple :returns: limit_reached, number of concurrent builds, number of max concurrent """ limit_reached = False query = Q( project__slug=project.slug, # Limit builds to 5 hours ago to speed up the query date__gte=timezone.now() - datetime.timedelta(hours=5), ) if project.main_language_project: # Project is a translation, counts all builds of all the translations query |= Q(project__main_language_project=project.main_language_project) query |= Q(project__slug=project.main_language_project.slug) elif project.translations.exists(): # The project has translations, counts their builds as well query |= Q(project__in=project.translations.all()) # If the project belongs to an organization, count all the projects # from this organization as well organization = project.organizations.first() if organization: query |= Q(project__in=organization.projects.all()) concurrent = ( self.filter(query) .exclude(state__in=[BUILD_STATE_TRIGGERED, BUILD_STATE_FINISHED]) ).distinct().count() max_concurrent = Project.objects.max_concurrent_builds(project) log.info( 'Concurrent builds. project=%s running=%s max=%s', project.slug, concurrent, max_concurrent, ) if concurrent >= max_concurrent: limit_reached = True return (limit_reached, concurrent, max_concurrent) class RelatedBuildQuerySet(models.QuerySet): """ For models with association to a project through :py:class:`Build`. .. note:: This is only used for ``BuildCommandViewSet`` from api v2. Which is being used to upload build command results from the builders. """ use_for_related_fields = True
[ 37811, 15580, 290, 10628, 43301, 7248, 6097, 526, 15931, 198, 11748, 4818, 8079, 198, 11748, 18931, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 9945, 13, 27530, 1330, 1195, 198, 6738, 42625, 14208, 13,...
2.263288
3,236
"""Platform for LGE climate integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta import logging from typing import Any, Awaitable, Callable, List, Tuple from .wideq import ( FEAT_HUMIDITY, FEAT_OUT_WATER_TEMP, UNIT_TEMP_FAHRENHEIT, DeviceType, ) from .wideq.ac import AirConditionerDevice, ACMode from homeassistant.components.climate import ClimateEntity, ClimateEntityDescription from homeassistant.components.climate.const import ( ATTR_HVAC_MODE, DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, ClimateEntityFeature, HVACMode, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import LGEDevice from .const import DOMAIN, LGE_DEVICES from .device_helpers import ( TEMP_UNIT_LOOKUP, LGERefrigeratorDevice, get_entity_name, ) # general ac attributes ATTR_FRIDGE = "fridge" ATTR_FREEZER = "freezer" HVAC_MODE_LOOKUP: dict[str, HVACMode] = { ACMode.ENERGY_SAVER.name: HVACMode.AUTO, ACMode.AI.name: HVACMode.AUTO, ACMode.HEAT.name: HVACMode.HEAT, ACMode.DRY.name: HVACMode.DRY, ACMode.COOL.name: HVACMode.COOL, ACMode.FAN.name: HVACMode.FAN_ONLY, ACMode.ACO.name: HVACMode.HEAT_COOL, } ATTR_SWING_HORIZONTAL = "swing_mode_horizontal" ATTR_SWING_VERTICAL = "swing_mode_vertical" SWING_PREFIX = ["Vertical", "Horizontal"] SCAN_INTERVAL = timedelta(seconds=120) _LOGGER = logging.getLogger(__name__) @dataclass class ThinQRefClimateRequiredKeysMixin: """Mixin for required keys.""" range_temp_fn: Callable[[Any], List[float]] set_temp_fn: Callable[[Any, float], Awaitable[None]] temp_fn: Callable[[Any], float | str] @dataclass class ThinQRefClimateEntityDescription( ClimateEntityDescription, ThinQRefClimateRequiredKeysMixin ): """A class that describes ThinQ climate entities.""" REFRIGERATOR_CLIMATE: Tuple[ThinQRefClimateEntityDescription, ...] = ( ThinQRefClimateEntityDescription( key=ATTR_FRIDGE, name="Fridge", icon="mdi:fridge-top", range_temp_fn=lambda x: x.device.fridge_target_temp_range, set_temp_fn=lambda x, y: x.device.set_fridge_target_temp(y), temp_fn=lambda x: x.temp_fridge, ), ThinQRefClimateEntityDescription( key=ATTR_FREEZER, name="Freezer", icon="mdi:fridge-bottom", range_temp_fn=lambda x: x.device.freezer_target_temp_range, set_temp_fn=lambda x, y: x.device.set_freezer_target_temp(y), temp_fn=lambda x: x.temp_freezer, ), ) def remove_prefix(text: str, prefix: str) -> str: """Remove a prefix from a string.""" if text.startswith(prefix): return text[len(prefix):] return text async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up LGE device climate based on config_entry.""" entry_config = hass.data[DOMAIN] lge_devices = entry_config.get(LGE_DEVICES) if not lge_devices: return _LOGGER.debug("Starting LGE ThinQ climate setup...") lge_climates = [] # AC devices lge_climates.extend( [ LGEACClimate(lge_device) for lge_device in lge_devices.get(DeviceType.AC, []) ] ) # Refrigerator devices lge_climates.extend( [ LGERefrigeratorClimate(lge_device, refrigerator_desc) for refrigerator_desc in REFRIGERATOR_CLIMATE for lge_device in lge_devices.get(DeviceType.REFRIGERATOR, []) ] ) async_add_entities(lge_climates) class LGEClimate(CoordinatorEntity, ClimateEntity): """Base climate device.""" def __init__(self, api: LGEDevice): """Initialize the climate.""" super().__init__(api.coordinator) self._api = api self._attr_device_info = api.device_info @property def should_poll(self) -> bool: """Return True if entity has to be polled for state. We overwrite coordinator property default setting because we need to poll to avoid the effect that after changing a climate settings it is immediately set to prev state. The async_update method here do nothing because the real update is performed by coordinator. """ return True async def async_update(self) -> None: """Update the entity. This is a fake update, real update is done by coordinator. """ return @property def available(self) -> bool: """Return True if entity is available.""" return self._api.available class LGEACClimate(LGEClimate): """Air-to-Air climate device.""" def __init__(self, api: LGEDevice) -> None: """Initialize the climate.""" super().__init__(api) self._device: AirConditionerDevice = api.device self._attr_name = api.name self._attr_unique_id = f"{api.unique_id}-AC" self._attr_fan_modes = self._device.fan_speeds self._attr_swing_modes = [ f"{SWING_PREFIX[0]}{mode}" for mode in self._device.vertical_step_modes ] + [ f"{SWING_PREFIX[1]}{mode}" for mode in self._device.horizontal_step_modes ] self._hvac_mode_lookup: dict[str, HVACMode] | None = None self._support_ver_swing = len(self._device.vertical_step_modes) > 0 self._support_hor_swing = len(self._device.horizontal_step_modes) > 0 self._set_hor_swing = self._support_hor_swing and not self._support_ver_swing def _available_hvac_modes(self) -> dict[str, HVACMode]: """Return available hvac modes from lookup dict.""" if self._hvac_mode_lookup is None: modes = {} for key, mode in HVAC_MODE_LOOKUP.items(): if key in self._device.op_modes: # invert key and mode to avoid duplicated HVAC modes modes[mode] = key self._hvac_mode_lookup = {v: k for k, v in modes.items()} return self._hvac_mode_lookup def _get_swing_mode(self, hor_mode=False) -> str | None: """Return the current swing mode for vert of hor mode.""" if hor_mode: mode = self._api.state.horizontal_step_mode else: mode = self._api.state.vertical_step_mode if mode: return f"{SWING_PREFIX[1 if hor_mode else 0]}{mode}" return None @property def supported_features(self) -> int: """Return the list of supported features.""" features = ClimateEntityFeature.TARGET_TEMPERATURE if len(self.fan_modes) > 0: features |= ClimateEntityFeature.FAN_MODE if self._support_ver_swing or self._support_hor_swing: features |= ClimateEntityFeature.SWING_MODE return features @property def extra_state_attributes(self): """Return the optional state attributes with device specific additions.""" attr = {} if self._support_hor_swing: attr[ATTR_SWING_HORIZONTAL] = self._get_swing_mode(True) if self._support_ver_swing: attr[ATTR_SWING_VERTICAL] = self._get_swing_mode(False) return attr @property def target_temperature_step(self) -> float: """Return the supported step of target temperature.""" return self._device.target_temperature_step @property def temperature_unit(self) -> str: """Return the unit of measurement used by the platform.""" if self._device.temperature_unit == UNIT_TEMP_FAHRENHEIT: return TEMP_FAHRENHEIT return TEMP_CELSIUS @property def hvac_mode(self) -> HVACMode: """Return hvac operation ie. heat, cool mode.""" op_mode: str | None = self._api.state.operation_mode if not self._api.state.is_on or op_mode is None: return HVACMode.OFF modes = self._available_hvac_modes() return modes.get(op_mode, HVACMode.AUTO) async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target hvac mode.""" if hvac_mode == HVACMode.OFF: await self._device.power(False) return modes = self._available_hvac_modes() reverse_lookup = {v: k for k, v in modes.items()} operation_mode = reverse_lookup.get(hvac_mode) if operation_mode is None: raise ValueError(f"Invalid hvac_mode [{hvac_mode}]") if self.hvac_mode == HVACMode.OFF: await self._device.power(True) await self._device.set_op_mode(operation_mode) @property def hvac_modes(self) -> list[HVACMode]: """Return the list of available hvac operation modes.""" modes = self._available_hvac_modes() return [HVACMode.OFF] + list(modes.values()) @property def current_temperature(self) -> float: """Return the current temperature.""" curr_temp = None if self._device.is_air_to_water: curr_temp = self._api.state.device_features.get(FEAT_OUT_WATER_TEMP) if curr_temp is None: curr_temp = self._api.state.current_temp return curr_temp @property @property def target_temperature(self) -> float: """Return the temperature we try to reach.""" return self._api.state.target_temp async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" if hvac_mode := kwargs.get(ATTR_HVAC_MODE): await self.async_set_hvac_mode(HVACMode(hvac_mode)) if new_temp := kwargs.get(ATTR_TEMPERATURE): await self._device.set_target_temp(new_temp) @property def fan_mode(self) -> str | None: """Return the fan setting.""" return self._api.state.fan_speed async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new target fan mode.""" if fan_mode not in self.fan_modes: raise ValueError(f"Invalid fan mode [{fan_mode}]") await self._device.set_fan_speed(fan_mode) @property def swing_mode(self) -> str | None: """Return the swing mode setting.""" if self._set_hor_swing and self._support_hor_swing: return self._get_swing_mode(True) return self._get_swing_mode(False) async def async_set_swing_mode(self, swing_mode: str) -> None: """Set new target swing mode.""" avl_mode = False curr_mode = None set_hor_swing = swing_mode.startswith(SWING_PREFIX[1]) dev_mode = remove_prefix( swing_mode, SWING_PREFIX[1 if set_hor_swing else 0] ) if set_hor_swing: if dev_mode in self._device.horizontal_step_modes: avl_mode = True curr_mode = self._api.state.horizontal_step_mode elif swing_mode.startswith(SWING_PREFIX[0]): if dev_mode in self._device.vertical_step_modes: avl_mode = True curr_mode = self._api.state.vertical_step_mode if not avl_mode: raise ValueError(f"Invalid swing_mode [{swing_mode}].") if curr_mode != dev_mode: if set_hor_swing: await self._device.set_horizontal_step_mode(dev_mode) else: await self._device.set_vertical_step_mode(dev_mode) self._set_hor_swing = set_hor_swing async def async_turn_on(self) -> None: """Turn the entity on.""" await self._device.power(True) async def async_turn_off(self) -> None: """Turn the entity off.""" await self._device.power(False) @property def min_temp(self) -> float: """Return the minimum temperature.""" if (min_value := self._device.target_temperature_min) is not None: return min_value return self._device.conv_temp_unit(DEFAULT_MIN_TEMP) @property def max_temp(self) -> float: """Return the maximum temperature.""" if (max_value := self._device.target_temperature_max) is not None: return max_value return self._device.conv_temp_unit(DEFAULT_MAX_TEMP) class LGERefrigeratorClimate(LGEClimate): """Refrigerator climate device.""" entity_description = ThinQRefClimateEntityDescription def __init__( self, api: LGEDevice, description: ThinQRefClimateEntityDescription, ) -> None: """Initialize the climate.""" super().__init__(api) self._wrap_device = LGERefrigeratorDevice(api) self.entity_description = description self._attr_name = get_entity_name(api, description.key, description.name) self._attr_unique_id = f"{api.unique_id}-{description.key}-AC" self._attr_hvac_modes = [HVACMode.AUTO] self._attr_hvac_mode = HVACMode.AUTO @property def supported_features(self) -> int: """Return the list of supported features.""" if not self._wrap_device.device.set_values_allowed: return 0 return ClimateEntityFeature.TARGET_TEMPERATURE @property def target_temperature_step(self) -> float: """Return the supported step of target temperature.""" return self._wrap_device.device.target_temperature_step @property def temperature_unit(self) -> str: """Return the unit of measurement used by the platform.""" if self._api.state: unit = self._api.state.temp_unit return TEMP_UNIT_LOOKUP.get(unit, TEMP_CELSIUS) return TEMP_CELSIUS @property def current_temperature(self) -> float | None: """Return the current temperature.""" curr_temp = self.entity_description.temp_fn(self._wrap_device) if curr_temp is None: return None try: return int(curr_temp) except ValueError: return None @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self.current_temperature async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" if new_temp := kwargs.get(ATTR_TEMPERATURE): await self.entity_description.set_temp_fn(self._wrap_device, new_temp) @property def min_temp(self) -> float: """Return the minimum temperature.""" return self.entity_description.range_temp_fn(self._wrap_device)[0] @property
[ 37811, 37148, 329, 406, 8264, 4258, 11812, 526, 15931, 198, 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 4818, 330, 28958, 1330, 4818, 330, 31172, 198, 6738, 4818, 8079, 1330, 28805, 12514, 198, 11748, 18931, 198, 6738, 19720, 13...
2.325926
6,345
import copy import math import time import torch import torch.nn as nn import numpy as np from constants import * from embeddings import * from tqdm import tqdm from utils.model_utils import device, model_checkpoint from utils.misc_utils import write_line_to_file from utils.lang_utils import make_std_mask from evaluate import corpus_eval def clones(module, n): "Produce n identical layers." return nn.ModuleList([copy.deepcopy(module) for _ in range(n)]) def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) # batch_size x n_heads x seq_len x seq_len, i.e. attn score on each word if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = torch.softmax(scores, dim=-1) # batch_size x n_heads x seq_len x seq_len, softmax on last dimension, i.e. 3rd dimension attend on 4th dimension if dropout is not None: p_attn = dropout(p_attn) return torch.matmul(p_attn, value), p_attn # attended output, attention vec class NoamOpt: "Optim wrapper that implements rate." def step(self): "Update parameters and rate" self._step += 1 rate = self.rate() for p in self.optimizer.param_groups: p['lr'] = rate self._rate = rate self.optimizer.step() def rate(self, step=None): "Implement `lrate` above" if step is None: step = self._step return self.factor * \ (self.model_size ** (-0.5) * min(step ** (-0.5), step * self.warmup ** (-1.5))) class LabelSmoothing(nn.Module): "Label smoothing actually starts to penalize the model if it gets very confident about a given choice" class LayerNorm(nn.Module): "Construct a layernorm module (See citation for details)." class PositionwiseFeedForward(nn.Module): "Implements FFN equation." class SublayerConnection(nn.Module): """ A residual connection followed by a layer norm. """ def forward(self, x, sublayer_func): "Apply residual connection to any sublayer with the same size." layer_output = sublayer_func(x) residual_rv = x + self.dropout(layer_output) return self.norm(residual_rv) class PositionalEncoding(nn.Module): "Implement the PE function." class GCN(nn.Module): """ A GCN/Contextualized GCN module operated on dependency graphs. """ def forward(self, gcn_inputs, adj): """ :param adj: batch_size * num_vertex * num_vertex :param gcn_inputs: batch_size * num_vertex * input_dim :return: gcn_outputs: list of batch_size * num_vertex * hidden_dim mask: batch_size * num_vertex * 1. In mask, 1 denotes this vertex is PAD vertex, 0 denotes true vertex. """ # use out degree, assume undirected graph denom = adj.sum(2).unsqueeze(2) + 1 adj_mask = (adj.sum(2) + adj.sum(1)).eq(0).unsqueeze(2) gcn_outputs = [] for l in range(self.num_layers): Ax = adj.bmm(gcn_inputs) AxW = self.W[l](Ax) AxW = AxW + self.W[l](gcn_inputs) # self loop AxW = AxW / denom gAxW = torch.relu(AxW) gcn_inputs = self.gcn_drop(gAxW) if l < self.num_layers - 1 else gAxW gcn_outputs.append(gcn_inputs) return gcn_outputs, adj_mask class Generator(nn.Module): "Define standard linear + softmax generation step."
[ 11748, 4866, 198, 11748, 10688, 198, 11748, 640, 198, 11748, 28034, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 38491, 1330, 1635, 198, 6738, 11525, 67, 654, 1330, 1635, 198, 6738, 256, 80,...
2.382937
1,512
# This Python file uses the following encoding: utf-8 import os import sys import time from PyQt5 import QtCore from PySide2.QtCore import QFile from PySide2.QtUiTools import QUiLoader from PySide2.QtWidgets import QApplication, QWidget, QFileDialog, \ QPushButton, QLineEdit, QMessageBox, QTextBrowser, QProgressBar from openpyxl import Workbook from threads import CreateThread, ProgressThread from workers import Worker if __name__ == "__main__": app = QApplication([sys.executable]) widget = XlsxStyler() widget.show() sys.exit(app.exec_())
[ 2, 770, 11361, 2393, 3544, 262, 1708, 21004, 25, 3384, 69, 12, 23, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 198, 6738, 9485, 48, 83, 20, 1330, 33734, 14055, 198, 6738, 9485, 24819, 17, 13, 48, 83, 14055, 1330, 119...
3
190
import os import FWCore.ParameterSet.Config as cms from Configuration.StandardSequences.Eras import eras process = cms.Process('PCL',eras.Run2_2017) # ---------------------------------------------------------------------- process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.threshold = 'INFO' process.MessageLogger.cerr.FwkReport.reportEvery = 10000 process.MessageLogger.categories.append('HLTrigReport') process.MessageLogger.categories.append('L1GtTrigReport') process.options = cms.untracked.PSet( SkipEvent = cms.untracked.vstring('ProductNotFound'), wantSummary = cms.untracked.bool(True) ) # -- Conditions process.load("Configuration.StandardSequences.MagneticField_38T_cff") process.load("Configuration.StandardSequences.GeometryRecoDB_cff") process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') from Configuration.AlCa.GlobalTag import GlobalTag process.GlobalTag = GlobalTag(process.GlobalTag, '92X_dataRun2_Express_v8', '') # -- Input files process.source = cms.Source( "PoolSource", fileNames = cms.untracked.vstring( "/store/express/Run2017F/ExpressPhysics/FEVT/Express-v1/000/305/366/00000/863EC350-6EB6-E711-8EAD-02163E019B61.root", "/store/express/Run2017F/ExpressPhysics/FEVT/Express-v1/000/305/366/00000/B6268B1F-6FB6-E711-A46C-02163E01439D.root", ), #lumisToProcess = cms.untracked.VLuminosityBlockRange("305366:1-305366:1"), ) # -- number of events process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) from EventFilter.SiPixelRawToDigi.SiPixelRawToDigi_cfi import siPixelDigis process.siPixelDigis = siPixelDigis.clone() process.siPixelDigis.InputLabel = cms.InputTag("rawDataCollector") process.siPixelStatusProducer = cms.EDProducer("SiPixelStatusProducer", SiPixelStatusProducerParameters = cms.PSet( badPixelFEDChannelCollections = cms.VInputTag(cms.InputTag('siPixelDigis')), pixelClusterLabel = cms.untracked.InputTag("siPixelClusters::RECO"), monitorOnDoubleColumn = cms.untracked.bool(False), resetEveryNLumi = cms.untracked.int32( 1 ) ) ) process.ALCARECOStreamSiPixelCalZeroBias = cms.OutputModule("PoolOutputModule", fileName = cms.untracked.string('SiPixelCalZeroBias.root'), outputCommands = cms.untracked.vstring('drop *', 'keep *_siPixelStatusProducer_*_*', ) ) process.p = cms.Path(process.siPixelDigis*process.siPixelStatusProducer) process.end = cms.EndPath(process.ALCARECOStreamSiPixelCalZeroBias) process.schedule = cms.Schedule(process.p,process.end) # Add early deletion of temporary data products to reduce peak memory need from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete process = customiseEarlyDelete(process) # End adding early deletion
[ 11748, 28686, 198, 11748, 48849, 14055, 13, 36301, 7248, 13, 16934, 355, 269, 907, 198, 6738, 28373, 13, 23615, 44015, 3007, 13, 36, 8847, 1330, 49089, 198, 14681, 796, 269, 907, 13, 18709, 10786, 47, 5097, 3256, 263, 292, 13, 10987, ...
2.812
1,000
# Consider a staircase of size : # # # # ## # ### # #### # # Observe that its base and height are both equal to , and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. # # Write a program that prints a staircase of size . # # Input Format # # A single integer, , denoting the size of the staircase. # # Output Format # # Print a staircase of size using # symbols and spaces. # # Note: The last line must have spaces in it. # # Sample Input # # 6 # Sample Output # # # # ## # ### # #### # ##### # ###### # # Explanation # # The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of . # # #!/bin/python import math import os import random import re import sys # Complete the staircase function below. if __name__ == '__main__': n = int(raw_input()) staircase(n)
[ 2, 12642, 257, 27656, 286, 2546, 1058, 198, 2, 220, 198, 2, 220, 220, 220, 1303, 198, 2, 220, 220, 22492, 198, 2, 220, 44386, 198, 2, 1303, 21017, 198, 2, 220, 198, 2, 11086, 3760, 326, 663, 2779, 290, 6001, 389, 1111, 4961, 284...
2.86262
313
#! /usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2019/3/10 8:10 PM # @Author : xiaoliji # @Email : yutian9527@gmail.com """ 求1+...n, 不能用循环等。 >>> sum_solution(10) 55 """
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2488, 7575, 220, 220, 220, 220, 1058, 13130, 14, 18, 14, 940, 807, 25, 940, 3122, 198, 2, 2488, 13838, 220, 220...
1.622951
122
""" COBRA Visualisations -------------------- This notebook will cover the visulaisation and plotting offered by pycobra. """ # %matplotlib inline import numpy as np from pycobra.cobra import Cobra from pycobra.ewa import Ewa from pycobra.visualisation import Visualisation from pycobra.diagnostics import Diagnostics # setting up our random data-set rng = np.random.RandomState(42) # D1 = train machines; D2 = create COBRA; D3 = calibrate epsilon, alpha; D4 = testing n_features = 2 D1, D2, D3, D4 = 200, 200, 200, 200 D = D1 + D2 + D3 + D4 X = rng.uniform(-1, 1, D * n_features).reshape(D, n_features) # Y = np.power(X[:,1], 2) + np.power(X[:,3], 3) + np.exp(X[:,10]) Y = np.power(X[:,0], 2) + np.power(X[:,1], 3) # training data-set X_train = X[:D1 + D2] X_test = X[D1 + D2 + D3:D1 + D2 + D3 + D4] X_eps = X[D1 + D2:D1 + D2 + D3] # for testing Y_train = Y[:D1 + D2] Y_test = Y[D1 + D2 + D3:D1 + D2 + D3 + D4] Y_eps = Y[D1 + D2:D1 + D2 + D3] # set up our COBRA machine with the data cobra = Cobra(epsilon=0.5) cobra.fit(X_train, Y_train) ###################################################################### # Plotting COBRA # ~~~~~~~~~~~~~~ # # We use the visualisation class to plot our results, and for various # visualisations. # cobra_vis = Visualisation(cobra, X_test, Y_test) # to plot our machines, we need a linspace as input. This is the 'scale' to plot and should be the range of the results # since our data ranges from -1 to 1 it is such - and we space it out to a hundred points cobra_vis.plot_machines(machines=["COBRA"]) cobra_vis.plot_machines() ###################################################################### # Plots and Visualisations of Results # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # QQ and Boxplots! # cobra_vis.QQ() cobra_vis.boxplot() ###################################################################### # Plotting EWA! # ~~~~~~~~~~~~~ # # We can use the same visualisation class for seeing how EWA works. Let's # demonstrate this! # ewa = Ewa() ewa.set_beta(X_beta=X_eps, y_beta=Y_eps) ewa.fit(X_train, Y_train) ewa_vis = Visualisation(ewa, X_test, Y_test) ewa_vis.QQ("EWA") ewa_vis.boxplot() ###################################################################### # Plotting ClassifierCobra # ~~~~~~~~~~~~~~~~~~~~~~~~ # from sklearn import datasets from sklearn.metrics import accuracy_score from pycobra.classifiercobra import ClassifierCobra bc = datasets.load_breast_cancer() X_cc = bc.data[:-40] y_cc = bc.target[:-40] X_cc_test = bc.data[-40:] y_cc_test = bc.target[-40:] cc = ClassifierCobra() cc.fit(X_cc, y_cc) cc_vis = Visualisation(cc, X_cc_test, y_cc_test) cc_vis.boxplot() ###################################################################### # Remember that all the estimators in the Pycobra package are scikit-learn # compatible - we can also use the scikit-learn metrics and tools to # analyse our machines! # from sklearn.metrics import classification_report print(classification_report(y_cc_test, cc.predict(X_cc_test))) ###################################################################### # Plotting COBRA colors! # ~~~~~~~~~~~~~~~~~~~~~~ # # We're now going to experiment with plotting colors and data. After we # get information about which indices are used by which machines the best # for a fixed epsilon (or not, we can toggle this option), we can plot the # distribution of machines. # # Why is this useful? Since we're dealing with a 2-D space now, we're # attempting to see if there are some parts in the input space which are # picked up by certain machines. This could lead to interesting # experiments and # # We first present a plot where the machine colors are mixed depending on # which machines were selected; after which we plot one machine at a time. # indices, MSE = cobra_vis.indice_info(X_test=X_eps[0:50], y_test=Y_eps[0:50], epsilon=0.50) cobra_vis.color_cobra(X_test=X_eps[0:50], indice_info=indices, single=True) cobra_vis.color_cobra(X_test=X_eps[0:50], indice_info=indices) ###################################################################### # Voronoi Tesselation # ~~~~~~~~~~~~~~~~~~~ # # We present a variety of Voronoi Tesselation based plots - the purpose of # this is to help in visualising the pattern of points which tend to be # picked up. # cobra_vis.voronoi(X_test=X_eps[0:50], indice_info=indices, single=True) cobra_vis.voronoi(X_test=X_eps[0:50], indice_info=indices) ###################################################################### # Gradient-Colored Based Voronoi # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # cobra_vis.voronoi(X_test=X_eps[0:50], indice_info=indices, MSE=MSE, gradient=True) ###################################################################### # Licensed under the MIT License - https://opensource.org/licenses/MIT #
[ 37811, 198, 8220, 33, 3861, 15612, 38189, 198, 19351, 198, 198, 1212, 20922, 481, 3002, 262, 1490, 4712, 5612, 290, 29353, 4438, 416, 198, 9078, 66, 672, 430, 13, 198, 198, 37811, 198, 198, 2, 4064, 6759, 29487, 8019, 26098, 198, 1174...
2.951415
1,626
# -*- coding:utf8 -*- from flask import Flask from flask_mongoengine import MongoEngine from config import config db = MongoEngine()
[ 2, 532, 9, 12, 19617, 25, 40477, 23, 532, 9, 12, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 62, 76, 25162, 18392, 1330, 42591, 13798, 198, 198, 6738, 4566, 1330, 4566, 198, 198, 9945, 796, 42591, 13798, 3419 ]
3.435897
39
#!/usr/bin/env python3 # This program finds files that are above a specified size within # a specified folder and its subfolders ''' Write a program that walks through a folder tree and searches for exceptionally large files or folders—say, ones that have a file size of more than 100MB. (Remember, to get a file’s size, you can use os.path.getsize() from the os module.) Print these files with their absolute path to the screen. ''' import os import shutil import sys # converts byte to megabytes # Confirm existence of the specified folder sourceFolder = './source' sourceFolder = os.path.abspath(sourceFolder) # simpleSourceFolder = re.search(r'/([\w .-]+)$',sourceFolder).group(1) tSize = 0.5 * 1024 * 1024 # 0.5 MB if os.path.exists(sourceFolder): print('\nWill scan for files with more than {0:.2} MB in size in'.\ format(mb(tSize))) print(sourceFolder) else: print('Source folder %s does not exist.' % (sourceFolder)) sys.exit() count = 0 # number of files scanned countAbove = 0 # number of files found above the threshold size = 0 # number of files sizeAbove = 0 # total size of files found in MB # Walk through the specified folder # while finding the locations of files above a certain size # and printing out their paths. for foldername, subfolders, filenames in os.walk(sourceFolder): print('\nExamining "{0}" for large files...'.\ format(os.path.basename(foldername))) for filename in filenames: count += 1 fileSize = os.path.getsize(os.path.join(foldername, filename)) size += fileSize if fileSize >= tSize: print('Found: "{0}", {1:.2} MB'.format(filename,\ mb(fileSize))) countAbove += 1 sizeAbove += fileSize print('\nReviewed {0} files with'\ ' a total size of {1:,} MB.'.format(count,\ int(mb(size)))) print('Found {0} of them to be above {1:.2} MB '\ 'with a total size of {2} MB.'.\ format(countAbove, tSize / (1024 * 1024), int(mb(sizeAbove))))
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 220, 770, 1430, 7228, 3696, 326, 389, 2029, 257, 7368, 2546, 1626, 198, 2, 220, 257, 7368, 9483, 290, 663, 850, 11379, 364, 198, 7061, 6, 198, 16594, 257, 1430, 326, 11114, ...
2.692208
770
""" Configuration: To use the car_milage_per_month component you will need to add the following to your configuration.yaml file: car_milage_per_month: odometer_sensor: sensor.ete123_odometer (the sensor that holds the total amount of km) """ import json import logging import calendar import os import voluptuous as vol import homeassistant.helpers.config_validation as cv from datetime import datetime from homeassistant.const import ( CONF_NAME, CONF_UNIT_OF_MEASUREMENT, LENGTH_KILOMETERS, STATE_UNKNOWN ) from homeassistant.helpers.entity import Entity from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.core import HomeAssistant, CoreState _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = 'car_milage_per_month' DOMAIN = 'car_milage_per_month' CONF_ODOMETER_SENSOR = 'odometer_sensor' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ODOMETER_SENSOR): cv.entity_id, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string }) def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the sensor platform.""" odometer_entity = config.get(CONF_ODOMETER_SENSOR) name = config.get(CONF_NAME) unit = config.get(CONF_UNIT_OF_MEASUREMENT) data = CarMilageData(hass, odometer_entity) add_devices([CarMilageSensor(hass, odometer_entity, name, unit, data)]) class CarMilageSensor(Entity): """Representation of a Sensor.""" def __init__(self, hass, odometer_entity, name, unit_of_measurement, data): """Initialize the sensor.""" self._hass = hass self._odometer_entity = odometer_entity self._name = name self._unit_of_measurement = unit_of_measurement self._state = STATE_UNKNOWN self.data = data self.update() @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self.data.getMilageForCurrentMonth() @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def device_state_attributes(self): """Return device specific state attributes.""" return self.data.values def update(self): """Fetch new state data for the sensor. This is the only method that should fetch new data for Home Assistant. """ if self._hass.state not in (CoreState.starting, CoreState.not_running): self.data.update() value = self.data.values class CarMilageData(object): """docstring for CarMilageData""" def getMilageForCurrentMonth(self): """ Returns the current month milage value """ current_month = str(datetime.now().month).lstrip("0") return self.getMilageForMonth(current_month) def setMilageForCurrentMonth(self, odometer_value): """ Sets the passed value to the current month milage value in the self.milageFile file """ current_month = str(datetime.now().month).lstrip("0") current_month_name = calendar.month_name[int(current_month)] _LOGGER.debug("Updating milage for month: %s to: %s", current_month_name, odometer_value) self.values['current_month'] = odometer_value with open(self.milageFile, 'r') as milage: data = json.load(milage) data[current_month_name] = odometer_value os.remove(self.milageFile) with open(self.milageFile, 'w') as milage: json.dump(data, milage) def getMilageForMonth(self, month): """ This method will return corresponding milage odometer value for the passed month by reading it from the self.milageFile file. """ monthName = calendar.month_name[int(month)] with open(self.milageFile) as milage: data = json.load(milage) for key, value in data.items(): if str(key) == str(monthName): return value def getStateValueFromEntity(self, entity): """ Get the current state from the passed entity """ state = self.hass.states.get(entity) return int(state.state) def setLastKnownValue(self, odometer_value): """ Sets the passed value to the last_known_value in the self.milageFile file and in the list """ _LOGGER.debug("Updating last_known_value to: %s", odometer_value) self.values['last_known_value'] = odometer_value with open(self.milageFile, 'r') as milage: data = json.load(milage) data['last_known_value'] = odometer_value os.remove(self.milageFile) with open(self.milageFile, 'w') as milage: json.dump(data, milage)
[ 37811, 198, 38149, 25, 198, 198, 2514, 779, 262, 1097, 62, 25433, 496, 62, 525, 62, 8424, 7515, 345, 481, 761, 284, 751, 262, 1708, 284, 534, 198, 11250, 3924, 13, 88, 43695, 2393, 25, 198, 198, 7718, 62, 25433, 496, 62, 525, 62, ...
2.440353
2,037