content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_quat_wxyz_to_xyzw(quat):
"""Convert quaternion from wxyz to xyzw representation."""
return quat[..., [1, 2, 3, 0]] | ed02298c4f7ff61297fdcb6f40aa394045b9a812 | 40,233 |
def yaml(path, _pod):
"""Retrieves a yaml file from the pod."""
return _pod.read_yaml(path) | ca610b1b916a83a535e578e3b6f102c36f0ed4af | 40,234 |
def snake_case_to_title(string):
""" A convenience function that converts a snake-cased function name into title case
:param str string: A string encoded using snake case
:return: A converted string
"""
return string.replace('_', ' ').title() | 9229ebbfbe48fd13da17616a9b81dae01cfcb303 | 40,238 |
def 取最大数(数值列表):
"""
传入要对比的列表,如(1,2,3),返回里面最大的数字
:param 数值列表: (1,2,3)
:return: 3
"""
return max(数值列表) | 111eba5c9c37e7656ca410447e1ac5a3f0041ea7 | 40,239 |
def ucc(graph):
"""Identify connected components in undirected graph.
Examples:
>>> ucc(graph)
{1: ['A', 'B', 'C', 'E', 'D', 'F', 'G'], 2: ['H', 'I', 'J'], 3: ['K']}
"""
visited = []
# Group each vertex with a component.
components = {}
# Component marker
num_cc = 0
... | 60688d8c4bc025e4cb12bbfff08c07cc29a611bd | 40,247 |
import datetime
def epoch_to_datetime(value):
"""
Converts epoch(unix) time into python datatime
"""
# return datetime.datetime.fromtimestamp(value)
return datetime.datetime.fromtimestamp(value).strftime('%c') | 5e725f3b6e43828fc08e9fb68ba3ce6db13ae8b6 | 40,248 |
import random
def random_number(bits):
"""Generate a random integer that will cleanly fit in a number of bits."""
max, min = 2**bits - 1, 2**(bits - 1)
return random.randint(min, max) | 89e7f167bc7af35b7193a7c148f863fd1e185a74 | 40,251 |
def check_ALL_DS(DS_ES_X_Map):
"""
ES used with ALL as DS can not be used with any other DS.
This function checks if this is true.
"""
ES_with_ALL = [row[1] for row in DS_ES_X_Map if row[0] == "ALL"]
ES_without_ALL = [ES for ES in ES_with_ALL
for row in DS_ES_X_Map if row[0... | 58b2f2fd4a4a1f20bba74aa6150d91169a4a9695 | 40,252 |
def default_zero(input):
"""
Helper function that returns the input, replacing anything Falsey
(such as Nones or empty strings) with 0.0.
"""
return round(input if input else 0.0, 2) | d5c06c9f0449277e5fc2b8083335fa7e35595305 | 40,256 |
def unquote_colors(context):
"""
URL unqote colors from context.
"""
for k, v in context.items():
if len(v) == 9 and v.startswith("%23"):
context[k] = "#" + v[3:]
return context | 040fa15b3f480db7762128b08d0e053a83697f50 | 40,258 |
def split_name(name):
"""
Split a name into two names. If there is only one name, the last name will be
empty. If there are more than two, the extra names will be appended to the last
name.
Args:
name (str): A name to split into first name, last name
Returns:
tuple: (first, last... | e399cc06f780a2c0139de93c1070a50f4224b38d | 40,260 |
def _GetAllBuildersInConfig(trybot_config):
"""Returns a list of all variable builders referenced in config."""
all_config_builders = set()
for builders in trybot_config.itervalues():
for builder in builders.itervalues():
waterfall_builder = builder.get('waterfall_trybot')
flake_builder = builder.... | 1796a221aebcb9724568e49bde781bc568f867a1 | 40,262 |
def filter_process_by_name(name):
"""Filter process by process name."""
if name in ["cp", "tee", "date", "Null", "recon-all"]:
return True
return False | 2b33d14e7e1bd3e6e09ce8af97a90e01d10dbe59 | 40,263 |
import time
def _CalculatePastDate(days_ago, now=None):
"""Calculates the timestamp N days ago from now."""
if now is None:
now = int(time.time())
ts = now - days_ago * 24 * 60 * 60
return ts | 1a0affad807e1380dbb61a093cbc956dd3e86107 | 40,267 |
def assert_uniqueness_clause(property: str, node: str = 'node') -> str:
"""
Returns the *part* of a statement that ensures a property of a node is unique.
Parameters
----------
property : str
Name of the mean-to-be-unique property
node : str, optional
Name of the node (coming from other statement)
Returns
... | 2433dfe24df0b58264387310b7875ce78ea7b3ac | 40,268 |
def findLinker(seq, linker):
"""
Match the linker in the read sequence.
"""
pos = -1
for i in range(len(seq) - 9):
seed = seq[i:i + 9]
if linker.startswith(seed):
pos = i
break
return pos | 93e767552d289a004eb10385d15e46ad90e785f3 | 40,269 |
def split_lengths_for_ratios(nitems, *ratios):
"""Return the lengths of the splits obtained when splitting nitems
by the given ratios"""
lengths = [int(ratio * nitems) for ratio in ratios]
i = 1
while sum(lengths) != nitems and i < len(ratios):
lengths[-i] += 1
i += 1
assert sum(... | 8d2ccdd028afe74309d955e3a3a6741c87411b0b | 40,271 |
def filter_corpus_category(corpus, category):
"""Returns only corrections with a defined category from the full corpus format.
Args:
corpus (dict): Corpus dictionary, loaded with 'load_enelvo_format_full'.
category (str): Selected category.
Returns:
list A list of tuples with forma... | e0fd35aaad9d0af429e21686fe56fcfdcf651533 | 40,274 |
def to_date_obj(date):
""" Transforms a date into an obj """
obj = {}
obj['year'] = date.year
obj['month'] = date.month
obj['day'] = date.day
obj['hour'] = date.hour
obj['minute'] = date.minute
obj['second'] = date.second
obj['microsecond'] = date.microsecond
obj['tzinfo'] = str(... | 34fcc0234a76c4644dc13ada139d11c0559ba4ea | 40,276 |
def read(name):
"""
Read file in local current working directory and return the contents
:param name: The name of the file
:type name: string
:returns: string -- Contents of file
"""
return open(name).read() | 243f3e0c5818e3e498d3be14a5dea0a59495e417 | 40,278 |
import pickle
def load_df(path):
"""Loads and returns an object from a pickle file in path
Parameters:
path (string): Path where the pickle file resides
Returns:
object: Object in pickle file
"""
infile = open(path, 'rb')
df = pickle.load(infile)
infile.close()
return df | 4399e897ef7ae9d7a2342548f0ad15819ded331e | 40,285 |
def getStratifiedSampleBandPoints(image, region, bandName, **kwargs):
"""
Function to perform stratitfied sampling of an image over a given region, using ee.Image.stratifiedSample(image, region, bandName, **kwargs)
Args:
image (ee.Image): an image to sample
region (ee.Geometry): the geometr... | c5a8ae26f8b4a76dc2d12e48524698f2d582d08e | 40,287 |
def z2lin(array):
"""calculate linear values from a array of dBs"""
return 10**(array/10.) | e0ed221666398c9ca8488fd20f5e3b0711ad6a7c | 40,288 |
def compute_jaccard_similarity(site_a, site_b):
"""
Compute the Jaccard similarity between two given ActiveSite instances.
Input: two ActiveSite instances
Output: the similarity between them (a floating point number)
"""
a = [i.type for i in site_a.residues]
b = [i.type for i in site_b.resi... | 1e3f83e3a98c3e7f658a22f75a5f377efd6529d5 | 40,289 |
def images_path(instance, filename):
"""
Returns path where free parking place images will be stored.
"""
parking_name = instance.owning_parking.name
if not parking_name:
parking_name = '.'
return 'parking_places/{0}/{1}'.format(parking_name.replace(' ', '_'), filename) | 6ea3eb2f8ffbd2af3f729fd7c425a707cccf3c32 | 40,295 |
def stringifyPlayMove(pos, modifiers, name="game"):
"""
A utility method for automating getting code for playing moves.
Helpful for generating code for testing particular cases of moves made.
Can be used with things like the GUI or moves made by the QModels to replicate exact board states
withou... | 2a902ce02627be707664f125346f21d14f333e02 | 40,298 |
from typing import Counter
def get_piece(turn, grid):
"""Counts the current piece on the grid
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: Number of pieces of "turn" on the grid
"""
grid_combined = []
for row in grid:
grid_combined += row
counter =... | 1c7fda238ddba6d2620b5dfdee1b4173f606ede6 | 40,302 |
def get_distance(p1, p2):
"""It finds the minimum distance between two Points
Parameters
----------
p1 : shapely geometric object
The first point
p2 : shapely geometric object
The second point
Returns
-------
list
Returns the minimum distance. The value follows ... | 2bcfdc62b25e286d1a1d46c27f058e8da3e722e9 | 40,305 |
def is_proxy(obj):
""" Return True if `obj` is an array proxy
"""
try:
return obj.is_proxy
except AttributeError:
return False | 871c163b30ccc1b31b435c9baac5c0d6063d271e | 40,308 |
def is_key_all_values_equal(list_of_dict, key, value):
"""
Check if all values of a key are equal to the specified value.
"""
for d in list_of_dict:
if d[key] != value:
return False
return True | c8e303ffd3f9de4f065ba0bd52d67e1a6c1f8708 | 40,309 |
def celsius_to_fahrenheit(celsius_temp):
"""Calculate fahrenheit temperature from celsius
PARAMETERS
----------
celsius_temp : float
A temperature in degrees
RETURNS
-------
temperature : float
"""
# apply formula
return (celsius_temp * (9/5)) + 32 | c6674816a463d022da8863e0f8fea78dd57c1a22 | 40,314 |
from functools import reduce
def merge_dicts(list_of_dicts):
"""
This will merge a list of dicts. Any duplicate keys will end up with the last value seen.
"""
return reduce(lambda a, d: a.update(d) or a, list_of_dicts, {}) | 68c2d67c97f2276c31b4932c34e31034b1fe3213 | 40,317 |
def filename_flag(filename, flag):
"""Add a string to filenames to indicate how they've been processed."""
filename_parts = filename.split('.')
output = ''
count = len(filename_parts)
for part in filename_parts:
if count == 1:
output = output + '-' + flag + '.'
count = co... | f3cd6016244cf050b732e273be8dea4f94693677 | 40,327 |
from typing import Union
from pathlib import Path
def is_valid_file(filepath: Union[str, Path, None]) -> bool:
"""check if the passed filepath points to a real file"""
if filepath is None:
return False
return Path(filepath).exists() | dbe6713938ac335d38d4df6a1f80b6595a65969f | 40,329 |
def shorten_record_name(record_name):
""" Return the first part of the record (which can be None, comet or
comet.connection)
"""
if record_name is None:
return record_name
return record_name.split(".", 1)[0] | b84c86b22153f403909e86aa452d6f2c7eea32ca | 40,330 |
import hashlib
def digest(key: str) -> str:
"""Get the hash digest for the key."""
return hashlib.sha256(key.encode()).hexdigest() | 82c426ce7f396ac6c5bce38ffe83ba802bb7ed83 | 40,333 |
import functools
import warnings
def deprecated(custom_msg=None, new_func_name=None):
"""This is a decorator which can be used to mark functions as deprecated.
It will result in a warning being emitted when the function is used. We use
this decorator instead of any deprecation library because all librarie... | 119774d6e0eb093b0e9039411ca62b824d6fb4e0 | 40,334 |
def coalesce_dates(dates):
"""
Coalesces all date pairs into combined date pairs that makes it easy to find free time gaps.
>>> from date_collapse import coalesce_dates
>>> dates = [(1,4),(2,8),(12,16),(16,21)]
>>> cdates = coalesce_dates(dates)
>>> print(cdates)
[(1, 8), (12, 21)]
>>> ... | 161ef92c6c8946a277e11504cb3dee1082582123 | 40,337 |
def zscore(rate, mean, std):
"""Calculates the Z-score from the mean and std."""
zscore = (rate - mean) / std
return zscore | f122034a930301182a85db67457ba18b76ceeea0 | 40,342 |
def apply_process(sequence, number_of_times, process):
"""Apply process function to sequence number_of_times."""
if isinstance(sequence, int):
sequence = [int(num) for num in str(sequence)]
for _ in range(number_of_times):
sequence = process(sequence)
return sequence | 6db3657360c4dfdb6f38d9241429f66656913135 | 40,345 |
def apply_1overt_decay(params, t):
"""
Implements the mathematical form: a = a0 / (1 + k*t).
Args:
params: parameters for the annealing
t: iteration number (or you can use number of epochs)
Returns:
Updated learning rate
"""
a0 = params['lr0'] # initial learning rate
... | 867e43cfe9733d66e469d9223d8b6e2521ca3362 | 40,347 |
import re
def _SplitFreqRange(freq_range):
"""Splits a `freq_range` str in a list of numerical (fmin, fmax) tuples."""
try:
fmin, fmax = re.split(',|-', freq_range.strip())
return [(float(fmin), float(fmax))]
except AttributeError:
freq_ranges = []
for one_range in freq_range:
fmin, fmax =... | db3c7fc2d2a3576ab07b5acdbae9308408a04575 | 40,349 |
def _create_key_val_str(input_dict):
"""
Returns string of format {'key': val, 'key2': val2}
Function is called recursively for nested dictionaries
:param input_dict: dictionary to transform
:return: (str) reformatted string
"""
def list_to_str(input_list):
"""
Convert all ... | 4313054d7afd46b216fabe226530c75466fee527 | 40,350 |
import re
def filter_tests(filters, test_ids):
"""Filter test_ids by the test_filters.
:param list filters: A list of regex filters to apply to the test_ids. The
output will contain any test_ids which have a re.search() match for any
of the regexes in this list. If this is None all test_ids w... | d8ca31fddb052dde7eaaa21c777e2963e705a598 | 40,353 |
def choose_best(ordered_choices, possible, check, default=None):
"""
Select the best xref from several possible xrefs given the ordered list of
xref database names. This function will iterate over each database name and
select all xrefs that come from the first (most preferred) database. This
uses t... | d10d8d1d527fc2a04603a8f4a6c8e10bb5768bdd | 40,357 |
def format_time_to_HMS( num_seconds ):
"""
Formats 'num_seconds' in H:MM:SS format. If the argument is a string,
then it checks for a colon. If it has a colon, the string is returned
untouched. Otherwise it assumes seconds and converts to an integer before
changing to H:MM:SS format.
"""
i... | 2cd24911976f9d502458043b022a3007e1a1611b | 40,361 |
def afri_16(b8a, b11):
"""
Aerosol Free Vegetation Index 1.6 \
(Karnieli, Kaufman, Remer, and Wald, 2001).
.. math:: AFRI_16 = b8a - 0.66 * (b11 / b8a) + 0.66 * b11
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:ret... | 0d0da371a4fea948032b2dfd1bb89a55ffe19680 | 40,364 |
def reserved(num):
"""
Return reserved bytes - zeros
"""
return bytearray(num) | 3e76b61a3c71179d3b3c8573420b60431f711d31 | 40,372 |
def episode_player_url(episode):
"""Return the player URL for the given episode code"""
player_url = 'http://www.bbc.co.uk/radio/player/{}'
return player_url.format(episode) | 99400b8d0b0a8ed8bcd73e788ecad0e19764cc33 | 40,375 |
import torch
def build_sparse_adjacent_matrix(edges: list, n: int, device=None, dtype=torch.float, undirectional=True):
"""
Return adjacency matrix
:param edges: list of edges, for example (st, ed)
:param n: number of vertices
:param device:
:param dtype:
:param undirectional: make adjacen... | bffcea8b65cd3c94c8b0da33aad3dc4108ce0519 | 40,384 |
def oz_to_g(oz):
"""
Convert ounces to grams
"""
return oz * 28.34952 | 0c547b3b95964e25ace4d00d9c491f367282b89f | 40,393 |
def lam2f(l):
"""
Computes the photon frequency in Hz
Parameters
----------
l : float
Photon wavelength in m
Returns
-------
f : float
Frequency in Hz
"""
f = 299792458/l
return f | 5e6d5745c1a19f4b2a8def3fbdca707e60634019 | 40,395 |
def _mangle(cls, name):
"""
Given a class and a name, apply python name mangling to it
:param cls: Class to mangle with
:param name: Name to mangle
:return: Mangled name
"""
return f"_{cls.__name__}__{name}" | 8b789a03b2f25c71bc661cc1eb394650087128b9 | 40,397 |
from typing import List
from typing import Dict
from typing import Optional
def aggregate_statuses(statuses: List[Dict], dc_voltage=False) -> Optional[Dict]:
"""Aggregates inverter statuses for use for PVOutput.org uploads.
Does some rounding and integer conversion.
Args:
statuses: List of inver... | 8432ec1f14c3e96360934df456e655eb08553f37 | 40,401 |
def traverse(fileName, steepness=(1, 3), start=0):
"""Count collisions of a traversal of a slope.
Parameters:
fileName: of tree-map
start: index of start position
steepness: tuple of horizontal speed (veer) and vertical speed (plummet)."""
width = 0
collisions = 0
position =... | 45b13edb3726b19d0df3e347dd177390568a54c2 | 40,403 |
def match_host(host, domainlist):
"""Return True if host matches an entry in given domain list."""
if not host:
return False
for domain in domainlist:
if domain.startswith('.'):
if host.endswith(domain):
return True
elif host == domain:
return ... | 099ea605da3734433a564815c1eb58d7d58dfd5a | 40,404 |
def isthaichar(ch: str) -> bool:
"""
Check if a character is Thai
เป็นอักษรไทยหรือไม่
:param str ch: input character
:return: True or False
"""
ch_val = ord(ch)
if ch_val >= 3584 and ch_val <= 3711:
return True
return False | e50f78105c3db03dc4ee8bac7735a1d809d53656 | 40,406 |
def get_prop_architecture(typology_df, architecture_DB):
"""
This function obtains every building's architectural properties based on the construction and renovation years.
:param typology_df: DataFrame containing each building's construction and renovation categories for each building
component ba... | 3dc4bfe88783c2a20a12a8951db789b3cdcfd460 | 40,410 |
def sets_to_contingency(a, b, N):
"""
Creates a contingency table from two sets.
params:
a, b: sets to compare
N: total number of possible items
returns:
(f11, f10, f01, f00) tuple of contingency table entries:
f11 = # of items both in a and b
f10 = # of items onl... | 3d782fb47899c6e401034750dddfaffc98f9afc2 | 40,412 |
def uniq_list(inlist):
"""Remove unique elements from a list"""
inset = set(inlist)
return list(inset) | 7699d42cbfad14f2479c8cf133113c62ae236ab4 | 40,413 |
from typing import Dict
from typing import Any
def get_field(data: Dict[str, Dict[str, Any]], key: str) -> Any:
"""
Get a field from nested dictionary, with the field denoted with dot-separated keys.
For example, "a.b.c" -> data['a']['b']['c']
"""
keys = key.split(".")
while keys:
d... | efd342e3badde4e83d3ad344a2188b7fb49b6d04 | 40,414 |
def canonicalize_node_size(node):
"""
Given a node description from the GCE API returns the canonical butter
format.
"""
return {
"type": node.name,
# Memory is returned in "MB"
"memory": int(node.ram * 1000 * 1000),
"cpus": float(node.extra["guestCpus"]),
"st... | 3bc9655234b6f7141eb3b311b3aecd9ba5ec1b99 | 40,420 |
def mix_images(background_img, foreground_img):
"""paste an image on top of another image
Args:
background_img: pillow image in background
foreground_img: pillow image in foreground
Returns:
pillow image
"""
background_img = background_img.convert('RGBA')
foreground_img ... | b86834041c42891b54795b72588f33f1c41e320a | 40,421 |
def _decode_instance(encoded_data, decoded_objects, data_to_decode):
""" Decode a data structure
Args:
encoded_data (:obj:`dict`, :obj:`list`, or scalar): data structure with
encoded objects
decoded_objects (:obj:`dict`): dictionary that maps the unique ids of
encoded ob... | 8e9cb5502aded89cc04268b3098cff9e25fb1a91 | 40,422 |
import bisect
def find_min_revision_index(revisions_list, revision):
"""Find the min index for bisection. Find largest revision <= the given
revision."""
# bisect_left partitions |revisions_list| into 2 such that:
# all(val < revision for val in a[:index])
# all(val >= revision for val in a[index:])
i... | 5a664b74613394a7376a5d2e54333dbf66e83b2c | 40,423 |
def users_to_names(users):
"""Convert a list of Users to a list of user names (str).
"""
return [u.display_name if u is not None else '' for u in users] | 881b6717e11d88971ef307fd6b128f9d83d0868c | 40,424 |
def sensibleBulk(Tw,Ta,S,rhoa=1.2,Ch=1.5e-3,cpa=1004.67):
"""
Sensible heat flux from water using the bulk exchange formulation
Inputs:
Tw - Water temp [C]
Ta - Air temp [C]
S - Wind speed magnitude [m s^-1]
rhoa - air density [kg m^-3]
Ch - Stanton number
... | ec7bf965a58704c7cbd5e099f6771fa40698c4e8 | 40,429 |
def triage_hashes(hash_map):
"""Triage hash map in pair of names to keep and to remove in that order.
Three cases:
0. size zero regardless of hash => remove
1. unique hash => keep
2. hash matching two entries => keep both
3. hash with more than two entries => keep first and last, rest remove
... | 0d2cb2f6cbff3436b780ac45eb1db0c3b7753488 | 40,432 |
import re
def remove_outer_parens(s):
"""
If there are outer parens when we don't need them, get rid of them
Only one set
>>> a = "(1910-1920)"
>>> remove_outer_parens(a)
'1910-1920'
"""
ret_val = s
m = re.match("\s*\((?P<inside_data>.*)\)\s*", s)
if m:
ret_va... | 353aa7adb19dd6e521c038acac3dabac72030325 | 40,434 |
import re
def expNumRe(text):
"""
expand numeric regular expression to list
e.g. 'n[01-03],n1[0-1]': ['n01','n02','n03','n10','n11']
e.g. 'n[09-11].com': ['n09.com','n10.com','n11.com']
"""
explist = []
for regex in text.split(','):
regex = regex.strip()
r = re.match(r'(.*)... | cd42ba0fca726c69a0a3b4335373317467cc9463 | 40,435 |
import shutil
def process_java_resources(target, source, env):
"""Copy resource file into .resources dir. """
shutil.copy2(str(source[0]), str(target[0]))
return None | 3ee5194703956d43187a0c4f802c3ee4c132c18a | 40,440 |
def function_paths(func, tags):
"""Paths to all source files in tags defining a function func."""
return sorted([tag['file'] for tag in tags if tag['symbol'] == func]) | 39931421d8220bd9aa74dc9d5813d29e7e686b5c | 40,441 |
def float_to_string(value: float, replacement: str = "0,00") -> str:
"""
Converts a float to a properly formatted string value
"""
return ("%.2f" % value).replace('.', ',') if value is not None else replacement | 95570ff4fcb78911c9f9a66f5559aea7fa73bbee | 40,442 |
import glob
import re
def _find_cpt_base(cpt_base):
"""
Find checkpoint file base name in current directory
:param str cpt_base: Start of checkpoint file name that ends with a
number of one to three digits followed by '.cpt'
:return: The base name of the checkpoint files (everything but the n... | 765bc409c49ffdc9d0574fab93a4e3a8e5660ab2 | 40,448 |
def _as_bytes(s):
""" Used to ensure string is treated as bytes
The output
Args:
s (str): string to convert to bytes
Returns:
byte-encoded string
Example:
>>> str(_as_bytes('Hello, World').decode()) # Duck typing to check for byte-type object
'Hello, World'
"... | fb5c2d09a1a1d930e05142ec4644554979156170 | 40,452 |
def _maybe_correct_vars(vars):
"""Change vars from string to singleton tuple of string, if necessary."""
if isinstance(vars, str):
return (vars,)
else:
return vars | 1aa46b03988f06a3697b703991c64899e173d0eb | 40,453 |
def decrementing_pattern(size: int) -> bytes:
"""
Return `size` bytes with a pattern of decrementing byte values.
"""
ret = bytearray(size)
for i in range(size - 1, -1, -1):
ret[i] = i & 0xff
return bytes(ret) | b33981468c9e23ae09582e873547147609ebd2e2 | 40,459 |
from typing import List
import json
def analyze_apache_logs(input_file: str, http_response_code_threshold=0.5) -> List:
"""
Analyze parsed Apache access log file to find malicious activity.
:param input_file: Apache access log file (JSON format)
:param http_response_code_threshold: HTTP response code ... | 2255e9ca7c43f93d28f61e6e25687d3b5f61ebd8 | 40,460 |
def build_lookup_dict_snmp_trap(list_content):
"""
Build key/value lookup dict specifically for SNMP Traps which use "server-ip" + "version"
:param list_content: List of dicts to derive lookup structs from
:return: lookup dict
"""
lookup_dict = {}
for item in list_content:
item_serv... | 42b38ff7cd26cd5c785f474d131c67c303fbe1ce | 40,463 |
import math
def format_hash(hash_str: str, hash_len: int, hash_seg_len: int, hash_sep: str) -> str:
"""
Format a hash string: keep only hash_len chars from it, and break it up into
segments of len hash_seg_len, using the hash_sep as separator. Ex:
>>> format_hash('abcdef1232567890', 8, 2, '-')
ab-... | 2e7866fcc871bab1c1758403bc198a10c54c1334 | 40,468 |
import importlib
def package_is_installed(package_name):
"""Return true iff package can be successfully imported."""
try:
importlib.import_module(package_name)
return True
except Exception:
return False | eb0c279bd85aae209331d4e6677fb19c31ab037e | 40,470 |
from typing import List
import difflib
def get_list_difference(list1: List[str], list2: List[str]) -> List[str]:
"""
Return list of elements that help turn list1 into list2.
This should be a "minimal" list of differences based on changing one list into the other.
>>> get_list_difference(["a", "b"], ... | e09e87148f4827a766afe42d8878e2eeeb4f3127 | 40,473 |
def _lane_detail_to_ss(fcid, ldetail):
"""Convert information about a lane into Illumina samplesheet output.
"""
return [fcid, ldetail["lane"], ldetail["name"], ldetail["genome_build"],
ldetail["bc_index"], ldetail["description"], "N", "", "",
ldetail["project_name"]] | cad5549b67a9147685416e9982b219ed29577190 | 40,474 |
def nv_compute_capability(dev):
"""If *dev* is an Nvidia GPU :class:`pyopencl.Device`, return a tuple
*(major, minor)* indicating the device's compute capability.
"""
try:
return (dev.compute_capability_major_nv,
dev.compute_capability_minor_nv)
except:
return None | eb7b6a9386b1f80019e94a0ed697f795d4474d79 | 40,477 |
def make_mmi_cmd(fa):
"""Return a minimap2 cmd string to build mmi index.
"""
return 'minimap2 -x map-pb -d {fa}.mmi {fa}'.format(fa=fa) | 8f03063cb3abcfee66ad364f788f4851c955d0b9 | 40,481 |
def _dict_keys_get(d, keys):
"""Recursively get values from d using `__getitem__`
"""
d = d
for k in keys:
d = d[k]
return d | d83dfce489ecff1b53eb7434e12d615aaf76def8 | 40,482 |
def _remove_tokens(tokenized_docs, counts, min_counts, max_counts):
"""
Words with count < min_counts or count > max_counts
will be removed.
"""
total_tokens_count = sum(
count for token, count in counts.most_common()
)
print('total number of tokens:', total_tokens_count)
unknow... | 2ef618c0ef7c7180c1426ca99f67ee98862813c8 | 40,486 |
def _get_cmd_tree(subcmds):
"""Convert flat list of subcmd objects into hierarchical dictionary
{'command name': {'subcommand name 1': subcmd1, 'subcommand name 2': subcmd2}}"""
cmds = {}
for sub_cmd in subcmds:
cmd_dict = cmds.setdefault(sub_cmd.cmd, {})
cmd_dict[sub_cmd.name] = sub_cmd... | 76f44db545d298b94f9eb2323a5ade280b5f0380 | 40,490 |
def _key_split(matchobj):
"""Expands a {key a+b+c} syntax into <span class="key">a</span> + ...
More explicitly, it takes a regex matching {key ctrl+alt+del} and returns:
<span class="key">ctrl</span> + <span class="key">alt</span> +
<span class="key">del</span>
"""
keys = [k.strip() for k in ... | 519aa2512967aabf266df604280c07d85575a291 | 40,494 |
def is_3d(ds, v):
"""Check if xr.DataArray has 3 dimensions."""
dims = ds[v].dims
if len(dims) == 3:
return True
return False | e095561f47f9daeeb57be327a8af93bb4ac2c2f4 | 40,496 |
def flat_ind_zp_so3(l, m, n, b):
"""
The SO3 spectrum consists of matrices f_hat^l of size (2l+1, 2l+1) for l=0, ..., L_max = b - 1.
These can be stored in a zero-padded array A of shape (b, 2b, 2b) with axes l, m, n with zero padding around
the center of the last two axes. If we flatten this array A w... | f1e9327e33ae31fce28c33d18c2c49b72adafb22 | 40,498 |
import warnings
def process_interaction_params(parameters):
"""Formats and completes interaction parameters.
Interaction parameters are combined into a dictionary passed as a single argumnet.
Parameters
----------
color: tuple
Format (r,g,b).
headheight: float
Height of inte... | 9665eb8ae602e3436609eda4920772c006a82127 | 40,500 |
import torch
def kl_loss_full(mean, var, mean_prior, var_prior):
"""
KL divergence of two multivariate normal distributions.
:param mean: mean of distribution 1
:param var: covariance of distribution 1
:param mean_prior: mean of distribution 2
:param var_prior: covariance of distribution 2
... | b3d7e01a37445b354f47daabb0159745d438b1df | 40,504 |
def xml_tree_equivalence(e1, e2):
"""
Rough XML comparison function based on https://stackoverflow.com/a/24349916/1294458.
This is necessary to provide some sort of structural equivalence of a generated XML
tree; however there is no XML deserialisation implementation yet. A naive text comparison
fai... | bdd135de65e0ecdf9f6d9d22f03b4b5dc06c476c | 40,505 |
def flip_check(intron, flip_dict):
"""
Checks an intron against a dictionary of introns with scores
that did not survive boundary switching.
If present, the score resulting from the boundary switch
will be returned, otherwise None.
"""
name = intron.get_name()
if name in flip_dict:
... | 9b1a392a102c757ccf4938fe0bf3ea6ae4955238 | 40,507 |
def correct_title(title):
"""
Return properly formatted job title.
"""
# Make sure title is a string
title = str(title)
if "grad student" in title.lower():
return "Grad student"
# We will group all professors together
if "professor" in title.lower():
return "Professor"
... | c1ddd3392bc0e1c310d21a2e61086526a086b240 | 40,508 |
def _mk_key(srev_info):
"""Returns the key for a SignedRevInfo object."""
return (srev_info.rev_info().isd_as(), srev_info.rev_info().p.ifID) | 780fb59859b514e0f6d4699cb1e6fef1d6e14042 | 40,511 |
def get_channels(ifo, plottype):
"""Get a list of channels to plot for a given IFO. Plot Type must be
either 'irigb' or 'duotone'."""
if plottype == "irigb":
return ['{}:CAL-PCAL{}_IRIGB_OUT_DQ'.format(ifo, arm)
for arm in ['X', 'Y']]
elif plottype == "duotone":
return ['... | d0c46f2a4f39b4a9eeb79a7ea9b43e994c95ad24 | 40,514 |
def use_tpu(tpu_cores: int, tpu_resource: str, tf_version: str):
"""An operator that configures GCP TPU spec in a container op.
Args:
tpu_cores: Required. The number of cores of TPU resource.
For example, the value can be '8', '32', '128', etc.
Check more details at: https://cloud.google... | ce5b9869512119966d59f1c0fb5ec53eeee53237 | 40,517 |
from typing import Any
from pathlib import Path
import json
def _save_to_json(data: Any, path: Path) -> Path:
"""
json形式で保存する
Parameters
----------
data : Any
保存対象のデータ
path : Path
保存先
Returns
-------
Path
保存されたPath
"""
with open(path, "w") as f:
... | d3fb406bc4767e2e5ce88b83126e68b0906850b6 | 40,520 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.