content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def filter_words(words, skip_words):
"""This function takes a list of words and returns a copy of the list from
which all words provided in the list skip_words have been removed.
For example:
>>> filter_words(["help", "me", "please"], ["me", "please"])
['help']
>>> filter_words(["go", "south"]... | 27f59ec3315a9129d402b1393430ec143b8b5498 | 566,744 |
import string
import random
def rand_char(len, src=string.ascii_letters + string.digits):
"""
Generate random characther of given maximum length.
"""
# No escape needed inside the generated content.
return "'%s'" % \
(''.join(random.choice(src) for _ in range(random.randint(1, len)))) | 5447c2b8c9f9b09f4dbacdcdb776019f711d1961 | 566,745 |
def get_default_index_name(model_class):
"""Get the default search index name for the given model"""
return "{0.app_label}_{0.model_name}".format(model_class._meta) | 2a89cff97d3bc796ebd884b0482e869a1bc42c04 | 566,746 |
def temperature_closest_to_zero(temperatures):
"""Receives an array of temperatures and returns the closest one to zero"""
closest_to_zero = temperatures[0]
for temperature in temperatures:
if (abs(temperature) < abs(closest_to_zero) or
(abs(temperature) == abs(closest_to_zero) and ... | 8e7ca31f31111eaf35a1ad37980b6cc9225824fb | 566,750 |
import re
def elapsed(t1, t2):
"""
Return a printable string showing the time elapsed from t1 to t2.
"""
# Use the timedelta's standard formatting, except discard microseconds.
retval = str(t2 - t1)
m = re.match(r"([^.]+)\.([0-9]+)", retval)
if m:
retval = m.group(1)
return ret... | e57d6a8ed5a4e890f1b2ee363e69137844f372dd | 566,751 |
def _get_sanitizer_values(obj):
"""
Return a dictionary of sanitizer's values for the object `obj`.
"""
try:
return getattr(obj, "__sanitizer_values")
except AttributeError:
result = dict()
setattr(obj, "__sanitizer_values", result)
return result | 0a411416511fa32bc693e1c62f6af9f3c0d3277f | 566,753 |
def is_coord(coord):
"""Is this string a valid coordinate?"""
return coord[0] in 'ABCDEFGH' and coord[1] in '01234567' | 1d63ca59e5c478d6fbaa82ea49ade1359a5fb501 | 566,754 |
def _perturb_ftr(ftr):
"""Displace a single particle.
Return the ID of the particle, and the perturbed DataFrame."""
ftr = ftr.copy()
pid = ftr.particle[(ftr.x == 15) & (ftr.y == 15)].values[0]
ftr.loc[ftr.particle == pid, 'y'] += 0.1
return pid, ftr | ee98e23897b9d92c0f6910b88b7cfed534a4c9bf | 566,755 |
def normalize_bbox(bbox):
"""Normalizes bounding box: sets minimal coords for first point and maximal
for second point. Returns new bounding box.
:type bbox: list
:param bbox: bounding box
:rtype: list
:return: new bounding box
"""
x0, y0, x1, y1 = bbox
return [min(x0, x1), min(y0, y1), max(x0, x1),... | 55a61a8ac03ea701f282d590f44719ac3c28fa78 | 566,757 |
def apply_noise(val_list, noise_params, noise_function):
"""
Applies noise to each value in a list of values and returns the result.
Noise is generated by a user-provided function that maps a value and
parameters to a random value.
"""
result = []
for val, params in zip(val_list, noise_par... | b13885bfccb361ab0f69e52e9d1ad75b127a8eea | 566,758 |
def get_allied_units_in_progress(observation):
"""
This function takes an observation and returns a dictionary holding
the current units in progress. This dictionary is built as follows
units_in_progress = {
(unit's type, unit's tag): unit's build progress
}
for each allied unit that has a build progress o... | 2ffdab3a40cb1ff29e57f14619983d0832818e54 | 566,759 |
def _format_function_call(fn_name, *v, **k):
"""
Return a Python function call as a string.
Keywords are sorted.
EXAMPLES::
sage: from sage.geometry.polyhedron.backend_normaliz import _format_function_call
sage: _format_function_call('foo', 17, hellooooo='goodbyeeee')
"foo(17,... | fd2904323a88d7fbd3b6df9649fe7489c6d2796c | 566,761 |
from typing import List
from bs4 import BeautifulSoup
def _remove_tags_and_disallowed_bodies(
text: str, disallowed_bodies_tags: List[str]) -> str:
"""Return a cleaned version of the text without any HTML tags and stripped
of the text in the bodies of the disallowed tags.
"""
soup = BeautifulS... | a37ce73ed9a13ecfe43ba012cea596bcbb2fef53 | 566,763 |
def reverse_complement(pattern: str) -> str:
"""Return the reverse complement of the input pattern
Arguments:
pattern {str} -- DNA string
Returns:
str -- Reverse complement
Example:
>>> reverse_complement("AGTCGCATAGT")
'ACTATGCGACT'
"""
transtab = {"A":"T", "... | adc706a6c940d70a9a1706ece8beeb7d1a4e06f0 | 566,767 |
import logging
def _get_obj_silent_fail(qs, **lookup):
"""
Gets an object and returns None if it does not exist
"""
try:
return qs.get(**lookup)
except qs.model.DoesNotExist:
logging.info(
"Could not find object %s from queryset %s", lookup, qs.__class__) | 5a0720291cb009cf0ccf90ec69d83e6e9c9fe92a | 566,774 |
from typing import Optional
def parse_suffixed_line(line: str, suffix: Optional[str]) -> Optional[str]:
"""
Return a `line` without `suffix` if `line` starts with `suffix`, else return `None`.
"""
if suffix is None:
return None
suffix = suffix.rstrip()
if line.endswith(suffix):
... | cda94c610427915991fe86bccc799d241c92ca2b | 566,777 |
def is_group(keyword):
"""Check if group keyword
Args:
Profiles keyword
Returns:
True if group keyword
"""
return bool(keyword[0] == 'G') | 0516dfb5917990994b723eff058e2524df23db23 | 566,778 |
def eval_expr(expr, dict_data):
"""
If expr is a string, will do a dict lookup using that string as a key.
If expr is a callable, will call it on the dict.
"""
if callable(expr):
return expr(dict_data)
else:
return dict_data.get(expr, None) | a1cb4af2a88d0636c24702124f0d31412da8de9a | 566,783 |
def _get_first_non_empty_item(items):
"""
:param items: anything that is iterable
:return: first non empty value
In this filter the following values are considered non empty:
- None
- any empty sequence, for example, '', (), [].
- any empty mapping, for example, {}.
Note: to guarantee... | 7880bef2183fa70cd8a24d61d48b18a28499d368 | 566,790 |
import ast
def toAST(code):
"""Takes a string in the ar4ds dsl and returns an AST
Args:
code (String): A ar4ds code snippet
Returns:
output (ast.Tree): An abstract syntax tree representing the code
"""
return ast.parse(code) | c52628d2bb49dbc8970b15ecd97b84c1b6986075 | 566,792 |
import re
def get_docstring_option_help(obj, arg):
"""Return the docstring help from an argument of a given object
Parameters
----------
obj : `class`, required
`class` of the object from which to read the docstring
arg : string, required
name of the argument from ... | 1d6c660ad32df02bcb38ec9c7ea518c7c9f95949 | 566,794 |
def get_dict_for_attrs(obj, attrs):
"""
Returns dictionary for each attribute from given ``obj``.
"""
data = {}
for attr in attrs:
data[attr] = getattr(obj, attr)
return data | 5c05eed78a3efc2229441fddbc01ea0e503fa2e8 | 566,800 |
def _is_step_running(step):
"""Return true if the given step is currently running."""
return (step['Status']['State'] not in
('CANCELLED', 'INTERRUPTED') and
step['Status']['Timeline'].get('StartDateTime') and
not step['Status']['Timeline'].get('EndDateTime')) | a29b095f32cb7a95114ab4e382606409b43e4168 | 566,803 |
def _is_pyspark_step_type(step_type):
"""Does the given step type indicate that it uses Spark and Python?"""
return step_type in ('spark', 'spark_script') | 91159147ed3f2cec0ce3c2f245f178567d72c7c7 | 566,804 |
def is_circuit_allowed_by_inclusion(op_inclusions, circuit):
"""
Returns True if `circuit` contains *any* of the gates from `op_inclusions`.
Otherwise, returns False. The exception is the empty circuit, which always
returns True.
"""
if len(circuit) == 0: return True # always include the empty ... | 49fc80bf201debec6c6f685767cfb3fb38cb6f8a | 566,806 |
def _ParseBucketName(name):
"""Normalizes bucket name.
Normalizes bucket name. If it starts with gs://, remove it.
Api_lib's function doesn't like the gs prefix.
Args:
name: gs bucket name string.
Returns:
A name string without 'gs://' prefix.
"""
gs = 'gs://'
if name.startswith(gs):
retu... | 07a3486152e50cdfd7e1567d6f867dbd7edef80a | 566,811 |
def get_dxy(nchr_pop1, nchr_pop2, allele1_pop1, allele1_pop2):
"""
Calculates dxy between two populations.
"""
p1 = allele1_pop1/nchr_pop1
p2 = allele1_pop2/nchr_pop2
dxy = round(p1*(1-p2) + p2*(1-p1), 4)
return dxy | 1e193bc8b10ef02e7c476a1bc72e25b7b4092f03 | 566,812 |
def edge_distances(peak,feature):
"""
Return distances between peak and feature edges
Arguments:
peak (Peak): peak instance
feature (Feature): feature instance
Returns:
tuple: a pair of distances, the first being the
smallest distance between an edge of the peak
regio... | bae1303e11bd730949f5639f7a604f5f8029065f | 566,814 |
def get_combinations_as_df(df, cols):
""" Return all unique combinations of values in columns
Args:
df (pd.DataFrame): input df.
cols (list): column names in df.
Returns:
df containing all unique combinations with frequency of each
"""
return df[cols].groupby(cols).size().res... | 5c852f094b9cf80330e4a8079d322fbf62974df6 | 566,818 |
import textwrap
def SplitParagraphs(text):
"""Split a block of text into paragraphs.
Args:
text: The text to split.
Returns:
A list of paragraphs as strings.
"""
text = textwrap.dedent(text.strip('\n'))
lines = text.split('\n')
# Split the text into paragraphs at blank line boundaries.
paragr... | c4c70ed14b8f6cd5136de0648a3d923d5ed4267f | 566,826 |
def sparse_to_tensors(sparse):
"""SparseConvNetTensor --> (locs/coords, features, spatial_size)"""
return sparse.get_spatial_locations(), sparse.features, sparse.spatial_size | 401b557b40afda679611dc1bb42f9d13da490a95 | 566,831 |
def rquicksort(arr):
"""Recursive quicksort"""
if len(arr) <= 1: return arr
return rquicksort([i for i in arr[1:] if i < arr[0]]) + \
[arr[0]] + \
rquicksort([i for i in arr[1:] if i > arr[0]]) | 8690739311a34d654eadb84b64184ce3576057b2 | 566,833 |
def _homogenous_line(A,B):
"""Return line through A and B in homogenous coordinates (a,b,c) with ax+by+c=0."""
if A==B: raise ValueError('Degenerate line through %s and %s' % (repr(A),repr(B)))
Ax,Ay=A
Bx,By=B
# keep magnitude of coefficients as close to unity as possible
if abs(Bx-Ax)>=abs(By-... | 6b30441206a6e32bce05c53630c5a85c966aa367 | 566,835 |
def slim_frame_data(frames, frame_allowance=25):
"""
Removes various excess metadata from middle frames which go beyond
``frame_allowance``.
Returns ``frames``.
"""
frames_len = len(frames)
if frames_len <= frame_allowance:
return frames
half_max = int(frame_allowance / 2)
... | 8d9eaea97f8c5ed5eac87a39894aea1b1e052c48 | 566,838 |
def bonferroni(alpha_orig, p_values):
"""
Bonferrnoi correction.
en.wikipedia.org/wiki/Bonferroni_correction
Parameters
----------
alpha_orig : float
alpha value before correction
p_values: list[float]
p values resulting from all the tests
Returns
-------
alpha... | cebcf251213bfbc48df4b35117383b0d873fce4a | 566,840 |
def get_character_count(line, character):
"""
Returns the number of times a character is found in a line.
"""
return sum(1 for char in line if char == character) | 6e6ab273fa43bfb3da0e63be7e46f2cabc68b030 | 566,841 |
import codecs
def get_dict(modfile):
"""
Return dictionary from file produced by make_dict
It return dictionary with module names as keys and filenames as values.
Parameters
----------
modfile : str
File with entries such as
.. code-block::
FortranFile: mo_mod1 mo... | 8ee9a996c9e344f6e7db4f0cea32417a0e5aef66 | 566,843 |
def sortCirclesBySize(circles):
"""
Sort a list of circles by size;
The imput is a list of [x,y,r] items where r is the size
The return is the list sorted
"""
sortedCircles = sorted(circles,key=lambda circles: circles[2])
return sortedCircles | 7487071685e8079f987fbdb8b9a4e6d4c7fddd0f | 566,844 |
def number_of_occurrences(element, sample):
"""
Function that returns the number of occurrences of an element in an array.
:param element: an integer value.
:param sample: an array of integers.
:return: the number of occurrences of an element in an array.
"""
return sample.count(element) | b7b7350a5032dce9a4b62033c116676c85edb36b | 566,845 |
from typing import List
import re
def extract_ghissue_references(text: str) -> List[str]:
"""
Extract identifiers that are (=look like) references to GH issues
"""
return [result.group(0) for result in re.finditer(r"#\d+", text)] | 4aec70ffec17429fc946ed5715d87dcc7d4cf74c | 566,850 |
import glob
def find_one_file(glob_pattern):
"""If exactly one file matches `glob_pattern`, returns the path to that file, else fails."""
matching_files = list(glob.glob(glob_pattern))
if len(matching_files) == 1:
return matching_files[0]
raise RuntimeError(f'find_one_file({glob_pattern}): {le... | dfff4b1994cdf010fc50efd13e73c7f8159af683 | 566,852 |
def get_number_available(soup):
""" Analyze "soup" to extract stock's availability.
Args:
soup -- bs4.BeautifulSoup from http request of book url.
Return:
stock's availability
"""
table = soup.table
cell = table.find_all("td")
number_available = cell[5].text[10:-11]
ret... | 0680c118ac4ff5743236f170c694bf875c89646d | 566,855 |
def format_string( oldString ):
"""
This function turns a given string (one of the two arguments passed to the
script by the user) into one that can be used as part of the URL used to
fetch the page from the lyrics wiki. Specifically, it needs to be camel-
case (or 'title' case) with underscores re... | 4b37a714a18b642cd5be37030a9854d177688004 | 566,858 |
def tableName(table):
"""Return a string with the name of the table in the current db."""
return table.sqlmeta.table | 23ea66b80c8516d191d5f66e9d647d296480e0ab | 566,859 |
def except_keys(dic, keys):
"""Return a copy of the dict without the specified keys.
::
>>> except_keys({"A": 1, "B": 2, "C": 3}, ["A", "C"])
{'B': 2}
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return re... | 3e04b023ebee10d3dc8214b2f80133fa9930b8c0 | 566,861 |
from typing import List
def get_image_type(image_flavor: str, level_index: int) -> List[str]:
"""Return image type.
Parameters
----------
image_flavor: str
Image flavor ('VOLUME', 'LABEL', 'OVERVIEW')
level_index: int:
Pyramidal level index of the image.
Returns
---------... | d16cd568e1be7a8ef2b54cdc39b6fcc3682c3316 | 566,862 |
def get_combined_representation(phrase, lemmas, pos, concepts, ner=[]):
"""
Generate a combined representation of the phrase,lemmas,pos,concepts and ner
:param phrase: current phrase
:param lemmas: current lemmas
:param pos: POS tags for the phrase
:param concepts: concepts for the phrase
:p... | 96d2c3560f8eb39d9a175d7b72dac955a0125f72 | 566,865 |
def normalize_format(fmt):
"""Turns common shortenings into full format names."""
if fmt == u"md":
fmt = "markdown"
elif fmt == u"mm":
fmt = "moinmoin"
return fmt | 7470074f1b6516442fc2837fcec5e91f54151850 | 566,867 |
def bbox_center_to_lowerleft(bbox):
"""convert a bbox of form [minx, miny, maxx, maxy] to [minx, miny, w, h]. Works for numpy array. """
minx, miny, maxx, maxy = bbox
out_box = [[]]*4
out_box[0] = minx
out_box[1] = miny
out_box[2] = maxx - minx
out_box[3] = maxy - miny
return out_... | b718773ea61ec93e3e155f6e0193561cab640aef | 566,871 |
import re
def replaceAcronyms(text):
"""
Replaces some commonly-used acronyms for an improved verbal weather report.
"""
def parseDirections(text):
words = {
'N': 'nord',
'S': 'sud',
'E': 'est',
'W': 'ouest',
}
output = [words[w]... | 9b83b405b9fa307e65ce2c291cf7acebaeeaa993 | 566,872 |
def get_num(x: str) -> int:
""" Extracts all digits from incomig string """
return int(''.join(ele for ele in x if ele.isdigit())) | df8858baf9e451998aff9f2eb2e19b59bec0d4fa | 566,873 |
def load_example_ploidyest_settings(example_data_path='.', output_dir='.'):
"""
Loads example settings for ploidy estimation.
:param example_data_path: the path where example data is located (default: '.') (str)
:param output_dir: the path where results should be saved (default: current working direct... | 462d2b693fbda9c0c6630e8cc2ac5ea458ec18cb | 566,874 |
def from_string( raw_bytes, offset, count = 0 ):
""" Converts a sequence of NUL-terminated bytes to a Python string. """
s_out = ""
i = 0
while True:
c = raw_bytes[ offset + i ]
if 0 == c: break
s_out += chr( c )
i += 1
if count and (i == count): break
retu... | dd7573b5d0d6343cb1dd4dd68b2bfb1d2a420803 | 566,876 |
def pass_custom_class(dummy):
"""
Used to test that custom class objects can be passed through as'
arguments
:param dummy: DummyClass
:return: The sum of numbers contained in the class
"""
return dummy.add_numbers() | 9bf920b7b1082e60354e0290cf14649aa51be590 | 566,877 |
import re
def sanitize(instr, pattern=r'\W', replace=''):
""" Sanitizes characters in string. Default removes all non-alphanumeric
characters.
"""
return re.sub(pattern, replace, instr) | 8c5d29c9236b6957efc4569ae01edec5ee6b253c | 566,878 |
def snake_to_text(x: str) -> str:
"""Convert snake case to regular text, with each word capitalized."""
return " ".join([w.capitalize() for w in x.split("_")]) | 2aa2d3af53c0ffac43971d51e174c24f0566a6a4 | 566,880 |
def has_fact_sheets(responses, derived):
""" Return whether or not the user is submitting fact sheets """
return any([derived['show_fact_sheet_b'], derived['show_fact_sheet_c'],
derived['show_fact_sheet_d'], derived['show_fact_sheet_e'],
derived['show_fact_sheet_f'], ]) | 0f5e869476ce83debb1c88d9c367594e6c9e952e | 566,883 |
def generate_iterables(scan_info, experiment, subjects, sessions=None):
"""Return lists of variables for model workflow iterables.
Parameters
----------
scan_info : nested dictionaries
A nested dictionary structure with the following key levels:
- subject ids
- session i... | 3869ea23b44278a57ad2239cef36729e8c18c4a8 | 566,885 |
def math_answer_valid(answer):
"""The purpose of this function is to prevent errors within the
honeybee_math() function by ensuring answers to the math questions
are integers. If the user does not provide a valid input, this function
will prompt the user until they enter a valid integer input. Once the
... | 52e935b2c854b46771790b57505ea76e38063695 | 566,888 |
def is_cql(cql_collections):
"""
Checks whether any colelction resource supports feature filter
:param collections: collection object
:returns: boolean value
"""
for _, v in cql_collections.items():
if v:
return True
return False | 01791854cf0fe7147b86f5d54ca1123712fa0b61 | 566,892 |
import torch
def flip_lr(image):
"""
Flip image horizontally
Parameters
----------
image : torch.Tensor [B,3,H,W]
Image to be flipped
Returns
-------
image_flipped : torch.Tensor [B,3,H,W]
Flipped image
"""
assert image.dim() == 4, 'You need to provide a [B,C,... | da3e55c2110b49df2f6b2c2b48d044a26151ba3c | 566,893 |
def time_c_to_s(t, clock_freq):
"""
Convert form time in sample chunks to time in seconds (1 chunk = 32 samples)
clock_freq is in Hz
"""
return float(t * 32.0) / float(clock_freq) | 0073924c01405db2227886e42df177162420a73a | 566,894 |
def has_feed_operators(block, feed_targets, feed_holder_name):
""" Check whether the block already has feed operators.
Return false if the block does not have any feed operators.
If some feed operators have been prepended to the block, check that
the info contained in these feed operators matches the f... | bd0543e18fbf3249f7357f3df6ffd5f391fbdbfc | 566,895 |
def is_external_artifact(label):
"""Determines whether a label corresponds to an external artifact."""
# Label.EXTERNAL_PATH_PREFIX is due to change from 'external' to '..' in Bazel 0.4.5.
# This code is for forwards and backwards compatibility.
# Remove the 'external' check when Bazel 0.4.4 and earlie... | f0c7025c940532ec6d08a29bdb440f43c27312a9 | 566,898 |
def camel_case(name):
"""Convert words into CamelCase."""
return ''.join(name.capitalize().split()) | 40430be30493a61f0428a79cd8259f02ad6c37ba | 566,900 |
import re
def wild_to_regex(string):
"""Transforms wildcard searches into regular expressions."""
regex = re.escape(string)
regex = regex.replace(r'\*', '.*')
regex = regex.replace(r'\?', '.')
return regex | 741721e4f6f58084e28863cedfe7f2e630524614 | 566,901 |
from typing import Union
def rev_reg_id(cd_id: str, tag: Union[str, int]) -> str:
"""
Given a credential definition identifier and a tag, return the corresponding
revocation registry identifier, repeating the issuer DID from the
input identifier.
:param cd_id: credential definition identifier
... | 75e986099cfb49a6174c35a7ff01e8ddcdfb9669 | 566,902 |
import re
def check_reg_matching(reg, stringa):
"""
Check if a regular expression matches a given string
Parameters
-------------
reg
Regular expression
stringa
String
Returns
-------------
boolean
Matches or not?
"""
if type(reg) is str:
r... | 528cf872f6ce8aee8e19bf46e917fa2c72c92c63 | 566,903 |
def load_DS(mol_file):
"""
Description -
Loads in .txt file of smiles and returns a list of all of the smiles
Input -
mol_file: A .txt file of smiles for data set analysis
Return -
smiles: A list of smiles from mol_file
"""
file = open(mol_file, 'r')
text = file.readlines()
... | fee51aef840db116cda062e94b7b0d81adec7d47 | 566,904 |
def nzbget_group_is_active(group):
""" Returns True if the group is considered 'active' i.e. downloading, post-processing, running a script, etc, but NOT 'PAUSED'. """
return group['Status'] != 'PAUSED' | 72db4b341fbf214e16896afb8ae837d29b93590f | 566,906 |
def count(a=False, b=False, c=False, d=False, e=False, f=False, g=False, h=False):
"""Counts no. of True values. `📘`_
- a: 1st boolean
- b: 2nd boolean
- ...
Example:
>>> count(True, True) == 2
>>> count(True, False) == 1
>>> count(True, True, True, False) == 3
... | e4d279c518e6fbd9431891a199c9b9bedccef6a8 | 566,910 |
def inhexrange(hsa, hsz, addr):
"""Check if addr within hex range."""
staddr = int(hsa, 16)
enaddr = int(hsa, 16) + int(hsz, 16)
if addr >= staddr and addr <= enaddr:
return True
return False | fb5eb0da8fe3ebc2133cea49a44a3293a0a7c707 | 566,914 |
def from_snake(s: str):
"""Convert from snake case cols to title"""
return s.replace('_', ' ').title() | 5ba98738ae4aeb9f0a684b5e25871df791c1b90a | 566,917 |
import yaml
def read_variable_from_yml(filename, variable_name):
"""
Read the given variable from the given yaml file.
:param filename: Yaml file to read from.
:param variable_name: Variable to read from file.
:return: Value of variable or None.
"""
with open(filename, 'r') as fh:
... | 5bc00894cfdc5e69269ba8196c93bb382f9e23f8 | 566,918 |
def get_all_sentence_lists(conn):
"""Get all sentence lists from table"""
cursor = conn.cursor()
cursor.execute('SELECT * FROM sentenceLists')
data = cursor.fetchall()
return data | f0494a46b8d7836253d99f3b7815a22d51f8d2a1 | 566,919 |
from math import sqrt
def isqrt(n) :
"""
Square root rounded down.
"""
return int(round(sqrt(n))) | 269b15d3c44491d20596daf6eba8653ded4c6ec1 | 566,920 |
def _mp3VersionKey(version):
"""Map mp3 version float to a data structure index.
1 -> 0, 2 -> 1, 2.5 -> 2
"""
key = None
if version == 2.5:
key = 2
else:
key = int(version - 1)
assert(0 <= key <= 2)
return key | aae4075b10eec3aef84e8cec6d4a837f405182c4 | 566,923 |
def get_wagtail_children_live_in_menu_all(root_page, active_page):
"""
Recursively find all live pages that have attribute In Menu flipped on.
:param root_page: The root_page page to start the search
:param active_page: The page currently being requested
:return: The filtered QuerySet of pages that... | d46947dad8d938a152cad602f2e5d451e4c17825 | 566,924 |
def _get_class(cls_or_obj) -> type:
"""
Get the class of an object if one is provided.
@param cls_or_obj: Either an object or a class.
@return: The class of the object or just the class again.
"""
if isinstance(cls_or_obj, type):
return cls_or_obj
return type(cls_or_obj) | 517f591276f884624c203d3e4bdcdf6c8e1a9642 | 566,925 |
def validate_string(s):
"""
Check input has length and that length > 0
:param s:
:return: True if len(s) > 0 else False
"""
try:
return len(s) > 0
except TypeError:
return False | c0adc92c9cf592669ae20f5aaefa9aedd69f151b | 566,930 |
def _get_num_coefficients(function_dict):
"""
Returns the number of coeffecients according to the IRAF fits format defined
here: http://iraf.net/irafdocs/specwcs.php
"""
function_type = function_dict["type"]
if function_type in ["legendre", "chebyshev"]:
return function_dict["order"]
... | 3a2eeff029fe8fdc7c55446d74b085f84a0ac21b | 566,933 |
import re
def normalize_string(string):
"""
Function returns string without redundant spaces and new lines in string given as an argument.
:param string: string to be modified
:return: normalized string
"""
return re.sub(r'[ ]{2,}', '', string).replace('\n', '').replace('\xa0', '').strip() | eb1a79d0914e248feacee7d79ae674dcf9e5be0a | 566,934 |
def _hgvs_coord_to_ci(s, e):
"""convert start,end interval in inclusive, discontinuous HGVS coordinates
(..,-2,-1,1,2,..) to continuous interbase (right-open) coordinates
(..,-2,-1,0,1,..)"""
def _hgvs_to_ci(c):
assert c != 0, 'received CDS coordinate 0; expected ..,-2,-1,1,1,...'
return... | ddf7eed4771d6f98738d90e45ad2dd6ed3c7fce9 | 566,937 |
def _append_y(clifford, qubit):
"""Apply a Y gate to a Clifford.
Args:
clifford (Clifford): a Clifford.
qubit (int): gate qubit index.
Returns:
Clifford: the updated Clifford.
"""
x = clifford.table.X[:, qubit]
z = clifford.table.Z[:, qubit]
clifford.table.phase ^= ... | ac2429e81590fcdb8f2821154b81165031a5ef26 | 566,940 |
def handle019a(tokens):
"""
Processes the 019A (Erscheinungsland) field. Currently, only subfield a is supported. Only the first country is extracted.
For details (in German), see: https://www.gbv.de/bibliotheken/verbundbibliotheken/02Verbund/01Erschliessung/02Richtlinien/01KatRicht/1700.pdf)
:param to... | bfd89fcddc1d49cefc083f75055bc3c987debf4f | 566,945 |
def getU8(abData, off):
"""Get a U8 field."""
return abData[off]; | 3756bae59cc75d2048e53bbdf389999f818a1cc6 | 566,947 |
import copy
def deepmerge(dest, src):
"""
Deep merge of two dicts.
This is destructive (`dest` is modified), but values
from `src` are passed through `copy.deepcopy`.
"""
for k, v in src.items():
if dest.get(k) and isinstance(v, dict):
deepmerge(dest[k], v)
else:
... | 52419b6db90fb4c98dfb7519961668ec8d478c80 | 566,953 |
def default_shear_conf() -> dict:
"""
Default shear configuration.
"""
shear_conf = {
'twinmode': '10-12',
'grids': 5,
'expansion_ratios': [1., 1., 1.],
}
return shear_conf | ad1523df07e335cd12411144dcad243ddfd143a8 | 566,956 |
import json
import ast
def loadAspectTermData(aspectTermDataPath):
"""
Module to load aspect term data obtained from Aspect Term Extraction Module
Args:
aspectTermDataPath: aspect term data path from Aspect Term Extraction Module
Returns:
termData: list of aspect term data from Aspect ... | d50e9e5f18a9be6e2bfbe38ad0f875a7321c5e0a | 566,962 |
import re
def standardize_annotator(annotation, annotator="annotator"):
"""Substitute coder name in annotation for annotator."""
# Anvil line for coder: <info key="coder" type="String">TMW</info>
# regex matches line prior to the coder name in group 1, coder name
# in group 2, and remainder in group 3... | 15136b0dfb60e6dcb317facadf997baaf40c7eec | 566,964 |
def skipnonsettingsinst(instances):
"""Removes non /settings sections. Useful for only returning settings monolith members.
Example: Members with paths `/redfish/v1/systems/1/bios/` and
`/redfish/v1/systems/1/bios/settings`
will return only the `/redfish/v1/systems/1/bios/settings` member.
:param i... | b558844061a334b48d2ba448544f91ddf18b1980 | 566,965 |
def type__var(in_var,FDparams, AddPrefix_for_UpDownWindVars=True):
""" Outputs [type] [variable name]; e.g.,
"const double variable"
:param in_var: Variable name
:param FDparams: Parameters used in the finite-difference codegen
:param AddPrefix_for_UpDownWindVars: Boolean -- add a prefix to up/down... | f136eecb96c04bb3e09cc4fe9dcad4d68aa36495 | 566,966 |
import requests
def _get_url(url, params, **kwargs):
"""Wraps the requests.get() call and returns the results as a decoded
JSON object.
Args:
url (str): URL to request
params (dict): Same as requests.get(params)
kwargs: Passed directly to requests.get()
Returns:
dict:... | 039e898f8a9ff91b31f6d1907fd6d9acc572b741 | 566,967 |
def JsonBool(bool):
"""Convert python bool to JSON bool"""
if bool:
return "true"
else:
return "false" | 79f70e3581ae9e47614dadbf3152cfdcaaed929c | 566,968 |
def rgb_tristimulus_to_chromacity(r, g, b, neg=True):
""" Convert RGB tristimulus to chromacity coordinates
:param r: Red value
:param g: Green value
:param b: Blue value
:param neg: Allows keeping negative values in result
:return: RGB chromacity coordinate """
if min(r, g, b) < 0.0:
... | 7f9cf1d9abbc564049ed909fd2934aa697b771f5 | 566,969 |
def _remove_keys(results: dict, remove: list) -> dict:
"""
Remove a set of keys from a dictionary.
Args:
results (dict): The dictionary of results
remove (list): the keys to remove
Returns:
dict: The altered dictionary
"""
removed = {}
for key, val in results.items(... | d5e42556af367dae235065257a468bcaadc01a4c | 566,971 |
def comp_surface_opening(self, Ndisc=200):
"""Compute the Slot opening surface (by numerical computation).
Caution, the bottom of the Slot is an Arc
Parameters
----------
self : Slot
A Slot object
Ndisc : int
Number of point to discretize the lines
Returns
-------
S... | b614c018eef124eb4bb0bf67c6c01589916859e1 | 566,974 |
def is_node_file(node):
"""Returns True if the object is a file (i.e. it may have
corresponding data in the object store)
"""
return node._dictionary["category"].endswith("_file") | 26e3ed1902b3d2bf3f494cbde59fbdab57d90353 | 566,976 |
from typing import List
def counting_sort(arr: List = [], exp: int = 1) -> List:
"""
Input: sequence of number store in array (list): [a1,a2,a3 ,.... an]
Output: permutation of that array that following the ascending value property: [a1', a2', a3', ... , an']
where a1'<= a2' <= a3' <= ... <= an'
... | ffddccc39645354b34d5cc5f5bd0feedb248e994 | 566,980 |
import time
def timestamp2float(ts: str) -> float:
""" Converts a timestamp of the form 2016-03-10T04:15:02.0036 into a time float
Arguments:
ts: timestamp string
Returns:
floating point time from mktime with microseconds added to it.
"""
(time_stamp, fractsecond... | 4c2d9201ac757c2d3d1330bc1d9abd656bab250a | 566,981 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.