content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from pathlib import Path
def ensure_dir(dpath):
"""Ensure that a directory exists"""
absdir = Path(dpath)
if not absdir.exists():
absdir.mkdir(parents=True)
return absdir | 91b9b9d1f21cf53f81d2fb398805ebe9012680f9 | 612,383 |
def get_next_chunk(chunk_enumerator):
""" An enumerator wrapper that returns None instead of throwing.
"""
try:
return next(chunk_enumerator)
except StopIteration:
return None | f5d2434738dd270f00b75ed480f69d1a4da9170e | 612,384 |
def get_all_subclasses(cls, include_itself=False):
""" recursively find all subclasses of a given class cls """
all_subclasses = [cls] if include_itself else []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
retu... | 9f0ddf27d35b27f9d4a22a6b0ab659970ed89ec7 | 612,393 |
from pathlib import Path
def create_folder(folder):
"""Create a folder if it doesn't exist"""
folder = Path(folder)
if not folder.is_dir():
folder.mkdir(parents=True)
return folder | 6030bf2315a4b96d6782e11a44d9d4242cc6cefb | 612,399 |
def map_range(x, in_min, in_max, out_min, out_max):
"""
Maps a number from one range to another.
Note: This implementation handles values < in_min differently than arduino's map function does.
:return: Returns value mapped to new range
:rtype: float
"""
mapped = (x-in_min) * (out_max - out_m... | b87e7fe7acf8478d5dcb25e6cb982bc7da08893f | 612,403 |
def is_nucleus(particle):
"""Test if particle is a nucleus.
See dataclasses/private/dataclasses/physics/I3Particle.cxx
Parameters
----------
particle : shape () ndarray of dtype I3PARTICLE_T
Returns
-------
is_nucleus : bool
"""
return 1000000000 <= abs(particle["pdg_encoding... | ea6ad913539d71333bf0942813a35a16a4fc4af6 | 612,412 |
def get_trace_component_for_rule(rule_db, trigger_instance_db):
"""
Returns the trace_component compatible dict representation of a rule.
:param rule_db: The rule to translate
:type rule_db: RuleDB
:param trigger_instance_db: The TriggerInstance with causal relation to rule_db
:type trigger_in... | d709e7815895639a625f0c4d396b55c34b90eca8 | 612,415 |
def undotify(dotdict):
"""
Expand a dictionary containing keys in "dot notation".
This support both standard dict or OrderedDict, or any dict subclass.
For example::
.. code-block:: python3
dotdict = {
'key1.key2.key3': 'string1',
'key1.key2.key4': 1000,
... | 2df8a3421d12c47c66bdb3a70b15afb2cc693b13 | 612,416 |
def spaces(num_spaces: int) -> str:
"""
Return a string with the given number of spaces.
"""
return ' ' * num_spaces | 55ecef32aab471fc0ccef10c93f3334ffb2caba6 | 612,419 |
def get_initials(name):
"""Return the intials from a string."""
return ''.join([x[0].upper() for x in name.split()]) | 6deae2609ec6d8924b55b3de114743b2f13fe0e4 | 612,422 |
def mag2Flux(mag, unit='maggy'):
"""
Convert HSC AB magnitude into physical flux.
Parameters
----------
mag : scalar or array of float
Magnitude of the object.
unit : string, optional
Unit of the flux. ('maggy/nanomaggy/jy')
Default : 'maggy'
"""
flux = 10.0 ** ... | d5b7dfbe5c580b2eefe4f9ab9bac11e62aee113d | 612,425 |
def get_cron_strings(job):
"""Returns cron strings.
:param Job job: An apscheduler.job.Job instance.
:return: cron strings
:rtype: dict
"""
return {
'month': str(job.trigger.fields[1]),
'day': str(job.trigger.fields[2]),
'week': str(job.trigger.fields[3]),
'day_of... | c3a84a09e50fcf202ae5c03059b71392154181b7 | 612,429 |
import math
def _crop_scans(obj_scan, blank_scan, dark_scan, crop_factor=[(0, 0), (1, 1)]):
"""Crop given scans with given factor.
Args:
obj_scan (float): A stack of sinograms. 3D numpy array, (num_views, num_slices, num_channels).
blank_scan (float) : A blank scan. 3D numpy array, (1, num_sl... | 9479ff3fe1d0059878785fcd3190e79447e04739 | 612,430 |
import re
def _is_valid_frequency(value: str) -> bool:
"""Returns true if the frequency passed is an instance of string, is not None, and adheres to the
regex patterns for frequency strings.
"""
pattern = r"^\d+[smhdwM]$"
return isinstance(value, str) and re.match(pattern, value) is not None | b450ae2b18f06d006b3693bc6281cf793ebeae29 | 612,438 |
import logging
def _level_to_allowed_num(level, name_to_level=logging._nameToLevel):
"""Returns int. Raises ValueError for invalid str (not in name_to_level) or invalid int, or TypeError if needed. """
max_level = max(name_to_level.values())
if isinstance(level, str):
level = name_to_level.get(lev... | 1730db26ae664b50303e558f04a0dcb2edf8af5a | 612,440 |
def getsuffix(subject):
"""
Returns the suffix of a filename. If the file has no suffix, returns None.
Can return an empty string if the filenam ends with a period.
"""
index = subject.rfind('.')
if index > subject.replace('\\', '/').rfind('/'):
return subject[index+1:]
return None | 7bec5ed03420f28a68e67d98278f952085aebe53 | 612,441 |
def is_image(ext):
"""
Checks if the file_format is a supported image to read.
:param ext: the extension of a file.
:return: whether or not the file is a image
"""
return ext == '.jpeg' or ext == '.png' or ext == '.jpg' or ext == '.bmp' | c8aa7017dc8a39322c5abc314d747aa88b428017 | 612,442 |
def get_cat(CatVar, data):
"""
Gets the possible values for all categorical predictors, to be used with ohe. Necessary to avoid different numbers of columns when encoding.
:param CatVar: List. The categorical variables in the data that will be passed.
:param data: DataFrame like object. The full data fo... | 6465875347568bc59a30762aa16b0de399eb19c8 | 612,443 |
def LineObsColFlag(state1, state2, obstaclelist, robrad):
"""
Performs a collision check between a line connecting two states and a list of obstacles
We assume that points are inside the environment and not colliding with any obstacles.
Inputs:
state1, state2: two states to check (must have passed ... | 46fc247e7d8f3d5870e59bfec6749c566ee5ba03 | 612,450 |
import itertools
def guess_dict(guess,wildcard_char='?'):
"""Get a dictionary of possible things / combinations that the guess word could make. Example 'arise' has '????e' and 'er???'
Args:
guess (string): word to generate the combinations with
wildcard_char (string, optional): wildcard chara... | ad30e336f186dd58dd918baf823670b73b95ec0b | 612,452 |
def get_average_monthly_donwloads(daily_donwloads_list):
"""
Calculate the average monthly downloads from the download API response
"""
total = 0
for daily_donwloads in daily_donwloads_list:
total += daily_donwloads['downloads']
return total // len(daily_donwloads_list) | c53268150d50c2e4e7309bc064b296d258cb9fa7 | 612,456 |
def valid_name(name):
"""
This function checks if the given name is a valid name
"""
if not isinstance(name, str):
return "Bad input. Name should be a string"
if len(name.strip()) == 0:
return "Name can't be empty. Please enter a valid name"
elif len(name.strip()) < 3:
re... | 73888aef36fefad2204377f7d22050ea5036e1cc | 612,458 |
from typing import List
def as_package(names: List[str]) -> str:
"""Joins names as a package name."""
return '.'.join(names) | 7369de516104d94d11784e1dfef64ca9c86ddb26 | 612,463 |
def get_available_username(user_info):
"""
Determines the username based on information available from slack.
First information is used in the following order:
1) display_name, 2) real_name, 3) name
See: https://api.slack.com/types/user
:param user_info: Slack user_info object
:return: human... | a493dd0200a5d66a1e47af7d0bc13cb2d050ae35 | 612,474 |
def indentation(string, indent, count=1):
"""Indents a string.
Keyword arguments:
string -- The string you want to indent.
indent -- The string to use for the indent.
count -- How many times you want indent repeated.
"""
# Type check for string and indent
if type(string) is not str or t... | c8ba91dd4faac47ffee988088b579b6f3cdd2b64 | 612,475 |
def is_string(val):
"""
Return whether a value is a ``str``.
"""
return isinstance(val, str) | 77a9f87cf5ff947104d03d746f74cdbf6b376fef | 612,476 |
def PartialProgress(f1, f2, progress_callback):
"""Often a function accepting a progress callback needs to call
sub-functions to perform the task. By wrapping the given callback
with this function before passing it on, correct progress will be
sent upwards.
Like so:
def LongRunningTask(pro... | 287742326209a4e2de98a37fbe7808acb02e149a | 612,478 |
import re
def crop_title(source: str) -> str:
"""
Crop out the first title from the source if it starts with it.
:param source: source string to be processed.
:returns: source string with the first title removed
"""
result = source.lstrip()
if re.match('^#{1,6} .+', result): # starts wi... | debe4be73f3c039eed34893771a67c37123259cd | 612,479 |
import functools
import inspect
def get_func_kwargs(func):
"""Get keyword args of a function."""
# first, unwrap functools.partial. only extra keyword arguments.
partial_supported_params = {}
while isinstance(func, functools.partial):
partial_supported_params.update(func.keywords)
func = func.func
#... | 453e905d43960b5fac4f431d7fb6ac5645b2473b | 612,480 |
def nm_to_wavenumbers(nm):
"""calculate wavenumbers from given nm"""
return 10**7/nm | 28ed158f48a1c0b854364ffddd504905457f621e | 612,481 |
def one_hot_encoding(data: dict, feature: str):
"""
:param data: dict[str, list], key is the column name, value is its data
:param feature: str, the column name of interest
:return data: dict[str, list], remove the feature column and add its one-hot encoding features
"""
if feature == 'Sex':
for i in range(len(... | e05f471bae13a75be07414a697a2e2cbd549b1e8 | 612,482 |
from datetime import datetime
import pytz
def naive_to_aware(dt: datetime):
"""
Converts naive datetime to aware datetime.
"""
if dt.tzinfo is None:
return pytz.utc.localize(dt)
return dt | 5098027920af9fd6e81739ddadbbd82ef30bceda | 612,487 |
def da_is_float(da):
"""
Check if DataArray is of floating point type
"""
assert hasattr(da, 'dtype')
return da.dtype.kind == 'f' | 96783df8fcb43507d5434eec516c315dfa21575a | 612,491 |
from typing import Optional
from typing import Dict
def _is_export_remote(remote_info: Optional[Dict]) -> bool:
"""Check if remote_info is valid and has exporttree set to "yes"
Parameters
----------
remote_info: Optional[Dict]
Optional dictionary the contains git annex special.
Returns
... | e99057e7d55fd49b780261cabce705f1ddbcb368 | 612,495 |
from datetime import datetime
def format_unix(unix_ts, date_format):
"""Format unix timestamp as a string timestamp in date_format.
Args:
unix_ts: unix timestamp
date_format: datetime time stamp format
Returns:
string: formatted timestamp in `date_format`
"""
return date... | 67ce12819803e63f0585937e34efd5ee508b5baa | 612,497 |
def _move_delta_lbound(d, bytes):
"""Move the delta by the given amount of bytes, reducing its size so that its
right bound stays static
:param bytes: amount of bytes to move, must be smaller than delta size
:return: d"""
if bytes == 0:
return
d.to += bytes
d.so += bytes
d.ts -= bytes
if d.data is not Non... | fe4563351c198cd1f11a2aa36090578d17e5f2e9 | 612,501 |
def formatfloat(x):
"""Convert x to a %.3f-format string."""
ret = "%.3f" % float(x)
if float(x) >= 0.0:
return f" {ret}"
return ret | a70e9550d09f44bff44d22987c35be2233e4af56 | 612,502 |
def recvall(sock, num_bytes):
"""
Receives a size-prefixed message from the send() function above.
Thanks to Adam Rosenfield and Hedde van der Heide for the elegant solution.
Args:
sock: The socket to receive from.
Returns:
The complete message received by the socket, or None if no... | 424012ca6f65d2f663cbbfaf88ea02cae7c89d37 | 612,504 |
def ensure_bytes(s):
"""Attempt to turn `s` into bytes.
Parameters
----------
s : Any
The object to be converted. Will correctly handled
* str
* bytes
* objects implementing the buffer protocol (memoryview, ndarray, etc.)
Returns
-------
b : bytes
Rais... | 99b90fef4774f91af054a8563fe0a495f6c0e242 | 612,505 |
def xy_to_im_coords(xy, im_size):
"""
Args:
xy [batch_size, 2] in [-1, 1] x [-1, 1]
im_size
Returns:
im_coords [batch_size, 2] in [0, im_size] x [0, im_size]
"""
im_coords = xy.clone()
im_coords[:, 0] = (xy[:, 0] + 1) / 2 * im_size
im_coords[:, 1] = im_size - (xy[:, ... | 270085038c18dad1306199fedaf30d5826710a5a | 612,507 |
def input_columns_names(picture_size):
"""
Generate the names of the input columns representing the pixels of the
pictures, for a given picture size.
"""
input_columns = []
for color in 'rgb':
input_columns.extend(['%s%i' % (color, i)
for i in range(picture_... | 8ed5a485f3b485da9ecb3e5827f8ce8761b9252c | 612,509 |
def wavelength_tlv(wave_period, velocity):
"""Usage: Calculate wavelength (l) using wave period (T) and velocity (v)"""
return wave_period*velocity | 35e6292ccf7407336acc33dbb934e7a034b6401b | 612,512 |
def recall(fn: float, tp: float) -> float:
"""
Calculate recall.
:param fn: False negative count.
:param tp: True positive count.
:return: Recall.
"""
return 0 if tp + fn == 0 else fn / (tp + fn) | 1961d66471c462c5f74e604d1f5a4c9504bba927 | 612,514 |
def game_node_hash(game_node):
"""
Creates a unique hash of a game node.
Hashes are created with respect to the current state of the board and the
move that put it in that state.
Parameters
----------
game_node : chess.pgn.GameNode
Some node to hash.
Returns
-------
str
A hash value.
"""
board = game... | 20b5a67c757943cdb641da2bed13aa9c5076585b | 612,516 |
def is_query_complete(query):
"""
returns indication as to if query includes a q=, cb.q=, or cb.fq
"""
if query.startswith("cb.urlver="):
return True
if query.startswith("q=") or \
query.startswith("cb.q=") or \
query.startswith("cb.fq="):
return True
return False | 2890aada92324ee36ca347214a3d77ad6108e44b | 612,521 |
import random
def draw_random_indices(
mutable_sonic_content_indices: list[int], n_tone_row_instances_by_group: list[int]
) -> tuple[int, int]:
"""
Draw index of melodic lines group and index of tone row instance from it.
:param mutable_sonic_content_indices:
indices of groups such that t... | 27f4503d5825b5a994db4af56459e910eb0210e9 | 612,527 |
def order_mirrored_vertex_points(vertices, plane):
"""
Order mirrored vertex points to keep consistent global system
Args:
:vertices: (tuple) vertices like (a, b, c, d)
:plane: (str) plane ('xy', 'xz' or 'yz')
Returns:
:ordered_vertices: (tuple) ordered vertices
"""
a,... | 28f5b74dbab176885696ebe3819f3efccb8c228d | 612,528 |
def port_range(range):
"""
:param range: openstack port range format '200: 300'
:return: fortigate port range format: '100-200'
e.g. tcp-portrange 100-200:300-400
"""
if range:
return '-'.join([p.strip() for p in range.split(':')])
else:
return '1-65535' | 41a346a51c9e66ce60836727d7ca03146efd7a5b | 612,529 |
def tuplify_port_dicts(dicts):
"""
Input:
dicts (dict): embedded state dictionaries with the {'port_id': {'state_id': state_value}}
Return:
dict: tuplified dictionary with {(port_id','state_id'): value}
"""
merge = {}
for port, states_dict in dicts.items():
if states_dic... | 8f8c4e6e46160781baffc438143de92ee62645c8 | 612,535 |
def prior_knolwedge_categorized(price, n_bins = 12):
"""
function of prior knowledge for categorized price
:param price: input price - this price should already be bucketized. The value is in the range [0, n_bin)
:param n_bins: number of bins
:return: expected prob.
"""
# The winning probabl... | 25931e258b966a987d11710551ecfe234b8f1746 | 612,539 |
import math
def binom(row_index, column_index=None):
"""
Computes the n-th coefficient or an entire row from Pascal's triangle
binomial coefficients.
"""
if column_index is None:
return [
math.factorial(row_index) / (math.factorial(row_index - c) * math.factorial(c))
... | ecfee06a91fbb49783a12940777e9e2576fd4185 | 612,540 |
import random
def random_text(length):
"""Returns a random lower-case string of len length."""
return "".join([
chr(random.sample(range(97, 123), 1)[0]) for _ in range(length)
]) | 5796b807aac968554c7c30226b2f6c4f608c2c6e | 612,544 |
import socket
def hostname_to_server_id(hostname):
""" Convert a hostname to a MySQL server_id using its ip address
Args:
hostname - A string
Returns:
An integer to be used for the server_id
"""
ip = socket.gethostbyname(hostname)
parts = ip.split('.')
return ((int(parts[0]) << 2... | 5dff8fdb3bc1a8c5b505c31f027283f164391492 | 612,545 |
def get_crop_points_vert(img_a_w, transfmd_corners_img_b):
"""Function to find the pixel corners in the vertically stitched images to crop and remove the
black space around.
Args:
img_a_h (int): the width of the pivot image that is image A
transfmd_corners_img_b (numpy array): of sh... | dc94e0b26ee46180f91dd38c2aed63ab696eca72 | 612,547 |
def legendre_symbol(a, p):
""" Compute the Legendre symbol a|p using
Euler's criterion. p is a prime, a is
relatively prime to p (if p divides
a, then a|p = 0)
Returns 1 if a has a square root modulo
p, -1 otherwise.
"""
ls = pow(a, (p - 1) // 2, p)
return -1 if ls == p - 1 else ls | 37776f0b335794bb7e88d1152b3959d63a3658f0 | 612,548 |
from typing import Union
def _get_antenna_from_scene_dir_second(scene_dir_second: str) -> Union[str, None]:
"""If there is antenna datum inside `scene_dir_second` string, then return it.
Otherwise, return None."""
valid_antennas = ('CB11', 'CP5', 'ETC2')
# return antenna datum from scene_dir_second,... | c8a5aac0fc0d696b83139d734d59b6c53eceebf2 | 612,549 |
import hashlib
def to_script_hash(byte_array) -> bytes:
"""
Converts a data to a script hash.
:param byte_array: data to hash.
:type byte_array: bytearray or bytes
:return: the script hash of the data
:rtype: bytes
"""
intermed = hashlib.sha256(byte_array).digest()
return hashlib... | 6f9088f23d2411ad2a5d93bf21a299dc6ac1b782 | 612,550 |
def ssh_cmd(cmd_str, ip, ssh_key=None):
"""construct an ssh command
"""
if ssh_key is None:
ssh_cmd_str = 'ssh %s \'%s\'' % (ip, cmd_str)
else:
ssh_cmd_str = 'ssh -i %s %s \'%s\'' % (ssh_key, ip, cmd_str)
return ssh_cmd_str | 323059169909fc71cdd258f83813eed92f2f4dcc | 612,551 |
from typing import Optional
from pathlib import Path
def get_aml_user_folder() -> Optional[Path]:
"""Return the root of the user folder."""
path_parts = Path(".").absolute().parts
if "Users" not in path_parts:
return None
# find the index of the last occurrence of "users"
users_idx = len(p... | d5f9dd480dfd285aa51950c83d1b0eae66d40d4c | 612,552 |
def match(s1, s2):
"""
:param s1: str, the long DNA sequence to be compared
:param s2: str, the short DNA sequence to match
:return: str, the most similar segment from the long DNA sequence
"""
ans = ''
maximum = 0
# The maximum of match rate
for i in range(len(s1) - len(s2) + 1):
... | 8b52d377831ffc94df4195430b2c251f7755f672 | 612,556 |
def acronym_gen(phrase):
"""Acronym generator
Args:
phrase (str): Phrase to shorten to acronym
Returns:
str: Acronym
"""
phrase_split = phrase.split()
acronym = ""
## iterate through every substring
for i in phrase_split:
acronym = acronym + i[0].upper()
... | 8ea4edf08b898e74370851a1b0bc8ae0440aa1c0 | 612,557 |
from functools import reduce
def _prod(seq):
"""Returns the product of the elements in the sequence `seq`."""
return reduce(lambda x, y: x*y, seq, 1) | 09aa53b89facf1194054407e1a9fedbfb4071173 | 612,559 |
def _validate_template_folder(template_folder):
"""
Validates the given `template_folder` value.
Parameters
----------
template_folder : `None` or `str`
The template folder's value.
Returns
-------
template_folder : `None` or `str`
The template folder's validated value.... | db1f704c88406539a578f8fd263c5547944e3db8 | 612,563 |
def formula(n):
"""Returns the n-th number of fib with math formula"""
sqrt_5 = 5**0.5
return round(((1 + sqrt_5) / 2)**n / sqrt_5) | 6654821fbde285aeb2ee1990739b128f2371fc8f | 612,570 |
from builtins import str as text
def get_attr(obj, attr):
"""
Get the right value for the attribute. Handle special cases like callables
and the __str__ attribute.
"""
if attr == '__str__':
value = text(obj)
else:
attribute = getattr(obj, attr)
value = attribute() if ca... | 49ea639815bf3594203ebdca96c9e3bcd2256ac5 | 612,574 |
def _replace_angle_brackets(url_string):
"""
Replace angle brackets with braces in a given url.
Swaggerhub prefers URLs with variables to have curly braces instead of
angle brackets, so this replaces all instances of angle brackets with curly
braces. For example:
/users/<user_id> -> /users/{us... | 117eb3081c0db9e4f32fb71b059cd923c297d208 | 612,575 |
def local(public_repo_name):
"""Return local form of public repo name.
Aptly REST API interprets '_' as '/' in repo names.
:param public_repo_name: The name of the repo (e.g. a4pizza/base)
"""
return public_repo_name.replace('/', '_') | 7827338a2c62cf0a8135b6d9eadca1aa4671055f | 612,576 |
import torch
def collate_sequences(samples, pad, align_right=False):
"""Collates 1D tensors of different length with padding."""
lengths = [x.size(0) for x in samples]
max_length = max(lengths)
# initialize with batch_size * length first
tensor = samples[0].new(len(samples), max_length).fill_(pad)... | 207fd6fc5ee09138072327c4ac97a50869539399 | 612,577 |
def get_intersection_columns_for_different_csv_files(output_dict):
"""
Args:
output_dict (dictionary): a dictionary that has the keys as
columns and the values as the number of csv files they occur in
Returns:
column_list (list): a list of columns that has the columns which occur
... | ef68f087a792a5f101778c9408320a6fddad4527 | 612,580 |
import re
def to_snake_case(section):
"""Transforms input to snake_case from formats like CamelCase
Required Args:
section (str) - Name of String to be converted
Returns:
(str) section in snake_case
"""
return re.sub(r'(?<!^)(?=[A-Z])', '_', section).lower() | 55f3f93ea6bba9b5bd96662616645a8583fb6080 | 612,583 |
def get_latest_file(file_path, filename_like, file_ext):
"""
Find absolute path to the file with the latest timestamp given the datasource name and file extension in the path
:param path: where to look for the file
:param datasource: stem name of the file
:param file_ext:
:return:
"""
fi... | bf31be16c304caea55b333c2c263823c62fd8a30 | 612,586 |
from functools import reduce
def compose(*functions):
"""
Create a single unary function from multiple unary functions
"""
# pylint:disable=undefined-variable
return reduce(lambda f, g: lambda x: f(g(x)), functions) | 930267cea5f638995f8fdd9e6001da957691a327 | 612,588 |
def soft_threshold(x, threshold):
"""
If abs(x) is less than or equal to threshold
then return 0, else move the value towards
0 by the threshold amount.
"""
if x > threshold:
val = x - threshold
elif x < -threshold:
val = x + threshold
else:
val = 0
return val | 91e8b856956d08dbc57a018bb6963877e97ba5dc | 612,589 |
def read_logfile(log_filepath):
"""
Function to read the portal.log file generated by Genesippr
:param log_filepath: Path to portal.log
:return: Raw list of lines from the log file
"""
try:
log_file = open(log_filepath, 'r')
log_lines = log_file.readlines()
log_file.clos... | 460ca782dff9c65e823c8a4703896d0f0862066e | 612,590 |
def generate_net_file_name(file_prefix, net_number):
""" Generate file name and suffix for net-file (.pth). """
return f"{file_prefix}-net{net_number}.pth" | 363c53de54f385863a046057f059165bf5d53fc4 | 612,594 |
def get_chrom_name_from_bin_fn(bin_fn):
"""
Assuming that the bin_fn is like this: genome_chr2.211_binary.txt.gz
Chrom name that is returned in this function will be like thisL chr2.211
"""
return bin_fn.split("_")[1] | 674bae8dd3ba31331a2bb306e64fa971f99c86c7 | 612,596 |
def add_marker(x, y, z):
""" Create a plotly marker dict. """
return {
"x": [x],
"y": [y],
"z": [z],
"mode": "markers",
"marker": {"size": 25, "line": {"width": 3}},
"name": "Marker",
"type": "scatter3d",
"text": ["Click point to remove annotation... | 04b62861d9fd774fd8ff2188fe6ded8098fb2a9b | 612,597 |
import bz2
def bz2_encode(data, level=9, out=None):
"""Compress BZ2."""
return bz2.compress(data, level) | bf69a7e99bd5e55dd0925773b9f0d7e5169f67ff | 612,598 |
import re
def contains_domain(address, domain):
"""Returns True if the email address contains the given,domain,in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False | 8ca7352995fe9b25e6c7e0094a4af89b65d10147 | 612,599 |
def built_before(building, timestamp, player):
"""Get list of buildings constructed before a given time."""
result = []
for item in player['build']:
if item['building'] == building and item['timestamp'] < timestamp:
result.append(item)
return result | 4d7dd2fce525ad79713034c458bf2ef78459a27e | 612,601 |
def recursive(array, element, left=0, right=None, sort=False):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements.
:param left: start limit of array.
:param right: end limit of array.
:param element: element to be searched.
:param sort: True will sort the array... | b401aa67ffc564cde2f3a2feb2cbebf31741815c | 612,607 |
def filesize_converter(size):
"""
Convert filesize unit to KB, MB and GB based on the size value.
# Arguments:
size: number of bytes
# Returns:
converted size.
"""
if size <= 1024:
size_report = str(round(size, 2)) + " KB"
elif size <= 1024*1024:
size_repor... | 2ebfc05393bafb07a7072697eb99a4868bad069b | 612,613 |
import re
def token_in_line(line, token):
"""Find if token is present in string."""
# the second regex needs to include digits for Base64 vs. Base, Type vs. Type1 etc.
pattern = r'(^|[^a-zA-Z_]+)' + token + r'($|[^a-zA-Z0-9_]+)'
p = re.compile(pattern)
hits = p.findall(line)
return len(hits) >... | c1f650cc401c0f3abe0d30c8bbaded7c419fe0b7 | 612,614 |
def get_content_values_by_name(content, name):
"""
:type content: dict
:param content: A dictionary as returned by KairosDB with timestamps converted to seconds since the epoch
:type name: str
:param name: The name of the entry in the results whose values will be returned
:rtype: list
:ret... | 17d44365836b471bfc010f4abbc2c25c7514844a | 612,620 |
def _feature_tokenize(
string, layer=0, tok_delim=None, feat_delim=None, truncate=None):
"""Split apart word features (like POS/NER tags) from the tokens.
Args:
string (str): A string with ``tok_delim`` joining tokens and
features joined by ``feat_delim``. For example,
`... | 1128855406cbaa13ba26bace09189d6b5c89c616 | 612,622 |
def label_atoms(mol, labels):
"""Label atoms when depicting a molecule
:param mol: input molecule
:param labels: labels, one for each atom
:return: molecule with labels
"""
[atm.SetProp('atomNote', "") for atm in mol.GetAtoms()]
for atm in mol.GetAtoms():
idx = atm.GetIdx()
... | bf0d886182a89008718fc590fb9d4c3bd10d0853 | 612,623 |
def is_high(speed: dict) -> dict:
"""Determine whether speed exceeds the limit"""
if speed['speed'] >= 100 or speed['speed'] <= 90:
speed['exceeds'] = True
else:
speed['exceeds'] = False
return speed | a35aca4f4ba96b0edd34466c2826ec168d5f851b | 612,625 |
def is_volume_classifier(model_prediction: dict, volume_metadata: dict) -> bool:
"""
Is this a prediction of a volume classifier?
:param model_prediction: a mapping from identifiers to classification results
:param volume_metadata: maps a volume_identifier to (exam_identifier, side, view)
:return:... | bd15ca3d239cab337f5a71d402ef9f419deb7335 | 612,626 |
def is_classifier(estimator):
"""
Returns True if the given estimator is (probably) a classifier.
From: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py#L526
"""
return getattr(estimator, "_estimator_type", None) == "classifier" | 148ba2e9fe97e10e381080968a86ea62e7d6b27a | 612,630 |
def convert_boolean_list_to_indices(list_of_booleans):
"""
take a list of boolean values and return the indices of the elements containing True
:param list_of_booleans: list
sequence of booleans
:return: list with integer values
list of the values that were True in the input list_of_boo... | a1471c0483e4f6d424e2ab992174965e1a19e7f9 | 612,635 |
def titleScraper(title):
"""remove special symbols "/\: *?"<>|" based on .txt filename restrictions"""
regex = r'/\\\\: \\*\\?"<>\\|'
cleanTitle = title.translate({ord(c): "_" for c in regex})
return cleanTitle | 7edfce7ec5714c9908a522cafe560b2c0e48e5ba | 612,637 |
def _find_project_dir(ftp, base_dir, projectid):
"""Find a genome project directory in ftp directory based upon directory name postfix. Return None if not found."""
# Retrieve listing of directories under base_dir
directory_listing = ftp.nlst(base_dir)
# Find projectid dir based on directory suffix
... | b31a489f13c0caa4df2bd559926e50abd3af18ca | 612,639 |
def extract_contact_responses_to_each_whisker(
coef_wscale_df,
big_waveform_info_df=None,
coef_metric='scaled_coef_single',
include_task=('discrimination',),
floor_response_at_zero=False,
drop_always_suppressed=False,
drop_C0=True,
drop_neurons_missing_whisker=True,
combine_off_targe... | 1b5a9b38d73c4c31b714fb4c71cb7675d48e3754 | 612,642 |
def _reverse_dict(my_dict, my_value):
"""
Tries to find which key corresponds to a given value in a dictionary - i.e.
reverses the dict lookup.
This code assumes no two keys share the same value - as is the case with
PSU-WOPWOP dicts used here.
"""
return {value: key for key, value in my_d... | d6e076b48bba70ee060b0979e15b141ca6516bcb | 612,643 |
def id(self):
"""Returns a unique id identifying the NodePath instance"""
return self.getKey() | b88fc47c2976159f98579e9f7a1e350ff97b9108 | 612,646 |
def remove_prefix(text: str, prefix: str) -> str:
"""Removes a prefix from a string, if present at its beginning.
Args:
text: string potentially containing a prefix.
prefix: string to remove at the beginning of text.
"""
if text.startswith(prefix):
return text[len(prefix):]
... | bee742d06b61e0872ea6384340c20b3be272abfe | 612,653 |
def get_argv(cmd: str) -> list:
""" Return a list of arguments from a fully-formed command line. """
return cmd.strip().split(' ') | c151fddb69a71feb65d3d481cde150b47577bf85 | 612,654 |
def rho_bot_vap(t_boil_y_bot, T0, Vm, M_bot_vap):
"""
Calculates the destiny of vapor at the bottom of column.
Parameters
----------
t_boil_y_bot : float
The boilling temperature of low-bolling component of vapor at the bottom of column, [C]
T0 : float
The initial temperature, [K... | ecd7afe3f0d80ac270aeb92d8bc19236bec7d6b3 | 612,659 |
def hz2dft(freq, sr, nfft):
"""Map frequency in Hz to discrete Fourier transform bins.
Parameters
----------
freq: array_like
Frequency in hz
sr: int
Sampling rate in hz
nfft: int
Number of DFT bins in range [0, 2*pi)
Returns
-------
bins: array_like
... | 53c9ff7e7a29e9202dc3e0133ace4f3977c2f8cf | 612,661 |
def split_age_parameter(age_breakpoints, parameter):
"""
creates a dictionary to request splitting of a parameter according to age breakpoints, but using values of 1 for
each age stratum
allows that later parameters that might be age-specific can be modified for some age strata
:param age_break... | 7776353cecd2008b24abd63946d09e6b8b7d1521 | 612,662 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.