content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def case_insensitive(string): """ :param string: str, a character. :return: lst, a lower character lst. """ new_string = '' for ch in string: if ch.islower(): new_string += ch else: new_string += ch.lower() return new_string
6d2d3e66af4f06f34736e8d9845ec5d38510c359
641,062
import subprocess import shlex import sys def exe(command): """ Executes command and returns string representations of stdout and stderr captured from the console. When universal_newlines=True stdout and stderr are opened in text mode. Otherwise, they are opened in binary mode. In that case captured s...
49bbcbcc214d2d3af2e67de8ab0fb4db9c944311
641,064
def create_json(sensor): """Simple function that creates a json object to return for each sensor Args as data: sensor object retrieved from MongoDB Returns: { Formatted sensor object as below } """ json_object = {'building': sensor.get('building'), ...
a0227dc91158b89e71dc827161c9e23d8262e8ee
641,065
def contains(script, keywords): """Performs DFS on the script to determine if keyword exists.""" # The keyword must be the first item in a list. if type(script) != list or not script: return False if script[0] in keywords: return True # Iterate over all children. return any(co...
dd7e05d63f153e4755b2c91744de1b699ca79a43
641,066
def dict_get(D, k1, k2, default = 0.0): """ Custom retrieval from nested dictionary. Get D[k1][k2] if it exists, otherwise default. """ if k1 in D and k2 in D[k1]: return D[k1][k2] else: return default
0d186374a930f2dc76b894e128f7918dc47cdc05
641,068
import requests def get_pokeapi_data(pokemon): """ Retrieve data on Pokemon from PokeAPI in JSON format. """ endpoint = 'http://pokeapi.co/api/v2/pokemon/' + pokemon r = requests.get(endpoint) r.raise_for_status() return r.json()
29b0209ae455b4fe9ab7abc8950350f988e3ddb6
641,069
def parse_qstat_jobid(output, job_id): """Parse and return output of the qstat command run with options to obtain job status. :param output: output of the qstat command :type output: str :param job_id: allocation id or job step id :type job_id: str :return: status :rtype: str """ ...
ce2afb877fdafc1ff71d9f55a066b5d0e0871f93
641,070
from typing import List from typing import Dict from typing import Any from typing import Optional def find_element_in_list( element_list: List[Dict[str, Any]], **fields ) -> Optional[Dict[str, Any]]: """ Find element with some fields in list of elements >>> element_list = [dict(n="a", v=2), dict(n="...
655bbd1e343cf967d57d20fabaa97f5fb7700c49
641,071
def signup(): """ API endpoint to sign up a new user """ return "Nice! You just signed up"
a6d5f944efe4c513ee46d4297e273f195f5ccd6c
641,072
def expanded_base_command(sys_argv): """ the exectuable path """ assert sys_argv base_cmd = sys_argv[0] return base_cmd
1b9b75ce224305a9df766627cfa904ea04b786e9
641,073
def scatter_props(event): """ Get information for a pick event on a PathCollection artist (usually created with ``scatter``). Parameters: ----------- event : PickEvent The pick event to process Returns: -------- A dict with keys: "c": The value of the color array at the point clicked. "s": Th...
8c25bbb04ce37f9a4511d3893cfa992324ba6e90
641,074
def clean_desc(desc): """ """ to_replace = [("-", ""), (" ", " "), (" ", "_")] ret = desc.lower() for tup in to_replace: ret = ret.replace(tup[0], tup[1]) return ret
ca781567066bfc1aeaec65fb7ec8000bafbaa085
641,075
import re def convert(line): """ blah """ exercise, reps = line['exercise'], line['reps'] match = re.match(r'(\d+)-(\d+)', reps) # default reps when no valid number is given if not match: return (exercise, 50, 100) return (exercise, int(match.group(1)), int(match.group(2)))
e18736a00827494913f95341dab86cb78eb5c8ef
641,076
import math def compute_sigma_at_t(theta, sigma_sq_prev, xi_prev): """ Calculate conditional variance at time t + 1 given parameters of time t Param ----- theta: Tuple(Float, Float, Float, Float, Float) GARCH(1, 1) parameter: (alpha_0, alpha_1, beta_1, risk premium lambda, standard de...
40df93216360d4fc5df69622d46159b240b674d7
641,077
def row_to_dict(row) -> dict: """ Helper function that converts a Resource or Edge into a dictionary """ d = {} for column in row.__table__.columns: d[column.name] = str(getattr(row, column.name)) return d
1caa7a0a093822ece365eadc1fb9f2e9162ec2ad
641,078
import ipaddress def validate_print_ip_address(ip_address): """Validates the given IP address and returns a printable version. For IPv4 addresses no changes are made, for IPv6 addresses brakets are added. Args: ip_address: IP address to validate as string. Returns: A printable ve...
991a42a96a1041ea02e5b525aa1edab979b642a9
641,079
def get_period_string(num_periods): """ Then, we define the logic for creating a string of periods of arbitrary length, using a FOR loop again: """ output = "" for i in range(num_periods): output += "." """ Then the return statement tells the program to send something back ou...
94161bb7bb9f3a02ce8f64b343275b880409976a
641,080
def contains_any(str, set): """ Check whether sequence str contains ANY of the items in set. """ return 1 in [c in str for c in set]
b2bc6146bd7ad38e240b06ed30c6df2b26156aeb
641,081
def _verify_rank_feature(value, low, high): """ Rank features must be a positive non-zero float. Our features are scaled from 0 to 100 for fair comparison. """ if value is None or value == 0: return None ceiling = min(value, high) floor = max(low, ceiling) return floor
8ebb22788f40e3d25b9443cd2ed12cb4ae52d286
641,082
def trajs_matmul(trajs, coeffs): """Right matrix multiply coefficients to all trajectories.""" result = [] for traj in trajs: result.append(traj @ coeffs) return result
19ade7cb2927719123c2f401e48310c5a62f2f68
641,083
def read_file(filename): """Read the given file and return a list of lines of text read from it.""" with open(filename, "r") as file: lines_list = file.readlines() return lines_list
0cf25c6fe6cc23fcf538060c008f6080e2d35824
641,084
def _listset(i): """create a list of unique values from iterable `i`, and return those as comma-separated string """ return ", ".join(list(set(i)))
6984924852112a7f3bb5b6b4740dbce650396b3c
641,085
def tolerance(dimension_mm, itg): """ Returns the tolerance in micrometers using ISO standard using the given dimension and ITG number """ return 10 ** ((itg - 1) / 5) * (0.45 * dimension_mm ** (1 / 3) + dimension_mm / 1000)
c862974eb83270ea170f1f660d19dc4dea0e5507
641,086
def get_matrix30(): """ Return the matrix with ID 30. """ return [ [0.0, 0.0, 0.5, 0.5], [0.6, 0.6, 0.5, 0.5], [0.0, 0.0, 0.5, 0.5], [0.8, 0.8, 0.5, 0.5], ]
c4aca8b55bb73c4604cf90bad2cf24ab6b5c5081
641,087
def _group_by_x(values, aggregationfunc, keyfunc): """input should be [(datetime, stuff), ...]""" groupings = {} for date, value in values: key = keyfunc(date) if key not in groupings: groupings[key] = [value] else: groupings[key].append(value) ret = [] ...
4e06b3ecc39cde42f58b123fb28847a8ea11e696
641,088
import copy def topological_sort(structure): """Does the topological sorting of the given structure. Args: structure: A 'list' of the nodes, following the format described in architecture_graph.py. Returns: A list of ordered indexes. """ structure = copy.deepcopy(structure) set_l = [] s...
5762fb0e3ed6e6299fc4b6b1c19b2b6b94f61753
641,089
def sort_and_count_split_inversions(firstHalf, secondHalf): """ This also comes more or less straight from the lectures. """ iFirst, iSecond = 0, 0 count = 0 tmp = [] for i in range(len(firstHalf) + len(secondHalf)): # bounds checking and sort if iFirst == len(firstHalf): ...
827cf95fe36bc96440dc1bb01fb280eb17bc6e89
641,090
def _clean_aircraft_name(name: str) -> str: """Почистить имя самолёта, чтобы оно могло быть ключом в БД""" return name.replace('.', '').replace(' ', '')
0d8e32d49c4c0d1d757f1b7f3b00ef6d365e4f2a
641,091
def sub(slice_left, slice_right): """ Removes the right slice from the left. Does NOT account for slices on the right that do not touch the border of the left """ start = 0 stop = 0 if slice_left.start == slice_right.start: start = min(slice_left.stop, slice_right.stop) stop ...
0387c7d5c2fa3777d863828a68b04700bab6b53b
641,092
def read_reaction_data(filename): """ Reads reaction data list into a dictionary consisting of keys of elements and the values being lists of the elements required to make the keys. """ data = {} f = open(filename, 'r') for line in f: data_line = "".join([char for char in l...
8a6ef3249cdb58cdb1f6b7623cc9a2d7b7e2d166
641,093
import argparse def get_args(): """ Define arguments to be used by the script """ parser = argparse.ArgumentParser( description="Mass Host HttpStatusCode Enumerater ", prog="hostchk", epilog="Have a nice day :)", ) parser.add_argument( "-in", dest="infile"...
3575e31043ac15c678e5095d10a55d21a032e15c
641,094
def _unpadd_symetric(arrays, p, paddtype): """ Helper function to unpadd in an assymetric way arrays. Parameters ---------- arrays : np.ndarray or list of np.ndarray array or list of arrays to padd. p : int, length of padding. paddtype : ['left', 'right'], where to pl...
550041627a585997b3270163af6edb7dacb331fa
641,095
import re def _hl_matches( regexp: str, subject: str, start: str, end: str, groupstart: str, groupend: str, initial_output="", closing_output="", ) -> str: """ Does not handle nested groups. """ if subject == "": return "" m = re.search(regexp, subject) ...
8134ea336297472da6ee84d7091a59f9dca99d26
641,096
def define_plot_layout(mapside, plotzoom, expidx): """Establish the visual of the igraph plot Args: mapside(int): side size of the map plotzoom(int): zoom of the map expidx(int): experiment index Returns: dict: to be used by igraph.plot """ # Square of the center surrounded by rad...
8160e6d228528d72129ca657177ec167b6b08761
641,097
def get_A_env(envelope): """外皮の部位の面積の合計 式(8) Args: envelope(dict(Envelope)): Envelope要素のノード名をkey、値をvalueとして持つ辞書 Returns: float: 外皮の部位の面積の合計 """ A_env = 0.0 # 窓を除く外皮等 wall_list = envelope['Wall'] for i in range(len(wall_list)): A_env += wall_list[i]['Area'] # ...
482132d659b20c468a09bff366476ee6c722cc23
641,098
import os def get_header_data(dir_stub): """fetch the header info from 'Stub Summary.txt' """ filename = os.path.join(dir_stub, 'Stub Summary.txt') # open the stub invo .csv file with open(filename, 'r') as f: file_inputdata = f.read() # extract the header-info from inp_data (first 14 l...
b28e160a8a037669ce3c3aa48ae394f6288b3fbb
641,099
def convert_flux_to_nanoJansky(flux, fluxmag0): """Convert the listed DM coadd-reported flux values to nanoJansky. Based on the given fluxmag0 value, which is AB mag = 0. Eventually we will get nJy from the final calibrated DRP processing. """ #pylint: disable=C0103 AB_mag_zp_wrt_Jansky = 8.90 ...
3889a4ef671b3afe6689c0c2766e6d3e96eeaf0c
641,101
def filter_by_substance_composition( data_set, compositions_to_include, compositions_to_exclude ): """Filters the data set so that it only contains properties measured for substances of specified compositions. This method is similar to `filter_by_smiles`, however here we explicitly define the full ...
a952aec4cf369209919d632991fd5d9424c0b282
641,102
def echo_transform(buildState): """ Assumes frame rate has not changed. The composite and donor mask are assumed to not change due to an associated manipulation operation. :param buildState: :return: updated composite mask @type buildState: BuildState @rtype: CompositeImage """ if b...
b33294b87b5641f0c5eb76bc8f25596a9ad780ce
641,103
def ZonalStats(valueCollection, zoneCollection, statistic, scale = 10, tileScale = 16): """Computes zonal statistics across an image collection as a table. An output value is computed: 1) For every zone in the input zone collection. 2) For every image in the value collection. Keyword arguments...
523fb117ff0e369fff5b2692be3614962604c4fd
641,104
def _is_separator(line: str) -> bool: """returns true if a table separator line is found""" # This function is cacheable since tables have identical separators strip_line = line.strip() if any(( strip_line.startswith('╒') and strip_line.endswith('╕'), strip_line.startswith('╞') and strip...
09c89e7fd98ed12c3dd56864c31382541c68ef2a
641,105
def compute_average(grades): """ Computes the average of all the grades in the list Parameters: grades (list) Returns: the average (float) rounded up to one decimal """ average = round(sum(grades)/len(grades), 1) return average
3a85a59c4047ef14b64e074c00bb6e0c7d95931d
641,106
def count_dup(gtree, events, node=None): """Returns the number of duplications in a gene tree""" var = {"dups": 0} def walk(node): if events[node] == "dup": var["dups"] += len(node.children) - 1 node.recurse(walk) if node: walk(node) else: walk(gtree.root...
4120129d19390a354b8728dde53877b40b173f91
641,107
def unicode_truncate(s: str, length: int, encoding: str = "utf-8") -> str: """Truncate a string to length in bytes. :param s: The string to truncate. :param length: The length in number of bytes — not characters.""" return s.encode(encoding)[:length].decode(encoding, errors="ignore")
4ce138ab69532d3932c2a964edbf41cf1f6bc021
641,108
def kwarg(string, separator='='): """Return a dict from a delimited string.""" if separator not in string: raise ValueError("Separator '%s' not in value '%s'" % (separator, string)) if string.strip().startswith(separator): raise ValueError("Value '%s' starts with sep...
2f587e1a9cd22a08d5afa884c3dc443a83229a5d
641,109
import os def get_cudnn_version(): """Gets the cuDNN version installed on the machine, if possible. The `CUDA_HOME` environment variable will be used, if set, to locate the CUDA installation. Returns: the cuDNN version string, or None if cuDNN is not installed or the installation cou...
8981f9b04db21e4bfd5a5483807f75e89a3b63e9
641,110
def Williams(df, period=14): """ returns Williams indicator """ low = df['_l'].rolling(period).min() high = df['_h'].rolling(period).max() _will = -100*(high-df['_c'])/(high-low) return _will
332a662370ccac312851efffef706ffea23756b0
641,111
import os import ctypes def administrator(): """ Return True if current user is administrator, otherwise False """ return bool(ctypes.windll.shell32.IsUserAnAdmin() if os.name == 'nt' else os.getuid() == 0)
53e94d8c7424e8478f9c3f18d22b578bbd69df70
641,112
def reindent(txt): """ reindents according to { and } braces. strips all whitespace, possibly not smartest thing to do. oh well. """ res = '' indent = 0 for l in txt.split("\n"): l = l.strip() if l.startswith("}"): indent -= 1 if indent < 0: ...
e985b5e8e03a81a80d2a60f23fc0e656439971ef
641,114
import fnmatch import os import logging def findFile(workdir, ext=None, pref=''): """ Check whether a file starting with `pref` and ending with `ext` exists. """ rs = fnmatch.filter(os.listdir(workdir), "{}.{}".format(pref, ext)) if rs: return os.path.join(workdir, rs[0]) else: ...
5a062d73435fc83920cf216fe641745cd41d32c2
641,117
def get_masks(tokens, max_seq_length): """Mask for padding""" if len(tokens)>max_seq_length: raise IndexError("Token length more than max seq length!") return [1]*len(tokens) + [0] * (max_seq_length - len(tokens))
72472a07b246dafce44d430d3de89e7f189d6c72
641,118
def orientation(u, v, w): """Computes the orientation (+/-1) of a basis""" det = u.dot(v.cross(w)) if det >= 0: return +1 else: return -1
1b6d99c1f38ca944d9a535ce48e065ff821dbaa9
641,119
import requests from bs4 import BeautifulSoup def get_lyrics_soup(url): """ Get a BeautifulSoup4 representation of a url :param str url: URL to read :rtype: BeautifulSoup :return: BeautifulSoup4 object of the loaded url """ html_text = requests.get(url).text soup = BeautifulSoup(html...
c5cdbe4adf1ff67b71cc39575e5005e7854d854e
641,120
import json def open_locale_file(fname): """Opens a locale file""" with open(fname) as json_file: return json.load(json_file)
903414bddf5335d5a1d1b51e835d59cc5df0b06b
641,121
import click def decorator_customize_config_file(f): """ CLI option to customize configuration file name. By default it is 'samconfig.toml' in project directory. Ex: --config-file samconfig.toml :param f: Callback function passed by Click :return: Callback function """ config_file_attrs = ...
efcb1bb57c9626227eb835f5d0046af945529cf9
641,122
def coroutine(func): """A decorator to automatically prime coroutines""" def start(*args, **kwargs): cr = func(*args, **kwargs) next(cr) return cr return start
79484b39fb68c4630e6a118b3e0606305116eeae
641,123
from pandas import NA from contextlib import suppress def _is_pandas_na(x): """Test if x is pandas.NA. We intentionally do not use this function to return `True` for `pd.NA` in `is_scalar_nan`, because estimators that support `pd.NA` are the exception rather than the rule at the moment. When `pd.NA` ...
92ad037f049829c6e8aa21516b625392a310f852
641,124
def plsPredict(pls, X, realY): """Given a PLSR model pls, and independent variables X, predict Y, and calculated difference to realY """ predY = pls.predict(X) dY = realY - predY return predY, dY
bd7d67f928af73ab06720daa7cb806603c3e09ca
641,125
def build_id_table(artifact_cursor): """Build the map of object ids to file paths. Args: artifact_cursor: the database cursor """ # for each row in the db, take the object id, parent path, and name, then create a tuple in the dictionary # with the object id as the key and the full file path...
08c59b0b0d21bb8ab0b38bbbac50ee55d55ab151
641,126
import json def dumpJson(path: str, data: dict): """ Dump data to json path. Returns ------- `tuple(path or exception, True or False)` : First item in tuple is a path if dumping succeeds, else it's an exceptions. Same thing goes for the second tuple """ try: with open(pat...
22d568e0833ee325a273967c4752e15ca469c3e8
641,128
import re import csv import logging def parse_sample_exp_args(sample_sheet_path): """ parses sample info into dict param: sample_sheet_path (str) : sample info path from args return: sample_info_dict (dict) : dict of info to pass to pipeline """ sample_info_fields_...
3be19d872ee61f4b3a1fec53d591183d5a40107b
641,129
def binomial_variance(n, p): """Does what it says it does.""" return n*p*(1-p)
c523e44821e4c0b9b3dc79c7fc63a107e9d04486
641,130
import os def filter_fcs_files(fcs_dir: str, exclude_comps: bool = True, exclude_dir: str = 'DUPLICATES') -> list: """ Given a directory, return file paths for all fcs files in directory and subdirectories contained within Parameters ---------- fcs_dir: s...
50b7d47a8f1254439278c495a2925dc88df6bdfe
641,131
def select_color_variety(frames, num_selected): """Select captures so that they are not too similar to each other. """ avg_color_sorted = sorted(frames, key=lambda x: x.avg_color) min_color = avg_color_sorted[0].avg_color max_color = avg_color_sorted[-1].avg_color color_span = max_color - min_co...
d0dd2e8e639b50bc188e1c640c95c7b6d2245ba1
641,132
def compact_form_of(walk): """A nicer format for printing.""" string_form = [str(e) for e in walk] return '-'.join(string_form)
62b7600b36b644e6c0108baa2b9c6bebfe46c514
641,133
import hashlib def checksum(path, hash=hashlib.sha256, blocksize=65536): """ Args: path (str | Path | None): Path to file hash: Hash algorithm to use blocksize (int): Returns: (str): Hex-digest """ if isinstance(hash, str): hash = getattr(hashlib, hash) ...
bc41d2f2dcc351f0b8cba597b34b916e14b6e672
641,134
import json def document_contents_differ(old, new, threshold=20): """Returns whether the two document contents differ sufficiently to merit a new backup.""" # In both the road and schedule file formats, the significant differences would occur in the # second level of the JSON object. if old == new: ...
a6f5248949bb630458ba2c34eff0f0d569dac131
641,135
import re def nearest(s: str, t: str, start: int) -> int: """Returns the beginning index of the answer span nearest to start index. If answers spans are found at equal distance on the left and right, return the left. """ gap = len(t) best = -1 ps = re.escape(s) if s[0].isalnum(): p...
ac13ac37e0daed2bef157da167b29722008508ee
641,136
def tfbs_filter(tfbs_data, tf_list, window_size=1000, min_acc_value=3): """Filters binding sites according to accumulation values in the moving window. Keyword arguments: -- datasets: GMQLDatasets containing TFBSes -- window_size: width of the moving window used to filter TFBS (defau...
672e39eb69fdd19e46096feda6ce0738b47465b3
641,138
import re def isNChar(znak): """Provjerava je li znak nchar""" p = re.compile('^[ -~]$') if (p.match(znak) is None or znak == '"'): return False return True
9f467b365542675eea9543e584d0e0f552448be1
641,139
def uuid(anon, obj, field, val): """ Returns a random uuid string """ return anon.faker.uuid(field=field)
69eb794505b871c39178e561f263f0bbb9ef384e
641,140
def safe_eval(command, module, allowed): """ A wrapper for the python eval() function that enforces the use of a list of allowable commands and excludes python builtin functions. This enables the use of an eval statement to convert user string input into a function or method without it being readily...
73e3d452c1af16d0dcf4c939ddacd0a2e47c5911
641,141
def _stringsToObjects(strings, arglist, proto): """ Convert an AmpBox to a dictionary of python objects, converting through a given arglist. @param strings: an AmpBox (or dict of strings) @param arglist: a list of 2-tuples of strings and Argument objects, as described in L{Command.arguments}. ...
a045154c7b775c8ae64fb6c47be4424cb1f01733
641,142
def unpackByte(fmt = b'11111111', byte = 0x00, boolean = True): """unpacks source byte into tuple of bit fields given by fmt string. Each char of fmt is a bit field length. returns unsigned fields values. Assumes network big endian so first fmt is high order bits. Format string is numbe...
359a439c60a3fccae7028bb54bf9c4fbb79d4be2
641,144
def normalize( df, baseline = 0.1 ): """ Normalize all spectrum. :param df: The Pandas DataFrame to normalize. :param baseline: Baseline correction threshold or False for no correction. [Default: 0.1] :returns: The normalized DataFrame. """ df = df.copy() df /= df.max() if b...
65a7a0238736c2c5a5e21b4bfc0205aca9f9f778
641,145
import os def get_running_pid(filename): """Retrieve the PID number from the given ``filename``. :param str filename: path to file to read the PID from :return: the PID number of a Sopel instance if running, ``None`` otherwise :rtype: integer This function tries to retrieve a PID number from the...
992bff266018baeb65ca0f071a9dc779a0a04271
641,147
import re def literals(choices, prefix="", suffix=""): """Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix+re.escape(c)+suffix for c in choices.split())
6e5aa234b11560738c72b31bd5c8090d4a673635
641,148
import numpy def csch(arg): """ Hyperbolic cosecant """ return 1 / numpy.sinh(arg)
cb9543721847120db738b0fd166402ed76178d95
641,150
def candidate_expansion_terms(tokens, k, wv): """Gets the candidate expansion terms""" candidates = set() for token in tokens: # check if the token is in the vocabulary if token in wv.vocab.keys(): result = wv.similar_by_word(token) limit = k if len(result) > k else l...
e1e30f0ed12765fda541ceda5af285c6f6a4b7e9
641,151
def register(client, username, password, password2=None, email=None): """Helper function to register a user""" if password2 is None: password2 = password if email is None: email = username + '@example.com' return client.post('/register', data={ 'username': username, '...
17936c2f52da3fe46bd27d543fdc890c22bb60dd
641,152
def get_underlying_type_name(parameter_type: str) -> str: """Get the underlying type name of the given type. Strip away information from type name like brackets for arrays, leading "struct ", etc. leaving just the underlying type name. """ return parameter_type.replace("struct ", "").replace("[]", ...
a2974b8bee3d7ead5772079442b77e2465fcd9c8
641,153
def read_vocab(vocab_dir,vocab_size=10000): """读取词汇表""" # words = open_file(vocab_dir).read().strip().split('\n') frequencys={} rank=0 with open(vocab_dir) as fp: # 如果是py2 则每个值都转化为unicode words = [] for line in fp.readlines(): #print (line) word=line.s...
b653fb5c0ae68b288e51cd17dbf79906375c2d95
641,154
def round_time(time): """Round up or down time based on set break_point.""" minutes = time.minute if time.second < 30 else time.minute + 1 hours = time.hour break_point = 7 # minutes if minutes > 45 + break_point: hours += 1 minutes = 0 elif minutes > 30 + break_point: m...
90a175efd631b60e485ca514d8a119f0f894b260
641,155
def get_speed_model_indices(reduced_tile): """ Extracts the speed model indices for the data structure """ speed_model_indices = set() for site in reduced_tile['sites']: for site_pin in site['site_pins'].keys(): if site['site_pins'][site_pin] is None: continue ...
01c4a1d9ccdd507ec6fdc4d3815324fb24351d52
641,156
import torch def log_trick(dot_product): """ loss = log(1 + e^(dt)) - s * dt """ return torch.log(1 + torch.exp(-torch.abs(dot_product))) + dot_product.clamp(min=0)
8425838d1d47a0467b0f1eac7c6003d5ab6bc441
641,157
import requests def is_domain_valid(dial_url): """校验domain有效性""" print(("check if {} is valid to access".format(dial_url))) try: # 关闭重定向开关,否则拿到的是302目标页面的响应,状态码为200 resp = requests.get(dial_url, verify=False) print(("{}({})".format(dial_url, resp.status_code))) # 登录重定向 ...
fc3a445cecde4add9c28d4769e9aadabf08e0764
641,158
def wind_setup (wind_v, wind_d, h_bar, a, b, c, h_0): """ Calculate wind set-up at n(=2) locations """ h_wind = (c(wind_d) * wind_v ** a ) / ((h_0 + h_bar) ** b) return h_wind
f7ba2cb10171a7494cf8930fc4aa4c774ea5b62b
641,159
from pathlib import Path import gzip def gzip_archive(directory: str, glob_pattern: str) -> None: """GZip files, deletes, and places results in nested '/archive' subdirectory""" filepath = Path(directory) archivepath = Path(directory) / "archive" files = [file for file in filepath.glob(glob_pattern) i...
34a1726fa43ecbae4e94122d80741dc420e5d13b
641,160
import json def load_category_names(category_names_file): """ Load the category file names of flowers Parameters: category_names_file - path name (starting from app current working directory) including the filename and its extension Returns: catalog of flower classes and labels """ ...
8093c23fe1b627d0f0019e3110a2e788a79599be
641,161
def dict_label_and_image(labels_name, labels_txt, images_path): """ labels_name:main目录下txt文件 labels_txt:列表,标注数据的绝对路径 iamges_path:列表,图像数据的绝对路径 return: {label_name: [label_txt_path, image_path], ...} """ dict_label_image = {} for name in labels_name: for label_txt_...
6fe2c5e2e49d1c3939f841d1421eae91eaa5aeb1
641,162
def to_coverage(total_n_reads, species_abundance, read_length, genome_size): """Calculate the coverage of a genome in a metagenome given its size and abundance Args: total_n_reads (int): total amount of reads in the dataset species_abundance (float): abundance of the species, between 0 and ...
86ac080ecd95983f40394dd546a0cab4fa85cc9a
641,163
def lz77_decompression(encoded_message): """ Decompress the given encoded string. Return the initial file in representation of string """ unpack = '' i_pack = 0 i_unpack = 0 while i_pack < len(encoded_message): if encoded_message[i_pack] != '#': unpack += encoded_mes...
dc24b0ed70b7a4f631be8279454b750b714fdcfd
641,164
def get_targets_in_network_of_expansion(node_file): """ In the network of expansion, the targets are scored 1.00. This function gets the targets in the network by identifying the nodes with score 1. """ targets_in_network = set() with open(node_file, 'r') as node_fd: for line in node_fd:...
f210f55a2e23d15dd287a1b12162577dd72007e2
641,165
def evaluate_row(row): """Evaluate a given row for various threats Input: row : list of row Output: white and black threats [n, n, n, n], [n, n, n, n] """ white_threats = [0, 0, 0, 0, 0, 0] # [win, straight threat, four threat, three threat, broken three, open two] black_threats = [0, 0,...
08d79c9e4b1cfeda8b1db59a96def356b6207544
641,166
import argparse import os def parse_args(): """ Parse basic input arguments. """ parser = argparse.ArgumentParser(description='Periodically log the site code of a given website.') parser.add_argument("url", type=str, help="the URL of the website to monitor.") parser.add_argument("-b", "--baseline"...
d2f97af725bbbf7e2808ea6b926f7edd55e0caf3
641,167
import subprocess import json def inventory_json(inventory_file): """Execute uam's dynamic inventory script and capture stdout. :param inventory_file: Location of uam dynamic inventory script :type inventory_file: str """ call_args = ['python', inventory_file] output = subprocess.check_output...
46ec57f263f4386022ee4754fa69592641d9c47c
641,168
def get_title(obj, objid): """ Returns title value of the object with given ID. :param obj: Structure containing YAML object ( nested lists / dicts ). :param objid: YAML ID of given node. :return: Title of given ID. """ result = None if isinstance(obj, dict): for key, val in o...
eac7045d937a27319b32acfbb431d5126243801a
641,169
import pytz def get_utc(dt): """ Converts datetime to UTC timezone More info: http://pytz.sourceforge.net/ """ return dt.replace(tzinfo=pytz.utc)
50268554b3e22946f08cff46ef2b6d74f60f1b41
641,171
import random def rand_int(start=1, end=10, seed=None): """ Returns a random integer number between the start and end number. .. versionadded:: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. vers...
e7e56a2b3f6b7684fe75c26ac96b59215db953f0
641,172
import hashlib def hash(input: str): """ Function to hash a sentence Parameters ---------- input : str Input sentence to hash. Returns ------- n : int Hashed value of the sentence. """ t_value = input.encode("utf8") h = hashlib.sha256(t_value) n = int...
4790611af2eacd9edc3c6e3550a1ccb46652b069
641,173