content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _etag_write_match(incoming_etag, server_etag):
"""
Compare two tiddler etags for a satisfactory match
for a PUT or DELETE. This means comparing without the
content type that _may_ be on the end.
"""
incoming_etag = incoming_etag.split(':', 1)[0].strip('"')
server_etag = server_etag.split... | 1ce4df6d1165a815a1ed3820e6ee5f8d238c09e3 | 627,290 |
import json
import sys
def _read_config(path):
"""Reads the assembled config"""
if path.exists():
f = open(path, "r")
config = json.load(f)
f.close()
return config
else:
print(f"No Config file found at: {path}")
sys.exit(1) | 98b4d6db63b40f6ab3de999806043f2d243b7a78 | 627,291 |
def relpath(repo_path):
"""Return a relative path to the given path within the repo.
The path is relative to the infra/bots dir, where the compile.isolate file
lives.
"""
repo_path = '../../' + repo_path
repo_path = repo_path.replace('../../infra/', '../')
repo_path = repo_path.replace('../bots/', '')
... | a21078411c332402c0a3e85847236ec0adedf138 | 627,292 |
def _pipeline_parallel_partition(function, pp_degree, devices):
"""Partitions the function into pipeline parallel stages.
We assume the following structure for the function:
MM_F1 -> R_F1 -> ... -> MM_FN -> R_FN -> L-> L_B -> R_BN -> MM_BN -> ... -> R_B1 -> MM_B1
(MM: MatMul, R: ReLU, L: Loss)
Th... | 7caf56725a8eb18d7b5898183780ae832841a6ec | 627,293 |
import os
def relative_path(src, destination):
"""Given a source and destination path, find the relative path"""
return os.path.relpath(destination, src) | 9030294f27424d8f2efd77c178eecfee34f8bf68 | 627,294 |
import base64
def encode_to_base64(filename):
"""
encoding file to base64 encoded stream text
:param filename:
:return:
"""
imgstr = ""
with open(filename, 'rb') as file:
imgstr = base64.b64encode(file.read())
return imgstr | 5d5ac827b3c02d7920e4f05a27247a639f82b867 | 627,295 |
def snake_to_header(string: str) -> str:
"""Converts a snake case string to a table header by replacing underscores
with spaces and making uppercase.
Args:
string (str): The snake case string.
Returns:
str: The header.
"""
return string.replace('_', ' ').upper() | 1f23e86113952a0f99a48b13c9e71203a313a18f | 627,296 |
from typing import List
def _smooth(values: List[float], beta: float) -> List[float]:
""" Exponential smoothing of values """
avg_value = 0.0
smoothed = []
for i, value in enumerate(values):
avg_value = beta * avg_value + (1 - beta) * value
smoothed.append(avg_value / (1 - beta ** (i +... | abdaa54bcdd68c68d3804df03090bde854547df8 | 627,298 |
def parent():
"""Set standard metadata for synonyms."""
return [] | 7848df9de01928be70480b88f7a57ce4b7e6a30a | 627,299 |
def arr2dict(arr,keyname="key",valuename="value"):
"""
arr2dict - transform an array to dictionary key:
"""
res = {}
for item in arr:
res[item[keyname]]= item[valuename] if valuename in item else None
return res | 50f36ff022d8ad95e5b444ae4a6fa65c5964fe37 | 627,300 |
import os
import glob
def _get_optados_fname(seed):
""" Get the most likely OptaDOS input file name, which here means either
only existing one, or the shortest one.
Parameters:
seed (str): seedname for the calculation.
Returns:
str: the OptaDOS input filename.
"""
odi_fname ... | 036b9111d96a53ead00230fbce1f81b4ee7decdf | 627,301 |
def extract_task(spark):
"""Load data from parquet file format.
#param spark: Spark session object.
#return: Spark Dataframe.
"""
df = spark.read.csv('/user/itv000513/reddit_all/*redditor*', header=True)
return df | 9152e87d475ad0c1c9300cf4dd8109ee54a7c27c | 627,302 |
def string_to_boolean(string):
"""
Converts string representations of TRUE/FALSE to an boolean value.
:param str string: the string to convert.
:return: _result
:rtype: bool
"""
_result = False
_string = str(string)
if(_string.lower() == 'true' or _string.lower() == 'yes' or
... | 12d8287c23fbee08d12be08a20020878260589fa | 627,303 |
def pieces(string):
"""returns a list containing all pieces of string, see example below"""
tag_pieces = []
for word in string.split():
cursor = 1
while True:
# this method produces pieces of 'TEXT' as 'T,TE,TEX,TEXT'
tag_pieces.append(str(word[:cursor]))
... | 89e62769be5c4d69760dc254d597e1b75aa5bdc2 | 627,304 |
def _verify_non_empty_string(value, field_name):
"""Ensures that a given proposed field value is a non-empty string.
Args:
value: proposed value for the field.
field_name: string name of the field, e.g. `project`.
Returns:
The given value, provided that it passed the checks.
Raises:
ValueError... | e102e94b2f02ff84a7eb0d295660fbb9c65986e5 | 627,305 |
import requests
def request_conceptnet(query, rels):
"""
:param query: a concept to request to ConceptNet
:param rels: relations to filter edges
:return: concepts to which the query is connected by rels
"""
nodes = []
url = 'http://api.conceptnet.io/c/ja/{}'.format(query)
obj = reque... | 06c2120a65856c482816c719fbe5752d6d3a165d | 627,306 |
import random
import string
def get_random_string(k: int = 1) -> str:
"""Returns a random string of length k.
Args:
k: Length of a string (default: 1).
Returns:
A random string.
"""
return ''.join([random.choice(string.ascii_letters) for _ in range(k)]) | c40b6ed689646e57a3bad291f218679dab77bf99 | 627,307 |
def leakyReLU(x):
"""
Leaky rectifier transfer function
if x > 0, return x ; else return 0.1 * x
"""
return x * (x > 0) + (.1 * x) * (x < 0) | e625a2d3dc09b9bea5b2407537a1866cfdcccaf4 | 627,308 |
import re
import os
def match_files(path, pattern):
"""
Match pattern str and return match files or dirs
:param path:
:param pattern:
:return:
>>> path = './'
>>> pattern = 'file_*\.py'
>>> match_files(path, pattern)
[]
>>> path = './'
>>> pattern = 'file_.*\.py'
>>> ... | dea1d3cca6e89a4c619e32c2f36b0a19073f5d96 | 627,309 |
from typing import Optional
import traceback
def format_exc(exc: Optional[int] = None) -> str:
"""Format a traceback."""
return traceback.format_exc(exc) | 3d3df2adaca14828f393a4cb0e6a5bfcbae158e8 | 627,310 |
def list_of_peak_parameters(peaks) :
"""Converts list of peak objects to the (old style) list of peak parameters.
"""
return [p.parameters() for p in peaks] | 988e05408d6d57122af7bfa9bba91f50e94b7cdf | 627,311 |
def parse_prot_cntct_line(prot_cntct_line):
"""Returns a dictionary containing the info from a line of a protein
contact report from MOE
Usage:
parse_prot_cntct_line(prot_cntct_line)
where pc_line is a string from a protein contact line from a MOE
protein contact report.
Returns a d... | b6d54ceb121a4b3f45234beb269d3f578f67d8e7 | 627,312 |
def label_list_to_int(label):
"""convert type of labels to integer"""
int_label = []
for e in label:
try:
inte = int(e)
except ValueError:
print('Label are not int numbers. A mapping will be used.')
break
int_label.append(inte)
if len(int_label... | 91c435cb6a9e1325906dfbf33329fe2a09bad757 | 627,313 |
def do_prepend(value, param='/'):
"""Prepend a string if the passed in string exists.
Example:
The template '{{ root|prepend('/')}}/path';
Called with root undefined renders:
/path
Called with root defined as 'root' renders:
/root/path
"""
if value:
return '%s%s' % (... | 7e88948fabc9f1ae08271b16cfbc18b85bac1745 | 627,314 |
def AddNoise(x, nvals=256):
"""
[0, 1] -> [0, nvals] -> add noise -> [0, 1]
"""
noise = x.new().resize_as_(x).uniform_()
x = x * (nvals - 1) + noise
x = x / nvals
return x | ad489cfda922f727f7ae80669aef4c7f6a8e80ce | 627,315 |
def parse_drspaths(paths):
"""Parse handover configuration."""
return [p.strip().split(',', 2) for p in paths.split('\n') if p.split()] | 1a224640863f68017a15bc633e30eda2795f9c49 | 627,317 |
def step_iterator(iterator, input_data=None):
"""Avanza un iterador un paso, enviándole un valor si es necesario.
El iterador *no* debe producir valores 'None' en ninguno de sus pasos.
Args:
iterator (iterator): Iterador a avanzar.
input_data (object): Valor a envíar al iterador.
Retur... | 3376c5db139836aad49e4e5e31801e5e2c6ffcfc | 627,318 |
def StressSign(SigmaxSd, SigmaySd):
""" """
stress = 'TENSION'
if SigmaxSd and SigmaySd != 0:
signX = SigmaxSd / abs(SigmaxSd)
signY = SigmaySd / abs(SigmaySd)
if signX == 1.0 and signY == 1.0:
stress = 'COMPRESSION'
else:
if SigmaxSd != 0:
sign... | 40d06b46315f9f593614529b0e6096ba374c3d15 | 627,320 |
def validateSyntax(func):
"""
Check if the function is valid.
Arguments: function
Warning: This function only checks if the function stays in the syntax limit. Further validation will be conducted later when an error is thrown.
"""
validSyntax = 'abcdefghijklmnopqrstuvwxz1234567890()+-*/^%!'
... | 8d9d5f9c3d346a4a6e03bc9e2903b70e5ad07cff | 627,321 |
def parse_mappings(mapping_list):
"""Parse a list of mapping strings into a dictionary.
Adapted from neutron_lib.utils.helpers.parse_mappings.
:param mapping_list: A list of strings of the form '<key>:<value>'.
:returns: A dict mapping keys to values or to list of values.
:raises ValueError: Upon ... | 04f5ca0d5f71712678700507973de92e728bde29 | 627,322 |
from typing import Any
def ensure_one(**kwargs: Any) -> tuple[str, Any]:
"""Ensures that only one argument is set."""
if sum(value is not None for value in kwargs.values()) != 1:
raise ValueError('Must specify exactly one of:', kwargs.keys())
for key, value in kwargs.items():
if value is... | d8cd369f9a474867e43f9618f8b91b8cdf2fafd5 | 627,323 |
def get_datatypes():
"""
Get pandas DataFrame datatypes.
:return: tuple(dict, dict)
"""
claims_dtypes = {
"policy_id": int,
"incident_severity": int,
"num_vehicles_involved": int,
"num_injuries": int,
"num_witnesses": int,
"police_report_available": i... | f258b230e0790e46b88facd7366c62b854056ec2 | 627,325 |
def flatten(sequence, types=(list, tuple)):
"""Flatten sequence made of types, returned as the same outer type as sequence.
REF: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
"""
sequence_type = type(sequence)
sequence = list(sequence)
i = 0
while i < len(sequence):
... | 9555e8611479bc2ac0ff94e2e9c97b45ed67f64d | 627,326 |
def calculate_distance(pos1: tuple, pos2: tuple) -> int:
"""
Taxicab/Manhattan distance
"""
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) | d7d0aaaf6f04820a34f8ac9fba0f8b906c1f2a5a | 627,328 |
def get_a_navi_navinext(cls, last_soup, next_):
"""Implementation of get_navi_link."""
# ComicPress (WordPress plugin)
return last_soup.find("a", class_="navi navi-next" if next_ else "navi navi-prev") | 8fefeb6fa9e701128730a48fd656000029cc74d5 | 627,329 |
import inspect
def extra_kwargs(s3):
"""Fixture to determine extra kwargs for devices"""
def _extra_kwargs(device_class, backend):
signature = inspect.signature(device_class).parameters
kwargs = {}
if "device_arn" in signature:
kwargs["device_arn"] = backend
else:
... | 2be03aa24a737faedfffbe07b8202dfbd20175a6 | 627,330 |
from typing import Any
from typing import Type
def field_type_is_of_class(
field_type: Any,
klass: Type[object],
):
"""
:param field_type: taken from attr.Attribute.type
:param klass: the class to check against
:return:
"""
try:
is_of_class = issubclass(field_type, klass)
... | 307434ae3d8bce58c38a9e72d15e8111092bf266 | 627,331 |
def EPE(input, target):
"""
Endpoint-error
:param input:
:param target:
:return:
"""
return (target - input).abs() | 747a32da669f5081f3b27d28e4b86f4dd73d5c14 | 627,332 |
def get_parameter_base_type_and_modifiers(omc, class_type, modifiers):
"""
Gets all pertinent information from super ('extends') classes
"""
# Assumption: Types can only inherit from one class (at a time)
base_type = class_type
# Extract inherited modifiers
for i in range(1, omc.getInherita... | da05d9a5a52c04b748c10961b397eae3a2233ab0 | 627,333 |
def extract_label_list(json_data, label_list):
"""Pull out label objects and add to list."""
labels = json_data.get("data").get("repository").get("labels")
cursor = labels.get("pageInfo").get("endCursor")
for label in labels.get("edges"):
label_list.append(label.get("node"))
return cursor, l... | 6f0087ac3bd2788fa2797c984d03b71f117354c8 | 627,334 |
def can_proceed(bound_method):
"""
Returns True if model in state allows to call bound_method
"""
if not hasattr(bound_method, '_django_fsm'):
raise NotImplementedError('%s method is not transition' % bound_method.im_func.__name__)
meta = bound_method._django_fsm
return meta.has_transi... | 6a2acbe94cf640e063c8e434b53938534d9f1bc7 | 627,335 |
import itertools
def get_contributions(site, username, num_contributions):
"""Get a list of talk-namespace contributions."""
result = []
gen = site.usercontributions(username, namespace=1)
for contrib in itertools.islice(gen, num_contributions):
result.append(contrib)
return result | 8fb9cafc5a8fcd166e18a60d395b27ffb6a2a18f | 627,336 |
import os
def clean_paths(row):
"""
Intended for use with DataFrame.apply()
Returns the basename of an 'oldfractal' element using basename() from os.path
"""
return os.path.basename(row['oldfractal']) | 4982196550fa7d7aff7d69b24e6d9fd1fd60abb1 | 627,339 |
def pick_bball_game(p):
"""
prob_game1 = p
prob_game2 = P(make 1+2) + P(make 1+3) + P(make 2+3) + P(make 1+2+3)
prob_game2 = p*p*(1-p) + p*(1-p)*p + (1-p)*p*p + p*p*p
prob_game2 = p**2 - p**3 + p**2 - p**3 + p**2 - p**3 + p**3
prob_game2 = 3 * p ** 2 - 2 * p ** 3
prob_game1 > prob_game2
... | 2c262477ba409636d5563048228b4418bbf41e8d | 627,340 |
def matching_files(directory, prefix=None, suffix=None, prepend=False):
"""Get a list of files that start with a specific prefix.
Args:
directory (pathlib.Path): The directory containing files.
prefix (str): A prefix to match filenames against.
suffix (str): A suffix (file extension) to ... | 3dfd056156337da428c01ff3612c84bb8f6ac8d5 | 627,341 |
import os
import sys
import subprocess
def get_setuppy_version(rootdir):
"""Get version from setup.py."""
setupfile = os.path.join(rootdir, "setup.py")
cmd = (sys.executable, setupfile, "--version")
release = subprocess.check_output(cmd).decode().rstrip(os.linesep)
version = release.rpartition("."... | 44d3dd52e659c6deccabec406777bf4f5cd784ca | 627,342 |
def rgb_to_brightness(r, g, b, grayscale=False):
"""
Calc a brightness factor according to rgb color
"""
if grayscale:
return 0.2126*r + 0.7152*g + 0.0722*b
else:
return 0.267*r + 0.642*g + 0.091*b | f37e7663e65f19d7f5c06247dde6ca5265ab276e | 627,343 |
import subprocess
def containers(include_stopped=False):
"""Get the container list"""
cmd = ['docker', 'ps', '--format', '{{.Names}}']
if include_stopped:
cmd += ['-a']
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subpro... | f6d8a501bf467a14d4f5d56528080208ce8687c4 | 627,344 |
def update_tekton_pipeline_task(cursor, info, task_id):
"""tekton_pipeline_task情報更新
Args:
cursor (mysql.connector.cursor): カーソル
info (Dict)): ワークスペース情報のJson形式
task_id (int): task_id
Returns:
int: アップデート件数
"""
# SQL生成
sqlstmt = ( 'UPDATE tekton_pipeli... | 23180d2a5be77125ae90e1c385f6fb44ef8ec8a0 | 627,345 |
def get_indices(dataset, class_name):
"""Return indices of class_name in dataset."""
indices = []
for i in range(len(dataset.targets)):
if dataset.targets[i] == class_name:
indices.append(i)
return indices | 5cbe22ddfc61a67e0c754576b34b3dff3d1c6b05 | 627,346 |
def filter_article(event):
"""
Optionally filters original article text from response.
Expects "original_text" and optional "filter_article"
fields in event.
"""
if event.get("filter_article", True):
del event["original_text"]
return event | fe1bc8f0ab51787fa169654fef617dd32a899fcb | 627,347 |
def decode(text):
"""
Декодирование текста полученного с фискального регистратора.
"""
return text.decode('cp1251') | 982fd8e5c5b08cc8b4405a5036e86936d89cf369 | 627,348 |
from typing import List
def create_questionnaire_response_item(question_id: str,
answers: List[dict]) -> dict:
"""
Create a questionnaire response answer item following the FHIR format
(https://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResp... | 4ef5d0647fc57d1310127cb980383ae4d07394b1 | 627,349 |
import os
def make_absolute(relative_path):
"""
Returns an absolute path from the root of the project directory based on the input relative
path
:param: relative_path The relative path to convert to an absolute path
:return: str The relative path as an absolute path
"""
... | 4e96146d519a675422fdfbd47a414423668bd809 | 627,350 |
def __carta(soup):
"""
Gets the most read news from the Carta Capital page
:param soup: the BeautifulSoup object
:return: a list with the most read news from the Carta Capital Page
"""
news = []
container = soup.find('dd', id='fieldset-maisacessadas-semana')
most_read = container.find_a... | 867de5b58333cea3e84c811920b89135f1659f59 | 627,351 |
def analysis_get_wavelength(analysis):
"""Gets the wavelength value of a specific analysis.
Parameters
----------
analysis: Any
An OpticStudio Analysis.
Returns
-------
int | str
Either the wavelength number, or 'All' if wavelength was set to 'All'.
"""
wl = analys... | 440a56c23444f75b737a64de4e90687277d2106f | 627,352 |
import argparse
def options():
"""Parse command line options.
Args:
Returns:
argparse object.
"""
parser = argparse.ArgumentParser(description="Calculates pairwise distances between persistence diagrams.")
parser.add_argument("-d", "--dir", help="Directory containing persistance dia... | d15c86efbc5d878bd53ba8477dbe4edeb85e1b77 | 627,353 |
import zipfile
def zip_folder(folder, files):
"""
Create a zip file of todays backupfolder.
:param dumped: list of dumped databases
"""
try:
zip_file = zipfile.ZipFile("{}.zip".format(folder), "w")
for src_file in files:
zip_file.write(
"{}/{}.sql".forma... | f3c85cd9e3509b33e211939654939df06dd993dd | 627,354 |
def auto_primitive_axes(primitive_matrix):
"""Check whether automatic primitive matrix setting or not."""
return type(primitive_matrix) is str and primitive_matrix == "auto" | de603c02c3c060398324d87c05fae0ea74c551fc | 627,355 |
import argparse
import os
def get_args():
"""Init argparser and return the args from cli."""
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--config",
help="the config file",
type=str,
default=os.getcwd() + os.sep + "judge.conf",
)
parser.add... | f5932f7d66ead65a7b3648e9f5631f6e098099c9 | 627,356 |
def clean_db(new_db):
"""A clean database"""
new_db.collection.delete_many({})
return new_db | 1745e4363970548d528e3ee0efa8a07f037ad1b6 | 627,358 |
def hardware_props(hardware):
"""Props which should be added to the device running the hardware."""
return hardware["props"] | 3475cbc0565a521fbce14deec2acc02b2e712cb3 | 627,359 |
def Choose(Decision,TrueChoice,FalseChoice):
"""
Ternary IIF operator, returns TrueChoice or FalseChoice based on
Decision.
This function is handy for use inside Curly Brace Expressions (CBE's).
Decision must evaluate to true or false (0 or 1, empty or full, etc).
If TRUE then TrueChoice wi... | 587ef86f024339a60e0dcfa0c66415aedbde8cab | 627,360 |
def quote(self):
""" I cannot believe I'm hacking this to overcome an API 'requirement' """
return '\"' + self + '\"' | 217dddf9646439a64b29fb177dac2258944f08f3 | 627,361 |
from typing import Collection
def listify(thing):
"""Always a list, for things that want lists"""
if isinstance(thing, Collection):
if not isinstance(thing, str):
return list(thing)
return [thing] | 2b7b69e8c8fcfc2fddd1001540f83924f798d7bc | 627,362 |
from typing import List
def date_from_path(path: str) -> List[str]:
"""
Takes a path like bla/number1/number2 and returns [number1, number2]
"""
parts = [p for p in path.split('/') if p.isnumeric()]
return parts | f89f2925b8eab778710731faa32718d4124f61d4 | 627,363 |
def loqus_exe_variant():
"""Returns a Loqus executable instance variant"""
variant_found = (
b'{"homozygote": 0, "hemizygote": 0, "observations": 1, "chrom": "1", "start": '
b'235918688, "end": 235918693, "ref": "CAAAAG", "alt": "C", "families": ["643594"],'
b' "total": 3}'
)
ret... | ce869626d75c2d7988e47c9dde0b201fb37cbc5a | 627,364 |
from typing import List
from typing import Dict
from typing import Any
def targets_to(targets: List[Dict[str, Any]], device):
"""Moves the target dicts to the given device."""
excluded_keys = [
"questionId",
"tokens_positive",
"tokens",
"dataset_name",
"sentence_id",
... | a5a1e258378aac8b63e362497b9d4bb415c31b0f | 627,365 |
def regroupRDDs(rdd, numGroup=10):
""" regroup an rdd using a new key added that is 0-numGtoup-1
:param rdd: input rdd as a (k,v) pairs
:param numGroup: number of groups to concatenate to
:return: a new rdd in the form of (groupNum, list of (k, v) in that group) pairs
"""
rdd = rdd.map(lambda k... | 6f9692b2374adf881ca81b993856f4f33ddc16b5 | 627,367 |
import re
def humanize_url(api_url):
"""Make an API endpoint to an Human endpoint."""
match = re.match('https://api.github.com/repos/(.*)/(.*)/issues/([0-9]*)', api_url)
if match is None:
raise RuntimeError('Format of API URLs has changed: ', api_url)
user, repo, issue_num = match.group(1), m... | 63aeefc11d724c1fa9223fa4128a810742345cc3 | 627,368 |
def db_to_linear_gain(db_value):
"""
Parameters
----------
db_value : float
Decibel value
Examples
--------
>>> db_to_linear_gain(db_value=-3)
0.5011872336272722
>>> db_to_linear_gain(db_value=10)
10.0
"""
return 10 ** (db_value / 10) | aca4931b53d496b573d540b1d95b394f6d9929c9 | 627,369 |
import hashlib
def buildOtrFingerprintHostname(jid):
"""
Build the hostname where the OTR fingerprint should be stored in a
text record if it has been published. Don't forget, it's always
possible that the name will not exist.
"""
parts = jid.split('@')
hostname = hashlib.sha224(parts[0])... | 34c250e129f403eb4fdc3f48effb96f27de9e0db | 627,370 |
def parse_get_params(request):
"""
parse all url get params that contains dots in a representation of
serializer field names, for example: d.docs.limit to d_docs_limit.
that makes compatible an actual API client with django-rest-framework
serializers.
:param request:
:return: QueryDict with ... | 56183fb931c84cc43ef1c5892793ac1a8ab82955 | 627,371 |
def metadatize(ds):
""" Move all non-axis dims to metadata """
scan_dims = [dim for dim in ds.dims if dim not in ["kthetarhos", "nions", "numsols"]]
metadata = {}
for name in ds.coords:
if all([dim not in scan_dims for dim in ds[name].dims]) and name not in [
"kthetarhos",
... | aff9fbe573b110bccf66fb1cf6e473cfcfd20e86 | 627,372 |
from collections import namedtuple
import inspect
def help_signature(f):
"""function help_signature
Args:
f:
Returns:
"""
sig = inspect.signature(f)
args = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
... | 2d9228da0fd8d443145666c6b175336af08c536d | 627,373 |
from typing import List
def calculate_diff_occurrence(joltages: List[int]) -> int:
"""Calculate diff occurrences for differences of 1 and 3.
Args:
joltages (List[int]): the joltages of the adapters on hand
Returns:
int: the product of numbers of diff of 1 and diff of 3
"""
lowes... | f331fce8319d5cc367fb2e75c282955d93364fb5 | 627,375 |
def update_output_frame_video_rate_metric(ml_output_names):
"""Update the metrics of the "Output Video Frame Rate (avg)" dashboard dashboard widget"""
result = []
for output in ml_output_names:
if output["Pipeline"] == "0":
entry = ["MediaLive", "OutputVideoFrameRate", "ChannelId", outpu... | 4f97ec95567d96becf32cc76ee0c9efb9af50051 | 627,376 |
def good_func():
"""
>>> good_func()
True
"""
return True | de88aece2b5abde58938da2fb6d2e05353832762 | 627,377 |
def is_supermodel__types(t0, t1):
"""Given two string representations of models, returns True iff t0 is a
submodel of t1"""
return len(t0) == len(t1) and all(
int(b) or not (int(a)) for a, b in zip(t0, t1)
) | 0bd7f7685f6aa8680fe487bead83f4daf03b68b6 | 627,378 |
def build_features(x, y, sentence, features_functions, i_shift=0):
"""applies predefined functions on one sample
returns shifted (corrected) data,i,j
i_shift is the row number, calling function is responsible setting it
"""
data, i, j = [], [], []
for ind, f in enumerate(features_functions):
... | 9ed7ca20261c18e8a99c1f0cb20f560814d1fb49 | 627,379 |
def _reverse_second_list_dimension(layers):
"""Reverses each list within a list of lists, but not the outer list."""
return [layer[::-1] for layer in layers] | 3612f8269bef4168cf10e7f9f0036780c3c1bfc1 | 627,381 |
def crosses(split1, split2):
"""
Check whether the splits intersect.
"""
intersect = False
#print(split1, split2)
#if bool(set(split1).intersection(split2)):
if not (set(split1).isdisjoint(split2) or set(split1).issubset(split2) or set(split2).issubset(split1)):
intersect = True... | 03342cd4c63b1fa410f5ae58526d92f3af12448d | 627,382 |
def csort(objs, key):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) | c19819a9c5f8fe1f3855cae554f6ae4912b27982 | 627,383 |
def std_array(comment, valueType, ndim, **kwargs):
"""Description for standard array column with variable shape (used for smaller arrays)."""
return dict(comment=comment, valueType=valueType, ndim=ndim, dataManagerType='StandardStMan',
dataManagerGroup='StandardStMan', _c_order=True, option=0, m... | e7d5c2fd68b0de81d75739ee541a29034fe44103 | 627,384 |
def comment_general(ci_data):
"""Comment string for non-staticman comment
"""
return f"""
The new [PFHub live website]({ci_data.surge_domain}) is ready for review.
""" | c0b8f56c1602c00770d3be4ba80258b9307d0642 | 627,385 |
def test_set_literal():
"""
>>> type(test_set_literal()) is set
True
>>> sorted(test_set_literal())
['a', 'b', 1]
"""
s1 = {1, 'a', 1, 'b', 'a'}
return s1 | 92c4f5dc8a051c11c666ad909f9db825d9825770 | 627,386 |
from pathlib import Path
def get_measurement_folders(lake):
"""Get a sorted ist of measurement folders
Filename pattern: results_<id>_unpack.zip
"""
path = Path(lake)
pathlist = sorted(
Path(lake).glob("*_unpack"),
key=lambda _: int(_.name.split("_")[1].split(".")[0]),
)
pa... | d1b2b009cf220f2c140bf3285a94971df2dea270 | 627,387 |
def split_GL_string(GL_string):
"""splits GL-string into alleles;
if it becomes too complicated, reduce to POS
"""
if "|" in GL_string: # pretyping contains phasing
return [GL_string] # put everything into first field
else:
alleles = GL_string.split("+")
if len(alleles) > 4: ... | fe2fae3bc605781b178975fe6a0a578ebfd0bc13 | 627,388 |
def get_source_files(source_ID, sofia_dir_path, name_base):
"""Return the full path of the files for a given source generated by
SoFiA. The source ID is equivalent to the ID in the catalog generated
by SoFiA.
This code is minimalistic, and works on a 'standard' output of SoFiA
see the code for the ... | a5cfc92941e96b33b5d75eb38284f3b946eaffa4 | 627,389 |
import sys
import linecache
import traceback
def formatTraceback(ex_type=None, ex_value=None, ex_tb=None, detailed=False):
"""Formats an exception traceback. If you ask for detailed formatting,
the result will contain info on the variables in each stack frame.
You don't have to provide the exception info ... | 21c33d975ed8f180a5c3905e639ced11e6230638 | 627,390 |
def rglen(ar):
"""shortcut for the iterator ``xrange(len(ar))``"""
return range(len(ar)) | 6bd7ab6a7d2d961eeb71f8a303f19de720f21677 | 627,391 |
def format_function_scipy(function):
"""
Formats the function string such that it is scipy-ready.
:param function: The function to be formatted
:type function: str
:return: The formatted function
:rtype: str
"""
function = function.replace("exp", "np.exp")
function = function.repl... | a798b5cc5f0603513b0cf126dee61e3621b6d090 | 627,392 |
def are_closest_line(index_line_1, index_line_2, index_lines, distance_segment):
"""
Returns True if there is no segments between line_1 and line_2, will return False if this is not the case
:param index_line_1:
:param index_line_2:
:param index_lines:
:param distance_segment:
:return: boole... | e987ae80f957899df0bfb67dfcc7c452db1811aa | 627,393 |
def best_oligo(tms, start, end, min_tm, max_tm, min_len, max_len, max_untiled_len, return_imperfect = False, right_end_check = False):
"""
Find the longest oligo in the window that begins between start and start+max_untiled_len+1.
If return_imperfect, the oligo with nearest Tm to acceptable is returned if no accepta... | 3a5dc80b38bf456bc9e4af6529a9c7807f66bd7c | 627,394 |
def jinja2_linktarget(env, target):
"""Makes sure that target is a proper link target."""
parts = target.split("#")
if parts[0] and not parts[0].endswith(".html"):
parts[0] += ".html"
return "#".join(parts) | 01324c2553838c9209296a40b1b6228a2cbb5e4b | 627,395 |
from operator import mod
def is_arithmetic_persian_leap_year(p_year):
"""Return True if p_year is a leap year on the Persian calendar."""
y = (p_year - 474) if (0 < p_year) else (p_year - 473)
year = mod(y, 2820) + 474
return mod((year + 38) * 31, 128) < 31 | 33da473ca27dd523c5cb16cb3f4dd073daa84e53 | 627,396 |
def developer(id, name, email, url = None):
""" Generates an id/string pair which can be consumed by maven_pom"""
if not url:
url = "http://github.com/{id}".format(id = id)
return "{id}::{name}::{email}::{url}".format(id = id, name = name, email = email, url = url) | c36496f07c11fc211f1fe1e600fb4c043061491c | 627,397 |
import requests
import calendar
import time
def coindeskticker(currency='USD'):
""" get current bitcoin exchange rate from Coindesk """
data = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json').json()
dataprice = data['bpi'][currency]['rate']
datatime = calendar.timegm(time.strptime(dat... | 8dba84be187060d6d7792be34656483bee434f4d | 627,398 |
def combinations_nb(n):
"""Return number of (i, j) combinations with 0 <= i < j < n"""
return (n * (n-1)) // 2 | 4bc3821f0696c4a7799209aa7f11e67ef45cadfa | 627,399 |
def read128(f):
"""Read the next few bytes from file f as LEB128/7bit encoding and return an integer."""
result,i = 0,0
while 1:
byte=ord(f.read(1))
result|=(byte&127)<<i
if byte>>7==0: return result
i+=7 | 02dde05996e25f02600c92f989e2309a1cb321cb | 627,400 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.