content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def split_string_content(content): """ Split the string content and returns as a list. """ file_contents = content.split("\n") if file_contents[-1] == '': file_contents = file_contents[:-1] return file_contents
85706b70a33f81c6546a24c8e2bb1766de7779c2
678,455
def is_widget(view): """ Returns `True` if @view is a widget. """ return view.settings().get('is_widget')
db949bb860cd2c29f295ca049c11163192c8e2a8
678,457
def Klein(z): """Klein's icosahedral invariants.""" return ( 1728 * (z * (z ** 10 + 11 * z ** 5 - 1)) ** 5 / (-(z ** 20 + 1) + 228 * (z ** 15 - z ** 5) - 494 * z ** 10) ** 3 )
0006cc1a29666397ec7d290047459c5a70c600c6
678,458
def geom_cooling(temp, alpha = 0.95): """ Geometric temperature decreasing procedure allows for temperature variations after every iteration (k). It returns a value of temperature such that T(k+1)=alpha*(T) Parameters ---------- temp: float Current temperature. ...
451deeef629707a9d8a66eb8be1ae88aa9231314
678,459
import time def apipoll(endpoint, *args, **kwargs): """Poll an api endpoint until there is a result that is not None poll_wait and max_poll can be specified in kwargs to set the polling interval and max wait time in seconds. """ result = endpoint(*args, **kwargs) if result is not None: ...
20ba59ac9d3df192f7fe92e5692fe0bc80f66ac1
678,461
import os def get_user_data_dir(): """Gets the user-specific dir where apps may store their data files. This is specific to the user running this program. Returns: str the dir path where applications store their user-specific data files. Raises: Exception: If neither XDG_DATA_HOME or HOME are set i...
3d1a15242996db4830f85a943df413493a2faf31
678,462
def documents(pmid_15146165, pmid_18073307): """Create test fixture for documents.""" return [pmid_15146165, pmid_18073307]
d52eecf2d8a2f51e690fd97363e0e01b7c693e66
678,463
import time def timestamp(): """ Get the current time. Returns the current time in the form YYYY-mm-ddTHH:MM:SS+00:00 """ return time.strftime('%Y-%m-%dT%H:%M:%S+00:00')
bb746f9c6919cedf4a98999cc04cda6109de94f0
678,464
def multiply(a, b): """ >>> multiply(3, 5) 15 >>> multiply(-4, 5) -20 >>> multiply(-4, -2) 8 """ iterator = 0 value = 0 if iterator < a: while iterator < a: value += b iterator += 1 else: while iterator > a: value -= b ...
3adf7ff18b8559bb8e1a04d79801f307c264f6bb
678,465
import re def human2bytes(s): """ >>> human2bytes('1M') 1048576 >>> human2bytes('1G') 1073741824 """ symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y') num = re.findall(r"[0-9\.]+", s) assert (len(num) == 1) num = num[0] num = float(num) for i, n in enumer...
8ed56b6ea327cdc12b58c662268e54719e568f1d
678,466
def print14list(pair14, shift, molecule): """Generate pair 14 list line Parameters ---------- pair14 : Angle Object Angle Object shift : int Shift produced by structural dummy atoms molecule : molecule object Molecule object Returns ------- pair14 : str ...
94b92d8b9acdc5d8efe25bd90fa53ca293e1fd88
678,467
import struct def readu8(file): """ Reads an unsigned byte from the file.""" data = file.read(1) return struct.unpack("B", data)[0]
1d8de9d2e056c43c2fe93c40892cf9bd285a83ff
678,468
from typing import Dict async def iterate_and_format_dict(d: Dict, replacements: Dict): """ Iterates through the values of a dictionary (with or without nested dictionaries), and formats values accordingly if they exist in the `replacements` dictionary. Example args: d = {"something": {"neste...
f78ff2e4a741a47fadb7864d008f06bd63893c18
678,469
def convert_coordinates(hpos, vpos, width, height, x_res, y_res): """ x = (coordinate['xResolution']/254.0) * coordinate['hpos'] y = (coordinate['yResolution']/254.0) * coordinate['vpos'] w = (coordinate['xResolution']/254.0) * coordinate['width'] h = (coordinate['yResolution']/254.0) * coo...
fe5dcd41380e05d5fd83edcbfc1c895e4bd5ee93
678,470
def userInputCorrectAttributeName(message, my_object, old_attribute_name, *args): """ ask user to correct attribute name in object usage: object = userInputCorrectAttributeName(...) :param message: message to print to user :param my_object: object whose attribute you wish to correct ...
6d495a2737c0ead134378928884c9df99447367e
678,471
import os def findmkv(basedir): """Returns a list of files that end in .mkv.""" baselisting = os.listdir(basedir) mkvfiles = [] for files in baselisting: if files.endswith('.mkv'): mkvfiles.append(files) return mkvfiles
8878c100563ecb1dfa010970ec46cad89d64632c
678,472
def is_float(istring): """Convert a string to a float. Parameters ---------- istring : str String to convert to a float. Returns ------- float Converted float when successful, ``0`` when when failed. """ try: return float(istring.strip()) except Exceptio...
0d0af19566e724f7433d8879a8445d8023c1b622
678,473
from typing import List def prime_factors(n: int) -> List[int]: """Return an ascending list of the (greather-than-one) prime factors of n. >>> prime_factors(1) [] >>> prime_factors(2) [2] >>> prime_factors(4) [2, 2] >>> prime_factors(60) [2, 2, 3, 5] """ factors = [] d = 2 while d * d <=...
605e1d05d6f47ab46ac48290de3d0dbeca0f948e
678,474
def create_translate(region, account_id): """Create translation function that will generate the full ARN URI from a given Lambda or Activity name. Note: region / account_id can be None if those parts of the ARN are already specified Args: region (string) : The region name for the ARN ...
385bd085e4213cc2feea9e8393ca4cd33b79e43b
678,476
def _proposed_scaling_both(current, desired): """ identify a x and y scaling to make the current size into the desired size Arguments --------- current : tuple float tuple of current size of svg object desired : tuple float tuple of desired size of svg object Returns --...
1db39b32a951a0944104d6011c6f399d926d50fa
678,477
def prometheus_worker_job_count(prometheus, testconfig): """ Given a type of a worker job (ReportJob or NotifyJob), returns the value of that metric """ def _prometheus_worker_job_count(job_type): metric_response_codes = prometheus.get_metric( f"apisonator_worker_job_count{{namespace...
22b41e5d3b97e97edacf120e50d50ee77e741d44
678,478
def truncate_descriptions(requested_user_rooms): """ Cut descriptions if too long """ for i in range(0, len(requested_user_rooms)): if len(requested_user_rooms[i]['description']) >= 85: requested_user_rooms[i]['description'] = requested_user_rooms[i]['description'][0:85] + "..." ...
002f0d9cf5d9a9bd67e08c56b4301fe9c67f5140
678,479
def mergeIndiciesToValuesByMap(valueList, valueIndexMap): """Package a list of stats for REST delivery according to the corrisponding valueIndexMap. """ if len(valueList) != len(valueIndexMap): raise Exception("Stats: Value list and value index map did not match.") return {valueIndexMap[i]: ...
668aaaded3f0e4e8dc2dbff62ca8a1feae29e54c
678,481
def dummy_decorator(*_): """Returns a dummy decorator""" def decorate(func): """Decorator func""" def call(*args, **kwargs): """Call func""" return func(*args, **kwargs) return call return decorate
e7d73290ce98c1117660aef91346480bd91f2bba
678,482
import math def factor(num, primes=None): """Return the prime factorization of a number in the form of a map between the prime key and the number of those primes in the prime factorization This runs much faster if a list of primes is provided.""" root=math.ceil(math.sqrt(num)) + 1 factors={} n...
d62cb5939267112c43e540fda092f01da3a5c11c
678,483
def calculate_expected_wins(win_rate, num_games): """Calculate current expected wins""" expected_wins = win_rate * float(num_games) result = int(round(expected_wins, 0)) return result
5f979a861a0fae1e0fe654c9cc4c9ccf6583b35e
678,484
def sanitize_username(uname): """ Take a user provided username and "normalize it" (take out spaces, quotes, etc). This is not a security measure, it's more for interoperability with, eg. command line tools. """ uname = uname.replace("'", "") uname = uname.replace('"', "") uname = u...
a3cd88310b8d379eb55414e87d7ac8f959daf969
678,486
def purgelist(artifactory): """Default Policy. Keeps the last 5 artifacts from each project""" purgable = artifactory.count_based_retention(retention_count=5) return purgable
a252a2ed263fa3b11c220b10ffada34535e0911c
678,487
import os def get_file_extension(file_path): """ :param file_path: The path of file :type file_path: str :return: file extension :rtype: str """ _, file_extension = os.path.splitext(file_path) return file_extension
ba47b7a74fa78c2bbcdfbeef88ff8217613f591e
678,488
def get_elesign(size, image): """ signature is black, RGB near 0 """ points = [] for j in range(size[0]): for i in range(size[1]): if image[i][j][0]>100 and image[i][j][1]>100 and image[i][j][2]>100: image[i][j][3] = 0 else: image[i][j]...
bbd4f6b790db5dd317a2c2a67cb5ed1a3e88b96f
678,489
def get_virtualenv_dir(version): """Get virtualenv directory for given version.""" return "version-{}".format(version)
1b292b48f9c5ce72304019ecb83a1befe25eaf77
678,490
def convert_timestamp(timestamp: str) -> int: """ Converts a timestamp (MM:SS) to milliseconds. """ timestamp_list = timestamp.split(":") minutes = timestamp_list[0] seconds = timestamp_list[1] minutes_in_ms = int(minutes) * 60 * 1000 seconds_in_ms = int(seconds) * 1000 total_ms = m...
7133709d3d5ff76661889bef48301bd0912047d4
678,491
def chk_keys(keys, src_list): """Check the keys are included in the src_list :param keys: the keys need to check :param src_list: the source list """ for key in keys: if key not in src_list: return False return True
48706a1f39c06cf79b107ca67eb0a5c5e202fe08
678,492
import logging import os def isPidRunning(pid): """ Check For the existence of a unix pid. """ try: logging.info('Checking if pid ' + str(pid) + ' is existing...') os.kill(pid, 0) logging.info('Pid ' + str(pid) + ' exists') except OSError: logging.info('Pid ' + str(pid) + '...
908323928bd21e09bbe6b2f3669333fb43793775
678,493
def field(fields, **kwargs): """Helper for inserting more fields into a metrics fields dictionary. Args: fields: Dictionary of metrics fields. kwargs: Each argument is a key/value pair to insert into dict. Returns: Copy of original dictionary with kwargs set as fields. """ f = fields.copy() f....
c197c458eabebc51138e15182d1485580e33b016
678,494
def batch_query_row_args_2_dict(args): """ change batch_query_row_args to dict :param args: batch query row args :type args: BatchQueryRowArgs :return: :rtype dict """ return { 'maxVersions': args.max_versions, 'rows': args.rows }
3153732644606092df0036e398c8ddbcb5b0661c
678,495
import requests def get_html_from_web(postal_code): """ gets html weather for postal code :param postal_code: :return: """ postal_code = postal_code.replace(" ", "") url = "https://www.wunderground.com/cgi-bin/findweather/getForecast?query={}".format(postal_code) response = requests....
ef00fb3208aca2b316ed2e8d961d9429da6ec265
678,496
def get_name(model, index: int): """Get the input name corresponding to the input index""" return model.inputs[index]
6620098f8fb99b18a37aed4ca4f8a28f038c8c79
678,497
import pathlib import os import shutil def copy_if_exist(file, directory): """Copies files to destination directory. Parameters ---------- file : str Path for file to be copied. directory : str Path for destination directory. Returns ------- bool True or false...
de3efd377eed042a6e551acb1a7d635eca66ac5b
678,498
def s1_orbit_number(title: str) -> str: """ sentinel competition date extractor extractor from product name """ if not title.startswith(('S1B', 'S1A','S2A','S2B')): raise ValueError("Title should start with ('S1B','S1A')") return title[49:49+6]
bd57a3fc3566d6db201f17b8f98a2bb66913e1f8
678,499
def chunkString(string, length): """This function returns a generator, using a generator comprehension. The generator returns the string sliced, from 0 + a multiple of the length of the chunks, to the length of the chunks + a multiple of the length of the chunks. Args: string (String): ...
819be7b7e234338ffc36450602e2b53bda2034a9
678,500
def post_process_headways(avg_headway, number_of_trips_per_hour, trip_per_hr_threshold=.5, reset_headway_if_low_trip_count=180): """Used to adjust headways if there are low trips per hour observed in the GTFS dataset. If the number of trips per hour is below the trip frequency interval...
df7f8de77e1e0828b00f3f0c556ccfce40e5206a
678,501
import os import yaml def _install_container_bcbio_system(datadir): """Install limited bcbio_system.yaml file for setting core and memory usage. Adds any non-specific programs to the exposed bcbio_system.yaml file, only when upgrade happening inside a docker container. """ base_file = os.path.joi...
78f9b19693483de840ce8d2af2fac418aceed590
678,502
def quick_eval(idx, model): """ Evaluation func for the multiprocessing that we have designed to be as quick as possible! """ env = model.get_env() env.reset() done = False total_reward = 0 obs = env.reset() while not done: action, _states = model.predict(obs) obs, re...
4d5033c0a799d8d105dc2adb8991159d9df3aa12
678,503
def sop_classes(uids): """Simple decorator that adds or extends ``sop_classes`` attribute with provided list of UIDs. """ def augment(service): if not hasattr(service, 'sop_classes'): service.sop_classes = [] service.sop_classes.extend(uids) return service return ...
adfb06e19930cf82965b3beb024edb8dada05fd9
678,505
def verify_active_call_number(log, ad, expected_number): """Verify the number of current active call. Verify if the number of current active call in <ad> is equal to <expected_number>. Args: ad: Android Device Object. expected_number: Expected active call number. """ calls ...
00c9e0cad6ee1784c5c1415e3114f8c500a4867e
678,506
import os def get_build_entries(root_path): """ Iterates through the root_path, creating a list for each file and directory. Excludes any path starting with extensions or distribution and paths ending with channel-prefs.js. """ rel_file_path_set = set() rel_dir_path_set = set() for...
2f0da3413426bc4e897c9276513d0ae3433c4b46
678,507
import re def parse_show_ip_ecmp(raw_result): """ Parse the 'show ip ecmp' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show ip ecmp in a \ dictionary of the form: :: { 'global_status': True, ...
3ae0d2ae6bae626691d1c58062a55c3f83013798
678,508
import sympy def DfjDxi(DN,f): """ This method defines a gradient. Returns a matrix D such that D(i,j) = D(fj)/D(xi) This is the standard in fluid dynamics, that is: D(f1)/D(x1) D(f2)/D(x1) D(f3)/D(x1) D(f1)/D(x2) D(f2)/D(x2) D(f3)/D(x2) D(f1)/D(x3) D(f2)/D(x3) D(f3)/D(x3) Ke...
fe99dc5d4e3b7377853f0d93a6c137e44e6f5a6b
678,509
import os import pickle def load_resource(file_name, rel_path="resources"): """ Load resource Args: file_name (str): full file name. This should be included in ```resources``` directory. rel_path (str): path to ```file_name```. Default value is...
ab271a006fca2abc77545d9d1aa48d0337f21179
678,510
def manhattan_distance(p1, p2): """ Precondition: p1 and p2 are same length :param p1: point 1 tuple coordinate :param p2: point 2 tuple coordinate :return: manhattan distance between two points p1 and p2 """ distance = 0 for dim in range(len(p1)): distance += abs(p1[dim] - p2[di...
8edc13b373fa14ea168481923cf4d243c3783b9c
678,511
def tags_with_text(xml, tags=None): """Return a list of tags that contain text retrieved recursively from an XML tree """ if tags is None: tags = [] for element in xml: if element.text is not None: tags.append(element) elif len(element) > 0: tags_with_...
a922034e1d04b98e0fbcebbae812a1e88109607d
678,512
def generate_text_notebook() -> str: """Generate `notebook.md` content.""" content = ( """\ --- file_format: mystnb kernelspec: name: python3 --- # Text-based Notebook ```{code-cell} print("Hello, World!") ``` """.rstrip() + "\n" ) return content
2cf2a5277840bfd6df5cfffb87b5692d2f95830c
678,513
import os def ensure_dir(d): """If directory d does not exist, create it @param d: name of an existing or not-yet-existing directory @type d: basestring @returns: d @rtype: basestring """ if not os.path.isdir(d): os.makedirs(d) return d
d654f6f2cadf4ccb2d7372f2f6ca452104f2d0dc
678,514
def splittermixerfieldlists(data, commdct, objkey): """docstring for splittermixerfieldlists""" objkey = objkey.upper() objindex = data.dtls.index(objkey) objcomms = commdct[objindex] theobjects = data.dt[objkey] fieldlists = [] for theobject in theobjects: fieldlist = list(range(1, ...
5f9dd46b48ec024f59a3edd61b8ecb2ce26cc58b
678,515
def build_vector(image, binary=True): """ 图像转一维特征向量 :param image: pillow Image object with mode 1 or mode L :param binary: 黑白图是否生成为0,1向量 :return: list of int """ vector = [] for pixel in image.getdata(): if binary: vector.append(1 if pixel == 255 else 0) else:...
fffb83574dbe438cadf3b29a4600f36ad70471bb
678,516
def utm_zone_to_epsg(zone): """ Convert UTM zone string to EPSG code. 56S -> 32756 55N -> 32655 """ if len(zone) < 2: raise ValueError(f'Not a valid zone: "{zone}", expect <int: 1-60><str:S|N>') offset = dict(S=32700, N=32600).get(zone[-1].upper()) if offset is None: r...
3eeb39092bc9ff31f8f21c0eea8ad36e2a973363
678,517
import math def compare_data(positions1, positions2): """Compares coordinates and key pressed between the two replays""" length = len(positions1) if len(positions1) <= len(positions2) else len(positions2) closeness = [] same_keys_pressed = 0 not_same_keys_pressed = 0 for rep_value in range(0,...
f2b04e9e25a0643afd9485b9e9d8677f02854dd6
678,518
from sys import path import os def enumeratepaths(path=path): """Returns the path to all the files in a directory as a list""" path_collection = [] for dirpath, dirnames, filenames in os.walk(path): for file in filenames: fullpath = os.path.join(dirpath, file) path_collecti...
782f948c996c903e16e87c08036dadcc3e1d0471
678,519
import pickle def converter_func(data): """Convert from storage to in-memory representation. """ print('converter_func({!r})\n'.format(data)) return pickle.loads(data)
d47cd5eb26947ae4f6fca81b70ac7a79b87308cd
678,520
import os import json def open_json_file(_data_dir): """Open the json format file into the python variable.""" if not os.path.exists(_data_dir): raise IOError("[Error] Json Path -> '{:s}' was not found...".format(_data_dir)) json_file = open(os.path.abspath(_data_dir), "r") raw_data = json.lo...
51094e1573833ba6071ee6c51d5ff148926d4135
678,521
from datetime import datetime def get_unix_epoch_milliseconds(): """ Function returns Unix Epoch time in milliseconds. """ return int(float(datetime.utcnow().timestamp()) * 1000)
b656a115d64599b433e1e7e941abe66b42750442
678,523
def combine_docs(docs): """ Combine documents from a list of documents. Only combines if the element is a string. Parameters ---------- `docs` : `list`. Documents to combine Returns ------- `string` : Combined string of documents """ combined_docs = "" for doc in docs: ...
4aaa59d8be3f605237b70425562433c0e6b117e4
678,524
def read_paragraphs(d): """ Returns a dictionary of paragraph-level text information """ paras = {} num_paras = len(d.paragraphs) for i in range(num_paras): para = d.paragraphs[i] paras[i] = { "text": para.text } return paras
5e0b7fd64b26b0c93c6a4c97f4225e6b775c2abd
678,525
from datetime import datetime def restore_timestamp(formatted_timestamp): """Return a timestamp from a formatted string.""" return datetime.strptime(formatted_timestamp, "%Y-%m-%d %H:%M:%S").strftime('%Y%m%d%H%M%S')
62e863f02ec2d93b19d4f3aa934ea8512957c5f4
678,528
import ctypes def cpuid(rdi=ctypes.c_int, rsi=ctypes.c_int, rdx=ctypes.c_void_p): """ # Function/instruction parameter mapping: # # cpuid(input-to-CPUID int32 EAX, # input-to-CPUID int32 ECX, # output-from-CPUID int32[4] EAX_EBX_ECX_EDX) # .intel_syntax noprefix push rb...
b4ac2d9c29dfc36208bd9df5c1a0175b9b20c08d
678,529
def div(n, d): """Divide, with a useful interpretation of division by zero.""" try: return n/d except ZeroDivisionError: if n: return n*float('inf') return float('nan')
e5828b600bf6632a2b86cf8c12ab3fcc054be768
678,530
import os def get_file_list(path, type="all"): """ 获取文件列表 """ file_list = [] if type == "all": for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: file_list.append((os.path.join(dirpath, filename))) return file_list if typ...
7173ce883853093185c0fe013786030535caed83
678,531
def pdf_pareto(t, a, k, xmax=None): """PDF of Pareto distribution Parameters ---------- t : input array a : power-law power (a = alpha-1 from real Pareto) array k : minimum value for power law array xmax : max value for, optional, by default None Returns ---...
d7d7a9469e1c49bdea43c0ddbd42049cd96540df
678,532
def wrap(ag, compound='atoms'): """ Shift the contents of a given AtomGroup back into the unit cell. :: +-----------+ +-----------+ | | | | | 3 | 6 | 6 3 | | ! | ! | ! ! | | 1-2-|-5-8 -> |...
42f46f73e9bf0317cc00d79e257726cff5ecdaf9
678,533
def parse_scripts(scp_path, value_processor=lambda x: x, num_tokens=2): """ Parse kaldi's script(.scp) file If num_tokens >= 2, function will check token number """ scp_dict = dict() line = 0 with open(scp_path, "r") as f: for raw_line in f: scp_tokens = raw_line.strip()....
db22596c8639c2e7d81d3fe749fc235a6281d0c3
678,534
def CheckPermutation(s1: str, s2: str) -> bool: """Determines if s1 is a permutation of s2. >>> CheckPermutation("", "") True >>> CheckPermutation("a", "aa") False >>> CheckPermutation("ab", "aa") False >>> CheckPermutation("ab", "ba") True >>> CheckPermutation("racecar", "c...
76b1ed4fda93476d9da22378c8e6e251b4d6e7b5
678,535
def split_list(_list, slice): """ 拆分列表 :param _list: 列表 :param slice: 拆分块的大小 :return: 拆分后的列表 """ return [_list[i:i + slice] for i in range(0, len(_list), slice)]
e194f87a09f80198d448e0b93f6245f68abfb09c
678,536
async def opp_admin_credential(opp, auth_provider): """Overload credentials to admin user.""" await opp.async_add_executor_job( auth_provider.data.add_auth, "test-user", "test-pass" ) return await auth_provider.async_get_or_create_credentials( {"username": "test-user"} )
c12e0fc584c31a239b46da71e3939507ace3a4f6
678,537
import random def word(allow_empty=True): """ :return: a randomly generated (non-ASCII) word :rtype: unicode """ length = random.randint(0 if allow_empty else 1, 10) return u"".join(chr(random.randint(256, 512)) for _ in range(length))
e1f6e217888138605a41e727b3e5486ba961040c
678,538
import json def read_json(fjson): """ Args: fjson (str) - file name of json to read Returns: dictionary stored in fjson """ with open(fjson) as f: return json.load(f)
d391c7d1aa7e2a74e1af16018e61bc63b68d2a88
678,539
def format_wildcards(wildcards, key_order=None): """ Convert wildcard dict to string suitable for filename suffix (Snakemake built-in doesn't work with Condor because it includes equal signs) """ # Alphabetically sort keys if no other order specified if key_order is None: key_order...
ecea76320833f299ded37421b3c6852eef4ca373
678,540
def InterResdueDistance(ires,jres): """ not used """ # shortest interatomic contact between two residues ires and jres return 'xxx'
404736aa9cab03a86146123eefefd93fe9c6f59d
678,541
from typing import List def check_strict_superset(raw_str: str, raw_arr: List[str]) -> bool: """ >>> check_strict_superset('1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78', ... ['1 2 3 4 5\\n', '100 11 12']) False """ superset = set(raw_str.split()) sets = (set(el.split()) for el in map(str.strip,...
1c92c5e292c02be874a12242808f3f50a38800e2
678,542
def display_message(message, other_lines=None, line_sep='*', side_sep='*', secondary=False, no_return=True): """ QoL function aiming at making a line visible in an otherwise dense log,usually to pinpoint a step change. ******************** * step 1 starting * ******************** :param messa...
4a6b9e3eef38b2ac7c22a0b27ebfb3bd44585355
678,543
def map_pathogen_id_to_name(pathogen_id): """ """ mapping = { "p00": "Acinetobacter baumannii", "p01": "Baceroides fragilis", "p02": "Burkholderia cepacia", "p03": "Candida albicans", "p04": "Candida giabrata", "p05": "Candida parapsilosis", "p06": "Ca...
2ef24ff2876320ce6a7f7da72376c412199eb7ba
678,544
def get_unique_covered_percentage(fuzzer_row_covered_regions, fuzzer_col_covered_regions): """Returns the number of regions covered by the fuzzer of the column but not by the fuzzer of the row.""" unique_region_count = 0 for region in fuzzer_col_covered_regions: ...
83b4b69ced91c3a1d279fe6b2fe1b43ce3131b61
678,545
def check_mid_low(device_name): """Check if a device domain contains mid or low""" domain, *_ = device_name.split("/") if "mid" in domain or "low" in domain: return True return False
de1271bab37057aed4850538ab7b4d46baba411a
678,546
import numpy def _bcdfo_solve_tridiag(M, b, trans='N'): """ Solves a triangular system of equations """ if trans is 'N': x = numpy.linalg.solve(M, b) else: x = numpy.linalg.solve(M.T, b) return x
e75c1d678735a75bd9e10b12a8b1421424d0b1a1
678,548
def observations_bytestring(dataset_bytestring, member_header_bytestring): """ Observations are streamed in the file after the member header. """ return dataset_bytestring[len(member_header_bytestring):]
ac617144c4b334aaaebfd11598de068767e52883
678,550
def getSonarData(sensor, angle): """ Transmits the sonar angle and returns the sonar intensities Args: sensor (Ping360): Sensor class angle (int): Gradian Angle Returns: list: Intensities from 0 - 255 """ sensor.transmitAngle(angle) data = bytearray(getattr(sensor, '_...
d007a192a5fe2cd2af9616638e15010b8e820477
678,551
from typing import Tuple import math def det_stop(len_dataset: int, len_output: int, gamma: float = 0.5) -> Tuple[float, float]: """ Deterministic method for finding the learning stop criterion len_dataset : int - training sample size len_output : int - number of neurons in the output layer gamma ...
bd14d6e6641550e83176a9761ef41c75a45a5d46
678,552
import re def drop_higirise(df): """ 高層気象データから不要データを除去する Args: df(DataFrame) : 対象のDataFrame Returns: DataFrame : 不要データ除去後のDataFrame """ #new_df = df.dropna(how='any', axis=1) # 各列がnullの有無を取得する(1行でもnullが含まれていれば有り) column_with_null = df.isnull().any() # 相対湿度がn...
9bad6ebcbd102185beb1d1fbae6b2f2f50ebd959
678,554
def _validate_params_epaipm(etl_params): """Validate the etl parameters for EPA IPM. Args: etl_params (iterable): dictionary of inputs Returns: iterable: validated dictionary of inputs """ epaipm_dict = {} # pull out the etl_params from the dictionary passed into this function ...
6a1737503ecaad0607de9e165d1bf9392dc9a445
678,555
import torch def recursive_to_device(input, device): """NOTE: If input is dict/list/tuple, it is changed in place.""" if isinstance(input, torch.Tensor): # print('=> IS torch.Tensor') # print('=> input.device before to_device: {}'.format(input.device)) input = input.to(device) ...
792f21052a40de8880b545fda5f800ae5c0f8e7e
678,556
def lon_offset(x, y): """Return angular separation between two offsets which possibly straddle l=0 >>> lon_offset(0, 1) 1 >>> lon_offset(1, 0) 1 >>> lon_offset(0, 355) 5 >>> lon_offset(355, 0) 5 >>> lon_offset(181, 0) 179 """ return min(abs(x - y), abs(x + 360 - ...
70edd8aa42ba1cb292ce2fa964fe635733136a15
678,557
def get_timepoints(conn, scenario_id, starting_tmp=None, ending_tmp=None, stage_id=1): """ Note: assumes timepoints are ordered! :param conn: :param scenario_id: :param starting_tmp: :param ending_tmp: :param stage_id: :return: """ if starting_tmp is None: start_query = ...
a2e1afc38463f7f07d3a67f7992a3643831bcb7e
678,558
def to_tuple(dataseq): """Converts a ``ctypes`` array to a tuple.""" return tuple(dataseq)
b60dbc57fb1049cdd4b336e02d23a8ff379add06
678,559
def __MyDefaultGetAttr(oSelf, sName): """ __getattribute__/__getattr__ default fake.""" try: oAttr = oSelf.__dict__[sName]; except: oAttr = dir(oSelf)[sName]; return oAttr;
bbd8b0769402a4fc63a9bb8ba242fb8d5b0d2207
678,560
import random def generate_emoji(num_emojis: int) -> str: """ Generates a psuedo-random list of emojis with pasta sprinkled in """ emojis = ["🙄", "😙", "😐", "🤤", "😤", "😲", "😬", "😭", "🥵", "🥺", "🤠", "🤫", "😳", "😢"] output: str = "" for _ in range(num_emojis): output += random.choice(...
593d00e6c072f266f1c219fab42c31d88bf0f4b3
678,561
def try_attribute(node, attribute_name, default=None): """Tries to get an attribute from the supplied node. Returns the default value if the attribute is unavailable.""" if node.hasAttribute(attribute_name): return node.getAttribute(attribute_name) return default
4edc2e42be001d200e53b820a6c14de55af46d87
678,562
def get_syns(words, embedding): """Get the synonyms to the words by embedding. Args: words (list): List of words to get their syns. embedding (wordembbeding.WordEmbbeding): Trained Word Embbeding model. Returns: dict: Dictionar containing the words and their syns. "...
b66684c462f5097eb0017646988ccc026bf91189
678,563
def parse_at_txt(txt, return_type='dict'): """ 아래의 형식을 파싱하여 dict, list 형태로 돌려줍니다. @start_date=2020-01-01 @end_date=2020-02-01 **Example** ``` import simple_utils print(simple_utils.text.parse_at_txt('@start_date=20200101 @end_date=20200101')) >> {'start_date': '20200101', 'end_date':...
965e5225114239815b509869f6b3c7d2114aeeb6
678,564
def _get_toolkit_function_name_from_function(fn): """ If fn is a toolkit function either imported by turicreate.extensions.ext_import or the magic import system, we return the name of toolkit function. Otherwise we return an empty string. """ try: if '__glmeta__' in fn.__dict__: ...
5888e45d147b5983f2e30bed849c27f710c0f757
678,565
import re def parse_size(size): """Parse a size, kinda like 10MB, and return an amount of bytes.""" size_re = re.compile(r'^(\d+)([GMK]?B)$') match = size_re.match(size.upper()) if not match: raise ValueError("Invalid size %r" % size) amount, unit = match.groups() amount = int(amount) ...
ada427b4c7f803bd0c90e134f0c2e87af4ac834c
678,567