content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _parse_boolean(value):
"""
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
"""
if not value:
return False
try:
# Lower string to check known "false" value
value = value.lower()
return value not... | 500ec0ae29f6056e6ce13c49889cea27e4e48644 | 597,429 |
def parameter_directmodel_extraction(pars):
"""Extraction of parameters from directmodel parameters."""
perts_info = [(e[0], e[2]) for e in pars[0]]
format_pars = [(e[0], e[2]) for e in pars[1]]
models_pars = [(e[0], e[2]) for e in pars[2]]
sampling_pars = [(e[0], e[2]) for e in pars[3]]
scorer_... | 26a82c66531afd9410ffab33606b8851cef18303 | 597,430 |
def evaluate(model, x, y, add_metrics={}):
"""Evaluate model performance
Args:
model: Keras model
x: model inputs
y: model targets
add_metrics: additional metrics
Returns:
A dictionary of type: <metric>: <value>
"""
keras_metrics = {name: metric
... | d69ab59788f9219ac8c207c7538346175bc0fb84 | 597,432 |
def uniform_stress(F, A):
"""Returns stress assuming uniform distribution in cross section
:param float F: Force
:param float A: Cross section area
:returns Stress
:rtype: float
"""
return F / A | d060f938c139a4ee5c58756660dd50ca085a0b61 | 597,434 |
def from_module(module_name):
"""
:samp:`Predicate for module-name detection.`
::
f(cls) = cls.module_name == module_name
:param module_name: the module-name in the detection
:return: lambda for module-name detection
"""
return lambda cls: cls.__module__.startswith(module_name) | 8413b57175bb82f0ed6ac91bd3d6c289121ca233 | 597,436 |
from typing import Union
def elapsed2string(tm: Union[int, float, str]) -> str:
"""Return elapsed time as friendly string representation
Arguments:
:param tm: (float|str): is a number of seconds
:return str: A string with the number of minutes and hours represented
"""
if isinstan... | c1fde9e56394bd49013b5350f6b1d91558a077ab | 597,437 |
def perm(lst):
""" Returns a list of all permutations of lst."""
if len(lst) == 1:
return [lst]
result = []
for e in lst:
without_e = [x for x in lst if x != e]
sub_answer = perm(without_e)
result.extend([[e] + sub for sub in sub_answer])
return result | 0f58dd885e023376fdd13374f73d95acd76077af | 597,439 |
def tolist(item):
"""
tolist wraps a single value in a list, or converts the item to a list
"""
return item if type(item) == list else list(item) | 585ce9fbdaa51a06fadc526b689d0b376251aceb | 597,442 |
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
x = round(x/step)*step
# Avoid "negative zero" (-0.0), which is different from +0.0 by IEEE standard
if x == 0: x = abs(x)
return x | 0fea822580ece371c462096641b8221adf17d862 | 597,444 |
def CalculateAverageMolWeight(mol):
"""
Calculation of average molecular weight. Note that not including H
Parameters:
mol: rdkit molecule
Returns:
AvgMolWeight: Average Molecular weight
"""
MolWeight = 0
for atom in mol.GetAtoms():
MolWeight = MolWeig... | 96b8c77951e5b831bb9f5927e7e648f42a88a1f0 | 597,445 |
def search(value, node):
"""
Search for element in the linked list
:param value: value to look for
:param node: value of head node, start of list
:return: bool: weather or not element is in the list
"""
if node is not None: # iterate through while valid nodes
if node.value == value... | 71e842d31310364cf40c1ece73b46b252cc7514b | 597,448 |
def check_layer_state(fileContainer,layerName):
""" Checks is layer "layerName" exists.
Returns True if it exists, and False otherwise. """
for layer in fileContainer.layers:
if layer.dxf.name == layerName:
return True
return False | 59584745c5ba33ed97a2b369df83528b7c14e15a | 597,454 |
def geoPointInsideBox(p, edges):
"""
returns True only if p lies inside or on the sides of box
"""
y,x = p
(y0,x0),(y1,x1) = edges
if y0>y1:
y0,y1 = y1,y0
if x0>x1:
x0,x1 = x1,x0
return x0<=x<=x1 and y0<=y<=y1 | 1b4a99fc6e148db71d575a11d0e0fbdfef4cbfd0 | 597,455 |
def to_lower(inp):
"""
Recursively convert inputs to lowercase strings, except if None.
Parameters
----------
inp : str or list of str
Object to be converted to lower.
Returns
-------
str, list or None
"""
if inp is None:
return None
if isinstance(inp, list... | 9898f34e08569eacb47fe59af4310f67981fd347 | 597,457 |
import itertools
def limit(iterator, n=None):
"""Produce a limited stream of values from an iterator.
If `n` is 0 or None, don't limit the iterator at all.
:param iterator: An iterator of values.
:param n: The maximum number of values to produce.
:yield: The first (at most) `n` values from the i... | da9d62cdb3e877b04965b048bdd7cc5d203e6786 | 597,459 |
def normalize_box(box,w,h):
""" Input: [ymin, xmin,ymax,xmax]
Output: normalized by width and height of image
"""
nbox = box.copy()
nbox[:,0] = nbox[:,0]/h
nbox[:,1] = nbox[:,1]/w
nbox[:,2] = nbox[:,2]/h
nbox[:,3] = nbox[:,3]/w
return nbox | b41ccd09fa361df7715daa8d47061d913c066460 | 597,462 |
import math
def to_radian(degree: float) -> float:
"""
Args:
degree(float): degre value to convert to radian
Returns:
float: radian value
"""
return degree * math.pi / 180.0 | eb7e8d44d523787a3d7120256c8ee251fa7df3fd | 597,464 |
def merge(a, b):
"""Shallow merge two dictionaries"""
r = a.copy()
r.update(b)
return r | 4f58f616271688b77925cce1407b86e1cf94362c | 597,469 |
def get_protocol(path: str) -> str:
"""Return fsspec filesystem protocol corresponding to path
Args:
path: local or remote path
Returns:
"file" unless "://" exists in path, in which case returns part of
path preceding "://"
"""
if "://" in path:
protocol = path.spli... | a6434e814799214b44938b4f9110bac164eec8ed | 597,477 |
def escape(keyword):
"""
Escape the backtick for keyword when generating an actual SQL.
"""
return keyword.replace('`', '``') | 50fbd9098cb8af1f1ca9128a9cfe751f78c52d24 | 597,478 |
def lcm(x, y):
"""Calculates least common multiple of two integers x and y."""
assert isinstance(x + y, int), 'Values must be integers!'
lcm_value = x if x > y else y
while lcm_value % x or lcm_value % y:
lcm_value += 1
return lcm_value | eaed1af1ab810a8ee19b7c3f944ddd859d5210a2 | 597,481 |
def get_csv_with_rev_path(csv_file):
"""Takes a csv file path and returns the name for a new version of the
file, after addition of columns with info about reverse search results.
"""
return csv_file.rsplit('.', 1)[0] + '_1.csv' | efc926ade4d6b83a1b146a0d92a1459499063594 | 597,482 |
def index_name_if_in_list(name, name_list, suffix='', prefix=''):
"""
Find a unique name by adding an index to the name so it is unique within the given list.
Parameters:
name (str): Name
name_list (iterable): List of names that the new name must differ from.
suffix (str): The suffi... | ea8075d129dd42094ef3bebef3de6d88612e97e5 | 597,486 |
def Power_Calc(Vcell, i):
"""
Calculate power.
:param Vcell: Vcell Voltage [V]
:type Vcell : float
:param i: cell load current [A]
:type i : float
:return: cell power [W] as float
"""
try:
result = Vcell * i
return result
except TypeError:
print(
... | be6bd75a37f649d8a1b6efc027670c5e67874d22 | 597,491 |
def bnds(val, lower, upper):
"""Make sure a value is between the bounds, or else it is None"""
if val is None:
return None
if val < lower or val > upper:
return None
return val | 63a8e07bde5f60bf5419929f5a26ec1149b2988d | 597,492 |
def get_scaled_action(action):
"""Get full action, scaled from [0, 1] to the maximum values allowed by the environment/simulator/car."""
# action = throttle, brake, steering
min_steer = -1.0
max_steer = +1.0
return [action[0],
action[1],
(action[2]*(max_steer-min_steer))+min_... | 0f1401fd34f1f41f30a18c9c0c655db710f3e03d | 597,493 |
def get_nmods(mod_seq, mod_str="Oxidation"):
"""
Get the number of modifications.
Args:
mod_seq: str, modified sequence string
mod_str: str, modification string to count
Returns:
int, number of mods seen in mod_seq
"""
return mod_seq.count(mod_str) | 4d31d9d5f590265c0cd87431d1c57ca25b9afd9b | 597,495 |
import re
import fnmatch
def make_regex(pattern: str, algorithm: str) -> str:
""" Transform a pattern to a regex pattern.
Supported algorithms;
- literal
- wildcard
- regex
- regmatch
:param pattern: The pattern to be transformed.
:param algorithm: The algorithm... | 87e611ad62f0bbac058a34fe4a909b9fbc9d9114 | 597,500 |
def multiple_shape(shape, stride):
"""
Given a shape (tuple), it returns the closest larger bounding box whose
sides are multiple of stride
"""
return tuple((s + (stride - 1)) // stride * stride for s in shape) | 3348c9ae147fd96f7782c8c2c4fb21bbef944681 | 597,503 |
def binary_search(lst: list, n: int) -> int:
"""Search any element in a list using binary search and return its index
or -1
Args:\n
lst (list): List of elements
n (int or any): element to find
Returns:\n
int: index of the element
"""
left_index = 0
right_index =... | c430c8892eb4bc322e8e7223f5a12d626b7b074c | 597,507 |
from urllib.error import HTTPError
from urllib.request import urlopen
def is_private(baseurl, package):
"""Tells if a given package (with a namespace) is public or private
This function checks if a fully qualified package in the format
``<namespace>/<name>`` is publicly accessible. It does this by tryin... | 8badf6b22ea582e22bb648d937738b9b21166284 | 597,509 |
def callTieBreak(obj, trackSubset, totNumTracks, distanceRatio):
"""Calls tieBreak() for multiprocessing
Parameters
----------
obj : btengine
The current btengine object (self)
Everything else same as btengine.tieBreak()
"""
return obj.tieBreak(trackSubset, totNumTracks, distanceRatio) | 41c872e1a5ad3bc3a49cf1fb1b21db44f45fdb6e | 597,513 |
def eh_posicao(pos): # universal -> booleano
"""
Indica se o argumento introduzido e uma posicao de um tabuleiro 3x3.
Argumentos:
pos - Argumento que sera analisado.
Retorno:
True - O argumento for uma posicao de um tabuleiro 3x3.
False - O argumento nao e uma posicao de um t... | c3c2c143df851b960dd69f18cfc83522f3086bb4 | 597,518 |
def _get_python_object_str(item):
"""Returns the Python Object represented as a String (used in toString)"""
return str(item) | ca2f348bfdba3080b8b5cfb4036311abf1160154 | 597,520 |
from typing import Set
def print_calltree(calldict: dict):
"""Print a space-indented recursive tree.
An asterisk after a name indicates the function has already been traversed.
"""
print('[+] Printing call tree with %d functions:' % len(calldict))
# It looks nicer to start from obvious entry poin... | 0c621b0d580d9e345f555532b1ba01af3a4aa8d6 | 597,525 |
def id_or_nid(song_dict):
"""Equivalent to ``d.get('id') or d['nid']``.
Uploaded songs have an id key, while AA tracks
have a nid key, which can often be used interchangably.
"""
return song_dict.get('id') or song_dict['nid'] | 13d3ba7be0bb4f7b258c89bd9bf52b1290c02a67 | 597,533 |
import torch
def bdiag_prod(M1, M2):
"""Computes matrix-matrix product of
two block matrices containing only
diagonal submatrices.
Input shapes: (N2, P, N1), (N1, P, N3)
Output shape: (N2, P, N3)"""
assert M1.size(2)==M2.size(0), "Dimension 2 of M1 does not match dimension 0 of M2"
asser... | 4ce7bd5fa608b7a3559752722f8f2c4db28d711d | 597,534 |
def update_c_tools_version(main, file):
""" Update Version import
"""
if main.replace_in_file(file, "from conans.model.version import Version", "from conans.tools import Version"):
main.output_result_update(title="Update 'Version' import")
return True
return False | 12592d0496273ac42c0e26a7c4481255013cb4e0 | 597,536 |
def get_mean(a, b):
"""
Find the mid point of two points
Inputs:
- a, b: floats
Outputs:
- the coordinate of the mid point: float
"""
return (a + b) / 2 | 14b4af9016dcce4f5e7bf31ec595c6cdacf33e37 | 597,539 |
def tag_in_tags(entity, attribute, value):
"""
Return ``True`` if the provided entity has a tag of value in its
tag list.
"""
return value in entity.tags | 69ceab42b86d83b12f24fda67e0b9f5582ef259b | 597,540 |
def upper_first_letter(name):
"""Return name with first letter uppercased."""
if not name:
return ''
return name[0].upper() + name[1:] | 0d1ad5b57f5f08e9c1427e4f74e522922db7bb58 | 597,541 |
def check_prev_char(password, current_char_set):
"""Function to ensure that there are no consecutive
UPPERCASE/lowercase/numbers/special-characters."""
index = len(password)
if index == 0:
return False
else:
prev_char = password[index - 1]
if prev_char in current_char_set:
... | e74fe737d0be6c13522f839305dc315689a5575c | 597,551 |
def _split_ports_per_fabric(slot_grouping, fabric_data):
"""Splits the slots per fabric which are to be placed on the same VIOS.
:param slot_grouping: The slots which are to be placed in the same vios
Ex:
[3, 6]
Here the slots 3 and ... | bf5267f1a1b9a97b7e0ed90ed0fd579c423e6c69 | 597,553 |
def mean(vector):
"""Calculates mean"""
list_vector = list(vector)
sum_vector = sum(list_vector)
len_vector = float(len(list_vector))
mean_final = sum_vector/len_vector
return(mean_final) | 1a79c41ac8214ac12c9f0f9b219d5b5c4bcfa645 | 597,555 |
def coffeelint_parser(stdout, stderr, previous_reports=None):
"""
Example summary line:
✗ Lint! » 98 errors and 0 warnings in 41 files
"""
lines = stdout.split('\n')
summary_line = lines[-3].split(' ')
total_errors = int(summary_line[3])
total_warnings = int(summary_line[6])
return {... | 87d4f8a2b4c457cfaba6c6fdb558d979ea238fa8 | 597,558 |
def _generate_args_view(args, kwargs):
"""Generate a string representing the arguments given.
All arguments and keyword arguments are separated by ", ".
All keyword arguments are in the form name=value.
:param args: a tuple containing the arguments
:type args: tuple
:param kwargs: a dict containing key/value pai... | 5a49ed140163c922849b59988211ed5b6208ef62 | 597,559 |
def named_capturing(pattern, name):
""" generate a named capturing pattern
:param pattern: an `re` pattern
:type pattern: str
:param name: a name for the capture
:type name: str
:rtype: str
"""
return r'(?P<{:s}>{:s})'.format(name, pattern) | 716d460707c4dc96e438ffefb7be0a50915e6386 | 597,561 |
def is_checkpoint(block_number: int, epoch_length: int) -> bool:
"""
Return ``True`` if the given ``block_number`` is a checkpoint, otherwise ``False``.
"""
return block_number % epoch_length == 0 | 4269c64f598d993d631a9ad09f73a67d5588cf35 | 597,566 |
def clean_data(data, missing_prop=0.25, max_stay=365):
"""Get rid of the columns where enough data is missing, and remove records
that last too long or have any missing data."""
for col in data.columns:
if data[col].isnull().sum() > missing_prop * len(data):
data = data.drop(col, axis=1... | fde963f7a43933530165dc9930840d1a4c11cc36 | 597,568 |
def compose(*funclist):
"""
Returns the composition of a list of functions, where each function
consumes the return value of the function that follows. In math terms,
composing the functions f()
:param funclist: List of functiosn [f0, f1, f2, f3, ... fn-1]
:return: New function f(x) = f... | d54327114e18f59693cec7ee5693435f6dca94a7 | 597,569 |
import time
def date_to_timestamp(date):
"""
Converts date instance to unix timestamp.
:param datetime.date date: Date instance.
:return: Unix timestamp.
:rtype: int
"""
return int(time.mktime(date.timetuple())) | dae4c2fe29f48c3b9ae03ab3eefb569a0c4cc1ba | 597,571 |
def craft_url(word: str, locale: str, raw: bool = False) -> str:
"""Craft the *word* URL for the given *locale*."""
url = f"https://{locale}.wiktionary.org/w/index.php?title={word}"
if raw:
url += "&action=raw"
return url | 61a2c08a081b8411d5d1d790663a216238efffe7 | 597,572 |
import re
def normalize(text):
"""
Normalizes the text by removing all punctuation and spaces as well as
making the string completely lowercase.
"""
return re.sub(r'[^a-z0-9]+', '', text.lower()) | 96b200d7b66d4a01937be993082a00e469a36144 | 597,573 |
import logging
def get_logger() -> logging.Logger:
"""Returns the endrpi logger."""
return logging.getLogger('endrpi') | 6257ae3d93f16540ecc84110b72cb14dda83b95f | 597,574 |
def get_package_link(config, pkg, os_name, os_code_name, os_arch):
"""
Get an informational link about a package.
This function uses the package_dashboards configuration to attempt to create
a URL to an information page regarding a package. If it is unsuccessful, the
URL to the package itself is re... | 3a94bb3cb2d0376df687129dad908bd68001e9dc | 597,575 |
import inspect
def parametrize(param_name, params):
"""Decorator for benchmarking over a set of parameters.
Parameters
----------
param_name : str
Parameter name. Must be one of the arguments of the decorated function.
params : list[any]
List of values to benchmark for the given p... | e5a342f025859515b46881651c79ed28a2471c06 | 597,576 |
import errno
def parsettestcases(path):
"""read a .t test file, return a set of test case names
If path does not exist, return an empty set.
"""
cases = []
try:
with open(path, "rb") as f:
for l in f:
if l.startswith(b"#testcases "):
cases.a... | bebfbbc5e73ef9ce549dbafc4ae36656279c031d | 597,577 |
def checkIdenticalExistingVectors( newgraphs, vectors, v ):
"""
Checks if there exists a vector from 'vectors' corresponding to one of the
graphs from 'newgraphs', that is equal to v (ie, checks if a vector equal to
v has already been generated). If such vector exists, it returns True, and
else it r... | 66797a351bf1666e59630789aa2aefbda9a820d3 | 597,578 |
def add_intf_to_map(intf_map, bridge_or_bond, config_type, intf_index,
lacp=False):
"""Adds an interface to the interface map, after performing validation
interface_map has a specific structure. this method checks and inserts
keys if they're missing for the bridge or interface being add... | 259de46e582882355042d9ad266d09aad43f0157 | 597,585 |
def get_match(match, index, default=''):
"""
Returns a value from match list for a given index. In the list is out of
bounds `default` is returned.
"""
if index >= len(match):
return default
else:
return match[index] | 8669380d3d5e3379d7169754c284498872f46570 | 597,586 |
def convective_heat_transfer_coefficient_simplified_summer(v_a: float) -> float:
"""
対流熱伝達率[W/(m2・K)]の計算(簡易計算、夏期条件)
:param v_a: 通気層の平均風速, m/s
:return: 対流熱伝達率, W/(m2・K)
"""
return 4.113 * v_a + 1.844 | 2c9153cdbb2c94e1349291c115a335c42c6f65c2 | 597,590 |
def bytes_to_str(byte_count):
"""pretty print string for bytes"""
if byte_count > 1024 * 1024 * 1024:
return str(int(byte_count / 1024 / 1024 / 1024)) + "GiB"
if byte_count > 1024 * 1024:
return str(int(byte_count / 1024 / 1024)) + "MiB"
if byte_count > 1024:
return str(int(byte_... | b4700024b1eaaa0258512ef00d1b757429a9e2ad | 597,591 |
def _extend_control_events_default(control_events, events, state):
"""Default function for extending control event sequence.
This function extends a control event sequence by duplicating the final event
in the sequence. The control event sequence will be extended to have length
one longer than the generated e... | 3dc3a56503d2408c657e8ca0925fa7000f566c33 | 597,592 |
def dec(x):
"""
Decrements the value of x
>>> dec(5)
4
"""
return x - 1 | 91c49278b7adf3eb60372ad58084a302bb882e27 | 597,593 |
def export_3dpdf(
client,
file_=None,
filename=None,
dirname=None,
height=None,
width=None,
dpi=None,
use_drawing_settings=None,
sheet_range="all",
):
"""Export a model to a 3D PDF file.
Args:
client (obj):
creopyson Client.
`file_` (str, optional... | 4f6a0b11b7426cc443766f60182210d40d58dee1 | 597,598 |
import importlib
def import_or_raise(library, error_msg):
"""Attempts to import the requested library. If the import fails, raises an
ImportError with the supplied error message.
Args:
library (str): the name of the library
error_msg (str): error message to return if the import fails
... | b1a2fb3aa820aec806274589c4fc9e47c137f39f | 597,605 |
def return_start_end(seq):
""" Returns the start and end indices of amino acids """
start = next(idx for (idx,s) in enumerate(seq) if s != '-')
try:
end = start -1 + next(idx for (idx,s) in enumerate(seq[start:]) if s == '-')
except StopIteration:
end = len(seq) - 1
return star... | 8c28692661d19a8272b563551e43aa1599e79852 | 597,606 |
def _html_decode(text):
"""
Decode HTML entities used in TiddlyWiki content into the 'real' things.
"""
return text.replace('>', '>').replace('<', '<').replace('&', '&').replace('"', '"') | f20d8534741392e1faf52073b5500c530143c157 | 597,607 |
def cummean(series):
"""
Calculates cumulative mean of values. Equivalent to
`series.expanding().mean()`.
Args:
series: column to compute cumulative mean for.
"""
means = series.expanding().mean()
return means | aafd970f18ca498058715697c64d943222508088 | 597,614 |
def image_person_object_factory(image_id, person_id):
"""Cook up a fake imageperson json object from given ids."""
personimage = {
'image_id': image_id,
'person_id': person_id
}
return personimage | 4aa59382f39b9acb5869b1839ab5cd5240404972 | 597,615 |
def _cut_string(string: str, from_line: int, to_line: int, from_col: int, to_col: int):
"""Cut a string and return the resulting substring.
Example:
Given a *string*,
"xxxxxxxxxxx
xxxxxAXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXBxxxx
xxxx"
, to cut a substring from... | 5a33fd2e2fbe7d4d1acc84e2fc598cb889c99879 | 597,619 |
def constant(value: float = 0):
"""
A constant float.
Parameters
----------
value : float
The float value.
"""
return value | de13e64083765fbd429e66f7c55afa887fcbd34f | 597,626 |
def replace_staff_placeholder(user_list, staff):
"""
Replace the staff placeholder with the actual list
of staff members in the user_list.
"""
if isinstance(user_list, str):
user_list = [user_list]
# We might end up in this case when one hub references the config of another deployed hub... | e18b852a1bb99435c69c42272eef46488392478b | 597,627 |
def max_segment_intersections(segments):
"""
Returns number of maximum intersecting segments
"""
diff = {}
for segment in segments:
diff[segment.start] = diff.get(segment.start, 0) + 1
diff[segment.end] = diff.get(segment.end, 0) - 1
max_intersections = 0
current_intersection... | 1fc4780778a603a962b1b6e858848428008a12b1 | 597,630 |
from datetime import datetime
from typing import Dict
def is_in_semester(
date_time: datetime,
semester_info: Dict,
) -> bool:
"""
Check if a datetime is within the first and last days of the semester.
:param date_time: the date/time
:param semester_info: the semester info
:return True if... | 4891bc7db97175b661a7803c88ed9e74e222791a | 597,631 |
def isdatadescriptor(object):
"""Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
... | 416e6d7167f541ee010e862be09b1f84fd046079 | 597,635 |
def tokenize_timeperiod(timeperiod):
"""
method breaks given timeperiod into 4 parts: (year, month, day, hour)
for instance: daily 2015031400 -> ('2013', '03', '14', '00')
hourly 2015031413 -> ('2013', '03', '14', '13')
monthly 2015030000 -> ('2013', '03', '00', '00')
... | 2c5208d825566426076043f3100699649b968d35 | 597,653 |
def get_indices(row_compound):
"""Finds indices of unique value/extinction objects at 'uvvis' scope
:param chemdataextractor.model.Compound row_compound : Compound containing uvvis data
:returns
list value_indices : UvvisSpectrum indices pointing to objects solely containing uvvis values
l... | 6351ce74150b06a1e87fd08d9fdcc8c52ce2a757 | 597,657 |
def select_items_by_bits(lst, i):
"""
Selects items from lst indexed by the bits in i.
:param lst: A list.
:param i: A non-negative integer whose most significant bit is at a position lesser than len(lst).
:return: A list containing all lst[k] where (i & (1 << k)) == 1.
"""
result = []
... | 32f68b32cd031ab227216cde538aa8e1a98c9322 | 597,661 |
def label(field):
"""
Construct a label for a data field suitable for use on a graph axis.
"""
if hasattr(field,'Along_name'):
return field.Along_name.nxdata
else:
return "%s (%s)"%(field.nxname,field.Aunits.nxdata) | 89e13571ad5221f6aa535fb339cabbca193384db | 597,663 |
def meanPoint(coordDict):
"""Compute the mean point from a list of cordinates."""
x, y, z = zip(*list(coordDict.values()))
mean = (float(format(sum(x) / len(coordDict), '.2f')),
float(format(sum(y) / len(coordDict), '.2f')))
return mean | b3f15e238f2ab7a5c41fada6072b3a9fd9caf6af | 597,664 |
def field_name_wo_brackets(field_name: str) -> str:
"""
Field names in a ulog message can end with [*]. This function removes the [*] at the end
"""
if field_name.endswith(']'):
return field_name[:-3]
return field_name | 8c49d330828e07c9edd4369c8c0d5c56b40500dd | 597,665 |
def center_image(image):
"""Sets an image's anchor point to its center"""
image.anchor_x = image.width//2
image.anchor_y = image.width//2
return image | 3cdb4ee68dfce8af7bd109ca6461790ecfa61f3f | 597,668 |
def check_words(words: str, text: str) -> bool:
""" Checks if the specified words are in the index card.
"""
return words.lower() in text.lower() | d6fa8398aa8fb6c448ac1bc4863ea88e977f1e47 | 597,671 |
import re
def fix_import_export_id_paths(fieldname):
"""
Fixes the id fields in import and exports, and splits field paths
on '/'.
:param str fieldname: name of the field to import/export
:return: split field name
:rtype: list of str
"""
fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', ... | d82dfb00831e1abfd7baa65078188c293c82079d | 597,672 |
import re
def get_all_local_funcs(vba):
"""
Get the names of all locally defined functions.
"""
pat = r"(?:Sub |Function )([^\(]+)"
r = []
for (_, _, _, vba_code) in vba.extract_macros():
for line in vba_code.split("\n"):
names = re.findall(pat, line)
r.extend(n... | eeb9889d230410a3f0087e039681870066f512dc | 597,674 |
def intersect_all(set1: set, set2: set, set3: set) -> set:
"""Return the intersection of all three of the given sets: set1, set2, and set3.
>>> intersect_all({1, 2, 3}, {1, 2, 3, "test"}, {1, 2, 6, 7, "test"}) == {1, 2}
True
>>> intersect_all(set(), {1, 2, 3}, {1, 2, 3}) == set()
True
>>> inter... | 805ce1170f6125eb4df74c9972e9147ffd543909 | 597,678 |
def df_row_to_com_dict(df_row):
""" From a single row of df, return comp dict
key: isotope (e.g. pu-239)
value: % mass
"""
iso_list = list(df_row)[5:]
assem_dict = df_row.to_dict()
assem_dict = {key: assem_dict[key] for key in assem_dict if key in iso_list}
return assem_dict | 7b2991d5274bb1c768d07143a3a31188443573d5 | 597,682 |
from datetime import datetime
def ut_to_dt(ut):
""" Convert unixtime to datetime. """
return datetime.utcfromtimestamp(float(ut)) | 840ba44d4c268e50944ffef821ad75f43c4bc3da | 597,684 |
def _format_tags(line, slice_):
"""
Create or format tags.
Parameters
----------
line: Line to add a tag.
slice_: Tag interval.
Returns
-------
str: formatted html tag
"""
map_formated_tags = map(lambda tag: '{}: {}'.format(tag, line[tag]), slice_)
return '<br/>'.joi... | 86d01eae1d81444183b08dc993db584ff795c6df | 597,686 |
def get_aliases_url(base_url, id):
"""
Build and return full Alias URL
"""
url = base_url + "api/snapshots/" + str(id) + "/aliases"
return url | a514aecea4caa5f7d09dbb6ec65b37e27c673e6d | 597,687 |
def _CopyFieldToProtocolBuffer(field, pb):
"""Copies field's contents to a document_pb.Field protocol buffer."""
pb.set_name(field.name.encode('utf-8'))
field_value_pb = pb.mutable_value()
if field.language:
field_value_pb.set_language(field.language.encode('utf-8'))
if field.value is not None:
field.... | 61406ff3d3e85d2f528888b5f7384bc4056e0da1 | 597,688 |
def to_proper_degrees(theta):
"""
Converts theta (degrees) to be within -180 and 180.
"""
if theta > 180 or theta < -180:
theta = theta % 180
return theta | cbc80069f0e3c07a277d3c2b54c7a26ead062bdc | 597,689 |
def is_0to255(value):
"""RGB values must be in the range 0 - 255 (inclusive)"""
return 0 <= value <= 255 | fb0fa2be671232d7aec9169c0e1fe3ffb12c1a4b | 597,690 |
def ToPowerOfTwo(bits: int) -> int:
"""
Given a number, find the next power of two that is >= to the given value.
Can be used to figure out a variable size given non-standard bit sizes in
matter: eg. a int24 can be stored in an int32, so ToPortOfTwo(24) == 32.
"""
# probably bit manipulation c... | 5912a5f2f98966320762a3be8947ab8476126d86 | 597,692 |
def is_even(k: int) -> bool:
"""Returns True if k is even, and False otherwise."""
# Reduces any number to its rightmost bit. If it is odd, that will
# complement then 1 and return 1 as a result of the bitwise AND. If
# it is even, it will return 0.
return k & 1 == 0 | cd11d0f629b9f28201731241a1f608732999c82a | 597,694 |
def orderDict(d: dict):
"""Deep sort dictionary by keys
Args:
d (dict): unsorted dictionary
Returns:
[dict]: Sorted dictionary
"""
return {k: orderDict(v) if isinstance(v, dict) else v for k, v in sorted(d.items())} | 747a60bb274c3a73b054eab78d4008a397c03de0 | 597,696 |
def sample_task(self, user_id, argument, **kwargs): # pylint: disable=unused-argument
"""
Example of a specific task inheriting from UserTask.
"""
print(f'Ran SampleTask for argument "{argument}"')
return argument | 15cc4463971831b6cc51e7c0898afb9799635a7d | 597,703 |
import inspect
def build_from_config(module, config: dict):
"""Returns an object of :class:`module` constructed from `config`.
Args:
module: A python or user-defined class
config: A python dict containing information used in the construction of the return object
Returns: An ``object`` of... | de75ff1f3f0e39c549e2a7c9a551b3a57d4d6257 | 597,704 |
def strip_hidden(key_tuples, visibilities):
"""Filter each tuple according to visibility.
Args:
key_tuples: A sequence of tuples of equal length (i.e. rectangular)
visibilities: A sequence of booleans equal in length to the tuples contained in key_tuples.
Returns:
A sequence equal ... | bd4ee5d1305299743256c16d9f8a1c9ec3e6715e | 597,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.