content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def split_train_val_list(full_list, val_ratio):
"""Split list by val_ratio.
Args:
full_list (list): list to be split
val_ratio (float): split ratio for val set
return:
list(list, list): train_list and val_list
"""
n_total = len(full_list)
offset = int(n_total * val_rati... | ee545db7e401ff54e221c91dcec7abe23e3fadc3 | 567,832 |
def check_mode_python(mode: str) -> bool:
"""
Checks whether a script should be read respecting Python syntax or traditional shell syntax based on syntax variable in script.
Returns true if Python specified, false if 'shell', 'bash', etc. specified, and raises an exception for other cases.
"""
if m... | c3db09a241024f41ce0e23704520df5e6bb84fd5 | 567,833 |
def is_status_update_request(request_data):
"""
Returns True if `request_data` contains status update else False.
"""
return any('status' in update for update in request_data) | 03f582f275b9ea543d17bfb5e85b97a357e6a6b7 | 567,834 |
def copy_or_get_app(api, app_name, project):
"""Copy a public application if it doesnt exist in your project
or get the existing public app
Args:
api: Seven bridges connection
app_name: Name of public app
project: CAVATICA project
Returns:
CAVATICA App
"""
# Query all public ... | b6b78c6e7331108409183817b3f54c65c882ce28 | 567,836 |
def get_all_rules(data):
"""
Create list of rules from data in format:
(color1, num, color2)
'<color1> bags contain <num> <color2> bags'
"""
rules = []
for record in data:
count = record.count(",")
record = record.split()
bag_from = record[0] + " " + record[1]
... | 710a6428f31668ca4f1469c7043e1379f384c81f | 567,841 |
def apply_to_all_elements(x, fn):
"""
Recursively apply function to all elements of nested lists/tuples
"""
if type(x) not in (list, tuple):
return fn(x)
return [apply_to_all_elements(y, fn) for y in x] | 3368a0bd3f5c4e05a13d581bff6ac1ddc0e9292d | 567,842 |
def _find_element(driver, by):
"""Looks up an element using a Locator"""
return driver.find_element(*by) | c03f0d2a69fe24be1721dd484d4601cb0f6231d9 | 567,844 |
def is_sublist(list_, sublist):
"""A sublist is part of a given list"""
return any(list_[i:i+len(sublist)] == sublist
for i in range(len(list_)-len(sublist)+1)) | 206b90f6b74c02918e008c889218ce3ad4d569f1 | 567,847 |
def expandElementalNuclideMassFracs(element, massFrac):
"""Return a dictionary of nuclide names to natural mass fractions."""
nucBases = element.getNaturalIsotopics()
elementalWeightGperMole = sum(nb.weight * nb.abundance for nb in nucBases)
if not any(nucBases):
raise ValueError("Cannot expand ... | 954038dbb47e68b2aaf92397e92cca6fb44bb837 | 567,848 |
def split_role(role):
"""
Return a tuple of cluster, type, and id
If no cluster is included in the role, the default cluster, 'ceph', is used
"""
cluster = 'ceph'
if role.count('.') > 1:
cluster, role = role.split('.', 1)
type_, id_ = role.split('.', 1)
return cluster, type_, id_ | 23524c244ecb7929bf05459dcadc956c9545102c | 567,849 |
import re
def handle_white_spaces(string, preserve):
"""Handle white spaces in text nodes."""
# http://www.w3.org/TR/SVG/text.html#WhiteSpace
if not string:
return ""
if preserve:
string = re.sub("[\n\r\t]", " ", string)
else:
string = re.sub("[\n\r]", "", string)
s... | d3786215490df6ffe87efd7601f4927dbe317f9c | 567,851 |
def relu_grad(z):
"""
Relu derivative.
g'(z) = 0 if g(z) <= 0
g'(z) = 1 if g(z) > 0
"""
return 1*(z > 0) | e117af7057be11f98c5c3307efb86085a2dbf0ec | 567,853 |
def to_list(iterator):
"""
Convert an object (e.g. a generator, or some other iterator) to a list.
:param iterator: The iterator to convert.
:return: The object converted into a list.
"""
return list(iterator) | f874c813baf8c087d9feabe8927c9bbd9070ca01 | 567,858 |
def clip(value, minimum, maximum):
"""
Function that clips a value between a minimum and a maximum.
:param value: value to clip
:param minimum: minimum value
:param maximum: maximum value
:return: clipped value
"""
if value < minimum:
return minimum
elif value > maximum:
... | 17956dea94a70c1f60c21ad65db68a58af8fb75d | 567,860 |
import time
def pelicandate(datetext):
"""return a Pelican format date according to the date text
datetext: Sunday, March 30, 2008 6:32:55 PM
pelicandate: 2008-03-30 06:32"""
datestruct = time.strptime(datetext, '%A, %B %d, %Y %I:%M:%S %p')
return time.strftime("%Y-%m-%d %H:%M", datestruct) | 92857571f8fb2daf3f9668b82ce74ddacef97d74 | 567,862 |
def filter_generate_files(
s3_prefix,
target_prefix,
files,
keywords=["T1w"],
):
"""Filter files based on keywords, generate target path
Parameters
----------
s3_prefix, target_prefix: str, str
Path to BIDS dataset on S3 and your dowload desination
files: list of str
... | 5300080653a48ae073a115ba943aa7209656ddbb | 567,863 |
from pathlib import Path
def test_directory(request):
"""Gets root directory of tests"""
return Path(request.config.rootdir) / "tests" | bd812fbcbc84eee350819b55ad4c590337bddeb2 | 567,871 |
def number_of_columns(df):
"""
Cuenta el número de columnas de un dataframe
:param df: dataframe
:return: int, númmero de columnas
"""
# Contamos los elementos en la lista
# con las columnas
return len(df.columns) | 20224bb50ccbea6254aa536935e4754e1e2c3405 | 567,881 |
def generateState(start, diff, stateSize, stateName):
"""Generates a dict that contains a stateName and a list of values."""
values = []
increment = float(1) / stateSize
for iteration in range(int(stateSize)):
# Get a value between start + diff
sample = start + diff * increment * iterati... | 901b11aee81cac224e5cb23e27933f735e0aead3 | 567,882 |
def _extract_source_ips(finding, key_in_additional_info=None):
"""
Extracts source IP addresses from a GuardDuty finding.
https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html
:param finding: a GuardDuty finding
:param key_in_additional_info: key name in 'additionalInfo' field fo... | 9733f7a7c0f499c2e6526db55cd024428cd2019d | 567,884 |
import hashlib
def md5(string: str):
"""Return an md5 digest for an input string."""
return hashlib.md5(string.encode("utf-8")).hexdigest() | 948d0f017a85d4bb6d3f8c9ad1e0f801e28b8f1b | 567,893 |
import random
def _limitsample(sample, desiredlen, randomize=True):
"""return a random subset of sample of at most desiredlen item.
If randomize is False, though, a deterministic subset is returned.
This is meant for integration tests.
"""
if len(sample) <= desiredlen:
return sample
i... | 6e9e97ef074e765b1d35166ea1f9e8961551df53 | 567,894 |
def toString( x ):
"""
Return a string representing x. If x is a float convert it to scientific notation.
Arguments:
x: The value to convert to a string.
"""
if isinstance( x, float ):
return "{:.2e}".format( x )
else:
return str( x ) | a619aa9867ab807721812e19ae88df67189b27aa | 567,895 |
import re
def _get_comment_field(comments, var_string):
"""
return value of a field from a list of comment lines
The comment line with a field has the following format:
# var_string: var_value
For example:
# Creation Date: 2012-02-01
So we need to create a pattern, find a match and th... | 6ba88b24491af2182abf617077d363f89ad0b892 | 567,896 |
import inspect
def get_settings_as_dict(settings_module):
"""
Returns given module as dict object with
keys taken from settings_module. Only
members with uppered names are returned.
"""
return dict((key, val) for key, val in inspect.getmembers(settings_module)\
if key == key.upper()) | a0f2bff3a6e3375dddd39c037628bbe33bbdfee7 | 567,897 |
import torch
def eul_to_quat(roll, pitch, yaw):
"""
Convert euler angles to quaternion.
By convention, put scalar first.
"""
sr = torch.sin(roll) # 0
cr = torch.cos(roll) # 1
sp = torch.sin(pitch) # 0
cp = torch.cos(pitch) # 1
sy = torch.sin(yaw)
cy = torch.cos(yaw)
qw = c... | 4a194d79efd6b03b112c59949dbd31c9d2fcb8a7 | 567,899 |
from pathlib import Path
from textwrap import dedent
import json
def template_directory(tmp_path: Path) -> Path:
"""Fixture for a template directory."""
def create(path: Path, text: str) -> None:
"""Create a file with the given path and contents."""
text = dedent(text).removeprefix("\n")
... | 77c54665ef8446bad6f8d5fb7d669996b83cac58 | 567,903 |
def read_results_from_file() -> list[tuple[int]]:
"""Read the results from time_results.txt."""
with open("time_results.txt", "r", encoding="utf-8", errors="ignore") as f:
results = []
for result in f:
result = tuple(float(time) for time in result.split(", "))
results.app... | b4b066eaed018641b88367b6130374cf43f163aa | 567,904 |
import re
def cleanYear(media):
"""
Takes a Show/Movie object and returns the title of it with the year
properly appended. Prevents media with the year already in the title
from having duplicate years. (e.g., avoids situations like
"The Flash (2014) (2014)").
Arguments:
media -- a Show/Mo... | 75bb401f8e09f3ae37473131fc761ea7d56b8f9d | 567,906 |
from typing import Sequence
def horner(poly: Sequence[float], x: float) -> float:
"""Evaluate a polynomial at specified point using Horner's method.
In terms of computational complexity, Horner's method is an efficient method
of evaluating a polynomial. It avoids the use of expensive exponentiation,
... | a6723ab40064d4e83e915d0a034b23960ace017b | 567,907 |
import math
def rad2deg(x):
"""
Convert radians to degrees
"""
return x / math.pi * 180.0 | 593975f97db52221cfc65dc0bd587114c12751fa | 567,909 |
def closest_multi(ref: float, base: float, force_next: bool = False) -> float:
"""
Computes the closest multiple of base based on a given reference.
:param float ref: Reference.
:param float base: Multiple base.
:param bool force_next: If reference is equal to multiple, forces next multi... | 8725556f75e06187e5b2f3a4babec810d8547a38 | 567,910 |
def permalink_to_full_link(link: str) -> str:
"""Turns permalinks returned by Praw 4.0+ into full links"""
return "https://www.reddit.com" + link | 13a2eb003d4268eaffd4e1d0a51064a7e1b5e009 | 567,912 |
def SuppressBlanks(text):
""" Replace succesive blanks with a blank
:param str text: string
:return: string
:rtype: str
"""
outtext=''
for s in text.split(): outtext=outtext+s+' '
return outtext.strip() | 42bedaf7f7601cffdad2410a119bef1506226c08 | 567,914 |
def padding_space(h, pgsz: int, space_data: bytes) -> list:
"""Padding each data block with `space_data` to let block size fit pgsz * N.
Args:
h (list): response from `asaloader.ihex.parse`.
pgsz (int): page size, e.g. 256, 512.
space_data (bytes): the byte data used to padding.
... | ced5d41f75711a508cb59821b1448450da9873b4 | 567,916 |
def precision(xs, ys):
"""Precision of list `xs` to list `ys`."""
return len([x for x in xs if x in ys]) / float(len(xs)) if xs else 0. | 601866550480572c79e397b8a2e9a6fcbcc83e10 | 567,918 |
def get_frame(env_observation, info):
"""Searches for a rendered frame in 'info', fallbacks to the env obs."""
info_frame = info.get('frame')
if info_frame is not None:
return info_frame
return env_observation | e6fe1342c3943459c4d18a35b844165c569db031 | 567,919 |
def BuildDetailedInfoResponse( text ):
""" Retuns the response object for displaying detailed information about types
and usage, suach as within a preview window"""
return {
'detailed_info': text
} | fb9fd9a85870bafe87feecf4e0e25b54c4b86eba | 567,921 |
def axis_or_axes(data, axis=None, axes=None, *args, **kwargs):
"""Return either axes, axis or the indices of the last two dimensions.
:param axis: indices to use in the fft
:type axis: list
:param axes: alternative naming
:type axes: list
:return: axis is returned if defined, otherwise axes i... | e02337a3d069ec2a7cd824697b44bb6ae491b1f8 | 567,924 |
def PostUploadHook(cl, change, output_api):
"""git cl upload will call this hook after the issue is created/modified.
This hook adds an extra try bot list to the CL description in order to run
the Mac GPU and Windows 10 bots in addition to the usual CQ try bots.
"""
return output_api.EnsureCQIncludeTrybotsAr... | 53f83df2c8860fe318adc238ab331b77b528635b | 567,928 |
import itertools
def is_value_in_list_sum(data, value):
"""
Returns True if the value is a sum of two items in the list.
The two numbers being summed must be different
"""
possible_sums = [sum(x) for x in itertools.combinations(data, 2) if x[0] != x[1]]
return value in possible_sums | 3560148fe43058b4db17ce55c4d4fd8521c5aa4f | 567,929 |
def get_departure_info(order, ticket):
"""Get numbers from ticket corresponding to departure fields from
the fields order.
"""
return [
number
for number, field_name in zip(ticket, order)
if 'departure' in field_name
] | 233d513235448b3c0f1c3eb79b4e7c7bcd45785f | 567,933 |
def BB_check(bb_1, bb_2):
"""
bb_1 and bb_2 are two bounding boxes.
Each is a 4 element tuple of :
(max_x,min_x,max_y,min_y)
BB_check(bb_1, bb_2)
returns 1 if the two boxes intersect
returns 0 if the two boxes don't intersect
"""
if ( (bb_1[0] > bb_2[1]) and (bb_1[1] < bb_2[0]) and
(bb_1[2] > bb_2... | 417c80e1a865e2ba382d337c811953d8e4190642 | 567,935 |
def Initialise(Pathway_row, Pathway_column, Gap, Rank):
"""Initialise the scoring matrix for Modified Needleman-Wunsch Algorithm."""
# Create empty matrix
matrix = [[0 for c in range(len(Pathway_column))] for r in range(len(Pathway_row))]
# Initialise frist row and column with r*gap value
for r, co... | 0a711aa2ea976f4547921fec22f661a88230a4bf | 567,936 |
def encode_one_hot(target, num_classes):
"""Encode integer labels into one-hot vectors
Args:
target (torch.Tensor): (N,)
num_classes (int): the number of classes
Returns:
torch.FloatTensor: (N, C)
"""
one_hot = target.new_zeros(target.size(0), num_classes)
one_hot = on... | 75236e32cd968c9af634a813ff98c86699a193b2 | 567,937 |
def dollar_volume(tick_prices, tick_volumes):
"""
Computes total dollar volume
:param tick_prices: a series of tick prices
:param tick_volumes: a series of tick_volumes
:return: total dollar volume
"""
return (tick_prices * tick_volumes).sum() | b7f5b888fca09643ba0a1a3dbef228fc7b40e943 | 567,938 |
def ABMagnitudeToJansky(ABmagnitude):
"""
Converts AB magnitudes to Janskys.
:note: Can be used with SQLite3 database.
:param ABmagnitude: AB-magnitude of the object
:type ABmagnitude: float or ndarray
:return: either a float or NumPy array
"""
return 10 ** ((23.9 - ABmagnitude) / 2.5... | 451faa6b9ba40fe10b3ea05970fbafbf30f16032 | 567,939 |
def length(x):
"""
Returns the length of x
:param x: the time series to calculate the feature of
:type x: pandas.Series
:return: the value of this feature
:return type: int
"""
return len(x) | 461d11ba6ca91b7ab6e7029ea7fe09fe4f78da1c | 567,946 |
from typing import OrderedDict
def init_model_attr(model):
"""
Initialize pscale attribute of a model object
"""
if not hasattr(model, 'pscale'):
model.pscale = OrderedDict()
for k in model.param_names:
model.pscale[k] = 1.
else:
for k in model.param_names:
... | 68c6de4e6c85afaf1774c285d751c7b78784140f | 567,947 |
def toggle_numbers(numbers: list, totlength: int) -> list:
"""
Given a list of integers called 'numbers', return the toggle of them from zero to totlength - 1.
Args:
numbers (list): Integers in the original list, in sorted order.
totlength (int): Number of elements in complete list. Ex: [0,... | 1dba26b14d6ec53ba4d2d057564f227dcecf5fee | 567,951 |
def append_if(array, item):
"""Append an ``item`` to an ``array`` if its not already in it.
:param array: ``list`` List object to append to
:param item: ``object`` Object to append to the list
:returns array: returns the amended list.
"""
if item not in array:
array.append(item)
... | 353904d78a4d00a95bc2b1377dfa0c16a9396ca4 | 567,952 |
def generate_configs(**configs):
"""
Given configs from users, we want to generate different combinations of
those configs
For example, given M = ((1, 2), N = (4, 5)) and sample_func being cross_product,
we will generate (({'M': 1}, {'N' : 4}),
({'M': 1}, {'N' : 5}),
... | 018259def2e58ea52cf8e443898add8b394a5057 | 567,954 |
def child_query_url(finder, obj):
"""Return Ajax query URL for children of given object."""
return finder.child_query_url(obj) | 7fc2b1993a7ef5fb8f70cd81250cd9a1c7547d27 | 567,955 |
def string_to_int(string, keyspace_chars):
""" Turn a string into a positive integer. """
output = 0
for char in string:
output = output * len(keyspace_chars) + keyspace_chars.index(char)
return output | 9f66ea93d6f691b4761fa7fe273c39edb63228a2 | 567,956 |
import uuid
def setup(pod_obj, bucket_factory):
"""
Setup function
Args:
pod_obj (Pod): A pod running the AWS CLI tools
bucket_factory: Calling this fixture creates a new bucket(s)
Returns:
Tuple: Returns tuple containing the params used in this test case
"""
bucket... | 04a83a76c5dcea8312ab5a67ae393d8068b60bd5 | 567,960 |
def get_identifiers(args_list, valid_keys):
"""Find string identifiers for each experiment. Used by pop-ups.
Args:
args_list (list of dictionary): dictionary consists of keys and values
that uniquely identify the plot.
Returns:
identifiers (list of strings)
"""
# ignor... | d84a4225985488f2d9688edcdf5f5babc721b063 | 567,970 |
def _multihead_attention_output_shape( # pylint: disable=invalid-name
input_shapes, feature_depth=None, **unused_kwargs):
"""Helper: calculate multihead attention output shape."""
input_shape = input_shapes[0] # Inputs are (q, k, v, mask).
return input_shape[:-1] + (feature_depth,) | 10c0c40d6c5590aba391b0f58e8727f12c5072d1 | 567,971 |
def robust_l1(x):
"""Robust L1 metric."""
return (x**2 + 0.001**2)**0.5 | bdca0ddca5cb73812a66ebb1f89f88b29be19a4b | 567,974 |
def plaquette_to_sites(p):
"""Turn a plaquette ``((i0, j0), (di, dj))`` into the sites it contains.
Examples
--------
>>> plaquette_to_sites([(3, 4), (2, 2)])
((3, 4), (3, 5), (4, 4), (4, 5))
"""
(i0, j0), (di, dj) = p
return tuple((i, j)
for i in range(i0, i0 ... | 2eb72ded6d223ebeec623af2f5ce1c9ed7dea0cf | 567,976 |
def x2trace(distance, interval):
"""Return the trace number closest to a given distance. The input distance is effectively dimesionless given that the interval is proportional to it. NB: Not sure if the returned trace is a python index or gpr trace but that needs to be specified here.
Attributes:
distan... | 7a9af5ff21293566993d2921ac0ff4df3ac780ac | 567,977 |
def _set_default_load_type(technology_id: int, type_id: int) -> int:
"""Set the default max rated temperature for mechanical relays.
:param technology_id: the current technology ID (represents the load type).
:param type_id: the type ID of the relay with missing defaults.
:return: _contact_form_id
... | bbe50fbd4df697f9b40184b97f5cf14cfa8d2d78 | 567,978 |
def removeprefix(value: str, *prefixes: str) -> str:
"""Works almost like str.removeprefix that comes with Python 3.9+"""
for prefix in prefixes:
while value.startswith(prefix):
value = value[len(prefix) :]
return value | bef27d981e0e0a21ee3fcbf77ad37488eed5c62a | 567,982 |
def format_header(string):
"""Returns the string as a header."""
return "\n# {}\n\n".format(string) | fe68e18bdfc96866366cd8428f32e8051faee037 | 567,988 |
def child_node_from_list(child_node_name):
"""Returns a value suitable for generating an XML child node on export.
The return value is a list of tuples that the simplexml connector will
use to build a child node.
See also list_from_child_node
Args:
child_node_name: The name to use for each child node.
... | 54a87edeae608e2d1db386146400a1d915d67917 | 567,992 |
def oddTuples(aTup):
"""
aTup: a tuple
returns: tuple, every other element of aTup.
"""
return (aTup[::2]) | c9cc8f93d37ddfb3ab1011ebab0a073c9fccb249 | 567,993 |
from typing import List
import random
def create_tags_sample(length=10, tags=["LOC", "PERSON", "DATE"]) -> List[str]:
"""Create completely random biluo tags. The output tags may be syntactically incorrect."""
res = []
for _ in range(length):
pref = random.choice("BILUO")
if pref == "O":
... | 710ba39f983b2391e80bb9a1995636dd87698921 | 567,996 |
from typing import Mapping
def update(dst, src):
"""
Recursively update values in dst from src.
Unlike the builtin dict.update() function, this method will descend into
nested dicts, updating all nested values.
Arguments:
dst (dict): Destination dict.
src (dict): Source dict.
Returns:
... | 21219f69a8f44a17b66f1fee99454cfed9202c95 | 567,997 |
def single_cond_prob_to_str(grid_idx, val, num_indices = 6):
"""Generate the string representing the probability:
Pr(o_i = val)
ex:
For Pr(o_2 = 1), we'd have the string '21'
NB we're 1-indexing here
"""
assert grid_idx >= 1 and grid_idx <= num_indices
return str(grid_idx) + st... | 462b35da49ae54b1fef9853243e902871abc76f3 | 567,998 |
def check_is_iterable(py_obj):
""" Check whether a python object is iterable.
Note: this treats unicode and string as NON ITERABLE
Args:
py_obj: python object to test
Returns:
iter_ok (bool): True if item is iterable, False is item is not
"""
if type(py_obj) in (str):
... | 1c0b46c19cb63e3adb6d5adb7afa611a96c83094 | 568,001 |
def quote_string(s: str, force:bool=False) -> str:
"""Sometimes wraps strings in double quotes, depending on the content and force parameter.
Description:
This function provides conditional wrapping of strings inside double quotes.
If the input string contains a space, OR force is set to T... | 6624881986b7ed7b08e2f4e5b5cfb1b171907c90 | 568,004 |
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
list = []
for i in range(0, len(paragraphs)):
s = i
... | af619a02a371b406932cdf3908ac5ecf32b85173 | 568,007 |
import hashlib
def sha3_512(m: bytes) -> bytes:
"""Return the SHA3_512 digest of the provided message."""
h = hashlib.sha3_512()
h.update(m)
return h.digest() | 97cd321b24ff268279bc3d72b1e5ec3236e41d49 | 568,008 |
def calculate_scale(imagewidth, ymin, xmax):
"""Calculates the scale of the map.
scale = map distance / ground distance"""
map_distance = abs(xmax-ymin)
ground_distance = (0.000264583 * imagewidth)
map_scale = int(map_distance/ground_distance)
modified_scale = '{:20,}'.format(map_scale)
retu... | 3a9de06b6edf1c77acea505c2b48e202bfbe71f5 | 568,013 |
import textwrap
def indent(text: str, space_count: int) -> str:
"""Return `text` indented by `space_count` spaces."""
return textwrap.indent(text, " " * space_count) | 6cf3a32749388a5d8ee280e0f6d860211c9cfc9b | 568,014 |
def diff(a, b):
"""Returns a new list of the differences between a and b"""
return set(b).difference(set(a)) | b7e0b379bf9b05f1d246ae288f4a65f1834241f7 | 568,018 |
def _get_last_page_offset(url_html):
"""Obtain last page offset.
Required to stop iterating over pages.
Parameters
----------
url_html : BeautifulSoup object
Returns
-------
int
"""
page_numbers = url_html.findAll("div", attrs={"class": "pageNumbers"})[0]
last_page_offset... | 3f3d01a095addb2c8ac577e33cc28129047df227 | 568,019 |
def match_files_names(files, names_lst):
"""
Given two lists (files and names) check if all the names appear in the files.
This function serve to check for the completeness of the directory.
"""
stems = [f.stem for f in files]
for name in names_lst:
if name not in stems:
ret... | 43947248e525edb51ec15017135279a386e7f48d | 568,021 |
import difflib
def _file_diff(current: str, should_be: str):
"""diff 2 files"""
with open(current, "r") as current_f:
with open(should_be, "r") as should_f:
diff = difflib.unified_diff(
current_f.read().splitlines(),
should_f.read().splitlines(),
... | 592ce0d7bbf9a6b3713488ae0abc341d770f6e07 | 568,022 |
def inner_product_d(x_d, y_d):
"""Inner product for sparse vectors."""
inner_prod = 0.0
for k, v in x_d.items():
if k in y_d:
inner_prod += v * y_d[k]
return inner_prod | cefdce5fb540860f870dc470b7c9a834df7cdefd | 568,023 |
def get_dataobj(img):
""" Return data object for nibabel image
Parameters
----------
img : ``SpatialImage`` instance
Instance of nibabel ``SpatialImage`` class
Returns
-------
dataobj : object
``ArrayProxy`` or ndarray object containing data for `img`
"""
try:
... | 067f0f715e7f1027a64346723dfcf55afdb44f4b | 568,024 |
import json
def RenderValue(value):
"""Convert a Python value to a string with its JavaScript representation."""
return json.dumps(value, sort_keys=True) | 9e8f33f5d38a5c5e4c89e69fdbf270da39e538e2 | 568,027 |
import warnings
def get_padding_up(Lin:int, Lout:int, kernel_size:int, stride=1, output_padding:int=0, dilation:int=1) -> int:
"""return padding length to math target Lout. (for up sampling)"""
assert Lin <= Lout
pad = ((Lin - 1)*stride + dilation*(kernel_size - 1) + output_padding+ 1 - Lout)/2
if pad... | 92cb3bc991bca42edbc1b3f255d15dd8d8728ec5 | 568,030 |
def adjust_lag2_corrcoef1(gamma_1, gamma_2):
"""A simple adjustment of lag-2 temporal autocorrelation coefficient to
ensure that the resulting AR(2) process is stationary when the parameters
are estimated from the Yule-Walker equations.
Parameters
----------
gamma_1 : float
Lag-1 temporal... | 081d387df865d52cbb0b811577ad7aada3b70e58 | 568,031 |
def deep_get(dikt, path):
"""Get a value located in `path` from a nested dictionary.
Use a string separated by periods as the path to access
values in a nested dictionary:
deep_get(data, "data.files.0") == data["data"]["files"][0]
Taken from jupyter/repo2docker
"""
value = dikt
for co... | ca2529039813f4172f7354ec2b36d066181a9cee | 568,034 |
def threshold_sigmoid(t):
"""prob > 0.5 --> 1 else 0"""
threashold = t.clone()
threashold.data.fill_(0.5)
return (t > threashold).float() | b88dd970950f83393b6ae4b6d7af07c1cd8efe94 | 568,035 |
import torch
import math
def generate_spirals(n_samples: int, length: int = 100):
"""
:param n_samples: number of samples to generate
:param length: length of the time sampling of the spirals
:return: X, y data samples. X is a torch.Tensor of shape (n_samples, length, 2), y is of shape (n_samples) wi... | b56c9344983da195368c5a5be41de0ef70ae0f5a | 568,039 |
def get_opposite_arr_dep(arr_dep):
"""
If arrDep is A it returns D and viceversa
"""
if arr_dep == "A":
return "D"
return "A" | 75764be1169dafb2c8210701b05489be8e69398f | 568,042 |
def getippart(ipentity):
"""
Get the CIDR from network entity and return the first 3 octates
"""
cidr = ""
for prop in ipentity.properties.split("|"):
if prop.startswith("CIDR"):
cidr=prop.split("=")[1]
iphead = cidr[:-4]
return iphead | 09a60381a3fcb170b9381008930ab20630adcaad | 568,046 |
def find_gaussian_hyperparams(left, right):
"""
Finds mean and standard deviation of Gaussian prior such that the 2
sigma intervals are the values `left` and `right`. As a result, about
95% of the prbability mass will be within the defined interval.
"""
# Compute width of interval
width = ab... | 35fbb485acdf62309f8dedc953168249ae676444 | 568,050 |
def datazoom(
is_datazoom_show=False,
datazoom_type="slider",
datazoom_range=None,
datazoom_orient="horizontal",
datazoom_xaxis_index=None,
datazoom_yaxis_index=None,
**kwargs
):
"""
dataZoom 组件 用于区域缩放,从而能自由关注细节的数据信息,或者概览数据整
体,或者去除离群点的影响。
:param is_datazoom_show:
是否使... | 4304a6d87264e1ef708fe62113625be5419e97ac | 568,051 |
import hashlib
def bin_dbl_sha256(s):
"""
Perform a double SHA256 operation on the input.
Args:
s(str): message to hash.
Returns:
bytes: hash.
"""
return hashlib.sha256(hashlib.sha256(s).digest()).digest() | f4062fadc7450764c6f537eebdefba49bc952990 | 568,052 |
import re
def get_codecaves(section,binary,size):
"""
Looks for caves into a binary file in a specifc PE section
Return the caves array [section, offsets]
"""
codecaves = []
raw_offset = section.PointerToRawData
length = section.SizeOfRawData
data = binary[raw_offset:raw_offset + lengt... | 81eae4bbe12073ed6f6676bdac5245765beecf10 | 568,056 |
def _get_percentage_difference(measured, base):
"""Return the percentage delta between the arguments."""
if measured == base:
return 0
try:
return (abs(measured - base) / base) * 100.0
except ZeroDivisionError:
# It means base and only base is 0.
return 100.0 | b7596467637de004a5f592b4992b23a4d664566f | 568,058 |
def extract_molecule(string):
"""
Extract the molecule(s) from an input string in the format moleculeID,startres,endres;moleculeID,startres,endres
"""
unique_molecule_id = []
for molecule_info in string.split(';'):
molecule_id = molecule_info.split(',')[0]
if molecule_id not in uniq... | 3b27b8b1a9ddc3c44ef9a3cfcfd61f913f364eb2 | 568,060 |
def note_name(note: int) -> str:
"""Returns name with accidental and octave number for a given note number.
>>> note_name(60)
'C4'
>>> note_name(90)
'Fs6'
"""
notes = ["C", "Cs", "D", "Ds", "E", "F", "Fs", "G", "Gs", "A", "As", "B"]
name = notes[note % len(notes)]
octave = note // 1... | 4920e40b255b729cb48228d85e9a68d913190b0a | 568,064 |
def _interval_to_ms(value: int, unit: str) -> int:
"""
Convert the value and unit into milliseconds, if the value is not within the
valid range (30 min to 24 hours) then the default (4 hours) is used.
"""
one_minute_in_ms = 60 * 1000
one_hour_in_ms = 60 * one_minute_in_ms
min_interval = 30 ... | 40782c58e675e0c61526c729f32ef47ed25230c7 | 568,065 |
def createPair(kmlDoc, mode, state):
"""
Used to create a single Pair environment that has a particular mode and state
"""
pairElement = kmlDoc.createElement('Pair')
key = kmlDoc.createElement('key')
key.appendChild(kmlDoc.createTextNode(str(mode)))
sturl = kmlDoc.createElement('styleUrl')
... | 51ef54596b2248f31d8c61dfd56b2a21fc9b6e51 | 568,070 |
def _image_name_from_key(agent_key: str) -> str:
"""Generate docker image name from an agent key.
Args:
agent_key: agent key in the form agent/organization/name.
Returns:
image_name: image name in the form : agent_organization_name.
"""
return agent_key.replace('/', '_').lower() | 0a7c2d0824a1c809364048def899d523c5853d48 | 568,071 |
def _switch_case_letter(ch):
"""switch the case of the character"""
return ch.swapcase() | c03fe2b1bf44bde6353b8d2b9028d0e755db90ef | 568,073 |
def aln_extends_off_contig(aln):
"""
Does the alignment extend off of a contig or scaffold?
aligned: # unaligned: - whatever: . edge: |
query |---#####....
target |#####....
OR
aligned: # unaligned: - whatever: . edge: |
query ...######---|
... | c64071f8f31dec926081b16a1364608d524c28e7 | 568,087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.