content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_first_parseable_indicated_ttp(indicator):
"""
Only certain indicated TTPs are parseable by this script. This
function returns the first instance of a parseable TTP.
:param indicator: The indicator to search
:return: An indicated or None
"""
for indicated_ttp in indicator.indicated... | 58ace814c382ecaf8f4aed1f342af6ec3433cec0 | 596,869 |
import math
def lcm(*nums: int) -> int:
"""Returns the least common multiple of the given integers"""
if nums:
nums_lcm = nums[0]
for n in nums[1:]:
nums_lcm = (nums_lcm * n) // math.gcd(nums_lcm, n)
return nums_lcm
return 1 | c840be4e6cf3633797ea880549ad656edb551a02 | 596,873 |
def suitable_xref(required_rna_type):
"""
Create a function, based upon the given rna_type, which will test if the
database has assinged the correct rna_type to the sequence. This is used
when selecting the description so we use the description from a database
that gets the rna_type correct. There ... | d36b2453781666f884de4949a2212714e8d8a7d3 | 596,874 |
def validate_leaderboard_type(type: str) -> str:
"""Validates that the leaderboard type is one of ``"GENERAL"``,
``"CONTESTS"``, ``"BOT_PROGRAMMING"``, ``"OPTIM"`` or ``"CODEGOLF"``.
Parameters
----------
type : :class:`str`
The type to validate.
Returns
-------
:cl... | 0a2b4c59a7605908d3897db755dabd87f23d11f0 | 596,876 |
def case2pod(case):
"""
Convert case into pod-compatible string
"""
s = case.split(" ")
s = [q for q in s if q] # remove empty strings
return "-".join(s) | b3b99dede1864b3e38605f5ba70102687ae0a2d2 | 596,879 |
def str2bool(string_, default='raise'):
"""
Convert a string to a bool.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "true" strings is detected.
Returns
-------
boolean : bool
Examples
--------
>>> str2bool('True')
True
>>> str2bool('1')
True
>>> s... | 0897bd0f48526bc1107dfe13cc80417155a85e05 | 596,883 |
def mutare_valida(tabla_de_joc, configuratie_curenta, nr_nod_curent, nr_alt_nod):
"""
Functie care verifica daca o mutare este valida.
:param tabla_de_joc: instanta a clasei TablaDeJoc
:param configuratie_curenta: configuratia curenta a joclui
:param nr_nod_curent: nr nodului curent in graf ( de un... | f83a79955da51b0217a98170156dbbc84fe132d2 | 596,884 |
def get_reingestion_day_list_list(*args):
"""
This method calculates day-shift lists for Provider API workflows.
The input should be pairs of integers:
`get_reingestion_day_list_list((x_0, y_0), ..., (x_n, y_n))`
The return will be a list of lists of integers. The zeroth inner
list will be a ... | a0bb66f9d545a80ddb371848656e719af807a6ea | 596,885 |
def resolve_import_alias(name, import_names):
"""Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple... | 645133762b28960ca7881435bbfba6982974f2e7 | 596,886 |
def fix_items_ref(vba_code):
"""
Change Scripting.Dictionary.Items() references to
Scripting.Dictionary.Items.
"""
# Do we need to do this?
if (".Items()(" not in vba_code):
return vba_code
r = vba_code.replace(".Items()(", ".Items(")
return r | 7f403faf11158180e2d492488f95b1cc644f971c | 596,889 |
def num_existing_reports(ir_json_v6):
"""
This returns the number of existing clinical reports (i.e. summary of findings) for a case
This can be used to check that there aren't any existing clinical reports before submitting a new one,
or to check that there is only one clinical report when submitting a... | 178a97d591bee222ba094035c187c5cce498d060 | 596,890 |
import re
def img_id(fname):
"""Extract image ID from filename.
Parameters
----------
fname: str or pathlib.Path
Input filename.
Returns
-------
str
Cassini image ID.
Raises
------
ValueError
If the provided name is invalid.
Examples
-------... | 25fbc136d6fc4009a6c5f924cd1387b21de7c817 | 596,891 |
def seconds_to_string(duration):
"""Convert a time in seconds to a mm:ss string
"""
if duration is None:
return '00:00'
minutes = int(duration // 60)
seconds = int(duration % 60)
return '{:02d}:{:02d}'.format(minutes, seconds) | c1367c1a4f714226b68fa57d67d4c3d666aee976 | 596,893 |
def compute_iou(box_1, box_2):
"""
This function takes a pair of bounding boxes and returns intersection-over-
union (IoU) of two bounding boxes.
"""
tl_row_1, tl_col_1, br_row_1, br_col_1 = box_1
tl_row_2, tl_col_2, br_row_2, br_col_2 = box_2
assert tl_row_1 < br_row_1
assert tl_col_1 ... | 04185a8afad3ef9f455cfa7465089d01f5246648 | 596,894 |
def argmax(iterable, labels=None):
"""
Return the pair (max, amax) where max is the max of iterable and amax is the
arg max of the iterable
"""
iterable = enumerate(iterable) if labels is None else zip(labels, iterable)
am, m = max(iterable, key=lambda tuple: tuple[1])
return m, am | b3aa611d54327886a0bdddfec4d19d6b25ddd199 | 596,896 |
def string_chop(InStr):
""" output = string_chop(InStr)
Chop the ending '\r' and '\n' from input string
Args:
InStr: str, the input string
Return:
output: str
'\r' corresponds to '0x0d' or 13,
'\n' corresponds to '0x0a' or 10
"""
... | 932fd4dcb121c98e16fdddb48f4fe191e02bbd70 | 596,898 |
def compose_capability_list(caps):
"""Returns a string containing a braced list of capabilities as enums.
Arguments:
- caps: a sequence of capability names
Returns:
a string containing the braced list of SpvCapability* enums named by caps.
"""
return '{' + ', '.join(['SpvCapability{}'.... | a908e262d15e6be7fd1ad9772181d44fcda11b83 | 596,900 |
def check_shell_asterisk(cmd):
"""
Determine whether a command appears to involve shell stars.
:param str cmd: Command to investigate.
:return bool: Whether the command appears to involve shell stars.
"""
return r"*" in cmd | 04b5c4985035e9c62506ff1fb2af4dea0d054f94 | 596,902 |
def get_account_name(provider_class):
"""
Return the account name for a particular provider. This name is used by
Qiskit internally and in the configuration file and uniquely identifies
a provider.
Args:
provider_class (class): class for the account.
Returns:
str: the account n... | cd4ef86b7e52d218e5c20a5364a00168b23758d7 | 596,903 |
from typing import List
def chunk_list(l: List, n: int) -> List[List]:
"""Get successive n-sized chunks from l."""
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
return [l[i:i + n] for i in range(0, len(l), n)] | 96317bd4ab675191c213cbe6b463cb8aec2e6fb1 | 596,907 |
def list_to_pg_array(elem):
"""Convert the passed list to PostgreSQL array
represented as a string.
Args:
elem (list): List that needs to be converted.
Returns:
elem (str): String representation of PostgreSQL array.
"""
elem = str(elem).strip('[]')
elem = '{' + elem + '}'
... | a06ed810a29a0c2aa26ab3615352bad2c2bab19c | 596,908 |
def read_data(fn: str) -> str:
"""Read in a txt file and strip newlines."""
with open(fn,"r",encoding='Latin-1') as fh:
data = fh.read()
return data | 415b7c15ceb3659df0bfb226d15b5d6b129b0f11 | 596,910 |
def fibonacci_memory(nth_nmb: int) -> int:
"""An recursive approach to find Fibonacci sequence value, storing those already calculated."""
memory: dict = {0: 0, 1: 1} # Cache to store calculated fib values in
def fib(_n):
if _n <= 1:
return _n # Return input nr
elif _n not in ... | 3c3c47612e8e55ff90e6b4a492c6611402f8a419 | 596,913 |
def get_model_config(config, model_id):
"""
Return config of a single model
"""
for model_config in config["models"]:
if model_config["model_id"] == model_id:
return model_config | 1f8cc16ce602d791b9f787ba7da54890463e9cee | 596,923 |
from typing import Any
def check_type(o: Any, target_type: str) -> bool:
"""
Check if `o`'s class path + name matches `target_type`.
E.g. `check_type(o, "numpy.ndarray")`
Checking types using this method instead of `isinstance` with the actual type is
preferred here so that we don't have to impo... | cf96d05d720d6e057a6eb3b46b96ce213d463d65 | 596,924 |
import click
def split_http_header(header_string):
"""Splits a colon-separated string into header and value"""
parts = tuple(part.strip() for part in header_string.split(":", 1))
if len(parts) != 2 or any(part == '' for part in parts):
msg = "Invalid header '{}'. Use colon to separate name and val... | f14bbb97fd6ede878928dc4f758d2cef96619a3a | 596,926 |
from typing import Dict
from typing import Tuple
from typing import Any
def get_train_and_validation_metrics(metrics: Dict) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Utility function to separate out train_metrics and val_metrics.
"""
train_metrics: Dict[str, Any] = {}
val_metrics: Dict[str, An... | da1e9b8df549883b0fd0addc3c5ad20012b994da | 596,928 |
import _datetime
import pytz
def move_tz(dt: _datetime.datetime, tz: str) -> _datetime.datetime:
"""Change a datetime from one timezone to another."""
# Datetime provides a ValueError if you use this function on a naive DT, so
# no need to explicitly raise an error here.
return dt.astimezone(pytz.time... | 070c63ace1c4f723ff6ce62ae7a1c1b5fa5b07b1 | 596,929 |
def backprop(y, y_pred, w, x):
"""
Backpropagation to compute w gradients
y : ground truth targets
y_pred : predicted targets
w : weights for the network
x : inputs to the net
"""
# start from outer most
y_grad = 2.0 * (y_pred - y)
# inner layer grads
w_grad = x.T.dot(y... | 96a6950844efae88eb6b3aaa0af6c1b31263248a | 596,931 |
def req_version(req):
"""Builds the version string for the requirement instance
:param req: requirement object
:returns: the version in desired format
:rtype: string or NoneType
"""
return ''.join(req.specs[0]) if req.specs else None | 54628c3a1c402e4a73df286f00b77ccdb727329c | 596,932 |
def zero_forcing(signal, threshold=1e-20):
"""
Parameters
----------
signal: np.ndarray a NxM numpy ndarray
threshold: float the cutoff value for the zero forcing (default: 1e-20)
Returns
-------
the signal, where no value is smaller than threshold
"""
signal[signal < threshold... | af5427026300e677406d47cf34c521e64ece7e2f | 596,934 |
import torch
def optim_to_device(
optim: torch.optim.Optimizer, device: torch.device
) -> torch.optim.Optimizer:
"""Change optimizer device.
Args:
optim: Optimizer.
device: To device.
Returns:
Optimizer on selected device.
"""
for state in optim.state.values():
... | 42144429b271c5a64582f71311f2e01e3937fa96 | 596,937 |
def get_db_directParent(connection,cd_tax):
"""
Retrieve direct parent information in the database
Parameters
-----------
connection: postgres connection
connection to the postgres database
cd_tax: int
identificador de la especie en la base de datos
Returns
---------... | b802509686334866a4581df98f6b03b13d982467 | 596,940 |
def get_master(isamAppliance, check_mode=False, force=False):
"""
Check if the node is the primary master
"""
return isamAppliance.invoke_get("Check if the node is the primary master",
"/isam/cluster/ismaster/v2") | 24a1c2883b281ec58a5dc5eec242d1e9b61a13ba | 596,941 |
def parseDate(date):
"""Parses a date tag from xml input
returns a tuple containing the year, month, and day as strings
"""
yearNode = date.getElementsByTagName('year').item(0)
monthNode = date.getElementsByTagName('month').item(0)
dayNode = date.getElementsByTagName('day').item(0)
year = yearNode.firstChild.da... | 0f58d078463887fd61a70de0209da7b5a717c2af | 596,942 |
def to_localstack_url(api_id: str, url: str):
"""
Converts a API GW url to localstack
"""
return url.replace("4566", f"4566/restapis/{api_id}").replace(
"dev", "dev/_user_request_"
) | 8981bad3b1c155a9f9ac0e44faa8cface44edb4e | 596,943 |
def base_command(resource):
""" Return the base gcloud command with api_version, group and subgroup.
Args:
resource: Definition of a type of gcloud resource.
Returns:
list of base commands of gcloud .
"""
base = ['gcloud']
if resource.api_version:
base += [resource.api_... | 535f37646f7c8f3205b69102b62f181162a52adc | 596,945 |
def setup_channels(roi, channel, dim_channel):
"""Setup channels array for the given ROI dimensions.
Args:
roi (:obj:`np.ndarray`): Region of interest, which is either a 3D
or 4D array in the formate ``[[z, y, x, (c)], ...]``.
channel (List[int]): Channels to select, which can b... | 87fdc287332827702a848c6aea072304252886cc | 596,947 |
def is_subdir(child, parent):
"""
Check whether "parent" is a sub-directory of "child".
:param child: Child path.
:type child: ``str``
:param parent: Parent directory to check against.
:type parent: ``str``
:return: True if child is a sub-directory of the parent.
:rtype: ``bool``
""... | 5903030c91801e17cf3dfb744f7737a56fbcc5c8 | 596,948 |
def _string_score(input_str):
"""Sum the ord(c) for characters in a string."""
return sum([ord(x) for x in input_str]) | 4674ca9c091afc2a47dd2d0a2b54e8f9adf90c71 | 596,949 |
def join_labels(labels, join_symbol="|", threshold=1.e-6):
"""
Join labels with a joining symbol when they are very close
:param labels: a list of length-2 tuples, in the format(position, label)
:param join_symbol: the string to use to join different paths. By default, a pipe
:param threshold: the ... | b52b69a23dddec2edb81f022571c9e2f5573a229 | 596,952 |
import torch
def fast_compute_class_metric(test_preds, test_sols, class_metrics = ('accuracy', 'recall', 'precision')):
"""
Computes manually (i.e. without sklearn functions) accuracy, recall and predicision.
Args:
test_preds: numpy array/ torch tensor of size N with discrete output vals
... | 997b1d279201b71c7b2e3b609ab60a76ba74ddce | 596,953 |
def infer_mask_from_batch_data(batch_data):
"""
Create binary mask for all non-empty timesteps
:param batch_data: BatchSize x SequenceLen x Features
:return: BatchSize x SequenceLen
"""
return batch_data.abs().sum(-1) > 0 | 658e9b634f06e797ff32ad5373907b647117e94d | 596,954 |
def bound_value(value: int, minimum: int=0, maximum: int=9) -> int:
"""
Bounds a value between an upper and lower bound
:param value: the value to bound
:param minimum: the minimal allowed value
:param maximum: the maximal allowed value
:return: the bounded value
"""
return minimum if v... | 9e5ec5551276d05c0056f97da2666e87569c0f28 | 596,956 |
def generate_diffs(hit):
""" Takes a hit location and returns diffs like ONE_TWO: upper left to upper right """
first_sensor = None
for key in hit.keys():
if hit[key] == 0:
first_sensor = key
break
diffs = {
"ONE_TWO" : (hit["one"] - hit["two"]),
... | 77b034199f85cfe3a2cf75544e167814737f3755 | 596,962 |
def clip(x, lower, upper):
"""Clip ``x`` to [``lower``, ``upper``]."""
return min(max(x, lower), upper) | 6a363bed0ed28a9145a3385ff74f2ca08768776a | 596,964 |
import codecs
def modifyHexByte (hexStr, n):
"""Takes a hex string and modifies the n-th byte in it."""
arr = bytearray (codecs.decode (hexStr, "hex"))
arr[n] = (arr[n] + 1) % 256
return arr.hex () | c090493c908a0e9b94eb30f9e0dbdc4bc96c82c1 | 596,965 |
def unscale_pos(q_sc):
"""
Unscale the position of the EMPS dataset to the original range.
"""
q_unsc = q_sc*0.125 + 0.125
return q_unsc | f22aa7bda064fb06715662f69a0be4b7b081e3a4 | 596,966 |
def turn_anticlockwise(direction):
"""
Given a direction, returns the next direction around anticlockwise.
"""
return (direction - 1) % 4 | c8b715c261c569a6cad1611ff376e24baa97a228 | 596,968 |
def empty(field):
""" Helper function that returns True if a field's value is empty """
return field.value.strip() == "" | e49e12c3261c60e03b34d9e7ebfd5f19774bf4d7 | 596,972 |
def handle_error(reason):
"""
Returns a dict containing err and reason
:param reason: A string, why it failed
:return: A dict containing err and reason
:rtype: dict
"""
return {
"err": True,
"reason": reason
} | e156ab163f4be5130b1fed7145b2b18b047a5830 | 596,973 |
def isprobablytitle(s):
"""Return True if string s looks like it could be a title; False otherwise.
This is a heuristic function based on my Gutenberg Poetry corpus. Takes
every word from string s with five or more characters
and returns True if the resulting joined string is in title case.
>>> is... | d462e9029efa98a215f2b8a060f36f6210bc8d90 | 596,978 |
def get_proto_deserializer(proto_class):
"""
Return a basic proto deserializer that takes in a proto type to deserialize
to
"""
def _deserialize_proto(serialized_rule):
proto = proto_class()
proto.ParseFromString(serialized_rule)
return proto
return _deserialize_proto | 53c0d051051d0ce7f57a8f01ef53b06a7920a344 | 596,981 |
import functools
import time
def timeit(func):
"""Decorator to measure the time spent by a function."""
@functools.wraps(func)
def timed(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
return end - start, result
return timed | 5fe7f53238c8b000fa39865f0100ad6add34e1af | 596,983 |
def merge_alignments(min_gap, alignments):
"""Combines previously identified alignments if close together
Alignments are combined if within min_gap distance
Returns list of Alignments
"""
merged_alignments = []
for alignment in alignments:
if len(merged_alignments) == 0:
me... | b280d2352148a6fd57c1ef01536cf998b91e8fdc | 596,985 |
def _ct_specification_type_to_python_type(specification_type: str) -> str:
"""
Convert a custom specification type into its python equivalent.
:param specification_type: a protocol specification data type
:return: The equivalent data type in Python
"""
python_type = specification_type[3:]
r... | 4a63283b0c888fe31e0d87b18b42d1948633b962 | 596,987 |
def parse_media_file(mediaf):
"""
Get the present media compounds.
Parameters:
mediaf: filepath to the tab-delimited media file.
Returns:
media: dictionary with first level of keys as compound IDs. The values
are another dictionary of compound name, formula, and charge.
... | 7ff9d7cb1b8d7706b087875fa09256373cac4dce | 596,989 |
def reverse_complement(seq):
"""This function returns the reverse_complement sequence of the input sequence
from 3' to 5' """
complement = {'A':'T', 'C':'G','G':'C', 'T':'A', 'N':'N'}
rcomp_seq = ''
for base in seq:
rcomp_seq = complement[base] + rcomp_seq
return rcomp_seq | 8ee586788ae38c32ded853451a99c50799538e5b | 596,994 |
def DecomposeStandardFieldName(standard_field_name):
"""Utility function takes a standard_field_name from the ontology and returns its composition.
Example: [run_command_1] -> ['Run', 'Command']
Args:
standard_field_name: a standard field name defined by Carson.
Returns:
list: a list of concepts that ... | 0b2afcb60fef8b09b01b576a4c785ce9f88cccb8 | 596,996 |
import torch
def apply_box_deltas_3D(boxes, deltas):
"""Applies the given deltas to the given boxes.
boxes: [N, 6] where each row is y1, x1, y2, x2, z1, z2
deltas: [N, 6] where each row is [dy, dx, dz, log(dh), log(dw), log(dd)]
"""
# Convert to y, x, h, w
height = boxes[:, 2] - boxes[:, 0]
... | 1cee6c19df3da620422eb5060e36826690af1849 | 596,997 |
def objective(k, p):
""" The objective function.
Delta is *negative* when p exceeds the maximum.
A k less than 1.13 also produces a negative value, but by a
much smaller amount.
"""
delta = 0.0
if k < 1.1 :
delta = k - 1.1
return 1.0 * (1.5 - p) + 50.0 * delta | 1c829852ca35d01ac000ecd5b67b26237d37bdb4 | 596,999 |
def Lambda_type_minus_r_over_t(g1d, gprime, gm, Delta1, Deltap, Omega):
"""
Minus the reflection coefficient of a Lambda-type atom divided
by the transmission coefficient. The transfer matrix for the
Lambda-type atoms will be written in terms of this ratio.
"""
#Assume real Omega
return g1d*... | 845dc9112c2e84a88ead001112e840d374666629 | 597,004 |
def compare(s1, s2, strict=False):
"""version.compare compares two version strings (format X.Y.Z)
if s1 < s2, returns -1
if s1 == s2, returns 0
if s1 > s2, returns 1
if strict=False (default) 2.1 == 2
if strict=True 2 < 2.1
"""
s1v = s1.split('.')
s2v = s2.split('.')
#process bot... | 161cd765cbb2d1c3ad3d9d8acb206bd1d229d485 | 597,008 |
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 |
def process_to_dict(process):
"""Return nested dicts for the nested namedtuples of a process."""
# These lines are sort of like a deep version of _asdict().
stages = [stage._asdict() for stage in process.stages]
for stage in stages:
stage['progress_items'] = [pi._asdict() for pi in stage['progress_items']]
... | 306e565fdaad76fa956e8706a9d2b605bce32a96 | 597,011 |
def remote_addr_ip(request):
"""
Returns the IP Address contained in the 'REMOTE_ADDR' header, if
present. Otherwise, `None`.
Should be suitable for local-development servers and some HTTP servers.
"""
return request.META.get('REMOTE_ADDR') | f12ec8ede61bc54f167a09fe9b21a2c9b5cd3d90 | 597,013 |
def _GetHeaders(plugins):
"""Returns a set of headers from the given plugins."""
headers = set()
for plugin in plugins:
headers.update(i['header'] for i in plugin['implementations'])
return headers | 21a73bfd9352bb41eb83ad0898aee9d79ead6527 | 597,017 |
def SEIR_Map(state):
"""
Encodes the literal SEIR state to an integer.
Args:
(str): State of the human i.e. S, E, I, or R
"""
if state == "S":
return 0
if state == "E":
return 1
if state == "I":
return 2
if state == "R":
return 3 | 08b412badcd6c33b482df6443272958f1fefca45 | 597,021 |
def convert_single_pair_dict_list(dict_list):
"""This function converts a list of single-pair dictionaries into a normal list.
:param dict_list: A list of single-pair dictionaries
:type dict_list: list
:returns: A normal list with the value from each dictionary
"""
new_list = []
for dict_pa... | 981a01fe219af98a15094a1ba278e6b1d74a56cb | 597,026 |
def has_dict_changed(new_dict, old_dict):
"""
Check if new_dict has differences compared to old_dict while
ignoring keys in old_dict which are None in new_dict.
"""
if new_dict is None:
return False
if not new_dict and old_dict:
return True
if not old_dict and new_dict:
... | 32d9e34e35906e6eefd5157cadb78953a96f43b0 | 597,030 |
def parse_pvc_param_line(pvc_param):
"""
Takes a pvc mount in the format: "pvc-name/subpath/desired:/mountpath/desired[:r]"
and returns {"name": "pvc-name",
"subPath": "subpath/desired",
"mountPath": "/mountpath/desired",
"readOnly": False}
:param pvc_... | b57278ccb814e276e683c6eed3eb73d4528e09a9 | 597,031 |
import re
def validate_version(version):
"""
Validate the version and check if the value is in the right format. This is a custom validation
and just checks if the version has the major.minor.patch parts. If required we can add more semver
specific regex from - https://semver.org/#is-there-a-suggeste... | 4049ec23ad96a57b3ff0e86f754e10547911b19f | 597,035 |
def find_index(val, array):
""" Return the index/position of element, whose value equals to val, in
array
"""
res = [i for i, v in enumerate(array) if v == val]
return res[0] | 8fe92c57789ba31be50ae181f4883744e0382a90 | 597,036 |
def scan_rate_formatter(scan_rate):
"""
Format the IDL table 'SCAN_RAT' column.
In IDL at least, the scan rate column has a very particular format (0.0000 for cases
where there is no scan being done, left-aligned). There's no good one-step way of
doing that formatting in python, so here's wha... | 3a57c642550238ac2fb38323a2e0f962aa06aba0 | 597,037 |
import csv
def read_csv_file(path):
"""
Read csv file that can be directly inserted into table.
In ccvg database these csv files should be predefined categories, units, province, city, county
Header and data of csv file are reading separately.
:param path: path to csv file
:return: data: rec... | aacbeb280c682de1a2a06a258cc6b5be73546abc | 597,046 |
def children(word, word_dict):
"""Returns a list of all words that can be formed by removing one letter.
word: string
Returns: list of strings
"""
res = []
for i in range(len(word)):
child = word[:i] + word[i+1:]
if child in word_dict:
res.append(child)
return r... | 128607bcf012e9b649583ae794e5f2ce42beabab | 597,048 |
def pytorch_id(node):
"""Returns a unique ID for a node."""
# After ONNX simplification, the scopeName is not unique anymore
# so append node outputs to guarantee uniqueness
return node.scopeName() + "/outputs/" + "/".join(["{}".format(o.unique()) for o in node.outputs()]) | 8c71b86dd5dd6f96af113f99222984ef0ff2ffa1 | 597,055 |
def GetDictFromMap(entries):
"""Gets a dictionary from an array of map entries. A map entry is any object
that has a key and value fields.
Args:
entries: list List of map entries.
Returns:
dict Dictionary constructed from map entries.
"""
dct = {}
for entry in entries:
dct[entry['key']] = en... | 7f84818fb3c27b03b48c6c2727ab534a7ef17a79 | 597,056 |
def point_judge(center, bbox):
"""
用于将矩形框的边界按顺序排列
:param center: 矩形中心的坐标[x, y]
:param bbox: 矩形顶点坐标[[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
:return: 矩形顶点坐标,依次是 左下, 右下, 左上, 右上
"""
left = []
right = []
for i in range(4):
if bbox[i][0] > center[0]: # 只要是x坐标比中心点坐标大,一定是右边
... | bb0d8eb6c4b056f8dc95493aa35c775045e0df90 | 597,058 |
import json
def init_chart_data(number_of_channels, number_of_samples):
"""
Initializes the chart with the specified number of samples.
Args:
number_of_channels (int): The number of channels to be displayed.
number_of_samples (int): The number of samples to be displayed.
Returns:
... | d814611ed2be435dc06e766267542e5804fdee5e | 597,059 |
def compute_leading_dashes_y(alignment, ind_x, seq_x, seq_y, scoring_matrix, alignment_matrix):
""" int, str, str, int, str, str, dict of dict, list of list -> int, str, str, int, int
Helper function that takes the current alignment strings and score and then
computes the next pair in the alignment with the... | 87033b508505fd5ea57e9af7135d8b2f4145d93d | 597,063 |
def peek_left_base(idl, genome, chr_prefixed):
"""Get the nucleotide immediately left to the indel
Args:
idl (Indel obj)
genome (pysam.FastaFile): reference genome
chr_prefixed (bool): True if chromosome names in BAM are "chr"-prefixed
Returns:
left_base (str)
E... | 1683c80765be8b68bff26c40ca52b91514fa5798 | 597,072 |
from typing import List
def count_word(word: str, word_list: List[str]) -> int:
"""
Counts how many times a word is present in a document
"""
return sum(1 for w in word_list if w == word) | 041592efdedb9bfc807cbe16d31d37a0d3b331c7 | 597,076 |
from typing import Any
from typing import Dict
def Constant(value: Any) -> Dict:
"""
A hyperparameter configuration for a constant value.
Arguments:
value:
A JSON-serializable value (int, float, str, or a some combination
of those types in a list or dictionary)
Return... | 185841de7bfe69f8915b3fc936c48aa2cedce135 | 597,080 |
def args2dict(args, dict_args={}):
"""convert list of arg strings to dict.
Args:
args (list): a list of ['key=val'] pairs
dict_args (dict): a dict to append to
Returns:
dict: a dictionary of the key/values
"""
for arg in args:
#this_entry = re.findall(r'[^"\s]\S*... | b86aa9abab189b3c02fb49a19160121e9c92fe7a | 597,081 |
def r_find_last_common(CL0_r, DoneSet0, CL1_r, DoneSet1):
"""CL0_r, CL1_r -- reversed versions of the command lists CL1 and CL0.
i: 0 1 2 3 4 5 6 7 8 k: 0 1 2 3 4 5 6
.-.-.-.-.-.-.-.-.-. .-.-.-.-.-.-.-.
|g|B|i|j|k|l|A|m|o| |a|b|c|B|A|e... | 3332dd3bd785f50eb2560db160326ffa37bd341a | 597,085 |
def is_sentence(value):
""" Determine if the given string is a sentence. """
if len(value) > 0 and value[0] == "S":
return True
else:
return False | a0138373d1673f70bce0e8ac3e25fa80b7150efc | 597,086 |
def extract_requirements(filename):
"""
Extracts requirements from a pip formatted requirements file.
:param filename: str path to file
:return: list of package names as strings
"""
with open(filename, 'r') as requirements_file:
return requirements_file.read().splitlines() | 7ed8654800e66bfe6ac48af22dc1cbeaa6693d13 | 597,092 |
def _identity(x):
"""Return input as is, the identity operation"""
return x | 631bc642720ceda8d94fe668a436870e84e79bca | 597,093 |
def pad(value,size):
""" pad a string with spaces to the size provided """
if len(value) < size:
value += ' '*(size-len(value))
return value | 975a82cfaceec4048340206524be6aadc1077199 | 597,095 |
def caip_uri_to_fields(uri):
"""Helper function to parse BQ URI."""
# Remove bq:// prefix.
uri = uri[5:]
project, dataset, table = uri.split('.')
return project, dataset, table | 133356e79736fb88f28743b1135429fd7a2abbe4 | 597,096 |
def executor(request, _switch):
"""
The actual fixture that should be used in testing.
Parametrize your test by decorating:
```
@pytest.mark.parametrize(
"executor", ["local", "sync", "mproc", "mthread"], indirect=True
)
```
or with some subset of executors th... | 3f4cdc66f194fd6242f6c34955c7762a66e78d17 | 597,097 |
import re
def parse_line(line):
"""
Input: A string
Output: One of 1. A dict with keys 'key', 'value'
2. 'nothing' (if the line contains no information)
2. 'unrecognized' (if parsing failed)
"""
if re.match('\s*(#.*)?$', line):
return 'nothing'
m... | cc9f137bae7471d78db9591d0a6f89a7b0f1bb3a | 597,098 |
def _BuildNetworkHookEnv(name, subnet, gateway, network6, gateway6,
mac_prefix, tags):
"""Builds network related env variables for hooks
This builds the hook environment from individual variables.
@type name: string
@param name: the name of the network
@type subnet: string
@param ... | 5f7e04640fcebbc024c246200d6eb187d48bb179 | 597,099 |
from typing import Iterable
def filter_exceptions(elements: Iterable) -> tuple[list, list[BaseException]]:
"""Filters the exceptions of the iterable and returns a tuple with the separated results."""
exceptions_ = []
no_exceptions = []
for element in elements:
if isinstance(element, BaseExce... | 49e4ba66a088db6562e9effe36e600c5d00613ce | 597,101 |
import random
def random_choice(seq):
"""wrapper around random.choice that returns None if the sequence is empty"""
return None if not seq else random.choice(seq) | 40894aa9c7f03712756fecaaa32e09f0803d9da1 | 597,108 |
from typing import Union
import requests
import random
def new_passphrase(
words: int = 4,
num: int = 1,
seperator: str = "-",
dice_rolls: int = 4,
dice_sides: int = 6,
list_url: str = "https://www.eff.org/files/2016/09/08/eff_short_wordlist_1.txt",
) -> Union[str, list]:
"""Generates one ... | de9f72c0d889c612a8e8e0c061b5c604c53213e8 | 597,110 |
def drop_duplicates(df):
"""Return df without duplicates."""
return df.drop_duplicates() | e948ffab2abf8d2149082a0cad0d965ca0e3965e | 597,111 |
from pathlib import Path
def get_image_path(name, directory):
"""Gets the path of an image based on a directory in the script's folder and a name.
:param name: The name of the image.
:param directory: The directory name, in the same folder as this script.
:type name: str
:type directory: str
... | bab9e782d8444a1f17fd78219d79d014718ea0d2 | 597,112 |
def g(x):
"""Example function 2
Parameters
----------
x : float
function argument
Returns
-------
float
function value in `x`
"""
x = abs(x - .5)
if x < .1:
return 2 + x
elif x < .3:
return 2.1 + (x - .1)**2
else:
return -(x - .3)... | 585c8b3f6208170baee136a842c4291dda77a00a | 597,113 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.