content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def get_alleles(glstring):
"""
Takes a GL String, and returns a set containing all the alleles
"""
alleles = set()
for allele in re.split(r'[/~+|^]', glstring):
alleles.add(allele)
return alleles | 0f0b9a94214c2973e6ccb8c17ff1c249849c440c | 595,502 |
def base128Stringified(value):
"""
Encodes the given integral value into a string that is an encoded comma-
separated series of bytes, base-128, with all but the last byte having
the high bit set, in C++ hex notation, as required by the DER rules for the
nodes of an OID after the first two.
>>>... | 3989d52173bec9831cc3199115fb47d5c58b077b | 595,503 |
def getAddress(address):
""" Method returns the formed address
:param address: raw address
:return: formed address
"""
message = 'Address: ' + address
return message | b4ef7d6b1479e19c4bc93037159f24c034067567 | 595,507 |
from typing import Union
def percentage(
per: float, whole: float, *, operation: str = "", log: bool = False
) -> Union[float, str]:
"""
This function will calculate a whole with a certain percentage value.
>>> from snakypy.helpers.calcs import percentage
>>> percentage(25, 500)
... | 526fc52c5f254d64b49706eed067a583779b0745 | 595,508 |
from datetime import datetime
import warnings
def _std_strftime(dt_obj: datetime, fmt_char: str) -> str:
"""
Standard datetime.strftime() with normalization and exception handling.
"""
str_ = ""
try:
str_ = dt_obj.strftime(f"%{fmt_char}")
if not str_ or str_ == f"%{fmt_char}":
... | faf2ef7534a7a0501239df636cb4db740de39a62 | 595,510 |
def StringSearch(*column_names):
"""
Search for string types, supports :contains and :exact modifiers.
If string search should be performed in multiple columns using OR
multiple columns can be passed.
"""
if len(column_names) == 0:
raise TypeError("StringSearch takes at least one positi... | 079013833efd9fb770f4a98446e6d4fb58ed5081 | 595,513 |
def remove_duplicates(annotations):
"""Removes duplicate annotations. This is mostly used for persons when same
person can be both actor and director.
Args:
annotations (List): List of annotations.
Returns:
List: List of annotations without duplicates.
"""
return [
anno... | 2b6af69f8e535ed5fd19d0ad51322fa46f35e460 | 595,515 |
def accepts(source):
""" Do we accept this source? """
if source["type"] == "git":
return True
# There are cases where we have a github repo, but don't wanna annalyze the code, just issues
if source["type"] == "github" and source.get("issuesonly", False) == False:
return True
return ... | 86ba7af47389a2eec0c816455e6b5997eeacc82d | 595,527 |
def interpolate_z(d_target, d_start, d_end, z_start, z_end):
"""Linearly interpolate z = f(d) between two points.
Parameters
----------
d_target : float
z is computed at this d value.
d_start : float
x coordinate of the first point.
d_end : float
x coordinate of the ... | f9a03eb5b68ddd8a3873c29b9522f9726339e059 | 595,532 |
def parse_list(string, convert_fn):
"""Parse a (possibly empty) colon-separated list of values."""
string = string.strip()
if string:
return [convert_fn(piece) for piece in string.split(':')]
else:
return [] | 7f0c61c2ebf688800b64fa04e3aedc661f5343fa | 595,534 |
def split_list(l, n_parts=1):
"""Split a list in a number of parts
Args:
l (list): a list
n_parts (in): the number of parts to split the list in
Returns:
list: a list of n_parts lists
"""
length = len(l)
return [l[i * length // n_parts: (i + 1) * length // n_parts]
... | 8829deaae2517856c7a98d98f07fb6163b811b64 | 595,535 |
def _evaluate_params(params_name: list, params_index: list, config_params_available: bool):
"""
This ensures that (1) if parameter names are provided in the config file, one and only one of
the arguments, `params_name` or `params_index`, might be given, and (2) if parameter names are
NOT provided in the... | 8d98c9537412fe6026e7385762647b05d972684c | 595,543 |
def asset_france(gee_dir):
"""return the france asset available in our test account"""
return f"{gee_dir}/france" | 0ebfbd84a630c0dd1fed25297cff0ca5ec903122 | 595,546 |
def get_key_by_value(dc: dict, value):
""" Returns key from dict by value """
for k, v in dc.items():
if v == value:
return k | 7b4d21b8c43c2318f9823d7cfbd5f5237f90e223 | 595,550 |
def load_initial_grid(state_slice, dimensions):
"""Make initial grid from the state_slice depending on number of
dimensions."""
grid = []
initial_slice = [
[column for column in row]
for row in state_slice
]
if dimensions == 4:
initial_slice = [initial_slice]
grid.app... | 93e23d0809b925eb813b6f97e74da35a869818ac | 595,553 |
import hashlib
def md5sum_bytes(content):
"""Calculate md5sum of a byte string."""
assert isinstance(content, bytes), 'Invalid type %s' % type(content)
m = hashlib.md5()
m.update(content)
return m.hexdigest() | 6fe57fb90958aa2bb5a5b9cd123a946d888a633d | 595,556 |
def cut_odd_events(end_time, event, save = True):
"""
Cuts sync pulses so that they are even (e.g recording stop before the last
trial ended)
:param end_time: Time in seconds of the end of the last trial
:param event: Syncing event to be corrected. It has to be a bunch object
(see brainb... | 1b76f1a7bf682fe46f932101aa0673f1ed33f712 | 595,557 |
from datetime import datetime
def datetime_from_string(dt_string):
"""
Converts string to datetime object
:param dt_string: datetime string
:type dt_string: str
:return: datetime object
:rtype: datetime
"""
return datetime.strptime(
dt_string.split("+")[0].split("Z")[0], "%Y-%... | be369b4468e10f54bfa8d1c5317cd0118e4b0af9 | 595,558 |
from typing import Mapping
from typing import Any
def is_nested(item: Mapping[Any, Any]) -> bool:
"""Returns if 'item' is nested at least one-level.
Args:
item (Union[object, Type[Any]]): class or instance to examine.
Returns:
bool: if 'item' is a nested mapping.
... | 9b61d63f100e7cd4da1ba628d7637c3d52a82ce1 | 595,562 |
def log_pop(N, t, r_m, K):
"""The right-hand side of the logistic ODE"""
return r_m*N*(1-N/K) | 2e15ab1789243f30099c58a510015f12140a64cf | 595,563 |
import torch
def repeat_tensors(n, x, dim=0):
"""
For a tensor of size Bx..., we repeat it n times, and make it Bnx...
For collections, do nested repeat
"""
if torch.is_tensor(x):
# x = x.unsqueeze(1) # Bx1x...
# x = x.expand(-1, n, *([-1] * len(x.shape[2:]))) # Bxnx...
#... | 78e3adaaa5112e4aee7959186ccb3cdea851fca0 | 595,566 |
import itertools
def combinations(p, target):
"""Return all possible subsets of the set {0...p-1} \ {target}"""
base = set(range(p)) - {target}
sets = []
for size in range(p):
sets += [set(s) for s in itertools.combinations(base, size)]
return sets | 04dc25c56e2c14630ec4a4f9b64154a70bf945fa | 595,569 |
import torch
def extract_relu_parameters(relu):
"""
For a feedforward network with (leaky) relu activation units, extract the
weights and bias into one tensor.
"""
weights_biases = []
for layer in relu:
if isinstance(layer, torch.nn.Linear):
weights_biases.append(layer.weig... | f8c307de2cfd1400f2ce45491d19aae92898576e | 595,576 |
def f_to_c(f) -> float:
"""Converts Fahrenheit degrees to Celsius degrees."""
return (f - 32) * 5/9 | d7f4ca61f400c34f37b11b160e049b2353c6e227 | 595,577 |
import hashlib
def sha256_hash(path):
"""
Returns a SHA-256 hash of either the contents of the path, or the data passed in if file-like.
"""
sha256 = hashlib.sha256()
if hasattr(path, 'read'):
file_object = path
else:
file_object = open(path, 'rb')
while True:
buf = file_object.read(0x100000)
if not bu... | e8a97f5716c5161b75fb7a96d202c423017d842c | 595,579 |
def longest_increasing_subsequence_by_one(a):
"""
Solution:
memo[i] stores the length of the longest subsequence which ends with a[i].
For every i, if a[i] - 1 is present in the array before the ith element,
then a[i] will add to the increasing subsequence which has a[i] - 1.
"""
index_of = ... | ec6c29a79982fa4044bfcacf25b90aed858f7b87 | 595,581 |
def string_to_strings(string):
"""transforms a comma-separated string to a list of strings"""
return string.split(",") | 4f532738aeff1ea52faa639d1cbc250889e28f9c | 595,584 |
import torch
def _cross_entropy(y_hat, y_true, class_weights=None, epsilon=1e-7):
"""Semi-supervised cross entropy loss function.
Args:
y_hat: prediction tensor with size (N, C), where C is the number of classes
y_true: label tensor with size (N, C). A sample won't be counted into loss
... | 65744075c2d4db34791bbbd50b53badeacb3d342 | 595,586 |
def get_db_syllable_side(node, matcher):
"""
Get which side is suitable according to syllable matching.
This function expect node to have both syllable neighbours.
Return minus int if char node should be added to left neighbour,
plus int if to right,
0 if not determined.
"""
if node.pre... | 5f08984b1805f3067b8e9483e0b33b3b19465ee7 | 595,589 |
def list_of_colors(length):
"""Return a list of colors of the given length"""
# list of nice colors: https://coolors.co/f94144-f3722c-f8961e-f9c74f-90be6d-43aa8b-577590
base_colors = ['#f94144', '#f3722c', '#f8961e', '#f9c74f', '#90be6d', '#43aa8b', '#577590']
colors = []
for i in range(length):
... | 01bb63346248c14b76c2196fcac1657d0809d61a | 595,590 |
def remove_first_range(some_list):
"""
Returns a given list with its first range removed.
list -> list
"""
return some_list[1:] | 43f6da41be8e73d53ce601481f47800f96781c1e | 595,591 |
def _repeat_f(repetitions, f, args):
"""Auxiliary function for function par_search()
This function executes ``f(*args)`` repeatedly (at most
``repetitions`` times) until the return value is a result
differnt from None. It returns the pair ``(result, n)``,
where ``result`` is the result of th... | f32d9ac3a23af41a99faadc85c6c5ef4c5a644b6 | 595,598 |
def get_error_message(resource_name: str, error: str = 'Not Found') -> str:
"""
Get error message.
Args:
resource_name (str): The name of the resource which trying to retrieve.
error (str): Exception message
Returns:
str: Error message.
"""
return f'An error occurred wh... | 78c82f945c240f1f79f12a13f5bd0c67a46f0469 | 595,601 |
import struct
def rawbytes(s):
"""Convert a string to raw bytes without encoding"""
outlist = []
for cp in s:
num = ord(cp)
if num < 255:
outlist.append(struct.pack('B', num))
elif num < 65535:
outlist.append(struct.pack('>H', num))
else:
... | 1616111d15d63dd102320cf26d9162cf1ab4e71b | 595,603 |
import re
def startsWithAuthor(s):
"""
This function is used to verify the string(s) contains 'Author' or not with the help of regular expressions.
Parameters:
s: String
Returns:
True if it contains author name otherwise False
"""
patt... | 26a87fb86cb7214f20e11fd79ca8f58b2e379d83 | 595,604 |
def dict_key(dictionary, key):
"""
Receive and dictinoary and a key
:param dictionary: 'playlists': {'0': {'id': 3, 'name': 'Novo'}, '1': {'id': 3, 'name': 'Novo'}}
:param key: '0' :str
:return: The value of the dict. Ex: {'id': 3, 'name': 'Novo'} :dict
"""
return dictionary[int(key)] | 7090bddc7c55282e55ac8ee2392e8b8d0e5bb633 | 595,606 |
import shutil
def rm(dir: str, recurse: bool = False) -> bool:
"""
Removes a file or directory
"""
if dir.startswith("file:"):
shutil.rmtree(dir[7:], recurse)
return True
print("skip: dbutils.fs.rm({},{})".format(dir, recurse))
return False | 9bfd15920bb6a3f7b3c12e2ab873230afc68e082 | 595,609 |
def calc_box_sum(intg_img, start, height, width):
"""
Calculates sum for specified sub-box of integral image
+---+---+
| nw| ne| :param intg_img: integral image (np.ndarray, int32)
+---+---+ :param start: start pixel coordinates (tuple, height x width)
| sw| se| ... | c961097955bcfd3004f437cec0de7a3879a02b73 | 595,610 |
import itertools
def make_labels(value, number):
"""
Make labels for training and testing of
a binary classifier.
Parameters
----------
value : int
The label, where `0` means a non-random
MAC addresses and `1` means a random
MAC address.
number : int
The number of labels.
Returns
... | df26320060e0180a854f8b47fbe1de1907496fa6 | 595,611 |
def headers_to_dict(header_file):
"""Reads from a header file and generates a ``dict`` from it.
:param str header_file: Path to the header file.
:return dict: The headers, in a ``dict`` representation.
"""
headers_dict = {}
with open(header_file, 'r') as headers:
for header in headers:
... | f5e123a8a2cb4894807bb5236269ceb42b5682c5 | 595,613 |
import time
import calendar
def startOfDayUTC(time_ts):
"""Calculate the unix epoch time for the start of a UTC day.
time_ts: A timestamp somewhere in the day for which the start-of-day
is desired.
returns: The timestamp for the start-of-day (00:00) in unix epoch time.
"""
_time... | c438803a40500dc588a938d97ae273205ec0b6fb | 595,616 |
def is_open(knot_vector, polynomial_degree):
"""
Check whether a knot vector is open.
Arguments
---------
knot_vector : array_like
The knot vector.
polynomial_degree : int
The polynomial degree of the curve generated by knot_vector.
Returns
-------
bool
True... | e1115928db962d429db01c432d555e1669f7ae22 | 595,617 |
import re
def simplify_punctuation(text):
"""
This function simplifies doubled or more complex punctuation.
The exception is '...'.
"""
corrected = str(text)
corrected = re.sub(r'([!?,;])\1+', r'\1', corrected)
corrected = re.sub(r'\.{2,}', r'...', corrected)
return corrected | 818701198fbaf71a73c542a2b6d7c5963af330d4 | 595,620 |
def vm_hostname(vm):
"""Get the name of the host where VM is running.
:param vm: A Nova VM object.
:return: The hostname.
"""
return str(vm.get('OS-EXT-SRV-ATTR:host')) | 922024cf07404752ddca85d810afcf2a8410fdeb | 595,623 |
from typing import List
def split_and_remove_whitespace(text: str) -> List[str]:
"""Convert raw text to list of line strings"""
return [line.strip() for line in text.split("\n")] | dd9df2a1a76e300cf4dc9670f123366789d0934a | 595,624 |
def extract_dict_from_dataframe(df, column_as_key, column_as_value):
"""
Args:
df: input data frame
column_as_key: column of data frame to be dictionary keys
column_as_value: column of data frame to be dictionary values
Returns: extracted dictionary
"""
keys = df[column_as... | 3b05760600352ecbf558d3229cf6325aba8f75c4 | 595,625 |
def get_node_file_output_str(nset, varstr, frequency=99999999):
""" Get the string to add to the input file.
:param nset: Name of node set from which output should be output
:type nset: str
:param varstr: comma separated list of variables to output
:type varstr: str
:param frequen... | c45ed6178f8821cbdfb4d614cd869bf95af256e2 | 595,630 |
def false_negative_rate(y_obs, y_pred, upper_ci, lower_ci, sigmas=2):
""" Calculate the false negative rate of predicted values. Finds all values
that equal zero in the known array and calculates the number of false
negatives found in the predicted given the number of samples and sigmas.
The defined bo... | f703e0aa5390016f545d580bd5919c25414efdbd | 595,632 |
def _get_rand(microsim_model, N=100):
"""Get a random number using the PopulationInitialisation object's random number generator"""
for _ in range(N):
microsim_model.random.random()
return microsim_model.random.random() | de5f3a4222f698483df5967d8b78d88600520dcf | 595,633 |
import torch
def squared_dist(x, y):
"""Calculate squared Euclidean distance
Args:
x: tensor of size (N, D)
y: tensor of size (M, D)
Returns:
d: tensor of size (N, M)
Examples:
x = torch.randn(3, 7)
y = torch.randn(5, 7)
d = dist(x, y)
torch.norm(d - torch.norm(x.unsquee... | c1763311a91cbdacfdb8c43d686d3d572811ea28 | 595,635 |
def validate_tag(tag):
"""Returns if tag is alphanumeric, plus underscores."""
return tag.replace("_", "").isalnum() | 7b3ab51317aa6c524954b50500a7a1a15ef57f04 | 595,636 |
def multi_layer_second_directional_derivative(G, z, c, x, G_z, epsilon, w=None, Q=None):
"""
Same as second_directional_derivative, but assumes G returns multiple outputs in a list
"""
if w is None:
_, G_to_x = G(z + x, c, return_bn=True, Q=Q)
_, G_from_x = G(z - x, c, return_bn=True, Q=... | 764bf4cf39d7e1c193e9de42743cb81094d59792 | 595,637 |
import random
def _get_new_parents(current_animal_names, previous_parent_sets, num_parents):
"""Return a set of `num_parents` parent names that is not present in `previous_parent_sets`."""
while True:
new_parent_names = frozenset(random.sample(current_animal_names, num_parents)) # nosec
# Dup... | 57520c38775bf59f971dfdb93a07cb3a6cccefe8 | 595,639 |
def id18to15(id18):
"""
Truncate an 18 char sObject ID to the case-sensitive 15 char variety.
"""
return id18[:15] | c29dde47ff76178d077481766f0059eafaf3c2a9 | 595,640 |
def key_output(job_name: str) -> str:
"""Returns the output ID for the cache key"""
return f"key-{job_name}" | ea90041fa4be926d8986253e129e15ca92644617 | 595,646 |
def L1_norm(seq):
"""calculates the L1 norm of a sequence or vector
:param seq: the sequence or vector
:returns: the L1 norm"""
norm = 0
for i in range(len(seq)):
norm += abs(seq[i])
return norm | 934603b7dff3a0c9bce368f7f2047eb874f4937f | 595,657 |
def lv_pack(*args):
"""
Serializes using length:value format
:param args: values
:return: string
"""
s = []
for a in args:
s.append("{}:{}".format(len(a), a))
return "".join(s) | cf2463497757d5a4dc33608661908debb7162e5a | 595,658 |
def merge_tables(table1, table2,join_type='exact'):
"""Merges two RMTables into a single table.
Inputs: table1 (RMTable): first table to be merged.
table2 (RMTable): second table to be merged.
join_type (str): 'exact' - requires both tables have exactly the same columns.
... | 2a3778972497b25a69801c483bd8dd064e3cebfe | 595,659 |
def add_to_set(entries, new):
"""Adds an entry to a list and makes a set for uniqueness before returning the list.
Args:
entries: `list`.
new: (any datatype) The new member to add to the list.
Returns:
`list`: A deduplicated list.
"""
entries.append(new)
unique_list = l... | 7fcff194d67850d0f7ace408e5bbbe908b71886b | 595,668 |
def values(dictionary: dict) -> tuple:
"""Return a tuple of values in a dictionary."""
return tuple(dictionary.values()) | 8ed512f5d2e93240ad2594e320e15b000325b006 | 595,669 |
def clean_id(post_id):
"""
Fixes the Reddit ID so that it can be used to get a new object.
By default, the Reddit ID is prefixed with something like `t1_` or
`t3_`, but this doesn't always work for getting a new object. This
method removes those prefixes and returns the rest.
:param post_id: S... | b35fee4dd458f841fca55b14c90bad66c82191d4 | 595,675 |
def next_pow_two(n):
"""Returns the next power of two greater than or equal to `n`"""
i = 1
while i < n:
i = i << 1
return i | 75143f7477eee8d421220b473b8058079d4a2452 | 595,677 |
def flatten_geoms(geoms):
"""Flatten (possibly nested) multipart geometry."""
geometries = []
for g in geoms:
if hasattr(g, "geoms"):
geometries.extend(flatten_geoms(g))
else:
geometries.append(g)
return geometries | 32c72f81b91156143aaf93c586343f486416a2ce | 595,678 |
import torch
def get_ranking(predictions, labels, num_guesses=5):
"""
Given a matrix of predictions and labels for the correct ones, get the number of guesses
required to get the prediction right per example.
:param predictions: [batch_size, range_size] predictions
:param labels: [batch_size] arra... | 3ed330e7d3620efe42a3e47b3818f57802cc14f9 | 595,682 |
def crop_center_point(image_array, size):
"""
Finding point for center crop for gray scale
image_array: numpy array of image
size: desirable width & height as input
$
return -> cropped the center of input image into given size
"""
img_height, img_width = image_array.shape
crop_height, ... | 0242bb82f7f230c0ac346cedcdc13831a5284b0d | 595,684 |
import requests
def get_nearby_stops(key, base_url, latitude, longitude):
"""Sends request to get the nearest 5 bus stops"""
print('Finding nearby bus stops')
params = {
"key": key,
"lat": latitude,
"lon": longitude,
"count": 5
}
r = requests.get(base_url + '/gets... | 4eadb2ee5a507d2833df9d27ae1b6f3a20853109 | 595,685 |
def is_multiclass(args):
"""
Check args for any hint of a multiclass problem
(Check is option dependent and may be incomplete)
"""
# Not sure if --wap, --ect multi-class are actually right
for mc_opt in ('--oaa', '--csoaa', '--ect', '--wap', '--sequence'):
if mc_opt in args:
... | 2cc2c0a72844eb87f41ba8728540cc9cb076b2d5 | 595,686 |
def boolToBytes(v):
"""
Encode the boolean value as a byte.
Args:
v (bool): A boolean to encode.
Returns:
int: A byte.
"""
return 0x01 if v else 0x00 | a3adc3b84140e682a2ff5229168ec314c5e00427 | 595,687 |
def get_last_success_filepath(last_success_lookup: str) -> str:
"""
Returns the filepath containing the last successful source response
"""
with open(last_success_lookup) as fp:
last_success_filepath = fp.readline().strip()
return last_success_filepath | c555318476924b2cb0c4b06cacea48532ceb2b5a | 595,689 |
def local_latest(results):
"""Sift through local query results dataframe and return only the latest versions
Args:
results (pandas.DataFrame): each row describes one simulation matching the constraints
Returns:
results (pandas.DataFrame): same but only latest versions
"""
if len(re... | 14b34599111ae5fbafcf9ca43e2419b92f452927 | 595,690 |
def findVoicedSegments(arrT, arrFo, timeStep, minSegLength = 3):
"""
find voiced segments (identified by consecutive fo analysis data points)
within a time series of fo data
:param arrT: a numpy array containing the time offset information [s]
:param arrFo: a numpy array containing the fo information [Hz]
:param ... | 0837e2d25f8beede315c6679a2079a16c91887b5 | 595,691 |
def format_numeric_column(column):
"""
Format fn for simple numeric columns.
Returns column (zero-indexed) +1 to give 1-indexed label.
"""
return column + 1 | ff8393d4fb13d9742d3bc636d4720237596b26fe | 595,692 |
def array_extract_units(data):
"""extract the units of an array
If ``data`` is not a quantity, the units are ``None``
"""
try:
return data.units
except AttributeError:
return None | cc1aff0d1804c8d6d7871ada16048497e6a217ba | 595,695 |
def productDict(pairsData):
"""
transform the data into Dict with product info
:param pairsData: (companyName,product)
:return: dict={companyName:[product1,...]...}
"""
product_dict = {}
for company_name,product in pairsData:
if company_name not in product_dict:
product_d... | 7f56dcd8248cb0c6a4a7ad6174dde8c3d9325898 | 595,696 |
def get_contig_orderings(in_groupings):
"""
From the orderings files, return the following:
1. Dictionary associating a reference header with a list of ordered contig headers
2. Dictionary associating a contig with an orientation
3. Dicitonary associating a contig with its assigned reference header... | 8bfabbc860d9a39b1285969da216f9e816496cb4 | 595,697 |
def _tf_tensorarray_append(list_, x):
"""Overload of list_append that stages a TensorArray write."""
return list_.write(list_.size(), x) | 7c0569f9becf7dedf91d92bd9ae31de355e4f128 | 595,698 |
import string
def alpha_enum(value):
"""Convert integer to ordinal letter code (a, b, c, ... z, aa, bb, ...)."""
max_len = len(string.ascii_lowercase)
return str(string.ascii_lowercase[value % max_len] * (value / max_len + 1)) | ec106ef8ad22aced160521bfaad8f7e17e0cd848 | 595,699 |
def checkPort(port):
"""
Checks if the port is in the range 1 - 65535
:param port: the port to check
:return: True if the port is in the range, False otherwise
"""
try:
p = int(port)
if p >= 1 and p<= 65535:
return True
else:
return False
excep... | db5e2703e82796f5c367a5f8c8134b9110054e25 | 595,701 |
def dict_equal(dict1, dict2):
"""Check if 2 dictionaries are equal"""
return len(dict1) == len(dict2) == len(dict1.items() & dict2.items()) | 2448a8c065fa6a02aacc324ae606b9e7b60beaad | 595,702 |
def get_svd_index(H, W, compress_rate):
"""
(1-c) = (2*H*index + index) / H * W
(1-c) = (2*H + 1) * index / H * W
index = (1-c) * H * W / (2*H + 1)
"""
if compress_rate > 100:
return min(H, W)
c = compress_rate / 100
index = int((1 - c) * H * W / (2 * H + 1))
return index | 69c1a6c0e1158e1a3afa774652c123c02ffef1df | 595,705 |
import logging
def _resolve_promise_to_id_list(promise):
"""Given an object that might be a promise or an ID list, return IDs."""
if type(promise) == list:
logging.info('got list %r', promise)
return promise # Which is actually an ID list.
else:
key_list = promise.get_result()
id_list = [k.inte... | 9c176a78017b42c9ca6727430d1d35d7d31d7b99 | 595,707 |
def getHistSeparation( S, B ):
"""Compare TH1* S and B -- need same dimensions
Copied from : https://root.cern.ch/doc/master/MethodBase_8cxx_source.html#l02740
"""
separation = 0
nstep = S.GetNbinsX()
xaxis = S.GetXaxis()
nS = S.GetSumOfWeights()
nB = B.GetSumOfWeights()
for b... | ac73332c58c6771b0beeb58cc15244aaa2ff974d | 595,709 |
def bytes_get_code(a, i):
"""Access i-th item of Bytes object.
"""
return a[i] | 496ddfd010685732652b3231895c77cac6006228 | 595,710 |
import hashlib
def hash160(msg):
"""RIPEMD160(SHA256(msg)) -> bytes"""
h = hashlib.new('ripemd160')
h.update(hashlib.sha256(msg).digest())
return h.digest() | 98d46a3ad11f83e3dc7f46789e0dc936df7d46a3 | 595,711 |
def prepend_text(a, b=None):
"""Prepends a to b if b exists, else just returns a"""
if not b:
return a
return u"{0}\n\n{1}".format(a, b) | 2ab76c94e69007a035850ee3ef6a4336f5affc8f | 595,714 |
def attrs(obj):
""" Return attribute values dictionary for an object """
return dict(i for i in vars(obj).items() if i[0][0] != '_') | b9170055ebbfbdd5b2fe68ecdbbe198986f406a2 | 595,715 |
def _recip(x):
"""Return the reciprocal of x; to be used as the derivative of log(x)"""
return 1.0 / x | 4dabed0966e7a65794c25c10a79ee2402e6aaa85 | 595,716 |
def feature_selected_dataset(dataset, selected_feature_names, output_is_tuple=False, num_parallel_calls=None):
"""Create a `Dataset` by selecting features from an existed `Dataset`.
Arguments:
dataset: A `dict` structured `Dataset`.
selected_feature_names: A sequence of `str`, select... | fec7b1aa477db145a44656277968efbfef83f121 | 595,717 |
import re
def camel_or_pascal_case_to_space_delimited(s: str) -> str:
"""Convert `camelCased` or `PascalCased` string to space-delimited.
Based on https://stackoverflow.com/a/9283563/1557013.
:param s: string in `camelCase` or `PascalCase`.
:return: space-delimited string.
"""
space_delimite... | 43a6649d18702fd3fc8d917034a23cc0c91fc727 | 595,721 |
def get_country_code(language_code: str) -> str:
"""Extract the country code from the language code."""
return language_code[0:language_code.find('-')] | 2e4ac0549cdbf02459ee1cb6864b9264056dc99c | 595,723 |
def tunetrimf(a, b, c, delta, eta):
"""
Tunes the parameters of a triangular membership function T(a, b, c) with the parameters delta and eta
Condition: a <= b <= c
Parameters
-----------
:param a: The first parameter of the triangle
:param b: The second parameter of the triangle
:param... | ecc72a185c4b59fb395936c50ac7e76e28033b4a | 595,732 |
def _get_log_formatter(verbosity_level):
"""
Get a log formatter string based on the supplied numeric verbosity level.
:param int verbosity_level: the verbosity level
:return: the log formatter string
:rtype: str
"""
formatter = "%(levelname)s: %(message)s"
if verbosity_level >= 3:
... | b34d470b679e3b7d540290ef394ccada418b9ef7 | 595,733 |
def group_by(resources, key):
"""Return a mapping of key value to resources with the corresponding value.
Key may be specified as dotted form for nested dictionary lookup
"""
resource_map = {}
parts = key.split('.')
for r in resources:
v = r
for k in parts:
v = v.get... | 5ac0140233e4f6dad873ac26b7e7a96f9822621c | 595,735 |
def set_axis_label(ncvar):
"""
Set label plotting axis from name and unit of given variable
`ncvar`.
Parameters
----------
ncvar : netCDF4._netCDF4.Variable
netcdf variables class
Returns
-------
str
Label string: name (unit)
Examples
--------
>>> ylab ... | dd8a6c7b5b672306f77c355a843b18caca40dbcb | 595,739 |
def get_code_start_line_num(source_lines):
"""
Get the start code line number exclude comments.
Args:
source_lines (list[str]): Split results of code.
Returns:
int, the start line number.
"""
stack = []
index = 0
for i, line in enumerate(source_lines):
line_stri... | d80247ea879758a0dfc0f5c025aefeab31da7343 | 595,747 |
import yaml
def read_from_file(fpath):
"""Read the data in file given by fpath."""
with open(fpath, 'r') as stream:
yaml_data = yaml.load(stream, Loader=yaml.SafeLoader)
return yaml_data | e49d53b8c9857939b41d10c084eed63d56cbd7fd | 595,748 |
def sort_by_points(hn_list):
"""
Returns a sorted list of dictionaries from alternative_hacker_news to
be ordered by score (highest first).
"""
sorted_list = sorted(hn_list, key=lambda k: k["score"], reverse=True)
return sorted_list | bf85a5cf62ea6ea85e8786b40e1eced15e3bece2 | 595,751 |
def _get_tag_name_from_entries(media_entries, tag_slug):
"""
Get a tag name from the first entry by looking it up via its slug.
"""
# ... this is slightly hacky looking :\
tag_name = tag_slug
for entry in media_entries:
for tag in entry.tags:
if tag['slug'] == tag_slug:
... | 0906c849f632a0f17c0e5128cd13baf0f3d3264a | 595,753 |
def diff_sizes(a, b, progressbar=None):
"""Return list of tuples where sizes differ.
Tuple structure:
(identifier, size in a, size in b)
Assumes list of identifiers in a and b are identical.
:param a: first :class:`dtoolcore.DataSet`
:param b: second :class:`dtoolcore.DataSet`
:returns: l... | bd60593563e9bab086c1f1d92f13b9be135c7a1c | 595,754 |
def concat_2(a):
"""Concatenate the string "2" to to the end of an existing string object.
Parameters
----------
a : string
The string to be concatenated to.
Returns
-------
a+"2" : string
The resulting string.
Notes
-----
Uses the built-in ``+`` operator.
... | 0309373be792264a2f5707d6ea81f4a59968f751 | 595,755 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.