content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
def disjunction_for_group(lines: List[str]) -> int:
"""
Returns the number of questions one group answered "yes" to,
given the lines of input for that group.
"""
assert all(line.isalpha() for line in lines)
return len(set(c for c in "".join(lines))) | d83ab53da86e67e98448d3f5d99cf4174bb62204 | 634,910 |
def computeLastHitValues(blocks):
"""
given the query length and 'blacks' sting from a last hit
return the:
match length
the blocks string looks something like this:
"73,0:1,15,0:1,13,0:1,9"
where integer elements indicate lenghts of matches and
colon separated elements ... | 7223e9d79a6cda29603d662d0c35f099ec11cdf2 | 634,914 |
import itertools
def product(l1, l2):
""" Returns all possible combinations of entries in two arrays
Args:
l1 -- list<str>
l2 -- list<str>
Returns:
iterable
"""
return itertools.product(l1, l2) | b7bd8e67f52cf95c0fd4d489597be5fa83bcad3d | 634,919 |
def boolean(value: str) -> bool:
"""Convert a "human" boolean (Y, Yes, True, ...) to a Python boolean,
raising a ValueError if it can't be converted.
"""
if value.lower() not in {"y", "yes", "n", "no", "true", "false"}:
raise ValueError('Please enter either "y" or "n".')
return value.lower()... | 8c4bb974a28ca166c5257929658d582457b7fffa | 634,920 |
from typing import List
def get_range(min_max: List[int]) -> range:
"""Returns a range with the turtles min max choices.
If the input is None then range(-25, 26) is returned.
Parameters
----------
min_max : List[int]
Returns
-------
min_max : range
"""
if min_max is None:
... | c446656d7b41ae9c87bb57a5b7cb1a695ac5e68d | 634,922 |
def split_list(ls, num):
"""
拆分list
:param ls: 带截取的列表 [0, 1, 2, 3, 4, 5, 6]
:param num: 除最后一个列表之外其他列表长度 3
:return: 所有拆分的列表 [[0, 1, 2], [3, 4, 5], [6]]
"""
a = len(ls)
if a <= num:
return [ls]
quotient = a // num # 商
remainder = a % num # 余数
res_split = []
for i ... | a903e03b38af905f59c6deaf41f4089090146f27 | 634,923 |
import torch
def impute(x, lengths, channels_last=True):
""" Set elements of a batch of a sequence of tensors to zero according to sequence lengths.
:param x: A tensor with shape [batch, time_step, ...] or [batch, ..., time_step]
:param lengths: A tensor with shape [batch]
:param channels_last: A bool... | b1f6fa73a0ce68b726c17fd2a533c2fc41651f12 | 634,924 |
def parse_header(header):
"""Parses the FASTQ header as specified by CASAVA 1.8.2 and returns the fields in a dictionary
@<instrument>:<run number>:<flowcell ID>:<lane>:<tile>:<x-pos>:<y-pos> <read>:<is filtered>:<control number>:<index sequence>
"""
if header[0] != '@':
return None
... | d533f9af13f6b9745757e11125612aafb8c8ec7d | 634,925 |
import math
def pixel_coords_to_tile_address(x,y):
"""Create a tile address from pixel coordinates of point within tile."""
x = int(math.floor(x / 256))
y = int(math.floor(y / 256))
return (x, y) | 774015a77f324abf35e95c4ccc849bd1858f2b59 | 634,926 |
def dict_to_string(m: dict) -> dict:
"""Convert dict values to strings
Parameters
----------
m : dict
Returns
-------
dict
"""
for k, v in m.items():
if isinstance(v, dict):
m[k] = dict_to_string(v)
else:
m[k] = str(v)
return m | 15fc73e47b49c6a39beb7a363d6952fce2b4398e | 634,927 |
def bmi_classify(bmi, format="json"):
"""Helper function to get "BMI Category" and "Health Risk" from the bmi number
Args:
bmi (int): BMI of the concerned person
format (str, optional): Json when for `native loop` method and anything else for `numpy` method. Defaults to "json".
"""
if b... | a5784da836f51a23d26e26a74d2fc6d0686a64cb | 634,930 |
def _str_to_bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueError('Need bool; got %r' % s)
return {'true': True, 'false': False}[s.lower()] | 9c4e8e9aff7b885f74ed632788b0ce0426e8265c | 634,932 |
def _explode_full_table_names(in_tables):
"""
Takes a list of schema-qualified names and creates a schema-key, table_list-value dict
:param in_tables: A list of schema-qualified table/view names
:return: schema-key, table_list-value dict
"""
schema_to_table = dict()
for t in set(in_... | 6f67d28fd51d8ea4c9aa08231c8d50232206d427 | 634,933 |
def get_file_name_from_url(url: str) -> str:
"""Get the last part of an URL."""
return url.rsplit('/', 1)[1] | d7647df3d686ef1e72e3c55c413c3c3a1be346fc | 634,939 |
def PrintMenu() -> int:
"""
Prints in console the menu of the app.
"""
option = 0
print("Select an option from the ones below")
print("1 - Simple Permutation.\n2 - Simple Variation.\n3 - Simple Combination.")
print("4 - Compound Permutation.\n5 - Compound Variation.\n6 - Compound Combination... | 65d066d8cf1cdaa68e57e395445366c15109e685 | 634,942 |
def class_name(cls):
"""Return a string representing the class"""
return cls.__name__.replace('.', '_') | eac9db2409831d60d11abde9092ca063bf568055 | 634,944 |
from typing import List
import math
def get_minimum_subintervals_set_math(intvl_upper_limit: int, range_length: int = 1) -> List[int]:
"""
Method that returns the minimal set of placements that cover the full interval. This method uses
the mathematical expresion that minimizes the number of points, howeve... | e4329c35eb93281e14b082f99ffb9d5ce71e6cdb | 634,946 |
import json
def resolve_json(text, resolver, recursive=True, fill_empty='{}'):
"""
Given a JSON Schema containing `$ref` keys, replace all
referenced URI values with their values using trimesh
Resolver objects.
Parameters
---------------
text : str
JSON text including `$ref` to othe... | 2af30642ac7d3f200498c72783c0f95590b52edc | 634,951 |
import torch
def unpack_episode(episode):
""" Helper function that extracts samples and labels from an episode in numpy
Args:
episode: the episode to unpack
"""
examples = torch.cat([episode["support_images"], episode["query_images"]], 1).numpy()
labels = torch.cat([episode["support_class_... | 1326228e3433dc4eb7cfa0c50256468d02a05b64 | 634,952 |
def get_path_from_source(source_path):
"""
Get file path from source
Args:
source_path (str): relative module path e.g. this.module.Class
"""
file_path = "/".join(source_path.split('.')[:-1]) + '.py'
return file_path | f429e1530c11b942c75ae34374a1d92da88a093a | 634,953 |
def name_to_crate_name(name):
"""Converts a build target's name into the name of its associated crate.
Crate names cannot contain certain characters, such as -, which are allowed
in build target names. All illegal characters will be converted to
underscores.
This is a similar conversion as that wh... | 8550686e5678e4cf7a720dbff1d1bf137317cd96 | 634,954 |
from typing import List
def _extract_docstring_path_specification_comment_from_line(
*, line: str, matches: List[str]) -> str:
"""
Extract a docstring path specification comment
from a specified markdown line text.
Parameters
----------
line : str
Target markdown line text.
... | af9599eb2700279669b32bd09f5ea74d374efde0 | 634,960 |
def _arg_no_mixin(num):
"""Return FindArgNoMixin for num."""
class FindArgNoMixin(object): # suppress(too-few-public-methods)
"""Mixin that provides generate() for finding args by number."""
def generate(self, # suppress(no-self-use)
sub,
other_transf... | f918a05183f265750490e62303173525134eb3ca | 634,961 |
from typing import List
def domains_check(domains: List[str]) -> List[str]:
"""
all input domains should have the same primary,
e.g.
* `example.com`, `a.example.com` are valid
* `example.com`, `a.example1.com` are invalid
* `domains=["a.x.com", "b.x.com"]` will be converted to
`["x.c... | 0815abdb01e531352b75492e5d260792e0496a71 | 634,962 |
def generate_report_name(sim_type, talent_string, covenant_string):
"""create report name based on talents and covenant"""
stripped_talents = talent_string.strip("_")
stripped_covenant = covenant_string.strip("_")
talents = f" - {stripped_talents}" if talent_string else ""
covenant = f" - {stripped_... | 4cd1b861a54c6e570174757f3a5b72a6d6b31775 | 634,964 |
def next_minute(dt):
"""
The next minute (as a datetime) for the given date time
:param dt: the date time
:return: the next minute (as a datetime)
"""
return dt.replace(minute=dt.minute + 1) | 624d772b729671668c5c91396f8c4341409fdce3 | 634,970 |
def get_pl_name(name, steps, counter=1):
"""Add a counter to a pipeline name if already in steps."""
og_name = name
while name.lower() in [elem[0] for elem in steps]:
counter += 1
name = og_name + str(counter)
return name.lower() | 09a1efe6dfdae00a7b158d12455c51b671a86cf4 | 634,971 |
def IsCoverageBuild(env):
"""Returns true if this is a coverage build.
Args:
env: The environment.
Returns:
whether this is a coverage build.
"""
return 'coverage' in env.subst('$BUILD_TYPE') | 9742599d8173812f2d995d801dd6a03688941934 | 634,975 |
import json
def get_json(response):
"""Get JSON from response."""
return json.loads(response.get_data(as_text=True)) | 27f71e963b8352e3e796dee913da53007c6c6d62 | 634,978 |
def get_pdos_generator_inputs(fixture_code, generate_structure):
"""Generate a set of default inputs for the ``PdosWorkChain.get_builder_from_protocol()`` method."""
return {
'pw_code': fixture_code('quantumespresso.pw'),
'dos_code': fixture_code('quantumespresso.dos'),
'projwfc_code': f... | bf553b2694372f9894dabb999e941b6d718b928c | 634,981 |
def opcode_4nnn(self, x, nn) -> int:
"""4XNN Skip the following instruction if the value of register VX is not equal to NN"""
return self.pc + (4 if self.v[x] != nn else 2) | c0283caa90f42855b6910a577e4826649492d084 | 634,982 |
def is_degenerate(sides):
"""
Check to see if a triangle is 'degenerate'.
:param sides: list[*int] - the length of the three sides of a triangle
:return bool - whether a triangle is degenerate or not
>>> is_degenerate([1, 2, 3])
True
>>> is_degenerate([4, 5, 6])
False
The sum of ... | 821639338a55aafc5900db7e7ac259272dee5b39 | 634,983 |
def _both_names(meta, to_prom_name):
"""If the pathname differs from the promoted name, return a string with
both names. Otherwise, just return the pathname.
"""
name = meta['pathname']
pname = to_prom_name[name]
if name == pname:
return "'%s'" % name
else:
return "'%s' (%s)"... | 4c12092bd2dcafe69e58b99d9da0609406d9b0f0 | 634,986 |
def string_7bit(string):
"""Strip hte highest bit of evey character in string"""
s = ""
for c in string: s += chr(ord(c) & 0x7f)
return s | 4ac00bc6d5e170191df775e34dff9fc31c565f12 | 634,991 |
import yaml
def parse_config(config_file: str) -> dict:
""" Parses yaml config file (if indicated)
:param str config_file: config file path
:return: configuration dictionary
"""
if config_file is None:
return {}
with open(config_file) as f:
return yaml.safe_load(f) | ec2dd4e5685563ea6ec0ce4ce7cb465fc49bafc3 | 634,992 |
def get_test_data_rdd(sc, X_test_path):
"""
sc: type sparckContext
X_test_path: type str, the path for the X_test data document, which contains the hash codes
return: type rdd, a rdd where each record contains a document content and its zipped index in ascendind order (the zipped index will be used for ... | 5e666b94e4df755533d3407f7637f46cd7b9a039 | 634,993 |
import re
def test(pattern, string):
"""Determines whether a given string matches a given regular expression"""
return bool(re.search(pattern, string)) | 5f04cff018207643c38c3a04d69cf9f949feaddb | 634,997 |
import binascii
def is_gzip_file(f):
"""
This is an elegant solution to test whether a file is gzipped by reading the first two characters.
I also use a version of this in fastq_pair if you want a C version :)
See https://stackoverflow.com/questions/3703276/how-to-tell-if-a-file-is-gzip-compressed for... | ef1d289960bab6e0f6c534b0cae636e5f98e54c1 | 635,004 |
import click
def progress_func(func, char='*'):
"""Use to wrap functions called in parallel. Prints a character for
each function call.
:param lambda-function func: A 'lambda wrapped' function to call
after printing a progress character
:param str char: The character (or multi-char string, if you
... | 6c1b62ec2485bbad8dfcd110a41ccc52f8dcfc70 | 635,007 |
def vec_print_str(tv, pdvars):
"""
This returns a string that will be used to print a line of code. If the
variable tv has not yet been used before, then the declaration of this
variable must be included in the string. pdvars is the list of variables
that have been previously defined.
tv: ... | a45ae337520ef0a21c2eee51ecff281bb76e614e | 635,013 |
import time
def format_duration(t0):
"""
Adapted from @john-fouhy:
https://stackoverflow.com/questions/538666/python-format-timedelta-to-string
"""
duration = time.time() - t0
hours, remainder = divmod(duration, 3600)
minutes, seconds = divmod(remainder, 60)
return "{:02}:{:02}:{:02}".... | 47eaf71e3067798e386f8380e3d69c84a15c6002 | 635,015 |
def channel_name_mapping(name_str):
"""
Turns a string like '1:foo,2:bar' into the dict
{1: 'foo', 2: 'bar'}
May raise an exception if the string doens't follow this format.
Returns {} for an empty string.
"""
mapping_strs = str(name_str).split(',')
str_pairs = [m.split(':') for m in map... | 89bd1235cc2a692f841c90f59bb9bfc7fb2cc22e | 635,022 |
def calc_thick_spherical_lens(n, roc1, roc2, d, ne=1):
"""Calculate the properties of a thick spherical lens.
Positive radius of curvature means center is further along the direction of travel. For a biconvex positive lens,
roc1>0, roc2<0. The principal plane distances are from the vertex to the principal... | 307fc47b813f5b3aeeda838c7c51c9ec3171589a | 635,024 |
def nint(a):
"""return the nearest integer to a."""
i = int(a)
if a > 0:
if a - i > 0.5:
i += 1
elif a < 0:
if a - i < -0.5:
i -= 1
return i | 0f22e2872b830dec76393096485ec957a819313c | 635,025 |
def example_group_indices(data, attr, values):
""" Return lists of indices into `data` for each `values` item that matches
the example value at `attr` attribute
Example::
cls_ind1, cls_ind2 = example_group_indices(data, data.domain.classVar, ["Class 1", "Class 2"])
"""
ret = [[] for _ i... | 0a824abd0b94f32762b465dee1d94a87af390c10 | 635,026 |
def longest_common_prefix(strings):
"""
Find the longest common prefix of a list of 2 or more strings.
Args:
strings (collection): at least 2 strings.
Returns:
string: The longest string that all submitted strings start with.
>>> longest_common_prefix(["abcd", "abce"])
'abc'
... | 65924132f44fd3e7affef58f9d172254336e3b76 | 635,027 |
def r_to_rq(r):
"""
reduced coordinate inverse:
(1+rq)
r = ------
(1-rq)
Hernquist & Ostriker 1992 eq. 2.16
"""
return (r-1.0)/(r+1.0); | 72aa09c6395b7a62575883b9cbadfbb21f530635 | 635,030 |
def flicker_amplitude_to_frequency(flicker_amplitude : float) -> float:
"""
Converts the flicker amplitude to the first filter frequency according to Kallinger et al. (2016)
:param flicker_amplitude: Flicker amplitude calculated according to Bastien et. al (2013)
:return: First filter frequency
"""
... | 772bb939b78b1ab2092a20764bd9c46c19873295 | 635,033 |
import six
def is_primitive(val):
"""
Checks if the passed value is a primitive type.
>>> is_primitive(1)
True
>>> is_primitive("abc")
True
>>> is_primitive(True)
True
>>> is_primitive({})
False
>>> is_primitive([])
False
>>> is_primitive(set([]))
:param ... | da3c0adc341a406719b786a487b0e1baad037657 | 635,035 |
import math
def get_distance(c1, c2):
""" Returns approximate distance between two pairs of coordinates in km.
Args:
c1: coordinate pair 1
c2: coordinate pair 2
Returns:
distance in km between c1 and c2
"""
# approximate radius of earth in km
R = 6373.0
lat1 = ma... | 1cc9b8933b56944df12ae842780386d35d9f984d | 635,036 |
def dbt_project_dir(tmp_path_factory):
"""A temporary directory to store dbt test files."""
d = tmp_path_factory.mktemp("project")
return d | a40c36c3236132f203f8ee263c9e3b4fc4a51cee | 635,039 |
def GetCbsdRegistrationRequest(cbsd):
"""Returns a CBSD registration request from the |Cbsd| object.
"""
return {
'cbsdCategory': cbsd.category,
'installationParam': {
'latitude': cbsd.latitude,
'longitude': cbsd.longitude,
'height': cbsd.height_agl,
'heightType... | 2720960f20e9eb792f0cc4dc5564c85a5dd69743 | 635,041 |
def states_bedline_to_vector(bedlines, states_dic):
"""
Convert a line from a bedfile containing states in categorical data to vector format.
Parameters
----------
bedline: [string,...]
A line form a bedfile broken up into its contituent parts
(e.g. ["chr1", "1000", "2000", "state"... | 1d95c73b09ac98290ffe4c84037d4ef2a5e0d85c | 635,042 |
import re
def is_valid_volume_id(volume_id):
"""
Validates drive and volume IDs, also known as the drive/volume "name".
A valid volume name should look like: volume-00000001 - It should always
start with "volume-" and end with 8 hexadecimal characters in lower case.
:type volume_id: str
:para... | 272f2ba61b1974da323fa31fe72ebb093056a424 | 635,043 |
def Not(query):
"""The negation of a query"""
return '(NOT %s)' % (query,) | 9bddebbd3c3c8e4c2e8e74b6c87049f0e4706dcb | 635,044 |
def lerp(xvar, xlim, ylim):
"""linearly interpolate a value of y given ranges for x, y.
arguments:
xvar: scalar
xlim: array with xmin, xmax
ylim: array with ymin, ymax
"""
delta_x = (xvar - xlim[0])
slope = ((ylim[1] - ylim[0]) / (xlim[1] - xlim[0]))
yvar = ylim[0] +... | a637d415555e80abf46b69d216d1acc63d4ed5ee | 635,045 |
def incidentlist(xml):
"""
Takes the full incident XML and returns a list of dictionaries with 'agency code' and 'incident number' tag and
text elements.
"""
i_list = []
for i in xml.iter('Incident'):
i_dict = dict()
i_dict['agency_code'] = i[2].text
i_dict['incident_numb... | 352f8291c509a5071bce93b01cd089626018f9c0 | 635,046 |
def fitAngleToBaxter(angle):
"""
Returns an angle fitted to use with Baxter.
Parameters
----------
angle (float): Angle to convert.
Returns
-------
new_angle (float): Angle transformed into Baxter's yaw.
"""
new_angle = -90.0 + angle if angle <= 90.0 else -180.0 + (angle - 90.... | 95e823ef9adb822b74b753fb8d4e55297f0631b4 | 635,049 |
def combine_adjacent(arr):
"""Sum like signed adjacent elements
arr : starting array
Returns
-------
output: new summed array
indexes: indexes indicating the first
element summed for each group in arr
"""
output, indexes = [], []
curr_i = 0
while len(arr) > 0:
... | 46638cc7f52df03c117d0ba6e300d9c3b5449431 | 635,052 |
def gen_all_strings(word):
"""
Generate all strings that can be composed from the letters in word
in any order.
Returns a list of all strings that can be formed from the letters
in word.
This function should be recursive.
"""
if len(word) == 0:
return [""]
else:
res... | 715d8bbdc0348daec08d302be244971d8f6f25de | 635,053 |
def get_str_from_params(params: dict):
""" Returns string from the parameters """
result = list()
keys = list(params.keys())
length = len(keys)
result.append("%s=%s" % (keys[0], params[keys[0]]))
for i in range(1, length):
result.append(":%s=%s" % (keys[i], params[keys[i]]))
return... | d4a169b61174ecd42a71eb9f1d540670bf780878 | 635,054 |
def get_tokens(tagger, content):
"""
文書内に出現した名詞のリストを取得する関数。
"""
tokens = [] # この記事で出現した名詞を格納するリスト。
node = tagger.parseToNode(content)
while node:
# node.featureはカンマで区切られた文字列なので、split()で分割して
# 最初の2項目をcategoryとsub_categoryに代入する。
category, sub_category = node.feature.spli... | fa43ddaf6cb554e437a80664ed713a348653db06 | 635,059 |
def sort_points_by_Y(list_of_points):
"""Given a list of 2D points (represented as Point objects), uses "sorted"
with the "key" argument to create and return a list of the SAME (not copied)
points sorted in decreasing order based on their Y coordinates, without
modifying the original list."""
return... | cc4a67b839d3e0ae1793e8cde9c17113022c7266 | 635,060 |
def tokens_to_index(token_list, vocab_dict):
"""
convert word tokens to number index
INPUT:
token_list: a list of string tokens
vocab_dict: a dictionary with tokens(key)-integer(value) pairs
OUTPUT:
index_list: a list of integer indices
"""
index_list = []
for x in t... | 1692858ea21bed7812c92db9cb09eb4e9a6a3641 | 635,061 |
from typing import Union
def _(value: Union[bytes, bytearray]) -> bytes:
"""Convert ``bytes`` or ``bytearray`` to bytes"""
return value | d595fe96c27f8ef58677935c80879ff8ebc2fc24 | 635,065 |
import sympy
import six
import random
def _split_factors(integer):
"""Randomly factors integer into product of two integers."""
assert integer.is_Integer
if integer == 0:
return [1, 0]
# Gives dict of form {factor: multiplicity}
factors = sympy.factorint(integer)
left = sympy.Integer(1)
right = symp... | 5a0adbc43296c325ee01b2043e5096c9702ce562 | 635,070 |
import json
def get_test_ids(check_nightly_status=False):
"""Get the test ids from conf.json
Keyword Arguments:
check_nightly_status {bool} -- if we are running nightly test (default: {False})
Returns:
tuple: (test_ids, skipped_tests)
"""
test_ids = []
with open("./Tests/conf... | 16efc15faaa16712069556191ee000cf7ada883e | 635,072 |
def compare_location_and_region(first_file, second_file):
"""
Compares versions for osfstoragefiles -
Compares location['bucket'] and location['object'].
Also compares version region_ids.
"""
first_loc = first_file['versions__location']
second_loc = second_file['versions__location']
if ... | 534e917e82a65472b4ca5f99f08ff3d523ff9321 | 635,073 |
def spritecollide(sprite, group, dokill, collided=None):
"""
**pyj2d.sprite.spritecollide**
Return list of sprites in group that intersect with sprite.
The dokill argument is a bool, True removes sprites that collide from all groups.
An optional collided is a callback function taking two sprite... | 3af14da2a26c2bdc733e16d44eb76a8009f99ac4 | 635,074 |
def make_error_logger(logger):
"""Make handlers that logs and ignores encoding errors."""
def log_errors(exc):
logger.error('incorrect character encoding', exc_info=exc)
return ('', exc.end)
return log_errors | 94d185f4a53cc4f54bb6cf7cd3f2d9abc8ec0e1a | 635,075 |
def is_compressed_key(pubkey_buffer):
"""
Checks whether or not a public key is compressed.
:param pubkey_buffer: public keys as bytes obj.
:return: true if public key is compressed; false otherwise
"""
if not isinstance(pubkey_buffer, bytes):
raise ValueError
length = len(pubkey_bu... | 2ec03c1982ab0cee2bb48e954dc088422f2e0696 | 635,078 |
def _detect_skipped_track(remaining_duration: float,
end_of_track_buffer: float, track: dict,
prev_track: dict) -> bool:
"""Performs the detection logic for whether a track was skipped
Args:
remaining_duration: The remaining duration of the track in m... | 93b90930f1c87131bec2958d6f81eed645133e2a | 635,080 |
def get_crashes_archive_name(cycle: int) -> str:
"""Return as crashes archive name given a cycle."""
return 'crashes-%04d.tar.gz' % cycle | f466f2c1fd0a578109e52175e6a6629bdeb2c2b2 | 635,081 |
def _output_filename(title):
"""Construct output filename."""
return title + ".html" | 46ada33d35a9a6acc77f06a32eac49692e546eaf | 635,083 |
def is_palindrome(word):
"""Returns true if the word is a palindrome."""
return word == word[::-1] | aacaae1cb0efa3c5fc743231e61f58d1408807ee | 635,091 |
def verify_approval_skip(data, env, env_configs):
"""Determines if a approval stage can be added/removed from a given
environment pipeline stage based on environment setting. Defaults to false,
and verifies administrators allow skips in given environments.
Args:
data (dict): environment config d... | 521e6b4b151ee509f75a9698c0ea74fe2d4af532 | 635,092 |
def get_formatted_name(name):
"""
Return a 3-letters acronym in upper case and longer names in PascalCase.
Exemple: 'sql' -> 'SQL'; 'hunting' -> 'Hunting'
"""
if len(name) == 3:
neat_title = f"{name.upper()}"
else:
neat_title = f"{name.capitalize()}"
return neat_title | c27da647d6615e899653d9ca75ae178d194f7736 | 635,093 |
def human_readable(value):
"""
Returns the number in a human readable format; for example 1048576 = "1Mi".
"""
value = float(value)
index = -1
suffixes = 'KMGTPEZY'
while value >= 1024 and index + 1 < len(suffixes):
index += 1
value = round(value / 1024)
if index == -1:
... | a8dc87493d0d8e7f8732630831991d58b8f01d38 | 635,095 |
def rain(walls):
"""
walls is a list of non-negative integers.
Return: Integer indicating total amount of rainwater retained.
Assume that the ends of the list (before index 0 and after index
walls[-1]) are not walls, meaning they will not retain water.
If the list is empty return 0.
"""
... | e26b22f09823f4a09b8f209780152ed739bf78bd | 635,099 |
def separable_conv(graph, input, all_w, kernel_dim, layer_id):
"""Defines a separable convolution.
Args:
graph: The TASO graph.
input: The input tensor.
all_w: A list of lists of weights (one list for each layer).
kernel_dim: The size of the kernel.
layer_id: The ID o... | 54762e65d63732f353c6bb73b3b4966706d828b6 | 635,100 |
def get_slurm_header(slurm_dict, walltime_hrs, num_nodes=None):
""" Write a SLURM script header from a set of slurm parameters.
Parameters:
slurm_dict (dict): dictionary of SLURM environment variables.
walltime_hrs (int): allowed walltime in hours
Keyword arguments:
num_nodes (int)... | fcc5abfe03e97d6daf73dbbbab87e9cc3f98ec66 | 635,103 |
import functools
def empty_energy_result(energy_result):
"""
Return False if the energy_result list contains only negative numbers, True otherwise
"""
return functools.reduce(lambda acc, x: acc or (x >= 0), energy_result, False) | 980cd49f687ee975eac773139855eec2a4fd59d2 | 635,104 |
def normalized_to_microseconds(normalized_setpoint: float, low: int, center: int, high: int) -> int:
"""
Converts a normalized setpoint (between -1.0 and 1.0) to a pulse width (in microseconds).
Positive and negative values are computed separately, as they can span different intervals in terms of pulse wid... | 65282397c23f77a96032330cf4dbf4d176b8ae0c | 635,105 |
import requests
def post_request(url, body, headers):
"""
Method which makes a POST request to specified url
:param url: url
:param body: data in json format
:param headers: headers
:return: post response
"""
return requests.post(url, data=body, headers=headers) | da685722b716f6523352b199625f9e7570feefd8 | 635,107 |
from typing import Optional
from typing import Union
from typing import Iterable
from typing import List
def listify_decorator_args(
argument: Optional[Union[str, Iterable[str]]],
) -> List[str]:
"""Converts a user-supplied "list" to an actual Python list.
This helper supports a "string" list as follows:
... | 283b095eb4d560ffe22d6ac84b2f4846f5bea2ef | 635,112 |
def precision(confusion, classes, classifiers):
""" Compute the precision from a confusion matrix.
Parameters
----------
confusion : array, shape = [n_classes, n_classes]
Where entry c_{ij} is the number of observations in class i but
are classified as class j.
... | 2ba2f28d51debd375104fed63f69bf87e842d6cf | 635,113 |
def insert_file_paths(command, file_paths, start_delim='<FILE:', end_delim='>'):
"""
Insert file paths into the command line at locations indicated by
the starting and ending delimiters.
"""
tokens = command.split()
final_tokens = []
for token in tokens:
if token.startswith(start_del... | 1d433d99332db84a6e91b82acfa27939e63d7bfe | 635,115 |
def getParameterFromCall(call, index=0):
"""
Returns a parameter node by index on the call node
"""
try:
return call[1][index]
except:
return None | 78cc1521576842d74c5c4d0dce5606587beb2422 | 635,116 |
import math
def triangle_geometry(triangle):
"""
Compute the area and circumradius of a triangle.
Parameters
----------
triangle : (3x3) array-like
The coordinates of the points which form the triangle.
Returns
-------
area : float
The area of the triangle
circum_... | 9cb5124fd30cc27c24d92c7e466ac67fe5d464ff | 635,117 |
import torch
import random
def gen_input_mask(
shape, hole_size, hole_area=None, max_holes=1):
"""
* inputs:
- shape (sequence, required):
Shape of a mask tensor to be generated.
A sequence of length 4 (N, C, H, W) is assumed.
- hole_size (sequence or in... | 799e5cd0590a58012888707b2997b69992a45f83 | 635,119 |
def pack_2byte_to_hn(low_byte, high_byte):
"""
Pack 2 bytes to network order unsigned short
"""
return ((low_byte << 8) | high_byte) & 0xffff | d8c41013feec2c61b011b6b99ea42b1104198609 | 635,120 |
def duration(duration, compact=False, unit=False):
"""Returns a time duration string representing the input value
:param duration: value to format, must be convertible into an into
:param compact: whether to show also seconds, defaults to False
:param unit: whether to display he unit, defaults to False... | 15b55f3f051a34a846ec3210f5081ab55fddb10e | 635,125 |
def getDBReleaseVersion(dbh, jobPars): # extra-wrapper function, to be deprecated?
""" Get the DBRelease version from the job parameters """
return dbh.getDBReleaseVersion(jobPars=jobPars) | d3d8ded7c8fbba37574d9f7d896fd394129edde5 | 635,126 |
def read_bdseq(message):
"""Read the bdSeq number from a TAHU message."""
for metric in message.metrics:
if metric.HasField('name') and metric.name == 'bdSeq':
return metric.long_value
return None | 8200784741bbab42532728c348739f709d8e32bc | 635,127 |
def _guessFileFormat(file, filename):
"""
Guess whether a file is PDB or PDBx/mmCIF based on its filename and contents.
authored by pandegroup
"""
filename = filename.lower()
if '.pdbx' in filename or '.cif' in filename:
return 'pdbx'
if '.pdb' in filename:
return 'pdb'
f... | ab04db18b05ee416315d8d2faa2381e469dda955 | 635,128 |
def env_config() -> dict:
"""
Configures a database connection using an environment variable (Oracle and PostgreSQL only).
:return: A dictionary containing information about the newly-created database connection.
"""
env_var = input(
"\nIdentify the name of the environment variable the conn... | bb181e3e6e12e6d6e2cf278a361a2b3ac7e6f3f3 | 635,132 |
def find_sub_list(sub_list, main_list):
"""Find starting and ending position of a sublist in a longer list.
Args:
sub_list (list): sublist
main_list (list): main longer list
Returns:
(int, int): start and end index in the list l. Returns None if sublist is not found in the main lis... | d9e0a4bad9854f3914d07c176ca5708e11bd0cd8 | 635,133 |
def roman_event(date):
"""Return the event of Roman date 'date'."""
return date[2] | f0c6ccf62b8c63a43a0158a7c744343cabb7d311 | 635,136 |
import copy
def strip_revision_in_copy(doc_map):
""" Strip the _rev field in a deep copy of doc_map and return it.
:param dict doc_map: A dict representation of a JSON document.
:return: doc_map itself without _rev
"""
new_doc = copy.deepcopy(doc_map)
new_doc.pop("_rev", None)
return new_doc | b0c5f7c2d674064effb270050aea654610eb90f4 | 635,141 |
def checkpoint2epoch(_checkpoint_name: str) -> int:
"""
Args:
_checkpoint_name: e.g. 'epoch=2.ckpt' or 'epoch=2_v0.ckpt'
Returns:
_epoch: e.g. 2
"""
return int(_checkpoint_name.split("epoch=")[-1].split("_")[0].replace(".ckpt", "")) | fb42c47aa29eba167e6469a8025b18bc00854de7 | 635,142 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.