content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def make_str(s):
"""Casts the input to string. If a string instance is Not given, Ikke gitt or None, return empty string."""
if s == 'Not given':
return ''
if s == 'Ikke gitt':
return ''
if s is None:
return ''
return str(s) | c3af6cb891ec069be1846214ae6af3a7e11ab319 | 661,131 |
def get_touchdown(df):
"""
Calculates instance of touchdown (landing).
"""
df = df.copy()
return df.iloc[df['Altitude'].idxmax():][df['Altitude'] <= 2].index[0] | 314aa3f1dfd91fd0f7a287359e48c930b731aa1e | 661,134 |
def format_cmd(cmd):
"""If some command arguments have spaces, quote them. Then concatenate the results."""
ans = ""
for val in cmd:
if " " in val or "\t" in cmd:
val = '"' + val + '"'
ans += val + " "
return ans | dcbcd93812fabb742b42fcdd68cbbb88acae224f | 661,137 |
import copy
def select_keys(d, keys):
"""Returns a dict containing only those entries in dict whose key is in keys
See also select_paths
:param d: dict to filter
:param keys: a list of keys to select
:returns: a copy of subset of d with only the specified keys
:rtype: dict
"""
return... | 1cc72071cd6c539fef2e53cd2062bb6af0c252b3 | 661,140 |
def replace_forward_slash(file_name):
"""
This method takes a string representing a file name and replaces forward slashes with ":"
This approach is consistent with how other clients deal with attempts to upload files with forward slashes
in the name.
"""
return file_name.replace("/", ":") | 0311edee118b9640c10b89cac95e3a91524aefed | 661,141 |
def jet_id(jets, options):
"""
Loose jet ID taken from flashgg: https://github.com/cms-analysis/flashgg/blob/dd6661a55448c403b46d1155510c67a313cd44a8/DataFormats/src/Jet.cc#L140-L155
"""
nemf_cut = jets.neEmEF < 0.99
nh_cut = jets.neHEF < 0.99
chf_cut = jets.chHEF > 0
chemf_cut = jets.chEmEF... | d522e56625a93f75460d83673bf89af5968c12eb | 661,144 |
def get_tokens(flight_list):
"""
Create list of booking tokens to retrieve booking info.
"""
return [i['booking_token'] for i in flight_list] | 863df7f52001154a4ba16e372712f062219b9774 | 661,146 |
def get_element_by_id(_id, group_list):
"""
Use next generator to find element in a group's list by identifier.
"""
return next(e for e in group_list if _id == e["id"]) | 9331de008e7bf40ad6d4fbd1d653159e9b7e079a | 661,148 |
from typing import Optional
from typing import Mapping
def _check_scale_factor(
spatial_data: Optional[Mapping],
img_key: Optional[str],
scale_factor: Optional[float],
) -> float:
"""Resolve scale_factor, defaults to 1."""
if scale_factor is not None:
return scale_factor
elif spatial_d... | bc19441ed69f9020fefdaa6ee87fb8954a429f64 | 661,149 |
from typing import List
def get_param_docstring(docstring: str) -> str:
"""
Get docstring of argument part.
Parameters
----------
docstring : str
Target docstring string.
Returns
-------
param_docstring : str
Argument part docstring.
"""
param_part_started: bo... | 469036274094d33d064c91e1755bfb2924dd4e5f | 661,150 |
def get_new_pos(old_pos):
"""This is a function that converts part-of-speech codes to abbreviated parts-of-speech"""
new_pos = ""
if old_pos.startswith('J'):
new_pos = "a"
elif old_pos.startswith('V'):
new_pos = "v"
elif old_pos.startswith('N'):
new_pos = "n"
elif old_pos... | 875b699ab7877693ae140862b0de98d980e764c0 | 661,151 |
def sanitize_metric_name(metric_name: str) -> str:
"""
Replace characters in string that are not path-friendly with underscore
"""
for s in ["?", "/", "\\", ":", "<", ">", "|", "'", '"', "#"]:
metric_name = metric_name.replace(s, "_")
return metric_name | ea108e806e3dcf7ea300746e1e42610e4e890fe8 | 661,152 |
def get_alignment_pdb_chain(alignment):
"""
Returns a string of the chain id, e.g. 'A', 'B', etc.
:param alignment:
:return:
"""
pdb_chain_id = alignment.hit_def.encode('ascii').split()[0]
chain = pdb_chain_id.split('_')[1].upper()
return chain | d322ea53606e8d8e5dd61bd50bf0ad44fbb24182 | 661,156 |
from typing import List
def calculate_magnitude(reduced_form: List[List[int]]) -> int:
"""
Generate the magnitude by reducing from inside out.
Ex: [[9,1], [1,9]]
=> [(9, 2), (1, 2), (1, 2), (9, 2)]
=> [(29, 1), (1, 2), (9, 2)]
=> [(29, 1), (21, 1)]
=> [(129, 0)]
=> ... | b0a67b3423b9094b0423eb552e841ada0b61bf77 | 661,160 |
def process_lines(file_reader, corpus_name:str)->list:
"""Strips and splits the lexicon lines.
The case is kept intact for the 'switchboard' corpus, but is lowered for all others
Args:
file_reader: file reader object of lexicon
corpus_name (str)
Returns:
(list): split lexicon li... | d78867a6c6687a6857e9ab9d05dc689cc36f5b28 | 661,161 |
def documentation_link(chapter):
# type: (str)->str
"""
Creates a link to the documentation.
This method is useful for showing a link to the ZSL documentation in case of any misconfiguration, etc.
:param chapter: Chapter name in to which the link points. Use underscores instead of spaces.
:retu... | 3fa25188811b1fece777e95755e5ebdc5cb1a4b8 | 661,162 |
def stcqt(sig, fr, cqbank):
"""Implement Judith Brown's Constant Q transform.
Parameters
----------
sig: array_like
Signal to be processed.
fr: int
Frame rate in Hz, or int(SR/hop_length).
cqbank: ConstantQ Filterbank class
A pre-defined constant Q filterbank class.
... | dc9b46323c530fafde2e29ca105b8e4ca33e0c18 | 661,164 |
def get_grid_offset(function, axis):
"""
For a function, return the grid offset for a specified axis.
Parameters
----------
function : devito Function
The function to get the offset of
axis : int
The axis for which offset should be recovered
"""
if function.is_Staggered:... | fbfa549008d1b856dcc560e5d10f9780a116e5bd | 661,166 |
def SplitSequence(seq, size):
"""Split a list.
Args:
seq: sequence
size: int
Returns:
New list.
Recipe From http://code.activestate.com/recipes/425397/ (Modified to not return blank values)
"""
newseq = []
splitsize = 1.0/size*len(seq)
for i in range(size):
newseq.append(seq[int(round... | 7f836854a46a13f99c2aaac72321656df65a837b | 661,171 |
def remove_formatting(ingredients_series):
"""Remove text formatting and non alphabetic characters,
replace . with ,"""
return (
ingredients_series.str.replace("<strong>", "", regex=False)
.str.replace("</strong>", "", regex=False)
.str.replace(" \(.*?\)", "", regex=True)
.st... | b60d56385eadf77b5174af9809651728a46310ee | 661,178 |
def darken(color, ratio=0.5):
"""Creates a darker version of a color given by an RGB triplet.
This is done by mixing the original color with black using the given
ratio. A ratio of 1.0 will yield a completely black color, a ratio
of 0.0 will yield the original color. The alpha values are left intact.
... | 3799437d126f27745710c1cd2db12c13cff1bab4 | 661,182 |
from typing import List
def find_disappeared(nums: List[int]) -> List[int]:
"""
Explanation:
We have two ways to encode information: the values in the array,
and the indices of the array. We iterate through the array,
and store info about the values at their corresponding index: value - 1.
W... | 548b81e293aa88c73af342420a31e0a39686cf5f | 661,185 |
def _mock_check_state(_):
"""Mocked check_state method."""
return True | 1db16fd64d93147d1b1eb849e6afb4463b0f6ff3 | 661,191 |
import math
def conv_float2negexp(val: float) -> int:
"""Least restrictive negative exponent of base 10 that achieves the floating point convergence criterium `val`."""
return -1 * int(math.floor(math.log(val, 10))) | e237466afa0fec8f128e1c4f72a81e0ca8dcb6bb | 661,194 |
def get_keys_by_value(dict_of_elements, value_to_find):
"""
Parse a dict() to get keys of elements with a specified value
:param dict_of_elements:
:param value_to_find:
:return:
"""
list_of_keys = list()
list_of_items = dict_of_elements.items()
for item in list_of_items:
if i... | 6d547ca6c4cfc3f2cb4c62a8675e8d88e084e100 | 661,196 |
def compat_is_coresight(dcompat):
"""
Check if a device tree node claims compatibility with CoreSight.
We don't check for "arm" here because an architecture-licensee core might be
ETM-compatible but not be an Arm device.
We also expect to see "primecell".
"""
for dc in dcompat:
if dc... | d339acfc95976c27141b800527ba64c655c578a4 | 661,197 |
import re
def parse_ancestor_offsets(date_arg):
"""Parse any ancestor offsets in date runtime argument.
The date argument passed in doesn't *need* to have any of these
offsets.
Args:
date_arg: A string containing a date argument to be
parsed.
Returns:
A two-tuple con... | 855db68cc3245e06bb4742c2cc677571b31340e6 | 661,198 |
def sum_list(x):
"""Takes a list, and returns the sum of that list.
If x is empty list, return 0.
>>> sum_list([1, 2, 3, 4])
10
>>> sum_list([])
0
"""
return sum(x) | adc3b608afe0868898a9822d041634170256acf5 | 661,205 |
def locate_tifs(file_list) -> list:
"""identify the .tif files in a list of files
Parameters
----------
file_list : list
list of files to parse
Returns
-------
list
list of files where the extension is .tif
"""
return list([s for s in file_list if '.tif' in s.lower... | 554244a7f321ac201f05a71f4585bc48d8feaf41 | 661,208 |
def skip_add(n):
""" Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0.
>>> skip_add(5) # 5 + 3 + 1 + 0
9
>>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0
30
>>> # Do not use while/for loops!
>>> from construct_check import check
>>> # ban iteration
>>> check(this_file, 'skip_add... | 06f51a030ed0dfc4b92da9451af4c4a9ae83dc47 | 661,209 |
import resource
def li_worker(func, storage, time, memory, *args, **kwargs):
"""limits the memory consumption and time taken to execute given function
Args:
func (`function`): function to execute
storage (`list`): multiprocessing.Manager().List() to store the peak memory
time (`int`):... | 9a4d3622c7a9c144c684f2fd6ef8ed243d5b497f | 661,215 |
import random
def random_system(tree):
"""Returns random system node.
"""
systems = tree.xpath('.//system')
idx = random.randrange(0,len(systems))
return systems[idx] | 97d16be47082fb7cf56ac8a3ba9dc2b31298854c | 661,216 |
import math
def resize(size, hwRatio):
"""
Return the minimum size of image that is at least "size" but
maintains the provided aspect ratio
"""
if size[0] * hwRatio > size[1]:
return (size[0], int(math.ceil(size[0]*hwRatio)))
else:
return (int(math.ceil(1.0*size[1] / hwRatio)),... | 15db9734e6d0b7314d8a51f2b918d37cdf065620 | 661,217 |
def _consume_until_marker(it, marker):
""" Consume data from the iterator, until marker is found (compared using
operator `is`).
Returns tuple of number of elements consumed before the marker and bool
indicating whether the marker was found (False means the iterator was
exhausted. """
i = -1
... | 230641058856c4576b5de4a186568707454a4f6f | 661,221 |
from typing import Dict
from typing import Any
def deep_update(src: Dict[Any, Any], dest: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Similar to ``dict.update``, except that we also ``deep_update``
any dictionaries we find inside of the destination. This is useful for
nested default settings, for instance.... | 73ca42fc487f3a5055528b43460c3fb12743b940 | 661,225 |
def spark_df_to_records(df):
"""Dump a Spark DF as a list of tuples representing rows ('records')."""
return [tuple(r) for r in df.collect()] | 31536a740fb997cbd4eb4e700068c7093bab054b | 661,230 |
def findRdkitMolRadicalAtomIds(rdkitMol):
"""Returns a list of atom ids with radical sites."""
radicalAtomIds = []
for atom in rdkitMol.GetAtoms():
if atom.GetNumRadicalElectrons() > 0:
radicalAtomIds.append(atom.GetIdx())
return radicalAtomIds | 8a8494c4c1a4a2a8af99e92498e0fb73ce45701c | 661,231 |
def region_slice(dset, x0=None, x1=None
, y0=None, y1=None):
"""
DESCRIPTION:
===========
Returns lon / lat rectangle slice of a xarray data set
USAGE:
=====
sliced_dataset = region(dset, x0, x1, y0, y1)
dset: xarray dataset
x0: long... | b98bcfe49fed526539ab121944c1e03f4ade6d0f | 661,233 |
def find_link(search, soup):
"""Find and return the first <a> tag's href element in `soup`."""
link = soup.find("a", text=lambda t: search in t)
return link.attrs["href"] | c0feb33f6f216b1a8665c061ac72e19ac4aaaf77 | 661,234 |
def _ev_remaining_range_supported(data):
"""Determine if remaining range is supported."""
return (
data["isElectric"]
and data["evStatus"]["chargeInfo"]["drivingRangeKm"] is not None
) | 4e038c5deea3899f54cd8616075536dced694525 | 661,235 |
def normalize_by_chrom_lengths(counts_dict, chrom_lengths_dict):
"""
Normalize the number of counts by the length of the chromosome
Parameters:
counts_dict(dict): count_chrom_alignments
chrom_lengths_dict(dict): output from determine_chrom_lengths()
Returns:
counts_dict (dict):... | c31a8fb8371960ce4740316abcb4dd9c35eff15a | 661,236 |
def rule2string(lhs,rhs,isCopy=False):
"""
Makes a string from a rule. Used in printing and in making a dict of rules and probs.
Arguments:
lhs : string
rhs : string list
isCopy : boolean indicating a copy rule. Only used in cky_constituent_copy
"""
s = "%s->%s"%(lhs,".".join(rhs)... | 17b8cd69729c695866c4306f26f3806fa57352ee | 661,241 |
import requests
def create_oauth_token(grant_type, client_id, client_secret, workspace_id=None, scopes='', username=None, password=None, uri='https://plaidcloud.com/oauth/token', proxy_settings=None):
"""Attempts to create an Oauth2 auth token using the provided data
This is designed primarily for password-t... | ce7d164166d8fefca87cddbbdae2ed6bfbaca23d | 661,243 |
from typing import List
def path_for_class(cls) -> List[str]:
"""
A list describing the import path for a given class.
Parameters
----------
cls
A class with some module path
Returns
-------
A list of modules terminating in the name of a class
"""
return f"{cls.__modu... | ddacd912e8742d0017cdb4d9eb7feb540fd78ae8 | 661,245 |
def check_defaults(options, default):
"""Adds the values in default to options.
Args:
options (dict): base options.
default (dict): default options.
Returns:
dict: options with the missing values that are in default but not in
options.
"""
if options is None:
... | 44010dd033da1ec4dceaa1b89111157489b71e61 | 661,249 |
def st_align(self,t_start):
"""
Shifts the current spike train to a different t_start.
The duration remains the same, this is just a shift.
"""
diff = self.t_start - t_start
new_st = self[:] - diff
new_st.t_start = t_start
new_st.t_stop = self.t_stop - diff
return new_st | d6ada6279bd020a1f3ce854dc76028e44cf0c3f4 | 661,250 |
def uniq(x):
"""Remove duplicated items and return new list.
If there are duplicated items, first appeared item remains and
others are removed.
>>> uniq([1,2,3,3,2,4,1])
[1, 2, 3, 4]
"""
y=[]
for i in x:
if not y.count(i):
y.append(i)
return y | 4fa8d2e55518d2794175002e1826be59fb6ec542 | 661,251 |
def AlternatesInModel(model):
"""Returns a set of altloc names of all conformers in all chains.
:param model: pdb.hierarchy.model to search for alternates.
:return: Set of strings. The set is will include only the empty string if no
chains in the model have alternates. It has an additional entry for every alt... | 2a156ee07f5187f8d8a4f173cf338889e7a1f0ad | 661,252 |
from typing import Optional
def decode_bytes_str(input_value=None, charset='utf-8') -> Optional[str]:
"""
Decode input value to string using the given charset
:param charset: charset to use while decoding (defaults to utf-8)
:param input_value:
:return:
"""
if input_value is not None and n... | d5c8aadaf7cff5ef5b0003d5e8f74da35de37a5b | 661,255 |
def instance_with_scenario_name(instance_name, scenario_name):
"""Format instance name that includes scenario."""
return f"{instance_name}-{scenario_name}" | 2ce13b41e604e7caaa2d9ccc1a7f042dfa223244 | 661,261 |
def nvmf_create_target(client,
name,
max_subsystems=0):
"""Create a new NVMe-oF Target.
Args:
name: Must be unique within the application
max_subsystems: Maximum number of NVMe-oF subsystems (e.g. 1024). default: 0 (Uses SPDK_NVMF_DEFAULT_MAX_SUBSYS... | 7b10540651b169406f942889caabef95506c4232 | 661,262 |
def confusion_matrix(classify=lambda document: False, documents=[(None, False)]):
""" Returns the performance of a binary classification task (i.e., predicts True or False)
as a tuple of (TP, TN, FP, FN):
- TP: true positives = correct hits,
- TN: true negatives = correct rejections,
... | 6521e24c3283fff6409609f9ace760b5d318c8f3 | 661,263 |
def setdeepr(obj, name, value):
"""Function to set deeper attributes, replaces setattr."""
names = name.split('.')
for name in names[:-1]:
obj = getattr(obj, name)
return setattr(obj, names[-1], value) | 933d93f7b020c63889ed4993048f9533343cc56f | 661,264 |
def pos_upper(num, string):
"""
Returns a string containing its first argument, and its second argument in upper case.
:param num: int
:param string: str
:return: str
"""
return f'{num}:{string.upper()}' | 06d6ee1f41fc2d81e39e39b35f339f138ae3606a | 661,267 |
def space_name(prefix, index):
"""Construct name of space from the prefix and its index."""
return "{p}{i}".format(p=prefix, i=index) | 079e36992f315a42abec40a4c1a58b11ecc7c5f4 | 661,270 |
import math
def square_distribution(size):
"""
Determines the "most square" x and y values which will make a grid of
the specified size.
args:
size - the size of the grid (int)
returns:
size_prime - True if size is prime (bool)
x ... | 8d61fae19bbd9e5c4b0300686f9318db30678100 | 661,271 |
def is_in_subnet(ip, subnet):
"""True if given IP instance belongs to Subnet."""
return ip.bits == subnet.bits and (ip.value & subnet.mask) == subnet.base | ac1e4e00e6a2eff64f75c08bd4057aceadb823cf | 661,278 |
import yaml
def dump_to_string(data)-> str:
"""
Dumps 'data' object to yaml string
"""
result = yaml.safe_dump(data,
default_flow_style=False,
default_style=None,
explicit_start=None)
return result | 234927a81831d92820bf8599a7b27ee7e256793f | 661,280 |
def xml_combine(root, elements):
"""Combine two xml elements and their subelements
This method will modify the 'root' argument and does
not return anything.
Args:
root (Element): The Element that will contain the merger
elements (Element or list): If an Element, merge all subelements o... | 9667c4cb8dd9cc02ea84808c866a23068b4f4830 | 661,282 |
def rescale(values, factor):
"""
Returns a new dictionary of scaled values
The values are scaled by the scale factor given
"""
return {key: value * float(factor) for (key, value) in values.iteritems()} | 4d1326512e755fabfdd475105cbf1f4502c37892 | 661,285 |
def is_above_or_to_left(ref_control, other_ctrl):
"""Return true if the other_ctrl is above or to the left of ref_control"""
text_r = other_ctrl.rectangle()
ctrl_r = ref_control.rectangle()
# skip controls where text win is to the right of ctrl
if text_r.left >= ctrl_r.right:
return False
... | dcc02e8e9424825704682f6b12683bb9de2fe132 | 661,288 |
def relative_humidity(e_a, e_s):
"""
Calculate the relative humidity of air (Allen et al., 1998).
Relative humidity expresses the degree of saturation of the air as a ratio
of the actual (e_a) to the saturation (e_s) vapour pressure at the same
temperature.
Parameters
----------
e_a : ... | a1a37d8273628e2ec51da7c08acf1f37c08b338f | 661,289 |
def is_number(x):
"""Check is a number."""
if isinstance(x, (int, float)):
return True
else:
return False | 6429c9337227dc7515c910a3d1c2c97004e26397 | 661,290 |
def add_data_args(parser):
"""Train/valid/test data arguments."""
group = parser.add_argument_group('data', 'data configurations')
group.add_argument('--model-parallel-size', type=int, default=1,
help='size of the model parallel.')
group.add_argument('--shuffle', action='store_t... | 1140d088daefdc59fa9aada435e229f41f606594 | 661,291 |
def get_paths(rlz):
"""
:param rlz:
a logic tree realization (composite or simple)
:returns:
a dict {'source_model_tree_path': string, 'gsim_tree_path': string}
"""
dic = {}
if hasattr(rlz, 'sm_lt_path'): # composite realization
dic['source_model_tree_path'] = '_'.join(r... | 3fef9c612bbb22c818b43284ee72d08e40640a7a | 661,293 |
from textwrap import dedent
import traceback
def format_exception_trace(exception: BaseException) -> str:
"""
Formats the traceback part of an exception as it would appear when printed by Python's exception handler.
Args:
exception: The exception to format
Returns:
A string, usually ... | c5785ee85d914ebdb241c72e034e9268a2304372 | 661,294 |
def sub_group_lines(lines):
""" Splits lines delimited by empty lines, groups split lines into lists.
Args:
lines (list): A list of lines seperated by empty lines.
Returns:
A list of lists of grouped lines.
"""
groups, sub_group = [], []
for line in lines:
if len(line... | 70a946509f89685f3262d709c29ee04370ce18c6 | 661,297 |
def batch_cmd_create_irf(
cwd,
mc_gamma,
mc_proton,
mc_electron,
output_irf_file,
dl3_config
):
"""Create batch command to create IRF file with sbatch."""
return [
"sbatch",
"--parsable",
"--mem=6GB",
"--job-name=irf",
"-D",... | b11b0cc046b9452f3b4b211a1df5788acb19c81e | 661,299 |
def greeting(name: str) -> str:
"""
Build the greeting message
"""
return 'Hello, ' + name + '!' | d6665cf26570dc93208b2f9b98de61ff8cab1a14 | 661,300 |
def get_linear_magnitude_scaling(scale_factor: float):
"""
Get a linear magnitude scaling function, to correct magnitude.
Parameters
----------
scale_factor : float
The scale factor, according to the definition given in STDI-0002.
Returns
-------
callable
"""
def scale... | ef2ded49ce6f0c7e38fcbd9ff8ab7b4352bce56c | 661,301 |
from functools import reduce
def deepgetattr(obj, attr, default=None, sep="."):
"""Recurse through an attribute chain to get the ultimate value."""
return reduce(lambda o, key: o.get(key, default), attr.split(sep), obj) | 471a6a6407e9e77e8ab6d1eb804fd905e09a721c | 661,304 |
def findCmdLineSwitch(argList, switch, ignoreCase=True):
"""
Argument List에서 command switch를 찾는다.
optViewFields = '/view_fields:'
optDeletedRecords = '/deleted_records'
argv = 'SQLiteParser.py external.db files /view_fields:_data,date_modified,date_added /deleted_records'.split()
v1 = findCmdLi... | 693d160bc21002b3d48775d70d6fa50a570b0fa5 | 661,307 |
def tio_is_attribute(tree_item):
"""
Returns 'True' if the tree item object is an attribute of the parent
opposed to e.g. a list element.
"""
if tree_item.is_attribute is None:
return ''
else:
return str(tree_item.is_attribute) | 914e150d257cacb8c89c48b94607d773a0736fe5 | 661,310 |
def evaluate(conf_matrix, label_filter=None):
"""
Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`.
Args:
conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts.
label_filter: a set of gold... | 5c3284a1647cfa336ec7170b35f7d702d1538c21 | 661,314 |
def lists_to_dict(list_keys, list_values):
"""two ordered lists to a dict where list_keys are the keys and list_values
are the values
Inputs:
list_keys - a list of n unique elements, where n = 0, 1 or many
list_values - a list of n elements
Returns:
a dict of ... | 15e679be617a5a3e9210ba15d12c605dbffa1686 | 661,315 |
def functionIsCompilable(f):
"""Is a python function 'f' compilable?
Specifically, we try to cordon off the functions we know are not going to compile
so that we can just represent them as python objects.
"""
# we know we can't compile standard numpy and scipy functions
if f.__module__ == "nump... | c6b7dd023aa4f3c00fcf04f33d3e2085d5e5bbaa | 661,317 |
def list_files(root, extension, parts):
"""Construct files from root, parts."""
files = [root + part + extension for part in parts]
return files | 59335ad99a996135ca61468ff6f51f0f553af8f3 | 661,318 |
def converge_lists(list_to_converge):
"""
Function to flatten and remove the sublist created during future obj
Args:
list_to_converge (list): arg list of lists, eg: [[1,2],[3,4]]
Returns:
list (list): return converged list eg: [1,2,3,4]
"""
return [item for sublist in list_to_co... | 7ff1db816c1e8b15909b386d829f3237b672bdf8 | 661,320 |
import asyncio
def _get_event_loop() -> asyncio.AbstractEventLoop:
""" This simply wraps the asyncio function so we have typing for autocomplet/linting"""
return asyncio.get_event_loop() | d7b90d74c3ce7445e047af576e4d172e480da597 | 661,321 |
def spaceHolder(response):
"""Return the response without parsing."""
return response | 567741a26d4d2dcb2794d550265bc45fda17e72d | 661,322 |
def get_schedule_v(df):
"""換気スケジュール
Args:
df(DateFrame): スケジュール
Returns:
ndarray: 換気スケジュール
"""
return df['換気'].values | 4395cf20666cb87da294d8f7743625194354bd90 | 661,324 |
from typing import List
def bert_preprocess(texts: List[str]) -> List[str]:
"""
Apply preprocessing appropriate for a BERT (or BERT-based) model to a set of texts.
Args:
texts: Texts to preprocess.
Returns:
List of preprocessed texts.
"""
# BERT truncates input, so don't pass in ... | 0414ed343cbfc2f662c33f7a7b5b943f01d48823 | 661,325 |
def projection_dict(projection):
"""Get a projection dictionary from a list of attribute names to project.
Args:
projection: List of string names of attributes to project.
Returns:
Dictionary like {'attr1': 1, 'attr': 1, ... }.
"""
if projection:
return dict(zip(projection, [1]... | 67e7755cb522dc9861c81a2f73f2c5fe1e87bffe | 661,327 |
def datetimefilter(value, format='%d/%m/%Y at %H:%M:%S'):
"""Convert a datetime to a different format."""
return value.strftime(format) | 30441124d8138807b3f4ac5b40d960337a1963b2 | 661,330 |
def filterNone(l):
"""Returns the list l after filtering out None (but 0"s are kept)."""
return [e for e in l if e is not None] | 0e5be1ad0e2127d47cbd9f73e4eda89b8aa35c1b | 661,333 |
from pathlib import Path
import re
def get_compressed_path(path, is_obs=None, compression='gz'):
"""Get the compressed path corresponding to a RINEX file after compression.
Parameters
----------
path : path or str
Path to the RINEX file being compressed.
is_obs : bool, optional
Wh... | fda088c76792cfa7bd9d19fbfb9edd86159b8306 | 661,340 |
import torch
def kron_einsum_batched_1D(A: torch.Tensor, B: torch.Tensor):
"""
Batched Version of Kronecker Products
:param A: has shape (b, c, a)
:param B: has shape (b, c, k)
:return: (b, c, ak)
"""
res = torch.einsum('ba,bk->bak', A, B).view(A.size(0), A.size(1)*B.size(1) )
# ... | c31ed2363f2c5a240d366fb4315080e06903dca5 | 661,341 |
import math
def generate_equator(step=0.5, type='equ'):
"""
step is in degrees
types:
equ = celestial equator
ecl = ecliptic
gal = galactic equator
"""
eps = math.radians(23.4392911)
se = math.sin(eps)
ce = math.cos(eps)
d = 0.
points = []
while d <= 360... | 1f59eeb9f825d549fa5795734fd97eb571b97f46 | 661,344 |
import string
def removePunctuations(target):
"""
this function takes in a string, and returns it after removing all
leading and trailing punctuations
string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
logic: to find a starting index and ending index to slice the string
"""
# initialise... | 11e810e10ed39748822c65112e7732ac94d23423 | 661,349 |
import tempfile
import re
def read_xyz(datapath_or_datastring,
is_datafile=True):
"""
Read data in .xyz format, from either a file or a raw string.
:param (string) datapath_or_datastring: Either the path to the XYZ file (can be relative
or absolute... | 5ade25ae41290b465a5e7377ef937c2ebf9639ef | 661,355 |
def get(
coin,
in_coin,
try_conversion=None,
exchange=None,
aggregate=None,
limit=None,
all_data=None,
to_timestamp=None,
extra_params=None,
sign=None,
):
"""
Get open, high, low, close, volumefrom and volumeto from the dayly
hi... | 526aa2b05667d5b5f6b6cf4afe1d798aafc18f50 | 661,356 |
def shared_lib_name(group_name: str) -> str:
"""Given a group name, return the actual name of its extension module.
(This just adds a suffix to the final component.)
"""
return '{}__mypyc'.format(group_name) | b4886edd8c7c4ee39215f2ed4d1d9ff7ba568924 | 661,358 |
def format_alignment(align1, align2, score, begin, end):
"""format_alignment(align1, align2, score, begin, end) -> string
Format the alignment prettily into a string.
"""
s = []
s.append("%s\n" % align1)
s.append("%s%s\n" % (" "*begin, "|"*(end-begin)))
s.append("%s\n" % align2)
s.appe... | 490fda758e5c8d8dd9f4a7bbdf1f092da474c86d | 661,362 |
def transform_to_bytes(content: str):
"""
Transform a string to bytes
Parameters
----------
- content (str): The string to convert
Raises
------
ValueError: the string is not valid
Returns
-------
- bytes: the converted string in bytes
"""
if isinsta... | cc3084c84444519f04c42a4f721fdd2272852deb | 661,363 |
def get_input(question: str) -> int:
"""Get input (int) from user
returns int"""
while True:
try:
value = int(input(question))
if value < 0:
print("Input must be a positive integer, try again: \n")
continue
break
except... | 41f25aae4e4992f490b22e24b9b6b0f3633e0662 | 661,365 |
def get_pausers(df):
"""
Filters the DataFrame for paused (begun but did not finish) replies.
:param df:
:return:
"""
return df[df['dispcode'] == 22] | ed5995a25de17b115633c72101ffa83a151bf3c7 | 661,366 |
def non_binary_search(data, item):
"""Return the position of query if in data."""
for index, val in enumerate(data):
if val == item:
return index
return None | 1bc82832937e1dff695b4f37f75565c17bfc6d9f | 661,367 |
def count_noun(number, noun, plural=None, pad_number=False, pad_noun=False):
"""
EXAMPLES::
sage: from sage.doctest.util import count_noun
sage: count_noun(1, "apple")
'1 apple'
sage: count_noun(1, "apple", pad_noun=True)
'1 apple '
sage: count_noun(1, "apple", p... | 23f40c44d16557b07e7c01deb7537cfdeebc2f1a | 661,368 |
def get_dim_order(x, y, z):
"""
Returns a tuple with the order of dimensions. Tuple can be used with
DIM_ROT.
"""
if x <= y and x <= z:
if y <= z:
return ('x', 'y', 'z')
else:
return ('x', 'z', 'y')
elif y <= x and y <= z:
if x <= z:
... | 1e867a12d130410f2ab5fdc5343bd87d41f3e45e | 661,369 |
from typing import List
from typing import Dict
def content_check(data: List[Dict[str, str]], check: str,
json_file: str, msg: str) -> bool:
"""
Checks whether a dictionary contains a column specific to expected data and returns
a corresponding boolean value. This avoids writing files of... | e4ce5389fae39fb36743d81ca5171534202678ec | 661,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.