content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _PrepareDevicePath(vm, link): """Find device path and grant full permission. Args: vm: VirtualMachine object. link: string. Represents device path. Returns: String represents the actual path to the device. """ path = vm.RemoteCommand('readlink -f %s' % link)[0][:-1] vm.RemoteCommand('sudo chmod 777 %s' % path) return path
4b34f3338ce0b328ff52d27f418674ad5c8a44da
569,342
def parse_requirements(fname): """Read requirements from a pip-compatible requirements file.""" with open(fname): lines = (line.strip() for line in open(fname)) return [line for line in lines if line and not line.startswith("#")]
9b27d34324b5ea304ff5c66289193640a385f393
679,356
def arg_from_keywords(node, arg): """Retrieves a keyword argument from the node's keywords. Args: node (ast.Call): a node that represents a function call. For more, see https://docs.python.org/3/library/ast.html#abstract-grammar. arg (str): the name of the argument. Returns: ast.keyword: the keyword argument if it is present. Otherwise, this returns ``None``. """ for kw in node.keywords: if kw.arg == arg: return kw return None
1c05737474e426eccd9337652a27cbc0118677b0
231,605
def odict_representer(dumper, self): """Serialize OrderedDict items in their order.""" return dumper.represent_mapping('tag:yaml.org,2002:map', self.items())
022025d70f826319796383857a1423c258f9879a
549,904
def some(*fs): """ Create a function that returns the first non-``None`` result of applying the arguments to each ``fs``. """ def _some(*a, **kw): for f in fs: result = f(*a, **kw) if result is not None: return result return None return _some
f7e0b7842d25107dc81c0eb913ad2d74aff0f6f7
385,741
def pad_time(timestring, pos='start'): """ Returns a 12 digit string as time by padding any missing month, day, hour or minute values. If `pos` is `start`: Pad with year=0, month=1, day=1, hour=0, min=0 If `pos` is `end`: Pad with year=9999, month=12, day=31, hour=23, min=59 Default is to pad with start position. """ yr = int(timestring[:4]) if pos == 'end': padder = "999912312359" else: # Default to start padder = "000001010000" if len(timestring) < 12: timestring = timestring + (padder[len(timestring):]) return timestring
1be1e98b8ac6d051acc1c2bfc887bd6b59534a16
380,175
def get_photo_url(photo, handler): """Returns the URL where this app is serving a hosted Photo object.""" id = photo.key().name().split(':')[1] return handler.get_url('/photo', id=id)
da4338b5e5089d1aa330355c82023a9201d2aa24
298,904
def escape_tab(s: str) -> str: """Replaces each tab character (\\t) in the input with \\\\t""" return s.replace('\t', '\\t')
44baf045af9a4779ce43aa4158c720c317f753dc
559,493
def assemble_url(league_id: int) -> str: """Assemble the ranking HTML's URL for the league with that ID.""" template = ( 'http://www.basketball-bund.net/public/tabelle.jsp' '?print=1' '&viewDescKey=sport.dbb.views.TabellePublicView/index.jsp_' '&liga_id={:d}' ) return template.format(league_id)
42c72c2c1c27430f343a063e7a6aded7d94de578
140,031
import csv def read_lun_file(filename): """Read lun csv file and return the list.""" lunlist = [] with open(filename, 'r') as cvsfile: filereader = csv.reader(cvsfile, delimiter=',') for row in filereader: lunlist.append(row) del lunlist[0] return lunlist
4ad633dcb673c50fc43d9ee81edb88d34c4b2f89
657,639
from typing import List from typing import Callable import functools def chain_calls(*funcs: List[Callable]) -> Callable: """Chain multiple functions that take only one argument, producing a new function that is the result of calling the individual functions in sequence. Example: ```python f1 = lambda x: 2 * x f2 = lambda x: 3 * x f3 = lambda x: 4 * x g = chain_calls(f1, f2, f3) assert g(1) == 24 ``` Returns: Single chained function """ def call(x, f): return f(x) def _inner(arg): return functools.reduce(call, funcs, arg) return _inner
a7963abc51f96e23d2b188edd6c0d8e8146dd842
460,157
def parse_fromaddr(fromaddr): """Generate an RFC 822 from-address string. Simple usage:: >>> parse_fromaddr('[email protected]') '[email protected]' >>> parse_fromaddr(('from', '[email protected]')) 'from <[email protected]>' :param fromaddr: string or tuple """ if isinstance(fromaddr, tuple): fromaddr = "%s <%s>" % fromaddr return fromaddr
20dc1083eeed1b57cb4fa5a0d4fffb351cd44ecc
435,590
def get_content(filename): """Return a tuple of ints from a given file. """ with open(filename) as stream: return tuple(map(int, stream.readlines()))
195f02d317fc33cade1384498f58f42b1383df7d
369,175
def average_tol_numpy(values, tolerance): """Compute the mean of values where value is > tolerance :param values: Range of values to compute average over :param tolerance: Only values greater than tolerance will be considered """ return values[values > tolerance].mean()
9c68aa3058879e5b30d63dffc34aff0916c6c76d
417,409
def get_eventnames(file): """Return a list of sorted temporal event names in trials.""" trials = file.intervals['trials'] event_names = [] for name in trials.colnames: t = trials[name].data[-1] try: if trials['start_time'][-1] <= t <= trials['stop_time'][-1]: event_names.append(name) except: pass ts = [trials[name].data[-1] for name in event_names] event_names = [name for _, name in sorted(zip(ts, event_names))] return event_names
b0bb8c3e4b844475b63230425750467a63bb2c3d
104,106
def funql_template_fn(target): """Simply returns target since entities are already anonymized in targets.""" return target
a5f95bd6b7feabb4826fff826e6638cd242e04d6
17,102
from typing import Optional def get_uri_parent(uri: str) -> Optional[str]: """Return URI of parent collection with trailing '/', or None, if URI is top-level. This function simply strips the last segment. It does not test, if the target is a 'collection', or even exists. """ if not uri or uri.strip() == "/": return None return uri.rstrip("/").rsplit("/", 1)[0] + "/"
b764eb6cdfd5b51265a234419b47aba9475caf7d
613,807
def test(azote, phosphore, potassium): """3 values between 0 and 1, summing to 1. Error is the distance between the given 3d point and the expected 3d point. """ expected = 0.3, 0.2, 0.5 return ( 1 - ( (azote - expected[0]) ** 2 + (phosphore - expected[1]) ** 2 + (potassium - expected[2]) ** 2 ) ** 0.5 )
9f3d6504dea2b04d09272e0c7f5bbf5c5c34c846
306,140
def labor_supply_shock(t, states, param, t_start_lockdown, t_end_lockdown, l_s): """ A function returning the labor reduction due to lockdown measures. Parameters ---------- t : pd.timestamp current date param: np.array initialised value of epsilon_S states : dict Dictionary containing all states of the economic model t_start_lockdown : pd.timestamp start of economic lockdown t_end_lockdown : pd.timestamp end of economic lockdown l_s : np.array number of unactive workers under lockdown measures (obtained from survey 25-04-2020) Returns ------- epsilon_S : np.array reduction in labor force """ if t < t_start_lockdown: return param elif ((t >= t_start_lockdown) & (t < t_end_lockdown)): return l_s else: return param
f53e0fae0ec7e90b527dda80534f4aeafa394060
392,507
import socket def is_valid_ip_address(address, family=socket.AF_INET): """ Check if the provided address is valid IPv4 or IPv6 address. :param address: IPv4 or IPv6 address to check. :type address: ``str`` :param family: Address family (socket.AF_INTET / socket.AF_INET6). :type family: ``int`` :return: ``bool`` True if the provided address is valid. """ try: socket.inet_pton(family, address) except socket.error: return False return True
f6c6c670c617ff88f8f7c95a1cb1558f3813bf8e
486,931
def xyzs2xyzfile(xyzs, filename=None, basename=None, title_line=''): """ For a list of xyzs in the form e.g [[C, 0.0, 0.0, 0.0], ...] convert create a standard .xyz file :param xyzs: List of xyzs :param filename: Name of the generated xyz file :param basename: Name of the generated xyz file without the file extension :param title_line: String to print on the title line of an xyz file :return: The filename """ if basename: filename = basename + '.xyz' if filename is None: return 1 if filename.endswith('.xyz'): with open(filename, 'w') as xyz_file: if xyzs: print(len(xyzs), '\n', title_line, sep='', file=xyz_file) else: return 1 [print('{:<3}{:^10.5f}{:^10.5f}{:^10.5f}'.format(*line), file=xyz_file) for line in xyzs] return filename
e9ab2f3436db3a54f7d60b5fd2c396e681f4090c
342,548
def eaton(v, vn, hydrostatic, lithostatic, n=3): """ Compute pore pressure using Eaton equation. Parameters ---------- v : 1-d ndarray velocity array whose unit is m/s. vn : 1-d ndarray normal velocity array whose unit is m/s. hydrostatic : 1-d ndarray hydrostatic pressure in mPa lithostatic : 1-d ndarray Overburden pressure whose unit is mPa. v0 : float, optional the velocity of unconsolidated regolith whose unit is ft/s. n : float, optional eaton exponent Returns ------- ndarray Notes ----- .. math:: P = S - {\\sigma}_{n}\\left(\\frac{V}{V_{n}}\\right)^{n} [4]_ .. [4] Eaton, B. A., & others. (1975). The equation for geopressure prediction from well logs. In Fall Meeting of the Society of Petroleum Engineers of AIME. Society of Petroleum Engineers. """ ves = (lithostatic - hydrostatic) * (v / vn)**n pressure = lithostatic - ves return pressure
80abde12e6890e8ae1febd52a0e1e86a65128d78
575,896
import math def obliquity_correction_deg(mean_obliquity_of_ecliptic_deg, julian_century): """Returns Obliquity Correction in Degrees with Mean Obliquity Ecliptic, mean_obliquity_of_ecliptic_deg and Julian Century, julian_century.""" obliquity_correction = mean_obliquity_of_ecliptic_deg + 0.00256 * math.cos( math.radians(125.04 - 1934.136 * julian_century) ) return obliquity_correction
838f1ca10ebd5299d515a39e7152dee4e1404021
493,139
def _prepare_round_config(round: str, round_config: dict) -> dict: """Internal function that combines a base config with a specific round config. The base config is updated with the round config, overwriting any common fields. Parameters ---------- round : str round_config : dict Returns ------- dict Raises ------ ValueError Raises an error if the resulting config dict is empty. Typically due to typos in the config file. """ config = {} if "Base" in round_config: config.update(round_config["Base"]) if round in round_config: config.update(round_config[round]) if not config: raise ValueError(f"Invalid configuration for round {round}") return config
f89343e9b06bf32ea87e0137868db441d455ae05
336,995
import base64 import gzip import json def decode(value, decompress=False): """Decodes response from Base64 encoded string.""" decoded = base64.b64decode(value) if decompress: decoded = gzip.decompress(decoded) return json.loads(decoded.decode())
f0c36cc9f3df5939365e069c900a78f3d4f47b69
563,481
def clamp_bbox(bbox, shape): """ Clamp a bounding box to the dimensions of an array Parameters ---------- bbox: ndarray([i1, i2, j1, j2]) A bounding box shape: tuple Dimensions to which to clamp """ [i1, i2, j1, j2] = bbox j1 = max(0, int(j1)) i1 = max(0, int(i1)) j2 = min(shape[1]-1, int(j2)) i2 = min(shape[0]-1, int(i2)) bbox[0:4] = [i1, i2, j1, j2] return bbox
d50391a17882c4070a8780d2ad745545741329d2
658,662
def latest(scores): """ Return the last score in the scores list. param: list of scores return: last score in scores """ return scores[-1]
4f28449255fe95eaaf5817f7b2e40ab8aff5100f
195,591
def calc_real_underlying_subst_rate(obs_aa_ident_full_protein, rand_ident_region1, rand_ident_region2, fraction_region1_residues=0.3): """Calculation of the real, underlying substitution rate in a protein with two regions of differing random identity. Estimation of the underlying substitution rate is the first step in calculating a normalisation factor, to remove the region1/region2 conservation attributable to the restricted subset of amino acids. Please see the associated article manuscript (in preparation) for a full explanation of the method. Example calculation: region1 = transmembrane(TM) region2 = non-transmembrane(nonTM) i = obs_aa_ident_full_protein = 0.60 #(i.e. 60% amino acid identity, 40% substitutions) fraction_TM_residues = 0.1 # the observed aa subst rate is 1 - obs_aa_ident_full_protein b = 1 - i = 1 - 0.60 = 0.4 # proportion of seq that is Membranous m = fraction_TM_residues = 0.1 # proportion of seq that is Soluble s = 1 - m = 1 - 0.1 = 0.90 # i.e. 90% of the residues are nonTM # random identity of TM region t = rand_ident_region1 = rand_TM = 0.12 # random identity of nonTM region n = rand_ident_region2 = rand_nonTM = 0.06 # real underlying aa subst rate for full protein # solved from b = mx - mtx + sx - snx x = b / ((m*-t) + m - n*s + s) = 0.428 Parameters ---------- obs_aa_ident_full_protein : float Observed amino acid identity of the full pairwise alignment "observed" in that it always includes some position that have had a substitution to the same AA (e.g. Leu to Leu), which are unobserved. Typically excluding gaps, which are heavily biased by splice variants, etc, and are excluded from AAIMON calculations. E.g. 0.6, for 60% amino acid identity. rand_TM : float Random identity of the TM region. e.g. 0.124 for 12.4% rand_nonTM : float Random identity of the nonTM region. e.g. 0.059 for 5.9% fraction_TM_residues : float Fraction of TM residues in protein sequence, e.g. 0.1 (10% TM, 90% nonTM) Used to estimate the real underlying AA substitution rate from the observed AA subst. rate. Returns ------- x : float Amino acid propensity normalisation factor. Real, underlying substitution rate for the full protein. Usage ----- # calculate the TM/nonTM conservation ratio for a particular query and homologue TM_over_nonTM_cons_ratio = percentage_identity_of_TMD / percentage_identity_of_nonTMD # calculate the amino acid propensity normalisation factor. obs_aa_ident_full_protein, rand_TM, rand_nonTM, fraction_TM_residues = 0.60, 0.136, 0.055, 0.10 real_underlying_subst_rate = calc_real_underlying_subst_rate(obs_aa_ident_full_protein, rand_TM, rand_nonTM, fraction_TM_residues) aa_prop_norm_factor = calc_aa_prop_norm_factor(real_underlying_subst_rate, rand_TM, rand_nonTM) # to normalise, divide the AAIMON by the aa_prop_norm_factor TM_over_nonTM_cons_ratio_normalised = TM_over_nonTM_cons_ratio / aa_prop_norm_factor """ # the oBserved aa subst rate is 1 - obs_aa_ident_full_protein b = 1 - obs_aa_ident_full_protein # proportion of seq that is Membranous m = fraction_region1_residues # proportion of seq that is Soluble s = 1 - m # random identity of Tm region t = rand_ident_region1 # random identity of NonTM region n = rand_ident_region2 # real underlying aa subst rate for full protein # solved from b = mx - mtx + sx - snx x = b / ((m * -t) + m - n * s + s) return x
5bdc11a775210c968100602e57b1fcf71f44c112
506,667
def limits_testing(environment_state, lower_limits, upper_limits, observed_states_indices): """ Test the limits to compare the output with the reward function :param environment_state: current state (ndarray) :param lower_limits: lower physical limits (ndarray) :param upper_limits: upper physical limits (ndarray) :param observed_states_indices: indices of the observed states for the limit violation :return: True if limits are violated, False otherwise """ if any(environment_state[observed_states_indices] > upper_limits[observed_states_indices]) or\ any(environment_state[observed_states_indices] < lower_limits[observed_states_indices]): return True else: return False
157c151e5ad1c10f3bb752ada06a4b3d8fe459f9
140,843
from typing import Tuple def reverse_causal(effective_kernel_size: int) -> Tuple[int, int]: """Post-padding such that output has no dependence on the past.""" return (0, effective_kernel_size - 1)
df182b5c710fbb143c83d7c80a718ed9d1db9c9d
576,612
import json def read_json(json_file): """ Utility method to read a json file schema Parameters: ----------- json_file : string file name for the json schema Returns: -------- dictionary, as serialized in the json_file """ with open(json_file) as schema: val = json.load(schema) return val
68af62d70a71ce326e8027b9d7ccccf1bfd6b144
294,600
import json def json_to_dict(path): """ Given a path to a .json file returns a dict of the .json file Parameters ---------- path: path to .json file Output: dict of json file """ with open(path) as data_file: data = json.load(data_file) return data
bf33d559d3171d80a43010789eeef880eb25e9c8
558,914
def get_recs(user_recs, k=None): """ Extracts recommended item indices, leaving out their scores. params: user_recs: list of lists of tuples of recommendations where each tuple has (item index, relevance score) with the list of tuples sorted in order of decreasing relevance k: maximumum number of recommendations to include for each user, if None, include all recommendations returns: list of lists of recommendations where each list has the column indices of recommended items sorted in order they appeared in user_recs """ recs = [[item for item, score in recs][0:k] for recs in user_recs] return recs
490d0473e640c70457aa69a9af7dc7a4269e39d3
673,772
def _load_consultancy_facilities_sme(df): """_load_consultancy_facilities_sme Args: df (pd.DataFrame): Services income table from HESA (table-2a). Returns: df (pd.DataFrame): Consultancy and facilities income from SMEs. """ df = df[df['Unit'] == '£000s'] df = df[ (df['Type of organisation'] == "SME's") & ((df['Type of service'] == 'Facilities and equipment related') | (df['Type of service'] == 'Consultancy'))] df['Value'] = (df['Value'] * 1000).astype(int) return df
606651c61e222a30cd46abdcf1d4f2080025a064
462,392
from pathlib import Path def setup_results_dir(experiment_name): """Create the directories for the results.""" root = Path(__file__).parent.parent result_path = root / "batchpredict" results_dir = ( result_path / experiment_name ) results_dir.mkdir(parents=True, exist_ok=True) print(f"Writing results to {results_dir}") return results_dir
17e79aa996538f31b26f5d4d2aaa523c5b2037d0
570,803
def get_skel(s): """Get a tuple representing an instrution skeleton. Args: s: String of chars in {0, 1, x} of the skeleton Returns: Tuple (before, length, after), where - before is the number before the mask - length is the length of x's in the mask - after is the number after the mask """ i = 0 # get number before x's before = 0 while i < len(s): if s[i] != 'x': assert s[i] == '0' or s[i] == '1' before += before before += int(s[i]) else: break i += 1 # get number of x's xlen = 0 while i < len(s): if s[i] == 'x': xlen += 1 else: break i += 1 # get number of 0s after x's zerolen = 0 while i < len(s): if s[i] == '0': zerolen += 1 else: break i += 1 # get number afer x's after = 0 while i < len(s): assert s[i] == '0' or s[i] == '1' after += after after += int(s[i]) i += 1 return (before, xlen, zerolen, after)
c310480448e6a959cf2a68e14d19dcbadb908e18
648,582
def post_step1(records): """Apply whatever extensions we have for GISTEMP step 1, that run after the main step 1. None at present.""" return records
98287f6930db6aa025715356084b3bef8c851774
709,673
def get_diff_optreg(comp, opt): """ Returns difference between two arrays of same size. Actually unused. Parameters ---------- comp : ndarray Computed results. opt : ndarray Target values. Returns ------- diff : ndarray Difference between computed and target. """ return comp - opt
05ab55d03143cfb2a079ba02a4620aca994c3654
152,382
def record_sets_fetcher(record): """Fetch a record's sets.""" return record.get('_oai', {}).get('sets', [])
4c3eeb1d5ae0ce7c832192bfb16e17c5c08583bb
197,875
def Heun_step(f, told, uold, h): """ Usage: unew = Heun_step(f, told, uold, h) Heun's Runge-Kutta of order 2 solver for one step of the ODE problem, u' = f(t,u), t in tspan, u(t0) = u0. Inputs: f = function for ODE right-hand side, f(t,u) told = current time uold = current solution h = time step size Outputs: unew = updated solution """ # call f to get ODE RHS at this time step f1 = f(told, uold) # set stages z1 and z2 z1 = uold z2 = uold + h*f1 # get f(t+h,z2) f2 = f(told+h, z2) # update solution in time return (uold + h/2*(f1+f2))
9502e2343abcb17024fdcee0b90e8ebef026277f
159,953
def norm(v): """Computes the norm (length) of a vector v, represented as a tuple or list of coords.""" norm = 0 for n in v: norm += n**2 return norm**0.5
f453258226c31deba2e7735da987882c5627a936
453,499
def _decodeASCII(string): """Returns an ASCII decoded version of the null terminated string. Non ASCII characters are ignored.""" return str(string.decode("ascii", "ignore").split("\0", 1)[0])
1620817bf4f98f0a4459914a482b90d906133044
514,936
import base64 import json def gen_sig_claim_file(reference: str, digest: str, requested_by: str) -> str: """ Generated a claim file to be signed based on given data. Args: reference: Docker reference for the signed content, e.g. registry.redhat.io/redhat/community-operator-index:v4.9 digest: Manifest digest for the signed content, usually in the format sha256:xxx requested_by: Name of the user that requested the signing, for auditing purposes """ claim = { "critical": { "image": {"docker-manifest-digest": digest}, "type": "atomic container signature", "identity": {"docker-reference": reference}, }, "optional": {"creator": requested_by}, } claim = base64.b64encode(json.dumps(claim).encode("utf-8")) return claim.decode("utf-8")
a411233510c0f2a3b59c464d2483859bf2f21f2d
352,366
import requests def is_arduino_library(repo): """Returns if the repo is an Arduino library, as determined by the existence of the 'library.properties' file. """ lib_prop_file = requests.get( "https://raw.githubusercontent.com/adafruit/" + repo["name"] + "/master/library.properties" ) return lib_prop_file.ok
89ccba5852eba6e746dad71c911abde4d51bc386
525,410
def m_total_from_m1_m2(mass1, mass2): """Return the total mass given the samples for mass1 and mass2 """ return mass1 + mass2
21476e4e92b9da043280a8553a13ceb54e8b4193
288,205
def _prepare_shape_for_squeeze(shape, axes): """ Creates the squeezed new shape based on the tensor and given axes. Args: shape (tuple): the shape of the tensor axes Union[None, int, tuple(int), list(int)]: the axes with dimensions squeezed. Returns: new_shape(tuple): the shape with dimensions squeezed. """ new_shape = [] ndim = len(shape) # Convert to set if isinstance(axes, int): if axes >= ndim or axes < -ndim: raise ValueError( f"axis {axes} is out of bounds for tensor of dimension {ndim}") axes = {axes} elif isinstance(axes, (list, tuple)): for axis in axes: if axis >= ndim or axis < -ndim: raise ValueError( f"axis {axis} is out of bounds for tensor of dimension {ndim}") axes = set(axes) elif axes is not None: raise TypeError( f"only int, tuple and list are allowed for axes, but got {type(axes)}") if axes is None: new_shape = [s for s in shape if s != 1] else: for idx, s in enumerate(shape): if s != 1 or (idx not in axes) and (idx - ndim not in axes): new_shape.append(s) # if an axis is selected with shape entry greater than one, an error is raised. if s != 1 and ((idx in axes) or (idx - ndim in axes)): raise ValueError( f"axis {axes} has shape entry {s} > 1, cannot be squeezed.") return tuple(new_shape)
0f984a9eab2b5897556c3001e2ca0c607035534f
55,141
def i_replaced(list_, i, value): """Return a new list with element i replaced by value. i : value Index to replace with value. value : value Value to replace at index i. None will return original list with element i removed. """ if value is not None: return list_[:i] + [value] + list_[i + 1 :] else: return list_[:i] + list_[i + 1 :]
88b9103b1439683553f12575ab3241071f994c2b
225,662
def replace_letters(string, encrypted, standard): """ Given a string, replace each encrypted letter with its equivalent frequency plaintext letter @param string is the string in which to replace characters @param encrypted is the encrypted letter alphabet @param standard is the standard language letter alphabet @returns the new decrypted string """ res = "" for letter in string: if letter not in standard: res += letter else: encrypted_distribution_index = encrypted.index(letter) res += standard[encrypted_distribution_index] return res
d23394d6b88b56a5d19b2ca18c70810cf355fe94
165,125
def make_slist(l, t_sizes): """ Create a list of tuples of given sizes from a list Parameters ---------- l : list or ndarray List or array to pack into shaped list. t_sizes : list of ints List of tuple sizes. Returns ------- slist : list of tuples List of tuples of lengths given by t_sizes. """ out = [] # output start = 0 for s in t_sizes: out.append(l[start:start + s]) start = start + s return out
b87ce7a430751d9b46e94609736bb9e25a180b27
89,077
def _get_text(node, tag, default=None): """Get the text for the provided tag from the provided node""" try: result = node.find(tag).text return result except AttributeError: return default
0777f70b82f5024bbf0fe2e90e3011c09d47df51
529,934
import re def escape_ansi(string): """Remove ansi-codes from help text.""" ansi_escape = re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]") return ansi_escape.sub("", string)
f9dbf939afcf0011faa04fc3c2017820548b167d
507,013
def chop_words(text, maximum_length=117): """ Deletes last word in a string until it does not exceed maximum length. Args: text (str): Status text. maximum_length (int): Maximum character length. Returns: str or ``None`` """ words = text.split() for i in range(len(words)): words.pop() chopped_text = ' '.join(words) if len(chopped_text) <= maximum_length: return chopped_text return None
793a536b7240b6cb6fb2a4796fb33d6a2a3e7e64
126,878
def unique(iterable): """Return unique values from iterable.""" seen = set() return [i for i in iterable if not (i in seen or seen.add(i))]
776d1003bb86415170b3406cce1a365fb06a494f
447,626
from typing import List from typing import Tuple def parse_linenos(term: str, max_val: int) -> List[Tuple[int, int]]: """Parse a comma-delimited list of line numbers and ranges.""" results: List[Tuple[int, int]] = [] if not term.strip(): return [] for term in term.strip().split(","): parts = term.split("-", 1) lower = int(parts[0]) higher = int(parts[1]) if len(parts) == 2 else lower if lower < 0 or higher < 0: raise ValueError( f"Invalid line number specification: {term}. Expects non-negative integers." ) elif lower > max_val or higher > max_val: raise ValueError( f"Invalid line number specification: {term}. Expects maximum value of {max_val}." ) elif lower > higher: raise ValueError( f"Invalid line number specification: {term}. Expects {lower} < {higher}." ) results.append((lower, higher)) return results
54af7c9556086c51b6d5eb7342fd603af80ea125
296,832
def fetch_following(api,name): """ Given a tweepy API object and the screen name of the Twitter user, return a a list of dictionaries containing the followed user info with keys-value pairs: name: real name screen_name: Twitter screen name followers: number of followers created: created date (no time info) image: the URL of the profile's image To collect data: get the list of User objects back from friends(); get a maximum of 100 results. Pull the appropriate values from the User objects and put them into a dictionary for each friend. """ friends_ls=[] for friend in api.get_friends(screen_name=name,count=100): #friend_name=api.get_user(screen_name=friend) dict_user={} dict_user['name']=friend.name dict_user['screen_name']=friend.screen_name dict_user['followers']=friend.followers_count dict_user['created']=friend.created_at.strftime('%Y-%m-%d') dict_user['image']=friend.profile_image_url_https friends_ls.append(dict_user) return friends_ls
3f71ccbfdafd744ed61dbec793b68c78e081274b
112,924
def insert_aux(seq): """ Auxiliary function for insert_at_junctions Returns the first element encountered """ list_insert = ["GGCAT", "GCAT", "CAT"] for insert in list_insert: if insert in seq: return insert return "-"
12a19f6bff877042b80123426141278b9005ff66
308,978
from pathlib import Path def create_target_absolute_file_path(file_path, source_absolute_root, target_path_root, target_suffix): """ Create an absolute path to a file. Create an absolute path to a file replacing the source_absolute_root part of the path with the target_path_root path if file_path is on the source_absolute_root path and replace the extension with target_suffix. If file_path is not on source_absolute_root return file_path with the target_suffix Parameters ---------- file_path : str or Path Path to a file source_absolute_root : str or Path a path that may be the start of file_path target_path_root : str or Path A path that will become the start of the path to the returned target path target_suffix : str The suffix to use on the returned target path Returns ------- Path The new absolute path to the file that was on file_path """ if Path(file_path).is_relative_to(source_absolute_root): target_relative_path_to_source_root = Path(file_path).relative_to(source_absolute_root) # target_relative_path_to_source_root is the relative path that will be added onto the export folder path return Path(target_path_root, target_relative_path_to_source_root).with_suffix(target_suffix) if not Path(file_path).is_absolute(): # path is relative add target path_root and new suffix return Path(target_path_root, file_path).with_suffix(target_suffix) # file is not in the source path return the file path with the new suffix return Path(file_path).with_suffix(target_suffix)
0d24f8544752967815bd8ddceea15b371076c500
29,485
def languages(context, flag_type='', **kwargs): """ Templatetag languages :param context: Getting context :param flag_type: Default empty, It acepts the string 'square' :param kwargs: Classes to HTML tags :return: A dict with classes """ if flag_type == 'square': flag_type = 'flag-icon-square' default = dict(li_class='', a_class='') classes = dict(default, **kwargs) return { 'icon_class': flag_type, 'classes': classes, 'redirect_to': context.request.get_full_path }
4530bdbb780f6c244eb46f6c7603305076f8ee29
284,740
def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal and keyword arguments to connect:: @receiver(signal_object, sender=sender) def signal_receiver(sender, **kwargs): ... """ def _decorator(func): signal.connect(func, **kwargs) return func return _decorator
dbbde0855b2a657adaff9fa688aa158053e46579
706,551
def bbox2location(bbox): """ From bbox [x,y,width,height] to location [top,right,bot,left] Args: bbox (list): bounding box [x,y,width,height] Returns: **location** (list) - coordinate [top,right,bot,left] """ location = [bbox[1],bbox[0]+bbox[2],bbox[1]+bbox[3],bbox[0]] return location
cca690d72c7887d96eea03810b439c06878dba4f
375,147
def is_positive(value): """Helper function that returns True if a given value is greater than zero. """ return value > 0
6caa36a857f5db476a010090abb630e1d6fdc481
425,002
def inner(v,w): """return the inner product of two vectors using the convention of conjugating the first argument """ return v.conj().dot(w)
078a1c4e8e1f71f218633b06f2f2b7df87c842c4
502,842
def chromosomes_from_fai(genome_fai): """ Read a fasta index (fai) file and parse the input chromosomes. :param str genome_fai: Path to the fai file. :return: list of input chromosomes :rtype: list[str] """ chromosomes = [] with open(genome_fai) as fai_file: for line in fai_file: line = line.strip().split() chromosomes.append(line[0]) return chromosomes
45dba8dcdf7ac331be298619ab83319b0737c402
406,857
import math def get_rounded_pruned_element_number(total: int, sparsity_rate: float, multiple_of: int = 8) -> int: """ Calculates number of sparsified elements (approximately sparsity rate) from total such as number of remaining items will be multiple of some value. Always rounds number of remaining elements up. :param total: Total elements number. :param sparsity_rate: Prorortion of zero elements in total. :param multiple_of: Number of remaining elements must be a multiple of `multiple_of`. :return: Number of elements to be zeroed. """ remaining_elems = math.ceil((total - total * sparsity_rate) / multiple_of) * multiple_of return max(total - remaining_elems, 0)
9565c091965689249b80fbe62cc1d67461bf26a1
97,229
def get_cmd_name(name=__name__): """Get command name from __name__ within a file""" return name.split('.')[-1]
9dbc79b30b220f92199a56fc9ea2a0116fc1d7a2
368,602
from pathlib import Path def _path_to_file_or_directory_to_path_iterator(path): """Convert a path to a file or directory to an iterator over paths.""" path = Path(path) if path.is_dir(): paths = list(path.rglob("*")) else: paths = [path] return paths
0f6ddb81ea56b7d184d26930e1d3926da0a8a7ec
396,515
def _convert_node_attr_types(G, node_type): """ Convert graph nodes' attributes' types from string to numeric. Parameters ---------- G : networkx.MultiDiGraph input graph node_type : type convert node ID (osmid) to this type Returns ------- G : networkx.MultiDiGraph """ for _, data in G.nodes(data=True): # convert node ID to user-requested type data["osmid"] = node_type(data["osmid"]) # convert numeric node attributes from string to float for attr in {"elevation", "elevation_res", "lat", "lon", "x", "y"}: if attr in data: data[attr] = float(data[attr]) return G
388d8b6c148ceebdad85f2b1d4ccbed7ca5d9e32
654,354
from typing import IO def read_line(f: IO[str]) -> str: """ Read a single non-comment line from a file :param f: The file :return: the line """ line = f.readline() while len(line) > 0 and line[0] == '#': line = f.readline() return line
205d6f9760ee070f6d2edcb566fd41cd62cbbafb
482,713
def get_distinct_values(df, key): """Get the distinct values that are present in a given column.""" return sorted(list(df[key].value_counts().index.values))
0833a6024f34faa28fb45d73b7ad7e22ac7ba541
679,066
import math def distance(a, b): """Euclidean distance between two points Parameters ---------- a : list of array_like First 3D point b : list or array_like Second 3D point Returns ------- d : float Euclidean distance between a and b """ return math.sqrt((a[0] - b[0])*(a[0] - b[0]) + (a[1] - b[1])*(a[1] - b[1]) + (a[2] - b[2])*(a[2] - b[2]))
60d61d961aa419e0af8ee39e5c87088fc1314ff4
343,514
def linear_search(array, item): """Returns true if item is in array Time Complexity O(n) """ for i in range(len(array)): if array[i] == item: return True return False
0fde49a4d879fd6849b9464e4ff4ac9df4698181
298,129
def parse_magic_invocation(line): """ Parses the magic invocation for the commands As a general rule we want to forward the arguments to sfdx But we also need to pass the variable to capture the results %%sfdx:cmd {var?} {...options} """ args = {"variable": None, "sfdx_args": ""} line = line.strip() if line.startswith("-"): args["sfdx_args"] = line return args else: [variable, *sfdx_args] = line.split(" ") args = {"variable": variable, "sfdx_args": " ".join(sfdx_args)} return args
5dfc59010f968f91ceef5fa81f550349e66dcdaf
547,348
from typing import Any from contextlib import suppress def cast_str_to_bool(value: Any) -> bool: """Parse anything to bool. Params: value: Anything to be casted to a bool. Tries to be as smart as possible. 1. Cast to number. Then: 0 = False; anything else = True. 1. Find [YAML booleans](https://yaml.org/type/bool.html), [YAML nulls](https://yaml.org/type/null.html) or `none` in it and use it appropriately. 1. Cast to boolean using standard python `bool(value)`. """ # Assume it's a number with suppress(TypeError, ValueError): return bool(float(value)) # Assume it's a string with suppress(AttributeError): lower = value.lower() if lower in {"y", "yes", "t", "true", "on"}: return True elif lower in {"n", "no", "f", "false", "off", "~", "null", "none"}: return False # Assume nothing return bool(value)
784ffba5e07962c329ff0accb4896449fc849480
237,284
def safe_column_name(name): """Generate SQL friendly column name""" return '"{}"'.format(name).upper()
495b54a94c4350a8f20df5a1416a5c8c10d7a559
697,756
def points2d_at_height(pts, height): """Returns a list of 2D point tuples as 3D tuples at height""" if isinstance(pts, tuple): if len(pts) == 2: return [(*pts, height)] return [(pts[0], pts[1], height)] pts3d = [] for pt in pts: if len(pt) == 3: pts3d.append((pt[0], pt[1], height)) else: pts3d.append((*pt, height)) return pts3d
a4f56f3f04e45eec04a476be331006ab58e922bb
475,519
def line_text(*fields, **kargs): """ Transform a list of values into a tsv line :param fields: list of values as parameters :param kargs: optional arguments: null_value: value to interpret as None :return: tsv line text """ null_value = kargs.get("null_value", "") return "\t".join([str(x) if x is not None else null_value for x in fields]) + "\n"
0b3abf4f408b5f75807d0ee514f88d2c2e1f98bd
583,406
def extract_bits(bit, bit_dict): """Extract bits which is turend on (1). Args: bit (int): Bit to check. bit_dict (dict): Correspondance dict of bit and status. Return: valid_bit (:obj:`list` of :obj:`str`): List of bit which is turned on (1). Example: >>> sample_dict = { ... "S1": 0b001, ... "S2": 0b010, ... "S3": 0b100, ... } >>> extract_bits(0b101, sample_dict) ["S1", "S3"] """ assert all(isinstance(val, int) for val in bit_dict.values()), \ "bit_dict: all elements are expected to be 'int'" valid_bit = [ key for key, val in bit_dict.items() if not int(bit) & val == 0 ] return valid_bit
ed82cdfa070f36ebfe59e7efa46a956a0e2a950c
436,805
def posName(i): """ posName(i) - this function returns the positioner name Pi used in sscan record where i - specify the zero based positioner sequence number """ if i < 4: return "P%d" % (i+1) else: return "?"
099cdad08aea41f9500518efc528102513c4b985
411,101
import io def stream_binary(f): """ Create a data stream from a file path (str), raw bytes, or stream. """ if isinstance(f, str): return open(f, "rb") if isinstance(f, bytes): return io.BytesIO(f) if hasattr(f, "read"): if hasattr(f, "seek"): f.seek(0) return f
b9651a903ac9d8e3efac9c3bad8403296effba24
117,072
import re def remove_hyperlinks(text): """ Remove all hyperlinks and URLs from the raw text Args: text(str) -- raw text Returns: text(str) -- text clean from hyperlinks """ text = re.sub(r'https?://\S+', '', text) return text
a5042e83e5891a71dac274b0a6fdf4dc6513ae8c
205,775
def localhost_url(url, local_hostname): """Return a version of the url optimized for local development. If the url includes the string `localhost`, it will be replaced by the `local_hostname`. Parameters ---------- url : str The url to check Returns ------- str : The url, possibly converted to use a different local hostname """ return url.replace('localhost', local_hostname)
dc2cba2acc89fe4ad7da30da9e6a3a1c16465731
26,217
def split_string(joined, split_char="_"): """Split joined string and substitute back the null characters with an underscore if necessary. Inverse function of `join_strings(strings)`. Args: joined: str, the joined representation of the substrings. split_char: str, the character to split by. Returns: A tuple of strings with the splitting character (underscore) removed. Examples: ```python >>> split_string('asd__\x00xcv\x00\x00') ('asd', '', '_xcv__') ``` """ strings = joined.split(split_char) strings_copy = [] for s in strings: strings_copy.append(s.replace("\0", split_char)) return tuple(strings_copy)
c99d911dc82961a58821c96ba38e8a902eaa2e5d
458,654
def _get_vector_identifier(line): """Return the identifier from the vector string. """ return line.split()[0]
f3d8dd43d1e49461474fe855fec1ecd7707d34f7
641,681
def list_kinds(client): """ List all valid kinds for Azure Cognitive Services account. :param client: the ResourceSkusOperations :return: a list """ # The client should be ResourceSkusOperations, and list() should return a list of SKUs for all regions. # The sku will have "kind" and we use that to extract full list of kinds. kinds = {x.kind for x in client.list()} return sorted(list(kinds))
fd8b49f1b5e83109859c00491d0914da2e5ccdc2
502,124
import csv def load_csv(filename): """Load a CSV file and return a list with datas (corresponding to truths or predictions). """ datas = list() with open(filename, 'r') as opened_csv: read_csv = csv.reader(opened_csv, delimiter=',') for line in read_csv: datas.append(line[1]) # Clean the header cell datas.remove("Hogwarts House") return datas
c1cd1beb03baaba0ba5ab25d74459e44d5e8a557
94,076
def summarize_results(results, gene, holdout_cancer_type, signal, z_dim, seed, algorithm, data_type): """ Given an input results file, summarize and output all pertinent files Arguments --------- results: a results object output from `get_threshold_metrics` gene: the gene being predicted holdout_cancer_type: the cancer type being used as holdout data signal: the signal of interest z_dim: the internal bottleneck dimension of the compression model seed: the seed used to compress the data algorithm: the algorithm used to compress the data data_type: the type of data (either training, testing, or cv) """ results_append_list = [ gene, holdout_cancer_type, signal, z_dim, seed, algorithm, data_type, ] metrics_out_ = [results["auroc"], results["aupr"]] + results_append_list roc_df_ = results["roc_df"] pr_df_ = results["pr_df"] roc_df_ = roc_df_.assign( predictor=gene, signal=signal, z_dim=z_dim, seed=seed, algorithm=algorithm, data_type=data_type, ) pr_df_ = pr_df_.assign( predictor=gene, signal=signal, z_dim=z_dim, seed=seed, algorithm=algorithm, data_type=data_type, ) return metrics_out_, roc_df_, pr_df_
d1a9a55be3ef614871c805aaffe706dc10c70a83
221,451
def pack_byte_to_hn(val): """ Pack byte to network order unsigned short """ return (val << 8) & 0xffff
a0ab9ca7460c45470570bb0eb8a56a16e613b720
610,224
async def async_api_reportstate(hass, config, directive, context): """Process a ReportState request.""" return directive.response(name="StateReport")
3ee0b8b8e4ca874a43e9d7cf3aae9b426eda0e43
649,621
def profile_probability(kmer, profile_matrix): """ A function to return the probability of a kmer based on a profile matrix Args: kmer: the kmer profile_matrix: the profile matrix Return: The probability of kmer computed w.r.t the profile matrix """ matrix_row = {"A": 0, "C": 1, "G": 2, "T": 3} probability = 1 for i in range(len(kmer)): probability = probability*profile_matrix[matrix_row[kmer[i]]][i] return probability
8824952b2a8556131dddfb8fa91b3db30ae4cc99
597,009
import json def load_json(filepath): """Deserialize ``filepath`` to a Python object.""" with open(filepath, "r", encoding="utf-8") as fd: return json.load(fd)
fafd4d98d9a90a6050ca185ca8f1ce79205037f9
499,146
def _x_zip_matcher(art): """ Is this artifact the x.zip file? """ return art['name'].endswith('.zip')
b018870a12ad3f5ad54aec28f346973c575f9241
659,404
def rm_empty_indices(*args): """ Remove unwanted list indices. First argument is the list of indices to remove. Other elements are the lists to trim. """ rm_inds = args[0] if not rm_inds: return args[1:] keep_inds = [i for i in range(len(args[1])) if i not in rm_inds] return [[a[i] for i in keep_inds] for a in args[1:]]
4151f75bb11dd6275ae87382be4e0898be9bdedd
422,055
def _sum(a, i, j): """Return the sum of the elements from a[i] to a[j].""" if i > j: # T(n) = 0 return 0 if i == j: # T(n) = 1 return a[i] mid = (i+j)//2 return _sum(a, i, mid) + _sum(a, mid+1, j)
c6c37e946311cbf93cd720fb7a6bcbc4b8818a25
481,530
def isOverlap1D(box1, box2): """Check if two 1D boxes overlap. Reference: https://stackoverflow.com/a/20925869/12646778 Arguments: box1, box2: format: (xmin, xmax) Returns: res: bool, True for overlapping, False for not """ xmin1, xmax1 = box1 xmin2, xmax2 = box2 return xmax1 >= xmin2 and xmax2 >= xmin1
898331f7f0aced6a86b244e22ebb069423fee719
696,396
def select_login_fields(fields): """ Select field having highest probability for class ``field``. :param dict fields: Nested dictionary containing label probabilities for each form element. :returns: (username field, password field, captcha field) :rtype: tuple """ username_field = None username_prob = 0 password_field = None password_prob = 0 captcha_field = None captcha_prob = 0 for field_name, labels in fields.items(): for label, prob in labels.items(): if label in ("username", "username or email") and prob > username_prob: username_field = field_name username_prob = prob elif label == "password" and prob > password_prob: password_field = field_name password_prob = prob elif label == "captcha" and prob > captcha_prob: captcha_field = field_name captcha_prob = prob return username_field, password_field, captcha_field
9bd97028a10736fc34958546ec7362128824673a
88,956
import socket def check_ip(ip): """Check if an IP address has a reverse DNS that matches worldpay.com, and if it does, check that that hostname has the IP as one of its resolvables.""" try: hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(ip) except socket.herror: # No reverse DNS service available return False except socket.gaierror: # No match return False if hostname.endswith(".worldpay.com") or hostname.endswith(".rbsworldpay.com"): try: # The 80 here is because getaddrinfo is expecting to be used to open # sockets. We can ignore the port, we're just interested in the # resolved version. names = socket.getaddrinfo(hostname, 80) except socket.gaierror: # Forward DNS lookup error return False for family, type_, proto, canonname, sockaddr in names: if sockaddr[0] == ip: return True return False
023869e20e1c5d95e49233f2ff98561d9e85324d
456,830
def with_metaclass(meta, *bases): """Create a base class with a metaclass for py2 & py3 This code snippet is copied from six.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. Because of internal type checks # we also need to make sure that we downgrade the custom metaclass # for one level to something closer to type (that's why __call__ and # __init__ comes back from type etc.). class metaclass(meta): __call__ = type.__call__ __init__ = type.__init__ def __new__(cls, name, this_bases, d): if this_bases is None: return type.__new__(cls, name, (), d) return meta(name, bases, d) return metaclass("temporary_class", None, {})
513f9e212bd8f689b09c74867876d51ab1ac544b
19,072
def aggregate_run_results(collection_failures, test_results): """ Determines overall status of run based on all failures and results. * 'ERROR' - At least one collection failure occurred during the run. * 'FAIL' - Template failed at least one test * 'PASS' - All tests executed properly and no failures were detected :param collection_failures: failures occuring during test setup :param test_results: list of all test executuion results :return: one of 'ERROR', 'FAIL', or 'PASS' """ if collection_failures: return "ERROR" elif any(r.is_failed for r in test_results): return "FAIL" else: return "PASS"
c63597486927597e70dbd4c67216f37b9f1d18ba
586,759
def summarize_broken_packages(broken): """ Create human-readable summary regarding missing packages. :param broken: tuples with information about the broken packages. :returns: the human-readable summary. """ # Group and sort by os, version, arch, key grouped = {} for os_name, os_ver, os_arch, key, package, _ in broken: platform = '%s %s on %s' % (os_name, os_ver, os_arch) if platform not in grouped: grouped[platform] = set() grouped[platform].add('- Package %s for rosdep key %s' % (package, key)) return '\n\n'.join( '* The following %d packages were not found for %s:\n%s' % ( len(pkg_msgs), platform, '\n'.join(sorted(pkg_msgs))) for platform, pkg_msgs in sorted(grouped.items()))
61c190349ba934871739822435fd36c209c2eb7a
94,531
from typing import List def _find_sibiling_ipynb_cells( ipynb_node_id: str, item_node_ids: "List[str]" ) -> "List[str]": """ Returns all sibiling IPyNb cells given an IPyNb cell nodeid. """ fpath = ipynb_node_id.split("::")[0] return [item for item in item_node_ids if fpath in item]
7ac86b6853bd217cb1e17ce16dffc261bca9a3d0
442,915