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 ... | 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:
... | 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 _so... | 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, mi... | 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 te... | 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 = l... | a7963abc51f96e23d2b188edd6c0d8e8146dd842 | 460,157 |
def parse_fromaddr(fromaddr):
"""Generate an RFC 822 from-address string.
Simple usage::
>>> parse_fromaddr('from@example.com')
'from@example.com'
>>> parse_fromaddr(('from', 'from@example.com'))
'from <from@example.com>'
:param fromaddr: string or tuple
"""
if isi... | 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]:
... | 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.str... | 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]) **... | 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
Di... | 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... | 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... | 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 pr... | 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.c... | 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
... | 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))... | 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... | 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 l... | 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:
va... | 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
... | 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[
(d... | 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)
... | 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 t... | 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... | 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
... | 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
... | 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.propert... | 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... | 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] + [valu... | 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 languag... | 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 tu... | 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(... | 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(","):
p... | 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
crea... | 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 ... | 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 = 'fl... | 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):
sig... | 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... | 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 el... | 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... | 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 mat... | 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": ""}
lin... | 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.
... | 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.appe... | 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 ... | 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:
>>> s... | 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)
... | 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, p... | 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.... | 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 ... | 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(li... | 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 ... | 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, ... | 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]
retu... | 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 x... | 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 = ... | 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 DN... | 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.... | 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 failu... | 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,... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.