content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def first_not_none_param(params, default):
"""
Given a list of `params`, use the first param in the list that is
not None. If all are None, fall back to `default`.
"""
for param in params:
if param is not None:
return param
return default | c219e5b3606683dbc84ee6fe1124833304e6fa9b | 621,217 |
def get_headers(depth=1):
"""
Return the standard request headers
"""
return {'accept': 'application/json;depth=' + str(depth)} | 2e48eba547a0b9cfa6845c1599eaa610a5a97bfb | 621,220 |
def _reconstruct_token(key):
"""Reconstruct a token from a key in a graph ('SomeName_<token>')"""
if len(key) < 34 or key[-33] != "_":
return
token = key[-32:]
try:
int(token, 16)
except ValueError:
return None
return token.lower() | 1e665762e08ab9a6aa0d300d0fb49375c4b1e21e | 621,221 |
from typing import List
from typing import Union
from typing import Any
def flatten_list(lst: List[Union[List, Any]]) -> List[Any]:
"""Flatten list of lists"""
result = []
for elm in lst:
if isinstance(elm, list):
result.extend(elm)
else:
result.append(elm)
retu... | 856bbca4aa218d73f5556010ad144907df82e15b | 621,224 |
def Yindex(ell, m, ell_min=0):
"""Compute index into array of mode weights
Parameters
----------
ell : int
Integer satisfying ell_min <= ell <= ell_max
m : int
Integer satisfying -ell <= m <= ell
ell_min : int, optional
Integer satisfying 0 <= ell_min. Defaults to 0.
... | ef84c05cbab12852783bcd0b16d408ecaecec5b7 | 621,225 |
def get_profdata_file_name(trial_id):
"""Returns the profdata file name for |trial_id|."""
return 'data-{id}.profdata'.format(id=trial_id) | 7510f8cf2a0389575fd6d62f7cb159b4c8b787b9 | 621,228 |
def readList(confDict, list_in, constructor, cryomodule_entry=None):
"""
Generic function to read list of components.
Takes the global configuration dictionary, cycles through the list of components
(list of names, list_in), uses the names to identify the configuration entries in
the global dictiona... | c6f9f47f21ec23e161dda188761e57e6661eee5d | 621,229 |
def get_qstar(inv, extrapolation=None):
"""
Get invariant value (Q*)
"""
return inv.get_qstar(extrapolation) | 3e3eade71d9efcb5b63cfb2807712f46cb025985 | 621,232 |
from typing import List
from typing import Tuple
from typing import Any
from typing import Dict
def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = None
try:
instance_i = param_names.index(... | 768b5dc68f587970c2ce45f94d18ca0dea6497be | 621,233 |
def _validate_dict(s, accept_none=False):
"""
A validation method to check if the input s is a dictionary otherwise raise error if it is not convertable
"""
if s is None and accept_none:
return None
if isinstance(s, dict):
return s
else:
raise ValueError('{} is not a dictionary!'.format(s)) | 8834142153fa2cb71d4a76e6a977324a698b8723 | 621,234 |
def gcd(a, b): # (1)
"""
Returns the greatest commond divisor of a and b.
Input:
a -- an integer
b -- an integer
Output:
an integer, the gcd of a and b
Examples:
>>> gcd(97,100)
1
>>> gcd(97 * 10**15, 19**20 * 97**2) ... | 20ede08d2316bd4fefa19f76d3884f1364adff1a | 621,237 |
import re
def refind(regex, text):
"""Find a regex in some text, and return the matched text, or None."""
m = re.search(regex, text)
if m:
return m.group()
else:
return None | a20e5bf5d94ac457af093448cf7bb201a89f29a6 | 621,240 |
import csv
def parse_csv_file(file_path, expected_num_columns):
"""
Reads the specified csv file. Checks for a value number of columns in
each row. Returns the csv file values as a list of tuples.
"""
values = []
with open(file_path) as csv_file:
csv_reader = csv.reader(csv_file, del... | d9fa59aebc8215ed35397490fc6edb5b0b6d6294 | 621,241 |
def clear_sesam_attributes(sesam_object: dict):
"""
Return same dict but without properties starting with "_"
:param sesam_object: input object from Sesam
:return: object cleared from Sesam properties
"""
return {k: v for k, v in sesam_object.items() if not k.startswith('_')} | 9dc1c59cacb29b34d1f650803ad44d2febc7d940 | 621,242 |
def card(n : int, text: str) -> str:
"""Create a HTML Card"""
html = f"""
<div class='card'>
<h4 class='card_text' id='test'->{n}<h4>
<span>{text}</span>
</div>
"""
return html | e8b6776a8e23d7a08ea1ca8793502224329d26bd | 621,244 |
def sign_max(X, axis = 0, n_jobs = 1):
"""
[Added 19/11/2018] [Edited 24/11/2018 Uses NUMBA]
Returns the sign of the maximum absolute value of an axis of X.
input: 1 argument, 2 optional
----------------------------------------------------------
X: Matrix X to be processed. Must b... | a1b8e173cd16b5c3b3de75b4f2ffd4c15d8d49a6 | 621,245 |
def median(nums):
"""
Find median of a list of numbers.
>>> median([0])
0
>>> median([4,1,3,2])
2.5
Args:
nums: List of nums
Returns:
Median.
"""
sorted_list = sorted(nums)
med = None
if len(sorted_list) % 2 == 0:
mid_index_1 = len(sorted_list) ... | 1d20e6231d6658c93ded89b960ee5cdf830a197a | 621,247 |
def major_version(v):
"""
Return the major version for the given version string.
"""
return v.split('.')[0] | d23c6c91001436a6f3e26522bdfab2ec1fef926c | 621,248 |
def has22(list_one:list)->bool:
"""Returns True if the list contains a 2 next to a
2. Otherwise, the function returns False .
>>>has22([1,2,2,3])
True
>>>has22([1,2,3,4])
False
"""
if ', 2, 2' in str(list_one):
return True
elif list_one[0] == 2 and list_on... | be5554cc17b760977505120fb965aa7f9014aa6b | 621,252 |
from typing import Iterable
from typing import Any
def unique(it: Iterable[Any]) -> bool:
""" check if all elements of an iterable of unqiue
Parameters
----------
it : Iterable[Any]
The iterable to be checked for unique elements
Returns
-------
bool:
True if all elements ... | 005ad33e01f7dbdbd073aad7b3033b1c26a4ba5f | 621,254 |
def split_by_length(str, length, rejoin_with=None):
"""
split a string by a given length
"""
str_arr = []
counter = 0
while counter<len(str):
str_arr.append(str[counter:counter+length])
counter += length
if rejoin_with:
return rejoin_with.join(str_arr)
else:
return str_arr | 673d6477cd19d326d6018c0c11f4eff3dd6a833b | 621,255 |
def split(seq):
"""
Split a sequence on zeros.
The given sequence is split into chunks separated by one or more
zeros. The start (inclusive) and end (exclusive) indices of the
chunks are returned as a list of 2-tuples.
"""
indices = []
start = None
for i, s in enumerate(seq):
... | 333356062e53e056f9946af7bafa2b82d37d650b | 621,256 |
import inspect
def get_caller(offset=0):
"""
lookup the caller of the current function from the stack,
with optional offset to climb higher up the stack.
"""
_, filename, linenum, funcname, _, _ = inspect.stack()[offset]
return {'filename': filename,
'linenum': linenum,
... | ef1a763dd4ae8dbd2d2b2e6f925a3c4e330047b1 | 621,258 |
def convert_iob_to_bio(seq):
"""Convert a sequence of IOB tags to BIO tags.
The difference between IOB and BIO (also called IOB2) is that in IOB
the B- prefix is only used to separate two chunks of the same type
while in BIO the B- prefix is used to start every chunk.
:param seq: `List[str]` The l... | ee91ca5e5e500d4c6c63d52242f6f859ed4664fa | 621,259 |
def filter_measurements(measurements, csc_name, topic_name):
"""Filter full list of measurements looking for CSC plus topic name.
Parameters
----------
measurements : list[str]
The list of all available measurements.
csc_name : str
Name of the CSC to filter on.
topic_name : str
... | 2747f36a4f1d4e43af563d98c11652ed57b0dadc | 621,260 |
from bs4 import BeautifulSoup
def has_exactly_one_list_item(toc: str) -> bool:
"""Check if the toc has exactly one list item."""
assert toc
soup = BeautifulSoup(toc, "html.parser")
if len(soup.find_all("li")) == 1:
return True
return False | b3d07d618dd345ea2d491dba2b21e684b12c6925 | 621,263 |
def getCheckCategoriesTemplate(usage, galleries, ncats):
"""Build the check categories template with all parameters."""
result = ('{{Check categories|year={{subst:CURRENTYEAR}}|month={{subst:'
'CURRENTMONTHNAME}}|day={{subst:CURRENTDAY}}\n')
usageCounter = 1
for (lang, project, article) in... | 324e8da80c887c1a541d395a5d8dfaab88bea1eb | 621,264 |
from typing import List
def pascal_case_to_enum(pascal_case: str) -> str:
"""Convert PascalCase to ENUM_CASE."""
word_arrays: List[List[str]] = [[]]
for c in pascal_case:
if c.isupper() and word_arrays[-1]:
word_arrays.append([c])
else:
word_arrays[-1].append(c.upp... | edb02c6ce9c7f7ed2a727f1c22d843a326fdcb60 | 621,267 |
import threading
def thread() -> int:
"""Return thread id."""
return threading.current_thread().ident or -1 | 1ec3ff9f8405fb4b349870c273b764474d80eb2f | 621,269 |
def simple_hash(int_list, prime1, prime2, prime3):
"""Compute a hash value from a list of integers and 3 primes"""
result = 0
for integer in int_list:
result += ((result + integer + prime1) * prime2) % prime3
return result | 92594b421b98ac78eec10b3fe6eb8646d9a64161 | 621,270 |
def gen_tagset(tags):
"""Create TagSet value from a dict."""
return [{'Key': key, 'Value': value} for key, value in tags.items()] | 0c12c8a901ac52f69098c4fe73da6ecbdf0cabc7 | 621,273 |
from pathlib import Path
def project_root_dir_path() -> Path:
"""
Get the project root directory as a Path object.
Returns
-------
project root directory
"""
# root = ../..
return Path(__file__).parent.parent | c95804e79176eb7d085255e13145a6ed135aff3c | 621,280 |
def sort_by_index_key(x):
"""
Used as key in sorted() to order items of a dictionary by the @index
entries in its child-dicts if present.
"""
if isinstance(x[1], dict) and '@index' in x[1]:
return x[1]['@index']
else:
return -1 | 66e828b61119723b5cf6e556de8b572a800de38a | 621,282 |
def maybe_parentheses(obj, operator: str = " ") -> str:
"""
Wrap the string (or object's string representation) in parentheses, but only if required.
:param obj:
The object to (potentially) wrap up in parentheses. If it is not a string, it is converted
to a string first.
:param operator:... | d271649520be68ea27367b6c346058f50cee5f88 | 621,286 |
def condense_border_none(css: str) -> str:
"""Condense border:none; to border:0;.
"""
return css.replace('border:none;', 'border:0;') | b564c48f939b8413af9cb680d983d3f1238f1fd5 | 621,289 |
def flatten_obj(obj, fields, *, rest_val=None):
"""
>>> class A: pass
>>> a = A(); a.a = 1; a.b=2
>>> flatten_obj(a, ('a', 'b'))
[1, 2]
>>> flatten_obj(a, ('a', 'b', 'c'))
Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'c'
>>> flatten_obj... | 4095e44a70d7f19d702a1155825638a09c6e2084 | 621,292 |
def validate_bookcover(book_details):
"""
Check if goodreads returns a nophoto
Use open library to fetch the book cover
based on ISBN
Args:
book_details: Book info returned as json by goodreads API
Returns:
This API checks for book cover, and returns with a valid
bookco... | be7a1f242d657f4c1c8f3b894f765cf2e6887f24 | 621,293 |
def get_z(coeffs, x, y):
"""
Calculate and return the height z given the coefficients and ordinates of ax + by + c = z
:param coeffs: numpy ndarray of coefficients a, b, c, in the order (c, a, b)
:param x: x value
:param y: y vakye
:return: the calculated z value
"""
as... | e414555b052deb02928859f71ede4d1f9a2efa09 | 621,294 |
def canonicalize(doc):
"""De-duplicate environment vars and sort them alphabetically."""
spec = doc.get('spec')
if not spec: return doc
template = spec.get('template')
if not template: return doc
spec2 = template.get('spec')
if not spec2: return doc
containers = spec2.get('containers')
... | ff82171f444d692549b563bc474d15e3c778836e | 621,298 |
def count_results(performances, result):
"""Count the number of performances with the specified result"""
return len([performance for performance in performances if performance['result'] == result]) | d09df821119812806557f839da65883954831370 | 621,299 |
def logpofr_old(r):
"""
Returns the nat. logarithm of a fit to the probability of finding
a zone of density contrast r in a Poisson particle simulation
"""
# 2D
#p = -2.6*(r-1.)
# 3D
p = -5.12*(r-1) - 0.8*(r-1)**2.8
return p | 50430eff6fcfa18032fa534e31b0d8a86a2508b3 | 621,304 |
def is_broadcastable_and_smaller(shp1, shp2):
"""
Test if shape 1 can be broadcast to shape 2, not allowing the case
where shape 2 has a dimension length 1
"""
for a, b in zip(shp1[::-1], shp2[::-1]):
# b==1 is broadcastable but not desired
if a == 1 or a == b:
pass
... | ec20132aa14d68bf15065f055d6f6a638b989b8a | 621,308 |
def time_format(secs):
"""Convert seconds to h:mm:ss."""
m, s = divmod(secs, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | e3677f03917c6ba5d6aa2aa4c1d32a4f066327b8 | 621,309 |
def round_upper_bound (value):
"""
This method expects an integer or float value, and will return an integer upper
bound suitable for example to define plot ranges. The upper bound is the
smallest value larger than the input value which is a multiple of 1, 2 or
5 times the order of magnitude (10**x... | c19b1fa46391c3f3a4e15ecef6d09b394a30ee1e | 621,311 |
def ltv_predict(data, mbg, ggf, discount_rate, time):
"""
Predict dollar value of customers from today up to time t.
"""
return ggf.customer_lifetime_value(mbg,
data['frequency_cal'],
data['recency_cal'],
... | a5fef42d42c5ed98498a36aa3284d10cbf502f10 | 621,317 |
import json
def json_pretty(obj):
"""Convert obj into pretty-printed JSON"""
return json.dumps(obj, indent=4, sort_keys=True) | 2c240eb7eb0c413f3da6d3477949968ea90ef5f9 | 621,319 |
def fixed_point_integer_part(fixed_point_val: int, precision: int) -> int:
"""
Extracts the integer part from the given fixed point value.
"""
if (precision >= 0):
return fixed_point_val >> precision
return fixed_point_val << precision | 5abf5c8dc9bbb0ba24099ff35fc0128c03fc791f | 621,324 |
def select_single_mlvl(mlvl_tensors, batch_id, detach=True):
"""Extract a multi-scale single image tensor from a multi-scale batch
tensor based on batch index.
Note: The default value of detach is True, because the proposal gradient
needs to be detached during the training of the two-stage model. E.g
... | 1a389d8ff836fb08f5e5519ec5dd9336d031ec54 | 621,326 |
import csv
def parse_fastqc_result(path_to_qc_summary):
"""
Args:
path_to_qc_summary (str): Path to the fastqc report summary file.
Returns:
dict: Parsed fastqc R1 report.
All values except are either "PASS", "WARN", or "FAIL".
For example:
{ "basic_statistic... | 133de8f205a601d39d361502d3fb64edd7745433 | 621,329 |
def process_test_result(passed, info, is_verbose, exit):
"""
Process and print test results to the console.
"""
# if the environment does not contain necessary programs, exit early.
if passed is False and "spellbook: command not found" in info["stderr"]:
print(f"\nMissing from environment:\n... | 9f059e6c4bbcc3a49babab07a9cdd5d17b6e975f | 621,331 |
def get_cls_dict(category_list):
"""Get the class ID to name translation dictionary."""
return {i: n for i, n in enumerate(category_list)} | a68845e592248af809dd13be098a05137ba69ee0 | 621,334 |
import random
def get_random_int(min_v=0, max_v=10, number=5, seed=None):
"""Return a list of random integer by the given range and quantity.
Parameters
-----------
min_v : number
The minimum value.
max_v : number
The maximum value.
number : int
Number of value.
se... | fb551cbcbb8983dfada2368c17607dfad4f1aa66 | 621,336 |
def bounds4(grid):
"""Return a list of tuples reporting the min and max value of each coordinate
in the given grid.
"""
xmin, ymin, zmin, wmin = list(grid.keys())[0]
xmax, ymax, zmax, wmax = xmin, ymin, zmin, wmin
for x, y, z, w in grid:
xmin = min(xmin, x)
ymin = min(ymin, y)
... | d8fd89d3977ed0d3003ab06c4eba47889dc252b1 | 621,342 |
def dictmax(d):
""" returns key with maximum value in dictionary """
return max(d.keys(), key = lambda x: d[x]) | 47c38b4785cd7abb6128ede500e402188cc08edc | 621,343 |
def _extract_dataset_from_db(force_sets_in_db, displacements_in_db, probs_in_db=None):
"""Collect force_sets, energies, and displacements to numpy arrays.
Parameters
----------
force_sets_in_db : List of ArrayData
Each ArrayData is the output of PhonopyWorkChain.
displacements_in_db : List ... | 6d1e94ce67a4c7cc598f7b3d0e34b861582ead7c | 621,347 |
def prevent_search(relation):
"""
Used to mark a model field or relation as "restricted from filtering"
e.g.,
class AuthToken(BaseModel):
user = prevent_search(models.ForeignKey(...))
sensitive_data = prevent_search(models.CharField(...))
The flag set by this function is used by
... | b657d69eea99c62f823f6db3c5dc530cc06b03ae | 621,348 |
def head_of_all(x, l):
"""List of lists from l where x is the head of all the lists."""
return [[x] + p for p in l] | baa77bba83dca0089063a2e7801c33da75c82d58 | 621,352 |
def is_list_of(value, elem_type):
""" Is the given value a list where each element is the elem_type
:param value: The value being checked
:type value: Any
:param elem_type: The element type
:type elem_type: type
:return: True is the value is a list and each element in the list is of the given ty... | a2b6f1b4f8f6875d3a0b27f6eb8257d3bc95b35c | 621,353 |
import socket
def ipv4(value):
"""Return true if IP address v4 is valid, otherwise - false."""
try:
socket.inet_pton(socket.AF_INET, value)
return True
except socket.error:
return False | cd1722f7df7abfa3fc7ff2e1038439c5e1a17541 | 621,355 |
def one_hot_encode(label):
"""
Given a label - "red", "green", or "yellow". Returns a one-hot encoded label
"""
if label == "red":
return [1, 0, 0]
if label == "green":
return [0, 0, 1]
return [0, 1, 0] | 6c6c2e60fa90fcf1a33c8c96814910113def9699 | 621,362 |
def _string_bool(value):
"""Returns the equivalent boolean if the input string is 'true' or 'false', else no change."""
if value == 'true': return True
if value == 'false': return False
return value | e656163fbef8640e342af6b89395914662670e2d | 621,367 |
def _paginated_scan(ddb_table, filter_exp=None):
"""performs a paginated scan of the DynamoDB table
"""
if filter_exp:
response = ddb_table.scan(FilterExpression=filter_exp)
else:
response = ddb_table.scan()
data = response['Items']
print(len(data))
while response.get('LastE... | bf8e78cb7a8cd9015eb35ceb6c73da262c5c6877 | 621,368 |
from typing import List
def update_current_measure_durations(
current_measure_durations: List[float], next_duration: float
) -> List[float]:
"""
Update a list of notes durations from a measure in progress.
:param current_measure_durations:
durations of notes (in fractions of whole measure... | 10ab1004c08e8e3c00569fb931fcfe6c79676d45 | 621,372 |
def scale(v: float, a: float, b: float, c: float, d: float) -> float:
"""Scale a value, v on a line with anchor points a,b to new anchors c,d."""
v01 = (v - a) / (b - a)
return c - v01 * (c - d) | c6aa756d683ca92bd7be9386422bcb28cff38da3 | 621,373 |
def extract_subset_from_monolithic_flags_as_dict_from_stream(
monolithic_trie, stream):
"""Extract a subset of flags from the trie of monolithic flags.
:param monolithic_trie: the trie containing all the monolithic flags.
:param stream: a stream containing a list of signature patterns that define
... | 492cfd0f2cce515258c439612c24f6d0b8ff6c1c | 621,376 |
def get_pids(search):
"""Get a list of pids of the search results."""
pids = []
for hit in search().scan():
pids.append(hit["pid"])
return pids | 280ab7996bc1daf8230762dd40a28a10153b31c7 | 621,377 |
import logging
def _setup_logger() -> logging.Logger:
"""Set up the logger."""
FORMAT = "[%(asctime)s][%(levelname)s] %(message)s"
logging.basicConfig(format=FORMAT)
logger_ = logging.getLogger("generate_all_protocols")
logger_.setLevel(logging.INFO)
return logger_ | e4e1d91d32a5f46f9a8f781ebe39f88ecb3bf025 | 621,378 |
def parse_enum_constant(enum_constant_or_name, enum_type):
"""
Return the enumerated constant corresponding to 'enum_constant_or_name', which
can be either this constant or a its name (string).
"""
if isinstance(enum_constant_or_name, enum_type):
return enum_constant_or_name
else:
... | ebbfa93ec0ff770cbeae8b0144c9b1db37fd7b19 | 621,381 |
def top_player_ids(info, statistics, formula, numplayers):
"""
Inputs:
info - Baseball data information dictionary
statistics - List of batting statistics dictionaries
formula - function that takes an info dictionary and a
batting statistics dictionary as input and
... | d0324c32a511a550cf4dcdcf545291e509fa8bff | 621,383 |
import ipaddress
def get_ip_list(ip_network, mask=None):
"""
Quickly convert an IPv4 or IPv6 network (CIDR or Subnet) to a list
of individual IPs in their string representation.
:param str ip_network:
:param int mask:
:return: list
"""
if mask and '/' not in ip_network:
net = ipaddress.ip_network("{0}/{1}"... | 7aa1e14d3cf6aa4fc861eb8a5f830e245a8f23c1 | 621,386 |
def _hashString (text):
"""
Compute hash for a string, returns an unsigned 64 bit number.
"""
value = 0x35af7b2c97a78b9e
step = 0x072f2b592a4c57f9
for ch in text:
value = ((value * 104297) + (step * ord (ch))) & 0xFFFFFFFFFFFFFFFF
return value | 4442cb0ee40580fe87511b5049f92268c09fa0f4 | 621,387 |
def exists(field):
"""Only return docs which have a value for ``field``"""
return {"exists": {"field": field}} | df3bb6f5c18af043a4052242847de049be12beab | 621,388 |
from typing import AnyStr
from typing import Union
from typing import Sequence
def separate(text: AnyStr, sep: Union[str, Sequence[str]] = ('!', '?', '.'), between_char=False) -> str:
"""
Creating a space between an element in sep values
e.g:
>>> separate('how are you?', sep='?')
'how are you ?'
... | e4bc3f299bc5f5a4a2ddea82789bc4d73623321a | 621,392 |
import uuid
def create_id() -> str:
"""
Create a unique id using uuid4
:return: str of the id
"""
id_unique = uuid.uuid4()
return str(id_unique) | bc660a0849585c024b30c1e8c683867ee221545a | 621,393 |
def value_or_from_dict(obj, key, default=None):
"""
Many Polygraphy APIs can accept a `Union[obj, Dict[str, obj]]` to allow
for specifying either a global value, or a per-key (e.g. input, output, etc.) value.
When a dictionary is provided, the `""` key indiciates a default value to use for keys
not... | 281067e9fb4f42203d1f9e77b88f945897b5eff5 | 621,394 |
def all_tree_names(pathnames):
"""Returns the set of all names, including intermediate names,
given a list of pathnames. For example, given the pathname 'a.b.c',
it would return set(['a', 'a.b', 'a.b.c'])
"""
allnames = set()
for key in pathnames:
parts = key.split('.')
allnames.... | 07ab52e6568b88726f26be30230f0a185ce64a0f | 621,396 |
def datetime_to_iso(date):
"""Convert a datetime object to a iso date string"""
return date.isoformat().replace('+00:00', 'Z') | cc1e167ffee2fa1b2902e3ab89e8d8c838067897 | 621,399 |
def sanitize_cr(clientrep):
""" Removes probably sensitive details from a client representation
:param clientrep: the clientrep dict to be sanitized
:return: sanitized clientrep dict
"""
result = clientrep.copy()
if 'secret' in result:
result['secret'] = 'no_log'
if 'attributes' in r... | 1020faf7dabce2aa33d43002d80c89a0853699c1 | 621,400 |
def readXRSL(filepath):
"""Return contents of given file."""
with open(filepath, 'r') as xrsl:
return xrsl.read() | c5449e466ba31da83382296979e54fae3954f32d | 621,401 |
def is_same_sensor(sicd1, sicd2):
"""
Are the two SICD structures from the same sensor?
Parameters
----------
sicd1 : sarpy.io.complex.sicd_elements.SICD.SICDType
sicd2 : sarpy.io.complex.sicd_elements.SICD.SICDType
Returns
-------
bool
"""
if sicd1 is sicd2:
retur... | f4f6c60212acc8aebcd4c6b9c327106f26c9aae3 | 621,402 |
from datetime import datetime
def _convert_tstamp(val):
"""
Safe convert string timestamp into a ``datetime`` object. Returns None if
it can't be converted.
"""
if val:
return datetime.fromtimestamp(float(val) / 1000) | ae97f78aeab952eae1835110f57def3d2565b211 | 621,404 |
def _RecoverGaps(text, starts, ends):
"""Recovers gaps from the segmenter-produced start and end indices.
The segmenter may produce gaps around spaces, e.g. segment("hello world") => "hello|world"
"""
out_starts = []
out_ends = []
prev_end = 0
for start, end in zip(starts, ends):
if start != prev_end:
out_... | 4b199c70b72d9bea9d37753d21a29f38ab90197b | 621,407 |
def infer_n_hypers(kernel):
"""Infer number of MCMC chains that should be used based on size of kernel"""
n_hypers = 3 * len(kernel)
if n_hypers % 2 == 1:
n_hypers += 1
return n_hypers | ae0e4a3cafbd8c052843585be8ea5c8209a3ee31 | 621,409 |
def permute_bond(bond, cycle):
"""
Permutes a bond indice if the bond indice is affected by the permutation cycle.
Parameters
----------
bond : list
A list of length 2, a subscript of an interatom distance
cycle : list
A cycle-notation permutation operation.
Returns
---... | cff616d9ca3b5bb631b80443286556c34258e700 | 621,411 |
def iob2(tags):
"""
Check that tags have a valid BIO format.
Tags in BIO1 format are converted to BIO2.
"""
for i, tag in enumerate(tags):
if tag == 'O':
continue
split = tag.split('-')
if len(split) != 2 or split[0] not in ['I', 'B']:
return False
... | 3f67beb4cb071be9b923756eb237336b450bcd84 | 621,415 |
def is_subseq(needle_seq, haystack_seq):
"""Determine if haystack_seq contains all items in needle_seq, in
the same order."""
# source: https://stackoverflow.com/questions/24017363/how-to-test-if-one-string-is-a-subsequence-of-another # NOQA
haystack_iter = iter(haystack_seq)
return all(item in hay... | 848203967c3a80875aff22db1acc576b36c8bac7 | 621,417 |
import random
def sampleIndexWithinRegionOfLength(length, lengthOfThingToEmbed):
"""Uniformly at random samples integers from 0 to
``length``-``lengthOfThingToEmbedIn``.
Arguments:
length: length of full region that could be embedded in
lengthOfThingToEmbed: length of thing being embedde... | ec12475abee40f9a53e891b5d0b0219a133fd86c | 621,419 |
def oauth2_client_id() -> str:
"""The Oauth client id obtained from the BingAds developer center"""
return 'abc1234-1234-1234-abc-abcd1234' | 18bb6f29d099e3ce0c8916fc1d7465914ebe5c39 | 621,424 |
import math
def date_label(i):
"""
Helper funtion, label 67 quarters, from 2000q1 to 2016q3.
Takes current iteration and returns quarter label.
"""
dlab = '{0}q{1}'
# count years
yr = 2000 + math.floor(i/4)
# count quarters
qt = i % 4+1
return(dlab.format(yr, qt)) | 79206c11628ad22adca0fee85cda4885711901cb | 621,425 |
from datetime import datetime
def set_created_at(v):
"""
Set created_at field to current datetime
"""
return datetime.utcnow() | ea16af0337c0fb55eef724dcd32c29160ec42e84 | 621,427 |
def spring_torsion_torque_t31(hatch, tors_bar):
"""
Determine the torque due to the laminated torsion bar
The ICD for this part also calls for stress limit check
"""
torque_bar = - tors_bar.tors_stiff * (tors_bar.windup_angle - hatch.angle_range)
max_stress = ((tors_bar.lam_thick * tors_bar.sh... | c286ec6973694910f78ec32d56efd4bd38752cbd | 621,429 |
def client(app):
"""A test client for the app. You can think of the test like a web browser;
it retrieves data from the website in a similar way that a browser would.
"""
return app.test_client() | 1063cbdc7859bc7184294637a98737bbd2f1795f | 621,430 |
def q_i(c1, **params):
"""
Implements Eq. 9.67 from Nawalka, Beliaeva, Soto (pg. 435)
Need params: k
"""
return 1 - params['k'] * c1 | 9fab5aa4883a48115321196b32b4fabad3e96ac0 | 621,431 |
def load_dic(path):
"""
The format of word dictionary : each line is a word.
Args:
Input path
Returns:
load dict {k, v} = {term, id}
"""
dic = {}
with open(path) as f:
for id, line in enumerate(f):
w = line.strip()
dic[w] = id
return dic | 6694415ec0a7a6906da6d2a2797c7bb335ec7950 | 621,432 |
def make_base_metainfo() -> dict:
"""Return generic metainfo.
"""
return {
'uuid': '',
'path_to_content': '',
'path_to_preview': '',
'path_to_thumbnail': '',
'original_filename': '',
'original_name': '',
'original_extension': '',
'series': '... | e8bbc047a7c5c18b480c0bcb6f36ff6b77083bac | 621,439 |
def my_momentum(M, v):
""" Calculate total momentum.
Args:
mass (float): particle mass
vel (np.array): particle velocities, shape (natom, ndim)
Return:
float: total momentum
"""
return sum(M*v) | 924de69e83f93d74cb5d65b62b042ba98b449a9f | 621,440 |
def kaimal(f, sigma2, **kwargs):
""" one-side Kaimal spectra, adopted in Amercian code ASCE7
Args:
f (1d-ndarray): freqency, unit: Hz
sigma2 (float): variance, (Iu * vz) ** 2
**kwargs: spectrum propeteries
z (float): height, unit:m
vz (float): mean wind speed at z heigh... | 9ebbbed5f2d59047da142ca0b5f082bd460b74c9 | 621,442 |
def sec_dev(f, x, h=1e-6):
"""
Calculates the second derivative of a function at a given x, given a small h
"""
return (f(x - h) - 2 * f(x) + f(x + h)) / float(h**2) | be4008eb135e7b8fd127435299f42b8dfde1bc95 | 621,444 |
def coord_linha(c):
"""
coord_linha: coordenada --> inteiro positivo
coord_linha(c) tem como valor a linha da coordenada.
"""
return c[0] | 0b79316560a39322528e4091aad255db9f4c39a6 | 621,445 |
def anonymize_ip(real_ip: str) -> str:
"""
Sets the last byte of the IP address `real_ip`.
.. note::
It is a good step but it may be possible to find out the physical address
with some efforts.
Example:
If the input is "595.42.122.983", the output is "595.42.122.0".
Raises... | f4ca8a072f295f6b06ac14712b84fe765a57d823 | 621,447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.