content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Iterable
def del_fields(d, fields):
"""Returns the same mapping, but with specified fields removed.
Intended to be applied to a stream of Mappings, using partial to fix fields
>>> d = [{'a': 1, 'b': 2}, {'a': 11, 'c': 3}]
>>> list(map(partial(del_fields, fields=['a']), d))
[{'b... | 9cc997018489bc744b8dc4c1e099e38871a94a46 | 590,444 |
def get_basename(path, extension):
"""Returns the filename (without its whole path) without its
extension.
Argument:
path: str
extension: str: The extension (with a dot if there is one).
Example:
>>> print get_basename("~/Meshes/my_mesh.mesh", ".mesh")
... my_mesh
"... | bc0414d123999674c3d581da0928a380242df23f | 590,445 |
import calendar
from datetime import datetime
def day_to_timestamp_ms(year, month, day):
"""Returns the milliseconds timestamp for the given date"""
return calendar.timegm(datetime(year, month, day).timetuple()) * 1000 | 39649002add3489c782ab09d18c5df4322a5ee7c | 590,446 |
import torch
def rescale_img(imgs):
"""
Rescale the values of an images from [-1,1] to [0, 255] and permute the channels of the images from [N, C, H, W] to
[N, H, W, C].
Args:
imgs: Image to rescale.
Returns: Rescaled images.
"""
return (imgs.permute(0, 2, 3, 1) * 127.5 + 128).c... | 5da1b1fab54878721d6d7cc3c6338f6832e911f9 | 590,449 |
from typing import Any
from typing import Callable
def make_async(return_value: Any) -> Callable:
"""Wrap value into async function."""
# pydocstyle
async def fn(*args, **kwargs):
return return_value
return fn | 59d0feb7aeb60194147a4b05ddaf76b356e2fb69 | 590,450 |
def sum_series(n, n0=0, n1=1):
"""
Compute the nth value of a summation series.
:param n0=0: value of zeroth element in the series
:param n1=1: value of first element in the series
This function should generalize the fibonacci() and the lucas(),
so that this function works for any first two nu... | abd9fcf4f74500b03c0c3fdd00ca2cb57553dcb5 | 590,452 |
import requests
def get_account(address):
"""Retrieves the account details of a CRO address
:param address: The address of the account to retrieve
:returns: The account JSON file or None if the request failed
"""
account = "https://crypto.org/explorer/api/v1/accounts/" + address
account_requ... | 9113bc5a3937be961c33b71e1530facb815cfe47 | 590,454 |
def setup(parser):
"""Add common sampling options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('-n', '--samples', type=int, required=True,
help='Number of Samples')
parse... | 771658c0c4f20acaab7785ae702baedb39cf87eb | 590,461 |
def get_parent(elt):
"""Get the parent of a given element."""
return elt.find_element_by_xpath('./..') | b1d992873022a4aea7f142fb99ddb7a3a01c9e41 | 590,463 |
import json
def cradmin_jsonencode(json_serializable_pythonobject):
"""
Template filter that converts a json serializable object
to a json encoded string.
"""
return json.dumps(json_serializable_pythonobject) | bb0330a84edb70548a381495228fe2920fe2ad22 | 590,467 |
def set_var(context, **kwds):
"""
Sets the given variables to provided values. Kind of like the 'with' block, only it isn't a block tag
:param context: template context (automatically provided by django)
:param kwds: named parameters with their respective values
:return: this tag doesn't render
... | 58cc142965a0bb49a8205b3e4892f1d71dbd6240 | 590,472 |
def quick_sort(list_values):
"""
Given a list, sort it using quick sort algorithm.
Working of quick sort: Take the last element as pivot,...
Partition the array around the pivot, and recursively sort the two sub-lists.
If the list contains one value, return the array.
"""
if len(list_values... | e2bbdbfe7fc6c889a7bbc5e0d0b33c6053e0ec60 | 590,473 |
def draw_specific_samples(param, parameters, samples):
"""Return samples for a given parameter
param: str
parameter that you wish to get samples for
parameters: nd list
list of all parameters stored in the result file
samples: nd list
list of samples for each parameter
"""
... | 24922620a6ca276321a19416b90e0fb880879e02 | 590,476 |
def denormalize_detections(detections, resized_size, scale, pad):
""" maps detection coordinates from [0,1] to image coordinates
The input image is padded and resized to fit the
size while maintaing the aspect ratio. This function maps the
normalized coordinates back to the original image coordinates.
... | bf9af656444b4aea99deca39f7761648ace87934 | 590,479 |
def is_valid(planning):
"""Validates planning, returns True on valid list.
- planning is expected to: be a parsed planning (see self.parse)
events in planning must be sorted by date from old to new.
"""
if not isinstance(planning, list):
return False
if len(planning) < 2:
re... | a9130dad357112b6149c23833fc0645458007e63 | 590,480 |
def get_document_ids(transaction_executor, table_name, field, value):
"""
Gets the document IDs from the given table.
:type transaction_executor: :py:class:`pyqldb.execution.executor.Executor`
:param transaction_executor: An Executor object allowing for execution of statements within a transaction.
... | 927284bf5b54a9d1c4dfc4b582ceda43d67fefdc | 590,482 |
def helper_sf_gather(sf_tensor, indeces):
"""
Helper function, given a SF tensor and action indeces, return only the
SFs associated with the actions
:param sf_tensor: SF tensor with action specific dimension of -2, here
with size (batch_n, *, |A|, d)
:param indeces: action inde... | 05a59b5cc59b48f4e27fa98e2f053d6bef773fce | 590,494 |
def flushqueue(q):
"""copy a queue into a list."""
l = list()
while not q.empty():
elem = q.get()
l.append(elem)
return l | 2b262f21753eaf247a70d20dfdc0498773da92ca | 590,495 |
def get_size(fobj):
"""
This function is used to determine the size of a file
"""
if fobj.content_length:
return fobj.content_length
try:
pos = fobj.tell()
fobj.seek(0, 2) # seek to end
size = fobj.tell()
fobj.seek(pos) # back to original position
r... | eb370f2e27c4bc1745260893af943c847e9d6a81 | 590,497 |
def preprocess_examples(examples, mode='train'):
"""
For training set and dev set, treat each utterance of the first speaker as
the response, and concatenate the goal, knowledge and the dialog’s previous
utterances as the history. In this way, multiple history-response pairs
are constructed.
... | 99beb7b61f7c6af00d30f751ddddc87be4fdabde | 590,498 |
def _parse_xyzin_box_lines(line):
"""Parses lines looking like "22.5 122.5 xlo xhi" to get the span (120 in the example)."""
data = line.split()
start = float(data[0])
end = float(data[1])
return end - start | 38e56e916f4984c7cde3323651d6eca9593adfcf | 590,501 |
def _test_assignment(assignment_test):
"""Test whether an assignment fails.
:arg str assignment_test: A python code snippet.
:returns bool: True if {assignment_test} fails with a TypeError.
"""
try:
eval(assignment_test)
except TypeError:
return True
return False | 574e2a78a07816f8b3b1d8e5523709eda1b680a1 | 590,505 |
def _add_comp_def(doc, comp_def):
"""Add the component definition while checking if it already existss
:param doc: The SBOL Document object
:param comp_def: Component definition
:type doc: Document
:type comp_def: ComponentDefinition
:rtype: ComponentDefinition
:return: The update... | c718de9c0c42fd88de2a4eddd6485f8ca02a3c4f | 590,506 |
import glob
def os_glob(in_dir):
"""
os_glob a given directory for all .py files and returns a list of source files.
"""
files = glob.glob(in_dir + "/**/*.py", recursive=True)
# remove .ipynb_checkpoints
files = [s for s in files if ".ipynb_checkpoints" not in s]
# print("os_glob files don... | 0f25271006f30ba39a8231d594c35d8f8393e1a7 | 590,512 |
from pathlib import Path
def get_input_filelist(data_path, glob_pattern=None):
"""
Return list of files in `data_path`
Parameters
----------
data_path: str
Directory path
glob_pattern: str
Glob the given pattern. To Glob recursively, add "**/" in front of the string
Retur... | 47ec00e8248d21c94b01fcade90a285c6ec86ba8 | 590,514 |
import random
def new_episode(client, carla_settings, position, vehicle_pair, pedestrian_pair, set_of_weathers):
"""
Start a CARLA new episode and generate a target to be pursued on this episode
Args:
client: the client connected to CARLA now
carla_settings: a carla settings object to be ... | d66c1c6409cf6413d4d5851f3f8fd1e510944a58 | 590,515 |
def _directed_neighbor_switch_rev(G, w, unsat, h_node_residual_in, chords,
h_partition_out, partition):
""" The reverse of directed_neighbor_switch.
Parameters
----------
G : networkx directed graph
graph within which the edge swap will take place.
w : inte... | 9490d43f4ce2f3969e80ad55c9c37b089c745bb6 | 590,518 |
import itertools
def complement_pairs(parent_set, include_self=False):
"""
Given a set, return the complement pairs of subsets
:param parent_set: a set of variables
:param include_self: whether to include (original set, empty set) in results
:return: pairs of complement subsets
"""
# use a... | fca7511e681adbb0661e279cda96f75a96d9ab47 | 590,519 |
import socket
def getservbyname(name):
"""Like socket.getservbyname() but return a ValueError with a descriptive
message if the ser4vice is not found."""
try:
port = socket.getservbyname(name)
except socket.error:
raise ValueError('unknown service: {0}'.format(name))
return port | 805d11b6efae065210c71d9ccd6a2eadb1d61809 | 590,524 |
def mconfig_get(defs, *args, default = {}):
"""Returns the value of the key supplied as *args in a config object.
This macro is normally used from within other macros defined in
*.bzl files, to retrieve the value from a dict, recursively.
Args:
*args: keys, used one after another.
default:... | 3a4c7897bba558c9aa8ad49e779db08d4cd4ae67 | 590,525 |
def get_count_of_increased_sequent(measurements) -> int:
"""
Count how many sequent increases are in a list of measurements
Args:
measurements (List[int]): list of measurements
Returns:
int: number of sequent increases
"""
if len(measurements) < 2:
ra... | 8f3cb2807a605036d1f2bf5d42693a90e1286372 | 590,527 |
def PyUnicode_Replace(space, w_str, w_substr, w_replstr, maxcount):
"""Replace at most maxcount occurrences of substr in str with replstr and
return the resulting Unicode object. maxcount == -1 means replace all
occurrences."""
return space.call_method(w_str, "replace", w_substr, w_replstr,
... | 53c3dd638275f8e5f049e441e0b844676f4ea3ca | 590,528 |
def get_rules(view):
"""Get auto-popup scope rule."""
rules = view.settings().get("color_helper.scan")
return rules if rules is not None and rules.get("enabled", False) else None | 1e04d93514785af0bb569c6b7ea7a8b2458c0175 | 590,529 |
def valid_post_data(data, required_keys):
"""
Return any missing required post key names.
"""
return [key for key in required_keys if key not in data] | f5cb39e93e61723dac9dd48e514c6130d6b8ac46 | 590,532 |
def _GetChannelIndicesInChannelDataIdList(id_list):
"""Returns a list of all the unique channel indices requested."""
channel_indices = []
for ch in id_list:
if ch.HasField('bipolar_channel'):
request_indices = [
ch.bipolar_channel.index, ch.bipolar_channel.referential_index
]
else:
... | 7ae29adfdb328cea35c5940ae091e5a84bf81995 | 590,534 |
def _group_proteins(proteins, peptides):
"""Group proteins when one's peptides are a subset of another's.
WARNING: This function directly modifies `peptides` for the sake of
memory.
Parameters
----------
proteins : dict[str, set of str]
A map of proteins to their peptides
peptides ... | 03f93be61c2b1ee88337f6a10653fd4de70990e5 | 590,535 |
def _start_end(**kwargs): # {{{
"""
Validate the position arguments. See DistLoad.__init_()
Returns:
Postition as a (start, end) tuple
Examples:
>>> _start_end(pos=(100, 200))
(100, 200)
>>> _start_end(start=100, end=200)
(100, 200)
"""
if "pos" in kwar... | 7293a8150af744cfe3b162db82b8606b97f4e100 | 590,539 |
import time
def _read_lines(raw_io):
"""Polls calls to `read()` on the given byte stream until some bytes are
returned, or the maximum number of attempts is reached.
:param raw_io: the byte stream to read from
:type raw_io: io.RawIOBase
:returns: the bytes read, decoded as UTF-8 and split into a ... | 521e6476f597f27169e7e6c326733cbf46791b1c | 590,540 |
import json
def jsonsplit(value, delimiter=",", type=str):
"""
Convert a string like a,b,c into a JSON array ["a", "b", "c"]
"""
return json.dumps([type(s.strip()) for s in value.split(delimiter)]) | ced1543757456c4ba9306aaf5372ac08410f79d7 | 590,544 |
def filepath(self, filename):
"""
Defines where files uploaded by the user should be stored
"""
return "users/" + self.user.username + "/" + filename | c3275a0820af2a8aee109c171984b3932f0e0a36 | 590,546 |
def get_protocol(url, default="http"):
"""
Extracts the protocol, or returns value of default param (defaults to http)
"""
double_slash = url.find("//")
if double_slash == -1:
protocol = default
else:
protocol = url[:url.find('//')]
if protocol.endswith(':'):
protocol = protocol[:-1]
if protocol == ... | d385ae97040744e2f2ffaea7d67c801d34098ae0 | 590,547 |
from datetime import datetime
def get_datetime(years_in_future=0):
"""Returns a DateTime object of today's date, years_in_the_future years in the future."""
return datetime.now().replace(year=datetime.now().year + years_in_future) | 70b26fcafddcd78571a1f6254258aefb9fa037d7 | 590,551 |
def query_header(ad, requested_input):
"""
Returns the header value associated with the 'requested_input'
string. The requested_input strings are defined in get_req_input_list(),
and they correspond to columns in the observation summary table.
:param ad: AstroData object that contains the header i... | 052db645e763f79c9b58aa5c305ef37bafb7b6d4 | 590,555 |
def calc_hov(da, lat1, lat2, dim='lat'):
"""Function to calculate Hovmoeller field
---------------------------------------------
Parameters:
da: xarray dataarray
lat1, lat2: (int) latitude band to use for averaging
dim: (str) dimension to average along
---------------------------------------... | ae85a1e5a3cc58fdda3015016fe5a540fb5b1f90 | 590,559 |
def query_task(query_function, project_id, local):
"""
Wrapper for query function for multithreading
:param query_function: query execute function
:param project_id: GCP project ID to scan
:param local: thread local variable
"""
return query_function(local.service, project_id) | e50f8f863d55c70af7ef5715c30ed46c1a0ac2d8 | 590,560 |
def handleLeftParen(root, nodeStack):
"""Create new left subtree and descend to it."""
root.insertLeft('')
nodeStack.push(root)
return root.getLeftChild() | 43db010b5eda845609d0c3ed7ffa1c1b485031cc | 590,561 |
def output(theta,final_list):
"""Function takes each point and returns the x,y,z coordinates in three lists.
Input: theta (for testing), final sides dictionary
Output: three lists of x,y,z
"""
#create 3 empty lists for the x,y,z coordinate values
x = list()
y = list()
z = list()
final_coordinates = []
#ite... | dd274de7fc14a4a9418418f0628d18931dea54be | 590,562 |
def ntp2ms(ntp: int) -> int:
"""Convert NTP time to milliseconds."""
return ((ntp >> 10) * 1000) >> 22 | c59e9a2c5b0a308e106ce5ce5705628d30c6127a | 590,563 |
import ctypes
def get_log(handle, log_fn):
"""Get logs from OpenGL.
:param handle: Handle for the associated object.
:param func log_fn: Function to call to get logs.
:returns: str
"""
c_buffer = ctypes.create_string_buffer(4096)
c_buffer_pointer = ctypes.cast(ctypes.pointer(c_buffer),
... | 8d76501bcc529f301a42bfd24b651aa7ccbabfef | 590,564 |
def wsgi_path_item(environ, name):
"""Extract the value of a named field in a URL.
Return None if the name is not present or there are no path items.
"""
# NOTE(cdent): For the time being we don't need to urldecode
# the value as the entire placement API has paths that accept no
# encoded value... | 4229b53af192c0fb2712350d0d093936768f9ce5 | 590,565 |
def convert_string_to_list(s):
"""
Converts string to list
:param s: Input string
"""
stl = s.split()
return stl | a8f5f03b5967b2e962b448e8a415b65adb4bb257 | 590,569 |
def NumToChar(number):
"""Converts a number to a one-character string containing a character with the ASCII code equal to the number."""
return chr(number) | 90a2e5700b58ef22fc3367fcc46d1fc39335b3f9 | 590,573 |
import torch
def iou_offset(offset_a: torch.Tensor,
offset_b: torch.Tensor,
eps: float = 1e-8
) -> torch.Tensor:
"""Compute IoU offsets between multiple offset pairs.
:param offset_a: Offsets of N positions. Sized [N, 2].
:param offset_b: Offsets of N position... | 79f9c35cde3853cbce253d8e3366db9273e4d80a | 590,576 |
def sorted_items(params): #93 (line num in coconut source)
"""Return an iterator of the dict's items sorted by its keys.""" #94 (line num in coconut source)
return sorted(params.items()) | b33ea1d86104e24523e14e05adef8a345ff2033d | 590,582 |
def _convert_java_pattern_to_python(pattern):
"""Convert a replacement pattern from the Java-style `$5` to the Python-style `\\5`."""
s = list(pattern)
i = 0
while i < len(s) - 1:
c = s[i]
if c == '$' and s[i + 1] in '0123456789':
s[i] = '\\'
elif c == '\\' and s[i + 1] == '$':
s[i] = ... | fe8c680bdad6e16cbbd5273297de3eaf4cbf8b68 | 590,584 |
def factor_transforms(transforms):
"""
Factor a list of transform tuples into a list of sort keys and a dict of
transforms
Parameters
----------
transforms : list of tuple
The transforms to factor
Returns
-------
sort_keys : list of str
The names of... | 9af24e6d858dc73376e049fa6f7a8b6ad2b3d8c9 | 590,588 |
import math
def plan_plot_grid(n_plots: int) -> tuple:
"""find optimal placement (rows, cols) for given number of plots to place
=> min{rows - cols} s.t. cols^2 <= n_plots <= rows^2 and cols * rows >= n_plots
:param n_plots: number of plots to place
:return: optimal (rows, cols)
"""
rows = m... | b2553cc3256ce848a829ab98ac1fa2b113f7d04d | 590,590 |
def identity(x):
"""Return its argument"""
return x | eaf1c643784540bf4f2c6716c3530412e05abf21 | 590,592 |
from typing import Dict
import math
def generate_good_id_to_name(nb_goods: int) -> Dict[str, str]:
"""
Generate ids for things.
:param nb_goods: the number of things.
:return: a dictionary mapping goods' ids to names.
"""
max_number_of_digits = math.ceil(math.log10(nb_goods))
string_forma... | 796f2081963a9565a07ac6bdd456190f464e1b0c | 590,595 |
import random
def random_int(low=0, high=2**31 - 1):
"""
Helper function that generates a random integer between two values (inclusive).
"""
return random.randint(low, high) | 6d03ede21e2a01bf5a364dd1c82cf68742485fe4 | 590,596 |
def count_words (val):
""" Counts the number of words in a string.
A word is defined as a sequence of one or more letters separated by one or more non-letter characters.
Args:
val (str): The string to count words in.
Returns:
int: The number of words in the string.
"""
current... | 6e474fd0549f7038ba0c3f9083076616b9a7e712 | 590,599 |
def group_records(G, class_label, cutoff=0):
""" Parse node attributes into group records
Args:
G: graph
class_label: class label
Returns:
records: list of dict [{class: name, members: list of index,]
"""
groups = {}
for n, node in G.nodes_iter(data=True):
c = n... | 9387019ee60a3cd4fed60809070994d1e36fb00b | 590,600 |
def summarize_mutation_io(name, type, required=False):
"""
This function returns the standard summary for mutations inputs
and outputs
"""
return dict(
name=name,
type=type,
required=required
) | 79a3b8b8394b7b25fbf3df09c989b8aca985ad2b | 590,606 |
def _get_versions(json_entry):
"""
Return version labels ranked from the most recent to the earliest one
"""
versions = []
if "versions" in json_entry:
for version in json_entry["versions"]:
# time indicated by "created" attribute
versions.insert(0, version["version"]... | 8967e6bc785e42c13770b6e1046a27a538548e3f | 590,613 |
def get_readme_description(head_string: str) -> str:
"""
Parse the head of README and get description.
:param head_string: A string containing title, description and images.
:return: Stripped description string.
"""
# Split title section and rule out empty lines.
parts = list(filter(bool, h... | a37d01565461b028874ca725f0473f87470b8816 | 590,617 |
import json
def read_input(input_file: str) -> str:
"""
Helper function for reading JSON contents from a file.
:param input_file: path to JSON file containing input
:return: `string` representing JSON input from given file
"""
with open(input_file, 'r') as f:
json_input = f.read()
... | 3f04ba274c38b0dfa33b12484acae6ba2d787a96 | 590,620 |
def random_walk(game):
"""
Solves MasterMind by throwing out random codes.
On average takes about 5 time n guesses, where n
is the number of possible solutions of the Mastermind Game.
For 6\ :sup:`4`, this means about 6000 guesses.
Returns the solution translated back into t... | e108c821abf6ba54400c5170d006bd2948d5f7cd | 590,624 |
def _chunk_iterable(_iterable, chunk_size):
"""Split an iterable into chunk_sized parts"""
chunks = [_iterable[index:index + chunk_size] for index in range(0, len(_iterable), chunk_size)]
return chunks | 9b27d61072038fc1a5c97e01fbd389b690c9eb8f | 590,625 |
def diplay_img_info(img, divisor, use_RGB):
""" This function displays the information of the image dimensions as a print"""
nr_z_slices = img.shape[1]
nr_timepoints = img.shape[0]
x_dim = img.shape[-2]
y_dim = img.shape[-2]
x_div = x_dim//divisor
y_div = y_dim//divisor
print(img.shape)... | 19119f7bcfcaa6e17ef3fedba76793dd05ac3f77 | 590,626 |
def _insert_space(end_index, string):
"""Inserts the number of spaces required given the string and the position
of the next non-blank field.
Parameters:
end_index : int
Expected string length
string : str
String to add spaces to
Returns:
string_with_blan... | ac916d1639b9e78c4729d8a65ccdcbed6a2a61f8 | 590,631 |
def get_bram36_site(db, grid, tile):
""" Return the BRAM36 prjxray.tile.Site object for the given BRAM tile. """
gridinfo = grid.gridinfo_at_tilename(tile)
tile_type = db.get_tile_type(gridinfo.tile_type)
sites = tile_type.get_instance_sites(gridinfo)
for site in sites:
if site.type == 'RAM... | b97be3b04b5f3c06fcd923bf1bf734c6b9554336 | 590,632 |
def loadAnimes(jikan):
"""Gets the top x animes from my anime list and returns a list that contains these"""
"""This is a naive way of loading"""
animes = []
# 7 x 50 = 350
for i in range(7):
# This gets a single page of top anime
data = jikan.top(type='anime', page=i, subtype='tv... | 02901dd204261ee25c3c258c2e485923de788fe8 | 590,634 |
def has_replication_policy(sysmeta_pyxb):
"""Check if SystemMetadata has ReplicationPolicy section.
Args:
sysmeta_pyxb: SystemMetadata PyXB object
Returns: bool
``True`` if SystemMetadata includes the optional ReplicationPolicy section.
"""
return bool(getattr(sysmeta_pyxb, "repli... | 870e1abed4905842d13ddef6e8fd26729dc762b7 | 590,637 |
def create_box_marker_msg(id, pose, dims=(0.7,0.7,2.0), color=(0,0,1,0.1), duration=0.4):
""" Creates a box marker message to be passed to the simulator.
Args:
id (int): Identifier for the box marker.
pose (list): Pose of the box [x, y, z, roll, pitch, yaw]
dims (list): ... | 66c8cccf35b68b5d4e5f0ae36dd9d0abbdae39c6 | 590,643 |
def yesno(question, default="n"):
""" Asks the user for YES or NO, always case insensitive.
Returns True for YES and False for NO.
"""
prompt = "%s (y/[n]) " % question
ans = input(prompt).strip().lower()
if not ans:
ans = default
if ans == "y":
return True
return ... | 2d7e1054246daa5ab8cf5344b9d2530afb5dedd3 | 590,645 |
def get_char(value):
"""Get the Unicode char."""
return chr(value) | 8e7037a3e0fdf2ef3e634d68efb9d9b3260dd534 | 590,647 |
def labware_id() -> str:
"""Get a labware id."""
return "some_labware_id" | 8c31f01a31388bc26aabf98f1a591b53543955e2 | 590,651 |
import inspect
def issequence(obj):
"""
Test if an object is an iterable generator, list or tuple.
Parameters
----------
obj : object
object to test
Returns
-------
bool :
True if :code:`obj` is a tuple, list or generator only.
Examples
--------
>>> isseq... | 18d8bc2215f92d2bed0c9b963d63154cc5de6f6f | 590,652 |
def listToStr(list, seperator=" "):
""" Return a string consists of elements in list seperated by
seperator.
"""
return seperator.join(map(str,list)) | 68d1dd5a1ee04b8e490e8fd54d433fd652215f6d | 590,657 |
import torch
def unflatten_parameters(params, example, device):
""" Unflatten parameters.
:args params: parameters as a single 1D np array
:args example: generator of parameters (as returned by module.parameters()),
used to reshape params
:args device: where to store unflattened parameters
... | eb5dbb2606dd52e0b0e3a53f369fab1faa56e1c6 | 590,659 |
import re
def clean_spaces(s):
"""Reduce all whitespaces to one space"""
s = re.sub(r'\s+', ' ', s)
return s | 566451e443b843b8228e6702dc61b0c202b38008 | 590,660 |
def gravitational_force(M, m, r, G = 6.674 * ( 10 ** - 11 ) ) :
"""
Calculates the gravitational_force when given Mass of object1 = M, Mass of object2 = m, Distance
between center of masses = r and Gravitational constant = G
Parameters
----------
M : float
m : float
... | f72431f628e12a95a54908551b58a82cc8bddcda | 590,661 |
def fibonacci(index):
"""
Recursive function that calculates Fibonacci sequence.
:param index: the n-th element of Fibonacci sequence to calculate.
:return: n-th element of Fibonacci sequence.
"""
if index <= 1:
return index
return fibonacci(index - 1) + fibonacci(index - 2) | 899ff4c80448e6c0b60f93fe0b670a85ea22b7a3 | 590,668 |
def bit(m, off):
"""
Returns the value of a bit at offset off in integer m.
"""
if m & (1 << off):
return 1
else:
return 0 | 820bfb28deb9d6aadcea30b6ea1d15f91f5a43f9 | 590,674 |
def check_port(port):
"""
Check whether the port is valid or not.
Args:
port (str): Port to check
Raises:
None
Returns:
bool: True if valid, else False
"""
if (int(port) >= 0 and
int(port) < 65536):
return True
else:
return False | 95e04a46d27c34ae34e006b6b15e2da3c94db9da | 590,677 |
def wrap(func, *args, **kwargs):
"""Wrap a callable as a task. Yield the boolean of its result.
"""
def initTask(**initkwargs):
def makeIterator(**runkwargs):
result = func(*args, **kwargs)
yield bool(result)
try: makeIterator.__name__ = func.__name__
except A... | b2ea88cf81ba68aef3a4e0c7d2fa61da7658666d | 590,678 |
from typing import List
def _extract_label_from_groups(groups: List[str], max_label_index: int) -> str:
"""Derives a label from the groups
:param groups: the groups an identifier is divided into.
:param max_label_index: after splitting the identifier into groups, if positive, this is the maximum amount o... | 6d63a62d87099828827237347ffc1b19f32a9f5a | 590,680 |
import hashlib
def hash_file(filename):
""" Return length-64 hexadecimal SHA256 hash of file with given filename. """
h = hashlib.sha256()
with open(filename, "rb") as f:
h.update(f.read(2**20))
return h.hexdigest() | b84b739913455889d9dc7c405d99577d59d1fbf2 | 590,683 |
def name_is_global(name: str) -> bool:
"""Determines whether a given name is global."""
return name.startswith("/") | 1b0c0854d5d2da25f283cfecf498cdbc3d0e6a79 | 590,684 |
def initialize_2d_board(num_rows, num_cols):
"""
Initializes a 2D board with 0s.
Parameters:
num_rows (int): number of rows
num_cols (int): number of columns
Returns: a 2D board of size num_rows * num_cols
"""
return [[0 for c in range(num_cols)] for r in range(num_rows)] | ab233465866d65bab28a185df4859ed738ce1a7e | 590,686 |
def EnablePrecompile(env, target_name):
"""Enable use of precompiled headers for target_name.
Args:
env: The environment.
target_name: Name of component.
Returns:
The pch .obj file.
"""
if env.Bit('use_precompiled_headers'):
# We enable all warnings on all levels. The goal is to fix the code... | 576cefb85a055cf5e99bb1052d8035b32f37abdc | 590,688 |
def build_result_and_recon_output(result_form):
"""Build dict of data from a result form and add reconciliation information
if it has a reconciliation form.
:param result_form: The result form to build data for.
:returns: A dict of information about this result form.
"""
output = {
'ba... | 41c036e1bfc0c87f0d2e5665edf1193d43dfa6de | 590,690 |
def unique(content):
"""Takes an iter and find the unique elements and return the simplified iter
:param content: iter
Any iter that can be converted to a set
:returns: iter
an iter of same type but with only unique elements
"""
the_type = type(content)
retur... | d0e8dcdf64874e401478edba8735a3f68a1cc5c9 | 590,695 |
def _prompt_from_message(message: str | None = None, default: str | None = None) -> str:
"""Returns an input prompt."""
if not message:
return ''
prompt_parts = [message]
if default is not None:
prompt_parts.append(f' (default "{default}")')
prompt_parts.append(': ')
return '... | ed73bd3efbbeaf5dc8f9d5405ddf5f56a57740ea | 590,696 |
def meter2centimeter(dist):
""" Function that converts m to cm. """
return dist * 100 | b5db785532e4a677a2726b4502b5192cb73ba7f8 | 590,697 |
def is_longitude(coord):
"""
Determines if a coordinate is longitude.
:param coord: coordinate of xarray dataset e.g. coord = ds.coords[coord_id]
:return: (bool) True if the coordinate is longitude.
"""
if "longitude" in coord.cf and coord.cf["longitude"].name == coord.name:
return True... | 6a7c4d32907df7587229eadff43f876c931352d3 | 590,711 |
def as_uncertainty_dict(value):
"""Given either a number or a ``stats_arrays`` uncertainty dict, return an uncertainty dict"""
if isinstance(value, dict):
return value
try:
return {"amount": float(value)}
except:
raise TypeError(
"Value must be either an uncertainty d... | faaf764f133b246a45cf68ab579e9adcc365864f | 590,713 |
def get_unique_envs(envs):
"""extract all unique envs from envs dict"""
result = set()
for v in envs.values():
result.update(v.keys())
#sort envs for convenience in testing and display
return sorted(result), len(result) | 08e08254b83b3134e081a6ce2878b72fde783aec | 590,714 |
def recursive_search(linkedlist, data):
"""Search 'linkedlist' recursively for a node containing 'data'.
If there is no such node in the list, or if the list is empty,
raise a ValueError.
Inputs:
linkedlist (SinglyLinkedList): a linked list.
data: the data to search for in the list.
... | 2b987fec77341682fddf5b188940279be15577ad | 590,717 |
from typing import List
from warnings import warn
import json
def keyboard_gen(pattern: List[List[dict]], one_time: bool = False, inline: bool = False):
""" Simple keyboard generator
:param pattern: Keyboard simple pattern, check github readme
:param one_time: Should keyboard be hidden after first use?
... | ea6780799a2b8976954fbe444450c8bf4802f3d2 | 590,719 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.